hexsha stringlengths 40 40 | size int64 19 11.4M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 270 | max_stars_repo_name stringlengths 5 110 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 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 3 270 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 270 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 19 11.4M | avg_line_length float64 1.93 229k | max_line_length int64 12 688k | alphanum_fraction float64 0.07 0.99 | matches listlengths 1 10 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
63dd0966ccc96260586e6efb39ecbb81ce9d4486 | 1,011 | cpp | C++ | gSpiderMac/gSpiderMac/cssstyleWrap.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | 87 | 2015-08-05T12:49:16.000Z | 2021-09-23T03:24:40.000Z | gSpiderMac/gSpiderMac/cssstyleWrap.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | null | null | null | gSpiderMac/gSpiderMac/cssstyleWrap.cpp | reichtiger/grampusSpider | d8ba6b96a7af085c7c2420a5bcb1fa35ee8b03b7 | [
"Apache-2.0"
] | 52 | 2015-09-24T05:19:29.000Z | 2020-10-14T07:14:22.000Z | //
// cssstyleWrap.cpp
// gSpiderMac
//
// Created by reich on 14/12/19.
// Copyright (c) 2014年 zhaohu. All rights reserved.
//
#include "cssstyleWrap.h"
namespace gSpider {
Handle<Object> cssstyle_Wrap(Isolate* isolate, cssstyle* pStyle)
{
EscapableHandleScope handle_scope(isolate);
Local<ObjectTemplate> templ = ObjectTemplate::New();
templ->SetInternalFieldCount(1);
// set accessores
templ->SetAccessor(String::NewFromUtf8(isolate, "color"), cssstyle_color, cssstyle_color_setter);
Local<Object> result = templ->NewInstance();
result->SetInternalField(0, External::New(isolate, pStyle));
return handle_scope.Escape(result);
}
void cssstyle_color(Local<String> name, const PropertyCallbackInfo<v8::Value>& info)
{
}
void cssstyle_color_setter(Local<String> name, Local<Value> value_obj, const PropertyCallbackInfo<void>& info)
{
}
} | 26.605263 | 114 | 0.637982 | [
"object"
] |
63e3f354a6e4f076fdd6005e33497643f05f96d1 | 5,811 | cc | C++ | src/fzyestim.cc | ManfredMaennle/fzymodel | fa4a07ce06b0e410f1032f45c8555f1edd4c5220 | [
"MIT"
] | null | null | null | src/fzyestim.cc | ManfredMaennle/fzymodel | fa4a07ce06b0e410f1032f45c8555f1edd4c5220 | [
"MIT"
] | null | null | null | src/fzyestim.cc | ManfredMaennle/fzymodel | fa4a07ce06b0e410f1032f45c8555f1edd4c5220 | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 1999, 2020 Manfred Maennle
*
* 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.
*
* $Id: fzyestim.cc,v 2.9 2020-08-29 10:47:37+00:00:02 manfred Exp $
*/
#include <time.h>
#include "global.hh"
#include "fmodel.hh"
#include "data.hh"
#include "fzyestim.hh"
void fzyestim(char* fzyfilename, char* datafilename) throw (Error) {
// load fuzzy model
FModel fmodel;
fmodel.load(fzyfilename);
if ( (GLOBAL::verbose > 1) && (! GLOBAL::quiet)) {
cout << "loaded model:\n\n" << fmodel << endl;
}
if (fmodel.rdim() < 1) {
string msg = "invalid fmodel (rdim < 1) loaded from file";
throw(Error(msg));
}
if (fmodel.cdim() < 1) {
string msg = "invalid fmodel (cdim < 1) loaded from file";
throw(Error(msg));
}
if (fmodel.udim() < 1) {
string msg = "invalid fmodel (udim < 1) loaded from file";
throw(Error(msg));
}
if (fmodel.cdim() > fmodel.udim() + 1) {
string msg = "invalid fmodel (cdim > udim+1) loaded from file";
throw(Error(msg));
}
if (fmodel.sdim() != 2 * (fmodel.rdim() - 1)) {
string msg = "invalid fmodel (sdim != 2(rdim-1)) loaded from file";
throw(Error(msg));
}
// load data
Data data;
data.load(datafilename);
if (data.U().size() < 1) {
string msg = "loaded data file contains no values!";
throw(Error(msg));
}
// check if model fits to data
if (GLOBAL::consequence_dimension > 1 + data.udim()) {
throw(ConsdimError(itos(GLOBAL::consequence_dimension),
itos(1 + data.udim())));
}
if (fmodel.udim() != data.udim()) {
string msg = "loded model has another udim than loaded data";
throw(Error(msg));
}
// ////////////////////////////////////////////////////////////////////
/* time measurements
* uncomment this block to get time measurement information
* when calling the estimation
*/
/*
{
const int n_iterations = 10000;
time_t t1;
time_t t2;
int tdiff;
for (int k=0; k<1000; ++k) {
fmodel.estimation(data);
}
t1 = time(NULL);
for (int k=0; k<n_iterations; ++k) {
fmodel.estimation(data);
}
t2 = time(NULL);
tdiff = t2 - t1;
PRINT(tdiff);
t1 = time(NULL);
for (int k=0; k<n_iterations; ++k) {
fmodel.RPROP(data);
}
t2 = time(NULL);
tdiff = t2 - t1;
PRINT(tdiff);
}
*/
// ////////////////////////////////////////////////////////////////////
// ok, do the job
string basefilename;
if (GLOBAL::mode == ESTIMATION) {
basefilename = (string)estimation_prefix + GLOBAL::filename_extension;
}
else if (GLOBAL::mode == SIMULATION) {
basefilename = (string)simulation_prefix + GLOBAL::filename_extension;
}
else {
assert(1 == 0);
}
int suffix_len = strlen(model_suffix);
int prefix_len = strlen(model_prefix);
int length = strlen(fzyfilename) - suffix_len - prefix_len;
if (length < 1) {
basefilename += fzyfilename;
}
else {
basefilename += ((string)fzyfilename).substr(prefix_len, length);
}
// basefilename += GLOBAL::filename_extension;
string outfilename = basefilename + output_suffix;
string r2filename = basefilename + r2_suffix;
string errfilename = basefilename + error_suffix;
ofstream r2file(r2filename.c_str());
if (!r2file) {
throw FileOpenError(r2filename);
}
ofstream errfile(errfilename.c_str());
if (!errfile) {
throw FileOpenError(errfilename);
}
Real error = -1.0;
if (GLOBAL::mode == ESTIMATION) {
error = fmodel.estimation(data, outfilename.c_str());
}
else if (GLOBAL::mode == SIMULATION) {
error = fmodel.simulation(data, outfilename.c_str());
}
Real R2 = fmodel.R2(data);
verbose(1, "error", error);
verbose(1, "R2", R2);
if (GLOBAL::mode == ESTIMATION) {
r2file << "### estimation data: \"" << datafilename << "\"\n";
r2file << R2 << endl;
errfile << "### estimation data: \"" << datafilename << "\"\n";
errfile << error << endl;
}
else if (GLOBAL::mode == SIMULATION) {
r2file << "### simulation data: \"" << datafilename << "\"\n";
r2file << R2 << endl;
errfile << "### simulation data: \"" << datafilename << "\"\n";
errfile << error << endl;
}
r2file.close();
errfile.close();
if ((GLOBAL::verbose > 0) && (! GLOBAL::quiet)) {
cout << "R2 and error from ";
if (GLOBAL::mode == ESTIMATION) {
cout << "estimation ";
}
if (GLOBAL::mode == SIMULATION) {
cout << "simulation ";
}
cout << "for `" << fzyfilename << "': "
<< R2 << " \t" << error << endl;
}
return;
}
| 30.265625 | 82 | 0.589916 | [
"model"
] |
63e86fdc21e40f6b2336da3bcc1f76409c8f1650 | 634 | cpp | C++ | solved-codeforces/the_redback/contest/3/a/24394270.cpp | Maruf-Tuhin/Online_Judge | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | 1 | 2019-03-31T05:47:30.000Z | 2019-03-31T05:47:30.000Z | solved-codeforces/the_redback/contest/3/a/24394270.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | solved-codeforces/the_redback/contest/3/a/24394270.cpp | the-redback/competitive-programming | cf9b2a522e8b1a9623d3996a632caad7fd67f751 | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <algorithm>
#include <fstream>
#include <cstring>
#include <cmath>
#include <cctype>
#include <string>
#include <cstdio>
#include <vector>
#include <stack>
#include <bitset>
using namespace std;
int main()
{
int b, d;
char a, c;
scanf("%c%d", &a, &b);
getchar();
scanf("%c%d", &c, &d);
getchar();
printf("%d\n", max(abs(a-c), abs(b-d)));
while(a != c || b != d) {
if(a > c) {
printf("L");
a--;
}
else if(a < c) {
printf("R");
a++;
}
if(b > d) {
printf("D");
b--;
}
else if(b < d) {
printf("U");
b++;
}
printf("\n");
}
return 0;
} | 12.192308 | 41 | 0.512618 | [
"vector"
] |
63e89f66a27ae4395d7c3ee8dcc0416ace203ba9 | 4,541 | hpp | C++ | raygun/pch.hpp | maggo007/Raygun | f6be537c835976a9d6cc356ebe187feba6592847 | [
"MIT"
] | null | null | null | raygun/pch.hpp | maggo007/Raygun | f6be537c835976a9d6cc356ebe187feba6592847 | [
"MIT"
] | null | null | null | raygun/pch.hpp | maggo007/Raygun | f6be537c835976a9d6cc356ebe187feba6592847 | [
"MIT"
] | null | null | null | // The MIT License (MIT)
//
// Copyright (c) 2019,2020 The Raygun Authors.
//
// 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
#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#define NOMINMAX
#define _CRT_SECURE_NO_WARNINGS
#include <Windows.h>
// Symbols that leak and cause problems:
#undef FAR
#undef NEAR
#endif
//////////////////////////////////////////////////////////////////////////
#include <algorithm>
#include <array>
#include <chrono>
#include <experimental/map>
#include <experimental/set>
#include <filesystem>
#include <fstream>
#include <future>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <ostream>
#include <queue>
#include <regex>
#include <set>
#include <sstream>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#include <cassert>
#include <cmath>
#include <csignal>
#include <cstdint>
#include <cstdlib>
#include <cstring>
//////////////////////////////////////////////////////////////////////////
#define VULKAN_HPP_DISPATCH_LOADER_DYNAMIC 1
#include <vulkan/vulkan.hpp>
//////////////////////////////////////////////////////////////////////////
#define GLFW_INCLUDE_NONE
#include <GLFW/glfw3.h>
//////////////////////////////////////////////////////////////////////////
#define GLM_FORCE_DEPTH_ZERO_TO_ONE
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtx/euler_angles.hpp>
#include <glm/gtx/matrix_decompose.hpp>
#include <glm/gtx/projection.hpp>
//////////////////////////////////////////////////////////////////////////
#include <ImGui/imgui.h>
#include <ImGui/imgui_impl_glfw.h>
#include <ImGui/imgui_impl_vulkan.h>
#include <ImGui/multiplot.h>
#include <imGuIZMO/imGuIZMO.h>
//////////////////////////////////////////////////////////////////////////
// PhysX complains if neither _DEBUG nor NDEBUG is set.
#if !defined(NDEBUG) && !defined(_DEBUG)
#define _DEBUG
#endif
#include <PxPhysicsAPI.h>
//////////////////////////////////////////////////////////////////////////
#include <json/json.hpp>
//////////////////////////////////////////////////////////////////////////
#include <fmt/format.h>
#include <fmt/ostream.h> // operator<< support for logging
//////////////////////////////////////////////////////////////////////////
#define SPDLOG_FMT_EXTERNAL
#include <spdlog/spdlog.h>
#include <spdlog/sinks/basic_file_sink.h>
#include <spdlog/sinks/stdout_color_sinks.h>
//////////////////////////////////////////////////////////////////////////
#include <assimp/Importer.hpp>
#include <assimp/postprocess.h>
#include <assimp/scene.h>
//////////////////////////////////////////////////////////////////////////
#include <AL/al.h>
#include <AL/alc.h>
#include <opus/opus_types.h>
#include <opus/opusfile.h>
//////////////////////////////////////////////////////////////////////////
namespace raygun {
namespace fs = std::filesystem;
using Clock = std::chrono::high_resolution_clock;
using string = std::string;
using string_view = std::string_view;
using vec2 = glm::vec2;
using vec3 = glm::vec3;
using vec4 = glm::vec4;
using quat = glm::quat;
using mat3 = glm::mat3;
using mat4 = glm::mat4;
using uint = glm::uint;
using json = nlohmann::json;
constexpr vec3 UP = {0.0f, 1.0f, 0.0f};
constexpr vec3 RIGHT = {1.0f, 0.0f, 0.0f};
constexpr vec3 FORWARD = {0.0f, 0.0f, -1.0f};
template<typename T = vec3>
constexpr T zero()
{
return glm::zero<T>();
}
} // namespace raygun
| 26.869822 | 79 | 0.590619 | [
"vector"
] |
63ed156e34687115c51f1f83e6d5ed0bd3f728fa | 3,802 | cpp | C++ | imt2531_Graphics_Exam_2016/TextureHandler.cpp | Muff1nz/imt2531_Graphics_Exam_2016 | 4be3c69f7fba3d7839add5d5af2c5855f8d00407 | [
"MIT"
] | null | null | null | imt2531_Graphics_Exam_2016/TextureHandler.cpp | Muff1nz/imt2531_Graphics_Exam_2016 | 4be3c69f7fba3d7839add5d5af2c5855f8d00407 | [
"MIT"
] | 1 | 2018-02-13T20:43:52.000Z | 2018-02-13T20:43:52.000Z | imt2531_Graphics_Exam_2016/TextureHandler.cpp | Muff1nz/imt2531_Graphics_Exam_2016 | 4be3c69f7fba3d7839add5d5af2c5855f8d00407 | [
"MIT"
] | null | null | null | #include "TextureHandler.h"
#include "globals.h"
void TextureHandler::init()
{
loadTexture("track", "./resources/trackFixed.png");
loadCubemap("skyBoxDay", "./resources/greywash_");
loadCubemap("skyBoxNight", "./resources/purplenebula_");
loadTexture("snow", "./resources/snow.png");
loadTexture("snow2", "./resources/snow2.png");
}
void TextureHandler::loadTexture(const std::string& name, const std::string& path)
{
// SDL Image is used to load the image and save it as a surface.
SDL_Surface* textureSurface = IMG_Load(path.c_str());
if (!textureSurface)
{
printf("Failed to load texture \"%s\": %s\n", path.c_str(), IMG_GetError());
return;
}
// Generate and bind the texture buffer
GLuint textureBuffer = 0;
glActiveTexture(GL_TEXTURE0 + textureIDs.size());
glGenTextures(1, &textureBuffer);
glBindTexture(GL_TEXTURE_2D, textureBuffer);
// We tell OpenGL what to do when it needs to render the texture at a higher or lower resolution.
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
// Create the texture
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, textureSurface->w, textureSurface->h, 0, GL_RGBA, GL_UNSIGNED_BYTE, textureSurface->pixels);
//SDL_FreeSurface(textureSurface); I hate this line of code so so much. crashes my program with certain textures, i'd rather leak memory
// wasted more time because of it then i'd like.
textureIDs.insert(std::pair<std::string, int>(name, textureIDs.size()));
textureCount++;
}
//This function assumes files from http://www.custommapmakers.org/skyboxes.php
void TextureHandler::loadCubemap(const std::string& name, const std::string& path) {
GLuint textureID;
SDL_Surface* textureSurface;
glGenTextures(1, &textureID);
glActiveTexture(GL_TEXTURE0 + textureIDs.size());
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
textureSurface = IMG_Load((path + "ft.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
textureSurface = IMG_Load((path + "bk.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_X, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
textureSurface = IMG_Load((path + "rt.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Z, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
textureSurface = IMG_Load((path + "lf.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
textureSurface = IMG_Load((path + "up.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_Y, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
textureSurface = IMG_Load((path + "dn.tga").c_str());
glTexImage2D(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y, 0, GL_RGB, textureSurface->w, textureSurface->h, 0, GL_RGB, GL_UNSIGNED_BYTE, textureSurface->pixels);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
textureIDs.insert(std::pair<std::string, int>(name, textureIDs.size()));
textureCount++;
}
int TextureHandler::getTexture(const std::string& name)
{
if (textureIDs.count(name))
return textureIDs[name];
printf("ERROR: No texture with the name \"%s\" could be found.\n", name.c_str());
return 0;
}
| 43.204545 | 148 | 0.765913 | [
"render"
] |
63ff800f3c9b0f830bb15d74624c3c79f14ded4b | 4,057 | cpp | C++ | code/aoce_ffmpeg/media/FH264Encoder.cpp | xxxzhou/aoce | c1895d7ecc784354744886fb6db4174f211d81d1 | [
"MIT"
] | 71 | 2020-10-15T03:13:50.000Z | 2022-03-30T02:04:28.000Z | code/aoce_ffmpeg/media/FH264Encoder.cpp | dengxbin/aoce | c1895d7ecc784354744886fb6db4174f211d81d1 | [
"MIT"
] | 9 | 2021-02-20T10:30:10.000Z | 2022-03-04T07:59:58.000Z | code/aoce_ffmpeg/media/FH264Encoder.cpp | dengxbin/aoce | c1895d7ecc784354744886fb6db4174f211d81d1 | [
"MIT"
] | 19 | 2021-01-01T12:03:02.000Z | 2022-03-21T07:59:59.000Z | #include "FH264Encoder.hpp"
namespace aoce {
namespace ffmpeg {
FH264Encoder::FH264Encoder(/* args */) {}
FH264Encoder::~FH264Encoder() {}
bool FH264Encoder::onPrepare() {
std::vector<std::string> videoEncodes = {"libx264", "h264_nvenc",
"h264_qsv"};
for (const auto& name : videoEncodes) {
auto codec = avcodec_find_encoder_by_name(name.c_str());
if (!codec) {
continue;
}
AVCodecContext* temp = avcodec_alloc_context3(codec);
if (!temp) {
continue;
}
cdeCtx = getUniquePtr(temp);
cdeCtx->codec_type = AVMEDIA_TYPE_VIDEO;
cdeCtx->width = stream.width;
cdeCtx->height = stream.height;
cdeCtx->coded_width = stream.width;
cdeCtx->coded_height = stream.height;
cdeCtx->bit_rate = stream.bitrate;
cdeCtx->rc_buffer_size = stream.bitrate;
cdeCtx->gop_size = stream.fps * 1;
cdeCtx->time_base = {1, stream.fps};
cdeCtx->delay = 0;
// H264
if (rate == RateControl::vbr) { // VBR
cdeCtx->flags |= AV_CODEC_FLAG_PASS1;
cdeCtx->flags |= AV_CODEC_FLAG_QSCALE;
cdeCtx->rc_min_rate = stream.bitrate;
cdeCtx->rc_max_rate = stream.bitrate * 3 / 2;
} else if (rate == RateControl::qp) { // QP
cdeCtx->qmin = 21;
cdeCtx->qmax = 26;
}
cdeCtx->has_b_frames = 0;
cdeCtx->max_b_frames = 0;
cdeCtx->me_pre_cmp = 2;
AVDictionary* param = nullptr;
if (stream.videoType == VideoType::yuv420P) {
temp->pix_fmt = AV_PIX_FMT_YUV420P;
av_dict_set(¶m, "profile", "high", 0);
} else if (stream.videoType == VideoType::yuy2P) {
temp->pix_fmt = AV_PIX_FMT_YUV422P;
av_dict_set(¶m, "profile", "high422", 0);
}
if (cdeCtx->codec_id == AV_CODEC_ID_H264) {
av_dict_set(¶m, "tune", "zerolatency", 0);
}
int ret = avcodec_open2(cdeCtx.get(), codec, ¶m);
if (ret < 0) {
cdeCtx.reset();
logFRet(ret, "open h264 codec failed.");
continue;
}
break;
}
if (!cdeCtx) {
return false;
}
frame = getUniquePtr(av_frame_alloc());
if (!frame) {
return false;
}
frame->format = cdeCtx->pix_fmt;
frame->width = cdeCtx->width;
frame->height = cdeCtx->height;
frame->linesize[0] = cdeCtx->width;
frame->linesize[1] = cdeCtx->width / 2;
frame->linesize[2] = cdeCtx->width / 2;
totalFrame = 0;
return true;
}
int32_t FH264Encoder::input(const VideoFrame& vframe) {
frame->data[0] = vframe.data[0];
frame->data[1] = vframe.data[1];
frame->data[2] = vframe.data[2];
if (vframe.dataAlign[0] > 0) {
frame->linesize[0] = vframe.dataAlign[0];
}
if (vframe.dataAlign[1] > 0) {
frame->linesize[1] = vframe.dataAlign[1];
}
if (vframe.dataAlign[2] > 0) {
frame->linesize[2] = vframe.dataAlign[2];
}
frame->pts = totalFrame;
int32_t ret = avcodec_send_frame(cdeCtx.get(), frame.get());
if (ret < 0) {
logFRet(ret, "h264 avcodec_send_frame error.");
}
totalFrame++;
return ret;
}
// int32_t FH264Encoder::output(VideoPacket& vpacket) {
// AVPacket packet = {};
// av_init_packet(&packet);
// int32_t ret = avcodec_receive_packet(cdeCtx.get(), &packet);
// if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
// return 0;
// } else if (ret < 0) {
// logFRet(ret, "h264 avcodec_receive_packet error.");
// av_packet_unref(&packet);
// return ret;
// }
// if (packet.size > AOCE_H264_BUFFER_MAX_SIZE) {
// return -2;
// }
// memcpy(vpacket.data, packet.data, packet.size);
// vpacket.lenght = packet.size;
// vpacket.timeStamp = packet.pts;
// av_packet_unref(&packet);
// return 0;
// }
} // namespace ffmpeg
} // namespace aoce | 32.198413 | 69 | 0.561499 | [
"vector"
] |
121065f90819d212c856618238758354023792bb | 7,211 | cpp | C++ | libpharos/demangle_json.cpp | tjschweizer/pharos | 4c5cea68c4489d798e341319d1d5e0d2fee71422 | [
"RSA-MD"
] | 1,247 | 2015-06-15T17:51:31.000Z | 2022-03-31T10:24:47.000Z | libpharos/demangle_json.cpp | tjschweizer/pharos | 4c5cea68c4489d798e341319d1d5e0d2fee71422 | [
"RSA-MD"
] | 191 | 2017-07-05T19:06:28.000Z | 2022-03-20T14:31:10.000Z | libpharos/demangle_json.cpp | tjschweizer/pharos | 4c5cea68c4489d798e341319d1d5e0d2fee71422 | [
"RSA-MD"
] | 180 | 2015-06-25T21:34:54.000Z | 2022-03-21T04:25:04.000Z | // Copyright 2017-2018 Carnegie Mellon University. See LICENSE file for terms.
#include "demangle_json.hpp"
#include <utility> // std::move
#include <sstream> // std::ostringstream
namespace demangle {
void JsonOutput::handle_symbol_type(Object & obj, DemangledType const & sym) const
{
// Symbol type
char const * symbol_type = nullptr;
switch (sym.symbol_type) {
case SymbolType::Unspecified:
return;
// Fall through
case SymbolType::StaticClassMember:
symbol_type = "static class member";
break;
case SymbolType::GlobalObject:
symbol_type = "global object";
break;
case SymbolType::GlobalFunction:
symbol_type = "global function";
break;
case SymbolType::ClassMethod:
symbol_type = "class method";
break;
case SymbolType::GlobalThing1:
symbol_type = "global thing 1";
break;
case SymbolType::GlobalThing2:
symbol_type = "global thing 2";
break;
case SymbolType::String:
symbol_type = "string";
break;
case SymbolType::VtorDisp:
symbol_type = "vtordisp";
break;
case SymbolType::StaticGuard:
symbol_type = "static guard";
break;
case SymbolType::MethodThunk:
symbol_type = "method thunk";
break;
case SymbolType::HexSymbol:
symbol_type = "hex symbol";
break;
}
obj.add("symbol_type", symbol_type);
}
void JsonOutput::handle_scope(Object & obj, DemangledType const & sym) const
{
char const * scope = nullptr;
switch (sym.scope) {
case Scope::Unspecified:
return;
case Scope::Private:
scope = "private";
break;
case Scope::Protected:
scope = "protected";
break;
case Scope::Public:
scope = "public";
break;
}
obj.add("scope", scope);
}
void JsonOutput::handle_distance(Object & obj, DemangledType const & sym) const
{
char const * distance = nullptr;
switch (sym.distance) {
case Distance::Unspecified:
return;
case Distance::Near:
distance = "near";
break;
case Distance::Far:
distance = "far";
break;
case Distance::Huge:
distance = "huge";
break;
}
obj.add("distance", distance);
}
void JsonOutput::handle_method_property(Object & obj, DemangledType const & sym) const
{
char const * prop = nullptr;
switch (sym.method_property) {
case MethodProperty::Unspecified:
return;
case MethodProperty::Ordinary:
prop = "ordinary";
break;
case MethodProperty::Static:
prop = "static";
break;
case MethodProperty::Virtual:
prop = "virtual";
break;
case MethodProperty::Thunk:
prop = "thunk";
break;
}
obj.add("method_property", prop);
}
void JsonOutput::handle_namespace(Object & obj, DemangledType const & sym) const
{
if (sym.name.empty()) {
return;
}
auto ns = builder.array();
for (auto & part : sym.name) {
ns->add(convert(*part));
}
obj.add("namespace", std::move(ns));
}
JsonOutput::ObjectRef JsonOutput::convert(DemangledType const & sym) const
{
// This is not yet finished
auto node = builder.object();
auto & obj = *node;
handle_symbol_type(obj, sym);
handle_scope(obj, sym);
if (sym.symbol_type == SymbolType::GlobalFunction
|| sym.symbol_type == SymbolType::ClassMethod)
{
handle_distance(obj, sym);
if (sym.retval) {
obj.add("return_type", convert(*sym.retval));
}
obj.add("calling_convention", sym.calling_convention);
}
handle_namespace(obj, sym);
return node;
}
JsonOutput::ObjectRef JsonOutput::raw(DemangledType const & sym) const
{
auto node = builder.object();
auto & obj = *node;
auto add_bool = [&obj](char const * name, bool val) {
if (val) {
obj.add(name, val);
}
};
auto add_rlist = [&obj, this](char const * name, FullyQualifiedName const & names) {
if (!names.empty()) {
auto nlist = builder.array();
for (auto i = names.rbegin(); i != names.rend(); ++i) {
nlist->add(raw(**i));
}
obj.add(name, std::move(nlist));
}
};
auto add_list = [&obj, this](char const * name, FullyQualifiedName const & names) {
if (!names.empty()) {
auto nlist = builder.array();
for (auto & n : names) {
nlist->add(raw(*n));
}
obj.add(name, std::move(nlist));
}
};
add_bool("is_const", sym.is_const);
add_bool("is_volatile", sym.is_volatile);
add_bool("is_reference", sym.is_reference);
add_bool("is_pointer", sym.is_pointer);
add_bool("is_array", sym.is_array);
if (!sym.dimensions.empty()) {
auto dim = builder.array();
for (auto d : sym.dimensions) {
dim->add(std::intmax_t(d));
}
obj.add("dimensions", std::move(dim));
}
add_bool("is_embedded", sym.is_embedded);
add_bool("is_func", sym.is_func);
add_bool("is_based", sym.is_based);
add_bool("is_member", sym.is_member);
add_bool("is_namespace", sym.is_namespace);
add_bool("is_anonymous", sym.is_anonymous);
add_bool("is_refref", sym.is_refref);
handle_symbol_type(obj, sym);
handle_distance(obj, sym);
add_bool("ptr64", sym.ptr64);
add_bool("unaligned", sym.unaligned);
add_bool("restrict", sym.restrict);
add_bool("is_gc", sym.is_gc);
add_bool("is_pin", sym.is_pin);
if (sym.inner_type) {
obj.add("inner_type", raw(*sym.inner_type));
}
if (sym.enum_real_type) {
obj.add("enum_real_type", raw(*sym.enum_real_type));
}
if (!sym.simple_type.empty()) {
obj.add("simple_type", sym.simple_type);
}
add_rlist("name", sym.name);
add_list("com_interface", sym.com_interface);
if (!sym.template_parameters.empty()) {
auto params = builder.array();
for (auto & param : sym.template_parameters) {
if (param) {
auto p = builder.object();
if (param->type) {
p->add("type", raw(*param->type));
if (param->pointer) {
p->add("pointer", param->pointer);
}
} else {
p->add("constant_value", param->constant_value);
}
params->add(std::move(p));
}
}
obj.add("template_parameters", std::move(params));
}
handle_scope(obj, sym);
handle_method_property(obj, sym);
if (!sym.calling_convention.empty()) {
obj.add("calling_convention", sym.calling_convention);
}
add_bool("is_ctor", sym.is_ctor);
add_bool("is_dtor", sym.is_dtor);
add_list("instance_name", sym.instance_name);
if (sym.retval) {
obj.add("retval", raw(*sym.retval));
}
add_list("args", sym.args);
if (sym.n1 || sym.n2 || sym.n3 || sym.n4) {
obj.add("n1", sym.n1);
obj.add("n2", sym.n2);
obj.add("n3", sym.n3);
obj.add("n4", sym.n4);
}
add_bool("extern_c", sym.extern_c);
// This is not raw, but has been added here for testing purposes
auto class_name = sym.get_class_name();
if (!class_name.empty()) {
obj.add("class_name", std::move(class_name));
}
// This is not raw, but has been added here for testing purposes
auto method_name = sym.get_method_name();
if (!method_name.empty()) {
obj.add("method_name", std::move(method_name));
}
return node;
}
} // namespace demangle
/* Local Variables: */
/* mode: c++ */
/* fill-column: 95 */
/* comment-column: 0 */
/* End: */
| 25.753571 | 86 | 0.631258 | [
"object"
] |
1216148c7769303687c5cc6a7124975cecfa4913 | 2,059 | cpp | C++ | leetcode/310. Minimum Height Trees.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | 1 | 2018-09-13T12:16:42.000Z | 2018-09-13T12:16:42.000Z | leetcode/310. Minimum Height Trees.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | leetcode/310. Minimum Height Trees.cpp | chamow97/Interview-Prep | 9ce13afef6090b1604f72bf5f80a6e1df65be24f | [
"MIT"
] | null | null | null | class Solution {
public:
int maxDepth;
int farthestNode;
void dfs(int s, vector<bool> &visited, vector< vector<int> > &adj, int currDepth, vector<int> &path) {
visited[s] = true;
if(maxDepth < currDepth) {
maxDepth = currDepth;
farthestNode = s;
}
for(auto i : adj[s]) {
if(!visited[i]) {
path[i] = s;
dfs(i, visited, adj, currDepth + 1, path);
}
}
}
vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) {
// find any leaf node and store the nodes based on the height
// while finding the diameter of the tree
// output the nodes with middle height
vector< vector<int> > adj(n, vector<int>(0));
for(int i = 0; i < edges.size(); i++) {
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
// resetting values
farthestNode = 0;
maxDepth = 0;
vector<int> path(n, -1);
vector<bool> visited(n, false);
// first DFS to find any leaf node
dfs(0, visited, adj, 0, path);
// resetting the values for next DFS which finds the diameter and its path
maxDepth = -1;
fill(visited.begin(), visited.end(), false);
fill(path.begin(), path.end(), -1);
dfs(farthestNode, visited, adj, 0, path);
// finding the middle node by traversing the path
int u = farthestNode;
int currDepth = 0;
vector<int> result;
while(u != -1) {
if(maxDepth % 2) {
if(currDepth == (maxDepth / 2) || currDepth == ((maxDepth + 1) / 2)) {
result.push_back(u);
}
} else {
if(currDepth == (maxDepth / 2)) {
result.push_back(u);
}
}
currDepth++;
u = path[u];
}
return result;
}
};
| 31.676923 | 106 | 0.478388 | [
"vector"
] |
1217af7539fe693cbe4134b56384ed31d572f27a | 3,940 | hpp | C++ | src/GraphViz.hpp | jhidalgocarrio/slam-envire_core | 4a1bc6b458989e39e4f16cab80777fdbb76cbff3 | [
"BSD-2-Clause"
] | null | null | null | src/GraphViz.hpp | jhidalgocarrio/slam-envire_core | 4a1bc6b458989e39e4f16cab80777fdbb76cbff3 | [
"BSD-2-Clause"
] | null | null | null | src/GraphViz.hpp | jhidalgocarrio/slam-envire_core | 4a1bc6b458989e39e4f16cab80777fdbb76cbff3 | [
"BSD-2-Clause"
] | null | null | null | #ifndef __ENVIRE_CORE_GRAPHVIZ__
#define __ENVIRE_CORE_GRAPHVIZ__
#include <fstream> // std::ofstream
#include <envire_core/TransformTree.hpp>
#include <boost/graph/graphviz.hpp>
namespace envire { namespace core
{
/**@class Transform Writer
* Frame Graph Viz property writer for boost graphs
* */
template <class _Frame>
class FrameWriter
{
public:
FrameWriter(_Frame _f):f(_f){}
template <class _Vertex>
void operator()(std::ostream &out, const _Vertex& n) const
{
if(f[n].name.find("camera") != std::string::npos)
{
out << "[shape=record, label=\"<f0> " << f[n].name <<
"|<f1>" << f[n].items.size()<<"\""
<<",style=filled,fillcolor=orange]";
}
else
{
out << "[shape=record, label=\"<f0> " << f[n].name <<
"|<f1>" << f[n].items.size()<<"\""
<<",style=filled,fillcolor=lightblue]";
}
}
private:
_Frame f;
};
/**@class Transform Writer
* Transform Graph Viz Property writer for boost graphs
* */
template <class _Transform>
class TransformWriter
{
public:
TransformWriter(_Transform _tf):tf(_tf){}
template <class _Edge>
void operator()(std::ostream &out, const _Edge& e) const
{
out << "[label=\"" << tf[e].time.toString(::base::Time::Seconds) <<
boost::format("\\nt: (%.1f %.1f %.1f)\\nr: (%.1f %.1f %.1f %.1f)") % tf[e].transform.translation.x() % tf[e].transform.translation.y() % tf[e].transform.translation.z()
% tf[e].transform.orientation.w() % tf[e].transform.orientation.x() % tf[e].transform.orientation.y() % tf[e].transform.orientation.z()
<< "\""
<< ",shape=ellipse,color=red,style=filled,fillcolor=lightcoral]";
}
private:
_Transform tf;
};
/**@class Environment Writer
* Transform Graph Viz Property writer for boost graphs
* */
class GraphPropWriter
{
public:
GraphPropWriter(){}
void operator()(std::ostream &out) const
{
//out<< "graph[rankdir=LR,splines=ortho];\n";
out<< "graph[size=\"88,136\", ranksep=3.0, nodesep=2.0, fontname=\"Helvetica\", fontsize=8];\n";
}
};
/**@class GraphViz
* Class to print TransformGraphs in Graph Viz
* */
class GraphViz
{
protected:
inline GraphPropWriter
make_graph_writer()
{
return GraphPropWriter();
}
/**@brief Writer for Frame Node
*/
template <class _Frame>
inline FrameWriter<_Frame>
make_node_writer(_Frame frame)
{
return FrameWriter<_Frame>(frame);
}
/**@brief Writer for Frame Node
*/
template <class _Transform>
inline TransformWriter<_Transform>
make_edge_writer(_Transform tf)
{
return TransformWriter<_Transform>(tf);
}
public:
/**@brief Export to GraphViz
*
*/
void write(const TransformGraph &graph, const std::string& filename = "")
{
std::streambuf * buf;
std::ofstream of;
if(!filename.empty())
{
of.open(filename.c_str());
buf = of.rdbuf();
}
else
{
buf = std::cout.rdbuf();
}
/** Print graph **/
std::ostream out(buf);
boost::write_graphviz (out, graph,
make_node_writer(boost::get(&FrameProperty::frame, graph)),
make_edge_writer(boost::get(&TransformProperty::transform, graph)),
make_graph_writer());
}
};
}}
#endif
| 27.172414 | 184 | 0.513959 | [
"shape",
"transform"
] |
121abd15584c89eb709f1b462bd0cfbb8702646e | 1,213 | cpp | C++ | src/xyz_reader.cpp | aasoni/wave | 91f4c4d45d97e8aed9d10d3a7114120e55d02a26 | [
"MIT"
] | null | null | null | src/xyz_reader.cpp | aasoni/wave | 91f4c4d45d97e8aed9d10d3a7114120e55d02a26 | [
"MIT"
] | 1 | 2016-06-25T22:10:57.000Z | 2016-06-25T22:10:57.000Z | src/xyz_reader.cpp | aasoni/wave | 91f4c4d45d97e8aed9d10d3a7114120e55d02a26 | [
"MIT"
] | null | null | null | #include <xyz_reader.h>
#include <fstream>
#include <iostream>
namespace aasoni {
//Reads file in format:
//x_1 y_m z_1_m
//x_2 y_m z_1_m
//x_3 y_m z_1_m
// .
// .
//x_n y_m z_1_(m-1)
//x_1 y_(m_1) z_1_(m-1)
// .
// .
//x_n y_1 z_n_1
bool XYZ_Reader::readFile(VEC *x, VEC *y, vector<VEC> *z)
{
if(!x || !y || !z)
return false;
ifstream fhandle(m_fileName.c_str(), ifstream::in);
if(!fhandle.good())
return false;
size_t &m = m_yLength;
size_t &n = m_xLength;
//allocate size for data vectors
x->resize(n);
y->resize(m);
z->resize(m);
for(size_t i=0; i != m; ++i)
(*z)[i].resize(n);
size_t i = 0, xIdx = 0, yIdx = 0;
double xVal, yVal, zVal;
while (i < m*n)
{
fhandle >> xVal >> yVal >> zVal;
//fill X (only needed for first n lines)
xIdx = i % n;
if(i < n)
(*x)[xIdx] = xVal;
//fill Y (only needed every m lines)
yIdx = m - 1 - (i - (i%n))/n;
if( (i % m) == 1 )
(*y)[yIdx] = yVal;
//fill Z
(*z)[yIdx][xIdx] = zVal;
++i;
}
return true;
}
}// end aasoni
| 18.661538 | 57 | 0.472383 | [
"vector"
] |
12272ecd85ed5ff772c5af06eed8e3acd94d2542 | 20,551 | cc | C++ | diagnostics/cros_healthd/cros_healthd_mojo_service_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/cros_healthd_mojo_service_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | diagnostics/cros_healthd/cros_healthd_mojo_service_test.cc | strassek/chromiumos-platform2 | 12c953f41f48b8a6b0bd1c181d09bdb1de38325c | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <functional>
#include <string>
#include <utility>
#include <vector>
#include <base/bind.h>
#include <base/optional.h>
#include <base/run_loop.h>
#include <base/test/task_environment.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <mojo/core/embedder/embedder.h>
#include "diagnostics/cros_healthd/cros_healthd_mojo_service.h"
#include "diagnostics/cros_healthd/cros_healthd_routine_service.h"
#include "diagnostics/cros_healthd/events/bluetooth_events_impl.h"
#include "diagnostics/cros_healthd/events/lid_events_impl.h"
#include "diagnostics/cros_healthd/events/power_events_impl.h"
#include "diagnostics/cros_healthd/fetch_aggregator.h"
#include "diagnostics/cros_healthd/system/mock_context.h"
#include "mojo/cros_healthd.mojom.h"
using testing::_;
using testing::Invoke;
using testing::NotNull;
using testing::Return;
using testing::StrictMock;
using testing::WithArgs;
namespace diagnostics {
namespace mojo_ipc = ::chromeos::cros_healthd::mojom;
namespace {
constexpr uint32_t kExpectedId = 123;
constexpr mojo_ipc::DiagnosticRoutineStatusEnum kExpectedStatus =
mojo_ipc::DiagnosticRoutineStatusEnum::kReady;
// Saves |response| to |response_destination|.
template <class T>
void SaveMojoResponse(T* response_destination, T response) {
*response_destination = std::move(response);
}
class MockCrosHealthdRoutineService : public CrosHealthdRoutineService {
public:
MOCK_METHOD0(GetAvailableRoutines,
std::vector<mojo_ipc::DiagnosticRoutineEnum>());
MOCK_METHOD4(RunBatteryCapacityRoutine,
void(uint32_t low_mah,
uint32_t high_mah,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD4(RunBatteryHealthRoutine,
void(uint32_t maximum_cycle_count,
uint32_t percent_battery_wear_allowed,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunUrandomRoutine,
void(uint32_t length_seconds,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD2(RunSmartctlCheckRoutine,
void(int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD4(RunAcPowerRoutine,
void(mojo_ipc::AcPowerStatusEnum expected_status,
const base::Optional<std::string>& expected_power_type,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunCpuCacheRoutine,
void(base::TimeDelta exec_duration,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunCpuStressRoutine,
void(base::TimeDelta exec_duration,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunFloatingPointAccuracyRoutine,
void(base::TimeDelta exec_duration,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunNvmeWearLevelRoutine,
void(uint32_t wear_level_threshold,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD3(RunNvmeSelfTestRoutine,
void(mojo_ipc::NvmeSelfTestTypeEnum nvme_self_test_type,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD5(RunDiskReadRoutine,
void(mojo_ipc::DiskReadRoutineTypeEnum type,
base::TimeDelta exec_duration,
uint32_t file_size_mb,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD4(RunPrimeSearchRoutine,
void(base::TimeDelta exec_duration,
uint64_t max_num,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD4(RunBatteryDischargeRoutine,
void(base::TimeDelta exec_duration,
uint32_t maximum_discharge_percent_allowed,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status));
MOCK_METHOD(void,
RunBatteryChargeRoutine,
(base::TimeDelta exec_duration,
uint32_t minimum_charge_percent_required,
int32_t* id,
mojo_ipc::DiagnosticRoutineStatusEnum* status),
(override));
MOCK_METHOD(void,
RunMemoryRoutine,
(int32_t*, mojo_ipc::DiagnosticRoutineStatusEnum*),
(override));
MOCK_METHOD4(GetRoutineUpdate,
void(int32_t uuid,
mojo_ipc::DiagnosticRoutineCommandEnum command,
bool include_output,
mojo_ipc::RoutineUpdate* response));
};
} // namespace
// Tests for the CrosHealthddMojoService class.
class CrosHealthdMojoServiceTest : public testing::Test {
protected:
void SetUp() override { ASSERT_TRUE(mock_context_.Initialize()); }
CrosHealthdMojoService* service() { return &service_; }
MockCrosHealthdRoutineService* routine_service() { return &routine_service_; }
private:
base::test::TaskEnvironment task_environment_{
base::test::TaskEnvironment::ThreadingMode::MAIN_THREAD_ONLY};
StrictMock<MockCrosHealthdRoutineService> routine_service_;
MockContext mock_context_;
FetchAggregator fetch_aggregator_{&mock_context_};
BluetoothEventsImpl bluetooth_events_{&mock_context_};
LidEventsImpl lid_events_{&mock_context_};
PowerEventsImpl power_events_{&mock_context_};
CrosHealthdMojoService service_{&fetch_aggregator_, &bluetooth_events_,
&lid_events_, &power_events_,
&routine_service_};
};
// Test that we can request the battery capacity routine.
TEST_F(CrosHealthdMojoServiceTest, RequestBatteryCapacityRoutine) {
constexpr uint32_t low_mah = 10;
constexpr uint32_t high_mah = 100;
EXPECT_CALL(*routine_service(), RunBatteryCapacityRoutine(
low_mah, high_mah, NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunBatteryCapacityRoutine(
low_mah, high_mah,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the battery health routine.
TEST_F(CrosHealthdMojoServiceTest, RequestBatteryHealthRoutine) {
constexpr uint32_t maximum_cycle_count = 44;
constexpr uint32_t percent_battery_wear_allowed = 13;
EXPECT_CALL(
*routine_service(),
RunBatteryHealthRoutine(maximum_cycle_count, percent_battery_wear_allowed,
NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunBatteryHealthRoutine(
maximum_cycle_count, percent_battery_wear_allowed,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the urandom routine.
TEST_F(CrosHealthdMojoServiceTest, RequestUrandomRoutine) {
constexpr uint32_t length_seconds = 22;
EXPECT_CALL(*routine_service(),
RunUrandomRoutine(length_seconds, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunUrandomRoutine(
length_seconds,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the smartctl-check routine.
TEST_F(CrosHealthdMojoServiceTest, RequestSmartctlCheckRoutine) {
EXPECT_CALL(*routine_service(), RunSmartctlCheckRoutine(NotNull(), NotNull()))
.WillOnce(WithArgs<0, 1>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunSmartctlCheckRoutine(base::Bind(
&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>, &response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the AC power routine.
TEST_F(CrosHealthdMojoServiceTest, RequestAcPowerRoutine) {
constexpr mojo_ipc::AcPowerStatusEnum kConnected =
mojo_ipc::AcPowerStatusEnum::kConnected;
const base::Optional<std::string> kPowerType{"USB_PD"};
EXPECT_CALL(*routine_service(),
RunAcPowerRoutine(kConnected, kPowerType, NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunAcPowerRoutine(
kConnected, kPowerType,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the CPU cache routine.
TEST_F(CrosHealthdMojoServiceTest, RequestCpuCacheRoutine) {
constexpr auto exec_duration = base::TimeDelta().FromSeconds(30);
EXPECT_CALL(*routine_service(),
RunCpuCacheRoutine(exec_duration, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunCpuCacheRoutine(
exec_duration.InSeconds(),
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the CPU stress routine.
TEST_F(CrosHealthdMojoServiceTest, RequestCpuStressRoutine) {
constexpr auto exec_duration = base::TimeDelta().FromMinutes(5);
EXPECT_CALL(*routine_service(),
RunCpuStressRoutine(exec_duration, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunCpuStressRoutine(
exec_duration.InSeconds(),
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the floating-point-accuracy routine.
TEST_F(CrosHealthdMojoServiceTest, RequestFloatingPointAccuracyRoutine) {
constexpr base::TimeDelta exec_duration = base::TimeDelta::FromSeconds(22);
EXPECT_CALL(*routine_service(), RunFloatingPointAccuracyRoutine(
exec_duration, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunFloatingPointAccuracyRoutine(
exec_duration.InSeconds(),
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the NvmeWearLevel routine.
TEST_F(CrosHealthdMojoServiceTest, RequestNvmeWearLevelRoutine) {
constexpr uint32_t kThreshold = 50;
EXPECT_CALL(*routine_service(),
RunNvmeWearLevelRoutine(kThreshold, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunNvmeWearLevelRoutine(
kThreshold, base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the NvmeSelfTest routine.
TEST_F(CrosHealthdMojoServiceTest, RequestNvmeSelfTestRoutine) {
constexpr mojo_ipc::NvmeSelfTestTypeEnum kNvmeSelfTestType =
mojo_ipc::NvmeSelfTestTypeEnum::kShortSelfTest;
EXPECT_CALL(*routine_service(),
RunNvmeSelfTestRoutine(kNvmeSelfTestType, NotNull(), NotNull()))
.WillOnce(WithArgs<1, 2>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunNvmeSelfTestRoutine(
kNvmeSelfTestType,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the disk-read routine.
TEST_F(CrosHealthdMojoServiceTest, RequestDiskReadRoutine) {
constexpr mojo_ipc::DiskReadRoutineTypeEnum kType =
mojo_ipc::DiskReadRoutineTypeEnum::kLinearRead;
constexpr auto kExecDuration = base::TimeDelta::FromSeconds(8);
constexpr uint32_t kFileSizeMb = 2048;
EXPECT_CALL(*routine_service(),
RunDiskReadRoutine(kType, kExecDuration, kFileSizeMb, NotNull(),
NotNull()))
.WillOnce(WithArgs<3, 4>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunDiskReadRoutine(
kType, kExecDuration.InSeconds(), kFileSizeMb,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the prime-search routine.
TEST_F(CrosHealthdMojoServiceTest, RequestPrimeSearchRoutine) {
constexpr auto kExecDuration = base::TimeDelta::FromSeconds(8);
constexpr uint32_t kMaxNum = 10020;
EXPECT_CALL(*routine_service(), RunPrimeSearchRoutine(kExecDuration, kMaxNum,
NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunPrimeSearchRoutine(
kExecDuration.InSeconds(), kMaxNum,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the battery discharge routine.
TEST_F(CrosHealthdMojoServiceTest, RequestBatteryDischargeRoutine) {
constexpr uint32_t kLengthSeconds = 90;
constexpr uint32_t kMaximumDischargePercentAllowed = 34;
EXPECT_CALL(*routine_service(),
RunBatteryDischargeRoutine(
base::TimeDelta::FromSeconds(kLengthSeconds),
kMaximumDischargePercentAllowed, NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunBatteryDischargeRoutine(
kLengthSeconds, kMaximumDischargePercentAllowed,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test that we can request the battery charge routine.
TEST_F(CrosHealthdMojoServiceTest, RequestBatteryChargeRoutine) {
constexpr uint32_t kLengthSeconds = 90;
constexpr uint32_t kMinimumChargePercentRequired = 21;
EXPECT_CALL(*routine_service(),
RunBatteryChargeRoutine(
base::TimeDelta::FromSeconds(kLengthSeconds),
kMinimumChargePercentRequired, NotNull(), NotNull()))
.WillOnce(WithArgs<2, 3>(Invoke(
[](int32_t* id, mojo_ipc::DiagnosticRoutineStatusEnum* status) {
*id = kExpectedId;
*status = kExpectedStatus;
})));
mojo_ipc::RunRoutineResponsePtr response;
service()->RunBatteryChargeRoutine(
kLengthSeconds, kMinimumChargePercentRequired,
base::Bind(&SaveMojoResponse<mojo_ipc::RunRoutineResponsePtr>,
&response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->id, kExpectedId);
EXPECT_EQ(response->status, kExpectedStatus);
}
// Test an update request.
TEST_F(CrosHealthdMojoServiceTest, RequestRoutineUpdate) {
constexpr int kId = 3;
constexpr mojo_ipc::DiagnosticRoutineCommandEnum kCommand =
mojo_ipc::DiagnosticRoutineCommandEnum::kGetStatus;
constexpr bool kIncludeOutput = true;
constexpr int kFakeProgressPercent = 13;
EXPECT_CALL(*routine_service(),
GetRoutineUpdate(kId, kCommand, kIncludeOutput, _))
.WillOnce(WithArgs<3>(Invoke([](mojo_ipc::RoutineUpdate* update) {
update->progress_percent = kFakeProgressPercent;
})));
mojo_ipc::RoutineUpdatePtr response;
service()->GetRoutineUpdate(
kId, kCommand, kIncludeOutput,
base::Bind(&SaveMojoResponse<mojo_ipc::RoutineUpdatePtr>, &response));
ASSERT_TRUE(!response.is_null());
EXPECT_EQ(response->progress_percent, kFakeProgressPercent);
}
// Test that we report available routines correctly.
TEST_F(CrosHealthdMojoServiceTest, RequestAvailableRoutines) {
const std::vector<mojo_ipc::DiagnosticRoutineEnum> available_routines = {
mojo_ipc::DiagnosticRoutineEnum::kUrandom,
mojo_ipc::DiagnosticRoutineEnum::kSmartctlCheck,
mojo_ipc::DiagnosticRoutineEnum::kFloatingPointAccuracy,
mojo_ipc::DiagnosticRoutineEnum::kNvmeWearLevel,
mojo_ipc::DiagnosticRoutineEnum::kNvmeSelfTest,
mojo_ipc::DiagnosticRoutineEnum::kDiskRead,
mojo_ipc::DiagnosticRoutineEnum::kPrimeSearch,
};
EXPECT_CALL(*routine_service(), GetAvailableRoutines())
.WillOnce(Return(available_routines));
std::vector<mojo_ipc::DiagnosticRoutineEnum> response;
service()->GetAvailableRoutines(base::Bind(
[](std::vector<chromeos::cros_healthd::mojom::DiagnosticRoutineEnum>* out,
const std::vector<
chromeos::cros_healthd::mojom::DiagnosticRoutineEnum>& routines) {
*out = routines;
},
&response));
EXPECT_EQ(response, available_routines);
}
} // namespace diagnostics
| 38.557223 | 80 | 0.686147 | [
"vector"
] |
1233181b9474322b556110502a4152f9b8da6b38 | 1,567 | hpp | C++ | .References/src/github.com/reinterpretcat/utymap_generative_3d_map/core/shared/Callbacks.hpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | .References/src/github.com/reinterpretcat/utymap_generative_3d_map/core/shared/Callbacks.hpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | .References/src/github.com/reinterpretcat/utymap_generative_3d_map/core/shared/Callbacks.hpp | roscopecoltran/SniperKit-Core | 4600dffe1cddff438b948b6c22f586d052971e04 | [
"MIT"
] | null | null | null | #ifndef CALLBACKS_HPP_DEFINED
#define CALLBACKS_HPP_DEFINED
#include <cstdint>
/// Callback which is called when directory should be created.
/// NOTE with C++11, directory cannot be created with header only libs.
typedef void OnNewDirectory(const char *path);
/// Callback which is called when mesh is built.
typedef void OnMeshBuilt(int tag, // a request tag
const char *name, // name
const double *vertices, int vertexSize, // vertices (x, y, elevation)
const int *triangles, int triSize, // triangle indices
const int *colors, int colorSize, // rgba colors
const double *uvs, int uvSize, // absolute texture uvs
const int *uvMap, int uvMapSize); // map with info about used atlas and texture region
/// Callback which is called when element is loaded.
typedef void OnElementLoaded(int tag, // a request tag
std::uint64_t id, // element id
const char **tags, int tagsSize, // tags
const double *vertices, int vertexSize, // vertices (x, y, elevation)
const char **style, int styleSize); // mapcss styles (key, value)
/// Callback which is called when error is occured.
typedef void OnError(const char *errorMessage);
#endif // CALLBACKS_HPP_DEFINED
| 52.233333 | 117 | 0.555201 | [
"mesh"
] |
123634b2c8366bc070f801b054fdd03c8f76dc72 | 6,572 | hpp | C++ | compression/src/tthresh/encode.hpp | shamanDevel/fV-SRN | 966926ee678a0db0f1c67661537c4bb7eec0c56f | [
"MIT"
] | 13 | 2021-12-06T05:08:09.000Z | 2022-03-07T15:11:06.000Z | compression/src/tthresh/encode.hpp | shamanDevel/fV-SRN | 966926ee678a0db0f1c67661537c4bb7eec0c56f | [
"MIT"
] | 1 | 2022-02-07T10:07:44.000Z | 2022-02-24T14:13:50.000Z | compression/src/tthresh/encode.hpp | shamanDevel/fV-SRN | 966926ee678a0db0f1c67661537c4bb7eec0c56f | [
"MIT"
] | 5 | 2021-12-13T07:02:23.000Z | 2022-01-12T15:46:44.000Z | /*
* Copyright (c) 2016-2017, Rafael Ballester-Ripoll
* (Visualization and MultiMedia Lab, University of Zurich),
* rballester@ifi.uzh.ch
*
* Licensed under the LGPLv3.0 (https://github.com/rballester/tthresh/blob/master/LICENSE)
*/
/*
The arithmetic loop (last part of this function) was provided by
https://marknelson.us/posts/2014/10/19/data-compression-with-arithmetic-coding.html
under the following MIT License:
Copyright (c) 2014 Mark Thomas Nelson
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.
*/
#ifndef __ENCODE_HPP__
#define __ENCODE_HPP__
#include "memtrace.h"
#include <map>
#include <iterator>
#include <vector>
#include "io.hpp"
//using namespace std;
static constexpr uint8_t CODE_VALUE_BITS = 32;
static constexpr uint64_t MAX_CODE = (1ULL<<CODE_VALUE_BITS)-1;
static constexpr uint64_t ONE_FOURTH = (MAX_CODE+1UL)/4;
static constexpr uint64_t ONE_HALF = ONE_FOURTH*2;
static constexpr uint64_t THREE_FOURTHS = ONE_FOURTH*3;
namespace tthresh
{
inline void put_bit(zs& zs, char bit) {
write_bits(zs, bit, 1);
}
inline void put_bit_plus_pending(zs& zs, bool bit, int& pending_bits)
{
put_bit(zs, bit);
for (int i = 0; i < pending_bits; i++)
put_bit(zs, !bit);
pending_bits = 0;
}
inline uint64_t encode(zs& zs, std::vector<uint64_t>& rle) {
// Build table of frequencies/probability intervals
// key -> (count, lower bound)
std::map<uint64_t, std::pair<uint64_t, uint64_t> > frequencies;
for (uint64_t i = 0; i < rle.size(); ++i)
++frequencies[rle[i]].first;
uint64_t count = 0;
for (std::map<uint64_t, std::pair<uint64_t, uint64_t> >::iterator it = frequencies.begin(); it != frequencies.end(); ++it) {
(it->second).second = count;
count += (it->second).first;
}
uint64_t encoding_bits = 0;
// open_wbit();
//*********
//********* Write frequencies
//*********
// Number of key/frequency pairs
uint64_t dict_size = frequencies.size();
write_bits(zs, dict_size, sizeof(uint64_t) * 8);
// cerr << "dict_size: " << dict_size << endl;
encoding_bits += sizeof(uint64_t) * 8;
// Key/code pairs
for (std::map<uint64_t, std::pair<uint64_t, uint64_t> >::iterator it = frequencies.begin(); it != frequencies.end(); ++it) {
uint64_t key = it->first;
uint64_t freq = (it->second).first;
// First, the key's length
int key_len = 0;
uint64_t key_copy = key;
while (key_copy) {
key_copy >>= 1;
key_len++;
}
key_len = std::max(1, key_len); // A 0 still requires 1 bit for us
write_bits(zs, key_len, 6);
// Next, the key itself
write_bits(zs, key, key_len);
// Now, the frequency's length
int freq_len = 0;
uint64_t freq_copy = freq;
while (freq_copy) {
freq_copy >>= 1;
freq_len++;
}
freq_len = std::max(1, freq_len); // A 0 still requires 1 bit for us
write_bits(zs, freq_len, 6);
// Finally, the frequency itself
write_bits(zs, freq, freq_len);
encoding_bits += 6 + key_len + 6 + freq_len;
}
// Number N of symbols to code
uint64_t n_symbols = rle.size();
write_bits(zs, n_symbols, sizeof(uint64_t) * 8);
encoding_bits += sizeof(uint64_t) * 8;
//*********
//********* Write the encoding
//*********
int pending_bits = 0;
uint64_t low = 0;
uint64_t high = MAX_CODE;
uint64_t rle_pos = 0;
for (; ; ) {
uint64_t c = rle[rle_pos];
rle_pos++;
uint64_t phigh = frequencies[c].second + frequencies[c].first;
uint64_t plow = frequencies[c].second;
uint64_t range = high - low + 1;
high = low + (range * phigh / n_symbols) - 1;
low = low + (range * plow / n_symbols);
for (; ; ) {
if (high < ONE_HALF) {
encoding_bits += pending_bits + 1;
put_bit_plus_pending(zs, 0, pending_bits);
}
else if (low >= ONE_HALF) {
encoding_bits += pending_bits + 1;
put_bit_plus_pending(zs, 1, pending_bits);
}
else if (low >= ONE_FOURTH && high < THREE_FOURTHS) {
pending_bits++;
low -= ONE_FOURTH;
high -= ONE_FOURTH;
}
else
break;
high <<= 1;
high++;
low <<= 1;
high &= MAX_CODE;
low &= MAX_CODE;
}
if (rle_pos == n_symbols)
break;
}
pending_bits++;
if (low < ONE_FOURTH) {
encoding_bits += pending_bits + 1;
put_bit_plus_pending(zs, 0, pending_bits);
}
else {
encoding_bits += pending_bits + 1;
put_bit_plus_pending(zs, 1, pending_bits);
}
write_bits(zs, 0UL, CODE_VALUE_BITS - 2); // Trailing zeros
encoding_bits += CODE_VALUE_BITS - 2;
// close_wbit();
return encoding_bits;
}
}
#endif // ENCODE_HPP
| 32.696517 | 132 | 0.565429 | [
"vector"
] |
72f3a16747c48a358e8d3e0671237a654a3797c5 | 609 | cpp | C++ | competitive/c++/codeforces/round 694 div 2/mainb.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | competitive/c++/codeforces/round 694 div 2/mainb.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | competitive/c++/codeforces/round 694 div 2/mainb.cpp | HackintoshwithUbuntu/BigRepo | 70746ddf7edc1ec9f13fe5f53a40eb4c3ebd2874 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
void solve() {
int n; cin >> n;
int x; cin >> x;
vector<int> a(n);
int ans = 0;
for(int i = 0; i < n; i++){
int y; cin >> y;
a[i] = y;
ans += y;
}
for(int i = 0; i < a.size(); i++){
if(a[i] % x == 0){
a.insert(a.end(), x, a[i] / x);
ans += a[i];
}
else break;
}
cout << ans << "\n";
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin >> t;
while(t--)
{
solve();
}
return 0;
} | 15.615385 | 43 | 0.37931 | [
"vector"
] |
f400df17001737560c138f4809cc91c43c7f0944 | 1,959 | cpp | C++ | Solutions/Problem_002.cpp | aviral19/daily-coding-problem | a4c3a0b820a41eaad785234551e757dcdfea2f4d | [
"MIT"
] | null | null | null | Solutions/Problem_002.cpp | aviral19/daily-coding-problem | a4c3a0b820a41eaad785234551e757dcdfea2f4d | [
"MIT"
] | null | null | null | Solutions/Problem_002.cpp | aviral19/daily-coding-problem | a4c3a0b820a41eaad785234551e757dcdfea2f4d | [
"MIT"
] | null | null | null | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define LOP(i,j,n) for(int i = j; i<n; i++)
#define MOD 1000000007
#define mp make_pair
#define pb push_back
#define FOREACH(it, l) for(auto it = l.begin(); it!= l.end(); it++)
// When Division is allowed
vector<int> productWithDivision(vector<int> a){
int n = a.size();
vector<int> res(n);
int lastnum = 1;
for(int i = 0; i<n-1; i++){
lastnum *= a[i]; // O(n) to get this
}
res[n-1] = lastnum;
for(int i = n-2; i>=0; i--){ // O(n) to fill this
res[i] = (res[i+1] * a[i+1])/a[i]; // Division is used here
}
return res;
}
// Follow up - When division is not allowed
vector<int> productWithoutDivision(vector<int> a){
int n = a.size();
vector<int> rightprod(n), leftprod(n);
leftprod[0] = a[0];
for(int i = 1; i<n;i++){
leftprod[i] = a[i] * leftprod[i-1]; // O(n) to fill this
}
rightprod[n-1] = a[n-1];
for(int i = n-2; i>=0; i--){
rightprod[i] = a[i] * rightprod[i+1]; // O(n) to fill this
}
vector<int> res(n);
for(int i = 1; i<n-1; i++){
res[i] = leftprod[i-1]*rightprod[i+1]; // O(n) to fill this
}
res[0] = rightprod[1];
res[n-1] = leftprod[n-2];
return res;
}
int main() {
vector<int> a1 = {1,2,3,4,5}, a2 = {3,2,1};
vector<int> res1, res2;
vector<int> res3, res4;
// Using with Division method
res1 = productWithDivision(a1);
for(int num : res1) cout << num << " ";
cout << endl;
res2 = productWithDivision(a2);
for(int num : res2) cout << num << " ";
cout << endl;
// Using without division method
res3 = productWithoutDivision(a1);
for(int num : res3) cout << num << " ";
cout << endl;
res4 = productWithoutDivision(a2);
for(int num : res4) cout << num << " ";
cout << endl;
} | 23.321429 | 72 | 0.529862 | [
"vector"
] |
f402147f1f7b285115d6242476cc3cb02abf820d | 1,376 | cpp | C++ | android-31/android/provider/ContactsContract_PinnedPositions.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 12 | 2020-03-26T02:38:56.000Z | 2022-03-14T08:17:26.000Z | android-31/android/provider/ContactsContract_PinnedPositions.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 1 | 2021-01-27T06:07:45.000Z | 2021-11-13T19:19:43.000Z | android-29/android/provider/ContactsContract_PinnedPositions.cpp | YJBeetle/QtAndroidAPI | 1468b5dc6eafaf7709f0b00ba1a6ec2b70684266 | [
"Apache-2.0"
] | 3 | 2021-02-02T12:34:55.000Z | 2022-03-08T07:45:57.000Z | #include "../content/ContentResolver.hpp"
#include "./ContactsContract_PinnedPositions.hpp"
namespace android::provider
{
// Fields
jint ContactsContract_PinnedPositions::DEMOTED()
{
return getStaticField<jint>(
"android.provider.ContactsContract$PinnedPositions",
"DEMOTED"
);
}
jint ContactsContract_PinnedPositions::UNPINNED()
{
return getStaticField<jint>(
"android.provider.ContactsContract$PinnedPositions",
"UNPINNED"
);
}
// QJniObject forward
ContactsContract_PinnedPositions::ContactsContract_PinnedPositions(QJniObject obj) : JObject(obj) {}
// Constructors
ContactsContract_PinnedPositions::ContactsContract_PinnedPositions()
: JObject(
"android.provider.ContactsContract$PinnedPositions",
"()V"
) {}
// Methods
void ContactsContract_PinnedPositions::pin(android::content::ContentResolver arg0, jlong arg1, jint arg2)
{
callStaticMethod<void>(
"android.provider.ContactsContract$PinnedPositions",
"pin",
"(Landroid/content/ContentResolver;JI)V",
arg0.object(),
arg1,
arg2
);
}
void ContactsContract_PinnedPositions::undemote(android::content::ContentResolver arg0, jlong arg1)
{
callStaticMethod<void>(
"android.provider.ContactsContract$PinnedPositions",
"undemote",
"(Landroid/content/ContentResolver;J)V",
arg0.object(),
arg1
);
}
} // namespace android::provider
| 24.571429 | 106 | 0.74564 | [
"object"
] |
f4035c239145bbc034bc0f2ad5909f1bf5be9ce3 | 412 | hh | C++ | tests/Titon/Common/StringableTest.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 206 | 2015-01-02T20:01:12.000Z | 2021-04-15T09:49:56.000Z | tests/Titon/Common/StringableTest.hh | ciklon-z/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 44 | 2015-01-02T06:03:43.000Z | 2017-11-20T18:29:06.000Z | tests/Titon/Common/StringableTest.hh | titon/framework | cbf44729173d3a83b91a2b0a217c6b3827512e44 | [
"BSD-2-Clause"
] | 27 | 2015-01-03T05:51:29.000Z | 2022-02-21T13:50:40.000Z | <?hh
namespace Titon\Common;
use Titon\Test\Stub\Common\StringableStub;
use Titon\Test\TestCase;
class StringableTest extends TestCase {
public function testToString(): void {
$object = new StringableStub();
$this->assertEquals('Titon\Test\Stub\Common\StringableStub', $object->toString());
$this->assertEquals('Titon\Test\Stub\Common\StringableStub', (string) $object);
}
}
| 24.235294 | 90 | 0.701456 | [
"object"
] |
f40689eaeb4748e7c8c110865640e1067803b832 | 2,272 | cpp | C++ | tools/aapt2/compile/XmlIdCollector.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | tools/aapt2/compile/XmlIdCollector.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | tools/aapt2/compile/XmlIdCollector.cpp | Keneral/aframeworksbase1 | 0287c3e3f6f763cd630290343cda11e15db1844f | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) 2015 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ResourceUtils.h"
#include "ResourceValues.h"
#include "compile/XmlIdCollector.h"
#include "xml/XmlDom.h"
#include <algorithm>
#include <vector>
namespace aapt {
namespace {
static bool cmpName(const SourcedResourceName& a, const ResourceNameRef& b) {
return a.name < b;
}
struct IdCollector : public xml::Visitor {
using xml::Visitor::visit;
std::vector<SourcedResourceName>* mOutSymbols;
IdCollector(std::vector<SourcedResourceName>* outSymbols) : mOutSymbols(outSymbols) {
}
void visit(xml::Element* element) override {
for (xml::Attribute& attr : element->attributes) {
ResourceNameRef name;
bool create = false;
if (ResourceUtils::tryParseReference(attr.value, &name, &create, nullptr)) {
if (create && name.type == ResourceType::kId) {
auto iter = std::lower_bound(mOutSymbols->begin(), mOutSymbols->end(),
name, cmpName);
if (iter == mOutSymbols->end() || iter->name != name) {
mOutSymbols->insert(iter, SourcedResourceName{ name.toResourceName(),
element->lineNumber });
}
}
}
}
xml::Visitor::visit(element);
}
};
} // namespace
bool XmlIdCollector::consume(IAaptContext* context, xml::XmlResource* xmlRes) {
xmlRes->file.exportedSymbols.clear();
IdCollector collector(&xmlRes->file.exportedSymbols);
xmlRes->root->accept(&collector);
return true;
}
} // namespace aapt
| 32 | 94 | 0.622799 | [
"vector"
] |
f40fba82f5ebf52ebb433a848827c06d1e885404 | 3,963 | cpp | C++ | src/app/IAPreferences.cpp | MatthiasWM/AllPlatformAppFLTK | 24054a8a494803ffae51cef7bdc5afb470c787eb | [
"MIT"
] | 12 | 2018-08-14T00:55:35.000Z | 2022-02-08T12:01:39.000Z | src/app/IAPreferences.cpp | MatthiasWM/AllPlatformAppFLTK | 24054a8a494803ffae51cef7bdc5afb470c787eb | [
"MIT"
] | 34 | 2018-09-17T08:02:42.000Z | 2018-10-17T22:56:23.000Z | src/app/IAPreferences.cpp | MatthiasWM/AllPlatformAppFLTK | 24054a8a494803ffae51cef7bdc5afb470c787eb | [
"MIT"
] | 9 | 2018-10-05T09:16:47.000Z | 2022-02-28T02:39:33.000Z | //
// IAPreferences.cpp
//
// Copyright (c) 2013-2018 Matthias Melcher. All rights reserved.
//
#include "IAPreferences.h"
#include "view/IAGUIMain.h"
#include <FL/Fl_Preferences.H>
/**
* Create the preferences interface an load the last settings.
*/
IAPreferences::IAPreferences()
{
char buf[FL_PATH_MAX];
Fl_Preferences pPrefs(Fl_Preferences::USER, "com.matthiasm.iota", "IotaSlicer");
buf[0] = 0;
pPrefs.getUserdataPath(buf, sizeof(buf));
strcat(buf, "printerDefinitions/");
pPrinterDefinitionsPath = strdup(buf);
Fl_Preferences main(pPrefs, "main");
Fl_Preferences window(main, "window");
window.get("x", pMainWindowX, -1);
window.get("y", pMainWindowY, -1);
window.get("w", pMainWindowW, 800);
window.get("h", pMainWindowH, 600);
Fl_Preferences recentFiles(main, "recentFiles");
for (int i=0; i<pNRecentFiles; i++) {
recentFiles.get(Fl_Preferences::Name(i), pRecentFile[i], "");
}
updateRecentfilesMenu();
main.get("recentPrinterIndex", pCurrentPrinterIndex, 0);
}
/**
* Write the current setting to the preferences file.
*/
IAPreferences::~IAPreferences()
{
flush();
if (pPrinterDefinitionsPath) ::free((void*)pPrinterDefinitionsPath);
}
/**
* Write the current setting to the preferences file.
*/
void IAPreferences::flush()
{
Fl_Preferences pPrefs(Fl_Preferences::USER, "com.matthiasm.iota", "IotaSlicer");
Fl_Preferences main(pPrefs, "main");
Fl_Preferences window(main, "window");
window.set("x", wMainWindow->x());
window.set("y", wMainWindow->y());
window.set("w", wMainWindow->w());
window.set("h", wMainWindow->h());
Fl_Preferences recentFiles(main, "recentFiles");
for (int i=0; i<pNRecentFiles; i++) {
recentFiles.set(Fl_Preferences::Name(i), pRecentFile[i]);
}
main.set("recentPrinterIndex", wPrinterChoice->value());
pPrefs.flush();
}
/**
* Update the main menu that shows all the recently loaded files.
*/
void IAPreferences::updateRecentfilesMenu()
{
auto menu = wRecentFiles;
int lastVisible = -1;
for (int i=0; i<pNRecentFiles; i++) {
if (pRecentFile[i] && pRecentFile[i][0]) {
menu->label(fl_filename_name(pRecentFile[i]));
menu->show();
menu->flags &= ~FL_MENU_DIVIDER;
lastVisible = i;
} else {
menu->label("");
menu->hide();
}
menu++;
}
if (lastVisible>=0) {
wRecentFiles[lastVisible].flags |= FL_MENU_DIVIDER;
}
}
/**
* Add another file to the list of recently opened files.
*
* \param[in] filename Add this file. We will always save the absolute path.
*/
void IAPreferences::addRecentFile(const char *filename)
{
if (!filename || !filename[0])
return;
char buf[FL_PATH_MAX];
fl_filename_absolute(buf, FL_PATH_MAX, filename);
int sameAs = pNRecentFiles;
for (int i=0; i<pNRecentFiles; i++) {
if (strcmp(pRecentFile[i], buf)==0) {
sameAs = i;
break;
}
}
char *first = nullptr;
if (sameAs==pNRecentFiles) {
first = strdup(buf);
::free((void*)pRecentFile[pNRecentFiles-1]);
sameAs--;
} else {
first = pRecentFile[sameAs];
}
for (int i=sameAs; i>0; i--) {
pRecentFile[i] = pRecentFile[i-1];
}
pRecentFile[0] = first;
updateRecentfilesMenu();
flush();
}
/**
* Clear all "Recent File" entries.
*/
void IAPreferences::clearRecentFileList()
{
for (int i=0; i<pNRecentFiles; i++) {
if (pRecentFile[i]) {
::free((void*)pRecentFile[i]);
}
pRecentFile[i] = strdup("");
}
updateRecentfilesMenu();
flush();
}
/**
* Get a file path for storing 3d printer definitions.
*
* \return path to a directory in the user data area.
*/
const char *IAPreferences::printerDefinitionsPath() const
{
return pPrinterDefinitionsPath;
}
| 23.311765 | 84 | 0.619228 | [
"3d"
] |
f41b630606bc51b427ad4f6d9fc8647832a3cae6 | 1,314 | cpp | C++ | metapushstream2/video/yangrecordthread.cpp | guoai2015/metaRTC | 70e9a09c9a703a547e791cd246c4054d87881f08 | [
"MIT"
] | 147 | 2021-09-12T07:23:45.000Z | 2021-11-11T11:31:26.000Z | metapushstream2/video/yangrecordthread.cpp | guoai2015/metaRTC | 70e9a09c9a703a547e791cd246c4054d87881f08 | [
"MIT"
] | 6 | 2021-11-30T07:53:09.000Z | 2022-02-25T01:36:38.000Z | metapushstream2/video/yangrecordthread.cpp | guoai2015/metaRTC | 70e9a09c9a703a547e791cd246c4054d87881f08 | [
"MIT"
] | 36 | 2021-09-13T06:24:20.000Z | 2021-11-12T10:23:54.000Z | #include "yangrecordthread.h"
#include <QDebug>
#include <QMapIterator>
YangRecordThread::YangRecordThread()
{
m_isLoop=0;
m_video=nullptr;
m_videoBuffer=nullptr;
m_bgColor={0,0,0};
m_textColor={0,0,255};
m_videoPlayNum=5;
m_sid=1;
showType=1;
m_isStart=0;
}
YangRecordThread::~YangRecordThread(){
m_video=nullptr;
m_videoBuffer=nullptr;
stopAll();
}
void YangRecordThread::stopAll(){
if(m_isLoop){
m_isLoop=0;
while (m_isStart) {
QThread::msleep(1);
}
}
closeAll();
}
void YangRecordThread::initPara(YangContext *pini){
m_para=pini;
m_videoPlayNum=pini->video.videoPlayCacheNum;
}
void YangRecordThread::closeAll(){
//clearRender();
}
void YangRecordThread::render(){
if(m_videoBuffer&&m_videoBuffer->size()>0){
uint8_t* t_vb=m_videoBuffer->getVideoRef(&m_frame);
if(t_vb&&m_video&&m_videoBuffer->m_width>0){
m_video->PlayOneFrame(t_vb,m_videoBuffer->m_width,m_videoBuffer->m_height);
}
t_vb=NULL;
}
}
void YangRecordThread::run(){
m_isLoop=1;
m_isStart=1;
while(m_isLoop){
QThread::msleep(20);
render();
}
m_isStart=0;
}
| 16.425 | 99 | 0.592846 | [
"render"
] |
f42abfbcbc3f31df9a51e3f2243eec937d0c9c83 | 813 | cpp | C++ | src/software/simulated_tests/terminating_validation_functions/robot_in_center_circle_validation.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/simulated_tests/terminating_validation_functions/robot_in_center_circle_validation.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | src/software/simulated_tests/terminating_validation_functions/robot_in_center_circle_validation.cpp | jonl112/Software | 61a028a98d5c0dd5e79bf055b231633290ddbf9f | [
"MIT"
] | null | null | null | #include "software/simulated_tests/terminating_validation_functions/robot_in_center_circle_validation.h"
#include "software/geom/algorithms/contains.h"
#include "software/logger/logger.h"
void robotInCenterCircle(std::shared_ptr<World> world_ptr,
ValidationCoroutine::push_type& yield)
{
auto robot_in_center_circle = [](std::shared_ptr<World> world_ptr) {
std::vector<Robot> robots = world_ptr->friendlyTeam().getAllRobots();
return std::any_of(robots.begin(), robots.end(), [world_ptr](Robot robot) {
Point position = robot.position();
return contains(world_ptr->field().centerCircle(), position);
});
};
while (!robot_in_center_circle(world_ptr))
{
yield("No robot has not entered the center circle");
}
}
| 36.954545 | 104 | 0.682657 | [
"vector"
] |
f42bd3edb229a7ebe3272d100a25ffeb0edaf5a5 | 2,232 | cpp | C++ | src/NULS/Signer.cpp | dinc334/wallet-core | b4502836c2bf7b6139868a22ab62ee894966f208 | [
"MIT"
] | 1 | 2020-09-18T14:15:09.000Z | 2020-09-18T14:15:09.000Z | src/NULS/Signer.cpp | dinc334/wallet-core | b4502836c2bf7b6139868a22ab62ee894966f208 | [
"MIT"
] | null | null | null | src/NULS/Signer.cpp | dinc334/wallet-core | b4502836c2bf7b6139868a22ab62ee894966f208 | [
"MIT"
] | 1 | 2019-09-21T18:07:59.000Z | 2019-09-21T18:07:59.000Z | // Copyright © 2017-2019 Trust Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Signer.h"
#include "Address.h"
#include "BinaryCoding.h"
#include "../Hash.h"
#include "../PrivateKey.h"
using namespace TW;
using namespace TW::NULS;
Signer::Signer(Proto::TransactionPlan& plan) : plan(plan) {
tx.set_amount(plan.amount());
tx.set_from_address(plan.from_address());
tx.set_to_address(plan.to_address());
tx.set_remark(plan.remark());
tx.set_timestamp(plan.timestamp());
*tx.mutable_inputs() = *plan.mutable_inputs();
*tx.mutable_outputs() = *plan.mutable_outputs();
}
Data Signer::sign() const {
if (plan.private_key().empty()) {
throw std::invalid_argument("Must have private key string");
} else if (tx.inputs_size() == 0) {
throw std::invalid_argument("Not enough input balance to do the transaction");
} else if (tx.outputs_size() == 0) {
throw std::invalid_argument("There must be at least one output, something is missed");
}
auto priv = Address::importHexPrivateKey(plan.private_key());
auto data = Data();
// Transaction Type
encode16LE(2, data);
// Timestamp
encode48LE(tx.timestamp(), data);
// Remark
std::string remark = tx.remark();
serializerRemark(remark, data);
// txData
encode32LE(0xffffffff, data);
// CoinData Input
std::vector<Proto::TransactionInput> inputs;
std::copy(tx.inputs().begin(), tx.inputs().end(), std::back_inserter(inputs));
serializerInput(inputs, data);
// CoinData Output
std::vector<Proto::TransactionOutput> outputs;
std::copy(tx.outputs().begin(), tx.outputs().end(), std::back_inserter(outputs));
serializerOutput(outputs, data);
// Calc transaction hash
Data txHash = calcTransactionDigest(data);
auto transactionSignature = makeTransactionSignature(priv, txHash);
encodeVarInt(transactionSignature.size(), data);
std::copy(transactionSignature.begin(), transactionSignature.end(), std::back_inserter(data));
return data;
}
| 33.818182 | 98 | 0.686828 | [
"vector"
] |
f42d67edfe899f8026281cd5379dcf7a93627448 | 22,376 | cpp | C++ | lib/transforms/xregPerspectiveXform.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 30 | 2020-09-29T18:36:13.000Z | 2022-03-28T09:25:13.000Z | lib/transforms/xregPerspectiveXform.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 3 | 2020-10-09T01:21:27.000Z | 2020-12-10T15:39:44.000Z | lib/transforms/xregPerspectiveXform.cpp | rg2/xreg | c06440d7995f8a441420e311bb7b6524452843d3 | [
"MIT"
] | 8 | 2021-05-25T05:14:48.000Z | 2022-02-26T12:29:50.000Z | /*
* MIT License
*
* Copyright (c) 2020 Robert Grupp
*
* 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 "xregPerspectiveXform.h"
#include <cmath>
#include <fmt/printf.h>
#include "xregRotUtils.h"
#include "xregRigidUtils.h"
#include "xregAssert.h"
std::tuple<xreg::Mat3x3,xreg::Mat4x4,xreg::CoordScalar>
xreg::DecompProjMat(const Mat3x4& P, const bool use_pos_rho)
{
using RowVec3 = Eigen::Matrix<CoordScalar,1,3>;
// We'll ask for thin U and V, therefore the matrix type must be dynamic
using JacSVD = Eigen::JacobiSVD<Eigen::Matrix<CoordScalar, Eigen::Dynamic, Eigen::Dynamic>>;
Mat3x3 K;
Mat4x4 T;
xregASSERT(std::abs(P.block(0,0,3,3).determinant()) > 1.0e-8);
const RowVec3 a1 = P.block(0, 0, 1, 3);
const RowVec3 a2 = P.block(1, 0, 1, 3);
const RowVec3 a3 = P.block(2, 0, 1, 3);
const CoordScalar rho = (use_pos_rho ? 1 : -1) / a3.norm();
const CoordScalar rho_sq = rho * rho;
const RowVec3 r3 = rho * a3;
const CoordScalar x0 = rho_sq * (a1.dot(a3));
const CoordScalar y0 = rho_sq * (a2.dot(a3));
const RowVec3 a1_x_a3 = a1.cross(a3);
const RowVec3 a2_x_a3 = a2.cross(a3);
const CoordScalar a1_x_a3_dot_a2_x_a3 = a1_x_a3.dot(a2_x_a3);
const CoordScalar a1_x_a3_norm = a1_x_a3.norm();
const CoordScalar a2_x_a3_norm = a2_x_a3.norm();
const RowVec3 r1 = a2_x_a3 / a2_x_a3_norm;
const RowVec3 r2 = r3.cross(r1);
Mat3x3 R;
R.block(0, 0, 1, 3) = r1;
R.block(1, 0, 1, 3) = r2;
R.block(2, 0, 1, 3) = r3;
// Make sure it's a rotation, these should only fail if the first 3x3 block
// is not invertible.
xregASSERT(std::abs(R.determinant() - 1) < 1.0e-4);
xregASSERT(((R.transpose() * R) - Mat3x3::Identity()).norm() < 1.0e-4);
CoordScalar sin_theta = 1;
CoordScalar cos_theta = 0;
if (std::abs(a1_x_a3_dot_a2_x_a3) > 1.0e-8)
{
// there is a shear
cos_theta = -a1_x_a3_dot_a2_x_a3 / (a1_x_a3_norm * a2_x_a3_norm);
sin_theta = std::sin(std::acos(cos_theta));
}
const CoordScalar alpha = rho_sq * a1_x_a3_norm * sin_theta;
// beta has the sin(theta) term, but later when populating the matrix we
// divide beta by sin(theta), so just leave it out here and not divide later.
const CoordScalar beta = rho_sq * a2_x_a3_norm; // * sin_theta;
K.setIdentity();
K(0,0) = alpha;
K(0,1) = -alpha * (cos_theta / sin_theta); // what I call gamma in Matlab
K(1,1) = beta;
K(0,2) = x0;
K(1,2) = y0;
T.setIdentity();
T.block(0, 0, 3, 3) = R;
JacSVD svd(K, Eigen::ComputeThinU | Eigen::ComputeThinV);
T.block(0, 3, 3, 1) = svd.solve(rho * P.block(0, 3, 3, 1));
return std::make_tuple(K,T,rho);
}
std::tuple<xreg::Mat3x3,xreg::Mat4x4,xreg::CoordScalar>
xreg::DecompProjMatQR(const Mat3x4& P)
{
// copied from my MATLAB implementation [K, H, rho] = cisDecompProjMatQR(M)
Mat3x3 perm = Mat3x3::Zero();
perm(0,2) = 1;
perm(1,1) = 1;
perm(2,0) = 1;
const Mat3x3 A = P.block(0,0,3,3).transpose() * perm;
xregASSERT(A.determinant() > 1.0e-8);
Eigen::HouseholderQR<Mat3x3> qr(A);
const Mat3x3 Q = qr.householderQ();
const Mat3x3 R = qr.matrixQR().triangularView<Eigen::Upper>();
Mat3x3 intrins = perm * R.transpose() * perm;
CoordScalar rho = intrins(2,2);
Mat3x3 rot_mat = perm * Q.transpose();
if (rot_mat.determinant() < 0)
{
// rotation matrix is actually a reflection; flip the direction of one column, guess which
// column to flip based on negative signs in intrins.
Mat3x3 N = Mat3x3::Identity();
if (intrins(0,0) < 0)
{
N(0,0) = -1;
}
else if (intrins(1,1) < 0)
{
N(1,1) = -1;
}
else
{
N(2,2) = -1;
}
intrins = intrins * N;
rot_mat = N * rot_mat;
}
// set rotation in extrinsic
Mat4x4 extrins = Mat4x4::Identity();
extrins.block(0,0,3,3) = rot_mat;
// recover translation
extrins.block(0,3,3,1) = intrins.jacobiSvd(Eigen::ComputeThinU|Eigen::ComputeThinV).solve(P.block(0,3,3,1));
// make sure the bottom right element of intrinsics is 1
intrins /= rho;
return std::make_tuple(intrins, extrins, rho);
}
xreg::CoordScalar xreg::FocalLenFromIntrins(const Mat3x3& K, CoordScalar xps, CoordScalar yps)
{
// Average of the focal lengths
return std::abs((K(0,0) * xps) + (K(1,1) * ((yps < 0) ? xps : yps))) * 0.5;
}
xreg::Mat3x4 xreg::ProjMat3x4FromIntrinsExtrins(const Mat3x3& intrins, const Mat4x4& extrins)
{
Mat3x4 K_aug = Mat3x4::Zero();
K_aug.block(0,0,3,3) = intrins;
return K_aug * extrins;
}
xreg::Mat3x3 xreg::MakeNaiveIntrins(const CoordScalar focal_len,
const unsigned long num_rows,
const unsigned long num_cols,
const CoordScalar pixel_row_spacing,
const CoordScalar pixel_col_spacing,
const bool z_is_neg)
{
xregASSERT(focal_len > CoordScalar(1.0e-8));
xregASSERT(num_rows && num_cols);
xregASSERT((pixel_row_spacing > CoordScalar(1.0e-8)) &&
(pixel_col_spacing > CoordScalar(1.0e-8)));
Mat3x3 intrins = Mat3x3::Identity();
intrins(0,0) = focal_len / pixel_col_spacing;
intrins(1,1) = focal_len / pixel_row_spacing;
// 2,2 is already one
if (z_is_neg)
{
intrins(0,0) *= -1;
intrins(1,1) *= -1;
}
// principal point is at the center pixel
intrins(0,2) = (num_cols - 1) * 0.5;
intrins(1,2) = (num_rows - 1) * 0.5;
return intrins;
}
void xreg::CameraModel::setup(const CoordScalar focal_len_arg, const size_type nr, const size_type nc,
const CoordScalar rs, const CoordScalar cs)
{
xregASSERT(focal_len_arg > CoordScalar(1.0e-8));
xregASSERT(nr && nc);
xregASSERT((rs > CoordScalar(1.0e-8)) && (cs > CoordScalar(1.0e-8)));
focal_len = focal_len_arg;
num_det_rows = nr;
num_det_cols = nc;
det_row_spacing = rs;
det_col_spacing = cs;
intrins = MakeNaiveIntrins(focal_len, num_det_rows, num_det_cols,
det_row_spacing, det_col_spacing,
coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z);
intrins_inv = intrins.inverse();
// no additional frame
extrins = FrameTransform::Identity();
extrins_inv = FrameTransform::Identity();
pinhole_pt = Pt3::Zero();
}
void xreg::CameraModel::setup(const Mat3x4& proj_mat, const size_type nr, const size_type nc,
const CoordScalar rs, const CoordScalar cs,
const bool use_extrins)
{
xregASSERT(nr && nc);
xregASSERT((rs > CoordScalar(1.0e-8)) && (cs > CoordScalar(1.0e-8)));
num_det_rows = nr;
num_det_cols = nc;
det_row_spacing = rs;
det_col_spacing = cs;
Mat4x4 extrins_mat;
std::tie(intrins,extrins_mat,std::ignore) = DecompProjMat(proj_mat,
(coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_POS_Z) ||
(coord_frame_type == kORIGIN_ON_DETECTOR));
focal_len = FocalLenFromIntrins(intrins, det_col_spacing, det_row_spacing);
intrins_inv = intrins.inverse();
if (use_extrins)
{
extrins.matrix() = extrins_mat;
}
else
{
extrins = FrameTransform::Identity();
}
extrins_inv.matrix() = SE3Inv(extrins.matrix());
if ((coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_POS_Z) ||
(coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z))
{
pinhole_pt = extrins_inv.matrix().block(0, 3, 3, 1);
}
else
{
Pt3 pinhole_wrt_cam = Pt3::Zero();
pinhole_wrt_cam(2) = focal_len;
pinhole_pt = extrins_inv * pinhole_wrt_cam;
}
}
void xreg::CameraModel::setup(const Mat3x3& intrins_mat, const Mat4x4& extrins_mat,
const size_type nr, const size_type nc,
const CoordScalar rs, const CoordScalar cs)
{
xregASSERT(nr && nc);
xregASSERT((rs > CoordScalar(1.0e-8)) && (cs > CoordScalar(1.0e-8)));
num_det_rows = nr;
num_det_cols = nc;
det_row_spacing = rs;
det_col_spacing = cs;
intrins = intrins_mat;
intrins_inv = intrins.inverse();
focal_len = FocalLenFromIntrins(intrins, det_col_spacing, det_row_spacing);
extrins = extrins_mat;
extrins_inv.matrix() = SE3Inv(extrins.matrix());
if ((coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_POS_Z) ||
(coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z))
{
pinhole_pt = extrins_inv.matrix().block(0, 3, 3, 1);
}
else
{
Pt3 pinhole_wrt_cam = Pt3::Zero();
pinhole_wrt_cam(2) = focal_len;
pinhole_pt = extrins_inv * pinhole_wrt_cam;
}
}
xreg::Pt3 xreg::CameraModel::proj_pt_to_det_pt(const Pt3& src_pt) const
{
return ind_pt_to_phys_det_pt(phys_pt_to_ind_pt(src_pt));
}
xreg::Pt3List xreg::CameraModel::proj_pts_to_det(const Pt3List& src_pts) const
{
const size_type num_pts = src_pts.size();
Pt3List pts_on_det(num_pts);
for (size_type pt_idx = 0; pt_idx < num_pts; ++pt_idx)
{
pts_on_det[pt_idx] = proj_pt_to_det_pt(src_pts[pt_idx]);
}
return pts_on_det;
}
xreg::Pt3 xreg::CameraModel::phys_pt_to_ind_pt(const Pt3& phys_pt) const
{
Pt3 idx;
if ((coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_POS_Z) ||
(coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z))
{
idx = intrins * (extrins * phys_pt);
}
else
{
Pt3 p = extrins * phys_pt;
p(2) = focal_len - p(2);
idx = intrins * p;
}
idx /= idx[2]; // normalize for homogeneous continuous index
return idx;
}
xreg::Pt3List xreg::CameraModel::phys_pts_to_ind_pts(const Pt3List& phys_pts) const
{
const size_type num_pts = phys_pts.size();
Pt3List idx_pts(num_pts);
for (size_type pt_idx = 0; pt_idx < num_pts; ++pt_idx)
{
idx_pts[pt_idx] = phys_pt_to_ind_pt(phys_pts[pt_idx]);
}
return idx_pts;
}
xreg::Pt3 xreg::CameraModel::ind_pt_to_phys_det_pt(const Pt2& ind_pt) const
{
Pt3 ind_pt3D;
ind_pt3D(0) = ind_pt(0);
ind_pt3D(1) = ind_pt(1);
ind_pt3D(2) = 1;
return ind_pt_to_phys_det_pt(ind_pt3D);
}
xreg::Pt3 xreg::CameraModel::ind_pt_to_phys_det_pt(const Pt3& ind_pt) const
{
// When the camera coordinate frame origin is on the detector, then we need
// to subtract [0;0;focal_len] after multiplying by the inverse intrinsic.
Pt3 z_adjust = Pt3::Zero();
if (coord_frame_type == kORIGIN_ON_DETECTOR)
{
z_adjust(2) = -focal_len;
}
const CoordScalar det_z_val = ((coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z) ? -1 : 1) * focal_len;
return extrins_inv * ((intrins_inv * (det_z_val * ind_pt)) + z_adjust);
}
xreg::Pt3List xreg::CameraModel::ind_pts_to_phys_det_pts(const Pt3List& ind_pts) const
{
const size_type num_pts = ind_pts.size();
Pt3List phys_det_pts(num_pts);
for (size_type pt_idx = 0; pt_idx < num_pts; ++pt_idx)
{
phys_det_pts[pt_idx] = ind_pt_to_phys_det_pt(ind_pts[pt_idx]);
}
return phys_det_pts;
}
bool xreg::CameraModel::operator==(const CameraModel& other) const
{
return (num_det_cols == other.num_det_cols) &&
(num_det_rows == other.num_det_rows) &&
(coord_frame_type == other.coord_frame_type) &&
(std::abs(det_row_spacing - other.det_row_spacing) < 1.0e-6) &&
(std::abs(det_col_spacing - other.det_col_spacing) < 1.0e-6) &&
(std::abs(focal_len - other.focal_len) < 1.0e-6) &&
((intrins - other.intrins).norm() < 1.0e-6) &&
((extrins.matrix() - other.extrins.matrix()).norm() < 1.0e-6);
}
bool xreg::CameraModel::operator!=(const CameraModel& other) const
{
return !operator==(other);
}
xreg::CameraModel::Point3DGrid xreg::CameraModel::detector_grid() const
{
Point3DGrid detector_pts(num_det_rows, num_det_cols);
// for each pixel index find the location of the pixel on the detector plane
// in "world" coordinates
// When the camera coordinate frame origin is on the detector, then we need
// to subtract [0;0;focal_len] after multiplying by the inverse intrinsic.
Pt3 z_adjust = Pt3::Zero();
if (coord_frame_type == kORIGIN_ON_DETECTOR)
{
z_adjust(2) = -focal_len;
}
const CoordScalar det_z_val = ((coord_frame_type == kORIGIN_AT_FOCAL_PT_DET_NEG_Z) ? -1 : 1) * focal_len;
Pt3 tmp_det_idx = Pt3::Zero();
tmp_det_idx[2] = det_z_val;
for (size_type det_row_idx = 0; det_row_idx < num_det_rows; ++det_row_idx)
{
tmp_det_idx[1] = det_row_idx * det_z_val;
for (size_type det_col_idx = 0; det_col_idx < num_det_cols; ++det_col_idx)
{
tmp_det_idx[0] = det_col_idx * det_z_val;
detector_pts(det_row_idx, det_col_idx) = extrins_inv * ((intrins_inv * tmp_det_idx) + z_adjust);
}
}
return detector_pts;
}
xreg::CameraModel xreg::UpdateCameraModelFor2DROI(const CameraModel& src_cam,
const int roi_start_col,
const int roi_start_row,
const int roi_end_col,
const int roi_end_row)
{
xregASSERT((roi_end_col > roi_start_col) && (roi_end_row > roi_start_row));
CameraModel dst_cam;
dst_cam.coord_frame_type = src_cam.coord_frame_type;
Mat3x3 dst_intrins = src_cam.intrins;
dst_intrins(0,2) -= CoordScalar(roi_start_col);
dst_intrins(1,2) -= CoordScalar(roi_start_row);
dst_cam.setup(dst_intrins, src_cam.extrins.matrix(),
roi_end_row - roi_start_row + 1,
roi_end_col - roi_start_col + 1,
src_cam.det_row_spacing, src_cam.det_col_spacing);
return dst_cam;
}
std::tuple<xreg::Pt2,xreg::Pt2>
xreg::GetBoundingBox2DProjPts(const CameraModel& cam, const Pt3List& pts_3d)
{
Pt2 top_left;
Pt2 bot_right;
const size_type num_pts = pts_3d.size();
CoordScalar& min_c = top_left[0];
CoordScalar& min_r = top_left[1];
CoordScalar& max_c = bot_right[0];
CoordScalar& max_r = bot_right[1];
min_c = std::numeric_limits<CoordScalar>::max();
min_r = std::numeric_limits<CoordScalar>::max();
max_c = std::numeric_limits<CoordScalar>::lowest();
max_r = std::numeric_limits<CoordScalar>::lowest();
Pt3 proj_pt;
for (size_type pt_idx = 0; pt_idx < num_pts; ++pt_idx)
{
proj_pt = cam.phys_pt_to_ind_pt(pts_3d[pt_idx]);
min_c = std::min(min_c, proj_pt[0]);
max_c = std::max(max_c, proj_pt[0]);
min_r = std::min(min_r, proj_pt[1]);
max_r = std::max(max_r, proj_pt[1]);
}
return std::make_tuple(top_left, bot_right);
}
xreg::CameraModel xreg::UpdateCameraModelTightBoundsForProjPts(const CameraModel& cam,
const Pt3List& pts_3d,
const CoordScalar pad_cols,
const CoordScalar pad_rows)
{
Pt2 top_left;
Pt2 bot_right;
std::tie(top_left,bot_right) = GetBoundingBox2DProjPts(cam, pts_3d);
CoordScalar min_c = top_left[0] - pad_cols;
CoordScalar max_c = bot_right[0] + pad_cols;
CoordScalar min_r = top_left[1] - pad_rows;
CoordScalar max_r = bot_right[1] + pad_rows;
// clamp to original image bounds
min_c = std::max(CoordScalar(0), std::floor(min_c));
min_r = std::max(CoordScalar(0), std::floor(min_r));
max_c = std::min(CoordScalar(cam.num_det_cols - 1), std::ceil(max_c));
min_r = std::min(CoordScalar(cam.num_det_rows - 1), std::ceil(max_r));
return UpdateCameraModelFor2DROI(cam,
static_cast<size_type>(min_c),
static_cast<size_type>(min_r),
static_cast<size_type>(max_c),
static_cast<size_type>(max_r));
}
xreg::CameraModel xreg::MoveFocalPointUpdateCam(const CameraModel& cam,
const Pt3 src_delta)
{
// No support for skewed cameras yet.
xregASSERT(std::abs(cam.intrins(0,1)) < 1.0e-6);
// Need to perform translations in the opposite directions for extrinsics
// so objects stay in the same relative location with respect to the detector
Pt3 extrins_trans;
extrins_trans(0) = -src_delta(0);
extrins_trans(1) = -src_delta(1);
const CoordScalar col_spacing = cam.det_col_spacing;
const CoordScalar row_spacing = cam.det_row_spacing;
Mat3x3 new_intrins = cam.intrins;
// X and Y cause the principal point to translate
new_intrins(0,2) += src_delta(0) / col_spacing;
new_intrins(1,2) += src_delta(1) / row_spacing;
// Z causes the focal length to change
CoordScalar new_focal_len = cam.focal_len;
if (cam.coord_frame_type == CameraModel::kORIGIN_AT_FOCAL_PT_DET_POS_Z)
{
new_focal_len -= src_delta(2);
extrins_trans(2) = -src_delta(2);
}
else
{
new_focal_len += src_delta(2);
if (cam.coord_frame_type == CameraModel::kORIGIN_AT_FOCAL_PT_DET_NEG_Z)
{
extrins_trans(2) = src_delta(2);
}
else
{
extrins_trans(2) = 0;
}
}
new_intrins(0,0) = new_focal_len / col_spacing;
new_intrins(1,1) = new_focal_len / row_spacing;
if (cam.coord_frame_type == CameraModel::kORIGIN_AT_FOCAL_PT_DET_NEG_Z)
{
new_intrins(0,0) *= -1;
new_intrins(1,1) *= -1;
}
const Mat4x4 new_extrins = TransXYZ4x4(extrins_trans) * cam.extrins.matrix();
CameraModel new_cam;
new_cam.coord_frame_type = cam.coord_frame_type;
new_cam.setup(new_intrins, new_extrins, cam.num_det_rows, cam.num_det_cols,
row_spacing, col_spacing);
return new_cam;
}
xreg::Pt3 xreg::CalcSourcePositionDelta(const CameraModel& cam1, const CameraModel& cam2)
{
xregASSERT(std::abs(cam1.intrins(0,1)) < 1.0e-6); // no skew
xregASSERT(std::abs(cam2.intrins(0,1)) < 1.0e-6); // no skew
xregASSERT(cam1.coord_frame_type == cam2.coord_frame_type);
Pt3 delta_cam1_src = Pt3::Zero();
delta_cam1_src(0) = (cam2.intrins(0,2) * cam2.det_col_spacing) -
(cam1.intrins(0,2) * cam1.det_col_spacing);
delta_cam1_src(1) = (cam2.intrins(1,2) * cam2.det_row_spacing) -
(cam1.intrins(1,2) * cam1.det_row_spacing);
delta_cam1_src(2) = cam1.focal_len - cam2.focal_len;
if ((cam1.coord_frame_type == CameraModel::kORIGIN_AT_FOCAL_PT_DET_NEG_Z) ||
(cam1.coord_frame_type == CameraModel::kORIGIN_ON_DETECTOR))
{
delta_cam1_src(2) *= -1;
}
return delta_cam1_src;
}
xreg::CameraModel xreg::DownsampleCameraModel(const CameraModel& src_cam, const CoordScalar ds_factor,
const bool force_even_dims)
{
CameraModel dst_cam;
dst_cam.coord_frame_type = src_cam.coord_frame_type;
auto intrins = src_cam.intrins;
intrins(0,0) *= ds_factor;
intrins(1,1) *= ds_factor;
intrins(0,2) *= ds_factor;
intrins(1,2) *= ds_factor;
long num_ds_rows = std::lround(src_cam.num_det_rows * ds_factor);
long num_ds_cols = std::lround(src_cam.num_det_cols * ds_factor);
if (force_even_dims)
{
if (num_ds_rows % 2)
{
--num_ds_rows;
}
if (num_ds_cols % 2)
{
--num_ds_cols;
}
}
dst_cam.setup(intrins, src_cam.extrins.matrix(),
num_ds_rows, num_ds_cols,
src_cam.det_row_spacing / ds_factor,
src_cam.det_col_spacing / ds_factor);
return dst_cam;
}
std::vector<xreg::CameraModel>
xreg::CreateCameraWorldUsingFiducial(const std::vector<CameraModel>& orig_cams,
const std::vector<FrameTransform>& cams_to_fid)
{
const size_type num_cams = orig_cams.size();
std::vector<CameraModel> dst_cams(num_cams);
for (size_type i = 0; i < num_cams; ++i)
{
const CameraModel& src_cam = orig_cams[i];
CameraModel& dst_cam = dst_cams[i];
dst_cam.coord_frame_type = src_cam.coord_frame_type;
dst_cam.setup(src_cam.intrins,
(src_cam.extrins * cams_to_fid[i].inverse()).matrix(),
src_cam.num_det_rows, src_cam.num_det_rows,
src_cam.det_row_spacing, src_cam.det_col_spacing);
}
return dst_cams;
}
void xreg::PrintCam(std::ostream& out, const CameraModel& cam)
{
std::string coord_frame_str;
switch (cam.coord_frame_type)
{
case CameraModel::kORIGIN_AT_FOCAL_PT_DET_POS_Z:
coord_frame_str = "origin at pinhole, z axis towards detector";
break;
case CameraModel::kORIGIN_AT_FOCAL_PT_DET_NEG_Z:
coord_frame_str = "origin at pinhole, z axis away from detector";
break;
case CameraModel::kORIGIN_ON_DETECTOR:
coord_frame_str = "origin on detector, z axis away from detector";
break;
default:
coord_frame_str = "unknown";
break;
}
out << fmt::sprintf(" num rows: %lu\n"
" num cols: %lu\n"
" row spacing: %7.4f\n"
" col spacing: %7.4f\n"
"focal length: %7.4f\n"
" pinhole: [%+12.4f , %+12.4f , %+12.4f]\n"
"coord. frame: %s\n",
cam.num_det_rows, cam.num_det_cols,
cam.det_row_spacing, cam.det_col_spacing,
cam.focal_len,
cam.pinhole_pt[0], cam.pinhole_pt[1], cam.pinhole_pt[2],
coord_frame_str);
out << "intrins:\n" << cam.intrins
<< "\nextrins:\n" << cam.extrins.matrix()
<< std::endl;
}
| 30.360923 | 110 | 0.646049 | [
"vector"
] |
f434bf4ab1cdf823f57a008d4e26e0fa8c46a5ca | 2,466 | hpp | C++ | src/PCVR_Scene.hpp | InnovativeDigitalSolution/NASA_PointCloudsVR | d837bfa1b742ece464f7cd9173634e4ba93279ce | [
"NASA-1.3"
] | 57 | 2019-12-26T20:31:36.000Z | 2022-02-27T04:02:20.000Z | src/PCVR_Scene.hpp | InnovativeDigitalSolution/NASA_PointCloudsVR | d837bfa1b742ece464f7cd9173634e4ba93279ce | [
"NASA-1.3"
] | null | null | null | src/PCVR_Scene.hpp | InnovativeDigitalSolution/NASA_PointCloudsVR | d837bfa1b742ece464f7cd9173634e4ba93279ce | [
"NASA-1.3"
] | 5 | 2020-02-01T22:26:25.000Z | 2021-07-24T10:40:05.000Z | #pragma once
#include <queue>
#include <osg/ArgumentParser>
#include <osg/ref_ptr>
#include <openvr.h>
#include <OpenFrames/CurveArtist.hpp>
#include <OpenFrames/DrawableTrajectory.hpp>
#include <OpenFrames/OpenVRDevice.hpp>
#include <OpenFrames/QWidgetPanel.hpp>
#include <OpenFrames/ReferenceFrame.hpp>
#include <OpenFrames/ReferenceFrame.hpp>
#include <OpenFrames/WindowProxy.hpp>
#include <QApplication>
#include "json.hpp"
#include "PCVR_Controller.hpp"
#include "PCVR_Selection.hpp"
#include "PCVR_Tool.hpp"
#include "PCVR_Trackball.hpp"
class PCVR_Scene : public QObject
{
Q_OBJECT
// Function Prototypes for Event Callbacks
friend void keyPressCallback(unsigned int *winID,
unsigned int *row, unsigned int *col, int *key);
friend void vrEventCallback(unsigned int *winID,
unsigned int *row, unsigned int *col, const OpenFrames::OpenVREvent *vrEvent);
public:
PCVR_Scene();
// Main public interface
virtual void parseArgs(osg::ArgumentParser& args);
virtual void initWindowAndVR();
virtual void buildScene();
virtual void run();
// Create laser-triggered GUI panels for the VR world
osg::ref_ptr<OpenFrames::QWidgetPanel> buildQtPanel(const std::string &name, const std::string &uiFile,
QWidget* &panelWidget);
static PCVR_Scene* Instance;
std::string _sceneType;
static osg::ref_ptr<OpenFrames::FrameManager> GetFrameManager();
osg::ref_ptr<OpenFrames::WindowProxy> getWinProxy() const;
osg::ref_ptr<OpenFrames::ReferenceFrame> getRootFrame() const;
osg::ref_ptr<PCVR_Trackball> _pcvrTrackball;
osg::ref_ptr<OpenFrames::OpenVRDevice> _ovrDevice;
osg::ref_ptr<OpenFrames::WindowProxy> _windowProxy;
protected:
// Arguments
bool _useVR;
unsigned int _winRes = 600;
std::vector<std::string> _dataPaths;
// OpenFrames
static osg::ref_ptr<OpenFrames::FrameManager> _FM;
osg::ref_ptr<OpenFrames::ReferenceFrame> _rootFrame;
osg::ref_ptr<OpenFrames::View> _mainView;
QApplication* _app;
std::string _uiFilePath = ":Qt/menu/default.ui";
bool _paused = false;
PCVR_Tool* _currentTool = nullptr;
std::queue<vr::VREvent_t> _eventQueue;
std::vector<PCVR_Selectable*> _selectables;
virtual void setupMenuEventListeners(PCVR_Controller* controller);
virtual void switchToolTo(PCVR_Tool* t);
virtual void handleVREvent(const vr::VREvent_t& ovrEvent);
virtual void showSkyBox(bool b);
virtual void step(OpenFrames::FramerateLimiter& waitLimiter);
void saveProjectFile();
virtual nlohmann::json& toJson();
}; | 28.344828 | 104 | 0.773317 | [
"vector"
] |
f436ecfcfd7593baf1564b8b8702bcc2bd82329b | 24,857 | cxx | C++ | cupsfilters/pdftopdf/qpdf-pdftopdf-processor.cxx | thakan25/cups-filters | e496badbf23d4d4215b542d5e73f931c8d9bcf73 | [
"Apache-2.0"
] | null | null | null | cupsfilters/pdftopdf/qpdf-pdftopdf-processor.cxx | thakan25/cups-filters | e496badbf23d4d4215b542d5e73f931c8d9bcf73 | [
"Apache-2.0"
] | null | null | null | cupsfilters/pdftopdf/qpdf-pdftopdf-processor.cxx | thakan25/cups-filters | e496badbf23d4d4215b542d5e73f931c8d9bcf73 | [
"Apache-2.0"
] | null | null | null | #include "qpdf-pdftopdf-processor-private.h"
#include <stdio.h>
#include <stdarg.h>
#include <assert.h>
#include <stdexcept>
#include <qpdf/QPDFWriter.hh>
#include <qpdf/QUtil.hh>
#include <qpdf/QPDFPageDocumentHelper.hh>
#include <qpdf/QPDFAcroFormDocumentHelper.hh>
#include "qpdf-tools-private.h"
#include "qpdf-xobject-private.h"
#include "qpdf-pdftopdf-private.h"
#include "pdftopdf-private.h"
// Use: content.append(debug_box(pe.sub,xpos,ypos));
static std::string debug_box(const _cfPDFToPDFPageRect &box,float xshift,float yshift) // {{{
{
return std::string("q 1 w 0.1 G\n ")+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" m "+
QUtil::double_to_string(box.right+xshift)+" "+QUtil::double_to_string(box.top+yshift)+" l "+"S \n "+
QUtil::double_to_string(box.right+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" m "+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.top+yshift)+" l "+"S \n "+
QUtil::double_to_string(box.left+xshift)+" "+QUtil::double_to_string(box.bottom+yshift)+" "+
QUtil::double_to_string(box.right-box.left)+" "+QUtil::double_to_string(box.top-box.bottom)+" re "+"S Q\n";
}
// }}}
_cfPDFToPDFQPDFPageHandle::_cfPDFToPDFQPDFPageHandle(QPDFObjectHandle page,int orig_no) // {{{
: page(page),
no(orig_no),
rotation(ROT_0)
{
}
// }}}
_cfPDFToPDFQPDFPageHandle::_cfPDFToPDFQPDFPageHandle(QPDF *pdf,float width,float height) // {{{
: no(0),
rotation(ROT_0)
{
assert(pdf);
page=QPDFObjectHandle::parse(
"<<"
" /Type /Page"
" /Resources <<"
" /XObject null "
" >>"
" /MediaBox null "
" /Contents null "
">>");
page.replaceKey("/MediaBox",_cfPDFToPDFMakeBox(0,0,width,height));
page.replaceKey("/Contents",QPDFObjectHandle::newStream(pdf));
// xobjects: later (in get())
content.assign("q\n"); // TODO? different/not needed
page=pdf->makeIndirectObject(page); // stores *pdf
}
// }}}
// Note: _cfPDFToPDFProcessor always works with "/Rotate"d and "/UserUnit"-scaled pages/coordinates/..., having 0,0 at left,bottom of the TrimBox
_cfPDFToPDFPageRect _cfPDFToPDFQPDFPageHandle::get_rect() const // {{{
{
page.assertInitialized();
_cfPDFToPDFPageRect ret=_cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
ret.translate(-ret.left,-ret.bottom);
ret.rotate_move(_cfPDFToPDFGetRotate(page),ret.width,ret.height);
ret.scale(_cfPDFToPDFGetUserUnit(page));
return ret;
}
// }}}
bool _cfPDFToPDFQPDFPageHandle::is_existing() const // {{{
{
page.assertInitialized();
return content.empty();
}
// }}}
QPDFObjectHandle _cfPDFToPDFQPDFPageHandle::get() // {{{
{
QPDFObjectHandle ret=page;
if (!is_existing()) { // finish up page
page.getKey("/Resources").replaceKey("/XObject",QPDFObjectHandle::newDictionary(xobjs));
content.append("Q\n");
page.getKey("/Contents").replaceStreamData(content,QPDFObjectHandle::newNull(),QPDFObjectHandle::newNull());
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(rotation));
} else {
pdftopdf_rotation_e rot=_cfPDFToPDFGetRotate(page)+rotation;
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(rot));
}
page=QPDFObjectHandle(); // i.e. uninitialized
return ret;
}
// }}}
// TODO: we probably need a function "ungetRect()" to transform to page/form space
// TODO: as member
static _cfPDFToPDFPageRect ungetRect(_cfPDFToPDFPageRect rect,const _cfPDFToPDFQPDFPageHandle &ph,pdftopdf_rotation_e rotation,QPDFObjectHandle page)
{
_cfPDFToPDFPageRect pg1=ph.get_rect();
_cfPDFToPDFPageRect pg2=_cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
// we have to invert /Rotate, /UserUnit and the left,bottom (TrimBox) translation
//_cfPDFToPDFRotationDump(rotation);
//_cfPDFToPDFRotationDump(_cfPDFToPDFGetRotate(page));
rect.width=pg1.width;
rect.height=pg1.height;
//std::swap(rect.width,rect.height);
//rect.rotate_move(-rotation,rect.width,rect.height);
rect.rotate_move(-_cfPDFToPDFGetRotate(page),pg1.width,pg1.height);
rect.scale(1.0/_cfPDFToPDFGetUserUnit(page));
// _cfPDFToPDFPageRect pg2=_cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
rect.translate(pg2.left,pg2.bottom);
//rect.dump();
return rect;
}
// TODO FIXME rotations are strange ... (via ungetRect)
// TODO? for non-existing (either drop comment or facility to create split streams needed)
void _cfPDFToPDFQPDFPageHandle::add_border_rect(const _cfPDFToPDFPageRect &_rect,pdftopdf_border_type_e border,float fscale) // {{{
{
assert(is_existing());
assert(border!=pdftopdf_border_type_e::NONE);
// straight from pstops
const double lw=(border&THICK)?0.5:0.24;
double line_width=lw*fscale;
double margin=2.25*fscale;
// (PageLeft+margin,PageBottom+margin) rect (PageRight-PageLeft-2*margin,...) ... for nup>1: PageLeft=0,etc.
// if (double) margin+=2*fscale ...rect...
_cfPDFToPDFPageRect rect=ungetRect(_rect,*this,rotation,page);
assert(rect.left<=rect.right);
assert(rect.bottom<=rect.top);
std::string boxcmd="q\n";
boxcmd+=" "+QUtil::double_to_string(line_width)+" w 0 G \n";
boxcmd+=" "+QUtil::double_to_string(rect.left+margin)+" "+QUtil::double_to_string(rect.bottom+margin)+" "+
QUtil::double_to_string(rect.right-rect.left-2*margin)+" "+QUtil::double_to_string(rect.top-rect.bottom-2*margin)+" re S \n";
if (border&TWO) {
margin+=2*fscale;
boxcmd+=" "+QUtil::double_to_string(rect.left+margin)+" "+QUtil::double_to_string(rect.bottom+margin)+" "+
QUtil::double_to_string(rect.right-rect.left-2*margin)+" "+QUtil::double_to_string(rect.top-rect.bottom-2*margin)+" re S \n";
}
boxcmd+="Q\n";
// if (!is_existing()) {
// // TODO: only after
// return;
// }
assert(page.getOwningQPDF()); // existing pages are always indirect
#ifdef DEBUG // draw it on top
static const char *pre="%pdftopdf q\n"
"q\n",
*post="%pdftopdf Q\n"
"Q\n";
QPDFObjectHandle stm1=QPDFObjectHandle::newStream(page.getOwningQPDF(),pre),
stm2=QPDFObjectHandle::newStream(page.getOwningQPDF(),std::string(post)+boxcmd);
page.addPageContents(stm1,true); // before
page.addPageContents(stm2,false); // after
#else
QPDFObjectHandle stm=QPDFObjectHandle::newStream(page.getOwningQPDF(),boxcmd);
page.addPageContents(stm,true); // before
#endif
}
// }}}
/*
* This crop function is written for print-scaling=fill option.
* Trim Box is used for trimming the page in required size.
* scale tells if we need to scale input file.
*/
pdftopdf_rotation_e _cfPDFToPDFQPDFPageHandle::crop(const _cfPDFToPDFPageRect &cropRect,pdftopdf_rotation_e orientation,pdftopdf_rotation_e param_orientation,pdftopdf_position_e xpos,pdftopdf_position_e ypos,bool scale,bool autorotate,pdftopdf_doc_t *doc)
{
page.assertInitialized();
pdftopdf_rotation_e save_rotate = _cfPDFToPDFGetRotate(page);
if(orientation==ROT_0||orientation==ROT_180)
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(ROT_90));
else
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(ROT_0));
_cfPDFToPDFPageRect currpage= _cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
double width = currpage.right-currpage.left;
double height = currpage.top-currpage.bottom;
double pageWidth = cropRect.right-cropRect.left;
double pageHeight = cropRect.top-cropRect.bottom;
double final_w,final_h; //Width and height of cropped image.
pdftopdf_rotation_e pageRot = _cfPDFToPDFGetRotate(page);
if ((autorotate &&
(((pageRot == ROT_0 || pageRot == ROT_180) &&
pageWidth <= pageHeight) ||
((pageRot == ROT_90 || pageRot == ROT_270) &&
pageWidth > pageHeight))) ||
(!autorotate &&
(param_orientation == ROT_90 || param_orientation == ROT_270)))
{
std::swap(pageHeight,pageWidth);
}
if(scale)
{
if(width*pageHeight/pageWidth<=height)
{
final_w = width;
final_h = width*pageHeight/pageWidth;
}
else{
final_w = height*pageWidth/pageHeight;
final_h = height;
}
}
else
{
final_w = pageWidth;
final_h = pageHeight;
}
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_DEBUG,
"cfFilterPDFToPDF: After Cropping: %lf %lf %lf %lf",
width,height,final_w,final_h);
double posw = (width-final_w)/2,
posh = (height-final_h)/2;
// posw, posh : pdftopdf_position_e along width and height respectively.
// Calculating required position.
if(xpos==pdftopdf_position_e::LEFT)
posw =0;
else if(xpos==pdftopdf_position_e::RIGHT)
posw*=2;
if(ypos==pdftopdf_position_e::TOP)
posh*=2;
else if(ypos==pdftopdf_position_e::BOTTOM)
posh=0;
// making _cfPDFToPDFPageRect for cropping.
currpage.left += posw;
currpage.bottom += posh;
currpage.top =currpage.bottom+final_h;
currpage.right=currpage.left+final_w;
//Cropping.
// TODO: Borders are covered by the image. buffer space?
page.replaceKey("/TrimBox",_cfPDFToPDFMakeBox(currpage.left,currpage.bottom,currpage.right,currpage.top));
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(save_rotate));
return _cfPDFToPDFGetRotate(page);
}
bool _cfPDFToPDFQPDFPageHandle::is_landscape(pdftopdf_rotation_e orientation)
{
page.assertInitialized();
pdftopdf_rotation_e save_rotate = _cfPDFToPDFGetRotate(page);
if(orientation==ROT_0||orientation==ROT_180)
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(ROT_90));
else
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(ROT_0));
_cfPDFToPDFPageRect currpage= _cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
double width = currpage.right-currpage.left;
double height = currpage.top-currpage.bottom;
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(save_rotate));
if(width>height)
return true;
return false;
}
// TODO: better cropping
// TODO: test/fix with qsub rotation
void _cfPDFToPDFQPDFPageHandle::add_subpage(const std::shared_ptr<_cfPDFToPDFPageHandle> &sub,float xpos,float ypos,float scale,const _cfPDFToPDFPageRect *crop) // {{{
{
auto qsub=dynamic_cast<_cfPDFToPDFQPDFPageHandle *>(sub.get());
assert(qsub);
std::string xoname="/X"+QUtil::int_to_string((qsub->no!=-1)?qsub->no:++no);
if (crop) {
_cfPDFToPDFPageRect pg=qsub->get_rect(),tmp=*crop;
// we need to fix a too small cropbox.
tmp.width=tmp.right-tmp.left;
tmp.height=tmp.top-tmp.bottom;
tmp.rotate_move(-_cfPDFToPDFGetRotate(qsub->page),tmp.width,tmp.height); // TODO TODO (pg.width? / unneeded?)
// TODO: better
// TODO: we need to obey page./Rotate
if (pg.width<tmp.width) {
pg.right=pg.left+tmp.width;
}
if (pg.height<tmp.height) {
pg.top=pg.bottom+tmp.height;
}
_cfPDFToPDFPageRect rect=ungetRect(pg,*qsub,ROT_0,qsub->page);
qsub->page.replaceKey("/TrimBox",_cfPDFToPDFMakeBox(rect.left,rect.bottom,rect.right,rect.top));
// TODO? do everything for cropping here?
}
xobjs[xoname]=_cfPDFToPDFMakeXObject(qsub->page.getOwningQPDF(),qsub->page); // trick: should be the same as page->getOwningQPDF() [only after it's made indirect]
_cfPDFToPDFMatrix mtx;
mtx.translate(xpos,ypos);
mtx.scale(scale);
mtx.rotate(qsub->rotation); // TODO? -sub.rotation ? // TODO FIXME: this might need another translation!?
if (crop) { // TODO? other technique: set trim-box before _cfPDFToPDFMakeXObject (but this modifies original page)
mtx.translate(crop->left,crop->bottom);
// crop->dump();
}
content.append("q\n ");
content.append(mtx.get_string()+" cm\n ");
if (crop) {
content.append("0 0 "+QUtil::double_to_string(crop->right-crop->left)+" "+QUtil::double_to_string(crop->top-crop->bottom)+" re W n\n ");
// content.append("0 0 "+QUtil::double_to_string(crop->right-crop->left)+" "+QUtil::double_to_string(crop->top-crop->bottom)+" re S\n ");
}
content.append(xoname+" Do\n");
content.append("Q\n");
}
// }}}
void _cfPDFToPDFQPDFPageHandle::mirror() // {{{
{
_cfPDFToPDFPageRect orig=get_rect();
if (is_existing()) {
// need to wrap in XObject to keep patterns correct
// TODO? refactor into internal ..._subpage fn ?
std::string xoname="/X"+QUtil::int_to_string(no);
QPDFObjectHandle subpage=get(); // this->page, with rotation
// replace all our data
*this=_cfPDFToPDFQPDFPageHandle(subpage.getOwningQPDF(),orig.width,orig.height);
xobjs[xoname]=_cfPDFToPDFMakeXObject(subpage.getOwningQPDF(),subpage); // we can only now set this->xobjs
// content.append(std::string("1 0 0 1 0 0 cm\n ");
content.append(xoname+" Do\n");
assert(!is_existing());
}
static const char *pre="%pdftopdf cm\n";
// Note: we don't change (TODO need to?) the media box
std::string mrcmd("-1 0 0 1 "+
QUtil::double_to_string(orig.right)+" 0 cm\n");
content.insert(0,std::string(pre)+mrcmd);
}
// }}}
void _cfPDFToPDFQPDFPageHandle::rotate(pdftopdf_rotation_e rot) // {{{
{
rotation=rot; // "rotation += rot;" ?
}
// }}}
void _cfPDFToPDFQPDFPageHandle::add_label(const _cfPDFToPDFPageRect &_rect, const std::string label) // {{{
{
assert(is_existing());
_cfPDFToPDFPageRect rect = ungetRect (_rect, *this, rotation, page);
assert (rect.left <= rect.right);
assert (rect.bottom <= rect.top);
// TODO: Only add in the font once, not once per page.
QPDFObjectHandle font = page.getOwningQPDF()->makeIndirectObject
(QPDFObjectHandle::parse(
"<<"
" /Type /Font"
" /Subtype /Type1"
" /Name /pagelabel-font"
" /BaseFont /Helvetica" // TODO: support UTF-8 labels?
">>"));
QPDFObjectHandle resources = page.getKey ("/Resources");
QPDFObjectHandle rfont = resources.getKey ("/Font");
rfont.replaceKey ("/pagelabel-font", font);
double margin = 2.25;
double height = 12;
std::string boxcmd = "q\n";
// White filled rectangle (top)
boxcmd += " 1 1 1 rg\n";
boxcmd += " " +
QUtil::double_to_string(rect.left + margin) + " " +
QUtil::double_to_string(rect.top - height - 2 * margin) + " " +
QUtil::double_to_string(rect.right - rect.left - 2 * margin) + " " +
QUtil::double_to_string(height + 2 * margin) + " re f\n";
// White filled rectangle (bottom)
boxcmd += " " +
QUtil::double_to_string(rect.left + margin) + " " +
QUtil::double_to_string(rect.bottom + height + margin) + " " +
QUtil::double_to_string(rect.right - rect.left - 2 * margin) + " " +
QUtil::double_to_string(height + 2 * margin) + " re f\n";
// Black outline (top)
boxcmd += " 0 0 0 RG\n";
boxcmd += " " +
QUtil::double_to_string(rect.left + margin) + " " +
QUtil::double_to_string(rect.top - height - 2 * margin) + " " +
QUtil::double_to_string(rect.right - rect.left - 2 * margin) + " " +
QUtil::double_to_string(height + 2 * margin) + " re S\n";
// Black outline (bottom)
boxcmd += " " +
QUtil::double_to_string(rect.left + margin) + " " +
QUtil::double_to_string(rect.bottom + height + margin) + " " +
QUtil::double_to_string(rect.right - rect.left - 2 * margin) + " " +
QUtil::double_to_string(height + 2 * margin) + " re S\n";
// Black text (top)
boxcmd += " 0 0 0 rg\n";
boxcmd += " BT\n";
boxcmd += " /pagelabel-font 12 Tf\n";
boxcmd += " " +
QUtil::double_to_string(rect.left + 2 * margin) + " " +
QUtil::double_to_string(rect.top - height - margin) + " Td\n";
boxcmd += " (" + label + ") Tj\n";
boxcmd += " ET\n";
// Black text (bottom)
boxcmd += " BT\n";
boxcmd += " /pagelabel-font 12 Tf\n";
boxcmd += " " +
QUtil::double_to_string(rect.left + 2 * margin) + " " +
QUtil::double_to_string(rect.bottom + height + 2 * margin) + " Td\n";
boxcmd += " (" + label + ") Tj\n";
boxcmd += " ET\n";
boxcmd += "Q\n";
assert(page.getOwningQPDF()); // existing pages are always indirect
static const char *pre="%pdftopdf q\n"
"q\n",
*post="%pdftopdf Q\n"
"Q\n";
QPDFObjectHandle stm1=QPDFObjectHandle::newStream(page.getOwningQPDF(),
std::string(pre)),
stm2=QPDFObjectHandle::newStream(page.getOwningQPDF(),
std::string(post) + boxcmd);
page.addPageContents(stm1,true); // before
page.addPageContents(stm2,false); // after
}
// }}}
void _cfPDFToPDFQPDFPageHandle::debug(const _cfPDFToPDFPageRect &rect,float xpos,float ypos) // {{{
{
assert(!is_existing());
content.append(debug_box(rect,xpos,ypos));
}
// }}}
void _cfPDFToPDFQPDFProcessor::close_file() // {{{
{
pdf.reset();
hasCM=false;
}
// }}}
// TODO? try/catch for PDF parsing errors?
bool _cfPDFToPDFQPDFProcessor::load_file(FILE *f,pdftopdf_doc_t *doc,pdftopdf_arg_ownership_e take,int flatten_forms) // {{{
{
close_file();
if (!f) {
throw std::invalid_argument("load_file(NULL,...) not allowed");
}
try {
pdf.reset(new QPDF);
} catch (...) {
if (take==CF_PDFTOPDF_TAKE_OWNERSHIP) {
fclose(f);
}
throw;
}
switch (take) {
case CF_PDFTOPDF_WILL_STAY_ALIVE:
try {
pdf->processFile("temp file",f,false);
} catch (const std::exception &e) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: load_file failed: %s", e.what());
return false;
}
break;
case CF_PDFTOPDF_TAKE_OWNERSHIP:
try {
pdf->processFile("temp file",f,true);
} catch (const std::exception &e) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: load_file failed: %s", e.what());
return false;
}
break;
case CF_PDFTOPDF_MUST_DUPLICATE:
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: load_file with CF_PDFTOPDF_MUST_DUPLICATE is not supported");
return false;
}
start(flatten_forms);
return true;
}
// }}}
bool _cfPDFToPDFQPDFProcessor::load_filename(const char *name,pdftopdf_doc_t *doc,int flatten_forms) // {{{
{
close_file();
try {
pdf.reset(new QPDF);
pdf->processFile(name);
} catch (const std::exception &e) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: load_filename failed: %s",e.what());
return false;
}
start(flatten_forms);
return true;
}
// }}}
void _cfPDFToPDFQPDFProcessor::start(int flatten_forms) // {{{
{
assert(pdf);
if (flatten_forms) {
QPDFAcroFormDocumentHelper afdh(*pdf);
afdh.generateAppearancesIfNeeded();
QPDFPageDocumentHelper dh(*pdf);
dh.flattenAnnotations(an_print);
}
pdf->pushInheritedAttributesToPage();
orig_pages=pdf->getAllPages();
// remove them (just unlink, data still there)
const int len=orig_pages.size();
for (int iA=0;iA<len;iA++) {
pdf->removePage(orig_pages[iA]);
}
// we remove stuff that becomes defunct (probably) TODO
pdf->getRoot().removeKey("/PageMode");
pdf->getRoot().removeKey("/Outlines");
pdf->getRoot().removeKey("/OpenAction");
pdf->getRoot().removeKey("/PageLabels");
}
// }}}
bool _cfPDFToPDFQPDFProcessor::check_print_permissions(pdftopdf_doc_t *doc) // {{{
{
if (!pdf) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: No PDF loaded");
return false;
}
return pdf->allowPrintHighRes() || pdf->allowPrintLowRes(); // from legacy pdftopdf
}
// }}}
std::vector<std::shared_ptr<_cfPDFToPDFPageHandle>> _cfPDFToPDFQPDFProcessor::get_pages(pdftopdf_doc_t *doc) // {{{
{
std::vector<std::shared_ptr<_cfPDFToPDFPageHandle>> ret;
if (!pdf) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: No PDF loaded");
assert(0);
return ret;
}
const int len=orig_pages.size();
ret.reserve(len);
for (int iA=0;iA<len;iA++) {
ret.push_back(std::shared_ptr<_cfPDFToPDFPageHandle>(new _cfPDFToPDFQPDFPageHandle(orig_pages[iA],iA+1)));
}
return ret;
}
// }}}
std::shared_ptr<_cfPDFToPDFPageHandle> _cfPDFToPDFQPDFProcessor::new_page(float width,float height,pdftopdf_doc_t *doc) // {{{
{
if (!pdf) {
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: No PDF loaded");
assert(0);
return std::shared_ptr<_cfPDFToPDFPageHandle>();
}
return std::shared_ptr<_cfPDFToPDFQPDFPageHandle>(new _cfPDFToPDFQPDFPageHandle(pdf.get(),width,height));
// return std::make_shared<_cfPDFToPDFQPDFPageHandle>(pdf.get(),width,height);
// problem: make_shared not friend
}
// }}}
void _cfPDFToPDFQPDFProcessor::add_page(std::shared_ptr<_cfPDFToPDFPageHandle> page,bool front) // {{{
{
assert(pdf);
auto qpage=dynamic_cast<_cfPDFToPDFQPDFPageHandle *>(page.get());
if (qpage) {
pdf->addPage(qpage->get(),front);
}
}
// }}}
#if 0
// we remove stuff now probably defunct TODO
pdf->getRoot().removeKey("/PageMode");
pdf->getRoot().removeKey("/Outlines");
pdf->getRoot().removeKey("/OpenAction");
pdf->getRoot().removeKey("/PageLabels");
#endif
void _cfPDFToPDFQPDFProcessor::multiply(int copies,bool collate) // {{{
{
assert(pdf);
assert(copies>0);
std::vector<QPDFObjectHandle> pages=pdf->getAllPages(); // need copy
const int len=pages.size();
if (collate) {
for (int iA=1;iA<copies;iA++) {
for (int iB=0;iB<len;iB++) {
pdf->addPage(pages[iB].shallowCopy(),false);
}
}
} else {
for (int iB=0;iB<len;iB++) {
for (int iA=1;iA<copies;iA++) {
pdf->addPageAt(pages[iB].shallowCopy(),false,pages[iB]);
}
}
}
}
// }}}
// TODO? elsewhere?
void _cfPDFToPDFQPDFProcessor::auto_rotate_all(bool dst_lscape,pdftopdf_rotation_e normal_landscape) // {{{
{
assert(pdf);
const int len=orig_pages.size();
for (int iA=0;iA<len;iA++) {
QPDFObjectHandle page=orig_pages[iA];
pdftopdf_rotation_e src_rot=_cfPDFToPDFGetRotate(page);
// copy'n'paste from _cfPDFToPDFQPDFPageHandle::get_rect
_cfPDFToPDFPageRect ret=_cfPDFToPDFGetBoxAsRect(_cfPDFToPDFGetTrimBox(page));
// ret.translate(-ret.left,-ret.bottom);
ret.rotate_move(src_rot,ret.width,ret.height);
// ret.scale(_cfPDFToPDFGetUserUnit(page));
const bool src_lscape=(ret.width>ret.height);
if (src_lscape!=dst_lscape) {
pdftopdf_rotation_e rotation=normal_landscape;
// TODO? other rotation direction, e.g. if (src_rot==ROT_0)&&(param.orientation==ROT_270) ... etc.
// rotation=ROT_270;
page.replaceOrRemoveKey("/Rotate",_cfPDFToPDFMakeRotate(src_rot+rotation));
}
}
}
// }}}
#include "qpdf-cm-private.h"
// TODO
void _cfPDFToPDFQPDFProcessor::add_cm(const char *defaulticc,const char *outputicc) // {{{
{
assert(pdf);
if (_cfPDFToPDFHasOutputIntent(*pdf)) {
return; // nothing to do
}
QPDFObjectHandle srcicc=_cfPDFToPDFSetDefaultICC(*pdf,defaulticc); // TODO? rename to putDefaultICC?
_cfPDFToPDFAddDefaultRGB(*pdf,srcicc);
_cfPDFToPDFAddOutputIntent(*pdf,outputicc);
hasCM=true;
}
// }}}
void _cfPDFToPDFQPDFProcessor::set_comments(const std::vector<std::string> &comments) // {{{
{
extraheader.clear();
const int len=comments.size();
for (int iA=0;iA<len;iA++) {
assert(comments[iA].at(0)=='%');
extraheader.append(comments[iA]);
extraheader.push_back('\n');
}
}
// }}}
void _cfPDFToPDFQPDFProcessor::emit_file(FILE *f,pdftopdf_doc_t *doc,pdftopdf_arg_ownership_e take) // {{{
{
if (!pdf) {
return;
}
QPDFWriter out(*pdf);
switch (take) {
case CF_PDFTOPDF_WILL_STAY_ALIVE:
out.setOutputFile("temp file",f,false);
break;
case CF_PDFTOPDF_TAKE_OWNERSHIP:
out.setOutputFile("temp file",f,true);
break;
case CF_PDFTOPDF_MUST_DUPLICATE:
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_ERROR,
"cfFilterPDFToPDF: emit_file with CF_PDFTOPDF_MUST_DUPLICATE is not supported");
return;
}
if (hasCM) {
out.setMinimumPDFVersion("1.4");
} else {
out.setMinimumPDFVersion("1.2");
}
if (!extraheader.empty()) {
out.setExtraHeaderText(extraheader);
}
out.setPreserveEncryption(false);
out.write();
}
// }}}
void _cfPDFToPDFQPDFProcessor::emit_filename(const char *name,pdftopdf_doc_t *doc) // {{{
{
if (!pdf) {
return;
}
// special case: name==NULL -> stdout
QPDFWriter out(*pdf,name);
if (hasCM) {
out.setMinimumPDFVersion("1.4");
} else {
out.setMinimumPDFVersion("1.2");
}
if (!extraheader.empty()) {
out.setExtraHeaderText(extraheader);
}
out.setPreserveEncryption(false);
std::vector<QPDFObjectHandle> pages=pdf->getAllPages();
int len=pages.size();
if (len)
out.write();
else
if (doc->logfunc) doc->logfunc(doc->logdata, CF_LOGLEVEL_DEBUG,
"cfFilterPDFToPDF: No pages left, outputting empty file.");
}
// }}}
// TODO:
// loadPDF(); success?
bool _cfPDFToPDFQPDFProcessor::has_acro_form() // {{{
{
if (!pdf) {
return false;
}
QPDFObjectHandle root=pdf->getRoot();
if (!root.hasKey("/AcroForm")) {
return false;
}
return true;
}
// }}}
| 32.114987 | 255 | 0.683309 | [
"vector",
"transform"
] |
f43a18443862f19fd1bd523cd1999a310a8495ee | 720 | cpp | C++ | test/initializer_list_assignment.cpp | LeonineKing1199/sleip | aa6ac4d9b581e42c8eb3883a9e42c5d015d377cc | [
"BSL-1.0"
] | 22 | 2020-01-19T03:47:26.000Z | 2020-11-03T17:11:13.000Z | test/initializer_list_assignment.cpp | LeonineKing1199/sleip | aa6ac4d9b581e42c8eb3883a9e42c5d015d377cc | [
"BSL-1.0"
] | null | null | null | test/initializer_list_assignment.cpp | LeonineKing1199/sleip | aa6ac4d9b581e42c8eb3883a9e42c5d015d377cc | [
"BSL-1.0"
] | 3 | 2020-01-05T21:18:25.000Z | 2020-04-07T08:21:04.000Z | #include <sleip/dynamic_array.hpp>
#include <vector>
#include <boost/core/lightweight_test.hpp>
void
test_initializer_list_assignment()
{
// empty
//
{
auto a = sleip::dynamic_array<int>();
auto list = std::initializer_list<int>{1, 2, 3};
a = list;
BOOST_TEST_EQ(a.size(), list.size());
BOOST_TEST_ALL_EQ(a.begin(), a.end(), list.begin(), list.end());
}
// non-empty
{
auto a = sleip::dynamic_array<std::vector<int>>(8);
auto list = std::initializer_list<std::vector<int>>{std::vector<int>()};
BOOST_TEST_EQ(a.size(), 8);
a = list;
BOOST_TEST_EQ(a.size(), 1);
}
}
int
main()
{
test_initializer_list_assignment();
return boost::report_errors();
}
| 17.560976 | 76 | 0.626389 | [
"vector"
] |
f43da71369a9c74a0eb34f89be1586d6673053db | 211 | cpp | C++ | Extensions/PhysicsBehavior/Box2D/Contributions/Platforms/Box2D.Net/VariousImplementations.cpp | mohajain/GDevelop | 8e8d96dd3a5957221fb3d0ec28a694620149d835 | [
"MIT"
] | 4 | 2021-03-18T22:26:31.000Z | 2021-07-16T00:12:15.000Z | Extensions/PhysicsBehavior/Box2D/Contributions/Platforms/Box2D.Net/VariousImplementations.cpp | mohajain/GDevelop | 8e8d96dd3a5957221fb3d0ec28a694620149d835 | [
"MIT"
] | 9 | 2020-04-04T19:26:47.000Z | 2022-03-25T18:41:20.000Z | Extensions/PhysicsBehavior/Box2D/Contributions/Platforms/Box2D.Net/VariousImplementations.cpp | mohajain/GDevelop | 8e8d96dd3a5957221fb3d0ec28a694620149d835 | [
"MIT"
] | 2 | 2020-03-02T05:20:41.000Z | 2021-05-10T03:59:05.000Z | #pragma once
#include "stdafx.h"
#include "Shape.cpp"
#include "Body.cpp"
namespace Box2D
{
namespace Net
{
Body^ Shape::Body::get()
{
return gcnew Box2D::Net::Body(shape->GetBody());
}
}
}
| 8.791667 | 51 | 0.616114 | [
"shape"
] |
f43f2643b35b2e5a260ee6a631b940acdf2f1f67 | 3,337 | hpp | C++ | src/geohash/core/include/geohash/string.hpp | fbriol/pangeo-geohash | 2f02985f789d91f4bb8ee28ff9ae224c2a990b04 | [
"MIT"
] | null | null | null | src/geohash/core/include/geohash/string.hpp | fbriol/pangeo-geohash | 2f02985f789d91f4bb8ee28ff9ae224c2a990b04 | [
"MIT"
] | null | null | null | src/geohash/core/include/geohash/string.hpp | fbriol/pangeo-geohash | 2f02985f789d91f4bb8ee28ff9ae224c2a990b04 | [
"MIT"
] | null | null | null | #pragma once
#include <pybind11/numpy.h>
#include <Eigen/Core>
#include <map>
#include <optional>
#include <tuple>
#include <vector>
#include "geohash/geometry.hpp"
namespace geohash::string {
// Handle the numpy arrays of geohash.
class Array {
public:
// Creation of a vector of "size" items of strings of maximum length
// "precision"
Array(const size_t size, const uint32_t precision)
: array_(new std::vector<char>(size * precision, '\0')),
capsule_(array_,
[](void* ptr) {
delete reinterpret_cast<std::vector<char>*>(ptr);
}),
chars_(precision),
size_(size) {}
// Get the pointer to the raw memory
[[nodiscard]] inline auto buffer() const -> char* { return array_->data(); }
// Creates the numpy array from the memory allocated in the C++ code without
// copying the data.
[[nodiscard]] inline auto pyarray() -> pybind11::array {
return pybind11::array(pybind11::dtype("S" + std::to_string(chars_)),
{size_}, {chars_ * sizeof(char)}, array_->data(),
capsule_);
}
static auto get_info(const pybind11::array& hashs, const ssize_t ndim)
-> pybind11::buffer_info;
private:
std::vector<char>* array_;
pybind11::capsule capsule_;
uint32_t chars_;
size_t size_;
};
// Encode a point into geohash with the given bit depth
auto encode(const Point& point, char* const buffer, uint32_t precision) -> void;
// Encode points into geohash with the given bit depth
[[nodiscard]] auto encode(
const Eigen::Ref<const Eigen::Matrix<Point, -1, 1>>& points,
uint32_t precision) -> pybind11::array;
// Returns the region encoded
[[nodiscard]] auto bounding_box(const char* const hash, size_t count) -> Box;
// Decode a hash into a spherical equatorial point. If round is true, the
// coordinates of the points will be rounded to the accuracy defined by the
// GeoHash.
[[nodiscard]] auto decode(const char* const hash, const size_t count,
const bool round) -> Point;
// Decode hashs into a spherical equatorial points. If round is true, the
// coordinates of the points will be rounded to the accuracy defined by the
// GeoHash.
[[nodiscard]] auto decode(const pybind11::array& hashs, const bool center)
-> Eigen::Matrix<Point, -1, 1>;
// Returns all neighbors hash clockwise from north around northwest at the
// given precision:
// 7 0 1
// 6 x 2
// 5 4 3
[[nodiscard]] auto neighbors(const char* const hash, const size_t count)
-> pybind11::array;
// Returns all GeoHash with the defined box
[[nodiscard]] auto bounding_boxes(const std::optional<Box>& box,
const uint32_t chars) -> pybind11::array;
// Returns all the GeoHash codes within the polygon.
[[nodiscard]] inline auto bounding_boxes(const Polygon& polygon, uint32_t chars)
-> pybind11::array {
auto box = Box();
boost::geometry::envelope<Polygon, Box>(polygon, box);
return bounding_boxes(box, chars);
}
// Returns the start and end indexes of the different GeoHash boxes.
[[nodiscard]] auto where(const pybind11::array& hashs)
-> std::map<std::string, std::tuple<std::tuple<int64_t, int64_t>,
std::tuple<int64_t, int64_t>>>;
} // namespace geohash::string
| 34.05102 | 80 | 0.659574 | [
"geometry",
"vector"
] |
f4422e160fad9ddfc8b9594f1bc53658f5966e86 | 5,604 | hpp | C++ | include/BlockManager.hpp | suncloudsmoon/Enemycraft | d47652ac954ae33c4548139be73b9a2d2535a448 | [
"MIT-0"
] | 1 | 2021-10-03T14:35:24.000Z | 2021-10-03T14:35:24.000Z | include/BlockManager.hpp | suncloudsmoon/Enemycraft | d47652ac954ae33c4548139be73b9a2d2535a448 | [
"MIT-0"
] | null | null | null | include/BlockManager.hpp | suncloudsmoon/Enemycraft | d47652ac954ae33c4548139be73b9a2d2535a448 | [
"MIT-0"
] | null | null | null | /*
* Copyright (c) 2021, suncloudsmoon and the Enemycraft contributors.
*
* 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.
*
* 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.
*/
/*
* BlockManager.hpp
*
* Created on: Oct 2, 2021
* Author: suncloudsmoon
*/
#ifndef INCLUDE_BLOCKMANAGER_HPP_
#define INCLUDE_BLOCKMANAGER_HPP_
#include <string>
#include <vector>
#include <random>
#include <SFML/Graphics.hpp>
#include <Block.hpp>
#include <TextureManager.hpp>
#include <Point.hpp>
#include <ForceTable.hpp>
#include <BlockArr2D.hpp>
template<class P, class T>
class BlockManager {
public:
BlockManager(P bSize, P bMass, T w, T h, float defaultMuConstant,
TextureManager &manager, std::mt19937 &device) :
blockSize(bSize), blockMass(bMass), width(w / bSize), height(
h / bSize), defaultMu(defaultMuConstant), textureManager(
manager), randDevice(device) {
blockMap = new BlockArr2D<P, T>(width, height, blockSize);
forceTable = new ForceTable<T, P>(width, height, blockSize);
magnetForce = 100;
// Debug Messages
std::cout << "BlockManager width: " << width << ", height: " << height
<< std::endl;
}
void add(Block<P> *block) {
// Learned: you cannot insert the same object twice
Point<P> blockCoord(block->getPosition().x, block->getPosition().y);
addMagneticForce(blockCoord, block);
blockMap->set(blockCoord, block);
}
void remove(Point<P> &p) {
remove(p.x, p.y);
}
void remove(P x, P y) {
Block<P> *block = blockMap->get(x, y);
removeMagneticForce(x, y, block);
blockMap->remove(x, y);
}
void addMagneticForce(const Point<P> &coords, const Block<P> *block) const {
addMagneticForce(coords.x, coords.y, block);
}
void addMagneticForce(P x, P y, const Block<P> *block) const {
switch (block->getMagnetFacingDirection()) {
// Up
case 1:
forceTable->addForce(x, y, 0, block->getMass());
break;
// Down
case 2:
forceTable->addForce(x, y, 0, -block->getMass());
break;
// Left
case 3:
forceTable->addForce(x, y, -block->getMass(), 0);
break;
// Right
case 4:
forceTable->addForce(x, y, block->getMass(), 0);
break;
default:
break;
}
}
void removeMagneticForce(const Point<P> &p, const Block<P> *block) const {
removeMagneticForce(p.x, p.y, block);
}
void removeMagneticForce(P x, P y, const Block<P> *block) const {
switch (block->getMagnetFacingDirection()) {
// Up
case 1:
forceTable->removeForce(x, y, 0, block->getMass());
break;
// Down
case 2:
forceTable->removeForce(x, y, 0, -block->getMass());
break;
// Left
case 3:
forceTable->removeForce(x, y, -block->getMass(), 0);
break;
// Right
case 4:
forceTable->removeForce(x, y, block->getMass(), 0);
break;
default:
break;
}
}
void generateAll() {
std::uniform_int_distribution<T> randsBlocks(0, blockSize);
std::uniform_int_distribution<T> randsX(1, width-1);
std::uniform_int_distribution<T> randsY(1, height-1);
std::uniform_int_distribution<T> randMagnetism(0, 4);
T numBlocks = randsBlocks(randDevice);
for (T i = 0; i < numBlocks; i++) {
Block<P> *block = new Block<P>(blockSize, blockMass, 0, 0,
defaultMu, textureManager);
block->setMagnetFacingDirection(randMagnetism(randDevice));
T x = (T) (randsX(randDevice) * blockSize);
T y = (T) (randsY(randDevice) * blockSize);
block->setPosition(x, y);
add(block);
}
}
Point<T> getBlockyCoordinates(Point<P> &p) {
return getBlockyCoordinates(p.x, p.y);
}
Point<T> getBlockyCoordinates(P x, P y) {
T newX = (T) (x / blockSize) * blockSize;
T newY = (T) (y / blockSize) * blockSize;
return Point<T>(newX, newY);
}
// LEARNED: Need to be careful with getters and setters; they can introduce bugs into code!
// Getters and Setters
T getBlockMass() const {
return blockMass;
}
void setBlockMass(T blockMass) {
this->blockMass = blockMass;
}
T getBlockSize() const {
return blockSize;
}
void setBlockSize(T blockSize) {
this->blockSize = blockSize;
}
T getHeight() const {
return height;
}
void setHeight(T height) {
this->height = height;
}
T getWidth() const {
return width;
}
void setWidth(T width) {
this->width = width;
}
ForceTable<T, P>*& getForceTable() {
return forceTable;
}
void setForceTable(ForceTable<T, P> *&forceTable) {
this->forceTable = forceTable;
}
BlockArr2D<P, T>*& getBlockMap() {
return blockMap;
}
void setBlockMap(BlockArr2D<P, T> *&blockMap) {
this->blockMap = blockMap;
}
private:
BlockArr2D<P, T> *blockMap;
ForceTable<T, P> *forceTable;
T blockSize;
T blockMass;
T width, height;
float defaultMu;
TextureManager &textureManager;
std::mt19937 &randDevice;
T magnetForce; // ASSUMPTION: magnetForce >= 0 Newtons
};
#endif /* INCLUDE_BLOCKMANAGER_HPP_ */
| 25.130045 | 92 | 0.681478 | [
"object",
"vector"
] |
f4491644afb9d9520a40337ddcedbd0d4a39238f | 3,478 | cpp | C++ | src/RmBkFilter/TransSmpte/TransSmpte.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | 5 | 2015-03-31T15:51:22.000Z | 2022-03-10T07:01:56.000Z | src/RmBkFilter/TransSmpte/TransSmpte.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | null | null | null | src/RmBkFilter/TransSmpte/TransSmpte.cpp | mkmpvtltd1/Webinaria | 41d86467800adb48e77ab49b92891fae2a99bb77 | [
"MIT"
] | null | null | null | //
#include <streams.h>
#include "..\iRGBFilters.h"
#include "TransSmpte.h"
static const AMOVIESETUP_MEDIATYPE
sudInputPinTypes = { &MEDIATYPE_Video // clsMajorType
, &MEDIASUBTYPE_NULL } ; // clsMinorType
static const AMOVIESETUP_MEDIATYPE
sudOutputPinTypes = { &MEDIATYPE_Video // clsMajorType
, &MEDIASUBTYPE_NULL } ; // clsMinorType
static const AMOVIESETUP_PIN
psudPins[] =
{
{ L"Input" // strName
, FALSE // bRendered
, FALSE // bOutput
, FALSE // bZero
, FALSE // bMany
, &CLSID_NULL // clsConnectsToFilter
, L"Output" // strConnectsToPin
, 1 // nTypes
, &sudInputPinTypes // lpTypes
}
,
{
L"Output" // strName
, FALSE // bRendered
, TRUE // bOutput
, FALSE // bZero
, FALSE // bMany
, &CLSID_NULL // clsConnectsToFilter
, L"Input" // strConnectsToPin
, 1 // nTypes
, &sudOutputPinTypes // lpTypes
}
};
const AMOVIESETUP_FILTER sudTransSmpte =
{
&CLSID_CRemoveBackground, // Filter CLSID
L"RemoveBackGround", // String name
MERIT_DO_NOT_USE, // Filter merit
2, // Number pins
psudPins // Pin details
};
CUnknown * WINAPI CRemoveBackground::CreateInstance(LPUNKNOWN lpunk, HRESULT *phr)
{
CUnknown *punk = new CRemoveBackground(lpunk, phr);
if (punk == NULL)
{
*phr = E_OUTOFMEMORY;
}
return punk;
}
CRemoveBackground::CRemoveBackground(LPUNKNOWN punk,HRESULT *phr)
: CTransInPlaceFilter(TEXT("RemoveBackGround"), punk, CLSID_CRemoveBackground, phr)
, m_nWidth(0)
, m_nHeight(0)
{
}
CRemoveBackground::~CRemoveBackground( )
{
}
HRESULT CRemoveBackground::SetMediaType( PIN_DIRECTION pindir, const CMediaType *pMediaType)
{
CheckPointer(pMediaType,E_POINTER);
VIDEOINFO* pVI = (VIDEOINFO*) pMediaType->Format();
CheckPointer(pVI,E_UNEXPECTED);
m_nWidth = pVI->bmiHeader.biWidth;
m_nHeight = pVI->bmiHeader.biHeight;
return CTransInPlaceFilter::SetMediaType( pindir, pMediaType );
}
HRESULT CRemoveBackground::CheckInputType(const CMediaType *mtIn)
{
CheckPointer(mtIn,E_POINTER);
if (*mtIn->FormatType() != FORMAT_VideoInfo)
{
return E_INVALIDARG;
}
if( *mtIn->Type( ) != MEDIATYPE_Video )
{
return E_INVALIDARG;
}
if( *mtIn->Subtype( ) != MEDIASUBTYPE_ARGB32)
{
return E_INVALIDARG;
}
VIDEOINFO *pVI = (VIDEOINFO *) mtIn->Format();
CheckPointer(pVI,E_UNEXPECTED);
if( pVI->bmiHeader.biBitCount != 32 )
{
return E_INVALIDARG;
}
// Reject negative height bitmaps to prevent drawing upside-down text
if( pVI->bmiHeader.biHeight < 0 )
{
return E_INVALIDARG;
}
return NOERROR;
}
HRESULT CRemoveBackground::Transform(IMediaSample *pSample)
{
CheckPointer(pSample,E_POINTER);
char *pBuffer = 0;
pSample->GetPointer( (LPBYTE*) &pBuffer );
CRemover::ClearBack(pBuffer, m_nWidth, m_nHeight);
return NOERROR;
} | 25.573529 | 92 | 0.561242 | [
"transform"
] |
f44c0fb480c5f58b4efa5770d61edde92072c562 | 1,593 | hxx | C++ | Legolas/Matrix/VirtualMatrix/VirtualMatrixKernel.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/VirtualMatrix/VirtualMatrixKernel.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | null | null | null | Legolas/Matrix/VirtualMatrix/VirtualMatrixKernel.hxx | LaurentPlagne/Legolas | fdf533528baf7ab5fcb1db15d95d2387b3e3723c | [
"MIT"
] | 1 | 2021-02-11T14:43:25.000Z | 2021-02-11T14:43:25.000Z | /**
* project DESCARTES
*
* @file VirtualMatrixKernel.hxx
*
* @author Laurent PLAGNE
* @date june 2004 - january 2005
*
* @par Modifications
* - author date object
*
* (c) Copyright EDF R&D - CEA 2001-2005
*/
#ifndef __LEGOLAS_VIRTUALMATRIXKERNEL_HXX__
#define __LEGOLAS_VIRTUALMATRIXKERNEL_HXX__
#include "Legolas/Matrix/VirtualMatrix/VirtualMatrixDataDriver.hxx"
namespace Legolas{
template <class MATRIX_DEFINITION, class MATRIX_OPTIONS, class MATRIX_ELEMENT_INTERFACE>
class VirtualMatrixKernel{
private:
typedef MATRIX_OPTIONS MatrixOptions;
typedef typename MatrixOptions::VirtualMatrixStructure MatrixStructure;
typedef typename MATRIX_DEFINITION::Data DAT;
typedef typename MATRIX_DEFINITION::GetElement GET;
typedef GET CGE;
typedef typename MATRIX_ELEMENT_INTERFACE::DataDriver EDD;
typedef typename MatrixStructure::template Engine<MATRIX_DEFINITION,DAT,CGE,GET,EDD> Engine;
typedef typename Engine::Hierarchy MatrixHierarchy;
public:
typedef MATRIX_ELEMENT_INTERFACE MatrixElementInterface;
typedef VirtualMatrixDataDriver<MatrixHierarchy,MATRIX_OPTIONS> MatrixDataDriver;
typedef typename MATRIX_DEFINITION::Data Data;
typedef typename MatrixOptions::MatrixVectorProduct MatrixVectorProduct;
typedef typename MatrixOptions::MatrixVectorInverse MatrixVectorInverse;
};
}
#endif
| 33.1875 | 96 | 0.684871 | [
"object"
] |
f44ed2da834cf98a6bd7da1df2f6afce2f93c4ba | 5,582 | cpp | C++ | fox_track/src/main.cpp | lowerrandom/fox_trap | 181eb3b809aa19eda2b03044d970f6abb76662d7 | [
"MIT"
] | 16 | 2018-08-31T18:42:03.000Z | 2020-10-23T17:41:04.000Z | fox_track/src/main.cpp | lowerrandom/fox_trap | 181eb3b809aa19eda2b03044d970f6abb76662d7 | [
"MIT"
] | null | null | null | fox_track/src/main.cpp | lowerrandom/fox_trap | 181eb3b809aa19eda2b03044d970f6abb76662d7 | [
"MIT"
] | 3 | 2018-08-31T19:46:20.000Z | 2019-04-28T05:38:45.000Z | #include <painlessMesh.h>
#include "../lib/stringUtils.cpp"
#define MESH_PREFIX "Not_a_botnet"
#define MESH_PASSWORD "password"
#define MESH_PORT 5566
//Define these
unsigned long ackSeconds = 3;
uint32_t ackTimes = 20;
// Prototype
Scheduler userScheduler; // to control your personal task
painlessMesh mesh;
uint16_t channel = 6;
int32_t maxRttDelay = 0;
unsigned long initDelay = 15000000;
uint32_t acknowledgementInterval = 900000; //ms
std::vector<uint32_t> foundTargetNodeIds;
const char* mac;
const char delimiter = ' ';
void receivedCallback( uint32_t from, String &msg );
void rootInitialization();
void acknowledgeTargets();
void disableAck();
void readSerialCommand();
String prepCommandForMesh(const String &command);
//Async functions
Task rootInitializationTask(TASK_IMMEDIATE, TASK_ONCE, &rootInitialization, &userScheduler);
Task acknowledgementTask(TASK_SECOND * ackSeconds, ackTimes, &acknowledgeTargets, &userScheduler, false, NULL, &disableAck);
Task readSerialTask (TASK_IMMEDIATE, TASK_FOREVER, &readSerialCommand, &userScheduler);
void acknowledgeTargets(){
if (!foundTargetNodeIds.empty()){
StaticJsonDocument<1024> msg;
// JsonObject& msg = jsonBuffer.createObject();
for (auto nodeId : foundTargetNodeIds) // access by reference to avoid copying
{
msg["foundack"] = nodeId;
String str;
serializeJson(msg, str);
serializeJsonPretty(msg, Serial);
Serial.printf("\n");
mesh.sendBroadcast(str);
}
}
}
void disableAck()
{
foundTargetNodeIds.clear();
}
void sendInitializationSignal()
{
StaticJsonDocument<16> msg;
msg["initialize"] = (maxRttDelay*2) + mesh.getNodeTime();
String str;
serializeJson(msg, str);
mesh.sendBroadcast(str);
// log to serial
Serial.printf("c2 initialization sent: ");
serializeJsonPretty(msg, Serial);
Serial.printf("\n");
}
void onNodeDelayReceivedCallback(uint32_t nodeId, int32_t delay)
{
Serial.printf("ROOT:onNodeDelayReceivedCallback: %u, %i\n", nodeId, delay);
maxRttDelay = (delay > maxRttDelay)
? delay
: maxRttDelay;
}
void rootInitialization(){
Serial.printf("ROOT:rootInitialization_BEGIN");
mesh.init( MESH_PREFIX, MESH_PASSWORD, &userScheduler, MESH_PORT, WIFI_AP, channel);
mesh.onReceive(&receivedCallback);
//keep the topology from unnesecary re-organization
mesh.setRoot(true);
// This and all other mesh should ideally now the mesh contains a root
mesh.setContainsRoot(true);
mesh.onNewConnection([](size_t nodeId) {
Serial.printf("New Connection %u\n", nodeId);
});
mesh.onDroppedConnection([](size_t nodeId) {
Serial.printf("Dropped Connection %u\n", nodeId);
});
Serial.printf("ROOT:rootInitialization_END");
}
void setup() {
Serial.begin(115200);
userScheduler.addTask(rootInitializationTask);
userScheduler.addTask(acknowledgementTask);
userScheduler.addTask(readSerialTask);
readSerialTask.enable();
rootInitializationTask.enable();
}
void loop() {
userScheduler.execute(); // it will run mesh scheduler as well
mesh.update();
}
void receivedCallback( uint32_t from, String &msg ) {
Serial.printf("[RECEIVED] from %u msg=%s\n", from, msg.c_str());
StaticJsonDocument<120> root;
deserializeJson(root, msg);
if (root.containsKey("found")) {
// serializeJsonPretty(root, Serial);
// Serial.printf("\n");
//uint32_t foundTargetNodeId = root["from"];
uint16_t chan = root["chan"];
signed rssi = root["rssi"];
mac = root["found"];
Serial.printf("[FOUND] %d | %s | %d | %i \n", from, mac, chan, rssi);
if(std::find(foundTargetNodeIds.begin(), foundTargetNodeIds.end(), from) == foundTargetNodeIds.end()) {
foundTargetNodeIds.push_back(from);
Serial.printf("[ADDED]NODE %u ADDED TARGET\n", from);
}
//checks if it is diabled and re-enables it. if it is out of iterations AND disabled, restart
if( !acknowledgementTask.enableIfNot()){
acknowledgementTask.restart();
}
}
if (root.containsKey("fin_ack")){
// serializeJsonPretty(root, Serial);
// Serial.printf("\n");
foundTargetNodeIds.erase(std::remove(foundTargetNodeIds.begin(), foundTargetNodeIds.end(), from), foundTargetNodeIds.end());
}
}
void readSerialCommand (){
// Serial.printf("reading serial");
if (Serial.available() > 0) {
// Serial.printf("serial open...\n");
char command[17];
command[Serial.readBytesUntil('\n', command, 16)] = '\0';
const String commandStr = command;
if (commandStr.startsWith("tar") || commandStr.startsWith("rem")){
// if (strcmp(command, "test") == 0) {
// mesh.sendBroadcast();
String msg = prepCommandForMesh(command);
mesh.sendBroadcast(msg);
// Serial.printf("%s\n",command);
}
}
}
String prepCommandForMesh(const String &command){
// size_t pos = 0;
// String token;
StaticJsonDocument<25> comMsg;
// while ((pos = command.indexOf(delimiter)) != -1) {
// token = command.substring(0, pos);
//
// command.remove(0, pos + delimiter.length());
// }
String commandAlias = getValue(command, delimiter, 0);
String commandValue = getValue(command, delimiter, 1);
comMsg[commandAlias] = commandValue.c_str();
//for debugging
serializeJsonPretty(comMsg, Serial);
// Serial.println();
String jsonStr;
serializeJson(comMsg, jsonStr);
return jsonStr;
}
| 30.010753 | 130 | 0.671802 | [
"mesh",
"vector"
] |
f45033e48926b0b07bb0ecf5e094051ec89c3809 | 22,187 | cxx | C++ | test/unity/toolkits/recsys/ranking_model_tests.cxx | LeeCenY/turicreate | fb2f3bf313e831ceb42a2e10aacda6e472ea8d93 | [
"BSD-3-Clause"
] | null | null | null | test/unity/toolkits/recsys/ranking_model_tests.cxx | LeeCenY/turicreate | fb2f3bf313e831ceb42a2e10aacda6e472ea8d93 | [
"BSD-3-Clause"
] | 2 | 2022-01-13T04:03:55.000Z | 2022-03-12T01:02:31.000Z | test/unity/toolkits/recsys/ranking_model_tests.cxx | ZeroInfinite/turicreate | dd210c2563930881abd51fd69cb73007955b33fd | [
"BSD-3-Clause"
] | null | null | null | /* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
const bool enable_expensive_tests = false;
#define BOOST_TEST_MODULE
#include <boost/test/unit_test.hpp>
#include <util/test_macros.hpp>
#include <vector>
#include <string>
#include <functional>
#include <random/random.hpp>
#include <sframe/sframe_iterators.hpp>
#include <unity/toolkits/recsys/models/linear_models/linear_model.hpp>
#include <unity/toolkits/recsys/models/linear_models/factorization_model.hpp>
#include <unity/toolkits/recsys/models/linear_models/matrix_factorization.hpp>
#include <unity/toolkits/util/data_generators.hpp>
#include <unity/toolkits/ml_data_2/ml_data.hpp>
#include <unity/toolkits/ml_data_2/ml_data_iterator.hpp>
#include <sframe/testing_utils.hpp>
#include <util/testing_utils.hpp>
#include <cfenv>
using namespace turi;
using namespace turi::recsys;
void run_exact_test(
const std::vector<size_t>& n_categorical_values,
std::map<std::string, flexible_type> opts,
const std::string& model_type) {
bool binary_target = false;
if(model_type == "linear" || model_type == "fm" || model_type == "mf") {
binary_target = false;
opts["y_mode"] = "squared_error";
} else if(model_type == "logistic" || model_type == "logistic_fm" || model_type == "logistic_mf") {
binary_target = true;
opts["y_mode"] = "logistic";
} else {
DASSERT_TRUE(false);
}
if(model_type == "mf" || model_type == "logistic_mf")
opts["only_2_factor_terms"] = true;
std::feraiseexcept(FE_ALL_EXCEPT);
size_t n_observations = opts.at("n_observations");
opts.erase("n_observations");
std::string target_column_name = "target";
std::vector<std::string> column_names = {"user", "item"};
DASSERT_NE(n_categorical_values[0], 0);
DASSERT_NE(n_categorical_values[1], 0);
for(size_t i = 2; i < n_categorical_values.size(); ++i) {
column_names.push_back("C-" + std::to_string(i));
}
lm_data_generator lmdata(column_names, n_categorical_values, opts);
sframe train_data = lmdata.generate(n_observations, target_column_name, 0, 0);
sframe test_data = lmdata.generate(n_observations, target_column_name, 1, 0);
std::map<std::string, flexible_type> options =
{ {"optimization_method", "auto"},
{"binary_target", binary_target},
{"target", target_column_name},
{"regularization", 0},
{"sgd_step_size", 0},
{"max_iterations", binary_target ? 200 : 100},
{"sgd_convergence_threshold", 1e-10},
// Add in the ranking regularizer
{"ranking_regularization", 0.1},
{"unobserved_rating_value", 0}
};
opts.erase("y_mode");
if(model_type == "mf" || model_type == "logistic_mf")
opts.erase("only_2_factor_terms");
options.insert(opts.begin(), opts.end());
if(model_type == "fm" || model_type == "logistic_fm"
|| model_type == "mf" || model_type == "logistic_mf") {
options["linear_regularization"] = 0;
}
// Instantiate some alternate versions to make sure the save and load work
typedef std::shared_ptr<recsys::recsys_model_base> model_ptr;
auto new_model = [&]() -> model_ptr {
model_ptr ret;
if(model_type == "linear" || model_type == "logistic") {
ret.reset(new recsys_linear_model);
} else if(model_type == "fm" || model_type == "logistic_fm") {
ret.reset(new recsys_factorization_model);
} else if(model_type == "mf" || model_type == "logistic_mf") {
ret.reset(new recsys_matrix_factorization);
} else {
ASSERT_TRUE(false);
}
return ret;
};
model_ptr model = new_model();
model->init_option_info();
model->set_options(options);
model->setup_and_train(train_data);
// Instantiate some alternate versions to make sure the save and load work
std::vector<model_ptr> all_models =
{model,
new_model(),
model_ptr((recsys::recsys_model_base*)(model->clone()))};
////////////////////////////////////////
{
// Save it
dir_archive archive_write;
archive_write.open_directory_for_write("linear_regression_cxx_tests");
turi::oarchive oarc(archive_write);
oarc << *model;
archive_write.close();
// Load it
dir_archive archive_read;
archive_read.open_directory_for_read("linear_regression_cxx_tests");
turi::iarchive iarc(archive_read);
iarc >> (*all_models[1]);
}
for(model_ptr m : all_models) {
sframe y_hat_sf = m->predict(model->create_ml_data(test_data));
std::vector<double> y_hat = testing_extract_column<double>(y_hat_sf.select_column(0));
{
size_t i = 0;
for(ml_data_iterator it(m->create_ml_data(test_data)); !it.done(); ++it, ++i) {
double y = it.target_value();
if(!binary_target) {
if(y > 0)
TS_ASSERT_LESS_THAN(y_hat[i], 1.1 * (y + 0.5));
} else {
if(y == 0)
TS_ASSERT_LESS_THAN(y_hat[i], 0.75);
}
}
}
}
}
struct linear_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_regression_se_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 100 } };
run_exact_test({1, 1}, opts, "linear");
}
////////////////////////////////////////////////////////////////////////////////
void test_regression_se_basic_3d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 100 } };
// run_exact_test({1,1,0}, opts, "linear");
}
////////////////////////////////////////////////////////////////////////////////
void test_regression_se_basic_5d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 250 } };
// run_exact_test({1,1,0,0,0}, opts, "linear");
}
// ////////////////////////////////////////////////////////////////////////////////
void test_regression_se_multiuser_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 500 } };
// run_exact_test({2,2,0,0,0}, opts, "linear");
}
// ////////////////////////////////////////////////////////////////////////////////
void test_regression_se_large_no_side() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 100000 } };
run_exact_test({100,100}, opts, "linear");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_regression_se_large_some_side() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 5*10*10 } };
run_exact_test({10,10,0,0,0}, opts, "linear");
}
};
struct log_linear_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_regression_log_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 100 } };
run_exact_test({1, 1}, opts, "logistic");
}
////////////////////////////////////////////////////////////////////////////////
void test_regression_log_basic_3d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 100 } };
// run_exact_test({1,1,0}, opts, "logistic");
}
// ////////////////////////////////////////////////////////////////////////////////
void test_regression_log_large_no_side() {
if(enable_expensive_tests) {
std::map<std::string, flexible_type> opts = {
{"n_observations", 10*100*100 } };
run_exact_test({100,100}, opts, "logistic");
}
}
};
struct factorization_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_factorization_se_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 10 },
{"n_factors", 1 } };
run_exact_test({1, 1}, opts, "fm");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_factorization_se_many_factors() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 5 } };
run_exact_test({1, 8}, opts, "fm");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_factorization_se_many_columns() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({16, 1, 1, 1}, opts, "fm");
}
};
struct log_factorization_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_factorization_log_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 10 },
{"n_factors", 1 } };
run_exact_test({1, 1}, opts, "logistic_fm");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_factorization_log_many_factors() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 5 } };
run_exact_test({1, 8}, opts, "logistic_fm");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_factorization_log_many_categories() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 2000 },
{"n_factors", 1 } };
run_exact_test({2, 50}, opts, "logistic_fm");
}
void test_factorization_log_many_dimensions() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({16, 1, 1, 1}, opts, "logistic_fm");
}
};
struct matrix_factorization_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_mf_se_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 10 },
{"n_factors", 1 } };
run_exact_test({1, 1}, opts, "mf");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_mf_se_many_factors() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 5 } };
run_exact_test({8, 1}, opts, "mf");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_mf_se_many_categories() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({2, 50}, opts, "mf");
}
void test_mf_se_many_columns() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({16, 1, 1, 1}, opts, "mf");
}
};
struct log_mf_tests {
public:
////////////////////////////////////////////////////////////////////////////////
void test_mf_log_really_bloody_basic_2d() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 10 },
{"n_factors", 1 } };
run_exact_test({1, 1}, opts, "logistic_mf");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_mf_log_many_factors() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 5 } };
run_exact_test({5, 5}, opts, "logistic_mf");
}
// // ////////////////////////////////////////////////////////////////////////////////
void test_mf_log_many_categories() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({2, 30}, opts, "logistic_mf");
}
void test_mf_log_many_dimensions() {
std::map<std::string, flexible_type> opts = {
{"n_observations", 1000 },
{"n_factors", 1 } };
run_exact_test({16, 1, 1, 1}, opts, "logistic_mf");
}
};
struct class pure_ranking {
// public:
// void run_pure_ranking_test(size_t n_users, size_t n_items,
// size_t n_items_train, size_t n_items_test,
// std::map<std::string, flexible_type> opts,
// const std::string& model_type) {
// std::feraiseexcept(FE_ALL_EXCEPT);
// std::vector<std::string> column_names = {"user", "item"};
// opts["y_mode"] = "squared_error";
// lm_data_generator lmdata(column_names, {n_users, n_items}, opts);
// opts.erase("y_mode");
// sframe train_data, test_data;
// std::tie(train_data, test_data) = lmdata.generate_for_ranking(
// n_items_train, n_items_test, 0, 0);
// std::shared_ptr<recsys_model_base> model;
// std::map<std::string, flexible_type> options =
// { {"optimization_method", "auto"},
// {"sgd_step_size", 0},
// {"max_iterations", 20},
// {"sgd_convergence_threshold", 1e-6},
// // No target column; so should be able to properly rank
// // things.
// };
// options.insert(opts.begin(), opts.end());
// // Instantiate some alternate versions to make sure the save and load work
// typedef std::shared_ptr<recsys::recsys_model_base> model_ptr;
// auto new_model = [&]() {
// model_ptr ret;
// if(model_type == "linear" || model_type == "logistic") {
// ret.reset(new recsys_linear_model);
// } else if(model_type == "fm" || model_type == "logistic_fm") {
// ret.reset(new recsys_factorization_model);
// } else if(model_type == "mf" || model_type == "logistic_mf") {
// ret.reset(new recsys_matrix_factorization);
// } else {
// ASSERT_TRUE(false);
// }
// return ret;
// };
// model = new_model();
// model->set_options(options);
// model->setup_and_train(train_data);
// std::vector<model_ptr> all_models =
// {model,
// new_model(),
// model_ptr((recsys::recsys_model_base*)(model->clone()))};
// ////////////////////////////////////////
// {
// // Save it
// dir_archive archive_write;
// archive_write.open_directory_for_write("linear_regression_cxx_tests");
// turi::oarchive oarc(archive_write);
// oarc << *model;
// archive_write.close();
// // Load it
// dir_archive archive_read;
// archive_read.open_directory_for_read("linear_regression_cxx_tests");
// turi::iarchive iarc(archive_read);
// iarc >> (*all_models[1]);
// }
// auto build_map = [&](const sframe& user_item_data) {
// std::map<size_t, std::set<size_t> > user_map;
// for(parallel_sframe_iterator it(user_item_data); !it.done(); ++it) {
// size_t user = it.value(0);
// size_t item = it.value(1);
// user_map[user].insert(item);
// }
// return user_map;
// };
// auto true_user_map = build_map(test_data);
// for(model_ptr m : all_models) {
// sframe rec_out = m->recommend(nullptr, n_items_test);
// auto user_map = build_map(rec_out);
// for(size_t i = 0; i < n_users; ++i) {
// // ASSERT_EQ(user_map[i], true_user_map[i]);
// }
// }
// }
// void test_linear_1() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 1} };
// run_pure_ranking_test(100, 10, 2, 1, opts, "linear");
// }
// void test_linear_2() {
// std::map<std::string, flexible_type> opts;
// run_pure_ranking_test(1000, 50, 20, 5, opts, "linear");
// }
// ////////////////////////////////////////////////////////////
// // Test the different aspects of the procedure to sample negative
// // points. There a number of internal asserts to check that the
// // sampling is consistent; below are the set of things which would
// // likely hit the corner cases of the sampling algorithm.
// void test_linear_most_items_rated_1() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 1} };
// run_pure_ranking_test(1000, 32, 31, 1, opts, "linear");
// }
// void test_linear_most_items_rated_2() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 16} };
// run_pure_ranking_test(10, 32, 31, 1, opts, "linear");
// }
// void test_linear_most_items_rated_1b() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 1} };
// run_pure_ranking_test(10, 65, 63, 1, opts, "linear");
// }
// void test_linear_most_items_rated_2b() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 16} };
// run_pure_ranking_test(10, 65, 64, 1, opts, "linear");
// }
// void test_linear_most_items_rated_3() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 4} };
// run_pure_ranking_test(10, 100, 90, 4, opts, "linear");
// }
// void test_linear_few_items_rated_1() {
// std::map<std::string, flexible_type> opts = {
// {"_num_sampled_negative_examples", 4} };
// run_pure_ranking_test(10, 1000, 2, 1, opts, "linear");
// }
// ////////////////////////////////////////////////////////////
// // Test matrix factorization
// void test_mf_1() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 1 } };
// run_pure_ranking_test(10, 10, 4, 2, opts, "mf");
// }
// void test_mf_2() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 4 } };
// run_pure_ranking_test(100, 10, 4, 2, opts, "mf");
// }
// void test_mf_3() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 1 } };
// run_pure_ranking_test(10, 50, 20, 5, opts, "mf");
// }
// void test_fm_1() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 1 } };
// run_pure_ranking_test(10, 10, 4, 2, opts, "fm");
// }
// void test_fm_2() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 4 } };
// run_pure_ranking_test(100, 10, 4, 2, opts, "fm");
// }
// void test_fm_3() {
// std::map<std::string, flexible_type> opts = {
// {"n_factors", 1 } };
// run_pure_ranking_test(10, 50, 20, 5, opts, "fm");
// }
// };
BOOST_FIXTURE_TEST_SUITE(_linear_tests, linear_tests)
BOOST_AUTO_TEST_CASE(test_regression_se_really_bloody_basic_2d) {
linear_tests::test_regression_se_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_regression_se_basic_3d) {
linear_tests::test_regression_se_basic_3d();
}
BOOST_AUTO_TEST_CASE(test_regression_se_basic_5d) {
linear_tests::test_regression_se_basic_5d();
}
BOOST_AUTO_TEST_CASE(test_regression_se_multiuser_basic_2d) {
linear_tests::test_regression_se_multiuser_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_regression_se_large_no_side) {
linear_tests::test_regression_se_large_no_side();
}
BOOST_AUTO_TEST_CASE(test_regression_se_large_some_side) {
linear_tests::test_regression_se_large_some_side();
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(_log_linear_tests, log_linear_tests)
BOOST_AUTO_TEST_CASE(test_regression_log_really_bloody_basic_2d) {
log_linear_tests::test_regression_log_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_regression_log_basic_3d) {
log_linear_tests::test_regression_log_basic_3d();
}
BOOST_AUTO_TEST_CASE(test_regression_log_large_no_side) {
log_linear_tests::test_regression_log_large_no_side();
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(_factorization_tests, factorization_tests)
BOOST_AUTO_TEST_CASE(test_factorization_se_really_bloody_basic_2d) {
factorization_tests::test_factorization_se_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_factorization_se_many_factors) {
factorization_tests::test_factorization_se_many_factors();
}
BOOST_AUTO_TEST_CASE(test_factorization_se_many_columns) {
factorization_tests::test_factorization_se_many_columns();
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(_log_factorization_tests, log_factorization_tests)
BOOST_AUTO_TEST_CASE(test_factorization_log_really_bloody_basic_2d) {
log_factorization_tests::test_factorization_log_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_factorization_log_many_factors) {
log_factorization_tests::test_factorization_log_many_factors();
}
BOOST_AUTO_TEST_CASE(test_factorization_log_many_categories) {
log_factorization_tests::test_factorization_log_many_categories();
}
BOOST_AUTO_TEST_CASE(test_factorization_log_many_dimensions) {
log_factorization_tests::test_factorization_log_many_dimensions();
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(_matrix_factorization_tests, matrix_factorization_tests)
BOOST_AUTO_TEST_CASE(test_mf_se_really_bloody_basic_2d) {
matrix_factorization_tests::test_mf_se_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_mf_se_many_factors) {
matrix_factorization_tests::test_mf_se_many_factors();
}
BOOST_AUTO_TEST_CASE(test_mf_se_many_categories) {
matrix_factorization_tests::test_mf_se_many_categories();
}
BOOST_AUTO_TEST_CASE(test_mf_se_many_columns) {
matrix_factorization_tests::test_mf_se_many_columns();
}
BOOST_AUTO_TEST_SUITE_END()
BOOST_FIXTURE_TEST_SUITE(_log_mf_tests, log_mf_tests)
BOOST_AUTO_TEST_CASE(test_mf_log_really_bloody_basic_2d) {
log_mf_tests::test_mf_log_really_bloody_basic_2d();
}
BOOST_AUTO_TEST_CASE(test_mf_log_many_factors) {
log_mf_tests::test_mf_log_many_factors();
}
BOOST_AUTO_TEST_CASE(test_mf_log_many_categories) {
log_mf_tests::test_mf_log_many_categories();
}
BOOST_AUTO_TEST_CASE(test_mf_log_many_dimensions) {
log_mf_tests::test_mf_log_many_dimensions();
}
BOOST_AUTO_TEST_SUITE_END()
| 29.94197 | 102 | 0.591653 | [
"vector",
"model"
] |
f4525860654f9b18630a70309ac3cd0a90a3744f | 25,267 | cpp | C++ | src/mongo/s/collection_manager_test.cpp | wentingwang/morphus | af40299a5f07fd3157946112738f602a566a9908 | [
"Apache-2.0"
] | 5 | 2015-02-03T18:12:03.000Z | 2016-07-09T09:52:00.000Z | src/mongo/s/collection_manager_test.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | null | null | null | src/mongo/s/collection_manager_test.cpp | stennie/mongo | 9ff44ae9ad16a70e49517a78279260a37d31ac7c | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2012 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <boost/scoped_ptr.hpp>
#include <string>
#include <vector>
#include "mongo/db/jsobj.h"
#include "mongo/dbtests/mock/mock_conn_registry.h"
#include "mongo/dbtests/mock/mock_remote_db_server.h"
#include "mongo/s/chunk_version.h"
#include "mongo/s/collection_manager.h"
#include "mongo/s/metadata_loader.h"
#include "mongo/s/type_chunk.h"
#include "mongo/s/type_collection.h"
#include "mongo/unittest/unittest.h"
#include "mongo/util/net/hostandport.h"
namespace {
using boost::scoped_ptr;
using mongo::BSONObj;
using mongo::BSONArray;
using mongo::ChunkType;
using mongo::ConnectionString;
using mongo::CollectionManager;
using mongo::CollectionType;
using mongo::Date_t;
using mongo::HostAndPort;
using mongo::MAXKEY;
using mongo::MetadataLoader;
using mongo::MINKEY;
using mongo::OID;
using mongo::ChunkVersion;
using mongo::MockConnRegistry;
using mongo::MockRemoteDBServer;
using std::string;
using std::vector;
const std::string CONFIG_HOST_PORT = "$dummy_config:27017";
class NoChunkFixture : public mongo::unittest::Test {
protected:
void setUp() {
_dummyConfig.reset(new MockRemoteDBServer(CONFIG_HOST_PORT));
mongo::ConnectionString::setConnectionHook(
MockConnRegistry::get()->getConnStrHook());
MockConnRegistry::get()->addServer(_dummyConfig.get());
OID epoch = OID::gen();
_dummyConfig->insert(CollectionType::ConfigNS,
BSON(CollectionType::ns("test.foo") <<
CollectionType::keyPattern(BSON("a" << 1)) <<
CollectionType::unique(false) <<
CollectionType::updatedAt(1ULL) <<
CollectionType::epoch(epoch)));
ConnectionString configLoc(CONFIG_HOST_PORT);
MetadataLoader loader(configLoc);
_manager.reset(loader.makeCollectionManager("test.foo", "shard0000", NULL, NULL));
ASSERT(_manager.get() != NULL);
}
void tearDown() {
MockConnRegistry::get()->clear();
}
CollectionManager* getCollManager() const {
return _manager.get();
}
private:
scoped_ptr<MockRemoteDBServer> _dummyConfig;
scoped_ptr<CollectionManager> _manager;
};
TEST_F(NoChunkFixture, BasicBelongsToMe) {
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << MINKEY)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 10)));
}
TEST_F(NoChunkFixture, CompoudKeyBelongsToMe) {
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 1 << "b" << 2)));
}
TEST_F(NoChunkFixture, getNextFromEmpty) {
ChunkType nextChunk;
ASSERT(getCollManager()->getNextChunk(BSONObj(), &nextChunk));
}
TEST_F(NoChunkFixture, FirstChunkClonePlus) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10));
chunk.setMax(BSON("a" << 20));
string errMsg;
const ChunkVersion version(99, 0, OID());
scoped_ptr<CollectionManager> cloned(getCollManager()->clonePlus(
chunk, version, &errMsg));
ASSERT(errMsg.empty());
ASSERT_EQUALS(1u, cloned->getNumChunks());
ASSERT_EQUALS(cloned->getMaxShardVersion().toLong(), version.toLong());
ASSERT_EQUALS(cloned->getMaxCollVersion().toLong(), version.toLong());
ASSERT(cloned->belongsToMe(BSON("a" << 15)));
}
TEST_F(NoChunkFixture, MustHaveVersionForFirstChunk) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10));
chunk.setMax(BSON("a" << 20));
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->clonePlus(
chunk, ChunkVersion(0, 0, OID()), &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
}
/**
* Fixture with single chunk containing:
* [10->20)
*/
class SingleChunkFixture : public mongo::unittest::Test {
protected:
void setUp() {
_dummyConfig.reset(new MockRemoteDBServer(CONFIG_HOST_PORT));
mongo::ConnectionString::setConnectionHook(MockConnRegistry::get()->getConnStrHook());
MockConnRegistry::get()->addServer(_dummyConfig.get());
OID epoch = OID::gen();
ChunkVersion chunkVersion = ChunkVersion(1, 0, epoch);
BSONObj collFoo = BSON(CollectionType::ns("test.foo") <<
CollectionType::keyPattern(BSON("a" << 1)) <<
CollectionType::unique(false) <<
CollectionType::updatedAt(1ULL) <<
CollectionType::epoch(epoch));
_dummyConfig->insert(CollectionType::ConfigNS, collFoo);
BSONObj fooSingle = BSON(ChunkType::name("test.foo-a_10") <<
ChunkType::ns("test.foo") <<
ChunkType::min(BSON("a" << 10)) <<
ChunkType::max(BSON("a" << 20)) <<
ChunkType::DEPRECATED_lastmod(chunkVersion.toLong()) <<
ChunkType::DEPRECATED_epoch(epoch) <<
ChunkType::shard("shard0000"));
_dummyConfig->insert(ChunkType::ConfigNS, fooSingle);
ConnectionString configLoc(CONFIG_HOST_PORT);
MetadataLoader loader(configLoc);
_manager.reset(loader.makeCollectionManager("test.foo", "shard0000", NULL, NULL));
ASSERT(_manager.get() != NULL);
}
void tearDown() {
MockConnRegistry::get()->clear();
}
CollectionManager* getCollManager() const {
return _manager.get();
}
private:
scoped_ptr<MockRemoteDBServer> _dummyConfig;
scoped_ptr<CollectionManager> _manager;
};
TEST_F(SingleChunkFixture, BasicBelongsToMe) {
ASSERT(getCollManager()->belongsToMe(BSON("a" << 10)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 15)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 19)));
}
TEST_F(SingleChunkFixture, DoesntBelongsToMe) {
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 0)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 9)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 20)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 1234)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << MINKEY)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << MAXKEY)));
}
TEST_F(SingleChunkFixture, CompoudKeyBelongsToMe) {
ASSERT(getCollManager()->belongsToMe(BSON("a" << 15 << "a" << 14)));
}
TEST_F(SingleChunkFixture, getNextFromEmpty) {
ChunkType nextChunk;
ASSERT(getCollManager()->getNextChunk(BSONObj(), &nextChunk));
ASSERT_EQUALS(0, nextChunk.getMin().woCompare(BSON("a" << 10)));
ASSERT_EQUALS(0, nextChunk.getMax().woCompare(BSON("a" << 20)));
}
TEST_F(SingleChunkFixture, GetNextFromLast) {
ChunkType nextChunk;
ASSERT(getCollManager()->getNextChunk(BSONObj(), &nextChunk));
}
TEST_F(SingleChunkFixture, LastChunkCloneMinus) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10));
chunk.setMax(BSON("a" << 20));
string errMsg;
const ChunkVersion zeroVersion(0, 0, OID());
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneMinus(
chunk, zeroVersion, &errMsg));
ASSERT(errMsg.empty());
ASSERT_EQUALS(0u, cloned->getNumChunks());
ASSERT_EQUALS(cloned->getMaxShardVersion().toLong(), zeroVersion.toLong());
ASSERT_EQUALS(cloned->getMaxCollVersion().toLong(),
getCollManager()->getMaxCollVersion().toLong());
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 15)));
}
TEST_F(SingleChunkFixture, LastChunkMinusCantHaveNonZeroVersion) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10));
chunk.setMax(BSON("a" << 20));
string errMsg;
ChunkVersion version(99, 0, OID());
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneMinus(
chunk, version, &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
}
/**
* Fixture with single chunk containing:
* [(min, min)->(max, max))
*/
class SingleChunkMinMaxCompoundKeyFixture : public mongo::unittest::Test {
protected:
void setUp() {
_dummyConfig.reset(new MockRemoteDBServer(CONFIG_HOST_PORT));
mongo::ConnectionString::setConnectionHook(
MockConnRegistry::get()->getConnStrHook());
MockConnRegistry::get()->addServer(_dummyConfig.get());
OID epoch = OID::gen();
ChunkVersion chunkVersion = ChunkVersion(1, 0, epoch);
BSONObj collFoo = BSON(CollectionType::ns("test.foo") <<
CollectionType::keyPattern(BSON("a" << 1)) <<
CollectionType::unique(false) <<
CollectionType::updatedAt(1ULL) <<
CollectionType::epoch(epoch));
_dummyConfig->insert(CollectionType::ConfigNS, collFoo);
BSONObj fooSingle = BSON(ChunkType::name("test.foo-a_MinKey") <<
ChunkType::ns("test.foo") <<
ChunkType::min(BSON("a" << MINKEY << "b" << MINKEY)) <<
ChunkType::max(BSON("a" << MAXKEY << "b" << MAXKEY)) <<
ChunkType::DEPRECATED_lastmod(chunkVersion.toLong()) <<
ChunkType::DEPRECATED_epoch(epoch) <<
ChunkType::shard("shard0000"));
_dummyConfig->insert(ChunkType::ConfigNS, fooSingle);
ConnectionString configLoc(CONFIG_HOST_PORT);
MetadataLoader loader(configLoc);
_manager.reset(loader.makeCollectionManager("test.foo", "shard0000", NULL, NULL));
ASSERT(_manager.get() != NULL);
}
void tearDown() {
MockConnRegistry::get()->clear();
}
CollectionManager* getCollManager() const {
return _manager.get();
}
private:
scoped_ptr<MockRemoteDBServer> _dummyConfig;
scoped_ptr<CollectionManager> _manager;
};
// Note: no tests for single key belongsToMe because they are not allowed
// if shard key is compound.
TEST_F(SingleChunkMinMaxCompoundKeyFixture, CompoudKeyBelongsToMe) {
ASSERT(getCollManager()->belongsToMe(BSON("a" << MINKEY << "b" << MINKEY)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << MAXKEY << "b" << MAXKEY)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << MINKEY << "b" << 10)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 10 << "b" << 20)));
}
/**
* Fixture with chunks:
* [(10, 0)->(20, 0)), [(30, 0)->(40, 0))
*/
class TwoChunksWithGapCompoundKeyFixture : public mongo::unittest::Test {
protected:
void setUp() {
_dummyConfig.reset(new MockRemoteDBServer(CONFIG_HOST_PORT));
mongo::ConnectionString::setConnectionHook(
MockConnRegistry::get()->getConnStrHook());
MockConnRegistry::get()->addServer(_dummyConfig.get());
OID epoch = OID::gen();
ChunkVersion chunkVersion = ChunkVersion(1, 0, epoch);
BSONObj collFoo = BSON(CollectionType::ns("test.foo") <<
CollectionType::keyPattern(BSON("a" << 1)) <<
CollectionType::unique(false) <<
CollectionType::updatedAt(1ULL) <<
CollectionType::epoch(epoch));
_dummyConfig->insert(CollectionType::ConfigNS, collFoo);
_dummyConfig->insert(ChunkType::ConfigNS,
BSON(ChunkType::name("test.foo-a_10") <<
ChunkType::ns("test.foo") <<
ChunkType::min(BSON("a" << 10 << "b" << 0)) <<
ChunkType::max(BSON("a" << 20 << "b" << 0)) <<
ChunkType::DEPRECATED_lastmod(chunkVersion.toLong()) <<
ChunkType::DEPRECATED_epoch(epoch) <<
ChunkType::shard("shard0000")));
_dummyConfig->insert(ChunkType::ConfigNS,
BSON(ChunkType::name("test.foo-a_10") <<
ChunkType::ns("test.foo") <<
ChunkType::min(BSON("a" << 30 << "b" << 0)) <<
ChunkType::max(BSON("a" << 40 << "b" << 0)) <<
ChunkType::DEPRECATED_lastmod(chunkVersion.toLong()) <<
ChunkType::DEPRECATED_epoch(epoch) <<
ChunkType::shard("shard0000")));
ConnectionString configLoc(CONFIG_HOST_PORT);
MetadataLoader loader(configLoc);
_manager.reset(loader.makeCollectionManager("test.foo", "shard0000",
NULL, NULL));
ASSERT(_manager.get() != NULL);
}
void tearDown() {
MockConnRegistry::get()->clear();
}
CollectionManager* getCollManager() const {
return _manager.get();
}
private:
scoped_ptr<MockRemoteDBServer> _dummyConfig;
scoped_ptr<CollectionManager> _manager;
};
TEST_F(TwoChunksWithGapCompoundKeyFixture, ClonePlusBasic) {
ChunkType chunk;
chunk.setMin(BSON("a" << 40 << "b" << 0));
chunk.setMax(BSON("a" << 50 << "b" << 0));
string errMsg;
ChunkVersion version(1, 0, OID());
scoped_ptr<CollectionManager> cloned(getCollManager()->clonePlus(
chunk, version, &errMsg));
ASSERT(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
ASSERT_EQUALS(3u, cloned->getNumChunks());
// TODO: test maxShardVersion, maxCollVersion
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 25 << "b" << 0)));
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 29 << "b" << 0)));
ASSERT(cloned->belongsToMe(BSON("a" << 30 << "b" << 0)));
ASSERT(cloned->belongsToMe(BSON("a" << 45 << "b" << 0)));
ASSERT(cloned->belongsToMe(BSON("a" << 49 << "b" << 0)));
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 50 << "b" << 0)));
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, ClonePlusOverlappingRange) {
ChunkType chunk;
chunk.setMin(BSON("a" << 15 << "b" << 0));
chunk.setMax(BSON("a" << 25 << "b" << 0));
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->clonePlus(chunk,
ChunkVersion(1, 0, OID()), &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, CloneMinusBasic) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10 << "b" << 0));
chunk.setMax(BSON("a" << 20 << "b" << 0));
string errMsg;
ChunkVersion version(1, 0, OID());
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneMinus(
chunk, version, &errMsg));
ASSERT(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
ASSERT_EQUALS(1u, cloned->getNumChunks());
// TODO: test maxShardVersion, maxCollVersion
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 5 << "b" << 0)));
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 15 << "b" << 0)));
ASSERT(cloned->belongsToMe(BSON("a" << 30 << "b" << 0)));
ASSERT(cloned->belongsToMe(BSON("a" << 35 << "b" << 0)));
ASSERT_FALSE(cloned->belongsToMe(BSON("a" << 40 << "b" << 0)));
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, CloneMinusNonExisting) {
ChunkType chunk;
chunk.setMin(BSON("a" << 25 << "b" << 0));
chunk.setMax(BSON("a" << 28 << "b" << 0));
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneMinus(chunk,
ChunkVersion(1, 0, OID()), &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, CloneSplitBasic) {
const BSONObj min(BSON("a" << 10 << "b" << 0));
const BSONObj max(BSON("a" << 20 << "b" << 0));
ChunkType chunk;
chunk.setMin(min);
chunk.setMax(max);
const BSONObj split1(BSON("a" << 15 << "b" << 0));
const BSONObj split2(BSON("a" << 18 << "b" << 0));
vector<BSONObj> splitKeys;
splitKeys.push_back(split1);
splitKeys.push_back(split2);
ChunkVersion version(1, 99, OID()); // first chunk 1|99 , second 1|100
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneSplit(chunk, splitKeys,
version, &errMsg));
version.incMinor(); /* second chunk 1|100, first split point */
version.incMinor(); /* third chunk 1|101, second split point */
ASSERT_EQUALS(cloned->getMaxShardVersion().toLong(), version.toLong() /* 1|101 */ );
ASSERT_EQUALS(cloned->getMaxCollVersion().toLong(), version.toLong());
ASSERT_EQUALS(getCollManager()->getNumChunks(), 2u);
ASSERT_EQUALS(cloned->getNumChunks(), 4u);
ASSERT(cloned->belongsToMe(min));
ASSERT(cloned->belongsToMe(split1));
ASSERT(cloned->belongsToMe(split2));
ASSERT(!cloned->belongsToMe(max));
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, CloneSplitOutOfRangeSplitPoint) {
ChunkType chunk;
chunk.setMin(BSON("a" << 10 << "b" << 0));
chunk.setMax(BSON("a" << 20 << "b" << 0));
vector<BSONObj> splitKeys;
splitKeys.push_back(BSON("a" << 5 << "b" << 0));
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneSplit(chunk, splitKeys,
ChunkVersion(1, 0, OID()), &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
}
TEST_F(TwoChunksWithGapCompoundKeyFixture, CloneSplitBadChunkRange) {
const BSONObj min(BSON("a" << 10 << "b" << 0));
const BSONObj max(BSON("a" << 25 << "b" << 0));
ChunkType chunk;
chunk.setMin(BSON("a" << 10 << "b" << 0));
chunk.setMax(BSON("a" << 25 << "b" << 0));
vector<BSONObj> splitKeys;
splitKeys.push_back(BSON("a" << 15 << "b" << 0));
string errMsg;
scoped_ptr<CollectionManager> cloned(getCollManager()->cloneSplit(chunk, splitKeys,
ChunkVersion(1, 0, OID()), &errMsg));
ASSERT(cloned == NULL);
ASSERT_FALSE(errMsg.empty());
ASSERT_EQUALS(2u, getCollManager()->getNumChunks());
}
/**
* Fixture with chunk containing:
* [min->10) , [10->20) , <gap> , [30->max)
*/
class ThreeChunkWithRangeGapFixture : public mongo::unittest::Test {
protected:
void setUp() {
_dummyConfig.reset(new MockRemoteDBServer(CONFIG_HOST_PORT));
mongo::ConnectionString::setConnectionHook(
MockConnRegistry::get()->getConnStrHook());
MockConnRegistry::get()->addServer(_dummyConfig.get());
OID epoch(OID::gen());
_dummyConfig->insert(CollectionType::ConfigNS,
BSON(CollectionType::ns("x.y") <<
CollectionType::dropped(false) <<
CollectionType::keyPattern(BSON("a" << 1)) <<
CollectionType::unique(false) <<
CollectionType::updatedAt(1ULL) <<
CollectionType::epoch(epoch)));
{
ChunkVersion version(1, 1, epoch);
_dummyConfig->insert(ChunkType::ConfigNS,
BSON(ChunkType::name("x.y-a_MinKey") <<
ChunkType::ns("x.y") <<
ChunkType::min(BSON("a" << MINKEY)) <<
ChunkType::max(BSON("a" << 10)) <<
ChunkType::DEPRECATED_lastmod(version.toLong()) <<
ChunkType::DEPRECATED_epoch(version.epoch()) <<
ChunkType::shard("shard0000")));
}
{
ChunkVersion version(1, 3, epoch);
_dummyConfig->insert(ChunkType::ConfigNS,
BSON(ChunkType::name("x.y-a_10") <<
ChunkType::ns("x.y") <<
ChunkType::min(BSON("a" << 10)) <<
ChunkType::max(BSON("a" << 20)) <<
ChunkType::DEPRECATED_lastmod(version.toLong()) <<
ChunkType::DEPRECATED_epoch(version.epoch()) <<
ChunkType::shard("shard0000")));
}
{
ChunkVersion version(1, 2, epoch);
_dummyConfig->insert(ChunkType::ConfigNS,
BSON(ChunkType::name("x.y-a_30") <<
ChunkType::ns("x.y") <<
ChunkType::min(BSON("a" << 30)) <<
ChunkType::max(BSON("a" << MAXKEY)) <<
ChunkType::DEPRECATED_lastmod(version.toLong()) <<
ChunkType::DEPRECATED_epoch(version.epoch()) <<
ChunkType::shard("shard0000")));
}
ConnectionString configLoc(CONFIG_HOST_PORT);
MetadataLoader loader(configLoc);
string errmsg;
_manager.reset(loader.makeCollectionManager("test.foo", "shard0000",
NULL, &errmsg));
ASSERT(_manager.get() != NULL);
}
void tearDown() {
MockConnRegistry::get()->clear();
}
CollectionManager* getCollManager() const {
return _manager.get();
}
private:
scoped_ptr<MockRemoteDBServer> _dummyConfig;
scoped_ptr<CollectionManager> _manager;
};
TEST_F(ThreeChunkWithRangeGapFixture, ShardOwnsDoc) {
ASSERT(getCollManager()->belongsToMe(BSON("a" << 5)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 10)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 30)));
ASSERT(getCollManager()->belongsToMe(BSON("a" << 40)));
}
TEST_F(ThreeChunkWithRangeGapFixture, ShardDoesntOwnDoc) {
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << 25)));
ASSERT_FALSE(getCollManager()->belongsToMe(BSON("a" << MAXKEY)));
}
TEST_F(ThreeChunkWithRangeGapFixture, GetNextFromEmpty) {
ChunkType nextChunk;
ASSERT_FALSE(getCollManager()->getNextChunk(BSONObj(), &nextChunk));
ASSERT_EQUALS(0, nextChunk.getMin().woCompare(BSON("a" << MINKEY)));
ASSERT_EQUALS(0, nextChunk.getMax().woCompare(BSON("a" << 10)));
}
TEST_F(ThreeChunkWithRangeGapFixture, GetNextFromMiddle) {
ChunkType nextChunk;
ASSERT_FALSE(getCollManager()->getNextChunk(BSON("a" << 10), &nextChunk));
ASSERT_EQUALS(0, nextChunk.getMin().woCompare(BSON("a" << 30)));
ASSERT_EQUALS(0, nextChunk.getMax().woCompare(BSON("a" << MAXKEY)));
}
TEST_F(ThreeChunkWithRangeGapFixture, GetNextFromLast) {
ChunkType nextChunk;
ASSERT(getCollManager()->getNextChunk(BSON("a" << 30), &nextChunk));
}
} // unnamed namespace
| 40.885113 | 98 | 0.555586 | [
"vector"
] |
f459fe49b9d3d14b46fd31ced3cc9ebcaf2f9d3c | 24,685 | cpp | C++ | src/mongo/dbtests/query_stage_cached_plan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/query_stage_cached_plan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | src/mongo/dbtests/query_stage_cached_plan.cpp | benety/mongo | 203430ac9559f82ca01e3cbb3b0e09149fec0835 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* 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
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#include "mongo/platform/basic.h"
#include <memory>
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/catalog/collection.h"
#include "mongo/db/catalog/database.h"
#include "mongo/db/catalog/database_holder.h"
#include "mongo/db/client.h"
#include "mongo/db/db_raii.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/exec/cached_plan.h"
#include "mongo/db/exec/mock_stage.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/json.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/query/canonical_query.h"
#include "mongo/db/query/collection_query_info.h"
#include "mongo/db/query/get_executor.h"
#include "mongo/db/query/mock_yield_policies.h"
#include "mongo/db/query/plan_cache.h"
#include "mongo/db/query/plan_cache_key_factory.h"
#include "mongo/db/query/query_knobs_gen.h"
#include "mongo/db/query/query_planner_params.h"
#include "mongo/dbtests/dbtests.h"
namespace QueryStageCachedPlan {
static const NamespaceString nss("unittests.QueryStageCachedPlan");
namespace {
std::unique_ptr<CanonicalQuery> canonicalQueryFromFilterObj(OperationContext* opCtx,
const NamespaceString& nss,
BSONObj filter) {
auto findCommand = std::make_unique<FindCommandRequest>(nss);
findCommand->setFilter(filter);
auto statusWithCQ = CanonicalQuery::canonicalize(opCtx, std::move(findCommand));
uassertStatusOK(statusWithCQ.getStatus());
return std::move(statusWithCQ.getValue());
}
} // namespace
class QueryStageCachedPlan : public unittest::Test {
public:
QueryStageCachedPlan() : _client(&_opCtx) {}
void setUp() {
// If collection exists already, we need to drop it.
dropCollection();
// Add indices.
addIndex(BSON("a" << 1));
addIndex(BSON("b" << 1));
dbtests::WriteContextForTests ctx(&_opCtx, nss.ns());
CollectionPtr collection = ctx.getCollection();
ASSERT(collection);
// Add data.
for (int i = 0; i < 10; i++) {
insertDocument(collection, BSON("_id" << i << "a" << i << "b" << 1));
}
}
void addIndex(const BSONObj& obj) {
ASSERT_OK(dbtests::createIndex(&_opCtx, nss.ns(), obj));
}
void dropIndex(BSONObj keyPattern) {
_client.dropIndex(nss.ns(), std::move(keyPattern));
}
void dropCollection() {
Lock::DBLock dbLock(&_opCtx, nss.db(), MODE_X);
auto databaseHolder = DatabaseHolder::get(&_opCtx);
auto database = databaseHolder->getDb(&_opCtx, nss.dbName());
if (!database) {
return;
}
WriteUnitOfWork wuow(&_opCtx);
database->dropCollection(&_opCtx, nss).transitional_ignore();
wuow.commit();
}
void insertDocument(const CollectionPtr& collection, BSONObj obj) {
WriteUnitOfWork wuow(&_opCtx);
OpDebug* const nullOpDebug = nullptr;
ASSERT_OK(collection->insertDocument(&_opCtx, InsertStatement(obj), nullOpDebug));
wuow.commit();
}
OperationContext* opCtx() {
return &_opCtx;
}
static size_t getNumResultsForStage(const WorkingSet& ws,
CachedPlanStage* cachedPlanStage,
CanonicalQuery* cq) {
size_t numResults = 0;
PlanStage::StageState state = PlanStage::NEED_TIME;
while (state != PlanStage::IS_EOF) {
WorkingSetID id = WorkingSet::INVALID_ID;
state = cachedPlanStage->work(&id);
if (state == PlanStage::ADVANCED) {
auto member = ws.get(id);
ASSERT(cq->root()->matchesBSON(member->doc.value().toBson()));
numResults++;
}
}
return numResults;
}
void forceReplanning(const CollectionPtr& collection, CanonicalQuery* cq) {
// Get planner params.
QueryPlannerParams plannerParams;
fillOutPlannerParams(&_opCtx, collection, cq, &plannerParams);
const size_t decisionWorks = 10;
const size_t mockWorks =
1U + static_cast<size_t>(internalQueryCacheEvictionRatio * decisionWorks);
auto mockChild = std::make_unique<MockStage>(_expCtx.get(), &_ws);
for (size_t i = 0; i < mockWorks; i++) {
mockChild->enqueueStateCode(PlanStage::NEED_TIME);
}
CachedPlanStage cachedPlanStage(_expCtx.get(),
collection,
&_ws,
cq,
plannerParams,
decisionWorks,
std::move(mockChild));
// This should succeed after triggering a replan.
NoopYieldPolicy yieldPolicy(_opCtx.getServiceContext()->getFastClockSource());
ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy));
}
protected:
const ServiceContext::UniqueOperationContext _opCtxPtr = cc().makeOperationContext();
OperationContext& _opCtx = *_opCtxPtr;
WorkingSet _ws;
DBDirectClient _client{&_opCtx};
boost::intrusive_ptr<ExpressionContext> _expCtx =
make_intrusive<ExpressionContext>(&_opCtx, nullptr, nss);
};
/**
* Test that on a memory limit exceeded failure, the cached plan stage replans the query but does
* not create a new cache entry.
*/
TEST_F(QueryStageCachedPlan, QueryStageCachedPlanFailureMemoryLimitExceeded) {
AutoGetCollectionForReadCommand collection(&_opCtx, nss);
ASSERT(collection);
// Query can be answered by either index on "a" or index on "b".
auto findCommand = std::make_unique<FindCommandRequest>(nss);
findCommand->setFilter(fromjson("{a: {$gte: 8}, b: 1}"));
auto statusWithCQ = CanonicalQuery::canonicalize(opCtx(), std::move(findCommand));
ASSERT_OK(statusWithCQ.getStatus());
const std::unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
auto key = plan_cache_key_factory::make<PlanCacheKey>(*cq, collection.getCollection());
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection.getCollection()).getPlanCache();
ASSERT(cache);
ASSERT_EQ(cache->get(key).state, PlanCache::CacheEntryState::kNotPresent);
// Get planner params.
QueryPlannerParams plannerParams;
fillOutPlannerParams(&_opCtx, collection.getCollection(), cq.get(), &plannerParams);
// Mock stage will return a failure during the cached plan trial period.
auto mockChild = std::make_unique<MockStage>(_expCtx.get(), &_ws);
mockChild->enqueueError(
Status{ErrorCodes::QueryExceededMemoryLimitNoDiskUseAllowed, "mock error"});
// High enough so that we shouldn't trigger a replan based on works.
const size_t decisionWorks = 50;
CachedPlanStage cachedPlanStage(_expCtx.get(),
collection.getCollection(),
&_ws,
cq.get(),
plannerParams,
decisionWorks,
std::move(mockChild));
// This should succeed after triggering a replan.
NoopYieldPolicy yieldPolicy(_opCtx.getServiceContext()->getFastClockSource());
ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy));
ASSERT_EQ(getNumResultsForStage(_ws, &cachedPlanStage, cq.get()), 2U);
// Plan cache should still be empty, as we don't write to it when we replan a failed
// query.
ASSERT_EQ(cache->get(key).state, PlanCache::CacheEntryState::kNotPresent);
}
/**
* Test that hitting the cached plan stage trial period's threshold for work cycles causes the
* query to be replanned. Also verify that the replanning results in a new plan cache entry.
*/
TEST_F(QueryStageCachedPlan, QueryStageCachedPlanHitMaxWorks) {
AutoGetCollectionForReadCommand collection(&_opCtx, nss);
ASSERT(collection);
// Query can be answered by either index on "a" or index on "b".
auto findCommand = std::make_unique<FindCommandRequest>(nss);
findCommand->setFilter(fromjson("{a: {$gte: 8}, b: 1}"));
auto statusWithCQ = CanonicalQuery::canonicalize(opCtx(), std::move(findCommand));
ASSERT_OK(statusWithCQ.getStatus());
const std::unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
auto key = plan_cache_key_factory::make<PlanCacheKey>(*cq, collection.getCollection());
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection.getCollection()).getPlanCache();
ASSERT(cache);
ASSERT_EQ(cache->get(key).state, PlanCache::CacheEntryState::kNotPresent);
// Get planner params.
QueryPlannerParams plannerParams;
fillOutPlannerParams(&_opCtx, collection.getCollection(), cq.get(), &plannerParams);
// Set up queued data stage to take a long time before returning EOF. Should be long
// enough to trigger a replan.
const size_t decisionWorks = 10;
const size_t mockWorks =
1U + static_cast<size_t>(internalQueryCacheEvictionRatio * decisionWorks);
auto mockChild = std::make_unique<MockStage>(_expCtx.get(), &_ws);
for (size_t i = 0; i < mockWorks; i++) {
mockChild->enqueueStateCode(PlanStage::NEED_TIME);
}
CachedPlanStage cachedPlanStage(_expCtx.get(),
collection.getCollection(),
&_ws,
cq.get(),
plannerParams,
decisionWorks,
std::move(mockChild));
// This should succeed after triggering a replan.
NoopYieldPolicy yieldPolicy(_opCtx.getServiceContext()->getFastClockSource());
ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy));
ASSERT_EQ(getNumResultsForStage(_ws, &cachedPlanStage, cq.get()), 2U);
// This time we expect to find something in the plan cache. Replans after hitting the
// works threshold result in a cache entry.
ASSERT_EQ(cache->get(key).state, PlanCache::CacheEntryState::kPresentInactive);
}
/**
* Test the way cache entries are added (either "active" or "inactive") to the plan cache.
*/
TEST_F(QueryStageCachedPlan, QueryStageCachedPlanAddsActiveCacheEntries) {
AutoGetCollectionForReadCommand collection(&_opCtx, nss);
ASSERT(collection);
// Never run - just used as a key for the cache's get() functions, since all of the other
// CanonicalQueries created in this test will have this shape.
const auto shapeCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 123}, b: {$gte: 123}}"));
auto planCacheKey =
plan_cache_key_factory::make<PlanCacheKey>(*shapeCq, collection.getCollection());
// Query can be answered by either index on "a" or index on "b".
const auto noResultsCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 11}, b: {$gte: 11}}"));
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection.getCollection()).getPlanCache();
ASSERT(cache);
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kNotPresent);
// Run the CachedPlanStage with a long-running child plan. Replanning should be
// triggered and an inactive entry will be added.
forceReplanning(collection.getCollection(), noResultsCq.get());
// Check for an inactive cache entry.
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentInactive);
// The works should be 1 for the entry since the query we ran should not have any results.
auto entry = assertGet(cache->getEntry(planCacheKey));
size_t works = 1U;
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), works);
const size_t kExpectedNumWorks = 10;
for (int i = 0; i < std::ceil(std::log(kExpectedNumWorks) / std::log(2)); ++i) {
works *= 2;
// Run another query of the same shape, which is less selective, and therefore takes
// longer).
auto someResultsCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 1}, b: {$gte: 0}}"));
forceReplanning(collection.getCollection(), someResultsCq.get());
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentInactive);
// The works on the cache entry should have doubled.
entry = assertGet(cache->getEntry(planCacheKey));
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), works);
}
// Run another query which takes less time, and be sure an active entry is created.
auto fewResultsCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 6}, b: {$gte: 0}}"));
forceReplanning(collection.getCollection(), fewResultsCq.get());
// Now there should be an active cache entry.
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentActive);
entry = assertGet(cache->getEntry(planCacheKey));
// This will query will match {a: 6} through {a:9} (4 works), plus one for EOF = 5 works.
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), 5U);
}
TEST_F(QueryStageCachedPlan, DeactivatesEntriesOnReplan) {
AutoGetCollectionForReadCommand collection(&_opCtx, nss);
ASSERT(collection);
// Never run - just used as a key for the cache's get() functions, since all of the other
// CanonicalQueries created in this test will have this shape.
const auto shapeCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 123}, b: {$gte: 123}}"));
auto planCacheKey =
plan_cache_key_factory::make<PlanCacheKey>(*shapeCq, collection.getCollection());
// Query can be answered by either index on "a" or index on "b".
const auto noResultsCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 11}, b: {$gte: 11}}"));
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection.getCollection()).getPlanCache();
ASSERT(cache);
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kNotPresent);
// Run the CachedPlanStage with a long-running child plan. Replanning should be
// triggered and an inactive entry will be added.
forceReplanning(collection.getCollection(), noResultsCq.get());
// Check for an inactive cache entry.
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentInactive);
// Run the plan again, to create an active entry.
forceReplanning(collection.getCollection(), noResultsCq.get());
// The works should be 1 for the entry since the query we ran should not have any results.
ASSERT_EQ(cache
->get(plan_cache_key_factory::make<PlanCacheKey>(*noResultsCq,
collection.getCollection()))
.state,
PlanCache::CacheEntryState::kPresentActive);
auto entry = assertGet(cache->getEntry(planCacheKey));
size_t works = 1U;
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), works);
// Run another query which takes long enough to evict the active cache entry. The current
// cache entry's works value is a very low number. When replanning is triggered, the cache
// entry will be deactivated, but the new plan will not overwrite it, since the new plan will
// have a higher works. Therefore, we will be left in an inactive entry which has had its works
// value doubled from 1 to 2.
auto highWorksCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 0}, b: {$gte:0}}"));
forceReplanning(collection.getCollection(), highWorksCq.get());
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentInactive);
entry = assertGet(cache->getEntry(planCacheKey));
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), 2U);
// Again, force replanning. This time run the initial query which finds no results. The multi
// planner will choose a plan with works value lower than the existing inactive
// entry. Replanning will thus deactivate the existing entry (it's already
// inactive so this is a noop), then create a new entry with a works value of 1.
forceReplanning(collection.getCollection(), noResultsCq.get());
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentActive);
entry = assertGet(cache->getEntry(planCacheKey));
ASSERT_TRUE(entry->works);
ASSERT_EQ(entry->works.get(), 1U);
}
TEST_F(QueryStageCachedPlan, EntriesAreNotDeactivatedWhenInactiveEntriesDisabled) {
// Set the global flag for disabling active entries.
internalQueryCacheDisableInactiveEntries.store(true);
ON_BLOCK_EXIT([] { internalQueryCacheDisableInactiveEntries.store(false); });
AutoGetCollectionForReadCommand collection(&_opCtx, nss);
ASSERT(collection);
// Never run - just used as a key for the cache's get() functions, since all of the other
// CanonicalQueries created in this test will have this shape.
const auto shapeCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 123}, b: {$gte: 123}}"));
auto planCacheKey =
plan_cache_key_factory::make<PlanCacheKey>(*shapeCq, collection.getCollection());
// Query can be answered by either index on "a" or index on "b".
const auto noResultsCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 11}, b: {$gte: 11}}"));
auto noResultKey =
plan_cache_key_factory::make<PlanCacheKey>(*noResultsCq, collection.getCollection());
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection.getCollection()).getPlanCache();
ASSERT(cache);
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kNotPresent);
// Run the CachedPlanStage with a long-running child plan. Replanning should be
// triggered and an _active_ entry will be added (since the disableInactiveEntries flag is on).
forceReplanning(collection.getCollection(), noResultsCq.get());
// Check for an inactive cache entry.
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentActive);
// Run the plan again. The entry should still be active.
forceReplanning(collection.getCollection(), noResultsCq.get());
ASSERT_EQ(cache->get(noResultKey).state, PlanCache::CacheEntryState::kPresentActive);
// Run another query which takes long enough to evict the active cache entry. After replanning
// is triggered, be sure that the the cache entry is still active.
auto highWorksCq =
canonicalQueryFromFilterObj(opCtx(), nss, fromjson("{a: {$gte: 0}, b: {$gte:0}}"));
forceReplanning(collection.getCollection(), highWorksCq.get());
ASSERT_EQ(cache->get(planCacheKey).state, PlanCache::CacheEntryState::kPresentActive);
}
TEST_F(QueryStageCachedPlan, ThrowsOnYieldRecoveryWhenIndexIsDroppedBeforePlanSelection) {
// Create an index which we will drop later on.
BSONObj keyPattern = BSON("c" << 1);
addIndex(keyPattern);
boost::optional<AutoGetCollectionForReadCommand> readLock;
readLock.emplace(&_opCtx, nss);
const auto& collection = readLock->getCollection();
ASSERT(collection);
// Query can be answered by either index on "a" or index on "b".
auto findCommand = std::make_unique<FindCommandRequest>(nss);
auto statusWithCQ = CanonicalQuery::canonicalize(opCtx(), std::move(findCommand));
ASSERT_OK(statusWithCQ.getStatus());
const std::unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection).getPlanCache();
ASSERT(cache);
// Get planner params.
QueryPlannerParams plannerParams;
fillOutPlannerParams(&_opCtx, collection, cq.get(), &plannerParams);
const size_t decisionWorks = 10;
CachedPlanStage cachedPlanStage(_expCtx.get(),
collection,
&_ws,
cq.get(),
plannerParams,
decisionWorks,
std::make_unique<MockStage>(_expCtx.get(), &_ws));
// Drop an index while the CachedPlanStage is in a saved state. Restoring should fail, since we
// may still need the dropped index for plan selection.
cachedPlanStage.saveState();
readLock.reset();
dropIndex(keyPattern);
readLock.emplace(&_opCtx, nss);
ASSERT_THROWS_CODE(cachedPlanStage.restoreState(&readLock->getCollection()),
DBException,
ErrorCodes::QueryPlanKilled);
}
TEST_F(QueryStageCachedPlan, DoesNotThrowOnYieldRecoveryWhenIndexIsDroppedAferPlanSelection) {
// Create an index which we will drop later on.
BSONObj keyPattern = BSON("c" << 1);
addIndex(keyPattern);
boost::optional<AutoGetCollectionForReadCommand> readLock;
readLock.emplace(&_opCtx, nss);
const auto& collection = readLock->getCollection();
ASSERT(collection);
// Query can be answered by either index on "a" or index on "b".
auto findCommand = std::make_unique<FindCommandRequest>(nss);
auto statusWithCQ = CanonicalQuery::canonicalize(opCtx(), std::move(findCommand));
ASSERT_OK(statusWithCQ.getStatus());
const std::unique_ptr<CanonicalQuery> cq = std::move(statusWithCQ.getValue());
// We shouldn't have anything in the plan cache for this shape yet.
PlanCache* cache = CollectionQueryInfo::get(collection).getPlanCache();
ASSERT(cache);
// Get planner params.
QueryPlannerParams plannerParams;
fillOutPlannerParams(&_opCtx, collection, cq.get(), &plannerParams);
const size_t decisionWorks = 10;
CachedPlanStage cachedPlanStage(_expCtx.get(),
collection,
&_ws,
cq.get(),
plannerParams,
decisionWorks,
std::make_unique<MockStage>(_expCtx.get(), &_ws));
NoopYieldPolicy yieldPolicy(_opCtx.getServiceContext()->getFastClockSource());
ASSERT_OK(cachedPlanStage.pickBestPlan(&yieldPolicy));
// Drop an index while the CachedPlanStage is in a saved state. We should be able to restore
// successfully.
cachedPlanStage.saveState();
readLock.reset();
dropIndex(keyPattern);
readLock.emplace(&_opCtx, nss);
cachedPlanStage.restoreState(&readLock->getCollection());
}
} // namespace QueryStageCachedPlan
| 44.638336 | 99 | 0.66745 | [
"shape"
] |
f46090bc0914ad4a3d6a7303f770038bc54f06e7 | 112,982 | cpp | C++ | plugins/protein_cuda/src/SombreroWarper.cpp | sellendk/megamol | 0e4840b1897706c861946992ce3524bafab53352 | [
"BSD-3-Clause"
] | null | null | null | plugins/protein_cuda/src/SombreroWarper.cpp | sellendk/megamol | 0e4840b1897706c861946992ce3524bafab53352 | [
"BSD-3-Clause"
] | null | null | null | plugins/protein_cuda/src/SombreroWarper.cpp | sellendk/megamol | 0e4840b1897706c861946992ce3524bafab53352 | [
"BSD-3-Clause"
] | null | null | null | /*
* TunnelCutter.h
* Copyright (C) 2006-2017 by MegaMol Team
* Alle Rechte vorbehalten.
*/
#include "stdafx.h"
#include "SombreroWarper.h"
#include <chrono>
#include <climits>
#include <iostream>
#include <limits>
#include <map>
#include "geometry_calls/CallTriMeshData.h"
#include "mmcore/param/BoolParam.h"
#include "mmcore/param/EnumParam.h"
#include "mmcore/param/FloatParam.h"
#include "mmcore/param/IntParam.h"
#include "protein_calls/BindingSiteCall.h"
#include "protein_calls/TunnelResidueDataCall.h"
#include "vislib/math/Matrix.h"
#include "vislib/math/ShallowPoint.h"
using namespace megamol;
using namespace megamol::core;
using namespace megamol::geocalls;
using namespace megamol::protein_cuda;
using namespace megamol::protein_calls;
//#define NO_DEFORMATION
//#define SWEAT
/*
* SombreroWarper::SombreroWarper
*/
SombreroWarper::SombreroWarper(void)
: Module()
, meshInSlot("dataIn", "Receives the input mesh")
, tunnelInSlot("tunnelIn", "Receives the tunnel data")
, warpedMeshOutSlot("getData", "Returns the mesh data of the wanted area")
, minBrimLevelParam("minBrimLevel", "Minimal vertex level to count as brim.")
, maxBrimLevelParam("maxBrimLevel",
"Maximal vertex level to count as brim. A value of -1 sets the value to the maximal available level")
, liftingTargetDistance("meshDeformation::liftingTargetDistance",
"The distance that is applied to a vertex during the lifting process.")
, maxAllowedLiftingDistance(
"meshDeformation::maxAllowedDistance", "The maximum allowed distance before vertex lifting is performed.")
, flatteningParam("flat", "Flat representation of the result")
, southBorderWeightParam("southBorderWeight",
"Weight of the southern border. This parameter influences the optical quality of the "
"tip of the head. Do not change unless you know what you do.")
, southBorderHeightFactor("southBorderHeight", "Height factor for the souther border vertices.")
, invertNormalParam("invertNormals", "Inverts the surface normals")
, fixMeshParam("fixMesh", "If enabled, the module tries to fix outlier vertices")
, meshFixDistanceParam("fixDistance", "Maximal distance between vertices before being considered as outlier")
, radiusSelectionSlot("radiusVariant", "Select the radius computation method")
, brimScalingParam("scale::brimScaling", "Scaling factor for the brim radius")
, radiusScalingParam("scale::radiusScaling", "Scaling factor for the sombrero radius")
, lengthScalingParam("scale::lengthScaling", "Scaling factor for the sombrero length") {
// Callee slot
this->warpedMeshOutSlot.SetCallback(
CallTriMeshData::ClassName(), CallTriMeshData::FunctionName(0), &SombreroWarper::getData);
this->warpedMeshOutSlot.SetCallback(
CallTriMeshData::ClassName(), CallTriMeshData::FunctionName(1), &SombreroWarper::getExtent);
this->MakeSlotAvailable(&this->warpedMeshOutSlot);
// Caller slots
this->meshInSlot.SetCompatibleCall<CallTriMeshDataDescription>();
this->MakeSlotAvailable(&this->meshInSlot);
this->tunnelInSlot.SetCompatibleCall<TunnelResidueDataCallDescription>();
this->MakeSlotAvailable(&this->tunnelInSlot);
// Param slots
this->minBrimLevelParam.SetParameter(new param::IntParam(1, 1, 100));
this->MakeSlotAvailable(&this->minBrimLevelParam);
this->maxBrimLevelParam.SetParameter(new param::IntParam(-1, -1, 100));
this->MakeSlotAvailable(&this->maxBrimLevelParam);
this->liftingTargetDistance.SetParameter(new param::IntParam(2, 2, 10));
this->MakeSlotAvailable(&this->liftingTargetDistance);
this->maxAllowedLiftingDistance.SetParameter(new param::IntParam(2, 2, 10));
this->MakeSlotAvailable(&this->maxAllowedLiftingDistance);
this->flatteningParam.SetParameter(new param::BoolParam(false));
this->MakeSlotAvailable(&this->flatteningParam);
this->southBorderWeightParam.SetParameter(new param::IntParam(5, 1, 200));
this->MakeSlotAvailable(&this->southBorderWeightParam);
this->southBorderHeightFactor.SetParameter(new param::FloatParam(0.5f, 0.0f, 1.0f));
this->MakeSlotAvailable(&this->southBorderHeightFactor);
this->invertNormalParam.SetParameter(new param::BoolParam(false));
this->MakeSlotAvailable(&this->invertNormalParam);
this->meshFixDistanceParam.SetParameter(new param::FloatParam(2.0f, 0.01f));
this->MakeSlotAvailable(&this->meshFixDistanceParam);
this->fixMeshParam.SetParameter(new param::BoolParam(false));
this->MakeSlotAvailable(&this->fixMeshParam);
param::EnumParam* ep = new param::EnumParam(0);
ep->SetTypePair(0, "Geometry-based");
ep->SetTypePair(1, "Exit radius");
ep->SetTypePair(2, "Bottleneck radius");
this->radiusSelectionSlot << ep;
this->MakeSlotAvailable(&this->radiusSelectionSlot);
this->brimScalingParam.SetParameter(new param::FloatParam(1.0f, 0.0f));
this->MakeSlotAvailable(&this->brimScalingParam);
this->radiusScalingParam.SetParameter(new param::FloatParam(1.0f, 0.0f));
this->MakeSlotAvailable(&this->radiusScalingParam);
this->lengthScalingParam.SetParameter(new param::FloatParam(1.0f, 0.0f));
this->MakeSlotAvailable(&this->lengthScalingParam);
this->lastDataHash = 0;
this->hashOffset = 0;
this->dirtyFlag = false;
this->cuda_kernels = std::unique_ptr<SombreroKernels>(new SombreroKernels());
}
/*
* SombreroWarper::~SombreroWarper
*/
SombreroWarper::~SombreroWarper(void) { this->Release(); }
/*
* SombreroWarper::create
*/
bool SombreroWarper::create(void) { return true; }
/*
* SombreroWarper::release
*/
void SombreroWarper::release(void) {}
/*
* SombreroWarper::getData
*/
bool SombreroWarper::getData(Call& call) {
CallTriMeshData* outCall = dynamic_cast<CallTriMeshData*>(&call);
if (outCall == nullptr) return false;
CallTriMeshData* inCall = this->meshInSlot.CallAs<CallTriMeshData>();
if (inCall == nullptr) return false;
TunnelResidueDataCall* tunnelCall = this->tunnelInSlot.CallAs<TunnelResidueDataCall>();
if (tunnelCall == nullptr) return false;
inCall->SetFrameID(outCall->FrameID());
tunnelCall->SetFrameID(outCall->FrameID());
outCall->SetObjects(static_cast<uint>(this->outMeshVector.size()), this->outMeshVector.data());
// if (this->outMeshVector.size() > 0) {
// printf("Length: %f ; Radius: %f; New Radius: %f\n", this->sombreroLength[0], this->sombreroRadius[0],
// this->sombreroRadiusNew[0]);
//}
return true;
}
/*
* SombreroWarper::getExtent
*/
bool SombreroWarper::getExtent(Call& call) {
CallTriMeshData* outCall = dynamic_cast<CallTriMeshData*>(&call);
if (outCall == nullptr) return false;
CallTriMeshData* inCall = this->meshInSlot.CallAs<CallTriMeshData>();
if (inCall == nullptr) return false;
TunnelResidueDataCall* tunnelCall = this->tunnelInSlot.CallAs<TunnelResidueDataCall>();
if (tunnelCall == nullptr) return false;
this->checkParameters();
if (dirtyFlag) {
this->hashOffset++;
}
inCall->SetFrameID(outCall->FrameID());
tunnelCall->SetFrameID(outCall->FrameID());
if (!(*inCall)(1)) return false;
if (!(*tunnelCall)(1)) return false;
if (!(*inCall)(0)) return false;
if (!(*tunnelCall)(0)) return false;
// something happened with the input data, we have to recompute it
if ((lastDataHash != inCall->DataHash()) || dirtyFlag) {
lastDataHash = inCall->DataHash();
dirtyFlag = false;
#ifdef SOMBRERO_TIMING
auto timebegin = std::chrono::steady_clock::now();
#endif
// copy
if (!this->copyMeshData(*inCall)) return false;
// search the sombrero border
if (!this->findSombreroBorder()) return false;
// fill the holes of the mesh
if (!this->fillMeshHoles()) return false;
#ifdef SOMBRERO_TIMING
auto timeend = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "***********Hole filling took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
// recompute the broken vertex distances
if (!this->recomputeVertexDistances()) return false;
// compute the Rahi & Sharp angles
if (!this->computeVertexAngles(*tunnelCall)) return false;
#ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "***********Phi value computation took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
// warp the mesh in the correct position
if (!this->warpMesh(*tunnelCall)) return false;
#ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "***********Mesh warping took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
// if needed, fix the mesh
if (this->fixMeshParam.Param<param::BoolParam>()->Value()) {
if (!this->fixBrokenMeshParts(this->meshFixDistanceParam.Param<param::FloatParam>()->Value())) return false;
}
#ifdef SOMBRERO_TIMING
timebegin = std::chrono::steady_clock::now();
#endif
// set the surface normals to correct values
if (!this->recomputeVertexNormals(*tunnelCall)) return false;
#ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "***********Normal computation took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
// cut the mesh into two parts
if (!this->divideMeshForOutput()) return false;
#ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "***********Mesh division took " << elapsed.count() << " ms" << std::endl << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
}
outCall->SetDataHash(inCall->DataHash() + this->hashOffset);
outCall->SetFrameCount(inCall->FrameCount());
outCall->SetExtent(inCall->FrameCount(), inCall->AccessBoundingBoxes());
outCall->AccessBoundingBoxes().SetObjectSpaceBBox(this->boundingBox);
outCall->AccessBoundingBoxes().SetObjectSpaceClipBox(this->boundingBox);
outCall->AccessBoundingBoxes().MakeScaledWorld(1.0f);
return true;
}
/*
* SombreroWarper::checkParameters
*/
void SombreroWarper::checkParameters(void) {
if (this->minBrimLevelParam.IsDirty()) {
this->minBrimLevelParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->maxBrimLevelParam.IsDirty()) {
this->maxBrimLevelParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->maxAllowedLiftingDistance.IsDirty()) {
this->maxAllowedLiftingDistance.ResetDirty();
this->dirtyFlag = true;
}
if (this->liftingTargetDistance.IsDirty()) {
this->liftingTargetDistance.ResetDirty();
this->dirtyFlag = true;
}
if (this->flatteningParam.IsDirty()) {
this->flatteningParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->southBorderWeightParam.IsDirty()) {
this->southBorderWeightParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->southBorderHeightFactor.IsDirty()) {
this->southBorderHeightFactor.ResetDirty();
this->dirtyFlag = true;
}
if (this->invertNormalParam.IsDirty()) {
this->invertNormalParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->meshFixDistanceParam.IsDirty()) {
this->meshFixDistanceParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->fixMeshParam.IsDirty()) {
this->fixMeshParam.ResetDirty();
this->dirtyFlag = true;
}
if (this->radiusSelectionSlot.IsDirty()) {
this->radiusSelectionSlot.ResetDirty();
this->dirtyFlag = true;
}
}
/*
* SombreroWarper::copyMeshData
*/
bool SombreroWarper::copyMeshData(CallTriMeshData& ctmd) {
this->meshVector.clear();
this->meshVector.resize(ctmd.Count());
this->meshVector.shrink_to_fit();
this->vertices.clear();
this->vertices.resize(ctmd.Count());
this->normals.clear();
this->normals.resize(ctmd.Count());
this->colors.clear();
this->colors.resize(ctmd.Count());
this->atomIndexAttachment.clear();
this->atomIndexAttachment.resize(ctmd.Count());
this->vertexLevelAttachment.clear();
this->vertexLevelAttachment.resize(ctmd.Count());
this->bsDistanceAttachment.clear();
this->bsDistanceAttachment.resize(ctmd.Count());
this->edgesForward.clear();
this->edgesForward.resize(ctmd.Count());
this->edgesReverse.clear();
this->edgesReverse.resize(ctmd.Count());
this->vertexEdgeOffsets.clear();
this->vertexEdgeOffsets.resize(ctmd.Count());
this->faces.clear();
this->faces.resize(ctmd.Count());
for (uint i = 0; i < ctmd.Count(); i++) {
uint vertCount = ctmd.Objects()[i].GetVertexCount();
uint triCount = ctmd.Objects()[i].GetTriCount();
uint attribCount = ctmd.Objects()[i].GetVertexAttribCount();
uint atomIndexAttrib = UINT_MAX;
uint vertexLvlAttrib = UINT_MAX;
uint bsDistAttrib = UINT_MAX;
if (attribCount < 3) {
megamol::core::utility::log::Log::DefaultLog.WriteError("Too few vertex attributes detected. The input mesh for the "
"Sombrero warper needs at least three UINT32 vertex attributes.");
return false;
}
// determine the location of the needed attributes
for (uint j = 0; j < attribCount; j++) {
auto dt = ctmd.Objects()[i].GetVertexAttribDataType(j);
if (atomIndexAttrib == UINT_MAX && dt == ctmd.Objects()[i].DT_UINT32) {
atomIndexAttrib = j;
} else if (vertexLvlAttrib == UINT_MAX && dt == ctmd.Objects()[i].DT_UINT32) {
vertexLvlAttrib = j;
} else if (bsDistAttrib == UINT_MAX && dt == ctmd.Objects()[i].DT_UINT32) {
bsDistAttrib = j;
}
}
if (atomIndexAttrib == UINT_MAX || vertexLvlAttrib == UINT_MAX || bsDistAttrib == UINT_MAX) {
megamol::core::utility::log::Log::DefaultLog.WriteError(
"Not enough UINT32 vertex attributes detected. The input mesh for the Sombrero warper needs at least "
"three UINT32 vertex attributes.");
return false;
}
this->vertices[i].resize(vertCount * 3);
this->normals[i].resize(vertCount * 3);
this->colors[i].resize(vertCount * 3);
this->atomIndexAttachment[i].resize(vertCount);
this->vertexLevelAttachment[i].resize(vertCount);
this->bsDistanceAttachment[i].resize(vertCount);
this->faces[i].resize(triCount * 3);
std::memcpy(this->vertices[i].data(), ctmd.Objects()[i].GetVertexPointerFloat(), vertCount * 3 * sizeof(float));
std::memcpy(this->normals[i].data(), ctmd.Objects()[i].GetNormalPointerFloat(), vertCount * 3 * sizeof(float));
std::memcpy(
this->colors[i].data(), ctmd.Objects()[i].GetColourPointerByte(), vertCount * 3 * sizeof(unsigned char));
std::memcpy(this->atomIndexAttachment[i].data(),
ctmd.Objects()[i].GetVertexAttribPointerUInt32(atomIndexAttrib), vertCount * sizeof(uint));
std::memcpy(this->vertexLevelAttachment[i].data(),
ctmd.Objects()[i].GetVertexAttribPointerUInt32(vertexLvlAttrib), vertCount * sizeof(uint));
std::memcpy(this->bsDistanceAttachment[i].data(), ctmd.Objects()[i].GetVertexAttribPointerUInt32(bsDistAttrib),
vertCount * sizeof(uint));
std::memcpy(this->faces[i].data(), ctmd.Objects()[i].GetTriIndexPointerUInt32(), triCount * 3 * sizeof(uint));
this->meshVector[i].SetVertexData(
vertCount, this->vertices[i].data(), this->normals[i].data(), this->colors[i].data(), nullptr, false);
this->meshVector[i].SetTriangleData(triCount, this->faces[i].data(), false);
this->meshVector[i].SetMaterial(nullptr);
this->meshVector[i].AddVertexAttribPointer(this->atomIndexAttachment[i].data());
this->meshVector[i].AddVertexAttribPointer(this->vertexLevelAttachment[i].data());
this->meshVector[i].AddVertexAttribPointer(this->bsDistanceAttachment[i].data());
// copy the edges
this->edgesForward[i].clear();
this->edgesReverse[i].clear();
for (uint j = 0; j < triCount; j++) {
uint vert1 = this->faces[i][j * 3 + 0];
uint vert2 = this->faces[i][j * 3 + 1];
uint vert3 = this->faces[i][j * 3 + 2];
edgesForward[i].push_back(std::pair<uint, uint>(vert1, vert2));
edgesForward[i].push_back(std::pair<uint, uint>(vert2, vert3));
edgesForward[i].push_back(std::pair<uint, uint>(vert3, vert1));
edgesReverse[i].push_back(std::pair<uint, uint>(vert2, vert1));
edgesReverse[i].push_back(std::pair<uint, uint>(vert3, vert2));
edgesReverse[i].push_back(std::pair<uint, uint>(vert1, vert3));
}
reconstructEdgeSearchStructures(i, vertCount);
}
return true;
}
/*
* SombreroWarper::findSombreroBorder
*/
bool SombreroWarper::findSombreroBorder(void) {
this->borderVertices.clear();
this->borderVertices.resize(this->meshVector.size());
this->brimFlags.clear();
this->brimFlags.resize(this->meshVector.size());
this->cutVertices.clear();
this->cutVertices.resize(this->meshVector.size());
this->brimIndices.clear();
this->brimIndices.resize(this->meshVector.size());
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
CallTriMeshData::Mesh& mesh = this->meshVector[i];
uint vCnt = mesh.GetVertexCount();
uint fCnt = mesh.GetTriCount();
// NOTE: the direct manipulation of the vectors and not the meshes only works because the mesh does not own
// the data storage. If this is changed, the code below has to be changed, too.
// build triangle search structures
std::vector<Triangle> firstOrder;
std::vector<Triangle> secondOrder;
std::vector<Triangle> thirdOrder;
firstOrder.resize(fCnt);
for (uint j = 0; j < fCnt; j++) {
firstOrder[j] = Triangle(this->faces[i][j * 3 + 0], this->faces[i][j * 3 + 1], this->faces[i][j * 3 + 2]);
}
secondOrder = firstOrder;
thirdOrder = firstOrder;
std::sort(
firstOrder.begin(), firstOrder.end(), [](const Triangle& a, const Triangle& b) { return a.v1 < b.v1; });
std::sort(
secondOrder.begin(), secondOrder.end(), [](const Triangle& a, const Triangle& b) { return a.v2 < b.v2; });
std::sort(
thirdOrder.begin(), thirdOrder.end(), [](const Triangle& a, const Triangle& b) { return a.v3 < b.v3; });
// adjust the color
uint maxVal = 0;
for (uint j = 0; j < vCnt; j++) {
uint atVal = this->vertexLevelAttachment[i][j];
if (atVal > maxVal) maxVal = atVal;
}
#if 0 // color the vertices corresponding to their level
float mvf = static_cast<float>(maxVal);
for (uint j = 0; j < vCnt; j++) {
float atVal = static_cast<float>(this->vertexLevelAttachment[i][j]);
float factor = atVal / mvf;
vislib::math::Vector<float, 3> resCol;
if (factor < 0.5f) {
vislib::math::Vector<float, 3> blue(0.0f, 0.0f, 1.0f);
vislib::math::Vector<float, 3> white(1.0f, 1.0f, 1.0f);
resCol = (factor * 2.0f) * white + (1.0f - (factor * 2.0f)) * blue;
} else {
vislib::math::Vector<float, 3> red(1.0f, 0.0f, 0.0f);
vislib::math::Vector<float, 3> white(1.0f, 1.0f, 1.0f);
resCol = ((factor - 0.5f) * 2.0f) * red + (1.0f - ((factor - 0.5f) * 2.0f)) * white;
}
this->colors[i][j * 3 + 0] = static_cast<unsigned char>(resCol.X() * 255.0f);
this->colors[i][j * 3 + 1] = static_cast<unsigned char>(resCol.Y() * 255.0f);
this->colors[i][j * 3 + 2] = static_cast<unsigned char>(resCol.Z() * 255.0f);
}
#endif
// we need at least 1 border vertex with level > 0 to start an outer border and brim
if (maxVal < 1) {
megamol::core::utility::log::Log::DefaultLog.WriteError(
"No region growing was performed and therefore no brim can be specified");
return false;
}
int maxBrimVal = this->maxBrimLevelParam.Param<param::IntParam>()->Value();
unsigned int minBrim = this->minBrimLevelParam.Param<param::IntParam>()->Value();
unsigned int maxBrim = this->maxBrimLevelParam.Param<param::IntParam>()->Value();
if (maxBrimVal < 0) maxBrim = maxVal;
if (minBrim > maxBrim) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The minBrim value is larger than the maxBrim value");
return false;
}
// count the number of vertices we have to process
uint maxValueVertexCount = static_cast<uint>(
std::count(this->vertexLevelAttachment[i].begin(), this->vertexLevelAttachment[i].end(), maxBrim));
this->borderVertices[i].clear();
std::vector<std::set<uint>> localBorder;
uint setIndex = 0;
std::set<uint> candidates; // set containing all border candidates
for (size_t j = 0; j < this->vertexLevelAttachment[i].size(); j++) {
if (this->vertexLevelAttachment[i][j] == maxBrim) {
candidates.insert(static_cast<uint>(j));
}
}
while (!candidates.empty()) {
auto start = static_cast<uint>(*candidates.begin()); // take the first element as starting point
candidates.erase(start);
localBorder.push_back(std::set<uint>());
localBorder[setIndex].insert(start);
std::set<uint> localCandidates;
localCandidates.insert(start);
while (!localCandidates.empty()) {
auto current = static_cast<uint>(*localCandidates.begin());
localCandidates.erase(current);
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
// go through all forward edges
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (this->vertexLevelAttachment[i][target] == maxBrim && localCandidates.count(target) == 0 &&
localBorder[setIndex].count(target) == 0) {
// when we have found an edge target which is not yet known, add it as local candidate and to
// the border set
localBorder[setIndex].insert(target);
localCandidates.insert(target);
candidates.erase(target);
}
forward++;
}
// go through all backward edges
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (this->vertexLevelAttachment[i][target] == maxBrim && localCandidates.count(target) == 0 &&
localBorder[setIndex].count(target) == 0) {
// when we have found an edge target which is not yet known, add it as local candidate and to
// the border set
localBorder[setIndex].insert(target);
localCandidates.insert(target);
candidates.erase(target);
}
reverse++;
}
}
setIndex++;
}
// all borders have been located
// find the longest one
size_t maxSize = 0;
size_t maxIndex = 0;
for (size_t j = 0; j < localBorder.size(); j++) {
if (localBorder[j].size() > maxSize) {
maxSize = localBorder[j].size();
maxIndex = j;
}
}
if (localBorder.size() < 1) {
megamol::core::utility::log::Log::DefaultLog.WriteError("No brim border found. No calculation possible!");
return false;
}
// clean the border
std::set<uint> newLocalBorder;
for (auto it = localBorder[maxIndex].begin(); it != localBorder[maxIndex].end(); it++) {
auto vIdx = *it;
// we iterate over all outgoing triangles and add up the angles they produce
// if the resulting angle is not very close to 360°, it is a cut vertex
auto firstIt = std::lower_bound(
firstOrder.begin(), firstOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v1 < s; });
auto secondIt = std::lower_bound(
secondOrder.begin(), secondOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v2 < s; });
auto thirdIt = std::lower_bound(
thirdOrder.begin(), thirdOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v3 < s; });
std::set<uint> vertexSet;
uint triCount = 0;
while (firstIt != firstOrder.end() && (*firstIt).v1 == vIdx) {
vertexSet.insert((*firstIt).v2);
vertexSet.insert((*firstIt).v3);
triCount++;
firstIt++;
}
while (secondIt != secondOrder.end() && (*secondIt).v2 == vIdx) {
vertexSet.insert((*secondIt).v1);
vertexSet.insert((*secondIt).v3);
triCount++;
secondIt++;
}
while (thirdIt != thirdOrder.end() && (*thirdIt).v3 == vIdx) {
vertexSet.insert((*thirdIt).v2);
vertexSet.insert((*thirdIt).v1);
triCount++;
thirdIt++;
}
// if we have more adjacent vertices than adjacent triangles, we have a cut vertex
if (vertexSet.size() > triCount) {
newLocalBorder.insert(vIdx);
}
}
localBorder[maxIndex] = newLocalBorder;
// write all indices to the storage
this->borderVertices[i] = localBorder[maxIndex];
#if 0 // color all found vertices blue
for (uint j = 0; j < localBorder.size(); j++) {
for (uint k = 0; k < vCnt; k++) {
if (localBorder[j].count(k) > 0) {
this->colors[i][k * 3 + 0] = 0;
this->colors[i][k * 3 + 1] = 0;
this->colors[i][k * 3 + 2] = 255;
} else {
this->colors[i][k * 3 + 0] = 255;
this->colors[i][k * 3 + 1] = 255;
this->colors[i][k * 3 + 2] = 255;
}
}
}
#endif
/**
* At this point, the border is found, we now try to extend it to form the brim
*/
#if 0 // color the border vertices red, the rest white
vislib::math::Vector<float, 3> red(1.0f, 0.0f, 0.0f);
vislib::math::Vector<float, 3> white(1.0f, 1.0f, 1.0f);
for (uint j = 0; j < vCnt; j++) {
if (this->borderVertices[i].count(j) > 0) {
this->colors[i][j * 3 + 0] = static_cast<unsigned char>(red.X() * 255.0f);
this->colors[i][j * 3 + 1] = static_cast<unsigned char>(red.Y() * 255.0f);
this->colors[i][j * 3 + 2] = static_cast<unsigned char>(red.Z() * 255.0f);
} else {
this->colors[i][j * 3 + 0] = static_cast<unsigned char>(white.X() * 255.0f);
this->colors[i][j * 3 + 1] = static_cast<unsigned char>(white.Y() * 255.0f);
this->colors[i][j * 3 + 2] = static_cast<unsigned char>(white.Z() * 255.0f);
}
}
#endif
std::vector<uint> vertexLevels(vCnt, UINT_MAX);
this->brimFlags[i].resize(vCnt, false);
this->brimIndices[i].clear();
for (size_t j = 0; j < vCnt; j++) {
if (this->borderVertices[i].count(static_cast<uint>(j)) > 0) {
this->brimFlags[i][j] = true;
this->brimIndices[i].push_back(static_cast<uint>(j));
vertexLevels[j] = 0;
}
}
// perform a region growing starting from the found border
std::set<uint> brimCandidates = this->borderVertices[i];
while (!brimCandidates.empty()) {
uint current = static_cast<uint>(*brimCandidates.begin());
brimCandidates.erase(current);
// search for the start indices in both edge lists
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (vertexLevels[target] > vertexLevels[current] + 1) {
vertexLevels[target] = vertexLevels[current] + 1;
brimCandidates.insert(target);
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (vertexLevels[target] > vertexLevels[current] + 1) {
vertexLevels[target] = vertexLevels[current] + 1;
brimCandidates.insert(target);
}
reverse++;
}
}
// go through all vertices. Where the level is <= than maxBrim - minBrim, assign the brim
for (size_t j = 0; j < vCnt; j++) {
if (vertexLevels[j] <= maxBrim - minBrim) {
this->brimFlags[i][j] = true;
#if 0 // coloring of brim vertices
if (vertexLevels[j] != 0) {
this->colors[i][j * 3 + 0] = 0;
this->colors[i][j * 3 + 1] = 255;
this->colors[i][j * 3 + 2] = 0;
}
#endif
}
}
this->cutVertices[i].resize(localBorder.size() - 1);
uint myIndex = 0;
// identify all real cut vertices
for (size_t j = 0; j < localBorder.size(); j++) {
// iterate over all identified vertices
for (auto vIdx : localBorder[j]) {
// we iterate over all outgoing triangles and add up the angles they produce
// if the resulting angle is not very close to 360°, it is a cut vertex
auto firstIt = std::lower_bound(
firstOrder.begin(), firstOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v1 < s; });
auto secondIt = std::lower_bound(
secondOrder.begin(), secondOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v2 < s; });
auto thirdIt = std::lower_bound(
thirdOrder.begin(), thirdOrder.end(), vIdx, [](const Triangle& t, uint s) { return t.v3 < s; });
std::set<uint> vertexSet;
uint triCount = 0;
while (firstIt != firstOrder.end() && (*firstIt).v1 == vIdx) {
vertexSet.insert((*firstIt).v2);
vertexSet.insert((*firstIt).v3);
triCount++;
firstIt++;
}
while (secondIt != secondOrder.end() && (*secondIt).v2 == vIdx) {
vertexSet.insert((*secondIt).v1);
vertexSet.insert((*secondIt).v3);
triCount++;
secondIt++;
}
while (thirdIt != thirdOrder.end() && (*thirdIt).v3 == vIdx) {
vertexSet.insert((*thirdIt).v2);
vertexSet.insert((*thirdIt).v1);
triCount++;
thirdIt++;
}
// if we have more adjacent vertices than adjacent triangles, we have a cut vertex
if (vertexSet.size() > triCount) {
if (j != maxIndex) {
this->cutVertices[i][myIndex].insert(vIdx);
}
}
}
if (j != maxIndex) {
myIndex++;
}
}
#if 0 // color all cut vertices
for (uint j = 0; j < vCnt; j++) {
bool colored = false;
for (uint s = 0; s < this->cutVertices[i].size(); s++) {
if (this->cutVertices[i][s].count(j) > 0) {
this->colors[i][j * 3 + 0] = 0;
this->colors[i][j * 3 + 1] = 0;
this->colors[i][j * 3 + 2] = 255;
colored = true;
}
}
if (!colored) {
this->colors[i][j * 3 + 0] = 255;
this->colors[i][j * 3 + 1] = 255;
this->colors[i][j * 3 + 2] = 255;
}
}
#endif
for (size_t j = 0; j < this->cutVertices[i].size(); j++) {
if (this->cutVertices[i][j].size() == 0) {
this->cutVertices[i].erase(this->cutVertices[i].begin() + j);
j--;
}
}
}
return true;
}
/*
* SombreroWarper::warpMesh
*/
bool SombreroWarper::warpMesh(TunnelResidueDataCall& tunnelCall) {
this->newBsDistances = this->bsDistanceAttachment;
this->sombreroLength.clear();
this->sombreroLength.resize(this->meshVector.size());
this->sombreroRadius.clear();
this->sombreroRadius.resize(this->meshVector.size());
this->brimWidth.clear();
this->brimWidth.resize(this->meshVector.size());
for (size_t i = 0; i < this->meshVector.size(); i++) {
uint vCnt = static_cast<uint>(this->vertices[i].size() / 3);
uint fCnt = static_cast<uint>(this->faces[i].size() / 3);
// find the index of the binding site vertex
auto bsIt = std::find(this->bsDistanceAttachment[i].begin(), this->bsDistanceAttachment[i].end(), 0);
uint bsVertex = 0; // index of binding site vertex
if (bsIt != this->bsDistanceAttachment[i].end()) {
bsVertex = static_cast<uint>(bsIt - this->bsDistanceAttachment[i].begin());
} else {
megamol::core::utility::log::Log::DefaultLog.WriteError("No binding site vertex present. No computation possible!");
return false;
}
#if 0
/*
* step 1: vertex level computation
*/
bool liftResult = this->liftVertices();
if (!liftResult) {
return false;
}
#endif
/*
* step 2: compute the necessary parameters
*/
// the length of the sombrero is the length of the first tunnel
/*float longestLength = 0.0f;
for (uint j = 0; j < static_cast<uint>(std::max(tunnelCall.getTunnelNumber(), 1)); j++) {
auto& tunnel = tunnelCall.getTunnelDescriptions()[j];
float localLength = 0.0f;
vislib::math::Vector<float, 3> first, second;
for (uint k = 4; k < static_cast<uint>(tunnel.coordinates.size()); k += 4) {
first = vislib::math::Vector<float, 3>(&tunnel.coordinates[k - 4]);
second = vislib::math::Vector<float, 3>(&tunnel.coordinates[k]);
localLength += (second - first).Length();
}
if (localLength > longestLength) {
longestLength = localLength;
}
}
this->sombreroLength[i] = longestLength;*/
if (tunnelCall.getTunnelNumber() > 0) {
this->sombreroLength[i] = tunnelCall.getTunnelDescriptions()[0].tunnelLength *
this->lengthScalingParam.Param<param::FloatParam>()->Value();
}
// the inner radius is the median of the sphere radii
std::vector<float> radii;
for (uint j = 0; j < static_cast<uint>(std::max(tunnelCall.getTunnelNumber(), 1)); j++) {
auto& tunnel = tunnelCall.getTunnelDescriptions()[j];
for (uint k = 3; k < static_cast<uint>(tunnel.coordinates.size()); k += 4) {
radii.push_back(tunnel.coordinates[k]);
}
}
std::sort(radii.begin(), radii.end());
this->sombreroRadius[i] = radii[static_cast<uint>(radii.size() / 2)];
#ifdef SOMBRERO_TIMING
auto timebegin = std::chrono::steady_clock::now();
#endif
// the brim radius is the average closest distance between the brim border vertices and the sweatband
uint minLevel = static_cast<uint>(this->minBrimLevelParam.Param<param::IntParam>()->Value());
float avg = 0.0f;
for (uint j = 0; j < static_cast<uint>(this->brimIndices.size()); j++) {
uint level = this->vertexLevelAttachment[i][this->brimIndices[i][j]];
uint current = this->brimIndices[i][j];
float dist = 0.0f;
while (level > minLevel) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current && !found) {
auto target = (*forward).second;
if (this->vertexLevelAttachment[i][target] < level) {
level = this->vertexLevelAttachment[i][target];
found = true;
// compute the distance between the two vertices
vislib::math::Vector<float, 3> curPos(&this->vertices[i][current * 3]);
vislib::math::Vector<float, 3> targetPos(&this->vertices[i][target * 3]);
dist += (targetPos - curPos).Length();
current = target;
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == current && !found) {
auto target = (*reverse).second;
if (this->vertexLevelAttachment[i][target] < level) {
level = this->vertexLevelAttachment[i][target];
found = true;
// compute the distance between the two vertices
vislib::math::Vector<float, 3> curPos(&this->vertices[i][current * 3]);
vislib::math::Vector<float, 3> targetPos(&this->vertices[i][target * 3]);
dist += (targetPos - curPos).Length();
current = target;
}
reverse++;
}
}
avg += dist;
}
this->brimWidth[i] = avg / static_cast<float>(this->brimIndices.size());
// megamol::core::utility::log::Log::DefaultLog.WriteWarn("Radius of %i is %f", static_cast<int>(i), this->sombreroRadius[i]);
// megamol::core::utility::log::Log::DefaultLog.WriteWarn("Brim width of %i is %f", static_cast<int>(i), this->brimWidth[i]);
#ifdef SOMBRERO_TIMING
auto timeend = std::chrono::steady_clock::now();
auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timebegin - timeend);
std::cout << "Brim width computation took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
#endif
/**
* step 3: mesh deformation
*/
#ifndef NO_DEFORMATION
bool yResult = this->computeHeightPerVertex(bsVertex);
if (!yResult) return false;
# ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "Height per vertex computation took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
# endif
bool xzResult = this->computeXZCoordinatePerVertex(tunnelCall);
if (!xzResult) return false;
# ifdef SOMBRERO_TIMING
timeend = std::chrono::steady_clock::now();
elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(timeend - timebegin);
std::cout << "x-z coordinate computation took " << elapsed.count() << " ms" << std::endl;
timebegin = std::chrono::steady_clock::now();
# endif
#endif
}
/**
* step 4: compute bounding box
*/
this->boundingBox = vislib::math::Cuboid<float>();
if (this->vertices.size() > 0 && this->vertices[0].size() > 0) {
this->boundingBox.Set(this->vertices[0][0], this->vertices[0][1], this->vertices[0][2], this->vertices[0][0],
this->vertices[0][1], this->vertices[0][2]);
for (size_t i = 0; i < this->vertices.size(); i++) {
for (size_t j = 0; j < this->vertices[i].size(); j += 3) {
vislib::math::ShallowPoint<float, 3> vert(&this->vertices[i][j]);
this->boundingBox.GrowToPoint(vert);
}
}
}
const float bbmargin = 0.1f;
if (this->flatteningParam.Param<param::BoolParam>()->Value()) {
this->boundingBox.SetBottom(this->boundingBox.Bottom() - bbmargin);
this->boundingBox.SetTop(this->boundingBox.Top() + bbmargin);
}
//#define COMPARE
#ifdef COMPARE
if (!this->flatteningParam.Param<param::BoolParam>()->Value() && this->sombreroLength.size() > 0) {
this->boundingBox.Set(-30.0f, -7.0f, -30.0f, 30.0f, 7.0f, 30.0f);
} else {
this->boundingBox.Set(-30.0f, -30.0f, (this->sombreroLength[0] / 2.0f) - bbmargin, 30.0f, 30.0f,
(this->sombreroLength[0] / 2.0f) + bbmargin);
}
#endif
return true;
}
/*
* SombreroWarper::fillMeshHoles
*/
bool SombreroWarper::fillMeshHoles(void) {
unsigned int minBrim = this->minBrimLevelParam.Param<param::IntParam>()->Value();
unsigned int maxBrim = this->maxBrimLevelParam.Param<param::IntParam>()->Value();
// for each mesh
for (uint i = 0; i < this->meshVector.size(); i++) {
// for each hole in the mesh
std::vector<std::vector<uint>> sortedCuts;
sortedCuts.resize(this->cutVertices[i].size());
// we have to sort the mesh vertices to be consecutive along the border
for (uint j = 0; j < this->cutVertices[i].size(); j++) {
sortedCuts[j].resize(this->cutVertices[i][j].size());
auto localSet = this->cutVertices[i][j];
uint current = *localSet.begin();
uint setsize = static_cast<uint>(this->cutVertices[i][j].size());
localSet.erase(current);
sortedCuts[j][0] = current;
uint k = 0;
while (!localSet.empty()) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (this->cutVertices[i][j].count(target) > 0) {
if (localSet.count(target) > 0 || k == setsize - 1) {
if (k == 0) {
// the direction does not matter with k == 0
localSet.erase(target);
sortedCuts[j][k + 1] = target;
found = true;
} else {
if (sortedCuts[j][k - 1] != target) {
localSet.erase(target);
if (k != setsize - 1) {
sortedCuts[j][k + 1] = target;
}
found = true;
}
}
}
}
forward++;
}
if (!found) {
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (this->cutVertices[i][j].count(target) > 0) {
if (localSet.count(target) > 0 || k == setsize - 1) {
if (k == 0) {
// the direction does not matter with k == 0
localSet.erase(target);
sortedCuts[j][k + 1] = target;
found = true;
} else {
if (sortedCuts[j][k - 1] != target) {
localSet.erase(target);
if (k != setsize - 1) {
sortedCuts[j][k + 1] = target;
}
found = true;
}
}
}
}
reverse++;
}
}
if (k != setsize - 1) {
current = sortedCuts[j][k + 1];
}
k++;
}
}
for (uint j = 0; j < this->cutVertices[i].size(); j++) {
vislib::math::Vector<float, 3> avgPos(0.0f, 0.0f, 0.0f);
vislib::math::Vector<float, 3> avgNormal(0.0f, 0.0f, 0.0f);
vislib::math::Vector<float, 3> avgColor(0.0f, 0.0f, 0.0f);
bool belongsToBrim = false;
for (auto v : this->cutVertices[i][j]) {
belongsToBrim |= this->brimFlags[i][v];
vislib::math::Vector<float, 3> pos(&this->vertices[i][v * 3]);
vislib::math::Vector<float, 3> normal(&this->normals[i][v * 3]);
vislib::math::Vector<float, 3> color(static_cast<float>(this->colors[i][v * 3]),
static_cast<float>(this->colors[i][v * 3 + 1]), static_cast<float>(this->colors[i][v * 3 + 2]));
avgPos += pos;
avgNormal += normal;
avgColor += color;
}
avgPos /= static_cast<float>(this->cutVertices[i][j].size());
avgColor /= static_cast<float>(this->cutVertices[i][j].size());
avgNormal.Normalise();
this->vertices[i].push_back(avgPos[0]);
this->vertices[i].push_back(avgPos[1]);
this->vertices[i].push_back(avgPos[2]);
this->normals[i].push_back(avgNormal[0]);
this->normals[i].push_back(avgNormal[1]);
this->normals[i].push_back(avgNormal[2]);
this->colors[i].push_back(static_cast<unsigned char>(avgColor[0]));
this->colors[i].push_back(static_cast<unsigned char>(avgColor[1]));
this->colors[i].push_back(static_cast<unsigned char>(avgColor[2]));
this->atomIndexAttachment[i].push_back(0);
this->bsDistanceAttachment[i].push_back(UINT_MAX);
this->vertexLevelAttachment[i].push_back(0);
this->brimFlags[i].push_back(belongsToBrim);
// vertex was added, now add all triangles
uint siz = static_cast<uint>(sortedCuts[j].size());
for (uint k = 0; k < siz; k++) {
uint x = static_cast<uint>(this->atomIndexAttachment[i].size() - 1);
uint y = sortedCuts[j][k];
uint z = sortedCuts[j][(k + 1) % siz];
this->faces[i].push_back(x);
this->faces[i].push_back(y);
this->faces[i].push_back(z);
this->edgesForward[i].push_back(std::pair<uint, uint>(x, y));
this->edgesForward[i].push_back(std::pair<uint, uint>(y, z));
this->edgesForward[i].push_back(std::pair<uint, uint>(z, x));
this->edgesReverse[i].push_back(std::pair<uint, uint>(y, x));
this->edgesReverse[i].push_back(std::pair<uint, uint>(z, y));
this->edgesReverse[i].push_back(std::pair<uint, uint>(x, z));
}
}
// resort the search structures
std::sort(edgesForward[i].begin(), edgesForward[i].end(),
[](const std::pair<unsigned int, unsigned int>& left, const std::pair<unsigned int, unsigned int>& right) {
return left.first < right.first;
});
std::sort(edgesReverse[i].begin(), edgesReverse[i].end(),
[](const std::pair<unsigned int, unsigned int>& left, const std::pair<unsigned int, unsigned int>& right) {
return left.first < right.first;
});
// remove edge duplicates
edgesForward[i].erase(std::unique(edgesForward[i].begin(), edgesForward[i].end()), edgesForward[i].end());
edgesReverse[i].erase(std::unique(edgesReverse[i].begin(), edgesReverse[i].end()), edgesReverse[i].end());
reconstructEdgeSearchStructures(i, static_cast<uint>(this->vertices[i].size() / 3));
}
return true;
}
/*
* SombreroWarper::recomputeVertexDistances
*/
bool SombreroWarper::recomputeVertexDistances(void) {
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
auto it = std::find(this->bsDistanceAttachment[i].begin(), this->bsDistanceAttachment[i].end(), 0);
uint bsIndex = UINT_MAX;
if (it != this->bsDistanceAttachment[i].end()) {
bsIndex = static_cast<uint>(it - this->bsDistanceAttachment[i].begin());
} else {
megamol::core::utility::log::Log::DefaultLog.WriteError("No binding site index found!");
return false;
}
std::set<uint> allowedVerticesSet;
std::set<uint> newset;
allowedVerticesSet.insert(bsIndex);
this->bsDistanceAttachment[i][bsIndex] = 0;
while (!allowedVerticesSet.empty()) {
newset.clear();
// for each currently allowed vertex
for (auto element : allowedVerticesSet) {
// search for the start indices in both edge lists
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][element].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][element].second;
// go through all forward edges starting with the vertex
while (forward != edgesForward[i].end() && (*forward).first == element) {
auto val = (*forward).second;
if (this->bsDistanceAttachment[i][val] > this->bsDistanceAttachment[i][element] + 1) {
this->bsDistanceAttachment[i][val] = this->bsDistanceAttachment[i][element] + 1;
newset.insert(val);
}
forward++;
}
// do the same thing for all reverse edges
while (reverse != edgesReverse[i].end() && (*reverse).first == element) {
auto val = (*reverse).second;
// check whether the endpoint is valid
if (this->bsDistanceAttachment[i][val] > this->bsDistanceAttachment[i][element] + 1) {
this->bsDistanceAttachment[i][val] = this->bsDistanceAttachment[i][element] + 1;
newset.insert(val);
}
reverse++;
}
}
allowedVerticesSet = newset;
}
}
return true;
}
/*
* SombreroWarper::computeVertexAngles
*/
bool SombreroWarper::computeVertexAngles(TunnelResidueDataCall& tunnelCall) {
this->rahiAngles.resize(this->meshVector.size());
this->rahiAngles.shrink_to_fit();
this->sombreroRadiusNew.clear();
this->sombreroRadiusNew.resize(this->meshVector.size());
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
// first: find the meridian
// startpoint: the binding site vertex
auto it = std::find(this->bsDistanceAttachment[i].begin(), this->bsDistanceAttachment[i].end(), 0);
uint startIndex = UINT_MAX;
if (it != this->bsDistanceAttachment[i].end()) {
startIndex = static_cast<uint>(it - this->bsDistanceAttachment[i].begin());
} else {
megamol::core::utility::log::Log::DefaultLog.WriteError("No start binding site index found!");
return false;
}
// end-point the brim vertex with the lowest level
uint lowestLevel = UINT_MAX;
uint endIndex = UINT_MAX;
std::sort(this->brimIndices[i].begin(), this->brimIndices[i].end());
for (auto v : this->brimIndices[i]) {
if (this->bsDistanceAttachment[i][v] < lowestLevel) {
lowestLevel = this->bsDistanceAttachment[i][v];
endIndex = v;
}
}
std::vector<uint> meridian;
meridian.push_back(endIndex);
uint current = endIndex;
for (uint j = 0; j < lowestLevel - 1; j++) {
uint mylevel = lowestLevel - j;
// search for the start indices in both edge lists
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (this->bsDistanceAttachment[i][target] == mylevel - 1) {
meridian.push_back(target);
current = target;
found = true;
break;
}
forward++;
}
if (found) continue;
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (this->bsDistanceAttachment[i][target] == mylevel - 1) {
meridian.push_back(target);
current = target;
found = true;
break;
}
reverse++;
}
}
meridian.push_back(startIndex);
#if 0 // color meridian vertices
for (auto v : meridian) {
this->colors[i][3 * v + 0] = 255;
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 0;
}
#endif
/**
* The indices mean the following:
* -1: polar vertex (only assigned for the binding site vertex
* 1 : meridian vertex
* 2 : vertex adjacent to the meridian to the left
* 3 : vertex adjacent to the meridian to the right
* 0 : all other vertices
*/
std::vector<int> vTypes(this->vertexLevelAttachment[i].size(), 0);
vTypes.shrink_to_fit();
for (auto v : meridian) {
vTypes[v] = 1;
}
vTypes[startIndex] = -1;
#if 0 // color brim vertices
for (auto v : this->brimIndices[i]) {
this->colors[i][3 * v + 0] = 255;
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 0;
}
#endif
// determine the vertices of the sweatband
std::set<uint> sweatSet;
// go through all forward edges, if one vertex is on the brim and one is not, take the second one
for (auto e : this->edgesForward[i]) {
if (this->brimFlags[i][e.first] && !this->brimFlags[i][e.second]) {
sweatSet.insert(e.second);
} else if (!this->brimFlags[i][e.first] && this->brimFlags[i][e.second]) {
sweatSet.insert(e.first);
}
}
// determine the length of all sweat-connecting edges
std::set<std::pair<uint, uint>> sweatedges;
for (auto e : this->edgesForward[i]) {
if (sweatSet.count(e.first) > 0 && sweatSet.count(e.second) > 0) {
// sweatedge found, check whether it is alread inserted
std::pair<uint, uint> fedge = std::make_pair(e.first, e.second);
std::pair<uint, uint> redge = std::make_pair(e.second, e.first);
if (!(sweatedges.count(fedge) > 0 || sweatedges.count(redge) > 0)) {
sweatedges.insert(fedge);
}
}
}
float lengthSum = 0.0f;
for (auto e : sweatedges) {
vislib::math::Vector<float, 3> firstPos(&this->vertices[i][3 * e.first]);
vislib::math::Vector<float, 3> secondPos(&this->vertices[i][3 * e.second]);
lengthSum += (secondPos - firstPos).Length();
}
const float thePi = 3.14159265358979f;
float sombrad = lengthSum / (2.0f * thePi);
this->sombreroRadiusNew[i] = sombrad;
// megamol::core::utility::log::Log::DefaultLog.WriteWarn("New radius of %i is %f", static_cast<int>(i), sombrad);
#if 0 // switch for the colouring of the sweatedges
vislib::math::Vector<float, 3> red(255.0f, 0.0f, 0.0f);
for (auto e : sweatedges) {
this->colors[i][3 * e.first + 0] = static_cast<unsigned char>(red[0]);
this->colors[i][3 * e.first + 1] = static_cast<unsigned char>(red[1]);
this->colors[i][3 * e.first + 2] = static_cast<unsigned char>(red[2]);
this->colors[i][3 * e.second + 0] = static_cast<unsigned char>(red[0]);
this->colors[i][3 * e.second + 1] = static_cast<unsigned char>(red[1]);
this->colors[i][3 * e.second + 2] = static_cast<unsigned char>(red[2]);
}
#endif
// determine starting point of the sweatband
// it should be the vertex that is member of the meridian and the sweatband
std::set<uint> meridianSet(meridian.begin(), meridian.end());
std::vector<uint> intRes;
std::set_intersection(
meridianSet.begin(), meridianSet.end(), sweatSet.begin(), sweatSet.end(), std::back_inserter(intRes));
if (intRes.size() != 1) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The sweatband and the meridian do not intersect properly");
return false;
}
// have to sort the brim indices in a circular manner
std::vector<uint> sortedBrim;
std::set<uint> brimTest(this->brimIndices[i].begin(), this->brimIndices[i].end());
std::set<uint> readySet;
sortedBrim.push_back(endIndex);
readySet.insert(endIndex);
bool isClockwise = false;
uint k = 0;
while (sortedBrim.size() != brimTest.size()) {
current = sortedBrim[sortedBrim.size() - 1];
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (brimTest.count(target) > 0 && readySet.count(target) == 0) {
sortedBrim.push_back(target);
readySet.insert(target);
found = true;
break;
}
forward++;
}
if (!found) {
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (brimTest.count(target) > 0 && readySet.count(target) == 0) {
sortedBrim.push_back(target);
readySet.insert(target);
found = true;
break;
}
reverse++;
}
}
k++;
if (!found) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The brim of the sombrero is not continous. Aborting...");
return false;
}
}
#if 0 // switch for the colouring of the brim vertices by angle
vislib::math::Vector<float, 3> red(255.0f, 0.0f, 0.0f);
float factor = 1.0f / static_cast<float>(sortedBrim.size());
int f = 0;
for (auto v : sortedBrim) {
this->colors[i][3 * v + 0] = static_cast<unsigned char>(f * factor * red[0]);
this->colors[i][3 * v + 1] = static_cast<unsigned char>(f * factor * red[1]);
this->colors[i][3 * v + 2] = static_cast<unsigned char>(f * factor * red[2]);
f++;
}
#endif
#ifdef SWEAT
// to compute the sweatband we need the multiplicity of the vertices
std::map<uint, uint> vertexMultiplicity;
std::map<uint, uint> nonbrimMultiplicity;
for (auto v : sweatSet) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][v].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][v].second;
std::set<uint> targets;
std::set<uint> nonBrimTargets;
while (forward != edgesForward[i].end() && (*forward).first == v) {
auto target = (*forward).second;
if (sweatSet.count(target) > 0) {
targets.insert(target);
} else {
if (this->brimFlags[i][target] == false) {
nonBrimTargets.insert(target);
}
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == v) {
auto target = (*reverse).second;
if (sweatSet.count(target) > 0) {
targets.insert(target);
} else {
if (this->brimFlags[i][target] == false) {
nonBrimTargets.insert(target);
}
}
reverse++;
}
vertexMultiplicity[v] = static_cast<uint>(targets.size());
nonbrimMultiplicity[v] = static_cast<uint>(nonBrimTargets.size());
}
// do the same with the sweatband
std::vector<uint> sweatSorted;
std::set<uint> sweatReadySet;
sweatSorted.push_back(intRes[0]);
sweatReadySet.insert(intRes[0]);
bool sweatIsClockwise = false;
while (sweatSorted.size() != sweatSet.size()) {
current = sweatSorted[sweatSorted.size() - 1];
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
std::set<uint> targets;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (sweatSet.count(target) > 0 && sweatReadySet.count(target) == 0) {
targets.insert(target);
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (sweatSet.count(target) > 0 && sweatReadySet.count(target) == 0) {
targets.insert(target);
}
reverse++;
}
if (targets.size() == 0) {
megamol::core::utility::log::Log::DefaultLog.WriteError("No target vertex for the sweatband computation found");
return false;
}
// go through all of the target vertices
// we prioritize the vertices with the lowest non-brim-multiplicity.
// if there are more than one of these vertices, take the one with the sweat-multiplicity
uint minnonbrim = UINT_MAX;
uint minmult = UINT_MAX;
std::set<uint> nb;
for (auto v : targets) {
if (nonbrimMultiplicity[v] < minnonbrim) {
nb.clear();
minnonbrim = nonbrimMultiplicity[v];
nb.insert(v);
} else if (nonbrimMultiplicity[v] == minnonbrim) {
nb.insert(v);
}
}
uint finalv;
for (auto v : nb) {
if (vertexMultiplicity[v] <= minmult) {
minmult = vertexMultiplicity[v];
finalv = v;
}
}
sweatSorted.push_back(finalv);
sweatReadySet.insert(finalv);
}
# if 0 // switch for the colouring of the sweatband vertices by angle
vislib::math::Vector<float, 3> red(255.0f, 0.0f, 0.0f);
float factor = 1.0f / static_cast<float>(sweatSet.size());
int f = 0;
for (auto v : sweatSet) {
this->colors[i][3 * v + 0] = static_cast<unsigned char>(red[1]);
this->colors[i][3 * v + 1] = static_cast<unsigned char>(red[0]);
this->colors[i][3 * v + 2] = static_cast<unsigned char>(red[2]);
}
for (auto v : sweatReadySet) {
this->colors[i][3 * v + 0] = static_cast<unsigned char>(f * factor * red[0]);
this->colors[i][3 * v + 1] = static_cast<unsigned char>(f * factor * red[1]);
this->colors[i][3 * v + 2] = static_cast<unsigned char>(f * factor * red[2]);
this->colors[i][3 * v + 0] = static_cast<unsigned char>(red[0]);
this->colors[i][3 * v + 1] = static_cast<unsigned char>(red[1]);
this->colors[i][3 * v + 2] = static_cast<unsigned char>(red[2]);
//if (v == 1957) {
// this->colors[i][3 * v + 0] = static_cast<unsigned char>(red[1]);
// this->colors[i][3 * v + 1] = static_cast<unsigned char>(red[2]);
// this->colors[i][3 * v + 2] = static_cast<unsigned char>(red[0]);
//}
f++;
}
# endif
#endif
// the brim and sweatband is sorted, now we can estimate the directions
// we assume that the endIndex is in the front
vislib::math::Vector<float, 3> endVertex(&this->vertices[i][3 * endIndex]);
vislib::math::Vector<float, 3> startVertex(&this->vertices[i][3 * startIndex]);
vislib::math::Vector<float, 3> v1, v2;
uint v1Idx = static_cast<uint>(sortedBrim.size() / 4);
uint v2Idx = static_cast<uint>(sortedBrim.size() / 2);
if (endIndex == v1Idx || endIndex == v2Idx || v1Idx == v2Idx) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The brim is too small to compute further");
return false;
}
v1 = vislib::math::Vector<float, 3>(&this->vertices[i][3 * v1Idx]);
v2 = vislib::math::Vector<float, 3>(&this->vertices[i][3 * v2Idx]);
// compute the average brim center
vislib::math::Vector<float, 3> centerVertex(0.0f, 0.0f, 0.0f);
for (auto v : sortedBrim) {
centerVertex[0] += this->vertices[i][3 * v + 0];
centerVertex[1] += this->vertices[i][3 * v + 1];
centerVertex[2] += this->vertices[i][3 * v + 2];
}
centerVertex /= static_cast<float>(sortedBrim.size());
auto dir = centerVertex - startVertex;
dir.Normalise();
// project v1 and v2 onto the plane by centerVertex and dir
v1 = v1 - (v1 - centerVertex).Dot(dir) * dir;
v2 = v2 - (v2 - centerVertex).Dot(dir) * dir;
vislib::math::Vector<float, 3> d1 = v1 - endVertex;
vislib::math::Vector<float, 3> d2 = v2 - endVertex;
d1.Normalise();
d2.Normalise();
auto normal = d1.Cross(d2);
normal.Normalise();
uint left, right;
if (normal.Dot(dir) >= 0) {
// the brim index 1 vertex is left of the end vertex
vTypes[sortedBrim[1]] = 2;
vTypes[sortedBrim[sortedBrim.size() - 1]] = 3;
left = sortedBrim[1];
right = sortedBrim[sortedBrim.size() - 1];
isClockwise = true;
} else {
// the brim index 1 vertex is right of the end vertex
vTypes[sortedBrim[1]] = 3;
vTypes[sortedBrim[sortedBrim.size() - 1]] = 2;
right = sortedBrim[1];
left = sortedBrim[sortedBrim.size() - 1];
isClockwise = false;
}
// determine candidate vertices
for (auto current : meridian) {
if (current == startIndex) continue;
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (vTypes[target] == 0) {
vTypes[target] = 4;
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (vTypes[target] == 0) {
vTypes[target] = 4;
}
reverse++;
}
}
// propagate the values
// on the left
current = left;
while (current != UINT_MAX) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (vTypes[target] == 4) {
vTypes[target] = 2;
current = target;
found = true;
break;
} else if (vTypes[target] == -1) {
current = UINT_MAX;
found = true;
break;
}
forward++;
}
if (found) continue;
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (vTypes[target] == 4) {
vTypes[target] = 2;
current = target;
found = true;
break;
} else if (vTypes[target] == -1) {
current = UINT_MAX;
found = true;
break;
}
reverse++;
}
}
// on the right
current = right;
while (current != UINT_MAX) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current) {
auto target = (*forward).second;
if (vTypes[target] == 4) {
vTypes[target] = 3;
current = target;
found = true;
break;
} else if (vTypes[target] == -1) {
current = UINT_MAX;
found = true;
break;
}
forward++;
}
if (found) continue;
while (reverse != edgesReverse[i].end() && (*reverse).first == current) {
auto target = (*reverse).second;
if (vTypes[target] == 4) {
vTypes[target] = 3;
current = target;
found = true;
break;
} else if (vTypes[target] == -1) {
current = UINT_MAX;
found = true;
break;
}
reverse++;
}
}
if (meridian.size() < 2) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The meridian is not long enough to proceed with the computation");
return false;
}
#if 0 // color meridian vertices
for (uint v = 0; v < this->vertexLevelAttachment[i].size(); v++) {
if (vTypes[v] == 1 || vTypes[v] == -1) { // red middle
this->colors[i][3 * v + 0] = 255;
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 0;
} else if (vTypes[v] == 2) { // green left
this->colors[i][3 * v + 0] = 0;
this->colors[i][3 * v + 1] = 255;
this->colors[i][3 * v + 2] = 0;
} else if (vTypes[v] == 3) { // blue right
this->colors[i][3 * v + 0] = 0;
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 255;
} else if (vTypes[v] == 4) { // candidates yellow
this->colors[i][3 * v + 0] = 255;
this->colors[i][3 * v + 1] = 255;
this->colors[i][3 * v + 2] = 0;
} else {
this->colors[i][3 * v + 0] = this->colors[i][3 * v + 0];
this->colors[i][3 * v + 1] = this->colors[i][3 * v + 1];
this->colors[i][3 * v + 2] = this->colors[i][3 * v + 2];
}
}
#endif
#ifdef SWEAT
// check whether the sweatband is clockwise or counter-clockwise
sweatIsClockwise = (vTypes[sweatSorted[1]] == 2);
#endif
this->rahiAngles[i].resize(this->atomIndexAttachment[i].size(), 0.0f);
this->rahiAngles[i].shrink_to_fit();
#if 1
// initialize the angle values of the circumpolar vertices
// for the brim
if (isClockwise) {
for (uint j = 0; j < static_cast<uint>(sortedBrim.size()); j++) {
this->rahiAngles[i][sortedBrim[j]] =
2.0f * thePi * (static_cast<float>(j) / static_cast<float>(sortedBrim.size()));
}
} else {
for (uint j = 0; j < static_cast<uint>(sortedBrim.size()); j++) {
this->rahiAngles[i][sortedBrim[j]] =
(2.0f * thePi) - (2.0f * thePi * (static_cast<float>(j) / static_cast<float>(sortedBrim.size())));
}
}
#endif
#ifdef SWEAT
// initialize the angle values of vertices of the sweatband
if (sweatIsClockwise) {
for (uint j = 0; j < static_cast<uint>(sweatSorted.size()); j++) {
this->rahiAngles[i][sweatSorted[j]] =
2.0f * thePi * (static_cast<float>(j) / static_cast<float>(sweatSorted.size()));
}
} else {
for (uint j = 0; j < static_cast<uint>(sweatSorted.size()); j++) {
this->rahiAngles[i][sweatSorted[j]] =
(2.0f * thePi) - (2.0f * thePi * (static_cast<float>(j) / static_cast<float>(sweatSorted.size())));
}
}
#endif
#if 1
// for the vertices around the binding site vertex
std::set<uint> bsVertices;
// search for the vertex right of the first meridian vertex
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][startIndex].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][startIndex].second;
while (forward != edgesForward[i].end() && (*forward).first == startIndex) {
auto target = (*forward).second;
bsVertices.insert(target);
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == startIndex) {
auto target = (*reverse).second;
bsVertices.insert(target);
reverse++;
}
if (bsVertices.size() < 3) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The binding site vertex lies in a degenerate region. Aborting...");
return false;
}
std::vector<uint> bsVertexCircle;
bsVertexCircle.push_back(meridian[meridian.size() - 2]);
for (auto v : bsVertices) {
if (vTypes[v] == 3) {
bsVertexCircle.push_back(v);
}
}
if (bsVertexCircle.size() != 2) {
megamol::core::utility::log::Log::DefaultLog.WriteError("Something went wrong during the circle computation. Aborting...");
return false;
}
std::set<uint> doneset = std::set<uint>(bsVertexCircle.begin(), bsVertexCircle.end());
while (bsVertexCircle.size() != bsVertices.size()) {
current = bsVertexCircle[bsVertexCircle.size() - 1];
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][current].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][current].second;
bool found = false;
while (forward != edgesForward[i].end() && (*forward).first == current && !found) {
auto target = (*forward).second;
if (doneset.count(target) == 0 && bsVertices.count(target) > 0) {
doneset.insert(target);
bsVertexCircle.push_back(target);
found = true;
}
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == current && !found) {
auto target = (*reverse).second;
if (doneset.count(target) == 0 && bsVertices.count(target) > 0) {
doneset.insert(target);
bsVertexCircle.push_back(target);
found = true;
}
reverse++;
}
}
for (uint j = 0; j < static_cast<uint>(bsVertexCircle.size()); j++) {
this->rahiAngles[i][bsVertexCircle[j]] =
2.0f * thePi * (static_cast<float>(j) / static_cast<float>(bsVertexCircle.size()));
}
#endif
// add north pole vertex to the mesh to be able to use the old code
uint newIndex = static_cast<uint>(this->vertexLevelAttachment[i].size());
this->vertices[i].push_back(0.0f);
this->vertices[i].push_back(0.0f);
this->vertices[i].push_back(0.0f);
this->colors[i].push_back(0);
this->colors[i].push_back(0);
this->colors[i].push_back(0);
this->normals[i].push_back(0.0f);
this->normals[i].push_back(1.0f);
this->normals[i].push_back(0.0f);
this->vertexLevelAttachment[i].push_back(UINT_MAX);
this->atomIndexAttachment[i].push_back(UINT_MAX);
this->bsDistanceAttachment[i].push_back(UINT_MAX);
this->rahiAngles[i].push_back(0.0f);
vTypes.push_back(-1);
// add a face for each neighbor of the new vertex
for (uint j = 0; j < static_cast<uint>(sortedBrim.size()); j++) {
this->faces[i].push_back(newIndex);
this->faces[i].push_back(sortedBrim[j]);
this->faces[i].push_back(sortedBrim[(j + 1) % sortedBrim.size()]);
this->edgesForward[i].push_back(std::pair<uint, uint>(newIndex, sortedBrim[j]));
this->edgesReverse[i].push_back(std::pair<uint, uint>(sortedBrim[j], newIndex));
this->edgesForward[i].push_back(std::pair<uint, uint>(newIndex, sortedBrim[(j + 1) % sortedBrim.size()]));
this->edgesReverse[i].push_back(std::pair<uint, uint>(sortedBrim[(j + 1) % sortedBrim.size()], newIndex));
// the other two edges should exist already
}
reconstructEdgeSearchStructures(i, newIndex + 1);
// compute valid vertex vector
std::vector<bool> validVertices(this->vertexLevelAttachment[i].size(), true);
validVertices.shrink_to_fit();
validVertices[startIndex] = false;
validVertices[endIndex] = false;
for (auto c : meridian) {
validVertices[c] = false;
}
for (auto c : sortedBrim) {
validVertices[c] = false;
}
#ifdef SWEAT
for (auto c : sweatSorted) {
validVertices[c] = false;
}
#endif
// vertex edge offset vector
std::vector<std::vector<SombreroKernels::Edge>> vertex_edge_offset_local(this->vertexLevelAttachment[i].size());
std::vector<uint> offsetDepth(this->vertexLevelAttachment[i].size(), 0);
vertex_edge_offset_local.shrink_to_fit();
for (uint j = 0; j < static_cast<uint>(vertex_edge_offset_local.size()); j++) {
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][j].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][j].second;
while (forward != edgesForward[i].end() && (*forward).first == j) {
auto target = (*forward).second;
SombreroKernels::Edge edge;
edge.vertex_id_0 = j;
edge.vertex_id_1 = target;
vertex_edge_offset_local[j].push_back(edge);
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == j) {
auto target = (*reverse).second;
SombreroKernels::Edge edge;
edge.vertex_id_0 = j;
edge.vertex_id_1 = target;
vertex_edge_offset_local[j].push_back(edge);
reverse++;
}
}
for (auto e : edgesForward[i]) { // compute the number of adjacent edges
offsetDepth[e.first]++;
offsetDepth[e.second]++;
}
uint sum = offsetDepth[0];
offsetDepth[0] = 0;
for (uint j = 1; j < offsetDepth.size(); j++) {
uint oldVal = offsetDepth[j];
offsetDepth[j] = sum;
sum += oldVal;
}
bool ret = this->cuda_kernels->CreatePhiValues(
0.01f, this->rahiAngles[i], validVertices, vertex_edge_offset_local, offsetDepth, vTypes);
if (!ret) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The CUDA angle diffusion failed");
return false;
}
// remove the added vertex
this->vertices[i].erase(this->vertices[i].end() - 3, this->vertices[i].end());
this->colors[i].erase(this->colors[i].end() - 3, this->colors[i].end());
this->normals[i].erase(this->normals[i].end() - 3, this->normals[i].end());
this->vertexLevelAttachment[i].pop_back();
this->atomIndexAttachment[i].pop_back();
this->bsDistanceAttachment[i].pop_back();
this->rahiAngles[i].pop_back();
uint addedFaceValues = static_cast<uint>(sortedBrim.size() * 3);
this->faces[i].erase(this->faces[i].end() - addedFaceValues, this->faces[i].end());
uint oldIndex = static_cast<uint>(this->vertexLevelAttachment[i].size());
auto rit = std::remove_if(this->edgesForward[i].begin(), this->edgesForward[i].end(),
[oldIndex](const std::pair<uint, uint>& e) { return ((e.first == oldIndex) || (e.second == oldIndex)); });
this->edgesForward[i].erase(rit, this->edgesForward[i].end());
rit = std::remove_if(this->edgesReverse[i].begin(), this->edgesReverse[i].end(),
[oldIndex](const std::pair<uint, uint>& e) { return ((e.first == oldIndex) || (e.second == oldIndex)); });
this->reconstructEdgeSearchStructures(i, oldIndex);
#if 0 // color by angle
for (uint v = 0; v < this->vertexLevelAttachment[i].size(); v++) {
this->colors[i][3 * v + 0] = 255 * (this->rahiAngles[i][v] / (2.0f * 3.14159265358979f));
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 0;
}
#endif
#if 0 // color by id
for (uint v = 0; v < this->vertexLevelAttachment[i].size(); v++) {
this->colors[i][3 * v + 0] = static_cast<unsigned char>(255 * (static_cast<float>(v) / static_cast<float>(this->vertexLevelAttachment[i].size())));
this->colors[i][3 * v + 1] = 0;
this->colors[i][3 * v + 2] = 0;
}
#endif
}
return true;
}
/*
* SombreroWarper::reconstructEdgeSearchStructures
*/
void SombreroWarper::reconstructEdgeSearchStructures(uint index, uint vertex_count) {
// sort the array
std::sort(edgesForward[index].begin(), edgesForward[index].end(),
[](const std::pair<unsigned int, unsigned int>& left, const std::pair<unsigned int, unsigned int>& right) {
return left.first < right.first;
});
std::sort(edgesReverse[index].begin(), edgesReverse[index].end(),
[](const std::pair<unsigned int, unsigned int>& left, const std::pair<unsigned int, unsigned int>& right) {
return left.first < right.first;
});
// construct the offset array
this->vertexEdgeOffsets[index] =
std::vector<std::pair<uint, uint>>(vertex_count, std::pair<uint, uint>(UINT_MAX, UINT_MAX));
for (uint i = 0; i < edgesForward[index].size(); i++) {
uint jj = edgesForward[index][i].first;
if (this->vertexEdgeOffsets[index][jj].first == UINT_MAX) {
this->vertexEdgeOffsets[index][jj].first = i;
}
}
for (uint i = 0; i < edgesReverse[index].size(); i++) {
uint jj = edgesReverse[index][i].first;
if (this->vertexEdgeOffsets[index][jj].second == UINT_MAX) {
this->vertexEdgeOffsets[index][jj].second = i;
}
}
// repair unset entries
for (uint i = 0; i < vertex_count; i++) {
if (this->vertexEdgeOffsets[index][i].first == UINT_MAX) {
uint j = i + 1;
while (j < vertex_count) {
if (this->vertexEdgeOffsets[index][j].first != UINT_MAX) {
this->vertexEdgeOffsets[index][i].first = this->vertexEdgeOffsets[index][j].first;
break;
}
j++;
}
if (j >= vertex_count) {
this->vertexEdgeOffsets[index][i].first = static_cast<uint>(this->edgesForward[index].size() - 1);
}
}
if (this->vertexEdgeOffsets[index][i].second == UINT_MAX) {
uint j = i + 1;
while (j < vertex_count) {
if (this->vertexEdgeOffsets[index][j].second != UINT_MAX) {
this->vertexEdgeOffsets[index][i].second = this->vertexEdgeOffsets[index][j].second;
break;
}
j++;
}
if (j >= vertex_count) {
this->vertexEdgeOffsets[index][i].second = static_cast<uint>(this->edgesReverse[index].size() - 1);
}
}
}
}
/**
* SombreroWarper::liftVertices
*/
bool SombreroWarper::liftVertices(void) {
// TODO currently not implemented, maybe needed later on
return true;
}
/**
* SombreroWarper::computeHeightPerVertex
*/
bool SombreroWarper::computeHeightPerVertex(uint bsVertex) {
bool flatmode = this->flatteningParam.Param<param::BoolParam>()->Value();
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
float maxHeight = this->sombreroLength[i] / 2.0f;
float minHeight = 0.0f - maxHeight;
uint maxBrimLevel = 0;
// all brim vertices have a y-position of + tunnellength / 2
for (size_t j = 0; j < this->vertexLevelAttachment[i].size(); j++) {
if (this->brimFlags[i][j]) {
this->vertices[i][3 * j + 1] = maxHeight;
if (this->bsDistanceAttachment[i][j] > maxBrimLevel) {
maxBrimLevel = this->bsDistanceAttachment[i][j];
}
}
}
// for the remaining vertices we have to perform a height diffusion, using the last vertices not belonging to
// the brim as source first step: identify these vertices
std::set<uint> borderSet;
std::set<uint> southBorder;
// go through all forward edges, if one vertex is on the brim and one is not, take the second one
for (auto e : this->edgesForward[i]) {
if (this->brimFlags[i][e.first] && !this->brimFlags[i][e.second]) {
borderSet.insert(e.second);
} else if (!this->brimFlags[i][e.first] && this->brimFlags[i][e.second]) {
borderSet.insert(e.first);
}
if (e.first == bsVertex) {
southBorder.insert(e.second);
} else if (e.second == bsVertex) {
southBorder.insert(e.first);
}
}
// get the number of non-brim vertices
uint newVertNum = static_cast<uint>(std::count(this->brimFlags[i].begin(), this->brimFlags[i].end(), false));
std::set<uint> newVertices;
// mapping of the new vertices to the old ones
std::vector<uint> vertMappingToOld(newVertNum);
// mapping of the old vertices to the new ones
std::vector<uint> vertMappingToNew(this->vertexLevelAttachment[i].size(), UINT_MAX);
uint idx = 0;
for (size_t j = 0; j < this->vertexLevelAttachment[i].size(); j++) {
if (!this->brimFlags[i][j]) {
auto cnt = newVertices.size();
newVertices.insert(static_cast<uint>(j));
// we have to do this to prevent multiple inserts
if (newVertices.size() != cnt) {
vertMappingToOld[idx] = static_cast<uint>(j);
vertMappingToNew[j] = idx;
idx++;
}
}
}
// build the necessary input fields
std::vector<float> zValues(newVertNum, 0.0f);
std::vector<bool> zValidity(newVertNum, true);
std::vector<std::vector<SombreroKernels::Edge>> zEdgeOffset(newVertNum);
std::vector<uint> zEdgeOffsetDepth(newVertNum);
std::vector<uint> zVertexWeights(newVertNum, 1u);
zValues[vertMappingToNew[bsVertex]] = minHeight;
zValidity[vertMappingToNew[bsVertex]] = false;
for (auto v : borderSet) { // north border
zValues[vertMappingToNew[v]] = maxHeight;
zValidity[vertMappingToNew[v]] = false;
}
float weight = this->southBorderHeightFactor.Param<param::FloatParam>()->Value();
for (auto v : southBorder) {
zValues[vertMappingToNew[v]] =
minHeight + weight * (maxHeight - minHeight) / static_cast<float>(maxBrimLevel);
zValidity[vertMappingToNew[v]] = false;
zVertexWeights[vertMappingToNew[v]] =
static_cast<uint>(this->southBorderWeightParam.Param<param::IntParam>()->Value());
}
for (auto e : this->edgesForward[i]) {
if (newVertices.count(e.first) > 0 && newVertices.count(e.second) > 0) {
SombreroKernels::Edge newEdge;
newEdge.vertex_id_0 = vertMappingToNew[e.first];
newEdge.vertex_id_1 = vertMappingToNew[e.second];
zEdgeOffset[newEdge.vertex_id_0].push_back(newEdge);
}
}
for (auto e : this->edgesReverse[i]) {
if (newVertices.count(e.first) > 0 && newVertices.count(e.second) > 0) {
SombreroKernels::Edge newEdge;
newEdge.vertex_id_0 = vertMappingToNew[e.first];
newEdge.vertex_id_1 = vertMappingToNew[e.second];
zEdgeOffset[newEdge.vertex_id_0].push_back(newEdge);
}
}
for (uint j = 0; j < zEdgeOffsetDepth.size(); j++) {
zEdgeOffsetDepth[j] = static_cast<uint>(zEdgeOffset[j].size());
}
uint sum = zEdgeOffsetDepth[0];
zEdgeOffsetDepth[0] = 0;
for (uint j = 1; j < zEdgeOffsetDepth.size(); j++) {
uint oldVal = zEdgeOffsetDepth[j];
zEdgeOffsetDepth[j] = sum;
sum += oldVal;
}
bool kernelRes =
this->cuda_kernels->CreateZValues(20000, zValues, zValidity, zEdgeOffset, zEdgeOffsetDepth, zVertexWeights);
if (!kernelRes) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The z-values kernel of the height computation failed!");
return false;
}
for (uint j = 0; j < zValues.size(); j++) {
auto idx = vertMappingToOld[j];
this->vertices[i][3 * idx + 1] = zValues[j];
}
}
return true;
}
/**
* SombreroWarper::computeXZCoordinatePerVertex
*/
bool SombreroWarper::computeXZCoordinatePerVertex(TunnelResidueDataCall& tunnelCall) {
bool flatmode = this->flatteningParam.Param<param::BoolParam>()->Value();
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
float minRad = this->sombreroRadius[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
switch (radiusSelectionSlot.Param<param::EnumParam>()->Value()) {
case 0: // Geometry-based
minRad = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
break;
case 1: // Exit radius
// do nothing since the radius is already correct
break;
case 2: // Bottleneck radius
if (tunnelCall.getTunnelNumber() > 0) {
minRad = tunnelCall.getTunnelDescriptions()[0].bottleneckRadius *
this->radiusScalingParam.Param<param::FloatParam>()->Value();
} else {
megamol::core::utility::log::Log::DefaultLog.WriteWarn(
"No tunnel descriptions given, falling back to geometry-based radius computation");
minRad = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
}
break;
default:
minRad = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
break;
}
float maxRad = minRad + this->brimWidth[i] * this->brimScalingParam.Param<param::FloatParam>()->Value();
std::set<uint> innerBorderSet;
// go through all forward edges, if one vertex is on the brim and one is not, take the second one
for (auto e : this->edgesForward[i]) {
if (this->brimFlags[i][e.first] && !this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.second);
} else if (!this->brimFlags[i][e.first] && this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.first);
}
}
std::set<uint> outerBorderSet = std::set<uint>(this->brimIndices[i].begin(), this->brimIndices[i].end());
std::set<uint> completeSet;
for (uint j = 0; j < this->vertexLevelAttachment[i].size(); j++) {
if (this->brimFlags[i][j]) {
completeSet.insert(j);
}
}
completeSet.insert(innerBorderSet.begin(), innerBorderSet.end());
uint newVertNum = static_cast<uint>(completeSet.size());
std::vector<float> zValues(newVertNum, 0.0f);
std::vector<bool> zValidity(newVertNum, true);
std::vector<std::vector<SombreroKernels::Edge>> zEdgeOffset(newVertNum);
std::vector<uint> zEdgeOffsetDepth(newVertNum);
std::vector<uint> zVertexWeights(newVertNum, 1u);
// mapping of the new vertices to the old ones
std::vector<uint> vertMappingToOld(newVertNum);
// mapping of the old vertices to the new ones
std::vector<uint> vertMappingToNew(this->vertexLevelAttachment[i].size(), UINT_MAX);
for (uint j = 0; j < newVertNum; j++) {
uint idx = *std::next(completeSet.begin(), j);
vertMappingToOld[j] = idx;
vertMappingToNew[idx] = j;
}
// compute validity flags and init values
for (auto v : completeSet) {
if (innerBorderSet.count(v) > 0) {
zValues[vertMappingToNew[v]] = minRad;
zValidity[vertMappingToNew[v]] = false;
}
if (outerBorderSet.count(v) > 0) {
zValues[vertMappingToNew[v]] = maxRad;
zValidity[vertMappingToNew[v]] = false;
}
}
// add edges
for (auto e : this->edgesForward[i]) {
if (completeSet.count(e.first) > 0 && completeSet.count(e.second) > 0) {
SombreroKernels::Edge newEdge;
newEdge.vertex_id_0 = vertMappingToNew[e.first];
newEdge.vertex_id_1 = vertMappingToNew[e.second];
zEdgeOffset[newEdge.vertex_id_0].push_back(newEdge);
}
}
for (auto e : this->edgesReverse[i]) {
if (completeSet.count(e.first) > 0 && completeSet.count(e.second) > 0) {
SombreroKernels::Edge newEdge;
newEdge.vertex_id_0 = vertMappingToNew[e.first];
newEdge.vertex_id_1 = vertMappingToNew[e.second];
zEdgeOffset[newEdge.vertex_id_0].push_back(newEdge);
}
}
// compute edge offset
for (uint j = 0; j < zEdgeOffsetDepth.size(); j++) {
zEdgeOffsetDepth[j] = static_cast<uint>(zEdgeOffset[j].size());
}
uint sum = zEdgeOffsetDepth[0];
zEdgeOffsetDepth[0] = 0;
for (uint j = 1; j < zEdgeOffsetDepth.size(); j++) {
uint oldVal = zEdgeOffsetDepth[j];
zEdgeOffsetDepth[j] = sum;
sum += oldVal;
}
bool kernelRes =
this->cuda_kernels->CreateZValues(20000, zValues, zValidity, zEdgeOffset, zEdgeOffsetDepth, zVertexWeights);
if (!kernelRes) {
megamol::core::utility::log::Log::DefaultLog.WriteError("The z-values kernel of the radius computation failed!");
return false;
}
// radius computation finished
float maxHeight = this->sombreroLength[i] / 2.0f;
float minHeight = 0.0f - maxHeight;
// compute the vertex position
for (uint v = 0; v < static_cast<uint>(this->vertexLevelAttachment[i].size()); v++) {
if (completeSet.count(v) > 0) {
// special case for the brim vertices
float radius = zValues[vertMappingToNew[v]];
float xCoord = radius * std::cos(this->rahiAngles[i][v]);
float zCoord = radius * std::sin(this->rahiAngles[i][v]);
this->vertices[i][3 * v + 0] = xCoord;
this->vertices[i][3 * v + 2] = zCoord;
if (flatmode) {
this->vertices[i][3 * v + 1] = maxHeight;
}
} else {
float l = this->sombreroLength[i] * this->lengthScalingParam.Param<param::FloatParam>()->Value();
float t = std::asin((this->vertices[i][3 * v + 1] - maxHeight) / l);
float cost = std::cos(t);
float xCoord = minRad * cost * std::cos(this->rahiAngles[i][v]);
float yCoord = this->vertices[i][3 * v + 1];
float zCoord = minRad * cost * std::sin(this->rahiAngles[i][v]);
if (flatmode) {
float alpha = (yCoord - minHeight) / (maxHeight - minHeight);
vislib::math::Vector<float, 2> vec(xCoord, zCoord);
vec.ScaleToLength(alpha * minRad);
xCoord = vec.GetX();
yCoord = maxHeight;
zCoord = vec.GetY();
}
this->vertices[i][3 * v + 0] = xCoord;
this->vertices[i][3 * v + 1] = yCoord;
this->vertices[i][3 * v + 2] = zCoord;
}
if (flatmode) {
auto help = this->vertices[i][3 * v + 2];
this->vertices[i][3 * v + 2] = this->vertices[i][3 * v + 1];
this->vertices[i][3 * v + 1] = help;
}
}
}
return true;
}
/*
* SombreroWarper::recomputeVertexNormals
*/
bool SombreroWarper::recomputeVertexNormals(TunnelResidueDataCall& tunnelCall) {
bool flatmode = this->flatteningParam.Param<param::BoolParam>()->Value();
bool invnormmode = this->invertNormalParam.Param<param::BoolParam>()->Value();
this->brimNormals = this->normals;
this->crownNormals = this->normals;
#ifdef NO_DEFORMATION // exit early if we want no new normals
return true;
#endif
for (size_t i = 0; i < this->meshVector.size(); i++) {
auto s_radius = this->sombreroRadius[i];
switch (radiusSelectionSlot.Param<param::EnumParam>()->Value()) {
case 0: // Geometry-based
s_radius = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
break;
case 1: // Exit radius
// do nothing since the radius is already correct
break;
case 2: // Bottleneck radius
if (tunnelCall.getTunnelNumber() > 0) {
s_radius = tunnelCall.getTunnelDescriptions()[0].bottleneckRadius *
this->radiusScalingParam.Param<param::FloatParam>()->Value();
} else {
megamol::core::utility::log::Log::DefaultLog.WriteWarn(
"No tunnel descriptions given, falling back to geometry-based radius computation");
s_radius = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
}
break;
default:
s_radius = this->sombreroRadiusNew[i] * this->radiusScalingParam.Param<param::FloatParam>()->Value();
break;
}
auto s_length = this->sombreroLength[i];
auto vert_cnt = this->vertices[i].size() / 3;
// detect the vertices marking the transition between hat and brim
std::set<uint> innerBorderSet;
// go through all forward edges, if one vertex is on the brim and one is not, take the second one
for (auto e : this->edgesForward[i]) {
if (this->brimFlags[i][e.first] && !this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.second);
} else if (!this->brimFlags[i][e.first] && this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.first);
}
}
vislib::math::Matrix<float, 4, vislib::math::COLUMN_MAJOR> scale;
scale.SetAt(0, 0, s_radius);
scale.SetAt(1, 1, s_length);
scale.SetAt(2, 2, s_radius);
scale.SetAt(3, 3, 1.0f);
auto scaleInv = scale;
scaleInv.Invert();
auto scaleInvTrans = scaleInv;
scaleInvTrans.Transpose();
for (size_t j = 0; j < vert_cnt; j++) {
vislib::math::Vector<float, 3> pos(&this->vertices[i][j * 3]);
vislib::math::Vector<float, 4> posA(pos[0], pos[1], pos[2], 1.0f);
// normalize the position so that the sombrero exit is at 0,0,0 and all vertices below it
pos[1] -= s_length / 2.0f;
auto spherePos = scaleInv * posA;
spherePos[3] = 0.0f;
auto n = scaleInvTrans * spherePos;
vislib::math::Vector<float, 3> normal(n.PeekComponents());
normal.Normalise();
if (invnormmode) {
normal = -normal;
}
if (this->brimFlags[i][j] || innerBorderSet.count(static_cast<uint>(j) > 0) || flatmode) {
this->normals[i][j * 3 + 0] = 0.0f;
this->normals[i][j * 3 + 1] = -1.0f;
this->normals[i][j * 3 + 2] = 0.0f;
if (invnormmode) {
this->normals[i][j * 3 + 1] = 1.0f;
}
} else {
this->normals[i][j * 3 + 0] = normal[0];
this->normals[i][j * 3 + 1] = normal[1];
this->normals[i][j * 3 + 2] = normal[2];
}
this->brimNormals[i][j * 3 + 0] = 0.0f;
this->brimNormals[i][j * 3 + 1] = -1.0f;
this->brimNormals[i][j * 3 + 2] = 0.0f;
if (invnormmode) {
this->brimNormals[i][j * 3 + 1] = 1.0f;
}
this->crownNormals[i][j * 3 + 0] = normal[0];
this->crownNormals[i][j * 3 + 1] = normal[1];
this->crownNormals[i][j * 3 + 2] = normal[2];
}
#if 0 // normal as color
for (size_t j = 0; j < vert_cnt; j++) {
this->colors[i][j * 3 + 0] = static_cast<uint>(255.0f * std::max(0.0f, this->normals[i][j * 3 + 0]));
this->colors[i][j * 3 + 1] = static_cast<uint>(255.0f * std::max(0.0f, this->normals[i][j * 3 + 1]));
this->colors[i][j * 3 + 2] = static_cast<uint>(255.0f * std::max(0.0f, this->normals[i][j * 3 + 2]));
}
#endif
}
if (flatmode) {
crownNormals = brimNormals;
}
return true;
}
/*
* SombreroWarper::divideMeshForOutput
*/
bool SombreroWarper::divideMeshForOutput(void) {
// reset the mesh vector
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
this->meshVector[i].SetVertexData(static_cast<uint>(this->vertices[i].size() / 3), this->vertices[i].data(),
this->normals[i].data(), this->colors[i].data(), nullptr, false);
this->meshVector[i].SetTriangleData(static_cast<uint>(this->faces[i].size() / 3), this->faces[i].data(), false);
this->meshVector[i].SetMaterial(nullptr);
this->meshVector[i].AddVertexAttribPointer(this->atomIndexAttachment[i].data());
this->meshVector[i].AddVertexAttribPointer(this->vertexLevelAttachment[i].data());
this->meshVector[i].AddVertexAttribPointer(this->bsDistanceAttachment[i].data());
}
for (size_t i = 0; i < this->meshVector.size(); i++) {
// detect the vertices marking the transition between hat and brim
std::set<uint> innerBorderSet;
// go through all forward edges, if one vertex is on the brim and one is not, take the second one
for (auto e : this->edgesForward[i]) {
if (this->brimFlags[i][e.first] && !this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.second);
} else if (!this->brimFlags[i][e.first] && this->brimFlags[i][e.second]) {
innerBorderSet.insert(e.first);
}
}
}
// copy the necessary faces
this->crownFaces.resize(this->faces.size());
this->brimFaces.resize(this->faces.size());
for (size_t i = 0; i < this->faces.size(); i++) {
this->crownFaces[i].clear();
this->brimFaces[i].clear();
for (size_t j = 0; j < this->faces[i].size() / 3; j++) {
uint v0 = this->faces[i][3 * j + 0];
uint v1 = this->faces[i][3 * j + 1];
uint v2 = this->faces[i][3 * j + 2];
if (this->brimFlags[i][v0] || this->brimFlags[i][v1] || this->brimFlags[i][v2]) {
this->brimFaces[i].push_back(v0);
this->brimFaces[i].push_back(v1);
this->brimFaces[i].push_back(v2);
} else {
this->crownFaces[i].push_back(v0);
this->crownFaces[i].push_back(v1);
this->crownFaces[i].push_back(v2);
}
}
}
this->outMeshVector.resize(2 * this->meshVector.size());
// reset the mesh vector
for (uint i = 0; i < static_cast<uint>(this->meshVector.size()); i++) {
this->outMeshVector[i * 2 + 0].SetVertexData(static_cast<uint>(this->vertices[i].size() / 3),
this->vertices[i].data(), this->brimNormals[i].data(), this->colors[i].data(), nullptr, false);
this->outMeshVector[i * 2 + 1].SetVertexData(static_cast<uint>(this->vertices[i].size() / 3),
this->vertices[i].data(), this->crownNormals[i].data(), this->colors[i].data(), nullptr, false);
this->outMeshVector[i * 2 + 0].SetTriangleData(
static_cast<uint>(this->brimFaces[i].size() / 3), this->brimFaces[i].data(), false);
this->outMeshVector[i * 2 + 1].SetTriangleData(
static_cast<uint>(this->crownFaces[i].size() / 3), this->crownFaces[i].data(), false);
this->outMeshVector[i * 2 + 0].SetMaterial(nullptr);
this->outMeshVector[i * 2 + 1].SetMaterial(nullptr);
this->outMeshVector[i * 2 + 0].AddVertexAttribPointer(this->atomIndexAttachment[i].data());
this->outMeshVector[i * 2 + 1].AddVertexAttribPointer(this->atomIndexAttachment[i].data());
this->outMeshVector[i * 2 + 0].AddVertexAttribPointer(this->vertexLevelAttachment[i].data());
this->outMeshVector[i * 2 + 1].AddVertexAttribPointer(this->vertexLevelAttachment[i].data());
this->outMeshVector[i * 2 + 0].AddVertexAttribPointer(this->bsDistanceAttachment[i].data());
this->outMeshVector[i * 2 + 1].AddVertexAttribPointer(this->bsDistanceAttachment[i].data());
}
return true;
}
/*
* SombreroWarper::fixBrokenMeshParts
*/
bool SombreroWarper::fixBrokenMeshParts(float maxDistance) {
for (size_t i = 0; i < this->meshVector.size(); i++) {
std::set<uint> outerBorderSet = std::set<uint>(this->brimIndices[i].begin(), this->brimIndices[i].end());
uint vert_cnt = this->vertices[i].size() / 3;
for (size_t v = 0; v < this->vertices[i].size() / 3; v++) {
std::vector<uint> neighbors;
// find the indices of the neighboring vertices
auto forward = edgesForward[i].begin() + this->vertexEdgeOffsets[i][v].first;
auto reverse = edgesReverse[i].begin() + this->vertexEdgeOffsets[i][v].second;
while (forward != edgesForward[i].end() && (*forward).first == v) {
auto target = (*forward).second;
neighbors.push_back(target);
forward++;
}
while (reverse != edgesReverse[i].end() && (*reverse).first == v) {
auto target = (*reverse).second;
neighbors.push_back(target);
reverse++;
}
std::unique(neighbors.begin(), neighbors.end());
uint tooLongCount = 0;
vislib::math::Vector<float, 3> neighavg(0.0f, 0.0f, 0.0f);
vislib::math::Vector<float, 3> mypos(&this->vertices[i][3 * v]);
for (auto t : neighbors) {
if (t < vert_cnt) {
vislib::math::Vector<float, 3> neighpos(&this->vertices[i][3 * t]);
neighavg += neighpos;
if ((mypos - neighpos).Length() > maxDistance) {
tooLongCount++;
}
}
}
neighavg /= static_cast<float>(neighbors.size());
if ((mypos - neighavg).Length() > maxDistance && outerBorderSet.count(v) == 0) {
this->vertices[i][3 * v + 0] = neighavg[0];
this->vertices[i][3 * v + 1] = neighavg[1];
this->vertices[i][3 * v + 2] = neighavg[2];
// for (auto t : neighbors) {
// this->colors[i][3 * t + 0] = 255;
// this->colors[i][3 * t + 1] = 0;
// this->colors[i][3 * t + 2] = 0;
//}
// this->colors[i][3 * v + 0] = 0;
// this->colors[i][3 * v + 1] = 0;
// this->colors[i][3 * v + 2] = 255;
}
}
}
return true;
}
| 44.116361 | 159 | 0.547308 | [
"mesh",
"geometry",
"vector"
] |
c2e1c1ad0cf742c27bff6571bd70a5f8c5ae4596 | 542 | cpp | C++ | atcoder/contests/abc171/B.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 18 | 2020-08-27T05:27:50.000Z | 2022-03-08T02:56:48.000Z | atcoder/contests/abc171/B.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | null | null | null | atcoder/contests/abc171/B.cpp | wingkwong/competitive-programming | e8bf7aa32e87b3a020b63acac20e740728764649 | [
"MIT"
] | 1 | 2020-10-13T05:23:58.000Z | 2020-10-13T05:23:58.000Z | /*
AtCoder Beginner Contest 171 - B - Mix Juice
https://atcoder.jp/contests/abc171/tasks/abc171_b
*/
#include <bits/stdc++.h>
using namespace std;
#define FAST_INP ios_base::sync_with_stdio(false);cin.tie(NULL)
int main()
{
FAST_INP;
int n,k;
cin >> n >> k;
vector<int> v(n);
// read the input
for(int i=0;i<n;i++) cin >> v[i];
// sort the input
sort(v.begin(),v.end());
int ans=0;
// sum the first k items up
for(int i=0;i<k;i++){
ans+=v[i];
}
cout << ans << endl;
return 0;
}
| 19.357143 | 64 | 0.571956 | [
"vector"
] |
c2e2195047ab7f1d1a89524bc1051b7fd7c4a7de | 379 | hpp | C++ | Projects/Cpp/Game/Breakout/BreakoutBrick.hpp | cimpresovec/Masters | d5705b72e1f9f19666d70a5ad6286fe6f5fb6c6c | [
"MIT"
] | null | null | null | Projects/Cpp/Game/Breakout/BreakoutBrick.hpp | cimpresovec/Masters | d5705b72e1f9f19666d70a5ad6286fe6f5fb6c6c | [
"MIT"
] | null | null | null | Projects/Cpp/Game/Breakout/BreakoutBrick.hpp | cimpresovec/Masters | d5705b72e1f9f19666d70a5ad6286fe6f5fb6c6c | [
"MIT"
] | null | null | null | #ifndef BREAKOUTBRICK_H
#define BREAKOUTBRICK_H
#include <raylib.h>
class BreakoutBrick
{
Rectangle collisionRectangle{0, 0, 80, 30};
bool _shouldDestroy = false;
Color color {};
public:
BreakoutBrick(const Vector2 position);
void render();
Rectangle getCollisionRectangle();
void destroy();
bool shouldDestroy();
};
#endif // BREAKOUTBRICK_H
| 18.047619 | 47 | 0.704485 | [
"render"
] |
c2e6f4ce79584d27db4c53eba952674291eceb73 | 399 | cpp | C++ | API/GameEngineContents/EnemyGreenEyegore.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | API/GameEngineContents/EnemyGreenEyegore.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | API/GameEngineContents/EnemyGreenEyegore.cpp | chaewoon83/WinApiPortfolio | e0f024a66a253a7e5b11e228cf9d0da93ddcc5ef | [
"MIT"
] | null | null | null | #include "EnemyGreenEyegore.h"
#include <windows.h>
#include <GameEngineBase/GameEngineWindow.h>
EnemyGreenEyegore::EnemyGreenEyegore()
{
}
EnemyGreenEyegore::~EnemyGreenEyegore()
{
}
void EnemyGreenEyegore::Start()
{
SetPosition(GameEngineWindow::GetScale().Half());
SetScale({ 500,500 });
}
void EnemyGreenEyegore::Update()
{
}
void EnemyGreenEyegore::Render()
{
DebugRectRender();
}
| 13.758621 | 50 | 0.736842 | [
"render"
] |
c2e7fc628901839031ee21fd7bfca64bb65e7cbb | 1,063 | cpp | C++ | boboleetcode/Play-Leetcode-master/0077-Combinations/cpp-0077/main3.cpp | yaominzh/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 2 | 2021-03-25T05:26:55.000Z | 2021-04-20T03:33:24.000Z | boboleetcode/Play-Leetcode-master/0077-Combinations/cpp-0077/main3.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | 6 | 2019-12-04T06:08:32.000Z | 2021-05-10T20:22:47.000Z | boboleetcode/Play-Leetcode-master/0077-Combinations/cpp-0077/main3.cpp | mcuallen/CodeLrn2019 | adc727d92904c5c5d445a2621813dfa99474206d | [
"Apache-2.0"
] | null | null | null | /// Source : https://leetcode.com/problems/combinations/description/
/// Author : liuyubobobo
/// Time : 2019-03-29
#include <iostream>
#include <vector>
using namespace std;
/// Using bit mask
/// Time Complexity: O(2^n * n)
/// Space Complexity: O(1)
class Solution {
public:
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> res;
int LIMIT = (1 << n);
for(int i = 0; i < LIMIT; i ++){
vector<int> tres = get_vector(i);
if(tres.size() == k) res.push_back(tres);
}
return res;
}
private:
vector<int> get_vector(int num){
vector<int> res;
int i = 1;
while(num){
if(num % 2) res.push_back(i);
i ++, num /= 2;
}
return res;
}
};
void print_vec(const vector<int>& vec){
for(int e: vec)
cout << e << " ";
cout << endl;
}
int main() {
vector<vector<int>> res = Solution().combine(4,2);
for( int i = 0 ; i < res.size() ; i ++ )
print_vec(res[i]);
return 0;
} | 18.649123 | 68 | 0.515522 | [
"vector"
] |
c2ea20fcab9f315c4d6d1448b422ea1f09914c1c | 13,731 | cpp | C++ | openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | 1 | 2016-12-29T08:45:03.000Z | 2016-12-29T08:45:03.000Z | openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | openstudiocore/src/model/ZoneHVACBaseboardRadiantConvectiveWater.cpp | jasondegraw/OpenStudio | 2ab13f6e5e48940929041444e40ad9d36f80f552 | [
"blessing"
] | null | null | null | /**********************************************************************
* Copyright (c) 2008-2016, Alliance for Sustainable Energy.
* All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********************************************************************/
#include "ZoneHVACBaseboardRadiantConvectiveWater.hpp"
#include "ZoneHVACBaseboardRadiantConvectiveWater_Impl.hpp"
#include "Schedule.hpp"
#include "Schedule_Impl.hpp"
#include "Surface.hpp"
#include "Surface_Impl.hpp"
#include "ThermalZone.hpp"
#include "ThermalZone_Impl.hpp"
#include "HVACComponent.hpp"
#include "HVACComponent_Impl.hpp"
#include "CoilHeatingWaterBaseboardRadiant.hpp"
#include "CoilHeatingWaterBaseboardRadiant_Impl.hpp"
#include "Model.hpp"
#include "Space.hpp"
#include "ScheduleTypeLimits.hpp"
#include "ScheduleTypeRegistry.hpp"
#include <utilities/idd/IddFactory.hxx>
#include <utilities/idd/OS_ZoneHVAC_Baseboard_RadiantConvective_Water_FieldEnums.hxx>
#include "../utilities/core/Assert.hpp"
namespace openstudio {
namespace model {
namespace detail {
ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const IdfObject& idfObject,
Model_Impl* model,
bool keepHandle)
: ZoneHVACComponent_Impl(idfObject,model,keepHandle)
{
OS_ASSERT(idfObject.iddObject().type() == ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType());
}
ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const openstudio::detail::WorkspaceObject_Impl& other,
Model_Impl* model,
bool keepHandle)
: ZoneHVACComponent_Impl(other,model,keepHandle)
{
OS_ASSERT(other.iddObject().type() == ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType());
}
ZoneHVACBaseboardRadiantConvectiveWater_Impl::ZoneHVACBaseboardRadiantConvectiveWater_Impl(const ZoneHVACBaseboardRadiantConvectiveWater_Impl& other,
Model_Impl* model,
bool keepHandle)
: ZoneHVACComponent_Impl(other,model,keepHandle)
{}
const std::vector<std::string>& ZoneHVACBaseboardRadiantConvectiveWater_Impl::outputVariableNames() const
{
static std::vector<std::string> result;
if (result.empty()){
}
return result;
}
IddObjectType ZoneHVACBaseboardRadiantConvectiveWater_Impl::iddObjectType() const {
return ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType();
}
std::vector<ScheduleTypeKey> ZoneHVACBaseboardRadiantConvectiveWater_Impl::getScheduleTypeKeys(const Schedule& schedule) const
{
std::vector<ScheduleTypeKey> result;
UnsignedVector fieldIndices = getSourceIndices(schedule.handle());
UnsignedVector::const_iterator b(fieldIndices.begin()), e(fieldIndices.end());
if (std::find(b,e,OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName) != e)
{
result.push_back(ScheduleTypeKey("ZoneHVACBaseboardRadiantConvectiveWater","Availability"));
}
return result;
}
unsigned ZoneHVACBaseboardRadiantConvectiveWater_Impl::inletPort() const
{
return 0; // this object has no inlet or outlet node
}
unsigned ZoneHVACBaseboardRadiantConvectiveWater_Impl::outletPort() const
{
return 0; // this object has no inlet or outlet node
}
boost::optional<ThermalZone> ZoneHVACBaseboardRadiantConvectiveWater_Impl::thermalZone() const
{
ModelObject thisObject = this->getObject<ModelObject>();
auto const thermalZones = this->model().getConcreteModelObjects<ThermalZone>();
for( auto const & thermalZone : thermalZones )
{
std::vector<ModelObject> equipment = thermalZone.equipment();
if( std::find(equipment.begin(),equipment.end(),thisObject) != equipment.end() )
{
return thermalZone;
}
}
return boost::none;
}
bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::addToThermalZone(ThermalZone & thermalZone)
{
Model m = this->model();
if( thermalZone.model() != m || thermalZone.isPlenum() )
{
return false;
}
removeFromThermalZone();
thermalZone.setUseIdealAirLoads(false);
thermalZone.addEquipment(this->getObject<ZoneHVACComponent>());
return true;
}
void ZoneHVACBaseboardRadiantConvectiveWater_Impl::removeFromThermalZone()
{
if ( auto thermalZone = this->thermalZone() ) {
thermalZone->removeEquipment(this->getObject<ZoneHVACComponent>());
}
}
std::vector<Surface> ZoneHVACBaseboardRadiantConvectiveWater_Impl::surfaces() const {
//vector to hold all of the surfaces that this radiant system is attached to
std::vector<Surface> surfaces;
//get the thermal zone this equipment belongs to
if (auto const thermalZone = this->thermalZone()) {
//loop through all the spaces in this zone
for (auto const & space : thermalZone->spaces()){
//loop through all the surfaces in this space
for (auto const & surface : space.surfaces()){
surfaces.push_back(surface);
}
}
}
return surfaces;
}
std::vector<ModelObject> ZoneHVACBaseboardRadiantConvectiveWater_Impl::children() const
{
std::vector<ModelObject> result;
if (OptionalHVACComponent intermediate = optionalHeatingCoil()) {
result.push_back(*intermediate);
}
return result;
}
ModelObject ZoneHVACBaseboardRadiantConvectiveWater_Impl::clone(Model model) const
{
auto baseboardRadConvWaterClone = ZoneHVACComponent_Impl::clone(model).cast<ZoneHVACBaseboardRadiantConvectiveWater>();
auto t_heatingCoil = heatingCoil();
auto heatingCoilClone = t_heatingCoil.clone(model).cast<HVACComponent>();
baseboardRadConvWaterClone.setHeatingCoil(heatingCoilClone);
if( model == this->model() ) {
if( auto plant = t_heatingCoil.plantLoop() ) {
plant->addDemandBranchForComponent(heatingCoilClone);
}
}
return baseboardRadConvWaterClone;
}
std::vector<IdfObject> ZoneHVACBaseboardRadiantConvectiveWater_Impl::remove()
{
if( auto waterHeatingCoil = heatingCoil().optionalCast<CoilHeatingWaterBaseboardRadiant>() ) {
if( boost::optional<PlantLoop> plantLoop = waterHeatingCoil->plantLoop() ) {
plantLoop->removeDemandBranchWithComponent( waterHeatingCoil.get() );
}
}
return ZoneHVACComponent_Impl::remove();
}
Schedule ZoneHVACBaseboardRadiantConvectiveWater_Impl::availabilitySchedule() const {
boost::optional<Schedule> value = optionalAvailabilitySchedule();
if (!value) {
LOG_AND_THROW(briefDescription() << " does not have an Availability Schedule attached.");
}
return value.get();
}
double ZoneHVACBaseboardRadiantConvectiveWater_Impl::fractionRadiant() const {
boost::optional<double> value = getDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionRadiant,true);
OS_ASSERT(value);
return value.get();
}
double ZoneHVACBaseboardRadiantConvectiveWater_Impl::fractionofRadiantEnergyIncidentonPeople() const {
boost::optional<double> value = getDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionofRadiantEnergyIncidentonPeople,true);
OS_ASSERT(value);
return value.get();
}
HVACComponent ZoneHVACBaseboardRadiantConvectiveWater_Impl::heatingCoil() const {
boost::optional<HVACComponent> value = optionalHeatingCoil();
if (!value) {
LOG_AND_THROW(briefDescription() << " does not have an Heating Coil attached.");
}
return value.get();
}
bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setAvailabilitySchedule(Schedule& schedule) {
bool result = setSchedule(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName,
"ZoneHVACBaseboardRadiantConvectiveWater",
"Availability",
schedule);
return result;
}
bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setFractionRadiant(double fractionRadiant) {
bool result = setDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionRadiant, fractionRadiant);
return result;
}
bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setFractionofRadiantEnergyIncidentonPeople(double fractionofRadiantEnergyIncidentonPeople) {
bool result = setDouble(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::FractionofRadiantEnergyIncidentonPeople, fractionofRadiantEnergyIncidentonPeople);
return result;
}
bool ZoneHVACBaseboardRadiantConvectiveWater_Impl::setHeatingCoil(const HVACComponent& radBaseboardHeatingCoil) {
bool result = setPointer(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::HeatingCoilName, radBaseboardHeatingCoil.handle());
return result;
}
boost::optional<Schedule> ZoneHVACBaseboardRadiantConvectiveWater_Impl::optionalAvailabilitySchedule() const {
return getObject<ModelObject>().getModelObjectTarget<Schedule>(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::AvailabilityScheduleName);
}
boost::optional<HVACComponent> ZoneHVACBaseboardRadiantConvectiveWater_Impl::optionalHeatingCoil() const {
return getObject<ModelObject>().getModelObjectTarget<HVACComponent>(OS_ZoneHVAC_Baseboard_RadiantConvective_WaterFields::HeatingCoilName);
}
} // detail
ZoneHVACBaseboardRadiantConvectiveWater::ZoneHVACBaseboardRadiantConvectiveWater(const Model& model)
: ZoneHVACComponent(ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType(),model)
{
OS_ASSERT(getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>());
bool ok = true;
auto alwaysOn = model.alwaysOnDiscreteSchedule();
ok = setAvailabilitySchedule( alwaysOn );
OS_ASSERT(ok);
ok = setFractionRadiant( 0.3 );
OS_ASSERT(ok);
ok = setFractionofRadiantEnergyIncidentonPeople( 0.3 );
OS_ASSERT(ok);
CoilHeatingWaterBaseboardRadiant coil( model );
ok = setHeatingCoil( coil );
OS_ASSERT(ok);
}
IddObjectType ZoneHVACBaseboardRadiantConvectiveWater::iddObjectType() {
return IddObjectType(IddObjectType::OS_ZoneHVAC_Baseboard_RadiantConvective_Water);
}
Schedule ZoneHVACBaseboardRadiantConvectiveWater::availabilitySchedule() const {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->availabilitySchedule();
}
double ZoneHVACBaseboardRadiantConvectiveWater::fractionRadiant() const {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->fractionRadiant();
}
double ZoneHVACBaseboardRadiantConvectiveWater::fractionofRadiantEnergyIncidentonPeople() const {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->fractionofRadiantEnergyIncidentonPeople();
}
HVACComponent ZoneHVACBaseboardRadiantConvectiveWater::heatingCoil() const {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->heatingCoil();
}
bool ZoneHVACBaseboardRadiantConvectiveWater::setAvailabilitySchedule(Schedule& schedule) {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setAvailabilitySchedule(schedule);
}
bool ZoneHVACBaseboardRadiantConvectiveWater::setFractionRadiant(double fractionRadiant) {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setFractionRadiant(fractionRadiant);
}
bool ZoneHVACBaseboardRadiantConvectiveWater::setFractionofRadiantEnergyIncidentonPeople(double fractionofRadiantEnergyIncidentonPeople) {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setFractionofRadiantEnergyIncidentonPeople(fractionofRadiantEnergyIncidentonPeople);
}
bool ZoneHVACBaseboardRadiantConvectiveWater::setHeatingCoil(const HVACComponent& radBaseboardHeatingCoil) {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->setHeatingCoil(radBaseboardHeatingCoil);
}
boost::optional<ThermalZone> ZoneHVACBaseboardRadiantConvectiveWater::thermalZone() {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->thermalZone();
}
bool ZoneHVACBaseboardRadiantConvectiveWater::addToThermalZone(ThermalZone & thermalZone) {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->addToThermalZone(thermalZone);
}
void ZoneHVACBaseboardRadiantConvectiveWater::removeFromThermalZone() {
return getImpl<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl>()->removeFromThermalZone();
}
/// @cond
ZoneHVACBaseboardRadiantConvectiveWater::ZoneHVACBaseboardRadiantConvectiveWater(std::shared_ptr<detail::ZoneHVACBaseboardRadiantConvectiveWater_Impl> impl)
: ZoneHVACComponent(impl)
{}
/// @endcond
} // model
} // openstudio
| 40.504425 | 163 | 0.740369 | [
"object",
"vector",
"model"
] |
c2edfbf8d2c8cb15f522c3f6d6bfef50c0f16810 | 4,964 | cpp | C++ | Engine/Src/SFCore/Util/SFLog.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | 1 | 2020-06-20T07:35:25.000Z | 2020-06-20T07:35:25.000Z | Engine/Src/SFCore/Util/SFLog.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | Engine/Src/SFCore/Util/SFLog.cpp | blue3k/StormForge | 1557e699a673ae9adcc8f987868139f601ec0887 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
//
// CopyRight (c) Kyungkun Ko
//
// Author : KyungKun Ko
//
// Description : Log
//
//
////////////////////////////////////////////////////////////////////////////////
#include "SFCorePCH.h"
#include "SFTypedefs.h"
#include "Util/SFStrUtil.h"
#include "Util/SFTimeUtil.h"
#include "Util/SFLog.h"
#include "Multithread/SFThread.h"
#include "Object/SFSharedObject.h"
#include "Service/SFService.h"
#include "MemoryManager/SFMemoryManager.h"
#if SF_PLATFORM == SF_PLATFORM_WINDOWS
// For crash dump
#pragma comment(lib, "Dbghelp.lib")
#endif
namespace SF {
namespace Log {
////////////////////////////////////////////////////////////////////////////////
//
// Trace Log Module
//
LogOutputHandler::LogOutputHandler(const LogOutputMask& outputMask)
: m_OutputMask(outputMask)
{
}
LogOutputHandler::~LogOutputHandler()
{
}
////////////////////////////////////////////////////////////////////////////////
//
// Trace Log Module
//
constexpr StringCrc64 LogModule::TypeName;
LogModule::LogModule(const LogOutputMask& logOutputGlobalMask)
: LibraryComponent("Log")
, LogService(logOutputGlobalMask)
, m_Thread([&](Thread* pThread) { Run(pThread); })
, m_OutputHandlers(GetSystemHeap())
{
Service::LogModule = this;
m_Thread.SetThreadName("LogThread");
m_Thread.Start();
m_Thread.SetPriority(Thread::PRIORITY::HIGHEST);
}
LogModule::~LogModule()
{
SFLog(System, Info, "Logging system terminated");
Flush();
m_Thread.SetKillEvent();
Service::LogModule = nullptr;
}
void LogModule::Run(Thread* pThread)
{
constexpr DurationMS flushWaitTime(3 * 1000);
while (!pThread->CheckKillEvent(DurationMS(3)))
{
auto timeWaitStart = Util::Time.GetTimeMs();
bool flushed = false;
auto pLockBuffer = m_LogSpinBuffer.Read_Lock( [&]()
{
// Flush if there is no log over 1 sec
if (!flushed && Util::TimeSince(timeWaitStart) > flushWaitTime)
{
flushed = true;
timeWaitStart = Util::Time.GetTimeMs();
for (auto itOutput : m_OutputHandlers)
{
itOutput->Flush();
}
}
// stop waiting if kill event has set
if (pThread->CheckKillEvent(DurationMS(0)))
return false;
return true;
});
if (pLockBuffer != nullptr)
{
LogItem& logItem = pLockBuffer->Data;
m_LogTimeMS = Util::Time.GetTimeMs();
for (auto itOutput : m_OutputHandlers)
{
if ((itOutput->GetOutputMask().Composited & logItem.OutputMask.Composited) != logItem.OutputMask.Composited)
continue;
itOutput->PrintOutput(&logItem);
}
m_LogSpinBuffer.Read_Unlock(pLockBuffer);
}
}
}
Result LogModule::InitializeComponent()
{
return LibraryComponent::InitializeComponent();
}
void LogModule::DeinitializeComponent()
{
Flush();
LibraryComponent::DeinitializeComponent();
}
// output handler
void LogModule::RegisterOutputHandler(LogOutputHandler* output)
{
if (output == nullptr) return;
m_OutputHandlers.push_back(output);
}
void LogModule::UnregisterOutputHandler(LogOutputHandler* output)
{
if (output == nullptr) return;
m_OutputHandlers.RemoveItem(output);
}
void* LogModule::ReserveWriteBuffer()
{
// prevent logging on log thread, it can cause deadlock
if (ThisThread::GetThreadID() == m_Thread.GetThreadID())
{
return nullptr;
}
auto pSpinBlock = m_LogSpinBuffer.Write_Lock();
pSpinBlock->Data.TimeStamp = std::chrono::system_clock::now();
return pSpinBlock;
}
void LogModule::ReleaseWriteBuffer(void* pBuffer, size_t messageSize)
{
LogSpinBuffer::BLOCK* pWriteBuffer = (LogSpinBuffer::BLOCK*)pBuffer;
char *pOutBuff = pWriteBuffer->Data.LogBuff;
int orgBuffLen = sizeof(pWriteBuffer->Data.LogBuff);
pOutBuff += messageSize;
int buffLen = orgBuffLen - (int)messageSize;
// pending \r\n
StrUtil::StringCopyEx(pOutBuff, buffLen, "\n");
pWriteBuffer->Data.LogStringSize = messageSize + 1;
m_LogSpinBuffer.Write_Unlock(pWriteBuffer);
}
size_t LogModule::WriteTimeTag(Log::LogItem* pLogItem)
{
std::time_t logTime = std::chrono::system_clock::to_time_t(pLogItem->TimeStamp);
auto tm = std::localtime(&logTime);
pLogItem->LogStringSize = StrUtil::Format(pLogItem->LogBuff, "{0}:{1}:{2} {3}:[{4}] ", tm->tm_hour, tm->tm_min, tm->tm_sec, pLogItem->Channel->ChannelName, ToString(pLogItem->OutputType));
return pLogItem->LogStringSize;
}
// Flush log queue
void LogModule::Flush()
{
auto writePosition = m_LogSpinBuffer.GetWritePosition();
do
{
auto readPosition = m_LogSpinBuffer.GetReadPosition();
if (writePosition - readPosition <= 0)
break;
} while (1);
}
} // namespace Log
} // namespace SF
| 22.563636 | 191 | 0.618453 | [
"object"
] |
c2f429b78e23e815f74692ea57a245b8a1d0f167 | 9,984 | cpp | C++ | src/Pegasus/ProviderManager2/CMPI/CMPI_Cql2Dnf.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 1 | 2021-11-12T21:28:50.000Z | 2021-11-12T21:28:50.000Z | src/Pegasus/ProviderManager2/CMPI/CMPI_Cql2Dnf.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 39 | 2021-01-18T19:28:41.000Z | 2022-03-27T20:55:36.000Z | src/Pegasus/ProviderManager2/CMPI/CMPI_Cql2Dnf.cpp | natronkeltner/openpegasus | e64f383c1ed37826041fc63e83b4e65fc1c679ae | [
"ICU",
"Unlicense",
"OpenSSL",
"MIT"
] | 4 | 2021-07-09T12:52:33.000Z | 2021-12-21T15:05:59.000Z | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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 "CMPI_Version.h"
#include <Pegasus/Common/Stack.h>
#include <Pegasus/CQL/CQLParser.h>
#include <Pegasus/CQL/CQLSelectStatementRep.h>
#include <Pegasus/CQL/CQLExpression.h>
#include <Pegasus/CQL/CQLSimplePredicate.h>
#include <Pegasus/CQL/CQLPredicate.h>
#include <Pegasus/CQL/CQLValue.h>
#include <Pegasus/Common/Tracer.h>
#include "CMPI_Cql2Dnf.h"
PEGASUS_USING_STD;
PEGASUS_NAMESPACE_BEGIN
//
// Routine to map the CQL data to String
//
String CQL2String (const CQLExpression & o)
{
CQLValue val;
if (o.isSimpleValue ())
{
val = o.getTerms ()[0].getFactors ()[0].getValue ();
}
else
{
return "NULL_VALUE";
}
return o.toString ();
}
//
// Routine to map the CQL type to CMPIPredOp
//
CMPIPredOp CQL2PredOp (ExpressionOpType op, Boolean isInverted)
{
CMPIPredOp op_type = (CMPIPredOp) 0;
switch (op)
{
case LT:
if (isInverted)
{
op_type = CMPI_PredOp_GreaterThan;
}
else
{
op_type = CMPI_PredOp_LessThan;
}
break;
case GT:
if (isInverted)
{
op_type = CMPI_PredOp_LessThan;
}
else
{
op_type = CMPI_PredOp_GreaterThan;
}
break;
case EQ:
if (isInverted)
{
op_type = CMPI_PredOp_NotEquals;
}
else
{
op_type = CMPI_PredOp_Equals;
}
break;
case LE:
if (isInverted)
{
op_type = CMPI_PredOp_GreaterThanOrEquals;
}
else
{
op_type = CMPI_PredOp_LessThanOrEquals;
}
break;
case GE:
if (isInverted)
{
op_type = CMPI_PredOp_LessThanOrEquals;
}
else
{
op_type = CMPI_PredOp_GreaterThanOrEquals;
}
break;
case NE:
if (isInverted)
{
op_type = CMPI_PredOp_Equals;
}
else
{
op_type = CMPI_PredOp_NotEquals;
}
break;
/* CMPI does not sport this operation. We convert the
IS NULL to EQ operation. (or NE if "IS NULL" has 'NOT' in
front (isInverted == true).
*/
case IS_NULL:
if (isInverted)
{
op_type = CMPI_PredOp_NotEquals;
}
else
{
op_type = CMPI_PredOp_Equals;
}
break;
case IS_NOT_NULL:
if (isInverted)
{
op_type = CMPI_PredOp_Equals;
}
else
{
op_type = CMPI_PredOp_NotEquals;
}
break;
case ISA:
if (isInverted)
{
op_type = CMPI_PredOp_NotIsa;
}
else
{
op_type = CMPI_PredOp_Isa;
}
break;
case LIKE:
if (isInverted)
{
op_type = CMPI_PredOp_NotLike;
}
else
{
op_type = CMPI_PredOp_Like;
}
break;
default:
break;
}
return op_type;
}
//
// Routine to map the CQL Value type to CMPI_QueryOperand type.
//
CMPI_QueryOperand::Type CQL2Type(CQLValue::CQLValueType typ)
{
switch (typ)
{
case CQLValue::Sint64_type:
return CMPI_QueryOperand::SINT64_TYPE;
case CQLValue::Uint64_type:
return CMPI_QueryOperand::UINT64_TYPE;
case CQLValue::Real_type:
return CMPI_QueryOperand::REAL_TYPE;
case CQLValue::String_type:
return CMPI_QueryOperand::STRING_TYPE;
case CQLValue::CIMDateTime_type:
return CMPI_QueryOperand::DATETIME_TYPE;
case CQLValue::CIMReference_type:
return CMPI_QueryOperand::REFERENCE_TYPE;
case CQLValue::CQLIdentifier_type:
return CMPI_QueryOperand::PROPERTY_TYPE;
case CQLValue::CIMObject_type:
/* There is not such thing as object type. */
break;
case CQLValue::Boolean_type:
return CMPI_QueryOperand::BOOLEAN_TYPE;
default:
break;
}
return CMPI_QueryOperand::NULL_TYPE;
}
void CMPI_Cql2Dnf::_populateTableau()
{
PEG_METHOD_ENTER(
TRC_CMPIPROVIDERINTERFACE,
"CMPI_Cql2Dnf::_populateTableau()");
cqs.validate ();
cqs.applyContext ();
cqs.normalizeToDOC ();
CQLPredicate cqsPred = cqs.getPredicate ();
Array <CQLPredicate> pred_Array;
Array <BooleanOpType> oper_Array = cqsPred.getOperators();
if (cqsPred.isSimple())
{
pred_Array.append(cqsPred);
}
else
{
pred_Array = cqsPred.getPredicates();
}
_tableau.reserveCapacity(pred_Array.size());
PEG_TRACE((TRC_CMPIPROVIDERINTERFACE,Tracer::LEVEL4,
"Expression: %s",(const char*)cqs.toString().getCString()));
CMPI_TableauRow tr;
CQLValue dummy("");
for (Uint32 i = 0; i < pred_Array.size (); i++)
{
CQLPredicate pred = pred_Array[i];
if (pred.isSimple())
{
CQLSimplePredicate simple = pred.getSimplePredicate();
CQLExpression lhs_cql = simple.getLeftExpression();
CQLExpression rhs_cql = simple.getRightExpression();
CMPIPredOp opr =
CQL2PredOp(simple.getOperation(), pred.getInverted());
CQLValue lhs_val;
CQLValue rhs_val;
if (lhs_cql.isSimpleValue())
{
//if (lhs_cql.getTerms ().size () != 0)
lhs_val = lhs_cql.getTerms()[0].getFactors()[0].getValue();
}
else
{
lhs_val = dummy;
}
if (rhs_cql.isSimpleValue())
{
//if (rhs_cql.getTerms ().size () != 0)
rhs_val = rhs_cql.getTerms()[0].getFactors()[0].getValue();
}
else
{
rhs_val = dummy;
}
// Have both side of the operation, such as 'A < 2'
CMPI_QueryOperand lhs(
CQL2String(lhs_cql),
CQL2Type(lhs_val.getValueType()));
CMPI_QueryOperand rhs(
CQL2String(rhs_cql),
CQL2Type(rhs_val.getValueType()));
// Add it as an row to the table row.
tr.append(CMPI_term_el(false, opr, lhs, rhs));
if (i < oper_Array.size())
{
// If the next operation is OR (disjunction), then treat
// the table row as as set of conjunctions and ..
if (oper_Array[i] == OR)
{
/* put the table of conjunctives in the tableau. Each
element in the tableau is a set of conjunctives.
It is understood that the boolean logic seperating
the conjunctives is the disjunctive operator (OR).
*/
_tableau.append(tr);
// Clear the table of conjunctives for the next operands.
tr.clear();
}
// If the operator is a conjunction, let the operands pile up
// on the table row until there is disjunction (OR) or there
// are ..
}
else
{
// ... no more operations. This is the last operand. Add it
// to the tableau as a disjunctions.
_tableau.append(tr);
}
}
}
PEG_METHOD_EXIT();
}
CMPI_Cql2Dnf::CMPI_Cql2Dnf(const CQLSelectStatement qs): cqs(qs)
{
PEG_METHOD_ENTER(
TRC_CMPIPROVIDERINTERFACE,
"CMPI_Cql2Dnf::CMPI_Cql2Dnf()");
_tableau.clear();
_populateTableau();
PEG_METHOD_EXIT();
}
CMPI_Cql2Dnf::~CMPI_Cql2Dnf()
{
}
PEGASUS_NAMESPACE_END
| 29.538462 | 80 | 0.536058 | [
"object"
] |
c2fa6bade20d0c30a03252e2b391e1c543da0429 | 13,287 | cpp | C++ | collab/sessions/sessions.cpp | alecmus/collab | 5d2d968b6dca6734d1f981eb273082c092d2056e | [
"MIT"
] | null | null | null | collab/sessions/sessions.cpp | alecmus/collab | 5d2d968b6dca6734d1f981eb273082c092d2056e | [
"MIT"
] | null | null | null | collab/sessions/sessions.cpp | alecmus/collab | 5d2d968b6dca6734d1f981eb273082c092d2056e | [
"MIT"
] | 1 | 2022-03-22T08:08:14.000Z | 2022-03-22T08:08:14.000Z | /*
** MIT License
**
** Copyright(c) 2021 Alec Musasa
**
** 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 noticeand 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 "../impl.h"
// serialize template to make collab::session serializable
template<class Archive>
void serialize(Archive& ar, collab::session& cls, const unsigned int version) {
ar& cls.unique_id;
ar& cls.name;
ar& cls.description;
ar& cls.passphrase_hash;
}
// serialize template to make session_broadcast_structure serializable
template<class Archive>
void serialize(Archive& ar, session_broadcast_structure& cls, const unsigned int version) {
ar& cls.source_node_unique_id;
ar& cls.session_list;
}
bool serialize_session_broadcast_structure(const session_broadcast_structure& cls,
std::string& serialized, std::string& error) {
error.clear();
std::stringstream ss;
try {
boost::archive::text_oarchive oa(ss);
oa& cls;
}
catch (const std::exception& e) {
error = e.what();
return false;
}
// encode to base64
serialized = liblec::leccore::base64::encode(ss.str());
return true;
}
bool deserialize_session_broadcast_structure(const std::string& serialized,
session_broadcast_structure& cls, std::string& error) {
std::stringstream ss;
// decode from base64
ss << liblec::leccore::base64::decode(serialized);
try {
boost::archive::text_iarchive ia(ss);
ia& cls;
return true;
}
catch (const std::exception& e) {
error = e.what();
return false;
}
}
void collab::impl::session_broadcast_sender_func(impl* p_impl) {
// create a broadcast sender object
liblec::lecnet::udp::broadcast::sender sender(SESSION_BROADCAST_PORT);
// loop until _stop_session_broadcast is false
while (true) {
{
liblec::auto_mutex lock(p_impl->_session_broadcast_mutex);
// check flag
if (p_impl->_stop_session_broadcast)
break;
}
std::string error;
std::vector<session> local_session_list;
// get session list from local database
if (p_impl->_collab.get_local_sessions(local_session_list, error)) {
// make a session broadcast object
std::string serialized_session_list;
session_broadcast_structure cls;
cls.source_node_unique_id = p_impl->_collab.unique_id();
cls.session_list = local_session_list;
// serialize the session broadcast object
if (serialize_session_broadcast_structure(cls, serialized_session_list, error)) {
// broadcast the serialized object
unsigned long actual_count = 0;
if (sender.send(serialized_session_list, 1, 0, actual_count, error)) {
// broadcast successful
}
}
}
// take a breath
std::this_thread::sleep_for(std::chrono::milliseconds{ session_broadcast_cycle });
}
}
void collab::impl::session_broadcast_receiver_func(impl* p_impl) {
// create broadcast receiver object
liblec::lecnet::udp::broadcast::receiver receiver(SESSION_BROADCAST_PORT, "0.0.0.0");
// loop until _stop_session_broadcast is false
while (true) {
{
liblec::auto_mutex lock(p_impl->_session_broadcast_mutex);
// check flag
if (p_impl->_stop_session_broadcast)
break;
}
std::string error;
// run the receiver
if (receiver.run(session_receiver_cycle, error)) {
// loop while running
while (receiver.running())
std::this_thread::sleep_for(std::chrono::milliseconds(1));
// no longer running ... check if a datagram was received
std::string serialized_session_list;
if (receiver.get(serialized_session_list, error)) {
// datagram received ... deserialize
session_broadcast_structure cls;
if (deserialize_session_broadcast_structure(serialized_session_list, cls, error)) {
// deserialized successfully
// check if data is coming from a different node
if (cls.source_node_unique_id == p_impl->_collab.unique_id())
continue; // ignore this data
std::vector<session> local_session_list;
// get session list from local database
if (!p_impl->_collab.get_sessions(local_session_list, error)) {
// database may be empty or table may not exist, so ignore
}
// check if any session is missing in the local database
for (const auto& it : cls.session_list) {
bool found = false;
for (const auto& m_it : local_session_list) {
if (it.unique_id == m_it.unique_id) {
found = true;
break;
}
}
if (!found) {
p_impl->_log("Session received (UDP): '" + it.name + "' (source node: " + shorten_unique_id(cls.source_node_unique_id) + ")");
// add this session to the local database
if (p_impl->_collab.create_session(it, error)) {
// session added successfully to the local database, add it to the temporary session list
if (p_impl->_collab.create_temporary_session_entry(it.unique_id, error))
p_impl->_log("Temporary session entry successful for '" + it.name + "'");
else
p_impl->_log("Creating temporary session entry for '" + it.name + "' failed: " + error);
}
else
p_impl->_log("Creating session '" + it.name + "' failed: " + error);
}
}
}
}
}
receiver.stop();
}
}
bool collab::create_session(const session& session, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
// create table if it doesn't exist
if (!con.execute("CREATE TABLE IF NOT EXISTS Sessions "
"(UniqueID TEXT, Name TEXT, Description TEXT, PassphraseHash TEXT, PRIMARY KEY(UniqueID));",
{}, error))
return false;
// insert data into table
if (!con.execute("INSERT INTO Sessions VALUES(?, ?, ?, ?);",
{ session.unique_id, session.name, session.description, session.passphrase_hash },
error))
return false;
return true;
}
bool collab::session_exists(const std::string& unique_id) {
liblec::auto_mutex lock(_d._database_mutex);
if (unique_id.empty())
return false;
std::string error;
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
liblec::leccore::database::table results;
if (!con.execute_query("SELECT UniqueID FROM Sessions WHERE UniqueID = ?;", { unique_id }, results, error))
return false;
return !results.data.empty();
}
bool collab::remove_session(const std::string& unique_id, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
if (unique_id.empty()) {
error = "Session unique id not supplied";
return false;
}
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
// insert data into table
if (!con.execute("DELETE FROM Sessions WHERE UniqueID = ?;", { unique_id }, error))
return false;
return true;
}
bool collab::get_session(const std::string& unique_id, session& session_info, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
session_info = {};
if (unique_id.empty()) {
error = "Session unique id not supplied";
return false;
}
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
liblec::leccore::database::table results;
if (!con.execute_query("SELECT UniqueID, Name, Description, PassphraseHash FROM Sessions WHERE UniqueID = ?;", { unique_id }, results, error))
return false;
for (auto& row : results.data) {
try {
if (row.at("UniqueID").has_value())
session_info.unique_id = liblec::leccore::database::get::text(row.at("UniqueID"));
if (row.at("Name").has_value())
session_info.name = liblec::leccore::database::get::text(row.at("Name"));
if (row.at("Description").has_value())
session_info.description = liblec::leccore::database::get::text(row.at("Description"));
if (row.at("PassphraseHash").has_value())
session_info.passphrase_hash = liblec::leccore::database::get::text(row.at("PassphraseHash"));
break; // only one row expected anyway
}
catch (const std::exception& e) {
error = e.what();
return false;
}
}
return true;
}
bool collab::get_sessions(std::vector<session>& sessions, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
sessions.clear();
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
liblec::leccore::database::table results;
if (!con.execute_query("SELECT UniqueID, Name, Description, PassphraseHash FROM Sessions;", {}, results, error))
return false;
for (auto& row : results.data) {
collab::session session;
try {
if (row.at("UniqueID").has_value())
session.unique_id = liblec::leccore::database::get::text(row.at("UniqueID"));
if (row.at("Name").has_value())
session.name = liblec::leccore::database::get::text(row.at("Name"));
if (row.at("Description").has_value())
session.description = liblec::leccore::database::get::text(row.at("Description"));
if (row.at("PassphraseHash").has_value())
session.passphrase_hash = liblec::leccore::database::get::text(row.at("PassphraseHash"));
sessions.push_back(session);
}
catch (const std::exception& e) {
error = e.what();
return false;
}
}
return true;
}
bool collab::get_local_sessions(std::vector<session>& sessions, std::string& error) {
sessions.clear();
error.clear();
std::vector<session> all_sessions;
if (!get_sessions(all_sessions, error))
return false;
for (const auto& it : all_sessions) {
if (!is_temporary_session_entry(it.unique_id))
sessions.push_back(it);
}
return true;
}
bool collab::create_temporary_session_entry(const std::string& unique_id, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
if (unique_id.empty()) {
error = "Session unique id not supplied";
return false;
}
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
// create table if it doesn't exist
if (!con.execute("CREATE TABLE IF NOT EXISTS TemporarySessions "
"(UniqueID TEXT, PRIMARY KEY(UniqueID));",
{}, error))
return false;
// insert data into table
if (!con.execute("INSERT INTO TemporarySessions VALUES(?);",
{ unique_id },
error))
return false;
return true;
}
bool collab::is_temporary_session_entry(const std::string& unique_id) {
liblec::auto_mutex lock(_d._database_mutex);
if (unique_id.empty())
return false;
std::string error;
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
liblec::leccore::database::table results;
if (!con.execute_query("SELECT * FROM TemporarySessions WHERE UniqueID = ?;", { unique_id }, results, error))
return false;
return !results.data.empty();
}
bool collab::remove_temporary_session_entry(const std::string& unique_id, std::string& error) {
liblec::auto_mutex lock(_d._database_mutex);
if (unique_id.empty()) {
error = "Session unique id not supplied";
return false;
}
// get optional object
auto con_opt = _d.get_connection();
if (!con_opt.has_value()) {
error = "No database connection";
return false;
}
// get database connection object reference
auto& con = con_opt.value().get();
// insert data into table
if (!con.execute("DELETE FROM TemporarySessions WHERE UniqueID = ?;", { unique_id }, error))
return false;
return true;
}
void collab::set_current_session_unique_id(const std::string& session_unique_id) {
liblec::auto_mutex lock(_d._message_broadcast_mutex);
_d._current_session_unique_id = session_unique_id;
}
| 27.56639 | 143 | 0.702867 | [
"object",
"vector"
] |
6c08ebf36a6d560eb76a82ed2e9009b6bc061699 | 27,528 | cpp | C++ | src/listNode.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 14 | 2021-08-29T19:04:30.000Z | 2022-03-10T09:35:21.000Z | src/listNode.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 2 | 2021-12-08T07:53:48.000Z | 2022-02-17T04:16:35.000Z | src/listNode.cpp | LUSpace/pactree | e91d832fb286fe7d37063b5d112c2cea55720f85 | [
"Apache-2.0"
] | 7 | 2021-08-22T23:57:19.000Z | 2022-01-26T19:31:00.000Z | // SPDX-FileCopyrightText: Copyright (c) 2019-2021 Virginia Tech
// SPDX-License-Identifier: Apache-2.0
#include <cstring>
#include <iostream>
#include "Oplog.h"
#include "listNode.h"
#include "threadData.h"
#include "pactree.h"
thread_local int logCnt=0;
thread_local int coreId=-1;
extern thread_local ThreadData* curThreadData;
std::mutex mtx[112];
ListNode :: ListNode(){
deleted = false;
bitMap.clear();
lastScanVersion = 0;
}
void ListNode::setCur(pptr<ListNode> ptr) {
this->curPtr = ptr;
}
void ListNode::setNext(pptr<ListNode> ptr) {
this->nextPtr = ptr;
}
void ListNode::setPrev(pptr<ListNode> ptr) {
this->prevPtr = ptr;
}
void ListNode::setMin(Key_t key) {
this->min = key;
}
void ListNode::setMax(Key_t key) {
this->max = key;
}
void ListNode::setFullBitmap() {
for(int i=0; i<MAX_ENTRIES; i++){
bitMap.set(i);
}
}
void ListNode::setDeleted(bool deleted) {
this->deleted = deleted;
}
ListNode *ListNode::getNext() {
ListNode *next = nextPtr.getVaddr();
return next;
}
pptr<ListNode> ListNode::getNextPtr() {
return nextPtr;
}
pptr<ListNode> ListNode::getCurPtr() {
return curPtr;
}
ListNode *ListNode::getPrev() {
ListNode *prev= prevPtr.getVaddr();
return prev;
}
pptr<ListNode> ListNode::getPrevPtr() {
return prevPtr;
}
version_t ListNode::readLock(uint64_t genId) {
return verLock.read_lock(genId);
}
version_t ListNode::writeLock(uint64_t genId) {
return verLock.write_lock(genId);
}
bool ListNode::readUnlock(version_t oldVersion) {
return verLock.read_unlock(oldVersion);
}
void ListNode::writeUnlock() {
return verLock.write_unlock();
}
int ListNode :: getNumEntries()
{
int numEntries = 0;
for(int i=0; i<MAX_ENTRIES; i++){
if (bitMap[i]) {
numEntries++;
}
}
return numEntries;
}
std::pair<Key_t, Val_t>* ListNode :: getKeyArray()
{
return this->keyArray;
}
std::pair<Key_t, Val_t>* ListNode :: getValueArray()
{
return this->keyArray;
}
Key_t ListNode :: getMin()
{
return this->min;
}
Key_t ListNode::getMax() {
return this->max;
}
bool ListNode::getDeleted() {
return deleted;
}
bool compare2 (std::pair<Key_t, uint8_t> &x, std::pair<Key_t, uint8_t> &y) {
return x.first < y.first;
}
bool compare(std::pair<Key_t, Val_t> &i, std::pair<Key_t, Val_t> &j) {
return i.first < j.first;
}
pptr<ListNode> ListNode :: split(Key_t key, Val_t val, uint8_t keyHash, int threadId, void **olog)
{
//Find median
std::pair<Key_t, Val_t> copyArray[MAX_ENTRIES];
std::copy(std::begin(keyArray), std::end(keyArray), std::begin(copyArray));
std::sort(std::begin(copyArray), std::end(copyArray), compare);
Key_t median = copyArray[MAX_ENTRIES/2].first;
int newNumEntries = 0;
Key_t newMin = median;
int chip, core;
read_coreid_rdtscp(&chip,&core);
if(core!=coreId)
coreId=core;
mtx[core].lock();
int numLogsPerThread = 1000;
int logIdx= numLogsPerThread *(core) + logCnt;
logCnt++;
if(logCnt==numLogsPerThread){
logCnt=0;
}
OpStruct* oplog;
#ifdef MULTIPOOL
uint16_t poolId = (uint16_t)(3*chip+1);
#else
uint16_t poolId = 1;
#endif
/*pptr<ListNode> oplogPtr;
PMEMoid oid;
PMem::alloc(poolId,sizeof(OpStruct),(void **)&(oplogPtr), &oid);
oplog=(OpStruct *) oplogPtr.getVaddr();*/
oplog = (OpStruct *)PMem::getOpLog(logIdx);
// 1) Add Oplog and set the infomration for current(overflown) node.
Oplog::writeOpLog(oplog, OpStruct::insert, newMin, (void*)curPtr.getRawPtr(), poolId, key, val);
flushToNVM((char*)oplog,sizeof(OpStruct));
smp_wmb();
// 2) Allocate new data node and store persistent pointer to the oplog.
pptr<ListNode> newNodePtr;
PMem::alloc(poolId,sizeof(ListNode),(void **)&(newNodePtr),&(oplog->newNodeOid));
if(newNodePtr.getVaddr()==nullptr){
exit(1);
}
unsigned long nPtr = newNodePtr.getRawPtr();
ListNode* newNode = (ListNode*)new(newNodePtr.getVaddr()) ListNode();
// 3) Perform Split Operation
// 3-1) Update New node
int removeIndex = -1;
for(int i = 0; i < MAX_ENTRIES; i++) {
if(keyArray[i].first >= median) {
newNode->insertAtIndex(keyArray[i], newNumEntries, fingerPrint[i], false);
newNumEntries++;
}
}
if (key >= newMin)
newNode->insertAtIndex(std::make_pair(key, val), newNumEntries, keyHash, false);
newNode->setMin(newMin);
newNode->setNext(nextPtr);
newNode->setCur(newNodePtr);
newNode->setDeleted(false);
newNode->setPrev(curPtr);
newNode->setMax(getMax());
setMax(newMin);
flushToNVM((char*)newNode,sizeof(ListNode));
smp_wmb();
// 3-2) Setting next pointer to the New node
nextPtr = newNodePtr;
// 3-3) Update overflown node
// 3-4) Make copy of the bitmap and update the bitmap value.
hydra::bitset curBitMap = *(this->getBitMap());
int numEntries = getNumEntries();
for(int i = 0; i < MAX_ENTRIES; i++) {
if(keyArray[i].first >= median) {
curBitMap.reset(i);
numEntries--;
if (removeIndex == -1) removeIndex = i;
}
}
// 3-4) copy updated bitmap to overflown node.
// What if the size of node is bigger than 64 entries?
bitMap = curBitMap;
flushToNVM((char*)this,L1_CACHE_BYTES);
smp_wmb();
if (key < newMin) {
if (removeIndex != -1)
insertAtIndex(std::make_pair(key, val), removeIndex, keyHash, true);
else
insertAtIndex(std::make_pair(key, val), numEntries, keyHash, true);
}
ListNode* nextNode = newNodePtr->getNext();
nextNode->setPrev(newNodePtr);
Oplog::enqPerThreadLog(oplog);
*olog=oplog;
mtx[core].unlock();
return newNodePtr;
}
pptr<ListNode> ListNode :: split(Key_t key, Val_t val, uint8_t keyHash, int threadId)
{
//Find median
std::pair<Key_t, Val_t> copyArray[MAX_ENTRIES];
std::copy(std::begin(keyArray), std::end(keyArray), std::begin(copyArray));
std::sort(std::begin(copyArray), std::end(copyArray), compare);
Key_t median = copyArray[MAX_ENTRIES/2].first;
int newNumEntries = 0;
Key_t newMin = median;
int chip, core;
read_coreid_rdtscp(&chip,&core);
if(core!=coreId)
coreId=core;
mtx[core].lock();
int numLogsPerThread = 1000;
int logIdx= numLogsPerThread *(core) + logCnt;
logCnt++;
if(logCnt==numLogsPerThread){
logCnt=0;
}
OpStruct* oplog;
#ifdef MULTIPOOL
uint16_t poolId = (uint16_t)(3*chip+1);
#else
uint16_t poolId = 1;
#endif
/* pptr<ListNode> oplogPtr;
PMEMoid oid;
PMem::alloc(poolId,sizeof(OpStruct),(void **)&(oplogPtr), &oid);
oplog=(OpStruct *) oplogPtr.getVaddr();*/
oplog = (OpStruct *)PMem::getOpLog(logIdx);
// 1) Add Oplog and set the infomration for current(overflown) node.
Oplog::writeOpLog(oplog, OpStruct::insert, newMin, (void*)curPtr.getRawPtr(), poolId, key, val);
flushToNVM((char*)oplog,sizeof(OpStruct));
//smp_wmb();
//exit(1); //case 1
// 2) Allocate new data node and store persistent pointer to the oplog.
pptr<ListNode> newNodePtr;
PMem::alloc(poolId,sizeof(ListNode),(void **)&(newNodePtr),&(oplog->newNodeOid));
if(newNodePtr.getVaddr()==nullptr){
exit(1);
}
unsigned long nPtr = newNodePtr.getRawPtr();
ListNode* newNode = (ListNode*)new(newNodePtr.getVaddr()) ListNode();
// 3) Perform Split Operation
// 3-1) Update New node
int removeIndex = -1;
for(int i = 0; i < MAX_ENTRIES; i++) {
if(keyArray[i].first >= median) {
newNode->insertAtIndex(keyArray[i], newNumEntries, fingerPrint[i], false);
newNumEntries++;
}
}
if (key >= newMin)
newNode->insertAtIndex(std::make_pair(key, val), newNumEntries, keyHash, false);
newNode->setMin(newMin);
newNode->setNext(nextPtr);
newNode->setCur(newNodePtr);
newNode->setDeleted(false);
newNode->setPrev(curPtr);
newNode->setMax(getMax());
setMax(newMin);
flushToNVM((char*)newNode,sizeof(ListNode));
smp_wmb();
// 3-2) Setting next pointer to the New node
nextPtr = newNodePtr;
//exit(1); //case 2
// 3-3) Update overflown node
// 3-4) Make copy of the bitmap and update the bitmap value.
hydra::bitset curBitMap = *(this->getBitMap());
int numEntries = getNumEntries();
for(int i = 0; i < MAX_ENTRIES; i++) {
if(keyArray[i].first >= median) {
curBitMap.reset(i);
numEntries--;
if (removeIndex == -1) removeIndex = i;
}
}
// 3-4) copy updated bitmap to overflown node.
// What if the size of node is bigger than 64 entries?
bitMap = curBitMap;
flushToNVM((char*)this,L1_CACHE_BYTES);
smp_wmb();
if (key < newMin) {
if (removeIndex != -1)
insertAtIndex(std::make_pair(key, val), removeIndex, keyHash, true);
else
insertAtIndex(std::make_pair(key, val), numEntries, keyHash, true);
}
ListNode* nextNode = newNodePtr->getNext();
nextNode->setPrev(newNodePtr);
Oplog::enqPerThreadLog(oplog);
mtx[core].unlock();
//exit(1); //case 3
return newNodePtr;
}
ListNode* ListNode :: mergeWithNext(uint64_t genId)
{
//exit(1);
ListNode* deleteNode = nextPtr.getVaddr();
if (!deleteNode->writeLock(genId)) return nullptr;
// 1) Add Oplog and set the infomration for current(overflown) node.
int numLogsPerThread = 1000;
int chip, core;
read_coreid_rdtscp(&chip,&core);
if(core!=coreId)
coreId=core;
mtx[core].lock();
int logIdx= numLogsPerThread *(core) + logCnt;
logCnt++;
OpStruct* oplog = (OpStruct *)PMem::getOpLog(logIdx);
#ifdef MULTIPOOL
uint16_t poolId = (uint16_t)(3*chip+1);
#else
uint16_t poolId = 1;
#endif
Oplog::writeOpLog(oplog, OpStruct::remove, getMin(),(void*)getNextPtr().getRawPtr(), poolId, -1, -1);
oplog->newNodeOid = pmemobj_oid(deleteNode);
flushToNVM((char*)oplog,sizeof(OpStruct));
smp_wmb();
// printf("case 4\n");
// exit(0); //case 4
int cur = 0;
for (int i = 0; i < MAX_ENTRIES; i++) {
if (deleteNode->getBitMap()->test(i)) {
for (int j = cur; j < MAX_ENTRIES; j++) {
if (!bitMap[j]) {
uint8_t keyHash = deleteNode->getFingerPrintArray()[i];
std::pair<Key_t,Val_t> &kv = deleteNode->getKeyArray()[i];
insertAtIndex(kv, j, keyHash, false);
cur = j + 1;
break;
}
}
}
}
flushToNVM((char*)this, sizeof(ListNode));
smp_wmb();
ListNode *next = deleteNode->getNext();
setMax(deleteNode->getMax());
deleteNode->setDeleted(true);
this->setNext(deleteNode->getNextPtr());
flushToNVM((char*)this, L1_CACHE_BYTES);
smp_wmb();
next->setPrev(curPtr);
flushToNVM((char*)next, L1_CACHE_BYTES);
smp_wmb();
mtx[core].unlock();
//printf("case 5\n");
//exit(0); //case 4
return deleteNode;
}
ListNode* ListNode :: mergeWithPrev(uint64_t genId)
{
ListNode* deleteNode = this;
ListNode* mergeNode = prevPtr.getVaddr();
if (!mergeNode->writeLock(genId)) return nullptr;
// 1) Add Oplog and set the infomration for current(overflown) node.
int numLogsPerThread = 1000;
int chip, core;
read_coreid_rdtscp(&chip,&core);
if(core!=coreId)
coreId=core;
mtx[core].lock();
int logIdx= numLogsPerThread *(core) + logCnt;
logCnt++;
OpStruct* oplog = (OpStruct *)PMem::getOpLog(logIdx);
#ifdef MULTIPOOL
uint16_t poolId = (uint16_t)(3*chip+1);
#else
uint16_t poolId = 1;
#endif
Oplog::writeOpLog(oplog, OpStruct::remove, mergeNode->getMin(),(void*)mergeNode->getNextPtr().getRawPtr(), poolId, -1, -1);
oplog->newNodeOid = pmemobj_oid(deleteNode);
flushToNVM((char*)oplog,sizeof(OpStruct));
smp_wmb();
//printf("case 6\n");
//exit(1); //case 6
int cur = 0;
for (int i = 0; i < MAX_ENTRIES; i++) {
if (deleteNode->getBitMap()->test(i)) {
for (int j = cur; j < MAX_ENTRIES; j++) {
if (!mergeNode->getBitMap()->test(j)) {
uint8_t keyHash = deleteNode->getFingerPrintArray()[i];
Key_t key = deleteNode->getKeyArray()[i].first;
Val_t val = deleteNode->getValueArray()[i].second;
mergeNode->insertAtIndex(std::make_pair(key, val), j, keyHash, false);
cur = j + 1;
break;
}
}
}
}
flushToNVM((char*)mergeNode, sizeof(ListNode));
smp_wmb();
// printf("case 7\n");
//exit(1); //case 7
ListNode *next = deleteNode->getNext();
mergeNode->setMax(deleteNode->getMax());
mergeNode->setNext(deleteNode->getNextPtr());
flushToNVM((char*)mergeNode, L1_CACHE_BYTES);
smp_wmb();
// printf("case 8\n");
//exit(1); //case 8
next->setPrev(prevPtr);
flushToNVM((char*)next, L1_CACHE_BYTES);
smp_wmb();
//printf("case 9\n");
//exit(1); //case 9
mergeNode->writeUnlock();
mtx[core].unlock();
return deleteNode;
}
bool ListNode :: insertAtIndex(std::pair<Key_t, Val_t> key, int index, uint8_t keyHash, bool flush)
{
keyArray[index] = key;
if(flush){
flushToNVM((char*)&keyArray[index],sizeof(keyArray[index]));
}
fingerPrint[index] = keyHash;
if(flush){
flushToNVM((char*)&fingerPrint[index],sizeof(uint8_t));
smp_wmb();
}
bitMap.set(index);
if(flush){
flushToNVM((char*)this, L1_CACHE_BYTES);
smp_wmb();
}
return true;
}
bool ListNode :: updateAtIndex(Val_t value, int index)
{
keyArray[index].second = value;
flushToNVM((char*)&keyArray[index],sizeof(keyArray[index]));
smp_wmb();
return true;
}
bool ListNode :: removeFromIndex(int index)
{
bitMap.reset(index);
flushToNVM((char*)this, L1_CACHE_BYTES);
smp_wmb();
return true;
}
uint8_t ListNode :: getKeyInsertIndex(Key_t key)
{
for (uint8_t i = 0; i < MAX_ENTRIES; i++) {
if (!bitMap[i]) return i;
}
}
#if MAX_ENTRIES==64
int ListNode:: getKeyIndex(Key_t key, uint8_t keyHash) {
__m512i v1 = _mm512_loadu_si512((__m512i*)fingerPrint);
__m512i v2 = _mm512_set1_epi8((int8_t)keyHash);
uint64_t mask = _mm512_cmpeq_epi8_mask(v1, v2);
uint64_t bitMapMask = bitMap.to_ulong();
uint64_t posToCheck_64 = (mask) & bitMapMask;
uint32_t posToCheck = (uint32_t) posToCheck_64;
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos].first == key)
return pos;
posToCheck = posToCheck & (~(1 << pos));
}
posToCheck = (uint32_t) (posToCheck_64 >> 32);
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos + 32].first == key)
return pos + 32;
posToCheck = posToCheck & (~(1 << pos));
}
return -1;
}
int ListNode:: getFreeIndex(Key_t key, uint8_t keyHash) {
int freeIndex;
int numEntries = getNumEntries();
if (numEntries != 0 && getKeyIndex(key, keyHash) != -1) return -1;
uint64_t bitMapMask = bitMap.to_ulong();
if (!(~bitMapMask)) return -2;
uint64_t freeIndexMask = ~(bitMapMask);
if ((uint32_t)freeIndexMask)
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
else {
freeIndexMask = freeIndexMask >> 32;
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
freeIndex += 32;
}
return freeIndex;
}
#elif MAX_ENTRIES==128
int ListNode:: getKeyIndex(Key_t key, uint8_t keyHash) {
__m512i v1 = _mm512_loadu_si512((__m512i*)fingerPrint);
__m512i v2 = _mm512_set1_epi8((int8_t)keyHash);
uint64_t mask = _mm512_cmpeq_epi8_mask(v1, v2);
uint64_t bitMapMask = bitMap.to_ulong(0);
uint64_t posToCheck_64 = (mask) & bitMapMask;
uint32_t posToCheck = (uint32_t) posToCheck_64;
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos].first == key)
return pos;
posToCheck = posToCheck & (~(1 << pos));
}
posToCheck = (uint32_t) (posToCheck_64 >> 32);
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos + 32].first == key)
return pos + 32;
posToCheck = posToCheck & (~(1 << pos));
}
v1 = _mm512_loadu_si512((__m512i*)&fingerPrint[64]);
mask = _mm512_cmpeq_epi8_mask(v1, v2);
bitMapMask = bitMap.to_ulong(1);
posToCheck_64 = mask & bitMapMask;
posToCheck = (uint32_t) posToCheck_64;
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos + 64].first == key)
return pos + 64;
posToCheck = posToCheck & (~(1 << pos));
}
posToCheck = (uint32_t) (posToCheck_64 >> 32);
while(posToCheck) {
int pos;
asm("bsrl %1, %0" : "=r"(pos) : "r"((uint32_t)posToCheck));
if (keyArray[pos + 96].first == key)
return pos + 96;
posToCheck = posToCheck & (~(1 << pos));
}
return -1;
}
int ListNode:: getFreeIndex(Key_t key, uint8_t keyHash) {
int freeIndex;
int numEntries = getNumEntries();
if (numEntries != 0 && getKeyIndex(key, keyHash) != -1) return -1;
uint64_t bitMapMask_lower = bitMap.to_ulong(0);
uint64_t bitMapMask_upper = bitMap.to_ulong(1);
if ((~(bitMapMask_lower) == 0x0) && (~(bitMapMask_upper) == 0x0)) return -2;
else if (~(bitMapMask_lower) != 0x0) {
uint64_t freeIndexMask = ~(bitMapMask_lower);
if ((uint32_t)freeIndexMask)
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
else {
freeIndexMask = freeIndexMask >> 32;
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
freeIndex += 32;
}
return freeIndex;
} else {
uint64_t freeIndexMask = ~(bitMapMask_upper);
if ((uint32_t)freeIndexMask) {
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
freeIndex += 64;
}
else {
freeIndexMask = freeIndexMask >> 32;
asm("bsf %1, %0" : "=r"(freeIndex) : "r"((uint32_t)freeIndexMask));
freeIndex += 96;
}
return freeIndex;
}
}
#else
int ListNode:: getKeyIndex(Key_t key, uint8_t keyHash) {
int count = 0;
int numEntries = getNumEntries();
for (uint8_t i = 0; i < MAX_ENTRIES; i++) {
if (bitMap[i] && keyHash == fingerPrint[i] && keyArray[i].first == key)
return (int) i;
if (bitMap[i]) count++;
if (count == numEntries) break;
}
return -1;
}
int ListNode:: getFreeIndex(Key_t key, uint8_t keyHash) {
int freeIndex = -2;
int count = 0;
int numEntries = getNumEntries();
bool keyCheckNeeded = true;
for (uint8_t i = 0; i < MAX_ENTRIES; i++) {
if (keyCheckNeeded && bitMap[i] && keyHash == fingerPrint[i] && keyArray[i].first == key)
return -1;
if (freeIndex == -2 && !bitMap[i]) freeIndex = i;
if (bitMap[i]) {
count++;
if (count == numEntries)
keyCheckNeeded = false;
}
}
return freeIndex;
}
#endif
bool ListNode::insert(Key_t key, Val_t value,int threadId) {
uint8_t keyHash = getKeyFingerPrint(key);
int index = getFreeIndex(key, keyHash);
if (index == -1) return false; // Key exitst
if (index == -2) { //No free index
pptr<ListNode> newNodePtr=split(key, value, keyHash,threadId);
ListNode* newNode =newNodePtr.getVaddr();
ListNode* nextNode = newNode->getNext();
nextNode->setPrev(newNodePtr);
return true;
}
if (!insertAtIndex(std::make_pair(key, value), (uint8_t)index, keyHash, true))
return false;
return true;
}
#ifdef SYNC
int ListNode::insert(Key_t key, Val_t value, void **locked_parent_node) {
uint8_t keyHash = getKeyFingerPrint(key);
int index = getFreeIndex(key, keyHash);
if (index == -1) return false; // Key exitst
if (index == -2) { //No free index
SearchLayer* sl = g_perNumaSlPtr[0];
OpStruct *oplog;
pptr<ListNode> newNodePtr=split(key, value, keyHash,0,(void**)&oplog);
ListNode* newNode =newNodePtr.getVaddr();
ListNode* nextNode = newNode->getNext();
nextNode->setPrev(newNodePtr);
if(*locked_parent_node!=nullptr){
sl->nodeUnlock(*locked_parent_node);
*locked_parent_node = nullptr;
}
void *nNode= reinterpret_cast<void*> (((unsigned long)(oplog->poolId)) << 48 | (oplog->newNodeOid.off));
sl->insert(oplog->key,(void *)nNode);
writeUnlock();
return true;
}
if (!insertAtIndex(std::make_pair(key, value), (uint8_t)index, keyHash, true)){
writeUnlock();
return false;
}
writeUnlock();
return true;
}
#endif
bool ListNode::update(Key_t key, Val_t value) {
uint8_t keyHash = getKeyFingerPrint(key);
int index = getKeyIndex(key, keyHash);
if (index == -1) return false; // Key Does not exit
if (!updateAtIndex(value, (uint8_t)index))
return false;
return true;
}
bool ListNode :: remove(Key_t key, uint64_t genId)
{
uint8_t keyHash = getKeyFingerPrint(key);
int index = getKeyIndex(key, keyHash);
int numEntries = getNumEntries();
ListNode *prev = prevPtr.getVaddr();
ListNode *next= nextPtr.getVaddr();
if (index == -1)
return false;
if (!removeFromIndex(index))
return false;
if (numEntries + next->getNumEntries() < MAX_ENTRIES/2) {
ListNode* delNode = mergeWithNext(genId);
return true;
}
if (prev != NULL && numEntries + prev->getNumEntries() < MAX_ENTRIES/2) {
ListNode* delNode = mergeWithPrev(genId);
}
return true;
}
bool ListNode :: checkRange(Key_t key)
{
return min <= key && key < max;
}
bool ListNode :: checkRangeLookup(Key_t key)
{
int numEntries = getNumEntries();
int ne = numEntries;
return min <= key && key <= keyArray[ne-1].first;
}
bool ListNode::probe(Key_t key) {
int keyHash = getKeyFingerPrint(key);
int index = getKeyIndex(key, keyHash);
if (index == -1)
return false;
else
return true;
}
bool ListNode::lookup(Key_t key, Val_t &value) {
int keyHash = getKeyFingerPrint(key);
int index = getKeyIndex(key, keyHash);
if (index == -1){
return false;
}
else {
value = keyArray[index].second;
return true;
}
}
void ListNode::print() {
int numEntries = getNumEntries();
printf("numEntries:%d min:%s max :%s\n",numEntries, getMin(),getMax());
#ifdef STRINGKEY
for(int i = 0; i < MAX_ENTRIES; i++){
if(bitMap[i])
printf("%s, ",keyArray[i].first);
}
#else
for(int i = 0; i < MAX_ENTRIES; i++){
if(bitMap[i])
printf("%lu, ",keyArray[i].first);
}
#endif
std::cout << "::"<<std::endl;
}
bool ListNode::scan(Key_t startKey, int range, std::vector<Val_t> &rangeVector, uint64_t writeVersion, uint64_t genId) {
restart:
ListNode* next = nextPtr.getVaddr();
if (next == nullptr)
return true;
int todo = static_cast<int>(range - rangeVector.size());
int numEntries = getNumEntries();
if (todo < 1) assert(0 && "ListNode:: scan: todo < 1");
if (writeVersion > lastScanVersion) {
if(!generatePermuter(writeVersion, genId)){
goto restart;
}
}
uint8_t startIndex = 0;
if (startKey > min) startIndex = permuterLowerBound(startKey);
for (uint8_t i = startIndex; i < numEntries && todo > 0; i++) {
rangeVector.push_back(keyArray[permuter[i]].second);
todo--;
}
return rangeVector.size() == range;
}
uint8_t ListNode::getKeyFingerPrint(Key_t key) {
#ifdef STRINGKEY
uint32_t length = key.size();
uint32_t hash = length;
const char* str = key.getData();
for (uint32_t i = 0; i < length; ++str, ++i) {
hash = ((hash << 5) ^ (hash >> 27)) ^ (*str);
}
return (uint8_t) (hash & 0xFF);
#else
key = (~key) + (key << 18); // key = (key << 18) - key - 1;
key = key ^ (key >> 31);
key = (key + (key << 2)) + (key << 4);
key = key ^ (key >> 11);
key = key + (key << 6);
key = key ^ (key >> 22);
return (uint8_t) (key);
#endif
}
hydra::bitset *ListNode::getBitMap() {
return &bitMap;
}
uint8_t *ListNode::getFingerPrintArray() {
return fingerPrint;
}
bool ListNode::generatePermuter(uint64_t writeVersion,uint64_t genId) {
if(pLock.write_lock(genId)==0){
return false;
}
if (writeVersion == lastScanVersion) {
pLock.write_unlock();
return true;
}
std::vector<std::pair<Key_t, uint8_t>> copyArray;
for (uint8_t i = 0; i < MAX_ENTRIES; i++) {
if (bitMap[i]) copyArray.push_back(std::make_pair(keyArray[i].first, i));
}
#ifdef STRINGKEY
std::sort(copyArray.begin(), copyArray.end(), compare2);
#else
std::sort(copyArray.begin(), copyArray.end());
#endif
for (uint8_t i = 0; i < copyArray.size(); i++) {
permuter[i] = copyArray[i].second;
}
flushToNVM((char*)permuter,L1_CACHE_BYTES);
smp_wmb();
lastScanVersion = writeVersion;
flushToNVM((char*)&lastScanVersion,sizeof(uint64_t));
smp_wmb();
pLock.write_unlock();
return true;
}
int ListNode :: permuterLowerBound(Key_t key)
{
int lower = 0;
int numEntries = getNumEntries();
int upper = numEntries;
do {
int mid = ((upper-lower)/2) + lower;
int actualMid = permuter[mid];
if (key < keyArray[actualMid].first) {
upper = mid;
} else if (key > keyArray[actualMid].first) {
lower = mid + 1;
} else {
return mid;
}
} while (lower < upper);
return (uint8_t) lower;
}
pptr<ListNode> ListNode::recoverSplit(OpStruct *olog){
uint8_t keyHash = getKeyFingerPrint(olog->newKey);
pptr<ListNode> newNodePtr=split(olog->newKey, olog->newVal, keyHash,0);
return newNodePtr;
}
void ListNode::recoverNode(Key_t min_key){
// delete duplicate entries
hydra::bitset curBitMap = *(this->getBitMap());
for(int i=0; i<MAX_ENTRIES; i++){
if(min_key <= keyArray[i].first){
curBitMap.reset(i);
}
}
bitMap = curBitMap;
flushToNVM((char*)this,L1_CACHE_BYTES);
smp_wmb();
}
void ListNode::recoverMergingNode(ListNode *deleted_node){
hydra::bitset curBitMap = *(this->getBitMap());
bool exist = false;
int idx = -1;
for(int i=0; i<MAX_ENTRIES; i++){
exist =false;
idx = -1;
if(curBitMap[i]){
for(int j=0; j<MAX_ENTRIES; j++){
if(deleted_node->getKeyArray()[i].first==keyArray[j].first){
exist=true;
break;
}
}
}
else if(idx==-1){
idx = i;
}
if(!exist){
Key_t key= deleted_node->getKeyArray()[i].first;
Val_t val = deleted_node->getKeyArray()[i].second;
uint8_t keyHash = getKeyFingerPrint(key);
insertAtIndex(std::make_pair(key, val), (uint8_t)idx, keyHash, true);
}
}
}
| 28.262834 | 128 | 0.605965 | [
"vector"
] |
6c093616f86b8aff9a065be86598fd38d695ab19 | 123,893 | cpp | C++ | basecode/compiler/byte_code_emitter.cpp | Alaboudi1/bootstrap | 4ec4629424ad6fe70c84d95d79b2132f24832379 | [
"MIT"
] | 32 | 2018-05-14T23:26:54.000Z | 2020-06-14T10:13:20.000Z | basecode/compiler/byte_code_emitter.cpp | Alaboudi1/bootstrap | 4ec4629424ad6fe70c84d95d79b2132f24832379 | [
"MIT"
] | 79 | 2018-08-01T11:50:45.000Z | 2020-11-17T13:40:06.000Z | basecode/compiler/byte_code_emitter.cpp | Alaboudi1/bootstrap | 4ec4629424ad6fe70c84d95d79b2132f24832379 | [
"MIT"
] | 14 | 2021-01-08T05:05:19.000Z | 2022-03-27T14:56:56.000Z | // ----------------------------------------------------------------------------
//
// Basecode Bootstrap Compiler
// Copyright (C) 2018 Jeff Panici
// All rights reserved.
//
// This software source file is licensed under the terms of MIT license.
// For details, please read the LICENSE file.
//
// ----------------------------------------------------------------------------
#include <vm/ffi.h>
#include <vm/terp.h>
#include <fmt/format.h>
#include <vm/assembler.h>
#include <compiler/session.h>
#include <vm/instruction_block.h>
#include "elements.h"
#include "element_map.h"
#include "scope_manager.h"
#include "element_builder.h"
#include "string_intern_map.h"
#include "byte_code_emitter.h"
namespace basecode::compiler {
// +-------------+
// | ... |
// | locals | -offsets
// | fp | 0
// | return addr | +offsets
// | return slot |
// | param 1 |
// | param 2 |
// +-------------+
//
///////////////////////////////////////////////////////////////////////////
void temp_count_result_t::update() {
if (_ints > ints)
ints = _ints;
if (_floats > floats)
floats = _floats;
_ints = _floats = 0;
}
void temp_count_result_t::count(compiler::type* type) {
switch (type->number_class()) {
case number_class_t::integer: {
++_ints;
break;
}
case number_class_t::floating_point: {
++_floats;
break;
}
default: {
break;
}
}
}
///////////////////////////////////////////////////////////////////////////
enum class cast_mode_t : uint8_t {
noop,
integer_truncate,
integer_sign_extend,
integer_zero_extend,
float_extend,
float_truncate,
float_to_integer,
integer_to_float,
};
///////////////////////////////////////////////////////////////////////////
byte_code_emitter::byte_code_emitter(compiler::session& session) : _session(session) {
}
///////////////////////////////////////////////////////////////////////////
void byte_code_emitter::pop_flow_control() {
if (_control_flow_stack.empty())
return;
}
flow_control_t* byte_code_emitter::current_flow_control() {
if (_control_flow_stack.empty())
return nullptr;
return &_control_flow_stack.top();
}
void byte_code_emitter::push_flow_control(const flow_control_t& control_flow) {
_control_flow_stack.push(control_flow);
}
///////////////////////////////////////////////////////////////////////////
void byte_code_emitter::read(
vm::instruction_block* block,
emit_result_t& result,
uint8_t number) {
const auto& local_ref = result.operands.front();
if (local_ref.type() != vm::instruction_operand_type_t::named_ref)
return;
auto number_class = result.type_result.inferred_type->number_class();
auto temp_name = temp_local_name(number_class, number);
auto named_ref = *local_ref.data<vm::assembler_named_ref_t*>();
if (named_ref->type == vm::assembler_named_ref_type_t::label)
return;
if (temp_name == named_ref->name)
return;
auto is_pointer_type = result.type_result.inferred_type->is_pointer_type();
auto is_composite = result.type_result.inferred_type->is_composite_type();
auto size = is_composite ?
vm::op_sizes::qword :
vm::op_size_for_byte_size(result.type_result.inferred_type->size_in_bytes());
const auto& offset = result.operands.size() == 2 ?
result.operands[1] :
vm::instruction_operand_t();
if (!is_temp_local(local_ref) || !offset.is_empty()) {
vm::instruction_operand_t temp(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_name,
size));
if (is_composite && !is_pointer_type) {
block->move(temp, local_ref, offset);
} else {
block->load(temp, local_ref, offset);
}
result.operands.push_back(temp);
}
}
bool byte_code_emitter::emit() {
identifier_by_section_t vars {};
vars.sections.insert(std::make_pair(vm::section_t::bss, element_list_t()));
vars.sections.insert(std::make_pair(vm::section_t::ro_data, element_list_t()));
vars.sections.insert(std::make_pair(vm::section_t::data, element_list_t()));
vars.sections.insert(std::make_pair(vm::section_t::text, element_list_t()));
intern_string_literals();
if (!emit_bootstrap_block())
return false;
if (!emit_type_table())
return false;
if (!emit_interned_string_table())
return false;
if (!emit_section_tables(vars))
return false;
if (!emit_procedure_types(vars))
return false;
if (!emit_start_block())
return false;
if (!emit_initializers(vars))
return false;
if (!emit_implicit_blocks(vars))
return false;
if (!emit_finalizers(vars))
return false;
return emit_end_block();
}
bool byte_code_emitter::emit_block(
vm::instruction_block* basic_block,
compiler::block* block,
identifier_list_t& locals,
temp_local_list_t& temp_locals) {
const auto excluded_parent_types = element_type_set_t{
element_type_t::directive,
};
if (!block->is_parent_type_one_of(excluded_parent_types)) {
if (block->has_stack_frame()) {
if (!begin_stack_frame(basic_block, block, locals, temp_locals))
return false;
} else {
for (const auto& temp : temp_locals)
basic_block->local(temp.type, temp.name, temp.offset);
for (auto var : locals) {
basic_block->move(
vm::instruction_operand_t(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::local,
var->label_name(),
vm::op_size_for_byte_size(var->type_ref()->type()->size_in_bytes()))),
vm::instruction_operand_t(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::label,
var->label_name())));
}
}
}
const auto& statements = block->statements();
for (size_t index = 0; index < statements.size(); ++index) {
auto stmt = statements[index];
for (auto label : stmt->labels()) {
emit_result_t label_result {};
if (!emit_element(basic_block, label, label_result))
return false;
}
auto expr = stmt->expression();
if (expr != nullptr
&& expr->element_type() == element_type_t::defer)
continue;
auto flow_control = current_flow_control();
if (flow_control != nullptr) {
compiler::element* prev = nullptr;
compiler::element* next = nullptr;
if (index > 0)
prev = statements[index - 1];
if (index < statements.size() - 1)
next = statements[index + 1];
auto& values_map = flow_control->values;
values_map[next_element] = next;
values_map[previous_element] = prev;
}
emit_result_t stmt_result;
if (!emit_element(basic_block, stmt, stmt_result))
return false;
}
auto working_stack = block->defer_stack();
while (!working_stack.empty()) {
auto deferred = working_stack.top();
emit_result_t defer_result {};
if (!emit_element(basic_block, deferred, defer_result))
return false;
working_stack.pop();
}
if (block->has_stack_frame()) {
end_stack_frame(basic_block, block, locals);
}
reset_temp();
return true;
}
bool byte_code_emitter::emit_element(
vm::instruction_block* block,
compiler::element* e,
emit_result_t& result) {
auto& builder = _session.builder();
auto& assembler = _session.assembler();
e->infer_type(_session, result.type_result);
switch (e->element_type()) {
case element_type_t::cast: {
// numeric casts
// ------------------------------------------------------------------------
// casting between two integers of the same size (s32 -> u32)
// is a no-op
//
// casting from a larger integer to a smaller integer
// (u32 -> u8) will truncate via move
//
// casting from smaller integer to larger integer (u8 -> u32) will:
// - zero-extend if the source is unsigned
// - sign-extend if the source is signed
//
// casting from float to an integer will round the float towards zero
//
// casting from an integer to a float will produce the
// floating point representation of the integer, rounded if necessary
//
// casting from f32 to f64 is lossless
//
// casting from f64 to f32 will produce the closest possible value, rounded if necessary
//
// casting bool to and integer type will yield 1 or 0
//
// casting any integer type whose LSB is set will yield true; otherwise, false
//
// pointer casts
// ------------------------------------------------------------------------
// integer to pointer type:
//
auto cast = dynamic_cast<compiler::cast*>(e);
auto expr = cast->expression();
auto cast_temp = allocate_temp();
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
read(block, expr_result, cast_temp);
cast_mode_t mode;
auto type_ref = cast->type();
auto source_number_class = expr_result.type_result.inferred_type->number_class();
auto source_size = expr_result.type_result.inferred_type->size_in_bytes();
auto target_number_class = type_ref->type()->number_class();
auto target_size = type_ref->type()->size_in_bytes();
if (source_number_class == number_class_t::none) {
_session.error(
expr->module(),
"C073",
fmt::format(
"cannot cast from type: {}",
expr_result.type_result.type_name()),
expr->location());
return false;
} else if (target_number_class == number_class_t::none) {
_session.error(
expr->module(),
"C073",
fmt::format(
"cannot cast to type: {}",
type_ref->symbol().name),
cast->type_location());
return false;
}
if (source_number_class == number_class_t::integer
&& target_number_class == number_class_t::integer) {
if (source_size == target_size) {
mode = cast_mode_t::integer_truncate;
} else if (source_size > target_size) {
mode = cast_mode_t::integer_truncate;
} else {
auto source_numeric_type = dynamic_cast<compiler::numeric_type*>(expr_result.type_result.inferred_type);
if (source_numeric_type->is_signed()) {
mode = cast_mode_t::integer_sign_extend;
} else {
mode = cast_mode_t::integer_zero_extend;
}
}
} else if (source_number_class == number_class_t::floating_point
&& target_number_class == number_class_t::floating_point) {
if (source_size == target_size) {
mode = cast_mode_t::float_truncate;
} else if (source_size > target_size) {
mode = cast_mode_t::float_truncate;
} else {
mode = cast_mode_t::float_extend;
}
} else {
if (source_number_class == number_class_t::integer) {
mode = cast_mode_t::integer_to_float;
} else {
mode = cast_mode_t::float_to_integer;
}
}
block->comment(
fmt::format(
"cast<{}> from type {}",
type_ref->name(),
expr_result.type_result.type_name()),
vm::comment_location_t::after_instruction);
vm::instruction_operand_t target_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(target_number_class, cast_temp),
vm::op_size_for_byte_size(target_size)));
result.operands.emplace_back(target_operand);
switch (mode) {
case cast_mode_t::noop: {
break;
}
case cast_mode_t::integer_truncate: {
block->move(
target_operand,
expr_result.operands.back());
break;
}
case cast_mode_t::integer_sign_extend: {
block->moves(
target_operand,
expr_result.operands.back());
break;
}
case cast_mode_t::integer_zero_extend: {
block->movez(
target_operand,
expr_result.operands.back());
break;
}
case cast_mode_t::float_extend:
case cast_mode_t::float_truncate:
case cast_mode_t::integer_to_float:
case cast_mode_t::float_to_integer: {
block->convert(
target_operand,
expr_result.operands.back());
break;
}
}
free_temp();
break;
}
case element_type_t::if_e: {
auto if_e = dynamic_cast<compiler::if_element*>(e);
auto begin_label_name = fmt::format("{}_begin", if_e->label_name());
auto true_label_name = fmt::format("{}_true", if_e->label_name());
auto false_label_name = fmt::format("{}_false", if_e->label_name());
auto end_label_name = fmt::format("{}_end", if_e->label_name());
auto predicate_temp = allocate_temp();
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(number_class_t::integer, predicate_temp)));
result.operands.emplace_back(result_operand);
block->label(assembler.make_label(begin_label_name));
emit_result_t predicate_result {};
if (!emit_element(block, if_e->predicate(), predicate_result))
return false;
read(block, predicate_result, predicate_temp);
block->bz(
predicate_result.operands.back(),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
false_label_name)));
block->label(assembler.make_label(true_label_name));
emit_result_t true_result {};
if (!emit_element(block, if_e->true_branch(), true_result))
return false;
if (!block->is_current_instruction(vm::op_codes::jmp)
&& !block->is_current_instruction(vm::op_codes::rts)) {
block->jump_direct(vm::instruction_operand_t(
assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
end_label_name)));
}
block->label(assembler.make_label(false_label_name));
auto false_branch = if_e->false_branch();
if (false_branch != nullptr) {
emit_result_t false_result {};
if (!emit_element(block, false_branch, false_result))
return false;
} else {
block->nop();
}
block->label(assembler.make_label(end_label_name));
free_temp();
break;
}
case element_type_t::with: {
auto with = dynamic_cast<compiler::with*>(e);
auto body = with->body();
if (body != nullptr) {
emit_result_t body_result {};
if (!emit_element(block, body, body_result))
return false;
}
break;
}
case element_type_t::for_e: {
auto for_e = dynamic_cast<compiler::for_element*>(e);
auto begin_label_name = fmt::format("{}_begin", for_e->label_name());
auto body_label_name = fmt::format("{}_body", for_e->label_name());
auto exit_label_name = fmt::format("{}_exit", for_e->label_name());
auto for_expr = for_e->expression();
switch (for_expr->element_type()) {
case element_type_t::intrinsic: {
auto intrinsic = dynamic_cast<compiler::intrinsic*>(for_expr);
if (intrinsic->name() == "range") {
auto begin_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
begin_label_name);
auto exit_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
exit_label_name);
flow_control_t flow_control {
.exit_label = exit_label_ref,
.continue_label = begin_label_ref
};
push_flow_control(flow_control);
defer(pop_flow_control());
auto range = dynamic_cast<compiler::range_intrinsic*>(intrinsic);
auto start_arg = range->arguments()->param_by_name("start");
auto induction_init = builder.make_binary_operator(
for_e->parent_scope(),
operator_type_t::assignment,
for_e->induction_decl()->identifier(),
start_arg);
induction_init->make_non_owning();
defer(_session.elements().remove(induction_init->id()));
if (!emit_element(block, induction_init, result))
return false;
auto dir_arg = range->arguments()->param_by_name("dir");
uint64_t dir_value;
if (!dir_arg->as_integer(dir_value))
return false;
auto kind_arg = range->arguments()->param_by_name("kind");
uint64_t kind_value;
if (!kind_arg->as_integer(kind_value))
return false;
auto step_op_type = dir_value == 0 ?
operator_type_t::add :
operator_type_t::subtract;
auto cmp_op_type = operator_type_t::less_than;
switch (kind_value) {
case 0: {
switch (dir_value) {
case 0:
cmp_op_type = operator_type_t::less_than_or_equal;
break;
case 1:
cmp_op_type = operator_type_t::greater_than_or_equal;
break;
}
break;
}
case 1: {
switch (dir_value) {
case 0:
cmp_op_type = operator_type_t::less_than;
break;
case 1:
cmp_op_type = operator_type_t::greater_than;
break;
}
break;
}
}
auto stop_arg = range->arguments()->param_by_name("stop");
block->label(assembler.make_label(begin_label_name));
auto comparison_op = builder.make_binary_operator(
for_e->parent_scope(),
cmp_op_type,
for_e->induction_decl()->identifier(),
stop_arg);
comparison_op->make_non_owning();
defer(_session.elements().remove(comparison_op->id()));
emit_result_t cmp_result;
if (!emit_element(block, comparison_op, cmp_result))
return false;
block->bz(
cmp_result.operands.back(),
vm::instruction_operand_t(exit_label_ref));
block->label(assembler.make_label(body_label_name));
if (!emit_element(block, for_e->body(), result))
return false;
auto step_param = range->arguments()->param_by_name("step");
auto induction_step = builder.make_binary_operator(
for_e->parent_scope(),
step_op_type,
for_e->induction_decl()->identifier(),
step_param);
auto induction_assign = builder.make_binary_operator(
for_e->parent_scope(),
operator_type_t::assignment,
for_e->induction_decl()->identifier(),
induction_step);
induction_step->make_non_owning();
induction_assign->make_non_owning();
defer({
_session.elements().remove(induction_assign->id());
_session.elements().remove(induction_step->id());
});
if (!emit_element(block, induction_assign, result))
return false;
block->jump_direct(vm::instruction_operand_t(begin_label_ref));
block->label(assembler.make_label(exit_label_name));
}
break;
}
default: {
block->comment("XXX: unsupported scenario", 4);
break;
}
}
break;
}
case element_type_t::label: {
block->blank_line();
block->label(assembler.make_label(e->label_name()));
break;
}
case element_type_t::block: {
identifier_list_t locals {};
auto scope_block = dynamic_cast<compiler::block*>(e);
temp_local_list_t temp_locals {};
if (!make_temp_locals(scope_block, temp_locals))
return false;
if (!emit_block(block, scope_block, locals, temp_locals))
return false;
break;
}
case element_type_t::field: {
auto field = dynamic_cast<compiler::field*>(e);
auto decl = field->declaration();
if (decl != nullptr) {
emit_result_t decl_result {};
if (!emit_element(block, decl, decl_result))
return false;
}
break;
}
case element_type_t::defer: {
auto defer = dynamic_cast<compiler::defer_element*>(e);
auto expr = defer->expression();
if (expr != nullptr) {
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
}
break;
}
case element_type_t::module: {
auto module = dynamic_cast<compiler::module*>(e);
auto scope = module->scope();
if (scope != nullptr) {
emit_result_t scope_result {};
if (!emit_element(block, scope, scope_result))
return false;
}
break;
}
case element_type_t::case_e: {
auto case_e = dynamic_cast<compiler::case_element*>(e);
auto true_label_name = fmt::format("{}_true", case_e->label_name());
auto false_label_name = fmt::format("{}_false", case_e->label_name());
auto flow_control = current_flow_control();
if (flow_control == nullptr) {
// XXX: error
return false;
}
flow_control->fallthrough = false;
auto is_default_case = case_e->expression() == nullptr;
vm::assembler_named_ref_t* fallthrough_label = nullptr;
if (!is_default_case) {
auto next = boost::any_cast<compiler::element*>(flow_control->values[next_element]);
if (next != nullptr
&& next->element_type() == element_type_t::statement) {
auto stmt = dynamic_cast<compiler::statement*>(next);
if (stmt != nullptr
&& stmt->expression()->element_type() == element_type_t::case_e) {
auto next_case = dynamic_cast<compiler::case_element*>(stmt->expression());
auto next_true_label_name = fmt::format("{}_true", next_case->label_name());
fallthrough_label = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
next_true_label_name);
}
}
}
if (!is_default_case) {
auto switch_expr = boost::any_cast<compiler::element*>(flow_control->values[switch_expression]);
auto equals_op = builder.make_binary_operator(
case_e->parent_scope(),
operator_type_t::equals,
switch_expr,
case_e->expression());
equals_op->make_non_owning();
defer(_session.elements().remove(equals_op->id()));
emit_result_t equals_result {};
if (!emit_element(block, equals_op, equals_result))
return false;
block->bz(
equals_result.operands.back(),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
false_label_name)));
}
block->label(assembler.make_label(true_label_name));
if (!emit_element(block, case_e->scope(), result))
return false;
if (!is_default_case) {
if (flow_control->fallthrough) {
block->jump_direct(vm::instruction_operand_t(fallthrough_label));
} else {
block->jump_direct(vm::instruction_operand_t(flow_control->exit_label));
}
}
block->label(assembler.make_label(false_label_name));
break;
}
case element_type_t::break_e: {
auto break_e = dynamic_cast<compiler::break_element*>(e);
vm::assembler_named_ref_t* label_ref = nullptr;
std::string label_name;
if (break_e->label() != nullptr) {
label_name = break_e->label()->label_name();
label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
label_name);
} else {
auto flow_control = current_flow_control();
if (flow_control == nullptr
|| flow_control->exit_label == nullptr) {
_session.error(
break_e->module(),
"P081",
"no valid exit label on stack.",
break_e->location());
return false;
}
label_ref = flow_control->exit_label;
label_name = label_ref->name;
}
block->comment(
fmt::format("break: {}", label_name),
vm::comment_location_t::after_instruction);
block->jump_direct(vm::instruction_operand_t(label_ref));
break;
}
case element_type_t::while_e: {
auto while_e = dynamic_cast<compiler::while_element*>(e);
auto begin_label_name = fmt::format("{}_begin", while_e->label_name());
auto body_label_name = fmt::format("{}_body", while_e->label_name());
auto exit_label_name = fmt::format("{}_exit", while_e->label_name());
auto end_label_name = fmt::format("{}_end", while_e->label_name());
auto begin_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
begin_label_name);
auto exit_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
exit_label_name);
push_flow_control(flow_control_t{
.exit_label = exit_label_ref,
.continue_label = begin_label_ref
});
defer(pop_flow_control());
block->label(assembler.make_label(begin_label_name));
emit_result_t predicate_result {};
if (!emit_element(block, while_e->predicate(), predicate_result))
return false;
block->bz(
predicate_result.operands.back(),
vm::instruction_operand_t(exit_label_ref));
block->label(assembler.make_label(body_label_name));
if (!emit_element(block, while_e->body(), result))
return false;
block->jump_direct(vm::instruction_operand_t(begin_label_ref));
block->label(assembler.make_label(exit_label_name));
block->nop();
block->label(assembler.make_label(end_label_name));
break;
}
case element_type_t::return_e: {
auto return_e = dynamic_cast<compiler::return_element*>(e);
auto return_type_field = return_e->field();
if (return_type_field != nullptr) {
auto temp = allocate_temp();
emit_result_t expr_result {};
if (!emit_element(block, return_e->expressions().front(), expr_result))
return false;
read(block, expr_result, temp);
block->store(
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
return_type_field->declaration()->identifier()->label_name())),
expr_result.operands.back());
free_temp();
}
block->move(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::fp());
block->pop(vm::instruction_operand_t::fp());
block->rts();
break;
}
case element_type_t::switch_e: {
auto switch_e = dynamic_cast<compiler::switch_element*>(e);
auto begin_label_name = fmt::format("{}_begin", switch_e->label_name());
auto exit_label_name = fmt::format("{}_exit", switch_e->label_name());
auto end_label_name = fmt::format("{}_end", switch_e->label_name());
auto exit_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
exit_label_name);
flow_control_t flow_control {
.exit_label = exit_label_ref,
};
flow_control.values.insert(std::make_pair(
switch_expression,
switch_e->expression()));
push_flow_control(flow_control);
defer(pop_flow_control());
block->label(assembler.make_label(begin_label_name));
if (!emit_element(block, switch_e->scope(), result))
return false;
block->label(assembler.make_label(exit_label_name));
block->nop();
block->label(assembler.make_label(end_label_name));
break;
}
case element_type_t::intrinsic: {
auto intrinsic = dynamic_cast<compiler::intrinsic*>(e);
const auto& name = intrinsic->name();
auto args = intrinsic->arguments()->elements();
if (name == "address_of") {
auto arg = args[0];
if (!emit_element(block, arg, result))
return false;
} else if (name == "alloc") {
auto arg = args[0];
auto arg_temp = allocate_temp();
emit_result_t arg_result {};
if (!emit_element(block, arg, arg_result))
return false;
read(block, arg_result, arg_temp);
auto result_temp = allocate_temp();
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(result.type_result.inferred_type->number_class(), result_temp)));
result.operands.emplace_back(result_operand);
block->alloc(
vm::op_sizes::byte,
result_operand,
arg_result.operands.back());
free_temp();
free_temp();
} else if (name == "free") {
auto arg = args[0];
auto arg_temp = allocate_temp();
emit_result_t arg_result {};
if (!emit_element(block, arg, arg_result))
return false;
read(block, arg_result, arg_temp);
block->free(arg_result.operands.back());
free_temp();
} else if (name == "fill") {
auto dest_arg = args[0];
auto value_arg = args[1];
auto length_arg = args[2];
auto dest_temp = allocate_temp();
emit_result_t dest_arg_result {};
if (!emit_element(block, dest_arg, dest_arg_result))
return false;
read(block, dest_arg_result, dest_temp);
auto value_temp = allocate_temp();
emit_result_t value_arg_result {};
if (!emit_element(block, value_arg, value_arg_result))
return false;
read(block, value_arg_result, value_temp);
auto len_temp = allocate_temp();
emit_result_t length_arg_result {};
if (!emit_element(block, length_arg, length_arg_result))
return false;
read(block, length_arg_result, len_temp);
block->fill(
vm::op_sizes::byte,
dest_arg_result.operands.back(),
value_arg_result.operands.back(),
length_arg_result.operands.back());
free_temp();
free_temp();
free_temp();
} else if (name == "copy") {
auto dest_arg = args[0];
auto src_arg = args[1];
auto size_arg = args[2];
auto dest_temp = allocate_temp();
emit_result_t dest_arg_result {};
if (!emit_element(block, dest_arg, dest_arg_result))
return false;
read(block, dest_arg_result, dest_temp);
auto src_temp = allocate_temp();
emit_result_t src_arg_result {};
if (!emit_element(block, src_arg, src_arg_result))
return false;
read(block, src_arg_result, src_temp);
auto size_temp = allocate_temp();
emit_result_t size_arg_result {};
if (!emit_element(block, size_arg, size_arg_result))
return false;
read(block, size_arg_result, size_temp);
block->copy(
vm::op_sizes::byte,
dest_arg_result.operands.back(),
src_arg_result.operands.back(),
size_arg_result.operands.back());
free_temp();
free_temp();
free_temp();
}
break;
}
case element_type_t::directive: {
auto directive = dynamic_cast<compiler::directive*>(e);
const std::string& name = directive->name();
if (name == "assembly") {
auto assembly_directive = dynamic_cast<compiler::assembly_directive*>(directive);
auto expr = assembly_directive->expression();
auto raw_block = dynamic_cast<compiler::raw_block*>(expr);
common::source_file source_file;
if (!source_file.load(_session.result(), raw_block->value() + "\n"))
return false;
auto success = assembler.assemble_from_source(
_session.result(),
source_file,
block,
expr->parent_scope());
if (!success)
return false;
} else if (name == "if") {
auto if_directive = dynamic_cast<compiler::if_directive*>(directive);
auto true_expr = if_directive->true_body();
if (true_expr != nullptr) {
block->comment(
"directive: if/elif/else",
vm::comment_location_t::after_instruction);
emit_result_t if_result {};
if (!emit_element(block, true_expr, if_result))
return false;
}
} else if (name == "run") {
auto run_directive = dynamic_cast<compiler::run_directive*>(directive);
block->comment(
"directive: run",
vm::comment_location_t::after_instruction);
block->meta_begin();
emit_result_t run_result {};
if (!emit_element(block, run_directive->expression(), run_result))
return false;
block->meta_end();
}
break;
}
case element_type_t::statement: {
auto statement = dynamic_cast<compiler::statement*>(e);
auto expr = statement->expression();
if (expr != nullptr) {
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
}
break;
}
case element_type_t::proc_call: {
auto proc_call = dynamic_cast<compiler::procedure_call*>(e);
auto procedure_type = proc_call->procedure_type();
auto label = proc_call->identifier()->label_name();
auto is_foreign = procedure_type->is_foreign();
size_t target_size = 8;
std::string return_temp_name {};
compiler::type* return_type = nullptr;
auto return_type_field = procedure_type->return_type();
if (return_type_field != nullptr) {
return_type = return_type_field->identifier()->type_ref()->type();
if (return_type != nullptr) {
target_size = return_type->size_in_bytes();
return_temp_name = temp_local_name(
return_type->number_class(),
allocate_temp());
}
}
if (!is_foreign)
block->push_locals(assembler, return_temp_name);
auto arg_list = proc_call->arguments();
if (arg_list != nullptr) {
emit_result_t arg_list_result {};
if (!emit_element(block, arg_list, arg_list_result))
return false;
}
if (is_foreign) {
auto& ffi = _session.ffi();
auto func = ffi.find_function(procedure_type->foreign_address());
if (func == nullptr) {
_session.error(
proc_call->module(),
"X000",
fmt::format(
"unable to find foreign function by address: {}",
procedure_type->foreign_address()),
proc_call->location());
return false;
}
block->comment(
fmt::format("call: {}", label),
vm::comment_location_t::after_instruction);
vm::instruction_operand_t address_operand(procedure_type->foreign_address());
if (func->is_variadic()) {
vm::function_value_list_t args {};
if (!arg_list->as_ffi_arguments(_session, args))
return false;
auto signature_id = common::id_pool::instance()->allocate();
func->call_site_arguments.insert(std::make_pair(signature_id, args));
block->call_foreign(
address_operand,
vm::instruction_operand_t(
static_cast<uint64_t>(signature_id),
vm::op_sizes::dword));
} else {
block->call_foreign(address_operand);
}
} else {
if (return_type != nullptr) {
block->comment(
"return slot",
vm::comment_location_t::after_instruction);
block->sub(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::sp(),
vm::instruction_operand_t(static_cast<uint64_t>(8), vm::op_sizes::byte));
}
block->comment(
fmt::format("call: {}", label),
vm::comment_location_t::after_instruction);
block->call(vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
label)));
}
if (!return_temp_name.empty()) {
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
return_temp_name,
vm::op_size_for_byte_size(target_size)));
result.operands.emplace_back(result_operand);
block->pop(result_operand);
// free_temp();
}
if (arg_list->allocated_size() > 0) {
block->comment(
"free stack space",
vm::comment_location_t::after_instruction);
block->add(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::sp(),
vm::instruction_operand_t(arg_list->allocated_size(), vm::op_sizes::word));
}
if (!is_foreign)
block->pop_locals(assembler, return_temp_name);
break;
}
case element_type_t::transmute: {
auto transmute = dynamic_cast<compiler::transmute*>(e);
auto expr = transmute->expression();
auto type_ref = transmute->type();
auto temp = allocate_temp();
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
read(block, expr_result, temp);
if (expr_result.type_result.inferred_type->number_class() == number_class_t::none) {
_session.error(
expr->module(),
"C073",
fmt::format(
"cannot transmute from type: {}",
expr_result.type_result.type_name()),
expr->location());
return false;
} else if (type_ref->type()->number_class() == number_class_t::none) {
_session.error(
transmute->module(),
"C073",
fmt::format(
"cannot transmute to type: {}",
type_ref->symbol().name),
transmute->type_location());
return false;
}
auto target_number_class = type_ref->type()->number_class();
auto target_size = type_ref->type()->size_in_bytes();
block->comment(
fmt::format("transmute<{}>", type_ref->symbol().name),
vm::comment_location_t::after_instruction);
vm::instruction_operand_t target_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(target_number_class, temp),
vm::op_size_for_byte_size(target_size)));
result.operands.emplace_back(target_operand);
block->move(
target_operand,
expr_result.operands.back(),
vm::instruction_operand_t::empty());
free_temp();
break;
}
case element_type_t::continue_e: {
auto continue_e = dynamic_cast<compiler::continue_element*>(e);
vm::assembler_named_ref_t* label_ref = nullptr;
std::string label_name;
if (continue_e->label() != nullptr) {
label_name = continue_e->label()->label_name();
label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
label_name);
} else {
auto flow_control = current_flow_control();
if (flow_control == nullptr
|| flow_control->continue_label == nullptr) {
_session.error(
continue_e->module(),
"P081",
"no valid continue label on stack.",
continue_e->location());
return false;
}
label_ref = flow_control->continue_label;
label_name = label_ref->name;
}
block->comment(
fmt::format("continue: {}", label_name),
vm::comment_location_t::after_instruction);
block->jump_direct(vm::instruction_operand_t(label_ref));
break;
}
case element_type_t::identifier: {
auto var = dynamic_cast<compiler::identifier*>(e);
result.operands.emplace_back(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::local,
var->label_name(),
vm::op_size_for_byte_size(result.type_result.inferred_type->size_in_bytes())));
break;
}
case element_type_t::expression: {
auto expr = dynamic_cast<compiler::expression*>(e);
auto root = expr->root();
if (root != nullptr)
return emit_element(block, root, result);
break;
}
case element_type_t::assignment: {
auto assignment = dynamic_cast<compiler::assignment*>(e);
for (auto expr : assignment->expressions()) {
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
}
break;
}
case element_type_t::declaration: {
auto decl = dynamic_cast<compiler::declaration*>(e);
auto assignment = decl->assignment();
if (assignment != nullptr) {
emit_result_t assignment_result {};
if (!emit_element(block, assignment, assignment_result))
return false;
}
break;
}
case element_type_t::namespace_e: {
auto ns = dynamic_cast<compiler::namespace_element*>(e);
auto expr = ns->expression();
if (expr != nullptr) {
emit_result_t expr_result {};
if (!emit_element(block, expr, expr_result))
return false;
}
break;
}
case element_type_t::initializer: {
auto init = dynamic_cast<compiler::initializer*>(e);
auto expr = init->expression();
if (expr != nullptr)
return emit_element(block, expr, result);
break;
}
case element_type_t::fallthrough: {
auto flow_control = current_flow_control();
if (flow_control != nullptr)
flow_control->fallthrough = true;
else {
_session.error(
e->module(),
"X000",
"fallthrough is only valid within a case.",
e->location());
return false;
}
break;
}
case element_type_t::nil_literal: {
result.operands.emplace_back(vm::instruction_operand_t(
static_cast<uint64_t>(0),
vm::op_sizes::qword));
break;
}
case element_type_t::type_literal: {
break;
}
case element_type_t::float_literal: {
auto float_literal = dynamic_cast<compiler::float_literal*>(e);
auto value = float_literal->value();
auto is_float = numeric_type::narrow_to_value(value) == "f32";
if (is_float) {
auto temp_value = static_cast<float>(value);
result.operands.emplace_back(vm::instruction_operand_t(temp_value));
} else {
result.operands.emplace_back(vm::instruction_operand_t(value));
}
break;
}
case element_type_t::string_literal: {
result.operands.emplace_back(vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
interned_string_data_label(e->id()))));
break;
}
case element_type_t::boolean_literal: {
auto bool_literal = dynamic_cast<compiler::boolean_literal*>(e);
result.operands.emplace_back(vm::instruction_operand_t(
static_cast<uint64_t>(bool_literal->value() ? 1 : 0),
vm::op_sizes::byte));
break;
}
case element_type_t::integer_literal: {
auto integer_literal = dynamic_cast<compiler::integer_literal*>(e);
auto size = result.type_result.inferred_type->size_in_bytes();
result.operands.emplace_back(vm::instruction_operand_t(
integer_literal->value(),
vm::op_size_for_byte_size(size)));
break;
}
case element_type_t::character_literal: {
auto char_literal = dynamic_cast<compiler::character_literal*>(e);
result.operands.emplace_back(vm::instruction_operand_t(
static_cast<int64_t>(char_literal->rune()),
vm::op_sizes::dword));
break;
}
case element_type_t::argument_list: {
auto arg_list = dynamic_cast<compiler::argument_list*>(e);
if (!emit_arguments(block, arg_list, arg_list->elements()))
return false;
break;
}
case element_type_t::assembly_label: {
auto label = dynamic_cast<compiler::assembly_label*>(e);
auto name = label->reference()->identifier()->label_name();
if (assembler.has_local(name)) {
result.operands.emplace_back(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::local,
name));
} else {
result.operands.emplace_back(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::label,
name));
}
break;
}
case element_type_t::unary_operator: {
auto unary_op = dynamic_cast<compiler::unary_operator*>(e);
auto op_type = unary_op->operator_type();
switch (op_type) {
case operator_type_t::pointer_dereference: {
block->comment("unary_op: deref", vm::comment_location_t::after_instruction);
break;
}
default:
break;
}
auto rhs_temp = allocate_temp();
emit_result_t rhs_emit_result {};
if (!emit_element(block, unary_op->rhs(), rhs_emit_result))
return false;
read(block, rhs_emit_result, rhs_temp);
auto is_composite_type = rhs_emit_result.type_result.inferred_type->is_composite_type();
auto size = vm::op_size_for_byte_size(result.type_result.inferred_type->size_in_bytes());
if (op_type == operator_type_t::pointer_dereference
&& !is_composite_type) {
auto pointer_type = dynamic_cast<compiler::pointer_type*>(result.type_result.inferred_type);
size = vm::op_size_for_byte_size(pointer_type->base_type_ref()->type()->size_in_bytes());
}
auto result_temp = allocate_temp();
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(result.type_result.inferred_type->number_class(), result_temp),
size));
switch (op_type) {
case operator_type_t::negate: {
block->comment("unary_op: negate", vm::comment_location_t::after_instruction);
block->neg(
result_operand,
rhs_emit_result.operands.back());
result.operands.emplace_back(result_operand);
break;
}
case operator_type_t::binary_not: {
block->comment("unary_op: binary not", vm::comment_location_t::after_instruction);
block->not_op(
result_operand,
rhs_emit_result.operands.back());
result.operands.emplace_back(result_operand);
break;
}
case operator_type_t::logical_not: {
block->comment("unary_op: logical not", vm::comment_location_t::after_instruction);
block->cmp(
result_operand.size(),
rhs_emit_result.operands.back(),
vm::instruction_operand_t(static_cast<uint64_t>(1), vm::op_sizes::byte));
block->setnz(result_operand);
result.operands.emplace_back(result_operand);
break;
}
case operator_type_t::pointer_dereference: {
if (!is_composite_type) {
block->load(
result_operand,
rhs_emit_result.operands.back());
result.operands.push_back(result_operand);
} else {
result.operands.push_back(rhs_emit_result.operands.back());
}
break;
}
default:
break;
}
free_temp();
free_temp();
break;
}
case element_type_t::binary_operator: {
auto binary_op = dynamic_cast<compiler::binary_operator*>(e);
switch (binary_op->operator_type()) {
case operator_type_t::add:
case operator_type_t::modulo:
case operator_type_t::divide:
case operator_type_t::subtract:
case operator_type_t::multiply:
case operator_type_t::exponent:
case operator_type_t::binary_or:
case operator_type_t::shift_left:
case operator_type_t::binary_and:
case operator_type_t::binary_xor:
case operator_type_t::shift_right:
case operator_type_t::rotate_left:
case operator_type_t::rotate_right: {
if (!emit_arithmetic_operator(block, binary_op, result))
return false;
break;
}
case operator_type_t::equals:
case operator_type_t::less_than:
case operator_type_t::not_equals:
case operator_type_t::logical_or:
case operator_type_t::logical_and:
case operator_type_t::greater_than:
case operator_type_t::less_than_or_equal:
case operator_type_t::greater_than_or_equal: {
if (!emit_relational_operator(block, binary_op, result))
return false;
break;
}
case operator_type_t::subscript: {
block->comment("XXX: implement subscript operator", 4);
block->nop();
break;
}
case operator_type_t::member_access: {
if (result.operands.size() < 2) {
result.operands.resize(2);
}
emit_result_t lhs_result {};
if (!emit_element(block, binary_op->lhs(), lhs_result))
return false;
result.operands[0] = lhs_result.operands.front();
int64_t offset = 0;
if (lhs_result.operands.size() == 2) {
auto& offset_operand = lhs_result.operands.back();
if (!offset_operand.is_empty())
offset = *offset_operand.data<int64_t>();
}
auto type = lhs_result.type_result.inferred_type;
if (lhs_result.type_result.inferred_type->is_pointer_type()) {
auto pointer_type = dynamic_cast<compiler::pointer_type*>(lhs_result.type_result.inferred_type);
type = pointer_type->base_type_ref()->type();
}
auto composite_type = dynamic_cast<compiler::composite_type*>(type);
if (composite_type != nullptr) {
auto rhs_ref = dynamic_cast<compiler::identifier_reference*>(binary_op->rhs());
auto field = composite_type->fields().find_by_name(rhs_ref->symbol().name);
if (field != nullptr) {
offset += field->start_offset();
}
}
result.operands[1] = vm::instruction_operand_t::offset(offset, vm::op_sizes::word);
break;
}
case operator_type_t::assignment: {
auto rhs_temp = allocate_temp();
emit_result_t rhs_result {};
if (!emit_element(block, binary_op->rhs(), rhs_result))
return false;
read(block, rhs_result, rhs_temp);
emit_result_t lhs_result {};
if (!emit_element(block, binary_op->lhs(), lhs_result))
return false;
auto copy_required = false;
auto lhs_is_composite = lhs_result.type_result.inferred_type->is_composite_type();
auto rhs_is_composite = rhs_result.type_result.inferred_type->is_composite_type();
if (!lhs_result.type_result.inferred_type->is_pointer_type()) {
if (lhs_is_composite && !rhs_is_composite) {
_session.error(
binary_op->module(),
"X000",
"cannot assign scalar to composite type.",
binary_op->rhs()->location());
return false;
}
if (!lhs_is_composite && rhs_is_composite) {
_session.error(
binary_op->module(),
"X000",
"cannot assign composite type to scalar.",
binary_op->rhs()->location());
return false;
}
copy_required = lhs_is_composite && rhs_is_composite;
}
if (copy_required) {
auto size = static_cast<uint64_t>(rhs_result.type_result.inferred_type->size_in_bytes());
block->copy(
vm::op_sizes::byte,
lhs_result.operands.front(),
rhs_result.operands.back(),
vm::instruction_operand_t(size));
} else {
if (lhs_result.operands.size() == 2) {
block->store(
lhs_result.operands[0],
rhs_result.operands.back(),
lhs_result.operands[1]);
} else {
block->store(
lhs_result.operands.back(),
rhs_result.operands.back());
}
}
free_temp();
break;
}
default:
break;
}
break;
}
case element_type_t::symbol:
case element_type_t::element:
case element_type_t::comment:
case element_type_t::program:
case element_type_t::import_e:
case element_type_t::rune_type:
case element_type_t::proc_type:
case element_type_t::bool_type:
case element_type_t::attribute:
case element_type_t::raw_block:
case element_type_t::tuple_type:
case element_type_t::array_type:
case element_type_t::module_type:
case element_type_t::unknown_type:
case element_type_t::numeric_type:
case element_type_t::pointer_type:
case element_type_t::generic_type:
case element_type_t::argument_pair:
case element_type_t::proc_instance:
case element_type_t::namespace_type:
case element_type_t::composite_type:
case element_type_t::type_reference:
case element_type_t::spread_operator:
case element_type_t::label_reference:
case element_type_t::module_reference:
case element_type_t::unknown_identifier:
case element_type_t::uninitialized_literal: {
break;
}
case element_type_t::identifier_reference: {
auto var_ref = dynamic_cast<compiler::identifier_reference*>(e);
auto identifier = var_ref->identifier();
if (identifier != nullptr) {
if (!emit_element(block, identifier, result))
return false;
}
break;
}
case element_type_t::assembly_literal_label: {
auto label = dynamic_cast<compiler::assembly_literal_label*>(e);
result.operands.emplace_back(vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
label->name())));
break;
}
}
return true;
}
bool byte_code_emitter::emit_type_info(
vm::instruction_block* block,
compiler::type* type) {
if (type == nullptr)
return false;
if (type->element_type() == element_type_t::generic_type
|| type->element_type() == element_type_t::unknown_type) {
return true;
}
auto& assembler = _session.assembler();
auto type_name = type->name();
auto type_name_len = static_cast<uint32_t>(type_name.length());
auto label_name = type::make_info_label_name(type);
block->blank_line();
block->comment(fmt::format("type: {}", type_name), 0);
block->label(assembler.make_label(label_name));
block->dwords({type_name_len});
block->dwords({type_name_len});
block->qwords({assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
type::make_literal_data_label_name(type))});
return true;
}
bool byte_code_emitter::count_temps(
compiler::element* e,
temp_count_result_t& result) {
switch (e->element_type()) {
case element_type_t::cast: {
auto cast = dynamic_cast<compiler::cast*>(e);
if (!count_temps(cast->expression(), result))
return false;
break;
}
case element_type_t::field: {
auto field = dynamic_cast<compiler::field*>(e);
if (!count_temps(field->identifier(), result))
return false;
break;
}
case element_type_t::proc_type: {
auto proc_type = dynamic_cast<compiler::procedure_type*>(e);
auto return_type = proc_type->return_type();
if (return_type != nullptr) {
if (!count_temps(return_type, result))
return false;
}
break;
}
case element_type_t::return_e: {
auto return_e = dynamic_cast<compiler::return_element*>(e);
for (auto expr : return_e->expressions()) {
if (!count_temps(expr, result))
return false;
}
break;
}
case element_type_t::intrinsic: {
auto intrinsic = dynamic_cast<compiler::intrinsic*>(e);
if (!count_temps(intrinsic->arguments(), result))
return false;
if (!count_temps(intrinsic->procedure_type(), result))
return false;
break;
}
case element_type_t::transmute: {
auto transmute = dynamic_cast<compiler::transmute*>(e);
if (!count_temps(transmute->expression(), result))
return false;
break;
}
case element_type_t::proc_call: {
auto proc_call = dynamic_cast<compiler::procedure_call*>(e);
if (!count_temps(proc_call->arguments(), result))
return false;
if (!count_temps(proc_call->procedure_type(), result))
return false;
break;
}
case element_type_t::expression: {
auto expr = dynamic_cast<compiler::expression*>(e)->root();
if (expr != nullptr) {
if (!count_temps(expr, result))
return false;
}
break;
}
case element_type_t::assignment: {
auto assignment = dynamic_cast<compiler::assignment*>(e);
for (auto expr : assignment->expressions()) {
if (!count_temps(expr, result))
return false;
}
break;
}
case element_type_t::identifier: {
infer_type_result_t type_result {};
if (!e->infer_type(_session, type_result))
return false;
result.count(type_result.inferred_type);
break;
}
case element_type_t::declaration: {
auto decl = dynamic_cast<compiler::declaration*>(e);
auto assignment = decl->assignment();
if (assignment != nullptr) {
if (!count_temps(assignment, result))
return false;
}
break;
}
case element_type_t::argument_list: {
auto arg_list = dynamic_cast<compiler::argument_list*>(e);
for (auto arg : arg_list->elements()) {
if (!count_temps(arg, result))
return false;
}
break;
}
case element_type_t::unary_operator: {
auto unary_op = dynamic_cast<compiler::unary_operator*>(e);
if (!count_temps(unary_op->rhs(), result))
return false;
infer_type_result_t type_result {};
if (!e->infer_type(_session, type_result))
return false;
result.count(type_result.inferred_type);
break;
}
case element_type_t::binary_operator: {
auto bin_op = dynamic_cast<compiler::binary_operator*>(e);
if (!count_temps(bin_op->lhs(), result))
return false;
if (!count_temps(bin_op->rhs(), result))
return false;
infer_type_result_t type_result {};
if (!e->infer_type(_session, type_result))
return false;
result.count(type_result.inferred_type);
break;
}
case element_type_t::identifier_reference: {
auto ref = dynamic_cast<compiler::identifier_reference*>(e);
if (ref->identifier() != nullptr) {
if (!count_temps(ref->identifier(), result))
return false;
}
break;
}
default: {
break;
}
}
return true;
}
bool byte_code_emitter::make_temp_locals(
compiler::block* block,
temp_local_list_t& locals) {
temp_count_result_t result {};
auto success = _session.scope_manager().visit_child_blocks(
_session.result(),
[&](compiler::block* scope) {
for (auto stmt : scope->statements()) {
auto expr = stmt->expression();
if (expr == nullptr)
continue;
if (!count_temps(expr, result))
return false;
result.update();
}
return true;
},
block);
if (!success)
return false;
for (size_t i = 1; i <= result.ints; i++) {
locals.push_back(temp_local_t{
fmt::format("itemp{}", i),
0,
vm::op_sizes::qword,
vm::local_type_t::integer});
}
for (size_t i = 1; i <= result.floats; i++) {
locals.push_back(temp_local_t{
fmt::format("ftemp{}", i),
0,
vm::op_sizes::qword,
vm::local_type_t::floating_point});
}
return true;
}
bool byte_code_emitter::emit_type_table() {
auto& assembler = _session.assembler();
auto type_info_block = assembler.make_basic_block();
type_info_block->section(vm::section_t::ro_data);
auto used_types = _session.used_types();
for (auto type : used_types) {
type_info_block->blank_line();
type_info_block->align(4);
type_info_block->string(
assembler.make_label(compiler::type::make_literal_label_name(type)),
assembler.make_label(compiler::type::make_literal_data_label_name(type)),
type->name());
}
type_info_block->blank_line();
type_info_block->align(8);
type_info_block->label(assembler.make_label("_ti_array"));
type_info_block->qwords({used_types.size()});
for (auto type : used_types) {
emit_type_info(type_info_block, type);
}
return true;
}
bool byte_code_emitter::emit_bootstrap_block() {
auto& assembler = _session.assembler();
auto block = assembler.make_basic_block();
block->jump_direct(vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
"_start")));
return true;
}
void byte_code_emitter::intern_string_literals() {
auto literals = _session
.elements()
.find_by_type<compiler::string_literal>(element_type_t::string_literal);
for (auto literal : literals) {
if (literal->is_parent_type_one_of({
element_type_t::attribute,
element_type_t::directive,
element_type_t::module_reference})) {
continue;
}
_session.intern_string(literal);
}
}
bool byte_code_emitter::emit_interned_string_table() {
auto& assembler = _session.assembler();
auto block = assembler.make_basic_block();
block->comment("interned string literals", 0);
block->section(vm::section_t::ro_data);
auto interned_strings = _session.interned_strings();
for (const auto& kvp : interned_strings) {
block->blank_line();
block->align(4);
block->comment(
fmt::format("\"{}\"", kvp.first),
0);
std::string escaped {};
if (!compiler::string_literal::escape(kvp.first, escaped)) {
_session.error(
nullptr,
"X000",
fmt::format("invalid escape sequence: {}", kvp.first),
{});
return false;
}
block->string(
assembler.make_label(fmt::format("_intern_str_lit_{}", kvp.second)),
assembler.make_label(fmt::format("_intern_str_lit_{}_data", kvp.second)),
escaped);
}
return true;
}
bool byte_code_emitter::emit_section_tables(identifier_by_section_t& vars) {
if (!group_identifiers(vars))
return false;
auto& assembler = _session.assembler();
auto block = assembler.make_basic_block();
for (const auto& section : vars.sections) {
block->blank_line();
block->section(section.first);
for (auto e : section.second)
emit_section_variable(block, section.first, e);
}
return true;
}
bool byte_code_emitter::emit_end_block() {
auto& assembler = _session.assembler();
auto end_block = assembler.make_basic_block();
end_block->align(vm::instruction_t::alignment);
end_block->label(assembler.make_label("_end"));
end_block->exit();
return true;
}
bool byte_code_emitter::emit_start_block() {
auto& assembler = _session.assembler();
auto start_block = assembler.make_basic_block();
start_block->align(vm::instruction_t::alignment);
start_block->label(assembler.make_label("_start"));
start_block->move(
vm::instruction_operand_t::fp(),
vm::instruction_operand_t::sp());
return true;
}
bool byte_code_emitter::referenced_module_variables(
vm::instruction_block* basic_block,
compiler::block* block,
const identifier_by_section_t& vars,
identifier_list_t& locals) {
element_id_set_t processed {};
return _session.scope_manager().visit_child_blocks(
_session.result(),
[&](compiler::block* scope) {
for (auto ref_id : scope->references()) {
auto ref = dynamic_cast<compiler::identifier_reference*>(_session.elements().find(ref_id));
if (ref == nullptr)
continue;
auto var = ref->identifier();
if (vars.identifiers.count(var->id()) == 0)
continue;
if (processed.count(var->id()) > 0)
continue;
processed.insert(var->id());
basic_block->local(vm::local_type_t::integer, var->label_name());
locals.emplace_back(var);
}
return true;
},
block);
}
bool byte_code_emitter::emit_implicit_blocks(const identifier_by_section_t& vars) {
auto& assembler = _session.assembler();
block_list_t implicit_blocks {};
auto module_refs = _session
.elements()
.find_by_type<compiler::module_reference>(element_type_t::module_reference);
for (auto mod_ref : module_refs) {
auto block = mod_ref->reference()->scope();
if (block->statements().empty())
continue;
implicit_blocks.emplace_back(block);
}
implicit_blocks.emplace_back(_session.program().module()->scope());
for (auto block : implicit_blocks) {
auto implicit_block = assembler.make_basic_block();
auto parent_element = block->parent_element();
switch (parent_element->element_type()) {
case element_type_t::namespace_e: {
auto parent_ns = dynamic_cast<compiler::namespace_element*>(parent_element);
implicit_block->comment(fmt::format(
"namespace: {}",
parent_ns->name()));
break;
}
case element_type_t::module: {
auto parent_module = dynamic_cast<compiler::module*>(parent_element);
implicit_block->comment(fmt::format(
"module: {}",
parent_module->source_file()->path().string()));
break;
}
default:
break;
}
implicit_block->label(assembler.make_label(block->label_name()));
implicit_block->frame_offset("locals", -8);
identifier_list_t locals {};
if (!referenced_module_variables(implicit_block, block, vars, locals))
return false;
temp_local_list_t temp_locals {};
if (!make_temp_locals(block, temp_locals))
return false;
if (!emit_block(implicit_block, block, locals, temp_locals))
return false;
}
return true;
}
bool byte_code_emitter::emit_procedure_types(const identifier_by_section_t& vars) {
procedure_instance_set_t proc_instance_set {};
auto proc_calls = _session
.elements()
.find_by_type<compiler::procedure_call>(element_type_t::proc_call);
for (auto proc_call : proc_calls) {
if (proc_call->is_foreign())
continue;
auto proc_type = proc_call->procedure_type();
if (proc_type == nullptr)
return false;
auto instance = proc_type->instance_for(_session, proc_call);
if (instance != nullptr)
proc_instance_set.insert(instance);
}
if (_session.result().is_failed())
return false;
auto& assembler = _session.assembler();
for (auto instance : proc_instance_set) {
auto basic_block = assembler.make_basic_block();
if (!emit_procedure_instance(basic_block, instance, vars))
return false;
}
return true;
}
bool byte_code_emitter::emit_finalizers(const identifier_by_section_t& vars) {
auto& assembler = _session.assembler();
auto block = assembler.make_basic_block();
block->align(vm::instruction_t::alignment);
block->label(assembler.make_label("_finalizer"));
std::vector<compiler::identifier*> to_finalize {};
for (const auto& section : vars.sections) {
for (compiler::element* e : section.second) {
auto var = dynamic_cast<compiler::identifier*>(e);
if (var == nullptr)
continue;
if (!var->type_ref()->is_composite_type())
continue;
auto local_type = number_class_to_local_type(var->type_ref()->type()->number_class());
block->local(local_type, var->label_name());
to_finalize.emplace_back(var);
}
}
if (!to_finalize.empty())
block->blank_line();
for (auto var : to_finalize) {
block->move(
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
var->label_name())),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
var->label_name())));
}
for (auto var : to_finalize) {
emit_finalizer(block, var);
}
return true;
}
bool byte_code_emitter::group_identifiers(identifier_by_section_t& vars) {
auto& scope_manager = _session.scope_manager();
auto bss_list = vars.variable_section(vm::section_t::bss);
auto data_list = vars.variable_section(vm::section_t::data);
auto ro_list = vars.variable_section(vm::section_t::ro_data);
std::set<common::id_t> processed_identifiers {};
const element_type_set_t parent_types {element_type_t::field};
const element_type_set_t ignored_types {
element_type_t::generic_type,
element_type_t::namespace_type,
element_type_t::module_reference,
};
auto identifier_refs = _session
.elements()
.find_by_type<compiler::identifier_reference>(element_type_t::identifier_reference);
for (auto ref : identifier_refs) {
auto var = ref->identifier();
if (processed_identifiers.count(var->id()) > 0)
continue;
processed_identifiers.insert(var->id());
if (scope_manager.within_local_scope(var->parent_scope()))
continue;
auto var_parent = var->parent_element();
if (var_parent != nullptr
&& var_parent->is_parent_type_one_of(parent_types)) {
continue;
}
auto var_type = var->type_ref()->type();
if (var_type == nullptr) {
// XXX: this is an error!
return false;
}
if (var_type->is_type_one_of(ignored_types)) {
continue;
}
auto init = var->initializer();
if (init != nullptr) {
switch (init->expression()->element_type()) {
case element_type_t::directive: {
auto directive = dynamic_cast<compiler::directive*>(init->expression());
if (directive->name() == "type")
continue;
break;
}
case element_type_t::proc_type:
case element_type_t::composite_type:
case element_type_t::type_reference:
case element_type_t::module_reference:
continue;
default:
break;
}
}
if (var->is_constant()) {
ro_list->emplace_back(var);
} else {
vars.identifiers.insert(var->id());
if (init == nullptr) {
bss_list->emplace_back(var);
} else {
data_list->emplace_back(var);
}
}
}
return true;
}
bool byte_code_emitter::emit_initializers(const identifier_by_section_t& vars) {
auto& assembler = _session.assembler();
auto block = assembler.make_basic_block();
block->align(vm::instruction_t::alignment);
block->label(assembler.make_label("_initializer"));
identifier_list_t to_init {};
for (const auto& section : vars.sections) {
for (compiler::element* e : section.second) {
auto var = dynamic_cast<compiler::identifier*>(e);
if (var == nullptr)
continue;
if (!var->type_ref()->is_composite_type())
continue;
auto init = var->initializer();
if (init != nullptr) {
if (init->expression()->element_type() == element_type_t::uninitialized_literal)
continue;
}
auto local_type = number_class_to_local_type(var->type_ref()->type()->number_class());
block->local(local_type, var->label_name());
to_init.emplace_back(var);
}
}
if (!to_init.empty())
block->blank_line();
for (auto var : to_init) {
block->move(
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
var->label_name())),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
var->label_name())));
}
for (auto var : to_init) {
emit_initializer(block, var);
}
return true;
}
bool byte_code_emitter::emit_section_variable(
vm::instruction_block* block,
vm::section_t section,
compiler::element* e) {
auto& assembler = _session.assembler();
switch (e->element_type()) {
case element_type_t::type_literal: {
auto type_literal = dynamic_cast<compiler::type_literal*>(e);
block->blank_line();
block->align(4);
auto var_label = assembler.make_label(type_literal->label_name());
block->label(var_label);
// XXX: emit data
break;
}
case element_type_t::identifier: {
auto var = dynamic_cast<compiler::identifier*>(e);
auto var_type = var->type_ref()->type();
auto init = var->initializer();
auto is_initialized = init != nullptr || section == vm::section_t::bss;
block->blank_line();
auto type_alignment = static_cast<uint8_t>(var_type->alignment());
if (type_alignment > 1)
block->align(type_alignment);
block->comment(fmt::format(
"identifier type: {}",
var->type_ref()->name()));
auto var_label = assembler.make_label(var->label_name());
block->label(var_label);
switch (var_type->element_type()) {
case element_type_t::bool_type: {
bool value = false;
var->as_bool(value);
if (!is_initialized)
block->reserve_byte(1);
else
block->bytes({static_cast<uint8_t>(value ? 1 : 0)});
break;
}
case element_type_t::rune_type: {
common::rune_t value = common::rune_invalid;
var->as_rune(value);
if (!is_initialized)
block->reserve_byte(4);
else
block->dwords({static_cast<uint32_t>(value)});
break;
}
case element_type_t::pointer_type: {
if (!is_initialized)
block->reserve_qword(1);
else
block->qwords({0});
break;
}
case element_type_t::numeric_type: {
uint64_t value = 0;
auto symbol_type = vm::integer_symbol_type_for_size(var_type->size_in_bytes());
if (var_type->number_class() == number_class_t::integer) {
var->as_integer(value);
} else {
double temp = 0;
if (var->as_float(temp)) {
vm::register_value_alias_t alias {};
if (symbol_type == vm::symbol_type_t::u32)
alias.dwf = static_cast<float>(temp);
else
alias.qwf = temp;
value = alias.qw;
}
}
switch (symbol_type) {
case vm::symbol_type_t::u8:
if (!is_initialized)
block->reserve_byte(1);
else
block->bytes({static_cast<uint8_t>(value)});
break;
case vm::symbol_type_t::u16:
if (!is_initialized)
block->reserve_word(1);
else
block->words({static_cast<uint16_t>(value)});
break;
case vm::symbol_type_t::f32:
case vm::symbol_type_t::u32:
if (!is_initialized)
block->reserve_dword(1);
else
block->dwords({static_cast<uint32_t>(value)});
break;
case vm::symbol_type_t::f64:
case vm::symbol_type_t::u64:
if (!is_initialized)
block->reserve_qword(1);
else
block->qwords({value});
break;
case vm::symbol_type_t::bytes:
break;
default:
break;
}
break;
}
case element_type_t::array_type:
case element_type_t::tuple_type:
case element_type_t::composite_type: {
block->reserve_byte(var_type->size_in_bytes());
break;
}
default: {
break;
}
}
break;
}
default:
break;
}
return true;
}
bool byte_code_emitter::emit_primitive_initializer(
vm::instruction_block* block,
const vm::instruction_operand_t& base_local,
compiler::identifier* var,
int64_t offset) {
auto var_type = var->type_ref()->type();
auto init = var->initializer();
uint64_t default_value = var_type->element_type() == element_type_t::rune_type ?
common::rune_invalid :
0;
vm::instruction_operand_t value(
default_value,
vm::op_size_for_byte_size(var_type->size_in_bytes()));
vm::instruction_operand_t* value_ptr = &value;
emit_result_t result {};
if (init != nullptr) {
if (!emit_element(block, init, result))
return false;
value_ptr = &result.operands.back();
}
block->comment(
fmt::format("initializer: {}: {}", var->label_name(), var_type->name()),
vm::comment_location_t::after_instruction);
block->store(
base_local,
*value_ptr,
vm::instruction_operand_t::offset(offset));
return true;
}
bool byte_code_emitter::emit_finalizer(
vm::instruction_block* block,
compiler::identifier* var) {
auto var_type = var->type_ref()->type();
block->comment(
fmt::format("finalizer: {}: {}", var->label_name(), var_type->name()),
4);
return true;
}
bool byte_code_emitter::emit_initializer(
vm::instruction_block* block,
compiler::identifier* var) {
vm::instruction_operand_t base_local(_session.assembler().make_named_ref(
vm::assembler_named_ref_type_t::local,
var->label_name()));
std::vector<compiler::identifier*> list {};
list.emplace_back(var);
uint64_t offset = 0;
while (!list.empty()) {
auto next_var = list.front();
list.erase(std::begin(list));
auto var_type = next_var->type_ref()->type();
switch (var_type->element_type()) {
case element_type_t::rune_type:
case element_type_t::bool_type:
case element_type_t::numeric_type:
case element_type_t::pointer_type: {
if (!emit_primitive_initializer(block, base_local, next_var, offset))
return false;
offset += var_type->size_in_bytes();
break;
}
case element_type_t::tuple_type:
case element_type_t::composite_type: {
auto composite_type = dynamic_cast<compiler::composite_type*>(var_type);
switch (composite_type->type()) {
case composite_types_t::enum_type: {
if (!emit_primitive_initializer(block, base_local, next_var, offset))
return false;
offset += var_type->size_in_bytes();
break;
}
case composite_types_t::union_type: {
// XXX: intentional no-op
break;
}
case composite_types_t::struct_type: {
auto field_list = composite_type->fields().as_list();
size_t index = 0;
for (auto fld: field_list) {
list.emplace(std::begin(list) + index, fld->identifier());
index++;
}
offset = common::align(offset, composite_type->alignment());
break;
}
}
break;
}
default: {
break;
}
}
}
return true;
}
bool byte_code_emitter::end_stack_frame(
vm::instruction_block* basic_block,
compiler::block* block,
const identifier_list_t& locals) {
identifier_list_t to_finalize {};
for (compiler::element* e : locals) {
auto var = dynamic_cast<compiler::identifier*>(e);
if (var == nullptr)
continue;
if (!var->type_ref()->is_composite_type()) {
continue;
}
to_finalize.emplace_back(var);
}
if (!basic_block->is_current_instruction(vm::op_codes::rts)) {
basic_block->move(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::fp());
basic_block->pop(vm::instruction_operand_t::fp());
}
return true;
}
bool byte_code_emitter::begin_stack_frame(
vm::instruction_block* basic_block,
compiler::block* block,
identifier_list_t& locals,
temp_local_list_t& temp_locals) {
auto& assembler = _session.assembler();
auto& scope_manager = _session.scope_manager();
identifier_list_t to_init {};
int64_t offset = 0;
for (const auto& temp : temp_locals)
basic_block->local(temp.type, temp.name);
scope_manager.visit_child_blocks(
_session.result(),
[&](compiler::block* scope) {
if (scope->is_parent_type_one_of({element_type_t::proc_type}))
return true;
for (auto var : scope->identifiers().as_list()) {
if (var->is_constant())
continue;
auto type = var->type_ref()->type();
if (type->is_proc_type())
continue;
offset += -type->size_in_bytes();
var->usage(identifier_usage_t::stack);
basic_block->local(
vm::local_type_t::integer,
var->label_name(),
offset,
"locals");
to_init.emplace_back(var);
locals.emplace_back(var);
}
return true;
},
block);
basic_block->push(vm::instruction_operand_t::fp());
basic_block->move(
vm::instruction_operand_t::fp(),
vm::instruction_operand_t::sp());
auto locals_size = common::align(static_cast<uint64_t>(-offset), 8);
if (locals_size > 0) {
locals_size += 8;
basic_block->sub(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::sp(),
vm::instruction_operand_t(static_cast<uint64_t>(locals_size), vm::op_sizes::dword));
}
for (auto var : locals) {
const auto& name = var->label_name();
const auto& local = basic_block->local(name);
basic_block->comment(
fmt::format("address: {}", name),
vm::comment_location_t::after_instruction);
if (!local->frame_offset.empty()) {
basic_block->move(
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
name)),
vm::instruction_operand_t::fp(),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::offset,
name,
vm::op_sizes::word)));
} else {
basic_block->move(
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
name)),
vm::instruction_operand_t(assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
name)));
}
}
for (auto var : to_init) {
if (!emit_initializer(basic_block, var))
return false;
}
return true;
}
std::string byte_code_emitter::temp_local_name(
number_class_t type,
uint8_t number) {
switch (type) {
case number_class_t::none: {
return fmt::format("temp{}", number);
}
case number_class_t::integer: {
return fmt::format("itemp{}", number);
}
case number_class_t::floating_point: {
return fmt::format("ftemp{}", number);
}
}
}
bool byte_code_emitter::emit_procedure_epilogue(
vm::instruction_block* block,
compiler::procedure_type* proc_type) {
if (proc_type->is_foreign())
return true;
if (!proc_type->has_return()) {
block->rts();
}
return true;
}
bool byte_code_emitter::emit_procedure_instance(
vm::instruction_block* block,
compiler::procedure_instance* proc_instance,
const identifier_by_section_t& vars) {
auto procedure_type = proc_instance->procedure_type();
if (procedure_type->is_foreign())
return true;
auto scope_block = proc_instance->scope();
identifier_list_t locals {};
if (!emit_procedure_prologue(block, procedure_type, locals))
return false;
if (!referenced_module_variables(block, scope_block, vars, locals))
return false;
temp_local_list_t temp_locals {};
if (!make_temp_locals(scope_block, temp_locals))
return false;
block->blank_line();
if (!emit_block(block, scope_block, locals, temp_locals))
return false;
return emit_procedure_epilogue(block, procedure_type);
}
bool byte_code_emitter::emit_procedure_prologue(
vm::instruction_block* block,
compiler::procedure_type* proc_type,
identifier_list_t& parameters) {
if (proc_type->is_foreign())
return true;
auto& assembler = _session.assembler();
auto procedure_label = proc_type->symbol()->name();
auto parent_init = proc_type->parent_element_as<compiler::initializer>();
if (parent_init != nullptr) {
auto parent_var = parent_init->parent_element_as<compiler::identifier>();
if (parent_var != nullptr) {
procedure_label = parent_var->label_name();
}
}
block->align(vm::instruction_t::alignment);
block->label(assembler.make_label(procedure_label));
block->frame_offset("locals", -8);
auto return_type = proc_type->return_type();
if (return_type != nullptr) {
block->frame_offset("returns", 16);
block->frame_offset("parameters", 24);
auto retval_var = return_type->declaration()->identifier();
parameters.emplace_back(retval_var);
block->local(
vm::local_type_t::integer,
retval_var->label_name(),
0,
"returns");
} else {
block->frame_offset("parameters", 16);
}
int64_t offset = 0;
auto fields = proc_type->parameters().as_list();
for (auto fld : fields) {
auto var = fld->identifier();
block->local(
vm::local_type_t::integer,
var->label_name(),
offset,
"parameters");
offset += 8;
parameters.emplace_back(var);
}
return true;
}
bool byte_code_emitter::emit_arguments(
vm::instruction_block* block,
compiler::argument_list* arg_list,
const compiler::element_list_t& elements) {
for (auto it = elements.rbegin(); it != elements.rend(); ++it) {
compiler::type* type = nullptr;
element* arg = *it;
switch (arg->element_type()) {
case element_type_t::argument_list: {
auto list = dynamic_cast<compiler::argument_list*>(arg);
if (!emit_arguments(block, list, list->elements()))
return false;
break;
}
case element_type_t::cast:
case element_type_t::transmute:
case element_type_t::proc_call:
case element_type_t::intrinsic:
case element_type_t::expression:
case element_type_t::nil_literal:
case element_type_t::float_literal:
case element_type_t::string_literal:
case element_type_t::unary_operator:
case element_type_t::assembly_label:
case element_type_t::binary_operator:
case element_type_t::boolean_literal:
case element_type_t::integer_literal:
case element_type_t::character_literal:
case element_type_t::identifier_reference: {
auto temp = allocate_temp();
emit_result_t arg_result {};
if (!emit_element(block, arg, arg_result))
return false;
read(block, arg_result, temp);
if (!arg_list->is_foreign_call()) {
type = arg_result.type_result.inferred_type;
switch (type->element_type()) {
case element_type_t::array_type:
case element_type_t::tuple_type:
case element_type_t::composite_type: {
auto size = static_cast<uint64_t>(common::align(
type->size_in_bytes(),
8));
block->sub(
vm::instruction_operand_t::sp(),
vm::instruction_operand_t::sp(),
vm::instruction_operand_t(size, vm::op_sizes::word));
block->copy(
vm::op_sizes::byte,
vm::instruction_operand_t::sp(),
arg_result.operands.back(),
vm::instruction_operand_t(size, vm::op_sizes::word));
break;
}
default: {
block->push(arg_result.operands.back());
break;
}
}
} else {
block->push(arg_result.operands.back());
}
free_temp();
break;
}
default:
break;
}
if (type != nullptr) {
auto size = static_cast<uint64_t>(common::align(
type->size_in_bytes(),
8));
arg_list->allocated_size(arg_list->allocated_size() + size);
}
}
return true;
}
bool byte_code_emitter::emit_relational_operator(
vm::instruction_block* block,
compiler::binary_operator* binary_op,
emit_result_t& result) {
auto& assembler = _session.assembler();
auto end_label_name = fmt::format("{}_end", binary_op->label_name());
auto end_label_ref = assembler.make_named_ref(
vm::assembler_named_ref_type_t::label,
end_label_name);
auto lhs_temp = allocate_temp();
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(result.type_result.inferred_type->number_class(), lhs_temp),
vm::op_sizes::byte));
result.operands.emplace_back(result_operand);
emit_result_t lhs_result {};
if (!emit_element(block, binary_op->lhs(), lhs_result))
return false;
read(block, lhs_result, lhs_temp);
auto rhs_temp = allocate_temp();
emit_result_t rhs_result {};
if (!emit_element(block, binary_op->rhs(), rhs_result))
return false;
read(block, rhs_result, rhs_temp);
auto is_signed = lhs_result.type_result.inferred_type->is_signed();
if (is_logical_conjunction_operator(binary_op->operator_type())) {
block->move(
result_operand,
lhs_result.operands.back());
switch (binary_op->operator_type()) {
case operator_type_t::logical_or: {
block->bnz(
result_operand,
vm::instruction_operand_t(end_label_ref));
break;
}
case operator_type_t::logical_and: {
block->bz(
result_operand,
vm::instruction_operand_t(end_label_ref));
break;
}
default: {
break;
}
}
block->move(
result_operand,
rhs_result.operands.back());
} else {
block->cmp(
lhs_result.operands.back(),
rhs_result.operands.back());
switch (binary_op->operator_type()) {
case operator_type_t::equals: {
block->setz(result_operand);
break;
}
case operator_type_t::less_than: {
if (is_signed)
block->setl(result_operand);
else
block->setb(result_operand);
break;
}
case operator_type_t::not_equals: {
block->setnz(result_operand);
break;
}
case operator_type_t::greater_than: {
if (is_signed)
block->setg(result_operand);
else
block->seta(result_operand);
break;
}
case operator_type_t::less_than_or_equal: {
if (is_signed)
block->setle(result_operand);
else
block->setbe(result_operand);
break;
}
case operator_type_t::greater_than_or_equal: {
if (is_signed)
block->setge(result_operand);
else
block->setae(result_operand);
break;
}
default: {
break;
}
}
}
block->label(assembler.make_label(end_label_name));
free_temp();
free_temp();
return true;
}
bool byte_code_emitter::emit_arithmetic_operator(
vm::instruction_block* block,
compiler::binary_operator* binary_op,
emit_result_t& result) {
auto& assembler = _session.assembler();
auto lhs_temp = allocate_temp();
emit_result_t lhs_result {};
if (!emit_element(block, binary_op->lhs(), lhs_result))
return false;
read(block, lhs_result, lhs_temp);
auto rhs_temp = allocate_temp();
emit_result_t rhs_result {};
if (!emit_element(block, binary_op->rhs(), rhs_result))
return false;
read(block, rhs_result, rhs_temp);
auto size = vm::op_size_for_byte_size(result.type_result.inferred_type->size_in_bytes());
vm::instruction_operand_t result_operand(assembler.make_named_ref(
vm::assembler_named_ref_type_t::local,
temp_local_name(result.type_result.inferred_type->number_class(), lhs_temp),
size));
result.operands.emplace_back(result_operand);
switch (binary_op->operator_type()) {
case operator_type_t::add: {
block->add(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::divide: {
block->div(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::modulo: {
block->mod(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::multiply: {
block->mul(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::exponent: {
block->pow(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::subtract: {
block->sub(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::binary_or: {
block->or_op(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::shift_left: {
block->shl(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::binary_and: {
block->and_op(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::binary_xor: {
block->xor_op(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::rotate_left: {
block->rol(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::shift_right: {
block->shr(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
case operator_type_t::rotate_right: {
block->ror(
result_operand,
lhs_result.operands.back(),
rhs_result.operands.back());
break;
}
default:
break;
}
free_temp();
free_temp();
return true;
}
std::string byte_code_emitter::interned_string_data_label(common::id_t id) {
common::id_t intern_id;
_session.interned_strings().element_id_to_intern_id(id, intern_id);
return fmt::format("_intern_str_lit_{}_data", intern_id);
}
bool byte_code_emitter::is_temp_local(const vm::instruction_operand_t& operand) {
if (operand.type() == vm::instruction_operand_type_t::named_ref) {
auto named_ref = *operand.data<vm::assembler_named_ref_t*>();
return named_ref->name.substr(1, 4) == "temp";
}
return false;
}
}
| 40.487908 | 128 | 0.474603 | [
"vector"
] |
6c0dd710754d54020621d04a92b187f5f60cd28c | 11,047 | cc | C++ | contribs/qecode/WorkManager.cc | guidotack/gecode | 027c57889d66dd26ad8e1a419c2cda22ab0cf305 | [
"MIT-feh"
] | 216 | 2016-07-11T12:44:44.000Z | 2022-03-24T01:48:06.000Z | contribs/qecode/WorkManager.cc | guidotack/gecode | 027c57889d66dd26ad8e1a419c2cda22ab0cf305 | [
"MIT-feh"
] | 105 | 2018-02-01T15:51:15.000Z | 2022-03-05T16:10:36.000Z | contribs/qecode/WorkManager.cc | guidotack/gecode | 027c57889d66dd26ad8e1a419c2cda22ab0cf305 | [
"MIT-feh"
] | 73 | 2016-02-15T07:09:36.000Z | 2022-03-22T23:10:26.000Z | /************************************************************ WorkManager.cc
Copyright (c) 2010 Universite d'Orleans - Jeremie Vautard
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 "WorkManager.hh"
bool isPrefix(vector<int> prefix,vector<int> a) {
if (a.size() < prefix.size())
return false;
else
for (unsigned int i=0;i<prefix.size();i++)
if (prefix[i] != a[i])
return false;
return true;
}
WorkPool::WorkPool(WorkComparator* a) {
cmp=a;
}
void WorkPool::push(QWork q) {
list<QWork>::iterator i = l.begin();
while (i != l.end() && cmp->cmp((*i),q)) i++;
l.insert(i,q);
}
QWork WorkPool::pop() {
QWork ret=l.front();
l.pop_front();
return ret;
}
void WorkPool::trash(vector<int> prefix) {
// cout<<" WPT called on ";
//if (prefix.empty()) cout<<"empty";
//for (int i=0;i< prefix.size();i++) cout<<prefix[i]<<" ";
//cout<<endl;
// cout<<"debug "<<l.size()<<endl;
list<QWork>::iterator i=l.begin();
while (!(i == l.end())) {
// cout<<"| ";
// cout.flush();
bool avance=true;
vector<int> root = (*i).root();
if (isPrefix(prefix,root)) {
(*i).clean();
i=l.erase(i);
avance = false;
// cout<<"erased";
}
if (avance) i++;
}
//cout<<endl;
//for (list<QWork>::iterator i=l.begin();i != l.end();i++) {
//vector<int> root = (*i).root();
//if (isPrefix(prefix,root)) {
// cout<<" trashing ";
// if (root.empty()) cout<<"empty";
// for (int j=0;j< root.size();j++) cout<<root[j]<<" ";
// cout<<endl;
//(*i).clean();
//l.erase(i);
//i--;
//}
// }
}
void WorkManager::getNewWorks() {
// cout<<"WM asking for "<<actives.front()<<" to stopandreturn"<<endl;
(actives.front())->stopAndReturn();
}
WorkManager::WorkManager(Qcop* p,WorkComparator* c) : Todos(c) {
problem=p;
vector<int> v;
MySpace* espace=p->getSpace(0);
Options o;
Engine* solutions = new WorkerToEngine<Gecode::Search::Sequential::DFS>(espace,/*sizeof(MySpace),*/o);
QWork first(0,v,solutions);
Todos.push(first);
finished=false;
S = Strategy::Dummy();
S.attach(Strategy::Stodo());
}
QWork WorkManager::getWork(AQWorker* worker) {
// clock_t start = clock();
// cout<<worker<<" WAIT getWork "<<start<<endl;
mex.acquire();
// clock_t stop = clock();
// cout<<worker<<" CONT getWork "<<stop<<" waited "<<(stop-start)<<endl;
// cout<<"G ";cout.flush();
// cout<<"WM getwork acquired"<<endl;
QWork ret;
if (Todos.empty()) {
// cout<<"WM : Todos was empty"<<endl;
if (actives.empty()) {
// cout<<"WM : Actives was empty, stopping worker."<<endl;
ret = QWork::Stop();
finished=true;
}
else {
getNewWorks();
// cout<<"WM sleeping worker"<<endl;
ret = QWork::Wait();
idles.push_back(worker);
}
}
else {
// cout<<"WM : giving work ";
ret = Todos.top();
Todos.pop();
// if (ret.root().empty()) cout<<"empty";
// for (int i=0;i< ret.root().size();i++) cout<<ret.root()[i]<<" ";
// cout<<endl;
actives.push_back(worker);
}
// cout<<"WM getwork release"<<endl;
mex.release();
return ret;
}
void WorkManager::returnWork(AQWorker* worker,Strategy ret,list<QWork> todo,vector<int> position) {
// If the worker is not among the actives ones, ignore his job. Else, withdraw it from the active workers
// and process its result
// clock_t start = clock();
// cout<<worker<<" WAIT returnWork "<<start<<endl;
mex.acquire();
// clock_t stop = clock();
// cout<<worker<<" CONT returnWork "<<stop<<" waited "<<(stop-start)<<endl;
// cout<<"RW returnWork acquired"<<endl;
// cout<<"returning work at ";
// if (position.empty()) cout<<"empty";
// for (int i=0;i< position.size();i++) cout<<position[i]<<" ";
// cout<<endl;
bool ok=false;
list<AQWorker*>::iterator i = actives.begin();
while (!(i == actives.end()) && !ok) {
bool avance=true;
if ((*i) == worker) {
// cout<<"RW Worker found in actives. Deleting"<<endl;
i=actives.erase(i);
avance = false;
ok=true;
}
if (avance) ++i;
}
if (!ok) {
// cout<<"RW Ignoring work"<<endl;
// when ignoring the result, we have to delete every search engine from the eventual to-do works it did
for (list<QWork>::iterator j = todo.begin();j != todo.end();j++) {
(*j).clean();
}
// cout<<"RW release"<<endl;
mex.release();
return;
}
// processing results...
// adding todo to Todos
// going to father of substrategy
bool acceptable = true;
Strategy father = S.getSubStrategy(position);
if (father.isDummy() && (father.id() != S.id())) {
// cout<<"ERROR : RW Work was not in current strategy. Ignoring."<<endl;
acceptable=false;
}
// remove the Todo node that marked this work
if (acceptable) {
// cout<<" RW Father position is ";
// vector<int> checkPosition = father.getPosition();
// if (checkPosition.empty()) cout<<"empty";
// for (int i=0;i< checkPosition.size();i++) cout<<checkPosition[i]<<" ";
// cout<<endl;
for (list<QWork>::iterator j = todo.begin();j != todo.end();j++) {
// cout<<"WM todo + 1"<<endl;
if (!idles.empty()) {
// cout<<"WM waking an idle"<<endl;
AQWorker* towake = idles.back();
idles.pop_back();
towake->wake();
}
// cout<<"RW Adding work in Todos : ";
// if ((*j).root().empty()) cout<<"empty";
// for (int i=0;i< (*j).root().size();i++) cout<<(*j).root()[i]<<" ";
// cout<<endl;
Todos.push(*j);
}
for (unsigned int i=0;i<father.degree();i++) {
if (father.getChild(i).isTodo()) {
// cout<<"RW deleting Todo node"<<endl;
father.detach(i);
i--;
}
}
if (!ret.isComplete()) { // still work to do...
// attach the (incomplete) substrategy
// cout<<"RW returned work was incomplete. Attaching"<<endl;
father.attach(ret);
}
else if (!ret.isFalse()) { // complete substrategy
// attach the (complete) substrategy
// recursively update node
// cout<<"RW returned work was true. Attaching and updating"<<endl;
father.attach(ret);
updateTrue(father);
}
else { //ret is false
// cout<<"RW returned work was false. Attaching and updating"<<endl;
int myscope = problem->qt_of_var(position.size() + 1);
if (myscope) { // if ret was a forall node, the father itself is false
// cout<<"RW work is A -> father is false"<<endl;
updateFalse(father);
}
else if (father.degree() == 0) { // Here ret was an exists node. If the father has no other son, then the father itself is false
// cout<<"RW work is E, father is without child"<<endl;
updateFalse(father);
}
// else {
// // cout<<"RW work is E, father still has children"<<endl;
// }
}
}
else { // work was not acceptable
for (list<QWork>::iterator j = todo.begin();j != todo.end();j++) {
(*j).clean();
}
}
// cout<<"RW release"<<endl;
mex.release();
}
void WorkManager::updateTrue(Strategy s) { //called when s has a son who is a complete strategy
// cout<<" UT on ";
// vector<int> hihi = s.getPosition();
// if (hihi.empty()) cout<<"empty";
// for (int i=0;i< hihi.size();i++) cout<<hihi[i]<<" ";
// cout<<endl;
if (s.isComplete()) {
// cout<<" UT Complete ";
if (s.quantifier()) {
// cout<< " A ";
if (s.hasFather()) {
// cout<<" with father"<<endl;
updateTrue(s.getFather());
}
else {
// cout<<" without father"<<endl;
}
}
else {
// cout<<" E ";
if (s.hasFather()) {
// cout<<" with father"<<endl;
Strategy father = s.getFather();
while (father.degree() != 0) {
father.detach(father.degree()-1);
}
father.attach(s);
trashWorks(father.getPosition());
updateTrue(father);
}
else {
// cout<<" without father"<<endl;
}
}
}
else {
// cout<<" UT incomplete"<<endl;
}
}
void WorkManager::updateFalse(Strategy s) { // called when s is false
// cout<<" UF on ";
// vector<int> hihi = s.getPosition();
// if (hihi.empty()) cout<<"empty";
// for (int i=0;i< hihi.size();i++) cout<<hihi[i]<<" ";
// cout<<endl;
trashWorks(s.getPosition());
if (s.isDummy()) {
return;
}
Strategy father=s.getFather();
if (s.quantifier()) { // if s is universal, its father is false
// cout<<" UF A";
if (father.isDummy()) { // if father is dummy, it is the root of the strategy. We must cut all its children and ad a false node.
// cout<<" father root "<<endl;
while (father.degree() != 0) {
father.detach(father.degree()-1);
}
father.attach(Strategy::SFalse());
}
// cout<<endl;
updateFalse(s.getFather());
}
else { // if s is existential, it it detached from its father
// cout<<" UF E ";
father.detach(s);
if (father.degree() == 0) {
// cout<<" father false"<<endl;
updateFalse(father);
}
else {
// cout<<" father still not false"<<endl;
}
}
}
void WorkManager::trashWorks(vector<int> prefix) {
// cout<<" TW called on ";
// if (prefix.empty()) cout<<"empty";
// for (int i=0;i< prefix.size();i++) cout<<prefix[i]<<" ";
// cout<<endl;
Todos.trash(prefix);
for (list<AQWorker*>::iterator i=actives.begin();i!=actives.end();i++) {
if (isPrefix(prefix,(*i)->workPosition())) {
// cout<<" TW stopping worker on";
// vector<int> plop = (*i)->workPosition();
// if (plop.empty()) cout<<"empty";
// for (int j=0;j< plop.size();j++) cout<<plop[j]<<" ";
// cout<<endl;
(*i)->stopAndForget();
i=actives.erase(i);
i--;
}
}
}
void WorkManager::printStatus() {
mex.acquire();
cout<<(finished?"Problem solved":"Problem not solved")<<endl;
cout<<"Size of pool : "<<Todos.size()<<endl;
cout<<"# idles : "<<idles.size()<<endl;
cout<<"# actives : "<<actives.size()<<endl;
mex.release();
}
| 29.302387 | 134 | 0.577261 | [
"vector"
] |
6c1750b3055eb3d9178afadf503d20f59c619bb5 | 6,786 | cpp | C++ | src/physics/collision/rectcollider.cpp | cbosoft/geas | 9451b7fd4924d5bc3f21f3c9cc053540953b95c0 | [
"MIT"
] | null | null | null | src/physics/collision/rectcollider.cpp | cbosoft/geas | 9451b7fd4924d5bc3f21f3c9cc053540953b95c0 | [
"MIT"
] | null | null | null | src/physics/collision/rectcollider.cpp | cbosoft/geas | 9451b7fd4924d5bc3f21f3c9cc053540953b95c0 | [
"MIT"
] | null | null | null | #include <vector>
#include "../../util/exception.hpp"
#include "../../geas_object/geas_object.hpp"
#ifdef DEBUG
#include "../../game/game.hpp"
#endif
#include "rectcollider.hpp"
const static float _rect_overlap = 1.0f;
RectCollider::RectCollider(GeasObject *owner, const Vec4 &rect)
: Transform(owner)
, tr(this)
, br(this)
, bl(this)
, tl(this)
, _renderable(nullptr)
{
Vec2 bl_offset({rect.x() - _rect_overlap, rect.y() - _rect_overlap});
this->size.x(rect.get(2) + _rect_overlap*2);
this->size.y(rect.get(3) + _rect_overlap*2);
this->relative_position(bl_offset.promote(0.0f));
this->tr.relative_position(size.promote(0.0f));
this->br.relative_position(Vec3({size.x(), 0.0f, 0.0f}));
this->tl.relative_position(Vec3({0.0f, size.y(), 0.0f}));
#ifdef DEBUG
if (Game::singleton()->should_show_colliders()) {
auto *r = new Renderable(owner);
r->set_texture("assets/textures/rectcollider.png");
r->size(this->size);
r->relative_position(this->relative_position());
this->_renderable = r;
}
#endif
}
RectCollider::RectCollider(GeasObject *owner, const Vec2 &bl_offset, const Vec2 &size)
: Transform(owner)
, size(size)
, tr(this)
, br(this)
, bl(this)
, tl(this)
, _renderable(nullptr)
{
Vec3 bl_pos = bl_offset.promote(0.0f);
bl_pos += Vec2(-_rect_overlap).promote(0.0f);
this->relative_position(bl_pos);
Vec3 size_after_offset = (size + Vec2(_rect_overlap*2)).promote(0.0f);
this->tr.relative_position(size_after_offset);
this->br.relative_position(Vec3({size_after_offset.x(), 0.0f, 0.0f}));
this->tl.relative_position(Vec3({0.0f, size_after_offset.y(), 0.0f}));
#ifdef DEBUG
if (Game::singleton()->should_show_colliders()) {
auto *r = new Renderable(owner);
r->set_texture("assets/textures/rectcollider.png");
r->size(this->size);
r->relative_position(this->relative_position());
this->_renderable = r;
}
#endif
}
RectCollider::~RectCollider()
{
// do nothing
}
/// Get the centre point of the rectangle, in absolute coordinates
/// \return the centre of the rectangle
Vec2 RectCollider::get_centre() const
{
Vec2 bl = this->absolute_position();
return bl + this->size*0.5;
}
/// Get the absolute (world) positions of the four corners of this rectangle.
/// \return list of Vec2 positions
std::list<Vec2> RectCollider::get_corners() const
{
std::list<Vec2> corners({
this->tr.absolute_position(),
this->br.absolute_position(),
this->bl.absolute_position(),
this->tl.absolute_position()
});
return corners;
}
/// Get the point on the rectangle nearest to the other point p.
/// \param p
/// \return Nearest point to p
Vec2 RectCollider::get_nearest(const Vec2 &p) const
{
//std::list<Vec2> corners = this->get_corners();
// TODO: get nearest point on the collider to the point p
(void) p;
return this->absolute_position();
}
/// Get nearest points on this collider to collider other
/// \param other
/// \return pair of position on *this* surface, and position on *other* surface
std::pair<Vec2, Vec2> RectCollider::get_nearest(const RectCollider *other) const
{
// TODO
// draw line from this centre to other centre
Vec2 dr = other->get_centre() - this->get_centre();
static Vec2 vert({0.0f, 1.0f});
const float a = std::abs(dr.dot(vert)/dr.magnitude());
float theta = std::acos(a);
if (dr.x() > 0.0f) {
if (dr.y() > 0.0) {
// angle is acute
// do nothing
}
else {
// pos x, neg y: angle is obtuse
theta += M_PI_2;
}
}
else {
if (dr.y() > 0.0) {
// neg x, pos y: angle is between 3/2 pi and 2 pi
theta += M_PI - M_PI_4;
}
else {
// neg x, neg y: angle is between pi and 3/2 pi
theta += M_PI;
}
}
// TODO calculate cross over of c2c vec and side
Vec2 thispos = this->absolute_position(), otherpos = other->absolute_position();
if ((theta >= M_PI_4) && (theta < M_PI - M_PI_4)) {
// right on this, left on other
thispos = thispos + this->size*Vec2({1.0,0.5});
otherpos = otherpos + Vec2({0.0f, this->size.y()*0.5f});
}
else if ((theta >= M_PI - M_PI_4) && (theta < M_PI + M_PI_4)) {
// bottom on this, top on other
thispos = thispos + Vec2({this->size.x()*0.5f, 0.0f});
otherpos = otherpos + this->size*Vec2({0.5f,1.0f});
}
else if ((theta >= M_PI + M_PI_4) && (theta < M_2_PI - M_PI_4)) {
// left on this, right on other
otherpos = otherpos + this->size*Vec2({1.0,0.5});
thispos = thispos + Vec2({0.0f, this->size.y()*0.5f});
}
else /*if ((theta >= M_2_PI - M_PI_4) || (theta < M_PI_4))*/ {
// top on this, bottom on other
otherpos = otherpos + Vec2({this->size.x()*0.5f, 0.0f});
thispos = thispos + this->size*Vec2({1.0,0.5});
}
return std::make_pair(thispos, otherpos);
}
/// Calculate the normal vector (vector pointing away perpendicular) to the surface of the collider
/// \param at the point on the collider at which to calc the normal
/// \return the normal vector (2D)
Vec2 RectCollider::get_surface_normal(const Vec2 &at) const
{
auto corners = this->get_corners();
corners.push_back(corners.front());
std::list<Vec2> normals{
Vec2({ 1.0, 0.0}),
Vec2({ 0.0, -1.0}),
Vec2({ -1.0, 0.0}),
Vec2({ 0.0, 1.0})
};
auto corner = corners.begin(), next_corner = corner++, normal = normals.begin();
for (;next_corner != corners.end();corner++, next_corner++, normal++) {
if (at.coincident(*corner, *next_corner, 0.01)) {
return *normal;
}
}
throw PositionError(Formatter() << "RectCollider::get_surface_normal(at) -> position " << at.to_string() << " is not on the rectangle. " << this->tr.absolute_position().to_string());
}
bool RectCollider::intersects(const Vec2 &dr, const RectCollider *other) const
{
auto corners = this->get_corners();
for (const auto &corner : corners) {
Vec2 ppos = corner + dr;
if (other->contains_point(ppos)) {
return true;
}
}
return false;
}
bool RectCollider::contains_point(const Vec2 &pt) const
{
Vec2 blpt = this->bl.absolute_position();
return (
(pt.x() > blpt.x()) &&
(pt.x() <= blpt.x() + this->size.x()) &&
(pt.y() > blpt.y()) &&
(pt.y() <= blpt.y() + this->size.y())
);
}
Renderable *RectCollider::renderable() const
{
return this->_renderable;
}
| 27.144 | 186 | 0.59608 | [
"vector",
"transform"
] |
6c2308d12322eec865d2b3be7619d0026a999e02 | 18,785 | cpp | C++ | Resource/Source/ResourceMgr.cpp | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | Resource/Source/ResourceMgr.cpp | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | Resource/Source/ResourceMgr.cpp | TaylorClark/PrimeTime | 3c62f6c53e0494146a95be1412273de3cf05bcd2 | [
"MIT"
] | null | null | null | //=================================================================================================
/*!
\file ResourceMgr.cpp
Resources Library
Resource Manager Source
\author Taylor Clark
\date March 3, 2006
This source file contains the implementation for ResourceManager class.
*/
//=================================================================================================
#include "../ResourceMgr.h"
#include <fstream>
#include "Base/MsgLogger.h"
#include "Base/NetSafeDataBlock.h"
#include "Base/StringFuncs.h"
#include "Base/TCAssert.h"
#include "Base/FileFuncs.h"
#include "Graphics2D/TCFont.h"
#include "Graphics2D/RefSprite.h"
#ifndef TOOLS
#include "Graphics2D/GraphicsMgr.h"
#endif
#include "GUI/GUIMgr.h"
#include "Audio/AudioMgr.h"
#include "Base/NetSafeSerializer.h"
#include "PrimeTime/ApplicationBase.h"
// Initialize the static variables
//const int ResourceMgr::MAX_RES_PER_DB = 128;
const FourCC ResourceMgr::FOURCCKEY_RESDB( "RSDB" );
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::Init() Public
///
/// Initialize the resource manager and find the resource files.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void ResourceMgr::Init()
{
// Get the resources
FindResources();
}
/// Release all resources and memory that was loaded
void ResourceMgr::Term()
{
// Free the inter-resource dependencies then free the object
for( std::map< ResourceID, Resource* >::iterator iterRes = m_LoadedResources.begin();iterRes != m_LoadedResources.end();++iterRes)
iterRes->second->ReleaseSubResources();
// Free the resources
for( std::map< ResourceID, Resource* >::iterator iterRes = m_LoadedResources.begin();iterRes != m_LoadedResources.end();++iterRes)
{
Resource* pRes = iterRes->second;
//TCASSERT(pRes->GetRefCount() == 0);
delete pRes;
}
m_LoadedResources.clear();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::FindResources() Private
///
/// Search the local directory for resource data files and enumerate the resources.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void ResourceMgr::FindResources()
{
// Create the search string
std::wstring sSearchPath = ApplicationBase::GetResourcePath();
std::list<std::wstring> rdbFileList = TCBase::FindFiles( sSearchPath.c_str(), L"*.rdb" );
// Go through the resource data files
for( std::list<std::wstring>::iterator iterRDBFile = rdbFileList.begin(); iterRDBFile != rdbFileList.end(); ++iterRDBFile )
{
// Skip the GUI and numbers files since they are special cases
if( *iterRDBFile == L"gui.rdb" || *iterRDBFile == L"numbers.rdb" )
continue;
// Load the resource file
LoadResourceDB( (sSearchPath + *iterRDBFile).c_str() );
}
}
void ResourceMgr::ResourceIndexItem::ToFromFile( TCBase::ISerializer& serializer )
{
uint32 temp = resourceID;
serializer.AddData( temp );
resourceID = static_cast<ResourceID>( temp );
temp = resType;
serializer.AddData( temp );
resType = static_cast<EResourceType>( temp );
temp = dataOffset;
serializer.AddData( temp );
dataOffset = temp;
if( serializer.InReadMode() )
TCBase::ReadChars( serializer, szName, RES_IDX_NAME_LEN );
else
TCBase::WriteChars( serializer, szName, RES_IDX_NAME_LEN );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::LoadResourceDB() Private
///
/// \param szResFile The full resource data file path
/// \returns True if the file was loaded successfuly, false otherwise
///
/// Load a resource data file.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
bool ResourceMgr::LoadResourceDB( const wchar_t* szResFile )
{
// Open the file
std::ifstream inFileStream( TCBase::Narrow(szResFile).c_str(), std::ios_base::in | std::ios_base::binary );
if( !inFileStream )
return false;
NetSafeSerializer serializer( &inFileStream );
// TEST Get the file size
/*inFile.seekg( 0, std::ios::end );
int fileLen = inFile.tellg();
inFile.seekg(0,std::ios::beg);*/
// Read in the FourCC key
int32 fourCCKeyVal = 0;
serializer.AddData( fourCCKeyVal );
//inFile.read( (char*)&fourCCKeyVal, sizeof(fourCCKeyVal) );
FourCC fileFourCC( fourCCKeyVal );
// Ensure the key is correct
if( fileFourCC != ResourceMgr::FOURCCKEY_RESDB )
{
// Close the file and bail
std::wstring sMsg = L"The file \"";
sMsg += szResFile;
sMsg += L"\" does not contain the resource data FourCC indentifier.";
MsgLogger::Get().Output( sMsg );
inFileStream.close();
return false;
}
// Read in the version
uint32 fileVer = 1;
serializer.AddData( fileVer );
//inFile.read( (char*)&fileVer, sizeof(fileVer) );
// Read in the number of resources
uint32 numResources = 0;
serializer.AddData( numResources );
//inFile.read( (char*)&numResources, sizeof(numResources) );
// Ensure there are not too many resources
if( numResources > ResourceMgr::MAX_RES_PER_DB )
{
// Close the file and bail
inFileStream.close();
MsgLogger::Get().Output( MsgLogger::MI_Error, L"This resource data file contains too many resources. It supposedly contains %d.", numResources );
return false;
}
// If the resource contains no resources then we are done
if( numResources == 0 )
{
inFileStream.close();
return false;
}
// Ensure there is enough data left in the file to read
uint32 fileSize = serializer.GetInputLength();
// Read in the resource index entries
ResourceIndexItem* pResIndexEntries = new ResourceIndexItem[ numResources ];
for( uint32 curResInfoIndex = 0; curResInfoIndex < numResources; ++curResInfoIndex )
pResIndexEntries[curResInfoIndex].ToFromFile( serializer );
// We are done reading the manifest data so we can close the file
inFileStream.close();
// Do a quick sanity check to ensure the last resource references a valid position in the file
ResourceIndexItem& lastEntry = pResIndexEntries[ numResources - 1 ];
if( lastEntry.dataOffset > fileSize )
{
// Close the file and bail
std::wostringstream sMsg;
sMsg << L"The file \"" << szResFile << L"\" is not a valid resource data file.";
MsgLogger::Get().Output( sMsg.str() );
return false;
}
// Store the data file name and index
int32 newDataFileIndex = (int32)m_ResourceDataFiles.size();
m_ResourceDataFiles.push_back( std::wstring(szResFile) );
// Get the max resource ID
uint32 curMaxResID = pResIndexEntries[0].resourceID;
for( uint32 resIndex = 1; resIndex < numResources; ++resIndex )
{
if( pResIndexEntries[resIndex].resourceID > curMaxResID )
curMaxResID = pResIndexEntries[resIndex].resourceID;
}
// Resize the array if needed
int maxResIDArraySizeNeeded = (curMaxResID - ResourceMgr::STARTING_RES_ID) + 1;
if( maxResIDArraySizeNeeded > (int)m_KnownResources.size() )
{
KnownResourceItem nullItem;
nullItem.dataFileIndex = -1;
nullItem.indexData.resourceID = 0;
m_KnownResources.resize( maxResIDArraySizeNeeded, nullItem );
}
// Add the resource index entries to the known resources list
for( uint32 resIndex = 0; resIndex < numResources; ++resIndex )
{
ResourceIndexItem& curEntry = pResIndexEntries[ resIndex ];
// If there is a resource already with this resource ID
int resArrayIndex = curEntry.resourceID - ResourceMgr::STARTING_RES_ID;
if( m_KnownResources[ resArrayIndex ].dataFileIndex != -1 )
{
std::wostringstream outStr;
outStr << L"The file \"" << szResFile << L"\" is trying to add a resource with the ID " << curEntry.resourceID << L" named " << curEntry.szName << L", but that resource ID is already in the known resource list with the name " << m_KnownResources[ resArrayIndex ].indexData.szName << L" so it will be skipped.";
MsgLogger::Get().Output( outStr.str() );
continue;
}
// Store the resource info
KnownResourceItem newItem;
newItem.indexData = curEntry;
newItem.dataFileIndex = newDataFileIndex;
m_KnownResources[ resArrayIndex ] = newItem;
}
// Free the index data
delete [] pResIndexEntries;
// Return success
return true;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::HookupCreateFunc() Public
///
/// \param resType The type of resource
/// \param pFunc The creation function for the resource type
/// \param retainMem Defaults to false. Indicates that the resource will manage its own memory
/// rather than be released after load.
///
/// Add a resource creation function.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void ResourceMgr::HookupCreateFunc( uint32 resType, CreateFunc* pFunc, bool retainMem )
{
// Fill in the creation structure
ResCreateData createData;
createData.pCreateFunc = pFunc;
createData.retainMemory = retainMem;
// If the type already has a definition then overwrite the entry
ResCreateMap::iterator iterEntry = m_ResCreateFuncs.find( resType );
if( iterEntry != m_ResCreateFuncs.end() )
iterEntry->second = createData;
// Else just store the data
else
m_ResCreateFuncs.insert( ResCreateMap::value_type( resType, createData ) );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::CreateResource() Private
///
/// \param resType The type of resource we are creating
/// \param resID The ID of the resource being loaded
/// \param dataBlock The block of memory representing the resource being loaded
/// \returns A pointer to the resource being loaded, false otherwise
///
/// Create a resource.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
Resource* ResourceMgr::CreateResource( EResourceType resType, ResourceID resID, DataBlock* pDataBlock, bool* pResRefsDataBlock ) const
{
if( pResRefsDataBlock )
*pResRefsDataBlock = false;
// Get the create function based on the type
ResCreateMap::const_iterator iterResCreate = m_ResCreateFuncs.find( resType );
if( iterResCreate == m_ResCreateFuncs.end() )
return 0;
// Create the resource
ResCreateData createData = iterResCreate->second;
Resource* pRetRes = createData.pCreateFunc( resID, pDataBlock );
// Mark the flag notifying if the memory block can be freed
if( createData.retainMemory && pResRefsDataBlock )
*pResRefsDataBlock = true;
if( !pRetRes )
{
// The type is unknown so return NULL
std::wostringstream outStr;
outStr << L"Failed to create resource with ID " << resID << L" due to unhandled type.";
MsgLogger::Get().Output( outStr.str() );
return NULL;
}
return pRetRes;
}
RefSpriteHndl ResourceMgr::GetRefSprite( ResourceID resID )
{
Resource* pRes = GetResource( resID );
if( pRes && pRes->GetResType() != RT_Sprite )
return RefSpriteHndl( NULL );
return RefSpriteHndl( (RefSprite*)pRes );
}
TCImageHndl ResourceMgr::GetTCImage( ResourceID resID )
{
Resource* pRes = GetResource( resID );
if( pRes && pRes->GetResType() != RT_Image )
return TCImageHndl( NULL );
return TCImageHndl( (TCImage*)pRes );
}
TCFontHndl ResourceMgr::GetTCFont( ResourceID resID )
{
Resource* pRes = GetResource( resID );
if( pRes && pRes->GetResType() != RT_Font )
return TCFontHndl( NULL );
return TCFontHndl( (TCFont*)pRes );
}
AudioSampleHndl ResourceMgr::GetAudioSample( ResourceID resID )
{
Resource* pRes = GetResource( resID );
if( pRes && pRes->GetResType() != RT_Sound )
return AudioSampleHndl( NULL );
return AudioSampleHndl( (AudioSample*)pRes );
}
/// Retrieve a music stream, loading if necessary
MusicStreamHndl ResourceMgr::GetMusicStream( ResourceID resID )
{
Resource* pRes = GetResource( resID );
if( pRes && pRes->GetResType() != RT_Music )
return MusicStreamHndl( NULL );
return MusicStreamHndl( (MusicStream*)pRes );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::ReleaseResource() Public
///
/// \param resID The ID of the resource to release, if there are any references to the resource
/// then the resource will not be released
///
/// Free the memory associated with a loaded resource
///
///////////////////////////////////////////////////////////////////////////////////////////////////
bool ResourceMgr::ReleaseResource( ResourceID resID )
{
if( m_LoadedResources.find( resID ) == m_LoadedResources.end() )
return false;
return false;
}
/// Get all of the loaded images
std::list< TCImage* > ResourceMgr::GetAllTCImages()
{
std::list< TCImage* > retList;
for( LoadedResMap::iterator iterRes = m_LoadedResources.begin(); iterRes != m_LoadedResources.end(); ++iterRes )
{
// Only use images
Resource* pRes = iterRes->second;
if( pRes->GetResType() != RT_Image )
continue;
retList.push_back( reinterpret_cast<TCImage*>( pRes ) );
}
return retList;
}
void ResourceMgr::ReloadImage( TCImage* pImage, bool isRecreate )
{
// Determine if the resource ID is known
KnownResVector::size_type resIndex = ResIDToIndex( pImage->GetResID() );
// Get the index item
const KnownResourceItem& resItem = m_KnownResources[ resIndex ];
// Get the data file
const std::wstring& sDataFile = m_ResourceDataFiles[ resItem.dataFileIndex ];
// Open the data file
std::ifstream inFile( TCBase::Narrow( sDataFile ).c_str(), std::ios_base::in | std::ios_base::binary );
if( !inFile )
return;
NetSafeSerializer serializer( &inFile );
// Get to the offset
serializer.Seek( resItem.indexData.dataOffset );
// Read in the data size
uint32 dataSize = 0;
serializer.AddData( dataSize );
// Allocate memory for the data
uint8* pData = new uint8[ dataSize ];
if( !pData )
{
MSG_LOGGER_OUT( MsgLogger::MI_Error, L"Failed to allocate memory for reloading image with res ID %u", pImage->GetResID() );
inFile.close();
return;
}
// Read in the data
serializer.AddRawData( pData, dataSize );
NetSafeDataBlock resDataBlock( pData, dataSize );
// We read the data we need so we can close the file
inFile.close();
// Parse the file data into a resource
#ifndef TOOLS
if( isRecreate )
g_pGraphicsMgr->RecreateImageData( pImage, &resDataBlock );
else
g_pGraphicsMgr->ReloadImageData( pImage, &resDataBlock );
#else
// Prevent the warning for unreferenced parameter
( isRecreate );
#endif
// Free the data
delete [] pData;
}
// Reload image data
void ResourceMgr::ReloadImageDataFunc( bool isRecreate )
{
for( LoadedResMap::iterator iterRes = m_LoadedResources.begin(); iterRes != m_LoadedResources.end(); ++iterRes )
{
// Only use images
Resource* pRes = iterRes->second;
if( pRes->GetResType() != RT_Image )
continue;
ReloadImage( reinterpret_cast<TCImage*>( pRes ), isRecreate );
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::ReloadImageResourceData() Public
///
/// Reload all resources of a type.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void ResourceMgr::ReloadImageResourceData()
{
ReloadImageDataFunc( false );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::RecreateImageResources() Public
///
/// Recreate the TCImage resources.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
void ResourceMgr::RecreateImageResources()
{
ReloadImageDataFunc( true );
}
///////////////////////////////////////////////////////////////////////////////////////////////////
//
// ResourceMgr::GetResource() Private
///
/// \param resID The ID of the resource to retrieve
/// \param forceReload True to ensure the resource is reloaded from file, otherwise the currently
/// loaded data is used
/// \returns A pointer to the resource being retrieved or NULL on failure
///
/// Retrieve an already active resource or load a new one.
///
///////////////////////////////////////////////////////////////////////////////////////////////////
Resource* ResourceMgr::GetResource( ResourceID resID, bool forceReload )
{
// Determine if the resource ID is known
std::vector<KnownResourceItem>::size_type resIndex = ResIDToIndex( resID );
if( resIndex >= m_KnownResources.size() )
{
if( resID != 0 )
MsgLogger::Get().Output( MsgLogger::MI_Error, L"Invalid resource ID: %u (It is out of the valid range).", resID );
return NULL;
}
if( m_KnownResources[ resIndex ].dataFileIndex < 0 || (std::vector<KnownResourceItem>::size_type)m_KnownResources[ resIndex ].dataFileIndex >= m_ResourceDataFiles.size() )
{
MsgLogger::Get().Output( MsgLogger::MI_Error, L"Unknown resource ID: %u", resID );
return NULL;
}
// See if the resource is already loaded
if( !forceReload && m_LoadedResources.find( resID ) != m_LoadedResources.end() )
return m_LoadedResources[ resID ];
// Get the index item
const KnownResourceItem& resItem = m_KnownResources[ resIndex ];
// Get the data file
const std::wstring& sDataFile = m_ResourceDataFiles[ resItem.dataFileIndex ];
// Open the data file
std::ifstream inFile( TCBase::Narrow( sDataFile ).c_str(), std::ios_base::in | std::ios_base::binary );
if( !inFile )
return NULL;
NetSafeSerializer serializer( &inFile );
// Get to the offset
serializer.Seek( resItem.indexData.dataOffset );
// Read in the data size
uint32 dataSize = 0;
serializer.AddData( dataSize );
// Allocate memory for the data
uint8* pData = new uint8[ dataSize ];
if( !pData )
{
std::wostringstream outStr;
outStr << L"Failed to load resource with ID " << resID << L" due to insufficient memory.";
MsgLogger::Get().Output( outStr.str() );
inFile.close();
return NULL;
}
// Read in the data
serializer.AddRawData( pData, dataSize );
NetSafeDataBlock resDataBlock( pData, dataSize );
// We read the data we need so we can close the file
inFile.close();
// Parse the file data into a resource
bool resRefsDataBlock = false;
Resource* pRes = CreateResource( resItem.indexData.resType, resID, &resDataBlock, &resRefsDataBlock );
// Free the data if the resource does not need it
if( !resRefsDataBlock )
delete [] pData;
// Only store valid resources
if( pRes )
{
// Store the resource in our list of loaded resources
LoadedResMap::iterator curIter = m_LoadedResources.find( resID );
if( curIter == m_LoadedResources.end() )
m_LoadedResources.insert( std::pair<ResourceID,Resource*>(resID,pRes) );
else
m_LoadedResources[ resID ] = pRes;
// Set the name
pRes->m_sName = resItem.indexData.szName;
}
// Return the resource pointer
return pRes;
} | 31.571429 | 313 | 0.643865 | [
"object",
"vector"
] |
6c2c1cd250c11011ac166bf5df25a6f103623d2b | 4,779 | cpp | C++ | src/geometric_shapes/src/shape_extents.cpp | househear/_ws_moveit2 | ea5c43ddd412ade6b4bebbdb929b6e08b7a5e888 | [
"Apache-2.0"
] | null | null | null | src/geometric_shapes/src/shape_extents.cpp | househear/_ws_moveit2 | ea5c43ddd412ade6b4bebbdb929b6e08b7a5e888 | [
"Apache-2.0"
] | null | null | null | src/geometric_shapes/src/shape_extents.cpp | househear/_ws_moveit2 | ea5c43ddd412ade6b4bebbdb929b6e08b7a5e888 | [
"Apache-2.0"
] | null | null | null | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
#include <geometric_shapes/shape_extents.h>
#include <geometric_shapes/solid_primitive_dims.h>
#include <limits>
void geometric_shapes::getShapeExtents(const shape_msgs::msg::SolidPrimitive& shape_msg, double& x_extent,
double& y_extent, double& z_extent)
{
x_extent = y_extent = z_extent = 0.0;
if (shape_msg.type == shape_msgs::msg::SolidPrimitive::SPHERE)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::solidPrimitiveDimCount<shape_msgs::msg::SolidPrimitive::SPHERE>())
x_extent = y_extent = z_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::SPHERE_RADIUS] * 2.0;
}
else if (shape_msg.type == shape_msgs::msg::SolidPrimitive::BOX)
{
if (shape_msg.dimensions.size() >= geometric_shapes::solidPrimitiveDimCount<shape_msgs::msg::SolidPrimitive::BOX>())
{
x_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::BOX_X];
y_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::BOX_Y];
z_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::BOX_Z];
}
}
else if (shape_msg.type == shape_msgs::msg::SolidPrimitive::CYLINDER)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::solidPrimitiveDimCount<shape_msgs::msg::SolidPrimitive::CYLINDER>())
{
x_extent = y_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::CYLINDER_RADIUS] * 2.0;
z_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::CYLINDER_HEIGHT];
}
}
else if (shape_msg.type == shape_msgs::msg::SolidPrimitive::CONE)
{
if (shape_msg.dimensions.size() >=
geometric_shapes::solidPrimitiveDimCount<shape_msgs::msg::SolidPrimitive::CONE>())
{
x_extent = y_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::CONE_RADIUS] * 2.0;
z_extent = shape_msg.dimensions[shape_msgs::msg::SolidPrimitive::CONE_HEIGHT];
}
}
}
void geometric_shapes::getShapeExtents(const shape_msgs::msg::Mesh& shape_msg, double& x_extent, double& y_extent,
double& z_extent)
{
x_extent = y_extent = z_extent = 0.0;
if (!shape_msg.vertices.empty())
{
double xmin = std::numeric_limits<double>::max(), ymin = std::numeric_limits<double>::max(),
zmin = std::numeric_limits<double>::max();
double xmax = -std::numeric_limits<double>::max(), ymax = -std::numeric_limits<double>::max(),
zmax = -std::numeric_limits<double>::max();
for (const geometry_msgs::msg::Point& vertex : shape_msg.vertices)
{
if (vertex.x > xmax)
xmax = vertex.x;
if (vertex.x < xmin)
xmin = vertex.x;
if (vertex.y > ymax)
ymax = vertex.y;
if (vertex.y < ymin)
ymin = vertex.y;
if (vertex.z > zmax)
zmax = vertex.z;
if (vertex.z < zmin)
zmin = vertex.z;
}
x_extent = xmax - xmin;
y_extent = ymax - ymin;
z_extent = zmax - zmin;
}
}
| 43.844037 | 120 | 0.671061 | [
"mesh"
] |
6c2c8c2db31312b7074a4cc816a4ce3f9fb1a765 | 34,676 | cc | C++ | chromium/media/base/key_systems.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | chromium/media/base/key_systems.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 2 | 2017-03-09T09:00:50.000Z | 2017-09-21T15:48:20.000Z | chromium/media/base/key_systems.cc | wedataintelligence/vivaldi-source | 22a46f2c969f6a0b7ca239a05575d1ea2738768c | [
"BSD-3-Clause"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/key_systems.h"
#include <stddef.h>
#include "base/containers/hash_tables.h"
#include "base/lazy_instance.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/strings/string_util.h"
#include "base/threading/thread_checker.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "media/base/key_system_info.h"
#include "media/base/key_systems_support_uma.h"
#include "media/base/media_client.h"
#include "media/cdm/key_system_names.h"
#include "third_party/widevine/cdm/widevine_cdm_common.h"
namespace media {
const char kClearKeyKeySystem[] = "org.w3.clearkey";
const char kPrefixedClearKeyKeySystem[] = "webkit-org.w3.clearkey";
const char kUnsupportedClearKeyKeySystem[] = "unsupported-org.w3.clearkey";
// These names are used by UMA. Do not change them!
const char kClearKeyKeySystemNameForUMA[] = "ClearKey";
const char kUnknownKeySystemNameForUMA[] = "Unknown";
struct NamedCodec {
const char* name;
EmeCodec type;
};
// Mapping between containers and their codecs.
// Only audio codec can belong to a "audio/*" container. Both audio and video
// codecs can belong to a "video/*" container.
// TODO(sandersd): This definition only makes sense for prefixed EME. Change it
// when prefixed EME is removed. http://crbug.com/249976
static NamedCodec kContainerToCodecMasks[] = {
{"audio/webm", EME_CODEC_WEBM_AUDIO_ALL},
{"video/webm", EME_CODEC_WEBM_ALL},
#if defined(USE_PROPRIETARY_CODECS)
{"audio/mp4", EME_CODEC_MP4_AUDIO_ALL},
{"video/mp4", EME_CODEC_MP4_ALL}
#endif // defined(USE_PROPRIETARY_CODECS)
};
// Mapping between codec names and enum values.
static NamedCodec kCodecStrings[] = {
{"opus", EME_CODEC_WEBM_OPUS},
{"vorbis", EME_CODEC_WEBM_VORBIS},
{"vp8", EME_CODEC_WEBM_VP8},
{"vp8.0", EME_CODEC_WEBM_VP8},
{"vp9", EME_CODEC_WEBM_VP9},
{"vp9.0", EME_CODEC_WEBM_VP9},
#if defined(USE_PROPRIETARY_CODECS)
{"mp4a", EME_CODEC_MP4_AAC},
{"avc1", EME_CODEC_MP4_AVC1},
{"avc3", EME_CODEC_MP4_AVC1}
#endif // defined(USE_PROPRIETARY_CODECS)
};
static EmeRobustness ConvertRobustness(const std::string& robustness) {
if (robustness.empty())
return EmeRobustness::EMPTY;
if (robustness == "SW_SECURE_CRYPTO")
return EmeRobustness::SW_SECURE_CRYPTO;
if (robustness == "SW_SECURE_DECODE")
return EmeRobustness::SW_SECURE_DECODE;
if (robustness == "HW_SECURE_CRYPTO")
return EmeRobustness::HW_SECURE_CRYPTO;
if (robustness == "HW_SECURE_DECODE")
return EmeRobustness::HW_SECURE_DECODE;
if (robustness == "HW_SECURE_ALL")
return EmeRobustness::HW_SECURE_ALL;
return EmeRobustness::INVALID;
}
static void AddClearKey(std::vector<KeySystemInfo>* concrete_key_systems) {
KeySystemInfo info;
info.key_system = kClearKeyKeySystem;
// On Android, Vorbis, VP8, AAC and AVC1 are supported in MediaCodec:
// http://developer.android.com/guide/appendix/media-formats.html
// VP9 support is device dependent.
info.supported_init_data_types =
kInitDataTypeMaskWebM | kInitDataTypeMaskKeyIds;
info.supported_codecs = EME_CODEC_WEBM_ALL;
#if defined(OS_ANDROID)
// Temporarily disable VP9 support for Android.
// TODO(xhwang): Use mime_util.h to query VP9 support on Android.
info.supported_codecs &= ~EME_CODEC_WEBM_VP9;
// Opus is not supported on Android yet. http://crbug.com/318436.
// TODO(sandersd): Check for platform support to set this bit.
info.supported_codecs &= ~EME_CODEC_WEBM_OPUS;
#endif // defined(OS_ANDROID)
#if defined(USE_PROPRIETARY_CODECS)
info.supported_init_data_types |= kInitDataTypeMaskCenc;
info.supported_codecs |= EME_CODEC_MP4_ALL;
#endif // defined(USE_PROPRIETARY_CODECS)
info.max_audio_robustness = EmeRobustness::EMPTY;
info.max_video_robustness = EmeRobustness::EMPTY;
info.persistent_license_support = EmeSessionTypeSupport::NOT_SUPPORTED;
info.persistent_release_message_support =
EmeSessionTypeSupport::NOT_SUPPORTED;
info.persistent_state_support = EmeFeatureSupport::NOT_SUPPORTED;
info.distinctive_identifier_support = EmeFeatureSupport::NOT_SUPPORTED;
info.use_aes_decryptor = true;
concrete_key_systems->push_back(info);
}
// Returns whether the |key_system| is known to Chromium and is thus likely to
// be implemented in an interoperable way.
// True is always returned for a |key_system| that begins with "x-".
//
// As with other web platform features, advertising support for a key system
// implies that it adheres to a defined and interoperable specification.
//
// To ensure interoperability, implementations of a specific |key_system| string
// must conform to a specification for that identifier that defines
// key system-specific behaviors not fully defined by the EME specification.
// That specification should be provided by the owner of the domain that is the
// reverse of the |key_system| string.
// This involves more than calling a library, SDK, or platform API.
// KeySystemsImpl must be populated appropriately, and there will likely be glue
// code to adapt to the API of the library, SDK, or platform API.
//
// Chromium mainline contains this data and glue code for specific key systems,
// which should help ensure interoperability with other implementations using
// these key systems.
//
// If you need to add support for other key systems, ensure that you have
// obtained the specification for how to integrate it with EME, implemented the
// appropriate glue/adapter code, and added all the appropriate data to
// KeySystemsImpl. Only then should you change this function.
static bool IsPotentiallySupportedKeySystem(const std::string& key_system) {
// Known and supported key systems.
if (key_system == kWidevineKeySystem)
return true;
if (key_system == kClearKey)
return true;
// External Clear Key is known and supports suffixes for testing.
if (IsExternalClearKey(key_system))
return true;
// Chromecast defines behaviors for Cast clients within its reverse domain.
const char kChromecastRoot[] = "com.chromecast";
if (IsParentKeySystemOf(kChromecastRoot, key_system))
return true;
// Implementations that do not have a specification or appropriate glue code
// can use the "x-" prefix to avoid conflicting with and advertising support
// for real key system names. Use is discouraged.
const char kExcludedPrefix[] = "x-";
if (key_system.find(kExcludedPrefix, 0, arraysize(kExcludedPrefix) - 1) == 0)
return true;
return false;
}
class KeySystemsImpl : public KeySystems {
public:
static KeySystemsImpl* GetInstance();
void UpdateIfNeeded();
bool IsConcreteSupportedKeySystem(const std::string& key_system) const;
bool PrefixedIsSupportedKeySystemWithMediaMimeType(
const std::string& mime_type,
const std::vector<std::string>& codecs,
const std::string& key_system);
std::string GetKeySystemNameForUMA(const std::string& key_system) const;
bool UseAesDecryptor(const std::string& concrete_key_system) const;
#if defined(ENABLE_PEPPER_CDMS)
std::string GetPepperType(const std::string& concrete_key_system) const;
#endif
void AddContainerMask(const std::string& container, uint32_t mask);
void AddCodecMask(EmeMediaType media_type,
const std::string& codec,
uint32_t mask);
// Implementation of KeySystems interface.
bool IsSupportedKeySystem(const std::string& key_system) const override;
bool IsSupportedInitDataType(const std::string& key_system,
EmeInitDataType init_data_type) const override;
EmeConfigRule GetContentTypeConfigRule(
const std::string& key_system,
EmeMediaType media_type,
const std::string& container_mime_type,
const std::vector<std::string>& codecs) const override;
EmeConfigRule GetRobustnessConfigRule(
const std::string& key_system,
EmeMediaType media_type,
const std::string& requested_robustness) const override;
EmeSessionTypeSupport GetPersistentLicenseSessionSupport(
const std::string& key_system) const override;
EmeSessionTypeSupport GetPersistentReleaseMessageSessionSupport(
const std::string& key_system) const override;
EmeFeatureSupport GetPersistentStateSupport(
const std::string& key_system) const override;
EmeFeatureSupport GetDistinctiveIdentifierSupport(
const std::string& key_system) const override;
private:
KeySystemsImpl();
~KeySystemsImpl() override;
void InitializeUMAInfo();
void UpdateSupportedKeySystems();
void AddConcreteSupportedKeySystems(
const std::vector<KeySystemInfo>& concrete_key_systems);
friend struct base::DefaultLazyInstanceTraits<KeySystemsImpl>;
typedef base::hash_map<std::string, KeySystemInfo> KeySystemInfoMap;
typedef base::hash_map<std::string, std::string> ParentKeySystemMap;
typedef base::hash_map<std::string, SupportedCodecs> ContainerCodecsMap;
typedef base::hash_map<std::string, EmeCodec> CodecsMap;
typedef base::hash_map<std::string, EmeInitDataType> InitDataTypesMap;
typedef base::hash_map<std::string, std::string> KeySystemNameForUMAMap;
// TODO(sandersd): Separate container enum from codec mask value.
// http://crbug.com/417440
SupportedCodecs GetCodecMaskForContainer(
const std::string& container) const;
EmeCodec GetCodecForString(const std::string& codec) const;
const std::string& PrefixedGetConcreteKeySystemNameFor(
const std::string& key_system) const;
// Returns whether a |container| type is supported by checking
// |key_system_supported_codecs|.
// TODO(xhwang): Update this to actually check initDataType support.
bool IsSupportedContainer(const std::string& container,
SupportedCodecs key_system_supported_codecs) const;
// Returns true if all |codecs| are supported in |container| by checking
// |key_system_supported_codecs|.
bool IsSupportedContainerAndCodecs(
const std::string& container,
const std::vector<std::string>& codecs,
SupportedCodecs key_system_supported_codecs) const;
// Map from key system string to capabilities.
KeySystemInfoMap concrete_key_system_map_;
// Map from parent key system to the concrete key system that should be used
// to represent its capabilities.
ParentKeySystemMap parent_key_system_map_;
KeySystemsSupportUMA key_systems_support_uma_;
ContainerCodecsMap container_to_codec_mask_map_;
CodecsMap codec_string_map_;
KeySystemNameForUMAMap key_system_name_for_uma_map_;
SupportedCodecs audio_codec_mask_;
SupportedCodecs video_codec_mask_;
// Makes sure all methods are called from the same thread.
base::ThreadChecker thread_checker_;
DISALLOW_COPY_AND_ASSIGN(KeySystemsImpl);
};
static base::LazyInstance<KeySystemsImpl>::Leaky g_key_systems =
LAZY_INSTANCE_INITIALIZER;
KeySystemsImpl* KeySystemsImpl::GetInstance() {
KeySystemsImpl* key_systems = g_key_systems.Pointer();
key_systems->UpdateIfNeeded();
return key_systems;
}
// Because we use a LazyInstance, the key systems info must be populated when
// the instance is lazily initiated.
KeySystemsImpl::KeySystemsImpl() :
audio_codec_mask_(EME_CODEC_AUDIO_ALL),
video_codec_mask_(EME_CODEC_VIDEO_ALL) {
for (size_t i = 0; i < arraysize(kContainerToCodecMasks); ++i) {
const std::string& name = kContainerToCodecMasks[i].name;
DCHECK(!container_to_codec_mask_map_.count(name));
container_to_codec_mask_map_[name] = kContainerToCodecMasks[i].type;
}
for (size_t i = 0; i < arraysize(kCodecStrings); ++i) {
const std::string& name = kCodecStrings[i].name;
DCHECK(!codec_string_map_.count(name));
codec_string_map_[name] = kCodecStrings[i].type;
}
InitializeUMAInfo();
// Always update supported key systems during construction.
UpdateSupportedKeySystems();
}
KeySystemsImpl::~KeySystemsImpl() {
}
SupportedCodecs KeySystemsImpl::GetCodecMaskForContainer(
const std::string& container) const {
ContainerCodecsMap::const_iterator iter =
container_to_codec_mask_map_.find(container);
if (iter != container_to_codec_mask_map_.end())
return iter->second;
return EME_CODEC_NONE;
}
EmeCodec KeySystemsImpl::GetCodecForString(const std::string& codec) const {
CodecsMap::const_iterator iter = codec_string_map_.find(codec);
if (iter != codec_string_map_.end())
return iter->second;
return EME_CODEC_NONE;
}
const std::string& KeySystemsImpl::PrefixedGetConcreteKeySystemNameFor(
const std::string& key_system) const {
ParentKeySystemMap::const_iterator iter =
parent_key_system_map_.find(key_system);
if (iter != parent_key_system_map_.end())
return iter->second;
return key_system;
}
void KeySystemsImpl::InitializeUMAInfo() {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(key_system_name_for_uma_map_.empty());
std::vector<KeySystemInfoForUMA> key_systems_info_for_uma;
if (GetMediaClient())
GetMediaClient()->AddKeySystemsInfoForUMA(&key_systems_info_for_uma);
for (const KeySystemInfoForUMA& info : key_systems_info_for_uma) {
key_system_name_for_uma_map_[info.key_system] =
info.key_system_name_for_uma;
if (info.reports_key_system_support_to_uma)
key_systems_support_uma_.AddKeySystemToReport(info.key_system);
}
// Clear Key is always supported.
key_system_name_for_uma_map_[kClearKeyKeySystem] =
kClearKeyKeySystemNameForUMA;
}
void KeySystemsImpl::UpdateIfNeeded() {
if (GetMediaClient() && GetMediaClient()->IsKeySystemsUpdateNeeded())
UpdateSupportedKeySystems();
}
void KeySystemsImpl::UpdateSupportedKeySystems() {
DCHECK(thread_checker_.CalledOnValidThread());
concrete_key_system_map_.clear();
parent_key_system_map_.clear();
// Build KeySystemInfo.
std::vector<KeySystemInfo> key_systems_info;
// Add key systems supported by the MediaClient implementation.
if (GetMediaClient())
GetMediaClient()->AddSupportedKeySystems(&key_systems_info);
// Clear Key is always supported.
AddClearKey(&key_systems_info);
AddConcreteSupportedKeySystems(key_systems_info);
}
void KeySystemsImpl::AddConcreteSupportedKeySystems(
const std::vector<KeySystemInfo>& concrete_key_systems) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(concrete_key_system_map_.empty());
DCHECK(parent_key_system_map_.empty());
for (const KeySystemInfo& info : concrete_key_systems) {
DCHECK(!info.key_system.empty());
DCHECK(info.max_audio_robustness != EmeRobustness::INVALID);
DCHECK(info.max_video_robustness != EmeRobustness::INVALID);
DCHECK(info.persistent_license_support != EmeSessionTypeSupport::INVALID);
DCHECK(info.persistent_release_message_support !=
EmeSessionTypeSupport::INVALID);
DCHECK(info.persistent_state_support != EmeFeatureSupport::INVALID);
DCHECK(info.distinctive_identifier_support != EmeFeatureSupport::INVALID);
// Supporting persistent state is a prerequsite for supporting persistent
// sessions.
if (info.persistent_state_support == EmeFeatureSupport::NOT_SUPPORTED) {
DCHECK(info.persistent_license_support ==
EmeSessionTypeSupport::NOT_SUPPORTED);
DCHECK(info.persistent_release_message_support ==
EmeSessionTypeSupport::NOT_SUPPORTED);
}
// persistent-release-message sessions are not currently supported.
// http://crbug.com/448888
DCHECK(info.persistent_release_message_support ==
EmeSessionTypeSupport::NOT_SUPPORTED);
// If distinctive identifiers are not supported, then no other features can
// require them.
if (info.distinctive_identifier_support ==
EmeFeatureSupport::NOT_SUPPORTED) {
DCHECK(info.persistent_license_support !=
EmeSessionTypeSupport::SUPPORTED_WITH_IDENTIFIER);
DCHECK(info.persistent_release_message_support !=
EmeSessionTypeSupport::SUPPORTED_WITH_IDENTIFIER);
}
// Distinctive identifiers and persistent state can only be reliably blocked
// (and therefore be safely configurable) for Pepper-hosted key systems. For
// other platforms, (except for the AES decryptor) assume that the CDM can
// and will do anything.
bool can_block = info.use_aes_decryptor;
#if defined(ENABLE_PEPPER_CDMS)
DCHECK_EQ(info.use_aes_decryptor, info.pepper_type.empty());
if (!info.pepper_type.empty())
can_block = true;
#endif
if (!can_block) {
DCHECK(info.distinctive_identifier_support ==
EmeFeatureSupport::ALWAYS_ENABLED);
DCHECK(info.persistent_state_support ==
EmeFeatureSupport::ALWAYS_ENABLED);
}
DCHECK(!IsConcreteSupportedKeySystem(info.key_system))
<< "Key system '" << info.key_system << "' already registered";
DCHECK(!parent_key_system_map_.count(info.key_system))
<< "'" << info.key_system << "' is already registered as a parent";
concrete_key_system_map_[info.key_system] = info;
if (!info.parent_key_system.empty()) {
DCHECK(!IsConcreteSupportedKeySystem(info.parent_key_system))
<< "Parent '" << info.parent_key_system << "' "
<< "already registered concrete";
DCHECK(!parent_key_system_map_.count(info.parent_key_system))
<< "Parent '" << info.parent_key_system << "' already registered";
parent_key_system_map_[info.parent_key_system] = info.key_system;
}
}
}
bool KeySystemsImpl::IsConcreteSupportedKeySystem(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
return concrete_key_system_map_.count(key_system) != 0;
}
bool KeySystemsImpl::IsSupportedContainer(
const std::string& container,
SupportedCodecs key_system_supported_codecs) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!container.empty());
// When checking container support for EME, "audio/foo" should be treated the
// same as "video/foo". Convert the |container| to achieve this.
// TODO(xhwang): Replace this with real checks against supported initDataTypes
// combined with supported demuxers.
std::string canonical_container = container;
if (container.find("audio/") == 0)
canonical_container.replace(0, 6, "video/");
// A container is supported iif at least one codec in that container is
// supported.
SupportedCodecs supported_codecs =
GetCodecMaskForContainer(canonical_container);
return (supported_codecs & key_system_supported_codecs) != 0;
}
bool KeySystemsImpl::IsSupportedContainerAndCodecs(
const std::string& container,
const std::vector<std::string>& codecs,
SupportedCodecs key_system_supported_codecs) const {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!container.empty());
DCHECK(!codecs.empty());
DCHECK(IsSupportedContainer(container, key_system_supported_codecs));
SupportedCodecs container_supported_codecs =
GetCodecMaskForContainer(container);
for (size_t i = 0; i < codecs.size(); ++i) {
if (codecs[i].empty())
continue;
EmeCodec codec = GetCodecForString(codecs[i]);
// Unsupported codec.
if (!(codec & key_system_supported_codecs))
return false;
// Unsupported codec/container combination, e.g. "video/webm" and "avc1".
if (!(codec & container_supported_codecs))
return false;
}
return true;
}
bool KeySystemsImpl::IsSupportedInitDataType(
const std::string& key_system,
EmeInitDataType init_data_type) const {
DCHECK(thread_checker_.CalledOnValidThread());
// Locate |key_system|. Only concrete key systems are supported in unprefixed.
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return false;
}
// Check |init_data_type|.
InitDataTypeMask available_init_data_types =
key_system_iter->second.supported_init_data_types;
switch (init_data_type) {
case EmeInitDataType::UNKNOWN:
return false;
case EmeInitDataType::WEBM:
return (available_init_data_types & kInitDataTypeMaskWebM) != 0;
case EmeInitDataType::CENC:
return (available_init_data_types & kInitDataTypeMaskCenc) != 0;
case EmeInitDataType::KEYIDS:
return (available_init_data_types & kInitDataTypeMaskKeyIds) != 0;
}
NOTREACHED();
return false;
}
bool KeySystemsImpl::PrefixedIsSupportedKeySystemWithMediaMimeType(
const std::string& mime_type,
const std::vector<std::string>& codecs,
const std::string& key_system) {
DCHECK(thread_checker_.CalledOnValidThread());
const std::string& concrete_key_system =
PrefixedGetConcreteKeySystemNameFor(key_system);
bool has_type = !mime_type.empty();
key_systems_support_uma_.ReportKeySystemQuery(key_system, has_type);
// Check key system support.
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(concrete_key_system);
if (key_system_iter == concrete_key_system_map_.end())
return false;
key_systems_support_uma_.ReportKeySystemSupport(key_system, false);
if (!has_type) {
DCHECK(codecs.empty());
return true;
}
SupportedCodecs key_system_supported_codecs =
key_system_iter->second.supported_codecs;
if (!IsSupportedContainer(mime_type, key_system_supported_codecs))
return false;
if (!codecs.empty() &&
!IsSupportedContainerAndCodecs(
mime_type, codecs, key_system_supported_codecs)) {
return false;
}
key_systems_support_uma_.ReportKeySystemSupport(key_system, true);
return true;
}
std::string KeySystemsImpl::GetKeySystemNameForUMA(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemNameForUMAMap::const_iterator iter =
key_system_name_for_uma_map_.find(key_system);
if (iter == key_system_name_for_uma_map_.end())
return kUnknownKeySystemNameForUMA;
return iter->second;
}
bool KeySystemsImpl::UseAesDecryptor(
const std::string& concrete_key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(concrete_key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
DLOG(ERROR) << concrete_key_system << " is not a known concrete system";
return false;
}
return key_system_iter->second.use_aes_decryptor;
}
#if defined(ENABLE_PEPPER_CDMS)
std::string KeySystemsImpl::GetPepperType(
const std::string& concrete_key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(concrete_key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
DLOG(FATAL) << concrete_key_system << " is not a known concrete system";
return std::string();
}
const std::string& type = key_system_iter->second.pepper_type;
DLOG_IF(FATAL, type.empty()) << concrete_key_system << " is not Pepper-based";
return type;
}
#endif
void KeySystemsImpl::AddContainerMask(const std::string& container,
uint32_t mask) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!container_to_codec_mask_map_.count(container));
container_to_codec_mask_map_[container] = static_cast<EmeCodec>(mask);
}
void KeySystemsImpl::AddCodecMask(EmeMediaType media_type,
const std::string& codec,
uint32_t mask) {
DCHECK(thread_checker_.CalledOnValidThread());
DCHECK(!codec_string_map_.count(codec));
codec_string_map_[codec] = static_cast<EmeCodec>(mask);
if (media_type == EmeMediaType::AUDIO) {
audio_codec_mask_ |= mask;
} else {
video_codec_mask_ |= mask;
}
}
bool KeySystemsImpl::IsSupportedKeySystem(const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
if (!IsConcreteSupportedKeySystem(key_system))
return false;
// TODO(ddorwin): Move this to where we add key systems when prefixed EME is
// removed (crbug.com/249976).
if (!IsPotentiallySupportedKeySystem(key_system)) {
// If you encounter this path, see the comments for the above function.
DLOG(ERROR) << "Unrecognized key system " << key_system
<< ". See code comments.";
return false;
}
return true;
}
EmeConfigRule KeySystemsImpl::GetContentTypeConfigRule(
const std::string& key_system,
EmeMediaType media_type,
const std::string& container_mime_type,
const std::vector<std::string>& codecs) const {
DCHECK(thread_checker_.CalledOnValidThread());
// Make sure the container matches |media_type|.
SupportedCodecs media_type_codec_mask = EME_CODEC_NONE;
switch (media_type) {
case EmeMediaType::AUDIO:
if (!base::StartsWith(container_mime_type, "audio/",
base::CompareCase::SENSITIVE))
return EmeConfigRule::NOT_SUPPORTED;
media_type_codec_mask = audio_codec_mask_;
break;
case EmeMediaType::VIDEO:
if (!base::StartsWith(container_mime_type, "video/",
base::CompareCase::SENSITIVE))
return EmeConfigRule::NOT_SUPPORTED;
media_type_codec_mask = video_codec_mask_;
break;
}
// Look up the key system's supported codecs.
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeConfigRule::NOT_SUPPORTED;
}
SupportedCodecs key_system_codec_mask =
key_system_iter->second.supported_codecs;
#if defined(OS_ANDROID)
SupportedCodecs key_system_secure_codec_mask =
key_system_iter->second.supported_secure_codecs;
#endif // defined(OS_ANDROID)
// Check that the container is supported by the key system. (This check is
// necessary because |codecs| may be empty.)
SupportedCodecs container_codec_mask =
GetCodecMaskForContainer(container_mime_type) & media_type_codec_mask;
if ((key_system_codec_mask & container_codec_mask) == 0)
return EmeConfigRule::NOT_SUPPORTED;
// Check that the codecs are supported by the key system and container.
EmeConfigRule support = EmeConfigRule::SUPPORTED;
for (size_t i = 0; i < codecs.size(); i++) {
SupportedCodecs codec = GetCodecForString(codecs[i]);
if ((codec & key_system_codec_mask & container_codec_mask) == 0)
return EmeConfigRule::NOT_SUPPORTED;
#if defined(OS_ANDROID)
// Check whether the codec supports a hardware-secure mode. The goal is to
// prevent mixing of non-hardware-secure codecs with hardware-secure codecs,
// since the mode is fixed at CDM creation.
//
// Because the check for regular codec support is early-exit, we don't have
// to consider codecs that are only supported in hardware-secure mode. We
// could do so, and make use of HW_SECURE_CODECS_REQUIRED, if it turns out
// that hardware-secure-only codecs actually exist and are useful.
if ((codec & key_system_secure_codec_mask) == 0)
support = EmeConfigRule::HW_SECURE_CODECS_NOT_ALLOWED;
#endif // defined(OS_ANDROID)
}
return support;
}
EmeConfigRule KeySystemsImpl::GetRobustnessConfigRule(
const std::string& key_system,
EmeMediaType media_type,
const std::string& requested_robustness) const {
DCHECK(thread_checker_.CalledOnValidThread());
EmeRobustness robustness = ConvertRobustness(requested_robustness);
if (robustness == EmeRobustness::INVALID)
return EmeConfigRule::NOT_SUPPORTED;
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeConfigRule::NOT_SUPPORTED;
}
EmeRobustness max_robustness = EmeRobustness::INVALID;
switch (media_type) {
case EmeMediaType::AUDIO:
max_robustness = key_system_iter->second.max_audio_robustness;
break;
case EmeMediaType::VIDEO:
max_robustness = key_system_iter->second.max_video_robustness;
break;
}
// We can compare robustness levels whenever they are not HW_SECURE_CRYPTO
// and SW_SECURE_DECODE in some order. If they are exactly those two then the
// robustness requirement is not supported.
if ((max_robustness == EmeRobustness::HW_SECURE_CRYPTO &&
robustness == EmeRobustness::SW_SECURE_DECODE) ||
(max_robustness == EmeRobustness::SW_SECURE_DECODE &&
robustness == EmeRobustness::HW_SECURE_CRYPTO) ||
robustness > max_robustness) {
return EmeConfigRule::NOT_SUPPORTED;
}
#if defined(OS_CHROMEOS)
if (key_system == kWidevineKeySystem) {
// TODO(ddorwin): Remove this once we have confirmed it is not necessary.
// See https://crbug.com/482277
if (robustness == EmeRobustness::EMPTY)
return EmeConfigRule::SUPPORTED;
// Hardware security requires remote attestation.
if (robustness >= EmeRobustness::HW_SECURE_CRYPTO)
return EmeConfigRule::IDENTIFIER_REQUIRED;
// For video, recommend remote attestation if HW_SECURE_ALL is available,
// because it enables hardware accelerated decoding.
// TODO(sandersd): Only do this when hardware accelerated decoding is
// available for the requested codecs.
if (media_type == EmeMediaType::VIDEO &&
max_robustness == EmeRobustness::HW_SECURE_ALL) {
return EmeConfigRule::IDENTIFIER_RECOMMENDED;
}
}
#elif defined(OS_ANDROID)
// Require hardware secure codecs for Widevine when SW_SECURE_DECODE or above
// is specified, or for all other key systems (excluding Clear Key).
if ((key_system == kWidevineKeySystem &&
robustness >= EmeRobustness::SW_SECURE_DECODE) ||
!IsClearKey(key_system)) {
return EmeConfigRule::HW_SECURE_CODECS_REQUIRED;
}
#endif // defined(OS_CHROMEOS)
return EmeConfigRule::SUPPORTED;
}
EmeSessionTypeSupport KeySystemsImpl::GetPersistentLicenseSessionSupport(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeSessionTypeSupport::INVALID;
}
return key_system_iter->second.persistent_license_support;
}
EmeSessionTypeSupport KeySystemsImpl::GetPersistentReleaseMessageSessionSupport(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeSessionTypeSupport::INVALID;
}
return key_system_iter->second.persistent_release_message_support;
}
EmeFeatureSupport KeySystemsImpl::GetPersistentStateSupport(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeFeatureSupport::INVALID;
}
return key_system_iter->second.persistent_state_support;
}
EmeFeatureSupport KeySystemsImpl::GetDistinctiveIdentifierSupport(
const std::string& key_system) const {
DCHECK(thread_checker_.CalledOnValidThread());
KeySystemInfoMap::const_iterator key_system_iter =
concrete_key_system_map_.find(key_system);
if (key_system_iter == concrete_key_system_map_.end()) {
NOTREACHED();
return EmeFeatureSupport::INVALID;
}
return key_system_iter->second.distinctive_identifier_support;
}
KeySystems* KeySystems::GetInstance() {
return KeySystemsImpl::GetInstance();
}
//------------------------------------------------------------------------------
std::string GetUnprefixedKeySystemName(const std::string& key_system) {
if (key_system == kClearKeyKeySystem)
return kUnsupportedClearKeyKeySystem;
if (key_system == kPrefixedClearKeyKeySystem)
return kClearKeyKeySystem;
return key_system;
}
std::string GetPrefixedKeySystemName(const std::string& key_system) {
DCHECK_NE(key_system, kPrefixedClearKeyKeySystem);
if (key_system == kClearKeyKeySystem)
return kPrefixedClearKeyKeySystem;
return key_system;
}
bool PrefixedIsSupportedConcreteKeySystem(const std::string& key_system) {
return KeySystemsImpl::GetInstance()->IsConcreteSupportedKeySystem(
key_system);
}
bool IsSupportedKeySystemWithInitDataType(const std::string& key_system,
EmeInitDataType init_data_type) {
return KeySystemsImpl::GetInstance()->IsSupportedInitDataType(key_system,
init_data_type);
}
bool PrefixedIsSupportedKeySystemWithMediaMimeType(
const std::string& mime_type,
const std::vector<std::string>& codecs,
const std::string& key_system) {
return KeySystemsImpl::GetInstance()
->PrefixedIsSupportedKeySystemWithMediaMimeType(mime_type, codecs,
key_system);
}
std::string GetKeySystemNameForUMA(const std::string& key_system) {
return KeySystemsImpl::GetInstance()->GetKeySystemNameForUMA(key_system);
}
bool CanUseAesDecryptor(const std::string& concrete_key_system) {
return KeySystemsImpl::GetInstance()->UseAesDecryptor(concrete_key_system);
}
#if defined(ENABLE_PEPPER_CDMS)
std::string GetPepperType(const std::string& concrete_key_system) {
return KeySystemsImpl::GetInstance()->GetPepperType(concrete_key_system);
}
#endif
// These two functions are for testing purpose only. The declaration in the
// header file is guarded by "#if defined(UNIT_TEST)" so that they can be used
// by tests but not non-test code. However, this .cc file is compiled as part of
// "media" where "UNIT_TEST" is not defined. So we need to specify
// "MEDIA_EXPORT" here again so that they are visible to tests.
MEDIA_EXPORT void AddContainerMask(const std::string& container,
uint32_t mask) {
KeySystemsImpl::GetInstance()->AddContainerMask(container, mask);
}
MEDIA_EXPORT void AddCodecMask(EmeMediaType media_type,
const std::string& codec,
uint32_t mask) {
KeySystemsImpl::GetInstance()->AddCodecMask(media_type, codec, mask);
}
} // namespace media
| 36.578059 | 80 | 0.743194 | [
"vector"
] |
6c2f74c9b8fa547c1adc776467351ca5162e4f56 | 11,068 | cpp | C++ | LibGraphics/Controllers/Wm4IKController.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 3 | 2021-08-02T04:03:03.000Z | 2022-01-04T07:31:20.000Z | LibGraphics/Controllers/Wm4IKController.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | null | null | null | LibGraphics/Controllers/Wm4IKController.cpp | wjezxujian/WildMagic4 | 249a17f8c447cf57c6283408e01009039810206a | [
"BSL-1.0"
] | 5 | 2019-10-13T02:44:19.000Z | 2021-08-02T04:03:10.000Z | // Geometric Tools, Inc.
// http://www.geometrictools.com
// Copyright (c) 1998-2006. All Rights Reserved
//
// The Wild Magic Version 4 Restricted Libraries source code is supplied
// under the terms of the license agreement
// http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf
// and may not be copied or disclosed except in accordance with the terms
// of that agreement.
#include "Wm4GraphicsPCH.h"
#include "Wm4IKController.h"
using namespace Wm4;
WM4_IMPLEMENT_RTTI(Wm4,IKController,Controller);
WM4_IMPLEMENT_STREAM(IKController);
//----------------------------------------------------------------------------
IKController::IKController (int iJointQuantity, IKJointPtr* aspkJoint,
int iGoalQuantity, IKGoalPtr* aspkGoal)
{
#ifdef _DEBUG
assert(iJointQuantity > 0 && aspkJoint);
assert(iGoalQuantity > 0 && aspkGoal);
int i;
for (i = 0; i < iJointQuantity; i++)
{
assert(aspkJoint[i]);
}
for (i = 0; i < iGoalQuantity; i++)
{
assert(aspkGoal[i]);
}
#endif
m_iJointQuantity = iJointQuantity;
m_aspkJoint = aspkJoint;
m_iGoalQuantity = iGoalQuantity;
m_aspkGoal = aspkGoal;
Iterations = 128;
OrderEndToRoot = true;
}
//----------------------------------------------------------------------------
IKController::IKController ()
{
m_iJointQuantity = 0;
m_aspkJoint = 0;
m_iGoalQuantity = 0;
m_aspkGoal = 0;
Iterations = 0;
OrderEndToRoot = false;
}
//----------------------------------------------------------------------------
IKController::~IKController ()
{
WM4_DELETE[] m_aspkJoint;
WM4_DELETE[] m_aspkGoal;
}
//----------------------------------------------------------------------------
bool IKController::Update (double dAppTime)
{
if (!Controller::Update(dAppTime))
{
return false;
}
// Make sure effectors are all current in world space. It is assumed
// that the joints form a chain, so the world transforms of joint I
// are the parent transforms for the joint I+1.
int iJoint;
for (iJoint = 0; iJoint < m_iJointQuantity; iJoint++)
{
m_aspkJoint[iJoint]->UpdateWorldSRT();
}
// Update joints one-at-a-time to meet goals. As each joint is updated,
// the nodes occurring in the chain after that joint must be made current
// in world space.
int iIter, i, j;
IKJoint* pkJoint;
if (OrderEndToRoot)
{
for (iIter = 0; iIter < Iterations; iIter++)
{
for (iJoint = 0; iJoint < m_iJointQuantity; iJoint++)
{
int iRJoint = m_iJointQuantity - 1 - iJoint;
pkJoint = m_aspkJoint[iRJoint];
for (i = 0; i < 3; i++)
{
if (pkJoint->AllowTranslation[i])
{
if (pkJoint->UpdateLocalT(i))
{
for (j = iRJoint; j < m_iJointQuantity; j++)
{
m_aspkJoint[j]->UpdateWorldRT();
}
}
}
}
for (i = 0; i < 3; i++)
{
if (pkJoint->AllowRotation[i])
{
if (pkJoint->UpdateLocalR(i))
{
for (j = iRJoint; j < m_iJointQuantity; j++)
{
m_aspkJoint[j]->UpdateWorldRT();
}
}
}
}
}
}
}
else // m_eOrder == PO_ROOT_TO_END
{
for (iIter = 0; iIter < Iterations; iIter++)
{
for (iJoint = 0; iJoint < m_iJointQuantity; iJoint++)
{
pkJoint = m_aspkJoint[iJoint];
for (i = 0; i < 3; i++)
{
if (pkJoint->AllowTranslation[i])
{
if (pkJoint->UpdateLocalT(i))
{
for (j = iJoint; j < m_iJointQuantity; j++)
{
m_aspkJoint[j]->UpdateWorldRT();
}
}
}
}
for (i = 0; i < 3; i++)
{
if (pkJoint->AllowRotation[i])
{
if (pkJoint->UpdateLocalR(i))
{
for (j = iJoint; j < m_iJointQuantity; j++)
{
m_aspkJoint[j]->UpdateWorldRT();
}
}
}
}
}
}
}
return true;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// name and unique id
//----------------------------------------------------------------------------
Object* IKController::GetObjectByName (const std::string& rkName)
{
Object* pkFound = Controller::GetObjectByName(rkName);
if (pkFound)
{
return pkFound;
}
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
pkFound = m_aspkJoint[i]->GetObjectByName(rkName);
if (pkFound)
{
return pkFound;
}
}
for (i = 0; i < m_iGoalQuantity; i++)
{
pkFound = m_aspkGoal[i]->GetObjectByName(rkName);
if (pkFound)
{
return pkFound;
}
}
return 0;
}
//----------------------------------------------------------------------------
void IKController::GetAllObjectsByName (const std::string& rkName,
std::vector<Object*>& rkObjects)
{
Controller::GetAllObjectsByName(rkName,rkObjects);
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
m_aspkJoint[i]->GetAllObjectsByName(rkName,rkObjects);
}
for (i = 0; i < m_iGoalQuantity; i++)
{
m_aspkGoal[i]->GetAllObjectsByName(rkName,rkObjects);
}
}
//----------------------------------------------------------------------------
Object* IKController::GetObjectByID (unsigned int uiID)
{
Object* pkFound = Controller::GetObjectByID(uiID);
if (pkFound)
{
return pkFound;
}
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
pkFound = m_aspkJoint[i]->GetObjectByID(uiID);
if (pkFound)
{
return pkFound;
}
}
for (i = 0; i < m_iGoalQuantity; i++)
{
pkFound = m_aspkGoal[i]->GetObjectByID(uiID);
if (pkFound)
{
return pkFound;
}
}
return 0;
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// streaming
//----------------------------------------------------------------------------
void IKController::Load (Stream& rkStream, Stream::Link* pkLink)
{
WM4_BEGIN_DEBUG_STREAM_LOAD;
Controller::Load(rkStream,pkLink);
// native data
rkStream.Read(m_iJointQuantity);
rkStream.Read(m_iGoalQuantity);
rkStream.Read(Iterations);
rkStream.Read(OrderEndToRoot);
// link data
Object* pkObject;
int i;
m_aspkJoint = WM4_NEW IKJointPtr[m_iJointQuantity];
for (i = 0; i < m_iJointQuantity; i++)
{
rkStream.Read(pkObject); // m_aspkJoint[i]
pkLink->Add(pkObject);
}
m_aspkGoal = WM4_NEW IKGoalPtr[m_iGoalQuantity];
for (i = 0; i < m_iGoalQuantity; i++)
{
rkStream.Read(pkObject); // m_aspkGoal[i]
pkLink->Add(pkObject);
}
WM4_END_DEBUG_STREAM_LOAD(IKController);
}
//----------------------------------------------------------------------------
void IKController::Link (Stream& rkStream, Stream::Link* pkLink)
{
Controller::Link(rkStream,pkLink);
Object* pkLinkID;
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
pkLinkID = pkLink->GetLinkID();
m_aspkJoint[i] = (IKJoint*)rkStream.GetFromMap(pkLinkID);
}
for (i = 0; i < m_iGoalQuantity; i++)
{
pkLinkID = pkLink->GetLinkID();
m_aspkGoal[i] = (IKGoal*)rkStream.GetFromMap(pkLinkID);
}
}
//----------------------------------------------------------------------------
bool IKController::Register (Stream& rkStream) const
{
if (!Controller::Register(rkStream))
{
return false;
}
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
m_aspkJoint[i]->Register(rkStream);
}
for (i = 0; i < m_iGoalQuantity; i++)
{
m_aspkGoal[i]->Register(rkStream);
}
return true;
}
//----------------------------------------------------------------------------
void IKController::Save (Stream& rkStream) const
{
WM4_BEGIN_DEBUG_STREAM_SAVE;
Controller::Save(rkStream);
// native data
rkStream.Write(m_iJointQuantity);
rkStream.Write(m_iGoalQuantity);
rkStream.Write(Iterations);
rkStream.Write(OrderEndToRoot);
// link data
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
rkStream.Write(m_aspkJoint[i]);
}
for (i = 0; i < m_iGoalQuantity; i++)
{
rkStream.Write(m_aspkGoal[i]);
}
WM4_END_DEBUG_STREAM_SAVE(IKController);
}
//----------------------------------------------------------------------------
int IKController::GetDiskUsed (const StreamVersion& rkVersion) const
{
return Controller::GetDiskUsed(rkVersion) +
sizeof(m_iJointQuantity) +
sizeof(m_iGoalQuantity) +
sizeof(Iterations) +
sizeof(OrderEndToRoot) +
m_iJointQuantity*sizeof(m_aspkJoint[0]) +
m_iGoalQuantity*sizeof(m_aspkGoal[0]);
}
//----------------------------------------------------------------------------
StringTree* IKController::SaveStrings (const char*)
{
StringTree* pkTree = WM4_NEW StringTree;
// strings
pkTree->Append(Format(&TYPE,GetName().c_str()));
pkTree->Append(Format("joint quantity =",m_iJointQuantity));
pkTree->Append(Format("goal quantity =",m_iGoalQuantity));
pkTree->Append(Format("iterations =",Iterations));
pkTree->Append(Format("end to root =",OrderEndToRoot));
// children
pkTree->Append(Controller::SaveStrings());
// joints
StringTree* pkJTree = WM4_NEW StringTree;
pkJTree->Append(Format("joints"));
int i;
for (i = 0; i < m_iJointQuantity; i++)
{
pkJTree->Append(m_aspkJoint[i]->SaveStrings());
}
pkTree->Append(pkJTree);
// goals
StringTree* pkGTree = WM4_NEW StringTree;
pkGTree->Append(Format("goals"));
for (i = 0; i < m_iGoalQuantity; i++)
{
pkGTree->Append(m_aspkGoal[i]->SaveStrings());
}
pkTree->Append(pkGTree);
return pkTree;
}
//----------------------------------------------------------------------------
| 28.16285 | 78 | 0.467203 | [
"object",
"vector"
] |
6c388fa5476cfb5c22dbafe5ba302f4196a2879d | 1,369 | cpp | C++ | src/Frodo-core/core/log/log.cpp | JeppeSRC/Frodo | f3229c4601608254f16f4499052d8d03c94c0e86 | [
"MIT"
] | 19 | 2016-04-19T21:31:47.000Z | 2018-02-28T19:28:43.000Z | src/Frodo-core/core/log/log.cpp | JeppeSRC/Frodo | f3229c4601608254f16f4499052d8d03c94c0e86 | [
"MIT"
] | null | null | null | src/Frodo-core/core/log/log.cpp | JeppeSRC/Frodo | f3229c4601608254f16f4499052d8d03c94c0e86 | [
"MIT"
] | null | null | null | #include "log.h"
#include "logdevice.h"
#include <core/types.h>
#include <stdarg.h>
namespace fd {
namespace core {
namespace log {
utils::List<LogDevice*> Log::devices;
void Log::AddDevice(LogDevice* device) {
devices.Push_back(device);
}
void Log::RemoveDevice(LogDevice* device) {
devices.Remove(device);
std::vector<int> shit;
}
void Log::Info(const char* const message...) {
va_list list;
va_start(list, message);
uint_t size = devices.GetSize();
for (uint_t i = 0; i < size; i++) {
devices[i]->Log(LogLevel::Info, message, list);
}
va_end(list);
}
void Log::Debug(const char* const message...) {
va_list list;
va_start(list, message);
uint_t size = devices.GetSize();
for (uint_t i = 0; i < size; i++) {
devices[i]->Log(LogLevel::Debug, message, list);
}
va_end(list);
}
void Log::Warning(const char* const message...) {
va_list list;
va_start(list, message);
uint_t size = devices.GetSize();
for (uint_t i = 0; i < size; i++) {
devices[i]->Log(LogLevel::Warning, message, list);
}
va_end(list);
}
void Log::Fatal(const char* const message...) {
va_list list;
va_start(list, message);
uint_t size = devices.GetSize();
for (uint_t i = 0; i < size; i++) {
devices[i]->Log(LogLevel::Fatal, message, list);
}
va_end(list);
}
}}
} | 17.551282 | 53 | 0.615778 | [
"vector"
] |
6c46ba5d0742d4a999314dd9c133e9f5159a5fd5 | 648 | cpp | C++ | cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode455-assign-cookies_two_pointers.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
class Solution {
public:
int findContentChildren(vector<int>& g, vector<int>& s) {
sort(g.begin(), g.end());
sort(s.begin(), s.end());
// 双指针
int j = 0; // 遇到满足条件的情形, j才移动一步(同时是一个计数器)
for (int i = 0; i < s.size() && j < g.size(); ++i) {
if (s[i] >= g[j]) j++;
}
return j;
}
};
// Test
int main()
{
Solution sol;
vector<int> s = {1,2,3}; // cookies we have
vector<int> g = {3};
int res = sol.findContentChildren(g, s);
cout << res << endl;
return 0;
}
| 20.25 | 61 | 0.498457 | [
"vector"
] |
6c470ebee942bf8c16a7930e4be1611ff53614f9 | 12,814 | cpp | C++ | src/LuminoEngine/src/Rendering/Material.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/Rendering/Material.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null | src/LuminoEngine/src/Rendering/Material.cpp | infinnie/Lumino | 921caabdbcb91528a2aac290e31d650628bc3bed | [
"MIT"
] | null | null | null |
#include "Internal.hpp"
#include <LuminoEngine/Base/Serializer.hpp>
#include <LuminoEngine/Asset/Assets.hpp>
#include <LuminoEngine/Graphics/GraphicsCommandBuffer.hpp>
#include <LuminoEngine/Shader/ShaderDescriptor.hpp>
#include <LuminoEngine/Graphics/Texture.hpp>
#include <LuminoEngine/Rendering/Material.hpp>
#include "RenderingManager.hpp"
namespace ln {
//==============================================================================
// Material
// https://docs.unrealengine.com/latest/JPN/Engine/Rendering/Materials/PhysicallyBased/index.html
// https://threejs.org/docs/#api/en/materials/MeshStandardMaterial
//
// フィールド名
// ----------
//
// - glTF > baseColor, Roughness, Metallic
// - filament > color, roughness, metallic
// - Three.js > color, roughness, metalness
// - Unity > Albedo, Metallic, Smoothness
// - UE4 > BaseColor, Roughness, Metallic, Specular
LN_OBJECT_IMPLEMENT(Material, Object) {}
static const Color Material_DefaultColor = Color(1.0f, 1.0f, 1.0f, 1.0f);
static const float Material_DefaultRoughness = 0.5f;
static const float Material_DefaultMetallic = 0.5f;
//static const float Material_DefaultSpecular = 0.5f;
static const Color Material_DefaultEmmisive = Color(0, 0, 0, 0);
Material* Material::defaultMaterial()
{
return detail::EngineDomain::renderingManager()->defaultMaterial();
}
Ref<Material> Material::create()
{
return makeObject<Material>();
}
Ref<Material> Material::create(Texture* mainTexture)
{
return makeObject<Material>(mainTexture);
}
Ref<Material> Material::create(Texture* mainTexture, ShadingModel shadingModel)
{
return makeObject<Material>(mainTexture, shadingModel);
}
Material::Material()
: m_needRefreshShaderBinding(false)
{
m_data.color = Material_DefaultColor;
m_data.roughness = Material_DefaultRoughness;
m_data.metallic = Material_DefaultMetallic;
//m_data.specular = Material_DefaultSpecular;
m_data.emissive = Material_DefaultEmmisive;
}
Material::~Material()
{
}
void Material::init()
{
Object::init();
}
void Material::init(Texture* mainTexture)
{
init(mainTexture, ShadingModel::Default);
}
void Material::init(Texture* mainTexture, ShadingModel shadingModel)
{
init();
setMainTexture(mainTexture);
m_shadingModel = shadingModel;
}
void Material::init(Texture* mainTexture, const detail::PhongMaterialData& phongMaterialData)
{
init();
setMainTexture(mainTexture);
setColor(phongMaterialData.diffuse);
}
void Material::setMainTexture(Texture* value)
{
m_mainTexture = value;
}
Texture* Material::mainTexture() const
{
return m_mainTexture;
}
void Material::setNormalMap(Texture* value)
{
m_normalMap = value;
}
Texture* Material::normalMap() const
{
return m_normalMap;
}
void Material::setMetallicRoughnessTexture(Texture* value)
{
m_metallicRoughnessTexture = value;
}
Texture* Material::metallicRoughnessTexture() const
{
return m_metallicRoughnessTexture;
}
void Material::setOcclusionTexture(Texture* value)
{
m_occlusionTexture = value;
}
Texture* Material::occlusionTexture() const
{
return m_occlusionTexture;
}
void Material::setColor(const Color& value)
{
m_data.color = value;
}
void Material::setRoughness(float value)
{
m_data.roughness = value;
}
void Material::setMetallic(float value)
{
m_data.metallic = value;
}
void Material::setEmissive(const Color& value)
{
m_data.emissive = value;
}
void Material::setShader(Shader* shader)
{
m_shader = shader;
m_needRefreshShaderBinding = true;
}
Shader* Material::shader() const
{
return m_shader;
}
void Material::setInt(const StringRef& name, int value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setInt(value);
}
void Material::setFloat(const StringRef& name, float value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setFloat(value);
}
void Material::setFloatArray(const StringRef& name, const float* values, int length)
{
detail::ShaderParameterValue* param = getValue(name);
param->setFloatArray(values, length);
}
void Material::setVector(const StringRef& name, const Vector4& value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setVector(value);
}
void Material::setVectorArray(const StringRef& name, const Vector4* values, int length)
{
detail::ShaderParameterValue* param = getValue(name);
param->setVectorArray(values, length);
}
void Material::setMatrix(const StringRef& name, const Matrix& value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setMatrix(value);
}
void Material::setTexture(const StringRef& name, Texture* value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setTexture(value);
}
void Material::setColor(const StringRef& name, const Color& value)
{
detail::ShaderParameterValue* param = getValue(name);
param->setVector(value.toVector4());
}
void Material::setBufferData(const StringRef& uniformBufferName, const void* data, int size)
{
ByteBuffer* buffer;
const auto itr = std::find_if(
m_uniformBufferData.begin(), m_uniformBufferData.end(), [&](const UniformBufferEntiry& e) {
return e.name == uniformBufferName;
});
if (itr != m_uniformBufferData.end()) {
buffer = itr->data;
}
else {
auto newBuf = makeRef<ByteBuffer>();
m_uniformBufferData.push_back({ uniformBufferName, newBuf, -1 });
buffer = newBuf;
m_needRefreshShaderBinding = true;
}
buffer->assign(data, size);
}
void Material::setBlendMode(Optional<BlendMode> mode)
{
blendMode = mode;
}
void Material::setCullingMode(Optional<CullMode> mode)
{
cullingMode = mode;
}
void Material::setDepthTestEnabled(Optional<bool> enabled)
{
depthTestEnabled = enabled;
}
void Material::setDepthWriteEnabled(Optional<bool> enabled)
{
depthWriteEnabled = enabled;
}
detail::ShaderParameterValue* Material::getValue(const ln::StringRef& name)
{
for (auto& pair : m_values) {
if (pair.first == name) {
return pair.second.get();
}
}
auto v = std::make_shared<detail::ShaderParameterValue>();
m_values.push_back({ String(name), v });
m_needRefreshShaderBinding = true;
return m_values.back().second.get();
}
void Material::updateShaderVariables(detail::GraphicsCommandList* commandList, detail::ShaderSecondaryDescriptor* descriptor)
{
Shader* target = descriptor->shader();
const ShaderDescriptorLayout* layout = target->descriptorLayout();
if (m_needRefreshShaderBinding) {
for (UniformBufferEntiry& e : m_uniformBufferData) {
e.descriptorIndex = layout->findUniformBufferRegisterIndex(e.name);
}
m_needRefreshShaderBinding = false;
}
// Material から Shader へ検索をかける。
// Shader はビルトインの変数がいくつか含まれているので、この方が高速に検索できる。
for (const auto& pair : m_values) {
auto* param = target->findParameter(pair.first);
if (param) {
switch (pair.second->type())
{
case ShaderVariableType::Unknown:
LN_UNREACHABLE();
break;
case ShaderVariableType::Bool:
LN_NOTIMPLEMENTED();
break;
case ShaderVariableType::BoolArray:
LN_NOTIMPLEMENTED();
break;
case ShaderVariableType::Int:
param->setInt(pair.second->getInt(), descriptor);
break;
case ShaderVariableType::Float:
param->setFloat(pair.second->getFloat(), descriptor);
break;
case ShaderVariableType::FloatArray:
param->setFloatArray(pair.second->getFloatArray(), pair.second->getArrayLength(), descriptor);
break;
case ShaderVariableType::Vector:
param->setVector(pair.second->getVector(), descriptor);
break;
case ShaderVariableType::VectorArray:
param->setVectorArray(pair.second->getVectorArray(), pair.second->getArrayLength(), descriptor);
break;
case ShaderVariableType::Matrix:
param->setMatrix(pair.second->getMatrix(), descriptor);
break;
case ShaderVariableType::MatrixArray:
param->setMatrixArray(pair.second->getMatrixArray(), pair.second->getArrayLength(), descriptor);
break;
case ShaderVariableType::Texture:
//param->setTexture(pair.second->getTexture(), descriptor);
descriptor->setTexture(param->m_dataIndex, pair.second->getTexture());
break;
case ShaderVariableType::Pointer:
LN_NOTIMPLEMENTED();
break;
default:
break;
}
}
}
for (const UniformBufferEntiry& e : m_uniformBufferData) {
if (!descriptor->uniformBuffer(e.descriptorIndex).buffer) {
descriptor->setUniformBuffer(e.descriptorIndex, commandList->allocateUniformBuffer(layout->m_buffers[e.descriptorIndex].size));
}
descriptor->setUniformBufferData(e.descriptorIndex, e.data->data(), e.data->size());
}
}
//void Material::serialize(Archive& ar)
//{
// Material::serialize(ar);
// ar & makeNVP(u"mainTexture", m_mainTexture);
//}
//
void Material::serialize(Serializer2& ar)
{
Object::serialize(ar);
LN_NOTIMPLEMENTED();
//// TODO: ↓Assets辺りに関数化
//if (ar.isSaving()) {
// Path path = Assets::getAssetPath(m_mainTexture);
// if (path.isEmpty()) {
// // assetPath が空であればインスタンスを serialize する
// ar & makeNVP(u"mainTexture", m_mainTexture);
// }
// else {
// // assetPath を持っているときは assetPath を serialize する
// ar & makeNVP(u"mainTexture", path);
// }
//}
//else {
// if (ar.readName(u"mainTexture")) {
// if (ar.readingValueIsObject()) {
// Path path = ar.readString();
// LN_NOTIMPLEMENTED();
// }
// else {
// Path path = ar.readString();
// m_mainTexture = Texture2D::load(path);
// }
// }
// else {
// m_mainTexture = nullptr;
// }
//}
}
////==============================================================================
//// PhongMaterial
//
////LN_TR_REFLECTION_TYPEINFO_IMPLEMENT(PhongMaterial, PhongMaterial);
//
//const String PhongMaterial::DiffuseParameterName(u"_Diffuse");
//const String PhongMaterial::AmbientParameterName(u"_Ambient");
//const String PhongMaterial::EmissiveParameterName(u"_Emissive");
//const String PhongMaterial::SpecularParameterName(u"_Specular");
//const String PhongMaterial::SpecularPowerParameterName(u"_Power");
//
//const Color PhongMaterial::DefaultDiffuse(1.0f, 1.0f, 1.0f, 1.0f);
//const Color PhongMaterial::DefaultAmbient(0.0f, 0.0f, 0.0f, 0.0f);
//const Color PhongMaterial::DefaultSpecular(0.5f, 0.5f, 0.5f, 0.5f);
//const Color PhongMaterial::DefaultEmissive(0.0f, 0.0f, 0.0f, 0.0f);
//const float PhongMaterial::DefaultPower = 50.0f;
//
//Ref<PhongMaterial> PhongMaterial::create()
//{
// return makeObject<PhongMaterial>();
//}
//
//PhongMaterial::PhongMaterial()
// : Material(detail::MaterialType::Phong)
//{
//}
//
//PhongMaterial::~PhongMaterial()
//{
//}
//
//void PhongMaterial::init()
//{
// Material::init();
//}
//
//void PhongMaterial::setDiffuse(const Color& value)
//{
// m_data.diffuse = value;
// setColor(DiffuseParameterName, value);
//}
//
//void PhongMaterial::setAmbient(const Color& value)
//{
// m_data.ambient = value;
// setColor(AmbientParameterName, value);
//}
//
//void PhongMaterial::setEmissive(const Color& value)
//{
// m_data.emissive = value;
// setColor(EmissiveParameterName, value);
//}
//
//void PhongMaterial::setSpecular(const Color& value)
//{
// m_data.specular = value;
// setColor(SpecularParameterName, value);
//}
//
//void PhongMaterial::setSpecularPower(float value)
//{
// m_data.power = value;
// setFloat(SpecularPowerParameterName, value);
//}
//
//void PhongMaterial::translateToPBRMaterialData(detail::PbrMaterialData* outData)
//{
// outData->color = m_data.diffuse;
// outData->roughness = Material_DefaultRoughness;
// outData->metallic = Material_DefaultMetallic;
// //outData->specular = Material_DefaultSpecular;
//}
//==============================================================================
// Material::BuilderDetails
Material::BuilderDetails::BuilderDetails()
: color(Material_DefaultColor)
, roughness(Material_DefaultRoughness)
, metallic(Material_DefaultMetallic)
{
}
void Material::BuilderDetails::apply(Material* p) const
{
p->setColor(color);
p->setRoughness(roughness);
p->setMetallic(metallic);
}
} // namespace ln
| 26.976842 | 139 | 0.6624 | [
"object",
"vector"
] |
484389ab1fa311ecccdffd2cae29bbd2bc0063e6 | 1,711 | cpp | C++ | aws-cpp-sdk-mediatailor/source/model/HttpPackageConfiguration.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-mediatailor/source/model/HttpPackageConfiguration.cpp | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-mediatailor/source/model/HttpPackageConfiguration.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mediatailor/model/HttpPackageConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace MediaTailor
{
namespace Model
{
HttpPackageConfiguration::HttpPackageConfiguration() :
m_pathHasBeenSet(false),
m_sourceGroupHasBeenSet(false),
m_type(Type::NOT_SET),
m_typeHasBeenSet(false)
{
}
HttpPackageConfiguration::HttpPackageConfiguration(JsonView jsonValue) :
m_pathHasBeenSet(false),
m_sourceGroupHasBeenSet(false),
m_type(Type::NOT_SET),
m_typeHasBeenSet(false)
{
*this = jsonValue;
}
HttpPackageConfiguration& HttpPackageConfiguration::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("Path"))
{
m_path = jsonValue.GetString("Path");
m_pathHasBeenSet = true;
}
if(jsonValue.ValueExists("SourceGroup"))
{
m_sourceGroup = jsonValue.GetString("SourceGroup");
m_sourceGroupHasBeenSet = true;
}
if(jsonValue.ValueExists("Type"))
{
m_type = TypeMapper::GetTypeForName(jsonValue.GetString("Type"));
m_typeHasBeenSet = true;
}
return *this;
}
JsonValue HttpPackageConfiguration::Jsonize() const
{
JsonValue payload;
if(m_pathHasBeenSet)
{
payload.WithString("Path", m_path);
}
if(m_sourceGroupHasBeenSet)
{
payload.WithString("SourceGroup", m_sourceGroup);
}
if(m_typeHasBeenSet)
{
payload.WithString("Type", TypeMapper::GetNameForType(m_type));
}
return payload;
}
} // namespace Model
} // namespace MediaTailor
} // namespace Aws
| 18.802198 | 82 | 0.722385 | [
"model"
] |
484e7cb9851553bbfeb1621d465e4cec6e04720c | 1,399 | cpp | C++ | attic/hwcpp-source/core/work1.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 21 | 2017-05-24T21:44:29.000Z | 2021-03-24T05:41:14.000Z | attic/hwcpp-source/core/work1.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 3 | 2017-11-21T14:44:13.000Z | 2018-03-02T11:55:05.000Z | attic/hwcpp-source/core/work1.cpp | wovo/hwcpp | 2462db6b360e585fd0c8c8c23fac2e5db24f52a0 | [
"BSL-1.0"
] | 2 | 2018-02-23T12:13:45.000Z | 2019-07-10T17:29:15.000Z | template< typename Timing >
class i2c_100kHz( Timing timing_ ) final {
const auto timing = timing_from( timing_ );
// from the "I2C-bus specification and user manual,
// 4 April 2014", UM10204.pdf, Table 10
const auto t_hd_sta = timing.ns( 4000 );
const auto t_low = timing.ns( 4700 );
const auto t_high = timing.ns( 4000 );
const auto t_su_sta = timing.ns( 4700 );
const auto t_hd_dat = timing.ns( 0 );
const auto t_su_sto = timing.ns( 4000 );
const auto t_buf = timing.ns( 4700 );
};
template< typename Timing >
constexpr auto i2c_100kHz( const Timing & timing_ ){
const auto timing = timing_from( timing_ );
return i2c_100kHz_implementation( timing );
}
auto sensor_temperature =
// LM35 should know the reference voltage? Or should ad?
template< typename Pin >
void temperature_print( const char * text, Pin & pin_ ){
auto ad_pin = pin_ad_from( pin_ );
auto sensor = lm35( ad_pin, volt( 3.3 ) );
std::cout << "temperature at " << location << " is " << sensor.read() << "\n";
}
temperature_print( target::ad0 );
temperature_print( target::ad1 );
temperature_print( object( target::ad0 ));
temperature_print( object( target::ad1 ));
void temperature_object_print( pin_ad & pin ){
temperature_print( pin );
}
temperature_object_print( target::ad0 );
temperature_object_print( target::ad1 );
| 29.765957 | 81 | 0.668335 | [
"object"
] |
48521b3377ac0e5d7f3bee6fbc9d786ee1b92414 | 2,426 | cpp | C++ | codes/CSES/CSES_2111.cpp | chessbot108/collection-of-chessbot-codes | 08418213edef5b4ed818cc84224e3122267bbb48 | [
"MIT"
] | 2 | 2021-03-07T03:34:02.000Z | 2021-03-09T01:22:21.000Z | codes/CSES/CSES_2111.cpp | chessbot108/collection-of-chessbot-codes | 08418213edef5b4ed818cc84224e3122267bbb48 | [
"MIT"
] | 1 | 2021-03-27T15:01:23.000Z | 2021-03-27T15:55:34.000Z | codes/CSES/CSES_2111.cpp | chessbot108/collection-of-chessbot-codes | 08418213edef5b4ed818cc84224e3122267bbb48 | [
"MIT"
] | 1 | 2021-03-27T05:02:33.000Z | 2021-03-27T05:02:33.000Z | //chtholly and emilia will carry me to cm
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <string>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <random>
#include <chrono>
#include <queue>
#include <set>
#include <map>
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define all(x) begin(x), end(x)
#define sz(x) (int)(x).size()
#define ll __int128
//#define int __int128
//typedef long long ll;
//typedef __int128 int;
typedef pair<int, int> pii;
typedef vector<int> vi;
//const ll mod = (119 << 23) + 1, root = 62;
const ll mod = 40000552961, root = 27790731745;
//40000552961 > 2e5 ^2, and as a 2^19-th root of unity
typedef vector<ll> vl;
ll modpow(ll b, ll e) {
ll ans = 1;
for (; e; b = b * b % mod, e /= 2)
if (e & 1) ans = ans * b % mod;
return ans;
}
void ntt(vl &a) {
int n = sz(a), L = 31 - __builtin_clz(n);
static vl rt(2, 1);
for (static int k = 2, s = 2; k < n; k *= 2, s++) {
rt.resize(n);
ll z[] = {1, modpow(root, mod >> s)};
rep(i,k,2*k) rt[i] = rt[i / 2] * z[i & 1] % mod;
}
vi rev(n);
rep(i,0,n) rev[i] = (rev[i / 2] | (i & 1) << L) / 2;
rep(i,0,n) if (i < rev[i]) swap(a[i], a[rev[i]]);
for (int k = 1; k < n; k *= 2)
for (int i = 0; i < n; i += 2 * k) rep(j,0,k) {
ll z = rt[j + k] * a[i + j + k] % mod, &ai = a[i + j];
a[i + j + k] = ai - z + (z > ai ? mod : 0);
ai += (ai + z >= mod ? z - mod : z);
}
}
vl conv(const vl &a, const vl &b) {
if (a.empty() || b.empty()) return {};
int s = sz(a) + sz(b) - 1, B = 32 - __builtin_clz(s), n = 1 << B;
ll inv = modpow(n, mod - 2);
vl L(a), R(b), out(n);
L.resize(n), R.resize(n);
ntt(L), ntt(R);
rep(i,0,n) out[-i & (n - 1)] = (ll)L[i] * R[i] % mod * inv % mod;
ntt(out);
return {out.begin(), out.begin() + s};
}
signed main() {
cin.tie(0)->sync_with_stdio(0);
cin.exceptions(cin.failbit);
signed n, m, k;
cin >> k >> n >> m;
//signed lg = (long)(ceil(log2(k+1)));
vector<ll> a(k + 1, 0), b(k + 1, 0);
for(int i = 0; i<n; i++){
signed x; cin >> x;
a[x]++;
}
for(int i = 0; i<m; i++){
signed x; cin >> x;
b[x]++;
}
/**
for(int i = 0; i<=k; i++){
cout << (long long)a[i] << " ";
} cout << "\n";
for(int i = 0; i<=k; i++){
cout << (long long)b[i] << " ";
} cout << "\n";
**/
vector<ll> ans = conv(a, b);
for(int i = 2; i<=2*k; i++){
cout << (long long)ans[i] << " ";
}
return 0;
}
| 24.505051 | 66 | 0.5169 | [
"vector"
] |
485259e61823278367952d8d106ca74eb0a13f54 | 5,115 | cc | C++ | example/laser_file_test.cc | ibyte2011/LaserDB | 326fa477c4cbee36f46706ecb3b4a48d3bdab057 | [
"Apache-2.0"
] | 26 | 2021-01-07T09:32:37.000Z | 2022-02-17T04:00:03.000Z | example/laser_file_test.cc | imotai/LaserDB | 16f02fe001751b26e4221f54f9d3e2ca8c1a0607 | [
"Apache-2.0"
] | 1 | 2021-09-01T09:16:53.000Z | 2021-12-04T02:25:15.000Z | example/laser_file_test.cc | imotai/LaserDB | 16f02fe001751b26e4221f54f9d3e2ca8c1a0607 | [
"Apache-2.0"
] | 10 | 2021-01-21T06:26:46.000Z | 2022-02-08T02:41:23.000Z | #include <fstream>
#include "folly/init/Init.h"
#include "folly/Random.h"
#include "service_router/http.h"
#include "laser/lib/loader_source_data.h"
#include "laser/lib/status.h"
#include "laser/client/laser_client.h"
#include "common/metrics/metrics.h"
DEFINE_string(host, "127.0.0.1", "current service host address");
DEFINE_int32(port, 0, "current service port");
DEFINE_string(service_name, "laser_client_file", "Current geo client service name");
DEFINE_string(target_service_name, "laser_dev", "Search laser service name");
DEFINE_string(database_name, "test", "Test laser database name");
DEFINE_string(table_name, "test_raw_string", "Test laser table names");
DEFINE_int32(delimiter, 1, "Test laser delimiter");
DEFINE_bool(print, true, "Test laser delimiter");
DEFINE_string(file_name, "file", "current service host address");
DEFINE_int32(rpc_request_timeout, 10, "each request recv timeout");
DEFINE_int32(diff_range, 256, "Address diff range");
DEFINE_string(load_balance_method, "random",
"request load balance method `random/roundrobin/localfirst/configurable_weight`");
DEFINE_string(client_request_read_mode, "mixed_read", "request read mode `leader_read/mixed_read");
DEFINE_int32(max_conn_per_server, 0, "Max connection pre server.");
class LaserCall {
public:
LaserCall(const std::string& target_service_name, const std::string& database_name, const std::string& table_name)
: target_service_name_(target_service_name), database_name_(database_name), table_name_(table_name) {}
~LaserCall() = default;
void init() {
client_ = std::make_shared<laser::LaserClient>(target_service_name_);
client_->init();
client_options_ = getClientOption();
}
const laser::ClientOption getClientOption() {
laser::ClientOption option;
option.setReceiveTimeoutMs(FLAGS_rpc_request_timeout);
option.setMaxConnPerServer(FLAGS_max_conn_per_server);
auto method = service_router::stringToLoadBalanceMethod(FLAGS_load_balance_method);
service_router::LoadBalanceMethod load_method = service_router::LoadBalanceMethod::RANDOM;
if (!method) {
FB_LOG_EVERY_MS(ERROR, 1000) << "Specified load balance method is invalid, default is random";
} else {
load_method = *method;
}
option.setLoadBalance(load_method);
auto read_mode = laser::ClientRequestReadMode::MIXED_READ;
auto read_mode_optional = laser::stringToClientRequestReadMode(FLAGS_client_request_read_mode);
if (read_mode_optional) {
read_mode = *read_mode_optional;
}
option.setReadMode(read_mode);
service_router::BalanceLocalFirstConfig local_first;
local_first.setLocalIp(FLAGS_host);
local_first.setDiffRange(FLAGS_diff_range);
option.setLocalFirstConfig(local_first);
return option;
}
void run(bool is_print, const std::string& file_name) {
std::ifstream fin(file_name);
if (!fin) {
LOG(ERROR) << "Open local file fail, path:" << file_name;
return;
}
std::string line_data;
uint64_t success_count = 0;
uint64_t fail_count = 0;
while (getline(fin, line_data)) {
std::vector<std::string> context_vals;
char delimiter = static_cast<char>(FLAGS_delimiter);
folly::split(delimiter, line_data, context_vals);
if (context_vals.size() != 2) {
FB_LOG_EVERY_MS(ERROR, 2000) << "Insert data format is invalid, split part is " << context_vals.size();
continue;
}
laser::LaserKey key;
getLaserKey(&key, context_vals[0]);
if (get(key, context_vals[1], is_print)) {
success_count++;
} else {
fail_count++;
}
FB_LOG_EVERY_MS(ERROR, 5000) << "Success number:" << success_count << " Fail count:" << fail_count;
}
}
private:
std::string target_service_name_;
std::string database_name_;
std::string table_name_;
std::shared_ptr<laser::LaserClient> client_;
laser::ClientOption client_options_;
bool get(const laser::LaserKey& key, const std::string& value, bool is_print) {
std::string data;
auto ret = client_->getSync(client_options_, &data, key);
if (!is_print) {
return true;
}
if (ret != laser::Status::OK) {
LOG(INFO) << "Call get api fail," << ret;
return false;
} else {
if (data != value) {
LOG(INFO) << "pk:" << key.get_primary_keys()[0] << " vlaue:" << data << " rvalue:" << value;
return false;
}
}
return true;
}
void getLaserKey(laser::LaserKey* laser_key, const std::string& key) {
std::vector<std::string> pks({key});
laser_key->set_database_name(database_name_);
laser_key->set_table_name(table_name_);
laser_key->set_primary_keys(pks);
}
};
int main(int argc, char* argv[]) {
FLAGS_logtostderr = true;
folly::Init init(&argc, &argv);
SCOPE_EXIT {
service_router::unregisterAll();
service_framework::http::stop();
service_router::stop_connection_pool();
};
LaserCall laser_call(FLAGS_target_service_name, FLAGS_database_name, FLAGS_table_name);
laser_call.init();
laser_call.run(FLAGS_print, FLAGS_file_name);
return 0;
}
| 35.520833 | 116 | 0.705767 | [
"vector"
] |
48679371dfa9bc6b8488a5468c54ae4a4ff4cc26 | 2,011 | cpp | C++ | main/count-element-occurrences/count-element-occurrences-extraspace.cpp | EliahKagan/old-practice-snapshot | 1b53897eac6902f8d867c8f154ce2a489abb8133 | [
"0BSD"
] | null | null | null | main/count-element-occurrences/count-element-occurrences-extraspace.cpp | EliahKagan/old-practice-snapshot | 1b53897eac6902f8d867c8f154ce2a489abb8133 | [
"0BSD"
] | null | null | null | main/count-element-occurrences/count-element-occurrences-extraspace.cpp | EliahKagan/old-practice-snapshot | 1b53897eac6902f8d867c8f154ce2a489abb8133 | [
"0BSD"
] | null | null | null | // A C++ program to print elements with count more than n/k
// Modified from original geeksforgeeks.org boilerplate source code:
// (a) Added comments.
// (b) Line numbering unfortunately changed (due to added code and comments).
// (c) Improved indentation for readability.
// (d) Used vector instead of VLA for compatibility: VLAs aren't standard C++.
// (e) Added my solution to the end.
#include<iostream>
#include<vector>
using namespace std;
long long int totalcount = 0;
void moreThanNdK(long long int arr[], long long int n, long long int k);
// A structure to store an element and its current count
struct eleCount
{
long long int e; // Element
long long int c; // Count
};
/* Driver program to test above function */
int main()
{
long long int t, k;
cin >> t;
while (t--)
{
long long int n, i;
cin >> n;
vector<long long> arr (n); //long long int arr[n];
for (i = 0; i<n; i++)
cin >> arr[i];
cin >> k;
moreThanNdK(arr.data(), n, k);
totalcount = 0;
}
return 0;
}
// A structure to store an element and its current count
/* struct eleCount
{
long long int e; // Element
long long int c; // Count
};
*/
// Prints elements with more than n/k occurrences in values[] of
// size n. If there are no such elements, then it prints nothing.
// FIXME: This comment seems incorrect.
void moreThanNdK(long long* const values, const long long n, const long long k)
{
// I assume only each a[i] <= nmax. Uses "O(n)" (nmax) extra space.
static constexpr auto nmax = 100000LL;
static int counts[nmax + 1LL] {};
static int* used[nmax] {}; // stack of pointers to nonzero counts
const auto threshold = n / k + 1LL;
auto top = used;
auto acc = 0;
for (auto i = 0LL; i != n; ++i) {
auto& c {counts[values[i]]};
if (c == 0) *top++ = &c;
if (++c == threshold) ++acc;
}
while (top != used) **--top = 0;
cout << acc << '\n';
}
| 27.547945 | 79 | 0.604674 | [
"vector"
] |
4869e9e644b58cf234cc8a61f666401b9fcd812d | 2,511 | cpp | C++ | Merge_Sorted_Arrays.cpp | omkar342/hacktober | 615a1aef427e64dc1b8b319eb558e6aae372c07a | [
"MIT"
] | null | null | null | Merge_Sorted_Arrays.cpp | omkar342/hacktober | 615a1aef427e64dc1b8b319eb558e6aae372c07a | [
"MIT"
] | 31 | 2021-10-01T13:33:11.000Z | 2021-10-31T05:23:03.000Z | Merge_Sorted_Arrays.cpp | omkar342/hacktober | 615a1aef427e64dc1b8b319eb558e6aae372c07a | [
"MIT"
] | 12 | 2020-10-02T15:01:18.000Z | 2021-10-31T05:23:13.000Z | // You are given two integer arrays nums1 and nums2, sorted in non-decreasing order, and two integers m and n, representing the number of elements in nums1 and nums2 respectively.
// Merge nums1 and nums2 into a single array sorted in non-decreasing order.
// The final sorted array should not be returned by the function, but instead be stored inside the array nums1. To accommodate this, nums1 has a length of m + n, where the first m elements denote the elements that should be merged, and the last n elements are set to 0 and should be ignored. nums2 has a length of n.
// Example 1:
// Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
// Output: [1,2,2,3,5,6]
// Explanation: The arrays we are merging are [1,2,3] and [2,5,6].
// The result of the merge is [1,2,2,3,5,6] with the underlined elements coming from nums1.
// Example 2:
// Input: nums1 = [1], m = 1, nums2 = [], n = 0
// Output: [1]
// Explanation: The arrays we are merging are [1] and [].
// The result of the merge is [1].
// Example 3:
// Input: nums1 = [0], m = 0, nums2 = [1], n = 1
// Output: [1]
// Explanation: The arrays we are merging are [] and [1].
// The result of the merge is [1].
// Note that because m = 0, there are no elements in nums1. The 0 is only there to ensure the merge result can fit in nums1.
// Constraints:
// nums1.length == m + n
// nums2.length == n
// 0 <= m, n <= 200
// 1 <= m + n <= 200
// -109 <= nums1[i], nums2[j] <= 109
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<int> &v)
{
cout << "The Given Array looks like - [ ";
for (int i = 0; i < v.size(); i++)
{
if (i == v.size() - 1)
cout << v[i];
else
cout << v[i] << ", ";
}
cout << " ] " << endl;
}
class Solution
{
public:
void merge(vector<int> &nums1, int m, vector<int> &nums2, int n)
{
int i = m - 1, j = n - 1, k = n + m - 1;
while (i >= 0 && j >= 0)
{
if (nums1[i] >= nums2[j])
{
nums1[k] = nums1[i];
i--;
}
else
{
nums1[k] = nums2[j];
j--;
}
k--;
}
while (j >= 0)
nums1[k--] = nums2[j--];
}
};
int main()
{
system("CLS");
Solution obj;
vector<int> nums1 = {1, 2, 3, 0, 0, 0};
vector<int> nums2 = {2, 5, 6};
int m = 3, n = 3;
obj.merge(nums1, m, nums2, n);
print_vector(nums1);
return 0;
} | 27.9 | 316 | 0.540024 | [
"vector"
] |
486f056e432697a4479d450544d60e7328d2b91c | 1,215 | cpp | C++ | src/SystemManager/SystemManager.cpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | null | null | null | src/SystemManager/SystemManager.cpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | 1 | 2016-03-13T10:55:21.000Z | 2016-03-13T10:55:21.000Z | src/SystemManager/SystemManager.cpp | cristianglezm/AntFarm | df7551621ad6eda6dae43a2ede56222500be1ae1 | [
"Apache-2.0"
] | null | null | null | #include <SystemManager/SystemManager.hpp>
namespace ant{
bool SystemManager::addSystem(std::shared_ptr<System> s){
auto result = systems.insert(std::make_pair(s->getName(),s));
return result.second;
}
std::shared_ptr<System> SystemManager::getSystem(const std::string& name){
return systems[name];
}
void SystemManager::setSystems(container systems){
this->systems = systems;
}
void SystemManager::removeSystem(const std::string& name){
systems.erase(name);
}
void SystemManager::setEntityManager(std::shared_ptr<EntityManager> entityManager){
for(auto& system : systems){
system.second->setEntityManager(entityManager);
}
}
void SystemManager::setEventQueue(std::shared_ptr<EventQueue> eventQueue){
for(auto& system : systems){
system.second->setEventQueue(eventQueue);
}
}
void SystemManager::update(const sf::Time& dt){
for(auto& system : systems){
system.second->update(dt);
}
}
void SystemManager::render(sf::RenderWindow& win){
for(auto& system : systems){
system.second->render(win);
}
}
}
| 31.973684 | 87 | 0.628807 | [
"render"
] |
486fac945c13aa4a46ef04410fc852292890d78f | 16,448 | cpp | C++ | src/tests/test_basics.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | 4 | 2017-03-20T22:14:10.000Z | 2018-03-21T09:24:32.000Z | src/tests/test_basics.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | src/tests/test_basics.cpp | ondra-novak/couchit | 10af4464327dcc2aeb470fe2db7fbd1594ff1b0d | [
"MIT"
] | null | null | null | /*
* test_basics.cpp
*
* Created on: 19. 3. 2016
* Author: ondra
*/
#include <iostream>
#include <set>
#include <vector>
#include <thread>
#include <chrono>
#include <condition_variable>
#include "../couchit/attachment.h"
#include "../couchit/document.h"
#include "../couchit/queryCache.h"
#include "../couchit/changeset.h"
#include "../couchit/couchDB.h"
#include "../couchit/query.h"
#include "../couchit/changes.h"
#include "../couchit/json.h"
#include "../couchit/queryServerIfc.h"
#include "../couchit/localView.h"
#include "test_common.h"
#include "testClass.h"
namespace couchit {
#define DATABASENAME "couchit_unittest"
static void couchConnect(std::ostream &print) {
CouchDB db(getTestCouch());
CouchDB::PConnection conn = db.getConnection("/");
Value v = db.requestGET(conn);
print << v["couchdb"].getString();
}
static void rawCreateDB(std::ostream &) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
db.createDatabase();
}
static void deleteDB(std::ostream &) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
db.deleteDatabase();
}
//randomly generated data
static const char *strdata="[[\"Kermit Byrd\",76,184],[\"Odette Hahn\",44,181],"
"[\"Scarlett Frazier\",43,183],[\"Pascale Burt\",46,153],"
"[\"Urielle Pennington\",21,166],[\"Bevis Bowen\",47,185],"
"[\"Dakota Shepherd\",52,165],[\"Ramona Lang\",23,190],"
"[\"Nicole Jordan\",75,150],[\"Owen Dillard\",80,151],"
"[\"Daniel Cochran\",36,170],[\"Kenneth Meyer\",42,156]]";
static const char *designs[]={
"{\"_id\":\"_design/testview\",\"language\":\"javascript\",\"views\":{"
"\"by_name\":{\"map\":function (doc) {if (doc.name) emit([doc.name], [doc.age,doc.height]);}},"
"\"by_age\":{\"map\":function (doc) {if (doc.name) emit(doc.age, doc.name);\n\t\t\t\t}},"
"\"by_age_group\":{\"map\":function (doc) {if (doc.name) emit([Math.floor(doc.age/10)*10, doc.age], doc.name);}},"
"\"age_group_height\":{\"map\":function (doc) {if (doc.name) emit([Math.floor(doc.age/10)*10, doc.age], doc.height);},\"reduce\":\"_stats\"}},"
"\"dummy\":false}"
};
static View by_name("_design/testview/_view/by_name");
static View by_name_cacheable("_design/testview/_view/by_name", View::includeDocs);
static View by_age_group("_design/testview/_view/by_age_group");
static View by_age("_design/testview/_view/by_age");
static View age_group_height("_design/testview/_view/age_group_height");
static void couchLoadData(std::ostream &print) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
std::vector<Document> savedDocs;
Changeset chset(db.createChangeset());
std::size_t id=10000;
Value data = Value::fromString(strdata);
for(auto &&item : data) {
Document doc;
doc("name",item[0])
("age",item[1])
("height",item[2])
("_id",UIntToStr(id,16));
id+=14823;
savedDocs.push_back(doc);
chset.update(doc);
}
chset.commit();
std::set<String> uuidmap;
for (std::size_t i = 0; i < savedDocs.size(); i++) {
StrViewA uuid = savedDocs[i]["_id"].getString();
uuidmap.insert(uuid);
}
print << uuidmap.size();
}
static void couchConflicted(std::ostream &print) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
try {
couchLoadData(print);
} catch (UpdateException &e) {
print << "conflicts-" << e.getErrors().length;
}
}
#define countof(x) (sizeof(x)/sizeof(x[0]))
static void couchLoadDesign(std::ostream &) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
for (std::size_t i = 0; i < countof(designs); i++) {
db.putDesignDocument(designs[i],strlen(designs[i]));
}
//try twice
for (std::size_t i = 0; i < countof(designs); i++) {
db.putDesignDocument(designs[i],strlen(designs[i]));
}
db.updateView(by_name,true);
}
static void couchFindWildcard(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(by_name));
Result res = q.prefixString({"K"}).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << " ";
}
}
static void couchFindGroup(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(by_age_group));
Result res = q.prefixKey(40).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.value.getString() << " ";
}
}
static void couchFindRange(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(by_age));
Result res = q.range(20,40).reversedOrder().exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.value.getString() << " ";
}
}
static void couchFindKeys(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(by_name));
Result res = q.keys({
{"Kermit Byrd"},
{"Owen Dillard"},
{"Nicole Jordan"}
}).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << " ";
}
}
static void couchCaching(std::ostream &a) {
QueryCache cache;
Config cfg = getTestCouch();
cfg.cache = &cache;
CouchDB db(cfg);
db.setCurrentDB(DATABASENAME);
json::PValue v;
for (std::size_t i = 0; i < 3; i++) {
Query q(db.createQuery(by_name_cacheable));
Value r = q.keys({
{"Kermit Byrd"},
{"Owen Dillard"},
{"Nicole Jordan"}
}).exec();
bool cached = r.getHandle() == v;
Result res(r);
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << ":"
<< cached << " ";
}
v = r.getHandle();
}
}
/*
static void couchCaching2(std::ostream &a) {
QueryCache cache;
Config cfg = getTestCouch();
cfg.cache = &cache;
CouchDB db(cfg);
db.use(DATABASENAME);
db.trackSeqNumbers();
String killDocName = "Owen Dillard";
Document killDoc;
json::PValue vhandle;
for (std::size_t i = 0; i < 3; i++) {
if (i == 2) {
//make a change during second run
Changeset cset = db.createChangeset();
killDoc.setDeleted();
cset.update(killDoc);
cset.commit(db);
//also calls listenChanges
db.getLastSeqNumber();
}
Query q(db.createQuery(by_name_cacheable));
Result res = q.select("Kermit Byrd")(Query::isArray)
.select("Owen Dillard")
.select("Nicole Jordan")
.exec();
while (res.hasItems()) {
Row row = res.getNext();
a("%1,%2,%3,%4 ") << row.key[0].getString()
<<row.value[0].getUInt()
<<row.value[1].getUInt()
<<(vhandle==res.getHandle()?"true":"false");
//remember values of what to erase
if (row.key[0] == killDocName) {
killDoc = row.doc;
}
}
vhandle = res.getHandle();
}
}
*/
static void couchReduce(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(age_group_height));
Result res = q.groupLevel(1).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getUInt() << ":"
<<(row.value["sum"].getUInt()/row.value["count"].getUInt()) << " ";
}
}
static Value lastId;
static void couchChangeSetOneShot(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
ChangesFeed chsink (db.createChangesFeed());
Changes chngs = chsink.exec();
std::size_t count = 0;
while (chngs.hasItems()) {
ChangeEvent doc(chngs.getNext());
count++;
}
a << (count > 10);
}
static void loadSomeDataThread(CouchDB &db,StrViewA locId) {
std::this_thread::sleep_for(std::chrono::seconds(1));
Changeset chset = db.createChangeset();
Document doc;
doc("_id",locId)
("aaa",100);
chset.update(doc);
chset.commit(db);
}
static void couchChangeSetWaitForData(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
String uid ( db.genUID());
std::thread thr([&]{loadSomeDataThread(db,uid);});
ChangesFeed chsink (db.createChangesFeed());
chsink.setTimeout(10000);
chsink.fromSeq(lastId);
bool found = false;
chsink >> [&](const ChangeEvent &doc) {
if (doc.id == uid && !doc.deleted) {
found = true;
return false;
}
return true;
};
if (found) {
a << "ok";
} else {
a << "fail";
}
thr.join();
}
class Event {
std::condition_variable condVar;
std::mutex mutex;
bool ready = false;
public:
void wait() {
std::unique_lock<std::mutex> _(mutex);
condVar.wait(_, [&]{return ready;});
ready = false;
}
void notify() {
std::unique_lock<std::mutex> _(mutex);
ready = true;
condVar.notify_one();
}
};
static void loadSomeDataThread3(CouchDB &db, String locId, Event &event) {
for (std::size_t i = 0; i < 3; i++) {
Changeset chset = db.createChangeset();
Document doc;
doc("_id",locId.substr(i))
("aaa",100);
chset.update(doc);
chset.commit(db);
event.wait();
}
}
static void couchChangeSetWaitForData3(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
String uid ( db.genUID());
int counter=0;
Event event;
std::thread thr([&]{loadSomeDataThread3(db,uid, event);});
ChangesFeed chsink (db.createChangesFeed());
chsink.setTimeout(10000);
chsink.fromSeq(lastId);
bool ok = false;
chsink >> [&](const ChangeEvent &doc) {
if (doc.id == uid && !doc.deleted) {
counter++;
event.notify();
} else if (counter) {
counter++;
event.notify();
if (counter == 3) {
ok = true;
return false;
}
}
return true;
};
if (ok) a << "ok"; else a << "fail";
thr.join();
}
static void couchChangesStopWait(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
ChangesFeed chsink (db.createChangesFeed());
chsink.setTimeout(10000);
std::thread thr([&chsink]() {
std::this_thread::sleep_for(std::chrono::seconds(1));
chsink.cancelWait();
});
chsink >> [](const ChangeEvent &) {return true;};
if (chsink.wasCanceled()) {
CouchDB::PConnection conn = db.getConnection("/");
Value v = db.requestGET(conn);
a << v["couchdb"].getString();
} else {
a << "fail";
}
thr.join();
}
static void couchGetSeqNumber(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
SeqNumber cnt = db.getLastSeqNumber();
SeqNumber beg(Value(1));
SeqNumber last = db.getLastKnownSeqNumber();
a << (cnt > beg && last == cnt?"ok":"failed");
}
static void couchRetrieveDocument(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Query q(db.createQuery(by_name));
Result res = q.key({"Kermit Byrd"}).exec();
Row row = res.getNext();
Document doc = db.get(row.id.getString(), CouchDB::flgSeqNumber);
//this is random - cannot be tested
doc.unset("_id").unset("_rev");
a << Value(doc).toString();
}
static void couchStoreAndRetrieveAttachment(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Document doc = db.newDocument("data-");
Upload upl = db.putAttachment(doc,"testAttachment","text/plain");
StrViewA sentence("The quick brown fox jumps over the lazy dog");
upl.write(BinaryView(sentence));
upl.finish();
Document doc2 = db.get(doc.getID());
AttachmentData data = db.getAttachment(doc2,"testAttachment");
a << data.contentType << "-" << StrViewA(data);
}
class ByName: public AbstractViewMapOnly<1> {
virtual void map(const Document &doc, IEmitFn &emit) override {
emit(Value(array,{doc["name"]}), {doc["age"],doc["height"]});
}
};
static void testLocalViewUpdate(std::ostream &a) {
LocalView l(new ByName,0);
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
l.loadFromView(db,by_name,true);
Query q(l.createQuery(db,0));
Result res = q.keys({
{"Kermit Byrd"},
{"Owen Dillard"},
{"Nicole Jordan"}
}).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << " ";
}
}
static void testLocalViewUpdate2(std::ostream &a) {
LocalView l(new ByName,0);
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
l.loadFromView(db,by_name,true);
Document doc;
doc("name","Ondra Novak")
("age",41)
("height",189)
("_id","someUnique");
db.put(doc);
Query q(l.createQuery(db,0));
Result res = q.keys({
{"Ondra Novak"},
{"Owen Dillard"},
{"Nicole Jordan"}
}).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << " ";
}
}
static void testLocalViewUpdate3(std::ostream &a) {
LocalView l(new ByName,0);
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
l.loadFromView(db,by_name,true);
Document doc = db.get("someUnique");
doc.setDeleted({"name"});
db.put(doc);
Query q(l.createQuery(db,0));
Result res = q.keys({
{"Ondra Novak"},
{"Owen Dillard"},
{"Nicole Jordan"}
}).exec();
while (res.hasItems()) {
Row row = res.getNext();
a << row.key[0].getString() << ","
<<row.value[0].getUInt() << ","
<<row.value[1].getUInt() << " ";
}
db.updateView(by_name,true);
}
static void testRecreate(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Document doc1 = db.get("test_recreate",CouchDB::flgCreateNew);
doc1.set("aaa","bbb");
db.put(doc1);
doc1.setDeleted();
db.put(doc1);
Document doc2 = db.get("test_recreate",CouchDB::flgCreateNew);
doc2.set("ccc","xxx");
db.put(doc2);
Document doc3 = db.get("test_recreate");
a << doc3["ccc"].getString();
}
static void couchLarge(std::ostream &a) {
CouchDB db(getTestCouch());
db.setCurrentDB(DATABASENAME);
Changeset chg = db.createChangeset();
for (int i = 0; i < 100000; i++) {
Document doc = db.newDocument();
doc.set("index",i);
chg.update(doc);
}
chg.commit();
for (int i = 0; i < 10; i++) {
Query q = db.createQuery(View::includeDocs);
Result r = q.exec();
a << r.size();
}
}
void runTestBasics(TestSimple &tst) {
tst.test("couchdb.connect","Welcome") >> &couchConnect;
tst.test("couchdb.createDB","") >> &rawCreateDB;
tst.test("couchdb.loadData","12") >> &couchLoadData;
tst.test("couchdb.loadDesign","") >> &couchLoadDesign;
tst.test("couchdb.detectConflict","conflicts-12") >> &couchConflicted;
tst.test("couchdb.findWildcard","Kenneth Meyer,42,156 Kermit Byrd,76,184 ") >> &couchFindWildcard;
tst.test("couchdb.findGroup","Kenneth Meyer Scarlett Frazier Odette Hahn Pascale Burt Bevis Bowen ") >> &couchFindGroup;
tst.test("couchdb.findRange","Daniel Cochran Ramona Lang Urielle Pennington ") >> &couchFindRange;
tst.test("couchdb.findKeys","Kermit Byrd,76,184 Owen Dillard,80,151 Nicole Jordan,75,150 ") >> &couchFindKeys;
tst.test("couchdb.retrieveDoc","{\"_local_seq\":1,\"age\":76,\"height\":184,\"name\":\"Kermit Byrd\"}") >> &couchRetrieveDocument;
tst.test("couchdb.caching","Kermit Byrd,76,184:0 Owen Dillard,80,151:0 Nicole Jordan,75,150:0 Kermit Byrd,76,184:1 Owen Dillard,80,151:1 Nicole Jordan,75,150:1 Kermit Byrd,76,184:1 Owen Dillard,80,151:1 Nicole Jordan,75,150:1 ") >> &couchCaching;
tst.test("couchdb.updateLocalView","Kermit Byrd,76,184 Owen Dillard,80,151 Nicole Jordan,75,150 ") >> &testLocalViewUpdate;
tst.test("couchdb.updateLocalView2","Ondra Novak,41,189 Owen Dillard,80,151 Nicole Jordan,75,150 ") >> &testLocalViewUpdate2;
tst.test("couchdb.updateLocalView3","Owen Dillard,80,151 Nicole Jordan,75,150 ") >> &testLocalViewUpdate3;
tst.test("couchdb.reduce","20:178 30:170 40:171 50:165 70:167 80:151 ") >> &couchReduce;
tst.test("couchdb.recreate","xxx") >> &testRecreate;
//defineTest test_couchCaching2("couchdb.caching2","Kermit Byrd,76,184 Owen Dillard,80,151 Nicole Jordan,75,150 Kermit Byrd,184,100 Owen Dillard,151,100 Nicole Jordan,150,100 Kermit Byrd,76,184 Nicole Jordan,75,150 ",&couchCaching2);
tst.test("couchdb.changesOneShot","1") >> &couchChangeSetOneShot;
tst.test("couchdb.changesWaiting","ok") >> &couchChangeSetWaitForData;
tst.test("couchdb.changesWaitingForThree","ok") >> &couchChangeSetWaitForData3;
tst.test("couchdb.changesStopWait","Welcome") >> &couchChangesStopWait;
tst.test("couchdb.getSeqNumber","ok") >> &couchGetSeqNumber;
tst.test("couchdb.attachments","text/plain-The quick brown fox jumps over the lazy dog") >> &couchStoreAndRetrieveAttachment;
tst.test("couchdb.large","100019100019100019100019100019100019100019100019100019100019") >> &couchLarge;
tst.test("couchdb.deleteDB","") >> &deleteDB;
}
}
| 25.421947 | 246 | 0.660323 | [
"vector"
] |
4871d7925d1d501e920e5cd7346b0e55b4fcea0e | 1,405 | cpp | C++ | code/56.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 23 | 2020-03-30T05:44:56.000Z | 2021-09-04T16:00:57.000Z | code/56.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 1 | 2020-05-10T15:04:05.000Z | 2020-06-14T01:21:44.000Z | code/56.cpp | Nightwish-cn/my_leetcode | 40f206e346f3f734fb28f52b9cde0e0041436973 | [
"MIT"
] | 6 | 2020-03-30T05:45:04.000Z | 2020-08-13T10:01:39.000Z | #include <bits/stdc++.h>
#define INF 2000000000
using namespace std;
typedef long long ll;
int read(){
int f = 1, x = 0;
char c = getchar();
while(c < '0' || c > '9'){if(c == '-') f = -f; c = getchar();}
while(c >= '0' && c <= '9')x = x * 10 + c - '0', c = getchar();
return f * x;
}
struct Interval {
int start;
int end;
Interval() : start(0), end(0) {}
Interval(int s, int e) : start(s), end(e) {}
};
class Solution {
public:
vector<Interval> merge(vector<Interval>& intervals) {
struct cmp{
bool operator ()(const Interval &i1, const Interval &i2){
if(i1.start == i2.start) return i1.end < i2.end;
return i1.start < i2.start;
}
};
int n = intervals.size();
vector<Interval> ans;
if(!n) return ans;
sort(intervals.begin(), intervals.end(), cmp());
int st = intervals[0].start, ed = intervals[0].end;
for (int i = 1; i < n; ++i){
if(intervals[i].start <= ed)
ed = max(ed, intervals[i].end);
else{
ans.push_back(Interval(st, ed));
st = intervals[i].start, ed = intervals[i].end;
}
}
ans.push_back(Interval(st, ed));
return ans;
}
};
Solution sol;
void init(){
}
void solve(){
// sol.convert();
}
int main(){
init();
solve();
return 0;
}
| 25.089286 | 69 | 0.499644 | [
"vector"
] |
48725ea626d3679862ec3095d2413ebafc461231 | 175 | hpp | C++ | include/border_mesh.hpp | yd-14/kurve | ec85f48df231f0bcc4ec93e07c6455fa38db6db6 | [
"MIT"
] | 2 | 2020-10-18T22:57:33.000Z | 2020-12-30T17:37:34.000Z | include/border_mesh.hpp | yd-14/kurve | ec85f48df231f0bcc4ec93e07c6455fa38db6db6 | [
"MIT"
] | 22 | 2020-12-17T07:25:49.000Z | 2021-01-09T20:56:14.000Z | include/border_mesh.hpp | yd-14/kurve | ec85f48df231f0bcc4ec93e07c6455fa38db6db6 | [
"MIT"
] | 2 | 2021-01-05T17:45:10.000Z | 2021-01-09T15:25:39.000Z | #ifndef BORDER_MESH_HPP
#define BORDER_MESH_HPP
#include "mesh.hpp"
class BorderMesh: public Mesh {
public:
BorderMesh();
virtual void draw() override;
};
#endif | 14.583333 | 33 | 0.714286 | [
"mesh"
] |
4875954dfb6ca3152191e1fe1d983aa0865bb96d | 1,735 | cpp | C++ | src/examples/using-with-cmake/ascent_render_example.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/examples/using-with-cmake/ascent_render_example.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | src/examples/using-with-cmake/ascent_render_example.cpp | srini009/ascent | 70558059dc3fe514206781af6e48715d8934c37c | [
"BSD-3-Clause"
] | null | null | null | //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_render_example.cpp
///
//-----------------------------------------------------------------------------
#include <ascent.hpp>
#include <conduit_blueprint.hpp>
#include <iostream>
using namespace ascent;
using namespace conduit;
int main(int argc, char **argv)
{
std::cout << ascent::about() << std::endl;
Ascent a;
// open ascent
a.open();
// create example mesh using conduit blueprint
Node n_mesh;
conduit::blueprint::mesh::examples::braid("hexs",
10,
10,
10,
n_mesh);
// publish mesh to ascent
a.publish(n_mesh);
// declare a scene to render the dataset
Node scenes;
scenes["s1/plots/p1/type"] = "pseudocolor";
scenes["s1/plots/p1/field"] = "braid";
// Set the output file name (ascent will add ".png")
scenes["s1/image_prefix"] = "out_ascent_render_3d";
// setup actions
Node actions;
Node &add_act = actions.append();
add_act["action"] = "add_scenes";
add_act["scenes"] = scenes;
// execute
a.execute(actions);
// close ascent
a.close();
}
| 27.539683 | 79 | 0.468012 | [
"mesh",
"render"
] |
4881eff1d332c1f780714fc891a1fc6c28cb98f6 | 513 | cc | C++ | zircon/system/ulib/fs/transaction/block_transaction_host.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | zircon/system/ulib/fs/transaction/block_transaction_host.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | zircon/system/ulib/fs/transaction/block_transaction_host.cc | zarelaky/fuchsia | 858cc1914de722b13afc2aaaee8a6bd491cd8d9a | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <zircon/assert.h>
#include <fs/transaction/block_transaction.h>
namespace fs {
zx_status_t TransactionHandler::RunRequests(
const std::vector<storage::BufferedOperation>& operations) {
// The actual operations are performed while building the requests.
ZX_DEBUG_ASSERT(operations.empty());
return ZX_OK;
}
} // namespace fs
| 27 | 73 | 0.756335 | [
"vector"
] |
48846db830a81f14a530437f4b55e403ee059f98 | 4,042 | cpp | C++ | English/Source/abearcs.cpp | bugsbycarlin/ABearCs | 3502b298d280df2948bfcc4954c5df71ed4162e3 | [
"MIT"
] | null | null | null | English/Source/abearcs.cpp | bugsbycarlin/ABearCs | 3502b298d280df2948bfcc4954c5df71ed4162e3 | [
"MIT"
] | null | null | null | English/Source/abearcs.cpp | bugsbycarlin/ABearCs | 3502b298d280df2948bfcc4954c5df71ed4162e3 | [
"MIT"
] | null | null | null | /*
BearsLoveHoney
Matthew Carlin
Copyright 2018
*/
#include "abearcs.h"
using namespace std;
using namespace Honey;
ABearCs::ABearCs() {
}
void ABearCs::loop() {
logic();
render();
}
void ABearCs::initialize() {
screen_width = hot_config.getInt("layout", "screen_width");
screen_height = hot_config.getInt("layout", "screen_height");
current_letter = -1;
last_letter = -1;
for (int i = 0; i < 26; i++) {
graphics.addImage(letters[i], "Art/" + letters[i] + ".png");
graphics.addImage(pictures[i], "Art/" + pictures[i] + ".png");
sound.addSound(letters[i], "Sound/" + letters[i] + "_" + pictures[i] + ".wav");
}
}
void ABearCs::logic() {
// Check and load configuration every 2 seconds
hot_config.checkAndUpdate();
// Set a bunch of variables from configuration
screen_color = hot_config.getString("layout", "screen_color");
picture_x = hot_config.getInt("layout", "picture_x");
picture_y = hot_config.getInt("layout", "picture_y");
text_x = hot_config.getInt("layout", "text_x");
text_y = hot_config.getInt("layout", "text_y");
tween_type = hot_config.getInt("animation", "tween_type");
float animation_duration = hot_config.getFloat("animation", "animation_duration");
float shake_duration = hot_config.getFloat("animation", "shake_duration");
int shake_width = hot_config.getInt("animation", "shake_width");
float key_swap_duration = hot_config.getFloat("input", "key_swap_duration");
float sound_volume = hot_config.getFloat("sound", "sound_volume");
float sound_lock_duration = hot_config.getFloat("sound", "sound_lock_duration");
sound.setSoundVolume(sound_volume);
if (current_letter == -1) {
timing.remove("sound_lock");
timing.lock("key_swap", key_swap_duration);
timing.lock("animation", animation_duration);
effects.makeTween("slide_last_letter", screen_height, 0, animation_duration);
effects.start("slide_last_letter");
last_letter = current_letter;
current_letter = 1;
}
// do stuff with input
for (int i = 0; i < 26; i++) {
if (input.keyDown(letters[i]) && !timing.locked("key_swap") && i != current_letter) {
timing.remove("sound_lock");
timing.lock("key_swap", key_swap_duration);
timing.lock("animation", animation_duration);
effects.makeTween("slide_last_letter", screen_height, 0, animation_duration);
effects.start("slide_last_letter");
last_letter = current_letter;
current_letter = i;
}
}
if (timing.locked("key_swap") && !timing.locked("animation") && !timing.locked("sound_lock")) {
timing.lock("sound_lock", sound_lock_duration);
sound.playSound(letters[current_letter], 1);
effects.makeShake("sound_shake", shake_width, shake_duration);
effects.start("sound_shake");
}
if (input.threeQuickKey("escape")) {
screenmanager.setQuit();
}
}
void ABearCs::render() {
// Clear the screen to a soft white color
graphics.clearScreen(screen_color);
// Switch to 2D drawing mode
graphics.draw2D();
// draw stuff
float x, y;
// Current picture
if (current_letter != -1) {
x = picture_x;
y = picture_y;
if (timing.locked("animation")) {
y += effects.tween("slide_last_letter", tween_type);
}
graphics.drawImage(pictures[current_letter], x, y);
x = text_x;
y = text_y;
if (timing.locked("animation")) {
y += effects.tween("slide_last_letter", tween_type);
}
if (timing.locked("key_swap")) {
x += effects.shake("sound_shake");
y += effects.shake("sound_shake");
}
graphics.drawImage(letters[current_letter], x, y);
}
// Last picture, if animating
if (timing.locked("animation") && last_letter != -1) {
x = picture_x;
y = picture_y - screen_height + effects.tween("slide_last_letter", tween_type);
graphics.drawImage(pictures[last_letter], x, y);
x = text_x;
y = text_y - screen_height + effects.tween("slide_last_letter", tween_type);
graphics.drawImage(letters[last_letter], x, y);
}
}
ABearCs::~ABearCs() {
} | 30.621212 | 97 | 0.675656 | [
"render"
] |
48852a31ce24ea37e0461fb2312c18668ddbd4a1 | 6,588 | cpp | C++ | libOTe/Tools/LDPC/LdpcSampler.cpp | ldr709/softspoken-implementation | a10ef32b81befc0832bdceb1584fec07c983ecee | [
"Unlicense"
] | 1 | 2021-07-15T03:08:47.000Z | 2021-07-15T03:08:47.000Z | libOTe/Tools/LDPC/LdpcSampler.cpp | DaneilNo1/libOTe | 8879e47d46672ccadce5bcb42ce6ded79c2cb70d | [
"Unlicense"
] | null | null | null | libOTe/Tools/LDPC/LdpcSampler.cpp | DaneilNo1/libOTe | 8879e47d46672ccadce5bcb42ce6ded79c2cb70d | [
"Unlicense"
] | 1 | 2022-02-07T03:24:53.000Z | 2022-02-07T03:24:53.000Z | #include "libOTe/Tools/LDPC/LdpcSampler.h"
#include "libOTe/Tools/LDPC/LdpcEncoder.h"
#include <fstream>
#include "libOTe/Tools/LDPC/Util.h"
#include <thread>
#ifdef ENABLE_ALGO994
extern "C" {
#include "libOTe/Tools/LDPC/Algo994/data_defs.h"
}
#endif
namespace osuCrypto
{
std::vector<i64> slopes_, ys_, lastYs_;
std::vector<double> yr_;
bool printDiag = false;
void sampleRegDiag(u64 rows, u64 gap, u64 weight, oc::PRNG& prng, PointList& points)
{
if (rows < gap * 2)
throw RTE_LOC;
auto cols = rows - gap;
std::vector<u64> rowWeights(cols);
std::vector<std::set<u64>> rowSets(rows - gap);
for (u64 c = 0; c < cols; ++c)
{
std::set<u64> s;
//auto remCols = cols - c;
for (u64 j = 0; j < gap; ++j)
{
auto rowIdx = c + j;
// how many remaining slots are there to the left (speial case at the start)
u64 remA = std::max<i64>(gap - rowIdx, 0);
// how many remaining slots there are to the right.
u64 remB = std::min<u64>(j, cols - c);
u64 rem = remA + remB;
auto& w = rowWeights[rowIdx % cols];
auto needed = (weight - w);
if (needed > rem)
throw RTE_LOC;
if (needed && needed == rem)
{
s.insert(rowIdx);
points.push_back({ rowIdx, c });
++w;
}
}
if (s.size() > weight)
throw RTE_LOC;
while (s.size() != weight)
{
auto j = (prng.get<u8>() % gap);
auto r = c + j;
auto& w = rowWeights[r % cols];
if (w != weight && s.insert(r).second)
{
++w;
points.push_back({ r, c });
}
}
for (auto ss : s)
{
rowSets[ss% cols].insert(c);
if (rowSets[ss % cols].size() > weight)
throw RTE_LOC;
}
if (c > gap && rowSets[c].size() != weight)
{
SparseMtx H(c + gap + 1, c + 1, points);
std::cout << H << std::endl << std::endl;
throw RTE_LOC;
}
}
if (printDiag)
{
//std::vector<std::vector<u64>> hh;
SparseMtx H(rows, cols, points);
std::cout << H << std::endl << std::endl;
std::cout << "{{\n";
for (u64 i = 0; i < cols; ++i)
{
std::cout << "{{ ";
bool first = true;
//hh.emplace_back();
for (u64 j = 0; j < (u64)H.row(i).size(); ++j)
{
auto c = H.row(i)[j];
c = (c + cols - 1 - i) % cols;
if (!first)
std::cout << ", ";
std::cout << c;
//hh[i].push_back(H.row(i)[j]);
first = false;
}
for (u64 j = 0; j < (u64)H.row(i + cols).size(); ++j)
{
auto c = H.row(i+cols)[j];
c = (c + cols - 1 - i) % cols;
if (!first)
std::cout << ", ";
std::cout << c;
//hh[i].push_back(H.row(i+cols)[j]);
first = false;
}
std::cout << "}},\n";
}
std::cout << "}}"<< std::endl;
//{
// u64 rowIdx = 0;
// for (auto row : hh)
// {
// std::set<u64> s;
// std::cout << "(";
// for (auto c : row)
// {
// std::cout << int(c) << " ";
// s.insert();
// }
// std::cout << std::endl << "{";
// for (auto c : s)
// std::cout << c << " ";
// std::cout << std::endl;
// ++rowIdx;
// }
//}
}
}
// sample a parity check which is approx triangular with.
// The diagonal will have fixed weight = dWeight.
// The other columns will have weight = weight.
void sampleRegTriangularBand(u64 rows, u64 cols,
u64 weight, u64 gap, u64 dWeight,
u64 diag, u64 dDiag,u64 period,
std::vector<u64> doubleBand,
bool trim, bool extend, bool randY,
oc::PRNG& prng, PointList& points)
{
//auto dHeight =;
assert(extend == false || trim == true);
assert(gap < rows);
assert(dWeight > 0);
assert(dWeight <= gap + 1);
if (trim == false)
throw RTE_LOC;
if (period == 0 || period > rows)
period = rows;
if (extend)
{
for (u64 i = 0; i < gap; ++i)
{
points.push_back({ rows - gap + i, cols - gap + i });
}
}
//auto b = trim ? cols - rows + gap : cols - rows;
auto b = cols - rows;
auto diagOffset = sampleFixedColWeight(rows, b, weight, diag, randY, prng, points);
u64 e = rows - gap;
auto e2 = cols - gap;
PointList diagPoints(period + gap, period);
sampleRegDiag(period + gap, gap, dWeight - 1, prng, diagPoints);
//std::cout << "cols " << cols << std::endl;
std::set<std::pair<u64, u64>> ss;
for (u64 i = 0; i < e; ++i)
{
points.push_back({ i, b + i });
if (b + i >= cols)
throw RTE_LOC;
//if (ss.insert({ i, b + i }));
for (auto db : doubleBand)
{
assert(db >= 1);
u64 j = db + gap + i;
if (j < rows)
points.push_back({ j, b + i });
}
}
auto blks = (e + period - 1) / (period);
for (u64 i = 0; i < blks; ++i)
{
auto ii = i * period;
for (auto p : diagPoints)
{
auto r = ii + p.mRow + 1;
auto c = ii + p.mCol + b;
if(r < rows && c < e2)
points.push_back({ r, c });
}
}
}
}
| 26.780488 | 92 | 0.378264 | [
"vector"
] |
488d1c66d9b2288b9a3c2699ca7d84481e07b105 | 2,978 | cpp | C++ | search/climbing_leaderboard/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | search/climbing_leaderboard/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | search/climbing_leaderboard/main.cpp | exbibyte/hr | 100514dfc2a1c9b5366c12ec0a75e889132a620e | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
vector<string> split_string(string);
// Complete the climbingLeaderboard function below.
vector<int> climbingLeaderboard(vector<int> scores, vector<int> alice) {
vector<int> rank(scores.size(),1);
int r = 1;
int v = scores[0];
for(int i = 1; i < scores.size(); ++i){
if(scores[i] == v){
rank[i] = r;
} else {
++r;
v = scores[i];
rank[i] = r;
}
}
vector<int> ret = {};
for(auto i: alice){
int l = 0;
int ri = scores.size();
while(l<ri){
int m = (ri+l)/2;
if(i == scores[m]){
ret.push_back(rank[m]);
break;
} else if(i < scores[m]){
l = m+1;
} else if(i > scores[m]){
ri = m;
}
}
if(l>=ri){
int index;
if(ri>=scores.size()){
index = scores.size();
}else{
index = ri;
}
if(index>=scores.size()){
ret.push_back(r+1);
}else{
ret.push_back(rank[ri]);
}
}
}
return ret;
}
int main()
{
// ofstream fout(getenv("OUTPUT_PATH"));
int scores_count;
cin >> scores_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string scores_temp_temp;
getline(cin, scores_temp_temp);
vector<string> scores_temp = split_string(scores_temp_temp);
vector<int> scores(scores_count);
for (int i = 0; i < scores_count; i++) {
int scores_item = stoi(scores_temp[i]);
scores[i] = scores_item;
}
int alice_count;
cin >> alice_count;
cin.ignore(numeric_limits<streamsize>::max(), '\n');
string alice_temp_temp;
getline(cin, alice_temp_temp);
vector<string> alice_temp = split_string(alice_temp_temp);
vector<int> alice(alice_count);
for (int i = 0; i < alice_count; i++) {
int alice_item = stoi(alice_temp[i]);
alice[i] = alice_item;
}
vector<int> result = climbingLeaderboard(scores, alice);
for (int i = 0; i < result.size(); i++) {
// fout << result[i];
cout << result[i];
if (i != result.size() - 1) {
// fout << "\n";
cout << "\n";
}
}
cout << "\n";
// fout << "\n";
// fout.close();
return 0;
}
vector<string> split_string(string input_string) {
string::iterator new_end = unique(input_string.begin(), input_string.end(), [] (const char &x, const char &y) {
return x == y and x == ' ';
});
input_string.erase(new_end, input_string.end());
while (input_string[input_string.length() - 1] == ' ') {
input_string.pop_back();
}
vector<string> splits;
char delimiter = ' ';
size_t i = 0;
size_t pos = input_string.find(delimiter);
while (pos != string::npos) {
splits.push_back(input_string.substr(i, pos - i));
i = pos + 1;
pos = input_string.find(delimiter, i);
}
splits.push_back(input_string.substr(i, min(pos, input_string.length()) - i + 1));
return splits;
}
| 20.39726 | 115 | 0.558764 | [
"vector"
] |
48937f179afc00f3bae742fe88527a042ca3a88d | 556 | cpp | C++ | 3]. Competitive Programming/09]. HackerRank/1]. Practice/02]. C++/1]. Introduction/_09)_Variable_Sized_Arrays.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 6,969 | 2021-05-29T11:38:30.000Z | 2022-03-31T19:31:49.000Z | 3]. Competitive Programming/09]. HackerRank/1]. Practice/02]. C++/1]. Introduction/_09)_Variable_Sized_Arrays.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 75 | 2021-06-15T07:59:43.000Z | 2022-02-22T14:21:52.000Z | 3]. Competitive Programming/09]. HackerRank/1]. Practice/02]. C++/1]. Introduction/_09)_Variable_Sized_Arrays.cpp | MLinesCode/The-Complete-FAANG-Preparation | 2d0c7e8940eb2a58caaf4e978e548c08dd1f9a52 | [
"MIT"
] | 1,524 | 2021-05-29T16:03:36.000Z | 2022-03-31T17:46:13.000Z | #include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int>> arr;
int n,q;
cin>>n>>q;
for(int i=0; i<n ; i++){
int e;
cin>>e;
vector<int> temp;
for(int j=0; j < e; j++){
int ele;
cin>>ele;
temp.push_back(ele);
}
arr.push_back(temp);
}
for(int i=0;i<q;i++){
int x,y;
cin>>x>>y;
cout<<arr[x][y]<<endl;
}
return 0;
}
| 15.444444 | 33 | 0.447842 | [
"vector"
] |
489492af74cf2f9d696f3071a04969b92a9f9866 | 42,685 | cpp | C++ | gnucash/qofbook.cpp | tkerns1965/tk_gnucash3.3-python | a62577482230766840ea04de342dfdd39af1c69c | [
"MIT"
] | null | null | null | gnucash/qofbook.cpp | tkerns1965/tk_gnucash3.3-python | a62577482230766840ea04de342dfdd39af1c69c | [
"MIT"
] | null | null | null | gnucash/qofbook.cpp | tkerns1965/tk_gnucash3.3-python | a62577482230766840ea04de342dfdd39af1c69c | [
"MIT"
] | null | null | null | /********************************************************************\
* qofbook.c -- dataset access (set of books of entities) *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License as *
* published by the Free Software Foundation; either version 2 of *
* the License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License*
* along with this program; if not, contact: *
* *
* Free Software Foundation Voice: +1-617-542-5942 *
* 51 Franklin Street, Fifth Floor Fax: +1-617-542-2652 *
* Boston, MA 02110-1301, USA gnu@gnu.org *
\********************************************************************/
/*
* FILE:
* qofbook.cpp
*
* FUNCTION:
* Encapsulate all the information about a QOF dataset.
*
* HISTORY:
* Created by Linas Vepstas December 1998
* Copyright (c) 1998-2001,2003 Linas Vepstas <linas@linas.org>
* Copyright (c) 2000 Dave Peticolas
* Copyright (c) 2007 David Hampton <hampton@employees.org>
*/
extern "C"
{
#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#ifdef GNC_PLATFORM_WINDOWS
/* Mingw disables the standard type macros for C++ without this override. */
#define __STDC_FORMAT_MACROS = 1
#endif
#include <inttypes.h>
}
#include "qof.h"
#include "qofevent-p.h"
#include "qofbackend.h"
#include "qofbook-p.h"
#include "qofid-p.h"
#include "qofobject-p.h"
#include "qofbookslots.h"
#include "kvp-frame.hpp"
// For GNC_ID_ROOT_ACCOUNT:
#include "AccountP.h"
static QofLogModule log_module = QOF_MOD_ENGINE;
#define AB_KEY "hbci"
#define AB_TEMPLATES "template-list"
enum
{
PROP_0,
// PROP_ROOT_ACCOUNT, /* Table */
// PROP_ROOT_TEMPLATE, /* Table */
/* keep trading accounts property, while adding book-currency, default gains
policy and default gains account properties, so that files prior to 2.7 can
be read/processed; GUI changed to use all four properties as of 2.7.
Trading accounts, on the one hand, and book-currency plus default-gains-
policy, and optionally, default gains account, on the other, are mutually
exclusive */
PROP_OPT_TRADING_ACCOUNTS, /* KVP */
/* Book currency and default gains policy properties only apply if currency
accounting method selected in GUI is 'book-currency'; both required and
both are exclusive with trading accounts */
PROP_OPT_BOOK_CURRENCY, /* KVP */
PROP_OPT_DEFAULT_GAINS_POLICY, /* KVP */
/* Default gains account property only applies if currency accounting method
selected in GUI is 'book-currency'; its use is optional but exclusive with
trading accounts */
PROP_OPT_DEFAULT_GAINS_ACCOUNT_GUID, /* KVP */
PROP_OPT_AUTO_READONLY_DAYS, /* KVP */
PROP_OPT_NUM_FIELD_SOURCE, /* KVP */
PROP_OPT_DEFAULT_BUDGET, /* KVP */
PROP_OPT_FY_END, /* KVP */
PROP_AB_TEMPLATES, /* KVP */
N_PROPERTIES /* Just a counter */
};
static void
qof_book_option_num_field_source_changed_cb (GObject *gobject,
GParamSpec *pspec,
gpointer user_data);
static void
qof_book_option_num_autoreadonly_changed_cb (GObject *gobject,
GParamSpec *pspec,
gpointer user_data);
// Use a #define for the GParam name to avoid typos
#define PARAM_NAME_NUM_FIELD_SOURCE "split-action-num-field"
#define PARAM_NAME_NUM_AUTOREAD_ONLY "autoreadonly-days"
QOF_GOBJECT_GET_TYPE(QofBook, qof_book, QOF_TYPE_INSTANCE, {});
QOF_GOBJECT_DISPOSE(qof_book);
QOF_GOBJECT_FINALIZE(qof_book);
static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
#undef G_PARAM_READWRITE
#define G_PARAM_READWRITE static_cast<GParamFlags>(G_PARAM_READABLE | G_PARAM_WRITABLE)
/* ====================================================================== */
/* constructor / destructor */
static void coll_destroy(gpointer col)
{
qof_collection_destroy((QofCollection *) col);
}
static void
qof_book_init (QofBook *book)
{
if (!book) return;
book->hash_of_collections = g_hash_table_new_full(
g_str_hash, g_str_equal,
(GDestroyNotify)qof_string_cache_remove, /* key_destroy_func */
coll_destroy); /* value_destroy_func */
qof_instance_init_data (&book->inst, QOF_ID_BOOK, book);
book->data_tables = g_hash_table_new (g_str_hash, g_str_equal);
book->data_table_finalizers = g_hash_table_new (g_str_hash, g_str_equal);
book->book_open = 'y';
book->read_only = FALSE;
book->session_dirty = FALSE;
book->version = 0;
book->cached_num_field_source_isvalid = FALSE;
book->cached_num_days_autoreadonly_isvalid = FALSE;
// Register a callback on this NUM_FIELD_SOURCE property of that object
// because it gets called quite a lot, so that its value must be stored in
// a bool member variable instead of a KVP lookup on each getter call.
g_signal_connect (G_OBJECT(book),
"notify::" PARAM_NAME_NUM_FIELD_SOURCE,
G_CALLBACK (qof_book_option_num_field_source_changed_cb),
book);
// Register a callback on this NUM_AUTOREAD_ONLY property of that object
// because it gets called quite a lot, so that its value must be stored in
// a bool member variable instead of a KVP lookup on each getter call.
g_signal_connect (G_OBJECT(book),
"notify::" PARAM_NAME_NUM_AUTOREAD_ONLY,
G_CALLBACK (qof_book_option_num_autoreadonly_changed_cb),
book);
}
static const std::string str_KVP_OPTION_PATH(KVP_OPTION_PATH);
static const std::string str_OPTION_SECTION_ACCOUNTS(OPTION_SECTION_ACCOUNTS);
static const std::string str_OPTION_NAME_TRADING_ACCOUNTS(OPTION_NAME_TRADING_ACCOUNTS);
static const std::string str_OPTION_NAME_AUTO_READONLY_DAYS(OPTION_NAME_AUTO_READONLY_DAYS);
static const std::string str_OPTION_NAME_NUM_FIELD_SOURCE(OPTION_NAME_NUM_FIELD_SOURCE);
static void
qof_book_get_property (GObject* object,
guint prop_id,
GValue* value,
GParamSpec* pspec)
{
QofBook *book;
gchar *key;
g_return_if_fail (QOF_IS_BOOK (object));
book = QOF_BOOK (object);
switch (prop_id)
{
case PROP_OPT_TRADING_ACCOUNTS:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_TRADING_ACCOUNTS});
break;
case PROP_OPT_BOOK_CURRENCY:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_BOOK_CURRENCY});
break;
case PROP_OPT_DEFAULT_GAINS_POLICY:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_GAINS_POLICY});
break;
case PROP_OPT_DEFAULT_GAINS_ACCOUNT_GUID:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_GAINS_LOSS_ACCT_GUID});
break;
case PROP_OPT_AUTO_READONLY_DAYS:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_AUTO_READONLY_DAYS});
break;
case PROP_OPT_NUM_FIELD_SOURCE:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_NUM_FIELD_SOURCE});
break;
case PROP_OPT_DEFAULT_BUDGET:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_BUDGET});
break;
case PROP_OPT_FY_END:
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {"fy_end"});
break;
case PROP_AB_TEMPLATES:
key = const_cast<char*>(AB_KEY "/" AB_TEMPLATES);
qof_instance_get_path_kvp (QOF_INSTANCE (book), value, {"AB_KEY", "AB_TEMPLATES"});
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
qof_book_set_property (GObject *object,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
QofBook *book;
gchar *key;
g_return_if_fail (QOF_IS_BOOK (object));
book = QOF_BOOK (object);
g_assert (qof_instance_get_editlevel(book));
switch (prop_id)
{
case PROP_OPT_TRADING_ACCOUNTS:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_TRADING_ACCOUNTS});
break;
case PROP_OPT_BOOK_CURRENCY:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_BOOK_CURRENCY});
break;
case PROP_OPT_DEFAULT_GAINS_POLICY:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_GAINS_POLICY});
break;
case PROP_OPT_DEFAULT_GAINS_ACCOUNT_GUID:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_GAINS_LOSS_ACCT_GUID});
break;
case PROP_OPT_AUTO_READONLY_DAYS:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_AUTO_READONLY_DAYS});
break;
case PROP_OPT_NUM_FIELD_SOURCE:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, str_OPTION_NAME_NUM_FIELD_SOURCE});
break;
case PROP_OPT_DEFAULT_BUDGET:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {str_KVP_OPTION_PATH,
str_OPTION_SECTION_ACCOUNTS, OPTION_NAME_DEFAULT_BUDGET});
break;
case PROP_OPT_FY_END:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {"fy_end"});
break;
case PROP_AB_TEMPLATES:
qof_instance_set_path_kvp (QOF_INSTANCE (book), value, {AB_KEY, AB_TEMPLATES});
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(object, prop_id, pspec);
break;
}
}
static void
qof_book_class_init (QofBookClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
gobject_class->dispose = qof_book_dispose;
gobject_class->finalize = qof_book_finalize;
gobject_class->get_property = qof_book_get_property;
gobject_class->set_property = qof_book_set_property;
g_object_class_install_property
(gobject_class,
PROP_OPT_TRADING_ACCOUNTS,
g_param_spec_string("trading-accts",
"Use Trading Accounts",
"Scheme true ('t') or NULL. If 't', then the book "
"uses trading accounts for managing multiple-currency "
"transactions.",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_BOOK_CURRENCY,
g_param_spec_string("book-currency",
"Select Book Currency",
"The reference currency used to manage multiple-currency "
"transactions when 'book-currency' currency accounting method "
"selected; requires valid default gains/loss policy.",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_DEFAULT_GAINS_POLICY,
g_param_spec_string("default-gains-policy",
"Select Default Gains Policy",
"The default policy to be used to calculate gains/losses on "
"dispositions of currencies/commodities other than "
"'book-currency' when 'book-currency' currency accounting "
"method selected; requires valid book-currency.",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_DEFAULT_GAINS_ACCOUNT_GUID,
g_param_spec_boxed("default-gain-loss-account-guid",
"Select Default Gain/Loss Account",
"The default account to be used for calculated gains/losses on "
"dispositions of currencies/commodities other than "
"'book-currency' when 'book-currency' currency accounting "
"method selected; requires valid book-currency.",
GNC_TYPE_GUID,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_NUM_FIELD_SOURCE,
g_param_spec_string(PARAM_NAME_NUM_FIELD_SOURCE,
"Use Split-Action in the Num Field",
"Scheme true ('t') or NULL. If 't', then the book "
"will put the split action value in the Num field.",
NULL,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_AUTO_READONLY_DAYS,
g_param_spec_double("autoreadonly-days",
"Transaction Auto-read-only Days",
"Prevent editing of transactions posted more than "
"this many days ago.",
0,
G_MAXDOUBLE,
0,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_DEFAULT_BUDGET,
g_param_spec_boxed("default-budget",
"Book Default Budget",
"The default Budget for this book.",
GNC_TYPE_GUID,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_OPT_FY_END,
g_param_spec_boxed("fy-end",
"Book Fiscal Year End",
"A GDate with a bogus year having the last Month and "
"Day of the Fiscal year for the book.",
G_TYPE_DATE,
G_PARAM_READWRITE));
g_object_class_install_property
(gobject_class,
PROP_AB_TEMPLATES,
g_param_spec_boxed("ab-templates",
"AQBanking Template List",
"A GList of AQBanking Templates",
GNC_TYPE_VALUE_LIST,
G_PARAM_READWRITE));
}
QofBook *
qof_book_new (void)
{
QofBook *book;
ENTER (" ");
book = static_cast<QofBook*>(g_object_new(QOF_TYPE_BOOK, NULL));
qof_object_book_begin (book);
qof_event_gen (&book->inst, QOF_EVENT_CREATE, NULL);
LEAVE ("book=%p", book);
return book;
}
static void
book_final (gpointer key, gpointer value, gpointer booq)
{
QofBookFinalCB cb = reinterpret_cast<QofBookFinalCB>(value);
QofBook *book = static_cast<QofBook*>(booq);
gpointer user_data = g_hash_table_lookup (book->data_tables, key);
(*cb) (book, key, user_data);
}
static void
qof_book_dispose_real (G_GNUC_UNUSED GObject *bookp)
{
}
static void
qof_book_finalize_real (G_GNUC_UNUSED GObject *bookp)
{
}
void
qof_book_destroy (QofBook *book)
{
GHashTable* cols;
if (!book) return;
ENTER ("book=%p", book);
book->shutting_down = TRUE;
qof_event_force (&book->inst, QOF_EVENT_DESTROY, NULL);
/* Call the list of finalizers, let them do their thing.
* Do this before tearing into the rest of the book.
*/
g_hash_table_foreach (book->data_table_finalizers, book_final, book);
qof_object_book_end (book);
g_hash_table_destroy (book->data_table_finalizers);
book->data_table_finalizers = NULL;
g_hash_table_destroy (book->data_tables);
book->data_tables = NULL;
/* qof_instance_release (&book->inst); */
/* Note: we need to save this hashtable until after we remove ourself
* from it, otherwise we'll crash in our dispose() function when we
* DO remove ourself from the collection but the collection had already
* been destroyed.
*/
cols = book->hash_of_collections;
g_object_unref (book);
g_hash_table_destroy (cols);
/*book->hash_of_collections = NULL;*/
LEAVE ("book=%p", book);
}
/* ====================================================================== */
gboolean
qof_book_session_not_saved (const QofBook *book)
{
if (!book) return FALSE;
return !qof_book_empty(book) && book->session_dirty;
}
void
qof_book_mark_session_saved (QofBook *book)
{
if (!book) return;
book->dirty_time = 0;
if (book->session_dirty)
{
/* Set the session clean upfront, because the callback will check. */
book->session_dirty = FALSE;
if (book->dirty_cb)
book->dirty_cb(book, FALSE, book->dirty_data);
}
}
void qof_book_mark_session_dirty (QofBook *book)
{
if (!book) return;
if (!book->session_dirty)
{
/* Set the session dirty upfront, because the callback will check. */
book->session_dirty = TRUE;
book->dirty_time = gnc_time (NULL);
if (book->dirty_cb)
book->dirty_cb(book, TRUE, book->dirty_data);
}
}
void
qof_book_print_dirty (const QofBook *book)
{
if (qof_book_session_not_saved(book))
PINFO("book is dirty.");
qof_book_foreach_collection
(book, (QofCollectionForeachCB)qof_collection_print_dirty, NULL);
}
time64
qof_book_get_session_dirty_time (const QofBook *book)
{
return book->dirty_time;
}
void
qof_book_set_dirty_cb(QofBook *book, QofBookDirtyCB cb, gpointer user_data)
{
if (book->dirty_cb)
PWARN("Already existing callback %p, will be overwritten by %p\n",
book->dirty_cb, cb);
book->dirty_data = user_data;
book->dirty_cb = cb;
}
/* ====================================================================== */
/* getters */
QofBackend *
qof_book_get_backend (const QofBook *book)
{
if (!book) return NULL;
return book->backend;
}
gboolean
qof_book_shutting_down (const QofBook *book)
{
if (!book) return FALSE;
return book->shutting_down;
}
/* ====================================================================== */
/* setters */
void
qof_book_set_backend (QofBook *book, QofBackend *be)
{
if (!book) return;
ENTER ("book=%p be=%p", book, be);
book->backend = be;
LEAVE (" ");
}
/* ====================================================================== */
/* Store arbitrary pointers in the QofBook for data storage extensibility */
/* XXX if data is NULL, we should remove the key from the hash table!
*/
void
qof_book_set_data (QofBook *book, const char *key, gpointer data)
{
if (!book || !key) return;
g_hash_table_insert (book->data_tables, (gpointer)key, data);
}
void
qof_book_set_data_fin (QofBook *book, const char *key, gpointer data, QofBookFinalCB cb)
{
if (!book || !key) return;
g_hash_table_insert (book->data_tables, (gpointer)key, data);
if (!cb) return;
g_hash_table_insert (book->data_table_finalizers, (gpointer)key,
reinterpret_cast<void*>(cb));
}
gpointer
qof_book_get_data (const QofBook *book, const char *key)
{
if (!book || !key) return NULL;
return g_hash_table_lookup (book->data_tables, (gpointer)key);
}
/* ====================================================================== */
gboolean
qof_book_is_readonly(const QofBook *book)
{
g_return_val_if_fail( book != NULL, TRUE );
return book->read_only;
}
void
qof_book_mark_readonly(QofBook *book)
{
g_return_if_fail( book != NULL );
book->read_only = TRUE;
}
gboolean
qof_book_empty(const QofBook *book)
{
if (!book) return TRUE;
auto root_acct_col = qof_book_get_collection (book, GNC_ID_ROOT_ACCOUNT);
return qof_collection_get_data(root_acct_col) == nullptr;
}
/* ====================================================================== */
QofCollection *
qof_book_get_collection (const QofBook *book, QofIdType entity_type)
{
QofCollection *col;
if (!book || !entity_type) return NULL;
col = static_cast<QofCollection*>(g_hash_table_lookup (book->hash_of_collections, entity_type));
if (!col)
{
col = qof_collection_new (entity_type);
g_hash_table_insert(
book->hash_of_collections,
qof_string_cache_insert(entity_type), col);
}
return col;
}
struct _iterate
{
QofCollectionForeachCB fn;
gpointer data;
};
static void
foreach_cb (G_GNUC_UNUSED gpointer key, gpointer item, gpointer arg)
{
struct _iterate *iter = static_cast<_iterate*>(arg);
QofCollection *col = static_cast<QofCollection*>(item);
iter->fn (col, iter->data);
}
void
qof_book_foreach_collection (const QofBook *book,
QofCollectionForeachCB cb, gpointer user_data)
{
struct _iterate iter;
g_return_if_fail (book);
g_return_if_fail (cb);
iter.fn = cb;
iter.data = user_data;
g_hash_table_foreach (book->hash_of_collections, foreach_cb, &iter);
}
/* ====================================================================== */
void qof_book_mark_closed (QofBook *book)
{
if (!book)
{
return;
}
book->book_open = 'n';
}
gint64
qof_book_get_counter (QofBook *book, const char *counter_name)
{
KvpFrame *kvp;
KvpValue *value;
if (!book)
{
PWARN ("No book!!!");
return -1;
}
if (!counter_name || *counter_name == '\0')
{
PWARN ("Invalid counter name.");
return -1;
}
/* Use the KVP in the book */
kvp = qof_instance_get_slots (QOF_INSTANCE (book));
if (!kvp)
{
PWARN ("Book has no KVP_Frame");
return -1;
}
value = kvp->get_slot({"counters", counter_name});
if (value)
{
/* found it */
return value->get<int64_t>();
}
else
{
/* New counter */
return 0;
}
}
gchar *
qof_book_increment_and_format_counter (QofBook *book, const char *counter_name)
{
KvpFrame *kvp;
KvpValue *value;
gint64 counter;
gchar* format;
gchar* result;
if (!book)
{
PWARN ("No book!!!");
return NULL;
}
if (!counter_name || *counter_name == '\0')
{
PWARN ("Invalid counter name.");
return NULL;
}
/* Get the current counter value from the KVP in the book. */
counter = qof_book_get_counter(book, counter_name);
/* Check if an error occurred */
if (counter < 0)
return NULL;
/* Increment the counter */
counter++;
/* Get the KVP from the current book */
kvp = qof_instance_get_slots (QOF_INSTANCE (book));
if (!kvp)
{
PWARN ("Book has no KVP_Frame");
return NULL;
}
/* Save off the new counter */
qof_book_begin_edit(book);
value = new KvpValue(counter);
delete kvp->set_path({"counters", counter_name}, value);
qof_instance_set_dirty (QOF_INSTANCE (book));
qof_book_commit_edit(book);
format = qof_book_get_counter_format(book, counter_name);
if (!format)
{
PWARN("Cannot get format for counter");
return NULL;
}
/* Generate a string version of the counter */
result = g_strdup_printf(format, counter);
g_free (format);
return result;
}
char *
qof_book_get_counter_format(const QofBook *book, const char *counter_name)
{
KvpFrame *kvp;
const char *user_format = NULL;
gchar *norm_format = NULL;
KvpValue *value;
gchar *error = NULL;
if (!book)
{
PWARN ("No book!!!");
return NULL;
}
if (!counter_name || *counter_name == '\0')
{
PWARN ("Invalid counter name.");
return NULL;
}
/* Get the KVP from the current book */
kvp = qof_instance_get_slots (QOF_INSTANCE (book));
if (!kvp)
{
PWARN ("Book has no KVP_Frame");
return NULL;
}
/* Get the format string */
value = kvp->get_slot({"counter_formats", counter_name});
if (value)
{
user_format = value->get<const char*>();
norm_format = qof_book_normalize_counter_format(user_format, &error);
if (!norm_format)
{
PWARN("Invalid counter format string. Format string: '%s' Counter: '%s' Error: '%s')", user_format, counter_name, error);
/* Invalid format string */
user_format = NULL;
g_free(error);
}
}
/* If no (valid) format string was found, use the default format
* string */
if (!norm_format)
{
/* Use the default format */
norm_format = g_strdup ("%.6" PRIi64);
}
return norm_format;
}
gchar *
qof_book_normalize_counter_format(const gchar *p, gchar **err_msg)
{
const gchar *valid_formats [] = {
G_GINT64_FORMAT,
"lli",
"I64i",
PRIi64,
"li",
NULL,
};
int i = 0;
gchar *normalized_spec = NULL;
while (valid_formats[i])
{
if (err_msg && *err_msg)
{
g_free (*err_msg);
*err_msg = NULL;
}
normalized_spec = qof_book_normalize_counter_format_internal(p, valid_formats[i], err_msg);
if (normalized_spec)
return normalized_spec; /* Found a valid format specifier, return */
i++;
}
return NULL;
}
gchar *
qof_book_normalize_counter_format_internal(const gchar *p,
const gchar *gint64_format, gchar **err_msg)
{
const gchar *conv_start, *base, *tmp = NULL;
gchar *normalized_str = NULL, *aux_str = NULL;
/* Validate a counter format. This is a very simple "parser" that
* simply checks for a single gint64 conversion specification,
* allowing all modifiers and flags that printf(3) specifies (except
* for the * width and precision, which need an extra argument). */
base = p;
/* Skip a prefix of any character except % */
while (*p)
{
/* Skip two adjacent percent marks, which are literal percent
* marks */
if (p[0] == '%' && p[1] == '%')
{
p += 2;
continue;
}
/* Break on a single percent mark, which is the start of the
* conversion specification */
if (*p == '%')
break;
/* Skip all other characters */
p++;
}
if (!*p)
{
if (err_msg)
*err_msg = g_strdup("Format string ended without any conversion specification");
return NULL;
}
/* Store the start of the conversion for error messages */
conv_start = p;
/* Skip the % */
p++;
/* See whether we have already reached the correct format
* specification (e.g. "li" on Unix, "I64i" on Windows). */
tmp = strstr(p, gint64_format);
if (!tmp)
{
if (err_msg)
*err_msg = g_strdup_printf("Format string doesn't contain requested format specifier: %s", gint64_format);
return NULL;
}
/* Skip any number of flag characters */
while (*p && (tmp != p) && strchr("#0- +'I", *p))
{
p++;
tmp = strstr(p, gint64_format);
}
/* Skip any number of field width digits,
* and precision specifier digits (including the leading dot) */
while (*p && (tmp != p) && strchr("0123456789.", *p))
{
p++;
tmp = strstr(p, gint64_format);
}
if (!*p)
{
if (err_msg)
*err_msg = g_strdup_printf("Format string ended during the conversion specification. Conversion seen so far: %s", conv_start);
return NULL;
}
/* See if the format string starts with the correct format
* specification. */
tmp = strstr(p, gint64_format);
if (tmp == NULL)
{
if (err_msg)
*err_msg = g_strdup_printf("Invalid length modifier and/or conversion specifier ('%.4s'), it should be: %s", p, gint64_format);
return NULL;
}
else if (tmp != p)
{
if (err_msg)
*err_msg = g_strdup_printf("Garbage before length modifier and/or conversion specifier: '%*s'", (int)(tmp - p), p);
return NULL;
}
/* Copy the string we have so far and add normalized format specifier for long int */
aux_str = g_strndup (base, p - base);
normalized_str = g_strconcat (aux_str, PRIi64, NULL);
g_free (aux_str);
/* Skip length modifier / conversion specifier */
p += strlen(gint64_format);
tmp = p;
/* Skip a suffix of any character except % */
while (*p)
{
/* Skip two adjacent percent marks, which are literal percent
* marks */
if (p[0] == '%' && p[1] == '%')
{
p += 2;
continue;
}
/* Break on a single percent mark, which is the start of the
* conversion specification */
if (*p == '%')
{
if (err_msg)
*err_msg = g_strdup_printf("Format string contains unescaped %% signs (or multiple conversion specifications) at '%s'", p);
g_free (normalized_str);
return NULL;
}
/* Skip all other characters */
p++;
}
/* Add the suffix to our normalized string */
aux_str = normalized_str;
normalized_str = g_strconcat (aux_str, tmp, NULL);
g_free (aux_str);
/* If we end up here, the string was valid, so return no error
* message */
return normalized_str;
}
/** Returns pointer to book-currency name for book, if one exists in the
* KVP, or NULL; does not validate contents nor determine if there is a valid
* default gain/loss policy, both of which are required, for the
* 'book-currency' currency accounting method to apply. Use instead
* 'gnc_book_get_book_currency_name' which does these validations. */
const gchar *
qof_book_get_book_currency_name (QofBook *book)
{
const gchar *opt = NULL;
qof_instance_get (QOF_INSTANCE (book),
"book-currency", &opt,
NULL);
return opt;
}
/** Returns pointer to default gain/loss policy for book, if one exists in the
* KVP, or NULL; does not validate contents nor determine if there is a valid
* book-currency, both of which are required, for the 'book-currency'
* currency accounting method to apply. Use instead
* 'gnc_book_get_default_gains_policy' which does these validations. */
const gchar *
qof_book_get_default_gains_policy (QofBook *book)
{
const gchar *opt = NULL;
qof_instance_get (QOF_INSTANCE (book),
"default-gains-policy", &opt,
NULL);
return opt;
}
/** Returns pointer to default gain/loss account GUID for book, if one exists in
* the KVP, or NULL; does not validate contents nor determine if there is a
* valid book-currency, both of which are required, for the 'book-currency'
* currency accounting method to apply. Use instead
* 'gnc_book_get_default_gain_loss_acct' which does these validations. */
GncGUID *
qof_book_get_default_gain_loss_acct_guid (QofBook *book)
{
GncGUID *guid = NULL;
qof_instance_get (QOF_INSTANCE (book),
"default-gain-loss-account-guid", &guid,
NULL);
return guid;
}
/* Determine whether this book uses trading accounts */
gboolean
qof_book_use_trading_accounts (const QofBook *book)
{
const char *opt = NULL;
qof_instance_get (QOF_INSTANCE (book),
"trading-accts", &opt,
NULL);
if (opt && opt[0] == 't' && opt[1] == 0)
return TRUE;
return FALSE;
}
/* Returns TRUE if this book uses split action field as the 'Num' field, FALSE
* if it uses transaction number field */
gboolean
qof_book_use_split_action_for_num_field (const QofBook *book)
{
g_assert(book);
if (!book->cached_num_field_source_isvalid)
{
// No cached value? Then do the expensive KVP lookup
gboolean result;
const char *opt = NULL;
qof_instance_get (QOF_INSTANCE (book),
PARAM_NAME_NUM_FIELD_SOURCE, &opt,
NULL);
if (opt && opt[0] == 't' && opt[1] == 0)
result = TRUE;
else
result = FALSE;
// We need to const_cast the "book" argument into a non-const pointer,
// but as we are dealing only with cache variables, I think this is
// understandable enough.
const_cast<QofBook*>(book)->cached_num_field_source = result;
const_cast<QofBook*>(book)->cached_num_field_source_isvalid = TRUE;
}
// Value is cached now. Use the cheap variable returning.
return book->cached_num_field_source;
}
// The callback that is called when the KVP option value of
// "split-action-num-field" changes, so that we mark the cached value as
// invalid.
static void
qof_book_option_num_field_source_changed_cb (GObject *gobject,
GParamSpec *pspec,
gpointer user_data)
{
QofBook *book = reinterpret_cast<QofBook*>(user_data);
g_return_if_fail(QOF_IS_BOOK(book));
book->cached_num_field_source_isvalid = FALSE;
}
gboolean qof_book_uses_autoreadonly (const QofBook *book)
{
g_assert(book);
return (qof_book_get_num_days_autoreadonly(book) != 0);
}
gint qof_book_get_num_days_autoreadonly (const QofBook *book)
{
g_assert(book);
if (!book->cached_num_days_autoreadonly_isvalid)
{
double tmp;
// No cached value? Then do the expensive KVP lookup
qof_instance_get (QOF_INSTANCE (book),
PARAM_NAME_NUM_AUTOREAD_ONLY, &tmp,
NULL);
const_cast<QofBook*>(book)->cached_num_days_autoreadonly = tmp;
const_cast<QofBook*>(book)->cached_num_days_autoreadonly_isvalid = TRUE;
}
// Value is cached now. Use the cheap variable returning.
return (gint) book->cached_num_days_autoreadonly;
}
GDate* qof_book_get_autoreadonly_gdate (const QofBook *book)
{
gint num_days;
GDate* result = NULL;
g_assert(book);
num_days = qof_book_get_num_days_autoreadonly(book);
if (num_days > 0)
{
result = gnc_g_date_new_today();
g_date_subtract_days(result, num_days);
}
return result;
}
// The callback that is called when the KVP option value of
// "autoreadonly-days" changes, so that we mark the cached value as
// invalid.
static void
qof_book_option_num_autoreadonly_changed_cb (GObject *gobject,
GParamSpec *pspec,
gpointer user_data)
{
QofBook *book = reinterpret_cast<QofBook*>(user_data);
g_return_if_fail(QOF_IS_BOOK(book));
book->cached_num_days_autoreadonly_isvalid = FALSE;
}
/* Note: this will fail if the book slots we're looking for here are flattened at some point !
* When that happens, this function can be removed. */
static Path opt_name_to_path (const char* opt_name)
{
Path result;
g_return_val_if_fail (opt_name, result);
auto opt_name_list = g_strsplit(opt_name, "/", -1);
for (int i=0; opt_name_list[i]; i++)
result.push_back (opt_name_list[i]);
g_strfreev (opt_name_list);
return result;
}
const char*
qof_book_get_string_option(const QofBook* book, const char* opt_name)
{
auto slot = qof_instance_get_slots(QOF_INSTANCE (book))->get_slot(opt_name_to_path(opt_name));
if (slot == nullptr)
return nullptr;
return slot->get<const char*>();
}
void
qof_book_set_string_option(QofBook* book, const char* opt_name, const char* opt_val)
{
qof_book_begin_edit(book);
auto frame = qof_instance_get_slots(QOF_INSTANCE(book));
auto opt_path = opt_name_to_path(opt_name);
if (opt_val && (*opt_val != '\0'))
delete frame->set(opt_path, new KvpValue(g_strdup(opt_val)));
else
delete frame->set(opt_path, nullptr);
qof_instance_set_dirty (QOF_INSTANCE (book));
qof_book_commit_edit(book);
}
void
qof_book_begin_edit (QofBook *book)
{
qof_begin_edit(&book->inst);
}
static void commit_err (G_GNUC_UNUSED QofInstance *inst, QofBackendError errcode)
{
PERR ("Failed to commit: %d", errcode);
// gnc_engine_signal_commit_error( errcode );
}
#define GNC_FEATURES "features"
static void
add_feature_to_hash (const gchar *key, KvpValue *value, GHashTable * user_data)
{
gchar *descr = g_strdup(value->get<const char*>());
g_hash_table_insert (user_data, (gchar*)key, descr);
}
GHashTable *
qof_book_get_features (QofBook *book)
{
KvpFrame *frame = qof_instance_get_slots (QOF_INSTANCE (book));
GHashTable *features = g_hash_table_new_full (g_str_hash, g_str_equal,
NULL, g_free);
auto slot = frame->get_slot({GNC_FEATURES});
if (slot != nullptr)
{
frame = slot->get<KvpFrame*>();
frame->for_each_slot_temp(&add_feature_to_hash, features);
}
return features;
}
void
qof_book_set_feature (QofBook *book, const gchar *key, const gchar *descr)
{
KvpFrame *frame = qof_instance_get_slots (QOF_INSTANCE (book));
KvpValue* feature = nullptr;
auto feature_slot = frame->get_slot({GNC_FEATURES});
if (feature_slot)
{
auto feature_frame = feature_slot->get<KvpFrame*>();
feature = feature_frame->get_slot({key});
}
if (feature == nullptr || g_strcmp0 (feature->get<const char*>(), descr))
{
qof_book_begin_edit (book);
delete frame->set_path({GNC_FEATURES, key}, new KvpValue(g_strdup (descr)));
qof_instance_set_dirty (QOF_INSTANCE (book));
qof_book_commit_edit (book);
}
}
void
qof_book_load_options (QofBook *book, GNCOptionLoad load_cb, GNCOptionDB *odb)
{
load_cb (odb, book);
}
void
qof_book_save_options (QofBook *book, GNCOptionSave save_cb,
GNCOptionDB* odb, gboolean clear)
{
/* Wrap this in begin/commit so that it commits only once instead of doing
* so for every option. Qof_book_set_option will take care of dirtying the
* book.
*/
qof_book_begin_edit (book);
save_cb (odb, book, clear);
qof_book_commit_edit (book);
}
static void noop (QofInstance *inst) {}
void
qof_book_commit_edit(QofBook *book)
{
if (!qof_commit_edit (QOF_INSTANCE(book))) return;
qof_commit_edit_part2 (&book->inst, commit_err, noop, noop/*lot_free*/);
}
/* Deal with the fact that some options are not in the "options" tree but rather
* in the "counters" tree */
static Path gslist_to_option_path (GSList *gspath)
{
Path tmp_path;
if (!gspath) return tmp_path;
Path path_v {str_KVP_OPTION_PATH};
for (auto item = gspath; item != nullptr; item = g_slist_next(item))
tmp_path.push_back(static_cast<const char*>(item->data));
if (tmp_path.front() == "counters")
return tmp_path;
path_v.insert(path_v.end(), tmp_path.begin(), tmp_path.end());
return path_v;
}
void
qof_book_set_option (QofBook *book, KvpValue *value, GSList *path)
{
KvpFrame *root = qof_instance_get_slots (QOF_INSTANCE (book));
qof_book_begin_edit (book);
delete root->set_path(gslist_to_option_path(path), value);
qof_instance_set_dirty (QOF_INSTANCE (book));
qof_book_commit_edit (book);
// Also, mark any cached value as invalid
book->cached_num_field_source_isvalid = FALSE;
}
KvpValue*
qof_book_get_option (QofBook *book, GSList *path)
{
KvpFrame *root = qof_instance_get_slots(QOF_INSTANCE (book));
return root->get_slot(gslist_to_option_path(path));
}
void
qof_book_options_delete (QofBook *book, GSList *path)
{
KvpFrame *root = qof_instance_get_slots(QOF_INSTANCE (book));
if (path != nullptr)
{
Path path_v {str_KVP_OPTION_PATH};
Path tmp_path;
for (auto item = path; item != nullptr; item = g_slist_next(item))
tmp_path.push_back(static_cast<const char*>(item->data));
delete root->set_path(gslist_to_option_path(path), nullptr);
}
else
delete root->set_path({str_KVP_OPTION_PATH}, nullptr);
}
/* QofObject function implementation and registration */
gboolean qof_book_register (void)
{
static QofParam params[] =
{
{ QOF_PARAM_GUID, QOF_TYPE_GUID, (QofAccessFunc)qof_entity_get_guid, NULL },
{ QOF_PARAM_KVP, QOF_TYPE_KVP, (QofAccessFunc)qof_instance_get_slots, NULL },
{ NULL },
};
qof_class_register (QOF_ID_BOOK, NULL, params);
return TRUE;
}
// ****************************************************************************
const GncGUID *
qof_book_get_default_budget_guid (QofBook *book)
{
GncGUID *guid = NULL;
g_return_val_if_fail(book, NULL);
qof_instance_get (QOF_INSTANCE (book),
"default-budget",
&guid,
NULL);
return guid;
}
void
qof_book_set_default_budget_guid (QofBook *book, const GncGUID *guid)
{
/*
qof_instance_set (QOF_INSTANCE (book),
"default-budget",
&guid,
NULL);
*/
qof_book_set_data (book, "default-budget", &guid);
}
// ****************************************************************************
/* ========================== END OF FILE =============================== */
| 31.455416 | 139 | 0.620546 | [
"object"
] |
48950e9dba1715363d22e95d56db5d1ce67d3cbf | 22,888 | cc | C++ | project/c++/mri/src/dataservice/test/ecm_harness.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/dataservice/test/ecm_harness.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | project/c++/mri/src/dataservice/test/ecm_harness.cc | jia57196/code41 | df611f84592afd453ccb2d22a7ad999ddb68d028 | [
"Apache-2.0"
] | null | null | null | /****************************************************************
* ecm_querytest.cc *
* Created on: Sep 19, 2013 *
* Author: lim55392 *
* Copyright (2013) JDS Uniphase. All rights reserved *
****************************************************************/
#include <iostream> // NOLINT
#include <stdlib.h>
#include <vector>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <log4cxx/xml/domconfigurator.h>
#define VERSION "1.0"
#define DISABLE_LOG4CXX
using namespace std;
#include "xtreme/cs/cs.h"
#include "xtreme/common/enrichdata_types.h"
#include "xtreme/dataservice/test_misch.h"
#include "xtreme/dataservice/ds_cachelite.h"
#include "xtreme/dataservice/internal/ds_enrichdata_impl.h"
// ------------------------- global definitions ------------------------------------------
typedef struct HarnessResultStruct {
uint64_t nCdrEdrInsertCount;
uint8_t nCdrCachePercentage, nEdrCachePercentage;
HarnessResultStruct()
: nCdrEdrInsertCount(0), nCdrCachePercentage(0), nEdrCachePercentage(0) {
}
}HarnessResultType;
typedef std::vector<HarnessResultType> HarnessResultsetType;
typedef struct ThreadOutputStruct {
double dCummulativeTime;
uint64_t nQueryTotal, nQueryHit;
}ThreadOutputType;
// ------------------------- global variables --------------------------------------------
static int nDbTableCount = 20;
static int nDbTableGranularity = 10 * 1000 * 1000;
static int nFeedingRate = 4000; // CDR+EDR
static int nTestDuration = 30; // seconds
static int nMaxInsrtThreadCount = 1;
static int nMinQueryThreadCount = 1;
static int nMaxQueryThreadCount = 16;
static int nMissRatio = 20; // in percentage
static int nResultInterval = 10;
static uint64_t nCallId = 1;
static uint64_t nCdrTableCacheCount = 0;
static uint64_t nEdrTableCacheCount = 0;
char szActivePath[1024] = { 0 };
CmdParam cmdparam;
boost::mutex mutex;
boost::thread* pQueryThread[128] = { NULL };
boost::thread* pInsertThread = NULL;
HarnessResultsetType* ThreadResultSet = NULL; // Harness resultset
ThreadOutputType* ThreadOutputSet = NULL; // Individual thread output
// ------------------------- support functions-------------------------------------------
string AccountingNumber(uint64_t nNumber);
void CreateResultsetOutput(uint32_t idx);
void InsertThreadProc(void);
void QueryThreadProc(uint32_t tid, ThreadOutputType* rpack);
// --------------------------- main routine ---------------------------------------------------------------------------
int main(int argc, char* argv[]) {
// Preparation for using CS
getcwd(szActivePath, sizeof(szActivePath));
chdir("..");
setenv("XTREME_LOG_PATH", "/var/log/mri", 1);
setenv("XTREME_LOG_CONFIG_FILE", "etc/Log4cxxConfig.xml", 1);
setenv("XTREME_COMPONENT_LIST_FILE", "etc/components_to_load.xml", 1);
setenv("XTREME_CONFIG_METADATA_FILE", "etc/config_schema.xml", 1);
setenv("XTREME_CONFIG_PARAMSTORE_FILE", "etc/config_parameters.xml", 1);
const std::string log4cxxConfigFname("etc/Log4cxxConfig.xml");
log4cxx::xml::DOMConfigurator::configure(log4cxxConfigFname.c_str());
// Initializing variable from configuration files -------------------------------------------------------
xtreme::cs::CS* theCS = new xtreme::cs::CS;
xtreme::config::CSParamAPI* pPAPI = (theCS!=NULL) ? theCS->getCSParamAPI() : NULL;
static String strStoragePath = pPAPI->get_string("DATASERVICE/ECACHE_PATH") + "-harness";
static String strStorageSchema = pPAPI->get_string("DATASERVICE/ECACHE_SCHEMA");
nCdrTableCacheCount = pPAPI->get_uint("DATASERVICE/ECACHE_CDRCACHE") * 1000;
nEdrTableCacheCount = pPAPI->get_uint("DATASERVICE/ECACHE_EDRCACHE") * 1000;
// Grabbing command-line parameters ---------------------------------------------------------------------
cmdparam.init(argc, argv);
if (cmdparam.find("-help") >= 0 || cmdparam.find("--help") >= 0) {
printf("Enrichment Cache utility for MRI - TestHarness module v%s\n", VERSION);
printf("Utility used to test and simulate query called into Enrichment Cache Manager\n\n");
printf("Usage: ecm_harness <option>\n");
printf("Available options:\n");
printf(" --feedrate Simulated insertion speed from CPP (def:%d)\n", nFeedingRate);
printf(" --duration Test duration for each loop seconds (def:%d)\n", nTestDuration);
printf(" --minqthread Min simultaneous query thread (def:%d)\n", nMinQueryThreadCount);
printf(" --maxqthread Max simultaneous query thread (def:%d)\n", nMaxQueryThreadCount);
printf(" --maxithread Max simultaneous insert thread (def:%d)\n", nMaxInsrtThreadCount);
printf(" --querymissratio Simulate missed query ratio (def:%d)\n", nMissRatio);
printf(" eg. value 0 means chance of 100%% hit rate\n");
printf(" value 20 means chance of 80%% hit rate\n");
printf(" value 100 means chance of 0%% hit rate\n");
printf("\nSample:\n");
printf(" ./ecm_harness --feedrate=4000 --duration=3600\n");
printf("running test harness using feed rate of 4000 and each thread running for 1 hour.\n");
return 0;
} else {
printf("Enrichment Cache utility for MRI - TestHarness module v%s\n", VERSION);
}
// Patching user parameters -----------------------------------------------------------------------------
int32_t index = cmdparam.find("--maxqthread");
if (index >= 0) {
nMaxQueryThreadCount = atoi(cmdparam[index].c_str());
if (nMaxQueryThreadCount > 1) {
nMaxQueryThreadCount &= 0x1F; // Maximum 32 threads
}
}
index = cmdparam.find("--minqthread");
if (index >= 0) {
nMinQueryThreadCount = atoi(cmdparam[index].c_str());
if (nMinQueryThreadCount > nMaxQueryThreadCount) {
int temp = nMinQueryThreadCount;
nMinQueryThreadCount = nMaxQueryThreadCount;
nMaxQueryThreadCount = temp;
}
if (nMinQueryThreadCount==0) {
nMinQueryThreadCount = 1;
}
}
index = cmdparam.find("--maxithread");
if (index >= 0) {
nMaxInsrtThreadCount = atoi(cmdparam[index].c_str());
if (nMaxInsrtThreadCount > 1) {
printf("MRI 1.0 supports only 1 insertion threads. Defaulted to 1\n");
}
nMaxInsrtThreadCount = 1;
}
index = cmdparam.find("--feedrate");
if (index >= 0) {
nFeedingRate = atoi(cmdparam[index].c_str());
}
index = cmdparam.find("--duration");
if (index >= 0) {
nTestDuration = atoi(cmdparam[index].c_str());
}
index = cmdparam.find("--querymissratio");
if (index >= 0) {
nMissRatio = atoi(cmdparam[index].c_str());
nMissRatio = (nMissRatio > 100) ? 100 : nMissRatio;
}
// Memory usage calculation
uint64_t nCdrMemoryConsumptionSize = (sizeof(xtreme::ecmCdrStruct) * nCdrTableCacheCount) / 1000;
uint64_t nEdrMemoryConsumptionSize = (sizeof(xtreme::ecmEdrStruct) * nEdrTableCacheCount) / 1000;
uint64_t nCDRParameterSize = 0;
nCDRParameterSize += sizeof(xtreme::cpp::IMSIType); // IMSI
nCDRParameterSize += sizeof(xtreme::cpp::IMEIType); // IMEI
nCDRParameterSize += sizeof(xtreme::cpp::MSISDNType) + 6; // MSISDN: + 6 average length
nCDRParameterSize += sizeof(xtreme::cpp::MCCType); // MCC
nCDRParameterSize += sizeof(xtreme::cpp::MNCType); // MNC
nCDRParameterSize += sizeof(xtreme::cpp::LACType); // LAC
nCDRParameterSize += sizeof(xtreme::cpp::RATType); // RAT
nCDRParameterSize += sizeof(xtreme::cpp::RACType); // RAC
nCDRParameterSize += sizeof(xtreme::cpp::SACType); // SAC
nCDRParameterSize += sizeof(xtreme::cpp::TACType); // TAC
nCDRParameterSize += sizeof(xtreme::cpp::CIType); // CI
nCDRParameterSize += sizeof(xtreme::cpp::ECIType); // ECI
nCdrMemoryConsumptionSize += (nCDRParameterSize * nCdrTableCacheCount) / 1000;
uint64_t nEDRParameterSize = 0;
nEDRParameterSize += sizeof(xtreme::cpp::APNType) + 24; // APN: size of string + 24 average lengths
nEDRParameterSize += sizeof(xtreme::cpp::PDNType); // PDN
nEDRParameterSize += sizeof(xtreme::cpp::EBIType); // EBI
nEDRParameterSize += sizeof(xtreme::cpp::QCIType); // QCI
nEDRParameterSize += sizeof(xtreme::cpp::NSAPIType); // NSAPI
nEdrMemoryConsumptionSize += (nEDRParameterSize * nEdrTableCacheCount) / 1000;
// Running test harness based on the configured configuration -----------------------------------------------------
cout << "Parameters:" << endl;
cout << "-StoragePath: '" << strStorageSchema << "' @ " << strStoragePath << endl;
cout << "-MaxECMTable(Cdr/Edr): " << nDbTableCount << " tables, spawn on every "
<< AccountingNumber(nDbTableGranularity) << " records" << endl;
cout << "-MaxCdrCacheRecordCount: " << AccountingNumber(nCdrTableCacheCount) << " records" << endl;
cout << "-MaxEdrCacheRecordCount: " << AccountingNumber(nEdrTableCacheCount) << " records" << endl;
cout << "-SimulatedFeedRate(CEDR/Sec): " << AccountingNumber(nFeedingRate) << " CDR & EDR" << endl;
cout << "-MinSimultaneousThread: " << nMinQueryThreadCount << endl;
cout << "-MaxSimultaneousThread: " << nMaxQueryThreadCount << endl;
cout << "-TestDurationOnEachThread(Sec): " << nTestDuration << endl;
cout << "-QueryMissRatio(%): " << nMissRatio << " *probability of miss in percentage" << endl;
cout << "MemoryConsumption:" << endl;
cout << "-SizeofEstimatedCdrRecord(B): " << sizeof(xtreme::ecmCdrStruct) + nCDRParameterSize << endl;
cout << "-SizeofEstimatedEdrRecord(B): " << sizeof(xtreme::ecmEdrStruct) + nEDRParameterSize << endl;
cout << "-MaxCdrCacheMemoryConsumption(KB): " << AccountingNumber(nCdrMemoryConsumptionSize) << endl;
cout << "-MaxEdrCacheMemoryConsumption(KB): " << AccountingNumber(nEdrMemoryConsumptionSize) << endl;
cout << endl;
char buffer[5 * 1024] = { 0 };
ThreadResultSet = new HarnessResultsetType[nMaxQueryThreadCount];
ThreadOutputSet = new ThreadOutputType[nMaxQueryThreadCount];
// Cleaning up past result
cout << "Removing existing database ..." << endl;
sprintf(buffer, "rm -rf %s", strStoragePath.c_str());
system(buffer);
cout << "Removing last resultset ..." << endl;
sprintf(buffer, "rm -f %s/harness_result_*_thread.txt", szActivePath);
system(buffer);
// Initialize CdrEdrCache -----------------------------------------------------------------------------------------
bool ECMDebug = false;
uint64_t nGranularityMB = nDbTableGranularity / 1000000;
xtreme::ds::CacheLite::GetInstance(strStoragePath, strStorageSchema, nGranularityMB, ECMDebug);
xtreme::ds::CacheLite::GetInstance()->SetLastSequenceInfo(0, 0);
// Starting Feeding thread (1 only for MRI version 1.0)
cout << "Starting CDR+EDR feed thread......@ " << nFeedingRate << "/s"<< endl;
pInsertThread = new boost::thread(InsertThreadProc);
// Starting quering thread
int nOneFifthDelay = nTestDuration / 5;
for (int32_t idx = 0; idx <= nMaxQueryThreadCount - nMinQueryThreadCount; ++idx) {
printf(":Perform simultaneous query with %2d threads ", nMinQueryThreadCount + idx);
// Running all threads
for (int32_t nthread = 0; nthread < (nMinQueryThreadCount + idx); ++nthread) {
pQueryThread[nthread] = new boost::thread(QueryThreadProc,
nMinQueryThreadCount + nthread, &ThreadOutputSet[nthread]);
}
// wait and printing responds
for (int32_t dly = 0; dly < nTestDuration; ++dly) {
if ((dly % nOneFifthDelay) == 0) {
printf(".");
fflush(stdout);
} else {
sleep(1);
}
}
// stop all of the threads.. time out reached
for (int32_t nthread = 0; nthread < (nMinQueryThreadCount + idx); ++nthread) {
pQueryThread[nthread]->interrupt();
delete pQueryThread[nthread];
}
sleep(2); // wait and ensure all thread stopped
// collect results
uint64_t nTotalHit = 0;
uint64_t nTotalCount = 0;
for (int32_t nthread = 0; nthread < (nMinQueryThreadCount + idx); ++nthread) {
nTotalHit += ThreadOutputSet[nthread].nQueryHit;
nTotalCount += ThreadOutputSet[nthread].nQueryTotal;
}
printf(" Query/Sec:%ld , HitRatio:%3.2f%%\n"
, nTotalCount / nTestDuration
,(nTotalHit * 100.0) / nTotalCount);
// CreateResultsetOutput(idx); // Printout Harness resultset
// xtreme::ds::CacheLite::GetInstance()->FlushECMTable();
}
cout << "Done..." << endl;
// cout << "Result written inside harness_result_xx_thread.txt" << endl;
if (pInsertThread != NULL) {
pInsertThread->interrupt();
delete pInsertThread;
pInsertThread = NULL;
}
delete[] ThreadResultSet;
delete[] ThreadOutputSet;
return 0;
}
// ------------------------------------------------------------------------------------------------
string AccountingNumber(uint64_t nNumber) {
string strFriendlyNumber;
uint64_t nDivider = 1000 * 1000 * 1000;
bool bFirst = false;
char buffer[16];
while (nDivider) {
uint32_t nValue = nNumber / nDivider;
if (nValue || bFirst) {
if (bFirst==false) {
sprintf(buffer, "%d,", nValue);
bFirst = true;
} else {
sprintf(buffer, "%03d,", nValue);
}
strFriendlyNumber += buffer;
}
nNumber %= nDivider;
nDivider /= 1000;
}
strFriendlyNumber.erase(strFriendlyNumber.end()-1);
return strFriendlyNumber;
}
// ------------------------------------------------------------------------------------------------
void CreateResultsetOutput(uint32_t idx) {
char buffer[5*1024];
sprintf(buffer, "%s/harness_result_%02d_thread.txt", szActivePath, idx+1);
FILE* handle = fopen(buffer, "wt");
if (handle) {
fprintf(handle, "CdrEdrInsertCount,CdrCachePercentage,EdrCachePercentage\n");
for (uint32_t tidx = 0; tidx < ThreadResultSet[idx].size(); ++tidx) {
fprintf(handle, "%ld,%d,%d\n",
ThreadResultSet[idx][tidx].nCdrEdrInsertCount,
ThreadResultSet[idx][tidx].nCdrCachePercentage,
ThreadResultSet[idx][tidx].nEdrCachePercentage);
}
fclose(handle);
}
}
// ------------------------------------------------------------------------------------------------
void InsertThreadProc(void) {
int32_t nInsertCount = 0;
uint32_t nRawtimer = 0;
try {
timespec ts;
HarnessResultType one;
clock_gettime(CLOCK_MONOTONIC, &ts);
nRawtimer = ts.tv_sec;
while (true) {
boost::this_thread::interruption_point();
clock_gettime(CLOCK_MONOTONIC, &ts);
if (nRawtimer + nResultInterval < ts.tv_sec) {
// update resultset
one.nCdrEdrInsertCount = nInsertCount;
ThreadResultSet[0].push_back(one);
// reset control variable
nRawtimer = ts.tv_sec;
} else {
// perform insertion if its not above insertion limit
if (nInsertCount < nFeedingRate) {
++nInsertCount;
// ECM Insertion code (CDR + EDR simultaneous insert)
xtreme::Timestamp nTimestamp = xtreme::Timestamp::SystemNow();
// CDR ----------------
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_CREATECALL, 0, 0, 0);
static uint64_t IMSI = 0xF310410349301813;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_IMSI,
reinterpret_cast<const uint8_t*>(&IMSI), sizeof(uint64_t));
static uint64_t IMEI = 0x0124180022658107;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_IMEI,
reinterpret_cast<const uint8_t*>(&IMEI), sizeof(uint64_t));
static uint64_t MSISDN = 0x18133349682F;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_MSISDN,
reinterpret_cast<const uint8_t*>(&MSISDN), 6 /*hardcode*/);
static uint8_t RAT = 0x01;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_RAT,
reinterpret_cast<const uint8_t*>(&RAT), sizeof(RAT));
static uint16_t MCC = 0xF310;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_MCC,
reinterpret_cast<const uint8_t*>(&MCC), sizeof(MCC));
static uint16_t MNC = 0xF410;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_MNC,
reinterpret_cast<const uint8_t*>(&MNC), sizeof(MNC));
static uint16_t LAC = 0xFEFF;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_LAC,
reinterpret_cast<const uint8_t*>(&LAC), sizeof(LAC));
static uint8_t RAC = 0xFF;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_RAC,
reinterpret_cast<const uint8_t*>(&RAC), sizeof(RAC));
static uint16_t SAC = 0x31B9;
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_SAC,
reinterpret_cast<const uint8_t*>(&SAC), sizeof(SAC));
xtreme::ds::CacheLite::GetInstance()->AddCdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_CLOSECALL, 0, 0, 0);
// EDR ----------------
xtreme::ds::CacheLite::GetInstance()->AddEdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_CREATECALL, xtreme::ds::CLPARAM_CDR,
reinterpret_cast<const uint8_t*>(&nCallId), sizeof(nCallId));
static uint8_t NSAPI = 0x01;
xtreme::ds::CacheLite::GetInstance()->AddEdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_NSAPI,
reinterpret_cast<const uint8_t*>(&NSAPI), sizeof(NSAPI));
static char szAPN[128] = { "internet.metropcs.mnc660.mcc311.gprs" };
xtreme::ds::CacheLite::GetInstance()->AddEdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_APN,
reinterpret_cast<const uint8_t*>(&szAPN), strlen(szAPN)+1);
static xtreme::cpp::PAAType PDN;
if (PDN.pdn_type != xtreme::cpp::PAA_IPV4) {
PDN.pdn_type = xtreme::cpp::PAA_IPV4;
PDN.ipv4_address = 0x0A0A0A;
PDN.ipv6_prefix = 0x00;
}
xtreme::ds::CacheLite::GetInstance()->AddEdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_ADDPARAM, xtreme::ds::CLPARAM_PDN,
reinterpret_cast<const uint8_t*>(&PDN), sizeof(PDN));
xtreme::ds::CacheLite::GetInstance()->AddEdrKnowledge(nTimestamp, nCallId,
xtreme::ds::CLEVENT_CLOSECALL, 0, 0, 0);
++nCallId;
}
}
}
} catch(...) {
}
}
// ------------------------------------------------------------------------------------------------
void QueryThreadProc(uint32_t tid, ThreadOutputType* rpack) {
try {
xtreme::Timestamp nTimestamp;
xtreme::ecmQueryStatus status;
xtreme::ecmQueryResultPtr Result;
xtreme::ds::CacheLite* pInstance = xtreme::ds::CacheLite::GetInstance();
rpack->nQueryHit = 0;
rpack->nQueryTotal = 0;
while (true) {
// Simulate shifting windows random (windows = size of memory cache)
// start offset define starts of random number to begin
uint64_t nStartOffsetCdr = (nCallId > nCdrTableCacheCount) ? nCallId - nCdrTableCacheCount : 0;
uint64_t nStartOffsetEdr = (nCallId > nEdrTableCacheCount) ? nCallId - nEdrTableCacheCount : 0;
uint64_t nRandomRangeCdr = (nCallId < nCdrTableCacheCount) ? nCallId : nCdrTableCacheCount;
uint64_t nRandomRangeEdr = (nCallId < nEdrTableCacheCount) ? nCallId : nEdrTableCacheCount;
// Adding miss query factor
nRandomRangeCdr = nRandomRangeCdr * ( 1 + nMissRatio / 100.0f);
uint64_t nRandomCdrId = (rand() % nRandomRangeCdr) + nStartOffsetCdr + 1;
uint64_t nRandomEdrId = (rand() % nRandomRangeEdr) + nStartOffsetEdr + 1;
// query enrichmentcache
status = pInstance->GetKnowledgeByCdrEdr(nTimestamp, nRandomCdrId, nRandomEdrId, Result);
if (status == xtreme::ecmStatusFound) rpack->nQueryHit++;
rpack->nQueryTotal++;
boost::this_thread::interruption_point();
}
} catch(...) {
}
}
| 49.327586 | 119 | 0.571216 | [
"vector"
] |
48a4ff2b310716ec367d5c0e7f59cb7c9390971b | 383 | cpp | C++ | array/kadane.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | array/kadane.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | array/kadane.cpp | Nilesh-Das/mustdogfg | bb39fe6eb9dd4964f97a7ab6d4e65e4c3994fc3f | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#define ll long long
using namespace std;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int n = 5;
vector<int> arr = {1,2,3,-2,5};
// kadane algo
int curr = 0, best = INT_MIN;
for(int i=0; i<n; i++) {
curr = max(arr[i], curr + arr[i]);
best = max(best, curr);
}
cout << best << '\n';
// return best;
return 0;
} | 17.409091 | 38 | 0.545692 | [
"vector"
] |
48b317e0ab28e47ee289f0c05e5acf64e8ea3eee | 1,435 | cpp | C++ | 3rd/byzauth/libbpka/test/test_clean_protoinit.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/byzauth/libbpka/test/test_clean_protoinit.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/byzauth/libbpka/test/test_clean_protoinit.cpp | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | /*
* test if the initialization and destruction is algrind clean
*/
#include "messageprocessor.h"
#include "byzantineauthenticationadapter.h"
#include <map>
#include <set>
#include <vector>
#include <string>
#include <iostream>
#include <cstring>
#include <sys/stat.h>
#include <sys/types.h>
#include <zlib.h>
int main()
{
std::cout << "IN MAIN" << std::endl;
ByzantineAuthenticationAdapter * adapter =
ByzantineAuthenticationAdapter::New( "example.conf" , // info for logging dir etc.
8 , // trusted group size
1000000, // expiry interval
300 ) ; // max payload
// there was an un init problem caused by lack of ini
// on time. does this solve the bug?
adapter->LocalTime(0) ;
adapter->LocalTime(10) ;
adapter->LocalTime(20) ;
peerid_t myid = "testid" ;
std::string filename = "./peerdata/" + myid + ".xml";
std::vector<peerid_t> tgs(10);
for( int i = 0; i < 10; i++ )
{
char name[16];
sprintf( name, "peer%d" , i ) ;
tgs[i] = name ;
}
if(!adapter->Init( 256 , myid, tgs, filename.c_str(), 40))
{
std::cerr << "can not init" << std::endl;
return false;
}
adapter->DeInit();
ByzantineAuthenticationAdapter::Delete(adapter);
}
| 23.916667 | 92 | 0.540767 | [
"vector"
] |
48cf1a482011a215916f33553a41ced594999c3e | 4,711 | hpp | C++ | cpp/subprojects/common/include/common/thresholds/coverage_state.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/include/common/thresholds/coverage_state.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | null | null | null | cpp/subprojects/common/include/common/thresholds/coverage_state.hpp | mrapp-ke/SyndromeLearner | ed18c282949bebbc8e1dd5d2ddfb0b224ee71293 | [
"MIT"
] | 1 | 2022-03-08T22:06:56.000Z | 2022-03-08T22:06:56.000Z | /*
* @author Michael Rapp (mrapp@ke.tu-darmstadt.de)
*/
#pragma once
#include "common/data/types.hpp"
#include <memory>
// Forward declarations
class IThresholdsSubset;
class SinglePartition;
class BiPartition;
class AbstractPrediction;
class Refinement;
/**
* Defines an interface for all classes that allow to keep track of the examples that are covered by a rule.
*/
class ICoverageState {
public:
virtual ~ICoverageState() { };
/**
* Creates and returns a deep copy of the coverage state.
*
* @return An unique pointer to an object of type `ICoverageState` that has been created
*/
virtual std::unique_ptr<ICoverageState> copy() const = 0;
/**
* Calculates and returns a quality score that assesses the quality of a rule's prediction for all examples that
* do not belong to the current sub-sample and are marked as covered.
*
* @param thresholdsSubset A reference to an object of type `IThresholdsSubset` that should be used to
* evaluate the prediction
* @param partition A reference to an object of type `SinglePartition` that provides access to the
* indices of the training examples that belong to the training set
* @param head A reference to an object of type `AbstractPrediction` that stores the scores that
* are predicted by the rule
* @return The calculated quality score
*/
virtual float64 evaluateOutOfSample(const IThresholdsSubset& thresholdsSubset, const SinglePartition& partition,
const AbstractPrediction& head) const = 0;
/**
* Calculates and returns a quality score that assesses the quality of a rule's prediction for all examples that
* do not belong to the current sub-sample and are marked as covered.
*
* @param thresholdsSubset A reference to an object of type `IThresholdsSubset` that should be used to
* evaluate the prediction
* @param partition A reference to an object of type `BiPartition` that provides access to the indices
* of the training examples that belong to the training set
* @param head A reference to an object of type `AbstractPrediction` that stores the scores that
* are predicted by the rule
* @return The calculated quality score
*/
virtual float64 evaluateOutOfSample(const IThresholdsSubset& thresholdsSubset, BiPartition& partition,
const AbstractPrediction& head) const = 0;
/**
* Recalculates the scores to be predicted by a refinement based on all examples in the training set that are
* marked as covered and updates the head of the refinement accordingly.
*
* @param thresholdsSubset A reference to an object of type `IThresholdsSubset` that should be used to
* recalculate the scores
* @param partition A reference to an object of type `SinglePartition` that provides access to the
* indices of the training examples that belong to the training set
* @param refinement A reference to an object of type `Refinement`, whose head should be updated
*/
virtual void recalculatePrediction(const IThresholdsSubset& thresholdsSubset, const SinglePartition& partition,
Refinement& refinement) const = 0;
/**
* Recalculates the scores to be predicted by a refinement based on all examples in the training set that are
* marked as covered and updates the head of the refinement accordingly.
*
* @param thresholdsSubset A reference to an object of type `IThresholdsSubset` that should be used to
* recalculate the scores
* @param partition A reference to an object of type `BiPartition` that provides access to the indices
* of the training examples that belong to the training set
* @param refinement A reference to an object of type `Refinement`, whose head should be updated
*/
virtual void recalculatePrediction(const IThresholdsSubset& thresholdsSubset, BiPartition& partition,
Refinement& refinement) const = 0;
};
| 52.344444 | 120 | 0.616005 | [
"object"
] |
48d49f1ee7517cac34c520eb2f3d53771f633f36 | 6,038 | cpp | C++ | clients/cpp-qt5/generated/client/OAIPipelineFolderImpl.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 23 | 2017-08-01T12:25:26.000Z | 2022-01-25T03:44:11.000Z | clients/cpp-qt5/generated/client/OAIPipelineFolderImpl.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 35 | 2017-06-14T03:28:15.000Z | 2022-02-14T10:25:54.000Z | clients/cpp-qt5/generated/client/OAIPipelineFolderImpl.cpp | PankTrue/swaggy-jenkins | aca35a7cca6e1fcc08bd399e05148942ac2f514b | [
"MIT"
] | 11 | 2017-08-31T19:00:20.000Z | 2021-12-19T12:04:12.000Z | /**
* Swaggy Jenkins
* Jenkins API clients generated from Swagger / Open API specification
*
* OpenAPI spec version: 1.1.1
* Contact: blah@cliffano.com
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
#include "OAIPipelineFolderImpl.h"
#include "OAIHelpers.h"
#include <QJsonDocument>
#include <QJsonArray>
#include <QObject>
#include <QDebug>
namespace OpenAPI {
OAIPipelineFolderImpl::OAIPipelineFolderImpl(QString json) {
init();
this->fromJson(json);
}
OAIPipelineFolderImpl::OAIPipelineFolderImpl() {
init();
}
OAIPipelineFolderImpl::~OAIPipelineFolderImpl() {
this->cleanup();
}
void
OAIPipelineFolderImpl::init() {
_class = new QString("");
m__class_isSet = false;
display_name = new QString("");
m_display_name_isSet = false;
full_name = new QString("");
m_full_name_isSet = false;
name = new QString("");
m_name_isSet = false;
organization = new QString("");
m_organization_isSet = false;
number_of_folders = 0;
m_number_of_folders_isSet = false;
number_of_pipelines = 0;
m_number_of_pipelines_isSet = false;
}
void
OAIPipelineFolderImpl::cleanup() {
if(_class != nullptr) {
delete _class;
}
if(display_name != nullptr) {
delete display_name;
}
if(full_name != nullptr) {
delete full_name;
}
if(name != nullptr) {
delete name;
}
if(organization != nullptr) {
delete organization;
}
}
OAIPipelineFolderImpl*
OAIPipelineFolderImpl::fromJson(QString json) {
QByteArray array (json.toStdString().c_str());
QJsonDocument doc = QJsonDocument::fromJson(array);
QJsonObject jsonObject = doc.object();
this->fromJsonObject(jsonObject);
return this;
}
void
OAIPipelineFolderImpl::fromJsonObject(QJsonObject pJson) {
::OpenAPI::setValue(&_class, pJson["_class"], "QString", "QString");
::OpenAPI::setValue(&display_name, pJson["displayName"], "QString", "QString");
::OpenAPI::setValue(&full_name, pJson["fullName"], "QString", "QString");
::OpenAPI::setValue(&name, pJson["name"], "QString", "QString");
::OpenAPI::setValue(&organization, pJson["organization"], "QString", "QString");
::OpenAPI::setValue(&number_of_folders, pJson["numberOfFolders"], "qint32", "");
::OpenAPI::setValue(&number_of_pipelines, pJson["numberOfPipelines"], "qint32", "");
}
QString
OAIPipelineFolderImpl::asJson ()
{
QJsonObject obj = this->asJsonObject();
QJsonDocument doc(obj);
QByteArray bytes = doc.toJson();
return QString(bytes);
}
QJsonObject
OAIPipelineFolderImpl::asJsonObject() {
QJsonObject obj;
if(_class != nullptr && *_class != QString("")){
toJsonValue(QString("_class"), _class, obj, QString("QString"));
}
if(display_name != nullptr && *display_name != QString("")){
toJsonValue(QString("displayName"), display_name, obj, QString("QString"));
}
if(full_name != nullptr && *full_name != QString("")){
toJsonValue(QString("fullName"), full_name, obj, QString("QString"));
}
if(name != nullptr && *name != QString("")){
toJsonValue(QString("name"), name, obj, QString("QString"));
}
if(organization != nullptr && *organization != QString("")){
toJsonValue(QString("organization"), organization, obj, QString("QString"));
}
if(m_number_of_folders_isSet){
obj.insert("numberOfFolders", QJsonValue(number_of_folders));
}
if(m_number_of_pipelines_isSet){
obj.insert("numberOfPipelines", QJsonValue(number_of_pipelines));
}
return obj;
}
QString*
OAIPipelineFolderImpl::getClass() {
return _class;
}
void
OAIPipelineFolderImpl::setClass(QString* _class) {
this->_class = _class;
this->m__class_isSet = true;
}
QString*
OAIPipelineFolderImpl::getDisplayName() {
return display_name;
}
void
OAIPipelineFolderImpl::setDisplayName(QString* display_name) {
this->display_name = display_name;
this->m_display_name_isSet = true;
}
QString*
OAIPipelineFolderImpl::getFullName() {
return full_name;
}
void
OAIPipelineFolderImpl::setFullName(QString* full_name) {
this->full_name = full_name;
this->m_full_name_isSet = true;
}
QString*
OAIPipelineFolderImpl::getName() {
return name;
}
void
OAIPipelineFolderImpl::setName(QString* name) {
this->name = name;
this->m_name_isSet = true;
}
QString*
OAIPipelineFolderImpl::getOrganization() {
return organization;
}
void
OAIPipelineFolderImpl::setOrganization(QString* organization) {
this->organization = organization;
this->m_organization_isSet = true;
}
qint32
OAIPipelineFolderImpl::getNumberOfFolders() {
return number_of_folders;
}
void
OAIPipelineFolderImpl::setNumberOfFolders(qint32 number_of_folders) {
this->number_of_folders = number_of_folders;
this->m_number_of_folders_isSet = true;
}
qint32
OAIPipelineFolderImpl::getNumberOfPipelines() {
return number_of_pipelines;
}
void
OAIPipelineFolderImpl::setNumberOfPipelines(qint32 number_of_pipelines) {
this->number_of_pipelines = number_of_pipelines;
this->m_number_of_pipelines_isSet = true;
}
bool
OAIPipelineFolderImpl::isSet(){
bool isObjectUpdated = false;
do{
if(_class != nullptr && *_class != QString("")){ isObjectUpdated = true; break;}
if(display_name != nullptr && *display_name != QString("")){ isObjectUpdated = true; break;}
if(full_name != nullptr && *full_name != QString("")){ isObjectUpdated = true; break;}
if(name != nullptr && *name != QString("")){ isObjectUpdated = true; break;}
if(organization != nullptr && *organization != QString("")){ isObjectUpdated = true; break;}
if(m_number_of_folders_isSet){ isObjectUpdated = true; break;}
if(m_number_of_pipelines_isSet){ isObjectUpdated = true; break;}
}while(false);
return isObjectUpdated;
}
}
| 26.482456 | 100 | 0.683339 | [
"object"
] |
48d8a552537a6775cad00cb51cb014e18190c006 | 11,449 | cpp | C++ | src/server/cmd_keys.cpp | jianqingdu/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 94 | 2017-11-30T03:17:58.000Z | 2022-03-29T13:43:07.000Z | src/server/cmd_keys.cpp | flike/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 9 | 2017-12-11T03:12:31.000Z | 2020-04-20T13:04:00.000Z | src/server/cmd_keys.cpp | jianqingdu/kedis | 97ac63d8d96c5cda69c878ef20f04eb8efb4b396 | [
"MIT"
] | 19 | 2017-12-01T17:22:15.000Z | 2022-01-10T01:39:39.000Z | //
// cmd_keys.cpp
// kedis
//
// Created by ziteng on 17/7/25.
// Copyright © 2017年 mgj. All rights reserved.
//
#include "cmd_keys.h"
#include "db_util.h"
#include "encoding.h"
void del_command(ClientConn* conn, const vector<string>& cmd_vec)
{
int del_cnt = 0;
int db_idx = conn->GetDBIndex();
int cmd_size = (int)cmd_vec.size();
set<string> keys;
for (int i = 1; i < cmd_size; i++) {
keys.insert(cmd_vec[i]);
}
lock_keys(db_idx, keys);
for (int i = 1; i < (int)cmd_vec.size(); i++) {
MetaData mdata;
int ret = expire_key_if_needed(db_idx, cmd_vec[i], mdata);
if (ret == kExpireKeyExist) {
delete_key(db_idx, cmd_vec[i], mdata.ttl, mdata.type);
del_cnt++;
}
}
if (del_cnt > 0) {
g_server.binlog.Store(db_idx, conn->GetCurReqCommand());
}
unlock_keys(db_idx, keys);
conn->SendInteger(del_cnt);
}
void exists_command(ClientConn* conn, const vector<string>& cmd_vec)
{
int db_idx = conn->GetDBIndex();
MetaData mdata;
KeyLockGuard lock_guard(db_idx, cmd_vec[1]);
int ret = expire_key_if_needed(db_idx, cmd_vec[1], mdata);
if (ret == kExpireDBError) {
conn->SendError("db error");
} else if (ret == kExpireKeyNotExist) {
conn->SendInteger(0);
} else {
conn->SendInteger(1);
}
}
static void generic_ttl_command(ClientConn* conn, const vector<string>& cmd_vec, bool output_ms)
{
int db_idx = conn->GetDBIndex();
MetaData mdata;
uint64_t now = get_tick_count();
KeyLockGuard lock_guard(db_idx, cmd_vec[1]);
int ret = expire_key_if_needed(db_idx, cmd_vec[1], mdata);
if (ret == kExpireDBError) {
conn->SendError("db error");
} else if (ret == kExpireKeyNotExist) {
conn->SendInteger(-2);
} else {
if (mdata.ttl == 0) {
conn->SendInteger(-1);
} else {
int64_t expire_ttl = mdata.ttl - now;
if (!output_ms) {
expire_ttl = (expire_ttl + 500) / 1000;
}
conn->SendInteger(expire_ttl);
}
}
}
void ttl_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_ttl_command(conn, cmd_vec, false);
}
void pttl_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_ttl_command(conn, cmd_vec, true);
}
void type_command(ClientConn* conn, const vector<string>& cmd_vec)
{
int db_idx = conn->GetDBIndex();
MetaData mdata;
KeyLockGuard lock_guard(db_idx, cmd_vec[1]);
int ret = expire_key_if_needed(db_idx, cmd_vec[1], mdata);
if (ret == kExpireDBError) {
conn->SendError("db error");
} else if (ret == kExpireKeyNotExist) {
conn->SendSimpleString("none");
} else {
string name = get_type_name(mdata.type);
conn->SendSimpleString(name);
}
}
static void generic_expire_command(ClientConn* conn, const vector<string>& cmd_vec, uint64_t base_time, bool second_unit)
{
unsigned long ttl;
if (get_ulong_from_string(cmd_vec[2], ttl) == CODE_ERROR) {
conn->SendError("value is not an integer or out of range");
return;
}
int db_idx = conn->GetDBIndex();
const string& key = cmd_vec[1];
MetaData mdata;
KeyLockGuard lock_guard(db_idx, key);
int ret = expire_key_if_needed(db_idx, key, mdata);
if (ret == kExpireDBError) {
conn->SendError("db error");
} else if (ret == kExpireKeyNotExist) {
conn->SendInteger(0);
} else {
if (second_unit) {
ttl *= 1000;
}
ttl += base_time;
if (ttl <= get_tick_count()) {
delete_key(db_idx, key, mdata.ttl, mdata.type);
conn->SendInteger(1);
return;
}
rocksdb::WriteBatch batch;
if (mdata.ttl != 0) {
del_ttl_data(db_idx, mdata.ttl, key, &batch);
} else {
g_server.ttl_key_count_vec[db_idx]++;
}
if (mdata.type == KEY_TYPE_STRING) {
put_kv_data(db_idx, key, mdata.value, ttl, &batch);
} else if (mdata.type == KEY_TYPE_LIST) {
put_meta_data(db_idx, mdata.type, key, ttl, mdata.count, mdata.head_seq, mdata.tail_seq,
mdata.current_seq, &batch);
} else {
put_meta_data(db_idx, mdata.type, key, ttl, mdata.count, &batch);
}
put_ttl_data(db_idx, ttl, key, mdata.type, &batch);
DB_BATCH_UPDATE(batch)
g_server.binlog.Store(db_idx, conn->GetCurReqCommand());
conn->SendInteger(1);
}
}
void expire_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_expire_command(conn, cmd_vec, get_tick_count(), true);
}
void expireat_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_expire_command(conn, cmd_vec, 0, true);
}
void pexpire_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_expire_command(conn, cmd_vec, get_tick_count(), false);
}
void pexpireat_command(ClientConn* conn, const vector<string>& cmd_vec)
{
generic_expire_command(conn, cmd_vec, 0, false);
}
void persist_command(ClientConn* conn, const vector<string>& cmd_vec)
{
int db_idx = conn->GetDBIndex();
MetaData mdata;
rocksdb::WriteBatch batch;
KeyLockGuard lock_guard(db_idx, cmd_vec[1]);
int ret = expire_key_if_needed(db_idx, cmd_vec[1], mdata);
if (ret == kExpireDBError) {
conn->SendError("db error");
} else if (ret == kExpireKeyNotExist) {
conn->SendInteger(0);
} else {
if (mdata.ttl != 0) {
g_server.ttl_key_count_vec[db_idx]--;
del_ttl_data(db_idx, mdata.ttl, cmd_vec[1], &batch);
if (mdata.type == KEY_TYPE_STRING) {
put_kv_data(db_idx, cmd_vec[1], mdata.value, 0, &batch);
} else if (mdata.type == KEY_TYPE_LIST) {
put_meta_data(db_idx, mdata.type, cmd_vec[1], 0, mdata.count, mdata.head_seq, mdata.tail_seq,
mdata.current_seq, &batch);
} else {
put_meta_data(db_idx, mdata.type, cmd_vec[1], 0, mdata.count, &batch);
}
DB_BATCH_UPDATE(batch)
g_server.binlog.Store(db_idx, conn->GetCurReqCommand());
conn->SendInteger(1);
} else {
conn->SendInteger(0);
}
}
}
// get a random key from the first 64 keys
void randomkey_command(ClientConn* conn, const vector<string>& cmd_vec)
{
EncodeKey key_prefix(KEY_TYPE_META, "");
rocksdb::Slice encode_prefix = key_prefix.GetEncodeKey();
int db_idx = conn->GetDBIndex();
rocksdb::ColumnFamilyHandle* cf_handle = g_server.cf_handles_map[db_idx];
rocksdb::Iterator* it = g_server.db->NewIterator(g_server.read_option, cf_handle);
vector<string> keys;
int seek_cnt = 0;
for (it->Seek(encode_prefix); it->Valid() && (int)keys.size() < 64; it->Next(), seek_cnt++) {
if (it->key()[0] != KEY_TYPE_META) {
break;
}
string encode_key = it->key().ToString();
string key;
int ret = DecodeKey::Decode(encode_key, KEY_TYPE_META, key);
if (ret == kDecodeErrorType) {
break;
}
ByteStream stream((uchar_t*)it->value().data(), (uint32_t)it->value().size());
try {
uint8_t type;
uint64_t ttl;
stream >> type;
stream >> ttl;
if (!ttl || ttl > get_tick_count()) {
keys.push_back(key);
}
} catch (ParseException& ex) {
conn->SendError("db error");
delete it;
return;
}
}
delete it;
if (keys.empty()) {
conn->SendRawResponse(kNullBulkString);
} else {
int rand_idx = rand() % (int)keys.size();
conn->SendBulkString(keys[rand_idx]);
}
}
void keys_command(ClientConn* conn, const vector<string>& cmd_vec)
{
const string& pattern = cmd_vec[1];
int pattern_size = (int)pattern.size();
int idx = 0;
for (; idx < pattern_size; idx++) {
char ch = pattern.at(idx);
if (ch == '*' || ch == '?' || ch == '[' || ch == '\\') {
break;
}
}
// extract normal pattern to reduce key scan range
string prefix = pattern.substr(0, idx);
EncodeKey key_prefix(KEY_TYPE_META, prefix);
rocksdb::Slice encode_prefix = key_prefix.GetEncodeKey();
int db_idx = conn->GetDBIndex();
ScanKeyGuard scan_key_guard(db_idx);
rocksdb::ColumnFamilyHandle* cf_handle = g_server.cf_handles_map[db_idx];
rocksdb::Iterator* it = g_server.db->NewIterator(g_server.read_option, cf_handle);
vector<string> keys;
for (it->Seek(encode_prefix); it->Valid(); it->Next()) {
if (!it->key().starts_with(encode_prefix)) {
break;
}
string encode_key = it->key().ToString();
string key;
int ret = DecodeKey::Decode(encode_key, KEY_TYPE_META, key);
if (ret == kDecodeErrorType) {
break;
}
if (!stringmatchlen(pattern.c_str(), (int)pattern.size(), key.c_str(), (int)key.size(), 0)) {
continue;
}
ByteStream stream((uchar_t*)it->value().data(), (uint32_t)it->value().size());
try {
uint8_t type;
uint64_t ttl;
stream >> type;
stream >> ttl;
if (!ttl || ttl > get_tick_count()) {
keys.push_back(key);
}
} catch (ParseException& ex) {
conn->SendError("db error");
delete it;
return;
}
}
delete it;
conn->SendArray(keys);
}
// SCAN cursor [MATCH pattern] [COUNT count]
// cursor is a string, that is diffreret from Redis scan command
void scan_command(ClientConn* conn, const vector<string>& cmd_vec)
{
long count = 10;
string pattern;
if (parse_scan_param(conn, cmd_vec, 2, pattern, count) == CODE_ERROR) {
return;
}
int db_idx = conn->GetDBIndex();
EncodeKey cursor_key(KEY_TYPE_META, cmd_vec[1]);
ScanKeyGuard scan_key_guard(db_idx);
rocksdb::ColumnFamilyHandle* cf_handle = g_server.cf_handles_map[db_idx];
rocksdb::Iterator* it = g_server.db->NewIterator(g_server.read_option, cf_handle);
string cursor;
vector<string> keys;
for (it->Seek(cursor_key.GetEncodeKey()); it->Valid(); it->Next()) {
if (it->key()[0] != KEY_TYPE_META) {
break;
}
string encode_key = it->key().ToString();
string key;
if (DecodeKey::Decode(encode_key, KEY_TYPE_META, key) != kDecodeOK) {
conn->SendError("invalid meta key");
delete it;
return;
}
if ((long)keys.size() >= count) {
cursor = key;
break;
}
if (pattern.empty()) {
keys.push_back(key);
} else {
if (stringmatchlen(pattern.c_str(), (int)pattern.size(), key.c_str(), (int)key.size(), 0)) {
keys.push_back(key);
}
}
}
delete it;
string start_resp = "*2\r\n";
conn->SendRawResponse(start_resp);
conn->SendBulkString(cursor);
conn->SendArray(keys);
}
| 30.449468 | 121 | 0.576819 | [
"vector"
] |
48da8fdf1ea53a18de0a45c7b373e3c1fa570e3f | 1,519 | cpp | C++ | kattis/cake.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 3 | 2020-06-25T21:04:02.000Z | 2021-05-12T03:33:19.000Z | kattis/cake.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | null | null | null | kattis/cake.cpp | btjanaka/competitive-programming-solutions | e3df47c18451802b8521ebe61ca71ee348e5ced7 | [
"MIT"
] | 1 | 2020-06-25T21:04:06.000Z | 2020-06-25T21:04:06.000Z | // Author: btjanaka (Bryon Tjanaka)
// Problem: (Kattis) cake
// Title: Cake
// Link: https://open.kattis.com/problems/cake
// Idea: Greedily divide the cake - it should always be possible to divide
// without leftovers.
// Difficulty: medium
// Tags: greedy, implementation
#include <bits/stdc++.h>
#define GET(x) scanf("%d", &x)
#define GED(x) scanf("%lf", &x)
using namespace std;
typedef long long ll;
typedef pair<int, int> ii;
typedef vector<int> vi;
int main() {
int p, q, n;
while (GET(p) > 0) {
GET(q);
GET(n);
vector<vector<int>> cake(p + 1);
for (int i = 0; i < n; ++i) {
int r, c;
GET(r);
GET(c);
cake[r].push_back(c);
}
// make sure to order the columns in each row
for (int i = 1; i <= p; ++i) {
sort(cake[i].begin(), cake[i].end());
}
// remove empty rows at back
while (cake.back().empty()) cake.pop_back();
// divide cake
vector<vector<int>> res;
for (int r = 1; r < cake.size(); ++r) {
if (!cake[r].empty()) {
int r0 = res.size() == 0 ? 1 : res.back()[2] + 1;
int rf = r == cake.size() - 1 ? p : r;
int c0, cf;
for (int i = 0; i < cake[r].size(); ++i) {
c0 = i == 0 ? 1 : res.back()[3] + 1;
cf = i == cake[r].size() - 1 ? q : cake[r][i];
res.push_back({r0, c0, rf, cf});
}
}
}
for (const vector<int>& ans : res) {
printf("%d %d %d %d\n", ans[0], ans[1], ans[2], ans[3]);
}
printf("0\n");
}
return 0;
}
| 25.316667 | 74 | 0.508887 | [
"vector"
] |
48e0356a80d889311bedc97d53ec5715eae9cda7 | 77,151 | hpp | C++ | include/lely/coapp/master.hpp | tshu/lely-core | fd0ceff2db726af6d2a766039a0b5a6d33d056e8 | [
"Apache-2.0"
] | 4 | 2020-12-27T11:31:57.000Z | 2022-02-09T11:32:08.000Z | include/lely/coapp/master.hpp | tshu/lely-core | fd0ceff2db726af6d2a766039a0b5a6d33d056e8 | [
"Apache-2.0"
] | null | null | null | include/lely/coapp/master.hpp | tshu/lely-core | fd0ceff2db726af6d2a766039a0b5a6d33d056e8 | [
"Apache-2.0"
] | 1 | 2022-01-03T01:41:59.000Z | 2022-01-03T01:41:59.000Z | /**@file
* This header file is part of the C++ CANopen application library; it contains
* the CANopen master declarations.
*
* @copyright 2018-2021 Lely Industries N.V.
*
* @author J. S. Seldenthuis <jseldenthuis@lely.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.
*/
#ifndef LELY_COCPP_MASTER_HPP_
#define LELY_COCPP_MASTER_HPP_
#include <lely/coapp/node.hpp>
#include <lely/coapp/sdo.hpp>
#include <map>
#include <memory>
#include <string>
#include <utility>
#include <cstddef>
namespace lely {
namespace canopen {
class DriverBase;
/**
* The CANopen master. The master implements a CANopen node. Handling events for
* remote CANopen slaves is delegated to drivers (see #lely::canopen::DriverBase
* and #lely::canopen::BasicDriver), one of which can be registered for each
* node-ID.
*
* For derived classes, the master behaves as an AssociativeContainer for
* drivers.
*/
class BasicMaster : public Node, protected ::std::map<uint8_t, DriverBase*> {
public:
class Object;
class ConstObject;
/**
* A mutator providing read/write access to a CANopen sub-object in a local
* object dictionary.
*/
class SubObject {
friend class Object;
public:
SubObject(const SubObject&) = default;
SubObject(SubObject&&) = default;
SubObject& operator=(const SubObject&) = default;
SubObject& operator=(SubObject&&) = default;
/**
* Sets the value of the sub-object.
*
* @param value the value to be written.
*
* @throws #lely::canopen::SdoError if the sub-object does not exist or the
* type does not match.
*
* @see Write()
*/
template <class T>
SubObject&
operator=(T&& value) {
return Write(::std::forward<T>(value));
}
/**
* Returns the value of the sub-object by submitting an SDO upload request
* to the local object dictionary.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Read()
*/
template <class T>
operator T() const {
return Read<T>();
}
/**
* Reads the value of the sub-object by submitting an SDO upload request to
* the local object dictionary.
*
* @returns the result of the SDO request.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::Read(uint16_t idx, uint8_t subidx) const
* @see Device::TpdoRead(uint8_t id, uint16_t idx, uint8_t subidx) const
*/
template <class T>
T
Read() const {
return id_ ? master_->TpdoRead<T>(id_, idx_, subidx_)
: master_->Read<T>(idx_, subidx_);
}
/**
* Reads the value of the sub-object by submitting an SDO upload request to
* the local object dictionary.
*
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @returns the result of the SDO request, or an empty value on error.
*
* @see Device::Read(uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::TpdoRead(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
*/
template <class T>
T
Read(::std::error_code& ec) const {
return id_ ? master_->TpdoRead<T>(id_, idx_, subidx_, ec)
: master_->Read<T>(idx_, subidx_, ec);
}
/**
* Writes a value to the sub-object by submitting an SDO download request to
* the local object dictionary.
*
* @param value the value to be written.
*
* @returns `*this`.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::Write(uint16_t idx, uint8_t subidx, T&& value)
* @see Device::TpdoWrite(uint8_t id, uint16_t idx, uint8_t subidx, T&& value)
*/
template <class T>
SubObject&
Write(T&& value) {
if (id_)
master_->TpdoWrite(id_, idx_, subidx_, ::std::forward<T>(value));
else
master_->Write(idx_, subidx_, ::std::forward<T>(value));
return *this;
}
/**
* Writes a value to the sub-object by submitting an SDO download request to
* the local object dictionary.
*
* @param value the value to be written.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @returns `*this`.
*
* @see Device::Write(uint16_t idx, uint8_t subidx, T value, ::std::error_code& ec)
* @see Device::Write(uint16_t idx, uint8_t subidx, const T& value, ::std::error_code& ec)
* @see Device::Write(uint16_t idx, uint8_t subidx, const char* value, ::std::error_code& ec)
* @see Device::Write(uint16_t idx, uint8_t subidx, const char16_t* value, ::std::error_code& ec)
* @see Device::TpdoWrite(uint8_t id, uint16_t idx, uint8_t subidx, T&& value, ::std::error_code& ec)
*/
template <class T>
SubObject&
Write(T&& value, ::std::error_code& ec) {
if (id_)
master_->TpdoWrite(id_, idx_, subidx_, ::std::forward<T>(value), ec);
else
master_->Write(idx_, subidx_, ::std::forward<T>(value), ec);
return *this;
}
/**
* Writes an OCTET_STRING or DOMAIN value to the sub-object by submitting an
* SDO download request to the local object dictionary.
*
* @param p a pointer to the bytes to be written.
* @param n the number of bytes to write.
*
* @returns `*this`.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::Write(uint16_t idx, uint8_t subidx, const void* p, ::std::size_t n)
*/
SubObject&
Write(const void* p, ::std::size_t n) {
if (!id_) master_->Write(idx_, subidx_, p, n);
return *this;
}
/**
* Writes an OCTET_STRING or DOMAIN value to the sub-object by submitting an
* SDO download request to the local object dictionary.
*
* @param p a pointer to the bytes to be written.
* @param n the number of bytes to write.
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @returns `*this`.
*
* @see Device::Write(uint16_t idx, uint8_t subidx, const void* p, ::std::size_t n, ::std::error_code& ec)
*/
SubObject&
Write(const void* p, ::std::size_t n, ::std::error_code& ec) {
if (!id_) master_->Write(idx_, subidx_, p, n, ec);
return *this;
}
/**
* Checks if the sub-object can be mapped into a PDO and, if so, triggers
* the transmission of every acyclic or event-driven Transmit-PDO into which
* the sub-object is mapped.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::WriteEvent(uint16_t idx, uint8_t subidx)
* @see Device::TpdoWriteEvent(uint8_t id, uint16_t idx, uint8_t subidx)
*/
void
WriteEvent() {
if (id_)
master_->TpdoWriteEvent(id_, idx_, subidx_);
else
master_->WriteEvent(idx_, subidx_);
}
/**
* Checks if the sub-object can be mapped into a PDO and, if so, triggers
* the transmission of every acyclic or event-driven Transmit-PDO into which
* the sub-object is mapped.
*
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @see Device::WriteEvent(uint16_t idx, uint8_t subidx, ::std::error_code& ec)
* @see Device::TpdoWriteEvent(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec)
*/
void
WriteEvent(::std::error_code& ec) noexcept {
if (id_)
master_->TpdoWriteEvent(id_, idx_, subidx_, ec);
else
master_->WriteEvent(idx_, subidx_, ec);
}
private:
SubObject(BasicMaster* master, uint16_t idx, uint8_t subidx) noexcept
: SubObject(master, 0, idx, subidx) {}
SubObject(BasicMaster* master, uint8_t id, uint16_t idx,
uint8_t subidx) noexcept
: master_(master), idx_(idx), subidx_(subidx), id_(id) {}
BasicMaster* master_;
uint16_t idx_;
uint8_t subidx_;
uint8_t id_;
};
/**
* An accessor providing read-only access to a CANopen sub-object in a local
* object dictionary.
*/
class ConstSubObject {
friend class Object;
friend class ConstObject;
public:
/**
* Returns the value of the sub-object by submitting an SDO upload request
* to the local object dictionary.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Read()
*/
template <class T>
operator T() const {
return Read<T>();
}
/**
* Reads the value of the sub-object by submitting an SDO upload request to
* the local object dictionary.
*
* @returns the result of the SDO request.
*
* @throws #lely::canopen::SdoError on error.
*
* @see Device::Read(uint16_t idx, uint8_t subidx) const
* @see Device::RpdoRead(uint8_t id, uint16_t idx, uint8_t subidx) const
* @see Device::TpdoRead(uint8_t id, uint16_t idx, uint8_t subidx) const
*/
template <class T>
T
Read() const {
return id_ ? (is_rpdo_ ? master_->RpdoRead<T>(id_, idx_, subidx_)
: master_->TpdoRead<T>(id_, idx_, subidx_))
: master_->Read<T>(idx_, subidx_);
}
/**
* Reads the value of the sub-object by submitting an SDO upload request to
* the local object dictionary.
*
* @param ec on error, the SDO abort code is stored in <b>ec</b>.
*
* @returns the result of the SDO request, or an empty value on error.
*
* @see Device::Read(uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::RpdoRead(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
* @see Device::TpdoRead(uint8_t id, uint16_t idx, uint8_t subidx, ::std::error_code& ec) const
*/
template <class T>
T
Read(::std::error_code& ec) const {
return id_ ? (is_rpdo_ ? master_->RpdoRead<T>(id_, idx_, subidx_, ec)
: master_->TpdoRead<T>(id_, idx_, subidx_, ec))
: master_->Read<T>(idx_, subidx_, ec);
}
private:
ConstSubObject(const BasicMaster* master, uint16_t idx,
uint8_t subidx) noexcept
: ConstSubObject(master, 0, idx, subidx, false) {}
ConstSubObject(const BasicMaster* master, uint8_t id, uint16_t idx,
uint8_t subidx, bool is_rpdo) noexcept
: master_(master),
idx_(idx),
subidx_(subidx),
id_(id),
is_rpdo_(is_rpdo) {}
const BasicMaster* master_;
uint16_t idx_;
uint8_t subidx_;
uint8_t id_ : 7;
uint8_t is_rpdo_ : 1;
};
class RpdoMapped;
class TpdoMapped;
/**
* A mutator providing read/write access to a CANopen object in a local object
* dictionary.
*/
class Object {
friend class TpdoMapped;
friend class BasicMaster;
public:
/**
* Returns a mutator object that provides read/write access to the specified
* CANopen sub-object in the local object dictionary (or the TPDO-mapped
* sub-object in the remote object dictionary). Note that this function
* succeeds even if the sub-object does not exist.
*
* @param subidx the object sub-index.
*
* @returns a mutator object for a CANopen sub-object in the local object
* dictionary.
*/
SubObject
operator[](uint8_t subidx) noexcept {
return SubObject(master_, id_, idx_, subidx);
}
/**
* Returns an accessor object that provides read-only access to the
* specified CANopen sub-object in the local object dictionary (or the
* TPDO-mapped sub-object in the remote object dictionary). Note that this
* function succeeds even if the object does not exist.
*
* @param subidx the object sub-index.
*
* @returns an accessor object for a CANopen sub-object in the local object
* dictionary.
*/
ConstSubObject
operator[](uint8_t subidx) const noexcept {
return ConstSubObject(master_, id_, idx_, subidx, false);
}
private:
Object(BasicMaster* master, uint16_t idx) noexcept
: Object(master, 0, idx) {}
Object(BasicMaster* master, uint8_t id, uint16_t idx) noexcept
: master_(master), idx_(idx), id_(id) {}
BasicMaster* master_;
uint16_t idx_;
uint8_t id_;
};
/**
* An accessor providing read-only access to a CANopen object in a local
* object dictionary.
*/
class ConstObject {
friend class RpdoMapped;
friend class TpdoMapped;
friend class BasicMaster;
public:
/**
* Returns an accessor object that provides read-only access to the
* specified CANopen sub-object in the local object dictionary (or the
* PDO-mapped sub-object in the remote object dictionary). Note that this
* function succeeds even if the object does not exist.
*
* @param subidx the object sub-index.
*
* @returns an accessor object for a CANopen sub-object in the local object
* dictionary.
*/
ConstSubObject
operator[](uint8_t subidx) const noexcept {
return ConstSubObject(master_, id_, idx_, subidx, is_rpdo_);
}
private:
ConstObject(const BasicMaster* master, uint16_t idx) noexcept
: ConstObject(master, 0, idx, false) {}
ConstObject(const BasicMaster* master, uint8_t id, uint16_t idx,
bool is_rpdo) noexcept
: master_(master), idx_(idx), id_(id), is_rpdo_(is_rpdo) {}
const BasicMaster* master_;
uint16_t idx_;
uint8_t id_ : 7;
uint8_t is_rpdo_ : 1;
};
/**
* An accessor providing read-only access to TPDO-mapped objects in a remote
* object dictionary.
*/
class RpdoMapped {
friend class BasicMaster;
public:
/**
* Returns an accessor object that provides read-only access to the
* specified RPDO-mapped object in the remote object dictionary. Note that
* this function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the remote object
* dictionary.
*/
ConstObject
operator[](uint16_t idx) const noexcept {
return ConstObject(master_, id_, idx, true);
}
private:
RpdoMapped(const BasicMaster* master, uint8_t id) noexcept
: master_(master), id_(id) {}
const BasicMaster* master_;
uint8_t id_;
};
/**
* A mutator providing read/write access to TPDO-mapped objects in a remote
* object dictionary.
*/
class TpdoMapped {
friend class BasicMaster;
public:
/**
* Returns a mutator object that provides read/write access to the specified
* PDO-mapped object in the remote object dictionary. Note that this
* function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns a mutator object for a CANopen object in the remote object
* dictionary.
*/
Object
operator[](uint16_t idx) noexcept {
return Object(master_, id_, idx);
}
/**
* Returns an accessor object that provides read-only access to the
* specified TPDO-mapped object in the remote object dictionary. Note that
* this function succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the remote object
* dictionary.
*/
ConstObject
operator[](uint16_t idx) const noexcept {
return ConstObject(master_, id_, idx, false);
}
private:
TpdoMapped(BasicMaster* master, uint8_t id) noexcept
: master_(master), id_(id) {}
BasicMaster* master_;
uint8_t id_;
};
/// @see Node::TpdoEventMutex
class TpdoEventMutex : public Node::TpdoEventMutex {
friend class BasicMaster;
public:
void lock() override;
void unlock() override;
protected:
using Node::TpdoEventMutex::TpdoEventMutex;
};
/**
* The signature of the callback function invoked on completion of an
* asynchronous read (SDO upload) operation from a remote object dictionary.
* Note that the callback function SHOULD NOT throw exceptions. Since it is
* invoked from C, any exception that is thrown cannot be caught and will
* result in a call to `std::terminate()`.
*
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param ec the SDO abort code (0 on success).
* @param value the value received from the SDO server.
*/
template <class T>
using ReadSignature = void(uint8_t id, uint16_t idx, uint8_t subidx,
::std::error_code ec, T value);
/**
* The signature of the callback function invoked on completion of an
* asynchronous write (SDO download) operation to a remote object dictionary.
* Note that the callback function SHOULD NOT throw exceptions. Since it is
* invoked from C, any exception that is thrown cannot be caught and will
* result in a call to `std::terminate()`.
*
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param ec the SDO abort code (0 on success).
*/
using WriteSignature = void(uint8_t id, uint16_t idx, uint8_t subidx,
::std::error_code ec);
/**
* Creates a new CANopen master. After creation, the master is in the NMT
* 'Initialisation' state and does not yet create any services or perform any
* communication. Call #Reset() to start the boot-up process.
*
* @param exec the executor used to process I/O and CANopen events. If
* <b>exec</b> is a null pointer, the CAN channel executor is
* used.
* @param timer the timer used for CANopen events. This timer MUST NOT be
* used for any other purpose.
* @param chan a CAN channel. This channel MUST NOT be used for any other
* purpose.
* @param dcf_txt the path of the text EDS or DCF containing the device
* description.
* @param dcf_bin the path of the (binary) concise DCF containing the values
* of (some of) the objets in the object dictionary. If
* <b>dcf_bin</b> is empty, no concise DCF is loaded.
* @param id the node-ID (in the range [1..127, 255]). If <b>id</b> is
* 255 (unconfigured), the node-ID is obtained from the DCF.
*/
explicit BasicMaster(ev_exec_t* exec, io::TimerBase& timer,
io::CanChannelBase& chan, const ::std::string& dcf_txt,
const ::std::string& dcf_bin = "", uint8_t id = 0xff);
/// Creates a new CANopen master.
explicit BasicMaster(io::TimerBase& timer, io::CanChannelBase& chan,
const ::std::string& dcf_txt,
const ::std::string& dcf_bin = "", uint8_t id = 0xff)
: BasicMaster(nullptr, timer, chan, dcf_txt, dcf_bin, id) {}
virtual ~BasicMaster();
/**
* Returns a mutator object that provides read/write access to the specified
* CANopen object in the local object dictionary. Note that this function
* succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns a mutator object for a CANopen object in the local object
* dictionary.
*/
Object
operator[](::std::ptrdiff_t idx) noexcept {
return Object(this, idx);
}
/**
* Returns an accessor object that provides read-only access to the specified
* CANopen object in the local object dictionary. Note that this function
* succeeds even if the object does not exist.
*
* @param idx the object index.
*
* @returns an accessor object for a CANopen object in the local object
* dictionary.
*/
ConstObject
operator[](::std::ptrdiff_t idx) const noexcept {
return ConstObject(this, idx);
}
/**
* Returns an accessor object that provides read-only access to RPDO-mapped
* objects in the remote object dictionary of the specified node. Note that
* this function succeeds even if no RPDO-mapped objects exist.
*
* @param id the node-ID.
*
* @returns an accessor object for RPDO-mapped objects in a remote object
* dictionary.
*/
RpdoMapped
RpdoMapped(uint8_t id) const noexcept {
return {this, id};
}
/**
* Returns a mutator object that provides read/write access to TPDO-mapped
* objects in the remote object dictionary of the specified node. Note that
* this function succeeds even if no TPDO-mapped objects exist.
*
* @param id the node-ID.
*
* @returns a mutator object for TPDO-mapped objects in a remote object
* dictionary.
*/
TpdoMapped
TpdoMapped(uint8_t id) noexcept {
return {this, id};
}
/**
* Requests the NMT 'boot slave' process for the specified node. OnBoot() is
* invoked once the boot-up process completes.
*/
bool Boot(uint8_t id);
/**
* Returns true if the remote node is ready (i.e., the NMT 'boot slave'
* process has successfully completed and no subsequent boot-up event has been
* received) and false if not. Invoking AsyncDeconfig() will also mark a node
* as not ready.
*
* If this function returns true, the default client-SDO service is available
* for the given node.
*
* @see IsConfig()
*/
bool IsReady(uint8_t id) const;
/**
* Queues the DriverBase::OnDeconfig() method for the driver with the
* specified node-ID and creates a future which becomes ready once the
* deconfiguration process completes.
*
* @returns a future which holds an error code on failure.
*
* @post IsReady(id) returns false.
*/
ev::Future<void> AsyncDeconfig(uint8_t id);
/**
* Queues the DriverBase::OnDeconfig() method for all registered drivers and
* creates a future which becomes ready once all deconfiguration processes
* complete.
*
* @returns a future which holds the number of deconfigured drivers.
*
* @post IsReady() returns false for all remote nodes.
*/
ev::Future<::std::size_t, void> AsyncDeconfig();
/**
* Indicates the occurrence of an error event on a remote node and triggers
* the error handling process (see Fig. 12 in CiA 302-2 v4.1.0). Note that
* depending on the value of objects 1F80 (NMT startup) and 1F81 (NMT slave
* assignment), the occurrence of an error event MAY trigger an NMT state
* transition of the entire network, including the master.
*
* @param id the node-ID (in the range[1..127]).
*/
void Error(uint8_t id);
/*
* Generates an EMCY error and triggers the error handling behavior according
* to object 1029:01 (Error behavior object) in case of a communication error
* (emergency error code 0x81xx).
*
* @param eec the emergency error code.
* @param er the error register.
* @param msef the manufacturer-specific error code.
*/
void Error(uint16_t eec, uint8_t er,
const uint8_t msef[5] = nullptr) noexcept;
/**
* Issues an NMT command to a slave.
*
* @param cs the NMT command specifier.
* @param id the node-ID (0 for all nodes, [1..127] for a specific slave).
*/
void Command(NmtCommand cs, uint8_t id = 0);
/// @see Node::RpdoRtr()
void RpdoRtr(int num = 0) noexcept;
/// @see Node::TpdoEvent()
void TpdoEvent(int num = 0) noexcept;
/// @see Node::DamMpdoEvent()
template <class T>
void
DamMpdoEvent(int num, uint8_t id, uint16_t idx, uint8_t subidx, T value) {
::std::lock_guard<BasicLockable> lock(*this);
Node::DamMpdoEvent(num, id, idx, subidx, value);
}
/**
* Returns the SDO timeout used during the NMT 'boot slave' and 'check
* configuration' processes.
*
* @see SetTimeout()
*/
::std::chrono::milliseconds GetTimeout() const;
/**
* Sets the SDO timeout used during the NMT 'boot slave' and 'check
* configuration' processes.
*
* @see GetTimeout()
*/
void SetTimeout(const ::std::chrono::milliseconds& timeout);
/**
* Equivalent to
* #SubmitRead(uint8_t id, SdoUploadRequest<T>& req, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T>
void
SubmitRead(uint8_t id, SdoUploadRequest<T>& req) {
::std::error_code ec;
SubmitRead(id, req, ec);
if (ec) throw SdoError(id, req.idx, req.subidx, ec, "SubmitRead");
}
/**
* Queues an asynchronous read (SDO upload) operation.
*
* @param id the node-ID (in the range[1..127]).
* @param req the SDO upload request.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T>
void
SubmitRead(uint8_t id, SdoUploadRequest<T>& req, ::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitUpload(req);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con) {
SubmitRead<T>(exec, id, idx, subidx, ::std::forward<F>(con), GetTimeout());
}
/**
* Equivalent to
* #SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T, class F>
void
SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con,
::std::error_code& ec) {
SubmitRead<T>(exec, id, idx, subidx, ::std::forward<F>(con), GetTimeout(),
ec);
}
/**
* Equivalent to
* #SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con,
const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitRead<T>(exec, id, idx, subidx, ::std::forward<F>(con), timeout, ec);
if (ec) throw SdoError(id, idx, subidx, ec, "SubmitRead");
}
/**
* Queues an asynchronous read (SDO upload) operation. This function reads the
* value of a sub-object in a remote object dictionary.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con,
const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
SubmitUpload<T>(exec, id, idx, subidx, ::std::forward<F>(con), false,
timeout, ec);
}
/**
* Equivalent to
* #SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con) {
SubmitBlockRead<T>(exec, id, idx, subidx, ::std::forward<F>(con),
GetTimeout());
}
/**
* Equivalent to
* #SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T, class F>
void
SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con, ::std::error_code& ec) {
SubmitBlockRead<T>(exec, id, idx, subidx, ::std::forward<F>(con),
GetTimeout(), ec);
}
/**
* Equivalent to
* #SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con, const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitBlockRead<T>(exec, id, idx, subidx, ::std::forward<F>(con), timeout,
ec);
if (ec) throw SdoError(id, idx, subidx, ec, "SubmitBlockRead");
}
/**
* Queues an asynchronous read (SDO block upload) operation. This function
* reads the value of a sub-object in a remote object dictionary using SDO
* block transfer. SDO block transfer is more effecient than segmented
* transfer for large values, but may not be supported by the remote server.
* If not, the operation will most likely fail with the #SdoErrc::NO_CS abort
* code.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con, const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
SubmitUpload<T>(exec, id, idx, subidx, ::std::forward<F>(con), true,
timeout, ec);
}
/**
* Queues an asynchronous SDO upload operation.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param block a flag specifying whether the request should use a block SDO
* instead of a segmented (or expedited) SDO.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitUpload(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
F&& con, bool block, const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitUpload<T>(exec, idx, subidx, ::std::forward<F>(con), block,
timeout);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #SubmitWrite(uint8_t id, SdoDownloadRequest<T>& req, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T>
void
SubmitWrite(uint8_t id, SdoDownloadRequest<T>& req) {
::std::error_code ec;
SubmitWrite(id, req, ec);
if (ec) throw SdoError(id, req.idx, req.subidx, ec, "SubmitWrite");
}
/**
* Queues an asynchronous write (SDO download) operation.
*
* @param id the node-ID (in the range[1..127]).
* @param req the SDO download request.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T>
void
SubmitWrite(uint8_t id, SdoDownloadRequest<T>& req, ::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitDownload(req);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con) {
SubmitWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), GetTimeout());
}
/**
* Equivalent to
* #SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T, class F>
void
SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con, ::std::error_code& ec) {
SubmitWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), GetTimeout(), ec);
}
/**
* Equivalent to
* #SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con, const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), timeout, ec);
if (ec) throw SdoError(id, idx, subidx, ec, "SubmitWrite");
}
/**
* Queues an asynchronous write (SDO download) operation. This function writes
* a value to a sub-object in a remote object dictionary.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con, const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
SubmitDownload(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), false, timeout, ec);
}
/**
* Equivalent to
* #SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con) {
SubmitBlockWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), GetTimeout());
}
/**
* Equivalent to
* #SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T, class F>
void
SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con, ::std::error_code& ec) {
SubmitBlockWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), GetTimeout(), ec);
}
/**
* Equivalent to
* #SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class T, class F>
void
SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con,
const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitBlockWrite(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), timeout, ec);
if (ec) throw SdoError(id, idx, subidx, ec, "SubmitBlockWrite");
}
/**
* Queues an asynchronous write (SDO block download) operation. This function
* writes a value to a sub-object in a remote object dictionary using SDO
* block transfer. SDO block transfer is more effecient than segmented
* transfer for large values, but may not be supported by the remote server.
* If not, the operation will most likely fail with the #SdoErrc::NO_CS abort
* code.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con,
const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
SubmitDownload(exec, id, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), true, timeout, ec);
}
/**
* Queues an asynchronous SDO download operation.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param con the confirmation function to be called on completion of the
* SDO request.
* @param block a flag specifying whether the request should use a block SDO
* instead of a segmented (or expedited) SDO.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class T, class F>
void
SubmitDownload(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, F&& con, bool block,
const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitDownload(exec, idx, subidx, ::std::forward<T>(value),
::std::forward<F>(con), block, timeout);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #SubmitWriteDcf(uint8_t id, SdoDownloadDcfRequest& req, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
void SubmitWriteDcf(uint8_t id, SdoDownloadDcfRequest& req);
/**
* Queues an asynchronous write (SDO download) operation.
*
* @param id the node-ID (in the range[1..127]).
* @param req the SDO download request.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
void SubmitWriteDcf(uint8_t id, SdoDownloadDcfRequest& req,
::std::error_code& ec);
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t *begin, const uint8_t *end, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin,
const uint8_t* end, F&& con) {
SubmitWriteDcf(exec, id, begin, end, ::std::forward<F>(con), GetTimeout());
}
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t *begin, const uint8_t *end, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin,
const uint8_t* end, F&& con, ::std::error_code& ec) {
SubmitWriteDcf(exec, id, begin, end, ::std::forward<F>(con), GetTimeout(),
ec);
}
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t *begin, const uint8_t *end, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin,
const uint8_t* end, F&& con,
const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitWriteDcf(exec, id, begin, end, ::std::forward<F>(con), timeout, ec);
if (ec) throw SdoError(id, 0, 0, ec, "SubmitWriteDcf");
}
/**
* Queues a series of asynchronous write (SDO download) operations. This
* function writes each entry in the specified concise DCF to a sub-object in
* a remote object dictionary.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param begin a pointer the the first byte in a concise DCF (see object
* 1F22 in CiA 302-3 version 4.1.0).
* @param end a pointer to one past the last byte in the concise DCF. At
* most `end - begin` bytes are read.
* @param con the confirmation function to be called when all SDO download
* requests are successfully completed, or when an error
* occurs.
* @param timeout the SDO timeout. If, after a single request is initiated,
* the timeout expires before receiving a response from the
* server, the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin,
const uint8_t* end, F&& con,
const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitDownloadDcf(exec, begin, end, ::std::forward<F>(con), timeout);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con) {
SubmitWriteDcf(exec, id, path, ::std::forward<F>(con), GetTimeout());
}
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con,
::std::error_code& ec) {
SubmitWriteDcf(exec, id, path, ::std::forward<F>(con), GetTimeout(), ec);
}
/**
* Equivalent to
* #SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con, const ::std::chrono::milliseconds& timeout, ::std::error_code& ec),
* except that it throws #lely::canopen::SdoError on error.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con,
const ::std::chrono::milliseconds& timeout) {
::std::error_code ec;
SubmitWriteDcf(exec, id, path, ::std::forward<F>(con), timeout, ec);
if (ec) throw SdoError(id, 0, 0, ec, "SubmitWriteDcf");
}
/**
* Queues a series of asynchronous write (SDO download) operations. This
* function writes each entry in the specified concise DCF to a sub-object in
* a remote object dictionary.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param path the path of the concise DCF.
* @param con the confirmation function to be called when all SDO download
* requests are successfully completed, or when an error
* occurs.
* @param timeout the SDO timeout. If, after a single request is initiated,
* the timeout expires before receiving a response from the
* server, the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
* @param ec the error code (0 on success). `ec == SdoErrc::NO_SDO` if no
* client-SDO is available.
*/
template <class F>
void
SubmitWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, F&& con,
const ::std::chrono::milliseconds& timeout,
::std::error_code& ec) {
::std::lock_guard<BasicLockable> lock(*this);
ec.clear();
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
sdo->SubmitDownloadDcf(exec, path, ::std::forward<F>(con), timeout);
} else {
ec = SdoErrc::NO_SDO;
}
}
/**
* Equivalent to
* #AsyncRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T>
SdoFuture<T>
AsyncRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx) {
return AsyncRead<T>(exec, id, idx, subidx, GetTimeout());
}
/**
* Queues an asynchronous read (SDO upload) operation and creates a future
* which becomes ready once the request completes (or is canceled).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the received value on success and the SDO
* error on failure.
*/
template <class T>
SdoFuture<T>
AsyncRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
const ::std::chrono::milliseconds& timeout) {
return AsyncUpload<T>(exec, id, idx, subidx, false, timeout);
}
/**
* Equivalent to
* #AsyncBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T>
SdoFuture<T>
AsyncBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx) {
return AsyncBlockRead<T>(exec, id, idx, subidx, GetTimeout());
}
/**
* Queues an asynchronous read (SDO block upload) operation and creates a
* future which becomes ready once the request completes (or is canceled).
* This function uses SDO block transfer, which is more effecient than
* segmented transfer for large values, but may not be supported by the remote
* server. If not, the operation will most likely fail with the
* #SdoErrc::NO_CS abort code.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the received value on success and the SDO
* error on failure.
*/
template <class T>
SdoFuture<T>
AsyncBlockRead(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
const ::std::chrono::milliseconds& timeout) {
return AsyncUpload<T>(exec, id, idx, subidx, true, timeout);
}
/**
* Queues an asynchronous SDO upload operation and creates a future which
* becomes ready once the request completes (or is canceled).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param block a flag specifying whether the request should use a block SDO
* instead of a segmented (or expedited) SDO.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the received value on success and the SDO
* error on failure.
*/
template <class T>
SdoFuture<T>
AsyncUpload(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
bool block, const ::std::chrono::milliseconds& timeout) {
if (!exec) exec = GetExecutor();
::std::lock_guard<BasicLockable> lock(*this);
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
return sdo->AsyncUpload<T>(exec, idx, subidx, block, timeout);
} else {
return make_error_sdo_future<T>(id, idx, subidx, SdoErrc::NO_SDO,
"AsyncRead");
}
}
/**
* Equivalent to
* #AsyncWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T>
SdoFuture<void>
AsyncWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value) {
return AsyncWrite(exec, id, idx, subidx, ::std::forward<T>(value),
GetTimeout());
}
/**
* Queues an asynchronous write (SDO download) operation and creates a future
* which becomes ready once the request completes (or is canceled).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the SDO error on failure.
*/
template <class T>
SdoFuture<void>
AsyncWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, const ::std::chrono::milliseconds& timeout) {
return AsyncDownload(exec, id, idx, subidx, ::std::forward<T>(value), false,
timeout);
}
/**
* Equivalent to
* #AsyncBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx, T&& value, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
template <class T>
SdoFuture<void>
AsyncBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value) {
return AsyncBlockWrite(exec, id, idx, subidx, ::std::forward<T>(value),
GetTimeout());
}
/**
* Queues an asynchronous write (SDO block download) operation and creates a
* future which becomes ready once the request completes (or is canceled).
* This function uses SDO block transfer, which is more effecient than
* segmented transfer for large values, but may not be supported by the remote
* server. If not, the operation will most likely fail with the
* #SdoErrc::NO_CS abort code.
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the SDO error on failure.
*/
template <class T>
SdoFuture<void>
AsyncBlockWrite(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, const ::std::chrono::milliseconds& timeout) {
return AsyncDownload(exec, id, idx, subidx, ::std::forward<T>(value), true,
timeout);
}
/**
* Queues an asynchronous SDO download operation and creates a future which
* becomes ready once the request completes (or is canceled).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param idx the object index.
* @param subidx the object sub-index.
* @param value the value to be written.
* @param block a flag specifying whether the request should use a block SDO
* instead of a segmented (or expedited) SDO.
* @param timeout the SDO timeout. If, after the request is initiated, the
* timeout expires before receiving a response from the server,
* the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the SDO error on failure.
*/
template <class T>
SdoFuture<void>
AsyncDownload(ev_exec_t* exec, uint8_t id, uint16_t idx, uint8_t subidx,
T&& value, bool block,
const ::std::chrono::milliseconds& timeout) {
if (!exec) exec = GetExecutor();
::std::lock_guard<BasicLockable> lock(*this);
auto sdo = GetSdo(id);
if (sdo) {
SetTime();
return sdo->AsyncDownload<T>(exec, idx, subidx, ::std::forward<T>(value),
block, timeout);
} else {
return make_error_sdo_future<void>(id, idx, subidx, SdoErrc::NO_SDO,
"AsyncWrite");
}
}
/**
* Equivalent to
* #AsyncWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin, const uint8_t* end, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
SdoFuture<void>
AsyncWriteDcf(ev_exec_t* exec, uint8_t id, const uint8_t* begin,
const uint8_t* end) {
return AsyncWriteDcf(exec, id, begin, end, GetTimeout());
}
/**
* Queues a series of asynchronous write (SDO download) operations,
* corresponding to the entries in the specified concise DCF, and creates a
* future which becomes ready once all requests complete (or an error occurs).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param begin a pointer the the first byte in a concise DCF (see object
* 1F22 in CiA 302-3 version 4.1.0).
* @param end a pointer to one past the last byte in the concise DCF. At
* most `end - begin` bytes are read.
* @param timeout the SDO timeout. If, after a single request is initiated,
* the timeout expires before receiving a response from the
* server, the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the SDO error on failure.
*/
SdoFuture<void> AsyncWriteDcf(ev_exec_t* exec, uint8_t id,
const uint8_t* begin, const uint8_t* end,
const ::std::chrono::milliseconds& timeout);
/**
* Equivalent to
* #AsyncWriteDcf(ev_exec_t* exec, uint8_t id, const char* path, const ::std::chrono::milliseconds& timeout),
* except that it uses the SDO timeout given by #GetTimeout().
*/
SdoFuture<void>
AsyncWriteDcf(ev_exec_t* exec, uint8_t id, const char* path) {
return AsyncWriteDcf(exec, id, path, GetTimeout());
}
/**
* Queues a series of asynchronous write (SDO download) operations,
* corresponding to the entries in the specified concise DCF, and creates a
* future which becomes ready once all requests complete (or an error occurs).
*
* @param exec the executor used to execute the completion task.
* @param id the node-ID (in the range[1..127]).
* @param path the path to a concise DCF.
* @param timeout the SDO timeout. If, after a single request is initiated,
* the timeout expires before receiving a response from the
* server, the client aborts the transfer with abort code
* #SdoErrc::TIMEOUT.
*
* @returns a future which holds the SDO error on failure.
*/
SdoFuture<void> AsyncWriteDcf(ev_exec_t* exec, uint8_t id, const char* path,
const ::std::chrono::milliseconds& timeout);
/**
* Registers a driver for a remote CANopen node. If an event occurs for that
* node, or for the entire CANopen network, the corresponding method of the
* driver will be invoked.
*
* @throws std::out_of_range if the node-ID is invalid or already registered.
*
* @see Erase()
*/
void Insert(DriverBase& driver);
/**
* Unregisters a driver for a remote CANopen node.
*
* @see Insert()
*/
void Erase(DriverBase& driver);
/// @see Node::OnCanState()
void
OnCanState(::std::function<void(io::CanState, io::CanState)> on_can_state) {
Node::OnCanState(on_can_state);
}
/// @see Node::OnCanError()
void
OnCanError(::std::function<void(io::CanError)> on_can_error) {
Node::OnCanError(on_can_error);
}
/// @see Device::OnRpdoWrite()
void
OnRpdoWrite(::std::function<void(uint8_t, uint16_t, uint8_t)> on_rpdo_write) {
Node::OnRpdoWrite(on_rpdo_write);
}
/// @see Node::OnCommand()
void
OnCommand(::std::function<void(NmtCommand)> on_command) {
Node::OnCommand(on_command);
}
/// @see Node::OnHeartbeat()
void
OnHeartbeat(::std::function<void(uint8_t, bool)> on_heartbeat) {
Node::OnHeartbeat(on_heartbeat);
}
/// @see Node::OnState()
void
OnState(::std::function<void(uint8_t, NmtState)> on_state) {
Node::OnState(on_state);
}
/// @see Node::OnSync()
void
OnSync(::std::function<void(uint8_t, const time_point&)> on_sync) {
Node::OnSync(on_sync);
}
/// @see Node::OnSyncError()
void
OnSyncError(::std::function<void(uint16_t, uint8_t)> on_sync_error) {
Node::OnSyncError(on_sync_error);
}
/// @see Node::OnTime()
void
OnTime(::std::function<void(const ::std::chrono::system_clock::time_point&)>
on_time) {
Node::OnTime(on_time);
}
/// @see Node::OnEmcy()
void
OnEmcy(
::std::function<void(uint8_t, uint16_t, uint8_t, uint8_t[5])> on_emcy) {
Node::OnEmcy(on_emcy);
}
/**
* Registers the function invoked when a node guarding timeout event occurs or
* is resolved. Only a single function can be registered at any one time. If
* <b>on_node_guarding</b> contains a callable function target, a copy of the
* target is invoked _after_ OnNodeGuarding(uint8_t, bool) completes.
*/
void OnNodeGuarding(::std::function<void(uint8_t, bool)> on_node_guarding);
/**
* Registers the function invoked when the NMT 'boot slave' process completes.
* Only a single function can be registered at any one time. If <b>on_boot</b>
* contains a callable function target, a copy of the target is invoked
* _after_ OnBoot(uint8_t, NmtState, char, const ::std::string&) completes.
*/
void OnBoot(
::std::function<void(uint8_t, NmtState, char, const ::std::string&)>
on_boot);
/// @see Node::tpdo_event_mutex
TpdoEventMutex tpdo_event_mutex;
protected:
using MapType = ::std::map<uint8_t, DriverBase*>;
/**
* The default implementation invokes #lely::canopen::Node::OnCanState() and
* notifies each registered driver.
*
* @see Node::OnCanState(), DriverBase::OnCanState()
*/
void OnCanState(io::CanState new_state,
io::CanState old_state) noexcept override;
/**
* The default implementation notifies all registered drivers.
*
* @see Node::OnCanError(), DriverBase::OnCanError()
*/
void OnCanError(io::CanError error) noexcept override;
/**
* The default implementation notifies the driver registered for node
* <b>id</b>.
*
* @see Device::OnRpdoWrite(), DriverBase::OnRpdoWrite()
*/
void OnRpdoWrite(uint8_t id, uint16_t idx, uint8_t subidx) noexcept override;
/**
* The default implementation notifies all registered drivers. Unless the
* master enters the pre-operational or operational state, all ongoing and
* pending SDO requests are aborted.
*
* @see Node::OnCommand(), DriverBase::OnCommand()
*/
void OnCommand(NmtCommand cs) noexcept override;
/**
* The default implementation notifies the driver registered for node
* <b>id</b>.
*
* @see Node::OnHeartbeat(), DriverBase::OnHeartbeat()
*/
void OnHeartbeat(uint8_t id, bool occurred) noexcept override;
/**
* The default implementation notifies the driver registered for node
* <b>id</b>. If a boot-up event (`st == NmtState::BOOTUP`) is detected, any
* ongoing or pending SDO requests for the slave are aborted. This is
* necessary because the master MAY need the Client-SDO service for the NMT
* 'boot slave' process.
*
* @see Node::OnState(), DriverBase::OnState()
*/
void OnState(uint8_t id, NmtState st) noexcept override;
/**
* The default implementation notifies all registered drivers.
*
* @see Node::OnSync(), DriverBase::OnSync()
*/
void OnSync(uint8_t cnt, const time_point& t) noexcept override;
/**
* The default implementation notifies all registered drivers.
*
* @see Node::OnSyncError(), DriverBase::OnSyncError()
*/
void OnSyncError(uint16_t eec, uint8_t er) noexcept override;
/**
* The default implementation notifies all registered drivers.
*
* @see Node::OnTime(), DriverBase::OnTime()
*/
void OnTime(const ::std::chrono::system_clock::time_point& abs_time) noexcept
override;
/**
* The default implementation notifies the driver registered for node
* <b>id</b>.
*
* @see Node::OnEmcy(), DriverBase::OnEmcy()
*/
void OnEmcy(uint8_t id, uint16_t eec, uint8_t er,
uint8_t msef[5]) noexcept override;
/**
* The function invoked when a node guarding timeout event occurs or is
* resolved. Note that depending on the value of object 1029:01 (Error
* behavior object), the occurrence of a node guarding event MAY trigger an
* NMT state transition. If so, this function is called _after_ the state
* change completes.
*
* The default implementation notifies the driver registered for node
* <b>id</b>.
*
* @param id the node-ID (in the range [1..127]).
* @param occurred `true` if the node guarding event occurred, `false` if it
* was resolved.
*
* @see DriverBase::OnNodeGuarding()
*/
virtual void OnNodeGuarding(uint8_t id, bool occurred) noexcept;
/**
* The function invoked when the NMT 'boot slave' process completes.
*
* The default implementation notifies the driver registered for node
* <b>id</b>.
*
* @param id the node-ID (in the range [1..127]).
* @param st the state of the remote node (including the toggle bit
* (#NmtState::TOGGLE) if node guarding is enabled).
* @param es the error status (in the range ['A'..'O'], or 0 on success):
* - 'A': The CANopen device is not listed in object 1F81.
* - 'B': No response received for upload request of object 1000.
* - 'C': Value of object 1000 from CANopen device is different to
* value in object 1F84 (%Device type).
* - 'D': Value of object 1018:01 from CANopen device is different
* to value in object 1F85 (Vendor-ID).
* - 'E': Heartbeat event. No heartbeat message received from
* CANopen device.
* - 'F': Node guarding event. No confirmation for guarding
* request received from CANopen device.
* - 'G': Objects for program download are not configured or
* inconsistent.
* - 'H': Software update is required, but not allowed because of
* configuration or current status.
* - 'I': Software update is required, but program download
* failed.
* - 'J': Configuration download failed.
* - 'K': Heartbeat event during start error control service. No
* heartbeat message received from CANopen device during start
* error control service.
* - 'L': NMT slave was initially operational. (CANopen manager
* may resume operation with other CANopen devices)
* - 'M': Value of object 1018:02 from CANopen device is different
* to value in object 1F86 (Product code).
* - 'N': Value of object 1018:03 from CANopen device is different
* to value in object 1F87 (Revision number).
* - 'O': Value of object 1018:04 from CANopen device is different
* to value in object 1F88 (Serial number).
* @param what if <b>es</b> is non-zero, contains a string explaining the
* error.
*
* @see DriverBase::OnBoot()
*/
virtual void OnBoot(uint8_t id, NmtState st, char es,
const ::std::string& what) noexcept;
/**
* Marks a remote note as ready or not ready.
*
* @post IsReady(id) returns <b>ready</b>.
*/
void IsReady(uint8_t id, bool ready) noexcept;
/**
* The function invoked when the 'update configuration' step is reached during
* the NMT 'boot slave' process. The 'boot slave' process is halted until the
* result of the 'update configuration' step is communicated to the NMT
* service with #ConfigResult().
*
* The default implementation delegates the configuration update to the
* driver, if one is registered for node <b>id</b>. If not, a successful
* result is communicated to the NMT service.
*
* @see IsConfig(), DriverBase::OnConfig()
*/
virtual void OnConfig(uint8_t id) noexcept;
/**
* Reports the result of the 'update configuration' step to the NMT service.
*
* @param id the node-ID (in the range [1..127]).
* @param ec the SDO abort code (0 on success).
*/
void ConfigResult(uint8_t id, ::std::error_code ec) noexcept;
/**
* Returns true if the remote node is configuring (i.e., the 'update
* configuration' step of the NMT 'boot slave' is reached but not yet
* completed) and false if not.
*
* If this function returns true, the default client-SDO service is available
* for the given node.
*
* @see IsReady(), OnConfig()
*/
bool IsConfig(uint8_t id) const;
/**
* Returns a pointer to the default client-SDO service for the given node. If
* the master is not in the pre-operational or operational state, or if the
* master needs the client-SDO to boot the node, a null pointer is returned.
*/
Sdo* GetSdo(uint8_t id);
/**
* Aborts any ongoing or pending SDO requests for the specified slave.
*
* @param id the node-ID (0 for all nodes, [1..127] for a specific slave).
*/
void CancelSdo(uint8_t id = 0);
private:
struct Impl_;
::std::unique_ptr<Impl_> impl_;
};
/**
* An asynchronous CANopen master. When a CANopen event occurs, this master
* queues a notification to (the executor of) each registered driver. The master
* itself does not block waiting for events to be handled.
*/
class AsyncMaster : public BasicMaster {
public:
using BasicMaster::BasicMaster;
/// @see Node::OnCanState()
void
OnCanState(::std::function<void(io::CanState, io::CanState)> on_can_state) {
BasicMaster::OnCanState(on_can_state);
}
/// @see Node::OnCanError()
void
OnCanError(::std::function<void(io::CanError)> on_can_error) {
BasicMaster::OnCanError(on_can_error);
}
/// @see Device::OnRpdoWrite()
void
OnRpdoWrite(::std::function<void(uint8_t, uint16_t, uint8_t)> on_rpdo_write) {
BasicMaster::OnRpdoWrite(on_rpdo_write);
}
/// @see Node::OnCommand()
void
OnCommand(::std::function<void(NmtCommand)> on_command) {
BasicMaster::OnCommand(on_command);
}
/// @see Node::OnHeartbeat()
void
OnHeartbeat(::std::function<void(uint8_t, bool)> on_heartbeat) {
BasicMaster::OnHeartbeat(on_heartbeat);
}
/// @see Node::OnState()
void
OnState(::std::function<void(uint8_t, NmtState)> on_state) {
BasicMaster::OnState(on_state);
}
/// @see Node::OnSync()
void
OnSync(::std::function<void(uint8_t, const time_point&)> on_sync) {
BasicMaster::OnSync(on_sync);
}
/// @see Node::OnSyncError()
void
OnSyncError(::std::function<void(uint16_t, uint8_t)> on_sync_error) {
BasicMaster::OnSyncError(on_sync_error);
}
/// @see Node::OnTime()
void
OnTime(::std::function<void(const ::std::chrono::system_clock::time_point&)>
on_time) {
BasicMaster::OnTime(on_time);
}
/// @see Node::OnEmcy()
void
OnEmcy(
::std::function<void(uint8_t, uint16_t, uint8_t, uint8_t[5])> on_emcy) {
BasicMaster::OnEmcy(on_emcy);
}
/// @see BasicMaster::OnNodeGuarding()
void
OnNodeGuarding(::std::function<void(uint8_t, bool)> on_node_guarding) {
BasicMaster::OnNodeGuarding(on_node_guarding);
}
/// @see BasicMaster::OnBoot()
void
OnBoot(::std::function<void(uint8_t, NmtState, char, const ::std::string&)>
on_boot) {
BasicMaster::OnBoot(on_boot);
}
protected:
/**
* The default implementation invokes #lely::canopen::Node::OnCanState() and
* queues a notification for each registered driver.
*
* @see Node::OnCanState(), DriverBase::OnCanState()
*/
void OnCanState(io::CanState new_state,
io::CanState old_state) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers.
*
* @see Node::OnCanError(), DriverBase::OnCanError()
*/
void OnCanError(io::CanError error) noexcept override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>.
*
* @see Device::OnRpdoWrite(), DriverBase::OnRpdoWrite()
*/
void OnRpdoWrite(uint8_t id, uint16_t idx, uint8_t subidx) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers. Unless the master enters the pre-operational or operational state,
* all ongoing and pending SDO requests are aborted.
*
* @see Node::OnCommand(), DriverBase::OnCommand()
*/
void OnCommand(NmtCommand cs) noexcept override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>.
*
* @see Node::OnHeartbeat(), DriverBase::OnHeartbeat()
*/
void OnHeartbeat(uint8_t id, bool occurred) noexcept override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>. If a boot-up event (`st == NmtState::BOOTUP`) is
* detected, any ongoing or pending SDO requests for the slave are aborted.
*
* @see Node::OnState(), DriverBase::OnState()
*/
void OnState(uint8_t id, NmtState st) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers.
*
* @see Node::OnSync(), DriverBase::OnSync()
*/
void OnSync(uint8_t cnt, const time_point& t) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers.
*
* @see Node::OnSyncError(), DriverBase::OnSyncError()
*/
void OnSyncError(uint16_t eec, uint8_t er) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers.
*
* @see Node::OnTime(), DriverBase::OnTime()
*/
void OnTime(const ::std::chrono::system_clock::time_point& abs_time) noexcept
override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>.
*
* @see Node::OnEmcy(), DriverBase::OnEmcy()
*/
void OnEmcy(uint8_t id, uint16_t eec, uint8_t er,
uint8_t msef[5]) noexcept override;
/**
* The default implementation queues a notification for all registered
* drivers.
*
* @see BasicMaster::OnNodeGuarding(), DriverBase::OnNodeGuarding()
*/
void OnNodeGuarding(uint8_t id, bool occurred) noexcept override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>.
*
* @see BasicMaster::OnBoot(), DriverBase::OnBoot()
*/
void OnBoot(uint8_t id, NmtState st, char es,
const ::std::string& what) noexcept override;
/**
* The default implementation queues a notification for the driver registered
* for node <b>id</b>.
*
* @see BasicMaster::OnConfig(), DriverBase::OnConfig()
*/
void OnConfig(uint8_t id) noexcept override;
};
} // namespace canopen
} // namespace lely
#endif // LELY_COCPP_MASTER_HPP_
| 35.834185 | 169 | 0.634327 | [
"object"
] |
48e1904c4b5e69d26fe7490f5d8d4bf6bd3658ab | 8,863 | cc | C++ | src/Enclave/ecallSrc/ecallIndex/enclaveBase.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | src/Enclave/ecallSrc/ecallIndex/enclaveBase.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | src/Enclave/ecallSrc/ecallIndex/enclaveBase.cc | debe-sgx/debe | 641f2b6473fec8ebea301c533d5aab563e53bcbb | [
"MIT"
] | null | null | null | /**
* @file enclaveBase.cc
* @author
* @brief implement the interface of the base of enclave
* @version 0.1
* @date 2020-12-28
*
* @copyright Copyright (c) 2020
*
*/
#include "../../include/enclaveBase.h"
/**
* @brief Construct a new Enclave Base object
*
* @param maxRecvChunkNum the pointer to the outside segment buffer
*/
EnclaveBase::EnclaveBase(uint64_t maxRecvChunkNum) {
// store the share parameter
maxRecvChunkNum_ = maxRecvChunkNum;
maxSegmentChunkNum_ = MAX_SEGMENT_SIZE / MIN_CHUNK_SIZE;
///
// the new object
storageCoreObj_ = new EcallStorageCore();
cryptoObj_ = new EcallCrypto(CIPHER_TYPE, HASH_TYPE);
///
EnclaveCommon::printf("EnclaveBase: Init the base of the enclave.\n");
}
/**
* @brief Destroy the Enclave Base object
*
*/
EnclaveBase::~EnclaveBase() {
delete storageCoreObj_;
delete cryptoObj_;
EnclaveCommon::printf("EnclaveBase: Destory the base of the enclave.\n");
}
/**
* @brief identify whether it is the end of a segment
*
* @param chunkHashVal the input chunk hash
* @param chunkSize the input chunk size
* @param currentSegment the reference to current segment
* @return true is the end
* @return false is not the end
*/
bool EnclaveBase::IsEndOfSegment(uint32_t chunkHashVal, uint32_t chunkSize, Segment_t* currentSegment) {
// step-1: judge the number of chunks in this segment
if (currentSegment->currentChunkNum + 1 > maxSegmentChunkNum_) {
// exceed the max allow number of chunks
// start to process
return true;
}
// step-2: judge the segment size
if (currentSegment->currentSegmentSize + chunkSize < MIN_SEGMENT_SIZE) {
// continue
return false;
} else if (currentSegment->currentSegmentSize + chunkSize > MAX_SEGMENT_SIZE) {
// capping the size
return true;
} else {
if (chunkHashVal % DIVISOR == PATTERN) {
// capping the size
return true;
} else {
// continue
return false;
}
}
}
/**
* @brief convert hash to a value
*
* @param inputHash the input chunk hash
* @return uint32_t the returned value
*/
uint32_t EnclaveBase::ConvertHashToValue(const uint8_t* inputHash) {
uint32_t hashVal = 0;
for (size_t i = 0; i < CHUNK_HASH_SIZE; i++) {
hashVal += inputHash[i];
}
return hashVal;
}
/**
* @brief update the file recipe
*
* @param chunkAddressStr the chunk address string
* @param recipeBuffer the reference to the recipe buffer
* @param currentClient the pointer to current client
*/
void EnclaveBase::UpdateFileRecipe(string& chunkAddressStr, RecipeBuffer_t& recipeBuffer,
EnclaveClient* currentClient) {
KeyForChunkHashDB_t* chunkAddressPtr;
chunkAddressPtr = (KeyForChunkHashDB_t*)(&chunkAddressStr[0]);
RecipeEntry_t* newRecipeEntryPtr;
newRecipeEntryPtr = recipeBuffer.recipeBuffer + recipeBuffer.recipeNum;
memcpy(newRecipeEntryPtr, chunkAddressPtr, sizeof(KeyForChunkHashDB_t));
// update the file recipe buffer offset
recipeBuffer.recipeNum++;
if ((recipeBuffer.recipeNum % maxRecvChunkNum_) == 0) {
// start to encrypt the file recipe with the enclave key
uint8_t cipherRecipe[maxRecvChunkNum_ * sizeof(RecipeEntry_t)];
cryptoObj_->EncryptWithKey(currentClient->GetCipherCTX(), (uint8_t*)recipeBuffer.recipeBuffer,
recipeBuffer.recipeNum * sizeof(RecipeEntry_t), currentClient->GetMasterKey(), cipherRecipe);
Ocall_UpdateFileRecipe((RecipeEntry_t*)cipherRecipe, recipeBuffer.recipeNum,
currentClient->GetClientID());
// reset the recipe num
recipeBuffer.recipeNum = 0;
}
return ;
}
/**
* @brief process an unique chunk
*
* @param chunkAddress the chunk address
* @param chunkBuffer the chunk buffer
* @param chunkSize the chunk size
* @param uploadOutSGXPtr the pointer to outside var
* @param currentClient the pointer to current client
*/
void EnclaveBase::ProcessUniqueChunk(KeyForChunkHashDB_t* chunkAddress, uint8_t* chunkBuffer,
uint32_t chunkSize, UploadOutSGX_t* uploadOutSGXPtr, EnclaveClient* currentClient) {
uint8_t tmpCipherChunk[MAX_CHUNK_SIZE];
#if (ENABLE_COMPRESSION==1)
uint8_t tmpCompressedChunk[MAX_CHUNK_SIZE];
int tmpCompressedChunkSize = 0;
#if (SGX_BREAKDOWN==1)
Ocall_GetCurrentTime(&startTime_);
#endif
tmpCompressedChunkSize = LZ4_compress_default((char*)(chunkBuffer), (char*)tmpCompressedChunk,
chunkSize, chunkSize);
#if (SGX_BREAKDOWN==1)
Ocall_GetCurrentTime(&endTime_);
compressTime_ += (endTime_ - startTime_);
compressCount_++;
#endif
#if (SGX_BREAKDOWN==1)
Ocall_GetCurrentTime(&startTime_);
#endif
uint8_t* currentIV = currentClient->PickNewIV();
EVP_CIPHER_CTX* cipher = currentClient->GetCipherCTX();
if (tmpCompressedChunkSize > 0) {
// it can be compressed
compressedDataSize_ += tmpCompressedChunkSize;
// do encryption
cryptoObj_->EncryptWithKeyIV(cipher, tmpCompressedChunk, tmpCompressedChunkSize,
EnclaveCommon::enclaveKey_, tmpCipherChunk, currentIV);
} else {
// it cannot be compressed
compressedDataSize_ += chunkSize;
tmpCompressedChunkSize = chunkSize;
// do encryption
cryptoObj_->EncryptWithKeyIV(cipher, chunkBuffer, chunkSize, EnclaveCommon::enclaveKey_,
tmpCipherChunk, currentIV);
}
#if (SGX_BREAKDOWN==1)
Ocall_GetCurrentTime(&endTime_);
encryptTime_ += (endTime_ - startTime_);
encryptCount_++;
#endif
// finish the encryption, assign this a container
storageCoreObj_->SaveChunk((char*)tmpCipherChunk, tmpCompressedChunkSize,
chunkAddress, uploadOutSGXPtr, currentClient);
#else
// do encryption
cryptoObj_->EncryptWithKey(cipher, chunkBuffer, chunkSize, EnclaveCommon::enclaveKey_,
tmpCipherChunk);
// finish the encryption, assign this chunk a container
storageCoreObj_->SaveChunk((char*)tmpCipherChunk, chunkSize, chunkAddress,
container, inputMQ);
#endif
return ;
}
/**
* @brief update the index store
*
* @param key the key of the k-v pair
* @param buffer the data buffer
* @param bufferSize the size of the buffer
* @return true success
* @return false fail
*/
bool EnclaveBase::UpdateIndexStore(const string& key, const char* buffer, size_t bufferSize) {
bool status;
Ocall_UpdateIndexStoreBuffer(&status, key.c_str(), key.size(),
(const uint8_t*)buffer, bufferSize);
return status;
}
/**
* @brief read the information from the index store
*
* @param key key
* @param value value
* @param clientID the client ID
* @return true
* @return false
*/
bool EnclaveBase::ReadIndexStore(const string& key, string& value, int clientID) {
bool status;
size_t expectedBufferSize = 0;
uint8_t* bufferPtr;
Ocall_ReadIndexStore(&status, key.c_str(), key.size(), &bufferPtr,
&expectedBufferSize, clientID);
// copy the buffer to the string
value.assign((const char*)bufferPtr, expectedBufferSize);
return status;
}
/**
* @brief Get the Time Differ object
*
* @param sTime the start time
* @param eTime the end time
* @return double the diff of time
*/
double EnclaveBase::GetTimeDiffer(uint64_t sTime, uint64_t eTime) {
double second = (eTime - sTime) / SEC_TO_USEC;
return second;
}
/**
* @brief reset the value of current segment
*
* @param currentSegment the pointer to current segment
*/
void EnclaveBase::ResetCurrentSegment(Segment_t* currentSegment) {
currentSegment->currentChunkNum = 0;
currentSegment->currentMinHashVal = UINT32_MAX;
currentSegment->currentSegmentSize = 0;
return ;
}
/**
* @brief finalize the file recipe
*
* @param buffer the pointer to the receive buffer
* @param payloadSize the payload size
* @param currentClient the pointer to current client
*/
void EnclaveBase::FinalizeFileRecipeHeader(uint8_t* buffer, uint64_t payloadSize,
EnclaveClient* currentClient) {
EVP_CIPHER_CTX* cipherCtx = currentClient->GetCipherCTX();
uint8_t* sessionKey = currentClient->GetSessionKey();
uint8_t* recvBuffer = currentClient->GetRecvBuffer();
int clientID = currentClient->GetClientID();
uint8_t* masterKey = currentClient->GetMasterKey();
// step-1: decrypt the recipe head
cryptoObj_->SessionKeyDec(cipherCtx, buffer, payloadSize, sessionKey, recvBuffer);
// step-2: encrypt it with the root key
Recipe_t cipherRecipeHeader;
cryptoObj_->EncryptWithKey(cipherCtx, recvBuffer, sizeof(Recipe_t), masterKey,
(uint8_t*)&cipherRecipeHeader);
// step-3: Ocall write it the outside file
Ocall_UpdateRecipeEnd(&cipherRecipeHeader, clientID);
return ;
} | 30.562069 | 105 | 0.699199 | [
"object"
] |
48e41cf1219157a62057b6b044bb27973fc1551a | 2,174 | cpp | C++ | src/1d_test.cpp | joshia5/ayj-omega_h | 8b65215013df29af066fa076261ba897d64a72c2 | [
"BSD-2-Clause-FreeBSD"
] | 44 | 2019-01-23T03:37:18.000Z | 2021-08-24T02:20:29.000Z | src/1d_test.cpp | joshia5/ayj-omega_h | 8b65215013df29af066fa076261ba897d64a72c2 | [
"BSD-2-Clause-FreeBSD"
] | 67 | 2019-01-29T15:35:42.000Z | 2021-08-17T20:42:40.000Z | src/1d_test.cpp | joshia5/ayj-omega_h | 8b65215013df29af066fa076261ba897d64a72c2 | [
"BSD-2-Clause-FreeBSD"
] | 29 | 2019-01-14T21:33:32.000Z | 2021-08-10T11:35:24.000Z | #include <iostream>
#include "Omega_h_adapt.hpp"
#include "Omega_h_array_ops.hpp"
#include "Omega_h_build.hpp"
#include "Omega_h_class.hpp"
#include "Omega_h_compare.hpp"
#include "Omega_h_for.hpp"
#include "Omega_h_shape.hpp"
#include "Omega_h_timer.hpp"
using namespace Omega_h;
Reals logistic_function(Reals x, Real x0, Real L, Real k) {
Write<Real> out(x.size());
auto f = OMEGA_H_LAMBDA(LO i) {
out[i] = L / (1 + std::exp(-k * (x[i] - x0)));
};
parallel_for(x.size(), f);
return out;
}
static void add_solution(Mesh* mesh) {
auto coords = mesh->coords();
auto sol = logistic_function(coords, 0.5, 1.0, 20.0);
mesh->add_tag(VERT, "solution", 1, sol);
}
static void add_metric(Mesh* mesh) {
MetricInput input;
input.sources.push_back(MetricSource{OMEGA_H_VARIATION, 1.0, "solution"});
input.should_limit_lengths = true;
input.max_length = 1.0;
input.should_limit_gradation = true;
input.max_gradation_rate = 1.0;
input.should_limit_element_count = true;
input.max_element_count = 100;
input.min_element_count = 50;
generate_metric_tag(mesh, input);
}
int main(int argc, char** argv) {
auto lib = Library(&argc, &argv);
auto world = lib.world();
auto nx = 10;
auto mesh = build_box(world, OMEGA_H_SIMPLEX, 1., 0., 0., nx, 0, 0);
mesh.set_parting(OMEGA_H_GHOSTED);
mesh.add_tag(mesh.dim(), "density", 1, Reals(mesh.nelems(), 1.0));
auto opts = AdaptOpts(&mesh);
opts.xfer_opts.type_map["density"] = OMEGA_H_CONSERVE;
opts.xfer_opts.integral_map["density"] = "mass";
opts.xfer_opts.integral_diffuse_map["mass"] = VarCompareOpts::none();
opts.verbosity = EXTRA_STATS;
opts.nquality_histogram_bins = 1;
Now t0 = now();
add_solution(&mesh);
add_metric(&mesh);
while (1) {
adapt(&mesh, opts);
mesh.set_parting(OMEGA_H_GHOSTED);
add_solution(&mesh);
mesh.remove_tag(VERT, "metric");
add_metric(&mesh);
if (mesh.max_length() < 2.0) break;
}
Now t1 = now();
mesh.set_parting(OMEGA_H_ELEM_BASED);
if (world->rank() == 0) {
std::cout << "total time: " << (t1 - t0) << " seconds\n";
}
bool ok = check_regression("gold_1d", &mesh);
if (!ok) return 2;
return 0;
}
| 28.986667 | 76 | 0.677553 | [
"mesh"
] |
48ed5a5ff9bfeb9e4df2fea65a901d4c477fb443 | 3,114 | hpp | C++ | source/reactive/sinks.hpp | graham-riches/led-matrix | 31e570732a8acdcfb3ea35b21fb96286aa8cd22a | [
"MIT"
] | null | null | null | source/reactive/sinks.hpp | graham-riches/led-matrix | 31e570732a8acdcfb3ea35b21fb96286aa8cd22a | [
"MIT"
] | null | null | null | source/reactive/sinks.hpp | graham-riches/led-matrix | 31e570732a8acdcfb3ea35b21fb96286aa8cd22a | [
"MIT"
] | null | null | null | /**
* \file io_sinks.hpp
* \author Graham Riches (graham.riches@live.com)
* \brief
* \version 0.1
* \date 2021-01-29
*
* @copyright Copyright (c) 2021
*
*/
#pragma once
/********************************** Includes *******************************************/
#include <functional>
#include <utility>
/********************************** Types *******************************************/
namespace reactive
{
namespace internals
{
/**
* \brief implementation of the sink object. Wrapped in a namespace to be somewhat hidden
*
* \tparam Sender type that conforms to the IO actor interface : TODO probably re-define that class :S
* \tparam Function message handler function
* \tparam Sender::value_type type of the sender messages
*/
template <typename Sender, typename Function, typename MessageType = typename Sender::value_type>
class sink_impl {
public:
/**
* \brief create a sink instance
*
* \param sender message sender object
* \param function message handler function
*/
sink_impl(Sender&& sender, Function&& function)
: _sender(std::move(sender))
, _function(function) {
_sender.set_message_emit_handler([this](MessageType&& message) { process_message(std::move(message)); });
}
/**
* \brief function to pass a receive message on to the internally registered function object
*
* \param message rvalue reference to the message. Moved to function.
*/
void process_message(MessageType&& message) const {
std::invoke(_function, std::move(message));
}
private:
Sender _sender;
Function _function;
};
/**
* \brief helper used in convenience pipe notation operator overload
*
* \tparam Function template function
*/
template <typename Function>
struct sink_helper {
Function function;
};
}; // namespace internals
/**
* \brief helper function to create a new sink object
*
* \param sender message sender object
* \param function message handler function
* \retval new instance of a sink with the attributes passed in
*/
template <typename Sender, typename Function>
auto sink(Sender&& sender, Function&& function) {
return reactive::internals::sink_impl(std::forward<Sender>(sender), std::forward<Function>(function));
}
namespace operators
{
/**
* \brief partially applied version of the sink function to allow operation chaining via pipes
*
* \param function function to bind
* \retval auto
*/
template <typename Function>
auto sink(Function&& function) {
return reactive::internals::sink_helper<Function>{std::forward<Function>(function)};
}
/**
* \brief operator overload to enable pipe syntax for IO operators :D
*
* \param sender message sender template object
* \param sink sink function
* \retval auto
*/
template <typename Sender, typename Function>
auto operator|(Sender&& sender, reactive::internals::sink_helper<Function> sink) {
return reactive::internals::sink_impl<Sender, Function>(std::forward<Sender>(sender), std::forward<Function>(sink.function));
}
}; // namespace operators
}; // namespace reactive
| 28.309091 | 129 | 0.668915 | [
"object"
] |
48f04376866f9cc78acc769bec66c74f9286d560 | 4,007 | cpp | C++ | src/khorne/Skullgrinder.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 5 | 2019-02-01T01:41:19.000Z | 2021-06-17T02:16:13.000Z | src/khorne/Skullgrinder.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 2 | 2020-01-14T16:57:42.000Z | 2021-04-01T00:53:18.000Z | src/khorne/Skullgrinder.cpp | rweyrauch/AoSSimulator | d2bfbbe0fab904cc543f1a01e62e0b82cf67c27b | [
"MIT"
] | 1 | 2019-03-02T20:03:51.000Z | 2019-03-02T20:03:51.000Z | /*
* Warhammer Age of Sigmar battle simulator.
*
* Copyright (C) 2019 by Rick Weyrauch - rpweyrauch@gmail.com
*
* This code is licensed under the MIT license (MIT) (http://opensource.org/licenses/MIT)
*/
#include <khorne/Skullgrinder.h>
#include <UnitFactory.h>
#include <Board.h>
#include "KhornePrivate.h"
namespace Khorne {
static const int g_basesize = 40;
static const int g_wounds = 5;
static const int g_pointsPerUnit = 90;
bool Skullgrinder::s_registered = false;
Skullgrinder::Skullgrinder(SlaughterHost host, CommandTrait trait, Artefact artefact, bool isGeneral) :
KhorneBase("Skullgrinder", 5, g_wounds, 8, 4, false, g_pointsPerUnit) {
m_keywords = {CHAOS, MORTAL, KHORNE, BLOODBOUND, HERO, SKULLGRINDER};
m_weapons = {&m_brazenAnvil};
m_battleFieldRole = Role::Leader;
s_globalBraveryMod.connect(this, &Skullgrinder::favouredByKhorne, &m_connection);
setSlaughterHost(host);
setCommandTrait(trait);
setArtefact(artefact);
setGeneral(isGeneral);
auto model = new Model(g_basesize, wounds());
model->addMeleeWeapon(&m_brazenAnvil);
addModel(model);
m_points = g_pointsPerUnit;
}
Skullgrinder::~Skullgrinder() {
m_connection.disconnect();
}
Unit *Skullgrinder::Create(const ParameterList ¶meters) {
auto host = (SlaughterHost) GetEnumParam("Slaughter Host", parameters, g_slaughterHost[0]);
auto trait = (CommandTrait) GetEnumParam("Command Trait", parameters, g_mortalbloodboundCommandTraits[0]);
auto artefact = (Artefact) GetEnumParam("Artefact", parameters, g_mortalArtefacts[0]);
auto general = GetBoolParam("General", parameters, false);
return new Skullgrinder(host, trait, artefact, general);
}
void Skullgrinder::Init() {
if (!s_registered) {
static FactoryMethod factoryMethod = {
Create,
ValueToString,
EnumStringToInt,
ComputePoints,
{
EnumParameter("Slaughter Host", g_slaughterHost[0], g_slaughterHost),
EnumParameter("Command Trait", g_mortalbloodboundCommandTraits[0],
g_mortalbloodboundCommandTraits),
EnumParameter("Artefact", g_mortalArtefacts[0], g_mortalArtefacts),
BoolParameter("General")
},
CHAOS,
{KHORNE}
};
s_registered = UnitFactory::Register("Skullgrinder", factoryMethod);
}
}
std::string Skullgrinder::ValueToString(const Parameter ¶meter) {
return KhorneBase::ValueToString(parameter);
}
int Skullgrinder::EnumStringToInt(const std::string &enumString) {
return KhorneBase::EnumStringToInt(enumString);
}
int Skullgrinder::favouredByKhorne(const Unit *unit) {
// Favoured by Khorne
if (unit->hasKeyword(KHORNE) && unit->hasKeyword(MORTAL) &&
(unit->owningPlayer() == owningPlayer()) && (distanceTo(unit) <= 12.0)) {
return 1;
}
return 0;
}
void Skullgrinder::onEndCombat(PlayerId player) {
KhorneBase::onEndCombat(player);
// Fiery Anvil
auto units = Board::Instance()->getUnitsWithin(this, GetEnemyId(owningPlayer()), 2.0);
for (auto unit : units) {
if (unit->hasKeyword(HERO) || unit->hasKeyword(MONSTER)) {
if (Dice::RollD6() >= 2) {
Wounds anvilWounds = {0, Dice::RollD3(), Wounds::Source::Ability, nullptr};
unit->applyDamage(anvilWounds, this);
break;
}
}
}
}
int Skullgrinder::ComputePoints(const ParameterList& /*parameters*/) {
return g_pointsPerUnit;
}
} // namespace Khorne | 35.149123 | 114 | 0.599701 | [
"model"
] |
f70362d2ebd7b97f04fd157bcf28d0ad8acdc93e | 6,193 | cpp | C++ | ensemble.cpp | K-Josai/make_rdf | 8773ac8a37dce23db932b71947ac5fa93ed09fda | [
"MIT"
] | null | null | null | ensemble.cpp | K-Josai/make_rdf | 8773ac8a37dce23db932b71947ac5fa93ed09fda | [
"MIT"
] | null | null | null | ensemble.cpp | K-Josai/make_rdf | 8773ac8a37dce23db932b71947ac5fa93ed09fda | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <array>
#include <math.h>
#include "consts.hpp"
#include "ensemble.hpp"
#include "MT.h"
using namespace std;
//コンストラクタ
Ens::Ens(){
int i, ix, iy;
div_t div_i;
double sum_ux=0, sum_uy=0, r1, r2;
init_genrand(1);
for(i=0; i<NAtom; i++){
div_i = div(i, NInitConfig);
ix = div_i.quot;
iy = div_i.rem;
x[i] = ((double)ix+0.5)*LBox/((double)NInitConfig);
y[i] = ((double)iy+0.5)*LBox/((double)NInitConfig);
x_ref[i] = x[i];
y_ref[i] = y[i];
r1=genrand_real3();
r2=genrand_real3();
ux[i]=sqrt(-2.0*log(r1))*cos(2.0*M_PI*r2);
uy[i]=sqrt(-2.0*log(r1))*sin(2.0*M_PI*r2);
sum_ux += ux[i];
sum_uy += uy[i];
}
//系全体の運動量をゼロにする
for(i=0; i<NAtom; i++){
ux[i] -= sum_ux/(double)NAtom;
uy[i] -= sum_ux/(double)NAtom;
}
}
bool Ens::apply_pbc(){
int i;
for(i=0;i<NAtom;i++){
if(x[i]<0.0){
x[i] += LBox;
}else if(x[i]>=LBox){
x[i] -= LBox;
}
if(y[i]<0.0){
y[i] += LBox;
}else if(y[i]>=LBox){
y[i] -= LBox;
}
}
return true;
}
void Ens::calcu(double T1){
int i;
for(i=0;i<NAtom;i++){
ux[i] += T1*Fx[i];
uy[i] += T1*Fy[i];
}
}
void Ens::calcr(double T1){
int i;
for(i=0;i<NAtom;i++){
x[i] += T1*ux[i];
y[i] += T1*uy[i];
}
}
double Ens::pbc_dist(double r){
double result;
if(r >= LHalf){
result = r - LBox;
}else if(r < -LHalf){
result = r + LBox;
}else{
result = r;
}
return result;
}
void Ens::give_label(){
int i,im;
for(im=0;im<MCell*MCell;im++){
LinkedList[im].clear();
LinkedList[im].shrink_to_fit();
}
for(i=0;i<NAtom;i++){
//粒子iがどのセルに属するかを調べる →コメントでは、簡単にセル(ix,iy)と表す
label_x[i] = floor(MCell/LBox*x[i]);
label_y[i] = floor(MCell/LBox*y[i]);
//セル(ix,iy)を番号ix+iy*Mで指定
//LinkedListを(ix, iy)に入っている粒子の一覧にするため、LinkedListに番号iを追加
LinkedList[label_x[i]+label_y[i]*MCell].push_back(i);
}
}
void Ens::make_VNL(){
NeighborList_i.clear();
NeighborList_i.shrink_to_fit();
NeighborList_j.clear();
NeighborList_j.shrink_to_fit();
pot=0.0;
int i,ix,iy,i_delta,jx,jy,j_cell,k,j;
double xij, yij, rij, Eij, Fij;
for(i=0;i<NAtom;i++){
Fx[i]=0.0;
Fy[i]=0.0;
}
give_label();
array<int, 5> delta_ix={0, 0, 1, 1, 1};
array<int, 5> delta_iy={0, -1, -1, 0, 1}; //順に、同じセル、上、右上、右、右下を指定する
for(i=0;i<NAtom;i++){
ix=label_x[i];
iy=label_y[i];
for(i_delta=0;i_delta<5;i_delta++){
jx = floored_mod((ix+delta_ix[i_delta]) , MCell); //近接するセルを指定
jy = floored_mod((iy+delta_iy[i_delta]) , MCell);
j_cell=jx+jy*MCell;
for(k=0;k<LinkedList[j_cell].size();k++){
j=LinkedList[j_cell][k];
if((i_delta==0) && (j<=i)){
continue;
}
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
Eij=0.0;
Fij=0.0;
if(rij<RList){
NeighborList_i.push_back(i);
NeighborList_j.push_back(j);
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
}
}
cout << "update VNL" <<endl;
}
/*
void Ens::make_VNL2(){
NeighborList_i.clear();
NeighborList_i.shrink_to_fit();
NeighborList_j.clear();
NeighborList_j.shrink_to_fit();
pot=0.0;
int i,j;
double xij, yij, rij, Eij, Fij;
for(i=0;i<NAtom;i++){
Fx[i]=0.0;
Fy[i]=0.0;
}
for(i=0;i<NAtom;i++){
for(j=i+1;j<NAtom;j++){
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
Eij=0.0;
Fij=0.0;
if(rij<RList){
NeighborList_i.push_back(i);
NeighborList_j.push_back(j);
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
}
cout << "update VNL" <<endl;
}*/
bool Ens::check_update_VNL(){
double diff,diffmax; //i番目の粒子がrefと比べてどれくらいの距離離れたか
int i;
diffmax=0.0;
for(i=0;i<NAtom;i++){
diff=sqrt(pow((x[i]-x_ref[i]),2)+pow((y[i]-y_ref[i]),2));
if(diff>diffmax){
diffmax=diff;
}
}
if(diffmax > Skin/2.0){
return true;
}else{
return false;
}
}
void Ens::use_VNL(){
pot=0.0;
int i,j,k,i_F;
for(i_F=0;i_F<NAtom;i_F++){
Fx[i_F]=0.0;
Fy[i_F]=0.0;
}
double xij,yij,rij,Eij,Fij;
for(k=0;k<NeighborList_i.size();k++){
i=NeighborList_i[k];
j=NeighborList_j[k];
xij = pbc_dist(x[j] - x[i]);
yij = pbc_dist(y[j] - y[i]);
rij=sqrt(pow(xij,2)+pow(yij,2));
if(rij<Rcut){
Eij=4.0*(pow(rij,-12)-pow(rij,-6));
Fij=24.0*(-2.0*pow(rij,-13)+pow(rij,-7));
Fx[i] += Fij*xij/rij;
Fy[i] += Fij*yij/rij;
Fx[j] -= Fij*xij/rij;
Fy[j] -= Fij*yij/rij;
pot += Eij/(double)NAtom;
}
}
}
void Ens::calcF(){
if(check_update_VNL()){
make_VNL(); //!
int i;
for(i=0;i<NAtom;i++){
x_ref[i]=(x[i]*1.0);
y_ref[i]=(y[i]*1.0);
}
}else{
use_VNL();
}
}
void Ens::VVcycle(){
calcu(dT/2.0);
calcr(dT);
apply_pbc();
calcF();
calcu(dT/2.0);
temp = 0;
int i;
for(i=0;i<NAtom;i++){
temp += ((pow(ux[i],2)+pow(uy[i],2))/2.0)/double(NAtom);
}
energy = temp + pot;
}
array<double,NAtom> Ens::getx(){
return x;
}
array<double,NAtom> Ens::gety(){
return y;
}
array<double,NAtom> Ens::getux(){
return ux;
}
array<double,NAtom> Ens::getuy(){
return uy;
}
array<double,NAtom> Ens::getFx(){
return Fx;
}
array<double,NAtom> Ens::getFy(){
return Fy;
}
double Ens::get_energy(){
return energy;
}
double Ens::get_pot(){
return pot;
}
double Ens::get_temp(){
return temp;
}
//-------------------------------------
//切り捨て割り算(余りの符号はbの符号と一致)
int floored_mod(int a, int b){
return a-floor((double)a/(double)b)*b;
}
| 20.304918 | 68 | 0.527693 | [
"vector"
] |
f738c32743fbd0f19b104d2433c523ed44667401 | 3,942 | cpp | C++ | COGengine/src/Math/PathFinder.cpp | dodoknight/CogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 3 | 2016-06-01T10:14:00.000Z | 2016-10-11T15:53:45.000Z | COGengine/src/Math/PathFinder.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | null | null | null | COGengine/src/Math/PathFinder.cpp | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 1 | 2020-08-15T17:01:00.000Z | 2020-08-15T17:01:00.000Z | #include "PathFinder.h"
#include "ofAppBaseWindow.h"
namespace Cog {
void PathFinder::CalcPathFromSteps(Vec2i start, Vec2i goal, unordered_map<Vec2i, Vec2i>& steps, vector<Vec2i>& output) const {
Vec2i current = goal;
output.push_back(current);
while (current != start) {
current = steps[current];
output.push_back(current);
}
// reverse path so the starting position will be on the first place
std::reverse(output.begin(), output.end());
}
bool BreadthFirstSearch::Search(const GridMap& grid, Vec2i start, Vec2i goal, PathFinderContext& outputCtx) const {
queue<Vec2i> frontier;
frontier.push(start);
outputCtx.cameFrom[start] = start;
while (!frontier.empty()) {
auto current = frontier.front();
outputCtx.visited.insert(current);
frontier.pop();
if (current == goal) {
// the goal was achieved
CalcPathFromSteps(start, goal, outputCtx.cameFrom, outputCtx.pathFound);
return true;
}
// get neighbors of the current grid block
vector<Vec2i> neighbors;
grid.GetNeighbors(current, neighbors);
for (auto& next : neighbors) {
if (!outputCtx.cameFrom.count(next)) {
frontier.push(next);
outputCtx.cameFrom[next] = current;
}
}
}
return false;
}
bool Dijkstra::Search(const GridMap& grid, Vec2i start, Vec2i goal, PathFinderContext& outputCtx) const {
// initialize priority queue, using GREATER functional template that provides descending order of priorities
// prioritized by heuristic function
PriorityQueue<Vec2i, int> frontier;
unordered_map<Vec2i, int> costSoFar;
// start with the first position
frontier.put(start, 0);
outputCtx.cameFrom[start] = start;
costSoFar[start] = 0;
while (!frontier.empty()) {
auto current = frontier.get();
outputCtx.visited.insert(current);
if (current == goal) {
// the goal was achieved
CalcPathFromSteps(start, goal, outputCtx.cameFrom, outputCtx.pathFound);
return true;
}
// get neighbors of the current grid block
vector<Vec2i> neighbors;
grid.GetNeighbors(current, neighbors);
for (auto& next : neighbors) {
double new_cost = costSoFar[current] + grid.GetCost(current, next);
if (!costSoFar.count(next) || new_cost < costSoFar[next]) {
costSoFar[next] = new_cost;
outputCtx.cameFrom[next] = current;
frontier.put(next, new_cost);
}
}
}
return false;
}
bool AStarSearch::Search(const GridMap& grid, Vec2i start, Vec2i goal, PathFinderContext& outputCtx) const {
// initialize priority queue, using GREATER functional template that provides descending order of priorities
// prioritized by heuristic function
PriorityQueue<Vec2i, float> frontier;
unordered_map<Vec2i, int> costSoFar;
// start with the first position
frontier.put(start, 0);
outputCtx.cameFrom[start] = start;
costSoFar[start] = 0;
while (!frontier.empty()) {
// get current position that should be explored
auto current = frontier.get();
outputCtx.visited.insert(current);
if (current == goal) {
// the goal was achieved
CalcPathFromSteps(start, goal, outputCtx.cameFrom, outputCtx.pathFound);
return true;
}
// get neighbors of the current grid block
vector<Vec2i> neighbors;
grid.GetNeighbors(current, neighbors);
// explore neighbors
for (auto& next : neighbors) {
// calculate the increment of the cost on the current path
int newCost = costSoFar[current] + grid.GetCost(current, next);
// verify if a better way was found
if (!costSoFar.count(next) || newCost < costSoFar[next]) {
costSoFar[next] = newCost;
// priority is price + manhattan distance between next position and the target
float heuristics = Vec2i::ManhattanDist(next, goal);
float priority = newCost + heuristics;
// explore next block
frontier.put(next, priority);
outputCtx.cameFrom[next] = current;
}
}
}
return false;
}
} | 27.566434 | 127 | 0.694318 | [
"vector"
] |
f73cbaf6b79501548afb7c488cd15261da242531 | 3,590 | cpp | C++ | src/Model.cpp | ClaudeTO80/Opti_plus_plus | 772bdce297f2b52455ba483b747890362d97beb4 | [
"MIT"
] | 4 | 2020-02-03T17:05:24.000Z | 2022-01-25T23:02:40.000Z | src/Model.cpp | ClaudeTO80/Opti_plus_plus | 772bdce297f2b52455ba483b747890362d97beb4 | [
"MIT"
] | null | null | null | src/Model.cpp | ClaudeTO80/Opti_plus_plus | 772bdce297f2b52455ba483b747890362d97beb4 | [
"MIT"
] | null | null | null | #include "Model.h"
#include "AnalysisConstraints.h"
#include "RobustDesign.h"
using namespace std;
using namespace AnalysisGenerator;
Model::Model() {};
Model::Model(std::shared_ptr<Generator>& generator) : generator_(generator)
{
auto temp = generator_->getBlock();
setBlock(temp);
return;
}
void Model::setGenerator(std::shared_ptr<Generator>& generator)
{
generator_ = generator;
auto temp = generator_->getBlock();
setBlock(temp);
return;
}
void Model::setBlock(std::shared_ptr<AnalysisParametersBlock>& block)
{
block_ = block;
return;
}
void Model::run()
{
generator_->generate();
auto mat = generator_->getMatrix();
if (robustDesign_)
{
auto objs = block_->getObjectives();
for_each(objs.begin(), objs.end(), [&](const shared_ptr<AnalysisObjective>&curr)
{
block_->addObjective(string("mean_").append(curr->name()), curr->dir());
block_->addObjective(string("stdvar_").append(curr->name()), AnalysisObjective::ObjDir::MIN_);
});
}
block_->addSamples(mat);
auto dim = block_->getNumSamples();
for (int i = 0; i < (int)dim; ++i)
{
cout << "Starting evaluation of solution " << i + 1 << " of " << dim << endl;
auto ret = objf_(block_, i);
if (robustDesign_)
{
vector<double> variances;
auto params=block_->getParameters();
variances.reserve(params.size());
for_each(params.begin(), params.end(), [&](const shared_ptr<AnalysisParameter>& curr)
{
if (curr->varType() == AnalysisParameter::ABSOLUTE_)
variances.push_back(curr->variance());
else if (curr->varType() == AnalysisParameter::PERCENTAGE_)
variances.push_back(curr->variance() * block_->getValue(curr->name(), i) / 100);
});
RobustDesignGenerator rdg(block_->getSample(i)->getValues(),variances,numSamples_);
rdg.generate();
auto rdgMatrix = rdg.getMatrix();
auto tempBlock = block_->clone();
vector<vector<double>> objs;
objs.resize(tempBlock->getObjectives().size());
for_each(objs.begin(), objs.end(), [&](vector<double>& curr)
{
curr.resize(numSamples_+1);
});
tempBlock->addSamples(rdgMatrix);
auto allBasicObjs = block_->getSampleObjectives(i);
for (int k = 0; k < (int)objs.size()/3; ++k)
objs[k][0] = allBasicObjs->getValues()[k];
for (int j = 1; j <= numSamples_; ++j)
{
auto ret = objf_(tempBlock, j);
if (ret)
{
auto allObjs = tempBlock->getSampleObjectives(j);
for (int k = 0; k < (int)objs.size() / 3; ++k)
objs[k][j] = allObjs->getValues()[k];
}
}
int pos = (int)objs.size() / 3;
for (int k = 0; k < pos; ++k)
{
auto currName = tempBlock->getObjectives()[k]->name();
block_->setObjective(string("mean_").append(currName), Utils::StatisticTools::mean(objs[k]), i);
block_->setObjective(string("stdvar_").append(currName), Utils::StatisticTools::stdVariance(objs[k]), i);
}
}
if (ret)
{
vector<shared_ptr<AnalysisConstraint>> constr = block_->getConstraints();
auto sampleConstr = block_->getSampleConstraints(i);
int numConstr=(int)constr.size();
for (int j = 0; j < numConstr; ++j)
{
auto ret = constr[j]->isSatisfed(block_->getSampleConstraints(i, j));
block_->setConstraintSatisfied(i, j, ret);
if (!ret)
block_->setSampleFeasibile(i,false);
}
/*if (objf_(block_, i) && postFeas_)
postFeas_(block_, i);*/
}
}
return;
}
void Model::dumpSamples(const std::string& filename,int opts=0)
{
block_->dumpSamples(filename,opts);
return;
}
void Model::setObjf(std::function<bool(std::shared_ptr<AnalysisParametersBlock>&, int)> objf) { objf_ = objf; }
| 25.827338 | 111 | 0.654596 | [
"vector",
"model"
] |
f754fe184acfe6b61e1f63a154d2599110ce462b | 5,369 | cpp | C++ | SpaceBomber/Linux/graph/Menu.cpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 40 | 2018-01-28T14:23:27.000Z | 2022-03-05T15:57:47.000Z | SpaceBomber/Linux/graph/Menu.cpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 1 | 2021-10-05T09:03:51.000Z | 2021-10-05T09:03:51.000Z | SpaceBomber/Linux/graph/Menu.cpp | 667MARTIN/Epitech | 81095d8e7d54e9abd95541ee3dfcc3bc85d5cf0e | [
"MIT"
] | 73 | 2019-01-07T18:47:00.000Z | 2022-03-31T08:48:38.000Z | #include "irrKlang-64bit-1.5.0/include/irrKlang.h"
#include "irrlicht.hpp"
#include "Menu.hpp"
#include "MenuEventReceiver.hpp"
Menu::Menu(irr::IrrlichtDevice* device) {
this->nbHuman = 2;
this->nbIA = 0;
this->mode = DEFAULT;
this->menuDevice = device;
this->button = device->getVideoDriver()->getTexture("./graph/irrlicht-1.8.3/media/button.png");
this->menuHey = new MenuEventReceiver;
this->drawMenu();
}
void Menu::drawMenu() {
this->menuDevice->getSceneManager()->clear();
this->menuDevice->getGUIEnvironment()->clear();
this->menuDevice->setEventReceiver(this->menuHey);
this->menuHey->setDevice(this->menuDevice);
this->menuHey->setMenu(this);
this->menuDriver = this->menuDevice->getVideoDriver();
this->setWallpaper("./graph/irrlicht-1.8.3/media/Menu.png");
this->menuSmgr = menuDevice->getSceneManager();
this->menuSmgr->addCameraSceneNode(0, irr::core::vector3df(0,70,0), irr::core::vector3df(0,5,0));
this->menuGuienv = menuDevice->getGUIEnvironment();
this->skin = this->menuGuienv->getSkin();
this->font = this->menuGuienv
->getFont("./graph/irrlicht-1.8.3/media/fonthaettenschweiler.bmp");
if (this->font)
this->skin->setFont(this->font);
this->putButtons();
}
void Menu::putButtons()
{
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 600, 1750, 600 + 50),
0, MenuEventReceiver::GUI_ID_NEWGAME, L"New Game", L"New Game")
->setImage(this->button);
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 660, 1750, 660 + 50),
0, MenuEventReceiver::GUI_ID_CONTINUE, L"Continue", L"Continue")
->setImage(this->button);
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 720, 1750, 720 + 50),
0, MenuEventReceiver::GUI_ID_CONTROLS, L"Controls", L"Controls")
->setImage(this->button);
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 780, 1750, 780 + 50),
0, MenuEventReceiver::GUI_ID_CREDITS, L"Credits", L"Credits")
->setImage(this->button);
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 840, 1750, 840 + 50),
0, MenuEventReceiver::GUI_ID_SCORES, L"Scores", L"Scores")
->setImage(this->button);
this->menuGuienv->addButton(irr::core::rect<irr::s32>(1550, 900, 1750, 900 + 50),
0, MenuEventReceiver::GUI_ID_QUIT, L"QUIT", L"Quit")
->setImage(this->button);
}
void Menu::exitGame() {
this->menuDevice->drop();
}
void Menu::exitMenu() {
this->menuSmgr->clear();
this->menuSmgr->addCameraSceneNode(0, irr::core::vector3df(0,70,0), irr::core::vector3df(0,5,0));
}
void Menu::setMode(Menu::Mode mode) {
this->mode = mode;
}
void Menu::setScore(std::vector <std::wstring>* score) {
this->score = score;
}
std::vector <std::wstring>* Menu::getScore() const {
return this->score;
}
int Menu::getMode() {
while (this->mode == DEFAULT) {
if (!(this->menuDevice->run()))
exit(0);
this->menuDriver->beginScene(true, true, irr::video::SColor(0.8, 128, 128, 128));
this->drawWallpaper();
this->menuSmgr->drawAll();
this->menuGuienv->drawAll();
this->menuDriver->endScene();
}
if (this->mode == QUIT)
this->exitGame();
else
this->exitMenu();
return this->mode;
}
void Menu::setWallpaper(irr::io::path wallpaper) {
this->image = this->menuDriver->getTexture(wallpaper);
this->taille = this->image->getSize();
this->position0.X = 0;
this->position0.Y = 0;
this->position1.X = this->taille.Width;
this->position1.Y = this->taille.Height;
this->rectangle.UpperLeftCorner = this->position0;
this->rectangle.LowerRightCorner = this->position1;
}
void Menu::drawWallpaper() {
this->menuDriver->draw2DImage(this->image, this->position0, this->rectangle,
0, irr::video::SColor(255, 255,255,255), true);
}
MenuEventReceiver* Menu::getMenuHey() const
{
return (this->menuHey);
}
irr::video::IVideoDriver* Menu::getMenuDriver() const
{
return (this->menuDriver);
}
irr::scene::ISceneManager* Menu::getMenuSmgr() const
{
return (this->menuSmgr);
}
irr::gui::IGUIEnvironment* Menu::getMenuGuienv() const
{
return (this->menuGuienv);
}
irrklang::ISoundEngine* Menu::getMenuEngine() const
{
return (this->menuEngine);
}
int Menu::getNbPlayers()
{
return (this->nbIA + this->nbHuman);
}
int const& Menu::getNbHuman() const
{
return (this->nbHuman);
}
int const& Menu::getNbIA() const
{
return (this->nbIA);
}
std::string Menu::getNamePlayer1() const {
return this->player1;
}
std::string Menu::getNamePlayer2() const {
return this->player2;
}
void Menu::setMenuHey(MenuEventReceiver *h)
{
this->menuHey = h;
}
void Menu::setMenuDriver(irr::video::IVideoDriver *iv)
{
this->menuDriver = iv;
}
void Menu::setMenuSmgr(irr::scene::ISceneManager *is)
{
this->menuSmgr = is;
}
void Menu::setMenuGuienv(irr::gui::IGUIEnvironment *ig)
{
this->menuGuienv = ig;
}
void Menu::setMenuEngine(irrklang::ISoundEngine *sme)
{
this->menuEngine = sme;
}
void Menu::setNbHuman(int nbH)
{
this->nbHuman = nbH;
}
void Menu::setNbIA(int IA)
{
this->nbIA = IA;
}
void Menu::setNamePlayer1(std::string str) {
this->player1 = str;
}
void Menu::setNamePlayer2(std::string str) {
this->player2 = str;
}
| 26.579208 | 99 | 0.65189 | [
"vector"
] |
f7559e965d0a39d94934c28dccbb614c5b10d438 | 13,235 | cpp | C++ | src/sensor_osus_manager_class.cpp | USArmyResearchLab/Fusion3D | 98b79ccfcbfd444a924f65c321482b540382758d | [
"Apache-2.0"
] | 4 | 2021-09-08T02:07:22.000Z | 2022-03-30T02:48:56.000Z | src/sensor_osus_manager_class.cpp | USArmyResearchLab/Fusion3D | 98b79ccfcbfd444a924f65c321482b540382758d | [
"Apache-2.0"
] | null | null | null | src/sensor_osus_manager_class.cpp | USArmyResearchLab/Fusion3D | 98b79ccfcbfd444a924f65c321482b540382758d | [
"Apache-2.0"
] | 1 | 2021-10-11T02:53:53.000Z | 2021-10-11T02:53:53.000Z | #include "internals.h"
// **********************************************
/// Constructor.
// **********************************************
sensor_osus_manager_class::sensor_osus_manager_class()
:atrlab_manager_class(100) // Never should use this max value
{
strcpy(class_type, "sensorOSUS");
n_data = 0; // Default is off
time_conversion = new time_conversion_class();
sensor_read_osus = new sensor_read_osus_class();
osus_image_store = new osus_image_store_class();
osus_command = new osus_command_class();
reset_all();
}
// **********************************************
/// Destructor.
// **********************************************
sensor_osus_manager_class::~sensor_osus_manager_class()
{
delete time_conversion;
delete sensor_read_osus;
delete osus_image_store;
delete osus_command;
}
// **********************************************
/// Clear all.
// **********************************************
int sensor_osus_manager_class::reset_all()
{
n_data = 0; // Default is off
om_image_index.clear();
om_sorted_index.clear();
om_create_time.clear();
user_bearing_val.clear();
user_bearing_id.clear();
iom_recent_camera.clear();
valid_asset_type.clear();
valid_asset_name.clear();
valid_asset_filter_flags.clear();
valid_asset_stat_flags.clear();
valid_asset_local_flags.clear();
valid_asset_camera_flags.clear();
valid_asset_prox_flags.clear();
valid_asset_red.clear();
valid_asset_grn.clear();
valid_asset_blu.clear();
n_images = 0;
n_images_max = 100;
display_name_flag = 0; // 0 for no text, 1 for sensor name
images_active_flag = -99; // Nonnegative to indicate images currently being displayed for this sensor
use_modify_time_flag = 0;
time_interval_show_stat = 240; // Show detections over 2-min interval
time_interval_show_mov = 30; // Show detections over 30-s interval
earliest_in_window_stat = -99;
latest_in_window_stat = -99;
earliest_in_window_mov = -99;
latest_in_window_mov = -99;
n_in_window_stat = 0;
n_in_window_mov = 0;
imagScaleFactorWorld = 20.;
offset_lat = 0.0;
offset_lon = 0.0;
offset_elev = 0.0f;
d_above_ground = 1.0;
request_osus_addr.clear();
request_sensor_types.clear();
request_osus_port = -99;
dir_flag_osus = 0;
dir_time_osus = 5.;
dirname_osus.clear();
dir_monitor_pattern_osus = "*.xml";
min_create_time_osus = 0; // Means you accept all files since all have write times larger than this
n_warn = 10;
return(1);
}
// **********************************************
/// Read file in tagged ascii format.
/// Read in operational parameters from the standard tagged ascii format.
// **********************************************
int sensor_osus_manager_class::read_tagged(const char* filename)
{
char tiff_tag[240], tiff_junk[240], name[300];
FILE *tiff_fd;
int ntiff, n_tags_read = 1;
float bearing;
string stemp, sname;
// ******************************
// Read-tagged from file
// ******************************
if (!(tiff_fd= fopen(filename,"r"))) {
cerr << "sensor_osus_manager_class::read_tagged: unable to open input file" << filename << endl;
return (0);
}
do {
/* Read tag */
ntiff = fscanf(tiff_fd,"%s",tiff_tag);
n_tags_read += ntiff;
/* If cant read any more (EOF), do nothing */
if (ntiff != 1) {
}
else if (strcmp(tiff_tag, "Osus-Interval-Stat") == 0) {
fscanf(tiff_fd, "%f", &time_interval_show_stat);
}
else if (strcmp(tiff_tag, "Osus-Interval-Mov") == 0) {
fscanf(tiff_fd, "%f", &time_interval_show_mov);
}
else if (strcmp(tiff_tag,"Osus-Offset") == 0) {
fscanf(tiff_fd,"%f %f %f", &offset_lat, &offset_lon, &offset_elev);
sensor_read_osus->set_sensor_offset(offset_lat, offset_lon, offset_elev);
}
else if (strcmp(tiff_tag,"Osus-Set-Bearing") == 0) {
fscanf(tiff_fd,"%s %f", tiff_junk, &bearing);
user_bearing_id.push_back(tiff_junk);
user_bearing_val.push_back(bearing);
}
else if (strcmp(tiff_tag,"Osus-Text-Display") == 0) {
fscanf(tiff_fd,"%d", &display_name_flag);
}
else if (strcmp(tiff_tag,"Osus-Image-Size") == 0) { // Does not work currently, but may want to reimplement
fscanf(tiff_fd,"%f", &imagScaleFactorWorld);
}
else if (strcmp(tiff_tag,"Osus-Use-Write-Time") == 0) {
use_modify_time_flag = 1;
}
else if (strcmp(tiff_tag, "Osus-Request-Addr") == 0) {
fscanf(tiff_fd, "%s %d", tiff_junk, &request_osus_port);
request_osus_addr = tiff_junk;
n_data++; // Turn on manager
}
else if (strcmp(tiff_tag, "Osus-Request-Id") == 0) {
read_string_with_spaces(tiff_fd, stemp); // OSUS sensor name may have spaces
request_sensor_types.push_back(stemp);
}
else if (strcmp(tiff_tag,"Osus-Monitor-Dir") == 0) {
fscanf(tiff_fd,"%f %s", &dir_time_osus, name);
if (!check_dir_exists(name)) exit_safe_s("In tag Osus-Monitor-Dir, dir does not exist", name);
dirname_osus = name;
dir_flag_osus = 1;
}
else if (strcmp(tiff_tag,"Osus-Monitor-Pat") == 0) {
fscanf(tiff_fd,"%s", name);
dir_monitor_pattern_osus = name;
}
else if (strcmp(tiff_tag, "Osus-Add-Sensor") == 0) {
int stationary_flag, local_flag, camera_flag, prox_flag, red, grn, blu, acoustic_flag=0, bearing_flag=0;
fscanf(tiff_fd, "%d %d %d %d %d %d %d", &stationary_flag, &local_flag, &camera_flag, &prox_flag, &red, &grn, &blu);
read_string_with_spaces(tiff_fd, stemp); // OSUS sensor name may have spaces
read_string_with_spaces(tiff_fd, sname); // OSUS sensor name may have spaces
valid_asset_type.push_back(stemp);
valid_asset_name.push_back(sname);
valid_asset_filter_flags.push_back(0); // No filters
valid_asset_stat_flags.push_back(stationary_flag);
valid_asset_local_flags.push_back(local_flag);
valid_asset_camera_flags.push_back(camera_flag);
valid_asset_prox_flags.push_back(prox_flag);
valid_asset_red.push_back(red);
valid_asset_grn.push_back(grn);
valid_asset_blu.push_back(blu);
sensor_read_osus->add_valid_sensor_type(stemp, sname, camera_flag, acoustic_flag, bearing_flag, stationary_flag, local_flag);
n_data++; // Turn on manager
}
else if (strcmp(tiff_tag, "Osus-Warn-Level") == 0) {
fscanf(tiff_fd, "%d", &n_warn);
}
else if (strcmp(tiff_tag,"Osus-Diag-Level") == 0) {
fscanf(tiff_fd,"%d", &diag_flag);
sensor_read_osus->set_diag_flag(diag_flag);
}
else {
fgets(tiff_junk,240,tiff_fd);
}
} while (ntiff == 1);
fclose(tiff_fd);
return(1);
}
// *******************************************
/// Write parameters to the currently opened ASCII file -- for saving all relevent parameters to an output Parameter file.
/// Assumes that the file has already been opened and will be closed outside this class.
// *******************************************
int sensor_osus_manager_class::write_parms(FILE *out_fd)
{
fprintf(out_fd, "# Sensor OSUS tags ######################################\n");
if (n_data > 0) {
if (dir_flag_osus) fprintf(out_fd, "Osus-Monitor-Dir %f %s\n", dir_time_osus, dirname_osus.c_str());
if (offset_lat != 0. || offset_lon != 0.) fprintf(out_fd, "Osus-Offset-M %f %f %f\n", offset_lat, offset_lon, offset_elev);
//if (d_above_ground != 20.) fprintf(out_fd, "Vector-Above-Ground %f\n", d_above_ground);
//if (diag_flag != 0) fprintf(out_fd, "Vector-Diag-Level %d\n", diag_flag);
}
fprintf(out_fd, "\n");
return(1);
}
// *******************************************
/// Sort O&M by file create time -- Private.
// *******************************************
int sensor_osus_manager_class::sort_oml(int ifirst, int ilast)
{
int i = ifirst;
int j = ilast;
time_t tmpt;
int tmpi;
time_t pivot = om_create_time[(ifirst+ilast) / 2];
// partition
while (i <= j) {
while (om_create_time[i] < pivot)
i++;
while (om_create_time[j] > pivot)
j--;
if (i <= j) {
tmpt = om_create_time[i];
om_create_time[i] = om_create_time[j];
om_create_time[j] = tmpt;
tmpi = om_sorted_index[i];
om_sorted_index[i] = om_sorted_index[j];
om_sorted_index[j] = tmpi;
i++;
j--;
}
};
// Recursion
if (ifirst < j)
sort_oml(ifirst, j);
if (i < ilast)
sort_oml(i, ilast);
return(1);
}
// ********************************************************************************
// Virtual
// ********************************************************************************
//int sensor_osus_manager_class::make_sensor_image_screen(float scaleFactor, xml_class *xmlt)
//{
// std::cerr << "sensor_osus_manager_class::make_sensor_image_screen: default method dummy" << std::endl;
// return(0);
//}
// **********************************************
/// Read and process any new OSUS files that have been put into the monitored directory since the last read -- Private.
/// @param n_new_sml Number of new sensors found
/// @param n_new_oml Number of new observations found
// **********************************************
int sensor_osus_manager_class::process_new_files_from_dir_osus(int &n_new_sml, int &n_new_oml)
{
int status;
string filename;
char dump[300];
float dnorth, deast, delev;
int i, ifirst, ilast, i_icon, i_icon_match, image_nx, image_ny, image_np;
unsigned char *image_data;
string sensor_id;
time_t rawtime;
tm* ptm;
// *********************************
// Find any new files
// *********************************
dir_monitor_class *dir_monitor = new dir_monitor_class();
dir_monitor->set_dir(dirname_osus.c_str());
if (use_modify_time_flag) dir_monitor->set_use_modify_time();
dir_monitor->set_min_create_time(min_create_time_osus); // Initial min time 0 allows all files
dir_monitor->find_all_with_pattern(dir_monitor_pattern_osus.c_str(), 1);
min_create_time_osus = dir_monitor->get_max_create_time();
int n_files = dir_monitor->get_nfiles();
if (n_files == 0) return(1);
// *********************************
// Wait a little to make sure writing is finished
// *********************************
cross_sleep(20); // Sleep time in msec
// *********************************
// Sort files by creation time
// *********************************
for (i=0; i<n_files; i++) {
om_create_time.push_back(dir_monitor->get_create_time(i));
om_sorted_index.push_back(i);
//cout << i << " orig time " << om_create_time[i] << endl;
}
if (n_files > 1) sort_oml(0, n_files - 1);
ifirst = om_sorted_index[0];
filename = dir_monitor->get_name(ifirst);
cout << "Earliest OSUS file " << filename << endl;
ilast = om_sorted_index[n_files-1];
filename = dir_monitor->get_name(ilast);
cout << "Latest OSUS file " << filename << endl;
rawtime = om_create_time[0];
ptm = gmtime(&rawtime);
cout << "First OSUS create time " << om_create_time[0] << " " << ptm->tm_hour << ":" << ptm->tm_min << ":" << ptm->tm_sec << endl;
rawtime = om_create_time[n_files-1];
ptm = gmtime(&rawtime);
cout << "Last OSUS create time " << om_create_time[n_files-1] << " " << ptm->tm_hour << ":" << ptm->tm_min << ":" << ptm->tm_sec << endl;
// *********************************
// Process files
// *********************************
n_new_sml = 0;
n_new_oml = 0;
sensor_read_osus->register_coord_system(gps_calc);
for (i=0; i<n_files; i++) {
int isort = om_sorted_index[i];
filename = dir_monitor->get_name(isort);
status = sensor_read_osus->read_file(filename.c_str()); // Return 0 for failed read, 1 for read OK but no useful info, 2 for new sensor with observation, 3 for observation only
if (status == 2) { //
n_new_sml++;
n_new_oml++;
}
else if (status == 3) { //
n_new_oml++;
}
// Process any images
if (status == 2 || status == 3) {
int flag = sensor_read_osus->get_current_image(image_nx, image_ny, image_np, image_data);
if (flag > 0) {
if (osus_image_store->make_sensor_image_screen(300.0f, image_nx, image_ny, image_np, image_data)) {
om_image_index.push_back(n_images);
n_images++;
}
else {
om_image_index.push_back(-99);
}
}
else {
om_image_index.push_back(-99);
}
}
}
int n_om = sensor_read_osus->get_n_om();
if (n_om > 0) {
cout << "New observations -- OSUS UGS: N new sensors=" << n_new_sml << ", N new obs=" << n_new_oml << endl;
time_conversion->set_float(sensor_read_osus->get_om_time(0));
cout << "First O&M observation time " << sensor_read_osus->get_om_time(0) << " gmt " << time_conversion->get_char() << endl;
time_conversion->set_float(sensor_read_osus->get_om_time(n_om-1));
cout << "Last O&M observation time " << sensor_read_osus->get_om_time(n_om-1) << " gmt " << time_conversion->get_char() << endl;
}
delete dir_monitor;
om_create_time.clear();
om_sorted_index.clear();
return(1);
}
| 36.161202 | 180 | 0.597053 | [
"vector"
] |
f75759f2a17df2ba9632dd742ea57bec4659cb43 | 344 | cpp | C++ | Algorithms/0946.Validate_Stack_Sequences.cpp | metehkaya/LeetCode | 52f4a1497758c6f996d515ced151e8783ae4d4d2 | [
"MIT"
] | 2 | 2020-07-20T06:40:22.000Z | 2021-11-20T01:23:26.000Z | Problems/LeetCode/Problems/0946.Validate_Stack_Sequences.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | Problems/LeetCode/Problems/0946.Validate_Stack_Sequences.cpp | metehkaya/Algo-Archive | 03b5fdcf06f84a03125c57762c36a4e03ca6e756 | [
"MIT"
] | null | null | null | class Solution {
public:
bool validateStackSequences(vector<int>& a, vector<int>& b) {
stack<int> st;
int n = a.size();
for( int i = 0 , j = 0 ; i < n ; i++ ) {
st.push(a[i]);
while(!st.empty() && st.top() == b[j])
st.pop() , j++;
}
return st.empty();
}
}; | 26.461538 | 65 | 0.415698 | [
"vector"
] |
f7594df9a9ecdcf5ca7bb980d6a207e63c1397cb | 1,106 | cpp | C++ | src/plugins/cgal/lua/module.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 232 | 2017-10-09T11:45:28.000Z | 2022-03-28T11:14:46.000Z | src/plugins/cgal/lua/module.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 26 | 2019-01-20T21:38:25.000Z | 2021-10-16T03:57:17.000Z | src/plugins/cgal/lua/module.cpp | martin-pr/possumwood | 0ee3e0fe13ef27cf14795a79fb497e4d700bef63 | [
"MIT"
] | 33 | 2017-10-26T19:20:38.000Z | 2022-03-16T11:21:43.000Z | #include "module.h"
#include "polyhedron.h"
namespace possumwood {
namespace cgal {
std::string Module::name() {
return "cgal";
}
void Module::init(possumwood::lua::State& state) {
using namespace luabind;
module(state, name().c_str())[class_<PolyhedronWrapper::Face>("face")
.def(luabind::constructor<>())
.def("addVertex", &PolyhedronWrapper::Face::addVertex),
class_<PolyhedronWrapper>("mesh")
.def(luabind::constructor<std::string>())
.def("addPoint", (std::size_t(PolyhedronWrapper::*)(float, float, float)) &
PolyhedronWrapper::addPoint)
.def("addPoint", (std::size_t(PolyhedronWrapper::*)(const lua::Vec3&)) &
PolyhedronWrapper::addPoint)
.def("addFace", &PolyhedronWrapper::addFace)];
}
} // namespace cgal
} // namespace possumwood
| 36.866667 | 110 | 0.487342 | [
"mesh"
] |
f75d498797583fe2e4f78f2ac157c186303a22ac | 3,024 | cpp | C++ | lib/tree/segment_tree.cpp | ta7uw/atcoder-cpp | 30c30ec3d5aab4f60a8447298316b7c36a1c32da | [
"MIT"
] | 1 | 2021-01-22T01:54:34.000Z | 2021-01-22T01:54:34.000Z | lib/tree/segment_tree.cpp | ta7uw/atcoder-cpp | 30c30ec3d5aab4f60a8447298316b7c36a1c32da | [
"MIT"
] | 13 | 2020-01-04T10:42:47.000Z | 2020-09-22T06:28:35.000Z | lib/tree/segment_tree.cpp | ta7uw/atcoder-cpp | 30c30ec3d5aab4f60a8447298316b7c36a1c32da | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using P = pair<ll, ll>;
using Graph = vector<vector<ll>>;
#define rep(i, n) for(ll i=0;i<(ll)(n);i++)
#define rep2(i, m, n) for(ll i=m;i<(ll)(n);i++)
#define rrep(i, n, m) for(ll i=n;i>=(ll)(m);i--)
const int dx[4] = {1, 0, -1, 0};
const int dy[4] = {0, 1, 0, -1};
const int ddx[8] = {0, 1, 1, 1, 0, -1, -1, -1};
const int ddy[8] = {1, 1, 0, -1, -1, -1, 0, 1};
const ll MOD = 1000000007;
const ll INF = 1000000000000000000L;
/**
* Library
* --------------------------------------------------------
*/
template<class Monoid>
class SegmentTree {
public:
/**
* @param N size
* @param e identity element
* @param operation operation to merge `data`
* @param updater operation to update `data`
*/
SegmentTree(size_t N, Monoid e, function<Monoid(Monoid, Monoid)> operation,
function<Monoid(Monoid, Monoid)> updater)
: e(e), operation(operation), updater(move(updater)) {
n = 1;
while (n < N) {
n *= 2;
}
data = vector<Monoid>(2 * n - 1, e);
for (int i = n - 2; i >= 0; i--) {
data[i] = operation(data[2 * i + 1], data[2 * i + 2]);
}
}
/**
* iの値をxに更新 ( 0-indexed )
*/
void update(int i, Monoid x) {
i += n - 1;
data[i] = updater(data[i], x);
while (i > 0) {
i = (i - 1) / 2;
data[i] = operation(data[i * 2 + 1], data[i * 2 + 2]);
}
}
/**
* [a, b)の区間でクエリを実行
*/
Monoid query(int a, int b) {
return query(a, b, 0, 0, n);
}
/**
* 添字でアクセス( 0-indexed )
*/
Monoid operator[](int i) {
return data[i + n - 1];
}
private:
int n;
vector<Monoid> data;
Monoid e;
function<Monoid(Monoid, Monoid)> operation;
function<Monoid(Monoid, Monoid)> updater;
Monoid query(int a, int b, int k, int l, int r) {
// 交差しない
if (r <= a || b <= l) return e;
// 区間 [a, b) に l, r が含まれる
if (a <= l && r <= b) return data[k];
// 左の子
Monoid c1 = query(a, b, 2 * k + 1, l, (l + r) / 2);
// 右の子
Monoid c2 = query(a, b, 2 * k + 2, (l + r) / 2, r);
return operation(c1, c2);
}
};
/**
* --------------------------------------------------------
*/
/**
* Range Minimum Query (RMQ)
* http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=DSL_2_A&lang=ja
*/
void Main() {
int N, Q;
cin >> N >> Q;
SegmentTree<ll> segmentTree(N, (1ll << 31) - 1, [](ll a, ll b) { return min(a, b); }, [](ll a, ll b) { return b; });
rep(q, Q) {
int com, x, y;
cin >> com >> x >> y;
if (com == 1) {
ll res = segmentTree.query(x, y + 1);
cout << res << '\n';
} else {
segmentTree.update(x, y);
}
}
}
int main() {
cin.tie(nullptr);
ios::sync_with_stdio(false);
cout << fixed << setprecision(15);
Main();
return 0;
}
| 24.786885 | 120 | 0.457011 | [
"vector"
] |
f767bf214836e157bc76d171d50da4beb31cce62 | 2,964 | cpp | C++ | src/dropbox/files/FilesSaveCopyReferenceError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 17 | 2016-12-03T09:12:29.000Z | 2020-06-20T22:08:44.000Z | src/dropbox/files/FilesSaveCopyReferenceError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-01-05T17:50:16.000Z | 2021-08-06T18:56:29.000Z | src/dropbox/files/FilesSaveCopyReferenceError.cpp | slashdotted/dropboxQt | 63d43fa882cec8fb980a2aab2464a2d7260b8089 | [
"MIT"
] | 8 | 2017-09-13T17:28:40.000Z | 2020-07-27T00:41:44.000Z | /**********************************************************
DO NOT EDIT
This file was generated from stone specification "files"
Part of "Ardi - the organizer" project.
osoft4ardi@gmail.com
www.prokarpaty.net
***********************************************************/
#include "dropbox/files/FilesSaveCopyReferenceError.h"
namespace dropboxQt{
namespace files{
///SaveCopyReferenceError
SaveCopyReferenceError::operator QJsonObject()const{
QJsonObject js;
this->toJson(js, "");
return js;
}
void SaveCopyReferenceError::toJson(QJsonObject& js, QString name)const{
switch(m_tag){
case SaveCopyReferenceError_PATH:{
if(!name.isEmpty())
js[name] = QString("path");
m_path.toJson(js, "path");
}break;
case SaveCopyReferenceError_INVALID_COPY_REFERENCE:{
if(!name.isEmpty())
js[name] = QString("invalid_copy_reference");
}break;
case SaveCopyReferenceError_NO_PERMISSION:{
if(!name.isEmpty())
js[name] = QString("no_permission");
}break;
case SaveCopyReferenceError_NOT_FOUND:{
if(!name.isEmpty())
js[name] = QString("not_found");
}break;
case SaveCopyReferenceError_TOO_MANY_FILES:{
if(!name.isEmpty())
js[name] = QString("too_many_files");
}break;
case SaveCopyReferenceError_OTHER:{
if(!name.isEmpty())
js[name] = QString("other");
}break;
}//switch
}
void SaveCopyReferenceError::fromJson(const QJsonObject& js){
QString s = js[".tag"].toString();
if(s.compare("path") == 0){
m_tag = SaveCopyReferenceError_PATH;
m_path.fromJson(js["path"].toObject());
}
else if(s.compare("invalid_copy_reference") == 0){
m_tag = SaveCopyReferenceError_INVALID_COPY_REFERENCE;
}
else if(s.compare("no_permission") == 0){
m_tag = SaveCopyReferenceError_NO_PERMISSION;
}
else if(s.compare("not_found") == 0){
m_tag = SaveCopyReferenceError_NOT_FOUND;
}
else if(s.compare("too_many_files") == 0){
m_tag = SaveCopyReferenceError_TOO_MANY_FILES;
}
else if(s.compare("other") == 0){
m_tag = SaveCopyReferenceError_OTHER;
}
}
QString SaveCopyReferenceError::toString(bool multiline)const
{
QJsonObject js;
toJson(js, "SaveCopyReferenceError");
QJsonDocument doc(js);
QString s(doc.toJson(multiline ? QJsonDocument::Indented : QJsonDocument::Compact));
return s;
}
std::unique_ptr<SaveCopyReferenceError> SaveCopyReferenceError::factory::create(const QByteArray& data)
{
QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject js = doc.object();
std::unique_ptr<SaveCopyReferenceError> rv = std::unique_ptr<SaveCopyReferenceError>(new SaveCopyReferenceError);
rv->fromJson(js);
return rv;
}
}//files
}//dropboxQt
| 28.776699 | 117 | 0.620445 | [
"object"
] |
f772011241f079148c400d80b9d29ab68298e949 | 64,976 | cc | C++ | project4/mariadb/server/sql/filesort.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 11 | 2017-10-28T08:41:08.000Z | 2021-06-24T07:24:21.000Z | project4/mariadb/server/sql/filesort.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | null | null | null | project4/mariadb/server/sql/filesort.cc | jiunbae/ITE4065 | 3b9fcf9317e93ca7c829f1438b85f0f5ea2885db | [
"MIT"
] | 4 | 2017-09-07T09:33:26.000Z | 2021-02-19T07:45:08.000Z | /* Copyright (c) 2000, 2015, Oracle and/or its affiliates.
Copyright (c) 2009, 2015, MariaDB
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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 */
/**
@file
@brief
Sorts a database
*/
#include <my_global.h>
#include "sql_priv.h"
#include "filesort.h"
#ifdef HAVE_STDDEF_H
#include <stddef.h> /* for macro offsetof */
#endif
#include <m_ctype.h>
#include "sql_sort.h"
#include "probes_mysql.h"
#include "sql_base.h"
#include "sql_test.h" // TEST_filesort
#include "opt_range.h" // SQL_SELECT
#include "bounded_queue.h"
#include "filesort_utils.h"
#include "sql_select.h"
#include "log_slow.h"
#include "debug_sync.h"
/// How to write record_ref.
#define WRITE_REF(file,from) \
if (my_b_write((file),(uchar*) (from),param->ref_length)) \
DBUG_RETURN(1);
/* functions defined in this file */
static uchar *read_buffpek_from_file(IO_CACHE *buffer_file, uint count,
uchar *buf);
static ha_rows find_all_keys(THD *thd, Sort_param *param, SQL_SELECT *select,
SORT_INFO *fs_info,
IO_CACHE *buffer_file,
IO_CACHE *tempfile,
Bounded_queue<uchar, uchar> *pq,
ha_rows *found_rows);
static bool write_keys(Sort_param *param, SORT_INFO *fs_info,
uint count, IO_CACHE *buffer_file, IO_CACHE *tempfile);
static void make_sortkey(Sort_param *param, uchar *to, uchar *ref_pos);
static void register_used_fields(Sort_param *param);
static bool save_index(Sort_param *param, uint count,
SORT_INFO *table_sort);
static uint suffix_length(ulong string_length);
static uint sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length,
bool *multi_byte_charset);
static SORT_ADDON_FIELD *get_addon_fields(ulong max_length_for_sort_data,
Field **ptabfield,
uint sortlength,
LEX_STRING *addon_buf);
static void unpack_addon_fields(struct st_sort_addon_field *addon_field,
uchar *buff, uchar *buff_end);
static bool check_if_pq_applicable(Sort_param *param, SORT_INFO *info,
TABLE *table,
ha_rows records, ulong memory_available);
void Sort_param::init_for_filesort(uint sortlen, TABLE *table,
ulong max_length_for_sort_data,
ha_rows maxrows, bool sort_positions)
{
DBUG_ASSERT(addon_field == 0 && addon_buf.length == 0);
sort_length= sortlen;
ref_length= table->file->ref_length;
if (!(table->file->ha_table_flags() & HA_FAST_KEY_READ) &&
!table->fulltext_searched && !sort_positions)
{
/*
Get the descriptors of all fields whose values are appended
to sorted fields and get its total length in addon_buf.length
*/
addon_field= get_addon_fields(max_length_for_sort_data,
table->field, sort_length, &addon_buf);
}
if (addon_field)
res_length= addon_buf.length;
else
{
res_length= ref_length;
/*
The reference to the record is considered
as an additional sorted field
*/
sort_length+= ref_length;
}
rec_length= sort_length + addon_buf.length;
max_rows= maxrows;
}
/**
Sort a table.
Creates a set of pointers that can be used to read the rows
in sorted order. This should be done with the functions
in records.cc.
Before calling filesort, one must have done
table->file->info(HA_STATUS_VARIABLE)
The result set is stored in
filesort_info->io_cache or
filesort_info->record_pointers.
@param thd Current thread
@param table Table to sort
@param filesort How to sort the table
@param[out] found_rows Store the number of found rows here.
This is the number of found rows after
applying WHERE condition.
@note
If we sort by position (like if filesort->sort_positions==true)
filesort() will call table->prepare_for_position().
@retval
0 Error
# SORT_INFO
*/
SORT_INFO *filesort(THD *thd, TABLE *table, Filesort *filesort,
Filesort_tracker* tracker, JOIN *join,
table_map first_table_bit)
{
int error;
DBUG_ASSERT(thd->variables.sortbuff_size <= SIZE_T_MAX);
size_t memory_available= (size_t)thd->variables.sortbuff_size;
uint maxbuffer;
BUFFPEK *buffpek;
ha_rows num_rows= HA_POS_ERROR;
IO_CACHE tempfile, buffpek_pointers, *outfile;
Sort_param param;
bool multi_byte_charset;
Bounded_queue<uchar, uchar> pq;
SQL_SELECT *const select= filesort->select;
ha_rows max_rows= filesort->limit;
uint s_length= 0;
DBUG_ENTER("filesort");
if (!(s_length= filesort->make_sortorder(thd, join, first_table_bit)))
DBUG_RETURN(NULL); /* purecov: inspected */
DBUG_EXECUTE("info",TEST_filesort(filesort->sortorder,s_length););
#ifdef SKIP_DBUG_IN_FILESORT
DBUG_PUSH(""); /* No DBUG here */
#endif
SORT_INFO *sort;
TABLE_LIST *tab= table->pos_in_table_list;
Item_subselect *subselect= tab ? tab->containing_subselect() : 0;
MYSQL_FILESORT_START(table->s->db.str, table->s->table_name.str);
DEBUG_SYNC(thd, "filesort_start");
if (!(sort= new SORT_INFO))
return 0;
if (subselect && subselect->filesort_buffer.is_allocated())
{
/* Reuse cache from last call */
sort->filesort_buffer= subselect->filesort_buffer;
sort->buffpek= subselect->sortbuffer;
subselect->filesort_buffer.reset();
subselect->sortbuffer.str=0;
}
outfile= &sort->io_cache;
my_b_clear(&tempfile);
my_b_clear(&buffpek_pointers);
buffpek=0;
error= 1;
sort->found_rows= HA_POS_ERROR;
param.init_for_filesort(sortlength(thd, filesort->sortorder, s_length,
&multi_byte_charset),
table,
thd->variables.max_length_for_sort_data,
max_rows, filesort->sort_positions);
sort->addon_buf= param.addon_buf;
sort->addon_field= param.addon_field;
sort->unpack= unpack_addon_fields;
if (multi_byte_charset &&
!(param.tmp_buffer= (char*) my_malloc(param.sort_length,
MYF(MY_WME | MY_THREAD_SPECIFIC))))
goto err;
if (select && select->quick)
thd->inc_status_sort_range();
else
thd->inc_status_sort_scan();
thd->query_plan_flags|= QPLAN_FILESORT;
tracker->report_use(max_rows);
// If number of rows is not known, use as much of sort buffer as possible.
num_rows= table->file->estimate_rows_upper_bound();
if (check_if_pq_applicable(¶m, sort,
table, num_rows, memory_available))
{
DBUG_PRINT("info", ("filesort PQ is applicable"));
thd->query_plan_flags|= QPLAN_FILESORT_PRIORITY_QUEUE;
status_var_increment(thd->status_var.filesort_pq_sorts_);
tracker->incr_pq_used();
const size_t compare_length= param.sort_length;
if (pq.init(param.max_rows,
true, // max_at_top
NULL, // compare_function
compare_length,
&make_sortkey, ¶m, sort->get_sort_keys()))
{
/*
If we fail to init pq, we have to give up:
out of memory means my_malloc() will call my_error().
*/
DBUG_PRINT("info", ("failed to allocate PQ"));
DBUG_ASSERT(thd->is_error());
goto err;
}
// For PQ queries (with limit) we initialize all pointers.
sort->init_record_pointers();
}
else
{
DBUG_PRINT("info", ("filesort PQ is not applicable"));
size_t min_sort_memory= MY_MAX(MIN_SORT_MEMORY,
param.sort_length*MERGEBUFF2);
set_if_bigger(min_sort_memory, sizeof(BUFFPEK*)*MERGEBUFF2);
while (memory_available >= min_sort_memory)
{
ulonglong keys= memory_available / (param.rec_length + sizeof(char*));
param.max_keys_per_buffer= (uint) MY_MIN(num_rows, keys);
if (sort->alloc_sort_buffer(param.max_keys_per_buffer, param.rec_length))
break;
size_t old_memory_available= memory_available;
memory_available= memory_available/4*3;
if (memory_available < min_sort_memory &&
old_memory_available > min_sort_memory)
memory_available= min_sort_memory;
}
if (memory_available < min_sort_memory)
{
my_error(ER_OUT_OF_SORTMEMORY,MYF(ME_ERROR + ME_FATALERROR));
goto err;
}
tracker->report_sort_buffer_size(sort->sort_buffer_size());
}
if (open_cached_file(&buffpek_pointers,mysql_tmpdir,TEMP_PREFIX,
DISK_BUFFER_SIZE, MYF(MY_WME)))
goto err;
param.sort_form= table;
param.end=(param.local_sortorder=filesort->sortorder)+s_length;
num_rows= find_all_keys(thd, ¶m, select,
sort,
&buffpek_pointers,
&tempfile,
pq.is_initialized() ? &pq : NULL,
&sort->found_rows);
if (num_rows == HA_POS_ERROR)
goto err;
maxbuffer= (uint) (my_b_tell(&buffpek_pointers)/sizeof(*buffpek));
tracker->report_merge_passes_at_start(thd->query_plan_fsort_passes);
tracker->report_row_numbers(param.examined_rows, sort->found_rows, num_rows);
if (maxbuffer == 0) // The whole set is in memory
{
if (save_index(¶m, (uint) num_rows, sort))
goto err;
}
else
{
/* filesort cannot handle zero-length records during merge. */
DBUG_ASSERT(param.sort_length != 0);
if (sort->buffpek.str && sort->buffpek.length < maxbuffer)
{
my_free(sort->buffpek.str);
sort->buffpek.str= 0;
}
if (!(sort->buffpek.str=
(char *) read_buffpek_from_file(&buffpek_pointers, maxbuffer,
(uchar*) sort->buffpek.str)))
goto err;
sort->buffpek.length= maxbuffer;
buffpek= (BUFFPEK *) sort->buffpek.str;
close_cached_file(&buffpek_pointers);
/* Open cached file if it isn't open */
if (! my_b_inited(outfile) &&
open_cached_file(outfile,mysql_tmpdir,TEMP_PREFIX,READ_RECORD_BUFFER,
MYF(MY_WME)))
goto err;
if (reinit_io_cache(outfile,WRITE_CACHE,0L,0,0))
goto err;
/*
Use also the space previously used by string pointers in sort_buffer
for temporary key storage.
*/
param.max_keys_per_buffer=((param.max_keys_per_buffer *
(param.rec_length + sizeof(char*))) /
param.rec_length - 1);
maxbuffer--; // Offset from 0
if (merge_many_buff(¶m,
(uchar*) sort->get_sort_keys(),
buffpek,&maxbuffer,
&tempfile))
goto err;
if (flush_io_cache(&tempfile) ||
reinit_io_cache(&tempfile,READ_CACHE,0L,0,0))
goto err;
if (merge_index(¶m,
(uchar*) sort->get_sort_keys(),
buffpek,
maxbuffer,
&tempfile,
outfile))
goto err;
}
if (num_rows > param.max_rows)
{
// If find_all_keys() produced more results than the query LIMIT.
num_rows= param.max_rows;
}
error= 0;
err:
my_free(param.tmp_buffer);
if (!subselect || !subselect->is_uncacheable())
{
sort->free_sort_buffer();
my_free(sort->buffpek.str);
}
else
{
/* Remember sort buffers for next subquery call */
subselect->filesort_buffer= sort->filesort_buffer;
subselect->sortbuffer= sort->buffpek;
sort->filesort_buffer.reset(); // Don't free this
}
sort->buffpek.str= 0;
close_cached_file(&tempfile);
close_cached_file(&buffpek_pointers);
if (my_b_inited(outfile))
{
if (flush_io_cache(outfile))
error=1;
{
my_off_t save_pos=outfile->pos_in_file;
/* For following reads */
if (reinit_io_cache(outfile,READ_CACHE,0L,0,0))
error=1;
outfile->end_of_file=save_pos;
}
}
tracker->report_merge_passes_at_end(thd->query_plan_fsort_passes);
if (error)
{
int kill_errno= thd->killed_errno();
DBUG_ASSERT(thd->is_error() || kill_errno || thd->killed == ABORT_QUERY);
my_printf_error(ER_FILSORT_ABORT,
"%s: %s",
MYF(0),
ER_THD(thd, ER_FILSORT_ABORT),
kill_errno ? ER_THD(thd, kill_errno) :
thd->killed == ABORT_QUERY ? "" :
thd->get_stmt_da()->message());
if (global_system_variables.log_warnings > 1)
{
sql_print_warning("%s, host: %s, user: %s, thread: %lu, query: %-.4096s",
ER_THD(thd, ER_FILSORT_ABORT),
thd->security_ctx->host_or_ip,
&thd->security_ctx->priv_user[0],
(ulong) thd->thread_id,
thd->query());
}
}
else
thd->inc_status_sort_rows(num_rows);
sort->examined_rows= param.examined_rows;
sort->return_rows= num_rows;
#ifdef SKIP_DBUG_IN_FILESORT
DBUG_POP(); /* Ok to DBUG */
#endif
DBUG_PRINT("exit",
("num_rows: %lld examined_rows: %lld found_rows: %lld",
(longlong) sort->return_rows, (longlong) sort->examined_rows,
(longlong) sort->found_rows));
MYSQL_FILESORT_DONE(error, num_rows);
if (error)
{
delete sort;
sort= 0;
}
DBUG_RETURN(sort);
} /* filesort */
void Filesort::cleanup()
{
if (select && own_select)
{
select->cleanup();
select= NULL;
}
}
uint Filesort::make_sortorder(THD *thd, JOIN *join, table_map first_table_bit)
{
uint count;
SORT_FIELD *sort,*pos;
ORDER *ord;
DBUG_ENTER("make_sortorder");
count=0;
for (ord = order; ord; ord= ord->next)
count++;
if (!sortorder)
sortorder= (SORT_FIELD*) thd->alloc(sizeof(SORT_FIELD) * (count + 1));
pos= sort= sortorder;
if (!pos)
DBUG_RETURN(0);
for (ord= order; ord; ord= ord->next, pos++)
{
Item *first= ord->item[0];
/*
It is possible that the query plan is to read table t1, while the
sort criteria actually has "ORDER BY t2.col" and the WHERE clause has
a multi-equality(t1.col, t2.col, ...).
The optimizer detects such cases (grep for
UseMultipleEqualitiesToRemoveTempTable to see where), but doesn't
perform equality substitution in the order->item. We need to do the
substitution here ourselves.
*/
table_map item_map= first->used_tables();
if (join && (item_map & ~join->const_table_map) &&
!(item_map & first_table_bit) && join->cond_equal &&
first->get_item_equal())
{
/*
Ok, this is the case descibed just above. Get the first element of the
multi-equality.
*/
Item_equal *item_eq= first->get_item_equal();
first= item_eq->get_first(NO_PARTICULAR_TAB, NULL);
}
Item *item= first->real_item();
pos->field= 0; pos->item= 0;
if (item->type() == Item::FIELD_ITEM)
pos->field= ((Item_field*) item)->field;
else if (item->type() == Item::SUM_FUNC_ITEM && !item->const_item())
pos->field= ((Item_sum*) item)->get_tmp_table_field();
else if (item->type() == Item::COPY_STR_ITEM)
{ // Blob patch
pos->item= ((Item_copy*) item)->get_item();
}
else
pos->item= *ord->item;
pos->reverse= (ord->direction == ORDER::ORDER_DESC);
DBUG_ASSERT(pos->field != NULL || pos->item != NULL);
}
DBUG_RETURN(count);
}
/** Read 'count' number of buffer pointers into memory. */
static uchar *read_buffpek_from_file(IO_CACHE *buffpek_pointers, uint count,
uchar *buf)
{
size_t length= sizeof(BUFFPEK)*count;
uchar *tmp= buf;
DBUG_ENTER("read_buffpek_from_file");
if (count > UINT_MAX/sizeof(BUFFPEK))
return 0; /* sizeof(BUFFPEK)*count will overflow */
if (!tmp)
tmp= (uchar *)my_malloc(length, MYF(MY_WME | MY_THREAD_SPECIFIC));
if (tmp)
{
if (reinit_io_cache(buffpek_pointers,READ_CACHE,0L,0,0) ||
my_b_read(buffpek_pointers, (uchar*) tmp, length))
{
my_free(tmp);
tmp=0;
}
}
DBUG_RETURN(tmp);
}
#ifndef DBUG_OFF
/* Buffer where record is returned */
char dbug_print_row_buff[512];
/* Temporary buffer for printing a column */
char dbug_print_row_buff_tmp[512];
/*
Print table's current row into a buffer and return a pointer to it.
This is intended to be used from gdb:
(gdb) p dbug_print_table_row(table)
$33 = "SUBQUERY2_t1(col_int_key,col_varchar_nokey)=(7,c)"
(gdb)
Only columns in table->read_set are printed
*/
const char* dbug_print_table_row(TABLE *table)
{
Field **pfield;
String tmp(dbug_print_row_buff_tmp,
sizeof(dbug_print_row_buff_tmp),&my_charset_bin);
String output(dbug_print_row_buff, sizeof(dbug_print_row_buff),
&my_charset_bin);
output.length(0);
output.append(table->alias);
output.append("(");
bool first= true;
for (pfield= table->field; *pfield ; pfield++)
{
if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index))
continue;
if (first)
first= false;
else
output.append(",");
output.append((*pfield)->field_name? (*pfield)->field_name: "NULL");
}
output.append(")=(");
first= true;
for (pfield= table->field; *pfield ; pfield++)
{
Field *field= *pfield;
if (table->read_set && !bitmap_is_set(table->read_set, (*pfield)->field_index))
continue;
if (first)
first= false;
else
output.append(",");
if (field->is_null())
output.append("NULL");
else
{
if (field->type() == MYSQL_TYPE_BIT)
(void) field->val_int_as_str(&tmp, 1);
else
field->val_str(&tmp);
output.append(tmp.ptr(), tmp.length());
}
}
output.append(")");
return output.c_ptr_safe();
}
/*
Print a text, SQL-like record representation into dbug trace.
Note: this function is a work in progress: at the moment
- column read bitmap is ignored (can print garbage for unused columns)
- there is no quoting
*/
static void dbug_print_record(TABLE *table, bool print_rowid)
{
char buff[1024];
Field **pfield;
String tmp(buff,sizeof(buff),&my_charset_bin);
DBUG_LOCK_FILE;
fprintf(DBUG_FILE, "record (");
for (pfield= table->field; *pfield ; pfield++)
fprintf(DBUG_FILE, "%s%s", (*pfield)->field_name, (pfield[1])? ", ":"");
fprintf(DBUG_FILE, ") = ");
fprintf(DBUG_FILE, "(");
for (pfield= table->field; *pfield ; pfield++)
{
Field *field= *pfield;
if (field->is_null())
fwrite("NULL", sizeof(char), 4, DBUG_FILE);
if (field->type() == MYSQL_TYPE_BIT)
(void) field->val_int_as_str(&tmp, 1);
else
field->val_str(&tmp);
fwrite(tmp.ptr(),sizeof(char),tmp.length(),DBUG_FILE);
if (pfield[1])
fwrite(", ", sizeof(char), 2, DBUG_FILE);
}
fprintf(DBUG_FILE, ")");
if (print_rowid)
{
fprintf(DBUG_FILE, " rowid ");
for (uint i=0; i < table->file->ref_length; i++)
{
fprintf(DBUG_FILE, "%x", (uchar)table->file->ref[i]);
}
}
fprintf(DBUG_FILE, "\n");
DBUG_UNLOCK_FILE;
}
#endif
/**
Search after sort_keys, and write them into tempfile
(if we run out of space in the sort_keys buffer).
All produced sequences are guaranteed to be non-empty.
@param param Sorting parameter
@param select Use this to get source data
@param sort_keys Array of pointers to sort key + addon buffers.
@param buffpek_pointers File to write BUFFPEKs describing sorted segments
in tempfile.
@param tempfile File to write sorted sequences of sortkeys to.
@param pq If !NULL, use it for keeping top N elements
@param [out] found_rows The number of FOUND_ROWS().
For a query with LIMIT, this value will typically
be larger than the function return value.
@note
Basic idea:
@verbatim
while (get_next_sortkey())
{
if (using priority queue)
push sort key into queue
else
{
if (no free space in sort_keys buffers)
{
sort sort_keys buffer;
dump sorted sequence to 'tempfile';
dump BUFFPEK describing sequence location into 'buffpek_pointers';
}
put sort key into 'sort_keys';
}
}
if (sort_keys has some elements && dumped at least once)
sort-dump-dump as above;
else
don't sort, leave sort_keys array to be sorted by caller.
@endverbatim
@retval
Number of records written on success.
@retval
HA_POS_ERROR on error.
*/
static ha_rows find_all_keys(THD *thd, Sort_param *param, SQL_SELECT *select,
SORT_INFO *fs_info,
IO_CACHE *buffpek_pointers,
IO_CACHE *tempfile,
Bounded_queue<uchar, uchar> *pq,
ha_rows *found_rows)
{
int error,flag,quick_select;
uint idx,indexpos,ref_length;
uchar *ref_pos,*next_pos,ref_buff[MAX_REFLENGTH];
my_off_t record;
TABLE *sort_form;
handler *file;
MY_BITMAP *save_read_set, *save_write_set, *save_vcol_set;
Item *sort_cond;
DBUG_ENTER("find_all_keys");
DBUG_PRINT("info",("using: %s",
(select ? select->quick ? "ranges" : "where":
"every row")));
idx=indexpos=0;
error=quick_select=0;
sort_form=param->sort_form;
file=sort_form->file;
ref_length=param->ref_length;
ref_pos= ref_buff;
quick_select=select && select->quick;
record=0;
*found_rows= 0;
flag= ((file->ha_table_flags() & HA_REC_NOT_IN_SEQ) || quick_select);
if (flag)
ref_pos= &file->ref[0];
next_pos=ref_pos;
DBUG_EXECUTE_IF("show_explain_in_find_all_keys",
dbug_serve_apcs(thd, 1);
);
if (!quick_select)
{
next_pos=(uchar*) 0; /* Find records in sequence */
DBUG_EXECUTE_IF("bug14365043_1",
DBUG_SET("+d,ha_rnd_init_fail"););
if (file->ha_rnd_init_with_error(1))
DBUG_RETURN(HA_POS_ERROR);
file->extra_opt(HA_EXTRA_CACHE, thd->variables.read_buff_size);
}
/* Remember original bitmaps */
save_read_set= sort_form->read_set;
save_write_set= sort_form->write_set;
save_vcol_set= sort_form->vcol_set;
/* Set up temporary column read map for columns used by sort */
DBUG_ASSERT(save_read_set != &sort_form->tmp_set);
bitmap_clear_all(&sort_form->tmp_set);
sort_form->column_bitmaps_set(&sort_form->tmp_set, &sort_form->tmp_set,
&sort_form->tmp_set);
register_used_fields(param);
if (quick_select)
select->quick->add_used_key_part_to_set();
sort_cond= (!select ? 0 :
(!select->pre_idx_push_select_cond ?
select->cond : select->pre_idx_push_select_cond));
if (sort_cond)
sort_cond->walk(&Item::register_field_in_read_map, 1, sort_form);
sort_form->file->column_bitmaps_signal();
if (quick_select)
{
if (select->quick->reset())
DBUG_RETURN(HA_POS_ERROR);
}
DEBUG_SYNC(thd, "after_index_merge_phase1");
for (;;)
{
if (quick_select)
{
if ((error= select->quick->get_next()))
break;
file->position(sort_form->record[0]);
DBUG_EXECUTE_IF("debug_filesort", dbug_print_record(sort_form, TRUE););
}
else /* Not quick-select */
{
{
error= file->ha_rnd_next(sort_form->record[0]);
if (!flag)
{
my_store_ptr(ref_pos,ref_length,record); // Position to row
record+= sort_form->s->db_record_offset;
}
else if (!error)
file->position(sort_form->record[0]);
}
if (error && error != HA_ERR_RECORD_DELETED)
break;
}
if (thd->check_killed())
{
DBUG_PRINT("info",("Sort killed by user"));
if (!quick_select)
{
(void) file->extra(HA_EXTRA_NO_CACHE);
file->ha_rnd_end();
}
DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */
}
bool write_record= false;
if (error == 0)
{
param->examined_rows++;
if (select && select->cond)
{
/*
If the condition 'select->cond' contains a subquery, restore the
original read/write sets of the table 'sort_form' because when
SQL_SELECT::skip_record evaluates this condition. it may include a
correlated subquery predicate, such that some field in the subquery
refers to 'sort_form'.
PSergey-todo: discuss the above with Timour.
*/
MY_BITMAP *tmp_read_set= sort_form->read_set;
MY_BITMAP *tmp_write_set= sort_form->write_set;
MY_BITMAP *tmp_vcol_set= sort_form->vcol_set;
if (select->cond->with_subselect)
sort_form->column_bitmaps_set(save_read_set, save_write_set,
save_vcol_set);
write_record= (select->skip_record(thd) > 0);
if (select->cond->with_subselect)
sort_form->column_bitmaps_set(tmp_read_set,
tmp_write_set,
tmp_vcol_set);
}
else
write_record= true;
}
if (write_record)
{
++(*found_rows);
if (pq)
{
pq->push(ref_pos);
idx= pq->num_elements();
}
else
{
if (idx == param->max_keys_per_buffer)
{
if (write_keys(param, fs_info, idx, buffpek_pointers, tempfile))
DBUG_RETURN(HA_POS_ERROR);
idx= 0;
indexpos++;
}
make_sortkey(param, fs_info->get_record_buffer(idx++), ref_pos);
}
}
/* It does not make sense to read more keys in case of a fatal error */
if (thd->is_error())
break;
/*
We need to this after checking the error as the transaction may have
rolled back in case of a deadlock
*/
if (!write_record)
file->unlock_row();
}
if (!quick_select)
{
(void) file->extra(HA_EXTRA_NO_CACHE); /* End cacheing of records */
if (!next_pos)
file->ha_rnd_end();
}
if (thd->is_error())
DBUG_RETURN(HA_POS_ERROR);
/* Signal we should use orignal column read and write maps */
sort_form->column_bitmaps_set(save_read_set, save_write_set, save_vcol_set);
DBUG_PRINT("test",("error: %d indexpos: %d",error,indexpos));
if (error != HA_ERR_END_OF_FILE)
{
file->print_error(error,MYF(ME_ERROR | ME_WAITTANG)); // purecov: inspected
DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */
}
if (indexpos && idx &&
write_keys(param, fs_info, idx, buffpek_pointers, tempfile))
DBUG_RETURN(HA_POS_ERROR); /* purecov: inspected */
const ha_rows retval=
my_b_inited(tempfile) ?
(ha_rows) (my_b_tell(tempfile)/param->rec_length) : idx;
DBUG_PRINT("info", ("find_all_keys return %llu", (ulonglong) retval));
DBUG_RETURN(retval);
} /* find_all_keys */
/**
@details
Sort the buffer and write:
-# the sorted sequence to tempfile
-# a BUFFPEK describing the sorted sequence position to buffpek_pointers
(was: Skriver en buffert med nycklar till filen)
@param param Sort parameters
@param sort_keys Array of pointers to keys to sort
@param count Number of elements in sort_keys array
@param buffpek_pointers One 'BUFFPEK' struct will be written into this file.
The BUFFPEK::{file_pos, count} will indicate where
the sorted data was stored.
@param tempfile The sorted sequence will be written into this file.
@retval
0 OK
@retval
1 Error
*/
static bool
write_keys(Sort_param *param, SORT_INFO *fs_info, uint count,
IO_CACHE *buffpek_pointers, IO_CACHE *tempfile)
{
size_t rec_length;
uchar **end;
BUFFPEK buffpek;
DBUG_ENTER("write_keys");
rec_length= param->rec_length;
uchar **sort_keys= fs_info->get_sort_keys();
fs_info->sort_buffer(param, count);
if (!my_b_inited(tempfile) &&
open_cached_file(tempfile, mysql_tmpdir, TEMP_PREFIX, DISK_BUFFER_SIZE,
MYF(MY_WME)))
goto err; /* purecov: inspected */
/* check we won't have more buffpeks than we can possibly keep in memory */
if (my_b_tell(buffpek_pointers) + sizeof(BUFFPEK) > (ulonglong)UINT_MAX)
goto err;
bzero(&buffpek, sizeof(buffpek));
buffpek.file_pos= my_b_tell(tempfile);
if ((ha_rows) count > param->max_rows)
count=(uint) param->max_rows; /* purecov: inspected */
buffpek.count=(ha_rows) count;
for (end=sort_keys+count ; sort_keys != end ; sort_keys++)
if (my_b_write(tempfile, (uchar*) *sort_keys, (uint) rec_length))
goto err;
if (my_b_write(buffpek_pointers, (uchar*) &buffpek, sizeof(buffpek)))
goto err;
DBUG_RETURN(0);
err:
DBUG_RETURN(1);
} /* write_keys */
/**
Store length as suffix in high-byte-first order.
*/
static inline void store_length(uchar *to, uint length, uint pack_length)
{
switch (pack_length) {
case 1:
*to= (uchar) length;
break;
case 2:
mi_int2store(to, length);
break;
case 3:
mi_int3store(to, length);
break;
default:
mi_int4store(to, length);
break;
}
}
void
Type_handler_string_result::make_sort_key(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
CHARSET_INFO *cs= item->collation.collation;
bool maybe_null= item->maybe_null;
if (maybe_null)
*to++= 1;
char *tmp_buffer= param->tmp_buffer ? param->tmp_buffer : (char*) to;
String tmp(tmp_buffer, param->sort_length, cs);
String *res= item->str_result(&tmp);
if (!res)
{
if (maybe_null)
memset(to - 1, 0, sort_field->length + 1);
else
{
/* purecov: begin deadcode */
/*
This should only happen during extreme conditions if we run out
of memory or have an item marked not null when it can be null.
This code is here mainly to avoid a hard crash in this case.
*/
DBUG_ASSERT(0);
DBUG_PRINT("warning",
("Got null on something that shouldn't be null"));
memset(to, 0, sort_field->length); // Avoid crash
/* purecov: end */
}
return;
}
if (use_strnxfrm(cs))
{
uint tmp_length __attribute__((unused));
tmp_length= cs->coll->strnxfrm(cs, to, sort_field->length,
item->max_char_length() *
cs->strxfrm_multiply,
(uchar*) res->ptr(), res->length(),
MY_STRXFRM_PAD_WITH_SPACE |
MY_STRXFRM_PAD_TO_MAXLEN);
DBUG_ASSERT(tmp_length == sort_field->length);
}
else
{
uint diff;
uint sort_field_length= sort_field->length - sort_field->suffix_length;
uint length= res->length();
if (sort_field_length < length)
{
diff= 0;
length= sort_field_length;
}
else
diff= sort_field_length - length;
if (sort_field->suffix_length)
{
/* Store length last in result_string */
store_length(to + sort_field_length, length, sort_field->suffix_length);
}
/* apply cs->sort_order for case-insensitive comparison if needed */
my_strnxfrm(cs,(uchar*)to,length,(const uchar*)res->ptr(),length);
char fill_char= ((cs->state & MY_CS_BINSORT) ? (char) 0 : ' ');
cs->cset->fill(cs, (char *)to+length,diff,fill_char);
}
}
void
Type_handler_int_result::make_sort_key(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
longlong value= item->val_int_result();
make_sort_key_longlong(to, item->maybe_null, item->null_value,
item->unsigned_flag, value);
}
void
Type_handler_temporal_result::make_sort_key(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
MYSQL_TIME buf;
if (item->get_date_result(&buf, TIME_INVALID_DATES))
{
DBUG_ASSERT(item->maybe_null);
DBUG_ASSERT(item->null_value);
make_sort_key_longlong(to, item->maybe_null, true,
item->unsigned_flag, 0);
}
else
make_sort_key_longlong(to, item->maybe_null, false,
item->unsigned_flag, pack_time(&buf));
}
void
Type_handler::make_sort_key_longlong(uchar *to,
bool maybe_null,
bool null_value,
bool unsigned_flag,
longlong value) const
{
if (maybe_null)
{
if (null_value)
{
memset(to, 0, 9);
return;
}
*to++= 1;
}
to[7]= (uchar) value;
to[6]= (uchar) (value >> 8);
to[5]= (uchar) (value >> 16);
to[4]= (uchar) (value >> 24);
to[3]= (uchar) (value >> 32);
to[2]= (uchar) (value >> 40);
to[1]= (uchar) (value >> 48);
if (unsigned_flag) /* Fix sign */
to[0]= (uchar) (value >> 56);
else
to[0]= (uchar) (value >> 56) ^ 128; /* Reverse signbit */
}
void
Type_handler_decimal_result::make_sort_key(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
my_decimal dec_buf, *dec_val= item->val_decimal_result(&dec_buf);
if (item->maybe_null)
{
if (item->null_value)
{
memset(to, 0, sort_field->length + 1);
return;
}
*to++= 1;
}
my_decimal2binary(E_DEC_FATAL_ERROR, dec_val, to,
item->max_length - (item->decimals ? 1 : 0),
item->decimals);
}
void
Type_handler_real_result::make_sort_key(uchar *to, Item *item,
const SORT_FIELD_ATTR *sort_field,
Sort_param *param) const
{
double value= item->val_result();
if (item->maybe_null)
{
if (item->null_value)
{
memset(to, 0, sort_field->length + 1);
return;
}
*to++= 1;
}
change_double_for_sort(value, to);
}
/** Make a sort-key from record. */
static void make_sortkey(register Sort_param *param,
register uchar *to, uchar *ref_pos)
{
reg3 Field *field;
reg1 SORT_FIELD *sort_field;
reg5 uint length;
for (sort_field=param->local_sortorder ;
sort_field != param->end ;
sort_field++)
{
bool maybe_null=0;
if ((field=sort_field->field))
{ // Field
field->make_sort_key(to, sort_field->length);
if ((maybe_null = field->maybe_null()))
to++;
}
else
{ // Item
sort_field->item->make_sort_key(to, sort_field->item, sort_field, param);
if ((maybe_null= sort_field->item->maybe_null))
to++;
}
if (sort_field->reverse)
{ /* Revers key */
if (maybe_null && (to[-1]= !to[-1]))
{
to+= sort_field->length; // don't waste the time reversing all 0's
continue;
}
length=sort_field->length;
while (length--)
{
*to = (uchar) (~ *to);
to++;
}
}
else
to+= sort_field->length;
}
if (param->addon_field)
{
/*
Save field values appended to sorted fields.
First null bit indicators are appended then field values follow.
In this implementation we use fixed layout for field values -
the same for all records.
*/
SORT_ADDON_FIELD *addonf= param->addon_field;
uchar *nulls= to;
DBUG_ASSERT(addonf != 0);
memset(nulls, 0, addonf->offset);
to+= addonf->offset;
for ( ; (field= addonf->field) ; addonf++)
{
if (addonf->null_bit && field->is_null())
{
nulls[addonf->null_offset]|= addonf->null_bit;
#ifdef HAVE_valgrind
bzero(to, addonf->length);
#endif
}
else
{
#ifdef HAVE_valgrind
uchar *end= field->pack(to, field->ptr);
uint length= (uint) ((to + addonf->length) - end);
DBUG_ASSERT((int) length >= 0);
if (length)
bzero(end, length);
#else
(void) field->pack(to, field->ptr);
#endif
}
to+= addonf->length;
}
}
else
{
/* Save filepos last */
memcpy((uchar*) to, ref_pos, (size_t) param->ref_length);
}
return;
}
/*
Register fields used by sorting in the sorted table's read set
*/
static void register_used_fields(Sort_param *param)
{
reg1 SORT_FIELD *sort_field;
TABLE *table=param->sort_form;
for (sort_field= param->local_sortorder ;
sort_field != param->end ;
sort_field++)
{
Field *field;
if ((field= sort_field->field))
{
if (field->table == table)
field->register_field_in_read_map();
}
else
{ // Item
sort_field->item->walk(&Item::register_field_in_read_map, 1, table);
}
}
if (param->addon_field)
{
SORT_ADDON_FIELD *addonf= param->addon_field;
Field *field;
for ( ; (field= addonf->field) ; addonf++)
field->register_field_in_read_map();
}
else
{
/* Save filepos last */
table->prepare_for_position();
}
}
static bool save_index(Sort_param *param, uint count,
SORT_INFO *table_sort)
{
uint offset,res_length;
uchar *to;
DBUG_ENTER("save_index");
DBUG_ASSERT(table_sort->record_pointers == 0);
table_sort->sort_buffer(param, count);
res_length= param->res_length;
offset= param->rec_length-res_length;
if (!(to= table_sort->record_pointers=
(uchar*) my_malloc(res_length*count,
MYF(MY_WME | MY_THREAD_SPECIFIC))))
DBUG_RETURN(1); /* purecov: inspected */
uchar **sort_keys= table_sort->get_sort_keys();
for (uchar **end= sort_keys+count ; sort_keys != end ; sort_keys++)
{
memcpy(to, *sort_keys+offset, res_length);
to+= res_length;
}
DBUG_RETURN(0);
}
/**
Test whether priority queue is worth using to get top elements of an
ordered result set. If it is, then allocates buffer for required amount of
records
@param param Sort parameters.
@param filesort_info Filesort information.
@param table Table to sort.
@param num_rows Estimate of number of rows in source record set.
@param memory_available Memory available for sorting.
DESCRIPTION
Given a query like this:
SELECT ... FROM t ORDER BY a1,...,an LIMIT max_rows;
This function tests whether a priority queue should be used to keep
the result. Necessary conditions are:
- estimate that it is actually cheaper than merge-sort
- enough memory to store the <max_rows> records.
If we don't have space for <max_rows> records, but we *do* have
space for <max_rows> keys, we may rewrite 'table' to sort with
references to records instead of additional data.
(again, based on estimates that it will actually be cheaper).
@retval
true - if it's ok to use PQ
false - PQ will be slower than merge-sort, or there is not enough memory.
*/
bool check_if_pq_applicable(Sort_param *param,
SORT_INFO *filesort_info,
TABLE *table, ha_rows num_rows,
ulong memory_available)
{
DBUG_ENTER("check_if_pq_applicable");
/*
How much Priority Queue sort is slower than qsort.
Measurements (see unit test) indicate that PQ is roughly 3 times slower.
*/
const double PQ_slowness= 3.0;
if (param->max_rows == HA_POS_ERROR)
{
DBUG_PRINT("info", ("No LIMIT"));
DBUG_RETURN(false);
}
if (param->max_rows + 2 >= UINT_MAX)
{
DBUG_PRINT("info", ("Too large LIMIT"));
DBUG_RETURN(false);
}
ulong num_available_keys=
memory_available / (param->rec_length + sizeof(char*));
// We need 1 extra record in the buffer, when using PQ.
param->max_keys_per_buffer= (uint) param->max_rows + 1;
if (num_rows < num_available_keys)
{
// The whole source set fits into memory.
if (param->max_rows < num_rows/PQ_slowness )
{
DBUG_RETURN(filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->rec_length) != NULL);
}
else
{
// PQ will be slower.
DBUG_RETURN(false);
}
}
// Do we have space for LIMIT rows in memory?
if (param->max_keys_per_buffer < num_available_keys)
{
DBUG_RETURN(filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->rec_length) != NULL);
}
// Try to strip off addon fields.
if (param->addon_field)
{
const ulong row_length=
param->sort_length + param->ref_length + sizeof(char*);
num_available_keys= memory_available / row_length;
// Can we fit all the keys in memory?
if (param->max_keys_per_buffer < num_available_keys)
{
const double sort_merge_cost=
get_merge_many_buffs_cost_fast(num_rows,
num_available_keys,
row_length);
/*
PQ has cost:
(insert + qsort) * log(queue size) / TIME_FOR_COMPARE_ROWID +
cost of file lookup afterwards.
The lookup cost is a bit pessimistic: we take scan_time and assume
that on average we find the row after scanning half of the file.
A better estimate would be lookup cost, but note that we are doing
random lookups here, rather than sequential scan.
*/
const double pq_cpu_cost=
(PQ_slowness * num_rows + param->max_keys_per_buffer) *
log((double) param->max_keys_per_buffer) / TIME_FOR_COMPARE_ROWID;
const double pq_io_cost=
param->max_rows * table->file->scan_time() / 2.0;
const double pq_cost= pq_cpu_cost + pq_io_cost;
if (sort_merge_cost < pq_cost)
DBUG_RETURN(false);
if (filesort_info->alloc_sort_buffer(param->max_keys_per_buffer,
param->sort_length +
param->ref_length))
{
/* Make attached data to be references instead of fields. */
my_free(filesort_info->addon_field);
filesort_info->addon_field= NULL;
param->addon_field= NULL;
param->res_length= param->ref_length;
param->sort_length+= param->ref_length;
param->rec_length= param->sort_length;
DBUG_RETURN(true);
}
}
}
DBUG_RETURN(false);
}
/** Merge buffers to make < MERGEBUFF2 buffers. */
int merge_many_buff(Sort_param *param, uchar *sort_buffer,
BUFFPEK *buffpek, uint *maxbuffer, IO_CACHE *t_file)
{
register uint i;
IO_CACHE t_file2,*from_file,*to_file,*temp;
BUFFPEK *lastbuff;
DBUG_ENTER("merge_many_buff");
if (*maxbuffer < MERGEBUFF2)
DBUG_RETURN(0); /* purecov: inspected */
if (flush_io_cache(t_file) ||
open_cached_file(&t_file2,mysql_tmpdir,TEMP_PREFIX,DISK_BUFFER_SIZE,
MYF(MY_WME)))
DBUG_RETURN(1); /* purecov: inspected */
from_file= t_file ; to_file= &t_file2;
while (*maxbuffer >= MERGEBUFF2)
{
if (reinit_io_cache(from_file,READ_CACHE,0L,0,0))
goto cleanup;
if (reinit_io_cache(to_file,WRITE_CACHE,0L,0,0))
goto cleanup;
lastbuff=buffpek;
for (i=0 ; i <= *maxbuffer-MERGEBUFF*3/2 ; i+=MERGEBUFF)
{
if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++,
buffpek+i,buffpek+i+MERGEBUFF-1,0))
goto cleanup;
}
if (merge_buffers(param,from_file,to_file,sort_buffer,lastbuff++,
buffpek+i,buffpek+ *maxbuffer,0))
break; /* purecov: inspected */
if (flush_io_cache(to_file))
break; /* purecov: inspected */
temp=from_file; from_file=to_file; to_file=temp;
*maxbuffer= (uint) (lastbuff-buffpek)-1;
}
cleanup:
close_cached_file(to_file); // This holds old result
if (to_file == t_file)
{
*t_file=t_file2; // Copy result file
}
DBUG_RETURN(*maxbuffer >= MERGEBUFF2); /* Return 1 if interrupted */
} /* merge_many_buff */
/**
Read data to buffer.
@retval
(uint)-1 if something goes wrong
*/
uint read_to_buffer(IO_CACHE *fromfile, BUFFPEK *buffpek,
uint rec_length)
{
register uint count;
uint length;
if ((count=(uint) MY_MIN((ha_rows) buffpek->max_keys,buffpek->count)))
{
if (my_b_pread(fromfile, (uchar*) buffpek->base,
(length= rec_length*count), buffpek->file_pos))
return ((uint) -1);
buffpek->key=buffpek->base;
buffpek->file_pos+= length; /* New filepos */
buffpek->count-= count;
buffpek->mem_count= count;
}
return (count*rec_length);
} /* read_to_buffer */
/**
Put all room used by freed buffer to use in adjacent buffer.
Note, that we can't simply distribute memory evenly between all buffers,
because new areas must not overlap with old ones.
@param[in] queue list of non-empty buffers, without freed buffer
@param[in] reuse empty buffer
@param[in] key_length key length
*/
void reuse_freed_buff(QUEUE *queue, BUFFPEK *reuse, uint key_length)
{
uchar *reuse_end= reuse->base + reuse->max_keys * key_length;
for (uint i= queue_first_element(queue);
i <= queue_last_element(queue);
i++)
{
BUFFPEK *bp= (BUFFPEK *) queue_element(queue, i);
if (bp->base + bp->max_keys * key_length == reuse->base)
{
bp->max_keys+= reuse->max_keys;
return;
}
else if (bp->base == reuse_end)
{
bp->base= reuse->base;
bp->max_keys+= reuse->max_keys;
return;
}
}
DBUG_ASSERT(0);
}
/**
Merge buffers to one buffer.
@param param Sort parameter
@param from_file File with source data (BUFFPEKs point to this file)
@param to_file File to write the sorted result data.
@param sort_buffer Buffer for data to store up to MERGEBUFF2 sort keys.
@param lastbuff OUT Store here BUFFPEK describing data written to to_file
@param Fb First element in source BUFFPEKs array
@param Tb Last element in source BUFFPEKs array
@param flag
@retval
0 OK
@retval
other error
*/
int merge_buffers(Sort_param *param, IO_CACHE *from_file,
IO_CACHE *to_file, uchar *sort_buffer,
BUFFPEK *lastbuff, BUFFPEK *Fb, BUFFPEK *Tb,
int flag)
{
int error;
uint rec_length,res_length,offset;
size_t sort_length;
ulong maxcount;
ha_rows max_rows,org_max_rows;
my_off_t to_start_filepos;
uchar *strpos;
BUFFPEK *buffpek;
QUEUE queue;
qsort2_cmp cmp;
void *first_cmp_arg;
element_count dupl_count= 0;
uchar *src;
uchar *unique_buff= param->unique_buff;
const bool killable= !param->not_killable;
THD* const thd=current_thd;
DBUG_ENTER("merge_buffers");
thd->inc_status_sort_merge_passes();
thd->query_plan_fsort_passes++;
error=0;
rec_length= param->rec_length;
res_length= param->res_length;
sort_length= param->sort_length;
uint dupl_count_ofs= rec_length-sizeof(element_count);
uint min_dupl_count= param->min_dupl_count;
bool check_dupl_count= flag && min_dupl_count;
offset= (rec_length-
(flag && min_dupl_count ? sizeof(dupl_count) : 0)-res_length);
uint wr_len= flag ? res_length : rec_length;
uint wr_offset= flag ? offset : 0;
maxcount= (ulong) (param->max_keys_per_buffer/((uint) (Tb-Fb) +1));
to_start_filepos= my_b_tell(to_file);
strpos= sort_buffer;
org_max_rows=max_rows= param->max_rows;
set_if_bigger(maxcount, 1);
if (unique_buff)
{
cmp= param->compare;
first_cmp_arg= (void *) ¶m->cmp_context;
}
else
{
cmp= get_ptr_compare(sort_length);
first_cmp_arg= (void*) &sort_length;
}
if (init_queue(&queue, (uint) (Tb-Fb)+1, offsetof(BUFFPEK,key), 0,
(queue_compare) cmp, first_cmp_arg, 0, 0))
DBUG_RETURN(1); /* purecov: inspected */
for (buffpek= Fb ; buffpek <= Tb ; buffpek++)
{
buffpek->base= strpos;
buffpek->max_keys= maxcount;
strpos+=
(uint) (error= (int) read_to_buffer(from_file, buffpek, rec_length));
if (error == -1)
goto err; /* purecov: inspected */
buffpek->max_keys= buffpek->mem_count; // If less data in buffers than expected
queue_insert(&queue, (uchar*) buffpek);
}
if (unique_buff)
{
/*
Called by Unique::get()
Copy the first argument to unique_buff for unique removal.
Store it also in 'to_file'.
*/
buffpek= (BUFFPEK*) queue_top(&queue);
memcpy(unique_buff, buffpek->key, rec_length);
if (min_dupl_count)
memcpy(&dupl_count, unique_buff+dupl_count_ofs,
sizeof(dupl_count));
buffpek->key+= rec_length;
if (! --buffpek->mem_count)
{
if (!(error= (int) read_to_buffer(from_file, buffpek,
rec_length)))
{
(void) queue_remove_top(&queue);
reuse_freed_buff(&queue, buffpek, rec_length);
}
else if (error == -1)
goto err; /* purecov: inspected */
}
queue_replace_top(&queue); // Top element has been used
}
else
cmp= 0; // Not unique
while (queue.elements > 1)
{
if (killable && thd->check_killed())
{
error= 1; goto err; /* purecov: inspected */
}
for (;;)
{
buffpek= (BUFFPEK*) queue_top(&queue);
src= buffpek->key;
if (cmp) // Remove duplicates
{
if (!(*cmp)(first_cmp_arg, &unique_buff,
(uchar**) &buffpek->key))
{
if (min_dupl_count)
{
element_count cnt;
memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt));
dupl_count+= cnt;
}
goto skip_duplicate;
}
if (min_dupl_count)
{
memcpy(unique_buff+dupl_count_ofs, &dupl_count,
sizeof(dupl_count));
}
src= unique_buff;
}
/*
Do not write into the output file if this is the final merge called
for a Unique object used for intersection and dupl_count is less
than min_dupl_count.
If the Unique object is used to intersect N sets of unique elements
then for any element:
dupl_count >= N <=> the element is occurred in each of these N sets.
*/
if (!check_dupl_count || dupl_count >= min_dupl_count)
{
if (my_b_write(to_file, src+wr_offset, wr_len))
{
error=1; goto err; /* purecov: inspected */
}
}
if (cmp)
{
memcpy(unique_buff, (uchar*) buffpek->key, rec_length);
if (min_dupl_count)
memcpy(&dupl_count, unique_buff+dupl_count_ofs,
sizeof(dupl_count));
}
if (!--max_rows)
{
error= 0; /* purecov: inspected */
goto end; /* purecov: inspected */
}
skip_duplicate:
buffpek->key+= rec_length;
if (! --buffpek->mem_count)
{
if (!(error= (int) read_to_buffer(from_file, buffpek,
rec_length)))
{
(void) queue_remove_top(&queue);
reuse_freed_buff(&queue, buffpek, rec_length);
break; /* One buffer have been removed */
}
else if (error == -1)
goto err; /* purecov: inspected */
}
queue_replace_top(&queue); /* Top element has been replaced */
}
}
buffpek= (BUFFPEK*) queue_top(&queue);
buffpek->base= (uchar*) sort_buffer;
buffpek->max_keys= param->max_keys_per_buffer;
/*
As we know all entries in the buffer are unique, we only have to
check if the first one is the same as the last one we wrote
*/
if (cmp)
{
if (!(*cmp)(first_cmp_arg, &unique_buff, (uchar**) &buffpek->key))
{
if (min_dupl_count)
{
element_count cnt;
memcpy(&cnt, (uchar *) buffpek->key+dupl_count_ofs, sizeof(cnt));
dupl_count+= cnt;
}
buffpek->key+= rec_length;
--buffpek->mem_count;
}
if (min_dupl_count)
memcpy(unique_buff+dupl_count_ofs, &dupl_count,
sizeof(dupl_count));
if (!check_dupl_count || dupl_count >= min_dupl_count)
{
src= unique_buff;
if (my_b_write(to_file, src+wr_offset, wr_len))
{
error=1; goto err; /* purecov: inspected */
}
if (!--max_rows)
{
error= 0;
goto end;
}
}
}
do
{
if ((ha_rows) buffpek->mem_count > max_rows)
{ /* Don't write too many records */
buffpek->mem_count= (uint) max_rows;
buffpek->count= 0; /* Don't read more */
}
max_rows-= buffpek->mem_count;
if (flag == 0)
{
if (my_b_write(to_file, (uchar*) buffpek->key,
(size_t)(rec_length*buffpek->mem_count)))
{
error= 1; goto err; /* purecov: inspected */
}
}
else
{
register uchar *end;
src= buffpek->key+offset;
for (end= src+buffpek->mem_count*rec_length ;
src != end ;
src+= rec_length)
{
if (check_dupl_count)
{
memcpy((uchar *) &dupl_count, src+dupl_count_ofs, sizeof(dupl_count));
if (dupl_count < min_dupl_count)
continue;
}
if (my_b_write(to_file, src, wr_len))
{
error=1; goto err;
}
}
}
}
while ((error=(int) read_to_buffer(from_file, buffpek, rec_length))
!= -1 && error != 0);
end:
lastbuff->count= MY_MIN(org_max_rows-max_rows, param->max_rows);
lastbuff->file_pos= to_start_filepos;
err:
delete_queue(&queue);
DBUG_RETURN(error);
} /* merge_buffers */
/* Do a merge to output-file (save only positions) */
int merge_index(Sort_param *param, uchar *sort_buffer,
BUFFPEK *buffpek, uint maxbuffer,
IO_CACHE *tempfile, IO_CACHE *outfile)
{
DBUG_ENTER("merge_index");
if (merge_buffers(param,tempfile,outfile,sort_buffer,buffpek,buffpek,
buffpek+maxbuffer,1))
DBUG_RETURN(1); /* purecov: inspected */
DBUG_RETURN(0);
} /* merge_index */
static uint suffix_length(ulong string_length)
{
if (string_length < 256)
return 1;
if (string_length < 256L*256L)
return 2;
if (string_length < 256L*256L*256L)
return 3;
return 4; // Can't sort longer than 4G
}
void
Type_handler_string_result::sortlength(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
CHARSET_INFO *cs;
sortorder->length= item->max_length;
set_if_smaller(sortorder->length, thd->variables.max_sort_length);
if (use_strnxfrm((cs= item->collation.collation)))
{
sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length);
}
else if (cs == &my_charset_bin)
{
/* Store length last to be able to sort blob/varbinary */
sortorder->suffix_length= suffix_length(sortorder->length);
sortorder->length+= sortorder->suffix_length;
}
}
void
Type_handler_temporal_result::sortlength(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length= 8; // Sizof intern longlong
}
void
Type_handler_int_result::sortlength(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length= 8; // Sizof intern longlong
}
void
Type_handler_real_result::sortlength(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length= sizeof(double);
}
void
Type_handler_decimal_result::sortlength(THD *thd,
const Type_std_attributes *item,
SORT_FIELD_ATTR *sortorder) const
{
sortorder->length=
my_decimal_get_binary_size(item->max_length - (item->decimals ? 1 : 0),
item->decimals);
}
/**
Calculate length of sort key.
@param thd Thread handler
@param sortorder Order of items to sort
@param s_length Number of items to sort
@param[out] multi_byte_charset Set to 1 if we are using multi-byte charset
(In which case we have to use strxnfrm())
@note
sortorder->length is updated for each sort item.
@return
Total length of sort buffer in bytes
*/
static uint
sortlength(THD *thd, SORT_FIELD *sortorder, uint s_length,
bool *multi_byte_charset)
{
uint length;
*multi_byte_charset= 0;
length=0;
for (; s_length-- ; sortorder++)
{
sortorder->suffix_length= 0;
if (sortorder->field)
{
CHARSET_INFO *cs= sortorder->field->sort_charset();
sortorder->length= sortorder->field->sort_length();
if (use_strnxfrm((cs=sortorder->field->sort_charset())))
{
*multi_byte_charset= true;
sortorder->length= cs->coll->strnxfrmlen(cs, sortorder->length);
}
if (sortorder->field->maybe_null())
length++; // Place for NULL marker
}
else
{
sortorder->item->sortlength(thd, sortorder->item, sortorder);
if (use_strnxfrm(sortorder->item->collation.collation))
{
*multi_byte_charset= true;
}
if (sortorder->item->maybe_null)
length++; // Place for NULL marker
}
set_if_smaller(sortorder->length, thd->variables.max_sort_length);
length+=sortorder->length;
}
sortorder->field= (Field*) 0; // end marker
DBUG_PRINT("info",("sort_length: %d",length));
return length;
}
/**
Get descriptors of fields appended to sorted fields and
calculate its total length.
The function first finds out what fields are used in the result set.
Then it calculates the length of the buffer to store the values of
these fields together with the value of sort values.
If the calculated length is not greater than max_length_for_sort_data
the function allocates memory for an array of descriptors containing
layouts for the values of the non-sorted fields in the buffer and
fills them.
@param thd Current thread
@param ptabfield Array of references to the table fields
@param sortlength Total length of sorted fields
@param [out] addon_buf Buffer to us for appended fields
@note
The null bits for the appended values are supposed to be put together
and stored the buffer just ahead of the value of the first field.
@return
Pointer to the layout descriptors for the appended fields, if any
@retval
NULL if we do not store field values with sort data.
*/
static SORT_ADDON_FIELD *
get_addon_fields(ulong max_length_for_sort_data,
Field **ptabfield, uint sortlength, LEX_STRING *addon_buf)
{
Field **pfield;
Field *field;
SORT_ADDON_FIELD *addonf;
uint length= 0;
uint fields= 0;
uint null_fields= 0;
MY_BITMAP *read_set= (*ptabfield)->table->read_set;
DBUG_ENTER("get_addon_fields");
/*
If there is a reference to a field in the query add it
to the the set of appended fields.
Note for future refinement:
This this a too strong condition.
Actually we need only the fields referred in the
result set. And for some of them it makes sense to use
the values directly from sorted fields.
But beware the case when item->cmp_type() != item->result_type()
*/
addon_buf->str= 0;
addon_buf->length= 0;
for (pfield= ptabfield; (field= *pfield) ; pfield++)
{
if (!bitmap_is_set(read_set, field->field_index))
continue;
if (field->flags & BLOB_FLAG)
DBUG_RETURN(0);
length+= field->max_packed_col_length(field->pack_length());
if (field->maybe_null())
null_fields++;
fields++;
}
if (!fields)
DBUG_RETURN(0);
length+= (null_fields+7)/8;
if (length+sortlength > max_length_for_sort_data ||
!my_multi_malloc(MYF(MY_WME | MY_THREAD_SPECIFIC),
&addonf, sizeof(SORT_ADDON_FIELD) * (fields+1),
&addon_buf->str, length,
NullS))
DBUG_RETURN(0);
addon_buf->length= length;
length= (null_fields+7)/8;
null_fields= 0;
for (pfield= ptabfield; (field= *pfield) ; pfield++)
{
if (!bitmap_is_set(read_set, field->field_index))
continue;
addonf->field= field;
addonf->offset= length;
if (field->maybe_null())
{
addonf->null_offset= null_fields/8;
addonf->null_bit= 1<<(null_fields & 7);
null_fields++;
}
else
{
addonf->null_offset= 0;
addonf->null_bit= 0;
}
addonf->length= field->max_packed_col_length(field->pack_length());
length+= addonf->length;
addonf++;
}
addonf->field= 0; // Put end marker
DBUG_PRINT("info",("addon_length: %d",length));
DBUG_RETURN(addonf-fields);
}
/**
Copy (unpack) values appended to sorted fields from a buffer back to
their regular positions specified by the Field::ptr pointers.
@param addon_field Array of descriptors for appended fields
@param buff Buffer which to unpack the value from
@note
The function is supposed to be used only as a callback function
when getting field values for the sorted result set.
@return
void.
*/
static void
unpack_addon_fields(struct st_sort_addon_field *addon_field, uchar *buff,
uchar *buff_end)
{
Field *field;
SORT_ADDON_FIELD *addonf= addon_field;
for ( ; (field= addonf->field) ; addonf++)
{
if (addonf->null_bit && (addonf->null_bit & buff[addonf->null_offset]))
{
field->set_null();
continue;
}
field->set_notnull();
field->unpack(field->ptr, buff + addonf->offset, buff_end, 0);
}
}
/*
** functions to change a double or float to a sortable string
** The following should work for IEEE
*/
#define DBL_EXP_DIG (sizeof(double)*8-DBL_MANT_DIG)
void change_double_for_sort(double nr,uchar *to)
{
uchar *tmp=(uchar*) to;
if (nr == 0.0)
{ /* Change to zero string */
tmp[0]=(uchar) 128;
memset(tmp+1, 0, sizeof(nr)-1);
}
else
{
#ifdef WORDS_BIGENDIAN
memcpy(tmp, &nr, sizeof(nr));
#else
{
uchar *ptr= (uchar*) &nr;
#if defined(__FLOAT_WORD_ORDER) && (__FLOAT_WORD_ORDER == __BIG_ENDIAN)
tmp[0]= ptr[3]; tmp[1]=ptr[2]; tmp[2]= ptr[1]; tmp[3]=ptr[0];
tmp[4]= ptr[7]; tmp[5]=ptr[6]; tmp[6]= ptr[5]; tmp[7]=ptr[4];
#else
tmp[0]= ptr[7]; tmp[1]=ptr[6]; tmp[2]= ptr[5]; tmp[3]=ptr[4];
tmp[4]= ptr[3]; tmp[5]=ptr[2]; tmp[6]= ptr[1]; tmp[7]=ptr[0];
#endif
}
#endif
if (tmp[0] & 128) /* Negative */
{ /* make complement */
uint i;
for (i=0 ; i < sizeof(nr); i++)
tmp[i]=tmp[i] ^ (uchar) 255;
}
else
{ /* Set high and move exponent one up */
ushort exp_part=(((ushort) tmp[0] << 8) | (ushort) tmp[1] |
(ushort) 32768);
exp_part+= (ushort) 1 << (16-1-DBL_EXP_DIG);
tmp[0]= (uchar) (exp_part >> 8);
tmp[1]= (uchar) exp_part;
}
}
}
/**
Free SORT_INFO
*/
SORT_INFO::~SORT_INFO()
{
DBUG_ENTER("~SORT_INFO::SORT_INFO()");
free_data();
DBUG_VOID_RETURN;
}
| 29.710105 | 84 | 0.608886 | [
"object"
] |
f772ea1b3a927f946dfc9d8a691b0a678d984392 | 31,464 | cpp | C++ | generation-module/main.cpp | Sunssshine/VirtualCameraEmulator | 97e2af5ab179f800d3ea43f1b7590a56cc3da38f | [
"MIT"
] | null | null | null | generation-module/main.cpp | Sunssshine/VirtualCameraEmulator | 97e2af5ab179f800d3ea43f1b7590a56cc3da38f | [
"MIT"
] | null | null | null | generation-module/main.cpp | Sunssshine/VirtualCameraEmulator | 97e2af5ab179f800d3ea43f1b7590a56cc3da38f | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <iostream>
#include "CameraDriver.h"
#include "setup_config.h"
#include "Color.h"
#include "Shader.h"
#include "Cylinder.h"
#include "camera_definition.h"
#include "Paraboloid.h"
#include "CurvedBlade.h"
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavutil/imgutils.h>
#include <libavutil/opt.h>
#include <libswscale/swscale.h>
}
#include "utils/json.hpp"
#include "glm/glm.hpp"
#include "glm/gtc/type_ptr.hpp"
#include "glm/gtc/matrix_transform.hpp"
#define GLM_ENABLE_EXPERIMENTAL
#include "glm/gtx/spline.hpp"
enum Constants { SCREENSHOT_MAX_FILENAME = 256 };
static GLubyte* pixels = NULL;
static GLuint fbo;
static GLuint rbo_color;
static GLuint rbo_depth;
static const unsigned int HEIGHT = 800;
static const unsigned int WIDTH = 1500;
static int offscreen = 0;
static unsigned int max_nframes = 100;
static unsigned int nframes = 0;
static unsigned int time0;
/* Model. */
static double angle;
static double delta_angle;
/* Adapted from: https://github.com/cirosantilli/cpp-cheat/blob/19044698f91fefa9cb75328c44f7a487d336b541/ffmpeg/encode.c */
static AVCodecContext* c = NULL;
static AVFrame* frame;
static AVPacket pkt;
static FILE* file;
static struct SwsContext* sws_context = NULL;
static uint8_t* rgb = NULL;
static void ffmpeg_encoder_set_frame_yuv_from_rgb(uint8_t* rgb) {
const int in_linesize[1] = { 4 * c->width };
sws_context = sws_getCachedContext(sws_context,
c->width, c->height, AV_PIX_FMT_RGB32,
c->width, c->height, AV_PIX_FMT_YUV420P,
0, NULL, NULL, NULL);
sws_scale(sws_context, (const uint8_t* const*)&rgb, in_linesize, 0,
c->height, frame->data, frame->linesize);
}
void ffmpeg_encoder_start(const char* filename, AVCodecID codec_id, int fps, int width, int height) {
AVCodec* codec;
int ret;
avcodec_register_all();
codec = avcodec_find_encoder(codec_id);
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
c = avcodec_alloc_context3(codec);
if (!c) {
fprintf(stderr, "Could not allocate video codec context\n");
exit(1);
}
c->bit_rate = 4000000;
c->width = width;
c->height = height;
c->time_base.num = 1;
c->time_base.den = fps;
c->gop_size = 10;
c->max_b_frames = 1;
c->pix_fmt = AV_PIX_FMT_YUV420P;
if (codec_id == AV_CODEC_ID_H264)
av_opt_set(c->priv_data, "preset", "slow", 0);
if (avcodec_open2(c, codec, NULL) < 0) {
fprintf(stderr, "Could not open codec\n");
exit(1);
}
file = fopen(filename, "wb");
if (!file) {
fprintf(stderr, "Could not open %s\n", filename);
exit(1);
}
frame = av_frame_alloc();
if (!frame) {
fprintf(stderr, "Could not allocate video frame\n");
exit(1);
}
frame->format = c->pix_fmt;
frame->width = c->width;
frame->height = c->height;
ret = av_image_alloc(frame->data, frame->linesize, c->width, c->height, c->pix_fmt, 32);
if (ret < 0) {
fprintf(stderr, "Could not allocate raw picture buffer\n");
exit(1);
}
}
void ffmpeg_encoder_finish(void) {
uint8_t endcode[] = { 0, 0, 1, 0xb7 };
int got_output, ret;
do {
fflush(stdout);
ret = avcodec_encode_video2(c, &pkt, NULL, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
fwrite(pkt.data, 1, pkt.size, file);
av_packet_unref(&pkt);
}
} while (got_output);
fwrite(endcode, 1, sizeof(endcode), file);
fclose(file);
avcodec_close(c);
av_free(c);
av_freep(&frame->data[0]);
av_frame_free(&frame);
}
void ffmpeg_encoder_encode_frame(uint8_t* rgb) {
int ret, got_output;
ffmpeg_encoder_set_frame_yuv_from_rgb(rgb);
av_init_packet(&pkt);
pkt.data = NULL;
pkt.size = 0;
ret = avcodec_encode_video2(c, &pkt, frame, &got_output);
if (ret < 0) {
fprintf(stderr, "Error encoding frame\n");
exit(1);
}
if (got_output) {
fwrite(pkt.data, 1, pkt.size, file);
av_packet_unref(&pkt);
}
}
void ffmpeg_encoder_glread_rgb(uint8_t** rgb, GLubyte** pixels, unsigned int width, unsigned int height) {
size_t i, j, k, cur_gl, cur_rgb, nvals;
const size_t format_nchannels = 4;
nvals = format_nchannels * width * height;
*pixels = (GLubyte*)realloc(*pixels, nvals * sizeof(GLubyte));
*rgb = (GLubyte*)realloc(*rgb, nvals * sizeof(uint8_t));
/* Get RGBA to align to 32 bits instead of just 24 for RGB. May be faster for FFmpeg. */
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, *pixels);
for (i = 0; i < height; i++) {
for (j = 0; j < width; j++) {
cur_gl = format_nchannels * (width * (height - i - 1) + j);
cur_rgb = format_nchannels * (width * i + j);
for (k = 0; k < format_nchannels; k++)
(*rgb)[cur_rgb + k] = (*pixels)[cur_gl + k];
}
}
}
static void init(void) {
int glget;
if (offscreen) {
/* Framebuffer */
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
/* Color renderbuffer. */
glGenRenderbuffers(1, &rbo_color);
glBindRenderbuffer(GL_RENDERBUFFER, rbo_color);
/* Storage must be one of: */
/* GL_RGBA4, GL_RGB565, GL_RGB5_A1, GL_DEPTH_COMPONENT16, GL_STENCIL_INDEX8. */
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB565, WIDTH, HEIGHT);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, rbo_color);
/* Depth renderbuffer. */
glGenRenderbuffers(1, &rbo_depth);
glBindRenderbuffer(GL_RENDERBUFFER, rbo_depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, WIDTH, HEIGHT);
glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbo_depth);
glReadBuffer(GL_COLOR_ATTACHMENT0);
/* Sanity check. */
assert(glCheckFramebufferStatus(GL_FRAMEBUFFER));
glGetIntegerv(GL_MAX_RENDERBUFFER_SIZE, &glget);
assert(WIDTH * HEIGHT < (unsigned int)glget);
}
else {
glReadBuffer(GL_BACK);
}
glClearColor(0.0, 0.0, 0.0, 0.0);
glEnable(GL_DEPTH_TEST);
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glViewport(0, 0, WIDTH, HEIGHT);
time0 = glfwGetTime();
ffmpeg_encoder_start("result.mpg", AV_CODEC_ID_MPEG1VIDEO, 60, WIDTH, HEIGHT);
}
static void deinit(void) {
printf("FPS = %f\n", 1000.0 * nframes / (double)(glfwGetTime() - time0));
free(pixels);
ffmpeg_encoder_finish();
free(rgb);
if (offscreen) {
glDeleteFramebuffers(1, &fbo);
glDeleteRenderbuffers(1, &rbo_color);
glDeleteRenderbuffers(1, &rbo_depth);
}
}
void processInput(GLFWwindow *window);
// camera
Camera camera(glm::vec3(4.0f, 4.0f, 20.0f));
// timing
float deltaTime = 0.0f;
float lastFrame = 0.0f;
// lighting
glm::vec3 lightPos(5.0f, 3.0f, 6.0f);
// force use advanced GPU (nvidia)
//extern "C" {
// _declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
//}
void paraboloidConfigurator(Paraboloid & myParaboloid);
void cylinderConfigurator(Cylinder & myCylinder);
void curvedBladeConfigurator(CurvedBlade & myCurvedBlade);
int main(int, char**)
{
// GLFW init
GLFWwindow * window = setupGLFW("MyWindow", WIDTH, HEIGHT);
if (window == nullptr)
{
std::cout << "Failed to setup GLFW";
return 1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetScrollCallback(window, scroll_callback);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
std::ifstream generationParametersFile;
generationParametersFile.open("parameters.json");
nlohmann::json parametersJsonObject;
generationParametersFile >> parametersJsonObject;
auto cameraDriver = CameraDriver(&camera);
for (auto & routePoint : parametersJsonObject["route"]) {
cameraDriver.addRoutePoint({
{
static_cast<float>(atof(routePoint["posX"].get<std::string>().c_str())),
static_cast<float>(atof(routePoint["posY"].get<std::string>().c_str())),
static_cast<float>(atof(routePoint["posZ"].get<std::string>().c_str()))
},
{
static_cast<float>(atof(routePoint["directionX"].get<std::string>().c_str())),
static_cast<float>(atof(routePoint["directionY"].get<std::string>().c_str())),
static_cast<float>(atof(routePoint["directionZ"].get<std::string>().c_str()))
},
static_cast<float>(atof(routePoint["duration"].get<std::string>().c_str()))
});
}
// IMGUI init
if (!setupImgui(window))
{
std::cout << "Failed to setup ImGUI";
return 1;
}
init();
glEnable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
bool show_demo_window = false;
bool show_start_window = true;
ImVec4 clear_color = ImVec4(0.103f, 0.103f, 0.103f, 1.00f);
ImVec4 draw_color = ImVec4(0.00f, 0.00f, 0.00f, 1.00f);
Shader lampShader("shaders/lampShader.vert", "shaders/lampShader.frag");
Shader lightingShader("shaders/lightingShader.vert", "shaders/lightingShader.frag");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f
};
Paraboloid myParaboloid(0, 0, 10, 42, 42);
Cylinder myCylinder(1, 1, 42);
CurvedBlade myCurvedBlade(
glm::vec2(-6.5f, -11.2f),
glm::vec2(-1.0f, 1.0f),
glm::vec2(1.0f, 0.01f),
glm::vec2(-3.8f, 3.5f),
10.0f,
10
);
// first, configure the cube's VAO (and VBO)
unsigned int cubeVBO, cubeVAO;
glGenBuffers(1, &cubeVBO);
glGenVertexArrays(1, &cubeVAO);
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(cubeVAO);
// position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
// second, configure the light's VAO (VBO stays the same; the vertices are the same for the light object which is also a 3D cube)
unsigned int lightVAO;
glGenVertexArrays(1, &lightVAO);
glBindVertexArray(lightVAO);
// we only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need (it's already bound, but we do it again for educational purposes)
glBindBuffer(GL_ARRAY_BUFFER, cubeVBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// std::cout << "Maximum nr of vertex attributes supported: " << nrAttributes << std::endl;
Color myColor(glm::vec3(1.0f, 0.0f, 0.0f));
bool isColorAnimate = false;
bool isWireMode = false;
bool isAxisVisible = true;
bool isOrtho = false;
bool isMSAA = false;
int lampSpeed = 0;
float lampRadius = 2;
float lampHeight = 3.0f;
float lampX = 5.0;
float lampZ = 6.0;
double angle = 30;
float angleX = 0.0f;
float angleY = 0.0f;
float angleZ = 0.0f;
float translateX = 4.0f;
float translateY = 2.0f;
float translateZ = 4.0f;
float scaleX = 1.0f;
float scaleY = 1.0f;
float scaleZ = 1.0f;
int fanSpeed = 10;
int bladesNum = 16;
glm::vec3 materialAmbient = glm::vec3(0.1, 0.1, 0.1);
glm::vec3 materialDiffuse = glm::vec3(1.0, 1.0, 1.0);
glm::vec3 materialSpecular = glm::vec3(0.5, 0.5, 0.5);
float materialShininess = 64.0f;
// Main loop
while (!glfwWindowShouldClose(window))
{
// Poll and handle events (inputs, window resize, etc.)
// You can read the io.WantCaptureMouse, io.WantCaptureKeyboard flags to tell if dear imgui wants to use your inputs.
// - When io.WantCaptureMouse is true, do not dispatch mouse input data to your main application.
// - When io.WantCaptureKeyboard is true, do not dispatch keyboard input data to your main application.
// Generally you may always pass all inputs to dear imgui, and hide them from your application based on those two flags.
glfwPollEvents();
GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
std::cout << "ERROR WTF " << error << std::endl;
}
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
// 1. Show the big demo window (Most of the sample code is in ImGui::ShowDemoWindow()! You can browse its code to learn more about Dear ImGui!).
if (show_demo_window)
ImGui::ShowDemoWindow(&show_demo_window);
// 2. Show a simple window that we create ourselves. We use a Begin/End pair to created a named window.
glm::vec3 currColor = myColor.getColor();
if(show_start_window)
{
draw_color = ImVec4(currColor.x, currColor.y, currColor.z, 0.00f);
ImGui::Begin("OpenGL Lab Control"); // Create a window called "Hello, world!" and append into it.
ImGui::Text("This is some useful text."); // Display some text (you can use a format strings too)
// Edit bools storing our window open/close state
//ImGui::Checkbox("Another Window", &show_another_window);
ImGui::Checkbox("Wire mode", &isWireMode);
ImGui::Checkbox("Show axes", &isAxisVisible);
ImGui::Checkbox("Use orthographic", &isOrtho);
ImGui::Checkbox("Enable MSAA", &isMSAA);
if (ImGui::CollapsingHeader("Fan settings"))
{
ImGui::SliderInt("Fan speed", &fanSpeed, 0, 69);
ImGui::SliderInt("Blades number", &bladesNum, 0, 42);
if (ImGui::TreeNode("Rotate fan##2"))
{
ImGui::SliderFloat("X angle", &angleX, 0.0f, 360.0f);
ImGui::SliderFloat("Y angle", &angleY, 0.0f, 360.0f);
ImGui::SliderFloat("Z angle", &angleZ, 0.0f, 360.0f);
ImGui::TreePop();
}
if (ImGui::TreeNode("Scale fan##2"))
{
ImGui::SliderFloat("X scale", &scaleX, 0.01f, 10.0f);
ImGui::SliderFloat("Y scale", &scaleY, 0.01f, 10.0f);
ImGui::SliderFloat("Z scale", &scaleZ, 0.01f, 10.0f);
ImGui::TreePop();
}
if (ImGui::TreeNode("Translate fan##2"))
{
ImGui::SliderFloat("X translate", &translateX, -10.0f, 10.0f);
ImGui::SliderFloat("Y translate", &translateY, -10.0f, 10.0f);
ImGui::SliderFloat("Z translate", &translateZ, -10.0f, 10.0f);
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Lamp settings"))
{
ImGui::SliderInt("Lamp speed", &lampSpeed, 0, 100);
ImGui::SliderFloat("Lamp radius", &lampRadius, 0.1f, 9.99f);
ImGui::SliderFloat("Lamp X pos", &lampX, -10.0f, 10.0f);
ImGui::SliderFloat("Lamp Y pos", &lampHeight, -10.0f, 10.0f);
ImGui::SliderFloat("Lamp Z pos", &lampZ, -10.0f, 10.0f);
lightPos.x = lampX;
lightPos.y = lampHeight;
lightPos.z = lampZ;
}
if (ImGui::CollapsingHeader("Primitives settings"))
{
if (ImGui::TreeNode("Paraboloid config##2"))
{
paraboloidConfigurator(myParaboloid);
ImGui::TreePop();
}
if (ImGui::TreeNode("Cylinder config##2"))
{
cylinderConfigurator(myCylinder);
ImGui::TreePop();
}
if (ImGui::TreeNode("Curved blade config##2"))
{
curvedBladeConfigurator(myCurvedBlade);
ImGui::TreePop();
}
}
if (ImGui::CollapsingHeader("Colors & Shaders"))
{
ImGui::Checkbox("Do color animate", &isColorAnimate);
myColor.doColorShift(isColorAnimate);
ImGui::ColorEdit3("Background color", (float*)&clear_color);
ImGui::ColorEdit3("Draw color", (float*)&draw_color); // Edit 3 floats representing a color
if (ImGui::TreeNode("Material##2"))
{
ImGui::ColorEdit3("Ambient", (float*)&materialAmbient);
ImGui::ColorEdit3("Diffuse", (float*)&materialDiffuse);
ImGui::ColorEdit3("Specular", (float*)&materialSpecular);
ImGui::SliderFloat("Shininess", &materialShininess, 0, 1024, "%.0f");
ImGui::TreePop();
}
}
ImGui::Text("Application average %.3f ms/frame (%.1f FPS)", 1000.0f / ImGui::GetIO().Framerate, ImGui::GetIO().Framerate);
ImGui::Text("Camera position: X: %.3f | Y: %.3f | Z: %.3f", camera.Position.x, camera.Position.y, camera.Position.z);
ImGui::Text("Camera direction: X: %.3f | Y: %.3f | Z: %.3f", camera.Front.x, camera.Front.y, camera.Front.z);
ImGui::End();
}
if ((draw_color.x != currColor.x) || (draw_color.y != currColor.y) || (draw_color.z != currColor.z))
{
currColor.x = draw_color.x;
currColor.y = draw_color.y;
currColor.z = draw_color.z;
myColor.setColor(currColor);
}
if (isMSAA)
{
glEnable(GL_MULTISAMPLE);
}
else
{
glDisable(GL_MULTISAMPLE);
}
// Rendering
ImGui::Render();
// per-frame time logic
// --------------------
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
cameraDriver.update(deltaTime);
lastFrame = currentFrame;
// input
// -----
processInput(window);
// render
// ------
glClearColor(clear_color.x, clear_color.y, clear_color.z, clear_color.w);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// be sure to activate shader when setting uniforms/drawing objects
lightingShader.use();
lightingShader.setVec3("objectColor", currColor);
lightingShader.setVec3("lightColor", 1.0f, 1.0f, 1.0f);
lightingShader.setVec3("lightWorldPos", lightPos);
lightingShader.setVec3("material.ambient", materialAmbient);
lightingShader.setVec3("material.diffuse", materialDiffuse);
lightingShader.setVec3("material.specular", materialSpecular);
lightingShader.setFloat("material.shininess", materialShininess);
//lightingShader.setVec3("viewPos", camera.Position);
// view/projection transformations
glm::mat4 projection;
if (isOrtho)
{
projection = glm::ortho(-(float)getFramebufferWidth()/100, (float)getFramebufferWidth()/100, -(float)getFramebufferHeight()/100, (float)getFramebufferHeight()/100, 0.01f, 100.0f);
}
else
{
projection = glm::perspective(glm::radians(camera.Zoom), (float)getFramebufferWidth() / (float)getFramebufferHeight(), 0.1f, 100.0f);
}
glm::mat4 view = camera.GetViewMatrix();
lightingShader.setMat4("projection", projection);
lightingShader.setMat4("view", view);
// world transformation
glm::mat4 model = glm::mat4(1.0f);
lightingShader.setMat4("model", model);
if(isWireMode)
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
else
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
// render the cube
// start drawing fan
// first calculate fan object transform matrix
glm::mat4 fanBaseModel = glm::mat4(1.0f);
fanBaseModel = glm::translate(fanBaseModel, glm::vec3(translateX, translateY, translateZ));
fanBaseModel = glm::rotate(fanBaseModel, glm::radians(angleX), glm::vec3(1, 0, 0));
fanBaseModel = glm::rotate(fanBaseModel, glm::radians(angleY), glm::vec3(0, 1, 0));
fanBaseModel = glm::rotate(fanBaseModel, glm::radians(angleZ), glm::vec3(0, 0, 1));
fanBaseModel = glm::scale(fanBaseModel, glm::vec3(scaleX, scaleY, scaleZ));
// then start transform and draw primitive figures
model = fanBaseModel;
model = glm::rotate(model, glm::radians(90.0f), glm::vec3(1, 0, 0));
model = glm::scale(model, glm::vec3(0.2, 0.2, 3));
lightingShader.setMat4("model", model);
myCylinder.draw();
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, 3, 0));
model = glm::rotate(model, glm::radians(90.0f), glm::vec3(1, 0, 0));
model = glm::scale(model, glm::vec3(0.15, 0.15, 3));
lightingShader.setMat4("model", model);
myCylinder.draw();
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, -1.75, 0));
model = glm::rotate(model, glm::radians(90.0f), glm::vec3(1, 0, 0));
model = glm::scale(model, glm::vec3(0.3, 0.3, 0.5));
lightingShader.setMat4("model", model);
myCylinder.draw();
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, 4.5, 1.85));
model = glm::scale(model, glm::vec3(0.65, 0.65, 0.65));
lightingShader.setMat4("model", model);
myCylinder.draw();
float time = glfwGetTime();
for (size_t i = 0; i < bladesNum; i++)
{
float angle = 360.0f / bladesNum * i + time * 10 * fanSpeed;
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, 4.5, 1.85));
model = glm::rotate(model, glm::radians(90.0f), glm::vec3(1, 0, 0));
model = glm::rotate(model, glm::radians(angle), glm::vec3(0, 1, 0));
model = glm::translate(model, glm::vec3(1.25, 0, 0));
model = glm::scale(model, glm::vec3(0.6, 0.325, 0.2));
lightingShader.setMat4("model", model);
myCurvedBlade.draw();
}
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, 4.5, -0.475));
model = glm::scale(model, glm::vec3(0.18, 0.18, 0.2));
lightingShader.setMat4("model", model);
myParaboloid.draw();
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, -1.915, 0));
model = glm::scale(model, glm::vec3(0.18, 0.18, 4));
lightingShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
model = fanBaseModel;
model = glm::translate(model, glm::vec3(0, -1.915, 0));
model = glm::scale(model, glm::vec3(4, 0.18, 0.18));
lightingShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
// fan drawing end
// also draw the lamp object
angle += lampSpeed/10.0f;
if (angle >= 360)
angle = 0;
if (lampSpeed)
{
lightPos.x = glm::cos(glm::radians(angle)) * lampRadius;
lightPos.z = glm::sin(glm::radians(angle)) * lampRadius;
}
lampShader.use();
lampShader.setMat4("projection", projection);
lampShader.setMat4("view", view);
lampShader.setVec3("objectColor", glm::vec3(1.0, 1.0, 1.0));
model = glm::mat4(1.0f);
model = glm::translate(model, lightPos);
model = glm::scale(model, glm::vec3(0.2f)); // a smaller cube
lampShader.setMat4("model", model);
glBindVertexArray(lightVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
if (isAxisVisible)
{
// draw axis
// X axis
model = glm::mat4(1.0f);
model = glm::scale(model, glm::vec3(1000, 0.10, 0.10));
lampShader.setVec3("objectColor", glm::vec3(1.0, 0.0, 0.0));
lampShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
// Y axis
model = glm::mat4(1.0f);
model = glm::scale(model, glm::vec3(0.10, 1000, 0.10));
lampShader.setVec3("objectColor", glm::vec3(0.0, 1.0, 0.0));
lampShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
// Z axis
model = glm::mat4(1.0f);
model = glm::scale(model, glm::vec3(0.10, 0.10, 1000));
lampShader.setVec3("objectColor", glm::vec3(0.0, 0.0, 1.0));
lampShader.setMat4("model", model);
glBindVertexArray(cubeVAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
glfwSwapBuffers(window);
frame->pts = nframes;
ffmpeg_encoder_glread_rgb(&rgb, &pixels, WIDTH, HEIGHT);
ffmpeg_encoder_encode_frame(rgb);
nframes++;
if (cameraDriver.getCurrentRoute().empty()) {
break;
}
}
deinit();
// Cleanup
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
glfwDestroyWindow(window);
glfwTerminate();
return 0;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_F1) == GLFW_PRESS)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
glfwSetCursorPosCallback(window, nullptr);
}
if (glfwGetKey(window, GLFW_KEY_F2) == GLFW_PRESS)
{
setFirstMouse();
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetCursorPosCallback(window, mouse_callback);
}
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
}
void paraboloidConfigurator(Paraboloid & myParaboloid)
{
static int newParabLevel = 42;
static int currParabLevel = 43;
static int newParabEdges = 42;
static int currParabEdges = 43;
static float newParabHeight = 10.0f;
static float currParabHeight = 4.1f;
ImGui::SliderInt("Levels number", &newParabLevel, 2, 360);
if (currParabLevel != newParabLevel)
{
currParabLevel = newParabLevel;
myParaboloid.recalculate(0, 0, currParabHeight, currParabEdges, currParabLevel);
}
ImGui::SliderInt("P_Edges number", &newParabEdges, 3, 360);
if (currParabEdges != newParabEdges)
{
currParabEdges = newParabEdges;
myParaboloid.recalculate(0, 0, currParabHeight, currParabEdges, currParabLevel);
}
ImGui::SliderFloat("Height", &newParabHeight, 0.1, 100);
if (currParabHeight != newParabHeight)
{
currParabHeight = newParabHeight;
myParaboloid.recalculate(0, 0, currParabHeight, currParabEdges, currParabLevel);
}
}
void cylinderConfigurator(Cylinder & myCylinder)
{
static float newRadius = 1;
static float currRadius = 2;
static float newHeight = 1;
static float currHeight = 2;
static int newEdgesNum = 10;
static int currEdgesNum = 11;
ImGui::SliderInt("C_Edges number", &newEdgesNum, 3, 360);
if (currEdgesNum != newEdgesNum)
{
currEdgesNum = newEdgesNum;
myCylinder.recalculate(currRadius, currHeight, currEdgesNum);
}
ImGui::SliderFloat("C_Radius", &newRadius, 0.01, 10);
if (currRadius != newRadius)
{
currRadius = newRadius;
myCylinder.recalculate(currRadius, currHeight, currEdgesNum);
}
ImGui::SliderFloat("C_Height", &newHeight, 0.01, 10);
if (currHeight != newHeight)
{
currHeight = newHeight;
myCylinder.recalculate(currRadius, currHeight, currEdgesNum);
}
}
void curvedBladeConfigurator(CurvedBlade & myCurvedBlade)
{
static float p1_newHeight = 1.0f;
static float p1_currHeight = 2.0f;
static float p2_newHeight = 2.0f;
static float p2_currHeight = 1.0f;
static float f_newControlPointX = -5.0f;
static float f_currControlPointX = 2.0f;
static float f_newControlPointY = 2.0f;
static float f_currControlPointY = 1.0f;
static float s_newControlPointX = 5.0f;
static float s_currControlPointX = 2;
static float s_newControlPointY = 1.0f;
static float s_currControlPointY = 2;
static float newSpinPerLevel = 0.5f;
static float currSpinPerLevel = 2;
static int newLevelsNum = 100;
static int currLevelsNum = 11;
ImGui::SliderFloat("Start height", &p1_newHeight, 0.001, 10);
ImGui::SliderFloat("End height", &p2_newHeight, 0.001, 10);
ImGui::SliderFloat("First control point X", &f_newControlPointX, -30, 30);
ImGui::SliderFloat("First control point Y", &f_newControlPointY, -30, 30);
ImGui::SliderFloat("Second control point X", &s_newControlPointX, -30, 30);
ImGui::SliderFloat("Second control point Y", &s_newControlPointY, -30, 30);
ImGui::SliderFloat("Spin per level", &newSpinPerLevel, 0, 10);
ImGui::SliderInt("Levels number", &newLevelsNum, 0.001, 100);
if (p1_currHeight != p1_newHeight)
{
p1_currHeight = p1_newHeight;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (p2_currHeight != p2_newHeight)
{
p2_currHeight = p2_newHeight;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (f_currControlPointX != f_newControlPointX)
{
f_currControlPointX = f_newControlPointX;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (f_currControlPointY != f_newControlPointY)
{
f_currControlPointY = f_newControlPointY;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (s_currControlPointX != s_newControlPointX)
{
s_currControlPointX = s_newControlPointX;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (s_currControlPointY != s_newControlPointY)
{
s_currControlPointY = s_newControlPointY;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (currSpinPerLevel != newSpinPerLevel)
{
currSpinPerLevel = newSpinPerLevel;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
if (currLevelsNum != newLevelsNum)
{
currLevelsNum = newLevelsNum;
myCurvedBlade.recalculate(
glm::vec2(f_currControlPointX, f_currControlPointY),
glm::vec2(-1.0f, p1_currHeight),
glm::vec2(1.0f, p2_currHeight),
glm::vec2(s_currControlPointX, s_currControlPointY),
currSpinPerLevel,
currLevelsNum
);
}
}
| 29.711048 | 206 | 0.67261 | [
"render",
"object",
"model",
"transform",
"3d"
] |
f7757e38b01512537c7f6ce130c615f91cd622a4 | 405 | cpp | C++ | src/kazen/accel.cpp | ZhongLingXiao/tinykazen | 34c8e4a676ea1b4e59b6ee990e2ab4645fc860a9 | [
"MulanPSL-1.0"
] | 1 | 2021-08-16T12:48:37.000Z | 2021-08-16T12:48:37.000Z | src/kazen/accel.cpp | ZhongLingXiao/tinykazen | 34c8e4a676ea1b4e59b6ee990e2ab4645fc860a9 | [
"MulanPSL-1.0"
] | null | null | null | src/kazen/accel.cpp | ZhongLingXiao/tinykazen | 34c8e4a676ea1b4e59b6ee990e2ab4645fc860a9 | [
"MulanPSL-1.0"
] | null | null | null | #include <kazen/accel.h>
NAMESPACE_BEGIN(kazen)
void Accel::addMesh(Mesh *mesh) {
}
void Accel::build() {
/* Nothing to do here for now */
}
bool Accel::rayIntersect(const Ray3f &ray_, Intersection &its, bool shadowRay) const {
bool foundIntersection = false; // Was an intersection found so far?
/* Do intersection test here */
return foundIntersection;
}
NAMESPACE_END(kazen)
| 16.875 | 86 | 0.693827 | [
"mesh"
] |
f77608e1a058dfcf1bc2e395b22c4539180de0b2 | 3,040 | cc | C++ | test/test_execution_engine_cache.cc | apaszke/TensorComprehensions | 378d61061a7c5c14e4c4cc117ec9b1b4e4f91a6c | [
"Apache-2.0"
] | 1 | 2019-02-13T06:31:57.000Z | 2019-02-13T06:31:57.000Z | test/test_execution_engine_cache.cc | apaszke/TensorComprehensions | 378d61061a7c5c14e4c4cc117ec9b1b4e4f91a6c | [
"Apache-2.0"
] | null | null | null | test/test_execution_engine_cache.cc | apaszke/TensorComprehensions | 378d61061a7c5c14e4c4cc117ec9b1b4e4f91a6c | [
"Apache-2.0"
] | 1 | 2018-10-13T19:19:11.000Z | 2018-10-13T19:19:11.000Z | /**
* Copyright (c) 2017-present, Facebook, 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 <iostream>
#include <string>
#include <vector>
#include <gflags/gflags.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <ATen/ATen.h>
#include "tc/aten/aten_compiler.h"
#include "tc/core/cuda/cuda_tc_executor.h"
#include "tc/core/mapping_options.h"
#include "test_harness_aten_cuda.h"
TEST(ATenCompilationCacheTest, Matmul) {
tc::ATenCompilationUnit<tc::CudaTcExecutor> atCompl;
auto tc = R"(
def matmul(float(M,K) A, float(K,N) B) -> (output) {
output(m, n) +=! A(m, kk) * B(kk, n)
}
)";
atCompl.define(tc);
// test matmul
LOG(INFO) << "Testing 1st matmul";
at::Tensor a = at::CUDA(at::kFloat).rand({3, 4});
at::Tensor b = at::CUDA(at::kFloat).rand({4, 5});
std::vector<at::Tensor> inputs = {a, b};
std::vector<at::Tensor> outputs;
auto mappingOptions = tc::MappingOptions::makeMlpMappingOptions();
auto handle = atCompl.compile("matmul", inputs, mappingOptions);
atCompl.run("matmul", inputs, outputs, handle);
at::Tensor diff = outputs[0].sub(a.mm(b));
checkRtol(diff, inputs, 4);
// running matmul again to hit cache
LOG(INFO) << "Testing 1st matmul again";
std::vector<at::Tensor> outputs1;
handle = atCompl.compile("matmul", inputs, mappingOptions);
atCompl.run("matmul", inputs, outputs1, handle);
diff = outputs1[0].sub(a.mm(b));
checkRtol(diff, inputs, 4); // reduction size is dimension of n
// test matmul on different inputs
LOG(INFO) << "Testing 2nd matmul with different inputs";
at::Tensor a2 = at::CUDA(at::kFloat).rand({4, 8});
at::Tensor b2 = at::CUDA(at::kFloat).rand({8, 7});
inputs = {a2, b2};
std::vector<at::Tensor> outputs2;
handle = atCompl.compile("matmul", inputs, mappingOptions);
atCompl.run("matmul", inputs, outputs2, handle);
diff = outputs2[0].sub(a2.mm(b2));
checkRtol(diff, inputs, 8); // reduction size is dimension of n
// run the first cached matmul again
LOG(INFO) << "Testing 1st cached matmul again";
inputs = {a, b};
std::vector<at::Tensor> outputs3;
handle = atCompl.compile("matmul", inputs, mappingOptions);
atCompl.run("matmul", inputs, outputs3, handle);
diff = outputs3[0].sub(a.mm(b));
checkRtol(diff, inputs, 4); // reduction size is dimension of n
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
::gflags::ParseCommandLineFlags(&argc, &argv, true);
::google::InitGoogleLogging(argv[0]);
return RUN_ALL_TESTS();
}
| 34.157303 | 75 | 0.684868 | [
"vector"
] |
f7781990a7113bc5384bdca1de28cc85ce46cdec | 32,723 | cxx | C++ | ITS/AliITSsimulationSPDgeom.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 52 | 2016-12-11T13:04:01.000Z | 2022-03-11T11:49:35.000Z | ITS/AliITSsimulationSPDgeom.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 1,388 | 2016-11-01T10:27:36.000Z | 2022-03-30T15:26:09.000Z | ITS/AliITSsimulationSPDgeom.cxx | AllaMaevskaya/AliRoot | c53712645bf1c7d5f565b0d3228e3a6b9b09011a | [
"BSD-3-Clause"
] | 275 | 2016-06-21T20:24:05.000Z | 2022-03-31T13:06:19.000Z | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
/* $Id$ */
#include <TRandom.h>
#include <TH1.h>
#include <TString.h>
#include "AliRun.h"
#include "AliITS.h"
#include "AliITSdigitSPD.h"
#include "AliITSmodule.h"
#include "AliITSMapA2.h"
#include "AliITSpList.h"
#include "AliITSsimulationSPD.h"
#include "AliLog.h"
//#define DEBUG
ClassImp(AliITSsimulationSPD)
////////////////////////////////////////////////////////////////////////
// Version: 0
// Written by Rocco Caliandro
// from a model developed with T. Virgili and R.A. Fini
// June 15 2000
//
// AliITSsimulationSPD is the simulation of SPDs
//
//______________________________________________________________________
AliITSsimulationSPD::AliITSsimulationSPD() : AliITSsimulation(),
fMapA2(0),
fHis(0){
// Default constructor
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A default constructed AliITSsimulationSPD class.
}
//______________________________________________________________________
AliITSsimulationSPD::AliITSsimulationSPD(AliITSDetTypeSim *dettyp):
AliITSsimulation(dettyp),
fMapA2(0),
fHis(0){
// Standard constructor
// Inputs:
// AliITSsegmentation *seg Segmentation class to be used
// AliITSresonse *res Response class to be used
// Outputs:
// none.
// Return:
// A standard constructed AliITSsimulationSPD class.
Init();
}
//______________________________________________________________________
void AliITSsimulationSPD::Init() {
// Initilizes the variables of AliITSsimulation SPD.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
fHis = 0;
if(fMapA2) delete fMapA2;
AliITSsegmentationSPD* seg = (AliITSsegmentationSPD*)GetSegmentationModel(0);
fMapA2 = new AliITSMapA2(seg);
if(fpList) delete fpList;
fpList = new AliITSpList(GetNPixelsZ()+1,GetNPixelsX()+1);
}
/*
//______________________________________________________________________
void AliITSsimulationSPD::Init(AliITSsegmentationSPD *seg,
AliITSCalibrationSPD *resp) {
// Initilizes the variables of AliITSsimulation SPD.
// Inputs:
// AliITSsegmentationSPD replacement segmentation class to be used
// aliITSresponseSPD replacement response class to be used
// Outputs:
// none.
// Return:
// none.
if(fHis){
fHis->Delete();
delete fHis;
} // end if fHis
fHis = 0;
if(fResponse) delete fResponse;
fResponse = resp;
if(GetSegmentationModel(0)) delete GetSegmentationModel(0);
GetSegmentationModel(0) = seg;
if(fMapA2) delete fMapA2;
fMapA2 = new AliITSMapA2(GetSegmentationModel(0));
if(fpList) delete fpList;
fpList = new AliITSpList(GetNPixelsZ()+1,GetNPixelsX()+1);
}
*/
//______________________________________________________________________
AliITSsimulationSPD::~AliITSsimulationSPD() {
// destructor
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
if(fMapA2) delete fMapA2;
if (fHis) {
fHis->Delete();
delete fHis;
} // end if
}
//______________________________________________________________________
AliITSsimulationSPD::AliITSsimulationSPD(const AliITSsimulationSPD &source) :
AliITSsimulation(source){
// Copy Constructor
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A new AliITSsimulationSPD class with the same parameters as source.
if(&source == this) return;
this->fMapA2 = source.fMapA2;
this->fHis = source.fHis;
return;
}
//______________________________________________________________________
AliITSsimulationSPD& AliITSsimulationSPD::operator=(const AliITSsimulationSPD
&source) {
// Assignment operator
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A new AliITSsimulationSPD class with the same parameters as source.
if(&source == this) return *this;
this->fMapA2 = source.fMapA2;
this->fHis = source.fHis;
return *this;
}
//______________________________________________________________________
AliITSsimulation& AliITSsimulationSPD::operator=(const AliITSsimulation
&source) {
// Assignment operator
// Inputs:
// none.
// Outputs:
// none.
// Return:
// A new AliITSsimulationSPD class with the same parameters as source.
if(&source == this) return *this;
Error("AliITSsimulationSPD","Not allowed to make a = with "
"AliITSsimulationSPD Using default creater instead");
return *this;
}
//______________________________________________________________________
void AliITSsimulationSPD::InitSimulationModule(Int_t module,Int_t event){
// Creates maps to build the list of tracks for each sumable digit
// Inputs:
// Int_t module // Module number to be simulated
// Int_t event // Event number to be simulated
// Outputs:
// none.
// Return
// none.
fModule = module;
fEvent = event;
fMapA2->ClearMap();
fpList->ClearMap();
}
//______________________________________________________________________
void AliITSsimulationSPD::FinishSDigitiseModule(){
// Does the Sdigits to Digits work
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
SDigitsToDigits(fModule,fpList);
}
//______________________________________________________________________
void AliITSsimulationSPD::SDigitiseModule(AliITSmodule *mod, Int_t dummy0,
Int_t dummy1) {
// Sum digitize module
// Inputs:
// AliITSmodule *mod The module to be SDgitized
// Int_t dummy0 Not used kept for general compatibility
// Int_t dummy1 Not used kept for general compatibility
// Outputs:
// none.
// Return:
// none.
if (!(mod->GetNhits())) return; // if module has no hits then no Sdigits.
Int_t number = 10000;
Int_t *frowpixel = new Int_t[number];
Int_t *fcolpixel = new Int_t[number];
Double_t *fenepixel = new Double_t[number];
dummy0 = dummy1; // remove unsued variable warning.
fModule = mod->GetIndex();
// Array of pointers to store the track index of the digits
// leave +1, otherwise pList crashes when col=256, row=192
HitsToAnalogDigits(mod,frowpixel,fcolpixel,fenepixel,fpList);
WriteSDigits(fpList);
// clean memory
delete[] frowpixel;
delete[] fcolpixel;
delete[] fenepixel;
fMapA2->ClearMap();
fpList->ClearMap();
}
//______________________________________________________________________
void AliITSsimulationSPD::DigitiseModule(AliITSmodule *mod, Int_t,Int_t) {
// digitize module. Also need to digitize modules with only noise.
// Inputs:
// AliITSmodule *mod The module to be SDgitized
// Outputs:
// none.
// Return:
// none.
Int_t number = 10000;
Int_t *frowpixel = new Int_t[number];
Int_t *fcolpixel = new Int_t[number];
Double_t *fenepixel = new Double_t[number];
// Array of pointers to store the track index of the digits
// leave +1, otherwise pList crashes when col=256, row=192
fModule = mod->GetIndex();
// noise setting
SetFluctuations(fpList,fModule);
HitsToAnalogDigits(mod,frowpixel,fcolpixel,fenepixel,fpList);
// apply mask to SPD module
SetMask(fModule);
CreateDigit(fModule,fpList);
// clean memory
delete[] frowpixel;
delete[] fcolpixel;
delete[] fenepixel;
fMapA2->ClearMap();
fpList->ClearMap();
}
//______________________________________________________________________
void AliITSsimulationSPD::SDigitsToDigits(Int_t module,AliITSpList *pList) {
// sum digits to Digits.
// Inputs:
// AliITSmodule *mod The module to be SDgitized
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
AliDebug(1,Form("Entering AliITSsimulatinSPD::SDigitsToDigits for module=%d",
module));
fModule = module;
// noise setting
SetFluctuations(pList,module);
fMapA2->ClearMap(); // since noise is in pList aready. Zero Map so that
// noise is not doubled when calling FillMapFrompList.
FillMapFrompList(pList);
// apply mask to SPD module
SetMask(fModule);
CreateDigit(module,pList);
fMapA2->ClearMap();
pList->ClearMap();
}
//______________________________________________________________________
void AliITSsimulationSPD::UpdateMapSignal(Int_t row,Int_t col,Int_t trk,
Int_t hit,Int_t mod,Double_t ene,
AliITSpList *pList) {
// updates the Map of signal, adding the energy (ene) released by
// the current track
// Inputs:
// Int_t row pixel row number
// Int_t col pixel column number
// Int_t trk track number which contributed
// Int_t hit hit number which contributed
// Int_t mod module number
// Double_t ene the energy associated with this contribution
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
fMapA2->AddSignal(row,col,ene);
pList->AddSignal(row,col,trk,hit,mod,ene);
}
//______________________________________________________________________
void AliITSsimulationSPD::UpdateMapNoise(Int_t row,Int_t col,Int_t mod,
Double_t ene,AliITSpList *pList) {
// updates the Map of noise, adding the energy (ene) give my noise
// Inputs:
// Int_t row pixel row number
// Int_t col pixel column number
// Int_t mod module number
// Double_t ene the energy associated with this contribution
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
fMapA2->AddSignal(row,col,ene);
pList->AddNoise(row,col,mod,ene);
}
//______________________________________________________________________
void AliITSsimulationSPD::HitsToAnalogDigits(AliITSmodule *mod,
Int_t *frowpixel,Int_t *fcolpixel,
Double_t *fenepixel,
AliITSpList *pList) {
// Loops over all hits to produce Analog/floting point digits. This
// is also the first task in producing standard digits.
// Inputs:
// AliITSmodule *mod module class
// Int_t *frowpixel array of pixel rows
// Int_t *fcolpixel array of pixel columns
// Double_t *fenepiexel array of pixel energies
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
// loop over hits in the module
Int_t hitpos,nhits = mod->GetNhits();
for (hitpos=0;hitpos<nhits;hitpos++) {
HitToDigit(mod,hitpos,frowpixel,fcolpixel,fenepixel,pList);
}// end loop over digits
}
//______________________________________________________________________
void AliITSsimulationSPD::HitToDigit(AliITSmodule *mod,Int_t hitpos,
Int_t *frowpixel,Int_t *fcolpixel,
Double_t *fenepixel,AliITSpList *pList) {
// Steering function to determine the digits associated to a given
// hit (hitpos)
// The digits are created by charge sharing (ChargeSharing) and by
// capacitive coupling (SetCoupling). At all the created digits is
// associated the track number of the hit (ntrack)
// Inputs:
// AliITSmodule *mod module class
// Int_t hitpos hit index value
// Int_t *frowpixel array of pixel rows
// Int_t *fcolpixel array of pixel columns
// Double_t *fenepiexel array of pixel energies
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
Double_t x1l=0.0,y1l=0.0,z1l=0.0,x2l=0.0,y2l=0.0,z2l=0.0;
Int_t r1,r2,c1,c2,row,col,npixel = 0;
Int_t ntrack;
Double_t ene=0.0,etot=0.0;
const Float_t kconv = 10000.; // cm -> microns
const Float_t kconv1= 0.277e9; // GeV -> electrons equivalent
if(!(mod->LineSegmentL(hitpos,x1l,x2l,y1l,y2l,z1l,z2l,etot,ntrack)))return;
x2l += x1l; y2l += y1l; z2l += z1l; // Convert to ending coordinate.
// positions shifted and converted in microns
x1l = x1l*kconv + GetSegmentationModel(0)->Dx()/2.;
z1l = z1l*kconv + GetSegmentationModel(0)->Dz()/2.;
// positions shifted and converted in microns
x2l = x2l*kconv + GetSegmentationModel(0)->Dx()/2.;
z2l = z2l*kconv + GetSegmentationModel(0)->Dz()/2.;
etot *= kconv1; // convert from GeV to electrons equivalent.
Int_t module = mod->GetIndex();
// to account for the effective sensitive area
// introduced in geometry
if (z1l<0 || z1l>GetSegmentationModel(0)->Dz()) return;
if (z2l<0 || z2l>GetSegmentationModel(0)->Dz()) return;
if (x1l<0 || x1l>GetSegmentationModel(0)->Dx()) return;
if (x2l<0 || x2l>GetSegmentationModel(0)->Dx()) return;
//Get the col and row number starting from 1
// the x direction is not inverted for the second layer!!!
GetSegmentationModel(0)->GetPadIxz(x1l, z1l, c1, r1);
GetSegmentationModel(0)->GetPadIxz(x2l, z2l, c2, r2);
// to account for unexpected equal entrance and
// exit coordinates
if (x1l==x2l) x2l=x2l+x2l*0.1;
if (z1l==z2l) z2l=z2l+z2l*0.1;
if ((r1==r2) && (c1==c2)){
// no charge sharing
npixel = 1;
frowpixel[npixel-1] = r1;
fcolpixel[npixel-1] = c1;
fenepixel[npixel-1] = etot;
} else {
// charge sharing
ChargeSharing(x1l,z1l,x2l,z2l,c1,r1,c2,r2,etot,
npixel,frowpixel,fcolpixel,fenepixel);
} // end if r1==r2 && c1==c2.
for (Int_t npix=0;npix<npixel;npix++){
row = frowpixel[npix];
col = fcolpixel[npix];
ene = fenepixel[npix];
UpdateMapSignal(row,col,ntrack,hitpos,module,ene,pList);
// Starting capacitive coupling effect
SetCoupling(row,col,ntrack,hitpos,module,pList);
} // end for npix
}
//______________________________________________________________________
void AliITSsimulationSPD::ChargeSharing(Float_t x1l,Float_t z1l,Float_t x2l,
Float_t z2l,Int_t c1,Int_t r1,Int_t c2,
Int_t r2,Float_t etot,
Int_t &npixel,Int_t *frowpixel,
Int_t *fcolpixel,Double_t *fenepixel){
// Take into account the geometrical charge sharing when the track
// crosses more than one pixel.
// Inputs:
// Float_t x1l
// Float_t z1l
// Float_t x2l
// Float_t z2l
// Int_t c1
// Int_t r1
// Int_t c2
// Int_t r2
// Float_t etot
// Int_t &npixel
// Int_t *frowpixel array of pixel rows
// Int_t *fcolpixel array of pixel columns
// Double_t *fenepiexel array of pixel energies
// Outputs:
// Int_t &npixel
// Return:
// none.
//
//Begin_Html
/*
<img src="picts/ITS/barimodel_2.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<a href="mailto:Rocco.Caliandro@ba.infn.it"></a>.
</font>
<pre>
*/
//End_Html
//Float_t dm;
Float_t xa,za,xb,zb,dx,dz,dtot,refr,refm,refc;
Float_t refn=0.;
Float_t arefm, arefr, arefn, arefc, azb, az2l, axb, ax2l;
Int_t dirx,dirz,rb,cb;
Int_t flag,flagrow,flagcol;
Double_t epar;
npixel = 0;
xa = x1l;
za = z1l;
// dx = x1l-x2l;
// dz = z1l-z2l;
dx = x2l-x1l;
dz = z2l-z1l;
dtot = TMath::Sqrt((dx*dx)+(dz*dz));
if (dtot==0.0) dtot = 0.01;
dirx = (Int_t) TMath::Sign((Float_t)1,dx);
dirz = (Int_t) TMath::Sign((Float_t)1,dz);
// calculate the x coordinate of the pixel in the next column
// and the z coordinate of the pixel in the next row
Float_t xpos, zpos;
GetSegmentationModel(0)->GetPadCxz(c1, r1-1, xpos, zpos);
Float_t xsize = GetSegmentationModel(0)->Dpx(0);
Float_t zsize = GetSegmentationModel(0)->Dpz(r1-1);
if (dirx == 1) refr = xpos+xsize/2.;
else refr = xpos-xsize/2.;
if (dirz == 1) refn = zpos+zsize/2.;
else refn = zpos-zsize/2.;
flag = 0;
flagrow = 0;
flagcol = 0;
do{
// calculate the x coordinate of the intersection with the pixel
// in the next cell in row direction
if(dz!=0)
refm = dx*((refn - z1l)/dz) + x1l;
else
refm = refr+dirx*xsize;
// calculate the z coordinate of the intersection with the pixel
// in the next cell in column direction
if (dx!=0)
refc = dz*((refr - x1l)/dx) + z1l;
else
refc = refn+dirz*zsize;
arefm = refm * dirx;
arefr = refr * dirx;
arefn = refn * dirz;
arefc = refc * dirz;
if ((arefm < arefr) && (arefn < arefc)){
// the track goes in the pixel in the next cell in row direction
xb = refm;
zb = refn;
cb = c1;
rb = r1 + dirz;
azb = zb * dirz;
az2l = z2l * dirz;
if (rb == r2) flagrow=1;
if (azb > az2l) {
zb = z2l;
xb = x2l;
} // end if
// shift to the pixel in the next cell in row direction
Float_t zsizeNext = GetSegmentationModel(0)->Dpz(rb-1);
//to account for cell at the borders of the detector
if(zsizeNext==0) zsizeNext = zsize;
refn += zsizeNext*dirz;
}else {
// the track goes in the pixel in the next cell in column direction
xb = refr;
zb = refc;
cb = c1 + dirx;
rb = r1;
axb = xb * dirx;
ax2l = x2l * dirx;
if (cb == c2) flagcol=1;
if (axb > ax2l) {
zb = z2l;
xb = x2l;
} // end ifaxb > ax2l
// shift to the pixel in the next cell in column direction
Float_t xsizeNext = GetSegmentationModel(0)->Dpx(cb-1);
//to account for cell at the borders of the detector
if(xsizeNext==0) xsizeNext = xsize;
refr += xsizeNext*dirx;
} // end if (arefm < arefr) && (arefn < arefc)
//calculate the energy lost in the crossed pixel
epar = TMath::Sqrt((xb-xa)*(xb-xa)+(zb-za)*(zb-za));
epar = etot*(epar/dtot);
//store row, column and energy lost in the crossed pixel
frowpixel[npixel] = r1;
fcolpixel[npixel] = c1;
fenepixel[npixel] = epar;
npixel++;
// the exit point of the track is reached
if (epar == 0) flag = 1;
if ((r1 == r2) && (c1 == c2)) flag = 1;
if (flag!=1) {
r1 = rb;
c1 = cb;
xa = xb;
za = zb;
} // end if flag!=1
} while (flag==0);
}
//______________________________________________________________________
void AliITSsimulationSPD::SetCoupling(Int_t row, Int_t col, Int_t ntrack,
Int_t idhit,Int_t module,
AliITSpList *pList) {
// Take into account the coupling between adiacent pixels.
// The parameters probcol and probrow are the probability of the
// signal in one pixel shared in the two adjacent pixels along
// the column and row direction, respectively.
// Inputs:
// Int_t row pixel row number
// Int_t col pixel column number
// Int_t ntrack track number of track contributing to this signal
// Int_t idhit hit number of hit contributing to this signal
// Int_t module module number
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
//
//Begin_Html
/*
<img src="picts/ITS/barimodel_3.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<a href="mailto:tiziano.virgili@cern.ch"></a>.
</font>
<pre>
*/
//End_Html
Int_t j1,j2,flag=0;
Double_t pulse1,pulse2;
Double_t couplR=0.0,couplC=0.0;
Double_t xr=0.;
GetCouplings(couplR,couplC);
j1 = row;
j2 = col;
pulse1 = fMapA2->GetSignal(row,col);
pulse2 = pulse1;
for (Int_t isign=-1;isign<=1;isign+=2){// loop in row direction
do{
j1 += isign;
// pulse1 *= couplR;
xr = gRandom->Rndm();
//if ((j1<0) || (j1>GetNPixelsZ()-1) || (pulse1<GetThreshold())){
if ((j1<0) || (j1>GetNPixelsZ()-1) || (xr>couplR)){
j1 = row;
flag = 1;
}else{
UpdateMapSignal(j1,col,ntrack,idhit,module,pulse1,pList);
// flag = 0;
flag = 1; // only first next!!
} // end if
} while(flag == 0);
// loop in column direction
do{
j2 += isign;
// pulse2 *= couplC;
xr = gRandom->Rndm();
//if ((j2<0) || (j2>(GetNPixelsX()-1)) || (pulse2<GetThreshold())){
if ((j2<0) || (j2>GetNPixelsX()-1) || (xr>couplC)){
j2 = col;
flag = 1;
}else{
UpdateMapSignal(row,j2,ntrack,idhit,module,pulse2,pList);
// flag = 0;
flag = 1; // only first next!!
} // end if
} while(flag == 0);
} // for isign
}
//______________________________________________________________________
void AliITSsimulationSPD::SetCouplingOld(Int_t row, Int_t col, Int_t ntrack,
Int_t idhit,Int_t module,
AliITSpList *pList) {
// Take into account the coupling between adiacent pixels.
// The parameters probcol and probrow are the fractions of the
// signal in one pixel shared in the two adjacent pixels along
// the column and row direction, respectively.
// Inputs:
// Int_t row pixel row number
// Int_t col pixel column number
// Int_t ntrack track number of track contributing to this pixel
// Int_t idhit hit index number of hit contributing to this pixel
// Int_t module module number
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
//
//Begin_Html
/*
<img src="picts/ITS/barimodel_3.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<a href="mailto:Rocco.Caliandro@ba.infn.it"></a>.
</font>
<pre>
*/
//End_Html
Int_t j1,j2,flag=0;
Double_t pulse1,pulse2;
Double_t couplR=0.0,couplC=0.0;
GetCouplings(couplR,couplC);
j1 = row;
j2 = col;
pulse1 = fMapA2->GetSignal(row,col);
pulse2 = pulse1;
for (Int_t isign=-1;isign<=1;isign+=2){// loop in row direction
do{
j1 += isign;
pulse1 *= couplR;
if ((j1<0) || (j1>GetNPixelsZ()-1) || (pulse1<GetThreshold())){
pulse1 = fMapA2->GetSignal(row,col);
j1 = row;
flag = 1;
}else{
UpdateMapSignal(j1,col,ntrack,idhit,module,pulse1,pList);
flag = 0;
} // end if
} while(flag == 0);
// loop in column direction
do{
j2 += isign;
pulse2 *= couplC;
if ((j2<0) || (j2>(GetNPixelsX()-1)) || (pulse2<GetThreshold())){
pulse2 = fMapA2->GetSignal(row,col);
j2 = col;
flag = 1;
}else{
UpdateMapSignal(row,j2,ntrack,idhit,module,pulse2,pList);
flag = 0;
} // end if
} while(flag == 0);
} // for isign
}
//______________________________________________________________________
void AliITSsimulationSPD::CreateDigit(Int_t module,AliITSpList *pList) {
// The pixels are fired if the energy deposited inside them is above
// the threshold parameter ethr. Fired pixed are interpreted as digits
// and stored in the file digitfilename. One also needs to write out
// cases when there is only noise (nhits==0).
// Inputs:
// Int_t module
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
static AliITS *aliITS = (AliITS*)gAlice->GetModule("ITS");
Int_t size = AliITSdigitSPD::GetNTracks();
Int_t * digits = new Int_t[size];
Int_t * tracks = new Int_t[size];
Int_t * hits = new Int_t[size];
Float_t * charges = new Float_t[size];
Int_t j1;
module=0; // remove unused variable warning.
for(j1=0;j1<size;j1++){tracks[j1]=-3;hits[j1]=-1;charges[j1]=0.0;}
for (Int_t r=1;r<=GetNPixelsZ();r++) {
for (Int_t c=1;c<=GetNPixelsX();c++) {
// check if the deposited energy in a pixel is above the
// threshold
Float_t signal = (Float_t) fMapA2->GetSignal(r,c);
if ( signal > GetThreshold()) {
digits[0] = r-1; // digits starts from 0
digits[1] = c-1; // digits starts from 0
//digits[2] = 1;
digits[2] = (Int_t) signal; // the signal is stored in
// electrons
for(j1=0;j1<size;j1++){
if(j1<pList->GetNEntries()){
tracks[j1] = pList->GetTrack(r,c,j1);
hits[j1] = pList->GetHit(r,c,j1);
//}else{
//tracks[j1] = -3;
//hits[j1] = -1;
} // end if
//charges[j1] = 0;
} // end for j1
Float_t phys = 0;
aliITS->AddSimDigit(0,phys,digits,tracks,hits,charges);
AliDebug(1,Form("mod=%d r,c=%d,%d sig=%f noise=%f Msig=%d Thres=%f",
fModule,r,c,fpList->GetSignalOnly(r,c),fpList->GetNoise(r,c),
signal,GetThreshold()));
} // end if of threshold condition
} // for c
}// end do on pixels
delete [] digits;
delete [] tracks;
delete [] hits;
delete [] charges;
}
//______________________________________________________________________
void AliITSsimulationSPD::SetFluctuations(AliITSpList *pList,Int_t module) {
// Set the electronic noise and threshold non-uniformities to all the
// pixels in a detector.
// The parameter fSigma is the squared sum of the sigma due to noise
// and the sigma of the threshold distribution among pixels.
// Inputs:
// Int_t module modulel number
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
//
//Begin_Html
/*
<img src="picts/ITS/barimodel_1.gif">
</pre>
<br clear=left>
<font size=+2 color=red>
<a href="mailto:Rocco.Caliandro@ba.infn.it"></a>.
</font>
<pre>
*/
//End_Html
Double_t thr=0.0,sigm=0.0;
Double_t signal,sigma;
Int_t iz,ix;
GetThresholds(thr,sigm);
sigma = (Double_t) sigm;
for(iz=1;iz<=GetNPixelsZ();iz++){
for(ix=1;ix<=GetNPixelsX();ix++){
signal = sigma*gRandom->Gaus();
fMapA2->SetHit(iz,ix,signal);
// insert in the label-signal-hit list the pixels fired
// only by noise
pList->AddNoise(iz,ix,module,signal);
} // end of loop on pixels
} // end of loop on pixels
}
//______________________________________________________________________
void AliITSsimulationSPD::SetMask(Int_t mod) {
// Apply a mask to the SPD module. 1% of the pixel channels are
// masked. When the database will be ready, the masked pixels
// should be read from it.
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
Double_t signal;
Int_t iz,ix,im;
Float_t totMask;
Float_t perc = ((AliITSCalibrationSPD*)GetCalibrationModel(mod))->GetFractionDead();
// in this way we get the same set of random numbers for all runs.
// This is a cluge for now.
static TRandom *rnd = new TRandom();
totMask= perc*GetNPixelsZ()*GetNPixelsX();
for(im=1;im<totMask;im++){
do{
ix=(Int_t)(rnd->Rndm()*(GetNPixelsX()-1.) + 1.);
} while(ix<=0 || ix>GetNPixelsX());
do{
iz=(Int_t)(rnd->Rndm()*(GetNPixelsZ()-1.) + 1.);
} while(iz<=0 || iz>GetNPixelsZ());
signal = -1.;
fMapA2->SetHit(iz,ix,signal);
} // end loop on masked pixels
}
//______________________________________________________________________
void AliITSsimulationSPD::CreateHistograms() {
// Create Histograms
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
Int_t i;
fHis=new TObjArray(GetNPixelsZ());
for(i=0;i<GetNPixelsZ();i++) {
TString spdname("spd_");
Char_t candnum[4];
sprintf(candnum,"%d",i+1);
spdname.Append(candnum);
(*fHis)[i] = new TH1F(spdname.Data(),"SPD maps",
GetNPixelsX(),0.,(Float_t) GetNPixelsX());
} // end for i
}
//______________________________________________________________________
void AliITSsimulationSPD::ResetHistograms() {
// Reset histograms for this detector
// Inputs:
// none.
// Outputs:
// none.
// Return:
// none.
Int_t i;
for(i=0;i<GetNPixelsZ();i++ ) {
if ((*fHis)[i]) ((TH1F*)(*fHis)[i])->Reset();
} // end for i
}
//______________________________________________________________________
void AliITSsimulationSPD::WriteSDigits(AliITSpList *pList){
// Fills the Summable digits Tree
// Inputs:
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
Int_t i,ni,j,nj;
static AliITS *aliITS = (AliITS*)gAlice->GetModule("ITS");
pList->GetMaxMapIndex(ni,nj);
for(i=0;i<ni;i++)for(j=0;j<nj;j++){
if(pList->GetSignalOnly(i,j)>0.0){
aliITS->AddSumDigit(*(pList->GetpListItem(i,j)));
if(AliDebugLevel()>0){
cout << "pListSPD: " << *(pList->GetpListItem(i,j)) << endl;
AliDebug(1,Form("mod=%d r,c=%d %d sig=%f noise=%f",
fModule,i,j,fpList->GetSignalOnly(i,j),fpList->GetNoise(i,j)))
} // end if GetDebug
} // end if
} // end for i,j
return;
}
//______________________________________________________________________
void AliITSsimulationSPD::FillMapFrompList(AliITSpList *pList){
// Fills fMap2A from the pList of Summable digits
// Inputs:
// AliITSpList *pList the array of SDigits
// Outputs:
// AliITSpList *pList the array of SDigits
// Return:
// none.
Int_t ix,iz;
for(iz=0;iz<GetNPixelsZ();iz++)for(ix=0;ix<GetNPixelsX();ix++)
fMapA2->AddSignal(iz,ix,pList->GetSignal(iz,ix));
return;
}
| 34.086458 | 88 | 0.58928 | [
"geometry",
"model"
] |
f77aa4165f2991a53e24064a0e34651227936a12 | 721 | hpp | C++ | src/ttauri/widgets/row_column_delegate.hpp | RustWorks/ttauri | 4b093eb16465091d01d80159e23fd26e5d4e4c03 | [
"BSL-1.0"
] | 279 | 2021-02-17T09:53:40.000Z | 2022-03-22T04:08:40.000Z | src/ttauri/widgets/row_column_delegate.hpp | RustWorks/ttauri | 4b093eb16465091d01d80159e23fd26e5d4e4c03 | [
"BSL-1.0"
] | 269 | 2021-02-17T12:53:15.000Z | 2022-03-29T22:10:49.000Z | src/ttauri/widgets/row_column_delegate.hpp | sthagen/ttauri | 772f4e55c007e0bc199a07d86ef4e2d4d46af139 | [
"BSL-1.0"
] | 25 | 2021-02-17T17:14:10.000Z | 2022-03-16T04:13:00.000Z | // Copyright Take Vos 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "../geometry/axis.hpp"
#include <memory>
#include <functional>
namespace tt::inline v1 {
template<axis>
class row_column_widget;
template<axis Axis>
class row_column_delegate {
public:
virtual ~row_column_delegate() = default;
virtual void init(row_column_widget<Axis> &sender) noexcept {}
virtual void deinit(row_column_widget<Axis> &sender) noexcept {}
};
using row_delegate = row_column_delegate<axis::row>;
using column_delegate = row_column_delegate<axis::column>;
} // namespace tt::inline v1
| 26.703704 | 91 | 0.757282 | [
"geometry"
] |
f7861cfc5b14b11558f0a3d96f4056c8e66e5b74 | 966 | cpp | C++ | Codechef/JAN19B/fancy.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | Codechef/JAN19B/fancy.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | Codechef/JAN19B/fancy.cpp | Binary-bug/CP | f9f356d36bd252c71ee3ed2d0585cc372f2baf5e | [
"MIT"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool space(char c){
return ::isspace(c);
}
bool not_space(char c){
return ! ::isspace(c);
}
vector<string> split(string& str){
typedef string::iterator iter;
vector<string> ret;
iter i = str.begin();
while(i!=str.end()){
//ignore leading blanks
i = find_if(i,str.end(),not_space);
//find end of next word
iter j = find_if(i,str.end(), ::isspace);
// copy the characters in [i,j)
if(i!=str.end())
ret.push_back(string(i,j));
i = j;
}
return ret;
}
int main(){
string s;
bool found;
int T,pos;
cin >> T;
cin.ignore();
vector<string> v;
while(T--){
found = false;
getline(cin,s);
v = split(s);
for(vector<string>::size_type i=0; i!=v.size(); i++) if(v[i] == "not"){ cout << "Real Fancy" << endl; found = true; break;}
if(!found) std::cout << "regularly fancy" << std::endl;
}
return 0;
}
| 18.226415 | 131 | 0.595238 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.