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
60e6f38df59b15ea527768e6be7dd7bebfabf8eb
411
cpp
C++
DataStructures/Arrays/2DMatrixTranspose.cpp
srivastavayushi/Interview-Preperation
c7fca371c885b9c1b26043450229ac9fe5f5d1ac
[ "MIT" ]
1
2021-05-26T18:01:16.000Z
2021-05-26T18:01:16.000Z
DataStructures/Arrays/2DMatrixTranspose.cpp
srivastavayushi/Interview-Preperation
c7fca371c885b9c1b26043450229ac9fe5f5d1ac
[ "MIT" ]
null
null
null
DataStructures/Arrays/2DMatrixTranspose.cpp
srivastavayushi/Interview-Preperation
c7fca371c885b9c1b26043450229ac9fe5f5d1ac
[ "MIT" ]
null
null
null
// Transpose of 2D Matrix #include <iostream> #include<array> using namespace std; int main(){ int arr[row][col]; cin>>row>>col; for(int i=0; i<row; i++){ for(int j=0;j<col;j++){ cin>>arr[row][col]; } } int array[col][row]; for(int i=0;i<col;i++){ for(int j=0;j<row;j++){ cout<<arr[row][col]=array[col][row]<<" "; } } }
18.681818
53
0.469586
srivastavayushi
60e74c1501eab4625e167fe06e0f36ec75d4182b
4,042
cpp
C++
apps/HelloAndroid/jni/native.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
7
2017-04-05T20:52:57.000Z
2018-11-26T10:07:10.000Z
apps/HelloAndroid/jni/native.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
10
2017-04-11T02:55:38.000Z
2019-06-27T18:13:36.000Z
apps/HelloAndroid/jni/native.cpp
jwitz54/Halide-2016-HLS
dd95daab3a7c871dd2f15c514912e21fb3c2bb7c
[ "MIT" ]
1
2020-07-10T16:00:39.000Z
2020-07-10T16:00:39.000Z
#include <jni.h> #include <android/log.h> #include <android/bitmap.h> #include <android/native_window_jni.h> #include <time.h> #include <string.h> #include <stdlib.h> #include "halide_generated.h" #include "HalideRuntime.h" #include "HalideRuntimeOpenCL.h" #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG,"halide_native",__VA_ARGS__) #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR,"halide_native",__VA_ARGS__) #define DEBUG 1 extern "C" void halide_set_error_handler(int (*handler)(void *user_context, const char *)); extern "C" int halide_host_cpu_count(); extern "C" int halide_start_clock(void *user_context); extern "C" int64_t halide_current_time_ns(); extern "C" int halide_copy_to_host(void *, buffer_t *); int handler(void */* user_context */, const char *msg) { LOGE("%s", msg); } extern "C" { JNIEXPORT void JNICALL Java_com_example_hellohalide_CameraPreview_processFrame( JNIEnv *env, jobject obj, jbyteArray jSrc, jint j_w, jint j_h, jint j_orientation, jobject surf) { const int w = j_w, h = j_h, orientation = j_orientation; halide_start_clock(NULL); halide_set_error_handler(handler); unsigned char *src = (unsigned char *)env->GetByteArrayElements(jSrc, NULL); if (!src) { LOGD("src is null\n"); return; } LOGD("[output window size] j_w = %d, j_h = %d", j_w, j_h); LOGD("[src array length] jSrc.length = %d", env->GetArrayLength(jSrc)); ANativeWindow *win = ANativeWindow_fromSurface(env, surf); static bool first_call = true; static unsigned counter = 0; static unsigned times[16]; if (first_call) { LOGD("According to Halide, host system has %d cpus\n", halide_host_cpu_count()); LOGD("Resetting buffer format"); ANativeWindow_setBuffersGeometry(win, w, h, 0); first_call = false; for (int t = 0; t < 16; t++) times[t] = 0; } ANativeWindow_Buffer buf; ARect rect = {0, 0, w, h}; if (int err = ANativeWindow_lock(win, &buf, NULL)) { LOGD("ANativeWindow_lock failed with error code %d\n", err); return; } uint8_t *dst = (uint8_t *)buf.bits; // If we're using opencl, use the gpu backend for it. #if COMPILING_FOR_OPENCL halide_opencl_set_device_type("gpu"); #endif // Make these static so that we can reuse device allocations across frames. static buffer_t srcBuf = {0}; static buffer_t dstBuf = {0}; if (dst) { srcBuf.host = (uint8_t *)src; srcBuf.host_dirty = true; srcBuf.extent[0] = w; srcBuf.extent[1] = h; srcBuf.extent[2] = 0; srcBuf.extent[3] = 0; srcBuf.stride[0] = 1; srcBuf.stride[1] = w; srcBuf.min[0] = 0; srcBuf.min[1] = 0; srcBuf.elem_size = 1; if (orientation >= 180) { // Camera sensor is probably upside down (e.g. Nexus 5x) srcBuf.host += w*h-1; srcBuf.stride[0] = -1; srcBuf.stride[1] = -w; } dstBuf.host = dst; dstBuf.extent[0] = w; dstBuf.extent[1] = h; dstBuf.extent[2] = 0; dstBuf.extent[3] = 0; dstBuf.stride[0] = 1; dstBuf.stride[1] = w; dstBuf.min[0] = 0; dstBuf.min[1] = 0; dstBuf.elem_size = 1; // Just set chroma to gray. memset(dst + w*h, 128, (w*h)/2); int64_t t1 = halide_current_time_ns(); halide_generated(&srcBuf, &dstBuf); if (dstBuf.dev) { halide_copy_to_host(NULL, &dstBuf); } int64_t t2 = halide_current_time_ns(); unsigned elapsed_us = (t2 - t1)/1000; times[counter & 15] = elapsed_us; counter++; unsigned min = times[0]; for (int i = 1; i < 16; i++) { if (times[i] < min) min = times[i]; } LOGD("Time taken: %d (%d)", elapsed_us, min); } ANativeWindow_unlockAndPost(win); ANativeWindow_release(win); env->ReleaseByteArrayElements(jSrc, (jbyte *)src, 0); } }
29.079137
102
0.607867
jwitz54
60e8c54e97e87900b1659b7f582cc54be08d7918
1,308
cpp
C++
lib/Target/AGC/AGCTargetObjectFile.cpp
lewis-revill/agc-llvm
3ea3042a7323b86631f5d45912970631e131b7fe
[ "Apache-2.0" ]
6
2019-02-13T15:15:12.000Z
2021-11-14T00:40:47.000Z
lib/Target/AGC/AGCTargetObjectFile.cpp
lewis-revill/agc-llvm
3ea3042a7323b86631f5d45912970631e131b7fe
[ "Apache-2.0" ]
null
null
null
lib/Target/AGC/AGCTargetObjectFile.cpp
lewis-revill/agc-llvm
3ea3042a7323b86631f5d45912970631e131b7fe
[ "Apache-2.0" ]
1
2021-11-14T00:40:27.000Z
2021-11-14T00:40:27.000Z
//===-- RISCVTargetObjectFile.cpp - RISCV Object Info ---------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "AGCTargetObjectFile.h" #include "AGCTargetMachine.h" #include "llvm/BinaryFormat/ELF.h" #include "llvm/MC/MCContext.h" using namespace llvm; void AGCELFTargetObjectFile::Initialize(MCContext &Ctx, const TargetMachine &TM) { TargetLoweringObjectFileELF::Initialize(Ctx, TM); InitializeELF(TM.Options.UseInitArray); TextSection = (MCSection *)Ctx.getELFSection( "BLOCK2", ELF::SHT_PROGBITS, ELF::SHF_EXECINSTR | ELF::SHF_ALLOC); } MCSection *AGCELFTargetObjectFile::SelectSectionForGlobal( const GlobalObject *GO, SectionKind Kind, const TargetMachine &TM) const { if (!Kind.isText()) return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM); const Function *F = dyn_cast<Function>(GO); if (!F || F->hasFnAttribute("implicit-section-name")) return TargetLoweringObjectFileELF::SelectSectionForGlobal(GO, Kind, TM); return TextSection; }
37.371429
80
0.670489
lewis-revill
60eb43c2bedfb51829ae7e72b5d4eab3a5c53239
3,237
cpp
C++
libraries/cor_system/sources/parallel_processor.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
4
2015-01-13T09:55:02.000Z
2016-09-10T03:42:23.000Z
libraries/cor_system/sources/parallel_processor.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
null
null
null
libraries/cor_system/sources/parallel_processor.cpp
rmake/cor-engine
d8920325db490d19dc8c116ab8e9620fe55e9975
[ "MIT" ]
2
2015-01-22T02:30:29.000Z
2021-05-10T06:56:49.000Z
#include "parallel_processor.h" #include <condition_variable> namespace cor { namespace system { struct ParallelProcessorItnl { std::vector<std::thread> threads; JobQueueSP thread_job_queue; JobQueueSP end_job_queue; std::mutex cnd_mutex; std::condition_variable cnd; std::mutex main_cnd_mutex; std::condition_variable main_cnd; std::mutex run_count_mutex; RSize run_count; ParallelProcessorItnl() { thread_job_queue = std::make_shared<JobQueue>(); end_job_queue = std::make_shared<JobQueue>(); run_count = 0; } }; ParallelProcessor::ParallelProcessor() : itnl(new ParallelProcessorItnl()) { set_threads(1); } ParallelProcessor::ParallelProcessor(RSize thread_count) : itnl(new ParallelProcessorItnl()) { set_threads(thread_count); } ParallelProcessor::~ParallelProcessor() { } void ParallelProcessor::set_threads(RSize thread_count) { for(RSize i = 0; i < thread_count; i++) { itnl->threads.push_back(std::thread([=](){ inc_run_count(); if(!itnl->thread_job_queue->empty()) { auto f = itnl->thread_job_queue->pop_job(); if(f) { f(); } } dec_run_count(); if(itnl->thread_job_queue->empty()) { std::unique_lock<std::mutex> l(itnl->cnd_mutex); itnl->main_cnd.notify_all(); itnl->cnd.wait(l); } })); } } void ParallelProcessor::inc_run_count() { std::lock_guard<std::mutex> locker(itnl->run_count_mutex); itnl->run_count++; } void ParallelProcessor::dec_run_count() { std::lock_guard<std::mutex> locker(itnl->run_count_mutex); itnl->run_count--; } void ParallelProcessor::get_run_count(std::function<void(RSize)> callback) { std::lock_guard<std::mutex> locker(itnl->run_count_mutex); callback(itnl->run_count); } void ParallelProcessor::run() { itnl->cnd.notify_all(); std::unique_lock<std::mutex> l(itnl->main_cnd_mutex); itnl->main_cnd.wait(l, [&](){ bool r; this->get_run_count([&](RSize ct){ r = ct <= 0; }); return r; }); } void ParallelProcessor::add_job(ThreadRunFunc run_func, ThreadEndFunc end_func) { itnl->thread_job_queue->add_job([=](){ run_func(); itnl->end_job_queue->add_job(end_func); }); } } }
27.905172
100
0.463701
rmake
60ee41e79385ab7c2c85208e24d2bd91c3e777c6
11,608
hpp
C++
src/hardware_layer/camera_calibration/include/camera/ocam/camera.hpp
robotic-mining-competition/NDSU2019
2f9a324d110fece78da3f42e2ae89a7fe198e6e3
[ "BSD-3-Clause" ]
1
2019-05-10T22:52:09.000Z
2019-05-10T22:52:09.000Z
src/hardware_layer/camera_calibration/include/camera/ocam/camera.hpp
robotic-mining-competition/NDSU2019
2f9a324d110fece78da3f42e2ae89a7fe198e6e3
[ "BSD-3-Clause" ]
null
null
null
src/hardware_layer/camera_calibration/include/camera/ocam/camera.hpp
robotic-mining-competition/NDSU2019
2f9a324d110fece78da3f42e2ae89a7fe198e6e3
[ "BSD-3-Clause" ]
null
null
null
/*******************************************************************************# # # # Withrobot Camera API # # # # Copyright (C) 2016 Withrobot. Inc. # # # # This program is free software: you can redistribute it and/or modify # # it under the terms of the GNU General Public License as published by # # the Free Software Foundation, either version 3 of the License, or # # (at your option) any later version. # # # # This program is distributed in the hope that it will be useful, # # but WITHOUT ANY WARRANTY; without even the implied warranty of # # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # # along with this program. If not, see <http://www.gnu.org/licenses/> # # # ********************************************************************************/ #ifndef OCAM_CAMERA_HPP_ #define OCAM_CAMERA_HPP_ #include <linux/videodev2.h> #include <sys/ioctl.h> #include <sys/mman.h> #include <libv4l2.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <assert.h> #include <memory.h> #include <vector> #include <string> #include <cstring> #include <map> #include <sstream> #include <stdio.h> #include "camera/ocam/utility.hpp" #define OCAM_CAMERA_DEFAULT_WIDTH 640 #define OCAM_CAMERA_DEFAULT_HEIGHT 480 #define OCAM_CAMERA_DEFAULT_FIXFORMAT V4L2_PIX_FMT_YUYV /* * DBG print */ #define PRINT_DEBUG_MSG /* When you want to show the debug messages remove the comment here. */ #ifdef PRINT_DEBUG_MSG #define DBG_PRINTF(...) {\ fprintf(stdout, "DBG: [%s, %d, %s] ", __FILE__, __LINE__, __FUNCTION__); \ fprintf(stdout, __VA_ARGS__); fprintf(stdout, "\n"); fflush(stdout); \ } #define DBG_PRINTF_MSG(...) { fprintf(stdout, __VA_ARGS__); fflush(stdout); } #define DBG_PERROR(...) { fflush(stdout); printf("DBG_ERR: [%s, %d, %s] ", __FILE__, __LINE__, __func__); fflush(stdout); perror(__VA_ARGS__); fflush(stdout); } #else #define DBG_PRINTF(...) #define DBG_PRINTF_MSG(...) #define DBG_PERROR(...) #endif /* PRINT_DEBUG_MSG */ /** * @defgroup Withrobot Camera API * @brief Withrobot inc. UVC type camera control API * * Withrobot UVC type camera control API * * @{ */ namespace ocam { /** * FOURCC ๋ฌธ์ž๋ฅผ pixel format ์ฝ”๋“œ๋กœ ๋ณ€ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜ * * e.g. fourcc_to_pixformat('Y', 'U', 'Y', 'V') * * @param a [์ž…๋ ฅ] first character * @param b [์ž…๋ ฅ] second character * @param c [์ž…๋ ฅ] third character * @param d [์ž…๋ ฅ] forth character * @return pixel_format ์ฝ”๋“œ */ inline static unsigned int fourcc_to_pixformat(const char a, const char b, const char c, const char d) { return (((unsigned int)a << 0)|((unsigned int)b << 8)|((unsigned int) c << 16)|((unsigned int)d << 24)); } /** * Camera control types */ enum camera_control_type { CAM_CTRL_TYPE_INTEGER = 1,//!< ์ •์ˆ˜ CAM_CTRL_TYPE_BOOLEAN = 2,//!< ๋ถˆ๋ฆฌ์–ธ CAM_CTRL_TYPE_MENU = 3,//!< ํ•˜์œ„ ๋ฉ”๋‰ด CAM_CTRL_TYPE_BUTTON = 4,//!< ๋ฒ„ํŠผ CAM_CTRL_TYPE_INTEGER64 = 5,//!< 64๋น„ํŠธ ์ •์ˆ˜ CAM_CTRL_TYPE_CTRL_CLASS = 6,//!< ์ปจํŠธ๋กค ํด๋ž˜์Šค CAM_CTRL_TYPE_STRING = 7,//!< ๋ฌธ์ž์—ด CAM_CTRL_TYPE_BITMASK = 8,//!< ๋น„ํŠธ ๋งˆ์Šคํฌ CAM_CTRL_TYPE_INTEGER_MENU = 9 //!< ์ •๋ถ€ ๋ฉ”๋‰ด }; /** * Camera control flags */ enum camera_control_flags { CAM_CTRL_FLAG_DISABLED = 1, //!< Disabled CAM_CTRL_FLAG_GRABBED = 2, //!< Grabbed CAM_CTRL_FLAG_READ_ONLY = 4, //!< Read only CAM_CTRL_FLAG_UPDATE = 8, //!< Update CAM_CTRL_FLAG_INACTIVE = 16,//!< Inactive CAM_CTRL_FLAG_SLIDER = 32,//!< Slider CAM_CTRL_FLAG_WRITE_ONLY = 64 //!< Wirte only }; /** * Camera image format structure */ struct camera_format { unsigned int pixformat; unsigned int width; unsigned int height; unsigned int image_size; unsigned int rate_numerator; unsigned int rate_denominator; double frame_rate; camera_format() { clear(); } void clear() { memset(this, 0, sizeof(*this)); } void print() { printf("Pixel format: %c, %c, %c, %c\n", (pixformat >> 0) & 0xFF, (pixformat >> 8) & 0xFF, (pixformat >> 16) & 0xff, (pixformat >> 24) & 0xFF); printf("Width: %d, Height: %d, Image size: %d\n", width, height, image_size); printf("Frame Rate : %d / %d (%.2f fps)\n", rate_numerator, rate_denominator, frame_rate); } void dbg_print() { DBG_PRINTF("Pixel format: %c, %c, %c, %c", (pixformat >> 0) & 0xFF, (pixformat >> 8) & 0xFF, (pixformat >> 16) & 0xff, (pixformat >> 24) & 0xFF); DBG_PRINTF("Width: %d, Height: %d, Image size: %d", width, height, image_size); DBG_PRINTF("Frame Rate : %d / %d (%.2f fps)", rate_numerator, rate_denominator, frame_rate); } }; /** * Camera control menu structure */ struct camera_control_menu { unsigned int index; char name[256]; int value; camera_control_menu() { clear(); } void clear() { memset(this, 0, sizeof(*this)); } void dbg_print() { DBG_PRINTF("Index: %d, Name: %s, Value: %d", index, name, value); } }; /** * Camera control structure */ struct camera_control { unsigned int id; //char name[256]; std::string name; int value; int default_value; unsigned int type; unsigned int flags; int minimum; int maximum; int step; std::vector<camera_control_menu> menu_list; camera_control() { clear(); } void clear() { memset(this, 0, sizeof(*this)); } void dbg_print() { DBG_PRINTF("Id: %u, Name: %s, Value(default [min, step, max]): %d ( %d [%d, %d, %d] ), Type: %d, Flag: %d", id, name.c_str(), value, default_value, minimum, step, maximum, type, flags); for (unsigned int i=0; i < menu_list.size(); i++) { DBG_PRINTF("Menu %d", i); menu_list[i].dbg_print(); } } }; /** * Camera Class */ class Camera { public: /* * oCam-1MGN * * [ supported image formats ] * * USB 3.0 * [1] "8-bit Greyscale 1280 x 720 60 fps" * [2] "8-bit Greyscale 1280 x 960 45 fps" * [3] "8-bit Greyscale 320 x 240 160 fps" * [4] "8-bit Greyscale 640 x 480 80 fps" * * USB 2.0 * [1] "8-bit Greyscale 1280 x 720 30 fps" * [2] "8-bit Greyscale 1280 x 960 22.5 fps" * [3] "8-bit Greyscale 320 x 240 160 fps" * [4] "8-bit Greyscale 640 x 480 80 fps" * * * [ supported camera controls; The double quotes are the 'get_control' and the 'set_control' function string argument values. ] * * [1] "Exposure (Absolute)", Value(default [min, step, max]): 39 ( 39 [1, 1, 625] ) * [2] "Brightness", Value(default [min, step, max]): 64 ( 64 [0, 1, 127] ) // gain * */ Camera(const char* dev_name, struct camera_format* conf=0, const char* format_string=0, const unsigned char disable_libv4l2=0); ~Camera(); bool start(); bool stop(); void get_configurations(std::vector<std::string>& formats, std::vector<std::string>& controls); bool get_current_format(camera_format& fmt); int get_frame(unsigned char* out_buffer, const unsigned int size, unsigned int timeout_sec=1); bool set_format(const char* format_description); bool set_format(unsigned int width, unsigned int height, unsigned int pixelformat, unsigned int rate_numerator=0, unsigned int rate_denomonator=0); bool get_control(camera_control& ctrl); int get_control(const char* name); bool set_control(const char* name, const int value); int valid_controls(std::vector<std::pair<const char*, unsigned int> >& list); int get_valid_image_format_list(std::vector<const char*>& list); int get_valid_resolution_list(const char* format_description, std::vector<const char*>& list); int get_valid_ratio_list(const char* resolution_description, std::vector<const char*>& list); /** * ๋™์ž‘์ค‘(streaming) ์—ฌ๋ถ€ ํ™•์ธ ํ•จ์ˆ˜ * @return streaming status */ inline bool is_running() { return streaming; } /** * ์žฅ์น˜ ์ด๋ฆ„ ์ œ๊ณต ํ•จ์ˆ˜ * @return device name */ inline std::string get_dev_name() { return std::string((const char*) v4l2_s.capability.card); } std::string get_serial_number(); private: struct _buffer { unsigned char* buffer; unsigned int length; }; struct _v4l2 { enum v4l2_buf_type buf_type; struct v4l2_capability capability; struct v4l2_format format; struct v4l2_requestbuffers requestbuffers; struct v4l2_buffer buffer; struct v4l2_queryctrl queryctrl; struct v4l2_querymenu querymenu; struct v4l2_fmtdesc fmtdesc; struct v4l2_frmsizeenum frmsizeenum; struct v4l2_frmivalenum frmivalenum; struct v4l2_streamparm streamparm; }; private: std::string dev_name; int fd; _v4l2 v4l2_s; _buffer* buffers; unsigned int buffer_count; unsigned char disable_libv4l2; /* set to 1 to disable libv4l2 calls */ std::map<std::string, v4l2_queryctrl> valid_control_list; std::map<std::string, v4l2_fmtdesc> valid_format_list; std::map<std::string, v4l2_frmsizeenum> valid_resolution_list; std::map<std::string, v4l2_frmivalenum> valid_ratio_list; std::vector<usb_device_info> usb_device_list; struct camera_format config; bool streaming; Mutex mutex; private: bool get_capability(); bool get_current_format(); bool set_buffer(); void check_essential_capability(); int enumerate_controls(); int enumerate_control_menu(); bool enumerate_image_formats(const enum v4l2_buf_type type); bool enumerate_frame_sizes(const unsigned int pixelformat, std::string& description); bool enumerate_frame_intervals(const unsigned int pixelformat, const unsigned int width, const unsigned int height, std::string& description); int get_buffer(unsigned char* yuy2_buffer, const unsigned int size); bool remove_buffers(); int xioctl(int IOCTL_X, void *arg); int query_ioctl(int current_ctrl, struct v4l2_queryctrl* ctrl); }; } /* namespace ocam */ /** @} */ // end of ocam #endif /* OCAM_CAMERA_HPP_ */
34.041056
160
0.562112
robotic-mining-competition
60f2510bf8276b0b3f53231b15e7d5b648234e56
1,605
cpp
C++
test/for_each.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
13
2017-10-24T07:13:28.000Z
2020-10-07T02:51:31.000Z
test/for_each.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
1
2019-10-30T21:50:44.000Z
2019-11-06T19:35:23.000Z
test/for_each.cpp
romariorios/coruja
275d1b05cdefd4d8e7665bb7bb37dbe15de3e9af
[ "BSL-1.0" ]
5
2018-09-19T20:29:07.000Z
2020-03-20T18:12:09.000Z
// Copyright Ricardo Calheiros de Miranda Cosme 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE or copy at // http://www.boost.org/LICENSE_1_0.txt) #include <coruja/object/object.hpp> #include <coruja/object/for_each.hpp> #include <coruja/object/view/transform.hpp> #include <boost/core/lightweight_test.hpp> #include <string> using namespace coruja; struct F { void operator()(bool o) const { b1 = true; } void operator()(std::string o) const { b2 = true; } bool &b1, &b2; }; int main() { { object<bool> o1{false}, o2{true}; object<std::string> o3{"abc"}; bool b1{false}, b2{false}; auto c = for_each(F{b1, b2}, o1, o2, o3); BOOST_TEST(b1); BOOST_TEST(b2); b1 = b2 = false; o1 = true; BOOST_TEST(b1); b1 = false; o2 = true; BOOST_TEST(b1); b1 = false; o3 = "def"; BOOST_TEST(b2); b2 = false; c.disconnect(); o1 = true; BOOST_TEST(!b1); o2 = true; BOOST_TEST(!b1); o3 = "ghi"; BOOST_TEST(!b2); } //ObservableObject as an rvalue { object<bool> o1{false}; bool b1{false}, b2{false}; for_each(F{b1, b2}, o1, view::transform(o1, [](bool v) -> std::string {return v ? "true" : "false";})); BOOST_TEST(b1); BOOST_TEST(b2); b1 = b2 = false; o1 = true; BOOST_TEST(b2); b2 = false; } }
23.26087
62
0.519003
romariorios
60f384d5c04fa91714da56a58c682b3f8d66ec0a
18,218
hpp
C++
include/System/ComponentModel/PropertyDescriptor.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/PropertyDescriptor.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
null
null
null
include/System/ComponentModel/PropertyDescriptor.hpp
v0idp/virtuoso-codegen
6f560f04822c67f092d438a3f484249072c1d21d
[ "Unlicense" ]
1
2022-03-30T21:07:35.000Z
2022-03-30T21:07:35.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ComponentModel.MemberDescriptor #include "System/ComponentModel/MemberDescriptor.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-array.hpp" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::ComponentModel namespace System::ComponentModel { // Forward declaring type: TypeConverter class TypeConverter; } // Forward declaring namespace: System::Collections namespace System::Collections { // Forward declaring type: Hashtable class Hashtable; // Forward declaring type: IList class IList; } // Forward declaring namespace: System namespace System { // Forward declaring type: Type class Type; // Forward declaring type: EventArgs class EventArgs; // Forward declaring type: Attribute class Attribute; } // Completed forward declares // Type namespace: System.ComponentModel namespace System::ComponentModel { // Forward declaring type: PropertyDescriptor class PropertyDescriptor; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::System::ComponentModel::PropertyDescriptor); DEFINE_IL2CPP_ARG_TYPE(::System::ComponentModel::PropertyDescriptor*, "System.ComponentModel", "PropertyDescriptor"); // Type namespace: System.ComponentModel namespace System::ComponentModel { // Size: 0x84 #pragma pack(push, 1) // Autogenerated type: System.ComponentModel.PropertyDescriptor // [TokenAttribute] Offset: FFFFFFFF // [ComVisibleAttribute] Offset: 69CEEC class PropertyDescriptor : public ::System::ComponentModel::MemberDescriptor { public: public: // private System.ComponentModel.TypeConverter converter // Size: 0x8 // Offset: 0x60 ::System::ComponentModel::TypeConverter* converter; // Field size check static_assert(sizeof(::System::ComponentModel::TypeConverter*) == 0x8); // private System.Collections.Hashtable valueChangedHandlers // Size: 0x8 // Offset: 0x68 ::System::Collections::Hashtable* valueChangedHandlers; // Field size check static_assert(sizeof(::System::Collections::Hashtable*) == 0x8); // private System.Object[] editors // Size: 0x8 // Offset: 0x70 ::ArrayW<::Il2CppObject*> editors; // Field size check static_assert(sizeof(::ArrayW<::Il2CppObject*>) == 0x8); // private System.Type[] editorTypes // Size: 0x8 // Offset: 0x78 ::ArrayW<::System::Type*> editorTypes; // Field size check static_assert(sizeof(::ArrayW<::System::Type*>) == 0x8); // private System.Int32 editorCount // Size: 0x4 // Offset: 0x80 int editorCount; // Field size check static_assert(sizeof(int) == 0x4); public: // Get instance field reference: private System.ComponentModel.TypeConverter converter [[deprecated("Use field access instead!")]] ::System::ComponentModel::TypeConverter*& dyn_converter(); // Get instance field reference: private System.Collections.Hashtable valueChangedHandlers [[deprecated("Use field access instead!")]] ::System::Collections::Hashtable*& dyn_valueChangedHandlers(); // Get instance field reference: private System.Object[] editors [[deprecated("Use field access instead!")]] ::ArrayW<::Il2CppObject*>& dyn_editors(); // Get instance field reference: private System.Type[] editorTypes [[deprecated("Use field access instead!")]] ::ArrayW<::System::Type*>& dyn_editorTypes(); // Get instance field reference: private System.Int32 editorCount [[deprecated("Use field access instead!")]] int& dyn_editorCount(); // public System.Type get_ComponentType() // Offset: 0xFFFFFFFFFFFFFFFF ::System::Type* get_ComponentType(); // public System.ComponentModel.TypeConverter get_Converter() // Offset: 0x140A360 ::System::ComponentModel::TypeConverter* get_Converter(); // public System.Boolean get_IsReadOnly() // Offset: 0xFFFFFFFFFFFFFFFF bool get_IsReadOnly(); // public System.Type get_PropertyType() // Offset: 0xFFFFFFFFFFFFFFFF ::System::Type* get_PropertyType(); // protected System.Object CreateInstance(System.Type type) // Offset: 0x140A7D0 ::Il2CppObject* CreateInstance(::System::Type* type); // protected System.Type GetTypeFromName(System.String typeName) // Offset: 0x140A5C0 ::System::Type* GetTypeFromName(::StringW typeName); // public System.Object GetValue(System.Object component) // Offset: 0xFFFFFFFFFFFFFFFF ::Il2CppObject* GetValue(::Il2CppObject* component); // protected System.Void OnValueChanged(System.Object component, System.EventArgs e) // Offset: 0x140AD6C void OnValueChanged(::Il2CppObject* component, ::System::EventArgs* e); // public System.Void SetValue(System.Object component, System.Object value) // Offset: 0xFFFFFFFFFFFFFFFF void SetValue(::Il2CppObject* component, ::Il2CppObject* value); // public System.Boolean ShouldSerializeValue(System.Object component) // Offset: 0xFFFFFFFFFFFFFFFF bool ShouldSerializeValue(::Il2CppObject* component); // protected System.Void .ctor(System.String name, System.Attribute[] attrs) // Offset: 0x140A350 // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Void MemberDescriptor::.ctor(System.String name, System.Attribute[] attrs) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PropertyDescriptor* New_ctor(::StringW name, ::ArrayW<::System::Attribute*> attrs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::ComponentModel::PropertyDescriptor::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PropertyDescriptor*, creationType>(name, attrs))); } // protected System.Void .ctor(System.ComponentModel.MemberDescriptor descr, System.Attribute[] attrs) // Offset: 0x140A358 // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Void MemberDescriptor::.ctor(System.ComponentModel.MemberDescriptor descr, System.Attribute[] attrs) template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static PropertyDescriptor* New_ctor(::System::ComponentModel::MemberDescriptor* descr, ::ArrayW<::System::Attribute*> attrs) { static auto ___internal__logger = ::Logger::get().WithContext("::System::ComponentModel::PropertyDescriptor::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<PropertyDescriptor*, creationType>(descr, attrs))); } // public override System.Boolean Equals(System.Object obj) // Offset: 0x140AA00 // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Boolean MemberDescriptor::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // protected override System.Void FillAttributes(System.Collections.IList attributeList) // Offset: 0x140AC0C // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Void MemberDescriptor::FillAttributes(System.Collections.IList attributeList) void FillAttributes(::System::Collections::IList* attributeList); // public override System.Int32 GetHashCode() // Offset: 0x140AC20 // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Int32 MemberDescriptor::GetHashCode() int GetHashCode(); // protected override System.Object GetInvocationTarget(System.Type type, System.Object instance) // Offset: 0x140AC78 // Implemented from: System.ComponentModel.MemberDescriptor // Base method: System.Object MemberDescriptor::GetInvocationTarget(System.Type type, System.Object instance) ::Il2CppObject* GetInvocationTarget(::System::Type* type, ::Il2CppObject* instance); }; // System.ComponentModel.PropertyDescriptor #pragma pack(pop) static check_size<sizeof(PropertyDescriptor), 128 + sizeof(int)> __System_ComponentModel_PropertyDescriptorSizeCheck; static_assert(sizeof(PropertyDescriptor) == 0x84); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::get_ComponentType // Il2CppName: get_ComponentType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (System::ComponentModel::PropertyDescriptor::*)()>(&System::ComponentModel::PropertyDescriptor::get_ComponentType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "get_ComponentType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::get_Converter // Il2CppName: get_Converter template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::ComponentModel::TypeConverter* (System::ComponentModel::PropertyDescriptor::*)()>(&System::ComponentModel::PropertyDescriptor::get_Converter)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "get_Converter", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::get_IsReadOnly // Il2CppName: get_IsReadOnly template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::ComponentModel::PropertyDescriptor::*)()>(&System::ComponentModel::PropertyDescriptor::get_IsReadOnly)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "get_IsReadOnly", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::get_PropertyType // Il2CppName: get_PropertyType template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (System::ComponentModel::PropertyDescriptor::*)()>(&System::ComponentModel::PropertyDescriptor::get_PropertyType)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "get_PropertyType", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::CreateInstance // Il2CppName: CreateInstance template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::ComponentModel::PropertyDescriptor::*)(::System::Type*)>(&System::ComponentModel::PropertyDescriptor::CreateInstance)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "CreateInstance", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::GetTypeFromName // Il2CppName: GetTypeFromName template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::System::Type* (System::ComponentModel::PropertyDescriptor::*)(::StringW)>(&System::ComponentModel::PropertyDescriptor::GetTypeFromName)> { static const MethodInfo* get() { static auto* typeName = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "GetTypeFromName", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{typeName}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::GetValue // Il2CppName: GetValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::ComponentModel::PropertyDescriptor::*)(::Il2CppObject*)>(&System::ComponentModel::PropertyDescriptor::GetValue)> { static const MethodInfo* get() { static auto* component = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "GetValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{component}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::OnValueChanged // Il2CppName: OnValueChanged template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::ComponentModel::PropertyDescriptor::*)(::Il2CppObject*, ::System::EventArgs*)>(&System::ComponentModel::PropertyDescriptor::OnValueChanged)> { static const MethodInfo* get() { static auto* component = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* e = &::il2cpp_utils::GetClassFromName("System", "EventArgs")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "OnValueChanged", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{component, e}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::SetValue // Il2CppName: SetValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::ComponentModel::PropertyDescriptor::*)(::Il2CppObject*, ::Il2CppObject*)>(&System::ComponentModel::PropertyDescriptor::SetValue)> { static const MethodInfo* get() { static auto* component = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; static auto* value = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "SetValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{component, value}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::ShouldSerializeValue // Il2CppName: ShouldSerializeValue template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::ComponentModel::PropertyDescriptor::*)(::Il2CppObject*)>(&System::ComponentModel::PropertyDescriptor::ShouldSerializeValue)> { static const MethodInfo* get() { static auto* component = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "ShouldSerializeValue", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{component}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead! // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::Equals // Il2CppName: Equals template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (System::ComponentModel::PropertyDescriptor::*)(::Il2CppObject*)>(&System::ComponentModel::PropertyDescriptor::Equals)> { static const MethodInfo* get() { static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "Equals", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{obj}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::FillAttributes // Il2CppName: FillAttributes template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (System::ComponentModel::PropertyDescriptor::*)(::System::Collections::IList*)>(&System::ComponentModel::PropertyDescriptor::FillAttributes)> { static const MethodInfo* get() { static auto* attributeList = &::il2cpp_utils::GetClassFromName("System.Collections", "IList")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "FillAttributes", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{attributeList}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::GetHashCode // Il2CppName: GetHashCode template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<int (System::ComponentModel::PropertyDescriptor::*)()>(&System::ComponentModel::PropertyDescriptor::GetHashCode)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "GetHashCode", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: System::ComponentModel::PropertyDescriptor::GetInvocationTarget // Il2CppName: GetInvocationTarget template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (System::ComponentModel::PropertyDescriptor::*)(::System::Type*, ::Il2CppObject*)>(&System::ComponentModel::PropertyDescriptor::GetInvocationTarget)> { static const MethodInfo* get() { static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg; static auto* instance = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg; return ::il2cpp_utils::FindMethod(classof(System::ComponentModel::PropertyDescriptor*), "GetInvocationTarget", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, instance}); } };
59.731148
236
0.753156
v0idp
60f3d824d18770e16cc359ff485cedefdfc756d0
199,284
inl
C++
Effects11/EffectVariable.inl
sysu-Beadle/LXQ-Engine
f8594f5f11df17af7052e49aa4ca4f0297b6de29
[ "MIT" ]
1
2021-05-12T08:59:01.000Z
2021-05-12T08:59:01.000Z
Effects11/EffectVariable.inl
sysu-Beadle/LXQ-Engine
f8594f5f11df17af7052e49aa4ca4f0297b6de29
[ "MIT" ]
null
null
null
Effects11/EffectVariable.inl
sysu-Beadle/LXQ-Engine
f8594f5f11df17af7052e49aa4ca4f0297b6de29
[ "MIT" ]
null
null
null
//-------------------------------------------------------------------------------------- // File: EffectVariable.inl // // Direct3D 11 Effects Variable reflection template // These templates define the many Effect variable types. // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. // // Copyright (c) Microsoft Corporation. All rights reserved. // // http://go.microsoft.com/fwlink/p/?LinkId=271568 //-------------------------------------------------------------------------------------- #pragma warning(push) #pragma warning(disable : 4127) ////////////////////////////////////////////////////////////////////////// // Invalid variable forward defines ////////////////////////////////////////////////////////////////////////// struct SEffectInvalidScalarVariable; struct SEffectInvalidVectorVariable; struct SEffectInvalidMatrixVariable; struct SEffectInvalidStringVariable; struct SEffectInvalidClassInstanceVariable; struct SEffectInvalidInterfaceVariable; struct SEffectInvalidShaderResourceVariable; struct SEffectInvalidUnorderedAccessViewVariable; struct SEffectInvalidRenderTargetViewVariable; struct SEffectInvalidDepthStencilViewVariable; struct SEffectInvalidConstantBuffer; struct SEffectInvalidShaderVariable; struct SEffectInvalidBlendVariable; struct SEffectInvalidDepthStencilVariable; struct SEffectInvalidRasterizerVariable; struct SEffectInvalidSamplerVariable; struct SEffectInvalidTechnique; struct SEffectInvalidPass; struct SEffectInvalidType; extern SEffectInvalidScalarVariable g_InvalidScalarVariable; extern SEffectInvalidVectorVariable g_InvalidVectorVariable; extern SEffectInvalidMatrixVariable g_InvalidMatrixVariable; extern SEffectInvalidStringVariable g_InvalidStringVariable; extern SEffectInvalidClassInstanceVariable g_InvalidClassInstanceVariable; extern SEffectInvalidInterfaceVariable g_InvalidInterfaceVariable; extern SEffectInvalidShaderResourceVariable g_InvalidShaderResourceVariable; extern SEffectInvalidUnorderedAccessViewVariable g_InvalidUnorderedAccessViewVariable; extern SEffectInvalidRenderTargetViewVariable g_InvalidRenderTargetViewVariable; extern SEffectInvalidDepthStencilViewVariable g_InvalidDepthStencilViewVariable; extern SEffectInvalidConstantBuffer g_InvalidConstantBuffer; extern SEffectInvalidShaderVariable g_InvalidShaderVariable; extern SEffectInvalidBlendVariable g_InvalidBlendVariable; extern SEffectInvalidDepthStencilVariable g_InvalidDepthStencilVariable; extern SEffectInvalidRasterizerVariable g_InvalidRasterizerVariable; extern SEffectInvalidSamplerVariable g_InvalidSamplerVariable; extern SEffectInvalidTechnique g_InvalidTechnique; extern SEffectInvalidPass g_InvalidPass; extern SEffectInvalidType g_InvalidType; enum ETemplateVarType { ETVT_Bool, ETVT_Int, ETVT_Float, ETVT_bool }; ////////////////////////////////////////////////////////////////////////// // Invalid effect variable struct definitions ////////////////////////////////////////////////////////////////////////// struct SEffectInvalidType : public ID3DX11EffectType { STDMETHOD_(bool, IsValid)() override { return false; } STDMETHOD(GetDesc)(_Out_ D3DX11_EFFECT_TYPE_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidType; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidType; } STDMETHOD_(ID3DX11EffectType*, GetMemberTypeBySemantic)(_In_z_ LPCSTR Semantic) override { UNREFERENCED_PARAMETER(Semantic); return &g_InvalidType; } STDMETHOD_(LPCSTR, GetMemberName)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return nullptr; } STDMETHOD_(LPCSTR, GetMemberSemantic)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return nullptr; } IUNKNOWN_IMP(SEffectInvalidType, ID3DX11EffectType, IUnknown); }; template<typename IBaseInterface> struct TEffectInvalidVariable : public IBaseInterface { public: STDMETHOD_(bool, IsValid)() override { return false; } STDMETHOD_(ID3DX11EffectType*, GetType)() override { return &g_InvalidType; } STDMETHOD(GetDesc)(_Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(_In_z_ LPCSTR Semantic) override { UNREFERENCED_PARAMETER(Semantic); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetElement)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() override { return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() override { return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() override { return &g_InvalidVectorVariable; } STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() override { return &g_InvalidMatrixVariable; } STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() override { return &g_InvalidStringVariable; } STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() override { return &g_InvalidClassInstanceVariable; } STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() override { return &g_InvalidInterfaceVariable; } STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() override { return &g_InvalidShaderResourceVariable; } STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() override { return &g_InvalidUnorderedAccessViewVariable; } STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() override { return &g_InvalidRenderTargetViewVariable; } STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() override { return &g_InvalidDepthStencilViewVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() override { return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() override { return &g_InvalidShaderVariable; } STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() override { return &g_InvalidBlendVariable; } STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() override { return &g_InvalidDepthStencilVariable; } STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() override { return &g_InvalidRasterizerVariable; } STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() override { return &g_InvalidSamplerVariable; } STDMETHOD(SetRawValue)(_In_reads_bytes_(Count) const void *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetRawValue)(_Out_writes_bytes_(Count) void *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } }; struct SEffectInvalidScalarVariable : public TEffectInvalidVariable<ID3DX11EffectScalarVariable> { public: STDMETHOD(SetFloat)(_In_ const float Value) override { UNREFERENCED_PARAMETER(Value); return E_FAIL; } STDMETHOD(GetFloat)(_Out_ float *pValue) override { UNREFERENCED_PARAMETER(pValue); return E_FAIL; } STDMETHOD(SetFloatArray)(_In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetFloatArray)(_Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(SetInt)(_In_ const int Value) override { UNREFERENCED_PARAMETER(Value); return E_FAIL; } STDMETHOD(GetInt)(_Out_ int *pValue) override { UNREFERENCED_PARAMETER(pValue); return E_FAIL; } STDMETHOD(SetIntArray)(_In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetIntArray)(_Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(SetBool)(_In_ const bool Value) override { UNREFERENCED_PARAMETER(Value); return E_FAIL; } STDMETHOD(GetBool)(_Out_ bool *pValue) override { UNREFERENCED_PARAMETER(pValue); return E_FAIL; } STDMETHOD(SetBoolArray)(_In_reads_(Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetBoolArray)(_Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidScalarVariable, ID3DX11EffectScalarVariable, ID3DX11EffectVariable); }; struct SEffectInvalidVectorVariable : public TEffectInvalidVariable<ID3DX11EffectVectorVariable> { public: STDMETHOD(SetFloatVector)(_In_reads_(4) const float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(SetIntVector)(_In_reads_(4) const int *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(SetBoolVector)(_In_reads_(4) const bool *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(GetFloatVector)(_Out_writes_(4) float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(GetIntVector)(_Out_writes_(4) int *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(GetBoolVector)(_Out_writes_(4) bool *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; }; STDMETHOD(SetBoolVectorArray) (_In_reads_(4*Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; STDMETHOD(SetIntVectorArray) (_In_reads_(4*Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; STDMETHOD(SetFloatVectorArray)(_In_reads_(4*Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; STDMETHOD(GetBoolVectorArray) (_Out_writes_(4*Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; STDMETHOD(GetIntVectorArray) (_Out_writes_(4*Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; STDMETHOD(GetFloatVectorArray)(_Out_writes_(4*Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; }; IUNKNOWN_IMP(SEffectInvalidVectorVariable, ID3DX11EffectVectorVariable, ID3DX11EffectVariable); }; struct SEffectInvalidMatrixVariable : public TEffectInvalidVariable<ID3DX11EffectMatrixVariable> { public: STDMETHOD(SetMatrix)(_In_reads_(16) const float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; } STDMETHOD(GetMatrix)(_Out_writes_(16) float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; } STDMETHOD(SetMatrixArray)(_In_reads_(16*Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetMatrixArray)(_Out_writes_(16*Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(SetMatrixPointerArray)(_In_reads_(16*Count) const float **ppData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetMatrixPointerArray)(_Out_writes_(16*Count) float **ppData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(SetMatrixTranspose)(_In_reads_(16) const float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; } STDMETHOD(GetMatrixTranspose)(_Out_writes_(16) float *pData) override { UNREFERENCED_PARAMETER(pData); return E_FAIL; } STDMETHOD(SetMatrixTransposeArray)(_In_reads_(16*Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetMatrixTransposeArray)(_Out_writes_(16*Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(SetMatrixTransposePointerArray)(_In_reads_(16*Count) const float **ppData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetMatrixTransposePointerArray)(_Out_writes_(16*Count) float **ppData, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidMatrixVariable, ID3DX11EffectMatrixVariable, ID3DX11EffectVariable); }; struct SEffectInvalidStringVariable : public TEffectInvalidVariable<ID3DX11EffectStringVariable> { public: STDMETHOD(GetString)(_Outptr_result_z_ LPCSTR *ppString) override { UNREFERENCED_PARAMETER(ppString); return E_FAIL; } STDMETHOD(GetStringArray)(_Out_writes_(Count) LPCSTR *ppStrings, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppStrings); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidStringVariable, ID3DX11EffectStringVariable, ID3DX11EffectVariable); }; struct SEffectInvalidClassInstanceVariable : public TEffectInvalidVariable<ID3DX11EffectClassInstanceVariable> { public: STDMETHOD(GetClassInstance)(_Outptr_ ID3D11ClassInstance **ppClassInstance) override { UNREFERENCED_PARAMETER(ppClassInstance); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidClassInstanceVariable, ID3DX11EffectClassInstanceVariable, ID3DX11EffectVariable); }; struct SEffectInvalidInterfaceVariable : public TEffectInvalidVariable<ID3DX11EffectInterfaceVariable> { public: STDMETHOD(SetClassInstance)(_In_ ID3DX11EffectClassInstanceVariable *pEffectClassInstance) override { UNREFERENCED_PARAMETER(pEffectClassInstance); return E_FAIL; } STDMETHOD(GetClassInstance)(_Outptr_ ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) override { UNREFERENCED_PARAMETER(ppEffectClassInstance); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidInterfaceVariable, ID3DX11EffectInterfaceVariable, ID3DX11EffectVariable); }; struct SEffectInvalidShaderResourceVariable : public TEffectInvalidVariable<ID3DX11EffectShaderResourceVariable> { public: STDMETHOD(SetResource)(_In_ ID3D11ShaderResourceView *pResource) override { UNREFERENCED_PARAMETER(pResource); return E_FAIL; } STDMETHOD(GetResource)(_Outptr_ ID3D11ShaderResourceView **ppResource) override { UNREFERENCED_PARAMETER(ppResource); return E_FAIL; } STDMETHOD(SetResourceArray)(_In_reads_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetResourceArray)(_Out_writes_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidShaderResourceVariable, ID3DX11EffectShaderResourceVariable, ID3DX11EffectVariable); }; struct SEffectInvalidUnorderedAccessViewVariable : public TEffectInvalidVariable<ID3DX11EffectUnorderedAccessViewVariable> { public: STDMETHOD(SetUnorderedAccessView)(_In_ ID3D11UnorderedAccessView *pResource) override { UNREFERENCED_PARAMETER(pResource); return E_FAIL; } STDMETHOD(GetUnorderedAccessView)(_Outptr_ ID3D11UnorderedAccessView **ppResource) override { UNREFERENCED_PARAMETER(ppResource); return E_FAIL; } STDMETHOD(SetUnorderedAccessViewArray)(_In_reads_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetUnorderedAccessViewArray)(_Out_writes_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidUnorderedAccessViewVariable, ID3DX11EffectUnorderedAccessViewVariable, ID3DX11EffectVariable); }; struct SEffectInvalidRenderTargetViewVariable : public TEffectInvalidVariable<ID3DX11EffectRenderTargetViewVariable> { public: STDMETHOD(SetRenderTarget)(_In_ ID3D11RenderTargetView *pResource) override { UNREFERENCED_PARAMETER(pResource); return E_FAIL; } STDMETHOD(GetRenderTarget)(_Outptr_ ID3D11RenderTargetView **ppResource) override { UNREFERENCED_PARAMETER(ppResource); return E_FAIL; } STDMETHOD(SetRenderTargetArray)(_In_reads_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetRenderTargetArray)(_Out_writes_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidRenderTargetViewVariable, ID3DX11EffectRenderTargetViewVariable, ID3DX11EffectVariable); }; struct SEffectInvalidDepthStencilViewVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilViewVariable> { public: STDMETHOD(SetDepthStencil)(_In_ ID3D11DepthStencilView *pResource) override { UNREFERENCED_PARAMETER(pResource); return E_FAIL; } STDMETHOD(GetDepthStencil)(_Outptr_ ID3D11DepthStencilView **ppResource) override { UNREFERENCED_PARAMETER(ppResource); return E_FAIL; } STDMETHOD(SetDepthStencilArray)(_In_reads_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } STDMETHOD(GetDepthStencilArray)(_Out_writes_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override { UNREFERENCED_PARAMETER(ppResources); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidDepthStencilViewVariable, ID3DX11EffectDepthStencilViewVariable, ID3DX11EffectVariable); }; struct SEffectInvalidConstantBuffer : public TEffectInvalidVariable<ID3DX11EffectConstantBuffer> { public: STDMETHOD(SetConstantBuffer)(_In_ ID3D11Buffer *pConstantBuffer) override { UNREFERENCED_PARAMETER(pConstantBuffer); return E_FAIL; } STDMETHOD(GetConstantBuffer)(_Outptr_ ID3D11Buffer **ppConstantBuffer) override { UNREFERENCED_PARAMETER(ppConstantBuffer); return E_FAIL; } STDMETHOD(UndoSetConstantBuffer)() override { return E_FAIL; } STDMETHOD(SetTextureBuffer)(_In_ ID3D11ShaderResourceView *pTextureBuffer) override { UNREFERENCED_PARAMETER(pTextureBuffer); return E_FAIL; } STDMETHOD(GetTextureBuffer)(_Outptr_ ID3D11ShaderResourceView **ppTextureBuffer) override { UNREFERENCED_PARAMETER(ppTextureBuffer); return E_FAIL; } STDMETHOD(UndoSetTextureBuffer)() override { return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidConstantBuffer, ID3DX11EffectConstantBuffer, ID3DX11EffectVariable); }; struct SEffectInvalidShaderVariable : public TEffectInvalidVariable<ID3DX11EffectShaderVariable> { public: STDMETHOD(GetShaderDesc)(_In_ uint32_t ShaderIndex, _Out_ D3DX11_EFFECT_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetVertexShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11VertexShader **ppVS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppVS); return E_FAIL; } STDMETHOD(GetGeometryShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11GeometryShader **ppGS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppGS); return E_FAIL; } STDMETHOD(GetPixelShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11PixelShader **ppPS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppPS); return E_FAIL; } STDMETHOD(GetHullShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11HullShader **ppHS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppHS); return E_FAIL; } STDMETHOD(GetDomainShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11DomainShader **ppDS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppDS); return E_FAIL; } STDMETHOD(GetComputeShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11ComputeShader **ppCS) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(ppCS); return E_FAIL; } STDMETHOD(GetInputSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(Element); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetOutputSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(Element); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetPatchConstantSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override { UNREFERENCED_PARAMETER(ShaderIndex); UNREFERENCED_PARAMETER(Element); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidShaderVariable, ID3DX11EffectShaderVariable, ID3DX11EffectVariable); }; struct SEffectInvalidBlendVariable : public TEffectInvalidVariable<ID3DX11EffectBlendVariable> { public: STDMETHOD(GetBlendState)(_In_ uint32_t Index, _Outptr_ ID3D11BlendState **ppState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(ppState); return E_FAIL; } STDMETHOD(SetBlendState)(_In_ uint32_t Index, _In_ ID3D11BlendState *pState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pState); return E_FAIL; } STDMETHOD(UndoSetBlendState)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return E_FAIL; } STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_BLEND_DESC *pDesc) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidBlendVariable, ID3DX11EffectBlendVariable, ID3DX11EffectVariable); }; struct SEffectInvalidDepthStencilVariable : public TEffectInvalidVariable<ID3DX11EffectDepthStencilVariable> { public: STDMETHOD(GetDepthStencilState)(_In_ uint32_t Index, _Outptr_ ID3D11DepthStencilState **ppState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(ppState); return E_FAIL; } STDMETHOD(SetDepthStencilState)(_In_ uint32_t Index, _In_ ID3D11DepthStencilState *pState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pState); return E_FAIL; } STDMETHOD(UndoSetDepthStencilState)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return E_FAIL; } STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_DEPTH_STENCIL_DESC *pDesc) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidDepthStencilVariable, ID3DX11EffectDepthStencilVariable, ID3DX11EffectVariable); }; struct SEffectInvalidRasterizerVariable : public TEffectInvalidVariable<ID3DX11EffectRasterizerVariable> { public: STDMETHOD(GetRasterizerState)(_In_ uint32_t Index, _Outptr_ ID3D11RasterizerState **ppState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(ppState); return E_FAIL; } STDMETHOD(SetRasterizerState)(_In_ uint32_t Index, _In_ ID3D11RasterizerState *pState) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pState); return E_FAIL; } STDMETHOD(UndoSetRasterizerState)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return E_FAIL; } STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_RASTERIZER_DESC *pDesc) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidRasterizerVariable, ID3DX11EffectRasterizerVariable, ID3DX11EffectVariable); }; struct SEffectInvalidSamplerVariable : public TEffectInvalidVariable<ID3DX11EffectSamplerVariable> { public: STDMETHOD(GetSampler)(_In_ uint32_t Index, _Outptr_ ID3D11SamplerState **ppSampler) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(ppSampler); return E_FAIL; } STDMETHOD(SetSampler)(_In_ uint32_t Index, _In_ ID3D11SamplerState *pSampler) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pSampler); return E_FAIL; } STDMETHOD(UndoSetSampler)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return E_FAIL; } STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_SAMPLER_DESC *pDesc) override { UNREFERENCED_PARAMETER(Index); UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidSamplerVariable, ID3DX11EffectSamplerVariable, ID3DX11EffectVariable); }; struct SEffectInvalidPass : public ID3DX11EffectPass { public: STDMETHOD_(bool, IsValid)() override { return false; } STDMETHOD(GetDesc)(_Out_ D3DX11_PASS_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetVertexShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetGeometryShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetPixelShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetHullShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetDomainShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD(GetComputeShaderDesc)(_Out_ D3DX11_PASS_SHADER_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidScalarVariable; } STDMETHOD(Apply)(_In_ uint32_t Flags, _In_ ID3D11DeviceContext* pContext) override { UNREFERENCED_PARAMETER(Flags); UNREFERENCED_PARAMETER(pContext); return E_FAIL; } STDMETHOD(ComputeStateBlockMask)(_Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) override { UNREFERENCED_PARAMETER(pStateBlockMask); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidPass, ID3DX11EffectPass, IUnknown); }; struct SEffectInvalidTechnique : public ID3DX11EffectTechnique { public: STDMETHOD_(bool, IsValid)() override { return false; } STDMETHOD(GetDesc)(_Out_ D3DX11_TECHNIQUE_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectPass*, GetPassByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidPass; } STDMETHOD_(ID3DX11EffectPass*, GetPassByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidPass; } STDMETHOD(ComputeStateBlockMask)(_Inout_ D3DX11_STATE_BLOCK_MASK *pStateBlockMask) override { UNREFERENCED_PARAMETER(pStateBlockMask); return E_FAIL; } IUNKNOWN_IMP(SEffectInvalidTechnique, ID3DX11EffectTechnique, IUnknown); }; struct SEffectInvalidGroup : public ID3DX11EffectGroup { public: STDMETHOD_(bool, IsValid)() override { return false; } STDMETHOD(GetDesc)(_Out_ D3DX11_GROUP_DESC *pDesc) override { UNREFERENCED_PARAMETER(pDesc); return E_FAIL; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); return &g_InvalidTechnique; } STDMETHOD_(ID3DX11EffectTechnique*, GetTechniqueByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); return &g_InvalidTechnique; } IUNKNOWN_IMP(SEffectInvalidGroup, ID3DX11EffectGroup, IUnknown); }; ////////////////////////////////////////////////////////////////////////// // Helper routines ////////////////////////////////////////////////////////////////////////// // This is an annoying warning that pops up in retail builds because // the code that jumps to "lExit" is conditionally not compiled. // The only alternative is more #ifdefs in every function #pragma warning( disable : 4102 ) // 'label' : unreferenced label #define VERIFYPARAMETER(x) \ { if (!(x)) { DPF(0, "%s: Parameter " #x " was nullptr.", pFuncName); \ __BREAK_ON_FAIL; hr = E_INVALIDARG; goto lExit; } } static HRESULT AnnotationInvalidSetCall(LPCSTR pFuncName) { DPF(0, "%s: Annotations are readonly", pFuncName); return D3DERR_INVALIDCALL; } static HRESULT ObjectSetRawValue() { DPF(0, "ID3DX11EffectVariable::SetRawValue: Objects do not support ths call; please use the specific object accessors instead."); return D3DERR_INVALIDCALL; } static HRESULT ObjectGetRawValue() { DPF(0, "ID3DX11EffectVariable::GetRawValue: Objects do not support ths call; please use the specific object accessors instead."); return D3DERR_INVALIDCALL; } ID3DX11EffectConstantBuffer * NoParentCB(); ID3DX11EffectVariable * GetAnnotationByIndexHelper(_In_z_ const char *pClassName, _In_ uint32_t Index, _In_ uint32_t AnnotationCount, _In_reads_(AnnotationCount) SAnnotation *pAnnotations); ID3DX11EffectVariable * GetAnnotationByNameHelper(_In_z_ const char *pClassName, _In_z_ LPCSTR Name, _In_ uint32_t AnnotationCount, _In_reads_(AnnotationCount) SAnnotation *pAnnotations); template<typename SVarType> _Success_(return) bool GetVariableByIndexHelper(_In_ uint32_t Index, _In_ uint32_t VariableCount, _In_reads_(VariableCount) SVarType *pVariables, _In_opt_ uint8_t *pBaseAddress, _Outptr_ SVarType **ppMember, _Outptr_ void **ppDataPtr) { static LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByIndex"; if (Index >= VariableCount) { DPF(0, "%s: Invalid index (%u, total: %u)", pFuncName, Index, VariableCount); return false; } *ppMember = pVariables + Index; *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; return true; } template<typename SVarType> _Success_(return) bool GetVariableByNameHelper(_In_z_ LPCSTR Name, _In_ uint32_t VariableCount, _In_reads_(VariableCount) SVarType *pVariables, _In_opt_ uint8_t *pBaseAddress, _Outptr_ SVarType **ppMember, _Outptr_ void **ppDataPtr, _Out_ uint32_t* pIndex) { static LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberByName"; if (nullptr == Name) { DPF(0, "%s: Parameter Name was nullptr.", pFuncName); return false; } bool bHasSuper = false; for (uint32_t i = 0; i < VariableCount; ++ i) { *ppMember = pVariables + i; assert((*ppMember)->pName != 0); _Analysis_assume_((*ppMember)->pName != 0); if (strcmp((*ppMember)->pName, Name) == 0) { *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; *pIndex = i; return true; } else if (i == 0 && (*ppMember)->pName[0] == '$' && strcmp((*ppMember)->pName, "$super") == 0) { bHasSuper = true; } } if (bHasSuper) { SVarType* pSuper = pVariables; return GetVariableByNameHelper<SVarType>(Name, pSuper->pType->StructType.Members, (SVarType*)pSuper->pType->StructType.pMembers, pBaseAddress + pSuper->Data.Offset, ppMember, ppDataPtr, pIndex); } DPF(0, "%s: Variable [%s] not found", pFuncName, Name); return false; } template<typename SVarType> _Success_(return) bool GetVariableBySemanticHelper(_In_z_ LPCSTR Semantic, _In_ uint32_t VariableCount, _In_reads_(VariableCount) SVarType *pVariables, _In_opt_ uint8_t *pBaseAddress, _Outptr_ SVarType **ppMember, _Outptr_ void **ppDataPtr, _Out_ uint32_t* pIndex) { static LPCSTR pFuncName = "ID3DX11EffectVariable::GetMemberBySemantic"; if (nullptr == Semantic) { DPF(0, "%s: Parameter Semantic was nullptr.", pFuncName); return false; } for (uint32_t i = 0; i < VariableCount; ++ i) { *ppMember = pVariables + i; if (nullptr != (*ppMember)->pSemantic && _stricmp((*ppMember)->pSemantic, Semantic) == 0) { *ppDataPtr = pBaseAddress + (*ppMember)->Data.Offset; *pIndex = i; return true; } } DPF(0, "%s: Variable with semantic [%s] not found", pFuncName, Semantic); return false; } inline bool AreBoundsValid(_In_ uint32_t Offset, _In_ uint32_t Count, _In_ const void *pData, _In_ const SType *pType, _In_ uint32_t TotalUnpackedSize) { if (Count == 0) return true; uint32_t singleElementSize = pType->GetTotalUnpackedSize(true); assert(singleElementSize <= pType->Stride); return ((Offset + Count >= Offset) && ((Offset + Count) < ((uint32_t)-1) / pType->Stride) && (Count * pType->Stride + (uint8_t*)pData >= (uint8_t*)pData) && ((Offset + Count - 1) * pType->Stride + singleElementSize <= TotalUnpackedSize)); } // Note that the branches in this code is based on template parameters and will be compiled out template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, bool ValidatePtr> __forceinline HRESULT CopyScalarValue(_In_ SRC_TYPE SrcValue, _Out_ void *pDest, _In_z_ const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG if (ValidatePtr) VERIFYPARAMETER(pDest); #else UNREFERENCED_PARAMETER(pFuncName); #endif switch (SourceType) { case ETVT_Bool: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = SrcValue ? 1 : 0; break; case ETVT_Float: *(float*)pDest = SrcValue ? 1.0f : 0.0f; break; case ETVT_bool: *(bool*)pDest = (SrcValue != 0) ? true : false; break; default: assert(0); } break; case ETVT_Int: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = (int) SrcValue; break; case ETVT_Float: *(float*)pDest = (float)(SrcValue); break; case ETVT_bool: *(bool*)pDest = (SrcValue != 0) ? true : false; break; default: assert(0); } break; case ETVT_Float: switch (DestType) { case ETVT_Bool: *(int*)pDest = (SrcValue != 0.0f) ? -1 : 0; break; case ETVT_Int: *(int*)pDest = (int) (SrcValue); break; case ETVT_Float: *(float*)pDest = (float) SrcValue; break; case ETVT_bool: *(bool*)pDest = (SrcValue != 0.0f) ? true : false; break; default: assert(0); } break; case ETVT_bool: switch (DestType) { case ETVT_Bool: *(int*)pDest = SrcValue ? -1 : 0; break; case ETVT_Int: *(int*)pDest = SrcValue ? 1 : 0; break; case ETVT_Float: *(float*)pDest = SrcValue ? 1.0f : 0.0f; break; case ETVT_bool: *(bool*)pDest = (SrcValue != 0) ? true : false; break; default: assert(0); } break; default: assert(0); } lExit: return hr; } #pragma warning(push) #pragma warning( disable : 6103 ) template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> inline HRESULT SetScalarArray(_In_reads_(Count) const SRC_TYPE *pSrcValues, _Out_writes_(Count) DEST_TYPE *pDestValues, _In_ uint32_t Offset, _In_ uint32_t Count, _In_ const SType *pType, _In_ uint32_t TotalUnpackedSize, _In_z_ const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG VERIFYPARAMETER(pSrcValues); #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pSrcValues, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #else UNREFERENCED_PARAMETER(TotalUnpackedSize); UNREFERENCED_PARAMETER(pFuncName); #endif uint32_t i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; pDestValues += Offset * delta; for (i = 0, j = 0; j < Count; i += delta, ++ j) { // pDestValues[i] = (DEST_TYPE)pSrcValues[j]; CopyScalarValue<SourceType, DestType, SRC_TYPE, false>(pSrcValues[j], &pDestValues[i], "SetScalarArray"); } lExit: return hr; } #pragma warning(pop) #pragma warning( disable : 6103 ) template<ETemplateVarType SourceType, ETemplateVarType DestType, typename SRC_TYPE, typename DEST_TYPE> inline HRESULT GetScalarArray(_In_reads_(Count) SRC_TYPE *pSrcValues, _Out_writes_(Count) DEST_TYPE *pDestValues, _In_ uint32_t Offset, _In_ uint32_t Count, _In_ const SType *pType, _In_ uint32_t TotalUnpackedSize, _In_z_ const char *pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG VERIFYPARAMETER(pDestValues); #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pDestValues, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #else UNREFERENCED_PARAMETER(TotalUnpackedSize); UNREFERENCED_PARAMETER(pFuncName); #endif uint32_t i, j, delta = pType->NumericType.IsPackedArray ? 1 : SType::c_ScalarsPerRegister; pSrcValues += Offset * delta; for (i = 0, j = 0; j < Count; i += delta, ++ j) { // pDestValues[j] = (DEST_TYPE)pSrcValues[i]; CopyScalarValue<SourceType, DestType, SRC_TYPE, false>(pSrcValues[i], &pDestValues[j], "GetScalarArray"); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // TVariable - implements type casting and member/element retrieval ////////////////////////////////////////////////////////////////////////// // requires that IBaseInterface contain SVariable's fields and support ID3DX11EffectVariable template<typename IBaseInterface> struct TVariable : public IBaseInterface { STDMETHOD_(bool, IsValid)() override { return true; } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByIndex)(_In_ uint32_t Index) { SVariable *pMember; UDataPointer dataPtr; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity2 = GetTopLevelEntity(); if (((ID3DX11Effect*)pTopLevelEntity2->pEffect)->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberByIndex: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableByIndexHelper<SVariable>(Index, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric)) { return &g_InvalidScalarVariable; } return pTopLevelEntity2->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity2, pMember, dataPtr, false, Index); } STDMETHOD_(ID3DX11EffectVariable*, GetMemberByName)(_In_z_ LPCSTR Name) { SVariable *pMember; UDataPointer dataPtr; uint32_t index; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity2 = GetTopLevelEntity(); if (pTopLevelEntity2->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberByName: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberByName: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableByNameHelper<SVariable>(Name, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) { return &g_InvalidScalarVariable; } return pTopLevelEntity2->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity2, pMember, dataPtr, false, index); } STDMETHOD_(ID3DX11EffectVariable*, GetMemberBySemantic)(_In_z_ LPCSTR Semantic) { SVariable *pMember; UDataPointer dataPtr; uint32_t index; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity2 = GetTopLevelEntity(); if (pTopLevelEntity2->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Cannot get members; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (pType->VarType != EVT_Struct) { DPF(0, "ID3DX11EffectVariable::GetMemberBySemantic: Variable is not a structure"); return &g_InvalidScalarVariable; } if (!GetVariableBySemanticHelper<SVariable>(Semantic, pType->StructType.Members, pType->StructType.pMembers, Data.pNumeric, &pMember, &dataPtr.pGeneric, &index)) { return &g_InvalidScalarVariable; } return pTopLevelEntity2->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity2, pMember, dataPtr, false, index); } STDMETHOD_(ID3DX11EffectVariable*, GetElement)(_In_ uint32_t Index) { static LPCSTR pFuncName = "ID3DX11EffectVariable::GetElement"; TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity2 = GetTopLevelEntity(); UDataPointer dataPtr; if (pTopLevelEntity2->pEffect->IsOptimized()) { DPF(0, "ID3DX11EffectVariable::GetElement: Cannot get element; effect has been Optimize()'ed"); return &g_InvalidScalarVariable; } if (!IsArray()) { DPF(0, "%s: This interface does not refer to an array", pFuncName); return &g_InvalidScalarVariable; } if (Index >= pType->Elements) { DPF(0, "%s: Invalid element index (%u, total: %u)", pFuncName, Index, pType->Elements); return &g_InvalidScalarVariable; } if (pType->BelongsInConstantBuffer()) { dataPtr.pGeneric = Data.pNumeric + pType->Stride * Index; } else { dataPtr.pGeneric = GetBlockByIndex(pType->VarType, pType->ObjectType, Data.pGeneric, Index); if (nullptr == dataPtr.pGeneric) { DPF(0, "%s: Internal error", pFuncName); return &g_InvalidScalarVariable; } } return pTopLevelEntity2->pEffect->CreatePooledVariableMemberInterface(pTopLevelEntity2, (SVariable *) this, dataPtr, true, Index); } STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Scalar) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidScalarVariable; } return (ID3DX11EffectScalarVariable *) this; } STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Vector) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidVectorVariable; } return (ID3DX11EffectVectorVariable *) this; } STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; if (pType->VarType != EVT_Numeric || pType->NumericType.NumericLayout != ENL_Matrix) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidMatrixVariable; } return (ID3DX11EffectMatrixVariable *) this; } STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; if (!pType->IsObjectType(EOT_String)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidStringVariable; } return (ID3DX11EffectStringVariable *) this; } STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; if (!pType->IsClassInstance() ) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidClassInstanceVariable; } else if( pMemberData == nullptr ) { DPF(0, "%s: Non-global class instance variables (members of structs or classes) and class instances " "inside tbuffers are not supported.", pFuncName ); return &g_InvalidClassInstanceVariable; } return (ID3DX11EffectClassInstanceVariable *) this; } STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; if (!pType->IsInterface()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidInterfaceVariable; } return (ID3DX11EffectInterfaceVariable *) this; } STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; if (!pType->IsShaderResource()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderResourceVariable; } return (ID3DX11EffectShaderResourceVariable *) this; } STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; if (!pType->IsUnorderedAccessView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidUnorderedAccessViewVariable; } return (ID3DX11EffectUnorderedAccessViewVariable *) this; } STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; if (!pType->IsRenderTargetView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRenderTargetViewVariable; } return (ID3DX11EffectRenderTargetViewVariable *) this; } STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; if (!pType->IsDepthStencilView()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilViewVariable; } return (ID3DX11EffectDepthStencilViewVariable *) this; } STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidConstantBuffer; } STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; if (!pType->IsShader()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderVariable; } return (ID3DX11EffectShaderVariable *) this; } STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; if (!pType->IsObjectType(EOT_Blend)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidBlendVariable; } return (ID3DX11EffectBlendVariable *) this; } STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; if (!pType->IsObjectType(EOT_DepthStencil)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilVariable; } return (ID3DX11EffectDepthStencilVariable *) this; } STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; if (!pType->IsObjectType(EOT_Rasterizer)) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRasterizerVariable; } return (ID3DX11EffectRasterizerVariable *) this; } STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; if (!pType->IsSampler()) { DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidSamplerVariable; } return (ID3DX11EffectSamplerVariable *) this; } // Numeric variables should override this STDMETHOD(SetRawValue)(_In_reads_bytes_(Count) const void *pData, _In_ uint32_t Offset, _In_ uint32_t Count) { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return ObjectSetRawValue(); } STDMETHOD(GetRawValue)(_Out_writes_(Count) void *pData, _In_ uint32_t Offset, _In_ uint32_t Count) { UNREFERENCED_PARAMETER(pData); UNREFERENCED_PARAMETER(Offset); UNREFERENCED_PARAMETER(Count); return ObjectGetRawValue(); } }; ////////////////////////////////////////////////////////////////////////// // TTopLevelVariable - functionality for annotations and global variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TTopLevelVariable : public SVariable, public IBaseInterface { // Required to create member/element variable interfaces CEffect *pEffect; CEffect* GetEffect() { return pEffect; } TTopLevelVariable() : pEffect (nullptr) { } uint32_t GetTotalUnpackedSize() { return ((SType*)pType)->GetTotalUnpackedSize(false); } STDMETHOD_(ID3DX11EffectType*, GetType)() { return (ID3DX11EffectType*)(SType*)pType; } TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() { return (TTopLevelVariable<ID3DX11EffectVariable> *)this; } bool IsArray() { return (pType->Elements > 0); } }; ////////////////////////////////////////////////////////////////////////// // TMember - functionality for structure/array members of other variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TMember : public SVariable, public IBaseInterface { // Indicates that this is a single element of a containing array uint32_t IsSingleElement : 1; // Required to create member/element variable interfaces TTopLevelVariable<ID3DX11EffectVariable> *pTopLevelEntity; TMember() { IsSingleElement = false; pTopLevelEntity = nullptr; } CEffect* GetEffect() { return pTopLevelEntity->pEffect; } uint32_t GetTotalUnpackedSize() { return pType->GetTotalUnpackedSize(IsSingleElement); } STDMETHOD_(ID3DX11EffectType*, GetType)() override { if (IsSingleElement) { return pTopLevelEntity->pEffect->CreatePooledSingleElementTypeInterface( pType ); } else { return (ID3DX11EffectType*) pType; } } STDMETHOD(GetDesc)(_Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) override { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != nullptr); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = 0; if (pTopLevelEntity->pEffect->IsReflectionData(pTopLevelEntity)) { // Is part of an annotation assert(pTopLevelEntity->pEffect->IsReflectionData(Data.pGeneric)); pDesc->Annotations = 0; pDesc->BufferOffset = 0; pDesc->Flags |= D3DX11_EFFECT_VARIABLE_ANNOTATION; } else { // Is part of a global variable assert(pTopLevelEntity->pEffect->IsRuntimeData(pTopLevelEntity)); if (!pTopLevelEntity->pType->IsObjectType(EOT_String)) { // strings are funny; their data is reflection data, so ignore those assert(pTopLevelEntity->pEffect->IsRuntimeData(Data.pGeneric)); } pDesc->Annotations = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->AnnotationCount; SConstantBuffer *pCB = ((TGlobalVariable<ID3DX11Effect>*)pTopLevelEntity)->pCB; if (pType->BelongsInConstantBuffer()) { assert(pCB != 0); _Analysis_assume_(pCB != 0); UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; assert(offset == (uint32_t)offset); pDesc->BufferOffset = (uint32_t)offset; assert(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size); } else { assert(pCB == nullptr); pDesc->BufferOffset = 0; } } lExit: return hr; } TTopLevelVariable<ID3DX11EffectVariable> * GetTopLevelEntity() { return pTopLevelEntity; } bool IsArray() { return (pType->Elements > 0 && !IsSingleElement); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { return pTopLevelEntity->GetAnnotationByIndex(Index); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { return pTopLevelEntity->GetAnnotationByName(Name); } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() override { return pTopLevelEntity->GetParentConstantBuffer(); } // Annotations should never be able to go down this codepath void DirtyVariable() { // make sure to call the global variable's version of dirty variable ((TGlobalVariable<ID3DX11EffectVariable>*)pTopLevelEntity)->DirtyVariable(); } }; ////////////////////////////////////////////////////////////////////////// // TAnnotation - functionality for top level annotations ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TAnnotation : public TVariable<TTopLevelVariable<IBaseInterface> > { STDMETHOD(GetDesc)(_Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) override { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != nullptr); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = D3DX11_EFFECT_VARIABLE_ANNOTATION; pDesc->Annotations = 0; pDesc->BufferOffset = 0; pDesc->ExplicitBindPoint = 0; lExit: return hr; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) override { UNREFERENCED_PARAMETER(Index); static LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByIndex"; DPF(0, "%s: Only variables may have annotations", pFuncName); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) override { UNREFERENCED_PARAMETER(Name); static LPCSTR pFuncName = "ID3DX11EffectVariable::GetAnnotationByName"; DPF(0, "%s: Only variables may have annotations", pFuncName); return &g_InvalidScalarVariable; } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() override { return NoParentCB(); } void DirtyVariable() { assert(0); } }; ////////////////////////////////////////////////////////////////////////// // TGlobalVariable - functionality for top level global variables ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TGlobalVariable : public TVariable<TTopLevelVariable<IBaseInterface> > { Timer LastModifiedTime; // if numeric, pointer to the constant buffer where this variable lives SConstantBuffer *pCB; uint32_t AnnotationCount; SAnnotation *pAnnotations; TGlobalVariable() : LastModifiedTime(0), pCB(nullptr), AnnotationCount(0), pAnnotations(nullptr) { } STDMETHOD(GetDesc)(_Out_ D3DX11_EFFECT_VARIABLE_DESC *pDesc) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVariable::GetDesc"; VERIFYPARAMETER(pDesc != nullptr); pDesc->Name = pName; pDesc->Semantic = pSemantic; pDesc->Flags = 0; pDesc->Annotations = AnnotationCount; if (pType->BelongsInConstantBuffer()) { assert(pCB != 0); _Analysis_assume_(pCB != 0); UINT_PTR offset = Data.pNumeric - pCB->pBackingStore; assert(offset == (uint32_t)offset); pDesc->BufferOffset = (uint32_t)offset; assert(pDesc->BufferOffset >= 0 && pDesc->BufferOffset + GetTotalUnpackedSize() <= pCB->Size ); } else { assert(pCB == nullptr); pDesc->BufferOffset = 0; } if (ExplicitBindPoint != -1) { pDesc->ExplicitBindPoint = ExplicitBindPoint; pDesc->Flags |= D3DX11_EFFECT_VARIABLE_EXPLICIT_BIND_POINT; } else { pDesc->ExplicitBindPoint = 0; } lExit: return hr; } // these are all well defined for global vars STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByIndex)(_In_ uint32_t Index) { return GetAnnotationByIndexHelper("ID3DX11EffectVariable", Index, AnnotationCount, pAnnotations); } STDMETHOD_(ID3DX11EffectVariable*, GetAnnotationByName)(_In_z_ LPCSTR Name) { return GetAnnotationByNameHelper("ID3DX11EffectVariable", Name, AnnotationCount, pAnnotations); } STDMETHOD_(ID3DX11EffectConstantBuffer*, GetParentConstantBuffer)() { if (nullptr != pCB) { assert(pType->BelongsInConstantBuffer()); return (ID3DX11EffectConstantBuffer*)pCB; } else { assert(!pType->BelongsInConstantBuffer()); return &g_InvalidConstantBuffer; } } inline void DirtyVariable() { assert(pCB != 0); _Analysis_assume_(pCB != 0); pCB->IsDirty = true; LastModifiedTime = pEffect->GetCurrentTime(); } }; ////////////////////////////////////////////////////////////////////////// // TNumericVariable - implements raw set/get functionality ////////////////////////////////////////////////////////////////////////// // IMPORTANT NOTE: All of these numeric & object aspect classes MUST NOT // add data members to the base variable classes. Otherwise type sizes // will disagree between object & numeric variables and we cannot eaily // create arrays of global variables using SGlobalVariable // Requires that IBaseInterface have SVariable's members, GetTotalUnpackedSize() and DirtyVariable() template<typename IBaseInterface, bool IsAnnotation> struct TNumericVariable : public IBaseInterface { STDMETHOD(SetRawValue)(_In_reads_bytes_(ByteCount) const void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) override { if (IsAnnotation) { return AnnotationInvalidSetCall("ID3DX11EffectVariable::SetRawValue"); } else { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectVariable::SetRawValue"; VERIFYPARAMETER(pData); if ((ByteOffset + ByteCount < ByteOffset) || (ByteCount + (uint8_t*)pData < (uint8_t*)pData) || ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) { // overflow of some kind DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif DirtyVariable(); memcpy(Data.pNumeric + ByteOffset, pData, ByteCount); lExit: return hr; } } STDMETHOD(GetRawValue)(_Out_writes_bytes_(ByteCount) void *pData, _In_ uint32_t ByteOffset, _In_ uint32_t ByteCount) override { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectVariable::GetRawValue"; VERIFYPARAMETER(pData); if ((ByteOffset + ByteCount < ByteOffset) || (ByteCount + (uint8_t*)pData < (uint8_t*)pData) || ((ByteOffset + ByteCount) > GetTotalUnpackedSize())) { // overflow of some kind DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif memcpy(pData, Data.pNumeric + ByteOffset, ByteCount); lExit: return hr; } }; ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TFloatScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation> struct TFloatScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(_In_ const float Value) override; STDMETHOD(GetFloat)(_Out_ float *pValue) override; STDMETHOD(SetFloatArray)(_In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetFloatArray)(_Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetInt)(_In_ const int Value) override; STDMETHOD(GetInt)(_Out_ int *pValue) override; STDMETHOD(SetIntArray)(_In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetIntArray)(_Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetBool)(_In_ const bool Value) override; STDMETHOD(GetBool)(_Out_ bool *pValue) override; STDMETHOD(SetBoolArray)(_In_reads_(Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetBoolArray)(_Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Float, float, false>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Float, ETVT_Float, float, true>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(const float *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Float, float, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Float, ETVT_Float, float, float>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetInt(const int Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Float, int, false>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Float, ETVT_Int, float, true>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(const int *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Float, int, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Float, ETVT_Int, float, int>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBool(const bool Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_bool, ETVT_Float, bool, false>(Value, Data.pNumericFloat, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBool(bool *pValue) { return CopyScalarValue<ETVT_Float, ETVT_bool, float, true>(*Data.pNumericFloat, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(const bool *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_bool, ETVT_Float, bool, float>(pData, Data.pNumericFloat, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TFloatScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(bool *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Float, ETVT_bool, float, bool>(Data.pNumericFloat, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TIntScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation> struct TIntScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(_In_ const float Value) override; STDMETHOD(GetFloat)(_Out_ float *pValue) override; STDMETHOD(SetFloatArray)(_In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetFloatArray)(_Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetInt)(_In_ const int Value) override; STDMETHOD(GetInt)(_Out_ int *pValue) override; STDMETHOD(SetIntArray)(_In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetIntArray)(_Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetBool)(_In_ const bool Value) override; STDMETHOD(GetBool)(_Out_ bool *pValue) override; STDMETHOD(SetBoolArray)(_In_reads_(Count) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetBoolArray)(_Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Int, float, false>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Int, ETVT_Float, int, true>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(const float *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Int, float, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Int, ETVT_Float, int, float>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetInt(const int Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Int, int, false>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Int, ETVT_Int, int, true>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(const int *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Int, int, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Int, ETVT_Int, int, int>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBool(const bool Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_bool, ETVT_Int, bool, false>(Value, Data.pNumericInt, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBool(bool *pValue) { return CopyScalarValue<ETVT_Int, ETVT_bool, int, true>(*Data.pNumericInt, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(const bool *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_bool, ETVT_Int, bool, int>(pData, Data.pNumericInt, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TIntScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(bool *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Int, ETVT_bool, int, bool>(Data.pNumericInt, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectScalarVariable (TBoolScalarVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation> struct TBoolScalarVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetFloat)(_In_ const float Value) override; STDMETHOD(GetFloat)(_Out_ float *pValue) override; STDMETHOD(SetFloatArray)(_In_reads_(Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetFloatArray)(_Out_writes_(Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetInt)(_In_ const int Value) override; STDMETHOD(GetInt)(_Out_ int *pValue) override; STDMETHOD(SetIntArray)(_In_reads_(Count) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetIntArray)(_Out_writes_(Count) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetBool)(_In_ const bool Value) override; STDMETHOD(GetBool)(_Out_ bool *pValue) override; STDMETHOD(SetBoolArray)(_In_reads_(Count) const bool *pData, uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetBoolArray)(_Out_writes_(Count) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloat(float Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloat"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Float, ETVT_Bool, float, false>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloat(float *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_Float, BOOL, true>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetFloat"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetFloatArray(const float *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetFloatArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Float, ETVT_Bool, float, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetFloatArray(float *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Bool, ETVT_Float, BOOL, float>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetFloatArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetInt(const int Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetInt"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_Int, ETVT_Bool, int, false>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetInt(int *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_Int, BOOL, true>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetInt"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetIntArray(const int *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetIntArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_Int, ETVT_Bool, int, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetIntArray(int *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Bool, ETVT_Int, BOOL, int>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetIntArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBool(const bool Value) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBool"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return CopyScalarValue<ETVT_bool, ETVT_Bool, bool, false>(Value, Data.pNumericBool, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBool(bool *pValue) { return CopyScalarValue<ETVT_Bool, ETVT_bool, BOOL, true>(*Data.pNumericBool, pValue, "ID3DX11EffectScalarVariable::GetBool"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::SetBoolArray(const bool *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectScalarVariable::SetBoolArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return SetScalarArray<ETVT_bool, ETVT_Bool, bool, BOOL>(pData, Data.pNumericBool, Offset, Count, pType, GetTotalUnpackedSize(), pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TBoolScalarVariable<IBaseInterface, IsAnnotation>::GetBoolArray(bool *pData, uint32_t Offset, uint32_t Count) { return GetScalarArray<ETVT_Bool, ETVT_bool, BOOL, bool>(Data.pNumericBool, pData, Offset, Count, pType, GetTotalUnpackedSize(), "ID3DX11EffectScalarVariable::GetBoolArray"); } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectVectorVariable (TVectorVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType > struct TVectorVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetBoolVector) (_In_reads_(4) const bool *pData) override; STDMETHOD(SetIntVector) (_In_reads_(4) const int *pData) override; STDMETHOD(SetFloatVector)(_In_reads_(4) const float *pData) override; STDMETHOD(GetBoolVector) (_Out_writes_(4) bool *pData) override; STDMETHOD(GetIntVector) (_Out_writes_(4) int *pData) override; STDMETHOD(GetFloatVector)(_Out_writes_(4) float *pData) override; STDMETHOD(SetBoolVectorArray) (_In_reads_(Count*4) const bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetIntVectorArray) (_In_reads_(Count*4) const int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetFloatVectorArray)(_In_reads_(Count*4) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetBoolVectorArray) (_Out_writes_(Count*4) bool *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetIntVectorArray) (_Out_writes_(Count*4) int *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetFloatVectorArray)(_Out_writes_(Count*4) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; // Note that branches in this code is based on template parameters and will be compiled out #pragma warning (push) #pragma warning (disable : 6101) template <ETemplateVarType DestType, ETemplateVarType SourceType> void __forceinline CopyDataWithTypeConversion(_Out_ void *pDest, _In_ const void *pSource, _In_ size_t dstVecSize, _In_ size_t srcVecSize, _In_ size_t elementCount, _In_ size_t vecCount) { switch (SourceType) { case ETVT_Bool: switch (DestType) { case ETVT_Bool: for (size_t j=0; j<vecCount; j++) { memcpy(pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((int*)pDest)[i] = ((bool*)pSource)[i] ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((float*)pDest)[i] = ((bool*)pSource)[i] ? -1.0f : 0.0f; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((bool*)pDest)[i] = (((int*)pSource)[i] != 0) ? true : false; pDest = ((bool*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: assert(0); } break; case ETVT_Int: switch (DestType) { case ETVT_Bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((int*)pDest)[i] = (((int*)pSource)[i] != 0) ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (size_t j=0; j<vecCount; j++) { memcpy(pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((float*)pDest)[i] = (float)(((int*)pSource)[i]); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((bool*)pDest)[i] = (((int*)pSource)[i] != 0) ? true : false; pDest = ((bool*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: assert(0); } break; case ETVT_Float: switch (DestType) { case ETVT_Bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((int*)pDest)[i] = (((float*)pSource)[i] != 0.0f) ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Int: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((int*)pDest)[i] = (int)((float*)pSource)[i]; pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_Float: for (size_t i=0; i<vecCount; i++) { memcpy( pDest, pSource, elementCount * SType::c_ScalarSize); pDest = ((float*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; case ETVT_bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) ((bool*)pDest)[i] = (((float*)pSource)[i] != 0.0f) ? true : false; pDest = ((bool*) pDest) + dstVecSize; pSource = ((float*) pSource) + srcVecSize; } break; default: assert(0); } break; case ETVT_bool: switch (DestType) { case ETVT_Bool: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) reinterpret_cast<int*>(pDest)[i] = reinterpret_cast<const bool*>(pSource)[i] ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((bool*) pSource) + srcVecSize; } break; case ETVT_Int: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) reinterpret_cast<int*>(pDest)[i] = reinterpret_cast<const bool*>(pSource)[i] ? -1 : 0; pDest = ((float*) pDest) + dstVecSize; pSource = ((bool*) pSource) + srcVecSize; } break; case ETVT_Float: for (size_t j=0; j<vecCount; j++) { for (size_t i=0; i<elementCount; i++) reinterpret_cast<float*>(pDest)[i] = reinterpret_cast<const bool*>(pSource)[i] ? -1.0f : 0.0f; pDest = ((float*) pDest) + dstVecSize; pSource = ((bool*) pSource) + srcVecSize; } break; case ETVT_bool: for (size_t j=0; j<vecCount; j++) { memcpy(pDest, pSource, elementCount); pDest = ((bool*) pDest) + dstVecSize; pSource = ((bool*) pSource) + srcVecSize; } break; default: assert(0); } break; default: assert(0); } } #pragma warning (pop) // Float Vector template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetFloatVector(const float *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVector(float *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Int Vector template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetIntVector(const int *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVector(int *pData) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVector"; VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Bool Vector template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType >::SetBoolVector(const bool *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); CopyDataWithTypeConversion<BaseType, ETVT_bool>(Data.pVector, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, 1); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVector(bool *pData) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVector"; VERIFYPARAMETER(pData); #endif CopyDataWithTypeConversion<ETVT_bool, BaseType>(pData, Data.pVector, pType->NumericType.Columns, 4, pType->NumericType.Columns, 1); lExit: return hr; } // Vector Arrays ///////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetFloatVectorArray(const float *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_Float>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetFloatVectorArray(float *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_Float, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } // int template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetIntVectorArray(const int *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetIntVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_Int>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetIntVectorArray(int *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetIntVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_Int, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } // bool template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::SetBoolVectorArray(const bool *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetBoolVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); // ensure we don't write over the padding at the end of the vector array CopyDataWithTypeConversion<BaseType, ETVT_bool>(Data.pVector + Offset, pData, 4, pType->NumericType.Columns, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation, ETemplateVarType BaseType> _Use_decl_annotations_ HRESULT TVectorVariable<IBaseInterface, IsAnnotation, BaseType>::GetBoolVectorArray(bool *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetBoolVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array CopyDataWithTypeConversion<ETVT_bool, BaseType>(pData, Data.pVector + Offset, pType->NumericType.Columns, 4, pType->NumericType.Columns, std::max(std::min((int)Count, (int)pType->Elements - (int)Offset), 0)); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectVector4Variable (TVectorVariable implementation) [OPTIMIZED] ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TVector4Variable : public TVectorVariable<IBaseInterface, false, ETVT_Float> { STDMETHOD(SetFloatVector)(_In_reads_(4) const float *pData) override; STDMETHOD(GetFloatVector)(_Out_writes_(4) float *pData) override; STDMETHOD(SetFloatVectorArray)(_In_reads_(Count*4) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetFloatVectorArray)(_Out_writes_(Count*4) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TVector4Variable<IBaseInterface>::SetFloatVector(const float *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif DirtyVariable(); Data.pVector[0] = ((CEffectVector4*) pData)[0]; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TVector4Variable<IBaseInterface>::GetFloatVector(float *pData) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVector"; #ifdef _DEBUG VERIFYPARAMETER(pData); #endif memcpy(pData, Data.pVector, pType->NumericType.Columns * SType::c_ScalarSize); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TVector4Variable<IBaseInterface>::SetFloatVectorArray(const float *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::SetFloatVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif DirtyVariable(); // ensure we don't write over the padding at the end of the vector array memcpy(Data.pVector + Offset, pData, std::min<size_t>(Count * sizeof(CEffectVector4), pType->TotalSize - (Offset * sizeof(CEffectVector4)))); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TVector4Variable<IBaseInterface>::GetFloatVectorArray(float *pData, uint32_t Offset, uint32_t Count) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectVectorVariable::GetFloatVectorArray"; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pData, pType, GetTotalUnpackedSize())) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #endif // ensure we don't read past the end of the vector array memcpy(pData, Data.pVector + Offset, std::min<size_t>(Count * sizeof(CEffectVector4), pType->TotalSize - (Offset * sizeof(CEffectVector4)))); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectMatrixVariable (TMatrixVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation> struct TMatrixVariable : public TNumericVariable<IBaseInterface, IsAnnotation> { STDMETHOD(SetMatrix)(_In_reads_(16) const float *pData) override; STDMETHOD(GetMatrix)(_Out_writes_(16) float *pData) override; STDMETHOD(SetMatrixArray)(_In_reads_(Count*16) const float *pData, uint32_t Offset, uint32_t Count) override; STDMETHOD(GetMatrixArray)(_Out_writes_(Count*16) float *pData, uint32_t Offset, uint32_t Count) override; STDMETHOD(SetMatrixPointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) override; STDMETHOD(GetMatrixPointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) override; STDMETHOD(SetMatrixTranspose)(_In_reads_(16) const float *pData) override; STDMETHOD(GetMatrixTranspose)(_Out_writes_(16) float *pData) override; STDMETHOD(SetMatrixTransposeArray)(_In_reads_(Count*16) const float *pData, uint32_t Offset, uint32_t Count) override; STDMETHOD(GetMatrixTransposeArray)(_Out_writes_(Count*16) float *pData, uint32_t Offset, uint32_t Count) override; STDMETHOD(SetMatrixTransposePointerArray)(_In_reads_(Count*16) const float **ppData, uint32_t Offset, uint32_t Count) override; STDMETHOD(GetMatrixTransposePointerArray)(_Out_writes_(Count*16) float **ppData, uint32_t Offset, uint32_t Count) override; }; #pragma warning (push) #pragma warning (disable : 6101) template<bool Transpose> static void SetMatrixTransposeHelper(_In_ const SType *pType, _Out_writes_bytes_(64) uint8_t *pDestData, _In_reads_(16) const float* pMatrix) { uint32_t registers, entries; if (Transpose) { // row major registers = pType->NumericType.Rows; entries = pType->NumericType.Columns; } else { // column major registers = pType->NumericType.Columns; entries = pType->NumericType.Rows; } _Analysis_assume_( registers <= 4 ); _Analysis_assume_( entries <= 4 ); for (size_t i = 0; i < registers; ++ i) { for (size_t j = 0; j < entries; ++ j) { #pragma prefast(suppress:__WARNING_UNRELATED_LOOP_TERMINATION, "regs / entries <= 4") ((float*)pDestData)[j] = ((float*)pMatrix)[j * 4 + i]; } pDestData += SType::c_RegisterSize; } } template<bool Transpose> static void GetMatrixTransposeHelper(_In_ const SType *pType, _In_reads_bytes_(64) uint8_t *pSrcData, _Out_writes_(16) float* pMatrix) { uint32_t registers, entries; if (Transpose) { // row major registers = pType->NumericType.Rows; entries = pType->NumericType.Columns; } else { // column major registers = pType->NumericType.Columns; entries = pType->NumericType.Rows; } _Analysis_assume_( registers <= 4 ); _Analysis_assume_( entries <= 4 ); for (size_t i = 0; i < registers; ++ i) { for (size_t j = 0; j < entries; ++ j) { ((float*)pMatrix)[j * 4 + i] = ((float*)pSrcData)[j]; } pSrcData += SType::c_RegisterSize; } } template<bool Transpose, bool IsSetting, bool ExtraIndirection> HRESULT DoMatrixArrayInternal(_In_ const SType *pType, _In_ uint32_t TotalUnpackedSize, _Out_ uint8_t *pEffectData, void *pMatrixData, _In_ uint32_t Offset, _In_ uint32_t Count, _In_z_ LPCSTR pFuncName) { HRESULT hr = S_OK; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } #else UNREFERENCED_PARAMETER(TotalUnpackedSize); UNREFERENCED_PARAMETER(pFuncName); #endif if ((pType->NumericType.IsColumnMajor && Transpose) || (!pType->NumericType.IsColumnMajor && !Transpose)) { // fast path uint32_t dataSize; if (Transpose) { dataSize = ((pType->NumericType.Columns - 1) * 4 + pType->NumericType.Rows) * SType::c_ScalarSize; } else { dataSize = ((pType->NumericType.Rows - 1) * 4 + pType->NumericType.Columns) * SType::c_ScalarSize; } for (size_t i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix; if (ExtraIndirection) { pMatrix = ((CEffectMatrix **)pMatrixData)[i]; if (!pMatrix) { continue; } } else { pMatrix = ((CEffectMatrix *)pMatrixData) + i; } if (IsSetting) { memcpy(pEffectData + pType->Stride * (i + Offset), pMatrix, dataSize); } else { memcpy(pMatrix, pEffectData + pType->Stride * (i + Offset), dataSize); } } } else { // slow path for (size_t i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix; if (ExtraIndirection) { pMatrix = ((CEffectMatrix **)pMatrixData)[i]; if (!pMatrix) { continue; } } else { pMatrix = ((CEffectMatrix *)pMatrixData) + i; } if (IsSetting) { SetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); } else { GetMatrixTransposeHelper<Transpose>(pType, pEffectData + pType->Stride * (i + Offset), (float*) pMatrix); } } } lExit: return hr; } #pragma warning (pop) template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrix(const float *pData) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrix"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<false, true, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), 0, 1, pFuncName); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrix(float *pData) { return DoMatrixArrayInternal<false, false, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrix"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixArray(const float *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<false, true, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixArray(float *pData, uint32_t Offset, uint32_t Count) { return DoMatrixArrayInternal<false, false, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixPointerArray(const float **ppData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<false, true, true>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixPointerArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixPointerArray(float **ppData, uint32_t Offset, uint32_t Count) { return DoMatrixArrayInternal<false, false, true>(pType, GetTotalUnpackedSize(), Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixPointerArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTranspose(const float *pData) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTranspose"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<true, true, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), 0, 1, "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTranspose(float *pData) { return DoMatrixArrayInternal<true, false, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, 0, 1, "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposeArray(const float *pData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<true, true, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float*>(pData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposeArray(float *pData, uint32_t Offset, uint32_t Count) { return DoMatrixArrayInternal<true, false, false>(pType, GetTotalUnpackedSize(), Data.pNumeric, pData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::SetMatrixTransposePointerArray(const float **ppData, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"; if (IsAnnotation) return AnnotationInvalidSetCall(pFuncName); DirtyVariable(); return DoMatrixArrayInternal<true, true, true>(pType, GetTotalUnpackedSize(), Data.pNumeric, const_cast<float**>(ppData), Offset, Count, "ID3DX11EffectMatrixVariable::SetMatrixTransposePointerArray"); } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TMatrixVariable<IBaseInterface, IsAnnotation>::GetMatrixTransposePointerArray(float **ppData, uint32_t Offset, uint32_t Count) { return DoMatrixArrayInternal<true, false, true>(pType, GetTotalUnpackedSize(), Data.pNumeric, ppData, Offset, Count, "ID3DX11EffectMatrixVariable::GetMatrixTransposePointerArray"); } // Optimize commonly used fast paths // (non-annotations only!) template<typename IBaseInterface, bool IsColumnMajor> struct TMatrix4x4Variable : public TMatrixVariable<IBaseInterface, false> { STDMETHOD(SetMatrix)(_In_reads_(16) const float *pData) override; STDMETHOD(GetMatrix)(_Out_writes_(16) float *pData) override; STDMETHOD(SetMatrixArray)(_In_reads_(16*Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetMatrixArray)(_Out_writes_(16*Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(SetMatrixTranspose)(_In_reads_(16) const float *pData) override; STDMETHOD(GetMatrixTranspose)(_Out_writes_(16) float *pData) override; STDMETHOD(SetMatrixTransposeArray)(_In_reads_(16*Count) const float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetMatrixTransposeArray)(_Out_writes_(16*Count) float *pData, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; inline static void Matrix4x4TransposeHelper(_In_reads_bytes_(64) const void *pSrc, _Out_writes_bytes_(64) void *pDst) { uint8_t *pDestData = (uint8_t*)pDst; uint32_t *pMatrix = (uint32_t*)pSrc; ((uint32_t*)pDestData)[0 * 4 + 0] = pMatrix[0 * 4 + 0]; ((uint32_t*)pDestData)[0 * 4 + 1] = pMatrix[1 * 4 + 0]; ((uint32_t*)pDestData)[0 * 4 + 2] = pMatrix[2 * 4 + 0]; ((uint32_t*)pDestData)[0 * 4 + 3] = pMatrix[3 * 4 + 0]; ((uint32_t*)pDestData)[1 * 4 + 0] = pMatrix[0 * 4 + 1]; ((uint32_t*)pDestData)[1 * 4 + 1] = pMatrix[1 * 4 + 1]; ((uint32_t*)pDestData)[1 * 4 + 2] = pMatrix[2 * 4 + 1]; ((uint32_t*)pDestData)[1 * 4 + 3] = pMatrix[3 * 4 + 1]; ((uint32_t*)pDestData)[2 * 4 + 0] = pMatrix[0 * 4 + 2]; ((uint32_t*)pDestData)[2 * 4 + 1] = pMatrix[1 * 4 + 2]; ((uint32_t*)pDestData)[2 * 4 + 2] = pMatrix[2 * 4 + 2]; ((uint32_t*)pDestData)[2 * 4 + 3] = pMatrix[3 * 4 + 2]; ((uint32_t*)pDestData)[3 * 4 + 0] = pMatrix[0 * 4 + 3]; ((uint32_t*)pDestData)[3 * 4 + 1] = pMatrix[1 * 4 + 3]; ((uint32_t*)pDestData)[3 * 4 + 2] = pMatrix[2 * 4 + 3]; ((uint32_t*)pDestData)[3 * 4 + 3] = pMatrix[3 * 4 + 3]; } inline static void Matrix4x4Copy(_In_reads_bytes_(64) const void *pSrc, _Out_writes_bytes_(64) void *pDst) { #if 1 // In tests, this path ended up generating faster code both on x86 and x64 // T1 - Matrix4x4Copy - this path // T2 - Matrix4x4Transpose // T1: 1.88 T2: 1.92 - with 32 bit copies // T1: 1.85 T2: 1.80 - with 64 bit copies uint64_t *pDestData = (uint64_t*)pDst; uint64_t *pMatrix = (uint64_t*)pSrc; pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; #else uint32_t *pDestData = (uint32_t*)pDst; uint32_t *pMatrix = (uint32_t*)pSrc; pDestData[0 * 4 + 0] = pMatrix[0 * 4 + 0]; pDestData[0 * 4 + 1] = pMatrix[0 * 4 + 1]; pDestData[0 * 4 + 2] = pMatrix[0 * 4 + 2]; pDestData[0 * 4 + 3] = pMatrix[0 * 4 + 3]; pDestData[1 * 4 + 0] = pMatrix[1 * 4 + 0]; pDestData[1 * 4 + 1] = pMatrix[1 * 4 + 1]; pDestData[1 * 4 + 2] = pMatrix[1 * 4 + 2]; pDestData[1 * 4 + 3] = pMatrix[1 * 4 + 3]; pDestData[2 * 4 + 0] = pMatrix[2 * 4 + 0]; pDestData[2 * 4 + 1] = pMatrix[2 * 4 + 1]; pDestData[2 * 4 + 2] = pMatrix[2 * 4 + 2]; pDestData[2 * 4 + 3] = pMatrix[2 * 4 + 3]; pDestData[3 * 4 + 0] = pMatrix[3 * 4 + 0]; pDestData[3 * 4 + 1] = pMatrix[3 * 4 + 1]; pDestData[3 * 4 + 2] = pMatrix[3 * 4 + 2]; pDestData[3 * 4 + 3] = pMatrix[3 * 4 + 3]; #endif } // Note that branches in this code is based on template parameters and will be compiled out #pragma warning (push) #pragma warning (disable : 6101) template<bool IsColumnMajor, bool Transpose, bool IsSetting> inline HRESULT DoMatrix4x4ArrayInternal(_In_ uint8_t *pEffectData, _When_(IsSetting, _In_reads_bytes_(64 * Count)) _When_(!IsSetting, _Out_writes_bytes_(64 * Count)) void *pMatrixData, _In_ uint32_t Offset, _In_ uint32_t Count #ifdef _DEBUG , _In_ const SType *pType, _In_ uint32_t TotalUnpackedSize, _In_z_ LPCSTR pFuncName #endif ) { HRESULT hr = S_OK; #ifdef _DEBUG #pragma warning( suppress : 6001 ) if (!AreBoundsValid(Offset, Count, pMatrixData, pType, TotalUnpackedSize)) { DPF(0, "%s: Invalid range specified", pFuncName); VH(E_INVALIDARG); } assert(pType->NumericType.IsColumnMajor == IsColumnMajor && pType->Stride == (4 * SType::c_RegisterSize)); #endif if ((IsColumnMajor && Transpose) || (!IsColumnMajor && !Transpose)) { // fast path for (size_t i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; if (IsSetting) { Matrix4x4Copy(pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); } else { Matrix4x4Copy(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), pMatrix); } } } else { // slow path for (size_t i = 0; i < Count; ++ i) { CEffectMatrix *pMatrix = ((CEffectMatrix *)pMatrixData) + i; if (IsSetting) { Matrix4x4TransposeHelper((float*) pMatrix, pEffectData + 4 * SType::c_RegisterSize * (i + Offset)); } else { Matrix4x4TransposeHelper(pEffectData + 4 * SType::c_RegisterSize * (i + Offset), (float*) pMatrix); } } } lExit: return hr; } #pragma warning (pop) template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrix(const float *pData) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, false, true>(Data.pNumeric, const_cast<float*>(pData), 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrix"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrix(float *pData) { return DoMatrix4x4ArrayInternal<IsColumnMajor, false, false>(Data.pNumeric, pData, 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrix"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixArray(const float *pData, uint32_t Offset, uint32_t Count) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, false, true>(Data.pNumeric, const_cast<float*>(pData), Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixArray"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixArray(float *pData, uint32_t Offset, uint32_t Count) { return DoMatrix4x4ArrayInternal<IsColumnMajor, false, false>(Data.pNumeric, pData, Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixArray"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTranspose(const float *pData) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, true, true>(Data.pNumeric, const_cast<float*>(pData), 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTranspose"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTranspose(float *pData) { return DoMatrix4x4ArrayInternal<IsColumnMajor, true, false>(Data.pNumeric, pData, 0, 1 #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTranspose"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::SetMatrixTransposeArray(const float *pData, uint32_t Offset, uint32_t Count) { DirtyVariable(); return DoMatrix4x4ArrayInternal<IsColumnMajor, true, true>(Data.pNumeric, const_cast<float*>(pData), Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::SetMatrixTransposeArray"); #else ); #endif } template<typename IBaseInterface, bool IsColumnMajor> _Use_decl_annotations_ HRESULT TMatrix4x4Variable<IBaseInterface, IsColumnMajor>::GetMatrixTransposeArray(float *pData, uint32_t Offset, uint32_t Count) { return DoMatrix4x4ArrayInternal<IsColumnMajor, true, false>(Data.pNumeric, pData, Offset, Count #ifdef _DEBUG , pType, GetTotalUnpackedSize(), "ID3DX11EffectMatrixVariable::GetMatrixTransposeArray"); #else ); #endif } #ifdef _DEBUG // Useful object macro to check bounds and parameters #define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ HRESULT hr = S_OK; \ VERIFYPARAMETER(Pointer) \ uint32_t elements = IsArray() ? pType->Elements : 1; \ \ if ((Offset + Count < Offset) || (elements < Offset + Count)) \ { \ DPF(0, "%s: Invalid range specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ HRESULT hr = S_OK; \ VERIFYPARAMETER(Pointer) \ uint32_t elements = IsArray() ? pType->Elements : 1; \ \ if (Index >= elements) \ { \ DPF(0, "%s: Invalid index specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #define CHECK_SCALAR_BOUNDS(Index) \ HRESULT hr = S_OK; \ uint32_t elements = IsArray() ? pType->Elements : 1; \ \ if (Index >= elements) \ { \ DPF(0, "%s: Invalid index specified", pFuncName); \ VH(E_INVALIDARG); \ } \ #else // _DEBUG #define CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, Pointer) \ HRESULT hr = S_OK; \ #define CHECK_OBJECT_SCALAR_BOUNDS(Index, Pointer) \ HRESULT hr = S_OK; \ #define CHECK_SCALAR_BOUNDS(Index) \ HRESULT hr = S_OK; \ #endif // _DEBUG ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectStringVariable (TStringVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface, bool IsAnnotation> struct TStringVariable : public IBaseInterface { STDMETHOD(GetString)(_Outptr_result_z_ LPCSTR *ppString) override; STDMETHOD(GetStringArray)( _Out_writes_(Count) LPCSTR *ppStrings, _In_ uint32_t Offset, _In_ uint32_t Count ) override; }; template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetString(LPCSTR *ppString) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetString"; VERIFYPARAMETER(ppString); if (GetTopLevelEntity()->pEffect->IsOptimized()) { DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); return D3DERR_INVALIDCALL; } assert(Data.pString != 0); _Analysis_assume_(Data.pString != 0); *ppString = Data.pString->pString; lExit: return hr; } template<typename IBaseInterface, bool IsAnnotation> _Use_decl_annotations_ #pragma warning(suppress : 6054) HRESULT TStringVariable<IBaseInterface, IsAnnotation>::GetStringArray( LPCSTR *ppStrings, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectStringVariable::GetStringArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppStrings); if (GetTopLevelEntity()->pEffect->IsOptimized()) { DPF(0, "%s: Effect has been Optimize()'ed; all string/reflection data has been deleted", pFuncName); return D3DERR_INVALIDCALL; } assert(Data.pString != 0); _Analysis_assume_(Data.pString != 0); for (size_t i = 0; i < Count; ++ i) { ppStrings[i] = (Data.pString + Offset + i)->pString; } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectClassInstanceVariable (TClassInstanceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TClassInstanceVariable : public IBaseInterface { STDMETHOD(GetClassInstance)(_Outptr_ ID3D11ClassInstance **ppClassInstance) override; }; template<typename IBaseClassInstance> HRESULT TClassInstanceVariable<IBaseClassInstance>::GetClassInstance(_Outptr_ ID3D11ClassInstance** ppClassInstance) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectClassInstanceVariable::GetClassInstance"; assert( pMemberData != 0 && pMemberData->Data.pD3DClassInstance != 0); _Analysis_assume_( pMemberData != 0 && pMemberData->Data.pD3DClassInstance != 0); *ppClassInstance = pMemberData->Data.pD3DClassInstance; SAFE_ADDREF(*ppClassInstance); lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectInterfaceeVariable (TInterfaceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TInterfaceVariable : public IBaseInterface { STDMETHOD(SetClassInstance)(_In_ ID3DX11EffectClassInstanceVariable *pEffectClassInstance) override; STDMETHOD(GetClassInstance)(_Outptr_ ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) override; }; template<typename IBaseInterface> HRESULT TInterfaceVariable<IBaseInterface>::SetClassInstance(_In_ ID3DX11EffectClassInstanceVariable *pEffectClassInstance) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::SetClassInstance"; // Note that we don't check if the types are compatible. The debug layer will complain if it is. // IsValid() will not catch type mismatches. SClassInstanceGlobalVariable* pCI = (SClassInstanceGlobalVariable*)pEffectClassInstance; Data.pInterface->pClassInstance = pCI; lExit: return hr; } template<typename IBaseInterface> HRESULT TInterfaceVariable<IBaseInterface>::GetClassInstance(_Outptr_ ID3DX11EffectClassInstanceVariable **ppEffectClassInstance) { HRESULT hr = S_OK; static LPCSTR pFuncName = "ID3DX11EffectInterfaceVariable::GetClassInstance"; #ifdef _DEBUG VERIFYPARAMETER(ppEffectClassInstance); #endif *ppEffectClassInstance = Data.pInterface->pClassInstance; lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectShaderResourceVariable (TShaderResourceVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TShaderResourceVariable : public IBaseInterface { STDMETHOD(SetResource)(_In_ ID3D11ShaderResourceView *pResource) override; STDMETHOD(GetResource)(_Outptr_ ID3D11ShaderResourceView **ppResource) override; STDMETHOD(SetResourceArray)(_In_reads_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetResourceArray)(_Out_writes_(Count) ID3D11ShaderResourceView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; static LPCSTR GetTextureTypeNameFromEnum(_In_ EObjectType ObjectType) { switch (ObjectType) { case EOT_Buffer: return "Buffer"; case EOT_Texture: return "texture"; case EOT_Texture1D: case EOT_Texture1DArray: return "Texture1D"; case EOT_Texture2DMS: case EOT_Texture2DMSArray: return "Texture2DMS"; case EOT_Texture2D: case EOT_Texture2DArray: return "Texture2D"; case EOT_Texture3D: return "Texture3D"; case EOT_TextureCube: return "TextureCube"; case EOT_TextureCubeArray: return "TextureCubeArray"; case EOT_RWTexture1D: case EOT_RWTexture1DArray: return "RWTexture1D"; case EOT_RWTexture2D: case EOT_RWTexture2DArray: return "RWTexture2D"; case EOT_RWTexture3D: return "RWTexture3D"; case EOT_RWBuffer: return "RWBuffer"; case EOT_ByteAddressBuffer: return "ByteAddressBuffer"; case EOT_RWByteAddressBuffer: return "RWByteAddressBuffer"; case EOT_StructuredBuffer: return "StructuredBuffe"; case EOT_RWStructuredBuffer: return "RWStructuredBuffer"; case EOT_RWStructuredBufferAlloc: return "RWStructuredBufferAlloc"; case EOT_RWStructuredBufferConsume: return "RWStructuredBufferConsume"; case EOT_AppendStructuredBuffer: return "AppendStructuredBuffer"; case EOT_ConsumeStructuredBuffer: return "ConsumeStructuredBuffer"; } return "<unknown texture format>"; } static LPCSTR GetResourceDimensionNameFromEnum(_In_ D3D11_RESOURCE_DIMENSION ResourceDimension) { switch (ResourceDimension) { case D3D11_RESOURCE_DIMENSION_BUFFER: return "Buffer"; case D3D11_RESOURCE_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_RESOURCE_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_RESOURCE_DIMENSION_TEXTURE3D: return "Texture3D"; } return "<unknown texture format>"; } static LPCSTR GetSRVDimensionNameFromEnum(_In_ D3D11_SRV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_SRV_DIMENSION_BUFFER: case D3D11_SRV_DIMENSION_BUFFEREX: return "Buffer"; case D3D11_SRV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_SRV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_SRV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_SRV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_SRV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; case D3D11_SRV_DIMENSION_TEXTURE3D: return "Texture3D"; case D3D11_SRV_DIMENSION_TEXTURECUBE: return "TextureCube"; } return "<unknown texture format>"; } static LPCSTR GetUAVDimensionNameFromEnum(_In_ D3D11_UAV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_UAV_DIMENSION_BUFFER: return "Buffer"; case D3D11_UAV_DIMENSION_TEXTURE1D: return "RWTexture1D"; case D3D11_UAV_DIMENSION_TEXTURE1DARRAY: return "RWTexture1DArray"; case D3D11_UAV_DIMENSION_TEXTURE2D: return "RWTexture2D"; case D3D11_UAV_DIMENSION_TEXTURE2DARRAY: return "RWTexture2DArray"; case D3D11_UAV_DIMENSION_TEXTURE3D: return "RWTexture3D"; } return "<unknown texture format>"; } static LPCSTR GetRTVDimensionNameFromEnum(_In_ D3D11_RTV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_RTV_DIMENSION_BUFFER: return "Buffer"; case D3D11_RTV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_RTV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_RTV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_RTV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_RTV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_RTV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; case D3D11_RTV_DIMENSION_TEXTURE3D: return "Texture3D"; } return "<unknown texture format>"; } static LPCSTR GetDSVDimensionNameFromEnum(_In_ D3D11_DSV_DIMENSION ViewDimension) { switch (ViewDimension) { case D3D11_DSV_DIMENSION_TEXTURE1D: return "Texture1D"; case D3D11_DSV_DIMENSION_TEXTURE1DARRAY: return "Texture1DArray"; case D3D11_DSV_DIMENSION_TEXTURE2D: return "Texture2D"; case D3D11_DSV_DIMENSION_TEXTURE2DARRAY: return "Texture2DArray"; case D3D11_DSV_DIMENSION_TEXTURE2DMS: return "Texture2DMS"; case D3D11_DSV_DIMENSION_TEXTURE2DMSARRAY: return "Texture2DMSArray"; } return "<unknown texture format>"; } static HRESULT ValidateTextureType(_In_ ID3D11ShaderResourceView *pView, _In_ EObjectType ObjectType, _In_z_ LPCSTR pFuncName) { if (nullptr != pView) { D3D11_SHADER_RESOURCE_VIEW_DESC desc; pView->GetDesc(&desc); switch (ObjectType) { case EOT_Texture: if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) return S_OK; break; case EOT_Buffer: if (desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFER && desc.ViewDimension != D3D11_SRV_DIMENSION_BUFFEREX) break; if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) { DPF(0, "%s: Resource type mismatch; %s expected, ByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { ID3D11Buffer* pBuffer = nullptr; pView->GetResource( (ID3D11Resource**)&pBuffer ); assert( pBuffer != nullptr ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { DPF(0, "%s: Resource type mismatch; %s expected, StructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { return S_OK; } } break; case EOT_Texture1D: case EOT_Texture1DArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1D || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE1DARRAY) return S_OK; break; case EOT_Texture2D: case EOT_Texture2DArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2D || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DARRAY) return S_OK; break; case EOT_Texture2DMS: case EOT_Texture2DMSArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMS || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE2DMSARRAY) return S_OK; break; case EOT_Texture3D: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURE3D) return S_OK; break; case EOT_TextureCube: case EOT_TextureCubeArray: if (desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBE || desc.ViewDimension == D3D11_SRV_DIMENSION_TEXTURECUBEARRAY) return S_OK; break; case EOT_ByteAddressBuffer: if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX && (desc.BufferEx.Flags & D3D11_BUFFEREX_SRV_FLAG_RAW)) return S_OK; break; case EOT_StructuredBuffer: if (desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFEREX || desc.ViewDimension == D3D11_SRV_DIMENSION_BUFFER) { ID3D11Buffer* pBuffer = nullptr; pView->GetResource( (ID3D11Resource**)&pBuffer ); assert( pBuffer != nullptr ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } } break; default: assert(0); // internal error, should never get here return E_FAIL; } DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetSRVDimensionNameFromEnum(desc.ViewDimension)); return E_INVALIDARG; } return S_OK; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderResourceVariable<IBaseInterface>::SetResource(ID3D11ShaderResourceView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResource"; VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pShaderResource->pShaderResource); Data.pShaderResource->pShaderResource = pResource; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderResourceVariable<IBaseInterface>::GetResource(ID3D11ShaderResourceView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResource"; VERIFYPARAMETER(ppResource); #endif assert(Data.pShaderResource != 0 && Data.pShaderResource->pShaderResource != 0); _Analysis_assume_(Data.pShaderResource != 0 && Data.pShaderResource->pShaderResource != 0); *ppResource = Data.pShaderResource->pShaderResource; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderResourceVariable<IBaseInterface>::SetResourceArray(ID3D11ShaderResourceView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::SetResourceArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); #ifdef _DEBUG for (size_t i = 0; i < Count; ++ i) { VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); } #endif // Texture variables don't need to be dirtied. for (size_t i = 0; i < Count; ++ i) { SShaderResource *pResourceBlock = Data.pShaderResource + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pShaderResource); pResourceBlock->pShaderResource = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderResourceVariable<IBaseInterface>::GetResourceArray(ID3D11ShaderResourceView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectShaderResourceVariable::GetResourceArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); for (size_t i = 0; i < Count; ++ i) { ppResources[i] = (Data.pShaderResource + Offset + i)->pShaderResource; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectUnorderedAccessViewVariable (TUnorderedAccessViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TUnorderedAccessViewVariable : public IBaseInterface { STDMETHOD(SetUnorderedAccessView)(_In_ ID3D11UnorderedAccessView *pResource) override; STDMETHOD(GetUnorderedAccessView)(_Outptr_ ID3D11UnorderedAccessView **ppResource) override; STDMETHOD(SetUnorderedAccessViewArray)(_In_reads_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetUnorderedAccessViewArray)(_Out_writes_(Count) ID3D11UnorderedAccessView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; static HRESULT ValidateTextureType(_In_ ID3D11UnorderedAccessView *pView, _In_ EObjectType ObjectType, _In_z_ LPCSTR pFuncName) { if (nullptr != pView) { D3D11_UNORDERED_ACCESS_VIEW_DESC desc; pView->GetDesc(&desc); switch (ObjectType) { case EOT_RWBuffer: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW) { DPF(0, "%s: Resource type mismatch; %s expected, RWByteAddressBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { ID3D11Buffer* pBuffer = nullptr; pView->GetResource( (ID3D11Resource**)&pBuffer ); assert( pBuffer != nullptr ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { DPF(0, "%s: Resource type mismatch; %s expected, an RWStructuredBuffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } else { return S_OK; } } break; case EOT_RWTexture1D: case EOT_RWTexture1DArray: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1D || desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE1DARRAY) return S_OK; break; case EOT_RWTexture2D: case EOT_RWTexture2DArray: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2D || desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE2DARRAY) return S_OK; break; case EOT_RWTexture3D: if (desc.ViewDimension == D3D11_UAV_DIMENSION_TEXTURE3D) return S_OK; break; case EOT_RWByteAddressBuffer: if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER && (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_RAW)) return S_OK; break; case EOT_RWStructuredBuffer: if (desc.ViewDimension == D3D11_UAV_DIMENSION_BUFFER) { ID3D11Buffer* pBuffer = nullptr; pView->GetResource( (ID3D11Resource**)&pBuffer ); assert( pBuffer != nullptr ); D3D11_BUFFER_DESC BufDesc; pBuffer->GetDesc( &BufDesc ); SAFE_RELEASE( pBuffer ); if( BufDesc.MiscFlags & D3D11_RESOURCE_MISC_BUFFER_STRUCTURED ) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-structured Buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } } break; case EOT_RWStructuredBufferAlloc: case EOT_RWStructuredBufferConsume: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_COUNTER) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-Counter buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } break; case EOT_AppendStructuredBuffer: case EOT_ConsumeStructuredBuffer: if (desc.ViewDimension != D3D11_UAV_DIMENSION_BUFFER) break; if (desc.Buffer.Flags & D3D11_BUFFER_UAV_FLAG_APPEND) { return S_OK; } else { DPF(0, "%s: Resource type mismatch; %s expected, non-Append buffer provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType)); return E_INVALIDARG; } break; default: assert(0); // internal error, should never get here return E_FAIL; } DPF(0, "%s: Resource type mismatch; %s expected, %s provided.", pFuncName, GetTextureTypeNameFromEnum(ObjectType), GetUAVDimensionNameFromEnum(desc.ViewDimension)); return E_INVALIDARG; } return S_OK; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessView(ID3D11UnorderedAccessView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessView"; VH(ValidateTextureType(pResource, pType->ObjectType, pFuncName)); #endif // UAV variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pUnorderedAccessView->pUnorderedAccessView); Data.pUnorderedAccessView->pUnorderedAccessView = pResource; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessView(ID3D11UnorderedAccessView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessView"; VERIFYPARAMETER(ppResource); #endif assert(Data.pUnorderedAccessView != 0 && Data.pUnorderedAccessView->pUnorderedAccessView != 0); _Analysis_assume_(Data.pUnorderedAccessView != 0 && Data.pUnorderedAccessView->pUnorderedAccessView != 0); *ppResource = Data.pUnorderedAccessView->pUnorderedAccessView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TUnorderedAccessViewVariable<IBaseInterface>::SetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::SetUnorderedAccessViewArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); #ifdef _DEBUG for (size_t i = 0; i < Count; ++ i) { VH(ValidateTextureType(ppResources[i], pType->ObjectType, pFuncName)); } #endif // Texture variables don't need to be dirtied. for (size_t i = 0; i < Count; ++ i) { SUnorderedAccessView *pResourceBlock = Data.pUnorderedAccessView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pUnorderedAccessView); pResourceBlock->pUnorderedAccessView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TUnorderedAccessViewVariable<IBaseInterface>::GetUnorderedAccessViewArray(ID3D11UnorderedAccessView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectUnorderedAccessViewVariable::GetUnorderedAccessViewArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); for (size_t i = 0; i < Count; ++ i) { ppResources[i] = (Data.pUnorderedAccessView + Offset + i)->pUnorderedAccessView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectRenderTargetViewVariable (TRenderTargetViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TRenderTargetViewVariable : public IBaseInterface { STDMETHOD(SetRenderTarget)(_In_ ID3D11RenderTargetView *pResource) override; STDMETHOD(GetRenderTarget)(_Outptr_ ID3D11RenderTargetView **ppResource) override; STDMETHOD(SetRenderTargetArray)(_In_reads_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetRenderTargetArray)(_Out_writes_(Count) ID3D11RenderTargetView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTarget(ID3D11RenderTargetView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTarget"; #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pRenderTargetView->pRenderTargetView); Data.pRenderTargetView->pRenderTargetView = pResource; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTarget(ID3D11RenderTargetView **ppResource) { HRESULT hr = S_OK; assert(Data.pRenderTargetView->pRenderTargetView != 0); _Analysis_assume_(Data.pRenderTargetView->pRenderTargetView != 0); *ppResource = Data.pRenderTargetView->pRenderTargetView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRenderTargetViewVariable<IBaseInterface>::SetRenderTargetArray(ID3D11RenderTargetView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::SetRenderTargetArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); // Texture variables don't need to be dirtied. for (size_t i = 0; i < Count; ++ i) { SRenderTargetView *pResourceBlock = Data.pRenderTargetView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pRenderTargetView); pResourceBlock->pRenderTargetView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRenderTargetViewVariable<IBaseInterface>::GetRenderTargetArray(ID3D11RenderTargetView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3DX11EffectRenderTargetVariable::GetRenderTargetArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); for (size_t i = 0; i < Count; ++ i) { ppResources[i] = (Data.pRenderTargetView + Offset + i)->pRenderTargetView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } ////////////////////////////////////////////////////////////////////////// // ID3DX11EffectDepthStencilViewVariable (TDepthStencilViewVariable implementation) ////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TDepthStencilViewVariable : public IBaseInterface { STDMETHOD(SetDepthStencil)(_In_ ID3D11DepthStencilView *pResource) override; STDMETHOD(GetDepthStencil)(_Outptr_ ID3D11DepthStencilView **ppResource) override; STDMETHOD(SetDepthStencilArray)(_In_reads_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; STDMETHOD(GetDepthStencilArray)(_Out_writes_(Count) ID3D11DepthStencilView **ppResources, _In_ uint32_t Offset, _In_ uint32_t Count) override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencil(ID3D11DepthStencilView *pResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencil"; #endif // Texture variables don't need to be dirtied. SAFE_ADDREF(pResource); SAFE_RELEASE(Data.pDepthStencilView->pDepthStencilView); Data.pDepthStencilView->pDepthStencilView = pResource; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencil(ID3D11DepthStencilView **ppResource) { HRESULT hr = S_OK; #ifdef _DEBUG static LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencil"; VERIFYPARAMETER(ppResource); #endif assert(Data.pDepthStencilView->pDepthStencilView != 0); _Analysis_assume_(Data.pDepthStencilView->pDepthStencilView != 0); *ppResource = Data.pDepthStencilView->pDepthStencilView; SAFE_ADDREF(*ppResource); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilViewVariable<IBaseInterface>::SetDepthStencilArray(ID3D11DepthStencilView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::SetDepthStencilArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); // Texture variables don't need to be dirtied. for (size_t i = 0; i < Count; ++ i) { SDepthStencilView *pResourceBlock = Data.pDepthStencilView + Offset + i; SAFE_ADDREF(ppResources[i]); SAFE_RELEASE(pResourceBlock->pDepthStencilView); pResourceBlock->pDepthStencilView = ppResources[i]; } lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilViewVariable<IBaseInterface>::GetDepthStencilArray(ID3D11DepthStencilView **ppResources, uint32_t Offset, uint32_t Count) { static LPCSTR pFuncName = "ID3D11DepthStencilViewVariable::GetDepthStencilArray"; CHECK_OBJECT_ARRAY_BOUNDS(Offset, Count, ppResources); for (size_t i = 0; i < Count; ++ i) { ppResources[i] = (Data.pDepthStencilView + Offset + i)->pDepthStencilView; SAFE_ADDREF(ppResources[i]); } lExit: return hr; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectShaderVariable (TShaderVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TShaderVariable : public IBaseInterface { STDMETHOD(GetShaderDesc)(_In_ uint32_t ShaderIndex, _Out_ D3DX11_EFFECT_SHADER_DESC *pDesc) override; STDMETHOD(GetVertexShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11VertexShader **ppVS) override; STDMETHOD(GetGeometryShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11GeometryShader **ppGS) override; STDMETHOD(GetPixelShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11PixelShader **ppPS) override; STDMETHOD(GetHullShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11HullShader **ppHS) override; STDMETHOD(GetDomainShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11DomainShader **ppDS) override; STDMETHOD(GetComputeShader)(_In_ uint32_t ShaderIndex, _Outptr_ ID3D11ComputeShader **ppCS) override; STDMETHOD(GetInputSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override; STDMETHOD(GetOutputSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override; STDMETHOD(GetPatchConstantSignatureElementDesc)(_In_ uint32_t ShaderIndex, _In_ uint32_t Element, _Out_ D3D11_SIGNATURE_PARAMETER_DESC *pDesc) override; STDMETHOD_(bool, IsValid)(); }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetShaderDesc(uint32_t ShaderIndex, D3DX11_EFFECT_SHADER_DESC *pDesc) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetShaderDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); hr = Data.pShader[ShaderIndex].GetShaderDesc(pDesc, false); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetVertexShader(uint32_t ShaderIndex, ID3D11VertexShader **ppVS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetVertexShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppVS); VH( Data.pShader[ShaderIndex].GetVertexShader(ppVS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetGeometryShader(uint32_t ShaderIndex, ID3D11GeometryShader **ppGS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetGeometryShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppGS); VH( Data.pShader[ShaderIndex].GetGeometryShader(ppGS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetPixelShader(uint32_t ShaderIndex, ID3D11PixelShader **ppPS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPixelShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppPS); VH( Data.pShader[ShaderIndex].GetPixelShader(ppPS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetHullShader(uint32_t ShaderIndex, ID3D11HullShader **ppHS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetHullShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppHS); VH( Data.pShader[ShaderIndex].GetHullShader(ppHS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetDomainShader(uint32_t ShaderIndex, ID3D11DomainShader **ppDS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetDomainShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppDS); VH( Data.pShader[ShaderIndex].GetDomainShader(ppDS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetComputeShader(uint32_t ShaderIndex, ID3D11ComputeShader **ppCS) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetComputeShader"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, ppCS); VH( Data.pShader[ShaderIndex].GetComputeShader(ppCS) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetInputSignatureElementDesc(uint32_t ShaderIndex, uint32_t Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetInputSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Input, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetOutputSignatureElementDesc(uint32_t ShaderIndex, uint32_t Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetOutputSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_Output, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TShaderVariable<IBaseInterface>::GetPatchConstantSignatureElementDesc(uint32_t ShaderIndex, uint32_t Element, D3D11_SIGNATURE_PARAMETER_DESC *pDesc) { static LPCSTR pFuncName = "ID3DX11EffectShaderVariable::GetPatchConstantSignatureElementDesc"; CHECK_OBJECT_SCALAR_BOUNDS(ShaderIndex, pDesc); VH( Data.pShader[ShaderIndex].GetSignatureElementDesc(SShaderBlock::ST_PatchConstant, Element, pDesc) ); lExit: return hr; } template<typename IBaseInterface> bool TShaderVariable<IBaseInterface>::IsValid() { uint32_t numElements = IsArray()? pType->Elements : 1; bool valid = true; while( numElements > 0 && ( valid = Data.pShader[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectBlendVariable (TBlendVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TBlendVariable : public IBaseInterface { public: STDMETHOD(GetBlendState)(_In_ uint32_t Index, _Outptr_ ID3D11BlendState **ppState) override; STDMETHOD(SetBlendState)(_In_ uint32_t Index, _In_ ID3D11BlendState *pState) override; STDMETHOD(UndoSetBlendState)(_In_ uint32_t Index) override; STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_BLEND_DESC *pDesc) override; STDMETHOD_(bool, IsValid)() override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TBlendVariable<IBaseInterface>::GetBlendState(uint32_t Index, ID3D11BlendState **ppState) { static LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBlendState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppState); assert(Data.pBlend[Index].pBlendObject != 0); _Analysis_assume_(Data.pBlend[Index].pBlendObject != 0); *ppState = Data.pBlend[Index].pBlendObject; SAFE_ADDREF(*ppState); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TBlendVariable<IBaseInterface>::SetBlendState(uint32_t Index, ID3D11BlendState *pState) { static LPCSTR pFuncName = "ID3DX11EffectBlendState::SetBlendState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pBlend[Index].IsUserManaged ) { // Save original state object in case we UndoSet assert( pMemberData[Index].Type == MDT_BlendState ); VB( pMemberData[Index].Data.pD3DEffectsManagedBlendState == nullptr ); pMemberData[Index].Data.pD3DEffectsManagedBlendState = Data.pBlend[Index].pBlendObject; Data.pBlend[Index].pBlendObject = nullptr; Data.pBlend[Index].IsUserManaged = true; } SAFE_ADDREF( pState ); SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); Data.pBlend[Index].pBlendObject = pState; Data.pBlend[Index].IsValid = true; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TBlendVariable<IBaseInterface>::UndoSetBlendState(uint32_t Index) { static LPCSTR pFuncName = "ID3DX11EffectBlendState::UndoSetBlendState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pBlend[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pBlend[Index].pBlendObject ); Data.pBlend[Index].pBlendObject = pMemberData[Index].Data.pD3DEffectsManagedBlendState; pMemberData[Index].Data.pD3DEffectsManagedBlendState = nullptr; Data.pBlend[Index].IsUserManaged = false; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TBlendVariable<IBaseInterface>::GetBackingStore(uint32_t Index, D3D11_BLEND_DESC *pBlendDesc) { static LPCSTR pFuncName = "ID3DX11EffectBlendVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pBlendDesc); if( Data.pBlend[Index].IsUserManaged ) { if( Data.pBlend[Index].pBlendObject ) { Data.pBlend[Index].pBlendObject->GetDesc( pBlendDesc ); } else { *pBlendDesc = CD3D11_BLEND_DESC( D3D11_DEFAULT ); } } else { SBlendBlock *pBlock = Data.pBlend + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy( pBlendDesc, &pBlock->BackingStore, sizeof(D3D11_BLEND_DESC) ); } lExit: return hr; } template<typename IBaseInterface> bool TBlendVariable<IBaseInterface>::IsValid() { uint32_t numElements = IsArray()? pType->Elements : 1; bool valid = true; while( numElements > 0 && ( valid = Data.pBlend[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectDepthStencilVariable (TDepthStencilVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TDepthStencilVariable : public IBaseInterface { public: STDMETHOD(GetDepthStencilState)(_In_ uint32_t Index, _Outptr_ ID3D11DepthStencilState **ppState) override; STDMETHOD(SetDepthStencilState)(_In_ uint32_t Index, _In_ ID3D11DepthStencilState *pState) override; STDMETHOD(UndoSetDepthStencilState)(_In_ uint32_t Index) override; STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_DEPTH_STENCIL_DESC *pDesc) override; STDMETHOD_(bool, IsValid)() override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilVariable<IBaseInterface>::GetDepthStencilState(uint32_t Index, ID3D11DepthStencilState **ppState) { static LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetDepthStencilState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppState); assert(Data.pDepthStencil[Index].pDSObject != 0); _Analysis_assume_(Data.pDepthStencil[Index].pDSObject != 0); *ppState = Data.pDepthStencil[Index].pDSObject; SAFE_ADDREF(*ppState); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilVariable<IBaseInterface>::SetDepthStencilState(uint32_t Index, ID3D11DepthStencilState *pState) { static LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::SetDepthStencilState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pDepthStencil[Index].IsUserManaged ) { // Save original state object in case we UndoSet assert( pMemberData[Index].Type == MDT_DepthStencilState ); VB( pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState == nullptr ); pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = Data.pDepthStencil[Index].pDSObject; Data.pDepthStencil[Index].pDSObject = nullptr; Data.pDepthStencil[Index].IsUserManaged = true; } SAFE_ADDREF( pState ); SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); Data.pDepthStencil[Index].pDSObject = pState; Data.pDepthStencil[Index].IsValid = true; lExit: return hr; } template<typename IBaseInterface> HRESULT TDepthStencilVariable<IBaseInterface>::UndoSetDepthStencilState(_In_ uint32_t Index) { static LPCSTR pFuncName = "ID3DX11EffectDepthStencilState::UndoSetDepthStencilState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pDepthStencil[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pDepthStencil[Index].pDSObject ); Data.pDepthStencil[Index].pDSObject = pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState; pMemberData[Index].Data.pD3DEffectsManagedDepthStencilState = nullptr; Data.pDepthStencil[Index].IsUserManaged = false; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TDepthStencilVariable<IBaseInterface>::GetBackingStore(uint32_t Index, D3D11_DEPTH_STENCIL_DESC *pDepthStencilDesc) { static LPCSTR pFuncName = "ID3DX11EffectDepthStencilVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pDepthStencilDesc); if( Data.pDepthStencil[Index].IsUserManaged ) { if( Data.pDepthStencil[Index].pDSObject ) { Data.pDepthStencil[Index].pDSObject->GetDesc( pDepthStencilDesc ); } else { *pDepthStencilDesc = CD3D11_DEPTH_STENCIL_DESC( D3D11_DEFAULT ); } } else { SDepthStencilBlock *pBlock = Data.pDepthStencil + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pDepthStencilDesc, &pBlock->BackingStore, sizeof(D3D11_DEPTH_STENCIL_DESC)); } lExit: return hr; } template<typename IBaseInterface> bool TDepthStencilVariable<IBaseInterface>::IsValid() { uint32_t numElements = IsArray()? pType->Elements : 1; bool valid = true; while( numElements > 0 && ( valid = Data.pDepthStencil[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectRasterizerVariable (TRasterizerVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TRasterizerVariable : public IBaseInterface { public: STDMETHOD(GetRasterizerState)(_In_ uint32_t Index, _Outptr_ ID3D11RasterizerState **ppState) override; STDMETHOD(SetRasterizerState)(_In_ uint32_t Index, _In_ ID3D11RasterizerState *pState) override; STDMETHOD(UndoSetRasterizerState)(_In_ uint32_t Index) override; STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_RASTERIZER_DESC *pDesc) override; STDMETHOD_(bool, IsValid)() override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRasterizerVariable<IBaseInterface>::GetRasterizerState(uint32_t Index, ID3D11RasterizerState **ppState) { static LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetRasterizerState"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppState); assert(Data.pRasterizer[Index].pRasterizerObject != 0); _Analysis_assume_(Data.pRasterizer[Index].pRasterizerObject != 0); *ppState = Data.pRasterizer[Index].pRasterizerObject; SAFE_ADDREF(*ppState); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRasterizerVariable<IBaseInterface>::SetRasterizerState(uint32_t Index, ID3D11RasterizerState *pState) { static LPCSTR pFuncName = "ID3DX11EffectRasterizerState::SetRasterizerState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pRasterizer[Index].IsUserManaged ) { // Save original state object in case we UndoSet assert( pMemberData[Index].Type == MDT_RasterizerState ); VB( pMemberData[Index].Data.pD3DEffectsManagedRasterizerState == nullptr ); pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = Data.pRasterizer[Index].pRasterizerObject; Data.pRasterizer[Index].pRasterizerObject = nullptr; Data.pRasterizer[Index].IsUserManaged = true; } SAFE_ADDREF( pState ); SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); Data.pRasterizer[Index].pRasterizerObject = pState; Data.pRasterizer[Index].IsValid = true; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRasterizerVariable<IBaseInterface>::UndoSetRasterizerState(uint32_t Index) { static LPCSTR pFuncName = "ID3DX11EffectRasterizerState::UndoSetRasterizerState"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pRasterizer[Index].IsUserManaged ) { return S_FALSE; } // Revert to original state object SAFE_RELEASE( Data.pRasterizer[Index].pRasterizerObject ); Data.pRasterizer[Index].pRasterizerObject = pMemberData[Index].Data.pD3DEffectsManagedRasterizerState; pMemberData[Index].Data.pD3DEffectsManagedRasterizerState = nullptr; Data.pRasterizer[Index].IsUserManaged = false; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TRasterizerVariable<IBaseInterface>::GetBackingStore(uint32_t Index, D3D11_RASTERIZER_DESC *pRasterizerDesc) { static LPCSTR pFuncName = "ID3DX11EffectRasterizerVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pRasterizerDesc); if( Data.pRasterizer[Index].IsUserManaged ) { if( Data.pRasterizer[Index].pRasterizerObject ) { Data.pRasterizer[Index].pRasterizerObject->GetDesc( pRasterizerDesc ); } else { *pRasterizerDesc = CD3D11_RASTERIZER_DESC( D3D11_DEFAULT ); } } else { SRasterizerBlock *pBlock = Data.pRasterizer + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pRasterizerDesc, &pBlock->BackingStore, sizeof(D3D11_RASTERIZER_DESC)); } lExit: return hr; } template<typename IBaseInterface> bool TRasterizerVariable<IBaseInterface>::IsValid() { uint32_t numElements = IsArray()? pType->Elements : 1; bool valid = true; while( numElements > 0 && ( valid = Data.pRasterizer[ numElements-1 ].IsValid ) ) numElements--; return valid; } //////////////////////////////////////////////////////////////////////////////// // ID3DX11EffectSamplerVariable (TSamplerVariable implementation) //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TSamplerVariable : public IBaseInterface { public: STDMETHOD(GetSampler)(_In_ uint32_t Index, _Outptr_ ID3D11SamplerState **ppSampler) override; STDMETHOD(SetSampler)(_In_ uint32_t Index, _In_ ID3D11SamplerState *pSampler) override; STDMETHOD(UndoSetSampler)(_In_ uint32_t Index) override; STDMETHOD(GetBackingStore)(_In_ uint32_t Index, _Out_ D3D11_SAMPLER_DESC *pDesc) override; }; template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TSamplerVariable<IBaseInterface>::GetSampler(uint32_t Index, ID3D11SamplerState **ppSampler) { static LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetSampler"; CHECK_OBJECT_SCALAR_BOUNDS(Index, ppSampler); _Analysis_assume_( Data.pSampler[Index].pD3DObject != 0 ); *ppSampler = Data.pSampler[Index].pD3DObject; SAFE_ADDREF(*ppSampler); lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TSamplerVariable<IBaseInterface>::SetSampler(uint32_t Index, ID3D11SamplerState *pSampler) { static LPCSTR pFuncName = "ID3DX11EffectSamplerState::SetSampler"; CHECK_SCALAR_BOUNDS(Index); // Replace all references to the old shader block with this one GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pSampler); if( !Data.pSampler[Index].IsUserManaged ) { // Save original state object in case we UndoSet assert( pMemberData[Index].Type == MDT_SamplerState ); VB( pMemberData[Index].Data.pD3DEffectsManagedSamplerState == nullptr ); pMemberData[Index].Data.pD3DEffectsManagedSamplerState = Data.pSampler[Index].pD3DObject; Data.pSampler[Index].pD3DObject = nullptr; Data.pSampler[Index].IsUserManaged = true; } SAFE_ADDREF( pSampler ); SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); Data.pSampler[Index].pD3DObject = pSampler; lExit: return hr; } template<typename IBaseInterface> HRESULT TSamplerVariable<IBaseInterface>::UndoSetSampler(_In_ uint32_t Index) { static LPCSTR pFuncName = "ID3DX11EffectSamplerState::UndoSetSampler"; CHECK_SCALAR_BOUNDS(Index); if( !Data.pSampler[Index].IsUserManaged ) { return S_FALSE; } // Replace all references to the old shader block with this one GetEffect()->ReplaceSamplerReference(&Data.pSampler[Index], pMemberData[Index].Data.pD3DEffectsManagedSamplerState); // Revert to original state object SAFE_RELEASE( Data.pSampler[Index].pD3DObject ); Data.pSampler[Index].pD3DObject = pMemberData[Index].Data.pD3DEffectsManagedSamplerState; pMemberData[Index].Data.pD3DEffectsManagedSamplerState = nullptr; Data.pSampler[Index].IsUserManaged = false; lExit: return hr; } template<typename IBaseInterface> _Use_decl_annotations_ HRESULT TSamplerVariable<IBaseInterface>::GetBackingStore(uint32_t Index, D3D11_SAMPLER_DESC *pDesc) { static LPCSTR pFuncName = "ID3DX11EffectSamplerVariable::GetBackingStore"; CHECK_OBJECT_SCALAR_BOUNDS(Index, pDesc); if( Data.pSampler[Index].IsUserManaged ) { if( Data.pSampler[Index].pD3DObject ) { Data.pSampler[Index].pD3DObject->GetDesc( pDesc ); } else { *pDesc = CD3D11_SAMPLER_DESC( D3D11_DEFAULT ); } } else { SSamplerBlock *pBlock = Data.pSampler + Index; if (pBlock->ApplyAssignments(GetTopLevelEntity()->pEffect)) { pBlock->pAssignments[0].LastRecomputedTime = 0; // Force a recreate of this block the next time ApplyRenderStateBlock is called } memcpy(pDesc, &pBlock->BackingStore.SamplerDesc, sizeof(D3D11_SAMPLER_DESC)); } lExit: return hr; } //////////////////////////////////////////////////////////////////////////////// // TUncastableVariable //////////////////////////////////////////////////////////////////////////////// template<typename IBaseInterface> struct TUncastableVariable : public IBaseInterface { STDMETHOD_(ID3DX11EffectScalarVariable*, AsScalar)() override; STDMETHOD_(ID3DX11EffectVectorVariable*, AsVector)() override; STDMETHOD_(ID3DX11EffectMatrixVariable*, AsMatrix)() override; STDMETHOD_(ID3DX11EffectStringVariable*, AsString)() override; STDMETHOD_(ID3DX11EffectClassInstanceVariable*, AsClassInstance)() override; STDMETHOD_(ID3DX11EffectInterfaceVariable*, AsInterface)() override; STDMETHOD_(ID3DX11EffectShaderResourceVariable*, AsShaderResource)() override; STDMETHOD_(ID3DX11EffectUnorderedAccessViewVariable*, AsUnorderedAccessView)() override; STDMETHOD_(ID3DX11EffectRenderTargetViewVariable*, AsRenderTargetView)() override; STDMETHOD_(ID3DX11EffectDepthStencilViewVariable*, AsDepthStencilView)() override; STDMETHOD_(ID3DX11EffectConstantBuffer*, AsConstantBuffer)() override; STDMETHOD_(ID3DX11EffectShaderVariable*, AsShader)() override; STDMETHOD_(ID3DX11EffectBlendVariable*, AsBlend)() override; STDMETHOD_(ID3DX11EffectDepthStencilVariable*, AsDepthStencil)() override; STDMETHOD_(ID3DX11EffectRasterizerVariable*, AsRasterizer)() override; STDMETHOD_(ID3DX11EffectSamplerVariable*, AsSampler)() override; }; template<typename IBaseInterface> ID3DX11EffectScalarVariable * TUncastableVariable<IBaseInterface>::AsScalar() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsScalar"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidScalarVariable; } template<typename IBaseInterface> ID3DX11EffectVectorVariable * TUncastableVariable<IBaseInterface>::AsVector() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsVector"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidVectorVariable; } template<typename IBaseInterface> ID3DX11EffectMatrixVariable * TUncastableVariable<IBaseInterface>::AsMatrix() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsMatrix"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidMatrixVariable; } template<typename IBaseInterface> ID3DX11EffectStringVariable * TUncastableVariable<IBaseInterface>::AsString() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsString"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidStringVariable; } template<typename IBaseClassInstance> ID3DX11EffectClassInstanceVariable * TUncastableVariable<IBaseClassInstance>::AsClassInstance() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsClassInstance"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidClassInstanceVariable; } template<typename IBaseInterface> ID3DX11EffectInterfaceVariable * TUncastableVariable<IBaseInterface>::AsInterface() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsInterface"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidInterfaceVariable; } template<typename IBaseInterface> ID3DX11EffectShaderResourceVariable * TUncastableVariable<IBaseInterface>::AsShaderResource() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsShaderResource"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderResourceVariable; } template<typename IBaseInterface> ID3DX11EffectUnorderedAccessViewVariable * TUncastableVariable<IBaseInterface>::AsUnorderedAccessView() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsUnorderedAccessView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidUnorderedAccessViewVariable; } template<typename IBaseInterface> ID3DX11EffectRenderTargetViewVariable * TUncastableVariable<IBaseInterface>::AsRenderTargetView() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsRenderTargetView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRenderTargetViewVariable; } template<typename IBaseInterface> ID3DX11EffectDepthStencilViewVariable * TUncastableVariable<IBaseInterface>::AsDepthStencilView() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencilView"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilViewVariable; } template<typename IBaseInterface> ID3DX11EffectConstantBuffer * TUncastableVariable<IBaseInterface>::AsConstantBuffer() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsConstantBuffer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidConstantBuffer; } template<typename IBaseInterface> ID3DX11EffectShaderVariable * TUncastableVariable<IBaseInterface>::AsShader() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsShader"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidShaderVariable; } template<typename IBaseInterface> ID3DX11EffectBlendVariable * TUncastableVariable<IBaseInterface>::AsBlend() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsBlend"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidBlendVariable; } template<typename IBaseInterface> ID3DX11EffectDepthStencilVariable * TUncastableVariable<IBaseInterface>::AsDepthStencil() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsDepthStencil"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidDepthStencilVariable; } template<typename IBaseInterface> ID3DX11EffectRasterizerVariable * TUncastableVariable<IBaseInterface>::AsRasterizer() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsRasterizer"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidRasterizerVariable; } template<typename IBaseInterface> ID3DX11EffectSamplerVariable * TUncastableVariable<IBaseInterface>::AsSampler() { static LPCSTR pFuncName = "ID3DX11EffectVariable::AsSampler"; DPF(0, "%s: Invalid typecast", pFuncName); return &g_InvalidSamplerVariable; } //////////////////////////////////////////////////////////////////////////////// // Macros to instantiate the myriad templates //////////////////////////////////////////////////////////////////////////////// // generates a global variable, annotation, global variable member, and annotation member of each struct type #define GenerateReflectionClasses(Type, BaseInterface) \ struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<BaseInterface>, false> { IUNKNOWN_IMP(S##Type##GlobalVariable, BaseInterface, ID3DX11EffectVariable); }; \ struct S##Type##Annotation : public T##Type##Variable<TAnnotation<BaseInterface>, true> { IUNKNOWN_IMP(S##Type##Annotation, BaseInterface, ID3DX11EffectVariable);}; \ struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, false> { IUNKNOWN_IMP(S##Type##GlobalVariableMember, BaseInterface, ID3DX11EffectVariable); }; \ struct S##Type##AnnotationMember : public T##Type##Variable<TVariable<TMember<BaseInterface> >, true> { IUNKNOWN_IMP(S##Type##AnnotationMember, BaseInterface, ID3DX11EffectVariable); }; #define GenerateVectorReflectionClasses(Type, BaseType, BaseInterface) \ struct S##Type##GlobalVariable : public TVectorVariable<TGlobalVariable<BaseInterface>, false, BaseType> { IUNKNOWN_IMP(S##Type##GlobalVariable, BaseInterface, ID3DX11EffectVariable); }; \ struct S##Type##Annotation : public TVectorVariable<TAnnotation<BaseInterface>, true, BaseType> { IUNKNOWN_IMP(S##Type##Annotation, BaseInterface, ID3DX11EffectVariable);}; \ struct S##Type##GlobalVariableMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, false, BaseType> { IUNKNOWN_IMP(S##Type##GlobalVariableMember, BaseInterface, ID3DX11EffectVariable);}; \ struct S##Type##AnnotationMember : public TVectorVariable<TVariable<TMember<BaseInterface> >, true, BaseType> { IUNKNOWN_IMP(S##Type##AnnotationMember, BaseInterface, ID3DX11EffectVariable);}; #define GenerateReflectionGlobalOnlyClasses(Type) \ struct S##Type##GlobalVariable : public T##Type##Variable<TGlobalVariable<ID3DX11Effect##Type##Variable> > { IUNKNOWN_IMP(S##Type##GlobalVariable, ID3DX11Effect##Type##Variable, ID3DX11EffectVariable); }; \ struct S##Type##GlobalVariableMember : public T##Type##Variable<TVariable<TMember<ID3DX11Effect##Type##Variable> > > { IUNKNOWN_IMP(S##Type##GlobalVariableMember, ID3DX11Effect##Type##Variable, ID3DX11EffectVariable); }; \ GenerateReflectionClasses(Numeric, ID3DX11EffectVariable); GenerateReflectionClasses(FloatScalar, ID3DX11EffectScalarVariable); GenerateReflectionClasses(IntScalar, ID3DX11EffectScalarVariable); GenerateReflectionClasses(BoolScalar, ID3DX11EffectScalarVariable); GenerateVectorReflectionClasses(FloatVector, ETVT_Float, ID3DX11EffectVectorVariable); GenerateVectorReflectionClasses(BoolVector, ETVT_Bool, ID3DX11EffectVectorVariable); GenerateVectorReflectionClasses(IntVector, ETVT_Int, ID3DX11EffectVectorVariable); GenerateReflectionClasses(Matrix, ID3DX11EffectMatrixVariable); GenerateReflectionClasses(String, ID3DX11EffectStringVariable); GenerateReflectionGlobalOnlyClasses(ClassInstance); GenerateReflectionGlobalOnlyClasses(Interface); GenerateReflectionGlobalOnlyClasses(ShaderResource); GenerateReflectionGlobalOnlyClasses(UnorderedAccessView); GenerateReflectionGlobalOnlyClasses(RenderTargetView); GenerateReflectionGlobalOnlyClasses(DepthStencilView); GenerateReflectionGlobalOnlyClasses(Shader); GenerateReflectionGlobalOnlyClasses(Blend); GenerateReflectionGlobalOnlyClasses(DepthStencil); GenerateReflectionGlobalOnlyClasses(Rasterizer); GenerateReflectionGlobalOnlyClasses(Sampler); // Optimized matrix classes struct SMatrix4x4ColumnMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, true> { IUNKNOWN_IMP(SMatrix4x4ColumnMajorGlobalVariable, ID3DX11EffectMatrixVariable, ID3DX11EffectVariable); }; struct SMatrix4x4RowMajorGlobalVariable : public TMatrix4x4Variable<TGlobalVariable<ID3DX11EffectMatrixVariable>, false> { IUNKNOWN_IMP(SMatrix4x4RowMajorGlobalVariable, ID3DX11EffectMatrixVariable, ID3DX11EffectVariable); }; struct SMatrix4x4ColumnMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, true> { IUNKNOWN_IMP(SMatrix4x4ColumnMajorGlobalVariableMember, ID3DX11EffectMatrixVariable, ID3DX11EffectVariable); }; struct SMatrix4x4RowMajorGlobalVariableMember : public TMatrix4x4Variable<TVariable<TMember<ID3DX11EffectMatrixVariable> >, false> { IUNKNOWN_IMP(SMatrix4x4RowMajorGlobalVariableMember, ID3DX11EffectMatrixVariable, ID3DX11EffectVariable); }; // Optimized vector classes struct SFloatVector4GlobalVariable : public TVector4Variable<TGlobalVariable<ID3DX11EffectVectorVariable> > { IUNKNOWN_IMP(SFloatVector4GlobalVariable, ID3DX11EffectVectorVariable, ID3DX11EffectVariable); }; struct SFloatVector4GlobalVariableMember : public TVector4Variable<TVariable<TMember<ID3DX11EffectVectorVariable> > > { IUNKNOWN_IMP(SFloatVector4GlobalVariableMember, ID3DX11EffectVectorVariable, ID3DX11EffectVariable); }; // These 3 classes should never be used directly // The "base" global variable struct (all global variables should be the same size in bytes, // but we pick this as the default). struct SGlobalVariable : public TGlobalVariable<ID3DX11EffectVariable> { }; // The "base" annotation struct (all annotations should be the same size in bytes, // but we pick this as the default). struct SAnnotation : public TAnnotation<ID3DX11EffectVariable> { }; // The "base" variable member struct (all annotation/global variable members should be the // same size in bytes, but we pick this as the default). struct SMember : public TVariable<TMember<ID3DX11EffectVariable> > { }; // creates a new variable of the appropriate polymorphic type where pVar was HRESULT PlacementNewVariable(_In_ void *pVar, _In_ SType *pType, _In_ bool IsAnnotation); SMember * CreateNewMember(_In_ SType *pType, _In_ bool IsAnnotation); #pragma warning(pop)
40.113527
247
0.684832
sysu-Beadle
60f42502d05b4be11116bf6ab42670c19c5e696c
5,063
cc
C++
base/synchronization/lock_unittest.cc
mockingbirdnest/chromium
da685abcc5b235ed6fac5d52e20dc276530ed9be
[ "BSD-3-Clause" ]
null
null
null
base/synchronization/lock_unittest.cc
mockingbirdnest/chromium
da685abcc5b235ed6fac5d52e20dc276530ed9be
[ "BSD-3-Clause" ]
null
null
null
base/synchronization/lock_unittest.cc
mockingbirdnest/chromium
da685abcc5b235ed6fac5d52e20dc276530ed9be
[ "BSD-3-Clause" ]
null
null
null
// 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 "base/synchronization/lock.h" #include <stdlib.h> #include "base/compiler_specific.h" #include "base/threading/platform_thread.h" #include "testing/gtest/include/gtest/gtest.h" namespace base { // Basic test to make sure that Acquire()/Release()/Try() don't crash ---------- class BasicLockTestThread : public PlatformThread::Delegate { public: explicit BasicLockTestThread(Lock* lock) : lock_(lock), acquired_(0) {} virtual void ThreadMain() override { for (int i = 0; i < 10; i++) { lock_->Acquire(); acquired_++; lock_->Release(); } for (int i = 0; i < 10; i++) { lock_->Acquire(); acquired_++; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 20)); lock_->Release(); } for (int i = 0; i < 10; i++) { if (lock_->Try()) { acquired_++; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 20)); lock_->Release(); } } } int acquired() const { return acquired_; } private: Lock* lock_; int acquired_; DISALLOW_COPY_AND_ASSIGN(BasicLockTestThread); }; TEST(LockTest, Basic) { Lock lock; BasicLockTestThread thread(&lock); PlatformThreadHandle handle; ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); int acquired = 0; for (int i = 0; i < 5; i++) { lock.Acquire(); acquired++; lock.Release(); } for (int i = 0; i < 10; i++) { lock.Acquire(); acquired++; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 20)); lock.Release(); } for (int i = 0; i < 10; i++) { if (lock.Try()) { acquired++; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 20)); lock.Release(); } } for (int i = 0; i < 5; i++) { lock.Acquire(); acquired++; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 20)); lock.Release(); } PlatformThread::Join(handle); EXPECT_GE(acquired, 20); EXPECT_GE(thread.acquired(), 20); } // Test that Try() works as expected ------------------------------------------- class TryLockTestThread : public PlatformThread::Delegate { public: explicit TryLockTestThread(Lock* lock) : lock_(lock), got_lock_(false) {} virtual void ThreadMain() override { got_lock_ = lock_->Try(); if (got_lock_) lock_->Release(); } bool got_lock() const { return got_lock_; } private: Lock* lock_; bool got_lock_; DISALLOW_COPY_AND_ASSIGN(TryLockTestThread); }; TEST(LockTest, TryLock) { Lock lock; ASSERT_TRUE(lock.Try()); // We now have the lock.... // This thread will not be able to get the lock. { TryLockTestThread thread(&lock); PlatformThreadHandle handle; ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_FALSE(thread.got_lock()); } lock.Release(); // This thread will.... { TryLockTestThread thread(&lock); PlatformThreadHandle handle; ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); PlatformThread::Join(handle); ASSERT_TRUE(thread.got_lock()); // But it released it.... ASSERT_TRUE(lock.Try()); } lock.Release(); } // Tests that locks actually exclude ------------------------------------------- class MutexLockTestThread : public PlatformThread::Delegate { public: MutexLockTestThread(Lock* lock, int* value) : lock_(lock), value_(value) {} // Static helper which can also be called from the main thread. static void DoStuff(Lock* lock, int* value) { for (int i = 0; i < 40; i++) { lock->Acquire(); int v = *value; PlatformThread::Sleep(TimeDelta::FromMilliseconds(rand() % 10)); *value = v + 1; lock->Release(); } } virtual void ThreadMain() override { DoStuff(lock_, value_); } private: Lock* lock_; int* value_; DISALLOW_COPY_AND_ASSIGN(MutexLockTestThread); }; TEST(LockTest, MutexTwoThreads) { Lock lock; int value = 0; MutexLockTestThread thread(&lock, &value); PlatformThreadHandle handle; ASSERT_TRUE(PlatformThread::Create(0, &thread, &handle)); MutexLockTestThread::DoStuff(&lock, &value); PlatformThread::Join(handle); EXPECT_EQ(2 * 40, value); } TEST(LockTest, MutexFourThreads) { Lock lock; int value = 0; MutexLockTestThread thread1(&lock, &value); MutexLockTestThread thread2(&lock, &value); MutexLockTestThread thread3(&lock, &value); PlatformThreadHandle handle1; PlatformThreadHandle handle2; PlatformThreadHandle handle3; ASSERT_TRUE(PlatformThread::Create(0, &thread1, &handle1)); ASSERT_TRUE(PlatformThread::Create(0, &thread2, &handle2)); ASSERT_TRUE(PlatformThread::Create(0, &thread3, &handle3)); MutexLockTestThread::DoStuff(&lock, &value); PlatformThread::Join(handle1); PlatformThread::Join(handle2); PlatformThread::Join(handle3); EXPECT_EQ(4 * 40, value); } } // namespace base
23.331797
80
0.645467
mockingbirdnest
60f667bc03e0cadc602f6af64b7d960c50339d91
3,110
hpp
C++
source/include/coffee/basis/Exception.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
2
2018-02-03T06:56:29.000Z
2021-04-20T10:28:32.000Z
source/include/coffee/basis/Exception.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
8
2018-02-18T21:00:07.000Z
2018-02-20T15:31:24.000Z
source/include/coffee/basis/Exception.hpp
ciscoruiz/wepa
e6d922157543c91b6804f11073424a0a9c6e8f51
[ "MIT" ]
1
2018-02-09T07:09:26.000Z
2018-02-09T07:09:26.000Z
// MIT License // // Copyright (c) 2018 Francisco Ruiz (francisco.ruiz.rayo@gmail.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // #ifndef __coffee_basis_Exception_hpp #define __coffee_basis_Exception_hpp #include <stdexcept> #include <coffee/config/defines.hpp> namespace coffee { namespace basis { /** * Base exception for all exception defined in this framework. */ class Exception : std::logic_error { public: using std::logic_error::what; /** * Destructor. */ virtual ~Exception () noexcept {;} /** * \return the method name from this exception was thrown. */ const char* getMethod () const noexcept { return m_fromMethod; } /** * \return the line number in file from this exception was thrown. */ const char* getFile () const noexcept { return m_fromFile; } /** * \return the line number in file from this exception was thrown. */ const unsigned getLine () const noexcept { return m_fromLine; } protected: /** * Constructor * \param str text associated to this exception. * \param fromMethod the method name from this exception was thrown. * \param fromFile the line number in file from this exception was thrown. * \param fromLine the line number in file from this exception was thrown. */ Exception (const std::string& str, const char* fromMethod, const char* fromFile, const unsigned fromLine) : std::logic_error (str), m_fromMethod (fromMethod), m_fromFile (removePathBeforeCoffee(fromFile)), m_fromLine (fromLine) {;} /** * Copy Constructor */ Exception (const Exception& other) : std::logic_error (other), m_fromMethod (other.m_fromMethod), m_fromFile (other.m_fromFile), m_fromLine (other.m_fromLine) {;} /** * \return Combines method, file and number of line on that file to locate were the exception was thrown. */ std::string filePosition () const noexcept; private: const char* m_fromMethod; const char* m_fromFile; const unsigned m_fromLine; }; } } #endif
30.490196
110
0.707395
ciscoruiz
60f895d37755ff98d5c14fcfa0a367677fcd88e5
43,388
cpp
C++
Source/AliveLibCommon/Masher.cpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
208
2018-06-06T13:14:03.000Z
2022-03-30T02:21:27.000Z
Source/AliveLibCommon/Masher.cpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
537
2018-06-06T16:50:45.000Z
2022-03-31T16:41:15.000Z
Source/AliveLibCommon/Masher.cpp
mouzedrift/alive_reversing
be7dfbaed3be99b452459e974bc4e79f9503c178
[ "MIT" ]
42
2018-06-06T00:40:08.000Z
2022-03-23T08:38:55.000Z
#include "stdafx_common.h" #include "Masher.hpp" #include "Function.hpp" #include "masher_tables.hpp" #include "Sys_common.hpp" #include <array> #include <assert.h> ALIVE_VAR(1, 0xbbb314, Movie_IO, sMovie_IO_BBB314, {}); Movie_IO& GetMovieIO() { return sMovie_IO_BBB314; } AudioDecompressor::AudioDecompressor() { init_Snd_tbl(); } /*static*/ s32 AudioDecompressor::GetSoundTableValue(s16 tblIndex) { const s32 positiveTblIdx = abs(tblIndex); const u32 shiftedIdx = (positiveTblIdx >> 7) & 0xFF; s32 result = static_cast<u16>(static_cast<s16>(gSndTbl_byte_62EEB0[shiftedIdx] << 7)) | static_cast<u16>(positiveTblIdx >> gSndTbl_byte_62EEB0[shiftedIdx]); if (tblIndex < 0) { result = -result; } return result; } s16 AudioDecompressor::sub_408F50(s16 sample) { s32 absSample = abs(sample); s32 sampleBits = absSample >> 7; s32 sampleMasked = absSample & 0x7F; s16 result = static_cast<u16>(sampleMasked << sampleBits); if (sampleBits >= 2) { result |= static_cast<u16>(1 << (sampleBits - 2)); } if (sample < 0) { result = -result; } return result; } s32 AudioDecompressor::ReadNextAudioWord(s32 value) { if (mUsedBits <= 16) { const s32 srcVal = *mAudioFrameDataPtr; ++mAudioFrameDataPtr; value |= srcVal << mUsedBits; mUsedBits += 16; } return value; } s32 AudioDecompressor::SndRelated_sub_409650() { const s32 numBits = mUsedBits & 7; mUsedBits -= numBits; mWorkBits >>= numBits; mWorkBits = ReadNextAudioWord(static_cast<s32>(mWorkBits)); return mUsedBits; } s16 AudioDecompressor::NextSoundBits(u16 numBits) { mUsedBits -= numBits; const s16 ret = static_cast<s16>(mWorkBits & ((1u << numBits) - 1u)); mWorkBits >>= numBits; mWorkBits = ReadNextAudioWord(static_cast<s32>(mWorkBits)); return ret; } bool AudioDecompressor::SampleMatches(s16& sample, s16 bitNum) { const s32 bitMask = 1 << (bitNum - 1); if (sample != bitMask) { if (sample & bitMask) { sample = -(sample & ~bitMask); } return true; } return false; } template <class T> void AudioDecompressor::decode_generic(T* outPtr, s32 numSamplesPerFrame, bool isLast) { const s16 useTableFlag = NextSoundBits(16); const s16 firstWord = NextSoundBits(16); const s16 secondWord = NextSoundBits(16); const s16 thirdWord = NextSoundBits(16); const s16 previous1 = NextSoundBits(16); s32 previousValue1 = static_cast<s16>(previous1); *outPtr = static_cast<T>(previous1); outPtr += mAudioNumChannels; const s16 previous2 = NextSoundBits(16); s32 previousValue2 = static_cast<s16>(previous2); *outPtr = static_cast<T>(previous2); outPtr += mAudioNumChannels; const s16 previous3 = NextSoundBits(16); s32 previousValue3 = static_cast<s16>(previous3); *outPtr = static_cast<T>(previous3); outPtr += mAudioNumChannels; if (numSamplesPerFrame > 3) { for (s32 counter = 0; counter < numSamplesPerFrame - 3; counter++) { s16 samplePart = 0; do { samplePart = NextSoundBits(firstWord); if (SampleMatches(samplePart, firstWord)) { break; } samplePart = NextSoundBits(secondWord); if (SampleMatches(samplePart, secondWord)) { break; } samplePart = NextSoundBits(thirdWord); if (SampleMatches(samplePart, thirdWord)) { break; } } while (false); const s32 previous = (5 * previousValue3) - (4 * previousValue2); const s32 samplePartOrTableIndex = (previousValue1 + previous) >> 1; previousValue1 = previousValue2; previousValue2 = previousValue3; const bool bUseTbl = useTableFlag != 0; if (bUseTbl) { const s32 soundTableValue = GetSoundTableValue(static_cast<s16>(samplePartOrTableIndex)); previousValue3 = sub_408F50(static_cast<s16>(samplePart + soundTableValue)); } else { // TODO: Case never hit for any known data? previousValue3 = static_cast<s16>(samplePartOrTableIndex + samplePart); } *outPtr = static_cast<T>(previousValue3); // s32 to word outPtr += mAudioNumChannels; } } if (!isLast) { SndRelated_sub_409650(); } } void AudioDecompressor::decode_8bit_audio_frame(u8* outPtr, s32 numSamplesPerFrame, bool isLast) { decode_generic(outPtr, numSamplesPerFrame, isLast); } void AudioDecompressor::decode_16bit_audio_frame(u16* outPtr, s32 numSamplesPerFrame, bool isLast) { decode_generic(outPtr, numSamplesPerFrame, isLast); } u16* AudioDecompressor::SetupAudioDecodePtrs(u16* rawFrameBuffer) { mAudioFrameDataPtr = rawFrameBuffer; mWorkBits = *reinterpret_cast<u32*>(mAudioFrameDataPtr); mAudioFrameDataPtr = mAudioFrameDataPtr + 2; mUsedBits = 32; return mAudioFrameDataPtr; } void AudioDecompressor::SetChannelCount(s32 numChannels) { mAudioNumChannels = numChannels; } /*static*/ void AudioDecompressor::init_Snd_tbl() { static bool done = false; if (!done) { done = true; s32 index = 0; do { s32 tableValue = 0; for (s32 i = index; i > 0; ++tableValue) { i >>= 1; } gSndTbl_byte_62EEB0[index++] = static_cast<u8>(tableValue); } while (index < 256); } } /*static*/ u8 AudioDecompressor::gSndTbl_byte_62EEB0[256]; bool IsPowerOf2(s32 i) { return !(i & (i - 1)); } u32 RoundUpPowerOf2(u32 numToRound, s32 multiple) { assert(multiple && IsPowerOf2(multiple)); return (numToRound + multiple - 1) & -multiple; } const s32 kMacroBlockWidth = 16; const s32 kMacroBlockHeight = 16; static u16 GetHiWord(u32 v) { return static_cast<u16>((v >> 16) & 0xFFFF); } #ifndef MAKELONG #define MAKELONG(a, b) ((((u16)(((a)) & 0xffff)) | ((u32)((u16)(((b)) & 0xffff))) << 16)) #endif static void SetLoWord(u32& v, u16 lo) { u16 hiWord = GetHiWord(v); v = MAKELONG(lo, hiWord); } static void SetHiWord(u32& v, u16 hi) { u16 loWord = v & 0xFFFF; v = MAKELONG(loWord, hi); } static u32 ExtractBits(u32 value, u32 numBits) { return value >> (32 - numBits); } static void SkipBits(u32& value, s8 numBits, s8& usedBitCount) { value = value << numBits; usedBitCount += numBits; } static inline void GetBits(s8& usedBitCount, u16*& rawBitStreamPtr, u32& rawWord4, u32& workBits) { // I think this is used as an escape code? if (usedBitCount & 16) // 0b10000 if bit 5 set { usedBitCount &= 15; rawWord4 = *rawBitStreamPtr++ << usedBitCount; workBits |= rawWord4; } } static inline void OutputWordAndAdvance(u16*& rawBitStreamPtr, u32& rawWord4, u16*& pOut, s8& usedBitCount, u32& workBits) { *pOut++ = workBits >> (32 - 16); rawWord4 = *rawBitStreamPtr++ << usedBitCount; workBits = rawWord4 | (workBits << 16); } #define MASK_11_BITS 0x7FF #define MASK_10_BITS 0x3FF #define MASK_13_BITS 0x1FFF #define MDEC_END 0xFE00u static s32 decode_bitstream(u16* pFrameData, u16* pOutput) { u32 table_index_2 = 0; s32 ret = *pFrameData; u32 workBits = ((pFrameData[2] << 16) | (pFrameData[1])); workBits = (workBits << 16) | (workBits >> 16); // Swap words 0xff9a005f u32 rawWord4 = ExtractBits(workBits, 11); s8 usedBitCount = 0; SkipBits(workBits, 11, usedBitCount); *pOutput++ = static_cast<u16>(rawWord4); // store in output 0x000007fc u16* rawBitStreamPtr = (pFrameData + 3); // 0x7f40 while (1) { do { while (1) { do { while (1) { do { while (1) { while (1) { table_index_2 = ExtractBits(workBits, 13); // 0x1FFF / 8191 table size? 8192/8=1024 entries? if (table_index_2 >= 32) { break; } const s32 table_index_1 = ExtractBits(workBits, 17); // 0x1FFFF / 131072, 131072/4=32768 entries? if (table_index_1 > ALIVE_COUNTOF(gTbl1)) { LOG_ERROR("Table index " << table_index_1); ALIVE_FATAL("Table 1 index out of bounds"); } SkipBits(workBits, 8, usedBitCount); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); const s8 bitsToShiftFromTbl = gTbl1[table_index_1].mBitsToShift; SkipBits(workBits, bitsToShiftFromTbl, usedBitCount); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); // Everything in the table is 0's after 4266 bytes 4266/2=2133 to perhaps 2048/4096 is max? *pOutput++ = gTbl1[table_index_1].mOutputWord; } // End while const s8 tblValueBits = gTbl2[table_index_2].mBitsToShift; SkipBits(workBits, tblValueBits, usedBitCount); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); SetLoWord(rawWord4, gTbl2[table_index_2].mOutputWord1); if (static_cast<u16>(rawWord4) != 0x7C1F) // 0b 11111 00000 11111 { break; } OutputWordAndAdvance(rawBitStreamPtr, rawWord4, pOutput, usedBitCount, workBits); } // End while *pOutput++ = static_cast<u16>(rawWord4); if (static_cast<u16>(rawWord4) == MDEC_END) { const s32 v15 = ExtractBits(workBits, 11); SkipBits(workBits, 11, usedBitCount); if (v15 == MASK_10_BITS) { return ret; } rawWord4 = v15 & MASK_11_BITS; *pOutput++ = static_cast<u16>(rawWord4); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); } SetLoWord(rawWord4, gTbl2[table_index_2].mOutputWord2); } while (!static_cast<u16>(rawWord4)); if (static_cast<u16>(rawWord4) != 0x7C1F) { break; } OutputWordAndAdvance(rawBitStreamPtr, rawWord4, pOutput, usedBitCount, workBits); } // End while *pOutput++ = static_cast<u16>(rawWord4); if (static_cast<u16>(rawWord4) == MDEC_END) { const s32 t11Bits = ExtractBits(workBits, 11); SkipBits(workBits, 11, usedBitCount); if (t11Bits == MASK_10_BITS) { return ret; } rawWord4 = t11Bits & MASK_11_BITS; *pOutput++ = static_cast<u16>(rawWord4); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); } SetLoWord(rawWord4, gTbl2[table_index_2].mOutputWord3); } while (!static_cast<u16>(rawWord4)); if (static_cast<u16>(rawWord4) != 0x7C1F) { break; } OutputWordAndAdvance(rawBitStreamPtr, rawWord4, pOutput, usedBitCount, workBits); } // End while *pOutput++ = static_cast<u16>(rawWord4); } while (static_cast<u16>(rawWord4) != MDEC_END); rawWord4 = ExtractBits(workBits, 11); SkipBits(workBits, 11, usedBitCount); if (rawWord4 == MASK_10_BITS) { return ret; } *pOutput++ = static_cast<u16>(rawWord4); GetBits(usedBitCount, rawBitStreamPtr, rawWord4, workBits); } return ret; } const u32 k_YTable_Matrix_42AEC8[64] = { 0x0000000C, 0x0000000B, 0x0000000A, 0x0000000C, 0x0000000E, 0x0000000E, 0x0000000D, 0x0000000E, 0x00000010, 0x00000018, 0x00000013, 0x00000010, 0x00000011, 0x00000012, 0x00000018, 0x00000016, 0x00000016, 0x00000018, 0x0000001A, 0x00000028, 0x00000033, 0x0000003A, 0x00000028, 0x0000001D, 0x00000025, 0x00000023, 0x00000031, 0x00000048, 0x00000040, 0x00000037, 0x00000038, 0x00000033, 0x00000039, 0x0000003C, 0x0000003D, 0x00000037, 0x00000045, 0x00000057, 0x00000044, 0x00000040, 0x0000004E, 0x0000005C, 0x0000005F, 0x00000057, 0x00000051, 0x0000006D, 0x00000050, 0x00000038, 0x0000003E, 0x00000067, 0x00000068, 0x00000067, 0x00000062, 0x00000070, 0x00000079, 0x00000071, 0x0000004D, 0x0000005C, 0x00000078, 0x00000064, 0x00000067, 0x00000065, 0x00000063, 0x00000010}; const u32 k_CTable_Matrix_42AFC4[64] = { 0x00000010, 0x00000012, 0x00000012, 0x00000018, 0x00000015, 0x00000018, 0x0000002F, 0x0000001A, 0x0000001A, 0x0000002F, 0x00000063, 0x00000042, 0x00000038, 0x00000042, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063, 0x00000063}; const u32 g_index_look_up_table[64] = { 0x00000001, 0x00000008, 0x00000010, 0x00000009, 0x00000002, 0x00000003, 0x0000000A, 0x00000011, 0x00000018, 0x00000020, 0x00000019, 0x00000012, 0x0000000B, 0x00000004, 0x00000005, 0x0000000C, 0x00000013, 0x0000001A, 0x00000021, 0x00000028, 0x00000030, 0x00000029, 0x00000022, 0x0000001B, 0x00000014, 0x0000000D, 0x00000006, 0x00000007, 0x0000000E, 0x00000015, 0x0000001C, 0x00000023, 0x0000002A, 0x00000031, 0x00000038, 0x00000039, 0x00000032, 0x0000002B, 0x00000024, 0x0000001D, 0x00000016, 0x0000000F, 0x00000017, 0x0000001E, 0x00000025, 0x0000002C, 0x00000033, 0x0000003A, 0x0000003B, 0x00000034, 0x0000002D, 0x00000026, 0x0000001F, 0x00000027, 0x0000002E, 0x00000035, 0x0000003C, 0x0000003D, 0x00000036, 0x0000002F, 0x00000037, 0x0000003E, 0x0000003F, 0x0000098E // TODO: Last value too large? }; // Same as PSXMDECDecoder::RL_ZSCAN_MATRIX const u32 RL_ZSCAN_MATRIX_2[64] = { 0x00000000, 0x00000001, 0x00000008, 0x00000010, 0x00000009, 0x00000002, 0x00000003, 0x0000000A, 0x00000011, 0x00000018, 0x00000020, 0x00000019, 0x00000012, 0x0000000B, 0x00000004, 0x00000005, 0x0000000C, 0x00000013, 0x0000001A, 0x00000021, 0x00000028, 0x00000030, 0x00000029, 0x00000022, 0x0000001B, 0x00000014, 0x0000000D, 0x00000006, 0x00000007, 0x0000000E, 0x00000015, 0x0000001C, 0x00000023, 0x0000002A, 0x00000031, 0x00000038, 0x00000039, 0x00000032, 0x0000002B, 0x00000024, 0x0000001D, 0x00000016, 0x0000000F, 0x00000017, 0x0000001E, 0x00000025, 0x0000002C, 0x00000033, 0x0000003A, 0x0000003B, 0x00000034, 0x0000002D, 0x00000026, 0x0000001F, 0x00000027, 0x0000002E, 0x00000035, 0x0000003C, 0x0000003D, 0x00000036, 0x0000002F, 0x00000037, 0x0000003E, 0x0000003F}; const u32 g_block_related_2_dword_42B0CC[64] = { 0x00000008, 0x00000010, 0x00000009, 0x00000002, 0x00000003, 0x0000000A, 0x00000011, 0x00000018, 0x00000020, 0x00000019, 0x00000012, 0x0000000B, 0x00000004, 0x00000005, 0x0000000C, 0x00000013, 0x0000001A, 0x00000021, 0x00000028, 0x00000030, 0x00000029, 0x00000022, 0x0000001B, 0x00000014, 0x0000000D, 0x00000006, 0x00000007, 0x0000000E, 0x00000015, 0x0000001C, 0x00000023, 0x0000002A, 0x00000031, 0x00000038, 0x00000039, 0x00000032, 0x0000002B, 0x00000024, 0x0000001D, 0x00000016, 0x0000000F, 0x00000017, 0x0000001E, 0x00000025, 0x0000002C, 0x00000033, 0x0000003A, 0x0000003B, 0x00000034, 0x0000002D, 0x00000026, 0x0000001F, 0x00000027, 0x0000002E, 0x00000035, 0x0000003C, 0x0000003D, 0x00000036, 0x0000002F, 0x00000037, 0x0000003E, 0x0000003F, 0x0000098E, 0x0000098E}; const u32 g_block_related_3_dword_42B0D0[64] = { 0x00000010, 0x00000009, 0x00000002, 0x00000003, 0x0000000A, 0x00000011, 0x00000018, 0x00000020, 0x00000019, 0x00000012, 0x0000000B, 0x00000004, 0x00000005, 0x0000000C, 0x00000013, 0x0000001A, 0x00000021, 0x00000028, 0x00000030, 0x00000029, 0x00000022, 0x0000001B, 0x00000014, 0x0000000D, 0x00000006, 0x00000007, 0x0000000E, 0x00000015, 0x0000001C, 0x00000023, 0x0000002A, 0x00000031, 0x00000038, 0x00000039, 0x00000032, 0x0000002B, 0x00000024, 0x0000001D, 0x00000016, 0x0000000F, 0x00000017, 0x0000001E, 0x00000025, 0x0000002C, 0x00000033, 0x0000003A, 0x0000003B, 0x00000034, 0x0000002D, 0x00000026, 0x0000001F, 0x00000027, 0x0000002E, 0x00000035, 0x0000003C, 0x0000003D, 0x00000036, 0x0000002F, 0x00000037, 0x0000003E, 0x0000003F, 0x0000098E, 0x0000098E, 0x0000F384}; u32 g_CTable[64] = {}; u32 g_YTable[64] = {}; // Return val becomes param 1 // for Cr, Cb, Y1, Y2, Y3, Y4 int16_t* RunLengthToBlock(int16_t* inPtr, int16_t* outputBlockPtr, bool isYBlock) { const s32 v1 = isYBlock; const u32* pTable = isYBlock ? &g_YTable[1] : &g_CTable[1]; u32 counter = 0; u16* pInput = reinterpret_cast<u16*>(inPtr); u32* pOutput = reinterpret_cast<u32*>(outputBlockPtr); // off 10 quantised coefficients // 0xFE00 == END_OF_BLOCK, hence this loop moves past the EOB while (*pInput == 0xFE00u) { pInput++; } *pOutput = (v1 << 10) + 2 * (*pInput << 21 >> 22); pInput++; if ((*(pInput - 1)) & 1) { do { const u32 macroBlockWord = *pInput++; // bail if end if (macroBlockWord == 0xFE00) { break; } const u32 q_scale = (macroBlockWord >> 10); counter += q_scale; const s32 lookedUpIndex = g_index_look_up_table[counter]; s32 v24 = pOutput[lookedUpIndex] + (macroBlockWord << 22); u32 v25 = 0; SetHiWord(v25, GetHiWord(v24)); SetLoWord(v25, static_cast<u16>((pTable[q_scale] * (v24 >> 22) + 4) >> 3)); pTable += q_scale + 1; pOutput[lookedUpIndex] = v25; counter++; } while (counter < 63); // 63 AC values? } else { while (1) { const u32 macroBlockWord = *pInput++; // bail if end if (macroBlockWord == 0xFE00) { break; } const u32 q_scale = (macroBlockWord >> 10); const s32 v24 = macroBlockWord << 22; s32 k = q_scale + 1; s32 idx = 0; while (1) { --k; idx = g_index_look_up_table[counter]; if (!k) { break; } pOutput[idx] = 0; ++counter; } u32 outVal = 0; SetHiWord(outVal, GetHiWord(v24)); SetLoWord(outVal, static_cast<u16>((pTable[q_scale] * (v24 >> 22) + 4) >> 3)); pTable += q_scale + 1; pOutput[idx] = outVal; ++counter; if (counter >= 63) // 63 AC values? { return reinterpret_cast<int16_t*>(pInput); } } if (counter) { s32 counter3 = counter + 1; if (counter3 & 3) { pOutput[RL_ZSCAN_MATRIX_2[counter3++]] = 0; if (counter3 & 3) { pOutput[RL_ZSCAN_MATRIX_2[counter3++]] = 0; if (counter3 & 3) { pOutput[RL_ZSCAN_MATRIX_2[counter3++]] = 0; } } } while (counter3 != 64) // 63 AC values? { pOutput[RL_ZSCAN_MATRIX_2[counter3]] = 0; pOutput[g_index_look_up_table[counter3]] = 0; pOutput[g_block_related_2_dword_42B0CC[counter3]] = 0; pOutput[g_block_related_3_dword_42B0D0[counter3]] = 0; counter3 += 4; } } else { memset(pOutput + 1, 0, 0xFCu); // 63 dwords buffer } } return reinterpret_cast<int16_t*>(pInput); } // TODO: Should probably just be 64? Making this bigger fixes a sound glitch which is probably caused // by an out of bounds write somewhere. typedef std::array<int32_t, 64 * 4> T64IntsArray; static T64IntsArray Cr_block = {}; static T64IntsArray Cb_block = {}; static T64IntsArray Y1_block = {}; static T64IntsArray Y2_block = {}; static T64IntsArray Y3_block = {}; static T64IntsArray Y4_block = {}; void half_idct(T64IntsArray& pSource, T64IntsArray& pDestination, s32 nPitch, s32 nIncrement, s32 nShift) { std::array<int32_t, 8> pTemp; size_t sourceIdx = 0; size_t destinationIdx = 0; for (s32 i = 0; i < 8; i++) { pTemp[4] = pSource[(0 * nPitch) + sourceIdx] * 8192 + pSource[(2 * nPitch) + sourceIdx] * 10703 + pSource[(4 * nPitch) + sourceIdx] * 8192 + pSource[(6 * nPitch) + sourceIdx] * 4433; pTemp[5] = pSource[(0 * nPitch) + sourceIdx] * 8192 + pSource[(2 * nPitch) + sourceIdx] * 4433 - pSource[(4 * nPitch) + sourceIdx] * 8192 - pSource[(6 * nPitch) + sourceIdx] * 10704; pTemp[6] = pSource[(0 * nPitch) + sourceIdx] * 8192 - pSource[(2 * nPitch) + sourceIdx] * 4433 - pSource[(4 * nPitch) + sourceIdx] * 8192 + pSource[(6 * nPitch) + sourceIdx] * 10704; pTemp[7] = pSource[(0 * nPitch) + sourceIdx] * 8192 - pSource[(2 * nPitch) + sourceIdx] * 10703 + pSource[(4 * nPitch) + sourceIdx] * 8192 - pSource[(6 * nPitch) + sourceIdx] * 4433; pTemp[0] = pSource[(1 * nPitch) + sourceIdx] * 11363 + pSource[(3 * nPitch) + sourceIdx] * 9633 + pSource[(5 * nPitch) + sourceIdx] * 6437 + pSource[(7 * nPitch) + sourceIdx] * 2260; pTemp[1] = pSource[(1 * nPitch) + sourceIdx] * 9633 - pSource[(3 * nPitch) + sourceIdx] * 2259 - pSource[(5 * nPitch) + sourceIdx] * 11362 - pSource[(7 * nPitch) + sourceIdx] * 6436; pTemp[2] = pSource[(1 * nPitch) + sourceIdx] * 6437 - pSource[(3 * nPitch) + sourceIdx] * 11362 + pSource[(5 * nPitch) + sourceIdx] * 2261 + pSource[(7 * nPitch) + sourceIdx] * 9633; pTemp[3] = pSource[(1 * nPitch) + sourceIdx] * 2260 - pSource[(3 * nPitch) + sourceIdx] * 6436 + pSource[(5 * nPitch) + sourceIdx] * 9633 - pSource[(7 * nPitch) + sourceIdx] * 11363; pDestination[(0 * nPitch) + destinationIdx] = (pTemp[4] + pTemp[0]) >> nShift; pDestination[(1 * nPitch) + destinationIdx] = (pTemp[5] + pTemp[1]) >> nShift; pDestination[(2 * nPitch) + destinationIdx] = (pTemp[6] + pTemp[2]) >> nShift; pDestination[(3 * nPitch) + destinationIdx] = (pTemp[7] + pTemp[3]) >> nShift; pDestination[(4 * nPitch) + destinationIdx] = (pTemp[7] - pTemp[3]) >> nShift; pDestination[(5 * nPitch) + destinationIdx] = (pTemp[6] - pTemp[2]) >> nShift; pDestination[(6 * nPitch) + destinationIdx] = (pTemp[5] - pTemp[1]) >> nShift; pDestination[(7 * nPitch) + destinationIdx] = (pTemp[4] - pTemp[0]) >> nShift; sourceIdx += nIncrement; destinationIdx += nIncrement; } } // 0x40ED90 void idct(int16_t* input, T64IntsArray& pDestination) // dst is 64 dwords { T64IntsArray pTemp; T64IntsArray pExtendedSource; // Source is passed as signed 16 bits stored every 32 bits // We sign extend it at the beginning like Masher does for (s32 i = 0; i < 64; i++) { pExtendedSource[i] = input[i * 2]; } half_idct(pExtendedSource, pTemp, 8, 1, 11); half_idct(pTemp, pDestination, 1, 8, 18); } static void Populate_Y_C_Tables(int quantScale) { if (quantScale > 0) { g_YTable[0] = 16; g_CTable[0] = 16; signed int result = 0; do { // 0 auto val = k_YTable_Matrix_42AEC8[result]; result++; // TODO: Bug ? Surely Y and C should be done the same way // 1 g_YTable[result] = quantScale * val; g_CTable[result] = quantScale * k_CTable_Matrix_42AFC4[result]; } while (result < 63); // 252/4=63 } else { // These are simply null buffers to start with for (s32 i = 0; i < 64; i++) { g_CTable[i] = 16; g_YTable[i] = 16; } } } s32 Masher::Init_4E6770(const char_type* movieFileName) { field_40_video_frame_to_decode = nullptr; field_44_decoded_frame_data_buffer = nullptr; field_48_sound_frame_to_decode = nullptr; field_4C_decoded_audio_buffer = nullptr; field_8C_macro_block_buffer = nullptr; field_80_raw_frame_data = nullptr; field_70_frame_sizes_array = nullptr; field_90_64_or_0 = 0; field_84_max_frame_size = 8; field_88_audio_data_offset = 0; // Open the file field_0_file_handle = sMovie_IO_BBB314.mIO_Open(movieFileName); // Read file magic u32 fileMagic = 0; if (!field_0_file_handle || !sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) &fileMagic, sizeof(u32)) || !sMovie_IO_BBB314.mIO_Wait(field_0_file_handle)) { return 1; } // Verify magic const u32 kDDV_dword_68EE70 = 0x564444; if (memcmp(&fileMagic, &kDDV_dword_68EE70, sizeof(u32))) { return 3; } // Read DDV header if (!sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) &field_4_ddv_header, sizeof(Masher_Header)) || !sMovie_IO_BBB314.mIO_Wait(field_0_file_handle)) { return 1; } // Verify version is correct if (field_4_ddv_header.field_0_ddv_version != 1) { return 4; } // Does the file contain a video stream? field_61_bHasVideo = field_4_ddv_header.field_4_contains & 1; if (field_61_bHasVideo) { // Read the video header if (!sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) &field_14_video_header, sizeof(Masher_VideoHeader)) || !sMovie_IO_BBB314.mIO_Wait(field_0_file_handle)) { return 1; } // Add on to the max frame size field_84_max_frame_size += field_14_video_header.field_C_max_audio_frame_size; // Allocate buffer for decoding frame data field_44_decoded_frame_data_buffer = (u16*) malloc(sizeof(u16) * field_14_video_header.field_10_max_video_frame_size); if (!field_44_decoded_frame_data_buffer) { return 2; } // Calculate blocks X/Y field_58_macro_blocks_x = (field_14_video_header.field_4_width + 15) / kMacroBlockWidth; field_5C_macro_blocks_y = (field_14_video_header.field_8_height + 15) / kMacroBlockHeight; // Alloc macro block temp buffer (6 blocks for Cr, Cb, Y1, Y2, Y3, Y4) field_8C_macro_block_buffer = malloc(kMacroBlockWidth * kMacroBlockHeight * 6 * field_58_macro_blocks_x * field_5C_macro_blocks_y); if (!field_8C_macro_block_buffer) { return 2; } field_90_64_or_0 = 64; // NOTE: Pruned dead branches here } field_2C_audio_header.field_10_num_frames_interleave = 0; // Does the file contain an audio stream? field_60_bHasAudio = (field_4_ddv_header.field_4_contains >> 1) & 1; if (field_60_bHasAudio) { // Read audio header if (!sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) &field_2C_audio_header, sizeof(Masher_AudioHeader)) || !sMovie_IO_BBB314.mIO_Wait(field_0_file_handle)) { return 1; } field_50_num_channels = 1; field_54_bits_per_sample = 8; if (field_2C_audio_header.field_0_audio_format & 1) { field_50_num_channels = 2; } if (field_2C_audio_header.field_0_audio_format & 2) { field_54_bits_per_sample = 16; } field_84_max_frame_size += field_2C_audio_header.field_8_max_audio_frame_size; field_4C_decoded_audio_buffer = static_cast<u8*>(malloc(field_2C_audio_header.field_C_single_audio_frame_size * (field_50_num_channels * field_54_bits_per_sample / 8))); if (!field_4C_decoded_audio_buffer) { return 2; } } // Align the size field_84_max_frame_size = RoundUpPowerOf2(field_84_max_frame_size, 2); field_80_raw_frame_data = static_cast<s32*>(malloc(2 * field_84_max_frame_size)); if (!field_80_raw_frame_data) { return 2; } // Allocate buffer for frame sizes const u32 frameSizeArrayInBytes = sizeof(u32) * (field_2C_audio_header.field_10_num_frames_interleave + field_4_ddv_header.field_C_number_of_frames); field_70_frame_sizes_array = static_cast<s32*>(malloc(frameSizeArrayInBytes)); if (!field_70_frame_sizes_array) { return 2; } // Populate frame sizes array from disk if (!sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) field_70_frame_sizes_array, frameSizeArrayInBytes) || !sMovie_IO_BBB314.mIO_Wait(field_0_file_handle)) { return 1; } field_64_audio_frame_idx = 0; field_74_pCurrentFrameSize = field_70_frame_sizes_array; field_68_frame_number = 0; field_6C_frame_num = 0; return 0; } void Masher::dtor_4E6AB0() { if (field_0_file_handle) { sMovie_IO_BBB314.mIO_Close(field_0_file_handle); } if (field_70_frame_sizes_array) { free(field_70_frame_sizes_array); } if (field_80_raw_frame_data) { free(field_80_raw_frame_data); } if (field_44_decoded_frame_data_buffer) { free(field_44_decoded_frame_data_buffer); } if (field_4C_decoded_audio_buffer) { free(field_4C_decoded_audio_buffer); } if (field_8C_macro_block_buffer) { if (field_90_64_or_0) { free(field_8C_macro_block_buffer); } } } s32 Masher::ReadNextFrame_4E6B30() { // Read next frame data if we are not at the end if (field_68_frame_number < field_4_ddv_header.field_C_number_of_frames) { s32 frameSizeToRead = *field_74_pCurrentFrameSize; field_74_pCurrentFrameSize++; if (field_60_bHasAudio && field_61_bHasVideo) { // Contains offset to audio in the buffer frameSizeToRead += sizeof(u32); } if (frameSizeToRead > 0 && (!sMovie_IO_BBB314.mIO_Wait(field_0_file_handle) || !sMovie_IO_BBB314.mIO_Read(field_0_file_handle, (u8*) field_80_raw_frame_data + field_88_audio_data_offset, frameSizeToRead))) { return 0; } } const s32 frameOffset = field_84_max_frame_size - field_88_audio_data_offset; field_88_audio_data_offset = frameOffset; // Audio with no video if (field_60_bHasAudio && !field_61_bHasVideo) { field_48_sound_frame_to_decode = (s32*) ((s8*) field_80_raw_frame_data + frameOffset); } // Video with no audio else if (!field_60_bHasAudio && field_61_bHasVideo) { field_40_video_frame_to_decode = field_80_raw_frame_data + frameOffset; } // Audio and video else { u8* pFrameData = reinterpret_cast<u8*>(field_80_raw_frame_data); field_40_video_frame_to_decode = reinterpret_cast<void*>(&pFrameData[frameOffset + sizeof(u32)]); // Skip video data + video data len to get start of sound data u32 videoDataSize = *reinterpret_cast<u32*>(&pFrameData[frameOffset]); field_48_sound_frame_to_decode = reinterpret_cast<s32*>(&pFrameData[frameOffset + sizeof(u32) + videoDataSize]); } return ++field_68_frame_number < field_4_ddv_header.field_C_number_of_frames + 2; } s32 CC Masher::ReadNextFrameToMemory_4EAC30(Masher* pMasher) { s32* pFrameSize = pMasher->field_74_pCurrentFrameSize; s32 sizeToRead = *pFrameSize; pMasher->field_74_pCurrentFrameSize = pFrameSize + 1; if (!sMovie_IO_BBB314.mIO_Read(pMasher->field_0_file_handle, reinterpret_cast<u8*>(pMasher->field_80_raw_frame_data), sizeToRead) || !sMovie_IO_BBB314.mIO_Wait(pMasher->field_0_file_handle)) { return 0; } pMasher->field_48_sound_frame_to_decode = pMasher->field_80_raw_frame_data; return 1; } void Masher::Decode_4EA670() { // This seems to be used to just skip data without rendering ?? VideoFrameDecode_4E6C60(nullptr); } void Masher::VideoFrameDecode_4E6C60(u8* pPixelBuffer) { if (!field_61_bHasVideo) { return; } ++field_6C_frame_num; // if (!(field_6C_frame_num % field_14_video_header.field_14_key_frame_rate)) { // return; } //if (field_6C_frame_num < field_2C_audio_header.field_10_num_frames_interleave) { // return; } // if (field_68_frame_number < field_2C_audio_header.field_10_num_frames_interleave) { // return; } const s32 blocksX = field_58_macro_blocks_x; const s32 blocksY = field_5C_macro_blocks_y; if (blocksX <= 0 || field_5C_macro_blocks_y <= 0) { return; } const s32 quantScale = decode_bitstream((u16*) field_40_video_frame_to_decode, field_44_decoded_frame_data_buffer); Populate_Y_C_Tables(quantScale); int16_t* bitstreamCurPos = reinterpret_cast<int16_t*>(field_44_decoded_frame_data_buffer); int16_t* block1Output = static_cast<int16_t*>(field_8C_macro_block_buffer); s32 xoff = 0; for (s32 xBlock = 0; xBlock < blocksX; xBlock++) { s32 yoff = 0; for (s32 yBlock = 0; yBlock < blocksY; yBlock++) { const s32 dataSizeBytes = field_90_64_or_0 * 2; // Convert to byte count 64*4=256 int16_t* afterBlock1Ptr = RunLengthToBlock(bitstreamCurPos, block1Output, 0); idct(block1Output, Cr_block); int16_t* block2Output = dataSizeBytes + block1Output; int16_t* afterBlock2Ptr = RunLengthToBlock(afterBlock1Ptr, block2Output, 0); idct(block2Output, Cb_block); int16_t* block3Output = dataSizeBytes + block2Output; int16_t* afterBlock3Ptr = RunLengthToBlock(afterBlock2Ptr, block3Output, 1); idct(block3Output, Y1_block); int16_t* block4Output = dataSizeBytes + block3Output; int16_t* afterBlock4Ptr = RunLengthToBlock(afterBlock3Ptr, block4Output, 1); idct(block4Output, Y2_block); int16_t* block5Output = dataSizeBytes + block4Output; int16_t* afterBlock5Ptr = RunLengthToBlock(afterBlock4Ptr, block5Output, 1); idct(block5Output, Y3_block); int16_t* block6Output = dataSizeBytes + block5Output; bitstreamCurPos = RunLengthToBlock(afterBlock5Ptr, block6Output, 1); idct(block6Output, Y4_block); block1Output = dataSizeBytes + block6Output; if (pPixelBuffer) { // TODO: Should probably be using gMasher_pitch_bytes_BB4AF8 ?? ConvertYuvToRgbAndBlit((u16*) pPixelBuffer, xoff, yoff, 640, 480, true, true); // pPixelBuffer += gMasher_pitch_bytes_BB4AF8; } yoff += kMacroBlockHeight; } xoff += kMacroBlockWidth; } } ALIVE_VAR(1, 0xbbb9b4, s32, gMasher_num_channels_BBB9B4, 0); ALIVE_VAR(1, 0xbbb9a8, s32, gMasher_bits_per_sample_BBB9A8, 0); void CC Masher::DDV_Set_Channels_And_BitsPerSample_4ECFD0(s32 numChannels, s32 bitsPerSample) { gMasher_num_channels_BBB9B4 = numChannels; gMasher_bits_per_sample_BBB9A8 = bitsPerSample; } void CC Masher::DDV_DecompressAudioFrame_4ECFF0(s32* pMasherFrame, u8* pDecodedFrame, s32 frameSize) { AudioDecompressor decompressor; const s32 bytesPerSample = gMasher_bits_per_sample_BBB9A8 / 8; decompressor.SetChannelCount(bytesPerSample); decompressor.SetupAudioDecodePtrs(reinterpret_cast<u16*>(pMasherFrame)); memset(pDecodedFrame, 0, frameSize * bytesPerSample * gMasher_num_channels_BBB9B4); if (gMasher_bits_per_sample_BBB9A8 == 8) { u8* pAsByte = pDecodedFrame; decompressor.decode_8bit_audio_frame(pAsByte, frameSize, false); if (gMasher_num_channels_BBB9B4 == 2) { decompressor.decode_8bit_audio_frame(pAsByte + 1, frameSize, true); } } if (gMasher_bits_per_sample_BBB9A8 == 16) { decompressor.decode_16bit_audio_frame(reinterpret_cast<u16*>(pDecodedFrame), frameSize, false); if (gMasher_num_channels_BBB9B4 == 2) { decompressor.decode_16bit_audio_frame(reinterpret_cast<u16*>(pDecodedFrame) + 1, frameSize, true); } } } void* CC Masher::GetDecompressedAudioFrame_4EAC60(Masher* pMasher) { void* result = nullptr; if (pMasher->field_60_bHasAudio && pMasher->field_64_audio_frame_idx < pMasher->field_4_ddv_header.field_C_number_of_frames) { DDV_Set_Channels_And_BitsPerSample_4ECFD0(pMasher->field_50_num_channels, pMasher->field_54_bits_per_sample); DDV_DecompressAudioFrame_4ECFF0( pMasher->field_48_sound_frame_to_decode, static_cast<u8*>(pMasher->field_4C_decoded_audio_buffer), pMasher->field_2C_audio_header.field_C_single_audio_frame_size); result = pMasher->field_4C_decoded_audio_buffer; ++pMasher->field_64_audio_frame_idx; } else { ++pMasher->field_64_audio_frame_idx; result = nullptr; } return result; } s32 Masher::To1d(s32 x, s32 y) { // 8x8 index to x64 index return y * 8 + x; } u8 Masher::Clamp(f32 v) { if (v < 0.0f) v = 0.0f; if (v > 255.0f) v = 255.0f; return static_cast<u8>(v); } void Masher::SetElement(s32 x, s32 y, s32 width, s32 height, u16* ptr, u16 value, bool doubleWidth, bool doubleHeight) { if (doubleWidth) { x *= 2; } if (doubleHeight) { y *= 2; } ptr[(width * y) + x] = value; if (doubleWidth) { if (x + 1 < width) { ptr[(width * y) + x + 1] = value; } } if (doubleHeight) { if (y + 1 < height) { ptr[(width * (y + 1)) + x] = value; if (doubleWidth) { if (x + 1 < width) { ptr[(width * (y + 1)) + x + 1] = value; } } } } } uint16_t Masher::rgb888torgb565(Macroblock_RGB_Struct& rgb888Pixel) { uint8_t red = rgb888Pixel.Red; uint8_t green = rgb888Pixel.Green; uint8_t blue = rgb888Pixel.Blue; uint16_t b = (blue >> 3) & 0x1f; uint16_t g = ((green >> 2) & 0x3f) << 5; uint16_t r = ((red >> 3) & 0x1f) << 11; return static_cast<uint16_t>(r | g | b); } void Masher::ConvertYuvToRgbAndBlit(u16* pixelBuffer, s32 xoff, s32 yoff, s32 width, s32 height, bool doubleWidth, bool doubleHeight) { // convert the Y1 Y2 Y3 Y4 and Cb and Cr blocks into a 16x16 array of (Y, Cb, Cr) pixels struct Macroblock_YCbCr_Struct final { f32 Y; f32 Cb; f32 Cr; }; std::array<std::array<Macroblock_YCbCr_Struct, 16>, 16> Macroblock_YCbCr = {}; for (s32 x = 0; x < 8; x++) { for (s32 y = 0; y < 8; y++) { Macroblock_YCbCr[x][y].Y = static_cast<f32>(Y1_block[To1d(x, y)]); Macroblock_YCbCr[x + 8][y].Y = static_cast<f32>(Y2_block[To1d(x, y)]); Macroblock_YCbCr[x][y + 8].Y = static_cast<f32>(Y3_block[To1d(x, y)]); Macroblock_YCbCr[x + 8][y + 8].Y = static_cast<f32>(Y4_block[To1d(x, y)]); Macroblock_YCbCr[x * 2][y * 2].Cb = static_cast<f32>(Cb_block[To1d(x, y)]); Macroblock_YCbCr[x * 2 + 1][y * 2].Cb = static_cast<f32>(Cb_block[To1d(x, y)]); Macroblock_YCbCr[x * 2][y * 2 + 1].Cb = static_cast<f32>(Cb_block[To1d(x, y)]); Macroblock_YCbCr[x * 2 + 1][y * 2 + 1].Cb = static_cast<f32>(Cb_block[To1d(x, y)]); Macroblock_YCbCr[x * 2][y * 2].Cr = static_cast<f32>(Cr_block[To1d(x, y)]); Macroblock_YCbCr[x * 2 + 1][y * 2].Cr = static_cast<f32>(Cr_block[To1d(x, y)]); Macroblock_YCbCr[x * 2][y * 2 + 1].Cr = static_cast<f32>(Cr_block[To1d(x, y)]); Macroblock_YCbCr[x * 2 + 1][y * 2 + 1].Cr = static_cast<f32>(Cr_block[To1d(x, y)]); } } // Convert the (Y, Cb, Cr) pixels into RGB pixels std::array<std::array<Macroblock_RGB_Struct, 16>, 16> Macroblock_RGB = {}; for (u32 x = 0; x < kMacroBlockWidth; x++) { for (u32 y = 0; y < kMacroBlockHeight; y++) { const f32 r = (Macroblock_YCbCr[x][y].Y) + 1.402f * Macroblock_YCbCr[x][y].Cb; const f32 g = (Macroblock_YCbCr[x][y].Y) - 0.3437f * Macroblock_YCbCr[x][y].Cr - 0.7143f * Macroblock_YCbCr[x][y].Cb; const f32 b = (Macroblock_YCbCr[x][y].Y) + 1.772f * Macroblock_YCbCr[x][y].Cr; Macroblock_RGB[x][y].Red = Clamp(r); Macroblock_RGB[x][y].Green = Clamp(g); Macroblock_RGB[x][y].Blue = Clamp(b); // Due to macro block padding this can be out of bounds s32 xpos = x + xoff; s32 ypos = y + yoff; if (xpos < width && ypos < height) { u16 pixel16Value = rgb888torgb565(Macroblock_RGB[x][y]); // Actually is no alpha in FMVs // pixelValue = (pixelValue << 8) + Macroblock_RGB[x][y].A SetElement(xpos, ypos, width, height, pixelBuffer, pixel16Value, doubleWidth, doubleHeight); } } } }
34.407613
194
0.605836
mouzedrift
60f9a4e25e775734af11a580734e64e7ddf4bc34
439
cpp
C++
ch03/ex3_40.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch03/ex3_40.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
ch03/ex3_40.cpp
zhang1990215/Cpp-Primer
81e51869c02f2ba75e4fe491dee07eaedce2bbc9
[ "CC0-1.0" ]
null
null
null
// more discuss: https://github.com/Mooophy/Cpp-Primer/pull/241 // @frank67 #include <iostream> #include <cstring> const char cstr1[]="Hello"; const char cstr2[]="world!"; int main(int argc, char const *argv[]) { constexpr size_t new_size = strlen(cstr1) + strlen(" ") + strlen(cstr2) +1; char cstr3[new_size]; strcpy(cstr3, cstr1); strcat(cstr3, " "); strcat(cstr3, cstr2); std::cout << cstr3 << std::endl; }
20.904762
79
0.637813
zhang1990215
60fba977c3998e5b3a61e596cd3a863537bf302d
679
cpp
C++
school1/3A/bnkAccProject/BankAccount.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
school1/3A/bnkAccProject/BankAccount.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
school1/3A/bnkAccProject/BankAccount.cpp
momomeomo/School
d004bf6ed6fa3a5cec4fa067b61e5842acbaa3f6
[ "Unlicense" ]
null
null
null
#include <iostream> #include "BankAccount.h" using namespace std; BankAccount::BankAccount() : name("John Doe"), balance(100) { } BankAccount::BankAccount(string n, double b) : name(n), balance(b) { } double BankAccount::getBalance() { return balance; } bool BankAccount::withdraw(double amt) { if (amt > 0 && balance > 0) { balance = balance - amt; return true; } else { return false; } } bool BankAccount::deposit(double amt) { if (amt > 0) { balance = balance + amt; return true; } else { return false; } } void BankAccount::showAccountInfo() { cout << "Account Information" << endl; cout << name << endl; cout << "$" << balance << endl; }
13.057692
44
0.637703
momomeomo
880024200dafe7d9aa45b922392c9b788090cb53
1,431
cpp
C++
tests/lpm_math_tests.cpp
pbosler/lpm
ee406355ce45ed4f12290199ba2842070fcc3442
[ "BSD-3-Clause" ]
null
null
null
tests/lpm_math_tests.cpp
pbosler/lpm
ee406355ce45ed4f12290199ba2842070fcc3442
[ "BSD-3-Clause" ]
18
2021-06-27T17:59:03.000Z
2022-02-22T03:41:27.000Z
tests/lpm_math_tests.cpp
pbosler/lpm
ee406355ce45ed4f12290199ba2842070fcc3442
[ "BSD-3-Clause" ]
null
null
null
#include "LpmConfig.h" #include "util/lpm_math.hpp" #include "util/lpm_floating_point.hpp" #include "lpm_comm.hpp" #include "lpm_logger.hpp" #include "catch.hpp" #include <typeinfo> #include <fstream> #include <string> using namespace Lpm; TEST_CASE("lpm_math", "") { Comm comm; Logger<> logger("math_test_log", Log::level::info, comm); logger.info("atan4(0,0) = {}, expected: 0", atan4(0,0)); REQUIRE(FloatingPoint<Real>::zero(atan4(0,0))); const Real a = 1; const Real b = -3; const Real c = 2; const Real d = 4; const Real det = two_by_two_determinant(a, b, c, d); logger.info("2x2 determinant = {}; expected: 10", det); REQUIRE(Lpm::FloatingPoint<Real>::equiv(det, 10)); Real r1, r2; quadratic_roots(r1, r2, a, b, c); logger.info("quadratic root 1 = {}; expected: 2", r1); logger.info("quadratic root 2 = {}; expected: 1", r2); REQUIRE( FloatingPoint<Real>::equiv(r1, 2)); REQUIRE( FloatingPoint<Real>::equiv(r2, 1)); logger.info("Checking that BesselJ0 is even"); REQUIRE( FloatingPoint<Real>::equiv(cyl_bessel_j(0, 0.5), cyl_bessel_j(0, -0.5))); logger.info("Checking that BesselJ1 is odd"); REQUIRE( FloatingPoint<Real>::equiv(cyl_bessel_j(1, 0.5), -cyl_bessel_j(1, -0.5))); #ifndef LPM_USE_CUDA logger.info("Checking that LegendreP(l,1) = 1 for l in {0,1,2,3,4}"); for (int l=0; l<5; ++l) { REQUIRE( FloatingPoint<Real>::equiv(legendre_p(l, 1), 1)); } #endif }
28.62
85
0.661775
pbosler
8803f55703a55fd53e4bd378a07d766705a380fa
3,669
cpp
C++
source/symbols/CompilationUnitSymbols.cpp
jankcorn/slang
2c697d8f16ef2449110d3094f8eeb6196d1fcabb
[ "MIT" ]
null
null
null
source/symbols/CompilationUnitSymbols.cpp
jankcorn/slang
2c697d8f16ef2449110d3094f8eeb6196d1fcabb
[ "MIT" ]
null
null
null
source/symbols/CompilationUnitSymbols.cpp
jankcorn/slang
2c697d8f16ef2449110d3094f8eeb6196d1fcabb
[ "MIT" ]
1
2021-11-15T05:37:12.000Z
2021-11-15T05:37:12.000Z
//------------------------------------------------------------------------------ // CompilationUnitSymbols.cpp // Contains compilation unit-related symbol definitions // // File is under the MIT license; see LICENSE for details //------------------------------------------------------------------------------ #include "slang/symbols/CompilationUnitSymbols.h" #include "slang/compilation/Compilation.h" #include "slang/symbols/MemberSymbols.h" #include "slang/syntax/AllSyntax.h" namespace slang { CompilationUnitSymbol::CompilationUnitSymbol(Compilation& compilation) : Symbol(SymbolKind::CompilationUnit, "", SourceLocation()), Scope(compilation, this) { // Default the time scale to the compilation default. If it turns out // this scope has a time unit declaration it will overwrite the member. timeScale = compilation.getDefaultTimeScale(); // All compilation units import the std package automatically. auto& stdPkg = compilation.getStdPackage(); auto import = compilation.emplace<WildcardImportSymbol>(stdPkg.name, SourceLocation::NoLocation); import->setPackage(stdPkg); addWildcardImport(*import); } void CompilationUnitSymbol::addMembers(const SyntaxNode& syntax) { if (syntax.kind == SyntaxKind::TimeUnitsDeclaration) { SemanticFacts::populateTimeScale(timeScale, *this, syntax.as<TimeUnitsDeclarationSyntax>(), unitsRange, precisionRange, !anyMembers); } else if (syntax.kind == SyntaxKind::CompilationUnit) { auto& cu = syntax.as<CompilationUnitSyntax>(); if (!cu.members.empty()) { anyMembers = true; for (auto member : cu.members) Scope::addMembers(*member); } } else { anyMembers = true; Scope::addMembers(syntax); } } PackageSymbol::PackageSymbol(Compilation& compilation, string_view name, SourceLocation loc, const NetType& defaultNetType, VariableLifetime defaultLifetime) : Symbol(SymbolKind::Package, name, loc), Scope(compilation, this), defaultNetType(defaultNetType), defaultLifetime(defaultLifetime) { } PackageSymbol& PackageSymbol::fromSyntax(const Scope& scope, const ModuleDeclarationSyntax& syntax, const NetType& defaultNetType, optional<TimeScale> directiveTimeScale) { auto& comp = scope.getCompilation(); auto lifetime = SemanticFacts::getVariableLifetime(syntax.header->lifetime); auto result = comp.emplace<PackageSymbol>(comp, syntax.header->name.valueText(), syntax.header->name.location(), defaultNetType, lifetime.value_or(VariableLifetime::Static)); result->setSyntax(syntax); result->setAttributes(scope, syntax.attributes); bool first = true; optional<SourceRange> unitsRange; optional<SourceRange> precisionRange; for (auto member : syntax.members) { if (member->kind == SyntaxKind::TimeUnitsDeclaration) { SemanticFacts::populateTimeScale(result->timeScale, scope, member->as<TimeUnitsDeclarationSyntax>(), unitsRange, precisionRange, first); continue; } first = false; result->addMembers(*member); } SemanticFacts::populateTimeScale(result->timeScale, scope, directiveTimeScale, unitsRange.has_value(), precisionRange.has_value()); return *result; } } // namespace slang
41.693182
99
0.618425
jankcorn
88099bf7d2c9f65a526784adf4b8e0b94b44aabb
3,402
cpp
C++
libsrc/agl/mesh/cylinder.cpp
catlin735/animation-toolkit
ab906fa213a21168b7b5b5fc12aac46dedf60b15
[ "MIT" ]
3
2021-12-24T04:12:53.000Z
2021-12-24T04:14:28.000Z
libsrc/agl/mesh/cylinder.cpp
catlin735/animation-toolkit
ab906fa213a21168b7b5b5fc12aac46dedf60b15
[ "MIT" ]
1
2021-09-17T21:18:38.000Z
2021-09-17T21:18:38.000Z
libsrc/agl/mesh/cylinder.cpp
catlin735/animation-toolkit
ab906fa213a21168b7b5b5fc12aac46dedf60b15
[ "MIT" ]
23
2021-09-02T00:25:25.000Z
2022-01-03T17:35:27.000Z
// Copyright 2018, Savvy Sine, Aline Normoyle #include "agl/mesh/cylinder.h" #include <iostream> #include <vector> #include <cmath> #include "agl/aglm.h" namespace agl { Cylinder::Cylinder(float r, float len, GLuint nSlices) { _r1 = r; _r2 = r; _length = len; _nSlices = nSlices; } Cylinder::Cylinder(float r1, float r2, float len, GLuint nSlices) { _r1 = r1; _r2 = r2; _length = len; _nSlices = nSlices; } void Cylinder::init() { computeMesh(_r1, _r2, _length, _nSlices); } void Cylinder::computeMesh(float r1, float r2, float len, GLuint nSlices) { int nVerts = (nSlices+1) * 2 + nSlices * 2; // num top triangles = nSlices // num bottom triangles = nSlices // num side triangles = nSlices * 2 int elements = (nSlices) * 4 * 3; // Verts std::vector<GLfloat> p(3 * nVerts); // Normals std::vector<GLfloat> n(3 * nVerts); // Tex coords std::vector<GLfloat> tex(2 * nVerts); // Elements std::vector<GLuint> el(elements); // Generate positions and normals GLfloat theta; GLfloat thetaFac = glm::two_pi<float>() / nSlices; GLfloat hLen = 0.5 * len; GLuint offsets[4] = { 0, nSlices+1, (nSlices+1)*2 - 1, (nSlices+1)*2 + nSlices - 1 }; GLuint idx = 0, tIdx = 0; for (GLuint i = 0; i <= nSlices; i++) { if (i == 0) { for (GLuint j = 0; j < 2; j++) { int offset = offsets[j]; float z = j % 2 == 0? -hLen : hLen; p[idx+0+3*offset] = 0.0; p[idx+1+3*offset] = 0.0; p[idx+2+3*offset] = z; n[idx+0+3*offset] = 0.0; n[idx+1+3*offset] = 0.0; n[idx+2+3*offset] = j % 2 == 0? -1.0 : 1.0; tex[tIdx+0+2*offset] = 0.0; tex[tIdx+1+2*offset] = (z+hLen)/len; } } else { theta = (i-1) * thetaFac; float nx = cosf(theta); float ny = sinf(theta); float s = 0.5 * (theta / glm::pi<float>()); for (GLuint j = 0; j < 4; j++) { int offset = offsets[j]; float z = j % 2 == 0? -hLen : hLen; float r = j % 2 == 0? r1 : r2; float t = (z+hLen)/len; p[idx+0+3*offset] = r * nx; p[idx+1+3*offset] = r * ny; p[idx+2+3*offset] = z; n[idx+0+3*offset] = j < 2? 0.0 : nx; n[idx+1+3*offset] = j < 2? 0.0 : ny; // todo: fix normal n[idx+2+3*offset] = j < 2? (j % 2 == 0? -1.0 : 1.0) : 0.0; tex[tIdx+0+2*offset] = s; tex[tIdx+1+2*offset] = t; } } idx += 3; tIdx += 2; } // Generate the element list idx = 0; for (GLuint i = 0; i < nSlices; i++) { el[idx+0] = 0; el[idx+1] = (i+1) % (nSlices) + 1; el[idx+2] = (i+1); el[idx+0+3*nSlices] = el[idx+0] + offsets[1]; el[idx+1+3*nSlices] = el[idx+2] + offsets[1]; el[idx+2+3*nSlices] = el[idx+1] + offsets[1]; idx += 3; } int offset = nSlices * 2 + 2; idx = (nSlices)*2*3; for (GLuint i = 0; i < nSlices; i++) { int back1 = i + offset; int back2 = (i+1) % nSlices + offset; int front1 = back1 + nSlices; int front2 = back2 + nSlices; el[idx+0] = front1; el[idx+1] = back1; el[idx+2] = back2; el[idx+3] = front1; el[idx+4] = back2; el[idx+5] = front2; idx += 6; } initBuffers(&el, &p, &n, &tex); } } // namespace agl
23.79021
76
0.498824
catlin735
8809dcf21bdfcfce59b4c87b5a6d4d4394dc4fd9
14,750
hpp
C++
modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/core/integration/include/nt2/integration/functions/common/quadgk.hpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #ifndef NT2_INTEGRATION_FUNCTIONS_COMMON_QUADGK_HPP_INCLUDED #define NT2_INTEGRATION_FUNCTIONS_COMMON_QUADGK_HPP_INCLUDED #include <nt2/integration/functions/quadgk.hpp> #include <nt2/integration/output.hpp> #include <nt2/integration/options.hpp> #include <nt2/integration/waypoints.hpp> #include <nt2/integration/fudge.hpp> #include <nt2/integration/order.hpp> #include <nt2/integration/split.hpp> #include <nt2/integration/midparea.hpp> #include <nt2/integration/int_transforms.hpp> #include <nt2/include/constants/half.hpp> #include <nt2/include/constants/two.hpp> #include <nt2/include/constants/zero.hpp> #include <nt2/include/functions/abs.hpp> #include <nt2/include/functions/asin.hpp> #include <nt2/include/functions/asinh.hpp> #include <nt2/include/functions/average.hpp> #include <nt2/include/functions/cast.hpp> #include <nt2/include/functions/diff.hpp> #include <nt2/include/functions/fliplr.hpp> #include <nt2/include/functions/flipud.hpp> #include <nt2/include/functions/globalsum.hpp> #include <nt2/include/functions/isempty.hpp> #include <nt2/include/functions/is_finite.hpp> #include <nt2/include/functions/is_inf.hpp> #include <nt2/include/functions/is_not_finite.hpp> #include <nt2/include/functions/linspace.hpp> #include <nt2/include/functions/logical_not.hpp> #include <nt2/include/functions/max.hpp> #include <nt2/include/functions/mean.hpp> #include <nt2/include/functions/mtimes.hpp> #include <nt2/include/functions/globalasum1.hpp> #include <nt2/include/functions/numel.hpp> #include <nt2/include/functions/rowvect.hpp> #include <nt2/include/functions/size.hpp> #include <nt2/include/functions/sin.hpp> #include <nt2/include/functions/sx.hpp> #include <nt2/include/functions/tanh.hpp> #include <nt2/include/functions/vertcat.hpp> #include <nt2/core/container/table/table.hpp> #include <nt2/sdk/complex/meta/is_complex.hpp> #include <boost/mpl/bool.hpp> namespace nt2 { namespace details { template<class T, class V> class quadgk_impl { public : typedef T input_t; typedef typename meta::as_logical<input_t>::type bi_t; typedef V value_t; typedef typename meta::is_complex<value_t>::type v_is_cplx_t; typedef typename boost::mpl::if_<v_is_cplx_t,value_t,input_t>::type result_t; typedef typename meta::as_real<value_t>::type real_t; typedef details::integration_settings<T, V, tag::quadgk_> o_t; typedef container::table<value_t> vtab_t; typedef container::table<input_t> itab_t; typedef container::table<real_t> rtab_t; typedef container::table<result_t> restab_t; typedef container::table<bi_t> bitab_t; quadgk_impl() : errbnd_(Nan<real_t>()), fcnt_(0), maxfcnt_(Valmax<size_t>()), warn_(0), res_(){} ~quadgk_impl() {} size_t nbeval() const { return fcnt_; } real_t lasterror() const { return errbnd_; } bool ok() const { return warn_ == 0; } const restab_t & result() const { return res_; } void setwarn(size_t w) { if(w > warn_) warn_ = w; } size_t warn() const { return warn_; } template < class FUNC, class X> void compute( const FUNC& f, const X & x, const o_t & o, const boost::mpl::false_ & choice) // cplx path integration { init(o, x, choice); interval_ = tinterval_; vadapt(transform<FUNC, details::no_transform, input_t, value_t>(f, a_, b_, interval_)); } template < class FUNC, class X> void compute( const FUNC& f, const X & x, const o_t & o, const boost::mpl::true_ & choice) // real interval integration { init(o, x, choice); if (a_ == b_) //quick return { result_t r = nt2::multiplies(f(a_), Zero<input_t>()); //result_t r = details::midparea<result_t, value_t>(f, tinterval_(begin_), tinterval_(end_)); res_ = r; errbnd_ = nt2::abs(r); return; } interval_ = tinterval_; adjust_and_call(f); if(reversedir_) res_ = -res_; } private : real_t errbnd_; size_t fcnt_; size_t maxfcnt_; size_t maxintvcnt_; size_t warn_; real_t abstol_; real_t reltol_; restab_t res_; real_t hmin_; bool reversedir_; itab_t tinterval_; //original points itab_t interval_; //transformed points, to reduce integration to a subinterval of [-1, 1] input_t a_, b_; bool firstfunceval_; size_t nb_; static const size_t minintervalcount_ = 10; // Minimum number subintervals to start. // Gauss-Kronrod (7,15) pair. Use symmetry in defining nodes and weights. static const itab_t& nodes() { static const input_t gk[7] = { input_t(0.2077849550078985), input_t(0.4058451513773972), input_t(0.5860872354676911), input_t(0.7415311855993944), input_t(0.8648644233597691), input_t(0.9491079123427585), input_t(0.9914553711208126)}; static const itab_t k(of_size(7, 1), &gk[0], &gk[7]); static const itab_t k15 = nt2::catv(nt2::catv(-flipud(k), nt2::Zero<input_t>()),k); return k15; } static const vtab_t& wt() { static const value_t pwt[7] = { value_t(0.2044329400752989), value_t(0.1903505780647854), value_t(0.1690047266392679), value_t(0.1406532597155259), value_t(0.1047900103222502), value_t(0.06309209262997855), value_t(0.02293532201052922) }; static const vtab_t wt(of_size(1, 7), &pwt[0], &pwt[7]); static const vtab_t wt15 = nt2::cath(nt2::cath(fliplr(wt),value_t(0.2094821410847278)),wt); return wt15; } static const vtab_t& ewt() { static const value_t pwt7[7] = { value_t(0),value_t(0.3818300505051189),value_t(0),value_t(0.2797053914892767), value_t(0),value_t(0.1294849661688697),value_t(0) }; static const vtab_t wt7(of_size(1, 7), &pwt7[0], &pwt7[7]); static const vtab_t ewt15 = wt()-nt2::cath(nt2::cath(fliplr(wt7),value_t(0.4179591836734694)),wt7); return ewt15; } template < class X > void init( const o_t & o, const X& x, const boost::mpl::false_ & ) { details::prepare_waypoints(o, x, tinterval_); a_ = tinterval_(begin_); b_ = tinterval_(end_); abstol_ = o.abstol; reltol_ = o.reltol; warn_ = 0; fcnt_ = 0; maxfcnt_ = Valmax<size_t>(); maxintvcnt_ = o.maxintvcnt; errbnd_ = nt2::Inf<real_t>(); } template < class X > void init( const o_t & o, const X& x, const boost::mpl::true_ & )//real path integration { details::prepare_waypoints(o, x, tinterval_); reversedir_ = details::order_points(tinterval_, true); a_ = tinterval_(begin_); b_ = tinterval_(end_); abstol_ = o.abstol; reltol_ = o.reltol; warn_ = 0; fcnt_ = 0; maxfcnt_ = Valmax<size_t>(); maxintvcnt_ = o.maxintvcnt; errbnd_ = nt2::Inf<real_t>(); firstfunceval_ = true; } template < class FUNC > inline bool check(FUNC f, bool t, size_t w, const result_t& q) { if (t) { fcnt_ = f.fcnt(); res_ = q; setwarn(w); } return t; } template < class FUNC > void vadapt(FUNC f) { real_t pathlen; itab_t tmp0; details::split(f.interval_, minintervalcount_, tmp0, pathlen); interval_ = tmp0; if (pathlen == 0) { input_t tmp = nt2::multiplies(f.interval_(end_), nt2::Half<real_t>()); input_t xx = nt2::fma(f.interval_(begin_), nt2::Half<real_t>(), tmp); input_t d = (f.interval_(end_)-f.interval_(begin_)); result_t r = nt2::multiplies(f(xx), d); res_ = r; errbnd_ = nt2::abs(r); return; } // Initialize array of subintervals of [a,b]. itab_t subs = nt2::catv(interval_(nt2::_(begin_, end_-1)), interval_(nt2::_(begin_+1, end_))); // Initialize partial sums. result_t q_ok = nt2::Zero<result_t>(); result_t err_ok = nt2::Zero<result_t>(); // Initialize main loop nb_ = 0; while (true) { ++nb_; // subs contains subintervals of [a,b] where the integral is not // sufficiently accurate. The first row of SUBS holds the left end // points and the second row, the corresponding right endpoints. itab_t midpt = nt2::mean(subs); // midpoints of the subintervals itab_t halfh = diff(subs)*Half<input_t>(); // half the lengths of the subintervals itab_t x = nt2::rowvect(nt2::sx(nt2::tag::plus_(),nt2::mtimes(nodes(), halfh),midpt)); // BOOST_AUTO_TPL(fx, f(x)); vtab_t fx = f(x); // Quit if mesh points are too close. fx.resize(nt2::of_size(nt2::numel(wt()), numel(fx)/numel(wt()))); // Quantities for subintervals. restab_t qsubs = nt2::mtimes(wt(), fx)*halfh; restab_t errsubs = nt2::mtimes(ewt(), fx)* halfh; // Calculate current values of q and tol. result_t q = nt2::globalsum(qsubs) + q_ok; if (check(f, f.tooclose(), 6, q)) break; real_t tol = max(abstol_,reltol_*nt2::abs(q)); // Locate subintervals where the approximate integrals are // sufficiently accurate and use them to update the partial // error sum. bitab_t ff= nt2::le(nt2::abs(errsubs), (Two<real_t>()*tol/pathlen)*nt2::abs(halfh)); bitab_t notff = nt2::logical_not(ff); err_ok += nt2::globalsum(errsubs(ff)); // Remove errsubs entries for subintervals with accurate // approximations. restab_t errsubs1 = nt2::rowvect(errsubs(notff)); errsubs = errsubs1; //ALIASING CAN BE AVOIDED PERHAPS // The approximate error bound is constructed by adding the // approximate error bounds for the subintervals with accurate // approximations to the 1-norm of the approximate error bounds // for the remaining subintervals. This guards against // excessive cancellation of the errors of the remaining // subintervals. errbnd_ = nt2::abs(err_ok) + nt2::globalasum1(errsubs); // Check for nonfinites. if (check(f, is_not_finite(q) && is_finite(errbnd_), 3, q)) break; // Infinite or Not-a-Number value encountered. if (check(f, errbnd_ <= tol, 0, q)) break; // tolerance reached: convergence // if (check(f, f.fcnt() > maxfcnt_, 5, q)) break; // Max evaluation number reached // Remove subintervals with accurate approximations. itab_t subs_tmp = subs(nt2::_, notff); subs = subs_tmp; if (check(f, nt2::isempty(subs), 0, q)) break; // All subs got required precision // Update the partial sum for the integral. q_ok += nt2::globalsum(qsubs(ff)); // Split the remaining subintervals in half. Quit if splitting // results in too many subintervals. size_t nsubs = 2*nt2::size(subs,2); if (check(f, nsubs > maxintvcnt_, 2, q)) break; //Reached the limit on the maximum number of intervals in use. itab_t midpt1 = nt2::rowvect(midpt(notff)); midpt = midpt1; itab_t z = catv(catv(catv(subs(begin_,nt2::_),midpt),midpt),subs(end_,nt2::_)); subs = reshape(z,2,numel(z)/2); } } template < class F > inline void adjust_and_call(const F &f) { bool fina = nt2::is_finite(a_); bool finb = nt2::is_finite(b_); if(fina && finb) { vadapt(transform<F, details::fina_finb, input_t, value_t>(f, a_, b_, interval_)); } else { bool infb = nt2::is_inf(b_); if (fina && infb) { vadapt(transform<F, details::fina_infb, input_t, value_t>(f, a_, b_, interval_)); } else { bool infa = nt2::is_inf(a_); if (infa && finb) { vadapt(transform<F, details::infa_finb, input_t, value_t>(f, a_, b_, interval_)); } else if (infa && infb) { vadapt(transform<F, details::infa_infb, input_t, value_t>(f, a_, b_, interval_)); } else //is_nan(a) || is_nan(b) { result_t r = Nan<result_t>(); errbnd_ = nt2::abs(r); fcnt_ = 1; } } } } }; } } namespace nt2 { namespace ext { BOOST_DISPATCH_IMPLEMENT ( quadgk_, tag::cpu_ , (F)(X)(O) , (unspecified_< F >) ((ast_<X, nt2::container::domain>)) (unspecified_<O>) ) { typedef typename O::value_t value_t; typedef typename O::input_t input_t; typedef typename O::real_t real_t; typedef typename O::result_t result_t; typedef typename O::restab_t restab_t; typedef typename boost::is_same<input_t,real_t>::type input_is_real_t; typedef nt2::integration::output<restab_t,real_t> result_type; result_type operator()(F f, X const& x, O const& o) { details::quadgk_impl<input_t, value_t> q; q.compute(f, x, o, input_is_real_t()); result_type that = {q.result(), q.lasterror(),q.nbeval(),q.ok(),q.warn()}; return that; } }; } } #endif
40.972222
137
0.57322
psiha
880b2355388b7e1f7ea00656f0cae36242952648
23,137
cpp
C++
src/mongo/s/strategy.cpp
baiyanghese/mongo
89fcbab94c7103105e8c72f654a5774a066bdb90
[ "Apache-2.0" ]
1
2015-11-06T05:42:37.000Z
2015-11-06T05:42:37.000Z
src/mongo/s/strategy.cpp
baiyanghese/mongo
89fcbab94c7103105e8c72f654a5774a066bdb90
[ "Apache-2.0" ]
null
null
null
src/mongo/s/strategy.cpp
baiyanghese/mongo
89fcbab94c7103105e8c72f654a5774a066bdb90
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2010 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ // strategy_sharded.cpp #include "mongo/pch.h" #include "mongo/base/status.h" #include "mongo/base/owned_pointer_vector.h" #include "mongo/bson/util/builder.h" #include "mongo/client/connpool.h" #include "mongo/client/dbclientcursor.h" #include "mongo/db/audit.h" #include "mongo/db/auth/action_type.h" #include "mongo/db/auth/authorization_session.h" #include "mongo/db/commands.h" #include "mongo/db/max_time.h" #include "mongo/db/server_parameters.h" #include "mongo/db/structure/catalog/index_details.h" #include "mongo/db/namespace_string.h" #include "mongo/db/query/lite_parsed_query.h" #include "mongo/db/stats/counters.h" #include "mongo/s/client_info.h" #include "mongo/s/cluster_write.h" #include "mongo/s/chunk.h" #include "mongo/s/chunk_version.h" #include "mongo/s/cursors.h" #include "mongo/s/grid.h" #include "mongo/s/request.h" #include "mongo/s/version_manager.h" #include "mongo/s/write_ops/batch_upconvert.h" #include "mongo/util/mongoutils/str.h" // error codes 8010-8040 namespace mongo { static bool _isSystemIndexes( const char* ns ) { return nsToCollectionSubstring(ns) == "system.indexes"; } /** * Returns true if request is a query for sharded indexes. */ static bool doShardedIndexQuery( Request& r, const QuerySpec& qSpec ) { // Extract the ns field from the query, which may be embedded within the "query" or // "$query" field. string indexNSQuery(qSpec.filter()["ns"].str()); DBConfigPtr config = grid.getDBConfig( r.getns() ); if ( !config->isSharded( indexNSQuery )) { return false; } // if you are querying on system.indexes, we need to make sure we go to a shard // that actually has chunks. This is not a perfect solution (what if you just // look at all indexes), but better than doing nothing. ShardPtr shard; ChunkManagerPtr cm; config->getChunkManagerOrPrimary( indexNSQuery, cm, shard ); if ( cm ) { set<Shard> shards; cm->getAllShards( shards ); verify( shards.size() > 0 ); shard.reset( new Shard( *shards.begin() ) ); } ShardConnection dbcon( *shard , r.getns() ); DBClientBase &c = dbcon.conn(); string actualServer; Message response; bool ok = c.call( r.m(), response, true , &actualServer ); uassert( 10200 , "mongos: error calling db", ok ); { QueryResult *qr = (QueryResult *) response.singleData(); if ( qr->resultFlags() & ResultFlag_ShardConfigStale ) { dbcon.done(); // Version is zero b/c this is deprecated codepath throw RecvStaleConfigException( r.getns(), "Strategy::doQuery", ChunkVersion( 0, 0, OID() ), ChunkVersion( 0, 0, OID() )); } } r.reply( response , actualServer.size() ? actualServer : c.getServerAddress() ); dbcon.done(); return true; } void Strategy::queryOp( Request& r ) { verify( !NamespaceString( r.getns() ).isCommand() ); Timer queryTimer; QueryMessage q( r.d() ); NamespaceString ns(q.ns); ClientBasic* client = ClientBasic::getCurrent(); AuthorizationSession* authSession = client->getAuthorizationSession(); Status status = authSession->checkAuthForQuery(ns, q.query); audit::logQueryAuthzCheck(client, ns, q.query, status.code()); uassertStatusOK(status); LOG(3) << "shard query: " << q.ns << " " << q.query << endl; if ( q.ntoreturn == 1 && strstr(q.ns, ".$cmd") ) throw UserException( 8010 , "something is wrong, shouldn't see a command here" ); QuerySpec qSpec( (string)q.ns, q.query, q.fields, q.ntoskip, q.ntoreturn, q.queryOptions ); // Parse "$maxTimeMS". StatusWith<int> maxTimeMS = LiteParsedQuery::parseMaxTimeMSQuery( q.query ); uassert( 17233, maxTimeMS.getStatus().reason(), maxTimeMS.isOK() ); if ( _isSystemIndexes( q.ns ) && doShardedIndexQuery( r, qSpec )) { return; } ParallelSortClusteredCursor * cursor = new ParallelSortClusteredCursor( qSpec, CommandInfo() ); verify( cursor ); // TODO: Move out to Request itself, not strategy based try { cursor->init(); if ( qSpec.isExplain() ) { BSONObjBuilder explain_builder; cursor->explain( explain_builder ); explain_builder.appendNumber( "millis", static_cast<long long>(queryTimer.millis()) ); BSONObj b = explain_builder.obj(); replyToQuery( 0 , r.p() , r.m() , b ); delete( cursor ); return; } } catch(...) { delete cursor; throw; } // TODO: Revisit all of this when we revisit the sharded cursor cache if (cursor->getNumQueryShards() != 1) { // More than one shard (or zero), manage with a ShardedClientCursor // NOTE: We may also have *zero* shards here when the returnPartial flag is set. // Currently the code in ShardedClientCursor handles this. ShardedClientCursorPtr cc (new ShardedClientCursor( q , cursor )); BufBuilder buffer( ShardedClientCursor::INIT_REPLY_BUFFER_SIZE ); int docCount = 0; const int startFrom = cc->getTotalSent(); bool hasMore = cc->sendNextBatch( r, q.ntoreturn, buffer, docCount ); if ( hasMore ) { LOG(5) << "storing cursor : " << cc->getId() << endl; int cursorLeftoverMillis = maxTimeMS.getValue() - queryTimer.millis(); if ( maxTimeMS.getValue() == 0 ) { // 0 represents "no limit". cursorLeftoverMillis = kMaxTimeCursorNoTimeLimit; } else if ( cursorLeftoverMillis <= 0 ) { cursorLeftoverMillis = kMaxTimeCursorTimeLimitExpired; } cursorCache.store( cc, cursorLeftoverMillis ); } replyToQuery( 0, r.p(), r.m(), buffer.buf(), buffer.len(), docCount, startFrom, hasMore ? cc->getId() : 0 ); } else{ // Only one shard is used // Remote cursors are stored remotely, we shouldn't need this around. scoped_ptr<ParallelSortClusteredCursor> cursorDeleter( cursor ); ShardPtr shard = cursor->getQueryShard(); verify( shard.get() ); DBClientCursorPtr shardCursor = cursor->getShardCursor(*shard); // Implicitly stores the cursor in the cache r.reply( *(shardCursor->getMessage()) , shardCursor->originalHost() ); // We don't want to kill the cursor remotely if there's still data left shardCursor->decouple(); } } void Strategy::clientCommandOp( Request& r ) { QueryMessage q( r.d() ); LOG(3) << "single query: " << q.ns << " " << q.query << " ntoreturn: " << q.ntoreturn << " options : " << q.queryOptions << endl; NamespaceString nss( r.getns() ); // Regular queries are handled in strategy_shard.cpp verify( nss.isCommand() || nss.isSpecialCommand() ); if ( handleSpecialNamespaces( r , q ) ) return; int loops = 5; while ( true ) { BSONObjBuilder builder; try { BSONObj cmdObj = q.query; { BSONElement e = cmdObj.firstElement(); if (e.type() == Object && (e.fieldName()[0] == '$' ? str::equals("query", e.fieldName()+1) : str::equals("query", e.fieldName()))) { // Extract the embedded query object. if (cmdObj.hasField(Query::ReadPrefField.name())) { // The command has a read preference setting. We don't want // to lose this information so we copy this to a new field // called $queryOptions.$readPreference BSONObjBuilder finalCmdObjBuilder; finalCmdObjBuilder.appendElements(e.embeddedObject()); BSONObjBuilder queryOptionsBuilder( finalCmdObjBuilder.subobjStart("$queryOptions")); queryOptionsBuilder.append(cmdObj[Query::ReadPrefField.name()]); queryOptionsBuilder.done(); cmdObj = finalCmdObjBuilder.obj(); } else { cmdObj = e.embeddedObject(); } } } Command::runAgainstRegistered(q.ns, cmdObj, builder, q.queryOptions); BSONObj x = builder.done(); replyToQuery(0, r.p(), r.m(), x); return; } catch ( StaleConfigException& e ) { if ( loops <= 0 ) throw e; loops--; log() << "retrying command: " << q.query << endl; // For legacy reasons, ns may not actually be set in the exception :-( string staleNS = e.getns(); if( staleNS.size() == 0 ) staleNS = q.ns; ShardConnection::checkMyConnectionVersions( staleNS ); if( loops < 4 ) versionManager.forceRemoteCheckShardVersionCB( staleNS ); } catch ( AssertionException& e ) { Command::appendCommandStatus(builder, e.toStatus()); BSONObj x = builder.done(); replyToQuery(0, r.p(), r.m(), x); return; } } } bool Strategy::handleSpecialNamespaces( Request& r , QueryMessage& q ) { const char * ns = strstr( r.getns() , ".$cmd.sys." ); if ( ! ns ) return false; ns += 10; BSONObjBuilder b; vector<Shard> shards; ClientBasic* client = ClientBasic::getCurrent(); AuthorizationSession* authSession = client->getAuthorizationSession(); if ( strcmp( ns , "inprog" ) == 0 ) { const bool isAuthorized = authSession->isAuthorizedForActionsOnResource( ResourcePattern::forClusterResource(), ActionType::inprog); audit::logInProgAuthzCheck( client, q.query, isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized); uassert(ErrorCodes::Unauthorized, "not authorized to run inprog", isAuthorized); Shard::getAllShards( shards ); BSONArrayBuilder arr( b.subarrayStart( "inprog" ) ); for ( unsigned i=0; i<shards.size(); i++ ) { Shard shard = shards[i]; ScopedDbConnection conn(shard.getConnString()); BSONObj temp = conn->findOne( r.getns() , q.query ); if ( temp["inprog"].isABSONObj() ) { BSONObjIterator i( temp["inprog"].Obj() ); while ( i.more() ) { BSONObjBuilder x; BSONObjIterator j( i.next().Obj() ); while( j.more() ) { BSONElement e = j.next(); if ( str::equals( e.fieldName() , "opid" ) ) { stringstream ss; ss << shard.getName() << ':' << e.numberInt(); x.append( "opid" , ss.str() ); } else if ( str::equals( e.fieldName() , "client" ) ) { x.appendAs( e , "client_s" ); } else { x.append( e ); } } arr.append( x.obj() ); } } conn.done(); } arr.done(); } else if ( strcmp( ns , "killop" ) == 0 ) { const bool isAuthorized = authSession->isAuthorizedForActionsOnResource( ResourcePattern::forClusterResource(), ActionType::killop); audit::logKillOpAuthzCheck( client, q.query, isAuthorized ? ErrorCodes::OK : ErrorCodes::Unauthorized); uassert(ErrorCodes::Unauthorized, "not authorized to run killop", isAuthorized); BSONElement e = q.query["op"]; if ( e.type() != String ) { b.append( "err" , "bad op" ); b.append( e ); } else { b.append( e ); string s = e.String(); string::size_type i = s.find( ':' ); if ( i == string::npos ) { b.append( "err" , "bad opid" ); } else { string shard = s.substr( 0 , i ); int opid = atoi( s.substr( i + 1 ).c_str() ); b.append( "shard" , shard ); b.append( "shardid" , opid ); log() << "want to kill op: " << e << endl; Shard s(shard); ScopedDbConnection conn(s.getConnString()); conn->findOne( r.getns() , BSON( "op" << opid ) ); conn.done(); } } } else if ( strcmp( ns , "unlock" ) == 0 ) { b.append( "err" , "can't do unlock through mongos" ); } else { warning() << "unknown sys command [" << ns << "]" << endl; return false; } BSONObj x = b.done(); replyToQuery(0, r.p(), r.m(), x); return true; } void Strategy::commandOp( const string& db, const BSONObj& command, int options, const string& versionedNS, const BSONObj& targetingQuery, vector<CommandResult>* results ) { QuerySpec qSpec(db + ".$cmd", command, BSONObj(), 0, 1, options); ParallelSortClusteredCursor cursor( qSpec, CommandInfo( versionedNS, targetingQuery ) ); // Initialize the cursor cursor.init(); set<Shard> shards; cursor.getQueryShards( shards ); for( set<Shard>::iterator i = shards.begin(), end = shards.end(); i != end; ++i ){ CommandResult result; result.shardTarget = *i; string errMsg; // ignored, should never be invalid b/c an exception thrown earlier result.target = ConnectionString::parse( cursor.getShardCursor( *i )->originalHost(), errMsg ); result.result = cursor.getShardCursor( *i )->peekFirst().getOwned(); results->push_back( result ); } } void Strategy::getMore( Request& r ) { Timer getMoreTimer; const char *ns = r.getns(); // TODO: Handle stale config exceptions here from coll being dropped or sharded during op // for now has same semantics as legacy request DBConfigPtr config = grid.getDBConfig( ns ); ShardPtr primary; ChunkManagerPtr info; config->getChunkManagerOrPrimary( ns, info, primary ); // // TODO: Cleanup cursor cache, consolidate into single codepath // int ntoreturn = r.d().pullInt(); long long id = r.d().pullInt64(); string host = cursorCache.getRef( id ); ShardedClientCursorPtr cursor = cursorCache.get( id ); int cursorMaxTimeMS = cursorCache.getMaxTimeMS( id ); // Cursor ids should not overlap between sharded and unsharded cursors massert( 17012, str::stream() << "duplicate sharded and unsharded cursor id " << id << " detected for " << ns << ", duplicated on host " << host, NULL == cursorCache.get( id ).get() || host.empty() ); ClientBasic* client = ClientBasic::getCurrent(); NamespaceString nsString(ns); AuthorizationSession* authSession = client->getAuthorizationSession(); Status status = authSession->checkAuthForGetMore( nsString, id ); audit::logGetMoreAuthzCheck( client, nsString, id, status.code() ); uassertStatusOK(status); if( !host.empty() ){ LOG(3) << "single getmore: " << ns << endl; // we used ScopedDbConnection because we don't get about config versions // not deleting data is handled elsewhere // and we don't want to call setShardVersion ScopedDbConnection conn(host); Message response; bool ok = conn->callRead( r.m() , response); uassert( 10204 , "dbgrid: getmore: error calling db", ok); bool hasMore = (response.singleData()->getCursor() != 0); if ( !hasMore ) { cursorCache.removeRef( id ); } r.reply( response , "" /*conn->getServerAddress() */ ); conn.done(); return; } else if ( cursor ) { if ( cursorMaxTimeMS == kMaxTimeCursorTimeLimitExpired ) { cursorCache.remove( id ); uasserted( ErrorCodes::ExceededTimeLimit, "operation exceeded time limit" ); } // TODO: Try to match logic of mongod, where on subsequent getMore() we pull lots more data? BufBuilder buffer( ShardedClientCursor::INIT_REPLY_BUFFER_SIZE ); int docCount = 0; const int startFrom = cursor->getTotalSent(); bool hasMore = cursor->sendNextBatch( r, ntoreturn, buffer, docCount ); if ( hasMore ) { // still more data cursor->accessed(); if ( cursorMaxTimeMS != kMaxTimeCursorNoTimeLimit ) { // Update remaining amount of time in cursor cache. int cursorLeftoverMillis = cursorMaxTimeMS - getMoreTimer.millis(); if ( cursorLeftoverMillis <= 0 ) { cursorLeftoverMillis = kMaxTimeCursorTimeLimitExpired; } cursorCache.updateMaxTimeMS( id, cursorLeftoverMillis ); } } else { // we've exhausted the cursor cursorCache.remove( id ); } replyToQuery( 0, r.p(), r.m(), buffer.buf(), buffer.len(), docCount, startFrom, hasMore ? cursor->getId() : 0 ); return; } else { LOG( 3 ) << "could not find cursor " << id << " in cache for " << ns << endl; replyToQuery( ResultFlag_CursorNotFound , r.p() , r.m() , 0 , 0 , 0 ); return; } } void Strategy::writeOp( int op , Request& r ) { // make sure we have a last error dassert( lastError.get( false /* don't create */) ); OwnedPointerVector<BatchedCommandRequest> requestsOwned; vector<BatchedCommandRequest*>& requests = requestsOwned.mutableVector(); msgToBatchRequests( r.m(), &requests ); for ( vector<BatchedCommandRequest*>::iterator it = requests.begin(); it != requests.end(); ++it ) { // Multiple commands registered to last error as multiple requests if ( it != requests.begin() ) lastError.startRequest( r.m(), lastError.get( false ) ); BatchedCommandRequest* request = *it; // Adjust namespaces for command NamespaceString fullNS( request->getNS() ); string cmdNS = fullNS.getCommandNS(); // We only pass in collection name to command request->setNS( fullNS.coll() ); BSONObjBuilder builder; BSONObj requestBSON = request->toBSON(); { // Disable the last error object for the duration of the write cmd LastError::Disabled disableLastError( lastError.get( false ) ); Command::runAgainstRegistered( cmdNS.c_str(), requestBSON, builder, 0 ); } BatchedCommandResponse response; bool parsed = response.parseBSON( builder.done(), NULL ); (void) parsed; // for compile dassert( parsed && response.isValid( NULL ) ); // Populate the lastError object based on the write response lastError.get( false )->reset(); bool hadError = batchErrorToLastError( *request, response, lastError.get( false ) ); // Check if this is an ordered batch and we had an error which should stop processing if ( request->getOrdered() && hadError ) break; } } Strategy * STRATEGY = new Strategy(); }
39.281834
139
0.532999
baiyanghese
880c54457c81ccea10835f5f299c0668d31f6026
1,793
cc
C++
test/cctest/heap/test-unmapper.cc
ProgArt/WebKit_js_v8
fc683744e50726fc1e3094a3ecce059488cb6921
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
test/cctest/heap/test-unmapper.cc
nacersalaheddine/v8
cffe6247ad06d90d2fb69e3710358983eaed39d5
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
test/cctest/heap/test-unmapper.cc
nacersalaheddine/v8
cffe6247ad06d90d2fb69e3710358983eaed39d5
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/v8.h" #include "src/heap/spaces.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" using v8::IdleTask; using v8::Task; using v8::Isolate; namespace v8 { namespace internal { namespace heap { class MockPlatformForUnmapper : public TestPlatform { public: MockPlatformForUnmapper() : task_(nullptr), old_platform_(i::V8::GetCurrentPlatform()) { // Now that it's completely constructed, make this the current platform. i::V8::SetPlatformForTesting(this); } virtual ~MockPlatformForUnmapper() { delete task_; i::V8::SetPlatformForTesting(old_platform_); for (auto& task : worker_tasks_) { old_platform_->CallOnWorkerThread(std::move(task)); } worker_tasks_.clear(); } void CallOnForegroundThread(v8::Isolate* isolate, Task* task) override { task_ = task; } void CallOnWorkerThread(std::unique_ptr<Task> task) override { worker_tasks_.push_back(std::move(task)); } bool IdleTasksEnabled(v8::Isolate* isolate) override { return false; } int NumberOfWorkerThreads() override { return old_platform_->NumberOfWorkerThreads(); } private: Task* task_; std::vector<std::unique_ptr<Task>> worker_tasks_; v8::Platform* old_platform_; }; TEST(EagerUnmappingInCollectAllAvailableGarbage) { CcTest::InitializeVM(); MockPlatformForUnmapper platform; Heap* heap = CcTest::heap(); i::heap::SimulateFullSpace(heap->old_space()); CcTest::CollectAllAvailableGarbage(); CHECK_EQ(0, heap->memory_allocator()->unmapper()->NumberOfChunks()); } } // namespace heap } // namespace internal } // namespace v8
26.761194
76
0.72058
ProgArt
880cda19cda901ac1805b41bdd6f4654f1d66887
1,211
cpp
C++
linear-list/list/copy_list_with_random_pointer.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
1
2015-07-15T07:31:42.000Z
2015-07-15T07:31:42.000Z
linear-list/list/copy_list_with_random_pointer.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
linear-list/list/copy_list_with_random_pointer.cpp
zhangxin23/leetcode
4c8fc60e59448045a3e880caaedd0486164e68e7
[ "MIT" ]
null
null
null
#include <stddef.h> /** * A linked list is given such that each node contains an additional random pointer which could point to * any node in the list or null. * Return a deep copy of the list. * */ struct RandomListNode { int label; RandomListNode *next, *random; RandomListNode(int x) : label(x), next(NULL), random(NULL) {} }; class Solution { public: RandomListNode* copyRandomList(RandomListNode* head) { RandomListNode* cur = head; while(cur) { RandomListNode* tmp = new RandomListNode(cur->label); RandomListNode* next = cur->next; cur->next = tmp; tmp->next = next; cur = next; } cur = head; while(cur) { if(cur->random != NULL) cur->next->random = cur->random->next; cur = cur->next->next; } cur = head; RandomListNode* new_head = head->next; RandomListNode* new_cur = new_head; while(new_cur) { cur->next = cur->next->next; new_cur->next = new_cur->next->next; cur = cur->next; new_cur = new_cur->next; } return new_head; } };
25.765957
104
0.54583
zhangxin23
8810dca7b29149e6c2cd44f608058dd9c9957fb7
3,404
cpp
C++
libairt/module.cpp
AiRT-Software/ocs
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
[ "BSD-4-Clause" ]
1
2019-02-07T12:24:51.000Z
2019-02-07T12:24:51.000Z
libairt/module.cpp
AiRT-Software/ocs
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
[ "BSD-4-Clause" ]
null
null
null
libairt/module.cpp
AiRT-Software/ocs
2d6056a1260ac9ac75cfd507fb1a77db3b26298a
[ "BSD-4-Clause" ]
1
2020-07-06T10:33:10.000Z
2020-07-06T10:33:10.000Z
#include "log.h" #include "stdMessage.h" #include "module.h" #include "net/message.h" #include "net/socket.h" #include "net/reactor.h" using airt::Context; using airt::Log; using airt::Message; using airt::Module; using airt::Reactor; using airt::Socket; using airt::StdMessage; Module::Module(const std::string &cmdport, const std::string &pubport, const std::string &subport, std::shared_ptr<Context> context) : commandport(cmdport), publishport(pubport), subscribeport(subport), deviceOn(false), done(false) { if (!context) this->context = std::make_shared<Context>(); else this->context = context; cmdsocket = std::unique_ptr<Socket>(new Socket(*(this->context), Socket::SocketType::pair)); cmdsocket->bind(commandport); pubsocket = std::unique_ptr<Socket>(new Socket(*(this->context), Socket::SocketType::publish)); pubsocket->bind(publishport); if (subscribeport.empty()) { thread = std::thread(std::bind(&Module::run<false>, this)); } else { subsocket = std::unique_ptr<Socket>(new Socket(*(this->context), Socket::SocketType::subscribe)); subsocket->bind(subscribeport); thread = std::thread(std::bind(&Module::run<true>, this)); } } void Module::processCmd() { Message m; if (!cmdsocket->receive(m, true)) return; if (airt::isStdCommand(m)) { switch (airt::getMessageAction(m)) { case StdMessage::QUIT: done = quitDevice(); break; case StdMessage::START: deviceOn = startDevice(); break; case StdMessage::STOP: stopDevice(); deviceOn = false; break; default: Log::error("Module: Unknown standard command message: {}", airt::to_string(m)); auto um = StdNotification(StdMessage::UNKNOWN_COMMAND).toMsg(); pubsocket->send(um); return; } } else this->onMessage(m); } void Module::processNot() { Message notification; if (subsocket->receive(notification, true)) { onNotification(notification); } } template <bool hassubscriber> void Module::run() { if (hassubscriber) { Log::info("Opening the ports {} (cmd), {} (pub) and {} (sub)", commandport, publishport, subscribeport); } else { Log::info("Opening the ports {} (cmd) and {} (pub)", commandport, publishport); } Reactor reactor; if (hassubscriber) reactor.add(*subsocket, std::bind(&Module::processNot, this)); reactor.add(*cmdsocket, std::bind(&Module::processCmd, this)); while (true) { bool idle = !reactor.poll(10); if (done) break; // Is the device on and there is a data ready? if (deviceOn && dataReady()) { idle = false; sendMessage(); } if (tasks.run()) idle = false; if (idle) { onIdle(); } } Log::info("Module in port {} shutting down", commandport); } void Module::shutdown() { stopDevice(); done = true; thread.join(); }
25.214815
112
0.543772
AiRT-Software
8811733f9867291a8ec1436637e46a5ee5c72b63
2,054
hpp
C++
include/cql/exceptions/cql_query_timeout_exception.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
3
2016-02-24T09:22:16.000Z
2021-04-06T03:04:21.000Z
include/cql/exceptions/cql_query_timeout_exception.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
null
null
null
include/cql/exceptions/cql_query_timeout_exception.hpp
ncbi/cassandra-cpp-driver
b2259e9b13849c98fc6b6485f2433c97c1fa4b9f
[ "Apache-2.0" ]
6
2015-04-26T07:16:44.000Z
2020-11-23T06:31:07.000Z
/* * File: cql_query_timeout_exception.hpp * Author: mc * * Created on September 16, 2013, 9:53 AM */ #ifndef CQL_QUERY_TIMEOUT_EXCEPTION_H_ #define CQL_QUERY_TIMEOUT_EXCEPTION_H_ #include "cql/cql.hpp" #include "cql/exceptions/cql_query_execution_exception.hpp" namespace cql { // A Cassandra timeout during a query. Such an exception is returned when the // query has been tried by Cassandra but cannot be achieved with the requested // consistency level within the rpc timeout set for Cassandra. class CQL_EXPORT cql_query_timeout_exception: public cql_query_execution_exception { public: cql_query_timeout_exception( const char* message, cql_consistency_enum consistency_level, cql_int_t received, cql_int_t required) : cql_query_execution_exception(message), _consistency(consistency_level), _recv_acknowledgements(received), _req_acknowledgements(required) { } cql_query_timeout_exception( const std::string& message, cql_consistency_enum consistency_level, cql_int_t received, cql_int_t required) : cql_query_execution_exception(message), _consistency(consistency_level), _recv_acknowledgements(received), _req_acknowledgements(required) { } // Gets the number of replica that had acknowledged/responded to the operation before it time outed. cql_int_t received_acknowledgements() const { return _recv_acknowledgements; } // Gets the minimum number of replica acknowledgments/responses that were required to fulfill the operation. cql_int_t required_acknowledgements() const { return _req_acknowledgements; } // Gets the consistency level of the operation that time outed. cql_consistency_enum consistency_level() const { return _consistency; } private: cql_consistency_enum _consistency; cql_int_t _recv_acknowledgements; cql_int_t _req_acknowledgements; }; } #endif /* CQL_QUERY_TIMEOUT_EXCEPTION_H_ */
29.342857
113
0.735151
ncbi
88133ebd9a4152b13aadee1838ae12ed8006217b
645
cpp
C++
leetcode.com/0024 Swap Nodes in Pairs/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0024 Swap Nodes in Pairs/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0024 Swap Nodes in Pairs/better.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <iostream> using namespace std; // Definition for singly-linked list. struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode sentinel(0); ListNode* top = &sentinel; top->next = head; ListNode* item1; ListNode* item2; while((item1 = top->next) && (item2 = top->next->next)) { top->next = item1->next; item1->next = item2->next; item2->next = item1; top = item2->next; } return sentinel.next; } };
20.806452
65
0.541085
sky-bro
8817a8f8e7104a76c3ff5556291661b26953b798
56
cpp
C++
test/engine/assets/test_data_factory.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
1
2018-10-20T22:08:59.000Z
2018-10-20T22:08:59.000Z
test/engine/assets/test_data_factory.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
test/engine/assets/test_data_factory.cpp
invaderjon/gdev
3f5c5da22160c4980afd6099b0b4e06fdf106204
[ "Apache-2.0" ]
null
null
null
// test_data_factory.cpp #include "test_data_factory.h"
18.666667
30
0.803571
invaderjon
8817cc614926aaf771444b44b68a2f30c0e95732
5,933
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/pmetricsCheck.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/pmetricsCheck.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/torsten/PKModel/pmetricsCheck.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_TORSTEN_PKMODEL_PMETRICSCHECK_HPP #define STAN_MATH_TORSTEN_PKMODEL_PMETRICSCHECK_HPP #include <Eigen/Dense> #include <stan/math/torsten/PKModel/pmxModel.hpp> #include <stan/math/prim/scal/err/invalid_argument.hpp> #include <boost/lexical_cast.hpp> #include <vector> #include <string> #include <iostream> namespace torsten { /** * Checks that the arguments the user inputs in the Torsten * functions are valid. * * @tparam T0 type of scalar for time of events. * @tparam T1 type of scalar for amount at each event. * @tparam T2 type of scalar for rate at each event. * @tparam T3 type of scalar for inter-dose inteveral at each event. * @tparam T4 type of scalar for model parameters * @tparam T5 type of scalar for bio-variability * @tparam T6 type of scalar for lag times * @param[in] time times of events * @param[in] amt amount at each event * @param[in] rate rate at each event * @param[in] ii inter-dose interval at each event * @param[in] evid event identity: * (0) observation * (1) dosing * (2) other * (3) reset * (4) reset AND dosing * @param[in] cmt compartment number at each event * @param[in] addl additional dosing at each event * @param[in] ss steady state approximation at each event (0: no, 1: yes) * @param[in] pMatrix parameters at each event * @param[in] bio-variability at each event * @param[in] lag times at each event * @param[in] function The name of the function for which the check is being * performed. * @param[in] model object that contains basic structural information about * a compartment model. * @return void * */ template <typename T0, typename T1, typename T2, typename T3, typename T4, typename T5, typename T6> void pmetricsCheck(const std::vector<T0>& time, const std::vector<T1>& amt, const std::vector<T2>& rate, const std::vector<T3>& ii, const std::vector<int>& evid, const std::vector<int>& cmt, const std::vector<int>& addl, const std::vector<int>& ss, const std::vector<std::vector<T4> >& pMatrix, const std::vector<std::vector<T5> >& biovar, const std::vector<std::vector<T6> >& tlag, const char* function) { using std::vector; using std::string; using Eigen::Dynamic; using stan::math::invalid_argument; if (!(time.size() > 0)) invalid_argument(function, "length of time vector,", time.size(), "", "needs to be positive and greater than 0!"); std::string message = ", but must be the same as the length of the time array: " // NOLINT + boost::lexical_cast<string>(time.size()) + "!"; const char* length_error = message.c_str(); if (!(amt.size() == time.size())) invalid_argument(function, "the length of the amount (amt) array is", amt.size(), "", length_error); if (!(rate.size() == time.size())) invalid_argument(function, "the length of the rate array is", rate.size(), "", length_error); if (!(evid.size() == time.size())) invalid_argument(function, "the length of the event ID (evid) array is", evid.size(), "", length_error); if (!(cmt.size() == time.size())) invalid_argument(function, "the length of the compartment (cmt) array is", cmt.size(), "", length_error); std::string message2 = ", but must be either 1 or the same as the length of the time array: " // NOLINT + boost::lexical_cast<string>(time.size()) + "!"; const char* length_error2 = message2.c_str(); if (!(ii.size() == time.size()) || (ii.size() == 1)) invalid_argument( function, "the length of the interdose interval (ii) array is", ii.size(), "", length_error2); if (!(addl.size() == time.size()) || (addl.size() == 1)) invalid_argument( function, "the length of the additional dosing (addl) array is", ii.size(), "", length_error2); if (!(ss.size() == time.size()) || (ss.size() == 1)) invalid_argument( function, "the length of the steady state approximation (ss) array is", ss.size(), "", length_error2); std::string message3 = ", but must be the same as the length of the additional dosing (addl) array: " // NOLINT + boost::lexical_cast<string>(addl.size()) + "!"; const char* length_error3 = message3.c_str(); if (!(ss.size() == time.size()) || (ss.size() == 1)) invalid_argument( function, "the length of steady state approximation (ss) array is", ss.size(), "", length_error3); // TEST ARGUMENTS FOR PARAMETERS static const char* noCheck("linOdeModel"); if (strcmp(function, noCheck) != 0) { if (!((pMatrix.size() == time.size()) || (pMatrix.size() == 1))) invalid_argument(function, "length of the parameter (2d) array,", pMatrix.size(), "", length_error2); if (!(pMatrix[0].size() > 0)) invalid_argument(function, "the number of parameters per event is", pMatrix[0].size(), "", " but must be greater than 0!"); } if (!((biovar.size() == time.size()) || (biovar.size() == 1))) invalid_argument(function, "length of the biovariability parameter (2d) array,", // NOLINT biovar.size(), "", length_error2); if (!(biovar[0].size() > 0)) invalid_argument(function, "the number of biovariability parameters per event is", biovar[0].size(), "", " but must be greater than 0!"); if (!((tlag.size() == time.size()) || (tlag.size() == 1))) invalid_argument(function, "length of the lag times (2d) array,", // NOLINT tlag.size(), "", length_error2); if (!(tlag[0].size() > 0)) invalid_argument(function, "the number of lagtimes parameters per event is", tlag[0].size(), "", " but must be greater than 0!"); } } // torsten namespace #endif
42.078014
113
0.621777
yizhang-cae
881d09865a7f04e3745d0d2320dd73f01a74b727
1,944
cpp
C++
src/gotobed/EquipMask.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
1
2022-03-03T17:01:38.000Z
2022-03-03T17:01:38.000Z
src/gotobed/EquipMask.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
null
null
null
src/gotobed/EquipMask.cpp
andrelo1/gotobed-ae
9b2001e89de0ac479e9b979f01fa3a6475c8cd79
[ "MIT" ]
null
null
null
#include "EquipMask.h" namespace Gotobed { EquipMask::EquipMask(std::uint32_t a_armor, bool a_lhand, bool a_rhand, bool a_ammo, bool a_misc): armor(a_armor), lhand(a_lhand), rhand(a_rhand), ammo(a_ammo), misc(a_misc) { } EquipMask::EquipMask(std::int32_t a_obj) { if (a_obj) { auto domain = jc::domain::get(); armor = jc::JMap::getInt(domain, a_obj, "armor", 0xFFFFFFFF); lhand = jc::JMap::getInt(domain, a_obj, "lhand", 1); rhand = jc::JMap::getInt(domain, a_obj, "rhand", 1); ammo = jc::JMap::getInt(domain, a_obj, "ammo", 1); misc = jc::JMap::getInt(domain, a_obj, "misc", 1); } } bool EquipMask::operator()(const EquipList::Entry& a_entry) const { if (!a_entry.item) { return false; } switch (a_entry.item->formType.get()) { case RE::FormType::Armor: { auto slotMask = static_cast<std::uint32_t>(static_cast<RE::TESObjectARMO*>(a_entry.item)->GetSlotMask()); return (slotMask || misc) && (slotMask & armor) == slotMask; }; case RE::FormType::Ammo: { return ammo; }; case RE::FormType::Weapon: { auto dom = RE::BGSDefaultObjectManager::GetSingleton(); auto lhandSlot = dom->GetObject<RE::BGSEquipSlot>(RE::DEFAULT_OBJECTS::kLeftHandEquip); auto rhandSlot = dom->GetObject<RE::BGSEquipSlot>(RE::DEFAULT_OBJECTS::kRightHandEquip); return a_entry.slot == lhandSlot && lhand || a_entry.slot == rhandSlot && rhand; }; } return misc; } EquipMask EquipMask::operator~() const { return { ~armor, !lhand, !rhand, !ammo, !misc }; } EquipMask::operator std::int32_t() const { auto domain = jc::domain::get(); auto maskObj = jc::JMap::object(domain); jc::JMap::setInt(domain, maskObj, "armor", armor); jc::JMap::setInt(domain, maskObj, "lhand", lhand); jc::JMap::setInt(domain, maskObj, "rhand", rhand); jc::JMap::setInt(domain, maskObj, "ammo", ammo); jc::JMap::setInt(domain, maskObj, "misc", misc); return maskObj; } }
28.588235
109
0.654321
andrelo1
881e39d0888cfe2ba83e65f8d8ddcc7722144ebd
14,946
cpp
C++
Libraries/Widget/Command.cpp
jodavis42/WelderEngineRevamp
1b8776c53857e66b2c933321e965bbe12f0df61e
[ "MIT" ]
3
2022-02-11T10:34:33.000Z
2022-02-24T17:44:17.000Z
Code/Extensions/Widget/Command.cpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
Code/Extensions/Widget/Command.cpp
WelderUpdates/WelderEngineRevamp
1c665239566e9c7156926852f7952948d9286d7d
[ "MIT" ]
null
null
null
// MIT Licensed (see LICENSE.md). #include "Precompiled.hpp" namespace Zero { namespace Events { DefineEvent(CommandStateChange); DefineEvent(CommandCaptureContext); DefineEvent(CommandExecute); DefineEvent(CommandAdded); DefineEvent(CommandRemoved); DefineEvent(CommandUpdated); } // namespace Events namespace Tags { DefineTag(Command); } // namespace Tags String SeperateWords(StringParam sourceString) { if (sourceString.Empty()) return sourceString; StringBuilder output; StringRange str = sourceString.All(); // Always take the start of the string output.Append(str.Front()); str.PopFront(); while (!str.Empty()) { if (str.IsCurrentRuneUpper()) output.Append(' '); output.Append(str.Front()); str.PopFront(); } return output.ToString(); } ZilchDefineType(CommandUpdateEvent, builder, type) { } CommandUpdateEvent::CommandUpdateEvent(Command* command) : mCommand(command) { } ZilchDefineType(CommandEvent, builder, type) { ZeroBindDocumented(); ZilchBindGetterProperty(Space); } CommandEvent::CommandEvent(Object* source, CommandManager* manager) : ObjectEvent(source), mManager(manager) { } Space* CommandEvent::GetSpace() { return mManager->GetContext()->Get<Space>(); } ZilchDefineType(CommandExecuter, builder, type) { } CommandExecuter* BuildMetaCommandExecuter(StringParam executionFunction) { // Parse the function string StringTokenRange tokens(executionFunction.All(), '.'); ReturnIf(tokens.Empty(), nullptr, "Bad execution function format '%s'", executionFunction.c_str()); String object = tokens.Front(); tokens.PopFront(); ReturnIf(tokens.Empty(), nullptr, "Bad execution function format '%s'", executionFunction.c_str()); String functionName = tokens.Front(); // Find object Object* systemObject = Z::gSystemObjects->FindObject(object); ReturnIf(systemObject == nullptr, nullptr, "Failed to find system object '%s'", object.c_str()); // Find Function BoundType* metaType = ZilchVirtualTypeId(systemObject); Function* function = metaType->GetFunction(functionName); ReturnIf(function == nullptr || !function->FunctionType->Parameters.Empty(), nullptr, "Failed to find method or invalid number of parameters '%s' on '%s'", functionName.c_str(), metaType->Name.c_str()); MetaCommandExecuter* executer = new MetaCommandExecuter(); executer->mDelegate.ThisHandle = systemObject; executer->mDelegate.BoundFunction = function; return executer; } ZilchDefineType(Command, builder, type) { } Command::Command() { mExecuter = nullptr; DevOnly = false; Active = false; ReadOnly = false; } Command::~Command() { SafeDelete(mExecuter); } void Command::Serialize(Serializer& stream) { SerializeName(Name); SerializeNameDefault(Description, String()); SerializeNameDefault(IconName, String()); SerializeNameDefault(Shortcut, String()); SerializeNameDefault(Function, String()); SerializeName(Tags); SerializeNameDefault(DevOnly, false); SerializeNameDefault(ReadOnly, false); } void Command::SetActive(bool active) { Active = active; ChangeState(); } bool Command::IsActive() { return Active; } bool Command::IsEnabled() { CommandManager* commandManager = CommandManager::GetInstance(); if (mExecuter) return mExecuter->IsEnabled(this, commandManager); return true; } void Command::Execute() { CommandManager* commandManager = CommandManager::GetInstance(); CommandEvent eventToSend(this, commandManager); this->GetDispatcher()->Dispatch(Events::CommandExecute, &eventToSend); if (mExecuter) mExecuter->Execute(this, commandManager); } StringParam Command::GetDisplayName() { return DisplayName; } void Command::SetDisplayName(StringParam name) { DisplayName = SeperateWords(name); } void Command::FillOutToolTip() { // Assumes all commands must have names. if (Name.Empty()) return; if (!Description.Empty()) { if (!Shortcut.Empty()) ToolTip = String::Format("%s - %s (%s)", Name.c_str(), Description.c_str(), Shortcut.c_str()); else ToolTip = String::Format("%s - %s", Name.c_str(), Description.c_str()); } else if (!Shortcut.Empty()) { ToolTip = String::Format("%s (%s)", Name.c_str(), Shortcut.c_str()); } else // !Name.Empty() { ToolTip = String::Format("%s", Name.c_str()); } } void Command::ChangeState() { ObjectEvent toSend = ObjectEvent(this); this->GetDispatcher()->Dispatch(Events::CommandStateChange, &toSend); } void Command::ExecuteCommand() { if (Z::gEngine->IsReadOnly() && !ReadOnly) { DoNotifyWarning("Command", BuildString("Cannot execute command ", Name, " because we are in read-only mode")); return; } Execute(); } CommandSearchProvider::CommandSearchProvider() : SearchProvider("Command") { } void CommandSearchProvider::Search(SearchData& search) { DeveloperConfig* devConfig = Z::gEngine->GetConfigCog()->has(DeveloperConfig); String filterString = search.SearchString; forRange (Command* command, mCommandSet->mCommands.All()) { // Only show dev commands if dev config is present if (command->DevOnly && devConfig == nullptr) continue; FilterAddCommand(search, command); } } String CommandSearchProvider::GetElementType(SearchViewResult& element) { const String CommandName = "Command"; return CommandName; } void CommandSearchProvider::RunCommand(SearchView* searchView, SearchViewResult& element) { Command* command = (Command*)element.Data; command->ExecuteCommand(); } Composite* CommandSearchProvider::CreatePreview(Composite* parent, SearchViewResult& element) { Command* command = (Command*)element.Data; return CreateTextPreview(parent, command->Description); } void CommandSearchProvider::FilterAddCommand(SearchData& search, Command* command) { if (!CheckAndAddTags(search, command->TagList)) return; int priority = PartialMatch(search.SearchString.All(), command->Name.All(), CaseInsensitiveCompare); if (priority != cNoMatch) { SearchViewResult& result = search.Results.PushBack(); result.Data = command; result.Interface = this; result.Name = command->Name; result.Priority = priority + SearchViewResultPriority::CommandBegin; } } // MenuDefinition void MenuDefinition::Serialize(Serializer& stream) { SerializeName(Name); SerializeNameDefault(Description, String()); SerializeNameDefault(Icon, String()); SerializeName(Entries); } // Manager ZilchDefineType(CommandManager, builder, type) { ZeroBindEvent(Events::CommandExecute, CommandEvent); } CommandManager::CommandManager() { } CommandManager::~CommandManager() { DeleteObjectsInContainer(mCommands); DeleteObjectsInContainer(mMenus); } void CommandManager::LoadCommands(StringParam filename) { Status status; UniquePointer<Serializer> stream(GetLoaderStreamFile(status, filename)); if (status) { Array<Command*> commands; LoadPolymorphicSerialize("Commands", "commands", *stream, commands, this); forRange (Command* command, commands.All()) { AddCommand(command); } } else { DoNotifyStatus(status); } } void CommandManager::LoadMenu(StringParam filename) { Status status; Array<MenuDefinition*> menus; UniquePointer<Serializer> stream(GetLoaderStreamFile(status, filename)); if (status) stream->SerializeValue(menus); forRange (MenuDefinition* menuDef, menus.All()) mMenus[menuDef->Name] = menuDef; } Command* CommandManager::CreateFromName(StringParam name) { return new Command(); } Command* CommandManager::AddCommand(StringParam commandName, CommandExecuter* executer, bool readOnly) { Command* existingCommand = mNamedCommands.FindValue(commandName, nullptr); if (existingCommand) { // Command already loaded, except the binding executer. existingCommand->mExecuter = executer; existingCommand->ReadOnly = readOnly; if (existingCommand->Description.Empty()) existingCommand->Description = executer->GetDescription(); return existingCommand; } // Make a command object Command* command = new Command(); command->Name = commandName; command->mExecuter = executer; command->ReadOnly = readOnly; if (command->Description.Empty()) command->Description = executer->GetDescription(); AddCommand(command); return command; } void CommandManager::AddCommand(Command* command) { mNamedCommands[command->Name] = command; mCommands.PushBack(command); command->SetDisplayName(command->Name); command->FillOutToolTip(); BuildTagList(command); if (!command->Shortcut.Empty() && !IsShortcutReserved(command->Shortcut)) mShortcuts.Insert(command->Shortcut, command); // Build command executer from meta, if applicable. if (!command->Function.Empty()) command->mExecuter = BuildMetaCommandExecuter(command->Function); CommandUpdateEvent eventToSend(command); DispatchEvent(Events::CommandAdded, &eventToSend); } Command* CommandManager::GetCommand(StringParam name) { return mNamedCommands.FindValue(name, nullptr); } void CommandManager::RemoveCommand(Command* command) { mNamedCommands.Erase(command->Name); mShortcuts.Erase(command->Name); mCommands.EraseValueError(command); CommandUpdateEvent eventToSend(command); DispatchEvent(Events::CommandRemoved, &eventToSend); delete command; } void CommandManager::RunParsedCommandsDelayed() { if (Z::gWidgetManager->RootWidgets.Empty()) { RunParsedCommandsImmediately(); } else { // We delay running commands by one frame so that lazy tasks have had a frame to complete ActionSequence* seq = new ActionSequence(&Z::gWidgetManager->RootWidgets.Front()); seq->Add(new CallAction<CommandManager, &CommandManager::RunParsedCommandsImmediately>(this)); } } void CommandManager::RunParsedCommandsImmediately() { Environment* environment = Environment::GetInstance(); StringMap& arguments = environment->mParsedCommandLineArguments; for (StringMap::Range range = arguments.All(); !range.Empty(); range.PopFront()) { String commandName = range.Front().first; Command* command = GetCommand(commandName); if (command) { ZPrint("Executing command: %s\n", commandName.c_str()); command->ExecuteCommand(); } } } String CommandManager::BuildShortcutString(bool ctrl, bool alt, bool shift, StringParam key) { StringBuilder builder; if (ctrl) builder << "Ctrl+"; if (alt) builder << "Alt+"; if (shift) builder << "Shift+"; builder << key; return builder.ToString(); } bool CommandManager::TestCommandKeyboardShortcuts(KeyboardEvent* event) { // Do not process handled keyboard events if (event->Handled || event->Key == Keys::Unknown) return false; String shortcut = BuildShortcutString( event->CtrlPressed, event->AltPressed, event->ShiftPressed, event->mKeyboard->ToSymbol(event->Key)); // ZPrint("Shortcut %s\n", shortcutString.c_str()); Command* command = mShortcuts.FindValue(shortcut, nullptr); if (command == nullptr) return false; event->Handled = true; command->ExecuteCommand(); return true; } bool CommandManager::TestCommandCopyPasteShortcuts(ClipboardEvent* event) { if (event->mHandled) return false; // The "Cut", "Copy", and "Paste" events are special. Command* command = mShortcuts.FindValue(event->EventId, nullptr); if (command == nullptr) return false; event->mHandled = true; GetContext()->Add(event); command->ExecuteCommand(); GetContext()->Remove(ZilchVirtualTypeId(event)); return true; } bool CommandManager::IsShortcutReserved(StringParam validShortcut) { return mShortcuts.FindValue(validShortcut, nullptr) != nullptr; } bool CommandManager::IsShortcutReserved(bool ctrl, bool alt, bool shift, StringParam validKey, Command** out) { String shortcut = BuildShortcutString(ctrl, alt, shift, validKey); *out = mShortcuts.FindValue(shortcut, nullptr); return (*out != nullptr); } bool CommandManager::ClearCommandShortcut(Command* command, bool sendEvents) { if (command->Shortcut.Empty()) return false; mShortcuts.Erase(command->Shortcut); command->Shortcut.Clear(); if (sendEvents) { CommandUpdateEvent eventToSend(command); DispatchEvent(Events::CommandUpdated, &eventToSend); } return true; } bool CommandManager::UpdateCommandShortcut( StringParam commandName, bool ctrl, bool alt, bool shift, StringParam key, bool sendEvents) { if (Command* command = mNamedCommands.FindValue(commandName, nullptr)) return UpdateCommandShortcut(command, ctrl, alt, shift, key, sendEvents); return false; } bool CommandManager::UpdateCommandShortcut( Command* command, bool ctrl, bool alt, bool shift, StringParam key, bool sendEvents) { String shortcut = BuildShortcutString(ctrl, alt, shift, key); // Supplied shortcut is already set on this command, do nothing. if (command->Shortcut == shortcut) return false; mShortcuts.Erase(command->Shortcut); command->Shortcut = shortcut; mShortcuts.Insert(shortcut, command); if (sendEvents) { CommandUpdateEvent eventToSend(command); DispatchEvent(Events::CommandUpdated, &eventToSend); } return true; } bool CommandManager::UpdateCommandTags(StringParam commandName, StringParam tags, bool sendEvents) { if (Command* command = mNamedCommands.FindValue(commandName, nullptr)) return UpdateCommandTags(command, tags); return false; } bool CommandManager::UpdateCommandTags(Command* command, StringParam tags, bool sendEvents) { if (command->Tags == tags) return false; command->Tags = tags; command->TagList.Clear(); // Build all tags for this command StringTokenRange tokens(command->Tags.c_str(), ' '); for (; !tokens.Empty(); tokens.PopFront()) { String tag = tokens.Front(); command->TagList.Insert(tag); } if (sendEvents) { CommandUpdateEvent eventToSend(command); DispatchEvent(Events::CommandUpdated, &eventToSend); } return true; } SearchProvider* CommandManager::GetCommandSearchProvider() { CommandSearchProvider* commandCompletion = new CommandSearchProvider(); commandCompletion->mCommandSet = this; return commandCompletion; } void CommandManager::BuildTagList(Command* command) { // Build all tags for this command StringTokenRange tokens(command->Tags.c_str(), ' '); for (; !tokens.Empty(); tokens.PopFront()) { String tag = tokens.Front(); command->TagList.Insert(tag); } } void CommandManager::ValidateCommands() { forRange (Command* command, mCommands.All()) { if (command->mExecuter) continue; if (command->GetDispatcher()->IsAnyConnected(Events::CommandExecute)) continue; ErrorIf(true, "Command not valid %s", command->Name.c_str()); } } Context* CommandManager::GetContext() { return &mContext; } ZilchDefineType(CommandCaptureContextEvent, builder, type) { } } // namespace Zero
24.262987
114
0.723003
jodavis42
881fd5ca6281a2843a492fc9390cac2ffbb44cf9
166
hpp
C++
examples/16_multiple_animations_and_render_flipping/ECS/Animation.hpp
nathandaven/sdl-vscode-template
098125e250ede58eeaa6cd06738d76c2983cdb58
[ "MIT" ]
null
null
null
examples/16_multiple_animations_and_render_flipping/ECS/Animation.hpp
nathandaven/sdl-vscode-template
098125e250ede58eeaa6cd06738d76c2983cdb58
[ "MIT" ]
null
null
null
examples/16_multiple_animations_and_render_flipping/ECS/Animation.hpp
nathandaven/sdl-vscode-template
098125e250ede58eeaa6cd06738d76c2983cdb58
[ "MIT" ]
null
null
null
struct Animation { int index; int frames; int speed; Animation() {} Animation(int i, int f, int s) { index = i; frames = f; speed = s; } };
11.857143
32
0.536145
nathandaven
8825c1b89fc59404b12bb81fc505e24571f21756
3,477
cpp
C++
gm/imagesource2.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
10
2017-12-04T10:41:55.000Z
2021-12-03T07:36:59.000Z
gm/imagesource2.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
5
2022-01-03T13:41:38.000Z
2022-03-02T13:01:38.000Z
gm/imagesource2.cpp
borodust/skia
bbbf1a7f50a303bd76163793bd5968c72f5f4432
[ "BSD-3-Clause" ]
17
2017-11-05T21:36:53.000Z
2021-05-22T20:33:51.000Z
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm/gm.h" #include "include/core/SkCanvas.h" #include "include/core/SkColor.h" #include "include/core/SkFilterQuality.h" #include "include/core/SkImage.h" #include "include/core/SkImageFilter.h" #include "include/core/SkPaint.h" #include "include/core/SkRect.h" #include "include/core/SkRefCnt.h" #include "include/core/SkScalar.h" #include "include/core/SkSize.h" #include "include/core/SkString.h" #include "include/core/SkSurface.h" #include "include/core/SkTypes.h" #include "include/effects/SkImageFilters.h" namespace skiagm { // This GM reproduces the issue in crbug.com/472795. The SkImageSource image // is shifted for high quality mode between cpu and gpu. class ImageSourceGM : public GM { public: ImageSourceGM(const char* suffix, const SkSamplingOptions& sampling) : fSuffix(suffix), fSampling(sampling) { this->setBGColor(0xFFFFFFFF); } protected: SkString onShortName() override { SkString name("imagesrc2_"); name.append(fSuffix); return name; } SkISize onISize() override { return SkISize::Make(256, 256); } // Create an image with high frequency vertical stripes void onOnceBeforeDraw() override { constexpr SkPMColor gColors[] = { SK_ColorRED, SK_ColorGRAY, SK_ColorGREEN, SK_ColorGRAY, SK_ColorBLUE, SK_ColorGRAY, SK_ColorCYAN, SK_ColorGRAY, SK_ColorMAGENTA, SK_ColorGRAY, SK_ColorYELLOW, SK_ColorGRAY, SK_ColorWHITE, SK_ColorGRAY, }; auto surface(SkSurface::MakeRasterN32Premul(kImageSize, kImageSize)); SkCanvas* canvas = surface->getCanvas(); int curColor = 0; for (int x = 0; x < kImageSize; x += 3) { SkRect r = SkRect::MakeXYWH(SkIntToScalar(x), SkIntToScalar(0), SkIntToScalar(3), SkIntToScalar(kImageSize)); SkPaint p; p.setColor(gColors[curColor]); canvas->drawRect(r, p); curColor = (curColor+1) % SK_ARRAY_COUNT(gColors); } fImage = surface->makeImageSnapshot(); } void onDraw(SkCanvas* canvas) override { const SkRect srcRect = SkRect::MakeLTRB(0, 0, SkIntToScalar(kImageSize), SkIntToScalar(kImageSize)); const SkRect dstRect = SkRect::MakeLTRB(0.75f, 0.75f, 225.75f, 225.75f); SkPaint p; p.setImageFilter(SkImageFilters::Image(fImage, srcRect, dstRect, fSampling)); canvas->saveLayer(nullptr, &p); canvas->restore(); } private: static constexpr int kImageSize = 503; SkString fSuffix; SkSamplingOptions fSampling; sk_sp<SkImage> fImage; using INHERITED = GM; }; ////////////////////////////////////////////////////////////////////////////// DEF_GM(return new ImageSourceGM("none", SkSamplingOptions());) DEF_GM(return new ImageSourceGM("low", SkSamplingOptions(SkFilterMode::kLinear));) DEF_GM(return new ImageSourceGM("med", SkSamplingOptions(SkFilterMode::kLinear, SkMipmapMode::kLinear));) DEF_GM(return new ImageSourceGM("high", SkSamplingOptions({1/3.0f, 1/3.0f}));) } // namespace skiagm
33.114286
85
0.618349
borodust
882606cebda081e19d82763690029d618de76d32
22,920
cpp
C++
dbcore/sm-log-file.cpp
ermia-db/ermia
558c254b32d70a934d8c2d35f32f170ec6c05be8
[ "MIT" ]
50
2016-02-03T19:36:19.000Z
2020-06-28T02:50:53.000Z
dbcore/sm-log-file.cpp
ermia-db/ermia
558c254b32d70a934d8c2d35f32f170ec6c05be8
[ "MIT" ]
5
2016-08-15T13:03:39.000Z
2018-02-22T15:22:02.000Z
dbcore/sm-log-file.cpp
ermia-db/ermia
558c254b32d70a934d8c2d35f32f170ec6c05be8
[ "MIT" ]
18
2016-02-04T02:40:14.000Z
2019-08-29T03:29:43.000Z
#include "sm-config.h" #include "sm-log-file.h" #include "rcu.h" #include <new> #include <sys/fcntl.h> #include <algorithm> namespace ermia { #warning Crash durability is NOT fully guaranteed by this implementation /* ^^^ I know that sounds bad, but it turns out this is a fiendishly difficult thing to make bulletproof. The reasons are twofold: 1. POSIX makes no guarantees that fsync actually does anything, and in fact explicitly allows a no-op. Mac OS X is a known offender. The implications should be obvious. 2. POSIX makes no guarantees about when data reaches disk, in particular vs. the metadata that describe it. Few file systems specify this either (ext3 is the only one I know of, and then only if you mount in ordered data mode). Even if fysnc works, it only guarantees that certain data *have* reached disk. There's no way to request that certain data *not* reach disk quite yet. This implementation does take several measures to avoid the worst problems, though: 1. The most important files are empty. Few decent filesystems will corrupt file names operations on crash, because metadata changes are journaled. We call fsync on the directory fd after all file-name operations. 2. We create each new log segment as soon as the system starts using its predecessor. That gives a much wider time window for things to reach disk, in the event of a crash. Once the system starts using a segment, it renames the file. The file's contents should be unaffected by the rename, however, and we redo the rename during recovery if necessary. 3. File descriptors are opened with O_SYNC, so all writes should go do disk immediately. There's also some evidence (on linux at least) that it's significantly faster than calling fsync separately. It's not clear whether O_SYNC is useful on systems where fsync is a no-op, however. 4. When there should only be one of a file (checkpoint, durable mark), we rename rather than creating and deleting. POSIX requires the rename operation to be atomic at runtime, and a journalling file system makes it extremely likely that it will also be atomic across a crash (though the change may be lost if the relevant journal entries weren't durable yet). */ /* Segments need to be large enough that we can actually fit a reasonable number of log records in them, but small enough that we can test them easily. Enforce the segment alignment given here, by fiat. */ static size_t const LOG_SEGMENT_ALIGN = 1024; struct dmark_file_name { char buf[CHKPT_FILE_NAME_BUFSZ]; dmark_file_name(LSN start) { size_t n = os_snprintf(buf, sizeof(buf), DURABLE_FILE_NAME_FMT, start._val); ASSERT(n < sizeof(buf)); } operator char const *() { return buf; } char const *operator*() { return buf; } }; void sm_log_file_mgr::create_segment_file(segment_id *sid) { ALWAYS_ASSERT(config::is_backup_srv()); nxt_seg_file_name oldname(sid->segnum); segment_file_name newname(sid); os_renameat(dfd, oldname, dfd, newname); os_fsync(dfd); nxt_seg_file_name sname(sid->segnum + 1); uint64_t fd = os_openat(dfd, sname, O_CREAT | O_EXCL | O_RDONLY); nxt_segment_fd = (fd << 32) | (sid->segnum + 1); } segment_id *sm_log_file_mgr::_oldest_segment() { return segments[volatile_read(oldest_segnum)]; } segment_id *sm_log_file_mgr::_newest_segment() { return volatile_read(active_segment); } void sm_log_file_mgr::_pop_oldest() { ASSERT(oldest_segnum < _newest_segment()->segnum); auto *sid = _oldest_segment(); os_close(sid->fd); sid->fd = -1; RCU::rcu_free(sid); segments[oldest_segnum] = NULL; oldest_segnum++; } void sm_log_file_mgr::_pop_newest() { ASSERT(oldest_segnum < _newest_segment()->segnum); segment_id *sid = _newest_segment(); segments[sid->segnum] = NULL; active_segment = segments[sid->segnum - 1]; os_close(sid->fd); sid->fd = -1; RCU::rcu_free(sid); } sm_log_file_mgr::segment_array::segment_array() { segment_id *sd = NULL; std::fill(arr, arr + NUM_LOG_SEGMENTS, sd); } sm_log_file_mgr::segment_array::~segment_array() { /* Free segment ids and close all file handles. Do *not* delete the files. Technically, we should wait to close files until RCU has reclaimed the sid---otherwise, the system might recycle the just-closed fd and a straggler who intends to access the original file will get the new one instead. However, we won't worry about it because any straggler that tries to access the old file after it has been discarded is likely to break things regardless of which file it accesses in the end! */ for (auto &sid : arr) { if (sid) { os_close(sid->fd); sid->fd = -1; } } } /* The log consists of 18 files: Sixteen log segment files, of the form log-$SEGNO-$BEGIN-$END. Each segment's name encodes the segment number, as well as the range of LSN offsets that map to it (some LSN offsets do not map to any segment). The file contains up to $END-$BEGIN bytes of data. One durable marker, an emtpy file named durable-$LSN. The writer periodically renames this file to reflect the latest known-durable LSN. The system can start verifying checksums at this point when searching for end-of-log (the file system is responsible for dealing with media errors). One checkpoint marker, an empty file named checkpoint-$BEGIN-$END. Whenever a new checkpoint is confirmed to be durable, the checkpoint code renames this file to point to it. The actual checkpoint data reside at $END, but recovery starts from $BEGIN. A checkpoint is just a special transaction: 1. Consisting of "updates" to all OID tables and allocators in the system, such that every change preceding the start LSN is accounted for (changes after may or may not be accounted for). 2. Whose commit block is wrapped in a "skip" record (similar to an overflow block) and invisible to a normal log scan. 3. Identified by the checkpoint marker file that tells the system where to find the checkpoint transaction, and also identifies the LSN from which recovery should begin. Log bootstrap does three things: 1. Verify that directory [dname] contains (only) valid log files 2. Find the most recent log checkpoint from which to begin recovery 3. Find the end of the log, truncating torn records if necessary If [dname] is empty, create a new (empty) log there. Otherwise, use on-disk data to initialize in-memory log structures. Either way, return the checkpoint and start LSN to the caller so they can begin recovery. */ /* Create a new log in directory [dir_name]. The caller must ensure that the directory exists and is empty. */ void sm_log_file_mgr::_make_new_log() { // create and open the first segment file uint32_t segnum = oldest_segnum = 1; nxt_segment_fd = 0; _create_nxt_seg_file(true); auto *sid = active_segment = _prepare_new_segment(segnum, 0, 0); /* Prime the segment with an empty checkpoint All checkpoints are nested inside the payload of a skip block; in our case the checkpoint itself is *also* a skip block. */ union LOG_ALIGN { char buf[OFFSETOF(log_block, records[0].data[MIN_LOG_BLOCK_SIZE])]; log_block b; }; auto fill_skip_block = [](log_block *b, LSN lsn, size_t payload_size) { b->nrec = 0; b->lsn = lsn; size_t blocksz = log_block::size(0, payload_size); LSN next_lsn = lsn.advance_within_segment(blocksz); fill_skip_record(b->records, next_lsn, payload_size, payload_size); }; // fill both blocks _chkpt_start_lsn = sid->make_lsn(0); fill_skip_block(&b, _chkpt_start_lsn, MIN_LOG_BLOCK_SIZE); log_block *b2 = (log_block *)b.payload(0); _chkpt_end_lsn = b.payload_lsn(0); fill_skip_block(b2, _chkpt_end_lsn, 0); // compute inner checksum first (outer depends on it) b2->checksum = b2->full_checksum(); b.checksum = b.full_checksum(); // write out the block int fd = open_for_write(sid); DEFER(os_close(fd)); os_pwrite(fd, buf, sizeof(buf), 0); _durable_lsn = b.next_lsn(); // create the checkpoint and durable mark files os_truncateat(dfd, cmark_file_name(_chkpt_start_lsn, _chkpt_end_lsn)); os_truncateat(dfd, dmark_file_name(_durable_lsn)); os_fsync(dfd); } sm_log_file_mgr::sm_log_file_mgr() { set_segment_size(config::log_segment_mb * config::MB); /* The code below does not close open segment file descriptors if anything goes wrong. There is no meaningful way to recover from a log bootstrap failure, so we would expect execution to terminate soon anyway should such a failure occur. There are also some log_segment_desc leaks. */ bool durable_found = false; bool chkpt_found = false; bool nxt_seg_found = false; std::vector<segment_id *> tmp; dirent_iterator dir(config::log_dir.c_str()); dfd = dir.dup(); for (char const *fname : dir) { switch (fname[0]) { case '.': { // skip files matching .* continue; } case 'c': { // allowed: one checkpoint marker char canary; int n = sscanf(fname, CHKPT_FILE_NAME_FMT "%c", &_chkpt_start_lsn._val, &_chkpt_end_lsn._val, &canary); if (n == 2) { // valid checkpoint marker file name THROW_IF(chkpt_found, log_file_error, "Multiple log checkpoint markers found"); THROW_IF(not(_chkpt_start_lsn < _chkpt_end_lsn), log_file_error, "Corrupt checkpoint marker: %s", fname); THROW_IF(not is_aligned(_chkpt_start_lsn.offset()), log_file_error, "Misaligned checkpoint start: %zx", size_t(_chkpt_start_lsn.offset())); THROW_IF(not is_aligned(_chkpt_end_lsn.offset()), log_file_error, "Misaligned checkpoint end: %zx", size_t(_chkpt_end_lsn.offset())); chkpt_found = true; continue; } break; } case 'd': { // allowed: one durability marker char canary; int n = sscanf(fname, DURABLE_FILE_NAME_FMT "%c", &_durable_lsn._val, &canary); if (n == 1) { // valid durability marker THROW_IF(durable_found, log_file_error, "Multiple durable markers found"); THROW_IF(not is_aligned(_durable_lsn.offset()), log_file_error, "Misaligned durable marker: %zx", size_t(_durable_lsn.offset())); durable_found = true; continue; } break; } case 'l': { // allowed: log segment char canary; segment_id *sid = RCU::rcu_alloc(); DEFER_UNLESS(success, RCU::rcu_free(sid)); int n = sscanf(fname, SEGMENT_FILE_NAME_FMT "%c", &sid->segnum, &sid->start_offset, &sid->end_offset, &canary); if (n == 3) { THROW_IF(not is_aligned(sid->start_offset), log_file_error, "Misaligned start for log segment %u: %zx", sid->segnum, size_t(sid->start_offset)); size_t ssize = sid->end_offset - sid->start_offset; THROW_IF(not is_aligned(ssize, LOG_SEGMENT_ALIGN), log_file_error, "Invalid size for log segment %u: %zx", sid->segnum, ssize); /* During recovery/startup, segments are added to the list out of order (we sort later) and with byte offset zero. The latter works because exactly one segment will be writable once startup completes, and the possibility of a hole in the log means we don't know yet which segment that will be. */ sid->byte_offset = 0; sid->fd = os_openat(dfd, fname, O_RDONLY); tmp.push_back(sid); success = true; continue; } break; } case 'n': { // allowed: new log segment file char canary; uint32_t segnum; int n = sscanf(fname, NXT_SEG_FILE_NAME_FMT "%c", &segnum, &canary); if (n == 1) { THROW_IF(nxt_seg_found, log_file_error, "Multiple new segments found"); uint64_t fd = os_openat(dfd, fname, O_RDONLY); nxt_segment_fd = (fd << 32) | segnum; nxt_seg_found = true; continue; } break; } case 'o': { // OID array chkpt file continue; } case 'r': { // Background async replay bounds file continue; } case 'm': { // Command log. TODO(tzwang): recovery continue; } default: break; } // we only get here if we hit a bad file name throw log_file_error("Invalid log file name `%s'", fname); } // Empty/missing log? if (tmp.empty()) { THROW_IF(chkpt_found or durable_found or nxt_seg_found, log_file_error, "Found checkpoint, durable marker and/or new segment file, but no " "log segments"); _make_new_log(); sm_log::need_recovery = false; return; } sm_log::need_recovery = true; THROW_IF(tmp.size() > NUM_LOG_SEGMENTS, log_file_error, "Log directory contains too many segment files: %zd", tmp.size()); THROW_IF(not chkpt_found, log_file_error, "Found log segments, but no checkpoint marker"); THROW_IF(not durable_found, log_file_error, "Found log segments, but no durable marker"); /* Now we have a list of segments and markers. Sort the checkpoints into their proper order (newest first) and cross-check with the checkpoint and durable markers. */ auto ssort = [](segment_id *a, segment_id *b) { THROW_IF(a->segnum == b->segnum, log_file_error, "Duplicate log segment files for segment %u", a->segnum); return a->segnum < b->segnum; }; std::sort(tmp.begin(), tmp.end(), ssort); auto *slo = tmp.front(); auto *shi = tmp.back(); THROW_IF(shi->segnum - slo->segnum != tmp.size() - 1, log_file_error, "Found gap(s) in the log segment file sequence"); oldest_segnum = slo->segnum; active_segment = shi; for (auto *sid : tmp) segments[sid->segnum] = sid; /* Validate checkpoint and durable LSN */ THROW_IF(_durable_lsn.offset() < slo->start_offset, log_file_error, "Durable marker before first log segment"); THROW_IF(shi->end_offset < _durable_lsn.offset(), log_file_error, "Durable marker after last log segment"); THROW_IF(_chkpt_start_lsn.offset() < slo->start_offset, log_file_error, "Checkpoint before first log segment"); THROW_IF(shi->end_offset < _chkpt_end_lsn.offset(), log_file_error, "Checkpoint end after last log segment"); if (nxt_seg_found) { /* Make sure the segment numbers agree */ THROW_IF(uint32_t(nxt_segment_fd) != shi->segnum + 1, log_file_error, "Wrong segment number for new segment file: %u (should be %u)", uint32_t(nxt_segment_fd), shi->segnum + 1); } else { /* Crash must have happened between opening of one segment and creation of the new file for the next. Schedule its creation. */ nxt_segment_fd = shi->segnum; } } /* Set the segment size, forcing to the log segment's minimum alignment */ void sm_log_file_mgr::set_segment_size(size_t ssize) { ASSERT(ssize > 0); segment_size = align_up(ssize, LOG_SEGMENT_ALIGN); } /* We try to keep a segment file ready to go at all times in order to allow a latch-free segment change (the fd is already open and usable by the time the atomic CAS completes). However, once a new segment file has actually been activated, we need to rename it fairly quickly to follow the normal log segment naming convention... and create a new segment file for the next segment so the cycle can repeat. */ void sm_log_file_mgr::_create_nxt_seg_file(bool force) { uint32_t segnum = uint32_t(nxt_segment_fd) + 1; bool doit = force; if (not doit) { segment_id *sid = _newest_segment(); if (uint32_t(nxt_segment_fd) == sid->segnum) { ASSERT(segnum == sid->segnum + 1); segments[sid->segnum] = sid; // The backup will create the real file after it got the // correct begin_offset value. if (config::is_backup_srv() && !config::command_log) { return; } nxt_seg_file_name oldname(sid->segnum); segment_file_name newname(sid); os_renameat(dfd, oldname, dfd, newname); os_fsync(dfd); doit = true; } } if (doit) { ALWAYS_ASSERT(!config::is_backup_srv() || config::command_log); nxt_seg_file_name sname(segnum); uint64_t fd = os_openat(dfd, sname, O_CREAT | O_EXCL | O_RDONLY); nxt_segment_fd = (fd << 32) | segnum; } } void sm_log_file_mgr::update_durable_mark(LSN dlsn) { file_mutex.lock(); DEFER(file_mutex.unlock()); _create_nxt_seg_file(false); ASSERT(_durable_lsn < dlsn); ASSERT(_oldest_segment()->start_offset <= dlsn.offset()); ASSERT(dlsn.offset() < _newest_segment()->end_offset); dmark_file_name oldname(_durable_lsn), newname(dlsn); os_renameat(dfd, oldname, dfd, newname); os_fsync(dfd); _durable_lsn = dlsn; } void sm_log_file_mgr::update_chkpt_mark(LSN cstart, LSN cend) { file_mutex.lock(); DEFER(file_mutex.unlock()); _create_nxt_seg_file(false); ASSERT(_chkpt_end_lsn < _durable_lsn); ASSERT(_chkpt_end_lsn < cstart); ASSERT(cstart < cend); ASSERT(_oldest_segment()->start_offset <= cstart.offset()); ASSERT(cend.offset() < _newest_segment()->end_offset); cmark_file_name oldname(_chkpt_start_lsn, _chkpt_end_lsn), newname(cstart, cend); os_renameat(dfd, oldname, dfd, newname); os_fsync(dfd); _chkpt_start_lsn = cstart; _chkpt_end_lsn = cend; } int sm_log_file_mgr::open_for_write(segment_id *sid) { file_mutex.lock(); DEFER(file_mutex.unlock()); _create_nxt_seg_file(false); segment_file_name sname(sid); return os_openat(dfd, sname, O_WRONLY | O_SYNC); } int sm_log_file_mgr::open_for_read(segment_id *sid) { file_mutex.lock(); DEFER(file_mutex.unlock()); _create_nxt_seg_file(false); segment_file_name sname(sid); return os_openat(dfd, sname, O_RDONLY | O_SYNC); } segment_id *sm_log_file_mgr::prepare_new_segment(uint64_t start) { auto *psid = _newest_segment(); if (start + MIN_LOG_BLOCK_SIZE < psid->end_offset) return 0; auto pssize = psid->end_offset - psid->start_offset; return _prepare_new_segment(psid->segnum + 1, start, psid->byte_offset + pssize); } segment_id *sm_log_file_mgr::_prepare_new_segment(uint32_t segnum, uint64_t start, uint64_t byte_offset) { /* In order to avoid I/O on the critical path, we rely on a daemon thread to have created a special "new segment" file and opened the appropriate file descriptors. Once a new segment is actually created, the daemon will rename the file to match the normal convention and create a "new segment" file for the next segment. If the new segment file is not ready yet, then we have to do the work manually, on the critical path. */ auto *sid = segments[segnum]; THROW_IF(sid and sid->segnum != segnum, log_is_full); auto fd_info = volatile_read(nxt_segment_fd); if (uint32_t(fd_info) < segnum) { // segment file isn't ready yet file_mutex.lock(); DEFER(file_mutex.unlock()); _create_nxt_seg_file(false); fd_info = volatile_read(nxt_segment_fd); ASSERT(segnum <= uint32_t(fd_info)); } if (uint32_t(fd_info) > segnum) return 0; // lost the race ASSERT(uint32_t(fd_info) == segnum); int fd = fd_info >> 32; auto end = start + volatile_read(segment_size); return RCU::rcu_new(fd, segnum, start, end, byte_offset); } bool sm_log_file_mgr::create_segment(segment_id *sid) { DEFER_UNLESS(success, RCU::rcu_free(sid)); auto *psid = _newest_segment(); if (sid->segnum == psid->segnum + 1) { ASSERT(psid->end_offset <= sid->start_offset + MIN_LOG_BLOCK_SIZE); /* Looks good so far! */ auto *nsid = __sync_val_compare_and_swap(&active_segment, psid, sid); if (nsid == psid) { success = true; ALWAYS_ASSERT(!segments[sid->segnum % NUM_LOG_SEGMENTS]); // Put the segment in the array - basically just for backup to continously // redo logs received which could generate new segments. volatile_write(segments[sid->segnum % NUM_LOG_SEGMENTS], sid); DLOG(INFO) << "Created segment " << sid->segnum << " fd=" << sid->fd << " " << sid->start_offset; return true; } } return false; } void sm_log_file_mgr::truncate_after(uint32_t segnum, uint64_t new_end) { file_mutex.lock(); DEFER(file_mutex.unlock()); THROW_IF(segnum < _oldest_segment()->segnum, illegal_argument, "Attempt to truncate beginning of log"); again: auto *sid = _newest_segment(); segment_file_name sname(sid); if (segnum < sid->segnum) { THROW_IF(sid->start_offset <= _chkpt_end_lsn.offset(), illegal_argument, "Attempt to truncate most recent checkpoint"); THROW_IF(sid->start_offset <= _durable_lsn.offset(), illegal_argument, "Attempt to truncate durable mark"); os_unlinkat(dfd, sname); _pop_newest(); goto again; } if (uint32_t(nxt_segment_fd) > segnum + 1) { // fun: replace those curlies with parens => compiler error nxt_seg_file_name sname{uint32_t(nxt_segment_fd)}; os_unlinkat(dfd, sname); nxt_segment_fd = segnum; _create_nxt_seg_file(true); } THROW_IF(new_end < sid->start_offset, log_file_error, "Truncation offset %zd precedes start of segment %d", size_t(new_end), segnum); THROW_IF(sid->end_offset < new_end, log_file_error, "Truncation offset %zd past end of segment %d", size_t(new_end), segnum); os_truncateat(dfd, sname, new_end - sid->start_offset); os_fsync(dfd); } void sm_log_file_mgr::reclaim_before(uint32_t segnum) { file_mutex.lock(); DEFER(file_mutex.unlock()); THROW_IF(_newest_segment()->segnum < segnum, illegal_argument, "Attempt to reclaim end of log"); again: auto *sid = _oldest_segment(); if (sid->segnum < segnum) { THROW_IF(_durable_lsn.offset() < sid->end_offset, illegal_argument, "Attempt to reclaim durable mark"); THROW_IF(_chkpt_start_lsn.offset() < sid->end_offset, illegal_argument, "Attempt to reclaim most recent checkpoint"); segment_file_name sname(sid); os_unlinkat(dfd, sname); _pop_oldest(); goto again; } os_fsync(dfd); } } // namespace ermia
35.045872
80
0.670244
ermia-db
88292e605f19fa3eda5bb7e58dbb4ebb26a91ce6
1,090
cc
C++
source/graphics_reps/pyG4Colour.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
6
2021-08-08T08:40:13.000Z
2022-03-23T03:05:15.000Z
source/graphics_reps/pyG4Colour.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-12-01T14:38:06.000Z
2022-02-10T11:28:28.000Z
source/graphics_reps/pyG4Colour.cc
yu22mal/geant4_pybind
ff7efc322fe53f39c7ae7ed140861052a92479fd
[ "Unlicense" ]
3
2021-07-16T13:57:34.000Z
2022-02-07T11:17:19.000Z
#include <pybind11/operators.h> #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <G4Color.hh> #include <G4Colour.hh> #include <limits> #include "typecast.hh" #include "opaques.hh" namespace py = pybind11; void export_G4Colour(py::module &m) { py::class_<G4Colour>(m, "G4Colour", "colour class") .def(py::init<>()) .def(py::init<G4double>()) .def(py::init<G4double, G4double>()) .def(py::init<G4double, G4double, G4double>()) .def(py::init<G4double, G4double, G4double, G4double>()) .def(py::init<G4ThreeVector>()) .def("GetRed", &G4Colour::GetRed) .def("GetGreen", &G4Colour::GetGreen) .def("GetBlue", &G4Colour::GetBlue) .def("GetAlpha", &G4Colour::GetAlpha) .def( "__str__", [](const G4Colour &self) { std::stringstream ss; ss << std::setprecision(std::numeric_limits<G4double>::digits10 + 1) << self; return ss.str(); }, py::is_operator()) .def(py::self != py::self); m.attr("G4Color") = m.attr("G4Colour"); }
24.772727
89
0.588991
yu22mal
88293be9be9f4f5941dc13953afc48bf554acd6a
8,895
cc
C++
lite/kernels/nnadapter/bridges/elementwise_ops.cc
fuaq/Paddle-Lite
56e1239410d976842fc6f7792de13c9d007d253f
[ "Apache-2.0" ]
1
2021-07-12T10:46:19.000Z
2021-07-12T10:46:19.000Z
lite/kernels/nnadapter/bridges/elementwise_ops.cc
fuaq/Paddle-Lite
56e1239410d976842fc6f7792de13c9d007d253f
[ "Apache-2.0" ]
null
null
null
lite/kernels/nnadapter/bridges/elementwise_ops.cc
fuaq/Paddle-Lite
56e1239410d976842fc6f7792de13c9d007d253f
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "lite/core/subgraph_bridge_registry.h" #include "lite/kernels/nnadapter/bridges/converter.h" #include "lite/kernels/nnadapter/bridges/utility.h" namespace paddle { namespace lite { namespace subgraph { namespace nnadapter { int ElementwiseConverter(void* ctx, OpLite* op, KernelBase* kernel) { CHECK(ctx != nullptr); CHECK(op != nullptr); auto converter = static_cast<Converter*>(ctx); auto op_info = op->op_info(); auto op_type = op_info->Type(); auto scope = op->scope(); VLOG(3) << "Converting " << op_type << " ..."; // Get input and output vars and op attributes auto x_name = op_info->Input("X").front(); auto x_scale_name = "X0_scale"; auto has_x_scale = op_info->HasInputScale(x_scale_name, true); auto x_scale = has_x_scale ? op_info->GetInputScale(x_scale_name, true)[0] : 0.f; auto x = scope->FindMutableTensor(x_name); auto x_dims = x->dims(); int x_rank = x_dims.size(); auto x_persistable = x->persistable(); auto y_name = op_info->Input("Y").front(); auto y_scale_name = "Y0_scale"; auto has_y_scale = op_info->HasInputScale(y_scale_name, true); auto y_scale = has_y_scale ? op_info->GetInputScale(y_scale_name, true)[0] : 0.f; auto y = scope->FindMutableTensor(y_name); auto y_dims = y->dims(); int y_rank = y_dims.size(); auto y_persistable = y->persistable(); auto out_name = op_info->Output("Out").front(); auto out_scale_name = "Out0_scale"; auto has_out_scale = op_info->HasOutputScale(out_scale_name, true); auto out_scale = has_out_scale ? op_info->GetOutputScale(out_scale_name, true)[0] : 0.f; auto out = scope->FindMutableTensor(out_name); auto out_dims = out->dims(); auto axis = op_info->GetAttr<int>("axis"); if (axis == -1) { axis = std::abs(x_rank - y_rank); } auto act_type = op_info->HasAttr("act_type") ? op_info->GetAttr<std::string>("act_type") : ""; // Check whether the two dimensions are compatiable(Numpy-style broadcasting // https://numpy.org/doc/stable/user/basics.broadcasting.html). // Fill the dimension of Y with 1 int max_rank = x_rank > y_rank ? x_rank : y_rank; std::vector<int64_t> x_shape(max_rank, 1); std::vector<int64_t> y_shape(max_rank, 1); if (x_rank > y_rank) { for (int i = 0; i < y_rank; i++) { y_shape[i + axis] = y_dims[i]; } y_dims = DDim(y_shape); } else { for (int i = 0; i < x_rank; i++) { x_shape[i + axis] = x_dims[i]; } x_dims = DDim(x_shape); } bool matched = true; for (int i = 0; i < max_rank; i++) { matched &= (x_dims[i] == y_dims[i] || x_dims[i] == 1 || y_dims[i] == 1); } CHECK(matched) << "Incompatible broadcasting for x " << x->dims().repr() << " y " << y->dims().repr(); // Input0 operand NNAdapterOperand* input0_operand = nullptr; if (converter->HasOperand(x_name)) { input0_operand = converter->GetOperand(x_name); // TODO(hong19860320) Add a NNADAPTER_RESHAPE operation if x_dims is changed } else { if (has_x_scale) { input0_operand = x_persistable ? converter->AddQuant8ConstantOperand( reinterpret_cast<int8_t*>(x->raw_data()), x_dims, x_scale) : converter->AddQuant8VariableOperand(x_dims, x_scale, x_name); } else { input0_operand = x_persistable ? converter->AddFloat32ConstantOperand( reinterpret_cast<float*>(x->raw_data()), x_dims) : converter->AddFloat32VariableOperand(x_dims, x_name); } } // Input1 operand NNAdapterOperand* input1_operand = nullptr; if (converter->HasOperand(y_name)) { input1_operand = converter->GetOperand(y_name); // TODO(hong19860320) Add a NNADAPTER_RESHAPE operation if y_dims is changed } else { if (has_y_scale) { input1_operand = y_persistable ? converter->AddQuant8ConstantOperand( reinterpret_cast<int8_t*>(y->raw_data()), y_dims, y_scale) : converter->AddQuant8VariableOperand(y_dims, y_scale, y_name); } else { input1_operand = y_persistable ? converter->AddFloat32ConstantOperand( reinterpret_cast<float*>(y->raw_data()), y_dims) : converter->AddFloat32VariableOperand(y_dims, y_name); } } // Fuse code operand int32_t fuse_code_value = NNADAPTER_FUSED_NONE; if (act_type == "relu") { fuse_code_value = NNADAPTER_FUSED_RELU; } else if (act_type == "relu1") { fuse_code_value = NNADAPTER_FUSED_RELU1; } else if (act_type == "relu6") { fuse_code_value = NNADAPTER_FUSED_RELU6; } else if (!act_type.empty()) { LOG(WARNING) << "Unsupported activation type: " << act_type; return FAILED; } auto fuse_code_operand = converter->AddInt32ConstantOperand(fuse_code_value); // Output operand NNAdapterOperand* output_operand = nullptr; if (has_out_scale) { output_operand = converter->AddQuant8VariableOperand(out_dims, out_scale, out_name); } else { output_operand = converter->AddFloat32VariableOperand(out_dims, out_name); } // ADD, SUB, MUL, DIV, MAX and MIN operation std::vector<NNAdapterOperand*> input_operands = { input0_operand, input1_operand, fuse_code_operand}; std::vector<NNAdapterOperand*> output_operands = {output_operand}; NNAdapterOperationType eltwise_operation_type; if (op_type == "elementwise_add" || op_type == "fusion_elementwise_add_activation") { eltwise_operation_type = NNADAPTER_ADD; } else if (op_type == "elementwise_sub" || op_type == "fusion_elementwise_sub_activation") { eltwise_operation_type = NNADAPTER_SUB; } else if (op_type == "elementwise_mul" || op_type == "fusion_elementwise_mul_activation") { eltwise_operation_type = NNADAPTER_MUL; } else if (op_type == "elementwise_div" || op_type == "fusion_elementwise_div_activation") { eltwise_operation_type = NNADAPTER_DIV; } else if (op_type == "elementwise_max" || op_type == "fusion_elementwise_max_activation") { eltwise_operation_type = NNADAPTER_MAX; } else if (op_type == "elementwise_min" || op_type == "fusion_elementwise_min_activation") { eltwise_operation_type = NNADAPTER_MIN; } else { LOG(WARNING) << "Unsupported elementwise op type: " << op_type; return FAILED; } converter->AddOperation( eltwise_operation_type, &input_operands, &output_operands); return REBUILD_WHEN_SHAPE_CHANGED; } } // namespace nnadapter } // namespace subgraph } // namespace lite } // namespace paddle REGISTER_SUBGRAPH_BRIDGE( elementwise_add, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( elementwise_sub, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( elementwise_mul, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( elementwise_div, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( elementwise_max, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( elementwise_min, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_add_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_sub_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_mul_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_div_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_min_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter); REGISTER_SUBGRAPH_BRIDGE( fusion_elementwise_max_activation, kNNAdapter, paddle::lite::subgraph::nnadapter::ElementwiseConverter);
37.0625
80
0.689713
fuaq
882a385fba0583dbe1d719741bdbfbd7fed5cafa
9,101
cpp
C++
test/CompilationTests/ConstructorTests/MakePromiseTests/Copy.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
2
2018-10-15T18:27:50.000Z
2019-04-16T18:34:59.000Z
test/CompilationTests/ConstructorTests/MakePromiseTests/Copy.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
null
null
null
test/CompilationTests/ConstructorTests/MakePromiseTests/Copy.cpp
rocky01/promise
638415a117207a4cae9181e04114e1d7575a9689
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "gmock/gmock.h" #include "Promise.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveUndefinedRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveTRejectUndefined.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveTRejectT.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveTRejectUndefined.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveUndefinedRejectT.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveVoidRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveVoidRejectUndefined.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveVoidRejectT.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveUndefinedRejectT.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveUndefinedRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveTRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveTRejectT.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveTRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveVoidRejectVoid.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteVoidResolveVoidRejectUndefined.hpp" #include "CompilationTests/ConstructorTests/AuxiliaryClasses/Then/Copy/CopyExecuteTResolveVoidRejectT.hpp" using namespace prm; /*** * * 1. make_promise function. * * We have types: * ExeT * ExeVoid * * ResolveT * ResolveVoid * ResolveUndefined * * RejectT * RejectVoid * RejectUndefined * * There are the following combinations availiable: * ExeT, ResolveT, RejectT * ExeT, ResolveT, RejectVoid * ExeT, ResolveT, RejectUndefined * * ExeT, ResolveVoid, RejectT * ExeT, ResolveVoid, RejectVoid * ExeT, ResolveVoid, RejectUndefined * * ExeT, ResolveUndefined, RejectT * ExeT, ResolveUndefined, RejectVoid * ExeT, ResolveUndefined, RejectUndefined <- Not supported * * ExeVoid, ResolveT, RejectT * ExeVoid, ResolveT, RejectVoid * ExeVoid, ResolveT, RejectUndefined * * ExeVoid, ResolveVoid, RejectT * ExeVoid, ResolveVoid, RejectVoid * ExeVoid, ResolveVoid, RejectUndefined * * ExeVoid, ResolveUndefined, RejectT * ExeVoid, ResolveUndefined, RejectVoid * ExeVoid, ResolveUndefined, RejectUndefined <- Not supported * ***/ class MakePromiseCopyRValue: public ::testing::TestWithParam<bool> { }; INSTANTIATE_TEST_CASE_P( TestWithParameters, MakePromiseCopyRValue, testing::Values( false, true )); // ExeT, ResolveT, RejectT TEST_P(MakePromiseCopyRValue, ExeResolveReject) { make_promise(CopyExecuteTResolveTRejectT(GetParam())) .startExecution(10); } // ExeT, ResolveT, RejectVoid TEST_P(MakePromiseCopyRValue, ExeResolveRejectVoid) { make_promise(CopyExecuteTResolveTRejectVoid(GetParam())) .startExecution(10); } // ExeT, ResolveT, RejectUndefined TEST(MakePromiseCopyRValue, ExeResolve) { make_promise(CopyExecuteTResolveTRejectUndefined()) .startExecution(10); } // ExeT, ResolveVoid, RejectT TEST_P(MakePromiseCopyRValue, ExeResolveVoidReject) { make_promise(CopyExecuteTResolveVoidRejectT(GetParam())) .startExecution(10); } // ExeT, ResolveVoid, RejectVoid TEST_P(MakePromiseCopyRValue, ExeResolveVoidRejectVoid) { make_promise(CopyExecuteTResolveVoidRejectVoid(GetParam())) .startExecution(10); } // ExeT, ResolveVoid, RejectUndefined TEST(MakePromiseCopyRValue, ExeResolveVoid) { make_promise(CopyExecuteTResolveVoidRejectUndefined()) .startExecution(10); } // ExeT, ResolveUndefined, RejectT TEST(MakePromiseCopyRValue, ExeReject) { make_promise(CopyExecuteTResolveUndefinedRejectT()) .startExecution(10); } // ExeT, ResolveUndefined, RejectVoid TEST(MakePromiseCopyRValue, ExeRejectVoid) { make_promise(CopyExecuteTResolveUndefinedRejectVoid()) .startExecution(10); } // ExeVoid, ResolveT, RejectT TEST_P(MakePromiseCopyRValue, ResolveReject) { make_promise(CopyExecuteVoidResolveVoidRejectT(GetParam())) .startExecution(); } // ExeVoid, ResolveT, RejectVoid TEST_P(MakePromiseCopyRValue, ResolveRejectVoid) { make_promise(CopyExecuteVoidResolveTRejectT(GetParam())) .startExecution(); } // ExeVoid, ResolveT, RejectUndefined TEST(MakePromiseCopyRValue, Resolve) { make_promise(CopyExecuteVoidResolveTRejectUndefined()) .startExecution(); } // ExeVoid, ResolveVoid, RejectT TEST_P(MakePromiseCopyRValue, ResolvVoideReject) { make_promise(CopyExecuteVoidResolveTRejectVoid(GetParam())) .startExecution(); } // ExeVoid, ResolveVoid, RejectVoid TEST_P(MakePromiseCopyRValue, ResolvVoideRejectVoid) { make_promise(CopyExecuteVoidResolveVoidRejectVoid(GetParam())) .startExecution(); } // ExeVoid, ResolveVoid, RejectUndefined TEST(MakePromiseCopyRValue, ResolvVoide) { make_promise(CopyExecuteVoidResolveVoidRejectUndefined()) .startExecution(); } // ExeVoid, ResolveUndefined, RejectT TEST(MakePromiseCopyRValue, Reject) { make_promise(CopyExecuteVoidResolveUndefinedRejectT()) .startExecution(); } // ExeVoid, ResolveUndefined, RejectVoid TEST(MakePromiseCopyRValue, RejectVoid) { make_promise(CopyExecuteVoidResolveUndefinedRejectVoid()) .startExecution(); } //-----------------LValue----------------- class MakePromiseCopyLValue: public ::testing::TestWithParam<bool> { }; INSTANTIATE_TEST_CASE_P( TestWithParameters, MakePromiseCopyLValue, testing::Values( false, true )); // ExeT, ResolveT, RejectT TEST_P(MakePromiseCopyLValue, ExeResolveReject) { auto lvalue = CopyExecuteTResolveTRejectT(GetParam()); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveT, RejectVoid TEST_P(MakePromiseCopyLValue, ExeResolveRejectVoid) { auto lvalue = CopyExecuteTResolveTRejectVoid(GetParam()); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveT, RejectUndefined TEST(MakePromiseCopyLValue, ExeResolve) { auto lvalue = CopyExecuteTResolveTRejectUndefined(); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveVoid, RejectT TEST_P(MakePromiseCopyLValue, ExeResolveVoidReject) { auto lvalue = CopyExecuteTResolveVoidRejectT(GetParam()); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveVoid, RejectVoid TEST_P(MakePromiseCopyLValue, ExeResolveVoidRejectVoid) { auto lvalue = CopyExecuteTResolveVoidRejectVoid(GetParam()); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveVoid, RejectUndefined TEST(MakePromiseCopyLValue, ExeResolveVoid) { auto lvalue = CopyExecuteTResolveVoidRejectUndefined(); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveUndefined, RejectT TEST(MakePromiseCopyLValue, ExeReject) { auto lvalue = CopyExecuteTResolveUndefinedRejectT(); make_promise(lvalue) .startExecution(10); } // ExeT, ResolveUndefined, RejectVoid TEST(MakePromiseCopyLValue, ExeRejectVoid) { auto lvalue = CopyExecuteTResolveUndefinedRejectVoid(); make_promise(lvalue) .startExecution(10); } // ExeVoid, ResolveT, RejectT TEST_P(MakePromiseCopyLValue, ResolveReject) { auto lvalue = CopyExecuteVoidResolveVoidRejectT(GetParam()); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveT, RejectVoid TEST_P(MakePromiseCopyLValue, ResolveRejectVoid) { auto lvalue = CopyExecuteVoidResolveTRejectT(GetParam()); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveT, RejectUndefined TEST(MakePromiseCopyLValue, Resolve) { auto lvalue = CopyExecuteVoidResolveTRejectUndefined(); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveVoid, RejectT TEST_P(MakePromiseCopyLValue, ResolvVoideReject) { auto lvalue = CopyExecuteVoidResolveTRejectVoid(GetParam()); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveVoid, RejectVoid TEST_P(MakePromiseCopyLValue, ResolvVoideRejectVoid) { auto lvalue = CopyExecuteVoidResolveVoidRejectVoid(GetParam()); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveVoid, RejectUndefined TEST(MakePromiseCopyLValue, ResolvVoide) { auto lvalue = CopyExecuteVoidResolveVoidRejectUndefined(); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveUndefined, RejectT TEST(MakePromiseCopyLValue, Reject) { auto lvalue = CopyExecuteVoidResolveUndefinedRejectT(); make_promise(lvalue) .startExecution(); } // ExeVoid, ResolveUndefined, RejectVoid TEST(MakePromiseCopyLValue, RejectVoid) { auto lvalue = CopyExecuteVoidResolveUndefinedRejectVoid(); make_promise(lvalue) .startExecution(); }
26.456395
117
0.785518
rocky01
882a90384d9f2a0ab12acc96d7ea555362512cf9
1,236
cpp
C++
Signal Flow Simulation/truetime-2.0/kernel/setnumberofcpus.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2019-08-31T08:06:48.000Z
2019-08-31T08:06:48.000Z
Signal Flow Simulation/truetime-2.0/kernel/setnumberofcpus.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
null
null
null
Signal Flow Simulation/truetime-2.0/kernel/setnumberofcpus.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2020-01-07T10:46:23.000Z
2020-01-07T10:46:23.000Z
/* * Copyright (c) 2016 Lund University * * Written by Anton Cervin, Dan Henriksson and Martin Ohlin, * Department of Automatic Control LTH, Lund University, Sweden. * * This file is part of TrueTime 2.0. * * TrueTime 2.0 is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * TrueTime 2.0 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 TrueTime 2.0. If not, see <http://www.gnu.org/licenses/> */ #ifndef SET_NUMBER_OF_CPUS #define SET_NUMBER_OF_CPUS void ttSetNumberOfCPUs(int nbr) { if (rtsys->initialized == true) { TT_MEX_ERROR("ttSetNumberOfCPUs must be called before ttInitKernel!"); return; } if (nbr > 0 && nbr <= 64) { rtsys->nbrOfCPUs = nbr; } else { TT_MEX_ERROR("ttSetNumberOfCPUs: number of CPUs must be <= 64"); } } #endif
29.428571
74
0.714401
raulest50
882aaba5ab5c6d29e70acbbc3c8d43ee8989abe0
8,567
cpp
C++
sdk/storage/azure-storage-queues/src/queue_service_client.cpp
JinmingHu-MSFT/azure-sdk-for-cpp
933486385a54a5a09a7444dbd823425f145ad75a
[ "MIT" ]
1
2022-01-19T22:54:41.000Z
2022-01-19T22:54:41.000Z
sdk/storage/azure-storage-queues/src/queue_service_client.cpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
sdk/storage/azure-storage-queues/src/queue_service_client.cpp
LarryOsterman/azure-sdk-for-cpp
d96216f50909a2bd39b555c9088f685bf0f7d6e6
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // SPDX-License-Identifier: MIT #include "azure/storage/queues/queue_service_client.hpp" #include <azure/core/http/policies/policy.hpp> #include <azure/storage/common/crypt.hpp> #include <azure/storage/common/internal/shared_key_policy.hpp> #include <azure/storage/common/internal/storage_per_retry_policy.hpp> #include <azure/storage/common/internal/storage_service_version_policy.hpp> #include <azure/storage/common/internal/storage_switch_to_secondary_policy.hpp> #include <azure/storage/common/storage_common.hpp> #include "private/package_version.hpp" namespace Azure { namespace Storage { namespace Queues { QueueServiceClient QueueServiceClient::CreateFromConnectionString( const std::string& connectionString, const QueueClientOptions& options) { auto parsedConnectionString = _internal::ParseConnectionString(connectionString); auto serviceUrl = std::move(parsedConnectionString.QueueServiceUrl); if (parsedConnectionString.KeyCredential) { return QueueServiceClient( serviceUrl.GetAbsoluteUrl(), parsedConnectionString.KeyCredential, options); } else { return QueueServiceClient(serviceUrl.GetAbsoluteUrl(), options); } } QueueServiceClient::QueueServiceClient( const std::string& serviceUrl, std::shared_ptr<StorageSharedKeyCredential> credential, const QueueClientOptions& options) : QueueServiceClient(serviceUrl, options) { QueueClientOptions newOptions = options; newOptions.PerRetryPolicies.emplace_back( std::make_unique<_internal::SharedKeyPolicy>(credential)); std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perRetryPolicies; std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perOperationPolicies; perRetryPolicies.emplace_back(std::make_unique<_internal::StorageSwitchToSecondaryPolicy>( m_serviceUrl.GetHost(), newOptions.SecondaryHostForRetryReads)); perRetryPolicies.emplace_back(std::make_unique<_internal::StoragePerRetryPolicy>()); perOperationPolicies.emplace_back( std::make_unique<_internal::StorageServiceVersionPolicy>(newOptions.ApiVersion.ToString())); m_pipeline = std::make_shared<Azure::Core::Http::_internal::HttpPipeline>( newOptions, _internal::QueueServicePackageName, _detail::PackageVersion::ToString(), std::move(perRetryPolicies), std::move(perOperationPolicies)); } QueueServiceClient::QueueServiceClient( const std::string& serviceUrl, std::shared_ptr<Core::Credentials::TokenCredential> credential, const QueueClientOptions& options) : QueueServiceClient(serviceUrl, options) { std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perRetryPolicies; std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perOperationPolicies; perRetryPolicies.emplace_back(std::make_unique<_internal::StorageSwitchToSecondaryPolicy>( m_serviceUrl.GetHost(), options.SecondaryHostForRetryReads)); perRetryPolicies.emplace_back(std::make_unique<_internal::StoragePerRetryPolicy>()); { Azure::Core::Credentials::TokenRequestContext tokenContext; tokenContext.Scopes.emplace_back(_internal::StorageScope); perRetryPolicies.emplace_back( std::make_unique<Azure::Core::Http::Policies::_internal::BearerTokenAuthenticationPolicy>( credential, tokenContext)); } perOperationPolicies.emplace_back( std::make_unique<_internal::StorageServiceVersionPolicy>(options.ApiVersion.ToString())); m_pipeline = std::make_shared<Azure::Core::Http::_internal::HttpPipeline>( options, _internal::QueueServicePackageName, _detail::PackageVersion::ToString(), std::move(perRetryPolicies), std::move(perOperationPolicies)); } QueueServiceClient::QueueServiceClient( const std::string& serviceUrl, const QueueClientOptions& options) : m_serviceUrl(serviceUrl) { std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perRetryPolicies; std::vector<std::unique_ptr<Azure::Core::Http::Policies::HttpPolicy>> perOperationPolicies; perRetryPolicies.emplace_back(std::make_unique<_internal::StorageSwitchToSecondaryPolicy>( m_serviceUrl.GetHost(), options.SecondaryHostForRetryReads)); perRetryPolicies.emplace_back(std::make_unique<_internal::StoragePerRetryPolicy>()); perOperationPolicies.emplace_back( std::make_unique<_internal::StorageServiceVersionPolicy>(options.ApiVersion.ToString())); m_pipeline = std::make_shared<Azure::Core::Http::_internal::HttpPipeline>( options, _internal::QueueServicePackageName, _detail::PackageVersion::ToString(), std::move(perRetryPolicies), std::move(perOperationPolicies)); } QueueClient QueueServiceClient::GetQueueClient(const std::string& queueName) const { auto queueUrl = m_serviceUrl; queueUrl.AppendPath(_internal::UrlEncodePath(queueName)); return QueueClient(std::move(queueUrl), m_pipeline); } ListQueuesPagedResponse QueueServiceClient::ListQueues( const ListQueuesOptions& options, const Azure::Core::Context& context) const { _detail::ServiceClient::ListServiceQueuesSegmentOptions protocolLayerOptions; protocolLayerOptions.Prefix = options.Prefix; protocolLayerOptions.Marker = options.ContinuationToken; protocolLayerOptions.MaxResults = options.PageSizeHint; protocolLayerOptions.Include = options.Include; auto response = _detail::ServiceClient::ListQueuesSegment( *m_pipeline, m_serviceUrl, protocolLayerOptions, _internal::WithReplicaStatus(context)); ListQueuesPagedResponse pagedResponse; pagedResponse.ServiceEndpoint = std::move(response.Value.ServiceEndpoint); pagedResponse.Prefix = std::move(response.Value.Prefix); pagedResponse.Queues = std::move(response.Value.Items); pagedResponse.m_queueServiceClient = std::make_shared<QueueServiceClient>(*this); pagedResponse.m_operationOptions = options; pagedResponse.CurrentPageToken = options.ContinuationToken.ValueOr(std::string()); pagedResponse.NextPageToken = response.Value.ContinuationToken; pagedResponse.RawResponse = std::move(response.RawResponse); return pagedResponse; } Azure::Response<Models::SetServicePropertiesResult> QueueServiceClient::SetProperties( Models::QueueServiceProperties properties, const SetServicePropertiesOptions& options, const Azure::Core::Context& context) const { (void)options; _detail::ServiceClient::SetServicePropertiesOptions protocolLayerOptions; protocolLayerOptions.QueueServiceProperties = std::move(properties); return _detail::ServiceClient::SetProperties( *m_pipeline, m_serviceUrl, protocolLayerOptions, context); } Azure::Response<Models::QueueServiceProperties> QueueServiceClient::GetProperties( const GetServicePropertiesOptions& options, const Azure::Core::Context& context) const { (void)options; _detail::ServiceClient::GetServicePropertiesOptions protocolLayerOptions; return _detail::ServiceClient::GetProperties( *m_pipeline, m_serviceUrl, protocolLayerOptions, _internal::WithReplicaStatus(context)); } Azure::Response<Models::ServiceStatistics> QueueServiceClient::GetStatistics( const GetQueueServiceStatisticsOptions& options, const Azure::Core::Context& context) const { (void)options; _detail::ServiceClient::GetServiceStatisticsOptions protocolLayerOptions; return _detail::ServiceClient::GetStatistics( *m_pipeline, m_serviceUrl, protocolLayerOptions, context); } Azure::Response<QueueClient> QueueServiceClient::CreateQueue( const std::string& queueName, const CreateQueueOptions& options, const Azure::Core::Context& context) const { auto queueClient = GetQueueClient(queueName); auto response = queueClient.Create(options, context); return Azure::Response<QueueClient>(std::move(queueClient), std::move(response.RawResponse)); } Azure::Response<Models::DeleteQueueResult> QueueServiceClient::DeleteQueue( const std::string& queueName, const DeleteQueueOptions& options, const Azure::Core::Context& context) const { auto queueClient = GetQueueClient(queueName); return queueClient.Delete(options, context); } }}} // namespace Azure::Storage::Queues
44.388601
100
0.755457
JinmingHu-MSFT
8836db43cb688f3dbf91c9a5945113f3431a135f
52,759
cpp
C++
code/external/libigl/external/embree/kernels/xeon/bvh/bvh4_factory.cpp
dybiszb/MeanCurvatureLibrary
b168911ef6bf08b283e7a225cc006b850fe26400
[ "MIT" ]
null
null
null
code/external/libigl/external/embree/kernels/xeon/bvh/bvh4_factory.cpp
dybiszb/MeanCurvatureLibrary
b168911ef6bf08b283e7a225cc006b850fe26400
[ "MIT" ]
1
2018-11-14T23:14:58.000Z
2018-11-14T23:14:58.000Z
code/external/libigl/external/embree/kernels/xeon/bvh/bvh4_factory.cpp
dybiszb/MeanCurvatureLibrary
b168911ef6bf08b283e7a225cc006b850fe26400
[ "MIT" ]
null
null
null
// ======================================================================== // // Copyright 2009-2015 Intel Corporation // // // // Licensed under the Apache License, Version 2.0 (the "License"); // // you may not use this file except in compliance with the License. // // You may obtain a copy of the License at // // // // http://www.apache.org/licenses/LICENSE-2.0 // // // // Unless required by applicable law or agreed to in writing, software // // distributed under the License is distributed on an "AS IS" BASIS, // // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // // limitations under the License. // // ======================================================================== // #include "bvh4_factory.h" #include "../bvh/bvh.h" #include "../geometry/bezier1v.h" #include "../geometry/bezier1i.h" #include "../geometry/linei.h" #include "../geometry/triangle.h" #include "../geometry/trianglev.h" #include "../geometry/trianglev_mb.h" #include "../geometry/trianglei.h" #include "../geometry/quadv.h" #include "../geometry/quadi.h" #include "../geometry/quadi_mb.h" #include "../geometry/subdivpatch1cached.h" #include "../geometry/object.h" #include "../../common/accelinstance.h" namespace embree { DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Line4iMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1vIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Bezier1iMBIntersector1_OBB); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4XfmTriangle4Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle8Intersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Triangle4vMBIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Subdivpatch1CachedIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4GridAOSIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4VirtualMBIntersector1); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4vIntersector1Moeller); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector1,BVH4Quad4iMBIntersector1Pluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Line4iMBIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1vIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Bezier1iMBIntersector4Single_OBB); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle8Intersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Triangle4vMBIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4vIntersector4HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Quad4iMBIntersector4HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector4,BVH4Subdivpatch1CachedIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4GridAOSIntersector4); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector4,BVH4VirtualMBIntersector4Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Line4iMBIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1vIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Bezier1iMBIntersector8Single_OBB); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle8Intersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Triangle4vMBIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4vIntersector8HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Quad4iMBIntersector8HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector8,BVH4Subdivpatch1CachedIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4GridAOSIntersector8); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector8,BVH4VirtualMBIntersector8Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Line4iMBIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1vIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Bezier1iMBIntersector16Single_OBB); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle8Intersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Triangle4vMBIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoeller); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4vIntersector16HybridMoellerNoFilter); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Quad4iMBIntersector16HybridPluecker); DECLARE_SYMBOL2(Accel::Intersector16,BVH4Subdivpatch1CachedIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4GridAOSIntersector16); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualIntersector16Chunk); DECLARE_SYMBOL2(Accel::Intersector16,BVH4VirtualMBIntersector16Chunk); DECLARE_BUILDER2(void,Scene,const createLineSegmentsAccelTy,BVH4BuilderTwoLevelLineSegmentsSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderTwoLevelTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,const createTriangleMeshAccelTy,BVH4BuilderInstancingTriangleMeshSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iMBBuilder_OBB_New); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Quad4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle8SceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4vSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Triangle4iSceneBuilderSpatialSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshBuilderSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4vMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMeshBuilderSAH); DECLARE_BUILDER2(void,QuadMesh,size_t,BVH4Quad4iMBMeshBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1vSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Bezier1iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4Line4iMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4VirtualMBSceneBuilderSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivPatch1CachedBuilderBinnedSAH); DECLARE_BUILDER2(void,Scene,size_t,BVH4SubdivGridEagerBuilderBinnedSAH); DECLARE_BUILDER2(void,LineSegments,size_t,BVH4Line4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshRefitSAH); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle8MeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4vMeshBuilderMortonGeneral); DECLARE_BUILDER2(void,TriangleMesh,size_t,BVH4Triangle4iMeshBuilderMortonGeneral); BVH4Factory::BVH4Factory (int features) { /* select builders */ SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelLineSegmentsSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderTwoLevelTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4BuilderInstancingTriangleMeshSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iMBBuilder_OBB_New); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4Quad4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4SceneBuilderSpatialSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8SceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iSceneBuilderSpatialSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4vMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Quad4iMBMeshBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1vSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Bezier1iSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4VirtualMBSceneBuilderSAH); SELECT_SYMBOL_DEFAULT_AVX_AVX512KNL(features,BVH4SubdivPatch1CachedBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4SubdivGridEagerBuilderBinnedSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Line4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshRefitSAH); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshRefitSAH); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4MeshBuilderMortonGeneral); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle8MeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4vMeshBuilderMortonGeneral); SELECT_SYMBOL_DEFAULT_AVX(features,BVH4Triangle4iMeshBuilderMortonGeneral); /* select intersectors1 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Line4iMBIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1vIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4Bezier1iMBIntersector1_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4Triangle4Intersector1Moeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2_AVX512KNL(features,BVH4XfmTriangle4Intersector1Moeller); SELECT_SYMBOL_INIT_AVX_AVX2 (features,BVH4Triangle8Intersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4vIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX (features,BVH4Triangle4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4GridAOSIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector1); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector1Moeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iIntersector1Pluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4iMBIntersector1Pluecker); #if defined (RTCORE_RAY_PACKETS) /* select intersectors4 */ SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Line4iMBIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1vIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Bezier1iMBIntersector4Single_OBB); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4vIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX(features,BVH4Triangle4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Triangle4vMBIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); SELECT_SYMBOL_DEFAULT_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoellerNoFilter); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_AVX (features,BVH4Quad4iMBIntersector4HybridPluecker); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector4); SELECT_SYMBOL_DEFAULT_AVX_AVX2 (features,BVH4GridAOSIntersector4); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4VirtualMBIntersector4Chunk); SELECT_SYMBOL_DEFAULT_SSE42_AVX_AVX2(features,BVH4Quad4vIntersector4HybridMoeller); /* select intersectors8 */ SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Line4iMBIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1vIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Bezier1iMBIntersector8Single_OBB); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle8Intersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4vIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Triangle4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Triangle4vMBIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoeller); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Quad4vIntersector8HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX (features,BVH4Quad4iMBIntersector8HybridPluecker); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4Subdivpatch1CachedIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4GridAOSIntersector8); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualIntersector8Chunk); SELECT_SYMBOL_INIT_AVX_AVX2(features,BVH4VirtualMBIntersector8Chunk); /* select intersectors16 */ SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Line4iMBIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1vIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Bezier1iMBIntersector16Single_OBB); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle8Intersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Triangle4vMBIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoeller); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4vIntersector16HybridMoellerNoFilter); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Quad4iMBIntersector16HybridPluecker); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4Subdivpatch1CachedIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4GridAOSIntersector16); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualIntersector16Chunk); SELECT_SYMBOL_INIT_AVX512KNL(features,BVH4VirtualMBIntersector16Chunk); #endif } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1; intersectors.intersector4 = BVH4Bezier1vIntersector4Single; intersectors.intersector8 = BVH4Bezier1vIntersector8Single; intersectors.intersector16 = BVH4Bezier1vIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1; intersectors.intersector4 = BVH4Bezier1iIntersector4Single; intersectors.intersector8 = BVH4Bezier1iIntersector8Single; intersectors.intersector16 = BVH4Bezier1iIntersector16Single; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iIntersector1; intersectors.intersector4 = BVH4Line4iIntersector4; intersectors.intersector8 = BVH4Line4iIntersector8; intersectors.intersector16 = BVH4Line4iIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Line4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Line4iMBIntersector1; intersectors.intersector4 = BVH4Line4iMBIntersector4; intersectors.intersector8 = BVH4Line4iMBIntersector8; intersectors.intersector16 = BVH4Line4iMBIntersector16; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1vIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1vIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1vIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1vIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1vIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Bezier1iMBIntersectors_OBB(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Bezier1iMBIntersector1_OBB; intersectors.intersector4 = BVH4Bezier1iMBIntersector4Single_OBB; intersectors.intersector8 = BVH4Bezier1iMBIntersector8Single_OBB; intersectors.intersector16 = BVH4Bezier1iMBIntersector16Single_OBB; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle4Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle4Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle4Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle4Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle4Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle4Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4IntersectorsInstancing(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4XfmTriangle4Intersector1Moeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle8IntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle8Intersector1Moeller; intersectors.intersector4_filter = BVH4Triangle8Intersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Triangle8Intersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Triangle8Intersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Triangle8Intersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Triangle8Intersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Triangle8Intersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4vIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4vIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4vIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4iIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4iIntersector1Pluecker; intersectors.intersector4 = BVH4Triangle4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Triangle4iIntersector8HybridPluecker; intersectors.intersector16 = BVH4Triangle4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Triangle4vMBIntersectorsHybrid(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Triangle4vMBIntersector1Moeller; intersectors.intersector4 = BVH4Triangle4vMBIntersector4HybridMoeller; intersectors.intersector8 = BVH4Triangle4vMBIntersector8HybridMoeller; intersectors.intersector16 = BVH4Triangle4vMBIntersector16HybridMoeller; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4vIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4vIntersector1Moeller; intersectors.intersector4_filter = BVH4Quad4vIntersector4HybridMoeller; intersectors.intersector4_nofilter = BVH4Quad4vIntersector4HybridMoellerNoFilter; intersectors.intersector8_filter = BVH4Quad4vIntersector8HybridMoeller; intersectors.intersector8_nofilter = BVH4Quad4vIntersector8HybridMoellerNoFilter; intersectors.intersector16_filter = BVH4Quad4vIntersector16HybridMoeller; intersectors.intersector16_nofilter = BVH4Quad4vIntersector16HybridMoellerNoFilter; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iIntersector16HybridPluecker; return intersectors; } Accel::Intersectors BVH4Factory::BVH4Quad4iMBIntersectors(BVH4* bvh) { Accel::Intersectors intersectors; intersectors.ptr = bvh; intersectors.intersector1 = BVH4Quad4iMBIntersector1Pluecker; intersectors.intersector4 = BVH4Quad4iMBIntersector4HybridPluecker; intersectors.intersector8 = BVH4Quad4iMBIntersector8HybridPluecker; intersectors.intersector16= BVH4Quad4iMBIntersector16HybridPluecker; return intersectors; } void BVH4Factory::createLineSegmentsLine4i(LineSegments* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Line4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Line4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Line4iMeshBuilderSAH(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8Morton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { accel = new BVH4(Triangle8::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); } #endif void BVH4Factory::createTriangleMeshTriangle4vMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4iMorton(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); builder = mesh->parent->device->bvh4_factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); } void BVH4Factory::createTriangleMeshTriangle4(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #if defined (__TARGET_AVX__) void BVH4Factory::createTriangleMeshTriangle8(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle8::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle8MeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle8MeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle8MeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } #endif void BVH4Factory::createTriangleMeshTriangle4v(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4v::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4vMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4vMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } void BVH4Factory::createTriangleMeshTriangle4i(TriangleMesh* mesh, AccelData*& accel, Builder*& builder) { BVH4Factory* factory = mesh->parent->device->bvh4_factory; accel = new BVH4(Triangle4i::type,mesh->parent); switch (mesh->flags) { case RTC_GEOMETRY_STATIC: builder = factory->BVH4Triangle4iMeshBuilderSAH(accel,mesh,0); break; case RTC_GEOMETRY_DEFORMABLE: builder = factory->BVH4Triangle4iMeshRefitSAH(accel,mesh,0); break; case RTC_GEOMETRY_DYNAMIC: builder = factory->BVH4Triangle4iMeshBuilderMortonGeneral(accel,mesh,0); break; default: throw_RTCError(RTC_UNKNOWN_ERROR,"invalid geometry flag"); } } Accel* BVH4Factory::BVH4Bezier1v(Scene* scene) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors(accel); Builder* builder = BVH4Bezier1vSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Bezier1i(Scene* scene) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors(accel); Builder* builder = BVH4Bezier1iSceneBuilderSAH(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4i(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = nullptr; if (scene->device->line_builder == "default" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "sah" ) builder = BVH4Line4iSceneBuilderSAH(accel,scene,0); else if (scene->device->line_builder == "dynamic" ) builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->line_builder+" for BVH4<Line4i>"); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iMB(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iMBIntersectors(accel); Builder* builder = BVH4Line4iMBSceneBuilderSAH(accel,scene,0); scene->needLineVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Line4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Line4i::type,scene); Accel::Intersectors intersectors = BVH4Line4iIntersectors(accel); Builder* builder = BVH4BuilderTwoLevelLineSegmentsSAH(accel,scene,&createLineSegmentsLine4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1v(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1v::type,scene); Accel::Intersectors intersectors = BVH4Bezier1vIntersectors_OBB(accel); Builder* builder = BVH4Bezier1vBuilder_OBB_New(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1i(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4OBBBezier1iMB(Scene* scene, bool highQuality) { BVH4* accel = new BVH4(Bezier1i::type,scene); Accel::Intersectors intersectors = BVH4Bezier1iMBIntersectors_OBB(accel); Builder* builder = BVH4Bezier1iMBBuilder_OBB_New(accel,scene,0); scene->needBezierVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4>"); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle8IntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle8IntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle8>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle8SceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8Morton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle8>"); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4v(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4vSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4vMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4v>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4i(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4iIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4i>"); Builder* builder = nullptr; if (scene->device->tri_builder == "default" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah" ) builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_spatial" ) builder = BVH4Triangle4iSceneBuilderSpatialSAH(accel,scene,0); else if (scene->device->tri_builder == "sah_presplit") builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,MODE_HIGH_QUALITY); else if (scene->device->tri_builder == "dynamic" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); else if (scene->device->tri_builder == "morton" ) builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4iMorton); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder+" for BVH4<Triangle4i>"); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vMB(Scene* scene) { BVH4* accel = new BVH4(Triangle4vMB::type,scene); Accel::Intersectors intersectors; if (scene->device->tri_traverser == "default") intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else if (scene->device->tri_traverser == "hybrid" ) intersectors = BVH4Triangle4vMBIntersectorsHybrid(accel); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown traverser "+scene->device->tri_traverser+" for BVH4<Triangle4vMB>"); Builder* builder = nullptr; if (scene->device->tri_builder_mb == "default" ) builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else if (scene->device->tri_builder_mb == "sah") builder = BVH4Triangle4vMBSceneBuilderSAH(accel,scene,0); else throw_RTCError(RTC_INVALID_ARGUMENT,"unknown builder "+scene->device->tri_builder_mb+" for BVH4<Triangle4vMB>"); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4InstancedBVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsInstancing(accel); Builder* builder = BVH4BuilderInstancingTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8Twolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle8); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4v); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iTwolevel(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); Builder* builder = BVH4BuilderTwoLevelTriangleMeshSAH(accel,scene,&createTriangleMeshTriangle4i); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8SpatialSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSpatialSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4::type,scene); Builder* builder = BVH4Triangle4SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #if defined (__TARGET_AVX__) Accel* BVH4Factory::BVH4Triangle8ObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle8::type,scene); Builder* builder = BVH4Triangle8SceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle8IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } #endif Accel* BVH4Factory::BVH4Triangle4vObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4v::type,scene); Builder* builder = BVH4Triangle4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4iObjectSplit(Scene* scene) { BVH4* accel = new BVH4(Triangle4i::type,scene); Builder* builder = BVH4Triangle4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Triangle4iIntersectorsHybrid(accel); scene->needTriangleVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivPatch1Cached(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Cached::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4Subdivpatch1CachedIntersector1; intersectors.intersector4 = BVH4Subdivpatch1CachedIntersector4; intersectors.intersector8 = BVH4Subdivpatch1CachedIntersector8; intersectors.intersector16 = BVH4Subdivpatch1CachedIntersector16; Builder* builder = BVH4SubdivPatch1CachedBuilderBinnedSAH(accel,scene,0); scene->needSubdivIndices = false; scene->needSubdivVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4SubdivGridEager(Scene* scene) { BVH4* accel = new BVH4(SubdivPatch1Eager::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4GridAOSIntersector1; intersectors.intersector4 = BVH4GridAOSIntersector4; intersectors.intersector8 = BVH4GridAOSIntersector8; intersectors.intersector16 = BVH4GridAOSIntersector16; Builder* builder = BVH4SubdivGridEagerBuilderBinnedSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometry(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualIntersector1; intersectors.intersector4 = BVH4VirtualIntersector4Chunk; intersectors.intersector8 = BVH4VirtualIntersector8Chunk; intersectors.intersector16 = BVH4VirtualIntersector16Chunk; Builder* builder = BVH4VirtualSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4UserGeometryMB(Scene* scene) { BVH4* accel = new BVH4(Object::type,scene); Accel::Intersectors intersectors; intersectors.ptr = accel; intersectors.intersector1 = BVH4VirtualMBIntersector1; intersectors.intersector4 = BVH4VirtualMBIntersector4Chunk; intersectors.intersector8 = BVH4VirtualMBIntersector8Chunk; intersectors.intersector16 = BVH4VirtualMBIntersector16Chunk; Builder* builder = BVH4VirtualMBSceneBuilderSAH(accel,scene,0); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4ObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4vObjectSplit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4v::type,mesh->parent); Builder* builder = BVH4Triangle4vMeshBuilderSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4vIntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Triangle4Refit(TriangleMesh* mesh) { BVH4* accel = new BVH4(Triangle4::type,mesh->parent); Builder* builder = BVH4Triangle4MeshRefitSAH(accel,mesh,0); Accel::Intersectors intersectors = BVH4Triangle4IntersectorsHybrid(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4v(Scene* scene) { BVH4* accel = new BVH4(Quad4v::type,scene); Builder* builder = BVH4Quad4vSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4vIntersectors(accel); return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4i(Scene* scene) { BVH4* accel = new BVH4(Quad4i::type,scene); Builder* builder = BVH4Quad4iSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } Accel* BVH4Factory::BVH4Quad4iMB(Scene* scene) { BVH4* accel = new BVH4(Quad4iMB::type,scene); Builder* builder = BVH4Quad4iMBSceneBuilderSAH(accel,scene,0); Accel::Intersectors intersectors = BVH4Quad4iMBIntersectors(accel); scene->needQuadVertices = true; return new AccelInstance(accel,builder,intersectors); } }
53.508114
153
0.797437
dybiszb
88371522baf1170d2466cfb0e236df6875764d3c
2,396
cpp
C++
Dynamic Programming/Zipper/Zipper.cpp
Sean16SYSU/Algorithms4N
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
[ "MIT" ]
2
2019-09-30T01:26:41.000Z
2019-10-02T01:36:34.000Z
Dynamic Programming/Zipper/Zipper.cpp
Sean16SYSU/Algorithms4N
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
[ "MIT" ]
null
null
null
Dynamic Programming/Zipper/Zipper.cpp
Sean16SYSU/Algorithms4N
24f06c29d476c4bd9c90bcc89dac90ba3a448c27
[ "MIT" ]
3
2020-05-18T15:09:01.000Z
2020-12-21T10:14:51.000Z
#include <iostream> #include <cstring> #include <algorithm> using namespace std; #include <string> string a, b, all; bool Arr[1000][1000]; //Arr[i][j]่กจ็คบ ไปฅ a[i]ๅ’Œb[j]็ป“ๆŸ็š„ไธฒๅœจไธๅœจๅ…ถไธญ ๅœจ = true,ๆˆ–่€… ไธๅœจ = false ; int find(char c, int no = -1) //no่กจ็คบไธๆ˜ฏๅๆ ‡no { for (int i = 0; i < all.length(); ++i) { if (all[i] == c && i != no) return i; } return -1; } void oper() { int pp1 = find(a[0]); int pp2 = find(b[0], pp1); //ๅพ—ๅˆฐๅœจpp2 != pp1็š„ๅ‰ๆไธ‹ๆ‰พๅˆฐไบ†b[0]็š„ๅผ€ๅคด,่ฟ˜ๆ˜ฏไปŽๅ‰้ขๆ‰พ if (pp2 == -1) { //้€š่ฟ‡่ฟ™็งๆ–นๅผ็š„ๅฏปๆ‰พ๏ผŒ็กฎไฟไบ†๏ผŒๆœ€ๅŽไธ€ไธชๅ…ƒ็ด ๅœจไธค่€…ไธญ้ƒฝๅญ˜ๅœจ cout << "no" << endl; return; } //่ฟ™ๆ˜ฏไธ€็งๅฏ่ƒฝ๏ผŒๅœจ่ฟ™็งๅฏ่ƒฝไน‹ไธ‹ Arr[0][0] = true; if (pp1 > pp2) { for (int i = pp2 + 1; i < pp1; ++i) { if (b[i] != all[i]) { cout << "no" << endl; return; } Arr[0][i] = true; } } else { for (int i = pp1 + 1; i < pp2; ++i) { if (a[i] != all[i]) { cout << "no" << endl; return; } Arr[i][0] = true; } } //่ฆๆ˜Ž็™ฝไธ€็‚น๏ผŒไธคไธชๅผ€ๅคด็š„ไฝ็ฝฎไน‹้—ด็š„ๅญ—็ฌฆๅฟ…ๅฎšๆ˜ฏๅฑžไบŽๅ‰้ข้‚ฃไธชๅญ—็ฌฆๆ‰€ๅฏนๅบ”็š„ๅญ—็ฌฆไธฒ็š„ //่‡ณๆญค๏ผŒๅฐฑๅผ€ๅง‹้ๅކๆ‰€ๆœ‰็š„่ตทๅง‹ไฝ็ฝฎ ,ไธคไธชไฝ็ฝฎ้ƒฝๅˆ’ๅฝ’ๅˆฐไบ†ๅŒไธ€ไฝ็ฝฎ //่ฟ›่กŒๆ–œ็€็š„ๅกซ่กจ่ฟ‡็จ‹๏ผŒๆฏไธ€ๆ–œ่กŒ๏ผŒ้ƒฝๆœ‰๏ผŒๆจช็บตๅๆ ‡็›ธๅŠ ้ƒฝๆ˜ฏ็›ธ็ญ‰็š„๏ผŒๅฐฑๆ˜ฏ่ฏด๏ผŒ่€ƒ่™‘็š„้ƒฝๆ˜ฏๅฏนไบŽallๆฅ่ฏด๏ผŒ้ƒฝๆ˜ฏๅ‰้ข็š„ //cat tree tcraete int p = max(pp1, pp2) + 1; //็”จ pๆฅ่กจ็คบ้œ€่ฆๅค„็†็š„all ็š„็ฌฌpไธชๅ…ƒ็ด (ไปŽ0ๅผ€ๅง‹่ฎกๆ•ฐ)๏ผŒๅ…ถๅฎžๅพˆๆ˜Žๆ˜พๅฏไปฅ็œ‹ๅˆฐ //็›ฎๅ‰๏ผŒๆŒ‡ๅฎšๅˆฐไบ†ๅ‡†็กฎ็š„ไฝ็ฝฎ while (p < all.length()) { //p่กจ็คบ็ฌฌpไธชๅ…ƒ็ด ๏ผŒๅฐฑๆ˜ฏ่กจ็คบ็ฌฌpๆ–œ่กŒ for (int i = 0; i <= p; ++i) { //ๅฏนไบŽ่ฟ™ไธช็ฌฌpไธชๅ…ƒ็ด ๏ผŒๅชๆœ‰ไธ‰็งๅฏ่ƒฝ๏ผŒ็ฌฌไธ€๏ผŒ่ฟ™ไธชๅฑžไบŽa[i]๏ผŒ็ฌฌไบŒ๏ผŒ่ฟ™ไธชๅฑžไบŽb[j],็ฌฌไธ‰ไธช๏ผŒ้ƒฝไธๅฑžไบŽ๏ผŒๅˆ™่ฟ”ๅ›ž; bool aB = false, bB = false; if (i >= 1) { if (a[i] == all[p]) aB = Arr[i - 1][p - i - 1]; } if (p - i - 1 >= 1) { if (b[p - i - 1] == all[p]) bB = Arr[i][p - i - 2]; } Arr[i][p - i - 1] = aB || bB; } ++p; } if (Arr[a.length() - 1][b.length() - 1]) cout << "yes" << endl; else cout << "no" << endl; return; } int main() { int n, caseNo = 0; cin >> n; while (n--) { cin >> a >> b >> all; cout << "Data set " << ++caseNo << ": "; if (a.length() + b.length() != all.length()) { cout << "no" << endl; continue; } memset(Arr, false, sizeof(Arr)); oper(); } }
23.722772
82
0.403172
Sean16SYSU
883c32cf672e71c390201dfc1368805b8698ec3b
3,441
cpp
C++
uart.cpp
LetsBuildRockets/Horizon-Tracker
dcd9c05bf41dce5a8c86a1fb97c59ff349bbb094
[ "MIT" ]
null
null
null
uart.cpp
LetsBuildRockets/Horizon-Tracker
dcd9c05bf41dce5a8c86a1fb97c59ff349bbb094
[ "MIT" ]
1
2017-07-25T18:53:21.000Z
2017-07-25T18:53:21.000Z
uart.cpp
LetsBuildRockets/Horizon-Tracker
dcd9c05bf41dce5a8c86a1fb97c59ff349bbb094
[ "MIT" ]
null
null
null
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> #include "horizonTracker.h" #define START_BYTE 0x12 const int DOUBLE_SIZE = sizeof(double); int uart0filestream = -1; void UARTInit(); int writeStartByte(); int writeAngleData(double&); int readAngleData(double&); int readStartByte(); void reverse_array(unsigned char*, int); void shiftLeft(unsigned char*, int, int); unsigned char rx_buffer[256] = { 0 }; int bytesInBuffer = 0; void UARTInit() { uart0filestream = open("/dev/ttyAMA0", O_RDWR | O_NOCTTY | O_NDELAY); if(uart0filestream == -1) { printf("Cant open UART\n"); } struct termios options; tcgetattr(uart0filestream, &options); options.c_cflag = B9600 | CS8 | CLOCAL | CREAD; options.c_iflag = IGNPAR; options.c_oflag = 0; options.c_lflag = 0; tcflush(uart0filestream, TCIFLUSH); tcsetattr(uart0filestream, TCSANOW, &options); } int writeStartByte() { if(mode == SERF) { printf("I'm not writing the start byte. I'm the SERF!"); } char const data[] = { START_BYTE }; if(uart0filestream) { int count = write(uart0filestream, &data, 1); if(count < 0) { printf("UART TX error\n"); return -1; } } } int writeAngleData(double & angle) { if(mode == MASTER) { printf("I'm not writing angle data. I'm the MASTER!\n"); return -1; } unsigned char data[DOUBLE_SIZE+1] = { 0 }; memcpy((&data+1), &angle, DOUBLE_SIZE); //unsigned char * const doubleData = reinterpret_cast<unsigned char * const>(&angle); if(uart0filestream) { int count = write(uart0filestream, &data, DOUBLE_SIZE+1); if(count < 0) { printf("UART TX error\n"); return -1; } } } int readAngleData(double & angle) { if(mode == SERF) { printf("I'm not reading angle data. I'm the SERF!\n"); return -1; } if(uart0filestream != -1) { while(bytesInBuffer<200) { if(read(uart0filestream, (void*)(rx_buffer+bytesInBuffer), 1) <= 0) { return -1; } else { bytesInBuffer++; if(rx_buffer[0]==0 && rx_buffer[8]== 0xc0) { memcpy(&angle, (&rx_buffer+1), DOUBLE_SIZE); printf("%f: %x %x %x %x %x %x %x %x\n", angle, rx_buffer[1], rx_buffer[2], rx_buffer[3], rx_buffer[4], rx_buffer[5], rx_buffer[6], rx_buffer[7], rx_buffer[8]); return 0; } } } if(bytesInBuffer >= 200) { printf("WE FILLED THE BUFFER!\n"); } } } int readStartByte() { if(mode == MASTER) { printf("I'm not reading start byte data. I'm the MASTER!\n"); return -1; } if(uart0filestream != -1) { unsigned char rx_buffer[256]; int rx_length = read(uart0filestream, (void*)rx_buffer, 255); if(rx_length <= 0) { // no data return 0; } else { if(rx_buffer[0] == START_BYTE) { return 1; } else { return 0; } } } } void shiftLeft(unsigned char * bytes, int length, int shift) { for(int j = 0; j < length-shift; j++) { bytes[j]=bytes[j+shift]; } for(int j = length-shift; j < length; j++) { bytes[j]=bytes[0]; } } void reverse_array( unsigned char array[], int arraylength ) { for (int i = 0; i < (arraylength / 2); i++) { unsigned char temporary = array[i]; array[i] = array[(arraylength - 1) - i]; array[(arraylength - 1) - i] = temporary; } }
20.981707
169
0.588782
LetsBuildRockets
883cdeb11215dbf64487270e662ec5a7af0cb5f5
2,628
cpp
C++
WKC/WebKit/WKC/WebCoreSupport/DropDownListClientWKC.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
15
2016-01-05T12:43:41.000Z
2022-03-15T10:34:47.000Z
WKC/WebKit/WKC/WebCoreSupport/DropDownListClientWKC.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
null
null
null
WKC/WebKit/WKC/WebCoreSupport/DropDownListClientWKC.cpp
s1rcheese/nintendo-3ds-internetbrowser-sourcecode
3dd05f035e0a5fc9723300623e9b9b359be64e11
[ "Unlicense" ]
2
2020-11-30T18:36:01.000Z
2021-02-05T23:20:24.000Z
/* * DropDownListClientWKC.cpp * * Copyright (c) 2010 ACCESS CO., LTD. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "DropDownListClientWKC.h" #include "WKCWebViewPrivate.h" #include "FrameView.h" #include "PopupMenuClient.h" #include "helpers/DropDownListClientIf.h" #include "helpers/privates/WKCFrameViewPrivate.h" #include "helpers/privates/WKCPopupMenuClientPrivate.h" // implementations namespace WKC { DropDownListClientWKC::DropDownListClientWKC(WKCWebViewPrivate* view) : m_view(view), m_appClient(0), m_destroyed(false) { } DropDownListClientWKC::~DropDownListClientWKC() { if (m_appClient && !m_destroyed) { m_destroyed = true; m_view->clientBuilders().deleteDropDownListClient(m_appClient); m_appClient = 0; } } DropDownListClientWKC* DropDownListClientWKC::create(WKCWebViewPrivate* view) { DropDownListClientWKC* self = 0; self = new DropDownListClientWKC(view); if (!self) return 0; if (!self->construct()) { delete self; return 0; } return self; } bool DropDownListClientWKC::construct() { m_appClient = m_view->clientBuilders().createDropDownListClient(m_view->parent()); if (!m_appClient) return false; return true; } void DropDownListClientWKC::show(const WebCore::IntRect& r, WebCore::FrameView* view, int index, WebCore::PopupMenuClient *client) { FrameViewPrivate v(view); PopupMenuClientPrivate pc(client); m_appClient->show(r, &v.wkc(), index, &pc.wkc()); } void DropDownListClientWKC::hide(WebCore::PopupMenuClient *client) { PopupMenuClientPrivate pc(client); m_appClient->hide(&pc.wkc()); } void DropDownListClientWKC::updateFromElement(WebCore::PopupMenuClient *client) { PopupMenuClientPrivate pc(client); m_appClient->updateFromElement(&pc.wkc()); } } // namespace
26.28
125
0.727169
s1rcheese
883feef17588c94e2aed6c4766dda148dcf4c32c
17,328
cpp
C++
libmuscle/cpp/src/libmuscle/data.cpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
null
null
null
libmuscle/cpp/src/libmuscle/data.cpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
null
null
null
libmuscle/cpp/src/libmuscle/data.cpp
DongweiYe/muscle3
0c2fcf5f62995b8639fc84ce1b983c8a8e6248d0
[ "Apache-2.0" ]
null
null
null
#include <cstring> #include <memory> #include <stdexcept> #include <string> #include <utility> #include <msgpack.hpp> #include "libmuscle/data.hpp" #include "libmuscle/mcp/data_pack.hpp" #include "libmuscle/mcp/ext_types.hpp" #include "ymmsl/identity.hpp" #include "ymmsl/settings.hpp" using libmuscle::impl::mcp::ExtTypeId; using ymmsl::SettingValue; using ymmsl::Reference; using ymmsl::Settings; namespace libmuscle { namespace impl { DataConstRef::DataConstRef() : mp_zones_(new std::vector<std::shared_ptr<msgpack::zone>>()) { mp_zones_->push_back(std::make_shared<msgpack::zone>()); mp_obj_ = zone_alloc_<msgpack::object>(); mp_obj_->type = msgpack::type::NIL; } DataConstRef::DataConstRef(bool value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(char const * const value) : DataConstRef() { char * buf = zone_alloc_<char>(strlen(value) + 1); strcpy(buf, value); *mp_obj_ << buf; } DataConstRef::DataConstRef(std::string const & value) : DataConstRef() { char * buf = zone_alloc_<char>(value.length() + 1); strncpy(buf, value.c_str(), value.length() + 1); *mp_obj_ << buf; } DataConstRef::DataConstRef(int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(long int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(long long int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(unsigned int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(unsigned long int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(unsigned long long int value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(float value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(double value) : DataConstRef() { *mp_obj_ << value; } DataConstRef::DataConstRef(SettingValue const & value) : DataConstRef() { if (value.is_a<std::string>()) { std::string val_str = value.as<std::string>(); char * buf = zone_alloc_<char>(val_str.length() + 1); strncpy(buf, val_str.c_str(), val_str.length() + 1); *mp_obj_ << buf; } else if (value.is_a<int64_t>()) *mp_obj_ << value.as<int64_t>(); else if (value.is_a<double>()) *mp_obj_ << value.as<double>(); else if (value.is_a<bool>()) *mp_obj_ << value.as<bool>(); else if (value.is_a<std::vector<double>>()) { auto vec = value.as<std::vector<double>>(); auto list = Data::nils(vec.size()); for (std::size_t i = 0u; i < vec.size(); ++i) list[i] = vec[i]; std::swap(list.mp_obj_, mp_obj_); std::swap(list.mp_zones_, mp_zones_); } else if (value.is_a<std::vector<std::vector<double>>>()) { auto vec = value.as<std::vector<std::vector<double>>>(); auto list = Data::nils(vec.size()); for (std::size_t i = 0u; i < vec.size(); ++i) { auto list2 = Data::nils(vec[i].size()); for (std::size_t j = 0u; j < vec[i].size(); ++j) list2[j] = vec[i][j]; list[i] = list2; } std::swap(list.mp_obj_, mp_obj_); std::swap(list.mp_zones_, mp_zones_); } } DataConstRef::DataConstRef(Settings const & settings) : DataConstRef() { auto settings_dict = Data::dict(); for (auto const & kv_pair: settings) settings_dict[static_cast<std::string>(kv_pair.first)] = kv_pair.second; msgpack::sbuffer buf; msgpack::pack(buf, settings_dict); char * zoned_mem = zone_alloc_<char>(buf.size() + 1); zoned_mem[0] = static_cast<char>(ExtTypeId::settings); memcpy(zoned_mem + 1, buf.data(), buf.size()); *mp_obj_ << msgpack::type::ext_ref(zoned_mem, buf.size() + 1); } void DataConstRef::reseat(DataConstRef const & target) { mp_zones_ = target.mp_zones_; mp_obj_ = target.mp_obj_; } template <> bool DataConstRef::is_a<bool>() const { return mp_obj_->type == msgpack::type::BOOLEAN; } template <> bool DataConstRef::is_a<char>() const { return (mp_obj_->type == msgpack::type::POSITIVE_INTEGER || mp_obj_->type == msgpack::type::NEGATIVE_INTEGER); } template <> bool DataConstRef::is_a<short int>() const { return (mp_obj_->type == msgpack::type::POSITIVE_INTEGER || mp_obj_->type == msgpack::type::NEGATIVE_INTEGER); } template <> bool DataConstRef::is_a<int>() const { return (mp_obj_->type == msgpack::type::POSITIVE_INTEGER || mp_obj_->type == msgpack::type::NEGATIVE_INTEGER); } template <> bool DataConstRef::is_a<long int>() const { return (mp_obj_->type == msgpack::type::POSITIVE_INTEGER || mp_obj_->type == msgpack::type::NEGATIVE_INTEGER); } template <> bool DataConstRef::is_a<long long int>() const { return (mp_obj_->type == msgpack::type::POSITIVE_INTEGER || mp_obj_->type == msgpack::type::NEGATIVE_INTEGER); } template <> bool DataConstRef::is_a<unsigned char>() const { return mp_obj_->type == msgpack::type::POSITIVE_INTEGER; } template <> bool DataConstRef::is_a<unsigned short int>() const { return mp_obj_->type == msgpack::type::POSITIVE_INTEGER; } template <> bool DataConstRef::is_a<unsigned int>() const { return mp_obj_->type == msgpack::type::POSITIVE_INTEGER; } template <> bool DataConstRef::is_a<unsigned long int>() const { return mp_obj_->type == msgpack::type::POSITIVE_INTEGER; } template <> bool DataConstRef::is_a<unsigned long long int>() const { return mp_obj_->type == msgpack::type::POSITIVE_INTEGER; } template <> bool DataConstRef::is_a<float>() const { return mp_obj_->type == msgpack::type::FLOAT32; } template <> bool DataConstRef::is_a<double>() const { return mp_obj_->type == msgpack::type::FLOAT64; } template <> bool DataConstRef::is_a<Settings>() const { return (mp_obj_->type == msgpack::type::EXT) && (mp_obj_->via.ext.type() == static_cast<int8_t>(ExtTypeId::settings)); } template <> bool DataConstRef::is_a<std::string>() const { return mp_obj_->type == msgpack::type::STR; } bool DataConstRef::is_nil() const { return mp_obj_->type == msgpack::type::NIL; } bool DataConstRef::is_a_dict() const { return mp_obj_->type == msgpack::type::MAP; } bool DataConstRef::is_a_list() const { return mp_obj_->type == msgpack::type::ARRAY; } bool DataConstRef::is_a_byte_array() const { return mp_obj_->type == msgpack::type::BIN; } template <> SettingValue DataConstRef::as<SettingValue>() const { DataConstRef const & self = *this; if (is_a<std::string>()) return as<std::string>(); else if (is_a<int64_t>()) return as<int64_t>(); else if (is_a<double>()) return as<double>(); else if (is_a<bool>()) return as<bool>(); else if (is_a_list()) { if (size() == 0u) return std::vector<double>(); else if (self[0].is_a<double>()) return as_vec_double_(); else if (self[0].is_a_list()) { std::vector<std::vector<double>> result; for (std::size_t i = 0u; i < size(); ++i) { if (self[i].is_a_list()) result.push_back(self[i].as_vec_double_()); else throw std::runtime_error("Found a list of something else" " than lists, which I cannot convert to a" " SettingValue."); } return result; } else throw std::runtime_error("Found a list of something else than" " lists, which I cannot convert to a SettingValue."); } else throw std::runtime_error("Tried to convert a DataConstRef or Data to" " a SettingValue, which it isn't. Did you receive data of a" " type you were not expecting?"); } // This uses as<SettingValue>, so has to be below it. template <> bool DataConstRef::is_a<SettingValue>() const { if (is_a<std::string>() || is_a<int64_t>() || is_a<double>() || is_a<bool>()) return true; // cheat, just try to convert and catch the exception // TODO: neater solution try { as<SettingValue>(); } catch (std::runtime_error const & e) { return false; } return true; } template <> Settings DataConstRef::as<Settings>() const { if (!is_a<Settings>()) throw std::runtime_error("Tried to convert a DataConstRef or Data to" " a Settings, which it isn't. Did you receive data of a type" " you were not expecting?"); auto ext = mp_obj_->as<msgpack::type::ext>(); auto oh = msgpack::unpack(ext.data(), ext.size()); if (oh.get().type != msgpack::type::MAP) throw std::runtime_error("Invalid Settings format. Bug in MUSCLE 3?"); Settings settings; auto zone = std::make_shared<msgpack::zone>(); Data settings_dict(mcp::unpack_data(zone, ext.data(), ext.size())); for (std::size_t i = 0u; i < settings_dict.size(); ++i) { Reference key(settings_dict.key(i)); auto val = settings_dict.value(i).as<SettingValue>(); settings[key] = val; } return settings; } std::size_t DataConstRef::size() const { if (is_a_dict()) return mp_obj_->via.map.size; else if (is_a_list()) return mp_obj_->via.array.size; else if (is_a_byte_array()) return mp_obj_->via.bin.size; else throw std::runtime_error("DataConstRef::size() called for an object that does" " not represent a list or dict"); } char const * DataConstRef::as_byte_array() const { if (!is_a_byte_array()) throw std::runtime_error("Tried to access as a byte array, but this is" " not a byte array."); return mp_obj_->via.bin.ptr; } DataConstRef DataConstRef::operator[](std::string const & key) const { if (mp_obj_->type == msgpack::type::MAP) { for (uint32_t i = 0; i < mp_obj_->via.map.size; ++i) { auto const & mkey = mp_obj_->via.map.ptr[i].key; if (mkey.type == msgpack::type::STR) if (mkey.via.str.size == key.size()) if (strncmp(mkey.via.str.ptr, key.data(), mkey.via.str.size) == 0) return DataConstRef(&(mp_obj_->via.map.ptr[i].val), mp_zones_); } throw std::out_of_range("Key " + key + " not found in map."); } throw std::runtime_error("Tried to look up a key, but this object is not a map."); } std::string DataConstRef::key(std::size_t i) const { if (mp_obj_->type == msgpack::type::MAP) { if (i < size()) return DataConstRef(&(mp_obj_->via.map.ptr[i].key), mp_zones_).as<std::string>(); else throw std::out_of_range("Index too large for this map."); } throw std::runtime_error("Tried to look up a key, but this object is not a map."); } DataConstRef DataConstRef::value(std::size_t i) const { if (mp_obj_->type == msgpack::type::MAP) { if (i < size()) return DataConstRef(&(mp_obj_->via.map.ptr[i].val), mp_zones_); else throw std::out_of_range("Index too large for this map."); } throw std::runtime_error("Tried to look up a value, but this object is not a map."); } DataConstRef DataConstRef::operator[](std::size_t index) const { if (mp_obj_->type == msgpack::type::ARRAY) if (index < mp_obj_->via.array.size) return DataConstRef(&(mp_obj_->via.array.ptr[index]), mp_zones_); else throw std::out_of_range("Array index out of range."); else throw std::runtime_error("Tried to index an object that is not a list."); } DataConstRef::DataConstRef( msgpack::object * obj, std::shared_ptr<msgpack::zone> const & zone) : mp_zones_(new std::vector<std::shared_ptr<msgpack::zone>>()) , mp_obj_(obj) { mp_zones_->push_back(zone); } DataConstRef::DataConstRef( msgpack::object * obj, Zones_ const & zones) : mp_zones_(zones) , mp_obj_(obj) {} DataConstRef::DataConstRef(std::shared_ptr<msgpack::zone> const & zone) : mp_zones_(new std::vector<std::shared_ptr<msgpack::zone>>{zone}) , mp_obj_(zone_alloc_<msgpack::object>()) { mp_obj_->type = msgpack::type::NIL; } std::vector<double> DataConstRef::as_vec_double_() const { std::vector<double> result; DataConstRef const & self = *this; for (std::size_t i = 0u; i < size(); ++i) { if (self[i].is_a<double>()) result.push_back(self[i].as<double>()); else throw std::runtime_error("Found a list containing" " something else than a double."); } return result; } Data Data::dict() { Data dict; dict.init_dict_(0u); return dict; } Data Data::list() { Data list; list.init_list_(0u); return list; } Data Data::nils(std::size_t size) { Data list; list.init_list_(size); for (std::size_t i = 0u; i < size; ++i) list.mp_obj_->via.array.ptr[i].type = msgpack::type::NIL; return list; } Data Data::byte_array(uint32_t size) { Data bytes; bytes.mp_obj_->type = msgpack::type::BIN; bytes.mp_obj_->via.bin.size = size; bytes.mp_obj_->via.bin.ptr = bytes.zone_alloc_<char>(size); return bytes; } Data Data::byte_array(char const * buf, uint32_t size) { Data bytes; bytes.mp_obj_->type = msgpack::type::BIN; bytes.mp_obj_->via.bin.size = size; bytes.mp_obj_->via.bin.ptr = buf; return bytes; } Data & Data::operator=(Data const & rhs) { if (mp_obj_ != rhs.mp_obj_) { *mp_obj_ = *rhs.mp_obj_; // We can't overwrite mp_zones_ here, because mp_obj_ is allocated on // one of them, and we don't know which. So we just append, which is // suboptimal because it may keep objects alive that are no longer // reachable. Consider a separate shared_ptr to the zone that mp_obj_ // is on (in a separate member), so that we can safely overwrite // mp_zones_. if (mp_zones_ != rhs.mp_zones_) mp_zones_->insert(mp_zones_->end(), rhs.mp_zones_->cbegin(), rhs.mp_zones_->cend()); } return *this; } Data Data::operator[](std::string const & key) { if (mp_obj_->type == msgpack::type::MAP) { for (uint32_t i = 0; i < mp_obj_->via.map.size; ++i) { auto const & mkey = mp_obj_->via.map.ptr[i].key; if (mkey.type == msgpack::type::STR) if (mkey.via.str.size == key.size()) if (strncmp(mkey.via.str.ptr, key.data(), mkey.via.str.size) == 0) return Data(&(mp_obj_->via.map.ptr[i].val), mp_zones_); } // key is not in here, reallocate and add msgpack::object_kv * new_ptr = zone_alloc_<msgpack::object_kv>(mp_obj_->via.map.size + 1); for (uint32_t i = 0u; i < mp_obj_->via.map.size; ++i) new_ptr[i] = mp_obj_->via.map.ptr[i]; mp_obj_->via.map.ptr = new_ptr; ++mp_obj_->via.map.size; // add new key auto & new_kv = mp_obj_->via.map.ptr[mp_obj_->via.map.size - 1]; new_kv.key = msgpack::object(key, *mp_zones_->front()); new_kv.val = msgpack::object(); return Data(&new_kv.val, mp_zones_); } throw std::runtime_error("Tried to look up a key, but this object is not a map."); } Data Data::value(std::size_t i) const { if (mp_obj_->type == msgpack::type::MAP) { if (i < size()) return Data(&(mp_obj_->via.map.ptr[i].val), mp_zones_); else throw std::out_of_range("Index too large for this map."); } throw std::runtime_error("Tried to look up a value, but this object is not a map."); } Data Data::operator[](std::size_t index) { if (mp_obj_->type == msgpack::type::ARRAY) { if (index < mp_obj_->via.array.size) return Data(&(mp_obj_->via.array.ptr[index]), mp_zones_); throw std::out_of_range("Tried to access index " + std::to_string(index) + " on an array of size " + std::to_string(mp_obj_->via.array.size)); } throw std::runtime_error("Tried to index an object that is not a list."); } char * Data::as_byte_array() { if (!is_a_byte_array()) throw std::runtime_error("Tried to access as a byte array, but this is" " not a byte array."); // MessagePack defines this const, probably because it doesn't need to // modify the data. We use this for our own purposes however, and need to // be able to write data into the buffer. So we cast the const away. return const_cast<char *>(mp_obj_->via.bin.ptr); } void Data::init_dict_(uint32_t size) { mp_obj_->type = msgpack::type::MAP; mp_obj_->via.map.size = size; mp_obj_->via.map.ptr = zone_alloc_<msgpack::object_kv>(size); } void Data::init_list_(uint32_t size) { mp_obj_->type = msgpack::type::ARRAY; mp_obj_->via.array.size = size; mp_obj_->via.array.ptr = zone_alloc_<msgpack::object>(size); } } } // namespace libmuscle::impl
30.83274
98
0.608033
DongweiYe
8841271f3d9d1e0dba1b1d24e485b6a4f5d8a1f7
6,836
cpp
C++
software/PSGTools/src/stream/Stream.cpp
Yevgeniy-Olexandrenko/ay-ym-usb-streamer
8dbc3972fb2cb653fa17d62d1481708ef2b534ae
[ "MIT" ]
null
null
null
software/PSGTools/src/stream/Stream.cpp
Yevgeniy-Olexandrenko/ay-ym-usb-streamer
8dbc3972fb2cb653fa17d62d1481708ef2b534ae
[ "MIT" ]
null
null
null
software/PSGTools/src/stream/Stream.cpp
Yevgeniy-Olexandrenko/ay-ym-usb-streamer
8dbc3972fb2cb653fa17d62d1481708ef2b534ae
[ "MIT" ]
null
null
null
#include <iomanip> #include <sstream> #include "Stream.h" //////////////////////////////////////////////////////////////////////////////// namespace { const int k_prefDurationMM = 4; const int k_prefDurationSS = 0; const int k_maxExtraLoops = 3; } Stream::Stream() : info(*this) , frames(*this) , loop(*this) , playback(*this) { } std::string Stream::property(Property property) const { std::stringstream stream; switch (property) { case Property::Title: stream << info.title(); break; case Property::Artist: stream << info.artist(); break; case Property::Comment: stream << info.comment(); break; case Property::Type: stream << info.type(); break;; case Property::Chip: return chip.toString(); case Property::Frames: stream << frames.count(); if (loop.available()) stream << " -> " << loop.frameId(); stream << " @ " << playback.frameRate() << " Hz"; break; case Property::Duration: int hh0 = 0, mm0 = 0, ss0 = 0, ms0 = 0; int hh1 = 0, mm1 = 0, ss1 = 0, ms1 = 0; playback.realDuration(hh0, mm0, ss0); playback.fakeDuration(hh1, mm1, ss1); stream << std::setfill('0') << std::setw(2) << hh0 << ':' << std::setfill('0') << std::setw(2) << mm0 << ':' << std::setfill('0') << std::setw(2) << ss0; if (hh0 != hh1 || mm0 != mm1 || ss0 != ss1) { stream << " ("; stream << std::setfill('0') << std::setw(2) << hh1 << ':' << std::setfill('0') << std::setw(2) << mm1 << ':' << std::setfill('0') << std::setw(2) << ss1; stream << ')'; } break; } return stream.str(); } //////////////////////////////////////////////////////////////////////////////// Stream::Info::Info(Stream& stream) : Delegate(stream) { } void Stream::Info::title(const std::string& title) { m_title = title; } const std::string& Stream::Info::title() const { return m_title; } bool Stream::Info::titleKnown() const { return !m_title.empty(); } void Stream::Info::artist(const std::string& artist) { m_artist = artist; } const std::string& Stream::Info::artist() const { return m_artist; } bool Stream::Info::artistKnown() const { return !m_artist.empty(); } void Stream::Info::comment(const std::string& comment) { m_comment = comment; } const std::string& Stream::Info::comment() const { return m_comment; } bool Stream::Info::commentKnown() const { return !m_comment.empty(); } void Stream::Info::type(const std::string& type) { m_type = type; } const std::string& Stream::Info::type() const { return m_type; } //////////////////////////////////////////////////////////////////////////////// Stream::Frames::Frames(Stream& stream) : Delegate(stream) { } void Stream::Frames::add(const Frame& frame) { if (count() < 100000) m_frames.push_back(frame); } const Frame& Stream::Frames::get(FrameId id) const { return m_frames[id]; } uint32_t Stream::Frames::count() const { return (uint32_t)m_frames.size(); } FrameId Stream::Frames::lastFrameId() const { return count() - 1; } bool Stream::Frames::available() const { return (count() > 0); } //////////////////////////////////////////////////////////////////////////////// Stream::Loop::Loop(Stream& stream) : Delegate(stream) , m_frameId(0) , m_extraLoops(0) { } void Stream::Loop::frameId(FrameId id) { m_frameId = id; UpdateLoopFrameChanges(); ComputeExtraLoops(); } FrameId Stream::Loop::frameId() const { return (m_frameId > 2 ? m_frameId : m_stream.frames.count()); } uint32_t Stream::Loop::framesCount() const { return m_stream.frames.count() - frameId(); } int Stream::Loop::extraLoops() const { return m_extraLoops; } bool Stream::Loop::available() const { return (framesCount() >= (m_stream.frames.count() / 2)); } void Stream::Loop::ComputeExtraLoops() { m_extraLoops = 0; if (available()) { uint32_t frameCount = m_stream.frames.count(); uint32_t maxPlaybackFrames = (k_prefDurationMM * 60 + k_prefDurationSS) * m_stream.playback.frameRate(); if (maxPlaybackFrames > frameCount) { m_extraLoops = (maxPlaybackFrames - frameCount) / framesCount(); m_extraLoops = std::min(m_extraLoops, k_maxExtraLoops); } } } void Stream::Loop::UpdateLoopFrameChanges() { if (available()) { uint8_t loopFrameData, lastFrameData; const Frame& lastFrame = m_stream.frames.get(m_stream.frames.lastFrameId()); Frame& loopFrame = const_cast<Frame&>(m_stream.frames.get(frameId())); for (uint8_t reg = 0; reg < 16; ++reg) { if (!loopFrame.IsChanged(0, reg)) { loopFrameData = loopFrame.Read(0, reg); lastFrameData = lastFrame.Read(0, reg); if (loopFrameData != lastFrameData) loopFrame.Write(0, reg, loopFrameData); } if (!loopFrame.IsChanged(1, reg)) { loopFrameData = loopFrame.Read(1, reg); lastFrameData = lastFrame.Read(1, reg); if (loopFrameData != lastFrameData) loopFrame.Write(1, reg, loopFrameData); } } } } //////////////////////////////////////////////////////////////////////////////// Stream::Playback::Playback(Stream& stream) : Delegate(stream) , m_frameRate(0) { } const Frame& Stream::Playback::getFrame(FrameId id) const { uint32_t frameCount = m_stream.frames.count(); if (id >= frameCount) { id = m_stream.loop.frameId() + ((id - frameCount) % m_stream.loop.framesCount()); } return m_stream.frames.get(id); } uint32_t Stream::Playback::framesCount() const { return m_stream.frames.count() + m_stream.loop.extraLoops() * m_stream.loop.framesCount(); } FrameId Stream::Playback::lastFrameId() const { return framesCount() - 1; } void Stream::Playback::frameRate(FrameRate frameRate) { m_frameRate = frameRate; } FrameRate Stream::Playback::frameRate() const { return m_frameRate; } void Stream::Playback::realDuration(int& hh, int& mm, int& ss, int& ms) const { ComputeDuration(m_stream.frames.count(), hh, mm, ss, ms); } void Stream::Playback::realDuration(int& hh, int& mm, int& ss) const { ComputeDuration(m_stream.frames.count(), hh, mm, ss); } void Stream::Playback::fakeDuration(int& hh, int& mm, int& ss, int& ms) const { ComputeDuration(framesCount(), hh, mm, ss, ms); } void Stream::Playback::fakeDuration(int& hh, int& mm, int& ss) const { ComputeDuration(framesCount(), hh, mm, ss); } void Stream::Playback::ComputeDuration(uint32_t frameCount, int& hh, int& mm, int& ss, int& ms) const { uint32_t duration = (frameCount * 1000) / frameRate(); ms = duration % 1000; duration /= 1000; ss = duration % 60; duration /= 60; mm = duration % 60; duration /= 60; hh = duration; } void Stream::Playback::ComputeDuration(uint32_t frameCount, int& hh, int& mm, int& ss) const { uint32_t duration = (((frameCount * 1000) / frameRate()) + 500) / 1000; ss = duration % 60; duration /= 60; mm = duration % 60; duration /= 60; hh = duration; } ////////////////////////////////////////////////////////////////////////////////
20.715152
106
0.612639
Yevgeniy-Olexandrenko
8846a385575a01108e04b50b3adf275d94905646
699
cpp
C++
codechef/January_Lunchtime_2015/1/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
13
2015-06-07T09:26:26.000Z
2019-05-01T13:23:38.000Z
codechef/January_Lunchtime_2015/1/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
null
null
null
codechef/January_Lunchtime_2015/1/main.cpp
seirion/code
3b8bf79764107255185061cec33decbc2235d03a
[ "Apache-2.0" ]
4
2016-03-05T06:21:05.000Z
2017-02-17T15:34:18.000Z
// http://www.codechef.com/LTIME20/problems/LCH15JAB // Piece of cake #include <cstdio> #include <cstring> #include <algorithm> #include <functional> using namespace std; int ch[26]; // a ~ z bool solve() { memset(ch, 0, sizeof(int) * 26); char buffer[51]; gets(buffer); int i, size = strlen(buffer); for (i = 0; i < size; i++) { int index = buffer[i] - 'a'; ch[index]++; } sort(ch, ch+26, greater<int>()); int sum = 0; for (i = 1; i < 26; i++) { sum += ch[i]; } return (ch[0] == sum); } int main() { int t; scanf("%d\n", &t); for (int i = 0; i < t; i++) { printf("%s\n", solve() ? "YES" : "NO"); } }
18.394737
52
0.493562
seirion
884804d07363685bcfc8865b97576945117d0d05
1,010
hpp
C++
TextEditor/Huffman/LeafNode.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
null
null
null
TextEditor/Huffman/LeafNode.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
42
2019-09-27T16:46:52.000Z
2019-12-06T18:39:18.000Z
TextEditor/Huffman/LeafNode.hpp
itravers/CS211-TextEditor
47ddf2745f54ae826a96209eb767fe8280f4ce30
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Created Date: November 7th, 2019 * Created By: Isaac Travers * ContextMenu.hpp: This is a leaf node for a Huffman tree Node * This code is pretty much straight copied from the class textbook, however I do modify things. *******************************************************************************/ #ifndef LEAF_NODE_HPP #define LEAF_NODE_HPP #include "HuffNode.hpp" template <typename E> class LeafNode: public HuffNode<E> { private: E it; //value int wgt; //weight public: //constructor LeafNode(const E& val, int freq) { it = val; wgt = freq; } int weight() { return wgt; } E val() { return it; } bool isLeaf() { return true; } void buildEncodingTable(unordered_map<char, string>& encodingTable, string currentPrefix = "") { char value = val(); (encodingTable)[value] = currentPrefix; //encodingTable. } }; #endif // endif LEAF_NODE_HPP
21.489362
97
0.552475
itravers
884bf045075828ee2b8eabc2225f65f9f0406a02
8,271
cpp
C++
Plugins/PLFrontendActiveX/src/PixelLightCtrl.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/PLFrontendActiveX/src/PixelLightCtrl.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/PLFrontendActiveX/src/PixelLightCtrl.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
// PixelLightCtrl.cpp : Implementation of PixelLightCtrl #include <PLCore/Runtime.h> #include <PLCore/Tools/Timing.h> #include "stdafx.h" #include "PixelLightCtrl.h" // PixelLightCtrl PixelLightCtrl::PixelLightCtrl() : m_bFrontendApplicationInitialized(false), m_bMouseVisible(true), m_bTrapMouse(false), m_cFrontend(m_cFrontendContext, *this) { // We *must* have a real window for this control m_bWindowOnly = true; // Scan PL-runtime directory for compatible plugins and load them in as well as scan for compatible data and register it PLCore::Runtime::ScanDirectoryPluginsAndData(); // Do the frontend life cycle thing - let the world know that we have been created FrontendImpl::OnCreate(); } PixelLightCtrl::~PixelLightCtrl() { // Do the frontend life cycle thing - de-initialize if (m_bFrontendApplicationInitialized) { FrontendImpl::OnPause(); FrontendImpl::OnStop(); } // Do the frontend life cycle thing - let the world know that we're going to die FrontendImpl::OnDestroy(); } //[-------------------------------------------------------] //[ Private virtual PLCore::Impl functions ] //[-------------------------------------------------------] int PixelLightCtrl::Run(const PLCore::String &sExecutableFilename, const PLCore::Array<PLCore::String> &lstArguments) { // Error, this frontend implementation is run and controlled by another application this frontend is embedded into return -1; } PLCore::handle PixelLightCtrl::GetNativeWindowHandle() const { return reinterpret_cast<PLCore::handle>(m_hFrontendWnd); } void PixelLightCtrl::Redraw() { // Redraw control RedrawWindow(); } void PixelLightCtrl::Ping() { // Check if we're allowed to perform an update right now if (PLCore::Timing::GetInstance()->Update()) { // Let the frontend update it's states FrontendImpl::OnUpdate(); } } PLCore::String PixelLightCtrl::GetTitle() const { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into return ""; } void PixelLightCtrl::SetTitle(const PLCore::String &sTitle) { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } int PixelLightCtrl::GetX() const { // Get window rect (in screen coordinates) RECT sRect; GetWindowRect(&sRect); return sRect.left; } int PixelLightCtrl::GetY() const { // Get window rect (in screen coordinates) RECT sRect; GetWindowRect(&sRect); return sRect.top; } PLCore::uint32 PixelLightCtrl::GetWidth() const { // Request a relative window position (always (0, 0)) and size (equal to (width, height)) RECT sRect; GetClientRect(&sRect); return sRect.right; } PLCore::uint32 PixelLightCtrl::GetHeight() const { // Request a relative window position (always (0, 0)) and size (equal to (width, height)) RECT sRect; GetClientRect(&sRect); return sRect.bottom; } void PixelLightCtrl::GetWindowPositionSize(int &nX, int &nY, PLCore::uint32 &nWidth, PLCore::uint32 &nHeight) const { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into // Set known default values nX = nY = nWidth = nHeight = 0; } void PixelLightCtrl::SetWindowPositionSize(int nX, int nY, PLCore::uint32 nWidth, PLCore::uint32 nHeight) { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } bool PixelLightCtrl::GetToggleFullscreenMode() const { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into return false; } void PixelLightCtrl::SetToggleFullscreenMode(bool bToggleFullscreenMode) { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } bool PixelLightCtrl::GetFullscreenAltTab() const { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into return false; } void PixelLightCtrl::SetFullscreenAltTab(bool bAllowed) { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } bool PixelLightCtrl::IsFullscreen() const { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into return false; } void PixelLightCtrl::SetFullscreen(bool bFullscreen) { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } void PixelLightCtrl::RefreshFullscreen() { // Ignore - This frontend implementation is run and controlled by another application this frontend is embedded into } bool PixelLightCtrl::IsMouseOver() const { // Get the mouse cursor's position (in screen coordinates) POINT sPOINT; if (GetCursorPos(&sPOINT)) { // Get window rectangle (in screen coordinates) RECT sRect; if (GetWindowRect(&sRect)) { // Is the mouse cursor within the window rectangle? return (PtInRect(&sRect, sPOINT) == TRUE); } } // Error! return false; } int PixelLightCtrl::GetMousePositionX() const { if (m_hFrontendWnd) { // Get the mouse cursor's position (in screen coordinates) POINT sPoint; ::GetCursorPos(&sPoint); // Get the mouse cursor position inside this window if (::ScreenToClient(m_hFrontendWnd, &sPoint)) return sPoint.x; } // Error! return -1; } int PixelLightCtrl::GetMousePositionY() const { if (m_hFrontendWnd) { // Get the mouse cursor's position (in screen coordinates) POINT sPoint; ::GetCursorPos(&sPoint); // Get the mouse cursor position inside this window if (::ScreenToClient(m_hFrontendWnd, &sPoint)) return sPoint.y; } // Error! return -1; } bool PixelLightCtrl::IsMouseVisible() const { return m_bMouseVisible; } void PixelLightCtrl::SetMouseVisible(bool bVisible) { // Backup the state m_bMouseVisible = bVisible; // Set mouse cursor visibility if (bVisible) { // Show mouse cursor while (ShowCursor(true) < 0) ; // Do nothing } else { // Hide mouse cursor while (ShowCursor(false) >= 0) ; // Do nothing } } void PixelLightCtrl::SetTrapMouse(bool bTrap) { if (m_hFrontendWnd) { // Trap mouse? if (bTrap) { // Get window rect (in screen coordinates) RECT sRect; GetWindowRect(&sRect); // Trap mouse ClipCursor(&sRect); } else { // Untrap mouse ClipCursor(nullptr); } // Backup the state m_bTrapMouse = bTrap; } } //[-------------------------------------------------------] //[ Private functions ] //[-------------------------------------------------------] /** * @brief * Update trap mouse if required */ void PixelLightCtrl::UpdateTrapMouse() { // Trap mouse? if (m_bTrapMouse) { // Get window rect (in screen coordinates) RECT sRect; ::GetWindowRect(m_hFrontendWnd, &sRect); // Trap mouse within up-to-date widget rectangle ::ClipCursor(&sRect); } } HRESULT PixelLightCtrl::OnDrawAdvanced(ATL_DRAWINFO &di) { // Let the frontend draw into it's window FrontendImpl::OnDraw(); // Ping Ping(); // Done return S_OK; } LRESULT PixelLightCtrl::OnCreate(UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled) { // Save window and device context handles m_hFrontendWnd = m_hWnd; { // Let the world know that this frontend is now going to run const PLCore::String sExecutableFilename; const PLCore::Array<PLCore::String> lstArguments; FrontendImpl::OnRun(sExecutableFilename, lstArguments); } // Do the frontend life cycle thing - initialize if (FrontendImpl::OnStart()) { FrontendImpl::OnResume(); // Frontend application successfully initialized m_bFrontendApplicationInitialized = true; } // Done return 0; } LRESULT PixelLightCtrl::OnEraseBkgnd(UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled) { // No background, please return 0; } // [TODO] React on move messages // Update trap mouse if required // UpdateTrapMouse(); // [TODO] Drag and drop of files LRESULT PixelLightCtrl::OnSize(UINT nMsg, WPARAM wParam, LPARAM lParam, BOOL &bHandled) { // Update trap mouse if required UpdateTrapMouse(); // Inform that the window size has been changed FrontendImpl::OnSize(); // Done return 0; }
24.543027
121
0.711764
ktotheoz
9c0092ada30fe3987bc67380e473f1bbc38f75b1
10,922
cc
C++
wrappers/8.1.1/vtkUnstructuredGridHomogeneousRayIntegratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/8.1.1/vtkUnstructuredGridHomogeneousRayIntegratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/8.1.1/vtkUnstructuredGridHomogeneousRayIntegratorWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkUnstructuredGridVolumeRayIntegratorWrap.h" #include "vtkUnstructuredGridHomogeneousRayIntegratorWrap.h" #include "vtkObjectBaseWrap.h" #include "vtkVolumeWrap.h" #include "vtkDataArrayWrap.h" #include "vtkDoubleArrayWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkUnstructuredGridHomogeneousRayIntegratorWrap::ptpl; VtkUnstructuredGridHomogeneousRayIntegratorWrap::VtkUnstructuredGridHomogeneousRayIntegratorWrap() { } VtkUnstructuredGridHomogeneousRayIntegratorWrap::VtkUnstructuredGridHomogeneousRayIntegratorWrap(vtkSmartPointer<vtkUnstructuredGridHomogeneousRayIntegrator> _native) { native = _native; } VtkUnstructuredGridHomogeneousRayIntegratorWrap::~VtkUnstructuredGridHomogeneousRayIntegratorWrap() { } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkUnstructuredGridHomogeneousRayIntegrator").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("UnstructuredGridHomogeneousRayIntegrator").ToLocalChecked(), ConstructorGetter); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkUnstructuredGridVolumeRayIntegratorWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkUnstructuredGridVolumeRayIntegratorWrap::ptpl)); tpl->SetClassName(Nan::New("VtkUnstructuredGridHomogeneousRayIntegratorWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "GetTransferFunctionTableSize", GetTransferFunctionTableSize); Nan::SetPrototypeMethod(tpl, "getTransferFunctionTableSize", GetTransferFunctionTableSize); Nan::SetPrototypeMethod(tpl, "Initialize", Initialize); Nan::SetPrototypeMethod(tpl, "initialize", Initialize); Nan::SetPrototypeMethod(tpl, "Integrate", Integrate); Nan::SetPrototypeMethod(tpl, "integrate", Integrate); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetTransferFunctionTableSize", SetTransferFunctionTableSize); Nan::SetPrototypeMethod(tpl, "setTransferFunctionTableSize", SetTransferFunctionTableSize); #ifdef VTK_NODE_PLUS_VTKUNSTRUCTUREDGRIDHOMOGENEOUSRAYINTEGRATORWRAP_INITPTPL VTK_NODE_PLUS_VTKUNSTRUCTUREDGRIDHOMOGENEOUSRAYINTEGRATORWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkUnstructuredGridHomogeneousRayIntegrator> native = vtkSmartPointer<vtkUnstructuredGridHomogeneousRayIntegrator>::New(); VtkUnstructuredGridHomogeneousRayIntegratorWrap* obj = new VtkUnstructuredGridHomogeneousRayIntegratorWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::GetTransferFunctionTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); int r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetTransferFunctionTableSize(); info.GetReturnValue().Set(Nan::New(r)); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::Initialize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkVolumeWrap::ptpl))->HasInstance(info[0])) { VtkVolumeWrap *a0 = ObjectWrap::Unwrap<VtkVolumeWrap>(info[0]->ToObject()); if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataArrayWrap::ptpl))->HasInstance(info[1])) { VtkDataArrayWrap *a1 = ObjectWrap::Unwrap<VtkDataArrayWrap>(info[1]->ToObject()); if(info.Length() != 2) { Nan::ThrowError("Too many parameters."); return; } native->Initialize( (vtkVolume *) a0->native.GetPointer(), (vtkDataArray *) a1->native.GetPointer() ); return; } } Nan::ThrowError("Parameter mismatch"); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::Integrate(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); size_t i; if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkDoubleArrayWrap::ptpl))->HasInstance(info[0])) { VtkDoubleArrayWrap *a0 = ObjectWrap::Unwrap<VtkDoubleArrayWrap>(info[0]->ToObject()); if(info.Length() > 1 && info[1]->IsObject() && (Nan::New(VtkDataArrayWrap::ptpl))->HasInstance(info[1])) { VtkDataArrayWrap *a1 = ObjectWrap::Unwrap<VtkDataArrayWrap>(info[1]->ToObject()); if(info.Length() > 2 && info[2]->IsObject() && (Nan::New(VtkDataArrayWrap::ptpl))->HasInstance(info[2])) { VtkDataArrayWrap *a2 = ObjectWrap::Unwrap<VtkDataArrayWrap>(info[2]->ToObject()); if(info.Length() > 3 && info[3]->IsFloat32Array()) { v8::Local<v8::Float32Array>a3(v8::Local<v8::Float32Array>::Cast(info[3]->ToObject())); if( a3->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->Integrate( (vtkDoubleArray *) a0->native.GetPointer(), (vtkDataArray *) a1->native.GetPointer(), (vtkDataArray *) a2->native.GetPointer(), (float *)(a3->Buffer()->GetContents().Data()) ); return; } else if(info.Length() > 3 && info[3]->IsArray()) { v8::Local<v8::Array>a3(v8::Local<v8::Array>::Cast(info[3]->ToObject())); float b3[4]; if( a3->Length() < 4 ) { Nan::ThrowError("Array too short."); return; } for( i = 0; i < 4; i++ ) { if( !a3->Get(i)->IsNumber() ) { Nan::ThrowError("Array contents invalid."); return; } b3[i] = a3->Get(i)->NumberValue(); } if(info.Length() != 4) { Nan::ThrowError("Too many parameters."); return; } native->Integrate( (vtkDoubleArray *) a0->native.GetPointer(), (vtkDataArray *) a1->native.GetPointer(), (vtkDataArray *) a2->native.GetPointer(), b3 ); return; } } } } Nan::ThrowError("Parameter mismatch"); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); vtkUnstructuredGridHomogeneousRayIntegrator * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkUnstructuredGridHomogeneousRayIntegratorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkUnstructuredGridHomogeneousRayIntegratorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkUnstructuredGridHomogeneousRayIntegratorWrap *w = new VtkUnstructuredGridHomogeneousRayIntegratorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectBaseWrap::ptpl))->HasInstance(info[0])) { VtkObjectBaseWrap *a0 = ObjectWrap::Unwrap<VtkObjectBaseWrap>(info[0]->ToObject()); vtkUnstructuredGridHomogeneousRayIntegrator * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObjectBase *) a0->native.GetPointer() ); VtkUnstructuredGridHomogeneousRayIntegratorWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkUnstructuredGridHomogeneousRayIntegratorWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkUnstructuredGridHomogeneousRayIntegratorWrap *w = new VtkUnstructuredGridHomogeneousRayIntegratorWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkUnstructuredGridHomogeneousRayIntegratorWrap::SetTransferFunctionTableSize(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkUnstructuredGridHomogeneousRayIntegratorWrap *wrapper = ObjectWrap::Unwrap<VtkUnstructuredGridHomogeneousRayIntegratorWrap>(info.Holder()); vtkUnstructuredGridHomogeneousRayIntegrator *native = (vtkUnstructuredGridHomogeneousRayIntegrator *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsInt32()) { if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetTransferFunctionTableSize( info[0]->Int32Value() ); return; } Nan::ThrowError("Parameter mismatch"); }
37.792388
166
0.745102
axkibe
9c061979bbec064e83aff57d0853987d44de0a6a
1,064
cpp
C++
AtCoder/abc174/C.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
AtCoder/abc174/C.cpp
iamsuryakant/competitive-programming
413000f5bc4a627407e1335c35dcdbee516e8cc1
[ "MIT" ]
null
null
null
AtCoder/abc174/C.cpp
iamsuryakant/competitive-programming
413000f5bc4a627407e1335c35dcdbee516e8cc1
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
#pragma GCC optimize("O3") #pragma GCC optimize("Ofast") #pragma GCC optimize("unroll-loops") #pragma GCC optimize("no-stack-protector") #pragma GCC optimize("fast-math") #pragma GCC optimize("trapv") #pragma GCC target("sse4") #include <bits/stdc++.h> #include <ext/pb_ds/tree_policy.hpp> #include <ext/pb_ds/assoc_container.hpp> using namespace std; using namespace __gnu_pbds; #define deb(x) cout << #x << " is " << x << "\n" #define int long long #define mod 1000000007LL #define PI acosl(-1) template <typename T> using ordered_set = tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; void solve() { int k; cin >> k; int val = 7 % k; for (int i = 1; i < 1e7; i++) { if (val == 0) { cout << i; return; } val = ((val * 10) + 7) % k; } cout << -1; } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); // #ifndef ONLINE_JUDGE // freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); // #endif solve(); return 0; }
20.862745
97
0.615602
Code-With-Aagam
9c088c7bfa64c721caf8eb5b214e9a367f2d6b47
320
cpp
C++
LiteCppDB/LiteCppDB.Tests/CustomTypeTest.cpp
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
2
2019-07-18T06:30:33.000Z
2020-01-23T17:40:36.000Z
LiteCppDB/LiteCppDB.Tests/CustomTypeTest.cpp
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
null
null
null
LiteCppDB/LiteCppDB.Tests/CustomTypeTest.cpp
pnadan/LiteCppDB
cb17db1ea6d82e0c1e669b4d70271dcf9c03d1a2
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "CustomTypeTest.h" using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace LiteCppDB_Tests { TEST_CLASS(CustomTypeTest_Test) { public: TEST_METHOD(Mapper___CustomType_Test) { const bool m_TestImplemented = false; Assert::IsTrue(m_TestImplemented); } }; }
16.842105
62
0.765625
pnadan
9c08ccfabfeb695b16ea3960f099286b27dbfdfd
1,110
cpp
C++
DreamTools/src/Platform/Windows/WindowsInput.cpp
ASoldo/DreamTools
9c80e25f6569482b9c29d4950ec7deb523b241f9
[ "Apache-2.0" ]
null
null
null
DreamTools/src/Platform/Windows/WindowsInput.cpp
ASoldo/DreamTools
9c80e25f6569482b9c29d4950ec7deb523b241f9
[ "Apache-2.0" ]
null
null
null
DreamTools/src/Platform/Windows/WindowsInput.cpp
ASoldo/DreamTools
9c80e25f6569482b9c29d4950ec7deb523b241f9
[ "Apache-2.0" ]
null
null
null
#include "dtpch.h" #include "../../DreamTools/Core/Input.h" #include "../../DreamTools/Core/Application.h" #include <../vendor/GLFW/include/GLFW/glfw3.h> namespace DreamTools { bool Input::IsKeyPressed(KeyCode keycode) { auto window =static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetKey(window, static_cast<uint32_t>(keycode)); return state == GLFW_PRESS || state == GLFW_REPEAT; } bool Input::IsMouseButtonPressed(MouseCode button) { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); auto state = glfwGetMouseButton(window, static_cast<uint32_t>(button)); return state == GLFW_PRESS; } float Input::GetMouseX() { auto [x, y] = GetMousePosition(); return x; } float Input::GetMouseY() { auto [x, y] = GetMousePosition(); return y; } std::pair<float, float> Input::GetMousePosition() { auto window = static_cast<GLFWwindow*>(Application::Get().GetWindow().GetNativeWindow()); double xPos, yPos; glfwGetCursorPos(window, &xPos, &yPos); return { (float)xPos, (float)yPos }; } }
26.428571
91
0.703604
ASoldo
9c0c873586be5f45a800af5c071a6d2c315057ed
21,931
cpp
C++
3rd-party/tbb/src/test/test_flow_graph_priorities.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
3,457
2018-06-09T15:36:42.000Z
2020-06-01T22:09:25.000Z
3rd-party/tbb/src/test/test_flow_graph_priorities.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
235
2020-06-02T01:26:49.000Z
2022-03-31T01:35:31.000Z
3rd-party/tbb/src/test/test_flow_graph_priorities.cpp
drobison00/taskflow
9415c3b68fd050889f57412394933e94b74755e0
[ "MIT" ]
426
2018-06-06T18:01:16.000Z
2020-06-01T05:26:17.000Z
/* Copyright (c) 2018-2020 Intel Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "harness_defs.h" #if __TBB_PREVIEW_FLOW_GRAPH_PRIORITIES #define TBB_DEPRECATED_INPUT_NODE_BODY __TBB_CPF_BUILD #include "harness_graph.h" #include "harness_barrier.h" #include "tbb/flow_graph.h" #include "tbb/tbb_thread.h" #include "tbb/parallel_for.h" #include "tbb/concurrent_queue.h" #include <vector> #include <cstdlib> using namespace tbb::flow; tbb::atomic<unsigned> g_task_num; void spin_for( double delta ) { tbb::tick_count start = tbb::tick_count::now(); while( (tbb::tick_count::now() - start).seconds() < delta ) ; } namespace PriorityNodesTakePrecedence { struct TaskInfo { TaskInfo() : my_priority(-1), my_task_index(-1) {} TaskInfo( int priority, int task_index ) : my_priority(priority), my_task_index(task_index) {} int my_priority; int my_task_index; }; std::vector<TaskInfo> g_task_info; tbb::atomic<bool> g_work_submitted; const unsigned node_num = 100; const unsigned start_index = node_num / 3; const unsigned end_index = node_num * 2 / 3; tbb::atomic<unsigned> g_priority_task_index; void body_func( int priority ) { while( !g_work_submitted ) __TBB_Yield(); int current_task_index = g_task_num++; if( priority ) g_task_info[g_priority_task_index++] = TaskInfo( priority, current_task_index ); } struct FunctionBody { FunctionBody( int priority ) : my_priority( priority ) {} int operator()( int msg ) const { body_func( my_priority ); return msg; } private: int my_priority; }; typedef multifunction_node< int,tuple<int> > multi_node; struct MultifunctionBody { MultifunctionBody( int priority ) : my_priority( priority ) {} void operator()( int msg, multi_node::output_ports_type& op ) const { body_func( my_priority ); get<0>(op).try_put( msg ); } private: int my_priority; }; template<typename NodeType, typename BodyType> NodeType* node_creator( graph& g, unsigned index ) { if( start_index <= index && index < end_index ) return new NodeType( g, unlimited, BodyType(index), node_priority_t(index) ); else return new NodeType( g, unlimited, BodyType(0) ); } struct passthru_body { continue_msg operator()( int ) const { return continue_msg(); } }; template<typename NodeType> sender<int>& get_sender( NodeType& node ) { return node; } template<> sender<int>& get_sender<multi_node>( multi_node& node ) { return output_port<0>(node); } template<typename NodeType, typename NodeTypeCreator, typename NodePortRetriever> void test_node( NodeTypeCreator node_creator_func, NodePortRetriever get_sender ) { graph g; broadcast_node<int> bn(g); function_node<int> tn(g, unlimited, passthru_body()); // Using pointers to nodes to avoid errors on compilers, which try to generate assignment // operator for the nodes std::vector<NodeType*> nodes; for( unsigned i = 0; i < node_num; ++i ) { nodes.push_back( node_creator_func(g, i) ); make_edge( bn, *nodes.back() ); make_edge( get_sender(*nodes.back()), tn ); } const size_t repeats = 50; const size_t priority_nodes_num = end_index - start_index; size_t internal_order_failures = 0; size_t global_order_failures = 0; for( size_t repeat = 0; repeat < repeats; ++repeat ) { g_work_submitted = false; g_task_num = g_priority_task_index = 0; g_task_info.clear(); g_task_info.resize( priority_nodes_num ); bn.try_put( 0 ); // Setting of the flag is based on the knowledge that the calling thread broadcasts the message // to successor nodes, that is spawns tasks. Thus, this makes this test to be a whitebox test to // some extent. g_work_submitted = true; g.wait_for_all(); ASSERT( g_priority_task_index == g_task_info.size(), "Incorrect number of tasks with priority" ); bool found_max = false; bool found_min = false; for( unsigned i = 0; i < g_priority_task_index/2; ++i ) { if( g_task_info[i].my_priority == int(end_index-1) ) found_max = true; if( g_task_info[g_priority_task_index-1-i].my_priority == int(start_index) ) found_min = true; } if( !found_min || !found_max ) ++internal_order_failures; for( unsigned i = 0; i < g_priority_task_index; ++i ) { // This check might fail because priorities do not guarantee ordering, i.e. assumption // that all priority nodes should increment the task counter before any subsequent // no-priority node is not correct. In the worst case, a thread that took a priority // node might be preempted and become the last to increment the counter. That's why the // test passing is based on statistics, which could be affected by machine overload // unfortunately. // TODO: make the test deterministic. if( g_task_info[i].my_task_index > int(priority_nodes_num) + MaxThread ) ++global_order_failures; } } float failure_ratio = float(internal_order_failures) / float(repeats); ASSERT( failure_ratio <= 0.3f, "Nodes with priorities executed in wrong order among each other too frequently." ); failure_ratio = float(global_order_failures) / float(repeats*priority_nodes_num); ASSERT( failure_ratio <= 0.1f, "Nodes with priorities executed in wrong order too frequently over non-prioritized nodes." ); for( size_t i = 0; i < nodes.size(); ++i ) delete nodes[i]; } void test( int num_threads ) { REMARK( "Testing execution of nodes with priority takes precedence (num_threads=%d) - ", num_threads ); tbb::task_scheduler_init init(num_threads); test_node< function_node<int,int> >( &node_creator<function_node<int,int>, FunctionBody>, &get_sender< function_node<int,int> > ); test_node<multi_node>( &node_creator<multi_node, MultifunctionBody>, &get_sender< multi_node > ); REMARK( "done\n" ); } } /* namespace PriorityNodesTakePrecedence */ namespace ThreadsEagerReaction { using Harness::SpinBarrier; enum task_type_t { no_task, regular_task, async_task }; struct profile_t { task_type_t task_type; unsigned global_task_id; double elapsed; }; std::vector<unsigned> g_async_task_ids; typedef unsigned data_type; typedef async_node<data_type, data_type> async_node_type; typedef multifunction_node< data_type, tuple<data_type, data_type> > decider_node_type; struct AsyncActivity { typedef async_node_type::gateway_type gateway_type; struct work_type { data_type input; gateway_type* gateway; }; bool done; tbb::concurrent_queue<work_type> my_queue; tbb::tbb_thread my_service_thread; struct ServiceThreadFunc { SpinBarrier& my_barrier; ServiceThreadFunc(SpinBarrier& barrier) : my_barrier(barrier) {} void operator()(AsyncActivity* activity) { while (!activity->done) { work_type work; while (activity->my_queue.try_pop(work)) { g_async_task_ids.push_back( ++g_task_num ); work.gateway->try_put(work.input); work.gateway->release_wait(); my_barrier.wait(); } } } }; void stop_and_wait() { done = true; my_service_thread.join(); } void submit(data_type input, gateway_type* gateway) { work_type work = { input, gateway }; gateway->reserve_wait(); my_queue.push(work); } AsyncActivity(SpinBarrier& barrier) : done(false), my_service_thread(ServiceThreadFunc(barrier), this) {} }; struct StartBody { bool has_run; #if TBB_DEPRECATED_INPUT_NODE_BODY bool operator()(data_type& input) { if (has_run) return false; else { input = 1; has_run = true; return true; } } #else data_type operator()(tbb::flow_control& fc) { if (has_run){ fc.stop(); return data_type(); } has_run = true; return 1; } #endif StartBody() : has_run(false) {} }; struct ParallelForBody { SpinBarrier& my_barrier; const data_type& my_input; ParallelForBody(SpinBarrier& barrier, const data_type& input) : my_barrier(barrier), my_input(input) {} void operator()(const data_type&) const { my_barrier.wait(); ++g_task_num; } }; struct CpuWorkBody { SpinBarrier& my_barrier; const int my_tasks_count; data_type operator()(const data_type& input) { tbb::parallel_for(0, my_tasks_count, ParallelForBody(my_barrier, input), tbb::simple_partitioner()); return input; } CpuWorkBody(SpinBarrier& barrier, int tasks_count) : my_barrier(barrier), my_tasks_count(tasks_count) {} }; struct DeciderBody { const data_type& my_limit; DeciderBody( const data_type& limit ) : my_limit( limit ) {} void operator()(data_type input, decider_node_type::output_ports_type& ports) { if (input < my_limit) get<0>(ports).try_put(input + 1); } }; struct AsyncSubmissionBody { AsyncActivity* my_activity; void operator()(data_type input, async_node_type::gateway_type& gateway) { my_activity->submit(input, &gateway); } AsyncSubmissionBody(AsyncActivity* activity) : my_activity(activity) {} }; void test( int num_threads ) { REMARK( "Testing threads react eagerly on asynchronous tasks (num_threads=%d) - ", num_threads ); if( num_threads == tbb::task_scheduler_init::default_num_threads() ) { // one thread is required for asynchronous compute resource REMARK("skipping test since it is designed to work on less number of threads than " "hardware concurrency allows\n"); return; } const unsigned cpu_threads = unsigned(num_threads); const unsigned cpu_tasks_per_thread = 4; const unsigned nested_cpu_tasks = cpu_tasks_per_thread * cpu_threads; const unsigned async_subgraph_reruns = 8; const unsigned cpu_subgraph_reruns = 2; SpinBarrier barrier(cpu_threads + /*async thread=*/1); g_task_num = 0; g_async_task_ids.clear(); g_async_task_ids.reserve(async_subgraph_reruns); tbb::task_scheduler_init init(cpu_threads); AsyncActivity activity(barrier); graph g; input_node<data_type> starter_node(g, StartBody()); function_node<data_type, data_type> cpu_work_node( g, unlimited, CpuWorkBody(barrier, nested_cpu_tasks)); decider_node_type cpu_restarter_node(g, unlimited, DeciderBody(cpu_subgraph_reruns)); async_node_type async_node(g, unlimited, AsyncSubmissionBody(&activity)); decider_node_type async_restarter_node( g, unlimited, DeciderBody(async_subgraph_reruns), node_priority_t(1) ); make_edge(starter_node, cpu_work_node); make_edge(cpu_work_node, cpu_restarter_node); make_edge(output_port<0>(cpu_restarter_node), cpu_work_node); make_edge(starter_node, async_node); make_edge(async_node, async_restarter_node); make_edge(output_port<0>(async_restarter_node), async_node); starter_node.activate(); g.wait_for_all(); activity.stop_and_wait(); const size_t async_task_num = size_t(async_subgraph_reruns); ASSERT( g_async_task_ids.size() == async_task_num, "Incorrect number of async tasks." ); unsigned max_span = unsigned(2 * cpu_threads + 1); for( size_t idx = 1; idx < async_task_num; ++idx ) { ASSERT( g_async_task_ids[idx] - g_async_task_ids[idx-1] <= max_span, "Async tasks were not able to interfere with CPU tasks." ); } REMARK("done\n"); } } /* ThreadsEagerReaction */ namespace LimitingExecutionToPriorityTask { enum work_type_t { NONPRIORITIZED_WORK, PRIORITIZED_WORK }; struct execution_tracker_t { execution_tracker_t() { reset(); } void reset() { prioritized_work_submitter = tbb::tbb_thread::id(); prioritized_work_started = false; prioritized_work_finished = false; prioritized_work_interrupted = false; } tbb::tbb_thread::id prioritized_work_submitter; bool prioritized_work_started; bool prioritized_work_finished; bool prioritized_work_interrupted; } exec_tracker; template<work_type_t work_type> void do_node_work( int work_size ); template<work_type_t> void do_nested_work( const tbb::tbb_thread::id& tid, const tbb::blocked_range<int>& subrange ); template<work_type_t work_type> struct CommonBody { CommonBody() : my_body_size( 0 ) { } CommonBody( int body_size ) : my_body_size( body_size ) { } continue_msg operator()( const continue_msg& msg ) const { do_node_work<work_type>(my_body_size); return msg; } void operator()( const tbb::blocked_range<int>& subrange ) const { do_nested_work<work_type>( /*tid=*/tbb::this_tbb_thread::get_id(), subrange ); } int my_body_size; }; template<work_type_t work_type> void do_node_work(int work_size) { tbb::parallel_for( tbb::blocked_range<int>(0, work_size), CommonBody<work_type>(), tbb::simple_partitioner() ); } template<work_type_t> void do_nested_work( const tbb::tbb_thread::id& tid, const tbb::blocked_range<int>& /*subrange*/ ) { // This is non-prioritized work... if( exec_tracker.prioritized_work_submitter != tid ) return; // ...being executed by the thread that initially started prioritized one... ASSERT( exec_tracker.prioritized_work_started, "Prioritized work should have been started by that time." ); // ...prioritized work has been started already... if( exec_tracker.prioritized_work_finished ) return; // ...but has not been finished yet exec_tracker.prioritized_work_interrupted = true; } struct IsolationFunctor { int work_size; IsolationFunctor(int ws) : work_size(ws) {} void operator()() const { tbb::parallel_for( tbb::blocked_range<int>(0, work_size), CommonBody<PRIORITIZED_WORK>(), tbb::simple_partitioner() ); } }; template<> void do_node_work<PRIORITIZED_WORK>(int work_size) { exec_tracker.prioritized_work_submitter = tbb::this_tbb_thread::get_id(); exec_tracker.prioritized_work_started = true; tbb::this_task_arena::isolate( IsolationFunctor(work_size) ); exec_tracker.prioritized_work_finished = true; } template<> void do_nested_work<PRIORITIZED_WORK>( const tbb::tbb_thread::id& tid, const tbb::blocked_range<int>& /*subrange*/ ) { if( exec_tracker.prioritized_work_submitter == tid ) { ASSERT( !exec_tracker.prioritized_work_interrupted, "Thread was not fully devoted to processing of prioritized task." ); } else { // prolong processing of prioritized work so that the thread that started // prioritized work has higher probability to help with non-prioritized one. spin_for(0.1); } } // Using pointers to nodes to avoid errors on compilers, which try to generate assignment operator // for the nodes typedef std::vector< continue_node<continue_msg>* > nodes_container_t; void create_nodes( nodes_container_t& nodes, graph& g, int num, int body_size ) { for( int i = 0; i < num; ++i ) nodes.push_back( new continue_node<continue_msg>( g, CommonBody<NONPRIORITIZED_WORK>( body_size ) ) ); } void test( int num_threads ) { REMARK( "Testing limit execution to priority tasks (num_threads=%d) - ", num_threads ); tbb::task_scheduler_init init( num_threads ); const int nodes_num = 100; const int priority_node_position_part = 10; const int pivot = nodes_num / priority_node_position_part; const int nodes_in_lane = 3 * num_threads; const int small_problem_size = 100; const int large_problem_size = 1000; graph g; nodes_container_t nodes; create_nodes( nodes, g, pivot, large_problem_size ); nodes.push_back( new continue_node<continue_msg>( g, CommonBody<PRIORITIZED_WORK>(small_problem_size), node_priority_t(1) ) ); create_nodes( nodes, g, nodes_num - pivot - 1, large_problem_size ); broadcast_node<continue_msg> bn(g); for( int i = 0; i < nodes_num; ++i ) if( i % nodes_in_lane == 0 ) make_edge( bn, *nodes[i] ); else make_edge( *nodes[i-1], *nodes[i] ); exec_tracker.reset(); bn.try_put( continue_msg() ); g.wait_for_all(); for( size_t i = 0; i < nodes.size(); ++i ) delete nodes[i]; REMARK( "done\n" ); } } /* namespace LimitingExecutionToPriorityTask */ #include "tbb/task_arena.h" namespace NestedCase { using tbb::task_arena; struct ResetGraphFunctor { graph& my_graph; ResetGraphFunctor(graph& g) : my_graph(g) {} // copy constructor to please some old compilers ResetGraphFunctor(const ResetGraphFunctor& rgf) : my_graph(rgf.my_graph) {} void operator()() const { my_graph.reset(); } }; struct InnerBody { continue_msg operator()( const continue_msg& ) const { return continue_msg(); } }; struct OuterBody { int my_max_threads; task_arena& my_inner_arena; OuterBody( int max_threads, task_arena& inner_arena ) : my_max_threads(max_threads), my_inner_arena(inner_arena) {} // copy constructor to please some old compilers OuterBody( const OuterBody& rhs ) : my_max_threads(rhs.my_max_threads), my_inner_arena(rhs.my_inner_arena) {} int operator()( const int& ) { graph inner_graph; continue_node<continue_msg> start_node(inner_graph, InnerBody()); continue_node<continue_msg> mid_node1(inner_graph, InnerBody(), node_priority_t(5)); continue_node<continue_msg> mid_node2(inner_graph, InnerBody()); continue_node<continue_msg> end_node(inner_graph, InnerBody(), node_priority_t(15)); make_edge( start_node, mid_node1 ); make_edge( mid_node1, end_node ); make_edge( start_node, mid_node2 ); make_edge( mid_node2, end_node ); my_inner_arena.execute( ResetGraphFunctor(inner_graph) ); start_node.try_put( continue_msg() ); inner_graph.wait_for_all(); return 13; } }; void execute_outer_graph( bool same_arena, task_arena& inner_arena, int max_threads, graph& outer_graph, function_node<int,int>& start_node ) { if( same_arena ) { start_node.try_put( 42 ); outer_graph.wait_for_all(); return; } for( int num_threads = 1; num_threads <= max_threads; ++num_threads ) { inner_arena.initialize( num_threads ); start_node.try_put( 42 ); outer_graph.wait_for_all(); inner_arena.terminate(); } } void test_in_arena( int max_threads, task_arena& outer_arena, task_arena& inner_arena ) { graph outer_graph; const unsigned num_outer_nodes = 10; const size_t concurrency = unlimited; std::vector< function_node<int,int>* > outer_nodes; for( unsigned node_index = 0; node_index < num_outer_nodes; ++node_index ) { internal::node_priority_t priority = internal::no_priority; if( node_index == num_outer_nodes / 2 ) priority = 10; outer_nodes.push_back( new function_node<int,int>( outer_graph, concurrency, OuterBody(max_threads, inner_arena), priority ) ); } for( unsigned node_index1 = 0; node_index1 < num_outer_nodes; ++node_index1 ) for( unsigned node_index2 = node_index1+1; node_index2 < num_outer_nodes; ++node_index2 ) make_edge( *outer_nodes[node_index1], *outer_nodes[node_index2] ); bool same_arena = &outer_arena == &inner_arena; for( int num_threads = 1; num_threads <= max_threads; ++num_threads ) { REMARK( "Testing nested nodes with specified priority in %s arenas, num_threads=%d) - ", same_arena? "same" : "different", num_threads ); outer_arena.initialize( num_threads ); outer_arena.execute( ResetGraphFunctor(outer_graph) ); execute_outer_graph( same_arena, inner_arena, max_threads, outer_graph, *outer_nodes[0] ); outer_arena.terminate(); REMARK( "done\n" ); } for( size_t i = 0; i < outer_nodes.size(); ++i ) delete outer_nodes[i]; } void test( int max_threads ) { tbb::task_scheduler_init init( max_threads ); task_arena outer_arena; task_arena inner_arena; test_in_arena( max_threads, outer_arena, outer_arena ); test_in_arena( max_threads, outer_arena, inner_arena ); } } int TestMain() { if( MinThread < 1 ) { REPORT( "Number of threads must be positive\n" ); return Harness::Skipped; } for( int p = MinThread; p <= MaxThread; ++p ) { PriorityNodesTakePrecedence::test( p ); ThreadsEagerReaction::test( p ); LimitingExecutionToPriorityTask::test( p ); } NestedCase::test( MaxThread ); return Harness::Done; } #else /* __TBB_PREVIEW_FLOW_GRAPH_PRIORITIES */ #define HARNESS_SKIP_TEST 1 #include "harness.h" #endif /* __TBB_PREVIEW_FLOW_GRAPH_PRIORITIES */
35.834967
108
0.675345
drobison00
9c0f65a49da5a04fdcebf5cd4ed0af3ab95362ec
442
cpp
C++
02_HSI_PLL/main.cpp
AVilezhaninov/STM32F103RB
3aca98801c73841c1c14677ea3495008b9673690
[ "MIT" ]
1
2020-08-03T16:27:08.000Z
2020-08-03T16:27:08.000Z
02_HSI_PLL/main.cpp
AVilezhaninov/STM32F103RB
3aca98801c73841c1c14677ea3495008b9673690
[ "MIT" ]
null
null
null
02_HSI_PLL/main.cpp
AVilezhaninov/STM32F103RB
3aca98801c73841c1c14677ea3495008b9673690
[ "MIT" ]
1
2021-07-30T14:42:34.000Z
2021-07-30T14:42:34.000Z
/* CMSIS */ #include "CMSIS\Device\stm32f103xb.h" /* User */ #include "user\RCC.h" /******************************************************************************/ /* Main ***********************************************************************/ /******************************************************************************/ int main() { rcc::InitSystemClock(); /* Config SYSCLK for 64 MHz with HSI and PLL */ while (1) { ; } }
26
80
0.276018
AVilezhaninov
9c10497e59a766a2679d3ff4018e3f0ff05aba9f
5,058
cpp
C++
Engine/Scene/Logic/SceneLogicMainThread.cpp
azhirnov/GraphicsGenFramework-modular
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
12
2017-12-23T14:24:57.000Z
2020-10-02T19:52:12.000Z
Engine/Scene/Logic/SceneLogicMainThread.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
Engine/Scene/Logic/SceneLogicMainThread.cpp
azhirnov/ModularGraphicsFramework
348be601f1991f102defa0c99250529f5e44c4d3
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) Zhirnov Andrey. For more information see 'LICENSE.txt' #include "Engine/Scene/Public/Scene.h" #include "Engine/Scene/Impl/SceneObjectConstructor.h" #include "Engine/Scene/Impl/BaseSceneModule.h" namespace Engine { namespace Scene { // // Scene Logic Main Thread // class SceneLogicMainThread final : public Module { // types protected: using SupportedMessages_t = MessageListFrom< SceneMsg::GetScenePrivateClasses >; using SupportedEvents_t = Module::SupportedEvents_t; // constants private: static const TypeIdList _eventTypes; // variables private: // methods public: SceneLogicMainThread (UntypedID_t, GlobalSystemsRef, const CreateInfo::SceneLogic &); ~SceneLogicMainThread (); // message handlers protected: bool _Link (const ModuleMsg::Link &); bool _Compose (const ModuleMsg::Compose &); bool _Delete (const ModuleMsg::Delete &); bool _AddToManager (const ModuleMsg::AddToManager &); bool _RemoveFromManager (const ModuleMsg::RemoveFromManager &); bool _GetScenePrivateClasses (const SceneMsg::GetScenePrivateClasses &); }; //----------------------------------------------------------------------------- const TypeIdList SceneLogicMainThread::_eventTypes{ UninitializedT< SupportedEvents_t >() }; /* ================================================= constructor ================================================= */ SceneLogicMainThread::SceneLogicMainThread (UntypedID_t id, GlobalSystemsRef gs, const CreateInfo::SceneLogic &ci) : Module( gs, ModuleConfig{ id, 1 }, &_eventTypes ) { SetDebugName( "SceneLogicMainThread" ); _SubscribeOnMsg( this, &SceneLogicMainThread::_OnModuleAttached_Impl ); _SubscribeOnMsg( this, &SceneLogicMainThread::_OnModuleDetached_Impl ); _SubscribeOnMsg( this, &SceneLogicMainThread::_AttachModule_Impl ); _SubscribeOnMsg( this, &SceneLogicMainThread::_DetachModule_Impl ); _SubscribeOnMsg( this, &SceneLogicMainThread::_FindModule_Empty ); _SubscribeOnMsg( this, &SceneLogicMainThread::_ModulesDeepSearch_Empty ); _SubscribeOnMsg( this, &SceneLogicMainThread::_Update_Empty ); _SubscribeOnMsg( this, &SceneLogicMainThread::_Link ); _SubscribeOnMsg( this, &SceneLogicMainThread::_Compose ); _SubscribeOnMsg( this, &SceneLogicMainThread::_Delete ); _SubscribeOnMsg( this, &SceneLogicMainThread::_AddToManager ); _SubscribeOnMsg( this, &SceneLogicMainThread::_RemoveFromManager ); _SubscribeOnMsg( this, &SceneLogicMainThread::_OnManagerChanged_Empty ); _SubscribeOnMsg( this, &SceneLogicMainThread::_GetScenePrivateClasses ); ASSERT( _ValidateMsgSubscriptions< SupportedMessages_t >() ); _AttachSelfToManager( null, SceneManagerModuleID, false ); } /* ================================================= destructor ================================================= */ SceneLogicMainThread::~SceneLogicMainThread () { } /* ================================================= _Link ================================================= */ bool SceneLogicMainThread::_Link (const ModuleMsg::Link &msg) { if ( _IsComposedOrLinkedState( GetState() ) ) return true; // already linked CHECK_ERR( _IsInitialState( GetState() ) ); // TODO return Module::_Link_Impl( msg ); } /* ================================================= _Compose ================================================= */ bool SceneLogicMainThread::_Compose (const ModuleMsg::Compose &msg) { if ( _IsComposedState( GetState() ) ) return true; // already composed CHECK_ERR( GetState() == EState::Linked ); // TODO return _DefCompose( true ); } /* ================================================= _Delete ================================================= */ bool SceneLogicMainThread::_Delete (const ModuleMsg::Delete &msg) { //TODO( "" ); return Module::_Delete_Impl( msg ); } /* ================================================= _AddToManager ================================================= */ bool SceneLogicMainThread::_AddToManager (const ModuleMsg::AddToManager &msg) { // TODO return true; } /* ================================================= _RemoveFromManager ================================================= */ bool SceneLogicMainThread::_RemoveFromManager (const ModuleMsg::RemoveFromManager &msg) { // TODO return true; } /* ================================================= _GetScenePrivateClasses ================================================= */ bool SceneLogicMainThread::_GetScenePrivateClasses (const SceneMsg::GetScenePrivateClasses &msg) { msg.result.Set({ }); // TODO return true; } //----------------------------------------------------------------------------- /* ================================================= CreateSceneLogic ================================================= */ ModulePtr SceneObjectConstructor::CreateSceneLogic (ModuleMsg::UntypedID_t id, GlobalSystemsRef gs, const CreateInfo::SceneLogic &ci) { return New< SceneLogicMainThread >( id, gs, ci ); } } // Scene } // Engine
26.904255
135
0.583432
azhirnov
9c10728d10c4f399ddbd15b50b7d51ef40418fe2
6,239
cpp
C++
src/SHA3.cpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
src/SHA3.cpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
src/SHA3.cpp
Jonas4420/Crypto
4fda1854c838407e6cbfb0ffaf862609eaac203a
[ "MIT" ]
null
null
null
#include "crypto/SHA3.hpp" #include <cstring> #if defined(_MSC_VER) || defined(__WATCOMC__) #define UL64(x) x##ui64 #else #define UL64(x) x##ULL #endif #define GET_UINT64(n, b, i) \ { \ (n) = ((uint64_t)(b)[(i) ] ) \ | ((uint64_t)(b)[(i) + 1] << 8) \ | ((uint64_t)(b)[(i) + 2] << 16) \ | ((uint64_t)(b)[(i) + 3] << 24) \ | ((uint64_t)(b)[(i) + 4] << 32) \ | ((uint64_t)(b)[(i) + 5] << 40) \ | ((uint64_t)(b)[(i) + 6] << 48) \ | ((uint64_t)(b)[(i) + 7] << 56); \ } namespace Crypto { SHA3::SHA3(std::size_t digest_sz) : digest_sz(digest_sz), r(200 - 2 * digest_sz) { // Assert that no overflow occures for r if ( 200 <= 2 * digest_sz ) { throw SHA3::Exception("Invalid digest length"); } // Prerequesit for HMAC if ( r <= digest_sz ) { throw SHA3::Exception("Invalid digest length"); } reset(); } SHA3::~SHA3(void) { reset(); } void SHA3::update(const uint8_t *input, std::size_t input_sz) { std::size_t fill; if ( (NULL == input) || (0 == input_sz) ) { return; } while ( input_sz >= (fill = r - buffer_sz) ) { absorb(input, fill); keccakf(state); buffer_sz = 0; input += fill; input_sz -= fill; } if ( input_sz > 0 ) { absorb(input, input_sz); } } void SHA3::finish(uint8_t *output) { uint8_t pad[200]; std::size_t pad_sz = r - buffer_sz; memset(pad, 0x00, pad_sz); pad[0] = 0x06; pad[pad_sz - 1] ^= 0x80; update(pad, pad_sz); memcpy(output, state, digest_sz); reset(); } void SHA3::reset(void) { buffer_sz = 0; zeroize(state, sizeof(state)); } void SHA3::keccakf(uint64_t S[25]) { uint64_t Aba, Abe, Abi, Abo, Abu; uint64_t Aga, Age, Agi, Ago, Agu; uint64_t Aka, Ake, Aki, Ako, Aku; uint64_t Ama, Ame, Ami, Amo, Amu; uint64_t Asa, Ase, Asi, Aso, Asu; uint64_t BCa, BCe, BCi, BCo, BCu; uint64_t Da, De, Di, Do, Du; uint64_t Eba, Ebe, Ebi, Ebo, Ebu; uint64_t Ega, Ege, Egi, Ego, Egu; uint64_t Eka, Eke, Eki, Eko, Eku; uint64_t Ema, Eme, Emi, Emo, Emu; uint64_t Esa, Ese, Esi, Eso, Esu; Aba = S[ 0]; Abe = S[ 5]; Abi = S[10]; Abo = S[15]; Abu = S[20]; Aga = S[ 1]; Age = S[ 6]; Agi = S[11]; Ago = S[16]; Agu = S[21]; Aka = S[ 2]; Ake = S[ 7]; Aki = S[12]; Ako = S[17]; Aku = S[22]; Ama = S[ 3]; Ame = S[ 8]; Ami = S[13]; Amo = S[18]; Amu = S[23]; Asa = S[ 4]; Ase = S[ 9]; Asi = S[14]; Aso = S[19]; Asu = S[24]; for ( std::size_t r = 0 ; r < 24 ; ++r ) { // Theta BCa = Aba ^ Abe ^ Abi ^ Abo ^ Abu; BCe = Aga ^ Age ^ Agi ^ Ago ^ Agu; BCi = Aka ^ Ake ^ Aki ^ Ako ^ Aku; BCo = Ama ^ Ame ^ Ami ^ Amo ^ Amu; BCu = Asa ^ Ase ^ Asi ^ Aso ^ Asu; Da = BCu ^ ROL(BCe, 1); Aba ^= Da; Abe ^= Da; Abi ^= Da; Abo ^= Da; Abu ^= Da; De = BCa ^ ROL(BCi, 1); Aga ^= De; Age ^= De; Agi ^= De; Ago ^= De; Agu ^= De; Di = BCe ^ ROL(BCo, 1); Aka ^= Di; Ake ^= Di; Aki ^= Di; Ako ^= Di; Aku ^= Di; Do = BCi ^ ROL(BCu, 1); Ama ^= Do; Ame ^= Do; Ami ^= Do; Amo ^= Do; Amu ^= Do; Du = BCo ^ ROL(BCa, 1); Asa ^= Du; Ase ^= Du; Asi ^= Du; Aso ^= Du; Asu ^= Du; // Rho and Pi Eba = Aba; Ebe = ROL(Ama, 28); Ebi = ROL(Aga, 1); Ebo = ROL(Asa, 27); Ebu = ROL(Aka, 62); Ega = ROL(Age, 44); Ege = ROL(Ase, 20); Egi = ROL(Ake, 6); Ego = ROL(Abe, 36); Egu = ROL(Ame, 55); Eka = ROL(Aki, 43); Eke = ROL(Abi, 3); Eki = ROL(Ami, 25); Eko = ROL(Agi, 10); Eku = ROL(Asi, 39); Ema = ROL(Amo, 21); Eme = ROL(Ago, 45); Emi = ROL(Aso, 8); Emo = ROL(Ako, 15); Emu = ROL(Abo, 41); Esa = ROL(Asu, 14); Ese = ROL(Aku, 61); Esi = ROL(Abu, 18); Eso = ROL(Amu, 56); Esu = ROL(Agu, 2); // Chi Aba = Eba ^ ((~Ega) & Eka); Abe = Ebe ^ ((~Ege) & Eke); Abi = Ebi ^ ((~Egi) & Eki); Abo = Ebo ^ ((~Ego) & Eko); Abu = Ebu ^ ((~Egu) & Eku); Aga = Ega ^ ((~Eka) & Ema); Age = Ege ^ ((~Eke) & Eme); Agi = Egi ^ ((~Eki) & Emi); Ago = Ego ^ ((~Eko) & Emo); Agu = Egu ^ ((~Eku) & Emu); Aka = Eka ^ ((~Ema) & Esa); Ake = Eke ^ ((~Eme) & Ese); Aki = Eki ^ ((~Emi) & Esi); Ako = Eko ^ ((~Emo) & Eso); Aku = Eku ^ ((~Emu) & Esu); Ama = Ema ^ ((~Esa) & Eba); Ame = Eme ^ ((~Ese) & Ebe); Ami = Emi ^ ((~Esi) & Ebi); Amo = Emo ^ ((~Eso) & Ebo); Amu = Emu ^ ((~Esu) & Ebu); Asa = Esa ^ ((~Eba) & Ega); Ase = Ese ^ ((~Ebe) & Ege); Asi = Esi ^ ((~Ebi) & Egi); Aso = Eso ^ ((~Ebo) & Ego); Asu = Esu ^ ((~Ebu) & Egu); // Iota Aba ^= RC[r]; } S[ 0] = Aba; S[ 5] = Abe; S[10] = Abi; S[15] = Abo; S[20] = Abu; S[ 1] = Aga; S[ 6] = Age; S[11] = Agi; S[16] = Ago; S[21] = Agu; S[ 2] = Aka; S[ 7] = Ake; S[12] = Aki; S[17] = Ako; S[22] = Aku; S[ 3] = Ama; S[ 8] = Ame; S[13] = Ami; S[18] = Amo; S[23] = Amu; S[ 4] = Asa; S[ 9] = Ase; S[14] = Asi; S[19] = Aso; S[24] = Asu; } void SHA3::absorb(const uint8_t *mask, std::size_t mask_sz) { uint64_t dword; // Align buffer_sz on 64 bits while ( (0 != (buffer_sz % 8)) && (mask_sz > 0) ) { dword = ((uint64_t)mask[0]) << (8 * (buffer_sz % 8)); state[buffer_sz / 8] ^= dword; mask += 1; mask_sz -= 1; buffer_sz += 1; } // Absorb 64 bits of mask at a time while ( mask_sz >= 8 ) { GET_UINT64(dword, mask, 0); state[buffer_sz / 8] ^= dword; mask += 8; mask_sz -= 8; buffer_sz += 8; } // Process remaining bits of mask while ( mask_sz > 0 ) { dword = ((uint64_t)mask[0]) << (8 * (buffer_sz % 8)); state[buffer_sz / 8] ^= dword; mask += 1; mask_sz -= 1; buffer_sz += 1; } } uint64_t SHA3::ROL(uint64_t x, std::size_t n) { return (x << n) | (x >> (64 - n)); } const uint64_t SHA3::RC[24] = { UL64(0x0000000000000001), UL64(0x0000000000008082), UL64(0x800000000000808a), UL64(0x8000000080008000), UL64(0x000000000000808b), UL64(0x0000000080000001), UL64(0x8000000080008081), UL64(0x8000000000008009), UL64(0x000000000000008a), UL64(0x0000000000000088), UL64(0x0000000080008009), UL64(0x000000008000000a), UL64(0x000000008000808b), UL64(0x800000000000008b), UL64(0x8000000000008089), UL64(0x8000000000008003), UL64(0x8000000000008002), UL64(0x8000000000000080), UL64(0x000000000000800a), UL64(0x800000008000000a), UL64(0x8000000080008081), UL64(0x8000000000008080), UL64(0x0000000080000001), UL64(0x8000000080008008) }; }
26.548936
85
0.532617
Jonas4420
9c13289143115c039132755ea7f3009b100f846a
21,471
cpp
C++
src/Communication/LSMSCommunication.cpp
JefferyQ/lsms
2d975008a829b328161f503109e324a9eae26768
[ "BSD-3-Clause" ]
1
2019-09-17T18:35:52.000Z
2019-09-17T18:35:52.000Z
src/Communication/LSMSCommunication.cpp
JefferyQ/lsms
2d975008a829b328161f503109e324a9eae26768
[ "BSD-3-Clause" ]
null
null
null
src/Communication/LSMSCommunication.cpp
JefferyQ/lsms
2d975008a829b328161f503109e324a9eae26768
[ "BSD-3-Clause" ]
null
null
null
/* -*- c-file-style: "bsd"; c-basic-offset: 2; indent-tabs-mode: nil -*- */ #include <mpi.h> #include "LSMSCommunication.hpp" // #define USE_ISEND void initializeCommunication(LSMSCommunication &comm) { MPI_Init(NULL,NULL); comm.comm=MPI_COMM_WORLD; MPI_Comm_rank(comm.comm, &comm.rank); MPI_Comm_size(comm.comm, &comm.size); } void initializeCommunication(LSMSCommunication &comm, MPI_Comm mpiCommunicator) { comm.comm=mpiCommunicator; MPI_Comm_rank(comm.comm, &comm.rank); MPI_Comm_size(comm.comm, &comm.size); } void finalizeCommunication(void) { MPI_Finalize(); } void exitLSMS(LSMSCommunication &comm, int errorCode) { MPI_Abort(comm.comm, errorCode); } void communicateParameters(LSMSCommunication &comm, LSMSSystemParameters &lsms, CrystalParameters &crystal, MixingParameters &mix, AlloyMixingDesc &alloyDesc) { const int s = sizeof(LSMSSystemParameters) + 9*sizeof(Real) + sizeof(int) + 10 + sizeof(MixingParameters) + 5*sizeof(int) + sizeof(int); // <-- +1 for no. alloy classes char buf[s]; int nalloy_classes; if(comm.rank==0) { int pos=0; MPI_Pack(lsms.systemid,80,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(lsms.title,80,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(lsms.potential_file_in,128,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(lsms.potential_file_out,128,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(&lsms.pot_in_type,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.pot_out_type,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.alloy_in_type,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.alloy_out_type,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(lsms.infoEvecFileIn,128,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(lsms.infoEvecFileOut,128,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(lsms.localAtomDataFile,128,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(&lsms.num_atoms,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.nspin,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.relativity,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.nrelc,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.nrelv,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.n_spin_cant,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.n_spin_pola,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.mtasa,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.xcFunctional[0],numFunctionalIndices,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.fixRMT,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.nscf,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.writeSteps,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.temperature,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.clight,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.grid,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.npts,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.ebot,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.etop,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.eibot,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.eitop,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.energyContour.maxGroupSize,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.adjustContourBottom,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.mixing,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.alphaDV,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.rmsTolerance,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&lsms.zblockLUSize,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.global.iprint,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.global.print_node,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.global.default_iprint,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&lsms.global.istop,32,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(&lsms.global.GPUThreads,32,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&crystal.num_types,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&crystal.bravais(0,0),9,MPI_DOUBLE,buf,s,&pos,comm.comm); nalloy_classes = alloyDesc.size(); MPI_Pack(&nalloy_classes,1,MPI_INT,buf,s,&pos,comm.comm); // MixingParameters // MPI_CXX_BOOL is not always available // MPI_Pack(&mix.quantity[0],mix.numQuantities,MPI_CXX_BOOL,buf,s,&pos,comm.comm); // copy to temporary int array and send this int tmpQuantity[mix.numQuantities]; for(int i=0; i<mix.numQuantities; i++) if(mix.quantity[i]) tmpQuantity[i] = 1; else tmpQuantity[i] = 0; MPI_Pack(&tmpQuantity[0],mix.numQuantities,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&mix.algorithm[0],mix.numQuantities,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&mix.mixingParameter[0],mix.numQuantities,MPI_DOUBLE,buf,s,&pos,comm.comm); } MPI_Bcast(buf,s,MPI_PACKED,0,comm.comm); if(comm.rank!=0) { int pos=0; MPI_Unpack(buf,s,&pos,lsms.systemid,80,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,lsms.title,80,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,lsms.potential_file_in,128,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,lsms.potential_file_out,128,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.pot_in_type,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.pot_out_type,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.alloy_in_type,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.alloy_out_type,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,lsms.infoEvecFileIn,128,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,lsms.infoEvecFileOut,128,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,lsms.localAtomDataFile,128,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.num_atoms,1,MPI_INT,comm.comm); crystal.num_atoms=lsms.num_atoms; MPI_Unpack(buf,s,&pos,&lsms.nspin,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.relativity,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.nrelc,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.nrelv,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.n_spin_cant,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.n_spin_pola,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.mtasa,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.xcFunctional[0],numFunctionalIndices,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.fixRMT,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.nscf,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.writeSteps,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.temperature,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.clight,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.grid,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.npts,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.ebot,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.etop,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.eibot,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.eitop,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.energyContour.maxGroupSize,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.adjustContourBottom,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.mixing,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.alphaDV,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.rmsTolerance,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.zblockLUSize,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.global.iprint,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.global.print_node,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.global.default_iprint,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.global.istop,32,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,&lsms.global.GPUThreads,32,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&crystal.num_types,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&crystal.bravais(0,0),9,MPI_DOUBLE,comm.comm); crystal.resize(crystal.num_atoms); crystal.resizeTypes(crystal.num_types); MPI_Unpack(buf,s,&pos,&nalloy_classes,1,MPI_INT,comm.comm); alloyDesc.resize(nalloy_classes); // MixingParameters // MPI_CXX_BOOL is not always available // MPI_Unpack(buf,s,&pos,&mix.quantity[0],mix.numQuantities,MPI_CXX_BOOL,comm.comm); // recieve temporary int array and copy int tmpQuantity[mix.numQuantities]; MPI_Unpack(buf,s,&pos,&tmpQuantity[0],mix.numQuantities,MPI_INT,comm.comm); for(int i=0; i<mix.numQuantities; i++) if(tmpQuantity[i]==1) mix.quantity[i] = true; else mix.quantity[i] = false; MPI_Unpack(buf,s,&pos,&mix.algorithm[0],mix.numQuantities,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&mix.mixingParameter[0],mix.numQuantities,MPI_DOUBLE,comm.comm); } MPI_Bcast(&crystal.position(0,0),3*crystal.num_atoms,MPI_DOUBLE,0,comm.comm); MPI_Bcast(&crystal.evecs(0,0),3*crystal.num_atoms,MPI_DOUBLE,0,comm.comm); MPI_Bcast(&crystal.type[0],crystal.num_atoms,MPI_INT,0,comm.comm); // This is dangerous and assumes homogeneous nodes: MPI_Bcast(&crystal.types[0],crystal.num_types*sizeof(AtomType),MPI_BYTE,0,comm.comm); // exchange size of alloy classes and components within each class int *ncomps = (int*) malloc(sizeof(int)*nalloy_classes); if( comm.rank == 0 ) for(int i = 0; i < alloyDesc.size(); i++) ncomps[i] = alloyDesc[i].size(); MPI_Bcast(ncomps,nalloy_classes,MPI_INT,0,comm.comm); if( comm.rank != 0 ) for(int i = 0; i < alloyDesc.size(); i++) alloyDesc[i].resize(ncomps[i]); for(int i = 0; i < alloyDesc.size(); i++) MPI_Bcast(alloyDesc[i].data(),ncomps[i]*sizeof(AtomType),MPI_BYTE,0,comm.comm); // <-- see danger above free(ncomps); // get maximum lmax crystal.maxlmax=0; for(int i=0; i<crystal.num_types; i++) if(crystal.types[i].lmax>crystal.maxlmax) crystal.maxlmax=crystal.types[i].lmax; lsms.maxlmax=crystal.maxlmax; // set lsms.commRank to comm.rank lsms.commRank = comm.rank; } void communicateSingleAtomData(LSMSCommunication &comm, int from, int to, int &local_id, AtomData &atom, int tag) { const int maxPts = 3051; const int maxCore = 30; int s = sizeof(AtomData) + sizeof(Real)*(2*3*maxPts+2*maxCore) + sizeof(int)*3*2*maxCore + sizeof(int); char buf[s]; int t; if(comm.rank == from) { int pos=0; MPI_Pack(&local_id,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.jmt,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.jws,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.xstart,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.rmt,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.rInscribed,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(atom.header,80,MPI_CHAR,buf,s,&pos,comm.comm); MPI_Pack(&atom.alat,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.efermi,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.vdif,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.ztotss,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.zcorss,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.zsemss,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.zvalss,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.qtotws,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.mtotws,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(atom.evec,3,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(atom.evecNew,3,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(atom.evecOut,3,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(atom.xvalws,2,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.localEnergy,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.localMadelungEnergy,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.alloy_class,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.omegaMT,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.omegaWS,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.rws,1,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.lmax,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.nspin,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.forceZeroMoment,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.numc,1,MPI_INT,buf,s,&pos,comm.comm); t=atom.vr.n_row(); MPI_Pack(&t,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.vr(0,0),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.vr(0,1),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.rhotot(0,0),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.rhotot(0,1),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.corden(0,0),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.corden(0,1),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.b_con[0],3,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.b_basis[0],9,MPI_DOUBLE,buf,s,&pos,comm.comm); t=atom.ec.n_row(); MPI_Pack(&t,1,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.ec(0,0),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.ec(0,1),t,MPI_DOUBLE,buf,s,&pos,comm.comm); MPI_Pack(&atom.nc(0,0),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.nc(0,1),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.lc(0,0),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.lc(0,1),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.kc(0,0),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Pack(&atom.kc(0,1),t,MPI_INT,buf,s,&pos,comm.comm); MPI_Send(buf,s,MPI_PACKED,to,tag,comm.comm); } if(comm.rank==to) { MPI_Status status; MPI_Recv(buf,s,MPI_PACKED,from,tag,comm.comm,&status); int pos=0; MPI_Unpack(buf,s,&pos,&local_id,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.jmt,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.jws,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.xstart,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.rmt,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.rInscribed,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,atom.header,80,MPI_CHAR,comm.comm); MPI_Unpack(buf,s,&pos,&atom.alat,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.efermi,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.vdif,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.ztotss,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.zcorss,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.zsemss,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.zvalss,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.qtotws,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.mtotws,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,atom.evec,3,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,atom.evecNew,3,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,atom.evecOut,3,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,atom.xvalws,2,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.localEnergy,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.localMadelungEnergy,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.alloy_class,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.omegaMT,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.omegaWS,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.rws,1,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.lmax,1,MPI_INT,comm.comm); atom.kkrsz = (atom.lmax+1)*(atom.lmax+1); MPI_Unpack(buf,s,&pos,&atom.nspin,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.forceZeroMoment,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.numc,1,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&t,1,MPI_INT,comm.comm); if(t!=atom.vr.n_row()) atom.resizePotential(t); MPI_Unpack(buf,s,&pos,&atom.vr(0,0),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.vr(0,1),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.rhotot(0,0),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.rhotot(0,1),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.corden(0,0),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.corden(0,1),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.b_con[0],3,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.b_basis[0],9,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&t,1,MPI_INT,comm.comm); if(t!=atom.nc.n_row()) atom.resizeCore(t); MPI_Unpack(buf,s,&pos,&atom.ec(0,0),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.ec(0,1),t,MPI_DOUBLE,comm.comm); MPI_Unpack(buf,s,&pos,&atom.nc(0,0),t,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.nc(0,1),t,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.lc(0,0),t,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.lc(0,1),t,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.kc(0,0),t,MPI_INT,comm.comm); MPI_Unpack(buf,s,&pos,&atom.kc(0,1),t,MPI_INT,comm.comm); } } void communicatePotentialShiftParameters(LSMSCommunication &comm, PotentialShifter &ps) { //const int s = sizeof(bool) + sizeof(double) * 2; const int s = sizeof(int) + sizeof(double) * 2; char buf[s]; if (comm.rank==0) { int pos = 0; // MPI_CXX_BOOL is not always available //MPI_Pack(&ps.vSpinShiftFlag, 1, MPI_CXX_BOOL, buf, s, &pos, comm.comm); int tmpFlag = 0; if (ps.vSpinShiftFlag) tmpFlag = 1; MPI_Pack(&tmpFlag, 1, MPI_INT, buf, s, &pos, comm.comm); MPI_Pack(&ps.minShift, 1, MPI_DOUBLE, buf, s, &pos, comm.comm); MPI_Pack(&ps.maxShift, 1, MPI_DOUBLE, buf, s, &pos, comm.comm); } MPI_Bcast(buf, s, MPI_PACKED, 0, comm.comm); if (comm.rank!=0) { int pos = 0; // MPI_CXX_BOOL is not always available //MPI_Unpack(buf, s, &pos, &ps.vSpinShiftFlag, 1, MPI_CXX_BOOL, comm.comm); int tmpFlag = 0; MPI_Unpack(buf, s, &pos, &tmpFlag, 1, MPI_INT, comm.comm); if (tmpFlag) ps.vSpinShiftFlag = true; else ps.vSpinShiftFlag = false; MPI_Unpack(buf, s, &pos, &ps.minShift, 1, MPI_DOUBLE, comm.comm); MPI_Unpack(buf, s, &pos, &ps.maxShift, 1, MPI_DOUBLE, comm.comm); } } void expectTmatCommunication(LSMSCommunication &comm, LocalTypeInfo &local) { // prepost all recieves for tmats from remote nodes for(int i=0; i<comm.numTmatFrom; i++) { int from=comm.tmatFrom[i].remoteNode; for(int j=0; j<comm.tmatFrom[i].numTmats; j++) { // printf("Node %d: expect tmat %d from %d\n",comm.rank,comm.tmatFrom[i].globalIdx[j],from); MPI_Irecv(&local.tmatStore(0,comm.tmatFrom[i].tmatStoreIdx[j]),2*local.lDimTmatStore, MPI_DOUBLE,from,comm.tmatFrom[i].globalIdx[j],comm.comm, &comm.tmatFrom[i].communicationRequest[j]); } } } void sendTmats(LSMSCommunication &comm, LocalTypeInfo &local) { for(int i=0; i<comm.numTmatTo; i++) { int to=comm.tmatTo[i].remoteNode; for(int j=0; j<comm.tmatTo[i].numTmats; j++) { // printf("Node %d: send tmat %d to %d\n",comm.rank,comm.tmatTo[i].globalIdx[j],to); #ifdef USE_ISEND MPI_Isend(&local.tmatStore(0,comm.tmatTo[i].tmatStoreIdx[j]),2*local.lDimTmatStore, MPI_DOUBLE,to,comm.tmatTo[i].globalIdx[j],comm.comm, &comm.tmatTo[i].communicationRequest[j]); #else MPI_Send(&local.tmatStore(0,comm.tmatTo[i].tmatStoreIdx[j]),2*local.lDimTmatStore, MPI_DOUBLE,to,comm.tmatTo[i].globalIdx[j],comm.comm); #endif } } } void finalizeTmatCommunication(LSMSCommunication &comm) { MPI_Status status; for(int i=0; i<comm.numTmatFrom; i++) { int from=comm.tmatFrom[i].remoteNode; for(int j=0; j<comm.tmatFrom[i].numTmats; j++) { // printf("Finalize recieve request %d from node %d\n",j,from); MPI_Wait(&comm.tmatFrom[i].communicationRequest[j],&status); } } #ifdef USE_ISEND for(int i=0; i<comm.numTmatTo; i++) { int to=comm.tmatTo[i].remoteNode; for(int j=0; j<comm.tmatTo[i].numTmats; j++) { // printf("Finalize send request %d to node %d\n",j,to); MPI_Wait(&comm.tmatTo[i].communicationRequest[j],&status); } } #endif } void printCommunicationInfo(FILE *f, LSMSCommunication &comm) { fprintf(f,"Communication: rank no. %d of %d\n",comm.rank,comm.size); fprintf(f,"Sending tmats to %d remote nodes:\n",comm.numTmatTo); for(int i=0; i<comm.numTmatTo; i++) { fprintf(f,"Node %d :",comm.tmatTo[i].remoteNode); for(int j=0; j<comm.tmatTo[i].numTmats; j++) fprintf(f," %d[%d]",comm.tmatTo[i].globalIdx[j],comm.tmatTo[i].tmatStoreIdx[j]); fprintf(f,"\n"); } fprintf(f,"Recieving tmats from %d remote nodes:\n",comm.numTmatFrom); for(int i=0; i<comm.numTmatFrom; i++) { fprintf(f,"Node %d :",comm.tmatFrom[i].remoteNode); for(int j=0; j<comm.tmatFrom[i].numTmats; j++) fprintf(f," %d[%d]",comm.tmatFrom[i].globalIdx[j],comm.tmatFrom[i].tmatStoreIdx[j]); fprintf(f,"\n"); } } void globalAnd(LSMSCommunication &comm,bool &a) { int ia=0; int r; if(a) ia=1; MPI_Allreduce(&ia,&r,1,MPI_INT,MPI_PROD,comm.comm); a=true; if(r==0) a=false; } long long calculateFomScale(LSMSCommunication &comm, LocalTypeInfo &local) { // fomScale = \sum_#atoms (LIZ * (lmax+1)^2)^3 long long fomLocal = 0; long long fom = 0; for(int i=0; i<local.num_local; i++) { // printf("nrmat = %d\n",local.atom[i].nrmat); fomLocal += local.atom[i].nrmat*local.atom[i].nrmat*local.atom[i].nrmat; } // printf("fomLocal = %ld\n",fomLocal); MPI_Allreduce(&fomLocal,&fom,1,MPI_LONG_LONG,MPI_SUM,comm.comm); // printf("fom = %ld\n",fom); return fom; }
41.610465
113
0.690047
JefferyQ
9c180259393eafb38a8b2b4009648ce0670cdfde
2,124
hpp
C++
KFContrib/KFCore/KFRecord.hpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
1
2021-04-26T09:31:32.000Z
2021-04-26T09:31:32.000Z
KFContrib/KFCore/KFRecord.hpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
KFContrib/KFCore/KFRecord.hpp
282951387/KFrame
5d6e953f7cc312321c36632715259394ca67144c
[ "Apache-2.0" ]
null
null
null
๏ปฟ#ifndef __KF_RECORD_H__ #define __KF_RECORD_H__ #include "KFData.h" #include "KFMap.h" namespace KFrame { class KFRecord : public KFData { public: KFRecord(); virtual ~KFRecord() = default; virtual void Reset( bool isdelete = true ); // ๆ˜ฏๅฆๆœ‰ๆ•ˆ virtual bool IsValid(); // common virtual uint32 Size(); // ๆœ€ๅคงๆ•ฐ้‡ virtual uint32 MaxSize(); // ๆ˜ฏๅฆ่พพๅˆฐไบ†ๆœ€ๅคงๅ€ผ virtual bool IsFull(); ////////////////////////////////////////////////////////////////////////////////////////////////////// virtual KFData* First(); virtual KFData* Next(); virtual void CopyFrom( KFData* kfother ); virtual void SaveTo( KFData* kfother ); ////////////////////////////////////////////////////////////////////////////////////////////////////// virtual KFData* Find( uint64 key ); virtual KFData* Find( uint64 key, const std::string& dataname ); virtual KFData* Find( uint64 parentkey, uint64 childkey ); virtual KFData* Find( uint64 parentkey, uint64 childkey, const std::string& dataname ); virtual KFData* Find( uint64 parentkey, const std::string& dataname, uint64 childkey ); virtual bool Add( uint64 key, KFData* data ); virtual bool Add( uint64 parentkey, uint64 childkey, KFData* data ); virtual bool Add( uint64 key, const std::string& dataname, KFData* data ); virtual KFData* Move( uint64 key ); virtual bool Remove( uint64 key ); virtual void Find( const std::string& dataname, uint64 value, std::list< KFData* >& findlist, bool findall ); virtual bool Check( const std::string& dataname, uint64 value, const std::string& checkname, uint64 checkvalue ); // ๆ ผๅผๅŒ–ๆˆๅญ—ไธฒ virtual std::string ToString(); virtual void FromString( const std::string& value ); // Map็š„็‰นๆฎŠๆ“ไฝœ virtual void ToMap( StringMap& values ); virtual void FromMap( const StringMap& values ); protected: // ๅˆ—่กจ KFMap< uint64, uint64, KFData > _data; }; } #endif
31.701493
121
0.553672
282951387
9c1a7d974411924064a1eb05a202148e36c63e19
4,258
cpp
C++
test/threads/ThreadsServer.cpp
pbhide/thrift
23fefaa19511b502f4977036bff7c4b967b5829c
[ "Apache-2.0" ]
51
2015-01-02T04:10:26.000Z
2020-11-21T16:33:19.000Z
test/threads/ThreadsServer.cpp
pbhide/thrift
23fefaa19511b502f4977036bff7c4b967b5829c
[ "Apache-2.0" ]
58
2015-01-29T15:52:19.000Z
2016-04-19T08:19:02.000Z
test/threads/ThreadsServer.cpp
pbhide/thrift
23fefaa19511b502f4977036bff7c4b967b5829c
[ "Apache-2.0" ]
8
2015-03-16T11:03:41.000Z
2019-07-11T06:39:31.000Z
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ // This autogenerated skeleton file illustrates how to build a server. // You should copy it to another filename to avoid overwriting it. #include "ThreadsTest.h" #include <thrift/protocol/TBinaryProtocol.h> #include <thrift/server/TThreadPoolServer.h> #include <thrift/server/TThreadedServer.h> #include <thrift/transport/TServerSocket.h> #include <thrift/transport/TTransportUtils.h> #include <thrift/concurrency/Monitor.h> #include <thrift/concurrency/ThreadManager.h> #include <thrift/concurrency/PlatformThreadFactory.h> using boost::shared_ptr; using namespace apache::thrift; using namespace apache::thrift::protocol; using namespace apache::thrift::transport; using namespace apache::thrift::server; using namespace apache::thrift::concurrency; class ThreadsTestHandler : virtual public ThreadsTestIf { public: ThreadsTestHandler() { // Your initialization goes here } int32_t threadOne(const int32_t sleep) { // Your implementation goes here printf("threadOne\n"); go2sleep(1, sleep); return 1; } int32_t threadTwo(const int32_t sleep) { // Your implementation goes here printf("threadTwo\n"); go2sleep(2, sleep); return 1; } int32_t threadThree(const int32_t sleep) { // Your implementation goes here printf("threadThree\n"); go2sleep(3, sleep); return 1; } int32_t threadFour(const int32_t sleep) { // Your implementation goes here printf("threadFour\n"); go2sleep(4, sleep); return 1; } int32_t stop() { printf("stop\n"); server_->stop(); return 1; } void setServer(boost::shared_ptr<TServer> server) { server_ = server; } protected: void go2sleep(int thread, int seconds) { Monitor m; for (int i = 0; i < seconds; ++i) { fprintf(stderr, "Thread %d: sleep %d\n", thread, i); try { m.wait(1000); } catch(TimedOutException& e) { } } fprintf(stderr, "THREAD %d DONE\n", thread); } private: boost::shared_ptr<TServer> server_; }; int main(int argc, char **argv) { int port = 9090; shared_ptr<ThreadsTestHandler> handler(new ThreadsTestHandler()); shared_ptr<TProcessor> processor(new ThreadsTestProcessor(handler)); shared_ptr<TServerTransport> serverTransport(new TServerSocket(port)); shared_ptr<TTransportFactory> transportFactory(new TBufferedTransportFactory()); shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory()); /* shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(10); shared_ptr<PlatformThreadFactory> threadFactory = shared_ptr<PlatformThreadFactory>(new PlatformThreadFactory()); threadManager->threadFactory(threadFactory); threadManager->start(); shared_ptr<TServer> server = shared_ptr<TServer>(new TThreadPoolServer(processor, serverTransport, transportFactory, protocolFactory, threadManager)); */ shared_ptr<TServer> server = shared_ptr<TServer>(new TThreadedServer(processor, serverTransport, transportFactory, protocolFactory)); handler->setServer(server); server->serve(); fprintf(stderr, "done.\n"); return 0; }
29.985915
82
0.675434
pbhide
9c1b84994f8940557b539576cd9ad0a86c1acdb3
659
cpp
C++
android-31/android/service/autofill/FillCallback.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
12
2020-03-26T02:38:56.000Z
2022-03-14T08:17:26.000Z
android-31/android/service/autofill/FillCallback.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
1
2021-01-27T06:07:45.000Z
2021-11-13T19:19:43.000Z
android-29/android/service/autofill/FillCallback.cpp
YJBeetle/QtAndroidAPI
1468b5dc6eafaf7709f0b00ba1a6ec2b70684266
[ "Apache-2.0" ]
3
2021-02-02T12:34:55.000Z
2022-03-08T07:45:57.000Z
#include "./FillResponse.hpp" #include "../../../JString.hpp" #include "./FillCallback.hpp" namespace android::service::autofill { // Fields // QJniObject forward FillCallback::FillCallback(QJniObject obj) : JObject(obj) {} // Constructors // Methods void FillCallback::onFailure(JString arg0) const { callMethod<void>( "onFailure", "(Ljava/lang/CharSequence;)V", arg0.object<jstring>() ); } void FillCallback::onSuccess(android::service::autofill::FillResponse arg0) const { callMethod<void>( "onSuccess", "(Landroid/service/autofill/FillResponse;)V", arg0.object() ); } } // namespace android::service::autofill
19.969697
82
0.685888
YJBeetle
9c1cc7e9ef0bb46fcd06665a22749028e823aa4e
624
hpp
C++
fixp/ref_data.hpp
mdobrea/effective-fix
0dc8013a8470366f99281f191ea4379d59ef761a
[ "BSD-2-Clause" ]
3
2016-08-08T08:05:11.000Z
2021-02-02T09:11:35.000Z
fixp/ref_data.hpp
mdobrea/effective-fix
0dc8013a8470366f99281f191ea4379d59ef761a
[ "BSD-2-Clause" ]
null
null
null
fixp/ref_data.hpp
mdobrea/effective-fix
0dc8013a8470366f99281f191ea4379d59ef761a
[ "BSD-2-Clause" ]
1
2019-12-29T22:19:47.000Z
2019-12-29T22:19:47.000Z
/* * ref_data.hpp * * Created on: 27.11.2014 * Author: Marius */ #ifndef FIXP_REF_DATA_HPP_ #define FIXP_REF_DATA_HPP_ #include <boost/container/flat_set.hpp> #include <boost/optional.hpp> #include <boost/property_tree/ptree.hpp> #include <string> namespace fixp { class dictionary { public: using tree_type=boost::property_tree::ptree; using optional_tree=boost::optional<const tree_type&>; void load_user_types(const tree_type& types); private: using AggregatedTypes=boost::container::flat_set<std::string>; AggregatedTypes fixpTypes, aliases, appTypes; }; } #endif /* FIXP_REF_DATA_HPP_ */
14.857143
63
0.741987
mdobrea
9c1f9b2a12ceddb16e01dd4b5bb2ce1324bf054a
657
cpp
C++
Notes_Week4/pointerAndFunction.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
1
2019-01-06T22:36:01.000Z
2019-01-06T22:36:01.000Z
Notes_Week4/pointerAndFunction.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
Notes_Week4/pointerAndFunction.cpp
WeiChienHsu/CS165
65e95efc90415c8acc707e2d544eb384d3982e18
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int SumOfElements(int *A, int size) { int i, sum = 0; cout << "Size of A[] in sum function: " << sizeof(A) << endl; for(i = 0; i < size; i++) { sum += A[i]; } cout << "Size of A[0] in sum function: " << sizeof(A[0]) << endl; return sum; } int main() { int A[] = {1,2,3,4,5}; int size = sizeof(A) / sizeof(A[0]); cout << "Size of A[] in main function: " << sizeof(A) << endl; cout << "Size of A[0] in main function: " << sizeof(A[0]) << endl; cout << "Sum of the Array: " << SumOfElements(&A[0], size) << endl; cout << "Sum of the Array: " << SumOfElements(A, size) << endl; return 0; }
31.285714
69
0.550989
WeiChienHsu
9c22fba7e42756dde106d5d687c2b7eab3933e79
4,362
cpp
C++
local_planner/src/utils/trajectory_simulator.cpp
Mekiso/avoidance
2329f84c03f2ea4bedbbae690f0f0052b1b868a8
[ "BSD-3-Clause" ]
3
2019-10-13T11:47:41.000Z
2022-02-27T22:18:46.000Z
local_planner/src/utils/trajectory_simulator.cpp
Mekiso/avoidance
2329f84c03f2ea4bedbbae690f0f0052b1b868a8
[ "BSD-3-Clause" ]
1
2020-08-24T03:28:49.000Z
2020-08-24T03:28:49.000Z
local_planner/src/utils/trajectory_simulator.cpp
Mekiso/avoidance
2329f84c03f2ea4bedbbae690f0f0052b1b868a8
[ "BSD-3-Clause" ]
1
2019-10-12T17:07:01.000Z
2019-10-12T17:07:01.000Z
#include "local_planner/trajectory_simulator.h" #include <cfloat> namespace { Eigen::Vector3f xy_norm_z_clamp(const Eigen::Vector3f& val, float max_xy_norm, float min_z, float max_z) { Eigen::Vector3f result; result.topRows<2>() = avoidance::norm_clamp<2>(val.topRows<2>(), max_xy_norm); result.z() = std::min(max_z, std::max(min_z, val.z())); return result; } float sqr(float f) { return f * f; } float cube(float f) { return f * f * f; } } namespace avoidance { TrajectorySimulator::TrajectorySimulator( const avoidance::simulation_limits& config, const avoidance::simulation_state& start, float step_time) : config_(config), start_(start), step_time_(step_time) {} std::vector<simulation_state> TrajectorySimulator::generate_trajectory( const Eigen::Vector3f& goal_direction, float simulation_duration) { int num_steps = static_cast<int>(std::ceil(simulation_duration / step_time_)); std::vector<simulation_state> timepoints; timepoints.reserve(num_steps); const Eigen::Vector3f unit_goal = goal_direction.normalized(); const Eigen::Vector3f desired_velocity = xy_norm_z_clamp( unit_goal * std::hypot(config_.max_xy_velocity_norm, unit_goal.z() > 0 ? config_.max_z_velocity : config_.min_z_velocity), config_.max_xy_velocity_norm, config_.min_z_velocity, config_.max_z_velocity); // calculate P and D constants such that they hit the jerk limit when // doing accel from 0 float max_accel_norm = std::min(2 * std::sqrt(config_.max_jerk_norm), config_.max_acceleration_norm); float P_constant = (std::sqrt(sqr(max_accel_norm) + config_.max_jerk_norm * desired_velocity.norm()) - max_accel_norm) / desired_velocity.norm() * 10; float D_constant = 2 * std::sqrt(P_constant); simulation_state run_state = start_; for (int i = 0; i < num_steps; i++) { float single_step_time = step_time_; const Eigen::Vector3f damped_jerk = jerk_for_velocity_setpoint( P_constant, D_constant, config_.max_jerk_norm, desired_velocity, run_state); // limit time step to not exceed the maximum acceleration, but clamp // jerk to 0 if at maximum acceleration already const Eigen::Vector3f requested_accel = run_state.acceleration + single_step_time * damped_jerk; Eigen::Vector3f jerk = damped_jerk; if (requested_accel.squaredNorm() > sqr(max_accel_norm)) { single_step_time = (max_accel_norm - run_state.acceleration.norm()) / damped_jerk.norm(); // Use a dot product here somewhere? if (single_step_time <= FLT_EPSILON || single_step_time > step_time_) { jerk = Eigen::Vector3f::Zero(); single_step_time = step_time_; } } // update the state based on motion equations with the final jerk run_state = simulate_step_constant_jerk(run_state, jerk, single_step_time); timepoints.push_back(run_state); } return timepoints; } simulation_state TrajectorySimulator::simulate_step_constant_jerk( const simulation_state& state, const Eigen::Vector3f& jerk, float step_time) { simulation_state next_state; next_state.position = state.position + step_time * state.velocity + 0.5f * sqr(step_time) * state.acceleration + (1.f / 6.f) * cube(step_time) * jerk; next_state.velocity = state.velocity + state.acceleration * step_time + 0.5f * sqr(step_time) * jerk; next_state.acceleration = state.acceleration + step_time * jerk; next_state.time = state.time + step_time; return next_state; } Eigen::Vector3f TrajectorySimulator::jerk_for_velocity_setpoint( float P_constant, float D_constant, float max_jerk_norm, const Eigen::Vector3f& desired_velocity, const simulation_state& state) { const Eigen::Vector3f desired_accel = Eigen::Vector3f::Zero(); const Eigen::Vector3f accel_diff = desired_accel - state.acceleration; const Eigen::Vector3f velocity_diff = desired_velocity - state.velocity; const Eigen::Vector3f p = velocity_diff * P_constant; const Eigen::Vector3f d = accel_diff * D_constant; const Eigen::Vector3f damped_jerk = norm_clamp<3>(p + d, max_jerk_norm); return damped_jerk; } }
40.388889
80
0.694177
Mekiso
9c23f1fc735f81c13b11658de35b1eb269cb2b38
10,940
hpp
C++
include/UnityEngine/TextCore/FaceInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/TextCore/FaceInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/UnityEngine/TextCore/FaceInfo.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes // Including type: System.ValueType #include "System/ValueType.hpp" // Completed includes // Begin il2cpp-utils forward declares struct Il2CppString; // Completed il2cpp-utils forward declares // Type namespace: UnityEngine.TextCore namespace UnityEngine::TextCore { // Size: 0x54 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: UnityEngine.TextCore.FaceInfo // [UsedByNativeCodeAttribute] Offset: DC2A0C struct FaceInfo/*, public System::ValueType*/ { public: // [NativeNameAttribute] Offset: 0xDC2B68 // private System.String m_FamilyName // Size: 0x8 // Offset: 0x0 ::Il2CppString* m_FamilyName; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // [NativeNameAttribute] Offset: 0xDC2BB4 // private System.String m_StyleName // Size: 0x8 // Offset: 0x8 ::Il2CppString* m_StyleName; // Field size check static_assert(sizeof(::Il2CppString*) == 0x8); // [NativeNameAttribute] Offset: 0xDC2C00 // private System.Int32 m_PointSize // Size: 0x4 // Offset: 0x10 int m_PointSize; // Field size check static_assert(sizeof(int) == 0x4); // [NativeNameAttribute] Offset: 0xDC2C4C // private System.Single m_Scale // Size: 0x4 // Offset: 0x14 float m_Scale; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2C98 // private System.Single m_LineHeight // Size: 0x4 // Offset: 0x18 float m_LineHeight; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2CE4 // private System.Single m_AscentLine // Size: 0x4 // Offset: 0x1C float m_AscentLine; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2D30 // private System.Single m_CapLine // Size: 0x4 // Offset: 0x20 float m_CapLine; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2D7C // private System.Single m_MeanLine // Size: 0x4 // Offset: 0x24 float m_MeanLine; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2DC8 // private System.Single m_Baseline // Size: 0x4 // Offset: 0x28 float m_Baseline; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2E14 // private System.Single m_DescentLine // Size: 0x4 // Offset: 0x2C float m_DescentLine; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2E60 // private System.Single m_SuperscriptOffset // Size: 0x4 // Offset: 0x30 float m_SuperscriptOffset; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2EAC // private System.Single m_SuperscriptSize // Size: 0x4 // Offset: 0x34 float m_SuperscriptSize; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2EF8 // private System.Single m_SubscriptOffset // Size: 0x4 // Offset: 0x38 float m_SubscriptOffset; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2F44 // private System.Single m_SubscriptSize // Size: 0x4 // Offset: 0x3C float m_SubscriptSize; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2F90 // private System.Single m_UnderlineOffset // Size: 0x4 // Offset: 0x40 float m_UnderlineOffset; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC2FDC // private System.Single m_UnderlineThickness // Size: 0x4 // Offset: 0x44 float m_UnderlineThickness; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC3028 // private System.Single m_StrikethroughOffset // Size: 0x4 // Offset: 0x48 float m_StrikethroughOffset; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC3074 // private System.Single m_StrikethroughThickness // Size: 0x4 // Offset: 0x4C float m_StrikethroughThickness; // Field size check static_assert(sizeof(float) == 0x4); // [NativeNameAttribute] Offset: 0xDC30C0 // private System.Single m_TabWidth // Size: 0x4 // Offset: 0x50 float m_TabWidth; // Field size check static_assert(sizeof(float) == 0x4); // Creating value type constructor for type: FaceInfo constexpr FaceInfo(::Il2CppString* m_FamilyName_ = {}, ::Il2CppString* m_StyleName_ = {}, int m_PointSize_ = {}, float m_Scale_ = {}, float m_LineHeight_ = {}, float m_AscentLine_ = {}, float m_CapLine_ = {}, float m_MeanLine_ = {}, float m_Baseline_ = {}, float m_DescentLine_ = {}, float m_SuperscriptOffset_ = {}, float m_SuperscriptSize_ = {}, float m_SubscriptOffset_ = {}, float m_SubscriptSize_ = {}, float m_UnderlineOffset_ = {}, float m_UnderlineThickness_ = {}, float m_StrikethroughOffset_ = {}, float m_StrikethroughThickness_ = {}, float m_TabWidth_ = {}) noexcept : m_FamilyName{m_FamilyName_}, m_StyleName{m_StyleName_}, m_PointSize{m_PointSize_}, m_Scale{m_Scale_}, m_LineHeight{m_LineHeight_}, m_AscentLine{m_AscentLine_}, m_CapLine{m_CapLine_}, m_MeanLine{m_MeanLine_}, m_Baseline{m_Baseline_}, m_DescentLine{m_DescentLine_}, m_SuperscriptOffset{m_SuperscriptOffset_}, m_SuperscriptSize{m_SuperscriptSize_}, m_SubscriptOffset{m_SubscriptOffset_}, m_SubscriptSize{m_SubscriptSize_}, m_UnderlineOffset{m_UnderlineOffset_}, m_UnderlineThickness{m_UnderlineThickness_}, m_StrikethroughOffset{m_StrikethroughOffset_}, m_StrikethroughThickness{m_StrikethroughThickness_}, m_TabWidth{m_TabWidth_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // public System.Void set_familyName(System.String value) // Offset: 0xF22404 void set_familyName(::Il2CppString* value); // public System.Void set_styleName(System.String value) // Offset: 0xF2240C void set_styleName(::Il2CppString* value); // public System.Int32 get_pointSize() // Offset: 0xF22414 int get_pointSize(); // public System.Void set_pointSize(System.Int32 value) // Offset: 0xF2241C void set_pointSize(int value); // public System.Single get_scale() // Offset: 0xF22424 float get_scale(); // public System.Void set_scale(System.Single value) // Offset: 0xF2242C void set_scale(float value); // public System.Single get_lineHeight() // Offset: 0xF22434 float get_lineHeight(); // public System.Void set_lineHeight(System.Single value) // Offset: 0xF2243C void set_lineHeight(float value); // public System.Single get_ascentLine() // Offset: 0xF22444 float get_ascentLine(); // public System.Void set_ascentLine(System.Single value) // Offset: 0xF2244C void set_ascentLine(float value); // public System.Single get_capLine() // Offset: 0xF22454 float get_capLine(); // public System.Void set_capLine(System.Single value) // Offset: 0xF2245C void set_capLine(float value); // public System.Void set_meanLine(System.Single value) // Offset: 0xF22464 void set_meanLine(float value); // public System.Single get_baseline() // Offset: 0xF2246C float get_baseline(); // public System.Void set_baseline(System.Single value) // Offset: 0xF22474 void set_baseline(float value); // public System.Single get_descentLine() // Offset: 0xF2247C float get_descentLine(); // public System.Void set_descentLine(System.Single value) // Offset: 0xF22484 void set_descentLine(float value); // public System.Single get_superscriptOffset() // Offset: 0xF2248C float get_superscriptOffset(); // public System.Void set_superscriptOffset(System.Single value) // Offset: 0xF22494 void set_superscriptOffset(float value); // public System.Single get_superscriptSize() // Offset: 0xF2249C float get_superscriptSize(); // public System.Void set_superscriptSize(System.Single value) // Offset: 0xF224A4 void set_superscriptSize(float value); // public System.Single get_subscriptOffset() // Offset: 0xF224AC float get_subscriptOffset(); // public System.Void set_subscriptOffset(System.Single value) // Offset: 0xF224B4 void set_subscriptOffset(float value); // public System.Single get_subscriptSize() // Offset: 0xF224BC float get_subscriptSize(); // public System.Void set_subscriptSize(System.Single value) // Offset: 0xF224C4 void set_subscriptSize(float value); // public System.Single get_underlineOffset() // Offset: 0xF224CC float get_underlineOffset(); // public System.Void set_underlineOffset(System.Single value) // Offset: 0xF224D4 void set_underlineOffset(float value); // public System.Single get_underlineThickness() // Offset: 0xF224DC float get_underlineThickness(); // public System.Void set_underlineThickness(System.Single value) // Offset: 0xF224E4 void set_underlineThickness(float value); // public System.Single get_strikethroughOffset() // Offset: 0xF224EC float get_strikethroughOffset(); // public System.Void set_strikethroughOffset(System.Single value) // Offset: 0xF224F4 void set_strikethroughOffset(float value); // public System.Void set_strikethroughThickness(System.Single value) // Offset: 0xF224FC void set_strikethroughThickness(float value); // public System.Single get_tabWidth() // Offset: 0xF22504 float get_tabWidth(); // public System.Void set_tabWidth(System.Single value) // Offset: 0xF2250C void set_tabWidth(float value); }; // UnityEngine.TextCore.FaceInfo #pragma pack(pop) static check_size<sizeof(FaceInfo), 80 + sizeof(float)> __UnityEngine_TextCore_FaceInfoSizeCheck; static_assert(sizeof(FaceInfo) == 0x54); } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TextCore::FaceInfo, "UnityEngine.TextCore", "FaceInfo");
40.669145
1,216
0.68245
darknight1050
9c26c6e7356900c151dca8033b989212fbad165e
819
cpp
C++
sorts/cycle_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
null
null
null
sorts/cycle_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
5
2021-12-21T13:08:27.000Z
2022-01-17T14:37:41.000Z
sorts/cycle_sort/main.cpp
Kingcitaldo125/Sorts
ce6d60359497490e982640de39370d56d4f17eba
[ "Apache-2.0" ]
null
null
null
#include <algorithm> #include <iostream> #include <vector> #include "SortUtils.hpp" void cycle_sort(std::vector<int> &mints) { auto i = mints.begin(); while (1) { auto scount = std::count_if(mints.begin(), mints.end(), [&](const auto &itm) { return *i > itm; }); if (std::distance(i, mints.begin() + scount) == 0) { if (i >= mints.end()) { break; } else { ++i; continue; } } auto displacement = mints.begin() + scount; std::iter_swap(i, displacement); } } int main() { std::vector<int> mints{11, 72, 89, 37, 59, 69, 12, 57, 27, 32}; cycle_sort(mints); SortUtils::print_vector(mints); SortUtils::print_sorted<int>(mints.begin(), mints.end(), "mints"); return 0; }
21.552632
76
0.527473
Kingcitaldo125
9c27834f18dfb9c63683d98a25bc65a42457ef5a
11,545
cpp
C++
src/Conversion/ONNXToKrnl/Math/Softmax.cpp
MikeHolman/onnx-mlir
7cf7ceddf4e5ae1295dff51bf4bc8ef97e567a57
[ "Apache-2.0" ]
272
2020-02-20T06:19:18.000Z
2022-03-29T05:34:22.000Z
src/Conversion/ONNXToKrnl/Math/Softmax.cpp
lipracer/onnx-mlir
ecacba10912457d91cfe66799ae2d4408ed85af7
[ "Apache-2.0" ]
1,107
2020-02-29T00:22:00.000Z
2022-03-31T23:50:22.000Z
src/Conversion/ONNXToKrnl/Math/Softmax.cpp
lipracer/onnx-mlir
ecacba10912457d91cfe66799ae2d4408ed85af7
[ "Apache-2.0" ]
157
2020-02-27T18:20:36.000Z
2022-03-30T20:34:57.000Z
/* * SPDX-License-Identifier: Apache-2.0 */ //===----------------- Softmax.cpp - Softmax Op ---------------------------===// // // Copyright 2019 The IBM Research Authors. // // ============================================================================= // // This file lowers ONNX softmax operator to Krnl dialect. // //===----------------------------------------------------------------------===// #include "src/Conversion/ONNXToKrnl/ONNXToKrnlCommon.hpp" #include "src/Dialect/Krnl/KrnlOps.hpp" using namespace mlir; static void emitInnerLoops(KrnlBuilder &createKrnl, int64_t numberOfLoops, SmallVectorImpl<IndexExpr> &Lbs, SmallVectorImpl<IndexExpr> &Ubs, ValueRange outerIndices, Value input, Value alloc, Value sumOp, Value maxOp, int64_t axis, bool coerced = true) { int64_t rank = alloc.getType().cast<MemRefType>().getRank(); // Compute the maximum value along axis. ValueRange maxLoops = createKrnl.defineLoops(numberOfLoops); createKrnl.iterateIE(maxLoops, maxLoops, Lbs, Ubs, [&](KrnlBuilder &createKrnl, ValueRange maxIndices) { MathBuilder createMath(createKrnl); IndexExprScope ieScope(createKrnl); // Get induction variables. SmallVector<Value, 4> maxLoopIVs; if (coerced) { for (auto iv : outerIndices) maxLoopIVs.push_back(iv); for (auto iv : maxIndices) maxLoopIVs.push_back(iv); } else { for (int64_t i = 0; i < axis; i++) maxLoopIVs.push_back(outerIndices[i]); maxLoopIVs.push_back(maxIndices[0]); for (int64_t i = axis + 1; i < rank; i++) maxLoopIVs.push_back(outerIndices[i - 1]); } Value max = createKrnl.load(maxOp, {}); Value nextMax = createKrnl.load(input, maxLoopIVs); auto maxCond = createMath.sgt(max, nextMax); max = createMath.select(maxCond, max, nextMax); createKrnl.store(max, maxOp, ArrayRef<Value>{}); }); // Load the maximum value. Value max = createKrnl.load(maxOp, {}); // Compute the sum of all values along axis. ValueRange sumLoops = createKrnl.defineLoops(numberOfLoops); createKrnl.iterateIE(sumLoops, sumLoops, Lbs, Ubs, [&](KrnlBuilder &createKrnl, ValueRange sumIndices) { MathBuilder createMath(createKrnl); IndexExprScope ieScope(createKrnl); // Get induction variables. SmallVector<Value, 4> sumLoopIVs; if (coerced) { for (auto iv : outerIndices) sumLoopIVs.push_back(iv); for (auto iv : sumIndices) sumLoopIVs.push_back(iv); } else { for (int64_t i = 0; i < axis; i++) sumLoopIVs.push_back(outerIndices[i]); sumLoopIVs.push_back(sumIndices[0]); for (int64_t i = axis + 1; i < rank; i++) sumLoopIVs.push_back(outerIndices[i - 1]); } Value sum = createKrnl.load(sumOp, {}); Value next = createKrnl.load(input, sumLoopIVs); Value sub = createMath.sub(next, max); Value exp = createMath.exp(sub); sum = createMath.add(sum, exp); createKrnl.store(sum, sumOp, ArrayRef<Value>{}); // Store intermediate values in the result to avoid // recomputation. createKrnl.store(exp, alloc, sumLoopIVs); }); // Load the sum value. Value sum = createKrnl.load(sumOp, {}); // Compute the softmax. ValueRange softmaxLoops = createKrnl.defineLoops(numberOfLoops); createKrnl.iterateIE(softmaxLoops, softmaxLoops, Lbs, Ubs, [&](KrnlBuilder &createKrnl, ValueRange softmaxIndices) { MathBuilder createMath(createKrnl); IndexExprScope ieScope(createKrnl); // Get induction variables. SmallVector<Value, 4> softmaxLoopIVs; if (coerced) { for (auto iv : outerIndices) softmaxLoopIVs.push_back(iv); for (auto iv : softmaxIndices) softmaxLoopIVs.push_back(iv); } else { for (int64_t i = 0; i < axis; i++) softmaxLoopIVs.push_back(outerIndices[i]); softmaxLoopIVs.push_back(softmaxIndices[0]); for (int64_t i = axis + 1; i < rank; i++) softmaxLoopIVs.push_back(outerIndices[i - 1]); } Value expLoadedVal = createKrnl.load(alloc, softmaxLoopIVs); Value result = createMath.div(expLoadedVal, sum); createKrnl.store(result, alloc, softmaxLoopIVs); }); } static void emitInstForSoftmaxBeforeV13(ConversionPatternRewriter &rewriter, Location loc, Value alloc, Value input, Value sumOp, Value maxOp, Value zero, Value negInfinity, int64_t axis) { int64_t rank = alloc.getType().cast<MemRefType>().getRank(); ImplicitLocOpBuilder ilob(loc, rewriter); KrnlBuilder createKrnl(ilob); IndexExprScope ieScope(createKrnl); MemRefBoundsIndexCapture inputBounds(input); // Coerce the input into a 2-D tensor. `axis` will be the coercing // point. This coercing follows the softmax definition in ONNX: // https://github.com/onnx/onnx/blob/master/docs/Operators.md#Softmax // Here, we create an outer loop and inner loop for handling the two // dimensions. The outer loop is only created once `axis` is not // zero. if (axis == 0) { // There is no need having outer loops. // Reset accumulators. createKrnl.store(zero, sumOp, ArrayRef<Value>{}); createKrnl.store(negInfinity, maxOp, ArrayRef<Value>{}); // Common information to create nested loops. int64_t numberOfLoops = rank; SmallVector<IndexExpr, 4> Lbs(numberOfLoops, LiteralIndexExpr(0)); SmallVector<IndexExpr, 4> Ubs; inputBounds.getDimList(Ubs); emitInnerLoops(createKrnl, numberOfLoops, Lbs, Ubs, {}, input, alloc, sumOp, maxOp, axis, /*coerced=*/true); } else { // Define outer loops. ValueRange outerLoops = createKrnl.defineLoops(axis); SmallVector<IndexExpr, 4> outerLbs(axis, LiteralIndexExpr(0)); SmallVector<IndexExpr, 4> outerUbs; for (int i = 0; i < axis; ++i) outerUbs.emplace_back(inputBounds.getDim(i)); createKrnl.iterateIE(outerLoops, outerLoops, outerLbs, outerUbs, [&](KrnlBuilder &createKrnl, ValueRange outerIndices) { IndexExprScope ieScope(createKrnl); // Reset accumulators. createKrnl.store(zero, sumOp, ArrayRef<Value>{}); createKrnl.store(negInfinity, maxOp, ArrayRef<Value>{}); // Common information to create inner nested loops. int64_t numberOfLoops = rank - axis; SmallVector<IndexExpr, 4> Lbs(numberOfLoops, LiteralIndexExpr(0)); SmallVector<IndexExpr, 4> Ubs; for (int i = axis; i < rank; ++i) Ubs.emplace_back(inputBounds.getDim(i)); // Emit the inner loops. emitInnerLoops(createKrnl, numberOfLoops, Lbs, Ubs, outerIndices, input, alloc, sumOp, maxOp, axis, /*coerced=*/true); }); } } static void emitInstForSoftmaxV13(ConversionPatternRewriter &rewriter, Location loc, Value alloc, Value input, Value sumOp, Value maxOp, Value zero, Value negInfinity, int64_t axis) { int64_t rank = alloc.getType().cast<MemRefType>().getRank(); ImplicitLocOpBuilder ilob(loc, rewriter); KrnlBuilder createKrnl(ilob); IndexExprScope ieScope(createKrnl); MemRefBoundsIndexCapture inputBounds(input); // In opset version 13, The "axis" attribute indicates the dimension along // which Softmax will be performed. No need to coerce the dimensions after // "axis". // Outer loops iterate over all dimensions except axis. ValueRange outerLoops = createKrnl.defineLoops(rank - 1); SmallVector<IndexExpr, 4> outerLbs(rank - 1, LiteralIndexExpr(0)); SmallVector<IndexExpr, 4> outerUbs; for (int i = 0; i < rank; ++i) if (i != axis) outerUbs.emplace_back(inputBounds.getDim(i)); // Emit outer loops. createKrnl.iterateIE(outerLoops, outerLoops, outerLbs, outerUbs, [&](KrnlBuilder &createKrnl, ValueRange outerIndices) { IndexExprScope ieScope(createKrnl); // Reset accumulators. createKrnl.store(zero, sumOp, ArrayRef<Value>{}); createKrnl.store(negInfinity, maxOp, ArrayRef<Value>{}); // Common information to create inner nested loops for axis only. int64_t numberOfLoops = 1; SmallVector<IndexExpr, 4> Lbs(numberOfLoops, LiteralIndexExpr(0)); SmallVector<IndexExpr, 4> Ubs(numberOfLoops, inputBounds.getDim(axis)); // Emit the inner loops. emitInnerLoops(createKrnl, numberOfLoops, Lbs, Ubs, outerIndices, input, alloc, sumOp, maxOp, axis, /*coerced=*/false); }); } struct ONNXSoftmaxOpLowering : public ConversionPattern { ONNXSoftmaxOpLowering(MLIRContext *ctx) : ConversionPattern(mlir::ONNXSoftmaxOp::getOperationName(), 1, ctx) {} LogicalResult matchAndRewrite(Operation *op, ArrayRef<Value> operands, ConversionPatternRewriter &rewriter) const final { // softmax(x) = let max_x = max(x) in // let exp_x = exp(x - max_x) in // let sum = sum(exp_x) in // exp_x / sum auto memRefType = convertToMemRefType(*op->result_type_begin()); int64_t rank = memRefType.getRank(); int64_t axis = llvm::dyn_cast<ONNXSoftmaxOp>(op).axis(); axis = axis >= 0 ? axis : rank + axis; assert(axis >= -rank && axis <= rank - 1); // Get opset number. Default is opset 11. int64_t opset = 11; IntegerAttr opsetAttr = op->getAttrOfType<::mlir::Attribute>("onnx_opset") .dyn_cast_or_null<IntegerAttr>(); if (opsetAttr) opset = opsetAttr.getValue().getSExtValue(); auto loc = op->getLoc(); ONNXSoftmaxOpAdaptor operandAdaptor(operands); Value input = operandAdaptor.input(); // Insert an allocation and deallocation for the result of this operation. auto elementType = memRefType.getElementType(); Value alloc; bool insertDealloc = checkInsertDealloc(op); if (hasAllConstantDimensions(memRefType)) alloc = insertAllocAndDealloc(memRefType, loc, rewriter, insertDealloc); else alloc = insertAllocAndDealloc( memRefType, loc, rewriter, insertDealloc, input); // Insert allocations and deallocations for sum and max. MemRefType scalarMemRefType = MemRefType::get({}, elementType, {}, 0); Value sumOp = insertAllocAndDealloc(scalarMemRefType, loc, rewriter, true); Value maxOp = insertAllocAndDealloc(scalarMemRefType, loc, rewriter, true); Value zero = emitConstantOp(rewriter, loc, elementType, 0); Value negInfinity = rewriter.create<ConstantOp>(loc, FloatAttr::get(elementType, -std::numeric_limits<float>::infinity())); if (opset < 13) // For Softmax opset < 13, `axis` is the coerced point. All dimensions // after `axis` will be logically coerced into a single dimension. emitInstForSoftmaxBeforeV13( rewriter, loc, alloc, input, sumOp, maxOp, zero, negInfinity, axis); else // For Softmax opset 13, `axis` attribute indicates the dimension along // which Softmax will be performed. No need to coerce the dimensions after // `axis`. emitInstForSoftmaxV13( rewriter, loc, alloc, input, sumOp, maxOp, zero, negInfinity, axis); rewriter.replaceOp(op, alloc); return success(); } }; void populateLoweringONNXSoftmaxOpPattern( RewritePatternSet &patterns, MLIRContext *ctx) { patterns.insert<ONNXSoftmaxOpLowering>(ctx); }
40.226481
80
0.651537
MikeHolman
9c27b380a2a20aba338f8c87d9ad9c0b45d217c2
18,397
cpp
C++
source/form_tools.cpp
smaslan/spellcross-map-edit
577ce6f23dff38922f7484fe2ab2f9b67ddafe05
[ "MIT" ]
null
null
null
source/form_tools.cpp
smaslan/spellcross-map-edit
577ce6f23dff38922f7484fe2ab2f9b67ddafe05
[ "MIT" ]
null
null
null
source/form_tools.cpp
smaslan/spellcross-map-edit
577ce6f23dff38922f7484fe2ab2f9b67ddafe05
[ "MIT" ]
null
null
null
/////////////////////////////////////////////////////////////////////////// // C++ code generated with wxFormBuilder (version 3.10.1-0-g8feb16b3) // http://www.wxformbuilder.org/ // // PLEASE DO *NOT* EDIT THIS FILE! /////////////////////////////////////////////////////////////////////////// #include "form_tools.h" /////////////////////////////////////////////////////////////////////////// FormTools::FormTools( wxWindow* parent, SpellData* spelldata, wxWindowID id, const wxString& title, const wxPoint& pos, const wxSize& size, long style ) : wxFrame( parent, id, title, pos, size, style ) { this->spell_data = spelldata; this->spell_map = NULL; // ==== BEGIN AUTO GENERATED ==== this->SetSizeHints(wxDefaultSize, wxDefaultSize); this->SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_MENU)); sbar = this->CreateStatusBar(1, wxSTB_SIZEGRIP, wxID_ANY); wxBoxSizer* szrMain; szrMain = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* szrToolset; szrToolset = new wxBoxSizer(wxVERTICAL); m_staticText19 = new wxStaticText(this, wxID_ANY, wxT("Toolsets:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText19->Wrap(-1); szrToolset->Add(m_staticText19, 0, wxLEFT | wxRIGHT | wxTOP, 5); lbToolset = new wxListBox(this, wxID_LB_TOOLSET, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_ALWAYS_SB); szrToolset->Add(lbToolset, 1, wxEXPAND | wxRIGHT | wxLEFT, 5); m_staticText21 = new wxStaticText(this, wxID_ANY, wxT("Toolset name:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText21->Wrap(-1); szrToolset->Add(m_staticText21, 0, wxTOP | wxRIGHT | wxLEFT, 5); txtNewToolset = new wxTextCtrl(this, wxID_TXT_NEW_TOOLSET, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); szrToolset->Add(txtNewToolset, 0, wxBOTTOM | wxRIGHT | wxLEFT | wxEXPAND, 5); m_staticText23 = new wxStaticText(this, wxID_ANY, wxT("Toolset title:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText23->Wrap(-1); szrToolset->Add(m_staticText23, 0, wxRIGHT | wxLEFT, 5); txtToolsetTitle = new wxTextCtrl(this, wxID_TXT_TOOLSET_TITLE, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); szrToolset->Add(txtToolsetTitle, 0, wxEXPAND | wxRIGHT | wxLEFT, 5); wxBoxSizer* szrScaling; szrScaling = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* szrScale; szrScale = new wxBoxSizer(wxVERTICAL); m_staticText26 = new wxStaticText(this, wxID_ANY, wxT("Glyph scaling:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText26->Wrap(-1); szrScale->Add(m_staticText26, 0, wxTOP | wxRIGHT | wxLEFT, 5); wxArrayString chbScalingChoices; chbScaling = new wxChoice(this, wxID_CHB_SCALE, wxDefaultPosition, wxDefaultSize, chbScalingChoices, 0); chbScaling->SetSelection(0); szrScale->Add(chbScaling, 0, wxBOTTOM | wxRIGHT | wxLEFT | wxEXPAND, 5); szrScaling->Add(szrScale, 1, wxEXPAND, 5); wxBoxSizer* szrWidth; szrWidth = new wxBoxSizer(wxVERTICAL); m_staticText27 = new wxStaticText(this, wxID_ANY, wxT("Width:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText27->Wrap(-1); szrWidth->Add(m_staticText27, 0, wxTOP | wxRIGHT | wxLEFT, 5); scWidth = new wxSpinCtrl(this, wxID_SC_WIDTH, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 32, 200, 80); scWidth->SetMinSize(wxSize(80, -1)); scWidth->SetMaxSize(wxSize(80, -1)); szrWidth->Add(scWidth, 0, wxBOTTOM | wxRIGHT | wxLEFT | wxEXPAND, 5); szrScaling->Add(szrWidth, 0, wxEXPAND, 5); wxBoxSizer* szrHeight; szrHeight = new wxBoxSizer(wxVERTICAL); m_staticText28 = new wxStaticText(this, wxID_ANY, wxT("Height:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText28->Wrap(-1); szrHeight->Add(m_staticText28, 0, wxTOP | wxRIGHT | wxLEFT, 5); scHeight = new wxSpinCtrl(this, wxID_SC_HEIGHT, wxEmptyString, wxDefaultPosition, wxDefaultSize, wxSP_ARROW_KEYS, 32, 200, 80); scHeight->SetMinSize(wxSize(80, -1)); scHeight->SetMaxSize(wxSize(80, -1)); szrHeight->Add(scHeight, 0, wxBOTTOM | wxRIGHT | wxLEFT | wxEXPAND, 5); szrScaling->Add(szrHeight, 0, wxEXPAND, 5); szrToolset->Add(szrScaling, 0, wxEXPAND, 5); wxGridSizer* szrToolsetBtn; szrToolsetBtn = new wxGridSizer(0, 5, 0, 0); btnAddToolset = new wxButton(this, wxID_BTN_TOOLSET_NEW, wxT("New"), wxDefaultPosition, wxDefaultSize, 0); szrToolsetBtn->Add(btnAddToolset, 0, wxALL | wxEXPAND, 5); btnRenameToolset = new wxButton(this, wxID_BTN_TOOLSET_RENAME, wxT("Update"), wxDefaultPosition, wxDefaultSize, 0); szrToolsetBtn->Add(btnRenameToolset, 0, wxALL | wxEXPAND, 5); btnToolsetDel = new wxButton(this, wxID_BTN_TOOLSET_REM, wxT("Remove"), wxDefaultPosition, wxDefaultSize, 0); szrToolsetBtn->Add(btnToolsetDel, 0, wxALL | wxEXPAND, 5); btnToolsetUp = new wxButton(this, wxID_BTN_TOOLSET_UP, wxT("Up"), wxDefaultPosition, wxDefaultSize, 0); szrToolsetBtn->Add(btnToolsetUp, 0, wxALL | wxEXPAND, 5); btnToolsetDown = new wxButton(this, wxID_BTN_TOOLSET_DOWN, wxT("Down"), wxDefaultPosition, wxDefaultSize, 0); szrToolsetBtn->Add(btnToolsetDown, 0, wxALL | wxEXPAND, 5); szrToolset->Add(szrToolsetBtn, 0, wxEXPAND, 5); szrMain->Add(szrToolset, 1, wxEXPAND, 5); wxBoxSizer* szrTool; szrTool = new wxBoxSizer(wxVERTICAL); m_staticText20 = new wxStaticText(this, wxID_ANY, wxT("Tools:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText20->Wrap(-1); szrTool->Add(m_staticText20, 0, wxTOP | wxRIGHT | wxLEFT, 5); lbTool = new wxListBox(this, wxID_LB_TOOL, wxDefaultPosition, wxDefaultSize, 0, NULL, wxLB_ALWAYS_SB); szrTool->Add(lbTool, 1, wxEXPAND | wxBOTTOM | wxRIGHT | wxLEFT, 5); m_staticText22 = new wxStaticText(this, wxID_ANY, wxT("Tool name:"), wxDefaultPosition, wxDefaultSize, 0); m_staticText22->Wrap(-1); szrTool->Add(m_staticText22, 0, wxTOP | wxRIGHT | wxLEFT, 5); txtNewTool = new wxTextCtrl(this, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0); szrTool->Add(txtNewTool, 0, wxBOTTOM | wxRIGHT | wxLEFT | wxEXPAND, 5); wxGridSizer* srzToolBtn; srzToolBtn = new wxGridSizer(0, 5, 0, 0); btnNewTool = new wxButton(this, wxID_BTN_TOOL_NEW, wxT("New"), wxDefaultPosition, wxDefaultSize, 0); srzToolBtn->Add(btnNewTool, 0, wxALL | wxEXPAND, 5); btnRenameTool = new wxButton(this, wxID_BTN_TOOL_RENAME, wxT("Rename"), wxDefaultPosition, wxDefaultSize, 0); srzToolBtn->Add(btnRenameTool, 0, wxALL | wxEXPAND, 5); btnToolDel = new wxButton(this, wxID_BTN_TOOL_REM, wxT("Delete"), wxDefaultPosition, wxDefaultSize, 0); srzToolBtn->Add(btnToolDel, 0, wxALL | wxEXPAND, 5); btnToolUp = new wxButton(this, wxID_BTN_TOOL_UP, wxT("Up"), wxDefaultPosition, wxDefaultSize, 0); srzToolBtn->Add(btnToolUp, 0, wxALL | wxEXPAND, 5); btnToolDown = new wxButton(this, wxID_BTN_TOOL_DOWN, wxT("Down"), wxDefaultPosition, wxDefaultSize, 0); srzToolBtn->Add(btnToolDown, 0, wxALL | wxEXPAND, 5); szrTool->Add(srzToolBtn, 0, wxEXPAND, 5); szrMain->Add(szrTool, 1, wxEXPAND, 5); this->SetSizer(szrMain); this->Layout(); mmBar = new wxMenuBar(0); mmFile = new wxMenu(); wxMenuItem* mmSave; mmSave = new wxMenuItem(mmFile, wxID_MM_SAVE, wxString(wxT("Save list")) + wxT('\t') + wxT("Ctrl+S"), wxEmptyString, wxITEM_NORMAL); mmFile->Append(mmSave); mmFile->AppendSeparator(); wxMenuItem* mmClose; mmClose = new wxMenuItem(mmFile, wxID_MM_CLOSE, wxString(wxT("Close")), wxEmptyString, wxITEM_NORMAL); mmFile->Append(mmClose); mmBar->Append(mmFile, wxT("File")); mmTerrain = new wxMenu(); mmBar->Append(mmTerrain, wxT("Terrain")); mmEdit = new wxMenu(); wxMenuItem* mmClrAllToolset; mmClrAllToolset = new wxMenuItem(mmEdit, wxID_MM_CLR_TOOLSETS, wxString(wxT("Remove all toolsets")), wxEmptyString, wxITEM_NORMAL); mmEdit->Append(mmClrAllToolset); wxMenuItem* mmClrAllTools; mmClrAllTools = new wxMenuItem(mmEdit, wxID_CLR_TOOLS, wxString(wxT("Remove all tools")), wxEmptyString, wxITEM_NORMAL); mmEdit->Append(mmClrAllTools); mmBar->Append(mmEdit, wxT("Edit")); this->SetMenuBar(mmBar); this->Centre(wxBOTH); // ==== END AUTO GENERATED ==== // fill terrain selector for (int k = 0; k < spell_data->GetTerrainCount(); k++) { Terrain* terr = spell_data->GetTerrain(k); mmTerrain->Append(TERR_ID0 + k, terr->name, wxEmptyString, wxITEM_RADIO); Bind(wxEVT_MENU, &FormTools::OnTerrainChange, this, TERR_ID0 + k); } SetMap(NULL); // fill glyph scaling selector chbScaling->Append("Mean aspect, fixed w/h"); chbScaling->Append("Max size"); chbScaling->Append("Max size, no zoom"); Bind(wxEVT_CLOSE_WINDOW, &FormTools::OnClose, this, this->m_windowId); Bind(wxEVT_MENU, &FormTools::OnCloseClick, this, wxID_MM_CLOSE); Bind(wxEVT_MENU, &FormTools::OnSaveContext, this, wxID_MM_SAVE); Bind(wxEVT_COMMAND_LISTBOX_SELECTED, &FormTools::OnToolsetSelect, this, wxID_LB_TOOLSET); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolsetRename, this, wxID_BTN_TOOLSET_RENAME); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolsetNew, this, wxID_BTN_TOOLSET_NEW); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolsetRemove, this, wxID_BTN_TOOLSET_REM); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolsetMove, this, wxID_BTN_TOOLSET_UP); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolsetMove, this, wxID_BTN_TOOLSET_DOWN); Bind(wxEVT_COMMAND_LISTBOX_SELECTED, &FormTools::OnToolSelect, this, wxID_LB_TOOL); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolRename, this, wxID_BTN_TOOL_RENAME); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolNew, this, wxID_BTN_TOOL_NEW); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolRemove, this, wxID_BTN_TOOL_REM); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolMove, this, wxID_BTN_TOOL_UP); Bind(wxEVT_COMMAND_BUTTON_CLICKED, &FormTools::OnToolMove, this, wxID_BTN_TOOL_DOWN); } FormTools::~FormTools() { } void FormTools::OnClose(wxCloseEvent& ev) { wxPostEvent(GetParent(), ev); ev.Skip(); Destroy(); } // close form void FormTools::OnCloseClick(wxCommandEvent& event) { Close(); } // save current terrain's constext void FormTools::OnSaveContext(wxCommandEvent& event) { // get this terrain Terrain* terrain = FindTerrain(); // split path to folder and file std::filesystem::path last_path = terrain->GetSpriteContextPath(); wstring dir = last_path.parent_path(); dir += wstring(L"\\"); wstring name = last_path.filename(); // show save dialog wxFileDialog saveFileDialog(this, _("Save Spellcross terrain context file"), dir, name, "Context file (*.con)|*.con", wxFD_SAVE); if (saveFileDialog.ShowModal() == wxID_CANCEL) return; wstring path = wstring(saveFileDialog.GetPath().ToStdWstring()); // save file terrain->SaveSpriteContext(path); } // set current map poitner void FormTools::SetMap(SpellMap* map) { spell_map = map; for (int k = 0; k < spell_data->GetTerrainCount(); k++) { Terrain* terr = spell_data->GetTerrain(k); wxString lab = terr->name; if (map && std::strcmp(map->terrain->name, spell_data->GetTerrain(k)->name) == 0) { lab = lab + " (active)"; mmTerrain->Check(TERR_ID0 + k,true); } mmTerrain->SetLabel(TERR_ID0 + k, lab); } SelectTerrain(); } // find terrain selected Terrain* FormTools::FindTerrain() { for (int k = 0; k < spell_data->GetTerrainCount(); k++) { if (GetMenuBar()->FindItem(TERR_ID0 + k)->IsChecked()) { // found selection Terrain* terr = spell_data->GetTerrain(k); return(terr); } } return(NULL); } // on terrain selection click void FormTools::OnTerrainChange(wxCommandEvent& event) { SelectTerrain(); } // terrain change void FormTools::SelectTerrain() { auto terr = FindTerrain(); if (!terr) return; // for each toolset: lbToolset->Freeze(); lbToolset->Clear(); for (int tid = 0; tid < terr->GetToolsCount(); tid++) { //auto toolset = terr->GetToolSet(tid); lbToolset->Append(terr->GetToolSetName(tid) + ": " + terr->GetToolSetTitle(tid)); } lbToolset->Thaw(); if(lbToolset->GetCount()) lbToolset->Select(0); SelectToolset(); } // on toolset selection click void FormTools::OnToolsetSelect(wxCommandEvent& event) { SelectToolset(); } // selection of toolset void FormTools::SelectToolset() { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset txtNewToolset->Clear(); txtToolsetTitle->Clear(); lbTool->Clear(); if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; //auto toolset = terr->GetToolSet(lbToolset->GetSelection()); auto selid = lbToolset->GetSelection(); // show name/title txtNewToolset->SetValue(terr->GetToolSetName(selid)); txtToolsetTitle->SetValue(terr->GetToolSetTitle(selid)); chbScaling->SetSelection(terr->GetToolSetGlyphScalingMode(selid)); auto [w,h] = terr->GetToolSetGlyphScaling(selid); scWidth->SetValue(w); scHeight->SetValue(h); // for each toolset: lbTool->Freeze(); for (auto const& str : terr->GetToolSetItems(selid)) lbTool->Append(str); lbTool->Thaw(); if (lbTool->GetCount()) lbTool->Select(0); SelectTool(); } // on toolset selection click void FormTools::OnToolSelect(wxCommandEvent& event) { SelectTool(); } // tool selection void FormTools::SelectTool() { // get terrain selection auto terr = FindTerrain(); if (!terr) return; txtNewTool->Clear(); // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; //auto toolset = terr->GetToolSet(lbToolset->GetSelection()); auto selid = lbToolset->GetSelection(); // get tool if (!lbTool->GetCount() || lbTool->GetSelection() < 0) return; txtNewTool->SetValue(terr->GetToolSetItem(selid, lbTool->GetSelection())); } // on toolset rename click void FormTools::OnToolsetRename(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; //auto toolset = terr->GetToolSet(lbToolset->GetSelection()); auto setid = lbToolset->GetSelection(); // update names terr->SetToolSetName(setid, txtNewToolset->GetValue().ToStdString()); terr->SetToolSetTitle(setid, txtToolsetTitle->GetValue().ToStdString()); terr->SetToolSetGlyphScalingMode(setid, chbScaling->GetSelection()); terr->SetToolSetGlyphScaling(setid, scWidth->GetValue(), scHeight->GetValue()); auto selid = lbToolset->GetSelection(); SelectTerrain(); lbToolset->SetSelection(selid); SelectToolset(); } // on toolset add new click void FormTools::OnToolsetNew(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset int selid = -1; if (lbToolset->GetCount() && lbToolset->GetSelection() >= 0) selid = lbToolset->GetSelection(); // add new toolset terr->AddToolSet(txtNewToolset->GetValue().ToStdString(), txtToolsetTitle->GetValue().ToStdString(), selid); SelectTerrain(); if(selid >= 0) lbToolset->SetSelection(selid); SelectToolset(); } // on toolset add new click void FormTools::OnToolsetRemove(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; auto selid = lbToolset->GetSelection(); // add new toolset terr->RemoveToolSet(selid); SelectTerrain(); if (lbToolset->GetCount()) lbToolset->SetSelection(min(selid, (int)lbToolset->GetCount()-1)); SelectToolset(); } // on toolset add new click void FormTools::OnToolsetMove(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; auto selid = lbToolset->GetSelection(); if (event.GetId() == wxID_BTN_TOOLSET_UP && selid > 0) { terr->MoveToolSet(selid, selid - 1); selid--; } else if (event.GetId() == wxID_BTN_TOOLSET_DOWN && selid < lbToolset->GetCount() - 1) { terr->MoveToolSet(selid, selid + 1); selid++; } SelectTerrain(); lbToolset->SetSelection(selid); SelectToolset(); } // on new tool click void FormTools::OnToolNew(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; auto setid = lbToolset->GetSelection(); int selid = -1; if (lbTool->GetCount() && lbTool->GetSelection() >= 0) selid = lbTool->GetSelection(); // update name terr->AddToolSetItem(setid, txtNewTool->GetValue().ToStdString(), selid); SelectToolset(); lbTool->SetSelection(selid); SelectTool(); } // on tool rename click void FormTools::OnToolRename(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; //auto toolset = terr->GetToolSet(lbToolset->GetSelection()); auto setid = lbToolset->GetSelection(); if (!lbTool->GetCount() || lbTool->GetSelection() < 0) return; // update name terr->RenameToolSetItem(setid, txtNewTool->GetValue().ToStdString(), lbTool->GetSelection()); auto selid = lbTool->GetSelection(); SelectToolset(); lbTool->SetSelection(selid); SelectTool(); } // on tool remove click void FormTools::OnToolRemove(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; auto setid = lbToolset->GetSelection(); if (!lbTool->GetCount() || lbTool->GetSelection() < 0) return; // update name auto selid = lbTool->GetSelection(); terr->RemoveToolSetItem(setid, selid); SelectToolset(); if(terr->GetToolSetItemsCount(setid)) lbTool->SetSelection(min(selid, terr->GetToolSetItemsCount(setid) - 1)); SelectTool(); } // on tool remove click void FormTools::OnToolMove(wxCommandEvent& event) { // get terrain selection auto terr = FindTerrain(); if (!terr) return; // get toolset if (!lbToolset->GetCount() || lbToolset->GetSelection() < 0) return; //auto toolset = terr->GetToolSet(lbToolset->GetSelection()); auto setid = lbToolset->GetSelection(); if (!lbTool->GetCount() || lbTool->GetSelection() < 0) return; auto selid = lbTool->GetSelection(); if (event.GetId() == wxID_BTN_TOOL_UP && selid > 0) { terr->MoveToolSetItem(setid, selid, selid - 1); selid--; } else if (event.GetId() == wxID_BTN_TOOL_DOWN && selid < lbTool->GetCount() - 1) { terr->MoveToolSetItem(setid, selid, selid + 1); selid++; } SelectToolset(); lbTool->SetSelection(selid); SelectTool(); }
29.720517
201
0.715117
smaslan
9c2cd888692b4e9289227ce199e7634e353862b2
25,829
cc
C++
cpp/src/arrow/array/array_binary_test.cc
H-Plus-Time/arrow
3586292d62c8c348e9fb85676eb524cde53179cf
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
40
2018-07-12T03:57:58.000Z
2021-12-31T00:20:50.000Z
cpp/src/arrow/array/array_binary_test.cc
H-Plus-Time/arrow
3586292d62c8c348e9fb85676eb524cde53179cf
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
5
2019-11-01T01:20:33.000Z
2021-09-03T15:49:01.000Z
cpp/src/arrow/array/array_binary_test.cc
H-Plus-Time/arrow
3586292d62c8c348e9fb85676eb524cde53179cf
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0" ]
22
2018-07-12T06:16:57.000Z
2022-01-15T03:38:51.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include <cstdint> #include <cstring> #include <memory> #include <string> #include <vector> #include <gmock/gmock-matchers.h> #include <gtest/gtest.h> #include "arrow/array.h" #include "arrow/buffer.h" #include "arrow/builder.h" #include "arrow/memory_pool.h" #include "arrow/status.h" #include "arrow/testing/gtest_common.h" #include "arrow/testing/gtest_util.h" #include "arrow/type.h" #include "arrow/type_traits.h" #include "arrow/util/bit_util.h" #include "arrow/util/bitmap_builders.h" #include "arrow/util/checked_cast.h" #include "arrow/util/string_view.h" #include "arrow/visitor_inline.h" namespace arrow { using internal::checked_cast; using StringTypes = ::testing::Types<StringType, LargeStringType, BinaryType, LargeBinaryType>; using UTF8Types = ::testing::Types<StringType, LargeStringType>; // ---------------------------------------------------------------------- // String / Binary tests template <typename ArrayType> void CheckStringArray(const ArrayType& array, const std::vector<std::string>& strings, const std::vector<uint8_t>& is_valid, int repeats = 1) { int64_t length = array.length(); int64_t base_length = static_cast<int64_t>(strings.size()); ASSERT_EQ(base_length, static_cast<int64_t>(is_valid.size())); ASSERT_EQ(base_length * repeats, length); int32_t value_pos = 0; for (int i = 0; i < length; ++i) { auto j = i % base_length; if (is_valid[j]) { ASSERT_FALSE(array.IsNull(i)); auto view = array.GetView(i); ASSERT_EQ(value_pos, array.value_offset(i)); ASSERT_EQ(strings[j].size(), view.size()); ASSERT_EQ(util::string_view(strings[j]), view); value_pos += static_cast<int32_t>(view.size()); } else { ASSERT_TRUE(array.IsNull(i)); } } } template <typename T> class TestStringArray : public ::testing::Test { public: using TypeClass = T; using offset_type = typename TypeClass::offset_type; using ArrayType = typename TypeTraits<TypeClass>::ArrayType; using BuilderType = typename TypeTraits<TypeClass>::BuilderType; void SetUp() { chars_ = {'a', 'b', 'b', 'c', 'c', 'c'}; offsets_ = {0, 1, 1, 1, 3, 6}; valid_bytes_ = {1, 1, 0, 1, 1}; expected_ = {"a", "", "", "bb", "ccc"}; MakeArray(); } void MakeArray() { length_ = static_cast<int64_t>(offsets_.size()) - 1; value_buf_ = Buffer::Wrap(chars_); offsets_buf_ = Buffer::Wrap(offsets_); ASSERT_OK_AND_ASSIGN(null_bitmap_, internal::BytesToBits(valid_bytes_)); null_count_ = CountNulls(valid_bytes_); strings_ = std::make_shared<ArrayType>(length_, offsets_buf_, value_buf_, null_bitmap_, null_count_); } void TestArrayBasics() { ASSERT_EQ(length_, strings_->length()); ASSERT_EQ(1, strings_->null_count()); ASSERT_OK(strings_->ValidateFull()); TestInitialized(*strings_); AssertZeroPadded(*strings_); } void TestArrayCtors() { // ARROW-8863: ArrayData::null_count set to 0 when no validity bitmap // provided ArrayType arr(length_, offsets_buf_, value_buf_); ASSERT_EQ(arr.data()->null_count, 0); } void TestTotalValuesLength() { auto ty = TypeTraits<T>::type_singleton(); auto arr = ArrayFromJSON(ty, R"(["a", null, "bbb", "cccc", "ddddd"])"); offset_type values_length = arr.total_values_length(); ASSERT_EQ(values_length, static_cast<offset_type>(13)); offset_type sliced_values_length = checked_cast<const ArrayType&>(*arr.Slice(3)).total_values_length(); ASSERT_EQ(sliced_values_length, static_cast<offset_type>(9)); // Zero-length array is a special case offset_type zero_size_length = checked_cast<const ArrayType&>(*arr.Slice(0, 0)).total_values_length(); ASSERT_EQ(zero_size_length, static_cast<offset_type>(0)); } void TestType() { std::shared_ptr<DataType> type = this->strings_->type(); if (std::is_same<TypeClass, StringType>::value) { ASSERT_EQ(Type::STRING, type->id()); ASSERT_EQ(Type::STRING, this->strings_->type_id()); } else if (std::is_same<TypeClass, LargeStringType>::value) { ASSERT_EQ(Type::LARGE_STRING, type->id()); ASSERT_EQ(Type::LARGE_STRING, this->strings_->type_id()); } else if (std::is_same<TypeClass, BinaryType>::value) { ASSERT_EQ(Type::BINARY, type->id()); ASSERT_EQ(Type::BINARY, this->strings_->type_id()); } else if (std::is_same<TypeClass, LargeBinaryType>::value) { ASSERT_EQ(Type::LARGE_BINARY, type->id()); ASSERT_EQ(Type::LARGE_BINARY, this->strings_->type_id()); } else { FAIL(); } } void TestListFunctions() { int64_t pos = 0; for (size_t i = 0; i < expected_.size(); ++i) { ASSERT_EQ(pos, strings_->value_offset(i)); ASSERT_EQ(expected_[i].size(), strings_->value_length(i)); pos += expected_[i].size(); } } void TestDestructor() { auto arr = std::make_shared<ArrayType>(length_, offsets_buf_, value_buf_, null_bitmap_, null_count_); } void TestGetString() { for (size_t i = 0; i < expected_.size(); ++i) { if (valid_bytes_[i] == 0) { ASSERT_TRUE(strings_->IsNull(i)); } else { ASSERT_FALSE(strings_->IsNull(i)); ASSERT_EQ(expected_[i], strings_->GetString(i)); } } } void TestEmptyStringComparison() { offsets_ = {0, 0, 0, 0, 0, 0}; offsets_buf_ = Buffer::Wrap(offsets_); length_ = static_cast<int64_t>(offsets_.size() - 1); auto strings_a = std::make_shared<ArrayType>(length_, offsets_buf_, nullptr, null_bitmap_, null_count_); auto strings_b = std::make_shared<ArrayType>(length_, offsets_buf_, nullptr, null_bitmap_, null_count_); ASSERT_TRUE(strings_a->Equals(strings_b)); } void TestCompareNullByteSlots() { BuilderType builder; BuilderType builder2; BuilderType builder3; ASSERT_OK(builder.Append("foo")); ASSERT_OK(builder2.Append("foo")); ASSERT_OK(builder3.Append("foo")); ASSERT_OK(builder.Append("bar")); ASSERT_OK(builder2.AppendNull()); // same length, but different ASSERT_OK(builder3.Append("xyz")); ASSERT_OK(builder.Append("baz")); ASSERT_OK(builder2.Append("baz")); ASSERT_OK(builder3.Append("baz")); std::shared_ptr<Array> array, array2, array3; FinishAndCheckPadding(&builder, &array); ASSERT_OK(builder2.Finish(&array2)); ASSERT_OK(builder3.Finish(&array3)); const auto& a1 = checked_cast<const ArrayType&>(*array); const auto& a2 = checked_cast<const ArrayType&>(*array2); const auto& a3 = checked_cast<const ArrayType&>(*array3); // The validity bitmaps are the same, the data is different, but the unequal // portion is masked out ArrayType equal_array(3, a1.value_offsets(), a1.value_data(), a2.null_bitmap(), 1); ArrayType equal_array2(3, a3.value_offsets(), a3.value_data(), a2.null_bitmap(), 1); ASSERT_TRUE(equal_array.Equals(equal_array2)); ASSERT_TRUE(a2.RangeEquals(equal_array2, 0, 3, 0)); ASSERT_TRUE(equal_array.Array::Slice(1)->Equals(equal_array2.Array::Slice(1))); ASSERT_TRUE( equal_array.Array::Slice(1)->RangeEquals(0, 2, 0, equal_array2.Array::Slice(1))); } void TestSliceGetString() { BuilderType builder; ASSERT_OK(builder.Append("a")); ASSERT_OK(builder.Append("b")); ASSERT_OK(builder.Append("c")); std::shared_ptr<Array> array; ASSERT_OK(builder.Finish(&array)); auto s = array->Slice(1, 10); auto arr = std::dynamic_pointer_cast<ArrayType>(s); ASSERT_EQ(arr->GetString(0), "b"); } Status ValidateFull(int64_t length, std::vector<offset_type> offsets, util::string_view data, int64_t offset = 0) { ArrayType arr(length, Buffer::Wrap(offsets), std::make_shared<Buffer>(data), /*null_bitmap=*/nullptr, /*null_count=*/0, offset); return arr.ValidateFull(); } Status ValidateFull(const std::string& json) { auto ty = TypeTraits<T>::type_singleton(); auto arr = ArrayFromJSON(ty, json); return arr->ValidateFull(); } void TestValidateOffsets() { ASSERT_OK(ValidateFull(0, {0}, "")); ASSERT_OK(ValidateFull(1, {0, 4}, "data")); ASSERT_OK(ValidateFull(2, {0, 4, 4}, "data")); ASSERT_OK(ValidateFull(2, {0, 5, 9}, "some data")); // Non-zero array offset ASSERT_OK(ValidateFull(0, {0, 4}, "data", 1)); ASSERT_OK(ValidateFull(1, {0, 5, 9}, "some data", 1)); ASSERT_OK(ValidateFull(0, {0, 5, 9}, "some data", 2)); // Not enough offsets ASSERT_RAISES(Invalid, ValidateFull(1, {}, "")); ASSERT_RAISES(Invalid, ValidateFull(1, {0}, "")); ASSERT_RAISES(Invalid, ValidateFull(2, {0, 4}, "data")); ASSERT_RAISES(Invalid, ValidateFull(1, {0, 4}, "data", 1)); // Offset out of bounds ASSERT_RAISES(Invalid, ValidateFull(1, {0, 5}, "data")); // Negative offset ASSERT_RAISES(Invalid, ValidateFull(1, {-1, 0}, "data")); ASSERT_RAISES(Invalid, ValidateFull(1, {0, -1}, "data")); ASSERT_RAISES(Invalid, ValidateFull(1, {0, -1, -1}, "data", 1)); // Offsets non-monotonic ASSERT_RAISES(Invalid, ValidateFull(2, {0, 5, 4}, "some data")); } void TestValidateData() { // Valid UTF8 ASSERT_OK(ValidateFull(R"(["Voix", "ambiguรซ", "dโ€™un", "cล“ur"])")); ASSERT_OK(ValidateFull(R"(["ใ„ใ‚ใฏใซใปใธใจ", "ใกใ‚Šใฌใ‚‹ใ‚’", "ใ‚ใ‹ใ‚ˆใŸใ‚Œใ"])")); ASSERT_OK(ValidateFull(R"(["๐Ÿ˜€", "๐Ÿ˜„"])")); ASSERT_OK(ValidateFull(1, {0, 4}, "\xf4\x8f\xbf\xbf")); // \U0010ffff // Invalid UTF8 auto ty = TypeTraits<T>::type_singleton(); auto st1 = ValidateFull(3, {0, 4, 6, 9}, "abc \xff def"); // Hypothetical \U00110000 auto st2 = ValidateFull(1, {0, 4}, "\xf4\x90\x80\x80"); // Single UTF8 character straddles two entries auto st3 = ValidateFull(2, {0, 1, 2}, "\xc3\xa9"); if (T::is_utf8) { ASSERT_RAISES(Invalid, st1); ASSERT_RAISES(Invalid, st2); ASSERT_RAISES(Invalid, st3); } else { ASSERT_OK(st1); ASSERT_OK(st2); ASSERT_OK(st3); } } protected: std::vector<offset_type> offsets_; std::vector<char> chars_; std::vector<uint8_t> valid_bytes_; std::vector<std::string> expected_; std::shared_ptr<Buffer> value_buf_; std::shared_ptr<Buffer> offsets_buf_; std::shared_ptr<Buffer> null_bitmap_; int64_t null_count_; int64_t length_; std::shared_ptr<ArrayType> strings_; }; TYPED_TEST_SUITE(TestStringArray, StringTypes); TYPED_TEST(TestStringArray, TestArrayBasics) { this->TestArrayBasics(); } TYPED_TEST(TestStringArray, TestArrayCtors) { this->TestArrayCtors(); } TYPED_TEST(TestStringArray, TestType) { this->TestType(); } TYPED_TEST(TestStringArray, TestListFunctions) { this->TestListFunctions(); } TYPED_TEST(TestStringArray, TestDestructor) { this->TestDestructor(); } TYPED_TEST(TestStringArray, TestGetString) { this->TestGetString(); } TYPED_TEST(TestStringArray, TestEmptyStringComparison) { this->TestEmptyStringComparison(); } TYPED_TEST(TestStringArray, CompareNullByteSlots) { this->TestCompareNullByteSlots(); } TYPED_TEST(TestStringArray, TestSliceGetString) { this->TestSliceGetString(); } TYPED_TEST(TestStringArray, TestValidateOffsets) { this->TestValidateOffsets(); } TYPED_TEST(TestStringArray, TestValidateData) { this->TestValidateData(); } template <typename T> class TestUTF8Array : public ::testing::Test { public: using TypeClass = T; using offset_type = typename TypeClass::offset_type; using ArrayType = typename TypeTraits<TypeClass>::ArrayType; Status ValidateUTF8(int64_t length, std::vector<offset_type> offsets, util::string_view data, int64_t offset = 0) { ArrayType arr(length, Buffer::Wrap(offsets), std::make_shared<Buffer>(data), /*null_bitmap=*/nullptr, /*null_count=*/0, offset); return arr.ValidateUTF8(); } Status ValidateUTF8(const std::string& json) { auto ty = TypeTraits<T>::type_singleton(); auto arr = ArrayFromJSON(ty, json); return checked_cast<const ArrayType&>(*arr).ValidateUTF8(); } void TestValidateUTF8() { ASSERT_OK(ValidateUTF8(R"(["Voix", "ambiguรซ", "dโ€™un", "cล“ur"])")); ASSERT_OK(ValidateUTF8(1, {0, 4}, "\xf4\x8f\xbf\xbf")); // \U0010ffff ASSERT_RAISES(Invalid, ValidateUTF8(1, {0, 1}, "\xf4")); // More tests in TestValidateData() above // (ValidateFull() calls ValidateUTF8() internally) } }; TYPED_TEST_SUITE(TestUTF8Array, UTF8Types); TYPED_TEST(TestUTF8Array, TestValidateUTF8) { this->TestValidateUTF8(); } // ---------------------------------------------------------------------- // String builder tests template <typename T> class TestStringBuilder : public TestBuilder { public: using TypeClass = T; using offset_type = typename TypeClass::offset_type; using ArrayType = typename TypeTraits<TypeClass>::ArrayType; using BuilderType = typename TypeTraits<TypeClass>::BuilderType; void SetUp() { TestBuilder::SetUp(); builder_.reset(new BuilderType(pool_)); } void Done() { std::shared_ptr<Array> out; FinishAndCheckPadding(builder_.get(), &out); result_ = std::dynamic_pointer_cast<ArrayType>(out); ASSERT_OK(result_->ValidateFull()); } void TestScalarAppend() { std::vector<std::string> strings = {"", "bb", "a", "", "ccc"}; std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1}; int N = static_cast<int>(strings.size()); int reps = 10; for (int j = 0; j < reps; ++j) { for (int i = 0; i < N; ++i) { if (!is_valid[i]) { ASSERT_OK(builder_->AppendNull()); } else { ASSERT_OK(builder_->Append(strings[i])); } } } Done(); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(reps, result_->null_count()); ASSERT_EQ(reps * 6, result_->value_data()->size()); CheckStringArray(*result_, strings, is_valid, reps); } void TestScalarAppendUnsafe() { std::vector<std::string> strings = {"", "bb", "a", "", "ccc"}; std::vector<uint8_t> is_valid = {1, 1, 1, 0, 1}; int N = static_cast<int>(strings.size()); int reps = 13; int64_t total_length = 0; for (const auto& s : strings) { total_length += static_cast<int64_t>(s.size()); } ASSERT_OK(builder_->Reserve(N * reps)); ASSERT_OK(builder_->ReserveData(total_length * reps)); for (int j = 0; j < reps; ++j) { for (int i = 0; i < N; ++i) { if (!is_valid[i]) { builder_->UnsafeAppendNull(); } else { builder_->UnsafeAppend(strings[i]); } } } ASSERT_EQ(builder_->value_data_length(), total_length * reps); Done(); ASSERT_OK(result_->ValidateFull()); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(reps, result_->null_count()); ASSERT_EQ(reps * total_length, result_->value_data()->size()); CheckStringArray(*result_, strings, is_valid, reps); } void TestVectorAppend() { std::vector<std::string> strings = {"", "bb", "a", "", "ccc"}; std::vector<uint8_t> valid_bytes = {1, 1, 1, 0, 1}; int N = static_cast<int>(strings.size()); int reps = 1000; for (int j = 0; j < reps; ++j) { ASSERT_OK(builder_->AppendValues(strings, valid_bytes.data())); } Done(); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(reps, result_->null_count()); ASSERT_EQ(reps * 6, result_->value_data()->size()); CheckStringArray(*result_, strings, valid_bytes, reps); } void TestAppendCStringsWithValidBytes() { const char* strings[] = {nullptr, "aaa", nullptr, "ignored", ""}; std::vector<uint8_t> valid_bytes = {1, 1, 1, 0, 1}; int N = static_cast<int>(sizeof(strings) / sizeof(strings[0])); int reps = 1000; for (int j = 0; j < reps; ++j) { ASSERT_OK(builder_->AppendValues(strings, N, valid_bytes.data())); } Done(); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(reps * 3, result_->null_count()); ASSERT_EQ(reps * 3, result_->value_data()->size()); CheckStringArray(*result_, {"", "aaa", "", "", ""}, {0, 1, 0, 0, 1}, reps); } void TestAppendCStringsWithoutValidBytes() { const char* strings[] = {"", "bb", "a", nullptr, "ccc"}; int N = static_cast<int>(sizeof(strings) / sizeof(strings[0])); int reps = 1000; for (int j = 0; j < reps; ++j) { ASSERT_OK(builder_->AppendValues(strings, N)); } Done(); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(reps, result_->null_count()); ASSERT_EQ(reps * 6, result_->value_data()->size()); CheckStringArray(*result_, {"", "bb", "a", "", "ccc"}, {1, 1, 1, 0, 1}, reps); } void TestCapacityReserve() { std::vector<std::string> strings = {"aaaaa", "bbbbbbbbbb", "ccccccccccccccc", "dddddddddd"}; int N = static_cast<int>(strings.size()); int reps = 15; int64_t length = 0; int64_t capacity = 1000; int64_t expected_capacity = BitUtil::RoundUpToMultipleOf64(capacity); ASSERT_OK(builder_->ReserveData(capacity)); ASSERT_EQ(length, builder_->value_data_length()); ASSERT_EQ(expected_capacity, builder_->value_data_capacity()); for (int j = 0; j < reps; ++j) { for (int i = 0; i < N; ++i) { ASSERT_OK(builder_->Append(strings[i])); length += static_cast<int64_t>(strings[i].size()); ASSERT_EQ(length, builder_->value_data_length()); ASSERT_EQ(expected_capacity, builder_->value_data_capacity()); } } int extra_capacity = 500; expected_capacity = BitUtil::RoundUpToMultipleOf64(length + extra_capacity); ASSERT_OK(builder_->ReserveData(extra_capacity)); ASSERT_EQ(length, builder_->value_data_length()); int64_t actual_capacity = builder_->value_data_capacity(); ASSERT_GE(actual_capacity, expected_capacity); ASSERT_EQ(actual_capacity & 63, 0); Done(); ASSERT_EQ(reps * N, result_->length()); ASSERT_EQ(0, result_->null_count()); ASSERT_EQ(reps * 40, result_->value_data()->size()); } void TestZeroLength() { // All buffers are null Done(); ASSERT_EQ(result_->length(), 0); ASSERT_EQ(result_->null_count(), 0); } protected: std::unique_ptr<BuilderType> builder_; std::shared_ptr<ArrayType> result_; }; TYPED_TEST_SUITE(TestStringBuilder, StringTypes); TYPED_TEST(TestStringBuilder, TestScalarAppend) { this->TestScalarAppend(); } TYPED_TEST(TestStringBuilder, TestScalarAppendUnsafe) { this->TestScalarAppendUnsafe(); } TYPED_TEST(TestStringBuilder, TestVectorAppend) { this->TestVectorAppend(); } TYPED_TEST(TestStringBuilder, TestAppendCStringsWithValidBytes) { this->TestAppendCStringsWithValidBytes(); } TYPED_TEST(TestStringBuilder, TestAppendCStringsWithoutValidBytes) { this->TestAppendCStringsWithoutValidBytes(); } TYPED_TEST(TestStringBuilder, TestCapacityReserve) { this->TestCapacityReserve(); } TYPED_TEST(TestStringBuilder, TestZeroLength) { this->TestZeroLength(); } // ---------------------------------------------------------------------- // ChunkedBinaryBuilder tests class TestChunkedBinaryBuilder : public ::testing::Test { public: void SetUp() {} void Init(int32_t chunksize) { builder_.reset(new internal::ChunkedBinaryBuilder(chunksize)); } void Init(int32_t chunksize, int32_t chunklength) { builder_.reset(new internal::ChunkedBinaryBuilder(chunksize, chunklength)); } protected: std::unique_ptr<internal::ChunkedBinaryBuilder> builder_; }; TEST_F(TestChunkedBinaryBuilder, BasicOperation) { const int32_t chunksize = 1000; Init(chunksize); const int elem_size = 10; uint8_t buf[elem_size]; BinaryBuilder unchunked_builder; const int iterations = 1000; for (int i = 0; i < iterations; ++i) { random_bytes(elem_size, i, buf); ASSERT_OK(unchunked_builder.Append(buf, elem_size)); ASSERT_OK(builder_->Append(buf, elem_size)); } std::shared_ptr<Array> unchunked; ASSERT_OK(unchunked_builder.Finish(&unchunked)); ArrayVector chunks; ASSERT_OK(builder_->Finish(&chunks)); // This assumes that everything is evenly divisible ArrayVector expected_chunks; const int elems_per_chunk = chunksize / elem_size; for (int i = 0; i < iterations / elems_per_chunk; ++i) { expected_chunks.emplace_back(unchunked->Slice(i * elems_per_chunk, elems_per_chunk)); } ASSERT_EQ(expected_chunks.size(), chunks.size()); for (size_t i = 0; i < chunks.size(); ++i) { AssertArraysEqual(*expected_chunks[i], *chunks[i]); } } TEST_F(TestChunkedBinaryBuilder, Reserve) { // ARROW-6060 const int32_t chunksize = 1000; Init(chunksize); ASSERT_OK(builder_->Reserve(chunksize / 2)); auto bytes_after_first_reserve = default_memory_pool()->bytes_allocated(); for (int i = 0; i < 8; ++i) { ASSERT_OK(builder_->Reserve(chunksize / 2)); } // no new memory will be allocated since capacity was sufficient for the loop's // Reserve() calls ASSERT_EQ(default_memory_pool()->bytes_allocated(), bytes_after_first_reserve); } TEST_F(TestChunkedBinaryBuilder, NoData) { Init(1000); ArrayVector chunks; ASSERT_OK(builder_->Finish(&chunks)); ASSERT_EQ(1, chunks.size()); ASSERT_EQ(0, chunks[0]->length()); } TEST_F(TestChunkedBinaryBuilder, LargeElements) { Init(100); const int bufsize = 101; uint8_t buf[bufsize]; const int iterations = 100; for (int i = 0; i < iterations; ++i) { random_bytes(bufsize, i, buf); ASSERT_OK(builder_->Append(buf, bufsize)); } ArrayVector chunks; ASSERT_OK(builder_->Finish(&chunks)); ASSERT_EQ(iterations, static_cast<int>(chunks.size())); int64_t total_data_size = 0; for (auto chunk : chunks) { ASSERT_EQ(1, chunk->length()); total_data_size += static_cast<int64_t>(static_cast<const BinaryArray&>(*chunk).GetView(0).size()); } ASSERT_EQ(iterations * bufsize, total_data_size); } TEST_F(TestChunkedBinaryBuilder, LargeElementCount) { int32_t max_chunk_length = 100; Init(100, max_chunk_length); auto length = max_chunk_length + 1; // ChunkedBinaryBuilder can reserve memory for more than its configured maximum // (per chunk) element count ASSERT_OK(builder_->Reserve(length)); for (int64_t i = 0; i < 2 * length; ++i) { // Appending more elements than have been reserved memory simply overflows to the next // chunk ASSERT_OK(builder_->Append("")); } ArrayVector chunks; ASSERT_OK(builder_->Finish(&chunks)); // should have two chunks full of empty strings and another with two more empty strings ASSERT_EQ(chunks.size(), 3); ASSERT_EQ(chunks[0]->length(), max_chunk_length); ASSERT_EQ(chunks[1]->length(), max_chunk_length); ASSERT_EQ(chunks[2]->length(), 2); for (auto&& boxed_chunk : chunks) { const auto& chunk = checked_cast<const BinaryArray&>(*boxed_chunk); ASSERT_EQ(chunk.value_offset(0), chunk.value_offset(chunk.length())); } } TEST(TestChunkedStringBuilder, BasicOperation) { const int chunksize = 100; internal::ChunkedStringBuilder builder(chunksize); std::string value = "0123456789"; const int iterations = 100; for (int i = 0; i < iterations; ++i) { ASSERT_OK(builder.Append(value)); } ArrayVector chunks; ASSERT_OK(builder.Finish(&chunks)); ASSERT_EQ(10, chunks.size()); // Type is correct for (auto chunk : chunks) { ASSERT_TRUE(chunk->type()->Equals(utf8())); } } // ---------------------------------------------------------------------- // ArrayDataVisitor<binary-like> tests struct BinaryAppender { Status VisitNull() { data.emplace_back("(null)"); return Status::OK(); } Status VisitValue(util::string_view v) { data.push_back(v); return Status::OK(); } std::vector<util::string_view> data; }; template <typename T> class TestBinaryDataVisitor : public ::testing::Test { public: using TypeClass = T; void SetUp() override { type_ = TypeTraits<TypeClass>::type_singleton(); } void TestBasics() { auto array = ArrayFromJSON(type_, R"(["foo", null, "bar"])"); BinaryAppender appender; ArrayDataVisitor<TypeClass> visitor; ASSERT_OK(visitor.Visit(*array->data(), &appender)); ASSERT_THAT(appender.data, ::testing::ElementsAreArray({"foo", "(null)", "bar"})); ARROW_UNUSED(visitor); // Workaround weird MSVC warning } void TestSliced() { auto array = ArrayFromJSON(type_, R"(["ab", null, "cd", "ef"])")->Slice(1, 2); BinaryAppender appender; ArrayDataVisitor<TypeClass> visitor; ASSERT_OK(visitor.Visit(*array->data(), &appender)); ASSERT_THAT(appender.data, ::testing::ElementsAreArray({"(null)", "cd"})); ARROW_UNUSED(visitor); // Workaround weird MSVC warning } protected: std::shared_ptr<DataType> type_; }; TYPED_TEST_SUITE(TestBinaryDataVisitor, StringTypes); TYPED_TEST(TestBinaryDataVisitor, Basics) { this->TestBasics(); } TYPED_TEST(TestBinaryDataVisitor, Sliced) { this->TestSliced(); } } // namespace arrow
31.730958
90
0.659104
H-Plus-Time
9c30089d944b9bbb69b07f941d1f5ac419a098bb
153
cpp
C++
src/Factory/AFactory.cpp
codeOverFlow/Stickman-project
cdaa582fc147bca68fbd079eaa6618fb86f70052
[ "MIT" ]
null
null
null
src/Factory/AFactory.cpp
codeOverFlow/Stickman-project
cdaa582fc147bca68fbd079eaa6618fb86f70052
[ "MIT" ]
null
null
null
src/Factory/AFactory.cpp
codeOverFlow/Stickman-project
cdaa582fc147bca68fbd079eaa6618fb86f70052
[ "MIT" ]
null
null
null
#include "../../include/Factory/AFactory.h" AFactory::~AFactory(){ } IBlock* AFactory::createBlock(char c) { m_block = build(c); return m_block; }
15.3
43
0.666667
codeOverFlow
9c31324722350363754ca4067c2b6f9429f682fd
664
cpp
C++
cipher/vignere/test/test1.cpp
akm-hub/algorithms
77c6471698665e676d0a59b079ad4a6289097421
[ "MIT" ]
null
null
null
cipher/vignere/test/test1.cpp
akm-hub/algorithms
77c6471698665e676d0a59b079ad4a6289097421
[ "MIT" ]
null
null
null
cipher/vignere/test/test1.cpp
akm-hub/algorithms
77c6471698665e676d0a59b079ad4a6289097421
[ "MIT" ]
null
null
null
/** * @purpose Vignere crypto driver code * * @author Ashish * @license MIT license * @version 1.0, Doxygen compatible comments */ #include <iostream> #include <string> #include "vignere.h" int main() { /// Create a cipher using the first 16 bytes of the passphrase Vignere *vignere = new Vignere("LEMON"); std::string cleartext = "ATTACKATDAWN"; /// Run it through the cipher and back std::string ciphertext = vignere->encrypt(cleartext); std::cout << "Encrypted text = " << ciphertext << std::endl; cleartext = vignere->decrypt(ciphertext); std::cout << "Clear text = " << cleartext << std::endl; return 0; }
25.538462
66
0.646084
akm-hub
9c32701633f5a145f3c5fbeca276e27fb4850050
1,299
cpp
C++
STF/Source/HAL/x86/HALSTFDataManipulation.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
STF/Source/HAL/x86/HALSTFDataManipulation.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
STF/Source/HAL/x86/HALSTFDataManipulation.cpp
rerunner/STCM_driver
8fef3dd7327812fd317fdb0e6fab8d36e345a505
[ "BSD-3-Clause" ]
null
null
null
// // Platform: Win32 // #include "STF/Interface/Types/STFBasicTypes.h" void MUL32x32(uint32 op1, uint32 op2, uint32 & upper, uint32 & lower) { uint32 u, l; __asm { mov eax, op1 mov edx, op2 mul edx mov u, edx mov l, eax } upper = u; lower = l; } uint32 DIV64x32(uint32 upper, uint32 lower, uint32 op) { uint32 res; if (op) { __asm { mov edx, upper mov eax, lower mov ecx, op div ecx mov res, eax }; return res; } else return 0; } uint32 ScaleDWord(uint32 op, uint32 from, uint32 to) { uint32 res; if (to && op) { __asm { mov eax, op mov edx, to mul edx mov ecx, from cmp edx, ecx jge done div ecx mov res, eax done: }; return res; } else return 0; } int32 ScaleLong(int32 op, int32 from, int32 to) { int32 res; if (to && op) { __asm { mov eax, op mov edx, to imul edx mov ecx, from cmp edx, ecx jge done idiv ecx mov res, eax done: }; return res; } else return 0; }
13.967742
92
0.451886
rerunner
9c34e89084fd5b55d6c375cd4b810c66235755ac
155
hxx
C++
src/Providers/UNIXProviders/EndpointForIPNetworkConnection/UNIX_EndpointForIPNetworkConnection_STUB.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
1
2020-10-12T09:00:09.000Z
2020-10-12T09:00:09.000Z
src/Providers/UNIXProviders/EndpointForIPNetworkConnection/UNIX_EndpointForIPNetworkConnection_STUB.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
src/Providers/UNIXProviders/EndpointForIPNetworkConnection/UNIX_EndpointForIPNetworkConnection_STUB.hxx
brunolauze/openpegasus-providers-old
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
[ "MIT" ]
null
null
null
#ifdef PEGASUS_OS_STUB #ifndef __UNIX_ENDPOINTFORIPNETWORKCONNECTION_PRIVATE_H #define __UNIX_ENDPOINTFORIPNETWORKCONNECTION_PRIVATE_H #endif #endif
12.916667
55
0.877419
brunolauze
9c37989cc3fe6e318742dd88771dc2e93cb224f2
1,535
cpp
C++
tests/dxbc/test_dxbc_compiler.cpp
oltolm/dxvk
687efdd4b45dd7b5c423581e197cfd317b1795d4
[ "Zlib" ]
1
2022-01-28T18:30:32.000Z
2022-01-28T18:30:32.000Z
tests/dxbc/test_dxbc_compiler.cpp
oltolm/dxvk
687efdd4b45dd7b5c423581e197cfd317b1795d4
[ "Zlib" ]
null
null
null
tests/dxbc/test_dxbc_compiler.cpp
oltolm/dxvk
687efdd4b45dd7b5c423581e197cfd317b1795d4
[ "Zlib" ]
null
null
null
#include <fstream> #include "../../src/dxbc/dxbc_module.h" #include "../../src/dxvk/dxvk_shader.h" #include <shellapi.h> #include <windows.h> namespace dxvk { Logger Logger::s_instance(L"dxbc-compiler.log"); } using namespace dxvk; int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { int argc = 0; LPWSTR* argv = CommandLineToArgvW( GetCommandLineW(), &argc); if (argc < 3) { Logger::err("Usage: dxbc-compiler input.dxbc output.spv"); return 1; } try { std::string ifileName = str::fromws(argv[1]); std::ifstream ifile(ifileName, std::ios::binary); ifile.ignore(std::numeric_limits<std::streamsize>::max()); std::streamsize length = ifile.gcount(); ifile.clear(); ifile.seekg(0, std::ios_base::beg); std::vector<char> dxbcCode(length); ifile.read(dxbcCode.data(), length); DxbcReader reader(dxbcCode.data(), dxbcCode.size()); DxbcModule module(reader); DxbcModuleInfo moduleInfo; moduleInfo.options.useSubgroupOpsForAtomicCounters = true; moduleInfo.options.useDemoteToHelperInvocation = true; moduleInfo.options.minSsboAlignment = 4; moduleInfo.xfb = nullptr; Rc<DxvkShader> shader = module.compile(moduleInfo, ifileName); std::ofstream ofile(str::fromws(argv[2]), std::ios::binary); shader->dump(ofile); return 0; } catch (const DxvkError& e) { Logger::err(e.message()); return 1; } }
26.929825
66
0.646906
oltolm
9c399dd6dae3c207cde1078bcbf39c9c0a9958e5
193
hpp
C++
include/ZombieArena.hpp
felixny/Arena
24d6b02584129a8c7db706c6f768ac9986e4b9ae
[ "MIT" ]
null
null
null
include/ZombieArena.hpp
felixny/Arena
24d6b02584129a8c7db706c6f768ac9986e4b9ae
[ "MIT" ]
null
null
null
include/ZombieArena.hpp
felixny/Arena
24d6b02584129a8c7db706c6f768ac9986e4b9ae
[ "MIT" ]
null
null
null
#pragma once #include "Zombie.hpp" #include <SFML/Graphics.hpp> using namespace sf; int createBackground(VertexArray& rVA, IntRect arena); Zombie* createHorde(int numZombies, IntRect arena);
21.444444
54
0.782383
felixny
9c3cd181c1640bdb7f1f2fe284617127b57d9fa7
4,406
cc
C++
src/types/ethaddr.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
null
null
null
src/types/ethaddr.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
null
null
null
src/types/ethaddr.cc
Alexey-Ershov/runos
dfbf8f74d7f45d25f0d4fad743b51f572ec272c9
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2015 Applied Research Center for Computer Networks * * 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 "ethaddr.hh" #include <regex> #include <istream> #include <boost/format.hpp> namespace runos { static unsigned long long parseMAC(const std::string &str) { static const std::string mac_pattern_colon = "([[:xdigit:]]{2}):([[:xdigit:]]{2}):" "([[:xdigit:]]{2}):([[:xdigit:]]{2}):" "([[:xdigit:]]{2}):([[:xdigit:]]{2})"; static const std::string mac_pattern_dash = "([[:xdigit:]]{2})-([[:xdigit:]]{2})-" "([[:xdigit:]]{2})-([[:xdigit:]]{2})-" "([[:xdigit:]]{2})-([[:xdigit:]]{2})"; static const std::string mac_pattern_dots = "^([[:xdigit:]]{2})([[:xdigit:]]{2})." "([[:xdigit:]]{2})([[:xdigit:]]{2})." "([[:xdigit:]]{2})([[:xdigit:]]{2})"; static const std::string mac_pattern = mac_pattern_colon + '|' + mac_pattern_dash + '|' + mac_pattern_dots; static const auto mac_regex = std::regex(mac_pattern, std::regex::optimize); std::smatch match; if (not std::regex_match(str, match, mac_regex)) { throw ethaddr::bad_representation("Bad MAC address: " + str); } size_t base = (match[1].length() > 0) ? 0 : // colon ( match[7].length() > 0 ? 6 /* dash */ : 12 /* dots */); unsigned long long res = 0; for (size_t oct = 1; oct <= 6; ++oct) { res <<= 8; res |= (uint8_t) std::stoi(match[base+oct], 0, 16); } return res; } ethaddr::ethaddr(const std::string &str) : data_(parseMAC(str)) { } ethaddr::ethaddr(uint64_t num) : data_(num) { if (num & 0xffff000000000000UL) { throw bad_representation("non-zero uint64_t padding of 48-bit mac"); } } ethaddr::ethaddr(const bytes_type &octets) noexcept : data_( ((unsigned long long) octets[0] << 40ULL) | ((unsigned long long) octets[1] << 32ULL) | ((unsigned long long) octets[2] << 24ULL) | ((unsigned long long) octets[3] << 16ULL) | ((unsigned long long) octets[4] << 8ULL ) | ((unsigned long long) octets[5]) ) { } ethaddr::bytes_type ethaddr::to_octets() const noexcept { uint64_t num = to_number(); return bytes_type{{ (uint8_t) ((num & 0xff0000000000ULL) >> 40ULL), (uint8_t) ((num & 0xff00000000ULL) >> 32ULL), (uint8_t) ((num & 0xff000000ULL) >> 24ULL), (uint8_t) ((num & 0xff0000ULL) >> 16ULL), (uint8_t) ((num & 0xff00ULL) >> 8ULL), (uint8_t) ((num & 0xffULL) >> 0ULL) }}; } bool is_broadcast(const ethaddr& addr) noexcept { return addr.data_.all(); } bool is_multicast(const ethaddr& addr) noexcept { return addr.data_[48 - 8]; } bool is_unicast(const ethaddr& addr) noexcept { return not addr.data_[48 - 8]; } bool ethaddr::is_locally_administered() const noexcept { return data_[48 - 7]; } std::ostream& operator<<(std::ostream& out, const ethaddr& addr) { const auto& data = addr.to_octets(); return out << boost::format("%02x:%02x:%02x:%02x:%02x:%02x") % (unsigned)data[0] % (unsigned)data[1] % (unsigned)data[2] % (unsigned)data[3] % (unsigned)data[4] % (unsigned)data[5]; } std::istream& operator>>(std::istream& in, ethaddr& addr) { enum { mac_str_size = 2*ethaddr::nbytes /* octets */ + (ethaddr::nbytes-1) /* colon */ + 1 /* \0 */ }; char buf[mac_str_size]; buf[mac_str_size-1] = '\0'; std::istream::sentry s(in); if (s) try { in.read(buf, mac_str_size - 1); addr = ethaddr(buf); } catch (ethaddr::bad_representation) { in.setstate(std::ios::failbit); } return in; } } // namespace runos using runos::ethaddr; size_t std::hash<ethaddr>::operator() (const ethaddr& addr) const { return std::hash<unsigned long long>()(addr.to_number()); }
28.425806
76
0.593736
Alexey-Ershov
9c3e998f68ba6852349807d3c00020e672422213
7,736
cpp
C++
2019/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
2019/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
2019/day19/main.cpp
batduck27/Advent_of_code
6b2dadf28bebd2301464c864f5112dccede9762b
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <unordered_map> #include <queue> enum OPCODE { ADD = 1, MUL = 2, IN = 3, OUT = 4, JMPT = 5, JMPF = 6, LT = 7, EQ = 8, ROFF = 9, HALT = 99, }; enum PARAM_MODE { POSITION = 0, IMMEDIATE = 1, RELATIVE = 2, }; static const std::unordered_map<enum OPCODE, int> opSizes{ { ADD, 4 }, { MUL, 4 }, { IN, 2 }, { OUT, 2 }, { JMPT, 3 }, { JMPF, 3 }, { LT, 4 }, { EQ, 4 }, { ROFF, 2 }, { HALT, 1 }, }; typedef struct Instruction { long long opcode; long long param1, param2, param3; enum PARAM_MODE mode1, mode2, mode3; } Instruction; class IntCodeComputer { private: std::queue<long long> input; std::unordered_map<long long, long long> v; std::unordered_map<long long, long long> copyV; long long ip; // instruction pointer long long diagCode; long long relativeBase; Instruction getNextInstruction(); long long getValueByMode(long long param, enum PARAM_MODE mode); void setValueByMode(long long param, enum PARAM_MODE mode, long long val); void addInstruction(Instruction ins); void mulInstruction(Instruction ins); void inInstruction(Instruction ins); void outInstruction(Instruction ins); void jmptInstruction(Instruction ins); void jmpfInstruction(Instruction ins); void ltInstruction(Instruction ins); void eqInstruction(Instruction ins); void roffInstruction(Instruction ins); public: IntCodeComputer() : input(), v(), copyV(), ip(), diagCode(), relativeBase() { } IntCodeComputer(std::unordered_map<long long, long long> v) : input(), v(v), copyV(v), ip(), diagCode(), relativeBase() { } bool hasHalted(); long long run(); void reset(); void provideInput(long long in); }; bool pointInBeam(IntCodeComputer& computer, int r, int c) { computer.reset(); computer.provideInput(c); computer.provideInput(r); return computer.run(); } int solvePart1(IntCodeComputer& computer, int size) { int points = 0; for (int r = 0; r < size; ++ r) { for (int c = r; c < size; ++ c) { points += pointInBeam(computer, r, c); } } return points; } int solvePart2(IntCodeComputer& computer, int size) { const int offset = size - 1; int r = size; int c = 0; while (true) { while (!pointInBeam(computer, r, c)) { ++ c; } if (pointInBeam(computer, r - offset, c) && pointInBeam(computer, r - offset, c + offset)) { break; } ++ r; } return c * 10000 + r - offset; } int main() { std::ifstream fin("data.in"); std::unordered_map<long long, long long> v; long long x, i = 0; while (fin >> x) { v[i ++] = x; fin.ignore(); } fin.close(); IntCodeComputer computer{v}; std::cout << "The answer for part1 is: " << solvePart1(computer, 50) << "\n"; std::cout << "The answer for part2 is: " << solvePart2(computer, 100) << "\n"; return 0; } long long IntCodeComputer::getValueByMode(long long param, enum PARAM_MODE mode) { if (mode == POSITION) { return v[param]; } if (mode == RELATIVE) { return v[param + relativeBase]; } return param; } void IntCodeComputer::setValueByMode(long long param, enum PARAM_MODE mode, long long val) { if (mode == POSITION) { v[param] = val; } else if (mode == RELATIVE) { v[param + relativeBase] = val; } else { std::cout << "SetValueByMode called with IMMEDIATE mode. HALTING\n"; ip = -1; } } void IntCodeComputer::provideInput(long long in) { input.push(in); } void IntCodeComputer::reset() { ip = 0; diagCode = 0; relativeBase = 0; v = copyV; while (!input.empty()) { input.pop(); } } bool IntCodeComputer::hasHalted() { return (ip < 0); } long long IntCodeComputer::run() { diagCode = 0; while (!hasHalted()) { Instruction ins = getNextInstruction(); switch (ins.opcode) { case ADD: addInstruction(ins); break; case MUL: mulInstruction(ins); break; case IN: inInstruction(ins); break; case OUT: outInstruction(ins); break; case JMPT: jmptInstruction(ins); break; case JMPF: jmpfInstruction(ins); break; case LT: ltInstruction(ins); break; case EQ: eqInstruction(ins); break; case ROFF: roffInstruction(ins); break; case HALT: ip = -1; break; default: std::cout << "Invalid opcode " << ins.opcode << " at index " << ip << "\n"; ip = -1; break; } } return diagCode; } Instruction IntCodeComputer::getNextInstruction() { Instruction ins = {0}; ins.opcode = v[ip] % 100; ins.mode1 = (enum PARAM_MODE)((v[ip] / 100) % 10); ins.mode2 = (enum PARAM_MODE)((v[ip] / 1000) % 10); ins.mode3 = (enum PARAM_MODE)((v[ip] / 10000) % 10); if (ins.opcode == HALT) { return ins; } ins.param1 = v[ip + 1]; if (ins.opcode == IN || ins.opcode == OUT || ins.opcode == ROFF) { return ins; } ins.param2 = v[ip + 2]; if (ins.opcode == JMPT || ins.opcode == JMPF) { return ins; } ins.param3 = v[ip + 3]; return ins; } void IntCodeComputer::addInstruction(Instruction ins) { long long tmp = getValueByMode(ins.param1, ins.mode1) + getValueByMode(ins.param2, ins.mode2); setValueByMode(ins.param3, ins.mode3, tmp); ip += opSizes.at(ADD); } void IntCodeComputer::mulInstruction(Instruction ins) { long long tmp = getValueByMode(ins.param1, ins.mode1) * getValueByMode(ins.param2, ins.mode2); setValueByMode(ins.param3, ins.mode3, tmp); ip += opSizes.at(MUL); } void IntCodeComputer::inInstruction(Instruction ins) { if (input.empty()) { std::cout << "No input in queue. HALTING\n"; ip = -1; } setValueByMode(ins.param1, ins.mode1, input.front()); input.pop(); ip += opSizes.at(IN); } void IntCodeComputer::outInstruction(Instruction ins) { diagCode = getValueByMode(ins.param1, ins.mode1); ip += opSizes.at(OUT); } void IntCodeComputer::jmptInstruction(Instruction ins) { if (getValueByMode(ins.param1, ins.mode1) != 0) { ip = getValueByMode(ins.param2, ins.mode2); } else { ip += opSizes.at(JMPT); } } void IntCodeComputer::jmpfInstruction(Instruction ins) { if (getValueByMode(ins.param1, ins.mode1) == 0) { ip = getValueByMode(ins.param2, ins.mode2); } else { ip += opSizes.at(JMPF); } } void IntCodeComputer::ltInstruction(Instruction ins) { long long tmp = ((getValueByMode(ins.param1, ins.mode1) < getValueByMode(ins.param2, ins.mode2)) ? 1LL : 0LL); setValueByMode(ins.param3, ins.mode3, tmp); ip += opSizes.at(LT); } void IntCodeComputer::eqInstruction(Instruction ins) { long long tmp = ((getValueByMode(ins.param1, ins.mode1) == getValueByMode(ins.param2, ins.mode2)) ? 1LL : 0LL); setValueByMode(ins.param3, ins.mode3, tmp); ip += opSizes.at(EQ); } void IntCodeComputer::roffInstruction(Instruction ins) { relativeBase += getValueByMode(ins.param1, ins.mode1); ip += opSizes.at(ROFF); }
23.442424
92
0.569545
batduck27
9c3ec9fa07f42549ef4c45bd74353252a643817c
29,901
cc
C++
Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
Boss2D/addon/webrtc-jumpingyang001_for_boss/modules/rtp_rtcp/source/rtcp_sender_unittest.cc
Yash-Wasalwar-07/Boss2D
37c5ba0f1c83c89810359a207cabfa0905f803d2
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <memory> #include BOSS_WEBRTC_U_common_types_h //original-code:"common_types.h" // NOLINT(build/include) #include BOSS_WEBRTC_U_modules__rtp_rtcp__source__rtcp_packet__bye_h //original-code:"modules/rtp_rtcp/source/rtcp_packet/bye.h" #include BOSS_WEBRTC_U_modules__rtp_rtcp__source__rtcp_packet__common_header_h //original-code:"modules/rtp_rtcp/source/rtcp_packet/common_header.h" #include BOSS_WEBRTC_U_modules__rtp_rtcp__source__rtcp_sender_h //original-code:"modules/rtp_rtcp/source/rtcp_sender.h" #include BOSS_WEBRTC_U_modules__rtp_rtcp__source__rtp_rtcp_impl_h //original-code:"modules/rtp_rtcp/source/rtp_rtcp_impl.h" #include BOSS_WEBRTC_U_rtc_base__rate_limiter_h //original-code:"rtc_base/rate_limiter.h" #include "test/gmock.h" #include "test/gtest.h" #include "test/mock_transport.h" #include "test/rtcp_packet_parser.h" using ::testing::_; using ::testing::ElementsAre; using ::testing::Invoke; using ::testing::SizeIs; namespace webrtc { class RtcpPacketTypeCounterObserverImpl : public RtcpPacketTypeCounterObserver { public: RtcpPacketTypeCounterObserverImpl() : ssrc_(0) {} ~RtcpPacketTypeCounterObserverImpl() override = default; void RtcpPacketTypesCounterUpdated( uint32_t ssrc, const RtcpPacketTypeCounter& packet_counter) override { ssrc_ = ssrc; counter_ = packet_counter; } uint32_t ssrc_; RtcpPacketTypeCounter counter_; }; class TestTransport : public Transport, public RtpData { public: TestTransport() {} bool SendRtp(const uint8_t* /*data*/, size_t /*len*/, const PacketOptions& options) override { return false; } bool SendRtcp(const uint8_t* data, size_t len) override { parser_.Parse(data, len); return true; } int OnReceivedPayloadData(const uint8_t* payload_data, size_t payload_size, const WebRtcRTPHeader* rtp_header) override { return 0; } test::RtcpPacketParser parser_; }; namespace { static const uint32_t kSenderSsrc = 0x11111111; static const uint32_t kRemoteSsrc = 0x22222222; static const uint32_t kStartRtpTimestamp = 0x34567; static const uint32_t kRtpTimestamp = 0x45678; } // namespace class RtcpSenderTest : public ::testing::Test { protected: RtcpSenderTest() : clock_(1335900000), receive_statistics_(ReceiveStatistics::Create(&clock_)), retransmission_rate_limiter_(&clock_, 1000) { RtpRtcp::Configuration configuration; configuration.audio = false; configuration.clock = &clock_; configuration.outgoing_transport = &test_transport_; configuration.retransmission_rate_limiter = &retransmission_rate_limiter_; rtp_rtcp_impl_.reset(new ModuleRtpRtcpImpl(configuration)); rtcp_sender_.reset(new RTCPSender(false, &clock_, receive_statistics_.get(), nullptr, nullptr, &test_transport_, configuration.rtcp_interval_config)); rtcp_sender_->SetSSRC(kSenderSsrc); rtcp_sender_->SetRemoteSSRC(kRemoteSsrc); rtcp_sender_->SetTimestampOffset(kStartRtpTimestamp); rtcp_sender_->SetLastRtpTime(kRtpTimestamp, clock_.TimeInMilliseconds()); } void InsertIncomingPacket(uint32_t remote_ssrc, uint16_t seq_num) { RTPHeader header; header.ssrc = remote_ssrc; header.sequenceNumber = seq_num; header.timestamp = 12345; header.headerLength = 12; size_t kPacketLength = 100; receive_statistics_->IncomingPacket(header, kPacketLength, false); } test::RtcpPacketParser* parser() { return &test_transport_.parser_; } RTCPSender::FeedbackState feedback_state() { return rtp_rtcp_impl_->GetFeedbackState(); } SimulatedClock clock_; TestTransport test_transport_; std::unique_ptr<ReceiveStatistics> receive_statistics_; std::unique_ptr<ModuleRtpRtcpImpl> rtp_rtcp_impl_; std::unique_ptr<RTCPSender> rtcp_sender_; RateLimiter retransmission_rate_limiter_; }; TEST_F(RtcpSenderTest, SetRtcpStatus) { EXPECT_EQ(RtcpMode::kOff, rtcp_sender_->Status()); rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(RtcpMode::kReducedSize, rtcp_sender_->Status()); } TEST_F(RtcpSenderTest, SetSendingStatus) { EXPECT_FALSE(rtcp_sender_->Sending()); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), true)); EXPECT_TRUE(rtcp_sender_->Sending()); } TEST_F(RtcpSenderTest, NoPacketSentIfOff) { rtcp_sender_->SetRTCPStatus(RtcpMode::kOff); EXPECT_EQ(-1, rtcp_sender_->SendRTCP(feedback_state(), kRtcpSr)); } TEST_F(RtcpSenderTest, SendSr) { const uint32_t kPacketCount = 0x12345; const uint32_t kOctetCount = 0x23456; rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); RTCPSender::FeedbackState feedback_state = rtp_rtcp_impl_->GetFeedbackState(); rtcp_sender_->SetSendingStatus(feedback_state, true); feedback_state.packets_sent = kPacketCount; feedback_state.media_bytes_sent = kOctetCount; NtpTime ntp = clock_.CurrentNtpTime(); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpSr)); EXPECT_EQ(1, parser()->sender_report()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->sender_report()->sender_ssrc()); EXPECT_EQ(ntp, parser()->sender_report()->ntp()); EXPECT_EQ(kPacketCount, parser()->sender_report()->sender_packet_count()); EXPECT_EQ(kOctetCount, parser()->sender_report()->sender_octet_count()); EXPECT_EQ(kStartRtpTimestamp + kRtpTimestamp, parser()->sender_report()->rtp_timestamp()); EXPECT_EQ(0U, parser()->sender_report()->report_blocks().size()); } TEST_F(RtcpSenderTest, DoNotSendSrBeforeRtp) { rtcp_sender_.reset(new RTCPSender(false, &clock_, receive_statistics_.get(), nullptr, nullptr, &test_transport_, RtcpIntervalConfig{})); rtcp_sender_->SetSSRC(kSenderSsrc); rtcp_sender_->SetRemoteSSRC(kRemoteSsrc); rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); rtcp_sender_->SetSendingStatus(feedback_state(), true); // Sender Report shouldn't be send as an SR nor as a Report. rtcp_sender_->SendRTCP(feedback_state(), kRtcpSr); EXPECT_EQ(0, parser()->sender_report()->num_packets()); rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport); EXPECT_EQ(0, parser()->sender_report()->num_packets()); // Other packets (e.g. Pli) are allowed, even if useless. EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpPli)); EXPECT_EQ(1, parser()->pli()->num_packets()); } TEST_F(RtcpSenderTest, DoNotSendCompundBeforeRtp) { rtcp_sender_.reset(new RTCPSender(false, &clock_, receive_statistics_.get(), nullptr, nullptr, &test_transport_, RtcpIntervalConfig{})); rtcp_sender_->SetSSRC(kSenderSsrc); rtcp_sender_->SetRemoteSSRC(kRemoteSsrc); rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); rtcp_sender_->SetSendingStatus(feedback_state(), true); // In compound mode no packets are allowed (e.g. Pli) because compound mode // should start with Sender Report. EXPECT_EQ(-1, rtcp_sender_->SendRTCP(feedback_state(), kRtcpPli)); EXPECT_EQ(0, parser()->pli()->num_packets()); } TEST_F(RtcpSenderTest, SendRr) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr)); EXPECT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->receiver_report()->sender_ssrc()); EXPECT_EQ(0U, parser()->receiver_report()->report_blocks().size()); } TEST_F(RtcpSenderTest, SendRrWithOneReportBlock) { const uint16_t kSeqNum = 11111; InsertIncomingPacket(kRemoteSsrc, kSeqNum); rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr)); EXPECT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->receiver_report()->sender_ssrc()); ASSERT_EQ(1U, parser()->receiver_report()->report_blocks().size()); const rtcp::ReportBlock& rb = parser()->receiver_report()->report_blocks()[0]; EXPECT_EQ(kRemoteSsrc, rb.source_ssrc()); EXPECT_EQ(0U, rb.fraction_lost()); EXPECT_EQ(0, rb.cumulative_lost_signed()); EXPECT_EQ(kSeqNum, rb.extended_high_seq_num()); } TEST_F(RtcpSenderTest, SendRrWithTwoReportBlocks) { const uint16_t kSeqNum = 11111; InsertIncomingPacket(kRemoteSsrc, kSeqNum); InsertIncomingPacket(kRemoteSsrc + 1, kSeqNum + 1); rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr)); EXPECT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->receiver_report()->sender_ssrc()); EXPECT_EQ(2U, parser()->receiver_report()->report_blocks().size()); EXPECT_EQ(kRemoteSsrc, parser()->receiver_report()->report_blocks()[0].source_ssrc()); EXPECT_EQ(kRemoteSsrc + 1, parser()->receiver_report()->report_blocks()[1].source_ssrc()); } TEST_F(RtcpSenderTest, SendSdes) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SetCNAME("alice@host")); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpSdes)); EXPECT_EQ(1, parser()->sdes()->num_packets()); EXPECT_EQ(1U, parser()->sdes()->chunks().size()); EXPECT_EQ(kSenderSsrc, parser()->sdes()->chunks()[0].ssrc); EXPECT_EQ("alice@host", parser()->sdes()->chunks()[0].cname); } TEST_F(RtcpSenderTest, SendSdesWithMaxChunks) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SetCNAME("alice@host")); const char cname[] = "smith@host"; for (size_t i = 0; i < 30; ++i) { const uint32_t csrc = 0x1234 + i; EXPECT_EQ(0, rtcp_sender_->AddMixedCNAME(csrc, cname)); } EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpSdes)); EXPECT_EQ(1, parser()->sdes()->num_packets()); EXPECT_EQ(31U, parser()->sdes()->chunks().size()); } TEST_F(RtcpSenderTest, SdesIncludedInCompoundPacket) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SetCNAME("alice@host")); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(1, parser()->sdes()->num_packets()); EXPECT_EQ(1U, parser()->sdes()->chunks().size()); } TEST_F(RtcpSenderTest, SendBye) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpBye)); EXPECT_EQ(1, parser()->bye()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->bye()->sender_ssrc()); } TEST_F(RtcpSenderTest, StopSendingTriggersBye) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), true)); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), false)); EXPECT_EQ(1, parser()->bye()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->bye()->sender_ssrc()); } TEST_F(RtcpSenderTest, SendApp) { const uint8_t kSubType = 30; uint32_t name = 'n' << 24; name += 'a' << 16; name += 'm' << 8; name += 'e'; const uint8_t kData[] = {'t', 'e', 's', 't', 'd', 'a', 't', 'a'}; EXPECT_EQ(0, rtcp_sender_->SetApplicationSpecificData(kSubType, name, kData, sizeof(kData))); rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpApp)); EXPECT_EQ(1, parser()->app()->num_packets()); EXPECT_EQ(kSubType, parser()->app()->sub_type()); EXPECT_EQ(name, parser()->app()->name()); EXPECT_EQ(sizeof(kData), parser()->app()->data_size()); EXPECT_EQ(0, memcmp(kData, parser()->app()->data(), sizeof(kData))); } TEST_F(RtcpSenderTest, SendEmptyApp) { const uint8_t kSubType = 30; const uint32_t kName = 0x6E616D65; EXPECT_EQ( 0, rtcp_sender_->SetApplicationSpecificData(kSubType, kName, nullptr, 0)); rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpApp)); EXPECT_EQ(1, parser()->app()->num_packets()); EXPECT_EQ(kSubType, parser()->app()->sub_type()); EXPECT_EQ(kName, parser()->app()->name()); EXPECT_EQ(0U, parser()->app()->data_size()); } TEST_F(RtcpSenderTest, SetInvalidApplicationSpecificData) { const uint8_t kData[] = {'t', 'e', 's', 't', 'd', 'a', 't'}; const uint16_t kInvalidDataLength = sizeof(kData) / sizeof(kData[0]); EXPECT_EQ(-1, rtcp_sender_->SetApplicationSpecificData( 0, 0, kData, kInvalidDataLength)); // Should by multiple of 4. } TEST_F(RtcpSenderTest, SendFir) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpFir)); EXPECT_EQ(1, parser()->fir()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->fir()->sender_ssrc()); EXPECT_EQ(1U, parser()->fir()->requests().size()); EXPECT_EQ(kRemoteSsrc, parser()->fir()->requests()[0].ssrc); uint8_t seq = parser()->fir()->requests()[0].seq_nr; EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpFir)); EXPECT_EQ(2, parser()->fir()->num_packets()); EXPECT_EQ(seq + 1, parser()->fir()->requests()[0].seq_nr); } TEST_F(RtcpSenderTest, SendPli) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpPli)); EXPECT_EQ(1, parser()->pli()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->pli()->sender_ssrc()); EXPECT_EQ(kRemoteSsrc, parser()->pli()->media_ssrc()); } TEST_F(RtcpSenderTest, SendNack) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); const uint16_t kList[] = {0, 1, 16}; const int32_t kListLength = sizeof(kList) / sizeof(kList[0]); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpNack, kListLength, kList)); EXPECT_EQ(1, parser()->nack()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->nack()->sender_ssrc()); EXPECT_EQ(kRemoteSsrc, parser()->nack()->media_ssrc()); EXPECT_THAT(parser()->nack()->packet_ids(), ElementsAre(0, 1, 16)); } TEST_F(RtcpSenderTest, RembNotIncludedBeforeSet) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr); ASSERT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(0, parser()->remb()->num_packets()); } TEST_F(RtcpSenderTest, RembNotIncludedAfterUnset) { const uint64_t kBitrate = 261011; const std::vector<uint32_t> kSsrcs = {kRemoteSsrc, kRemoteSsrc + 1}; rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); rtcp_sender_->SetRemb(kBitrate, kSsrcs); rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr); ASSERT_EQ(1, parser()->receiver_report()->num_packets()); EXPECT_EQ(1, parser()->remb()->num_packets()); // Turn off REMB. rtcp_sender no longer should send it. rtcp_sender_->UnsetRemb(); rtcp_sender_->SendRTCP(feedback_state(), kRtcpRr); ASSERT_EQ(2, parser()->receiver_report()->num_packets()); EXPECT_EQ(1, parser()->remb()->num_packets()); } TEST_F(RtcpSenderTest, SendRemb) { const uint64_t kBitrate = 261011; const std::vector<uint32_t> kSsrcs = {kRemoteSsrc, kRemoteSsrc + 1}; rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); rtcp_sender_->SetRemb(kBitrate, kSsrcs); rtcp_sender_->SendRTCP(feedback_state(), kRtcpRemb); EXPECT_EQ(1, parser()->remb()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->remb()->sender_ssrc()); EXPECT_EQ(kBitrate, parser()->remb()->bitrate_bps()); EXPECT_THAT(parser()->remb()->ssrcs(), ElementsAre(kRemoteSsrc, kRemoteSsrc + 1)); } TEST_F(RtcpSenderTest, RembIncludedInEachCompoundPacketAfterSet) { const int kBitrate = 261011; const std::vector<uint32_t> kSsrcs = {kRemoteSsrc, kRemoteSsrc + 1}; rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); rtcp_sender_->SetRemb(kBitrate, kSsrcs); rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport); EXPECT_EQ(1, parser()->remb()->num_packets()); // REMB should be included in each compound packet. rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport); EXPECT_EQ(2, parser()->remb()->num_packets()); } TEST_F(RtcpSenderTest, SendXrWithVoipMetric) { rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); RTCPVoIPMetric metric; metric.lossRate = 1; metric.discardRate = 2; metric.burstDensity = 3; metric.gapDensity = 4; metric.burstDuration = 0x1111; metric.gapDuration = 0x2222; metric.roundTripDelay = 0x3333; metric.endSystemDelay = 0x4444; metric.signalLevel = 5; metric.noiseLevel = 6; metric.RERL = 7; metric.Gmin = 8; metric.Rfactor = 9; metric.extRfactor = 10; metric.MOSLQ = 11; metric.MOSCQ = 12; metric.RXconfig = 13; metric.JBnominal = 0x5555; metric.JBmax = 0x6666; metric.JBabsMax = 0x7777; EXPECT_EQ(0, rtcp_sender_->SetRTCPVoIPMetrics(&metric)); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpXrVoipMetric)); EXPECT_EQ(1, parser()->xr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->xr()->sender_ssrc()); ASSERT_TRUE(parser()->xr()->voip_metric()); EXPECT_EQ(kRemoteSsrc, parser()->xr()->voip_metric()->ssrc()); const auto& parsed_metric = parser()->xr()->voip_metric()->voip_metric(); EXPECT_EQ(metric.lossRate, parsed_metric.lossRate); EXPECT_EQ(metric.discardRate, parsed_metric.discardRate); EXPECT_EQ(metric.burstDensity, parsed_metric.burstDensity); EXPECT_EQ(metric.gapDensity, parsed_metric.gapDensity); EXPECT_EQ(metric.burstDuration, parsed_metric.burstDuration); EXPECT_EQ(metric.gapDuration, parsed_metric.gapDuration); EXPECT_EQ(metric.roundTripDelay, parsed_metric.roundTripDelay); EXPECT_EQ(metric.endSystemDelay, parsed_metric.endSystemDelay); EXPECT_EQ(metric.signalLevel, parsed_metric.signalLevel); EXPECT_EQ(metric.noiseLevel, parsed_metric.noiseLevel); EXPECT_EQ(metric.RERL, parsed_metric.RERL); EXPECT_EQ(metric.Gmin, parsed_metric.Gmin); EXPECT_EQ(metric.Rfactor, parsed_metric.Rfactor); EXPECT_EQ(metric.extRfactor, parsed_metric.extRfactor); EXPECT_EQ(metric.MOSLQ, parsed_metric.MOSLQ); EXPECT_EQ(metric.MOSCQ, parsed_metric.MOSCQ); EXPECT_EQ(metric.RXconfig, parsed_metric.RXconfig); EXPECT_EQ(metric.JBnominal, parsed_metric.JBnominal); EXPECT_EQ(metric.JBmax, parsed_metric.JBmax); EXPECT_EQ(metric.JBabsMax, parsed_metric.JBabsMax); } TEST_F(RtcpSenderTest, SendXrWithDlrr) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); RTCPSender::FeedbackState feedback_state = rtp_rtcp_impl_->GetFeedbackState(); rtcp::ReceiveTimeInfo last_xr_rr; last_xr_rr.ssrc = 0x11111111; last_xr_rr.last_rr = 0x22222222; last_xr_rr.delay_since_last_rr = 0x33333333; feedback_state.last_xr_rtis.push_back(last_xr_rr); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpReport)); EXPECT_EQ(1, parser()->xr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->xr()->sender_ssrc()); ASSERT_THAT(parser()->xr()->dlrr().sub_blocks(), SizeIs(1)); EXPECT_EQ(last_xr_rr.ssrc, parser()->xr()->dlrr().sub_blocks()[0].ssrc); EXPECT_EQ(last_xr_rr.last_rr, parser()->xr()->dlrr().sub_blocks()[0].last_rr); EXPECT_EQ(last_xr_rr.delay_since_last_rr, parser()->xr()->dlrr().sub_blocks()[0].delay_since_last_rr); } TEST_F(RtcpSenderTest, SendXrWithMultipleDlrrSubBlocks) { const size_t kNumReceivers = 2; rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); RTCPSender::FeedbackState feedback_state = rtp_rtcp_impl_->GetFeedbackState(); for (size_t i = 0; i < kNumReceivers; ++i) { rtcp::ReceiveTimeInfo last_xr_rr; last_xr_rr.ssrc = i; last_xr_rr.last_rr = (i + 1) * 100; last_xr_rr.delay_since_last_rr = (i + 2) * 200; feedback_state.last_xr_rtis.push_back(last_xr_rr); } EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state, kRtcpReport)); EXPECT_EQ(1, parser()->xr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->xr()->sender_ssrc()); ASSERT_THAT(parser()->xr()->dlrr().sub_blocks(), SizeIs(kNumReceivers)); for (size_t i = 0; i < kNumReceivers; ++i) { EXPECT_EQ(feedback_state.last_xr_rtis[i].ssrc, parser()->xr()->dlrr().sub_blocks()[i].ssrc); EXPECT_EQ(feedback_state.last_xr_rtis[i].last_rr, parser()->xr()->dlrr().sub_blocks()[i].last_rr); EXPECT_EQ(feedback_state.last_xr_rtis[i].delay_since_last_rr, parser()->xr()->dlrr().sub_blocks()[i].delay_since_last_rr); } } TEST_F(RtcpSenderTest, SendXrWithRrtr) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), false)); rtcp_sender_->SendRtcpXrReceiverReferenceTime(true); NtpTime ntp = clock_.CurrentNtpTime(); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(1, parser()->xr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->xr()->sender_ssrc()); EXPECT_FALSE(parser()->xr()->dlrr()); EXPECT_FALSE(parser()->xr()->voip_metric()); ASSERT_TRUE(parser()->xr()->rrtr()); EXPECT_EQ(ntp, parser()->xr()->rrtr()->ntp()); } TEST_F(RtcpSenderTest, TestNoXrRrtrSentIfSending) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), true)); rtcp_sender_->SendRtcpXrReceiverReferenceTime(true); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(0, parser()->xr()->num_packets()); } TEST_F(RtcpSenderTest, TestNoXrRrtrSentIfNotEnabled) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_EQ(0, rtcp_sender_->SetSendingStatus(feedback_state(), false)); rtcp_sender_->SendRtcpXrReceiverReferenceTime(false); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(0, parser()->xr()->num_packets()); } TEST_F(RtcpSenderTest, TestRegisterRtcpPacketTypeObserver) { RtcpPacketTypeCounterObserverImpl observer; rtcp_sender_.reset(new RTCPSender(false, &clock_, receive_statistics_.get(), &observer, nullptr, &test_transport_, RtcpIntervalConfig{})); rtcp_sender_->SetRemoteSSRC(kRemoteSsrc); rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpPli)); EXPECT_EQ(1, parser()->pli()->num_packets()); EXPECT_EQ(kRemoteSsrc, observer.ssrc_); EXPECT_EQ(1U, observer.counter_.pli_packets); EXPECT_EQ(clock_.TimeInMilliseconds(), observer.counter_.first_packet_time_ms); } TEST_F(RtcpSenderTest, SendTmmbr) { const unsigned int kBitrateBps = 312000; rtcp_sender_->SetRTCPStatus(RtcpMode::kReducedSize); rtcp_sender_->SetTargetBitrate(kBitrateBps); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpTmmbr)); EXPECT_EQ(1, parser()->tmmbr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->tmmbr()->sender_ssrc()); EXPECT_EQ(1U, parser()->tmmbr()->requests().size()); EXPECT_EQ(kBitrateBps, parser()->tmmbr()->requests()[0].bitrate_bps()); // TODO(asapersson): tmmbr_item()->Overhead() looks broken, always zero. } TEST_F(RtcpSenderTest, TmmbrIncludedInCompoundPacketIfEnabled) { const unsigned int kBitrateBps = 312000; rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); EXPECT_FALSE(rtcp_sender_->TMMBR()); rtcp_sender_->SetTMMBRStatus(true); EXPECT_TRUE(rtcp_sender_->TMMBR()); rtcp_sender_->SetTargetBitrate(kBitrateBps); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(1, parser()->tmmbr()->num_packets()); EXPECT_EQ(1U, parser()->tmmbr()->requests().size()); // TMMBR should be included in each compound packet. EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(2, parser()->tmmbr()->num_packets()); rtcp_sender_->SetTMMBRStatus(false); EXPECT_FALSE(rtcp_sender_->TMMBR()); } TEST_F(RtcpSenderTest, SendTmmbn) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); rtcp_sender_->SetSendingStatus(feedback_state(), true); std::vector<rtcp::TmmbItem> bounding_set; const uint32_t kBitrateBps = 32768000; const uint32_t kPacketOh = 40; const uint32_t kSourceSsrc = 12345; const rtcp::TmmbItem tmmbn(kSourceSsrc, kBitrateBps, kPacketOh); bounding_set.push_back(tmmbn); rtcp_sender_->SetTmmbn(bounding_set); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpSr)); EXPECT_EQ(1, parser()->sender_report()->num_packets()); EXPECT_EQ(1, parser()->tmmbn()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->tmmbn()->sender_ssrc()); EXPECT_EQ(1U, parser()->tmmbn()->items().size()); EXPECT_EQ(kBitrateBps, parser()->tmmbn()->items()[0].bitrate_bps()); EXPECT_EQ(kPacketOh, parser()->tmmbn()->items()[0].packet_overhead()); EXPECT_EQ(kSourceSsrc, parser()->tmmbn()->items()[0].ssrc()); } // This test is written to verify actual behaviour. It does not seem // to make much sense to send an empty TMMBN, since there is no place // to put an actual limit here. It's just information that no limit // is set, which is kind of the starting assumption. // See http://code.google.com/p/webrtc/issues/detail?id=468 for one // situation where this caused confusion. TEST_F(RtcpSenderTest, SendsTmmbnIfSetAndEmpty) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); rtcp_sender_->SetSendingStatus(feedback_state(), true); std::vector<rtcp::TmmbItem> bounding_set; rtcp_sender_->SetTmmbn(bounding_set); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpSr)); EXPECT_EQ(1, parser()->sender_report()->num_packets()); EXPECT_EQ(1, parser()->tmmbn()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->tmmbn()->sender_ssrc()); EXPECT_EQ(0U, parser()->tmmbn()->items().size()); } TEST_F(RtcpSenderTest, SendCompoundPliRemb) { const int kBitrate = 261011; std::vector<uint32_t> ssrcs; ssrcs.push_back(kRemoteSsrc); rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); rtcp_sender_->SetRemb(kBitrate, ssrcs); std::set<RTCPPacketType> packet_types; packet_types.insert(kRtcpRemb); packet_types.insert(kRtcpPli); EXPECT_EQ(0, rtcp_sender_->SendCompoundRTCP(feedback_state(), packet_types)); EXPECT_EQ(1, parser()->remb()->num_packets()); EXPECT_EQ(1, parser()->pli()->num_packets()); } // This test is written to verify that BYE is always the last packet // type in a RTCP compoud packet. The rtcp_sender_ is recreated with // mock_transport, which is used to check for whether BYE at the end // of a RTCP compound packet. TEST_F(RtcpSenderTest, ByeMustBeLast) { MockTransport mock_transport; EXPECT_CALL(mock_transport, SendRtcp(_, _)) .WillOnce(Invoke([](const uint8_t* data, size_t len) { const uint8_t* next_packet = data; const uint8_t* const packet_end = data + len; rtcp::CommonHeader packet; while (next_packet < packet_end) { EXPECT_TRUE(packet.Parse(next_packet, packet_end - next_packet)); next_packet = packet.NextPacket(); if (packet.type() == rtcp::Bye::kPacketType) // Main test expectation. EXPECT_EQ(0, packet_end - next_packet) << "Bye packet should be last in a compound RTCP packet."; if (next_packet == packet_end) // Validate test was set correctly. EXPECT_EQ(packet.type(), rtcp::Bye::kPacketType) << "Last packet in this test expected to be Bye."; } return true; })); // Re-configure rtcp_sender_ with mock_transport_ rtcp_sender_.reset(new RTCPSender(false, &clock_, receive_statistics_.get(), nullptr, nullptr, &mock_transport, RtcpIntervalConfig{})); rtcp_sender_->SetSSRC(kSenderSsrc); rtcp_sender_->SetRemoteSSRC(kRemoteSsrc); rtcp_sender_->SetTimestampOffset(kStartRtpTimestamp); rtcp_sender_->SetLastRtpTime(kRtpTimestamp, clock_.TimeInMilliseconds()); // Set up XR VoIP metric to be included with BYE rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); RTCPVoIPMetric metric; EXPECT_EQ(0, rtcp_sender_->SetRTCPVoIPMetrics(&metric)); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpBye)); } TEST_F(RtcpSenderTest, SendXrWithTargetBitrate) { rtcp_sender_->SetRTCPStatus(RtcpMode::kCompound); const size_t kNumSpatialLayers = 2; const size_t kNumTemporalLayers = 2; VideoBitrateAllocation allocation; for (size_t sl = 0; sl < kNumSpatialLayers; ++sl) { uint32_t start_bitrate_bps = (sl + 1) * 100000; for (size_t tl = 0; tl < kNumTemporalLayers; ++tl) allocation.SetBitrate(sl, tl, start_bitrate_bps + (tl * 20000)); } rtcp_sender_->SetVideoBitrateAllocation(allocation); EXPECT_EQ(0, rtcp_sender_->SendRTCP(feedback_state(), kRtcpReport)); EXPECT_EQ(1, parser()->xr()->num_packets()); EXPECT_EQ(kSenderSsrc, parser()->xr()->sender_ssrc()); const absl::optional<rtcp::TargetBitrate>& target_bitrate = parser()->xr()->target_bitrate(); ASSERT_TRUE(target_bitrate); const std::vector<rtcp::TargetBitrate::BitrateItem>& bitrates = target_bitrate->GetTargetBitrates(); EXPECT_EQ(kNumSpatialLayers * kNumTemporalLayers, bitrates.size()); for (size_t sl = 0; sl < kNumSpatialLayers; ++sl) { uint32_t start_bitrate_bps = (sl + 1) * 100000; for (size_t tl = 0; tl < kNumTemporalLayers; ++tl) { size_t index = (sl * kNumSpatialLayers) + tl; const rtcp::TargetBitrate::BitrateItem& item = bitrates[index]; EXPECT_EQ(sl, item.spatial_layer); EXPECT_EQ(tl, item.temporal_layer); EXPECT_EQ(start_bitrate_bps + (tl * 20000), item.target_bitrate_kbps * 1000); } } } } // namespace webrtc
42.473011
148
0.720845
Yash-Wasalwar-07
9c40334d571488ee97d64179883e411b7551c701
9,665
cpp
C++
src/autowiring/test/ContextMapTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
87
2015-01-18T00:43:06.000Z
2022-02-11T17:40:50.000Z
src/autowiring/test/ContextMapTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
274
2015-01-03T04:50:49.000Z
2021-03-08T09:01:09.000Z
src/autowiring/test/ContextMapTest.cpp
CaseyCarter/autowiring
48e95a71308318c8ffb7ed1348e034fd9110f70c
[ "Apache-2.0" ]
15
2015-09-30T20:58:43.000Z
2020-12-19T21:24:56.000Z
// Copyright (C) 2012-2018 Leap Motion, Inc. All rights reserved. #include "stdafx.h" #include "TestFixtures/ExitRaceThreaded.hpp" #include "TestFixtures/SimpleThreaded.hpp" #include "autotesting/AutowiringEnclosure.h" #include <autowiring/autowiring.h> #include <autowiring/ContextMap.h> #include <string> #include THREAD_HEADER class ContextMapTest: public testing::Test { }; using namespace std; TEST_F(ContextMapTest, VerifySimple) { ContextMap<string> mp; std::weak_ptr<CoreContext> ctxtWeak; // Create a new context and add it to the map: { AutoCreateContext context; ctxtWeak = context; // Verify the reference count or the rest of the test will fail ASSERT_TRUE(context.unique()) << "A newly created context's use count isn't what was expected"; // Add and ensure the reference count is unmodified mp.Add("context_simple", context); ASSERT_TRUE(context.unique()) << "The map altered the context use count"; // We should be able to find this context now: std::shared_ptr<CoreContext> found = mp.Find("context_simple"); ASSERT_TRUE(!!found.get()) << "Failed to find a context that was just inserted into a context map"; } ASSERT_TRUE(ctxtWeak.expired()) << "Context was leaked after it should have gone out of scope"; // We shouldn't be able to find it now that it's gone out of scope: std::shared_ptr<CoreContext> notFound = mp.Find("context_simple"); ASSERT_FALSE(!!notFound.get()) << "Context was not evicted as expected when it went out of scope"; } TEST_F(ContextMapTest, VerifyWithThreads) { AutoCurrentContext()->Initiate(); ContextMap<string> mp; std::shared_ptr<SimpleThreaded> threaded; std::weak_ptr<CoreContext> weakContext; { AutoCreateContext context; // Obtain a weak pointer of our own, and add to the context: weakContext = context; mp.Add("context_withthreads", context); // Add a thread to hold the context open for awhile: threaded = context->Inject<SimpleThreaded>(); // Start the context context->Initiate(); } // Assert that the context still actually exists: ASSERT_TRUE(!weakContext.expired()) << "Simple thread exited before it was signalled to exit"; { // Verify that we can still find the context while the thread is alive: std::shared_ptr<CoreContext> context = mp.Find("context_withthreads"); ASSERT_TRUE(!!context.get()) << "Map evicted a context before expected"; // Relock the weak context, verify that we get back the same pointer: ASSERT_EQ(weakContext.lock(), context) << "Mapped context pointer was not identical to a previously stored context pointer"; // Terminate whole context, wait for it to respond context->SignalShutdown(); context->Wait(); ASSERT_TRUE(autowiring::autotesting::WaitForUseCount(context, 1L, std::chrono::seconds(5))) << "Context reference should have been unique after thread expiration"; } // Release our threaded entity: ASSERT_TRUE(autowiring::autotesting::WaitForUseCount(threaded, 1L, std::chrono::seconds(5))) << "Thread was holding a self-reference even after context termination has completed"; threaded.reset(); ASSERT_TRUE(weakContext.expired()) << "Context still existed even after the last reference to it should have been gone"; { // Verify that the context is gone now that everything in it has stopped running auto ctxt = mp.Find("context_withthreads"); ASSERT_FALSE(ctxt) << "Context was not properly evicted from the map"; // Just return early if the context was empty as we expected, the next part of this test is for diagnostics if(!ctxt) return; // Release the pointer so we aren't guilty of holding a reference to the very thing whose // destruction we are trying to assure. ctxt.reset(); // Sleep for a little bit and run the verification again. If the prior expectation fails, // but this one succeeds, it could be due to race conditions in CoreThread std::this_thread::sleep_for(std::chrono::milliseconds(10)); ctxt = mp.Find("context_withthreads"); ASSERT_FALSE(ctxt) << "Context was not properly evicted even after waiting for a time to ensure eviction"; } } TEST_F(ContextMapTest, ConcurrentDestructionTestPathological) { for(size_t i = 0; i < 100; i++) { // Create our map and a few contexts: ContextMap<string> mp; AutoCreateContext contexts[4]; weak_ptr<SimpleThreaded> threads[4]; // Insert into the map: mp.Add("pathological_destruction0", contexts[0]); mp.Add("pathological_destruction1", contexts[1]); mp.Add("pathological_destruction2", contexts[2]); mp.Add("pathological_destruction3", contexts[3]); // Add a thread and kick off the context: for(size_t i = ARRAYCOUNT(contexts); i--;) { threads[i] = contexts[i]->Inject<SimpleThreaded>(); contexts[i]->Initiate(); } // Immediately tear contexts down: for(size_t i = ARRAYCOUNT(contexts); i--;) contexts[i]->SignalShutdown(); // Wait on anything not signalled: for(size_t i = 0; i < ARRAYCOUNT(threads); i++) { auto cur = threads[i].lock(); if(cur) ASSERT_TRUE(cur->WaitFor(std::chrono::seconds(1))) << "Spawned thread did not exit in a timely fashion"; } } } TEST_F(ContextMapTest, OutOfOrderDeletionTest) { try { AutoCreateContext controlled; ContextMap<size_t> mp; // Add the current context to the map: mp.Add(1, controlled); // Map is destroyed first, then the enclosed context--no exceptions should be thrown } catch(...) { FAIL() << "Exception thrown while attempting an out-of-order teardown"; } } TEST_F(ContextMapTest, VerifyWithThreadsPathological) { ContextMap<size_t> mp; // Context collection and exit race threads: vector<std::shared_ptr<CoreContext>> contexts; // Exit race controller: AutoRequired<ExitRaceSignal> signal; // Create a number of dependent contexts: for(size_t i = 0; i < 100; i++) { AutoCreateContext context; contexts.push_back(context); // Store a shared pointer mp.Add(i, context); // Start the context context->Initiate(); } // Set the signal: signal->Signal(); // Verify that the map empties once our zero-count is hit: for(size_t i = 0; i < contexts.size(); i++) { contexts[i]->SignalShutdown(true); } // Clear the context collection: contexts.clear(); ASSERT_EQ(0UL, mp.size()) << "Context map did not empty as expected"; } TEST_F(ContextMapTest, AdjacentCleanupTest) { ContextMap<string> mp; std::weak_ptr<CoreContext> outerWeak; std::weak_ptr<CoreContext> innerWeak; // Add two contexts, and let one go out of scope AutoCreateContext outer; mp.Add("0", outer); outerWeak = outer; { AutoCreateContext inner; mp.Add("1", inner); innerWeak = inner; // Verify that we can find both contexts std::shared_ptr<CoreContext> outerSearched = mp.Find("0"); ASSERT_TRUE(!!outerSearched.get()) << "Outer context just added, but couldn't be found"; std::shared_ptr<CoreContext> innerSearched = mp.Find("1"); ASSERT_TRUE(!!innerSearched.get()) << "Inner context just added, but couldn't be found"; } // Inner should be 404 by now ASSERT_TRUE(innerWeak.expired()) << "Unexpected outstanding reference to the inner context"; // Try to find the outer context. This should evict the inner context. mp.Find("0"); ASSERT_EQ(1UL, mp.size()) << "Proximity eviction didn't function as expected"; } TEST_F(ContextMapTest, VerifySimpleEnumeration) { ContextMap<string> mp; AutoCreateContext ctxt1; AutoCreateContext ctxt2; AutoCreateContext ctxt3; mp.Add("context_se_1", ctxt1); mp.Add("context_se_2", ctxt2); mp.Add("context_se_3", ctxt3); std::set<std::string> found; size_t count = 0; mp.Enumerate( [&count, &found] (const string& name, std::shared_ptr<CoreContext>& ctxt) -> bool { count++; found.insert(name); return true; } ); ASSERT_EQ(3UL, count) << "Failed to enumerate all expected context pointers"; ASSERT_EQ(1UL, found.count("context_se_1")) << "Failed to find map element '1'"; ASSERT_EQ(1UL, found.count("context_se_2")) << "Failed to find map element '2'"; ASSERT_EQ(1UL, found.count("context_se_3")) << "Failed to find map element '3'"; } TEST_F(ContextMapTest, VerifyRangeBasedEnumeration) { std::shared_ptr<CoreContext> ctxt1 = AutoCreateContext(); std::shared_ptr<CoreContext> ctxt2 = AutoCreateContext(); std::shared_ptr<CoreContext> ctxt3 = AutoCreateContext(); ContextMap<string> mp; mp.Add("a", ctxt1); mp.Add("b", ctxt2); mp.Add("c", ctxt3); size_t ct = 0; // Internal map in ContextMap ensures entries are enumerated in-order for (auto& cur : mp) { (void)cur; switch (ct) { case 0: // Release the entry we are presently enumerating ctxt1.reset(); break; case 1: // No behavior break; case 2: // Release an entry we already enumerated ctxt2.reset(); break; } ct++; } ASSERT_EQ(3UL, ct) << "Context map range-based enumeration did not correctly enumerate all members"; } TEST_F(ContextMapTest, Clear) { std::shared_ptr<CoreContext> ctxt1 = AutoCreateContext(); std::shared_ptr<CoreContext> ctxt2 = AutoCreateContext(); std::shared_ptr<CoreContext> ctxt3 = AutoCreateContext(); ContextMap<string> mp; mp.Add("a", ctxt1); mp.Add("b", ctxt2); mp.Add("c", ctxt3); ASSERT_EQ(3UL, mp.size()) << "Map did not have the correct number of entries after setup"; mp.clear(); ASSERT_EQ(0UL, mp.size()) << "Map clear operation did not clear the map itself as expected"; }
32.762712
181
0.693533
CaseyCarter
9c405057780019e49def40b98a83be8de1c9b05b
275
cpp
C++
quizzes/questions/r.cf.1/code/question.cpp
2016-spring-csuf-benblazak-cpsc-121/course-materials
e448d43f562b8be06ed1d408b677d578a4e54796
[ "CC-BY-4.0" ]
13
2016-01-26T22:07:47.000Z
2021-01-13T06:42:48.000Z
quizzes/questions/r.cf.1/code/question.cpp
2016-spring-csuf-benblazak-cpsc-121/course-materials
e448d43f562b8be06ed1d408b677d578a4e54796
[ "CC-BY-4.0" ]
1
2016-02-10T05:52:31.000Z
2016-02-28T01:08:47.000Z
quizzes/questions/r.cf.1/code/question.cpp
2016-spring-csuf-benblazak-cpsc-121/course-materials
e448d43f562b8be06ed1d408b677d578a4e54796
[ "CC-BY-4.0" ]
32
2016-01-25T23:37:48.000Z
2016-05-17T04:04:30.000Z
#include <iostream> using std::cout; using std::endl; int main() { // SECTION BEGIN all for (int a = 1; a <= 5; a++) { for (int b = 1; b <= a; b++) { cout << a << " "; } cout << endl; } // SECTION END all return 0; }
16.176471
38
0.421818
2016-spring-csuf-benblazak-cpsc-121
9c432db6a08684e4760dbe847137f29c6f396883
666
cpp
C++
base/timestamp.cpp
hxgned/reactor
d6f0596f166a5358a82a98f9b92c1abe368dc85e
[ "MIT" ]
1
2021-08-29T02:50:55.000Z
2021-08-29T02:50:55.000Z
base/timestamp.cpp
hxgned/reactor
d6f0596f166a5358a82a98f9b92c1abe368dc85e
[ "MIT" ]
null
null
null
base/timestamp.cpp
hxgned/reactor
d6f0596f166a5358a82a98f9b92c1abe368dc85e
[ "MIT" ]
1
2021-08-29T02:51:08.000Z
2021-08-29T02:51:08.000Z
#include "base/timestamp.hpp" namespace reactor { std::string fmt_timestamp(time_t t) { t += 8 * 60 * 60; struct tm *p; p = gmtime(&t); char s[80]; strftime(s, 80, "%Y-%m-%d %H:%M:%S", p); std::string st(s); return st; } time_t reverse_fmt_timestamp(const char *tstring) { if (!tstring || tstring[0] == '\0') return 0; struct tm *tmp_time = (struct tm *)malloc(sizeof(struct tm)); strptime(tstring, "%Y-%m-%d %H:%M:%S", tmp_time); time_t t = mktime(tmp_time); free(tmp_time); return t - 16 * 60 * 60; } std::string readable_current_time() { return fmt_timestamp(time(nullptr)); } } // namespace reactor
22.965517
76
0.599099
hxgned
9c45cbf441298542d263ca37f0ca9df6b5503020
15,596
cc
C++
src/scene/object.cc
RichardRanft/Torque6
db6cd08f18f4917e0c6557b2766fb40d8e2bee39
[ "MIT" ]
312
2015-02-17T15:07:28.000Z
2022-03-12T07:09:56.000Z
src/scene/object.cc
lukaspj/Torque6
db6cd08f18f4917e0c6557b2766fb40d8e2bee39
[ "MIT" ]
23
2015-03-30T14:47:37.000Z
2020-11-02T00:00:24.000Z
src/scene/object.cc
lukaspj/Torque6
db6cd08f18f4917e0c6557b2766fb40d8e2bee39
[ "MIT" ]
73
2015-02-17T15:07:30.000Z
2021-10-02T03:11:59.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2015 Andrew Mac // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "object.h" #include "console/consoleInternal.h" #include "components/baseComponent.h" #include "game/moveList.h" #include <bx/fpumath.h> #include "object_Binding.h" namespace Scene { IMPLEMENT_CO_NETOBJECT_V1(SceneObject); SceneObject::SceneObject() : mAddedToScene(false) { mStatic = true; mGhosted = false; mNetFlags.set( Ghostable | ScopeAlways ); mTemplateAssetID = StringTable->EmptyString; mTemplate = NULL; mTransform.set(Point3F(0.0f, 0.0f, 0.0f), VectorF(0.0f, 0.0f, 0.0f), VectorF(1.0f, 1.0f, 1.0f)); } SceneObject::~SceneObject() { clearComponents(); if ( mTemplate != NULL ) mTemplate->deleteObject(); } void SceneObject::initPersistFields() { Parent::initPersistFields(); addGroup("SceneObject"); addProtectedField("Template", TypeAssetId, Offset(mTemplateAssetID, SceneObject), &setTemplateAsset, &defaultProtectedGetFn, "", AbstractClassRep::ObjectTemplateAssetField); addProtectedField("Position", TypePoint3F, 0, &SceneObject::setPositionFn, &SceneObject::getPositionFn, &defaultProtectedWriteFn, "World position of the object."); addProtectedField("Rotation", TypePoint3F, 0, &SceneObject::setRotationFn, &SceneObject::getRotationFn, &defaultProtectedWriteFn, "World rotation of the object."); addProtectedField("Scale", TypePoint3F, 0, &SceneObject::setScaleFn, &SceneObject::getScaleFn, &defaultProtectedWriteFn, "World scale of the object."); addField("Static", TypeBool, Offset(mStatic, SceneObject), ""); endGroup("SceneObject"); addGroup("SceneObject: Networking"); addProtectedField("Ghosted", TypeBool, Offset(mGhosted, SceneObject), &setGhosted, &defaultProtectedGetFn, ""); endGroup("SceneObject: Networking"); } void SceneObject::onAddToScene() { mAddedToScene = true; for (S32 n = 0; n < mComponents.size(); ++n) { mComponents[n]->setOwnerObject(this); mComponents[n]->onAddToScene(); } refresh(); } void SceneObject::onRemoveFromScene() { mAddedToScene = false; for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->onRemoveFromScene(); } void SceneObject::onSceneStart() { for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->onSceneStart(); } void SceneObject::onScenePlay() { for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->onScenePlay(); } void SceneObject::onScenePause() { for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->onScenePause(); } void SceneObject::onSceneStop() { for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->onSceneStop(); } void SceneObject::setGhosted( bool _value ) { if ( _value ) { mGhosted = true; mNetFlags.set( Ghostable | ScopeAlways ); } else { mGhosted = false; mNetFlags.set( Ghostable | ScopeAlways ); } if ( isServerObject() ) setMaskBits(GhostedMask); } void SceneObject::addComponent(BaseComponent* component) { component->setOwnerObject(this); mComponents.push_back(component); if (mAddedToScene) { component->onAddToScene(); if (Scene::isPlaying()) { component->onSceneStart(); component->onScenePlay(); } } } void SceneObject::removeComponent(BaseComponent* component) { for (S32 n = 0; n < mComponents.size(); ++n) { if (mComponents[n] == component) { mComponents.erase(n); component->onRemoveFromScene(); component->unregisterObject(); SAFE_DELETE(component); } } } void SceneObject::clearComponents() { for (S32 n = 0; n < mComponents.size(); ++n) { mComponents[n]->onRemoveFromScene(); mComponents[n]->deleteObject(); } mComponents.clear(); } void SceneObject::setTemplateAsset( StringTableEntry assetID ) { if ( mTemplate != NULL ) return; mTemplateAssetID = StringTable->insert(assetID); AssetPtr<ObjectTemplateAsset> templateAsset; templateAsset.setAssetId(mTemplateAssetID); if ( !templateAsset.isNull() ) { mTemplate = templateAsset->getInstance(); // We keep a vector of BaseComponent pointers for quick access. clearComponents(); for(S32 n = 0; n < mTemplate->size(); ++n) { BaseComponent* component = static_cast<BaseComponent*>(mTemplate->at(n)); addComponent(component); } } if ( isServerObject() ) setMaskBits(TemplateMask); } bool SceneObject::raycast(const Point3F& start, const Point3F& end, Point3F& hitPoint) { for (S32 n = 0; n < mComponents.size(); ++n) { if (mComponents[n]->raycast(start, end, hitPoint)) return true; } return false; } bool SceneObject::boxSearch(const PlaneSetF& planes) { for (S32 n = 0; n < mComponents.size(); ++n) { if (mComponents[n]->boxSearch(planes)) return true; } return false; } void SceneObject::refresh() { // Refresh components for (S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->refresh(); // Calculate bounding box based on component bounding boxes. Box3F newBoundingBox; newBoundingBox.set(Point3F(0, 0, 0)); for (S32 n = 0; n < mComponents.size(); ++n) { if ( n == 0 ) newBoundingBox = mComponents[n]->getBoundingBox(); else newBoundingBox.intersect(mComponents[n]->getBoundingBox()); } mBoundingBox = newBoundingBox; mBoundingBox.transform(mTransform); //if ( isServerObject() ) // setMaskBits(TransformMask); } SimObject* SceneObject::findComponentByType(const char* pType) { for(S32 n = 0; n < mComponents.size(); ++n) { if ( dStrcmp(mComponents[n]->getClassName(), pType) == 0 ) return mComponents[n]; } return NULL; } Vector<SimObject*> SceneObject::findComponentsByType(const char* pType) { Vector<SimObject*> results; for (S32 n = 0; n < mComponents.size(); ++n) { if (dStrcmp(mComponents[n]->getClassName(), pType) == 0) results.push_back(mComponents[n]); } return results; } SimObject* SceneObject::findComponent(StringTableEntry internalName) { for (S32 n = 0; n < mComponents.size(); ++n) { StringTableEntry name = mComponents[n]->getInternalName(); if (name == NULL) continue; if (dStrcmp(name, internalName) == 0) return mComponents[n]; } return NULL; } void SceneObject::writePacketData(GameConnection *conn, BitStream *stream) { // Components for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->writePacketData(conn, stream); } void SceneObject::readPacketData(GameConnection *conn, BitStream *stream) { // Components for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->readPacketData(conn, stream); } U32 SceneObject::packUpdate(NetConnection* conn, U32 mask, BitStream* stream) { // Ghosted Update. if ( stream->writeFlag(GhostedMask && mask) ) stream->writeFlag(mGhosted); // If we're not ghosted we don't send anything else. if ( !mGhosted ) return 0; // Template Update. if ( stream->writeFlag(TemplateMask && mask) ) stream->writeString(mTemplateAssetID); // Transform Update. if ( stream->writeFlag(TransformMask && mask) ) { stream->writeTransform(mTransform); } // Components for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->packUpdate(conn, mask, stream); return 0; } void SceneObject::unpackUpdate(NetConnection* conn, BitStream* stream) { // Ghosted Update. if ( stream->readFlag() ) setGhosted(stream->readFlag()); if ( !mGhosted ) return; // Template Update. if ( stream->readFlag() ) { char strBuf[256]; stream->readString(strBuf); setTemplateAsset(strBuf); } // Transform Update. if ( stream->readFlag() ) { stream->readTransform(&mTransform); refresh(); } // Components for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->unpackUpdate(conn, stream); } void SceneObject::processMove( const Move *move ) { for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->processMove(move); } void SceneObject::interpolateMove( F32 delta ) { for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->interpolateMove(delta); } void SceneObject::advanceMove( F32 dt ) { for(S32 n = 0; n < mComponents.size(); ++n) mComponents[n]->advanceMove(dt); } //----------------------------------------------------------------------------- void SceneObject::onTamlCustomWrite(TamlCustomNodes& customNodes) { // Call parent. Parent::onTamlCustomWrite(customNodes); // Finish early out if no components. const U32 componentCount = (U32)mComponents.size(); if (componentCount == 0) return; // We don't write components if we're a templated entity. if (mTemplate != NULL) return; TamlCustomNode* pComponentNodes = customNodes.addNode("Components"); for (S32 n = 0; n < mComponents.size(); ++n) { Scene::BaseComponent* component = mComponents[n]; TamlCustomNode* pComponentNode = pComponentNodes->addNode(StringTable->insert(component->getClassName()), false); // Static Fields AbstractClassRep::FieldList fieldList = component->getFieldList(); for (Vector<AbstractClassRep::Field>::iterator itr = fieldList.begin(); itr != fieldList.end(); itr++) { const AbstractClassRep::Field* f = itr; if (f->type == AbstractClassRep::StartGroupFieldType || f->type == AbstractClassRep::DepricatedFieldType || f->type == AbstractClassRep::EndGroupFieldType) continue; for (U32 j = 0; S32(j) < f->elementCount; j++) { const char *val = (*f->getDataFn)(component, Con::getData(f->type, (void *)(((const char *)component) + f->offset), j, f->table, f->flag)); if (!val) continue; pComponentNode->addField(StringTable->insert(f->pFieldname), StringTable->insert(val)); } } // Dynamic Fields SimFieldDictionary* fieldDictionary = component->getFieldDictionary(); for (SimFieldDictionaryIterator ditr(fieldDictionary); *ditr; ++ditr) pComponentNode->addField((*ditr)->slotName, (*ditr)->value); } } //----------------------------------------------------------------------------- void SceneObject::onTamlCustomRead(const TamlCustomNodes& customNodes) { // Call parent. Parent::onTamlCustomRead(customNodes); // Find custom node name. const TamlCustomNode* pResultsNode = customNodes.findNode("Components"); // Finish if we don't have a results name. if (pResultsNode == NULL) return; // Fetch children component nodes. const TamlCustomNodeVector& componentNodes = pResultsNode->getChildren(); // Iterate component nodes. for (TamlCustomNodeVector::const_iterator componentNodeItr = componentNodes.begin(); componentNodeItr != componentNodes.end(); ++componentNodeItr) { // Fetch component node. const TamlCustomNode* pComponentNode = *componentNodeItr; StringTableEntry componentType = pComponentNode->getNodeName(); BaseComponent* newComponent = dynamic_cast<BaseComponent*>(Con::createObject(componentType)); if (newComponent) { // Fetch field nodes. const TamlCustomFieldVector& fields = pComponentNode->getFields(); // Iterate fields. for (TamlCustomFieldVector::const_iterator nodeFieldItr = fields.begin(); nodeFieldItr != fields.end(); ++nodeFieldItr) { // Fetch field. TamlCustomField* pField = *nodeFieldItr; // Set Field. newComponent->setDataField(pField->getFieldName(), NULL, pField->getFieldValue()); } // Add Component to Entity newComponent->registerObject(); addComponent(newComponent); } } } bool SceneObject::setPositionFn(void* obj, const char* data) { Point3F position; Con::setData(TypePoint3F, position, 0, 1, &data); static_cast<SceneObject*>(obj)->mTransform.setPosition(position); return false; } const char* SceneObject::getPositionFn(void* obj, const char* data) { return Con::getData(TypePoint3F, static_cast<SceneObject*>(obj)->mTransform.getPosition(), 0); } bool SceneObject::setRotationFn(void* obj, const char* data) { Point3F rotation; Con::setData(TypePoint3F, rotation, 0, 1, &data); static_cast<SceneObject*>(obj)->mTransform.setRotation(rotation); return false; } const char* SceneObject::getRotationFn(void* obj, const char* data) { return Con::getData(TypePoint3F, static_cast<SceneObject*>(obj)->mTransform.getRotationEuler(), 0); } bool SceneObject::setScaleFn(void* obj, const char* data) { Point3F scale; Con::setData(TypePoint3F, scale, 0, 1, &data); static_cast<SceneObject*>(obj)->mTransform.setScale(scale); return false; } const char* SceneObject::getScaleFn(void* obj, const char* data) { return Con::getData(TypePoint3F, static_cast<SceneObject*>(obj)->mTransform.getScale(), 0); } }
30.580392
182
0.599513
RichardRanft
9c48875db5906142a4ce29cf9b45f5d929492de4
2,584
hpp
C++
rclpy/src/rclpy/guard_condition.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
null
null
null
rclpy/src/rclpy/guard_condition.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
null
null
null
rclpy/src/rclpy/guard_condition.hpp
RoboStack/rclpy
c67e43a69a1580eeac4a90767e24ceeea31a298e
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef RCLPY__GUARD_CONDITION_HPP_ #define RCLPY__GUARD_CONDITION_HPP_ #include <pybind11/pybind11.h> #include <rcl/error_handling.h> #include <rcl/guard_condition.h> #include <memory> #include "rclpy_common/handle.h" #include "context.hpp" #include "destroyable.hpp" #include "exceptions.hpp" #include "utils.hpp" namespace py = pybind11; namespace rclpy { /// Create a general purpose guard condition class GuardCondition : public Destroyable, public std::enable_shared_from_this<GuardCondition> { public: /** * Raises RuntimeError if initializing the guard condition fails */ explicit GuardCondition(Context & context); /// Trigger a general purpose guard condition /** * Raises ValueError if pygc is not a guard condition capsule * Raises RCLError if the guard condition could not be triggered */ void trigger_guard_condition(); /// Get rcl_guard_condition_t pointer rcl_guard_condition_t * rcl_ptr() const { return rcl_guard_condition_.get(); } // TODO(ahcorde): Remove the pycapsule method when #728 is in /// Return a pycapsule object to be able to handle the signal in C. py::capsule pycapsule() const { PyObject * capsule = rclpy_create_handle_capsule( rcl_guard_condition_.get(), "rcl_guard_condition_t", _rclpy_destroy_guard_condition); if (!capsule) { throw py::error_already_set(); } return py::reinterpret_steal<py::capsule>(capsule); } /// Force an early destruction of this object void destroy() override; private: Context context_; std::shared_ptr<rcl_guard_condition_t> rcl_guard_condition_; /// Handle destructor for guard condition static void _rclpy_destroy_guard_condition(void * p) { (void)p; // Empty destructor, the class should take care of the lifecycle. } }; /// Define a pybind11 wrapper for an rclpy::Service void define_guard_condition(py::object module); } // namespace rclpy #endif // RCLPY__GUARD_CONDITION_HPP_
27.784946
94
0.740712
RoboStack
9c49c64dc561ac6bb5d6d6f4f313105699edbc9e
321
cpp
C++
test/atcoder/atc001-c.cpp
sash2104/library
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
[ "Unlicense" ]
null
null
null
test/atcoder/atc001-c.cpp
sash2104/library
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
[ "Unlicense" ]
10
2020-01-27T15:57:45.000Z
2021-12-20T03:26:26.000Z
test/atcoder/atc001-c.cpp
sash2104/library
ecb52543e4f8a66300ffd8794ea9c13bc74bdb19
[ "Unlicense" ]
null
null
null
#include <vector> #include "../../external/fft.hpp" using namespace std; int main() { int n; cin >> n; vector<double> a(n+1), b(n+1); for (int i = 0; i < n; ++i) { cin >> a[i+1] >> b[i+1]; } vector<double> c = convolve(a, b); for (int i = 1; i <= 2*n; ++i) { cout << (int)(c[i]+0.5) << endl; } }
18.882353
36
0.479751
sash2104
9c4cdaee81963357e0ad062d02143d067d5d8bd3
17,254
cpp
C++
Engine/Graphics/Direct3D12/D3D12Core.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/Direct3D12/D3D12Core.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
Engine/Graphics/Direct3D12/D3D12Core.cpp
ZackShrout/HavanaEngine
b8869acfff27e41bd37079716d152c2df9674fe2
[ "Apache-2.0" ]
null
null
null
#include "D3D12Core.h" #include "D3D12Surface.h" #include "D3D12Shaders.h" #include "D3D12GPass.h" #include "D3D12PostProcess.h" using namespace Microsoft::WRL; namespace Havana::Graphics::D3D12::Core { namespace { class D3D12Command { public: D3D12Command() = default; DISABLE_COPY_AND_MOVE(D3D12Command) explicit D3D12Command(id3d12Device* const device, D3D12_COMMAND_LIST_TYPE type) { HRESULT hr{ S_OK }; D3D12_COMMAND_QUEUE_DESC description{}; description.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE; description.NodeMask = 0; description.Priority = D3D12_COMMAND_QUEUE_PRIORITY_NORMAL; description.Type = type; // Command Queue DXCall(hr = device->CreateCommandQueue(&description, IID_PPV_ARGS(&m_commandQueue))); if (FAILED(hr)) { Release(); return; } NAME_D3D12_OBJECT(m_commandQueue, type == D3D12_COMMAND_LIST_TYPE_DIRECT ? L"Graphics Command Queue" : type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? L"Compute Command Queue" : L"Command Queue"); // Command allocators for (u32 i{ 0 }; i < frameBufferCount; i++) { CommandFrame& frame{ m_commandFrames[i] }; DXCall(hr = device->CreateCommandAllocator(type, IID_PPV_ARGS(&frame.commandAllocator))); if (FAILED(hr)) { Release(); return; } NAME_D3D12_OBJECT_INDEXED(frame.commandAllocator, i, type == D3D12_COMMAND_LIST_TYPE_DIRECT ? L"GFX Command Allocator" : type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? L"Compute Command Allocator" : L"Command Allocator"); } // Command list DXCall(hr = device->CreateCommandList(0, type, m_commandFrames[0].commandAllocator , nullptr, IID_PPV_ARGS(&m_commandList))); if (FAILED(hr)) { Release(); return; } DXCall(m_commandList->Close()); NAME_D3D12_OBJECT(m_commandList, type == D3D12_COMMAND_LIST_TYPE_DIRECT ? L"Graphics Command List" : type == D3D12_COMMAND_LIST_TYPE_COMPUTE ? L"Compute Command List" : L"Command List"); // Fence DXCall(hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&m_fence))); if (FAILED(hr)) { Release(); return; } NAME_D3D12_OBJECT(m_fence, L"D3D12 Fence"); m_fenceEvent = CreateEventEx(nullptr, nullptr, 0, EVENT_ALL_ACCESS); assert(m_fenceEvent); } ~D3D12Command() { assert(!m_commandQueue && !m_commandList && !m_fence); } // Wait for the current frame to be signaled and reset the command list/allocator void BeginFrame() { CommandFrame& frame{ m_commandFrames[m_frameIndex] }; frame.Wait(m_fenceEvent, m_fence); DXCall(frame.commandAllocator->Reset()); DXCall(m_commandList->Reset(frame.commandAllocator, nullptr)); } // Singal the fence with the new fence value void EndFrame(const D3D12Surface& surface) { DXCall(m_commandList->Close()); ID3D12CommandList* const commandLists[]{ m_commandList }; m_commandQueue->ExecuteCommandLists(_countof(commandLists), &commandLists[0]); // Presenting swap chain buffers happens in lockstep with frame buffers. surface.Present(); u64& fenceValue{ m_fenceValue }; fenceValue++; CommandFrame& frame{ m_commandFrames[m_frameIndex] }; frame.fenceValue = fenceValue; m_commandQueue->Signal(m_fence, fenceValue); m_frameIndex = (m_frameIndex + 1) % frameBufferCount; } // Complete all work on GPU for all frames void Flush() { for (u32 i{ 0 }; i < frameBufferCount; i++) { m_commandFrames[i].Wait(m_fenceEvent, m_fence); } m_frameIndex = 0; } void Release() { Flush(); Core::Release(m_fence); m_fenceValue = 0; CloseHandle(m_fenceEvent); m_fenceEvent = nullptr; Core::Release(m_commandQueue); Core::Release(m_commandList); for (u32 i{ 0 }; i < frameBufferCount; i++) { m_commandFrames[i].Release(); } } [[nodiscard]] constexpr ID3D12CommandQueue* const CommandQueue() const { return m_commandQueue; } [[nodiscard]] constexpr id3d12GraphicsCommandList* const CommandList() const { return m_commandList; } [[nodiscard]] constexpr u32 FrameIndex() const { return m_frameIndex; } private: struct CommandFrame { ID3D12CommandAllocator* commandAllocator{ nullptr }; u64 fenceValue{ 0 }; void Wait(HANDLE fenceEvent, ID3D12Fence1* fence) { assert(fence && fenceEvent); // If the current fence value is still less than "fenceValue" // then we know the GPU hasn't finished executing the command list // since it has not reached the commandQueue->Signel() command. if (fence->GetCompletedValue() < fenceValue) { // We have the fence create an event which is signaled once the fence's current value equals "fenceValue" DXCall(fence->SetEventOnCompletion(fenceValue, fenceEvent)); // Wait until the fence creates the above event, signaling that the command queue has finished executing WaitForSingleObject(fenceEvent, INFINITE); } } void Release() { Core::Release(commandAllocator); fenceValue = 0; } }; ID3D12CommandQueue* m_commandQueue{ nullptr }; id3d12GraphicsCommandList* m_commandList{ nullptr }; ID3D12Fence1* m_fence{ nullptr }; HANDLE m_fenceEvent{ nullptr }; u64 m_fenceValue{ 0 }; CommandFrame m_commandFrames[frameBufferCount]{}; u32 m_frameIndex{ 0 }; }; using surface_collection = Utils::free_list<D3D12Surface>; id3d12Device* mainDevice{ nullptr }; IDXGIFactory7* dxgiFactory{ nullptr }; D3D12Command gfxCommand; surface_collection surfaces; D3DX::ResourceBarrier resourceBarriers{}; DescriptorHeap rtvDescHeap{ D3D12_DESCRIPTOR_HEAP_TYPE_RTV }; DescriptorHeap dsvDescHeap{ D3D12_DESCRIPTOR_HEAP_TYPE_DSV }; DescriptorHeap srvDescHeap{ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV }; DescriptorHeap uavDescHeap{ D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV }; Utils::vector<IUnknown*> deferredReleases[frameBufferCount]{}; u32 deferredReleasesFlag[frameBufferCount]{}; std::mutex deferredReleasesMutex{}; constexpr D3D_FEATURE_LEVEL minimumFeatureLevel{ D3D_FEATURE_LEVEL_11_0 }; bool FailedInit() { Shutdown(); return false; } // Get the first most performing adapter that supports the minimum feature level. // NOTE: this function can be expanded in functionality with, for example, checking if any // output devices (i.e. screens) are attached, enumerate the supported resolutions, provide // a means for the user to choose which adapter to use in a multi-adapter setting, etc. IDXGIAdapter4* DetermineMainAdapter() { IDXGIAdapter4* adapter{ nullptr }; // Get adapters in decending order of performance for (u32 i{ 0 }; dxgiFactory->EnumAdapterByGpuPreference(i, DXGI_GPU_PREFERENCE_HIGH_PERFORMANCE, IID_PPV_ARGS(&adapter)) != DXGI_ERROR_NOT_FOUND; i++) { // Pick the first adapter that supports the minimum feature level if (SUCCEEDED(D3D12CreateDevice(adapter, minimumFeatureLevel, __uuidof(ID3D12Device), nullptr))) { return adapter; } Release(adapter); } return nullptr; } /// <summary> /// Get the maximum supported feature level of the given adapter /// </summary> /// <param name="adapter"> - Adapter to check feature levels of.</param> /// <returns>D3D_FEATURE_LEVEL containing max feature level.</returns> D3D_FEATURE_LEVEL GetMaxFeatureLevel(IDXGIAdapter4* adapter) { constexpr D3D_FEATURE_LEVEL featureLevels[4] { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_12_0, D3D_FEATURE_LEVEL_12_1 }; D3D12_FEATURE_DATA_FEATURE_LEVELS featureLevelInfo{}; featureLevelInfo.NumFeatureLevels = _countof(featureLevels); featureLevelInfo.pFeatureLevelsRequested = featureLevels; ComPtr<ID3D12Device> device; DXCall(D3D12CreateDevice(adapter, minimumFeatureLevel, IID_PPV_ARGS(&device))); DXCall(device->CheckFeatureSupport(D3D12_FEATURE_FEATURE_LEVELS, &featureLevelInfo, sizeof(featureLevelInfo))); return featureLevelInfo.MaxSupportedFeatureLevel; } // This wont be called often so we shouldn't have this inlined void __declspec(noinline) ProcessDeferredReleases(u32 frameIdx) { std::lock_guard lock{ deferredReleasesMutex }; // This flag is cleared at the beginning becuase otherwise it might // overwrite some other thread that was trying to set it. Its ok if // the overwrite happens before processing the items. deferredReleasesFlag[frameIdx] = 0; rtvDescHeap.ProcessDeferredFree(frameIdx); dsvDescHeap.ProcessDeferredFree(frameIdx); srvDescHeap.ProcessDeferredFree(frameIdx); uavDescHeap.ProcessDeferredFree(frameIdx); Utils::vector<IUnknown*>& resources{ deferredReleases[frameIdx] }; if (!resources.empty()) { for (auto& resource : resources) Release(resource); resources.clear(); } } } // anonymous namespace namespace Detail { void DeferredRelease(IUnknown* resource) { const u32 frameIdx{ CurrentFrameIndex() }; std::lock_guard lock{ deferredReleasesMutex }; deferredReleases[frameIdx].push_back(resource); SetDeferredReleasesFlag(); } } // Detail namespace bool Initialize() { if (mainDevice) Shutdown(); u32 dxgiFactoryFlags{ 0 }; #ifdef _DEBUG // Enable debugging layer. Requires "Graphics Tools" optional feature { ComPtr<ID3D12Debug3> debugInterface; if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugInterface)))) { debugInterface->EnableDebugLayer(); #if 0 #pragma message("WARNING: GPU based validation is enabled. This will considerably slow down the renderer!") debugInterface->SetEnableGPUBasedValidation(1); #endif } else { OutputDebugStringA("Warning: D3D12 debug interface is not available. Verify that the Graphics Tools optional feature is installed in this device.\n"); } dxgiFactoryFlags |= DXGI_CREATE_FACTORY_DEBUG; } #endif // _DEBUG HRESULT hr{ S_OK }; DXCall(hr = CreateDXGIFactory2(dxgiFactoryFlags, IID_PPV_ARGS(&dxgiFactory))); if (FAILED(hr)) return FailedInit(); // Determine which adapter (i.e. graphics card) to use, if any ComPtr<IDXGIAdapter4> mainAdapter; mainAdapter.Attach(DetermineMainAdapter()); if (!mainAdapter) return FailedInit(); // Determine what the max feature level supported is D3D_FEATURE_LEVEL maxFeatureLevel{ GetMaxFeatureLevel(mainAdapter.Get()) }; assert(maxFeatureLevel >= minimumFeatureLevel); if (maxFeatureLevel < minimumFeatureLevel) return FailedInit(); // Create an ID3D12Device (virtual adapter) DXCall(hr = D3D12CreateDevice(mainAdapter.Get(), maxFeatureLevel, IID_PPV_ARGS(&mainDevice))); if (FAILED(hr)) return FailedInit(); #ifdef _DEBUG { ComPtr<ID3D12InfoQueue> infoQueue; DXCall(mainDevice->QueryInterface(IID_PPV_ARGS(&infoQueue))); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, true); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, true); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, true); } #endif // _DEBUG // Initialize Descriptor Heaps bool result{ true }; result &= rtvDescHeap.Initialize(512, false); result &= dsvDescHeap.Initialize(512, false); result &= srvDescHeap.Initialize(4896, true); result &= uavDescHeap.Initialize(512, false); if (!result) return FailedInit(); // There is nothing in D3D12Command that would cause a memory leak by calling // new here, but care must be taken. new (&gfxCommand) D3D12Command(mainDevice, D3D12_COMMAND_LIST_TYPE_DIRECT); if (!gfxCommand.CommandQueue()) return FailedInit(); // Initialize modules if (!(Shaders::Initialize() && GPass::Initialize() && FX::Initialize())) return FailedInit(); NAME_D3D12_OBJECT(mainDevice, L"Main D3D Device"); NAME_D3D12_OBJECT(rtvDescHeap.Heap(), L"RTV Descriptor Heap"); NAME_D3D12_OBJECT(dsvDescHeap.Heap(), L"DSV Descriptor Heap"); NAME_D3D12_OBJECT(srvDescHeap.Heap(), L"SRV Descriptor Heap"); NAME_D3D12_OBJECT(uavDescHeap.Heap(), L"USV Descriptor Heap"); return true; } void Shutdown() { gfxCommand.Release(); // This is not called at the end because some resources // (like swap chains) can't be released before their // depending resources are released. for (u32 i{ 0 }; i < frameBufferCount; i++) { ProcessDeferredReleases(i); } // Shutdown modules FX::Shutdown(); GPass::Shutdown(); Shaders::Shutdown(); Release(dxgiFactory); // NOTE: Some modules free their descriptors when they shutdown. // We process those by calling ProcessDeferredFree once more. rtvDescHeap.ProcessDeferredFree(0); dsvDescHeap.ProcessDeferredFree(0); srvDescHeap.ProcessDeferredFree(0); uavDescHeap.ProcessDeferredFree(0); rtvDescHeap.Release(); dsvDescHeap.Release(); srvDescHeap.Release(); uavDescHeap.Release(); // Some types only use deferred releases for their resources // during shutdown/reset/clear. To release these resources, // this function is called one last time. ProcessDeferredReleases(0); #ifdef _DEBUG { { ComPtr<ID3D12InfoQueue> infoQueue; DXCall(mainDevice->QueryInterface(IID_PPV_ARGS(&infoQueue))); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_CORRUPTION, false); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_WARNING, false); infoQueue->SetBreakOnSeverity(D3D12_MESSAGE_SEVERITY_ERROR, false); } ComPtr<ID3D12DebugDevice2> debugDevice; DXCall(mainDevice->QueryInterface(IID_PPV_ARGS(&debugDevice))); Release(mainDevice); DXCall(debugDevice->ReportLiveDeviceObjects ( D3D12_RLDO_SUMMARY | D3D12_RLDO_DETAIL | D3D12_RLDO_IGNORE_INTERNAL )); } #endif // _DEBUG Release(mainDevice); } id3d12Device* const Device() { return mainDevice; } DescriptorHeap& RTVHeap() { return rtvDescHeap; } DescriptorHeap& DSVHeap() { return dsvDescHeap; } DescriptorHeap& SRVHeap() { return srvDescHeap; } DescriptorHeap& UAVHeap() { return uavDescHeap; } u32 CurrentFrameIndex() { return gfxCommand.FrameIndex(); } void SetDeferredReleasesFlag() { deferredReleasesFlag[CurrentFrameIndex()] = 1; } Surface CreateSurface(Platform::Window window) { surface_id id{ surfaces.add(window) }; surfaces[id].CreateSwapChain(dxgiFactory, gfxCommand.CommandQueue()); return Surface{ id }; } void RemoveSurface(surface_id id) { gfxCommand.Flush(); surfaces.remove(id); } void ResizeSurface(surface_id id, u32, u32) { gfxCommand.Flush(); surfaces[id].Resize(); } u32 SurfaceWidth(surface_id id) { return surfaces[id].Width(); } u32 SurfaceHeight(surface_id id) { return surfaces[id].Height(); } void RenderSurface(surface_id id) { // Wait for the GPU to finish with the command allocator and // reset the allocator once the GPU is done with it. // This frees the memory that was used to store commands. gfxCommand.BeginFrame(); id3d12GraphicsCommandList* cmdList{ gfxCommand.CommandList() }; // Check to see if there are deferred releases to handle const u32 frameIdx{ CurrentFrameIndex() }; if (deferredReleasesFlag[frameIdx]) { (ProcessDeferredReleases(frameIdx)); } const D3D12Surface& surface{ surfaces[id] }; ID3D12Resource* const currentBackBuffer{ surface.BackBuffer() }; D3D12FrameInfo frameInfo { surface.Width(), surface.Height() }; GPass::SetSize({ frameInfo.surfaceWidth, frameInfo.surfaceHeight }); D3DX::ResourceBarrier& barriers{ resourceBarriers }; // Record commands ID3D12DescriptorHeap* const heaps[]{ srvDescHeap.Heap() }; cmdList->SetDescriptorHeaps(1, &heaps[0]); cmdList->RSSetViewports(1, &surface.Viewport()); cmdList->RSSetScissorRects(1, &surface.ScissorRect()); // Depth Prepass barriers.Add(currentBackBuffer, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_BARRIER_FLAG_BEGIN_ONLY); GPass::AddTransitionsForDepthPrepass(barriers); barriers.Apply(cmdList); GPass::SetRenderTargetsForDepthPrepass(cmdList); GPass::DepthPrepass(cmdList, frameInfo); // Geometry and Lighting Pass GPass::AddTransitionsForGPass(barriers); barriers.Apply(cmdList); GPass::SetRenderTargetsForGPass(cmdList); GPass::Render(cmdList, frameInfo); // Post-process barriers.Add(currentBackBuffer, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_BARRIER_FLAG_END_ONLY); GPass::AddTransitionsForPostProcess(barriers); barriers.Apply(cmdList); // -- Will write final image to the current back buffer, so the back buffer is a render target FX::PostProcess(cmdList, surface.RTV()); // After post-process D3DX::TransitionResource(cmdList, currentBackBuffer, D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT); // Presenting swap chain buffers happens in lockstep with frame buffers. //surface.Present(); // Done recording commands, now execute them, // signal and incriment fence value for next frame. gfxCommand.EndFrame(surface); } }
31.032374
154
0.720065
ZackShrout
9c4ce9d38e67f747ad745f068b9c666f1982d440
12,460
cpp
C++
source/rendering/simple_bitmap_font.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
1
2021-08-02T04:49:44.000Z
2021-08-02T04:49:44.000Z
source/rendering/simple_bitmap_font.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
null
null
null
source/rendering/simple_bitmap_font.cpp
xeek-pro/isometric
6f7d05ce597683552d5dc3078a1634fddd41092b
[ "MIT" ]
1
2021-09-09T16:49:53.000Z
2021-09-09T16:49:53.000Z
#include "simple_bitmap_font.h" #include <SDL_ttf.h> #include <vector> #include <tuple> using namespace isometric::rendering; static void generate_glyph_surfaces(TTF_Font* font, const std::vector<char>& glyphs, bitmap_font_info& font_info); static void generate_glyph_srcrects(bitmap_font_info& font_info); static void generate_glyph_textures(SDL_Renderer* renderer, bitmap_font_info& font_info, bool free_glyph_surfaces = true); simple_bitmap_font::simple_bitmap_font(SDL_Renderer* renderer, TTF_Font* font, unsigned char start_glyph, unsigned char end_glyph) : renderer(renderer), sdl_font(font) { size_t num_glyphs = (static_cast<size_t>(end_glyph) - start_glyph) + 1; // end_glyph is inclusive so + 1 std::vector<char> glyphs(num_glyphs); unsigned char current_glyph = start_glyph; for (size_t i = 0; i < num_glyphs; current_glyph++, i++) { glyphs[i] = static_cast<char>(current_glyph); } create(glyphs); } simple_bitmap_font::simple_bitmap_font(SDL_Renderer* renderer, TTF_Font* font, const char* glyphs, size_t glyphs_size) : simple_bitmap_font(renderer, font, std::vector<char>(glyphs, glyphs + glyphs_size)) { } simple_bitmap_font::simple_bitmap_font(SDL_Renderer* renderer, TTF_Font* font, const std::vector<char>& glyphs) : renderer(renderer), sdl_font(font) { create(glyphs); } simple_bitmap_font::~simple_bitmap_font() { destroy(); } uint32_t simple_bitmap_font::set_color(uint32_t color) { auto pixel_format = SDL_AllocFormat(SDL_PIXELFORMAT_RGBA8888); SDL_Color new_color{}; SDL_GetRGBA( color, pixel_format, &new_color.r, &new_color.g, &new_color.b, &new_color.a ); uint32_t old_color = get_color_as_hex(); set_color(new_color); SDL_FreeFormat(pixel_format); return old_color; } SDL_Color simple_bitmap_font::set_color(const SDL_Color& color) { SDL_Color old_color = current_color; current_color = color; return old_color; } const uint32_t simple_bitmap_font::get_color_as_hex() const { SDL_Color color = get_color(); return color.a + (color.b << 8) + (color.g << 16) + (color.r << 24); } const SDL_Color& simple_bitmap_font::get_color() const { return current_color; } void simple_bitmap_font::draw( const std::string& text, const SDL_Point& point, content_align align ) const { SDL_Rect dstrect = { point.x, point.y, 0, 0 }; if (align != content_align::top_left) { auto measured_rect = measure(text, SDL_Point{ dstrect.x, dstrect.y }); // The alignment has to be handled here since it works differntly than when using the dstrect version of this // function. // Horizontal Alignment: switch (align) { case content_align::top_center: case content_align::middle_center: case content_align::bottom_center: dstrect.x -= static_cast<int>(std::round(measured_rect.w / 2.0)); break; case content_align::top_right: case content_align::middle_right: case content_align::bottom_right: dstrect.x -= measured_rect.w; break; } // Vertical Alignment: switch (align) { case content_align::middle_left: case content_align::middle_center: case content_align::middle_right: dstrect.y -= static_cast<int>(std::round(measured_rect.h / 2.0)); break; case content_align::bottom_left: case content_align::bottom_center: case content_align::bottom_right: dstrect.y -= measured_rect.h; break; } } draw(text, dstrect, content_align::top_left, true); } void simple_bitmap_font::draw( const std::string& text, const SDL_Rect& dstrect, content_align align, bool no_clip ) const { for (const auto& texture_info : font_info.textures) { SDL_Texture* texture = std::get<0>(texture_info); SDL_SetTextureColorMod(texture, current_color.r, current_color.g, current_color.b); SDL_SetTextureAlphaMod(texture, current_color.a); } // To keep up with the current glyph drawing position: SDL_Rect glyph_dstrect{ dstrect.x, dstrect.y }; if (align != content_align::top_left) { auto measured_rect = measure(text, SDL_Point{ dstrect.x, dstrect.y }); // Horizontal Alignment: switch (align) { case content_align::top_center: case content_align::middle_center: case content_align::bottom_center: glyph_dstrect.x += static_cast<int>(std::round(dstrect.w / 2.0 - measured_rect.w / 2.0)); break; case content_align::top_right: case content_align::middle_right: case content_align::bottom_right: glyph_dstrect.x += dstrect.w - measured_rect.w; break; } // Vertical Alignment: switch (align) { case content_align::middle_left: case content_align::middle_center: case content_align::middle_right: glyph_dstrect.y += static_cast<int>(std::round(dstrect.h / 2.0 - measured_rect.h / 2.0)); break; case content_align::bottom_left: case content_align::bottom_center: case content_align::bottom_right: glyph_dstrect.y += dstrect.h - measured_rect.h; break; } } // Text rendering: for (char character : text) { if (!font_info.glyphs.contains(character)) continue; const auto& info = font_info.glyphs.at(character); glyph_dstrect = { glyph_dstrect.x, glyph_dstrect.y, info.srcrect.w, info.srcrect.h }; if (!no_clip && !SDL_HasIntersection(&glyph_dstrect, &dstrect)) { break; } if (info.texture_index < font_info.textures.size()) { SDL_Texture* texture = std::get<0>(font_info.textures[info.texture_index]); if (texture) { SDL_RenderCopy(renderer, texture, &info.srcrect, &glyph_dstrect); } } glyph_dstrect.x += info.srcrect.w; } } SDL_Rect simple_bitmap_font::measure( const std::string& text, const SDL_Point& point ) const { int width = 0, height = 0; for (char character : text) { if (font_info.glyphs.contains(character)) { const auto& info = font_info.glyphs.at(character); width += info.srcrect.w; if (info.srcrect.h > height) { height = info.srcrect.h; } } } return SDL_Rect{ point.x, point.y, width, height }; } void simple_bitmap_font::create(const std::vector<char>& glyphs) { generate_glyph_surfaces(sdl_font, glyphs, font_info); generate_glyph_srcrects(font_info); generate_glyph_textures(renderer, font_info, true); } void simple_bitmap_font::destroy() { for (auto& texture_info : font_info.textures) { auto& texture = std::get<0>(texture_info); if (texture) { SDL_DestroyTexture(texture); texture = nullptr; } } font_info.textures.clear(); font_info.glyphs.clear(); if (destroy_font && this->sdl_font) { TTF_CloseFont(this->sdl_font); this->sdl_font = nullptr; } } static void generate_glyph_surfaces( TTF_Font* font, const std::vector<char>& glyphs, bitmap_font_info& font_info ) { if (!font || glyphs.empty()) return; font_info.glyphs.clear(); for (char character : glyphs) { SDL_Surface* surface = TTF_RenderGlyph_Blended(font, character, SDL_Color{ 255, 255, 255, 255 }); if (surface) { font_info.glyphs[character] = glyph_info{ surface, SDL_Rect{ 0, 0, surface->w, surface->h }, 0 }; } } } static void generate_glyph_srcrects( bitmap_font_info& font_info ) { if (!font_info.textures.empty() || font_info.glyphs.empty()) return; constexpr int max_texture_width = 2048, max_texture_height = 2048; int texture_width = 0, texture_height = 0; size_t texture_index = 0; int x = 0, y = 0, row_height = 0; for (auto& pair : font_info.glyphs) { char character = pair.first; glyph_info& glyph = pair.second; // The current row's height should be the tallest glyph: if (glyph.surface->h > row_height) row_height = glyph.surface->h; // If the farthest x-extent has been reached, start a new row: if (x + glyph.surface->w >= max_texture_width) { x = 0; y += row_height; row_height = glyph.surface->h; } // If the farthest y-extent has been reached, configure the texture's dimensions and move onto the next // texture: if (y + glyph.surface->h >= max_texture_height) { font_info.textures.push_back( std::make_tuple<SDL_Texture*, SDL_Rect>( nullptr, SDL_Rect{ 0, 0, texture_width, texture_height } ) ); texture_index++; texture_width = texture_height = x = y = 0; } // Set the glyph's source rectangle: glyph.srcrect = SDL_Rect{ x, y, glyph.surface->w, glyph.surface->h }; glyph.texture_index = texture_index; // Increment the x coord: x += glyph.surface->w; // Use the greatest x or y to update the texture_width and texture_height: if (x > texture_width) texture_width = x; // Not adding the glyph width since it was done above if (y + row_height > texture_height) texture_height = y + row_height; } // The last texture's dimension needs to be setup after the loop: if (texture_width > 0 && texture_height > 0) { font_info.textures.push_back( std::make_tuple<SDL_Texture*, SDL_Rect>( nullptr, SDL_Rect{ 0, 0, texture_width, texture_height } ) ); } } static void generate_glyph_textures( SDL_Renderer* renderer, bitmap_font_info& font_info, bool free_glyph_surfaces ) { std::vector<SDL_Surface*> atlas_surfaces; for (auto& texture_info : font_info.textures) { const SDL_Rect& dimensions = std::get<1>(texture_info); SDL_Surface* atlas_surface = SDL_CreateRGBSurface(0, dimensions.w, dimensions.h, 32, #if SDL_BYTEORDER == SDL_BIG_ENDIAN 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff #else 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000 #endif ); atlas_surfaces.push_back(atlas_surface); } for (auto& pair : font_info.glyphs) { char character = pair.first; glyph_info& glyph = pair.second; const size_t texture_index = glyph.texture_index; // This is the dstrect in this context, since the destination // surface will be the source in the future SDL_Rect dstrect = glyph.srcrect; SDL_Rect srcrect = SDL_Rect{ 0, 0, dstrect.w, dstrect.h }; SDL_Surface* dst = atlas_surfaces[texture_index]; if (dst && glyph.surface) { // Disable blending for the glyph surface because if blending is enabled, black will bleed through the // anti-aliasing even though it's 0,0,0,0 SDL_SetSurfaceBlendMode(glyph.surface, SDL_BLENDMODE_NONE); SDL_BlitSurface(glyph.surface, &srcrect, dst, &dstrect); if (free_glyph_surfaces) { SDL_FreeSurface(glyph.surface); glyph.surface = nullptr; } } } for (size_t texture_index = 0; texture_index < font_info.textures.size(); texture_index++) { auto& texture = std::get<0>(font_info.textures[texture_index]); auto& surface = atlas_surfaces[texture_index]; if (surface) { texture = SDL_CreateTextureFromSurface(renderer, surface); // For testing, output the glyph atlas as an image file. Don't forget to #include <SDL_image.h> // IMG_SavePNG(surface, std::format("./simple_font.{}.png", texture_index).c_str()); SDL_FreeSurface(surface); surface = nullptr; } } }
29.808612
130
0.620305
xeek-pro
9c4ec648c2fe579b50c28a09ec4744a0eaa441df
1,748
hpp
C++
include/boost/simd/arch/common/generic/function/acotd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/common/generic/function/acotd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
include/boost/simd/arch/common/generic/function/acotd.hpp
yaeldarmon/boost.simd
561316cc54bdc6353ca78f3b6d7e9120acd11144
[ "BSL-1.0" ]
null
null
null
//================================================================================================== /*! @file @copyright 2015 NumScale SAS @copyright 2015 J.T. Lapreste Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ //================================================================================================== #ifndef BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_ACOTD_HPP_INCLUDED #define BOOST_SIMD_ARCH_COMMON_FUNCTION_GENERIC_ACOTD_HPP_INCLUDED #ifndef BOOST_SIMD_NO_INFINITIES #include <boost/simd/function/simd/is_inf.hpp> #endif #include <boost/simd/constant/ratio.hpp> #include <boost/simd/function/abs.hpp> #include <boost/simd/function/atand.hpp> #include <boost/simd/function/bitofsign.hpp> #include <boost/simd/function/bitwise_or.hpp> #include <boost/simd/function/if_else_zero.hpp> #include <boost/simd/function/if_zero_else.hpp> #include <boost/simd/function/is_nez.hpp> #include <boost/simd/function/minus.hpp> #include <boost/dispatch/function/overload.hpp> #include <boost/config.hpp> namespace boost { namespace simd { namespace ext { namespace bd = boost::dispatch; namespace bs = boost::simd; BOOST_DISPATCH_OVERLOAD ( acotd_ , (typename A0) , bd::cpu_ , bd::generic_<bd::floating_<A0> > ) { BOOST_FORCEINLINE A0 operator() ( A0 const& a0) const BOOST_NOEXCEPT { A0 z = Ratio<A0, 90>()-if_else_zero(is_nez(a0),atand(bs::abs(a0))); #ifndef BOOST_SIMD_NO_INFINITIES z = if_zero_else(is_inf(a0),z); #endif return bitwise_or(z, bitofsign(a0)); } }; } } } #endif
32.981132
100
0.6127
yaeldarmon
9c4f1bff0639e13a8c6617b6fd5539af1a5a94f4
7,409
cpp
C++
code/engine.vc2008/xrGame/ai/monsters/chimera/chimera.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
7
2018-03-27T12:36:07.000Z
2020-06-26T11:31:52.000Z
code/engine.vc2008/xrGame/ai/monsters/chimera/chimera.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
2
2018-05-26T23:17:14.000Z
2019-04-14T18:33:27.000Z
code/engine.vc2008/xrGame/ai/monsters/chimera/chimera.cpp
Rikoshet-234/xray-oxygen
eaac3fa4780639152684f3251b8b4452abb8e439
[ "Apache-2.0" ]
5
2020-10-18T11:55:26.000Z
2022-03-28T07:21:35.000Z
#include "stdafx.h" #include "chimera.h" #include "chimera_state_manager.h" //#include "../../../../Include/xrRender/KinematicsAnimated.h" #include "../../../detail_path_manager.h" #include "../monster_velocity_space.h" #include "../../../level.h" //#include "../../../PhysicsShell.h" #include "../../../sound_player.h" #include "../control_animation_base.h" #include "../control_movement_base.h" #include "../control_path_builder_base.h" CChimera::CChimera () { StateMan = xr_new<CStateManagerChimera> (this); com_man().add_ability (ControlCom::eControlJump); } CChimera::~CChimera () { xr_delete (StateMan); } void CChimera::Load (LPCSTR section) { inherited::Load (section); anim().accel_load (section); anim().accel_chain_add (eAnimWalkFwd, eAnimRun); anim().accel_chain_add (eAnimWalkFwd, eAnimRunTurnLeft); anim().accel_chain_add (eAnimWalkFwd, eAnimRunTurnRight); anim().accel_chain_add (eAnimWalkDamaged, eAnimRunDamaged); anim().AddReplacedAnim (&m_bDamaged, eAnimRun, eAnimRunDamaged); anim().AddReplacedAnim (&m_bDamaged, eAnimWalkFwd, eAnimWalkDamaged); anim().AddReplacedAnim (&m_bRunTurnLeft, eAnimRun, eAnimRunTurnLeft); anim().AddReplacedAnim (&m_bRunTurnRight, eAnimRun, eAnimRunTurnRight); SVelocityParam &velocity_none = move().get_velocity(MonsterMovement::eVelocityParameterIdle); SVelocityParam &velocity_turn = move().get_velocity(MonsterMovement::eVelocityParameterStand); SVelocityParam &velocity_walk = move().get_velocity(MonsterMovement::eVelocityParameterWalkNormal); SVelocityParam &velocity_run = move().get_velocity(MonsterMovement::eVelocityParameterRunNormal); SVelocityParam &velocity_walk_dmg = move().get_velocity(MonsterMovement::eVelocityParameterWalkDamaged); SVelocityParam &velocity_run_dmg = move().get_velocity(MonsterMovement::eVelocityParameterRunDamaged); SVelocityParam &velocity_steal = move().get_velocity(MonsterMovement::eVelocityParameterSteal); m_velocity_rotate.Load (section, "Velocity_Rotate"); m_velocity_jump_start.Load (section, "Velocity_JumpStart"); anim().AddAnim (eAnimStandIdle, "stand_idle_", -1, &velocity_none, PS_STAND); //@ IKinematicsAnimated* KA = smart_cast<IKinematicsAnimated*>(Visual()); MotionID idle_motion_id1 = KA->LL_MotionID("stand_idle_0"); MotionID idle_motion_id2 = KA->LL_MotionID("stand_idle_1"); anim().AddAnim (eAnimLieIdle, "stand_idle_", -1, &velocity_none, PS_LIE); anim().AddAnim (eAnimSleep, "stand_idle_", -1, &velocity_none, PS_LIE); anim().AddAnim (eAnimWalkFwd, "stand_walk_", -1, &velocity_walk, PS_STAND); anim().AddAnim (eAnimStandTurnLeft, "stand_turn_ls_", -1, &velocity_turn, PS_STAND); anim().AddAnim (eAnimStandTurnRight, "stand_turn_rs_", -1, &velocity_turn, PS_STAND); anim().AddAnim (eAnimFastStandTurnLeft, "stand_run_turn_90_ls_", -1, &m_velocity_rotate, PS_STAND); anim().AddAnim (eAnimFastStandTurnRight, "stand_run_turn_90_rs_", -1, &m_velocity_rotate, PS_STAND); anim().AddAnim (eAnimWalkDamaged, "stand_walk_dmg_", -1, &velocity_walk_dmg, PS_STAND); anim().AddAnim (eAnimRun, "stand_run_fwd_", -1, &velocity_run, PS_STAND); anim().AddAnim (eAnimRunDamaged, "stand_run_dmg_", -1, &velocity_run_dmg, PS_STAND); anim().AddAnim (eAnimCheckCorpse, "stand_check_corpse_", -1, &velocity_none, PS_STAND); anim().AddAnim (eAnimEat, "stand_eat_", -1, &velocity_none, PS_STAND); anim().AddAnim (eAnimAttack, "stand_idle_", -1, &velocity_turn, PS_STAND); anim().AddAnim (eAnimLookAround, "stand_idle_", -1, &velocity_none, PS_STAND); anim().AddAnim (eAnimSteal, "stand_walk_", -1, &velocity_steal, PS_STAND); anim().AddAnim (eAnimPrepareAttack, "stand_agressive_idle_",-1, &velocity_none, PS_STAND); anim().AddAnim (eAnimSteal, "stand_walk_", -1, &velocity_steal, PS_STAND); anim().AddAnim (eAnimDie, "stand_idle_", -1, &velocity_none, PS_STAND); anim().AddAnim (eAnimThreaten, "stand_idle_", -1, &velocity_none, PS_STAND); anim().AddAnim (eAnimRunTurnLeft, "stand_run_turn_ls_", -1, &velocity_run, PS_STAND); anim().AddAnim (eAnimRunTurnRight, "stand_run_turn_rs_", -1, &velocity_run, PS_STAND); anim().AddAnim (eAnimUpperAttack, "jump_attack_", -1, &m_velocity_jump_start, PS_STAND); // link action anim().LinkAction (ACT_STAND_IDLE, eAnimStandIdle); anim().LinkAction (ACT_SIT_IDLE, eAnimLieIdle); anim().LinkAction (ACT_LIE_IDLE, eAnimLieIdle); anim().LinkAction (ACT_WALK_FWD, eAnimWalkFwd); //anim().LinkAction (ACT_WALK_BKWD, eAnimDragCorpse); anim().LinkAction (ACT_RUN, eAnimRun); anim().LinkAction (ACT_EAT, eAnimEat); anim().LinkAction (ACT_SLEEP, eAnimSleep); anim().LinkAction (ACT_REST, eAnimLieIdle); //anim().LinkAction (ACT_DRAG, eAnimDragCorpse); anim().LinkAction (ACT_ATTACK, eAnimAttack); anim().LinkAction (ACT_STEAL, eAnimSteal); anim().LinkAction (ACT_LOOK_AROUND, eAnimLookAround); m_attack_params.attack_radius = READ_IF_EXISTS(pSettings, r_float,section, "attack_radius", 10.f); m_attack_params.prepare_jump_timeout = READ_IF_EXISTS(pSettings, r_u32, section, "prepare_jump_timeout", 2000); m_attack_params.attack_jump_timeout = READ_IF_EXISTS(pSettings ,r_u32, section, "attack_jump_timeout", 1000); m_attack_params.stealth_timeout = READ_IF_EXISTS(pSettings ,r_u32, section, "stealth_timeout", 2000); m_attack_params.force_attack_distance = READ_IF_EXISTS(pSettings ,r_float, section, "force_attack_distance", 8); m_attack_params.num_attack_jumps = READ_IF_EXISTS(pSettings ,r_u32, section, "num_attack_jumps", 4); m_attack_params.num_prepare_jumps = READ_IF_EXISTS(pSettings ,r_u32, section, "num_prepare_jumps", 2); #ifdef DEBUG anim().accel_chain_test (); #endif PostLoad (section); } EAction CChimera::CustomVelocityIndex2Action (u32 velocity_index) { switch ( velocity_index ) { case MonsterMovement::eChimeraVelocityParameterJumpGround: return ACT_RUN; case MonsterMovement::eChimeraVelocityParameterPrepare: return ACT_RUN; } return ACT_STAND_IDLE; } void CChimera::reinit () { inherited::reinit (); move().load_velocity (*cNameSect(), "Velocity_JumpGround", MonsterMovement::eChimeraVelocityParameterJumpGround); com_man().load_jump_data (0,//"jump_attack_0", 0,//"jump_attack_0", "jump_attack_1", "jump_attack_2", u32(-1),//MonsterMovement::eVelocityParameterRunNormal, MonsterMovement::eChimeraVelocityParameterJumpGround, 0); } void CChimera::CheckSpecParams (u32 spec_params) { // if ( (spec_params & ASP_THREATEN) == ASP_THREATEN ) // { // anim().SetCurAnim(eAnimThreaten); // } // if ( (spec_params & ASP_ATTACK_RUN) == ASP_ATTACK_RUN ) // { // anim().SetCurAnim(eAnimAttackRun); // } } void CChimera::HitEntityInJump (const CEntity *pEntity) { SAAParam &params = anim().AA_GetParams("jump_attack_1"); HitEntity (pEntity, params.hit_power, params.impulse, params.impulse_dir); } void CChimera::jump (Fvector const &position, float const factor) { com_man().script_jump (position, factor); sound().play (MonsterSound::eMonsterSoundAggressive); } void CChimera::UpdateCL() { inherited::UpdateCL (); }
42.096591
114
0.719935
Rikoshet-234
9c54e92fb7810670979ffd11764a525e64f9f322
3,281
hpp
C++
src/catch2/internal/catch_unique_ptr.hpp
shanep/Catch2
2db1cf34047f76cb2679a3804b476881536ad27b
[ "BSL-1.0" ]
9,861
2017-11-03T13:11:42.000Z
2022-03-31T23:50:03.000Z
src/catch2/internal/catch_unique_ptr.hpp
shanep/Catch2
2db1cf34047f76cb2679a3804b476881536ad27b
[ "BSL-1.0" ]
1,409
2017-11-03T13:42:48.000Z
2022-03-31T14:46:42.000Z
src/catch2/internal/catch_unique_ptr.hpp
shanep/Catch2
2db1cf34047f76cb2679a3804b476881536ad27b
[ "BSL-1.0" ]
2,442
2017-11-03T14:48:53.000Z
2022-03-31T23:07:09.000Z
// Copyright Catch2 Authors // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // https://www.boost.org/LICENSE_1_0.txt) // SPDX-License-Identifier: BSL-1.0 #ifndef CATCH_UNIQUE_PTR_HPP_INCLUDED #define CATCH_UNIQUE_PTR_HPP_INCLUDED #include <cassert> #include <type_traits> #include <catch2/internal/catch_move_and_forward.hpp> #if defined(__clang__) && defined(__has_attribute) # if __has_attribute(trivial_abi) # define TRIVIAL_ABI [[clang::trivial_abi]] # endif #endif #if !defined(TRIVIAL_ABI) # define TRIVIAL_ABI #endif namespace Catch { namespace Detail { /** * A reimplementation of `std::unique_ptr` for improved compilation performance * * Does not support arrays nor custom deleters, but has trivial ABI * when supposed by the compiler. */ template <typename T> class TRIVIAL_ABI unique_ptr { T* m_ptr; public: constexpr unique_ptr(std::nullptr_t = nullptr): m_ptr{} {} explicit constexpr unique_ptr(T* ptr): m_ptr(ptr) {} template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> unique_ptr(unique_ptr<U>&& from): m_ptr(from.release()) {} template <typename U, typename = std::enable_if_t<std::is_base_of<T, U>::value>> unique_ptr& operator=(unique_ptr<U>&& from) { reset(from.release()); return *this; } unique_ptr(unique_ptr const&) = delete; unique_ptr& operator=(unique_ptr const&) = delete; unique_ptr(unique_ptr&& rhs) noexcept: m_ptr(rhs.m_ptr) { rhs.m_ptr = nullptr; } unique_ptr& operator=(unique_ptr&& rhs) noexcept { reset(rhs.release()); return *this; } ~unique_ptr() { delete m_ptr; } T& operator*() { assert(m_ptr); return *m_ptr; } T const& operator*() const { assert(m_ptr); return *m_ptr; } T* operator->() noexcept { assert(m_ptr); return m_ptr; } T const* operator->() const noexcept { assert(m_ptr); return m_ptr; } T* get() { return m_ptr; } T const* get() const { return m_ptr; } void reset(T* ptr = nullptr) { delete m_ptr; m_ptr = ptr; } T* release() { auto temp = m_ptr; m_ptr = nullptr; return temp; } explicit operator bool() const { return m_ptr; } friend void swap(unique_ptr& lhs, unique_ptr& rhs) { auto temp = lhs.m_ptr; lhs.m_ptr = rhs.m_ptr; rhs.m_ptr = temp; } }; //! Specialization to cause compile-time error for arrays template <typename T> class unique_ptr<T[]>; template <typename T, typename... Args> unique_ptr<T> make_unique(Args&&... args) { return unique_ptr<T>(new T(CATCH_FORWARD(args)...)); } } // end namespace Detail } // end namespace Catch #endif // CATCH_UNIQUE_PTR_HPP_INCLUDED
25.434109
88
0.565681
shanep
9c56af0b2bed3f2a2a700e81cc2c817ee8d85915
14,168
cpp
C++
uberlogger.cpp
wolfviking0/uberlog
acd6a576d1ef1511828a661725951d349903b694
[ "MIT" ]
null
null
null
uberlogger.cpp
wolfviking0/uberlog
acd6a576d1ef1511828a661725951d349903b694
[ "MIT" ]
null
null
null
uberlogger.cpp
wolfviking0/uberlog
acd6a576d1ef1511828a661725951d349903b694
[ "MIT" ]
null
null
null
/* This is the child process that is spawned by a log writer. Here we consume log messages from the ring buffer, and write them into the log file. */ #ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #ifndef NOMINMAX #define NOMINMAX #endif //#define UNICODE #include <windows.h> #include <io.h> #include <fcntl.h> #include <sys/timeb.h> #include <sys/types.h> #define write _write #define open _open #define close _close #endif #ifdef __linux__ #include <sys/types.h> #include <sys/fcntl.h> #include <unistd.h> #include <glob.h> #include <time.h> #endif #ifdef __APPLE__ #include <libproc.h> #include <sys/proc_info.h> #include <stdlib.h> #include <sys/types.h> #include <sys/fcntl.h> #include <unistd.h> #include <glob.h> #include <time.h> #define lseek64 lseek #endif #include <string.h> #include <string> #include <vector> #include <thread> #include <algorithm> #include <stdio.h> #include <stdint.h> #include "uberlog.h" #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable : 6031) // /analyze is worried about us ignoring snprintf return value, but we're statically sized everywhere. #endif namespace uberlog { namespace internal { // Manage the log file, and the log rotation. // Assume we are the only process writing to this log file. class LogFile { public: LogFile() { } ~LogFile() { Close(); } void Init(std::string filename, int64_t maxFileSize, int32_t maxNumArchiveFiles) { Filename = filename; MaxFileSize = maxFileSize; MaxNumArchiveFiles = maxNumArchiveFiles; } bool Write(const void* buf, size_t len) { if (!Open()) return false; if (FileSize + (int64_t) len > MaxFileSize) { if (!RollOver()) return false; if (!Open()) return false; } if (len == 0) return true; // ignore the possibility that write() is allowed to write less than 'len' bytes. auto res = write(FD, buf, (int) len); if (res == -1) { // Perhaps something has happened on the file system, such as a network share being lost and then restored, etc. // Closing and opening again is the best thing we can try in this scenario. Close(); if (!Open()) return false; res = write(FD, buf, (int) len); } if (res != -1) FileSize += res; return res == len; } bool Open() { if (FD == -1) { #ifdef _WIN32 FD = _open(Filename.c_str(), _O_BINARY | _O_WRONLY | _O_CREAT, _S_IREAD | _S_IWRITE); if (FD == -1) return false; FileSize = (int64_t) _lseeki64(FD, 0, SEEK_END); #else FD = open(Filename.c_str(), O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP); if (FD == -1) return false; FileSize = (int64_t) lseek64(FD, 0, SEEK_END); #endif if (FileSize == -1) { close(FD); FD = -1; } } return FD != -1; } void Close() { if (FD == -1) return; close(FD); FD = -1; FileSize = 0; } private: std::string Filename; int64_t FileSize = 0; int64_t MaxFileSize = 0; int32_t MaxNumArchiveFiles = 0; int FD = -1; std::string FilenameExtension() const { // figure out the log file extension auto dot = Filename.rfind('.'); auto lastFSlash = Filename.rfind('/'); auto lastBSlash = Filename.rfind('\\'); std::string ext; if (dot != -1 && (lastFSlash == -1 || lastFSlash < dot) && (lastBSlash == -1 || lastBSlash < dot)) return Filename.substr(dot); return ""; } std::string ArchiveFilename() const { // build time representation (UTC) char timeBuf[100]; tm timev; #ifdef _WIN32 struct timeb t; ftime(&t); _gmtime64_s(&timev, &t.time); uint32_t millis = (uint32_t) t.millitm; #else struct timespec tp; clock_gettime(CLOCK_REALTIME, &tp); time_t t = tp.tv_sec; uint32_t millis = tp.tv_nsec / 1000000; gmtime_r(&t, &timev); #endif strftime(timeBuf, sizeof(timeBuf), "-%Y-%m-%dT%H-%M-%S-", &timev); char milliBuf[20]; snprintf(milliBuf, 20, "%03u-Z", millis); strcat(timeBuf, milliBuf); // build the archive filename std::string ext = FilenameExtension(); std::string archive = Filename.substr(0, Filename.length() - ext.length()); archive += timeBuf; archive += ext; return archive; } std::string LogDir() const { auto lastSlash = Filename.rfind(PATH_SLASH); if (lastSlash == -1) return ""; return Filename.substr(0, lastSlash + 1); } std::vector<std::string> FindArchiveFiles() const { auto dir = LogDir(); auto ext = FilenameExtension(); auto wildcard = Filename.substr(0, Filename.length() - ext.length()) + "-*"; std::vector<std::string> archives; #ifdef _WIN32 WIN32_FIND_DATAA fd; HANDLE fh = FindFirstFileA(wildcard.c_str(), &fd); if (fh != INVALID_HANDLE_VALUE) { do { archives.push_back(dir + fd.cFileName); } while (!!FindNextFileA(fh, &fd)); FindClose(fh); } #else glob_t pglob; if (glob(wildcard.c_str(), 0, nullptr, &pglob) == 0) { for (size_t i = 0; i < pglob.gl_pathc; i++) archives.push_back(dir + pglob.gl_pathv[i]); globfree(&pglob); } #endif // rely on our lexicographic archive naming convention, so that files are sorted oldest to newest std::sort(archives.begin(), archives.end()); return archives; } bool RollOver() { Close(); // rename current log file std::string archive = ArchiveFilename(); if (rename(Filename.c_str(), archive.c_str()) != 0) { OutOfBandWarning("Rollover failed trying to rename '%s' to '%s'\n", Filename.c_str(), archive.c_str()); return false; } // delete old archives, but ignore failure auto archives = FindArchiveFiles(); if (archives.size() > (size_t) MaxNumArchiveFiles) { for (size_t i = 0; i < archives.size() - MaxNumArchiveFiles; i++) remove(archives[i].c_str()); } return true; } }; //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////////// // This implements the logic of the logger slave process class LoggerSlave { public: static const size_t WriteBufSize = LoggerSlaveWriteBufferSize; bool EnableDebugMessages = false; uint32_t ParentPID = 0; uint32_t RingSize = 0; std::atomic<bool> IsParentDead; RingBuffer Ring; shm_handle_t ShmHandle = internal::NullShmHandle; std::thread WatcherThread; std::string Filename; int64_t MaxLogSize = 30 * 1024 * 1024; int32_t MaxNumArchives = 3; uint32_t MaxSleepMS = 1024; uint32_t WaitForOpenSleepMS = 1; // Our sleep periods when we're waiting for the ring buffer to be opened LogFile Log; char* WriteBuf = nullptr; #ifdef _WIN32 HANDLE CloseMessageEvent = NULL; #else bool CloseMessageFlag = false; #endif LoggerSlave() { IsParentDead = false; } void Run() { DebugMsg("uberlog writer [%v, %v MB max size, %v archives] is starting\n", Filename, MaxLogSize / 1024 / 1024, MaxNumArchives); WriteBuf = new char[WriteBufSize]; #ifdef _WIN32 CloseMessageEvent = CreateEvent(NULL, true, false, NULL); #endif std::thread watcherThread = WatchForParentProcessDeath(); // Windows-only Log.Init(Filename, MaxLogSize, MaxNumArchives); // Try to open file immediately, for consistency & predictability sake Log.Open(); uint32_t sleepMS = 0; uint64_t totalSleepMS = 0; while (!IsParentDead && !HasReceivedCloseMessage()) { bool idle = false; if (!Ring.Buf) OpenRingBuffer(); if (Ring.Buf) { uint64_t nmessages = ReadMessages(); if (nmessages == 0) idle = true; } if (idle) sleepMS = std::min(std::max(sleepMS, 1u) * 2, MaxSleepMS); else if (Ring.Buf) sleepMS = 0; else sleepMS = WaitForOpenSleepMS; // This is a no-op on Windows, because on Windows we just WaitForSingleObject(parentProcessHandle) PollForParentProcessDeath(); totalSleepMS += sleepMS; internal::SleepMS(sleepMS); } // Drain the buffer if (IsParentDead && Ring.Buf) ReadMessages(); //uberlog_tsf::print("Logger slave slept for a total of %v MS\n", totalSleepMS); CloseRingBuffer(); Log.Close(); if (HasReceivedCloseMessage()) DebugMsg("uberlog is stopping: received Close instruction\n"); if (IsParentDead) DebugMsg("uberlog is stopping: parent is dead\n"); //SleepMS(2000); // DEBUG if (watcherThread.joinable()) watcherThread.join(); #ifdef _WIN32 if (CloseMessageEvent) CloseHandle(CloseMessageEvent); CloseMessageEvent = NULL; #endif delete[] WriteBuf; } private: std::thread WatchForParentProcessDeath() { #ifdef _WIN32 // Assume that if we can't open the process, then it is already dead HANDLE hproc = OpenProcess(SYNCHRONIZE, false, (DWORD) ParentPID); if (hproc == NULL) { IsParentDead = true; return std::thread(); } return std::thread([this, hproc]() { HANDLE h[] = {hproc, CloseMessageEvent}; DWORD fired = WaitForMultipleObjects(2, h, false, INFINITE) - WAIT_OBJECT_0; if (fired == 0) this->IsParentDead = true; CloseHandle(hproc); }); #else // The linux implementation polls, via PollForParentProcessDeath return std::thread(); #endif } void PollForParentProcessDeath() { #if defined(__linux__) || defined(__APPLE__) // On linux, if our parent process dies, then we will get a new parent pid (ppid). We take any change in ppid // as a sign that our parent process has died. When not running under docker, you can use ppid = 0 or ppid = 1 // as a sign that your parent process has died, but this is not reliable under docker. So we only check for // a change in ppid. // See http://stackoverflow.com/a/2035683/90614 auto ppid = getppid(); if (ppid != ParentPID) { IsParentDead = true; } #endif // On Windows, we don't need to implement this path, because we can wait on process death } bool OpenRingBuffer() { shm_handle_t shm = NullShmHandle; void* buf = nullptr; if (!SetupSharedMemory(ParentPID, Filename.c_str(), SharedMemSizeFromRingSize(RingSize), false, shm, buf)) return false; ShmHandle = shm; Ring.Init(buf, RingSize, false); return true; } void CloseRingBuffer() { if (Ring.Buf) CloseSharedMemory(ShmHandle, Ring.Buf, SharedMemSizeFromRingSize(Ring.Size)); Ring.Buf = nullptr; Ring.Size = 0; ShmHandle = NullShmHandle; } // Returns number of log messages consumed uint64_t ReadMessages() { // Buffer up messages, so that we don't issue an OS write for every message size_t bufpos = 0; uint64_t nmessages = 0; while (true) { MessageHead head; size_t avail = Ring.AvailableForRead(); if (avail < sizeof(head)) break; if (Ring.Read(&head, sizeof(head)) != sizeof(head)) Panic("ring.Read(head) failed"); avail -= sizeof(head); switch (head.Cmd) { case Command::Close: SetReceivedCloseMessage(); break; case Command::LogMsg: { nmessages++; if (avail < head.PayloadLen) Panic("ring.Read: message payload not available in ring buffer"); if (head.PayloadLen > WriteBufSize - bufpos) { if (!Log.Write(WriteBuf, bufpos)) OutOfBandWarning("Failed to write to log file '%s'\n", Filename.c_str()); bufpos = 0; } if (head.PayloadLen <= WriteBufSize - bufpos) { // store message in buffer size_t nread = Ring.Read(WriteBuf + bufpos, head.PayloadLen); if (nread != head.PayloadLen) Panic("ring.Read: unable to read all of payload\n"); bufpos += head.PayloadLen; } else { // log message is too large to buffer. write it directly if (bufpos != 0) Panic("ring.Read: should have flushed log"); // the Log.Write call 10 lines above should have done this already void* ptr1 = nullptr; void* ptr2 = nullptr; size_t size1 = 0; size_t size2 = 0; Ring.ReadNoCopy(head.PayloadLen, ptr1, size1, ptr2, size2); bool ok = Log.Write(ptr1, size1); if (ok && size2 != 0) ok = Log.Write(ptr2, size2); if (!ok) OutOfBandWarning("Failed to write to log file '%s'\n", Filename.c_str()); Ring.Read(nullptr, head.PayloadLen); } break; } default: Panic("Unexpected command"); } } // flush write buffer if (bufpos != 0) { if (!Log.Write(WriteBuf, bufpos)) OutOfBandWarning("Failed to write to log file '%s'\n", Filename.c_str()); } return nmessages; } void SetReceivedCloseMessage() { #ifdef _WIN32 SetEvent(CloseMessageEvent); #else CloseMessageFlag = true; #endif } bool HasReceivedCloseMessage() { #ifdef _WIN32 return WaitForSingleObject(CloseMessageEvent, 0) == WAIT_OBJECT_0; #else return CloseMessageFlag; #endif } template <typename... Args> void DebugMsg(const char* msg, const Args&... args) { if (!EnableDebugMessages) return; fputs(uberlog_tsf::fmt(msg, args...).c_str(), stdout); } }; void ShowHelp() { auto help = R"(uberlogger is a child process that is spawned by an application that performs logging. Normally, you do not launch uberlogger manually. It is launched automatically by the uberlog library. uberlogger <parentpid> <ringsize> <logfilename> <maxlogsize> <maxarchives>)"; printf("%s\n", help); } } // namespace internal } // namespace uberlog int main(int argc, char** argv) { bool showHelp = true; if (argc == 6) { showHelp = false; uberlog::internal::LoggerSlave slave; slave.ParentPID = (uint32_t) strtoul(argv[1], nullptr, 10); slave.RingSize = (uint32_t) strtoul(argv[2], nullptr, 10); slave.Filename = argv[3]; slave.MaxLogSize = (int64_t) strtoull(argv[4], nullptr, 10); slave.MaxNumArchives = (int32_t) strtol(argv[5], nullptr, 10); slave.Run(); } if (showHelp) { uberlog::internal::ShowHelp(); return 1; } return 0; } #ifdef _MSC_VER #pragma warning(pop) #endif
24.899824
134
0.635305
wolfviking0
9c58087d525a543e228a2eec3ab9599f71d45814
910
cpp
C++
C++/222. Count Complete Tree Nodes.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
3
2018-07-28T15:36:18.000Z
2020-03-17T01:26:22.000Z
C++/222. Count Complete Tree Nodes.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
null
null
null
C++/222. Count Complete Tree Nodes.cpp
WangYang-wy/LeetCode
c92fcb83f86c277de6785d5a950f16bc007ccd31
[ "MIT" ]
null
null
null
// // Created by ็Ž‹้˜ณ on 2018/8/12. // #include "header.h" class Solution { public: int countNodes(TreeNode *root) { if (nullptr == root) { return 0; } else { int left = this->get_left_height(root); int right = this->get_right_height(root); if (left == right) { return (1 << right) - 1; } else { return this->countNodes(root->left) + this->countNodes(root->right) + 1; } } } int get_left_height(TreeNode *root) { int height = 0; while (root) { height++; root = root->left; } return height; } int get_right_height(TreeNode *root) { int height = 0; while (root) { height++; root = root->right; } return height; } }; int main() { return 0; }
20.222222
88
0.459341
WangYang-wy
9c5bb9e394606f0485402ba57e04f8fbf4284097
2,353
cpp
C++
Luogu/P5490_withoutPTR.cpp
Thomitics/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
140
2021-02-14T02:41:48.000Z
2021-07-08T02:59:13.000Z
Luogu/P5490_withoutPTR.cpp
LikiBlaze/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
1
2021-02-16T02:46:45.000Z
2021-02-16T02:46:45.000Z
Luogu/P5490_withoutPTR.cpp
Thomitics/MyOI
72f75b61b79230835a65ca313896031ba9d4665f
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define INF 999999999 #define lch (nowX << 1) #define rch (nowX << 1 | 1) using namespace std; inline long long read() { long long x = 0; int f = 1; char ch = getchar(); while (ch < '0' || ch > '9') { if (ch == '-') f = -1; ch = getchar(); } while (ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); } return x * f; } void write(const long long &x) { if (!x) { putchar('0'); return; } char f[100]; long long tmp = x; if (tmp < 0) { tmp = -tmp; putchar('-'); } long long s = 0; while (tmp > 0) { f[s++] = tmp % 10 + '0'; tmp /= 10; } while (s > 0) { putchar(f[--s]); } } const long long maxN = 1000090; struct Line { long long l, r; long long h; short mark; } lines[maxN << 1]; bool operator<(Line a, Line b) { return a.h < b.h; } struct Node { long long l, r; long long sum; long long len; } nodes[maxN << 2]; long long X[maxN << 1]; void build(long long nowX, long long L, long long R) { nodes[nowX].l = L; nodes[nowX].r = R; nodes[nowX].len = 0; nodes[nowX].sum = 0; if (L == R) { return; } long long Mid = (L + R) >> 1; build(lch, L, Mid); build(rch, Mid + 1, R); } void pushup(long long nowX) { if (nodes[nowX].sum) { nodes[nowX].len = X[nodes[nowX].r + 1] - X[nodes[nowX].l]; } else { nodes[nowX].len = nodes[lch].len + nodes[rch].len; } } void update(long long nowX, long long L, long long R, long long C) { if (X[nodes[nowX].r + 1] <= L || X[nodes[nowX].l] >= R) { return; } if ((L <= X[nodes[nowX].l]) && (X[nodes[nowX].r + 1] <= R)) { nodes[nowX].sum += C; pushup(nowX); return; } update(lch, L, R, C); update(rch, L, R, C); pushup(nowX); } long long totN; long long totL; long long totANS; int main() { totN = read(); for (int i = 1, Xa, Ya, Xb, Yb; i <= totN; ++i) { Xa = read(); Ya = read(); Xb = read(); Yb = read(); X[2 * i - 1] = Xa; X[2 * i] = Xb; lines[2 * i - 1] = {Xa, Xb, Ya, 1}; lines[2 * i] = {Xa, Xb, Yb, -1}; } totN <<= 1; sort(lines + 1, lines + totN + 1); sort(X + 1, X + totN + 1); totL = unique(X + 1, X + totN + 1) - (X + 1); build(1, 1, totL - 1); for (int i = 1; i < totN; ++i) { update(1, lines[i].l, lines[i].r, lines[i].mark); totANS += nodes[1].len * (lines[i + 1].h - lines[i].h); } write(totANS); return 0; } //Thomitics Code
16.227586
66
0.517212
Thomitics
9c5d6d101fb732a02431fa8338d851742fd43f6b
1,702
cpp
C++
vpc/src/v2/model/NeutronUpdateFirewallGroupResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
5
2021-03-03T08:23:43.000Z
2022-02-16T02:16:39.000Z
vpc/src/v2/model/NeutronUpdateFirewallGroupResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
null
null
null
vpc/src/v2/model/NeutronUpdateFirewallGroupResponse.cpp
yangzhaofeng/huaweicloud-sdk-cpp-v3
4f3caac5ba9a9b75b4e5fd61683d1c4d57ec1c23
[ "Apache-2.0" ]
7
2021-02-26T13:53:35.000Z
2022-03-18T02:36:43.000Z
#include "huaweicloud/vpc/v2/model/NeutronUpdateFirewallGroupResponse.h" namespace HuaweiCloud { namespace Sdk { namespace Vpc { namespace V2 { namespace Model { NeutronUpdateFirewallGroupResponse::NeutronUpdateFirewallGroupResponse() { firewallGroupIsSet_ = false; } NeutronUpdateFirewallGroupResponse::~NeutronUpdateFirewallGroupResponse() = default; void NeutronUpdateFirewallGroupResponse::validate() { } web::json::value NeutronUpdateFirewallGroupResponse::toJson() const { web::json::value val = web::json::value::object(); if(firewallGroupIsSet_) { val[utility::conversions::to_string_t("firewall_group")] = ModelBase::toJson(firewallGroup_); } return val; } bool NeutronUpdateFirewallGroupResponse::fromJson(const web::json::value& val) { bool ok = true; if(val.has_field(utility::conversions::to_string_t("firewall_group"))) { const web::json::value& fieldValue = val.at(utility::conversions::to_string_t("firewall_group")); if(!fieldValue.is_null()) { NeutronFirewallGroup refVal; ok &= ModelBase::fromJson(fieldValue, refVal); setFirewallGroup(refVal); } } return ok; } NeutronFirewallGroup NeutronUpdateFirewallGroupResponse::getFirewallGroup() const { return firewallGroup_; } void NeutronUpdateFirewallGroupResponse::setFirewallGroup(const NeutronFirewallGroup& value) { firewallGroup_ = value; firewallGroupIsSet_ = true; } bool NeutronUpdateFirewallGroupResponse::firewallGroupIsSet() const { return firewallGroupIsSet_; } void NeutronUpdateFirewallGroupResponse::unsetfirewallGroup() { firewallGroupIsSet_ = false; } } } } } }
21.012346
105
0.731492
yangzhaofeng
9c610f9066faa56fa1ffaef317e0e93336359470
3,234
cpp
C++
Raven.CppClient/ToggleDatabasesStateOperation.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient/ToggleDatabasesStateOperation.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient/ToggleDatabasesStateOperation.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
๏ปฟ#include "stdafx.h" #include "ToggleDatabasesStateOperation.h" #include "json_utils.h" namespace ravendb::client::documents::operations { void toggle_databases_state_operation::to_json(nlohmann::json& j, const Parameters& p) { using ravendb::client::impl::utils::json_utils::set_val_to_json; set_val_to_json(j, "DatabaseNames", p.database_names); } ToggleDatabasesStateOperation::~ToggleDatabasesStateOperation() = default; ToggleDatabasesStateOperation::ToggleDatabasesStateOperation(std::string database_name, bool disable) : _disabled(disable) , _parameters({{std::move(database_name)}}) {} ToggleDatabasesStateOperation::ToggleDatabasesStateOperation(std::vector<std::string> database_names, bool disable) : _disabled(disable) , _parameters({std::move(database_names)}) {} ToggleDatabasesStateOperation::ToggleDatabasesStateOperation(toggle_databases_state_operation::Parameters parameters, bool disable) : _disabled(disable) , _parameters(std::move(parameters)) {} std::unique_ptr<http::RavenCommand<DisableDatabaseToggleResult>> ToggleDatabasesStateOperation::get_command( std::shared_ptr<documents::conventions::DocumentConventions> conventions) const { return std::make_unique<ToggleDatabaseStateCommand>(conventions, _parameters, _disabled); } ToggleDatabasesStateOperation::ToggleDatabaseStateCommand::~ToggleDatabaseStateCommand() = default; ToggleDatabasesStateOperation::ToggleDatabaseStateCommand::ToggleDatabaseStateCommand( std::shared_ptr<documents::conventions::DocumentConventions> conventions, toggle_databases_state_operation::Parameters parameters, bool disabled) : _disabled(disabled) , _parameters(std::move(parameters)) , _parameters_json_str(nlohmann::json(_parameters).dump()) {} void ToggleDatabasesStateOperation::ToggleDatabaseStateCommand::create_request( impl::CurlHandlesHolder::CurlReference& curl_ref, std::shared_ptr<const http::ServerNode> node, std::optional<std::string>& url_ref) { auto curl = curl_ref.get(); std::ostringstream path_builder; path_builder << node->url << "/admin/databases/" << (_disabled ? "disable" : "enable"); curl_ref.headers.insert_or_assign("Transfer-Encoding", "chunked"); curl_ref.headers.insert_or_assign(constants::headers::CONTENT_TYPE, "application/json"); curl_ref.method = constants::methods::POST; curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl_ref.get(), CURLOPT_POSTFIELDSIZE_LARGE, curl_off_t(_parameters_json_str.size())); curl_easy_setopt(curl_ref.get(), CURLOPT_POSTFIELDS, _parameters_json_str.c_str()); url_ref.emplace(path_builder.str()); } void ToggleDatabasesStateOperation::ToggleDatabaseStateCommand::set_response( const std::optional<nlohmann::json>& response, bool from_cache) { if(!response) { throw_invalid_response(); } auto&& json_node = response.value(); auto&& status_node = json_node.at("Status"); if(!status_node.is_array()) { throw_invalid_response(); } auto&& database_status = status_node.at(0); _result = std::make_shared<ResultType>(database_status.get<ResultType>()); } bool ToggleDatabasesStateOperation::ToggleDatabaseStateCommand::is_read_request() const { return false; } }
33.6875
118
0.780148
mlawsonca
9c66c550a684052ab098d82ce6d8edb79b7d90e5
3,554
cpp
C++
lib/models/guild_member.cpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-09-19T15:28:25.000Z
2018-08-09T13:17:40.000Z
lib/models/guild_member.cpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
44
2016-11-03T17:27:30.000Z
2017-12-10T16:17:31.000Z
lib/models/guild_member.cpp
FiniteReality/disccord
1b89cde8031a1d6f9d43fa8f39dbc0959c8639ff
[ "MIT" ]
13
2016-11-01T00:17:20.000Z
2018-08-03T19:51:16.000Z
#include <disccord/models/guild_member.hpp> namespace disccord { namespace models { guild_member::guild_member() : member(), nick(), roles(), joined_at(""), deaf(false), mute(false) { } guild_member::~guild_member() { } void guild_member::decode(web::json::value json) { joined_at = json.at("joined_at").as_string(); deaf = json.at("deaf").as_bool(); mute = json.at("mute").as_bool(); #define get_field(var, conv) \ if (json.has_field(#var)) { \ auto field = json.at(#var); \ if (!field.is_null()) { \ var = decltype(var)(field.conv()); \ } else { \ var = decltype(var)::no_value(); \ } \ } else { \ var = decltype(var)(); \ } get_field(nick, as_string); if (json.has_field("user")) { auto field = json.at("user"); if (!field.is_null()) { user val; val.decode(field); member = util::optional<user>(val); } else { member = util::optional<user>::no_value(); } } else { member = util::optional<user>(); } if (json.has_field("roles")) { auto _roles_array = json.at("roles").as_array(); std::vector<uint64_t> roles_array(_roles_array.size()); std::transform(_roles_array.begin(), _roles_array.end(), roles_array.begin(), [](web::json::value _role) { return std::stoull(_role.as_string()); }); roles = roles_array; } #undef get_field } void guild_member::encode_to( std::unordered_map<std::string, web::json::value> &info) { info["joined_at"] = web::json::value(joined_at); info["deaf"] = web::json::value(deaf); info["mute"] = web::json::value(mute); if (nick.is_specified()) info["nick"] = web::json::value(nick.get_value()); if (member.is_specified()) info["user"] = member.get_value().encode(); if (roles.is_specified()) { auto _roles = get_roles().get_value(); std::vector<web::json::value> roles_array(_roles.size()); std::transform(_roles.begin(), _roles.end(), roles_array.begin(), [](uint64_t role) { return web::json::value(role); }); info["roles"] = web::json::value::array(roles_array); } } #define define_get_method(field_name) \ decltype(guild_member::field_name) \ guild_member::get_##field_name() { \ return field_name; \ } define_get_method(joined_at) define_get_method(deaf) define_get_method(mute) define_get_method(nick) define_get_method(member) define_get_method(roles) #undef define_get_method } }
33.214953
73
0.433877
FiniteReality
9c6766113058abefb8881daad153bc72d8a29f8e
4,011
cpp
C++
platformio/src/display/lvgl_adapter.cpp
th0mpy/simple_stepper_motor_analyzer
a8e6377aac78fe9a346e57819f1963a0ae52e446
[ "CC0-1.0" ]
218
2021-01-30T07:36:53.000Z
2022-03-28T23:34:35.000Z
platformio/src/display/lvgl_adapter.cpp
th0mpy/simple_stepper_motor_analyzer
a8e6377aac78fe9a346e57819f1963a0ae52e446
[ "CC0-1.0" ]
19
2021-04-17T12:45:07.000Z
2022-03-03T22:38:48.000Z
platformio/src/display/lvgl_adapter.cpp
th0mpy/simple_stepper_motor_analyzer
a8e6377aac78fe9a346e57819f1963a0ae52e446
[ "CC0-1.0" ]
38
2021-03-23T21:13:12.000Z
2022-03-19T20:34:13.000Z
// See display porting here: // https://docs.lvgl.io/v7/en/html/porting/display.html #include "lvgl_adapter.h" #include <stdio.h> #include "io.h" #include "lvgl.h" #include "misc/hardware_config.h" #include "pico/stdlib.h" #include "tft_driver.h" #include "touch_driver.h" #if LV_COLOR_DEPTH != 16 #error "Expecting LVGL color depth of 16" #endif namespace lvgl_adapter { //#define TFT_SYNC_PIN 0 #define MY_DISP_HOR_RES (480) // A static variable to store the buffers. static lv_disp_buf_t disp_buf; static lv_disp_drv_t disp_drv; // LVGL renders up to this number of pixels at a time. // We use two buffers, each with a 1/4 screen size and alternate // render/DMA. static constexpr uint32_t kBufferSize = MY_DISP_HOR_RES * 80; // static lv_color_t buf_1[kBufferSize]; static lv_color_t buf_2[kBufferSize]; // Called by LV_GL to flush a buffer to the display. Per our LVGL config, // color is uint16_t RGB565. static void my_flush_cb(lv_disp_drv_t* disp_drv, const lv_area_t* area, lv_color_t* color_p) { // LED2_ON; // if (screen_capture_enabled) { // capture_buffer(area, color_p); //} // if (sync_next_update_flag) { // wait_for_tft_sync(); // sync_next_update_flag = false; // } // Per our lv config settings, LVGL uses 16 bits colors. const lv_color16_t* lv_color16 = static_cast<lv_color16_t*>(color_p); tft_driver::render_buffer(area->x1, area->y1, area->x2, area->y2, (uint16_t*)lv_color16); // LED2_OFF; // NOTE: The DMA completion callback will call lv_disp_flush_ready(disp_drv) // once the DMA to the TFT is completed. } void static init_display_driver() { // Initialize `disp_buf` with the buffer. We pass NULL for // the second (optional) buffer since we don't use DMA. lv_disp_buf_init(&disp_buf, buf_1, buf_2, kBufferSize); lv_disp_drv_init(&disp_drv); // Sets an initialized buffer. disp_drv.buffer = &disp_buf; // Sets a flush callback to draw to the display. disp_drv.flush_cb = my_flush_cb; // Register the driver and save the created display objects. lv_disp_drv_register(&disp_drv); } // This is how LVGL reads the touch screen's status. bool my_touch_read_cb(lv_indev_drv_t* drv, lv_indev_data_t* data) { uint16_t x, y; bool is_pressed; touch_driver::touch_read(&x, &y, &is_pressed); data->point.x = x; data->point.y = y; data->state = is_pressed ? LV_INDEV_STATE_PR : LV_INDEV_STATE_REL; // No buffering now so no more data read. return false; } void static init_touch_driver() { lv_indev_drv_t indev_drv; lv_indev_drv_init(&indev_drv); indev_drv.type = LV_INDEV_TYPE_POINTER; indev_drv.read_cb = my_touch_read_cb; // Register the driver in LVGL and save the created input device object. // TODO: verify result is not null (error) lv_indev_drv_register(&indev_drv); } // DMA completion callback from the tft_driver. void dma_completion_irq_cb() { lv_disp_flush_ready(&disp_drv); } // Called once from main on program start. void setup() { tft_driver::begin(); // Init gpio // constexpr uint kInputMask = 1ul << TFT_SYNC_PIN; // gpio_init_mask(kInputMask); // gpio_set_dir_in_masked(kInputMask); lv_init(); init_display_driver(); init_touch_driver(); } void dump_stats() { lv_mem_monitor_t lv_info; lv_mem_monitor(&lv_info); printf("total_size=%lu, free_cnt=%lu, free_size=%lu, free_bigest_size=%lu\n", lv_info.total_size, lv_info.free_cnt, lv_info.free_size, lv_info.free_biggest_size); printf("used_cnt=%lu, max_used=%lu, used_pct=%hu, frag_pct=%hu\n", lv_info.used_cnt, lv_info.max_used, lv_info.used_pct, lv_info.frag_pct); } void set_backlight(uint8_t percents) { tft_driver::set_backlight(percents); } void dump_screen() { if (hardware_config::level() < hardware_config::LEVEL_MK3) { printf("Hardware version %s doesn't support screen dump\n", hardware_config::level_name()); } tft_driver::dump_screen(); } } // namespace lvgl_adapter
28.65
79
0.71653
th0mpy
9c67cdeeb75828bed82cf2147172a6c1dd2d6e9d
12,209
cpp
C++
libclamav/c++/llvm/lib/Target/SubtargetFeature.cpp
watchdogdevel/wsdk-scanner-core
7a2451bbee9ed9a7246eb5fbb21d09d7e0442240
[ "BSL-1.0" ]
1
2022-01-22T12:16:33.000Z
2022-01-22T12:16:33.000Z
libclamav/c++/llvm/lib/Target/SubtargetFeature.cpp
watchdogdevel/wsdk-scanner-core
7a2451bbee9ed9a7246eb5fbb21d09d7e0442240
[ "BSL-1.0" ]
null
null
null
libclamav/c++/llvm/lib/Target/SubtargetFeature.cpp
watchdogdevel/wsdk-scanner-core
7a2451bbee9ed9a7246eb5fbb21d09d7e0442240
[ "BSL-1.0" ]
null
null
null
//===- SubtargetFeature.cpp - CPU characteristics Implementation ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the SubtargetFeature interface. // //===----------------------------------------------------------------------===// #include "llvm/Target/SubtargetFeature.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ADT/StringExtras.h" #include <algorithm> #include <cassert> #include <cctype> #include <cstdlib> using namespace llvm; //===----------------------------------------------------------------------===// // Static Helper Functions //===----------------------------------------------------------------------===// /// hasFlag - Determine if a feature has a flag; '+' or '-' /// static inline bool hasFlag(const std::string &Feature) { assert(!Feature.empty() && "Empty string"); // Get first character char Ch = Feature[0]; // Check if first character is '+' or '-' flag return Ch == '+' || Ch =='-'; } /// StripFlag - Return string stripped of flag. /// static inline std::string StripFlag(const std::string &Feature) { return hasFlag(Feature) ? Feature.substr(1) : Feature; } /// isEnabled - Return true if enable flag; '+'. /// static inline bool isEnabled(const std::string &Feature) { assert(!Feature.empty() && "Empty string"); // Get first character char Ch = Feature[0]; // Check if first character is '+' for enabled return Ch == '+'; } /// PrependFlag - Return a string with a prepended flag; '+' or '-'. /// static inline std::string PrependFlag(const std::string &Feature, bool IsEnabled) { assert(!Feature.empty() && "Empty string"); if (hasFlag(Feature)) return Feature; return std::string(IsEnabled ? "+" : "-") + Feature; } /// Split - Splits a string of comma separated items in to a vector of strings. /// static void Split(std::vector<std::string> &V, const std::string &S) { // Start at beginning of string. size_t Pos = 0; while (true) { // Find the next comma size_t Comma = S.find(',', Pos); // If no comma found then the rest of the string is used if (Comma == std::string::npos) { // Add string to vector V.push_back(S.substr(Pos)); break; } // Otherwise add substring to vector V.push_back(S.substr(Pos, Comma - Pos)); // Advance to next item Pos = Comma + 1; } } /// Join a vector of strings to a string with a comma separating each element. /// static std::string Join(const std::vector<std::string> &V) { // Start with empty string. std::string Result; // If the vector is not empty if (!V.empty()) { // Start with the CPU feature Result = V[0]; // For each successive feature for (size_t i = 1; i < V.size(); i++) { // Add a comma Result += ","; // Add the feature Result += V[i]; } } // Return the features string return Result; } /// Adding features. void SubtargetFeatures::AddFeature(const std::string &String, bool IsEnabled) { // Don't add empty features if (!String.empty()) { // Convert to lowercase, prepend flag and add to vector Features.push_back(PrependFlag(LowercaseString(String), IsEnabled)); } } /// Find KV in array using binary search. template<typename T> const T *Find(const std::string &S, const T *A, size_t L) { // Make the lower bound element we're looking for T KV; KV.Key = S.c_str(); // Determine the end of the array const T *Hi = A + L; // Binary search the array const T *F = std::lower_bound(A, Hi, KV); // If not found then return NULL if (F == Hi || std::string(F->Key) != S) return NULL; // Return the found array item return F; } /// getLongestEntryLength - Return the length of the longest entry in the table. /// static size_t getLongestEntryLength(const SubtargetFeatureKV *Table, size_t Size) { size_t MaxLen = 0; for (size_t i = 0; i < Size; i++) MaxLen = std::max(MaxLen, std::strlen(Table[i].Key)); return MaxLen; } /// Display help for feature choices. /// static void Help(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize, const SubtargetFeatureKV *FeatTable, size_t FeatTableSize) { // Determine the length of the longest CPU and Feature entries. unsigned MaxCPULen = getLongestEntryLength(CPUTable, CPUTableSize); unsigned MaxFeatLen = getLongestEntryLength(FeatTable, FeatTableSize); // Print the CPU table. errs() << "Available CPUs for this target:\n\n"; for (size_t i = 0; i != CPUTableSize; i++) errs() << " " << CPUTable[i].Key << std::string(MaxCPULen - std::strlen(CPUTable[i].Key), ' ') << " - " << CPUTable[i].Desc << ".\n"; errs() << "\n"; // Print the Feature table. errs() << "Available features for this target:\n\n"; for (size_t i = 0; i != FeatTableSize; i++) errs() << " " << FeatTable[i].Key << std::string(MaxFeatLen - std::strlen(FeatTable[i].Key), ' ') << " - " << FeatTable[i].Desc << ".\n"; errs() << "\n"; errs() << "Use +feature to enable a feature, or -feature to disable it.\n" << "For example, llc -mcpu=mycpu -mattr=+feature1,-feature2\n"; exit(1); } //===----------------------------------------------------------------------===// // SubtargetFeatures Implementation //===----------------------------------------------------------------------===// SubtargetFeatures::SubtargetFeatures(const std::string &Initial) { // Break up string into separate features Split(Features, Initial); } std::string SubtargetFeatures::getString() const { return Join(Features); } void SubtargetFeatures::setString(const std::string &Initial) { // Throw out old features Features.clear(); // Break up string into separate features Split(Features, LowercaseString(Initial)); } /// setCPU - Set the CPU string. Replaces previous setting. Setting to "" /// clears CPU. void SubtargetFeatures::setCPU(const std::string &String) { Features[0] = LowercaseString(String); } /// setCPUIfNone - Setting CPU string only if no string is set. /// void SubtargetFeatures::setCPUIfNone(const std::string &String) { if (Features[0].empty()) setCPU(String); } /// getCPU - Returns current CPU. /// const std::string & SubtargetFeatures::getCPU() const { return Features[0]; } /// SetImpliedBits - For each feature that is (transitively) implied by this /// feature, set it. /// static void SetImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry, const SubtargetFeatureKV *FeatureTable, size_t FeatureTableSize) { for (size_t i = 0; i < FeatureTableSize; ++i) { const SubtargetFeatureKV &FE = FeatureTable[i]; if (FeatureEntry->Value == FE.Value) continue; if (FeatureEntry->Implies & FE.Value) { Bits |= FE.Value; SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize); } } } /// ClearImpliedBits - For each feature that (transitively) implies this /// feature, clear it. /// static void ClearImpliedBits(uint32_t &Bits, const SubtargetFeatureKV *FeatureEntry, const SubtargetFeatureKV *FeatureTable, size_t FeatureTableSize) { for (size_t i = 0; i < FeatureTableSize; ++i) { const SubtargetFeatureKV &FE = FeatureTable[i]; if (FeatureEntry->Value == FE.Value) continue; if (FE.Implies & FeatureEntry->Value) { Bits &= ~FE.Value; ClearImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize); } } } /// getBits - Get feature bits. /// uint32_t SubtargetFeatures::getBits(const SubtargetFeatureKV *CPUTable, size_t CPUTableSize, const SubtargetFeatureKV *FeatureTable, size_t FeatureTableSize) { assert(CPUTable && "missing CPU table"); assert(FeatureTable && "missing features table"); #ifndef NDEBUG for (size_t i = 1; i < CPUTableSize; i++) { assert(strcmp(CPUTable[i - 1].Key, CPUTable[i].Key) < 0 && "CPU table is not sorted"); } for (size_t i = 1; i < FeatureTableSize; i++) { assert(strcmp(FeatureTable[i - 1].Key, FeatureTable[i].Key) < 0 && "CPU features table is not sorted"); } #endif uint32_t Bits = 0; // Resulting bits // Check if help is needed if (Features[0] == "help") Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize); // Find CPU entry const SubtargetFeatureKV *CPUEntry = Find(Features[0], CPUTable, CPUTableSize); // If there is a match if (CPUEntry) { // Set base feature bits Bits = CPUEntry->Value; // Set the feature implied by this CPU feature, if any. for (size_t i = 0; i < FeatureTableSize; ++i) { const SubtargetFeatureKV &FE = FeatureTable[i]; if (CPUEntry->Value & FE.Value) SetImpliedBits(Bits, &FE, FeatureTable, FeatureTableSize); } } else { errs() << "'" << Features[0] << "' is not a recognized processor for this target" << " (ignoring processor)\n"; } // Iterate through each feature for (size_t i = 1; i < Features.size(); i++) { const std::string &Feature = Features[i]; // Check for help if (Feature == "+help") Help(CPUTable, CPUTableSize, FeatureTable, FeatureTableSize); // Find feature in table. const SubtargetFeatureKV *FeatureEntry = Find(StripFlag(Feature), FeatureTable, FeatureTableSize); // If there is a match if (FeatureEntry) { // Enable/disable feature in bits if (isEnabled(Feature)) { Bits |= FeatureEntry->Value; // For each feature that this implies, set it. SetImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize); } else { Bits &= ~FeatureEntry->Value; // For each feature that implies this, clear it. ClearImpliedBits(Bits, FeatureEntry, FeatureTable, FeatureTableSize); } } else { errs() << "'" << Feature << "' is not a recognized feature for this target" << " (ignoring feature)\n"; } } return Bits; } /// Get info pointer void *SubtargetFeatures::getInfo(const SubtargetInfoKV *Table, size_t TableSize) { assert(Table && "missing table"); #ifndef NDEBUG for (size_t i = 1; i < TableSize; i++) { assert(strcmp(Table[i - 1].Key, Table[i].Key) < 0 && "Table is not sorted"); } #endif // Find entry const SubtargetInfoKV *Entry = Find(Features[0], Table, TableSize); if (Entry) { return Entry->Value; } else { errs() << "'" << Features[0] << "' is not a recognized processor for this target" << " (ignoring processor)\n"; return NULL; } } /// print - Print feature string. /// void SubtargetFeatures::print(raw_ostream &OS) const { for (size_t i = 0, e = Features.size(); i != e; ++i) OS << Features[i] << " "; OS << "\n"; } /// dump - Dump feature info. /// void SubtargetFeatures::dump() const { print(dbgs()); } /// getDefaultSubtargetFeatures - Return a string listing the features /// associated with the target triple. /// /// FIXME: This is an inelegant way of specifying the features of a /// subtarget. It would be better if we could encode this information /// into the IR. See <rdar://5972456>. /// void SubtargetFeatures::getDefaultSubtargetFeatures(const std::string &CPU, const Triple& Triple) { setCPU(CPU); if (Triple.getVendor() == Triple::Apple) { if (Triple.getArch() == Triple::ppc) { // powerpc-apple-* AddFeature("altivec"); } else if (Triple.getArch() == Triple::ppc64) { // powerpc64-apple-* AddFeature("64bit"); AddFeature("altivec"); } } }
31.711688
80
0.595053
watchdogdevel
9c6bef073a4ae6954415cbc0a28227b140d74451
5,125
hpp
C++
http_parser/utils/pos_string_view.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
http_parser/utils/pos_string_view.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
http_parser/utils/pos_string_view.hpp
zerhud/std_http_utils
0c37eecc242a93a7bf7d2d7ea8f0eb9f51d77293
[ "MIT" ]
null
null
null
#pragma once /************************************************************************* * Copyright ยฉ 2022 Hudyaev Alexy <hudyaev.alexy@gmail.com> * This file is part of http_parser. * Distributed under the MIT License. * See accompanying file LICENSE (at the root of this repository) *************************************************************************/ #include <span> #include <string_view> namespace http_parser { template<typename Container> class basic_position_string_view { const Container* src=nullptr; std::size_t pos=0; std::size_t len=0; public: using value_type = typename Container::value_type; using std_string_view = std::basic_string_view<typename Container::value_type>; basic_position_string_view() =default ; basic_position_string_view(const Container* s) : basic_position_string_view(s, 0, s->size()) {} basic_position_string_view(const Container* s, std::size_t p, std::size_t l) : src(s) { assign(p, l); } basic_position_string_view(const Container* s, const basic_position_string_view& other) : src(s) , pos(other.pos) , len(other.len) { } basic_position_string_view& operator = (const basic_position_string_view& other) { src = other.src; pos = other.pos; len = other.len; return *this; } template<typename T> basic_position_string_view& operator = (std::basic_string_view<T> sv) { using vt = typename Container::value_type; if(!src) throw std::runtime_error("no strign for assign"); if((vt*)sv.data() < src->data()) throw std::runtime_error("no string correlation"); if(src->size() < (vt*)sv.data() - src->data()) throw std::runtime_error("no string correlation"); pos = (vt*)sv.data() - src->data(); len = sv.size(); return *this; } const Container* underlying_container() const { return src; } bool empty() const { return len == 0; } std::size_t size() const { return len; } void resize(std::size_t nl) { advance_to_end(); if(nl < len) len = nl; } void advance_to_end() { assert(src); len = src->size() - pos; } basic_position_string_view<Container> substr(std::size_t p) const { basic_position_string_view<Container> ret(src); assert( this->pos + p <= src->size() ); ret.pos = this->pos + p; ret.advance_to_end(); return ret; } basic_position_string_view<Container> substr(std::size_t p, std::size_t l) const { basic_position_string_view<Container> ret(src); ret.pos = this->pos + p; ret.len = src->size() <= p + l ? src->size() - p : l; return ret; } basic_position_string_view<Container> following() const { basic_position_string_view<Container> ret(src); ret.pos = this->pos + this->len; ret.advance_to_end(); return ret; } const value_type& operator[](std::size_t i) const { return (*src)[pos + i]; } const value_type& back() const { assert(!empty()); return *(src->data() + pos + len - 1); } const value_type& front() const { assert(!empty()); return *(src->data() + pos); } const value_type* data() const { assert(src != nullptr); assert(pos <= src->size()); return src->data() + pos; } void reset() { pos = 0; len = src->size(); } void assign(const Container* s, const basic_position_string_view& other) { src = s; if(src->size() < other.pos + other.len) throw std::runtime_error("underline string is too small"); pos = other.pos; len = other.len; } void assign(const basic_position_string_view& other) { assign(src, other); } void assign(Container* s, std::size_t p, std::size_t l) { src = s; if(src) assign(p, l); } void assign(std::size_t p, std::size_t l) { if(!src) throw std::runtime_error("cannot assign to positioned string view without source"); if(src->size() <= p && l != 0) throw std::runtime_error("position is too big in positioned string view"); pos = p; std::size_t ctrl = pos + l; len = src->size() <= ctrl ? src->size() - pos : l; } auto span() const { if(!src) return std::span<const value_type>{}; assert( pos < src->size() && pos + len <= src->size() ); return std::span( src->data() + pos, len ); } template<typename C> std::basic_string_view<C> as() const { if(!src) return std::basic_string_view<C>{}; if( pos < src->size() && pos + len <= src->size() ) return std::basic_string_view<C>{ (const C*)src->data() + pos, len }; return std::basic_string_view<C>{ }; } operator std_string_view() const { if(!src) return std_string_view{}; if( pos < src->size() && pos + len <= src->size() ) return std_string_view{src->data() + pos, len}; return std_string_view{}; } }; template<typename Container, typename Char> inline bool operator == (basic_position_string_view<Container> l, std::basic_string_view<Char> r) { if(l.size() != r.size()) return false; for(std::size_t i=0;i<r.size();++i) if(l[i] != (typename Container::value_type)r[i]) return false; return true; } template<typename OStream, typename Container> OStream& operator << (OStream& out, const basic_position_string_view<Container>& v) { return out << v.template as<typename OStream::char_type>(); } } // namespace http_parser
25.371287
97
0.646439
zerhud
9c743e42b45f0d5cb56a2403c1fa6bdb214eddb3
1,086
inl
C++
Library/Sources/Stroika/Foundation/IO/FileSystem/Directory.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
28
2015-09-22T21:43:32.000Z
2022-02-28T01:35:01.000Z
Library/Sources/Stroika/Foundation/IO/FileSystem/Directory.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
98
2015-01-22T03:21:27.000Z
2022-03-02T01:47:00.000Z
Library/Sources/Stroika/Foundation/IO/FileSystem/Directory.inl
SophistSolutions/Stroika
f4e5d84767903a054fba0a6b9c7c4bd1aaefd105
[ "MIT" ]
4
2019-02-21T16:45:25.000Z
2022-02-18T13:40:04.000Z
/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #ifndef _Stroika_Foundation_IO_FileSystem_Directory_inl_ #define _Stroika_Foundation_IO_FileSystem_Directory_inl_ 1 /* ******************************************************************************** ***************************** Implementation Details *************************** ******************************************************************************** */ #include "PathName.h" namespace Stroika::Foundation::IO::FileSystem { DISABLE_COMPILER_MSC_WARNING_START (4996) // class deprecated but still need to implement it template <> inline String Directory::As () const { return FromPath (fFileFullPath_); } template <> inline wstring Directory::As () const { return FromPath (fFileFullPath_).As<wstring> (); } inline SDKString Directory::AsSDKString () const { return FromPath (fFileFullPath_).AsSDKString (); } DISABLE_COMPILER_MSC_WARNING_END (4996) } #endif /*_Stroika_Foundation_IO_FileSystem_Directory_inl_*/
30.166667
96
0.572744
SophistSolutions
9c7663b12324c0bd317f5556dd6bb0116a923d50
6,536
hpp
C++
ql/experimental/credit/syntheticcdo.hpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/credit/syntheticcdo.hpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
null
null
null
ql/experimental/credit/syntheticcdo.hpp
quantosaurosProject/quantLib
84b49913d3940cf80d6de8f70185867373f45e8d
[ "BSD-3-Clause" ]
1
2022-03-29T05:44:27.000Z
2022-03-29T05:44:27.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2008 Roland Lichters This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file syntheticcdo.hpp \brief Synthetic Collateralized Debt Obligation and pricing engines */ #ifndef quantlib_synthetic_cdo_hpp #define quantlib_synthetic_cdo_hpp #include <ql/instrument.hpp> #include <ql/default.hpp> #include <ql/experimental/credit/issuer.hpp> #include <ql/time/schedule.hpp> #include <ql/termstructures/yieldtermstructure.hpp> #include <ql/termstructures/defaulttermstructure.hpp> #include <ql/experimental/credit/basket.hpp> #include <ql/experimental/credit/lossdistribution.hpp> #include <ql/experimental/credit/onefactorcopula.hpp> namespace QuantLib { //! Synthetic Collateralized Debt Obligation /*! The instrument prices a mezzanine CDO tranche with loss given default between attachment point \f$ D_1\f$ and detachment point \f$ D_2 > D_1 \f$. For purchased protection, the instrument value is given by the difference of the protection value \f$ V_1 \f$ and premium value \f$ V_2 \f$, \f[ V = V_1 - V_2. \f] The protection leg is priced as follows: - Build the probability distribution for volume of defaults \f$ L \f$ (before recovery) or Loss Given Default \f$ LGD = (1-r)\,L \f$ at times/dates \f$ t_i, i=1, ..., N\f$ (premium schedule times with intermediate steps) - Determine the expected value \f$ E_i = E_{t_i}\,\left[Pay(LGD)\right] \f$ of the protection payoff \f$ Pay(LGD) \f$ at each time \f$ t_i\f$ where \f[ Pay(L) = min (D_1, LGD) - min (D_2, LGD) = \left\{ \begin{array}{lcl} \displaystyle 0 &;& LGD < D_1 \\ \displaystyle LGD - D_1 &;& D_1 \leq LGD \leq D_2 \\ \displaystyle D_2 - D_1 &;& LGD > D_2 \end{array} \right. \f] - The protection value is then calculated as \f[ V_1 \:=\: \sum_{i=1}^N (E_i - E_{i-1}) \cdot d_i \f] where \f$ d_i\f$ is the discount factor at time/date \f$ t_i \f$ The premium is paid on the protected notional amount, initially \f$ D_2 - D_1. \f$ This notional amount is reduced by the expected protection payments \f$ E_i \f$ at times \f$ t_i, \f$ so that the premium value is calculated as \f[ V_2 = m \, \cdot \sum_{i=1}^N \,(D_2 - D_1 - E_i) \cdot \Delta_{i-1,i}\,d_i \f] where \f$ m \f$ is the premium rate, \f$ \Delta_{i-1, i}\f$ is the day count fraction between date/time \f$ t_{i-1}\f$ and \f$ t_i.\f$ The construction of the portfolio loss distribution \f$ E_i \f$ is based on the probability bucketing algorithm described in <strong> John Hull and Alan White, "Valuation of a CDO and nth to default CDS without Monte Carlo simulation", Journal of Derivatives 12, 2, 2004 </strong> The pricing algorithm allows for varying notional amounts and default termstructures of the underlyings. \ingroup credit \todo Investigate and fix cases \f$ E_{i+1} < E_i. \f$ */ class SyntheticCDO : public Instrument { public: class arguments; class results; class engine; SyntheticCDO (const boost::shared_ptr<Basket> basket, Protection::Side side, const Schedule& schedule, Rate upfrontRate, Rate runningRate, const DayCounter& dayCounter, BusinessDayConvention paymentConvention, const Handle<YieldTermStructure>& yieldTS); boost::shared_ptr<Basket> basket() const { return basket_; } bool isExpired () const; Rate fairPremium() const; Rate fairUpfrontPremium() const; Rate premiumValue () const; Rate protectionValue () const; Real premiumLegNPV() const; Real protectionLegNPV() const; /*! Total outstanding tranche notional, not wiped out */ Real remainingNotional() const; /*! Expected tranche loss for all payment dates */ std::vector<Real> expectedTrancheLoss() const; Size error () const; void setupArguments(PricingEngine::arguments*) const; void fetchResults(const PricingEngine::results*) const; private: void setupExpired() const; boost::shared_ptr<Basket> basket_; Protection::Side side_; Schedule schedule_; Rate upfrontRate_; Rate runningRate_; DayCounter dayCounter_; BusinessDayConvention paymentConvention_; Handle<YieldTermStructure> yieldTS_; mutable Rate fairPremium_; mutable Real premiumValue_; mutable Real protectionValue_; mutable Real upfrontPremiumValue_; mutable Real remainingNotional_; mutable Size error_; mutable std::vector<Real> expectedTrancheLoss_; }; class SyntheticCDO::arguments : public virtual PricingEngine::arguments { public: arguments() : side(Protection::Side(-1)), upfrontRate(Null<Real>()), runningRate(Null<Real>()) {} void validate() const; boost::shared_ptr<Basket> basket; Protection::Side side; Schedule schedule; Rate upfrontRate; Rate runningRate; DayCounter dayCounter; BusinessDayConvention paymentConvention; Handle<YieldTermStructure> yieldTS; }; class SyntheticCDO::results : public Instrument::results { public: void reset(); Real premiumValue; Real protectionValue; Real upfrontPremiumValue; Real remainingNotional; Real xMin, xMax; Size error; std::vector<Real> expectedTrancheLoss; }; } #endif
34.4
83
0.642289
quantosaurosProject
9c76667354ac64801a24f99037aacd7de40e0152
7,193
cpp
C++
extra/news/src/apk/gtagml/gtagml/gtagml/output/gtagml-output-event-handler.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/output/gtagml-output-event-handler.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
extra/news/src/apk/gtagml/gtagml/gtagml/output/gtagml-output-event-handler.cpp
scignscape/PGVM
e24f46cdf657a8bdb990c7883c6bd3d0a0c9cff0
[ "BSL-1.0" ]
null
null
null
// Copyright Nathaniel Christen 2019. // 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 "gtagml-output-event-handler.h" #include "kernel/document/gtagml-document.h" #include "kernel/graph/gtagml-node.h" #include "tile/gtagml-token.h" #include "kernel/output/gtagml-output-bundle.h" #include "tile/gtagml-tile.h" #include "tile/gtagml-attribute-tile.h" #include "tag-command/gtagml-tag-command.h" #include "tile/gtagml-paralex-tile.h" #include "annotation/gtagml-annotation-tile.h" //?#include "ngml-htxn/ngml-htxn-node.h" #include <QFile> #include <QFileInfo> #include "kans.h" USING_KANS(GTagML) GTagML_Output_Event_Handler::GTagML_Output_Event_Handler() { } caon_ptr<GTagML_Tag_Command_Callback> GTagML_Output_Event_Handler::check_command_callback(const GTagML_Output_Bundle& b) { if(caon_ptr<GTagML_Tag_Command> ntc = b.node->GTagML_tag_command()) { return check_command_callback(ntc); } } caon_ptr<GTagML_Tag_Command_Callback> GTagML_Output_Event_Handler::check_command_callback(caon_ptr<GTagML_Tag_Command> ntc) { CAON_PTR_DEBUG(GTagML_Tag_Command ,ntc) return caon_ptr<GTagML_Tag_Command_Callback>( nullptr ); } void GTagML_Output_Event_Handler::generate_root(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Root> nr) { } caon_ptr<GTagML_Tag_Command> GTagML_Output_Event_Handler::generate_tag_command_entry(const GTagML_Output_Bundle& b) { caon_ptr<GTagML_Tag_Command_Callback> cb = check_command_callback(b); if(caon_ptr<GTagML_Tag_Command> ntc = b.node->GTagML_tag_command()) { CAON_PTR_DEBUG(GTagML_Tag_Command ,ntc) generate_tag_command_entry(b.with_callback(cb), ntc); // // ? wha ? if(ntc->flags.is_closed) { return ntc; } } return caon_ptr<GTagML_Tag_Command>( nullptr ); } void GTagML_Output_Event_Handler::generate_tag_command_entry(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tag_Command> ntc) { } void GTagML_Output_Event_Handler::generate_tag_command_leave(const GTagML_Output_Bundle& b) { if(caon_ptr<GTagML_Tag_Command> ntc = b.node->GTagML_tag_command()) { generate_tag_command_leave(b, ntc); check_generate_whitespace(b, ntc); } } void GTagML_Output_Event_Handler::tag_command_annotation(caon_ptr<GTagML_Tile> nt, caon_ptr<tNode> node) { if(caon_ptr<GTagML_Annotation_Tile> tile = node->GTagML_annotation_tile()) tag_command_annotation(nt, tile); } void GTagML_Output_Event_Handler::tag_command_annotation(caon_ptr<GTagML_Tile> nt, caon_ptr<GTagML_Annotation_Tile> tile) { } void GTagML_Output_Event_Handler::generate_tag_command_auto_leave(const GTagML_Output_Bundle& b) { if(caon_ptr<GTagML_Tag_Command> ntc = b.node->GTagML_tag_command()) { generate_tag_command_auto_leave(b, ntc); check_generate_whitespace(b, ntc); } } void GTagML_Output_Event_Handler::generate_tag_command_leave(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tag_Command> ntc) { } void GTagML_Output_Event_Handler::generate_tag_command_auto_leave(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tag_Command> ntc) { generate_tag_command_leave(b, ntc); } void GTagML_Output_Event_Handler::generate_tag_body_leave(const GTagML_Output_Bundle& b) { if(caon_ptr<GTagML_Tag_Command> ntc = b.node->GTagML_tag_command()) { generate_tag_body_leave(b, ntc); } } void GTagML_Output_Event_Handler::generate_tag_command_entry_connector(const GTagML_Output_Bundle& b) { } void GTagML_Output_Event_Handler::generate_tag_body_leave(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tag_Command> ntc) { } void GTagML_Output_Event_Handler::generate_tile(const GTagML_Output_Bundle& b) { if(caon_ptr<GTagML_Tile> tile = b.node->GTagML_tile()) { generate_tile(b, tile); } else if(caon_ptr<GTagML_Attribute_Tile> tile = b.node->GTagML_attribute_tile()) { generate_tile(b, tile); } else if(caon_ptr<GTagML_Paralex_Tile> tile = b.node->GTagML_paralex_tile()) { generate_tile(b, tile); } } void GTagML_Output_Event_Handler::check_update_index(const GTagML_Output_Bundle& b, GTagML_Tile& tile) { b.index += tile.raw_text().length(); } //void GTagML_Output_Event_Handler::generate_tile_via_htxn(const GTagML_Output_Bundle& b, GTagML_HTXN_Node& nhn) //{ //} //void GTagML_Output_Event_Handler::generate_attribute_tile_via_htxn(const GTagML_Output_Bundle& b, GTagML_HTXN_Node& nhn) //{ //} //void GTagML_Output_Event_Handler::generate_parelex_tile_via_htxn(const GTagML_Output_Bundle& b, GTagML_HTXN_Node& nhn) //{ //} //void GTagML_Output_Event_Handler::generate_annotation_tile_via_htxn(const GTagML_Output_Bundle& b, GTagML_HTXN_Node& nhn) //{ //} void GTagML_Output_Event_Handler::generate_tile_via_gh(const GTagML_Output_Bundle& b, GH_Prenode& ghn) { } void GTagML_Output_Event_Handler::generate_tile(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tile> tile) { CAON_PTR_DEBUG(GTagML_Tile ,tile) if(GH_Prenode* ghp = tile->prenode()) { generate_tile_via_gh(b, *ghp); // // here? //? check_generate_whitespace(b, *ghn); check_generate_whitespace(b, tile); return; } QString rt = tile->raw_text(); if(!rt.startsWith("*:")) { b.qts << tile->raw_text(); check_update_index(b, *tile); } check_generate_whitespace(b, tile); } void GTagML_Output_Event_Handler::generate_tile(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Attribute_Tile> tile) { tile->write_html(b.qts); } void GTagML_Output_Event_Handler::generate_tile(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Annotation_Tile> tile) { } void GTagML_Output_Event_Handler::handle_annotation(caon_ptr<GTagML_Tile> tile, caon_ptr<GTagML_Annotation_Tile> atile) { } void GTagML_Output_Event_Handler::handle_annotation(caon_ptr<GTagML_Tile> tile, caon_ptr<tNode> node) { if(caon_ptr<GTagML_Annotation_Tile> atile = node->GTagML_annotation_tile()) { handle_annotation(tile, atile); } } void GTagML_Output_Event_Handler::generate_tile(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Paralex_Tile> tile) { tile->write_html(b.qts); check_generate_whitespace(b, tile); } //void GTagML_Output_Event_Handler::check_generate_whitespace(const GTagML_Output_Bundle& b, GTagML_HTXN_Node& nhn) //{ // nhn.write_whitespace(b.qts); //} void GTagML_Output_Event_Handler::check_generate_whitespace(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tag_Command> ntc) { CAON_PTR_DEBUG(GTagML_Tag_Command ,ntc) ntc->write_whitespace(b.qts); //? check_update_index_after_whitespace(b, ntc); } void GTagML_Output_Event_Handler::check_generate_whitespace(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Paralex_Tile> tile) { tile->write_whitespace(b.qts); } void GTagML_Output_Event_Handler::check_generate_whitespace(const GTagML_Output_Bundle& b, caon_ptr<GTagML_Tile> tile) { tile->write_whitespace(b.qts); check_update_index_after_whitespace(b, *tile); } void GTagML_Output_Event_Handler::check_update_index_after_whitespace(const GTagML_Output_Bundle& b, GTagML_Tile& tile) { b.index += tile.ws().get_length(); } void GTagML_Output_Event_Handler::check_update_index_after_whitespace(const GTagML_Output_Bundle& b, GTagML_Tag_Command& ntc) { b.index += ntc.ws().get_length(); }
26.347985
130
0.791464
scignscape
9c773dca787edd1cfd75e19ea8df58f0e778fe09
19,070
cpp
C++
tier0/dbg.cpp
DannyParker0001/Kisak-Strike
99ed85927336fe3aff2efd9b9382b2b32eb1d05d
[ "Unlicense" ]
252
2020-12-16T15:34:43.000Z
2022-03-31T23:21:37.000Z
cstrike15_src/tier0/dbg.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
23
2020-12-20T18:02:54.000Z
2022-03-28T16:58:32.000Z
cstrike15_src/tier0/dbg.cpp
bahadiraraz/Counter-Strike-Global-Offensive
9a0534100cb98ffa1cf0c32e138f0e7971e910d3
[ "MIT" ]
42
2020-12-19T04:32:33.000Z
2022-03-30T06:00:28.000Z
//===== Copyright (c) 1996-2005, Valve Corporation, All rights reserved. ======// // // Purpose: // // $NoKeywords: $ // //===========================================================================// #include "tier0/platform.h" #if defined( PLATFORM_WINDOWS_PC ) #define WIN_32_LEAN_AND_MEAN #include <windows.h> // Currently needed for IsBadReadPtr and IsBadWritePtr #pragma comment(lib,"user32.lib") // For MessageBox #endif #include "tier0/minidump.h" #include "tier0/stacktools.h" #include "tier0/etwprof.h" #include <assert.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include "color.h" #include "tier0/dbg.h" #include "tier0/threadtools.h" #include "tier0/icommandline.h" #include "tier0/vprof.h" #include <math.h> #if defined( _X360 ) #include "xbox/xbox_console.h" #endif #ifndef STEAM #define PvRealloc realloc #define PvAlloc malloc #endif // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" #if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) #pragma optimize( "g", off ) //variable argument functions seem to screw up stack walking unless this optimization is disabled // Disable this warning: dbg.cpp(479): warning C4748: /GS can not protect parameters and local variables from local buffer overrun because optimizations are disabled in function #pragma warning( disable : 4748 ) #endif DEFINE_LOGGING_CHANNEL_NO_TAGS( LOG_LOADING, "LOADING" ); //----------------------------------------------------------------------------- // Stack attachment management //----------------------------------------------------------------------------- #if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) static bool s_bCallStacksWithAllWarnings = false; //if true, attach a call stack to every SPEW_WARNING message. Warning()/DevWarning()/... static int s_iWarningMaxCallStackLength = 5; #define AutomaticWarningCallStackLength() (s_bCallStacksWithAllWarnings ? s_iWarningMaxCallStackLength : 0) void _Warning_AlwaysSpewCallStack_Enable( bool bEnable ) { s_bCallStacksWithAllWarnings = bEnable; } void _Warning_AlwaysSpewCallStack_Length( int iMaxCallStackLength ) { s_iWarningMaxCallStackLength = iMaxCallStackLength; } static bool s_bCallStacksWithAllErrors = false; //if true, attach a call stack to every SPEW_ERROR message. Mostly just Error() static int s_iErrorMaxCallStackLength = 20; //default to higher output with an error since we're quitting anyways #define AutomaticErrorCallStackLength() (s_bCallStacksWithAllErrors ? s_iErrorMaxCallStackLength : 0) void _Error_AlwaysSpewCallStack_Enable( bool bEnable ) { s_bCallStacksWithAllErrors = bEnable; } void _Error_AlwaysSpewCallStack_Length( int iMaxCallStackLength ) { s_iErrorMaxCallStackLength = iMaxCallStackLength; } #else //#if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) #define AutomaticWarningCallStackLength() 0 #define AutomaticErrorCallStackLength() 0 void _Warning_AlwaysSpewCallStack_Enable( bool bEnable ) { } void _Warning_AlwaysSpewCallStack_Length( int iMaxCallStackLength ) { } void _Error_AlwaysSpewCallStack_Enable( bool bEnable ) { } void _Error_AlwaysSpewCallStack_Length( int iMaxCallStackLength ) { } #endif //#if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) // Skip forward past the directory static const char *SkipToFname( const tchar* pFile ) { if ( pFile == NULL ) return "unknown"; const tchar* pSlash = _tcsrchr( pFile, '\\' ); const tchar* pSlash2 = _tcsrchr( pFile, '/' ); if (pSlash < pSlash2) pSlash = pSlash2; return pSlash ? pSlash + 1: pFile; } void _ExitOnFatalAssert( const tchar* pFile, int line ) { Log_Msg( LOG_ASSERT, _T("Fatal assert failed: %s, line %d. Application exiting.\n"), pFile, line ); // only write out minidumps if we're not in the debugger if ( !Plat_IsInDebugSession() ) { WriteMiniDump(); } Log_Msg( LOG_DEVELOPER, _T("_ExitOnFatalAssert\n") ); Plat_ExitProcess( EXIT_FAILURE ); } //----------------------------------------------------------------------------- // Templates to assist in validating pointers: //----------------------------------------------------------------------------- PLATFORM_INTERFACE void _AssertValidReadPtr( void* ptr, int count/* = 1*/ ) { #if defined( _WIN32 ) && !defined( _X360 ) Assert( !IsBadReadPtr( ptr, count ) ); #else Assert( !count || ptr ); #endif } PLATFORM_INTERFACE void _AssertValidWritePtr( void* ptr, int count/* = 1*/ ) { #if defined( _WIN32 ) && !defined( _X360 ) Assert( !IsBadWritePtr( ptr, count ) ); #else Assert( !count || ptr ); #endif } PLATFORM_INTERFACE void _AssertValidReadWritePtr( void* ptr, int count/* = 1*/ ) { #if defined( _WIN32 ) && !defined( _X360 ) Assert(!( IsBadWritePtr(ptr, count) || IsBadReadPtr(ptr,count))); #else Assert( !count || ptr ); #endif } PLATFORM_INTERFACE void _AssertValidStringPtr( const tchar* ptr, int maxchar/* = 0xFFFFFF */ ) { #if defined( _WIN32 ) && !defined( _X360 ) #ifdef TCHAR_IS_CHAR Assert( !IsBadStringPtr( ptr, maxchar ) ); #else Assert( !IsBadStringPtrW( ptr, maxchar ) ); #endif #else Assert( ptr ); #endif } PLATFORM_INTERFACE void AssertValidWStringPtr( const wchar_t* ptr, int maxchar/* = 0xFFFFFF */ ) { #if defined( _WIN32 ) && !defined( _X360 ) Assert( !IsBadStringPtrW( ptr, maxchar ) ); #else Assert( ptr ); #endif } void AppendCallStackToLogMessage( tchar *formattedMessage, int iMessageLength, int iAppendCallStackLength ) { #if defined( ENABLE_RUNTIME_STACK_TRANSLATION ) # if defined( TCHAR_IS_CHAR ) //I'm horrible with unicode and I don't plan on testing this with wide characters just yet if( iAppendCallStackLength > 0 ) { int iExistingMessageLength = (int)strlen( formattedMessage ); //no V_strlen in tier 0, plus we're only compiling this for windows and 360. Seems safe formattedMessage += iExistingMessageLength; iMessageLength -= iExistingMessageLength; if( iMessageLength <= 32 ) return; //no room for anything useful //append directly to the spew message if( (iExistingMessageLength > 0) && (formattedMessage[-1] == '\n') ) { --formattedMessage; ++iMessageLength; } //append preface int iAppendedLength = _snprintf( formattedMessage, iMessageLength, _T("\nCall Stack:\n\t") ); void **CallStackBuffer = (void **)stackalloc( iAppendCallStackLength * sizeof( void * ) ); int iCount = GetCallStack( CallStackBuffer, iAppendCallStackLength, 2 ); if( TranslateStackInfo( CallStackBuffer, iCount, formattedMessage + iAppendedLength, iMessageLength - iAppendedLength, _T("\n\t") ) == 0 ) { //failure formattedMessage[0] = '\0'; //this is pointing at where we wrote "\nCall Stack:\n\t" } else { iAppendedLength += (int)strlen( formattedMessage + iAppendedLength ); //no V_strlen in tier 0, plus we're only compiling this for windows and 360. Seems safe if( iAppendedLength < iMessageLength ) { formattedMessage[iAppendedLength] = '\n'; //Add another newline. ++iAppendedLength; formattedMessage[iAppendedLength] = '\0'; } } } # else AssertMsg( false, "Fixme" ); # endif #endif } // Forward declare for internal use only. CLoggingSystem *GetGlobalLoggingSystem(); #define Log_LegacyHelperColor_Stack( Channel, Severity, Color, MessageFormat, AppendCallStackLength ) \ do \ { \ CLoggingSystem *pLoggingSystem = GetGlobalLoggingSystem(); \ if ( pLoggingSystem->IsChannelEnabled( Channel, Severity ) ) \ { \ tchar formattedMessage[MAX_LOGGING_MESSAGE_LENGTH]; \ va_list args; \ va_start( args, MessageFormat ); \ Tier0Internal_vsntprintf( formattedMessage, MAX_LOGGING_MESSAGE_LENGTH, MessageFormat, args ); \ va_end( args ); \ AppendCallStackToLogMessage( formattedMessage, MAX_LOGGING_MESSAGE_LENGTH, AppendCallStackLength ); \ pLoggingSystem->LogDirect( Channel, Severity, Color, formattedMessage ); \ } \ } while( 0 ) #define Log_LegacyHelperColor( Channel, Severity, Color, MessageFormat ) Log_LegacyHelperColor_Stack( Channel, Severity, Color, MessageFormat, 0 ) #define Log_LegacyHelper_Stack( Channel, Severity, MessageFormat, AppendCallStackLength ) Log_LegacyHelperColor_Stack( Channel, Severity, pLoggingSystem->GetChannelColor( Channel ), MessageFormat, AppendCallStackLength ) #define Log_LegacyHelper( Channel, Severity, MessageFormat ) Log_LegacyHelperColor( Channel, Severity, pLoggingSystem->GetChannelColor( Channel ), MessageFormat ) #if !defined( DBGFLAG_STRINGS_STRIP ) void Msg( const tchar* pMsgFormat, ... ) { Log_LegacyHelper( LOG_GENERAL, LS_MESSAGE, pMsgFormat ); } void Warning( const tchar *pMsgFormat, ... ) { Log_LegacyHelper_Stack( LOG_GENERAL, LS_WARNING, pMsgFormat, AutomaticWarningCallStackLength() ); } void Warning_SpewCallStack( int iMaxCallStackLength, const tchar *pMsgFormat, ... ) { Log_LegacyHelper_Stack( LOG_GENERAL, LS_WARNING, pMsgFormat, iMaxCallStackLength ); } #endif // !DBGFLAG_STRINGS_STRIP void Error( const tchar *pMsgFormat, ... ) { #if !defined( DBGFLAG_STRINGS_STRIP ) Log_LegacyHelper_Stack( LOG_GENERAL, LS_ERROR, pMsgFormat, AutomaticErrorCallStackLength() ); // Many places that call Error assume that execution will not continue afterwards so it // is important to exit here. The function prototype promises that this will happen. Plat_ExitProcess( 100 ); #endif } void Error_SpewCallStack( int iMaxCallStackLength, const tchar *pMsgFormat, ... ) { #if !defined( DBGFLAG_STRINGS_STRIP ) Log_LegacyHelper_Stack( LOG_GENERAL, LS_ERROR, pMsgFormat, iMaxCallStackLength ); // Many places that call Error_SpewCallStack assume that execution will not continue afterwards so it // is important to exit here. The function prototype promises that this will happen. Plat_ExitProcess( 100 ); #endif } #if !defined( DBGFLAG_STRINGS_STRIP ) //----------------------------------------------------------------------------- // A couple of super-common dynamic spew messages, here for convenience // These looked at the "developer" group, print if it's level 1 or higher //----------------------------------------------------------------------------- void DevMsg( int level, const tchar* pMsgFormat, ... ) { LoggingChannelID_t channel = level >= 2 ? LOG_DEVELOPER_VERBOSE : LOG_DEVELOPER; Log_LegacyHelper( channel, LS_MESSAGE, pMsgFormat ); } void DevWarning( int level, const tchar *pMsgFormat, ... ) { LoggingChannelID_t channel = level >= 2 ? LOG_DEVELOPER_VERBOSE : LOG_DEVELOPER; Log_LegacyHelper( channel, LS_WARNING, pMsgFormat ); } void DevMsg( const tchar *pMsgFormat, ... ) { Log_LegacyHelper( LOG_DEVELOPER, LS_MESSAGE, pMsgFormat ); } void DevWarning( const tchar *pMsgFormat, ... ) { Log_LegacyHelper( LOG_DEVELOPER, LS_WARNING, pMsgFormat ); } void ConColorMsg( const Color& clr, const tchar* pMsgFormat, ... ) { Log_LegacyHelperColor( LOG_CONSOLE, LS_MESSAGE, clr, pMsgFormat ); } void ConMsg( const tchar *pMsgFormat, ... ) { Log_LegacyHelper( LOG_CONSOLE, LS_MESSAGE, pMsgFormat ); } void ConDMsg( const tchar *pMsgFormat, ... ) { Log_LegacyHelper( LOG_DEVELOPER_CONSOLE, LS_MESSAGE, pMsgFormat ); } #endif // !DBGFLAG_STRINGS_STRIP // If we don't have a function from math.h, then it doesn't link certain floating-point // functions in and printfs with %f cause runtime errors in the C libraries. PLATFORM_INTERFACE float CrackSmokingCompiler( float a ) { return (float)fabs( a ); } void* Plat_SimpleLog( const tchar* file, int line ) { FILE* f = _tfopen( _T("simple.log"), _T("at+") ); _ftprintf( f, _T("%s:%i\n"), file, line ); fclose( f ); return NULL; } #if !defined( DBGFLAG_STRINGS_STRIP ) //----------------------------------------------------------------------------- // Purpose: For debugging startup times, etc. // Input : *fmt - // ... - //----------------------------------------------------------------------------- void COM_TimestampedLog( char const *fmt, ... ) { static float s_LastStamp = 0.0; static bool s_bShouldLog = false; static bool s_bShouldLogToConsole = false; static bool s_bShouldLogToETW = false; static bool s_bChecked = false; static bool s_bFirstWrite = false; if ( !s_bChecked ) { s_bShouldLog = ( CommandLine()->CheckParm( "-profile" ) ) ? true : false; s_bShouldLogToConsole = ( CommandLine()->ParmValue( "-profile", 0.0f ) != 0.0f ) ? true : false; s_bShouldLogToETW = ( CommandLine()->CheckParm( "-etwprofile" ) ) ? true : false; if ( s_bShouldLogToETW ) { s_bShouldLog = true; } s_bChecked = true; } if ( !s_bShouldLog ) { return; } char string[1024]; va_list argptr; va_start( argptr, fmt ); Tier0Internal_vsnprintf( string, sizeof( string ), fmt, argptr ); va_end( argptr ); float curStamp = Plat_FloatTime(); #if defined( _X360 ) XBX_rTimeStampLog( curStamp, string ); #elif defined( _PS3 ) Log_Warning( LOG_LOADING, "%8.4f / %8.4f: %s\n", curStamp, curStamp - s_LastStamp, string ); #endif if ( IsPC() ) { // If ETW profiling is enabled then do it only. if ( s_bShouldLogToETW ) { ETWMark( string ); } else { if ( !s_bFirstWrite ) { unlink( "timestamped.log" ); s_bFirstWrite = true; } FILE* fp = fopen( "timestamped.log", "at+" ); fprintf( fp, "%8.4f / %8.4f: %s\n", curStamp, curStamp - s_LastStamp, string ); fclose( fp ); if ( s_bShouldLogToConsole ) { Msg( "%8.4f / %8.4f: %s\n", curStamp, curStamp - s_LastStamp, string ); } } } s_LastStamp = curStamp; } #endif // !DBGFLAG_STRINGS_STRIP static AssertFailedNotifyFunc_t s_AssertFailedNotifyFunc = NULL; //----------------------------------------------------------------------------- // Sets an assert failed notify handler //----------------------------------------------------------------------------- void SetAssertFailedNotifyFunc( AssertFailedNotifyFunc_t func ) { s_AssertFailedNotifyFunc = func; } //----------------------------------------------------------------------------- // Calls the assert failed notify handler if one has been set //----------------------------------------------------------------------------- void CallAssertFailedNotifyFunc( const char *pchFile, int nLine, const char *pchMessage ) { if ( s_AssertFailedNotifyFunc ) s_AssertFailedNotifyFunc( pchFile, nLine, pchMessage ); } #ifdef IS_WINDOWS_PC class CHardwareBreakPoint { public: enum EOpCode { BRK_SET = 0, BRK_UNSET, }; CHardwareBreakPoint() { m_eOperation = BRK_SET; m_pvAddress = 0; m_hThread = 0; m_hThreadEvent = 0; m_nRegister = 0; m_bSuccess = false; } const void *m_pvAddress; HANDLE m_hThread; EHardwareBreakpointType m_eType; EHardwareBreakpointSize m_eSize; HANDLE m_hThreadEvent; int m_nRegister; EOpCode m_eOperation; bool m_bSuccess; static void SetBits( DWORD_PTR& dw, int lowBit, int bits, int newValue ); static DWORD WINAPI ThreadProc( LPVOID lpParameter ); }; void CHardwareBreakPoint::SetBits( DWORD_PTR& dw, int lowBit, int bits, int newValue ) { DWORD_PTR mask = (1 << bits) - 1; dw = (dw & ~(mask << lowBit)) | (newValue << lowBit); } DWORD WINAPI CHardwareBreakPoint::ThreadProc( LPVOID lpParameter ) { CHardwareBreakPoint *h = reinterpret_cast< CHardwareBreakPoint * >( lpParameter ); SuspendThread( h->m_hThread ); // Get current context CONTEXT ct = {0}; ct.ContextFlags = CONTEXT_DEBUG_REGISTERS; GetThreadContext(h->m_hThread,&ct); int FlagBit = 0; bool Dr0Busy = false; bool Dr1Busy = false; bool Dr2Busy = false; bool Dr3Busy = false; if (ct.Dr7 & 1) Dr0Busy = true; if (ct.Dr7 & 4) Dr1Busy = true; if (ct.Dr7 & 16) Dr2Busy = true; if (ct.Dr7 & 64) Dr3Busy = true; if ( h->m_eOperation == CHardwareBreakPoint::BRK_UNSET ) { // Remove if (h->m_nRegister == 0) { FlagBit = 0; ct.Dr0 = 0; Dr0Busy = false; } if (h->m_nRegister == 1) { FlagBit = 2; ct.Dr1 = 0; Dr1Busy = false; } if (h->m_nRegister == 2) { FlagBit = 4; ct.Dr2 = 0; Dr2Busy = false; } if (h->m_nRegister == 3) { FlagBit = 6; ct.Dr3 = 0; Dr3Busy = false; } ct.Dr7 &= ~(1 << FlagBit); } else { if (!Dr0Busy) { h->m_nRegister = 0; ct.Dr0 = (DWORD_PTR)h->m_pvAddress; Dr0Busy = true; } else if (!Dr1Busy) { h->m_nRegister = 1; ct.Dr1 = (DWORD_PTR)h->m_pvAddress; Dr1Busy = true; } else if (!Dr2Busy) { h->m_nRegister = 2; ct.Dr2 = (DWORD_PTR)h->m_pvAddress; Dr2Busy = true; } else if (!Dr3Busy) { h->m_nRegister = 3; ct.Dr3 = (DWORD_PTR)h->m_pvAddress; Dr3Busy = true; } else { h->m_bSuccess = false; ResumeThread(h->m_hThread); SetEvent(h->m_hThreadEvent); return 0; } ct.Dr6 = 0; int st = 0; if (h->m_eType == BREAKPOINT_EXECUTE) st = 0; if (h->m_eType == BREAKPOINT_READWRITE) st = 3; if (h->m_eType == BREAKPOINT_WRITE) st = 1; int le = 0; if (h->m_eSize == BREAKPOINT_SIZE_1) le = 0; if (h->m_eSize == BREAKPOINT_SIZE_2) le = 1; if (h->m_eSize == BREAKPOINT_SIZE_4) le = 3; if (h->m_eSize == BREAKPOINT_SIZE_8) le = 2; SetBits( ct.Dr7, 16 + h->m_nRegister*4, 2, st ); SetBits( ct.Dr7, 18 + h->m_nRegister*4, 2, le ); SetBits( ct.Dr7, h->m_nRegister*2,1,1); } ct.ContextFlags = CONTEXT_DEBUG_REGISTERS; SetThreadContext(h->m_hThread,&ct); ResumeThread( h->m_hThread ); h->m_bSuccess = true; SetEvent( h->m_hThreadEvent ); return 0; } HardwareBreakpointHandle_t SetHardwareBreakpoint( EHardwareBreakpointType eType, EHardwareBreakpointSize eSize, const void *pvLocation ) { CHardwareBreakPoint *h = new CHardwareBreakPoint(); h->m_pvAddress = pvLocation; h->m_eSize = eSize; h->m_eType = eType; HANDLE hThread = GetCurrentThread(); h->m_hThread = hThread; if ( hThread == GetCurrentThread() ) { DWORD nThreadId = GetCurrentThreadId(); h->m_hThread = OpenThread( THREAD_ALL_ACCESS, 0, nThreadId ); } h->m_hThreadEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); h->m_eOperation = CHardwareBreakPoint::BRK_SET; // Set Break CreateThread( 0, 0, CHardwareBreakPoint::ThreadProc, (LPVOID)h, 0, 0 ); WaitForSingleObject( h->m_hThreadEvent,INFINITE ); CloseHandle( h->m_hThreadEvent ); h->m_hThreadEvent = 0; if ( hThread == GetCurrentThread() ) { CloseHandle( h->m_hThread ); } h->m_hThread = hThread; if ( !h->m_bSuccess ) { delete h; return (HardwareBreakpointHandle_t)0; } return (HardwareBreakpointHandle_t)h; } bool ClearHardwareBreakpoint( HardwareBreakpointHandle_t handle ) { CHardwareBreakPoint *h = reinterpret_cast< CHardwareBreakPoint* >( handle ); if ( !h ) { return false; } bool bOpened = false; if ( h->m_hThread == GetCurrentThread() ) { DWORD nThreadId = GetCurrentThreadId(); h->m_hThread = OpenThread( THREAD_ALL_ACCESS, 0, nThreadId ); bOpened = true; } h->m_hThreadEvent = CreateEvent( NULL, FALSE, FALSE, NULL ); h->m_eOperation = CHardwareBreakPoint::BRK_UNSET; // Remove Break CreateThread( 0,0,CHardwareBreakPoint::ThreadProc, (LPVOID)h, 0,0 ); WaitForSingleObject( h->m_hThreadEvent, INFINITE ); CloseHandle( h->m_hThreadEvent ); h->m_hThreadEvent = 0; if ( bOpened ) { CloseHandle( h->m_hThread ); } delete h; return true; } #endif // IS_WINDOWS_PC
27.75837
220
0.675564
DannyParker0001
9c78bd8d14dbe2591198501573c86303cded5b80
522
hpp
C++
clove/components/systems/ai/include/Clove/AI/Selector.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
null
null
null
clove/components/systems/ai/include/Clove/AI/Selector.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
null
null
null
clove/components/systems/ai/include/Clove/AI/Selector.hpp
mondoo/Clove
3989dc3fea0d886a69005c1e0bb4396501f336f2
[ "MIT" ]
null
null
null
#pragma once #include "Clove/AI/Composite.hpp" #include <Clove/DeltaTime.hpp> namespace clove { class Selector : public Composite { //FUNCTIONS public: Selector(); Selector(Selector const &other) = delete; Selector(Selector &&other) noexcept; Selector &operator=( Selector const &other) = delete; Selector &operator=(Selector &&other) noexcept; ~Selector(); Status activate(DeltaTime const deltaTime, Blackboard &blackboard) override; }; }
22.695652
84
0.643678
mondoo
9c79f4915ffb3c45110427ac487ebf9044face56
6,641
hpp
C++
recipes-coinutils/coinutils/coinutils/src/CoinPresolvePsdebug.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-coinutils/coinutils/coinutils/src/CoinPresolvePsdebug.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
recipes-coinutils/coinutils/coinutils/src/CoinPresolvePsdebug.hpp
Justin790126/meta-coinor
0180187c583b3a6fd0a8dac7c85ac1bd89bf8cc9
[ "MIT" ]
null
null
null
// Copyright (C) 2002, International Business Machines // Corporation and others. All Rights Reserved. // This code is licensed under the terms of the Eclipse Public License (EPL). #ifndef CoinPresolvePsdebug_H #define CoinPresolvePsdebug_H /* The current idea of the relation between PRESOLVE_DEBUG and PRESOLVE_CONSISTENCY is that PRESOLVE_CONSISTENCY triggers the consistency checks and PRESOLVE_DEBUG triggers consistency checks and output. This isn't always true in the code, but that's the goal. Really, the whole compile-time scheme should be replaced with something more user-friendly (control variables that can be changed during the run). Also floating about are PRESOLVE_SUMMARY and COIN_PRESOLVE_TUNING. -- lh, 111208 -- */ /*! \defgroup PresolveDebugFunctions Presolve Debug Functions These functions implement consistency checks on data structures involved in presolve and postsolve and on the components of the lp solution. To use these functions, include CoinPresolvePsdebug.hpp in your file and define the compile-time constants PRESOLVE_SUMMARY, PRESOLVE_DEBUG, and PRESOLVE_CONSISTENCY. A value is needed (<i>i.e.</i>, PRESOLVE_DEBUG=1). In a few places, higher values will get you a bit more output. ******** Define the symbols PRESOLVE_DEBUG and PRESOLVE_CONSISTENCY on the configure command line (use ADD_CXXFLAGS), in a Makefile, or similar and do a full rebuild (including any presolve driver code). If the symbols are not consistently nonzero across *all* presolve code, you'll get something between garbage and a core dump! Debugging adds messages to CoinMessage and allocates and maintains arrays that hold debug information. That said, given that you've configured and built with PRESOLVE_DEBUG and PRESOLVE_CONSISTENCY nonzero everywhere, it's safe to adjust PRESOLVE_DEBUG to values in the range 1..n in individual files to increase or decrease the amount of output. The suggested approach for PRESOLVE_DEBUG is to define it to 1 in the build and then increase it in individual presolve code files to get more detail. ******** */ //@{ /*! \relates CoinPresolveMatrix \brief Check column-major and/or row-major matrices for duplicate entries in the major vectors. By default, scans both the column- and row-major matrices. Set doCol (doRow) to false to suppress the column (row) scan. */ void presolve_no_dups(const CoinPresolveMatrix *preObj, bool doCol = true, bool doRow = true); /*! \relates CoinPresolveMatrix \brief Check the links which track storage order for major vectors in the bulk storage area. By default, scans both the column- and row-major matrix. Set doCol = false to suppress the column-major scan. Set doRow = false to suppres the row-major scan. */ void presolve_links_ok(const CoinPresolveMatrix *preObj, bool doCol = true, bool doRow = true); /*! \relates CoinPresolveMatrix \brief Check for explicit zeros in the column- and/or row-major matrices. By default, scans both the column- and row-major matrices. Set doCol (doRow) to false to suppress the column (row) scan. */ void presolve_no_zeros(const CoinPresolveMatrix *preObj, bool doCol = true, bool doRow = true); /*! \relates CoinPresolveMatrix \brief Checks for equivalence of the column- and row-major matrices. Normally the routine will test for coefficient presence and value. Set \p chkvals to false to suppress the check for equal value. */ void presolve_consistent(const CoinPresolveMatrix *preObj, bool chkvals = true); /*! \relates CoinPostsolveMatrix \brief Checks that column threads agree with column lengths */ void presolve_check_threads(const CoinPostsolveMatrix *obj); /*! \relates CoinPostsolveMatrix \brief Checks the free list Scans the thread of free locations in the bulk store and checks that all entries are reasonable (0 <= index < bulk0_). If chkElemCnt is true, it also checks that the total number of entries in the matrix plus the locations on the free list total to the size of the bulk store. Postsolve routines do not maintain an accurate element count, but this is useful for checking a newly constructed postsolve matrix. */ void presolve_check_free_list(const CoinPostsolveMatrix *obj, bool chkElemCnt = false); /*! \relates CoinPostsolveMatrix \brief Check stored reduced costs for accuracy and consistency with variable status. The routine will check the value of the reduced costs for architectural variables (CoinPrePostsolveMatrix::rcosts_). It performs an accuracy check by recalculating the reduced cost from scratch. It will also check the value for consistency with the status information in CoinPrePostsolveMatrix::colstat_. */ void presolve_check_reduced_costs(const CoinPostsolveMatrix *obj); /*! \relates CoinPostsolveMatrix \brief Check the dual variables for consistency with row activity. The routine checks that the value of the dual variable is consistent with the state of the constraint (loose, tight at lower bound, or tight at upper bound). */ void presolve_check_duals(const CoinPostsolveMatrix *postObj); /*! \relates CoinPresolveMatrix \brief Check primal solution and architectural variable status. The architectural variables can be checked for bogus values, feasibility, and valid status. The row activity is checked for bogus values, accuracy, and feasibility. By default, row activity is not checked (presolve is sloppy about maintaining it). See the definitions in CoinPresolvePsdebug.cpp for more information. */ void presolve_check_sol(const CoinPresolveMatrix *preObj, int chkColSol = 2, int chkRowAct = 1, int chkStatus = 1); /*! \relates CoinPostsolveMatrix \brief Check primal solution and architectural variable status. The architectural variables can be checked for bogus values, feasibility, and valid status. The row activity is checked for bogus values, accuracy, and feasibility. See the definitions in CoinPresolvePsdebug.cpp for more information. */ void presolve_check_sol(const CoinPostsolveMatrix *postObj, int chkColSol = 2, int chkRowAct = 2, int chkStatus = 1); /*! \relates CoinPresolveMatrix \brief Check for the proper number of basic variables. */ void presolve_check_nbasic(const CoinPresolveMatrix *preObj); /*! \relates CoinPostsolveMatrix \brief Check for the proper number of basic variables. */ void presolve_check_nbasic(const CoinPostsolveMatrix *postObj); //@} #endif /* vi: softtabstop=2 shiftwidth=2 expandtab tabstop=2 */
39.295858
79
0.764644
Justin790126
9c7adc4c02a84daea674d31050975ef4d4497336
526
cpp
C++
tests/core/gui/widgets/MarginsTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
null
null
null
tests/core/gui/widgets/MarginsTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
29
2020-10-21T07:34:55.000Z
2021-01-12T15:15:53.000Z
tests/core/gui/widgets/MarginsTests.cpp
Kubaaa96/IdleRomanEmpire
c41365babaccd309dd78e953a333b39d8045913a
[ "MIT" ]
1
2020-10-19T19:30:40.000Z
2020-10-19T19:30:40.000Z
#include <catch2/catch.hpp> #include "core/gui/widgets/Margins.h" TEST_CASE("[Margins]") { auto margins = std::make_unique< ire::core::gui::Margins>(); SECTION("Values") { REQUIRE(*margins.get() == ire::core::gui::Margins({ 0, 0, 0, 0 })); margins->m_left = 10; margins->m_top = 15; REQUIRE(*margins.get() == ire::core::gui::Margins({ 10, 0, 15, 0 })); auto margins1 = std::make_unique<ire::core::gui::Margins>( 22, 15, 54, 9); REQUIRE(*margins1.get() == ire::core::gui::Margins({ 22, 15, 54, 9 })); } }
23.909091
76
0.608365
Kubaaa96