hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
bfc94e8a369ac0b387b55fb5dfc0562e1d119cba | 442 | cpp | C++ | CommandExecutorDecorator.cpp | Gruppio/House | 46183d24531d2dd14acc7e9092fe29a39595d8b4 | [
"MIT"
] | 1 | 2019-11-17T08:57:28.000Z | 2019-11-17T08:57:28.000Z | CommandExecutorDecorator.cpp | Gruppio/House | 46183d24531d2dd14acc7e9092fe29a39595d8b4 | [
"MIT"
] | null | null | null | CommandExecutorDecorator.cpp | Gruppio/House | 46183d24531d2dd14acc7e9092fe29a39595d8b4 | [
"MIT"
] | null | null | null | //
// CommandExecutorDecorator.cpp
// Ambrogio
//
// Created by Gruppioni Michele on 20/11/2016.
// Copyright © 2016 Michele Gruppioni. All rights reserved.
//
#include "CommandExecutorDecorator.h"
CommandExecutorDecorator::CommandExecutorDecorator(CommandExecutor *commandExecutor)
:commandExecutor(commandExecutor) {
}
void CommandExecutorDecorator::executeCommand(Command *command) {
commandExecutor->executeCommand(command);
}
| 24.555556 | 84 | 0.78733 | Gruppio |
bfd4348b4676821fb281169c958199fcde8a14b8 | 571 | hxx | C++ | src/demo/bode/bode.hxx | rochus-keller/nappgui_src | 394875dfc11c9c73cd7995d56f77dcd4629d70b5 | [
"MIT"
] | 133 | 2021-09-09T17:53:54.000Z | 2022-03-24T17:17:35.000Z | src/demo/bode/bode.hxx | rochus-keller/nappgui_src | 394875dfc11c9c73cd7995d56f77dcd4629d70b5 | [
"MIT"
] | 9 | 2021-09-09T21:20:49.000Z | 2022-03-22T00:07:56.000Z | src/demo/bode/bode.hxx | rochus-keller/nappgui_src | 394875dfc11c9c73cd7995d56f77dcd4629d70b5 | [
"MIT"
] | 10 | 2021-11-25T00:15:32.000Z | 2022-01-18T13:46:32.000Z | /*
* NAppGUI Cross-platform C SDK
* 2015-2022 Francisco Garcia Collado
* MIT Licence
* https://nappgui.com/en/legal/license.html
*
* File: bode.hxx
*
*/
/* Bode Types */
#ifndef __TYPES_HXX__
#define __TYPES_HXX__
#include "gui.hxx"
typedef struct _params_t Params;
typedef struct _model_t Model;
typedef struct _plot_t Plot;
typedef struct _ctrl_t Ctrl;
struct _params_t
{
real32_t P[5];
real32_t Q[9];
real32_t K[3];
real32_t T;
real32_t R;
real32_t KRg[6];
};
struct _model_t
{
V2Df wpos;
S2Df wsize;
Params cparams;
Params sparams;
};
#endif
| 13.595238 | 44 | 0.712785 | rochus-keller |
bfd49e2e4c39de94a8724db19fa453afeda9c926 | 2,262 | cpp | C++ | third-party/Empirical/examples/config/namespaces.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/examples/config/namespaces.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/examples/config/namespaces.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | #include <iostream>
#include "emp/config/config.hpp"
EMP_BUILD_CONFIG( MyConfig,
GROUP(DEFAULT_GROUP, "General Settings"),
VALUE(DEBUG_MODE, bool, false, "Should we output debug information?"),
VALUE(RANDOM_SEED, int, 0, "Random number seed (0 for based on time)"),
GROUP(TEST_GROUP, "These are settings with the sole purpose of testing cConfig.\nFor example, are multi-line descriptions okay?"),
VALUE(TEST_BOOL, bool, false, "This is a bool value.\nWhat happens\n ...if we have multiple\n lines?"),
VALUE(TEST_STRING, std::string, "default", "This is a string!"),
CONST(TEST_CONST, int, 91, "This is an unchanging const!"),
VALUE(TEST_STRING_SPACE, std::string, "abc def ghi", "This is a string with spaces."),
VALUE(TEST_DUP, int, 20, "This is a test of the same name in multiple namespaces.")
)
EMP_BUILD_CONFIG( MyConfig_internal,
GROUP(DEFAULT_GROUP, "BASIC SETTINGS"),
VALUE(TEST_INT1, int, 1, "This is my first integer test."),
VALUE(TEST_INT2, int, 2, "This is my second integer test."),
VALUE(TEST_DUP, int, 3333, "This is a test of the same name in multiple namespaces.")
)
int main()
{
MyConfig config;
MyConfig_internal config2;
config.AddNameSpace(config2, "internal");
config.Read("namespaces.cfg");
//config.Write("namespaces.cfg");
//config.WriteMacros("test-macro.h");
std::cout << "We are in namespaces!" << std::endl;
std::cout << "Config values:";
std::cout << " config.DEBUG_MODE() = " << config.DEBUG_MODE() << std::endl;
std::cout << " config.RANDOM_SEED() = " << config.RANDOM_SEED() << std::endl;
std::cout << " config.TEST_BOOL() = " << config.TEST_BOOL() << std::endl;
std::cout << " config.TEST_STRING() = " << config.TEST_STRING() << std::endl;
std::cout << " config.TEST_CONST() = " << config.TEST_CONST() << std::endl;
std::cout << " config.TEST_STRING_SPACE() = " << config.TEST_STRING_SPACE() << std::endl;
std::cout << " config.TEST_DUP() = " << config.TEST_DUP() << std::endl;
std::cout << "\nConfig2 values:";
std::cout << " config2.TEST_INT1() = " << config2.TEST_INT1() << std::endl;
std::cout << " config2.TEST_INT2() = " << config2.TEST_INT2() << std::endl;
std::cout << " config2.TEST_DUP() = " << config2.TEST_DUP() << std::endl;
}
| 46.163265 | 132 | 0.662688 | koellingh |
bfd5156f8d2ef8243bcedc72435a19f18f3c28c7 | 4,745 | cpp | C++ | TestC_21_Crab Pong/main.cpp | liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu | 9309df734ade3e26e95aabfd33eaeabe5e7d701d | [
"MIT"
] | null | null | null | TestC_21_Crab Pong/main.cpp | liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu | 9309df734ade3e26e95aabfd33eaeabe5e7d701d | [
"MIT"
] | null | null | null | TestC_21_Crab Pong/main.cpp | liuyuwang2016/OpenGL-Tutorial-by-Yvan-Liu | 9309df734ade3e26e95aabfd33eaeabe5e7d701d | [
"MIT"
] | null | null | null | /* 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 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.
*/
/* File for "A Sample Game: Crab Pong" lesson of the OpenGL tutorial on
* www.videotutorialsrock.com
*/
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <math.h>
#include <stdlib.h>
#ifdef __APPLE__
#include <OpenGL/OpenGL.h>
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
#include "gamedrawer.h"
using namespace std;
const float PI = 3.1415926535f;
//The number of milliseconds between calls to update
const int TIMER_MS = 25;
GameDrawer* gameDrawer;
//Whether the left key is currently depressed
bool isLeftKeyPressed = false;
//Whether the right key is currently depressed
bool isRightKeyPressed = false;
//Starts at 0, then increases until it reaches 2 * PI, then jumps back to 0 and
//repeats. Used to have the camera angle slowly change.
float rotationVar = 0;
void cleanup() {
delete gameDrawer;
cleanupGameDrawer();
}
void handleKeypress(unsigned char key, int x, int y) {
switch (key) {
case '\r': //Enter key
if (gameDrawer->isGameOver()) {
gameDrawer->startNewGame(2.2f, 20);
}
break;
case 27: //Escape key
cleanup();
exit(0);
}
}
void handleSpecialKeypress(int key, int x, int y) {
switch (key) {
case GLUT_KEY_LEFT:
isLeftKeyPressed = true;
if (isRightKeyPressed) {
gameDrawer->setPlayerCrabDir(0);
}
else {
gameDrawer->setPlayerCrabDir(1);
}
break;
case GLUT_KEY_RIGHT:
isRightKeyPressed = true;
if (isLeftKeyPressed) {
gameDrawer->setPlayerCrabDir(0);
}
else {
gameDrawer->setPlayerCrabDir(-1);
}
break;
}
}
void handleSpecialKeyReleased(int key, int x, int y) {
switch (key) {
case GLUT_KEY_LEFT:
isLeftKeyPressed = false;
if (isRightKeyPressed) {
gameDrawer->setPlayerCrabDir(-1);
}
else {
gameDrawer->setPlayerCrabDir(0);
}
break;
case GLUT_KEY_RIGHT:
isRightKeyPressed = false;
if (isLeftKeyPressed) {
gameDrawer->setPlayerCrabDir(1);
}
else {
gameDrawer->setPlayerCrabDir(0);
}
break;
}
}
void initRendering() {
glEnable(GL_DEPTH_TEST);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_NORMALIZE);
glEnable(GL_CULL_FACE);
glShadeModel(GL_SMOOTH);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
initGameDrawer();
}
void handleResize(int w, int h) {
glViewport(0, 0, w, h);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45.0, (double)w / (double)h, 0.02, 5.0);
}
void drawScene() {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glTranslatef(0.5f, -0.3f, -1.8f);
glRotatef(50, 1, 0, 0);
glRotatef(180, 0, 1, 0);
//This makes the camera rotate slowly over time
glTranslatef(0.5f, 0, 0.5f);
glRotatef(3 * sin(rotationVar), 0, 1, 0);
glTranslatef(-0.5f, 0, -0.5f);
gameDrawer->draw();
glutSwapBuffers();
}
void update(int value) {
gameDrawer->advance((float)TIMER_MS / 1000);
rotationVar += 0.2f * (float)TIMER_MS / 1000;
while (rotationVar > 2 * PI) {
rotationVar -= 2 * PI;
}
glutPostRedisplay();
glutTimerFunc(TIMER_MS, update, 0);
}
int main(int argc, char** argv) {
srand((unsigned int)time(0)); //Seed the random number generator
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(600, 600);
glutCreateWindow("A Sample Game: Crab Pong - videotutorialsrock.com");
initRendering();
gameDrawer = new GameDrawer();
glutDisplayFunc(drawScene);
glutKeyboardFunc(handleKeypress);
glutSpecialFunc(handleSpecialKeypress);
glutSpecialUpFunc(handleSpecialKeyReleased);
glutReshapeFunc(handleResize);
glutTimerFunc(TIMER_MS, update, 0);
glutMainLoop();
return 0;
}
| 23.725 | 80 | 0.71549 | liuyuwang2016 |
bfd573a1dca58165e16ad07c6f9d205d83a40c91 | 5,170 | cpp | C++ | Aphrodite-Runtime/src/Aphrodite/UI/UILayer.cpp | npchitman/Aphrodite | f2fe3fecfd2d0cc6604362e16ee012db079242a8 | [
"MIT"
] | 17 | 2021-07-01T09:18:12.000Z | 2022-01-22T04:54:16.000Z | Aphrodite-Runtime/src/Aphrodite/UI/UILayer.cpp | npchitman/GEngine | f2fe3fecfd2d0cc6604362e16ee012db079242a8 | [
"MIT"
] | 1 | 2021-07-12T10:32:23.000Z | 2021-12-31T07:06:11.000Z | Aphrodite-Runtime/src/Aphrodite/UI/UILayer.cpp | npchitman/GEngine | f2fe3fecfd2d0cc6604362e16ee012db079242a8 | [
"MIT"
] | 2 | 2021-07-08T08:26:25.000Z | 2021-07-12T10:29:29.000Z | //
// Created by npchitman on 5/31/21.
//
#include "Aphrodite/UI/UILayer.h"
#include <ImGuizmo.h>
#include <backends/imgui_impl_glfw.h>
#include <backends/imgui_impl_opengl3.h>
#include <imgui.h>
#include "Aphrodite/Core/Application.h"
#include "Aphrodite/Fonts/IconsFontAwesome5Pro.h"
#include "GLFW/glfw3.h"
#include "pch.h"
namespace Aph {
UILayer::UILayer() : Layer("UILayer") {}
UILayer::~UILayer() = default;
void UILayer::OnAttach() {
APH_PROFILE_FUNCTION();
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO &io = ImGui::GetIO(); (void) io;
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;// Enable Keyboard Controls
// TODO: Enable Gamepad
// io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable; // Enable Docking
// io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;// Enable Multi-Viewport
static const ImWchar icons_ranges_fontawesome[] = {ICON_MIN_FA, ICON_MAX_FA, 0};
ImFontConfig icons_config_fontawesome;
icons_config_fontawesome.MergeMode = true;
icons_config_fontawesome.PixelSnapH = true;
io.FontDefault = io.Fonts->AddFontFromFileTTF(FONT_UI, Style::FontSize::text);
APH_ASSERT(io.Fonts->AddFontFromFileTTF(FONT_ICON_FILE_NAME_FAS, Style::FontSize::icon,
&icons_config_fontawesome, icons_ranges_fontawesome), "Can't find icon fonts");
#if 1
ImGui::StyleColorsDark();
#else
//UI::StyleColorsClassic();
#endif
// ImGuiStyle &style = ImGui::GetStyle();
// if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
// style.WindowRounding = 0.0f;
// style.Colors[ImGuiCol_WindowBg].w = 1.0f;
// }
SetDarkThemeColors();
auto &app = Application::Get();
auto *window = static_cast<GLFWwindow *>(app.GetWindow().GetNativeWindow());
ImGui_ImplGlfw_InitForOpenGL(window, true);
ImGui_ImplOpenGL3_Init("#version 460");
}
void UILayer::OnDetach() {
APH_PROFILE_FUNCTION();
ImGui_ImplOpenGL3_Shutdown();
ImGui_ImplGlfw_Shutdown();
ImGui::DestroyContext();
}
void UILayer::OnEvent(Event &e) {
if (m_BlockEvents) {
ImGuiIO &io = ImGui::GetIO();
e.Handled |= e.IsInCateGory(EventCategoryMouse) & io.WantCaptureMouse;
e.Handled |= e.IsInCateGory(EventCategoryKeyboard) & io.WantCaptureKeyboard;
}
}
void UILayer::Begin() {
APH_PROFILE_FUNCTION();
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGuizmo::BeginFrame();
}
void UILayer::End() {
APH_PROFILE_FUNCTION();
ImGuiIO &io = ImGui::GetIO();
auto &app = Application::Get();
io.DisplaySize = ImVec2(static_cast<float>(app.GetWindow().GetWidth()),
static_cast<float>(app.GetWindow().GetHeight()));
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
// if (io.ConfigFlags & ImGuiConfigFlags_ViewportsEnable) {
// auto *backup_current_context = glfwGetCurrentContext();
// ImGui::UpdatePlatformWindows();
// ImGui::RenderPlatformWindowsDefault();
// glfwMakeContextCurrent(backup_current_context);
// }
}
void UILayer::SetDarkThemeColors() {
auto &colors = ImGui::GetStyle().Colors;
// Text
colors[ImGuiCol_Text] = Style::Color::foreground_1;
// Window
colors[ImGuiCol_WindowBg] = Style::Color::background_1;
// MenuBar
colors[ImGuiCol_MenuBarBg] = Style::Color::background_1;
// Headers
colors[ImGuiCol_Header] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_HeaderHovered] = Style::Color::background_hovered;
colors[ImGuiCol_HeaderActive] = Style::Color::background_active;
// Buttons
colors[ImGuiCol_Button] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_ButtonHovered] = Style::Color::background_hovered;
colors[ImGuiCol_ButtonActive] = Style::Color::background_active;
// Frame BG
colors[ImGuiCol_FrameBg] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
colors[ImGuiCol_FrameBgHovered] = Style::Color::background_hovered;
colors[ImGuiCol_FrameBgActive] = Style::Color::background_active;
// Tabs
colors[ImGuiCol_Tab] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TabHovered] = ImVec4{0.38f, 0.3805f, 0.381f, 1.0f};
colors[ImGuiCol_TabActive] = ImVec4{0.28f, 0.2805f, 0.281f, 1.0f};
colors[ImGuiCol_TabUnfocused] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TabUnfocusedActive] = ImVec4{0.2f, 0.205f, 0.21f, 1.0f};
// Title
colors[ImGuiCol_TitleBg] = Style::Color::background_1;
colors[ImGuiCol_TitleBgActive] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
colors[ImGuiCol_TitleBgCollapsed] = ImVec4{0.15f, 0.1505f, 0.151f, 1.0f};
}
}// namespace Aph
| 34.697987 | 116 | 0.640232 | npchitman |
bfd58a379b35c4da708ceca70a20e09b2e8af7e5 | 257 | cpp | C++ | docs/mfc/codesnippet/CPP/carchive-class_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 965 | 2017-06-25T23:57:11.000Z | 2022-03-31T14:17:32.000Z | docs/mfc/codesnippet/CPP/carchive-class_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 3,272 | 2017-06-24T00:26:34.000Z | 2022-03-31T22:14:07.000Z | docs/mfc/codesnippet/CPP/carchive-class_1.cpp | bobbrow/cpp-docs | 769b186399141c4ea93400863a7d8463987bf667 | [
"CC-BY-4.0",
"MIT"
] | 951 | 2017-06-25T12:36:14.000Z | 2022-03-26T22:49:06.000Z | CFile file;
TCHAR szBuf[512];
if (!file.Open(_T("CArchive__test__file.txt"),
CFile::modeCreate | CFile::modeWrite))
{
#ifdef _DEBUG
AFXDUMP(_T("Unable to open file\n"));
exit(1);
#endif
}
CArchive ar(&file, CArchive::store, 512, szBuf); | 23.363636 | 53 | 0.653696 | bobbrow |
bfd8be58022267758a479926ca6d820fe4e40d4f | 6,343 | cpp | C++ | src/JoystickSDL2.cpp | Daivuk/onut | b02c5969b36897813de9c574a26d9437b67f189e | [
"MIT"
] | 50 | 2015-06-01T19:23:24.000Z | 2021-12-22T02:14:23.000Z | src/JoystickSDL2.cpp | Daivuk/onut | b02c5969b36897813de9c574a26d9437b67f189e | [
"MIT"
] | 109 | 2015-07-20T07:43:03.000Z | 2021-01-31T21:52:36.000Z | src/JoystickSDL2.cpp | Daivuk/onut | b02c5969b36897813de9c574a26d9437b67f189e | [
"MIT"
] | 9 | 2015-07-02T21:36:20.000Z | 2019-10-19T04:18:02.000Z | // Internal
#include "JoystickSDL2.h"
#include <onut/Log.h>
static const char* getSDLJoystickTypeName(SDL_JoystickType type)
{
switch (type)
{
case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
return "Game Controller";
case SDL_JOYSTICK_TYPE_WHEEL:
return "Wheel";
case SDL_JOYSTICK_TYPE_ARCADE_STICK:
return "Arcade Stick";
case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
return "Flight Stick";
case SDL_JOYSTICK_TYPE_DANCE_PAD:
return "Dance Pad";
case SDL_JOYSTICK_TYPE_GUITAR:
return "Guitar";
case SDL_JOYSTICK_TYPE_DRUM_KIT:
return "Drum Kit";
case SDL_JOYSTICK_TYPE_ARCADE_PAD:
return "Arcade Pad";
case SDL_JOYSTICK_TYPE_THROTTLE:
return "Throttle";
default:
case SDL_JOYSTICK_TYPE_UNKNOWN:
return "Unknown";
}
}
namespace onut
{
OJoystickRef Joystick::create(int index)
{
return std::shared_ptr<JoystickSDL2>(new JoystickSDL2(index));
}
JoystickSDL2::JoystickSDL2(int index)
: Joystick(index)
, m_pSDLJoystick(nullptr)
, m_axisStates(nullptr)
, m_state(nullptr)
, m_previousState(nullptr)
{
m_pSDLJoystick = SDL_JoystickOpen(index);
if (m_pSDLJoystick)
{
m_buttonCount = SDL_JoystickNumButtons(m_pSDLJoystick);
m_hatCount = SDL_JoystickNumHats(m_pSDLJoystick);
m_axisCount = SDL_JoystickNumAxes(m_pSDLJoystick);
auto type = SDL_JoystickGetType(m_pSDLJoystick);
auto buttonCount = getButtonCount();
m_state = new Uint8[buttonCount];
m_previousState = new Uint8[buttonCount];
m_axisStates = new float[m_axisCount];
memset(m_state, 0, sizeof(Uint8) * buttonCount);
memset(m_previousState, 0, sizeof(Uint8) * buttonCount);
memset(m_axisStates, 0, sizeof(int) * m_axisCount);
switch (type)
{
case SDL_JOYSTICK_TYPE_ARCADE_STICK:
case SDL_JOYSTICK_TYPE_FLIGHT_STICK:
m_type = Type::Stick;
break;
case SDL_JOYSTICK_TYPE_THROTTLE:
m_type = Type::Throttle;
break;
case SDL_JOYSTICK_TYPE_WHEEL:
case SDL_JOYSTICK_TYPE_GAMECONTROLLER:
case SDL_JOYSTICK_TYPE_DANCE_PAD:
case SDL_JOYSTICK_TYPE_GUITAR:
case SDL_JOYSTICK_TYPE_DRUM_KIT:
case SDL_JOYSTICK_TYPE_ARCADE_PAD:
default:
m_type = Type::Other;
break;
}
m_name = SDL_JoystickName(m_pSDLJoystick);
OLog("Joystick: " + m_name +
", type = " + getSDLJoystickTypeName(type) +
", axis = " + std::to_string(m_axisCount) +
", buttons = " + std::to_string(m_buttonCount) + " + " + std::to_string(m_axisCount * 2) +
", balls = " + std::to_string(SDL_JoystickNumBalls(m_pSDLJoystick)) +
", hats = " + std::to_string(m_hatCount));
}
}
JoystickSDL2::~JoystickSDL2()
{
if (m_pSDLJoystick)
{
SDL_JoystickClose(m_pSDLJoystick);
}
if (m_state) delete[] m_state;
if (m_previousState) delete[] m_previousState;
}
void JoystickSDL2::update()
{
for (int i = 0; i < m_axisCount; ++i)
{
m_axisStates[i] = (float)SDL_JoystickGetAxis(m_pSDLJoystick, i) / 32768.0f;
}
if (bSwaped)
{
memcpy(m_previousState, m_state, sizeof(Uint8) * getButtonCount());
}
bSwaped = true;
}
void JoystickSDL2::updateSDL2()
{
if (!m_pSDLJoystick) return;
if (bSwaped)
{
memcpy(m_previousState, m_state, sizeof(Uint8) * getButtonCount());
}
// Buttons
for (int i = 0; i < m_buttonCount; ++i)
{
auto sdlState = SDL_JoystickGetButton(m_pSDLJoystick, i);
if (sdlState || bSwaped)
{
m_state[i] = sdlState;
}
}
// Hats
auto hatBase = m_buttonCount;
for (int i = 0; i < m_hatCount; ++i)
{
auto hatState = SDL_JoystickGetHat(m_pSDLJoystick, i);
m_state[hatBase + i * 4 + 0] = (hatState & SDL_HAT_UP) ? 1 : 0;
m_state[hatBase + i * 4 + 1] = (hatState & SDL_HAT_RIGHT) ? 1 : 0;
m_state[hatBase + i * 4 + 2] = (hatState & SDL_HAT_DOWN) ? 1 : 0;
m_state[hatBase + i * 4 + 3] = (hatState & SDL_HAT_LEFT) ? 1 : 0;
}
// Axis
auto axisBase = m_buttonCount + m_hatCount * 4;
for (int i = 0; i < m_axisCount; ++i)
{
auto value = (float)SDL_JoystickGetAxis(m_pSDLJoystick, i) / 32768.0f;
m_state[axisBase + i * 2 + 0] = (value < -0.3f) ? 1 : 0;
m_state[axisBase + i * 2 + 1] = (value > 0.3f) ? 1 : 0;
}
bSwaped = false;
}
bool JoystickSDL2::isPressed(int button) const
{
return isPressed(button, m_state);
}
bool JoystickSDL2::isJustPressed(int button) const
{
return !isPressed(button, m_previousState) && isPressed(button, m_state);
}
bool JoystickSDL2::isJustReleased(int button) const
{
return isPressed(button, m_previousState) && !isPressed(button, m_state);
}
float JoystickSDL2::getAxis(int id) const
{
if (id < 0 || id >= getAxisCount()) return 0.0f;
return m_axisStates[id];
}
int JoystickSDL2::getAxisCount() const
{
return m_axisCount;
}
int JoystickSDL2::getButtonCount() const
{
return m_buttonCount + m_hatCount * 4 + m_axisCount * 2;
}
int JoystickSDL2::getHatButtonBase() const
{
return m_buttonCount;
}
int JoystickSDL2::getAxisButtonBase() const
{
return m_buttonCount + m_hatCount * 4;
}
bool JoystickSDL2::isPressed(int button, const Uint8* state) const
{
if (button < 0 || button >= getButtonCount()) return false;
return state[button] ? true : false;
}
}
| 30.349282 | 107 | 0.558726 | Daivuk |
bfd94adc5ebc883e78ee7acbfa2c5de732404b06 | 432 | cpp | C++ | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/eprintf.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/eprintf.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | project/OFEC_sc2/instance/algorithm/realworld/DVRP/LKH/eprintf.cpp | BaiChunhui-9803/bch_sc2_OFEC | d50211b27df5a51a953a2475b6c292d00cbfeff6 | [
"MIT"
] | null | null | null | #include "./INCLUDE/LKH.h"
#include <stdarg.h>
/*
* The eprintf function prints an error message and exits.
*/
void LKH::LKHAlg::eprintf(const char *fmt, ...)
{
va_list args;
if (LastLine && *LastLine)
fprintf(stderr, "\n%s\n", LastLine);
fprintf(stderr, "\n*** Error ***\n");
va_start(args, fmt);
vfprintf(stderr, fmt, args);
va_end(args);
fprintf(stderr, "\n");
exit(EXIT_FAILURE);
}
| 20.571429 | 58 | 0.599537 | BaiChunhui-9803 |
bfe37635b7544ca38850eff753e7d9622a43cd5d | 5,733 | cpp | C++ | Util/src/PropertyFileConfiguration.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 3 | 2015-06-08T15:09:28.000Z | 2020-12-31T02:28:37.000Z | Util/src/PropertyFileConfiguration.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 3 | 2021-06-02T02:59:06.000Z | 2021-09-16T04:35:06.000Z | Util/src/PropertyFileConfiguration.cpp | astlin/poco | b878152e9034b89c923bc3c97e16ae1b92c09bf4 | [
"BSL-1.0"
] | 6 | 2021-06-02T02:39:34.000Z | 2022-03-29T05:51:57.000Z | //
// PropertyFileConfiguration.cpp
//
// Library: Util
// Package: Configuration
// Module: PropertyFileConfiguration
//
// Copyright (c) 2004-2009, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/Util/PropertyFileConfiguration.h"
#include "Poco/Exception.h"
#include "Poco/String.h"
#include "Poco/Path.h"
#include "Poco/FileStream.h"
#include "Poco/LineEndingConverter.h"
#include "Poco/Ascii.h"
using Poco::trim;
using Poco::Path;
namespace Poco {
namespace Util {
PropertyFileConfiguration::PropertyFileConfiguration() :
_preserveComment(false)
{
}
PropertyFileConfiguration::PropertyFileConfiguration(std::istream& istr, bool preserveComment) :
_preserveComment(preserveComment)
{
load(istr, preserveComment);
}
PropertyFileConfiguration::PropertyFileConfiguration(const std::string& path, bool preserveComment) :
_preserveComment(preserveComment)
{
load(path, preserveComment);
}
PropertyFileConfiguration::~PropertyFileConfiguration()
{
}
void PropertyFileConfiguration::load(std::istream& istr, bool preserveComment)
{
_preserveComment = preserveComment;
clear();
_fileContent.clear();
_keyFileContentItMap.clear();
while (!istr.eof()) parseLine(istr);
}
void PropertyFileConfiguration::load(const std::string& path, bool preserveComment)
{
Poco::FileInputStream istr(path);
if (istr.good())
load(istr, preserveComment);
else
throw Poco::OpenFileException(path);
}
void PropertyFileConfiguration::save(std::ostream& ostr) const
{
if (_preserveComment)
{
for (FileContent::const_iterator it = _fileContent.begin(); it != _fileContent.end(); ++it)
ostr << *it;
}
else
{
for (MapConfiguration::iterator it = begin(); it != end(); ++it)
ostr << composeOneLine(it->first, it->second);
}
}
void PropertyFileConfiguration::save(const std::string& path) const
{
Poco::FileOutputStream ostr(path);
if (ostr.good())
{
Poco::OutputLineEndingConverter lec(ostr);
save(lec);
lec.flush();
ostr.flush();
if (!ostr.good()) throw Poco::WriteFileException(path);
}
else throw Poco::CreateFileException(path);
}
// If _preserveComment is true, not only save key-value into map
// but also save the entire file into _fileContent.
// Otherwise, only save key-value into map.
void PropertyFileConfiguration::parseLine(std::istream& istr)
{
skipSpace(istr);
if (!istr.eof())
{
if (isComment(istr.peek()))
{
if (_preserveComment) saveComment(istr);
else skipLine(istr);
}
else saveKeyValue(istr);
}
}
void PropertyFileConfiguration::skipSpace(std::istream& istr) const
{
while (!istr.eof() && Poco::Ascii::isSpace(istr.peek())) istr.get();
}
int PropertyFileConfiguration::readChar(std::istream& istr)
{
for (;;)
{
int c = istr.get();
if (c == '\\')
{
c = istr.get();
switch (c)
{
case 't':
return '\t';
case 'r':
return '\r';
case 'n':
return '\n';
case 'f':
return '\f';
case '\r':
if (istr.peek() == '\n')
istr.get();
continue;
case '\n':
continue;
default:
return c;
}
}
else if (c == '\n' || c == '\r')
return 0;
else
return c;
}
}
void PropertyFileConfiguration::setRaw(const std::string& key, const std::string& value)
{
MapConfiguration::setRaw(key, value);
if (_preserveComment)
{
// Insert the key-value to the end of _fileContent and update _keyFileContentItMap.
if (_keyFileContentItMap.count(key) == 0)
{
FileContent::iterator fit = _fileContent.insert(_fileContent.end(), composeOneLine(key, value));
_keyFileContentItMap[key] = fit;
}
// Update the key-value in _fileContent.
else
{
FileContent::iterator fit = _keyFileContentItMap[key];
*fit = composeOneLine(key, value);
}
}
}
void PropertyFileConfiguration::removeRaw(const std::string& key)
{
MapConfiguration::removeRaw(key);
// remove the key from _fileContent and _keyFileContentItMap.
if (_preserveComment)
{
_fileContent.erase(_keyFileContentItMap[key]);
_keyFileContentItMap.erase(key);
}
}
bool PropertyFileConfiguration::isComment(int c) const
{
return c == '#' || c == '!';
}
void PropertyFileConfiguration::saveComment(std::istream& istr)
{
std::string comment;
int c = istr.get();
while (!isNewLine(c))
{
comment += (char) c;
c = istr.get();
}
comment += (char) c;
_fileContent.push_back(comment);
}
void PropertyFileConfiguration::skipLine(std::istream& istr) const
{
int c = istr.get();
while (!isNewLine(c)) c = istr.get();
}
void PropertyFileConfiguration::saveKeyValue(std::istream& istr)
{
int c = istr.get();
std::string key;
while (!isNewLine(c) && !isKeyValueSeparator(c))
{
key += (char) c;
c = istr.get();
}
std::string value;
if (isKeyValueSeparator(c))
{
c = readChar(istr);
while (!istr.eof() && c)
{
value += (char) c;
c = readChar(istr);
}
}
setRaw(trim(key), trim(value));
}
bool PropertyFileConfiguration::isNewLine(int c) const
{
return c == std::char_traits<char>::eof() || c == '\n' || c == '\r';
}
std::string PropertyFileConfiguration::composeOneLine(const std::string& key, const std::string& value) const
{
std::string result = key + ": ";
for (std::string::const_iterator its = value.begin(); its != value.end(); ++its)
{
switch (*its)
{
case '\t':
result += "\\t";
break;
case '\r':
result += "\\r";
break;
case '\n':
result += "\\n";
break;
case '\f':
result += "\\f";
break;
case '\\':
result += "\\\\";
break;
default:
result += *its;
break;
}
}
return result += "\n";
}
bool PropertyFileConfiguration::isKeyValueSeparator(int c) const
{
return c == '=' || c == ':';
}
} } // namespace Poco::Util
| 18.983444 | 109 | 0.666492 | astlin |
bfe3a5b32dafa56acddd93f459ac0d365f19c96b | 3,332 | cpp | C++ | samples/LoginCpp/LoginCpp/LoginCpp.Shared/Dialogs.Shared.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 197 | 2015-07-14T22:33:14.000Z | 2019-05-05T15:26:15.000Z | samples/LoginCpp/LoginCpp/LoginCpp.Shared/Dialogs.Shared.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 209 | 2015-07-15T14:49:48.000Z | 2019-02-15T14:39:48.000Z | samples/LoginCpp/LoginCpp/LoginCpp.Shared/Dialogs.Shared.xaml.cpp | omer-ispl/winsdkfb1 | e3bcd1d1e49e5ff94e6a9c971e4d8a9c82fad93b | [
"MIT"
] | 115 | 2015-07-15T06:57:34.000Z | 2019-01-12T08:55:15.000Z |
//******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "pch.h"
#include "Dialogs.xaml.h"
using namespace LoginCpp;
using namespace concurrency;
using namespace winsdkfb;
using namespace Platform;
using namespace Platform::Collections;
using namespace Windows::Foundation;
using namespace Windows::Foundation::Collections;
using namespace Windows::Graphics::Display;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Controls::Primitives;
using namespace Windows::UI::Xaml::Data;
using namespace Windows::UI::Xaml::Input;
using namespace Windows::UI::Xaml::Interop;
using namespace Windows::UI::Xaml::Media;
using namespace Windows::UI::Xaml::Navigation;
void Dialogs::FeedDialogButton_Click(
Object^ sender,
RoutedEventArgs^ e
)
{
FBSession^ s = FBSession::ActiveSession;
if (!s->LoggedIn)
{
OutputDebugString(L"The user is no longer logged in.\n");
}
else
{
PropertySet^ params = ref new PropertySet();
params->Insert(L"caption", L"I love Brussels Sprouts!");
params->Insert(L"link", L"https://en.wikipedia.org/wiki/Brussels_sprout");
params->Insert(L"description", L"Om Nom Nom!");
create_task(s->ShowFeedDialogAsync(params))
.then([=](FBResult^ Response)
{
OutputDebugString(L"Showed 'Feed' dialog.\n");
});
}
}
void Dialogs::AppRequestsButton_Click(
Object^ sender,
RoutedEventArgs^ e
)
{
FBSession^ s = FBSession::ActiveSession;
if (!s->LoggedIn)
{
OutputDebugString(L"The user is no longer logged in.\n");
}
else
{
PropertySet^ params = ref new PropertySet();
params->Insert(L"title", L"I love Brussels Sprouts!");
params->Insert(L"message", L"Om Nom Nom!");
create_task(s->ShowRequestsDialogAsync(params))
.then([=](FBResult^ Response)
{
OutputDebugString(L"Showed 'Requests' dialog.\n");
});
}
}
void LoginCpp::Dialogs::SendDialogButton_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
FBSession^ s = FBSession::ActiveSession;
if (!s->LoggedIn)
{
OutputDebugString(L"The user is no longer logged in.\n");
}
else
{
PropertySet^ params = ref new PropertySet();
params->Insert(L"link", L"http://example.com");
create_task(s->ShowSendDialogAsync(params))
.then([=](FBResult^ DialogResponse)
{
OutputDebugString(L"Showed 'Send' dialog.\n");
});
}
}
| 30.290909 | 111 | 0.632053 | omer-ispl |
bfe95b088e682b4233cd278ffd85342546789b91 | 341 | cpp | C++ | MarioBros/GameApp/main.cpp | SIYUN09/Portfolio | 9b9327e46bd873de52cd1bf44ae3079502b27958 | [
"MIT"
] | null | null | null | MarioBros/GameApp/main.cpp | SIYUN09/Portfolio | 9b9327e46bd873de52cd1bf44ae3079502b27958 | [
"MIT"
] | null | null | null | MarioBros/GameApp/main.cpp | SIYUN09/Portfolio | 9b9327e46bd873de52cd1bf44ae3079502b27958 | [
"MIT"
] | null | null | null | #include <Windows.h>
#include <GameEngineBase/GameEngineDebug.h>
#include <GameEngineBase/GameEngineWindow.h>
#include <GameEngineContents/StudyGame.h>
int __stdcall WinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ char* lpCmdLine,
_In_ int nCmdShow)
{
GameEngine::Start<StudyGame>();
} | 20.058824 | 47 | 0.739003 | SIYUN09 |
bff5f4973c8c2094ed85910bab7947e4e7e6f5f5 | 575 | hpp | C++ | hyper/include/hyper/backends/c/c_linker.hpp | HyperionOrg/HyperLang | 30f7a1707d00fb5cc6dc22913764389a3b998f09 | [
"MIT"
] | null | null | null | hyper/include/hyper/backends/c/c_linker.hpp | HyperionOrg/HyperLang | 30f7a1707d00fb5cc6dc22913764389a3b998f09 | [
"MIT"
] | null | null | null | hyper/include/hyper/backends/c/c_linker.hpp | HyperionOrg/HyperLang | 30f7a1707d00fb5cc6dc22913764389a3b998f09 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2022-present, SkillerRaptor <skillerraptor@protonmail.com>
*
* SPDX-License-Identifier: MIT
*/
#pragma once
#include <string>
#include <vector>
namespace hyper
{
class CLinker
{
public:
CLinker(
const std::vector<std::string> &output_files,
bool freestanding,
std::string_view linker_script,
std::string_view output_file);
void link() const;
private:
const std::vector<std::string> &m_output_files;
bool m_freestanding = false;
std::string_view m_linker_script;
std::string_view m_output_file;
};
} // namespace hyper
| 17.96875 | 75 | 0.716522 | HyperionOrg |
bff9b40675e1785000253d3206e7048883dc3780 | 397 | cpp | C++ | Seminarii/seminar_2/movieseries.cpp | andreea-olariu/oop-2022 | df2d5246d6050874c4a5cd6677fdb6b3a3670be5 | [
"MIT"
] | null | null | null | Seminarii/seminar_2/movieseries.cpp | andreea-olariu/oop-2022 | df2d5246d6050874c4a5cd6677fdb6b3a3670be5 | [
"MIT"
] | null | null | null | Seminarii/seminar_2/movieseries.cpp | andreea-olariu/oop-2022 | df2d5246d6050874c4a5cd6677fdb6b3a3670be5 | [
"MIT"
] | null | null | null | #include <iostream>
#include "movieseries.h"
void MovieSeries::init() {
size = 0;
}
void MovieSeries::add(const Movie &movie) {
movies[size] = movie;
size++;
}
void MovieSeries::print() const {
for(unsigned i = 0; i < size; i++) {
std::cout << i + 1 << ": " << movies[i].get_name() << " "
<< movies[i].get_score() << " " << movies[i].get_year() << '\n';
}
}
| 20.894737 | 72 | 0.528967 | andreea-olariu |
bffe0f38c3291d7e0baca7170e33ec4c1f04dc41 | 24,297 | cpp | C++ | app/src/main/cpp/Levels/Level.cpp | ArnisLielturks/Urho3D-Project-Template | 998d12e2470ec8a43ec552a1c2182eecfed63ca1 | [
"MIT"
] | 48 | 2019-01-06T02:17:44.000Z | 2021-09-28T15:10:30.000Z | app/src/main/cpp/Levels/Level.cpp | urnenfeld/Urho3D-Project-Template | efd45e4edcffb232753010a3ee623d6cf9bc1c26 | [
"MIT"
] | 17 | 2019-01-22T17:48:58.000Z | 2021-04-04T17:52:56.000Z | app/src/main/cpp/Levels/Level.cpp | ArnisLielturks/Urho3D-Project-Template | 998d12e2470ec8a43ec552a1c2182eecfed63ca1 | [
"MIT"
] | 18 | 2019-02-18T13:55:41.000Z | 2021-04-02T14:28:00.000Z | #include <Urho3D/Resource/Localization.h>
#include <Urho3D/Audio/SoundListener.h>
#include <Urho3D/Audio/Audio.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/UI/UI.h>
#include <Urho3D/Physics/PhysicsEvents.h>
#include <Urho3D/Physics/PhysicsWorld.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Physics/CollisionShape.h>
#include <Urho3D/Physics/RigidBody.h>
#include <Urho3D/Network/NetworkEvents.h>
#include <Urho3D/Resource/ResourceCache.h>
#include <Urho3D/Graphics/Material.h>
#if !defined(__EMSCRIPTEN__)
#include <Urho3D/Network/Network.h>
#endif
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Graphics/Model.h>
#include <Urho3D/Graphics/Octree.h>
#include <Urho3D/Graphics/Camera.h>
#include <Urho3D/Graphics/Graphics.h>
#include "../Generator/Generator.h"
#include "Level.h"
#include "../CustomEvents.h"
#include "../Audio/AudioManagerDefs.h"
#include "../Audio/AudioManager.h"
#include "../Input/ControllerInput.h"
#include "../Messages/Achievements.h"
#include "../Player/PlayerEvents.h"
#include "../UI/WindowManager.h"
#include "../Console/ConsoleHandlerEvents.h"
#include "../LevelManagerEvents.h"
#include "../Input/ControllerEvents.h"
#include "../UI/WindowEvents.h"
#include "../Audio/AudioEvents.h"
#include "../Network/NetworkEvents.h"
#include "../SceneManager.h"
#include "../Globals/CollisionLayers.h"
#include "../Globals/ViewLayers.h"
#include "../Input/ControlDefines.h"
#ifdef VOXEL_SUPPORT
#include "Voxel/VoxelWorld.h"
#include "Voxel/LightManager.h"
#include "Voxel/VoxelEvents.h"
#include "Voxel/ChunkGenerator.h"
#include "Voxel/TreeGenerator.h"
using namespace VoxelEvents;
#endif
using namespace Levels;
using namespace ConsoleHandlerEvents;
using namespace LevelManagerEvents;
using namespace ControllerEvents;
using namespace WindowEvents;
using namespace AudioEvents;
using namespace CustomEvents;
using namespace NetworkEvents;
static int REMOTE_PLAYER_ID = 1000;
Level::Level(Context* context) :
BaseLevel(context),
drawDebug_(false)
{
}
Level::~Level()
{
StopAllAudio();
#ifdef VOXEL_SUPPORT
if (GetSubsystem<VoxelWorld>()) {
context_->RemoveSubsystem<VoxelWorld>();
context_->RemoveSubsystem<ChunkGenerator>();
context_->RemoveSubsystem<LightManager>();
context_->RemoveSubsystem<TreeGenerator>();
}
#endif
}
void Level::RegisterObject(Context* context)
{
context->RegisterFactory<Level>();
Player::RegisterObject(context);
#ifdef VOXEL_SUPPORT
VoxelWorld::RegisterObject(context);
Chunk::RegisterObject(context);
ChunkGenerator::RegisterObject(context);
LightManager::RegisterObject(context);
TreeGenerator::RegisterObject(context);
#endif
}
void Level::Init()
{
if (!scene_) {
auto localization = GetSubsystem<Localization>();
// There is no scene, get back to the main menu
VariantMap& eventData = GetEventDataMap();
eventData["Name"] = "MainMenu";
eventData["Message"] = localization->Get("NO_SCENE");
SendEvent(E_SET_LEVEL, eventData);
return;
}
auto listener = scene_->CreateComponent<SoundListener>();
GetSubsystem<Audio>()->SetListener(listener);
// Enable achievement showing for this level
GetSubsystem<Achievements>()->SetShowAchievements(true);
StopAllAudio();
StartAudio();
auto* controllerInput = GetSubsystem<ControllerInput>();
Vector<int> controlIndexes = controllerInput->GetControlIndexes();
InitViewports(controlIndexes);
// Create the scene content
CreateScene();
// Create the UI content
CreateUI();
#ifdef VOXEL_SUPPORT
if (data_.Contains("Map") && data_["Map"].GetString() == "Scenes/Voxel.xml") {
CreateVoxelWorld();
}
#endif
if (data_.Contains("Map") && data_["Map"].GetString() == "Scenes/Terrain.xml") {
auto cache = GetSubsystem<ResourceCache>();
Node *terrainNode = scene_->CreateChild("Terrain");
terrainNode->SetPosition(Vector3(0.0f, -0.0f, 0.0f));
terrain_ = terrainNode->CreateComponent<Terrain>();
terrain_->SetPatchSize(64);
terrain_->SetSpacing(Vector3(1.0f, 0.1f, 1.0f));
terrain_->SetSmoothing(true);
terrain_->SetHeightMap(GetSubsystem<Generator>()->GetImage());
terrain_->SetMaterial(cache->GetResource<Material>("Materials/Terrain.xml"));
terrain_->SetOccluder(true);
terrain_->SetCastShadows(true);
auto *body = terrainNode->CreateComponent<RigidBody>();
body->SetCollisionLayerAndMask(COLLISION_MASK_GROUND, COLLISION_MASK_PLAYER | COLLISION_MASK_OBSTACLES);
auto *shape = terrainNode->CreateComponent<CollisionShape>();
shape->SetTerrain();
}
// Subscribe to global events for camera movement
SubscribeToEvents();
auto input = GetSubsystem<Input>();
if (input->IsMouseVisible()) {
input->SetMouseVisible(false);
}
if (!GetSubsystem<Engine>()->IsHeadless()) {
for (auto it = controlIndexes.Begin(); it != controlIndexes.End(); ++it) {
using namespace RemoteClientId;
if (data_.Contains(P_NODE_ID) && data_.Contains(P_PLAYER_ID)) {
// We are the client, we have to lookup the node on the received scene
players_[(*it)] = CreatePlayer((*it), true, "", data_[P_NODE_ID].GetInt());
} else {
players_[(*it)] = CreatePlayer((*it), true, "Player " + String((*it)));
}
}
}
#if !defined(__EMSCRIPTEN__)
if (!GetSubsystem<Network>()->GetServerConnection()) {
for (int i = 0; i < 0; i++) {
players_[100 + i] = CreatePlayer(100 + i, false, "Bot " + String(100 + i));
URHO3D_LOGINFO("Bot created");
}
}
#endif
#ifdef __ANDROID__
GetSubsystem<ControllerInput>()->ShowOnScreenJoystick();
#endif
}
#ifdef VOXEL_SUPPORT
void Level::CreateVoxelWorld()
{
if (!GetSubsystem<VoxelWorld>()) {
context_->RegisterSubsystem(new VoxelWorld(context_));
}
if (!GetSubsystem<ChunkGenerator>()) {
context_->RegisterSubsystem(new ChunkGenerator(context_));
GetSubsystem<ChunkGenerator>()->SetSeed(1);
}
if (!GetSubsystem<LightManager>()) {
context_->RegisterSubsystem(new LightManager(context_));
}
if (!GetSubsystem<TreeGenerator>()) {
context_->RegisterSubsystem(new TreeGenerator(context_));
}
GetSubsystem<VoxelWorld>()->Init();
}
#endif
SharedPtr<Player> Level::CreatePlayer(int controllerId, bool controllable, const String& name, int nodeID)
{
SharedPtr<Player> newPlayer(new Player(context_));
auto mapInfo = GetSubsystem<SceneManager>()->GetCurrentMapInfo();
if (mapInfo) {
if (!mapInfo->startNode.Empty()) {
Node* startNode = scene_->GetChild(mapInfo->startNode, true);
if (startNode) {
newPlayer->SetSpawnPoint(startNode->GetWorldPosition());
URHO3D_LOGINFOF("Start point node");
} else {
newPlayer->SetSpawnPoint(mapInfo->startPoint);
}
} else {
newPlayer->SetSpawnPoint(mapInfo->startPoint);
}
}
if (nodeID > 0) {
newPlayer->FindNode(scene_, nodeID);
} else {
newPlayer->CreateNode(scene_, controllerId, terrain_, 0);
}
newPlayer->SetControllable(controllable);
newPlayer->SetControllerId(controllerId);
if (!name.Empty()) {
newPlayer->SetName(name);
}
#ifdef VOXEL_SUPPORT
if (GetSubsystem<ChunkGenerator>()) {
Vector3 spawnPoint = newPlayer->GetSpawnPoint();
spawnPoint.y_ = GetSubsystem<ChunkGenerator>()->GetTerrainHeight(spawnPoint);
spawnPoint.y_ += 5;
newPlayer->SetSpawnPoint(spawnPoint);
newPlayer->ResetPosition();
}
if (GetSubsystem<VoxelWorld>()) {
GetSubsystem<VoxelWorld>()->AddObserver(newPlayer->GetNode());
}
#endif
return newPlayer;
}
void Level::StartAudio()
{
using namespace AudioDefs;
using namespace PlaySound;
VariantMap& data = GetEventDataMap();
data[P_INDEX] = AMBIENT_SOUNDS::LEVEL;
data[P_TYPE] = SOUND_AMBIENT;
SendEvent(E_PLAY_SOUND, data);
}
void Level::StopAllAudio()
{
SendEvent(E_STOP_ALL_SOUNDS);
}
void Level::CreateScene()
{
if (!scene_->HasComponent<PhysicsWorld>()) {
scene_->CreateComponent<PhysicsWorld>(REPLICATED);
}
}
void Level::CreateUI()
{
auto* localization = GetSubsystem<Localization>();
auto ui = GetSubsystem<UI>();
Text* text = ui->GetRoot()->CreateChild<Text>();
text->SetHorizontalAlignment(HA_CENTER);
text->SetVerticalAlignment(VA_TOP);
text->SetPosition(0, 50);
text->SetStyleAuto();
text->SetText(localization->Get("TUTORIAL"));
text->SetTextEffect(TextEffect::TE_STROKE);
text->SetFontSize(16);
text->SetColor(Color(0.8f, 0.8f, 0.2f));
text->SetBringToBack(true);
}
void Level::SubscribeToEvents()
{
SubscribeToEvent(E_PHYSICSPRESTEP, URHO3D_HANDLER(Level, HandlePhysicsPrestep));
SubscribeToEvent(E_POSTUPDATE, URHO3D_HANDLER(Level, HandlePostUpdate));
SubscribeToEvent(E_KEYDOWN, URHO3D_HANDLER(Level, HandleKeyDown));
SubscribeToEvent(E_KEYUP, URHO3D_HANDLER(Level, HandleKeyUp));
SubscribeToEvent(E_POSTRENDERUPDATE, URHO3D_HANDLER(Level, HandlePostRenderUpdate));
SubscribeToEvent(E_MAPPED_CONTROL_PRESSED, URHO3D_HANDLER(Level, HandleMappedControlPressed));
SubscribeToEvent(E_CLIENTCONNECTED, URHO3D_HANDLER(Level, HandleClientConnected));
SubscribeToEvent(E_CLIENTDISCONNECTED, URHO3D_HANDLER(Level, HandleClientDisconnected));
SubscribeToEvent(E_SERVERCONNECTED, URHO3D_HANDLER(Level, HandleServerConnected));
SubscribeToEvent(E_SERVERDISCONNECTED, URHO3D_HANDLER(Level, HandleServerDisconnected));
SubscribeToEvent(E_CONTROLLER_ADDED, URHO3D_HANDLER(Level, HandleControllerConnected));
SubscribeToEvent(E_CONTROLLER_REMOVED, URHO3D_HANDLER(Level, HandleControllerDisconnected));
SubscribeToEvent(E_CONTROLLER_REMOVED, URHO3D_HANDLER(Level, HandleControllerDisconnected));
SubscribeToEvent(E_VIDEO_SETTINGS_CHANGED, URHO3D_HANDLER(Level, HandleVideoSettingsChanged));
SubscribeToEvent(PlayerEvents::E_SET_PLAYER_CAMERA_TARGET, URHO3D_HANDLER(Level, HandlePlayerTargetChanged));
RegisterConsoleCommands();
SubscribeToEvent(E_LEVEL_BEFORE_DESTROY, URHO3D_HANDLER(Level, HandleBeforeLevelDestroy));
SubscribeToEvent("SettingsButtonPressed", [&](StringHash eventType, VariantMap& eventData) {
ShowPauseMenu();
});
}
void Level::RegisterConsoleCommands()
{
SendEvent(
E_CONSOLE_COMMAND_ADD,
ConsoleCommandAdd::P_NAME, "debug_geometry",
ConsoleCommandAdd::P_EVENT, "#debug_geometry",
ConsoleCommandAdd::P_DESCRIPTION, "Toggle debugging geometry",
ConsoleCommandAdd::P_OVERWRITE, true
);
SubscribeToEvent("#debug_geometry", [&](StringHash eventType, VariantMap& eventData) {
StringVector params = eventData["Parameters"].GetStringVector();
if (params.Size() > 1) {
URHO3D_LOGERROR("This command doesn't take any arguments!");
return;
}
drawDebug_ = !drawDebug_;
});
#ifdef VOXEL_SUPPORT
SendEvent(
E_CONSOLE_COMMAND_ADD,
ConsoleCommandAdd::P_NAME, "seed",
ConsoleCommandAdd::P_EVENT, "#seed",
ConsoleCommandAdd::P_DESCRIPTION, "Change world seed",
ConsoleCommandAdd::P_OVERWRITE, true
);
SubscribeToEvent("#seed", [&](StringHash eventType, VariantMap& eventData) {
StringVector params = eventData["Parameters"].GetStringVector();
if (params.Size() != 2) {
URHO3D_LOGERROR("Seed parameter is required!");
return;
}
int seed = ToInt(params[1]);
if (!GetSubsystem<ChunkGenerator>()) {
GetSubsystem<ChunkGenerator>()->SetSeed(seed);
}
});
#endif
}
void Level::HandleBeforeLevelDestroy(StringHash eventType, VariantMap& eventData)
{
remotePlayers_.Clear();
#if !defined(__EMSCRIPTEN__)
UnsubscribeFromEvent(E_SERVERDISCONNECTED);
if (GetSubsystem<Network>() && GetSubsystem<Network>()->IsServerRunning()) {
GetSubsystem<Network>()->StopServer();
}
if (GetSubsystem<Network>() && GetSubsystem<Network>()->GetServerConnection()) {
GetSubsystem<Network>()->Disconnect();
}
#endif
}
void Level::HandleControllerConnected(StringHash eventType, VariantMap& eventData)
{
#if !defined(__EMSCRIPTEN__)
// TODO: allow to play splitscreen when connected to server
if (GetSubsystem<Network>()->GetServerConnection()) {
URHO3D_LOGWARNING("Local splitscreen multiplayer is not yet supported in the network mode");
return;
}
#endif
using namespace ControllerAdded;
int controllerIndex = eventData[P_INDEX].GetInt();
auto* controllerInput = GetSubsystem<ControllerInput>();
Vector<int> controlIndexes = controllerInput->GetControlIndexes();
InitViewports(controlIndexes);
VariantMap& data = GetEventDataMap();
data["Message"] = "New controller connected!";
SendEvent("ShowNotification", data);
if (!players_.Contains(controllerIndex)) {
players_[controllerIndex] = CreatePlayer(controllerIndex, true, "Player " + String(controllerIndex + 1));
}
}
void Level::HandleControllerDisconnected(StringHash eventType, VariantMap& eventData)
{
#if !defined(__EMSCRIPTEN__)
if (GetSubsystem<Network>()->GetServerConnection()) {
return;
}
#endif
using namespace ControllerRemoved;
int controllerIndex = eventData[P_INDEX].GetInt();
if (controllerIndex > 0) {
players_.Erase(controllerIndex);
}
auto* controllerInput = GetSubsystem<ControllerInput>();
Vector<int> controlIndexes = controllerInput->GetControlIndexes();
InitViewports(controlIndexes);
VariantMap& data = GetEventDataMap();
data["Message"] = "Controller disconnected!";
SendEvent("ShowNotification", data);
}
void Level::UnsubscribeToEvents()
{
UnsubscribeFromEvent(E_PHYSICSPRESTEP);
UnsubscribeFromEvent(E_POSTUPDATE);
UnsubscribeFromEvent(E_KEYDOWN);
UnsubscribeFromEvent(E_KEYUP);
}
void Level::HandlePhysicsPrestep(StringHash eventType, VariantMap& eventData)
{
if (!scene_->IsUpdateEnabled()) {
return;
}
}
void Level::HandlePostRenderUpdate(StringHash eventType, VariantMap& eventData)
{
if (!drawDebug_) {
return;
}
scene_->GetComponent<PhysicsWorld>()->DrawDebugGeometry(true);
scene_->GetComponent<PhysicsWorld>()->SetDebugRenderer(scene_->GetComponent<DebugRenderer>());
// scene_->GetComponent<Octree>()->DrawDebugGeometry(scene_->GetComponent<DebugRenderer>(), true);
}
void Level::HandlePostUpdate(StringHash eventType, VariantMap& eventData)
{
if (!scene_->IsUpdateEnabled()) {
return;
}
using namespace PostUpdate;
float timeStep = eventData[P_TIMESTEP].GetFloat();
auto* controllerInput = GetSubsystem<ControllerInput>();
for (auto it = players_.Begin(); it != players_.End(); ++it) {
int playerId = (*it).first_;
Controls controls = controllerInput->GetControls((*it).first_);
if (cameras_[playerId]) {
Quaternion rotation(controls.pitch_, controls.yaw_, 0.0f);
cameras_[playerId]->SetRotation(rotation);
Node* target = (*it).second_->GetCameraTarget();
if (target) {
// Move camera some distance away from the ball
cameras_[playerId]->SetPosition(target->GetPosition() +
cameras_[playerId]->GetRotation() * Vector3::BACK *
(*it).second_->GetCameraDistance());
}
}
}
}
void Level::HandleKeyDown(StringHash eventType, VariantMap& eventData)
{
int key = eventData["Key"].GetInt();
if (key == KEY_TAB && !showScoreboard_) {
VariantMap& data = GetEventDataMap();
data["Name"] = "ScoreboardWindow";
SendEvent(E_OPEN_WINDOW, data);
showScoreboard_ = true;
}
if (key == KEY_ESCAPE) {
ShowPauseMenu();
}
}
void Level::ShowPauseMenu()
{
VariantMap& data = GetEventDataMap();
data["Name"] = "PauseWindow";
SendEvent(E_OPEN_WINDOW, data);
#if !defined(__EMSCRIPTEN__)
if (!GetSubsystem<Network>()->IsServerRunning() && !GetSubsystem<Network>()->GetServerConnection()) {
UnsubscribeToEvents();
SubscribeToEvent(E_WINDOW_CLOSED, URHO3D_HANDLER(Level, HandleWindowClosed));
Pause();
}
#endif
}
void Level::PauseMenuHidden()
{
UnsubscribeFromEvent(E_WINDOW_CLOSED);
SubscribeToEvents();
Input* input = GetSubsystem<Input>();
if (input->IsMouseVisible()) {
input->SetMouseVisible(false);
}
Run();
}
void Level::HandleKeyUp(StringHash eventType, VariantMap& eventData)
{
int key = eventData["Key"].GetInt();
if (key == KEY_TAB && showScoreboard_) {
VariantMap& data = GetEventDataMap();
data["Name"] = "ScoreboardWindow";
SendEvent(E_CLOSE_WINDOW, data);
showScoreboard_ = false;
}
}
void Level::HandleWindowClosed(StringHash eventType, VariantMap& eventData)
{
String name = eventData["Name"].GetString();
if (name == "PauseWindow") {
PauseMenuHidden();
}
if (!GetSubsystem<WindowManager>()->IsAnyWindowOpened()) {
auto input = GetSubsystem<Input>();
input->SetMouseVisible(false);
}
}
void Level::HandleVideoSettingsChanged(StringHash eventType, VariantMap& eventData)
{
auto* controllerInput = GetSubsystem<ControllerInput>();
Vector<int> controlIndexes = controllerInput->GetControlIndexes();
InitViewports(controlIndexes);
}
void Level::HandleClientConnected(StringHash eventType, VariantMap& eventData)
{
using namespace ClientConnected;
// When a client connects, assign to scene to begin scene replication
auto* newConnection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
newConnection->SetScene(scene_);
remotePlayers_[newConnection] = CreatePlayer(REMOTE_PLAYER_ID, true, "Remote " + String(REMOTE_PLAYER_ID));
remotePlayers_[newConnection]->SetClientConnection(newConnection);
REMOTE_PLAYER_ID++;
using namespace RemoteClientId;
VariantMap data;
data[P_NODE_ID] = remotePlayers_[newConnection]->GetNode()->GetID();
data[P_PLAYER_ID] = remotePlayers_[newConnection]->GetControllerId();
URHO3D_LOGINFOF("Sending out remote client id %d", remotePlayers_[newConnection]->GetNode()->GetID());
newConnection->SendRemoteEvent(E_REMOTE_CLIENT_ID, true, data);
}
void Level::HandleClientDisconnected(StringHash eventType, VariantMap& eventData)
{
URHO3D_LOGINFO("Client disconnected");
using namespace ClientDisconnected;
// When a client connects, assign to scene to begin scene replication
auto* connection = static_cast<Connection*>(eventData[P_CONNECTION].GetPtr());
remotePlayers_.Erase(connection);
}
void Level::HandleServerConnected(StringHash eventType, VariantMap& eventData)
{
}
void Level::HandleServerDisconnected(StringHash eventType, VariantMap& eventData)
{
players_.Clear();
auto localization = GetSubsystem<Localization>();
VariantMap data;
data["Name"] = "MainMenu";
data["Message"] = localization->Get("DISCONNECTED_FROM_SERVER");
data["Type"] = "error";
SendEvent(E_SET_LEVEL, data);
}
void Level::HandlePlayerTargetChanged(StringHash eventType, VariantMap& eventData)
{
using namespace PlayerEvents::SetPlayerCameraTarget;
int playerId = eventData[P_ID].GetInt();
Node* targetNode = nullptr;
float cameraDistance = 0.0f;
if (eventData.Contains(P_NODE)) {
targetNode = static_cast<Node*>(eventData[P_NODE].GetPtr());
}
if (eventData.Contains(P_DISTANCE)) {
cameraDistance = eventData[P_DISTANCE].GetFloat();
}
if (players_.Contains(playerId)) {
players_[playerId]->SetCameraTarget(targetNode);
players_[playerId]->SetCameraDistance(cameraDistance);
}
}
bool Level::RaycastFromCamera(Camera* camera, float maxDistance, Vector3& hitPos, Vector3& hitNormal, Drawable*& hitDrawable) {
hitDrawable = nullptr;
UI* ui = GetSubsystem<UI>();
Input* input = GetSubsystem<Input>();
IntVector2 pos = ui->GetCursorPosition();
// Check the cursor is visible and there is no UI element in front of the cursor
if (input->IsMouseVisible() || ui->GetElementAt(pos, true))
return false;
Graphics* graphics = GetSubsystem<Graphics>();
Ray cameraRay = camera->GetScreenRay((float)pos.x_ / graphics->GetWidth(), (float)pos.y_ / graphics->GetHeight());
// Pick only geometry objects, not eg. zones or lights, only get the first (closest) hit
PODVector<RayQueryResult> results;
RayOctreeQuery query(results, cameraRay, RAY_TRIANGLE, maxDistance, DRAWABLE_GEOMETRY, VIEW_MASK_CHUNK);
scene_->GetComponent<Octree>()->RaycastSingle(query);
if (results.Size()) {
RayQueryResult& result = results[0];
hitPos = result.position_;
hitNormal = result.normal_;
hitDrawable = result.drawable_;
return true;
}
return false;
}
void Level::HandleMappedControlPressed(StringHash eventType, VariantMap& eventData)
{
using namespace MappedControlPressed;
int action = eventData[P_ACTION].GetInt();
if (action == CTRL_ACTION) {
int controllerId = eventData[P_CONTROLLER].GetInt();
if (cameras_.Contains(controllerId)) {
Camera* camera = cameras_[controllerId]->GetComponent<Camera>();
Vector3 hitPosition;
Vector3 hitNormal;
Drawable* hitDrawable;
bool hit = RaycastFromCamera(camera, 100.0f, hitPosition, hitNormal, hitDrawable);
if (hit) {
#ifdef VOXEL_SUPPORT
using namespace ChunkHit;
VariantMap& data = GetEventDataMap();
data[P_POSITION] = hitPosition - hitNormal * 0.5f;
data[P_DIRECTION] = hitNormal * 0.5f;
data[P_ORIGIN] = hitPosition + hitNormal * 0.5f;;
data[P_CONTROLLER_ID] = eventData[P_CONTROLLER];
data[P_ACTION_ID] = action;
hitDrawable->GetNode()->GetParent()->SendEvent(E_CHUNK_HIT, data);
#endif
}
}
} else if (action == CTRL_SECONDARY || action == CTRL_DETECT) {
int controllerId = eventData[P_CONTROLLER].GetInt();
if (cameras_.Contains(controllerId)) {
Camera* camera = cameras_[controllerId]->GetComponent<Camera>();
Vector3 hitPosition;
Vector3 hitNormal;
Drawable* hitDrawable;
bool hit = RaycastFromCamera(camera, 100.0f, hitPosition, hitNormal, hitDrawable);
if (hit) {
// URHO3D_LOGINFO("Hit target " + hitDrawable->GetNode()->GetName() + " Normal: " + hitNormal.ToString());
Vector3 playerPosition = players_[controllerId]->GetNode()->GetWorldPosition();
Vector3 blockPosition = hitPosition + hitNormal * 0.5f;
// URHO3D_LOGINFO("Player position " + playerPosition.ToString() + " block position " + blockPosition.ToString());
if (
Floor(blockPosition.x_) != Floor(playerPosition.x_) ||
Floor(blockPosition.y_) != Floor(playerPosition.y_) ||
Floor(blockPosition.z_) != Floor(playerPosition.z_)
) {
#ifdef VOXEL_SUPPORT
using namespace ChunkAdd;
VariantMap& data = GetEventDataMap();
data[P_POSITION] = blockPosition;
data[P_CONTROLLER_ID] = eventData[P_CONTROLLER];
data[P_ACTION_ID] = action;
data[P_ITEM_ID] = players_[controllerId]->GetSelectedItem();
hitDrawable->GetNode()->GetParent()->SendEvent(E_CHUNK_ADD, data);
#endif
} else {
URHO3D_LOGINFO("You cannot place a block where you stand");
}
}
}
}
}
| 34.269394 | 129 | 0.672881 | ArnisLielturks |
bffe6163d3fc4df1e4bc7294a2891169c9e7df93 | 3,844 | cpp | C++ | LibMathematics/Distance/Wm5DistPoint3Circle3.cpp | bazhenovc/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | 48 | 2015-10-07T07:26:14.000Z | 2022-03-18T14:30:07.000Z | LibMathematics/Distance/Wm5DistPoint3Circle3.cpp | zouxiaohang/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | null | null | null | LibMathematics/Distance/Wm5DistPoint3Circle3.cpp | zouxiaohang/WildMagic | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | [
"BSL-1.0"
] | 21 | 2015-09-01T03:14:47.000Z | 2022-01-04T04:07:46.000Z | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#include "Wm5MathematicsPCH.h"
#include "Wm5DistPoint3Circle3.h"
namespace Wm5
{
//----------------------------------------------------------------------------
template <typename Real>
DistPoint3Circle3<Real>::DistPoint3Circle3 (const Vector3<Real>& point,
const Circle3<Real>& circle)
:
mPoint(&point),
mCircle(&circle)
{
}
//----------------------------------------------------------------------------
template <typename Real>
const Vector3<Real>& DistPoint3Circle3<Real>::GetPoint () const
{
return *mPoint;
}
//----------------------------------------------------------------------------
template <typename Real>
const Circle3<Real>& DistPoint3Circle3<Real>::GetCircle () const
{
return *mCircle;
}
//----------------------------------------------------------------------------
template <typename Real>
Real DistPoint3Circle3<Real>::Get ()
{
return Math<Real>::Sqrt(GetSquared());
}
//----------------------------------------------------------------------------
template <typename Real>
Real DistPoint3Circle3<Real>::GetSquared ()
{
// Signed distance from point to plane of circle.
Vector3<Real> diff0 = *mPoint - mCircle->Center;
Real dist = diff0.Dot(mCircle->Normal);
// Projection of P-C onto plane is Q-C = P-C - (fDist)*N.
Vector3<Real> diff1 = diff0 - dist*mCircle->Normal;
Real sqrLen = diff1.SquaredLength();
Real sqrDistance;
if (sqrLen >= Math<Real>::ZERO_TOLERANCE)
{
mClosestPoint1 = mCircle->Center + (mCircle->Radius/
Math<Real>::Sqrt(sqrLen))*diff1;
Vector3<Real> diff2 = *mPoint - mClosestPoint1;
sqrDistance = diff2.SquaredLength();
}
else
{
mClosestPoint1 = Vector3<Real>(Math<Real>::MAX_REAL,
Math<Real>::MAX_REAL,Math<Real>::MAX_REAL);
sqrDistance = mCircle->Radius*mCircle->Radius + dist*dist;
}
mClosestPoint0 = *mPoint;
return sqrDistance;
}
//----------------------------------------------------------------------------
template <typename Real>
Real DistPoint3Circle3<Real>::Get (Real t,
const Vector3<Real>& velocity0, const Vector3<Real>& velocity1)
{
Vector3<Real> movedPoint = *mPoint + t*velocity0;
Vector3<Real> movedCenter = mCircle->Center + t*velocity1;
Circle3<Real> movedCircle(movedCenter, mCircle->Direction0,
mCircle->Direction1, mCircle->Normal, mCircle->Radius);
return DistPoint3Circle3<Real>(movedPoint, movedCircle).Get();
}
//----------------------------------------------------------------------------
template <typename Real>
Real DistPoint3Circle3<Real>::GetSquared (Real t,
const Vector3<Real>& velocity0, const Vector3<Real>& velocity1)
{
Vector3<Real> movedPoint = *mPoint + t*velocity0;
Vector3<Real> movedCenter = mCircle->Center + t*velocity1;
Circle3<Real> movedCircle(movedCenter, mCircle->Direction0,
mCircle->Direction1, mCircle->Normal, mCircle->Radius);
return DistPoint3Circle3<Real>(movedPoint, movedCircle).GetSquared();
}
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// Explicit instantiation.
//----------------------------------------------------------------------------
template WM5_MATHEMATICS_ITEM
class DistPoint3Circle3<float>;
template WM5_MATHEMATICS_ITEM
class DistPoint3Circle3<double>;
//----------------------------------------------------------------------------
}
| 36.264151 | 99 | 0.522893 | bazhenovc |
87005a66210187f6abe7412e2de6c68afc22ca6e | 2,515 | cpp | C++ | send-pin-with-camera/jni/natpmpclient.cpp | 0E800/android-keyboard-gadget | 43a1bdffc4054fe050bdc4c0a1f0244b4001ecdc | [
"Apache-2.0"
] | 1,029 | 2015-01-04T04:05:35.000Z | 2022-03-29T14:10:21.000Z | send-pin-with-camera/jni/natpmpclient.cpp | yauchungpo/android-keyboard-sss77147 | 3a4e88cf9a6b42b15b30dd79cc70a56284a08a64 | [
"Apache-2.0"
] | 167 | 2015-01-08T09:54:54.000Z | 2022-03-20T21:02:49.000Z | send-pin-with-camera/jni/natpmpclient.cpp | yauchungpo/android-keyboard-sss77147 | 3a4e88cf9a6b42b15b30dd79cc70a56284a08a64 | [
"Apache-2.0"
] | 303 | 2015-01-09T12:32:41.000Z | 2022-03-29T15:15:42.000Z | #include <string>
#include <sstream>
#include <sys/select.h>
#include "beginvision.h"
#include "libnatpmp/natpmp.h"
#define JNIDEFINE(fname) Java_teaonly_droideye_MainActivity_##fname
extern "C" {
JNIEXPORT jstring JNICALL JNIDEFINE(nativeQueryInternet)(JNIEnv* env, jclass clz);
};
jstring JNICALL JNIDEFINE(nativeQueryInternet)(JNIEnv* env, jclass clz) {
natpmp_t natpmp;
natpmpresp_t response;
std::string ipaddr;
uint16_t privatePort = 8080;
uint16_t publicPort = 7910;
uint32_t lifetime = 36000; // 10 hours
int protocol = NATPMP_PROTOCOL_TCP;
in_addr_t gateway = 0;
fd_set fds;
struct timeval timeout;
int ret;
std::string result = "";
// 1. init internal object
ret = initnatpmp(&natpmp, 0, gateway);
if (ret < 0) {
result = "error:gateway";
goto _done;
}
// 2. get internet public ip address
ret = sendpublicaddressrequest(&natpmp);
if ( ret != 2) {
result = "error:ipaddr";
goto _done;
}
FD_ZERO(&fds);
FD_SET(natpmp.s, &fds);
getnatpmprequesttimeout(&natpmp, &timeout);
ret = select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
if(ret < 0) {
result = "error:select";
goto _done;
}
ret = readnatpmpresponseorretry(&natpmp, &response);
if( ret == NATPMP_TRYAGAIN ) {
result = "error:timeout";
goto _done;
} else if ( ret < 0) {
result = "error:failed";
goto _done;
}
ipaddr = inet_ntoa(response.pnu.publicaddress.addr);
// 3. set extern port mapping
ret = sendnewportmappingrequest(&natpmp, protocol,
privatePort, publicPort,
lifetime);
FD_ZERO(&fds);
FD_SET(natpmp.s, &fds);
getnatpmprequesttimeout(&natpmp, &timeout);
ret = select(FD_SETSIZE, &fds, NULL, NULL, &timeout);
if(ret < 0) {
result = "error:select";
goto _done;
}
ret = readnatpmpresponseorretry(&natpmp, &response);
if( ret == NATPMP_TRYAGAIN ) {
result = "error:timeout";
goto _done;
} else if ( ret < 0) {
result = "error:failed";
goto _done;
}
privatePort = response.pnu.newportmapping.privateport;
publicPort = response.pnu.newportmapping.mappedpublicport;
{
std::stringstream stream;
stream << "http://" << ipaddr << ":" << publicPort;
result = stream.str();
}
_done:
return env->NewStringUTF(result.c_str());
}
| 27.043011 | 86 | 0.602783 | 0E800 |
8700fea54fdd4c670a5180b512386c0629880c6f | 9,038 | cpp | C++ | source/FFTOceanPatchGPUFrag.cpp | MihaiBairac/My-FFT-Ocean-Scattering-Sky | 288ff11795149d27d26e11ea506e0f36729fde5d | [
"MIT"
] | 1 | 2020-01-18T14:15:55.000Z | 2020-01-18T14:15:55.000Z | source/FFTOceanPatchGPUFrag.cpp | MihaiBairac/My-FFT-Ocean-Scattering-Sky | 288ff11795149d27d26e11ea506e0f36729fde5d | [
"MIT"
] | null | null | null | source/FFTOceanPatchGPUFrag.cpp | MihaiBairac/My-FFT-Ocean-Scattering-Sky | 288ff11795149d27d26e11ea506e0f36729fde5d | [
"MIT"
] | 1 | 2021-08-03T05:53:26.000Z | 2021-08-03T05:53:26.000Z | /* Author: BAIRAC MIHAI */
#include "FFTOceanPatchGPUFrag.h"
#include "CommonHeaders.h"
#include "GLConfig.h"
// glm::vec2, glm::vec3 come from the header
#include "glm/common.hpp" //abs()
#include "glm/exponential.hpp" //sqrt()
#include "glm/gtc/constants.hpp" //pi(), two_pi()
#include "glm/vector_relational.hpp" //any(), notEqual()
#include "FileUtils.h"
#include "GlobalConfig.h"
#include "FFTNormalGradientFoldingBase.h"
#include <time.h>
FFTOceanPatchGPUFrag::FFTOceanPatchGPUFrag ( void )
: m_FFTInitDataTexId(0), m_pFFTDisplaymentData(nullptr)
{
LOG("FFTOceanPatchGPUFrag successfully created!");
}
FFTOceanPatchGPUFrag::FFTOceanPatchGPUFrag ( const GlobalConfig& i_Config )
: m_FFTInitDataTexId(0), m_pFFTDisplaymentData(nullptr)
{
Initialize(i_Config);
}
FFTOceanPatchGPUFrag::~FFTOceanPatchGPUFrag ( void )
{
Destroy();
}
void FFTOceanPatchGPUFrag::Destroy ( void )
{
// should free resources
SAFE_ARRAY_DELETE(m_pFFTDisplaymentData);
LOG("FFTOceanPatchGPUFrag successfully destroyed!");
}
void FFTOceanPatchGPUFrag::Initialize ( const GlobalConfig& i_Config )
{
FFTOceanPatchBase::Initialize(i_Config);
///////////////
m_2DIFFT.Initialize(i_Config);
////////// Initialize FFT Data /////////
m_FFTInitData.resize(m_FFTSize * m_FFTSize);
InitFFTData();
//// Create H0Omega texture
m_FFTTM.Initialize("FFTOceanPatchGPUFrag", i_Config);
m_FFTInitDataTexId = m_FFTTM.Create2DTexture(GL_RGB16F, GL_RGB, GL_FLOAT, m_FFTSize, m_FFTSize, GL_REPEAT, GL_NEAREST, &m_FFTInitData[0], i_Config.TexUnit.Ocean.FFTOceanPatchGPUFrag.FFTInitDataMap);
m_pFFTDisplaymentData = new float[m_FFTSize * m_FFTSize * 4 * sizeof(float)];
assert(m_pFFTDisplaymentData != nullptr);
///////////// FFT Ht SETUP ///////////
m_FFTHtSM.Initialize("FFTOceanPatchGPUFrag");
if (m_2DIFFT.GetUseFFTSlopes())
{
m_FFTHtSM.BuildRenderingProgram("resources/shaders/Quad.vert.glsl", "resources/shaders/FFTHt.frag.glsl", i_Config);
}
else
{
m_FFTHtSM.BuildRenderingProgram("resources/shaders/Quad.vert.glsl", "resources/shaders/FFTHt_NoFFTSlopes.frag.glsl", i_Config);
}
m_FFTHtSM.UseProgram();
std::map<MeshBufferManager::VERTEX_ATTRIBUTE_TYPE, int> fftHtAttributes;
fftHtAttributes[MeshBufferManager::VERTEX_ATTRIBUTE_TYPE::VAT_POSITION] = m_FFTHtSM.GetAttributeLocation("a_position");
fftHtAttributes[MeshBufferManager::VERTEX_ATTRIBUTE_TYPE::VAT_UV] = m_FFTHtSM.GetAttributeLocation("a_uv");
m_FFTHtUniforms["u_FFTSize"] = m_FFTHtSM.GetUniformLocation("u_FFTSize");
m_FFTHtSM.SetUniform(m_FFTHtUniforms.find("u_FFTSize")->second, static_cast<float>(m_FFTSize));
m_FFTHtUniforms["u_FFTInitDataMap"] = m_FFTHtSM.GetUniformLocation("u_FFTInitDataMap");
m_FFTHtSM.SetUniform(m_FFTHtUniforms.find("u_FFTInitDataMap")->second, i_Config.TexUnit.Ocean.FFTOceanPatchGPUFrag.FFTInitDataMap);
m_FFTHtUniforms["u_PatchSize"] = m_FFTHtSM.GetUniformLocation("u_PatchSize");
m_FFTHtSM.SetUniform(m_FFTHtUniforms.find("u_PatchSize")->second, static_cast<float>(m_PatchSize));
m_FFTHtUniforms["u_Time"] = m_FFTHtSM.GetUniformLocation("u_Time");
m_FFTHtSM.SetupFragmentOutputStreams(m_2DIFFT.GetFFTLayerCount(), 0);
m_FFTHtSM.UnUseProgram();
////////
m_FFTHtFBM.Initialize("FFTHt FrameBuffer", i_Config);
m_FFTHtFBM.CreateLayered(fftHtAttributes, m_2DIFFT.GetSourceTexId(), m_2DIFFT.GetFFTLayerCount());
m_FFTHtFBM.Bind();
m_FFTHtFBM.SetupDrawBuffers(m_2DIFFT.GetFFTLayerCount(), 0);
m_FFTHtFBM.UnBind();
/////////// NORMAL, FOLDING SETUP ///////////
if (i_Config.Scene.Ocean.Surface.OceanPatch.NormalGradientFolding.Type == CustomTypes::Ocean::NormalGradientFoldingType::NGF_GPU_FRAG)
{
if (m_pNormalGradientFolding)
{
m_pNormalGradientFolding->LinkSourceTex(m_2DIFFT.GetDestinationTexUnitId());
}
}
else if (i_Config.Scene.Ocean.Surface.OceanPatch.NormalGradientFolding.Type == CustomTypes::Ocean::NormalGradientFoldingType::NGF_GPU_COMP)
{
if (m_pNormalGradientFolding)
{
m_pNormalGradientFolding->LinkSourceTex(m_2DIFFT.GetDestinationTexId());
}
}
LOG("FFTOceanPatchGPUFrag successfully created!");
}
void FFTOceanPatchGPUFrag::SetFFTData ( void )
{
InitFFTData();
m_FFTTM.Update2DTextureData(m_FFTInitDataTexId, &m_FFTInitData[0]);
}
void FFTOceanPatchGPUFrag::InitFFTData ( void )
{
srand(0);
glm::vec2 waveVector(0.0f);
float fPatchSize = static_cast<float>(m_PatchSize);
float min = glm::pi<float>() / m_PatchSize;
for (unsigned short i = 0; i < m_FFTSize; ++ i)
{
waveVector.y = glm::pi<float>() * (2.0f * i - m_FFTSize) / fPatchSize;
for (unsigned short j = 0; j < m_FFTSize; ++ j)
{
waveVector.x = glm::pi<float>() * (2.0f * j - m_FFTSize) / fPatchSize;
unsigned int index = i * m_FFTSize + j;
if (glm::abs(waveVector.x) < min && glm::abs(waveVector.y) < min)
{
m_FFTInitData[index].x = 0.0f;
m_FFTInitData[index].y = 0.0f;
m_FFTInitData[index].z = 0.0f;
}
else
{
float specFactor = 1.0f;
switch (m_SpectrumType)
{
case CustomTypes::Ocean::SpectrumType::ST_PHILLIPS:
specFactor = glm::sqrt(PhillipsSpectrum(waveVector) / 2.0f);
break;
case CustomTypes::Ocean::SpectrumType::ST_UNIFIED:
specFactor = glm::sqrt(UnifiedSpectrum(waveVector) / 2.0f) * glm::two_pi<float>() / m_PatchSize;
break;
case CustomTypes::Ocean::SpectrumType::ST_COUNT:
default: ERR("Invalid ocean spectrum type!");
}
glm::vec2 hTilde0 = GaussianRandomVariable() * specFactor;
m_FFTInitData[index].x = hTilde0.x;
m_FFTInitData[index].y = hTilde0.y;
m_FFTInitData[index].z = DispersionFrequency(waveVector);
}
}
}
}
void FFTOceanPatchGPUFrag::EvaluateWaves ( float i_CrrTime )
{
/////// UPDATE HEIGHTMAP
glm::ivec4 oldViewport;
glm::ivec4 newViewport(0, 0, m_FFTSize, m_FFTSize);
// save current viewport
glGetIntegerv(GL_VIEWPORT, &oldViewport[0]);
if (glm::any(glm::notEqual(newViewport, oldViewport)))
{
glViewport(newViewport.x, newViewport.y, newViewport.z, newViewport.w);
}
m_FFTHtFBM.Bind();
//// UPDATE FFT Ht
m_FFTHtSM.UseProgram();
m_FFTHtSM.SetUniform(m_FFTHtUniforms.find("u_Time")->second, i_CrrTime);
m_FFTHtFBM.RenderToQuad();
//// PERFORM 2D Inverse FFT
m_2DIFFT.Perform2DIFFT();
/////
FFTOceanPatchBase::EvaluateWaves(i_CrrTime);
// restore viewport
if (glm::any(glm::notEqual(newViewport, oldViewport)))
{
glViewport(oldViewport.x, oldViewport.y, oldViewport.z, oldViewport.w);
}
}
float FFTOceanPatchGPUFrag::ComputeWaterHeightAt ( const glm::vec2& i_XZ ) const
{
float waterHeight = 0.0f;
if (m_pFFTDisplaymentData)
{
//// obtain the height data from the FFT texture (displacement is available at layer 0)
m_2DIFFT.BindDestinationTexture();
glGetTexImage(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, GL_FLOAT, m_pFFTDisplaymentData);
//// compute the water height by interploating the nearest 4 neighbors from the FFT displayament texture at the given (x, z) data space position
// Convert coords from world-space to data-space
int x = static_cast<int>(i_XZ.x) % m_FFTSize,
z = static_cast<int>(i_XZ.y) % m_FFTSize;
// If data-space coords are negative, transform it to positive
if (i_XZ.x < 0.0f) x += (m_FFTSize - 1);
if (i_XZ.y < 0.0f) z += (m_FFTSize - 1);
// Adjust the index if coords are out of range
int xx = (x == m_FFTSize - 1) ? -1 : x,
zz = (z == m_FFTSize - 1) ? -1 : z;
// the data we get from FFT data texture is an array of floats groups as xyzw values (4 floats)
const int k_stride = 4;
const int k_yOffset = 1; // y - has offset 1, because x offset = 0, z offset = 2, w offset = 3
// Determine x and y diff for linear interpolation
int xINT = (i_XZ.x > 0.0f) ? static_cast<int>(i_XZ.x) : static_cast<int>(i_XZ.x - 1.0f),
zINT = (i_XZ.y > 0.0f) ? static_cast<int>(i_XZ.y) : static_cast<int>(i_XZ.y - 1.0f);
// Calculate interpolation coefficients
float xDIFF = i_XZ.x - xINT,
zDIFF = i_XZ.y - zINT,
_xDIFF = 1.0f - xDIFF,
_zDIFF = 1.0f - zDIFF;
// A B
//
//
// C D
//interpolate among 4 adjacent neighbors
unsigned int indexA = k_stride * (z * m_FFTSize + x) + k_yOffset,
indexB = k_stride * (z * m_FFTSize + (xx + 1)) + k_yOffset,
indexC = k_stride * ((zz + 1) * m_FFTSize + x) + k_yOffset,
indexD = k_stride * ((zz + 1) * m_FFTSize + (xx + 1)) + k_yOffset;
waterHeight = m_pFFTDisplaymentData[indexA] * _xDIFF *_zDIFF + m_pFFTDisplaymentData[indexB] * xDIFF *_zDIFF + m_pFFTDisplaymentData[indexC] * _xDIFF * zDIFF + m_pFFTDisplaymentData[indexD] * xDIFF * zDIFF;
}
return waterHeight;
}
void FFTOceanPatchGPUFrag::BindFFTWaveDataTexture ( void ) const
{
m_2DIFFT.BindDestinationTexture();
}
unsigned short FFTOceanPatchGPUFrag::GetFFTWaveDataTexUnitId ( void ) const
{
return m_2DIFFT.GetDestinationTexUnitId();
} | 33.227941 | 209 | 0.700155 | MihaiBairac |
8706f027a47b2f8b66e0fe90e86848c818d53176 | 1,915 | hpp | C++ | lib/builder/LBVH_CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 4 | 2019-03-09T16:35:00.000Z | 2022-01-12T06:32:05.000Z | lib/builder/LBVH_CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | null | null | null | lib/builder/LBVH_CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 1 | 2020-09-09T15:47:13.000Z | 2020-09-09T15:47:13.000Z | /*
* Copyright (C) 2018 Daniel Mensinger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "base/BVH.hpp"
using BVHTest::base::AABB;
using BVHTest::base::CUDAMemoryBVHPointer;
using BVHTest::base::MeshRaw;
using BVHTest::base::Triangle;
using glm::vec3;
struct LBVH_TriData {
AABB bbox;
vec3 centroid;
uint32_t faceIndex;
uint64_t __padding__;
};
struct LBVH_WorkingMemory {
bool lRes = false;
uint32_t * mortonCodes = nullptr;
uint32_t * mortonCodesSorted = nullptr;
LBVH_TriData *triData = nullptr;
LBVH_TriData *triDataSorted = nullptr;
void * cubTempStorage = nullptr;
uint32_t * atomicLocks = nullptr;
uint32_t numFaces = 0;
size_t cubTempStorageSize = 0;
uint32_t numLocks = 0;
};
AABB LBVH_initTriData(LBVH_WorkingMemory *_mem, MeshRaw *_rawMesh);
void LBVH_calcMortonCodes(LBVH_WorkingMemory *_mem, AABB _sceneAABB);
void LBVH_sortMortonCodes(LBVH_WorkingMemory *_mem);
void LBVH_buildBVHTree(LBVH_WorkingMemory *_mem, CUDAMemoryBVHPointer *_bvh);
void LBVH_fixAABB(LBVH_WorkingMemory *_mem, CUDAMemoryBVHPointer *_bvh);
bool LBVH_allocateBVH(CUDAMemoryBVHPointer *_bvh, MeshRaw *_rawMesh);
LBVH_WorkingMemory LBVH_allocateWorkingMemory(MeshRaw *_rawMesh);
void LBVH_freeWorkingMemory(LBVH_WorkingMemory *_mem);
void LBVH_doCUDASyc();
| 31.916667 | 83 | 0.73107 | mensinda |
87091b24e23cbddfe2c4776dd8a7e8aeec2ca0a0 | 1,307 | cpp | C++ | test/type_traits/iterator_category.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | test/type_traits/iterator_category.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | test/type_traits/iterator_category.cpp | pmiddend/fcppt | 9f437acbb10258e6df6982a550213a05815eb2be | [
"BSL-1.0"
] | null | null | null | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/type_traits/is_iterator_of_category.hpp>
#include <fcppt/config/external_begin.hpp>
#include <iterator>
#include <list>
#include <fcppt/config/external_end.hpp>
int
main()
{
static_assert(
fcppt::type_traits::is_iterator_of_category<
int *,
std::input_iterator_tag
>::value,
""
);
static_assert(
fcppt::type_traits::is_iterator_of_category<
int *,
std::random_access_iterator_tag
>::value,
""
);
static_assert(
!fcppt::type_traits::is_iterator_of_category<
std::list<
int
>::const_iterator,
std::random_access_iterator_tag
>::value,
""
);
static_assert(
fcppt::type_traits::is_iterator_of_category<
std::list<
int
>::const_iterator,
std::bidirectional_iterator_tag
>::value,
""
);
static_assert(
fcppt::type_traits::is_iterator_of_category<
std::list<
int
>::const_iterator,
std::forward_iterator_tag
>::value,
""
);
static_assert(
fcppt::type_traits::is_iterator_of_category<
std::ostream_iterator<
int
>,
std::output_iterator_tag
>::value,
""
);
}
| 17.90411 | 61 | 0.684009 | pmiddend |
870f7318138ad908ed531f1eaf83eabff5c80dd4 | 1,736 | cpp | C++ | test/subset_inversion_test.cpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | 15 | 2017-03-26T03:54:16.000Z | 2021-04-04T13:10:43.000Z | test/subset_inversion_test.cpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | null | null | null | test/subset_inversion_test.cpp | georeth/OJLIBS | de59d4fd21255cc2f0a580db7726b634449e6885 | [
"MIT"
] | 1 | 2018-03-06T09:59:14.000Z | 2018-03-06T09:59:14.000Z | #include <gtest/gtest.h>
#include <ojlibs/subset_inversion.hpp>
#include <ojlibs/binary_operator.hpp>
#include <vector>
#include <random>
using namespace std;
using uni = std::uniform_int_distribution<>;
using Op = ojlibs::modular_plus<int, 1000000007>;
std::mt19937 gen;
Op op;
TEST(RANDOM, subset) {
static const int TEST_GROUP = 100;
static const int K = 10;
static const int M = 1 << K;
for (int i = 0; i < TEST_GROUP; ++i) {
vector<int> f(M);
for (int x = 0; x < M; ++x)
f[x] = uni(0, 1000)(gen);
vector<int> g = ojlibs::subset_transform(f, K, Op());
vector<int> gg(M);
for (int x = 0; x < M; ++x)
for (int y = 0; y < M; ++y) if ((y & x) == y)
gg[x] = op(gg[x], f[y]);
ASSERT_EQ(g, gg);
vector<int> ff = ojlibs::subset_inverse(g, K, Op());
ASSERT_EQ(f, ff);
int x = uni(0, M - 1)(gen);
EXPECT_EQ(f[x], ojlibs::subset_inverse_single(g, K, x, Op()));
}
}
TEST(RANDOM, superset) {
static const int TEST_GROUP = 100;
static const int K = 10;
static const int M = 1 << K;
for (int i = 0; i < TEST_GROUP; ++i) {
vector<int> f(M);
for (int x = 0; x < M; ++x)
f[x] = uni(0, 1000)(gen);
vector<int> g = ojlibs::superset_transform(f, K, Op());
vector<int> gg(M);
for (int x = 0; x < M; ++x)
for (int y = 0; y < M; ++y) if ((y & x) == x)
gg[x] = op(gg[x], f[y]);
ASSERT_EQ(g, gg);
vector<int> ff = ojlibs::superset_inverse(g, K, Op());
ASSERT_EQ(f, ff);
int x = uni(0, M - 1)(gen);
EXPECT_EQ(f[x], ojlibs::superset_inverse_single(g, K, x, Op()));
}
}
| 28 | 72 | 0.510369 | georeth |
870fbbe8a4d823fcd36f3a66cba6f8d8cc0a22b5 | 1,296 | cpp | C++ | high-five.cpp | shirishbahirat/code_examples | ebc8bb743b7b0a4ad1e01164cd85afc0bfe7f107 | [
"MIT"
] | null | null | null | high-five.cpp | shirishbahirat/code_examples | ebc8bb743b7b0a4ad1e01164cd85afc0bfe7f107 | [
"MIT"
] | null | null | null | high-five.cpp | shirishbahirat/code_examples | ebc8bb743b7b0a4ad1e01164cd85afc0bfe7f107 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<int>> highFive(vector<vector<int>> &items) {
vector<int> student_id(1000, 0);
vector<int> student_marks(1000, 0);
vector<int> subject_index(1000, 0);
vector<int> minimum_marks(1000, 0xFFFF);
for (vector<vector<int>>::iterator it = items.begin(); it != items.end();
++it) {
vector<int> marks = *it;
if (minimum_marks.at(marks[0]) > marks[1]) {
minimum_marks.at(marks[0]) = marks[1];
cout << "Minimum " << minimum_marks[marks[0]] << endl;
}
subject_index[marks[0]]++;
student_marks[marks[0]] += marks[1];
cout << student_marks[marks[0]] << endl;
if (subject_index[marks[0]] > 5) {
student_marks[marks[0]] -= minimum_marks[marks[0]];
}
}
for (int i = 0; i < 1000; ++i) {
student_marks[i] /= 5;
cout << student_marks[i] << " ";
}
return items;
}
};
int main(int argc, char const *argv[]) {
Solution *sln = new Solution();
vector<vector<int>> items{{1, 91}, {1, 92}, {2, 93}, {2, 97},
{1, 60}, {2, 77}, {1, 65}, {1, 87},
{1, 100}, {2, 100}, {2, 76}};
sln->highFive(items);
return 0;
}
| 23.142857 | 77 | 0.531636 | shirishbahirat |
870fdf487c2d929567df6fc17c176d914b17ff11 | 1,478 | hpp | C++ | mpllibs/metamonad/v1/metafunction.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 70 | 2015-01-15T09:05:15.000Z | 2021-12-08T15:49:31.000Z | mpllibs/metamonad/v1/metafunction.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 4 | 2015-06-18T19:25:34.000Z | 2016-05-13T19:49:51.000Z | mpllibs/metamonad/v1/metafunction.hpp | sabel83/mpllibs | 8e245aedcf658fe77bb29537aeba1d4e1a619a19 | [
"BSL-1.0"
] | 5 | 2015-07-10T08:18:09.000Z | 2021-12-01T07:17:57.000Z | #ifndef MPLLIBS_METAMONAD_V1_METAFUNCTION_HPP
#define MPLLIBS_METAMONAD_V1_METAFUNCTION_HPP
// Copyright Abel Sinkovics (abel@sinkovics.hu) 2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <mpllibs/metamonad/v1/impl/metafunction_body.hpp>
#include <mpllibs/metamonad/v1/impl/expand_arg_usage.hpp>
#include <mpllibs/metamonad/v1/impl/expand_arg_usage_with_na.hpp>
#include <mpllibs/metamonad/v1/impl/curried_call.hpp>
#include <mpllibs/metamonad/v1/tmp_value.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/seq/enum.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/size.hpp>
#ifdef MPLLIBS_V1_METAFUNCTION
# error MPLLIBS_V1_METAFUNCTION already defined
#endif
#define MPLLIBS_V1_METAFUNCTION(name, args) \
template <BOOST_PP_SEQ_FOR_EACH_I(MPLLIBS_V1_EXPAND_ARG_USAGE, ~, args)> \
struct BOOST_PP_CAT(name, ___impl); \
\
template < \
BOOST_PP_SEQ_FOR_EACH_I(MPLLIBS_V1_EXPAND_ARG_USAGE_WITH_NA, ~, args) \
> \
struct name : \
BOOST_PP_CAT( \
mpllibs::metamonad::v1::impl::curried_call, \
BOOST_PP_SEQ_SIZE(args) \
)<BOOST_PP_CAT(name, ___impl), BOOST_PP_SEQ_ENUM(args)> \
{}; \
\
template <BOOST_PP_SEQ_FOR_EACH_I(MPLLIBS_V1_EXPAND_ARG_USAGE, ~, args)> \
struct BOOST_PP_CAT(name, ___impl) : MPLLIBS_V1_METAFUNCTION_BODY
#endif
| 35.190476 | 76 | 0.76793 | sabel83 |
871774f6bd347001fda18c84b11a9fef81985ba0 | 786 | cpp | C++ | 3404/6786626_AC_0MS_136K.cpp | vandreas19/POJ_sol | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 18 | 2017-08-14T07:34:42.000Z | 2022-01-29T14:20:29.000Z | 3404/6786626_AC_0MS_136K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | null | null | null | 3404/6786626_AC_0MS_136K.cpp | pinepara/poj_solutions | 4895764ab800e8c2c4b2334a562dec2f07fa243e | [
"MIT"
] | 14 | 2016-12-21T23:37:22.000Z | 2021-07-24T09:38:57.000Z | #include<cstdio>
#include<algorithm>
int main(){
int travelerNum;
scanf("%d",&travelerNum);
int *timeCosts=new int[travelerNum];
for(int index=0;index<travelerNum;index++)
scanf("%d",timeCosts+index);
std::sort(timeCosts,timeCosts+travelerNum);
int timeSum=0;
while(travelerNum>=4){
int timePlanA=timeCosts[0]+2*timeCosts[1]+timeCosts[travelerNum-1];
int timePlanB=2*timeCosts[0]+timeCosts[travelerNum-2]+timeCosts[travelerNum-1];
timeSum+=std::min(timePlanA,timePlanB);
travelerNum-=2;
}
if(travelerNum==3)
timeSum+=timeCosts[0]+timeCosts[1]+timeCosts[2];
else if(travelerNum==2)
timeSum+=std::max(timeCosts[0],timeCosts[1]);
else if(travelerNum==1)
timeSum+=timeCosts[0];
printf("%d\n",timeSum);
delete[] timeCosts;
return 0;
} | 29.111111 | 82 | 0.698473 | vandreas19 |
26b9351b3386e7111a003a61752d12affa9679c1 | 3,954 | cpp | C++ | examples/week5/GLSLPhong/src/GLSLPhongApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | 8 | 2015-02-23T22:10:08.000Z | 2021-02-27T16:07:39.000Z | examples/week5/GLSLPhong/src/GLSLPhongApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | null | null | null | examples/week5/GLSLPhong/src/GLSLPhongApp.cpp | Hebali/AOGP | 4840e009994b77ee23a913dc0d7bae373294936b | [
"BSD-3-Clause"
] | 3 | 2016-09-26T08:15:19.000Z | 2018-04-01T06:57:55.000Z | //////////////////////////////////////////////////
/* Art of Graphics Programming */
/* Taught by Patrick Hebron */
/* Interactive Telecommunications Program (ITP) */
/* New York University */
/* Fall 2014 */
//////////////////////////////////////////////////
#include "cinder/app/AppNative.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/GlslProg.h"
#include "cinder/Camera.h"
using namespace ci;
using namespace ci::app;
using namespace std;
#define STRINGIFY(x) #x
// See:
// http://stackoverflow.com/questions/15588860/what-exactly-are-eye-space-coordinates
// https://www.opengl.org/sdk/docs/tutorials/ClockworkCoders/lighting.php
// http://en.wikibooks.org/wiki/GLSL_Programming/GLUT/Multiple_Lights
static const string kVertGlsl =
STRINGIFY(
varying vec3 vVertex;
varying vec3 vNormal;
void main(void)
{
// In camera-space:
// Get vertex position:
vVertex = vec3( gl_ModelViewMatrix * gl_Vertex );
// Get vertex normal:
vNormal = normalize( gl_NormalMatrix * gl_Normal );
// Set vertex position:
gl_Position = ftransform();
}
);
static const string kFragGlsl =
STRINGIFY(
uniform vec3 mLightPosition;
uniform vec4 mAmbient;
uniform vec4 mDiffuse;
uniform vec4 mSpecular;
uniform float mShininess;
varying vec3 vVertex;
varying vec3 vNormal;
void main (void)
{
// In camera-space:
// Convert light position from world-space to camera-space:
vec4 tLightCamSpace = gl_ModelViewMatrix * vec4( mLightPosition, 1.0 );
// Compute light direction:
vec3 tLightDir = normalize( tLightCamSpace.xyz - vVertex );
// Compute camera vector:
vec3 tCamVec = normalize( -vVertex );
// Compute reflection direction for light vector:
vec3 tRefDir = normalize( -reflect( tLightDir, vNormal ) );
// Compute diffuse color:
vec4 tDiff = clamp( mDiffuse * max( dot( vNormal, tLightDir ), 0.0 ), 0.0, 1.0 );
// Compute specular color:
vec4 tSpec = clamp( mSpecular * pow( max( dot( tRefDir, tCamVec ), 0.0 ), 0.3 * mShininess ), 0.0, 1.0 );
// Compute final color:
gl_FragColor = mAmbient + tDiff + tSpec;
}
);
class GLSLPhongApp : public AppNative {
public:
void setup();
void mouseDown(MouseEvent event);
void update();
void draw();
void resize();
CameraPersp mCam;
gl::GlslProg mShader;
};
void GLSLPhongApp::setup()
{
// Enable alpha blending:
gl::enableAlphaBlending();
// Enable depth buffer read/write:
gl::enableDepthRead();
gl::enableDepthWrite();
// Load shader from strings (using the stringify macro):
mShader = gl::GlslProg( kVertGlsl.c_str(), kFragGlsl.c_str() );
}
void GLSLPhongApp::mouseDown(MouseEvent event)
{
}
void GLSLPhongApp::update()
{
}
void GLSLPhongApp::draw()
{
// Clear window:
gl::clear( Color( 0, 0, 0 ) );
// Set matrix from camera:
gl::setMatrices( mCam );
// Set color:
gl::color( 1.0, 1.0, 1.0 );
// Set light position (in world-space):
Vec3f tLightPos = Vec3f( 5.0*cos(getElapsedSeconds()), 0.0, 5.0*sin(getElapsedSeconds()) );
// Bind shader:
mShader.bind();
// Set shader uniform parameters:
mShader.uniform( "mLightPosition", tLightPos );
mShader.uniform( "mAmbient", ColorA( 0.1, 0.1, 0.1, 1.0 ) );
mShader.uniform( "mDiffuse", ColorA( 0.2, 0.8, 0.4, 1.0 ) );
mShader.uniform( "mSpecular", ColorA( 0.1, 0.4, 0.2, 1.0 ) );
mShader.uniform( "mShininess", 128.0f );
// Draw sphere:
gl::drawSphere( Vec3f::zero(), 1.0, 50 );
// Unbind shader:
mShader.unbind();
// Draw light position (as a small sphere):
gl::drawSphere( tLightPos, 0.1 );
}
void GLSLPhongApp::resize()
{
// Setup camera:
mCam.setPerspective( 60, getWindowAspectRatio(), 1, 1000 );
mCam.lookAt( Vec3f( 0.0, 0.0, 10.0 ), Vec3f::zero() );
}
CINDER_APP_NATIVE( GLSLPhongApp, RendererGl )
| 26.36 | 110 | 0.62873 | Hebali |
26bd32bdab133bd17bb7a0888932aab35da1a477 | 11,242 | hpp | C++ | mtvmtl/core/tvmin_prpt.hpp | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | 3 | 2017-05-08T12:40:46.000Z | 2019-06-02T05:11:01.000Z | mtvmtl/core/tvmin_prpt.hpp | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | null | null | null | mtvmtl/core/tvmin_prpt.hpp | pdebus/MTVMTL | 65a7754b34d1f6a1e86d15e3c2d4346b9418414f | [
"MIT"
] | null | null | null | #ifndef TVMTL_TVMINIMIZER_PRPT_HPP
#define TVMTL_TVMINIMIZER_PRPT_HPP
//System includes
#include <iostream>
#include <map>
#include <vector>
#include <chrono>
#ifdef TVMTL_TVMIN_DEBUG
#include <string>
#endif
//Eigen includes
#include <Eigen/Sparse>
#include <Eigen/Core>
#include <unsupported/Eigen/Splines>
//CGAL includes For linear Interpolation
#include <CGAL/Exact_predicates_inexact_constructions_kernel.h>
#include <CGAL/Delaunay_triangulation_2.h>
#include <CGAL/Interpolation_traits_2.h>
#include <CGAL/natural_neighbor_coordinates_2.h>
#include <CGAL/interpolation_functions.h>
//vpp includes
#include <vpp/vpp.hh>
namespace tvmtl {
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
class TV_Minimizer< PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR > {
public:
// Manifold typedefs
typedef typename MANIFOLD::scalar_type scalar_type;
typedef typename MANIFOLD::value_type value_type;
// Functional typedefs
typedef typename FUNCTIONAL::weights_mat weights_mat;
typedef typename FUNCTIONAL::weights_type weights_type;
// Data acccess typedefs
typedef vpp::box_nbh2d<value_type,3,3> nbh_type;
typedef typename DATA::storage_type img_type;
// Constructor
TV_Minimizer(FUNCTIONAL& func, DATA& dat):
func_(func),
data_(dat)
{
static_assert(FUNCTIONAL::disc_type == ANISO, "Proximal point is only possible with anisotropic weights!");
for(int i = 0; i < 5; i++){
proximal_mappings_[i] = img_type(data_.img_.domain());
}
use_approximate_mean_ = false;
max_prpt_steps_ = 50;
tolerance_ = 1e-4;
max_runtime_ = 1000.0;
}
void use_approximate_mean(bool u) { use_approximate_mean_ = u; }
void first_guess();
void updateFidelity(double muk);
void updateTV(double muk, int dim, const weights_mat& W);
void geod_mean();
void approx_mean();
void prpt_step(double muk);
void minimize();
void setMax_runtime(int t) { max_runtime_ = t; }
void setMax_prpt_steps(int n) { max_prpt_steps_ = n; }
void setTolerance(double t) {tolerance_ =t; }
int max_runtime(int t) const { return max_runtime_; }
int max_prpt_steps(int n) const { return max_prpt_steps_; }
int tolerance(double t) const { return tolerance_; }
private:
FUNCTIONAL& func_;
DATA& data_;
img_type proximal_mappings_[5];
bool use_approximate_mean_;
int prpt_step_;
int max_prpt_steps_;
double tolerance_;
double max_runtime_;
std::vector< std::chrono::duration<double> > Ts_;
std::vector< typename FUNCTIONAL::result_type > Js_;
};
/*----- IMPLEMENTATION PRPT------*/
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::updateFidelity(double muk){
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t Fidelity Update with muk: " << muk << std::endl;
func_.output_img(data_.img_, "prptImg.csv");
func_.output_img(data_.noise_img_,"prptNoiseImg.csv");
func_.output_img(proximal_mappings_[0],"prptProxMap.csv");
#endif
double tau = muk / (muk + 1.0);
if(data_.doInpaint()){
auto proximal_mapF = [&] (value_type& p, const value_type& i, const value_type& n, const bool inp ) {
value_type temp;
MANIFOLD::convex_combination(i, n, tau, temp);
p = temp * (1-inp) + i * inp;
};
vpp::pixel_wise(proximal_mappings_[0], data_.img_, data_.noise_img_, data_.inp_) | proximal_mapF;
}
else{
auto proximal_mapF = [&] (value_type& p, const value_type& i, const value_type& n) {
MANIFOLD::convex_combination(i, n, tau, p);
};
vpp::pixel_wise(proximal_mappings_[0], data_.img_, data_.noise_img_) | proximal_mapF;
}
}
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::updateTV(double muk, int dim, const weights_mat& W){
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t TV Update with muk: " << muk << std::endl;
std::cout << "\t\t... Dimension: " << dim << std::endl;
#endif
double lmuk = muk * func_.getlambda();
weights_mat tau = vpp::pixel_wise(W) | [&] (const weights_type& w) {return std::min(lmuk * w, 0.5); };
// 2D
int nr = data_.img_.nrows();
int nc = data_.img_.ncols();
// Dimensions of slice
vpp::vint2 dims(nr, nc); dims(dim) = 2; // y-dim = 0, x-dim = 1
vpp::vint2 loopdims(nr, nc); loopdims(dim) = 1; // y-dim = 0, x-dim = 1
//vpp::vint3 b(nz, ny, nx); dims(dim) =2;
// Relative neighbor coordinates
vpp::vint2 n(0,0); n(dim) = 1;
// Correct Subimage
vpp::box2d subimage = data_.img_.domain();
if(dim == 0 && (nr % 2 != 0)) // dim = y
subimage = vpp::box2d(vpp::vint2(0,0), vpp::vint2(nr-2, nc-1)); // subdomain without last row
if(dim == 1 && (nc % 2 != 0)) // dim =x
subimage = vpp::box2d(vpp::vint2(0,0), vpp::vint2(nr-1, nc-2)); // subdomain without last columns
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t\t...Odd Pairs..., dims = (" << dims(0) << "," << dims(1) << "), n = (" << n(0) << "," << n(1) << ")" <<std::endl;
int num_blocks = 0;
#endif
auto blockwise_proximal_map = [&] (const auto I, const auto T, auto P) {
for(int r = 0; r < loopdims(0); ++r ){
for(int c = 0; c < loopdims(1); ++c){
#ifdef TVMTL_TVMIN_DEBUG_VERBOSE
std::cout << "\t\t\tBlock: " << num_blocks << ", Row: " << r << ", Col: " << c << std::endl;
#endif
value_type l;
MANIFOLD::log(I(r,c), I(vpp::vint2(r,c) + n), l);
MANIFOLD::exp(I(r,c), l * T(r,c), P(r,c));
MANIFOLD::exp(I(r,c), l - l * T(r,c), P(vpp::vint2(r,c) + n));
}
}
#ifdef TVMTL_TVMIN_DEBUG
num_blocks++;
#endif
};
proximal_mappings_[1 + 2 * dim] = vpp::clone(data_.img_);
vpp::block_wise(dims, data_.img_ | subimage, tau | subimage, proximal_mappings_[1 + 2 * dim] | subimage) | blockwise_proximal_map;
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t\tBlock processed: " << num_blocks << std::endl;
#endif
if(dim == 0 /* y */)
if(nr % 2 == 0)
subimage = vpp::box2d(vpp::vint2(1,0), vpp::vint2(nr-2, nc-1)); // subdomain without first and last row
else
subimage = vpp::box2d(vpp::vint2(1,0), vpp::vint2(nr-1, nc-1)); // subdomain without first row
if(dim == 1 /* x */)
if(nc % 2 == 0)
subimage = vpp::box2d(vpp::vint2(0,1), vpp::vint2(nr-1, nc-2)); // subdomain without first and last column
else
subimage = vpp::box2d(vpp::vint2(0,1), vpp::vint2(nr-1, nc-1)); // subdomain without first column
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t\t...Even Pairs..." << std::endl;
num_blocks = 0;
#endif
proximal_mappings_[2 + 2 * dim] = vpp::clone(data_.img_);
vpp::block_wise(dims, data_.img_ | subimage, tau | subimage, proximal_mappings_[2 + 2 * dim] | subimage) | blockwise_proximal_map;
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t\tBlocks processed: " << num_blocks << std::endl;
#endif
}
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::geod_mean(){
typedef value_type& vtr;
typedef const vtr cvtr;
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t Calculate Geodesic mean: "<< std::endl;
std::cout << "\t\t...first guess euclidiean mean: "<< std::endl;
#endif
// First estimate
auto euclidian_mean = [&] (vtr i, cvtr p0, cvtr p1, cvtr p2, cvtr p3, cvtr p4) {
i = (p0 + p1 + p2 + p3 + p4) / 5.0;
};
vpp::pixel_wise(data_.img_, proximal_mappings_[0], proximal_mappings_[1], proximal_mappings_[2], proximal_mappings_[3], proximal_mappings_[4]) | euclidian_mean;
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t\t...Karcher mean Iteration: "<< std::endl;
#endif
//TODO: Put in Algo traits
double tol = 1e-10;
double max_karcher_iterations = 15;
auto karcher_mean = [&] (vtr i, cvtr p0, cvtr p1, cvtr p2, cvtr p3, cvtr p4) {
/* Slow version, - needs to copy p_i for insertion in value_list
typename MANIFOLD::value_list v;
v.push_back(p0);
v.push_back(p1);
v.push_back(p2);
v.push_back(p3);
v.push_back(p4);
MANIFOLD::karcher_mean(i, v, tol, max_karcher_iterations); */
MANIFOLD::karcher_mean(i, p0, p1, p2, p3, p4);
};
vpp::pixel_wise(data_.img_, proximal_mappings_[0], proximal_mappings_[1], proximal_mappings_[2], proximal_mappings_[3], proximal_mappings_[4]) | karcher_mean;
}
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::approx_mean(){
typedef value_type& vtr;
typedef const vtr cvtr;
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t Calculate approximate mean via convex combinations: "<< std::endl;
#endif
auto convex_comb_mean = [&] (vtr i, cvtr p0, cvtr p1, cvtr p2, cvtr p3, cvtr p4) {
value_type p01, p23;
MANIFOLD::convex_combination(p0, p1, 0.5, p01);
MANIFOLD::convex_combination(p2, p3, 0.5, p23);
MANIFOLD::convex_combination(p01, p23, 0.5, i);
MANIFOLD::convex_combination(i, p4, 0.2, i);
};
vpp::pixel_wise(data_.img_, proximal_mappings_[0], proximal_mappings_[1], proximal_mappings_[2], proximal_mappings_[3], proximal_mappings_[4]) | convex_comb_mean;
}
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::prpt_step(double muk){
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t Proximal step with muk: " << muk << std::endl;
#endif
weights_mat X = func_.getweightsX();
weights_mat Y = func_.getweightsY();
updateFidelity(muk);
updateTV(muk, 0, Y);
updateTV(muk, 1, X);
if(use_approximate_mean_)
approx_mean();
else
geod_mean();
}
template <class FUNCTIONAL, class MANIFOLD, class DATA, enum PARALLEL PAR>
void TV_Minimizer<PRPT, FUNCTIONAL, MANIFOLD, DATA, PAR>::minimize(){
std::cout << "Starting Proximal Point Algorithm with..." << std::endl;
std::cout << "\t Lambda = \t" << func_.getlambda() << std::endl;
std::cout << "\t Max Steps = \t" << max_prpt_steps_ << std::endl;
prpt_step_ = 1;
std::chrono::time_point<std::chrono::system_clock> start, end;
std::chrono::duration<double> t = std::chrono::duration<double>::zero();
start = std::chrono::system_clock::now();
// PRPT Iteration Loop
while(prpt_step_ <= max_prpt_steps_ && t.count() < max_runtime_){
std::cout << "PRPT Step #" << prpt_step_ << std::endl;
typename FUNCTIONAL::result_type J = func_.evaluateJ();
Js_.push_back(J);
std::cout << "\t Value of Functional J: " << J << std::endl;
double muk = 3.0 * std::pow(static_cast<double>(prpt_step_),-0.95);
#ifdef TVMTL_TVMIN_DEBUG
std::cout << "\t Value of muk: " << muk << std::endl;
#endif
prpt_step(muk);
end = std::chrono::system_clock::now();
t = end - start;
std::cout << "\t Elapsed time: " << t.count() << " seconds." << std::endl;
prpt_step_++;
Ts_.push_back(t);
}
std::cout << "Minimization in " << t.count() << " seconds." << std::endl;
}
} // end namespace tvmtl
#endif
| 32.491329 | 166 | 0.645526 | pdebus |
26bf34b3aef83465daf69577f87d4d5ce6ef30d0 | 22,231 | cpp | C++ | crypto/pkc/pkc_rsa.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | crypto/pkc/pkc_rsa.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | crypto/pkc/pkc_rsa.cpp | sttr00/crypto | ef290e4d1b93bb3a659d2d0cafec291ee50df0e8 | [
"BSD-2-Clause"
] | null | null | null | #include "pkc_rsa.h"
#include "utils.h"
#include <crypto/asn1/decoder.h>
#include <crypto/asn1/encoder.h>
#include <crypto/oid_const.h>
#include <crypto/hash_factory.h>
#include <bigint/bigint.h>
#include <platform/endian_ex.h>
#include <platform/alloca.h>
#include <cstring>
#include <cassert>
using namespace oid;
#define countof(a) (sizeof(a)/sizeof(a[0]))
static const size_t MIN_BITS = 512;
static const size_t MAX_BITS = 16384;
static const size_t MIN_BYTES = MIN_BITS/8;
static const size_t MAX_BYTES = MAX_BITS/8 + 2;
static const size_t MIN_PRIV_EXP_BYTES = 16;
static const int MAX_DIGEST_SIZE = 64;
static const uint16_t v15_oid_pairs[] =
{
ID_SIGN_RSA_MD2, ID_HASH_MD2,
ID_SIGN_RSA_MD5, ID_HASH_MD5,
ID_SIGN_RSA_SHA1, ID_HASH_SHA1,
ID_SIGN_RSA_SHA224, ID_HASH_SHA224,
ID_SIGN_RSA_SHA256, ID_HASH_SHA256,
ID_SIGN_RSA_SHA384, ID_HASH_SHA384,
ID_SIGN_RSA_SHA512, ID_HASH_SHA512,
ID_SIGN_RSA_SHA512_224, ID_HASH_SHA512,
ID_SIGN_RSA_SHA512_256, ID_HASH_SHA512_256,
ID_SIGN_RSA_SHA3_224, ID_HASH_SHA3_224,
ID_SIGN_RSA_SHA3_256, ID_HASH_SHA3_256,
ID_SIGN_RSA_SHA3_384, ID_HASH_SHA3_384,
ID_SIGN_RSA_SHA3_512, ID_HASH_SHA3_512
};
pkc_rsa::pkc_rsa()
{
modulus.clear();
pub_exp_large.clear();
pub_exp_small = 0;
priv_exp.clear();
}
int pkc_rsa::get_id() const
{
return ID_RSA;
}
int pkc_rsa::sign_oid_to_hash_oid(int id)
{
for (unsigned i = 0; i < countof(v15_oid_pairs); i += 2)
if (v15_oid_pairs[i] == id) return v15_oid_pairs[i + 1];
return 0;
}
int pkc_rsa::hash_oid_to_sign_oid(int id)
{
for (unsigned i = 0; i < countof(v15_oid_pairs); i += 2)
if (v15_oid_pairs[i + 1] == id) return v15_oid_pairs[i];
return 0;
}
static bool get_modulus(pkc_base::data_buffer &out, const asn1::element *el)
{
if (!el->is_valid_positive_int()) return false;
if (el->size < MIN_BYTES || el->size > MAX_BYTES) return false;
get_integer(out, el);
return true;
}
static bool get_pub_exponent(pkc_base::data_buffer &pub_exp_large, unsigned &pub_exp_small,
const pkc_base::data_buffer &modulus, const asn1::element *el)
{
if (!el->is_valid_positive_int()) return false;
if (el->get_small_uint(pub_exp_small))
{
if (pub_exp_small < 3) return false;
pub_exp_large.clear();
return true;
}
get_integer(pub_exp_large, el);
if (!is_less(pub_exp_large, modulus)) return false;
pub_exp_small = 0;
return true;
}
static bool get_priv_exponent(pkc_base::data_buffer &priv_exp,
const pkc_base::data_buffer &modulus, const asn1::element *el)
{
if (!el->is_valid_positive_int()) return false;
if (el->size < MIN_PRIV_EXP_BYTES) return false;
get_integer(priv_exp, el);
return is_less(priv_exp, modulus);
}
bool pkc_rsa::set_public_key(const void *data, size_t size, const asn1::element *param)
{
if (param && param->tag != asn1::TYPE_NULL) return false;
asn1::element *root = asn1::decode(data, size, 0, nullptr);
if (!root) return false;
bool result = false;
if (root->is_sequence())
{
data_buffer res_modulus, res_pub_exp_large;
unsigned res_pub_exp_small;
const asn1::element *el = root->child;
if (el && get_modulus(res_modulus, el))
{
el = el->sibling;
if (el && get_pub_exponent(res_pub_exp_large, res_pub_exp_small, res_modulus, el))
{
result = true;
modulus = res_modulus;
pub_exp_large = res_pub_exp_large;
pub_exp_small = res_pub_exp_small;
// new public key is set, clear private key
priv_exp.clear();
}
}
}
asn1::delete_tree(root);
return result;
}
bool pkc_rsa::set_private_key(const void *data, size_t size, const asn1::element *param)
{
if (param && param->tag != asn1::TYPE_NULL) return false;
asn1::element *root = asn1::decode(data, size, 0, nullptr);
if (!root) return false;
bool result = false;
if (root->is_sequence())
{
const asn1::element *el = root->child;
unsigned version;
if (el && el->get_small_uint(version) && version == 0)
{
data_buffer res_modulus, res_pub_exp_large, res_priv_exp;
unsigned res_pub_exp_small;
el = el->sibling;
if (el && get_modulus(res_modulus, el))
{
el = el->sibling;
if (el && get_pub_exponent(res_pub_exp_large, res_pub_exp_small, res_modulus, el))
{
el = el->sibling;
if (el && get_priv_exponent(res_priv_exp, res_modulus, el))
{
result = true;
modulus = res_modulus;
pub_exp_large = res_pub_exp_large;
pub_exp_small = res_pub_exp_small;
priv_exp = res_priv_exp;
}
}
}
}
}
asn1::delete_tree(root);
return result;
}
bool pkc_rsa::power_public(void *out, size_t &out_size, const void *in, size_t in_size) const
{
if (!modulus.data || in_size > modulus.size) return false;
assert(pub_exp_large.data || pub_exp_small);
bigint_t val_modulus = bigint_create_bytes_be(modulus.data, modulus.size);
bigint_t val_public = pub_exp_small?
bigint_create_word(pub_exp_small) : bigint_create_bytes_be(pub_exp_large.data, pub_exp_large.size);
bigint_t val_input = bigint_create_bytes_be(in, in_size);
bigint_t val_result = bigint_create(0);
bigint_mpow(val_result, val_input, val_public, val_modulus);
size_t pad_size = 0;
size_t result_size = bigint_get_byte_count(val_result);
if (result_size < modulus.size)
{
pad_size = modulus.size-result_size;
memset(out, 0, pad_size);
}
int result = bigint_get_bytes_be(val_result, static_cast<uint8_t*>(out) + pad_size, out_size - pad_size);
bigint_destroy(val_result);
bigint_destroy(val_input);
bigint_destroy(val_public);
bigint_destroy(val_modulus);
if (result < 0) return false;
out_size = result + pad_size;
return true;
}
bool pkc_rsa::power_private(void *out, size_t &out_size, const void *in, size_t in_size) const
{
if (!priv_exp.data) return false;
assert(modulus.data);
bigint_t val_modulus = bigint_create_bytes_be(modulus.data, modulus.size);
bigint_t val_private = bigint_create_bytes_be(priv_exp.data, priv_exp.size);
bigint_t val_input = bigint_create_bytes_be(in, in_size);
bigint_t val_result = bigint_create(0);
bigint_mpow(val_result, val_input, val_private, val_modulus);
size_t pad_size = 0;
size_t result_size = bigint_get_byte_count(val_result);
if (result_size < modulus.size)
{
pad_size = modulus.size-result_size;
memset(out, 0, pad_size);
}
int result = bigint_get_bytes_be(val_result, static_cast<uint8_t*>(out) + pad_size, out_size - pad_size);
bigint_destroy(val_result);
bigint_destroy(val_input);
bigint_destroy(val_private);
bigint_destroy(val_modulus);
if (result < 0) return false;
out_size = result + pad_size;
return true;
}
static void mgf1(uint8_t *out, size_t out_size, const void *seed, size_t seed_len, const hash_def *hd)
{
uint32_t counter = 0;
void *ctx = alloca(hd->context_size);
while (out_size)
{
size_t result_size = hd->hash_size;
if (result_size > out_size) result_size = out_size;
hd->func_init(ctx);
hd->func_update(ctx, seed, seed_len);
uint32_t be_counter = VALUE_BE32(counter);
hd->func_update(ctx, &be_counter, 4);
memcpy(out, hd->func_final(ctx), result_size);
counter++;
out += result_size;
out_size -= result_size;
}
}
#define GET_INT_PARAM(result) \
if (params[i].size) return 0; \
result = params[i].ival;
#define GET_BOOL_PARAM(result) \
if (params[i].size) return 0; \
result = params[i].bval;
#define GET_DATA_PARAM(result) \
result.data = params[i].data; \
result.size = params[i].size;
bool pkc_rsa::create_signature(void *out, size_t &out_size,
const void *data, size_t data_size,
const param_data *params, int param_count,
random_gen *rng) const
{
if (!priv_exp.data || out_size < modulus.size) return false;
uint8_t digest[MAX_DIGEST_SIZE];
bool data_is_hash = false;
bool raw_signature = false;
int wrap_alg = ID_RSA;
int hash_alg = 0;
int mg_hash_alg = 0;
data_buffer salt;
size_t in_size;
salt.clear();
for (int i = 0; i < param_count; i++)
switch (params[i].type)
{
case PARAM_DATA_IS_HASH:
GET_BOOL_PARAM(data_is_hash);
break;
case PARAM_WRAPPING_ALG:
GET_INT_PARAM(wrap_alg);
if (!(wrap_alg == ID_RSA || wrap_alg == ID_RSASSA_PSS)) return false;
break;
case PARAM_HASH_ALG:
GET_INT_PARAM(hash_alg);
break;
case PARAM_MGF_HASH_ALG:
GET_INT_PARAM(mg_hash_alg);
break;
case PARAM_SALT:
GET_DATA_PARAM(salt);
if (salt.size >= 0x10000) return false;
break;
case PARAM_RAW_SIGNATURE:
GET_BOOL_PARAM(raw_signature);
break;
default:
return false;
}
if (!raw_signature && !hash_alg) return false;
if (wrap_alg == ID_RSASSA_PSS)
{
// encoded PSS signature can have modulus.size or modulus.size-1 bytes,
// depending on the MSB position
in_size = modulus.size;
int top_bit = bsr32(static_cast<const uint8_t*>(modulus.data)[0]);
uint8_t top_mask = 0xFF >> (8-top_bit);
if (!top_mask)
{
in_size--;
top_mask = 0xFF;
}
uint8_t *masked = static_cast<uint8_t*>(out);
const hash_def *hd_hash = hash_factory(hash_alg);
if (!hd_hash) return false;
if (hd_hash->hash_size + salt.size + 2 > in_size) return false;
if (!mg_hash_alg) mg_hash_alg = hash_alg;
const hash_def *hd_mgf = hash_factory(mg_hash_alg);
if (!hd_mgf) return false;
void *ctx = alloca(hd_hash->context_size);
const void *msg;
size_t msg_size;
if (data_is_hash)
{
msg = data;
msg_size = data_size;
} else
{
msg_size = hd_hash->hash_size;
assert(msg_size <= MAX_DIGEST_SIZE);
hd_hash->func_init(ctx);
hd_hash->func_update(ctx, data, data_size);
memcpy(digest, hd_hash->func_final(ctx), msg_size);
msg = digest;
}
hd_hash->func_init(ctx);
uint64_t ps1 = 0;
hd_hash->func_update(ctx, &ps1, sizeof(ps1));
hd_hash->func_update(ctx, msg, msg_size);
hd_hash->func_update(ctx, salt.data, salt.size);
size_t mask_size = in_size - 1 - hd_hash->hash_size;
uint8_t *hash_out = masked + mask_size;
memcpy(hash_out, hd_hash->func_final(ctx), hd_hash->hash_size);
hash_out[hd_hash->hash_size] = 0xBC;
mgf1(masked, mask_size, hash_out, hd_hash->hash_size, hd_mgf);
xor_data(masked + mask_size - salt.size, static_cast<const uint8_t*>(salt.data), salt.size);
masked[mask_size - salt.size - 1] ^= 1;
masked[0] &= top_mask;
} else
if (!raw_signature)
{
const oid_def *hash_oid_def = get(hash_alg);
if (!hash_oid_def) return false;
const hash_def *hd_hash = nullptr;
const void *msg;
size_t msg_size;
if (data_is_hash)
{
if (data_size + 11 > modulus.size) return false;
msg = data;
msg_size = data_size;
} else
{
hd_hash = hash_factory(hash_alg);
if (!hd_hash) return false;
msg_size = hd_hash->hash_size;
if (msg_size + 11 > modulus.size) return false;
assert(msg_size <= MAX_DIGEST_SIZE);
void *ctx = alloca(hd_hash->context_size);
hd_hash->func_init(ctx);
hd_hash->func_update(ctx, data, data_size);
memcpy(digest, hd_hash->func_final(ctx), msg_size);
msg = digest;
}
asn1::element el_root(asn1::TYPE_SEQUENCE);
asn1::element el_alg(asn1::TYPE_SEQUENCE);
asn1::element el_oid(asn1::TYPE_OID, hash_oid_def->data, hash_oid_def->size);
asn1::element el_params(asn1::TYPE_NULL);
asn1::element el_hash(asn1::TYPE_OCTET_STRING, msg, msg_size);
el_alg.child = &el_oid;
el_oid.sibling = &el_params;
el_alg.sibling = &el_hash;
el_root.child = &el_alg;
size_t asn_size = asn1::calc_encoded_size(&el_root);
if (asn_size + 11 > modulus.size) return false;
uint8_t *pad = static_cast<uint8_t*>(out);
size_t pad_len = modulus.size - asn_size - 3;
// leading zero is removed, it's not needed for power_private
pad[0] = 1;
memset(pad + 1, 0xFF, pad_len);
pad[pad_len + 1] = 0;
size_t encoded_size = asn_size;
if (!asn1::encode_def_length(pad + pad_len + 2, encoded_size, &el_root))
{
assert(0);
return false;
}
assert(asn_size == encoded_size);
in_size = modulus.size - 1;
} else
{
if (data_size + 11 > modulus.size) return false;
uint8_t *pad = static_cast<uint8_t*>(out);
size_t pad_len = modulus.size - data_size - 3;
// leading zero is removed, it's not needed for power_private
pad[0] = 1;
memset(pad + 1, 0xFF, pad_len);
pad[pad_len + 1] = 0;
memcpy(pad + pad_len + 2, data, data_size);
in_size = modulus.size - 1;
}
return power_private(out, out_size, out, in_size);
}
asn1::element *pkc_rsa::create_params_struct(const param_data *params, int param_count, int where) const
{
int wrap_alg = ID_RSA;
int hash_alg = 0, mg_hash_alg = 0;
data_buffer salt;
salt.clear();
for (int i = 0; i < param_count; i++)
switch (params[i].type)
{
case PARAM_DATA_IS_HASH:
break;
case PARAM_WRAPPING_ALG:
GET_INT_PARAM(wrap_alg);
if (!(wrap_alg == ID_RSA || wrap_alg == ID_RSASSA_PSS)) return nullptr;
break;
case PARAM_HASH_ALG:
GET_INT_PARAM(hash_alg);
break;
case PARAM_MGF_HASH_ALG:
GET_INT_PARAM(mg_hash_alg);
break;
case PARAM_SALT:
GET_DATA_PARAM(salt);
if (salt.size >= 0x10000) return nullptr;
break;
default:
return nullptr;
}
if (!hash_alg) return nullptr;
int sign_id;
const oid_def *hash_oid_def = nullptr;
const oid_def *mg_hash_oid_def = nullptr;
if (wrap_alg == ID_RSASSA_PSS)
{
sign_id = ID_RSASSA_PSS;
if (hash_alg != ID_HASH_SHA1)
{
hash_oid_def = get(hash_alg);
if (!hash_oid_def) return nullptr;
}
if (!mg_hash_alg) mg_hash_alg = hash_alg;
if (mg_hash_alg != ID_HASH_SHA1)
{
mg_hash_oid_def = get(mg_hash_alg);
if (!mg_hash_oid_def) return nullptr;
}
} else
{
sign_id = hash_oid_to_sign_oid(hash_alg);
if (!sign_id) return nullptr;
}
const oid_def *sign_oid_def = get(sign_id);
if (!sign_oid_def) return nullptr;
asn1::element *el_oid = asn1::element::create(asn1::TYPE_OID, sign_oid_def->data, sign_oid_def->size);
if (wrap_alg == ID_RSASSA_PSS)
{
asn1::element *params = asn1::element::create(asn1::TYPE_SEQUENCE);
asn1::element *prev = nullptr;
if (hash_oid_def)
{
asn1::element *el = create_tagged_element(0, create_alg_id(hash_oid_def));
append_child(params, el, prev);
}
if (mg_hash_oid_def)
{
const oid_def *mgf1_def = get(ID_MGF1);
assert(mgf1_def);
asn1::element *el = create_alg_id(mgf1_def);
el->child->sibling = create_alg_id(mg_hash_oid_def);
el = create_tagged_element(1, el);
append_child(params, el, prev);
}
if (mg_hash_alg != ID_HASH_SHA1 || salt.size != 20)
{
void *uint_buf = operator new(8);
size_t uint_size = pack_small_uint(static_cast<uint8_t*>(uint_buf), salt.size);
asn1::element *el_int = asn1::element::create(asn1::TYPE_INTEGER, uint_buf, uint_size);
el_int->flags |= asn1::element::FLAG_OWN_BUFFER;
append_child(params, create_tagged_element(2, el_int), prev);
}
if (params->child) el_oid->sibling = params; else delete params;
} else
{
el_oid->sibling = asn1::element::create(asn1::TYPE_NULL);
}
asn1::element *el_root = asn1::element::create(asn1::TYPE_SEQUENCE);
el_root->child = el_oid;
return el_root;
}
static bool parse_hash_alg(int &hash_alg, const asn1::element *el)
{
const asn1::element *params;
if (!parse_alg_id(hash_alg, params, el->child) || params) return false;
return true;
}
static bool parse_mg_alg(int &mg_hash_alg, const asn1::element *el)
{
const asn1::element *params;
int mg_alg;
if (!parse_alg_id(mg_alg, params, el->child) || !params) return false;
if (mg_alg != ID_MGF1) return false;
if (!parse_alg_id(mg_hash_alg, params, params) || params) return false;
return true;
}
static bool parse_salt_len(int &salt_len, const asn1::element *el)
{
el = el->child;
unsigned value;
if (!(el && el->get_small_uint(value))) return false;
if (value >= 0x10000) return false;
salt_len = value;
return true;
}
static bool parse_trailer(const asn1::element *el)
{
el = el->child;
unsigned value;
if (!(el && el->get_small_uint(value))) return false;
return value == 1;
}
static bool check_zero(const uint8_t *data, size_t size)
{
for (size_t i = 0; i < size; i++)
if (data[i]) return false;
return true;
}
static size_t decode_v15_sign_padding(const uint8_t *data, size_t size)
{
if (data[0] || data[1] != 1) return 0;
size_t pos = 2;
for (;;)
{
if (data[pos] != 0xFF) break;
if (++pos == size) return 0;
}
if (pos < 10 || data[pos]) return 0;
if (++pos == size) return 0;
return pos;
}
static const uint8_t *decode_v15_wrapping(const uint8_t *data, size_t size, int hash_id, size_t &hash_size)
{
asn1::element *root = asn1::decode(data, size, 0, nullptr);
if (!root) return nullptr;
const uint8_t *result = nullptr;
if (root->is_sequence())
{
const asn1::element *el = root->child;
const asn1::element *params;
int alg_id;
if (parse_alg_id(alg_id, params, el) && alg_id == hash_id)
{
el = el->sibling;
if (el && el->is_octet_string())
{
result = el->data;
hash_size = el->size;
}
}
}
asn1::delete_tree(root);
return result;
}
bool pkc_rsa::verify_signature(const void *sig, size_t sig_size,
const void *data, size_t data_size,
const param_data *params, int param_count) const
{
if (!modulus.data) return false;
const hash_def *hd_hash = nullptr;
const hash_def *hd_mgf = nullptr;
int salt_len = -1;
uint8_t top_mask;
uint8_t digest[MAX_DIGEST_SIZE];
bool result;
int enc_alg = ID_RSA, hash_alg = 0;
const asn1::element *alg_info = nullptr;
const asn1::element *alg_param = nullptr;
bool data_is_hash = false;
bool raw_signature = false;
for (int i = 0; i < param_count; i++)
switch (params[i].type)
{
case PARAM_DATA_IS_HASH:
GET_BOOL_PARAM(data_is_hash);
break;
case PARAM_HASH_ALG:
GET_INT_PARAM(hash_alg);
break;
case PARAM_ALG_INFO:
if (params[i].size) return false;
alg_info = static_cast<const asn1::element*>(params[i].data);
break;
case PARAM_RAW_SIGNATURE:
GET_BOOL_PARAM(raw_signature);
break;
default:
return false;
}
if (raw_signature)
{
if (sig_size != modulus.size) return false;
enc_alg = 0;
alg_info = nullptr;
}
if (alg_info && !parse_alg_id(enc_alg, alg_param, alg_info)) return false;
if (enc_alg == ID_RSASSA_PSS)
{
hash_alg = ID_HASH_SHA1;
int mg_hash_alg = ID_HASH_SHA1;
if (alg_param)
{
if (!alg_param->is_sequence()) return false;
int prev_tag = -1;
for (const asn1::element *el = alg_param->child; el; el = el->sibling)
{
if (el->cls != asn1::CLASS_CONTEXT_SPECIFIC || el->tag >= 0x10000) return false;
int tag = static_cast<int>(el->tag);
if (tag <= prev_tag) return false;
switch (tag)
{
case 0:
if (!parse_hash_alg(hash_alg, el)) return false;
break;
case 1:
if (!parse_mg_alg(mg_hash_alg, el)) return false;
break;
case 2:
if (!parse_salt_len(salt_len, el)) return false;
break;
case 3:
if (!parse_trailer(el)) return false;
break;
}
prev_tag = tag;
}
}
hd_hash = hash_factory(hash_alg);
if (!hd_hash) return false;
hd_mgf = hash_factory(mg_hash_alg);
if (!hd_mgf) return false;
if (salt_len < 0) salt_len = hd_hash->hash_size;
if (static_cast<size_t>(hd_hash->hash_size) > sig_size - 2) return false;
if (static_cast<size_t>(salt_len) > sig_size - (hd_hash->hash_size + 2)) return false;
int top_bit = bsr32(static_cast<const uint8_t*>(modulus.data)[0]);
top_mask = 0xFF >> (8-top_bit);
if (data_is_hash && hd_hash->hash_size != data_size) return false;
assert(hd_hash->hash_size <= MAX_DIGEST_SIZE);
} else
if (!raw_signature)
{
if (alg_info) hash_alg = sign_oid_to_hash_oid(enc_alg);
if (!hash_alg) return false;
hd_hash = hash_factory(hash_alg);
if (!hd_hash) return false;
if (data_is_hash && hd_hash->hash_size != data_size) return false;
assert(hd_hash->hash_size <= MAX_DIGEST_SIZE);
}
size_t out_size = modulus.size;
uint8_t *out = static_cast<uint8_t*>(alloca(out_size));
if (!power_public(out, out_size, sig, sig_size)) return false;
assert(out_size == modulus.size);
if (enc_alg == ID_RSASSA_PSS)
{
if (!top_mask)
{
out++;
out_size--;
top_mask = 0xFF;
}
if (static_cast<size_t>(hd_hash->hash_size + salt_len + 2) > out_size) return false;
if (out[out_size-1] != 0xBC) return false;
if (out[0] & ~top_mask) return false;
size_t mask_len = out_size - (hd_hash->hash_size + 1);
const uint8_t *hash = out + mask_len;
uint8_t *mask = static_cast<uint8_t*>(alloca(mask_len));
mgf1(mask, mask_len, hash, hd_hash->hash_size, hd_mgf);
xor_data(out, mask, mask_len);
out[0] &= top_mask;
size_t pad_len = mask_len - salt_len - 1;
if (!check_zero(out, pad_len) || out[pad_len] != 1) return false;
void *ctx = alloca(hd_hash->context_size);
const void *use_digest;
if (data_is_hash)
{
use_digest = data;
} else
{
hd_hash->func_init(ctx);
hd_hash->func_update(ctx, data, data_size);
memcpy(digest, hd_hash->func_final(ctx), hd_hash->hash_size);
use_digest = digest;
}
hd_hash->func_init(ctx);
uint64_t ps1 = 0;
hd_hash->func_update(ctx, &ps1, sizeof(ps1));
hd_hash->func_update(ctx, use_digest, hd_hash->hash_size);
hd_hash->func_update(ctx, out + pad_len + 1, salt_len);
result = memcmp(hd_hash->func_final(ctx), hash, hd_hash->hash_size) == 0;
} else
{
size_t pad_len = decode_v15_sign_padding(out, out_size);
if (!pad_len) return false;
if (raw_signature)
{
if (sig_size - pad_len != data_size) return false;
result = memcmp(out + pad_len, data, data_size) == 0;
} else
{
size_t hash_size;
const void *hash = decode_v15_wrapping(out + pad_len, out_size - pad_len, hd_hash->id, hash_size);
if (!hash || static_cast<int>(hash_size) != hd_hash->hash_size) return false;
const void *use_digest;
if (data_is_hash)
{
use_digest = data;
} else
{
void *ctx = alloca(hd_hash->context_size);
hd_hash->func_init(ctx);
hd_hash->func_update(ctx, data, data_size);
memcpy(digest, hd_hash->func_final(ctx), hd_hash->hash_size);
use_digest = digest;
}
result = memcmp(use_digest, hash, hash_size) == 0;
}
}
return result;
}
int pkc_rsa::get_key_bits() const
{
return get_bits(modulus);
}
| 28.648196 | 107 | 0.690612 | sttr00 |
26c21dd0409c40669ce17fd35d421a5c4a0458cb | 29,722 | cpp | C++ | plugins/astro/src/AstroParticleConverter.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | plugins/astro/src/AstroParticleConverter.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | plugins/astro/src/AstroParticleConverter.cpp | xge/megamol | 1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b | [
"BSD-3-Clause"
] | null | null | null | /*
* AstroParticleConverter.cpp
*
* Copyright (C) 2019 by VISUS (Universitaet Stuttgart)
* All rights reserved.
*/
#include "AstroParticleConverter.h"
#include <glm/gtc/type_ptr.hpp>
#include "simultaneous_sort.h"
using namespace megamol;
using namespace megamol::astro;
using namespace megamol::core;
using namespace megamol::geocalls;
/*
* AstroParticleConverter::AstroParticleConverter
*/
AstroParticleConverter::AstroParticleConverter(void)
: Module()
, sphereDataSlot("sphereData", "Output slot for the resulting sphere data")
, sphereSpecialSlot(
"formattedSphereData", "Output slot for the sphere data containing density and velocity informaton")
, astroDataSlot("astroData", "Input slot for astronomical data")
, colorModeSlot("colorMode", "Coloring mode for the output particles")
, minColorSlot("minColor", "minimum color of the used range")
, midColorSlot("midColor", "median color of the used range")
, maxColorSlot("maxColor", "maximum color of the used range")
, useMidColorSlot("useMidColor", "Enables the usage of the mid color in the color interpolation")
, minValueSlot("minValue", "minimum value of the currently shown parameter")
, maxValueSlot("maxValue", "maximum value of the currently shown parameter")
, lastDataHash(0)
, hashOffset(0)
, valmin(0.0f)
, valmax(1.0f)
, densityMin(0.0f)
, densityMax(0.0f) {
this->astroDataSlot.SetCompatibleCall<AstroDataCallDescription>();
this->MakeSlotAvailable(&this->astroDataSlot);
this->sphereDataSlot.SetCallback(
MultiParticleDataCall::ClassName(), MultiParticleDataCall::FunctionName(0), &AstroParticleConverter::getData);
this->sphereDataSlot.SetCallback(
MultiParticleDataCall::ClassName(), MultiParticleDataCall::FunctionName(1), &AstroParticleConverter::getExtent);
this->MakeSlotAvailable(&this->sphereDataSlot);
this->sphereSpecialSlot.SetCallback(MultiParticleDataCall::ClassName(), MultiParticleDataCall::FunctionName(0),
&AstroParticleConverter::getSpecialData);
this->sphereSpecialSlot.SetCallback(
MultiParticleDataCall::ClassName(), MultiParticleDataCall::FunctionName(1), &AstroParticleConverter::getExtent);
this->MakeSlotAvailable(&this->sphereSpecialSlot);
param::EnumParam* enu = new param::EnumParam(static_cast<int>(ColoringMode::GRAVITATIONAL_POTENTIAL));
enu->SetTypePair(static_cast<int>(ColoringMode::MASS), "Mass");
enu->SetTypePair(static_cast<int>(ColoringMode::INTERNAL_ENERGY), "Internal Energy");
enu->SetTypePair(static_cast<int>(ColoringMode::SMOOTHING_LENGTH), "Smoothing Length");
enu->SetTypePair(static_cast<int>(ColoringMode::MOLECULAR_WEIGHT), "Molecular Weight");
enu->SetTypePair(static_cast<int>(ColoringMode::DENSITY), "Density");
enu->SetTypePair(static_cast<int>(ColoringMode::GRAVITATIONAL_POTENTIAL), "Gravitational Potential");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_BARYON), "Baryon");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_STAR), "Star");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_WIND), "Wind");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_STAR_FORMING_GAS), "Star-forming Gas");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_AGN), "AGN");
enu->SetTypePair(static_cast<int>(ColoringMode::IS_DARK_MATTER), "Dark Matter");
enu->SetTypePair(static_cast<int>(ColoringMode::TEMPERATURE), "Temperature");
enu->SetTypePair(static_cast<int>(ColoringMode::ENTROPY), "Entropy");
enu->SetTypePair(static_cast<int>(ColoringMode::INTERNAL_ENERGY_DERIVATIVE), "Internal Energy Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::SMOOTHING_LENGTH_DERIVATIVE), "Smoothing Length Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::MOLECULAR_WEIGHT_DERIVATIVE), "Molecular Weight Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::DENSITY_DERIVATIVE), "Density Derivative");
enu->SetTypePair(
static_cast<int>(ColoringMode::GRAVITATIONAL_POTENTIAL_DERIVATIVE), "Gravitational Potential Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::TEMPERATURE_DERIVATIVE), "Temperature Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::ENTROPY_DERIVATIVE), "Entropy Derivative");
enu->SetTypePair(static_cast<int>(ColoringMode::AGN_DISTANCES), "AGN Distances");
this->colorModeSlot << enu;
this->MakeSlotAvailable(&this->colorModeSlot);
this->minColorSlot.SetParameter(new param::ColorParam("#146496"));
this->MakeSlotAvailable(&this->minColorSlot);
this->midColorSlot.SetParameter(new param::ColorParam("#f0f0f0"));
this->MakeSlotAvailable(&this->midColorSlot);
this->maxColorSlot.SetParameter(new param::ColorParam("#ae3b32"));
this->MakeSlotAvailable(&this->maxColorSlot);
this->useMidColorSlot.SetParameter(new param::BoolParam(true));
this->MakeSlotAvailable(&this->useMidColorSlot);
auto minPar = new param::FloatParam(0.0f);
minPar->SetGUIReadOnly(true);
this->minValueSlot.SetParameter(minPar);
this->MakeSlotAvailable(&this->minValueSlot);
auto maxPar = new param::FloatParam(0.0f);
maxPar->SetGUIReadOnly(true);
this->maxValueSlot.SetParameter(maxPar);
this->MakeSlotAvailable(&this->maxValueSlot);
}
/*
* AstroParticleConverter::~AstroParticleConverter
*/
AstroParticleConverter::~AstroParticleConverter(void) {
this->Release();
}
/*
* AstroParticleConverter::create
*/
bool AstroParticleConverter::create(void) {
// intentionally empty
return true;
}
/*
* AstroParticleConverter::release
*/
void AstroParticleConverter::release(void) {
// intentionally empty
}
/*
* AstroParticleConverter::getData
*/
bool AstroParticleConverter::getData(Call& call) {
MultiParticleDataCall* mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
if (mpdc == nullptr)
return false;
AstroDataCall* ast = this->astroDataSlot.CallAs<AstroDataCall>();
if (ast == nullptr)
return false;
ast->SetFrameID(mpdc->FrameID(), mpdc->IsFrameForced());
// ast->SetUnlocker(nullptr, false);
if ((*ast)(AstroDataCall::CallForGetData)) {
bool freshMinMax = false;
if (this->lastDataHash != ast->DataHash() || this->colorModeSlot.IsDirty() ||
this->lastFrame != mpdc->FrameID()) {
this->lastFrame = mpdc->FrameID();
this->lastDataHash = ast->DataHash();
this->colorModeSlot.ResetDirty();
this->calcMinMaxValues(*ast);
freshMinMax = true;
}
auto particleCount = ast->GetParticleCount();
mpdc->SetDataHash(this->lastDataHash + this->hashOffset);
mpdc->SetParticleListCount(1);
MultiParticleDataCall::Particles& p = mpdc->AccessParticles(0);
p.SetCount(particleCount);
if (p.GetCount() > 0) {
p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZ, ast->GetPositions()->data());
if (freshMinMax || this->minColorSlot.IsDirty() || this->midColorSlot.IsDirty() ||
this->maxColorSlot.IsDirty() || this->useMidColorSlot.IsDirty()) {
this->calcColorTable(*ast);
this->minColorSlot.ResetDirty();
this->midColorSlot.ResetDirty();
this->maxColorSlot.ResetDirty();
this->useMidColorSlot.ResetDirty();
}
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_RGBA, this->usedColors.data());
p.SetColourMapIndexValues(this->valmin, this->valmax);
p.SetDirData(SimpleSphericalParticles::DirDataType::DIRDATA_FLOAT_XYZ, ast->GetVelocities()->data());
}
// ast->Unlock();
return true;
}
ast->Unlock();
return false;
}
/*
* AstroParticleConverter::getSpecialData
*/
bool AstroParticleConverter::getSpecialData(Call& call) {
MultiParticleDataCall* mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
if (mpdc == nullptr)
return false;
AstroDataCall* ast = this->astroDataSlot.CallAs<AstroDataCall>();
if (ast == nullptr)
return false;
ast->SetFrameID(mpdc->FrameID(), mpdc->IsFrameForced());
// ast->SetUnlocker(nullptr, false);
if ((*ast)(AstroDataCall::CallForGetData)) {
bool freshMinMax = false;
if (this->lastDataHash != ast->DataHash() || this->colorModeSlot.IsDirty() ||
this->lastFrame != mpdc->FrameID()) {
this->lastFrame = mpdc->FrameID();
this->lastDataHash = ast->DataHash();
this->colorModeSlot.ResetDirty();
this->calcMinMaxValues(*ast);
freshMinMax = true;
}
auto particleCount = ast->GetParticleCount();
auto positions = *ast->GetPositions().get();
vel_ = *ast->GetVelocities().get();
dens_ = *ast->GetDensity().get();
sl_ = *ast->GetSmoothingLength().get();
temp_ = *ast->GetTemperature().get();
mass_ = *ast->GetMass().get();
mw_ = *ast->GetMolecularWeights().get();
auto isBaryon = ast->GetIsBaryonFlags();
std::vector<char> ib(isBaryon->size());
for (size_t idx = 0; idx < isBaryon->size(); ++idx) {
if (isBaryon->operator[](idx)) {
ib[idx] = 1;
} else {
ib[idx] = 0;
}
}
/*pos_.clear();
pos_.reserve(particleCount / 2);
vel_.clear();
vel_.reserve(particleCount / 2);
dens_.clear();
dens_.reserve(particleCount / 2);*/
sort_with([](auto a, auto b) { return a > b; }, ib, positions, vel_, dens_, sl_, temp_, mass_, mw_);
auto it = std::find(ib.cbegin(), ib.cend(), false);
auto idx = std::distance(ib.cbegin(), it);
positions.erase(positions.begin() + idx, positions.end());
vel_.erase(vel_.begin() + idx, vel_.end());
dens_.erase(dens_.begin() + idx, dens_.end());
sl_.erase(sl_.begin() + idx, sl_.end());
temp_.erase(temp_.begin() + idx, temp_.end());
mass_.erase(mass_.begin() + idx, mass_.end());
mw_.erase(mw_.begin() + idx, mw_.end());
pos_.resize(positions.size());
for (size_t idx = 0; idx < positions.size(); ++idx) {
pos_[idx].x = positions[idx].x;
pos_[idx].y = positions[idx].y;
pos_[idx].z = positions[idx].z;
pos_[idx].w = sl_[idx];
}
mpdc->SetDataHash(this->lastDataHash + this->hashOffset);
mpdc->SetParticleListCount(1);
MultiParticleDataCall::Particles& p = mpdc->AccessParticles(0);
p.SetCount(pos_.size());
if (p.GetCount() > 0) {
p.SetVertexData(MultiParticleDataCall::Particles::VERTDATA_FLOAT_XYZR, pos_.data());
if (freshMinMax || this->minColorSlot.IsDirty() || this->midColorSlot.IsDirty() ||
this->maxColorSlot.IsDirty() || this->useMidColorSlot.IsDirty()) {
this->calcColorTable(*ast);
this->minColorSlot.ResetDirty();
this->midColorSlot.ResetDirty();
this->maxColorSlot.ResetDirty();
this->useMidColorSlot.ResetDirty();
}
auto const sel = colorModeSlot.Param<core::param::EnumParam>()->Value();
if (sel == static_cast<int>(ColoringMode::TEMPERATURE)) {
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, temp_.data());
auto minmax_val = std::minmax_element(temp_.begin(), temp_.end());
p.SetColourMapIndexValues(*minmax_val.first, *minmax_val.second);
} else if (sel == static_cast<int>(ColoringMode::MASS)) {
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, mass_.data());
auto minmax_val = std::minmax_element(mass_.begin(), mass_.end());
p.SetColourMapIndexValues(*minmax_val.first, *minmax_val.second);
} else if (sel == static_cast<int>(ColoringMode::MOLECULAR_WEIGHT)) {
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, mw_.data());
auto minmax_val = std::minmax_element(mw_.begin(), mw_.end());
p.SetColourMapIndexValues(*minmax_val.first, *minmax_val.second);
} else {
p.SetColourData(MultiParticleDataCall::Particles::COLDATA_FLOAT_I, dens_.data());
auto minmax_val = std::minmax_element(dens_.begin(), dens_.end());
p.SetColourMapIndexValues(*minmax_val.first, *minmax_val.second);
}
p.SetDirData(SimpleSphericalParticles::DirDataType::DIRDATA_FLOAT_XYZ, vel_.data());
}
// ast->Unlock();
return true;
}
ast->Unlock();
return true;
}
/*
* AstroParticleConverter::getExtent
*/
bool AstroParticleConverter::getExtent(Call& call) {
MultiParticleDataCall* mpdc = dynamic_cast<MultiParticleDataCall*>(&call);
if (mpdc == nullptr)
return false;
AstroDataCall* ast = this->astroDataSlot.CallAs<AstroDataCall>();
if (ast == nullptr)
return false;
ast->SetUnlocker(nullptr, false);
if ((*ast)(AstroDataCall::CallForGetExtent)) {
mpdc->SetFrameCount(ast->FrameCount());
if (this->colorModeSlot.IsDirty() || this->minColorSlot.IsDirty() || this->midColorSlot.IsDirty() ||
this->maxColorSlot.IsDirty() || this->useMidColorSlot.IsDirty()) {
this->hashOffset++;
}
mpdc->SetDataHash(ast->DataHash() + this->hashOffset);
mpdc->AccessBoundingBoxes() = ast->AccessBoundingBoxes();
ast->Unlock();
return true;
}
ast->Unlock();
return false;
}
/*
* AstroParticleConverter::calcMinMaxValues
*/
void AstroParticleConverter::calcMinMaxValues(const AstroDataCall& ast) {
auto colmode = static_cast<ColoringMode>(this->colorModeSlot.Param<param::EnumParam>()->Value());
this->valmin = this->densityMin = 0.0f;
this->valmax = this->densityMax = 1.0f;
if (ast.GetParticleCount() < 1) { // when no particles are present the pointer dereferencing later does not work
this->minValueSlot.Param<param::FloatParam>()->SetValue(this->valmin);
this->maxValueSlot.Param<param::FloatParam>()->SetValue(this->valmax);
return;
}
switch (colmode) {
case megamol::astro::AstroParticleConverter::ColoringMode::MASS:
this->valmin = *std::min_element(ast.GetMass()->begin(), ast.GetMass()->end());
this->valmax = *std::max_element(ast.GetMass()->begin(), ast.GetMass()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::INTERNAL_ENERGY:
this->valmin = *std::min_element(ast.GetInternalEnergy()->begin(), ast.GetInternalEnergy()->end());
this->valmax = *std::max_element(ast.GetInternalEnergy()->begin(), ast.GetInternalEnergy()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::SMOOTHING_LENGTH:
this->valmin = *std::min_element(ast.GetSmoothingLength()->begin(), ast.GetSmoothingLength()->end());
this->valmax = *std::max_element(ast.GetSmoothingLength()->begin(), ast.GetSmoothingLength()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::MOLECULAR_WEIGHT:
this->valmin = *std::min_element(ast.GetMolecularWeights()->begin(), ast.GetMolecularWeights()->end());
this->valmax = *std::max_element(ast.GetMolecularWeights()->begin(), ast.GetMolecularWeights()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::DENSITY:
this->valmin = *std::min_element(ast.GetDensity()->begin(), ast.GetDensity()->end());
this->valmax = *std::max_element(ast.GetDensity()->begin(), ast.GetDensity()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::GRAVITATIONAL_POTENTIAL:
this->valmin =
*std::min_element(ast.GetGravitationalPotential()->begin(), ast.GetGravitationalPotential()->end());
this->valmax =
*std::max_element(ast.GetGravitationalPotential()->begin(), ast.GetGravitationalPotential()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::TEMPERATURE:
this->valmin = *std::min_element(ast.GetTemperature()->begin(), ast.GetTemperature()->end());
this->valmax = *std::max_element(ast.GetTemperature()->begin(), ast.GetTemperature()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::ENTROPY:
this->valmin = *std::min_element(ast.GetEntropy()->begin(), ast.GetEntropy()->end());
this->valmax = *std::max_element(ast.GetEntropy()->begin(), ast.GetEntropy()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::INTERNAL_ENERGY_DERIVATIVE:
this->valmin =
*std::min_element(ast.GetInternalEnergyDerivatives()->begin(), ast.GetInternalEnergyDerivatives()->end());
this->valmax =
*std::max_element(ast.GetInternalEnergyDerivatives()->begin(), ast.GetInternalEnergyDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::SMOOTHING_LENGTH_DERIVATIVE:
this->valmin =
*std::min_element(ast.GetSmoothingLengthDerivatives()->begin(), ast.GetSmoothingLengthDerivatives()->end());
this->valmax =
*std::max_element(ast.GetSmoothingLengthDerivatives()->begin(), ast.GetSmoothingLengthDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::MOLECULAR_WEIGHT_DERIVATIVE:
this->valmin =
*std::min_element(ast.GetMolecularWeightDerivatives()->begin(), ast.GetMolecularWeightDerivatives()->end());
this->valmax =
*std::max_element(ast.GetMolecularWeightDerivatives()->begin(), ast.GetMolecularWeightDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::DENSITY_DERIVATIVE:
this->valmin = *std::min_element(ast.GetDensityDerivative()->begin(), ast.GetDensityDerivative()->end());
this->valmax = *std::max_element(ast.GetDensityDerivative()->begin(), ast.GetDensityDerivative()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::GRAVITATIONAL_POTENTIAL_DERIVATIVE:
this->valmin = *std::min_element(
ast.GetGravitationalPotentialDerivatives()->begin(), ast.GetGravitationalPotentialDerivatives()->end());
this->valmax = *std::max_element(
ast.GetGravitationalPotentialDerivatives()->begin(), ast.GetGravitationalPotentialDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::TEMPERATURE_DERIVATIVE:
this->valmin =
*std::min_element(ast.GetTemperatureDerivatives()->begin(), ast.GetTemperatureDerivatives()->end());
this->valmax =
*std::max_element(ast.GetTemperatureDerivatives()->begin(), ast.GetTemperatureDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::ENTROPY_DERIVATIVE:
this->valmin = *std::min_element(ast.GetEntropyDerivatives()->begin(), ast.GetEntropyDerivatives()->end());
this->valmax = *std::max_element(ast.GetEntropyDerivatives()->begin(), ast.GetEntropyDerivatives()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::AGN_DISTANCES:
this->valmin = *std::min_element(ast.GetAgnDistances()->begin(), ast.GetAgnDistances()->end());
this->valmax = *std::max_element(ast.GetAgnDistances()->begin(), ast.GetAgnDistances()->end());
break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_BARYON:
case megamol::astro::AstroParticleConverter::ColoringMode::IS_STAR:
case megamol::astro::AstroParticleConverter::ColoringMode::IS_WIND:
case megamol::astro::AstroParticleConverter::ColoringMode::IS_STAR_FORMING_GAS:
case megamol::astro::AstroParticleConverter::ColoringMode::IS_AGN:
case megamol::astro::AstroParticleConverter::ColoringMode::IS_DARK_MATTER:
default:
this->valmin = 0.0f;
this->valmax = 1.0f;
break;
}
this->minValueSlot.Param<param::FloatParam>()->SetValue(this->valmin);
this->maxValueSlot.Param<param::FloatParam>()->SetValue(this->valmax);
this->densityMin = *std::min_element(ast.GetDensity()->begin(), ast.GetDensity()->end());
this->densityMax = *std::max_element(ast.GetDensity()->begin(), ast.GetDensity()->end());
}
/*
* AstroParticleConverter::calcColorTable
*/
void AstroParticleConverter::calcColorTable(const AstroDataCall& ast) {
float value = 0.0f;
auto colmode = static_cast<ColoringMode>(this->colorModeSlot.Param<param::EnumParam>()->Value());
this->usedColors.resize(ast.GetPositions()->size());
auto minCol = glm::make_vec4(this->minColorSlot.Param<param::ColorParam>()->Value().data());
auto midCol = glm::make_vec4(this->midColorSlot.Param<param::ColorParam>()->Value().data());
auto maxCol = glm::make_vec4(this->maxColorSlot.Param<param::ColorParam>()->Value().data());
auto useMid = this->useMidColorSlot.Param<param::BoolParam>()->Value();
float denom = this->valmax - this->valmin;
switch (colmode) {
case megamol::astro::AstroParticleConverter::ColoringMode::MASS: {
auto v = ast.GetMass();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::INTERNAL_ENERGY: {
auto v = ast.GetInternalEnergy();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::SMOOTHING_LENGTH: {
auto v = ast.GetSmoothingLength();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::MOLECULAR_WEIGHT: {
auto v = ast.GetMolecularWeights();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::DENSITY: {
auto v = ast.GetDensity();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::GRAVITATIONAL_POTENTIAL: {
auto v = ast.GetGravitationalPotential();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::TEMPERATURE: {
auto v = ast.GetTemperature();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::ENTROPY: {
auto v = ast.GetEntropy();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_BARYON: {
auto v = ast.GetIsBaryonFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = maxCol : this->usedColors[i] = minCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_STAR: {
auto v = ast.GetIsStarFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = maxCol : this->usedColors[i] = minCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_WIND: {
auto v = ast.GetIsWindFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = maxCol : this->usedColors[i] = minCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_STAR_FORMING_GAS: {
auto v = ast.GetIsStarFormingGasFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = maxCol : this->usedColors[i] = minCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_AGN: {
auto v = ast.GetIsAGNFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = maxCol : this->usedColors[i] = minCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::IS_DARK_MATTER: { // inverse case to IS_BARYON
auto v = ast.GetIsBaryonFlags();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
v->at(i) ? this->usedColors[i] = minCol : this->usedColors[i] = maxCol;
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::INTERNAL_ENERGY_DERIVATIVE: {
auto v = ast.GetInternalEnergyDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::SMOOTHING_LENGTH_DERIVATIVE: {
auto v = ast.GetSmoothingLengthDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::MOLECULAR_WEIGHT_DERIVATIVE: {
auto v = ast.GetMolecularWeightDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::DENSITY_DERIVATIVE: {
auto v = ast.GetDensityDerivative();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::GRAVITATIONAL_POTENTIAL_DERIVATIVE: {
auto v = ast.GetGravitationalPotentialDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::TEMPERATURE_DERIVATIVE: {
auto v = ast.GetTemperatureDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::ENTROPY_DERIVATIVE: {
auto v = ast.GetEntropyDerivatives();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
case megamol::astro::AstroParticleConverter::ColoringMode::AGN_DISTANCES: {
auto v = ast.GetAgnDistances();
for (size_t i = 0; i < this->usedColors.size(); ++i) {
float alpha = (v->at(i) - this->valmin) / denom;
this->usedColors[i] = this->interpolateColor(minCol, midCol, maxCol, alpha, useMid);
}
} break;
default:
break;
}
}
/*
* AstroParticleConverter::interpolateColor
*/
glm::vec4 AstroParticleConverter::interpolateColor(const glm::vec4& minCol, const glm::vec4& midCol,
const glm::vec4& maxCol, const float alpha, const bool useMidValue) {
if (!useMidValue)
return glm::mix(minCol, maxCol, alpha);
if (alpha < 0.5f)
return glm::mix(minCol, midCol, alpha * 2.0f);
return glm::mix(midCol, maxCol, (alpha - 0.5f) * 2.0f);
}
| 48.804598 | 120 | 0.647668 | xge |
26c5dc8bacb68de7b88aa6813032cbf113f1dd44 | 1,083 | cpp | C++ | python2-pybind11/challenge/containers.cpp | lsst-dm/python-cpp-challenge | 8b49116d2e896960f901a01a3af7e95ef2f94499 | [
"MIT"
] | 20 | 2016-05-26T22:29:42.000Z | 2021-10-04T12:42:27.000Z | python2-pybind11/challenge/containers.cpp | lsst-dm/python-cpp-challenge | 8b49116d2e896960f901a01a3af7e95ef2f94499 | [
"MIT"
] | 2 | 2016-04-20T20:10:47.000Z | 2016-04-26T20:38:10.000Z | python2-pybind11/challenge/containers.cpp | lsst-dm/python-cpp-challenge | 8b49116d2e896960f901a01a3af7e95ef2f94499 | [
"MIT"
] | 1 | 2016-03-15T21:40:56.000Z | 2016-03-15T21:40:56.000Z | #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include "basics.hpp"
#include "containers.hpp"
namespace py = pybind11;
PYBIND11_DECLARE_HOLDER_TYPE(T, std::shared_ptr<T>);
PYBIND11_PLUGIN(containers) {
py::module m("containers", "wrapped C++ containers module");
py::class_<containers::DoodadSet> c(m, "DoodadSet");
c.def(py::init<>())
.def("__len__", &containers::DoodadSet::size)
.def("add", (void (containers::DoodadSet::*)(std::shared_ptr<basics::Doodad>)) &containers::DoodadSet::add)
.def("add", [](containers::DoodadSet &ds, std::pair<std::string, int> p) { ds.add(basics::WhatsIt{p.first, p.second}) ; })
.def("__iter__", [](containers::DoodadSet &ds) { return py::make_iterator(ds.begin(), ds.end()); },
py::keep_alive<0, 1>())
.def("as_dict", &containers::DoodadSet::as_map)
.def("as_list", &containers::DoodadSet::as_vector)
.def("assign", &containers::DoodadSet::assign);
c.attr("Item") = py::module::import("challenge.basics").attr("Doodad");
return m.ptr();
}
| 34.935484 | 130 | 0.635272 | lsst-dm |
26cf9fc6c5e46e6035df5ba15756118bbeb46264 | 16,484 | cpp | C++ | src/modules/AlignmentTrackChi2/AlignmentTrackChi2.cpp | simonspa/corryvreckan | ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436 | [
"MIT"
] | null | null | null | src/modules/AlignmentTrackChi2/AlignmentTrackChi2.cpp | simonspa/corryvreckan | ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436 | [
"MIT"
] | null | null | null | src/modules/AlignmentTrackChi2/AlignmentTrackChi2.cpp | simonspa/corryvreckan | ffa5d1f7a47341ab6eb1b6208c9e0c472a58f436 | [
"MIT"
] | null | null | null | /**
* @file
* @brief Implementation of module AlignmentTrackChi2
*
* @copyright Copyright (c) 2017-2022 CERN and the Corryvreckan authors.
* This software is distributed under the terms of the MIT License, copied verbatim in the file "LICENSE.md".
* In applying this license, CERN does not waive the privileges and immunities granted to it by virtue of its status as an
* Intergovernmental Organization or submit itself to any jurisdiction.
*/
#include "AlignmentTrackChi2.h"
#include <TVirtualFitter.h>
#include <numeric>
using namespace corryvreckan;
using namespace std;
// Global container declarations
TrackVector AlignmentTrackChi2::globalTracks;
std::shared_ptr<Detector> AlignmentTrackChi2::globalDetector;
int AlignmentTrackChi2::detNum;
AlignmentTrackChi2::AlignmentTrackChi2(Configuration& config, std::vector<std::shared_ptr<Detector>> detectors)
: Module(config, std::move(detectors)) {
config_.setDefault<size_t>("iterations", 3);
config_.setDefault<bool>("prune_tracks", false);
config_.setDefault<bool>("align_position", true);
config_.setDefault<bool>("align_orientation", true);
config_.setDefault<size_t>("max_associated_clusters", 1);
config_.setDefault<double>("max_track_chi2ndof", 10.);
nIterations = config_.get<size_t>("iterations");
m_pruneTracks = config_.get<bool>("prune_tracks");
m_alignPosition = config_.get<bool>("align_position");
if(m_alignPosition) {
LOG(INFO) << "Aligning positions";
}
m_alignOrientation = config_.get<bool>("align_orientation");
if(m_alignOrientation) {
LOG(INFO) << "Aligning orientations";
}
m_maxAssocClusters = config_.get<size_t>("max_associated_clusters");
m_maxTrackChi2 = config_.get<double>("max_track_chi2ndof");
LOG(INFO) << "Aligning telescope";
}
// During run, just pick up tracks and save them till the end
StatusCode AlignmentTrackChi2::run(const std::shared_ptr<Clipboard>& clipboard) {
// Get the tracks
auto tracks = clipboard->getData<Track>();
TrackVector alignmenttracks;
std::map<std::string, std::vector<Cluster*>> alignmentclusters;
// Make a local copy and store it
for(auto& track : tracks) {
// Apply selection to tracks for alignment - only allow tracks with certain Chi2/NDoF:
if(m_pruneTracks && track->getChi2ndof() > m_maxTrackChi2) {
LOG(DEBUG) << "Discarded track with Chi2/NDoF - " << track->getChi2ndof();
m_discardedtracks++;
continue;
}
LOG(TRACE) << "Storing track with track model \"" << track->getType() << "\" for alignment";
alignmenttracks.push_back(track);
for(auto& cluster : track->getClusters()) {
alignmentclusters[cluster->detectorID()].push_back(cluster);
}
}
// Store all tracks we want for alignment on the permanent storage:
clipboard->putPersistentData(alignmenttracks);
// Copy the objects of all track clusters on the clipboard to persistent storage:
for(auto& clusters : alignmentclusters) {
clipboard->copyToPersistentData(clusters.second, clusters.first);
}
// Otherwise keep going
return StatusCode::Success;
}
// ========================================
// Minimisation functions for Minuit
// ========================================
// METHOD 0
// This method will move the detector in question, refit all of the tracks, and
// try to minimise the
// track chi2. If there were no clusters from this detector on any tracks then
// it would do nothing!
void AlignmentTrackChi2::MinimiseTrackChi2(Int_t&, Double_t*, Double_t& result, Double_t* par, Int_t) {
LOG(DEBUG) << AlignmentTrackChi2::globalDetector->displacement() << "' " << globalDetector->rotation();
// Pick up new alignment conditions
AlignmentTrackChi2::globalDetector->displacement(
XYZPoint(par[detNum * 6 + 0], par[detNum * 6 + 1], par[detNum * 6 + 2]));
AlignmentTrackChi2::globalDetector->rotation(XYZVector(par[detNum * 6 + 3], par[detNum * 6 + 4], par[detNum * 6 + 5]));
// Apply new alignment conditions
AlignmentTrackChi2::globalDetector->update();
// The chi2 value to be returned
result = 0.;
// Loop over all tracks
for(auto& track : AlignmentTrackChi2::globalTracks) {
// Get all clusters on the track
auto trackClusters = track->getClusters();
// Find the cluster that needs to have its position recalculated
for(size_t iTrackCluster = 0; iTrackCluster < trackClusters.size(); iTrackCluster++) {
Cluster* trackCluster = trackClusters[iTrackCluster];
if(AlignmentTrackChi2::globalDetector->getName() != trackCluster->detectorID()) {
continue;
}
// Recalculate the global position from the local
auto positionLocal = trackCluster->local();
auto positionGlobal = AlignmentTrackChi2::globalDetector->localToGlobal(positionLocal);
trackCluster->setClusterCentre(positionGlobal);
LOG(DEBUG) << "Updating cluster with corrected global position for detector "
<< AlignmentTrackChi2::globalDetector->getName();
}
// Refit the track
track->registerPlane(AlignmentTrackChi2::globalDetector->getName(),
AlignmentTrackChi2::globalDetector->displacement().z(),
AlignmentTrackChi2::globalDetector->materialBudget(),
AlignmentTrackChi2::globalDetector->toLocal());
LOG(DEBUG) << "Updated transformations for detector " << AlignmentTrackChi2::globalDetector->getName();
track->fit();
// Add the new chi2
result += track->getChi2();
}
}
// ==================================================================
// The finalise function - effectively the brains of the alignment!
// ==================================================================
void AlignmentTrackChi2::finalize(const std::shared_ptr<ReadonlyClipboard>& clipboard) {
if(m_discardedtracks > 0) {
LOG(INFO) << "Discarded " << m_discardedtracks << " input tracks.";
}
// Make the fitting object
TVirtualFitter* residualFitter = TVirtualFitter::Fitter(nullptr, 50);
residualFitter->SetFCN(MinimiseTrackChi2);
// Set the global parameters
AlignmentTrackChi2::globalTracks = clipboard->getPersistentData<Track>();
// Set the printout arguments of the fitter
Double_t arglist[10];
arglist[0] = -1;
residualFitter->ExecuteCommand("SET PRINT", arglist, 1);
// Set some fitter parameters
arglist[0] = 1000; // number of function calls
arglist[1] = 0.001; // tolerance
// Store the alignment shifts per detector:
std::map<std::string, std::vector<double>> shiftsX;
std::map<std::string, std::vector<double>> shiftsY;
std::map<std::string, std::vector<double>> rotX;
std::map<std::string, std::vector<double>> rotY;
std::map<std::string, std::vector<double>> rotZ;
// Loop over all planes. For each plane, set the plane alignment parameters which will be varied, and then minimise the
// track chi2 (sum of biased residuals). This means that tracks are refitted with each minimisation step.
for(size_t iteration = 0; iteration < nIterations; iteration++) {
LOG_PROGRESS(STATUS, "alignment_track") << "Alignment iteration " << (iteration + 1) << " of " << nIterations;
int det = 0;
for(auto& detector : get_regular_detectors(false)) {
string detectorID = detector->getName();
// Do not align the reference plane
if(detector->isReference()) {
LOG(DEBUG) << "Skipping detector " << detector->getName();
continue;
}
// Say that this is the detector we align
AlignmentTrackChi2::globalDetector = detector;
detNum = det;
// Add the parameters to the fitter (z displacement not allowed to move!)
if(m_alignPosition) {
residualFitter->SetParameter(
det * 6 + 0, (detectorID + "_displacementX").c_str(), detector->displacement().X(), 0.01, -50, 50);
residualFitter->SetParameter(
det * 6 + 1, (detectorID + "_displacementY").c_str(), detector->displacement().Y(), 0.01, -50, 50);
} else {
residualFitter->SetParameter(
det * 6 + 0, (detectorID + "_displacementX").c_str(), detector->displacement().X(), 0, -50, 50);
residualFitter->SetParameter(
det * 6 + 1, (detectorID + "_displacementY").c_str(), detector->displacement().Y(), 0, -50, 50);
}
residualFitter->SetParameter(
det * 6 + 2, (detectorID + "_displacementZ").c_str(), detector->displacement().Z(), 0, -10, 500);
if(m_alignOrientation) {
residualFitter->SetParameter(
det * 6 + 3, (detectorID + "_rotationX").c_str(), detector->rotation().X(), 0.001, -6.30, 6.30);
residualFitter->SetParameter(
det * 6 + 4, (detectorID + "_rotationY").c_str(), detector->rotation().Y(), 0.001, -6.30, 6.30);
residualFitter->SetParameter(
det * 6 + 5, (detectorID + "_rotationZ").c_str(), detector->rotation().Z(), 0.001, -6.30, 6.30);
} else {
residualFitter->SetParameter(
det * 6 + 3, (detectorID + "_rotationX").c_str(), detector->rotation().X(), 0, -6.30, 6.30);
residualFitter->SetParameter(
det * 6 + 4, (detectorID + "_rotationY").c_str(), detector->rotation().Y(), 0, -6.30, 6.30);
residualFitter->SetParameter(
det * 6 + 5, (detectorID + "_rotationZ").c_str(), detector->rotation().Z(), 0, -6.30, 6.30);
}
auto old_position = detector->displacement();
auto old_orientation = detector->rotation();
// Fit this plane (minimising global track chi2)
LOG(DEBUG) << "fitting residuals for detetcor " << detector->getName();
residualFitter->ExecuteCommand("MIGRAD", arglist, 2);
// Retrieve fit results:
auto displacementX = residualFitter->GetParameter(det * 6 + 0);
auto displacementY = residualFitter->GetParameter(det * 6 + 1);
auto displacementZ = residualFitter->GetParameter(det * 6 + 2);
auto rotationX = residualFitter->GetParameter(det * 6 + 3);
auto rotationY = residualFitter->GetParameter(det * 6 + 4);
auto rotationZ = residualFitter->GetParameter(det * 6 + 5);
// Store corrections:
shiftsX[detectorID].push_back(
static_cast<double>(Units::convert(detector->displacement().X() - old_position.X(), "um")));
shiftsY[detectorID].push_back(
static_cast<double>(Units::convert(detector->displacement().Y() - old_position.Y(), "um")));
rotX[detectorID].push_back(
static_cast<double>(Units::convert(detector->rotation().X() - old_orientation.X(), "deg")));
rotY[detectorID].push_back(
static_cast<double>(Units::convert(detector->rotation().Y() - old_orientation.Y(), "deg")));
rotZ[detectorID].push_back(
static_cast<double>(Units::convert(detector->rotation().Z() - old_orientation.Z(), "deg")));
LOG(INFO) << detector->getName() << "/" << iteration << " dT"
<< Units::display(detector->displacement() - old_position, {"mm", "um"}) << " dR"
<< Units::display(detector->rotation() - old_orientation, {"deg"});
// Now that this device is fitted, set parameter errors to 0 so that they
// are not fitted again
residualFitter->SetParameter(det * 6 + 0, (detectorID + "_displacementX").c_str(), displacementX, 0, -50, 50);
residualFitter->SetParameter(det * 6 + 1, (detectorID + "_displacementY").c_str(), displacementY, 0, -50, 50);
residualFitter->SetParameter(det * 6 + 2, (detectorID + "_displacementZ").c_str(), displacementZ, 0, -10, 500);
residualFitter->SetParameter(det * 6 + 3, (detectorID + "_rotationX").c_str(), rotationX, 0, -6.30, 6.30);
residualFitter->SetParameter(det * 6 + 4, (detectorID + "_rotationY").c_str(), rotationY, 0, -6.30, 6.30);
residualFitter->SetParameter(det * 6 + 5, (detectorID + "_rotationZ").c_str(), rotationZ, 0, -6.30, 6.30);
// Set the alignment parameters of this plane to be the optimised values
// from the alignment
detector->displacement(XYZPoint(displacementX, displacementY, displacementZ));
detector->rotation(XYZVector(rotationX, rotationY, rotationZ));
detector->update();
det++;
}
}
LOG_PROGRESS(STATUS, "alignment_track") << "Alignment finished, " << nIterations << " iteration.";
// Now list the new alignment parameters
for(auto& detector : get_regular_detectors(false)) {
// Do not align the reference plane
if(detector->isReference()) {
continue;
}
LOG(STATUS) << detector->getName() << " new alignment: " << std::endl
<< "T" << Units::display(detector->displacement(), {"mm", "um"}) << " R"
<< Units::display(detector->rotation(), {"deg"});
// Fill the alignment convergence graphs:
std::vector<double> iterations(nIterations);
std::iota(std::begin(iterations), std::end(iterations), 0);
std::string name = "alignment_correction_displacementX_" + detector->getName();
align_correction_shiftX[detector->getName()] = new TGraph(
static_cast<int>(shiftsX[detector->getName()].size()), &iterations[0], &shiftsX[detector->getName()][0]);
align_correction_shiftX[detector->getName()]->GetXaxis()->SetTitle("# iteration");
align_correction_shiftX[detector->getName()]->GetYaxis()->SetTitle("correction [#mum]");
align_correction_shiftX[detector->getName()]->Write(name.c_str());
name = "alignment_correction_displacementY_" + detector->getName();
align_correction_shiftY[detector->getName()] = new TGraph(
static_cast<int>(shiftsY[detector->getName()].size()), &iterations[0], &shiftsY[detector->getName()][0]);
align_correction_shiftY[detector->getName()]->GetXaxis()->SetTitle("# iteration");
align_correction_shiftY[detector->getName()]->GetYaxis()->SetTitle("correction [#mum]");
align_correction_shiftY[detector->getName()]->Write(name.c_str());
name = "alignment_correction_rotationX_" + detector->getName();
align_correction_rotX[detector->getName()] =
new TGraph(static_cast<int>(rotX[detector->getName()].size()), &iterations[0], &rotX[detector->getName()][0]);
align_correction_rotX[detector->getName()]->GetXaxis()->SetTitle("# iteration");
align_correction_rotX[detector->getName()]->GetYaxis()->SetTitle("correction [deg]");
align_correction_rotX[detector->getName()]->Write(name.c_str());
name = "alignment_correction_rotationY_" + detector->getName();
align_correction_rotY[detector->getName()] =
new TGraph(static_cast<int>(rotY[detector->getName()].size()), &iterations[0], &rotY[detector->getName()][0]);
align_correction_rotY[detector->getName()]->GetXaxis()->SetTitle("# iteration");
align_correction_rotY[detector->getName()]->GetYaxis()->SetTitle("correction [deg]");
align_correction_rotY[detector->getName()]->Write(name.c_str());
name = "alignment_correction_rotationZ_" + detector->getName();
align_correction_rotZ[detector->getName()] =
new TGraph(static_cast<int>(rotZ[detector->getName()].size()), &iterations[0], &rotZ[detector->getName()][0]);
align_correction_rotZ[detector->getName()]->GetXaxis()->SetTitle("# iteration");
align_correction_rotZ[detector->getName()]->GetYaxis()->SetTitle("correction [deg]");
align_correction_rotZ[detector->getName()]->Write(name.c_str());
}
// Clean up local track storage
AlignmentTrackChi2::globalTracks.clear();
AlignmentTrackChi2::globalDetector.reset();
}
| 49.650602 | 123 | 0.624727 | simonspa |
26d1fb5bd0cfc1229f186e0bd233c7e3a0548ff6 | 8,892 | cc | C++ | wrspice/devlib/cap/cap.cc | wrcad/xictools | f46ba6d42801426739cc8b2940a809b74f1641e2 | [
"Apache-2.0"
] | 73 | 2017-10-26T12:40:24.000Z | 2022-03-02T16:59:43.000Z | wrspice/devlib/cap/cap.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 12 | 2017-11-01T10:18:22.000Z | 2022-03-20T19:35:36.000Z | wrspice/devlib/cap/cap.cc | chris-ayala/xictools | 4ea72c118679caed700dab3d49a8d36445acaec3 | [
"Apache-2.0"
] | 34 | 2017-10-06T17:04:21.000Z | 2022-02-18T16:22:03.000Z |
/*========================================================================*
* *
* Distributed by Whiteley Research Inc., Sunnyvale, California, USA *
* http://wrcad.com *
* Copyright (C) 2017 Whiteley Research Inc., all rights reserved. *
* Author: Stephen R. Whiteley, except as indicated. *
* *
* As fully as possible recognizing licensing terms and conditions *
* imposed by earlier work from which this work was derived, if any, *
* this work is released under the Apache License, Version 2.0 (the *
* "License"). You may not use this file except in compliance with *
* the License, and compliance with inherited licenses which are *
* specified in a sub-header below this one if applicable. A copy *
* of the License is provided with this distribution, or you may *
* obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* See the License for the specific language governing permissions *
* and limitations under the License. *
* *
* 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 NON- *
* INFRINGEMENT. IN NO EVENT SHALL WHITELEY RESEARCH INCORPORATED *
* OR STEPHEN R. WHITELEY 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. *
* *
*========================================================================*
* XicTools Integrated Circuit Design System *
* *
* WRspice Circuit Simulation and Analysis Tool: Device Library *
* *
*========================================================================*
$Id:$
*========================================================================*/
/***************************************************************************
JSPICE3 adaptation of Spice3f2 - Copyright (c) Stephen R. Whiteley 1992
Copyright 1990 Regents of the University of California. All rights reserved.
Authors: 1985 Thomas L. Quarles
1993 Stephen R. Whiteley
****************************************************************************/
#include "capdefs.h"
namespace {
IFparm CAPpTable[] = {
IO("capacitance", CAP_CAP, IF_PARSETREE|IF_CAP|IF_AC|IF_PRINCIPAL,
"Device capacitance"),
IO("cap", CAP_CAP, IF_PARSETREE|IF_CAP|IF_AC|IF_PRINCIPAL|IF_REDUNDANT,
"Device capacitance"),
IO("c", CAP_CAP, IF_PARSETREE|IF_CAP|IF_AC|IF_PRINCIPAL|IF_REDUNDANT,
"Device capacitance"),
IO("ic", CAP_IC, IF_REAL|IF_VOLT|IF_AC,
"Initial condition (capacitor voltage"),
IO("w", CAP_WIDTH, IF_REAL|IF_LEN|IF_AC,
"Capacitor width"),
IO("l", CAP_LENGTH, IF_REAL|IF_LEN|IF_AC,
"Capacitor length"),
IO("temp", CAP_TEMP, IF_REAL|IF_TEMP,
"Capacitor temperature"),
IO("tc1", CAP_TC1, IF_REAL|IF_SETQUERY,
"First order temp coeff."),
IO("tc2", CAP_TC2, IF_REAL|IF_ORQUERY,
"Second order temp coeff"),
IO("m", CAP_M, IF_REAL,
"Parallel multiplier"),
IO("poly", CAP_POLY, IF_REALVEC,
"Capacitance polynomial"),
OP("charge", CAP_CHARGE, IF_REAL|IF_CHARGE,
"Capacitor charge"),
OP("v", CAP_VOLTAGE, IF_REAL|IF_VOLT,
"Capacitor voltage"),
OP("i", CAP_CURRENT, IF_REAL|IF_AMP|IF_USEALL,
"Capacitor current"),
OP("p", CAP_POWER, IF_REAL|IF_POWR,
"Instantaneous stored power"),
OP("node1", CAP_POSNODE, IF_INTEGER,
"Node 1 number"),
OP("node2", CAP_NEGNODE, IF_INTEGER,
"Node 2 number"),
OP("expr", CAP_TREE, IF_PARSETREE,
"Capacitance expression")
};
IFparm CAPmPTable[] = {
IP("c", CAP_MOD_C, IF_FLAG,
"Capacitor model"),
IO("cj", CAP_MOD_CJ, IF_REAL|IF_AC,
"Bottom Capacitance per area"),
IO("cjsw", CAP_MOD_CJSW, IF_REAL|IF_AC,
"Sidewall capacitance per meter"),
IO("defw", CAP_MOD_DEFWIDTH, IF_REAL|IF_NONSENSE,
"Default width"),
IO("narrow", CAP_MOD_NARROW, IF_REAL|IF_AC,
"Width correction factor"),
IO("tnom", CAP_MOD_TNOM, IF_REAL|IF_NONSENSE,
"Parameter measurement temperature"),
IO("tc1", CAP_MOD_TC1, IF_REAL|IF_SETQUERY,
"First order temp. coefficient"),
IO("tc2", CAP_MOD_TC2, IF_REAL|IF_ORQUERY,
"Second order temp. coefficient"),
IO("m", CAP_M, IF_REAL,
"Default parallel multiplier")
};
const char *CAPnames[] = {
"C+",
"C-"
};
const char *CAPmodNames[] = {
"c",
0
};
IFkeys CAPkeys[] = {
IFkeys( 'c', CAPnames, 2, 2, 0 )
};
} // namespace
CAPdev::CAPdev()
{
dv_name = "Capacitor";
dv_description = "Fixed capacitor model";
dv_numKeys = NUMELEMS(CAPkeys);
dv_keys = CAPkeys,
dv_levels[0] = 1;
dv_levels[1] = 0;
dv_modelKeys = CAPmodNames;
dv_numInstanceParms = NUMELEMS(CAPpTable);
dv_instanceParms = CAPpTable;
dv_numModelParms = NUMELEMS(CAPmPTable);
dv_modelParms = CAPmPTable;
dv_flags = DV_TRUNC;
};
sGENmodel *
CAPdev::newModl()
{
return (new sCAPmodel);
}
sGENinstance *
CAPdev::newInst()
{
return (new sCAPinstance);
}
int
CAPdev::destroy(sGENmodel **model)
{
return (IFdevice::destroy<sCAPmodel, sCAPinstance>(model));
}
int
CAPdev::delInst(sGENmodel *model, IFuid dname, sGENinstance *fast)
{
return (IFdevice::delInst<sCAPmodel, sCAPinstance>(model, dname,
fast));
}
int
CAPdev::delModl(sGENmodel **model, IFuid modname, sGENmodel *modfast)
{
return (IFdevice::delModl<sCAPmodel, sCAPinstance>(model, modname,
modfast));
}
// capacitor parser
// Cname <node> <node> [<model>] [<val>] [IC=<val>]
//
void
CAPdev::parse(int type, sCKT *ckt, sLine *current)
{
DEV.parse(ckt, current, type, dv_keys->minTerms, dv_keys->maxTerms,
true, "capacitance");
}
// Setup the tran parameters for any tran function nodes.
//
void
CAPdev::initTranFuncs(sGENmodel *modp, double step, double finaltime)
{
for (sCAPmodel *model = (sCAPmodel*)modp; model; model = model->next()) {
for (sCAPinstance *inst = (sCAPinstance*)model->GENinstances;
inst; inst = inst->next()) {
if (inst->CAPtree)
inst->CAPtree->initTranFuncs(step, finaltime);
}
}
}
// Below is hugely GCC-specific. The __WRMODULE__ and __WRVERSION__
// tokens are defined in the Makefile and passed with -D when
// compiling.
#define STR(x) #x
#define STRINGIFY(x) STR(x)
#define MCAT(x, y) x ## y
#define MODNAME(x, y) MCAT(x, y)
// Module initializer. Sets locations in the main app to some
// identifying strings.
//
__attribute__((constructor)) static void initializer()
{
extern const char *WRS_ModuleName, *WRS_ModuleVersion;
WRS_ModuleName = STRINGIFY(__WRMODULE__);
WRS_ModuleVersion = STRINGIFY(__WRVERSION__);
}
// Device constructor function. This should be the only globally
// visible symbol in the module. The function name expands to the
// module name with trailing _c.
//
extern "C" {
void
MODNAME(__WRMODULE__, _c)(IFdevice **d, int *cnt)
{
*d = new CAPdev;
(*cnt)++;
}
}
| 35.854839 | 96 | 0.507647 | wrcad |
26d370da1d9b1d2b5492e9508791cea6ea35898f | 3,033 | cpp | C++ | src/detail/matrix/atlas_library.cpp | qjiang310/PRNN-GRU | 868ea7978e5805021ba4d3091404adde0912b45c | [
"Apache-2.0"
] | 640 | 2016-06-20T18:27:15.000Z | 2022-02-17T16:31:11.000Z | src/detail/matrix/atlas_library.cpp | qjiang310/PRNN-GRU | 868ea7978e5805021ba4d3091404adde0912b45c | [
"Apache-2.0"
] | 12 | 2016-06-21T01:30:41.000Z | 2020-08-11T18:40:34.000Z | src/detail/matrix/atlas_library.cpp | qjiang310/PRNN-GRU | 868ea7978e5805021ba4d3091404adde0912b45c | [
"Apache-2.0"
] | 116 | 2016-06-20T18:27:24.000Z | 2022-02-02T20:19:12.000Z | /* \file AtlasLibrary.cpp
\brief The source file for the AtlasLibrary class.
*/
// Persistent RNN Includes
#include <prnn/detail/matrix/atlas_library.h>
#include <prnn/detail/util/casts.h>
#include <prnn/detail/util/logger.h>
// Standard Library Includes
#include <stdexcept>
// System-Specific Includes
#include <dlfcn.h>
namespace prnn
{
namespace matrix
{
void AtlasLibrary::load()
{
_interface.load();
}
bool AtlasLibrary::loaded()
{
load();
return _interface.loaded();
}
void AtlasLibrary::sgemm(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const float alpha, const float *A,
const int lda, const float *B, const int ldb,
const float beta, float *C, const int ldc)
{
_check();
(*_interface.cblas_sgemm)(Order, TransA, TransB, M, N, K, alpha, A, lda, B,
ldb, beta, C, ldc);
}
void AtlasLibrary::dgemm(const int Order, const int TransA,
const int TransB, const int M, const int N,
const int K, const double alpha, const double* A,
const int lda, const double* B, const int ldb,
const double beta, double* C, const int ldc)
{
_check();
(*_interface.cblas_dgemm)(Order, TransA, TransB, M, N, K, alpha, A, lda, B,
ldb, beta, C, ldc);
}
void AtlasLibrary::_check()
{
load();
if(!loaded())
{
throw std::runtime_error("Tried to call ATLAS function when "
"the library is not loaded. Loading library failed, consider "
"installing ATLAS.");
}
}
AtlasLibrary::Interface::Interface()
: _library(nullptr), _failed(false)
{
}
AtlasLibrary::Interface::~Interface()
{
unload();
}
static void checkFunction(void* pointer, const std::string& name)
{
if(pointer == nullptr)
{
throw std::runtime_error("Failed to load function '" + name +
"' from dynamic library.");
}
}
void AtlasLibrary::Interface::load()
{
if(_failed) return;
if(loaded()) return;
#ifdef __APPLE__
const char* libraryName = "libcblas.dylib";
#else
const char* libraryName = "libcblas.so.3";
#endif
_library = dlopen(libraryName, RTLD_LAZY);
util::log("AtlasLibrary") << "Loading library '" << libraryName << "'\n";
if(!loaded())
{
util::log("AtlasLibrary") << " Failed to load library '" << libraryName
<< "'\n";
_failed = true;
return;
}
#define DynLink( function ) util::bit_cast(function, \
dlsym(_library, #function)); checkFunction((void*)function, #function)
DynLink(cblas_sgemm);
DynLink(cblas_dgemm);
#undef DynLink
util::log("AtlasLibrary") << " Loaded library '" << libraryName
<< "' successfully\n";
}
bool AtlasLibrary::Interface::loaded() const
{
return _library != nullptr;
}
void AtlasLibrary::Interface::unload()
{
if(!loaded()) return;
dlclose(_library);
_library = nullptr;
}
AtlasLibrary::Interface AtlasLibrary::_interface;
}
}
| 20.632653 | 79 | 0.626442 | qjiang310 |
26d3de3078e6e7b924bc6f727b6eb1a38dfd8092 | 2,528 | cpp | C++ | src/widgetsgui/main/applicationerrorview.cpp | squeevee/Addle | 20ec4335669fbd88d36742f586899d8416920959 | [
"MIT"
] | 3 | 2020-03-05T06:36:51.000Z | 2020-06-20T03:25:02.000Z | src/widgetsgui/main/applicationerrorview.cpp | squeevee/Addle | 20ec4335669fbd88d36742f586899d8416920959 | [
"MIT"
] | 13 | 2020-03-11T17:43:42.000Z | 2020-12-11T03:36:05.000Z | src/widgetsgui/main/applicationerrorview.cpp | squeevee/Addle | 20ec4335669fbd88d36742f586899d8416920959 | [
"MIT"
] | 1 | 2020-09-28T06:53:46.000Z | 2020-09-28T06:53:46.000Z | /**
* Addle source code
* @file
* @copyright Copyright 2020 Eleanor Hawk
* @copyright Modification and distribution permitted under the terms of the
* MIT License. See "LICENSE" for full details.
*/
#include <QCloseEvent>
#ifdef ADDLE_DEBUG
#include "exceptions/unhandledexception.hpp"
#endif
#include "applicationerrorview.hpp"
using namespace Addle;
ModalErrorDialog::ModalErrorDialog(IErrorPresenter& presenter, QWidget* parent)
: QMessageBox(parent), _presenter(presenter)
{
switch(_presenter.severity())
{
case IErrorPresenter::Info:
setWindowModality(Qt::NonModal);
setIcon(QMessageBox::Icon::Information);
break;
case IErrorPresenter::Warning:
if (parentWidget())
setWindowModality(Qt::WindowModal);
else
setWindowModality(Qt::NonModal);
setIcon(QMessageBox::Icon::Warning);
break;
case IErrorPresenter::Critical:
setWindowModality(Qt::ApplicationModal);
setIcon(QMessageBox::Icon::Critical);
break;
}
setText(presenter.message());
#ifdef ADDLE_DEBUG
if (presenter.exception() && presenter.exception()->isLogicError())
{
// thanks https://stackoverflow.com/a/38371503/2808947
setStyleSheet(
"QTextEdit {"
"font-family: monospace;"
"min-width: 720px;"
"}");
if (typeid(*presenter.exception()) == typeid(UnhandledException))
{
auto ex = dynamic_cast<const UnhandledException&>(*presenter.exception());
if (ex.addleException())
{
setDetailedText(ex.addleException()->what());
}
else if (ex.stdException())
{
setDetailedText(ex.stdException()->what());
}
}
}
#endif
}
void ModalErrorDialog::closeEvent(QCloseEvent* event)
{
event->accept();
emit closeEventAccepted();
}
void ApplicationErrorView::initialize(IErrorPresenter& presenter)
{
const Initializer init(_initHelper);
_presenter = &presenter;
_dialog = std::unique_ptr<ModalErrorDialog>(new ModalErrorDialog(presenter));
connect(_dialog.get(), &ModalErrorDialog::closeEventAccepted, this, &ApplicationErrorView::closed);
connect(_dialog.get(), &ModalErrorDialog::destroyed, this, &ApplicationErrorView::deleteLater);
}
void ApplicationErrorView::show()
{
ASSERT_INIT();
_dialog->show();
}
void ApplicationErrorView::close()
{
ASSERT_INIT();
_dialog->close();
} | 26.333333 | 103 | 0.64913 | squeevee |
26d8c5e906976ca5ee2859231eb676eb91d7f49e | 1,900 | cpp | C++ | algo/geometry/halfplanes.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | 13 | 2017-07-04T14:58:47.000Z | 2022-03-23T09:04:41.000Z | algo/geometry/halfplanes.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | null | null | null | algo/geometry/halfplanes.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | 5 | 2017-10-14T21:48:20.000Z | 2018-06-18T12:12:15.000Z | #include <bits/stdc++.h>
using namespace std;
#define forn(i, n) for (int i = 0; i < int(n); ++i)
#define all(x) x.begin(), x.end()
#include "primitives.cpp"
typedef vector<int> vi;
bool cmpLine(const line &a, const line &b) {
bool au = a.v.up(), bu = b.v.up();
if (au != bu)
return au;
ld prod = a.v % b.v;
if (!ze(prod))
return prod > 0;
// the strongest constraint is first for correct unique
return a.c > b.c;
}
bool eqLine(const line &a, const line &b) {
return a.v.up() == b.v.up() && ze(a.v % b.v);
}
//BEGIN_CODE
ld det3x3(line a, line b, line c) {
return a.c * (b.v % c.v)
+ b.c * (c.v % a.v)
+ c.c * (a.v % b.v);
}
//check: bounding box is included
vector<pt> halfplanesIntersection(vector<line> l) {
sort(all(l), cmpLine); //the strongest constraint is first
l.erase(unique(all(l), eqLine), l.end());
int n = sz(l);
vi st;
forn (iter, 2)
forn (i, n) {
while (sz(st) > 1) {
int j = st.back(), k = *next(st.rbegin());
if (l[k].v % l[i].v <= eps ||
det3x3(l[k], l[j], l[i]) <= eps)
break;
st.pop_back();
}
st.push_back(i);
}
vi pos(n, -1);
bool ok = false;
forn (i, sz(st)) {
int id = st[i];
if (pos[id] != -1) {
st = vi(st.begin() + pos[id], st.begin() + i);
ok = true;
break;
} else
pos[id] = i;
}
if (!ok)
return {};
vector<pt> res;
pt M{0, 0};
int k = sz(st);
forn (i, k) {
line l1 = l[st[i]], l2 = l[st[(i + 1) % k]];
res.push_back(linesIntersection(l1, l2));
M = M + res.back();
}
M = M * (1. / k);
for (int id: st)
if (l[id].signedDist(M) < -eps)
return {};
return res;
}
| 25 | 62 | 0.449474 | agrishutin |
26d9481b3574ba5b9410df17ae55c204a20c22ca | 1,203 | cpp | C++ | qt/infrastructure/EfotoDoubleSpinBox.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | 3 | 2021-06-28T21:07:58.000Z | 2021-07-02T11:21:49.000Z | qt/infrastructure/EfotoDoubleSpinBox.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | null | null | null | qt/infrastructure/EfotoDoubleSpinBox.cpp | e-foto/e-foto | cf143a1076c03c7bdf5a2f41efad2c98e9272722 | [
"FTL"
] | null | null | null | #include "EfotoDoubleSpinBox.h"
#include <QDebug>
namespace br {
namespace uerj {
namespace eng {
namespace efoto {
EfotoDoubleSpinBox::EfotoDoubleSpinBox(QWidget *parent):QDoubleSpinBox(parent)
{
installEventFilter(this);
}
bool EfotoDoubleSpinBox::eventFilter(QObject *obj, QEvent *evt)
{
if (evt->type()==QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(evt);
keyPressEvent(keyEvent);
return true;
}else
{
return QDoubleSpinBox::eventFilter(obj,evt);
}
}
void EfotoDoubleSpinBox::keyPressEvent(QKeyEvent *event)
{
//qDebug()<<"tecla apertada"<< event->key();
if(event->key()==Qt::Key_Period )
{
if(locale().decimalPoint()==',')
{
keyPressEvent(new QKeyEvent(QEvent::KeyPress,Qt::Key_Comma,event->modifiers(),","));
//return;
}
else
QDoubleSpinBox::keyPressEvent(event);
}
else if(event->key()==Qt::Key_Comma)
{
if(locale().decimalPoint()=='.')
{
keyPressEvent(new QKeyEvent(QEvent::KeyPress,Qt::Key_Period,event->modifiers(),"."));
//return;
}
else
QDoubleSpinBox::keyPressEvent(event);
}
else
QDoubleSpinBox::keyPressEvent(event);
}
} // namespace efoto
} // namespace eng
} // namespace uerj
} // namespace br
| 18.507692 | 88 | 0.689111 | e-foto |
26dd047117f0b7d397950081207cad409aec01ce | 1,155 | hpp | C++ | raytracer/hittable_list.hpp | chenmx00/RayTracer | c818aaf26be514c4247366f78d4f8ab060bdcf1d | [
"MIT"
] | 1 | 2020-09-27T08:14:01.000Z | 2020-09-27T08:14:01.000Z | raytracer/hittable_list.hpp | chenmx00/RayTracer | c818aaf26be514c4247366f78d4f8ab060bdcf1d | [
"MIT"
] | null | null | null | raytracer/hittable_list.hpp | chenmx00/RayTracer | c818aaf26be514c4247366f78d4f8ab060bdcf1d | [
"MIT"
] | null | null | null | //
// hittable_list.hpp
// raytracer
//
// Created by Minxing Chen on 11/6/21.
// Copyright © 2021 Minxing Chen. All rights reserved.
//
#ifndef hittable_list_hpp
#define hittable_list_hpp
#include "hittable.hpp"
#include <memory>
#include <vector>
using std::shared_ptr;
using std::make_shared;
class hittable_list : public hittable {
public:
hittable_list(){}
hittable_list(shared_ptr<hittable> object){add(object);}
void clear(){objects.clear();}
void add(shared_ptr<hittable> object){objects.push_back(object);}
virtual bool hit(const ray& r, double t_min, double t_max, hit_record &rec) const override;
public:
std::vector<shared_ptr<hittable>> objects;
};
bool hittable_list::hit(const ray &r, double t_min, double t_max, hit_record &rec) const {
hit_record temp_rec;
bool hit_anything = false;
auto closet_so_far = t_max;
for (const auto& object : objects){
if (object->hit(r, t_min, closet_so_far, temp_rec)){
hit_anything = true;
closet_so_far = temp_rec.t;
rec = temp_rec;
}
}
return hit_anything;
}
#endif /* hittable_list_hpp */
| 25.666667 | 95 | 0.678788 | chenmx00 |
26e15299600841d637b59ed738396fd4114ca7f3 | 1,539 | cpp | C++ | NetServer/EventLoopThread.cpp | lddddd1997/NetServer | 940b84bef7d0856bc2fe5f16164bfe041e4d4c9f | [
"MIT"
] | null | null | null | NetServer/EventLoopThread.cpp | lddddd1997/NetServer | 940b84bef7d0856bc2fe5f16164bfe041e4d4c9f | [
"MIT"
] | null | null | null | NetServer/EventLoopThread.cpp | lddddd1997/NetServer | 940b84bef7d0856bc2fe5f16164bfe041e4d4c9f | [
"MIT"
] | null | null | null | /**
* @file EventLoopThread.cpp
* @brief 事件循环IO线程one loop per thread
* @author lddddd (https://github.com/lddddd1997)
*/
#include <iostream>
#include "EventLoopThread.h"
EventLoopThread::EventLoopThread() :
thread_id_(-1),
loop_(nullptr)
{
}
EventLoopThread::~EventLoopThread()
{
// std::cout << "Clean up the IO thread id: " << thread_id_ << std::endl;
if(loop_ != nullptr)
{
loop_->Quit();
if(thread_.joinable())
{
thread_.join(); // 清理IO线程
}
}
}
EventLoop* EventLoopThread::StartLoop()
{
thread_ = std::thread(&EventLoopThread::RunInThread, this); // thread& operator=(thread&& __t) noexcept
EventLoop *loop;
{
std::unique_lock<std::mutex> lock(mutex_);
while(loop_ == nullptr)
{
condition_.wait(lock); // 等待线程创建好后通知,否则会出现返回的loop_为nullptr
}
loop = loop_;
}
return loop;
}
void EventLoopThread::RunInThread()
{
thread_id_ = std::this_thread::get_id();
// std::cout << "The IO thread is running, thread id = " << thread_id_ << std::endl;
EventLoop loop("IO");
{
std::lock_guard<std::mutex> lock(mutex_);
loop_ = &loop;
condition_.notify_one();
}
try
{
loop_->Looping();
}
catch(const std::exception& ex)
{
std::cerr << "exception caught int EventLoopThread::RunInThread at: " << thread_id_ << std::endl;
std::cerr << "reason: " << ex.what() << std::endl;
exit(EXIT_FAILURE);
}
}
| 23.318182 | 107 | 0.576348 | lddddd1997 |
26e8fd20c5d862c8a1caff19af6fe46a66fd4803 | 3,365 | hpp | C++ | Quartz/Engine/Include/Quartz/Utilities/Plugin.hpp | JosiahWI/QuartzEngine | 1289fc74f15218d791a9558964eaef90ca10c1cc | [
"BSD-3-Clause"
] | 38 | 2019-02-23T08:53:36.000Z | 2019-10-10T04:07:26.000Z | Quartz/Engine/Include/Quartz/Utilities/Plugin.hpp | JosiahWI/QuartzEngine | 1289fc74f15218d791a9558964eaef90ca10c1cc | [
"BSD-3-Clause"
] | 50 | 2019-03-01T01:43:02.000Z | 2019-10-04T20:10:44.000Z | Quartz/Engine/Include/Quartz/Utilities/Plugin.hpp | JosiahWI/QuartzEngine | 1289fc74f15218d791a9558964eaef90ca10c1cc | [
"BSD-3-Clause"
] | 13 | 2019-03-03T01:26:40.000Z | 2019-08-27T02:54:25.000Z | // Copyright 2019 Genten Studios
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <Quartz/Core.hpp>
#if defined(QZ_PLATFORM_WINDOWS)
#include <Windows.h>
#elif defined(QZ_PLATFORM_LINUX) || defined(QZ_PLATFORM_APPLE)
#include <dlfcn.h>
#endif
#include <string>
#include <system_error>
#include <exception>
namespace qz
{
namespace utils
{
class Plugin
{
public:
Plugin();
Plugin(const std::string& path);
~Plugin();
void load(const std::string& path);
void unload();
template <typename T>
T get(const std::string& procname)
{
T funcptr;
#if defined(QZ_PLATFORM_WINDOWS)
if (NULL == (funcptr = reinterpret_cast<T>(GetProcAddress(m_hInstance, procname.c_str()))))
{
throw std::system_error(
std::error_code(::GetLastError(), std::system_category())
, std::string("Couldn't find ") + procname
);
}
#elif defined(QZ_PLATFORM_LINUX) || defined(QZ_PLATFORM_APPLE)
if (NULL == (funcptr = reinterpret_cast<T>(dlsym(m_hInstance, procname.c_str()))))
{
throw std::system_error(
std::error_code(errno, std::system_category())
, std::string("Couldn't find ") + procname + ", " + std::string(dlerror())
);
}
#endif
return funcptr;
}
private:
#if defined(QZ_PLATFORM_WINDOWS)
HINSTANCE m_hInstance;
#elif defined(QZ_PLATFORM_LINUX) || defined(QZ_PLATFORM_APPLE)
void* m_hInstance;
#endif
std::string m_path;
bool m_loaded;
};
} // namespace utils
} // namespace qz | 36.182796 | 107 | 0.638039 | JosiahWI |
26ebb350cf58c0f8505494cc70ab18e31affb8c6 | 5,908 | cpp | C++ | test/texturetest.cpp | CasualYT31/ComputerWars | 0a011e6b87fab3798093db4211af166607d44243 | [
"MIT"
] | 4 | 2020-04-21T01:45:34.000Z | 2021-07-08T22:48:59.000Z | test/texturetest.cpp | CasualYT31/ComputerWars | 0a011e6b87fab3798093db4211af166607d44243 | [
"MIT"
] | 9 | 2020-04-16T18:05:44.000Z | 2022-01-24T16:29:34.000Z | test/texturetest.cpp | CasualYT31/ComputerWars | 0a011e6b87fab3798093db4211af166607d44243 | [
"MIT"
] | null | null | null | /*Copyright 2019-2021 CasualYouTuber31 <naysar@protonmail.com>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify,
merge, publish, distribute, sublicense, and/or sell copies of the
Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**@file texturetest.h
* Tests the \c sfx::animated_spritesheet class.
*/
#include "sharedfunctions.h"
#include "texture.h"
/**
* This test fixture is used to initialise testing objects.
*/
class TextureTest : public ::testing::Test {
protected:
/**
* Prepares and loads configuration scripts for all objects before all tests.
*/
void SetUp() override {
if (isTest({ "LoadValidScript" })) {
setupRendererJSONScript();
// setup the standard texture test script
setupJSONScript([](nlohmann::json& j) {
j["path"] = getTestAssetPath("sprites/sheet.png");
j["frames"] = 1;
j["framerate"] = 0.0;
j["sprites"] = R"([
[0,0,100,100],
[100,0,100,100],
[0,100,100,100],
[100,100,100,100]
])"_json;
}, "sprites/sheet.json");
// setup the multi-frame texture test script
setupJSONScript([](nlohmann::json& j) {
j["path"] = getTestAssetPath("sprites/sheet.png");
j["frames"] = 6;
j["framerate"] = 0.0;
j["sprites"] = R"([
[0,0,200,200]
])"_json;
}, "sprites/multi.json");
// setup the animated texture test script
setupJSONScript([](nlohmann::json& j) {
j["path"] = getTestAssetPath("sprites/sheet.png");
j["frames"] = 6;
j["framerate"] = 2.0;
j["sprites"] = R"([
[0,0,200,200]
])"_json;
}, "sprites/ani.json");
}
// always load the texture script at the beginning of every test
if (isTest({ "AnimatedSprite", "AnimatedSpriteLaggy" })) {
sheet->load(getTestAssetPath("sprites/ani.json"));
} else if (isTest({ "ManualFrameSelection" })) {
sheet->load(getTestAssetPath("sprites/multi.json"));
} else {
sheet->load(getTestAssetPath("sprites/sheet.json"));
}
// load the renderer script at the beginning of most tests
if (!isTest({ "LoadValidScript", "LoadInvalidScript" })) {
window.load(getTestAssetPath("renderer/renderer.json"));
}
// setup animated_sprite
sprite.setSpritesheet(sheet);
sprite.setSprite(0);
}
/**
* The \c animated_spritehseet object to test.
*/
std::shared_ptr<sfx::animated_spritesheet> sheet =
std::make_shared<sfx::animated_spritesheet>();
/**
* The \c renderer object to test sprites with.
*/
sfx::renderer window;
/**
* The animated sprite object to test with.
*/
sfx::animated_sprite sprite;
/**
* A timer object.
*/
sf::Clock timer;
};
/**
* Tests the behaviour of \c sfx::animated_spritesheet::load().
*/
TEST_F(TextureTest, LoadValidScript) {
EXPECT_NO_THROW(sheet->accessTexture(0));
EXPECT_THROW(sheet->accessTexture(1), std::out_of_range);
}
/**
* Tests the behaviour of loading an invalid script.
* The state of the \c animated_spritesheet object should be retained in case the
* \c path key was invalid.
*/
TEST_F(TextureTest, LoadInvalidScript) {
sheet->load(getTestAssetPath("sprites/faultysheet.json"));
EXPECT_NO_THROW(sheet->accessTexture(0));
}
#ifdef COMPUTER_WARS_FULL_TEXTURE_TESTING
/**
* Tests the behaviour of ordinary sprites.
*/
TEST_F(TextureTest, OrdinarySprites) {
window.openWindow();
timer.restart();
for (;;) {
window.clear();
window.animate(sprite);
window.draw(sprite);
window.display();
if (timer.getElapsedTime().asSeconds() >= 1.0) {
if (sprite.getSprite() == 3) break;
sprite.setSprite(sprite.getSprite() + 1);
timer.restart();
}
}
}
/**
* Tests the behaviour of an animated sprite.
*/
TEST_F(TextureTest, AnimatedSprite) {
window.openWindow();
timer.restart();
while (timer.getElapsedTime().asSeconds() < 3.5) {
window.clear();
window.animate(sprite);
window.draw(sprite, sf::RenderStates().transform.translate(50.0, 50.0));
window.display();
}
}
/**
* Tests the behaviour of an animated sprite in a laggy environment.
* Frames should be skipped.
*/
TEST_F(TextureTest, AnimatedSpriteLaggy) {
window.openWindow();
timer.restart();
int counter = 0;
while (counter < 4) {
window.clear();
if (!counter) {
window.animate(sprite);
counter++;
}
// can't be >= 1.0f because that's the delta timeout,
// then the animation won't progress at all
if (timer.getElapsedTime().asSeconds() >= 0.9f) {
window.animate(sprite);
timer.restart();
counter++;
}
window.draw(sprite, sf::RenderStates().transform.translate(50.0, 50.0));
window.display();
}
}
/**
* Tests the behaviour of manually selecting a sprite's frame.
*/
TEST_F(TextureTest, ManualFrameSelection) {
bool flip = false;
window.openWindow();
timer.restart();
for (;;) {
window.clear();
window.animate(sprite);
window.draw(sprite, sf::RenderStates().transform.scale(1.25, 1.25));
window.display();
if (timer.getElapsedTime().asSeconds() >= 1.0) {
if (sprite.getCurrentFrame() == 5) flip = true;
if (flip) {
if (--sprite == 5) break;
} else {
sprite++;
}
timer.restart();
}
}
}
#endif | 27.607477 | 81 | 0.683311 | CasualYT31 |
26ebc0db56a6cfb2d8c5a4925fbf00712faa32c8 | 3,663 | cpp | C++ | src/samplers/SamplerCapCVT/gx_capcvt2d/generated/L.cpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 44 | 2018-01-09T19:56:29.000Z | 2022-03-03T06:38:54.000Z | src/samplers/SamplerCapCVT/gx_capcvt2d/generated/L.cpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 16 | 2018-01-29T18:01:42.000Z | 2022-03-31T07:01:09.000Z | src/samplers/SamplerCapCVT/gx_capcvt2d/generated/L.cpp | FrancoisGaits/utk | 8c408dd79635f98c46ed075c098f15e23972aad0 | [
"BSD-2-Clause-FreeBSD"
] | 12 | 2018-03-14T00:24:14.000Z | 2022-03-03T06:40:07.000Z | #include "L.h"
namespace Geex {
L::L() : Function(1,6,0){}
void L::eval(bool do_f, bool do_g, bool do_H) {
if(do_f) {
{
double tmp_1 = x(5);
double tmp_2 = x(1);
double tmp_3 = -tmp_2;
double tmp_4 = tmp_3+tmp_1;
double tmp_5 = x(3);
double tmp_6 = tmp_3+tmp_5;
double tmp_8 = x(0);
double tmp_9 = x(2);
double tmp_10 = -tmp_9;
double tmp_11 = tmp_10+tmp_8;
double tmp_12 = x(4);
double tmp_13 = -tmp_8;
double tmp_14 = tmp_13+tmp_12;
double f0 = -((tmp_6*tmp_6)+tmp_4*tmp_6-tmp_11*tmp_14+(tmp_14*tmp_14)+(tmp_11*tmp_11)+(tmp_4*tmp_4))*(tmp_4*tmp_11+tmp_6*tmp_14);
f(0) = f0;
}
}
if(do_g) {
{
double tmp_1 = x(4);
double tmp_2 = x(0);
double tmp_4 = x(2);
double tmp_6 = x(3);
double tmp_7 = x(1);
double tmp_8 = -tmp_7;
double tmp_9 = tmp_6+tmp_8;
double tmp_10 = -tmp_2;
double tmp_11 = tmp_10+tmp_1;
double tmp_13 = -tmp_4;
double tmp_14 = tmp_13+tmp_2;
double tmp_15 = x(5);
double tmp_16 = tmp_15+tmp_8;
double g0_0 = (tmp_6-tmp_15)*((tmp_14*tmp_14)+(tmp_9*tmp_9)+(tmp_16*tmp_16)+tmp_16*tmp_9+(tmp_11*tmp_11)-tmp_11*tmp_14)-3.0*(tmp_9*tmp_11+tmp_16*tmp_14)*(2.0*tmp_2-tmp_1-tmp_4);
g(0,0) = g0_0;
}
{
double tmp_1 = x(3);
double tmp_2 = x(1);
double tmp_3 = -tmp_2;
double tmp_4 = tmp_3+tmp_1;
double tmp_5 = x(4);
double tmp_6 = x(0);
double tmp_7 = -tmp_6;
double tmp_8 = tmp_5+tmp_7;
double tmp_10 = x(2);
double tmp_11 = -tmp_10;
double tmp_12 = tmp_6+tmp_11;
double tmp_13 = x(5);
double tmp_14 = tmp_3+tmp_13;
double g0_1 = -3.0*(tmp_8*tmp_4+tmp_14*tmp_12)*(2.0*tmp_2-tmp_1-tmp_13)+(tmp_11+tmp_5)*((tmp_12*tmp_12)+(tmp_14*tmp_14)-tmp_8*tmp_12+(tmp_4*tmp_4)+tmp_14*tmp_4+(tmp_8*tmp_8));
g(0,1) = g0_1;
}
{
double tmp_1 = x(5);
double tmp_2 = x(1);
double tmp_3 = -tmp_2;
double tmp_4 = tmp_1+tmp_3;
double tmp_5 = x(3);
double tmp_6 = tmp_5+tmp_3;
double tmp_8 = x(0);
double tmp_9 = x(2);
double tmp_10 = -tmp_9;
double tmp_11 = tmp_8+tmp_10;
double tmp_12 = x(4);
double tmp_13 = -tmp_8;
double tmp_14 = tmp_12+tmp_13;
double g0_2 = ((tmp_6*tmp_6)+tmp_4*tmp_6+(tmp_11*tmp_11)-tmp_11*tmp_14+(tmp_14*tmp_14)+(tmp_4*tmp_4))*tmp_4-(2.0*tmp_9+tmp_12-3.0*tmp_8)*(tmp_11*tmp_4+tmp_14*tmp_6);
g(0,2) = g0_2;
}
{
double tmp_1 = x(5);
double tmp_2 = x(1);
double tmp_3 = -tmp_2;
double tmp_4 = tmp_3+tmp_1;
double tmp_5 = x(3);
double tmp_6 = tmp_3+tmp_5;
double tmp_8 = x(0);
double tmp_9 = x(2);
double tmp_10 = -tmp_9;
double tmp_11 = tmp_10+tmp_8;
double tmp_12 = x(4);
double tmp_13 = -tmp_8;
double tmp_14 = tmp_13+tmp_12;
double g0_3 = (tmp_11*tmp_4+tmp_6*tmp_14)*(3.0*tmp_2-2.0*tmp_5-tmp_1)+tmp_14*(tmp_11*tmp_14-(tmp_4*tmp_4)-(tmp_6*tmp_6)-tmp_6*tmp_4-(tmp_14*tmp_14)-(tmp_11*tmp_11));
g(0,3) = g0_3;
}
{
double tmp_1 = x(3);
double tmp_2 = x(1);
double tmp_3 = -tmp_2;
double tmp_4 = tmp_3+tmp_1;
double tmp_5 = x(4);
double tmp_6 = x(0);
double tmp_7 = -tmp_6;
double tmp_8 = tmp_5+tmp_7;
double tmp_10 = x(2);
double tmp_11 = -tmp_10;
double tmp_12 = tmp_6+tmp_11;
double tmp_13 = x(5);
double tmp_14 = tmp_3+tmp_13;
double g0_4 = -((tmp_8*tmp_8)+(tmp_4*tmp_4)+(tmp_12*tmp_12)+(tmp_14*tmp_14)-tmp_12*tmp_8+tmp_14*tmp_4)*tmp_4+(tmp_12*tmp_14+tmp_8*tmp_4)*(3.0*tmp_6-2.0*tmp_5-tmp_10);
g(0,4) = g0_4;
}
{
double tmp_1 = x(3);
double tmp_2 = x(5);
double tmp_4 = x(1);
double tmp_7 = -tmp_4;
double tmp_8 = tmp_7+tmp_1;
double tmp_9 = x(4);
double tmp_10 = x(0);
double tmp_11 = -tmp_10;
double tmp_12 = tmp_9+tmp_11;
double tmp_14 = x(2);
double tmp_15 = -tmp_14;
double tmp_16 = tmp_10+tmp_15;
double tmp_17 = tmp_7+tmp_2;
double g0_5 = -(tmp_16*tmp_17+tmp_12*tmp_8)*(2.0*tmp_2+tmp_1-3.0*tmp_4)-tmp_16*((tmp_17*tmp_17)+(tmp_12*tmp_12)+(tmp_8*tmp_8)+tmp_8*tmp_17+(tmp_16*tmp_16)-tmp_16*tmp_12);
g(0,5) = g0_5;
}
}
}
}
| 28.176923 | 177 | 0.685231 | FrancoisGaits |
26fa197a4cc841fbe58433a4e9b5e6c6dcff9280 | 7,037 | cpp | C++ | src/phaser.cpp | transmogrifox/transmogriFX_bela | 1b8fae86d1253fcd062053c44032001421609f04 | [
"Unlicense"
] | 27 | 2018-02-17T17:36:02.000Z | 2022-03-31T17:54:10.000Z | src/phaser.cpp | transmogrifox/transmogriFX_bela | 1b8fae86d1253fcd062053c44032001421609f04 | [
"Unlicense"
] | 8 | 2020-10-28T03:39:42.000Z | 2020-11-06T17:05:38.000Z | src/phaser.cpp | rhaleblian/transmogriFX_bela | 1b8fae86d1253fcd062053c44032001421609f04 | [
"Unlicense"
] | 9 | 2019-08-08T14:40:49.000Z | 2022-01-24T02:36:06.000Z | #include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include "phaser.h"
void commit_circuit_config(phaser_coeffs* cf)
{
int i = 0;
//There is always something to calculate for position zero
cf->a1p_min[i] = -expf(-(cf->w_min[i])/cf->fs);
cf->a1p_max[i] = -expf(-(cf->w_max[i])/cf->fs);
cf->a1p_dif[i] = cf->a1p_max[i] - cf->a1p_min[i];
cf->a1p[i] = cf->a1p_min[i];
cf->ghpf[i] = (1.0 - cf->a1p[i])*0.5;
for(i = 1; i < cf->n_stages; i++)
{
if(cf->stagger[i]) {
cf->a1p_min[i] = -expf(-(cf->w_min[i])/cf->fs);
cf->a1p_max[i] = -expf(-(cf->w_max[i])/cf->fs);
cf->a1p_dif[i] = cf->a1p_max[i] - cf->a1p_min[i];
cf->a1p[i] = cf->a1p_min[i];
cf->ghpf[i] = (1.0 - cf->a1p[i])*0.5;
} else
{
//Should never use these but it's a safe default
//in the event some unforeseen conditions exists in which
//stagger is set true for what would be an unitialized set of
//coefficients
cf->a1p_min[i] = cf->a1p_min[0];
cf->a1p_max[i] = cf->a1p_max[0];
cf->a1p_dif[i] = cf->a1p_dif[0];
cf->a1p[i] = cf->a1p[0];
cf->ghpf[i] = cf->ghpf[0];
}
}
}
void phaser_circuit_preset(int ckt, phaser_coeffs* cf)
{
int i = 0;
switch(ckt)
{
case PHASE_90:
cf->n_stages = 4;
for(i = 0; i < PHASER_MAX_STAGES; i++)
{
cf->gfb[i] = 0.0; //feedback gains all 0
cf->w_min[i] = 2.0*M_PI*350.0;
cf->w_max[i] = 2.0*M_PI*1800.0;
cf-> w_diff[i] = cf->w_max[i] - cf->w_min[i];
cf->stagger[i] = false;
cf->apply_feedback[i] = false;
}
cf->gfb[3] = 0.455; //tap feedback from stage 4
cf->apply_feedback[3] = true;
cf->distort = 0.5;
cf->idistort = 1.0/cf->distort;
cf->wet = 1.0;
cf->dry = 1.0;
cf->mod->lfo_type = RELAX;
break;
case PHASER_DEFAULT:
default:
cf->n_stages = 6;
for(i = 0; i < PHASER_MAX_STAGES; i++)
{
cf->gfb[i] = 0.0; //feedback gains all 0
cf->w_min[i] = 2.0*M_PI*350.0;
cf->w_max[i] = 2.0*M_PI*2000.0;
cf-> w_diff[i] = cf->w_max[i] - cf->w_min[i];
cf->stagger[i] = false;
cf->apply_feedback[i] = false;
}
cf->distort = 0.5;
cf->idistort = 1.0/cf->distort;
cf->wet = 1.0;
cf->dry = 1.0;
cf->mod->lfo_type = EXP;
break;
}
//Compute DSP filter coefficients
commit_circuit_config(cf);
}
//Initialize filter state variables
void zero_state_variables(phaser_coeffs* cf)
{
cf->fb = 0.0;
int i = 0;
for(i = 0; i < PHASER_MAX_STAGES; i++)
{
cf->yh1[i] = 0.0;
cf->xh1[i] = 0.0;
cf->ph1[i] = 0.0;
}
//Signal this has already been done so
cf->reset = false;
}
phaser_coeffs*
make_phaser(phaser_coeffs* cf, float fs)
{
//First malloc the struct
cf = (phaser_coeffs*) malloc(sizeof(phaser_coeffs));
cf->fs = fs;
//setup LFO
cf->mod = init_lfo(cf->mod,1.0, cf->fs, 0.0);
//Default to something that makes decent sound
phaser_circuit_preset(PHASER_DEFAULT, cf);
//Initialize everything to 0.0
zero_state_variables(cf);
//Start out bypassed
cf->bypass = true;
return cf;
}
inline float sqr(float x)
{
return x*x;
}
inline float clip_hard(float x)
{
float thrs = 0.8;
float nthrs = -0.72;
float f=1.25;
//Hard limiting
if(x >= 1.2) x = 1.2;
if(x <= -1.12) x = -1.12;
//Soft clipping
if(x > thrs){
x -= f*sqr(x - thrs);
}
if(x < nthrs){
x += f*sqr(x - nthrs);
}
return x;
}
inline void
phaser_modulate(phaser_coeffs* cf)
{
unsigned int st = 0;
float lfo = 1.0 - run_lfo(cf->mod);
lfo += lfo*lfo;
lfo *= 0.5;
cf->a1p[st] = cf->a1p_min[st] + cf->a1p_dif[st]*lfo;
cf->ghpf[st] = (1.0 - cf->a1p[st])*0.5;
if(cf->stagger[0] == false) return;
for(st = 1; st < cf->n_stages; st++)
{
if(cf->stagger[st])
{
cf->a1p[st] = cf->a1p_min[st] + cf->a1p_dif[st]*lfo;
cf->ghpf[st] = (1.0 - cf->a1p[st])*0.5;
}
}
}
inline float
phaser_tick(float x_, phaser_coeffs* cf)
{
unsigned int st = 0;
unsigned int stn = 0;
unsigned int stag = 0;
phaser_modulate(cf);
cf->ph1[0] = x_ + cf->fb;
cf->fb = 0.0;
for(st = 0; st < cf->n_stages; st++)
{
if(cf->stagger[st])
{
stag = st;
} else
{
stag = 0;
}
if(st > 0) stn = st -1;
cf->yh1[st] = cf->ghpf[stag] * ( cf->ph1[stn] - cf->xh1[st] ) - cf->a1p[stag]*cf->yh1[st];
cf->xh1[st] = cf->ph1[stn];
cf->ph1[st] = 2.0*cf->idistort*clip_hard(cf->distort*cf->yh1[st]) - cf->ph1[stn];
//cf->ph1[st] = 2.0*cf->yh1[st] - cf->ph1[stn];
if(cf->apply_feedback[st])
{
cf->fb += cf->ph1[st]*cf->gfb[st];
}
}
float out = cf->wet*cf->ph1[cf->n_stages-1] + cf->dry*x_;
//And ship it!
return out;
}
void
phaser_tick_n(phaser_coeffs* cf, int n, float* x)
{
if(cf->bypass)
{
if(cf->reset)
{
zero_state_variables(cf);
}
return;
} else
{
cf->reset = true;
}
int i = 0;
for(i=0; i<n; i++)
{
x[i] = phaser_tick(x[i], cf);
}
}
void
phaser_set_nstages(phaser_coeffs* cf, int nstages)
{
//TODO: Check feedback not coming from invalid stage
cf->n_stages = nstages;
commit_circuit_config(cf);
}
void
phaser_set_mix(phaser_coeffs* cf, float wet)
{
float wet_ = wet;
float gain = 1.0 + 2.0*fabs(wet_);
if(gain > 2.0) gain = 4.0 - gain;
if(wet < 0.0)
{
cf->wet = wet*gain;
cf->dry = (1.0 + wet)*gain;
}
else
{
cf->wet = wet*gain;
cf->dry = (1.0 - wet)*gain;
}
}
void
phaser_set_lfo_type(phaser_coeffs* cf, int n)
{
cf->mod->lfo_type = n;
}
void
phaser_set_lfo_rate(phaser_coeffs* cf, float rate)
{
update_lfo(cf->mod, rate, cf->fs);
}
void
phaser_set_lfo_depth(phaser_coeffs* cf, float depth, int stage)
{
cf->w_min[stage] = 2.0*M_PI*depth;
cf->w_max[stage] = cf->w_min[stage] + cf-> w_diff[stage];
commit_circuit_config(cf);
}
void
phaser_set_lfo_width(phaser_coeffs* cf, float width, int stage)
{
cf->w_diff[stage] = 2.0*M_PI*width;
cf->w_max[stage] = cf->w_min[stage] + cf-> w_diff[stage];
commit_circuit_config(cf);
}
void
phaser_set_feedback(phaser_coeffs* cf, float fb, int stage)
{
cf->gfb[stage] = fb;
if(fb == 0.0)
cf->apply_feedback[stage] = false;
else
cf->apply_feedback[stage] = true;
}
void
phaser_set_distortion(phaser_coeffs* cf, float d)
{
if(d < 0.001)
cf->distort = 0.001;
else if (d >1000.0)
cf->distort = 1000.0;
else
cf->distort = d;
cf->idistort = 1.0/d;
}
bool phaser_toggle_bypass(phaser_coeffs* cf)
{
if(cf->bypass) cf->bypass = false;
else cf->bypass = true;
return cf->bypass;
}
| 21.786378 | 98 | 0.534603 | transmogrifox |
f80060ae61e9bc31c27fc9deaaadede454c9edfc | 510 | hpp | C++ | taskflow/declarations.hpp | leokolln/cpp-taskflow | b5cd4ca2006b18d309f1c7c22f90a13becf97fd3 | [
"MIT"
] | null | null | null | taskflow/declarations.hpp | leokolln/cpp-taskflow | b5cd4ca2006b18d309f1c7c22f90a13becf97fd3 | [
"MIT"
] | null | null | null | taskflow/declarations.hpp | leokolln/cpp-taskflow | b5cd4ca2006b18d309f1c7c22f90a13becf97fd3 | [
"MIT"
] | null | null | null | #pragma once
namespace tf {
// ----------------------------------------------------------------------------
// forward declarations inside tf
// ----------------------------------------------------------------------------
class Node;
class Graph;
class FlowBuilder;
class Subflow;
class Task;
class TaskView;
class Taskflow;
class Topology;
class Executor;
class cudaNode;
class cudaGraph;
class cudaTask;
class cudaFlow;
} // end of namespace tf -----------------------------------------------------
| 18.214286 | 79 | 0.441176 | leokolln |
f80649689a57361eca9a5b1864c945e358d59e35 | 1,655 | cpp | C++ | shift_the_string.cpp | Delfad0r/CompetitiveProgrammingCourse | a986045372138f550e38f6262933ed34f7a57d77 | [
"Apache-2.0"
] | null | null | null | shift_the_string.cpp | Delfad0r/CompetitiveProgrammingCourse | a986045372138f550e38f6262933ed34f7a57d77 | [
"Apache-2.0"
] | null | null | null | shift_the_string.cpp | Delfad0r/CompetitiveProgrammingCourse | a986045372138f550e38f6262933ed34f7a57d77 | [
"Apache-2.0"
] | null | null | null | /*
We create a new string A+"$"+B+B, and then we compute the Z array (for an
explanation of the Z-algorithm, see https://codeforces.com/blog/entry/3107).
At this point, the answer is simply the first position of the Z array with
maximum value.
Time complexity: O(N)
Space complexity: O(N)
*/
#include <bits/stdc++.h>
using namespace std;
// Implementation of the Z algorithm to compute the Z array.
// Given a string S, Z[i] is the maximum m such that S[0..m-1]=S[i..i+m-1].
// Complexity: O(N), where N is the length of S
// Function to compute the Z array.
// Takes two random-access iterators b and e as input, representing
// the beginning and the end of the string S.
// Returns the Z array of S.
template<typename I>
vector<int> Z_algorithm(I b, I e) {
I l = b, r = b;
vector<int> Z(e - b);
for(I i = b + 1; i != e; ++i) {
if(i > r) {
l = r = i;
while(r < e and *(b + (r - l)) == *r) {
++r;
}
Z[i - b] = r - l;
--r;
} else {
if(Z[i - l] <= r - i) {
Z[i - b] = Z[i - l];
} else {
l = i;
while(r < e and *(b + (r - l)) == *r) {
++r;
}
Z[i - b] = r - l;
--r;
}
}
}
return Z;
}
int main() {
int N;
string A, B;
cin >> N >> A >> B;
A += "$" + B + B;
auto Z = Z_algorithm(A.begin(), A.end());
int ans = 0, pos = 0;
for(int n = 0; n < N; ++n) {
if(Z[N + 1 + n] > ans) {
ans = Z[N + 1 + n];
pos = n;
}
}
cout << pos << "\n";
return 0;
}
| 24.701493 | 76 | 0.459819 | Delfad0r |
f80e4d4bca6f4c96eb17fcb70a0bcf06cebe84e8 | 3,231 | hpp | C++ | SDK/PUBG_P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 7 | 2019-03-06T11:04:52.000Z | 2019-07-10T20:00:51.000Z | SDK/PUBG_P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | null | null | null | SDK/PUBG_P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_classes.hpp | realrespecter/PUBG-FULL-SDK | 5e2b0f103c74c95d2329c4c9dfbfab48aa0da737 | [
"MIT"
] | 10 | 2019-03-06T11:53:46.000Z | 2021-02-18T14:01:11.000Z | #pragma once
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_structs.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP.P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_C
// 0x006C (0x051C - 0x04B0)
class AP_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_C : public ATslParticleEnvironment
{
public:
struct FVector SpawnBoxMax; // 0x04B0(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
struct FVector SpawnBoxMin; // 0x04BC(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
struct FVector Color; // 0x04C8(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
float SpawnRate; // 0x04D4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
struct FVector SizeMax; // 0x04D8(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
struct FVector SizeMin; // 0x04E4(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
struct FVector VelocityMax; // 0x04F0(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
struct FVector VelocityMin; // 0x04FC(0x000C) (Edit, BlueprintVisible, IsPlainOldData)
float LifeTime; // 0x0508(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float LifeTimeLow; // 0x050C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float ALPHA; // 0x0510(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float RotationRateMax; // 0x0514(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
float RotationRateMin; // 0x0518(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP.P_Vikendi_Environment_SnowSmoke_WindStraight_03_BP_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 64.62 | 185 | 0.486537 | realrespecter |
f81006bd1da9d1892d48de4567602f3fe9d4fa83 | 453 | cpp | C++ | src/classwork/03_assign/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | src/classwork/03_assign/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | src/classwork/03_assign/main.cpp | acc-cosc-1337-fall-2020/acc-cosc-1337-fall-2020-djchenevert | 0f7b3f47eb518fc4e85ec853cab9ceb4c629025a | [
"MIT"
] | null | null | null | //Write the include statement for decisions.h here
#include "decision.h"
//Write namespace using statements for cout and cin
using std::cin; using std::cout;
int main()
{
int grade;
cout<<"Input your numerical grade between 0 and 100: ";
cin>>grade;
if(grade >= 00 && grade <= 100)
{
get_letter_grade_using_if(grade);
get_letter_grade_using_switch(grade);
}
else
{
cout<<"You have entered an invalid number.";
}
return 0;
}
| 15.62069 | 56 | 0.686534 | acc-cosc-1337-fall-2020 |
f814fd0799096bf194f44e537f550746915471ea | 1,055 | hpp | C++ | SDK/ARKSurvivalEvolved_PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_classes.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_structs.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant.PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_C
// 0x0000 (0x0AF8 - 0x0AF8)
class UPrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_C : public UPrimalItemConsumable_Egg_Iguanodon_Fertilized_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant.PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant_C");
return ptr;
}
void ExecuteUbergraph_PrimalItemConsumable_Egg_Iguanodon_Fertilized_Aberrant(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 27.051282 | 178 | 0.726066 | 2bite |
f817cc92eab16cc76948be13f6e595c9b017da11 | 12,751 | cpp | C++ | Plugins/Puerts/Source/JsEnv/Private/JitScript.cpp | Anehta/Unreal4ReactUMG | af1b4bdfb5993845819a74d17c42bf353e3aa53a | [
"MIT"
] | null | null | null | Plugins/Puerts/Source/JsEnv/Private/JitScript.cpp | Anehta/Unreal4ReactUMG | af1b4bdfb5993845819a74d17c42bf353e3aa53a | [
"MIT"
] | null | null | null | Plugins/Puerts/Source/JsEnv/Private/JitScript.cpp | Anehta/Unreal4ReactUMG | af1b4bdfb5993845819a74d17c42bf353e3aa53a | [
"MIT"
] | null | null | null | /*
* Tencent is pleased to support the open source community by making Puerts available.
* Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
* Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms.
* This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package.
*/
#include "JitScript.h"
#include "Misc/Base64.h"
#include "Async/Async.h"
#define MODULE_LAZY_LOAD_TEMPLATE "(function() { puerts.__MODULE_LAZY_LOAD = function(require) { var __filename = '%s', __dirname = '%s', exports ={}, module = { exports : exports, filename : __filename }; (function (exports, require, console, prompt) { %s\n})(exports, require, puerts.console); return module.exports;}})()"
namespace puerts
{
int CallbackPool::Add(std::function<void(const FString&, const JSError*)> Callback)
{
std::lock_guard<std::mutex> guard(Mutex);
while(Callbacks.find(AllocedCallbackId) != Callbacks.end())
{
++AllocedCallbackId;
}
Callbacks.insert({AllocedCallbackId, Callback});
return AllocedCallbackId++;
}
void CallbackPool::OnFinish(int CallbackId, const FString& Reply)
{
std::lock_guard<std::mutex> guard(Mutex);
auto iter = Callbacks.find(CallbackId);
if (iter != Callbacks.end())
{
auto callback = iter->second;
Callbacks.erase(iter);
callback(Reply, nullptr);
}
else
{
Logger->Error(FString::Printf(TEXT("unexpect callback id:%d"), CallbackId));
}
}
void CallbackPool::OnError(int CallbackId, const JSError* Error)
{
std::lock_guard<std::mutex> guard(Mutex);
auto iter = Callbacks.find(CallbackId);
if (iter != Callbacks.end())
{
auto callback = iter->second;
Callbacks.erase(iter);
callback(TEXT(""), Error);
}
else
{
Logger->Error(FString::Printf(TEXT("unexpect callback id:%d"), CallbackId));
}
}
//FJitScript::FJitScript() : FJitScript(std::make_unique<DefaultJSModuleLoader>(), CreateJSEngine(EBackendEngine::Auto), std::make_shared<FDefaultLogger>())
//{
//}
FJitScript::FJitScript(std::unique_ptr<IJSModuleLoader> InModuleLoader/* = std::make_unique<DefaultJSModuleLoader>()*/, std::unique_ptr<IJsEngine> InJsEnv/* = CreateJSEngine(EBackendEngine::Auto)*/, std::shared_ptr<ILogger> InLogger/* = new FDefaultLogger()*/) : RequestCallbackPool(InLogger)
{
ModuleLoader = std::move(InModuleLoader);
JsEnv = std::move(InJsEnv);
Logger = InLogger;
StartModuleCalled = false;
Init();
}
FJitScript::~FJitScript()
{
}
void FJitScript::Close()
{
this->JsEnv->Close();
}
void FJitScript::Init()
{
JsEnv->SetMessageHandler(std::bind(&FJitScript::HandleMessage, this, std::placeholders::_1));
JsEnv->SetLogger(Logger);
RegisterOnewayRequestHandler("log", std::bind(&FJitScript::Log, this, std::placeholders::_1));
RegisterOnewayRequestHandler("info", std::bind(&FJitScript::Info, this, std::placeholders::_1));
RegisterOnewayRequestHandler("warn", std::bind(&FJitScript::Warn, this, std::placeholders::_1));
RegisterOnewayRequestHandler("error", std::bind(&FJitScript::Error, this, std::placeholders::_1));
RegisterRequestHandler("pollRequest", std::bind(&FJitScript::OnPollRequest, this, std::placeholders::_1));
RegisterOnewayRequestHandler("onReply", std::bind(&FJitScript::OnReply, this, std::placeholders::_1));
RegisterRequestHandler("loadBinary", std::bind(&FJitScript::LoadBinary, this, std::placeholders::_1));
RegisterRequestHandler("loadModule", std::bind(&FJitScript::LoadModule, this, std::placeholders::_1));
ExecuteModule("puerts/polyfill.js");
ExecuteModule("puerts/message.js");
ExecuteModule("puerts/log.js");
ExecuteModule("puerts/modular.js");
}
void FJitScript::Start(const FString& ModuleName)
{
if (StartModuleCalled)
{
Error("Call TGameJS::Start more than once!");
return;
}
ExecuteModule(ModuleName, [](const FString& Script, const FString& Path)
{
auto PathInJs = Path.Replace(TEXT("\\"), TEXT("\\\\"));
auto DirInJs = FPaths::GetPath(Path).Replace(TEXT("\\"), TEXT("\\\\"));
return FString::Printf(TEXT("(function() { var __filename = '%s', __dirname = '%s', exports ={}, module = { exports : exports, filename : __filename }; (function (exports, require, console, prompt) { %s\n})(exports, puerts.genRequire('%s'), puerts.console);})()"), *PathInJs, *DirInJs, *Script, *DirInJs);
});
StartModuleCalled = true;
}
void FJitScript::ExecuteModule(const FString& ModuleName, std::function<FString(const FString&, const FString&)> Preprocessor)
{
FString OutPath;
FString DebugPath;
TArray<uint8> Data;
try
{
LoadFile(TEXT(""), ModuleName, OutPath, DebugPath, Data);
}
catch (const JSError& Err)
{
Error(Err.Message);
return;
}
FString Script;
FFileHelper::BufferToString(Script, Data.GetData(), Data.Num());
//UE_LOG(JSMessge, Log, TEXT("script:%s"), *(Preprocessor ? Preprocessor(script, path): script));
JsEnv->ExecuteJavascript(Preprocessor ? Preprocessor(Script, OutPath): Script, DebugPath, [ModuleName, this](const puerts::JSError* jsError) {
if (jsError)
{
Error(FString::Printf(TEXT("module[%s] execute fail: %s"), *ModuleName, *(jsError->Message)));
}
else
{
Info(FString::Printf(TEXT("module[%s] executed"), *ModuleName));
}
});
}
FString FJitScript::OnPollRequest(const FString&)
{
std::lock_guard<std::mutex> guard(RequestQueueMutex);
if (RequestQueue.empty())
{
return TEXT("");
}
else
{
auto req = RequestQueue.front();
RequestQueue.pop();
if (req.Callback)
{
auto Id = RequestCallbackPool.Add(req.Callback);
return FString::Printf(TEXT("%d#%s#%s"), Id, *(req.Cmd), *(req.Data));
}
else
{
return FString::Printf(TEXT("#%s#%s"), *(req.Cmd), *(req.Data));
}
}
}
void FJitScript::OnReply(const FString& Reply)
{
int pos;
if (Reply.FindChar('#', pos))
{
FString RpyIDStr = Reply.Mid(0, pos);
FString Message = Reply.Mid(pos + 1);
int RpyId = FCString::Atoi(*RpyIDStr);
//UE_LOG(JSMessge, Log, TEXT("ID:%d, Msg:%s"), RpyID, *Message);
if (Message[0] == '#') // reply
{
RequestCallbackPool.OnFinish(RpyId, Message.Mid(1));
}
else
{
JSError Err(Message);
RequestCallbackPool.OnError(RpyId, &Err);
}
}
}
void FJitScript::LoadFile(const FString& RequiringDir, const FString& ModuleName, FString& OutPath, FString& OutDebugPath, TArray<uint8>& Data)
{
if (ModuleLoader->Search(RequiringDir, ModuleName, OutPath, OutDebugPath)) {
if (!ModuleLoader->Load(OutPath, Data))
{
throw JSError(FString::Printf(TEXT("can not load [%s]"), *ModuleName));
}
} else {
throw JSError(FString::Printf(TEXT("can not find [%s]"), *ModuleName));
}
}
FString FJitScript::LoadBinary(const FString& Path)
{
FString OutPath;
FString OutDebugPath;
TArray<uint8> Data;
LoadFile(TEXT(""), Path, OutPath, OutDebugPath, Data);
return FBase64::Encode(Data);
}
FString FJitScript::LoadModule(const FString& Arguments)
{
int32 Pos;
if (!Arguments.FindChar('#', Pos))
{
throw JSError(TEXT("invalid message for loadModule"));
}
FString ModuleName = Arguments.Mid(0, Pos);
FString RequiringDir = Arguments.Mid(Pos + 1);
FString OutPath;
FString OutDebugPath;
TArray<uint8> Data;
LoadFile(RequiringDir, ModuleName, OutPath, OutDebugPath, Data);
FString Script;
FFileHelper::BufferToString(Script, Data.GetData(), Data.Num());
return FString::Printf(TEXT("%s\n%s\n%s"), *OutPath, *OutDebugPath, *Script);
}
void FJitScript::SendRquest(const FString& Cmd, const FString& Data)
{
SendRquest(Cmd, Data, nullptr);
}
void FJitScript::SendRquest(const FString& Cmd, const FString& Data, std::function<void(const FString&, const JSError*)> Callback)
{
RequestQueue.push({Cmd, Data, Callback});
}
void FJitScript::RegisterRequestHandlerImpl(const FString& Cmd, std::function<FString(const FString&)> Handler)
{
if (!Handler)
{
Error(TEXT("Handler invalid!"));
return;
}
if (MessageHandlers.find(Cmd) != MessageHandlers.end())
{
Error(FString::Printf(TEXT("Cmd[%s] register yet!"), *Cmd));
return;
}
MessageHandlers.insert({Cmd, Handler});
}
void FJitScript::RegisterOnewayRequestHandler(const FString& Cmd, std::function<void(const FString&)> Handler)
{
RegisterRequestHandlerImpl(Cmd, [Handler](const FString& Message){
try
{
Handler(Message);
}
catch (const JSError& /* Error */)
{
}
return TEXT("");
});
}
void FJitScript::RegisterRequestHandler(const FString& Cmd, std::function<FString(const FString&)> Handler)
{
RegisterRequestHandlerImpl(Cmd, [this, Handler](const FString& Message){
try
{
return MakeReply(Handler(Message));
}
catch (const JSError& Error)
{
return MakeErrorReply(Error.Message);
}
});
}
FString FJitScript::HandleMessageInGameThread(const FString& Msg)
{
if (IsInGameThread())
{
return HandleMessage(Msg);
}
else
{
TPromise<FString> Promise;
TFuture<FString> Future = Promise.GetFuture();
AsyncTask(ENamedThreads::GameThread, [this, &Promise, &Msg]()
{
Promise.SetValue(HandleMessage(Msg));
});
return Future.Get();
}
}
FString FJitScript::HandleMessage(const FString& RawMsg)
{
int pos;
if (RawMsg.FindChar('#', pos))
{
FString Cmd = RawMsg.Mid(0, pos);
FString Message = RawMsg.Mid(pos + 1);
//UE_LOG(JSMessge, Log, TEXT("cmd:[%s]"), *cmd);
//UE_LOG(JSMessge, Log, TEXT("data:[%s]"), *data);
auto handler = MessageHandlers.find(Cmd);
if (handler != MessageHandlers.end())
{
return handler->second(Message);
}
else
{
//UE_LOG(JSMessge, Error, TEXT("can not find cmd handler for: %s "), *Cmd);
return MakeErrorReply(TEXT("can not find cmd handler for:") + Cmd);
}
}
else
{
//UE_LOG(JSMessge, Error, TEXT("invalid js message:[%s]"), *RawMsg);
return MakeErrorReply(TEXT("invalid js message:") + RawMsg);
}
}
FString FJitScript::MakeErrorReply(const FString& ErrorMessage)
{
return ErrorMessage.Replace(TEXT("#"), TEXT(""));
}
FString FJitScript::MakeReply(const FString& Message)
{
return "#" + Message;
}
void FJitScript::Log(const FString& Message) const
{
Logger->Log(Message);
}
void FJitScript::Info(const FString& Message) const
{
Logger->Info(Message);
}
void FJitScript::Warn(const FString& Message) const
{
Logger->Warn(Message);
}
void FJitScript::Error(const FString& Message) const
{
Logger->Error(Message);
}
}
| 34.276882 | 325 | 0.567093 | Anehta |
f819d000e99288c29420882d9b055889477f8b9a | 214 | cpp | C++ | basic_programme/fabonacci.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | basic_programme/fabonacci.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | basic_programme/fabonacci.cpp | sahilduhan/Learn-C-plus-plus | 80dba2ee08b36985deb297293a0318da5d6ace94 | [
"RSA-MD"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
long long int fibonacci(int num)
{
if (num <= 1)
return num;
return fibonacci(num - 1) + fibonacci(num - 2);
}
int main()
{
cout << fibonacci(5);
} | 16.461538 | 51 | 0.593458 | sahilduhan |
f819d618195d2ba46c22f6ff794ff29a0227d071 | 937 | cpp | C++ | libft/test_ft_lstadd_back.cpp | study-group-99/ultimate-pilates-engine | 9f665956d8ca7a3af0e16ac0f2b797bbd36b4b6d | [
"Unlicense"
] | 3 | 2021-06-01T11:17:49.000Z | 2021-06-17T08:56:52.000Z | libft/test_ft_lstadd_back.cpp | study-group-99/ultimate-pilates-engine | 9f665956d8ca7a3af0e16ac0f2b797bbd36b4b6d | [
"Unlicense"
] | 16 | 2021-06-02T23:02:02.000Z | 2021-06-24T14:46:37.000Z | libft/test_ft_lstadd_back.cpp | study-group-99/ultimate-pilates-engine | 9f665956d8ca7a3af0e16ac0f2b797bbd36b4b6d | [
"Unlicense"
] | null | null | null | #include <gtest/gtest.h>
#include <stdlib.h>
#include <strings.h>
extern "C" {
#include "../libft.h"
}
TEST(TestFtLstadd_back, Basic) {
t_list *got = ft_lstnew(strdup("test"));
t_list *want = ft_lstnew(strdup("OK"));
ft_lstadd_back(&got, want);
EXPECT_TRUE(want == got->next);
EXPECT_STREQ("OK", (char *)got->next->content);
}
TEST(TestFtLstadd_back, Null) {
t_list *got = ft_lstnew(NULL);
t_list *want = ft_lstnew(strdup("OK"));
ft_lstadd_back(&got, want);
EXPECT_TRUE(want->content == got->next->content);
}
TEST(TestFtLstadd_back, Null2) {
t_list *got = ft_lstnew(strdup("test"));
t_list *want = ft_lstnew(NULL);
ft_lstadd_back(&got, want);
EXPECT_TRUE(want->content == got->next->content);
}
TEST(TestFtLstadd_back, DoubleNull) {
t_list *got = ft_lstnew(NULL);
t_list *want = ft_lstnew(NULL);
ft_lstadd_back(&got, want);
EXPECT_TRUE(NULL == got->content);
EXPECT_TRUE(want == got->next);
}
| 20.369565 | 53 | 0.674493 | study-group-99 |
f81b36c4d2282a5455fea5c20f047ea1ab25e827 | 776 | cpp | C++ | cpp/aTourOfModernCpp/c06-range-based-for-loop.cpp | sysbender/learncoding | beb8b36793d85dfd6649eb3380161814ec4d19f6 | [
"Unlicense"
] | null | null | null | cpp/aTourOfModernCpp/c06-range-based-for-loop.cpp | sysbender/learncoding | beb8b36793d85dfd6649eb3380161814ec4d19f6 | [
"Unlicense"
] | null | null | null | cpp/aTourOfModernCpp/c06-range-based-for-loop.cpp | sysbender/learncoding | beb8b36793d85dfd6649eb3380161814ec4d19f6 | [
"Unlicense"
] | null | null | null | #include "header.h"
using namespace std;
template<typename Container>
void print(const Container& container){
for(auto const & x: container){
std::cout << x << " ";
}
std::cout << std::endl;
}
int main(){
vector<int> v {1,2,3,4};
// print - for legecy
for( int i =0; i<v.size() ; i++){
cout << v.at(i)<< ", ";
}
cout << endl;
// print - for range
for (auto &&i : v)
{
cout << i << ";";
}
cout <<endl;
// modify
for( int & i : v) {
i = i * i;
}
print(v);
// map
map<string, int> histogram{ {"a", 1},{"b", 2}};
for(const auto& kvp: histogram){
cout << kvp.first <<" : " << kvp.second << " ";
}
cout << endl;
return 0;
} | 15.52 | 58 | 0.443299 | sysbender |
f81da0b427974298bc97783a35ec7daf2e9f342a | 22,236 | cpp | C++ | src/test/chip8_emu_test.cpp | Druage/chip8_cpp | e3c10a49a04c7118348dc63e60f48bebea62b8e6 | [
"Apache-2.0"
] | null | null | null | src/test/chip8_emu_test.cpp | Druage/chip8_cpp | e3c10a49a04c7118348dc63e60f48bebea62b8e6 | [
"Apache-2.0"
] | null | null | null | src/test/chip8_emu_test.cpp | Druage/chip8_cpp | e3c10a49a04c7118348dc63e60f48bebea62b8e6 | [
"Apache-2.0"
] | null | null | null | //
// Created by lee on 2020-07-29.
//
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in one cpp file
#include "include/catch.hpp"
#include "include/utils.h"
#include <chip8_emu.h>
TEST_CASE("All chip8 fields are initialized correctly", "[INITIALIZED") {
Chip8Emu emu;
REQUIRE(emu.memory.size() == 4096);
REQUIRE(game_memory_locations_are_zeroed_out(emu));
REQUIRE(emu.pc == 0x200);
REQUIRE(emu.i_register == 0);
REQUIRE(emu.stack.size() == 16);
REQUIRE(is_zeroed_out(emu.stack));
REQUIRE(emu.stack_pointer == 0);
REQUIRE(emu.V.size() == 16);
REQUIRE(is_zeroed_out(emu.V));
REQUIRE(emu.delay_timer == 0);
REQUIRE(emu.sound_timer == 0);
REQUIRE(emu.input_keys.size() == 16);
REQUIRE(is_zeroed_out(emu.input_keys));
REQUIRE(emu.vfx.size() == 64 * 32);
REQUIRE(is_zeroed_out(emu.vfx));
REQUIRE(emu.game_buffer.empty());
}
TEST_CASE("The fonts [0x0 - 0xF] are stored in the first 80 characters of the memory", "[INITIALIZED]") {
Chip8Emu emu;
for (size_t i = Chip8Emu::FONT_MEMORY_STARTING_LOCATION; i < Chip8Emu::FONT_MEMORY_SIZE; ++i) {
REQUIRE(emu.memory[i] == emu.fonts[i]);
}
}
TEST_CASE("0x00E0 - Clears the screen", "[OP_CODE]") {
Chip8Emu emu;
emu.vfx.fill(1);
emu.memory[emu.pc + 0] = 0x00;
emu.memory[emu.pc + 1] = 0xE0;
emu.fetch_op_code();
REQUIRE(is_zeroed_out(emu.vfx));
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x00EE - Returns from a subroutine.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x00;
emu.memory[emu.pc + 1] = 0xEE;
emu.stack_pointer = 2;
emu.stack[emu.stack_pointer - 1] = 0xFF;
emu.fetch_op_code();
REQUIRE(emu.i_register == 0);
REQUIRE(emu.stack_pointer == 1);
REQUIRE(emu.pc == 0xFF + 0x02);
}
TEST_CASE("0x1NNN - Jumps to address NNN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x1A;
emu.memory[emu.pc + 1] = 0xAA;
emu.fetch_op_code();
REQUIRE(emu.pc == 0x0AAA);
}
TEST_CASE("0x2NNN - Calls subroutine at NNN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x20;
emu.memory[emu.pc + 1] = 0x01;
auto original_pc_val = emu.pc;
emu.fetch_op_code();
REQUIRE(emu.stack_pointer == 1);
REQUIRE(emu.stack[emu.stack_pointer - 1] == original_pc_val);
REQUIRE(emu.pc == 0x0001);
}
TEST_CASE("0x3XNN - Skips the next instruction if VX equals NN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x31;
emu.memory[emu.pc + 1] = 0xBB;
emu.V[1] = 0xBB;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0x3XNN - Does not skip the next instruction if VX does not equal NN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x31;
emu.memory[emu.pc + 1] = 0xBB;
emu.V[1] = 0xCC;
emu.fetch_op_code();
REQUIRE(emu.pc == 0x200 + 2);
}
TEST_CASE("0x4XNN - Skips the next instruction if VX doesn't equal NN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x41;
emu.memory[emu.pc + 1] = 0xBB;
emu.V[1] = 0xAA;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0x4XNN - Does not skip the next instruction if VX equals NN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x41;
emu.memory[emu.pc + 1] = 0xBB;
emu.V[1] = 0xBB;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x5XY0 - Skips the next instruction if VX equals VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x51;
emu.memory[emu.pc + 1] = 0x20;
emu.V[1] = 0xAA;
emu.V[2] = 0xAA;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0x5XY0 - Does not skip the next instruction if VX does not equal VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x51;
emu.memory[emu.pc + 1] = 0x20;
emu.V[1] = 0xAA;
emu.V[2] = 0xBB;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x6XNN - Sets VX to NN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x61;
emu.memory[emu.pc + 1] = 0xFF;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0xFF);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x7XNN - Adds NN to VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x71;
emu.memory[emu.pc + 1] = 0x02;
emu.V[1] = 0x02;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x04);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY0 - Sets VX to the value of VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x20;
emu.V[1] = 0x02;
emu.V[2] = 0x03;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x03);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY1 - Sets VX to VX or VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x21;
emu.V[1] = 0x02;
emu.V[2] = 0x04;
emu.fetch_op_code();
auto expected_result = 0x02u | 0x04u;
REQUIRE(emu.V[1] == expected_result);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY2 - Sets VX to VX and VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x22;
emu.V[1] = 0x02;
emu.V[2] = 0x04;
emu.fetch_op_code();
auto expected_result = 0x02u & 0x04u;
REQUIRE(emu.V[1] == expected_result);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY3 - Sets VX to VX xor VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x23;
emu.V[1] = 0x02;
emu.V[2] = 0x06;
emu.fetch_op_code();
auto expected_result = 0x02u ^0x06u;
REQUIRE(emu.V[1] == expected_result);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY4 - Adds VY to VX. VF is set to 0 because there is not a carry.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x24;
emu.V[1] = 0x02;
emu.V[2] = 0x06;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x08u);
REQUIRE(emu.V[0xF] == 0u);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY4 - Adds VY to VX. VF is set to 1 because there is a carry", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x24;
emu.V[1] = 0x02;
emu.V[2] = 0xFF;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 1);
REQUIRE(emu.V[0xF] == 1u);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY5 - VY is subtracted from VX. VF is set to 0 when there's a borrow", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x25;
emu.V[1] = 0x04;
emu.V[2] = 0x05;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0xFF);
REQUIRE(emu.V[0xF] == 0u);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY5 - VY is subtracted from VX. VF is set to 1 when there's not a borrow", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x25;
emu.V[1] = 0x04;
emu.V[2] = 0x03;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 1u);
REQUIRE(emu.V[0xF] == 1u);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY6 - Stores the least significant bit of VX in VF and then shifts VX to the right by 1.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x26;
emu.V[1] = 0x40;
emu.V[2] = 0x03;
emu.fetch_op_code();
REQUIRE(emu.V[0xF] == 0x0);
REQUIRE(emu.V[1] == 0x20);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY6 - Double checks storing the least significant bit of VX in VF", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x26;
emu.V[1] = 0x03;
emu.V[2] = 0x03;
emu.fetch_op_code();
REQUIRE(emu.V[0xF] == 0x1);
}
TEST_CASE("0x8XY7 - Sets VX to VY minus VX. VF is set to 0 because there is a borrow",
"[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x27;
emu.V[1] = 0x03;
emu.V[2] = 0x02;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0xFF);
REQUIRE(emu.V[0xF] == 0x0);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XY7 - Sets VX to VY minus VX. VF is set to 1 because there is not a borrow",
"[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x27;
emu.V[1] = 0x03;
emu.V[2] = 0x04;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x1);
REQUIRE(emu.V[0xF] == 0x1);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x8XYE - Stores the most significant bit of VX in VF and then shifts VX to the left by 1.",
"[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x81;
emu.memory[emu.pc + 1] = 0x2E;
emu.V[1] = 0x40;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x80);
REQUIRE(emu.V[0xF] == 0x0);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0x9XY0 - Skips the next instruction because VX doesn't equal VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x91;
emu.memory[emu.pc + 1] = 0x20;
emu.V[1] = 0x40;
emu.V[2] = 0x50;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0x9XY0 - Does not skip the next instruction because VX equals VY.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0x91;
emu.memory[emu.pc + 1] = 0x20;
emu.V[1] = 0x40;
emu.V[2] = 0x40;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xANNN - Sets I register to the address NNN.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xAB;
emu.memory[emu.pc + 1] = 0xCD;
emu.fetch_op_code();
REQUIRE(emu.i_register == 0X0BCD);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xBNNN - Jumps to the address NNN plus V0.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xBA;
emu.memory[emu.pc + 1] = 0xAD;
emu.V[0] = 0x10;
emu.fetch_op_code();
REQUIRE(emu.pc == 0x10 + 0x0AAD);
}
TEST_CASE("0xCXNN - Sets VX to the result of a bitwise and operation on a random number [0-255]", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xC1;
emu.memory[emu.pc + 1] = 0x00;
emu.V[1] = 0x40;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
// TODO - Backfill this test
TEST_CASE("0xDXYN - Draws a sprite at coordinate (VX, VY). Sprite is 8x8 pixels", "[OP_CODE]") {
Chip8Emu emu;
bool video_cb_was_called = false;
emu.render_video_frame_cb = [&](const uint8_t *vfx, std::size_t size) {
video_cb_was_called = true;
REQUIRE(vfx == emu.vfx.data());
REQUIRE(size == emu.vfx.size());
return true;
};
emu.memory[emu.pc + 0] = 0xD1;
emu.memory[emu.pc + 1] = 0x22;
emu.V[1] = 0x00;
emu.V[2] = 0x00;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
REQUIRE(video_cb_was_called);
}
TEST_CASE("0xDXYN - Should not error out if no video callback was provided", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xD1;
emu.memory[emu.pc + 1] = 0x22;
emu.V[1] = 0x00;
emu.V[2] = 0x00;
REQUIRE_NOTHROW(emu.fetch_op_code());
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xEX9E - Skips the next instruction because the key stored in VX is pressed.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xE1;
emu.memory[emu.pc + 1] = 0x9E;
//Store that there was a key change in register V1 for key 0
emu.V[1] = 0x00;
// The key 0 was pressed!
emu.input_keys[0] = Chip8Emu::KeyState::PRESSED;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0xEX9E - Does not skip the next instruction because the key stored in VX was not pressed.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xE1;
emu.memory[emu.pc + 1] = 0x9E;
emu.V[1] = 0x00;
emu.input_keys[0] = Chip8Emu::KeyState::RELEASED;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xEXA1 - Skips the next instruction because the key stored in VX isn't pressed.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xE1;
emu.memory[emu.pc + 1] = 0xA1;
emu.V[1] = 0x00;
emu.input_keys[0] = Chip8Emu::KeyState::RELEASED;
emu.fetch_op_code();
REQUIRE(next_instruction_was_skipped(emu));
}
TEST_CASE("0xEXA1 - Does not skip the next instruction because the key stored in VX is pressed.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xE1;
emu.memory[emu.pc + 1] = 0xA1;
emu.V[1] = 0x00;
emu.input_keys[0] = Chip8Emu::KeyState::PRESSED;
emu.fetch_op_code();
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX07 - Sets VX to the value of the delay timer.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x07;
emu.delay_timer = 0x05;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x05u);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX0A - A key press is awaited, and then stored in VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x0A;
emu.V[1] = 0x00;
emu.input_keys[1] = Chip8Emu::KeyState::RELEASED;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x00);
REQUIRE(instruction_has_not_changed(emu));
emu.input_keys[1] = Chip8Emu::KeyState::PRESSED;
emu.fetch_op_code();
REQUIRE(emu.V[1] == 0x01);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX15 - Sets the delay timer to VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x15;
emu.V[1] = 0x07;
emu.fetch_op_code();
REQUIRE(emu.delay_timer == 0x07);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX18 - Sets the sound timer to VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x18;
emu.V[1] = 0x09;
emu.fetch_op_code();
REQUIRE(emu.sound_timer == 0x09);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX1E - Adds VX to I. VF is not affected.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x1E;
emu.V[1] = 0x09;
emu.i_register = 0x01;
emu.fetch_op_code();
REQUIRE(emu.i_register == 0x09 + 0x01);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX29 - Sets I to the location of the sprite for the character in VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x29;
emu.V[1] = 0x09;
emu.i_register = 0x01;
emu.fetch_op_code();
REQUIRE(emu.i_register == 0x09 * 0x5);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("0xFX33 - Stores the binary-coded decimal representation of VX.", "[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xF1;
emu.memory[emu.pc + 1] = 0x33;
emu.V[1] = 128;
emu.fetch_op_code();
REQUIRE(emu.memory[emu.i_register + 0] == 1);
REQUIRE(emu.memory[emu.i_register + 1] == 2);
REQUIRE(emu.memory[emu.i_register + 2] == 8);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE(
"0xFX55 - Stores V0 to VX (including VX) in memory starting at address I. The offset from I is increased by 1 for each value written, but I itself is left unmodified.",
"[OP_CODE]") {
Chip8Emu emu;
emu.i_register = 1000;
emu.memory[emu.pc + 0] = 0xFF;
emu.memory[emu.pc + 1] = 0x55;
emu.V[0x00] = 0x00;
emu.V[0x01] = 0x01;
emu.V[0x02] = 0x02;
emu.V[0x03] = 0x03;
emu.V[0x04] = 0x04;
emu.V[0x05] = 0x05;
emu.V[0x06] = 0x06;
emu.V[0x07] = 0x07;
emu.V[0x08] = 0x08;
emu.V[0x09] = 0x09;
emu.V[0xA] = 0xA;
emu.V[0xB] = 0xB;
emu.V[0xC] = 0xC;
emu.V[0xD] = 0xD;
emu.V[0xE] = 0xE;
emu.V[0xF] = 0xF;
emu.fetch_op_code();
REQUIRE(emu.memory[emu.i_register + 0] == 0x00);
REQUIRE(emu.memory[emu.i_register + 1] == 0x01);
REQUIRE(emu.memory[emu.i_register + 2] == 0x02);
REQUIRE(emu.memory[emu.i_register + 0xF] == 0xF);
REQUIRE(emu.i_register == 1000);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE(
"0xFX65 - Fills V0 to VX (including VX) with values from memory starting at address I. The offset from I is increased by 1 for each value written, but I itself is left unmodified.",
"[OP_CODE]") {
Chip8Emu emu;
emu.memory[emu.pc + 0] = 0xFF;
emu.memory[emu.pc + 1] = 0x65;
emu.memory[emu.i_register + 0x00] = 0x00;
emu.memory[emu.i_register + 0x01] = 0x01;
emu.memory[emu.i_register + 0x02] = 0x02;
emu.memory[emu.i_register + 0x03] = 0x03;
emu.memory[emu.i_register + 0x04] = 0x04;
emu.memory[emu.i_register + 0x05] = 0x05;
emu.memory[emu.i_register + 0x06] = 0x06;
emu.memory[emu.i_register + 0x07] = 0x07;
emu.memory[emu.i_register + 0x08] = 0x08;
emu.memory[emu.i_register + 0x09] = 0x09;
emu.memory[emu.i_register + 0xA] = 0xA;
emu.memory[emu.i_register + 0xB] = 0xB;
emu.memory[emu.i_register + 0xC] = 0xC;
emu.memory[emu.i_register + 0xD] = 0xD;
emu.memory[emu.i_register + 0xE] = 0xE;
emu.memory[emu.i_register + 0xF] = 0xF;
emu.fetch_op_code();
REQUIRE(emu.V[0] == 0x00);
REQUIRE(emu.V[1] == 0x01);
REQUIRE(emu.V[2] == 0x02);
REQUIRE(emu.V[0xF] == 0xF);
REQUIRE(emu.i_register == 0);
REQUIRE(instruction_was_incremented_normally(emu));
}
TEST_CASE("A game file can be loaded and copied into memory, starting at 0x200 (pc)", "[LOADING_GAME]") {
Chip8Emu emu;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.memory[emu.pc + 0] == 'T');
REQUIRE(emu.memory[emu.pc + 1] == 'E');
REQUIRE(emu.memory[emu.pc + 2] == 'S');
REQUIRE(emu.memory[emu.pc + 3] == 'T');
REQUIRE(emu.memory[emu.pc + 4] == '_');
REQUIRE(emu.memory[emu.pc + 5] == 'R');
REQUIRE(emu.memory[emu.pc + 6] == 'O');
REQUIRE(emu.memory[emu.pc + 7] == 'M');
REQUIRE(emu.memory[emu.pc + 8] == '\n');
REQUIRE(emu.memory[emu.pc + 9] == '\0');
REQUIRE(emu.game_loaded_flag == true);
}
TEST_CASE("Should throw an error if the game file could not be found", "[LOADING_GAME]") {
Chip8Emu emu;
REQUIRE_THROWS_AS(emu.load("BAD_FILE_PATH"), std::runtime_error);
REQUIRE(game_memory_locations_are_zeroed_out(emu));
}
TEST_CASE("Should throw an error if a game was not loaded before running a cycle", "[RUN]") {
Chip8Emu emu;
REQUIRE_THROWS_AS(emu.run(), std::runtime_error);
}
TEST_CASE("Should run the emulator for a single cycle", "[RUN]") {
Chip8Emu emu;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.game_loaded_flag);
REQUIRE_NOTHROW(emu.run());
}
TEST_CASE("Should count down the delay and sound timers by 1 each time the emulator is run when values are above zero",
"[RUN]") {
Chip8Emu emu;
emu.delay_timer = 60;
emu.sound_timer = 60;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.game_loaded_flag);
REQUIRE_NOTHROW(emu.run());
REQUIRE(emu.delay_timer == 59);
REQUIRE(emu.sound_timer == 59);
}
TEST_CASE("Should not count down the delay and sound timers because the timer values are 0", "[RUN]") {
Chip8Emu emu;
emu.sound_timer = 0;
emu.delay_timer = 0;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.game_loaded_flag);
REQUIRE_NOTHROW(emu.run());
REQUIRE(emu.delay_timer == 0);
REQUIRE(emu.sound_timer == 0);
}
TEST_CASE("Should call the audio callback when the sound timer is 1", "[RUN]") {
Chip8Emu emu;
emu.sound_timer = 1;
bool audio_cb_was_called = false;
emu.play_audio_cb = [&]() {
audio_cb_was_called = true;
return true;
};
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.game_loaded_flag);
REQUIRE_NOTHROW(emu.run());
REQUIRE(emu.sound_timer == 0);
REQUIRE(audio_cb_was_called);
}
TEST_CASE("Should not error out when the sound timer is 1 and no audio callback was provided", "[RUN]") {
Chip8Emu emu;
emu.sound_timer = 1;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE(emu.game_loaded_flag);
REQUIRE_NOTHROW(emu.run());
REQUIRE(emu.sound_timer == 0);
}
TEST_CASE("Should the input key states when run is called", "[RUN]") {
Chip8Emu emu;
for (uint8_t key : emu.input_keys) {
REQUIRE(key == 0);
}
bool update_input_key_cb_was_called = false;
emu.update_input_key_state_cb = [&](size_t key) -> uint8_t {
update_input_key_cb_was_called = true;
return 1;
};
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE_NOTHROW(emu.run());
REQUIRE(update_input_key_cb_was_called);
for (uint8_t key : emu.input_keys) {
REQUIRE(key == 1);
}
}
TEST_CASE("Should not error out when the update input key callback is not provided to the emulator", "[RUN]") {
Chip8Emu emu;
FakeGameFile fakeGameFile;
REQUIRE_NOTHROW(emu.load(fakeGameFile.file_name));
REQUIRE_NOTHROW(emu.run());
} | 23.1625 | 189 | 0.630014 | Druage |
f81e8e655066cfe98a25dd02f71a800d4c3d0306 | 892 | hpp | C++ | libs/geometry/test/algorithms/length/linestring_cases.hpp | lijgame/boost | ec2214a19cdddd1048058321a8105dd0231dac47 | [
"BSL-1.0"
] | 1 | 2018-12-15T19:57:24.000Z | 2018-12-15T19:57:24.000Z | thirdparty-cpp/boost_1_62_0/libs/geometry/test/algorithms/length/linestring_cases.hpp | nxplatform/nx-mobile | 0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5 | [
"Apache-2.0"
] | null | null | null | thirdparty-cpp/boost_1_62_0/libs/geometry/test/algorithms/length/linestring_cases.hpp | nxplatform/nx-mobile | 0dc174c893f2667377cb2ef7e5ffeb212fa8b3e5 | [
"Apache-2.0"
] | null | null | null | #ifndef LINESTRING_CASES_HPP
#define LINESTRING_CASES_HPP
#include <string>
static std::string Ls_data_geo[] = {"LINESTRING(0 90,1 80,1 70)",
"LINESTRING(0 90,1 80,1 80,1 80,1 70,1 70)",
"LINESTRING(0 90,1 80,1 79,1 78,1 77,1 76,1 75,1 74,\
1 73,1 72,1 71,1 70)"};
static std::string Ls_data_sph[] = {"LINESTRING(0 0,180 0,180 180)",
"LINESTRING(0 0,180 0,180 0,180 0,180 180,180 180)",
"LINESTRING(0 0,180 0,180 10,180 20,180 30,180 40,180 50,180 60,\
180 70,180 80,180 90,180 100,180 110,180 120,180 130,\
180 140,180 150,180 160,180 170,180 180)"};
#endif // LINESTRING_CASES_HPP
| 49.555556 | 103 | 0.457399 | lijgame |
f81e9ab9ecd763d4f850d347001ec48759cf1519 | 7,704 | cpp | C++ | Source/Renderer/Public/Resource/MaterialBlueprint/Cache/GraphicsPipelineStateSignature.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 187 | 2015-11-02T21:27:57.000Z | 2022-02-17T21:39:17.000Z | Source/Renderer/Public/Resource/MaterialBlueprint/Cache/GraphicsPipelineStateSignature.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | null | null | null | Source/Renderer/Public/Resource/MaterialBlueprint/Cache/GraphicsPipelineStateSignature.cpp | cofenberg/unrimp | 90310657f106eb83f3a9688329b78619255a1042 | [
"MIT"
] | 20 | 2015-11-04T19:17:01.000Z | 2021-11-18T11:23:25.000Z | /*********************************************************\
* Copyright (c) 2012-2021 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "Renderer/Public/Resource/MaterialBlueprint/Cache/GraphicsPipelineStateSignature.h"
#include "Renderer/Public/Resource/MaterialBlueprint/MaterialBlueprintResourceManager.h"
#include "Renderer/Public/Resource/MaterialBlueprint/MaterialBlueprintResource.h"
#include "Renderer/Public/Resource/ShaderBlueprint/ShaderBlueprintResourceManager.h"
#include "Renderer/Public/Resource/ShaderBlueprint/ShaderBlueprintResource.h"
#include "Renderer/Public/Core/Math/Math.h"
#include "Renderer/Public/IRenderer.h"
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Renderer
{
//[-------------------------------------------------------]
//[ Public static methods ]
//[-------------------------------------------------------]
ShaderCombinationId GraphicsPipelineStateSignature::generateShaderCombinationId(const ShaderBlueprintResource& shaderBlueprintResource, const ShaderProperties& shaderProperties)
{
ShaderCombinationId shaderCombinationId(Math::FNV1a_INITIAL_HASH_32);
{ // Apply shader blueprint resource ID
const ShaderBlueprintResourceId shaderBlueprintResourceId = shaderBlueprintResource.getId();
shaderCombinationId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&shaderBlueprintResourceId), sizeof(uint32_t), shaderCombinationId);
}
// Apply shader properties
const ShaderProperties& referencedShaderProperties = shaderBlueprintResource.getReferencedShaderProperties();
for (const ShaderProperties::Property& property : shaderProperties.getSortedPropertyVector())
{
// Use the additional information to reduce the shader properties in order to generate fewer combinations
const ShaderPropertyId shaderPropertyId = property.shaderPropertyId;
if (referencedShaderProperties.hasPropertyValue(shaderPropertyId))
{
// No need to check for zero-value shader properties in here, already optimized out by "Renderer::MaterialBlueprintResource::optimizeShaderProperties()"
// Apply shader property ID
shaderCombinationId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&shaderPropertyId), sizeof(uint32_t), shaderCombinationId);
// Apply shader property value
shaderCombinationId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&property.value), sizeof(int32_t), shaderCombinationId);
}
}
// Done
return shaderCombinationId;
}
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
GraphicsPipelineStateSignature::GraphicsPipelineStateSignature(const GraphicsPipelineStateSignature& graphicsPipelineStateSignature) :
mMaterialBlueprintResourceId(graphicsPipelineStateSignature.mMaterialBlueprintResourceId),
mSerializedGraphicsPipelineStateHash(graphicsPipelineStateSignature.mSerializedGraphicsPipelineStateHash),
mShaderProperties(graphicsPipelineStateSignature.mShaderProperties),
mGraphicsPipelineStateSignatureId(graphicsPipelineStateSignature.mGraphicsPipelineStateSignatureId),
mShaderCombinationId{graphicsPipelineStateSignature.mShaderCombinationId[0], graphicsPipelineStateSignature.mShaderCombinationId[1], graphicsPipelineStateSignature.mShaderCombinationId[2], graphicsPipelineStateSignature.mShaderCombinationId[3], graphicsPipelineStateSignature.mShaderCombinationId[4]}
{
// Nothing here
}
GraphicsPipelineStateSignature& GraphicsPipelineStateSignature::operator=(const GraphicsPipelineStateSignature& graphicsPipelineStateSignature)
{
mMaterialBlueprintResourceId = graphicsPipelineStateSignature.mMaterialBlueprintResourceId;
mSerializedGraphicsPipelineStateHash = graphicsPipelineStateSignature.mSerializedGraphicsPipelineStateHash;
mShaderProperties = graphicsPipelineStateSignature.mShaderProperties;
mGraphicsPipelineStateSignatureId = graphicsPipelineStateSignature.mGraphicsPipelineStateSignatureId;
for (uint8_t i = 0; i < NUMBER_OF_GRAPHICS_SHADER_TYPES; ++i)
{
mShaderCombinationId[i] = graphicsPipelineStateSignature.mShaderCombinationId[i];
}
// Done
return *this;
}
void GraphicsPipelineStateSignature::set(const MaterialBlueprintResource& materialBlueprintResource, uint32_t serializedGraphicsPipelineStateHash, const ShaderProperties& shaderProperties)
{
mMaterialBlueprintResourceId = materialBlueprintResource.getId();
mSerializedGraphicsPipelineStateHash = serializedGraphicsPipelineStateHash;
mShaderProperties = shaderProperties;
mGraphicsPipelineStateSignatureId = Math::FNV1a_INITIAL_HASH_32;
for (uint8_t i = 0; i < NUMBER_OF_GRAPHICS_SHADER_TYPES; ++i)
{
mShaderCombinationId[i] = getInvalid<ShaderCombinationId>();
}
// Incorporate primitive hashes
mGraphicsPipelineStateSignatureId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&mMaterialBlueprintResourceId), sizeof(uint32_t), mGraphicsPipelineStateSignatureId);
mGraphicsPipelineStateSignatureId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&mSerializedGraphicsPipelineStateHash), sizeof(uint32_t), mGraphicsPipelineStateSignatureId);
// Incorporate shader related hashes
const ShaderBlueprintResourceManager& shaderBlueprintResourceManager = materialBlueprintResource.getResourceManager<MaterialBlueprintResourceManager>().getRenderer().getShaderBlueprintResourceManager();
for (uint8_t i = 0; i < NUMBER_OF_GRAPHICS_SHADER_TYPES; ++i)
{
const ShaderBlueprintResource* shaderBlueprintResource = shaderBlueprintResourceManager.tryGetById(materialBlueprintResource.getGraphicsShaderBlueprintResourceId(static_cast<GraphicsShaderType>(i)));
if (nullptr != shaderBlueprintResource)
{
const uint32_t hash = mShaderCombinationId[i] = generateShaderCombinationId(*shaderBlueprintResource, mShaderProperties);
mGraphicsPipelineStateSignatureId = Math::calculateFNV1a32(reinterpret_cast<const uint8_t*>(&hash), sizeof(uint32_t), mGraphicsPipelineStateSignatureId);
}
}
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Renderer
| 56.647059 | 302 | 0.726246 | cofenberg |
f82a14d7328b9727dd80b1d377a0db0b62489233 | 15,988 | cpp | C++ | Source/CSwing.cpp | sizlo/SwingGame | d60e9214998082e8a75dfbe620188a46beb12369 | [
"MIT"
] | null | null | null | Source/CSwing.cpp | sizlo/SwingGame | d60e9214998082e8a75dfbe620188a46beb12369 | [
"MIT"
] | 2 | 2015-02-20T19:09:32.000Z | 2015-02-22T15:16:58.000Z | Source/CSwing.cpp | sizlo/SwingGame | d60e9214998082e8a75dfbe620188a46beb12369 | [
"MIT"
] | null | null | null | //
// CSwing.cpp
// SwingGame
//
// Created by Tim Brier on 31/10/2014.
// Copyright (c) 2014 tbrier. All rights reserved.
//
// =============================================================================
// Include Files
// -----------------------------------------------------------------------------
#include "CSwing.hpp"
#include "CSwingGame.hpp"
#include "CLevel.hpp"
#include "CollisionHandler.hpp"
// =============================================================================
// Static members
// -----------------------------------------------------------------------------
float CSwing::smMaxLength = 500.0f;
float CSwing::smMinLength = 25.0f;
float CSwing::smClimbSpeed = 100.0f;
float CSwing::smCollisionIgnoreDistance = 1.0f;
float CSwing::smAnchorGap = 5.0f;
float CSwing::smReflectionScaleFactor = -1.0f;
// =============================================================================
// CSwing constructor/destructor
// -----------------------------------------------------------------------------
CSwing::CSwing(CPlayer *theBob, CLevel *theParentLevel)
: mBob(theBob),
mParentLevel(theParentLevel),
mAttached(false),
mColour(CColour::Black)
{
}
CSwing::~CSwing()
{
// Unregister this x-able
if (mAttached)
{
CSwingGame::UnregisterRenderable(this);
CSwingGame::UnregisterUpdateable(this);
}
}
// =============================================================================
// CSwing::AttemptToAttach
// Find the first point between the bob and the aim point to attach to
// -----------------------------------------------------------------------------
void CSwing::AttemptToAttach(CVector2f theAimPoint)
{
// Attach the swing if we can find a valid anchor point
CVector2f anchorPoint;
if (IsThereAValidAnchor(theAimPoint, &anchorPoint))
{
// Make sure we detach from any existing swing
Detach();
// Now attach
mAttached = true;
mOrigin = anchorPoint;
mOriginDrawPoint = mOrigin;
mLength = GetDistanceToBob();
RespondToAttach();
// Register ourselves now we're active
CSwingGame::RegisterRenderable(this);
CSwingGame::RegisterUpdateable(this);
}
}
// =============================================================================
// CSwing::Detach
// -----------------------------------------------------------------------------
void CSwing::Detach(bool shouldRespond /* = false */)
{
if (mAttached)
{
mAttached = false;
CSwingGame::UnregisterUpdateable(this);
CSwingGame::UnregisterRenderable(this);
if (shouldRespond)
{
RespondToDetach();
}
}
}
// =============================================================================
// CSwing::AttenuateGravity
// Alter the affect of gravity based on the swings angle
// -----------------------------------------------------------------------------
CVector2f CSwing::AttenuateGravity(CVector2f gravity)
{
// If we're not attached then don't affect gravity
if (!mAttached)
{
return gravity;
}
// Throw away any component of the gravity that isn't perpendicular to the
// swing
return gravity.GetComponentInDirection(GetPerpendicularDirection());
}
// =============================================================================
// CSwing::Draw
// -----------------------------------------------------------------------------
void CSwing::Draw(CWindow *theWindow)
{
// The line
DrawSwingSection(theWindow, mOrigin, mBob->GetPosition());
// The anchor
DrawAnchorPoint(theWindow, mOriginDrawPoint);
}
// =============================================================================
// CSwing::Update
// -----------------------------------------------------------------------------
void CSwing::Update(CTime elapsedTime)
{
DetachIfAnchorIsNotValid();
if (mAttached)
{
HandleInput(elapsedTime);
// Adjust the velocity so it is perpendicular to the swing
CVector2f v = mBob->GetVelocity();
CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
newV.Normalise();
newV *= v.GetMagnitude();
mBob->SetVelocity(newV);
// Make sure the bob isn't further away from the origin than the length
// of the swing
CVector2f bobToOrigin = mOrigin - mBob->GetPosition();
float distance = bobToOrigin.GetMagnitude();
if (distance != mLength)
{
// Move by the difference between the distance and length
float moveDistance = distance - mLength;
bobToOrigin.Normalise();
bobToOrigin *= moveDistance;
mBob->MoveFixedDistanceUntilCollision(bobToOrigin);
}
HandleCollisions();
}
}
// =============================================================================
// CSwing::ShouldUpdateForGameState
// -----------------------------------------------------------------------------
bool CSwing::ShouldUpdateForState(EGameState theState)
{
// Only update if we're not paused
if ((theState & kGameStatePaused) != 0)
{
return false;
}
return CUpdateable::ShouldUpdateForState(theState);
}
// =============================================================================
// CSwing::CanJumpFrom
// -----------------------------------------------------------------------------
bool CSwing::CanJumpFrom()
{
// Most swings can't be jumped from
return false;
}
// =============================================================================
// CSwing::IsAttached
// -----------------------------------------------------------------------------
bool CSwing::IsAttached()
{
return mAttached;
}
// =============================================================================
// CSwing::GetColour
// -----------------------------------------------------------------------------
CColour CSwing::GetColour()
{
return mColour;
}
// =============================================================================
// CSwing::GetDistanceToBob
// -----------------------------------------------------------------------------
float CSwing::GetDistanceToBob()
{
CVector2f bobPosition = mBob->GetPosition();
CVector2f bobToOrigin = mOrigin - bobPosition;
return bobToOrigin.GetMagnitude();
}
// =============================================================================
// CSwing::IsThereAValidAnchor
// -----------------------------------------------------------------------------
bool CSwing::IsThereAValidAnchor(CVector2f theAimPoint, CVector2f *anchor)
{
bool validPointFound = false;
// Find the direction from the bob to the aim point
CVector2f bobPosition = mBob->GetPosition();
CVector2f aimDirection = theAimPoint - bobPosition;
aimDirection.Normalise();
// Make sure there is nothing in the way of the swing until we reach the
// minimum swing length
float currentLength = 0.0f;
CVector2f currentSamplePoint = bobPosition;
CCircleShape anchorShape(smAnchorGap);
std::list<CPhysicsBody *> obstacles = mParentLevel->GetObstacles();
CVector2f cv;
bool blockingObjectFound = false;
while (!blockingObjectFound && currentLength < smMinLength)
{
anchorShape.setPosition(currentSamplePoint);
FOR_EACH_IN_LIST(CPhysicsBody*, obstacles)
{
CConvexShape obstacleShape = *((*it)->GetShape());
if (CollisionHandler::AreColliding(anchorShape, obstacleShape, &cv))
{
blockingObjectFound = true;
}
}
// Now move to the next sample point
currentLength += 1.0f;
currentSamplePoint += aimDirection;
}
// Now start at the minimum swing length and sample at each unit point
// along the possible rope points until we reach the max swing length
// At each point see if an anchor collides with any obstacles
// As soon as it collides this is the anchor point
currentLength = smMinLength;
currentSamplePoint = bobPosition + (aimDirection * currentLength);
while (!validPointFound
&& !blockingObjectFound
&& currentLength <= smMaxLength)
{
anchorShape.setPosition(currentSamplePoint);
FOR_EACH_IN_LIST(CPhysicsBody*, obstacles)
{
CConvexShape obstacleShape = *((*it)->GetShape());
if (CollisionHandler::AreColliding(anchorShape, obstacleShape, &cv))
{
validPointFound = true;
anchor->x = currentSamplePoint.x;
anchor->y = currentSamplePoint.y;
}
}
// Now move to the next sample point
currentLength += 1.0f;
currentSamplePoint += aimDirection;
}
return validPointFound;
}
// =============================================================================
// CSwing::GetPerpendicularDirection
// -----------------------------------------------------------------------------
CVector2f CSwing::GetPerpendicularDirection()
{
CVector2f originToBob = mBob->GetPosition() - mOrigin;
originToBob.Normalise();
CVector2f perpendicularDirection;
perpendicularDirection.x = originToBob.y;
perpendicularDirection.y = -originToBob.x;
return perpendicularDirection;
}
// =============================================================================
// CSwing::HandleInput
// -----------------------------------------------------------------------------
void CSwing::HandleInput(CTime elapsedTime)
{
CVector2f climbOffset = CVector2f(0.0f, 0.0f);
CVector2f climbDirection = mOrigin - mBob->GetPosition();
climbDirection.Normalise();
// Climb while w is pressed
if (CKeyboard::isKeyPressed(CKeyboard::W))
{
climbOffset += climbDirection * smClimbSpeed * elapsedTime.asSeconds();
}
// Descend while s is presses
if (CKeyboard::isKeyPressed(CKeyboard::S))
{
climbOffset -= climbDirection * smClimbSpeed * elapsedTime.asSeconds();
}
if (climbOffset .GetMagnitude() > 0)
{
mBob->MoveFixedDistanceUntilCollision(climbOffset);
mLength = GetDistanceToBob();
mLength = std::min(mLength, smMaxLength);
mLength = std::max(mLength, smMinLength);
}
}
// =============================================================================
// CSwing::HandleCollisions
// -----------------------------------------------------------------------------
void CSwing::HandleCollisions()
{
// Keep track of the closest intersection to the origin we care about
bool validIntersectionFound = false;
float distanceToClosestIntersection = smMaxLength;
CVector2f closestIntersection;
// Check for collisions with all obstacles in the level
CLine theLine = CLine(mOrigin, mBob->GetPosition());
std::list<CPhysicsBody *> theObstacles = mParentLevel->GetObstacles();
FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)
{
CPhysicsBody *theObs = (*it);
CConvexShape theShape = *(theObs->GetShape());
std::list<CVector2f> theIntPoints;
if (CollisionHandler::AreIntersecting(theLine, theShape, &theIntPoints))
{
FOR_EACH_IN_LIST(CVector2f, theIntPoints)
{
CVector2f thisIntersection = (*it);
CVector2f originToInt = thisIntersection - mOrigin;
float distanceToThisIntersection = originToInt.GetMagnitude();
if (distanceToThisIntersection > smCollisionIgnoreDistance)
{
validIntersectionFound = true;
// Only record this if its closer to the origin
if (distanceToThisIntersection < distanceToClosestIntersection)
{
distanceToClosestIntersection = distanceToThisIntersection;
closestIntersection = thisIntersection;
}
}
}
}
}
// If we found a collision we care about then handle it
if (validIntersectionFound)
{
RespondToCollisionAt(closestIntersection);
}
}
// =============================================================================
// CSwing::DetachIfAnchorIsNotValid
// -----------------------------------------------------------------------------
void CSwing::DetachIfAnchorIsNotValid()
{
if (mAttached)
{
CCircleShape anchorShape(smAnchorGap);
anchorShape.setPosition(mOrigin);
std::list<CPhysicsBody*> theObstacles = mParentLevel->GetObstacles();
CVector2f cv;
bool collisionFound = false;
FOR_EACH_IN_LIST(CPhysicsBody*, theObstacles)
{
if (CollisionHandler::AreColliding(anchorShape,
*((*it)->GetShape()),
&cv))
{
collisionFound = true;
}
}
if (!collisionFound)
{
Detach();
}
}
}
// =============================================================================
// CSwing::DrawAnchorPoint
// -----------------------------------------------------------------------------
void CSwing::DrawAnchorPoint(CWindow *theWindow, CVector2f theAnchor)
{
CCircleShape theCircle = CCircleShape(smAnchorGap);
theCircle.setPosition(theAnchor);
theCircle.setOutlineColor(CColour::Black);
theCircle.setOutlineThickness(1.0f);
theCircle.setFillColor(CColour::Transparent);
theWindow->draw(theCircle);
}
// =============================================================================
// CSwing::DrawSwingSection
// -----------------------------------------------------------------------------
void CSwing::DrawSwingSection(CWindow *theWindow,
CVector2f start,
CVector2f end)
{
theWindow->DrawLine(CLine(start, end), mColour);
}
// =============================================================================
// CSwing::RespondToAttach
// -----------------------------------------------------------------------------
void CSwing::RespondToAttach()
{
// Throw away any velocity that isn't perpendicular to the swing
CVector2f v = mBob->GetVelocity();
CVector2f newV = v.GetComponentInDirection(GetPerpendicularDirection());
mBob->SetVelocity(newV);
}
// =============================================================================
// CSwing::RespondToDetach
// -----------------------------------------------------------------------------
void CSwing::RespondToDetach()
{
// Do nothing for the basic swing type
}
// =============================================================================
// CSwing::RespondToCollisionAt
// -----------------------------------------------------------------------------
void CSwing::RespondToCollisionAt(CVector2f intersectionPoint)
{
// Seperate the swing and the obstacle
AdjustDirectionToGoThrough(intersectionPoint);
// For this rigid swing we'll just reflect the players velocity
// Apply a scaling factor as well so we can dampen it
mBob->SetVelocity(mBob->GetVelocity() * smReflectionScaleFactor);
}
// =============================================================================
// CSwing::AdjustDirectionToGoThrough
// -----------------------------------------------------------------------------
void CSwing::AdjustDirectionToGoThrough(CVector2f targetPoint)
{
CVector2f originToTarget = targetPoint - mOrigin;
originToTarget.Normalise();
originToTarget *= mLength;
CVector2f newBobPosition = mOrigin + originToTarget;
mBob->SetPosition(newBobPosition);
} | 34.162393 | 83 | 0.485864 | sizlo |
f82a6d3ec33196552bc60c3bde766c84b68dff29 | 1,607 | cpp | C++ | HackerEarth/DynamicPrograming/coin-problem.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 3 | 2017-12-27T04:58:16.000Z | 2018-02-05T14:11:06.000Z | HackerEarth/DynamicPrograming/coin-problem.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 4 | 2018-10-04T07:45:07.000Z | 2018-11-23T17:36:20.000Z | HackerEarth/DynamicPrograming/coin-problem.cpp | Gmaurya/data-structure-and-algorithms | 9f9790140719d24d15ee401e0d11a99dedde4235 | [
"MIT"
] | 8 | 2018-10-02T20:34:58.000Z | 2018-10-07T14:27:53.000Z | #include<iostream>
#include<bits/stdc++.h>
// iteration and input/output stream
#define rep(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))
#define srep(i, begin, end) for (__typeof(end) i = begin; i != end; i++)
#define si(x) int x; scanf("%d", &x)
#define sll(x) ll x; scanf("%lld", &x)
#define pi(x) printf("%d", x)
#define pll(x) printf("%lld", x)
#define nl prinf("\n")
#define tr(cont,it) \
for(decltype(cont.begin()) it = cont.begin(); it!= cont.end() ; it++)
#define tc() int t; cin >> t ; while (t--)
//STL shortcuts
#define pb push_back
#define pf push_front
#define pob pop_back
#define pof pop_front
#define F first
#define S second
#define MP make_pair
using namespace std;
typedef long long int ll; // 64 bit integer
typedef unsigned long long int ull; // 64 bit unsigned integer
typedef long double ld;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vll;
typedef pair<int,int> pii;
typedef pair<int,ll> pill;
inline void smax(int &x , int y) { x = max(x , y) ; }
inline void smin(int &x , int y) { x = min(x , y) ; }
#define MOD 1000000007
#define inf 4000000000000000000LL
#define SYNC std::ios::sync_with_stdio(false); cin.tie(NULL);
ll gcd(ll a,ll b){ return ((b==0)? a:gcd(b,a%b) ); }
int main()
{
SYNC
int m;
cin>>m;
vll dp(1000001);
dp[0] =1;
dp[1] = 2;
dp[2] = 4;
dp[3] = 7;
rep(i,4,1000001)
dp[i] = ((dp[i-1]*2)%MOD -dp[i-4] + MOD)%MOD ;
rep(i,0,m)
{
int n;
cin>>n;
cout<<dp[n]<<endl;
}
} | 25.507937 | 142 | 0.598009 | Gmaurya |
f830b772ce537c5a50b56030abf13f164d0d8f21 | 1,850 | cpp | C++ | CORE/Source/Entities/GUI Objects/ButtonComponents/MouseProcesor.cpp | pike4/CORE-Dev-Build-1.0 | 08376bae09a8bb3598f4aa8edfacd1ca1c45eaa3 | [
"MIT"
] | 3 | 2016-10-06T22:42:50.000Z | 2016-10-14T16:04:46.000Z | CORE/Source/Entities/GUI Objects/ButtonComponents/MouseProcesor.cpp | pike4/CORE-Dev-Build-1.0 | 08376bae09a8bb3598f4aa8edfacd1ca1c45eaa3 | [
"MIT"
] | null | null | null | CORE/Source/Entities/GUI Objects/ButtonComponents/MouseProcesor.cpp | pike4/CORE-Dev-Build-1.0 | 08376bae09a8bb3598f4aa8edfacd1ca1c45eaa3 | [
"MIT"
] | null | null | null | #include "MouseProcessor.h"
#include "QuadTree.h"
#include "Entity.h"
#include "Data.h"
bool isWithin(int pointX, int pointY, int rectX, int rectY, int rectW, int rectH)
{
return ((pointX > rectX) && (pointX < (rectX + rectW))
&& (pointY > rectY) && (pointY < (rectY + rectH)));
}
MouseProcessor::MouseProcessor()
{
events.push_back(mouseMoved);
events.push_back(mouse1Down);
events.push_back(mouse1Up);
}
void MouseProcessor::handle(Event e)
{
if (!parent)
{
return;
}
bool newWithin = false;
switch (e.opcode)
{
DataImpl<int>* aX;
DataImpl<int>* aY;
case mouseMoved:
aX = (DataImpl<int>*) e.arguments[0].data;
aY = (DataImpl<int>*) e.arguments[1].data;
newWithin = isWithin(*aX, *aY, *x, *y, *w, *h);
if (mouseIsDownOnThis)
{
Event dragEvent = mouseDrag;
DataImpl<int> doX;
doX = dragOriginX;
DataImpl<int> doY;
doY = dragOriginY;
DataImpl<bool> isUp;
isUp = true;
dragEvent.arguments = { &doX, &doY, &isUp };
parent->handle(dragEvent);
}
if (!mouseIsWithin && newWithin)
{
mouseIsWithin = true;
parent->handle(mouseEnter);
}
else if (mouseIsWithin && !newWithin)
{
mouseIsWithin = false;
parent->handle(mouseLeave);
}
break;
case mouse1Down:
aX = (DataImpl<int>*) e.arguments[1].data;
aY = (DataImpl<int>*) e.arguments[2].data;
if (isWithin(*aX, *aY, *x, *y, *w, *h))
{
mouseIsDownOnThis = true;
dragOriginX = *aX - *x;
dragOriginY = *aY - *y;
parent->handle(mousePress);
}
if (!mouseTimer.hasElapsed(0))
{
parent->handle(doubleClick);
}
mouseTimer.updateTime();
break;
case mouse1Up:
if (mouseIsDownOnThis)
{
mouseIsDownOnThis = false;
parent->handle(mouseRelease);
}
break;
}
} | 20.108696 | 82 | 0.595676 | pike4 |
f832a14a9abdd87591eb8d9414f913d85973acfc | 624 | hpp | C++ | deps/tinympl/tinympl/bool.hpp | gtaisbetterthanfn/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 186 | 2015-01-18T05:46:11.000Z | 2022-03-22T10:03:44.000Z | deps/tinympl/tinympl/bool.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 82 | 2015-01-14T01:02:04.000Z | 2022-03-20T23:55:59.000Z | deps/tinympl/tinympl/bool.hpp | AlisonMDL/modloader | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | [
"MIT"
] | 34 | 2015-01-07T11:17:00.000Z | 2022-02-28T00:16:20.000Z | // Copyright (C) 2013, Ennio Barbaro.
//
// Use, modification, and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://sbabbi.github.io/tinympl for documentation.
//
// You are welcome to contact the author at:
// enniobarbaro@gmail.com
//
#ifndef TINYMPL_BOOL_HPP
#define TINYMPL_BOOL_HPP
#include <type_traits>
namespace tinympl {
//! \ingroup NewTypes
//! Compile time bool
template<bool i> using bool_ = std::integral_constant<bool,i>;
} // namespace tinympl
#endif // TINYMPL_BOOL_HPP
| 23.111111 | 74 | 0.735577 | gtaisbetterthanfn |
f838055dcdc4cdff42952aefd9794805b96a3c55 | 3,057 | cpp | C++ | source/tastefulserver/source/http/RequestParameters.cpp | scheibel/tastefulserver | 69364fe5a1e2fb836ce471231f317d45154fc58f | [
"MIT"
] | 2 | 2015-07-07T16:54:32.000Z | 2021-04-13T08:32:59.000Z | source/tastefulserver/source/http/RequestParameters.cpp | scheibel/tasteful-server | 69364fe5a1e2fb836ce471231f317d45154fc58f | [
"MIT"
] | 1 | 2015-02-19T12:02:07.000Z | 2015-02-19T12:02:07.000Z | source/tastefulserver/source/http/RequestParameters.cpp | scheibel/tastefulserver | 69364fe5a1e2fb836ce471231f317d45154fc58f | [
"MIT"
] | 6 | 2015-07-08T00:23:43.000Z | 2020-02-06T16:12:53.000Z | #include <tastefulserver/RequestParameters.h>
#include <QUrl>
#include <QByteArray>
#include <QStringList>
#include <tastefulserver/MultiPart.h>
#include <tastefulserver/UploadedFile.h>
#include <tastefulserver/ByteStream.h>
namespace tastefulserver {
RequestParameters::RequestParameters()
{
}
void RequestParameters::clear()
{
m_params.clear();
m_files.clear();
}
RequestParameters RequestParameters::fromUrl(const QUrl & url)
{
RequestParameters params;
params.parseUrl(url);
return params;
}
RequestParameters RequestParameters::fromUrlEncoded(const QByteArray & urlEncodedPost)
{
RequestParameters params;
params.parseUrlEncoded(urlEncodedPost);
return params;
}
RequestParameters RequestParameters::fromMultiPart(const MultiPart & multiPart)
{
RequestParameters params;
params.parseMultiPart(multiPart);
return params;
}
void RequestParameters::parseUrl(const QUrl & url)
{
if (!url.hasQuery())
{
return;
}
for (const QString & parameter : url.query(QUrl::FullyDecoded).split('&'))
{
int splitIndex = parameter.indexOf('=');
if (splitIndex<=0)
{
continue;
}
QString key = parameter.left(splitIndex);
QString value = parameter.mid(splitIndex + 1);
m_params[key] = value;
}
}
void RequestParameters::parseUrlEncoded(const QByteArray & urlEncoded)
{
QByteArray copy(urlEncoded);
parseUrl(QUrl::fromPercentEncoding("/?" + copy.replace('+', ' ')));
}
void RequestParameters::parseMultiPart(const MultiPart & multiPart)
{
for (const Part & part : multiPart.getParts())
{
HttpHeader contentDisposition = part.getHeader(http::ContentDisposition);
HttpHeaderElement element = contentDisposition.getElement();
if (element.getName()=="form-data")
{
QString name = element.getParameter("name");
if (part.hasHeader(http::ContentType))
{
UploadedFile uploadedFile;
uploadedFile.setContent(part.getContent());
if (element.isSet("filename"))
{
uploadedFile.setFilename(element.getParameter("filename"));
}
m_files[name] = uploadedFile;
}
else
{
m_params[name] = QString(part.getContent());
}
}
}
}
QString RequestParameters::get(const QString & key) const
{
return m_params.value(key, "");
}
bool RequestParameters::contains(const QString & key) const
{
return m_params.contains(key);
}
UploadedFile RequestParameters::getFile(const QString & key) const
{
return m_files.value(key);
}
bool RequestParameters::containsFile(const QString & key) const
{
return m_files.contains(key);
}
const QHash<QString, QString> & RequestParameters::parameters() const
{
return m_params;
}
const QHash<QString, UploadedFile> & RequestParameters::files() const
{
return m_files;
}
} // namespace tastefulserver
| 22.152174 | 86 | 0.652601 | scheibel |
f83a446bf119d3ee6a041ed081f7782cf4363abc | 674 | cpp | C++ | quicksort.cpp | ilimugur/Hacktoberfest-2020 | 62f33773c36f3f820b79d1129af6f344af20c63f | [
"Apache-2.0"
] | null | null | null | quicksort.cpp | ilimugur/Hacktoberfest-2020 | 62f33773c36f3f820b79d1129af6f344af20c63f | [
"Apache-2.0"
] | 5 | 2020-10-01T08:55:52.000Z | 2020-10-07T12:30:24.000Z | quicksort.cpp | ilimugur/Hacktoberfest-2020 | 62f33773c36f3f820b79d1129af6f344af20c63f | [
"Apache-2.0"
] | 4 | 2020-10-01T08:55:59.000Z | 2020-10-19T09:49:54.000Z | #include <iostream>
#include<bits/stdc++.h>
using namespace std;
int partition(int *a, int s, int e){
int pivot = a[e];
int i=s-1;
for(int j=s; j<=e-1; j++){
if(a[j] <= pivot){
i++;
swap(a[i], a[j]);
}
}
swap(a[++i], a[e]);
return i;
}
void quickSort(int *a, int s, int e){
if(s>=e)
return;
int index = partition(a, s, e);
quickSort(a, s, index-1);
quickSort(a, index+1, e);
}
int main(){
int n;
cin>>n;
int a[n];
for(int i=0; i<n; i++)
cin>>a[i];
quickSort(a, 0, n-1);
for(int i=0; i<n; i++)
cout<<a[i]<<" ";
return 0;
}
| 16.047619 | 37 | 0.437685 | ilimugur |
f841879466c87f7c928caebeb21e9a3c323abd15 | 801 | cpp | C++ | src/ui/element/PushButtonWithMenu.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/ui/element/PushButtonWithMenu.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | src/ui/element/PushButtonWithMenu.cpp | vitorjna/LoggerClient | b447f36224e98919045138bb08a849df211e5491 | [
"MIT"
] | null | null | null | #include "PushButtonWithMenu.h"
PushButtonWithMenu::PushButtonWithMenu(QWidget *parent)
: QToolButton(parent)
{
setPopupMode(QToolButton::MenuButtonPopup);
setAutoRaise(true);
// setToolButtonStyle(Qt::ToolButtonTextOnly);
connect(this, SIGNAL(triggered(QAction *)),
this, SLOT(setDefaultAction(QAction *)));
}
PushButtonWithMenu::~PushButtonWithMenu()
{
}
void PushButtonWithMenu::addAction(QAction *myAction)
{
if (myAction == nullptr) {
return;
}
QToolButton::addAction(myAction);
if (this->actions().size() == 1) {
this->setDefaultAction(myAction);
}
}
void PushButtonWithMenu::addActions(const QList<QAction *> *myActionList)
{
for (QAction *myAction : *myActionList) {
this->addAction(myAction);
}
}
| 21.078947 | 73 | 0.672909 | vitorjna |
f84b9e53403b6400d8768fc9dac185ca35af7198 | 2,187 | cc | C++ | tools/embedding_plugin/cc/kernels/v2/embedding_wrapper_forward_helper.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | 1 | 2021-06-04T04:03:54.000Z | 2021-06-04T04:03:54.000Z | tools/embedding_plugin/cc/kernels/v2/embedding_wrapper_forward_helper.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | null | null | null | tools/embedding_plugin/cc/kernels/v2/embedding_wrapper_forward_helper.cc | quinnrong94/HugeCTR | 1068dc48b05a1219b393144dd3b61a1749f232df | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020, NVIDIA CORPORATION.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "embedding_wrapper.h"
#include "HugeCTR/include/embeddings/distributed_slot_sparse_embedding_hash.hpp"
#include "HugeCTR/include/embeddings/localized_slot_sparse_embedding_hash.hpp"
#include "HugeCTR/include/embeddings/localized_slot_sparse_embedding_one_hot.hpp"
namespace HugeCTR {
namespace Version2 {
template <typename TypeKey, typename TypeFP>
void EmbeddingWrapper<TypeKey, TypeFP>::forward_helper(
const std::string& embedding_name, const bool is_training) {
/*get embedding*/
std::shared_ptr<IEmbedding> embedding = get_item_from_map(embeddings_, embedding_name);
if (!embedding) {
const std::string error_info(std::string(__FILE__) + ":" + std::to_string(__LINE__) + " "
+ "Cannot find embedding instance whose name is " + embedding_name);
throw std::invalid_argument(error_info);
}
/*do forward propagation*/
try {
embedding->forward(is_training);
} catch (const std::exception& error) {
throw error;
}
}
template void EmbeddingWrapper<long long, float>::forward_helper(
const std::string& embedding_name, const bool is_training);
template void EmbeddingWrapper<long long, __half>::forward_helper(
const std::string& embedding_name, const bool is_training);
template void EmbeddingWrapper<unsigned int, float>::forward_helper(
const std::string& embedding_name, const bool is_training);
template void EmbeddingWrapper<unsigned int, __half>::forward_helper(
const std::string& embedding_name, const bool is_training);
} // namespace Version2
} // namespace HugeCTR | 39.763636 | 97 | 0.748057 | quinnrong94 |
f85059edaab4f4d640be587f162c0ffb99c8d8aa | 1,912 | cpp | C++ | romTest.cpp | ckronber/CPlusPlusCode | 889e9301031217b37641d94e7ea52200e06e5862 | [
"Unlicense"
] | null | null | null | romTest.cpp | ckronber/CPlusPlusCode | 889e9301031217b37641d94e7ea52200e06e5862 | [
"Unlicense"
] | null | null | null | romTest.cpp | ckronber/CPlusPlusCode | 889e9301031217b37641d94e7ea52200e06e5862 | [
"Unlicense"
] | null | null | null | #include <iostream>
#include <vector>
#include <cmath>
#include <string>
using namespace std;
void numberVal(int num, int * place);
int main()
{
int nums[7] = {1,5,10,50,100,500,1000};
char rom[7] = {'I','V','X','L','C','D','M'};
int place[4];
vector <char> romChars;
int num = 1987,j,hold;
char temp;
numberVal(num,place);
for(int i=3;i>=0;i--) // run for how many places are included in the number
{ // it should not be more than 4 numbers
j = 0;
if(i == 3 && (place[i] > 0)) // calculates the number of thousands in the number
while(place[i] > 0)
{
romChars.push_back(rom[6]);
place[i]--;
}
//hundreds and below will be calculated and added to the roman numeral number here
else
{
while((place[i] * pow(10,i)) < nums[j])
j++;
if(place[i] == 9 || place[i] == 4)
{
if(place[i] == 9)
hold = -1;
else
hold = 0;
romChars.push_back(rom[j-hold]);
romChars.push_back(rom[j+1]);
}
else
{
if(nums[j] == place[i]*pow(10,i))
hold = j;
else if(nums[j] > place[i]*pow(10,i))
hold = j-1;
romChars.push_back(rom[hold]);
}
}
}
int i = 0;
while(i < romChars.size())
{
cout <<romChars[i];
i++;
}
cout <<endl <<endl;
return 0;
}
void numberVal(int num, int * place)
{
for(int i=3;i>=0;i--)
{
place[i] = num/pow(10,i);
num -= (place[i]*pow(10,i));
}
} | 24.202532 | 97 | 0.402197 | ckronber |
f8571d4b20608dbc7875cd2b65d4558f0550bfba | 12,437 | cc | C++ | node_modules/gl/angle/src/tests/third_party/gpu_test_expectations/gpu_test_config.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 27 | 2016-04-27T01:02:03.000Z | 2021-12-13T08:53:19.000Z | node_modules/gl/angle/src/tests/third_party/gpu_test_expectations/gpu_test_config.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 2 | 2020-03-14T04:03:53.000Z | 2021-09-02T04:26:49.000Z | node_modules/gl/angle/src/tests/third_party/gpu_test_expectations/gpu_test_config.cc | aaverty/editly | 71bccaf91f8d68609c80ba59425b79e3f94579ad | [
"MIT"
] | 17 | 2016-04-27T02:06:39.000Z | 2019-12-18T08:07:00.000Z | // Copyright (c) 2012 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 "gpu_test_config.h"
#include "gpu_info.h"
#include "gpu_test_expectations_parser.h"
#if defined(OS_LINUX)
extern "C" {
# include <pci/pci.h>
}
#endif
#if defined(OS_MACOSX)
#include "gpu_test_config_mac.h"
#endif
using namespace gpu;
#if defined(OS_WIN)
namespace base {
namespace {
// Disable the deprecated function warning for GetVersionEx
#pragma warning(disable: 4996)
class SysInfo
{
public:
static void OperatingSystemVersionNumbers(
int32 *major_version, int32 *minor_version, int32 *bugfix_version);
};
// static
void SysInfo::OperatingSystemVersionNumbers(
int32 *major_version, int32 *minor_version, int32 *bugfix_version)
{
OSVERSIONINFOEX version_info = { sizeof version_info };
::GetVersionEx(reinterpret_cast<OSVERSIONINFO*>(&version_info));
*major_version = version_info.dwMajorVersion;
*minor_version = version_info.dwMinorVersion;
*bugfix_version = version_info.dwBuildNumber;
}
} // anonymous namespace
} // namespace base
void DeviceIDToVendorAndDevice(const std::string& id,
uint32* vendor_id,
uint32* device_id) {
*vendor_id = 0;
*device_id = 0;
if (id.length() < 21)
return;
std::string vendor_id_string = id.substr(8, 4);
std::string device_id_string = id.substr(17, 4);
base::HexStringToUInt(vendor_id_string, vendor_id);
base::HexStringToUInt(device_id_string, device_id);
}
CollectInfoResult CollectGpuID(uint32* vendor_id, uint32* device_id) {
DCHECK(vendor_id && device_id);
*vendor_id = 0;
*device_id = 0;
// Taken from http://developer.nvidia.com/object/device_ids.html
DISPLAY_DEVICEA dd;
dd.cb = sizeof(DISPLAY_DEVICEA);
std::string id;
for (int i = 0; EnumDisplayDevicesA(NULL, i, &dd, 0); ++i) {
if (dd.StateFlags & DISPLAY_DEVICE_PRIMARY_DEVICE) {
id = dd.DeviceID;
break;
}
}
if (id.length() > 20) {
DeviceIDToVendorAndDevice(id, vendor_id, device_id);
if (*vendor_id != 0 && *device_id != 0)
return kCollectInfoSuccess;
}
return kCollectInfoNonFatalFailure;
}
#endif // defined(OS_WIN)
#if defined(OS_LINUX)
const uint32 kVendorIDIntel = 0x8086;
const uint32 kVendorIDNVidia = 0x10de;
const uint32 kVendorIDAMD = 0x1002;
CollectInfoResult CollectPCIVideoCardInfo(GPUInfo* gpu_info) {
DCHECK(gpu_info);
struct pci_access* access = pci_alloc();
DCHECK(access != NULL);
pci_init(access);
pci_scan_bus(access);
bool primary_gpu_identified = false;
for (pci_dev* device = access->devices;
device != NULL; device = device->next) {
pci_fill_info(device, 33);
bool is_gpu = false;
switch (device->device_class) {
case PCI_CLASS_DISPLAY_VGA:
case PCI_CLASS_DISPLAY_XGA:
case PCI_CLASS_DISPLAY_3D:
is_gpu = true;
break;
case PCI_CLASS_DISPLAY_OTHER:
default:
break;
}
if (!is_gpu)
continue;
if (device->vendor_id == 0 || device->device_id == 0)
continue;
GPUInfo::GPUDevice gpu;
gpu.vendor_id = device->vendor_id;
gpu.device_id = device->device_id;
if (!primary_gpu_identified) {
primary_gpu_identified = true;
gpu_info->gpu = gpu;
} else {
// TODO(zmo): if there are multiple GPUs, we assume the non Intel
// one is primary. Revisit this logic because we actually don't know
// which GPU we are using at this point.
if (gpu_info->gpu.vendor_id == kVendorIDIntel &&
gpu.vendor_id != kVendorIDIntel) {
gpu_info->secondary_gpus.push_back(gpu_info->gpu);
gpu_info->gpu = gpu;
} else {
gpu_info->secondary_gpus.push_back(gpu);
}
}
}
// Detect Optimus or AMD Switchable GPU.
if (gpu_info->secondary_gpus.size() == 1 &&
gpu_info->secondary_gpus[0].vendor_id == kVendorIDIntel) {
if (gpu_info->gpu.vendor_id == kVendorIDNVidia)
gpu_info->optimus = true;
if (gpu_info->gpu.vendor_id == kVendorIDAMD)
gpu_info->amd_switchable = true;
}
pci_cleanup(access);
if (!primary_gpu_identified)
return kCollectInfoNonFatalFailure;
return kCollectInfoSuccess;
}
CollectInfoResult CollectGpuID(uint32* vendor_id, uint32* device_id) {
DCHECK(vendor_id && device_id);
*vendor_id = 0;
*device_id = 0;
GPUInfo gpu_info;
CollectInfoResult result = CollectPCIVideoCardInfo(&gpu_info);
if (result == kCollectInfoSuccess) {
*vendor_id = gpu_info.gpu.vendor_id;
*device_id = gpu_info.gpu.device_id;
}
return result;
}
#endif // defined(OS_LINUX)
#if defined(OS_MACOSX)
CollectInfoResult CollectGpuID(uint32* vendor_id, uint32* device_id) {
DCHECK(vendor_id && device_id);
GPUInfo::GPUDevice gpu = GetActiveGPU();
*vendor_id = gpu.vendor_id;
*device_id = gpu.device_id;
if (*vendor_id != 0 && *device_id != 0)
return kCollectInfoSuccess;
return kCollectInfoNonFatalFailure;
}
#endif
namespace gpu {
namespace {
GPUTestConfig::OS GetCurrentOS() {
#if defined(OS_CHROMEOS)
return GPUTestConfig::kOsChromeOS;
#elif defined(OS_LINUX) || defined(OS_OPENBSD)
return GPUTestConfig::kOsLinux;
#elif defined(OS_WIN)
int32 major_version = 0;
int32 minor_version = 0;
int32 bugfix_version = 0;
base::SysInfo::OperatingSystemVersionNumbers(
&major_version, &minor_version, &bugfix_version);
if (major_version == 5)
return GPUTestConfig::kOsWinXP;
if (major_version == 6 && minor_version == 0)
return GPUTestConfig::kOsWinVista;
if (major_version == 6 && minor_version == 1)
return GPUTestConfig::kOsWin7;
if (major_version == 6 && (minor_version == 2 || minor_version == 3))
return GPUTestConfig::kOsWin8;
if (major_version == 10)
return GPUTestConfig::kOsWin10;
#elif defined(OS_MACOSX)
int32 major_version = 0;
int32 minor_version = 0;
int32 bugfix_version = 0;
base::SysInfo::OperatingSystemVersionNumbers(
&major_version, &minor_version, &bugfix_version);
if (major_version == 10) {
switch (minor_version) {
case 5:
return GPUTestConfig::kOsMacLeopard;
case 6:
return GPUTestConfig::kOsMacSnowLeopard;
case 7:
return GPUTestConfig::kOsMacLion;
case 8:
return GPUTestConfig::kOsMacMountainLion;
case 9:
return GPUTestConfig::kOsMacMavericks;
case 10:
return GPUTestConfig::kOsMacYosemite;
case 11:
return GPUTestConfig::kOsMacElCapitan;
}
}
#elif defined(OS_ANDROID)
return GPUTestConfig::kOsAndroid;
#endif
return GPUTestConfig::kOsUnknown;
}
} // namespace anonymous
GPUTestConfig::GPUTestConfig()
: validate_gpu_info_(true),
os_(kOsUnknown),
gpu_device_id_(0),
build_type_(kBuildTypeUnknown),
api_(kAPIUnknown) {}
GPUTestConfig::~GPUTestConfig() {
}
void GPUTestConfig::set_os(int32 os) {
DCHECK_EQ(0, os & ~(kOsAndroid | kOsWin | kOsMac | kOsLinux | kOsChromeOS));
os_ = os;
}
void GPUTestConfig::AddGPUVendor(uint32 gpu_vendor) {
DCHECK_NE(0u, gpu_vendor);
for (size_t i = 0; i < gpu_vendor_.size(); ++i)
DCHECK_NE(gpu_vendor_[i], gpu_vendor);
gpu_vendor_.push_back(gpu_vendor);
}
void GPUTestConfig::set_gpu_device_id(uint32 id) {
gpu_device_id_ = id;
}
void GPUTestConfig::set_build_type(int32 build_type) {
DCHECK_EQ(0, build_type & ~(kBuildTypeRelease | kBuildTypeDebug));
build_type_ = build_type;
}
void GPUTestConfig::set_api(int32 api) {
DCHECK_EQ(0, api & ~(kAPID3D9 | kAPID3D11 | kAPIGLDesktop | kAPIGLES));
api_ = api;
}
bool GPUTestConfig::IsValid() const {
if (!validate_gpu_info_)
return true;
if (gpu_device_id_ != 0 && (gpu_vendor_.size() != 1 || gpu_vendor_[0] == 0))
return false;
return true;
}
bool GPUTestConfig::OverlapsWith(const GPUTestConfig& config) const {
DCHECK(IsValid());
DCHECK(config.IsValid());
if (config.os_ != kOsUnknown && os_ != kOsUnknown &&
(os_ & config.os_) == 0)
return false;
if (config.gpu_vendor_.size() > 0 && gpu_vendor_.size() > 0) {
bool shared = false;
for (size_t i = 0; i < config.gpu_vendor_.size() && !shared; ++i) {
for (size_t j = 0; j < gpu_vendor_.size(); ++j) {
if (config.gpu_vendor_[i] == gpu_vendor_[j]) {
shared = true;
break;
}
}
}
if (!shared)
return false;
}
if (config.gpu_device_id_ != 0 && gpu_device_id_ != 0 &&
gpu_device_id_ != config.gpu_device_id_)
return false;
if (config.build_type_ != kBuildTypeUnknown &&
build_type_ != kBuildTypeUnknown &&
(build_type_ & config.build_type_) == 0)
return false;
return true;
}
void GPUTestConfig::DisableGPUInfoValidation() {
validate_gpu_info_ = false;
}
void GPUTestConfig::ClearGPUVendor() {
gpu_vendor_.clear();
}
GPUTestBotConfig::~GPUTestBotConfig() {
}
void GPUTestBotConfig::AddGPUVendor(uint32 gpu_vendor) {
DCHECK_EQ(0u, GPUTestConfig::gpu_vendor().size());
GPUTestConfig::AddGPUVendor(gpu_vendor);
}
bool GPUTestBotConfig::SetGPUInfo(const GPUInfo& gpu_info) {
DCHECK(validate_gpu_info_);
if (gpu_info.gpu.device_id == 0 || gpu_info.gpu.vendor_id == 0)
return false;
ClearGPUVendor();
AddGPUVendor(gpu_info.gpu.vendor_id);
set_gpu_device_id(gpu_info.gpu.device_id);
return true;
}
bool GPUTestBotConfig::IsValid() const {
switch (os()) {
case kOsWinXP:
case kOsWinVista:
case kOsWin7:
case kOsWin8:
case kOsWin10:
case kOsMacLeopard:
case kOsMacSnowLeopard:
case kOsMacLion:
case kOsMacMountainLion:
case kOsMacMavericks:
case kOsMacYosemite:
case kOsMacElCapitan:
case kOsLinux:
case kOsChromeOS:
case kOsAndroid:
break;
default:
return false;
}
if (validate_gpu_info_) {
if (gpu_vendor().size() != 1 || gpu_vendor()[0] == 0)
return false;
if (gpu_device_id() == 0)
return false;
}
switch (build_type()) {
case kBuildTypeRelease:
case kBuildTypeDebug:
break;
default:
return false;
}
return true;
}
bool GPUTestBotConfig::Matches(const GPUTestConfig& config) const {
DCHECK(IsValid());
DCHECK(config.IsValid());
if (config.os() != kOsUnknown && (os() & config.os()) == 0)
return false;
if (config.gpu_vendor().size() > 0) {
bool contained = false;
for (size_t i = 0; i < config.gpu_vendor().size(); ++i) {
if (config.gpu_vendor()[i] == gpu_vendor()[0]) {
contained = true;
break;
}
}
if (!contained)
return false;
}
if (config.gpu_device_id() != 0 &&
gpu_device_id() != config.gpu_device_id())
return false;
if (config.build_type() != kBuildTypeUnknown &&
(build_type() & config.build_type()) == 0)
return false;
if (config.api() != 0 && (api() & config.api()) == 0)
return false;
return true;
}
bool GPUTestBotConfig::Matches(const std::string& config_data) const {
GPUTestExpectationsParser parser;
GPUTestConfig config;
if (!parser.ParseConfig(config_data, &config))
return false;
return Matches(config);
}
bool GPUTestBotConfig::LoadCurrentConfig(const GPUInfo* gpu_info) {
bool rt;
if (gpu_info == NULL) {
GPUInfo my_gpu_info;
CollectInfoResult result = CollectGpuID(
&my_gpu_info.gpu.vendor_id, &my_gpu_info.gpu.device_id);
if (result != kCollectInfoSuccess) {
LOG(ERROR) << "Fail to identify GPU";
DisableGPUInfoValidation();
rt = true;
} else {
rt = SetGPUInfo(my_gpu_info);
}
} else {
rt = SetGPUInfo(*gpu_info);
}
set_os(GetCurrentOS());
if (os() == kOsUnknown) {
LOG(ERROR) << "Unknown OS";
rt = false;
}
#if defined(NDEBUG)
set_build_type(kBuildTypeRelease);
#else
set_build_type(kBuildTypeDebug);
#endif
return rt;
}
// static
bool GPUTestBotConfig::CurrentConfigMatches(const std::string& config_data) {
GPUTestBotConfig my_config;
if (!my_config.LoadCurrentConfig(NULL))
return false;
return my_config.Matches(config_data);
}
// static
bool GPUTestBotConfig::CurrentConfigMatches(
const std::vector<std::string>& configs) {
GPUTestBotConfig my_config;
if (!my_config.LoadCurrentConfig(NULL))
return false;
for (size_t i = 0 ; i < configs.size(); ++i) {
if (my_config.Matches(configs[i]))
return true;
}
return false;
}
} // namespace gpu
| 26.183158 | 78 | 0.676369 | aaverty |
f85777d94c08d1b534962c5f819942a6dff1202a | 18,527 | cpp | C++ | src/spf.cpp | ajbc/spf | a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5 | [
"MIT"
] | 28 | 2015-05-08T23:07:07.000Z | 2021-09-08T19:56:49.000Z | src/spf.cpp | ajbc/spf | a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5 | [
"MIT"
] | 2 | 2016-11-29T10:43:06.000Z | 2017-02-09T11:39:46.000Z | src/spf.cpp | ajbc/spf | a2f9712a852d67dbf0659c8e5fe7bd5a46df1ac5 | [
"MIT"
] | 10 | 2015-08-13T00:22:21.000Z | 2021-04-06T20:17:32.000Z | #include "spf.h"
SPF::SPF(model_settings* model_set, Data* dataset) {
settings = model_set;
data = dataset;
// user influence
printf("\tinitializing user influence (tau)\n");
tau = sp_fmat(data->user_count(), data->user_count());
logtau = sp_fmat(data->user_count(), data->user_count());
a_tau = sp_fmat(data->user_count(), data->user_count());
b_tau = sp_fmat(data->user_count(), data->user_count());
// user preferences
printf("\tinitializing user preferences (theta)\n");
theta = fmat(settings->k, data->user_count());
logtheta = fmat(settings->k, data->user_count());
a_theta = fmat(settings->k, data->user_count());
b_theta = fmat(settings->k, data->user_count());
// item attributes
printf("\tinitializing item attributes (beta)\n");
printf("\t%d users and %d items\n", data->user_count(), data->item_count());
beta = fmat(settings->k, data->item_count());
logbeta = fmat(settings->k, data->item_count());
a_beta = fmat(settings->k, data->item_count());
a_beta_user = fmat(settings->k, data->item_count());
b_beta = fmat(settings->k, data->item_count());
delta = fvec(data->item_count());
a_delta = fvec(data->item_count());
b_delta = settings->b_delta + data->user_count();
a_delta_user = fvec(data->item_count());
// keep track of old a_beta and a_delta for SVI
a_beta_old = fmat(settings->k, data->item_count());
a_beta_old.fill(settings->a_beta);
a_delta_old = fvec(data->item_count());
a_delta_old.fill(settings->a_delta);
printf("\tsetting random seed\n");
rand_gen = gsl_rng_alloc(gsl_rng_taus);
gsl_rng_set(rand_gen, (long) settings->seed); // init the seed
initialize_parameters();
scale = settings->svi ? float(data->user_count()) / float(settings->sample_size) : 1;
}
void SPF::learn() {
double old_likelihood, delta_likelihood, likelihood = -1e10;
int likelihood_decreasing_count = 0;
time_t start_time, end_time;
int iteration = 0;
char iter_as_str[4];
bool converged = false;
bool on_final_pass = false;
while (!converged) {
time(&start_time);
iteration++;
printf("iteration %d\n", iteration);
reset_helper_params();
// update rate for user preferences
b_theta.each_col() += sum(beta, 1);
set<int> items;
int user = -1, item, rating;
for (int i = 0; i < settings->sample_size; i++) {
if (on_final_pass && settings->final_pass_test) {
user++;
while (data->test_users.count(user)==0) {
user++;
}
} else if (settings->svi) {
user = gsl_rng_uniform_int(rand_gen, data->user_count());
} else {
user = i;
}
bool user_converged = false;
int user_iters = 0;
while (!user_converged) {
user_iters++;
a_beta_user.zeros();
a_delta_user.zeros();
// look at all the user's items
for (int j = 0; j < data->item_count(user); j++) {
item = data->get_item(user, j);
items.insert(item);
rating = 1;
//TODO: rating = data->get_train_rating(i);
update_shape(user, item, rating);
}
// update per-user parameters
double user_change = 0;
if (!settings->factor_only && !settings->fix_influence)
user_change += update_tau(user);
if (!settings->social_only)
user_change += update_theta(user);
if (!settings->social_only && !settings->factor_only && !settings->fix_influence) {
user_change /= 2;
// if the updates are less than 1% change or over 10 local iterations,
// declare the local params to be converged
if (user_change < 0.01 || user_iters > 10)
user_converged = true;
} else {
// if we're only looking at social or factor (not combined)
// then the user parameters will always have converged with
// a single pass (since there's nothing to balance against)
user_converged = true;
}
}
if (settings->verbose)
printf("%d\tuser %d took %d iters to converge\n", iteration, user, user_iters);
a_beta += a_beta_user;
a_delta += a_delta_user;
}
if (!settings->social_only) {
// update rate for item attributes
b_beta.each_col() += sum(theta, 1);
// update per-item parameters
set<int>::iterator it;
for (it = items.begin(); it != items.end(); it++) {
item = *it;
if (iter_count[item] == 0)
iter_count[item] = 0;
iter_count[item]++;
update_beta(item);
if (settings->item_bias)
update_delta(item);
}
} else if (settings->item_bias) {
set<int>::iterator it;
for (it = items.begin(); it != items.end(); it++) {
item = *it;
if (iter_count[item] == 0)
iter_count[item] = 0;
iter_count[item]++;
if (settings->item_bias)
update_delta(item);
}
}
// check for convergence
if (on_final_pass) {
printf("Final pass complete\n");
converged = true;
old_likelihood = likelihood;
likelihood = get_ave_log_likelihood();
delta_likelihood = abs((old_likelihood - likelihood) /
old_likelihood);
log_convergence(iteration, likelihood, delta_likelihood);
} else if (iteration >= settings->max_iter) {
printf("Reached maximum number of iterations.\n");
converged = true;
old_likelihood = likelihood;
likelihood = get_ave_log_likelihood();
delta_likelihood = abs((old_likelihood - likelihood) /
old_likelihood);
log_convergence(iteration, likelihood, delta_likelihood);
} else if (iteration % settings->conv_freq == 0) {
old_likelihood = likelihood;
likelihood = get_ave_log_likelihood();
if (likelihood < old_likelihood)
likelihood_decreasing_count += 1;
else
likelihood_decreasing_count = 0;
delta_likelihood = abs((old_likelihood - likelihood) /
old_likelihood);
log_convergence(iteration, likelihood, delta_likelihood);
if (settings->verbose) {
printf("delta: %f\n", delta_likelihood);
printf("old: %f\n", old_likelihood);
printf("new: %f\n", likelihood);
}
if (iteration >= settings->min_iter &&
delta_likelihood < settings->likelihood_delta) {
printf("Model converged.\n");
converged = true;
} else if (iteration >= settings->min_iter &&
likelihood_decreasing_count >= 2) {
printf("Likelihood decreasing.\n");
converged = true;
}
}
// save intermediate results
if (!converged && settings->save_freq > 0 &&
iteration % settings->save_freq == 0) {
printf(" saving\n");
sprintf(iter_as_str, "%04d", iteration);
save_parameters(iter_as_str);
}
// intermediate evaluation
if (!converged && settings->eval_freq > 0 &&
iteration % settings->eval_freq == 0) {
sprintf(iter_as_str, "%04d", iteration);
evaluate(iter_as_str);
}
time(&end_time);
log_time(iteration, difftime(end_time, start_time));
if (converged && !on_final_pass &&
(settings->final_pass || settings->final_pass_test)) {
printf("final pass on all users.\n");
on_final_pass = true;
converged = false;
// we need to modify some settings for the final pass
// things should look exactly like batch for all users
if (settings->final_pass) {
settings->set_stochastic_inference(false);
settings->set_sample_size(data->user_count());
scale = 1;
} else {
settings->set_sample_size(data->test_users.size());
scale = data->user_count() / settings->sample_size;
}
}
}
save_parameters("final");
}
double SPF::predict(int user, int item) {
double prediction = settings->social_only ? 1e-10 : 0;
prediction += accu(tau.col(user) % data->ratings.col(item));
if (!settings->social_only) {
prediction += accu(theta.col(user) % beta.col(item));
}
if (settings->item_bias) {
prediction += delta(item);
}
return prediction;
}
// helper function to sort predictions properly
bool prediction_compare(const pair<pair<double,int>, int>& itemA,
const pair<pair<double, int>, int>& itemB) {
// if the two values are equal, sort by popularity!
if (itemA.first.first == itemB.first.first) {
if (itemA.first.second == itemB.first.second)
return itemA.second < itemB.second;
return itemA.first.second > itemB.first.second;
}
return itemA.first.first > itemB.first.first;
}
void SPF::evaluate() {
evaluate("final", true);
}
void SPF::evaluate(string label) {
evaluate(label, false);
}
void SPF::evaluate(string label, bool write_rankings) {
time_t start_time, end_time;
time(&start_time);
eval(this, &Model::predict, settings->outdir, data, false, settings->seed,
settings->verbose, label, write_rankings, false);
time(&end_time);
log_time(-1, difftime(end_time, start_time));
}
/* PRIVATE */
void SPF::initialize_parameters() {
int user, neighbor, n, item, i, k;
if (!settings->factor_only) {
for (user = 0; user < data->user_count(); user++) {
// user influence
for (n = 0; n < data->neighbor_count(user); n++) {
neighbor = data->get_neighbor(user, n);
tau(neighbor, user) = 1.0;
logtau(neighbor, user) = log(1.0 + 1e-5);
double all = settings->b_tau;
for (i = 0; i < data->item_count(neighbor); i++) {
item = data->get_item(neighbor, i);
all += data->ratings(neighbor, item);
} //TODO: this doeesn't need to be done as much... only one time per user (U), not UxU times
b_tau(neighbor, user) = all;
}
}
}
if (!settings->social_only) {
// user preferences
for (user = 0; user < data->user_count(); user++) {
for (k = 0; k < settings->k; k++) {
theta(k, user) = (settings->a_theta +
gsl_rng_uniform_pos(rand_gen))
/ (settings->b_theta);
logtheta(k, user) = log(theta(k, user));
}
theta.col(user) /= accu(theta.col(user));
}
// item attributes
for (item = 0; item < data->item_count(); item++) {
for (k = 0; k < settings->k; k++) {
beta(k, item) = (settings->a_beta +
gsl_rng_uniform_pos(rand_gen))
/ (settings->b_beta);
logbeta(k, item) = log(beta(k, item));
}
beta.col(item) /= accu(beta.col(item));
}
}
if (settings->item_bias) {
for (item = 0; item < data->item_count(); item++) {
delta(item) = data->popularity(item);
}
}
}
void SPF::reset_helper_params() {
a_tau = data->network_spmat * settings->a_tau;
a_theta.fill(settings->a_theta);
b_theta.fill(settings->b_theta);
a_beta.fill(settings->a_beta);
b_beta.fill(settings->b_beta);
a_delta.fill(settings->a_delta);
}
void SPF::save_parameters(string label) {
FILE* file;
if (!settings->factor_only & !settings->fix_influence) {
// save tau
file = fopen((settings->outdir+"/tau-"+label+".dat").c_str(), "w");
fprintf(file, "uid\torig.uid\tvid\torig.vid\ttau\n");
int user, neighbor, n;
double tau_uv;
for (user = 0; user < data->user_count(); user++) {
for (n = 0; n < data->neighbor_count(user); n++) {
neighbor = data->get_neighbor(user, n);
tau_uv = tau(neighbor, user);
fprintf(file, "%d\t%d\t%d\t%d\t%e\n", user, data->user_id(user),
neighbor, data->user_id(neighbor), tau_uv);
}
}
fclose(file);
}
if (!settings->social_only) {
int k;
// write out theta
file = fopen((settings->outdir+"/theta-"+label+".dat").c_str(), "w");
for (int user = 0; user < data->user_count(); user++) {
fprintf(file, "%d\t%d", user, data->user_id(user));
for (k = 0; k < settings->k; k++)
fprintf(file, "\t%e", theta(k, user));
fprintf(file, "\n");
}
fclose(file);
// write out beta
file = fopen((settings->outdir+"/beta-"+label+".dat").c_str(), "w");
for (int item = 0; item < data->item_count(); item++) {
fprintf(file, "%d\t%d", item, data->item_id(item));
for (k = 0; k < settings->k; k++)
fprintf(file, "\t%e", beta(k, item));
fprintf(file, "\n");
}
fclose(file);
}
if (settings->item_bias) {
// write out bias delta
file = fopen((settings->outdir+"/delta-"+label+".dat").c_str(), "w");
for (int item = 0; item < data->item_count(); item++) {
fprintf(file, "%d\t%d\t%e", item, data->item_id(item), delta(item));
}
fclose(file);
}
}
void SPF::update_shape(int user, int item, int rating) {
sp_fmat phi_SF = logtau.col(user) % data->ratings.col(item);
double phi_sum = accu(phi_SF);
fmat phi_MF;
float phi_B = 0;
// we don't need to do a similar check for factor only because
// sparse matrices play nice when empty
if (!settings->social_only) {
phi_MF = exp(logtheta.col(user) + logbeta.col(item));
phi_sum += accu(phi_MF);
}
if (settings->item_bias) {
phi_B = delta(item);
phi_sum += phi_B;
}
if (phi_sum == 0)
return;
if (!settings->factor_only & !settings->fix_influence) {
phi_SF /= phi_sum * rating;
int neighbor;
for (int n = 0; n < data->neighbor_count(user); n++) {
neighbor = data->get_neighbor(user, n);
a_tau(neighbor, user) += phi_SF(neighbor, 0);
}
}
if (!settings->social_only) {
phi_MF /= phi_sum * rating;
a_theta.col(user) += phi_MF;
a_beta_user.col(item) += phi_MF * scale;
}
if (settings->item_bias) {
a_delta(item) += (phi_B / (phi_sum * rating)) * scale;
}
}
double SPF::update_tau(int user) {
int neighbor, n;
double old, change, total;
change = 0;
total = 0;
for (n = 0; n < data->neighbor_count(user); n++) {
neighbor = data->get_neighbor(user, n);
old = tau(neighbor, user);
total += tau(neighbor, user);
tau(neighbor, user) = a_tau(neighbor, user) / b_tau(neighbor, user);
// fake log!
logtau(neighbor, user) = exp(gsl_sf_psi(a_tau(neighbor, user)) - log(b_tau(neighbor, user)));
change += abs(old - tau(neighbor, user));
}
return total==0 ? 0 : change / total;
}
double SPF::update_theta(int user) {
double change = accu(abs(theta(user) - (a_theta(user) / b_theta(user))));
double total = accu(theta(user));
for (int k = 0; k < settings->k; k++) {
theta(k, user) = a_theta(k, user) / b_theta(k, user);
logtheta(k, user) = gsl_sf_psi(a_theta(k, user));
}
logtheta(user) = logtheta(user) - log(b_theta(user));
return change / total;
}
void SPF::update_beta(int item) {
if (settings->svi) {
double rho = pow(iter_count[item] + settings->delay,
-1 * settings->forget);
a_beta(item) = (1 - rho) * a_beta_old(item) + rho * a_beta(item);
a_beta_old(item) = a_beta(item);
}
for (int k = 0; k < settings->k; k++) {
beta(k, item) = a_beta(k, item) / b_beta(k, item);
logbeta(k, item) = gsl_sf_psi(a_beta(k, item));
}
logbeta(item) = logbeta(item) - log(b_beta(item));
}
void SPF::update_delta(int item) {
if (settings->svi) {
double rho = pow(iter_count[item] + settings->delay,
-1 * settings->forget);
a_delta(item) = (1 - rho) * a_delta_old(item) + rho * a_delta(item);
a_delta_old(item) = a_delta(item);
}
delta(item) = a_delta(item) / b_delta;
}
double SPF::get_ave_log_likelihood() {
double prediction, likelihood = 0;
int user, item, rating;
for (int i = 0; i < data->num_validation(); i++) {
user = data->get_validation_user(i);
item = data->get_validation_item(i);
rating = data->get_validation_rating(i);
prediction = predict(user, item);
likelihood +=
log(prediction) * rating - log(factorial(rating)) - prediction;
}
return likelihood / data->num_validation();
}
void SPF::log_convergence(int iteration, double ave_ll, double delta_ll) {
FILE* file = fopen((settings->outdir+"/log_likelihood.dat").c_str(), "a");
fprintf(file, "%d\t%f\t%f\n", iteration, ave_ll, delta_ll);
fclose(file);
}
void SPF::log_time(int iteration, double duration) {
FILE* file = fopen((settings->outdir+"/time_log.dat").c_str(), "a");
fprintf(file, "%d\t%.f\n", iteration, duration);
fclose(file);
}
void SPF::log_user(FILE* file, int user, int heldout, double rmse, double mae,
double rank, int first, double crr, double ncrr, double ndcg) {
fprintf(file, "%d\t%f\t%f\t%f\t%d\t%f\t%f\t%f\n", user,
rmse, mae, rank, first, crr, ncrr, ndcg);
}
| 34.245841 | 108 | 0.54488 | ajbc |
f8579065aff8ac369152ea1c4971d4a7517e61cc | 7,812 | cpp | C++ | test/run/code/vppTestFormats/main.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/run/code/vppTestFormats/main.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | test/run/code/vppTestFormats/main.cpp | maikebing/vpp | efa6c32f898e103d749764ce3a0b7dc29d6e9a51 | [
"BSD-2-Clause"
] | null | null | null | // -----------------------------------------------------------------------------
#include <vppAll.hpp>
// -----------------------------------------------------------------------------
namespace vpptest {
// -----------------------------------------------------------------------------
unsigned int s_passedChecks = 0;
unsigned int s_failedChecks = 0;
// -----------------------------------------------------------------------------
void check ( bool bCondition )
{
if ( ! bCondition )
{
++s_failedChecks;
std::cerr << "Check failed" << std::endl;
}
else
++s_passedChecks;
}
// -----------------------------------------------------------------------------
void testBasicTypes()
{
using namespace vpp;
{
usint2_t v20, v21, v22, v23, v24;
v20 = 0u; v21 = 1u; v22 = 2u; v23 = 3u; v24 = 4u;
check ( v20 == 0u ); check ( v21 == 1u ); check ( v22 == 2u );
check ( v23 == 3u ); check ( v24 == 0u );
usint8_t v80, v81, v82, v8255, v8256;
v80 = 0u; v81 = 1u; v82 = 2u; v8255 = 255u; v8256 = 256u;
check ( v80 == 0u ); check ( v81 == 1u ); check ( v82 == 2u );
check ( v8255 == 255u ); check ( v8256 == 0u );
}
{
sint2_t v20, v21, v2m1, v2m2, v24;
v20 = 0; v21 = 1; v2m1 = -1; v2m2 = -2; v24 = 4;
check ( v20 == 0 ); check ( v21 == 1 ); check ( v2m1 == -1 );
check ( v2m2 == -2 ); check ( v24 == 0 );
sint8_t v80, v81, v8m1, v8256;
v80 = 0; v81 = 1; v8m1 = -1; v8256 = 256;
check ( v80 == 0 ); check ( v81 == 1 ); check ( v8m1 == -1 );
check ( v8256 == 0 );
}
{
unorm8_t a0, a1, a2;
a0 = 0.0f; check ( float(a0) == 0.0f );
a1 = 1.0f; check ( float(a1) == 1.0f );
a2 = 7.0f/255.0f; check ( float(a2) == 7.0f/255.0f );
a0 = 0.0; check ( double(a0) == 0.0 );
a1 = 1.0; check ( double(a1) == 1.0 );
a2 = 7.0/255.0; check ( double(a2) == 7.0/255.0 );
}
{
snorm8_t a0, a1, a2, a3, a4;
a0 = 0.0f; check ( float(a0) == 0.0f );
a1 = 1.0f; check ( float(a1) == 1.0f );
a2 = -1.0f; check ( float(a2) == -1.0f );
a3 = 7.0f/127.0f; check ( float(a3) == 7.0f/127.0f );
a4 = -7.0f/127.0f; check ( float(a4) == -7.0f/127.0f );
a0 = 0.0; check ( double(a0) == 0.0 );
a1 = 1.0; check ( double(a1) == 1.0 );
a2 = -1.0; check ( double(a2) == -1.0 );
a3 = 7.0/127.0; check ( double(a3) == 7.0/127.0 );
a4 = -7.0/127.0; check ( double(a4) == -7.0/127.0 );
}
// uscaled_t
// sscaled_t
// srgb_t
// float16_t
}
// -----------------------------------------------------------------------------
void testPackedFormats()
{
using namespace vpp;
{
typedef format< unorm4_t, unorm4_t > FmtR4G4;
typedef FmtR4G4::data_type DatR4G4;
check ( FmtR4G4::code == VK_FORMAT_R4G4_UNORM_PACK8 );
check ( sizeof ( DatR4G4 ) == 1 );
DatR4G4 a00, a01, a10, a11;
a00.set ( 0.0f, 0.0f ); check ( float(a00.r) == 0.0f && float(a00.g) == 0.0f );
a01.set ( 0.0f, 1.0f ); check ( float(a01.r) == 0.0f && float(a01.g) == 1.0f );
a10.set ( 1.0f, 0.0f ); check ( float(a10.r) == 1.0f && float(a10.g) == 0.0f );
a11.set ( 1.0f, 1.0f ); check ( float(a11.r) == 1.0f && float(a11.g) == 1.0f );
}
{
typedef format< unorm4_t, unorm4_t, unorm4_t, unorm4_t > FmtR4G4B4A4;
typedef FmtR4G4B4A4::data_type DatR4G4B4A4;
check ( FmtR4G4B4A4::code == VK_FORMAT_R4G4B4A4_UNORM_PACK16 );
check ( sizeof ( DatR4G4B4A4 ) == 2 );
DatR4G4B4A4 a0000, a0001, a0010, a0100, a1000, a1111;
a0000.set ( 0.0f, 0.0f, 0.0f, 0.0f ); check ( float(a0000.r) == 0.0f && float(a0000.g) == 0.0f && float(a0000.b) == 0.0f && float(a0000.a) == 0.0f );
a0001.set ( 0.0f, 0.0f, 0.0f, 1.0f ); check ( float(a0001.r) == 0.0f && float(a0001.g) == 0.0f && float(a0001.b) == 0.0f && float(a0001.a) == 1.0f );
a0010.set ( 0.0f, 0.0f, 1.0f, 0.0f ); check ( float(a0010.r) == 0.0f && float(a0010.g) == 0.0f && float(a0010.b) == 1.0f && float(a0010.a) == 0.0f );
a0100.set ( 0.0f, 1.0f, 0.0f, 0.0f ); check ( float(a0100.r) == 0.0f && float(a0100.g) == 1.0f && float(a0100.b) == 0.0f && float(a0100.a) == 0.0f );
a1000.set ( 1.0f, 0.0f, 0.0f, 0.0f ); check ( float(a1000.r) == 1.0f && float(a1000.g) == 0.0f && float(a1000.b) == 0.0f && float(a1000.a) == 0.0f );
a1111.set ( 1.0f, 1.0f, 1.0f, 1.0f ); check ( float(a1111.r) == 1.0f && float(a1111.g) == 1.0f && float(a1111.b) == 1.0f && float(a1111.a) == 1.0f );
}
{
typedef format< unorm4_t, unorm4_t, unorm4_t, unorm4_t, BGRA > FmtB4G4R4A4;
typedef FmtB4G4R4A4::data_type DatB4G4R4A4;
check ( FmtB4G4R4A4::code == VK_FORMAT_B4G4R4A4_UNORM_PACK16 );
check ( sizeof ( DatB4G4R4A4 ) == 2 );
DatB4G4R4A4 a0000, a0001, a0010, a0100, a1000, a1111;
a0000.set ( 0.0f, 0.0f, 0.0f, 0.0f ); check ( float(a0000.r) == 0.0f && float(a0000.g) == 0.0f && float(a0000.b) == 0.0f && float(a0000.a) == 0.0f );
a0001.set ( 0.0f, 0.0f, 0.0f, 1.0f ); check ( float(a0001.r) == 0.0f && float(a0001.g) == 0.0f && float(a0001.b) == 0.0f && float(a0001.a) == 1.0f );
a0010.set ( 0.0f, 0.0f, 1.0f, 0.0f ); check ( float(a0010.r) == 0.0f && float(a0010.g) == 0.0f && float(a0010.b) == 1.0f && float(a0010.a) == 0.0f );
a0100.set ( 0.0f, 1.0f, 0.0f, 0.0f ); check ( float(a0100.r) == 0.0f && float(a0100.g) == 1.0f && float(a0100.b) == 0.0f && float(a0100.a) == 0.0f );
a1000.set ( 1.0f, 0.0f, 0.0f, 0.0f ); check ( float(a1000.r) == 1.0f && float(a1000.g) == 0.0f && float(a1000.b) == 0.0f && float(a1000.a) == 0.0f );
a1111.set ( 1.0f, 1.0f, 1.0f, 1.0f ); check ( float(a1111.r) == 1.0f && float(a1111.g) == 1.0f && float(a1111.b) == 1.0f && float(a1111.a) == 1.0f );
}
{
typedef format< unorm5_t, unorm6_t, unorm5_t > FmtR5G6B5;
typedef FmtR5G6B5::data_type DatR5G6B5;
check ( FmtR5G6B5::code == VK_FORMAT_R5G6B5_UNORM_PACK16 );
check ( sizeof ( DatR5G6B5 ) == 2 );
DatR5G6B5 a000, a001, a010, a100, a111;
a000.set ( 0.0f, 0.0f, 0.0f ); check ( float(a000.r) == 0.0f && float(a000.g) == 0.0f && float(a000.b) == 0.0f );
a001.set ( 0.0f, 0.0f, 1.0f ); check ( float(a001.r) == 0.0f && float(a001.g) == 0.0f && float(a001.b) == 1.0f );
a010.set ( 0.0f, 1.0f, 0.0f ); check ( float(a010.r) == 0.0f && float(a010.g) == 1.0f && float(a010.b) == 0.0f );
a100.set ( 1.0f, 0.0f, 0.0f ); check ( float(a100.r) == 1.0f && float(a100.g) == 0.0f && float(a100.b) == 0.0f );
a111.set ( 1.0f, 1.0f, 1.0f ); check ( float(a111.r) == 1.0f && float(a111.g) == 1.0f && float(a111.b) == 1.0f );
}
}
// -----------------------------------------------------------------------------
void printResults()
{
std::cout << "VPP Formats test results:" << std::endl;
if ( s_failedChecks == 0 )
std::cout << "All tests passed !" << std::endl;
std::cout << "Passed checks: " << s_passedChecks << std::endl;
std::cout << "Failed checks: " << s_failedChecks << std::endl;
}
// -----------------------------------------------------------------------------
} // namespace vpptest
// -----------------------------------------------------------------------------
int main()
{
using namespace vpptest;
testBasicTypes();
testPackedFormats();
printResults();
return 0;
}
// -----------------------------------------------------------------------------
| 44.64 | 158 | 0.450589 | maikebing |
d3781cf444b8d8b8f0f1d33a3f7235bc372ddc7f | 499 | cpp | C++ | Cpp/Strings/amazing-subarrays.cpp | mailtokartik1/InterviewBit-Solutions | 8a9be25cf55947aff456c7c138e2ee6f518aa6a5 | [
"MIT"
] | 58 | 2019-06-15T01:35:06.000Z | 2021-04-27T08:32:39.000Z | Strings/amazing-subarrays.cpp | mojo912/InterviewBit-Solutions | 62fb19efff15bbe3b42183c12d2e6adf7c4c2a84 | [
"MIT"
] | 3 | 2019-06-17T00:20:13.000Z | 2019-06-30T05:41:10.000Z | Strings/amazing-subarrays.cpp | mojo912/InterviewBit-Solutions | 62fb19efff15bbe3b42183c12d2e6adf7c4c2a84 | [
"MIT"
] | 14 | 2019-06-15T01:35:09.000Z | 2020-08-27T19:45:28.000Z | int Solution::solve(string A) {
int count = 0;
// Store the vowels in a map
map<char, int> B;
B['A'] = 1;
B['a'] = 1;
B['E'] = 1;
B['e'] = 1;
B['I'] = 1;
B['i'] = 1;
B['O'] = 1;
B['o'] = 1;
B['U'] = 1;
B['u'] = 1;
// Loop through the array and if the value exists, increment the count
for (int i = 0; i < A.size(); i ++) {
if (B[A[i]]) {
count += (A.size() - i) % 10003;
}
}
return count % 10003;
}
| 18.481481 | 74 | 0.400802 | mailtokartik1 |
d3782145691ad62d124577e502c6906818c0aef3 | 303 | cpp | C++ | 55. Jump Game.cpp | qinenergy/leetCode | 79f960795445470a16a4755b05aa05f99e5c616b | [
"MIT"
] | 3 | 2017-02-22T14:28:27.000Z | 2017-04-26T16:26:06.000Z | 55. Jump Game.cpp | qinenergy/leetCode | 79f960795445470a16a4755b05aa05f99e5c616b | [
"MIT"
] | null | null | null | 55. Jump Game.cpp | qinenergy/leetCode | 79f960795445470a16a4755b05aa05f99e5c616b | [
"MIT"
] | null | null | null | class Solution2 {
public:
bool canJump(vector<int>& nums) {
int len = nums.size();
if(len <= 1) return true;
int last = len - 1;
for(int i = len - 2; i >= 0; --i){
if(nums[i] == 0 || i + nums[i] < last) continue;
else last = i;
}
return last == 0;
}
}; | 23.307692 | 54 | 0.478548 | qinenergy |
d37a523c4b28b4e5f9886451637e3826748d1e54 | 20,334 | cc | C++ | pin-2.11/source/tools/ToolUnitTests/transactionalmem.cc | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | 3 | 2020-06-26T09:35:19.000Z | 2021-01-03T16:58:11.000Z | pin-2.11/source/tools/ToolUnitTests/transactionalmem.cc | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | null | null | null | pin-2.11/source/tools/ToolUnitTests/transactionalmem.cc | swchoi1994/Project | e46fa191afe54d6676016d41534c3531eb51ff79 | [
"Intel"
] | 2 | 2020-12-27T03:58:38.000Z | 2020-12-27T03:58:38.000Z | /* ================================================================== */
/* Transactional Memory Pin Tool */
/* ------------------------------------------------------------------ */
/* */
/* functionality: */
/* a simple transactional memory model */
/* */
/* commands line options: */
/* -traceon enables the log file of memory tracing */
/* -tiebreaker <INT> decides which transaction wins when conflicting */
/* (see PickSuccessfulTransaction() for detail) */
/* */
/* ================================================================== */
#include "utilities.h"
#include "memlog.h"
#include <map>
/* ------------------------------------------------------------------ */
/* Global Type(s) */
/* ------------------------------------------------------------------ */
class THREADSTATE
{
public:
THREADSTATE(BOOL verbose) :
intransaction(false),
aborting(false)
{
memlog = new MEMLOG(verbose);
}
~THREADSTATE() { delete memlog; }
BOOL intransaction;
BOOL aborting;
CHECKPOINT chkpt;
MEMLOG* memlog;
};
/* ------------------------------------------------------------------ */
/* Global Variables */
/* ------------------------------------------------------------------ */
map<UINT32, THREADSTATE*> threadstates; // tracks the state of the threads
BOOL verbose; // whether to output trace file
fstream tracefile; // trace file
UINT32 tiebreaker; // scheme to decide which transaction will win
UINT32 ntransactions; // number of threads currently in a transaction
/* ------------------------------------------------------------------ */
/* Function Declarations */
/* ------------------------------------------------------------------ */
VOID Init(UINT32, char**);
VOID Fini(INT32, VOID*);
VOID ThreadBegin(UINT32, VOID*, int, VOID*);
VOID ThreadEnd(UINT32, INT32, VOID*);
VOID FlagXRtn(RTN, VOID*);
VOID FlagMemIns(INS, VOID*);
VOID ProcessMemIns(BOOL, BOOL, BOOL, ADDRINT, UINT32, ADDRINT, ADDRINT, UINT32, UINT32);
VOID BeginTransaction(UINT32, CHECKPOINT*);
VOID CommitTransaction(UINT32);
VOID AbortTransaction(UINT32);
VOID AbortTransactionBegin(THREADSTATE*);
VOID AbortTransactionEnd(THREADSTATE*);
UINT32 PickSuccessfulTransaction(UINT32, set<UINT32>, BOOL);
VOID LogInsTrace(UINT32, ADDRINT, ADDRINT, const string*);
/* ================================================================== */
int main(UINT32 argc, char** argv)
{
Init(argc, argv);
PIN_InitSymbols();
PIN_Init(argc, argv);
PIN_AddThreadBeginFunction(ThreadBegin, 0);
PIN_AddThreadEndFunction(ThreadEnd, 0);
RTN_AddInstrumentFunction(FlagXRtn, 0);
INS_AddInstrumentFunction(FlagMemIns, 0);
PIN_AddFiniFunction(Fini, 0);
PIN_StartProgram();
return 0;
}
/* ------------------------------------------------------------------ */
/* Initalization & Clean Up */
/* ------------------------------------------------------------------ */
VOID Init(UINT32 argc, char** argv)
{
GetArg(argc, argv, "-traceon", verbose);
ThreadBegin(0, NULL, 0, NULL);
if (verbose)
{
tracefile.open("transactionalmem.txt", fstream::out | fstream::app);
}
GetArg(argc, argv, "-tiebreaker", tiebreaker, 1);
ntransactions = 0;
}
VOID Fini(INT32 code, VOID* v)
{
ThreadEnd(0, 0, NULL);
if (verbose)
{
tracefile.close();
}
}
/* ------------------------------------------------------------------ */
/* Initialization and Clean Up of Thread State */
/* ------------------------------------------------------------------ */
VOID ThreadBegin(THREADID thread_id, VOID* sp, int flags, VOID* v)
{
std::cout << "Thread " << thread_id << " begins.\n" << flush;
ASSERTX(threadstates.find(thread_id) == threadstates.end());
threadstates[thread_id] = new THREADSTATE(verbose);
}
VOID ThreadEnd(THREADID thread_id, INT32 code, VOID* v)
{
std::cout << "Thread " << thread_id << " ends.\n" << flush;
map<UINT32, THREADSTATE*>::iterator threadstate_ptr = threadstates.find(thread_id);
ASSERTX(threadstate_ptr != threadstates.end());
delete threadstate_ptr->second;
threadstates.erase(threadstate_ptr);
}
/* ------------------------------------------------------------------ */
/* Instrumentation Routines */
/* ------------------------------------------------------------------ */
VOID FlagXRtn(RTN rtn, VOID* v)
{
RTN_Open(rtn);
const string* rtn_name = new string(RTN_Name(rtn));
if (rtn_name->find("XBEGIN") != string::npos)
{
RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)BeginTransaction,
IARG_THREAD_ID,
IARG_CHECKPOINT,
IARG_END);
}
else if (rtn_name->find("XEND") != string::npos)
{
RTN_InsertCall(rtn, IPOINT_BEFORE, (AFUNPTR)CommitTransaction,
IARG_THREAD_ID,
IARG_END);
}
RTN_Close(rtn);
}
VOID FlagMemIns(INS ins, VOID* v)
{
if (INS_IsMemoryWrite(ins) || INS_IsMemoryRead(ins))
{
if (INS_IsMemoryWrite(ins) && INS_IsMemoryRead(ins) && INS_HasMemoryRead2(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)ProcessMemIns,
IARG_BOOL, true,
IARG_BOOL, true,
IARG_BOOL, true,
IARG_MEMORYWRITE_EA,
IARG_MEMORYWRITE_SIZE,
IARG_MEMORYREAD_EA,
IARG_MEMORYREAD2_EA,
IARG_MEMORYREAD_SIZE,
IARG_THREAD_ID,
IARG_END);
}
else if (INS_IsMemoryWrite(ins) && INS_IsMemoryRead(ins) && !INS_HasMemoryRead2(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)ProcessMemIns,
IARG_BOOL, true,
IARG_BOOL, true,
IARG_BOOL, false,
IARG_MEMORYWRITE_EA,
IARG_MEMORYWRITE_SIZE,
IARG_MEMORYREAD_EA,
IARG_ADDRINT, 0,
IARG_MEMORYREAD_SIZE,
IARG_THREAD_ID,
IARG_END);
}
else if (INS_IsMemoryWrite(ins) && !INS_IsMemoryRead(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)ProcessMemIns,
IARG_BOOL, true,
IARG_BOOL, false,
IARG_BOOL, false,
IARG_MEMORYWRITE_EA,
IARG_MEMORYWRITE_SIZE,
IARG_ADDRINT, 0,
IARG_ADDRINT, 0,
IARG_UINT32, 0,
IARG_THREAD_ID,
IARG_END);
}
else if (!INS_IsMemoryWrite(ins) && INS_IsMemoryRead(ins) && INS_HasMemoryRead2(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)ProcessMemIns,
IARG_BOOL, false,
IARG_BOOL, true,
IARG_BOOL, true,
IARG_ADDRINT, 0,
IARG_UINT32, 0,
IARG_MEMORYREAD_EA,
IARG_MEMORYREAD2_EA,
IARG_MEMORYREAD_SIZE,
IARG_THREAD_ID,
IARG_END);
}
else if (!INS_IsMemoryWrite(ins) && INS_IsMemoryRead(ins) && !INS_HasMemoryRead2(ins))
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)ProcessMemIns,
IARG_BOOL, false,
IARG_BOOL, true,
IARG_BOOL, false,
IARG_ADDRINT, 0,
IARG_UINT32, 0,
IARG_MEMORYREAD_EA,
IARG_ADDRINT, 0,
IARG_MEMORYREAD_SIZE,
IARG_THREAD_ID,
IARG_END);
}
else
{
ASSERTX(0);
}
}
if (verbose)
{
INS_InsertCall(ins, IPOINT_BEFORE, (AFUNPTR)LogInsTrace,
IARG_THREAD_ID,
IARG_INST_PTR,
IARG_REG_VALUE, REG_STACK_PTR,
IARG_PTR, new string(INS_Disassemble(ins)),
IARG_END);
}
}
/* ------------------------------------------------------------------ */
/* ProcessMemIns: */
/* meat of the transactional memory model: detects conflicts with */
/* current transactions, aborts transaction(s) if necessary, and */
/* updates transaction memory logs */
/* ------------------------------------------------------------------ */
VOID ProcessMemIns(BOOL iswrite, BOOL isread, BOOL hasread2,
ADDRINT waddr, UINT32 wlen,
ADDRINT raddr, ADDRINT raddr2, UINT32 rlen,
THREADID thread_id)
{
PIN_LockClient();
if (ntransactions > 0)
{
map<UINT32, THREADSTATE*>::iterator threadstate_ptr = threadstates.find(thread_id);
ASSERTX(threadstate_ptr != threadstates.end());
THREADSTATE* threadstate = threadstate_ptr->second;
// transaction aborting: memory already restored, but need to rollback execution
if (threadstate->aborting)
{
std::cout << "Thread " << thread_id << " " << flush;
AbortTransactionEnd(threadstate);
}
else if ((ntransactions > 1) || (!(threadstate->intransaction)))
{
// detect conflicts with other threads' transactions
set<UINT32> conflicts;
map<UINT32, THREADSTATE*>::iterator itr;
for (itr = threadstates.begin(); itr != threadstates.end(); itr++)
{
MEMLOG* memlog = (itr->second)->memlog;
if ((itr->first != thread_id) &&
((itr->second)->intransaction) &&
((iswrite && memlog->DetectConflict(waddr, wlen, true, tracefile)) ||
(isread && memlog->DetectConflict(raddr, rlen, false, tracefile)) ||
(hasread2 && memlog->DetectConflict(raddr2, rlen, false, tracefile))))
{
conflicts.insert(itr->first);
}
}
// decide which thread(s) continue and which thread(s) abort (if any)
UINT32 winner;
if (!conflicts.empty())
{
winner = PickSuccessfulTransaction(thread_id, conflicts, threadstate->intransaction);
std::cout << "Thread " << thread_id << " conflicts with thread(s): " << flush;
set<UINT32>::iterator itr_conflicts;
for (itr_conflicts = conflicts.begin(); itr_conflicts != conflicts.end(); itr_conflicts++)
{
std::cout << *itr_conflicts << " " << flush;
}
std::cout << "\n" << flush;
// abort current thread's transaction
if (winner != thread_id)
{
AbortTransaction(thread_id);
}
// abort conflicting transactions
else
{
for (itr_conflicts = conflicts.begin(); itr_conflicts != conflicts.end(); itr_conflicts++)
{
map<UINT32, THREADSTATE*>::iterator abortingthreadstate_ptr = threadstates.find(*itr_conflicts);
ASSERTX(abortingthreadstate_ptr != threadstates.end());
THREADSTATE* abortingthreadstate = abortingthreadstate_ptr->second;
ASSERTX(abortingthreadstate->intransaction);
std::cout << "Thread " << abortingthreadstate_ptr->first << " " << flush;
AbortTransactionBegin(abortingthreadstate);
}
}
conflicts.clear();
}
else
{
winner = thread_id;
}
// update current thread's transaction log if successful
if ((winner == thread_id) && (threadstate->intransaction))
{
MEMLOG* memlog = threadstate->memlog;
if (iswrite) { memlog->RecordWrite(waddr, wlen, tracefile); }
if (isread) { memlog->RecordRead(raddr, rlen, tracefile); }
if (hasread2) { memlog->RecordRead(raddr2, rlen, tracefile); }
}
}
else
{
// if current thread has the only transaction, skipped conflict detection code, but still need to update log
ASSERTX((threadstate->intransaction) && (ntransactions == 1));
MEMLOG* memlog = threadstate->memlog;
if (iswrite) { memlog->RecordWrite(waddr, wlen, tracefile); }
if (isread) { memlog->RecordRead(raddr, rlen, tracefile); }
if (hasread2) { memlog->RecordRead(raddr2, rlen, tracefile); }
}
}
PIN_UnlockClient();
}
/* ------------------------------------------------------------------ */
/* BeginTransaction: */
/* checkpoints the processor state and changes the thread's state to */
/* indicate that it's inside a transaction */
/* ------------------------------------------------------------------ */
VOID BeginTransaction(THREADID thread_id, CHECKPOINT* _chkpt)
{
PIN_LockClient();
std::cout << "Thread " << thread_id << " entering transaction.\n" << flush;
if (verbose)
{
tracefile << "Thread " << thread_id << " entering transaction.\n" << flush;
}
ntransactions++;
map<UINT32, THREADSTATE*>::iterator threadstate_ptr = threadstates.find(thread_id);
ASSERTX(threadstate_ptr != threadstates.end());
THREADSTATE* threadstate = threadstate_ptr->second;
threadstate->intransaction = true;
PIN_SaveCheckpoint(_chkpt, &(threadstate->chkpt));
PIN_UnlockClient();
}
/* ------------------------------------------------------------------ */
/* CommitTransaction: */
/* since the transaction has completed successful, we can trash the */
/* the checkpointed processor state and memory log; also change the */
/* thread's state to indicate that it's no longer inside a transaction*/
/* ------------------------------------------------------------------ */
VOID CommitTransaction(THREADID thread_id)
{
PIN_LockClient();
std::cout << "Thread " << thread_id << " committing transaction.\n" << flush;
ntransactions--;
map<UINT32, THREADSTATE*>::iterator threadstate_ptr = threadstates.find(thread_id);
ASSERTX(threadstate_ptr != threadstates.end());
THREADSTATE* threadstate = threadstate_ptr->second;
threadstate->intransaction = false;
(threadstate->memlog)->Reset();
PIN_UnlockClient();
}
/* ------------------------------------------------------------------ */
/* AbortTransaction: */
/* transaction is aborted due to detected memory conflict */
/* note, this is split into two parts because we cannot roll back an */
/* aborted thread's execution if it is not inside the pin tool */
/* currently, but we cannot release the current thread without first */
/* undoing the aborted thread's shared memory changes; it's ok to */
/* wait to roll back the aborted thread the next time we instrument */
/* its load or store, b/c it has not changed any globally visible */
/* in between */
/* ------------------------------------------------------------------ */
VOID AbortTransaction(THREADID thread_id)
{
std::cout << "Thread " << thread_id << " aborting transaction.\n" << flush;
map<UINT32, THREADSTATE*>::iterator threadstate_ptr = threadstates.find(thread_id);
ASSERTX(threadstate_ptr != threadstates.end());
THREADSTATE* threadstate = threadstate_ptr->second;
ASSERTX(threadstate->intransaction);
AbortTransactionBegin(threadstate);
AbortTransactionEnd(threadstate);
}
/* ------------------------------------------------------------------ */
/* AbortTransactionBegin: */
/* undo the aborted transaction's memory changes, and sets the */
/* thread's state to 'aborting' */
/* ------------------------------------------------------------------ */
VOID AbortTransactionBegin(THREADSTATE* threadstate)
{
std::cout << "restoring memory (abort, part I).\n" << flush;
(threadstate->memlog)->RestoreMem(tracefile);
threadstate->aborting = true;
}
/* ------------------------------------------------------------------ */
/* AbortTransactionEnd: */
/* roll back to the beginning of the transaction */
/* ------------------------------------------------------------------ */
VOID AbortTransactionEnd(THREADSTATE* threadstate)
{
std::cout << "resuming (abort, part II).\n" << flush;
ASSERTX(threadstate->aborting);
threadstate->aborting = false;
PIN_UnlockClient();
PIN_Resume(&(threadstate->chkpt));
}
/* ------------------------------------------------------------------ */
/* PickSuccessfulTransaction: */
/* very simple schemes to pick which transaction gets to proceed */
/* in the case of conflicts */
/* (1) always lets the non-transaction memop win over transactions */
/* (2) between multiple transactions: */
/* -tiebreaker 1 pick the smallest ID to win */
/* -tiebreaker 2 pick the largest ID to win */
/* ------------------------------------------------------------------ */
UINT32 PickSuccessfulTransaction(UINT32 current, set<UINT32> conflicts, BOOL current_in_transaction)
{
if (!current_in_transaction)
{
std::cout << "not in transaction!\n" << flush;
return current;
}
ASSERTX(!conflicts.empty());
ASSERTX(conflicts.find(current) == conflicts.end());
switch(tiebreaker)
{
case 1:
return((current < *(conflicts.begin())) ? current : *(conflicts.begin()));
case 2:
return((current > *(conflicts.rbegin())) ? current : *(conflicts.begin()));
default:
ASSERTX(0);
return 0;
}
}
/* ------------------------------------------------------------------ */
/* LogInsTrace: */
/* records the instructions and some state (stack pointer and */
/* the value at the top of the stack) */
/* ------------------------------------------------------------------ */
VOID LogInsTrace(THREADID thread_id, ADDRINT ip, ADDRINT sp, const string* disassm)
{
tracefile << dec << thread_id << ":\t" << hex << ip << "\t" << sp << "\t" << flush;
PrintHexWord(sp, tracefile);
tracefile << "\t" << *disassm << "\n";
}
/* ------------------------------------------------------------------ */
| 42.186722 | 121 | 0.464641 | swchoi1994 |
d38c6777e8de0303010838912276076fad268e68 | 191 | cpp | C++ | X-Engine/src/XEngine/LayerSystem/Layer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 4 | 2020-02-17T07:08:26.000Z | 2020-08-07T21:35:12.000Z | X-Engine/src/XEngine/LayerSystem/Layer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 25 | 2020-03-08T05:35:25.000Z | 2020-07-08T01:59:52.000Z | X-Engine/src/XEngine/LayerSystem/Layer.cpp | JohnMichaelProductions/X-Engine | 218ffcf64bfe5d5aed51b483c6f6986831ceeec4 | [
"Apache-2.0"
] | 1 | 2020-10-15T12:39:29.000Z | 2020-10-15T12:39:29.000Z | // Source file for Layer Class
#include "Xpch.h"
#include "XEngine/LayerSystem/Layer.h"
namespace XEngine
{
Layer::Layer(const std::string& name) : m_DebugName(name) {}
Layer::~Layer() {}
} | 23.875 | 61 | 0.706806 | JohnMichaelProductions |
d38e1c156a6d624d54108eb233756bd9cc5b4a6c | 198 | hh | C++ | Include/Luce/Text.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | 23 | 2017-02-09T11:48:01.000Z | 2017-04-08T10:19:21.000Z | Include/Luce/Text.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | null | null | null | Include/Luce/Text.hh | kmc7468/luce | 6f71407f250dbc0428ceba33aeef345cc601db34 | [
"MIT"
] | null | null | null | #ifndef LUCE_HEADER_TEXT_HH
#define LUCE_HEADER_TEXT_HH
#include <Luce/Text/Character.hh>
#include <Luce/Text/Encoding.hh>
#include <Luce/Text/EncodingRef.hh>
#include <Luce/Text/String.hh>
#endif | 22 | 35 | 0.792929 | kmc7468 |
d392029633060be323c771b62307fd41ade53bb1 | 2,444 | cpp | C++ | src/notifybyexecute.cpp | pasnox/knotifications | ef2871b2a485be5abe393e61c6cd93867420f896 | [
"BSD-3-Clause"
] | 1 | 2019-11-02T03:54:16.000Z | 2019-11-02T03:54:16.000Z | src/notifybyexecute.cpp | pasnox/knotifications | ef2871b2a485be5abe393e61c6cd93867420f896 | [
"BSD-3-Clause"
] | 2 | 2019-10-27T23:06:33.000Z | 2020-01-11T00:44:07.000Z | src/notifybyexecute.cpp | brute4s99/knotifications | bc01688f99fcbdc2d3ceb4ad9475da1359441408 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (C) 2005-2006 by Olivier Goffart <ogoffart at kde.org>
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) version 3, or any
later version accepted by the membership of KDE e.V. (or its
successor approved by the membership of KDE e.V.), which shall
act as a proxy defined in Section 6 of version 3 of the license.
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, see <http://www.gnu.org/licenses/>.
*/
#include "notifybyexecute.h"
#include <QHash>
#include <QWidget>
#include <KProcess>
#include <knotifyconfig.h>
#include "knotification.h"
#include "debug_p.h"
#include <kmacroexpander.h>
NotifyByExecute::NotifyByExecute(QObject *parent)
: KNotificationPlugin(parent)
{
}
NotifyByExecute::~NotifyByExecute()
{
}
void NotifyByExecute::notify(KNotification *notification, KNotifyConfig *config)
{
QString command = config->readEntry(QStringLiteral("Execute"));
if (!command.isEmpty()) {
QHash<QChar,QString> subst;
subst.insert(QLatin1Char('e'), notification->eventId());
subst.insert(QLatin1Char('a'), notification->appName());
subst.insert(QLatin1Char('s'), notification->text());
if (notification->widget()) {
subst.insert(QLatin1Char('w'), QString::number(notification->widget()->topLevelWidget()->winId()));
} else {
subst.insert(QLatin1Char('w'), QStringLiteral("0"));
}
subst.insert(QLatin1Char('i'), QString::number(notification->id()));
QString execLine = KMacroExpander::expandMacrosShellQuote(command, subst);
if (execLine.isEmpty()) {
execLine = command; // fallback
}
KProcess proc;
proc.setShellCommand(execLine.trimmed());
if (!proc.startDetached()) {
qCDebug(LOG_KNOTIFICATIONS) << "KProcess returned an error while trying to execute this command:" << execLine;
}
}
finish(notification);
}
| 32.586667 | 122 | 0.686579 | pasnox |
d393e442a14795a5fbbf833bbdb930dc797eadff | 1,093 | cpp | C++ | tests/Version/Test_Version.cpp | mathersm/Penguin | e593dca4283364db02f2eca87dedeb9f61304f06 | [
"MIT"
] | 1 | 2019-01-27T15:17:04.000Z | 2019-01-27T15:17:04.000Z | tests/Version/Test_Version.cpp | mathersm/Penguin | e593dca4283364db02f2eca87dedeb9f61304f06 | [
"MIT"
] | 1 | 2017-06-06T15:02:42.000Z | 2017-06-06T15:02:43.000Z | tests/Version/Test_Version.cpp | mathersm/Penguin | e593dca4283364db02f2eca87dedeb9f61304f06 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 Michael Mathers
*/
#include <penguin/Version.h>
#include <iostream>
#include <sstream>
namespace
{
void print_test_result(int result, std::string test_text)
{
std::cout << "[" << (result ? "FAIL" : " OK ") << "] " << test_text.c_str() << std::endl;
}
int test_version_string(void)
{
std::string version;
std::stringstream string_stream;
string_stream << Penguin::PENGUIN_MAJOR_VERSION;
string_stream << ".";
string_stream << Penguin::PENGUIN_MINOR_VERSION;
string_stream << ".";
string_stream << Penguin::PENGUIN_PATCH_VERSION;
std::string crafted_version(string_stream.str());
std::string constexpr_version(Penguin::PENGUIN_VERSION);
int result = crafted_version.compare(constexpr_version);
print_test_result(result, "test_version_string()");
return result;
}
}
int main(int argc, char *argv[])
{
std::cout << "Test_Version" << std::endl;
int result = 0;
result |= test_version_string();
return result;
}
| 23.255319 | 97 | 0.622141 | mathersm |
d3988951a50165c9076482141b914e2668377d82 | 2,190 | cpp | C++ | src/VERGE/ResourceSystem/ResourceSystem.cpp | zrmyers/VERGE | 692f2c57191652054fbdf569230a84782c745ea8 | [
"MIT"
] | null | null | null | src/VERGE/ResourceSystem/ResourceSystem.cpp | zrmyers/VERGE | 692f2c57191652054fbdf569230a84782c745ea8 | [
"MIT"
] | null | null | null | src/VERGE/ResourceSystem/ResourceSystem.cpp | zrmyers/VERGE | 692f2c57191652054fbdf569230a84782c745ea8 | [
"MIT"
] | null | null | null | /*
* ResourceSystem.cpp
*
* Created on: Sep 18, 2017
* Author: Zane
*/
#include "ResourceSystem.h"
#include "../ID.h"
#include "Resources/Mesh.h"
namespace VERGE {
std::shared_ptr<ResourceSystem> ResourceSystem::getResourceSystem() {
static std::shared_ptr<ResourceSystem> resourceSystem(new ResourceSystem());
return resourceSystem;
}
ResourceSystem::ResourceSystem() {
resourceTypeIDs[ResourceNames::MESH] =
resourceFactory.registerType([](){ return (FactoryObject*) new Mesh();});
resourceManifest = ResourceManifestDAO::getResourceManifest();
}
ResourceSystem::~ResourceSystem() {
}
int ResourceSystem::getResourceID(std::string resourceType, std::string resourceHandleString) {
int resourceID = ID::UNKNOWN_ID;
/*
* Check to see that the resource type is registered with our resource factory. If it isn't
* we can't create this resource.
*/
auto resourceTypeID_iter = resourceTypeIDs.find(resourceType);
if (resourceTypeID_iter != resourceTypeIDs.end()) {
int resourceTypeID = resourceTypeID_iter->second;
/*
* The resource is registered with our factory, so we can now check to see if it is in our manifest. We'll
* have to add a new resource to the manifest if it doesn't exist.
*/
std::shared_ptr<ResourceHandle> handle = resourceManifest->getResourceHandle(resourceHandleString);
if (!handle) {
handle = std::shared_ptr<ResourceHandle>(new ResourceHandle);
handle->handle = resourceHandleString;
handle->type = resourceType;
/*
* We can only add it to the resource manifest, if there is a file we can save it to. Because there is
* no such file, we won't be setting the file field in the resource handle.
*/
}
/*
*
*/
std::shared_ptr<Resource> resource = resourceFactory.create(resourceTypeID);
resourceID = resource->getID();
}
return resourceID;
}
int ResourceSystem::getResourceTypeID(std::string resourceTypeString) {
int typeID = ID::UNKNOWN_ID;
auto id = resourceTypeIDs.find(resourceTypeString);
if (id != resourceTypeIDs.end()) typeID = id->second;
return typeID;
}
} /* namespace VERGE */
| 29.2 | 110 | 0.7 | zrmyers |
d398d8ec08690f28123cadcde53e35950d3474d7 | 2,965 | cc | C++ | src/objects/database/database.cc | bengotow/better-sqlite3 | 2606eef344cdf22f23ec8bd403f4aeb305f644cb | [
"MIT"
] | 2 | 2017-10-10T06:24:35.000Z | 2021-06-15T15:01:39.000Z | src/objects/database/database.cc | bengotow/better-sqlite3 | 2606eef344cdf22f23ec8bd403f4aeb305f644cb | [
"MIT"
] | null | null | null | src/objects/database/database.cc | bengotow/better-sqlite3 | 2606eef344cdf22f23ec8bd403f4aeb305f644cb | [
"MIT"
] | 2 | 2017-03-15T06:34:50.000Z | 2017-05-05T02:47:03.000Z | #include <stdint.h>
#include <sqlite3.h>
#include <nan.h>
#include "database.h"
#include "../statement/statement.h"
#include "../transaction/transaction.h"
#include "../../workers/open.h"
#include "../../workers/close.h"
#include "../../util/macros.h"
#include "../../util/data.h"
#include "../../util/list.h"
#include "../../util/transaction-handles.h"
const v8::PropertyAttribute FROZEN = static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly);
bool CONSTRUCTING_PRIVILEGES = false;
sqlite3_uint64 NEXT_STATEMENT_ID = 0;
sqlite3_uint64 NEXT_TRANSACTION_ID = 0;
Nan::Persistent<v8::Function> NullFactory;
#include "new.cc"
#include "open.cc"
#include "close.cc"
#include "create-statement.cc"
#include "create-transaction.cc"
#include "pragma.cc"
#include "checkpoint.cc"
#include "util.cc"
Database::Database() : Nan::ObjectWrap(),
db_handle(NULL),
t_handles(NULL),
state(DB_CONNECTING),
workers(0),
in_each(false),
safe_ints(false) {}
Database::~Database() {
state = DB_DONE;
// This is necessary in the case that a database and its statements are
// garbage collected at the same time. The database might be destroyed
// first, so it needs to tell all of its statements "hey, I don't exist
// anymore". By the same nature, statements must remove themselves from a
// database's sets when they are garbage collected first.
CloseChildHandles();
CloseHandles();
}
void Database::Init(v8::Local<v8::Object> exports, v8::Local<v8::Object> module) {
Nan::HandleScope scope;
v8::Local<v8::FunctionTemplate> t = Nan::New<v8::FunctionTemplate>(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(Nan::New("Database").ToLocalChecked());
Nan::SetPrototypeMethod(t, "close", Close);
Nan::SetPrototypeMethod(t, "prepare", CreateStatement);
Nan::SetPrototypeMethod(t, "transaction", CreateTransaction);
Nan::SetPrototypeMethod(t, "pragma", Pragma);
Nan::SetPrototypeMethod(t, "checkpoint", Checkpoint);
Nan::SetPrototypeMethod(t, "defaultSafeIntegers", DefaultSafeIntegers);
Nan::SetAccessor(t->InstanceTemplate(), Nan::New("open").ToLocalChecked(), Open);
Nan::Set(exports, Nan::New("Database").ToLocalChecked(),
Nan::GetFunction(t).ToLocalChecked());
// Save NullFactory to persistent handle.
v8::Local<v8::Function> require = v8::Local<v8::Function>::Cast(Nan::Get(module, Nan::New("require").ToLocalChecked()).ToLocalChecked());
v8::Local<v8::Value> args[1] = {Nan::New("../../lib/null-factory.js").ToLocalChecked()};
NullFactory.Reset(v8::Local<v8::Function>::Cast(Nan::Call(require, module, 1, args).ToLocalChecked()));
}
// Returns an SQLite3 result code.
int Database::CloseHandles() {
delete t_handles;
int status = sqlite3_close(db_handle);
t_handles = NULL;
db_handle = NULL;
return status;
}
void Database::CloseChildHandles() {
for (Statement* stmt : stmts) {stmt->CloseHandles();}
for (Transaction* trans : transs) {trans->CloseHandles();}
stmts.clear();
transs.clear();
}
| 34.08046 | 138 | 0.720405 | bengotow |
d39e92ec613b0a4cc4644d3213468edee474aece | 1,157 | cpp | C++ | p1149.cpp | joe1166/noi | be2e9fcd8306ff4f20a4306e219656346a396013 | [
"Apache-2.0"
] | null | null | null | p1149.cpp | joe1166/noi | be2e9fcd8306ff4f20a4306e219656346a396013 | [
"Apache-2.0"
] | null | null | null | p1149.cpp | joe1166/noi | be2e9fcd8306ff4f20a4306e219656346a396013 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
using namespace std;
int numof[10] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6};
int n;
int a, b;
int c = 0;
int fnum = 0;
int count(int n, int a)
{
if (a < 10)
{
return n - numof[a];
}
else if (a < 100)
{
return n - (numof[a / 10] + numof[a % 10]);
}
else if (a < 1000)
{
return n - (numof[a / 100] + numof[(a % 100) / 10] + numof[a % 10]);
}
else
{
return -1;
}
}
int findb(int n)
{
int bn = 0;
for (int i = 0; i < 1000; i++)
{
b = i;
bn = count(n, i);
if (bn > 0)
{
c = a + b;
bn = count(bn, c);
if (bn == 0)
{
fnum++;
//cout << a << " " << b << " " << c << endl;
}
}
}
return 0;
}
int finda(int n)
{
int an = 0;
for (int i = 0; i < 1000; i++)
{
a = i;
an = count(n, i);
if (an > 0)
findb(an);
}
return 0;
}
int main(int argc, char const *argv[])
{
cin >> n;
n = n - 4;
finda(n);
cout << fnum;
//system("PAUSE");
return 0;
}
| 15.025974 | 76 | 0.357822 | joe1166 |
d39ee50288a65d7534a54319b9cd3b4be07f3691 | 497 | cpp | C++ | src/main.cpp | simojanhunen/dungeon_crawler | 09385ddf33c4144ad06c819d0ef93d24f02fb630 | [
"MIT"
] | null | null | null | src/main.cpp | simojanhunen/dungeon_crawler | 09385ddf33c4144ad06c819d0ef93d24f02fb630 | [
"MIT"
] | null | null | null | src/main.cpp | simojanhunen/dungeon_crawler | 09385ddf33c4144ad06c819d0ef93d24f02fb630 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------
// Main
// ----------------------------------------------------------------------------
#include <stdlib.h>
#include "game/game.hpp"
int main(void)
{
#if defined(_WIN64) || defined(_WIN32)
(void)system("CLS");
#else
(void)system("clear");
#endif
Game game;
game.initGame();
// Main game loop
while (game.getRunningStatus())
{
game.MainMenu();
}
return EXIT_SUCCESS;
}
| 18.407407 | 79 | 0.400402 | simojanhunen |
d3a718090b460168c2e0d82a3f1a0bda888fca7c | 1,218 | cpp | C++ | 1st_100/problem068.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 1st_100/problem068.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | null | null | null | 1st_100/problem068.cpp | takekoputa/project-euler | 6f434be429bd26f5d0f84f5ab0f5fa2bd677c790 | [
"MIT"
] | 1 | 2021-11-02T12:08:46.000Z | 2021-11-02T12:08:46.000Z | // Problem: https://projecteuler.net/problem=68
#include<iostream>
#include<algorithm>
#include<vector>
#include<numeric>
#include<sstream>
using namespace std;
#define endl "\n"
typedef uint64_t N64;
const N64 N = 10;
const N64 M = 16;
bool V1_lowest(const vector<N64>& V)
{
for (int i = 1; i < N/2; i++)
if (V[0] > V[i])
return false;
return true;
}
string V_to_number(const vector<N64>& V)
{
stringstream s;
N64 n = V[0] + V[5] + V[6];
if (V[1] + V[6] + V[7] != n ||
V[2] + V[7] + V[8] != n ||
V[3] + V[8] + V[9] != n ||
V[4] + V[9] + V[5] != n)
return "0";
s << V[0] << V[5] << V[6];
s << V[1] << V[6] << V[7];
s << V[2] << V[7] << V[8];
s << V[3] << V[8] << V[9];
s << V[4] << V[9] << V[5];
if (s.str().size() != M)
return "0";
return s.str();
}
int main()
{
string ans = "0";
vector<N64> V = vector<N64>(N);
iota(begin(V), end(V), 1);
do
{
if (!V1_lowest(V))
continue;
string n = V_to_number(V);
if (n.compare(ans) > 0)
ans = n;
} while (next_permutation(V.begin(), V.end()));
cout << ans << endl;
return 0;
} | 18.179104 | 51 | 0.458128 | takekoputa |
d3a842e859e219171b1bcb569201b3c2d7d36602 | 4,650 | cpp | C++ | benchmark/benchmark.cpp | tower120/SyncedChunkedArray | 8c91171d3718dc5cfae1392ea1ce24daa8542422 | [
"MIT"
] | 6 | 2017-10-25T15:38:39.000Z | 2021-02-19T13:53:14.000Z | benchmark/benchmark.cpp | tower120/SyncedChunkedArray | 8c91171d3718dc5cfae1392ea1ce24daa8542422 | [
"MIT"
] | 6 | 2017-10-19T18:37:19.000Z | 2017-10-25T14:34:19.000Z | benchmark/benchmark.cpp | tower120/SyncedChunkedArray | 8c91171d3718dc5cfae1392ea1ce24daa8542422 | [
"MIT"
] | null | null | null | // All in all, iteration speed should be 2x slower then vector, in worst case (for single threaded execution).
// gcc 7/clang 5 compiles to 1.25x-1.5x of vector speed
// * try different BigData size (by indcreasing payload)
// * try different threads_count
// * try different array size
// * try to use iterate_shared instead of iterate
// * try random erase. half-empty chunks could slighly affect performance.
// Very small chunks will be merged (see Synced::ChunkedArray::Chunk::merge_threshold).
#include <chrono>
#include <list>
#include <array>
#include <vector>
#include <iostream>
#include <cmath>
#include <thread>
#include <deque>
#include "../SyncedChunkedArray.h"
template<class time_unit = std::chrono::milliseconds, class Closure>
auto measure(Closure&& closure){
using namespace std::chrono;
high_resolution_clock::time_point t1 = high_resolution_clock::now();
closure();
high_resolution_clock::time_point t2 = high_resolution_clock::now();
return duration_cast<time_unit>( t2 - t1 ).count();
}
template<class time_unit = std::chrono::milliseconds, class Closure>
auto benchmark(int times, Closure&& closure){
return measure<time_unit>([&](){
for(int i=0;i<times;i++)
closure();
});
}
struct BigData {
long long value;
BigData(long long value)
:value(value)
{}
std::array<char, 1> payload;
};
void benchmark_iterate(int times) {
const int size = 10000;
static constexpr const int threads_count = 0;
SyncedChunkedArray<BigData> arr; // 512 for benchmark
std::vector<BigData> vec;
{
auto t = measure([&]() {
for (int i = 0; i < size; i++)
vec.emplace_back(i);
});
std::cout << "vec inserted in: " << t << std::endl;
}
{
auto t = measure([&]() {
for (int i = 0; i < size; i++)
arr.emplace(i);
});
std::cout << "arr inserted in: " << t << std::endl;
}
// random erase
{
const float erase_probability = 0; // 50 - worst case
const int break_point = std::round(RAND_MAX * erase_probability / 100.0);
auto t = measure([&]() {
std::size_t i = 0;
arr.iterate([&](auto &&iter) {
const int random_variable = std::rand();
if (random_variable < break_point) {
arr.erase(iter);
//vec.erase(vec.begin() + i);
vec.pop_back();
i--;
}
i++;
});
});
std::cout << "Erased in: " << t << std::endl;
}
auto benchmark_threaded_read = [&](auto times, auto&& closure) -> std::size_t {
std::array<std::thread, threads_count> threads;
std::atomic<std::size_t> total{0};
if (threads_count == 0){
return benchmark(times, [&]() {
closure();
});
}
for (int i = 0; i < threads_count; i++) {
threads[i] = std::thread([&](){
auto t = benchmark(times, [&]() {
closure();
});
total.fetch_add(t, std::memory_order_relaxed);
});
}
for (auto &thread : threads) thread.join();
return total.load();
};
{
std::atomic<std::size_t> sum{0};
std::atomic<std::size_t> iterate_count{0};
auto t = benchmark_threaded_read(times, [&]() {
std::size_t local_sum{0};
std::size_t local_iterate_count{0};
for(auto& i : vec) {
local_iterate_count++;
local_sum += i.value;
}
sum += local_sum;
iterate_count += local_iterate_count;
});
std::cout << "vec: " << t << " [" << sum << "] it: " << iterate_count << std::endl;
}
{
std::atomic<std::size_t> sum{0};
std::atomic<std::size_t> iterate_count{0};
auto t = benchmark_threaded_read(times, [&]() {
std::size_t local_sum{0};
std::size_t local_iterate_count{0};
// try iterate_shared also.
arr.iterate([&](const auto &i) {
local_iterate_count++;
local_sum += (*i).value;
});
sum += local_sum;
iterate_count += local_iterate_count;
});
std::cout << "ChunkedArray: " << t << " [" << sum << "] it: " << iterate_count << std::endl;
}
}
int main(){
std::cout << "-= iteration benchmark =-" << std::endl;
benchmark_iterate(1000);
} | 27.514793 | 110 | 0.527742 | tower120 |
d3ad0f2b413fd6afbbbe53d898fb62e4094ea5c4 | 22,566 | cc | C++ | training/const_reorder/constituent_reorder_model.cc | pks/cdec-dtrain-legacy | 8d900ca0af90dff71d68a7b596571df3e64c2101 | [
"Apache-2.0"
] | 114 | 2015-01-11T05:41:03.000Z | 2021-08-31T03:47:12.000Z | training/const_reorder/constituent_reorder_model.cc | pks/cdec-dtrain-legacy | 8d900ca0af90dff71d68a7b596571df3e64c2101 | [
"Apache-2.0"
] | 29 | 2015-01-09T01:00:09.000Z | 2019-09-25T06:04:02.000Z | training/const_reorder/constituent_reorder_model.cc | pks/cdec-dtrain-legacy | 8d900ca0af90dff71d68a7b596571df3e64c2101 | [
"Apache-2.0"
] | 50 | 2015-02-13T13:48:39.000Z | 2019-08-07T09:45:11.000Z | /*
* constituent_reorder_model.cc
*
* Created on: Jul 10, 2013
* Author: junhuili
*/
#include <string>
#include <unordered_map>
#include <boost/program_options.hpp>
#include "utils/filelib.h"
#include "trainer.h"
using namespace std;
using namespace const_reorder;
typedef std::unordered_map<std::string, int> Map;
typedef std::unordered_map<std::string, int>::iterator Iterator;
namespace po = boost::program_options;
inline void fnPreparingTrainingdata(const char* pszFName, int iCutoff,
const char* pszNewFName) {
Map hashPredicate;
{
ReadFile f(pszFName);
string line;
while (getline(*f.stream(), line)) {
if (!line.size()) continue;
vector<string> terms;
SplitOnWhitespace(line, &terms);
for (const auto& i : terms) {
++hashPredicate[i];
}
}
}
{
ReadFile in(pszFName);
WriteFile out(pszNewFName);
string line;
while (getline(*in.stream(), line)) {
if (!line.size()) continue;
vector<string> terms;
SplitOnWhitespace(line, &terms);
bool written = false;
for (const auto& i : terms) {
if (hashPredicate[i] >= iCutoff) {
(*out.stream()) << i << " ";
written = true;
}
}
if (written) {
(*out.stream()) << "\n";
}
}
}
}
struct SConstReorderTrainer {
SConstReorderTrainer(
const char* pszSynFname, // source-side flattened parse tree file name
const char* pszAlignFname, // alignment filename
const char* pszSourceFname, // source file name
const char* pszTargetFname, // target file name
const char* pszInstanceFname, // training instance file name
const char* pszModelPrefix, // classifier model file name prefix
int iCutoff, // feature count threshold
const char* /*pszOption*/ // other classifier parameters (for svmlight)
) {
fnGenerateInstanceFile(pszSynFname, pszAlignFname, pszSourceFname,
pszTargetFname, pszInstanceFname);
string strInstanceLeftFname = string(pszInstanceFname) + string(".left");
string strInstanceRightFname = string(pszInstanceFname) + string(".right");
string strModelLeftFname = string(pszModelPrefix) + string(".left");
string strModelRightFname = string(pszModelPrefix) + string(".right");
fprintf(stdout, "...Training the left ordering model\n");
fnTraining(strInstanceLeftFname.c_str(), strModelLeftFname.c_str(),
iCutoff);
fprintf(stdout, "...Training the right ordering model\n");
fnTraining(strInstanceRightFname.c_str(), strModelRightFname.c_str(),
iCutoff);
}
~SConstReorderTrainer() {}
private:
void fnTraining(const char* pszInstanceFname, const char* pszModelFname,
int iCutoff) {
char* pszNewInstanceFName = new char[strlen(pszInstanceFname) + 50];
if (iCutoff > 0) {
sprintf(pszNewInstanceFName, "%s.tmp", pszInstanceFname);
fnPreparingTrainingdata(pszInstanceFname, iCutoff, pszNewInstanceFName);
} else {
strcpy(pszNewInstanceFName, pszInstanceFname);
}
/*Zhangle_Maxent *pZhangleMaxent = new Zhangle_Maxent(NULL);
pZhangleMaxent->fnTrain(pszInstanceFname, "lbfgs", pszModelFname, 100, 2.0);
delete pZhangleMaxent;*/
Tsuruoka_Maxent_Trainer* pMaxent = new Tsuruoka_Maxent_Trainer;
pMaxent->fnTrain(pszNewInstanceFName, "l1", pszModelFname);
delete pMaxent;
if (strcmp(pszNewInstanceFName, pszInstanceFname) != 0) {
sprintf(pszNewInstanceFName, "rm %s.tmp", pszInstanceFname);
system(pszNewInstanceFName);
}
delete[] pszNewInstanceFName;
}
inline bool fnIsVerbPOS(const char* pszTerm) {
if (strcmp(pszTerm, "VV") == 0 || strcmp(pszTerm, "VA") == 0 ||
strcmp(pszTerm, "VC") == 0 || strcmp(pszTerm, "VE") == 0)
return true;
return false;
}
inline void fnGetOutcome(int iL1, int iR1, int iL2, int iR2,
const SAlignment* /*pAlign*/, string& strOutcome) {
if (iL1 == -1 && iL2 == -1)
strOutcome = "BU"; // 1. both are untranslated
else if (iL1 == -1)
strOutcome = "1U"; // 2. XP1 is untranslated
else if (iL2 == -1)
strOutcome = "2U"; // 3. XP2 is untranslated
else if (iL1 == iL2 && iR1 == iR2)
strOutcome = "SS"; // 4. Have same scope
else if (iL1 <= iL2 && iR1 >= iR2)
strOutcome = "1C2"; // 5. XP1's translation covers XP2's
else if (iL1 >= iL2 && iR1 <= iR2)
strOutcome = "2C1"; // 6. XP2's translation covers XP1's
else if (iR1 < iL2) {
int i = iR1 + 1;
/*while (i < iL2) {
if (pAlign->fnIsAligned(i, false))
break;
i++;
}*/
if (i == iL2)
strOutcome = "M"; // 7. Monotone
else
strOutcome = "DM"; // 8. Discontinuous monotone
} else if (iL1 < iL2 && iL2 <= iR1 && iR1 < iR2)
strOutcome = "OM"; // 9. Overlap monotone
else if (iR2 < iL1) {
int i = iR2 + 1;
/*while (i < iL1) {
if (pAlign->fnIsAligned(i, false))
break;
i++;
}*/
if (i == iL1)
strOutcome = "S"; // 10. Swap
else
strOutcome = "DS"; // 11. Discontinuous swap
} else if (iL2 < iL1 && iL1 <= iR2 && iR2 < iR1)
strOutcome = "OS"; // 12. Overlap swap
else
assert(false);
}
inline void fnGetOutcome(int i1, int i2, string& strOutcome) {
assert(i1 != i2);
if (i1 < i2) {
if (i2 > i1 + 1)
strOutcome = string("DM");
else
strOutcome = string("M");
} else {
if (i1 > i2 + 1)
strOutcome = string("DS");
else
strOutcome = string("S");
}
}
inline void fnGetRelativePosition(const vector<int>& vecLeft,
vector<int>& vecPosition) {
vecPosition.clear();
vector<float> vec;
for (size_t i = 0; i < vecLeft.size(); i++) {
if (vecLeft[i] == -1) {
if (i == 0)
vec.push_back(-1);
else
vec.push_back(vecLeft[i - 1] + 0.1);
} else
vec.push_back(vecLeft[i]);
}
for (size_t i = 0; i < vecLeft.size(); i++) {
int count = 0;
for (size_t j = 0; j < vecLeft.size(); j++) {
if (j == i) continue;
if (vec[j] < vec[i]) {
count++;
} else if (vec[j] == vec[i] && j < i) {
count++;
}
}
vecPosition.push_back(count);
}
}
/*
* features:
* f1: (left_label, right_label, parent_label)
* f2: (left_label, right_label, parent_label, other_right_sibling_label)
* f3: (left_label, right_label, parent_label, other_left_sibling_label)
* f4: (left_label, right_label, left_head_pos)
* f5: (left_label, right_label, left_head_word)
* f6: (left_label, right_label, right_head_pos)
* f7: (left_label, right_label, right_head_word)
* f8: (left_label, right_label, left_chunk_status)
* f9: (left_label, right_label, right_chunk_status)
* f10: (left_label, parent_label)
* f11: (right_label, parent_label)
*/
void fnGenerateInstance(const SParsedTree* pTree, const STreeItem* pParent,
int iPos, const vector<string>& vecChunkStatus,
const vector<int>& vecPosition,
const vector<string>& vecSTerms,
const vector<string>& /*vecTTerms*/, string& strOutcome,
ostringstream& ostr) {
STreeItem* pCon1, *pCon2;
pCon1 = pParent->m_vecChildren[iPos - 1];
pCon2 = pParent->m_vecChildren[iPos];
fnGetOutcome(vecPosition[iPos - 1], vecPosition[iPos], strOutcome);
string left_label = string(pCon1->m_pszTerm);
string right_label = string(pCon2->m_pszTerm);
string parent_label = string(pParent->m_pszTerm);
vector<string> vec_other_right_sibling;
for (int i = iPos + 1; i < pParent->m_vecChildren.size(); i++)
vec_other_right_sibling.push_back(
string(pParent->m_vecChildren[i]->m_pszTerm));
if (vec_other_right_sibling.size() == 0)
vec_other_right_sibling.push_back(string("NULL"));
vector<string> vec_other_left_sibling;
for (int i = 0; i < iPos - 1; i++)
vec_other_left_sibling.push_back(
string(pParent->m_vecChildren[i]->m_pszTerm));
if (vec_other_left_sibling.size() == 0)
vec_other_left_sibling.push_back(string("NULL"));
// generate features
// f1
ostr << "f1=" << left_label << "_" << right_label << "_" << parent_label;
// f2
for (int i = 0; i < vec_other_right_sibling.size(); i++)
ostr << " f2=" << left_label << "_" << right_label << "_" << parent_label
<< "_" << vec_other_right_sibling[i];
// f3
for (int i = 0; i < vec_other_left_sibling.size(); i++)
ostr << " f3=" << left_label << "_" << right_label << "_" << parent_label
<< "_" << vec_other_left_sibling[i];
// f4
ostr << " f4=" << left_label << "_" << right_label << "_"
<< pTree->m_vecTerminals[pCon1->m_iHeadWord]->m_ptParent->m_pszTerm;
// f5
ostr << " f5=" << left_label << "_" << right_label << "_"
<< vecSTerms[pCon1->m_iHeadWord];
// f6
ostr << " f6=" << left_label << "_" << right_label << "_"
<< pTree->m_vecTerminals[pCon2->m_iHeadWord]->m_ptParent->m_pszTerm;
// f7
ostr << " f7=" << left_label << "_" << right_label << "_"
<< vecSTerms[pCon2->m_iHeadWord];
// f8
ostr << " f8=" << left_label << "_" << right_label << "_"
<< vecChunkStatus[iPos - 1];
// f9
ostr << " f9=" << left_label << "_" << right_label << "_"
<< vecChunkStatus[iPos];
// f10
ostr << " f10=" << left_label << "_" << parent_label;
// f11
ostr << " f11=" << right_label << "_" << parent_label;
}
/*
* Source side (11 features):
* f1: the categories of XP1 and XP2 (f1_1, f1_2)
* f2: the head words of XP1 and XP2 (f2_1, f2_2)
* f3: the first and last word of XP1 (f3_f, f3_l)
* f4: the first and last word of XP2 (f4_f, f4_l)
* f5: is XP1 or XP2 the head node (f5_1, f5_2)
* f6: the category of the common parent
* Target side (6 features):
* f7: the first and the last word of XP1's translation (f7_f, f7_l)
* f8: the first and the last word of XP2's translation (f8_f, f8_l)
* f9: the translation of XP1's and XP2's head word (f9_1, f9_2)
*/
void fnGenerateInstance(const SParsedTree* /*pTree*/, const STreeItem* pParent,
const STreeItem* pCon1, const STreeItem* pCon2,
const SAlignment* pAlign,
const vector<string>& vecSTerms,
const vector<string>& /*vecTTerms*/, string& strOutcome,
ostringstream& ostr) {
int iLeft1, iRight1, iLeft2, iRight2;
pAlign->fnGetLeftRightMost(pCon1->m_iBegin, pCon1->m_iEnd, true, iLeft1,
iRight1);
pAlign->fnGetLeftRightMost(pCon2->m_iBegin, pCon2->m_iEnd, true, iLeft2,
iRight2);
fnGetOutcome(iLeft1, iRight1, iLeft2, iRight2, pAlign, strOutcome);
// generate features
// f1
ostr << "f1_1=" << pCon1->m_pszTerm << " f1_2=" << pCon2->m_pszTerm;
// f2
ostr << " f2_1=" << vecSTerms[pCon1->m_iHeadWord] << " f2_2"
<< vecSTerms[pCon2->m_iHeadWord];
// f3
ostr << " f3_f=" << vecSTerms[pCon1->m_iBegin]
<< " f3_l=" << vecSTerms[pCon1->m_iEnd];
// f4
ostr << " f4_f=" << vecSTerms[pCon2->m_iBegin]
<< " f4_l=" << vecSTerms[pCon2->m_iEnd];
// f5
if (pParent->m_iHeadChild == pCon1->m_iBrotherIndex)
ostr << " f5_1=1";
else
ostr << " f5_1=0";
if (pParent->m_iHeadChild == pCon2->m_iBrotherIndex)
ostr << " f5_2=1";
else
ostr << " f5_2=0";
// f6
ostr << " f6=" << pParent->m_pszTerm;
/*//f7
if (iLeft1 != -1) {
ostr << " f7_f=" << vecTTerms[iLeft1] << " f7_l=" <<
vecTTerms[iRight1];
}
if (iLeft2 != -1) {
ostr << " f8_f=" << vecTTerms[iLeft2] << " f8_l=" <<
vecTTerms[iRight2];
}
const vector<int>* pvecTarget =
pAlign->fnGetSingleWordAlign(pCon1->m_iHeadWord, true);
string str = "";
for (size_t i = 0; pvecTarget != NULL && i < pvecTarget->size(); i++) {
str += vecTTerms[(*pvecTarget)[i]] + "_";
}
if (str.length() > 0) {
ostr << " f9_1=" << str.substr(0, str.size()-1);
}
pvecTarget = pAlign->fnGetSingleWordAlign(pCon2->m_iHeadWord, true);
str = "";
for (size_t i = 0; pvecTarget != NULL && i < pvecTarget->size(); i++) {
str += vecTTerms[(*pvecTarget)[i]] + "_";
}
if (str.length() > 0) {
ostr << " f9_2=" << str.substr(0, str.size()-1);
} */
}
void fnGetFocusedParentNodes(const SParsedTree* pTree,
vector<STreeItem*>& vecFocused) {
for (size_t i = 0; i < pTree->m_vecTerminals.size(); i++) {
STreeItem* pParent = pTree->m_vecTerminals[i]->m_ptParent;
while (pParent != NULL) {
// if (pParent->m_vecChildren.size() > 1 && pParent->m_iEnd -
// pParent->m_iBegin > 5) {
if (pParent->m_vecChildren.size() > 1) {
// do constituent reordering for all children of pParent
vecFocused.push_back(pParent);
}
if (pParent->m_iBrotherIndex != 0) break;
pParent = pParent->m_ptParent;
}
}
}
void fnGenerateInstanceFile(
const char* pszSynFname, // source-side flattened parse tree file name
const char* pszAlignFname, // alignment filename
const char* pszSourceFname, // source file name
const char* pszTargetFname, // target file name
const char* pszInstanceFname // training instance file name
) {
SAlignmentReader* pAlignReader = new SAlignmentReader(pszAlignFname);
SParseReader* pParseReader = new SParseReader(pszSynFname, false);
ReadFile source_file(pszSourceFname);
ReadFile target_file(pszTargetFname);
string strInstanceLeftFname = string(pszInstanceFname) + string(".left");
string strInstanceRightFname = string(pszInstanceFname) + string(".right");
WriteFile left_file(strInstanceLeftFname);
WriteFile right_file(strInstanceRightFname);
// read sentence by sentence
SAlignment* pAlign;
SParsedTree* pTree;
string line;
int iSentNum = 0;
while ((pAlign = pAlignReader->fnReadNextAlignment()) != NULL) {
pTree = pParseReader->fnReadNextParseTree();
assert(getline(*source_file.stream(), line));
vector<string> vecSTerms;
SplitOnWhitespace(line, &vecSTerms);
assert(getline(*target_file.stream(), line));
vector<string> vecTTerms;
SplitOnWhitespace(line, &vecTTerms);
if (pTree != NULL) {
vector<STreeItem*> vecFocused;
fnGetFocusedParentNodes(pTree, vecFocused);
for (size_t i = 0; i < vecFocused.size(); i++) {
STreeItem* pParent = vecFocused[i];
vector<int> vecLeft, vecRight;
for (size_t j = 0; j < pParent->m_vecChildren.size(); j++) {
STreeItem* pCon1 = pParent->m_vecChildren[j];
int iLeft1, iRight1;
pAlign->fnGetLeftRightMost(pCon1->m_iBegin, pCon1->m_iEnd, true,
iLeft1, iRight1);
vecLeft.push_back(iLeft1);
vecRight.push_back(iRight1);
}
vector<int> vecLeftPosition;
fnGetRelativePosition(vecLeft, vecLeftPosition);
vector<int> vecRightPosition;
fnGetRelativePosition(vecRight, vecRightPosition);
vector<string> vecChunkStatus;
for (size_t j = 0; j < pParent->m_vecChildren.size(); j++) {
string strOutcome =
pAlign->fnIsContinuous(pParent->m_vecChildren[j]->m_iBegin,
pParent->m_vecChildren[j]->m_iEnd);
vecChunkStatus.push_back(strOutcome);
}
for (size_t j = 1; j < pParent->m_vecChildren.size(); j++) {
// children[j-1] vs. children[j] reordering
string strLeftOutcome;
ostringstream ostr;
fnGenerateInstance(pTree, pParent, j, vecChunkStatus,
vecLeftPosition, vecSTerms, vecTTerms,
strLeftOutcome, ostr);
string ostr_str = ostr.str();
// fprintf(stderr, "%s %s\n", ostr.str().c_str(),
// strLeftOutcome.c_str());
(*left_file.stream()) << ostr_str << " " << strLeftOutcome << "\n";
string strRightOutcome;
fnGetOutcome(vecRightPosition[j - 1], vecRightPosition[j],
strRightOutcome);
(*right_file.stream()) << ostr_str
<< " LeftOrder=" << strLeftOutcome << " "
<< strRightOutcome << "\n";
}
}
delete pTree;
}
delete pAlign;
iSentNum++;
if (iSentNum % 100000 == 0) fprintf(stderr, "#%d\n", iSentNum);
}
delete pAlignReader;
delete pParseReader;
}
void fnGenerateInstanceFile2(
const char* pszSynFname, // source-side flattened parse tree file name
const char* pszAlignFname, // alignment filename
const char* pszSourceFname, // source file name
const char* pszTargetFname, // target file name
const char* pszInstanceFname // training instance file name
) {
SAlignmentReader* pAlignReader = new SAlignmentReader(pszAlignFname);
SParseReader* pParseReader = new SParseReader(pszSynFname, false);
ReadFile source_file(pszSourceFname);
ReadFile target_file(pszTargetFname);
WriteFile output_file(pszInstanceFname);
// read sentence by sentence
SAlignment* pAlign;
SParsedTree* pTree;
string line;
int iSentNum = 0;
while ((pAlign = pAlignReader->fnReadNextAlignment()) != NULL) {
pTree = pParseReader->fnReadNextParseTree();
assert(getline(*source_file.stream(), line));
vector<string> vecSTerms;
SplitOnWhitespace(line, &vecSTerms);
assert(getline(*target_file.stream(), line));
vector<string> vecTTerms;
SplitOnWhitespace(line, &vecTTerms);
if (pTree != NULL) {
vector<STreeItem*> vecFocused;
fnGetFocusedParentNodes(pTree, vecFocused);
for (size_t i = 0;
i < vecFocused.size() && pTree->m_vecTerminals.size() > 10; i++) {
STreeItem* pParent = vecFocused[i];
for (size_t j = 1; j < pParent->m_vecChildren.size(); j++) {
// children[j-1] vs. children[j] reordering
string strOutcome;
ostringstream ostr;
fnGenerateInstance(pTree, pParent, pParent->m_vecChildren[j - 1],
pParent->m_vecChildren[j], pAlign, vecSTerms,
vecTTerms, strOutcome, ostr);
// fprintf(stderr, "%s %s\n", ostr.str().c_str(),
// strOutcome.c_str());
(*output_file.stream()) << ostr.str() << " " << strOutcome << "\n";
}
}
delete pTree;
}
delete pAlign;
iSentNum++;
if (iSentNum % 100000 == 0) fprintf(stderr, "#%d\n", iSentNum);
}
delete pAlignReader;
delete pParseReader;
}
};
inline void print_options(std::ostream& out,
po::options_description const& opts) {
typedef std::vector<boost::shared_ptr<po::option_description> > Ds;
Ds const& ds = opts.options();
out << '"';
for (unsigned i = 0; i < ds.size(); ++i) {
if (i) out << ' ';
out << "--" << ds[i]->long_name();
}
out << '\n';
}
inline string str(char const* name, po::variables_map const& conf) {
return conf[name].as<string>();
}
//--parse_file /scratch0/mt_exp/gq-ctb/data/train.srl.cn --align_file
/// scratch0/mt_exp/gq-ctb/data/aligned.grow-diag-final-and --source_file
/// scratch0/mt_exp/gq-ctb/data/train.cn --target_file
/// scratch0/mt_exp/gq-ctb/data/train.en --instance_file
/// scratch0/mt_exp/gq-ctb/data/srl-instance --model_prefix
/// scratch0/mt_exp/gq-ctb/data/srl-instance --feature_cutoff 10
int main(int argc, char** argv) {
po::options_description opts("Configuration options");
opts.add_options()("parse_file", po::value<string>(),
"parse file path (input)")(
"align_file", po::value<string>(), "Alignment file path (input)")(
"source_file", po::value<string>(), "Source text file path (input)")(
"target_file", po::value<string>(), "Target text file path (input)")(
"instance_file", po::value<string>(), "Instance file path (output)")(
"model_prefix", po::value<string>(),
"Model file path prefix (output): three files will be generated")(
"feature_cutoff", po::value<int>()->default_value(100),
"Feature cutoff threshold")("svm_option", po::value<string>(),
"Parameters for SVMLight classifier")(
"help", "produce help message");
po::variables_map vm;
if (argc) {
po::store(po::parse_command_line(argc, argv, opts), vm);
po::notify(vm);
}
if (vm.count("help")) {
print_options(cout, opts);
return 1;
}
if (!vm.count("parse_file") || !vm.count("align_file") ||
!vm.count("source_file") || !vm.count("target_file") ||
!vm.count("instance_file") || !vm.count("model_prefix")) {
print_options(cout, opts);
if (!vm.count("parse_file")) cout << "--parse_file NOT FOUND\n";
if (!vm.count("align_file")) cout << "--align_file NOT FOUND\n";
if (!vm.count("source_file")) cout << "--source_file NOT FOUND\n";
if (!vm.count("target_file")) cout << "--target_file NOT FOUND\n";
if (!vm.count("instance_file")) cout << "--instance_file NOT FOUND\n";
if (!vm.count("model_prefix")) cout << "--model_prefix NOT FOUND\n";
exit(0);
}
const char* pOption;
if (vm.count("svm_option"))
pOption = str("svm_option", vm).c_str();
else
pOption = NULL;
SConstReorderTrainer* pTrainer = new SConstReorderTrainer(
str("parse_file", vm).c_str(), str("align_file", vm).c_str(),
str("source_file", vm).c_str(), str("target_file", vm).c_str(),
str("instance_file", vm).c_str(), str("model_prefix", vm).c_str(),
vm["feature_cutoff"].as<int>(), pOption);
delete pTrainer;
return 0;
}
| 35.425432 | 82 | 0.585837 | pks |
d3bbf760d89b4294e96c42774735be6701863276 | 6,659 | cpp | C++ | examples/BasicTypes/main.cpp | think-cell/tcjs | 8a0e2d00b1ed68b611734964ad2563092a7a80e4 | [
"Apache-2.0"
] | 15 | 2020-01-10T21:57:23.000Z | 2021-10-06T12:03:52.000Z | examples/BasicTypes/main.cpp | think-cell/tcjs | 8a0e2d00b1ed68b611734964ad2563092a7a80e4 | [
"Apache-2.0"
] | 18 | 2020-05-25T13:00:29.000Z | 2021-10-05T13:01:34.000Z | examples/BasicTypes/main.cpp | think-cell/tcjs | 8a0e2d00b1ed68b611734964ad2563092a7a80e4 | [
"Apache-2.0"
] | 2 | 2020-10-06T00:58:53.000Z | 2021-01-28T03:14:01.000Z | #include <emscripten/val.h>
#include <type_traits>
#include "explicit_cast.h"
#include "range.h"
#include "assert_defs.h"
#include "js_types.h"
#include "js_ref.h"
namespace js = tc::js;
namespace jst = tc::jst;
int main() {
// any
{
static_assert(std::is_convertible<double, js::any>::value);
static_assert(std::is_convertible<bool, js::any>::value);
static_assert(std::is_convertible<js::string, js::any>::value);
static_assert(std::is_convertible<js::null, js::any>::value);
static_assert(std::is_convertible<js::undefined, js::any>::value);
static_assert(!std::is_convertible<std::string, js::any>::value);
static_assert(!std::is_convertible<char, js::any>::value);
static_assert(!std::is_convertible<float, js::any>::value);
static_assert(!std::is_convertible<int, js::any>::value);
// Explicit casting to supported types only, no implicit conversion
static_assert(tc::is_explicit_castable<bool, js::any>::value); // any -> bool conversion checks at runtime that any stores a bool, no JS truthiness
static_assert(tc::is_explicit_castable<double, js::any>::value);
static_assert(tc::is_explicit_castable<js::null, js::any>::value);
static_assert(tc::is_explicit_castable<js::undefined, js::any>::value);
static_assert(tc::is_explicit_castable<js::string, js::any>::value);
static_assert(!std::is_convertible<js::any, bool>::value);
static_assert(!std::is_convertible<js::any, double>::value);
static_assert(!std::is_convertible<js::any, js::null>::value);
static_assert(!std::is_convertible<js::any, js::undefined>::value);
static_assert(!std::is_convertible<js::any, js::string>::value);
static_assert(!tc::is_explicit_castable<int, js::any>::value);
static_assert(!std::is_convertible<js::any, int>::value);
}
{
// Emscripten supports reading an int from a double, so we support doubles only, like JS
emscripten::val const x(1.23);
_ASSERTEQUAL(x.as<int>(), 1);
// We also do not expose the JS semantics to conversion-to-bool
_ASSERT(x.as<bool>());
emscripten::val const y(0);
_ASSERT(!y.as<bool>());
emscripten::val const z(std::string("Hello"));
_ASSERT(z.as<bool>());
emscripten::val const v(std::string(""));
_ASSERT(!v.as<bool>());
}
{
js::any a = true;
js::any b = false;
_ASSERT(tc::explicit_cast<bool>(a) && !tc::explicit_cast<bool>(b));
}
// string
{
// Constructible from anything we can create a std::string from
static_assert(std::is_constructible<js::string, char const*>::value);
static_assert(std::is_constructible<js::string, std::string>::value);
static_assert(!std::is_constructible<js::string, double>::value);
static_assert(!std::is_constructible<js::string, int>::value);
// Implicit conversion string -> any
static_assert(std::is_convertible<js::string, js::any>::value);
static_assert(!std::is_convertible<js::any, js::string>::value);
// Explicit conversion any -> string
static_assert(tc::is_explicit_castable<js::string, js::any>::value);
// Neither implicit nor explicit conversion to bool. No JS truthiness of strings.
static_assert(!std::is_convertible<js::string, bool>::value);
static_assert(!tc::is_explicit_castable<bool, js::string>::value);
js::string message("Hello World");
_ASSERTEQUAL(message.length(), 11);
_ASSERTEQUAL(tc::explicit_cast<std::string>(message), "Hello World");
// Implicit base-cast.
js::any anyMessage = message;
_ASSERTEQUAL(message.length(), 11);
_ASSERT(message.getEmval().strictlyEquals(anyMessage.getEmval()));
anyMessage = message;
_ASSERTEQUAL(message.length(), 11);
_ASSERT(message.getEmval().strictlyEquals(anyMessage.getEmval()));
// Explicit derived-cast.
js::string const message2(anyMessage);
_ASSERT(message.getEmval().strictlyEquals(message2.getEmval()));
}
{
auto const message = jst::make_string("Hello", tc::as_dec(10), "world");
static_assert(std::is_same<const js::string, decltype(message)>::value);
_ASSERTEQUAL(message.length(), 12);
_ASSERTEQUAL(tc::explicit_cast<std::string>(message), "Hello10world");
}
{
emscripten::val const emval{js::undefined{}};
_ASSERTE(emval.isUndefined());
js::undefined{emval};
}
{
emscripten::val const emval{js::null{}};
_ASSERTE(emval.isNull());
js::null{emval};
}
// optional
{
static_assert(
std::is_same<
typename emscripten::internal::BindingType<jst::optional<js::string>>::WireType,
typename emscripten::internal::BindingType<emscripten::val>::WireType
>::value
);
{
jst::optional<js::string> ostr;
_ASSERT(ostr.getEmval().isUndefined());
_ASSERT(!ostr);
_ASSERT(!ostr.getEmval().template as<jst::optional<js::string>>());
}
{
js::string const str("Hello World");
emscripten::val emval{jst::optional<js::string>(str)};
_ASSERT(!emval.isUndefined());
auto const ostrReturned = emval.template as<jst::optional<js::string>>();
_ASSERT(ostrReturned);
_ASSERT(ostrReturned.getEmval().strictlyEquals(emval));
_ASSERT(ostrReturned.getEmval().strictlyEquals(str.getEmval()));
}
{
jst::optional<js::string> ostr;
emscripten::val const emval(ostr);
_ASSERT(!emval.template as<jst::optional<js::string>>());
_ASSERT(emval.isUndefined());
}
{
jst::optional<js::string> ostr;
_ASSERT(!ostr);
jst::optional<js::string> ostr2(tc::aggregate_tag, "Hello World");
_ASSERT(ostr2);
_ASSERTEQUAL(ostr2->length(), 11);
jst::optional<js::string> ostr3(tc::aggregate_tag, "");
_ASSERT(ostr3);
}
}
{
// Test optional of double.
{
jst::optional<double> const iValue;
emscripten::val const emval(iValue);
_ASSERT(emval.isUndefined());
_ASSERT(!emval.isNumber());
}
{
jst::optional<double> const iValue(123.5);
emscripten::val const emval(iValue);
_ASSERT(!emval.isUndefined());
_ASSERT(emval.isNumber());
_ASSERT(123.5 == emval.as<double>());
}
}
// ref
{
struct ISomeObject : virtual jst::object_base {
struct _tcjs_definitions { // Optional
using Foo = int;
};
auto foo() noexcept {
return _call<js::string>("foo");
}
auto operator()(double) noexcept {
return _call_this<void>();
}
auto operator()(js::string) noexcept {
return _call_this<double>();
}
};
using SomeObject = jst::ref<ISomeObject>;
static_assert(std::is_same<int, SomeObject::Foo>::value);
static_assert(std::is_same<js::string, decltype(std::declval<SomeObject>()->foo())>::value);
static_assert(std::is_same<void, decltype(std::declval<SomeObject>()(10.0))>::value);
static_assert(std::is_same<double, decltype(std::declval<SomeObject>()(js::string("hi")))>::value);
}
return 0;
}
| 31.861244 | 149 | 0.689143 | think-cell |
d3c3d0ec9755772b888ee624908261ca771612f1 | 170 | hpp | C++ | src/KEngineTools/ProjectRainPacker/Logic/ResourceManufacturer.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2019-04-09T13:03:11.000Z | 2021-01-27T04:58:29.000Z | src/KEngineTools/ProjectRainPacker/Logic/ResourceManufacturer.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 2 | 2017-02-06T03:48:45.000Z | 2020-08-31T01:30:10.000Z | src/KEngineTools/ProjectRainPacker/Logic/ResourceManufacturer.hpp | yxbh/Project-Forecast | 8ea2f6249a38c9e7f4d6d7d1e51e11ad0b05c2c4 | [
"BSD-3-Clause"
] | 4 | 2020-06-28T08:19:53.000Z | 2020-06-28T16:30:19.000Z | #pragma once
#include "KEngine/Interfaces/IResource.hpp"
#include <QString>
class ResourceManufacturer
{
public:
ke::ResourceSptr create(QString resourceType);
};
| 14.166667 | 50 | 0.764706 | yxbh |
d3c4f0562840e4836b7c50c7567e2610a8d81c7c | 461 | cpp | C++ | MT Game Engine/Source/Rendering/Texture/SkyboxTextureContainer.cpp | MatthewATaylor/MT-Game-Engine | bad800163a2ae5476fbe7d08a8c245e6a563c4fb | [
"MIT"
] | 3 | 2019-10-08T20:58:43.000Z | 2020-10-17T15:59:01.000Z | MT Game Engine/Source/Rendering/Texture/SkyboxTextureContainer.cpp | MatthewATaylor/MT-Game-Engine | bad800163a2ae5476fbe7d08a8c245e6a563c4fb | [
"MIT"
] | null | null | null | MT Game Engine/Source/Rendering/Texture/SkyboxTextureContainer.cpp | MatthewATaylor/MT-Game-Engine | bad800163a2ae5476fbe7d08a8c245e6a563c4fb | [
"MIT"
] | null | null | null | #include "Rendering/Texture/SkyboxTextureContainer.h"
namespace mtge {
//Constructor
SkyboxTextureContainer::SkyboxTextureContainer(
std::string frontTexFile,
std::string backTexFile,
std::string upTexFile,
std::string downTexFile,
std::string rightTexFile,
std::string leftTexFile) {
files[0] = frontTexFile;
files[1] = backTexFile;
files[2] = upTexFile;
files[3] = downTexFile;
files[4] = rightTexFile;
files[5] = leftTexFile;
}
} | 23.05 | 53 | 0.72885 | MatthewATaylor |
d3c601726c706e9e04d61c7743f918abb32c3a3d | 600 | cpp | C++ | test/delete_duplicates_unittest.cpp | Rokugatsu/leetcode | f868c494a9d23ac6519c94374281781f209fb19c | [
"MIT"
] | null | null | null | test/delete_duplicates_unittest.cpp | Rokugatsu/leetcode | f868c494a9d23ac6519c94374281781f209fb19c | [
"MIT"
] | null | null | null | test/delete_duplicates_unittest.cpp | Rokugatsu/leetcode | f868c494a9d23ac6519c94374281781f209fb19c | [
"MIT"
] | null | null | null | /**
* @file delete_duplicates_unittest.cpp
* @author lipingan (lipingan.dev@outlook.com)
* @brief
* @version 0.1
* @date 2022-01-09
*
* @copyright Copyright (c) 2022
*
*/
#include "delete_duplicates.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace leetcode {
TEST(delete_duplicates, case_0) {
std::vector<int> vector{1, 1, 1, 1, 1, 1, 1, 1, 2, 3, 4, 4, 4, 4, 4, 5, 5,
5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 9, 9};
ListNode *head = spawnList(vector);
printList(head);
deleteDuplicates(head);
printList(head);
}
} // namespace leetcode
| 21.428571 | 76 | 0.605 | Rokugatsu |
d3ca0d276e40a2f729175da04f5ea84de19e0db0 | 3,379 | cpp | C++ | src/WtMsgQue/MQServer.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | null | null | null | src/WtMsgQue/MQServer.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | 1 | 2022-03-21T06:51:59.000Z | 2022-03-21T06:51:59.000Z | src/WtMsgQue/MQServer.cpp | v1otusc/wondertrader | fd65a052d26be32882f89e8e9dfcd1d7b8736a3b | [
"MIT"
] | null | null | null | /*!
* \file EventCaster.cpp
* \project WonderTrader
*
* \author Wesley
* \date 2020/03/30
*
* \brief
*/
#include "MQServer.h"
#include "MQManager.h"
#include "../Share/StrUtil.hpp"
#include <spdlog/fmt/fmt.h>
#include <atomic>
#ifndef NN_STATIC_LIB
#define NN_STATIC_LIB
#endif
#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>
USING_NS_WTP;
inline uint32_t makeMQSvrId()
{
static std::atomic<uint32_t> _auto_server_id{ 1001 };
return _auto_server_id.fetch_add(1);
}
MQServer::MQServer(MQManager* mgr)
: _sock(-1)
, _ready(false)
, _mgr(mgr)
, _confirm(false)
, m_bTerminated(false)
{
_id = makeMQSvrId();
}
MQServer::~MQServer()
{
if (!_ready)
return;
m_bTerminated = true;
m_condCast.notify_all();
if (m_thrdCast)
m_thrdCast->join();
//if (_sock >= 0)
// nn_close(_sock);
}
bool MQServer::init(const char* url, bool confirm /* = false */)
{
if (_sock >= 0)
return true;
_confirm = confirm;
_sock = nn_socket(AF_SP, NN_PUB);
if(_sock < 0)
{
_mgr->log_server(_id, fmt::format("MQServer {} has an error {} while initializing", _id, _sock).c_str());
return false;
}
int bufsize = 8 * 1024 * 1024;
nn_setsockopt(_sock, NN_SOL_SOCKET, NN_SNDBUF, &bufsize, sizeof(bufsize));
_url = url;
if(nn_bind(_sock, url) < 0)
{
_mgr->log_server(_id, fmt::format("MQServer {} has an error while binding url {}", _id, url).c_str());
return false;
}
else
{
_mgr->log_server(_id, fmt::format("MQServer {} has binded to {} ", _id, url).c_str());
}
_ready = true;
_mgr->log_server(_id, fmt::format("MQServer {} ready", _id).c_str());
return true;
}
void MQServer::publish(const char* topic, const void* data, uint32_t dataLen)
{
if(_sock < 0)
{
_mgr->log_server(_id, fmt::format("MQServer {} has not been initialized yet", _id).c_str());
return;
}
if(data == NULL || dataLen == 0 || m_bTerminated)
return;
{
StdUniqueLock lock(m_mtxCast);
m_dataQue.push(PubData(topic, data, dataLen));
}
if(m_thrdCast == NULL)
{
m_thrdCast.reset(new StdThread([this](){
if (m_sendBuf.empty())
m_sendBuf.resize(1024 * 1024, 0);
while (!m_bTerminated)
{
int cnt = (int)nn_get_statistic(_sock, NN_STAT_CURRENT_CONNECTIONS);
if(m_dataQue.empty() || (cnt == 0 && _confirm))
{
StdUniqueLock lock(m_mtxCast);
m_condCast.wait(lock);
continue;
}
PubDataQue tmpQue;
{
StdUniqueLock lock(m_mtxCast);
tmpQue.swap(m_dataQue);
}
while(!tmpQue.empty())
{
const PubData& pubData = tmpQue.front();
if (!pubData._data.empty())
{
std::size_t len = sizeof(MQPacket) + pubData._data.size();
if (m_sendBuf.size() < len)
m_sendBuf.resize(m_sendBuf.size() * 2);
MQPacket* pack = (MQPacket*)m_sendBuf.data();
strncpy(pack->_topic, pubData._topic.c_str(), 32);
pack->_length = pubData._data.size();
memcpy(&pack->_data, pubData._data.data(), pubData._data.size());
int bytes_snd = 0;
for(;;)
{
int bytes = nn_send(_sock, m_sendBuf.data() + bytes_snd, len - bytes_snd, 0);
if (bytes >= 0)
{
bytes_snd += bytes;
if(bytes_snd == len)
break;
}
else
std::this_thread::sleep_for(std::chrono::milliseconds(1));
}
}
tmpQue.pop();
}
}
}));
}
else
{
m_condCast.notify_all();
}
} | 19.994083 | 107 | 0.620894 | v1otusc |
d3cd573f675089f989061cdcde656282d96f18d5 | 400 | hh | C++ | src/main-window.hh | lIlIIV/QtModelView | 1e596e32677a1281b8b95b889174724a40e7cacb | [
"MIT"
] | null | null | null | src/main-window.hh | lIlIIV/QtModelView | 1e596e32677a1281b8b95b889174724a40e7cacb | [
"MIT"
] | null | null | null | src/main-window.hh | lIlIIV/QtModelView | 1e596e32677a1281b8b95b889174724a40e7cacb | [
"MIT"
] | null | null | null | #ifndef MAIN_WINDOW
#define MAIN_WINDOW
#include <QDockWidget>
#include <QListView>
#include <QMainWindow>
#include <QVBoxLayout>
#include "my-delegate.hh"
#include "my-model.hh"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow();
~MainWindow();
private:
QListView * list_view;
MyModel * my_model;
MyDelegate * my_delegate;
};
#endif // MAIN_WINDOW
| 13.793103 | 37 | 0.705 | lIlIIV |
d3d374022596a4eed8ff242a30224a47f2950c30 | 1,870 | cpp | C++ | rpc_examples/RpcServer.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | 1 | 2020-05-22T08:47:00.000Z | 2020-05-22T08:47:00.000Z | rpc_examples/RpcServer.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | rpc_examples/RpcServer.cpp | cd606/tm_examples | 5ea8e9774f5070fbcc073c71c39bcb7febef88a7 | [
"Apache-2.0"
] | null | null | null | #include <tm_kit/infra/Environments.hpp>
#include <tm_kit/infra/DeclarativeGraph.hpp>
#include <tm_kit/infra/TerminationController.hpp>
#include <tm_kit/infra/RealTimeApp.hpp>
#include <tm_kit/basic/SpdLoggingComponent.hpp>
#include <tm_kit/basic/real_time_clock/ClockComponent.hpp>
#include <tm_kit/basic/SerializationHelperMacros.hpp>
#include <tm_kit/transport/CrossGuidComponent.hpp>
#include <tm_kit/transport/MultiTransportFacilityWrapper.hpp>
#include "RpcServer.hpp"
using namespace dev::cd606::tm;
using Environment = infra::Environment<
infra::CheckTimeComponent<true>,
infra::TrivialExitControlComponent,
basic::TimeComponentEnhancedWithSpdLogging<basic::real_time_clock::ClockComponent>,
transport::CrossGuidComponent,
transport::AllNetworkTransportComponents
>;
using M = infra::RealTimeApp<Environment>;
using R = infra::AppRunner<M>;
int main() {
Environment env;
R r(&env);
using FacilityCreator = R::OnOrderFacilityPtr<rpc_examples::Input,rpc_examples::Output> (*)();
std::vector<std::tuple<
FacilityCreator,std::string
>> specs {
{&rpc_examples::simpleFacility<R>, "simple"}
, {&rpc_examples::clientStreamFacility<R>, "client_stream"}
, {&rpc_examples::serverStreamFacility<R>, "server_stream"}
, {&rpc_examples::bothStreamFacility<R>, "both_stream"}
};
for (auto const &spec : specs) {
auto f = std::get<0>(spec)();
infra::DeclarativeGraph<R>("", {
{std::get<1>(spec), f}
})(r);
transport::MultiTransportFacilityWrapper<R>::wrap<rpc_examples::Input,rpc_examples::Output>(
r
, f
, "redis://127.0.0.1:6379:::rpc_example_"+std::get<1>(spec)
, std::get<1>(spec)+"_wrapper"
);
}
r.finalize();
infra::terminationController(infra::RunForever {});
} | 33.392857 | 100 | 0.682353 | cd606 |
d3d5bdd5ebd956cb59a3af50480b511202e52f93 | 6,814 | cc | C++ | runtime/ops/indexing.cc | ir5/chainer-compiler | c6d9b9ba3175931321c1e512c17642a613c03bfc | [
"MIT"
] | null | null | null | runtime/ops/indexing.cc | ir5/chainer-compiler | c6d9b9ba3175931321c1e512c17642a613c03bfc | [
"MIT"
] | null | null | null | runtime/ops/indexing.cc | ir5/chainer-compiler | c6d9b9ba3175931321c1e512c17642a613c03bfc | [
"MIT"
] | null | null | null | #include <chainerx/routines/creation.h>
#include <chainerx/routines/indexing.h>
#include <chainerx/routines/manipulation.h>
#include <common/log.h>
#include <runtime/chainerx_util.h>
#include <runtime/gen_chxvm_ops.h>
namespace chainer_compiler {
namespace runtime {
chainerx::Array SliceOp::RunImpl(ChxVMState* st, const chainerx::Array& data) {
std::vector<chainerx::ArrayIndex> indices(data.ndim(), chainerx::Slice());
for (size_t i = 0; i < axes.size(); ++i) {
int64_t axis = axes[i];
int64_t start = starts[i];
int64_t end = ends[i];
indices[axis] = chainerx::Slice(start, end, 1);
}
return data.At(indices);
}
namespace {
std::vector<chainerx::ArrayIndex> GetIndicesForDynamicSlice(
const chainerx::Array& data,
const chainerx::Array& starts,
const chainerx::Array& ends,
const absl::optional<chainerx::Array>& axes,
const absl::optional<chainerx::Array>& steps) {
CHECK_EQ(1, starts.ndim());
CHECK_EQ(1, ends.ndim());
std::vector<chainerx::ArrayIndex> indices(data.ndim(), chainerx::Slice());
for (int64_t i = 0; i < starts.shape()[0]; ++i) {
int64_t axis = axes.has_value() ? int64_t(chainerx::AsScalar(axes->At({i}))) : i;
int64_t start = int64_t(chainerx::AsScalar(starts.At({i})));
int64_t end = int64_t(chainerx::AsScalar(ends.At({i})));
int64_t step = steps.has_value() ? int64_t(chainerx::AsScalar(steps->At({i}))) : 1;
indices[axis] = chainerx::Slice(start, end, step);
}
return indices;
}
} // namespace
chainerx::Array DynamicSliceOp::RunImpl(
ChxVMState* st,
const chainerx::Array& data,
const chainerx::Array& starts,
const chainerx::Array& ends,
const absl::optional<chainerx::Array>& axes,
const absl::optional<chainerx::Array>& steps) {
std::vector<chainerx::ArrayIndex> indices = GetIndicesForDynamicSlice(data, starts, ends, axes, steps);
return data.At(indices);
}
chainerx::Array DynamicSliceGradOp::RunImpl(
ChxVMState* st,
const chainerx::Array& gy,
const chainerx::Shape& shape,
const chainerx::Array& starts,
const chainerx::Array& ends,
const absl::optional<chainerx::Array>& axes,
const absl::optional<chainerx::Array>& steps) {
chainerx::Array out = chainerx::Zeros(shape, gy.dtype());
std::vector<chainerx::ArrayIndex> indices = GetIndicesForDynamicSlice(out, starts, ends, axes, steps);
BlitArray(gy, out.At(indices));
return out;
}
namespace {
std::vector<chainerx::ArrayIndex> GetIndicesForGetItem(
const std::vector<chainerx::Array>& index_arrays, const Int64StackVector& slice_specs) {
std::vector<chainerx::ArrayIndex> indices;
size_t i = 0;
for (int slice_spec : slice_specs) {
switch (slice_spec) {
case 0:
indices.emplace_back(chainerx::Slice());
break;
case 1: {
int64_t index = int64_t(chainerx::AsScalar(index_arrays[i++]));
indices.emplace_back(index);
break;
}
case 2: {
int64_t start = int64_t(chainerx::AsScalar(index_arrays[i++]));
int64_t stop = int64_t(chainerx::AsScalar(index_arrays[i++]));
indices.emplace_back(chainerx::Slice(start, stop));
break;
}
case 3: {
int64_t start = int64_t(chainerx::AsScalar(index_arrays[i++]));
int64_t stop = int64_t(chainerx::AsScalar(index_arrays[i++]));
int64_t step = int64_t(chainerx::AsScalar(index_arrays[i++]));
indices.emplace_back(chainerx::Slice(start, stop, step));
break;
}
case 4:
CHECK(false) << "Not implemented";
break;
}
}
CHECK_EQ(i, index_arrays.size());
return indices;
}
} // namespace
chainerx::Array GetItemOp::RunImpl(ChxVMState* st, const chainerx::Array& data, const std::vector<chainerx::Array>& index_arrays) {
std::vector<chainerx::ArrayIndex> indices = GetIndicesForGetItem(index_arrays, slice_specs);
return data.At(indices);
}
chainerx::Array GetItemGradOp::RunImpl(
ChxVMState* st, const chainerx::Array& gy, const chainerx::Shape& shape, const std::vector<chainerx::Array>& index_arrays) {
chainerx::Array out = chainerx::Zeros(shape, gy.dtype());
std::vector<chainerx::ArrayIndex> indices = GetIndicesForGetItem(index_arrays, slice_specs);
BlitArray(gy, out.At(indices));
return out;
}
chainerx::Array GatherOp::RunImpl(ChxVMState* st, const chainerx::Array& data, const chainerx::Array& indices) {
return data.Take(indices, axis);
}
chainerx::Array GatherGradOp::RunImpl(
ChxVMState* st, const chainerx::Array& gy, const chainerx::Array& indices, const chainerx::Shape& shape) {
chainerx::Array out = chainerx::Zeros(shape, gy.dtype());
// TODO(hamaji): Ineffcient. Update the TODO is removed in ChainerX:
// https://github.com/chainer/chainer/pull/6789
return chainerx::AddAt(out, indices, axis, gy);
}
chainerx::Array SelectItemOp::RunImpl(ChxVMState* st, const chainerx::Array& data, const chainerx::Array& indices) {
CHECK_EQ(2UL, data.shape().size()) << "TODO(hamaji): Support SelectItem for non-2D array";
int64_t batch_size = data.shape()[0];
int64_t num_classes = data.shape()[1];
int64_t total_size = batch_size * num_classes;
chainerx::Array take_indices =
(indices + chainerx::Arange(0, total_size, num_classes, indices.dtype(), indices.device())).ToDevice(data.device());
return data.Reshape({total_size}).Take(take_indices, 0);
}
chainerx::Array SelectItemGradOp::RunImpl(
ChxVMState* st, const chainerx::Array& gy, const chainerx::Array& indices, const chainerx::Shape& shape) {
CHECK_EQ(2, shape.size()) << "TODO(hamaji): Support SelectItem for non-2D array";
int64_t batch_size = shape[0];
int64_t num_classes = shape[1];
int64_t total_size = batch_size * num_classes;
chainerx::Array out = chainerx::Zeros({total_size}, gy.dtype());
chainerx::Array take_indices =
(indices + chainerx::Arange(0, total_size, num_classes, indices.dtype(), indices.device())).ToDevice(out.device());
// TODO(hamaji): Ineffcient. Update the TODO is removed in ChainerX:
// https://github.com/chainer/chainer/pull/6789
out = chainerx::AddAt(out, take_indices, 0, gy);
return out.Reshape(shape);
}
chainerx::Array WhereOp::RunImpl(ChxVMState* st, chainerx::Array const& condition, chainerx::Array const& x, chainerx::Array const& y) {
return chainerx::Where(condition, x, y);
}
} // namespace runtime
} // namespace chainer_compiler
| 40.802395 | 136 | 0.649692 | ir5 |
d3d726dc30da3c85b6453af936412bfeaad158e9 | 1,542 | hpp | C++ | src/net/SessionBase.hpp | lineCode/webrtc-datachannels | 0f814632361c829c3aff1764cb662bd6290d54d9 | [
"Apache-2.0"
] | 1 | 2020-11-05T21:48:16.000Z | 2020-11-05T21:48:16.000Z | src/net/SessionBase.hpp | lineCode/webrtc-datachannels | 0f814632361c829c3aff1764cb662bd6290d54d9 | [
"Apache-2.0"
] | null | null | null | src/net/SessionBase.hpp | lineCode/webrtc-datachannels | 0f814632361c829c3aff1764cb662bd6290d54d9 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "log/Logger.hpp"
#include <boost/asio.hpp>
#include <functional>
#include <memory>
#include <thread>
#include <vector>
namespace gloer {
namespace config {
struct ServerConfig;
} // namespace config
} // namespace gloer
namespace gloer {
namespace algo {
class DispatchQueue;
} // namespace algo
} // namespace gloer
namespace gloer {
namespace net {
namespace wrtc {
class WRTCServer;
class WRTCSession;
} // namespace wrtc
} // namespace net
} // namespace gloer
namespace gloer {
namespace net {
template<typename session_type>
class SessionBase {
public:
typedef std::function<void(const session_type& sessId, const std::string& message)>
on_message_callback;
typedef std::function<void(const session_type& sessId)> on_close_callback;
typedef uint32_t metadata_key;
SessionBase(const session_type& id) : id_(id) {}
virtual ~SessionBase() {}
virtual void send(const std::string& ss) = 0;
virtual session_type getId() const { return id_; }
virtual bool isExpired() const = 0;
// virtual void setExpiredCallback(); // TODO
virtual void SetOnMessageHandler(on_message_callback handler) { onMessageCallback_ = handler; }
virtual void SetOnCloseHandler(on_close_callback handler) { onCloseCallback_ = handler; }
protected:
const session_type id_;
//std::map<metadata_key, std::unique_ptr<MetaData>> metadata_;
on_message_callback onMessageCallback_;
on_close_callback onCloseCallback_;
const size_t MAX_ID_LEN = 2048;
};
} // namespace net
} // namespace gloer
| 20.837838 | 97 | 0.743839 | lineCode |
d3d7a2e5537b4cff36c1b64a2ad310843bb3cd79 | 2,479 | cpp | C++ | bsp/BSPBalanceSplitSelector.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 3 | 2019-04-20T10:16:36.000Z | 2021-03-21T19:51:38.000Z | bsp/BSPBalanceSplitSelector.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | null | null | null | bsp/BSPBalanceSplitSelector.cpp | Andrewich/deadjustice | 48bea56598e79a1a10866ad41aa3517bf7d7c724 | [
"BSD-3-Clause"
] | 2 | 2020-04-18T20:04:24.000Z | 2021-09-19T05:07:41.000Z | #include "BSPBalanceSplitSelector.h"
#include "BSPPolygon.h"
#include "BSPNode.h"
#include "ProgressIndicator.h"
#include <lang/Math.h>
#include <math/Vector4.h>
#include <assert.h>
#include "config.h"
//-----------------------------------------------------------------------------
using namespace lang;
using namespace math;
//-----------------------------------------------------------------------------
namespace bsp
{
BSPBalanceSplitSelector::BSPBalanceSplitSelector( int polySkip ) :
m_polySkip( polySkip )
{
if ( m_polySkip < 0 )
m_polySkip = 0;
}
double BSPBalanceSplitSelector::guessWork( int polygons ) const
{
double depthGuess = (int)( Math::log((float)polygons) / Math::log(2.f) );
if ( depthGuess < 1 )
depthGuess = 1;
double workTotal = (double)(polygons/2+1) * (double)(polygons/2+1) * depthGuess / 1.5;
return workTotal / (m_polySkip+1);
}
bool BSPBalanceSplitSelector::getSplitPlane( const util::Vector<BSPPolygon*>& polys,
ProgressIndicator* progress, Vector4* splitPlane ) const
{
assert( polys.size() > 0 );
int maxPolys = polys.size();
int maxScore = -1;
int maxScorePoly = -1;
double workUnit = maxPolys;
for ( int i = 0 ; i < maxPolys ; i += m_polySkip+1 )
{
if ( progress )
progress->addProgress( workUnit );
int poly = i;
int score = getPlaneScore( polys[poly]->plane(), polys );
if ( score > maxScore )
{
maxScore = score;
maxScorePoly = poly;
}
}
assert( maxScore >= 0 );
assert( maxScorePoly >= 0 );
*splitPlane = polys[maxScorePoly]->plane();
return maxScore > 0 && splitPlane->finite();
}
int BSPBalanceSplitSelector::getPlaneScore( const Vector4& plane,
const util::Vector<BSPPolygon*>& polys )
{
int pos = 0;
int neg = 0;
int onplane = 0;
for ( int i = 0 ; i < polys.size() ; ++i )
{
const BSPPolygon* poly = polys[i];
int vpos = 0;
int vneg = 0;
int vonplane = 0;
const int verts = poly->vertices();
for ( int k = 0 ; k < verts ; ++k )
{
const Vector3& v = poly->getVertex(k);
float sdist = v.x*plane.x + v.y*plane.y + v.z*plane.z + plane.w;
if ( sdist >= BSPNode::PLANE_THICKNESS )
++vpos;
else if ( sdist <= -BSPNode::PLANE_THICKNESS )
++vneg;
else
++vonplane;
}
if ( verts == vpos )
++pos;
else if ( verts == vneg )
++neg;
else if ( verts == vonplane )
++onplane;
}
return Math::min(pos, neg);
}
} // bsp
| 22.953704 | 88 | 0.572812 | Andrewich |
d3e1f7f857c2477d24b3d038a2f6de3ca5c60215 | 1,037 | cpp | C++ | Pinball/ModuleTitleScreen.cpp | yeraytm/Pinball | f39b8d7b0e1b793ae7f3f992caec1a2960c1923c | [
"MIT"
] | null | null | null | Pinball/ModuleTitleScreen.cpp | yeraytm/Pinball | f39b8d7b0e1b793ae7f3f992caec1a2960c1923c | [
"MIT"
] | null | null | null | Pinball/ModuleTitleScreen.cpp | yeraytm/Pinball | f39b8d7b0e1b793ae7f3f992caec1a2960c1923c | [
"MIT"
] | null | null | null | #include "Application.h"
#include "ModuleTitleScreen.h"
#include "ModuleTextures.h"
#include "ModuleFadeToBlack.h"
#include "ModuleRender.h"
#include "ModuleInput.h"
#include "ModuleAudio.h"
#include "ModuleWindow.h"
ModuleTitleScreen::ModuleTitleScreen(Application* app, bool startEnabled) : Module(app, startEnabled) {}
ModuleTitleScreen::~ModuleTitleScreen() {}
bool ModuleTitleScreen::Start()
{
bool ret = true;
// Screen rect
screen = { 0, 0, SCREEN_WIDTH, SCREEN_HEIGHT };
tex = App->textures->Load("pinball/graphics/title_screen.png");
if (tex == nullptr)
{
ret = false;
}
return ret;
}
update_status ModuleTitleScreen::Update()
{
update_status ret = UPDATE_CONTINUE;
if (App->input->GetKey(SDL_SCANCODE_RETURN) == KEY_DOWN)
{
App->fade_to_black->FadeToBlack(this, (Module*)App->scene_intro, 100);
}
// Blit
if (!App->renderer->Blit(tex, 0, 0, &screen, 0.0f))
{
ret = UPDATE_STOP;
}
return ret;
}
bool ModuleTitleScreen::CleanUp()
{
bool ret = true;
App->textures->Unload(tex);
return ret;
} | 19.203704 | 104 | 0.708775 | yeraytm |
d3e359b05bd5789bf669003e029f5afcbb67979c | 2,880 | hpp | C++ | lib/builder/Bittner13CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 4 | 2019-03-09T16:35:00.000Z | 2022-01-12T06:32:05.000Z | lib/builder/Bittner13CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | null | null | null | lib/builder/Bittner13CUDA.hpp | mensinda/BVHTest | 46e24818f623797c78f2e094434213e3728a114c | [
"Apache-2.0"
] | 1 | 2020-09-09T15:47:13.000Z | 2020-09-09T15:47:13.000Z | /*
* Copyright (C) 2018 Daniel Mensinger
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include "base/BVH.hpp"
#include "base/BVHPatch.hpp"
#include <cstdint>
using BVHTest::base::CUDAMemoryBVHPointer;
typedef BVHTest::base::BVHPatch PATCH;
typedef BVHTest::base::MiniPatch MINI_PATCH;
const size_t CUDA_QUEUE_SIZE = 4096;
const size_t CUDA_ALT_QUEUE_SIZE = 16;
struct TodoStruct {
uint32_t *nodes = nullptr;
float * costs = nullptr;
};
struct GPUWorkingMemory {
bool result;
TodoStruct todoNodes;
TodoStruct todoSorted;
uint32_t *leafNodes = nullptr;
uint8_t * deviceSelectFlags = nullptr;
PATCH * patches = nullptr;
uint32_t *skipped = nullptr;
uint32_t *nodesToFix = nullptr;
uint32_t *flags = nullptr;
void * cubSortTempStorage = nullptr;
uint32_t numLeafNodes = 0;
uint32_t numInnerNodes = 0;
uint32_t numPatches = 0;
uint32_t numSkipped = 0;
uint32_t numNodesToFix = 0;
uint32_t numFlags = 0;
size_t cubSortTempStorageSize = 0;
};
struct AlgoCFG {
uint32_t numChunks;
uint32_t chunkSize;
uint32_t blockSize = 32;
bool offsetAccess = true;
bool altFindNode = true;
bool altFixTree = true;
bool altSort = true;
bool sort = true;
bool localPatchCPY = true;
};
GPUWorkingMemory allocateMemory(CUDAMemoryBVHPointer *_bvh, uint32_t _batchSize, uint32_t _numFaces);
void freeMemory(GPUWorkingMemory *_data);
void initData(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, uint32_t _blockSize);
void fixTree1(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, uint32_t _blockSize);
void fixTree3(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, uint32_t _blockSize);
void bn13_selectNodes(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, AlgoCFG _cfg);
void bn13_rmAndReinsChunk(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, AlgoCFG _cfg, uint32_t _chunk);
void bn13_doAlgorithmStep(GPUWorkingMemory *_data, CUDAMemoryBVHPointer *_GPUbvh, AlgoCFG _cfg);
float CUDAcalcSAH(CUDAMemoryBVHPointer *_GPUbvh);
void doCudaDevSync();
uint32_t calcNumSkipped(GPUWorkingMemory *_data);
| 34.285714 | 113 | 0.697222 | mensinda |
d3e4118169d70aefc553a867f9615b30b751a403 | 3,167 | hpp | C++ | src/mfx/uitk/Rect.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 69 | 2017-01-17T13:17:31.000Z | 2022-03-01T14:56:32.000Z | src/mfx/uitk/Rect.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 1 | 2020-11-03T14:52:45.000Z | 2020-12-01T20:31:15.000Z | src/mfx/uitk/Rect.hpp | mikelange49/pedalevite | a81bd8a6119c5920995ec91b9f70e11e9379580e | [
"WTFPL"
] | 8 | 2017-02-08T13:30:42.000Z | 2021-12-09T08:43:09.000Z | /*****************************************************************************
Rect.hpp
Author: Laurent de Soras, 2016
--- Legal stuff ---
This program is free software. It comes without any warranty, to
the extent permitted by applicable law. You can redistribute it
and/or modify it under the terms of the Do What The Fuck You Want
To Public License, Version 2, as published by Sam Hocevar. See
http://sam.zoy.org/wtfpl/COPYING for more details.
*Tab=3***********************************************************************/
#if ! defined (mfx_uitk_Rect_CODEHEADER_INCLUDED)
#define mfx_uitk_Rect_CODEHEADER_INCLUDED
/*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
namespace mfx
{
namespace uitk
{
/*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
Rect::Rect (int x1, int y1, int x2, int y2)
: Inherited ({{ Vec2d (x1, y1) , Vec2d (x2, y2) }})
{
// Nothing
}
Rect::Rect (Vec2d c0, Vec2d c1)
: Inherited ({{ c0, c1 }})
{
// Nothing
}
// Returns a null rect if there is no intersection
Rect & Rect::intersect (const Rect &other)
{
Rect & lhs = *this;
if ( lhs [1] [0] <= other [0] [0]
|| lhs [0] [0] >= other [1] [0]
|| lhs [1] [1] <= other [0] [1]
|| lhs [0] [1] >= other [1] [1])
{
lhs = Rect ();
}
else
{
lhs [0] [0] = std::max (lhs [0] [0], other [0] [0]);
lhs [0] [1] = std::max (lhs [0] [1], other [0] [1]);
lhs [1] [0] = std::min (lhs [1] [0], other [1] [0]);
lhs [1] [1] = std::min (lhs [1] [1], other [1] [1]);
}
return lhs;
}
Rect & Rect::merge (const Rect &other)
{
Rect & lhs = *this;
const Vec2d sz_lhs = lhs.get_size ();
const Vec2d sz_rhs = other.get_size ();
if (sz_lhs [0] <= 0 || sz_lhs [1] <= 0)
{
lhs = other;
}
else if (sz_rhs [0] > 0 && sz_rhs [1] > 0)
{
lhs [0] [0] = std::min (lhs [0] [0], other [0] [0]);
lhs [0] [1] = std::min (lhs [0] [1], other [0] [1]);
lhs [1] [0] = std::max (lhs [1] [0], other [1] [0]);
lhs [1] [1] = std::max (lhs [1] [1], other [1] [1]);
}
return lhs;
}
Vec2d Rect::get_size () const
{
return (*this) [1] - (*this) [0];
}
Rect & Rect::operator += (const Vec2d &other)
{
(*this) [0] += other;
(*this) [1] += other;
return *this;
}
Rect & Rect::operator -= (const Vec2d &other)
{
(*this) [0] -= other;
(*this) [1] -= other;
return *this;
}
bool Rect::is_empty () const
{
const Rect & tmp = *this;
return (tmp [1] [0] <= tmp [0] [0] || tmp [1] [1] <= tmp [0] [1]);
}
/*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
/*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
} // namespace uitk
} // namespace mfx
mfx::uitk::Rect operator + (const mfx::uitk::Rect &lhs, const mfx::uitk::Vec2d &rhs)
{
mfx::uitk::Rect res (lhs);
res += rhs;
return res;
}
mfx::uitk::Rect operator - (const mfx::uitk::Rect &lhs, const mfx::uitk::Vec2d &rhs)
{
mfx::uitk::Rect res (lhs);
res -= rhs;
return res;
}
#endif // mfx_uitk_Rect_CODEHEADER_INCLUDED
/*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
| 17.994318 | 85 | 0.469845 | mikelange49 |
d3f00464d44d556046de78702a25bd6c6101a143 | 815 | cpp | C++ | tests/appenv/multifile/integers.cpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null | tests/appenv/multifile/integers.cpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null | tests/appenv/multifile/integers.cpp | FloEdelmann/universal | c5b83f251ad91229399b7f97e4eeefcf718819d4 | [
"MIT"
] | null | null | null |
// integers.cpp: compilation test to check arithmetic type usage in application environments
//
// Copyright (C) 2017-2022 Stillwater Supercomputing, Inc.
//
// This file is part of the universal numbers project, which is released under an MIT Open Source license.
#include <universal/number/integer/integer.hpp>
#include <iostream>
#include <vector>
using Integer = sw::universal::integer<8, uint8_t, sw::universal::IntegerNumberType::IntegerNumber>;
Integer integerPolynomial(const std::vector<int>& coef, const Integer& x) {
using namespace sw::universal;
if (coef.size() < 2) {
std::cerr << "Coefficient set is too small to represent a polynomial\n";
return Integer(0);
}
Integer v = coef[0];
for (size_t i = 1; i < coef.size(); ++i) {
v += Integer(coef[i]) * pow(x, Integer(i));
}
return v;
}
| 31.346154 | 106 | 0.711656 | FloEdelmann |
d3f252bde3e1479ae92e85876cc86fcf77fbd286 | 364 | cpp | C++ | src/8.cpp | dxscjx123/SwordOffer | e04958beb3f99c103f879b09f3da547679a208c4 | [
"MIT"
] | 3 | 2018-04-20T14:07:14.000Z | 2019-08-29T14:35:30.000Z | src/8.cpp | dxscjx123/SwordOffer | e04958beb3f99c103f879b09f3da547679a208c4 | [
"MIT"
] | null | null | null | src/8.cpp | dxscjx123/SwordOffer | e04958beb3f99c103f879b09f3da547679a208c4 | [
"MIT"
] | null | null | null | // 分析:
// 斐波拉契数列问题。递归方式下需注意函数嵌套太深。
class Solution {
public:
int jumpFloor(int number) {
if(number <= 2)
return number;
int pre = 1, next = 2;
int result, tmp;
for(int i = 3; i <= number; i++)
{
tmp = next; //设置tmp保存前一个变量next
next = pre + next; //更新next
pre = tmp; //pre指向旧的next作为新的pre
}
result = next;
return result;
}
}; | 18.2 | 36 | 0.57967 | dxscjx123 |
d3f300588ab97dafe9edcfa1d79ffdfa40fcbb1d | 27 | hpp | C++ | LearnCmake/HelloWorld/foo.hpp | wisemountain/wise.learn | a8e1343a7d5fd791a3327c108268f752e56b63d7 | [
"MIT"
] | 3 | 2021-04-23T04:01:55.000Z | 2021-09-20T12:47:53.000Z | LearnCmake/HelloWorld/foo.hpp | wisemountain/wise.learn | a8e1343a7d5fd791a3327c108268f752e56b63d7 | [
"MIT"
] | null | null | null | LearnCmake/HelloWorld/foo.hpp | wisemountain/wise.learn | a8e1343a7d5fd791a3327c108268f752e56b63d7 | [
"MIT"
] | null | null | null | #pragma once
void foo();
| 6.75 | 13 | 0.62963 | wisemountain |
d3f352e8821edcd4848cf4d13d75431b6ee504a9 | 2,584 | cpp | C++ | demo/src/GLDebugger.cpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | demo/src/GLDebugger.cpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | demo/src/GLDebugger.cpp | pdm-pcb/pdmath | 6c8ac4288c68bbe547e71f5bb7d1e44d3f1e35ab | [
"MIT"
] | null | null | null | #include "GLDebugger.hpp"
#include <iostream>
void GLAPIENTRY
GLDebugger::error_callback(GLenum source,
GLenum type, GLuint id, GLenum severity,
GLsizei length, const GLchar *message,
const void *user_data) {
const char *_severity;
const char *_source;
const char *_type;
switch(severity) {
case GL_DEBUG_SEVERITY_HIGH:
_severity = "High";
break;
case GL_DEBUG_SEVERITY_MEDIUM:
_severity = "Medium";
break;
case GL_DEBUG_SEVERITY_LOW:
_severity = "Low";
break;
case GL_DEBUG_SEVERITY_NOTIFICATION:
_severity = "Notification";
break;
default:
_severity = "Unknown";
break;
}
switch(source) {
case GL_DEBUG_SOURCE_API:
_source = "API";
break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM:
_source = "Window System";
break;
case GL_DEBUG_SOURCE_SHADER_COMPILER:
_source = "Shader Compiler";
break;
case GL_DEBUG_SOURCE_THIRD_PARTY:
_source = "Third Party";
break;
case GL_DEBUG_SOURCE_APPLICATION:
_source = "Application";
break;
case GL_DEBUG_SOURCE_OTHER:
_source = "Other";
break;
default:
_source = "Unknown";
break;
}
switch(type) {
case GL_DEBUG_TYPE_ERROR:
_type = "Error";
break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR:
_type = "Depricated Behavior";
break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR:
_type = "Undefined Behavior";
break;
case GL_DEBUG_TYPE_PORTABILITY:
_type = "Portability";
break;
case GL_DEBUG_TYPE_PERFORMANCE:
_type = "Performance";
break;
case GL_DEBUG_TYPE_OTHER:
_type = "Other";
break;
case GL_DEBUG_TYPE_MARKER:
_type = "Marker";
break;
default:
_type = "Unknown";
break;
}
std::cerr << "\n[OpenGL] " << _type << " #" << id << " (Severity: "
<< _severity << ")" << " from " << _source << "\n---\n"
<< message << "\n---"
<< std::endl;
}
GLDebugger::GLDebugger() {
glEnable(GL_DEBUG_OUTPUT);
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
glDebugMessageCallback(&error_callback, nullptr);
std::ios_base::sync_with_stdio(false);
std::cout << "***\n"
<< glGetString(GL_VERSION) << " : "
<< glGetString(GL_RENDERER)
<< "\n***\n";
} | 22.275862 | 71 | 0.55805 | pdm-pcb |
d3f70845df1404282c219c0ce8918e5706d174b2 | 4,407 | cpp | C++ | modules/squarepine_audio/wrappers/AudioTransportProcessor.cpp | thinium/squarepine_core | 9d73b0820b8b44129b62a643785e8a7d4a7035b0 | [
"ISC"
] | 7 | 2021-12-03T16:09:39.000Z | 2022-02-02T15:53:21.000Z | modules/squarepine_audio/wrappers/AudioTransportProcessor.cpp | thinium/squarepine_core | 9d73b0820b8b44129b62a643785e8a7d4a7035b0 | [
"ISC"
] | 2 | 2021-07-06T16:56:06.000Z | 2021-07-08T19:23:36.000Z | modules/squarepine_audio/wrappers/AudioTransportProcessor.cpp | thinium/squarepine_core | 9d73b0820b8b44129b62a643785e8a7d4a7035b0 | [
"ISC"
] | 2 | 2021-07-06T16:10:59.000Z | 2021-08-06T13:54:12.000Z | AudioTransportProcessor::AudioTransportProcessor() :
transport (new AudioTransportSource()),
source (nullptr)
{
audioSourceProcessor.setAudioSource (transport, true);
prepareToPlay (44100.0, 256);
}
AudioTransportProcessor::~AudioTransportProcessor()
{
audioSourceProcessor.setAudioSource (nullptr, false);
}
//==============================================================================
const String AudioTransportProcessor::getName() const
{
return TRANS ("Audio Transport");
}
Identifier AudioTransportProcessor::getIdentifier() const
{
return "AudioTransportProcessor";
}
//==============================================================================
void AudioTransportProcessor::play()
{
const ScopedLock lock (getCallbackLock());
transport->start();
}
void AudioTransportProcessor::playFromStart()
{
const ScopedLock lock (getCallbackLock());
transport->setPosition (0);
transport->start();
}
void AudioTransportProcessor::stop()
{
const ScopedLock lock (getCallbackLock());
transport->stop();
}
void AudioTransportProcessor::setLooping (const bool shouldLoop)
{
const ScopedLock lock (getCallbackLock());
transport->setLooping (shouldLoop);
if (source != nullptr)
source->setLooping (shouldLoop);
}
bool AudioTransportProcessor::isLooping() const
{
return transport->isLooping();
}
bool AudioTransportProcessor::isPlaying() const
{
return transport->isPlaying();
}
double AudioTransportProcessor::getLengthSeconds() const noexcept
{
return transport->getLengthInSeconds();
}
int64 AudioTransportProcessor::getLengthSamples() const noexcept
{
return transport->getTotalLength();
}
double AudioTransportProcessor::getCurrentTimeSeconds() const noexcept
{
return transport->getCurrentPosition();
}
int64 AudioTransportProcessor::getCurrentTimeSamples() const noexcept
{
return (int64) (getCurrentTimeSeconds() * getSampleRate());
}
void AudioTransportProcessor::setCurrentTime (const double newPosition)
{
transport->setPosition (newPosition);
}
void AudioTransportProcessor::setCurrentTime (const int64 samples)
{
transport->setPosition ((double) samples / getSampleRate());
}
void AudioTransportProcessor::setResamplingRatio (const double)
{
}
void AudioTransportProcessor::clear()
{
const ScopedLock lock (getCallbackLock());
stop();
transport->setSource (nullptr);
source = nullptr;
}
//==============================================================================
void AudioTransportProcessor::setSource (PositionableAudioSource* const s,
const int readAheadBufferSize,
TimeSliceThread* const readAheadThread,
const double sourceSampleRateToCorrectFor,
const int maxNumChannels)
{
const ScopedLock lock (getCallbackLock());
source = s;
transport->setSource (source, readAheadBufferSize, readAheadThread,
sourceSampleRateToCorrectFor, maxNumChannels);
prepareToPlay (getSampleRate(), getBlockSize());
}
void AudioTransportProcessor::setSource (AudioFormatReaderSource* const readerSource,
const int readAheadBufferSize,
TimeSliceThread* const readAheadThread)
{
int maxNumChans = 2;
auto sampleRate = 44100.0;
if (readerSource != nullptr)
{
if (auto* afr = readerSource->getAudioFormatReader())
{
maxNumChans = (int) afr->numChannels;
sampleRate = afr->sampleRate;
}
}
setSource (readerSource, readAheadBufferSize, readAheadThread, sampleRate, maxNumChans);
}
//==============================================================================
void AudioTransportProcessor::prepareToPlay (const double newSampleRate, const int estimatedSamplesPerBlock)
{
setRateAndBufferSizeDetails (newSampleRate, estimatedSamplesPerBlock);
audioSourceProcessor.prepareToPlay (newSampleRate, estimatedSamplesPerBlock);
}
void AudioTransportProcessor::processBlock (juce::AudioBuffer<float>& buffer, MidiBuffer& midiMessages)
{
audioSourceProcessor.processBlock (buffer, midiMessages);
}
void AudioTransportProcessor::releaseResources()
{
audioSourceProcessor.releaseResources();
}
| 27.54375 | 108 | 0.652598 | thinium |
d3f771c8e33bf22e64142a9aaec5a5717c849197 | 34,838 | cpp | C++ | src/network/network.cpp | trademarks/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 8 | 2016-10-21T09:01:43.000Z | 2021-05-31T06:32:14.000Z | src/network/network.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | null | null | null | src/network/network.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 4 | 2017-05-16T00:15:58.000Z | 2020-08-06T01:46:31.000Z | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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.
* OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file network.cpp Base functions for networking support. */
#include "../stdafx.h"
#ifdef ENABLE_NETWORK
#include "../strings_func.h"
#include "../command_func.h"
#include "../date_func.h"
#include "network_admin.h"
#include "network_client.h"
#include "network_server.h"
#include "network_content.h"
#include "network_udp.h"
#include "network_gamelist.h"
#include "network_base.h"
#include "core/udp.h"
#include "core/host.h"
#include "network_gui.h"
#include "../console_func.h"
#include "../3rdparty/md5/md5.h"
#include "../core/random_func.hpp"
#include "../window_func.h"
#include "../company_func.h"
#include "../company_base.h"
#include "../landscape_type.h"
#include "../rev.h"
#include "../core/pool_func.hpp"
#include "../gfx_func.h"
#include "table/strings.h"
#ifdef DEBUG_DUMP_COMMANDS
#include "../fileio_func.h"
/** When running the server till the wait point, run as fast as we can! */
bool _ddc_fastforward = true;
#endif /* DEBUG_DUMP_COMMANDS */
/** Make sure both pools have the same size. */
assert_compile(NetworkClientInfoPool::MAX_SIZE == NetworkClientSocketPool::MAX_SIZE);
/** The pool with client information. */
NetworkClientInfoPool _networkclientinfo_pool("NetworkClientInfo");
INSTANTIATE_POOL_METHODS(NetworkClientInfo)
bool _networking; ///< are we in networking mode?
bool _network_server; ///< network-server is active
bool _network_available; ///< is network mode available?
bool _network_dedicated; ///< are we a dedicated server?
bool _is_network_server; ///< Does this client wants to be a network-server?
NetworkServerGameInfo _network_game_info; ///< Information about our game.
NetworkCompanyState *_network_company_states = NULL; ///< Statistics about some companies.
ClientID _network_own_client_id; ///< Our client identifier.
ClientID _redirect_console_to_client; ///< If not invalid, redirect the console output to a client.
bool _network_need_advertise; ///< Whether we need to advertise.
uint32 _network_last_advertise_frame; ///< Last time we did advertise.
uint8 _network_reconnect; ///< Reconnect timeout
StringList _network_bind_list; ///< The addresses to bind on.
StringList _network_host_list; ///< The servers we know.
StringList _network_ban_list; ///< The banned clients.
uint32 _frame_counter_server; ///< The frame_counter of the server, if in network-mode
uint32 _frame_counter_max; ///< To where we may go with our clients
uint32 _frame_counter; ///< The current frame.
uint32 _last_sync_frame; ///< Used in the server to store the last time a sync packet was sent to clients.
NetworkAddressList _broadcast_list; ///< List of broadcast addresses.
uint32 _sync_seed_1; ///< Seed to compare during sync checks.
#ifdef NETWORK_SEND_DOUBLE_SEED
uint32 _sync_seed_2; ///< Second part of the seed.
#endif
uint32 _sync_frame; ///< The frame to perform the sync check.
bool _network_first_time; ///< Whether we have finished joining or not.
bool _network_udp_server; ///< Is the UDP server started?
uint16 _network_udp_broadcast; ///< Timeout for the UDP broadcasts.
uint8 _network_advertise_retries; ///< The number of advertisement retries we did.
CompanyMask _network_company_passworded; ///< Bitmask of the password status of all companies.
/* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
assert_compile((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
assert_compile((int)NETWORK_COMPANY_NAME_LENGTH == MAX_LENGTH_COMPANY_NAME_CHARS * MAX_CHAR_LENGTH);
extern NetworkUDPSocketHandler *_udp_client_socket; ///< udp client socket
extern NetworkUDPSocketHandler *_udp_server_socket; ///< udp server socket
extern NetworkUDPSocketHandler *_udp_master_socket; ///< udp master socket
/** The amount of clients connected */
byte _network_clients_connected = 0;
/* Some externs / forwards */
extern void StateGameLoop();
/**
* Basically a client is leaving us right now.
*/
NetworkClientInfo::~NetworkClientInfo()
{
/* Delete the chat window, if you were chatting with this client. */
InvalidateWindowData(WC_SEND_NETWORK_MSG, DESTTYPE_CLIENT, this->client_id);
}
/**
* Return the CI given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
*/
/* static */ NetworkClientInfo *NetworkClientInfo::GetByClientID(ClientID client_id)
{
NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_id == client_id) return ci;
}
return NULL;
}
/**
* Return the client state given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
*/
/* static */ ServerNetworkGameSocketHandler *ServerNetworkGameSocketHandler::GetByClientID(ClientID client_id)
{
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == client_id) return cs;
}
return NULL;
}
byte NetworkSpectatorCount()
{
const NetworkClientInfo *ci;
byte count = 0;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_playas == COMPANY_SPECTATOR) count++;
}
/* Don't count a dedicated server as spectator */
if (_network_dedicated) count--;
return count;
}
/**
* Change the company password of a given company.
* @param company_id ID of the company the password should be changed for.
* @param password The unhashed password we like to set ('*' or '' resets the password)
* @return The password.
*/
const char *NetworkChangeCompanyPassword(CompanyID company_id, const char *password, bool already_hashed)
{
if (strcmp(password, "*") == 0) password = "";
if (_network_server) {
NetworkServerSetCompanyPassword(company_id, password, already_hashed);
} else {
NetworkClientSetCompanyPassword(password);
}
return password;
}
/**
* Hash the given password using server ID and game seed.
* @param password Password to hash.
* @param password_server_id Server ID.
* @param password_game_seed Game seed.
* @return The hashed password.
*/
const char *GenerateCompanyPasswordHash(const char *password, const char *password_server_id, uint32 password_game_seed)
{
if (StrEmpty(password)) return password;
char salted_password[NETWORK_SERVER_ID_LENGTH];
memset(salted_password, 0, sizeof(salted_password));
snprintf(salted_password, sizeof(salted_password), "%s", password);
/* Add the game seed and the server's ID as the salt. */
for (uint i = 0; i < NETWORK_SERVER_ID_LENGTH - 1; i++) {
salted_password[i] ^= password_server_id[i] ^ (password_game_seed >> (i % 32));
}
Md5 checksum;
uint8 digest[16];
static char hashed_password[NETWORK_SERVER_ID_LENGTH];
/* Generate the MD5 hash */
checksum.Append(salted_password, sizeof(salted_password) - 1);
checksum.Finish(digest);
for (int di = 0; di < 16; di++) sprintf(hashed_password + di * 2, "%02x", digest[di]);
hashed_password[lengthof(hashed_password) - 1] = '\0';
return hashed_password;
}
/**
* Check if the company we want to join requires a password.
* @param company_id id of the company we want to check the 'passworded' flag for.
* @return true if the company requires a password.
*/
bool NetworkCompanyIsPassworded(CompanyID company_id)
{
return HasBit(_network_company_passworded, company_id);
}
/* This puts a text-message to the console, or in the future, the chat-box,
* (to keep it all a bit more general)
* If 'self_send' is true, this is the client who is sending the message */
void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const char *name, const char *str, int64 data)
{
StringID strid;
switch (action) {
case NETWORK_ACTION_SERVER_MESSAGE:
/* Ignore invalid messages */
strid = STR_NETWORK_SERVER_MESSAGE;
colour = CC_DEFAULT;
break;
case NETWORK_ACTION_COMPANY_SPECTATOR:
colour = CC_DEFAULT;
strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_SPECTATE;
break;
case NETWORK_ACTION_COMPANY_JOIN:
colour = CC_DEFAULT;
strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_JOIN;
break;
case NETWORK_ACTION_COMPANY_NEW:
colour = CC_DEFAULT;
strid = STR_NETWORK_MESSAGE_CLIENT_COMPANY_NEW;
break;
case NETWORK_ACTION_JOIN:
/* Show the Client ID for the server but not for the client. */
strid = _network_server ? STR_NETWORK_MESSAGE_CLIENT_JOINED_ID : STR_NETWORK_MESSAGE_CLIENT_JOINED;
break;
case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_MESSAGE_CLIENT_LEFT; break;
case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_MESSAGE_NAME_CHANGE; break;
case NETWORK_ACTION_GIVE_MONEY: strid = self_send ? STR_NETWORK_MESSAGE_GAVE_MONEY_AWAY : STR_NETWORK_MESSAGE_GIVE_MONEY; break;
case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
default: strid = STR_NETWORK_CHAT_ALL; break;
}
char message[1024];
SetDParamStr(0, name);
SetDParamStr(1, str);
SetDParam(2, data);
/* All of these strings start with "***". These characters are interpreted as both left-to-right and
* right-to-left characters depending on the context. As the next text might be an user's name, the
* user name's characters will influence the direction of the "***" instead of the language setting
* of the game. Manually set the direction of the "***" by inserting a text-direction marker. */
char *msg_ptr = message + Utf8Encode(message, _current_text_dir == TD_LTR ? CHAR_TD_LRM : CHAR_TD_RLM);
GetString(msg_ptr, strid, lastof(message));
DEBUG(desync, 1, "msg: %08x; %02x; %s", _date, _date_fract, message);
IConsolePrintF(colour, "%s", message);
NetworkAddChatMessage((TextColour)colour, _settings_client.gui.network_chat_timeout, "%s", message);
}
/* Calculate the frame-lag of a client */
uint NetworkCalculateLag(const NetworkClientSocket *cs)
{
int lag = cs->last_frame_server - cs->last_frame;
/* This client has missed his ACK packet after 1 DAY_TICKS..
* so we increase his lag for every frame that passes!
* The packet can be out by a max of _net_frame_freq */
if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter) {
lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
}
return lag;
}
/* There was a non-recoverable error, drop back to the main menu with a nice
* error */
void NetworkError(StringID error_string)
{
_switch_mode = SM_MENU;
extern StringID _switch_mode_errorstr;
_switch_mode_errorstr = error_string;
}
/**
* Retrieve the string id of an internal error number
* @param err NetworkErrorCode
* @return the StringID
*/
StringID GetNetworkErrorMsg(NetworkErrorCode err)
{
/* List of possible network errors, used by
* PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
static const StringID network_error_strings[] = {
STR_NETWORK_ERROR_CLIENT_GENERAL,
STR_NETWORK_ERROR_CLIENT_DESYNC,
STR_NETWORK_ERROR_CLIENT_SAVEGAME,
STR_NETWORK_ERROR_CLIENT_CONNECTION_LOST,
STR_NETWORK_ERROR_CLIENT_PROTOCOL_ERROR,
STR_NETWORK_ERROR_CLIENT_NEWGRF_MISMATCH,
STR_NETWORK_ERROR_CLIENT_NOT_AUTHORIZED,
STR_NETWORK_ERROR_CLIENT_NOT_EXPECTED,
STR_NETWORK_ERROR_CLIENT_WRONG_REVISION,
STR_NETWORK_ERROR_CLIENT_NAME_IN_USE,
STR_NETWORK_ERROR_CLIENT_WRONG_PASSWORD,
STR_NETWORK_ERROR_CLIENT_COMPANY_MISMATCH,
STR_NETWORK_ERROR_CLIENT_KICKED,
STR_NETWORK_ERROR_CLIENT_CHEATER,
STR_NETWORK_ERROR_CLIENT_SERVER_FULL,
STR_NETWORK_ERROR_CLIENT_TOO_MANY_COMMANDS
};
if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
return network_error_strings[err];
}
/**
* Handle the pause mode change so we send the right messages to the chat.
* @param prev_mode The previous pause mode.
* @param changed_mode The pause mode that got changed.
*/
void NetworkHandlePauseChange(PauseMode prev_mode, PauseMode changed_mode)
{
if (!_networking) return;
switch (changed_mode) {
case PM_PAUSED_NORMAL:
case PM_PAUSED_JOIN:
case PM_PAUSED_ACTIVE_CLIENTS: {
bool changed = ((_pause_mode == PM_UNPAUSED) != (prev_mode == PM_UNPAUSED));
bool paused = (_pause_mode != PM_UNPAUSED);
if (!paused && !changed) return;
StringID str;
if (!changed) {
int i = -1;
if ((_pause_mode & PM_PAUSED_NORMAL) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL);
if ((_pause_mode & PM_PAUSED_JOIN) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS);
if ((_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) != PM_UNPAUSED) SetDParam(++i, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS);
str = STR_NETWORK_SERVER_MESSAGE_GAME_STILL_PAUSED_1 + i;
} else {
switch (changed_mode) {
case PM_PAUSED_NORMAL: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_MANUAL); break;
case PM_PAUSED_JOIN: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_CONNECTING_CLIENTS); break;
case PM_PAUSED_ACTIVE_CLIENTS: SetDParam(0, STR_NETWORK_SERVER_MESSAGE_GAME_REASON_NOT_ENOUGH_PLAYERS); break;
default: NOT_REACHED();
}
str = paused ? STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED : STR_NETWORK_SERVER_MESSAGE_GAME_UNPAUSED;
}
char buffer[DRAW_STRING_BUFFER];
GetString(buffer, str, lastof(buffer));
NetworkTextMessage(NETWORK_ACTION_SERVER_MESSAGE, CC_DEFAULT, false, NULL, buffer);
break;
}
default:
return;
}
}
/**
* Helper function for the pause checkers. If pause is true and the
* current pause mode isn't set the game will be paused, if it it false
* and the pause mode is set the game will be unpaused. In the other
* cases nothing happens to the pause state.
* @param pause whether we'd like to pause
* @param pm the mode which we would like to pause with
*/
static void CheckPauseHelper(bool pause, PauseMode pm)
{
if (pause == ((_pause_mode & pm) != PM_UNPAUSED)) return;
DoCommandP(0, pm, pause ? 1 : 0, CMD_PAUSE);
}
/**
* Counts the number of active clients connected.
* It has to be in STATUS_ACTIVE and not a spectator
* @return number of active clients
*/
static uint NetworkCountActiveClients()
{
const NetworkClientSocket *cs;
uint count = 0;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->status != NetworkClientSocket::STATUS_ACTIVE) continue;
if (!Company::IsValidID(cs->GetInfo()->client_playas)) continue;
count++;
}
return count;
}
/**
* Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate
*/
static void CheckMinActiveClients()
{
if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
!_network_dedicated ||
(_settings_client.network.min_active_clients == 0 && (_pause_mode & PM_PAUSED_ACTIVE_CLIENTS) == PM_UNPAUSED)) {
return;
}
CheckPauseHelper(NetworkCountActiveClients() < _settings_client.network.min_active_clients, PM_PAUSED_ACTIVE_CLIENTS);
}
/**
* Checks whether there is a joining client
* @return true iff one client is joining (but not authorizing)
*/
static bool NetworkHasJoiningClient()
{
const NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->status >= NetworkClientSocket::STATUS_AUTHORIZED && cs->status < NetworkClientSocket::STATUS_ACTIVE) return true;
}
return false;
}
/**
* Check whether we should pause on join
*/
static void CheckPauseOnJoin()
{
if ((_pause_mode & PM_PAUSED_ERROR) != PM_UNPAUSED ||
(!_settings_client.network.pause_on_join && (_pause_mode & PM_PAUSED_JOIN) == PM_UNPAUSED)) {
return;
}
CheckPauseHelper(NetworkHasJoiningClient(), PM_PAUSED_JOIN);
}
/**
* Converts a string to ip/port/company
* Format: IP:port#company
*
* connection_string will be re-terminated to seperate out the hostname, and company and port will
* be set to the company and port strings given by the user, inside the memory area originally
* occupied by connection_string.
*/
void ParseConnectionString(const char **company, const char **port, char *connection_string)
{
bool ipv6 = (strchr(connection_string, ':') != strrchr(connection_string, ':'));
char *p;
for (p = connection_string; *p != '\0'; p++) {
switch (*p) {
case '[':
ipv6 = true;
break;
case ']':
ipv6 = false;
break;
case '#':
*company = p + 1;
*p = '\0';
break;
case ':':
if (ipv6) break;
*port = p + 1;
*p = '\0';
break;
}
}
}
/**
* Handle the acception of a connection to the server.
* @param s The socket of the new connection.
* @param address The address of the peer.
*/
/* static */ void ServerNetworkGameSocketHandler::AcceptConnection(SOCKET s, const NetworkAddress &address)
{
/* Register the login */
_network_clients_connected++;
SetWindowDirty(WC_CLIENT_LIST, 0);
ServerNetworkGameSocketHandler *cs = new ServerNetworkGameSocketHandler(s);
cs->client_address = address; // Save the IP of the client
}
/**
* Resets the pools used for network clients, and the admin pool if needed.
* @param close_admins Whether the admin pool has to be cleared as well.
*/
static void InitializeNetworkPools(bool close_admins = true)
{
PoolBase::Clean(PT_NCLIENT | (close_admins ? PT_NADMIN : PT_NONE));
}
/**
* Close current connections.
* @param close_admins Whether the admin connections have to be closed as well.
*/
void NetworkClose(bool close_admins)
{
if (_network_server) {
if (close_admins) {
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ADMIN_SOCKETS(as) {
as->CloseConnection(true);
}
}
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
cs->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}
ServerNetworkGameSocketHandler::CloseListeners();
ServerNetworkAdminSocketHandler::CloseListeners();
} else if (MyClient::my_client != NULL) {
MyClient::SendQuit();
MyClient::my_client->CloseConnection(NETWORK_RECV_STATUS_CONN_LOST);
}
TCPConnecter::KillAll();
_networking = false;
_network_server = false;
NetworkFreeLocalCommandQueue();
free(_network_company_states);
_network_company_states = NULL;
InitializeNetworkPools(close_admins);
}
/* Inits the network (cleans sockets and stuff) */
static void NetworkInitialize(bool close_admins = true)
{
InitializeNetworkPools(close_admins);
NetworkUDPInitialize();
_sync_frame = 0;
_network_first_time = true;
_network_reconnect = 0;
}
/** Non blocking connection create to query servers */
class TCPQueryConnecter : TCPConnecter {
public:
TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
{
NetworkDisconnect();
}
virtual void OnConnect(SOCKET s)
{
_networking = true;
new ClientNetworkGameSocketHandler(s);
MyClient::SendCompanyInformationQuery();
}
};
/* Query a server to fetch his game-info
* If game_info is true, only the gameinfo is fetched,
* else only the client_info is fetched */
void NetworkTCPQueryServer(NetworkAddress address)
{
if (!_network_available) return;
NetworkDisconnect();
NetworkInitialize();
new TCPQueryConnecter(address);
}
/* Validates an address entered as a string and adds the server to
* the list. If you use this function, the games will be marked
* as manually added. */
void NetworkAddServer(const char *b)
{
if (*b != '\0') {
const char *port = NULL;
const char *company = NULL;
char host[NETWORK_HOSTNAME_LENGTH];
uint16 rport;
strecpy(host, b, lastof(host));
strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
rport = NETWORK_DEFAULT_PORT;
ParseConnectionString(&company, &port, host);
if (port != NULL) rport = atoi(port);
NetworkUDPQueryServer(NetworkAddress(host, rport), true);
}
}
/**
* Get the addresses to bind to.
* @param addresses the list to write to.
* @param port the port to bind to.
*/
void GetBindAddresses(NetworkAddressList *addresses, uint16 port)
{
for (char **iter = _network_bind_list.Begin(); iter != _network_bind_list.End(); iter++) {
*addresses->Append() = NetworkAddress(*iter, port);
}
/* No address, so bind to everything. */
if (addresses->Length() == 0) {
*addresses->Append() = NetworkAddress("", port);
}
}
/* Generates the list of manually added hosts from NetworkGameList and
* dumps them into the array _network_host_list. This array is needed
* by the function that generates the config file. */
void NetworkRebuildHostList()
{
_network_host_list.Clear();
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
if (item->manually) *_network_host_list.Append() = strdup(item->address.GetAddressAsString(false));
}
}
/** Non blocking connection create to actually connect to servers */
class TCPClientConnecter : TCPConnecter {
public:
TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
{
NetworkError(STR_NETWORK_ERROR_NOCONNECTION);
}
virtual void OnConnect(SOCKET s)
{
_networking = true;
new ClientNetworkGameSocketHandler(s);
IConsoleCmdExec("exec scripts/on_client.scr 0");
NetworkClient_Connected();
}
};
/* Used by clients, to connect to a server */
void NetworkClientConnectGame(NetworkAddress address, CompanyID join_as, const char *join_server_password, const char *join_company_password)
{
if (!_network_available) return;
if (address.GetPort() == 0) return;
strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
_settings_client.network.last_port = address.GetPort();
_network_join_as = join_as;
_network_join_server_password = join_server_password;
_network_join_company_password = join_company_password;
NetworkDisconnect();
NetworkInitialize();
_network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
ShowJoinStatusWindow();
new TCPClientConnecter(address);
}
static void NetworkInitGameInfo()
{
if (StrEmpty(_settings_client.network.server_name)) {
snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
}
/* The server is a client too */
_network_game_info.clients_on = _network_dedicated ? 0 : 1;
/* There should be always space for the server. */
assert(NetworkClientInfo::CanAllocateItem());
NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
}
bool NetworkServerStart()
{
if (!_network_available) return false;
/* Call the pre-scripts */
IConsoleCmdExec("exec scripts/pre_server.scr 0");
if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
NetworkDisconnect(false, false);
NetworkInitialize(false);
if (!ServerNetworkGameSocketHandler::Listen(_settings_client.network.server_port)) return false;
/* Only listen for admins when the password isn't empty. */
if (!StrEmpty(_settings_client.network.admin_password) && !ServerNetworkAdminSocketHandler::Listen(_settings_client.network.server_admin_port)) return false;
/* Try to start UDP-server */
_network_udp_server = _udp_server_socket->Listen();
_network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
_network_server = true;
_networking = true;
_frame_counter = 0;
_frame_counter_server = 0;
_frame_counter_max = 0;
_last_sync_frame = 0;
_network_own_client_id = CLIENT_ID_SERVER;
_network_clients_connected = 0;
_network_company_passworded = 0;
NetworkInitGameInfo();
/* execute server initialization script */
IConsoleCmdExec("exec scripts/on_server.scr 0");
/* if the server is dedicated ... add some other script */
if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
/* Try to register us to the master server */
_network_last_advertise_frame = 0;
_network_need_advertise = true;
NetworkUDPAdvertise();
/* welcome possibly still connected admins - this can only happen on a dedicated server. */
if (_network_dedicated) ServerNetworkAdminSocketHandler::WelcomeAll();
return true;
}
/* The server is rebooting...
* The only difference with NetworkDisconnect, is the packets that is sent */
void NetworkReboot()
{
if (_network_server) {
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
cs->SendNewGame();
cs->SendPackets();
}
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ADMIN_SOCKETS(as) {
as->SendNewGame();
as->SendPackets();
}
}
/* For non-dedicated servers we have to kick the admins as we are not
* certain that we will end up in a new network game. */
NetworkClose(!_network_dedicated);
}
/**
* We want to disconnect from the host/clients.
* @param blocking whether to wait till everything has been closed.
* @param close_admins Whether the admin sockets need to be closed as well.
*/
void NetworkDisconnect(bool blocking, bool close_admins)
{
if (_network_server) {
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
cs->SendShutdown();
cs->SendPackets();
}
if (close_admins) {
ServerNetworkAdminSocketHandler *as;
FOR_ALL_ADMIN_SOCKETS(as) {
as->SendShutdown();
as->SendPackets();
}
}
}
if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking);
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
NetworkClose(close_admins);
/* Reinitialize the UDP stack, i.e. close all existing connections. */
NetworkUDPInitialize();
}
/**
* Receives something from the network.
* @return true if everthing went fine, false when the connection got closed.
*/
static bool NetworkReceive()
{
if (_network_server) {
ServerNetworkAdminSocketHandler::Receive();
return ServerNetworkGameSocketHandler::Receive();
} else {
return ClientNetworkGameSocketHandler::Receive();
}
}
/* This sends all buffered commands (if possible) */
static void NetworkSend()
{
if (_network_server) {
ServerNetworkAdminSocketHandler::Send();
ServerNetworkGameSocketHandler::Send();
} else {
ClientNetworkGameSocketHandler::Send();
}
}
/* We have to do some UDP checking */
void NetworkUDPGameLoop()
{
_network_content_client.SendReceive();
TCPConnecter::CheckCallbacks();
NetworkHTTPSocketHandler::HTTPReceive();
if (_network_udp_server) {
_udp_server_socket->ReceivePackets();
_udp_master_socket->ReceivePackets();
} else {
_udp_client_socket->ReceivePackets();
if (_network_udp_broadcast > 0) _network_udp_broadcast--;
NetworkGameListRequery();
}
}
/* The main loop called from ttd.c
* Here we also have to do StateGameLoop if needed! */
void NetworkGameLoop()
{
if (!_networking) return;
if (!NetworkReceive()) return;
if (_network_server) {
/* Log the sync state to check for in-syncedness of replays. */
if (_date_fract == 0) {
/* We don't want to log multiple times if paused. */
static Date last_log;
if (last_log != _date) {
DEBUG(desync, 1, "sync: %08x; %02x; %08x; %08x", _date, _date_fract, _random.state[0], _random.state[1]);
last_log = _date;
}
}
#ifdef DEBUG_DUMP_COMMANDS
/* Loading of the debug commands from -ddesync>=1 */
static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
static Date next_date = 0;
static uint32 next_date_fract;
static CommandPacket *cp = NULL;
static bool check_sync_state = false;
static uint32 sync_state[2];
if (f == NULL && next_date == 0) {
DEBUG(net, 0, "Cannot open commands.log");
next_date = 1;
}
while (f != NULL && !feof(f)) {
if (_date == next_date && _date_fract == next_date_fract) {
if (cp != NULL) {
NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, NULL, cp->text, cp->company);
DEBUG(net, 0, "injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd));
free(cp);
cp = NULL;
}
if (check_sync_state) {
if (sync_state[0] == _random.state[0] && sync_state[1] == _random.state[1]) {
DEBUG(net, 0, "sync check: %08x; %02x; match", _date, _date_fract);
} else {
DEBUG(net, 0, "sync check: %08x; %02x; mismatch expected {%08x, %08x}, got {%08x, %08x}",
_date, _date_fract, sync_state[0], sync_state[1], _random.state[0], _random.state[1]);
NOT_REACHED();
}
check_sync_state = false;
}
}
if (cp != NULL || check_sync_state) break;
char buff[4096];
if (fgets(buff, lengthof(buff), f) == NULL) break;
char *p = buff;
/* Ignore the "[date time] " part of the message */
if (*p == '[') {
p = strchr(p, ']');
if (p == NULL) break;
p += 2;
}
if (strncmp(p, "cmd: ", 5) == 0) {
cp = CallocT<CommandPacket>(1);
int company;
int ret = sscanf(p + 5, "%x; %x; %x; %x; %x; %x; %x; \"%[^\"]\"", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text);
/* There are 8 pieces of data to read, however the last is a
* string that might or might not exist. Ignore it if that
* string misses because in 99% of the time it's not used. */
assert(ret == 8 || ret == 7);
cp->company = (CompanyID)company;
} else if (strncmp(p, "join: ", 6) == 0) {
/* Manually insert a pause when joining; this way the client can join at the exact right time. */
int ret = sscanf(p + 6, "%x; %x", &next_date, &next_date_fract);
assert(ret == 2);
DEBUG(net, 0, "injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract);
cp = CallocT<CommandPacket>(1);
cp->company = COMPANY_SPECTATOR;
cp->cmd = CMD_PAUSE;
cp->p1 = PM_PAUSED_NORMAL;
cp->p2 = 1;
_ddc_fastforward = false;
} else if (strncmp(p, "sync: ", 6) == 0) {
int ret = sscanf(p + 6, "%x; %x; %x; %x", &next_date, &next_date_fract, &sync_state[0], &sync_state[1]);
assert(ret == 4);
check_sync_state = true;
} else if (strncmp(p, "msg: ", 5) == 0 || strncmp(p, "client: ", 8) == 0 ||
strncmp(p, "load: ", 6) == 0 || strncmp(p, "save: ", 6) == 0) {
/* A message that is not very important to the log playback, but part of the log. */
} else {
/* Can't parse a line; what's wrong here? */
DEBUG(net, 0, "trying to parse: %s", p);
NOT_REACHED();
}
}
if (f != NULL && feof(f)) {
DEBUG(net, 0, "End of commands.log");
fclose(f);
f = NULL;
}
#endif /* DEBUG_DUMP_COMMANDS */
if (_frame_counter >= _frame_counter_max) {
/* Only check for active clients just before we're going to send out
* the commands so we don't send multiple pause/unpause commands when
* the frame_freq is more than 1 tick. Same with distributing commands. */
CheckPauseOnJoin();
CheckMinActiveClients();
NetworkDistributeCommands();
}
bool send_frame = false;
/* We first increase the _frame_counter */
_frame_counter++;
/* Update max-frame-counter */
if (_frame_counter > _frame_counter_max) {
_frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
send_frame = true;
}
NetworkExecuteLocalCommandQueue();
/* Then we make the frame */
StateGameLoop();
_sync_seed_1 = _random.state[0];
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = _random.state[1];
#endif
NetworkServer_Tick(send_frame);
} else {
/* Client */
/* Make sure we are at the frame were the server is (quick-frames) */
if (_frame_counter_server > _frame_counter) {
/* Run a number of frames; when things go bad, get out. */
while (_frame_counter_server > _frame_counter) {
if (!ClientNetworkGameSocketHandler::GameLoop()) return;
}
} else {
/* Else, keep on going till _frame_counter_max */
if (_frame_counter_max > _frame_counter) {
/* Run one frame; if things went bad, get out. */
if (!ClientNetworkGameSocketHandler::GameLoop()) return;
}
}
}
NetworkSend();
}
static void NetworkGenerateServerId()
{
Md5 checksum;
uint8 digest[16];
char hex_output[16 * 2 + 1];
char coding_string[NETWORK_NAME_LENGTH];
int di;
snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Server ID");
/* Generate the MD5 hash */
checksum.Append((const uint8*)coding_string, strlen(coding_string));
checksum.Finish(digest);
for (di = 0; di < 16; ++di) {
sprintf(hex_output + di * 2, "%02x", digest[di]);
}
/* _settings_client.network.network_id is our id */
snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
}
void NetworkStartDebugLog(NetworkAddress address)
{
extern SOCKET _debug_socket; // Comes from debug.c
DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
SOCKET s = address.Connect();
if (s == INVALID_SOCKET) {
DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
return;
}
_debug_socket = s;
DEBUG(net, 0, "DEBUG() is now redirected");
}
/** This tries to launch the network for a given OS */
void NetworkStartUp()
{
DEBUG(net, 3, "[core] starting network...");
/* Network is available */
_network_available = NetworkCoreInitialize();
_network_dedicated = false;
_network_last_advertise_frame = 0;
_network_need_advertise = true;
_network_advertise_retries = 0;
/* Generate an server id when there is none yet */
if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateServerId();
memset(&_network_game_info, 0, sizeof(_network_game_info));
NetworkInitialize();
DEBUG(net, 3, "[core] network online, multiplayer available");
NetworkFindBroadcastIPs(&_broadcast_list);
}
/** This shuts the network down */
void NetworkShutDown()
{
NetworkDisconnect(true);
NetworkUDPClose();
DEBUG(net, 3, "[core] shutting down network");
_network_available = false;
NetworkCoreShutdown();
}
/**
* Checks whether the given version string is compatible with our version.
* @param other the version string to compare to
*/
bool IsNetworkCompatibleVersion(const char *other)
{
return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
}
#endif /* ENABLE_NETWORK */
| 32.168052 | 200 | 0.726305 | trademarks |
108f777d2cb40510cc2226292c9dfce7b944fbf2 | 739 | cc | C++ | game/AIDarylMatrix.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null | game/AIDarylMatrix.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null | game/AIDarylMatrix.cc | alvaroma94/EDA-Game | f1912f3e726a315e1a850d1a16081e9363bc2d65 | [
"MIT"
] | null | null | null |
#include "Player.hh"
using namespace std;
/**
* Escriu el nom * del teu jugador i guarda
* aquest fitxer amb el nom AI*.cc
*/
#define PLAYER_NAME DarylMatrix
/**
* Podeu declarar constants aquí
*/
struct PLAYER_NAME : public Player {
/**
* Factory: retorna una nova instància d'aquesta classe.
* No toqueu aquesta funció.
*/
static Player* factory () {
return new PLAYER_NAME;
}
/**
* Els atributs dels vostres jugadors es poden definir aquí.
*/
vector<vector<bool>> visit;
/**
* Mètode play.
*
* Aquest mètode serà invocat una vegada cada torn.
*/
virtual void play () {
}
};
/**
* No toqueu aquesta línia.
*/
RegisterPlayer(PLAYER_NAME);
| 12.741379 | 62 | 0.612991 | alvaroma94 |
10915f5776ebe6144a87326b65fd65bffff744c4 | 557 | cpp | C++ | Stream/MemoryInputStream.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | null | null | null | Stream/MemoryInputStream.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | 1 | 2017-11-14T16:56:26.000Z | 2017-11-20T02:00:23.000Z | Stream/MemoryInputStream.cpp | Unitrunker/Tile | 71b8b0e33bf8100090be6d9ac45e7d300f812cbc | [
"Apache-2.0"
] | 2 | 2017-11-14T14:18:51.000Z | 2019-06-16T11:58:47.000Z | #include "MemoryInputStream.h"
MemoryInputStream::MemoryInputStream(const unsigned char *memory, size_t limit) : _memory(memory), _limit(limit), _cursor(0)
{
}
bool MemoryInputStream::Read(unsigned char *pOctets, size_t iOctets, size_t &iRead)
{
size_t iRemains = _limit - _cursor;
if (iRemains > 0)
{
if (iOctets > iRemains)
iOctets = iRemains;
memcpy(pOctets, _memory + _cursor, iOctets);
iRead = iOctets;
_cursor += iOctets;
return true;
}
return false;
}
void MemoryInputStream::Close()
{
_cursor = 0;
}
| 20.62963 | 125 | 0.678636 | Unitrunker |
1092ea6194eb5bcf22ecb1c5b569bd637553e3f9 | 236 | cpp | C++ | component_solution/1.4/16.cpp | hsefz2018/NOIP-openjudge | b606d399b780959caadcf0094b90fa9163f30029 | [
"MIT"
] | 11 | 2016-02-03T11:13:07.000Z | 2021-05-30T04:37:02.000Z | 1.4/16.cpp | 20200117/noip-openjudge | 5c8b0786ea3fe2208ff9a44f244a631dbc5bb24c | [
"MIT"
] | 4 | 2015-08-18T10:52:33.000Z | 2015-10-29T12:51:52.000Z | 1.4/16.cpp | 20200117/noip-openjudge | 5c8b0786ea3fe2208ff9a44f244a631dbc5bb24c | [
"MIT"
] | 5 | 2016-02-03T11:13:09.000Z | 2019-07-10T13:25:59.000Z | #include <iostream>
#include <string>
#include <cmath>
using namespace std;
int main() {
long long a, b, c;
cin >> a >> b >> c;
cout << (((a + b > c) && (b + c > a) && (a + c > b)) ? "yes" : "no") << endl;
return 0;
}
| 18.153846 | 81 | 0.466102 | hsefz2018 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.