hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
ff8981a48d12dfee9b4d9d2cd76e1659de010af6
493
hpp
C++
source/Engine/GameObject.hpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
8
2018-06-27T00:34:11.000Z
2018-09-07T06:56:20.000Z
source/Engine/GameObject.hpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
null
null
null
source/Engine/GameObject.hpp
rincew1nd/Minesweeper-Switch
6a441c4bbcc33cdbd0fe17fd5b9d4fb7e7cb0467
[ "MIT" ]
2
2018-06-28T03:02:07.000Z
2019-01-26T06:02:17.000Z
#pragma once #include "Input.hpp" #include <switch.h> #include "SDL2/SDL.h" #include <vector> #include <functional> class GameObject { public: GameObject(int, int, int, int); void SetAction(std::function<void()>); void Press() { if (_onPress != nullptr) _onPress(); }; bool Hovered(TouchInfo*); void Move(int, int); virtual ~GameObject() {}; protected: SDL_Rect* _rect; private: std::function<void()> _onPress; };
20.541667
62
0.592292
rincew1nd
ff89b78858cd90644eef2fcf23f7ed0c4eab2411
4,870
cpp
C++
Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
2
2022-03-25T17:37:45.000Z
2022-03-26T02:22:22.000Z
Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
null
null
null
Code/Engine/Animation/Graph/Nodes/Animation_RuntimeGraphNode_Ragdoll.cpp
jagt/KRG
ba20cd8798997b0450491b0cc04dc817c4a4bc76
[ "MIT" ]
null
null
null
#include "Animation_RuntimeGraphNode_Ragdoll.h" #include "Engine/Animation/TaskSystem/Tasks/Animation_Task_Ragdoll.h" #include "Engine/Animation/TaskSystem/Tasks/Animation_Task_DefaultPose.h" #include "Engine/Physics/PhysicsRagdoll.h" #include "Engine/Physics/PhysicsScene.h" #include "System/Core/Logging/Log.h" //------------------------------------------------------------------------- namespace KRG::Animation::GraphNodes { void PoweredRagdollNode::Settings::InstantiateNode( TVector<GraphNode*> const& nodePtrs, GraphDataSet const* pDataSet, InitOptions options ) const { auto pNode = CreateNode<PoweredRagdollNode>( nodePtrs, options ); SetOptionalNodePtrFromIndex( nodePtrs, m_physicsBlendWeightNodeIdx, pNode->m_pBlendWeightValueNode ); PassthroughNode::Settings::InstantiateNode( nodePtrs, pDataSet, GraphNode::Settings::InitOptions::OnlySetPointers ); pNode->m_pRagdollDefinition = pDataSet->GetResource<Physics::RagdollDefinition>( m_dataSlotIdx ); } bool PoweredRagdollNode::IsValid() const { return PassthroughNode::IsValid() && m_pRagdollDefinition != nullptr && m_pRagdoll != nullptr; } void PoweredRagdollNode::InitializeInternal( GraphContext& context, SyncTrackTime const& initialTime ) { KRG_ASSERT( context.IsValid() ); PassthroughNode::InitializeInternal( context, initialTime ); // Create ragdoll if ( m_pRagdollDefinition != nullptr && context.m_pPhysicsScene != nullptr ) { auto pNodeSettings = GetSettings<PoweredRagdollNode>(); m_pRagdoll = context.m_pPhysicsScene->CreateRagdoll( m_pRagdollDefinition, pNodeSettings->m_profileID, context.m_graphUserID ); m_pRagdoll->SetPoseFollowingEnabled( true ); m_pRagdoll->SetGravityEnabled( pNodeSettings->m_isGravityEnabled ); } //------------------------------------------------------------------------- if ( m_pBlendWeightValueNode != nullptr ) { m_pBlendWeightValueNode->Initialize( context ); } m_isFirstUpdate = true; } void PoweredRagdollNode::ShutdownInternal( GraphContext& context ) { KRG_ASSERT( context.IsValid() ); if ( m_pBlendWeightValueNode != nullptr ) { m_pBlendWeightValueNode->Shutdown( context ); } //------------------------------------------------------------------------- // Destroy the ragdoll if ( m_pRagdoll != nullptr ) { m_pRagdoll->RemoveFromScene(); KRG::Delete( m_pRagdoll ); } PassthroughNode::ShutdownInternal( context ); } GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context ) { GraphPoseNodeResult result; if ( IsValid() ) { result = PassthroughNode::Update( context ); result = RegisterRagdollTasks( context, result ); } else { result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose ); } return result; } GraphPoseNodeResult PoweredRagdollNode::Update( GraphContext& context, SyncTrackTimeRange const& updateRange ) { GraphPoseNodeResult result; if ( IsValid() ) { result = PassthroughNode::Update( context, updateRange ); result = RegisterRagdollTasks( context, result ); } else { result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::DefaultPoseTask>( GetNodeIndex(), Pose::InitialState::ReferencePose ); } return result; } GraphPoseNodeResult PoweredRagdollNode::RegisterRagdollTasks( GraphContext& context, GraphPoseNodeResult const& childResult ) { KRG_ASSERT( IsValid() ); GraphPoseNodeResult result = childResult; //------------------------------------------------------------------------- Tasks::RagdollSetPoseTask::InitOption const initOptions = m_isFirstUpdate ? Tasks::RagdollSetPoseTask::InitializeBodies : Tasks::RagdollSetPoseTask::DoNothing; TaskIndex const setPoseTaskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollSetPoseTask>( m_pRagdoll, GetNodeIndex(), childResult.m_taskIdx, initOptions ); m_isFirstUpdate = false; //------------------------------------------------------------------------- float const physicsWeight = ( m_pBlendWeightValueNode != nullptr ) ? m_pBlendWeightValueNode->GetValue<float>( context ) : GetSettings<PoweredRagdollNode>()->m_physicsBlendWeight; result.m_taskIdx = context.m_pTaskSystem->RegisterTask<Tasks::RagdollGetPoseTask>( m_pRagdoll, GetNodeIndex(), setPoseTaskIdx, physicsWeight ); return result; } }
39.593496
187
0.625667
jagt
ff8c2c32a08dd2d13e630fc35220e58f31eb80fc
23,299
cpp
C++
src/gpu/cl/kernels/ClDirectConv2dKernel.cpp
hixio-mh/ComputeLibrary
8f587de9214dbc3aee4ff4eeb2ede66747769b19
[ "MIT" ]
1
2022-03-18T19:50:04.000Z
2022-03-18T19:50:04.000Z
src/gpu/cl/kernels/ClDirectConv2dKernel.cpp
hixio-mh/ComputeLibrary
8f587de9214dbc3aee4ff4eeb2ede66747769b19
[ "MIT" ]
null
null
null
src/gpu/cl/kernels/ClDirectConv2dKernel.cpp
hixio-mh/ComputeLibrary
8f587de9214dbc3aee4ff4eeb2ede66747769b19
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017-2021 Arm Limited. * * SPDX-License-Identifier: MIT * * 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 "src/gpu/cl/kernels/ClDirectConv2dKernel.h" #include "arm_compute/core/CL/CLHelpers.h" #include "arm_compute/core/CL/CLKernelLibrary.h" #include "arm_compute/core/CL/ICLTensor.h" #include "arm_compute/core/Helpers.h" #include "arm_compute/core/ITensor.h" #include "arm_compute/core/PixelValue.h" #include "arm_compute/core/Utils.h" #include "arm_compute/core/utils/misc/ShapeCalculator.h" #include "arm_compute/core/utils/quantization/AsymmHelpers.h" #include "src/core/AccessWindowStatic.h" #include "src/core/CL/CLUtils.h" #include "src/core/CL/CLValidate.h" #include "src/core/helpers/AutoConfiguration.h" #include "src/core/helpers/WindowHelpers.h" #include "src/gpu/cl/kernels/gemm/ClGemmHelpers.h" #include "support/Cast.h" #include "support/StringSupport.h" namespace arm_compute { namespace opencl { namespace kernels { namespace { Status validate_arguments(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info) { ARM_COMPUTE_RETURN_ERROR_ON_F16_UNSUPPORTED(src); ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(src, 1, DataType::QASYMM8_SIGNED, DataType::QASYMM8, DataType::F16, DataType::F32); ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, weights); const DataLayout data_layout = src->data_layout(); const int width_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::WIDTH); const int height_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::HEIGHT); const int channel_idx = get_data_layout_dimension_index(data_layout, DataLayoutDimension::CHANNEL); ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(channel_idx) != src->dimension(channel_idx), "Weights feature map dimension should match the respective src's one"); ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->num_dimensions() > 4, "Weights can be at most 4 dimensional"); if(data_layout == DataLayout::NCHW) { ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != weights->dimension(height_idx), "Weights should have same width and height"); ARM_COMPUTE_RETURN_ERROR_ON_MSG((weights->dimension(width_idx) == 1) && std::get<0>(conv_info.stride()) > 3, "Strides larger than 3 not supported for 1x1 convolution."); ARM_COMPUTE_RETURN_ERROR_ON_MSG((weights->dimension(width_idx) == 3 || weights->dimension(width_idx) == 5 || weights->dimension(width_idx) == 9) && std::get<0>(conv_info.stride()) > 2, "Strides larger than 2 not supported for 3x3, 5x5, 9x9 convolution."); ARM_COMPUTE_RETURN_ERROR_ON_MSG(!is_data_type_float(src->data_type()) && act_info.enabled(), "Activation supported only for floating point and NHWC."); if(is_data_type_quantized(src->data_type())) { ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != 1 && weights->dimension(width_idx) != 3 && weights->dimension(width_idx) != 5 && weights->dimension(width_idx) != 9, "Kernel sizes other than 1x1, 3x3, 5x5 or 9x9 are not supported with quantized data types"); } else { ARM_COMPUTE_RETURN_ERROR_ON_MSG(weights->dimension(width_idx) != 1 && weights->dimension(width_idx) != 3 && weights->dimension(width_idx) != 5, "Kernel sizes other than 1x1, 3x3 or 5x5 are not supported with float data types"); } } if(biases != nullptr) { if(is_data_type_quantized_asymmetric(src->data_type())) { ARM_COMPUTE_RETURN_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(biases, 1, DataType::S32); } else { ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(weights, biases); } ARM_COMPUTE_RETURN_ERROR_ON_MSG(biases->dimension(0) != weights->dimension(3), "Biases size and number of dst feature maps should match"); ARM_COMPUTE_RETURN_ERROR_ON_MSG(biases->num_dimensions() > 1, "Biases should be one dimensional"); } // Checks performed when dst is configured if(dst->total_size() != 0) { ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DIMENSIONS(dst->tensor_shape(), misc::shape_calculator::compute_deep_convolution_shape(*src, *weights, conv_info)); ARM_COMPUTE_RETURN_ERROR_ON_MISMATCHING_DATA_TYPES(src, dst); } const auto data_type = src->data_type(); if(is_data_type_quantized(data_type)) { const UniformQuantizationInfo iqinfo = src->quantization_info().uniform(); const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform(); const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform(); float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale; int output_multiplier = 0; int output_shift = 0; ARM_COMPUTE_RETURN_ON_ERROR(quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift)); } return Status{}; } bool export_to_cl_image_support(ITensorInfo *tensor, GPUTarget gpu_target, DataLayout data_layout) { if(tensor->tensor_shape()[0] % 4 || (data_layout != DataLayout::NHWC)) { return false; } // If not floating point if(!is_data_type_float(tensor->data_type())) { return false; } if(gpu_target == GPUTarget::G71 || get_arch_from_target(gpu_target) == GPUTarget::MIDGARD) { return false; } // Check if the cl_khr_image2d_from_buffer extension is supported on the target platform if(!image2d_from_buffer_supported(CLKernelLibrary::get().get_device())) { return false; } // Check cl image pitch alignment if(get_cl_image_pitch_alignment(CLKernelLibrary::get().get_device()) == 0) { return false; } const size_t image_w = tensor->tensor_shape()[0] / 4; const size_t image_h = tensor->tensor_shape()[1] * tensor->tensor_shape()[2] * tensor->tensor_shape()[3]; const size_t max_image_w = CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_IMAGE2D_MAX_WIDTH>(); const size_t max_image_h = CLKernelLibrary::get().get_device().getInfo<CL_DEVICE_IMAGE2D_MAX_HEIGHT>(); if(image_w > max_image_w || image_h > max_image_h) { return false; } return true; } } // namespace ClDirectConv2dKernel::ClDirectConv2dKernel() { _type = CLKernelType::DIRECT; } void ClDirectConv2dKernel::configure(const CLCompileContext &compile_context, ITensorInfo *src, ITensorInfo *weights, ITensorInfo *biases, ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info) { ARM_COMPUTE_ERROR_ON_NULLPTR(src, weights, dst); // Perform validation ARM_COMPUTE_ERROR_THROW_ON(validate_arguments(src, weights, biases, dst, conv_info, act_info)); const int conv_stride_x = std::get<0>(conv_info.stride()); const int conv_stride_y = std::get<1>(conv_info.stride()); _data_layout = src->data_layout(); _conv_info = conv_info; const unsigned int width_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::WIDTH); const unsigned int height_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::HEIGHT); const unsigned int channel_idx = get_data_layout_dimension_index(_data_layout, DataLayoutDimension::CHANNEL); const unsigned int kernel_size = weights->dimension(width_idx); const DataType data_type = src->data_type(); const GPUTarget gpu_target = get_target(); unsigned int _num_elems_processed_per_iteration = 0; // Get dst shape TensorShape output_shape = misc::shape_calculator::compute_deep_convolution_shape(*src, *weights, conv_info); // Output auto inizialitation if not yet initialized auto_init_if_empty(*dst, output_shape, 1, src->data_type(), src->quantization_info()); // Configure kernel window Window win; if(_data_layout == DataLayout::NHWC) { const unsigned int vec_size = std::min(static_cast<unsigned int>(dst->tensor_shape()[0]), 4u); unsigned int num_rows = 1U; if(dst->tensor_shape()[0] > 16) { num_rows = src->data_type() == DataType::F32 ? 2U : 4U; } // Create window and update padding win = calculate_max_window(output_shape, Steps(vec_size, num_rows)); } else if(_data_layout == DataLayout::NCHW) { _num_elems_processed_per_iteration = 1u; win = calculate_max_window(*dst, Steps(_num_elems_processed_per_iteration)); } ICLKernel::configure_internal(win); std::stringstream kernel_name; CLBuildOptions build_options; if(_data_layout == DataLayout::NHWC) { kernel_name << "direct_convolution_nhwc"; const unsigned int n0 = win.x().step(); const unsigned int m0 = win.y().step(); const unsigned int k0 = adjust_vec_size(is_data_type_quantized(data_type) ? 16u : 8u, src->dimension(channel_idx)); const unsigned int partial_store_n0 = dst->dimension(channel_idx) % n0; const unsigned int pad_left = conv_info.pad_left(); const unsigned int pad_top = conv_info.pad_top(); const bool export_to_cl_image = export_to_cl_image_support(weights, gpu_target, _data_layout); // Update the padding for the weights tensor if we can export to cl_image if(export_to_cl_image) { gemm::update_padding_for_cl_image(weights); } if(biases != nullptr) { build_options.add_option(std::string("-DHAS_BIAS")); build_options.add_option(std::string("-DBIA_DATA_TYPE=" + get_cl_type_from_data_type(biases->data_type()))); } build_options.add_option("-cl-fast-relaxed-math"); build_options.add_option("-DSRC_TENSOR_TYPE=BUFFER"); build_options.add_option("-DSRC_DATA_TYPE=" + get_cl_type_from_data_type(src->data_type())); build_options.add_option("-DDST_TENSOR_TYPE=BUFFER"); build_options.add_option("-DDST_DATA_TYPE=" + get_cl_type_from_data_type(dst->data_type())); build_options.add_option_if_else(export_to_cl_image, "-DWEI_TENSOR_TYPE=IMAGE", "-DWEI_TENSOR_TYPE=BUFFER"); build_options.add_option("-DWEI_WIDTH=" + support::cpp11::to_string(weights->dimension(width_idx))); build_options.add_option("-DWEI_HEIGHT=" + support::cpp11::to_string(weights->dimension(height_idx))); build_options.add_option("-DWEI_DATA_TYPE=" + get_cl_type_from_data_type(weights->data_type())); build_options.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x)); build_options.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_stride_y)); build_options.add_option("-DPAD_LEFT=" + support::cpp11::to_string(pad_left)); build_options.add_option("-DPAD_TOP=" + support::cpp11::to_string(pad_top)); build_options.add_option("-DN0=" + support::cpp11::to_string(n0)); build_options.add_option("-DM0=" + support::cpp11::to_string(m0)); build_options.add_option("-DK0=" + support::cpp11::to_string(k0)); build_options.add_option("-DPARTIAL_N0=" + support::cpp11::to_string(partial_store_n0)); build_options.add_option_if((src->dimension(channel_idx) % k0) != 0, "-DLEFTOVER_LOOP"); build_options.add_option("-DACTIVATION_TYPE=" + lower_string(string_from_activation_func(act_info.activation()))); if(is_data_type_quantized(data_type)) { const UniformQuantizationInfo iqinfo = src->quantization_info().uniform(); const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform(); const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform(); PixelValue zero_value = PixelValue(0, src->data_type(), src->quantization_info()); int zero_value_s32; zero_value.get(zero_value_s32); float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale; int output_multiplier = 0; int output_shift = 0; quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift); build_options.add_option("-DIS_QUANTIZED"); build_options.add_option("-DDST_MULTIPLIER=" + support::cpp11::to_string(output_multiplier)); build_options.add_option("-DDST_SHIFT=" + support::cpp11::to_string(output_shift)); build_options.add_option("-DSRC_OFFSET=" + support::cpp11::to_string(-iqinfo.offset)); build_options.add_option("-DWEI_OFFSET=" + support::cpp11::to_string(-wqinfo.offset)); build_options.add_option("-DDST_OFFSET=" + support::cpp11::to_string(oqinfo.offset)); build_options.add_option("-DZERO_VALUE=" + support::cpp11::to_string(zero_value_s32)); build_options.add_option("-DACC_DATA_TYPE=" + get_cl_type_from_data_type(DataType::S32)); } else { build_options.add_option("-DACC_DATA_TYPE=" + get_cl_type_from_data_type(data_type)); build_options.add_option("-DZERO_VALUE=" + support::cpp11::to_string(0)); build_options.add_option("-DSRC_OFFSET=" + support::cpp11::to_string(0)); build_options.add_option("-DWEI_OFFSET=" + support::cpp11::to_string(0)); build_options.add_option("-DDST_OFFSET=" + support::cpp11::to_string(0)); build_options.add_option_if(act_info.enabled(), "-DA_VAL=" + float_to_string_with_full_precision(act_info.a())); build_options.add_option_if(act_info.enabled(), "-DB_VAL=" + float_to_string_with_full_precision(act_info.b())); } } else { kernel_name << "direct_convolution_nchw"; build_options.add_option_if(biases != nullptr, std::string("-DHAS_BIAS")); build_options.add_option("-DSRC_WIDTH=" + support::cpp11::to_string(src->dimension(width_idx))); build_options.add_option("-DSRC_HEIGHT=" + support::cpp11::to_string(src->dimension(height_idx))); build_options.add_option("-DSRC_CHANNELS=" + support::cpp11::to_string(src->dimension(channel_idx))); build_options.add_option("-DPAD_LEFT=" + support::cpp11::to_string(conv_info.pad_left())); build_options.add_option("-DPAD_TOP=" + support::cpp11::to_string(conv_info.pad_top())); build_options.add_option("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x)); build_options.add_option("-DSTRIDE_Y=" + support::cpp11::to_string(conv_stride_y)); build_options.add_option("-DWEI_WIDTH=" + support::cpp11::to_string(weights->dimension(width_idx))); build_options.add_option("-DWEI_HEIGHT=" + support::cpp11::to_string(weights->dimension(height_idx))); build_options.add_option(std::string("-DDATA_TYPE=" + get_cl_type_from_data_type(data_type))); build_options.add_option(std::string("-DDATA_SIZE=" + get_data_size_from_data_type(data_type))); build_options.add_option(std::string("-DWEIGHTS_DEPTH=" + support::cpp11::to_string(weights->dimension(channel_idx)))); build_options.add_option(std::string("-DSTRIDE_X=" + support::cpp11::to_string(conv_stride_x))); build_options.add_option(std::string("-DDATA_TYPE_PROMOTED=" + get_cl_type_from_data_type(data_type))); build_options.add_option(std::string("-DVEC_SIZE=" + support::cpp11::to_string(_num_elems_processed_per_iteration))); build_options.add_option(std::string("-DVEC_SIZE_LEFTOVER=" + support::cpp11::to_string(src->dimension(0) % _num_elems_processed_per_iteration))); if(is_data_type_quantized(data_type)) { const UniformQuantizationInfo iqinfo = src->quantization_info().uniform(); const UniformQuantizationInfo wqinfo = weights->quantization_info().uniform(); const UniformQuantizationInfo oqinfo = dst->quantization_info().uniform(); float multiplier = iqinfo.scale * wqinfo.scale / oqinfo.scale; int output_multiplier = 0; int output_shift = 0; quantization::calculate_quantized_multiplier(multiplier, &output_multiplier, &output_shift); build_options.add_option("-DIS_QUANTIZED"); build_options.add_option("-DOUTPUT_MULTIPLIER=" + support::cpp11::to_string(output_multiplier)); build_options.add_option("-DOUTPUT_SHIFT=" + support::cpp11::to_string(output_shift)); build_options.add_option("-DKERNEL_SIZE=" + support::cpp11::to_string(kernel_size)); build_options.add_option("-DINPUT_OFFSET=" + support::cpp11::to_string(-iqinfo.offset)); build_options.add_option("-DWEIGHTS_OFFSET=" + support::cpp11::to_string(-wqinfo.offset)); build_options.add_option("-DOUTPUT_OFFSET=" + support::cpp11::to_string(oqinfo.offset)); } } _kernel = create_kernel(compile_context, kernel_name.str(), build_options.options()); // Set config_id for enabling LWS tuning _config_id = kernel_name.str(); _config_id += "_"; _config_id += lower_string(string_from_data_type(data_type)); _config_id += "_"; _config_id += support::cpp11::to_string(kernel_size); _config_id += "_"; _config_id += support::cpp11::to_string(border_size().left); _config_id += "_"; _config_id += support::cpp11::to_string(border_size().top); _config_id += "_"; _config_id += support::cpp11::to_string(border_size().right); _config_id += "_"; _config_id += support::cpp11::to_string(border_size().bottom); _config_id += "_"; _config_id += support::cpp11::to_string(conv_stride_x); _config_id += "_"; _config_id += support::cpp11::to_string(conv_stride_y); _config_id += "_"; _config_id += support::cpp11::to_string(dst->dimension(width_idx)); _config_id += "_"; _config_id += support::cpp11::to_string(dst->dimension(height_idx)); _config_id += "_"; _config_id += lower_string(string_from_data_layout(_data_layout)); } Status ClDirectConv2dKernel::validate(const ITensorInfo *src, const ITensorInfo *weights, const ITensorInfo *biases, const ITensorInfo *dst, const PadStrideInfo &conv_info, const ActivationLayerInfo &act_info) { ARM_COMPUTE_RETURN_ON_ERROR(validate_arguments(src, weights, biases, dst, conv_info, act_info)); return Status{}; } void ClDirectConv2dKernel::run_op(ITensorPack &tensors, const Window &window, cl::CommandQueue &queue) { ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(IKernel::window(), window); // Get initial windows Window slice = window.first_slice_window_3D(); const auto src = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_0)); const auto weights = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_1)); const auto biases = utils::cast::polymorphic_downcast<const ICLTensor *>(tensors.get_const_tensor(TensorType::ACL_SRC_2)); auto dst = utils::cast::polymorphic_downcast<ICLTensor *>(tensors.get_tensor(TensorType::ACL_DST)); if(_data_layout == DataLayout::NHWC) { cl::Image2D weights_cl_image; const size_t dim_y_collapsed = ceil_to_multiple(dst->info()->dimension(1) * dst->info()->dimension(2), slice.y().step()); const bool export_to_cl_image = export_to_cl_image_support(weights->info(), get_target(), _data_layout); slice.set(Window::DimY, Window::Dimension(0, dim_y_collapsed, slice.y().step())); slice.set(Window::DimZ, Window::Dimension(0, dst->info()->dimension(3), 1)); if(export_to_cl_image) { const size_t image_w = weights->info()->dimension(0) / 4; const size_t image_h = weights->info()->dimension(1) * weights->info()->dimension(2) * weights->info()->dimension(3); const TensorShape shape2d(image_w, image_h); const size_t image_row_pitch = weights->info()->strides_in_bytes()[1]; // Export cl_buffer to cl_image weights_cl_image = create_image2d_from_buffer(CLKernelLibrary::get().context(), weights->cl_buffer(), shape2d, weights->info()->data_type(), image_row_pitch); } unsigned int idx = 0; add_4d_tensor_nhwc_argument(idx, src); add_4d_tensor_nhwc_argument(idx, dst); if(export_to_cl_image) { _kernel.setArg(idx++, weights_cl_image); } add_4d_tensor_nhwc_argument(idx, weights); if(biases != nullptr) { add_1D_tensor_argument(idx, biases, slice); } enqueue(queue, *this, slice, lws_hint()); } else { unsigned int idx1 = 2 * num_arguments_per_3D_tensor(); add_3D_tensor_argument(idx1, weights, slice); if(biases != nullptr) { Window slice_biases; slice_biases.use_tensor_dimensions(biases->info()->tensor_shape()); add_1D_tensor_argument(idx1, biases, slice_biases); } _kernel.setArg(idx1++, static_cast<unsigned int>(weights->info()->strides_in_bytes()[3])); do { unsigned int idx = 0; add_3D_tensor_argument(idx, src, slice); add_3D_tensor_argument(idx, dst, slice); enqueue(queue, *this, slice, lws_hint()); } while(window.slide_window_slice_3D(slice)); } } } // namespace kernels } // namespace opencl } // namespace arm_compute
50.54013
193
0.681274
hixio-mh
ff8d44093357788ed0f52884afcd51ab01a92478
1,270
cpp
C++
modules/moduleTest/testCommon.cpp
helinux/FFdynamic
d65959641fd0f8e69e1d799b8b439c8ad2793600
[ "MIT" ]
299
2018-10-21T03:28:53.000Z
2022-03-20T12:04:13.000Z
modules/moduleTest/testCommon.cpp
helinux/FFdynamic
d65959641fd0f8e69e1d799b8b439c8ad2793600
[ "MIT" ]
31
2018-11-13T12:46:15.000Z
2022-01-19T19:30:16.000Z
modules/moduleTest/testCommon.cpp
helinux/FFdynamic
d65959641fd0f8e69e1d799b8b439c8ad2793600
[ "MIT" ]
68
2018-11-02T14:05:00.000Z
2022-03-01T19:16:29.000Z
#include "testCommon.h" using namespace ff_dynamic; namespace test_common { std::atomic<bool> g_bExit = ATOMIC_VAR_INIT(false); std::atomic<int> g_bInterruptCount = ATOMIC_VAR_INIT(0); void sigIntHandle(int sig) { g_bExit = true; LOG(INFO) << "sig " << sig << " captured. count" << g_bInterruptCount; if (++g_bInterruptCount >= 3) { LOG(INFO) << "exit program"; exit(1); } } int testInit(const string & logtag) { google::InitGoogleLogging(logtag.c_str()); google::InstallFailureSignalHandler(); FLAGS_stderrthreshold = 0; FLAGS_logtostderr = 1; auto & sigHandle = GlobalSignalHandle::getInstance(); sigHandle.registe(SIGINT, sigIntHandle); av_log_set_callback([] (void *ptr, int level, const char *fmt, va_list vl) { if (level > AV_LOG_WARNING) return ; char message[8192]; const char *ffmpegModule = nullptr; if (ptr) { AVClass *avc = *(AVClass**) ptr; if (avc->item_name) ffmpegModule = avc->item_name(ptr); } vsnprintf(message, sizeof(message), fmt, vl); LOG(WARNING) << "[FFMPEG][" << (ffmpegModule ? ffmpegModule : "") << "]" << message; }); return 0; } } // namespace test_common
28.222222
92
0.611024
helinux
ff8dfd03a24507754cb34b9f3f9288977bab48f3
14,769
cpp
C++
src/splinesonic/sim/Test.cpp
Ryp/Reaper
ccaef540013db7e8bf873db6e597e9036184d100
[ "MIT" ]
11
2016-11-07T07:47:46.000Z
2018-07-19T16:04:45.000Z
src/splinesonic/sim/Test.cpp
Ryp/Reaper
ccaef540013db7e8bf873db6e597e9036184d100
[ "MIT" ]
null
null
null
src/splinesonic/sim/Test.cpp
Ryp/Reaper
ccaef540013db7e8bf873db6e597e9036184d100
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// Reaper /// /// Copyright (c) 2015-2022 Thibault Schueller /// This file is distributed under the MIT License //////////////////////////////////////////////////////////////////////////////// #include "Test.h" #if defined(REAPER_USE_BULLET_PHYSICS) # include <BulletCollision/CollisionShapes/btBoxShape.h> # include <BulletCollision/CollisionShapes/btScaledBvhTriangleMeshShape.h> # include <BulletCollision/CollisionShapes/btTriangleMesh.h> # include <BulletCollision/Gimpact/btGImpactCollisionAlgorithm.h> # include <btBulletDynamicsCommon.h> #endif #include "mesh/Mesh.h" #include "core/Assert.h" #include "profiling/Scope.h" #include <glm/gtc/matrix_access.hpp> #include <glm/gtc/quaternion.hpp> #include <glm/gtx/projection.hpp> #include <glm/vec3.hpp> #include <bit> namespace SplineSonic { namespace { #if defined(REAPER_USE_BULLET_PHYSICS) inline glm::vec3 toGlm(btVector3 const& vec) { return glm::vec3(vec.getX(), vec.getY(), vec.getZ()); } inline glm::quat toGlm(btQuaternion const& quat) { return glm::quat(quat.getW(), quat.getX(), quat.getY(), quat.getZ()); } inline glm::fmat4x3 toGlm(const btTransform& transform) { const btMatrix3x3 basis = transform.getBasis(); const glm::fvec3 translation = toGlm(transform.getOrigin()); return glm::fmat4x3(toGlm(basis[0]), toGlm(basis[1]), toGlm(basis[2]), translation); } inline btVector3 toBt(glm::vec3 const& vec) { return btVector3(vec.x, vec.y, vec.z); } inline btMatrix3x3 m33toBt(const glm::fmat3x3& m) { return btMatrix3x3(m[0].x, m[1].x, m[2].x, m[0].y, m[1].y, m[2].y, m[0].z, m[1].z, m[2].z); } // inline btQuaternion toBt(glm::quat const& quat) { return btQuaternion(quat.w, quat.x, quat.y, quat.z); } inline btTransform toBt(const glm::fmat4x3& transform) { btMatrix3x3 mat = m33toBt(glm::fmat3x3(transform)); btTransform ret = btTransform(mat, toBt(glm::column(transform, 3))); return ret; } static const int SimulationMaxSubStep = 3; // FIXME glm::fvec3 forward() { return glm::vec3(1.0f, 0.0f, 0.0f); } glm::fvec3 up() { return glm::vec3(0.0f, 0.0f, 1.0f); } void pre_tick(PhysicsSim& sim, const ShipInput& input, float /*dt*/) { REAPER_PROFILE_SCOPE_FUNC(); btRigidBody* playerRigidBody = sim.players[0]; const glm::fmat4x3 player_transform = toGlm(playerRigidBody->getWorldTransform()); const glm::fvec3 player_position_ws = player_transform[3]; const glm::quat player_orientation = toGlm(playerRigidBody->getWorldTransform().getRotation()); float min_dist_sq = 10000000.f; const btRigidBody* closest_track_chunk = nullptr; for (auto track_chunk : sim.static_rigid_bodies) { glm::fvec3 delta = player_position_ws - toGlm(track_chunk->getWorldTransform().getOrigin()); float dist_sq = glm::dot(delta, delta); if (dist_sq < min_dist_sq) { min_dist_sq = dist_sq; closest_track_chunk = track_chunk; } } Assert(closest_track_chunk); // FIXME const glm::fmat4x3 projected_transform = toGlm(closest_track_chunk->getWorldTransform()); const glm::quat projected_orientation = toGlm(closest_track_chunk->getWorldTransform().getRotation()); glm::vec3 shipUp; glm::vec3 shipFwd; shipUp = projected_orientation * up(); shipFwd = player_orientation * forward(); // shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane // Re-eval ship orientation // FIXME player_orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp))); const glm::fvec3 linear_speed = toGlm(playerRigidBody->getLinearVelocity()); // change steer angle { // float steerMultiplier = 0.035f; // float inclinationMax = 2.6f; // float inclForce = (log(glm::length(linear_speed * 0.5f) + 1.0f) + 0.2f) * input.steer; // float inclinationRepel = -movement.inclination * 5.0f; // movement.inclination = // glm::clamp(movement.inclination + (inclForce + inclinationRepel) * dtSecs, -inclinationMax, // inclinationMax); // movement.orientation *= glm::angleAxis(-input.steer * steerMultiplier, up()); } ShipStats ship_stats; ship_stats.thrust = 100.f; ship_stats.braking = 10.f; // Integrate forces glm::vec3 forces = {}; forces += -shipUp * 98.331f; // 10x earth gravity forces += shipFwd * input.throttle * ship_stats.thrust; // Engine thrust // forces += shipFwd * player.getAcceleration(); // Engine thrust forces += -glm::proj(linear_speed, shipFwd) * input.brake * ship_stats.braking; // Brakes force // forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * sim.pHandling; // Handling term forces += -linear_speed * sim.linear_friction; forces += -linear_speed * glm::length(linear_speed) * sim.quadratic_friction; // Progressive repelling force that pushes the ship downwards // FIXME // float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp)); // if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f) // forces += player_orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f); playerRigidBody->clearForces(); playerRigidBody->applyCentralForce(toBt(forces)); } /* { shipUp = projection.orientation * glm::up(); shipFwd = movement.orientation * glm::forward(); shipFwd = glm::normalize(shipFwd - glm::proj(shipFwd, shipUp)); // Ship Fwd in on slice plane // Re-eval ship orientation movement.orientation = glm::quat(glm::mat3(shipFwd, shipUp, glm::cross(shipFwd, shipUp))); // change steer angle steer(dt, movement, factors.getTurnFactor()); // sum all forces // forces += - shipUp * 98.331f; // 10x earth gravity forces += -shipUp * 450.0f; // lot of times earth gravity forces += shipFwd * factors.getThrustFactor() * player->getAcceleration(); // Engine thrust forces += -glm::proj(movement.speed, shipFwd) * factors.getBrakeFactor() * _pBrakesForce; // Brakes force forces += -glm::proj(movement.speed, glm::cross(shipFwd, shipUp)) * _pHandling; // Handling term forces += -movement.speed * linear_friction; // Linear friction term forces += -movement.speed * glm::length(movement.speed) * _pQuadFriction; // Quadratic friction term // Progressive repelling force that pushes the ship downwards float upSpeed = glm::length(movement.speed - glm::proj(movement.speed, shipUp)); if (projection.relativePosition.y > 2.0f && upSpeed > 0.0f) forces += movement.orientation * (glm::vec3(0.0f, 2.0f - upSpeed, 0.0f) * 10.0f); playerRigidBody->clearForces(); playerRigidBody->applyCentralForce(toBt(forces)); } */ void post_tick(PhysicsSim& sim, float /*dt*/) { REAPER_PROFILE_SCOPE_FUNC(); btRigidBody* playerRigidBody = sim.players.front(); // FIXME toGlm(playerRigidBody->getLinearVelocity()); toGlm(playerRigidBody->getOrientation()); } #endif } // namespace PhysicsSim create_sim() { PhysicsSim sim = {}; // Physics tweakables sim.linear_friction = 4.0f; sim.quadratic_friction = 0.01f; #if defined(REAPER_USE_BULLET_PHYSICS) // Boilerplate code for a standard rigidbody simulation sim.broadphase = new btDbvtBroadphase(); sim.collisionConfiguration = new btDefaultCollisionConfiguration(); sim.dispatcher = new btCollisionDispatcher(sim.collisionConfiguration); btGImpactCollisionAlgorithm::registerAlgorithm(sim.dispatcher); sim.solver = new btSequentialImpulseConstraintSolver; // Putting all of that together sim.dynamicsWorld = new btDiscreteDynamicsWorld(sim.dispatcher, sim.broadphase, sim.solver, sim.collisionConfiguration); #endif return sim; } void destroy_sim(PhysicsSim& sim) { #if defined(REAPER_USE_BULLET_PHYSICS) for (auto player_rigid_body : sim.players) { sim.dynamicsWorld->removeRigidBody(player_rigid_body); delete player_rigid_body->getMotionState(); delete player_rigid_body; } for (auto rb : sim.static_rigid_bodies) { sim.dynamicsWorld->removeRigidBody(rb); delete rb->getMotionState(); delete rb; } for (auto collision_shape : sim.collision_shapes) { delete collision_shape; } for (auto vb : sim.vertexArrayInterfaces) delete vb; // Delete the rest of the bullet context delete sim.dynamicsWorld; delete sim.solver; delete sim.dispatcher; delete sim.collisionConfiguration; delete sim.broadphase; #else static_cast<void>(sim); #endif } namespace { #if defined(REAPER_USE_BULLET_PHYSICS) void pre_tick_callback(btDynamicsWorld* world, btScalar dt) { PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo()); Assert(sim_ptr); PhysicsSim& sim = *sim_ptr; pre_tick(sim, sim.last_input, dt); } void post_tick_callback(btDynamicsWorld* world, btScalar dt) { PhysicsSim* sim_ptr = static_cast<PhysicsSim*>(world->getWorldUserInfo()); Assert(sim_ptr); post_tick(*sim_ptr, dt); } #endif } // namespace void sim_start(PhysicsSim* sim) { REAPER_PROFILE_SCOPE_FUNC(); Assert(sim); #if defined(REAPER_USE_BULLET_PHYSICS) sim->dynamicsWorld->setInternalTickCallback(pre_tick_callback, sim, true); sim->dynamicsWorld->setInternalTickCallback(post_tick_callback, sim, false); #endif } void sim_update(PhysicsSim& sim, const ShipInput& input, float dt) { REAPER_PROFILE_SCOPE_FUNC(); sim.last_input = input; // FIXME #if defined(REAPER_USE_BULLET_PHYSICS) sim.dynamicsWorld->stepSimulation(dt, SimulationMaxSubStep); #else static_cast<void>(sim); static_cast<void>(dt); #endif } glm::fmat4x3 get_player_transform(PhysicsSim& sim) { #if defined(REAPER_USE_BULLET_PHYSICS) const btRigidBody* playerRigidBody = sim.players.front(); const btMotionState* playerMotionState = playerRigidBody->getMotionState(); btTransform output; playerMotionState->getWorldTransform(output); return toGlm(output); #else static_cast<void>(sim); AssertUnreachable(); return glm::fmat4x3(1.f); // FIXME #endif } void sim_register_static_collision_meshes(PhysicsSim& sim, const nonstd::span<Mesh> meshes, nonstd::span<const glm::fmat4x3> transforms_no_scale, nonstd::span<const glm::fvec3> scales) { // FIXME Assert scale values #if defined(REAPER_USE_BULLET_PHYSICS) Assert(meshes.size() == transforms_no_scale.size()); Assert(scales.empty() || scales.size() == transforms_no_scale.size()); for (u32 i = 0; i < meshes.size(); i++) { const Mesh& mesh = meshes[i]; // Describe how the mesh is laid out in memory btIndexedMesh indexedMesh; indexedMesh.m_numTriangles = mesh.indexes.size() / 3; indexedMesh.m_triangleIndexBase = reinterpret_cast<const u8*>(mesh.indexes.data()); indexedMesh.m_triangleIndexStride = 3 * sizeof(mesh.indexes[0]); indexedMesh.m_numVertices = mesh.positions.size(); indexedMesh.m_vertexBase = reinterpret_cast<const u8*>(mesh.positions.data()); indexedMesh.m_vertexStride = sizeof(mesh.positions[0]); indexedMesh.m_indexType = PHY_INTEGER; indexedMesh.m_vertexType = PHY_FLOAT; // Create bullet collision shape based on the mesh described btTriangleIndexVertexArray* meshInterface = new btTriangleIndexVertexArray(); sim.vertexArrayInterfaces.push_back(meshInterface); meshInterface->addIndexedMesh(indexedMesh); btBvhTriangleMeshShape* meshShape = new btBvhTriangleMeshShape(meshInterface, true); sim.collision_shapes.push_back(meshShape); const btVector3 scale = scales.empty() ? btVector3(1.f, 1.f, 1.f) : toBt(scales[i]); btScaledBvhTriangleMeshShape* scaled_mesh_shape = new btScaledBvhTriangleMeshShape(meshShape, scale); sim.collision_shapes.push_back(scaled_mesh_shape); btDefaultMotionState* chunkMotionState = new btDefaultMotionState(btTransform(toBt(transforms_no_scale[i]))); // Create the rigidbody with the collision shape btRigidBody::btRigidBodyConstructionInfo staticMeshRigidBodyInfo(0, chunkMotionState, scaled_mesh_shape); btRigidBody* staticRigidMesh = new btRigidBody(staticMeshRigidBodyInfo); sim.static_rigid_bodies.push_back(staticRigidMesh); // Add it to our scene sim.dynamicsWorld->addRigidBody(staticRigidMesh); } #else static_cast<void>(sim); static_cast<void>(meshes); static_cast<void>(transforms_no_scale); static_cast<void>(scales); #endif } void sim_create_player_rigid_body(PhysicsSim& sim, const glm::fmat4x3& player_transform, const glm::fvec3& shape_extent) { #if defined(REAPER_USE_BULLET_PHYSICS) btMotionState* motionState = new btDefaultMotionState(toBt(player_transform)); btCollisionShape* collisionShape = new btBoxShape(toBt(shape_extent)); sim.collision_shapes.push_back(collisionShape); btScalar mass = 10.f; // FIXME btVector3 inertia(0.f, 0.f, 0.f); collisionShape->calculateLocalInertia(mass, inertia); btRigidBody::btRigidBodyConstructionInfo constructInfo(mass, motionState, collisionShape, inertia); btRigidBody* player_rigid_body = new btRigidBody(constructInfo); player_rigid_body->setFriction(0.1f); player_rigid_body->setRollingFriction(0.8f); // FIXME doesn't do anything? Wrong collision mesh? player_rigid_body->setCcdMotionThreshold(0.05f); player_rigid_body->setCcdSweptSphereRadius(shape_extent.x); sim.dynamicsWorld->addRigidBody(player_rigid_body); sim.players.push_back(player_rigid_body); #else static_cast<void>(sim); static_cast<void>(player_transform); static_cast<void>(shape_extent); #endif } } // namespace SplineSonic
36.647643
120
0.658
Ryp
ff8e398156839678e8cc2b3641fc9024a31b7fba
1,270
hxx
C++
admin/cmdline/xcacls/filesec.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
admin/cmdline/xcacls/filesec.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
admin/cmdline/xcacls/filesec.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------- // // File: FILESEC.hxx // // Contents: class encapsulating file security. // // Classes: CFileSecurity // // History: Nov-93 Created DaveMont // Oct-96 Modified BrunoSc // //-------------------------------------------------------------------- #ifndef __FILESEC__ #define __FILESEC__ #include "t2.hxx" #include "daclwrap.hxx" //+------------------------------------------------------------------- // // Class: CFileSecurity // // Purpose: encapsulation of File security, this class wraps the // NT security descriptor for a file, allowing application // of a class that wraps DACLS to it, thus changing the // acces control on the file. // //-------------------------------------------------------------------- class CFileSecurity { public: CFileSecurity(LPWSTR filename); ~CFileSecurity(); ULONG Init(); // methods to actually set the security on the file ULONG SetFS(BOOL fmodify, CDaclWrap *pcdw, BOOL fdir); private: BYTE * _psd ; LPWSTR _pwfilename ; }; #endif // __FILESEC__
23.518519
72
0.444094
npocmaka
ff8f018c95f6afd999ea906b57ac9f7f3866b5b5
1,453
cpp
C++
questions/49850513/keypad.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
302
2017-03-04T00:05:23.000Z
2022-03-28T22:51:29.000Z
questions/49850513/keypad.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
30
2017-12-02T19:26:43.000Z
2022-03-28T07:40:36.000Z
questions/49850513/keypad.cpp
sesu089/stackoverflow
6fae69be6fa74fba9d554e6b5f387e5d3c1aad73
[ "MIT" ]
388
2017-07-04T16:53:12.000Z
2022-03-18T22:20:19.000Z
#include "keypad.h" #include <QApplication> #include <QCoreApplication> #include <QGridLayout> #include <QKeyEvent> #include <QToolButton> Keypad::Keypad(QWidget *parent) : QWidget{parent} { QGridLayout *lay = new QGridLayout{this}; const std::vector<Keys> keys = { {"1", Qt::Key_1}, {"2", Qt::Key_2}, {"3", Qt::Key_3}, {"4", Qt::Key_4}, {"5", Qt::Key_5}, {"6", Qt::Key_6}, {"7", Qt::Key_7}, {"8", Qt::Key_8}, {"9", Qt::Key_9}, {".", Qt::Key_Colon}, {"del", Qt::Key_Delete}, {"enter", Qt::Key_Return}}; for (unsigned int i = 0; i < keys.size(); i++) { QToolButton *button = new QToolButton; button->setFixedSize(64, 64); const Keys &_key = keys[i]; button->setText(_key.name); lay->addWidget(button, i / 3, i % 3); button->setProperty("key", _key.key); connect(button, &QToolButton::clicked, this, &Keypad::on_clicked); } } void Keypad::on_clicked() { QToolButton *button = qobject_cast<QToolButton *>(sender()); const QString &text = button->text(); int key = button->property("key").toInt(); QWidget *widget = QApplication::focusWidget(); if (text == "del") { QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, Qt::Key_A, Qt::ControlModifier, text); QCoreApplication::postEvent(widget, event); } QKeyEvent *event = new QKeyEvent(QEvent::KeyPress, key, Qt::NoModifier, text); QCoreApplication::postEvent(widget, event); }
34.595238
80
0.617343
sesu089
ff9250213626d9179509c8cd779d17b5770051d8
2,719
cpp
C++
source/backend/opengl/execution/GLPool.cpp
xindongzhang/MNN
f4740c78dc8fc67ee4596552d2257f12c48af067
[ "Apache-2.0" ]
1
2019-08-09T03:16:49.000Z
2019-08-09T03:16:49.000Z
source/backend/opengl/execution/GLPool.cpp
xindongzhang/MNN
f4740c78dc8fc67ee4596552d2257f12c48af067
[ "Apache-2.0" ]
null
null
null
source/backend/opengl/execution/GLPool.cpp
xindongzhang/MNN
f4740c78dc8fc67ee4596552d2257f12c48af067
[ "Apache-2.0" ]
1
2021-08-23T03:40:09.000Z
2021-08-23T03:40:09.000Z
// // GLPool.cpp // MNN // // Created by MNN on 2019/01/31. // Copyright © 2018, Alibaba Group Holding Limited // #include "GLPool.hpp" #include "AllShader.hpp" #include "GLBackend.hpp" #include "Macro.h" namespace MNN { namespace OpenGL { ErrorCode GLPool::onResize(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { auto inputTensor = inputs[0]; auto pool = mPool; if (!pool->isGlobal()) { int kx = pool->kernelX(); int ky = pool->kernelY(); int sx = pool->strideX(); int sy = pool->strideY(); int px = pool->padX(); int py = pool->padY(); mSetUniform = [=] { glUniform2i(2, kx, ky); glUniform2i(3, sx, sy); glUniform2i(4, px, py); }; } else { mSetUniform = [=] { glUniform2i(2, inputTensor->width(), inputTensor->height()); glUniform2i(3, 1, 1); glUniform2i(4, 0, 0); }; } return NO_ERROR; } ErrorCode GLPool::onExecute(const std::vector<Tensor *> &inputs, const std::vector<Tensor *> &outputs) { auto imageInput = inputs[0]->deviceId(); auto imageOutput = outputs[0]->deviceId(); auto outputTensor = outputs[0]; auto inputTensor = inputs[0]; MNN_ASSERT(mPoolProgram.get() != NULL); mPoolProgram->useProgram(); glBindImageTexture(0, imageInput, 0, GL_TRUE, 0, GL_READ_ONLY, TEXTURE_FORMAT); glBindImageTexture(1, imageOutput, 0, GL_TRUE, 0, GL_WRITE_ONLY, TEXTURE_FORMAT); mSetUniform(); glUniform3i(10, outputTensor->width(), outputTensor->height(), UP_DIV(outputTensor->channel(), 4)); glUniform3i(11, inputTensor->width(), inputTensor->height(), UP_DIV(inputTensor->channel(), 4)); OPENGL_CHECK_ERROR; auto depthQuad = UP_DIV(outputTensor->channel(), 4); ((GLBackend *)backend())->compute(UP_DIV(outputTensor->width(), 2), UP_DIV(outputTensor->height(), 2), UP_DIV(depthQuad, 16)); OPENGL_CHECK_ERROR; return NO_ERROR; } GLPool::~GLPool() { } GLPool::GLPool(const std::vector<Tensor *> &inputs, const Op *op, Backend *bn) : Execution(bn) { auto extra = (GLBackend *)bn; auto pool = op->main_as_Pool(); switch (pool->type()) { case PoolType_MAXPOOL: mPoolProgram = extra->getProgram("maxPool", glsl_maxpool_glsl); break; case PoolType_AVEPOOL: mPoolProgram = extra->getProgram("meanPool", glsl_avgpool_glsl); break; default: MNN_ASSERT(false); break; } mPool = pool; } GLCreatorRegister<TypedCreator<GLPool>> __pool_op(OpType_Pooling); } // namespace OpenGL } // namespace MNN
31.252874
130
0.606841
xindongzhang
ff93fd3e2be089421deaaa30ef0d89fdbc7dea88
491
cpp
C++
STL/algorithm/count.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
STL/algorithm/count.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
STL/algorithm/count.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
// count #include"iostream" #include"set" #include"algorithm" using namespace std; int main() { multiset<int,less<int> > intSet; intSet.insert(85); intSet.insert(90); intSet.insert(100); intSet.insert(85); intSet.insert(85); cout<<"Set: "; multiset<int,less<int> >::iterator it=intSet.begin(); for(int i=0;i<intSet.size();i++) cout<<*it++<<' '; cout<<endl; int cnt=count(intSet.begin(),intSet.end(),85); // 统计85分的数量 cout<<"85的数量为:"<<cnt<<endl; system("pause"); return 0; }
18.884615
59
0.653768
liangjisheng
ff9532bc79c7e9e4ecc0a96c35f0cd22712a079f
4,069
cpp
C++
Clank/src/cl/System/Logger.cpp
Repertoi-e/Clank
3f954f90af9853ca0a7ad6638efd3644c98c8d40
[ "MIT" ]
1
2017-08-03T15:04:33.000Z
2017-08-03T15:04:33.000Z
Clank/src/cl/System/Logger.cpp
Repertoi-e/Clank
3f954f90af9853ca0a7ad6638efd3644c98c8d40
[ "MIT" ]
null
null
null
Clank/src/cl/System/Logger.cpp
Repertoi-e/Clank
3f954f90af9853ca0a7ad6638efd3644c98c8d40
[ "MIT" ]
null
null
null
#include "cl/stdafx.h" #include "Logger.h" #include <filesystem> #include <cstddef> namespace cl { Logger& g_Logger = Logger::Instance(); void Logger::Start(void) { m_LogLevel = INFO; m_HConsole = GetStdHandle(STD_OUTPUT_HANDLE); Print(L"Starting Logging system...% % % %\n", 5, true, false, 4); SetLocale(LC_ALL); } void Logger::Shutdown(void) { Print(L"Shutting down Logging system...\n"); } void Logger::SetLocale(s32 locale) { const char* l = setlocale(locale, ""); //Print(!l ? "Locale not set\n" : "Locale set to %\n", l); } void Logger::SetLogLevel(LogLevel level) { m_LogLevel = level; } void Logger::PrintNumber(StringBuffer& buffer, u64 number, u64 base) { constexpr wchar* table = L"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_#"; ASSERT(base >= 2, "Invalid base!"); ASSERT(base <= 64, "Invalid base!"); constexpr u32 MAX_OUTPUT_LEN = 64; wchar output[MAX_OUTPUT_LEN]; wchar* end = &output[MAX_OUTPUT_LEN]; wchar* p = end; while (number) { u64 place = number % base; number /= base; p -= 1; *p = table[place]; } if (p == end) { p -= 1; *p = L'0'; } buffer.AppendString(p, u32(end - p)); } void Logger::HandleArgument(StringBuffer& buffer, const PrintArg& arg) { const std::any& value = arg.m_Value; switch (arg.m_Type) { case PrintArg::TypeEnum::INTEGER: { { FormatInt& formatInt = std::any_cast<FormatInt>(value); if (formatInt.m_Base == 10 && formatInt.m_Negative) buffer.AppendString(L"-"); PrintNumber(buffer, formatInt.m_IntegerValue, formatInt.m_Base); } break; } case PrintArg::TypeEnum::FLOAT: { FormatFloat& formatFloat = std::any_cast<FormatFloat>(value); wchar temp[512] = { 0 }; swprintf(temp, L"%*.*f", formatFloat.m_FieldWidth, formatFloat.m_Precision, formatFloat.m_FloatValue); buffer.AppendString(temp); } break; case PrintArg::TypeEnum::STRING: { SmartString& str = std::any_cast<SmartString>(value); buffer.AppendString(str.String); str.TryFree(); } break; case PrintArg::TypeEnum::BOOL: buffer.AppendString(std::any_cast<bool>(value) ? L"true" : L"false"); break; } } void Logger::PrintInternal(StringBuffer& buffer, const PrintArg* args, u32 argc) { const PrintArg& first = args[0]; if (u32 arg = 1; first.m_Type == PrintArg::TypeEnum::STRING) { SmartString& str = std::any_cast<SmartString>(first.m_Value); wchar* s = str.String; wchar* t = s; while (*t) { if (*t == L'%') { if (arg < argc) { buffer.AppendString(s, u32(t - s)); HandleArgument(buffer, args[arg]); t++; s = t; arg++; } } t++; } buffer.AppendString(s, u32(t - s)); str.TryFree(); } } void Logger::PrintSequenceInternal(StringBuffer& buffer, const PrintArg* args, u32 argc) { for (u32 arg = 0; arg < argc; arg++) HandleArgument(buffer, args[arg]); } void Logger::PrintColored(StringBuffer& buffer, LogLevel level) { switch (level) { case FATAL: SetConsoleTextAttribute(m_HConsole, BACKGROUND_RED | BACKGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY); break; case ERROR: SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_INTENSITY); break; case WARN: SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY); break; } wprintf(buffer.Data); SetConsoleTextAttribute(m_HConsole, FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_GREEN); } void PrintArg::HandleString(const char ch) { StringBuffer buffer; buffer.AppendChar(ch); m_Value = std::any(SmartString(buffer.Data, true)); } void PrintArg::HandleString(const char* str) { StringBuffer buffer; buffer.AppendString(str); m_Value = std::any(SmartString(buffer.Data, true)); } void PrintArg::HandlePrinter(const IPrintable& printable) { StringBuffer buffer; printable.Print(buffer); m_Value = std::any(SmartString(buffer.Data, true)); } }
21.529101
155
0.664783
Repertoi-e
910d156efe41482750f26a50252b38056131dfff
494
cpp
C++
src/ktlexcept.cpp
Shtan7/KTL
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
[ "MIT" ]
38
2020-12-16T22:12:50.000Z
2022-03-24T04:07:14.000Z
src/ktlexcept.cpp
Shtan7/KTL
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
[ "MIT" ]
165
2020-11-11T21:22:23.000Z
2022-03-26T14:30:40.000Z
src/ktlexcept.cpp
Shtan7/KTL
9c0adf8fac2f0bb481060b7bbb15b1356089af3c
[ "MIT" ]
5
2021-07-16T19:05:28.000Z
2021-12-22T11:46:42.000Z
#include <ktlexcept.hpp> #include <string.hpp> namespace ktl { NTSTATUS out_of_range::code() const noexcept { return STATUS_ARRAY_BOUNDS_EXCEEDED; } NTSTATUS range_error::code() const noexcept { return STATUS_RANGE_NOT_FOUND; } NTSTATUS overflow_error::code() const noexcept { return STATUS_BUFFER_OVERFLOW; } NTSTATUS kernel_error::code() const noexcept { return m_code; } NTSTATUS format_error::code() const noexcept { return STATUS_BAD_DESCRIPTOR_FORMAT; } } // namespace ktl
20.583333
48
0.771255
Shtan7
91191747f06046dd61ef2f8fef4f1f0bba7ec5b7
424
cpp
C++
day02/main.cpp
wuggy-ianw/AoC2017
138c66bdd407e76f6ad71c9d68df50e0afa2251a
[ "Unlicense" ]
null
null
null
day02/main.cpp
wuggy-ianw/AoC2017
138c66bdd407e76f6ad71c9d68df50e0afa2251a
[ "Unlicense" ]
null
null
null
day02/main.cpp
wuggy-ianw/AoC2017
138c66bdd407e76f6ad71c9d68df50e0afa2251a
[ "Unlicense" ]
null
null
null
// // Created by wuggy on 02/12/2017. // #include <fstream> #include "day02.h" #include "../utils/aocutils.h" int main() { std::ifstream ifs("input.txt"); std::vector< std::vector<std::size_t> > sheet = AOCUtils::parseByLines<std::vector<std::size_t> >(ifs, AOCUtils::parseItem<std::size_t>); std::cout << Day2::solve_part1(sheet) << std::endl; std::cout << Day2::solve_part2(sheet) << std::endl; return 0; }
21.2
139
0.648585
wuggy-ianw
911a1c6a0d88e064544f7d4f1bd5f6018918941a
62,837
cpp
C++
ds/security/services/w32time/w32tm/othercmds.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
ds/security/services/w32time/w32tm/othercmds.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
ds/security/services/w32time/w32tm/othercmds.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//depot/Lab03_N/DS/security/services/w32time/w32tm/OtherCmds.cpp#16 - edit change 15254 (text) //-------------------------------------------------------------------- // OtherCmds-implementation // Copyright (C) Microsoft Corporation, 1999 // // Created by: Louis Thomas (louisth), 2-17-00 // // Other useful w32tm commands // #include "pch.h" // precompiled headers #include <strsafe.h> //-------------------------------------------------------------------- //#################################################################### //## //## Copied from c run time and modified to be 64bit capable //## #include <crt\limits.h> /* flag values */ #define FL_UNSIGNED 1 /* wcstoul called */ #define FL_NEG 2 /* negative sign found */ #define FL_OVERFLOW 4 /* overflow occured */ #define FL_READDIGIT 8 /* we've read at least one correct digit */ MODULEPRIVATE unsigned __int64 my_wcstoxl (const WCHAR * nptr, WCHAR ** endptr, int ibase, int flags) { const WCHAR *p; WCHAR c; unsigned __int64 number; unsigned __int64 digval; unsigned __int64 maxval; p=nptr; /* p is our scanning pointer */ number=0; /* start with zero */ c=*p++; /* read char */ while (iswspace(c)) c=*p++; /* skip whitespace */ if (c=='-') { flags|=FL_NEG; /* remember minus sign */ c=*p++; } else if (c=='+') c=*p++; /* skip sign */ if (ibase<0 || ibase==1 || ibase>36) { /* bad base! */ if (endptr) /* store beginning of string in endptr */ *endptr=(wchar_t *)nptr; return 0L; /* return 0 */ } else if (ibase==0) { /* determine base free-lance, based on first two chars of string */ if (c != L'0') ibase=10; else if (*p==L'x' || *p==L'X') ibase=16; else ibase=8; } if (ibase==16) { /* we might have 0x in front of number; remove if there */ if (c==L'0' && (*p==L'x' || *p==L'X')) { ++p; c=*p++; /* advance past prefix */ } } /* if our number exceeds this, we will overflow on multiply */ maxval=_UI64_MAX / ibase; for (;;) { /* exit in middle of loop */ /* convert c to value */ if (iswdigit(c)) digval=c-L'0'; else if (iswalpha(c)) digval=(TCHAR)CharUpper((LPTSTR)c)-L'A'+10; else break; if (digval>=(unsigned)ibase) break; /* exit loop if bad digit found */ /* record the fact we have read one digit */ flags|=FL_READDIGIT; /* we now need to compute number=number*base+digval, but we need to know if overflow occured. This requires a tricky pre-check. */ if (number<maxval || (number==maxval && (unsigned __int64)digval<=_UI64_MAX%ibase)) { /* we won't overflow, go ahead and multiply */ number=number*ibase+digval; } else { /* we would have overflowed -- set the overflow flag */ flags|=FL_OVERFLOW; } c=*p++; /* read next digit */ } --p; /* point to place that stopped scan */ if (!(flags&FL_READDIGIT)) { /* no number there; return 0 and point to beginning of string */ if (endptr) /* store beginning of string in endptr later on */ p=nptr; number=0L; /* return 0 */ } else if ((flags&FL_OVERFLOW) || (!(flags&FL_UNSIGNED) && (((flags&FL_NEG) && (number>-_I64_MIN)) || (!(flags&FL_NEG) && (number>_I64_MAX))))) { /* overflow or signed overflow occurred */ //errno=ERANGE; if ( flags&FL_UNSIGNED ) number=_UI64_MAX; else if ( flags&FL_NEG ) number=(unsigned __int64)(-_I64_MIN); else number=_I64_MAX; } if (endptr != NULL) /* store pointer to char that stopped the scan */ *endptr=(wchar_t *)p; if (flags&FL_NEG) /* negate result if there was a neg sign */ number=(unsigned __int64)(-(__int64)number); return number; /* done. */ } MODULEPRIVATE unsigned __int64 wcstouI64(const WCHAR *nptr, WCHAR ** endptr, int ibase) { return my_wcstoxl(nptr, endptr, ibase, FL_UNSIGNED); } MODULEPRIVATE HRESULT my_wcstoul_safe(const WCHAR *wsz, ULONG ulMin, ULONG ulMax, ULONG *pulResult) { HRESULT hr; ULONG ulResult; WCHAR *wszLast; if (L'\0' == *wsz) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); _JumpError(hr, error, "my_wcstoul_safe: empty string is not valid"); } ulResult = wcstoul(wsz, &wszLast, 0); // Ensure that we were able to parse the whole string: if (wsz+wcslen(wsz) != wszLast) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); _JumpError(hr, error, "wcstoul"); } // Ensure that we lie within the bounds specified by the caler: if (!((ulMin <= ulResult) && (ulResult <= ulMax))) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_DATA); _JumpError(hr, error, "my_wcstoul_safe: result not within bounds"); } *pulResult = ulResult; hr = S_OK; error: return hr; } //#################################################################### //-------------------------------------------------------------------- HRESULT myHExceptionCode(EXCEPTION_POINTERS * pep) { HRESULT hr=pep->ExceptionRecord->ExceptionCode; if (!FAILED(hr)) { hr=HRESULT_FROM_WIN32(hr); } return hr; } //-------------------------------------------------------------------- // NOTE: this function is accessed through a hidden option, and does not need to be localized. void PrintNtpPeerInfo(W32TIME_NTP_PEER_INFO *pnpInfo) { LPWSTR pwszNULL = L"(null)"; wprintf(L"PEER: %s\n", pnpInfo->wszUniqueName ? pnpInfo->wszUniqueName : pwszNULL); wprintf(L"ulSize: %d\n", pnpInfo->ulSize); wprintf(L"ulResolveAttempts: %d\n", pnpInfo->ulResolveAttempts); wprintf(L"u64TimeRemaining: %I64u\n", pnpInfo->u64TimeRemaining); wprintf(L"u64LastSuccessfulSync: %I64u\n", pnpInfo->u64LastSuccessfulSync); wprintf(L"ulLastSyncError: 0x%08X\n", pnpInfo->ulLastSyncError); wprintf(L"ulLastSyncErrorMsgId: 0x%08X\n", pnpInfo->ulLastSyncErrorMsgId); wprintf(L"ulValidDataCounter: %d\n", pnpInfo->ulValidDataCounter); wprintf(L"ulAuthTypeMsgId: 0x%08X\n", pnpInfo->ulAuthTypeMsgId); wprintf(L"ulMode: %d\n", pnpInfo->ulMode); wprintf(L"ulStratum: %d\n", pnpInfo->ulStratum); wprintf(L"ulReachability: %d\n", pnpInfo->ulReachability); wprintf(L"ulPeerPollInterval: %d\n", pnpInfo->ulPeerPollInterval); wprintf(L"ulHostPollInterval: %d\n", pnpInfo->ulHostPollInterval); } //-------------------------------------------------------------------- // NOTE: this function is accessed through a hidden option, and does not need to be localized. void PrintNtpProviderData(W32TIME_NTP_PROVIDER_DATA *pNtpProviderData) { wprintf(L"ulSize: %d, ulError: 0x%08X, ulErrorMsgId: 0x%08X, cPeerInfo: %d\n", pNtpProviderData->ulSize, pNtpProviderData->ulError, pNtpProviderData->ulErrorMsgId, pNtpProviderData->cPeerInfo ); for (DWORD dwIndex = 0; dwIndex < pNtpProviderData->cPeerInfo; dwIndex++) { wprintf(L"\n"); PrintNtpPeerInfo(&(pNtpProviderData->pPeerInfo[dwIndex])); } } //-------------------------------------------------------------------- HRESULT PrintStr(HANDLE hOut, WCHAR * wszBuf) { return MyWriteConsole(hOut, wszBuf, wcslen(wszBuf)); } //-------------------------------------------------------------------- HRESULT Print(HANDLE hOut, WCHAR * wszFormat, ...) { HRESULT hr; WCHAR wszBuf[1024]; va_list vlArgs; va_start(vlArgs, wszFormat); // print the formatted data to our buffer: hr=StringCchVPrintf(wszBuf, ARRAYSIZE(wszBuf), wszFormat, vlArgs); va_end(vlArgs); if (SUCCEEDED(hr)) { // only print the string if our vprintf was successful: hr = PrintStr(hOut, wszBuf); } return hr; } //-------------------------------------------------------------------- MODULEPRIVATE HRESULT PrintNtTimeAsLocalTime(HANDLE hOut, unsigned __int64 qwTime) { HRESULT hr; FILETIME ftLocal; SYSTEMTIME stLocal; unsigned int nChars; // must be cleaned up WCHAR * wszDate=NULL; WCHAR * wszTime=NULL; if (!FileTimeToLocalFileTime((FILETIME *)(&qwTime), &ftLocal)) { _JumpLastError(hr, error, "FileTimeToLocalFileTime"); } if (!FileTimeToSystemTime(&ftLocal, &stLocal)) { _JumpLastError(hr, error, "FileTimeToSystemTime"); } nChars=GetDateFormat(NULL, 0, &stLocal, NULL, NULL, 0); if (0==nChars) { _JumpLastError(hr, error, "GetDateFormat"); } wszDate=(WCHAR *)LocalAlloc(LPTR, nChars*sizeof(WCHAR)); _JumpIfOutOfMemory(hr, error, wszDate); nChars=GetDateFormat(NULL, 0, &stLocal, NULL, wszDate, nChars); if (0==nChars) { _JumpLastError(hr, error, "GetDateFormat"); } nChars=GetTimeFormat(NULL, 0, &stLocal, NULL, NULL, 0); if (0==nChars) { _JumpLastError(hr, error, "GetTimeFormat"); } wszTime=(WCHAR *)LocalAlloc(LPTR, nChars*sizeof(WCHAR)); _JumpIfOutOfMemory(hr, error, wszTime); nChars=GetTimeFormat(NULL, 0, &stLocal, NULL, wszTime, nChars); if (0==nChars) { _JumpLastError(hr, error, "GetTimeFormat"); } Print(hOut, L"%s %s (local time)", wszDate, wszTime); hr=S_OK; error: if (NULL!=wszDate) { LocalFree(wszDate); } if (NULL!=wszTime) { LocalFree(wszTime); } return hr; } //-------------------------------------------------------------------- void PrintNtTimePeriod(HANDLE hOut, NtTimePeriod tp) { Print(hOut, L"%02I64u.%07I64us", tp.qw/10000000,tp.qw%10000000); } //-------------------------------------------------------------------- void PrintNtTimeOffset(HANDLE hOut, NtTimeOffset to) { NtTimePeriod tp; if (to.qw<0) { PrintStr(hOut, L"-"); tp.qw=(unsigned __int64)-to.qw; } else { PrintStr(hOut, L"+"); tp.qw=(unsigned __int64)to.qw; } PrintNtTimePeriod(hOut, tp); } //#################################################################### //-------------------------------------------------------------------- void PrintHelpOtherCmds(void) { DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_OTHERCMD_HELP); } //-------------------------------------------------------------------- HRESULT PrintNtte(CmdArgs * pca) { HRESULT hr; unsigned __int64 qwTime; HANDLE hOut; // must be cleaned up WCHAR * wszDate=NULL; WCHAR * wszTime=NULL; if (pca->nNextArg!=pca->nArgs-1) { if (pca->nNextArg==pca->nArgs) { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_MISSING_PARAM); } else { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_TOO_MANY_PARAMS); } hr=E_INVALIDARG; _JumpError(hr, error, "(command line parsing)"); } qwTime=wcstouI64(pca->rgwszArgs[pca->nNextArg], NULL, 0); { unsigned __int64 qwTemp=qwTime; DWORD dwNanoSecs=(DWORD)(qwTemp%10000000); qwTemp/=10000000; DWORD dwSecs=(DWORD)(qwTemp%60); qwTemp/=60; DWORD dwMins=(DWORD)(qwTemp%60); qwTemp/=60; DWORD dwHours=(DWORD)(qwTemp%24); DWORD dwDays=(DWORD)(qwTemp/24); DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_NTTE, dwDays, dwHours, dwMins, dwSecs, dwNanoSecs); } hOut=GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE==hOut) { _JumpLastError(hr, error, "GetStdHandle"); } hr=PrintNtTimeAsLocalTime(hOut, qwTime); if (FAILED(hr)) { if (HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)==hr) { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_INVALID_LOCALTIME); } else { _JumpError(hr, error, "PrintNtTimeAsLocalTime"); } } wprintf(L"\n"); hr=S_OK; error: if (NULL!=wszDate) { LocalFree(wszDate); } if (NULL!=wszTime) { LocalFree(wszTime); } return hr; } //-------------------------------------------------------------------- HRESULT PrintNtpte(CmdArgs * pca) { HRESULT hr; unsigned __int64 qwTime; HANDLE hOut; // must be cleaned up WCHAR * wszDate=NULL; WCHAR * wszTime=NULL; if (pca->nNextArg!=pca->nArgs-1) { if (pca->nNextArg==pca->nArgs) { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_MISSING_PARAM); } else { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_TOO_MANY_PARAMS); } hr=E_INVALIDARG; _JumpError(hr, error, "(command line parsing)"); } qwTime=wcstouI64(pca->rgwszArgs[pca->nNextArg], NULL, 0); { NtpTimeEpoch teNtp={qwTime}; qwTime=NtTimeEpochFromNtpTimeEpoch(teNtp).qw; unsigned __int64 qwTemp=qwTime; DWORD dwNanoSecs=(DWORD)(qwTemp%10000000); qwTemp/=10000000; DWORD dwSecs=(DWORD)(qwTemp%60); qwTemp/=60; DWORD dwMins=(DWORD)(qwTemp%60); qwTemp/=60; DWORD dwHours=(DWORD)(qwTemp%24); DWORD dwDays=(DWORD)(qwTemp/24); DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_NTPTE, qwTime, dwDays, dwHours, dwMins, dwSecs, dwNanoSecs); } hOut=GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE==hOut) { _JumpLastError(hr, error, "GetStdHandle") } hr=PrintNtTimeAsLocalTime(hOut, qwTime); if (FAILED(hr)) { if (HRESULT_FROM_WIN32(ERROR_INVALID_PARAMETER)==hr) { LocalizedWPrintf(IDS_W32TM_ERRORGENERAL_INVALID_LOCALTIME); } else { _JumpError(hr, error, "PrintNtTimeAsLocalTime"); } } wprintf(L"\n"); hr=S_OK; error: if (NULL!=wszDate) { LocalFree(wszDate); } if (NULL!=wszTime) { LocalFree(wszTime); } return hr; } //-------------------------------------------------------------------- // NOTE: this function is accessed through a hidden option, and does not need to be localized. HRESULT SysExpr(CmdArgs * pca) { HRESULT hr; unsigned __int64 qwExprDate; HANDLE hOut; hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); hOut=GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE==hOut) { _JumpLastError(hr, error, "GetStdHandle") } GetSysExpirationDate(&qwExprDate); wprintf(L"0x%016I64X - ", qwExprDate); if (0==qwExprDate) { wprintf(L"no expiration date\n"); } else { hr=PrintNtTimeAsLocalTime(hOut, qwExprDate); _JumpIfError(hr, error, "PrintNtTimeAsLocalTime") wprintf(L"\n"); } hr=S_OK; error: return hr; } //-------------------------------------------------------------------- HRESULT ResyncCommand(CmdArgs * pca) { HANDLE hTimeSlipEvent = NULL; HRESULT hr; WCHAR * wszComputer=NULL; WCHAR * wszComputerDisplay; bool bUseDefaultErrorPrinting = false; bool bHard=true; bool bNoWait=false; bool bRediscover=false; unsigned int nArgID; DWORD dwResult; DWORD dwSyncFlags=0; // must be cleaned up WCHAR * wszError=NULL; // find out what computer to resync if (FindArg(pca, L"computer", &wszComputer, &nArgID)) { MarkArgUsed(pca, nArgID); } wszComputerDisplay=wszComputer; if (NULL==wszComputerDisplay) { wszComputerDisplay=L"local computer"; } // find out if we need to use the w32tm named timeslip event to resync if (FindArg(pca, L"event", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); hTimeSlipEvent = OpenEvent(EVENT_MODIFY_STATE, FALSE, W32TIME_NAMED_EVENT_SYSTIME_NOT_CORRECT); if (NULL == hTimeSlipEvent) { bUseDefaultErrorPrinting = true; _JumpLastError(hr, error, "OpenEvent"); } if (!SetEvent(hTimeSlipEvent)) { bUseDefaultErrorPrinting = true; _JumpLastError(hr, error, "SetEvent"); } } else { // find out if we need to do a soft resync if (FindArg(pca, L"soft", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); dwSyncFlags = TimeSyncFlag_SoftResync; } else if (FindArg(pca, L"update", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); dwSyncFlags = TimeSyncFlag_UpdateAndResync; } else if (FindArg(pca, L"rediscover", NULL, &nArgID)) { // find out if we need to do a rediscover MarkArgUsed(pca, nArgID); dwSyncFlags = TimeSyncFlag_Rediscover; } else { dwSyncFlags = TimeSyncFlag_HardResync; } // find out if we don't want to wait if (FindArg(pca, L"nowait", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); bNoWait=true; } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); if (bRediscover && !bHard) { LocalizedWPrintfCR(IDS_W32TM_WARN_IGNORE_SOFT); } LocalizedWPrintf2(IDS_W32TM_STATUS_SENDING_RESYNC_TO, L" %s...\n", wszComputerDisplay); dwResult=W32TimeSyncNow(wszComputer, !bNoWait, TimeSyncFlag_ReturnResult | dwSyncFlags); if (ResyncResult_Success==dwResult) { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_COMMAND_SUCCESSFUL); } else if (ResyncResult_NoData==dwResult) { LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_NO_TIME_DATA); } else if (ResyncResult_StaleData==dwResult) { LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_STALE_DATA); } else if (ResyncResult_Shutdown==dwResult) { LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_SHUTTING_DOWN); } else if (ResyncResult_ChangeTooBig==dwResult) { LocalizedWPrintfCR(IDS_W32TM_ERRORRESYNC_CHANGE_TOO_BIG); } else { bUseDefaultErrorPrinting = true; hr = HRESULT_FROM_WIN32(dwResult); _JumpError(hr, error, "W32TimeSyncNow"); } } hr=S_OK; error: if (FAILED(hr)) { HRESULT hr2 = GetSystemErrorString(hr, &wszError); _IgnoreIfError(hr2, "GetSystemErrorString"); if (SUCCEEDED(hr2)) { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); } } if (NULL!=hTimeSlipEvent) { CloseHandle(hTimeSlipEvent); } if (NULL!=wszError) { LocalFree(wszError); } return hr; } //-------------------------------------------------------------------- HRESULT Stripchart(CmdArgs * pca) { HRESULT hr; WCHAR * wszParam; WCHAR * wszComputer; bool bDataOnly=false; unsigned int nArgID; unsigned int nIpAddrs; TIME_ZONE_INFORMATION timezoneinfo; signed __int64 nFullTzBias; DWORD dwTimeZoneMode; DWORD dwSleepSeconds; HANDLE hOut; bool bDontRunForever=false; unsigned int nSamples=0; NtTimeEpoch teNow; // must be cleaned up bool bSocketLayerOpened=false; in_addr * rgiaLocalIpAddrs=NULL; in_addr * rgiaRemoteIpAddrs=NULL; // find out what computer to watch if (FindArg(pca, L"computer", &wszComputer, &nArgID)) { MarkArgUsed(pca, nArgID); } else { LocalizedWPrintfCR(IDS_W32TM_ERRORPARAMETER_COMPUTER_MISSING); hr=E_INVALIDARG; _JumpError(hr, error, "command line parsing"); } // find out how often to watch if (FindArg(pca, L"period", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); dwSleepSeconds=wcstoul(wszParam, NULL, 0); if (dwSleepSeconds<1) { dwSleepSeconds=1; } } else { dwSleepSeconds=2; } // find out if we want a limited number of samples if (FindArg(pca, L"samples", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); bDontRunForever=true; nSamples=wcstoul(wszParam, NULL, 0); } // find out if we only want to dump data if (FindArg(pca, L"dataonly", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); bDataOnly=true; } // redirect to file handled via stdout hOut=GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE==hOut) { _JumpLastError(hr, error, "GetStdHandle") } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); dwTimeZoneMode=GetTimeZoneInformation(&timezoneinfo); if (TIME_ZONE_ID_INVALID==dwTimeZoneMode) { _JumpLastError(hr, error, "GetTimeZoneInformation"); } else if (TIME_ZONE_ID_DAYLIGHT==dwTimeZoneMode) { nFullTzBias=(signed __int64)(timezoneinfo.Bias+timezoneinfo.DaylightBias); } else { nFullTzBias=(signed __int64)(timezoneinfo.Bias+timezoneinfo.StandardBias); } nFullTzBias*=600000000; // convert to from minutes to 10^-7s hr=OpenSocketLayer(); _JumpIfError(hr, error, "OpenSocketLayer"); bSocketLayerOpened=true; hr=MyGetIpAddrs(wszComputer, &rgiaLocalIpAddrs, &rgiaRemoteIpAddrs, &nIpAddrs, NULL); _JumpIfError(hr, error, "MyGetIpAddrs"); // write out who we are tracking Print(hOut, L"Tracking %s [%u.%u.%u.%u].\n", wszComputer, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b1, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b2, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b3, rgiaRemoteIpAddrs[0].S_un.S_un_b.s_b4); if (bDontRunForever) { Print(hOut, L"Collecting %u samples.\n", nSamples); } // Write out the current time in full, since we will be using abbreviations later. PrintStr(hOut, L"The current time is "); AccurateGetSystemTime(&teNow.qw); PrintNtTimeAsLocalTime(hOut, teNow.qw); PrintStr(hOut, L".\n"); while (false==bDontRunForever || nSamples>0) { const DWORD c_dwTimeout=1000; NtpPacket npPacket; NtTimeEpoch teDestinationTimestamp; DWORD dwSecs; DWORD dwMins; DWORD dwHours; signed int nMsMin=-10000; signed int nMsMax=10000; unsigned int nGraphWidth=55; AccurateGetSystemTime(&teNow.qw); teNow.qw-=nFullTzBias; teNow.qw/=10000000; dwSecs=(DWORD)(teNow.qw%60); teNow.qw/=60; dwMins=(DWORD)(teNow.qw%60); teNow.qw/=60; dwHours=(DWORD)(teNow.qw%24); if (!bDataOnly) { Print(hOut, L"%02u:%02u:%02u ", dwHours, dwMins, dwSecs); } else { Print(hOut, L"%02u:%02u:%02u, ", dwHours, dwMins, dwSecs); } hr=MyNtpPing(&(rgiaRemoteIpAddrs[0]), c_dwTimeout, &npPacket, &teDestinationTimestamp); if (FAILED(hr)) { Print(hOut, L"error: 0x%08X", hr); } else { // calculate the offset NtTimeEpoch teOriginateTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teOriginateTimestamp); NtTimeEpoch teReceiveTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teReceiveTimestamp); NtTimeEpoch teTransmitTimestamp=NtTimeEpochFromNtpTimeEpoch(npPacket.teTransmitTimestamp); NtTimeOffset toLocalClockOffset= (teReceiveTimestamp-teOriginateTimestamp) + (teTransmitTimestamp-teDestinationTimestamp); toLocalClockOffset/=2; // calculate the delay NtTimeOffset toRoundtripDelay= (teDestinationTimestamp-teOriginateTimestamp) - (teTransmitTimestamp-teReceiveTimestamp); if (!bDataOnly) { PrintStr(hOut, L"d:"); PrintNtTimeOffset(hOut, toRoundtripDelay); PrintStr(hOut, L" o:"); PrintNtTimeOffset(hOut, toLocalClockOffset); } else { PrintNtTimeOffset(hOut, toLocalClockOffset); } // draw graph if (!bDataOnly) { unsigned int nSize=nMsMax-nMsMin+1; double dRatio=((double)nGraphWidth)/nSize; signed int nPoint=(signed int)(toLocalClockOffset.qw/10000); bool bOutOfRange=false; if (nPoint>nMsMax) { nPoint=nMsMax; bOutOfRange=true; } else if (nPoint<nMsMin) { nPoint=nMsMin; bOutOfRange=true; } unsigned int nLeftOffset=(unsigned int)((nPoint-nMsMin)*dRatio); unsigned int nZeroOffset=(unsigned int)((0-nMsMin)*dRatio); PrintStr(hOut, L" ["); unsigned int nIndex; for (nIndex=0; nIndex<nGraphWidth; nIndex++) { if (nIndex==nLeftOffset) { if (bOutOfRange) { PrintStr(hOut, L"@"); } else { PrintStr(hOut, L"*"); } } else if (nIndex==nZeroOffset) { PrintStr(hOut, L"|"); } else { PrintStr(hOut, L" "); } } PrintStr(hOut, L"]"); } // <- end drawing graph } // <- end if sample received PrintStr(hOut, L"\n"); nSamples--; if (0!=nSamples) { Sleep(dwSleepSeconds*1000); } } // <- end sample collection loop hr=S_OK; error: if (NULL!=rgiaLocalIpAddrs) { LocalFree(rgiaLocalIpAddrs); } if (NULL!=rgiaRemoteIpAddrs) { LocalFree(rgiaRemoteIpAddrs); } if (bSocketLayerOpened) { HRESULT hr2=CloseSocketLayer(); _TeardownError(hr, hr2, "CloseSocketLayer"); } if (FAILED(hr)) { WCHAR * wszError; HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); LocalFree(wszError); } } return hr; } //-------------------------------------------------------------------- HRESULT Config(CmdArgs * pca) { HRESULT hr; DWORD dwRetval; WCHAR * wszParam; WCHAR * wszComputer; unsigned int nArgID; bool bManualPeerList=false; bool bUpdate=false; bool bSyncFromFlags=false; bool bLocalClockDispersion=false; bool bReliable=false; bool bLargePhaseOffset=false; unsigned int nManualPeerListLenBytes=0; DWORD dwSyncFromFlags=0; DWORD dwLocalClockDispersion; DWORD dwAnnounceFlags; DWORD dwLargePhaseOffset; // must be cleaned up WCHAR * mwszManualPeerList=NULL; HKEY hkLMRemote=NULL; HKEY hkW32TimeConfig=NULL; HKEY hkW32TimeParameters=NULL; SC_HANDLE hSCM=NULL; SC_HANDLE hTimeService=NULL; // find out what computer to talk to if (FindArg(pca, L"computer", &wszComputer, &nArgID)) { MarkArgUsed(pca, nArgID); } else { // modifying local computer wszComputer=NULL; } // find out if we want to notify the service if (FindArg(pca, L"update", NULL, &nArgID)) { MarkArgUsed(pca, nArgID); bUpdate=true; } // see if they want to change the manual peer list if (FindArg(pca, L"manualpeerlist", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); nManualPeerListLenBytes=(wcslen(wszParam)+1)*sizeof(WCHAR); mwszManualPeerList=(WCHAR *)LocalAlloc(LPTR, nManualPeerListLenBytes); _JumpIfOutOfMemory(hr, error, mwszManualPeerList); hr = StringCbCopy(mwszManualPeerList, nManualPeerListLenBytes, wszParam); _JumpIfError(hr, error, "StringCbCopy"); bManualPeerList=true; } // see if they want to change the syncfromflags if (FindArg(pca, L"syncfromflags", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); // find keywords in the string dwSyncFromFlags=0; WCHAR * wszKeyword=wszParam; bool bLastKeyword=false; while (false==bLastKeyword) { WCHAR * wszNext=wcschr(wszKeyword, L','); if (NULL==wszNext) { bLastKeyword=true; } else { wszNext[0]=L'\0'; wszNext++; } if (L'\0'==wszKeyword[0]) { // 'empty' keyword - no changes, but can be used to sync from nowhere. } else if (0==_wcsicmp(L"manual", wszKeyword)) { dwSyncFromFlags|=NCSF_ManualPeerList; } else if (0==_wcsicmp(L"domhier", wszKeyword)) { dwSyncFromFlags|=NCSF_DomainHierarchy; } else { LocalizedWPrintf2(IDS_W32TM_ERRORPARAMETER_UNKNOWN_PARAMETER_SYNCFROMFLAGS, L" '%s'.\n", wszKeyword); hr=E_INVALIDARG; _JumpError(hr, error, "command line parsing"); } wszKeyword=wszNext; } bSyncFromFlags=true; } // see if they want to change the local clock dispersion if (FindArg(pca, L"localclockdispersion", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); hr = my_wcstoul_safe(wszParam, 0, 16, &dwLocalClockDispersion); if (FAILED(hr)) { DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_BAD_NUMERIC_INPUT_VALUE, L"localclockdispersion", 0, 16); hr = E_INVALIDARG; _JumpError(hr, error, "Config: bad large phase offset"); } bLocalClockDispersion=true; } if (FindArg(pca, L"reliable", &wszParam, &nArgID)) { dwAnnounceFlags=0; if (0 == _wcsicmp(L"YES", wszParam)) { dwAnnounceFlags=Timeserv_Announce_Yes | Reliable_Timeserv_Announce_Yes; } else if (0 == _wcsicmp(L"NO", wszParam)) { dwAnnounceFlags=Timeserv_Announce_Auto | Reliable_Timeserv_Announce_Auto; } if (dwAnnounceFlags) { MarkArgUsed(pca, nArgID); bReliable=true; } } if (FindArg(pca, L"largephaseoffset", &wszParam, &nArgID)) { MarkArgUsed(pca, nArgID); // Command-line tool takes argument in millis, registry value is stored in 10^-7 second units. hr = my_wcstoul_safe(wszParam, 0, 120000, &dwLargePhaseOffset); if (FAILED(hr)) { DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_BAD_NUMERIC_INPUT_VALUE, L"largephaseoffset", 0, 120000); hr = E_INVALIDARG; _JumpError(hr, error, "Config: bad large phase offset"); } dwLargePhaseOffset*=10000; // scale: user input (milliseconds) --> NT time (10^-7 seconds) bLargePhaseOffset=true; } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); if (!bManualPeerList && !bSyncFromFlags && !bUpdate && !bLocalClockDispersion && !bReliable && !bLargePhaseOffset) { LocalizedWPrintfCR(IDS_W32TM_ERRORCONFIG_NO_CHANGE_SPECIFIED); hr=E_INVALIDARG; _JumpError(hr, error, "command line parsing"); } // make registry changes if (bManualPeerList || bSyncFromFlags || bLocalClockDispersion || bReliable || bLargePhaseOffset) { // open the key dwRetval=RegConnectRegistry(wszComputer, HKEY_LOCAL_MACHINE, &hkLMRemote); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegConnectRegistry"); } // set "w32time\parameters" reg values if (bManualPeerList || bSyncFromFlags) { dwRetval=RegOpenKey(hkLMRemote, wszW32TimeRegKeyParameters, &hkW32TimeParameters); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegOpenKey"); } if (bManualPeerList) { dwRetval=RegSetValueEx(hkW32TimeParameters, wszW32TimeRegValueNtpServer, 0, REG_SZ, (BYTE *)mwszManualPeerList, nManualPeerListLenBytes); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegSetValueEx"); } } if (bSyncFromFlags) { LPWSTR pwszType; switch (dwSyncFromFlags) { case NCSF_NoSync: pwszType = W32TM_Type_NoSync; break; case NCSF_ManualPeerList: pwszType = W32TM_Type_NTP; break; case NCSF_DomainHierarchy: pwszType = W32TM_Type_NT5DS; break; case NCSF_ManualAndDomhier: pwszType = W32TM_Type_AllSync; break; default: hr = E_NOTIMPL; _JumpError(hr, error, "SyncFromFlags not supported."); } dwRetval=RegSetValueEx(hkW32TimeParameters, wszW32TimeRegValueType, 0, REG_SZ, (BYTE *)pwszType, (wcslen(pwszType)+1) * sizeof(WCHAR)); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegSetValueEx"); } } } if (bLocalClockDispersion || bReliable || bLargePhaseOffset) { dwRetval=RegOpenKey(hkLMRemote, wszW32TimeRegKeyConfig, &hkW32TimeConfig); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegOpenKey"); } if (bLocalClockDispersion) { dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueLocalClockDispersion, 0, REG_DWORD, (BYTE *)&dwLocalClockDispersion, sizeof(dwLocalClockDispersion)); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegSetValueEx"); } } if (bReliable) { dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueAnnounceFlags, 0, REG_DWORD, (BYTE *)&dwAnnounceFlags, sizeof(dwAnnounceFlags)); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegSetValueEx"); } } if (bLargePhaseOffset) { dwRetval=RegSetValueEx(hkW32TimeConfig, wszW32TimeRegValueLargePhaseOffset, 0, REG_DWORD, (BYTE *)&dwLargePhaseOffset, sizeof(dwLargePhaseOffset)); if (ERROR_SUCCESS!=dwRetval) { hr=HRESULT_FROM_WIN32(dwRetval); _JumpError(hr, error, "RegSetValueEx"); } } } } // send service message if (bUpdate) { SERVICE_STATUS servicestatus; hSCM=OpenSCManager(wszComputer, SERVICES_ACTIVE_DATABASE, SC_MANAGER_CONNECT); if (NULL==hSCM) { _JumpLastError(hr, error, "OpenSCManager"); } hTimeService=OpenService(hSCM, L"w32time", SERVICE_PAUSE_CONTINUE); if (NULL==hTimeService) { _JumpLastError(hr, error, "OpenService"); } if (!ControlService(hTimeService, SERVICE_CONTROL_PARAMCHANGE, &servicestatus)) { _JumpLastError(hr, error, "ControlService"); } } hr=S_OK; error: if (NULL!=mwszManualPeerList) { LocalFree(mwszManualPeerList); } if (NULL!=hkW32TimeConfig) { RegCloseKey(hkW32TimeConfig); } if (NULL!=hkW32TimeParameters) { RegCloseKey(hkW32TimeParameters); } if (NULL!=hkLMRemote) { RegCloseKey(hkLMRemote); } if (NULL!=hTimeService) { CloseServiceHandle(hTimeService); } if (NULL!=hSCM) { CloseServiceHandle(hSCM); } if (FAILED(hr) && E_INVALIDARG!=hr) { WCHAR * wszError; HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); LocalFree(wszError); } } else if (S_OK==hr) { LocalizedWPrintfCR(IDS_W32TM_ERRORGENERAL_COMMAND_SUCCESSFUL); } return hr; } //-------------------------------------------------------------------- // NOTE: this function is accessed through a hidden option, and does not need to be localized. HRESULT TestInterface(CmdArgs * pca) { HRESULT hr; WCHAR * wszComputer=NULL; WCHAR * wszComputerDisplay; unsigned int nArgID; DWORD dwResult; unsigned long ulBits; void (* pfnW32TimeVerifyJoinConfig)(void); void (* pfnW32TimeVerifyUnjoinConfig)(void); // must be cleaned up WCHAR * wszError=NULL; HMODULE hmW32Time=NULL; // check for gnsb (get netlogon service bits) if (true==CheckNextArg(pca, L"gnsb", NULL)) { // find out what computer to resync if (FindArg(pca, L"computer", &wszComputer, &nArgID)) { MarkArgUsed(pca, nArgID); } wszComputerDisplay=wszComputer; if (NULL==wszComputerDisplay) { wszComputerDisplay=L"local computer"; } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); LocalizedWPrintf2(IDS_W32TM_STATUS_CALLING_GETNETLOGONBITS_ON, L" %s.\n", wszComputerDisplay); dwResult=W32TimeGetNetlogonServiceBits(wszComputer, &ulBits); if (S_OK==dwResult) { wprintf(L"Bits: 0x%08X\n", ulBits); } else { hr=GetSystemErrorString(HRESULT_FROM_WIN32(dwResult), &wszError); _JumpIfError(hr, error, "GetSystemErrorString"); LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); } // check for vjc (verify join config) } else if (true==CheckNextArg(pca, L"vjc", NULL)) { hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); LocalizedWPrintfCR(IDS_W32TM_STATUS_CALLING_JOINCONFIG); hmW32Time=LoadLibrary(wszDLLNAME); if (NULL==hmW32Time) { _JumpLastError(hr, vjcerror, "LoadLibrary"); } pfnW32TimeVerifyJoinConfig=(void (*)(void))GetProcAddress(hmW32Time, "W32TimeVerifyJoinConfig"); if (NULL==pfnW32TimeVerifyJoinConfig) { _JumpLastErrorStr(hr, vjcerror, "GetProcAddress", L"W32TimeVerifyJoinConfig"); } _BeginTryWith(hr) { pfnW32TimeVerifyJoinConfig(); } _TrapException(hr); _JumpIfError(hr, vjcerror, "pfnW32TimeVerifyJoinConfig"); hr=S_OK; vjcerror: if (FAILED(hr)) { HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); } goto error; } // check for vuc (verify unjoin config) } else if (true==CheckNextArg(pca, L"vuc", NULL)) { hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); LocalizedWPrintfCR(IDS_W32TM_STATUS_CALLING_UNJOINCONFIG); hmW32Time=LoadLibrary(wszDLLNAME); if (NULL==hmW32Time) { _JumpLastError(hr, vucerror, "LoadLibrary"); } pfnW32TimeVerifyUnjoinConfig=(void (*)(void))GetProcAddress(hmW32Time, "W32TimeVerifyUnjoinConfig"); if (NULL==pfnW32TimeVerifyUnjoinConfig) { _JumpLastErrorStr(hr, vucerror, "GetProcAddress", L"W32TimeVerifyJoinConfig"); } _BeginTryWith(hr) { pfnW32TimeVerifyUnjoinConfig(); } _TrapException(hr); _JumpIfError(hr, vucerror, "pfnW32TimeVerifyUnjoinConfig"); hr=S_OK; vucerror: if (FAILED(hr)) { HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); } goto error; } // error out appropriately } else if (true==CheckNextArg(pca, L"qps", NULL)) { // find out what computer to resync if (FindArg(pca, L"computer", &wszComputer, &nArgID)) { MarkArgUsed(pca, nArgID); } wszComputerDisplay=wszComputer; if (NULL==wszComputerDisplay) { wszComputerDisplay=L"local computer"; } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); //LocalizedWPrintf2(IDS_W32TM_STATUS_CALLING_GETNETLOGONBITS_ON, L" %s.\n", wszComputerDisplay); { W32TIME_NTP_PROVIDER_DATA *ProviderInfo = NULL; dwResult=W32TimeQueryNTPProviderStatus(wszComputer, 0, L"NtpClient", &ProviderInfo); if (S_OK==dwResult) { PrintNtpProviderData(ProviderInfo); } else { hr=GetSystemErrorString(HRESULT_FROM_WIN32(dwResult), &wszError); _JumpIfError(hr, error, "GetSystemErrorString"); LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); } } } else { hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); LocalizedWPrintf(IDS_W32TM_ERRORGENERAL_NOINTERFACE); hr=E_INVALIDARG; _JumpError(hr, error, "command line parsing"); } hr=S_OK; error: if (NULL!=hmW32Time) { FreeLibrary(hmW32Time); } if (NULL!=wszError) { LocalFree(wszError); } return hr; } //-------------------------------------------------------------------- HRESULT ShowTimeZone(CmdArgs * pca) { DWORD dwTimeZoneID; HRESULT hr; LPWSTR pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED = NULL; LPWSTR pwsz_IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE = NULL; LPWSTR pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT = NULL; LPWSTR pwsz_IDS_W32TM_TIMEZONE_STANDARD = NULL; LPWSTR pwsz_IDS_W32TM_TIMEZONE_UNKNOWN = NULL; LPWSTR wszDaylightDate = NULL; LPWSTR wszStandardDate = NULL; LPWSTR wszTimeZoneId = NULL; TIME_ZONE_INFORMATION tzi; // Load the strings we'll need struct LocalizedStrings { UINT id; LPWSTR *ppwsz; } rgStrings[] = { { IDS_W32TM_SIMPLESTRING_UNSPECIFIED, &pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED }, { IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE, &pwsz_IDS_W32TM_TIMEZONE_CURRENT_TIMEZONE }, { IDS_W32TM_TIMEZONE_DAYLIGHT, &pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT }, { IDS_W32TM_TIMEZONE_STANDARD, &pwsz_IDS_W32TM_TIMEZONE_STANDARD }, { IDS_W32TM_TIMEZONE_UNKNOWN, &pwsz_IDS_W32TM_TIMEZONE_UNKNOWN } }; for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, rgStrings[dwIndex].id, rgStrings[dwIndex].ppwsz)) { hr = HRESULT_FROM_WIN32(GetLastError()); _JumpError(hr, error, "WriteMsg"); } } hr=VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); dwTimeZoneID=GetTimeZoneInformation(&tzi); switch (dwTimeZoneID) { case TIME_ZONE_ID_DAYLIGHT: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_DAYLIGHT; break; case TIME_ZONE_ID_STANDARD: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_STANDARD; break; case TIME_ZONE_ID_UNKNOWN: wszTimeZoneId = pwsz_IDS_W32TM_TIMEZONE_UNKNOWN; break; default: hr = HRESULT_FROM_WIN32(GetLastError()); LocalizedWPrintfCR(IDS_W32TM_ERRORTIMEZONE_INVALID); _JumpError(hr, error, "GetTimeZoneInformation") } // Construct a string representing the "StandardDate" field of the TimeZoneInformation: if (0==tzi.StandardDate.wMonth) { wszStandardDate = pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED; } else if (tzi.StandardDate.wMonth>12 || tzi.StandardDate.wDay>5 || tzi.StandardDate.wDay<1 || tzi.StandardDate.wDayOfWeek>6) { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_INVALID_TZ_DATE, &wszStandardDate, tzi.StandardDate.wMonth, tzi.StandardDate.wDay, tzi.StandardDate.wDayOfWeek)) { _JumpLastError(hr, error, "WriteMsg"); } } else { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_VALID_TZ_DATE, &wszStandardDate, tzi.StandardDate.wMonth, tzi.StandardDate.wDay, tzi.StandardDate.wDayOfWeek)) { _JumpLastError(hr, error, "WriteMsg"); } } // Construct a string representing the "DaylightDate" field of the TimeZoneInformation: if (0==tzi.DaylightDate.wMonth) { wszDaylightDate = pwsz_IDS_W32TM_SIMPLESTRING_UNSPECIFIED; } else if (tzi.DaylightDate.wMonth>12 || tzi.DaylightDate.wDay>5 || tzi.DaylightDate.wDay<1 || tzi.DaylightDate.wDayOfWeek>6) { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_INVALID_TZ_DATE, &wszDaylightDate, tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay, tzi.DaylightDate.wDayOfWeek)) { _JumpLastError(hr, error, "WriteMsg"); } } else { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_VALID_TZ_DATE, &wszDaylightDate, tzi.DaylightDate.wMonth, tzi.DaylightDate.wDay, tzi.DaylightDate.wDayOfWeek)) { _JumpLastError(hr, error, "WriteMsg"); } } DisplayMsg(FORMAT_MESSAGE_FROM_HMODULE, IDS_W32TM_TIMEZONE_INFO, wszTimeZoneId, tzi.Bias, tzi.StandardName, tzi.StandardBias, wszStandardDate, tzi.DaylightName, tzi.DaylightBias, wszDaylightDate); hr=S_OK; error: // Free our localized strings: for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) { if (NULL != *(rgStrings[dwIndex].ppwsz)) { LocalFree(*(rgStrings[dwIndex].ppwsz)); } } if (NULL != wszDaylightDate) { LocalFree(wszDaylightDate); } if (NULL != wszStandardDate) { LocalFree(wszStandardDate); } if (FAILED(hr) && E_INVALIDARG!=hr) { WCHAR * wszError; HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); LocalFree(wszError); } } return hr; } //-------------------------------------------------------------------- HRESULT PrintRegLine(IN HANDLE hOut, IN DWORD dwValueNameOffset, IN LPWSTR pwszValueName, IN DWORD dwValueTypeOffset, IN LPWSTR pwszValueType, IN DWORD dwValueDataOffset, IN LPWSTR pwszValueData) { DWORD dwCurrentOffset = 0; HRESULT hr; LPWSTR pwszCurrent; LPWSTR pwszEnd; WCHAR pwszLine[1024]; WCHAR wszNULL[] = L"<NULL>"; if (NULL == pwszValueName) { pwszValueName = &wszNULL[0]; } if (NULL == pwszValueType) { pwszValueType = &wszNULL[0]; } if (NULL == pwszValueData) { pwszValueData = &wszNULL[0]; } pwszEnd = pwszLine + ARRAYSIZE(pwszLine); // point to the end of the line buffer pwszCurrent = &pwszLine[0]; // point to the beginning of the line buffer // // Use the safe string functions to populate the line buffer // hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueName); _JumpIfError(hr, error, "StringCchCopy"); pwszCurrent += wcslen(pwszCurrent); // Insert enough spaces to align the "type" field with the type offset for (DWORD dwIndex = pwszCurrent-pwszLine; dwIndex < dwValueTypeOffset; dwIndex++) { hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L" "); _JumpIfError(hr, error, "StringCchCopy"); pwszCurrent++; } hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueType); _JumpIfError(hr, error, "StringCchCopy"); pwszCurrent += wcslen(pwszCurrent); // Insert enoughs spaces to align the "data" field with the data offset for (DWORD dwIndex = pwszCurrent-pwszLine; dwIndex < dwValueDataOffset; dwIndex++) { hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L" "); _JumpIfError(hr, error, "StringCchCopy"); pwszCurrent++; } hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, pwszValueData); _JumpIfError(hr, error, "StringCchCopy"); pwszCurrent += wcslen(pwszCurrent); hr = StringCchCopy(pwszCurrent, pwszEnd-pwszCurrent, L"\n"); _JumpIfError(hr, error, "StringCchCopy"); // Finally, display the reg line PrintStr(hOut, &pwszLine[0]); hr = S_OK; error: return hr; } HRESULT DumpReg(CmdArgs * pca) { BOOL fFreeRegData = FALSE; // Used to indicate whether we've dymanically allocated pwszRegData BOOL fLoggedFailure = FALSE; DWORD dwMaxValueNameLen = 0; // Size in TCHARs. DWORD dwMaxValueDataLen = 0; // Size in bytes. DWORD dwNumValues = 0; DWORD dwRetval = 0; DWORD dwType = 0; DWORD dwValueNameLen = 0; // Size in TCHARs. DWORD dwValueDataLen = 0; // Size in bytes. HANDLE hOut = NULL; HKEY hKeyConfig = NULL; HKEY HKLM = HKEY_LOCAL_MACHINE; HKEY HKLMRemote = NULL; HRESULT hr = E_FAIL; LPWSTR pwszValueName = NULL; LPBYTE pbValueData = NULL; LPWSTR pwszSubkeyName = NULL; LPWSTR pwszComputerName = NULL; LPWSTR pwszRegType = NULL; LPWSTR pwszRegData = NULL; unsigned int nArgID = 0; WCHAR rgwszKeyName[1024]; // Variables to display formatted output: DWORD dwCurrentOffset = 0; DWORD dwValueNameOffset = 0; DWORD dwValueTypeOffset = 0; DWORD dwValueDataOffset = 0; // Localized strings: LPWSTR pwsz_VALUENAME = NULL; LPWSTR pwsz_VALUETYPE = NULL; LPWSTR pwsz_VALUEDATA = NULL; LPWSTR pwsz_REGTYPE_BINARY = NULL; LPWSTR pwsz_REGTYPE_DWORD = NULL; LPWSTR pwsz_REGTYPE_SZ = NULL; LPWSTR pwsz_REGTYPE_MULTISZ = NULL; LPWSTR pwsz_REGTYPE_EXPANDSZ = NULL; LPWSTR pwsz_REGTYPE_UNKNOWN = NULL; LPWSTR pwsz_REGDATA_UNPARSABLE = NULL; // Load the strings we'll need struct LocalizedStrings { UINT id; LPWSTR *ppwsz; } rgStrings[] = { { IDS_W32TM_VALUENAME, &pwsz_VALUENAME }, { IDS_W32TM_VALUETYPE, &pwsz_VALUETYPE }, { IDS_W32TM_VALUEDATA, &pwsz_VALUEDATA }, { IDS_W32TM_REGTYPE_BINARY, &pwsz_REGTYPE_BINARY }, { IDS_W32TM_REGTYPE_DWORD, &pwsz_REGTYPE_DWORD }, { IDS_W32TM_REGTYPE_SZ, &pwsz_REGTYPE_SZ }, { IDS_W32TM_REGTYPE_MULTISZ, &pwsz_REGTYPE_MULTISZ }, { IDS_W32TM_REGTYPE_EXPANDSZ, &pwsz_REGTYPE_EXPANDSZ }, { IDS_W32TM_REGTYPE_UNKNOWN, &pwsz_REGTYPE_UNKNOWN }, { IDS_W32TM_REGDATA_UNPARSABLE, &pwsz_REGDATA_UNPARSABLE } }; for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) { if (!WriteMsg(FORMAT_MESSAGE_FROM_HMODULE, rgStrings[dwIndex].id, rgStrings[dwIndex].ppwsz)) { hr = HRESULT_FROM_WIN32(GetLastError()); _JumpError(hr, error, "WriteMsg"); } } hr = StringCchCopy(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), wszW32TimeRegKeyRoot); _JumpIfError(hr, error, "StringCchCopy"); if (true==FindArg(pca, L"subkey", &pwszSubkeyName, &nArgID)) { MarkArgUsed(pca, nArgID); if (NULL == pwszSubkeyName) { LocalizedWPrintfCR(IDS_W32TM_ERRORDUMPREG_NO_SUBKEY_SPECIFIED); fLoggedFailure = TRUE; hr = E_INVALIDARG; _JumpError(hr, error, "command line parsing"); } hr = StringCchCat(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), L"\\"); _JumpIfError(hr, error, "StringCchCopy"); hr = StringCchCat(&rgwszKeyName[0], ARRAYSIZE(rgwszKeyName), pwszSubkeyName); _JumpIfError(hr, error, "StringCchCopy"); } if (true==FindArg(pca, L"computer", &pwszComputerName, &nArgID)) { MarkArgUsed(pca, nArgID); dwRetval = RegConnectRegistry(pwszComputerName, HKEY_LOCAL_MACHINE, &HKLMRemote); if (ERROR_SUCCESS != dwRetval) { hr = HRESULT_FROM_WIN32(dwRetval); _JumpErrorStr(hr, error, "RegConnectRegistry", L"HKEY_LOCAL_MACHINE"); } HKLM = HKLMRemote; } hr = VerifyAllArgsUsed(pca); _JumpIfError(hr, error, "VerifyAllArgsUsed"); dwRetval = RegOpenKeyEx(HKLM, rgwszKeyName, 0, KEY_QUERY_VALUE, &hKeyConfig); if (ERROR_SUCCESS != dwRetval) { hr = HRESULT_FROM_WIN32(dwRetval); _JumpErrorStr(hr, error, "RegOpenKeyEx", rgwszKeyName); } dwRetval = RegQueryInfoKey (hKeyConfig, NULL, // class buffer NULL, // size of class buffer NULL, // reserved NULL, // number of subkeys NULL, // longest subkey name NULL, // longest class string &dwNumValues, // number of value entries &dwMaxValueNameLen, // longest value name &dwMaxValueDataLen, // longest value data NULL, NULL ); if (ERROR_SUCCESS != dwRetval) { hr = HRESULT_FROM_WIN32(dwRetval); _JumpErrorStr(hr, error, "RegQueryInfoKey", rgwszKeyName); } else if (0 == dwNumValues) { hr = HRESULT_FROM_WIN32(ERROR_NO_MORE_ITEMS); _JumpErrorStr(hr, error, "RegQueryInfoKey", rgwszKeyName); } dwMaxValueNameLen += sizeof(WCHAR); // Include space for NULL character pwszValueName = (LPWSTR)LocalAlloc(LPTR, dwMaxValueNameLen * sizeof(WCHAR)); _JumpIfOutOfMemory(hr, error, pwszValueName); pbValueData = (LPBYTE)LocalAlloc(LPTR, dwMaxValueDataLen); _JumpIfOutOfMemory(hr, error, pbValueData); dwValueNameOffset = 0; dwValueTypeOffset = dwValueNameOffset + dwMaxValueNameLen + 3; dwValueDataOffset += dwValueTypeOffset + 20; // Print table header: hOut = GetStdHandle(STD_OUTPUT_HANDLE); if (INVALID_HANDLE_VALUE==hOut) { _JumpLastError(hr, error, "GetStdHandle"); } PrintStr(hOut, L"\n"); PrintRegLine(hOut, dwValueNameOffset, pwsz_VALUENAME, dwValueTypeOffset, pwsz_VALUETYPE, dwValueDataOffset, pwsz_VALUEDATA); // Next line: dwCurrentOffset = dwValueNameOffset; for (DWORD dwIndex = dwCurrentOffset; dwIndex < (dwValueDataOffset + wcslen(pwsz_VALUEDATA) + 3); dwIndex++) { PrintStr(hOut, L"-"); } PrintStr(hOut, L"\n\n"); for (DWORD dwIndex = 0; dwIndex < dwNumValues; dwIndex++) { dwValueNameLen = dwMaxValueNameLen; dwValueDataLen = dwMaxValueDataLen; memset(reinterpret_cast<LPBYTE>(pwszValueName), 0, dwMaxValueNameLen * sizeof(WCHAR)); memset(pbValueData, 0, dwMaxValueDataLen); dwRetval = RegEnumValue (hKeyConfig, // handle to key to query dwIndex, // index of value to query pwszValueName, // value buffer &dwValueNameLen, // size of value buffer (in TCHARs) NULL, // reserved &dwType, // type buffer pbValueData, // data buffer &dwValueDataLen // size of data buffer ); if (ERROR_SUCCESS != dwRetval) { hr = HRESULT_FROM_WIN32(dwRetval); _JumpErrorStr(hr, error, "RegEnumValue", wszW32TimeRegKeyConfig); } _Verify(dwValueNameLen <= dwMaxValueNameLen, hr, error); _Verify(dwValueDataLen <= dwMaxValueDataLen, hr, error); { switch (dwType) { case REG_DWORD: { WCHAR rgwszDwordData[20]; // Ensure that the returned data buffer is large enough to contain a DWORD: _Verify(dwValueDataLen >= sizeof(long), hr, error); _ltow(*(reinterpret_cast<long *>(pbValueData)), rgwszDwordData, 10); pwszRegType = pwsz_REGTYPE_DWORD; pwszRegData = &rgwszDwordData[0]; } break; case REG_MULTI_SZ: { DWORD cbMultiSzData = 0; WCHAR wszDelimiter[] = { L'\0', L'\0', L'\0' }; LPWSTR pwsz; // calculate the size of the string buffer needed to contain the string data for this MULTI_SZ for (pwsz = (LPWSTR)pbValueData; L'\0' != *pwsz; pwsz += wcslen(pwsz)+1) { cbMultiSzData += sizeof(WCHAR)*(wcslen(pwsz)+1); cbMultiSzData += sizeof(WCHAR)*2; // include space for delimiter } cbMultiSzData += sizeof(WCHAR); // include space for NULL-termination char // allocate the buffer pwszRegData = (LPWSTR)LocalAlloc(LPTR, cbMultiSzData); _JumpIfOutOfMemory(hr, error, pwszRegData); fFreeRegData = TRUE; for (pwsz = (LPWSTR)pbValueData; L'\0' != *pwsz; pwsz += wcslen(pwsz)+1) { hr = StringCbCat(pwszRegData, cbMultiSzData, wszDelimiter); _JumpIfError(hr, error, "StringCbCat"); hr = StringCbCat(pwszRegData, cbMultiSzData, pwsz); _JumpIfError(hr, error, "StringCbCat"); wszDelimiter[0] = L','; wszDelimiter[1] = L' '; } pwszRegType = pwsz_REGTYPE_MULTISZ; } break; case REG_EXPAND_SZ: { pwszRegType = pwsz_REGTYPE_EXPANDSZ; pwszRegData = reinterpret_cast<WCHAR *>(pbValueData); } break; case REG_SZ: { pwszRegType = pwsz_REGTYPE_SZ; pwszRegData = reinterpret_cast<WCHAR *>(pbValueData); } break; case REG_BINARY: { DWORD ccRegData = (2*dwValueDataLen); pwszRegType = pwsz_REGTYPE_BINARY; // Allocate 2 characters per each byte of the binary data. pwszRegData = (LPWSTR)LocalAlloc(LPTR, sizeof(WCHAR)*(ccRegData+1)); _JumpIfOutOfMemory(hr, error, pwszRegData); fFreeRegData = TRUE; LPBYTE pb = pbValueData; for (LPWSTR pwsz = pwszRegData; pwsz < pwsz+ccRegData; ) { hr = StringCchPrintf(pwsz, ccRegData+1, L"%02X", *pb); _JumpIfError(hr, error, "StringCchPrintf"); pwsz += 2; ccRegData -= 2; pb++; } } break; default: // Unrecognized reg type... pwszRegType = pwsz_REGTYPE_UNKNOWN; pwszRegData = pwsz_REGDATA_UNPARSABLE; } PrintRegLine(hOut, dwValueNameOffset, pwszValueName, dwValueTypeOffset, pwszRegType, dwValueDataOffset, pwszRegData); if (fFreeRegData) { LocalFree(pwszRegData); fFreeRegData = FALSE; } pwszRegData = NULL; } } PrintStr(hOut, L"\n"); hr = S_OK; error: // Free our localized strings: for (DWORD dwIndex = 0; dwIndex < ARRAYSIZE(rgStrings); dwIndex++) { if (NULL != *(rgStrings[dwIndex].ppwsz)) { LocalFree(*(rgStrings[dwIndex].ppwsz)); } } if (NULL != hKeyConfig) { RegCloseKey(hKeyConfig); } if (NULL != HKLMRemote) { RegCloseKey(HKLMRemote); } if (NULL != pwszValueName) { LocalFree(pwszValueName); } if (NULL != pbValueData) { LocalFree(pbValueData); } if (fFreeRegData && NULL != pwszRegData) { LocalFree(pwszRegData); } if (FAILED(hr) && !fLoggedFailure) { WCHAR * wszError; HRESULT hr2=GetSystemErrorString(hr, &wszError); if (FAILED(hr2)) { _IgnoreError(hr2, "GetSystemErrorString"); } else { LocalizedWPrintf2(IDS_W32TM_ERRORGENERAL_ERROR_OCCURED, L" %s\n", wszError); LocalFree(wszError); } } return hr; }
35.947941
162
0.570556
npocmaka
911db9de6e667c6f419998033a3f3f1dd4e83062
27,348
cpp
C++
MainWindow.cpp
mrQzs/LVGLBuilder
41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5
[ "MIT" ]
null
null
null
MainWindow.cpp
mrQzs/LVGLBuilder
41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5
[ "MIT" ]
null
null
null
MainWindow.cpp
mrQzs/LVGLBuilder
41dbfbd6d9d6f624e0ae1b7c542eef5f681ca4b5
[ "MIT" ]
null
null
null
#include "MainWindow.h" #include <QDebug> #include <QFileDialog> #include <QInputDialog> #include <QMessageBox> #include <QSettings> #include <QSortFilterProxyModel> #include "LVGLDialog.h" #include "LVGLFontData.h" #include "LVGLFontDialog.h" #include "LVGLHelper.h" #include "LVGLItem.h" #include "LVGLNewDialog.h" #include "LVGLObjectModel.h" #include "LVGLProject.h" #include "LVGLPropertyModel.h" #include "LVGLSimulator.h" #include "LVGLStyleModel.h" #include "LVGLWidgetListView.h" #include "LVGLWidgetModel.h" #include "LVGLWidgetModelDisplay.h" #include "LVGLWidgetModelInput.h" #include "ListDelegate.h" #include "ListViewItem.h" #include "TabWidget.h" #include "lvgl/lvgl.h" #include "ui_MainWindow.h" #include "widgets/LVGLWidgets.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), m_ui(new Ui::MainWindow), m_zoom_slider(new QSlider(Qt::Horizontal)), m_project(nullptr), m_maxFileNr(5), m_curSimulation(nullptr), m_proxyModel(nullptr), m_objectModel(nullptr), m_proxyModelDPW(nullptr), m_proxyModelIPW(nullptr), m_widgetModel(nullptr), m_widgetModelDPW(nullptr), m_widgetModelIPW(nullptr), m_filter(nullptr), m_curTabWIndex(-1), m_frun(true) { m_ui->setupUi(this); m_ui->style_tree->setStyleSheet( "QTreeView::item{border:1px solid " "#f2f2f2;}"); m_ui->property_tree->setStyleSheet( "QTreeView::item{border:1px solid " "#f2f2f2;}"); m_propertyModel = new LVGLPropertyModel(); m_ld1 = new ListDelegate(m_ui->list_widgets->getlistview()); m_ld2 = new ListDelegate(m_ui->list_widgets_2->getlistview()); m_ld3 = new ListDelegate(m_ui->list_widgets_3->getlistview()); m_ui->property_tree->setModel(m_propertyModel); m_ui->property_tree->setItemDelegate(new LVGLPropertyDelegate); m_ui->button_remove_image->setEnabled(false); m_ui->button_remove_font->setEnabled(false); m_zoom_slider->setRange(-2, 2); m_ui->statusbar->addPermanentWidget(m_zoom_slider); m_styleModel = new LVGLStyleModel; connect(m_styleModel, &LVGLStyleModel::styleChanged, this, &MainWindow::styleChanged); m_ui->style_tree->setModel(m_styleModel); m_ui->style_tree->setItemDelegate( new LVGLStyleDelegate(m_styleModel->styleBase())); m_ui->style_tree->expandAll(); connect(m_ui->action_new, &QAction::triggered, this, &MainWindow::openNewProject); // recent configurations QAction *recentFileAction = nullptr; for (int i = 0; i < m_maxFileNr; i++) { recentFileAction = new QAction(this); recentFileAction->setVisible(false); connect(recentFileAction, &QAction::triggered, this, &MainWindow::loadRecent); m_recentFileActionList.append(recentFileAction); m_ui->menu_resent_filess->addAction(recentFileAction); } updateRecentActionList(); // add style editor dock to property dock and show the property dock tabifyDockWidget(m_ui->PropertyEditor, m_ui->ObjecInspector); m_ui->PropertyEditor->raise(); m_ui->StyleEditor->raise(); // add font editor dock to image dock and show the image dock tabifyDockWidget(m_ui->ImageEditor, m_ui->FontEditor); m_ui->ImageEditor->raise(); m_liststate << LV_STATE_DEFAULT << LV_STATE_CHECKED << LV_STATE_FOCUSED << LV_STATE_EDITED << LV_STATE_HOVERED << LV_STATE_PRESSED << LV_STATE_DISABLED; connect(m_ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::tabChanged); // initcodemap(); // initNewWidgets(); LVGLHelper::getInstance().setMainW(this); } MainWindow::~MainWindow() { delete m_ui; } LVGLSimulator *MainWindow::simulator() const { return m_curSimulation; } void MainWindow::updateProperty() { LVGLObject *o = m_curSimulation->selectedObject(); if (o == nullptr) return; LVGLProperty *p = o->widgetClass()->property("Geometry"); if (p == nullptr) return; for (int i = 0; i < p->count(); ++i) { auto index = m_propertyModel->propIndex(p->child(i), o->widgetClass(), 1); emit m_propertyModel->dataChanged(index, index); } } void MainWindow::setCurrentObject(LVGLObject *obj) { m_ui->combo_style->clear(); m_ui->combo_state->setCurrentIndex(0); m_propertyModel->setObject(obj); if (obj) { auto parts = obj->widgetClass()->parts(); m_styleModel->setPart(parts[0]); m_styleModel->setState(LV_STATE_DEFAULT); m_styleModel->setObj(obj->obj()); m_ui->combo_style->addItems(obj->widgetClass()->styles()); m_styleModel->setStyle(obj->style(0, 0), obj->widgetClass()->editableStyles(0)); updateItemDelegate(); } else { m_styleModel->setStyle(nullptr); } } void MainWindow::styleChanged() { LVGLObject *obj = m_curSimulation->selectedObject(); if (obj) { int index = m_ui->combo_style->currentIndex(); obj->widgetClass()->setStyle(obj->obj(), index, obj->style(index)); // refresh_children_style(obj->obj()); // lv_obj_refresh_style(obj->obj()); } } void MainWindow::loadRecent() { QAction *action = qobject_cast<QAction *>(QObject::sender()); if (action == nullptr) return; loadProject(action->data().toString()); } void MainWindow::openNewProject() { LVGLNewDialog dialog(this); if (dialog.exec() == QDialog::Accepted) { if (m_curSimulation != nullptr) revlvglConnect(); TabWidget *tabw = new TabWidget(dialog.selectedName(), this); lvgl = tabw->getCore(); const auto res = dialog.selectedResolution(); lvgl->init(res.width(), res.height()); if (m_frun) { m_frun = false; initNewWidgets(); initcodemap(); } lvgl->initw(m_widgets); lvgl->initwDP(m_widgetsDisplayW); lvgl->initwIP(m_widgetsInputW); m_coreRes[lvgl] = res; m_listTabW.push_back(tabw); m_ui->tabWidget->addTab(tabw, tabw->getName()); m_ui->tabWidget->setCurrentIndex(m_listTabW.size() - 1); setEnableBuilder(true); m_curSimulation->clear(); m_project = tabw->getProject(); m_project->setres(res); lvgl->changeResolution(res); } else if (m_project == nullptr) { setEnableBuilder(false); setWindowTitle("LVGL Builder"); } } void MainWindow::addImage(LVGLImageData *img, QString name) { LVGLImageDataCast cast; cast.ptr = img; QListWidgetItem *item = new QListWidgetItem(img->icon(), name); item->setData(Qt::UserRole + 3, cast.i); m_ui->list_images->addItem(item); } void MainWindow::updateImages() { m_ui->list_images->clear(); for (LVGLImageData *i : lvgl->images()) { if (i->fileName().isEmpty()) continue; QString name = QFileInfo(i->fileName()).baseName() + QString(" [%1x%2]").arg(i->width()).arg(i->height()); addImage(i, name); } } void MainWindow::addFont(LVGLFontData *font, QString name) { LVGLFontDataCast cast; cast.ptr = font; QListWidgetItem *item = new QListWidgetItem(name); item->setData(Qt::UserRole + 3, cast.i); m_ui->list_fonts->addItem(item); } void MainWindow::updateFonts() { m_ui->list_fonts->clear(); for (const LVGLFontData *f : lvgl->customFonts()) addFont(const_cast<LVGLFontData *>(f), f->name()); } void MainWindow::updateRecentActionList() { QSettings settings("at.fhooe.lvgl", "LVGL Builder"); QStringList recentFilePaths; for (const QString &f : settings.value("recentFiles").toStringList()) { if (QFile(f).exists()) recentFilePaths.push_back(f); } int itEnd = m_maxFileNr; if (recentFilePaths.size() <= m_maxFileNr) itEnd = recentFilePaths.size(); for (int i = 0; i < itEnd; i++) { QString strippedName = QFileInfo(recentFilePaths.at(i)).fileName(); m_recentFileActionList.at(i)->setText(strippedName); m_recentFileActionList.at(i)->setData(recentFilePaths.at(i)); m_recentFileActionList.at(i)->setVisible(true); } for (int i = itEnd; i < m_maxFileNr; i++) m_recentFileActionList.at(i)->setVisible(false); } void MainWindow::adjustForCurrentFile(const QString &fileName) { QSettings settings("at.fhooe.lvgl", "LVGL Builder"); QStringList recentFilePaths = settings.value("recentFiles").toStringList(); recentFilePaths.removeAll(fileName); recentFilePaths.prepend(fileName); while (recentFilePaths.size() > m_maxFileNr) recentFilePaths.removeLast(); settings.setValue("recentFiles", recentFilePaths); updateRecentActionList(); } void MainWindow::loadProject(const QString &fileName) { delete m_project; m_curSimulation->clear(); m_project = LVGLProject::load(fileName); if (m_project == nullptr) { QMessageBox::critical(this, "Error", "Could not load lvgl file!"); setWindowTitle("LVGL Builder"); setEnableBuilder(false); } else { adjustForCurrentFile(fileName); setWindowTitle("LVGL Builder - [" + m_project->name() + "]"); lvgl->changeResolution(m_project->resolution()); m_curSimulation->changeResolution(m_project->resolution()); setEnableBuilder(true); } updateImages(); updateFonts(); } void MainWindow::setEnableBuilder(bool enable) { m_ui->action_save->setEnabled(enable); m_ui->action_export_c->setEnabled(enable); m_ui->action_run->setEnabled(enable); m_ui->WidgeBox->setEnabled(enable); m_ui->ImageEditor->setEnabled(enable); m_ui->FontEditor->setEnabled(enable); } void MainWindow::updateItemDelegate() { auto it = m_ui->style_tree->itemDelegate(); if (nullptr != it) delete it; m_ui->style_tree->setItemDelegate( new LVGLStyleDelegate(m_styleModel->styleBase())); } void MainWindow::on_action_load_triggered() { QString path; if (m_project != nullptr) path = m_project->fileName(); QString fileName = QFileDialog::getOpenFileName(this, "Load lvgl", path, "LVGL (*.lvgl)"); if (fileName.isEmpty()) return; loadProject(fileName); } void MainWindow::on_action_save_triggered() { QString path; if (m_project != nullptr) path = m_project->fileName(); QString fileName = QFileDialog::getSaveFileName(this, "Save lvgl", path, "LVGL (*.lvgl)"); if (fileName.isEmpty()) return; if (!m_project->save(fileName)) { QMessageBox::critical(this, "Error", "Could not save lvgl file!"); } else { adjustForCurrentFile(fileName); } } void MainWindow::on_combo_style_currentIndexChanged(int index) { LVGLObject *obj = m_curSimulation->selectedObject(); if (obj && (index >= 0)) { auto parts = obj->widgetClass()->parts(); m_styleModel->setState(m_liststate[m_ui->combo_state->currentIndex()]); m_styleModel->setPart(parts[index]); m_styleModel->setStyle( obj->style(index, m_ui->combo_state->currentIndex()), obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex())); m_ui->combo_state->setCurrentIndex(0); on_combo_state_currentIndexChanged(0); } } void MainWindow::on_action_export_c_triggered() { QString dir; if (m_project != nullptr) { QFileInfo fi(m_project->fileName()); dir = fi.absoluteFilePath(); } QString path = QFileDialog::getExistingDirectory(this, "Export C files", dir); if (path.isEmpty()) return; if (m_project->exportCode(path)) QMessageBox::information(this, "Export", "C project exported!"); } void MainWindow::on_button_add_image_clicked() { QString dir; if (m_project != nullptr) { QFileInfo fi(m_project->fileName()); dir = fi.absoluteFilePath(); } QStringList fileNames = QFileDialog::getOpenFileNames( this, "Import image", dir, "Image (*.png *.jpg *.bmp *.jpeg)"); for (const QString &fileName : fileNames) { QImage image(fileName); if (image.isNull()) continue; if (image.width() >= 2048 || image.height() >= 2048) { QMessageBox::critical( this, "Error Image Size", tr("Image size must be under 2048! (Src: '%1')").arg(fileName)); continue; } QString name = QFileInfo(fileName).baseName(); LVGLImageData *i = lvgl->addImage(fileName, name); name += QString(" [%1x%2]").arg(i->width()).arg(i->height()); addImage(i, name); } } void MainWindow::on_button_remove_image_clicked() { QListWidgetItem *item = m_ui->list_images->currentItem(); if (item == nullptr) return; const int row = m_ui->list_images->currentRow(); LVGLImageDataCast cast; cast.i = item->data(Qt::UserRole + 3).toLongLong(); if (lvgl->removeImage(cast.ptr)) m_ui->list_images->takeItem(row); } void MainWindow::on_list_images_customContextMenuRequested(const QPoint &pos) { QPoint item = m_ui->list_images->mapToGlobal(pos); QListWidgetItem *listItem = m_ui->list_images->itemAt(pos); if (listItem == nullptr) return; QMenu menu; QAction *save = menu.addAction("Save as ..."); QAction *color = menu.addAction("Set output color ..."); QAction *sel = menu.exec(item); if (sel == save) { LVGLImageDataCast cast; cast.i = listItem->data(Qt::UserRole + 3).toLongLong(); QStringList options({"C Code (*.c)", "Binary (*.bin)"}); QString selected; QString fileName = QFileDialog::getSaveFileName( this, "Save image as c file", cast.ptr->codeName(), options.join(";;"), &selected); if (fileName.isEmpty()) return; bool ok = false; if (selected == options.at(0)) ok = cast.ptr->saveAsCode(fileName); else if (selected == options.at(1)) ok = cast.ptr->saveAsBin(fileName); if (!ok) { QMessageBox::critical(this, "Error", tr("Could not save image '%1'").arg(fileName)); } } else if (sel == color) { LVGLImageDataCast cast; cast.i = listItem->data(Qt::UserRole + 3).toLongLong(); int index = static_cast<int>(cast.ptr->colorFormat()); QString ret = QInputDialog::getItem(this, "Output color", "Select output color", LVGLImageData::colorFormats(), index, false); index = LVGLImageData::colorFormats().indexOf(ret); if (index >= 0) cast.ptr->setColorFormat(static_cast<LVGLImageData::ColorFormat>(index)); } } void MainWindow::on_list_images_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) m_ui->button_remove_image->setEnabled(current != nullptr); } void MainWindow::on_button_add_font_clicked() { LVGLFontDialog dialog(this); if (dialog.exec() != QDialog::Accepted) return; LVGLFontData *f = lvgl->addFont(dialog.selectedFontPath(), dialog.selectedFontSize()); if (f) addFont(f, f->name()); else QMessageBox::critical(this, "Error", "Could not load font!"); } void MainWindow::on_button_remove_font_clicked() { QListWidgetItem *item = m_ui->list_fonts->currentItem(); if (item == nullptr) return; const int row = m_ui->list_fonts->currentRow(); LVGLFontDataCast cast; cast.i = item->data(Qt::UserRole + 3).toLongLong(); if (lvgl->removeFont(cast.ptr)) m_ui->list_fonts->takeItem(row); } void MainWindow::on_list_fonts_customContextMenuRequested(const QPoint &pos) { QPoint item = m_ui->list_fonts->mapToGlobal(pos); QListWidgetItem *listItem = m_ui->list_fonts->itemAt(pos); if (listItem == nullptr) return; QMenu menu; QAction *save = menu.addAction("Save as ..."); QAction *sel = menu.exec(item); if (sel == save) { LVGLFontDataCast cast; cast.i = listItem->data(Qt::UserRole + 3).toLongLong(); QStringList options({"C Code (*.c)", "Binary (*.bin)"}); QString selected; QString fileName = QFileDialog::getSaveFileName( this, "Save font as c file", cast.ptr->codeName(), options.join(";;"), &selected); if (fileName.isEmpty()) return; bool ok = false; if (selected == options.at(0)) ok = cast.ptr->saveAsCode(fileName); if (!ok) { QMessageBox::critical(this, "Error", tr("Could not save font '%1'").arg(fileName)); } } } void MainWindow::on_list_fonts_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous) { Q_UNUSED(previous) m_ui->button_remove_font->setEnabled(current != nullptr); } void MainWindow::on_action_run_toggled(bool run) { m_curSimulation->setMouseEnable(run); m_curSimulation->setSelectedObject(nullptr); } void MainWindow::showEvent(QShowEvent *event) { QMainWindow::showEvent(event); if (m_project == nullptr) QTimer::singleShot(50, this, SLOT(openNewProject())); } QPixmap MainWindow::getPix(int type) { QPixmap p; switch (type) { case 0: p.load(":/icons/Arc.png"); break; case 1: p.load(":/icons/Bar.png"); break; case 2: p.load(":/icons/Button.png"); break; case 3: p.load(":/icons/Button Matrix.png"); break; case 4: p.load(":/icons/Calendar.png"); break; case 5: p.load(":/icons/Canvas.png"); break; case 6: p.load(":/icons/Check box.png"); break; case 7: p.load(":/icons/Chart.png"); break; case 8: p.load(":/icons/Container.png"); break; case 9: p.load(":/icons/Color picker.png"); break; case 10: p.load(":/icons/Dropdown.png"); break; case 11: p.load(":/icons/Gauge.png"); break; case 12: p.load(":/icons/Image.png"); break; case 13: p.load(":/icons/Image button.png"); break; case 16: p.load(":/icons/Keyboard.png"); break; case 17: p.load(":/icons/Label.png"); break; case 18: p.load(":/icons/LED.png"); break; case 19: p.load(":/icons/Line.png"); break; case 20: p.load(":/icons/List.png"); break; case 21: p.load(":/icons/Line meter.png"); break; case 22: p.load(":/icons/Message box.png"); break; case 23: p.load(":/icons/ObjectMask.png"); break; case 24: p.load(":/icons/Page.png"); break; case 25: p.load(":/icons/Roller.png"); break; case 26: p.load(":/icons/Slider.png"); break; case 27: p.load(":/icons/Spinbox.png"); break; case 28: p.load(":/icons/Spinner.png"); break; case 29: p.load(":/icons/Switch.png"); break; case 30: p.load(":/icons/Table.png"); break; case 31: p.load(":/icons/Tabview.png"); break; case 32: p.load(":/icons/Text area.png"); break; case 33: p.load(":/icons/TileView.png"); break; case 34: p.load(":/icons/Window.png"); break; } return p; } void MainWindow::addWidget(LVGLWidget *w) { w->setPreview(getPix(w->type())); m_widgets.insert(w->className(), w); } void MainWindow::addWidgetDisplayW(LVGLWidget *w) { w->setPreview(getPix(w->type())); m_widgetsDisplayW.insert(w->className(), w); } void MainWindow::addWidgetInputW(LVGLWidget *w) { w->setPreview(getPix(w->type())); m_widgetsInputW.insert(w->className(), w); } void MainWindow::initcodemap() { auto pt = lv_obj_create(NULL, NULL); m_codemap[0] = lv_arc_create(pt, NULL); m_codemap[1] = lv_bar_create(pt, NULL); m_codemap[2] = lv_btn_create(pt, NULL); m_codemap[3] = lv_btnmatrix_create(pt, NULL); m_codemap[4] = lv_calendar_create(pt, NULL); m_codemap[5] = lv_canvas_create(pt, NULL); m_codemap[6] = lv_checkbox_create(pt, NULL); m_codemap[7] = lv_chart_create(pt, NULL); m_codemap[8] = lv_cont_create(pt, NULL); m_codemap[9] = lv_cpicker_create(pt, NULL); m_codemap[10] = lv_dropdown_create(pt, NULL); m_codemap[11] = lv_gauge_create(pt, NULL); m_codemap[12] = lv_img_create(pt, NULL); m_codemap[13] = lv_imgbtn_create(pt, NULL); m_codemap[16] = lv_keyboard_create(pt, NULL); m_codemap[17] = lv_label_create(pt, NULL); m_codemap[18] = lv_led_create(pt, NULL); m_codemap[19] = lv_line_create(pt, NULL); m_codemap[20] = lv_list_create(pt, NULL); m_codemap[21] = lv_linemeter_create(pt, NULL); m_codemap[22] = lv_msgbox_create(pt, NULL); m_codemap[23] = lv_objmask_create(pt, NULL); m_codemap[24] = lv_page_create(pt, NULL); m_codemap[25] = lv_roller_create(pt, NULL); m_codemap[26] = lv_slider_create(pt, NULL); m_codemap[27] = lv_spinbox_create(pt, NULL); m_codemap[28] = lv_spinner_create(pt, NULL); m_codemap[29] = lv_switch_create(pt, NULL); m_codemap[30] = lv_table_create(pt, NULL); m_codemap[31] = lv_tabview_create(pt, NULL); m_codemap[32] = lv_textarea_create(pt, NULL); m_codemap[33] = lv_tileview_create(pt, NULL); m_codemap[34] = lv_win_create(pt, NULL); } void MainWindow::initNewWidgets() { addWidget(new LVGLButton); addWidget(new LVGLButtonMatrix); addWidget(new LVGLImageButton); addWidgetDisplayW(new LVGLArc); addWidgetDisplayW(new LVGLBar); addWidgetDisplayW(new LVGLImage); addWidgetDisplayW(new LVGLLabel); addWidgetDisplayW(new LVGLLED); addWidgetDisplayW(new LVGLMessageBox); addWidgetDisplayW(new LVGLObjectMask); addWidgetDisplayW(new LVGLPage); addWidgetDisplayW(new LVGLTable); addWidgetDisplayW(new LVGLTabview); addWidgetDisplayW(new LVGLTileView); addWidgetDisplayW(new LVGLTextArea); addWidgetDisplayW(new LVGLWindow); addWidgetInputW(new LVGLCalendar); addWidgetInputW(new LVGLCanvas); addWidgetInputW(new LVGLChart); addWidgetInputW(new LVGLCheckBox); addWidgetInputW(new LVGLColorPicker); addWidgetInputW(new LVGLContainer); addWidgetInputW(new LVGLDropDownList); addWidgetInputW(new LVGLGauge); addWidgetInputW(new LVGLKeyboard); addWidgetInputW(new LVGLLine); addWidgetInputW(new LVGLList); addWidgetInputW(new LVGLLineMeter); addWidgetInputW(new LVGLRoller); addWidgetInputW(new LVGLSlider); addWidgetInputW(new LVGLSpinbox); addWidgetInputW(new LVGLSpinner); addWidgetInputW(new LVGLSwitch); } void MainWindow::initlvglConnect() { if (m_objectModel) delete m_objectModel; if (m_proxyModel) delete m_proxyModel; if (m_proxyModelDPW) delete m_proxyModelDPW; if (m_proxyModelIPW) delete m_proxyModelIPW; if (m_widgetModel) delete m_widgetModel; if (m_widgetModelDPW) delete m_widgetModelDPW; if (m_widgetModelIPW) delete m_widgetModelIPW; m_objectModel = new LVGLObjectModel(this); m_widgetModel = new LVGLWidgetModel(this); m_widgetModelDPW = new LVGLWidgetModelDisplay(this); m_widgetModelIPW = new LVGLWidgetModelInput(this); m_proxyModel = new QSortFilterProxyModel(this); m_proxyModelDPW = new QSortFilterProxyModel(this); m_proxyModelIPW = new QSortFilterProxyModel(this); m_ui->object_tree->setModel(m_objectModel); m_curSimulation->setObjectModel(m_objectModel); m_proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModel->setSourceModel(m_widgetModel); m_proxyModel->sort(0); m_proxyModelDPW->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModelDPW->setSourceModel(m_widgetModelDPW); m_proxyModelDPW->sort(0); m_proxyModelIPW->setFilterCaseSensitivity(Qt::CaseInsensitive); m_proxyModelIPW->setSourceModel(m_widgetModelIPW); m_proxyModelIPW->sort(0); m_ui->list_widgets->getlistview()->setItemDelegate(m_ld1); m_ui->list_widgets_2->getlistview()->setItemDelegate(m_ld2); m_ui->list_widgets_3->getlistview()->setItemDelegate(m_ld3); m_ui->list_widgets->getlistview()->setModel(m_proxyModel); m_ui->list_widgets_2->getlistview()->setModel(m_proxyModelDPW); m_ui->list_widgets_3->getlistview()->setModel(m_proxyModelIPW); m_ui->list_widgets->settoolbtnText(tr("Button")); m_ui->list_widgets_2->settoolbtnText(tr("DisplayWidgets")); m_ui->list_widgets_3->settoolbtnText(tr("InputWidgts")); connect(m_curSimulation, &LVGLSimulator::objectSelected, this, &MainWindow::setCurrentObject); connect(m_curSimulation, &LVGLSimulator::objectSelected, m_ui->property_tree, &QTreeView::expandAll); connect(m_curSimulation->item(), &LVGLItem::geometryChanged, this, &MainWindow::updateProperty); connect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree, &QTreeView::expandAll); connect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel, &LVGLObjectModel::setCurrentObject); connect(m_ui->object_tree, &QTreeView::doubleClicked, this, [this](const QModelIndex &index) { m_curSimulation->setSelectedObject(m_objectModel->object(index)); }); connect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation, &LVGLSimulator::setZoomLevel); connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel, &QSortFilterProxyModel::setFilterWildcard); connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW, &QSortFilterProxyModel::setFilterWildcard); connect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW, &QSortFilterProxyModel::setFilterWildcard); if (m_filter != nullptr) delete m_filter; m_filter = new LVGLKeyPressEventFilter(m_curSimulation, qApp); qApp->installEventFilter(m_filter); m_ui->combo_state->clear(); QStringList statelist; statelist << "LV_STATE_DEFAULT" << "LV_STATE_CHECKED" << "LV_STATE_FOCUSED" << "LV_STATE_EDITED" << "LV_STATE_HOVERED" << "LV_STATE_PRESSED" << "LV_STATE_DISABLED"; m_ui->combo_state->addItems(statelist); } void MainWindow::revlvglConnect() { disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModel, &QSortFilterProxyModel::setFilterWildcard); disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelDPW, &QSortFilterProxyModel::setFilterWildcard); disconnect(m_ui->edit_filter, &QLineEdit::textChanged, m_proxyModelIPW, &QSortFilterProxyModel::setFilterWildcard); disconnect(m_curSimulation, &LVGLSimulator::objectSelected, this, &MainWindow::setCurrentObject); disconnect(m_curSimulation, &LVGLSimulator::objectSelected, m_ui->property_tree, &QTreeView::expandAll); disconnect(m_curSimulation->item(), &LVGLItem::geometryChanged, this, &MainWindow::updateProperty); disconnect(m_curSimulation, &LVGLSimulator::objectAdded, m_ui->object_tree, &QTreeView::expandAll); disconnect(m_curSimulation, &LVGLSimulator::objectSelected, m_objectModel, &LVGLObjectModel::setCurrentObject); disconnect(m_zoom_slider, &QSlider::valueChanged, m_curSimulation, &LVGLSimulator::setZoomLevel); } void MainWindow::on_combo_state_currentIndexChanged(int index) { LVGLObject *obj = m_curSimulation->selectedObject(); if (obj && (index >= 0)) { auto parts = obj->widgetClass()->parts(); m_styleModel->setPart(parts[m_ui->combo_style->currentIndex()]); m_styleModel->setState(m_liststate[index]); m_styleModel->setStyle( obj->style(m_ui->combo_style->currentIndex(), index), obj->widgetClass()->editableStyles(m_ui->combo_style->currentIndex())); updateItemDelegate(); } } void MainWindow::tabChanged(int index) { if (index != m_curTabWIndex) { if (nullptr != m_curSimulation) m_curSimulation->setSelectedObject(nullptr); m_curSimulation = m_listTabW[index]->getSimulator(); lvgl = m_listTabW[index]->getCore(); m_project = m_listTabW[index]->getProject(); // dont need initlvglConnect(); lvgl->changeResolution(m_coreRes[lvgl]); m_curSimulation->changeResolution(m_coreRes[lvgl]); m_curSimulation->repaint(); m_curTabWIndex = index; } }
33.229648
80
0.685644
mrQzs
911dd4796f0fde651220d48ea1b63b48ce2d0be8
2,964
cpp
C++
lib/os/thread_win32.cpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
lib/os/thread_win32.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
lib/os/thread_win32.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- lib/os/thread_win32.cpp --------------------------------------------===// //* _ _ _ * //* | |_| |__ _ __ ___ __ _ __| | * //* | __| '_ \| '__/ _ \/ _` |/ _` | * //* | |_| | | | | | __/ (_| | (_| | * //* \__|_| |_|_| \___|\__,_|\__,_| * //* * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// /// \file thread.cpp #include "pstore/os/thread.hpp" #ifdef _WIN32 # include <array> # include <cerrno> # include <cstring> # include <system_error> # include "pstore/config/config.hpp" # include "pstore/support/error.hpp" namespace pstore { namespace threads { static thread_local char thread_name[name_size]; void set_name (gsl::not_null<gsl::czstring> name) { // This code taken from http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx // Sadly, threads don't actually have names in Win32. The process via // RaiseException is just a "Secret Handshake" with the VS Debugger, who // actually stores the thread -> name mapping. Windows itself has no // notion of a thread "name". std::strncpy (thread_name, name, name_size); thread_name[name_size - 1] = '\0'; # ifndef NDEBUG DWORD const MS_VC_EXCEPTION = 0x406D1388; # pragma pack(push, 8) struct THREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. }; # pragma pack(pop) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name; info.dwThreadID = GetCurrentThreadId (); info.dwFlags = 0; __try { RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR *) &info); } __except (EXCEPTION_EXECUTE_HANDLER) { } # endif // NDEBUG } gsl::czstring get_name (gsl::span<char, name_size> name /*out*/) { auto const length = name.size (); if (name.data () == nullptr || length < 1) { raise (errno_erc{EINVAL}); } std::strncpy (name.data (), thread_name, length); name[length - 1] = '\0'; return name.data (); } } // end namespace threads } // end namespace pstore #endif //_WIN32
35.285714
89
0.501012
paulhuggett
91247fb88c0d36401416ae2546fbf6b735a19739
1,694
cpp
C++
src/interface/TWTezosAddress.cpp
jacobcreech/wallet-core
d5a1497c8d50685030ea752332dc28f48c82da36
[ "MIT" ]
null
null
null
src/interface/TWTezosAddress.cpp
jacobcreech/wallet-core
d5a1497c8d50685030ea752332dc28f48c82da36
[ "MIT" ]
null
null
null
src/interface/TWTezosAddress.cpp
jacobcreech/wallet-core
d5a1497c8d50685030ea752332dc28f48c82da36
[ "MIT" ]
null
null
null
// Copyright © 2017-2019 Trust Wallet. // // This file is part of Trust. The full Trust copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include <TrustWalletCore/TWTezosAddress.h> #include "../Tezos/Address.h" #include <TrustWalletCore/TWHash.h> #include <TrustWalletCore/TWPublicKey.h> #include <TrezorCrypto/ecdsa.h> #include <string.h> #include <memory> using namespace TW; using namespace TW::Tezos; bool TWTezosAddressEqual(struct TWTezosAddress *_Nonnull lhs, struct TWTezosAddress *_Nonnull rhs) { return lhs->impl == rhs->impl; } bool TWTezosAddressIsValidString(TWString *_Nonnull string) { auto s = reinterpret_cast<const std::string*>(string); return Address::isValid(*s); } struct TWTezosAddress *_Nullable TWTezosAddressCreateWithString(TWString *_Nonnull string) { auto s = reinterpret_cast<const std::string*>(string); const auto address = Address(*s); return new TWTezosAddress{ std::move(address) }; } struct TWTezosAddress *_Nonnull TWTezosAddressCreateWithPublicKey(struct TWPublicKey *_Nonnull publicKey) { return new TWTezosAddress{ Address(publicKey->impl) }; } void TWTezosAddressDelete(struct TWTezosAddress *_Nonnull address) { delete address; } TWString *_Nonnull TWTezosAddressDescription(struct TWTezosAddress *_Nonnull address) { const auto string = address->impl.string(); return TWStringCreateWithUTF8Bytes(string.c_str()); } TWData *_Nonnull TWTezosAddressKeyHash(struct TWTezosAddress *_Nonnull address) { return TWDataCreateWithBytes(address->impl.bytes.data(), Address::size); }
32.576923
107
0.767414
jacobcreech
9128bace1e9e94ff0e730643982c5494b5a74fab
1,055
cpp
C++
src/lox/Object.cpp
dylanclark/loxplusplus
a533389e73f86c067ad705a317c3a3cc0f66b63f
[ "MIT" ]
null
null
null
src/lox/Object.cpp
dylanclark/loxplusplus
a533389e73f86c067ad705a317c3a3cc0f66b63f
[ "MIT" ]
null
null
null
src/lox/Object.cpp
dylanclark/loxplusplus
a533389e73f86c067ad705a317c3a3cc0f66b63f
[ "MIT" ]
null
null
null
#include <loxpp_pch.h> #include <Object.h> #include <VisitHelpers.h> namespace Loxpp::Object { // Handy template class and function to cast from a variant T1 to variant T2, // where T2 is a superset of T1: https://stackoverflow.com/a/47204507/15150338 template <class... Args> struct variant_cast_proxy { std::variant<Args...> v; template <class... ToArgs> operator std::variant<ToArgs...>() const { return std::visit( [](auto&& arg) -> std::variant<ToArgs...> { return arg; }, v); } }; template <class... Args> auto variant_cast(const std::variant<Args...>& v) -> variant_cast_proxy<Args...> { return {v}; } LoxObj FromLiteralValue(const Lexer::LiteralValue& value) { return LoxObj{variant_cast(value)}; } bool IsTruthy(const LoxObj& obj) { return std::visit(overloaded{[](std::monostate /*m*/) { return false; }, [](bool b) { return b; }, [](auto&& arg) { return true; }}, obj); } } // namespace Loxpp::Object
29.305556
78
0.595261
dylanclark
912bc5f9488b04a8bb775c60c37d5c0327a8f8d7
1,243
cpp
C++
arrays/largestBand.cpp
kaushikbalasundar/cpp_dsa_solutions
6a74bd6d114a882b5c95c5e4cc74447d58bbae7b
[ "MIT" ]
null
null
null
arrays/largestBand.cpp
kaushikbalasundar/cpp_dsa_solutions
6a74bd6d114a882b5c95c5e4cc74447d58bbae7b
[ "MIT" ]
null
null
null
arrays/largestBand.cpp
kaushikbalasundar/cpp_dsa_solutions
6a74bd6d114a882b5c95c5e4cc74447d58bbae7b
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<unordered_set> #include<algorithm> using namespace std; //find the longest band in a given array of integers //Input: {1,9,3,0,5,2,4,10,7,12,6} //Output: 8 {0,1,2,3,4,5,6,7} int longestBand(vector<int> arr){ int result = 0; unordered_set<int> os; for(int element : arr){ os.insert(element); } for(auto element: os){ //note that you can iterate through an unordered set like this. You looked this up. int parent = element -1 ; // find the root of a sequence if(os.find(parent)==os.end()){ // if root is found int count = 1; // start counting int next_element = element + 1; //find next element while(os.find(next_element)!=os.end()){ //keep incrementing as long as the sequence holds count++; next_element++; } if(count > result){// update maximum sequence found till now result = count; } } } return result; //return maximum sequence } int main(){ int result = longestBand({1,9,3,0,5,4,10,7,12,6}); cout << "The longest band is: " << result << endl; return 0; }
23.018519
111
0.565567
kaushikbalasundar
912c40f76e858930903aa926c3d49888dda1bc63
1,939
cpp
C++
client/src/Helper.cpp
bendelec/Grandma
d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8
[ "MIT" ]
2
2020-05-25T11:12:19.000Z
2022-01-18T01:38:19.000Z
client/src/Helper.cpp
bendelec/Grandma
d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8
[ "MIT" ]
1
2020-03-28T03:47:22.000Z
2020-03-28T03:47:22.000Z
client/src/Helper.cpp
bendelec/Grandma
d7ac708b5357107a0e4b32e175c2e8cb71fdbcd8
[ "MIT" ]
1
2022-01-18T01:50:30.000Z
2022-01-18T01:50:30.000Z
/** *************************************************************************** * Various helper functions * * (c)2020 Christian Bendele * */ #include "Helper.h" #include <sstream> #include <iostream> namespace Grandma { std::vector<std::string> Helper::vectorize_path(const std::string path) { std::stringstream ss; if(path[0] == '/') { ss << path.substr(1); } else { ss << path; } std::string segment; std::vector<std::string> vectorized; while(getline(ss, segment, '/')) { vectorized.push_back(segment); } return vectorized; } // TODO: this can hardly be called a real URL parser. It is very simplicistic and supports only a // small part of RFCxxxx. Also, string operations in C++ are not my forte... bool Helper::URL::parse_from_string(std::string s_uri) { std::cout << "Parsing URI " << s_uri << std::endl; // parse protocol size_t delim = s_uri.find("://"); if(delim == std::string::npos) return false; std::string proto_s = s_uri.substr(0, delim); std::cout << "proto_s is " << proto_s << std::endl; if("http" == proto_s || "HTTP" == proto_s) { protocol = Protocol::HTTP; } else if("https" == proto_s || "HTTPS" == proto_s) { protocol = Protocol::HTTPS; } else { return false; } s_uri = s_uri.substr(delim+3); // parse path delim = s_uri.find("/"); if(delim == std::string::npos) { path = "/"; } else { path = s_uri.substr(delim); s_uri = s_uri.substr(0, delim); } std::cout << "Path is " << path << std::endl; //parse port delim = s_uri.find(":"); if(delim == std::string::npos) { port = 8080; } else { std::string s_port = s_uri.substr(delim+1); port = std::stoi(s_port); // FIXME: may throw exception } std::cout << "Port is " << port << std::endl; // reminder is server server = s_uri.substr(0, delim); std::cout << "server is " << server << std::endl; return true; } } // namespace
23.646341
97
0.580712
bendelec
912cc52e2b2b978b1892fd6af1f65cdde82d667b
996
cpp
C++
srcs/utils/datetime.cpp
alexandretea/ddti
d81fd3069e67402ba695a2ada50a67f90ea45fb9
[ "MIT" ]
3
2020-11-30T01:57:35.000Z
2021-06-15T01:36:10.000Z
srcs/utils/datetime.cpp
alexandretea/ddti
d81fd3069e67402ba695a2ada50a67f90ea45fb9
[ "MIT" ]
null
null
null
srcs/utils/datetime.cpp
alexandretea/ddti
d81fd3069e67402ba695a2ada50a67f90ea45fb9
[ "MIT" ]
1
2020-11-30T01:57:48.000Z
2020-11-30T01:57:48.000Z
// C/C++ File // Author: Alexandre Tea <alexandre.qtea@gmail.com> // File: /Users/alexandretea/Work/ddti/srcs/utils/datetime.cpp // Purpose: datetime utilities // Created: 2017-07-29 22:52:26 // Modified: 2017-08-23 23:19:15 #include <ctime> #include "datetime.hpp" namespace utils { namespace datetime { std::string now_str(char const* format) { std::time_t t = std::time(0); char cstr[128]; std::strftime(cstr, sizeof(cstr), format, std::localtime(&t)); return cstr; } // Timer class Timer::Timer() : _start(chrono::system_clock::now()), _end(chrono::system_clock::now()) { } Timer::~Timer() { } void Timer::start() { _start = chrono::system_clock::now(); _end = chrono::system_clock::now(); } void Timer::stop() { _end = chrono::system_clock::now(); } void Timer::reset() { _start = chrono::system_clock::now(); _end = chrono::system_clock::now(); } } // end of namespace datetime } // end of namespace utils
17.172414
66
0.631526
alexandretea
912cdf3d4eaeb961412b1a5c078948adb4ca82da
1,771
cpp
C++
AllStat/source/Generator.cpp
efmsoft/allstat
54409844f533811964679b033eeb4a9b1c59c961
[ "Apache-2.0" ]
4
2021-05-26T15:42:20.000Z
2022-01-27T09:04:30.000Z
AllStat/source/Generator.cpp
efmsoft/allstat
54409844f533811964679b033eeb4a9b1c59c961
[ "Apache-2.0" ]
null
null
null
AllStat/source/Generator.cpp
efmsoft/allstat
54409844f533811964679b033eeb4a9b1c59c961
[ "Apache-2.0" ]
null
null
null
#define _CRT_NONSTDC_NO_DEPRECATE #include <AllStat/AllStat.h> #include "Generator.h" using namespace AllStat; #pragma warning(disable : 4996 26812) AllStat::Generator* AllStat::Generator::First = nullptr; Generator::Generator( const char* name , const char* format , AS_GENERATOR id , FGetTables gettables , FGetInfo getinfo , FGetConst getconst ) : Next(nullptr) , ID(id) , Name(name) , Format(format) , Tables{} , GetInfo(getinfo) , GetConst(getconst) { gettables(Tables); Next = First; First = this; } std::string Generator::ToStr(uint32_t e) { const STATUS_ITEM* p = EntryByCode(e, Tables.Items, Tables.Code2name); return FormatName(e, p, Format); } const char* Generator::ToStrC(uint32_t e) { std::string str = ToStr(e); return strdup(str.c_str()); } ItemArray Generator::ToInfo(uint32_t e) { ItemArray aa; auto a = EntryByCodeArray(e, Tables.Items, Tables.Code2name); for (auto it = a.begin(); it != a.end(); ++it) { auto item = *it; AS_ITEM ai; ItemFromStatusItem(*item, ai, ID, ID); aa.push_back(ai); } return aa; } PAS_ITEM_ARRAY Generator::ToInfoC(uint32_t e) { ItemArray arr = ToInfo(e); return BuildItemArray(arr); } const char* Generator::ToName(uint32_t e) { const STATUS_ITEM* p = EntryByCode(e, Tables.Items, Tables.Code2name); return p ? p->Name : nullptr; } uint32_t Generator::ToItem(const char* constant_name, PAS_ITEM pitem) { if (pitem == nullptr) { assert(pitem); return AS_UNKNOWN; } auto e = EntryByName(constant_name, Tables.Items, Tables.Name2code); if (e == nullptr) return AS_UNKNOWN; ItemFromStatusItem(*e, *pitem, ID, ID); return 0; }
20.125
73
0.647657
efmsoft
9132187b6b9c4b45a56d0813fb2d310b9dacbfad
32,161
cpp
C++
third_party/virtualbox/src/VBox/Devices/Storage/ATAPIPassthrough.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
third_party/virtualbox/src/VBox/Devices/Storage/ATAPIPassthrough.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
third_party/virtualbox/src/VBox/Devices/Storage/ATAPIPassthrough.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/* $Id: ATAPIPassthrough.cpp $ */ /** @file * VBox storage devices: ATAPI emulation (common code for DevATA and DevAHCI). */ /* * Copyright (C) 2012-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #define LOG_GROUP LOG_GROUP_DEV_IDE #include <iprt/log.h> #include <iprt/assert.h> #include <iprt/mem.h> #include <iprt/string.h> #include <VBox/log.h> #include <VBox/err.h> #include <VBox/cdefs.h> #include <VBox/scsi.h> #include <VBox/scsiinline.h> #include "ATAPIPassthrough.h" /** The track was not detected yet. */ #define TRACK_FLAGS_UNDETECTED RT_BIT_32(0) /** The track is the lead in track of the medium. */ #define TRACK_FLAGS_LEAD_IN RT_BIT_32(1) /** The track is the lead out track of the medium. */ #define TRACK_FLAGS_LEAD_OUT RT_BIT_32(2) /** Don't clear already detected tracks on the medium. */ #define ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR RT_BIT_32(0) /** * Track main data form. */ typedef enum TRACKDATAFORM { /** Invalid data form. */ TRACKDATAFORM_INVALID = 0, /** 2352 bytes of data. */ TRACKDATAFORM_CDDA, /** CDDA data is pause. */ TRACKDATAFORM_CDDA_PAUSE, /** Mode 1 with 2048 bytes sector size. */ TRACKDATAFORM_MODE1_2048, /** Mode 1 with 2352 bytes sector size. */ TRACKDATAFORM_MODE1_2352, /** Mode 1 with 0 bytes sector size (generated by the drive). */ TRACKDATAFORM_MODE1_0, /** XA Mode with 2336 bytes sector size. */ TRACKDATAFORM_XA_2336, /** XA Mode with 2352 bytes sector size. */ TRACKDATAFORM_XA_2352, /** XA Mode with 0 bytes sector size (generated by the drive). */ TRACKDATAFORM_XA_0, /** Mode 2 with 2336 bytes sector size. */ TRACKDATAFORM_MODE2_2336, /** Mode 2 with 2352 bytes sector size. */ TRACKDATAFORM_MODE2_2352, /** Mode 2 with 0 bytes sector size (generated by the drive). */ TRACKDATAFORM_MODE2_0 } TRACKDATAFORM; /** * Subchannel data form. */ typedef enum SUBCHNDATAFORM { /** Invalid subchannel data form. */ SUBCHNDATAFORM_INVALID = 0, /** 0 bytes for the subchannel (generated by the drive). */ SUBCHNDATAFORM_0, /** 96 bytes of data for the subchannel. */ SUBCHNDATAFORM_96 } SUBCHNDATAFORM; /** * Track entry. */ typedef struct TRACK { /** Start LBA of the track. */ int64_t iLbaStart; /** Number of sectors in the track. */ uint32_t cSectors; /** Data form of main data. */ TRACKDATAFORM enmMainDataForm; /** Data form of sub channel. */ SUBCHNDATAFORM enmSubChnDataForm; /** Flags for the track. */ uint32_t fFlags; } TRACK, *PTRACK; /** * Media track list. */ typedef struct TRACKLIST { /** Number of detected tracks of the current medium. */ unsigned cTracksCurrent; /** Maximum number of tracks the list can contain. */ unsigned cTracksMax; /** Variable list of tracks. */ PTRACK paTracks; } TRACKLIST, *PTRACKLIST; /** * Reallocate the given track list to be able to hold the given number of tracks. * * @returns VBox status code. * @param pTrackList The track list to reallocate. * @param cTracks Number of tracks the list must be able to hold. * @param fFlags Flags for the reallocation. */ static int atapiTrackListReallocate(PTRACKLIST pTrackList, unsigned cTracks, uint32_t fFlags) { int rc = VINF_SUCCESS; if (!(fFlags & ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR)) ATAPIPassthroughTrackListClear(pTrackList); if (pTrackList->cTracksMax < cTracks) { PTRACK paTracksNew = (PTRACK)RTMemRealloc(pTrackList->paTracks, cTracks * sizeof(TRACK)); if (paTracksNew) { pTrackList->paTracks = paTracksNew; /* Mark new tracks as undetected. */ for (unsigned i = pTrackList->cTracksMax; i < cTracks; i++) pTrackList->paTracks[i].fFlags |= TRACK_FLAGS_UNDETECTED; pTrackList->cTracksMax = cTracks; } else rc = VERR_NO_MEMORY; } if (RT_SUCCESS(rc)) pTrackList->cTracksCurrent = cTracks; return rc; } /** * Initilizes the given track from the given CUE sheet entry. * * @returns nothing. * @param pTrack The track to initialize. * @param pbCueSheetEntry CUE sheet entry to use. */ static void atapiTrackListEntryCreateFromCueSheetEntry(PTRACK pTrack, const uint8_t *pbCueSheetEntry) { TRACKDATAFORM enmTrackDataForm = TRACKDATAFORM_INVALID; SUBCHNDATAFORM enmSubChnDataForm = SUBCHNDATAFORM_INVALID; /* Determine size of main data based on the data form field. */ switch (pbCueSheetEntry[3] & 0x3f) { case 0x00: /* CD-DA with data. */ enmTrackDataForm = TRACKDATAFORM_CDDA; break; case 0x01: /* CD-DA without data (used for pauses between tracks). */ enmTrackDataForm = TRACKDATAFORM_CDDA_PAUSE; break; case 0x10: /* CD-ROM mode 1 */ case 0x12: enmTrackDataForm = TRACKDATAFORM_MODE1_2048; break; case 0x11: case 0x13: enmTrackDataForm = TRACKDATAFORM_MODE1_2352; break; case 0x14: enmTrackDataForm = TRACKDATAFORM_MODE1_0; break; case 0x20: /* CD-ROM XA, CD-I */ case 0x22: enmTrackDataForm = TRACKDATAFORM_XA_2336; break; case 0x21: case 0x23: enmTrackDataForm = TRACKDATAFORM_XA_2352; break; case 0x24: enmTrackDataForm = TRACKDATAFORM_XA_0; break; case 0x31: /* CD-ROM Mode 2 */ case 0x33: enmTrackDataForm = TRACKDATAFORM_MODE2_2352; break; case 0x30: case 0x32: enmTrackDataForm = TRACKDATAFORM_MODE2_2336; break; case 0x34: enmTrackDataForm = TRACKDATAFORM_MODE2_0; break; default: /* Reserved, invalid mode. Log and leave default sector size. */ LogRel(("ATA: Invalid data form mode %d for current CUE sheet\n", pbCueSheetEntry[3] & 0x3f)); } /* Determine size of sub channel data based on data form field. */ switch ((pbCueSheetEntry[3] & 0xc0) >> 6) { case 0x00: /* Sub channel all zeroes, autogenerated by the drive. */ enmSubChnDataForm = SUBCHNDATAFORM_0; break; case 0x01: case 0x03: enmSubChnDataForm = SUBCHNDATAFORM_96; break; default: LogRel(("ATA: Invalid sub-channel data form mode %u for current CUE sheet\n", pbCueSheetEntry[3] & 0xc0)); } pTrack->enmMainDataForm = enmTrackDataForm; pTrack->enmSubChnDataForm = enmSubChnDataForm; pTrack->iLbaStart = scsiMSF2LBA(&pbCueSheetEntry[5]); if (pbCueSheetEntry[1] != 0xaa) { /* Calculate number of sectors from the next entry. */ int64_t iLbaNext = scsiMSF2LBA(&pbCueSheetEntry[5+8]); pTrack->cSectors = iLbaNext - pTrack->iLbaStart; } else { pTrack->fFlags |= TRACK_FLAGS_LEAD_OUT; pTrack->cSectors = 0; } pTrack->fFlags &= ~TRACK_FLAGS_UNDETECTED; } /** * Update the track list from a SEND CUE SHEET request. * * @returns VBox status code. * @param pTrackList Track list to update. * @param pbCDB CDB of the SEND CUE SHEET request. * @param pvBuf The CUE sheet. */ static int atapiTrackListUpdateFromSendCueSheet(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { int rc = VINF_SUCCESS; unsigned cbCueSheet = scsiBE2H_U24(pbCDB + 6); unsigned cTracks = cbCueSheet / 8; AssertReturn(cbCueSheet % 8 == 0 && cTracks, VERR_INVALID_PARAMETER); rc = atapiTrackListReallocate(pTrackList, cTracks, 0); if (RT_SUCCESS(rc)) { const uint8_t *pbCueSheet = (uint8_t *)pvBuf; PTRACK pTrack = pTrackList->paTracks; for (unsigned i = 0; i < cTracks; i++) { atapiTrackListEntryCreateFromCueSheetEntry(pTrack, pbCueSheet); if (i == 0) pTrack->fFlags |= TRACK_FLAGS_LEAD_IN; pTrack++; pbCueSheet += 8; } } return rc; } static int atapiTrackListUpdateFromSendDvdStructure(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { RT_NOREF(pTrackList, pbCDB, pvBuf); return VERR_NOT_IMPLEMENTED; } /** * Update track list from formatted TOC data. * * @returns VBox status code. * @param pTrackList The track list to update. * @param iTrack The first track the TOC has data for. * @param fMSF Flag whether block addresses are in MSF or LBA format. * @param pbBuf Buffer holding the formatted TOC. * @param cbBuffer Size of the buffer. */ static int atapiTrackListUpdateFromFormattedToc(PTRACKLIST pTrackList, uint8_t iTrack, bool fMSF, const uint8_t *pbBuf, uint32_t cbBuffer) { RT_NOREF(iTrack, cbBuffer); /** @todo unused parameters */ int rc = VINF_SUCCESS; unsigned cbToc = scsiBE2H_U16(pbBuf); uint8_t iTrackFirst = pbBuf[2]; unsigned cTracks; cbToc -= 2; pbBuf += 4; AssertReturn(cbToc % 8 == 0, VERR_INVALID_PARAMETER); cTracks = cbToc / 8 + iTrackFirst; rc = atapiTrackListReallocate(pTrackList, iTrackFirst + cTracks, ATAPI_TRACK_LIST_REALLOCATE_FLAGS_DONT_CLEAR); if (RT_SUCCESS(rc)) { PTRACK pTrack = &pTrackList->paTracks[iTrackFirst]; for (unsigned i = iTrackFirst; i < cTracks; i++) { if (pbBuf[1] & 0x4) pTrack->enmMainDataForm = TRACKDATAFORM_MODE1_2048; else pTrack->enmMainDataForm = TRACKDATAFORM_CDDA; pTrack->enmSubChnDataForm = SUBCHNDATAFORM_0; if (fMSF) pTrack->iLbaStart = scsiMSF2LBA(&pbBuf[4]); else pTrack->iLbaStart = scsiBE2H_U32(&pbBuf[4]); if (pbBuf[2] != 0xaa) { /* Calculate number of sectors from the next entry. */ int64_t iLbaNext; if (fMSF) iLbaNext = scsiMSF2LBA(&pbBuf[4+8]); else iLbaNext = scsiBE2H_U32(&pbBuf[4+8]); pTrack->cSectors = iLbaNext - pTrack->iLbaStart; } else pTrack->cSectors = 0; pTrack->fFlags &= ~TRACK_FLAGS_UNDETECTED; pbBuf += 8; pTrack++; } } return rc; } static int atapiTrackListUpdateFromReadTocPmaAtip(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { int rc = VINF_SUCCESS; uint16_t cbBuffer = scsiBE2H_U16(&pbCDB[7]); bool fMSF = (pbCDB[1] & 0x2) != 0; uint8_t uFmt = pbCDB[2] & 0xf; uint8_t iTrack = pbCDB[6]; switch (uFmt) { case 0x00: rc = atapiTrackListUpdateFromFormattedToc(pTrackList, iTrack, fMSF, (uint8_t *)pvBuf, cbBuffer); break; case 0x01: case 0x02: case 0x03: case 0x04: rc = VERR_NOT_IMPLEMENTED; break; case 0x05: rc = VINF_SUCCESS; /* Does not give information about the tracklist. */ break; default: rc = VERR_INVALID_PARAMETER; } return rc; } static int atapiTrackListUpdateFromReadTrackInformation(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { RT_NOREF(pTrackList, pbCDB, pvBuf); return VERR_NOT_IMPLEMENTED; } static int atapiTrackListUpdateFromReadDvdStructure(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { RT_NOREF(pTrackList, pbCDB, pvBuf); return VERR_NOT_IMPLEMENTED; } static int atapiTrackListUpdateFromReadDiscInformation(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { RT_NOREF(pTrackList, pbCDB, pvBuf); return VERR_NOT_IMPLEMENTED; } #ifdef LOG_ENABLED /** * Converts the given track data form to a string. * * @returns Track data form as a string. * @param enmTrackDataForm The track main data form. */ static const char *atapiTrackListMainDataFormToString(TRACKDATAFORM enmTrackDataForm) { switch (enmTrackDataForm) { case TRACKDATAFORM_CDDA: return "CD-DA"; case TRACKDATAFORM_CDDA_PAUSE: return "CD-DA Pause"; case TRACKDATAFORM_MODE1_2048: return "Mode 1 (2048 bytes)"; case TRACKDATAFORM_MODE1_2352: return "Mode 1 (2352 bytes)"; case TRACKDATAFORM_MODE1_0: return "Mode 1 (0 bytes)"; case TRACKDATAFORM_XA_2336: return "XA (2336 bytes)"; case TRACKDATAFORM_XA_2352: return "XA (2352 bytes)"; case TRACKDATAFORM_XA_0: return "XA (0 bytes)"; case TRACKDATAFORM_MODE2_2336: return "Mode 2 (2336 bytes)"; case TRACKDATAFORM_MODE2_2352: return "Mode 2 (2352 bytes)"; case TRACKDATAFORM_MODE2_0: return "Mode 2 (0 bytes)"; case TRACKDATAFORM_INVALID: default: return "Invalid"; } } /** * Converts the given subchannel data form to a string. * * @returns Subchannel data form as a string. * @param enmSubChnDataForm The subchannel main data form. */ static const char *atapiTrackListSubChnDataFormToString(SUBCHNDATAFORM enmSubChnDataForm) { switch (enmSubChnDataForm) { case SUBCHNDATAFORM_0: return "0"; case SUBCHNDATAFORM_96: return "96"; case SUBCHNDATAFORM_INVALID: default: return "Invalid"; } } /** * Dump the complete track list to the release log. * * @returns nothing. * @param pTrackList The track list to dump. */ static void atapiTrackListDump(PTRACKLIST pTrackList) { LogRel(("Track List: cTracks=%u\n", pTrackList->cTracksCurrent)); for (unsigned i = 0; i < pTrackList->cTracksCurrent; i++) { PTRACK pTrack = &pTrackList->paTracks[i]; LogRel((" Track %u: LBAStart=%lld cSectors=%u enmMainDataForm=%s enmSubChnDataForm=%s fFlags=[%s%s%s]\n", i, pTrack->iLbaStart, pTrack->cSectors, atapiTrackListMainDataFormToString(pTrack->enmMainDataForm), atapiTrackListSubChnDataFormToString(pTrack->enmSubChnDataForm), pTrack->fFlags & TRACK_FLAGS_UNDETECTED ? "UNDETECTED " : "", pTrack->fFlags & TRACK_FLAGS_LEAD_IN ? "Lead-In " : "", pTrack->fFlags & TRACK_FLAGS_LEAD_OUT ? "Lead-Out" : "")); } } #endif /* LOG_ENABLED */ DECLHIDDEN(int) ATAPIPassthroughTrackListCreateEmpty(PTRACKLIST *ppTrackList) { int rc = VERR_NO_MEMORY; PTRACKLIST pTrackList = (PTRACKLIST)RTMemAllocZ(sizeof(TRACKLIST)); if (pTrackList) { rc = VINF_SUCCESS; *ppTrackList = pTrackList; } return rc; } DECLHIDDEN(void) ATAPIPassthroughTrackListDestroy(PTRACKLIST pTrackList) { if (pTrackList->paTracks) RTMemFree(pTrackList->paTracks); RTMemFree(pTrackList); } DECLHIDDEN(void) ATAPIPassthroughTrackListClear(PTRACKLIST pTrackList) { AssertPtrReturnVoid(pTrackList); pTrackList->cTracksCurrent = 0; /* Mark all tracks as undetected. */ for (unsigned i = 0; i < pTrackList->cTracksMax; i++) pTrackList->paTracks[i].fFlags |= TRACK_FLAGS_UNDETECTED; } DECLHIDDEN(int) ATAPIPassthroughTrackListUpdate(PTRACKLIST pTrackList, const uint8_t *pbCDB, const void *pvBuf) { int rc = VINF_SUCCESS; switch (pbCDB[0]) { case SCSI_SEND_CUE_SHEET: rc = atapiTrackListUpdateFromSendCueSheet(pTrackList, pbCDB, pvBuf); break; case SCSI_SEND_DVD_STRUCTURE: rc = atapiTrackListUpdateFromSendDvdStructure(pTrackList, pbCDB, pvBuf); break; case SCSI_READ_TOC_PMA_ATIP: rc = atapiTrackListUpdateFromReadTocPmaAtip(pTrackList, pbCDB, pvBuf); break; case SCSI_READ_TRACK_INFORMATION: rc = atapiTrackListUpdateFromReadTrackInformation(pTrackList, pbCDB, pvBuf); break; case SCSI_READ_DVD_STRUCTURE: rc = atapiTrackListUpdateFromReadDvdStructure(pTrackList, pbCDB, pvBuf); break; case SCSI_READ_DISC_INFORMATION: rc = atapiTrackListUpdateFromReadDiscInformation(pTrackList, pbCDB, pvBuf); break; default: LogRel(("ATAPI: Invalid opcode %#x while determining media layout\n", pbCDB[0])); rc = VERR_INVALID_PARAMETER; } #ifdef LOG_ENABLED atapiTrackListDump(pTrackList); #endif return rc; } DECLHIDDEN(uint32_t) ATAPIPassthroughTrackListGetSectorSizeFromLba(PTRACKLIST pTrackList, uint32_t iAtapiLba) { PTRACK pTrack = NULL; uint32_t cbAtapiSector = 2048; if (pTrackList->cTracksCurrent) { if ( iAtapiLba > UINT32_C(0xffff4fa1) && (int32_t)iAtapiLba < -150) { /* Lead-In area, this is always the first entry in the cue sheet. */ pTrack = pTrackList->paTracks; Assert(pTrack->fFlags & TRACK_FLAGS_LEAD_IN); LogFlowFunc(("Selected Lead-In area\n")); } else { int64_t iAtapiLba64 = (int32_t)iAtapiLba; pTrack = &pTrackList->paTracks[1]; /* Go through the track list and find the correct entry. */ for (unsigned i = 1; i < pTrackList->cTracksCurrent - 1; i++) { if (pTrack->fFlags & TRACK_FLAGS_UNDETECTED) continue; if ( pTrack->iLbaStart <= iAtapiLba64 && iAtapiLba64 < pTrack->iLbaStart + pTrack->cSectors) break; pTrack++; } } if (pTrack) { switch (pTrack->enmMainDataForm) { case TRACKDATAFORM_CDDA: case TRACKDATAFORM_MODE1_2352: case TRACKDATAFORM_XA_2352: case TRACKDATAFORM_MODE2_2352: cbAtapiSector = 2352; break; case TRACKDATAFORM_MODE1_2048: cbAtapiSector = 2048; break; case TRACKDATAFORM_CDDA_PAUSE: case TRACKDATAFORM_MODE1_0: case TRACKDATAFORM_XA_0: case TRACKDATAFORM_MODE2_0: cbAtapiSector = 0; break; case TRACKDATAFORM_XA_2336: case TRACKDATAFORM_MODE2_2336: cbAtapiSector = 2336; break; case TRACKDATAFORM_INVALID: default: AssertMsgFailed(("Invalid track data form %d\n", pTrack->enmMainDataForm)); } switch (pTrack->enmSubChnDataForm) { case SUBCHNDATAFORM_0: break; case SUBCHNDATAFORM_96: cbAtapiSector += 96; break; case SUBCHNDATAFORM_INVALID: default: AssertMsgFailed(("Invalid subchannel data form %d\n", pTrack->enmSubChnDataForm)); } } } return cbAtapiSector; } static uint8_t atapiPassthroughCmdErrorSimple(uint8_t *pbSense, size_t cbSense, uint8_t uATAPISenseKey, uint8_t uATAPIASC) { memset(pbSense, '\0', cbSense); if (RT_LIKELY(cbSense >= 13)) { pbSense[0] = 0x70 | (1 << 7); pbSense[2] = uATAPISenseKey & 0x0f; pbSense[7] = 10; pbSense[12] = uATAPIASC; } return SCSI_STATUS_CHECK_CONDITION; } DECLHIDDEN(bool) ATAPIPassthroughParseCdb(const uint8_t *pbCdb, size_t cbCdb, size_t cbBuf, PTRACKLIST pTrackList, uint8_t *pbSense, size_t cbSense, PDMMEDIATXDIR *penmTxDir, size_t *pcbXfer, size_t *pcbSector, uint8_t *pu8ScsiSts) { uint32_t uLba = 0; uint32_t cSectors = 0; size_t cbSector = 0; size_t cbXfer = 0; bool fPassthrough = false; PDMMEDIATXDIR enmTxDir = PDMMEDIATXDIR_NONE; RT_NOREF(cbCdb); switch (pbCdb[0]) { /* First the commands we can pass through without further processing. */ case SCSI_BLANK: case SCSI_CLOSE_TRACK_SESSION: case SCSI_LOAD_UNLOAD_MEDIUM: case SCSI_PAUSE_RESUME: case SCSI_PLAY_AUDIO_10: case SCSI_PLAY_AUDIO_12: case SCSI_PLAY_AUDIO_MSF: case SCSI_PREVENT_ALLOW_MEDIUM_REMOVAL: case SCSI_REPAIR_TRACK: case SCSI_RESERVE_TRACK: case SCSI_SCAN: case SCSI_SEEK_10: case SCSI_SET_CD_SPEED: case SCSI_SET_READ_AHEAD: case SCSI_START_STOP_UNIT: case SCSI_STOP_PLAY_SCAN: case SCSI_SYNCHRONIZE_CACHE: case SCSI_TEST_UNIT_READY: case SCSI_VERIFY_10: fPassthrough = true; break; case SCSI_ERASE_10: uLba = scsiBE2H_U32(pbCdb + 2); cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_FORMAT_UNIT: cbXfer = cbBuf; enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_GET_CONFIGURATION: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_GET_EVENT_STATUS_NOTIFICATION: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_GET_PERFORMANCE: cbXfer = cbBuf; enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_INQUIRY: cbXfer = scsiBE2H_U16(pbCdb + 3); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_MECHANISM_STATUS: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_MODE_SELECT_10: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_MODE_SENSE_10: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_10: uLba = scsiBE2H_U32(pbCdb + 2); cSectors = scsiBE2H_U16(pbCdb + 7); cbSector = 2048; cbXfer = cSectors * cbSector; enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_12: uLba = scsiBE2H_U32(pbCdb + 2); cSectors = scsiBE2H_U32(pbCdb + 6); cbSector = 2048; cbXfer = cSectors * cbSector; enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_BUFFER: cbXfer = scsiBE2H_U24(pbCdb + 6); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_BUFFER_CAPACITY: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_CAPACITY: cbXfer = 8; enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_CD: case SCSI_READ_CD_MSF: { /* Get sector size based on the expected sector type field. */ switch ((pbCdb[1] >> 2) & 0x7) { case 0x0: /* All types. */ { uint32_t iLbaStart; if (pbCdb[0] == SCSI_READ_CD) iLbaStart = scsiBE2H_U32(&pbCdb[2]); else iLbaStart = scsiMSF2LBA(&pbCdb[3]); if (pTrackList) cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, iLbaStart); else cbSector = 2048; /* Might be incorrect if we couldn't determine the type. */ break; } case 0x1: /* CD-DA */ cbSector = 2352; break; case 0x2: /* Mode 1 */ cbSector = 2048; break; case 0x3: /* Mode 2 formless */ cbSector = 2336; break; case 0x4: /* Mode 2 form 1 */ cbSector = 2048; break; case 0x5: /* Mode 2 form 2 */ cbSector = 2324; break; default: /* Reserved */ AssertMsgFailed(("Unknown sector type\n")); cbSector = 0; /** @todo we should probably fail the command here already. */ } if (pbCdb[0] == SCSI_READ_CD) cbXfer = scsiBE2H_U24(pbCdb + 6) * cbSector; else /* SCSI_READ_MSF */ { cSectors = scsiMSF2LBA(pbCdb + 6) - scsiMSF2LBA(pbCdb + 3); if (cSectors > 32) cSectors = 32; /* Limit transfer size to 64~74K. Safety first. In any case this can only harm software doing CDDA extraction. */ cbXfer = cSectors * cbSector; } enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; } case SCSI_READ_DISC_INFORMATION: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_DVD_STRUCTURE: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_FORMAT_CAPACITIES: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_SUBCHANNEL: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_TOC_PMA_ATIP: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_READ_TRACK_INFORMATION: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_REPORT_KEY: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_REQUEST_SENSE: cbXfer = pbCdb[4]; enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_SEND_CUE_SHEET: cbXfer = scsiBE2H_U24(pbCdb + 6); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_SEND_DVD_STRUCTURE: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_SEND_EVENT: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_SEND_KEY: cbXfer = scsiBE2H_U16(pbCdb + 8); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_SEND_OPC_INFORMATION: cbXfer = scsiBE2H_U16(pbCdb + 7); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_SET_STREAMING: cbXfer = scsiBE2H_U16(pbCdb + 9); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_WRITE_10: case SCSI_WRITE_AND_VERIFY_10: uLba = scsiBE2H_U32(pbCdb + 2); cSectors = scsiBE2H_U16(pbCdb + 7); if (pTrackList) cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, uLba); else cbSector = 2048; cbXfer = cSectors * cbSector; enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_WRITE_12: uLba = scsiBE2H_U32(pbCdb + 2); cSectors = scsiBE2H_U32(pbCdb + 6); if (pTrackList) cbSector = ATAPIPassthroughTrackListGetSectorSizeFromLba(pTrackList, uLba); else cbSector = 2048; cbXfer = cSectors * cbSector; enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; case SCSI_WRITE_BUFFER: switch (pbCdb[1] & 0x1f) { case 0x04: /* download microcode */ case 0x05: /* download microcode and save */ case 0x06: /* download microcode with offsets */ case 0x07: /* download microcode with offsets and save */ case 0x0e: /* download microcode with offsets and defer activation */ case 0x0f: /* activate deferred microcode */ LogRel(("ATAPI: CD-ROM passthrough command attempted to update firmware, blocked\n")); *pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_INV_FIELD_IN_CMD_PACKET); break; default: cbXfer = scsiBE2H_U16(pbCdb + 6); enmTxDir = PDMMEDIATXDIR_TO_DEVICE; fPassthrough = true; break; } break; case SCSI_REPORT_LUNS: /* Not part of MMC-3, but used by Windows. */ cbXfer = scsiBE2H_U32(pbCdb + 6); enmTxDir = PDMMEDIATXDIR_FROM_DEVICE; fPassthrough = true; break; case SCSI_REZERO_UNIT: /* Obsolete command used by cdrecord. What else would one expect? * This command is not sent to the drive, it is handled internally, * as the Linux kernel doesn't like it (message "scsi: unknown * opcode 0x01" in syslog) and replies with a sense code of 0, * which sends cdrecord to an endless loop. */ *pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE); break; default: LogRel(("ATAPI: Passthrough unimplemented for command %#x\n", pbCdb[0])); *pu8ScsiSts = atapiPassthroughCmdErrorSimple(pbSense, cbSense, SCSI_SENSE_ILLEGAL_REQUEST, SCSI_ASC_ILLEGAL_OPCODE); break; } if (fPassthrough) { *penmTxDir = enmTxDir; *pcbXfer = cbXfer; *pcbSector = cbSector; } return fPassthrough; }
33.641213
148
0.589161
Fimbure
9135f5762b1991c7b3549b6f7a47b86fe68019ac
318
cpp
C++
Demos/ODFAEGVIDEOTUTORIAL/bar.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
5
2015-06-13T13:11:59.000Z
2020-04-17T23:10:23.000Z
Demos/ODFAEGVIDEOTUTORIAL/bar.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
4
2019-01-07T11:46:21.000Z
2020-02-14T15:04:15.000Z
Demos/ODFAEGVIDEOTUTORIAL/bar.cpp
Cwc-Test/ODFAEG
5e5bd13e3145764c3d0182225aad591040691481
[ "Zlib" ]
4
2016-01-05T09:54:57.000Z
2021-01-06T18:52:26.000Z
#include "bar.hpp" using namespace odfaeg::graphic; using namespace odfaeg::math; using namespace odfaeg::physic; Bar::Bar(Vec2f position, Vec2f size) : Entity(position, size, size * 0.5f, "E_BAR") { BoundingVolume* bv = new BoundingBox(position.x, position.y, 0 ,size.x, size.y, 0); setCollisionVolume(bv); }
35.333333
87
0.716981
Cwc-Test
913927feb67944f43b5632fc1701f53ba18637b1
7,792
cc
C++
chrome/browser/search/suggestions/suggestions_service_unittest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-16T03:57:28.000Z
2021-01-23T15:29:45.000Z
chrome/browser/search/suggestions/suggestions_service_unittest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/browser/search/suggestions/suggestions_service_unittest.cc
shaochangbin/chromium-crosswalk
634d34e4cf82b4f7400357c53ec12efaffe94add
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2015-04-17T13:19:09.000Z
2021-10-21T12:55:15.000Z
// Copyright 2014 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 "chrome/browser/search/suggestions/suggestions_service.h" #include <map> #include <string> #include "base/bind.h" #include "base/memory/scoped_ptr.h" #include "base/metrics/field_trial.h" #include "base/prefs/pref_service.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/history/history_types.h" #include "chrome/browser/search/suggestions/proto/suggestions.pb.h" #include "chrome/browser/search/suggestions/suggestions_service_factory.h" #include "chrome/test/base/testing_profile.h" #include "components/variations/entropy_provider.h" #include "components/variations/variations_associated_data.h" #include "content/public/test/test_browser_thread_bundle.h" #include "net/http/http_response_headers.h" #include "net/http/http_status_code.h" #include "net/url_request/test_url_fetcher_factory.h" #include "net/url_request/url_request_status.h" #include "net/url_request/url_request_test_util.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kFakeSuggestionsURL[] = "https://mysuggestions.com/proto"; const char kTestTitle[] = "a title"; const char kTestUrl[] = "http://go.com"; scoped_ptr<net::FakeURLFetcher> CreateURLFetcher( const GURL& url, net::URLFetcherDelegate* delegate, const std::string& response_data, net::HttpStatusCode response_code, net::URLRequestStatus::Status status) { scoped_ptr<net::FakeURLFetcher> fetcher(new net::FakeURLFetcher( url, delegate, response_data, response_code, status)); if (response_code == net::HTTP_OK) { scoped_refptr<net::HttpResponseHeaders> download_headers( new net::HttpResponseHeaders("")); download_headers->AddHeader("Content-Type: text/html"); fetcher->set_response_headers(download_headers); } return fetcher.Pass(); } } // namespace namespace suggestions { class SuggestionsServiceTest : public testing::Test { public: void CheckSuggestionsData(const SuggestionsProfile& suggestions_profile) { EXPECT_EQ(1, suggestions_profile.suggestions_size()); EXPECT_EQ(kTestTitle, suggestions_profile.suggestions(0).title()); EXPECT_EQ(kTestUrl, suggestions_profile.suggestions(0).url()); ++suggestions_data_check_count_; } void ExpectEmptySuggestionsProfile(const SuggestionsProfile& profile) { EXPECT_EQ(0, profile.suggestions_size()); ++suggestions_empty_data_count_; } int suggestions_data_check_count_; int suggestions_empty_data_count_; protected: SuggestionsServiceTest() : suggestions_data_check_count_(0), suggestions_empty_data_count_(0), factory_(NULL, base::Bind(&CreateURLFetcher)) { profile_ = profile_builder_.Build(); } virtual ~SuggestionsServiceTest() {} // Enables the "ChromeSuggestions.Group1" field trial. void EnableFieldTrial(const std::string& url) { // Clear the existing |field_trial_list_| to avoid firing a DCHECK. field_trial_list_.reset(NULL); field_trial_list_.reset( new base::FieldTrialList(new metrics::SHA1EntropyProvider("foo"))); chrome_variations::testing::ClearAllVariationParams(); std::map<std::string, std::string> params; params[kSuggestionsFieldTrialStateParam] = kSuggestionsFieldTrialStateEnabled; params[kSuggestionsFieldTrialURLParam] = url; chrome_variations::AssociateVariationParams(kSuggestionsFieldTrialName, "Group1", params); field_trial_ = base::FieldTrialList::CreateFieldTrial( kSuggestionsFieldTrialName, "Group1"); field_trial_->group(); } SuggestionsService* CreateSuggestionsService() { SuggestionsServiceFactory* suggestions_service_factory = SuggestionsServiceFactory::GetInstance(); return suggestions_service_factory->GetForProfile(profile_.get()); } protected: net::FakeURLFetcherFactory factory_; private: content::TestBrowserThreadBundle thread_bundle_; scoped_ptr<base::FieldTrialList> field_trial_list_; scoped_refptr<base::FieldTrial> field_trial_; TestingProfile::Builder profile_builder_; scoped_ptr<TestingProfile> profile_; DISALLOW_COPY_AND_ASSIGN(SuggestionsServiceTest); }; TEST_F(SuggestionsServiceTest, ServiceBeingCreated) { // Field trial not enabled. EXPECT_TRUE(CreateSuggestionsService() == NULL); // Field trial enabled. EnableFieldTrial(""); EXPECT_TRUE(CreateSuggestionsService() != NULL); } TEST_F(SuggestionsServiceTest, FetchSuggestionsData) { // Field trial enabled with a specific suggestions URL. EnableFieldTrial(kFakeSuggestionsURL); SuggestionsService* suggestions_service = CreateSuggestionsService(); EXPECT_TRUE(suggestions_service != NULL); SuggestionsProfile suggestions_profile; ChromeSuggestion* suggestion = suggestions_profile.add_suggestions(); suggestion->set_title(kTestTitle); suggestion->set_url(kTestUrl); factory_.SetFakeResponse(GURL(kFakeSuggestionsURL), suggestions_profile.SerializeAsString(), net::HTTP_OK, net::URLRequestStatus::SUCCESS); // Send the request. The data will be returned to the callback. suggestions_service->FetchSuggestionsData( base::Bind(&SuggestionsServiceTest::CheckSuggestionsData, base::Unretained(this))); // Send the request a second time. suggestions_service->FetchSuggestionsData( base::Bind(&SuggestionsServiceTest::CheckSuggestionsData, base::Unretained(this))); // (Testing only) wait until suggestion fetch is complete. base::MessageLoop::current()->RunUntilIdle(); // Ensure that CheckSuggestionsData() ran twice. EXPECT_EQ(2, suggestions_data_check_count_); } TEST_F(SuggestionsServiceTest, FetchSuggestionsDataRequestError) { // Field trial enabled with a specific suggestions URL. EnableFieldTrial(kFakeSuggestionsURL); SuggestionsService* suggestions_service = CreateSuggestionsService(); EXPECT_TRUE(suggestions_service != NULL); // Fake a request error. factory_.SetFakeResponse(GURL(kFakeSuggestionsURL), "irrelevant", net::HTTP_OK, net::URLRequestStatus::FAILED); // Send the request. Empty data will be returned to the callback. suggestions_service->FetchSuggestionsData( base::Bind(&SuggestionsServiceTest::ExpectEmptySuggestionsProfile, base::Unretained(this))); // (Testing only) wait until suggestion fetch is complete. base::MessageLoop::current()->RunUntilIdle(); // Ensure that ExpectEmptySuggestionsProfile ran once. EXPECT_EQ(1, suggestions_empty_data_count_); } TEST_F(SuggestionsServiceTest, FetchSuggestionsDataResponseNotOK) { // Field trial enabled with a specific suggestions URL. EnableFieldTrial(kFakeSuggestionsURL); SuggestionsService* suggestions_service = CreateSuggestionsService(); EXPECT_TRUE(suggestions_service != NULL); // Response code != 200. factory_.SetFakeResponse(GURL(kFakeSuggestionsURL), "irrelevant", net::HTTP_BAD_REQUEST, net::URLRequestStatus::SUCCESS); // Send the request. Empty data will be returned to the callback. suggestions_service->FetchSuggestionsData( base::Bind(&SuggestionsServiceTest::ExpectEmptySuggestionsProfile, base::Unretained(this))); // (Testing only) wait until suggestion fetch is complete. base::MessageLoop::current()->RunUntilIdle(); // Ensure that ExpectEmptySuggestionsProfile ran once. EXPECT_EQ(1, suggestions_empty_data_count_); } } // namespace suggestions
37.104762
76
0.741273
shaochangbin
913cb13eefd820e77540f03164b2ed79872be779
640
hpp
C++
ShadowPeople/sound/Mixer.hpp
SamuelSiltanen/ShadowPeople
58f94a4397dc5084d9705d4378599cae480b4776
[ "Apache-2.0" ]
null
null
null
ShadowPeople/sound/Mixer.hpp
SamuelSiltanen/ShadowPeople
58f94a4397dc5084d9705d4378599cae480b4776
[ "Apache-2.0" ]
null
null
null
ShadowPeople/sound/Mixer.hpp
SamuelSiltanen/ShadowPeople
58f94a4397dc5084d9705d4378599cae480b4776
[ "Apache-2.0" ]
null
null
null
#pragma once #include <memory> #include <random> #include "../Types.hpp" #include "AudioFormat.hpp" namespace sound { class RawAudioBuffer; class Mixer { public: Mixer(const AudioFormat& format); void setFormat(const AudioFormat& format); void mix(std::shared_ptr<RawAudioBuffer> rawAudioBuffer); private: void mixUnorm8(Range<uint8_t> data); void mixUnorm16(Range<uint16_t> data); void mixUnorm32(Range<uint32_t> data); void mixFloat32(Range<float> data); AudioFormat m_format; float m_mixerTime; std::mt19937 m_gen; }; }
20
65
0.635938
SamuelSiltanen
913cd8af5adfbebe6460514d0ef861a49f64b3c3
27,224
cc
C++
chrome/browser/nearby_sharing/nearby_per_session_discovery_manager_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
chrome/browser/nearby_sharing/nearby_per_session_discovery_manager_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/nearby_sharing/nearby_per_session_discovery_manager_unittest.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2020 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 "chrome/browser/nearby_sharing/nearby_per_session_discovery_manager.h" #include <string> #include "base/callback_forward.h" #include "base/callback_helpers.h" #include "base/optional.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/test/mock_callback.h" #include "chrome/browser/nearby_sharing/mock_nearby_sharing_service.h" #include "chrome/browser/nearby_sharing/share_target.h" #include "chrome/browser/nearby_sharing/transfer_metadata.h" #include "chrome/browser/nearby_sharing/transfer_metadata_builder.h" #include "chrome/browser/ui/webui/nearby_share/nearby_share.mojom.h" #include "content/public/test/browser_task_environment.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/pending_remote.h" #include "mojo/public/cpp/bindings/receiver.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace { using testing::_; MATCHER_P(MatchesTarget, target, "") { return arg.id == target.id; } const char kTextAttachmentBody[] = "Test text payload"; std::vector<std::unique_ptr<Attachment>> CreateTextAttachments() { std::vector<std::unique_ptr<Attachment>> attachments; attachments.push_back(std::make_unique<TextAttachment>( TextAttachment::Type::kText, kTextAttachmentBody, /*title=*/base::nullopt, /*mime_type=*/base::nullopt)); return attachments; } std::vector<std::unique_ptr<Attachment>> CreateFileAttachments( size_t count, std::string mime_type, sharing::mojom::FileMetadata::Type type) { std::vector<std::unique_ptr<Attachment>> attachments; for (size_t i = 0; i < count; i++) { std::string file_name("File-" + base::NumberToString(i)); attachments.push_back( std::make_unique<FileAttachment>(i, i, file_name, mime_type, type)); } return attachments; } void ExpectTextAttachment( const std::string& text_body, const std::vector<std::unique_ptr<Attachment>>& attachments) { ASSERT_EQ(1u, attachments.size()); ASSERT_TRUE(attachments[0]); ASSERT_EQ(Attachment::Family::kText, attachments[0]->family()); auto* text_attachment = static_cast<TextAttachment*>(attachments[0].get()); EXPECT_EQ(text_body, text_attachment->text_body()); } class MockShareTargetListener : public nearby_share::mojom::ShareTargetListener { public: MockShareTargetListener() = default; ~MockShareTargetListener() override = default; mojo::PendingRemote<ShareTargetListener> Bind() { return receiver_.BindNewPipeAndPassRemote(); } void reset() { receiver_.reset(); } // nearby_share::mojom::ShareTargetListener: MOCK_METHOD(void, OnShareTargetDiscovered, (const ShareTarget&), (override)); MOCK_METHOD(void, OnShareTargetLost, (const ShareTarget&), (override)); private: mojo::Receiver<ShareTargetListener> receiver_{this}; }; class MockTransferUpdateListener : public nearby_share::mojom::TransferUpdateListener { public: MockTransferUpdateListener() = default; ~MockTransferUpdateListener() override = default; void Bind(mojo::PendingReceiver<TransferUpdateListener> receiver) { return receiver_.Bind(std::move(receiver)); } // nearby_share::mojom::TransferUpdateListener: MOCK_METHOD(void, OnTransferUpdate, (nearby_share::mojom::TransferStatus status, const base::Optional<std::string>&), (override)); private: mojo::Receiver<TransferUpdateListener> receiver_{this}; }; class NearbyPerSessionDiscoveryManagerTest : public testing::Test { public: using MockSelectShareTargetCallback = base::MockCallback< NearbyPerSessionDiscoveryManager::SelectShareTargetCallback>; using MockStartDiscoveryCallback = base::MockCallback< NearbyPerSessionDiscoveryManager::StartDiscoveryCallback>; using MockGetPayloadPreviewCallback = base::MockCallback< nearby_share::mojom::DiscoveryManager::GetPayloadPreviewCallback>; enum SharingServiceState { None, Transferring, Connecting, Scanning }; NearbyPerSessionDiscoveryManagerTest() = default; ~NearbyPerSessionDiscoveryManagerTest() override = default; void SetUp() override { EXPECT_CALL(sharing_service(), IsTransferring()) .WillRepeatedly(testing::ReturnPointee(&is_transferring_)); EXPECT_CALL(sharing_service(), IsConnecting()) .WillRepeatedly(testing::ReturnPointee(&is_connecting_)); EXPECT_CALL(sharing_service(), IsScanning()) .WillRepeatedly(testing::ReturnPointee(&is_scanning_)); } void SetSharingServiceState(SharingServiceState state) { is_transferring_ = state == SharingServiceState::Transferring; is_connecting_ = state == SharingServiceState::Connecting; is_scanning_ = state == SharingServiceState::Scanning; } MockNearbySharingService& sharing_service() { return sharing_service_; } NearbyPerSessionDiscoveryManager& manager() { return manager_; } private: content::BrowserTaskEnvironment task_environment_; MockNearbySharingService sharing_service_; NearbyPerSessionDiscoveryManager manager_{&sharing_service_, CreateTextAttachments()}; bool is_transferring_ = false; bool is_scanning_ = false; bool is_connecting_ = false; }; } // namespace TEST_F(NearbyPerSessionDiscoveryManagerTest, CreateDestroyWithoutRegistering) { EXPECT_CALL(sharing_service(), RegisterSendSurface(&manager(), &manager(), _)) .Times(0); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .Times(0); { NearbyPerSessionDiscoveryManager manager(&sharing_service(), CreateTextAttachments()); // Creating and destroying an instance should not register itself with the // NearbySharingService. } } TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_Success) { EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); MockStartDiscoveryCallback callback; EXPECT_CALL( callback, Run( /*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess)); EXPECT_CALL( sharing_service(), RegisterSendSurface(&manager(), &manager(), NearbySharingService::SendSurfaceState::kForeground)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .Times(0); // Should not be called! MockShareTargetListener listener; manager().StartDiscovery(listener.Bind(), callback.Get()); // Reset the listener here like the UI does when switching pages. listener.reset(); // We have to run util idle to give the disconnect handler a chance to run. // We no longer have a disconnect handler, but we want to very that once the // mojo connection is torn down, that we don't unregister. base::RunLoop run_loop; run_loop.RunUntilIdle(); // Verify that UnregisterSendSurface was NOT called due to the disconnect. // This previously failed when disconnect handler was being registered. EXPECT_TRUE(::testing::Mock::VerifyAndClearExpectations(&sharing_service())); // However, we do expect UnregisterSendSurface to be called from the // destructor. EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_ErrorInProgress) { MockStartDiscoveryCallback callback; MockShareTargetListener listener; EXPECT_CALL(callback, Run(/*result=*/nearby_share::mojom::StartDiscoveryResult:: kErrorInProgressTransferring)); SetSharingServiceState(SharingServiceState::Transferring); manager().StartDiscovery(listener.Bind(), callback.Get()); listener.reset(); EXPECT_CALL(callback, Run(/*result=*/nearby_share::mojom::StartDiscoveryResult:: kErrorInProgressTransferring)); SetSharingServiceState(SharingServiceState::Connecting); manager().StartDiscovery(listener.Bind(), callback.Get()); listener.reset(); EXPECT_CALL(callback, Run(/*result=*/nearby_share::mojom::StartDiscoveryResult:: kErrorInProgressTransferring)); SetSharingServiceState(SharingServiceState::Scanning); manager().StartDiscovery(listener.Bind(), callback.Get()); listener.reset(); EXPECT_CALL( callback, Run(/*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess)); SetSharingServiceState(SharingServiceState::None); manager().StartDiscovery(listener.Bind(), callback.Get()); } TEST_F(NearbyPerSessionDiscoveryManagerTest, StartDiscovery_Error) { EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); MockStartDiscoveryCallback callback; EXPECT_CALL( callback, Run( /*result=*/nearby_share::mojom::StartDiscoveryResult::kErrorGeneric)); EXPECT_CALL( sharing_service(), RegisterSendSurface(&manager(), &manager(), NearbySharingService::SendSurfaceState::kForeground)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kError)); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .Times(0); MockShareTargetListener listener; manager().StartDiscovery(listener.Bind(), callback.Get()); } TEST_F(NearbyPerSessionDiscoveryManagerTest, OnShareTargetDiscovered) { MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; base::RunLoop run_loop; EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target))) .WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); manager().OnShareTargetDiscovered(share_target); run_loop.Run(); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, OnShareTargetDiscovered_DuplicateDeviceId) { MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target1; share_target1.device_id = "device_id"; ShareTarget share_target2; share_target2.device_id = "device_id"; { base::RunLoop run_loop; EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target1))) .WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); manager().OnShareTargetDiscovered(share_target1); run_loop.Run(); } // If a newly discovered share target has the same device ID as a previously // discovered share target, remove the old share target then add the new share // target. { base::RunLoop run_loop; EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target1))); EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target2))) .WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); manager().OnShareTargetDiscovered(share_target2); run_loop.Run(); } EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, OnShareTargetLost) { MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; // A share-target-lost notification should only be sent if the lost share // target has already been discovered and has not already been removed from // the list of discovered devices. EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target))) .Times(0); manager().OnShareTargetLost(share_target); { base::RunLoop run_loop; EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target))) .WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); manager().OnShareTargetDiscovered(share_target); run_loop.Run(); } { base::RunLoop run_loop; EXPECT_CALL(listener, OnShareTargetLost(MatchesTarget(share_target))) .WillOnce(testing::InvokeWithoutArgs(&run_loop, &base::RunLoop::Quit)); manager().OnShareTargetLost(share_target); run_loop.Run(); } EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_Invalid) { MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); MockSelectShareTargetCallback callback; EXPECT_CALL( callback, Run(nearby_share::mojom::SelectShareTargetResult::kInvalidShareTarget, testing::IsFalse(), testing::IsFalse())); manager().SelectShareTarget({}, callback.Get()); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_SendSuccess) { // Setup share target MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; manager().OnShareTargetDiscovered(share_target); MockSelectShareTargetCallback callback; EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk, testing::IsTrue(), testing::IsTrue())); EXPECT_CALL(sharing_service(), SendAttachments(_, _)) .WillOnce(testing::Invoke( [&share_target]( const ShareTarget& target, std::vector<std::unique_ptr<Attachment>> attachments) { EXPECT_EQ(share_target.id, target.id); ExpectTextAttachment(kTextAttachmentBody, attachments); return NearbySharingService::StatusCodes::kOk; })); manager().SelectShareTarget(share_target.id, callback.Get()); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, SelectShareTarget_SendError) { // Setup share target MockShareTargetListener listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; manager().OnShareTargetDiscovered(share_target); // Expect an error if NearbySharingService::Send*() fails. MockSelectShareTargetCallback callback; EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kError, testing::IsFalse(), testing::IsFalse())); EXPECT_CALL(sharing_service(), SendAttachments(_, _)) .WillOnce(testing::Invoke( [&share_target]( const ShareTarget& target, std::vector<std::unique_ptr<Attachment>> attachments) { EXPECT_EQ(share_target.id, target.id); ExpectTextAttachment(kTextAttachmentBody, attachments); return NearbySharingService::StatusCodes::kError; })); manager().SelectShareTarget(share_target.id, callback.Get()); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, OnTransferUpdate_WaitRemote) { // Setup share target MockShareTargetListener listener; MockTransferUpdateListener transfer_listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); base::RunLoop run_loop; EXPECT_CALL(transfer_listener, OnTransferUpdate(_, _)) .WillOnce(testing::Invoke( [&run_loop](nearby_share::mojom::TransferStatus status, const base::Optional<std::string>& token) { EXPECT_EQ( nearby_share::mojom::TransferStatus::kAwaitingRemoteAcceptance, status); EXPECT_FALSE(token.has_value()); run_loop.Quit(); })); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target))) .Times(1); manager().OnShareTargetDiscovered(share_target); MockSelectShareTargetCallback callback; EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk, testing::IsTrue(), testing::IsTrue())) .WillOnce(testing::Invoke( [&transfer_listener]( nearby_share::mojom::SelectShareTargetResult result, mojo::PendingReceiver<nearby_share::mojom::TransferUpdateListener> listener, mojo::PendingRemote<nearby_share::mojom::ConfirmationManager> manager) { transfer_listener.Bind(std::move(listener)); })); EXPECT_CALL(sharing_service(), SendAttachments(_, _)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); manager().SelectShareTarget(share_target.id, callback.Get()); auto metadata = TransferMetadataBuilder() .set_status(TransferMetadata::Status::kAwaitingRemoteAcceptance) .build(); manager().OnTransferUpdate(share_target, metadata); run_loop.Run(); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, OnTransferUpdate_WaitLocal) { // Setup share target MockShareTargetListener listener; MockTransferUpdateListener transfer_listener; EXPECT_CALL(sharing_service(), RegisterSendSurface(testing::_, testing::_, testing::_)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); const std::string expected_token = "Test Token"; base::RunLoop run_loop; EXPECT_CALL(transfer_listener, OnTransferUpdate(_, _)) .WillOnce(testing::Invoke([&run_loop, &expected_token]( nearby_share::mojom::TransferStatus status, const base::Optional<std::string>& token) { EXPECT_EQ( nearby_share::mojom::TransferStatus::kAwaitingLocalConfirmation, status); EXPECT_EQ(expected_token, token); run_loop.Quit(); })); EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); manager().StartDiscovery(listener.Bind(), base::DoNothing()); ShareTarget share_target; EXPECT_CALL(listener, OnShareTargetDiscovered(MatchesTarget(share_target))) .Times(1); manager().OnShareTargetDiscovered(share_target); MockSelectShareTargetCallback callback; EXPECT_CALL(callback, Run(nearby_share::mojom::SelectShareTargetResult::kOk, testing::IsTrue(), testing::IsTrue())) .WillOnce(testing::Invoke( [&transfer_listener]( nearby_share::mojom::SelectShareTargetResult result, mojo::PendingReceiver<nearby_share::mojom::TransferUpdateListener> listener, mojo::PendingRemote<nearby_share::mojom::ConfirmationManager> manager) { transfer_listener.Bind(std::move(listener)); })); EXPECT_CALL(sharing_service(), SendAttachments(_, _)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); manager().SelectShareTarget(share_target.id, callback.Get()); auto metadata = TransferMetadataBuilder() .set_status(TransferMetadata::Status::kAwaitingLocalConfirmation) .set_token(expected_token) .build(); manager().OnTransferUpdate(share_target, metadata); run_loop.Run(); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, TransferUpdateWithoutListener) { MockStartDiscoveryCallback callback; EXPECT_CALL( callback, Run( /*result=*/nearby_share::mojom::StartDiscoveryResult::kSuccess)); EXPECT_CALL( sharing_service(), RegisterSendSurface(&manager(), &manager(), NearbySharingService::SendSurfaceState::kForeground)) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .Times(0); // Should not be called! EXPECT_CALL(sharing_service(), IsTransferring()).Times(1); MockShareTargetListener listener; manager().StartDiscovery(listener.Bind(), callback.Get()); // It is possible that during registration if a transfer is in progress // already we might get a transfer update before selecting the share target. // This used to cause a crash due to transfer_update_listener_ not being // bound. ShareTarget share_target; manager().OnTransferUpdate( share_target, TransferMetadataBuilder() .set_status(TransferMetadata::Status::kComplete) .build()); // However, we do expect UnregisterSendSurface to be called from the // destructor. EXPECT_CALL(sharing_service(), UnregisterSendSurface(&manager(), &manager())) .WillOnce(testing::Return(NearbySharingService::StatusCodes::kOk)); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewText) { NearbyPerSessionDiscoveryManager manager(&sharing_service(), CreateTextAttachments()); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, kTextAttachmentBody); EXPECT_EQ(payload_preview.file_count, 0); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kText); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSingleVideo) { NearbyPerSessionDiscoveryManager manager( &sharing_service(), CreateFileAttachments(/*count=*/1, /*mime_type=*/"", /*type=*/FileAttachment::Type::kVideo)); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, "File-0"); EXPECT_EQ(payload_preview.file_count, 1); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kVideoFile); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSinglePDF) { NearbyPerSessionDiscoveryManager manager( &sharing_service(), CreateFileAttachments(/*count=*/1, /*mime_type=*/"application/pdf", /*type=*/FileAttachment::Type::kUnknown)); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, "File-0"); EXPECT_EQ(payload_preview.file_count, 1); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kPdfFile); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewSingleUnknownFile) { NearbyPerSessionDiscoveryManager manager( &sharing_service(), CreateFileAttachments(/*count=*/1, /*mime_type=*/"", /*type=*/FileAttachment::Type::kUnknown)); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, "File-0"); EXPECT_EQ(payload_preview.file_count, 1); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kUnknownFile); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewMultipleFiles) { NearbyPerSessionDiscoveryManager manager( &sharing_service(), CreateFileAttachments(/*count=*/2, /*mime_type=*/"", /*type=*/FileAttachment::Type::kUnknown)); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, "File-0"); EXPECT_EQ(payload_preview.file_count, 2); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kMultipleFiles); } TEST_F(NearbyPerSessionDiscoveryManagerTest, PreviewNoAttachments) { NearbyPerSessionDiscoveryManager manager( &sharing_service(), CreateFileAttachments(/*count=*/0, /*mime_type=*/"", /*type=*/FileAttachment::Type::kUnknown)); MockGetPayloadPreviewCallback callback; nearby_share::mojom::PayloadPreview payload_preview; EXPECT_CALL(callback, Run(_)) .WillOnce(testing::SaveArgPointee<0>(&payload_preview)); manager.GetPayloadPreview(callback.Get()); EXPECT_EQ(payload_preview.description, ""); EXPECT_EQ(payload_preview.file_count, 0); EXPECT_EQ(payload_preview.share_type, nearby_share::mojom::ShareType::kText); }
40.094256
80
0.724655
iridium-browser
913ea9d2070980d26d18cb720a52ff488776a0aa
14,789
cpp
C++
Source/PluginProcessorReceive.cpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
Source/PluginProcessorReceive.cpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
Source/PluginProcessorReceive.cpp
jmaibaum/Camomile
5801804fd69ad17ef29a026afbff5b5f89224297
[ "BSD-2-Clause" ]
null
null
null
/* // Copyright (c) 2015-2018 Pierre Guillot. // For information on usage and redistribution, and for a DISCLAIMER OF ALL // WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #include "PluginProcessor.h" #include "PluginParameter.h" ////////////////////////////////////////////////////////////////////////////////////////////// // MIDI METHODS // ////////////////////////////////////////////////////////////////////////////////////////////// void CamomileAudioProcessor::receiveNoteOn(const int channel, const int pitch, const int velocity) { if(velocity == 0) { m_midi_buffer_out.addEvent(MidiMessage::noteOff(channel, pitch, uint8(0)), m_audio_advancement); } else { m_midi_buffer_out.addEvent(MidiMessage::noteOn(channel, pitch, static_cast<uint8>(velocity)), m_audio_advancement); } } void CamomileAudioProcessor::receiveControlChange(const int channel, const int controller, const int value) { m_midi_buffer_out.addEvent(MidiMessage::controllerEvent(channel, controller, value), m_audio_advancement); } void CamomileAudioProcessor::receiveProgramChange(const int channel, const int value) { m_midi_buffer_out.addEvent(MidiMessage::programChange(channel, value), m_audio_advancement); } void CamomileAudioProcessor::receivePitchBend(const int channel, const int value) { m_midi_buffer_out.addEvent(MidiMessage::pitchWheel(channel, value + 8192), m_audio_advancement); } void CamomileAudioProcessor::receiveAftertouch(const int channel, const int value) { m_midi_buffer_out.addEvent(MidiMessage::channelPressureChange(channel, value), m_audio_advancement); } void CamomileAudioProcessor::receivePolyAftertouch(const int channel, const int pitch, const int value) { m_midi_buffer_out.addEvent(MidiMessage::aftertouchChange(channel, pitch, value), m_audio_advancement); } void CamomileAudioProcessor::receiveMidiByte(const int port, const int byte) { m_midi_buffer_out.addEvent(MidiMessage(byte), m_audio_advancement); } ////////////////////////////////////////////////////////////////////////////////////////////// // PRINT METHOD // ////////////////////////////////////////////////////////////////////////////////////////////// void CamomileAudioProcessor::receivePrint(const std::string& message) { if(!message.empty()) { if(!message.compare(0, 6, "error:")) { std::string const temp(message.begin()+7, message.end()); add(ConsoleLevel::Error, temp); } else if(!message.compare(0, 11, "verbose(4):")) { std::string const temp(message.begin()+12, message.end()); add(ConsoleLevel::Error, temp); } else if(!message.compare(0, 5, "tried")) { add(ConsoleLevel::Log, message); } else if(!message.compare(0, 16, "input channels =")) { add(ConsoleLevel::Log, message); } else { add(ConsoleLevel::Normal, message); } } } ////////////////////////////////////////////////////////////////////////////////////////////// // MESSAGE METHOD // ////////////////////////////////////////////////////////////////////////////////////////////// void CamomileAudioProcessor::receiveMessage(const std::string& msg, const std::vector<pd::Atom>& list) { if(msg == std::string("param")) { if(list.size() >= 2 && list[0].isSymbol() && list[1].isFloat()) { std::string const method = list[0].getSymbol(); int const index = static_cast<int>(list[1].getFloat()) - 1; if(method == "set") { if(list.size() >= 3 && list[2].isFloat()) { CamomileAudioParameter* param = static_cast<CamomileAudioParameter *>(getParameters()[index]); if(param) { param->setOriginalScaledValueNotifyingHost(list[2].getFloat()); if(list.size() > 3) { add(ConsoleLevel::Error, "camomile parameter set method extra arguments"); } } else { add(ConsoleLevel::Error, "camomile parameter set method index: out of range"); } } else { add(ConsoleLevel::Error, "camomile parameter set method: wrong argument"); } } else if(method == "change") { if(list.size() >= 3 && list[2].isFloat()) { AudioProcessorParameter* param = getParameters()[index]; if(param) { if(list[2].getFloat() > std::numeric_limits<float>::epsilon()) { if(m_params_states[index]) { add(ConsoleLevel::Error, "camomile parameter change " + std::to_string(index+1) + " already started"); } else { param->beginChangeGesture(); m_params_states[index] = true; if(list.size() > 3) { add(ConsoleLevel::Error, "camomile parameter change method extra arguments"); } } } else { if(!m_params_states[index]) { add(ConsoleLevel::Error, "camomile parameter change " + std::to_string(index+1) + " not started"); } else { param->endChangeGesture(); m_params_states[index] = false; if(list.size() > 3) { add(ConsoleLevel::Error, "camomile parameter change method extra arguments"); } } } } else { add(ConsoleLevel::Error, "camomile parameter change method index: out of range"); } } else { add(ConsoleLevel::Error, "camomile parameter change method: wrong argument"); } } else { add(ConsoleLevel::Error, "camomile param no method: " + method); } } else { add(ConsoleLevel::Error, "camomile param error syntax: method index..."); } } else if(msg == std::string("program")) { parseProgram(list); } else if(msg == std::string("openpanel")) { parseOpenPanel(list); } else if(msg == std::string("savepanel")) { parseSavePanel(list); } else if(msg == std::string("array")) { parseArray(list); } else if(msg == std::string("save")) { parseSaveInformation(list); } else if(msg == std::string("gui")) { parseGui(list); } else if(msg == std::string("audio")) { parseAudio(list); } else { add(ConsoleLevel::Error, "camomile unknow message : " + msg); } } void CamomileAudioProcessor::parseProgram(const std::vector<pd::Atom>& list) { if(list.size() >= 1 && list[0].isSymbol() && list[0].getSymbol() == "updated") { updateHostDisplay(); } else { add(ConsoleLevel::Error, "camomile program method accepts updated method only"); } } void CamomileAudioProcessor::parseOpenPanel(const std::vector<pd::Atom>& list) { if(list.size() >= 1) { if(list[0].isSymbol()) { if(list.size() > 1) { if(list[1].isSymbol()) { if(list[1].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string("-s")}); } else if(list[0].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("openpanel"), list[1].getSymbol(), std::string("-s")}); } else { add(ConsoleLevel::Error, "camomile openpanel one argument must be a flag \"-s\""); } if(list.size() > 2) { add(ConsoleLevel::Error, "camomile openpanel method extra arguments"); } } else { add(ConsoleLevel::Error, "camomile openpanel second argument must be a symbol"); } } else { if(list[0].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string("-s")}); } else { m_queue_gui.try_enqueue({std::string("openpanel"), list[0].getSymbol(), std::string()}); } } } else { add(ConsoleLevel::Error, "camomile openpanel method argument must be a symbol"); } } else { m_queue_gui.try_enqueue({std::string("openpanel"), std::string(), std::string()}); } } void CamomileAudioProcessor::parseSavePanel(const std::vector<pd::Atom>& list) { if(list.size() >= 1) { if(list[0].isSymbol()) { if(list.size() > 1) { if(list[1].isSymbol()) { if(list[1].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string("-s")}); } else if(list[0].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("savepanel"), list[1].getSymbol(), std::string("-s")}); } else { add(ConsoleLevel::Error, "camomile savepanel one argument must be a flag \"-s\""); } if(list.size() > 2) { add(ConsoleLevel::Error, "camomile savepanel method extra arguments"); } } else { add(ConsoleLevel::Error, "camomile savepanel second argument must be a symbol"); } } else { if(list[0].getSymbol() == "-s") { m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string("-s")}); } else { m_queue_gui.try_enqueue({std::string("savepanel"), list[0].getSymbol(), std::string()}); } } } else { add(ConsoleLevel::Error, "camomile savepanel method argument must be a symbol"); } } else { m_queue_gui.try_enqueue({std::string("savepanel"), std::string(), std::string()}); } } void CamomileAudioProcessor::parseArray(const std::vector<pd::Atom>& list) { if(list.size() >= 1) { if(list[0].isSymbol()) { m_queue_gui.try_enqueue({std::string("array"), list[0].getSymbol(), ""}); if(list.size() > 1) { add(ConsoleLevel::Error, "camomile array method extra arguments"); } } else { add(ConsoleLevel::Error, "camomile array method argument must be a symbol"); } } else { add(ConsoleLevel::Error, "camomile array needs a name"); } } void CamomileAudioProcessor::parseGui(const std::vector<pd::Atom>& list) { if(list.size() >= 1) { if(list[0].isSymbol()) { m_queue_gui.try_enqueue({std::string("gui"), list[0].getSymbol(), ""}); if(list.size() > 1) { add(ConsoleLevel::Error, "camomile gui method extra arguments"); } } else { add(ConsoleLevel::Error, "camomile gui method argument must be a symbol"); } } else { add(ConsoleLevel::Error, "camomile gui needs a command"); } } void CamomileAudioProcessor::parseAudio(const std::vector<pd::Atom>& list) { if(list.size() >= 1) { if(list[0].isSymbol()) { if(list[0].getSymbol() == std::string("latency")) { if(list.size() >= 2 && list[1].isFloat()) { const int latency = static_cast<int>(list[1].getFloat()); if(latency >= 0) { setLatencySamples(latency + Instance::getBlockSize()); if(list.size() > 2) { add(ConsoleLevel::Error, "camomile audio method: latency option extra arguments"); } if(CamomileEnvironment::isLatencyInitialized()) { add(ConsoleLevel::Error, "camomile audio method: latency overwrites the preferences"); } } else { add(ConsoleLevel::Error, "camomile audio method: latency must be positive or null"); } } else { add(ConsoleLevel::Error, "camomile audio method: latency option expects a number"); } } else { add(ConsoleLevel::Error, "camomile audio method: unknown option \"" + list[0].getSymbol() + "\""); } } else { add(ConsoleLevel::Error, "camomile audio method: first argument must be an option"); } } else { add(ConsoleLevel::Error, "camomile audio method: expects arguments"); } }
36.070732
123
0.451349
jmaibaum
913ec1eb1a1e01c777765330a73ea5f9d8a3a13c
3,585
hpp
C++
include/staticlib/tinydir/file_sink.hpp
staticlibs/staticlib_tinydir
c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610
[ "Apache-2.0" ]
1
2021-03-13T03:12:23.000Z
2021-03-13T03:12:23.000Z
include/staticlib/tinydir/file_sink.hpp
staticlibs/staticlib_tinydir
c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610
[ "Apache-2.0" ]
1
2018-10-18T21:31:26.000Z
2018-10-18T21:31:26.000Z
include/staticlib/tinydir/file_sink.hpp
staticlibs/staticlib_tinydir
c8ab3dae0ef7543dc1d1e7a7debc7132ad8d1610
[ "Apache-2.0" ]
2
2017-03-05T02:30:03.000Z
2018-05-21T16:17:31.000Z
/* * Copyright 2017, alex at staticlibs.net * * 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. */ /* * File: file_sink.hpp * Author: alex * * Created on February 6, 2017, 2:44 PM */ #ifndef STATICLIB_TINYDIR_FILE_SINK_HPP #define STATICLIB_TINYDIR_FILE_SINK_HPP #include <string> #include "staticlib/config.hpp" #include "staticlib/io/span.hpp" #include "staticlib/tinydir/tinydir_exception.hpp" namespace staticlib { namespace tinydir { /** * Implementation of a file descriptor/handle wrapper with a * unified interface for *nix and windows */ class file_sink { #ifdef STATICLIB_WINDOWS void* handle = nullptr; #else // STATICLIB_WINDOWS /** * Native file descriptor (handle on windows) */ int fd = -1; #endif // STATICLIB_WINDOWS /** * Path to file */ std::string file_path; public: /** * File open mode */ enum class open_mode { create, append, from_file }; /** * Constructor * * @param file_path path to file */ file_sink(const std::string& file_path, open_mode mode = open_mode::create); /** * Destructor, will close the descriptor */ ~file_sink() STATICLIB_NOEXCEPT; /** * Deleted copy constructor * * @param other instance */ file_sink(const file_sink&) = delete; /** * Deleted copy assignment operator * * @param other instance * @return this instance */ file_sink& operator=(const file_sink&) = delete; /** * Move constructor * * @param other other instance */ file_sink(file_sink&& other) STATICLIB_NOEXCEPT; /** * Move assignment operator * * @param other other instance * @return this instance */ file_sink& operator=(file_sink&& other) STATICLIB_NOEXCEPT; /** * Writes specified number of bytes to this file descriptor * * @param buf source buffer * @param count number of bytes to write * @return number of bytes successfully written */ std::streamsize write(sl::io::span<const char> span); /** * Writes the contents of the specified file to this file descriptor * * @param string source file path * @return number of bytes successfully written */ std::streamsize write_from_file(const std::string& source_file); /** * Seeks over this file descriptor * * @param offset offset to seek with starting from the current position * @return resulting offset location as measured in bytes from the beginning of the file */ std::streampos seek(std::streamsize offset); /** * No-op * * @return zero */ std::streamsize flush(); /** * Closed the underlying file descriptor, will be called automatically * on destruction */ void close() STATICLIB_NOEXCEPT; /** * File path accessor * * @return path to this file */ const std::string& path() const; }; } // namespace } #endif /* STATICLIB_TINYDIR_FILE_SINK_HPP */
22.980769
92
0.642678
staticlibs
91401b573cbfc972a277cf047c1f76ed67d81f83
2,598
cpp
C++
test/module/libs/converter/string_converter_test.cpp
alohamora/iroha
aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7
[ "Apache-2.0" ]
null
null
null
test/module/libs/converter/string_converter_test.cpp
alohamora/iroha
aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7
[ "Apache-2.0" ]
null
null
null
test/module/libs/converter/string_converter_test.cpp
alohamora/iroha
aa8be2c62fedaa2de08f94f2d920275ad9ae8ba7
[ "Apache-2.0" ]
null
null
null
/** * Copyright Soramitsu Co., Ltd. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ #include <gtest/gtest.h> #include "common/byteutils.hpp" using namespace iroha; using namespace std::string_literals; /** * @given hex string * @when hex string was converted to binary string * @then converted string match the result we are expected */ TEST(StringConverterTest, ConvertHexToBinary) { std::string hex = "ff000233551117daa110050399"; std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s; ASSERT_EQ(hexstringToBytestring(hex).value(), bin); } /** * @given invalid hex string * @when string is converted to binary string * @then std::nullopt is returned */ TEST(StringConverterTest, InvalidHexToBinary) { std::string invalid_hex = "au"; ASSERT_FALSE(hexstringToBytestring(invalid_hex)); } /** * @given binary string * @when binary string was converted to hex string * @then converted string match the result we are expected */ TEST(StringConverterTest, ConvertBinaryToHex) { std::string bin = "\xFF\x00\x02\x33\x55\x11\x17\xDA\xA1\x10\x05\x03\x99"s; ASSERT_EQ(bytestringToHexstring(bin), "ff000233551117daa110050399"); } /** * @given hex string of length 256 with all possible byte values * @when convert it to byte string and back * @then resulted string is the same as given one */ TEST(StringConverterTest, ConvertHexToBinaryAndBack) { std::stringstream ss; ss << std::hex << std::setfill('0'); for (int i = 0; i < 256; ++i) { ss << std::setw(2) << i; } ASSERT_EQ(ss.str(), bytestringToHexstring(hexstringToBytestring(ss.str()).value())); } /** * @given numeric value * @when converting it to a hex string * @then converted string match expected result */ TEST(StringConverterTest, ConvertNumToHex) { // Testing uint64_t values std::vector<uint64_t> vals64{ 0x4234324309085, 0x34532, 0x0, 0x1, 0x3333333333333333}; std::vector<std::string> hexes{"0004234324309085", "0000000000034532", "0000000000000000", "0000000000000001", "3333333333333333"}; for (size_t i = 0; i < vals64.size(); i++) ASSERT_EQ(numToHexstring(vals64[i]), hexes[i]); // Testing int32_t values std::vector<int32_t> vals32{0x42343243, 0x34532, 0x0, 0x1, 0x79999999}; std::vector<std::string> hexes2{ "42343243", "00034532", "00000000", "00000001", "79999999"}; for (size_t i = 0; i < vals32.size(); i++) ASSERT_EQ(numToHexstring(vals32[i]), hexes2[i]); }
31.682927
76
0.669746
alohamora
91409ed7e7e1fad82fdd8058dadd1918cf6ab2f6
4,744
hpp
C++
octree/Octree.hpp
Koukan/voxomap
104a068b4bc84f7a208460248f824dfcde49f470
[ "MIT" ]
2
2019-03-01T16:34:02.000Z
2020-10-08T21:27:52.000Z
octree/Octree.hpp
Koukan/voxomap
104a068b4bc84f7a208460248f824dfcde49f470
[ "MIT" ]
null
null
null
octree/Octree.hpp
Koukan/voxomap
104a068b4bc84f7a208460248f824dfcde49f470
[ "MIT" ]
null
null
null
#ifndef _VOXOMAP_OCTREE_HPP_ #define _VOXOMAP_OCTREE_HPP_ #include <cstdint> #include <memory> #include <vector> #include <assert.h> namespace voxomap { /*! \defgroup Octree Octree Classes use for define the octree */ /*! \class Octree \ingroup Octree \brief Octree container */ template <class T_Node> class Octree { public: using Node = T_Node; /*! \brief Default constructor */ Octree(); /*! \brief Copy constructor */ Octree(Octree const& other); /*! \brief Move constructor */ Octree(Octree&& other); /*! \brief Default virtual destructor */ virtual ~Octree() = default; /*! \brief Assignement operator \param other Right operand \return Reference to \a this */ Octree& operator=(Octree const& other); /*! \brief Assignement move operator \param other Right operand \return Reference to \a this */ Octree& operator=(Octree&& other); /*! \brief Pushes \a node into the octree \param node Node to push */ virtual T_Node* push(T_Node& node); /*! \brief Removes \a node from the octree \return */ virtual std::unique_ptr<T_Node> pop(T_Node& node); /*! \brief Search the node that corresponds to the parameters \param x X coordinate of the node \param y Y coordinate of the node \param z Z coordinate of the node \param size Size of the node \return Pointer to the node if it exists otherwise nullptr */ T_Node* findNode(int x, int y, int z, uint32_t size) const; /*! \brief Clear the octree Removes all nodes and all elements. */ virtual void clear(); /*! \brief Getter of the root node \return The root node */ T_Node* getRootNode() const; protected: // Node method /*! \brief Set \a child as child of \a parent \param parent Parent node \param child Child node */ void setChild(T_Node& parent, T_Node& child); /*! \brief Set \a child as child of \a parent \param parent Parent node \param child Child node \param childId Id of the child inside parent's children array */ void setChild(T_Node& parent, T_Node& child, uint8_t childId); /*! \brief Remove \a child from its parent and so from the octree */ void removeFromParent(T_Node& child); /*! \brief Remove the child with \a id from the \a parent node \return The removed node */ T_Node* removeChild(T_Node& parent, uint8_t id); /*! \brief Find node inside \a parent that can contain \a node \param parent Parent node \param node The new node \param childId Id of the node inside the found parent \return The found parent node, nullptr if not exist */ T_Node* findParentNode(T_Node& parent, T_Node& node, uint8_t& childId) const; /*! \brief Push \a node inside \a parent \param parent Parent node \param node Node to push \return Node added, can be different than \a node if a similar node already exist */ T_Node* push(T_Node& parent, T_Node& node); /*! \brief Push \a node inside \a parent \param parent Parent node \param child Child node \param childId Id of the child inside parent's children array \return Node added, can be different than \a node if a similar node already exist */ T_Node* push(T_Node& parent, T_Node& child, uint8_t childId); /*! \brief Create an intermediate node that can contain \a child and \a newChild and push it into octree */ void insertIntermediateNode(T_Node& child, T_Node& newChild); /*! \brief Merge two nodes \param currentNode Node already present in the octree \param newNode Node to merge inside */ void merge(T_Node& currentNode, T_Node& newNode); /*! \brief Remove useless intermediate node, intermediate node with only one child \param node The intermediate node */ void removeUselessIntermediateNode(T_Node& node); /*! \brief Compute the new coordinates and size of the NegPosRootNode */ void recomputeNegPosRootNode(); /*! \brief Called when \a node is remove from the octree */ virtual void notifyNodeRemoving(T_Node& node); std::unique_ptr<T_Node> _rootNode; //!< Main node of the octree }; } #include "Octree.ipp" #endif // _VOXOMAP_OCTREE_HPP_
28.578313
108
0.60645
Koukan
914132746cecdd6b5bb28f6a9916459143ab1fed
2,785
cpp
C++
rtc/src/main.cpp
Bergi84/vihaltests_ext
6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e
[ "BSD-2-Clause" ]
null
null
null
rtc/src/main.cpp
Bergi84/vihaltests_ext
6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e
[ "BSD-2-Clause" ]
null
null
null
rtc/src/main.cpp
Bergi84/vihaltests_ext
6fc5a96c6da8398dfbccf3dce59ced1ba359ee4e
[ "BSD-2-Clause" ]
null
null
null
// file: main.cpp (uart) // brief: VIHAL UART Test // created: 2021-10-03 // authors: nvitya #include "platform.h" #include "cppinit.h" #include "clockcnt.h" #include "traces.h" #include "hwclk.h" #include "hwpins.h" #include "hwuart.h" #include "hwrtc.h" #include "board_pins.h" THwRtc gRtc; volatile unsigned hbcounter = 0; extern "C" __attribute__((noreturn)) void _start(unsigned self_flashing) // self_flashing = 1: self-flashing required for RAM-loaded applications { // after ram setup and region copy the cpu jumps here, with probably RC oscillator mcu_disable_interrupts(); // Set the interrupt vector table offset, so that the interrupts and exceptions work mcu_init_vector_table(); // run the C/C++ initialization (variable initializations, constructors) cppinit(); if (!hwclk_init(EXTERNAL_XTAL_HZ, MCU_CLOCK_SPEED)) // if the EXTERNAL_XTAL_HZ == 0, then the internal RC oscillator will be used { while (1) { // error } } hwlsclk_init(true); mcu_enable_fpu(); // enable coprocessor if present mcu_enable_icache(); // enable instruction cache if present clockcnt_init(); // go on with the hardware initializations board_pins_init(); gRtc.init(); THwRtc::time_t startTime, lastTime; startTime.msec = 768; startTime.sec = 13; startTime.min = 43; startTime.hour = 13; startTime.day = 13; startTime.month = 03; startTime.year = 22; gRtc.setTime(startTime, lastTime); THwRtc::time_t aktTime; gRtc.getTime(aktTime); TRACE("\r\n--------------------------------------\r\n"); TRACE("%sHello From VIHAL !\r\n", CC_BLU); TRACE("Board: %s\r\n", BOARD_NAME); TRACE("SystemCoreClock: %u\r\n", SystemCoreClock); TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year); gRtc.enableWakeupIRQ(); gRtc.setWakeupTimer(100); mcu_enable_interrupts(); // Infinite loop while (1) { } } extern "C" void IRQ_Handler_03() { ++hbcounter; if (hbcounter == 20) { gRtc.setWakeupTimer(500); } THwRtc::time_t aktTime; gRtc.getTime(aktTime); switch(hbcounter%8) { case 0: TRACE("%s", CC_NRM); break; case 1: TRACE("%s", CC_RED); break; case 2: TRACE("%s", CC_GRN); break; case 3: TRACE("%s", CC_YEL); break; case 4: TRACE("%s", CC_BLU); break; case 5: TRACE("%s", CC_MAG); break; case 6: TRACE("%s", CC_CYN); break; case 7: TRACE("%s", CC_WHT); break; } TRACE("%02hhu:%02hhu:%02hhu.%03hu %02hhu.%02hhu.%02hhu\r\n", aktTime.hour, aktTime.min, aktTime.sec, aktTime.msec, aktTime.day, aktTime.month, aktTime.year); gRtc.clearWakeupIRQ(); } // ----------------------------------------------------------------------------
25.09009
159
0.644883
Bergi84
91424f7e6fffe7065a55386e569947453016e96f
18,465
cpp
C++
Source Code/Rendering/PostFX/PostFX.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Rendering/PostFX/PostFX.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
Source Code/Rendering/PostFX/PostFX.cpp
IonutCava/trunk
19dc976bbd7dc637f467785bd0ca15f34bc31ed5
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "Headers/PostFX.h" #include "Headers/PreRenderOperator.h" #include "Core/Headers/ParamHandler.h" #include "Core/Headers/PlatformContext.h" #include "Core/Headers/StringHelper.h" #include "Core/Resources/Headers/ResourceCache.h" #include "Core/Time/Headers/ApplicationTimer.h" #include "Geometry/Shapes/Predefined/Headers/Quad3D.h" #include "Managers/Headers/SceneManager.h" #include "Platform/Video/Headers/GFXDevice.h" #include "Platform/Video/Headers/CommandBuffer.h" #include "Platform/Video/Shaders/Headers/ShaderProgram.h" #include "Platform/Video/Buffers/RenderTarget/Headers/RenderTarget.h" #include "Rendering/Camera/Headers/Camera.h" namespace Divide { const char* PostFX::FilterName(const FilterType filter) noexcept { switch (filter) { case FilterType::FILTER_SS_ANTIALIASING: return "SS_ANTIALIASING"; case FilterType::FILTER_SS_REFLECTIONS: return "SS_REFLECTIONS"; case FilterType::FILTER_SS_AMBIENT_OCCLUSION: return "SS_AMBIENT_OCCLUSION"; case FilterType::FILTER_DEPTH_OF_FIELD: return "DEPTH_OF_FIELD"; case FilterType::FILTER_MOTION_BLUR: return "MOTION_BLUR"; case FilterType::FILTER_BLOOM: return "BLOOM"; case FilterType::FILTER_LUT_CORECTION: return "LUT_CORRECTION"; case FilterType::FILTER_UNDERWATER: return "UNDERWATER"; case FilterType::FILTER_NOISE: return "NOISE"; case FilterType::FILTER_VIGNETTE: return "VIGNETTE"; default: break; } return "Unknown"; }; PostFX::PostFX(PlatformContext& context, ResourceCache* cache) : PlatformContextComponent(context), _preRenderBatch(context.gfx(), *this, cache) { std::atomic_uint loadTasks = 0u; context.paramHandler().setParam<bool>(_ID("postProcessing.enableVignette"), false); DisableAll(_postFXTarget._drawMask); SetEnabled(_postFXTarget._drawMask, RTAttachmentType::Colour, to_U8(GFXDevice::ScreenTargets::ALBEDO), true); Console::printfn(Locale::Get(_ID("START_POST_FX"))); ShaderModuleDescriptor vertModule = {}; vertModule._moduleType = ShaderType::VERTEX; vertModule._sourceFile = "baseVertexShaders.glsl"; vertModule._variant = "FullScreenQuad"; ShaderModuleDescriptor fragModule = {}; fragModule._moduleType = ShaderType::FRAGMENT; fragModule._sourceFile = "postProcessing.glsl"; fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCREEN %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_NOISE %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_NOISE))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_BORDER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_BORDER))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_UNDERWATER %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SSR %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SSR))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_DATA %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_SCENE_VELOCITY %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_LINDEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH))); fragModule._defines.emplace_back(Util::StringFormat("TEX_BIND_POINT_DEPTH %d", to_base(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH))); ShaderProgramDescriptor postFXShaderDescriptor = {}; postFXShaderDescriptor._modules.push_back(vertModule); postFXShaderDescriptor._modules.push_back(fragModule); _drawConstantsCmd._constants.set(_ID("_noiseTile"), GFX::PushConstantType::FLOAT, 0.1f); _drawConstantsCmd._constants.set(_ID("_noiseFactor"), GFX::PushConstantType::FLOAT, 0.02f); _drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false); _drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, vec2<F32>(0.01f, 500.0f)); TextureDescriptor texDescriptor(TextureType::TEXTURE_2D); ImageTools::ImportOptions options; options._isNormalMap = true; options._useDDSCache = true; options._outputSRGB = false; options._alphaChannelTransparency = false; texDescriptor.textureOptions(options); ResourceDescriptor textureWaterCaustics("Underwater Normal Map"); textureWaterCaustics.assetName(ResourcePath("terrain_water_NM.jpg")); textureWaterCaustics.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation); textureWaterCaustics.propertyDescriptor(texDescriptor); textureWaterCaustics.waitForReady(false); _underwaterTexture = CreateResource<Texture>(cache, textureWaterCaustics, loadTasks); options._isNormalMap = false; texDescriptor.textureOptions(options); ResourceDescriptor noiseTexture("noiseTexture"); noiseTexture.assetName(ResourcePath("bruit_gaussien.jpg")); noiseTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation); noiseTexture.propertyDescriptor(texDescriptor); noiseTexture.waitForReady(false); _noise = CreateResource<Texture>(cache, noiseTexture, loadTasks); ResourceDescriptor borderTexture("borderTexture"); borderTexture.assetName(ResourcePath("vignette.jpeg")); borderTexture.assetLocation(Paths::g_assetsLocation + Paths::g_imagesLocation); borderTexture.propertyDescriptor(texDescriptor); borderTexture.waitForReady(false); _screenBorder = CreateResource<Texture>(cache, borderTexture), loadTasks; _noiseTimer = 0.0; _tickInterval = 1.0f / 24.0f; _randomNoiseCoefficient = 0; _randomFlashCoefficient = 0; ResourceDescriptor postFXShader("postProcessing"); postFXShader.propertyDescriptor(postFXShaderDescriptor); _postProcessingShader = CreateResource<ShaderProgram>(cache, postFXShader, loadTasks); _postProcessingShader->addStateCallback(ResourceState::RES_LOADED, [this, &context](CachedResource*) { PipelineDescriptor pipelineDescriptor; pipelineDescriptor._stateHash = context.gfx().get2DStateBlock(); pipelineDescriptor._shaderProgramHandle = _postProcessingShader->handle(); pipelineDescriptor._primitiveTopology = PrimitiveTopology::TRIANGLES; _drawPipeline = context.gfx().newPipeline(pipelineDescriptor); }); WAIT_FOR_CONDITION(loadTasks.load() == 0); } PostFX::~PostFX() { } void PostFX::updateResolution(const U16 newWidth, const U16 newHeight) { if (_resolutionCache.width == newWidth && _resolutionCache.height == newHeight|| newWidth < 1 || newHeight < 1) { return; } _resolutionCache.set(newWidth, newHeight); _preRenderBatch.reshape(newWidth, newHeight); _setCameraCmd._cameraSnapshot = Camera::GetUtilityCamera(Camera::UtilityCamera::_2D)->snapshot(); } void PostFX::prePass(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) { static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: PrePass" }; GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd); GFX::EnqueueCommand<GFX::PushCameraCommand>(bufferInOut)->_cameraSnapshot = _setCameraCmd._cameraSnapshot; _preRenderBatch.prePass(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut); GFX::EnqueueCommand<GFX::PopCameraCommand>(bufferInOut); GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut); } void PostFX::apply(const PlayerIndex idx, const CameraSnapshot& cameraSnapshot, GFX::CommandBuffer& bufferInOut) { static GFX::BeginDebugScopeCommand s_beginScopeCmd{ "PostFX: Apply" }; GFX::EnqueueCommand(bufferInOut, s_beginScopeCmd); GFX::EnqueueCommand(bufferInOut, _setCameraCmd); _preRenderBatch.execute(idx, cameraSnapshot, _filterStack | _overrideFilterStack, bufferInOut); GFX::BeginRenderPassCommand beginRenderPassCmd{}; beginRenderPassCmd._target = RenderTargetNames::SCREEN; beginRenderPassCmd._descriptor = _postFXTarget; beginRenderPassCmd._name = "DO_POSTFX_PASS"; GFX::EnqueueCommand(bufferInOut, beginRenderPassCmd); GFX::EnqueueCommand(bufferInOut, GFX::BindPipelineCommand{ _drawPipeline }); if (_filtersDirty) { _drawConstantsCmd._constants.set(_ID("vignetteEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_VIGNETTE)); _drawConstantsCmd._constants.set(_ID("noiseEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_NOISE)); _drawConstantsCmd._constants.set(_ID("underwaterEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_UNDERWATER)); _drawConstantsCmd._constants.set(_ID("lutCorrectionEnabled"), GFX::PushConstantType::BOOL, getFilterState(FilterType::FILTER_LUT_CORECTION)); _filtersDirty = false; }; _drawConstantsCmd._constants.set(_ID("_zPlanes"), GFX::PushConstantType::VEC2, cameraSnapshot._zPlanes); _drawConstantsCmd._constants.set(_ID("_invProjectionMatrix"), GFX::PushConstantType::VEC2, cameraSnapshot._invProjectionMatrix); GFX::EnqueueCommand(bufferInOut, _drawConstantsCmd); const auto& rtPool = context().gfx().renderTargetPool(); const auto& prbAtt = _preRenderBatch.getOutput(false)._rt->getAttachment(RTAttachmentType::Colour, 0); const auto& linDepthDataAtt =_preRenderBatch.getLinearDepthRT()._rt->getAttachment(RTAttachmentType::Colour, 0); const auto& ssrDataAtt = rtPool.getRenderTarget(RenderTargetNames::SSR_RESULT)->getAttachment(RTAttachmentType::Colour, 0); const auto& sceneDataAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::NORMALS)); const auto& velocityAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Colour, to_base(GFXDevice::ScreenTargets::VELOCITY)); const auto& depthAtt = rtPool.getRenderTarget(RenderTargetNames::SCREEN)->getAttachment(RTAttachmentType::Depth_Stencil, 0); SamplerDescriptor defaultSampler = {}; defaultSampler.wrapUVW(TextureWrap::REPEAT); const size_t samplerHash = defaultSampler.getHash(); DescriptorSet& set = GFX::EnqueueCommand<GFX::BindDescriptorSetsCommand>(bufferInOut)->_set; set._usage = DescriptorSetUsage::PER_DRAW_SET; { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCREEN); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { prbAtt->texture()->data(), prbAtt->descriptor()._samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_DEPTH); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { depthAtt->texture()->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_LINDEPTH); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { linDepthDataAtt->texture()->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SSR); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { ssrDataAtt->texture()->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_DATA); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { sceneDataAtt->texture()->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_SCENE_VELOCITY); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { velocityAtt->texture()->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_UNDERWATER); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { _underwaterTexture->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_NOISE); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { _noise->data(), samplerHash }; } { auto& binding = set._bindings.emplace_back(); binding._type = DescriptorSetBindingType::COMBINED_IMAGE_SAMPLER; binding._resourceSlot = to_U8(TexOperatorBindPoint::TEX_BIND_POINT_BORDER); binding._shaderStageVisibility = DescriptorSetBinding::ShaderStageVisibility::FRAGMENT; binding._data.As<DescriptorCombinedImageSampler>() = { _screenBorder->data(), samplerHash }; } GFX::EnqueueCommand<GFX::DrawCommand>(bufferInOut); GFX::EnqueueCommand(bufferInOut, GFX::EndRenderPassCommand{}); GFX::EnqueueCommand<GFX::EndDebugScopeCommand>(bufferInOut); } void PostFX::idle(const Configuration& config) { OPTICK_EVENT(); // Update states if (getFilterState(FilterType::FILTER_NOISE)) { _noiseTimer += Time::Game::ElapsedMilliseconds(); if (_noiseTimer > _tickInterval) { _noiseTimer = 0.0; _randomNoiseCoefficient = Random(1000) * 0.001f; _randomFlashCoefficient = Random(1000) * 0.001f; } _drawConstantsCmd._constants.set(_ID("randomCoeffNoise"), GFX::PushConstantType::FLOAT, _randomNoiseCoefficient); _drawConstantsCmd._constants.set(_ID("randomCoeffFlash"), GFX::PushConstantType::FLOAT, _randomFlashCoefficient); } } void PostFX::update(const U64 deltaTimeUSFixed, const U64 deltaTimeUSApp) { OPTICK_EVENT(); if (_fadeActive) { _currentFadeTimeMS += Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp); F32 fadeStrength = to_F32(std::min(_currentFadeTimeMS / _targetFadeTimeMS , 1.0)); if (!_fadeOut) { fadeStrength = 1.0f - fadeStrength; } if (fadeStrength > 0.99) { if (_fadeWaitDurationMS < std::numeric_limits<D64>::epsilon()) { if (_fadeOutComplete) { _fadeOutComplete(); _fadeOutComplete = DELEGATE<void>(); } } else { _fadeWaitDurationMS -= Time::MicrosecondsToMilliseconds<D64>(deltaTimeUSApp); } } _drawConstantsCmd._constants.set(_ID("_fadeStrength"), GFX::PushConstantType::FLOAT, fadeStrength); _fadeActive = fadeStrength > std::numeric_limits<D64>::epsilon(); if (!_fadeActive) { _drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, false); if (_fadeInComplete) { _fadeInComplete(); _fadeInComplete = DELEGATE<void>(); } } } _preRenderBatch.update(deltaTimeUSApp); } void PostFX::setFadeOut(const UColour3& targetColour, const D64 durationMS, const D64 waitDurationMS, DELEGATE<void> onComplete) { _drawConstantsCmd._constants.set(_ID("_fadeColour"), GFX::PushConstantType::VEC4, Util::ToFloatColour(targetColour)); _drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true); _targetFadeTimeMS = durationMS; _currentFadeTimeMS = 0.0; _fadeWaitDurationMS = waitDurationMS; _fadeOut = true; _fadeActive = true; _fadeOutComplete = MOV(onComplete); } // clear any fading effect currently active over the specified time interval // set durationMS to instantly clear the fade effect void PostFX::setFadeIn(const D64 durationMS, DELEGATE<void> onComplete) { _targetFadeTimeMS = durationMS; _currentFadeTimeMS = 0.0; _fadeOut = false; _fadeActive = true; _drawConstantsCmd._constants.set(_ID("_fadeActive"), GFX::PushConstantType::BOOL, true); _fadeInComplete = MOV(onComplete); } void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 waitDurationMS) { if (waitDurationMS > 0.0) { setFadeOutIn(targetColour, waitDurationMS * 0.5, waitDurationMS * 0.5, durationFadeOutMS); } } void PostFX::setFadeOutIn(const UColour3& targetColour, const D64 durationFadeOutMS, const D64 durationFadeInMS, const D64 waitDurationMS) { setFadeOut(targetColour, durationFadeOutMS, waitDurationMS, [this, durationFadeInMS]() {setFadeIn(durationFadeInMS); }); } };
51.008287
167
0.730355
IonutCava
9143da8e877140cb542acb632ae678726bd00d00
177
cpp
C++
cpp/main.cpp
mit-gfx/diff_stokes_flow
55eb7c0f3a9d58a50c1a09c2231177b81e0da84e
[ "MIT" ]
40
2020-11-07T06:27:40.000Z
2021-11-09T07:09:48.000Z
cpp/main.cpp
mit-gfx/diff_stokes_flow
55eb7c0f3a9d58a50c1a09c2231177b81e0da84e
[ "MIT" ]
null
null
null
cpp/main.cpp
mit-gfx/diff_stokes_flow
55eb7c0f3a9d58a50c1a09c2231177b81e0da84e
[ "MIT" ]
6
2020-10-09T05:24:22.000Z
2021-10-04T06:35:22.000Z
#include <iostream> #include "Eigen/Dense" #include "common/config.h" #include "common/common.h" int main() { PrintInfo("The program compiles just fine."); return 0; }
17.7
49
0.683616
mit-gfx
91446e3be5af90f48f56537f2b0d19e44bf57785
35,694
cpp
C++
mp/src/game/server/hl2mp/hl2mp_client.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
null
null
null
mp/src/game/server/hl2mp/hl2mp_client.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
null
null
null
mp/src/game/server/hl2mp/hl2mp_client.cpp
Code4Cookie/Atomic-Secobmod
9738d91bc37f8d9e9fb63d4a444ecbeaa0e0cf70
[ "Unlicense" ]
null
null
null
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ // //=============================================================================// /* ===== tf_client.cpp ======================================================== HL2 client/server game specific stuff */ #include "cbase.h" #include "hl2mp_player.h" #include "hl2mp_gamerules.h" #include "gamerules.h" #include "teamplay_gamerules.h" #include "entitylist.h" #include "physics.h" #include "game.h" #include "player_resource.h" #include "engine/IEngineSound.h" #include "team.h" #include "viewport_panel_names.h" #include "tier0/vprof.h" #ifdef SecobMod__SAVERESTORE #include "filesystem.h" #endif //SecobMod__SAVERESTORE // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" void Host_Say(edict_t *pEdict, bool teamonly); ConVar sv_motd_unload_on_dismissal("sv_motd_unload_on_dismissal", "0", 0, "If enabled, the MOTD contents will be unloaded when the player closes the MOTD."); extern CBaseEntity* FindPickerEntityClass(CBasePlayer *pPlayer, char *classname); extern bool g_fGameOver; #ifdef SecobMod__USE_PLAYERCLASSES void SSPlayerClassesBGCheck(CHL2MP_Player *pPlayer) { CSingleUserRecipientFilter user(pPlayer); user.MakeReliable(); UserMessageBegin(user, "SSPlayerClassesBGCheck"); MessageEnd(); } void ShowSSPlayerClasses(CHL2MP_Player *pPlayer) { CSingleUserRecipientFilter user(pPlayer); user.MakeReliable(); UserMessageBegin(user, "ShowSSPlayerClasses"); MessageEnd(); } CON_COMMAND(ss_classes_default, "The current map is a background level - do default spawn") { CHL2MP_Player *pPlayer = ToHL2MPPlayer(UTIL_GetCommandClient()); if (pPlayer != NULL) { CSingleUserRecipientFilter user(pPlayer); user.MakeReliable(); pPlayer->InitialSpawn(); pPlayer->Spawn(); pPlayer->m_Local.m_iHideHUD |= HIDEHUD_ALL; pPlayer->RemoveAllItems(true); //SecobMod__Information These are now commented out because for your own mod you'll have to use the black room spawn method anyway. // That is for your own maps, you create a seperate room with fully black textures, no light and a single info_player_start. //You may end up needing to uncomment it if you don't use playerclasses, but you'll figure that out for yourself when you cant see anything but your HUD. //color32 black = {0,0,0,255}; //UTIL_ScreenFade( pPlayer, black, 0.0f, 0.0f, FFADE_IN|FFADE_PURGE ); } } #endif //SecobMod__USE_PLAYERCLASSES void FinishClientPutInServer(CHL2MP_Player *pPlayer) { #ifdef SecobMod__USE_PLAYERCLASSES pPlayer->InitialSpawn(); pPlayer->Spawn(); pPlayer->RemoveAllItems(true); SSPlayerClassesBGCheck(pPlayer); #else pPlayer->InitialSpawn(); pPlayer->Spawn(); #endif //SecobMod__USE_PLAYERCLASSES char sName[128]; Q_strncpy(sName, pPlayer->GetPlayerName(), sizeof(sName)); // First parse the name and remove any %'s for (char *pApersand = sName; pApersand != NULL && *pApersand != 0; pApersand++) { // Replace it with a space if (*pApersand == '%') *pApersand = ' '; } // notify other clients of player joining the game UTIL_ClientPrintAll(HUD_PRINTNOTIFY, "#Game_connected", sName[0] != 0 ? sName : "<unconnected>"); if (HL2MPRules()->IsTeamplay() == true) { ClientPrint(pPlayer, HUD_PRINTTALK, "You are on team %s1\n", pPlayer->GetTeam()->GetName()); } const ConVar *hostname = cvar->FindVar("hostname"); const char *title = (hostname) ? hostname->GetString() : "MESSAGE OF THE DAY"; KeyValues *data = new KeyValues("data"); data->SetString("title", title); // info panel title data->SetString("type", "1"); // show userdata from stringtable entry data->SetString("msg", "motd"); // use this stringtable entry data->SetBool("unload", sv_motd_unload_on_dismissal.GetBool()); pPlayer->ShowViewPortPanel(PANEL_INFO, true, data); #ifndef SecobMod__SAVERESTORE #ifdef SecobMod__USE_PLAYERCLASSES pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL); #endif //SecobMod__USE_PLAYERCLASSES #endif //SecobMod__SAVERESTORE #ifdef SecobMod__SAVERESTORE //if (Transitioned) //{ //SecobMod KeyValues *pkvTransitionRestoreFile = new KeyValues("transition.cfg"); //Msg ("Transition path is: %s !!!!!\n",TransitionPath); if (pkvTransitionRestoreFile->LoadFromFile(filesystem, "transition.cfg")) { while (pkvTransitionRestoreFile) { const char *pszSteamID = pkvTransitionRestoreFile->GetName(); //Gets our header, which we use the players SteamID for. const char *PlayerSteamID = engine->GetPlayerNetworkIDString(pPlayer->edict()); //Finds the current players Steam ID. Msg("In-File SteamID is %s.\n", pszSteamID); Msg("In-Game SteamID is %s.\n", PlayerSteamID); if (Q_strcmp(PlayerSteamID, pszSteamID) != 0) { if (pkvTransitionRestoreFile == NULL) { break; } //SecobMod__Information No SteamID found for this person, maybe they're new to the game or have "STEAM_ID_PENDING". Show them the class menu and break the loop. pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL); break; } Msg("SteamID Match Found!"); #ifdef SecobMod__USE_PLAYERCLASSES //Class. KeyValues *pkvCurrentClass = pkvTransitionRestoreFile->FindKey("CurrentClass"); #endif //SecobMod__USE_PLAYERCLASSES //Health KeyValues *pkvHealth = pkvTransitionRestoreFile->FindKey("Health"); //Armour KeyValues *pkvArmour = pkvTransitionRestoreFile->FindKey("Armour"); //CurrentHeldWeapon KeyValues *pkvActiveWep = pkvTransitionRestoreFile->FindKey("ActiveWeapon"); //Weapon_0. KeyValues *pkvWeapon_0 = pkvTransitionRestoreFile->FindKey("Weapon_0"); KeyValues *pkvWeapon_0_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClip"); KeyValues *pkvWeapon_0_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClip"); KeyValues *pkvWeapon_0_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmo"); KeyValues *pkvWeapon_0_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmo"); KeyValues *pkvWeapon_0_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_PriClipAmmoLeft"); KeyValues *pkvWeapon_0_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_0_SecClipAmmoLeft"); //Weapon_1. KeyValues *pkvWeapon_1 = pkvTransitionRestoreFile->FindKey("Weapon_1"); KeyValues *pkvWeapon_1_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClip"); KeyValues *pkvWeapon_1_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClip"); KeyValues *pkvWeapon_1_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmo"); KeyValues *pkvWeapon_1_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmo"); KeyValues *pkvWeapon_1_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_PriClipAmmoLeft"); KeyValues *pkvWeapon_1_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_1_SecClipAmmoLeft"); //Weapon_2. KeyValues *pkvWeapon_2 = pkvTransitionRestoreFile->FindKey("Weapon_2"); KeyValues *pkvWeapon_2_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClip"); KeyValues *pkvWeapon_2_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClip"); KeyValues *pkvWeapon_2_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmo"); KeyValues *pkvWeapon_2_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmo"); KeyValues *pkvWeapon_2_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_PriClipAmmoLeft"); KeyValues *pkvWeapon_2_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_2_SecClipAmmoLeft"); //Weapon_3. KeyValues *pkvWeapon_3 = pkvTransitionRestoreFile->FindKey("Weapon_3"); KeyValues *pkvWeapon_3_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClip"); KeyValues *pkvWeapon_3_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClip"); KeyValues *pkvWeapon_3_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmo"); KeyValues *pkvWeapon_3_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmo"); KeyValues *pkvWeapon_3_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_PriClipAmmoLeft"); KeyValues *pkvWeapon_3_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_3_SecClipAmmoLeft"); //Weapon_4. KeyValues *pkvWeapon_4 = pkvTransitionRestoreFile->FindKey("Weapon_4"); KeyValues *pkvWeapon_4_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClip"); KeyValues *pkvWeapon_4_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClip"); KeyValues *pkvWeapon_4_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmo"); KeyValues *pkvWeapon_4_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmo"); KeyValues *pkvWeapon_4_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_PriClipAmmoLeft"); KeyValues *pkvWeapon_4_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_4_SecClipAmmoLeft"); //Weapon_5. KeyValues *pkvWeapon_5 = pkvTransitionRestoreFile->FindKey("Weapon_5"); KeyValues *pkvWeapon_5_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClip"); KeyValues *pkvWeapon_5_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClip"); KeyValues *pkvWeapon_5_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmo"); KeyValues *pkvWeapon_5_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmo"); KeyValues *pkvWeapon_5_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_PriClipAmmoLeft"); KeyValues *pkvWeapon_5_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_5_SecClipAmmoLeft"); //Weapon_6. KeyValues *pkvWeapon_6 = pkvTransitionRestoreFile->FindKey("Weapon_6"); KeyValues *pkvWeapon_6_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClip"); KeyValues *pkvWeapon_6_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClip"); KeyValues *pkvWeapon_6_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmo"); KeyValues *pkvWeapon_6_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmo"); KeyValues *pkvWeapon_6_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_PriClipAmmoLeft"); KeyValues *pkvWeapon_6_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_6_SecClipAmmoLeft"); //Weapon_7. KeyValues *pkvWeapon_7 = pkvTransitionRestoreFile->FindKey("Weapon_7"); KeyValues *pkvWeapon_7_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClip"); KeyValues *pkvWeapon_7_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClip"); KeyValues *pkvWeapon_7_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmo"); KeyValues *pkvWeapon_7_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmo"); KeyValues *pkvWeapon_7_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_PriClipAmmoLeft"); KeyValues *pkvWeapon_7_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_7_SecClipAmmoLeft"); //Weapon_8. KeyValues *pkvWeapon_8 = pkvTransitionRestoreFile->FindKey("Weapon_8"); KeyValues *pkvWeapon_8_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClip"); KeyValues *pkvWeapon_8_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClip"); KeyValues *pkvWeapon_8_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmo"); KeyValues *pkvWeapon_8_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmo"); KeyValues *pkvWeapon_8_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_PriClipAmmoLeft"); KeyValues *pkvWeapon_8_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_8_SecClipAmmoLeft"); //Weapon_9. KeyValues *pkvWeapon_9 = pkvTransitionRestoreFile->FindKey("Weapon_9"); KeyValues *pkvWeapon_9_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClip"); KeyValues *pkvWeapon_9_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClip"); KeyValues *pkvWeapon_9_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmo"); KeyValues *pkvWeapon_9_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmo"); KeyValues *pkvWeapon_9_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_PriClipAmmoLeft"); KeyValues *pkvWeapon_9_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_9_SecClipAmmoLeft"); //Weapon_10. KeyValues *pkvWeapon_10 = pkvTransitionRestoreFile->FindKey("Weapon_10"); KeyValues *pkvWeapon_10_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClip"); KeyValues *pkvWeapon_10_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClip"); KeyValues *pkvWeapon_10_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmo"); KeyValues *pkvWeapon_10_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmo"); KeyValues *pkvWeapon_10_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_PriClipAmmoLeft"); KeyValues *pkvWeapon_10_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_10_SecClipAmmoLeft"); //Weapon_11. KeyValues *pkvWeapon_11 = pkvTransitionRestoreFile->FindKey("Weapon_11"); KeyValues *pkvWeapon_11_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClip"); KeyValues *pkvWeapon_11_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClip"); KeyValues *pkvWeapon_11_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmo"); KeyValues *pkvWeapon_11_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmo"); KeyValues *pkvWeapon_11_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_PriClipAmmoLeft"); KeyValues *pkvWeapon_11_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_11_SecClipAmmoLeft"); //Weapon_12. KeyValues *pkvWeapon_12 = pkvTransitionRestoreFile->FindKey("Weapon_12"); KeyValues *pkvWeapon_12_PriClip = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClip"); KeyValues *pkvWeapon_12_SecClip = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClip"); KeyValues *pkvWeapon_12_PriClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmo"); KeyValues *pkvWeapon_12_SecClipAmmo = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmo"); KeyValues *pkvWeapon_12_PriClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_PriClipAmmoLeft"); KeyValues *pkvWeapon_12_SecClipAmmoLeft = pkvTransitionRestoreFile->FindKey("Weapon_12_SecClipAmmoLeft"); //===================================================================== if (pszSteamID) { //Set ints for the class,health and armour. #ifdef SecobMod__USE_PLAYERCLASSES int PlayerClassValue = pkvCurrentClass->GetInt(); #endif int PlayerHealthValue = pkvHealth->GetInt(); int PlayerArmourValue = pkvArmour->GetInt(); //Current Active Weapon const char *pkvActiveWep_Value = pkvActiveWep->GetString(); //============================================================================================ #ifdef SecobMod__USE_PLAYERCLASSES if (PlayerClassValue == 1) { pPlayer->m_iCurrentClass = 1; pPlayer->m_iClientClass = pPlayer->m_iCurrentClass; pPlayer->ForceHUDReload(pPlayer); Msg("Respawning...\n"); pPlayer->PlayerCanChangeClass = false; pPlayer->RemoveAllItems(true); pPlayer->m_iHealth = PlayerHealthValue; pPlayer->m_iMaxHealth = 125; pPlayer->SetArmorValue(PlayerArmourValue); pPlayer->SetMaxArmorValue(0); pPlayer->CBasePlayer::SetWalkSpeed(50); pPlayer->CBasePlayer::SetNormSpeed(190); pPlayer->CBasePlayer::SetSprintSpeed(640); pPlayer->CBasePlayer::SetJumpHeight(200.0); //SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix. pPlayer->CBasePlayer::KeyValue("targetname", "Assaulter"); pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl"); //SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start. CBaseEntity *pEntity = NULL; Vector pEntityOrigin; pEntity = gEntList.FindEntityByClassnameNearest("info_player_assaulter", pEntityOrigin, 0); if (pEntity != NULL) { pEntityOrigin = pEntity->GetAbsOrigin(); pPlayer->SetAbsOrigin(pEntityOrigin); } //PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required. pPlayer->EquipSuit(); pPlayer->StartSprinting(); pPlayer->StopSprinting(); } else if (PlayerClassValue == 2) { pPlayer->m_iCurrentClass = 2; pPlayer->m_iClientClass = pPlayer->m_iCurrentClass; pPlayer->ForceHUDReload(pPlayer); Msg("Respawning...\n"); pPlayer->PlayerCanChangeClass = false; pPlayer->RemoveAllItems(true); pPlayer->m_iHealth = PlayerHealthValue; pPlayer->m_iMaxHealth = 100; pPlayer->SetArmorValue(PlayerArmourValue); pPlayer->SetMaxArmorValue(0); pPlayer->CBasePlayer::SetWalkSpeed(150); pPlayer->CBasePlayer::SetNormSpeed(190); pPlayer->CBasePlayer::SetSprintSpeed(500); pPlayer->CBasePlayer::SetJumpHeight(150.0); //SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix. pPlayer->CBasePlayer::KeyValue("targetname", "Supporter"); pPlayer->SetModel("models/sdk/Humans/Group03/l7h_rebel.mdl"); //SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start. CBaseEntity *pEntity = NULL; Vector pEntityOrigin; pEntity = gEntList.FindEntityByClassnameNearest("info_player_supporter", pEntityOrigin, 0); if (pEntity != NULL) { pEntityOrigin = pEntity->GetAbsOrigin(); pPlayer->SetAbsOrigin(pEntityOrigin); } //PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required. pPlayer->EquipSuit(); pPlayer->StartSprinting(); pPlayer->StopSprinting(); } else if (PlayerClassValue == 3) { pPlayer->m_iCurrentClass = 3; pPlayer->m_iClientClass = pPlayer->m_iCurrentClass; pPlayer->ForceHUDReload(pPlayer); pPlayer->PlayerCanChangeClass = false; pPlayer->RemoveAllItems(true); pPlayer->m_iHealth = PlayerHealthValue; pPlayer->m_iMaxHealth = 80; pPlayer->SetArmorValue(PlayerArmourValue); pPlayer->SetMaxArmorValue(0); pPlayer->CBasePlayer::SetWalkSpeed(150); pPlayer->CBasePlayer::SetNormSpeed(190); pPlayer->CBasePlayer::SetSprintSpeed(320); pPlayer->CBasePlayer::SetJumpHeight(100.0); //SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix. pPlayer->CBasePlayer::KeyValue("targetname", "Medic"); pPlayer->SetModel("models/sdk/Humans/Group03/male_05.mdl"); //SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start. CBaseEntity *pEntity = NULL; Vector pEntityOrigin; pEntity = gEntList.FindEntityByClassnameNearest("info_player_medic", pEntityOrigin, 0); if (pEntity != NULL) { pEntityOrigin = pEntity->GetAbsOrigin(); pPlayer->SetAbsOrigin(pEntityOrigin); } //PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required. pPlayer->EquipSuit(); pPlayer->StartSprinting(); pPlayer->StopSprinting(); pPlayer->EquipSuit(false); } else if (PlayerClassValue == 4) { pPlayer->m_iCurrentClass = 4; pPlayer->m_iClientClass = pPlayer->m_iCurrentClass; pPlayer->ForceHUDReload(pPlayer); pPlayer->PlayerCanChangeClass = false; pPlayer->RemoveAllItems(true); pPlayer->m_iHealth = PlayerHealthValue; pPlayer->m_iMaxHealth = 150; pPlayer->SetArmorValue(PlayerArmourValue); pPlayer->SetMaxArmorValue(200); pPlayer->CBasePlayer::SetWalkSpeed(150); pPlayer->CBasePlayer::SetNormSpeed(190); pPlayer->CBasePlayer::SetSprintSpeed(320); pPlayer->CBasePlayer::SetJumpHeight(40.0); //SecobMod__Information This allows you to use filtering while mapping. Such as only a trigger one class may actually trigger. Thanks to Alters for providing this fix. pPlayer->CBasePlayer::KeyValue("targetname", "Heavy"); pPlayer->SetModel("models/sdk/Humans/Group03/police_05.mdl"); //SecobMod__Information Due to the way our player classes now work, the first spawn of any class has to teleport to their specific player start. CBaseEntity *pEntity = NULL; Vector pEntityOrigin; pEntity = gEntList.FindEntityByClassnameNearest("info_player_heavy", pEntityOrigin, 0); if (pEntity != NULL) { pEntityOrigin = pEntity->GetAbsOrigin(); pPlayer->SetAbsOrigin(pEntityOrigin); } //PlayerClass bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required. pPlayer->EquipSuit(); pPlayer->StartSprinting(); pPlayer->StopSprinting(); } #endif //SecobMod__USE_PLAYERCLASSES #ifndef SecobMod__USE_PLAYERCLASSES pPlayer->m_iHealth = PlayerHealthValue; pPlayer->m_iMaxHealth = 125; pPlayer->SetArmorValue(PlayerArmourValue); pPlayer->SetModel("models/sdk/Humans/Group03/male_06_sdk.mdl"); //Bug fix - if the below lines are removed the player is stuck with 0 movement, once they're able to move again we can remove the suit as required. pPlayer->EquipSuit(); pPlayer->StartSprinting(); pPlayer->StopSprinting(); #endif //SecobMod__USE_PLAYERCLASSES NOT const char *pkvWeapon_Value = NULL; int Weapon_PriClip_Value = 0; const char *pkvWeapon_PriClipAmmo_Value = NULL; int Weapon_SecClip_Value = 0; const char *pkvWeapon_SecClipAmmo_Value = NULL; int Weapon_PriClipCurrent_Value = 0; int Weapon_SecClipCurrent_Value = 0; //Loop through all of our weapon slots. for (int i = 0; i < 12; i++) { if (i == 0) { pkvWeapon_Value = pkvWeapon_0->GetString(); Weapon_PriClip_Value = pkvWeapon_0_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_0_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_0_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_0_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_0_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_0_SecClipAmmoLeft->GetInt(); } else if (i == 1) { pkvWeapon_Value = pkvWeapon_1->GetString(); Weapon_PriClip_Value = pkvWeapon_1_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_1_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_1_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_1_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_1_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_1_SecClipAmmoLeft->GetInt(); } else if (i == 2) { pkvWeapon_Value = pkvWeapon_2->GetString(); Weapon_PriClip_Value = pkvWeapon_2_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_2_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_2_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_2_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_2_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_2_SecClipAmmoLeft->GetInt(); } else if (i == 3) { pkvWeapon_Value = pkvWeapon_3->GetString(); Weapon_PriClip_Value = pkvWeapon_3_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_3_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_3_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_3_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_3_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_3_SecClipAmmoLeft->GetInt(); } else if (i == 4) { pkvWeapon_Value = pkvWeapon_4->GetString(); Weapon_PriClip_Value = pkvWeapon_4_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_4_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_4_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_4_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_4_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_4_SecClipAmmoLeft->GetInt(); } else if (i == 5) { pkvWeapon_Value = pkvWeapon_5->GetString(); Weapon_PriClip_Value = pkvWeapon_5_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_5_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_5_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_5_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_5_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_5_SecClipAmmoLeft->GetInt(); } else if (i == 6) { pkvWeapon_Value = pkvWeapon_6->GetString(); Weapon_PriClip_Value = pkvWeapon_6_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_6_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_6_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_6_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_6_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_6_SecClipAmmoLeft->GetInt(); } else if (i == 7) { pkvWeapon_Value = pkvWeapon_7->GetString(); Weapon_PriClip_Value = pkvWeapon_7_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_7_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_7_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_7_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_7_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_7_SecClipAmmoLeft->GetInt(); } else if (i == 8) { pkvWeapon_Value = pkvWeapon_8->GetString(); Weapon_PriClip_Value = pkvWeapon_8_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_8_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_8_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_8_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_8_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_8_SecClipAmmoLeft->GetInt(); } else if (i == 9) { pkvWeapon_Value = pkvWeapon_9->GetString(); Weapon_PriClip_Value = pkvWeapon_9_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_9_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_9_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_9_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_9_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_9_SecClipAmmoLeft->GetInt(); } else if (i == 10) { pkvWeapon_Value = pkvWeapon_10->GetString(); Weapon_PriClip_Value = pkvWeapon_10_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_10_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_10_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_10_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_10_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_10_SecClipAmmoLeft->GetInt(); } else if (i == 11) { pkvWeapon_Value = pkvWeapon_11->GetString(); Weapon_PriClip_Value = pkvWeapon_11_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_11_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_11_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_11_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_11_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_11_SecClipAmmoLeft->GetInt(); } else if (i == 12) { pkvWeapon_Value = pkvWeapon_12->GetString(); Weapon_PriClip_Value = pkvWeapon_12_PriClip->GetInt(); pkvWeapon_PriClipAmmo_Value = pkvWeapon_12_PriClipAmmo->GetString(); Weapon_SecClip_Value = pkvWeapon_12_SecClip->GetInt(); pkvWeapon_SecClipAmmo_Value = pkvWeapon_12_SecClipAmmo->GetString(); Weapon_PriClipCurrent_Value = pkvWeapon_12_PriClipAmmoLeft->GetInt(); Weapon_SecClipCurrent_Value = pkvWeapon_12_SecClipAmmoLeft->GetInt(); } //Now give the weapon and ammo. pPlayer->GiveNamedItem((pkvWeapon_Value)); pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvWeapon_Value)); if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo1()) { if (Weapon_PriClipCurrent_Value != -1) { if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0) { pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value; pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value; pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value)); pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value); } else { pPlayer->GetActiveWeapon()->m_iClip1 = Weapon_PriClipCurrent_Value; pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, pkvWeapon_PriClipAmmo_Value); //Msg("Weapon primary clip value should be: %i\n", Weapon_PriClipCurrent_Value); } } } else { pPlayer->GetActiveWeapon()->m_iPrimaryAmmoType = Weapon_PriClip_Value; pPlayer->GetActiveWeapon()->SetPrimaryAmmoCount(int(Weapon_PriClip_Value)); pPlayer->CBasePlayer::GiveAmmo(Weapon_PriClip_Value, Weapon_PriClip_Value); } if (pPlayer->GetActiveWeapon()->UsesClipsForAmmo2()) { if (Weapon_SecClipCurrent_Value != -1) { if (strcmp(pkvWeapon_Value, "weapon_crossbow") == 0) { pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value; pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value; pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value)); pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value); } else { pPlayer->GetActiveWeapon()->m_iClip2 = Weapon_SecClipCurrent_Value; pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, pkvWeapon_SecClipAmmo_Value); } } } else { pPlayer->GetActiveWeapon()->m_iSecondaryAmmoType = Weapon_SecClip_Value; pPlayer->GetActiveWeapon()->SetSecondaryAmmoCount(int(Weapon_SecClip_Value)); pPlayer->CBasePlayer::GiveAmmo(Weapon_SecClip_Value, Weapon_SecClip_Value); } } //Now restore the players Active Weapon (the weapon they had out at the level transition). pPlayer->Weapon_Switch(pPlayer->Weapon_OwnsThisType(pkvActiveWep_Value)); } else { //Something went wrong show the class panel. pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL); } break; } } else { //Something went wrong show the class panel. pPlayer->ShowViewPortPanel(PANEL_CLASS, true, NULL); } #endif //SecobMod__SAVERESTORE #ifdef SecobMod__ENABLE_MAP_BRIEFINGS pPlayer->ShowViewPortPanel(PANEL_INFO, false, NULL); const char *brief_title = "Briefing: ";//(hostname) ? hostname->GetString() : "MESSAGE OF THE DAY"; KeyValues *brief_data = new KeyValues("brief_data"); brief_data->SetString("title", brief_title); // info panel title brief_data->SetString("type", "1"); // show userdata from stringtable entry brief_data->SetString("msg", "briefing"); // use this stringtable entry pPlayer->ShowViewPortPanel(PANEL_INFO, true, brief_data); #endif //SecobMod__ENABLE_MAP_BRIEFINGS data->deleteThis(); } /* =========== ClientPutInServer called each time a player is spawned into the game ============ */ void ClientPutInServer(edict_t *pEdict, const char *playername) { // Allocate a CBaseTFPlayer for pev, and call spawn CHL2MP_Player *pPlayer = CHL2MP_Player::CreatePlayer("player", pEdict); pPlayer->SetPlayerName(playername); } void ClientActive(edict_t *pEdict, bool bLoadGame) { // Can't load games in CS! Assert(!bLoadGame); CHL2MP_Player *pPlayer = ToHL2MPPlayer(CBaseEntity::Instance(pEdict)); FinishClientPutInServer(pPlayer); } /* =============== const char *GetGameDescription() Returns the descriptive name of this .dll. E.g., Half-Life, or Team Fortress 2 =============== */ const char *GetGameDescription() { if (g_pGameRules) // this function may be called before the world has spawned, and the game rules initialized return g_pGameRules->GetGameDescription(); else return "Half-Life 2 Deathmatch"; } //----------------------------------------------------------------------------- // Purpose: Given a player and optional name returns the entity of that // classname that the player is nearest facing // // Input : // Output : //----------------------------------------------------------------------------- CBaseEntity* FindEntity(edict_t *pEdict, char *classname) { // If no name was given set bits based on the picked if (FStrEq(classname, "")) { return (FindPickerEntityClass(static_cast<CBasePlayer*>(GetContainingEntity(pEdict)), classname)); } return NULL; } //----------------------------------------------------------------------------- // Purpose: Precache game-specific models & sounds //----------------------------------------------------------------------------- void ClientGamePrecache(void) { CBaseEntity::PrecacheModel("models/player.mdl"); CBaseEntity::PrecacheModel("models/gibs/agibs.mdl"); CBaseEntity::PrecacheModel("models/weapons/v_hands.mdl"); CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowAmmo"); CBaseEntity::PrecacheScriptSound("HUDQuickInfo.LowHealth"); CBaseEntity::PrecacheScriptSound("FX_AntlionImpact.ShellImpact"); CBaseEntity::PrecacheScriptSound("Missile.ShotDown"); CBaseEntity::PrecacheScriptSound("Bullets.DefaultNearmiss"); CBaseEntity::PrecacheScriptSound("Bullets.GunshipNearmiss"); CBaseEntity::PrecacheScriptSound("Bullets.StriderNearmiss"); CBaseEntity::PrecacheScriptSound("Geiger.BeepHigh"); CBaseEntity::PrecacheScriptSound("Geiger.BeepLow"); } // called by ClientKill and DeadThink void respawn(CBaseEntity *pEdict, bool fCopyCorpse) { CHL2MP_Player *pPlayer = ToHL2MPPlayer(pEdict); if (pPlayer) { if (gpGlobals->curtime > pPlayer->GetDeathTime() + DEATH_ANIMATION_TIME) { // respawn player pPlayer->Spawn(); } else { pPlayer->SetNextThink(gpGlobals->curtime + 0.1f); } } } void GameStartFrame(void) { VPROF("GameStartFrame()"); if (g_fGameOver) return; gpGlobals->teamplay = (teamplay.GetInt() != 0); #ifdef DEBUG extern void Bot_RunAll(); Bot_RunAll(); #endif } //========================================================= // instantiate the proper game rules object //========================================================= void InstallGameRules() { // vanilla deathmatch CreateGameRulesObject("CHL2MPRules"); }
44.230483
177
0.734885
Code4Cookie
9144fae7a490acfaabb4036f476a6b31aa8956f1
1,697
cpp
C++
sparta/test/DisjointUnionAbstractDomainTest.cpp
penguin-wwy/redex
31baadec7ccddcadb5ddaf4947a63112f2eadc04
[ "MIT" ]
6,059
2016-04-12T21:07:05.000Z
2022-03-31T16:31:48.000Z
sparta/test/DisjointUnionAbstractDomainTest.cpp
penguin-wwy/redex
31baadec7ccddcadb5ddaf4947a63112f2eadc04
[ "MIT" ]
638
2016-04-12T22:45:48.000Z
2022-03-29T21:50:09.000Z
sparta/test/DisjointUnionAbstractDomainTest.cpp
penguin-wwy/redex
31baadec7ccddcadb5ddaf4947a63112f2eadc04
[ "MIT" ]
704
2016-04-12T23:47:01.000Z
2022-03-30T09:44:56.000Z
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ // Because of the rules of argument-dependent lookup, we need to include the // definition of operator<< for ConstantAbstractDomain before that of operator<< // for DisjointUnionAbstractDomain. #include "ConstantAbstractDomain.h" #include "DisjointUnionAbstractDomain.h" #include <gtest/gtest.h> #include <string> #include "AbstractDomainPropertyTest.h" using namespace sparta; using IntDomain = ConstantAbstractDomain<int>; using StringDomain = ConstantAbstractDomain<std::string>; using IntStringDomain = DisjointUnionAbstractDomain<IntDomain, StringDomain>; INSTANTIATE_TYPED_TEST_CASE_P(DisjointUnionAbstractDomain, AbstractDomainPropertyTest, IntStringDomain); template <> std::vector<IntStringDomain> AbstractDomainPropertyTest<IntStringDomain>::top_values() { return {IntDomain::top(), StringDomain::top()}; } template <> std::vector<IntStringDomain> AbstractDomainPropertyTest<IntStringDomain>::bottom_values() { return {IntDomain::bottom(), StringDomain::bottom()}; } template <> std::vector<IntStringDomain> AbstractDomainPropertyTest<IntStringDomain>::non_extremal_values() { return {IntDomain(0), StringDomain("foo")}; } TEST(DisjointUnionAbstractDomainTest, basicOperations) { IntStringDomain zero = IntDomain(0); IntStringDomain str = StringDomain(""); EXPECT_TRUE(zero.join(str).is_top()); EXPECT_TRUE(zero.meet(str).is_bottom()); EXPECT_NLEQ(zero, str); EXPECT_NLEQ(str, zero); EXPECT_NE(zero, str); }
29.77193
80
0.751326
penguin-wwy
9149d2a1b7940bbed03cb6426d69eaecbbd1b6e1
2,320
cpp
C++
Source/FactoryGame/FGActorRepresentation.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGActorRepresentation.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
Source/FactoryGame/FGActorRepresentation.cpp
iam-Legend/Project-Assembly
1ff3587704232d5e330515bc0d2aceb64ff09a7f
[ "MIT" ]
null
null
null
// This file has been automatically generated by the Unreal Header Implementation tool #include "FGActorRepresentation.h" bool UFGActorRepresentation::IsSupportedForNetworking() const{ return bool(); } void UFGActorRepresentation::GetLifetimeReplicatedProps( TArray<FLifetimeProperty>& OutLifetimeProps) const{ } FVector UFGActorRepresentation::GetActorLocation() const{ return FVector(); } FRotator UFGActorRepresentation::GetActorRotation() const{ return FRotator(); } UTexture2D* UFGActorRepresentation::GetRepresentationTexture() const{ return nullptr; } FText UFGActorRepresentation::GetRepresentationText() const{ return FText(); } FLinearColor UFGActorRepresentation::GetRepresentationColor() const{ return FLinearColor(); } ERepresentationType UFGActorRepresentation::GetRepresentationType() const{ return ERepresentationType(); } bool UFGActorRepresentation::GetShouldShowInCompass() const{ return bool(); } bool UFGActorRepresentation::GetShouldShowOnMap() const{ return bool(); } EFogOfWarRevealType UFGActorRepresentation::GetFogOfWarRevealType() const{ return EFogOfWarRevealType(); } float UFGActorRepresentation::GetFogOfWarRevealRadius() const{ return float(); } void UFGActorRepresentation::SetIsOnClient( bool onClient){ } ECompassViewDistance UFGActorRepresentation::GetCompassViewDistance() const{ return ECompassViewDistance(); } void UFGActorRepresentation::SetLocalCompassViewDistance( ECompassViewDistance compassViewDistance){ } AFGActorRepresentationManager* UFGActorRepresentation::GetActorRepresentationManager(){ return nullptr; } void UFGActorRepresentation::UpdateLocation(){ } void UFGActorRepresentation::UpdateRotation(){ } void UFGActorRepresentation::UpdateRepresentationText(){ } void UFGActorRepresentation::UpdateRepresentationTexture(){ } void UFGActorRepresentation::UpdateRepresentationColor(){ } void UFGActorRepresentation::UpdateShouldShowInCompass(){ } void UFGActorRepresentation::UpdateShouldShowOnMap(){ } void UFGActorRepresentation::UpdateFogOfWarRevealType(){ } void UFGActorRepresentation::UpdateFogOfWarRevealRadius(){ } void UFGActorRepresentation::UpdateCompassViewDistance(){ } void UFGActorRepresentation::OnRep_ShouldShowInCompass(){ } void UFGActorRepresentation::OnRep_ShouldShowOnMap(){ } void UFGActorRepresentation::OnRep_ActorRepresentationUpdated(){ }
68.235294
110
0.840948
iam-Legend
9151163ce73ca6cdaf0d49ed2c19ba114ea924c3
4,623
cpp
C++
QTP/views/createstaffdialog.cpp
Qu3tzal/TpQt
a741c64659d4808693c92de217261c75ed5fe17a
[ "MIT" ]
null
null
null
QTP/views/createstaffdialog.cpp
Qu3tzal/TpQt
a741c64659d4808693c92de217261c75ed5fe17a
[ "MIT" ]
null
null
null
QTP/views/createstaffdialog.cpp
Qu3tzal/TpQt
a741c64659d4808693c92de217261c75ed5fe17a
[ "MIT" ]
1
2018-09-30T10:39:37.000Z
2018-09-30T10:39:37.000Z
#include "CreateStaffDialog.h" #include "ui_createstaffdialog.h" #include "model/staffmodel.h" #include "model/accountmodel.h" #include "model/account.h" #include "model/staff.h" #include "QMessageBox" #include "mainwindow.h" #include "stringutil.h" CreateStaffDialog::CreateStaffDialog(int staffId, QWidget *parent) : QDialog(parent) , ui(new Ui::CreateStaffDialog) , staff(Staff(staffId, "", "", -1)) , account(Account(-1, -1, "", "")) { // Load the UI. ui->setupUi(this); // Check if we are in modification or add. int currentIndex = 0; if(staffId != -1) { // Load the staff data. staff = StaffModel::getStaffById(staffId); // Fill the forms with the data. ui->firstNameLineEdit->setText(staff.getFirstName()); ui->lastNameLineEdit->setText(staff.getLastName()); if(staff.getTypeId() == 7) account = AccountModel::getAccountById(staff.getId()); // Change window title. setWindowTitle(QString("Modification de la ressource ") + staff.getFirstName() + " " + staff.getLastName()); } QList<StaffType> types = StaffModel::getStaffTypes(); for(int i = 0; i < types.size(); i++) { ui->typeComboBox->addItem(types[i].label); if(staffId != -1 && types[i].id == staff.getTypeId()) currentIndex = i; } if(staffId != -1) { ui->typeComboBox->setCurrentIndex(currentIndex); } // Hide login and password onComboBoxChanged(); // Connections. connect(this, SIGNAL(accepted()), this, SLOT(onDialogAccepted())); connect(this, SIGNAL(rejected()), this, SLOT(onDialogRejected())); connect(ui->typeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxChanged())); connect(this, SIGNAL(onStaffAdded()), (MainWindow*)parent, SLOT(onClientAdded())); // Capitalizer. QFont font = ui->firstNameLineEdit->font(); font.setCapitalization(QFont::Capitalize); ui->firstNameLineEdit->setFont(font); ui->lastNameLineEdit->setFont(font); } CreateStaffDialog::~CreateStaffDialog() { delete ui; } void CreateStaffDialog::onDialogAccepted() { if(staff.getId() == -1) { // Create staff. int staffId = StaffModel::addStaff(Staff(-1, StringUtil::capitalize(ui->firstNameLineEdit->text()), StringUtil::capitalize(ui->lastNameLineEdit->text()), StaffModel::getTypeIdFromLabel(ui->typeComboBox->currentText()))); // Create account only if needed. if(ui->typeComboBox->currentText() == "Informaticien") { QString login = ui->loginLineEdit->text(); QString password = ui->passwordLineEdit->text(); AccountModel::createAccount(login, password, staffId); } } else { // Create staff. StaffModel::updateStaff(Staff(staff.getId(), StringUtil::capitalize(ui->firstNameLineEdit->text()), StringUtil::capitalize(ui->lastNameLineEdit->text()), StaffModel::getTypeIdFromLabel(ui->typeComboBox->currentText()))); // Create account only if needed. if(ui->typeComboBox->currentText() == "Informaticien") { QString login = ui->loginLineEdit->text(); QString password = ui->passwordLineEdit->text(); if(staff.getTypeId() == 7) AccountModel::updateAccount(Account(account.getId(), staff.getId(), login, password)); else AccountModel::createAccount(login, password, staff.getId()); } // Type 7 == informaticien else if(staff.getTypeId() == 7) { AccountModel::removeAccountOfStaff(staff.getId()); } } emit onStaffAdded(); } void CreateStaffDialog::onDialogRejected() { } void CreateStaffDialog::onComboBoxChanged() { // If the selected role is one with an account, display the login & password. if(ui->typeComboBox->currentText() == "Informaticien") { if(staff.getTypeId() == 7) { ui->passwordLineEdit->setText(account.getPassword()); ui->loginLineEdit->setText(account.getLogin()); } ui->loginLabel->setVisible(true); ui->loginLineEdit->setVisible(true); ui->passwordLabel->setVisible(true); ui->passwordLineEdit->setVisible(true); } else { if(staff.getTypeId() == 7) { QMessageBox::warning(this,"Attention", "Attention cela va supprimer le compte !"); } ui->loginLabel->setVisible(false); ui->loginLineEdit->setVisible(false); ui->passwordLabel->setVisible(false); ui->passwordLineEdit->setVisible(false); } }
30.82
228
0.631624
Qu3tzal
9153ce528d3233d5711d659b095c160f2610f2fe
7,655
cpp
C++
ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp
morpheus-org/morpheus-interoperability
66161199fa1926914e16c1feb02eb910ffef5ed4
[ "Apache-2.0" ]
null
null
null
ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp
morpheus-org/morpheus-interoperability
66161199fa1926914e16c1feb02eb910ffef5ed4
[ "Apache-2.0" ]
3
2021-10-09T16:17:19.000Z
2021-10-12T21:31:23.000Z
ccl/src/phost/Morpheus_Ccl_CsrMatrix.cpp
morpheus-org/morpheus-fortran-interop
66161199fa1926914e16c1feb02eb910ffef5ed4
[ "Apache-2.0" ]
null
null
null
/** * Morpheus_Ccl_CsrMatrix.cpp * * EPCC, The University of Edinburgh * * (c) 2021 The University of Edinburgh * * Contributing Authors: * Christodoulos Stylianou (c.stylianou@ed.ac.uk) * * 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 <phost/Morpheus_Ccl_CsrMatrix.hpp> void ccl_phmat_csr_create_default(ccl_phmat_csr** A) { *A = (new ccl_phmat_csr()); } void ccl_phmat_csr_create(ccl_phmat_csr** A, ccl_index_t nrows, ccl_index_t ncols, ccl_index_t nnnz) { *A = (new ccl_phmat_csr("ccl_phmat_csr::", nrows, ncols, nnnz)); } void ccl_phmat_csr_create_from_phmat_csr(ccl_phmat_csr* src, ccl_phmat_csr** dst) { *dst = (new ccl_phmat_csr(*src)); } void ccl_phmat_csr_create_from_phmat_dyn(ccl_phmat_dyn* src, ccl_phmat_csr** dst) { *dst = (new ccl_phmat_csr(*src)); } void ccl_phmat_csr_resize(ccl_phmat_csr* A, const ccl_index_t num_rows, const ccl_index_t num_cols, const ccl_index_t num_nnz) { A->resize(num_rows, num_cols, num_nnz); } // Assumes dst matrix is always created void ccl_phmat_csr_allocate_from_phmat_csr(ccl_phmat_csr* src, ccl_phmat_csr* dst) { dst->allocate("ccl_phmat_csr::allocate::", *src); } void ccl_phmat_csr_destroy(ccl_phmat_csr** A) { delete (*A); } ccl_index_t ccl_phmat_csr_nrows(ccl_phmat_csr* A) { return A->nrows(); } ccl_index_t ccl_phmat_csr_ncols(ccl_phmat_csr* A) { return A->ncols(); } ccl_index_t ccl_phmat_csr_nnnz(ccl_phmat_csr* A) { return A->nnnz(); } void ccl_phmat_csr_set_nrows(ccl_phmat_csr* A, ccl_index_t nrows) { A->set_nrows(nrows); } void ccl_phmat_csr_set_ncols(ccl_phmat_csr* A, ccl_index_t ncols) { A->set_ncols(ncols); } void ccl_phmat_csr_set_nnnz(ccl_phmat_csr* A, ccl_index_t nnnz) { A->set_nnnz(nnnz); } ccl_index_t ccl_phmat_csr_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i) { return A->row_offsets(i); } ccl_index_t ccl_phmat_csr_column_indices_at(ccl_phmat_csr* A, ccl_index_t i) { return A->column_indices(i); } ccl_value_t ccl_phmat_csr_values_at(ccl_phmat_csr* A, ccl_index_t i) { return A->values(i); } ccl_phvec_dense_i* ccl_phmat_csr_row_offsets(ccl_phmat_csr* A) { return &(A->row_offsets()); } ccl_phvec_dense_i* ccl_phmat_csr_column_indices(ccl_phmat_csr* A) { return &(A->column_indices()); } ccl_phvec_dense_v* ccl_phmat_csr_values(ccl_phmat_csr* A) { return &(A->values()); } void ccl_phmat_csr_set_row_offsets_at(ccl_phmat_csr* A, ccl_index_t i, ccl_index_t val) { A->row_offsets(i) = val; } void ccl_phmat_csr_set_column_indices_at(ccl_phmat_csr* A, ccl_index_t i, ccl_index_t val) { A->column_indices(i) = val; } void ccl_phmat_csr_set_values_at(ccl_phmat_csr* A, ccl_index_t i, ccl_value_t val) { A->values(i) = val; } ccl_formats_e ccl_phmat_csr_format_enum(ccl_phmat_csr* A) { return A->format_enum(); } int ccl_phmat_csr_format_index(ccl_phmat_csr* A) { return A->format_index(); } void ccl_phmat_csr_hostmirror_create_default(ccl_phmat_csr_hostmirror** A) { *A = (new ccl_phmat_csr_hostmirror()); } void ccl_phmat_csr_hostmirror_create(ccl_phmat_csr_hostmirror** A, ccl_index_t nrows, ccl_index_t ncols, ccl_index_t nnnz) { *A = (new ccl_phmat_csr_hostmirror("ccl_phmat_csr_hostmirror::", nrows, ncols, nnnz)); } void ccl_phmat_csr_hostmirror_create_from_phmat_csr_hostmirror( ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror** dst) { *dst = (new ccl_phmat_csr_hostmirror(*src)); } void ccl_phmat_csr_hostmirror_create_from_phmat_dyn_hostmirror( ccl_phmat_dyn_hostmirror* src, ccl_phmat_csr_hostmirror** dst) { *dst = (new ccl_phmat_csr_hostmirror(*src)); } void ccl_phmat_csr_hostmirror_resize(ccl_phmat_csr_hostmirror* A, const ccl_index_t num_rows, const ccl_index_t num_cols, const ccl_index_t num_nnz) { A->resize(num_rows, num_cols, num_nnz); } // Assumes dst matrix is always created void ccl_phmat_csr_hostmirror_allocate_from_phmat_csr_hostmirror( ccl_phmat_csr_hostmirror* src, ccl_phmat_csr_hostmirror* dst) { dst->allocate("ccl_phmat_csr_hostmirror::allocate::", *src); } void ccl_phmat_csr_hostmirror_destroy(ccl_phmat_csr_hostmirror** A) { delete (*A); } ccl_index_t ccl_phmat_csr_hostmirror_nrows(ccl_phmat_csr_hostmirror* A) { return A->nrows(); } ccl_index_t ccl_phmat_csr_hostmirror_ncols(ccl_phmat_csr_hostmirror* A) { return A->ncols(); } ccl_index_t ccl_phmat_csr_hostmirror_nnnz(ccl_phmat_csr_hostmirror* A) { return A->nnnz(); } void ccl_phmat_csr_hostmirror_set_nrows(ccl_phmat_csr_hostmirror* A, ccl_index_t nrows) { A->set_nrows(nrows); } void ccl_phmat_csr_hostmirror_set_ncols(ccl_phmat_csr_hostmirror* A, ccl_index_t ncols) { A->set_ncols(ncols); } void ccl_phmat_csr_hostmirror_set_nnnz(ccl_phmat_csr_hostmirror* A, ccl_index_t nnnz) { A->set_nnnz(nnnz); } ccl_index_t ccl_phmat_csr_hostmirror_row_offsets_at(ccl_phmat_csr_hostmirror* A, ccl_index_t i) { return A->row_offsets(i); } ccl_index_t ccl_phmat_csr_hostmirror_column_indices_at( ccl_phmat_csr_hostmirror* A, ccl_index_t i) { return A->column_indices(i); } ccl_value_t ccl_phmat_csr_hostmirror_values_at(ccl_phmat_csr_hostmirror* A, ccl_index_t i) { return A->values(i); } ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_row_offsets( ccl_phmat_csr_hostmirror* A) { return &(A->row_offsets()); } ccl_phvec_dense_i_hostmirror* ccl_phmat_csr_hostmirror_column_indices( ccl_phmat_csr_hostmirror* A) { return &(A->column_indices()); } ccl_phvec_dense_v_hostmirror* ccl_phmat_csr_hostmirror_values( ccl_phmat_csr_hostmirror* A) { return &(A->values()); } void ccl_phmat_csr_hostmirror_set_row_offsets_at(ccl_phmat_csr_hostmirror* A, ccl_index_t i, ccl_index_t val) { A->row_offsets(i) = val; } void ccl_phmat_csr_hostmirror_set_column_indices_at(ccl_phmat_csr_hostmirror* A, ccl_index_t i, ccl_index_t val) { A->column_indices(i) = val; } void ccl_phmat_csr_hostmirror_set_values_at(ccl_phmat_csr_hostmirror* A, ccl_index_t i, ccl_value_t val) { A->values(i) = val; } ccl_formats_e ccl_phmat_csr_hostmirror_format_enum( ccl_phmat_csr_hostmirror* A) { return A->format_enum(); } int ccl_phmat_csr_hostmirror_format_index(ccl_phmat_csr_hostmirror* A) { return A->format_index(); }
31.632231
80
0.677335
morpheus-org
9155d85b095ad63a3ce325cf87816c7be6bda86c
41
cpp
C++
Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
5
2021-04-20T17:00:41.000Z
2022-01-18T20:16:03.000Z
Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
7
2021-08-22T21:30:50.000Z
2022-01-14T16:56:34.000Z
Othuum/AhwassaGraphicsLib/BufferObjects/Mesh.cpp
Liech/Yathsou
95b6dda3c053bc25789cce416088e22f54a743b4
[ "MIT" ]
null
null
null
#include "Mesh.h" namespace Ahwassa { }
8.2
19
0.682927
Liech
9156515ceb072c7dfc4c82041de6706a826d7364
1,044
cpp
C++
examples/xtd.forms.examples/controls/checked_list_box/src/checked_list_box.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
251
2019-04-20T02:02:24.000Z
2022-03-31T09:52:08.000Z
examples/xtd.forms.examples/controls/checked_list_box/src/checked_list_box.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
29
2021-01-07T12:52:12.000Z
2022-03-29T08:42:14.000Z
examples/xtd.forms.examples/controls/checked_list_box/src/checked_list_box.cpp
ExternalRepositories/xtd
5889d69900ad22a00fcb640d7850a1d599cf593a
[ "MIT" ]
27
2019-11-21T02:37:44.000Z
2022-03-30T22:59:14.000Z
#include <xtd/xtd> using namespace std; using namespace xtd; using namespace xtd::forms; namespace examples { class form1 : public form { public: form1() { text("Checked list box example"); client_size({200, 240}); checked_list_box1.parent(*this); checked_list_box1.anchor(anchor_styles::top | anchor_styles::left | anchor_styles::bottom | anchor_styles::right); checked_list_box1.location({20, 20}); checked_list_box1.size({160, 200}); for (auto index = 1; index <= 10; ++index) checked_list_box1.items().push_back({ustring::format("Item {}", index), index % 2 != 0}); checked_list_box1.selected_index(0); checked_list_box1.item_check += [](object& sender, item_check_event_args& e) { cdebug << ustring::format("item_check, index={}, new_value={}, current_value={}", e.index(), e.new_value(), e.current_value()) << endl; }; } private: checked_list_box checked_list_box1; }; } int main() { application::run(examples::form1()); }
29
143
0.648467
ExternalRepositories
91583af8c3e6e20525cac6f1fa384585effe7648
11,254
cpp
C++
src/vizdoom/src/bbannouncer.cpp
johny-c/ViZDoom
6fe0d2470872adbfa5d18c53c7704e6ff103cacc
[ "MIT" ]
1,102
2017-02-02T15:39:57.000Z
2022-03-23T09:43:29.000Z
src/bbannouncer.cpp
Leonan8995/Xenomia
3f3743dd5aff047608ec31fb71186d177812c7df
[ "Unlicense" ]
339
2017-02-17T09:55:38.000Z
2022-03-29T11:44:01.000Z
src/bbannouncer.cpp
Leonan8995/Xenomia
3f3743dd5aff047608ec31fb71186d177812c7df
[ "Unlicense" ]
331
2017-02-02T15:34:42.000Z
2022-03-23T02:42:24.000Z
/* ** bbannouncer.cpp ** The announcer from Blood (The Voice). ** **--------------------------------------------------------------------------- ** Copyright 1998-2006 Randy Heit ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** ** It's been so long since I played a bloodbath, I don't know when all ** these sounds are used, so much of this usage is me guessing. Some of ** it has also obviously been reused for events that were never present ** in bloodbaths. ** ** I should really have a base Announcer class and derive the Bloodbath ** announcer off of that. That way, multiple announcer styles could be ** supported easily. */ // HEADER FILES ------------------------------------------------------------ #include "actor.h" #include "gstrings.h" #include "s_sound.h" #include "m_random.h" #include "d_player.h" #include "g_level.h" #include "doomstat.h" // MACROS ------------------------------------------------------------------ // TYPES ------------------------------------------------------------------- struct SoundAndString { const char *Message; const char *Sound; }; // EXTERNAL FUNCTION PROTOTYPES -------------------------------------------- void SexMessage (const char *from, char *to, int gender, const char *victim, const char *killer); // PUBLIC FUNCTION PROTOTYPES ---------------------------------------------- // PRIVATE FUNCTION PROTOTYPES --------------------------------------------- // EXTERNAL DATA DECLARATIONS ---------------------------------------------- // PUBLIC DATA DEFINITIONS ------------------------------------------------- CVAR (Bool, cl_bbannounce, false, CVAR_ARCHIVE) // PRIVATE DATA DEFINITIONS ------------------------------------------------ static const char *BeginSounds[] = { "VO1.SFX", // Let the bloodbath begin "VO2.SFX", // The festival of blood continues }; static const SoundAndString WorldKillSounds[] = { { "BBA_EXCREMENT", "VO7.SFX" }, // Excrement { "BBA_HAMBURGER", "VO8.SFX" }, // Hamburger { "BBA_SCROTUM", "VO9.SFX" }, // Scrotum separation }; static const SoundAndString SuicideSounds[] = { { "BBA_SUICIDE", "VO13.SFX" }, // Unassisted death { "BBA_SUICIDE", "VO5.SFX" }, // Kevorkian approves { "BBA_POPULATION", "VO12.SFX" }, // Population control { "BBA_DARWIN", "VO16.SFX" } // Darwin award }; static const SoundAndString KillSounds[] = { { "BBA_BONED", "BONED.SFX" }, // Boned { "BBA_CREAMED", "CREAMED.SFX" }, // Creamed { "BBA_DECIMAT", "DECIMAT.SFX" }, // Decimated { "BBA_DESTRO", "DESTRO.SFX" }, // Destroyed { "BBA_DICED", "DICED.SFX" }, // Diced { "BBA_DISEMBO", "DISEMBO.SFX" }, // Disembowled { "BBA_FLATTE", "FLATTE.SFX" }, // Flattened { "BBA_JUSTICE", "JUSTICE.SFX" }, // Justice { "BBA_MADNESS", "MADNESS.SFX" }, // Madness { "BBA_KILLED", "KILLED.SFX" }, // Killed { "BBA_MINCMEAT", "MINCMEAT.SFX" }, // Mincemeat { "BBA_MASSACR", "MASSACR.SFX" }, // Massacred { "BBA_MUTILA", "MUTILA.SFX" }, // Mutilated { "BBA_REAMED", "REAMED.SFX" }, // Reamed { "BBA_RIPPED", "RIPPED.SFX" }, // Ripped { "BBA_SLAUGHT", "SLAUGHT.SFX" }, // Slaughtered { "BBA_SMASHED", "SMASHED.SFX" }, // Smashed { "BBA_SODOMIZ", "SODOMIZ.SFX" }, // Sodomized { "BBA_SPLATT", "SPLATT.SFX" }, // Splattered { "BBA_SQUASH", "SQUASH.SFX" }, // Squashed { "BBA_THROTTL", "THROTTL.SFX" }, // Throttled { "BBA_WASTED", "WASTED.SFX" }, // Wasted { "BBA_BODYBAG", "VO10.SFX" }, // Body bagged { "BBA_HOSED", "VO25.SFX" }, // Hosed { "BBA_TOAST", "VO27.SFX" }, // Toasted { "BBA_HELL", "VO28.SFX" }, // Sent to hell { "BBA_SPRAYED", "VO35.SFX" }, // Sprayed { "BBA_DOGMEAT", "VO36.SFX" }, // Dog meat { "BBA_BEATEN", "VO39.SFX" }, // Beaten like a cur { "BBA_SNUFF", "VO41.SFX" }, // Snuffed { "BBA_CASTRA", "CASTRA.SFX" }, // Castrated }; static const char *GoodJobSounds[] = { "VO22.SFX", // Fine work "VO23.SFX", // Well done "VO44.SFX", // Excellent }; static const char *TooBadSounds[] = { "VO17.SFX", // Go play Mario "VO18.SFX", // Need a tricycle? "VO37.SFX", // Bye bye now }; static const char *TelefragSounds[] = { "VO29.SFX", // Pass the jelly "VO34.SFX", // Spillage "VO40.SFX", // Whipped and creamed "VO42.SFX", // Spleen vented "VO43.SFX", // Vaporized "VO38.SFX", // Ripped him loose "VO14.SFX", // Shat upon }; #if 0 // Sounds I don't know what to do with "VO6.SFX", // Asshole "VO15.SFX", // Finish him "VO19.SFX", // Talented "VO20.SFX", // Good one "VO21.SFX", // Lunch meat "VO26.SFX", // Humiliated "VO30.SFX", // Punishment delivered "VO31.SFX", // Bobbit-ized "VO32.SFX", // Stiffed "VO33.SFX", // He shoots... He scores #endif static int LastAnnounceTime; static FRandom pr_bbannounce ("BBAnnounce"); // CODE -------------------------------------------------------------------- //========================================================================== // // DoVoiceAnnounce // //========================================================================== void DoVoiceAnnounce (const char *sound) { // Don't play announcements too close together if (LastAnnounceTime == 0 || LastAnnounceTime <= level.time-5) { LastAnnounceTime = level.time; S_Sound (CHAN_VOICE, sound, 1, ATTN_NONE); } } //========================================================================== // // AnnounceGameStart // // Called when a new map is entered. // //========================================================================== bool AnnounceGameStart () { LastAnnounceTime = 0; if (cl_bbannounce && deathmatch) { DoVoiceAnnounce (BeginSounds[pr_bbannounce() & 1]); } return false; } //========================================================================== // // AnnounceKill // // Called when somebody dies. // //========================================================================== bool AnnounceKill (AActor *killer, AActor *killee) { const char *killerName; const SoundAndString *choice; const char *message; int rannum = pr_bbannounce(); if (cl_bbannounce && deathmatch) { bool playSound = killee->CheckLocalView (consoleplayer); if (killer == NULL) { // The world killed the player if (killee->player->userinfo.GetGender() == GENDER_MALE) { // Only males have scrotums to separate choice = &WorldKillSounds[rannum % 3]; } else { choice = &WorldKillSounds[rannum & 1]; } killerName = NULL; } else if (killer == killee) { // The player killed self choice = &SuicideSounds[rannum & 3]; killerName = killer->player->userinfo.GetName(); } else { // Another player did the killing if (killee->player->userinfo.GetGender() == GENDER_MALE) { // Only males can be castrated choice = &KillSounds[rannum % countof(KillSounds)]; } else { choice = &KillSounds[rannum % (countof(KillSounds) - 1)]; } killerName = killer->player->userinfo.GetName(); // Blood only plays the announcement sound on the killer's // computer. I think it sounds neater to also hear it on // the killee's machine. playSound |= killer->CheckLocalView (consoleplayer); } message = GStrings(choice->Message); if (message != NULL) { char assembled[1024]; SexMessage (message, assembled, killee->player->userinfo.GetGender(), killee->player->userinfo.GetName(), killerName); Printf (PRINT_MEDIUM, "%s\n", assembled); } if (playSound) { DoVoiceAnnounce (choice->Sound); } return message != NULL; } return false; } //========================================================================== // // AnnounceTelefrag // // Called when somebody dies by telefragging. // //========================================================================== bool AnnounceTelefrag (AActor *killer, AActor *killee) { int rannum = pr_bbannounce(); if (cl_bbannounce && multiplayer) { const char *message = GStrings("OB_MPTELEFRAG"); if (message != NULL) { char assembled[1024]; SexMessage (message, assembled, killee->player->userinfo.GetGender(), killee->player->userinfo.GetName(), killer->player->userinfo.GetName()); Printf (PRINT_MEDIUM, "%s\n", assembled); } if (killee->CheckLocalView (consoleplayer) || killer->CheckLocalView (consoleplayer)) { DoVoiceAnnounce (TelefragSounds[rannum % 7]); } return message != NULL; } return false; } //========================================================================== // // AnnounceSpree // // Called when somebody is on a spree. // //========================================================================== bool AnnounceSpree (AActor *who) { return false; } //========================================================================== // // AnnounceSpreeLoss // // Called when somebody on a spree gets killed. // //========================================================================== bool AnnounceSpreeLoss (AActor *who) { if (cl_bbannounce) { if (who->CheckLocalView (consoleplayer)) { DoVoiceAnnounce (TooBadSounds[M_Random() % 3]); } } return false; } //========================================================================== // // AnnounceMultikill // // Called when somebody is quickly raking in kills. // //========================================================================== bool AnnounceMultikill (AActor *who) { if (cl_bbannounce) { if (who->CheckLocalView (consoleplayer)) { DoVoiceAnnounce (GoodJobSounds[M_Random() % 3]); } } return false; }
30.416216
78
0.543896
johny-c
915d64b41290a639c0c8a2e2ac5971ae28637546
4,787
inl
C++
sfml-extensions/Extensions/Vector4.inl
degski/SFML-Extensions
13236325da2e9bef2e24f7ad80ec78db6bf33879
[ "MIT" ]
null
null
null
sfml-extensions/Extensions/Vector4.inl
degski/SFML-Extensions
13236325da2e9bef2e24f7ad80ec78db6bf33879
[ "MIT" ]
null
null
null
sfml-extensions/Extensions/Vector4.inl
degski/SFML-Extensions
13236325da2e9bef2e24f7ad80ec78db6bf33879
[ "MIT" ]
null
null
null
//////////////////////////////////////////////////////////// // // SFML - Simple and Fast Multimedia Library // Copyright (C) 2007-2015 Laurent Gomila (laurent@sfml-dev.org) // // This software is provided 'as-is', without any express or implied warranty. // In no event will the authors be held liable for any damages arising from the use of this software. // // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it freely, // subject to the following restrictions: // // 1. The origin of this software must not be misrepresented; // you must not claim that you wrote the original software. // If you use this software in a product, an acknowledgment // in the product documentation would be appreciated but is not required. // // 2. Altered source versions must be plainly marked as such, // and must not be misrepresented as being the original software. // // 3. This notice may not be removed or altered from any source distribution. // //////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>::Vector4() : v0(0), v1(0), v2(0), v3(0) { } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>::Vector4(T V0, T V1, T V2, T V3) : v0(V0), v1(V1), v2(V2), v3(V3) { } //////////////////////////////////////////////////////////// template <typename T> template <typename U> inline Vector4<T>::Vector4(const Vector4<U>& vector) : v0(static_cast<T>(vector.v0)), v1(static_cast<T>(vector.v1)), v2(static_cast<T>(vector.v2)), v3(static_cast<T>(vector.v3)) { } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator -(const Vector4<T>& left) { return Vector4<T>(-left.v0, -left.v1, -left.v2, -left.v3); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>& operator +=(Vector4<T>& left, const Vector4<T>& right) { left.v0 += right.v0; left.v1 += right.v1; left.v2 += right.v2; left.v3 += right.v3; return left; } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>& operator -=(Vector4<T>& left, const Vector4<T>& right) { left.v0 -= right.v0; left.v1 -= right.v1; left.v2 -= right.v2; left.v3 -= right.v3; return left; } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator +(const Vector4<T>& left, const Vector4<T>& right) { return Vector4<T>(left.v0 + right.v0, left.v1 + right.v1, left.v2 + right.v2, left.v3 + right.v3); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator -(const Vector4<T>& left, const Vector4<T>& right) { return Vector4<T>(left.v0 - right.v0, left.v1 - right.v1, left.v2 - right.v2, left.v3 - right.v3); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator *(const Vector4<T>& left, T right) { return Vector4<T>(left.v0 * right, left.v1 * right, left.v2 * right, left.v3 * right); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator *(T left, const Vector4<T>& right) { return Vector4<T>(left * right.v0, left * right.v1, left * right.v2, left * right.v3); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>& operator *=(Vector4<T>& left, T right) { left.v0 *= right; left.v1 *= right; left.v2 *= right; left.v3 *= right; return left; } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T> operator /(const Vector4<T>& left, T right) { return Vector4<T>(left.v0 / right, left.v1 / right, left.v2 / right, left.v3 / right); } //////////////////////////////////////////////////////////// template <typename T> inline Vector4<T>& operator /=(Vector4<T>& left, T right) { left.v0 /= right; left.v1 /= right; left.v2 /= right; left.v3 /= right; return left; } //////////////////////////////////////////////////////////// template <typename T> inline bool operator ==(const Vector4<T>& left, const Vector4<T>& right) { return (left.v0 == right.v0) && (left.v1 == right.v1) && (left.v2 == right.v2) && (left.v3 == right.v3); } //////////////////////////////////////////////////////////// template <typename T> inline bool operator !=(const Vector4<T>& left, const Vector4<T>& right) { return (left.v0 != right.v0) && (left.v1 != right.v1) && (left.v2 != right.v2) && (left.v3 != right.v3); }
27.198864
108
0.519323
degski
915dfbbdfa9cf201235b06cd9444b624db01716e
1,342
cpp
C++
orca/gporca/libnaucrates/src/parser/CParseHandlerUtils.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
3
2017-12-10T16:41:21.000Z
2020-07-08T12:59:12.000Z
orca/gporca/libnaucrates/src/parser/CParseHandlerUtils.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
null
null
null
orca/gporca/libnaucrates/src/parser/CParseHandlerUtils.cpp
vitessedata/gpdb.4.3.99.x
9462aad5df1bf120a2a87456b1f9574712227da4
[ "PostgreSQL", "Apache-2.0" ]
4
2017-12-10T16:41:35.000Z
2020-11-28T12:20:30.000Z
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2012 EMC Corp. // // @filename: // CParseHandlerUtils.cpp // // @doc: // Implementation of the helper methods for parse handler // // // @owner: // // // @test: // // //--------------------------------------------------------------------------- #include "naucrates/dxl/parser/CParseHandlerUtils.h" #include "naucrates/statistics/IStatistics.h" using namespace gpos; using namespace gpdxl; using namespace gpnaucrates; //--------------------------------------------------------------------------- // @function: // CParseHandlerUtils::SetProperties // // @doc: // Parse and the set operator's costing and statistical properties // //--------------------------------------------------------------------------- void CParseHandlerUtils::SetProperties ( CDXLNode *pdxln, CParseHandlerProperties *pphProp ) { GPOS_ASSERT(NULL != pphProp->Pdxlprop()); // set physical properties CDXLPhysicalProperties *pdxlprop = pphProp->Pdxlprop(); pdxlprop->AddRef(); pdxln->SetProperties(pdxlprop); // set the statistical information CDXLStatsDerivedRelation *pdxlstatsderrel = pphProp->Pdxlstatsderrel(); if (NULL != pdxlstatsderrel) { pdxlstatsderrel->AddRef(); pdxlprop->SetStats(pdxlstatsderrel); } } // EOF
22.745763
77
0.555142
vitessedata
916030d8552b3ca9ddf2ed73c821f5b33bf96d22
3,261
cc
C++
src/limits/ThreadsLimitListener.cc
NieDzejkob/sio2jail
8589541cfe11c68ce5ef13eb30a488b09ad3a139
[ "MIT" ]
14
2018-06-19T19:54:22.000Z
2021-09-16T18:03:40.000Z
src/limits/ThreadsLimitListener.cc
NieDzejkob/sio2jail
8589541cfe11c68ce5ef13eb30a488b09ad3a139
[ "MIT" ]
16
2018-09-16T17:08:43.000Z
2022-01-19T15:43:41.000Z
src/limits/ThreadsLimitListener.cc
NieDzejkob/sio2jail
8589541cfe11c68ce5ef13eb30a488b09ad3a139
[ "MIT" ]
6
2018-09-15T20:56:06.000Z
2022-03-05T09:27:22.000Z
#include "ThreadsLimitListener.h" #include "common/WithErrnoCheck.h" #include "logger/Logger.h" #include "seccomp/SeccompRule.h" #include "seccomp/action/ActionAllow.h" #include "seccomp/action/ActionKill.h" #include "seccomp/filter/LibSeccompFilter.h" namespace s2j { namespace limits { ThreadsLimitListener::ThreadsLimitListener(int32_t threadsLimit) : threadsLimit_{threadsLimit} { TRACE(threadsLimit); syscallRules_.emplace_back( seccomp::SeccompRule("fork", seccomp::action::ActionKill{})); syscallRules_.emplace_back( seccomp::SeccompRule("vfork", seccomp::action::ActionKill{})); if (threadsLimit_ < 0) { // Disable threads support syscallRules_.emplace_back( seccomp::SeccompRule("clone", seccomp::action::ActionKill{})); } else { // Enable threads support using Arg = seccomp::filter::SyscallArg; syscallRules_.emplace_back(seccomp::SeccompRule( "clone", seccomp::action::ActionAllow{}, (Arg(2) & CLONE_VM) == CLONE_VM)); syscallRules_.emplace_back(seccomp::SeccompRule( "clone", seccomp::action::ActionKill(), (Arg(2) & CLONE_VM) == 0)); // And various thread related syscallRules_.emplace_back(seccomp::SeccompRule( // TODO: allow sleep up to time limit "nanosleep", seccomp::action::ActionAllow{})); } } std::tuple<tracer::TraceAction, tracer::TraceAction> ThreadsLimitListener::onPostClone( const tracer::TraceEvent& traceEvent, tracer::Tracee& tracee, tracer::Tracee& traceeChild) { TRACE(tracee.getPid(), traceeChild.getPid()); if (threadsLimit_ < 0) { outputBuilder_->setKillReason( printer::OutputBuilder::KillReason::RV, "Threads are not allowed"); return {tracer::TraceAction::KILL, tracer::TraceAction::KILL}; } threadsPids_.insert(traceeChild.getPid()); logger::debug( "Thread ", traceeChild.getPid(), " started, new thread count ", threadsPids_.size()); if (threadsPids_.size() > static_cast<uint32_t>(threadsLimit_)) { outputBuilder_->setKillReason( printer::OutputBuilder::KillReason::RV, "threads limit exceeded"); logger::info( "Threads limit ", threadsLimit_, " exceeded, killing tracee"); return {tracer::TraceAction::KILL, tracer::TraceAction::KILL}; } return {tracer::TraceAction::CONTINUE, tracer::TraceAction::CONTINUE}; } executor::ExecuteAction ThreadsLimitListener::onExecuteEvent( const executor::ExecuteEvent& executeEvent) { TRACE(executeEvent.pid); if (threadsLimit_ < 0) return executor::ExecuteAction::CONTINUE; if (executeEvent.exited || executeEvent.killed) { threadsPids_.erase(executeEvent.pid); logger::debug( "Thread ", executeEvent.pid, " exited, new threads count ", threadsPids_.size()); } return executor::ExecuteAction::CONTINUE; } } // namespace limits } // namespace s2j
33.618557
78
0.618522
NieDzejkob
9160e358a516a4aab8384bdc37461f8af33bc3f7
542
cc
C++
cses/1084.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
506
2018-08-22T10:30:38.000Z
2022-03-31T10:01:49.000Z
cses/1084.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
13
2019-08-07T18:31:18.000Z
2020-12-15T21:54:41.000Z
cses/1084.cc
Ashindustry007/competitive-programming
2eabd3975c029d235abb7854569593d334acae2f
[ "WTFPL" ]
234
2018-08-06T17:11:41.000Z
2022-03-26T10:56:42.000Z
// https://cses.fi/problemset/task/1084/ #include <algorithm> #include <iostream> #include <vector> using namespace std; typedef vector<int> vi; int main() { int n, m, k; cin >> n >> m >> k; vi a(m); for (int i = 0; i < n; i++) cin >> a[i]; vi b(m); for (int i = 0; i < m; i++) cin >> b[i]; sort(a.begin(), a.end()); sort(b.begin(), b.end()); int i = 0; int j = 0; int c = 0; while (i < n && j < m) if (a[i] + k < b[j]) i++; else if (a[i] - k > b[j]) j++; else { i++; j++; c++; } cout << c << endl; }
19.357143
42
0.47048
Ashindustry007
91649df8e531bea4f0405ea8f7ceb37726ca7518
3,041
cpp
C++
deps/libgeos/geos/src/precision/PrecisionReducerCoordinateOperation.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
57
2020-02-08T17:52:17.000Z
2021-10-14T03:45:09.000Z
deps/libgeos/geos/src/precision/PrecisionReducerCoordinateOperation.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
47
2020-02-12T16:41:40.000Z
2021-09-28T22:27:56.000Z
deps/libgeos/geos/src/precision/PrecisionReducerCoordinateOperation.cpp
AmristarSolutions/node-gdal-next
8c0a7d9b26c240bf04abbf1b1de312b0691b3d88
[ "Apache-2.0" ]
8
2020-03-17T11:18:07.000Z
2021-10-14T03:45:15.000Z
/********************************************************************** * * GEOS - Geometry Engine Open Source * http://geos.osgeo.org * * Copyright (C) 2012 Sandro Santilli <strk@kbt.io> * * This is free software; you can redistribute and/or modify it under * the terms of the GNU Lesser General Public Licence as published * by the Free Software Foundation. * See the COPYING file for more information. * *********************************************************************** * * Last port: precision/PrecisionreducerCoordinateOperation.java r591 (JTS-1.12) * **********************************************************************/ #include <geos/precision/PrecisionReducerCoordinateOperation.h> #include <geos/geom/PrecisionModel.h> #include <geos/geom/CoordinateSequenceFactory.h> #include <geos/geom/CoordinateSequence.h> #include <geos/geom/GeometryFactory.h> #include <geos/geom/Geometry.h> #include <geos/geom/LineString.h> #include <geos/geom/LinearRing.h> #include <geos/operation/valid/RepeatedPointRemover.h> #include <geos/util.h> #include <vector> using namespace geos::geom; namespace geos { namespace precision { // geos.precision std::unique_ptr<CoordinateSequence> PrecisionReducerCoordinateOperation::edit(const CoordinateSequence* cs, const Geometry* geom) { auto csSize = cs->size(); if(csSize == 0) { return nullptr; } auto vc = detail::make_unique<std::vector<Coordinate>>(csSize); // copy coordinates and reduce for(size_t i = 0; i < csSize; ++i) { (*vc)[i] = cs->getAt(i); targetPM.makePrecise((*vc)[i]); } // reducedCoords take ownership of 'vc' auto reducedCoords = geom->getFactory()->getCoordinateSequenceFactory()->create(vc.release()); // remove repeated points, to simplify returned geometry as // much as possible. std::unique_ptr<CoordinateSequence> noRepeatedCoords = operation::valid::RepeatedPointRemover::removeRepeatedPoints(reducedCoords.get()); /** * Check to see if the removal of repeated points * collapsed the coordinate List to an invalid length * for the type of the parent geometry. * It is not necessary to check for Point collapses, * since the coordinate list can * never collapse to less than one point. * If the length is invalid, return the full-length coordinate array * first computed, or null if collapses are being removed. * (This may create an invalid geometry - the client must handle this.) */ unsigned int minLength = 0; if(dynamic_cast<const LineString*>(geom)) { minLength = 2; } if(dynamic_cast<const LinearRing*>(geom)) { minLength = 4; } if(removeCollapsed) { reducedCoords = nullptr; } // return null or original length coordinate array if(noRepeatedCoords->getSize() < minLength) { return reducedCoords; } // ok to return shorter coordinate array return noRepeatedCoords; } } // namespace geos.precision } // namespace geos
31.350515
141
0.646827
AmristarSolutions
91661ff93084dfcdfae9cede333776a2c2fc720e
20,677
hpp
C++
include/xtensor/xblockwise_reducer.hpp
DavisVaughan/xtensor
fe81957365ce7eb56ea417bea95476c1344d7c31
[ "BSD-3-Clause" ]
1,592
2016-11-03T09:30:00.000Z
2019-10-12T16:40:06.000Z
include/xtensor/xblockwise_reducer.hpp
DavisVaughan/xtensor
fe81957365ce7eb56ea417bea95476c1344d7c31
[ "BSD-3-Clause" ]
1,133
2016-11-05T09:16:11.000Z
2019-10-13T12:19:10.000Z
include/xtensor/xblockwise_reducer.hpp
DavisVaughan/xtensor
fe81957365ce7eb56ea417bea95476c1344d7c31
[ "BSD-3-Clause" ]
238
2016-11-03T09:27:29.000Z
2019-10-08T17:05:27.000Z
#ifndef XTENSOR_XBLOCKWISE_REDUCER_HPP #define XTENSOR_XBLOCKWISE_REDUCER_HPP #include "xtl/xclosure.hpp" #include "xtl/xsequence.hpp" #include "xshape.hpp" #include "xblockwise_reducer_functors.hpp" #include "xmultiindex_iterator.hpp" #include "xreducer.hpp" namespace xt { template<class CT, class F, class X, class O> class xblockwise_reducer { public: using self_type = xblockwise_reducer<CT, F, X, O>; using raw_options_type = std::decay_t<O>; using keep_dims = xtl::mpl::contains<raw_options_type, xt::keep_dims_type>; using xexpression_type = std::decay_t<CT>; using shape_type = typename xreducer_shape_type<typename xexpression_type::shape_type, std::decay_t<X>, keep_dims>::type; using functor_type = F; using value_type = typename functor_type::value_type; using input_shape_type = typename xexpression_type::shape_type; using input_chunk_index_type = filter_fixed_shape_t<input_shape_type>; using input_grid_strides = filter_fixed_shape_t<input_shape_type>; using axes_type = X; using chunk_shape_type = filter_fixed_shape_t<shape_type>; template<class E, class BS, class XX, class OO, class FF> xblockwise_reducer(E && e, BS && block_shape, XX && axes, OO && options, FF && functor); const input_shape_type & input_shape()const; const axes_type & axes() const; std::size_t dimension() const; const shape_type & shape() const; const chunk_shape_type & chunk_shape() const; template<class R> void assign_to(R & result) const; private: using mapping_type = filter_fixed_shape_t<shape_type>; using input_chunked_view_type = xchunked_view<const std::decay_t<CT> &>; using input_const_chunked_iterator_type = typename input_chunked_view_type::const_chunk_iterator; using input_chunk_range_type = std::array<xmultiindex_iterator<input_chunk_index_type>, 2>; template<class CI> void assign_to_chunk(CI & result_chunk_iter) const; template<class CI> input_chunk_range_type compute_input_chunk_range(CI & result_chunk_iter) const; input_const_chunked_iterator_type get_input_chunk_iter(input_chunk_index_type input_chunk_index) const; void init_shapes(); CT m_e; xchunked_view<const std::decay_t<CT> &> m_e_chunked_view; axes_type m_axes; raw_options_type m_options; functor_type m_functor; shape_type m_result_shape; chunk_shape_type m_result_chunk_shape; mapping_type m_mapping; input_grid_strides m_input_grid_strides; }; template<class CT, class F, class X, class O> template<class E, class BS, class XX, class OO, class FF> xblockwise_reducer<CT, F, X, O>::xblockwise_reducer(E && e, BS && block_shape, XX && axes, OO && options, FF && functor) : m_e(std::forward<E>(e)), m_e_chunked_view(m_e, std::forward<BS>(block_shape)), m_axes(std::forward<XX>(axes)), m_options(std::forward<OO>(options)), m_functor(std::forward<FF>(functor)), m_result_shape(), m_result_chunk_shape(), m_mapping(), m_input_grid_strides() { init_shapes(); resize_container(m_input_grid_strides, m_e.dimension()); std::size_t stride = 1; for (std::size_t i = m_input_grid_strides.size(); i != 0; --i) { m_input_grid_strides[i-1] = stride; stride *= m_e_chunked_view.grid_shape()[i - 1]; } } template<class CT, class F, class X, class O> inline auto xblockwise_reducer<CT, F, X, O>::input_shape()const -> const input_shape_type & { return m_e.shape(); } template<class CT, class F, class X, class O> inline auto xblockwise_reducer<CT, F, X, O>::axes() const -> const axes_type & { return m_axes; } template<class CT, class F, class X, class O> inline std::size_t xblockwise_reducer<CT, F, X, O>::dimension() const { return m_result_shape.size(); } template<class CT, class F, class X, class O> inline auto xblockwise_reducer<CT, F, X, O>::shape() const -> const shape_type & { return m_result_shape; } template<class CT, class F, class X, class O> inline auto xblockwise_reducer<CT, F, X, O>::chunk_shape() const -> const chunk_shape_type & { return m_result_chunk_shape; } template<class CT, class F, class X, class O> template<class R> inline void xblockwise_reducer<CT, F, X, O>::assign_to(R & result) const { auto result_chunked_view = as_chunked(result, m_result_chunk_shape); for(auto chunk_iter = result_chunked_view.chunk_begin(); chunk_iter != result_chunked_view.chunk_end(); ++chunk_iter) { assign_to_chunk(chunk_iter); } } template<class CT, class F, class X, class O> auto xblockwise_reducer<CT, F, X, O>::get_input_chunk_iter(input_chunk_index_type input_chunk_index) const ->input_const_chunked_iterator_type { std::size_t chunk_linear_index = 0; for(std::size_t i=0; i<m_e_chunked_view.dimension(); ++i) { chunk_linear_index += input_chunk_index[i] * m_input_grid_strides[i]; } return input_const_chunked_iterator_type(m_e_chunked_view, std::move(input_chunk_index), chunk_linear_index); } template<class CT, class F, class X, class O> template<class CI> void xblockwise_reducer<CT, F, X, O>::assign_to_chunk(CI & result_chunk_iter) const { auto result_chunk_view = *result_chunk_iter; auto reduction_variable = m_functor.reduction_variable(result_chunk_view); // get the range of input chunks we need to compute the desired ouput chunk auto range = compute_input_chunk_range(result_chunk_iter); // iterate over input chunk (indics) auto first = true; // std::for_each(std::get<0>(range), std::get<1>(range), [&](auto && input_chunk_index) auto iter = std::get<0>(range); while(iter != std::get<1>(range)) { const auto & input_chunk_index = *iter; // get input chunk iterator from chunk index auto chunked_input_iter = this->get_input_chunk_iter(input_chunk_index); auto input_chunk_view = *chunked_input_iter; // compute the per block result auto block_res = m_functor.compute(input_chunk_view, m_axes, m_options); // merge m_functor.merge(block_res, first, result_chunk_view, reduction_variable); first = false; ++iter; } // finalize (ie smth like normalization) m_functor.finalize(reduction_variable, result_chunk_view, *this); } template<class CT, class F, class X, class O> template<class CI> auto xblockwise_reducer<CT, F, X, O>::compute_input_chunk_range(CI & result_chunk_iter) const -> input_chunk_range_type { auto input_chunks_begin = xtl::make_sequence<input_chunk_index_type>(m_e_chunked_view.dimension(), 0); auto input_chunks_end = xtl::make_sequence<input_chunk_index_type>(m_e_chunked_view.dimension()); XTENSOR_ASSERT(input_chunks_begin.size() == m_e_chunked_view.dimension()); XTENSOR_ASSERT(input_chunks_end.size() == m_e_chunked_view.dimension()); std::copy(m_e_chunked_view.grid_shape().begin(), m_e_chunked_view.grid_shape().end(), input_chunks_end.begin()); const auto & chunk_index = result_chunk_iter.chunk_index(); for(std::size_t result_ax_index=0; result_ax_index<m_result_shape.size(); ++result_ax_index) { if(m_result_shape[result_ax_index] != 1) { const auto input_ax_index = m_mapping[result_ax_index]; input_chunks_begin[input_ax_index] = chunk_index[result_ax_index]; input_chunks_end[input_ax_index] = chunk_index[result_ax_index] + 1; } } return input_chunk_range_type{ multiindex_iterator_begin<input_chunk_index_type>(input_chunks_begin, input_chunks_end), multiindex_iterator_end<input_chunk_index_type>(input_chunks_begin, input_chunks_end) }; } template<class CT, class F, class X, class O> void xblockwise_reducer<CT, F, X, O>::init_shapes() { const auto & shape = m_e.shape(); const auto dimension = m_e.dimension(); const auto & block_shape = m_e_chunked_view.chunk_shape(); if (xtl::mpl::contains<raw_options_type, xt::keep_dims_type>::value) { resize_container(m_result_shape, dimension); resize_container(m_result_chunk_shape, dimension); resize_container(m_mapping, dimension); for (std::size_t i = 0; i < dimension; ++i) { m_mapping[i] = i; if (std::find(m_axes.begin(), m_axes.end(), i) == m_axes.end()) { // i not in m_axes! m_result_shape[i] = shape[i]; m_result_chunk_shape[i] = block_shape[i]; } else { m_result_shape[i] = 1; m_result_chunk_shape[i] = 1; } } } else { const auto result_dim = dimension - m_axes.size(); resize_container(m_result_shape, result_dim); resize_container(m_result_chunk_shape, result_dim); resize_container(m_mapping, result_dim); for (std::size_t i = 0, idx = 0; i < dimension; ++i) { if (std::find(m_axes.begin(), m_axes.end(), i) == m_axes.end()) { // i not in axes! m_result_shape[idx] = shape[i]; m_result_chunk_shape[idx] = block_shape[i]; m_mapping[idx] = i; ++idx; } } } } template<class E, class CS, class A, class O, class FF> inline auto blockwise_reducer(E && e, CS && chunk_shape, A && axes, O && raw_options, FF && functor) { using functor_type = std::decay_t<FF>; using closure_type = xtl::const_closure_type_t<E>; using axes_type = std::decay_t<A>; return xblockwise_reducer< closure_type, functor_type, axes_type, O >( std::forward<E>(e), std::forward<CS>(chunk_shape), std::forward<A>(axes), std::forward<O>(raw_options), std::forward<FF>(functor) ); } namespace blockwise { #define XTENSOR_BLOCKWISE_REDUCER_FUNC(FNAME, FUNCTOR)\ template<class T=void, class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\ >\ auto FNAME(E && e, BS && block_shape, X && axes, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::forward<X>(axes),\ std::forward<O>(options),\ functor_type());\ }\ template<class T=void, class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\ >\ auto FNAME(E && e, BS && block_shape, X axis, O options = O())\ {\ std::array<X,1> axes{axis};\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ axes,\ std::forward<O>(options),\ functor_type());\ }\ template<class T=void, class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\ >\ auto FNAME(E && e, BS && block_shape, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\ axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\ XTENSOR_ASSERT(axes.size() == e.dimension());\ std::iota(axes.begin(), axes.end(), 0);\ using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(axes),\ std::forward<O>(options),\ functor_type());\ }\ template<class T=void, class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\ auto FNAME(E && e, BS && block_shape, const I (&axes)[N], O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type, T>;\ using axes_type = std::array<std::size_t, N>;\ auto ax = xt::forward_normalize<axes_type>(e, axes);\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(ax),\ std::forward<O>(options),\ functor_type());\ } XTENSOR_BLOCKWISE_REDUCER_FUNC(sum, xt::detail::blockwise::sum_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(prod, xt::detail::blockwise::prod_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(amin, xt::detail::blockwise::amin_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(amax, xt::detail::blockwise::amax_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(mean, xt::detail::blockwise::mean_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(variance, xt::detail::blockwise::variance_functor) XTENSOR_BLOCKWISE_REDUCER_FUNC(stddev, xt::detail::blockwise::stddev_functor) #undef XTENSOR_BLOCKWISE_REDUCER_FUNC // norm reducers do *not* allow to to pass a template // parameter to specifiy the internal computation type #define XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(FNAME, FUNCTOR)\ template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\ >\ auto FNAME(E && e, BS && block_shape, X && axes, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::forward<X>(axes),\ std::forward<O>(options),\ functor_type());\ }\ template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\ >\ auto FNAME(E && e, BS && block_shape, X axis, O options = O())\ {\ std::array<X,1> axes{axis};\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ axes,\ std::forward<O>(options),\ functor_type());\ }\ template<class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\ >\ auto FNAME(E && e, BS && block_shape, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\ axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\ XTENSOR_ASSERT(axes.size() == e.dimension());\ std::iota(axes.begin(), axes.end(), 0);\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(axes),\ std::forward<O>(options),\ functor_type());\ }\ template<class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\ auto FNAME(E && e, BS && block_shape, const I (&axes)[N], O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ using axes_type = std::array<std::size_t, N>;\ auto ax = xt::forward_normalize<axes_type>(e, axes);\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(ax),\ std::forward<O>(options),\ functor_type());\ } XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l0, xt::detail::blockwise::norm_l0_functor) XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l1, xt::detail::blockwise::norm_l1_functor) XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_l2, xt::detail::blockwise::norm_l2_functor) XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_sq, xt::detail::blockwise::norm_sq_functor) XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_linf, xt::detail::blockwise::norm_linf_functor) #undef XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC #define XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(FNAME, FUNCTOR)\ template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::negation<is_reducer_options<X>>, xtl::negation<xtl::is_integral<std::decay_t<X>>>)\ >\ auto FNAME(E && e, BS && block_shape, double p, X && axes, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::forward<X>(axes),\ std::forward<O>(options),\ functor_type(p));\ }\ template<class E, class BS, class X, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(xtl::is_integral<std::decay_t<X>>)\ >\ auto FNAME(E && e, BS && block_shape, double p, X axis, O options = O())\ {\ std::array<X,1> axes{axis};\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ axes,\ std::forward<O>(options),\ functor_type(p));\ }\ template<class E, class BS, class O = DEFAULT_STRATEGY_REDUCERS,\ XTL_REQUIRES(is_reducer_options<O>, xtl::negation<xtl::is_integral<std::decay_t<O>>>)\ >\ auto FNAME(E && e, BS && block_shape, double p, O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using axes_type = filter_fixed_shape_t<typename input_expression_type::shape_type>;\ axes_type axes = xtl::make_sequence<axes_type>(e.dimension());\ XTENSOR_ASSERT(axes.size() == e.dimension());\ std::iota(axes.begin(), axes.end(), 0);\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(axes),\ std::forward<O>(options),\ functor_type(p));\ }\ template<class E, class BS, class I, std::size_t N, class O = DEFAULT_STRATEGY_REDUCERS>\ auto FNAME(E && e, BS && block_shape, double p, const I (&axes)[N], O options = O())\ {\ using input_expression_type = std::decay_t<E>;\ using functor_type = FUNCTOR <typename input_expression_type::value_type>;\ using axes_type = std::array<std::size_t, N>;\ auto ax = xt::forward_normalize<axes_type>(e, axes);\ return blockwise_reducer(\ std::forward<E>(e), \ std::forward<BS>(block_shape), \ std::move(ax),\ std::forward<O>(options),\ functor_type(p));\ } XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_lp_to_p, xt::detail::blockwise::norm_lp_to_p_functor); XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC(norm_lp, xt::detail::blockwise::norm_lp_functor); #undef XTENSOR_BLOCKWISE_NORM_REDUCER_FUNC } } #endif
41.025794
143
0.632877
DavisVaughan
9168643a5f8ec02fc865ff9fa16ef7cf29c61ce9
308
cpp
C++
Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
4
2020-06-11T00:35:03.000Z
2020-06-23T11:57:52.000Z
Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
1
2020-03-17T13:34:16.000Z
2020-03-17T13:34:16.000Z
Ruken/Source/Src/Vulkan/Resources/TextureLoadingDescriptor.cpp
Renondedju/Daemon
8cdfcbc62d7e9dc6c6121ec1484555a23a20b8b6
[ "MIT" ]
2
2020-03-19T12:20:17.000Z
2020-09-03T07:49:06.000Z
 #include "Vulkan/Resources/TextureLoadingDescriptor.hpp" USING_RUKEN_NAMESPACE #pragma region Constructor TextureLoadingDescriptor::TextureLoadingDescriptor(Renderer const& in_renderer, RkChar const* in_path) noexcept: renderer {in_renderer}, path {in_path} { } #pragma endregion
20.533333
112
0.766234
Renondedju
9168dd9019c6a142e4da3d36e2c18e93877a61b0
1,126
cpp
C++
545_c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
545_c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
545_c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair typedef long long ll; typedef pair<int,int> pii; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; int n; long long x[100007], h[100007]; long long last=-1000000007; int wyn; int main() { ios::sync_with_stdio(0); cin.tie(0); cout.tie(0); #ifndef ONLINE_JUDGE freopen("inputf.in","r",stdin); freopen("outputf.in","w",stdout); #endif scanf("%d", &n); for (int i=1; i<=n; i++) { scanf("%lld%lld", &x[i], &h[i]); } for (int i=1; i<n; i++) { if (x[i]-h[i]>last) { wyn++; last=x[i]; continue; } if (x[i]+h[i]<x[i+1]) { wyn++; last=x[i]+h[i]; continue; } last=x[i]; } wyn++; printf("%d", wyn); return 0; }
20.851852
106
0.515986
onexmaster
916929982c9ff5be579031316759797cb0e54995
1,505
cpp
C++
DQMOffline/Trigger/test/EgHLTComCodes_catch2_test.cpp
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
DQMOffline/Trigger/test/EgHLTComCodes_catch2_test.cpp
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
DQMOffline/Trigger/test/EgHLTComCodes_catch2_test.cpp
bisnupriyasahu/cmssw
6cf37ca459246525be0e8a6f5172c6123637d259
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "catch.hpp" #include "DQMOffline/Trigger/interface/EgHLTComCodes.h" #include "DQMOffline/Trigger/interface/EgHLTEgCutCodes.h" TEST_CASE("EgHLTComCodes", "[EgHLTComCodes]") { egHLT::ComCodes codes; constexpr unsigned int kFoo = 0b1; constexpr unsigned int kBar = 0b10; constexpr unsigned int kIsh = 0b100; constexpr unsigned int kTar = 0b1000; constexpr unsigned int kash = 0b10000; codes.setCode("Foo",kFoo); codes.setCode("Bar",kBar); codes.setCode("Ish",kIsh); codes.setCode("Tar",kTar); codes.setCode("ash",kash); codes.sort(); SECTION("Sorted") { REQUIRE(codes.getCode("ash") == kash); REQUIRE(codes.getCode("Bar") == kBar); REQUIRE(codes.getCode("Foo") == kFoo); REQUIRE(codes.getCode("Ish") == kIsh); REQUIRE(codes.getCode("Tar") == kTar); } SECTION("Select multiple") { REQUIRE(codes.getCode("ash:Ish") == (kash|kIsh)); REQUIRE(codes.getCode("Bar:Foo:Tar") == (kBar|kFoo|kTar)); REQUIRE(codes.getCode("Tar:Foo:Bar") == (kTar|kFoo|kBar)); } SECTION("Missing") { REQUIRE(codes.getCode("BAD") == 0); REQUIRE(codes.getCode("Tar:BAD:Bar") == (kTar|kBar)); //no partial match REQUIRE(codes.getCode("as") == 0); REQUIRE(codes.getCode("ashton")==0); } } TEST_CASE("EgHLTCutCodes", "[EgHLTCutCodes]") { SECTION("get good codes") { REQUIRE(egHLT::EgCutCodes::getCode("et") == egHLT::EgCutCodes::ET ); REQUIRE(egHLT::EgCutCodes::getCode("maxr9") == egHLT::EgCutCodes::MAXR9 ); } }
27.87037
78
0.651827
bisnupriyasahu
9169b0ae10ff6728f0719cc9e43777139decf96d
196
cpp
C++
AnvilEldorado/Source/Blam/Data/LruvCacheBase.cpp
MasterScott/AnvilClient
9b7751d9583d7221fd9c9f1b864f27e7ff9fcf79
[ "MIT" ]
57
2016-01-17T16:13:59.000Z
2020-07-17T05:39:33.000Z
AnvilEldorado/Source/Blam/Data/LruvCacheBase.cpp
MasterScott/AnvilClient
9b7751d9583d7221fd9c9f1b864f27e7ff9fcf79
[ "MIT" ]
24
2016-02-05T01:03:30.000Z
2020-12-08T18:44:33.000Z
AnvilEldorado/Source/Blam/Data/LruvCacheBase.cpp
MasterScott/AnvilClient
9b7751d9583d7221fd9c9f1b864f27e7ff9fcf79
[ "MIT" ]
23
2015-12-29T23:33:15.000Z
2019-10-21T22:45:27.000Z
#include "LruvCacheBase.hpp" using namespace Blam::Data; LruvCacheBase::LruvCacheBase() : Unknown32(nullptr), Unknown36(nullptr), Unknown40(nullptr), Unknown44(nullptr), Allocator(nullptr) { }
21.777778
101
0.770408
MasterScott
916a408dc7ee44d6ec5f38196509d6e12f13c902
2,188
cc
C++
hw2/framebuffer.cc
chrismorgan-hb/usc-cs480
d4f22e4b8f3643ce8241abc996ede10fdea43658
[ "Apache-2.0" ]
null
null
null
hw2/framebuffer.cc
chrismorgan-hb/usc-cs480
d4f22e4b8f3643ce8241abc996ede10fdea43658
[ "Apache-2.0" ]
null
null
null
hw2/framebuffer.cc
chrismorgan-hb/usc-cs480
d4f22e4b8f3643ce8241abc996ede10fdea43658
[ "Apache-2.0" ]
null
null
null
// framebuffer.cc // class implementation for Framebuffer // Author: Christopher Morgan // CSCI 480 Sp2004 #include "framebuffer.h" #include "utility.h" #include <iostream> #include <fstream> using namespace std; #include <limits.h> //constructor //framebuffer must be created with width and height Framebuffer::Framebuffer(int w, int h) { width = w; height = h; buffer = new int* [w]; colors = new RGBColor* [w]; zBuffer = new float* [w]; for(int k = 0; k < w; k++) { buffer[k] = new int[h]; colors[k] = new RGBColor[h]; zBuffer[k] = new float[h]; } //set all pixels to black initially RGBColor black(0,0,0); for(int i = 0; i < w; i++) for(int j = 0; j < h; j++) { buffer[i][j] = 0; colors[i][j] = black; zBuffer[i][j] = -1; } } Framebuffer::~Framebuffer() { for(int i = 0; i < width; i++) delete buffer[i]; delete [] buffer; } int Framebuffer::getWidth() { return width; } int Framebuffer::getHeight() { return height; } //fillPixel //uses zBuffering to determine if pixel is on top //if so, fills with color c //otherwise, does nothing void Framebuffer::fillPixel(int x, int y, float z, RGBColor c) { if(x < 0 || x > width) return; else if(y < 0 || y > height) return; else { if(z < zBuffer[x][y] || zBuffer[x][y] == -1) { colors[x][y] = c; zBuffer[x][y] = z; } } } // writeOut // write the framebuffer to a file <image.ppm> void Framebuffer::writeOut() { ofstream outFile("image.ppm", ios::out); // make sure the file opened if(!outFile) { cout << "Error, could not create output file... aborting." << endl; exit(-1); } // header information outFile << "P6" << endl << width << " " << height << endl << "255" << endl; char r, g, b; for(int i = 0; i < height; i++) { for(int j = 0; j < width; j++) { // get rgb values from colors array and // cast to char for P6 r = (char)(colors[j][height - i - 1]).getR(); g = (char)(colors[j][height - i - 1]).getG(); b = (char)(colors[j][height - i - 1]).getB(); // write rgb to file outFile << r; outFile << g; outFile << b; } } }
19.535714
77
0.568099
chrismorgan-hb
916b055dad09ff569d36ae770d7a317bb59ce520
2,320
cpp
C++
Source/Core/AS_SFML/Joystick.cpp
ace13/LD34
82ecda6bdd69208be1ec6d03c3eb250313c4b7d1
[ "MIT" ]
1
2017-01-05T01:55:16.000Z
2017-01-05T01:55:16.000Z
Source/Core/AS_SFML/Joystick.cpp
ace13/AngelscriptMP
583d481fdbef75e4d96a45eb2942a21189087c77
[ "MIT" ]
null
null
null
Source/Core/AS_SFML/Joystick.cpp
ace13/AngelscriptMP
583d481fdbef75e4d96a45eb2942a21189087c77
[ "MIT" ]
null
null
null
#include "Shared.hpp" #include <SFML/Window/Joystick.hpp> namespace { enum Stick { Left = 0, Right, Pov }; void getStickPosition(asIScriptGeneric* gen) { uint32_t id = gen->GetArgDWord(0); Stick stick = Stick(gen->GetArgDWord(1)); switch (stick) { case Left: new (gen->GetAddressOfReturnLocation()) sf::Vector2f( sf::Joystick::getAxisPosition(id, sf::Joystick::X), sf::Joystick::getAxisPosition(id, sf::Joystick::Y) ); break; case Right: new (gen->GetAddressOfReturnLocation()) sf::Vector2f( sf::Joystick::getAxisPosition(id, sf::Joystick::R), sf::Joystick::getAxisPosition(id, sf::Joystick::U) ); break; case Pov: new (gen->GetAddressOfReturnLocation()) sf::Vector2f( sf::Joystick::getAxisPosition(id, sf::Joystick::PovX), sf::Joystick::getAxisPosition(id, sf::Joystick::PovY) ); break; } } } void as::priv::RegJoystick(asIScriptEngine* eng) { AS_ASSERT(eng->SetDefaultNamespace("sf::Joystick")); AS_ASSERT(eng->RegisterEnum("Axis")); AS_ASSERT(eng->RegisterEnumValue ("Axis", "X", sf::Joystick::X)); AS_ASSERT(eng->RegisterEnumValue("Axis", "Y", sf::Joystick::Y)); AS_ASSERT(eng->RegisterEnumValue("Axis", "Z", sf::Joystick::Z)); AS_ASSERT(eng->RegisterEnumValue("Axis", "RX", sf::Joystick::R)); AS_ASSERT(eng->RegisterEnumValue("Axis", "RY", sf::Joystick::U)); AS_ASSERT(eng->RegisterEnumValue("Axis", "RZ", sf::Joystick::V)); AS_ASSERT(eng->RegisterEnumValue("Axis", "PovX", sf::Joystick::PovX)); AS_ASSERT(eng->RegisterEnumValue("Axis", "PovY", sf::Joystick::PovY)); AS_ASSERT(eng->RegisterEnum("Stick")); AS_ASSERT(eng->RegisterEnumValue("Stick", "Left", 0)); AS_ASSERT(eng->RegisterEnumValue("Stick", "Right", 1)); AS_ASSERT(eng->RegisterEnumValue("Stick", "Pov", 2)); AS_ASSERT(eng->RegisterGlobalFunction("bool IsConnected(uint)", asFUNCTION(sf::Joystick::isConnected), asCALL_CDECL)); AS_ASSERT(eng->RegisterGlobalFunction("bool IsPressed(uint,uint)", asFUNCTION(sf::Joystick::isButtonPressed), asCALL_CDECL)); AS_ASSERT(eng->RegisterGlobalFunction("float AxisPosition(uint,Axis)", asFUNCTION(sf::Joystick::getAxisPosition), asCALL_CDECL)); AS_ASSERT(eng->RegisterGlobalFunction("Vec2 StickPosition(uint,Stick=Left)", asFUNCTION(getStickPosition), asCALL_GENERIC)); AS_ASSERT(eng->SetDefaultNamespace("")); }
35.151515
130
0.709914
ace13
9170c9869e819713d8036fa207df18ea7f74be52
1,365
cpp
C++
aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ssm-contacts/source/model/ListContactChannelsResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ssm-contacts/model/ListContactChannelsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::SSMContacts::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListContactChannelsResult::ListContactChannelsResult() { } ListContactChannelsResult::ListContactChannelsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListContactChannelsResult& ListContactChannelsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } if(jsonValue.ValueExists("ContactChannels")) { Array<JsonView> contactChannelsJsonList = jsonValue.GetArray("ContactChannels"); for(unsigned contactChannelsIndex = 0; contactChannelsIndex < contactChannelsJsonList.GetLength(); ++contactChannelsIndex) { m_contactChannels.push_back(contactChannelsJsonList[contactChannelsIndex].AsObject()); } } return *this; }
27.3
126
0.768498
perfectrecall
91745dfbe3cff1a6b168029fae6e5609d6362c72
527
cpp
C++
src/common/expression/VertexExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-04-11T12:12:39.000Z
2020-04-11T12:12:39.000Z
src/common/expression/VertexExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
24
2021-09-15T12:42:03.000Z
2021-09-16T04:59:19.000Z
src/common/expression/VertexExpression.cpp
blacklovebear/nebula
f500d478ac53b7c7977da305ca1ed07f8e44376a
[ "Apache-2.0" ]
1
2020-08-03T10:19:39.000Z
2020-08-03T10:19:39.000Z
/* Copyright (c) 2020 vesoft inc. All rights reserved. * * This source code is licensed under Apache 2.0 License, * attached with Common Clause Condition 1.0, found in the LICENSES directory. */ #include "common/expression/VertexExpression.h" #include "common/expression/ExprVisitor.h" namespace nebula { const Value &VertexExpression::eval(ExpressionContext &ctx) { result_ = ctx.getVertex(); return result_; } void VertexExpression::accept(ExprVisitor *visitor) { visitor->visit(this); } } // namespace nebula
25.095238
78
0.745731
blacklovebear
9176cd1e0a82f1e5bdb12346c0452393f36b4acb
38,747
cpp
C++
Src/lunaui/notifications/DashboardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/lunaui/notifications/DashboardWindowManager.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/notifications/DashboardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include <glib.h> #include <QGraphicsSceneMouseEvent> #include <QStateMachine> #include <QState> #include <QDeclarativeEngine> #include <QDeclarativeComponent> #include <QDeclarativeContext> #include "DashboardWindowManager.h" #include "AlertWindow.h" #include "BannerWindow.h" #include "DashboardWindow.h" #include "DashboardWindowContainer.h" #include "DashboardWindowManagerStates.h" #include "CoreNaviManager.h" #include "DisplayManager.h" #include "GraphicsItemContainer.h" #include "HostBase.h" #include "Logging.h" #include "NewContentIndicatorEvent.h" #include "NotificationPolicy.h" #include "PersistentWindowCache.h" #include "Settings.h" #include "SystemUiController.h" #include "Time.h" #include "WebAppMgrProxy.h" #include "Window.h" #include "WindowServer.h" #include "WindowServerLuna.h" #include "Preferences.h" #include "Utils.h" #include "FlickGesture.h" #include "DockModeWindowManager.h" #include <QGraphicsPixmapItem> static const int kTabletAlertWindowPadding = 5; static const int kTabletNotificationContentWidth = 320; DashboardWindowManager::DashboardWindowManager(int maxWidth, int maxHeight) : WindowManagerBase(maxWidth, maxHeight) ,m_stateMachine(0) ,m_stateDashboardOpen(0) ,m_stateAlertOpen(0) ,m_stateClosed(0) ,m_stateCurrent(0) ,m_bannerWin(0) ,m_bgItem(0) ,m_alertWinContainer(0) ,m_transientContainer(0) ,m_dashboardWinContainer(0) ,m_dashboardRightOffset(0) ,m_qmlNotifMenu(0) ,m_menuObject(0) ,m_notifMenuRightEdgeOffset(0) ,m_activeTransientAlert(0) { setObjectName("DashboardWindowManager"); m_notificationPolicy = new NotificationPolicy(); m_bannerHasContent = false; m_AlertWindowFadeOption = Invalid; m_deleteWinAfterAnimation = NULL; m_deleteTransientWinAfterAnimation = false; m_previousActiveAlertWindow = NULL; m_inDockModeAnimation = false; // grab all gestures handled by the scenes viewport widget so // we can prevent them from being propogated to items below the dashboard grabGesture(Qt::TapGesture); grabGesture(Qt::TapAndHoldGesture); grabGesture(Qt::PinchGesture); grabGesture((Qt::GestureType) SysMgrGestureFlick); grabGesture((Qt::GestureType) SysMgrGestureSingleClick); SystemUiController* suc = SystemUiController::instance(); m_isOverlay = !suc->dashboardOwnsNegativeSpace(); // Connect to this signal only if we own the negative space. if(!m_isOverlay) { connect(suc, SIGNAL(signalNegativeSpaceChanged(const QRect&)), this, SLOT(slotNegativeSpaceChanged(const QRect&))); connect(suc, SIGNAL(signalNegativeSpaceChangeFinished(const QRect&)), this, SLOT(slotNegativeSpaceChangeFinished(const QRect&))); } else { connect(suc, SIGNAL(signalPositiveSpaceChanged(const QRect&)), this, SLOT(slotPositiveSpaceChanged(const QRect&))); connect(suc, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)), this, SLOT(slotPositiveSpaceChangeFinished(const QRect&))); setFlag(QGraphicsItem::ItemHasNoContents, true); } connect(SystemUiController::instance(), SIGNAL(signalCloseDashboard(bool)), this, SLOT(slotCloseDashboard(bool))); connect(SystemUiController::instance(), SIGNAL(signalOpenDashboard()), this, SLOT(slotOpenDashboard())); connect(SystemUiController::instance(), SIGNAL(signalCloseAlert()), this, SLOT(slotCloseAlert())); } DashboardWindowManager::~DashboardWindowManager() { } void DashboardWindowManager::init() { int width = boundingRect().toRect().width(); int height = boundingRect().toRect().height(); if(m_isOverlay) { QDeclarativeEngine* qmlEngine = WindowServer::instance()->declarativeEngine(); if(qmlEngine) { QDeclarativeContext* context = qmlEngine->rootContext(); m_dashboardWinContainer = new DashboardWindowContainer(this, kTabletNotificationContentWidth, 0); if(context) { context->setContextProperty("DashboardContainer", m_dashboardWinContainer); } Settings* settings = Settings::LunaSettings(); std::string systemMenuQmlPath = settings->lunaQmlUiComponentsPath + "DashboardMenu/DashboardMenu.qml"; QUrl url = QUrl::fromLocalFile(systemMenuQmlPath.c_str()); m_qmlNotifMenu = new QDeclarativeComponent(qmlEngine, url, this); if(m_qmlNotifMenu) { m_menuObject = qobject_cast<QGraphicsObject *>(m_qmlNotifMenu->create()); if(m_menuObject) { m_menuObject->setParentItem(this); m_notifMenuRightEdgeOffset = m_menuObject->property("edgeOffset").toInt(); QMetaObject::invokeMethod(m_menuObject, "setMaximumHeight", Q_ARG(QVariant, m_dashboardWinContainer->getMaximumHeightForMenu())); } } } } if(!m_isOverlay) { m_dashboardWinContainer = new DashboardWindowContainer(this, width, height); m_alertWinContainer = new GraphicsItemContainer(width, height, GraphicsItemContainer::SolidRectBackground); } else { m_alertWinContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::PopupBackground); m_alertWinContainer->setBlockGesturesAndMouse(true); m_alertWinContainer->setAcceptTouchEvents(true); } m_transientContainer = new GraphicsItemContainer(kTabletNotificationContentWidth, 0, GraphicsItemContainer::TransientAlertBackground); m_transientContainer->setBlockGesturesAndMouse(true); m_transientContainer->setOpacity(0.0); m_transientContainer->setVisible(true); m_transientContainer->setAcceptTouchEvents(true); m_transAlertAnimation.setTargetObject(m_transientContainer); m_transAlertAnimation.setPropertyName("opacity"); // Connect the signal to process events after animation is complete connect(&m_transAlertAnimation, SIGNAL(finished()), SLOT(slotTransientAnimationFinished())); connect(m_dashboardWinContainer, SIGNAL(signalWindowAdded(DashboardWindow*)), SLOT(slotDashboardWindowAdded(DashboardWindow*))); connect(m_dashboardWinContainer, SIGNAL(signalWindowsRemoved(DashboardWindow*)), SLOT(slotDashboardWindowsRemoved(DashboardWindow*))); connect(m_dashboardWinContainer, SIGNAL(signalViewportHeightChanged()), SLOT(slotDashboardViewportHeightChanged())); connect(SystemUiController::instance()->statusBar(), SIGNAL(signalDashboardAreaRightEdgeOffset(int)), this, SLOT(slotDashboardAreaRightEdgeOffset(int))); m_bannerWin = new BannerWindow(this, width, Settings::LunaSettings()->positiveSpaceTopPadding); m_bgItem = new GraphicsItemContainer(width, height, m_isOverlay ? GraphicsItemContainer::NoBackground : GraphicsItemContainer::SolidRectBackground); if(!m_isOverlay) { m_dashboardWinContainer->setParentItem(this); } // Listen for dock mode DockModeWindowManager* dmwm = 0; dmwm = ((DockModeWindowManager*)((WindowServerLuna*)WindowServer::instance())->dockModeManager()); // Listen for dock mode animation to ignore dashboard open / close requests connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationStarted()), this, SLOT(slotDockModeAnimationStarted())); connect ((WindowServerLuna*)WindowServer::instance(), SIGNAL (signalDockModeAnimationComplete()), this, SLOT(slotDockModeAnimationComplete())); m_alertWinContainer->setParentItem(this); m_bgItem->setParentItem(this); m_bannerWin->setParentItem(m_bgItem); if(m_isOverlay) { m_transientContainer->setParentItem(this); // Set the pos of the Alert Containers correctly. positionAlertWindowContainer(); positionTransientWindowContainer(); if (m_menuObject) { int uiHeight = SystemUiController::instance()->currentUiHeight(); // temporary location just until the status bar tell us where to place the dashboard container m_menuObject->setPos(0, -uiHeight/2 + Settings::LunaSettings()->positiveSpaceTopPadding); } // Connect the signal to process events after animation is complete connect(&m_fadeInOutAnimation, SIGNAL(finished()), SLOT(slotDeleteAnimationFinished())); } else { setPosTopLeft(m_alertWinContainer, 0, 0); m_alertWinContainer->setBrush(Qt::black); m_bgItem->setBrush(Qt::black); } setPosTopLeft(m_bgItem, 0, 0); setPosTopLeft(m_bannerWin, 0, 0); setupStateMachine(); } void DashboardWindowManager::setupStateMachine() { m_stateMachine = new QStateMachine(this); m_stateDashboardOpen = new DWMStateOpen(this); m_stateAlertOpen = new DWMStateAlertOpen(this); m_stateClosed = new DWMStateClosed(this); m_stateMachine->addState(m_stateDashboardOpen); m_stateMachine->addState(m_stateAlertOpen); m_stateMachine->addState(m_stateClosed); // ------------------------------------------------------------------------------ m_stateDashboardOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed); m_stateAlertOpen->addTransition(this, SIGNAL(signalActiveAlertWindowChanged()), m_stateClosed); m_stateDashboardOpen->addTransition(m_dashboardWinContainer, SIGNAL(signalEmpty()), m_stateClosed); m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, this, SIGNAL(signalActiveAlertWindowChanged()))); m_stateClosed->addTransition(this, SIGNAL(signalOpen()), m_stateDashboardOpen); m_stateClosed->addTransition(new DWMTransitionClosedToAlertOpen(this, m_stateAlertOpen, m_stateClosed, SIGNAL(signalNegativeSpaceAnimationFinished()))); m_stateDashboardOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed); m_stateAlertOpen->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed); m_stateClosed->addTransition(this, SIGNAL(signalClose(bool)), m_stateClosed); // ------------------------------------------------------------------------------ m_stateMachine->setInitialState(m_stateClosed); m_stateMachine->start(); } int DashboardWindowManager::sTabletUiWidth() { return kTabletNotificationContentWidth; } int DashboardWindowManager::bannerWindowHeight() { return m_bannerWin->boundingRect().height(); } bool DashboardWindowManager::canCloseDashboard() const { return m_stateCurrent == m_stateDashboardOpen; } bool DashboardWindowManager::dashboardOpen() const { return m_stateCurrent == m_stateDashboardOpen; } bool DashboardWindowManager::hasDashboardContent() const { return m_bannerHasContent || !m_dashboardWinContainer->empty(); } void DashboardWindowManager::openDashboard() { if (m_inDockModeAnimation) return; if(!SystemUiController::instance()->statusBarAndNotificationAreaShown()) return; if (!m_alertWinArray.empty() || m_dashboardWinContainer->empty()) { return ; } Q_EMIT signalOpen(); } void DashboardWindowManager::slotPositiveSpaceChanged(const QRect& r) { positionAlertWindowContainer(r); positionTransientWindowContainer(r); positionDashboardContainer(r); } void DashboardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r) { positionAlertWindowContainer(r); positionTransientWindowContainer(r); positionDashboardContainer(r); } void DashboardWindowManager::slotNegativeSpaceChanged(const QRect& r) { negativeSpaceChanged(r); } void DashboardWindowManager::negativeSpaceChanged(const QRect& r) { setPos(0, r.y()); update(); } void DashboardWindowManager::slotNegativeSpaceChangeFinished(const QRect& r) { if (G_UNLIKELY(m_stateCurrent == 0)) { g_critical("m_stateCurrent is null"); return; } m_stateCurrent->negativeSpaceAnimationFinished(); } void DashboardWindowManager::slotOpenDashboard() { openDashboard(); } void DashboardWindowManager::slotCloseDashboard(bool forceClose) { if (!forceClose && !m_stateCurrent->allowsSoftClose()) return; Q_EMIT signalClose(forceClose); } void DashboardWindowManager::slotCloseAlert() { AlertWindow* win = topAlertWindow(); if(!win) return; win->deactivate(); notifyActiveAlertWindowDeactivated(win); win->close(); } void DashboardWindowManager::slotDashboardAreaRightEdgeOffset(int offset) { if (m_menuObject) { m_dashboardRightOffset = offset; m_menuObject->setX((boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset); } } void DashboardWindowManager::slotDeleteAnimationFinished() { switch(m_AlertWindowFadeOption) { case FadeInAndOut: case FadeOutOnly: // Reset the dimensions and position of the dashboardwindow container to the orignal one. m_alertWinContainer->resize(kTabletNotificationContentWidth, 0); positionAlertWindowContainer(); if(m_previousActiveAlertWindow) { m_previousActiveAlertWindow->setParent(NULL); m_previousActiveAlertWindow->setVisible(false); m_previousActiveAlertWindow = NULL; } if(m_deleteWinAfterAnimation) { delete m_deleteWinAfterAnimation; m_deleteWinAfterAnimation = NULL; } if(FadeOutOnly == m_AlertWindowFadeOption) { // Change the state to closed. Q_EMIT signalActiveAlertWindowChanged(); } else if(topAlertWindow()) { // we need to fade in the new alert window m_AlertWindowFadeOption = FadeInOnly; resizeAlertWindowContainer(topAlertWindow(), true); animateAlertWindow(); notifyActiveAlertWindowActivated (topAlertWindow()); } else { m_AlertWindowFadeOption = Invalid; } m_AlertWindowFadeOption = Invalid; break; default: m_AlertWindowFadeOption = Invalid; break; } } void DashboardWindowManager::slotTransientAnimationFinished() { if(m_deleteTransientWinAfterAnimation) { if(m_activeTransientAlert) { delete m_activeTransientAlert; m_activeTransientAlert = NULL; } m_deleteTransientWinAfterAnimation = false; } if(m_transientContainer->opacity() == 0.0) m_transientContainer->setVisible(false); } void DashboardWindowManager::setBannerHasContent(bool val) { m_bannerHasContent = val; if (val || !m_dashboardWinContainer->empty()) { SystemUiController::instance()->setDashboardHasContent(true); if (G_LIKELY(m_stateCurrent)) m_stateCurrent->dashboardContentAdded(); } else { SystemUiController::instance()->setDashboardHasContent(false); if (G_LIKELY(m_stateCurrent)) m_stateCurrent->dashboardContentRemoved(); } update(); } void DashboardWindowManager::focusWindow(Window* w) { // we listen to focus and blur only for alert windows if (!(w->type() == Window::Type_PopupAlert || w->type() == Window::Type_BannerAlert)) return; AlertWindow* win = static_cast<AlertWindow*>(w); // And only for persistable windows PersistentWindowCache* persistCache = PersistentWindowCache::instance(); if (!persistCache->shouldPersistWindow(win)) return; addAlertWindow(win); } void DashboardWindowManager::unfocusWindow(Window* w) { // we listen to focus and blur only for alert windows if (w->type() != Window::Type_PopupAlert && w->type() != Window::Type_BannerAlert) return; AlertWindow* win = static_cast<AlertWindow*>(w); // Is this window in our current list of windows? If no, // nothing to do if (!m_alertWinArray.contains(win)) return; // Look only for persistable windows PersistentWindowCache* persistCache = PersistentWindowCache::instance(); if (!persistCache->shouldPersistWindow(win)) return; // Add to persistent cache if not already in there if (!persistCache->hasWindow(win)) persistCache->addWindow(win); hideOrCloseAlertWindow(win); } void DashboardWindowManager::animateAlertWindow() { // We are running on a tablet and we need to fade the AlertWindows in or out. There are two cases: // 1: If there are no more alert windows, just animate this one out and be done with it. // 2: If we have other alert windows, activate them. // Stop the existing animation m_fadeInOutAnimation.stop(); m_fadeInOutAnimation.clear(); AlertWindow* w = NULL; qreal endValue = 0.0; // Set the opacity of the window to 0; switch(m_AlertWindowFadeOption) { case FadeInOnly: w = topAlertWindow(); m_alertWinContainer->setOpacity(0.0); w->show(); w->activate(); endValue = 1.0; break; case FadeInAndOut: case FadeOutOnly: if(m_previousActiveAlertWindow) { w = m_previousActiveAlertWindow; } else { w = m_deleteWinAfterAnimation; } endValue = 0.0; break; default: return; } // Start the animation QPropertyAnimation* a = new QPropertyAnimation(m_alertWinContainer, "opacity"); a->setEndValue(endValue); // TODO - CHANGE DURATION TO READ FROM ANIMATIONSETTINGS.H a->setDuration(400); a->setEasingCurve(QEasingCurve::Linear); m_fadeInOutAnimation.addAnimation(a); m_fadeInOutAnimation.start(); } void DashboardWindowManager::animateTransientAlertWindow(bool in) { // Stop the existing animation m_transAlertAnimation.stop(); if(!m_activeTransientAlert) return; qreal endValue = 0.0; if(in) { m_transientContainer->setVisible(true); m_activeTransientAlert->show(); m_activeTransientAlert->activate(); endValue = 1.0; } else { endValue = 0.0; } // Start the animation m_transAlertAnimation.setStartValue(m_transientContainer->opacity()); m_transAlertAnimation.setEndValue(endValue); m_transAlertAnimation.setDuration(400); m_transAlertAnimation.setEasingCurve(QEasingCurve::Linear); m_transAlertAnimation.start(); } void DashboardWindowManager::hideOrCloseAlertWindow(AlertWindow* win) { bool isActiveAlert = false; if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win)) isActiveAlert = true; int removeIndex = m_alertWinArray.indexOf(win); if (removeIndex != -1) m_alertWinArray.remove(removeIndex); // Is this a window that we want to persist? PersistentWindowCache* persistCache = PersistentWindowCache::instance(); if (!persistCache->shouldPersistWindow(win)) { if (isActiveAlert) { win->deactivate(); notifyActiveAlertWindowDeactivated(win); } // No. Close it win->close(); return; } if (!persistCache->hasWindow(win)) persistCache->addWindow(win); persistCache->hideWindow(win); if (isActiveAlert) { win->deactivate(); notifyActiveAlertWindowDeactivated(win); Q_EMIT signalActiveAlertWindowChanged(); } } void DashboardWindowManager::resizeAlertWindowContainer(AlertWindow* w, bool repositionWindow) { if(!w) return; // This should not be executed if we are running on a phone. if(!isOverlay()) return; bool wasResized = false; QRectF bRect = m_alertWinContainer->boundingRect(); if(w->initialHeight() != bRect.height() || w->initialWidth() != bRect.width()) { m_alertWinContainer->resize(w->initialWidth(), w->initialHeight()); positionAlertWindowContainer(); wasResized = true; } if(true == repositionWindow) { if(true == wasResized) { w->setPos(0,0); } } } void DashboardWindowManager::addAlertWindow(AlertWindow* win) { if(win->isTransientAlert()) { // transient alerts are handled separately addTransientAlertWindow(win); return; } // This window may have already been added because a persistent // window called focus before the corresponding webapp was ready if (m_alertWinArray.contains(win)) return; bool reSignalOpenAlert = false; PersistentWindowCache* persistCache = PersistentWindowCache::instance(); if (persistCache->shouldPersistWindow(win)) { if (!persistCache->hasWindow(win)) { persistCache->addWindow(win); } } AlertWindow* oldActiveWindow = 0; if (!m_alertWinArray.empty()) oldActiveWindow = m_alertWinArray[0]; addAlertWindowBasedOnPriority(win); // Set the flags depending on whether we are running on phone/tablet. if(isOverlay()) { if(Invalid == m_AlertWindowFadeOption) { m_AlertWindowFadeOption = FadeInOnly; } // resize the alertwindowcontainer if there are no other active alert windows. if(m_stateCurrent != m_stateAlertOpen) { resizeAlertWindowContainer(win, false); } } if(!isOverlay()) { if(win->boundingRect().width() != SystemUiController::instance()->currentUiWidth()) { win->resizeEventSync(SystemUiController::instance()->currentUiWidth(), win->initialHeight()); setPosTopLeft(win, 0, 0); } } else { win->setPos(0,0); } if (!win->parentItem()) { win->setParentItem(m_alertWinContainer); if(!m_isOverlay) setPosTopLeft(win, 0, 0); else win->setPos(0,0); // Initially set the visibility to false win->setVisible(false); } AlertWindow* newActiveWindow = m_alertWinArray[0]; if (oldActiveWindow && (oldActiveWindow == newActiveWindow)) { // Adding the new window did not displace the current active window. // Nothing to do further return; } if (oldActiveWindow) { reSignalOpenAlert = true; m_previousActiveAlertWindow = oldActiveWindow; // Displaced the current active window. Need to hide it if (persistCache->shouldPersistWindow(oldActiveWindow)) { if (!persistCache->hasWindow(oldActiveWindow)) persistCache->addWindow(oldActiveWindow); persistCache->hideWindow(oldActiveWindow); } else { oldActiveWindow->deactivate(); } // Set that we need to fade the existing window out and the new window in. m_AlertWindowFadeOption = FadeInAndOut; } else if(FadeOutOnly == m_AlertWindowFadeOption) { // currently in the process of closing the dashboard (last alert just got deactivated before the new window was added), // so mark the fade option as Fade Ina dn Out to bring it back with the new alert window m_AlertWindowFadeOption = FadeInAndOut; return; } if(!isOverlay()) { Q_EMIT signalActiveAlertWindowChanged(); } else { // Check if we need to resignal to show the latest alert. if(false == reSignalOpenAlert) { // Dashboard was open. The first signal will close the dashbaord. Resignal to open the alert if(m_stateCurrent == m_stateDashboardOpen) reSignalOpenAlert = true; } // Signal once to move the state to closed Q_EMIT signalActiveAlertWindowChanged(); // signal again to move the state to display the active alert window if(true == reSignalOpenAlert) { Q_EMIT signalActiveAlertWindowChanged(); } } } void DashboardWindowManager::addTransientAlertWindow(AlertWindow* win) { if (m_activeTransientAlert == win) return; if(m_activeTransientAlert) { // only one transient alert is allowed at any given time, so close the current one m_activeTransientAlert->deactivate(); m_deleteTransientWinAfterAnimation = NULL; m_transAlertAnimation.stop(); notifyTransientAlertWindowDeactivated(m_activeTransientAlert); delete m_activeTransientAlert; m_activeTransientAlert = 0; } m_activeTransientAlert = win; win->setParentItem(m_transientContainer); win->setVisible(true); win->setOpacity(1.0); win->setPos(0,0); win->resizeEventSync(win->initialWidth(), win->initialHeight()); // resize the transient alert window container if there are no other active alert windows. QRectF bRect = m_transientContainer->boundingRect(); if(win->initialHeight() != bRect.height() || win->initialWidth() != bRect.width()) { m_transientContainer->resize(win->initialWidth(), win->initialHeight()); } positionTransientWindowContainer(); notifyTransientAlertWindowActivated(m_activeTransientAlert); animateTransientAlertWindow(true); } void DashboardWindowManager::removeAlertWindow(AlertWindow* win) { if(win->isTransientAlert()) { // transient alerts are handled separately removeTransientAlertWindow(win); return; } PersistentWindowCache* persistCache = PersistentWindowCache::instance(); if (!m_alertWinArray.contains(win)) { // This can happen in two cases: // * a window was stuffed int the persistent window cache on hiding // * a window was closed before being added to the window manager if (persistCache->hasWindow(win)) { persistCache->removeWindow(win); } delete win; return; } if (persistCache->hasWindow(win)) persistCache->removeWindow(win); bool isActiveAlert = false; if (!m_alertWinArray.empty() && (m_alertWinArray[0] == win)) isActiveAlert = true; int removeIndex = m_alertWinArray.indexOf(win); if (removeIndex != -1) { m_alertWinArray.remove(removeIndex); } if (isActiveAlert) { win->deactivate(); notifyActiveAlertWindowDeactivated(win); } // If we are running on the phone, just signal the state to enter closed. if(!isOverlay()) { delete win; if(isActiveAlert) { Q_EMIT signalActiveAlertWindowChanged(); } } else { m_deleteWinAfterAnimation = win; if (isActiveAlert) { // Change the state if there are more alert windows in the system if(!m_alertWinArray.empty()) { // This will cause the state to enter stateClosed. Q_EMIT signalActiveAlertWindowChanged(); // If we are running on a tablet and if this flag is set to true, signal that we need to display the next alert if (G_UNLIKELY(m_stateCurrent == 0)) { g_critical("m_stateCurrent is null"); return; } // Set that we need to fade the existing window out and the new window in. m_AlertWindowFadeOption = FadeInAndOut; // Signal that we need to bring the next active window in m_stateCurrent->negativeSpaceAnimationFinished(); } else { m_AlertWindowFadeOption = FadeOutOnly; animateAlertWindow(); } } } } void DashboardWindowManager::removeTransientAlertWindow(AlertWindow* win) { if (m_activeTransientAlert != win) { delete win; return; } win->deactivate(); notifyTransientAlertWindowDeactivated(win); m_deleteTransientWinAfterAnimation = true; animateTransientAlertWindow(false); } void DashboardWindowManager::addAlertWindowBasedOnPriority(AlertWindow* win) { if (m_alertWinArray.empty()) { m_alertWinArray.append(win); return; } AlertWindow* activeAlertWin = m_alertWinArray[0]; // Add the window to the list of alert windows, sorted by priority int newWinPriority = m_notificationPolicy->popupAlertPriority(win->appId(), win->name()); if (newWinPriority == m_notificationPolicy->defaultPriority()) { // optimization. if we are at default priority we don't need to walk the list // we will just queue up this window int oldSize = m_alertWinArray.size(); m_alertWinArray.append(win); } else if (newWinPriority < m_notificationPolicy->popupAlertPriority(activeAlertWin->appId(), activeAlertWin->name())) { // if the priority of new window is higher than the currently shown window, then we push // both the windows in the queue with the new window in front QVector<AlertWindow*>::iterator it = qFind(m_alertWinArray.begin(), m_alertWinArray.end(), activeAlertWin); Q_ASSERT(it != m_alertWinArray.end()); m_alertWinArray.insert(it, win); } else { bool added = false; QMutableVectorIterator<AlertWindow*> it(m_alertWinArray); while (it.hasNext()) { AlertWindow* a = it.next(); if (newWinPriority < m_notificationPolicy->popupAlertPriority(a->appId(), a->name())) { it.insert(win); added = true; break; } } if (!added) m_alertWinArray.append(win); } } void DashboardWindowManager::addWindow(Window* win) { if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert) addAlertWindow(static_cast<AlertWindow*>(win)); else if (win->type() == Window::Type_Dashboard) m_dashboardWinContainer->addWindow(static_cast<DashboardWindow*>(win)); } void DashboardWindowManager::removeWindow(Window* win) { if (win->type() == Window::Type_PopupAlert || win->type() == Window::Type_BannerAlert) removeAlertWindow(static_cast<AlertWindow*>(win)); else if (win->type() == Window::Type_Dashboard) m_dashboardWinContainer->removeWindow(static_cast<DashboardWindow*>(win)); /* if dashboard is empty, all throb requests should have been dismissed * this is defensive coding to ensure that all requests are cleared */ if (m_dashboardWinContainer->empty() && m_alertWinArray.empty()) CoreNaviManager::instance()->clearAllStandbyRequests(); } int DashboardWindowManager::activeAlertWindowHeight() { const Window* alert = getActiveAlertWin(); if(!alertOpen() || !alert) { if(!isOverlay()) return Settings::LunaSettings()->positiveSpaceBottomPadding; else return 0; } return alert->boundingRect().height(); } bool DashboardWindowManager::doesMousePressFallInBannerWindow(QGraphicsSceneMouseEvent* event) { QPointF pos = mapToItem(m_bannerWin, event->pos()); if(m_bannerWin->boundingRect().contains(pos)) { return true; } else { return false; } } /* BannerWindow is invisible when the DashboardWinContainer is up. So if the user clicks in the BannerWindow area, it will not get any notifications. So, we need to have this workaround in DashboardWinMgr::mousePressEvent that will detect if the user clicked on BannerWindow area and prevent it from launching the dashboard again as a part of Qt::GestureComplete */ void DashboardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event) { if(!m_isOverlay) { event->accept(); } else { // if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container. if(true == dashboardOpen()) { event->accept(); } else { event->ignore(); } } } void DashboardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if(!m_isOverlay) { event->accept(); } else { // if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container. if(true == dashboardOpen()) { event->accept(); } else { event->ignore(); } } } void DashboardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if(!m_isOverlay) { event->accept(); } else { // if dashboard has content and we get a mousepress event, we need to close the dashboardwindow container. if(true == dashboardOpen()) { hideDashboardWindow(); event->accept(); if(true == doesMousePressFallInBannerWindow(event)) { m_bannerWin->resetIgnoreGestureUpEvent(); } m_dashboardWinContainer->resetLocalState(); } else { event->ignore(); } } } bool DashboardWindowManager::sceneEvent(QEvent* event) { switch (event->type()) { case QEvent::GestureOverride: { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QList<QGesture*> activeGestures = ge->activeGestures(); Q_FOREACH(QGesture* g, activeGestures) { if (g->hasHotSpot()) { QPointF pt = ge->mapToGraphicsScene(g->hotSpot()); if (dashboardOpen()) { ge->accept(g); } else { ge->ignore(g); } } } break; } default: break; } return WindowManagerBase::sceneEvent(event); } void DashboardWindowManager::raiseAlertWindow(AlertWindow* window) { g_message("%s", __PRETTY_FUNCTION__); m_alertWinContainer->show(); m_alertWinContainer->raiseChild(window); m_bgItem->hide(); if(!m_isOverlay) m_dashboardWinContainer->hide(); } void DashboardWindowManager::raiseDashboardWindowContainer() { g_message("%s", __PRETTY_FUNCTION__); if(!m_isOverlay) m_dashboardWinContainer->show(); m_alertWinContainer->hide(); m_bgItem->hide(); } void DashboardWindowManager::raiseBackgroundWindow() { if(m_stateCurrent != m_stateAlertOpen) { g_message("%s", __PRETTY_FUNCTION__); m_alertWinContainer->hide(); m_bgItem->show(); m_bannerWin->show(); if(!m_isOverlay) m_dashboardWinContainer->hide(); } else { g_message("%s: In alert state. raise alert window container", __PRETTY_FUNCTION__); m_alertWinContainer->show(); m_bgItem->hide(); if(!m_isOverlay) m_dashboardWinContainer->hide(); } } void DashboardWindowManager::hideDashboardWindow() { if(m_stateCurrent == m_stateDashboardOpen) { Q_EMIT signalClose(true); } if(!m_isOverlay) m_dashboardWinContainer->hide(); } void DashboardWindowManager::sendClicktoDashboardWindow(int num, int x, int y, bool whileLocked) { m_dashboardWinContainer->sendClickToDashboardWindow(num, QPointF(x, y), true); } void DashboardWindowManager::notifyActiveAlertWindowActivated(AlertWindow* win) { if (win->isIncomingCallAlert()) DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_ACTIVATED); else DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED); // NOTE: order matters, the DisplayManager needs to act on the alert before anyone else SystemUiController::instance()->notifyAlertActivated(); Q_EMIT signalAlertWindowActivated(win); } void DashboardWindowManager::notifyActiveAlertWindowDeactivated(AlertWindow* win) { if (win->isIncomingCallAlert()) DisplayManager::instance()->alert(DISPLAY_ALERT_PHONECALL_DEACTIVATED); else DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED); SystemUiController::instance()->notifyAlertDeactivated(); Q_EMIT signalAlertWindowDeactivated(); } void DashboardWindowManager::notifyTransientAlertWindowActivated(AlertWindow* win) { if(!alertOpen()) DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_ACTIVATED); // NOTE: order matters, the DisplayManager needs to act on the alert before anyone else SystemUiController::instance()->notifyTransientAlertActivated(); } void DashboardWindowManager::notifyTransientAlertWindowDeactivated(AlertWindow* win) { if(!alertOpen()) DisplayManager::instance()->alert(DISPLAY_ALERT_GENERIC_DEACTIVATED); SystemUiController::instance()->notifyTransientAlertDeactivated(); } void DashboardWindowManager::slotDashboardWindowAdded(DashboardWindow* w) { SystemUiController::instance()->setDashboardHasContent(true); m_bgItem->update(); if (G_LIKELY(m_stateCurrent)) m_stateCurrent->dashboardContentAdded(); } void DashboardWindowManager::slotDashboardWindowsRemoved(DashboardWindow* w) { m_bgItem->update(); if (m_bannerHasContent || !m_dashboardWinContainer->empty()) return; SystemUiController::instance()->setDashboardHasContent(false); if (G_LIKELY(m_stateCurrent)) m_stateCurrent->dashboardContentRemoved(); } void DashboardWindowManager::slotDashboardViewportHeightChanged() { if (G_LIKELY(m_stateCurrent)) m_stateCurrent->dashboardViewportHeightChanged(); } void DashboardWindowManager::resize(int width, int height) { QRectF bRect = boundingRect(); // accept requests for resizing to the current dimensions, in case we are doing a force resize WindowManagerBase::resize(width, height); if(!m_isOverlay) { m_dashboardWinContainer->resize(width, height); setPosTopLeft(m_dashboardWinContainer, 0, 0); m_dashboardWinContainer->resizeWindowsEventSync(width); m_alertWinContainer->resize(width, height); setPosTopLeft(m_alertWinContainer, 0, 0); resizeAlertWindows(width); } else { int yLocCommon = -(height/2) + Settings::LunaSettings()->positiveSpaceTopPadding; int xLocDashWinCtr; if (m_menuObject) { xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset - m_menuObject->boundingRect().width() + m_notifMenuRightEdgeOffset; } else { xLocDashWinCtr = (boundingRect().width()/2) - m_dashboardRightOffset + m_notifMenuRightEdgeOffset; } int yLocDashWinCtr = yLocCommon; int yLocAlertWinCtr = (m_stateCurrent != m_stateAlertOpen)?yLocCommon:(yLocCommon + topAlertWindow()->initialHeight()/2 + kTabletAlertWindowPadding); // Set the new position of the m_dashboardWinContainer if (m_menuObject) { m_menuObject->setPos(xLocDashWinCtr, yLocDashWinCtr); } positionAlertWindowContainer(); } if(!m_isOverlay) { // reposition the banner window and the backgound item m_bgItem->resize(width, height); setPosTopLeft(m_bgItem, 0, 0); m_bannerWin->resize(width, Settings::LunaSettings()->positiveSpaceTopPadding); setPosTopLeft(m_bannerWin, 0, 0); if((alertOpen())) { setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - activeAlertWindowHeight() - Settings::LunaSettings()->positiveSpaceBottomPadding)); } else if (hasDashboardContent()) { setPos(0, (SystemUiController::instance()->currentUiHeight()/2 + height/2 - Settings::LunaSettings()->positiveSpaceBottomPadding)); } else { setPos(0, SystemUiController::instance()->currentUiHeight()/2 + height/2); } } m_stateCurrent->handleUiResizeEvent(); // resize all cached Alert Windows PersistentWindowCache* persistCache = PersistentWindowCache::instance(); std::set<Window*>* cachedWindows = persistCache->getCachedWindows(); if(cachedWindows) { std::set<Window*>::iterator it; it=cachedWindows->begin(); for ( it=cachedWindows->begin() ; it != cachedWindows->end(); it++ ) { Window* w = *it; if(w->type() == Window::Type_PopupAlert || w->type() == Window::Type_BannerAlert) { ((AlertWindow*)w)->resizeEventSync((m_isOverlay ? kTabletNotificationContentWidth : width), ((AlertWindow*)w)->initialHeight()); } } } } void DashboardWindowManager::resizeAlertWindows(int width) { Q_FOREACH(AlertWindow* a, m_alertWinArray) { if (a) { a->resizeEventSync(width, a->initialHeight()); if(!m_isOverlay) setPosTopLeft(a, 0, 0); else a->setPos(0,0); } } } void DashboardWindowManager::slotDockModeAnimationStarted() { m_inDockModeAnimation = true; } void DashboardWindowManager::slotDockModeAnimationComplete() { m_inDockModeAnimation = false; } void DashboardWindowManager::positionDashboardContainer(const QRect& posSpace) { if (m_menuObject) { QRect positiveSpace; if(posSpace.isValid()) positiveSpace = posSpace; else positiveSpace = SystemUiController::instance()->positiveSpaceBounds(); int uiHeight = SystemUiController::instance()->currentUiHeight(); m_menuObject->setY(-uiHeight/2 + positiveSpace.y()); } } void DashboardWindowManager::positionAlertWindowContainer(const QRect& posSpace) { QRect positiveSpace; if(posSpace.isValid()) positiveSpace = posSpace; else positiveSpace = SystemUiController::instance()->positiveSpaceBounds(); int uiHeight = SystemUiController::instance()->currentUiHeight(); m_alertWinContainer->setPos(QPoint(positiveSpace.width()/2 - kTabletAlertWindowPadding - m_alertWinContainer->width()/2, -uiHeight/2 + positiveSpace.y() + kTabletAlertWindowPadding + m_alertWinContainer->height()/2)); } void DashboardWindowManager::positionTransientWindowContainer(const QRect& posSpace) { QRect positiveSpace; if(posSpace.isValid()) positiveSpace = posSpace; else positiveSpace = SystemUiController::instance()->positiveSpaceBounds(); int uiHeight = SystemUiController::instance()->currentUiHeight(); int uiWidth = SystemUiController::instance()->currentUiWidth(); m_transientContainer->setPos(QPoint(positiveSpace.center().x() - uiWidth/2, positiveSpace.center().y() - uiHeight/2)); }
29.398331
162
0.750665
ericblade
91770e793ba9d44a8110448b8c28e185ae0710f0
4,385
cpp
C++
Editor/IKWindow.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
1
2020-09-07T23:12:17.000Z
2020-09-07T23:12:17.000Z
Editor/IKWindow.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
null
null
null
Editor/IKWindow.cpp
ValtoGameEngines/WickedEngine
1831df147c24fe1bbbe3aeddf98da3535284ade8
[ "Zlib", "MIT" ]
1
2020-06-29T07:54:10.000Z
2020-06-29T07:54:10.000Z
#include "stdafx.h" #include "IKWindow.h" #include "Editor.h" using namespace wiECS; using namespace wiScene; IKWindow::IKWindow(EditorComponent* editor) : GUI(&editor->GetGUI()) { assert(GUI && "Invalid GUI!"); window = new wiWindow(GUI, "Inverse Kinematics (IK) Window"); window->SetSize(XMFLOAT2(460, 200)); GUI->AddWidget(window); float x = 100; float y = 0; float step = 25; float siz = 200; float hei = 20; createButton = new wiButton("Create"); createButton->SetTooltip("Create/Remove IK Component to selected entity"); createButton->SetPos(XMFLOAT2(x, y += step)); createButton->SetSize(XMFLOAT2(siz, hei)); window->AddWidget(createButton); targetCombo = new wiComboBox("Target: "); targetCombo->SetSize(XMFLOAT2(siz, hei)); targetCombo->SetPos(XMFLOAT2(x, y += step)); targetCombo->SetEnabled(false); targetCombo->OnSelect([&](wiEventArgs args) { Scene& scene = wiScene::GetScene(); InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity); if (ik != nullptr) { if (args.iValue == 0) { ik->target = INVALID_ENTITY; } else { ik->target = scene.transforms.GetEntity(args.iValue - 1); } } }); targetCombo->SetTooltip("Choose a target entity (with transform) that the IK will follow"); window->AddWidget(targetCombo); disabledCheckBox = new wiCheckBox("Disabled: "); disabledCheckBox->SetTooltip("Disable simulation."); disabledCheckBox->SetPos(XMFLOAT2(x, y += step)); disabledCheckBox->SetSize(XMFLOAT2(hei, hei)); disabledCheckBox->OnClick([=](wiEventArgs args) { wiScene::GetScene().inverse_kinematics.GetComponent(entity)->SetDisabled(args.bValue); }); window->AddWidget(disabledCheckBox); chainLengthSlider = new wiSlider(0, 10, 0, 10, "Chain Length: "); chainLengthSlider->SetTooltip("How far the hierarchy chain is simulated backwards from this entity"); chainLengthSlider->SetPos(XMFLOAT2(x, y += step)); chainLengthSlider->SetSize(XMFLOAT2(siz, hei)); chainLengthSlider->OnSlide([&](wiEventArgs args) { wiScene::GetScene().inverse_kinematics.GetComponent(entity)->chain_length = args.iValue; }); window->AddWidget(chainLengthSlider); iterationCountSlider = new wiSlider(0, 10, 1, 10, "Iteration Count: "); iterationCountSlider->SetTooltip("How many iterations to compute the inverse kinematics for. Higher values are slower but more accurate."); iterationCountSlider->SetPos(XMFLOAT2(x, y += step)); iterationCountSlider->SetSize(XMFLOAT2(siz, hei)); iterationCountSlider->OnSlide([&](wiEventArgs args) { wiScene::GetScene().inverse_kinematics.GetComponent(entity)->iteration_count = args.iValue; }); window->AddWidget(iterationCountSlider); window->Translate(XMFLOAT3((float)wiRenderer::GetDevice()->GetScreenWidth() - 740, 150, 0)); window->SetVisible(false); SetEntity(INVALID_ENTITY); } IKWindow::~IKWindow() { window->RemoveWidgets(true); GUI->RemoveWidget(window); delete window; } void IKWindow::SetEntity(Entity entity) { this->entity = entity; Scene& scene = wiScene::GetScene(); const InverseKinematicsComponent* ik = scene.inverse_kinematics.GetComponent(entity); if (ik != nullptr) { window->SetEnabled(true); disabledCheckBox->SetCheck(ik->IsDisabled()); chainLengthSlider->SetValue((float)ik->chain_length); iterationCountSlider->SetValue((float)ik->iteration_count); targetCombo->ClearItems(); targetCombo->AddItem("NO TARGET"); for (size_t i = 0; i < scene.transforms.GetCount(); ++i) { Entity entity = scene.transforms.GetEntity(i); const NameComponent* name = scene.names.GetComponent(entity); targetCombo->AddItem(name == nullptr ? std::to_string(entity) : name->name); if (ik->target == entity) { targetCombo->SetSelected((int)i + 1); } } } else { window->SetEnabled(false); } const TransformComponent* transform = wiScene::GetScene().transforms.GetComponent(entity); if (transform != nullptr) { createButton->SetEnabled(true); if (ik == nullptr) { createButton->SetText("Create"); createButton->OnClick([=](wiEventArgs args) { wiScene::GetScene().inverse_kinematics.Create(entity).chain_length = 1; SetEntity(entity); }); } else { createButton->SetText("Remove"); createButton->OnClick([=](wiEventArgs args) { wiScene::GetScene().inverse_kinematics.Remove_KeepSorted(entity); SetEntity(entity); }); } } }
29.42953
140
0.715393
ValtoGameEngines
9177c39579b2d5034dc3556aa2cb796e77d693b8
584
cpp
C++
tests/test_list.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_list.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
tests/test_list.cpp
ToruNiina/wad
f5f0445f7f0a53efd31988ce7d381bccb463b951
[ "MIT" ]
null
null
null
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "wad/list.hpp" #include "wad/integer.hpp" #include "utility.hpp" TEST_CASE( "std::list save/load", "[std::list]" ) { std::list<int> upto_16; std::list<int> upto_u16; std::list<int> upto_u32; for(int i=0; i< 5; ++i) {upto_16 .push_back(i);} for(int i=0; i< 20; ++i) {upto_u16.push_back(i);} for(int i=0; i<70000; ++i) {upto_u32.push_back(i);} REQUIRE(wad::save_load(upto_16) == upto_16); REQUIRE(wad::save_load(upto_u16) == upto_u16); REQUIRE(wad::save_load(upto_u32) == upto_u32); }
27.809524
55
0.633562
ToruNiina
917a05e8dc1c3ecfcc2df14f84dc596304a00d5b
685
cpp
C++
abc/233e.cpp
wky32768/Atcoder
b816b8de922b5bcd59881d808ea0f98148c07311
[ "MIT" ]
null
null
null
abc/233e.cpp
wky32768/Atcoder
b816b8de922b5bcd59881d808ea0f98148c07311
[ "MIT" ]
null
null
null
abc/233e.cpp
wky32768/Atcoder
b816b8de922b5bcd59881d808ea0f98148c07311
[ "MIT" ]
null
null
null
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <algorithm> #define For(i,a,b) for(int i=a;i<=b;i++) #define int long long using namespace std; char ch[1000005]; int ans[1000005],tot[1000005]; signed main() { scanf("%s",ch+1); int n=strlen(ch+1); For(i,1,n) tot[i]=tot[i-1]+ch[i]-'0'; For(i,1,n) { ans[i]+=tot[n+1-i]; // cout<<i<<" "<<ans[i]<<'\n'; ans[i+1]+=ans[i]/10; ans[i]%=10; // cout<<i<<" "<<ans[i]<<'\n'; } int len=(ans[n+1]==0?n:n+1); // cout<<ans[5]<<'\n'; // while(ans[len]>=10){ // ans[len+1]+=ans[len]/10; // ans[len]%=10; // len++; // } // cout<<"len="<<len<<'\n'; for(int i=len;i>=1;i--) cout<<ans[i]; return 0; }
20.757576
40
0.538686
wky32768
917b03dd4a82d7015337584227ba1f3a8cf8e663
53,037
cc
C++
src/topo_ma.cc
erdemeren/VDlib
23091adbea4ba26379eaf941be53d925304a0560
[ "Apache-2.0", "MIT" ]
null
null
null
src/topo_ma.cc
erdemeren/VDlib
23091adbea4ba26379eaf941be53d925304a0560
[ "Apache-2.0", "MIT" ]
null
null
null
src/topo_ma.cc
erdemeren/VDlib
23091adbea4ba26379eaf941be53d925304a0560
[ "Apache-2.0", "MIT" ]
null
null
null
#include <tgmath.h> #include<algorithm> #include "apf.h" #include "ma.h" #include "maMesh.h" #include "topo_extinfo.h" #include "topo_geom.h" #include "topo_ma.h" // Get the lowest quality element and it's quality. std::pair<apf::MeshEntity*, double> calc_valid_q(apf::Mesh2* m, ma::SizeField* s_f) { apf::MeshEntity* e_valid = NULL; double valid = 1; apf::MeshEntity* elem; apf::MeshIterator* it = m->begin(3); while(elem = m->iterate(it)) { double q_temp = measureTetQuality(m, s_f, elem); if(q_temp < valid) { e_valid = elem; valid = q_temp; } } m->end(it); if(valid < std::numeric_limits<double>::min()) { valid = std::fabs(valid); } return std::make_pair(e_valid,valid/5); } // Collect elements with quality less than threshold. double get_low_q(apf::Mesh2* m, ma::SizeField* s_f, std::vector<apf::MeshEntity*> &tets, double q_th) { std::map<apf::MeshEntity*, bool> low{}; std::map<apf::MeshEntity*, double> qual{}; int nbr = 0; double valid = 1; tets.clear(); apf::MeshEntity* elem; apf::MeshIterator* it = m->begin(3); while(elem = m->iterate(it)) { double q_temp = measureTetQuality(m, s_f, elem); if(q_temp < q_th) { nbr = nbr + 1; low[elem] = true; qual[elem] = q_temp; } if(q_temp < valid) valid = q_temp; } m->end(it); tets.reserve(nbr); it = m->begin(3); while(elem = m->iterate(it)) { if(low[elem]) { tets.push_back(elem); } } m->end(it); if(valid < std::numeric_limits<double>::min()) { valid = std::fabs(valid); } return valid; } double calc_good_vol(apf::Mesh2* m, double ref_len, double m_len) { std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0)); apf::Downward d_v; apf::Downward d_e; apf::Downward d_s; v.at(0) = apf::Vector3(0,0,0); v.at(1) = apf::Vector3(m_len,0,0); v.at(2) = apf::Vector3(0,ref_len,0); v.at(3) = apf::Vector3(0,0,ref_len); // Create a new entity to calculate it's quailty. apf::MeshEntity* elem; apf::MeshIterator* it = m->begin(3); elem = m->iterate(it); m->end(it); apf::ModelEntity* mdl = m->toModel(elem); for(int i = 0; i < 4; i++) { d_v[i] = m->createVert(mdl); m->setPoint(d_v[i], 0, v.at(i)); } elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0); m->getDownward(elem, 1, d_e); m->getDownward(elem, 2, d_s); double vol = vd_volume_tet(m, elem); // Destroy the entities: m->destroy(elem); for(int i = 0; i < 4; i++) m->destroy(d_s[i]); for(int i = 0; i < 6; i++) m->destroy(d_e[i]); for(int i = 0; i < 4; i++) m->destroy(d_v[i]); return vol; } bool vd_chk_vol_valid(apf::Mesh2* m, apf::MeshEntity* tet, apf::MeshEntity* ent) { int ent_type = m->getType(ent); int d = m->typeDimension[ent_type]; assert(d > -1 and d < 3); bool valid = true; if(d > 0) { std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0)); apf::Downward d_v; apf::Downward d_v2; m->getDownward(tet, 0, d_v); std::map<apf::MeshEntity*, apf::Vector3> old_pos{}; for(int i = 0; i < 4; i++) { m->getPoint(d_v[i], 0, v.at(i)); old_pos[d_v[i]] = v.at(i); } int dc = m->getDownward(tet, d, d_v2); int e1 = findIn(d_v2, dc, ent); assert(e1 > -1); dc = m->getDownward(ent, 0, d_v2); apf::Vector3 midpoint(0,0,0); midpoint = vd_get_pos(m, ent); for(int j = 0; j < dc; j++) { m->setPoint(d_v2[j], 0, midpoint); bool vol = vd_volume_tet_sign(m, tet); valid = (valid and vol); m->setPoint(d_v2[j], 0, old_pos[d_v2[j]]); } } return valid; } double calc_good_q(apf::Mesh2* m, double ref_len, double m_len) { std::vector<apf::Vector3> v(4, apf::Vector3(0,0,0)); apf::Downward d_v; apf::Downward d_e; apf::Downward d_s; v.at(0) = apf::Vector3(0,0,0); v.at(1) = apf::Vector3(m_len,0,0); v.at(2) = apf::Vector3(0,ref_len,0); v.at(3) = apf::Vector3(0,0,ref_len); // Create a new entity to calculate it's quailty. apf::MeshEntity* elem; apf::MeshIterator* it = m->begin(3); elem = m->iterate(it); m->end(it); apf::ModelEntity* mdl = m->toModel(elem); for(int i = 0; i < 4; i++) { d_v[i] = m->createVert(mdl); m->setPoint(d_v[i], 0, v.at(i)); } elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0); m->getDownward(elem, 1, d_e); m->getDownward(elem, 2, d_s); ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m); double qual = measureTetQuality(m, ref_0c, elem); delete ref_0c; // Destroy the entities: m->destroy(elem); for(int i = 0; i < 4; i++) m->destroy(d_s[i]); for(int i = 0; i < 6; i++) m->destroy(d_e[i]); for(int i = 0; i < 4; i++) m->destroy(d_v[i]); return qual; } double calc_q(apf::Mesh2* m, std::vector<apf::Vector3> &v) { apf::Downward d_v; apf::Downward d_s; apf::Downward d_e; // Create a new entity to calculate it's quailty. apf::MeshEntity* elem; apf::MeshIterator* it = m->begin(3); elem = m->iterate(it); m->end(it); apf::ModelEntity* mdl = m->toModel(elem); for(int i = 0; i < 4; i++) { d_v[i] = m->createVert(mdl); m->setPoint(d_v[i], 0, v.at(i)); } elem = buildElement(m, mdl, apf::Mesh::TET, d_v, 0); m->getDownward(elem, 1, d_e); m->getDownward(elem, 2, d_s); ma::IdentitySizeField* ref_0c = new ma::IdentitySizeField(m); double qual = measureTetQuality(m, ref_0c, elem); delete ref_0c; // Destroy the entities: m->destroy(elem); for(int i = 0; i < 4; i++) m->destroy(d_s[i]); for(int i = 0; i < 6; i++) m->destroy(d_e[i]); for(int i = 0; i < 4; i++) m->destroy(d_v[i]); return qual; } MaSwap3Dcheck::MaSwap3Dcheck(apf::Mesh2* m): mesh(m) { halves[0].init(m); halves[1].init(m); edge = 0; } MaSwap3Dcheck::~MaSwap3Dcheck() {} bool MaSwap3Dcheck::run(apf::MeshEntity* e) { if (ma::isOnModelEdge(mesh,e)) return false; edge = e; if (ma::isOnModelFace(mesh,edge)) { } else { cavityExists[0] = halves[0].setFromEdge(edge); if(!cavityExists[0]) { MaLoop loop; loop.init(mesh); loop.setEdge(edge); std::vector<apf::MeshEntity*> tets(0); std::vector<apf::MeshEntity*> surf(0); vd_set_up(mesh, e, &surf); vd_set_up(mesh, &surf, &tets); apf::ModelEntity* mdl = mesh->toModel(edge); std::cout << "Curl is not OK! " << edge << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; apf::Downward dv; apf::Up up; mesh->getDownward(edge, 0, dv); mdl = mesh->toModel(dv[0]); std::cout << "Verts: " << dv[0] << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; mdl = mesh->toModel(dv[1]); std::cout << dv[1] << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; for(int i = 0; i < tets.size(); i++) { mdl = mesh->toModel(tets.at(i)); std::cout << "Tet " << tets.at(i) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << " " << vd_get_pos(mesh, tets.at(i)) << std::endl; vd_print_down(mesh, tets.at(i)); } for(int i = 0; i < surf.size(); i++) { mdl = mesh->toModel(surf.at(i)); std::cout << "Surf " << surf.at(i) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << " " << vd_get_pos(mesh, surf.at(i)) << std::endl; vd_print_down(mesh, surf.at(i)); vd_set_up(mesh, surf.at(i), &tets); apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge); for(int j = 0; j < tets.size(); j++) { mdl = mesh->toModel(tets.at(j)); std::cout << "Tet " << tets.at(j) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; std::cout << "Curl:" << loop.isCurlOk(v,tets.at(j)) << std::endl; } } } assert(cavityExists[0]); } return true; } bool MaSwap3Dcheck::run_all_surf(apf::MeshEntity* e) { bool curl_ok = true; if (ma::isOnModelEdge(mesh,e)) return curl_ok; edge = e; if (ma::isOnModelFace(mesh,edge)) { } else { MaLoop loop; loop.init(mesh); loop.setEdge(edge); std::vector<apf::MeshEntity*> tets(0); std::vector<apf::MeshEntity*> surf(0); vd_set_up(mesh, e, &surf); vd_set_up(mesh, &surf, &tets); apf::ModelEntity* mdl = mesh->toModel(edge); std::cout << edge << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; apf::Downward dv; apf::Up up; mesh->getDownward(edge, 0, dv); mdl = mesh->toModel(dv[0]); std::cout << "Verts: " << dv[0] << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; mdl = mesh->toModel(dv[1]); std::cout << dv[1] << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; for(int i = 0; i < tets.size(); i++) { mdl = mesh->toModel(tets.at(i)); std::cout << "Tet " << tets.at(i) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << " " << vd_get_pos(mesh, tets.at(i)) << std::endl; vd_print_down(mesh, tets.at(i)); } for(int i = 0; i < surf.size(); i++) { mdl = mesh->toModel(surf.at(i)); std::cout << "Surf " << surf.at(i) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << " " << vd_get_pos(mesh, surf.at(i)) << std::endl; vd_print_down(mesh, surf.at(i)); vd_set_up(mesh, surf.at(i), &tets); bool curls_tot = false; apf::MeshEntity* v = ma::getTriVertOppositeEdge(mesh,surf.at(i),edge); for(int j = 0; j < tets.size(); j++) { mdl = mesh->toModel(tets.at(j)); std::cout << "Tet " << tets.at(j) << " " << mesh->getModelType(mdl) << "c" << mesh->getModelTag(mdl) << std::endl; bool curl_curr = loop.isCurlOk(v,tets.at(j)); std::cout << "Curl:" << curl_curr << std::endl; curls_tot = curls_tot or curl_curr; } curl_ok = curl_ok and curls_tot; } } return curl_ok; } bool chk_ma_swap(apf::Mesh2* m) { MaSwap3Dcheck swap_chk(m); apf::MeshEntity* e; apf::ModelEntity* mdl; std::cout << "Doing swap check for cavityexists crashes" << std::endl; apf::MeshIterator* it = m->begin(1); while ((e = m->iterate(it))) { mdl = m->toModel(e); if(m->getModelType(mdl) == 3) { if(!swap_chk.run(e)) { return false; } } } m->end(it); return true; } bool chk_ma_swap(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) { MaSwap3Dcheck swap_chk(m); apf::ModelEntity* mdl; std::cout << "Doing swap check for cavityexists crashes" << std::endl; std::vector<apf::MeshEntity*> edge(0); vd_set_up(m, &vert_in, &edge); apf::MeshEntity* e; for(int i = 0; i < edge.size(); i++) { e = edge.at(i); mdl = m->toModel(e); if(m->getModelType(mdl) == 3) { if(!swap_chk.run(e)) { return false; } } } return true; } bool chk_ma_swap_all(apf::Mesh2* m) { MaSwap3Dcheck swap_chk(m); apf::MeshEntity* e; apf::ModelEntity* mdl; std::cout << "Doing swap check for cavityexists crashes" << std::endl; bool curl_ok = true; apf::MeshIterator* it = m->begin(1); while ((e = m->iterate(it))) { mdl = m->toModel(e); if(m->getModelType(mdl) == 3) { bool curl_curr = swap_chk.run_all_surf(e); curl_ok = curl_ok and curl_curr; } } m->end(it); return curl_ok; } bool chk_ma_swap_all(apf::Mesh2* m, std::vector<apf::MeshEntity*> &vert_in) { MaSwap3Dcheck swap_chk(m); apf::ModelEntity* mdl; std::cout << "Doing swap check for cavityexists crashes" << std::endl; bool curl_ok = true; std::vector<apf::MeshEntity*> edge(0); vd_set_up(m, &vert_in, &edge); apf::MeshEntity* e; for(int i = 0; i < edge.size(); i++) { e = edge.at(i); mdl = m->toModel(e); if(m->getModelType(mdl) == 3) { bool curl_curr = swap_chk.run_all_surf(e); curl_ok = curl_ok and curl_curr; } } return curl_ok; } // Given an ma::Input, replace the old size field. void repl_sz_field(ma::Input* in, apf::Mesh2* m, MA_SIZE_TYPE MA_T) { if(MA_T == MA_SIZE_TYPE::EDGE_COL) { delete in->sizeField; ModelEdgeCollapse* ref = new ModelEdgeCollapse(m); in->sizeField = ref; } else if(MA_T == MA_SIZE_TYPE::EDGE_SPLIT) { delete in->sizeField; ModelEdgeSplit* ref = new ModelEdgeSplit(m); in->sizeField = ref; } else if(MA_T == MA_SIZE_TYPE::EDGE_REFINER) { delete in->sizeField; ModelEdgeRefiner* ref = new ModelEdgeRefiner(m); in->sizeField = ref; } else { assert(MA_T == MA_SIZE_TYPE::EDGE_REF_DIST); delete in->sizeField; ModelEdgeRefinerDist* ref = new ModelEdgeRefinerDist(m); in->sizeField = ref; } } void vd_ma_input::set_def() { maximumIterations = 3; shouldCoarsen = true; shouldFixShape = true; shouldForceAdaptation = false; shouldPrintQuality = true; goodQuality = 0.027; maximumEdgeRatio = 2.0; shouldCheckQualityForDoubleSplits = false; validQuality = 1e-10; maximumImbalance = 1.10; shouldRunPreZoltan = false; shouldRunPreZoltanRib = false; shouldRunPreParma = false; shouldRunMidZoltan = false; shouldRunMidParma = false; shouldRunPostZoltan = false; shouldRunPostZoltanRib = false; shouldRunPostParma = false; shouldTurnLayerToTets = false; shouldCleanupLayer = false; shouldRefineLayer = false; shouldCoarsenLayer = false; splitAllLayerEdges = false; } void vd_ma_input::flip_template(INPUT_TYPE IT_IN) { assert(IT_IN < INPUT_TYPE::END); if(IT_IN == INPUT_TYPE::ADAPT_SPLIT) { shouldRefineLayer = true; } else if(IT_IN == INPUT_TYPE::ADAPT_COL) { shouldRunPreZoltan = false; shouldRunMidParma = false; shouldRunPostParma = false; shouldRefineLayer = false; shouldCoarsen = true; shouldCoarsenLayer = true; shouldFixShape = false; } else { assert(IT_IN == INPUT_TYPE::ADAPT_Q); shouldRunPreZoltan = true; shouldRunMidParma = true; shouldRunPostParma = true; shouldRefineLayer = true; shouldFixShape = true; } } void vd_ma_input::set_template(INPUT_TYPE IT_IN) { set_def(); flip_template(IT_IN); } // Get the input fields from ma::Input. void vd_ma_input::get_input(ma::Input* in) { maximumIterations = in->maximumIterations; shouldCoarsen = in->shouldCoarsen; shouldFixShape = in->shouldFixShape; shouldForceAdaptation = in->shouldForceAdaptation; shouldPrintQuality = in->shouldPrintQuality; goodQuality = in->goodQuality; maximumEdgeRatio = in->maximumEdgeRatio; shouldCheckQualityForDoubleSplits = in->shouldCheckQualityForDoubleSplits; validQuality = in->validQuality; maximumImbalance = in->maximumImbalance; shouldRunPreZoltan = in->shouldRunPreZoltan; shouldRunPreZoltanRib = in->shouldRunPreZoltanRib; shouldRunPreParma = in->shouldRunPreParma; shouldRunMidZoltan = in->shouldRunMidZoltan; shouldRunMidParma = in->shouldRunMidParma; shouldRunPostZoltan = in->shouldRunPostZoltan; shouldRunPostZoltanRib = in->shouldRunPostZoltanRib; shouldRunPostParma = in->shouldRunPostParma; shouldTurnLayerToTets = in->shouldTurnLayerToTets; shouldCleanupLayer = in->shouldCleanupLayer; shouldRefineLayer = in->shouldRefineLayer; shouldCoarsenLayer = in->shouldCoarsenLayer; splitAllLayerEdges = in->splitAllLayerEdges; } // Transfer the input fields to ma::Input. void vd_ma_input::set_input(ma::Input* in) { in->maximumIterations = maximumIterations; in->shouldCoarsen = shouldCoarsen; in->shouldFixShape = shouldFixShape; in->shouldForceAdaptation = shouldForceAdaptation; in->shouldPrintQuality = shouldPrintQuality; in->goodQuality = goodQuality; in->maximumEdgeRatio = maximumEdgeRatio; in->shouldCheckQualityForDoubleSplits = shouldCheckQualityForDoubleSplits; in->validQuality = validQuality; in->maximumImbalance = maximumImbalance; in->shouldRunPreZoltan = shouldRunPreZoltan; in->shouldRunPreZoltanRib = shouldRunPreZoltanRib; in->shouldRunPreParma = shouldRunPreParma; in->shouldRunMidZoltan = shouldRunMidZoltan; in->shouldRunMidParma = shouldRunMidParma; in->shouldRunPostZoltan = shouldRunPostZoltan; in->shouldRunPostZoltanRib = shouldRunPostZoltanRib; in->shouldRunPostParma = shouldRunPostParma; in->shouldTurnLayerToTets = shouldTurnLayerToTets; in->shouldCleanupLayer = shouldCleanupLayer; in->shouldRefineLayer = shouldRefineLayer; in->shouldCoarsenLayer = shouldCoarsenLayer; in->splitAllLayerEdges = splitAllLayerEdges; } // Copy constructor vd_ma_input::vd_ma_input(const vd_ma_input& that) { maximumIterations = that.maximumIterations; shouldCoarsen = that.shouldCoarsen; shouldFixShape = that.shouldFixShape; shouldForceAdaptation = that.shouldForceAdaptation; shouldPrintQuality = that.shouldPrintQuality; goodQuality = that.goodQuality; maximumEdgeRatio = that.maximumEdgeRatio; shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits; validQuality = that.validQuality; maximumImbalance = that.maximumImbalance; shouldRunPreZoltan = that.shouldRunPreZoltan; shouldRunPreZoltanRib = that.shouldRunPreZoltanRib; shouldRunPreParma = that.shouldRunPreParma; shouldRunMidZoltan = that.shouldRunMidZoltan; shouldRunMidParma = that.shouldRunMidParma; shouldRunPostZoltan = that.shouldRunPostZoltan; shouldRunPostZoltanRib = that.shouldRunPostZoltanRib; shouldRunPostParma = that.shouldRunPostParma; shouldTurnLayerToTets = that.shouldTurnLayerToTets; shouldCleanupLayer = that.shouldCleanupLayer; shouldRefineLayer = that.shouldRefineLayer; shouldCoarsenLayer = that.shouldCoarsenLayer; splitAllLayerEdges = that.splitAllLayerEdges; } // Copy vd_ma_input& vd_ma_input::operator=(const vd_ma_input& that) { maximumIterations = that.maximumIterations; shouldCoarsen = that.shouldCoarsen; shouldFixShape = that.shouldFixShape; shouldForceAdaptation = that.shouldForceAdaptation; shouldPrintQuality = that.shouldPrintQuality; goodQuality = that.goodQuality; maximumEdgeRatio = that.maximumEdgeRatio; shouldCheckQualityForDoubleSplits = that.shouldCheckQualityForDoubleSplits; validQuality = that.validQuality; maximumImbalance = that.maximumImbalance; shouldRunPreZoltan = that.shouldRunPreZoltan; shouldRunPreZoltanRib = that.shouldRunPreZoltanRib; shouldRunPreParma = that.shouldRunPreParma; shouldRunMidZoltan = that.shouldRunMidZoltan; shouldRunMidParma = that.shouldRunMidParma; shouldRunPostZoltan = that.shouldRunPostZoltan; shouldRunPostZoltanRib = that.shouldRunPostZoltanRib; shouldRunPostParma = that.shouldRunPostParma; shouldTurnLayerToTets = that.shouldTurnLayerToTets; shouldCleanupLayer = that.shouldCleanupLayer; shouldRefineLayer = that.shouldRefineLayer; shouldCoarsenLayer = that.shouldCoarsenLayer; splitAllLayerEdges = that.splitAllLayerEdges; } vd_ma_input::vd_ma_input() : maximumIterations(3), shouldCoarsen(true), shouldFixShape(true), shouldForceAdaptation(false), shouldPrintQuality(true), goodQuality(0.027), maximumEdgeRatio(2.0), shouldCheckQualityForDoubleSplits(false), validQuality(1e-10), maximumImbalance(1.10), shouldRunPreZoltan(false), shouldRunPreZoltanRib(false), shouldRunPreParma(false), shouldRunMidZoltan(false), shouldRunMidParma(false), shouldRunPostZoltan(false), shouldRunPostZoltanRib(false), shouldRunPostParma(false), shouldTurnLayerToTets(false), shouldCleanupLayer(false), shouldRefineLayer(false), shouldCoarsenLayer(false), splitAllLayerEdges(false) { } vd_ma_input::~vd_ma_input() {} vd_input_iso::vd_input_iso() { } /* // A wrapper for ma::Input object with common predefined use cases. // Using INPUT_TYPE flags as input, the input flags can be set for a certain // option, or the flags associated with a INPUT_TYPE can be flipped. vd_input_iso::vd_input_iso(apf::Mesh2* m, ma::IsotropicFunction* sf, ma::IdentitySizeField* ref) : in(NULL) { in = ma::configure(m, sf); if(ref != NULL) { delete in->sizeField; in->sizeField = ref; } in->shouldRunPreZoltan = true; in->shouldRunMidParma = true; in->shouldRunPostParma = true; in->shouldRefineLayer = true; in->shouldCoarsenLayer = true; in->shouldFixShape = true; in->goodQuality = 0.2; in->validQuality = 10e-5; std::cout << "Minimum quality is " << in->validQuality << ", good quality is " << in->goodQuality << std::endl; in->maximumEdgeRatio = 12; in->maximumIterations = 3; } */ //void vd_input_iso::set_valid(double v_in) { // in->validQuality = v_in; // std::cout << "Set valid quality to " << in->validQuality // << std::endl; //} //void vd_input_iso::set_good(double g_in) { // in->goodQuality = g_in; // std::cout << "Set good quality to " << in->goodQuality // << std::endl; //} vd_input_iso::~vd_input_iso() { } //void vd_input_iso::set_sizefield(ma::IdentitySizeField* ref) { // assert(ref != NULL); // delete in->sizeField; // in->sizeField = ref; //} void vd_input_iso::set_input(std::vector<INPUT_TYPE> &IT_IN) { IT = IT_IN; } //ma::Input* vd_input_iso::get_input() { // return in; //} // Container for keeping calculations of distances of a given stratum vertices // from its bounding strata. Calculates for bounding 2s for 3c, 1s for 2s and // 0s for 1s. // Set the cell for the distances to be calculated: void DistBurner::set_cell(int d_in, int id_in, apf::Mesh2* m_in, vd_entlist & e_list, cell_base* c_base_in, double len) { clear(); c_dim = d_in; c_id = id_in; sim_len = len; m = m_in; c_base = c_base_in; collect_adj(e_list); burn_dist(); //consider the distance to entity centers, in addition to vertices. } // Collect adjacencies: void DistBurner::collect_adj(vd_entlist & e_list) { assert(e_list.e.at(c_dim).at(c_id).at(c_dim).size() > 0); front.reserve(e_list.e.at(c_dim).at(c_id).at(c_dim).size()); // Link the downward adjacencies of the same dimensional entities of the // calculated stratum to it's entities of one dimension lower. int d_lower = c_dim - 1; apf::Downward d_e; for(int i = 0; i < e_list.e.at(c_dim).at(c_id).at(c_dim).size(); i++) { apf::MeshEntity* e_curr = e_list.e.at(c_dim).at(c_id).at(c_dim).at(i); m->getDownward(e_curr, d_lower, d_e); for(int j = 0; j < c_dim + 1; j++) { if(e_map1[d_e[j]] == NULL) { e_map1[d_e[j]] = e_curr; } else { assert(e_map2[d_e[j]] == NULL); e_map2[d_e[j]] = e_curr; } } } ent_conn* edown = new ent_conn(); c_base->get_conn(c_dim, c_id, edown); // TODO for now, assume no ring-like strata. In future, consider the distance // from the weighted center. assert(edown->conn.size() > 0); // Collect the geometric information about boundary entities. int lookup_tet_x_surf [4] = {3, 2, 0, 1}; int lookup_v_tri_x_e [3] = {2,0,1}; apf::Vector3 temp(0,0,0); apf::Downward d_v; apf::Up up; for(int c_down = 0; c_down < e_list.e.at(d_lower).size(); c_down++) { if(e_list.e.at(d_lower).at(c_down).at(d_lower).size() > 0) { // Walk over downward adjancency lists: for(int i = 0; i < e_list.e.at(d_lower).at(c_down).at(d_lower).size(); i++) { apf::MeshEntity* e_curr = e_list.e.at(d_lower).at(c_down) .at(d_lower).at(i); m->getUp(e_curr, up); // The geometric information is assigned. Used in lower dim boundary // entities to prevent spurious assignment. std::map<apf::MeshEntity*, bool> asgn{}; bool found = false; for(int j = 0; j < up.n; j++) { apf::ModelEntity* mdl = m->toModel(up.e[j]); int d_up = m->getModelType(mdl); int id_up = m->getModelTag(mdl) - 1; if(d_up == c_dim and id_up == c_id) { assert(!found); found = true; front.push_back(up.e[j]); m->getDownward(up.e[j], d_lower, d_e); int e1 = findIn(d_e, c_dim+1, e_curr); // Collecting entities bounding a 1cell: if(d_lower == 0) { // The information about the bounding vertex is collected: m->getPoint(e_curr, 0, temp); v_pos[e_curr] = temp; asgn[e_curr] = true; // The vertex of the front entity is collected: int v1 = (e1 + 1) % 2; v_map[up.e[j]] = d_e[v1]; v_id[up.e[j]] = v1; m->getPoint(d_e[v1], 0, temp); v_pos[d_e[v1]] = temp; } // Collecting entities bounding a 2cell: else if(d_lower == 1) { // The vertex of the front entity is collected: m->getDownward(up.e[j], 0, d_v); int v1 = lookup_v_tri_x_e[e1]; v_map[up.e[j]] = d_v[v1]; v_id[up.e[j]] = v1; // Position of the interior vertex. m->getPoint(d_v[v1], 0, temp); v_pos[d_v[v1]] = temp; // The information about the bounding entities are collected: apf::Vector3 temp2(0,0,0); int v2 = (v1+1)%3; m->getPoint(d_v[v2], 0, temp); v_pos[d_v[v2]] = temp; asgn[d_v[v2]] = true; v2 = (v1+2)%3; m->getPoint(d_v[v2], 0, temp2); v_pos[d_v[v2]] = temp2; asgn[d_v[v2]] = true; e_pos[e_curr] = temp; e_dir[e_curr] = norm_0(temp2 - temp); asgn[e_curr] = true; } else { // The vertex of the front entity is collected: m->getDownward(up.e[j], 0, d_v); int v1 = lookup_tet_x_surf[e1]; v_map[up.e[j]] = d_v[v1]; v_id[up.e[j]] = v1; // Position of the interior vertex. m->getPoint(d_v[v1], 0, temp); v_pos[d_v[v1]] = temp; // The information about the bounding entities are collected: t_pos[e_curr] = apf::Vector3(0,0,0); for(int k = 0; k < 3; k++) { int v2 = (v1+k+1)%4; m->getPoint(d_v[v2], 0, temp); v_pos[d_v[v2]] = temp; asgn[d_v[v2]] = true; t_pos[e_curr] = t_pos[e_curr] + temp; } m->getPoint(d_v[v1], 0, temp); t_dir[e_curr] = vd_area_out_n(m, e_curr); if((temp - t_pos[e_curr])*t_dir[e_curr] < - std::numeric_limits<double>::min()) t_dir[e_curr] = t_dir[e_curr]*(-1); m->getDownward(e_curr, 1, d_e); for(int k = 0; k < 3; k++) { m->getDownward(d_e[k], 0, d_v); assert(asgn[d_v[0]]); assert(asgn[d_v[1]]); m->getPoint(d_v[0], 0, temp); e_pos[d_e[k]] = temp; m->getPoint(d_v[1], 0, temp); e_dir[d_e[k]] = norm_0(temp - e_pos[d_e[k]]); asgn[d_e[k]] = true; } } } } assert(found); } } } delete edown; } // Starting from the current entity on the front and moving over the // adjacent entities, find the smallest distance boundary element // reachable from the starting element for the vertex associated // with the starting entity. void DistBurner::calc_v_3c(apf::MeshEntity* tet) { apf::Downward d_v; /* apf::Vector3 int_pt(0,0,0); apf::MeshEntity* last; apf::MeshEntity* next; next = tri_proj_v(v_map[tet], last, int_pt); if(last == next) */ } void DistBurner::calc_v_2c(apf::MeshEntity* tri) { } void DistBurner::calc_v_1c(apf::MeshEntity* edge) { } // Starting from given triangle, return the entity the closest projection of // the vertex onto the boundary lies on. If the projection is on the triangle, // return the intersection point. apf::MeshEntity* DistBurner::tri_proj_v(apf::MeshEntity* v, apf::MeshEntity* tri, apf::Vector3& int_pt) { apf::MeshEntity* ent = tri; apf::Vector3 temp1(0,0,0); apf::Vector3 temp2(0,0,0); apf::Vector3 edir(0,0,0); apf::Vector3 epos(0,0,0); int_pt = v_pos[v] - t_pos[tri]; int_pt = int_pt - t_dir[tri]*(int_pt*t_dir[tri]) + t_pos[tri]; for(int i = 0; i < 3; i++) { edir = e_dir[e_d[tri].at(i)]; epos = e_pos[e_d[tri].at(i)]; temp1 = (int_pt - epos); temp1 = temp1 - edir*(temp1*edir); temp2 = (t_pos[tri] - epos); temp2 = temp2 - edir*(temp2*edir); // If outside get the first edge that the projection lies outside of. if( temp1*temp2 < - std::numeric_limits<double>::min()) { //std::cout << "v1v2 - t_pos[tri]" << temp1*temp2 << std::endl; if(e_map1[e_d[tri].at(i)] == tri) ent = e_map2[e_d[tri].at(i)]; else { assert(e_map2[e_d[tri].at(i)] == tri); ent = e_map1[e_d[tri].at(i)]; } i = 3; } } return ent; } // Calculate the distance from the vertex to a given entity. double DistBurner::calc_d_tri(apf::MeshEntity* v, apf::MeshEntity* tri) { } double DistBurner::calc_d_edge(apf::MeshEntity* v, apf::MeshEntity* edge) { } double DistBurner::calc_d_vert(apf::MeshEntity* v, apf::MeshEntity* vert) { apf::Downward d_v; } // Burn the vertices below (1+dist_tol)*dist_min distance from the boundary // remove the burnt entities in the front and add new ones. void DistBurner::step_front() { } // Run step_front until the front is empty. void DistBurner::burn_dist() { /* dist_max = sim_len; while(front.size() > 0) { // The end burnt number of tets are burnt and not to be considered. int burnt = 0; double dist_min = sim_len; for(int i = 0; i < front.size() - burnt; i++) { apf::MeshEntity* t_curr = front.at(i); assert(!t_burn[t_curr]); m->getDownward(t_curr, 0, d_v); bool found = false; for(int j = 0; j < 4; j++) { if(!v_burn[d_v[j]]) { assert(!found); found = true; v_map[t_curr] = d_v[j]; v_id[t_curr] = j; } } assert(found); t_dist[t_curr] = approx_dist(m, v_dist, d_v, v_map[t_curr]); if(t_dist[t_curr] < v_dist[v_map[t_curr]]) { v_dist[v_map[t_curr]] = t_dist[t_curr]; if(v_dist[v_map[t_curr]] < dist_min) dist_min = v_dist[v_map[t_curr]]; } } int added = 0; double dist_th = dist_min*(1+dist_tol); for(int i = 0; i < front.size() - burnt - added; i++) { apf::MeshEntity* t_curr = front.at(i); if(v_dist[v_map[t_curr]] < dist_th) { v_burn[v_map[t_curr]] = true; } } for(int i = 0; i < front.size() - burnt - added; i++) { apf::MeshEntity* t_curr = front.at(i); assert(tv_id[t_curr] > -1); assert(v_map[t_curr] != NULL); if(v_dist[v_map[t_curr]] < dist_th) { m->getDownward(t_curr, 2, d_t); int v_id = tv_id[t_curr]; for(int j = 0; j < 3; j++) { int t_id = lookup_tet_surf[v_id][j]; apf::MeshEntity* tri_curr = d_t[t_id]; m->getUp(tri_curr, up); if(up.n == 2) { apf::MeshEntity* t_next; if(up.e[0] == t_curr) t_next = up.e[1]; else t_next = up.e[0]; if(!t_burn[t_next]) { int t1 = findIn(&front, front.size(), t_next); if(t1 == -1) { m->getDownward(t_next, 0, d_v); bool found1 = false; bool found2 = false; for(int j = 0; j < 4; j++) { if(!v_burn[d_v[j]]) { if(found1) found2 = true; else found1 = true; } } assert(!found2); if(found1) { if(burnt > 0) { int i_b = front.size() - burnt; assert(!t_burn[front.at(i_b-1)]); assert(t_burn[front.at(i_b)]); front.push_back(front.at(i_b)); front.at(i_b) = t_next; //m->getDownward(t_next, 2, d_t2); //int t2 = findIn(d_t2, 4, tri_curr); //assert(t2 > -1); //v_map[t_next] = d_v[lookup_tet_surf_x[t2]]; //t_dist[t_next] = approx_dist(m, v_dist, d_v, // v_map[t_curr]); } else front.push_back(t_next); tv_id[t_next] = -1; v_map[t_next] = NULL; added = added + 1; } else { t_burn[t_next] = true; } } } } } t_burn[t_curr] = true; int i_ub = front.size() - burnt - added - 1; int i_ad = front.size() - burnt - 1; if(i_ub != i) assert(!t_burn[front.at(i_ub)]); if(added > 0) assert(!t_burn[front.at(i_ub+1)]); if(burnt > 0) assert(t_burn[front.at(i_ub+added+1)]); front.at(i) = front.at(i_ub); front.at(i_ub) = front.at(i_ad); front.at(i_ad) = t_curr; burnt = burnt + 1; i = i-1; } } front.resize(front.size() - burnt); } */ } void DistBurner::clear() { v_pos.clear(); e_pos.clear(); t_pos.clear(); e_dir.clear(); t_dir.clear(); v_dist.clear(); front.clear(); burn_curr.clear(); e_d.clear(); e_v.clear(); v_map.clear(); v_id.clear(); e_map1.clear(); e_map2.clear(); b_map.clear(); } DistBurner::DistBurner() : m(NULL), v_pos{}, e_pos{}, t_pos{}, e_dir{}, t_dir{}, v_dist{}, burn_curr{}, front(0), e_d{}, e_v{}, v_map{}, v_id{}, e_map1{}, e_map2{}, b_map{} { } DistBurner::~DistBurner() { clear(); } ModelEdgeRefiner::ModelEdgeRefiner(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) { } bool ModelEdgeRefiner::shouldCollapse(ma::Entity* edge) { int dim_e = mesh->getModelType(mesh->toModel(edge)); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return true; return false; } bool ModelEdgeRefiner::shouldSplit(ma::Entity* edge) { apf::Downward d_v; mesh->getDownward(edge, 0, d_v); int dim_e = mesh->getModelType(mesh->toModel(edge)); int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0])); int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1])); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return false; else if(dim_e > dim_v0 and dim_e > dim_v1) { if(dim_e == 1) return true; else if(split_all) return true; } return false; } ModelEdgeRefiner::~ModelEdgeRefiner() { for(int i = 0; i < 3; i++) { coarse_map.at(i).clear(); } coarse_map.clear(); } ModelEdgeRefinerDist::ModelEdgeRefinerDist(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false), split_target(1.5), coarse_target(0.5) { field_step = m->findField("adapt_step"); assert(field_step != NULL); } double ModelEdgeRefinerDist::measure_dist(ma::Entity* edge) { // TODO Use integrators of apf to integrate the field directly. For linear // elements and for isotropic metrics, it is equivalent. apf::MeshElement* me = apf::createMeshElement(mesh, edge); double len = measure(edge); apf::destroyMeshElement(me); apf::Downward d_v; mesh->getDownward(edge, 0, d_v); double dist = apf::getScalar(field_step, d_v[0], 0); dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2; assert(dist > std::numeric_limits<double>::min()); //return average*dist*sizing; return len*dist; } bool ModelEdgeRefinerDist::shouldCollapse(ma::Entity* edge) { int dim_e = mesh->getModelType(mesh->toModel(edge)); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return true; return this->measure_dist(edge) < coarse_target; } bool ModelEdgeRefinerDist::shouldSplit(ma::Entity* edge) { apf::Downward d_v; mesh->getDownward(edge, 0, d_v); int dim_e = mesh->getModelType(mesh->toModel(edge)); int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0])); int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1])); //double v0 = apf::getScalar(field_step, d_v[0], 0); //double v1 = apf::getScalar(field_step, d_v[1], 0); //double len = vd_meas_ent(mesh, edge); //return (1 > v0) or (1 > v1); //return (2*len > v0) or (2*len > v1); //return (len > v0/4+v1/4); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return false; //else if(dim_e == 1 and dim_e > dim_v0 and dim_e > dim_v1) else if(dim_e > dim_v0 and dim_e > dim_v1) { if(dim_e == 1) return true; else if(split_all) return true; } return this->measure_dist(edge) > split_target; //else if } void ModelEdgeRefinerDist::set_target_th(double coarse_in, double split_in) { split_target = split_in; coarse_target = coarse_in; } ModelEdgeRefinerDist::~ModelEdgeRefinerDist() { for(int i = 0; i < 3; i++) { coarse_map.at(i).clear(); } coarse_map.clear(); } ModelEdgeCollapse::ModelEdgeCollapse(ma::Mesh* m) : coarse_map{}, IdentitySizeField(m) { } bool ModelEdgeCollapse::shouldCollapse(ma::Entity* edge) { int dim_e = mesh->getModelType(mesh->toModel(edge)); if(coarse_map[edge]) return true; return false; } bool ModelEdgeCollapse::shouldSplit(ma::Entity* edge) { return false; } ModelEdgeCollapse::~ModelEdgeCollapse() { coarse_map.clear(); } ModelEdgeSplit::ModelEdgeSplit(ma::Mesh* m) : split_map{}, IdentitySizeField(m) { } bool ModelEdgeSplit::shouldCollapse(ma::Entity* edge) { return false; } bool ModelEdgeSplit::shouldSplit(ma::Entity* edge) { if(split_map[edge]) return true; return false; } ModelEdgeSplit::~ModelEdgeSplit() { split_map.clear(); } ///////////////////////////////////// // ModelEdgeRefinerGrain ///////////////////////////////////// ModelEdgeRefinerGrain::ModelEdgeRefinerGrain(ma::Mesh* m) : coarse_map(3, std::map<int, bool> {}), IdentitySizeField(m), split_all(false) { field_step = m->findField("adapt_step"); assert(field_step != NULL); } double ModelEdgeRefinerGrain::measure_dist(ma::Entity* edge) { // TODO Use integrators of apf to integrate the field directly. For linear // elements and for isotropic metrics, it is equivalent. apf::MeshElement* me = apf::createMeshElement(mesh, edge); double len = measure(edge); apf::destroyMeshElement(me); apf::Downward d_v; mesh->getDownward(edge, 0, d_v); double dist = apf::getScalar(field_step, d_v[0], 0); dist = (dist + apf::getScalar(field_step, d_v[1], 0))/2; assert(dist > std::numeric_limits<double>::min()); //return average*dist*sizing; return len*dist; } bool ModelEdgeRefinerGrain::shouldCollapse(ma::Entity* edge) { int dim_e = mesh->getModelType(mesh->toModel(edge)); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return true; return this->measure_dist(edge) < 0.5; } bool ModelEdgeRefinerGrain::shouldSplit(ma::Entity* edge) { apf::Downward d_v; mesh->getDownward(edge, 0, d_v); int dim_e = mesh->getModelType(mesh->toModel(edge)); int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0])); int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1])); //double v0 = apf::getScalar(field_step, d_v[0], 0); //double v1 = apf::getScalar(field_step, d_v[1], 0); //double len = vd_meas_ent(mesh, edge); //return (1 > v0) or (1 > v1); //return (2*len > v0) or (2*len > v1); //return (len > v0/4+v1/4); if(coarse_map.at(dim_e - 1)[mesh->getModelTag(mesh->toModel(edge))]) return false; else if(dim_e > dim_v0 and dim_e > dim_v1) { if(dim_e == 1) return true; else if(split_all) return true; } return this->measure_dist(edge) > 1.5; //else if } ModelEdgeRefinerGrain::~ModelEdgeRefinerGrain() { for(int i = 0; i < 3; i++) { coarse_map.at(i).clear(); } coarse_map.clear(); } ///////////////////////////////////// // ModelEdgeRefinerVarying ///////////////////////////////////// ModelEdgeRefinerVarying::ModelEdgeRefinerVarying(ma::Mesh* m) : len_map(3, std::map<int, double> {}), rat_map(3, std::map<int, double> {}), IdentitySizeField(m), split_target(1.5), coarse_target(0.5) { gmi_model* mdl = m->getModel(); struct gmi_iter* it_gmi; struct gmi_ent* e_gmi; struct gmi_set* s_gmi; apf::MeshEntity* e; for(int dim = 1; dim < 4; dim++) { apf::MeshIterator* it = m->begin(dim); while ((e = m->iterate(it))) { apf::ModelEntity* mdl_curr = m->toModel(e); int c_type = m->getModelType(mdl_curr); int c_tag = m->getModelTag(mdl_curr); double meas_curr = vd_meas_ent(m, e); len_map.at(c_type - 1)[c_tag] = len_map.at(c_type - 1)[c_tag] + meas_curr; } m->end(it); } double pow[3] = {1., 0.5, 1.0/3}; double coef[3] = {1./2, 1./8, 1./16}; for(int dim = 1; dim < 4; dim++) { it_gmi = gmi_begin(mdl, dim); while ((e_gmi = gmi_next(mdl, it_gmi))) { int c_tag = gmi_tag(mdl,e_gmi); len_map.at(dim - 1)[c_tag] = std::pow(len_map.at(dim - 1)[c_tag]*coef[dim-1], pow[dim-1]); rat_map.at(dim - 1)[c_tag] = 1; } gmi_end(mdl, it_gmi); } } // Set the rat_map for boundary cells such that they are refined to yield edge // length len. void ModelEdgeRefinerVarying::set_all_cell(double len) { gmi_model* mdl = mesh->getModel(); struct gmi_iter* it_gmi; struct gmi_ent* e_gmi; struct gmi_set* s_gmi; for(int dim = 1; dim < 4; dim++) { it_gmi = gmi_begin(mdl, dim); while ((e_gmi = gmi_next(mdl, it_gmi))) { int c_tag = gmi_tag(mdl,e_gmi); rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len; } gmi_end(mdl, it_gmi); } } // Set the rat_map for boundary cells such that they are refined to yield edge // length len. void ModelEdgeRefinerVarying::set_bound_cell(double len, std::vector<std::pair<int,int> >* cells) { if(cells != NULL) { for(int i = 0; i < cells->size(); i++) { int dim = cells->at(i).first; int c_tag = cells->at(i).second; rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len; } } else { gmi_model* mdl = mesh->getModel(); struct gmi_iter* it_gmi; struct gmi_ent* e_gmi; struct gmi_set* s_gmi; for(int dim = 1; dim < 3; dim++) { it_gmi = gmi_begin(mdl, dim); while ((e_gmi = gmi_next(mdl, it_gmi))) { int c_tag = gmi_tag(mdl,e_gmi); rat_map.at(dim - 1)[c_tag] = len_map.at(dim - 1)[c_tag]/len; } gmi_end(mdl, it_gmi); } } } double ModelEdgeRefinerVarying::measure_dist(ma::Entity* edge) { // TODO Use integrators of apf to integrate the field directly. For linear // elements and for isotropic metrics, it is equivalent. apf::MeshElement* me = apf::createMeshElement(mesh, edge); double len = measure(edge); apf::destroyMeshElement(me); apf::ModelEntity* mdl = mesh->toModel(edge); int dim_e = mesh->getModelType(mdl); int tag_e = mesh->getModelTag(mdl); if(len_map.at(dim_e - 1)[tag_e] < std::numeric_limits<double>::min()) return len; return len/len_map.at(dim_e - 1)[tag_e]*rat_map.at(dim_e - 1)[tag_e]; } bool ModelEdgeRefinerVarying::shouldCollapse(ma::Entity* edge) { return this->measure_dist(edge) < coarse_target; } bool ModelEdgeRefinerVarying::shouldSplit(ma::Entity* edge) { apf::Downward d_v; mesh->getDownward(edge, 0, d_v); int dim_e = mesh->getModelType(mesh->toModel(edge)); int dim_v0 = mesh->getModelType(mesh->toModel(d_v[0])); int dim_v1 = mesh->getModelType(mesh->toModel(d_v[1])); //double v0 = apf::getScalar(field_step, d_v[0], 0); //double v1 = apf::getScalar(field_step, d_v[1], 0); //double len = vd_meas_ent(mesh, edge); //return (1 > v0) or (1 > v1); //return (2*len > v0) or (2*len > v1); //return (len > v0/4+v1/4); if(dim_e > dim_v0 and dim_e > dim_v1) { if(dim_e == 1) return true; } return this->measure_dist(edge) > split_target; } void ModelEdgeRefinerVarying::set_target_th(double coarse_in, double split_in) { split_target = split_in; coarse_target = coarse_in; } ModelEdgeRefinerVarying::~ModelEdgeRefinerVarying() { for(int i = 0; i < 3; i++) { len_map.at(i).clear(); } len_map.clear(); } //////////////////////////// // STEP //////////////////////////// Step::Step(ma::Mesh* m, double sz) { if(sz > std::numeric_limits<double>::min()) sizing = sz; else sizing = 1; mesh = m; average = ma::getAverageEdgeLength(m); field_step = m->findField("adapt_step"); assert(field_step); } double Step::getValue(ma::Entity* v) { double dist = apf::getScalar(field_step, v, 0); assert(dist > std::numeric_limits<double>::min()); //return average*dist*sizing; return dist/sizing; } Step_ns::Step_ns(ma::Mesh* m, double sz) { if(sz > std::numeric_limits<double>::min()) sizing = sz; else sizing = 1; mesh = m; average = ma::getAverageEdgeLength(m); field_step = m->findField("adapt_step"); assert(field_step); } double Step_ns::getValue(ma::Entity* v) { double dist = apf::getScalar(field_step, v, 0); assert(dist > std::numeric_limits<double>::min()); //return average*dist*sizing; return dist; } void vd_adapt_0cell(apf::Mesh2* m, struct cell_base* c) { std::vector<double> avg_cell(0); avg_cell = upd_cell_rad(m); Linear_0cell sf(m, c, &avg_cell); ma::Input* in = ma::configure(m, &sf); in->shouldRunPreZoltan = true; in->shouldRunMidParma = true; in->shouldRunPostParma = true; in->shouldRefineLayer = true; ma::adapt(in); } void vd_adapt(apf::Mesh2* m) { Linear sf(m, 1.1); ma::Input* in = ma::configure(m, &sf); in->shouldRunPreZoltan = true; in->shouldRunMidParma = true; in->shouldRunPostParma = true; in->shouldRefineLayer = true; ma::adapt(in); } Linear_0cell::Linear_0cell(ma::Mesh* m, struct cell_base* c, std::vector<double>* avg_cell_in) : mesh(NULL), average(0), avg_cell(0), cell0(0), cell0_pos(0, apf::Vector3(0, 0, 0)), cnc0(0, std::vector<std::vector<int > > (0, std::vector<int >(0) ) ) { avg_cell = *avg_cell_in; mesh = m; c_base = c; refresh(); } void Linear_0cell::reload(ma::Mesh* m, struct cell_base* c, std::vector<double>* avg_cell_in) { avg_cell = *avg_cell_in; mesh = m; c_base = c; refresh(); } double Linear_0cell::getValue(ma::Entity* v) { return getDistance(v); //return getDistance(v)*sizing; } double Linear_0cell::getDistance(ma::Entity* v) { double distance = average+1; double temp_len; apf::Vector3 e_pos; apf::Vector3 temp; mesh->getPoint(v, 0, e_pos); int ent_type = mesh->getType(v); int d = mesh->typeDimension[ent_type]; apf::ModelEntity* mdl = mesh->toModel(v); int c_type = mesh->getModelType(mdl); int c_tag = mesh->getModelTag(mdl); //std::cout << c_type << "c" << c_tag << " " // << d << "-ent" << v << std::endl; for(int i = 0; i < cnc0.at(c_type).at(c_tag-1).size(); i++) { int c_id = cnc0.at(c_type).at(c_tag-1).at(i); if(cell0.at(c_id) != NULL) { //std::cout << "v " << cell0.at(c_id) // << " pos " << cell0_pos.at(c_id) << std::endl; temp = e_pos - cell0_pos.at(c_id); temp_len = temp.getLength(); if(distance > temp_len); distance = temp_len; } } if(distance < average) { //if(c_type == 0) return distance*0.7; //else // return distance; //return distance*3; //return average*3; //return average*exp(-average/distance); } else //return avg_cell.at(c_type-1); return avg_cell.at(0)*0.7; //return average; } Linear_0cell::~Linear_0cell() { clear(); } void Linear_0cell::refresh() { clear(); load_0cell(); average = ma::getAverageEdgeLength(mesh); } void Linear_0cell::load_0cell_ent() { cell0_pos.resize(c_base->get_sz(0)); cell0.resize(c_base->get_sz(0)); double z[3] = {0,0,0}; for(int i = 0; i < cell0_pos.size(); i++) { cell0_pos.at(i).fromArray(z); } for(int i = 0; i < cell0.size(); i++) { cell0.at(i) = NULL; } apf::MeshIterator* it_e = mesh->begin(0); //std::cout << "Iterator." << std::endl; apf::MeshEntity* v; while (v = mesh->iterate(it_e)) { apf::ModelEntity* mdl = mesh->toModel(v); int type = mesh->getModelType(mdl); int tag = mesh->getModelTag(mdl); if(type == 0) { assert(cell0.at(tag-1) == NULL); cell0.at(tag-1) = v; } } mesh->end(it_e); } void Linear_0cell::load_0cell_pos() { apf::Vector3 vert_pos; for(int i = 0; i < cell0.size(); i++) { if(cell0.at(i) != NULL) { mesh->getPoint(cell0.at(i), 0, vert_pos); cell0_pos.at(i) = vert_pos; } } } // TODO very ugly notation. void Linear_0cell::load_0cell() { load_0cell_ent(); load_0cell_pos(); cnc0.at(3).resize(c_base->get_sz(3)); cnc0.at(2).resize(c_base->get_sz(2)); cnc0.at(1).resize(c_base->get_sz(1)); cnc0.at(0).resize(c_base->get_sz(0)); struct ent_conn e_cover; int max_sz = 1; for(int i = 0; i < cnc0.at(3).size(); i++) { c_base->get_conn_lower(0, 3, i, &e_cover); cnc0.at(3).at(i).reserve(e_cover.conn.size()); for(int j = 0; j < e_cover.conn.size(); j++) { cnc0.at(3).at(i).push_back(e_cover.conn.at(j)); } if(max_sz < e_cover.conn.size()) max_sz = e_cover.conn.size(); } for(int i = 0; i < cnc0.at(2).size(); i++) { cnc0.at(2).at(i).reserve(2*max_sz); } for(int i = 0; i < cnc0.at(1).size(); i++) { cnc0.at(1).at(i).reserve(7*max_sz); } for(int i = 0; i < cnc0.at(0).size(); i++) { c_base->get_conn_dim(0, 0, i, &e_cover); cnc0.at(0).at(i).reserve(e_cover.conn.size()); for(int j = 0; j < e_cover.conn.size(); j++) { if(i != e_cover.conn.at(j)) cnc0.at(0).at(i).push_back(e_cover.conn.at(j)); } } // Go over 2cell adj. of 3cell, check for 0cell adj of the 3cell in the 0cell // list of the 2cell. for(int i = 0; i < cnc0.at(3).size(); i++) { //std::cout << "3c-" << i + 1 << std::endl; c_base->get_conn_lower(2, 3, i, &e_cover); for(int j = 0; j < e_cover.conn.size(); j++) { //std::cout << "2c-" << e_cover.conn.at(j) + 1 << std::endl; for(int k = 0; k < cnc0.at(3).at(i).size(); k++) { std::vector<int>::iterator c_st; std::vector<int>::iterator c_end; c_st = cnc0.at(2).at(e_cover.conn.at(j)).begin(); c_end = cnc0.at(2).at(e_cover.conn.at(j)).end(); int c0 = cnc0.at(3).at(i).at(k); //std::cout << "0c-" << c0 + 1 << ", " // << (std::find(c_st, c_end, c0) != c_end) << ", "; if(std::find(c_st, c_end, c0) == c_end) { cnc0.at(2).at(e_cover.conn.at(j)).push_back(c0); } } //std::cout << std::endl; } //std::cout << std::endl; c_base->get_conn_lower(1, 3, i, &e_cover); for(int j = 0; j < e_cover.conn.size(); j++) { for(int k = 0; k < cnc0.at(3).at(i).size(); k++) { std::vector<int>::iterator c_st; std::vector<int>::iterator c_end; c_st = cnc0.at(1).at(e_cover.conn.at(j)).begin(); c_end = cnc0.at(1).at(e_cover.conn.at(j)).end(); int c0 = cnc0.at(3).at(i).at(k); if(std::find(c_st, c_end, c0) == c_end) { cnc0.at(1).at(e_cover.conn.at(j)).push_back(c0); } } } } for(int i = 0; i < cnc0.size(); i++) { for(int j = 0; j < cnc0.at(i).size(); j++) { //std::cout << i << "c" << j+1 << std::endl; for(int k = 0; k < cnc0.at(i).at(j).size(); k++) { //std::cout << "0" << "c" << cnc0.at(i).at(j).at(k) + 1 << ", "; } //std::cout << std::endl; } } } void Linear_0cell::clear() { dummy_clear_stop(); cell0_pos.clear(); for(int i = 0; i < cnc0.size(); i++) { for(int j = 0; j < cnc0.at(i).size(); j++) { cnc0.at(i).at(j).clear(); } cnc0.at(i).clear(); } cnc0.clear(); cnc0.resize(4); }
29.662752
201
0.593623
erdemeren
91825db1e52c5f3d5b3aa48752a882d39450bd28
28,923
cpp
C++
Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp
IceLuna/Eagle
3b0d5f014697c97138f160ddd535b1afd6d0c141
[ "Apache-2.0" ]
1
2021-12-10T19:15:25.000Z
2021-12-10T19:15:25.000Z
Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp
IceLuna/Eagle
3b0d5f014697c97138f160ddd535b1afd6d0c141
[ "Apache-2.0" ]
41
2021-08-18T21:32:14.000Z
2022-02-20T11:44:06.000Z
Eagle/src/Eagle/Script/ScriptEngineRegistry.cpp
IceLuna/Eagle
3b0d5f014697c97138f160ddd535b1afd6d0c141
[ "Apache-2.0" ]
null
null
null
#include "egpch.h" #include "ScriptEngineRegistry.h" #include "ScriptEngine.h" #include "ScriptWrappers.h" #include "Eagle/Components/Components.h" #include "Eagle/Core/Entity.h" #include <mono/jit/jit.h> #include <mono/metadata/assembly.h> namespace Eagle { std::unordered_map<MonoType*, std::function<void(Entity&)>> m_AddComponentFunctions; std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_HasComponentFunctions; //SceneComponents std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetWorldTransformFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, const Transform*)>> m_SetRelativeTransformFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetWorldTransformFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, Transform*)>> m_GetRelativeTransformFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetForwardVectorFunctions; //Light Component std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetLightColorFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetLightColorFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetAmbientFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetAmbientFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, const glm::vec3*)>> m_SetSpecularFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, glm::vec3*)>> m_GetSpecularFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetAffectsWorldFunctions; std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_GetAffectsWorldFunctions; //BaseColliderComponent std::unordered_map<MonoType*, std::function<void(Entity&, bool)>> m_SetIsTriggerFunctions; std::unordered_map<MonoType*, std::function<bool(Entity&)>> m_IsTriggerFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetStaticFrictionFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetDynamicFrictionFunctions; std::unordered_map<MonoType*, std::function<void(Entity&, float)>> m_SetBouncinessFrictionFunctions; std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetStaticFrictionFunctions; std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetDynamicFrictionFunctions; std::unordered_map<MonoType*, std::function<float(Entity&)>> m_GetBouncinessFunctions; extern MonoImage* s_CoreAssemblyImage; #define REGISTER_COMPONENT_TYPE(Type)\ {\ MonoType* type = mono_reflection_type_from_name("Eagle." #Type, s_CoreAssemblyImage);\ if (type)\ {\ m_HasComponentFunctions[type] = [](Entity& entity) { return entity.HasComponent<Type>(); };\ m_AddComponentFunctions[type] = [](Entity& entity) { entity.AddComponent<Type>(); };\ \ if (std::is_base_of<SceneComponent, Type>::value)\ {\ m_SetWorldTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetWorldTransform(*transform); };\ m_SetRelativeTransformFunctions[type] = [](Entity& entity, const Transform* transform) { ((SceneComponent&)entity.GetComponent<Type>()).SetRelativeTransform(*transform); };\ \ m_GetWorldTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetWorldTransform(); };\ m_GetRelativeTransformFunctions[type] = [](Entity& entity, Transform* transform) { *transform = ((SceneComponent&)entity.GetComponent<Type>()).GetRelativeTransform(); };\ m_GetForwardVectorFunctions[type] = [](Entity& entity, glm::vec3* outVector) { *outVector = ((SceneComponent&)entity.GetComponent<Type>()).GetForwardVector(); };\ }\ \ if (std::is_base_of<LightComponent, Type>::value)\ {\ m_SetLightColorFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).LightColor = *value; };\ m_GetLightColorFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).LightColor; };\ \ m_SetAmbientFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Ambient = *value; };\ m_GetAmbientFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Ambient; };\ \ m_SetSpecularFunctions[type] = [](Entity& entity, const glm::vec3* value) { ((LightComponent&)entity.GetComponent<Type>()).Specular = *value; };\ m_GetSpecularFunctions[type] = [](Entity& entity, glm::vec3* outValue) { *outValue = ((LightComponent&)entity.GetComponent<Type>()).Specular; };\ \ m_SetAffectsWorldFunctions[type] = [](Entity& entity, bool value) { ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld = value; };\ m_GetAffectsWorldFunctions[type] = [](Entity& entity) { return ((LightComponent&)entity.GetComponent<Type>()).bAffectsWorld; };\ }\ if (std::is_base_of<BaseColliderComponent, Type>::value)\ {\ m_SetIsTriggerFunctions[type] = [](Entity& entity, bool bTrigger) { ((BaseColliderComponent&)entity.GetComponent<Type>()).SetIsTrigger(bTrigger); };\ m_IsTriggerFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).IsTrigger(); };\ m_SetStaticFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->StaticFriction = value; comp.SetPhysicsMaterial(mat); };\ m_SetDynamicFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->DynamicFriction = value; comp.SetPhysicsMaterial(mat); };\ m_SetBouncinessFrictionFunctions[type] = [](Entity& entity, float value) { auto& comp = ((BaseColliderComponent&)entity.GetComponent<Type>()); auto mat = MakeRef<PhysicsMaterial>(comp.GetPhysicsMaterial()); mat->Bounciness = value; comp.SetPhysicsMaterial(mat); };\ m_GetStaticFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->StaticFriction; };\ m_GetDynamicFrictionFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->DynamicFriction; };\ m_GetBouncinessFunctions[type] = [](Entity& entity) { return ((BaseColliderComponent&)entity.GetComponent<Type>()).GetPhysicsMaterial()->Bounciness; };\ }\ }\ else\ EG_CORE_ERROR("No C# Component found for " #Type "!");\ } static void InitComponentTypes() { REGISTER_COMPONENT_TYPE(TransformComponent); REGISTER_COMPONENT_TYPE(SceneComponent); REGISTER_COMPONENT_TYPE(PointLightComponent); REGISTER_COMPONENT_TYPE(DirectionalLightComponent); REGISTER_COMPONENT_TYPE(SpotLightComponent); REGISTER_COMPONENT_TYPE(StaticMeshComponent); REGISTER_COMPONENT_TYPE(AudioComponent); REGISTER_COMPONENT_TYPE(RigidBodyComponent); REGISTER_COMPONENT_TYPE(BoxColliderComponent); REGISTER_COMPONENT_TYPE(SphereColliderComponent); REGISTER_COMPONENT_TYPE(CapsuleColliderComponent); REGISTER_COMPONENT_TYPE(MeshColliderComponent); } void ScriptEngineRegistry::RegisterAll() { InitComponentTypes(); //Entity mono_add_internal_call("Eagle.Entity::GetParent_Native", Eagle::Script::Eagle_Entity_GetParent); mono_add_internal_call("Eagle.Entity::SetParent_Native", Eagle::Script::Eagle_Entity_SetParent); mono_add_internal_call("Eagle.Entity::GetChildren_Native", Eagle::Script::Eagle_Entity_GetChildren); mono_add_internal_call("Eagle.Entity::CreateEntity_Native", Eagle::Script::Eagle_Entity_CreateEntity); mono_add_internal_call("Eagle.Entity::DestroyEntity_Native", Eagle::Script::Eagle_Entity_DestroyEntity); mono_add_internal_call("Eagle.Entity::AddComponent_Native", Eagle::Script::Eagle_Entity_AddComponent); mono_add_internal_call("Eagle.Entity::HasComponent_Native", Eagle::Script::Eagle_Entity_HasComponent); mono_add_internal_call("Eagle.Entity::GetEntityName_Native", Eagle::Script::Eagle_Entity_GetEntityName); mono_add_internal_call("Eagle.Entity::GetForwardVector_Native", Eagle::Script::Eagle_Entity_GetForwardVector); mono_add_internal_call("Eagle.Entity::GetRightVector_Native", Eagle::Script::Eagle_Entity_GetRightVector); mono_add_internal_call("Eagle.Entity::GetUpVector_Native", Eagle::Script::Eagle_Entity_GetUpVector); //Entity-Physics mono_add_internal_call("Eagle.Entity::WakeUp_Native", Eagle::Script::Eagle_Entity_WakeUp); mono_add_internal_call("Eagle.Entity::PutToSleep_Native", Eagle::Script::Eagle_Entity_PutToSleep); mono_add_internal_call("Eagle.Entity::GetMass_Native", Eagle::Script::Eagle_Entity_GetMass); mono_add_internal_call("Eagle.Entity::SetMass_Native", Eagle::Script::Eagle_Entity_SetMass); mono_add_internal_call("Eagle.Entity::AddForce_Native", Eagle::Script::Eagle_Entity_AddForce); mono_add_internal_call("Eagle.Entity::AddTorque_Native", Eagle::Script::Eagle_Entity_AddTorque); mono_add_internal_call("Eagle.Entity::GetLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetLinearVelocity); mono_add_internal_call("Eagle.Entity::SetLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetLinearVelocity); mono_add_internal_call("Eagle.Entity::GetAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetAngularVelocity); mono_add_internal_call("Eagle.Entity::SetAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetAngularVelocity); mono_add_internal_call("Eagle.Entity::GetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxLinearVelocity); mono_add_internal_call("Eagle.Entity::SetMaxLinearVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxLinearVelocity); mono_add_internal_call("Eagle.Entity::GetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_GetMaxAngularVelocity); mono_add_internal_call("Eagle.Entity::SetMaxAngularVelocity_Native", Eagle::Script::Eagle_Entity_SetMaxAngularVelocity); mono_add_internal_call("Eagle.Entity::SetLinearDamping_Native", Eagle::Script::Eagle_Entity_SetLinearDamping); mono_add_internal_call("Eagle.Entity::SetAngularDamping_Native", Eagle::Script::Eagle_Entity_SetAngularDamping); mono_add_internal_call("Eagle.Entity::IsDynamic_Native", Eagle::Script::Eagle_Entity_IsDynamic); mono_add_internal_call("Eagle.Entity::IsKinematic_Native", Eagle::Script::Eagle_Entity_IsKinematic); mono_add_internal_call("Eagle.Entity::IsGravityEnabled_Native", Eagle::Script::Eagle_Entity_IsGravityEnabled); mono_add_internal_call("Eagle.Entity::IsLockFlagSet_Native", Eagle::Script::Eagle_Entity_IsLockFlagSet); mono_add_internal_call("Eagle.Entity::GetLockFlags_Native", Eagle::Script::Eagle_Entity_GetLockFlags); mono_add_internal_call("Eagle.Entity::SetKinematic_Native", Eagle::Script::Eagle_Entity_SetKinematic); mono_add_internal_call("Eagle.Entity::SetGravityEnabled_Native", Eagle::Script::Eagle_Entity_SetGravityEnabled); mono_add_internal_call("Eagle.Entity::SetLockFlag_Native", Eagle::Script::Eagle_Entity_SetLockFlag); //Input mono_add_internal_call("Eagle.Input::IsMouseButtonPressed_Native", Eagle::Script::Eagle_Input_IsMouseButtonPressed); mono_add_internal_call("Eagle.Input::IsKeyPressed_Native", Eagle::Script::Eagle_Input_IsKeyPressed); mono_add_internal_call("Eagle.Input::GetMousePosition_Native", Eagle::Script::Eagle_Input_GetMousePosition); mono_add_internal_call("Eagle.Input::SetCursorMode_Native", Eagle::Script::Eagle_Input_SetCursorMode); mono_add_internal_call("Eagle.Input::GetCursorMode_Native", Eagle::Script::Eagle_Input_GetCursorMode); //TransformComponent mono_add_internal_call("Eagle.TransformComponent::GetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_GetWorldTransform); mono_add_internal_call("Eagle.TransformComponent::GetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldLocation); mono_add_internal_call("Eagle.TransformComponent::GetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_GetWorldRotation); mono_add_internal_call("Eagle.TransformComponent::GetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_GetWorldScale); mono_add_internal_call("Eagle.TransformComponent::SetWorldTransform_Native", Eagle::Script::Eagle_TransformComponent_SetWorldTransform); mono_add_internal_call("Eagle.TransformComponent::SetWorldLocation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldLocation); mono_add_internal_call("Eagle.TransformComponent::SetWorldRotation_Native", Eagle::Script::Eagle_TransformComponent_SetWorldRotation); mono_add_internal_call("Eagle.TransformComponent::SetWorldScale_Native", Eagle::Script::Eagle_TransformComponent_SetWorldScale); mono_add_internal_call("Eagle.TransformComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeTransform); mono_add_internal_call("Eagle.TransformComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeLocation); mono_add_internal_call("Eagle.TransformComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeRotation); mono_add_internal_call("Eagle.TransformComponent::GetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_GetRelativeScale); mono_add_internal_call("Eagle.TransformComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeTransform); mono_add_internal_call("Eagle.TransformComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeLocation); mono_add_internal_call("Eagle.TransformComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeRotation); mono_add_internal_call("Eagle.TransformComponent::SetRelativeScale_Native", Eagle::Script::Eagle_TransformComponent_SetRelativeScale); //Scene Component mono_add_internal_call("Eagle.SceneComponent::GetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_GetWorldTransform); mono_add_internal_call("Eagle.SceneComponent::GetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldLocation); mono_add_internal_call("Eagle.SceneComponent::GetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_GetWorldRotation); mono_add_internal_call("Eagle.SceneComponent::GetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_GetWorldScale); mono_add_internal_call("Eagle.SceneComponent::SetWorldTransform_Native", Eagle::Script::Eagle_SceneComponent_SetWorldTransform); mono_add_internal_call("Eagle.SceneComponent::SetWorldLocation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldLocation); mono_add_internal_call("Eagle.SceneComponent::SetWorldRotation_Native", Eagle::Script::Eagle_SceneComponent_SetWorldRotation); mono_add_internal_call("Eagle.SceneComponent::SetWorldScale_Native", Eagle::Script::Eagle_SceneComponent_SetWorldScale); mono_add_internal_call("Eagle.SceneComponent::GetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeTransform); mono_add_internal_call("Eagle.SceneComponent::GetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeLocation); mono_add_internal_call("Eagle.SceneComponent::GetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeRotation); mono_add_internal_call("Eagle.SceneComponent::GetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_GetRelativeScale); mono_add_internal_call("Eagle.SceneComponent::SetRelativeTransform_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeTransform); mono_add_internal_call("Eagle.SceneComponent::SetRelativeLocation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeLocation); mono_add_internal_call("Eagle.SceneComponent::SetRelativeRotation_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeRotation); mono_add_internal_call("Eagle.SceneComponent::SetRelativeScale_Native", Eagle::Script::Eagle_SceneComponent_SetRelativeScale); mono_add_internal_call("Eagle.SceneComponent::GetForwardVector_Native", Eagle::Script::Eagle_SceneComponent_GetForwardVector); //Light Component mono_add_internal_call("Eagle.LightComponent::GetLightColor_Native", Eagle::Script::Eagle_LightComponent_GetLightColor); mono_add_internal_call("Eagle.LightComponent::GetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_GetAmbientColor); mono_add_internal_call("Eagle.LightComponent::GetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_GetSpecularColor); mono_add_internal_call("Eagle.LightComponent::GetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_GetAffectsWorld); mono_add_internal_call("Eagle.LightComponent::SetLightColor_Native", Eagle::Script::Eagle_LightComponent_SetLightColor); mono_add_internal_call("Eagle.LightComponent::SetAmbientColor_Native", Eagle::Script::Eagle_LightComponent_SetAmbientColor); mono_add_internal_call("Eagle.LightComponent::SetSpecularColor_Native", Eagle::Script::Eagle_LightComponent_SetSpecularColor); mono_add_internal_call("Eagle.LightComponent::SetAffectsWorld_Native", Eagle::Script::Eagle_LightComponent_SetAffectsWorld); //PointLight Component mono_add_internal_call("Eagle.PointLightComponent::GetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_GetIntensity); mono_add_internal_call("Eagle.PointLightComponent::SetIntensity_Native", Eagle::Script::Eagle_PointLightComponent_SetIntensity); //DirectionalLight Component //SpotLight Component mono_add_internal_call("Eagle.SpotLightComponent::GetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetInnerCutoffAngle); mono_add_internal_call("Eagle.SpotLightComponent::GetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_GetOuterCutoffAngle); mono_add_internal_call("Eagle.SpotLightComponent::SetInnerCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetInnerCutoffAngle); mono_add_internal_call("Eagle.SpotLightComponent::SetOuterCutoffAngle_Native", Eagle::Script::Eagle_SpotLightComponent_SetOuterCutoffAngle); mono_add_internal_call("Eagle.SpotLightComponent::SetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_SetIntensity); mono_add_internal_call("Eagle.SpotLightComponent::GetIntensity_Native", Eagle::Script::Eagle_SpotLightComponent_GetIntensity); //Texture mono_add_internal_call("Eagle.Texture::IsValid_Native", Eagle::Script::Eagle_Texture_IsValid); //Texture2D mono_add_internal_call("Eagle.Texture2D::Create_Native", Eagle::Script::Eagle_Texture2D_Create); //Static Mesh mono_add_internal_call("Eagle.StaticMesh::Create_Native", Eagle::Script::Eagle_StaticMesh_Create); mono_add_internal_call("Eagle.StaticMesh::IsValid_Native", Eagle::Script::Eagle_StaticMesh_IsValid); mono_add_internal_call("Eagle.StaticMesh::SetDiffuseTexture_Native", Eagle::Script::Eagle_StaticMesh_SetDiffuseTexture); mono_add_internal_call("Eagle.StaticMesh::SetSpecularTexture_Native", Eagle::Script::Eagle_StaticMesh_SetSpecularTexture); mono_add_internal_call("Eagle.StaticMesh::SetNormalTexture_Native", Eagle::Script::Eagle_StaticMesh_SetNormalTexture); mono_add_internal_call("Eagle.StaticMesh::SetScalarMaterialParams_Native", Eagle::Script::Eagle_StaticMesh_SetScalarMaterialParams); mono_add_internal_call("Eagle.StaticMesh::GetMaterial_Native", Eagle::Script::Eagle_StaticMesh_GetMaterial); //StaticMeshComponent mono_add_internal_call("Eagle.StaticMeshComponent::SetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_SetMesh); mono_add_internal_call("Eagle.StaticMeshComponent::GetMesh_Native", Eagle::Script::Eagle_StaticMeshComponent_GetMesh); //Sound mono_add_internal_call("Eagle.Sound2D::Play_Native", Eagle::Script::Eagle_Sound2D_Play); mono_add_internal_call("Eagle.Sound3D::Play_Native", Eagle::Script::Eagle_Sound3D_Play); //AudioComponent mono_add_internal_call("Eagle.AudioComponent::SetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinDistance); mono_add_internal_call("Eagle.AudioComponent::SetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMaxDistance); mono_add_internal_call("Eagle.AudioComponent::SetMinMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_SetMinMaxDistance); mono_add_internal_call("Eagle.AudioComponent::SetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_SetRollOffModel); mono_add_internal_call("Eagle.AudioComponent::SetVolume_Native", Eagle::Script::Eagle_AudioComponent_SetVolume); mono_add_internal_call("Eagle.AudioComponent::SetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_SetLoopCount); mono_add_internal_call("Eagle.AudioComponent::SetLooping_Native", Eagle::Script::Eagle_AudioComponent_SetLooping); mono_add_internal_call("Eagle.AudioComponent::SetMuted_Native", Eagle::Script::Eagle_AudioComponent_SetMuted); mono_add_internal_call("Eagle.AudioComponent::SetSound_Native", Eagle::Script::Eagle_AudioComponent_SetSound); mono_add_internal_call("Eagle.AudioComponent::SetStreaming_Native", Eagle::Script::Eagle_AudioComponent_SetStreaming); mono_add_internal_call("Eagle.AudioComponent::Play_Native", Eagle::Script::Eagle_AudioComponent_Play); mono_add_internal_call("Eagle.AudioComponent::Stop_Native", Eagle::Script::Eagle_AudioComponent_Stop); mono_add_internal_call("Eagle.AudioComponent::SetPaused_Native", Eagle::Script::Eagle_AudioComponent_SetPaused); mono_add_internal_call("Eagle.AudioComponent::GetMinDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMinDistance); mono_add_internal_call("Eagle.AudioComponent::GetMaxDistance_Native", Eagle::Script::Eagle_AudioComponent_GetMaxDistance); mono_add_internal_call("Eagle.AudioComponent::GetRollOffModel_Native", Eagle::Script::Eagle_AudioComponent_GetRollOffModel); mono_add_internal_call("Eagle.AudioComponent::GetVolume_Native", Eagle::Script::Eagle_AudioComponent_GetVolume); mono_add_internal_call("Eagle.AudioComponent::GetLoopCount_Native", Eagle::Script::Eagle_AudioComponent_GetLoopCount); mono_add_internal_call("Eagle.AudioComponent::IsLooping_Native", Eagle::Script::Eagle_AudioComponent_IsLooping); mono_add_internal_call("Eagle.AudioComponent::IsMuted_Native", Eagle::Script::Eagle_AudioComponent_IsMuted); mono_add_internal_call("Eagle.AudioComponent::IsStreaming_Native", Eagle::Script::Eagle_AudioComponent_IsStreaming); mono_add_internal_call("Eagle.AudioComponent::IsPlaying_Native", Eagle::Script::Eagle_AudioComponent_IsPlaying); //RigidBodyComponent mono_add_internal_call("Eagle.RigidBodyComponent::SetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_SetMass); mono_add_internal_call("Eagle.RigidBodyComponent::GetMass_Native", Eagle::Script::Eagle_RigidBodyComponent_GetMass); mono_add_internal_call("Eagle.RigidBodyComponent::SetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLinearDamping); mono_add_internal_call("Eagle.RigidBodyComponent::GetLinearDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetLinearDamping); mono_add_internal_call("Eagle.RigidBodyComponent::SetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_SetAngularDamping); mono_add_internal_call("Eagle.RigidBodyComponent::GetAngularDamping_Native", Eagle::Script::Eagle_RigidBodyComponent_GetAngularDamping); mono_add_internal_call("Eagle.RigidBodyComponent::SetEnableGravity_Native", Eagle::Script::Eagle_RigidBodyComponent_SetEnableGravity); mono_add_internal_call("Eagle.RigidBodyComponent::IsGravityEnabled_Native", Eagle::Script::Eagle_RigidBodyComponent_IsGravityEnabled); mono_add_internal_call("Eagle.RigidBodyComponent::SetIsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_SetIsKinematic); mono_add_internal_call("Eagle.RigidBodyComponent::IsKinematic_Native", Eagle::Script::Eagle_RigidBodyComponent_IsKinematic); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPosition_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPosition); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionX); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionY); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockPositionZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockPositionZ); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotation_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotation); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationX_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationX); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationY_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationY); mono_add_internal_call("Eagle.RigidBodyComponent::SetLockRotationZ_Native", Eagle::Script::Eagle_RigidBodyComponent_SetLockRotationZ); mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionXLocked); mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionYLocked); mono_add_internal_call("Eagle.RigidBodyComponent::IsPositionZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsPositionZLocked); mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationXLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationXLocked); mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationYLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationYLocked); mono_add_internal_call("Eagle.RigidBodyComponent::IsRotationZLocked_Native", Eagle::Script::Eagle_RigidBodyComponent_IsRotationZLocked); //BaseColliderComponent mono_add_internal_call("Eagle.BaseColliderComponent::SetIsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_SetIsTrigger); mono_add_internal_call("Eagle.BaseColliderComponent::IsTrigger_Native", Eagle::Script::Eagle_BaseColliderComponent_IsTrigger); mono_add_internal_call("Eagle.BaseColliderComponent::SetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetStaticFriction); mono_add_internal_call("Eagle.BaseColliderComponent::SetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_SetDynamicFriction); mono_add_internal_call("Eagle.BaseColliderComponent::SetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_SetBounciness); mono_add_internal_call("Eagle.BaseColliderComponent::GetStaticFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetStaticFriction); mono_add_internal_call("Eagle.BaseColliderComponent::GetDynamicFriction_Native", Eagle::Script::Eagle_BaseColliderComponent_GetDynamicFriction); mono_add_internal_call("Eagle.BaseColliderComponent::GetBounciness_Native", Eagle::Script::Eagle_BaseColliderComponent_GetBounciness); //BoxColliderComponent mono_add_internal_call("Eagle.BoxColliderComponent::SetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_SetSize); mono_add_internal_call("Eagle.BoxColliderComponent::GetSize_Native", Eagle::Script::Eagle_BoxColliderComponent_GetSize); //SphereColliderComponent mono_add_internal_call("Eagle.SphereColliderComponent::SetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_SetRadius); mono_add_internal_call("Eagle.SphereColliderComponent::GetRadius_Native", Eagle::Script::Eagle_SphereColliderComponent_GetRadius); //CapsuleColliderComponent mono_add_internal_call("Eagle.CapsuleColliderComponent::SetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetRadius); mono_add_internal_call("Eagle.CapsuleColliderComponent::GetRadius_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetRadius); mono_add_internal_call("Eagle.CapsuleColliderComponent::SetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_SetHeight); mono_add_internal_call("Eagle.CapsuleColliderComponent::GetHeight_Native", Eagle::Script::Eagle_CapsuleColliderComponent_GetHeight); //MeshColliderComponent mono_add_internal_call("Eagle.MeshColliderComponent::SetIsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_SetIsConvex); mono_add_internal_call("Eagle.MeshColliderComponent::IsConvex_Native", Eagle::Script::Eagle_MeshColliderComponent_IsConvex); mono_add_internal_call("Eagle.MeshColliderComponent::SetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_SetCollisionMesh); mono_add_internal_call("Eagle.MeshColliderComponent::GetCollisionMesh_Native", Eagle::Script::Eagle_MeshColliderComponent_GetCollisionMesh); } }
88.449541
271
0.831
IceLuna
91828a3fc770a1d12be4bbfa6992f2f34a1114de
73
cpp
C++
VChat/client/src/socket.cpp
xmmmmmovo/VChat
db0c45fcca55af09c3e18def61a4601655575eaa
[ "Apache-2.0" ]
null
null
null
VChat/client/src/socket.cpp
xmmmmmovo/VChat
db0c45fcca55af09c3e18def61a4601655575eaa
[ "Apache-2.0" ]
null
null
null
VChat/client/src/socket.cpp
xmmmmmovo/VChat
db0c45fcca55af09c3e18def61a4601655575eaa
[ "Apache-2.0" ]
null
null
null
#include "socket.h" #include <sys/socket.h> client::Socket::Socket() {}
14.6
27
0.671233
xmmmmmovo
91834e8215c7c0af05dc6635277eee55d53d54e4
1,790
cpp
C++
src/RESTAPI_oauth2Handler.cpp
shimmy568/wlan-cloud-ucentralgw
806e24e1e666c31175c059373440ae029d9fff67
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI_oauth2Handler.cpp
shimmy568/wlan-cloud-ucentralgw
806e24e1e666c31175c059373440ae029d9fff67
[ "BSD-3-Clause" ]
null
null
null
src/RESTAPI_oauth2Handler.cpp
shimmy568/wlan-cloud-ucentralgw
806e24e1e666c31175c059373440ae029d9fff67
[ "BSD-3-Clause" ]
null
null
null
// // License type: BSD 3-Clause License // License copy: https://github.com/Telecominfraproject/wlan-cloud-ucentralgw/blob/master/LICENSE // // Created by Stephane Bourque on 2021-03-04. // Arilia Wireless Inc. // #include "Poco/JSON/Parser.h" #include "RESTAPI_oauth2Handler.h" #include "uAuthService.h" void RESTAPI_oauth2Handler::handleRequest(Poco::Net::HTTPServerRequest & Request, Poco::Net::HTTPServerResponse & Response) { if(!ContinueProcessing(Request,Response)) return; try { if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_POST) { // Extract the info for login... Poco::JSON::Parser parser; Poco::JSON::Object::Ptr Obj = parser.parse(Request.stream()).extract<Poco::JSON::Object::Ptr>(); Poco::DynamicStruct ds = *Obj; auto userId = ds["userId"].toString(); auto password = ds["password"].toString(); uCentral::Objects::WebToken Token; if (uCentral::Auth::Authorize(userId, password, Token)) { Poco::JSON::Object ReturnObj; Token.to_json(ReturnObj); ReturnObject(ReturnObj, Response); } else { UnAuthorized(Response); } } else if (Request.getMethod() == Poco::Net::HTTPServerRequest::HTTP_DELETE) { if (!IsAuthorized(Request, Response)) return; auto Token = GetBinding("token", "..."); if (Token == SessionToken_) uCentral::Auth::Logout(Token); OK(Response); } return; } catch (const Poco::Exception &E) { Logger_.warning(Poco::format( "%s: Failed with: %s" , std::string(__func__), E.displayText())); } BadRequest(Response); }
31.403509
123
0.594413
shimmy568
91860598057b479f935047626faa8fe8337d007a
810
cpp
C++
src/blinkit/blink/renderer/core/layout/ViewFragmentationContext.cpp
titilima/blink
2de70073edfe0e1e0aaf2bb22b5d6abd9b776fad
[ "MIT" ]
13
2020-04-21T13:14:00.000Z
2021-11-13T14:55:12.000Z
third_party/WebKit/Source/core/layout/ViewFragmentationContext.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/core/layout/ViewFragmentationContext.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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 "core/layout/ViewFragmentationContext.h" #include "core/layout/LayoutView.h" namespace blink { bool ViewFragmentationContext::isFragmentainerLogicalHeightKnown() { ASSERT(m_view.pageLogicalHeight()); return true; } LayoutUnit ViewFragmentationContext::fragmentainerLogicalHeightAt(LayoutUnit) { ASSERT(m_view.pageLogicalHeight()); return m_view.pageLogicalHeight(); } LayoutUnit ViewFragmentationContext::remainingLogicalHeightAt(LayoutUnit blockOffset) { LayoutUnit pageLogicalHeight = m_view.pageLogicalHeight(); return pageLogicalHeight - intMod(blockOffset, pageLogicalHeight); } } // namespace blink
27
85
0.788889
titilima
918703b4412c8929081f8d7ed31fc9b756f1dbb2
11,982
cpp
C++
third_party/virtualbox/src/VBox/Runtime/testcase/tstRTSemEventMulti.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
521
2019-03-29T15:44:08.000Z
2022-03-22T09:46:19.000Z
third_party/virtualbox/src/VBox/Runtime/testcase/tstRTSemEventMulti.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
30
2019-06-04T17:00:49.000Z
2021-09-08T20:44:19.000Z
third_party/virtualbox/src/VBox/Runtime/testcase/tstRTSemEventMulti.cpp
Fimbure/icebox-1
0b81992a53e1b410955ca89bdb6f8169d6f2da86
[ "MIT" ]
99
2019-03-29T16:04:13.000Z
2022-03-28T16:59:34.000Z
/* $Id: tstRTSemEventMulti.cpp $ */ /** @file * IPRT Testcase - Multiple Release Event Semaphores. */ /* * Copyright (C) 2009-2017 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. * * The contents of this file may alternatively be used under the terms * of the Common Development and Distribution License Version 1.0 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the * VirtualBox OSE distribution, in which case the provisions of the * CDDL are applicable instead of those of the GPL. * * You may elect to license modified versions of this file under the * terms and conditions of either the GPL or the CDDL or both. */ /********************************************************************************************************************************* * Header Files * *********************************************************************************************************************************/ #include <iprt/semaphore.h> #include <iprt/asm.h> #include <iprt/assert.h> #include <iprt/rand.h> #include <iprt/stream.h> #include <iprt/string.h> #include <iprt/test.h> #include <iprt/thread.h> #include <iprt/time.h> /********************************************************************************************************************************* * Global Variables * *********************************************************************************************************************************/ /** The test handle. */ static RTTEST g_hTest; static DECLCALLBACK(int) test1Thread1(RTTHREAD ThreadSelf, void *pvUser) { RTSEMEVENTMULTI hSem = *(PRTSEMEVENTMULTI)pvUser; RT_NOREF_PV(ThreadSelf); uint64_t u64 = RTTimeSystemMilliTS(); RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, 1000), VERR_TIMEOUT); u64 = RTTimeSystemMilliTS() - u64; RTTEST_CHECK_MSG(g_hTest, u64 < 1500 && u64 > 950, (g_hTest, "u64=%llu\n", u64)); RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, 2000), VINF_SUCCESS); return VINF_SUCCESS; } static DECLCALLBACK(int) test1Thread2(RTTHREAD ThreadSelf, void *pvUser) { RTSEMEVENTMULTI hSem = *(PRTSEMEVENTMULTI)pvUser; RT_NOREF_PV(ThreadSelf); RTTEST_CHECK_RC(g_hTest, RTSemEventMultiWait(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS); return VINF_SUCCESS; } static void test1(void) { RTTestISub("Three threads"); /* * Create the threads and let them block on the event multi semaphore. */ RTSEMEVENTMULTI hSem; RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS); RTTHREAD hThread2; RTTESTI_CHECK_RC_RETV(RTThreadCreate(&hThread2, test1Thread2, &hSem, 0, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "test2"), VINF_SUCCESS); RTThreadSleep(100); RTTHREAD hThread1; RTTESTI_CHECK_RC_RETV(RTThreadCreate(&hThread1, test1Thread1, &hSem, 0, RTTHREADTYPE_DEFAULT, RTTHREADFLAGS_WAITABLE, "test1"), VINF_SUCCESS); /* Force first thread (which has a timeout of 1 second) to timeout in the * first wait, and the second wait will succeed. */ RTTESTI_CHECK_RC(RTThreadSleep(1500), VINF_SUCCESS); RTTESTI_CHECK_RC(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC(RTThreadWait(hThread1, 5000, NULL), VINF_SUCCESS); RTTESTI_CHECK_RC(RTThreadWait(hThread2, 5000, NULL), VINF_SUCCESS); RTTESTI_CHECK_RC(RTSemEventMultiDestroy(hSem), VINF_SUCCESS); } static void testBasicsWaitTimeout(RTSEMEVENTMULTI hSem, unsigned i) { RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, 0), VERR_TIMEOUT); #if 0 RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, 0), VERR_TIMEOUT); #else RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_RELATIVE, 0), VERR_TIMEOUT); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeSystemNanoTS() + 1000*i), VERR_TIMEOUT); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeNanoTS() + 1000*i), VERR_TIMEOUT); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_RELATIVE, 0), VERR_TIMEOUT); #endif } static void testBasicsWaitSuccess(RTSEMEVENTMULTI hSem, unsigned i) { RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWait(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS); #if 0 RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitNoResume(hSem, RT_INDEFINITE_WAIT), VINF_SUCCESS); #else RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_RELATIVE, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_INDEFINITE, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_NORESUME | RTSEMWAIT_FLAGS_INDEFINITE, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeSystemNanoTS() + 1000*i), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeNanoTS() + 1000*i), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, _1G), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_NANOSECS | RTSEMWAIT_FLAGS_ABSOLUTE, UINT64_MAX), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeSystemMilliTS() + 1000*i), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE, RTTimeMilliTS() + 1000*i), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE, 0), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE, _1M), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiWaitEx(hSem, RTSEMWAIT_FLAGS_RESUME | RTSEMWAIT_FLAGS_MILLISECS | RTSEMWAIT_FLAGS_ABSOLUTE, UINT64_MAX), VINF_SUCCESS); #endif } static void testBasics(void) { RTTestISub("Basics"); RTSEMEVENTMULTI hSem; RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS); /* The semaphore is created in a reset state, calling reset explicitly shouldn't make any difference. */ testBasicsWaitTimeout(hSem, 0); RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); testBasicsWaitTimeout(hSem, 1); if (RTTestIErrorCount()) return; /* When signalling the semaphore all successive wait calls shall succeed, signalling it again should make no difference. */ RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); testBasicsWaitSuccess(hSem, 2); if (RTTestIErrorCount()) return; /* After resetting it we should time out again. */ RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); testBasicsWaitTimeout(hSem, 3); if (RTTestIErrorCount()) return; /* The number of resets or signal calls shouldn't matter. */ RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); testBasicsWaitTimeout(hSem, 4); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); testBasicsWaitSuccess(hSem, 5); RTTESTI_CHECK_RC_RETV(RTSemEventMultiReset(hSem), VINF_SUCCESS); testBasicsWaitTimeout(hSem, 6); /* Destroy it. */ RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(NIL_RTSEMEVENTMULTI), VINF_SUCCESS); /* Whether it is reset (above), signalled or not used shouldn't matter. */ RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiSignal(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiCreate(&hSem), VINF_SUCCESS); RTTESTI_CHECK_RC_RETV(RTSemEventMultiDestroy(hSem), VINF_SUCCESS); RTTestISubDone(); } int main(int argc, char **argv) { RT_NOREF_PV(argc); RT_NOREF_PV(argv); RTEXITCODE rcExit = RTTestInitAndCreate("tstRTSemEventMulti", &g_hTest); if (rcExit != RTEXITCODE_SUCCESS) return rcExit; testBasics(); if (!RTTestErrorCount(g_hTest)) { test1(); } return RTTestSummaryAndDestroy(g_hTest); }
45.045113
146
0.610749
Fimbure
918abea4dce52fbbe598c3104be24779f2e2604f
2,940
cpp
C++
Libs/ModuleDescription/ctkModuleParameter.cpp
lassoan/CTK
ba271a053217d26e90dee35837cd3979c3bb5b8b
[ "Apache-2.0" ]
1
2018-11-15T17:02:06.000Z
2018-11-15T17:02:06.000Z
Libs/ModuleDescription/ctkModuleParameter.cpp
SlicerRt/CTK
4ff3dff4b9560b0dd78512ca7fc47999b0a8fca1
[ "Apache-2.0" ]
null
null
null
Libs/ModuleDescription/ctkModuleParameter.cpp
SlicerRt/CTK
4ff3dff4b9560b0dd78512ca7fc47999b0a8fca1
[ "Apache-2.0" ]
null
null
null
/*============================================================================= Library: CTK Copyright (c) 2010 Brigham and Women's Hospital (BWH) 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 "ctkModuleParameter.h" #include "QStringList" //---------------------------------------------------------------------------- bool ctkModuleParameter::isReturnParameter() const { // could check for tag == float, int, float-vector, ... return (*this)["Channel"] == "output" && !this->isFlagParameter() && !this->isIndexParameter(); } //---------------------------------------------------------------------------- bool ctkModuleParameter::isFlagParameter() const { return ((*this)["Flag"] != "" || (*this)[ "LongFlag" ] != ""); } //---------------------------------------------------------------------------- bool ctkModuleParameter::isIndexParameter() const { return ((*this)[ "Index" ] != ""); } //----------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const ctkModuleParameter &parameter) { os << " Parameter" << endl; os << " "; os.setFieldWidth(7); os.setFieldAlignment(QTextStream::AlignLeft); os << QHash<QString, QString>( parameter ); os.setFieldWidth(0); os << "Flag aliases: "; os << parameter["FlagAliases"].split( "," ); os << " " << "Deprecated Flag aliases: "; os << parameter["DeprecatedFlagAliases"].split( "," ); os << " " << "LongFlag aliases: "; os << parameter["LongFlagAliases"].split( "," ); os << " " << "Deprecated LongFlag aliases: "; os << parameter["DeprecatedLongFlagAliases"].split( "," ); os << " " << "FileExtensions: "; os << parameter["FileExtensions"].split( "," ); return os; } //---------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const QStringList &list) { os << list.join(", ") << endl; return os; } //---------------------------------------------------------------------------- QTextStream & operator<<(QTextStream &os, const QHash<QString, QString> &hash) { QHash<QString,QString>::const_iterator itProp; for ( itProp = hash.begin( ) ; itProp != hash.end( ) ; itProp++ ) { os << itProp.key( ) << ": " << itProp.value( ) << endl; } return os; }
31.612903
79
0.507143
lassoan
9260ca69020853cf63f5f7cedc1273b07105d241
3,602
cc
C++
tests/sxg_encoded_response_test.cc
rgs1/libsxg
5bfaf438eb1ecb57112c419fb5d7d396dea593a2
[ "Apache-2.0" ]
51
2019-08-16T05:22:45.000Z
2022-03-30T17:38:36.000Z
tests/sxg_encoded_response_test.cc
rgs1/libsxg
5bfaf438eb1ecb57112c419fb5d7d396dea593a2
[ "Apache-2.0" ]
56
2019-08-28T10:48:30.000Z
2021-11-05T21:18:24.000Z
tests/sxg_encoded_response_test.cc
rgs1/libsxg
5bfaf438eb1ecb57112c419fb5d7d396dea593a2
[ "Apache-2.0" ]
35
2019-08-17T21:07:04.000Z
2022-01-31T21:25:26.000Z
// Copyright 2019 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "libsxg/sxg_encoded_response.h" #include <string> #include "gtest/gtest.h" #include "test_util.h" namespace { using ::sxg_test::BufferToString; TEST(SxgEncodedResponse, InitializeAndReleaseEmptyRawResponse) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_raw_response_release(&resp); } TEST(SxgEncodedResponse, InitializeAndReleaseEmptyEncodedResponse) { sxg_encoded_response_t resp = sxg_empty_encoded_response(); sxg_encoded_response_release(&resp); } std::string HeaderFindKey(const sxg_header_t& header, const char* key) { for (size_t i = 0; i < header.size; ++i) { if (strcasecmp(header.entries[i].key, key) == 0) { return BufferToString(header.entries[i].value); } } return ""; } TEST(SxgEncodedResponse, EncodeMinimum) { // https://tools.ietf.org/html/draft-thomson-http-mice-03#section-2.2 // If 0 octets are available, and "top-proof" is SHA-256("\0") (whose base64 // encoding is "bjQLnP+zepicpUTmu3gKLHiQHT+zNzh2hRGjBhevoB0="), then return a // 0-length decoded payload. sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t output = sxg_empty_encoded_response(); std::string expected_digest = "mi-sha256-03=bjQLnP+zepicpUTmu3gKLHiQHT+zNzh2hRGjBhevoB0="; EXPECT_TRUE(sxg_encode_response(16, &resp, &output)); EXPECT_EQ(3u, output.header.size); EXPECT_EQ("200", HeaderFindKey(output.header, ":status")); EXPECT_EQ("mi-sha256-03", HeaderFindKey(output.header, "content-encoding")); EXPECT_EQ(expected_digest, HeaderFindKey(output.header, "digest")); EXPECT_EQ(0u, output.payload.size); sxg_raw_response_release(&resp); sxg_encoded_response_release(&output); } TEST(SxgEncodedResponse, IntegrityMinimum) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t enc = sxg_empty_encoded_response(); sxg_buffer_t output = sxg_empty_buffer(); std::string expected = "sha256-4zGVTZ38P1nbTw6MnJfVF21L7qg0pJsfXjIOOfcXIgo="; EXPECT_TRUE(sxg_encode_response(4096, &resp, &enc)); EXPECT_TRUE(sxg_write_header_integrity(&enc, &output)); EXPECT_EQ(expected, BufferToString(output)); sxg_raw_response_release(&resp); sxg_encoded_response_release(&enc); sxg_buffer_release(&output); } TEST(SxgEncodedResponse, SomeHeader) { sxg_raw_response_t resp = sxg_empty_raw_response(); sxg_encoded_response_t enc = sxg_empty_encoded_response(); sxg_encode_response(16, &resp, &enc); sxg_buffer_t output = sxg_empty_buffer(); sxg_header_append_string("foo", "bar", &resp.header); std::string expected = "sha256-CUivwFQMaYG/EfLfL4l4dbde7Xp/+jIzdP6GqttQNTw="; EXPECT_TRUE(sxg_encode_response(4096, &resp, &enc)); EXPECT_EQ(4u, enc.header.size); EXPECT_TRUE(sxg_write_header_integrity(&enc, &output)); EXPECT_EQ(expected, BufferToString(output)); sxg_raw_response_release(&resp); sxg_encoded_response_release(&enc); sxg_buffer_release(&output); } } // namespace
35.313725
79
0.742088
rgs1
9261111d8b22ae7ef0b7729a17ded03c8517d3e5
10,336
hpp
C++
sources/include/vd/timeline.hpp
amikey/video-player
fcf920f6085f934cd9984007a773f0c87031b30c
[ "MIT" ]
9
2016-07-18T07:49:51.000Z
2022-03-08T06:09:51.000Z
sources/include/vd/timeline.hpp
amikey/video-player
fcf920f6085f934cd9984007a773f0c87031b30c
[ "MIT" ]
null
null
null
sources/include/vd/timeline.hpp
amikey/video-player
fcf920f6085f934cd9984007a773f0c87031b30c
[ "MIT" ]
6
2016-02-03T07:30:32.000Z
2020-05-01T14:25:38.000Z
/** VD */ #pragma once #include <vd/common.hpp> #include <vd/proto.hpp> #include <QObject> #include <QScrollBar> #include <QGraphicsItem> #include <QGraphicsView> #include <QGraphicsScene> namespace vd { struct StreamConf { double time_base; }; class MediaDecoder { public: MediaDecoder(); virtual ~MediaDecoder() {} DecodingStatePtr decode(MediaPtr media); DecodingStatePtr decode(Media* media); static MediaDecoder& i() { VD_ASSERT2(instance_, "MediaDecoder singleton wasn't created"); return *instance_; } protected: static MediaDecoder* instance_; typedef std::map<AString, DecodingStatePtr> Decoders; typedef std::map<AString, DecodingStatePtr>::iterator DecodersIter; Decoders decoders_; }; class PreviewState; class TimeLineObject { public: TimeLineObject(TimeLineTrack* track); void set_track(TimeLineTrack* track) { track_ = track; } TimeLineTrack* track() { return track_; } const TimeLineTrack* track() const { return track_; } virtual void set_start(time_mark start) { start_ = start; } time_mark start() const { return start_; } virtual void set_length(time_mark length) { length_ = length; } time_mark length() const { return length_; } virtual void set_playing(time_mark playing) { playing_ = playing; } time_mark playing() const { return playing_; } virtual void seek(time_mark t) = 0; virtual IFramePtr show_next() = 0; private: TimeLineTrack* track_; time_mark start_; time_mark length_; time_mark playing_; }; class TimeLineContainer { public: virtual void add(TimeLineRectPtr rect) = 0; }; class MediaClip { public: MediaClip(MediaPtr media); void set_start(time_mark start) { start_ = start; } time_mark start() const { return start_; } void set_length(time_mark length) { length_ = length; } time_mark length() const { return length_; } MediaPtr media() const { return media_; } protected: MediaPtr media_; time_mark start_; time_mark length_; }; class MediaPipelineTransformer; class MediaPipeline { public: }; class FrameFormat; class MediaPipelineTransformer { public: virtual IFramePtr transform(IFramePtr frame) = 0; virtual bool accepts(const FrameFormat& format) = 0; protected: }; class MediaLoader { public: virtual void seek(time_mark t) = 0; virtual IFramePtr load_next() = 0; }; class MediaBackend { protected: struct Node { time_mark start; time_mark end; std::deque<IFramePtr> frames; }; friend class Iter; public: class Iter { public: IFramePtr show_next(); time_mark time() const { return t_; } protected: MediaBackend* backend_; Node* cached_; time_mark t_; }; }; class MediaObject : public TimeLineObject { public: MediaObject(); void setup(MediaClip* clip, int stream_id, PresenterPtr presenter); void seek(time_mark t) VD_OVERRIDE; IFramePtr show_next() VD_OVERRIDE; void set_length(time_mark length) VD_OVERRIDE; time_mark time_base() const; DecodingStatePtr decoder() { return decoder_; } protected: void preload_next(); public: MediaClipUPtr clip_; int stream_id_; /// Pts which corresponds first frame in frames_ queue time_mark ready_pts_; std::deque<IFramePtr> frames_; /// Pts which corresponds last decoded frame in frames_ queue time_mark read_pts_; DecodingStatePtr decoder_; PresenterPtr presenter_; }; struct PreviewPreset { float audio_volume; PreviewPreset() : audio_volume(1.f) {} }; class PreviewState { public: struct Pres { double time_base; }; PreviewState(Project* project); void sync(time_mark t); IFramePtr next_video(); MovieResourcePtr next_audio(); time_mark time_base(); void update_preset(const PreviewPreset& preset); protected: MediaObjectPtr peek_video_clip(time_mark t); MediaObjectPtr peek_audio_clip(time_mark t); protected: Project* project_; Scene* scene_; time_mark time_base_; time_mark playing_; PreviewPreset preset_; MediaObjectPtr video_clip_; MediaObjectPtr audio_clip_; std::vector<MediaObjectPtr> clips_; }; class TimeLineTrack { public: TimeLineTrack(int track) : track_(track) {} int track() const { return track_; } protected: public: int track_; typedef std::vector<MediaObjectPtr> MediaClips; typedef std::vector<MediaObjectPtr>::iterator MediaClipsIter; std::vector<MediaObjectPtr> comps_; }; class TimeLine { public: typedef std::vector<ScenePtr> Scenes; typedef std::vector<ScenePtr>::iterator ScenesIter; public: TimeLine(); void notify_project(Project* project); void _create_test() ; void query(time_mark t); Scene* scene_from_time(time_mark t); protected: public: Scenes scenes_; Project* project_; }; class TimeLineRectWidget : public QGraphicsItem { friend class TimeLineWidget; QRectF boundingRect() const; public: TimeLineRectWidget(MediaObjectPtr composed, QGraphicsItem* parent); void sync(const QPointF& size); void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void mousePressEvent(QGraphicsSceneMouseEvent* ev); void mouseMoveEvent(QGraphicsSceneMouseEvent* ev); void mouseReleaseEvent(QGraphicsSceneMouseEvent* ev); MediaObjectPtr composed() { return composed_; } protected: MediaObjectPtr composed_; QPointF offset_; QPointF size_; TimeLineTrackWidget* parent_track_; }; class TimeLineTrackWidget : public QGraphicsObject { friend class TimeLineTrack; Q_OBJECT public: typedef std::vector<TimeLineRectPtr> MediaClips; typedef std::vector<TimeLineRectPtr>::iterator MediaClipsIter; public: TimeLineTrackWidget(TimeLineTrack* track, TimeLineWidget* parent_widget); QRectF boundingRect(void) const; void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void pose_rect(TimeLineRectPtr rect); void add(MediaObjectPtr composed); QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); protected: void sync(); public: TimeLineWidget* parent_widget_; TimeLineTrack* track_; std::vector<TimeLineRectPtr> comps_; }; class TimeLineCursorWidget : public QGraphicsItem { friend class TimeLineWidget; QRectF boundingRect() const; public: TimeLineCursorWidget(QGraphicsView* parent); void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); void mousePressEvent(QGraphicsSceneMouseEvent* ev); void mouseMoveEvent(QGraphicsSceneMouseEvent* ev); void mouseReleaseEvent(QGraphicsSceneMouseEvent* ev); void sync(); int current() const; void set_to(int center); protected: TimeLineWidget* parent_; QPointF offset_; qreal height_; int click_width_div2; }; class TimeLineSceneWidget : public QGraphicsObject, public TimeLineContainer { Q_OBJECT public: typedef std::vector<TimeLineTrackWidgetPtr> Tracks; typedef std::vector<TimeLineTrackWidgetPtr>::iterator TracksIter; public: TimeLineSceneWidget(Scene* scene, TimeLineWidget* time_line); QRectF boundingRect() const { return QRectF(); } void paint(QPainter* painter, const QStyleOptionGraphicsItem* option, QWidget* widget); QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); void add(TimeLineRectPtr rect) VD_OVERRIDE; protected: void sync(); public: Scene* scene_; TimeLineWidget* time_line_; std::vector<TimeLineTrackWidgetPtr> tracks_; }; class TimeLineWidget : public QGraphicsView, public TimeLineContainer { Q_OBJECT friend class TimeLine; public: typedef std::vector<TimeLineSceneWidgetPtr> Scenes; typedef std::vector<TimeLineSceneWidgetPtr>::iterator ScenesIter; public: TimeLineWidget(QWidget* parent = 0); void bind(TimeLine* tm); //void bind_ctrls(QScrollBar* scroll); void wheelEvent(QWheelEvent* ev); void mouseDoubleClickEvent(QMouseEvent * ev); void add(TimeLineRectPtr rect) VD_OVERRIDE; QPointF transf(const QPointF& p); QPointF scale(const QPointF& p); qreal time2pos(time_mark t); time_mark pos2time(qreal pos); static TimeLineWidget& i() { VD_ASSERT2(instance_, "No TimeLineWidget instance!"); return *instance_; } void notify_current_preview_time(time_mark t); void set_preview(Preview* preview) { preview_ = preview; } signals: void set_playing(bool playing); public slots: void cursor_updated(); public slots: void scroll_moved(int value); int cd(float c); float dc(int d); protected slots: void update_timer(); void setup_timer(bool playing); protected: void sync(TimeLine* tm); void pose_cursor(float current); void update_ctrls(); void update_time_label(); protected: static TimeLineWidget* instance_; TimeLine* tm_; QGraphicsScene scene_; float offset_; float scale_; float current_; float length_; QScrollBar* scroll_; TimeLineCursorWidget* cursor_; Scenes scenes_; QLabel* time_lbl_; time_mark preview_time_; QTimer* timer_; bool playing_; Preview* preview_; }; class Scene { public: typedef std::vector<TimeLineTrackPtr> Tracks; typedef std::vector<TimeLineTrackPtr>::iterator TracksIter; typedef std::vector<CompositorPtr> Compositor; typedef std::vector<CompositorPtr>::iterator CompositorIter; Scene(Project* project); public: void _create_test(); time_mark duration() const; protected: public: Project* project_; Tracks tracks_; Compositor comps_; }; template <typename _T> class VarCtrl { public: virtual ~VarCtrl() = 0; virtual _T value(time_mark t) const = 0; }; class TimeLineParam : public TimeLineObject { public: TimeLineParam(const Name& name) : TimeLineObject(nullptr), name_(name) {} const Name& name() const { return name_; } protected: Name name_; }; template <typename _T> class TimeLineVar : public TimeLineParam { public: TimeLineVar(Name& name) : TimeLineParam(name) {} _T value(time_mark t) { return value_ctrl_->value(t); } _T* ctrl() { return value_ctrl_; } const _T* ctrl() const { return value_ctrl_; } void set_ctrl(_T* ctrl) { value_ctrl_ = ctrl; } protected: Name name_; _T* value_ctrl_; }; class Project { public: Project(PresenterPtr video_presenter, PresenterPtr audio_presenter); ~Project(); void _create_test(); TimeLine* time_line() { return time_line_.get(); } PresenterPtr video_presenter() { return video_presenter_; } PresenterPtr audio_presenter() { return audio_presenter_; } protected: public: AString name_; PresenterPtr video_presenter_; PresenterPtr audio_presenter_; int frame_rate_; TimeLinePtr time_line_; }; }// namespace vd
17.790017
112
0.756095
amikey
9262f0f0afd214758b8e18e6dacf30a35ca5d0dd
188
cpp
C++
library/src/ProgressBar.cpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
library/src/ProgressBar.cpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
library/src/ProgressBar.cpp
StratifyLabs/UxAPI
4dc043b132452896ed9626038d53439b0def786a
[ "MIT" ]
null
null
null
// Copyright 2016-2021 Tyler Gilbert and Stratify Labs, Inc; see LICENSE.md #include "ux/ProgressBar.hpp" #include "ux/draw/Rectangle.hpp" using namespace ux::sgfx; using namespace ux;
20.888889
75
0.760638
StratifyLabs
9262f30414ebd6153de123175ac857de8ebf8c87
382
hpp
C++
include/Defines.hpp
Aargonian/JLMG
18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7
[ "MIT" ]
null
null
null
include/Defines.hpp
Aargonian/JLMG
18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7
[ "MIT" ]
null
null
null
include/Defines.hpp
Aargonian/JLMG
18fa141b7e8c895e93c2e5450d9e8543b3b7b1e7
[ "MIT" ]
null
null
null
// // Created by Aaron Helton on 1/16/2020. // #ifndef JLMG_DEFINES_HPP #define JLMG_DEFINES_HPP #include <cstdint> typedef uint_least8_t uint8; typedef uint_least16_t uint16; typedef uint_least32_t uint32; typedef uint_least64_t uint64; typedef int_least8_t int8; typedef int_least16_t int16; typedef int_least32_t int32; typedef int_least64_t int64; #endif //JLMG_DEFINES_HPP
19.1
40
0.816754
Aargonian
9267740308a459caa4270a25b0bd9fcad4df2114
909
hpp
C++
vnix/bit-range.hpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
null
null
null
vnix/bit-range.hpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
4
2019-04-17T21:36:00.000Z
2019-04-30T22:06:31.000Z
vnix/bit-range.hpp
tevaughan/units
75e5cfa76a44225983ca55f2a54e0869ff7b3715
[ "BSD-3-Clause" ]
null
null
null
/// @file vnix/bit-range.hpp /// @brief Definition of vnix::bit, vnix::bit_range. /// @copyright 2019 Thomas E. Vaughan; all rights reserved. /// @license BSD Three-Clause; see LICENSE. #ifndef VNIX_BIT_HPP #define VNIX_BIT_HPP namespace vnix { /// Word with specified bit set. /// @tparam I Type of integer word. /// @param n Offset of bit in word. template <typename I> constexpr I bit(unsigned n) { return I(1) << n; } /// Word with specified range of bits set. /// @tparam I Type of integer word. /// @param n1 Offset of bit at one end of range. /// @param n2 Offset of bit at other end of range. template <typename I> constexpr I bit_range(unsigned n1, unsigned n2) { if (n1 < n2) { return bit<I>(n1) | bit_range<I>(n1 + 1, n2); } if (n2 < n1) { return bit<I>(n2) | bit_range<I>(n2 + 1, n1); } return bit<I>(n1); } } // namespace vnix #endif // ndef VNIX_BIT_HPP
28.40625
71
0.647965
tevaughan
926a055de26b3c432f325946c99f67115254cf3d
69,374
cpp
C++
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/gsearch.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/gsearch.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/glib-adv/gsearch.cpp
qiuhere/Bench
80f15facb81120b754547586cf3a7e5f46ca1551
[ "Apache-2.0" ]
null
null
null
///////////////////////////////////////////////// // WdGix-Constants TStr TGixConst::WdGixFNm = "WdGix"; TStr TGixConst::WdGixDatFNm = "WdGix.Dat"; TStr TGixConst::WdGixBsFNm = "WdGixBs.MBlobBs"; TStr TGixConst::WdGixMDSFNm = "WdGixMDS.Dat"; TStr TGixConst::TrGixFNm = "TrGix"; TStr TGixConst::TrGixDatFNm = "TrGix.Dat"; TStr TGixConst::TrGixDocBsFNm = "TrGixDocBs.MBlobBs"; TStr TGixConst::TrGixSentBsFNm = "TrGixSentBs.MBlobBs"; TStr TGixConst::TrGixTrAttrBsFNm = "TrGixTrAttrBs.MBlobBs"; TStr TGixConst::MWdGixFNm = "MWdGix"; TStr TGixConst::MWdGixDatFNm = "MWdGix.Dat"; TStr TGixConst::MWdGixDocBsFNm = "MWdGixDocBs.MBlobBs"; TStr TGixConst::MWdGixBsFNm = "MWdGixBs.Dat"; ///////////////////////////////////////////////// // Word-Inverted-Index-DataField int TWdGixItem::TitleBit = 0; int TWdGixItem::NmObjBit = 1; int TWdGixItem::AnchorBit = 2; int TWdGixItem::EmphBit = 3; TWdGixItem::TWdGixItem(const TBlobPt& BlobPt, const uchar& _Wgt, const uchar& _WdPos, const bool& TitleP, const bool& NmObjP, const bool& AnchorP, const bool& EmphP): Seg(BlobPt.GetSeg()), Addr(BlobPt.GetAddr()), WdPos(_WdPos) { FSet.SetBit(TitleBit, TitleP); FSet.SetBit(NmObjBit, NmObjP); FSet.SetBit(AnchorBit, AnchorP); FSet.SetBit(EmphBit, EmphP); } TWdGixItem::TWdGixItem(const uchar& _Seg, const uint& _Addr, const uchar& _Wgt, const uchar& _WdPos, const bool& TitleP, const bool& NmObjP, const bool& AnchorP, const bool& EmphP): Seg(_Seg), Addr(_Addr), Wgt(_Wgt), WdPos(_WdPos) { FSet.SetBit(TitleBit, TitleP); FSet.SetBit(NmObjBit, NmObjP); FSet.SetBit(AnchorBit, AnchorP); FSet.SetBit(EmphBit, EmphP); } TWdGixItem::TWdGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(Wgt); SIn.Load(WdPos); FSet=TB8Set(SIn); } void TWdGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(Wgt); SOut.Save(WdPos); FSet.Save(SOut); } inline bool TWdGixItem::operator==(const TWdGixItem& Item) const { return (Seg == Item.Seg) && (Addr == Item.Addr); // && (WdPos == Item.WdPos); } inline bool TWdGixItem::operator<(const TWdGixItem& Item) const { return (Seg < Item.Seg) || ((Seg == Item.Seg) && (Addr < Item.Addr)); // || //((Seg == Item.Seg) && (Addr == Item.Addr) && (WdPos < Item.WdPos)); } ///////////////////////////////////////////////// // Word-Inverted-Index void TWdGix::LoadTags() { TitleTagH.AddKey("<TITLE>"); NmObjTagH.AddKey("<NMOBJ>"); EmphTagH.AddKey("<EM>"); EmphTagH.AddKey("<A>"); EmphTagH.AddKey("<B>"); EmphTagH.AddKey("<I>"); EmphTagH.AddKey("<H1>"); EmphTagH.AddKey("<H2>"); EmphTagH.AddKey("<H3>"); EmphTagH.AddKey("<H4>"); EmphTagH.AddKey("<H5>"); } TWdGix::TWdGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // prepare gix WGix = TWGix::New(TGixConst::WdGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess == faCreate) { Stemmer = TStemmer::New(stmtPorter, false); SwSet = TSwSet::New(swstEn523); } else { // prepare file name TStr WdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixDatFNm; // load stuff TFIn FIn(WdGixDatFNm); WordH.Load(FIn); Stemmer = TStemmer::Load(FIn); SwSet = TSwSet::Load(FIn); } // load tags LoadTags(); } TWdGix::~TWdGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // prepare file name TStr WdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixDatFNm; // save word tables TFOut FOut(WdGixDatFNm); WordH.Save(FOut); Stemmer->Save(FOut); SwSet->Save(FOut); } } void TWdGix::AddHtml(const TStr& HtmlStr, const TBlobPt& BlobPt, const uchar& Wgt) { // create html lexical PSIn HtmlSIn = TStrIn::New(HtmlStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); // prepare word vector, position counter and flags THash<TInt, TWdGixItemV> WIdToItemVH; uchar WdPos = 0; bool TitleP = false, NmObjP = false; int EmphLv = 0; // traverse html string symbols while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // should we keep this word? if (!SwSet->IsIn(WordStr)) { // stem the word WordStr=Stemmer->GetStem(WordStr); // get the word id const int WId = WordH.AddKey(WordStr); // increase the position count WdPos++; // add word to vector WIdToItemVH.AddDat(WId).Add( TWdGixItem(BlobPt, Wgt, WdPos, TitleP, NmObjP, false, (EmphLv>0))); } } else if (HtmlLx.Sym == hsyBTag) { // we have a tag, we update flags accordingly TStr TagStr = HtmlLx.UcChA; if (TitleTagH.IsKey(TagStr)) { TitleP = true; } if (NmObjTagH.IsKey(TagStr)) { NmObjP = true; } if (EmphTagH.IsKey(TagStr)) { EmphLv++; } } else if (HtmlLx.Sym == hsyETag) { // we have a tag, we update flags accordingly TStr TagStr = HtmlLx.UcChA; if (TitleTagH.IsKey(TagStr)) { TitleP = false; } if (NmObjTagH.IsKey(TagStr)) { NmObjP = false; } if (EmphTagH.IsKey(TagStr)) { EmphLv--; EmphLv = TInt::GetMx(0, EmphLv); } } // get next symbol HtmlLx.GetSym(); } // load add documents to words in inverted index int WdKeyId = WIdToItemVH.FFirstKeyId(); while (WIdToItemVH.FNextKeyId(WdKeyId)) { const int WId = WIdToItemVH.GetKey(WdKeyId); WordH[WId]++; const TWdGixItemV& ItemV = WIdToItemVH[WdKeyId]; // HACK combine all items into one const uchar Seg = ItemV[0].GetSeg(); const uint Addr = ItemV[0].GetAddr(); const uchar Count = uchar(TInt::GetMn(int(TUCh::Mx), ItemV.Len())); bool TitleP = false, NmObjP = false, EmphP = false, AnchorP = false; for (int ItemN = 0; ItemN < ItemV.Len(); ItemN++) { const TWdGixItem& Item = ItemV[ItemN]; TitleP = TitleP || Item.IsTitle(); NmObjP = NmObjP || Item.IsNmObj(); EmphP = EmphP || Item.IsAnchor(); AnchorP = AnchorP || Item.IsEmph(); } TWdGixItem Item(Seg, Addr, Wgt, Count, TitleP, NmObjP, AnchorP, EmphP); // add ti index WGix->AddItem(WId, Item); } } bool TWdGix::Search(const TStr& QueryStr, TWdGixItemV& ResItemV) { //HACK simple parsing (no operators...) PWGixExpItem WGixExp = TWGixExpItem::NewEmpty(); PSIn HtmlSIn = TStrIn::New(QueryStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // stem the word WordStr=Stemmer->GetStem(WordStr); // check if we have it const int WId = WordH.GetKeyId(WordStr); if (WId != -1) { PWGixExpItem WGixExpItem = TWGixExpItem::NewItem(WId); if (WGixExp->IsEmpty()) { WGixExp = WGixExpItem; } else { WGixExp = TWGixExpItem::NewAnd(WGixExp, WGixExpItem); } } } // get next symbol HtmlLx.GetSym(); } // search return WGixExp->Eval(WGix, ResItemV); } ///////////////////////////////////////////////// // WdGix-Meta-Data-Base void TWdGixMDS::AddDate(const TBlobPt& DocBlobPt, const TTm& DateTime) { TAddrPr AddrPr(DocBlobPt.GetSeg(), DocBlobPt.GetAddr()); const uint64 DateMSecs = TTm::GetMSecsFromTm(DateTime); AddrPrToDateH.AddDat(AddrPr, DateMSecs); } inline uint64 TWdGixMDS::GetDateMSecs(const TBlobPt& DocBlobPt) const { return AddrPrToDateH.GetDat(TAddrPr(DocBlobPt.GetSeg(), DocBlobPt.GetAddr())); } inline TTm TWdGixMDS::GetDateTTm(const TBlobPt& DocBlobPt) const { return TTm::GetTmFromMSecs(GetDateMSecs(DocBlobPt)); } ///////////////////////////////////////////////// // WdGix-Result-Set void TWdGixRSet::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV, const TTm& DateTime) { DocTitleV.Add(DocTitle); DocTitleV.Last().DelChAll('\n'); DocTitleV.Last().DelChAll('\r'); DocStrV.Add(DocStr); CatNmVV.Add(CatNmV); DateTimeV.Add(DateTime); } void TWdGixRSet::SortByDate(const bool& Asc) { // sort hits by date typedef TPair<TUInt64, TInt> TUInt64IntPr; TVec<TUInt64IntPr> TmMSecsDocNV; const int Docs = GetDocs(); for (int DocN = 0; DocN < Docs; DocN++) { uint64 TmMSecs = TTm::GetMSecsFromTm(DateTimeV[DocN]); TmMSecsDocNV.Add(TUInt64IntPr(TmMSecs, DocN)); } TmMSecsDocNV.Sort(Asc); // resort the original vectors TStrV NewDocTitleV(Docs, 0), NewDocStrV(Docs, 0); TVec<TStrV> NewCatNmVV(Docs, 0); TTmV NewDateTimeV(Docs, 0); for (int NewDocN = 0; NewDocN < Docs; NewDocN++) { const int OldDocN = TmMSecsDocNV[NewDocN].Val2; NewDocTitleV.Add(DocTitleV[OldDocN]); NewDocStrV.Add(DocStrV[OldDocN]); NewCatNmVV.Add(CatNmVV[OldDocN]); NewDateTimeV.Add(DateTimeV[OldDocN]); } DocTitleV = NewDocTitleV; DocStrV = NewDocStrV; CatNmVV = NewCatNmVV; DateTimeV = NewDateTimeV; } void TWdGixRSet::PrintRes(PNotify Notify) { const int Docs = GetDocs(); Notify->OnStatus(TStr::Fmt( "All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); for (int DocN = 0; DocN < Docs; DocN++) { TTm DateTime = DateTimeV[DocN]; if (DateTime.IsDef()) { Notify->OnStatus(TStr::Fmt("[%d: %s] %s ...", DocN+1, DateTime.GetWebLogDateStr().CStr(), DocTitleV[DocN].Left(50).CStr())); } else { Notify->OnStatus(TStr::Fmt("[%d] %s ...", DocN+1, DocTitleV[DocN].Left(60).CStr())); } } Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); } PBowDocBs TWdGixRSet::GenBowDocBs() const { PSwSet SwSet = TSwSet::New(swstEn523); PStemmer Stemmer = TStemmer::New(stmtPorter, true); PBowDocBs BowDocBs = TBowDocBs::New(SwSet, Stemmer, NULL); const int Docs = GetDocs(); for (int DocN = 0; DocN < Docs; DocN++) { const TStr& DocNm = DocTitleV[DocN]; const TStr& DocStr = DocStrV[DocN]; BowDocBs->AddHtmlDoc(DocNm, TStrV(), DocStr, true); } return BowDocBs; } ///////////////////////////////////////////////// // WdGix-Base void TWdGixBs::Filter(const TWgtWdGixItemKdV& InItemV, const TWdGixBsGrouping& Grouping, TWgtWdGixItemKdV& OutItemV) { OutItemV.Clr(); if (Grouping == wgbgName) { // group by name and remember best ranked item for it TStrFltH NameToRankH; TStrH NameToItemNH; const int Items = InItemV.Len(); for (int ItemN = 0; ItemN < Items; ItemN++) { TBlobPt BlobPt = InItemV[ItemN].Dat.GetBlobPt(); TStr Name = GetDocTitle(BlobPt); const double Rank = InItemV[ItemN].Key; if (NameToRankH.IsKey(Name)) { //TODO why? const int KeyId = NameToRankH.GetKeyId(Name); const double OldRank = NameToRankH.GetDat(Name); if (Rank > OldRank) { NameToRankH.GetDat(Name) = Rank; NameToItemNH.GetDat(Name) = ItemN; } } else { NameToRankH.AddDat(Name) = Rank; NameToItemNH.AddDat(Name) = ItemN; } } // load the best items int othe OutItemV int KeyId = NameToItemNH.FFirstKeyId(); while (NameToItemNH.FNextKeyId(KeyId)) { const int ItemN = NameToItemNH[KeyId]; OutItemV.Add(InItemV[ItemN]); } } else if (Grouping == wgbgDate) { Fail; } else if (Grouping == wgbgDateTime) { Fail; } } TWdGixBs::TWdGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // create blob base TStr WdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixBsFNm; DocBBs = TMBlobBs::New(WdGixBsFNm, FAccess); // load metadata store if (FAccess == faCreate) { WdGixMDS = TWdGixMDS::New(); } else { TStr WdGixMDSFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixMDSFNm; WdGixMDS = TWdGixMDS::LoadBin(WdGixMDSFNm); } // load inverted index WdGix = TWdGix::New(FPath, FAccess, CacheSize); } TWdGixBs::~TWdGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { TStr WdGixMDSFNm = TStr::GetNrFPath(FPath) + TGixConst::WdGixMDSFNm; WdGixMDS->SaveBin(WdGixMDSFNm); } } void TWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV, const TTm& DateTime, const uchar& Wgt) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // save to metadata store if (DateTime.IsDef()) { WdGixMDS->AddDate(DocBlobPt, DateTime); } // add to index WdGix->AddHtml(DocStr, DocBlobPt, Wgt); } void TWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStoreStr, const TStr& DocIndexStr, const TStrV& CatNmV, const TTm& DateTime, const uchar& Wgt) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStoreStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // save to metadata store if (DateTime.IsDef()) { WdGixMDS->AddDate(DocBlobPt, DateTime); } // add to index WdGix->AddHtml(DocIndexStr, DocBlobPt, Wgt); } void TWdGixBs::GetDoc(const TBlobPt& BlobPt, TStr& DocTitle, TStr& DocStr, TStrV& CatNmV) const { PSIn SIn = DocBBs->GetBlob(BlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); CatNmV.Load(*SIn); } TStr TWdGixBs::GetDocTitle(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); TStr DocTitle; DocTitle.Load(*SIn); return DocTitle; } TStr TWdGixBs::GetDocStr(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} TStr DocStr; DocStr.Load(*SIn); return DocStr; } TStrV TWdGixBs::GetDocCatNmV(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} {TStr DocStr; DocStr.Load(*SIn);} TStrV CatNmV; CatNmV.Load(*SIn); return CatNmV; } PWdGixRSet TWdGixBs::SearchDoc(const TStr& QueryStr, const TWdGixBsGrouping& Grouping, TWdGixRankFun& RankFun, const int& Docs, const int& Offset, const TTm& MnDate, const TTm& MxDate) { // retrieve list of matching documents from inverted index printf(" Loading from Gix ...\n"); TWdGixItemV ResItemV; WdGix->Search(QueryStr, ResItemV); // sort and filter by date the documents printf(" Weighting %d hits ...\n", ResItemV.Len()); TWgtWdGixItemKdV FullWgtItemV(ResItemV.Len(), 0); const bool CheckMnDateP = MnDate.IsDef(); const bool CheckMxDateP = MxDate.IsDef(); for (int ItemN = 0; ItemN < ResItemV.Len(); ItemN++) { const TWdGixItem& Item = ResItemV[ItemN]; TTm DateTime = WdGixMDS->GetDateTTm(Item.GetBlobPt()); // check if document in time range if (CheckMnDateP && DateTime < MnDate) { continue; } if (CheckMxDateP && DateTime > MxDate) { continue; } // calculate the ranking weight of the document const double Wgt = RankFun(DateTime, Item.GetWgt(), Item.GetWdPos(), Item.IsTitle(), Item.IsNmObj(), Item.IsAnchor(), Item.IsEmph()); // add to the full result list FullWgtItemV.Add(TWgtWdGixItemKd(Wgt, Item)); } // filter the result list printf(" Filtering ...\n"); if (Grouping != wgbgNone) { TWgtWdGixItemKdV TmpWgtItemV; Filter(FullWgtItemV, Grouping, TmpWgtItemV); FullWgtItemV = TmpWgtItemV; } // select the correct portion of documents printf(" Sorting %d hits ...\n", FullWgtItemV.Len()); TWgtWdGixItemKdV WgtItemV; if (Docs == -1) { // return all resuts WgtItemV = FullWgtItemV; } else if (ResItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtItemV = FullWgtItemV; WgtItemV.Sort(false); WgtItemV.Trunc(Docs + Offset); WgtItemV.Sort(true); WgtItemV.Trunc(Docs); } else if (ResItemV.Len() > Offset) { // last page ... WgtItemV = FullWgtItemV; WgtItemV.Sort(true); WgtItemV.Trunc(FullWgtItemV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtItemV.Sort(false); // feed them to the result set printf(" Loading content for %d hits ...\n", WgtItemV.Len()); PWdGixRSet RSet = TWdGixRSet::New( QueryStr, FullWgtItemV.Len(), Offset); for (int ItemN = 0; ItemN < WgtItemV.Len(); ItemN++) { const TWdGixItem& Item = WgtItemV[ItemN].Dat; TBlobPt DocBlobPt = Item.GetBlobPt(); TStr DocTitle, DocStr; TStrV CatNmV; GetDoc(DocBlobPt, DocTitle, DocStr, CatNmV); TTm DateTime = WdGixMDS->GetDateTTm(DocBlobPt); RSet->AddDoc(DocTitle, DocStr, CatNmV, DateTime); } printf(" Done\n"); return RSet; } void TWdGixBs::AddReuters(const TStr& XmlFNm) { // parse reuters articles PXmlDoc Doc=TXmlDoc::LoadTxt(XmlFNm); // parse date TStr DateStr = Doc->GetTagTok("newsitem")->GetArgVal("date"); TTm DateTm = TTm::GetTmFromWebLogDateTimeStr(DateStr, '-'); // parse content TChA DocChA; DocChA += "<doc>"; TStr DocTitle = Doc->GetTagTok("newsitem|title")->GetTokStr(false); DocChA += "<title>"; DocChA += TXmlDoc::GetXmlStr(DocTitle); DocChA += "</title>"; DocChA += "<body>"; // get headline as emphesised text TStr DocHeadline = Doc->GetTagTok("newsitem|headline")->GetTokStr(false); DocChA += "<p><em>"; DocChA += TXmlDoc::GetXmlStr(DocHeadline); DocChA += "</em></p>\n"; // document content TXmlTokV ParTokV; Doc->GetTagTokV("newsitem|text|p", ParTokV); for (int ParTokN = 0; ParTokN < ParTokV.Len(); ParTokN++){ TStr ParStr = TXmlDoc::GetXmlStr(ParTokV[ParTokN]->GetTokStr(false)); TXmlTokV NmObjTokV; ParTokV[ParTokN]->GetTagTokV("enamex", NmObjTokV); // mark name entities for (int NmObjTokN = 0; NmObjTokN < NmObjTokV.Len(); NmObjTokN++) { TStr NmObjStr = TXmlDoc::GetXmlStr(NmObjTokV[NmObjTokN]->GetTokStr(false)); ParStr.ChangeStrAll(NmObjStr, "<nmobj>" + NmObjStr + "</nmobj>"); } DocChA += "<p>"; DocChA += ParStr; DocChA += "</p>"; } DocChA += "</body></doc>"; // categories TStrV CatNmV; TXmlTokV CdsTokV; Doc->GetTagTokV("newsitem|metadata|codes", CdsTokV); for (int CdsTokN = 0; CdsTokN < CdsTokV.Len(); CdsTokN++){ PXmlTok CdsTok = CdsTokV[CdsTokN]; TXmlTokV CdTokV; CdsTok->GetTagTokV("code", CdTokV); if (CdsTok->GetArgVal("class") == "bip:topics:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm = CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else if (CdsTok->GetArgVal("class")=="bip:countries:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm=CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else if (CdsTok->GetArgVal("class")=="bip:industries:1.0"){ for (int CdTokN = 0; CdTokN < CdTokV.Len(); CdTokN++){ TStr CdNm=CdTokV[CdTokN]->GetArgVal("code"); CatNmV.AddMerged(CdNm); } } else { Fail; } } // store the news article to the search base AddDoc(DocTitle, DocChA, CatNmV, DateTm); } void TWdGixBs::IndexReuters(const TStr& FPath) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading Reuters documents from " + FPath + " ...\n"); TFFile FFile(FPath, ".xml", true); TStr XmlFNm; int Files = 0; while (FFile.Next(XmlFNm)) { //if (Files > 10000) { break; } // load document if (TFile::Exists(XmlFNm)) { AddReuters(XmlFNm); Files++; } // print statistics if (Files % 1000 == 0) { Notify->OnStatus(TStr::Fmt("F:%d\r", Files)); } } Notify->OnStatus(TStr::Fmt("F:%d\n", Files)); } void TWdGixBs::IndexNmEnBs(const TStr& FNm) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading name-entitites from " + FNm + " ...\n"); // load name-entity base together with contexts PNmEnBs NmEnBs = TNmEnBs::LoadBin(FNm, true); // add name-entities to int NmEnKeyId = NmEnBs->GetFFirstNmEn(); int NmEnN = 0; const int NmEns = NmEnBs->GetNmEns(); while (NmEnBs->GetFNextNmEn(NmEnKeyId)) { if (NmEnN > 100000) { break; } // print statistics if (NmEnN % 1000 == 0) { Notify->OnStatus(TStr::Fmt("N:%d/%d\r", NmEnN, NmEns)); } // get name-entity name TStr NmEnStr = NmEnBs->GetNmEnStr(NmEnKeyId); IAssertR(NmEnBs->IsNmEn(NmEnStr), NmEnStr); // iterate over all the mentions of the name-entity // and concatenate them accross days THash<TUInt, TChA> DateIntToCtxH; THash<TUInt, TInt> DateIntToCountH; const TIntV& NmEnCtxIdV = NmEnBs->GetCtxIdV(NmEnKeyId); for (int CtxIdN = 0; CtxIdN < NmEnCtxIdV.Len(); CtxIdN++) { const int CtxId = NmEnCtxIdV[CtxIdN]; TStr NmEnCtxStr = NmEnBs->GetCtxStr(CtxId); TTm NmEnCtxTm = NmEnBs->GetCtxTm(CtxId); const uint DateInt = TTm::GetDateIntFromTm(NmEnCtxTm); DateIntToCtxH.AddDat(DateInt) += NmEnCtxStr; DateIntToCountH.AddDat(DateInt)++; } // store the name-entity to the search base per day int CtxKeyId = DateIntToCtxH.FFirstKeyId(); while (DateIntToCtxH.FNextKeyId(CtxKeyId)) { const int DateInt = DateIntToCtxH.GetKey(CtxKeyId); TTm CtxDate = TTm::GetTmFromDateTimeInt(DateInt); TStr CtxStr = DateIntToCtxH[CtxKeyId]; const uchar Wgt = uchar(DateIntToCountH.GetDat(DateInt).Val); AddDoc(NmEnStr, CtxStr, TStrV(), CtxDate, Wgt); } // next NmEnN++; } Notify->OnStatus(TStr::Fmt("N:%d/%d", NmEnN, NmEns)); } void TWdGixBs::IndexNyt(const TStr& XmlFNm) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading NYT documents from " + XmlFNm + " ...\n"); PSIn SIn = TFIn::New(XmlFNm); int Docs = 0; TStr LastTitle = ""; forever { if (Docs % 1000 == 0) { Notify->OnStatus(TStr::Fmt("Docs: %d\r", Docs)); } PXmlDoc Doc = TXmlDoc::LoadTxt(SIn); Docs++; if (!Doc->IsOk()) { printf("%s - %s\n", LastTitle.CStr(), Doc->GetMsgStr().CStr()); break; } // parse date TStr DateStr = Doc->GetTagTok("newsitem")->GetArgVal("date"); TTm DateTm = TTm::GetTmFromWebLogDateTimeStr(DateStr, '-'); // parse content TChA DocChA; DocChA += "<doc>"; TStr DocTitle = Doc->GetTagTok("newsitem|title")->GetTokStr(false); DocChA += "<title>"; DocChA += TXmlDoc::GetXmlStr(DocTitle); DocChA += "</title>"; DocChA += "<body>"; // document content TXmlTokV ParTokV; Doc->GetTagTokV("newsitem|text|p", ParTokV); for (int ParTokN = 0; ParTokN < ParTokV.Len(); ParTokN++){ TStr ParStr = TXmlDoc::GetXmlStr(ParTokV[ParTokN]->GetTokStr(false)); TXmlTokV NmObjTokV; ParTokV[ParTokN]->GetTagTokV("ent", NmObjTokV); // mark name entities for (int NmObjTokN = 0; NmObjTokN < NmObjTokV.Len(); NmObjTokN++) { TStr NmObjStr = TXmlDoc::GetXmlStr(NmObjTokV[NmObjTokN]->GetTokStr(false)); ParStr.ChangeStrAll(NmObjStr, "<nmobj>" + NmObjStr + "</nmobj>"); } DocChA += "<p>"; DocChA += ParStr; DocChA += "</p>"; } DocChA += "</body></doc>"; // store the news article to the search base AddDoc(DocTitle, DocChA, TStrV(), DateTm); LastTitle = DocTitle; } Notify->OnStatus(TStr::Fmt("Docs: %d", Docs)); } ///////////////////////////////////////////////// // Search-Topics TSearchTopics::TSearchTopics(PWdGixRSet RSet, const int& Topics) { PBowDocBs BowDocBs = RSet->GenBowDocBs(); TRnd Rnd(1); PBowDocPart BowDocPart = TBowClust::GetKMeansPart( TNullNotify::New(), BowDocBs, TBowSim::New(bstCos), Rnd, Topics, 1, 10, 1, bwwtLogDFNrmTFIDF, 0.0, 0); TopicV.Gen(Topics, 0); TIntH FrameH; THash<TInt, TIntH> FrameTopicHH; for (int ClustN = 0; ClustN < BowDocPart->GetClusts(); ClustN++) { PBowDocPartClust Clust = BowDocPart->GetClust(ClustN); TStr TopicNm = Clust->GetConceptSpV()->GetStr(BowDocBs, 3, 1, ", ", false, false); TopicV.Add(TopicNm); for (int DocN = 0; DocN < Clust->GetDocs(); DocN++) { const int DocId = Clust->GetDId(DocN); TTm DocDate = RSet->GetDocDateTime(DocId); //const uint FrameId = TTm::GetMonthIntFromTm(DocDate); const uint FrameId = TTm::GetYearIntFromTm(DocDate); FrameH.AddDat(FrameId)++; FrameTopicHH.AddDat(FrameId).AddDat(ClustN)++; } } const int Frames = FrameH.Len(); FrameV.Gen(Frames, 0); TopicFrameFqVV.Gen(Topics, Frames); TopicFrameFqVV.PutAll(0.0); FrameH.SortByKey(); int FrameKeyId = FrameH.FFirstKeyId(); while (FrameH.FNextKeyId(FrameKeyId)) { int FrameId = FrameH.GetKey(FrameKeyId); // load name TTm FrameDate = TTm::GetTmFromDateTimeInt(FrameId); //TStr FrameNm = TStr::Fmt("%4d-%2d", FrameDate.GetYear(), FrameDate.GetMonth()); TStr FrameNm = TStr::Fmt("%4d", FrameDate.GetYear()); const int FrameN = FrameV.Add(FrameNm); // load counts //const int FrameCounts = FrameH.GetDat(FrameId); const TIntH& TopicH = FrameTopicHH.GetDat(FrameId); int TopicKeyId = TopicH.FFirstKeyId(); int CountSum = 0; while (TopicH.FNextKeyId(TopicKeyId)) { const int TopicN = TopicH.GetKey(TopicKeyId); int TopicCount = TInt::Abs(TopicH.GetDat(TopicKeyId)) > 1000 ? 0 : TopicH.GetDat(TopicKeyId)(); CountSum += TopicCount; const double Fq = double(CountSum); // / double(FrameCounts); TopicFrameFqVV(TopicN, FrameN) = Fq; } } } ///////////////////////////////////////////////// // Triplet-Inverted-Index-Item TTrGixItem::TTrGixItem(const TBlobPt& BlobPt, const int& _SubjectId, const int& _PredicatId, const int& _ObjectId, const int& _WdId, const uchar& Type, const uchar& Pos, const bool& Full, const bool& Stem, const uchar& Hyper): Seg(BlobPt.GetSeg()), Addr(BlobPt.GetAddr()), SubjectId(_SubjectId), PredicatId(_PredicatId), ObjectId(_ObjectId), WdId(_WdId) { SetWordInfo(Type, Pos, Full, Stem, Hyper); ClrMergeInfo(); } TTrGixItem::TTrGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(SubjectId); SIn.Load(PredicatId); SIn.Load(ObjectId); SIn.Load(WdId); SIn.Load(WdInfo); ClrMergeInfo(); } void TTrGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(SubjectId); SOut.Save(PredicatId); SOut.Save(ObjectId); SOut.Save(WdId); SOut.Save(WdInfo); } bool TTrGixItem::operator==(const TTrGixItem& Item) const { return ((Seg==Item.Seg)&&(Addr==Item.Addr)&& (SubjectId==Item.SubjectId)&& (PredicatId==Item.PredicatId)&& (ObjectId==Item.ObjectId)); } bool TTrGixItem::operator<(const TTrGixItem& Item) const { return (Seg<Item.Seg) || ((Seg==Item.Seg)&&(Addr<Item.Addr)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId<Item.SubjectId)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId==Item.SubjectId)&&(PredicatId<Item.PredicatId)) || ((Seg==Item.Seg)&&(Addr==Item.Addr)&&(SubjectId==Item.SubjectId)&&(PredicatId==Item.PredicatId)&&(ObjectId<Item.ObjectId)); } void TTrGixItem::SetWordInfo(const uchar& Type, const uchar& Pos, const bool& Full, const bool& Stem, const uchar& Hyper) { TTrGixItemWdInfo Info; Info.Short = 0; Info.Bits.Type = Type; Info.Bits.Pos = Type; Info.Bits.Full = Full ? 1 : 0; Info.Bits.Stem = Stem ? 1 : 0; Info.Bits.Hyper = Hyper; WdInfo = Info.Short; } ///////////////////////////////////////////////// // Triplet-Inverted-Index char TTrGix::SubjectType = 0; char TTrGix::SubjectWdType = 1; char TTrGix::SubjectAttrWdType = 2; char TTrGix::SubjectStemType = 3; char TTrGix::SubjectAttrStemType = 4; char TTrGix::PredicatType = 5; char TTrGix::PredicatWdType = 6; char TTrGix::PredicatAttrWdType = 7; char TTrGix::PredicatStemType = 8; char TTrGix::PredicatAttrStemType = 9; char TTrGix::ObjectType = 10; char TTrGix::ObjectWdType = 11; char TTrGix::ObjectAttrWdType = 12; char TTrGix::ObjectStemType = 13; char TTrGix::ObjectAttrStemType = 14; void TTrGix::AddTrPart(const int& FullId, const char& Type, const int& SubjectId, const int& PredicatId, const int& ObjectId, const TBlobPt& BlobPt) { // add to the index Gix->AddItem(TTrGixKey(FullId, Type), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, FullId, Type, 0, true, false, 0)); } void TTrGix::AddTrPart(const TIntPrV& IdPrV, const char& WdType, const char& StemType, const int& SubjectId, const int& PredicatId, const int& ObjectId, const TBlobPt& BlobPt) { for (int IdPrN = 0; IdPrN < IdPrV.Len(); IdPrN++) { // add word to the index const int WdId = IdPrV[IdPrN].Val1; Gix->AddItem(TTrGixKey(WdId, WdType), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, WdId, WdType, IdPrN, false, false, 0)); // add stem to the index const int StemId = IdPrV[IdPrN].Val2; Gix->AddItem(TTrGixKey(StemId, StemType), TTrGixItem(BlobPt, SubjectId, PredicatId, ObjectId, StemId, StemType, IdPrN, false, true, 0)); } } TTrGix::PTGixExpItem TTrGix::GetExactExp(const TStr& Str, const char& Type) { TTrGixKey FullTrKey = TTrGixKey(GetWordId(Str, false), Type); return TTGixExpItem::NewItem(FullTrKey); } TTrGix::PTGixExpItem TTrGix::GetPartExp(const TStr& Str, const char& WdType, const char& StemType) { // get word/stem ids from the string TIntPrV WordStemIdV; GetWordIdV(Str, WordStemIdV, false); // prepare the expresion for these words/stems PTGixExpItem Exp = TTGixExpItem::NewEmpty(); for (int WordStemIdN = 0; WordStemIdN < WordStemIdV.Len(); WordStemIdN++) { // prepare the search keys for both word and for the stem TTrGixKey WdKey(WordStemIdV[WordStemIdN].Val1, WdType); TTrGixKey StemKey(WordStemIdV[WordStemIdN].Val2, StemType); // either of the two should appear PTGixExpItem ExpItem = TTGixExpItem::NewOr( TTGixExpItem::NewItem(WdKey), TTGixExpItem::NewItem(StemKey)); // update the expresion with the new word/stem if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } return Exp; } TTrGix::TTrGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // prepare gix Gix = TTGix::New(TGixConst::TrGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess == faCreate) { Stemmer = TStemmer::New(stmtPorter, true); } else { // prepare file name TStr TrGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDatFNm; // load stuff TFIn FIn(TrGixDatFNm); WordH.Load(FIn); Stemmer = TStemmer::Load(FIn); } } TTrGix::~TTrGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // prepare file name TStr TrGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDatFNm; // save word tables TFOut FOut(TrGixDatFNm); WordH.Save(FOut); Stemmer->Save(FOut); } } int TTrGix::GetWordId(const TStr& WordStr, const bool& AddIfNotExistP) { if (WordStr.Empty()) { return -1; } // should we just do a look-up or add the word if not exist if (AddIfNotExistP) { return WordH.AddKey(WordStr.GetUc()); } else { return WordH.GetKeyId(WordStr.GetUc()); } } inline TStr TTrGix::GetWordStr(const int& WId) const { return WId != -1 ? WordH.GetKey(WId) : ""; } void TTrGix::GetWordIdV(const TStr& Str, TIntPrV& WordStemIdV, const bool& AddIfNotExistP) { // tokenize the phrase PSIn HtmlSIn = TStrIn::New(Str); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { const TStr WordStr = HtmlLx.UcChA; // get the word id const int WordId = GetWordId(WordStr, AddIfNotExistP); // get the stem id const int StemId = GetWordId(Stemmer->GetStem(WordStr), AddIfNotExistP); // store it WordStemIdV.Add(TIntPr(WordId, StemId)); } HtmlLx.GetSym(); } } void TTrGix::GetWordIdV(const TStrV& WordStrV, TIntPrV& WordStemIdV, const bool& AddIfNotExistP) { // just iterate over all the elements and get their word-stem pairs for (int WordStrN = 0; WordStrN < WordStrV.Len(); WordStrN++) { GetWordIdV(WordStrV[WordStrN], WordStemIdV, AddIfNotExistP); } } void TTrGix::AddTr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& BlobPt) { // store full strings const int SubjectId = GetWordId(SubjectStr, true); const int PredicatId = GetWordId(PredicatStr, true); const int ObjectId = GetWordId(ObjectStr, true); // add them to the index AddTrPart(SubjectId, SubjectType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatId, PredicatType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectId, ObjectType, SubjectId, PredicatId, ObjectId, BlobPt); // get ids of separate words and their stems, including from attributes TIntPrV SubjectWIdSIdV; GetWordIdV(SubjectStr, SubjectWIdSIdV, true); TIntPrV SubjectAttrWIdSIdV; GetWordIdV(SubjectAttrV, SubjectAttrWIdSIdV, true); TIntPrV PredicatWIdSIdV; GetWordIdV(PredicatStr, PredicatWIdSIdV, true); TIntPrV PredicatAttrWIdSIdV; GetWordIdV(PredicatAttrV, PredicatAttrWIdSIdV, true); TIntPrV ObjectWIdSIdV; GetWordIdV(ObjectStr, ObjectWIdSIdV, true); TIntPrV ObjectAttrWIdSIdV; GetWordIdV(ObjectAttrV, ObjectAttrWIdSIdV, true); // add them to the index AddTrPart(SubjectWIdSIdV, SubjectWdType, SubjectStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(SubjectAttrWIdSIdV, SubjectAttrWdType, SubjectAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatWIdSIdV, PredicatWdType, PredicatStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(PredicatAttrWIdSIdV, PredicatAttrWdType, PredicatAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectWIdSIdV, ObjectWdType, ObjectStemType, SubjectId, PredicatId, ObjectId, BlobPt); AddTrPart(ObjectAttrWIdSIdV, ObjectAttrWdType, ObjectAttrStemType, SubjectId, PredicatId, ObjectId, BlobPt); } bool TTrGix::SearchExact(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixItemV& ResItemV) { // generate exprasion PTGixExpItem Exp = TTGixExpItem::NewEmpty(); if (!SubjectStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(SubjectStr, SubjectType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!PredicatStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(PredicatStr, PredicatType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!ObjectStr.Empty()) { PTGixExpItem ExpItem = GetExactExp(ObjectStr, ObjectType); if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } // evaluate the expresion return Exp->Eval(Gix, ResItemV); } bool TTrGix::SearchPart(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixItemV& ResItemV, const bool& IncExactP) { // generate exprasion PTGixExpItem Exp = TTGixExpItem::NewEmpty(); if (!SubjectStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(SubjectStr, SubjectWdType, SubjectStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(SubjectStr, SubjectType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!PredicatStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(PredicatStr, PredicatWdType, PredicatStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(PredicatStr, PredicatType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } if (!ObjectStr.Empty()) { PTGixExpItem ExpItem = GetPartExp(ObjectStr, ObjectWdType, ObjectStemType); if (IncExactP) { TTGixExpItem::NewOr(GetExactExp(ObjectStr, ObjectType), ExpItem); } if (Exp->IsEmpty()) { Exp = ExpItem; } else { Exp = TTGixExpItem::NewAnd(Exp, ExpItem); } } // evaluate the expresion return Exp->Eval(Gix, ResItemV); } ///////////////////////////////////////////////// // TrGix-Result-Set void TTrGixRSet::AddTr(const TStrTr& TrStr, const TBlobPtV& TrAttrBlobPtV) { TrStrV.Add(TrStr); TrAttrBlobPtVV.Add(TrAttrBlobPtV); } void TTrGixRSet::GetSubjectV(TStrIntKdV& SubjectStrWgtV) { TIntStrKdV SubjectWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& SubjectStr = TrStrV[TrN].Val1; const int Wgt = GetTrCount(TrN); SubjectWgtStrV.Add(TIntStrKd(Wgt, SubjectStr)); } SubjectWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(SubjectWgtStrV, SubjectStrWgtV); } void TTrGixRSet::GetPredicatV(TStrIntKdV& PredicatStrWgtV) { TIntStrKdV PredicatWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& PredicatStr = TrStrV[TrN].Val2; const int Wgt = GetTrCount(TrN); PredicatWgtStrV.Add(TIntStrKd(Wgt, PredicatStr)); } PredicatWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(PredicatWgtStrV, PredicatStrWgtV); } void TTrGixRSet::GetObjectV(TStrIntKdV& ObjectStrWgtV) { TIntStrKdV ObjectWgtStrV; for (int TrN = 0; TrN < GetTrs(); TrN++) { const TStr& ObjectStr = TrStrV[TrN].Val3; const int Wgt = GetTrCount(TrN); ObjectWgtStrV.Add(TIntStrKd(Wgt, ObjectStr)); } ObjectWgtStrV.Sort(false); GetSwitchedKdV<TInt, TStr>(ObjectWgtStrV, ObjectStrWgtV); } void TTrGixRSet::PrintRes(const bool& PrintSentsP, PNotify Notify) const { // result set stats printf("Query:\n"); printf(" Subject: '%s'\n", GetSubjectStr().CStr()); printf(" Predicat: '%s'\n", GetPredicatStr().CStr()); printf(" Object: '%s'\n", GetObjectStr().CStr()); printf("Displaying: %d - %d (All hits: %d)\n", GetOffset()+1, Offset.Val+GetTrs()+1, GetAllTrs()); // hits for (int TrN = 0; TrN < GetTrs(); TrN++) { printf("%d. [%s <- %s -> %s], (Support:%d)\n", TrN+GetOffset()+1, GetTrSubjectStr(TrN).CStr(), GetTrPredicatStr(TrN).CStr(), GetTrObjectStr(TrN).CStr(), GetTrCount(TrN)); //if (PrintSentsP) { // for (int SentN = 0; SentN < GetTrSents(TrN); SentN++) { // const TStr& SentStr = GetTrSentStr(TrN, SentN); // if (SentStr.Len() < 110) { printf(" %s\n", SentStr.CStr()); } // else { printf(" %s...\n", SentStr.Left(110).CStr()); } // } //} } } ///////////////////////////////////////////////// // TrGix-Merger ///////////////////////////////////////////////// // TrGix-Base void TTrGixBs::GetAttrV(PXmlTok XmlTok, TStrV& AttrV) { TXmlTokV AttrTokV; XmlTok->GetTagTokV("attrib", AttrTokV); for (int AttrTokN = 0; AttrTokN < AttrTokV.Len(); AttrTokN++) { PXmlTok AttrTok = AttrTokV[AttrTokN]; AttrV.Add(AttrTok->GetStrArgVal("word")); GetAttrV(AttrTok, AttrV); } } TTrGixBs::TTrGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; // create document blob base TStr TrGixDocBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixDocBsFNm; DocBBs = TMBlobBs::New(TrGixDocBsFNm, FAccess); // create sentence blob base TStr TrGixSentBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixSentBsFNm; SentBBs = TMBlobBs::New(TrGixSentBsFNm, FAccess); // create triplet attribute blob base TStr TrGixTrAttrBsFNm = TStr::GetNrFPath(FPath) + TGixConst::TrGixTrAttrBsFNm; TrAttrBBs = TMBlobBs::New(TrGixTrAttrBsFNm, FAccess); // load inverted index TrGix = TTrGix::New(FPath, FAccess, CacheSize); } TTrGixBs::~TTrGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { // save whatever doesnt save itself automaticaly in destructor } } TBlobPt TTrGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStrV& CatNmV) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); CatNmV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); return DocBlobPt; } TBlobPt TTrGixBs::AddSent(const TStr& SentStr) { TMOut SentMOut; SentStr.Save(SentMOut); TBlobPt SentBlobPt = SentBBs->PutBlob(SentMOut.GetSIn()); return SentBlobPt; } TBlobPt TTrGixBs::AddTrAttr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& SentBlobPt, const TBlobPt& DocBlobPt) { TMOut TrAttrMOut; SubjectStr.Save(TrAttrMOut); SubjectAttrV.Save(TrAttrMOut); PredicatStr.Save(TrAttrMOut); PredicatAttrV.Save(TrAttrMOut); ObjectStr.Save(TrAttrMOut); ObjectAttrV.Save(TrAttrMOut); SentBlobPt.Save(TrAttrMOut); DocBlobPt.Save(TrAttrMOut); TBlobPt TrAttrBlobPt = TrAttrBBs->PutBlob(TrAttrMOut.GetSIn()); return TrAttrBlobPt; } void TTrGixBs::AddTr(const TStr& SubjectStr, const TStrV& SubjectAttrV, const TStr& PredicatStr, const TStrV& PredicatAttrV, const TStr& ObjectStr, const TStrV& ObjectAttrV, const TBlobPt& TrAttrBlobPt) { TrGix->AddTr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, TrAttrBlobPt); } void TTrGixBs::GetDoc(const TBlobPt& DocBlobPt, TStr& DocTitle, TStr& DocStr, TStrV& CatNmV) const { PSIn SIn = DocBBs->GetBlob(DocBlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); CatNmV.Load(*SIn); } TStr TTrGixBs::GetDocTitle(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); TStr DocTitle; DocTitle.Load(*SIn); return DocTitle; } TStr TTrGixBs::GetDocStr(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} TStr DocStr; DocStr.Load(*SIn); return DocStr; } TStrV TTrGixBs::GetDocCatNmV(const TBlobPt& BlobPt) const { PSIn SIn = DocBBs->GetBlob(BlobPt); {TStr DocTitle; DocTitle.Load(*SIn);} {TStr DocStr; DocStr.Load(*SIn);} TStrV CatNmV; CatNmV.Load(*SIn); return CatNmV; } TStr TTrGixBs::GetSentStr(const TBlobPt& SentBlobPt) { PSIn SIn = SentBBs->GetBlob(SentBlobPt); return TStr(*SIn); } void TTrGixBs::GetTrAttr(const TBlobPt& TrAttrBlobPt, TStr& SubjectStr, TStrV& SubjectAttrV, TStr& PredicatStr, TStrV& PredicatAttrV, TStr& ObjectStr, TStrV& ObjectAttrV, TBlobPt& SentBlobPt, TBlobPt& DocBlobPt) { PSIn SIn = TrAttrBBs->GetBlob(TrAttrBlobPt); SubjectStr.Load(*SIn); SubjectAttrV.Load(*SIn); PredicatStr.Load(*SIn); PredicatAttrV.Load(*SIn); ObjectStr.Load(*SIn); ObjectAttrV.Load(*SIn); SentBlobPt = TBlobPt(*SIn); DocBlobPt = TBlobPt(*SIn); } PTrGixRSet TTrGixBs::SearchTr(const TStr& SubjectStr, const TStr& PredicatStr, const TStr& ObjectStr, TTrGixRankFun& RankFun, const int& Docs, const int& Offset, const bool& ExactP) { // get all hits from index //printf(" Loading from Gix ...\n"); TTrGixItemV ResItemV; if (ExactP) { TrGix->SearchExact(SubjectStr, PredicatStr, ObjectStr, ResItemV); } else { TrGix->SearchPart(SubjectStr, PredicatStr, ObjectStr, ResItemV, true); } // grouping the hits by triplets //printf(" Grouping %d hits ...\n", ResItemV.Len()); THash<TIntTr, TIntV> TrToItemVH; for (int ItemN = 0; ItemN < ResItemV.Len(); ItemN++) { const TTrGixItem& Item = ResItemV[ItemN]; TrToItemVH.AddDat(Item.GetIdTr()).Add(ItemN); } // rank the triplets //printf(" Ranking %d triplets ...\n", TrToItemVH.Len()); TFltIntKdV FullWgtTrKeyIdV; int TrKeyId = TrToItemVH.FFirstKeyId(); while (TrToItemVH.FNextKeyId(TrKeyId)) { const double Wgt = RankFun(TrToItemVH[TrKeyId].Len()); FullWgtTrKeyIdV.Add(TFltIntKd(Wgt, TrKeyId)); } // select the correct portion of documents //printf(" Sorting %d triplets ...\n", TrToItemVH.Len()); TFltIntKdV WgtTrKeyIdV; if (Docs == -1) { // return all resuts WgtTrKeyIdV = FullWgtTrKeyIdV; } else if (ResItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtTrKeyIdV = FullWgtTrKeyIdV; WgtTrKeyIdV.Sort(false); WgtTrKeyIdV.Trunc(Docs + Offset); WgtTrKeyIdV.Sort(true); WgtTrKeyIdV.Trunc(Docs); } else if (ResItemV.Len() > Offset) { // last page ... WgtTrKeyIdV = FullWgtTrKeyIdV; WgtTrKeyIdV.Sort(true); WgtTrKeyIdV.Trunc(FullWgtTrKeyIdV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtTrKeyIdV.Sort(false); // feed them to the result set //printf(" Loading content for %d triplets ...\n", WgtTrKeyIdV.Len()); PTrGixRSet RSet = TTrGixRSet::New(SubjectStr, PredicatStr, ObjectStr, FullWgtTrKeyIdV.Len(), Offset); for (int TrN = 0; TrN < WgtTrKeyIdV.Len(); TrN++) { const int TrKeyId = WgtTrKeyIdV[TrN].Dat; const TIntTr& WIdTr = TrToItemVH.GetKey(TrKeyId); const TIntV& ItemV = TrToItemVH[TrKeyId]; TStr SubjectStr = TrGix->GetWordStr(WIdTr.Val1); TStr PredicatStr = TrGix->GetWordStr(WIdTr.Val2); TStr ObjectStr = TrGix->GetWordStr(WIdTr.Val3); TStrTr TrStr(SubjectStr, PredicatStr, ObjectStr); // load triplet attribute blob pointers TBlobPtV TrAttrBlobPtV; for (int ItemN = 0; ItemN < ItemV.Len(); ItemN++) { const TTrGixItem& Item = ResItemV[ItemV[ItemN]]; TBlobPt TrAttrBlobPt = Item.GetBlobPt(); TrAttrBlobPtV.Add(TrAttrBlobPt); } // add the triplet to the RSet RSet->AddTr(TrStr, TrAttrBlobPtV); } //printf(" Done\n"); return RSet; } void TTrGixBs::AddReuters(const TStr& XmlFNm, int& Trs, const PSOut& CsvOut) { PNotify Notify = TStdNotify::New(); // create empty document TBlobPt EmptyDocBlobPt = AddDoc("No full document text!"); // we skip the top tak so we only parse one sentence at a time PSIn XmlSIn = TFIn::New(XmlFNm); TXmlDoc::SkipTopTag(XmlSIn); PXmlDoc XmlDoc; int XmlDocs = 0; forever{ // print count if (Trs % 100 == 0) { Notify->OnStatus(TStr::Fmt("%d\r", Trs)); } // load xml tree XmlDocs++; XmlDoc = TXmlDoc::LoadTxt(XmlSIn); // stop if at the last tag if (!XmlDoc->IsOk()) { break; } // extract documents from xml-trees PXmlTok TopTok = XmlDoc->GetTok(); if (TopTok->IsTag("sentence")){ // read and store the document from which the sentence comes TStr DocStr = ""; TBlobPt DocBlobPt = EmptyDocBlobPt; // read and store the sentence from where the triplet comes TStr SentStr = TopTok->GetTagTok("originalSentence")->GetTokStr(false); TBlobPt SentBlobPt = AddSent(SentStr); // iterate over all the triplets and add them to the index TXmlTokV TrTokV; TopTok->GetTagTokV("triplet", TrTokV); for (int TrTokN = 0; TrTokN < TrTokV.Len(); TrTokN++) { PXmlTok TrTok = TrTokV[TrTokN]; TStr SubjectStr = TrTok->GetTagTok("subject")->GetStrArgVal("word"); TStr PredicatStr = TrTok->GetTagTok("verb")->GetStrArgVal("word"); TStr ObjectStr = TrTok->GetTagTok("object")->GetStrArgVal("word"); TStrV SubjectAttrV; GetAttrV(TrTok->GetTagTok("subject"), SubjectAttrV); TStrV PredicatAttrV; GetAttrV(TrTok->GetTagTok("verb"), PredicatAttrV); TStrV ObjectAttrV; GetAttrV(TrTok->GetTagTok("object"), ObjectAttrV); TBlobPt TrAttrBlobPt = AddTrAttr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, SentBlobPt, DocBlobPt); AddTr(SubjectStr, SubjectAttrV, PredicatStr, PredicatAttrV, ObjectStr, ObjectAttrV, TrAttrBlobPt); Trs++; // we should also output CSV file if (!CsvOut.Empty()) { // make sure no ',' in the strings and dump the triplet SubjectStr.DelChAll(','); CsvOut->PutStr(SubjectStr + ","); PredicatStr.DelChAll(','); CsvOut->PutStr(PredicatStr + ","); ObjectStr.DelChAll(','); CsvOut->PutStr(ObjectStr + ","); // dump the document blob pointer CsvOut->PutStr(TStr::Fmt("%u,", uint(SentBlobPt.GetSeg()))); CsvOut->PutStr(TStr::Fmt("%u,", SentBlobPt.GetAddr())); // dump the adjectives CsvOut->PutStr(TStr::Fmt("%d,", SubjectAttrV.Len())); for (int AttrN = 0; AttrN < SubjectAttrV.Len(); AttrN++) { SubjectAttrV[AttrN].DelChAll(','); CsvOut->PutStr(SubjectAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr(TStr::Fmt("%d,", PredicatAttrV.Len())); for (int AttrN = 0; AttrN < PredicatAttrV.Len(); AttrN++) { PredicatAttrV[AttrN].DelChAll(','); CsvOut->PutStr(PredicatAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr(TStr::Fmt("%d,", ObjectAttrV.Len())); for (int AttrN = 0; AttrN < ObjectAttrV.Len(); AttrN++) { ObjectAttrV[AttrN].DelChAll(','); CsvOut->PutStr(ObjectAttrV[AttrN]); CsvOut->PutStr(","); } CsvOut->PutStr("-1"); CsvOut->PutLn(); } } } } CsvOut->Flush(); } void TTrGixBs::IndexReuters(const TStr& XmlFPath, const TStr& CsvFNm, const int& MxTrs) { PNotify Notify = TStdNotify::New(); Notify->OnStatus("Loading Reuters documents from " + XmlFPath + " ...\n"); TFFile FFile(XmlFPath, ".xml", true); TStr XmlFNm; int Files = 0, Trs = 0; PSOut CsvOut; if (!CsvFNm.Empty()) { CsvOut = TFOut::New(CsvFNm); } while (FFile.Next(XmlFNm) && ((MxTrs == -11)||(MxTrs > Trs))) { // load document Notify->OnStatus(TStr::Fmt("Loading %3d : %s ...", Files+1, XmlFNm.CStr())); if (TFile::Exists(XmlFNm)) { AddReuters(XmlFNm, Trs, CsvOut); Files++; } } Notify->OnStatus(TStr::Fmt("Triplets loaded: %d", Trs)); } ///////////////////////////////////////////////// // Multilingual-Word-Inverted-Index-Item TMWdGixItem::TMWdGixItem(TSIn& SIn) { SIn.Load(Seg); SIn.Load(Addr); SIn.Load(WdFq); SIn.Load(DocWds); } void TMWdGixItem::Save(TSOut& SOut) const { SOut.Save(Seg); SOut.Save(Addr); SOut.Save(WdFq); SOut.Save(DocWds); } inline bool TMWdGixItem::operator==(const TMWdGixItem& Item) const { return (Seg == Item.Seg) && (Addr == Item.Addr); } inline bool TMWdGixItem::operator<(const TMWdGixItem& Item) const { return (Seg < Item.Seg) || ((Seg == Item.Seg) && (Addr < Item.Addr)); } ///////////////////////////////////////////////// // General-Inverted-Index-Default-Merger void TMWdGixDefMerger::Union(TMWdGixItemV& DstV, const TMWdGixItemV& SrcV) const { TMWdGixItemV DstValV(TInt::GetMx(DstV.Len(), SrcV.Len()), 0); int ValN1 = 0; int ValN2 = 0; while ((ValN1<DstV.Len()) && (ValN2<SrcV.Len())){ const TMWdGixItem& Val1 = DstV.GetVal(ValN1); const TMWdGixItem& Val2 = SrcV.GetVal(ValN2); if (Val1 < Val2) { DstValV.Add(Val1); ValN1++; } else if (Val1>Val2) { DstValV.Add(Val2); ValN2++; } else { DstValV.Add(TMWdGixItem(Val1, Val2)); ValN1++; ValN2++; } } for (int RestValN1=ValN1; RestValN1<DstV.Len(); RestValN1++){ DstValV.Add(DstV.GetVal(RestValN1));} for (int RestValN2=ValN2; RestValN2<SrcV.Len(); RestValN2++){ DstValV.Add(SrcV.GetVal(RestValN2));} DstV = DstValV; } void TMWdGixDefMerger::Def(const TInt& Key, TMWdGixItemV& ItemV) const { const int WdDocFq = MWdGix->GetWdFq(Key); const int Docs = MWdGix->GetAllDocs(); const double AvgDocWds = MWdGix->GetAvgDocWds(); const int Items = ItemV.Len(); for (int ItemN = 0; ItemN < Items; ItemN++) { TMWdGixItem& Item = ItemV[ItemN]; const int WdFq = Item.GetWdFq(); const int DocWds = Item.GetDocWds(); const double Wgt = RankFun->WdRank(WdFq, DocWds, WdDocFq, Docs, AvgDocWds); Item.PutWgt(Wgt); } } ///////////////////////////////////////////////// // Multilingual-Word-Inverted-Index TMWdGix::TMWdGix(const TStr& _FPath, const TFAccess& _FAccess, const int64& CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; printf("Loading '%s' .. ", FPath.CStr()); if (FAccess == faCreate) { printf("create .. "); } if (FAccess == faRdOnly) { printf("read-only .. "); } printf("Cache[%s]\n", TUInt64::GetMegaStr(CacheSize).CStr()); // prepare gix MWGix = TMWGix::New(TGixConst::MWdGixFNm, FPath, FAccess, CacheSize); // load word tables if (FAccess != faCreate) { // prepare file name TStr MWdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDatFNm; // load stuff TFIn FIn(MWdGixDatFNm); WordH.Load(FIn); AllDocs.Load(FIn); AllWords.Load(FIn); } } TMWdGix::~TMWdGix() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { printf("Closing %s: docs=%d, words=%d\n", FPath.CStr(), AllDocs.Val, AllWords.Val); // prepare file name TStr MWdGixDatFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDatFNm; // save word tables TFOut FOut(MWdGixDatFNm); WordH.Save(FOut); AllDocs.Save(FOut); AllWords.Save(FOut); } } void TMWdGix::AddHtml(const TStr& DocStr, const TBlobPt& BlobPt) { // create html lexical PSIn HtmlSIn = TStrIn::New(DocStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); // prepare word vector, position counter and flags TIntH DocWIdH; int DocWds = 0; // traverse html string symbols while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // get the word id const int WId = WordH.AddKey(WordStr); // increas the frequency count DocWIdH.AddDat(WId)++; // increase document word count DocWds++; } // get next symbol HtmlLx.GetSym(); } // load add documents to words in inverted index int WdKeyId = DocWIdH.FFirstKeyId(); while (DocWIdH.FNextKeyId(WdKeyId)) { const int WId = DocWIdH.GetKey(WdKeyId); const int WdFq = DocWIdH[WdKeyId]; WordH[WId]++; // count for document frequency TMWdGixKey Key(WId); TMWdGixItem Item(BlobPt, WdFq, DocWds); // add to index MWGix->AddItem(Key, Item); } // increase counters AllDocs++; AllWords += DocWds; } bool TMWdGix::Search(const TStr& QueryStr, TMWdGixItemV& ResItemV, const TMWdGixDefMerger& Merger) { // first we prepare the query just for current language PMWGixExpItem MWGixExp = TMWGixExpItem::NewEmpty(); PSIn HtmlSIn = TStrIn::New(QueryStr); THtmlLx HtmlLx(HtmlSIn); HtmlLx.GetSym(); while (HtmlLx.Sym != hsyEof) { if (HtmlLx.Sym == hsyStr) { // get word token TStr WordStr = HtmlLx.UcChA; // check if we have it const int WId = WordH.GetKeyId(WordStr); if (WId != -1) { PMWGixExpItem MWGixExpItem = TMWGixExpItem::NewItem(TMWdGixKey(WId)); if (MWGixExp->IsEmpty()) { MWGixExp = MWGixExpItem; } else { MWGixExp = TMWGixExpItem::NewOr(MWGixExp, MWGixExpItem); } } } // get next symbol HtmlLx.GetSym(); } // search return MWGixExp->Eval(MWGix, ResItemV, Merger); } ///////////////////////////////////////////////// // MWdGix-Result-Set TStr TMWdGixRSet::GetMainPara(const TStr& QueryStr, const TStr& FullStr) { PBowDocBs BowDocBs = TBowDocBs::New(); BowDocBs->AddHtmlDoc("Query", TStrV(), QueryStr, false); TStrV ParaV; FullStr.SplitOnAllCh('\n', ParaV); if (ParaV.Empty()) { return ""; } for (int ParaN = 0; ParaN < ParaV.Len(); ParaN++) { BowDocBs->AddHtmlDoc("Doc" + TInt::GetStr(ParaN), TStrV(), ParaV[ParaN], false); } PBowDocWgtBs BowDocWgtBs = TBowDocWgtBs::New(BowDocBs, bwwtNrmTFIDF); PBowSpV QuerySpV = BowDocWgtBs->GetSpV(0); int MxParaN = 0; double MxParaSim = TBowSim::GetCosSim(QuerySpV, BowDocWgtBs->GetSpV(1)); for (int ParaN = 1; ParaN < ParaV.Len(); ParaN++) { const double ParaSim = TBowSim::GetCosSim(QuerySpV, BowDocWgtBs->GetSpV(ParaN+1)); if (ParaSim > MxParaSim) { MxParaSim = ParaSim; MxParaN = ParaN; } } return ParaV[MxParaN]; } void TMWdGixRSet::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStr& DocLang, const TStrV& KeyWdV) { DocTitleV.Add(DocTitle); DocTitleV.Last().DelChAll('\n'); DocTitleV.Last().DelChAll('\r'); DocStrV.Add(GetMainPara(LangQueryH.GetDat(DocLang), DocStr)); DocLangV.Add(DocLang); KeyWdVV.Add(KeyWdV); } void TMWdGixRSet::PrintRes(PNotify Notify) { const int Docs = GetDocs(); Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); for (int DocN = 0; DocN < Docs; DocN++) { TStr DocStr = DocTitleV[DocN] + " - " + DocStrV[DocN]; DocStr.DelChAll('\n'); DocStr.DelChAll('\r'); Notify->OnStatus(TStr::Fmt("[%d:%s] %s ...", DocN+1, DocLangV[DocN].CStr(), DocStr.Left(60).CStr())); } Notify->OnStatus(TStr::Fmt("All results: %d, Showing results from %d to %d", AllDocs.Val, Docs, Docs + Offset.Val)); } TStr TMWdGixRSet::GetWsXml(const TStrPrStrH& EurovocH) const { PXmlTok TopTok = TXmlTok::New("cca"); TopTok->AddArg("allhits", GetAllDocs()); for (int DocN = 0; DocN < GetDocs(); DocN++) { PXmlTok HitTok = TXmlTok::New("hit"); HitTok->AddArg("rank", DocN+1); HitTok->AddArg("lang", DocLangV[DocN]); TStr Title = DocTitleV[DocN]; if (Title.Len() > 100) { Title = Title.Left(100) + "..."; } TStr Snipet = DocStrV[DocN].Left(800); if (Snipet.Len() > 800) { Snipet = Snipet.Left(800) + "..."; } HitTok->AddSubTok(TXmlTok::New("title", Title)); HitTok->AddSubTok(TXmlTok::New("snipet", Snipet)); PXmlTok KeyWdTok = TXmlTok::New("keywords"); const TStrV& KeyWdV = KeyWdVV[DocN]; int GoodKeyWds = 0; for (int KeyWdN = 0; KeyWdN < KeyWdV.Len(); KeyWdN++) { TStrPr KeyWd(QueryLang, KeyWdV[KeyWdN]); //printf("'%s' - '%s'\n", KeyWd.Val1.CStr(), KeyWd.Val2.CStr()); if (EurovocH.IsKey(KeyWd)) { KeyWdTok->AddSubTok(TXmlTok::New("keyword", EurovocH.GetDat(KeyWd))); GoodKeyWds++; } } HitTok->AddSubTok(KeyWdTok); if (GoodKeyWds == 0) { continue; } TopTok->AddSubTok(HitTok); } return TopTok->GetTokStr(); } ///////////////////////////////////////////////// // MWdGix-Base TMWdGixBs::TMWdGixBs(const TStr& _FPath, const TFAccess& _FAccess, const int64& _CacheSize) { // store policy FPath = _FPath; FAccess = _FAccess; CacheSize = _CacheSize; // create blob base TStr MWdGixDocBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixDocBsFNm; DocBBs = TMBlobBs::New(MWdGixDocBsFNm, FAccess); // load AlignPairBs if (FAccess != faCreate) { TStr MWdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixBsFNm; AlignPairBs = TAlignPairBs::LoadBin(MWdGixBsFNm); InitGixs(FAccess); } } TMWdGixBs::~TMWdGixBs() { if ((FAccess == faCreate) || (FAccess == faUpdate)) { TStr MWdGixBsFNm = TStr::GetNrFPath(FPath) + TGixConst::MWdGixBsFNm; AlignPairBs->SaveBin(MWdGixBsFNm); } } void TMWdGixBs::AddDoc(const TStr& DocTitle, const TStr& DocStr, const TStr& DocLang, const TStrV& KeyWdV) { // save to blob base TMOut DocMOut; DocTitle.Save(DocMOut); DocStr.Save(DocMOut); DocLang.Save(DocMOut); KeyWdV.Save(DocMOut); TBlobPt DocBlobPt = DocBBs->PutBlob(DocMOut.GetSIn()); // add to index LangMWdGixH.GetDat(DocLang)->AddHtml(DocStr, DocBlobPt); } void TMWdGixBs::GetDoc(const TBlobPt& BlobPt, TStr& DocTitle, TStr& DocStr, TStr& DocLang, TStrV& KeyWdV) const { PSIn SIn = DocBBs->GetBlob(BlobPt); DocTitle.Load(*SIn); DocStr.Load(*SIn); DocLang.Load(*SIn); KeyWdV.Load(*SIn); } PMWdGixRSet TMWdGixBs::SearchDoc(const TStr& QueryStr, const TStr& QueryLang, const TStrV& TargetLangV, const int& Docs, const int& Offset, PMWdGixRankFun& RankFun) { // check if language is good if (!AlignPairBs->IsLang(QueryLang)) { return TMWdGixRSet::New(QueryStr, "", TStrStrH(), 0, 0); } // translate queries to target languages const int Queries = TargetLangV.Len(); printf(" Translationg %d queries ...\n", Queries); const int QueryLangId = AlignPairBs->GetLangId(QueryLang); TStrStrH LangQueryH; TWgtMWdGixIntItemKdV FullWgtLangItemV; for (int TargetLangN = 0; TargetLangN < Queries; TargetLangN++) { if (!AlignPairBs->IsLang(TargetLangV[TargetLangN])) { continue; } // first we translate the query const TStr& TargetLang = TargetLangV[TargetLangN]; const int TargetLangId = AlignPairBs->GetLangId(TargetLang); if (TargetLangId == QueryLangId) { continue; } TStr TargetQueryStr = AlignPairBs->MapQuery( AlignPairMap, QueryStr, QueryLangId, TargetLangId); LangQueryH.AddDat(TargetLang, TargetQueryStr); printf(" Query: '%s' -> '%s'\n", QueryStr.CStr(), TargetQueryStr.CStr()); // then we fire it against the inverted index printf(" Loading from Gix ...\n"); TMWdGixItemV LangResItemV; PMWdGix LangMWdGix = LangMWdGixH.GetDat(TargetLang); TMWdGixDefMerger LangMerger(LangMWdGix, RankFun); LangMWdGix->Search(TargetQueryStr, LangResItemV, LangMerger); // get max weight double MxWgt = 0.0; for (int ItemN = 0; ItemN < LangResItemV.Len(); ItemN++) { const TMWdGixItem& Item = LangResItemV[ItemN]; MxWgt = TFlt::GetMx(Item.GetWgt(), MxWgt); } // reweight so max is 1.0 printf(" MxWgt: %g\n", MxWgt); for (int ItemN = 0; ItemN < LangResItemV.Len(); ItemN++) { const TMWdGixItem& Item = LangResItemV[ItemN]; const double Wgt = MxWgt > 0.0 ? Item.GetWgt() / MxWgt : 0.0; TMWdGixIntItemPr LangItemPr(TargetLangId, Item); FullWgtLangItemV.Add(TWgtMWdGixIntItemKd(Wgt, LangItemPr)); } } // sort the results FullWgtLangItemV.Sort(false); // select the correct portion of documents printf(" Sorting %d hits ...\n", FullWgtLangItemV.Len()); TWgtMWdGixIntItemKdV WgtLangItemV; if (Docs == -1) { // return all resuts WgtLangItemV = FullWgtLangItemV; } else if (FullWgtLangItemV.Len() >= (Docs + Offset)) { // get a subset of results from perticular sub-page WgtLangItemV = FullWgtLangItemV; WgtLangItemV.Sort(false); WgtLangItemV.Trunc(Docs + Offset); WgtLangItemV.Sort(true); WgtLangItemV.Trunc(Docs); } else if (FullWgtLangItemV.Len() > Offset) { // last page ... WgtLangItemV = FullWgtLangItemV; WgtLangItemV.Sort(true); WgtLangItemV.Trunc(FullWgtLangItemV.Len() - Offset); } else { // out of range, leave empty } // sort according to the rank WgtLangItemV.Sort(false); // feed them to the result set printf(" Loading content for %d hits ...\n", WgtLangItemV.Len()); PMWdGixRSet RSet = TMWdGixRSet::New(QueryStr, QueryLang, LangQueryH, FullWgtLangItemV.Len(), Offset); for (int ItemN = 0; ItemN < WgtLangItemV.Len(); ItemN++) { const TMWdGixIntItemPr& LangItem = WgtLangItemV[ItemN].Dat; const TMWdGixItem& Item = LangItem.Val2; TBlobPt DocBlobPt = Item.GetBlobPt(); TStr DocTitle, DocStr, DocLang; TStrV KeyWdV; GetDoc(DocBlobPt, DocTitle, DocStr, DocLang, KeyWdV); RSet->AddDoc(DocTitle, DocStr, DocLang, KeyWdV); } printf(" Done\n"); return RSet; } void TMWdGixBs::AddAcquis(const TStr& XmlFNm, const TStr& Lang) { PXmlDoc XmlDoc = TXmlDoc::LoadTxt(XmlFNm); if (!XmlDoc->IsOk()) { return; } PXmlTok TopTok = XmlDoc->GetTok(); // title & body PXmlTok TextTok = TopTok->GetTagTok("text|body"); if (TextTok.Empty()) { printf(" Bad file '%s'\n", XmlFNm.CStr()); return; } TStr DocTitle; TChA DocChA; for (int SubTokN = 0; SubTokN < TextTok->GetSubToks(); SubTokN++) { PXmlTok SubTok = TextTok->GetSubTok(SubTokN); if (!SubTok->IsTag()) { continue; } if (SubTok->GetTagNm() == "head") { DocTitle = SubTok->GetTokStr(false); } else if (SubTok->GetTagNm() == "div") { // iterate over paragraphs for (int ParaN = 0; ParaN < SubTok->GetSubToks(); ParaN++) { if (SubTok->IsTag()) { DocChA += SubTok->GetSubTok(ParaN)->GetTokStr(false); DocChA += '\n'; } } DocChA += '\n'; } } // keywords TStrV KeyWdV; PXmlTok KeyWdTok = TopTok->GetTagTok("teiHeader|profileDesc|textClass"); if (!KeyWdTok.Empty()) { for (int SubTokN = 0; SubTokN < KeyWdTok->GetSubToks(); SubTokN++) { PXmlTok SubTok = KeyWdTok->GetSubTok(SubTokN); if (!SubTok->IsTag()) { continue; } if (SubTok->IsArg("scheme")) { KeyWdV.Add(SubTok->GetStrArgVal("scheme") + "-" + SubTok->GetTokStr(false)); } } } // index if (!KeyWdV.Empty()) { AddDoc(DocTitle, DocChA, Lang, KeyWdV); } } void TMWdGixBs::IndexAcquis(const TStr& InFPath, PAlignPairBs _AlignPairBs, const int& MxDocs, const int64& IndexCacheSize) { AlignPairBs = _AlignPairBs; // iterate over all the lanugages int LangId = AlignPairBs->FFirstLangId(); while (AlignPairBs->FNextLangId(LangId)) { const TStr& Lang = AlignPairBs->GetLang(LangId); TStr LangFPath = InFPath + "/" + Lang; printf("Indexing %s ...\n", LangFPath.CStr()); // prepare index for this language LangMWdGixH.AddDat(Lang) = TMWdGix::New(FPath + "/" + Lang, FAccess, IndexCacheSize); // iterate over all the files for this language and index them TFFile FFile(LangFPath, ".xml", true); TStr XmlFNm; int XmlFNms = 0; while (FFile.Next(XmlFNm)) { if (XmlFNms == MxDocs) { break; } if (XmlFNms % 100 == 0) { printf(" %d\r", XmlFNms); } try { AddAcquis(XmlFNm, Lang); } catch (...) { } XmlFNms++; } printf("\n"); // clear the index to disk LangMWdGixH.Clr(); } // fin :-) InitGixs(faRdOnly); }
40.617096
131
0.613558
qiuhere
92707a6b7d5cee6fd23069968cc63ef3251a9703
12,829
cc
C++
PhysicsTools/NanoAOD/plugins/IsoValueMapProducer.cc
Michael-Krohn/cmssw
25064b40a13dc451b498e850214fcbe141f7cb75
[ "Apache-2.0" ]
1
2018-03-14T16:25:31.000Z
2018-03-14T16:25:31.000Z
PhysicsTools/NanoAOD/plugins/IsoValueMapProducer.cc
Michael-Krohn/cmssw
25064b40a13dc451b498e850214fcbe141f7cb75
[ "Apache-2.0" ]
null
null
null
PhysicsTools/NanoAOD/plugins/IsoValueMapProducer.cc
Michael-Krohn/cmssw
25064b40a13dc451b498e850214fcbe141f7cb75
[ "Apache-2.0" ]
2
2020-03-20T18:46:13.000Z
2021-03-12T09:23:07.000Z
// -*- C++ -*- // // Package: PhysicsTools/NanoAOD // Class: IsoValueMapProducer // /**\class IsoValueMapProducer IsoValueMapProducer.cc PhysicsTools/NanoAOD/plugins/IsoValueMapProducer.cc Description: [one line class summary] Implementation: [Notes on implementation] */ // // Original Author: Marco Peruzzi // Created: Mon, 04 Sep 2017 22:43:53 GMT // // // system include files #include <memory> // user include files #include "FWCore/Framework/interface/Frameworkfwd.h" #include "FWCore/Framework/interface/global/EDProducer.h" #include "FWCore/Framework/interface/Event.h" #include "FWCore/Framework/interface/MakerMacros.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include "FWCore/Utilities/interface/StreamID.h" #include "CommonTools/Egamma/interface/EffectiveAreas.h" #include "DataFormats/PatCandidates/interface/Muon.h" #include "DataFormats/PatCandidates/interface/Electron.h" #include "DataFormats/PatCandidates/interface/Photon.h" #include "DataFormats/PatCandidates/interface/IsolatedTrack.h" // // class declaration // template <typename T> class IsoValueMapProducer : public edm::global::EDProducer<> { public: explicit IsoValueMapProducer(const edm::ParameterSet& iConfig) : src_(consumes<edm::View<T>>(iConfig.getParameter<edm::InputTag>("src"))), relative_(iConfig.getParameter<bool>("relative")) { if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { produces<edm::ValueMap<float>>("miniIsoChg"); produces<edm::ValueMap<float>>("miniIsoAll"); ea_miniiso_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_MiniIso")).fullPath())); rho_miniiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_MiniIso")); } if ((typeid(T) == typeid(pat::Electron))) { produces<edm::ValueMap<float>>("PFIsoChg"); produces<edm::ValueMap<float>>("PFIsoAll"); produces<edm::ValueMap<float>>("PFIsoAll04"); ea_pfiso_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso")).fullPath())); rho_pfiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_PFIso")); } else if ((typeid(T) == typeid(pat::Photon))) { produces<edm::ValueMap<float>>("PFIsoChg"); produces<edm::ValueMap<float>>("PFIsoAll"); ea_pfiso_chg_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Chg")).fullPath())); ea_pfiso_neu_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Neu")).fullPath())); ea_pfiso_pho_.reset(new EffectiveAreas((iConfig.getParameter<edm::FileInPath>("EAFile_PFIso_Pho")).fullPath())); rho_pfiso_ = consumes<double>(iConfig.getParameter<edm::InputTag>("rho_PFIso")); } } ~IsoValueMapProducer() override {} static void fillDescriptions(edm::ConfigurationDescriptions& descriptions); private: void produce(edm::StreamID, edm::Event&, const edm::EventSetup&) const override; // ----------member data --------------------------- edm::EDGetTokenT<edm::View<T>> src_; bool relative_; edm::EDGetTokenT<double> rho_miniiso_; edm::EDGetTokenT<double> rho_pfiso_; std::unique_ptr<EffectiveAreas> ea_miniiso_; std::unique_ptr<EffectiveAreas> ea_pfiso_; std::unique_ptr<EffectiveAreas> ea_pfiso_chg_; std::unique_ptr<EffectiveAreas> ea_pfiso_neu_; std::unique_ptr<EffectiveAreas> ea_pfiso_pho_; float getEtaForEA(const T*) const; void doMiniIso(edm::Event&) const; void doPFIsoEle(edm::Event&) const; void doPFIsoPho(edm::Event&) const; }; // // constants, enums and typedefs // // // static data member definitions // template <typename T> float IsoValueMapProducer<T>::getEtaForEA(const T* obj) const { return obj->eta(); } template <> float IsoValueMapProducer<pat::Electron>::getEtaForEA(const pat::Electron* el) const { return el->superCluster()->eta(); } template <> float IsoValueMapProducer<pat::Photon>::getEtaForEA(const pat::Photon* ph) const { return ph->superCluster()->eta(); } template <typename T> void IsoValueMapProducer<T>::produce(edm::StreamID streamID, edm::Event& iEvent, const edm::EventSetup& iSetup) const { if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { doMiniIso(iEvent); }; if ((typeid(T) == typeid(pat::Electron))) { doPFIsoEle(iEvent); } if ((typeid(T) == typeid(pat::Photon))) { doPFIsoPho(iEvent); } } template <typename T> void IsoValueMapProducer<T>::doMiniIso(edm::Event& iEvent) const { edm::Handle<edm::View<T>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_miniiso_, rho); unsigned int nInput = src->size(); std::vector<float> miniIsoChg, miniIsoAll; miniIsoChg.reserve(nInput); miniIsoAll.reserve(nInput); for (const auto& obj : *src) { auto iso = obj.miniPFIsolation(); auto chg = iso.chargedHadronIso(); auto neu = iso.neutralHadronIso(); auto pho = iso.photonIso(); auto ea = ea_miniiso_->getEffectiveArea(fabs(getEtaForEA(&obj))); float R = 10.0 / std::min(std::max(obj.pt(), 50.0), 200.0); ea *= std::pow(R / 0.3, 2); float scale = relative_ ? 1.0 / obj.pt() : 1; miniIsoChg.push_back(scale * chg); miniIsoAll.push_back(scale * (chg + std::max(0.0, neu + pho - (*rho) * ea))); } std::unique_ptr<edm::ValueMap<float>> miniIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*miniIsoChgV); fillerChg.insert(src, miniIsoChg.begin(), miniIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> miniIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*miniIsoAllV); fillerAll.insert(src, miniIsoAll.begin(), miniIsoAll.end()); fillerAll.fill(); iEvent.put(std::move(miniIsoChgV), "miniIsoChg"); iEvent.put(std::move(miniIsoAllV), "miniIsoAll"); } template <> void IsoValueMapProducer<pat::Photon>::doMiniIso(edm::Event& iEvent) const {} template <typename T> void IsoValueMapProducer<T>::doPFIsoEle(edm::Event& iEvent) const {} template <> void IsoValueMapProducer<pat::Electron>::doPFIsoEle(edm::Event& iEvent) const { edm::Handle<edm::View<pat::Electron>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_pfiso_, rho); unsigned int nInput = src->size(); std::vector<float> PFIsoChg, PFIsoAll, PFIsoAll04; PFIsoChg.reserve(nInput); PFIsoAll.reserve(nInput); PFIsoAll04.reserve(nInput); for (const auto& obj : *src) { auto iso = obj.pfIsolationVariables(); auto chg = iso.sumChargedHadronPt; auto neu = iso.sumNeutralHadronEt; auto pho = iso.sumPhotonEt; auto ea = ea_pfiso_->getEffectiveArea(fabs(getEtaForEA(&obj))); float scale = relative_ ? 1.0 / obj.pt() : 1; PFIsoChg.push_back(scale * chg); PFIsoAll.push_back(scale * (chg + std::max(0.0, neu + pho - (*rho) * ea))); PFIsoAll04.push_back(scale * (obj.chargedHadronIso() + std::max(0.0, obj.neutralHadronIso() + obj.photonIso() - (*rho) * ea * 16. / 9.))); } std::unique_ptr<edm::ValueMap<float>> PFIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*PFIsoChgV); fillerChg.insert(src, PFIsoChg.begin(), PFIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*PFIsoAllV); fillerAll.insert(src, PFIsoAll.begin(), PFIsoAll.end()); fillerAll.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAll04V(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll04(*PFIsoAll04V); fillerAll04.insert(src, PFIsoAll04.begin(), PFIsoAll04.end()); fillerAll04.fill(); iEvent.put(std::move(PFIsoChgV), "PFIsoChg"); iEvent.put(std::move(PFIsoAllV), "PFIsoAll"); iEvent.put(std::move(PFIsoAll04V), "PFIsoAll04"); } template <typename T> void IsoValueMapProducer<T>::doPFIsoPho(edm::Event& iEvent) const {} template <> void IsoValueMapProducer<pat::Photon>::doPFIsoPho(edm::Event& iEvent) const { edm::Handle<edm::View<pat::Photon>> src; iEvent.getByToken(src_, src); edm::Handle<double> rho; iEvent.getByToken(rho_pfiso_, rho); unsigned int nInput = src->size(); std::vector<float> PFIsoChg, PFIsoAll; PFIsoChg.reserve(nInput); PFIsoAll.reserve(nInput); for (const auto& obj : *src) { auto chg = obj.chargedHadronIso(); auto neu = obj.neutralHadronIso(); auto pho = obj.photonIso(); auto ea_chg = ea_pfiso_chg_->getEffectiveArea(fabs(getEtaForEA(&obj))); auto ea_neu = ea_pfiso_neu_->getEffectiveArea(fabs(getEtaForEA(&obj))); auto ea_pho = ea_pfiso_pho_->getEffectiveArea(fabs(getEtaForEA(&obj))); float scale = relative_ ? 1.0 / obj.pt() : 1; PFIsoChg.push_back(scale * std::max(0.0, chg - (*rho) * ea_chg)); PFIsoAll.push_back(PFIsoChg.back() + scale * (std::max(0.0, neu - (*rho) * ea_neu) + std::max(0.0, pho - (*rho) * ea_pho))); } std::unique_ptr<edm::ValueMap<float>> PFIsoChgV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerChg(*PFIsoChgV); fillerChg.insert(src, PFIsoChg.begin(), PFIsoChg.end()); fillerChg.fill(); std::unique_ptr<edm::ValueMap<float>> PFIsoAllV(new edm::ValueMap<float>()); edm::ValueMap<float>::Filler fillerAll(*PFIsoAllV); fillerAll.insert(src, PFIsoAll.begin(), PFIsoAll.end()); fillerAll.fill(); iEvent.put(std::move(PFIsoChgV), "PFIsoChg"); iEvent.put(std::move(PFIsoAllV), "PFIsoAll"); } // ------------ method fills 'descriptions' with the allowed parameters for the module ------------ template <typename T> void IsoValueMapProducer<T>::fillDescriptions(edm::ConfigurationDescriptions& descriptions) { edm::ParameterSetDescription desc; desc.add<edm::InputTag>("src")->setComment("input physics object collection"); desc.add<bool>("relative")->setComment("compute relative isolation instead of absolute one"); if ((typeid(T) == typeid(pat::Muon)) || (typeid(T) == typeid(pat::Electron)) || typeid(T) == typeid(pat::IsolatedTrack)) { desc.add<edm::FileInPath>("EAFile_MiniIso") ->setComment("txt file containing effective areas to be used for mini-isolation pileup subtraction"); desc.add<edm::InputTag>("rho_MiniIso") ->setComment("rho to be used for effective-area based mini-isolation pileup subtraction"); } if ((typeid(T) == typeid(pat::Electron))) { desc.add<edm::FileInPath>("EAFile_PFIso") ->setComment( "txt file containing effective areas to be used for PF-isolation pileup subtraction for electrons"); desc.add<edm::InputTag>("rho_PFIso") ->setComment("rho to be used for effective-area based PF-isolation pileup subtraction for electrons"); } if ((typeid(T) == typeid(pat::Photon))) { desc.add<edm::InputTag>("mapIsoChg")->setComment("input charged PF isolation calculated in VID for photons"); desc.add<edm::InputTag>("mapIsoNeu")->setComment("input neutral PF isolation calculated in VID for photons"); desc.add<edm::InputTag>("mapIsoPho")->setComment("input photon PF isolation calculated in VID for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Chg") ->setComment( "txt file containing effective areas to be used for charged PF-isolation pileup subtraction for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Neu") ->setComment( "txt file containing effective areas to be used for neutral PF-isolation pileup subtraction for photons"); desc.add<edm::FileInPath>("EAFile_PFIso_Pho") ->setComment( "txt file containing effective areas to be used for photon PF-isolation pileup subtraction for photons"); desc.add<edm::InputTag>("rho_PFIso") ->setComment("rho to be used for effective-area based PF-isolation pileup subtraction for photons"); } std::string modname; if (typeid(T) == typeid(pat::Muon)) modname += "Muon"; else if (typeid(T) == typeid(pat::Electron)) modname += "Ele"; else if (typeid(T) == typeid(pat::Photon)) modname += "Pho"; else if (typeid(T) == typeid(pat::IsolatedTrack)) modname += "IsoTrack"; modname += "IsoValueMapProducer"; descriptions.add(modname, desc); } typedef IsoValueMapProducer<pat::Muon> MuonIsoValueMapProducer; typedef IsoValueMapProducer<pat::Electron> EleIsoValueMapProducer; typedef IsoValueMapProducer<pat::Photon> PhoIsoValueMapProducer; typedef IsoValueMapProducer<pat::IsolatedTrack> IsoTrackIsoValueMapProducer; //define this as a plug-in DEFINE_FWK_MODULE(MuonIsoValueMapProducer); DEFINE_FWK_MODULE(EleIsoValueMapProducer); DEFINE_FWK_MODULE(PhoIsoValueMapProducer); DEFINE_FWK_MODULE(IsoTrackIsoValueMapProducer);
39.965732
119
0.699353
Michael-Krohn
92709647dac00dbcd443e80ee4ecf9a2a5e46208
6,127
cc
C++
paddle/pten/core/convert_utils.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
2
2022-01-04T10:51:58.000Z
2022-01-10T12:29:08.000Z
paddle/pten/core/convert_utils.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
null
null
null
paddle/pten/core/convert_utils.cc
zhenlin-work/Paddle
ed7a21dea0ddcffb6f7f33ce21c5c368f5c7866b
[ "Apache-2.0" ]
1
2020-11-25T10:41:52.000Z
2020-11-25T10:41:52.000Z
/* Copyright (c) 2021 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 "paddle/pten/core/convert_utils.h" // See Note [ Why still include the fluid headers? ] #include "paddle/fluid/platform/gpu_info.h" namespace pten { // TODO(chenweihang): Add other place trans cases later Backend TransToPtenBackend(const paddle::platform::Place& place) { if (paddle::platform::is_cpu_place(place)) { return Backend::CPU; } else if (paddle::platform::is_gpu_place(place)) { return Backend::CUDA; } else { return Backend::UNDEFINED; } } paddle::experimental::DataType TransToPtenDataType( const paddle::framework::proto::VarType::Type& dtype) { // Set the order of case branches according to the frequency with // the data type is used switch (dtype) { case paddle::framework::proto::VarType::FP32: return DataType::FLOAT32; case paddle::framework::proto::VarType::FP64: return DataType::FLOAT64; case paddle::framework::proto::VarType::INT64: return DataType::INT64; case paddle::framework::proto::VarType::INT32: return DataType::INT32; case paddle::framework::proto::VarType::INT8: return DataType::INT8; case paddle::framework::proto::VarType::UINT8: return DataType::UINT8; case paddle::framework::proto::VarType::INT16: return DataType::INT16; case paddle::framework::proto::VarType::COMPLEX64: return DataType::COMPLEX64; case paddle::framework::proto::VarType::COMPLEX128: return DataType::COMPLEX128; case paddle::framework::proto::VarType::FP16: return DataType::FLOAT16; case paddle::framework::proto::VarType::BF16: return DataType::BFLOAT16; case paddle::framework::proto::VarType::BOOL: return DataType::BOOL; default: return DataType::UNDEFINED; } } DataLayout TransToPtenDataLayout(const paddle::framework::DataLayout& layout) { switch (layout) { case paddle::framework::DataLayout::kNHWC: return DataLayout::NHWC; case paddle::framework::DataLayout::kNCHW: return DataLayout::NCHW; case paddle::framework::DataLayout::kAnyLayout: return DataLayout::ANY; case paddle::framework::DataLayout::kMKLDNN: return DataLayout::MKLDNN; default: return DataLayout::UNDEFINED; } } paddle::platform::Place TransToFluidPlace(const Backend& backend) { // TODO(chenweihang): add other trans cases later switch (backend) { case pten::Backend::CPU: return paddle::platform::CPUPlace(); #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) case pten::Backend::CUDA: return paddle::platform::CUDAPlace( paddle::platform::GetCurrentDeviceId()); #endif #ifdef PADDLE_WITH_MKLDNN case pten::Backend::MKLDNN: return paddle::platform::CPUPlace(); #endif #if defined(PADDLE_WITH_CUDA) || defined(PADDLE_WITH_HIP) case pten::Backend::CUDNN: return paddle::platform::CUDAPlace( paddle::platform::GetCurrentDeviceId()); #endif default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported backend `%s` when casting it to paddle place type.", backend)); } } paddle::framework::proto::VarType::Type TransToProtoVarType( const paddle::experimental::DataType& dtype) { // Set the order of case branches according to the frequency with // the data type is used switch (dtype) { case DataType::FLOAT32: return paddle::framework::proto::VarType::FP32; case DataType::FLOAT64: return paddle::framework::proto::VarType::FP64; case DataType::INT64: return paddle::framework::proto::VarType::INT64; case DataType::INT32: return paddle::framework::proto::VarType::INT32; case DataType::INT8: return paddle::framework::proto::VarType::INT8; case DataType::UINT8: return paddle::framework::proto::VarType::UINT8; case DataType::INT16: return paddle::framework::proto::VarType::INT16; case DataType::COMPLEX64: return paddle::framework::proto::VarType::COMPLEX64; case DataType::COMPLEX128: return paddle::framework::proto::VarType::COMPLEX128; case DataType::FLOAT16: return paddle::framework::proto::VarType::FP16; case DataType::BFLOAT16: return paddle::framework::proto::VarType::BF16; case DataType::BOOL: return paddle::framework::proto::VarType::BOOL; default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported data type `%s` when casting it into " "paddle data type.", dtype)); } } paddle::framework::DataLayout TransToFluidDataLayout(const DataLayout& layout) { switch (layout) { case DataLayout::NHWC: return paddle::framework::DataLayout::kNHWC; case DataLayout::NCHW: return paddle::framework::DataLayout::kNCHW; case DataLayout::ANY: return paddle::framework::DataLayout::kAnyLayout; case DataLayout::MKLDNN: return paddle::framework::DataLayout::kMKLDNN; default: PADDLE_THROW(paddle::platform::errors::Unimplemented( "Unsupported data layout `%s` when casting it into " "paddle data layout.", layout)); } } paddle::framework::LoD TransToFluidLoD(const pten::LoD& lod) { paddle::framework::LoD out; out.reserve(lod.size()); for (auto& elem : lod) { out.emplace_back(elem); } return out; } pten::LoD TransToPtenLoD(const paddle::framework::LoD& lod) { pten::LoD out; out.reserve(lod.size()); for (auto& elem : lod) { out.emplace_back(elem); } return out; } } // namespace pten
33.298913
80
0.693814
zhenlin-work
9271323e52f133fcecca87a1821b7f8ddec1a8b2
358
cpp
C++
test/unit/src/alloy/source/model.cpp
brunocodutra/alloy
e05e30a40b1b04c09819b8b968829ba4f62dc221
[ "MIT" ]
16
2017-06-15T18:37:05.000Z
2022-02-20T09:17:38.000Z
test/unit/src/alloy/source/model.cpp
brunocodutra/alloy
e05e30a40b1b04c09819b8b968829ba4f62dc221
[ "MIT" ]
3
2017-06-15T18:26:02.000Z
2017-07-29T15:29:16.000Z
test/unit/src/alloy/source/model.cpp
brunocodutra/alloy
e05e30a40b1b04c09819b8b968829ba4f62dc221
[ "MIT" ]
1
2018-06-05T20:39:14.000Z
2018-06-05T20:39:14.000Z
#include <alloy.hpp> #include "test.hpp" template<auto X, auto Y, auto Z> struct matrix { constexpr matrix() { auto f = [](auto&& sink) { return values<X, Y, Z>()(FWD(sink)); }; static_assert(qualify<X>(alloy::source{callable<X>(f)}) >> expect(values<X, Y, Z>())); } }; int main() { return test<matrix>; }
18.842105
94
0.541899
brunocodutra
92744e2ec5f824ed15a53b13adbfd9f970556322
740
cpp
C++
snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
2
2020-03-12T19:26:36.000Z
2022-01-10T21:45:33.000Z
snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
555
2019-09-23T22:22:58.000Z
2021-07-15T18:51:12.000Z
snippets/cpp/VS_Snippets_CLR/Interop CallingConvention/CPP/callingconv.cpp
BohdanMosiyuk/samples
59d435ba9e61e0fc19f5176c96b1cdbd53596142
[ "CC-BY-4.0", "MIT" ]
3
2020-01-29T16:31:15.000Z
2021-08-24T07:00:15.000Z
// <Snippet1> using namespace System; using namespace System::Runtime::InteropServices; public ref class LibWrap { public: // CallingConvention.Cdecl must be used since the stack is // cleaned up by the caller. // int printf( const char *format [, argument]... ) [DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)] static int printf( String^ format, int i, double d ); [DllImport("msvcrt.dll",CharSet=CharSet::Unicode, CallingConvention=CallingConvention::Cdecl)] static int printf( String^ format, int i, String^ s ); }; int main() { LibWrap::printf( "\nPrint params: %i %f", 99, 99.99 ); LibWrap::printf( "\nPrint params: %i %s", 99, "abcd" ); } // </Snippet1>
27.407407
97
0.687838
BohdanMosiyuk
92751b7feb47284fdb5c09836d601fd2b0034d6c
2,256
hpp
C++
external/mapnik/include/mapnik/boolean.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/boolean.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
external/mapnik/include/mapnik/boolean.hpp
baiyicanggou/mapnik_mvt
9bde52fa9958d81361c015c816858534ec0931bb
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2015 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef MAPNIK_BOOLEAN_HPP #define MAPNIK_BOOLEAN_HPP // mapnik #include <mapnik/config.hpp> #include <mapnik/util/conversions.hpp> // std #include <iosfwd> #include <string> namespace mapnik { class MAPNIK_DECL boolean_type { public: boolean_type() : b_(false) {} boolean_type(bool b) : b_(b) {} boolean_type(boolean_type const& b) : b_(b.b_) {} operator bool() const { return b_; } boolean_type & operator =(boolean_type const& other) { if (this == &other) return *this; b_ = other.b_; return *this; } private: bool b_; }; // Special stream input operator for boolean_type values template <typename charT, typename traits> std::basic_istream<charT, traits> & operator >> ( std::basic_istream<charT, traits> & s, boolean_type & b ) { if ( s ) { std::string word; s >> word; bool result; if (util::string2bool(word,result)) b = result; } return s; } template <typename charT, typename traits> std::basic_ostream<charT, traits> & operator << ( std::basic_ostream<charT, traits> & s, boolean_type const& b ) { s << ( b ? "true" : "false" ); return s; } } #endif // MAPNIK_BOOLEAN_HPP
25.348315
79
0.615248
baiyicanggou
927874510225c5fb5aa53d0a5b089bc99afc57bd
326
cpp
C++
alex/chapter4/4.3_functional_addition.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
alex/chapter4/4.3_functional_addition.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
alex/chapter4/4.3_functional_addition.cpp
Alexhhhc/gay-school-cpp-homework
fa864ce1632367ef0fa269c25030e60d3a0aafac
[ "BSD-3-Clause" ]
null
null
null
#include<iostream> using namespace std; int main(){ float add(float x,float y);//声明add函数 float a,b,c; cout<<"Please enter a&b:";//输出语句 cin>>a>>b; //输入语句 c=add(a,b); //调用add函数 cout<<"sum="<<c<<endl; //输出语句 return 0; } float add(float x,float y){ //定义add函数 float z; z=x+y; return(z); }
20.375
40
0.56135
Alexhhhc
927b69374ca11b474ccc4a9e048fa783236a3b5d
1,215
cpp
C++
pr2_coffee/elevator/elevator_door_status/elevator_door_status.cpp
atp42/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
3
2017-02-02T13:27:45.000Z
2018-06-17T11:52:13.000Z
pr2_coffee/elevator/elevator_door_status/elevator_door_status.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
pr2_coffee/elevator/elevator_door_status/elevator_door_status.cpp
salisbury-robotics/jks-ros-pkg
367fc00f2a9699f33d05c7957d319a80337f1ed4
[ "FTL" ]
null
null
null
#include <cmath> #include <cstdio> #include "elevator_door_status.h" using std::vector; ElevatorDoorStatus::ElevatorDoorStatus() { } ElevatorDoorStatus::~ElevatorDoorStatus() { } void ElevatorDoorStatus::set_reference(vector<float> scan) { ref = scan; } ElevatorDoorStatus::DoorState ElevatorDoorStatus::detect(vector<float> scan) { static int scan_count = 0; scan_count++; if (!ref.size() || ref.size() != scan.size()) return INVALID_DATA; vector<float> diff = ref; // find sum of differences on the right and left sides of the scan float left_sum = 0, left_idx_sum = 0; float right_sum = 0, right_idx_sum = 0; for (size_t i = 0; i < scan.size(); i++) { diff[i] -= scan[i]; if (diff[i] > 0) continue; // we're only looking for holes, not filled space if (i < scan.size() / 2) { left_sum += diff[i]; left_idx_sum++; } else { right_sum += diff[i]; right_idx_sum++; } } //if (left_sum < -3 || right_sum < -3) // depends on how far away you are // printf("%.05f %.05f\n", left_sum, right_sum); if (left_sum < -3) return LEFT_OPEN; else if (right_sum < -3) return RIGHT_OPEN; else return ALL_CLOSED; }
22.090909
76
0.62963
atp42
927c3a493597d78d90019a891bee8151b2c5bf2f
7,821
cpp
C++
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/main.cpp
artiste-qb-net/qubiter
af0340584d0b47d6b18d3dd28cd9b55a08cb507c
[ "Apache-2.0" ]
129
2016-03-22T17:50:16.000Z
2022-01-26T14:53:03.000Z
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/main.cpp
yourball/qubiter
5ef0ea064fa8c9f125f7951a01fbb88504a054a5
[ "Apache-2.0" ]
40
2016-03-22T19:38:27.000Z
2019-07-02T19:40:27.000Z
qubiter/quantum_CSD_compiler/LEGACY/qubiter1.11-C++source/main.cpp
artiste-qb-net/qubiter
af0340584d0b47d6b18d3dd28cd9b55a08cb507c
[ "Apache-2.0" ]
36
2016-03-28T07:48:54.000Z
2022-01-26T14:49:28.000Z
#include "UNITARY_MAT.h" #include "TREE.h" #include "STRINGY.h" #include "OPTIMIZATIONS.h" #include "PERMUTATION.h" #include "CENTRAL_MAT.h" #include "W_SPEC.h" //This global is a string that denotes the //matrix being decomposed. The global will //be used as a prefix in file names. STRINGY g_mat_name; VOID pmut_opt1_grow_one_tree( UNITARY_MAT * u_p, W_SPEC & w_spec, BOOLEAN keep_identity_pmut, const PERMUTATION & desired_pmut); VOID pmut_opt1_grow_many_trees( UNITARY_MAT * u_p, W_SPEC & w_spec, BOOLEAN keep_identity_pmut, const PERMUTATION & desired_pmut); //****************************************** //VOID main(VOID) int main(VOID) { SetDebugThrow_(debugAction_Alert); SetDebugSignal_(debugAction_Alert); //params = parameters //comp = components //engl = english //pict = picture //i(o)strm = in(out) stream //opt = optimization //pmut = permutation IFSTREAM param_strm; USHORT do_compilation, do_decompilation; USHORT do_light_right_opt; USHORT do_complex_d_mat_opt; USHORT pmut_opt_level; USHORT do_all_bit_pmuts, keep_identity_pmut; PERMUTATION desired_pmut; USHORT pmut_len, i; param_strm.open("qbtr-params.in"); if(!param_strm.is_open()) { cerr<<"'qbtr-params.in' file is missing."; exit(-1); } param_strm.exceptions(ios::badbit | ios::failbit); try{ param_strm.ignore(500, k_endline); param_strm>>g_mat_name; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_compilation; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_decompilation; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_light_right_opt; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>do_complex_d_mat_opt; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); param_strm>>pmut_opt_level; param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); if(pmut_opt_level==1){ param_strm>>do_all_bit_pmuts; param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); } param_strm.ignore(500, k_endline); if(pmut_opt_level==1){ param_strm>>keep_identity_pmut; param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); } param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); if(pmut_opt_level==1 && !keep_identity_pmut){ param_strm>>pmut_len; desired_pmut.resize(0, pmut_len); for(i=0; i<pmut_len; i++){ param_strm>>desired_pmut[i]; } param_strm.ignore(500, k_endline); }else{ param_strm.ignore(500, k_endline); param_strm.ignore(500, k_endline); } } catch(const ios::failure & io_exc){ cerr<<"'qbtr-params.in' file is illegal."; exit(-1); } param_strm.close(); OPTIMIZATIONS::its_lighten_right_mats = do_light_right_opt; OPTIMIZATIONS::its_extract_d_mat_phases = do_complex_d_mat_opt; OPTIMIZATIONS::its_pmut_opt_level = pmut_opt_level; //pmut_opt_level>1 not yet implemented ThrowIf_(pmut_opt_level>1); if(do_compilation){ IFSTREAM comp_strm; comp_strm.open((g_mat_name && ".in").get_string()); if( !comp_strm.is_open() ) { cerr<<"'mat_name.in' file is missing."; exit(-1); } UNITARY_MAT * u_p = new UNITARY_MAT(); //u_p is destroyed by TREE()->NODE() //if choose destroy option in TREE(). u_p->read_components_file(&comp_strm); comp_strm.close(); if(u_p->get_num_of_bits()==0){ OPTIMIZATIONS::its_pmut_opt_level = pmut_opt_level = 0; } if(pmut_opt_level==1){ if(!keep_identity_pmut){ ThrowIf_(u_p->get_num_of_bits()!=pmut_len); }else{ pmut_len = u_p->get_num_of_bits(); desired_pmut.set_to_identity(pmut_len); } } OFSTREAM engl_strm; OFSTREAM pict_strm; W_SPEC w_spec; engl_strm.open((g_mat_name && "-engl.out").get_string()); pict_strm.open((g_mat_name && "-pict.out").get_string()); engl_strm<<fixed<<showpoint<<setprecision(9); w_spec.its_engl_strm_p = &engl_strm; w_spec.its_pict_strm_p = &pict_strm; if(pmut_opt_level!=1){ TREE tree(u_p, true);//destroys u_p w_spec.its_pmut_p = 0; tree.write(w_spec); }else{//pmut_opt_level==1 if(!do_all_bit_pmuts){ //destroys u_p pmut_opt1_grow_one_tree(u_p, w_spec, keep_identity_pmut, desired_pmut); }else{//do all bit permutations //destroys u_p pmut_opt1_grow_many_trees(u_p, w_spec, keep_identity_pmut, desired_pmut); } }//pmut_opt_level engl_strm.close(); pict_strm.close(); }//do compilation if(do_decompilation){ UNITARY_MAT v; IFSTREAM engl_strm; engl_strm.open((g_mat_name && "-engl.out").get_string()); if(!engl_strm.is_open()) { cerr<<"'mat_name-engl.out' file is missing."; exit(-1); } v.read_english_file(&engl_strm); engl_strm.close(); OFSTREAM comp_strm; comp_strm.open((g_mat_name && "-chk.out").get_string());//chk = check comp_strm<<fixed<<showpoint; v.write_components_file(&comp_strm); comp_strm.close(); if(do_compilation){ IFSTREAM decr_strm;//decr = decrement decr_strm.open((g_mat_name && ".in").get_string()); if( !decr_strm.is_open() ) { cerr<<"'mat_name.in' file is missing."; exit(-1); } v.read_decrements_file(&decr_strm); decr_strm.close(); OFSTREAM err_strm;//err = error err_strm.open((g_mat_name && "-err.out").get_string()); err_strm<<fixed<<showpoint; v.write_components_file(&err_strm); err_strm.close(); } } } //****************************************** VOID pmut_opt1_grow_one_tree( UNITARY_MAT * u_p, //io W_SPEC & w_spec, //io BOOLEAN keep_identity_pmut, //in const PERMUTATION & desired_pmut) //in { if(!keep_identity_pmut){ u_p->permute_bits(desired_pmut); } TREE tree(u_p, true); PERMUTATION inv_pmut(desired_pmut.get_len()); if(!keep_identity_pmut){ desired_pmut.get_inverse(inv_pmut); w_spec.its_pmut_p = &inv_pmut; }else{ w_spec.its_pmut_p = 0; } tree.write(w_spec); } //****************************************** VOID pmut_opt1_grow_many_trees( UNITARY_MAT * u_p, //io W_SPEC & w_spec, //io BOOLEAN keep_identity_pmut, //in const PERMUTATION & desired_pmut) //in { //save the ostream pointers OFSTREAM * engl_strm_p = w_spec.its_engl_strm_p; OFSTREAM * pict_strm_p = w_spec.its_pict_strm_p; OFSTREAM pmut_strm;//permutation log pmut_strm.open((g_mat_name && "-pmut.out").get_string()); TRANSPOSITION transp;//identity by default USHORT p_counter=1; BOOLEAN more_pmuts; USHORT pmut_len = desired_pmut.get_len(); PERMUTATION pmut(pmut_len); PERMUTATION inv_pmut(pmut_len); pmut.prepare_for_lazy_advance(); do{ more_pmuts = pmut.lazy_advance(transp); u_p->transpose_bits(transp); TREE tree(u_p, false);//destroy u_p at the end of this method //In write: //If engl_strm_p = 0, then no actual //writing is done in english file. //Same for pict_strm_p. //If pmut_p = 0, no permutation is done when writing english file. if(pmut!=desired_pmut){ w_spec.its_engl_strm_p = 0; w_spec.its_pict_strm_p = 0; w_spec.its_pmut_p = 0; }else{ w_spec.its_engl_strm_p = engl_strm_p; w_spec.its_pict_strm_p = pict_strm_p; if(!keep_identity_pmut){ desired_pmut.get_inverse(inv_pmut); w_spec.its_pmut_p = &inv_pmut; }else{ w_spec.its_pmut_p = 0; } } CENTRAL_MAT::set_cum_num_of_elem_ops(0); tree.write(w_spec); pmut_strm<< '(' << p_counter << ')'; for(USHORT i=0; i<pmut_len; i++){ pmut_strm<<'\t'<<pmut[i]; } pmut_strm<< k_endline <<'\t'<<"number of steps = "; pmut_strm<<CENTRAL_MAT::get_cum_num_of_elem_ops()<<k_endline; p_counter++; }while(more_pmuts); delete u_p; pmut_strm.close(); }
28.133094
77
0.68738
artiste-qb-net
927e4f75c55a804c83b0033ede86cba10772b177
1,403
cc
C++
source/Detectors/MeshModels.cc
vetlewi/AFRODITE
4aa42184c0f94613e7e2b219bc8aca371094143e
[ "MIT" ]
null
null
null
source/Detectors/MeshModels.cc
vetlewi/AFRODITE
4aa42184c0f94613e7e2b219bc8aca371094143e
[ "MIT" ]
1
2021-05-04T10:52:08.000Z
2021-05-04T10:52:08.000Z
source/Detectors/MeshModels.cc
vetlewi/AFRODITE
4aa42184c0f94613e7e2b219bc8aca371094143e
[ "MIT" ]
null
null
null
// // Created by Vetle Wegner Ingeberg on 30/04/2021. // #include "meshreader/incbin.h" #ifndef SRC_PATH #define SRC_PATH "../" #endif // SRC_PATH #ifndef PLY_PATH #define PLY_PATH SRC_PATH"Mesh-Models" #endif // PLY_PATH #ifndef DETECTOR_PATH #define DETECTOR_PATH PLY_PATH"/DETECTORS" #endif // DETECTOR_PATH #ifndef CLOVER_PATH #define CLOVER_PATH DETECTOR_PATH"/CLOVER" #endif // CLOVER_PATH // Including all the CLOVER HPGe mesh models INCBIN(CLOVER_VACCUM, CLOVER_PATH"/CLOVER-InternalVacuum/CloverInternalVacuum_approx.ply"); INCBIN(CLOVER_ENCASEMENT, CLOVER_PATH"/CloverEncasement/CloverEncasement_new_approx.ply"); INCBIN(HPGeCrystalA, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal1_10umTolerance.ply"); INCBIN(HPGeCrystalB, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal2_10umTolerance.ply"); INCBIN(HPGeCrystalC, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal3_10umTolerance.ply"); INCBIN(HPGeCrystalD, CLOVER_PATH"/HPGeCrystals/HPGe-RoundedCrystal4_10umTolerance.ply"); INCBIN(HPGeContactA, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact1_10um.ply"); INCBIN(HPGeContactB, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact2_10um.ply"); INCBIN(HPGeContactC, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact3_10um.ply"); INCBIN(HPGeContactD, CLOVER_PATH"/HPGeCrystals/HPGe_pureCylindricalBorehole_LithiumContact4_10um.ply");
40.085714
103
0.840342
vetlewi
927e8a6f4a1a295f15b212626ccc771a4f6f0576
1,913
cpp
C++
cpp/graphs/shortestpaths/dijkstra.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
1,727
2015-01-01T18:32:37.000Z
2022-03-28T05:56:03.000Z
cpp/graphs/shortestpaths/dijkstra.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
110
2015-05-03T10:23:18.000Z
2021-07-31T22:44:39.000Z
cpp/graphs/shortestpaths/dijkstra.cpp
ayushbhatt2000/codelibrary
e1209b5e6195717d20127e12e908839c595c2f4c
[ "Unlicense" ]
570
2015-01-01T10:17:11.000Z
2022-03-31T22:23:46.000Z
#include <bits/stdc++.h> using namespace std; typedef pair<int, int> edge; typedef pair<int, int> item; // https://cp-algorithms.com/graph/dijkstra_sparse.html // O(E*log(V)) time and O(E) memory tuple<vector<int>, vector<int>> dijkstra_heap(const vector<vector<edge>> &g, int s) { size_t n = g.size(); vector<int> prio(n, numeric_limits<int>::max()); vector<int> pred(n, -1); priority_queue<item, vector<item>, greater<>> q; q.emplace(prio[s] = 0, s); while (!q.empty()) { auto [d, u] = q.top(); q.pop(); if (d != prio[u]) continue; for (auto [v, len] : g[u]) { int nprio = prio[u] + len; if (prio[v] > nprio) { prio[v] = nprio; pred[v] = u; q.emplace(nprio, v); } } } return {prio, pred}; } // O(E*log(V)) time and O(V) memory tuple<vector<int>, vector<int>> dijkstra_set(const vector<vector<edge>> &g, int s) { size_t n = g.size(); vector<int> prio(n, numeric_limits<int>::max()); vector<int> pred(n, -1); set<item> q; q.emplace(prio[s] = 0, s); while (!q.empty()) { int u = q.begin()->second; q.erase(q.begin()); for (auto [v, len] : g[u]) { int nprio = prio[u] + len; if (prio[v] > nprio) { q.erase({prio[v], v}); prio[v] = nprio; pred[v] = u; q.emplace(prio[v], v); } } } return {prio, pred}; } int main() { vector<vector<edge>> g(3); g[0].emplace_back(1, 10); g[1].emplace_back(2, -5); g[0].emplace_back(2, 8); auto [prio1, pred1] = dijkstra_heap(g, 0); auto [prio2, pred2] = dijkstra_set(g, 0); for (int x : prio1) cout << x << " "; cout << endl; for (int x : prio2) cout << x << " "; cout << endl; }
23.617284
85
0.482488
ayushbhatt2000
927ee64432a2995e81dd219e9c153f16bd5ebd47
527
cpp
C++
testing/timesync.cpp
staticfloat/liblsl
ccdc76f80622690768707035436c8d833bb3dfd2
[ "MIT" ]
1
2020-07-13T00:04:51.000Z
2020-07-13T00:04:51.000Z
testing/timesync.cpp
staticfloat/liblsl
ccdc76f80622690768707035436c8d833bb3dfd2
[ "MIT" ]
null
null
null
testing/timesync.cpp
staticfloat/liblsl
ccdc76f80622690768707035436c8d833bb3dfd2
[ "MIT" ]
null
null
null
#include "helpers.h" #include "catch.hpp" #include <lsl_cpp.h> #include <iostream> namespace { TEST_CASE("simple timesync", "[timesync][basic]") { auto sp = create_streampair(lsl::stream_info("timesync", "Test")); double offset = sp.in_.time_correction(5.) * 1000; CHECK(offset < 1); CAPTURE(offset); double remote_time, uncertainty; offset = sp.in_.time_correction(&remote_time, &uncertainty, 5.) * 1000; CHECK(offset < 1); CHECK(uncertainty * 1000 < 1); CHECK(remote_time < lsl::local_clock()); } } // namespace
23.954545
72
0.70019
staticfloat
927feb418c31d63018cf81ffc516680a7b3d707a
2,613
cpp
C++
src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/scene/speciallogic/worldspecial/specialguildquestion.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "specialguildquestion.hpp" #include "scene/activityshadow/activityshadow.hpp" #include "obj/character/role.h" #include "obj/otherobj/gatherobj.h" #include "servercommon/activitydef.hpp" #include "config/logicconfigmanager.hpp" #include "servercommon/string/gameworldstr.h" #include "scene/scenemanager.h" #include "other/event/eventhandler.hpp" #include "global/guild/guild.hpp" #include "global/guild/guildmanager.hpp" #include "protocal/msgchatmsg.h" #include "config/activityconfig/guildquestionconfig.hpp" SpecialGuildQuestion::SpecialGuildQuestion(Scene *scene) : SpecialLogic(scene), m_is_init(false), m_is_open(true), m_is_first(false) { } SpecialGuildQuestion::~SpecialGuildQuestion() { } void SpecialGuildQuestion::Update(unsigned long interval, time_t now_second) { SpecialLogic::Update(interval, now_second); if (!m_is_open) { this->DelayKickOutAllRole(); } } void SpecialGuildQuestion::OnRoleEnterScene(Role *role) { if (NULL == role || !m_is_open) { return; } if (!m_is_first && ActivityShadow::Instance().IsActivtyOpen(ACTIVITY_TYPE_GUILD_QUESTION)) { m_is_first = true; this->RefreshGatherItem(); } ActivityShadow::Instance().OnJoinGuildQuestionActivity(role); } void SpecialGuildQuestion::OnRoleLeaveScene(Role *role, bool is_logout) { } void SpecialGuildQuestion::NotifySystemMsg(char *str_buff, int str_len) { } void SpecialGuildQuestion::OnActivityStart() { if (!m_is_first) { m_is_first = true; this->RefreshGatherItem(); } } void SpecialGuildQuestion::OnActivityClose() { m_is_open = false; } void SpecialGuildQuestion::RefreshGatherItem() { const GuildQuestionOtherConfig &other_cfg = LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg(); int pos_count = LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPosCount(); for (int i = 0; i < pos_count; i ++) { Posi gather_pos(0, 0); if (!LOGIC_CONFIG->GetGuildQuestionConfig().GetGatherPos(i, &gather_pos)) { continue; } if (m_scene->GetMap()->Validate(Obj::OBJ_TYPE_ROLE, gather_pos.x, gather_pos.y)) { GatherObj *gather_obj = new GatherObj(); gather_obj->SetPos(gather_pos); gather_obj->Init(NULL, other_cfg.gather_id, other_cfg.gather_time_s * 1000, 0, false); m_scene->AddObj(gather_obj); } } } bool SpecialGuildQuestion::SpecialCanGather(Role *role, GatherObj *gather) { if (NULL == role || NULL == gather) { return false; } if (gather->GatherId() != LOGIC_CONFIG->GetGuildQuestionConfig().GetOtherCfg().gather_id) { return false; } if (!ActivityShadow::Instance().IsCanGatherGuildQuestion(role)) { return false; } return true; }
21.775
98
0.745886
mage-game
92815904666326c63eb5fd49b88dcdb571f2738b
2,772
cc
C++
Geometry/TrackerCommonData/plugins/DDTrackerXYZPosAlgo.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
Geometry/TrackerCommonData/plugins/DDTrackerXYZPosAlgo.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
Geometry/TrackerCommonData/plugins/DDTrackerXYZPosAlgo.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
/////////////////////////////////////////////////////////////////////////////// // File: DDTrackerXYZPosAlgo.cc // Description: Position n copies at given x-values, y-values and z-values /////////////////////////////////////////////////////////////////////////////// #include <cmath> #include <algorithm> #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "DetectorDescription/Core/interface/DDCurrentNamespace.h" #include "DetectorDescription/Core/interface/DDSplit.h" #include "Geometry/TrackerCommonData/plugins/DDTrackerXYZPosAlgo.h" #include "CLHEP/Units/GlobalPhysicalConstants.h" #include "CLHEP/Units/GlobalSystemOfUnits.h" DDTrackerXYZPosAlgo::DDTrackerXYZPosAlgo() { LogDebug("TrackerGeom") <<"DDTrackerXYZPosAlgo info: Creating an instance"; } DDTrackerXYZPosAlgo::~DDTrackerXYZPosAlgo() {} void DDTrackerXYZPosAlgo::initialize(const DDNumericArguments & nArgs, const DDVectorArguments & vArgs, const DDMapArguments & , const DDStringArguments & sArgs, const DDStringVectorArguments & vsArgs) { startCopyNo = int(nArgs["StartCopyNo"]); incrCopyNo = int(nArgs["IncrCopyNo"]); xvec = vArgs["XPositions"]; yvec = vArgs["YPositions"]; zvec = vArgs["ZPositions"]; rotMat = vsArgs["Rotations"]; idNameSpace = DDCurrentNamespace::ns(); childName = sArgs["ChildName"]; DDName parentName = parent().name(); LogDebug("TrackerGeom") << "DDTrackerXYZPosAlgo debug: Parent " << parentName << "\tChild " << childName << " NameSpace " << idNameSpace << "\tCopyNo (Start/Increment) " << startCopyNo << ", " << incrCopyNo << "\tNumber " << xvec.size() << ", " << yvec.size() << ", " << zvec.size(); for (int i = 0; i < (int)(zvec.size()); i++) { LogDebug("TrackerGeom") << "\t[" << i << "]\tX = " << xvec[i] << "\t[" << i << "]\tY = " << yvec[i] << "\t[" << i << "]\tZ = " << zvec[i] << ", Rot.Matrix = " << rotMat[i]; } } void DDTrackerXYZPosAlgo::execute(DDCompactView& cpv) { int copy = startCopyNo; DDName mother = parent().name(); DDName child(DDSplit(childName).first, DDSplit(childName).second); for (int i=0; i<(int)(zvec.size()); i++) { DDTranslation tran(xvec[i], yvec[i], zvec[i]); std::string rotstr = DDSplit(rotMat[i]).first; DDRotation rot; if (rotstr != "NULL") { std::string rotns = DDSplit(rotMat[i]).second; rot = DDRotation(DDName(rotstr, rotns)); } cpv.position(child, mother, copy, tran, rot); LogDebug("TrackerGeom") << "DDTrackerXYZPosAlgo test: " << child <<" number " << copy << " positioned in " << mother << " at " << tran << " with " << rot; copy += incrCopyNo; } }
37.459459
80
0.585137
nistefan
92828ab08dc5e49f6157298c519b9b7157dc7a67
1,254
cpp
C++
tests/ebpf_map_tests/map_get_next_key_test.cpp
0mp/generic-ebpf
1ff5c744e2509d0131a28ab16c54da0e3bb37081
[ "Apache-2.0" ]
82
2017-10-05T07:15:12.000Z
2019-12-15T14:20:25.000Z
tests/ebpf_map_tests/map_get_next_key_test.cpp
0mp/generic-ebpf
1ff5c744e2509d0131a28ab16c54da0e3bb37081
[ "Apache-2.0" ]
6
2020-01-11T15:33:14.000Z
2021-07-25T06:38:45.000Z
tests/ebpf_map_tests/map_get_next_key_test.cpp
0mp/generic-ebpf
1ff5c744e2509d0131a28ab16c54da0e3bb37081
[ "Apache-2.0" ]
9
2017-08-05T17:09:50.000Z
2019-09-09T02:59:19.000Z
#include <gtest/gtest.h> extern "C" { #include <errno.h> #include <stdint.h> #include <sys/ebpf.h> #include "../test_common.hpp" } namespace { class MapGetNextKeyTest : public CommonFixture { protected: struct ebpf_map *em; virtual void SetUp() { int error; CommonFixture::SetUp(); struct ebpf_map_attr attr; attr.type = EBPF_MAP_TYPE_ARRAY; attr.key_size = sizeof(uint32_t); attr.value_size = sizeof(uint32_t); attr.max_entries = 100; attr.flags = 0; error = ebpf_map_create(ee, &em, &attr); ASSERT_TRUE(!error); } virtual void TearDown() { ebpf_map_destroy(em); CommonFixture::TearDown(); } }; TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLMap) { int error; uint32_t key = 50, next_key = 0; error = ebpf_map_get_next_key_from_user(NULL, &key, &next_key); EXPECT_EQ(EINVAL, error); } TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLKey) { int error; uint32_t key = 50, next_key = 0; error = ebpf_map_get_next_key_from_user(em, NULL, &next_key); EXPECT_NE(EINVAL, error); } TEST_F(MapGetNextKeyTest, GetNextKeyWithNULLNextKey) { int error; uint32_t key = 50; error = ebpf_map_get_next_key_from_user(em, &key, NULL); EXPECT_EQ(EINVAL, error); } } // namespace
19.292308
65
0.694577
0mp
928569bb6b8d4e4dd3aa3ba56dc744b2e81b2734
349
cpp
C++
Engine/Application/ClientApplication.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
16
2018-12-22T02:09:05.000Z
2022-03-09T20:38:59.000Z
Engine/Application/ClientApplication.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
46
2018-04-02T11:06:01.000Z
2019-12-14T11:16:04.000Z
Engine/Application/ClientApplication.cpp
hhyyrylainen/Leviathan
0a0d2ea004a153f9b17c6230da029e8160716f71
[ "BSL-1.0" ]
14
2018-04-09T02:26:15.000Z
2021-09-11T03:12:15.000Z
// ------------------------------------ // #include "ClientApplication.h" using namespace Leviathan; // ------------------------------------ // DLLEXPORT ClientApplication::ClientApplication() {} DLLEXPORT ClientApplication::ClientApplication(Engine* engine) : LeviathanApplication(engine) {} DLLEXPORT ClientApplication::~ClientApplication() {}
29.083333
93
0.616046
hhyyrylainen
928721107e2c12801e71dbdca664b7c9fd173c72
356
cpp
C++
Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
1
2021-12-18T13:50:51.000Z
2021-12-18T13:50:51.000Z
Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
1
2021-11-30T08:09:46.000Z
2021-11-30T08:09:46.000Z
Plugins/Pixel2D/Source/Pixel2DEditor/Private/Pixel2DLayers/Pixel2DLayerCommands.cpp
UnderGround-orchestra-band/SuperRogue
65a520ac6ccf859c5994e429ffe915e9ff6f1028
[ "MIT" ]
null
null
null
// Copyright 1998-2018 Epic Games, Inc. All Rights Reserved. #include "Pixel2DLayerCommands.h" #define LOCTEXT_NAMESPACE "FPixel2DLayerModule" void FPixel2DLayerCommands::RegisterCommands() { UI_COMMAND(OpenPluginWindow, "Pixel2DLayers", "Bring up Pixel2D Layers window", EUserInterfaceActionType::Button, FInputGesture()); } #undef LOCTEXT_NAMESPACE
27.384615
132
0.80618
UnderGround-orchestra-band
9287ca9ef9d07942489290990f895af0f69dc0d9
4,118
cpp
C++
lightcrafts/tools/trial/trial.cpp
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
303
2015-01-28T12:03:10.000Z
2022-03-21T12:14:56.000Z
lightcrafts/tools/trial/trial.cpp
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
127
2015-01-04T12:14:22.000Z
2022-03-29T01:48:30.000Z
lightcrafts/tools/trial/trial.cpp
mr-c/LightZone
acf5501fdda8e1077770cf6937879824a759ec93
[ "BSD-3-Clause" ]
51
2015-03-19T22:18:08.000Z
2022-01-28T15:42:19.000Z
/* Copyright (C) 2005-2011 Fabio Riccardi */ #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iostream> using namespace std; int const OldTrialLicenseSize = 1 + sizeof( time_t ); int const TrialLicenseSize = OldTrialLicenseSize + sizeof( short ); long const TrialLicenseDuration = 60*60*24 /* seconds/day */ * 30 /* days */; enum cpu_t { cpu_none, cpu_intel, cpu_powerpc }; cpu_t cpu; char const* me; bool opt_print_start; bool opt_write_expired; /** * Flip a time_t for the right CPU. */ void flip( time_t *t ) { #ifdef __POWERPC__ if ( cpu == cpu_intel ) { #else if ( cpu == cpu_powerpc ) { #endif *t = (*t << 24) & 0xFF000000 | (*t << 8) & 0x00FF0000 | (*t >> 8) & 0x0000FF00 | (*t >> 24) & 0x000000FF ; } } /** * Read an existing trial license file. */ void read_trial( char const *file ) { ifstream in( file, ios::binary ); if ( !in ) { cerr << me << ": could not open " << file << endl; ::exit( 2 ); } char buf[ 64 ]; int const bytes_read = in.readsome( buf, sizeof( buf ) ); in.close(); switch ( bytes_read ) { case OldTrialLicenseSize: case TrialLicenseSize: if ( buf[0] != 'T' ) { cerr << me << ": " << file << " isn't a trial license file (first byte is 0x" << hex << (int)buf[0] << ")\n"; ::exit( 3 ); } break; default: cerr << me << ": " << file << " isn't either " << OldTrialLicenseSize << " or " << TrialLicenseSize << " bytes\n"; ::exit( 4 ); } time_t t; ::memcpy( &t, buf + 1, sizeof( time_t ) ); flip( &t ); if ( !opt_print_start ) t += TrialLicenseDuration; cout << ::ctime( &t ); } /** * Write a new trial license file. */ void write_trial( char const *file ) { ofstream out( file, ios::out | ios::binary ); if ( !out ) { cerr << me << ": could not write to " << file << endl; ::exit( 5 ); } char buf[ TrialLicenseSize ]; buf[0] = 'T'; time_t now; if ( opt_write_expired ) now = 0; else { now = ::time( 0 ); flip( &now ); } ::memcpy( buf + 1, &now, sizeof( time_t ) ); short revision = 0; ::memcpy( buf + 5, &revision, sizeof( short ) ); out.write( buf, sizeof( buf ) ); out.close(); } /** * Print usage message and exit. */ void usage() { cerr << "usage: " << me << "[options] trial_file\n" "------\n" " -e: write an expired license for testing (implies -w)\n" " -i: read/write Intel\n" " -p: read/write PowerPC\n" " -s: print start date instead of expiration\n" " -w: write new file instead of read\n"; ::exit( 1 ); } /** * Main. */ int main( int argc, char *argv[] ) { if ( me = ::strrchr( argv[0], '/' ) ) ++me; else me = argv[0]; bool opt_write_new = false; extern char *optarg; extern int optind, opterr; for ( int c; (c = ::getopt( argc, argv, "eipsw" )) != EOF; ) switch ( c ) { case 'i': cpu = cpu_intel; break; case 'p': cpu = cpu_powerpc; break; case 's': opt_print_start = true; break; case 'e': opt_write_expired = true; cpu = cpu_intel; // doesn't matter for expired // no break; case 'w': opt_write_new = true; break; case '?': usage(); } argc -= optind, argv += optind; if ( argc != 1 ) usage(); if ( cpu == cpu_none ) { cerr << me << ": either -i or -p is required\n"; ::exit( 1 ); } if ( opt_write_new ) write_trial( argv[0] ); else read_trial( argv[0] ); } /* vim:set et sw=4 ts=4: */
24.807229
78
0.470131
mr-c
92886a7939396c808f0ed681d65c74420a805bbc
2,062
cpp
C++
code/SoulVania/ItemRenderingSystem.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
1
2021-06-30T06:29:54.000Z
2021-06-30T06:29:54.000Z
code/SoulVania/ItemRenderingSystem.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
code/SoulVania/ItemRenderingSystem.cpp
warzes/Soulvania
83733b6a6aa38f8024109193893eb5b65b0e6294
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "ItemRenderingSystem.h" #include "GameObject.h" ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, std::string spritePath, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->spritePath = spritePath; this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } ItemRenderingSystem::ItemRenderingSystem( GameObject& parent, TextureRegion textureRegion, std::unique_ptr<IEffect> deadEffect, std::unique_ptr<IEffect> hitEffect) : parent{ parent } { this->sprite = std::make_unique<Sprite>(textureRegion); this->deadEffect = std::move(deadEffect); this->hitEffect = std::move(hitEffect); } Sprite& ItemRenderingSystem::GetSprite() { return *sprite; } GameObject& ItemRenderingSystem::GetParent() { return parent; } void ItemRenderingSystem::LoadContent(ContentManager& content) { RenderingSystem::LoadContent(content); if (sprite != nullptr) return; auto texture = content.Load<Texture>(spritePath); sprite = std::make_unique<Sprite>(texture); } void ItemRenderingSystem::Update(GameTime gameTime) { if (GetParent().GetState() == ObjectState::DYING) { deadEffect->Update(gameTime); if (deadEffect->IsFinished()) GetParent().Destroy(); } if (hitEffect != nullptr) hitEffect->Update(gameTime); } void ItemRenderingSystem::Draw(SpriteExtensions& spriteBatch) { switch (GetParent().GetState()) { case ObjectState::NORMAL: spriteBatch.Draw(*sprite, GetParent().GetPosition()); RenderingSystem::Draw(spriteBatch); break; case ObjectState::DYING: deadEffect->Draw(spriteBatch); break; } if (hitEffect != nullptr) hitEffect->Draw(spriteBatch); } void ItemRenderingSystem::OnStateChanged() { if (GetParent().GetState() == ObjectState::DYING) { if (deadEffect != nullptr) deadEffect->Show(GetParent().GetOriginPosition()); else GetParent().Destroy(); } } void ItemRenderingSystem::OnTakingDamage() { if (hitEffect != nullptr) hitEffect->Show(GetParent().GetOriginPosition()); }
20.828283
62
0.733269
warzes
928e9e3abae0d2050be710cc91fb58a4db56f6ef
20,800
cc
C++
lite/tests/kernels/strided_slice_compute_test.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
808
2018-04-17T17:43:12.000Z
2019-08-18T07:39:13.000Z
lite/tests/kernels/strided_slice_compute_test.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
728
2018-04-18T08:15:25.000Z
2019-08-16T07:14:43.000Z
lite/tests/kernels/strided_slice_compute_test.cc
714627034/Paddle-Lite
015ba88a4d639db0b73603e37f83e47be041a4eb
[ "Apache-2.0" ]
364
2018-04-18T17:05:02.000Z
2019-08-18T03:25:38.000Z
// Copyright (c) 2021 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 <gtest/gtest.h> #include "lite/api/paddle_use_kernels.h" #include "lite/api/paddle_use_ops.h" #include "lite/core/test/arena/framework.h" namespace paddle { namespace lite { inline std::vector<int64_t> vector_int2int64_t(std::vector<int> input) { std::vector<int64_t> output{}; for (auto i : input) { output.push_back(static_cast<int64_t>(i)); } return output; } template <typename T> void stride_slice(const T* input, T* out, std::vector<int64_t> in_dims, std::vector<int64_t> out_dims, std::vector<int64_t> starts_indices, std::vector<int64_t> ends_indices, std::vector<int64_t> strides_indices) { size_t in_dims_size = in_dims.size(); std::vector<int> dst_step; std::vector<int> src_step; for (size_t i = 0; i < in_dims_size; ++i) { dst_step.push_back(1); src_step.push_back(1); } int out_num = out_dims[in_dims_size - 1]; for (int i = in_dims_size - 2; i >= 0; i--) { dst_step[i] = out_dims[i + 1] * dst_step[i + 1]; src_step[i] = in_dims[i + 1] * src_step[i + 1]; out_num *= out_dims[i]; } for (int dst_id = 0; dst_id < out_num; dst_id++) { int src_id = 0; int index_id = dst_id; for (size_t j = 0; j < out_dims.size(); j++) { int cur_id = index_id / dst_step[j]; index_id = index_id % dst_step[j]; src_id += (cur_id * strides_indices[j] + starts_indices[j]) * src_step[j]; } out[dst_id] = input[src_id]; } } template <typename T> void reverse(const T* input, T* out, std::vector<int64_t> in_dims, std::vector<bool> reverse_axis) { const T* in_ptr = input; T* out_ptr = out; size_t in_dims_size = in_dims.size(); std::vector<int> src_step; for (size_t i = 0; i < in_dims_size; ++i) { src_step.push_back(1); } for (int i = in_dims_size - 2; i >= 0; i--) { src_step[i] *= in_dims[i + 1] * src_step[i + 1]; } for (size_t i = 0; i < reverse_axis.size(); i++) { if (reverse_axis[i]) { // reverse for (int j = 0; j < in_dims[i]; j++) { int size = 1; if (i + 1 < in_dims_size) { size = src_step[i + 1]; } const T* in_ptr1 = in_ptr + j * size; T* out_ptr1 = out_ptr + (in_dims[i] - 1 - j) * size; memcpy(out_ptr1, in_ptr1, sizeof(T) * size); } } in_ptr += src_step[i]; out_ptr += src_step[i]; } } inline std::vector<int64_t> StridedSliceOutDims( const std::vector<int> starts, const std::vector<int> ends, const std::vector<int> strides, const std::vector<int> axes, const std::vector<int> infer_flags, const std::vector<int64_t> in_dims, const std::vector<int> decrease_axis, const size_t size, bool infer_shape) { std::vector<int64_t> out_dims_vector; for (size_t i = 0; i < in_dims.size(); i++) { out_dims_vector.push_back(in_dims[i]); } int stride_index; int start_index; int end_index; for (size_t i = 0; i < size; i++) { int axes_index = axes[i]; start_index = starts[i]; end_index = ends[i]; stride_index = strides[i]; bool decrease_axis_affect = false; if (start_index == -1 && end_index == 0 && infer_flags[i] == -1) { auto ret = std::find(decrease_axis.begin(), decrease_axis.end(), axes[i]); if (ret != decrease_axis.end()) { decrease_axis_affect = true; } } if (decrease_axis_affect) { out_dims_vector[axes_index] = 1; continue; } if (infer_shape && infer_flags[i] == -1) { out_dims_vector[axes_index] = -1; continue; } CHECK_NE(stride_index, 0) << "stride index in StridedSlice operator is 0."; CHECK_LT(axes_index, in_dims.size()) << "axes_index: " << axes_index << " should be less than in_dims.size(): " << in_dims.size() << "."; int64_t axis_size = in_dims[axes_index]; if (axis_size < 0) { continue; } if (start_index < 0) { start_index = start_index + axis_size; } if (end_index < 0) { if (!(end_index == -1 && stride_index < 0)) { // skip None stop condition end_index = end_index + axis_size; } } if (stride_index < 0) { start_index = start_index + 1; end_index = end_index + 1; } bool zero_dim_condition = ((stride_index < 0 && (start_index <= end_index)) || (stride_index > 0 && (start_index >= end_index))); CHECK_EQ(zero_dim_condition, false) << "The start index and end index are " "invalid for their corresponding " "stride."; auto tmp = std::max(start_index, end_index); int32_t left = std::max(static_cast<int32_t>(0), std::min(start_index, end_index)); int64_t right = std::min(axis_size, static_cast<int64_t>(tmp)); int64_t step = std::abs(static_cast<int64_t>(stride_index)); auto out_dims_index = (std::abs(right - left) + step - 1) / step; out_dims_vector[axes_index] = out_dims_index; } return out_dims_vector; } inline void StridedSliceFunctor(int* starts, int* ends, int* strides, int* axes, int* reverse_axis, std::vector<int64_t> dims, const std::vector<int> infer_flags, const std::vector<int> decrease_axis, const size_t size) { for (size_t axis = 0; axis < size; axis++) { int64_t axis_size = dims[axes[axis]]; int axis_index = axis; if (axis_size < 0) { starts[axis_index] = 0; ends[axis_index] = 1; strides[axis_index] = 1; } bool decrease_axis_affect = false; if (starts[axis_index] == -1 && ends[axis_index] == 0 && infer_flags[axis_index] == -1) { auto ret = std::find( decrease_axis.begin(), decrease_axis.end(), axes[axis_index]); if (ret != decrease_axis.end()) { decrease_axis_affect = true; } } // stride must not be zero if (starts[axis_index] < 0) { starts[axis_index] = starts[axis_index] + axis_size; } if (ends[axis_index] < 0) { if (!(ends[axis_index] == -1 && strides[axis_index] < 0)) { // skip None stop condition ends[axis_index] = ends[axis_index] + axis_size; } } if (decrease_axis_affect) { if (strides[axis_index] < 0) { ends[axis_index] = starts[axis_index] - 1; } else { ends[axis_index] = starts[axis_index] + 1; } } if (strides[axis_index] < 0) { reverse_axis[axis_index] = 1; strides[axis_index] = -strides[axis_index]; if (starts[axis_index] > ends[axis_index]) { // swap the reverse starts[axis_index] = starts[axis_index] + 1; ends[axis_index] = ends[axis_index] + 1; } std::swap(starts[axis_index], ends[axis_index]); } else { reverse_axis[axis_index] = 0; strides[axis_index] = strides[axis_index]; } } } class StridedSliceComputeTester : public arena::TestCase { protected: // common attributes for this op. std::string input_ = "Input"; std::string output_ = "Out"; std::vector<int> axes_; std::vector<int> starts_; std::vector<int> ends_; std::vector<int> strides_; std::vector<int64_t> starts_i64; std::vector<int64_t> ends_i64; std::vector<int> decrease_axis_; DDim dims_; std::vector<int> infer_flags_; std::string starts_tensor_ = "StartsTensor"; std::string ends_tensor_ = "EndsTensor"; bool use_tensor_; bool use_tensor_list_; public: StridedSliceComputeTester(const Place& place, const std::string& alias, const std::vector<int>& axes, const std::vector<int>& starts, const std::vector<int>& ends, const std::vector<int>& strides, const std::vector<int>& decrease_axis, const DDim& dims, bool use_tensor = false, bool use_tensor_list = false, const std::vector<int>& infer_flags = {}) : TestCase(place, alias), axes_(axes), starts_(starts), ends_(ends), strides_(strides), decrease_axis_(decrease_axis), dims_(dims), infer_flags_(infer_flags), use_tensor_(use_tensor), use_tensor_list_(use_tensor_list) { this->starts_i64 = vector_int2int64_t(starts); this->ends_i64 = vector_int2int64_t(ends); } void RunBaseline(Scope* scope) override { auto* out = scope->NewTensor(output_); auto* input = scope->FindTensor(input_); CHECK(out); CHECK(input); const auto* input_data = input->data<float>(); auto in_dims = input->dims(); std::vector<int64_t> out_dims_vector(in_dims.size(), -1); out_dims_vector = StridedSliceOutDims(starts_, ends_, strides_, axes_, infer_flags_, in_dims.data(), decrease_axis_, axes_.size(), true); auto out_dims = DDim(out_dims_vector); out->Resize(out_dims); auto* out_data = out->mutable_data<float>(); std::vector<int> reverse_vector(starts_.size(), 0); StridedSliceFunctor(starts_.data(), ends_.data(), strides_.data(), axes_.data(), reverse_vector.data(), in_dims.data(), infer_flags_, decrease_axis_, starts_.size()); std::vector<int64_t> starts_indices; std::vector<int64_t> ends_indices; std::vector<int64_t> strides_indices; std::vector<bool> reverse_axis; for (size_t axis = 0; axis < in_dims.size(); axis++) { starts_indices.push_back(0); ends_indices.push_back(out_dims[axis]); strides_indices.push_back(1); reverse_axis.push_back(false); } for (size_t axis = 0; axis < axes_.size(); axis++) { int axis_index = axes_[axis]; starts_indices[axis_index] = starts_[axis]; ends_indices[axis_index] = ends_[axis]; strides_indices[axis_index] = strides_[axis]; reverse_axis[axis_index] = (reverse_vector[axis] == 1) ? true : false; } auto out_dims_origin = out_dims; if (decrease_axis_.size() > 0) { std::vector<int64_t> new_out_shape; for (size_t i = 0; i < decrease_axis_.size(); ++i) { out_dims_origin[decrease_axis_[i]] = 0; } for (size_t i = 0; i < out_dims_origin.size(); ++i) { if (out_dims_origin[i] != 0) { new_out_shape.push_back(out_dims_origin[i]); } } if (new_out_shape.size() == 0) { new_out_shape.push_back(1); } out_dims_origin = DDim(new_out_shape); } bool need_reverse = false; for (size_t axis = 0; axis < axes_.size(); axis++) { if (reverse_vector[axis] == 1) { need_reverse = true; break; } } out->Resize(out_dims); if (need_reverse) { Tensor* tmp = new Tensor(); tmp->Resize(out_dims); auto* tmp_t = tmp->mutable_data<float>(); stride_slice(input_data, tmp_t, in_dims.data(), out_dims.data(), starts_indices, ends_indices, strides_indices); reverse(tmp_t, out_data, out_dims.data(), reverse_axis); } else { stride_slice(input_data, out_data, in_dims.data(), out_dims.data(), starts_indices, ends_indices, strides_indices); } if (decrease_axis_.size() > 0) { out->Resize(out_dims_origin); } } void PrepareOpDesc(cpp::OpDesc* op_desc) { op_desc->SetType("strided_slice"); op_desc->SetInput("Input", {input_}); if (use_tensor_) { op_desc->SetInput("StartsTensor", {starts_tensor_}); op_desc->SetInput("EndsTensor", {ends_tensor_}); } else if (use_tensor_list_) { std::vector<std::string> starts_tensor_list_; std::vector<std::string> ends_tensor_list_; for (size_t i = 0; i < starts_.size(); ++i) { starts_tensor_list_.push_back("starts_tensor_list_" + paddle::lite::to_string(i)); ends_tensor_list_.push_back("ends_tensor_list_" + paddle::lite::to_string(i)); } op_desc->SetInput("StartsTensorList", {starts_tensor_list_}); op_desc->SetInput("EndsTensorList", {ends_tensor_list_}); } if (infer_flags_.size() > 0) { op_desc->SetAttr("infer_flags", infer_flags_); } op_desc->SetOutput("Out", {output_}); op_desc->SetAttr("axes", axes_); op_desc->SetAttr("starts", starts_); op_desc->SetAttr("ends", ends_); op_desc->SetAttr("strides", strides_); op_desc->SetAttr("decrease_axis", decrease_axis_); } void PrepareData() override { std::vector<float> data(dims_.production()); for (int i = 0; i < dims_.production(); i++) { data[i] = i; } SetCommonTensor(input_, dims_, data.data()); if (use_tensor_) { SetCommonTensor(starts_tensor_, DDim({static_cast<int64_t>(starts_.size())}), starts_i64.data()); SetCommonTensor(ends_tensor_, DDim({static_cast<int64_t>(ends_.size())}), ends_i64.data()); } else if (use_tensor_list_) { for (size_t i = 0; i < starts_.size(); ++i) { SetCommonTensor("starts_tensor_list_" + paddle::lite::to_string(i), DDim({1}), &starts_i64[i]); } for (size_t i = 0; i < ends_.size(); ++i) { SetCommonTensor("ends_tensor_list_" + paddle::lite::to_string(i), DDim({1}), &ends_i64[i]); } } } }; void test_slice(Place place, float abs_error) { std::vector<int> axes({1, 2}); std::vector<int> starts({2, 2}); std::vector<int> strides({1, 1}); std::vector<int> ends({6, 7}); std::vector<int> infer_flags({1, 1}); std::vector<int> decrease_axis({}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_axes(Place place, float abs_error) { std::vector<int> axes({1, 2}); std::vector<int> starts({1, 1}); std::vector<int> strides({1, 1}); std::vector<int> ends({2, 3}); std::vector<int> infer_flags({1, 1}); std::vector<int> decrease_axis({}); DDim dims({2, 3, 4, 5}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_decrease_axis(Place place, float abs_error) { std::vector<int> axes({1}); std::vector<int> starts({0}); std::vector<int> ends({1}); std::vector<int> strides({1}); std::vector<int> decrease_axis({1}); std::vector<int> infer_flags({1}); DDim dims({2, 3, 4, 5}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_tensor(Place place, float abs_error) { std::vector<int> axes({0, 1, 2}); std::vector<int> starts({2, 2, 2}); std::vector<int> ends({5, 6, 7}); std::vector<int> strides({1, 1, 2}); std::vector<int> infer_flags({1, 1, 1}); std::vector<int> decrease_axis({}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, false, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } void test_slice_tensor_list(Place place, float abs_error) { std::vector<int> axes({0, 1, 2}); std::vector<int> starts({2, 2, 2}); std::vector<int> ends({5, 6, 7}); std::vector<int> strides({1, 1, 2}); std::vector<int> decrease_axis({}); std::vector<int> infer_flags({1, 1, 1}); DDim dims({10, 10, 10}); std::unique_ptr<arena::TestCase> tester( new StridedSliceComputeTester(place, "def", axes, starts, ends, strides, decrease_axis, dims, false, true, infer_flags)); arena::Arena arena(std::move(tester), place, 2e-4); arena.TestPrecision(); } TEST(StrideSlice, precision) { Place place; float abs_error = 1e-5; #if defined(LITE_WITH_NNADAPTER) place = TARGET(kNNAdapter); #if defined(NNADAPTER_WITH_HUAWEI_ASCEND_NPU) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #elif defined(NNADAPTER_WITH_HUAWEI_KIRIN_NPU) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #elif defined(NNADAPTER_WITH_NVIDIA_TENSORRT) abs_error = 1e-2; test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); return; #else return; #endif #elif defined(LITE_WITH_X86) || defined(LITE_WITH_ARM) place = TARGET(kHost); #endif test_slice(place, abs_error); test_slice_axes(place, abs_error); test_slice_decrease_axis(place, abs_error); test_slice_tensor(place, abs_error); test_slice_tensor_list(place, abs_error); } } // namespace lite } // namespace paddle
34.724541
80
0.535913
714627034
928ff6427e75f750af4d841ed2de785f10a04b9e
2,641
inl
C++
repos/plywood/src/build/Instantiators.inl
lambdatastic/plywood
1a5688e0cdd03471a17f3a628752a5734cbd0d07
[ "MIT" ]
null
null
null
repos/plywood/src/build/Instantiators.inl
lambdatastic/plywood
1a5688e0cdd03471a17f3a628752a5734cbd0d07
[ "MIT" ]
null
null
null
repos/plywood/src/build/Instantiators.inl
lambdatastic/plywood
1a5688e0cdd03471a17f3a628752a5734cbd0d07
[ "MIT" ]
null
null
null
// ply instantiate build-common PLY_BUILD void inst_ply_build_common(TargetInstantiatorArgs* args) { args->addSourceFiles("common/ply-build-common"); args->addIncludeDir(Visibility::Public, "common"); args->addTarget(Visibility::Public, "reflect"); } // ply instantiate build-target PLY_BUILD void inst_ply_build_target(TargetInstantiatorArgs* args) { args->addSourceFiles("target/ply-build-target"); args->addIncludeDir(Visibility::Public, "target"); args->addIncludeDir(Visibility::Private, NativePath::join(args->projInst->env->buildFolderPath, "codegen/ply-build-target")); args->addTarget(Visibility::Public, "build-common"); // Write codegen/ply-build-target/ply-build-target/NativeToolchain.inl // Note: If we ever cross-compile this module, the NativeToolchain will have to be different const CMakeGeneratorOptions* cmakeOptions = args->projInst->env->cmakeOptions; PLY_ASSERT(cmakeOptions); String nativeToolchainFile = String::format( R"(CMakeGeneratorOptions NativeToolchain = {{ "{}", "{}", "{}", "{}", }}; )", cmakeOptions->generator, cmakeOptions->platform, cmakeOptions->toolset, cmakeOptions->buildType); FileSystem::native()->makeDirsAndSaveTextIfDifferent( NativePath::join(args->projInst->env->buildFolderPath, "codegen/ply-build-target/ply-build-target/NativeToolchain.inl"), nativeToolchainFile, TextFormat::platformPreference()); } // ply instantiate build-provider PLY_BUILD void inst_ply_build_provider(TargetInstantiatorArgs* args) { args->addSourceFiles("provider/ply-build-provider"); args->addIncludeDir(Visibility::Public, "provider"); args->addTarget(Visibility::Public, "build-common"); args->addTarget(Visibility::Private, "pylon-reflect"); } // ply instantiate build-repo PLY_BUILD void inst_ply_build_repo(TargetInstantiatorArgs* args) { args->addSourceFiles("repo/ply-build-repo"); args->addIncludeDir(Visibility::Public, "repo"); args->addTarget(Visibility::Public, "build-target"); args->addTarget(Visibility::Public, "build-provider"); args->addTarget(Visibility::Private, "pylon-reflect"); args->addTarget(Visibility::Private, "cpp"); } // ply instantiate build-folder PLY_BUILD void inst_ply_build_folder(TargetInstantiatorArgs* args) { args->addSourceFiles("folder/ply-build-folder"); args->addIncludeDir(Visibility::Public, "folder"); args->addTarget(Visibility::Public, "build-repo"); args->addTarget(Visibility::Private, "pylon-reflect"); }
43.295082
99
0.706929
lambdatastic
92922d321b2e9ab0af0973ddf5fc489078167e7c
740
cpp
C++
Codeforces/918B/map.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2018-02-14T01:59:31.000Z
2018-03-28T03:30:45.000Z
Codeforces/918B/map.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
null
null
null
Codeforces/918B/map.cpp
codgician/ACM
391f3ce9b89b0a4bbbe3ff60eb2369fef57460d4
[ "MIT" ]
2
2017-12-30T02:46:35.000Z
2018-03-28T03:30:49.000Z
#include <iostream> #include <cstdio> #include <cmath> #include <algorithm> #include <cstring> #include <string> #include <iomanip> #include <climits> #include <vector> #include <set> #include <queue> #include <map> using namespace std; map <string, string> mp; int main() { ios::sync_with_stdio(false); int serverNum, commandNum; cin >> serverNum >> commandNum; for (int i = 0; i < serverNum; i++) { string name, ip; cin >> name >> ip; mp[ip] = name; } for (int i = 0; i < commandNum; i++) { string command, ip; cin >> command >> ip; ip = ip.substr(0, ip.length() - 1); cout << command << " " << ip << "; #" << mp[ip] << endl; } return 0; }
20
64
0.55
codgician
92938214ecf428d006b075c336428d30b84ba127
9,478
cc
C++
simulation/astrobee_gazebo/src/astrobee_gazebo.cc
linorobot/astrobee
e74a241ddea4e2088923891f8173fdcfea4afd2b
[ "Apache-2.0" ]
3
2018-01-04T02:00:49.000Z
2020-09-29T20:32:07.000Z
simulation/astrobee_gazebo/src/astrobee_gazebo.cc
nicedone/astrobee
e74a241ddea4e2088923891f8173fdcfea4afd2b
[ "Apache-2.0" ]
null
null
null
simulation/astrobee_gazebo/src/astrobee_gazebo.cc
nicedone/astrobee
e74a241ddea4e2088923891f8173fdcfea4afd2b
[ "Apache-2.0" ]
2
2020-02-20T06:02:33.000Z
2020-07-21T11:45:47.000Z
/* Copyright (c) 2017, United States Government, as represented by the * Administrator of the National Aeronautics and Space Administration. * * All rights reserved. * * The Astrobee platform is 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 <astrobee_gazebo/astrobee_gazebo.h> // Transformation helper code #include <Eigen/Eigen> #include <Eigen/Geometry> // TF2 eigen bindings #include <tf2_eigen/tf2_eigen.h> namespace gazebo { // Model plugin FreeFlyerModelPlugin::FreeFlyerModelPlugin(std::string const& name, bool heartbeats) : ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {} FreeFlyerModelPlugin::~FreeFlyerModelPlugin() { thread_.join(); } void FreeFlyerModelPlugin::Load(physics::ModelPtr model, sdf::ElementPtr sdf) { gzmsg << "[FF] Loading plugin for model with name " << name_ << "\n"; // Get usefule properties sdf_ = sdf; link_ = model->GetLink(); world_ = model->GetWorld(); model_ = model; // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized"); // Get a nodehandle based on the model name and use a different default queue // We have to do this to avoid gazebo main thread blocking the ROS queue. nh_ = ros::NodeHandle(model_->GetName()); nh_.setCallbackQueue(&queue_); // Start a custom queue thread for messages thread_ = boost::thread( boost::bind(&FreeFlyerModelPlugin::QueueThread, this)); // Call initialize on the freeflyer nodelet to start heartbeat and faults Setup(nh_); // Pass the new callback queue LoadCallback(&nh_, model_, sdf_); } // Get the model link physics::LinkPtr FreeFlyerModelPlugin::GetLink() { return link_; } // Get the model world physics::WorldPtr FreeFlyerModelPlugin::GetWorld() { return world_; } // Get the model physics::ModelPtr FreeFlyerModelPlugin::GetModel() { return model_; } // Get the extrinsics frame std::string FreeFlyerModelPlugin::GetFrame(std::string target) { std::string frame = (target.empty() ? "body" : target); if (GetModel()->GetName() == "/") return frame; return GetModel()->GetName() + "/" + frame; } // Put laser data to the interface void FreeFlyerModelPlugin::QueueThread() { while (nh_.ok()) queue_.callAvailable(ros::WallDuration(0.1)); } // Sensor plugin FreeFlyerSensorPlugin::FreeFlyerSensorPlugin(std::string const& name, bool heartbeats) : ff_util::FreeFlyerNodelet(name, heartbeats), name_(name) {} FreeFlyerSensorPlugin::~FreeFlyerSensorPlugin() { thread_.join(); } void FreeFlyerSensorPlugin::Load(sensors::SensorPtr sensor, sdf::ElementPtr sdf) { gzmsg << "[FF] Loading plugin for sensor with name " << name_ << "\n"; // Get the world in which this sensor exists, and the link it is attached to sensor_ = sensor; sdf_ = sdf; world_ = gazebo::physics::get_world(sensor->WorldName()); model_ = boost::static_pointer_cast < physics::Link > ( world_->GetEntity(sensor->ParentName()))->GetModel(); // If we specify a frame name different to our sensor tag name if (sdf->HasElement("frame")) frame_ = sdf->Get<std::string>("frame"); else frame_ = sensor_->Name(); // If we specify a different sensor type if (sdf->HasElement("rotation_type")) rotation_type_ = sdf->Get<std::string>("rotation_type"); else rotation_type_ = sensor_->Type(); // Make sure the ROS node for Gazebo has already been initialized if (!ros::isInitialized()) ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized"); // Get a nodehandle based on the model name and use a different default queue // We have to do this to avoid gazebo main thread blocking the ROS queue. nh_ = ros::NodeHandle(model_->GetName()); nh_.setCallbackQueue(&queue_); // Start a custom queue thread for messages thread_ = boost::thread( boost::bind(&FreeFlyerSensorPlugin::QueueThread, this)); // Call initialize on the freeflyer nodelet to start heartbeat and faults Setup(nh_); // Pass the new callback queue LoadCallback(&nh_, sensor_, sdf_); // Defer the extrinsics setup to allow plugins to load timer_ = nh_.createTimer(ros::Duration(1.0), &FreeFlyerSensorPlugin::SetupExtrinsics, this, true, true); } // Get the sensor world physics::WorldPtr FreeFlyerSensorPlugin::GetWorld() { return world_; } // Get the sensor model physics::ModelPtr FreeFlyerSensorPlugin::GetModel() { return model_; } // Get the extrinsics frame std::string FreeFlyerSensorPlugin::GetFrame(std::string target) { std::string frame = (target.empty() ? frame_ : target); if (GetModel()->GetName() == "/") return frame; return GetModel()->GetName() + "/" + frame; } // Get the type of the sensor std::string FreeFlyerSensorPlugin::GetRotationType() { return rotation_type_; } // Put laser data to the interface void FreeFlyerSensorPlugin::QueueThread() { while (nh_.ok()) queue_.callAvailable(ros::WallDuration(0.1)); } // Manage the extrinsics based on the sensor type void FreeFlyerSensorPlugin::SetupExtrinsics(const ros::TimerEvent&) { // Create a buffer and listener for TF2 transforms tf2_ros::Buffer buffer; tf2_ros::TransformListener listener(buffer); // Get extrinsics from framestore try { // Lookup the transform for this sensor geometry_msgs::TransformStamped tf = buffer.lookupTransform( GetFrame("body"), GetFrame(), ros::Time(0), ros::Duration(60.0)); // Handle the transform for all sensor types ignition::math::Pose3d pose( tf.transform.translation.x, tf.transform.translation.y, tf.transform.translation.z, tf.transform.rotation.w, tf.transform.rotation.x, tf.transform.rotation.y, tf.transform.rotation.z); sensor_->SetPose(pose); gzmsg << "Extrinsics set for sensor " << name_ << "\n"; // Get the pose as an Eigen type Eigen::Quaterniond pose_temp = Eigen::Quaterniond(tf.transform.rotation.w, tf.transform.rotation.x, tf.transform.rotation.y, tf.transform.rotation.z); // define the two rotations needed to transform from the flight software camera pose to the // gazebo camera pose Eigen::Quaterniond rot_90_x = Eigen::Quaterniond(0.70710678, 0.70710678, 0, 0); Eigen::Quaterniond rot_90_z = Eigen::Quaterniond(0.70710678, 0, 0, 0.70710678); pose_temp = pose_temp * rot_90_x; pose_temp = pose_temp * rot_90_z; pose = ignition::math::Pose3d( tf.transform.translation.x, tf.transform.translation.y, tf.transform.translation.z, pose_temp.w(), pose_temp.x(), pose_temp.y(), pose_temp.z()); // transform the pose into the world frame and set the camera world pose math::Pose tf_bs = pose; math::Pose tf_wb = model_->GetWorldPose(); math::Pose tf_ws = tf_bs + tf_wb; ignition::math::Pose3d world_pose = ignition::math::Pose3d(tf_ws.pos.x, tf_ws.pos.y, tf_ws.pos.z, tf_ws.rot.w, tf_ws.rot.x, tf_ws.rot.y, tf_ws.rot.z); //////////////////////////// // SPECIAL CASE 1: CAMERA // //////////////////////////// if (sensor_->Type() == "camera") { // Dynamically cast to the correct sensor sensors::CameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::CameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a camera sensor as a parent.\n"; // set the sensor pose to the pose from tf2 static sensor_->SetPose(pose); sensor->Camera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for camera " << name_ << "\n"; } ////////////////////////////////////// // SPECIAL CASE 2: WIDEANGLE CAMERA // ////////////////////////////////////// if (sensor_->Type() == "wideanglecamera") { // Dynamically cast to the correct sensor sensors::WideAngleCameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::WideAngleCameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a wideanglecamera sensor as a parent.\n"; // set the sensor pose to the pose from tf2 static sensor_->SetPose(pose); sensor->Camera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for wideanglecamera " << name_ << "\n"; } ////////////////////////////////// // SPECIAL CASE 3: DEPTH CAMERA // ////////////////////////////////// if (sensor_->Type() == "depth") { // Dynamically cast to the correct sensor sensors::DepthCameraSensorPtr sensor = std::dynamic_pointer_cast < sensors::DepthCameraSensor > (sensor_); if (!sensor) gzerr << "Extrinsics requires a depth camera sensor as a parent.\n"; sensor->DepthCamera()->SetWorldPose(world_pose); gzmsg << "Extrinsics update for depth camera " << name_ << "\n"; } } catch (tf2::TransformException &ex) { gzmsg << "[FF] No extrinsics for sensor " << name_ << "\n"; } } } // namespace gazebo
33.491166
95
0.675986
linorobot
9295ce21dcffbbc90049cad2b6d7fcb6ba7dd7a9
13,233
hpp
C++
src/3rd party/components/AlexMX/multi_edit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
8
2016-01-25T20:18:51.000Z
2019-03-06T07:00:04.000Z
src/3rd party/components/AlexMX/multi_edit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
null
null
null
src/3rd party/components/AlexMX/multi_edit.hpp
OLR-xray/OLR-3.0
b6a9bb2a0c1fb849b8c6cea2e831e1ceea5cc611
[ "Apache-2.0" ]
3
2016-02-14T01:20:43.000Z
2021-02-03T11:19:11.000Z
// Borland C++ Builder // Copyright (c) 1995, 2002 by Borland Software Corporation // All rights reserved // (DO NOT EDIT: machine generated header) 'multi_edit.pas' rev: 6.00 #ifndef multi_editHPP #define multi_editHPP #pragma delphiheader begin #pragma option push -w- #pragma option push -Vx #include <CommCtrl.hpp> // Pascal unit #include <ComCtrls.hpp> // Pascal unit #include <ExtCtrls.hpp> // Pascal unit #include <StdCtrls.hpp> // Pascal unit #include <Graphics.hpp> // Pascal unit #include <Menus.hpp> // Pascal unit #include <Forms.hpp> // Pascal unit #include <Controls.hpp> // Pascal unit #include <Classes.hpp> // Pascal unit #include <SysUtils.hpp> // Pascal unit #include <Windows.hpp> // Pascal unit #include <Messages.hpp> // Pascal unit #include <SysInit.hpp> // Pascal unit #include <System.hpp> // Pascal unit //-- user supplied ----------------------------------------------------------- namespace Multi_edit { //-- type declarations ------------------------------------------------------- #pragma option push -b- enum TSpinButtonState { sbNotDown, sbTopDown, sbBottomDown }; #pragma option pop #pragma option push -b- enum TValueType { vtInt, vtFloat, vtHex }; #pragma option pop #pragma option push -b- enum TSpinButtonKind { bkStandard, bkDiagonal, bkLightWave }; #pragma option pop #pragma option push -b- enum TLWButtonState { sbLWNotDown, sbLWDown }; #pragma option pop class DELPHICLASS TMultiObjSpinButton; class PASCALIMPLEMENTATION TMultiObjSpinButton : public Controls::TGraphicControl { typedef Controls::TGraphicControl inherited; private: TSpinButtonState FDown; Graphics::TBitmap* FUpBitmap; Graphics::TBitmap* FDownBitmap; bool FDragging; bool FInvalidate; Graphics::TBitmap* FTopDownBtn; Graphics::TBitmap* FBottomDownBtn; Extctrls::TTimer* FRepeatTimer; Graphics::TBitmap* FNotDownBtn; TSpinButtonState FLastDown; Controls::TWinControl* FFocusControl; Classes::TNotifyEvent FOnTopClick; Classes::TNotifyEvent FOnBottomClick; void __fastcall TopClick(void); void __fastcall BottomClick(void); void __fastcall GlyphChanged(System::TObject* Sender); Graphics::TBitmap* __fastcall GetUpGlyph(void); Graphics::TBitmap* __fastcall GetDownGlyph(void); void __fastcall SetUpGlyph(Graphics::TBitmap* Value); void __fastcall SetDownGlyph(Graphics::TBitmap* Value); void __fastcall SetDown(TSpinButtonState Value); void __fastcall SetFocusControl(Controls::TWinControl* Value); void __fastcall DrawAllBitmap(void); void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TSpinButtonState ADownState); void __fastcall TimerExpired(System::TObject* Sender); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); protected: virtual void __fastcall Paint(void); DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); public: __fastcall virtual TMultiObjSpinButton(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjSpinButton(void); __property TSpinButtonState Down = {read=FDown, write=SetDown, default=0}; __published: __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Visible = {default=1}; __property Graphics::TBitmap* DownGlyph = {read=GetDownGlyph, write=SetDownGlyph}; __property Graphics::TBitmap* UpGlyph = {read=GetUpGlyph, write=SetUpGlyph}; __property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl}; __property ShowHint ; __property ParentShowHint = {default=1}; __property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick}; __property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick}; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnStartDrag ; }; typedef void __fastcall (__closure *TLWNotifyEvent)(System::TObject* Sender, int Val); class DELPHICLASS TMultiObjLWButton; class PASCALIMPLEMENTATION TMultiObjLWButton : public Controls::TGraphicControl { typedef Controls::TGraphicControl inherited; private: TLWButtonState FDown; Graphics::TBitmap* FLWBitmap; bool FDragging; bool FInvalidate; Graphics::TBitmap* FLWDownBtn; Graphics::TBitmap* FLWNotDownBtn; Controls::TWinControl* FFocusControl; TLWNotifyEvent FOnLWChange; double FSens; double FAccum; void __fastcall LWChange(System::TObject* Sender, int Val); void __fastcall GlyphChanged(System::TObject* Sender); Graphics::TBitmap* __fastcall GetGlyph(void); void __fastcall SetGlyph(Graphics::TBitmap* Value); void __fastcall SetDown(TLWButtonState Value); void __fastcall SetFocusControl(Controls::TWinControl* Value); void __fastcall DrawAllBitmap(void); void __fastcall DrawBitmap(Graphics::TBitmap* ABitmap, TLWButtonState ADownState); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); protected: virtual void __fastcall Paint(void); DYNAMIC void __fastcall MouseDown(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseMove(Classes::TShiftState Shift, int X, int Y); DYNAMIC void __fastcall MouseUp(Controls::TMouseButton Button, Classes::TShiftState Shift, int X, int Y); virtual void __fastcall Notification(Classes::TComponent* AComponent, Classes::TOperation Operation); void __fastcall SetSens(double Value); public: __fastcall virtual TMultiObjLWButton(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjLWButton(void); __property TLWButtonState Down = {read=FDown, write=SetDown, default=0}; virtual void __fastcall Invalidate(void); __published: __property double LWSensitivity = {read=FSens, write=SetSens}; __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Visible = {default=1}; __property Graphics::TBitmap* LWGlyph = {read=GetGlyph, write=SetGlyph}; __property Controls::TWinControl* FocusControl = {read=FFocusControl, write=SetFocusControl}; __property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange}; __property ShowHint ; __property ParentShowHint = {default=1}; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnStartDrag ; }; class DELPHICLASS TMultiObjSpinEdit; class PASCALIMPLEMENTATION TMultiObjSpinEdit : public Stdctrls::TCustomEdit { typedef Stdctrls::TCustomEdit inherited; private: bool bIsMulti; bool bChanged; Extended BeforeValue; Graphics::TColor StartColor; Graphics::TColor FBtnColor; Classes::TAlignment FAlignment; Extended FMinValue; Extended FMaxValue; Extended FIncrement; int FButtonWidth; Byte FDecimal; bool FChanging; bool FEditorEnabled; TValueType FValueType; TMultiObjSpinButton* FButton; Controls::TWinControl* FBtnWindow; bool FArrowKeys; Classes::TNotifyEvent FOnTopClick; Classes::TNotifyEvent FOnBottomClick; TSpinButtonKind FButtonKind; Comctrls::TCustomUpDown* FUpDown; TMultiObjLWButton* FLWButton; TLWNotifyEvent FOnLWChange; double FSens; TSpinButtonKind __fastcall GetButtonKind(void); void __fastcall SetButtonKind(TSpinButtonKind Value); void __fastcall UpDownClick(System::TObject* Sender, Comctrls::TUDBtnType Button); void __fastcall LWChange(System::TObject* Sender, int Val); Extended __fastcall GetValue(void); Extended __fastcall CheckValue(Extended NewValue); int __fastcall GetAsInteger(void); bool __fastcall IsIncrementStored(void); bool __fastcall IsMaxStored(void); bool __fastcall IsMinStored(void); bool __fastcall IsValueStored(void); void __fastcall SetArrowKeys(bool Value); void __fastcall SetAsInteger(int NewValue); void __fastcall SetValue(Extended NewValue); void __fastcall SetValueType(TValueType NewType); void __fastcall SetButtonWidth(int NewValue); void __fastcall SetDecimal(Byte NewValue); int __fastcall GetButtonWidth(void); void __fastcall RecreateButton(void); void __fastcall ResizeButton(void); void __fastcall SetEditRect(void); void __fastcall SetAlignment(Classes::TAlignment Value); HIDESBASE MESSAGE void __fastcall WMSize(Messages::TWMSize &Message); HIDESBASE MESSAGE void __fastcall CMEnter(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMExit(Messages::TWMNoParams &Message); MESSAGE void __fastcall WMPaste(Messages::TWMNoParams &Message); MESSAGE void __fastcall WMCut(Messages::TWMNoParams &Message); HIDESBASE MESSAGE void __fastcall CMCtl3DChanged(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMEnabledChanged(Messages::TMessage &Message); HIDESBASE MESSAGE void __fastcall CMFontChanged(Messages::TMessage &Message); void __fastcall SetBtnColor(Graphics::TColor Value); protected: DYNAMIC void __fastcall Change(void); virtual bool __fastcall IsValidChar(char Key); virtual void __fastcall UpClick(System::TObject* Sender); virtual void __fastcall DownClick(System::TObject* Sender); DYNAMIC void __fastcall KeyDown(Word &Key, Classes::TShiftState Shift); DYNAMIC void __fastcall KeyPress(char &Key); virtual void __fastcall CreateParams(Controls::TCreateParams &Params); virtual void __fastcall CreateWnd(void); void __fastcall SetSens(double Val); double __fastcall GetSens(void); public: __fastcall virtual TMultiObjSpinEdit(Classes::TComponent* AOwner); __fastcall virtual ~TMultiObjSpinEdit(void); __property int AsInteger = {read=GetAsInteger, write=SetAsInteger, default=0}; __property Text ; void __fastcall ObjFirstInit(float v); void __fastcall ObjNextInit(float v); void __fastcall ObjApplyFloat(float &_to); void __fastcall ObjApplyInt(int &_to); __published: __property double LWSensitivity = {read=GetSens, write=SetSens}; __property Classes::TAlignment Alignment = {read=FAlignment, write=SetAlignment, default=0}; __property bool ArrowKeys = {read=FArrowKeys, write=SetArrowKeys, default=1}; __property Graphics::TColor BtnColor = {read=FBtnColor, write=SetBtnColor, default=-2147483633}; __property TSpinButtonKind ButtonKind = {read=FButtonKind, write=SetButtonKind, default=0}; __property Byte Decimal = {read=FDecimal, write=SetDecimal, default=2}; __property int ButtonWidth = {read=FButtonWidth, write=SetButtonWidth, default=14}; __property bool EditorEnabled = {read=FEditorEnabled, write=FEditorEnabled, default=1}; __property Extended Increment = {read=FIncrement, write=FIncrement, stored=IsIncrementStored}; __property Extended MaxValue = {read=FMaxValue, write=FMaxValue, stored=IsMaxStored}; __property Extended MinValue = {read=FMinValue, write=FMinValue, stored=IsMinStored}; __property TValueType ValueType = {read=FValueType, write=SetValueType, default=0}; __property Extended Value = {read=GetValue, write=SetValue, stored=IsValueStored}; __property AutoSelect = {default=1}; __property AutoSize = {default=1}; __property BorderStyle = {default=1}; __property Color = {default=-2147483643}; __property Ctl3D ; __property DragCursor = {default=-12}; __property DragMode = {default=0}; __property Enabled = {default=1}; __property Font ; __property Anchors = {default=3}; __property BiDiMode ; __property Constraints ; __property DragKind = {default=0}; __property ParentBiDiMode = {default=1}; __property ImeMode = {default=3}; __property ImeName ; __property MaxLength = {default=0}; __property ParentColor = {default=0}; __property ParentCtl3D = {default=1}; __property ParentFont = {default=1}; __property ParentShowHint = {default=1}; __property PopupMenu ; __property ReadOnly = {default=0}; __property ShowHint ; __property TabOrder = {default=-1}; __property TabStop = {default=1}; __property Visible = {default=1}; __property TLWNotifyEvent OnLWChange = {read=FOnLWChange, write=FOnLWChange}; __property Classes::TNotifyEvent OnBottomClick = {read=FOnBottomClick, write=FOnBottomClick}; __property Classes::TNotifyEvent OnTopClick = {read=FOnTopClick, write=FOnTopClick}; __property OnChange ; __property OnClick ; __property OnDblClick ; __property OnDragDrop ; __property OnDragOver ; __property OnEndDrag ; __property OnEnter ; __property OnExit ; __property OnKeyDown ; __property OnKeyPress ; __property OnKeyUp ; __property OnMouseDown ; __property OnMouseMove ; __property OnMouseUp ; __property OnStartDrag ; __property OnContextPopup ; __property OnMouseWheelDown ; __property OnMouseWheelUp ; __property OnEndDock ; __property OnStartDock ; public: #pragma option push -w-inl /* TWinControl.CreateParented */ inline __fastcall TMultiObjSpinEdit(HWND ParentWindow) : Stdctrls::TCustomEdit(ParentWindow) { } #pragma option pop }; //-- var, const, procedure --------------------------------------------------- } /* namespace Multi_edit */ using namespace Multi_edit; #pragma option pop // -w- #pragma option pop // -Vx #pragma delphiheader end. //-- end unit ---------------------------------------------------------------- #endif // multi_edit
39.035398
130
0.775712
OLR-xray
9298a61340db9fd60a9c5603815e935dcdeec3d5
1,389
cpp
C++
src/gui/window_taborder.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
1
2021-10-31T04:29:16.000Z
2021-10-31T04:29:16.000Z
src/gui/window_taborder.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
null
null
null
src/gui/window_taborder.cpp
ShigotoShoujin/shigoto.shoujin
165bac0703ffdec544ab275af25dd3504529a565
[ "MIT" ]
null
null
null
//#include "../assert/assert.hpp" #include "../assert/assert.hpp" #include "window.hpp" #include "window_taborder.hpp" namespace shoujin::gui { void WindowTabOrder::AddWindow(Window* window, int& out_taborder) { SHOUJIN_ASSERT(window); if(window->tabstop()) { _taborder_map.emplace(++_taborder_max, window); out_taborder = _taborder_max; } else out_taborder = 0; } void WindowTabOrder::CycleTab(bool cycle_up) { HWND focus_hwnd = GetFocus(); if(!focus_hwnd) { SetFocusToFirstWindow(); return; } auto window = Window::FindWindowByHandle(focus_hwnd); if(!window) { SetFocusToFirstWindow(); return; } window = FindNextWindowInTabOrder(window, cycle_up); if(window) window->SetFocus(); } Window* WindowTabOrder::FindNextWindowInTabOrder(Window* window, bool cycle_up) const { if(_taborder_map.size() == 1) return window; auto current = _taborder_map.find(window->taborder()); if(current == _taborder_map.end()) return nullptr; if(cycle_up) { if(current == _taborder_map.begin()) return _taborder_map.rbegin()->second; return std::prev(current)->second; } auto next = std::next(current); if(next == _taborder_map.end()) return _taborder_map.begin()->second; return next->second; } void WindowTabOrder::SetFocusToFirstWindow() { const auto it = _taborder_map.cbegin(); if(it != _taborder_map.cend()) it->second->SetFocus(); } }
19.842857
85
0.714903
ShigotoShoujin
929b975bdfe46c0afc7e916b74dc9b1e3dd5e2bd
608
cpp
C++
C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
195
2020-05-09T02:26:13.000Z
2022-03-30T06:12:07.000Z
C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
31
2021-06-15T19:00:57.000Z
2022-02-02T15:51:25.000Z
C++/Algorithms/RecursionAlgorithms/RecursiveSum.cpp
m-payal/AlgorithmsAndDataStructure
db53da00cefa3b681b4fcebfc0d22ee91cd489f9
[ "MIT" ]
64
2020-05-09T02:26:15.000Z
2022-02-23T16:02:01.000Z
/* Title - Recusive Sum Description- A Program to recursively calculate sum of N natural numbers. */ #include<bits/stdc++.h> using namespace std; // A recursive function to calculate the sum of N natural numbers int recursiveSum(int num) { if(num == 0) return 0; return (recursiveSum(num - 1) + num); } int main() { int num; cout<<"\n Enter a number N to find sum of first N natural numbers: "; cin>>num; cout<<"\n Sum of first "<<num<<" natural numbers is = "<<recursiveSum(num); return 0; } /* Time complexity - O(n) Sample Input - 5 Sample Output - 15 */
19.612903
80
0.636513
m-payal
929c1561b2ff5533ede9ff300b9fbd2f63160531
24,627
cpp
C++
ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp
ibstewart/ntv2
0acbac70a0b5e6509cca78cfbf69974c73c10db9
[ "MIT" ]
null
null
null
ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp
ibstewart/ntv2
0acbac70a0b5e6509cca78cfbf69974c73c10db9
[ "MIT" ]
null
null
null
ajaapps/crossplatform/demoapps/ntv2capture8k/ntv2capture8k.cpp
ibstewart/ntv2
0acbac70a0b5e6509cca78cfbf69974c73c10db9
[ "MIT" ]
null
null
null
/* SPDX-License-Identifier: MIT */ /** @file ntv2capture8k.cpp @brief Implementation of NTV2Capture class. @copyright (C) 2012-2021 AJA Video Systems, Inc. All rights reserved. **/ #include "ntv2capture8k.h" #include "ntv2utils.h" #include "ntv2devicefeatures.h" #include "ajabase/system/process.h" #include "ajabase/system/systemtime.h" #include "ajabase/system/memory.h" using namespace std; /** @brief The alignment of the video and audio buffers has a big impact on the efficiency of DMA transfers. When aligned to the page size of the architecture, only one DMA descriptor is needed per page. Misalignment will double the number of descriptors that need to be fetched and processed, thus reducing bandwidth. **/ static const uint32_t BUFFER_ALIGNMENT (4096); // The correct size for many systems NTV2Capture8K::NTV2Capture8K (const string inDeviceSpecifier, const bool withAudio, const NTV2Channel channel, const NTV2FrameBufferFormat pixelFormat, const bool inLevelConversion, const bool inDoMultiFormat, const bool inWithAnc, const bool inDoTsiRouting) : mConsumerThread (AJAThread()), mProducerThread (AJAThread()), mDeviceID (DEVICE_ID_NOTFOUND), mDeviceSpecifier (inDeviceSpecifier), mWithAudio (withAudio), mInputChannel (channel), mInputSource (::NTV2ChannelToInputSource (mInputChannel)), mVideoFormat (NTV2_FORMAT_UNKNOWN), mPixelFormat (pixelFormat), mSavedTaskMode (NTV2_DISABLE_TASKS), mAudioSystem (NTV2_AUDIOSYSTEM_1), mDoLevelConversion (inLevelConversion), mDoMultiFormat (inDoMultiFormat), mGlobalQuit (false), mWithAnc (inWithAnc), mVideoBufferSize (0), mAudioBufferSize (0), mDoTsiRouting (inDoTsiRouting) { ::memset (mAVHostBuffer, 0x0, sizeof (mAVHostBuffer)); } // constructor NTV2Capture8K::~NTV2Capture8K () { // Stop my capture and consumer threads, then destroy them... Quit (); // Unsubscribe from input vertical event... mDevice.UnsubscribeInputVerticalEvent (mInputChannel); // Unsubscribe from output vertical mDevice.UnsubscribeOutputVerticalEvent(NTV2_CHANNEL1); // Free all my buffers... for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++) { if (mAVHostBuffer[bufferNdx].fVideoBuffer) { delete mAVHostBuffer[bufferNdx].fVideoBuffer; mAVHostBuffer[bufferNdx].fVideoBuffer = AJA_NULL; } if (mAVHostBuffer[bufferNdx].fAudioBuffer) { delete mAVHostBuffer[bufferNdx].fAudioBuffer; mAVHostBuffer[bufferNdx].fAudioBuffer = AJA_NULL; } if (mAVHostBuffer[bufferNdx].fAncBuffer) { delete mAVHostBuffer[bufferNdx].fAncBuffer; mAVHostBuffer[bufferNdx].fAncBuffer = AJA_NULL; } } // for each buffer in the ring if (!mDoMultiFormat) { mDevice.ReleaseStreamForApplication(kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid())); mDevice.SetEveryFrameServices(mSavedTaskMode); // Restore prior task mode } } // destructor void NTV2Capture8K::Quit (void) { // Set the global 'quit' flag, and wait for the threads to go inactive... mGlobalQuit = true; while (mConsumerThread.Active()) AJATime::Sleep(10); while (mProducerThread.Active()) AJATime::Sleep(10); mDevice.DMABufferUnlockAll(); } // Quit AJAStatus NTV2Capture8K::Init (void) { AJAStatus status (AJA_STATUS_SUCCESS); // Open the device... if (!CNTV2DeviceScanner::GetFirstDeviceFromArgument (mDeviceSpecifier, mDevice)) {cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not found" << endl; return AJA_STATUS_OPEN;} if (!mDevice.IsDeviceReady ()) {cerr << "## ERROR: Device '" << mDeviceSpecifier << "' not ready" << endl; return AJA_STATUS_INITIALIZE;} if (!mDoMultiFormat) { if (!mDevice.AcquireStreamForApplication (kDemoAppSignature, static_cast<int32_t>(AJAProcess::GetPid()))) return AJA_STATUS_BUSY; // Another app is using the device mDevice.GetEveryFrameServices (mSavedTaskMode); // Save the current state before we change it } mDevice.SetEveryFrameServices (NTV2_OEM_TASKS); // Since this is an OEM demo, use the OEM service level mDeviceID = mDevice.GetDeviceID (); // Keep the device ID handy, as it's used frequently // Sometimes other applications disable some or all of the frame buffers, so turn them all on here... mDevice.EnableChannel(NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL1); if (::NTV2DeviceCanDoMultiFormat (mDeviceID)) { mDevice.SetMultiFormatMode (mDoMultiFormat); } else { mDoMultiFormat = false; } // Set up the video and audio... status = SetupVideo (); if (AJA_FAILURE (status)) return status; status = SetupAudio (); if (AJA_FAILURE (status)) return status; // Set up the circular buffers, the device signal routing, and both playout and capture AutoCirculate... SetupHostBuffers (); RouteInputSignal (); SetupInputAutoCirculate (); return AJA_STATUS_SUCCESS; } // Init AJAStatus NTV2Capture8K::SetupVideo (void) { // Enable and subscribe to the interrupts for the channel to be used... mDevice.EnableInputInterrupt(mInputChannel); mDevice.SubscribeInputVerticalEvent(mInputChannel); // The input vertical is not always available so we like to use the output for timing - sometimes mDevice.SubscribeOutputVerticalEvent(mInputChannel); // disable SDI transmitter mDevice.SetSDITransmitEnable(mInputChannel, false); // Wait for four verticals to let the reciever lock... mDevice.WaitForOutputVerticalInterrupt(mInputChannel, 10); // Set the video format to match the incomming video format. // Does the device support the desired input source? // Determine the input video signal format... mVideoFormat = mDevice.GetInputVideoFormat (mInputSource); if (mVideoFormat == NTV2_FORMAT_UNKNOWN) { cerr << "## ERROR: No input signal or unknown format" << endl; return AJA_STATUS_NOINPUT; // Sorry, can't handle this format } // Convert the signal wire format to a 8k format CNTV2DemoCommon::Get8KInputFormat(mVideoFormat); mDevice.SetVideoFormat(mVideoFormat, false, false, mInputChannel); mDevice.SetQuadQuadFrameEnable(true, mInputChannel); mDevice.SetQuadQuadSquaresEnable(!mDoTsiRouting, mInputChannel); // Set the device video format to whatever we detected at the input... // The user has an option here. If doing multi-format, we are, lock to the board. // If the user wants to E-E the signal then lock to input. mDevice.SetReference(NTV2_REFERENCE_FREERUN); // Set the frame buffer pixel format for all the channels on the device // (assuming it supports that pixel format -- otherwise default to 8-bit YCbCr)... if (!::NTV2DeviceCanDoFrameBufferFormat (mDeviceID, mPixelFormat)) mPixelFormat = NTV2_FBF_8BIT_YCBCR; // ...and set all buffers pixel format... if (mDoTsiRouting) { if (mInputChannel < NTV2_CHANNEL3) { mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL1); mDevice.EnableChannel(NTV2_CHANNEL2); if (!mDoMultiFormat) { mDevice.DisableChannel(NTV2_CHANNEL3); mDevice.DisableChannel(NTV2_CHANNEL4); } } else { mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL4); if (!mDoMultiFormat) { mDevice.DisableChannel(NTV2_CHANNEL1); mDevice.DisableChannel(NTV2_CHANNEL2); } } } else { mDevice.SetFrameBufferFormat(NTV2_CHANNEL1, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL2, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL3, mPixelFormat); mDevice.SetFrameBufferFormat(NTV2_CHANNEL4, mPixelFormat); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL1); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL2); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL3); mDevice.SetEnableVANCData(false, false, NTV2_CHANNEL4); mDevice.EnableChannel(NTV2_CHANNEL1); mDevice.EnableChannel(NTV2_CHANNEL2); mDevice.EnableChannel(NTV2_CHANNEL3); mDevice.EnableChannel(NTV2_CHANNEL4); } return AJA_STATUS_SUCCESS; } // SetupVideo AJAStatus NTV2Capture8K::SetupAudio (void) { // In multiformat mode, base the audio system on the channel... if (mDoMultiFormat && ::NTV2DeviceGetNumAudioSystems (mDeviceID) > 1 && UWord (mInputChannel) < ::NTV2DeviceGetNumAudioSystems (mDeviceID)) mAudioSystem = ::NTV2ChannelToAudioSystem (mInputChannel); // Have the audio system capture audio from the designated device input (i.e., ch1 uses SDIIn1, ch2 uses SDIIn2, etc.)... mDevice.SetAudioSystemInputSource (mAudioSystem, NTV2_AUDIO_EMBEDDED, ::NTV2InputSourceToEmbeddedAudioInput (mInputSource)); mDevice.SetNumberAudioChannels (::NTV2DeviceGetMaxAudioChannels (mDeviceID), mAudioSystem); mDevice.SetAudioRate (NTV2_AUDIO_48K, mAudioSystem); // The on-device audio buffer should be 4MB to work best across all devices & platforms... mDevice.SetAudioBufferSize (NTV2_AUDIO_BUFFER_BIG, mAudioSystem); mDevice.SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, mAudioSystem); return AJA_STATUS_SUCCESS; } // SetupAudio void NTV2Capture8K::SetupHostBuffers (void) { // Let my circular buffer know when it's time to quit... mAVCircularBuffer.SetAbortFlag (&mGlobalQuit); mVideoBufferSize = ::GetVideoWriteSize (mVideoFormat, mPixelFormat); printf("video size = %d\n", mVideoBufferSize); mAudioBufferSize = NTV2_AUDIOSIZE_MAX; mAncBufferSize = NTV2_ANCSIZE_MAX; // Allocate and add each in-host AVDataBuffer to my circular buffer member variable... for (unsigned bufferNdx = 0; bufferNdx < CIRCULAR_BUFFER_SIZE; bufferNdx++ ) { mAVHostBuffer [bufferNdx].fVideoBuffer = reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mVideoBufferSize, BUFFER_ALIGNMENT)); mAVHostBuffer [bufferNdx].fVideoBufferSize = mVideoBufferSize; mAVHostBuffer [bufferNdx].fAudioBuffer = mWithAudio ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAudioBufferSize, BUFFER_ALIGNMENT)) : 0; mAVHostBuffer [bufferNdx].fAudioBufferSize = mWithAudio ? mAudioBufferSize : 0; mAVHostBuffer [bufferNdx].fAncBuffer = mWithAnc ? reinterpret_cast <uint32_t *> (AJAMemory::AllocateAligned (mAncBufferSize, BUFFER_ALIGNMENT)) : 0; mAVHostBuffer [bufferNdx].fAncBufferSize = mAncBufferSize; mAVCircularBuffer.Add (& mAVHostBuffer [bufferNdx]); // Page lock the memory if (mAVHostBuffer [bufferNdx].fVideoBuffer != AJA_NULL) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fVideoBuffer, mVideoBufferSize, true); if (mAVHostBuffer [bufferNdx].fAudioBuffer) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAudioBuffer, mAudioBufferSize, true); if (mAVHostBuffer [bufferNdx].fAncBuffer) mDevice.DMABufferLock((ULWord*)mAVHostBuffer [bufferNdx].fAncBuffer, mAncBufferSize, true); } // for each AVDataBuffer } // SetupHostBuffers void NTV2Capture8K::RouteInputSignal(void) { if (mDoTsiRouting) { if (::IsRGBFormat (mPixelFormat)) { if (mInputChannel < NTV2_CHANNEL3) { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } else { if (mInputChannel < NTV2_CHANNEL3) { if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat)) { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer1DS2Input, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer2DS2Input, NTV2_XptSDIIn2DS2); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); } } else { if (NTV2_IS_QUAD_QUAD_HFR_VIDEO_FORMAT(mVideoFormat)) { mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer3DS2Input, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptFrameBuffer4DS2Input, NTV2_XptSDIIn4DS2); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } } } else { if (::IsRGBFormat (mPixelFormat)) { mDevice.Connect(NTV2_XptDualLinkIn1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptDualLinkIn1DSInput, NTV2_XptSDIIn1DS2); mDevice.Connect(NTV2_XptDualLinkIn2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptDualLinkIn2DSInput, NTV2_XptSDIIn2DS2); mDevice.Connect(NTV2_XptDualLinkIn3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptDualLinkIn3DSInput, NTV2_XptSDIIn3DS2); mDevice.Connect(NTV2_XptDualLinkIn4Input, NTV2_XptSDIIn4); mDevice.Connect(NTV2_XptDualLinkIn4DSInput, NTV2_XptSDIIn4DS2); mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptDuallinkIn1); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptDuallinkIn2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptDuallinkIn3); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptDuallinkIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } else { mDevice.Connect(NTV2_XptFrameBuffer1Input, NTV2_XptSDIIn1); mDevice.Connect(NTV2_XptFrameBuffer2Input, NTV2_XptSDIIn2); mDevice.Connect(NTV2_XptFrameBuffer3Input, NTV2_XptSDIIn3); mDevice.Connect(NTV2_XptFrameBuffer4Input, NTV2_XptSDIIn4); mDevice.SetSDITransmitEnable(NTV2_CHANNEL1, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL2, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL3, false); mDevice.SetSDITransmitEnable(NTV2_CHANNEL4, false); } } } // RouteInputSignal void NTV2Capture8K::SetupInputAutoCirculate (void) { // Tell capture AutoCirculate to use 7 frame buffers on the device... ULWord startFrame = 0, endFrame = 7; mDevice.AutoCirculateStop(NTV2_CHANNEL1); mDevice.AutoCirculateStop(NTV2_CHANNEL2); mDevice.AutoCirculateStop(NTV2_CHANNEL3); mDevice.AutoCirculateStop(NTV2_CHANNEL4); mDevice.AutoCirculateInitForInput (mInputChannel, 0, // 0 frames == explicitly set start & end frames mWithAudio ? mAudioSystem : NTV2_AUDIOSYSTEM_INVALID, // Which audio system (if any)? AUTOCIRCULATE_WITH_RP188 | AUTOCIRCULATE_WITH_ANC, // Include timecode & custom Anc 1, startFrame, endFrame); } // SetupInputAutoCirculate AJAStatus NTV2Capture8K::Run () { // Start the playout and capture threads... StartConsumerThread (); StartProducerThread (); return AJA_STATUS_SUCCESS; } // Run ////////////////////////////////////////////// // This is where we will start the consumer thread void NTV2Capture8K::StartConsumerThread (void) { // Create and start the consumer thread... mConsumerThread.Attach(ConsumerThreadStatic, this); mConsumerThread.SetPriority(AJA_ThreadPriority_High); mConsumerThread.Start(); } // StartConsumerThread // The consumer thread function void NTV2Capture8K::ConsumerThreadStatic (AJAThread * pThread, void * pContext) // static { (void) pThread; // Grab the NTV2Capture instance pointer from the pContext parameter, // then call its ConsumeFrames method... NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext)); pApp->ConsumeFrames (); } // ConsumerThreadStatic void NTV2Capture8K::ConsumeFrames (void) { CAPNOTE("Thread started"); while (!mGlobalQuit) { // Wait for the next frame to become ready to "consume"... AVDataBuffer * pFrameData (mAVCircularBuffer.StartConsumeNextBuffer ()); if (pFrameData) { // Do something useful with the frame data... // . . . . . . . . . . . . // . . . . . . . . . . . . // . . . . . . . . . . . . // Now release and recycle the buffer... mAVCircularBuffer.EndConsumeNextBuffer (); } } // loop til quit signaled CAPNOTE("Thread completed, will exit"); } // ConsumeFrames ////////////////////////////////////////////// ////////////////////////////////////////////// // This is where we start the capture thread void NTV2Capture8K::StartProducerThread (void) { // Create and start the capture thread... mProducerThread.Attach(ProducerThreadStatic, this); mProducerThread.SetPriority(AJA_ThreadPriority_High); mProducerThread.Start(); } // StartProducerThread // The capture thread function void NTV2Capture8K::ProducerThreadStatic (AJAThread * pThread, void * pContext) // static { (void) pThread; // Grab the NTV2Capture instance pointer from the pContext parameter, // then call its CaptureFrames method... NTV2Capture8K * pApp (reinterpret_cast <NTV2Capture8K *> (pContext)); pApp->CaptureFrames (); } // ProducerThreadStatic void NTV2Capture8K::CaptureFrames (void) { NTV2AudioChannelPairs nonPcmPairs, oldNonPcmPairs; CAPNOTE("Thread started"); // Start AutoCirculate running... mDevice.AutoCirculateStart (mInputChannel); while (!mGlobalQuit) { AUTOCIRCULATE_STATUS acStatus; mDevice.AutoCirculateGetStatus (mInputChannel, acStatus); if (acStatus.IsRunning () && acStatus.HasAvailableInputFrame ()) { // At this point, there's at least one fully-formed frame available in the device's // frame buffer to transfer to the host. Reserve an AVDataBuffer to "produce", and // use it in the next transfer from the device... AVDataBuffer * captureData (mAVCircularBuffer.StartProduceNextBuffer ()); mInputTransfer.SetBuffers (captureData->fVideoBuffer, captureData->fVideoBufferSize, captureData->fAudioBuffer, captureData->fAudioBufferSize, captureData->fAncBuffer, captureData->fAncBufferSize); // Do the transfer from the device into our host AVDataBuffer... mDevice.AutoCirculateTransfer (mInputChannel, mInputTransfer); // mInputTransfer.acTransferStatus.acAudioTransferSize; // this is the amount of audio captured NTV2SDIInStatistics sdiStats; mDevice.ReadSDIStatistics (sdiStats); // "Capture" timecode into the host AVDataBuffer while we have full access to it... NTV2_RP188 timecode; mInputTransfer.GetInputTimeCode (timecode); captureData->fRP188Data = timecode; // Signal that we're done "producing" the frame, making it available for future "consumption"... mAVCircularBuffer.EndProduceNextBuffer (); } // if A/C running and frame(s) are available for transfer else { // Either AutoCirculate is not running, or there were no frames available on the device to transfer. // Rather than waste CPU cycles spinning, waiting until a frame becomes available, it's far more // efficient to wait for the next input vertical interrupt event to get signaled... mDevice.WaitForInputVerticalInterrupt (mInputChannel); } } // loop til quit signaled // Stop AutoCirculate... mDevice.AutoCirculateStop (mInputChannel); CAPNOTE("Thread completed, will exit"); } // CaptureFrames ////////////////////////////////////////////// void NTV2Capture8K::GetACStatus (ULWord & outGoodFrames, ULWord & outDroppedFrames, ULWord & outBufferLevel) { AUTOCIRCULATE_STATUS status; mDevice.AutoCirculateGetStatus (mInputChannel, status); outGoodFrames = status.acFramesProcessed; outDroppedFrames = status.acFramesDropped; outBufferLevel = status.acBufferLevel; }
39.593248
157
0.697811
ibstewart
929d530fe906177786471f26757b646ba7848678
2,832
cpp
C++
Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp
bLandais/txRobotic
bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03
[ "CC0-1.0" ]
2
2018-04-04T18:59:50.000Z
2021-06-13T01:07:38.000Z
Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp
bLandais/txRobotic
bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03
[ "CC0-1.0" ]
9
2017-03-22T17:26:25.000Z
2017-06-25T13:35:34.000Z
Scratch-firmata/Scratch_Firmata_lib/ControlPanel.cpp
bLandais/txRobotic
bfe4a0ef0fdb9745e222ab0f5c61223cb3543e03
[ "CC0-1.0" ]
3
2017-03-22T15:09:12.000Z
2018-04-04T18:59:51.000Z
/* File: ControlPanel.cpp Author: Mathilde Created on 18 octobre 2016, 11:37 */ #include <map> #include "vector" #include <math.h> #include <iostream> #include "Arduino.h" #include "ControlPanel.h" #include "Button.h" // constructors ControlPanel::ControlPanel() { } ControlPanel::ControlPanel(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //getter /* std::vector::size_type ControlPanel::getBtnNumber(){ return this->btnList.size; }*/ int ControlPanel::getBtnNumberMax() { return this->btnList.capacity(); } std::vector<Button> ControlPanel::getBtnList() { return this->btnList; } //setters void ControlPanel::setBtnNumberMax(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //************************************************************************ // Add button in the control panel button list // Arguments : the button you want to add in the list // Return : nothing //************************************************************************ void ControlPanel::addButton(Button newBtn) { this->btnList.push_back(newBtn); } //************************************************************************ // Memory reservation for buttons // Arguments : the number of buttons you want to rreserve memory for // Return : nothing //************************************************************************ void ControlPanel::reserve(int newBtnNumberMax) { this->btnList.reserve(newBtnNumberMax); } //************************************************************************ // Control panel read: read all buttons stocked in the button vector // Arguments : none // Return : none //************************************************************************ void ControlPanel::controlRead() { for (auto &btn : this->btnList) { btn.readValue(); } } //int ControlPanel::toBinary(){ // int count=0; // int binary=0; // // controlRead(); // for (auto &btn: this->btnList){ // if(btn.getValue() == LOW){ // binary = binary + pow(10,count); // } // count++; // } // return binary; //} //************************************************************************ // Control panel analyse: analyse the values stored in memory from read // Arguments : none // Return : 1 right; 2 left; 3 down; 4 up; 5 validate //************************************************************************ int ControlPanel::analyze() { controlRead(); // Serial.println("Analyse button"); if (this->btnList[0].value == LOW) { return 1; } else if (this->btnList[1].value == LOW) { return 2; } else if (this->btnList[2].value == LOW) { return 3; } else if (this->btnList[3].value == LOW) { return 4; } else if (this->btnList[4].value == LOW) { return 5; } else { return 0; } }
23.6
74
0.513771
bLandais
929f720a94a4ebbc040a014231c03521e5eccb7c
11,055
cpp
C++
src/GameCardProcess.cpp
jakcron/NXTools
04662e529f2be92f590ca0754e780c7716b8c077
[ "MIT" ]
40
2017-07-18T18:21:00.000Z
2018-08-05T12:30:05.000Z
src/GameCardProcess.cpp
PMArkive/NNTools
276db64e45471a77345a87abb5c10a54ed8cc71e
[ "MIT" ]
9
2018-04-05T07:44:54.000Z
2018-08-07T09:11:22.000Z
src/GameCardProcess.cpp
PMArkive/NNTools
276db64e45471a77345a87abb5c10a54ed8cc71e
[ "MIT" ]
13
2018-01-22T09:10:13.000Z
2018-08-05T12:30:06.000Z
#include "GameCardProcess.h" #include <tc/crypto.h> #include <tc/io/IOUtil.h> #include <nn/hac/GameCardUtil.h> #include <nn/hac/ContentMetaUtil.h> #include <nn/hac/ContentArchiveUtil.h> #include <nn/hac/GameCardFsMetaGenerator.h> #include "FsProcess.h" nstool::GameCardProcess::GameCardProcess() : mModuleName("nstool::GameCardProcess"), mFile(), mCliOutputMode(true, false, false, false), mVerify(false), mListFs(false), mProccessExtendedHeader(false), mRootPfs(), mExtractJobs() { } void nstool::GameCardProcess::process() { importHeader(); // validate header signature if (mVerify) validateXciSignature(); // display header if (mCliOutputMode.show_basic_info) displayHeader(); // process nested HFS0 processRootPfs(); } void nstool::GameCardProcess::setInputFile(const std::shared_ptr<tc::io::IStream>& file) { mFile = file; } void nstool::GameCardProcess::setKeyCfg(const KeyBag& keycfg) { mKeyCfg = keycfg; } void nstool::GameCardProcess::setCliOutputMode(CliOutputMode type) { mCliOutputMode = type; } void nstool::GameCardProcess::setVerifyMode(bool verify) { mVerify = verify; } void nstool::GameCardProcess::setExtractJobs(const std::vector<nstool::ExtractJob> extract_jobs) { mExtractJobs = extract_jobs; } void nstool::GameCardProcess::setShowFsTree(bool show_fs_tree) { mListFs = show_fs_tree; } void nstool::GameCardProcess::importHeader() { if (mFile == nullptr) { throw tc::Exception(mModuleName, "No file reader set."); } if (mFile->canRead() == false || mFile->canSeek() == false) { throw tc::NotSupportedException(mModuleName, "Input stream requires read/seek permissions."); } // check stream is large enough for header if (mFile->length() < tc::io::IOUtil::castSizeToInt64(sizeof(nn::hac::sSdkGcHeader))) { throw tc::Exception(mModuleName, "Corrupt GameCard Image: File too small."); } // allocate memory for header tc::ByteData scratch = tc::ByteData(sizeof(nn::hac::sSdkGcHeader)); // read header region mFile->seek(0, tc::io::SeekOrigin::Begin); mFile->read(scratch.data(), scratch.size()); // determine if this is a SDK XCI or a "Community" XCI if (((nn::hac::sSdkGcHeader*)scratch.data())->signed_header.header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic) { mIsTrueSdkXci = true; mGcHeaderOffset = sizeof(nn::hac::sGcKeyDataRegion); } else if (((nn::hac::sGcHeader_Rsa2048Signed*)scratch.data())->header.st_magic.unwrap() == nn::hac::gc::kGcHeaderStructMagic) { mIsTrueSdkXci = false; mGcHeaderOffset = 0; } else { throw tc::Exception(mModuleName, "Corrupt GameCard Image: Unexpected magic bytes."); } nn::hac::sGcHeader_Rsa2048Signed* hdr_ptr = (nn::hac::sGcHeader_Rsa2048Signed*)(scratch.data() + mGcHeaderOffset); // generate hash of raw header tc::crypto::GenerateSha256Hash(mHdrHash.data(), (byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader)); // save the signature memcpy(mHdrSignature.data(), hdr_ptr->signature.data(), mHdrSignature.size()); // decrypt extended header byte_t xci_header_key_index = hdr_ptr->header.key_flag & 7; if (mKeyCfg.xci_header_key.find(xci_header_key_index) != mKeyCfg.xci_header_key.end()) { nn::hac::GameCardUtil::decryptXciHeader(&hdr_ptr->header, mKeyCfg.xci_header_key[xci_header_key_index].data()); mProccessExtendedHeader = true; } // deserialise header mHdr.fromBytes((byte_t*)&hdr_ptr->header, sizeof(nn::hac::sGcHeader)); } void nstool::GameCardProcess::displayHeader() { const nn::hac::sGcHeader* raw_hdr = (const nn::hac::sGcHeader*)mHdr.getBytes().data(); fmt::print("[GameCard/Header]\n"); fmt::print(" CardHeaderVersion: {:d}\n", mHdr.getCardHeaderVersion()); fmt::print(" RomSize: {:s}", nn::hac::GameCardUtil::getRomSizeAsString((nn::hac::gc::RomSize)mHdr.getRomSizeType())); if (mCliOutputMode.show_extended_info) fmt::print(" (0x{:x})", mHdr.getRomSizeType()); fmt::print("\n"); fmt::print(" PackageId: 0x{:016x}\n", mHdr.getPackageId()); fmt::print(" Flags: 0x{:02x}\n", *((byte_t*)&raw_hdr->flags)); for (auto itr = mHdr.getFlags().begin(); itr != mHdr.getFlags().end(); itr++) { fmt::print(" {:s}\n", nn::hac::GameCardUtil::getHeaderFlagsAsString((nn::hac::gc::HeaderFlags)*itr)); } if (mCliOutputMode.show_extended_info) { fmt::print(" KekIndex: {:s} ({:d})\n", nn::hac::GameCardUtil::getKekIndexAsString((nn::hac::gc::KekIndex)mHdr.getKekIndex()), mHdr.getKekIndex()); fmt::print(" TitleKeyDecIndex: {:d}\n", mHdr.getTitleKeyDecIndex()); fmt::print(" InitialData:\n"); fmt::print(" Hash:\n"); fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getInitialDataHash().data(), mHdr.getInitialDataHash().size(), true, "", 0x10, 6, false)); } if (mCliOutputMode.show_extended_info) { fmt::print(" Extended Header AesCbc IV:\n"); fmt::print(" {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getAesCbcIv().data(), mHdr.getAesCbcIv().size(), true, "")); } fmt::print(" SelSec: 0x{:x}\n", mHdr.getSelSec()); fmt::print(" SelT1Key: 0x{:x}\n", mHdr.getSelT1Key()); fmt::print(" SelKey: 0x{:x}\n", mHdr.getSelKey()); if (mCliOutputMode.show_layout) { fmt::print(" RomAreaStartPage: 0x{:x}", mHdr.getRomAreaStartPage()); if (mHdr.getRomAreaStartPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getRomAreaStartPage())); fmt::print("\n"); fmt::print(" BackupAreaStartPage: 0x{:x}", mHdr.getBackupAreaStartPage()); if (mHdr.getBackupAreaStartPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getBackupAreaStartPage())); fmt::print("\n"); fmt::print(" ValidDataEndPage: 0x{:x}", mHdr.getValidDataEndPage()); if (mHdr.getValidDataEndPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage())); fmt::print("\n"); fmt::print(" LimArea: 0x{:x}", mHdr.getLimAreaPage()); if (mHdr.getLimAreaPage() != (uint32_t)(-1)) fmt::print(" (0x{:x})", nn::hac::GameCardUtil::blockToAddr(mHdr.getLimAreaPage())); fmt::print("\n"); fmt::print(" PartitionFs Header:\n"); fmt::print(" Offset: 0x{:x}\n", mHdr.getPartitionFsAddress()); fmt::print(" Size: 0x{:x}\n", mHdr.getPartitionFsSize()); if (mCliOutputMode.show_extended_info) { fmt::print(" Hash:\n"); fmt::print(" {:s}", tc::cli::FormatUtil::formatBytesAsStringWithLineLimit(mHdr.getPartitionFsHash().data(), mHdr.getPartitionFsHash().size(), true, "", 0x10, 6, false)); } } if (mProccessExtendedHeader) { fmt::print("[GameCard/ExtendedHeader]\n"); fmt::print(" FwVersion: v{:d} ({:s})\n", mHdr.getFwVersion(), nn::hac::GameCardUtil::getCardFwVersionDescriptionAsString((nn::hac::gc::FwVersion)mHdr.getFwVersion())); fmt::print(" AccCtrl1: 0x{:x}\n", mHdr.getAccCtrl1()); fmt::print(" CardClockRate: {:s}\n", nn::hac::GameCardUtil::getCardClockRateAsString((nn::hac::gc::CardClockRate)mHdr.getAccCtrl1())); fmt::print(" Wait1TimeRead: 0x{:x}\n", mHdr.getWait1TimeRead()); fmt::print(" Wait2TimeRead: 0x{:x}\n", mHdr.getWait2TimeRead()); fmt::print(" Wait1TimeWrite: 0x{:x}\n", mHdr.getWait1TimeWrite()); fmt::print(" Wait2TimeWrite: 0x{:x}\n", mHdr.getWait2TimeWrite()); fmt::print(" SdkAddon Version: {:s} (v{:d})\n", nn::hac::ContentArchiveUtil::getSdkAddonVersionAsString(mHdr.getFwMode()), mHdr.getFwMode()); fmt::print(" CompatibilityType: {:s} ({:d})\n", nn::hac::GameCardUtil::getCompatibilityTypeAsString((nn::hac::gc::CompatibilityType)mHdr.getCompatibilityType()), mHdr.getCompatibilityType()); fmt::print(" Update Partition Info:\n"); fmt::print(" CUP Version: {:s} (v{:d})\n", nn::hac::ContentMetaUtil::getVersionAsString(mHdr.getUppVersion()), mHdr.getUppVersion()); fmt::print(" CUP TitleId: 0x{:016x}\n", mHdr.getUppId()); fmt::print(" CUP Digest: {:s}\n", tc::cli::FormatUtil::formatBytesAsString(mHdr.getUppHash().data(), mHdr.getUppHash().size(), true, "")); } } bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash, bool use_salt, byte_t salt) { // read region into memory tc::ByteData scratch = tc::ByteData(tc::io::IOUtil::castInt64ToSize(len)); mFile->seek(offset, tc::io::SeekOrigin::Begin); mFile->read(scratch.data(), scratch.size()); // update hash tc::crypto::Sha256Generator sha256_gen; sha256_gen.initialize(); sha256_gen.update(scratch.data(), scratch.size()); if (use_salt) sha256_gen.update(&salt, sizeof(salt)); // calculate hash nn::hac::detail::sha256_hash_t calc_hash; sha256_gen.getHash(calc_hash.data()); return memcmp(calc_hash.data(), test_hash, calc_hash.size()) == 0; } bool nstool::GameCardProcess::validateRegionOfFile(int64_t offset, int64_t len, const byte_t* test_hash) { return validateRegionOfFile(offset, len, test_hash, false, 0); } void nstool::GameCardProcess::validateXciSignature() { if (mKeyCfg.xci_header_sign_key.isSet()) { if (tc::crypto::VerifyRsa2048Pkcs1Sha256(mHdrSignature.data(), mHdrHash.data(), mKeyCfg.xci_header_sign_key.get()) == false) { fmt::print("[WARNING] GameCard Header Signature: FAIL\n"); } } else { fmt::print("[WARNING] GameCard Header Signature: FAIL (Failed to load rsa public key.)\n"); } } void nstool::GameCardProcess::processRootPfs() { if (mVerify && validateRegionOfFile(mHdr.getPartitionFsAddress(), mHdr.getPartitionFsSize(), mHdr.getPartitionFsHash().data(), mHdr.getCompatibilityType() != nn::hac::gc::COMPAT_GLOBAL, mHdr.getCompatibilityType()) == false) { fmt::print("[WARNING] GameCard Root HFS0: FAIL (bad hash)\n"); } std::shared_ptr<tc::io::IStream> gc_fs_raw = std::make_shared<tc::io::SubStream>(tc::io::SubStream(mFile, mHdr.getPartitionFsAddress(), nn::hac::GameCardUtil::blockToAddr(mHdr.getValidDataEndPage()+1) - mHdr.getPartitionFsAddress())); auto gc_vfs_meta = nn::hac::GameCardFsMetaGenerator(gc_fs_raw, mHdr.getPartitionFsSize(), mVerify ? nn::hac::GameCardFsMetaGenerator::ValidationMode_Warn : nn::hac::GameCardFsMetaGenerator::ValidationMode_None); std::shared_ptr<tc::io::IStorage> gc_vfs = std::make_shared<tc::io::VirtualFileSystem>(tc::io::VirtualFileSystem(gc_vfs_meta) ); FsProcess fs_proc; fs_proc.setInputFileSystem(gc_vfs); fs_proc.setFsFormatName("PartitionFs"); fs_proc.setFsProperties({ fmt::format("Type: Nested HFS0"), fmt::format("DirNum: {:d}", gc_vfs_meta.dir_entries.empty() ? 0 : gc_vfs_meta.dir_entries.size() - 1), // -1 to not include root directory fmt::format("FileNum: {:d}", gc_vfs_meta.file_entries.size()) }); fs_proc.setShowFsInfo(mCliOutputMode.show_basic_info); fs_proc.setShowFsTree(mListFs); fs_proc.setFsRootLabel(kXciMountPointName); fs_proc.setExtractJobs(mExtractJobs); fs_proc.process(); }
38.653846
235
0.686839
jakcron