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
02ba23328eeca0f62d4af2e2b270976537a6404d
7,190
cc
C++
mlfe/operators/impl/xnnpack/conv2d.cc
shi510/mlfe
aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0
[ "MIT" ]
13
2019-01-23T11:21:01.000Z
2021-06-20T18:25:11.000Z
mlfe/operators/impl/xnnpack/conv2d.cc
shi510/mlfe
aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0
[ "MIT" ]
null
null
null
mlfe/operators/impl/xnnpack/conv2d.cc
shi510/mlfe
aec8d52ddb54ce6f6e00a6515d7023ffba9d02f0
[ "MIT" ]
4
2018-01-08T12:40:22.000Z
2021-12-02T05:23:36.000Z
#include "mlfe/operators/conv2d.h" #include "mlfe/core/op_kernel.h" #include "mlfe/device_context/cpu_context.h" #include "mlfe/core/device.h" #include "mlfe/math/blas.h" #include "mlfe/math/basic_functions.h" #include "mlfe/math/transform.h" #include "mlfe/device_context/cpu_context.h" #include "mlfe/operators/utils.h" #include <xnnpack.h> #include <iostream> namespace mlfe{ namespace operators{ namespace { template <typename T> struct conv2d_nhwc_op { static void run(Tensor x, Tensor kernel, Tensor y, std::vector<int32_t> strides, std::vector<int32_t> paddings ) { if(xnn_status_success != xnn_initialize(nullptr)){ std::cout<<"Fail xnn_initialize"<<std::endl; } xnn_operator_t xnn_op = nullptr; int batch = x.shape()[0]; int in_h = x.shape()[1]; int in_w = x.shape()[2]; int in_c = x.shape()[3]; int kh = kernel.shape()[0]; int kw = kernel.shape()[1]; auto status = xnn_create_convolution2d_nhwc_f32( paddings[0], paddings[1], paddings[0], paddings[1], kh, kw, /*subsampling_height=*/strides[0], /*subsampling_width=*/strides[1], /*dilation height=*/1, /*dilation width=*/1, /*groups=*/1, /*group_input_channels=*/in_c, /*group_output_channels=*/y.shape()[3], /*input_pixel_stride=*/in_c, /*output_pixel_stride=*/y.shape()[3], /*weight_ptr=*/kernel.device_data<T>(), /*bias_ptr=*/nullptr, /*output_min=*/-std::numeric_limits<T>::infinity(), /*output_max=*/std::numeric_limits<T>::infinity(), /*depthwise_layout=*/0, &xnn_op); if(xnn_status_success != status){ std::cout<<"Fail xnn_create_convolution2d_nhwc_f32"<<std::endl; } status = xnn_setup_convolution2d_nhwc_f32( xnn_op, batch, in_h, in_w, x.device_data<T>(), y.mutable_device_data<T>(), nullptr); if(xnn_status_success != status){ std::cout<<"Fail xnn_setup_convolution2d_nhwc_f32"<<std::endl; } if(xnn_status_success != xnn_run_operator(xnn_op, nullptr)){ std::cout<<"Fail xnn_run_operator"<<std::endl; } if(xnn_status_success != xnn_delete_operator(xnn_op)){ std::cout<<"Fail xnn_delete_operator"<<std::endl; } } }; template <typename T> struct conv2d_nhwc_input_grad_op { static void run( Tensor kernel, Tensor dy, Tensor dx, std::vector<int32_t> strides, std::vector<int32_t> paddings ) { using IntVec = std::vector<type::int32::T>; memory_ptr col_buf; int m, n, k, batch; int in_c, in_h, in_w; std::vector<type::int32::T> filters_hw; filters_hw.resize(2); filters_hw[0] = kernel.shape()[0]; filters_hw[1] = kernel.shape()[1]; batch = dx.shape()[0]; in_h = dx.shape()[1]; in_w = dx.shape()[2]; in_c = dx.shape()[3]; // output channels. m = kernel.shape()[3]; // output height * output width n = dy.shape()[1] * dy.shape()[2]; // input channels * kernel height * kernel width k = kernel.shape()[2] * filters_hw[0] * filters_hw[1]; col_buf = create_memory(k * n * sizeof(T)); auto w_ptr = kernel.device_data<T>(); auto dy_ptr = dy.device_data<T>(); auto dx_ptr = dx.mutable_device_data<T>(); auto col_ptr = col_buf->mutable_device_data<T>(); math::set<T, CPUContext>(dx.size(), static_cast<T>(0), dx_ptr); for(int i = 0; i < batch; ++i){ /* * Calculate loss to propagate through bottom. * w({kernel_size, out_channel}) * dy({out_size, out_channel})^T * = col({kernel_size, out_size}) */ math::gemm<T, CPUContext>( false, true, k, n, m, static_cast<T>(1), w_ptr, k, dy_ptr, n, static_cast<T>(0), col_ptr, n, nullptr ); math::col2im_nhwc<T, CPUContext>( col_ptr, in_c, in_h, in_w, filters_hw[0], strides[0], paddings[0], dx_ptr ); /* * next batch. */ dx_ptr += dx.size() / batch; dy_ptr += n * m; } } }; template <typename T> struct conv2d_nhwc_kernel_grad_op{ static void run( Tensor x, Tensor dy, Tensor dkernel, std::vector<int32_t> strides, std::vector<int32_t> paddings ) { using IntVec = std::vector<type::int32::T>; memory_ptr col_buf; int m, n, k, batch; int in_c, in_h, in_w; std::vector<type::int32::T> kernel_hw = {dkernel.shape()[0], dkernel.shape()[1]}; batch = x.shape()[0]; in_h = x.shape()[1]; in_w = x.shape()[2]; in_c = x.shape()[3]; // output channels. m = dkernel.shape()[3]; // output height * width n = dy.shape()[1] * dy.shape()[2]; // in_channels * kernel_height * kernel_width k = x.shape()[3] * kernel_hw[0] * kernel_hw[1]; col_buf = create_memory(k * n * sizeof(T)); auto x_ptr = x.device_data<T>(); auto dy_ptr = dy.device_data<T>(); auto dw_ptr = dkernel.mutable_device_data<T>(); auto col_ptr = col_buf->mutable_device_data<T>(); math::set<T, CPUContext>(dkernel.size(), static_cast<T>(0), dw_ptr); math::set<T, CPUContext>(k * n, static_cast<T>(0), col_ptr); for(int i = 0; i < batch; ++i){ math::im2col_nhwc<T, CPUContext>( in_c, in_h, in_w, kernel_hw[0], kernel_hw[1], strides[0], paddings[0], x_ptr, col_ptr ); /* * Calculate gradients of weights. * kernel_size ={kernel_h, kernel_w, channel_of_x} = k * filters ={number of feature map channel} = m * out_size ={y_h, y_w} = n * col({kernel_size, out_size}) * dy({filters, out_size})^T * = dw({filters, kernel_size}) */ math::gemm<T, CPUContext>( false, true, k, m, n, static_cast<T>(1), col_ptr, n, dy_ptr, n, static_cast<T>(1), dw_ptr, k, nullptr ); /* * next batch. */ x_ptr += x.size() / batch; dy_ptr += n * m; } } }; } // namespace anonymous REGIST_OP_KERNEL( conv2d_fwd, conv2d_fwd_fn_t, conv2d_nhwc_op<float>::run ); REGIST_OP_KERNEL( conv2d_input_bwd, conv2d_input_bwd_fn_t, conv2d_nhwc_input_grad_op<float>::run ); REGIST_OP_KERNEL( conv2d_kernel_bwd, conv2d_kernel_bwd_fn_t, conv2d_nhwc_kernel_grad_op<float>::run ); } // namespace operators } // namespace mlfe
30.083682
76
0.530042
shi510
02bf76daecd4b55313c0e9b8fc047c19960f1f06
1,341
cpp
C++
src/VKUFrame.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/VKUFrame.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/VKUFrame.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
#include "VKUFrame.h" #include "VKUFormFactory.h" #include "VKUPanelFactory.h" #include "AppResourceId.h" #include "ObjectCounter.h" using namespace Tizen::Base; using namespace Tizen::Ui; using namespace Tizen::Ui::Controls; using namespace Tizen::Ui::Scenes; VKUFrame::VKUFrame(void) { CONSTRUCT(L"VKUFrame"); } VKUFrame::~VKUFrame(void) { DESTRUCT(L"VKUFrame"); } result VKUFrame::OnInitializing(void) { result r = E_SUCCESS; SceneManager* pSceneManager = SceneManager::GetInstance(); TryCatch(GetLastResult() == E_SUCCESS, r = GetLastResult(), "Failed SceneManager::GetInstance"); static VKUFormFactory formFactory; static VKUPanelFactory panelFactory; r = pSceneManager->RegisterFormFactory(formFactory); TryCatch(r == E_SUCCESS, , "Failed RegisterFormFactory"); r = pSceneManager->RegisterPanelFactory(panelFactory); TryCatch(r == E_SUCCESS, , "Failed RegisterPanelFactory"); r = pSceneManager->RegisterScene(L"workflow"); TryCatch(r == E_SUCCESS, , "Failed RegisterScene"); r = pSceneManager->GoForward(SceneTransitionId(ID_SCNT_START)); TryCatch(r == E_SUCCESS, , "Failed GoForward"); return r; CATCH: AppLogException("OnInitializing is failed.", GetErrorMessage(r)); return r; } result VKUFrame::OnTerminating(void) { result r = E_SUCCESS; // TODO: // Add your termination code here return r; }
24.381818
97
0.747949
igorglotov
02bffe093fc3864ecef598ca30f7c1a97c7dfb76
19,213
cpp
C++
src/lib/Camera.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
22
2020-05-18T02:37:09.000Z
2022-03-13T18:44:30.000Z
src/lib/Camera.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
null
null
null
src/lib/Camera.cpp
edisonlee0212/UniEngine
62278ae811235179e6a1c24eb35acf73e400fe28
[ "BSD-3-Clause" ]
3
2020-12-21T01:21:03.000Z
2021-09-06T08:07:41.000Z
#include "AssetManager.hpp" #include <Utilities.hpp> #include <Camera.hpp> #include <Cubemap.hpp> #include <EditorManager.hpp> #include <Gui.hpp> #include <PostProcessing.hpp> #include <RenderManager.hpp> #include <SerializationManager.hpp> #include <Texture2D.hpp> using namespace UniEngine; CameraInfoBlock Camera::m_cameraInfoBlock; std::unique_ptr<OpenGLUtils::GLUBO> Camera::m_cameraUniformBufferBlock; Plane::Plane() : m_a(0), m_b(0), m_c(0), m_d(0) { } void Plane::Normalize() { const float mag = glm::sqrt(m_a * m_a + m_b * m_b + m_c * m_c); m_a /= mag; m_b /= mag; m_c /= mag; m_d /= mag; } void Camera::CalculatePlanes(std::vector<Plane> &planes, glm::mat4 projection, glm::mat4 view) { glm::mat4 comboMatrix = projection * glm::transpose(view); planes[0].m_a = comboMatrix[3][0] + comboMatrix[0][0]; planes[0].m_b = comboMatrix[3][1] + comboMatrix[0][1]; planes[0].m_c = comboMatrix[3][2] + comboMatrix[0][2]; planes[0].m_d = comboMatrix[3][3] + comboMatrix[0][3]; planes[1].m_a = comboMatrix[3][0] - comboMatrix[0][0]; planes[1].m_b = comboMatrix[3][1] - comboMatrix[0][1]; planes[1].m_c = comboMatrix[3][2] - comboMatrix[0][2]; planes[1].m_d = comboMatrix[3][3] - comboMatrix[0][3]; planes[2].m_a = comboMatrix[3][0] - comboMatrix[1][0]; planes[2].m_b = comboMatrix[3][1] - comboMatrix[1][1]; planes[2].m_c = comboMatrix[3][2] - comboMatrix[1][2]; planes[2].m_d = comboMatrix[3][3] - comboMatrix[1][3]; planes[3].m_a = comboMatrix[3][0] + comboMatrix[1][0]; planes[3].m_b = comboMatrix[3][1] + comboMatrix[1][1]; planes[3].m_c = comboMatrix[3][2] + comboMatrix[1][2]; planes[3].m_d = comboMatrix[3][3] + comboMatrix[1][3]; planes[4].m_a = comboMatrix[3][0] + comboMatrix[2][0]; planes[4].m_b = comboMatrix[3][1] + comboMatrix[2][1]; planes[4].m_c = comboMatrix[3][2] + comboMatrix[2][2]; planes[4].m_d = comboMatrix[3][3] + comboMatrix[2][3]; planes[5].m_a = comboMatrix[3][0] - comboMatrix[2][0]; planes[5].m_b = comboMatrix[3][1] - comboMatrix[2][1]; planes[5].m_c = comboMatrix[3][2] - comboMatrix[2][2]; planes[5].m_d = comboMatrix[3][3] - comboMatrix[2][3]; planes[0].Normalize(); planes[1].Normalize(); planes[2].Normalize(); planes[3].Normalize(); planes[4].Normalize(); planes[5].Normalize(); } void Camera::CalculateFrustumPoints( const std::shared_ptr<Camera> &cameraComponrnt, float nearPlane, float farPlane, glm::vec3 cameraPos, glm::quat cameraRot, glm::vec3 *points) { const glm::vec3 front = cameraRot * glm::vec3(0, 0, -1); const glm::vec3 right = cameraRot * glm::vec3(1, 0, 0); const glm::vec3 up = cameraRot * glm::vec3(0, 1, 0); const glm::vec3 nearCenter = front * nearPlane; const glm::vec3 farCenter = front * farPlane; const float e = tanf(glm::radians(cameraComponrnt->m_fov * 0.5f)); const float near_ext_y = e * nearPlane; const float near_ext_x = near_ext_y * cameraComponrnt->GetResolutionRatio(); const float far_ext_y = e * farPlane; const float far_ext_x = far_ext_y * cameraComponrnt->GetResolutionRatio(); points[0] = cameraPos + nearCenter - right * near_ext_x - up * near_ext_y; points[1] = cameraPos + nearCenter - right * near_ext_x + up * near_ext_y; points[2] = cameraPos + nearCenter + right * near_ext_x + up * near_ext_y; points[3] = cameraPos + nearCenter + right * near_ext_x - up * near_ext_y; points[4] = cameraPos + farCenter - right * far_ext_x - up * far_ext_y; points[5] = cameraPos + farCenter - right * far_ext_x + up * far_ext_y; points[6] = cameraPos + farCenter + right * far_ext_x + up * far_ext_y; points[7] = cameraPos + farCenter + right * far_ext_x - up * far_ext_y; } glm::quat Camera::ProcessMouseMovement(float yawAngle, float pitchAngle, bool constrainPitch) { // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } glm::vec3 front; front.x = cos(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front.y = sin(glm::radians(pitchAngle)); front.z = sin(glm::radians(yawAngle)) * cos(glm::radians(pitchAngle)); front = glm::normalize(front); const glm::vec3 right = glm::normalize(glm::cross( front, glm::vec3(0.0f, 1.0f, 0.0f))); // Normalize the vectors, because their length gets closer to 0 the more // you look up or down which results in slower movement. const glm::vec3 up = glm::normalize(glm::cross(right, front)); return glm::quatLookAt(front, up); } void Camera::ReverseAngle(const glm::quat &rotation, float &pitchAngle, float &yawAngle, const bool &constrainPitch) { const auto angle = glm::degrees(glm::eulerAngles(rotation)); pitchAngle = angle.x; yawAngle = glm::abs(angle.z) > 90.0f ? 90.0f - angle.y : -90.0f - angle.y; if (constrainPitch) { if (pitchAngle > 89.0f) pitchAngle = 89.0f; if (pitchAngle < -89.0f) pitchAngle = -89.0f; } } std::shared_ptr<Texture2D> Camera::GetTexture() const { return m_colorTexture; } std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferDepth() { return m_gBufferDepth; } std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferNormal() { return m_gBufferNormal; } std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferAlbedo() { return m_gBufferAlbedo; } std::unique_ptr<OpenGLUtils::GLTexture2D> &Camera::UnsafeGetGBufferMetallicRoughnessEmissionAmbient() { return m_gBufferMetallicRoughnessEmissionAmbient; } glm::mat4 Camera::GetProjection() const { return glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); } glm::vec3 Camera::Project(GlobalTransform &ltw, glm::vec3 position) { return m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view * glm::vec4(position, 1.0f); } glm::vec3 Camera::UnProject(GlobalTransform &ltw, glm::vec3 position) const { glm::mat4 inversed = glm::inverse(m_cameraInfoBlock.m_projection * m_cameraInfoBlock.m_view); glm::vec4 start = glm::vec4(position, 1.0f); start = inversed * start; return start / start.w; } glm::vec3 Camera::GetMouseWorldPoint(GlobalTransform &ltw, glm::vec2 mousePosition) const { const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const glm::vec4 start = glm::vec4((mousePosition.x - halfX) / halfX, -1 * (mousePosition.y - halfY) / halfY, 0.0f, 1.0f); return start / start.w; } void Camera::SetClearColor(glm::vec3 color) const { m_frameBuffer->ClearColor(glm::vec4(color.x, color.y, color.z, 0.0f)); m_frameBuffer->Clear(); m_frameBuffer->ClearColor(glm::vec4(0.0f)); } Ray Camera::ScreenPointToRay(GlobalTransform &ltw, glm::vec2 mousePosition) const { const auto position = ltw.GetPosition(); const auto rotation = ltw.GetRotation(); const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto projection = glm::perspective(glm::radians(m_fov * 0.5f), GetResolutionRatio(), m_nearDistance, m_farDistance); const auto view = glm::lookAt(position, position + front, up); const glm::mat4 inv = glm::inverse(projection * view); const float halfX = static_cast<float>(m_resolutionX) / 2.0f; const float halfY = static_cast<float>(m_resolutionY) / 2.0f; const auto realX = (mousePosition.x + halfX) / halfX; const auto realY = (mousePosition.y - halfY) / halfY; if (glm::abs(realX) > 1.0f || glm::abs(realY) > 1.0f) return {glm::vec3(FLT_MAX), glm::vec3(FLT_MAX)}; glm::vec4 start = glm::vec4(realX, -1 * realY, -1, 1.0); glm::vec4 end = glm::vec4(realX, -1.0f * realY, 1.0f, 1.0f); start = inv * start; end = inv * end; start /= start.w; end /= end.w; const glm::vec3 dir = glm::normalize(glm::vec3(end - start)); return {glm::vec3(ltw.m_value[3]) + m_nearDistance * dir, glm::vec3(ltw.m_value[3]) + m_farDistance * dir}; } void Camera::GenerateMatrices() { m_cameraUniformBufferBlock = std::make_unique<OpenGLUtils::GLUBO>(); m_cameraUniformBufferBlock->SetData(sizeof(CameraInfoBlock), nullptr, GL_STREAM_DRAW); m_cameraUniformBufferBlock->SetBase(0); } void Camera::ResizeResolution(int x, int y) { if (m_resolutionX == x && m_resolutionY == y) return; m_resolutionX = x > 0 ? x : 1; m_resolutionY = y > 0 ? y : 1; m_gBufferNormal->ReSize(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY); m_gBufferDepth->ReSize(0, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, 0, m_resolutionX, m_resolutionY); m_gBufferAlbedo->ReSize(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY); m_gBufferMetallicRoughnessEmissionAmbient->ReSize( 0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY); m_gBuffer->SetResolution(m_resolutionX, m_resolutionY); m_colorTexture->m_texture->ReSize(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0, m_resolutionX, m_resolutionY); m_depthStencilTexture->m_texture->ReSize( 0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0, m_resolutionX, m_resolutionY); } void Camera::OnCreate() { m_resolutionX = 1; m_resolutionY = 1; m_frameCount = 0; m_colorTexture = AssetManager::CreateAsset<Texture2D>(); m_colorTexture->m_name = "CameraTexture"; m_colorTexture->m_texture = std::make_shared<OpenGLUtils::GLTexture2D>(0, GL_RGBA16F, m_resolutionX, m_resolutionY, false); m_colorTexture->m_texture->SetData(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_colorTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_colorTexture->m_texture.get(), GL_COLOR_ATTACHMENT0); m_depthStencilTexture = AssetManager::CreateAsset<Texture2D>(); m_depthStencilTexture->m_texture = std::make_shared<OpenGLUtils::GLTexture2D>(0, GL_DEPTH32F_STENCIL8, m_resolutionX, m_resolutionY, false); m_depthStencilTexture->m_texture->SetData(0, GL_DEPTH32F_STENCIL8, GL_DEPTH_STENCIL, GL_FLOAT_32_UNSIGNED_INT_24_8_REV, 0); m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_depthStencilTexture->m_texture->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); AttachTexture(m_depthStencilTexture->m_texture.get(), GL_DEPTH_STENCIL_ATTACHMENT); m_gBuffer = std::make_unique<RenderTarget>(m_resolutionX, m_resolutionY); m_gBufferDepth = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_DEPTH_COMPONENT32F, m_resolutionX, m_resolutionY, false); m_gBufferDepth->SetData(0, GL_DEPTH_COMPONENT32F, GL_DEPTH_COMPONENT, GL_FLOAT, 0); m_gBufferDepth->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gBufferDepth->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gBufferDepth->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gBufferDepth->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gBufferDepth.get(), GL_DEPTH_ATTACHMENT); m_gBufferNormal = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGB16F, m_resolutionX, m_resolutionY, false); m_gBufferNormal->SetData(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0); m_gBufferNormal->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gBufferNormal->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gBufferNormal->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gBufferNormal->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gBufferNormal.get(), GL_COLOR_ATTACHMENT0); m_gBufferAlbedo = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGB16F, m_resolutionX, m_resolutionY, false); m_gBufferAlbedo->SetData(0, GL_RGB16F, GL_RGB, GL_HALF_FLOAT, 0); m_gBufferAlbedo->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gBufferAlbedo->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gBufferAlbedo->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gBufferAlbedo->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gBufferAlbedo.get(), GL_COLOR_ATTACHMENT1); m_gBufferMetallicRoughnessEmissionAmbient = std::make_unique<OpenGLUtils::GLTexture2D>(0, GL_RGBA16F, m_resolutionX, m_resolutionY, false); m_gBufferMetallicRoughnessEmissionAmbient->SetData(0, GL_RGBA16F, GL_RGBA, GL_HALF_FLOAT, 0); m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_MIN_FILTER, GL_NEAREST); m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_MAG_FILTER, GL_NEAREST); m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); m_gBufferMetallicRoughnessEmissionAmbient->SetInt(GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); m_gBuffer->AttachTexture(m_gBufferMetallicRoughnessEmissionAmbient.get(), GL_COLOR_ATTACHMENT2); m_gBuffer->Clear(); SetEnabled(true); } void Camera::Serialize(YAML::Emitter &out) { out << YAML::Key << "m_resolutionX" << YAML::Value << m_resolutionX; out << YAML::Key << "m_resolutionY" << YAML::Value << m_resolutionY; out << YAML::Key << "m_useClearColor" << YAML::Value << m_useClearColor; out << YAML::Key << "m_clearColor" << YAML::Value << m_clearColor; out << YAML::Key << "m_allowAutoResize" << YAML::Value << m_allowAutoResize; out << YAML::Key << "m_nearDistance" << YAML::Value << m_nearDistance; out << YAML::Key << "m_farDistance" << YAML::Value << m_farDistance; out << YAML::Key << "m_fov" << YAML::Value << m_fov; m_skybox.Save("m_skybox", out); } void Camera::Deserialize(const YAML::Node &in) { int resolutionX = in["m_resolutionX"].as<int>(); int resolutionY = in["m_resolutionY"].as<int>(); m_useClearColor = in["m_useClearColor"].as<bool>(); m_clearColor = in["m_clearColor"].as<glm::vec3>(); m_allowAutoResize = in["m_allowAutoResize"].as<bool>(); m_nearDistance = in["m_nearDistance"].as<float>(); m_farDistance = in["m_farDistance"].as<float>(); m_fov = in["m_fov"].as<float>(); ResizeResolution(resolutionX, resolutionY); m_skybox.Load("m_skybox", in); } void Camera::OnDestroy() { } void Camera::OnInspect() { ImGui::Checkbox("Allow auto resize", &m_allowAutoResize); if (!m_allowAutoResize) { glm::ivec2 resolution = {m_resolutionX, m_resolutionY}; if (ImGui::DragInt2("Resolution", &resolution.x)) { ResizeResolution(resolution.x, resolution.y); } } ImGui::Checkbox("Use clear color", &m_useClearColor); const bool savedState = (this == EntityManager::GetCurrentScene()->m_mainCamera.Get<Camera>().get()); bool isMainCamera = savedState; ImGui::Checkbox("Main Camera", &isMainCamera); if (savedState != isMainCamera) { if (isMainCamera) { EntityManager::GetCurrentScene()->m_mainCamera = GetOwner().GetOrSetPrivateComponent<Camera>().lock(); } else { EntityManager::GetCurrentScene()->m_mainCamera.Clear(); } } if (m_useClearColor) { ImGui::ColorEdit3("Clear Color", (float *)(void *)&m_clearColor); } else { EditorManager::DragAndDropButton<Cubemap>(m_skybox, "Skybox"); } ImGui::DragFloat("Near", &m_nearDistance, m_nearDistance / 10.0f, 0, m_farDistance); ImGui::DragFloat("Far", &m_farDistance, m_farDistance / 10.0f, m_nearDistance); ImGui::DragFloat("FOV", &m_fov, 1.0f, 1, 359); FileUtils::SaveFile("Screenshot", "Texture2D", {".png", ".jpg"}, [this](const std::filesystem::path &filePath) { m_colorTexture->SetPathAndSave(filePath); }); if (ImGui::TreeNode("Debug")) { static float debugSacle = 0.25f; ImGui::DragFloat("Scale", &debugSacle, 0.01f, 0.1f, 1.0f); debugSacle = glm::clamp(debugSacle, 0.1f, 1.0f); ImGui::Image( (ImTextureID)m_colorTexture->UnsafeGetGLTexture()->Id(), ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle), ImVec2(0, 1), ImVec2(1, 0)); ImGui::Image( (ImTextureID)m_gBufferNormal->Id(), ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle), ImVec2(0, 1), ImVec2(1, 0)); ImGui::Image( (ImTextureID)m_gBufferAlbedo->Id(), ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle), ImVec2(0, 1), ImVec2(1, 0)); ImGui::Image( (ImTextureID)m_gBufferMetallicRoughnessEmissionAmbient->Id(), ImVec2(m_resolutionX * debugSacle, m_resolutionY * debugSacle), ImVec2(0, 1), ImVec2(1, 0)); ImGui::TreePop(); } } void Camera::PostCloneAction(const std::shared_ptr<IPrivateComponent> &target) { } void Camera::Start() { } void Camera::CollectAssetRef(std::vector<AssetRef> &list) { list.push_back(m_skybox); } std::shared_ptr<Texture2D> Camera::GetDepthStencil() const { return m_depthStencilTexture; } Camera &Camera::operator=(const Camera &source) { m_allowAutoResize = source.m_allowAutoResize; m_nearDistance = source.m_nearDistance; m_farDistance = source.m_farDistance; m_fov = source.m_fov; m_useClearColor = source.m_useClearColor; m_clearColor = source.m_clearColor; m_skybox = source.m_skybox; return *this; } void CameraInfoBlock::UpdateMatrices(const std::shared_ptr<Camera> &camera, glm::vec3 position, glm::quat rotation) { const glm::vec3 front = rotation * glm::vec3(0, 0, -1); const glm::vec3 up = rotation * glm::vec3(0, 1, 0); const auto ratio = camera->GetResolutionRatio(); m_projection = glm::perspective(glm::radians(camera->m_fov * 0.5f), ratio, camera->m_nearDistance, camera->m_farDistance); m_position = glm::vec4(position, 0); m_view = glm::lookAt(position, position + front, up); m_inverseProjection = glm::inverse(m_projection); m_inverseView = glm::inverse(m_view); m_reservedParameters = glm::vec4( camera->m_nearDistance, camera->m_farDistance, glm::tan(glm::radians(camera->m_fov * 0.5f)), static_cast<float>(camera->m_resolutionX) / camera->m_resolutionY); m_clearColor = glm::vec4(camera->m_clearColor, 1.0f); if(camera->m_useClearColor){ m_clearColor.w = 1.0f; }else{ m_clearColor.w = 0.0f; } } void CameraInfoBlock::UploadMatrices(const std::shared_ptr<Camera> &camera) const { Camera::m_cameraUniformBufferBlock->SubData(0, sizeof(CameraInfoBlock), this); }
40.61945
127
0.687451
edisonlee0212
02c14f97597e4f5c3756cb0597674a3ef166e17a
1,071
hpp
C++
src/modules/module_manager.hpp
ECP-VeloC/veloc
d27224029349b156f6420d764cf23547cf3f2b53
[ "MIT" ]
null
null
null
src/modules/module_manager.hpp
ECP-VeloC/veloc
d27224029349b156f6420d764cf23547cf3f2b53
[ "MIT" ]
null
null
null
src/modules/module_manager.hpp
ECP-VeloC/veloc
d27224029349b156f6420d764cf23547cf3f2b53
[ "MIT" ]
null
null
null
#ifndef __MODULE_MANAGER_HPP #define __MODULE_MANAGER_HPP #include "common/command.hpp" #include "common/status.hpp" #include "common/config.hpp" #include "modules/client_watchdog.hpp" #include "modules/client_aggregator.hpp" #include "modules/ec_module.hpp" #include "modules/transfer_module.hpp" #include "modules/chksum_module.hpp" #include "modules/versioning_module.hpp" #include <functional> #include <vector> #include <mpi.h> class module_manager_t { typedef std::function<int (const command_t &)> method_t; std::vector<method_t> modules; client_watchdog_t *watchdog = NULL; transfer_module_t *transfer = NULL; client_aggregator_t *ec_agg = NULL; ec_module_t *redset = NULL; chksum_module_t *chksum = NULL; versioning_module_t *versioning = NULL; public: module_manager_t(); ~module_manager_t(); void add_default(const config_t &cfg, MPI_Comm comm = MPI_COMM_NULL); void add_module(const method_t &m) { modules.push_back(m); } int notify_command(const command_t &c); }; #endif // __MODULE_MANAGER_HPP
26.775
73
0.745098
ECP-VeloC
02c29d072f65b1e2b6f47bbc4f6172c4ab61f63c
943
cpp
C++
src/frontends/paddle/src/op/softplus.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
1,127
2018-10-15T14:36:58.000Z
2020-04-20T09:29:44.000Z
src/frontends/paddle/src/op/softplus.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
439
2018-10-20T04:40:35.000Z
2020-04-19T05:56:25.000Z
src/frontends/paddle/src/op/softplus.cpp
ryanloney/openvino-1
4e0a740eb3ee31062ba0df88fcf438564f67edb7
[ "Apache-2.0" ]
414
2018-10-17T05:53:46.000Z
2020-04-16T17:29:53.000Z
// Copyright (C) 2018-2022 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include "default_opset.hpp" #include "openvino/frontend/paddle/node_context.hpp" namespace ov { namespace frontend { namespace paddle { namespace op { NamedOutputs softplus(const NodeContext& node) { auto data = node.get_input("X"); auto beta = node.get_attribute<float>("beta"); auto threshold = node.get_attribute<float>("threshold"); float supported_beta = 1.0; float supported_threshold = 20.0; const float EPSINON = 1e-6; if (!(std::fabs(beta - supported_beta) <= EPSINON) || !(std::fabs(threshold - supported_threshold) <= EPSINON)) { PADDLE_OP_CHECK(node, false, "only support beta==1.0 && threshold==20.0"); } return node.default_single_output_mapping({std::make_shared<default_opset::SoftPlus>(data)}, {"Out"}); } } // namespace op } // namespace paddle } // namespace frontend } // namespace ov
33.678571
117
0.695652
ryanloney
02c37cd234d326e4236068424db52eb986a1ee7f
8,678
cpp
C++
src/engine/input.cpp
Timurinyo/classic_game_template
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
[ "MIT" ]
null
null
null
src/engine/input.cpp
Timurinyo/classic_game_template
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
[ "MIT" ]
null
null
null
src/engine/input.cpp
Timurinyo/classic_game_template
4486e534fa76ccc8b4323515fad1c5fdae6ad8bc
[ "MIT" ]
null
null
null
#include <engine/pch.h> #include <engine/input.h> namespace cgt { Input::ScancodeMappings GenerateScancodeMappings(); Input::ScancodeMappings Input::s_ScancodeMappings = GenerateScancodeMappings(); Input::Input(Input::InputProcessingMode mode) : m_Mode(mode) { } WindowEventControlFlow Input::ProcessWindowEvent(const SDL_Event& event) { bool eventHandled = false; switch (event.type) { case SDL_KEYDOWN: { auto scancode = event.key.keysym.scancode; SetKeyboardKeyState(m_Pressed, scancode, true); SetKeyboardKeyState(m_Held, scancode, true); eventHandled = true; break; } case SDL_KEYUP: { auto scancode = event.key.keysym.scancode; SetKeyboardKeyState(m_Held, scancode, false); SetKeyboardKeyState(m_Released, scancode, true); eventHandled = true; break; } case SDL_MOUSEBUTTONDOWN: { u8 buttonIndex = event.button.button; SetMouseButtonState(m_Pressed, buttonIndex, true); SetMouseButtonState(m_Held, buttonIndex, true); eventHandled = true; break; } case SDL_MOUSEBUTTONUP: { u8 buttonIndex = event.button.button; SetMouseButtonState(m_Held, buttonIndex, false); SetMouseButtonState(m_Released, buttonIndex, true); eventHandled = true; break; } case SDL_MOUSEWHEEL: i32 motion = event.wheel.y; m_MouseWheelMotion += motion; eventHandled = true; break; } if (eventHandled && m_Mode == InputProcessingMode::Consume) { return WindowEventControlFlow::ConsumeEvent; } return WindowEventControlFlow::PassthroughEvent; } void Input::NewFrame() { m_Pressed.reset(); m_Released.reset(); m_MouseWheelMotion = 0; } bool Input::IsKeyPressed(KeyCode keyCode) const { return Get(m_Pressed, keyCode); } bool Input::IsKeyReleased(KeyCode keyCode) const { return Get(m_Released, keyCode); } bool Input::IsKeyHeld(KeyCode keyCode) const { return Get(m_Held, keyCode); } glm::ivec2 Input::GetMousePosition() const { glm::ivec2 position; SDL_GetMouseState(&position.x, &position.y); return position; } i32 Input::GetMouseWheelMotion() const { return m_MouseWheelMotion; } bool Input::Get(const Input::KeysBitset& bitset, KeyCode key) const { if (key == KeyCode::Any) { return bitset.any(); } return bitset.test((usize)key); } void Input::SetKeyboardKeyState(KeysBitset& bitset, SDL_Scancode scancode, bool active) { CGT_ASSERT(scancode < s_ScancodeMappings.size()); const auto keyCode = s_ScancodeMappings[scancode]; if (keyCode != KeyCode::Any) { bitset.set((usize)keyCode, active); } } void Input::SetMouseButtonState(KeysBitset& bitset, u8 buttonIndex, bool active) { auto keyCode = KeyCode::Any; switch (buttonIndex) { case SDL_BUTTON_LEFT: keyCode = KeyCode::LeftMouseButton; break; case SDL_BUTTON_RIGHT: keyCode = KeyCode::RightMouseButton; break; case SDL_BUTTON_MIDDLE: keyCode = KeyCode::MiddleMouseButton; break; } if (keyCode != KeyCode::Any) { bitset.set((usize)keyCode, active); } } void Input::Reset() { m_Pressed.reset(); m_Held.reset(); m_Released.reset(); m_MouseWheelMotion = 0; } Input::ScancodeMappings GenerateScancodeMappings() { Input::ScancodeMappings mappings; mappings[SDL_SCANCODE_A] = KeyCode::A; mappings[SDL_SCANCODE_B] = KeyCode::B; mappings[SDL_SCANCODE_C] = KeyCode::C; mappings[SDL_SCANCODE_D] = KeyCode::D; mappings[SDL_SCANCODE_E] = KeyCode::E; mappings[SDL_SCANCODE_F] = KeyCode::F; mappings[SDL_SCANCODE_G] = KeyCode::G; mappings[SDL_SCANCODE_H] = KeyCode::H; mappings[SDL_SCANCODE_I] = KeyCode::I; mappings[SDL_SCANCODE_J] = KeyCode::J; mappings[SDL_SCANCODE_K] = KeyCode::K; mappings[SDL_SCANCODE_L] = KeyCode::L; mappings[SDL_SCANCODE_M] = KeyCode::M; mappings[SDL_SCANCODE_N] = KeyCode::N; mappings[SDL_SCANCODE_O] = KeyCode::O; mappings[SDL_SCANCODE_P] = KeyCode::P; mappings[SDL_SCANCODE_Q] = KeyCode::Q; mappings[SDL_SCANCODE_R] = KeyCode::R; mappings[SDL_SCANCODE_S] = KeyCode::S; mappings[SDL_SCANCODE_T] = KeyCode::T; mappings[SDL_SCANCODE_U] = KeyCode::U; mappings[SDL_SCANCODE_V] = KeyCode::V; mappings[SDL_SCANCODE_W] = KeyCode::W; mappings[SDL_SCANCODE_X] = KeyCode::X; mappings[SDL_SCANCODE_Y] = KeyCode::Y; mappings[SDL_SCANCODE_Z] = KeyCode::Z; mappings[SDL_SCANCODE_1] = KeyCode::Number1; mappings[SDL_SCANCODE_2] = KeyCode::Number2; mappings[SDL_SCANCODE_3] = KeyCode::Number3; mappings[SDL_SCANCODE_4] = KeyCode::Number4; mappings[SDL_SCANCODE_5] = KeyCode::Number5; mappings[SDL_SCANCODE_6] = KeyCode::Number6; mappings[SDL_SCANCODE_7] = KeyCode::Number7; mappings[SDL_SCANCODE_8] = KeyCode::Number8; mappings[SDL_SCANCODE_9] = KeyCode::Number9; mappings[SDL_SCANCODE_0] = KeyCode::Number0; mappings[SDL_SCANCODE_RETURN] = KeyCode::Return; mappings[SDL_SCANCODE_ESCAPE] = KeyCode::Escape; mappings[SDL_SCANCODE_BACKSPACE] = KeyCode::Backspace; mappings[SDL_SCANCODE_TAB] = KeyCode::Tab; mappings[SDL_SCANCODE_SPACE] = KeyCode::Space; mappings[SDL_SCANCODE_MINUS] = KeyCode::Minus; mappings[SDL_SCANCODE_EQUALS] = KeyCode::Equals; mappings[SDL_SCANCODE_LEFTBRACKET] = KeyCode::LeftBracket; mappings[SDL_SCANCODE_RIGHTBRACKET] = KeyCode::RightBracket; mappings[SDL_SCANCODE_BACKSLASH] = KeyCode::Backslash; mappings[SDL_SCANCODE_SEMICOLON] = KeyCode::Semicolon; mappings[SDL_SCANCODE_APOSTROPHE] = KeyCode::Apostrophe; mappings[SDL_SCANCODE_GRAVE] = KeyCode::Grave; mappings[SDL_SCANCODE_COMMA] = KeyCode::Comma; mappings[SDL_SCANCODE_PERIOD] = KeyCode::Period; mappings[SDL_SCANCODE_SLASH] = KeyCode::Slash; mappings[SDL_SCANCODE_CAPSLOCK] = KeyCode::Capslock; mappings[SDL_SCANCODE_F1] = KeyCode::F1; mappings[SDL_SCANCODE_F2] = KeyCode::F2; mappings[SDL_SCANCODE_F3] = KeyCode::F3; mappings[SDL_SCANCODE_F4] = KeyCode::F4; mappings[SDL_SCANCODE_F5] = KeyCode::F5; mappings[SDL_SCANCODE_F6] = KeyCode::F6; mappings[SDL_SCANCODE_F7] = KeyCode::F7; mappings[SDL_SCANCODE_F8] = KeyCode::F8; mappings[SDL_SCANCODE_F9] = KeyCode::F9; mappings[SDL_SCANCODE_F10] = KeyCode::F10; mappings[SDL_SCANCODE_F11] = KeyCode::F11; mappings[SDL_SCANCODE_F12] = KeyCode::F12; mappings[SDL_SCANCODE_PRINTSCREEN] = KeyCode::Printscreen; mappings[SDL_SCANCODE_SCROLLLOCK] = KeyCode::Scrolllock; mappings[SDL_SCANCODE_PAUSE] = KeyCode::Pause; mappings[SDL_SCANCODE_INSERT] = KeyCode::Insert; mappings[SDL_SCANCODE_HOME] = KeyCode::Home; mappings[SDL_SCANCODE_PAGEUP] = KeyCode::PageUp; mappings[SDL_SCANCODE_DELETE] = KeyCode::Delete; mappings[SDL_SCANCODE_END] = KeyCode::End; mappings[SDL_SCANCODE_PAGEDOWN] = KeyCode::PageDown; mappings[SDL_SCANCODE_RIGHT] = KeyCode::Right; mappings[SDL_SCANCODE_LEFT] = KeyCode::Left; mappings[SDL_SCANCODE_DOWN] = KeyCode::Down; mappings[SDL_SCANCODE_UP] = KeyCode::Up; mappings[SDL_SCANCODE_KP_DIVIDE] = KeyCode::NumPadDivide; mappings[SDL_SCANCODE_KP_MULTIPLY] = KeyCode::NumPadMultiply; mappings[SDL_SCANCODE_KP_MINUS] = KeyCode::NumPadMinus; mappings[SDL_SCANCODE_KP_PLUS] = KeyCode::NumPadPlus; mappings[SDL_SCANCODE_KP_ENTER] = KeyCode::NumPadEnter; mappings[SDL_SCANCODE_KP_1] = KeyCode::NumPad1; mappings[SDL_SCANCODE_KP_2] = KeyCode::NumPad2; mappings[SDL_SCANCODE_KP_3] = KeyCode::NumPad3; mappings[SDL_SCANCODE_KP_4] = KeyCode::NumPad4; mappings[SDL_SCANCODE_KP_5] = KeyCode::NumPad5; mappings[SDL_SCANCODE_KP_6] = KeyCode::NumPad6; mappings[SDL_SCANCODE_KP_7] = KeyCode::NumPad7; mappings[SDL_SCANCODE_KP_8] = KeyCode::NumPad8; mappings[SDL_SCANCODE_KP_9] = KeyCode::NumPad9; mappings[SDL_SCANCODE_KP_0] = KeyCode::NumPad0; mappings[SDL_SCANCODE_KP_PERIOD] = KeyCode::NumPadPeriod; mappings[SDL_SCANCODE_KP_COMMA] = KeyCode::NumPadComma; mappings[SDL_SCANCODE_LCTRL] = KeyCode::LeftCtrl; mappings[SDL_SCANCODE_LSHIFT] = KeyCode::LeftShift; mappings[SDL_SCANCODE_LALT] = KeyCode::LeftAlt; mappings[SDL_SCANCODE_LGUI] = KeyCode::LeftGui; mappings[SDL_SCANCODE_RCTRL] = KeyCode::RightCtrl; mappings[SDL_SCANCODE_RSHIFT] = KeyCode::RightShift; mappings[SDL_SCANCODE_RALT] = KeyCode::RightAlt; mappings[SDL_SCANCODE_RGUI] = KeyCode::RightGui; return mappings; } }
31.787546
87
0.707536
Timurinyo
02c7302d901d1d7aff9c21837af635ffdcf8cd27
584
cpp
C++
CPP/alternatingsquarepattern.cpp
thefool76/hacktoberfest2021
237751e17a4fc325ded29fca013fb9f5853cd27c
[ "CC0-1.0" ]
448
2021-10-01T04:24:14.000Z
2022-03-06T14:34:20.000Z
CPP/alternatingsquarepattern.cpp
Chanaka-Madushan-Herath/hacktoberfest2021
8473df9e058ccb6049720dd372342e0ea60f0e59
[ "CC0-1.0" ]
282
2021-10-01T04:29:06.000Z
2022-03-07T12:42:57.000Z
CPP/alternatingsquarepattern.cpp
Chanaka-Madushan-Herath/hacktoberfest2021
8473df9e058ccb6049720dd372342e0ea60f0e59
[ "CC0-1.0" ]
1,807
2021-10-01T04:24:02.000Z
2022-03-28T04:51:25.000Z
/*You're given a number N. Print the first N lines of the below-given pattern. 1 2 3 4 5 10 9 8 7 6 11 12 13 14 15 20 19 18 17 16 21 22 23 24 25 30 29 28 27 26 */ #include <iostream> using namespace std; int main() { int n; cin>>n; int i1=0; for(int i=0; i<n; i++){ if(i%2==0){ for(int j=(10*i1)+1; j<=(i+1)*5; j++){ cout<<j<<" "; } i1++; cout<<endl; } else{ for(int k=(i+1)*5; k>=(5*i)+1; k--){ cout<<k<<" "; } cout<<endl; } } }
16.685714
79
0.416096
thefool76
02ca5391639149cdef1c7023f5df3d4e3e3c158a
40
hpp
C++
engine/src/Engine.hpp
codekrafter/CodekraftEngine
c0965b74dc4926e4612e1ff953be248acceb3198
[ "MIT" ]
null
null
null
engine/src/Engine.hpp
codekrafter/CodekraftEngine
c0965b74dc4926e4612e1ff953be248acceb3198
[ "MIT" ]
1
2018-06-26T14:00:35.000Z
2018-06-26T14:00:57.000Z
engine/src/Engine.hpp
codekrafter/CodekraftEngine
c0965b74dc4926e4612e1ff953be248acceb3198
[ "MIT" ]
1
2018-03-28T18:19:19.000Z
2018-03-28T18:19:19.000Z
#pragma once #include "Core/Engine.hpp"
13.333333
26
0.75
codekrafter
02ca54d8208161ca2a9bcca46891d4c941d5fcf4
2,788
cpp
C++
src/opts/SkBlitRow_opts_SSE4.cpp
Perspex/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
27
2016-04-27T01:02:03.000Z
2021-12-13T08:53:19.000Z
src/opts/SkBlitRow_opts_SSE4.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
2
2017-03-09T09:00:50.000Z
2017-09-21T15:48:20.000Z
src/opts/SkBlitRow_opts_SSE4.cpp
AvaloniaUI/skia
e25fe5a294e9cee8f23207eef63fad6cffa9ced4
[ "Apache-2.0" ]
17
2016-04-27T02:06:39.000Z
2019-12-18T08:07:00.000Z
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkBlitRow_opts_SSE4.h" // Some compilers can't compile SSSE3 or SSE4 intrinsics. We give them stub methods. // The stubs should never be called, so we make them crash just to confirm that. #if SK_CPU_SSE_LEVEL < SK_CPU_SSE_LEVEL_SSE41 void S32A_Opaque_BlitRow32_SSE4(SkPMColor* SK_RESTRICT, const SkPMColor* SK_RESTRICT, int, U8CPU) { sk_throw(); } #else #include <smmintrin.h> // SSE4.1 intrinsics #include "SkColorPriv.h" #include "SkColor_opts_SSE2.h" void S32A_Opaque_BlitRow32_SSE4(SkPMColor* SK_RESTRICT dst, const SkPMColor* SK_RESTRICT src, int count, U8CPU alpha) { SkASSERT(alpha == 255); // As long as we can, we'll work on 16 pixel pairs at once. int count16 = count / 16; __m128i* dst4 = (__m128i*)dst; const __m128i* src4 = (const __m128i*)src; for (int i = 0; i < count16 * 4; i += 4) { // Load 16 source pixels. __m128i s0 = _mm_loadu_si128(src4+i+0), s1 = _mm_loadu_si128(src4+i+1), s2 = _mm_loadu_si128(src4+i+2), s3 = _mm_loadu_si128(src4+i+3); const __m128i alphaMask = _mm_set1_epi32(0xFF << SK_A32_SHIFT); const __m128i ORed = _mm_or_si128(s3, _mm_or_si128(s2, _mm_or_si128(s1, s0))); if (_mm_testz_si128(ORed, alphaMask)) { // All 16 source pixels are fully transparent. There's nothing to do! continue; } const __m128i ANDed = _mm_and_si128(s3, _mm_and_si128(s2, _mm_and_si128(s1, s0))); if (_mm_testc_si128(ANDed, alphaMask)) { // All 16 source pixels are fully opaque. There's no need to read dst or blend it. _mm_storeu_si128(dst4+i+0, s0); _mm_storeu_si128(dst4+i+1, s1); _mm_storeu_si128(dst4+i+2, s2); _mm_storeu_si128(dst4+i+3, s3); continue; } // The general slow case: do the blend for all 16 pixels. _mm_storeu_si128(dst4+i+0, SkPMSrcOver_SSE2(s0, _mm_loadu_si128(dst4+i+0))); _mm_storeu_si128(dst4+i+1, SkPMSrcOver_SSE2(s1, _mm_loadu_si128(dst4+i+1))); _mm_storeu_si128(dst4+i+2, SkPMSrcOver_SSE2(s2, _mm_loadu_si128(dst4+i+2))); _mm_storeu_si128(dst4+i+3, SkPMSrcOver_SSE2(s3, _mm_loadu_si128(dst4+i+3))); } // Wrap up the last <= 15 pixels. for (int i = count16*16; i < count; i++) { // This check is not really necessarily, but it prevents pointless autovectorization. if (src[i] & 0xFF000000) { dst[i] = SkPMSrcOver(src[i], dst[i]); } } } #endif
38.722222
99
0.620875
Perspex
c49cd43e742500e91bd39afa0b55d12bcacc9318
41,168
hpp
C++
include/cascade/detail/cascade_impl.hpp
Thompson-Liu/cascade
283d99eb70da99ac1d11611037e9750397c5d011
[ "BSD-3-Clause" ]
null
null
null
include/cascade/detail/cascade_impl.hpp
Thompson-Liu/cascade
283d99eb70da99ac1d11611037e9750397c5d011
[ "BSD-3-Clause" ]
null
null
null
include/cascade/detail/cascade_impl.hpp
Thompson-Liu/cascade
283d99eb70da99ac1d11611037e9750397c5d011
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <memory> #include <map> namespace derecho { namespace cascade { #define debug_enter_func_with_args(format,...) \ dbg_default_debug("Entering {} with parameter:" #format ".", __func__, __VA_ARGS__) #define debug_leave_func_with_value(format,...) \ dbg_default_debug("Leaving {} with " #format "." , __func__, __VA_ARGS__) #define debug_enter_func() dbg_default_debug("Entering {}.") #define debug_leave_func() dbg_default_debug("Leaving {}.") /////////////////////////////////////////////////////////////////////////////// // 1 - Volatile Cascade Store Implementation /////////////////////////////////////////////////////////////////////////////// template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::put(const VT& value) const { debug_enter_func_with_args("value.get_key_ref={}",value.get_key_ref()); derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_put)>(value); auto& replies = results.get(); std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0); // TODO: verfiy consistency ? for (auto& reply_pair : replies) { ret = reply_pair.second.get(); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret)); return ret; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::remove(const KT& key) const { debug_enter_func_with_args("key={}",key); derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_remove)>(key); auto& replies = results.get(); std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0); // TODO: verify consistency ? for (auto& reply_pair : replies) { ret = reply_pair.second.get(); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret)); return ret; } template<typename KT, typename VT, KT* IK, VT* IV> const VT VolatileCascadeStore<KT,VT,IK,IV>::get(const KT& key, const persistent::version_t& ver, bool) const { debug_enter_func_with_args("key={},ver=0x{:x}",key,ver); if (ver != CURRENT_VERSION) { debug_leave_func_with_value("Cannot support versioned get, ver=0x{:x}", ver); return *IV; } derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get)>(key); auto& replies = results.get(); // TODO: verify consistency ? // for (auto& reply_pair : replies) { // ret = reply_pair.second.get(); // } debug_leave_func(); return replies.begin()->second.get(); } template<typename KT, typename VT, KT* IK, VT* IV> const VT VolatileCascadeStore<KT,VT,IK,IV>::get_by_time(const KT& key, const uint64_t& ts_us) const { // VolatileCascadeStore does not support this. debug_enter_func(); debug_leave_func(); return *IV; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::list_keys(const persistent::version_t& ver) const { debug_enter_func_with_args("ver=0x{:x}",ver); if (ver != CURRENT_VERSION) { debug_leave_func_with_value("Cannot support versioned list_keys, ver=0x{:x}", ver); return {}; } derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_list_keys)>(); auto& replies = results.get(); std::vector<KT> ret; // TODO: verfity consistency ? for (auto& reply_pair : replies) { ret = reply_pair.second.get(); } debug_leave_func(); return ret; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::list_keys_by_time(const uint64_t& ts_us) const { // VolatileCascadeStore does not support this. debug_enter_func_with_args("ts_us=0x{:x}", ts_us); debug_leave_func(); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t VolatileCascadeStore<KT,VT,IK,IV>::get_size(const KT& key, const persistent::version_t& ver, bool) const { debug_enter_func_with_args("key={},ver=0x{:x}",key,ver); if (ver != CURRENT_VERSION) { debug_leave_func_with_value("Cannot support versioned get, ver=0x{:x}", ver); return 0; } derecho::Replicated<VolatileCascadeStore>& subgroup_handle = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get_size)>(key); auto& replies = results.get(); // TODO: verify consistency ? // for (auto& reply_pair : replies) { // ret = reply_pair.second.get(); // } debug_leave_func(); return replies.begin()->second.get(); } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t VolatileCascadeStore<KT,VT,IK,IV>::get_size_by_time(const KT& key, const uint64_t& ts_us) const { // VolatileCascadeStore does not support this. debug_enter_func(); debug_leave_func(); return 0; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> VolatileCascadeStore<KT,VT,IK,IV>::ordered_list_keys() { std::vector<KT> key_list; debug_enter_func(); for(auto kv: this->kv_map) { key_list.push_back(kv.first); } debug_leave_func(); return key_list; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::ordered_put(const VT& value) { debug_enter_func_with_args("key={}",value.get_key_ref()); std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_next_version(); if constexpr (std::is_base_of<IKeepVersion,VT>::value) { value.set_version(std::get<0>(version_and_timestamp)); } if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) { value.set_timestamp(std::get<1>(version_and_timestamp)); } // Verify previous version MUST happen before update previous versions. if constexpr (std::is_base_of<IVerifyPreviousVersion,VT>::value) { bool verify_result; if (this->kv_map.find(value.get_key_ref())!=this->kv_map.end()) { verify_result = value.verify_previous_version(this->update_version,this->kv_map.at(value.get_key_ref()).get_version()); } else { verify_result = value.verify_previous_version(this->update_version,persistent::INVALID_VERSION); } if (!verify_result) { // reject the update by returning an invalid version and timestamp return {persistent::INVALID_VERSION,0}; } } if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) { if (this->kv_map.find(value.get_key_ref())!=this->kv_map.end()) { value.set_previous_version(this->update_version,this->kv_map.at(value.get_key_ref()).get_version()); } else { value.set_previous_version(this->update_version,persistent::INVALID_VERSION); } } this->kv_map.erase(value.get_key_ref()); // remove this->kv_map.emplace(value.get_key_ref(), value); // copy constructor this->update_version = std::get<0>(version_and_timestamp); if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( // group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id this->subgroup_index, // this is subgroup index group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_shard_num(), value.get_key_ref(), value, cascade_context_ptr); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return version_and_timestamp; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> VolatileCascadeStore<KT,VT,IK,IV>::ordered_remove(const KT& key) { debug_enter_func_with_args("key={}",key); std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_next_version(); if (this->kv_map.find(key)==this->kv_map.end()) { debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return version_and_timestamp; } auto value = create_null_object_cb<KT,VT,IK,IV>(key); if constexpr (std::is_base_of<IKeepVersion,VT>::value) { value.set_version(std::get<0>(version_and_timestamp)); } if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) { value.set_timestamp(std::get<1>(version_and_timestamp)); } if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) { if (this->kv_map.find(key)!=this->kv_map.end()) { value.set_previous_version(this->update_version,this->kv_map.at(key).get_version()); } else { value.set_previous_version(this->update_version,persistent::INVALID_VERSION); } } this->kv_map.erase(key); // remove this->kv_map.emplace(key, value); this->update_version = std::get<0>(version_and_timestamp); if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( // group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id this->subgroup_index, group->template get_subgroup<VolatileCascadeStore>(this->subgroup_index).get_shard_num(), key, value,cascade_context_ptr); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return version_and_timestamp; } template<typename KT, typename VT, KT* IK, VT* IV> const VT VolatileCascadeStore<KT,VT,IK,IV>::ordered_get(const KT& key) { debug_enter_func_with_args("key={}",key); if (this->kv_map.find(key) != this->kv_map.end()) { debug_leave_func_with_value("key={}",key); return this->kv_map.at(key); } else { debug_leave_func(); return *IV; } } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t VolatileCascadeStore<KT,VT,IK,IV>::ordered_get_size(const KT& key) { debug_enter_func_with_args("key={}",key); if (this->kv_map.find(key) != this->kv_map.end()) { return mutils::bytes_size(this->kv_map.at(key)); } else { debug_leave_func(); return 0; } } template<typename KT, typename VT, KT* IK, VT* IV> void VolatileCascadeStore<KT,VT,IK,IV>::trigger_put(const VT& value) const { debug_enter_func_with_args("key={}",value.get_key_ref()); if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( this->subgroup_index, group->template get_subgroup<VolatileCascadeStore<KT,VT,IK,IV>>(this->subgroup_index).get_shard_num(), value.get_key_ref(), value, cascade_context_ptr, true); } debug_leave_func(); } template<typename KT, typename VT, KT* IK, VT* IV> std::unique_ptr<VolatileCascadeStore<KT,VT,IK,IV>> VolatileCascadeStore<KT,VT,IK,IV>::from_bytes( mutils::DeserializationManager* dsm, char const* buf) { auto kv_map_ptr = mutils::from_bytes<std::map<KT,VT>>(dsm,buf); auto update_version_ptr = mutils::from_bytes<persistent::version_t>(dsm,buf+mutils::bytes_size(*kv_map_ptr)); auto volatile_cascade_store_ptr = std::make_unique<VolatileCascadeStore>(std::move(*kv_map_ptr), *update_version_ptr, dsm->registered<CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>>()):nullptr, dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr); return volatile_cascade_store_ptr; } template<typename KT, typename VT, KT* IK, VT* IV> VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore( CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): update_version(persistent::INVALID_VERSION), cascade_watcher_ptr(cw), cascade_context_ptr(cc) { debug_enter_func(); debug_leave_func(); } template<typename KT, typename VT, KT* IK, VT* IV> VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore( const std::map<KT,VT>& _kvm, persistent::version_t _uv, CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): kv_map(_kvm), update_version(_uv), cascade_watcher_ptr(cw), cascade_context_ptr(cc) { debug_enter_func_with_args("copy to kv_map, size={}",kv_map.size()); debug_leave_func(); } template<typename KT, typename VT, KT* IK, VT* IV> VolatileCascadeStore<KT,VT,IK,IV>::VolatileCascadeStore( std::map<KT,VT>&& _kvm, persistent::version_t _uv, CriticalDataPathObserver<VolatileCascadeStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): kv_map(std::move(_kvm)), update_version(_uv), cascade_watcher_ptr(cw), cascade_context_ptr(cc) { debug_enter_func_with_args("move to kv_map, size={}",kv_map.size()); debug_leave_func(); } /////////////////////////////////////////////////////////////////////////////// // 2 - Persistent Cascade Store Implementation /////////////////////////////////////////////////////////////////////////////// template <typename KT, typename VT, KT* IK, VT* IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::set_data_len(const size_t& dlen) { assert(capacity >= dlen); this->len = dlen; } template <typename KT, typename VT, KT* IK, VT* IV> char* DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::data_ptr() { assert(buffer != nullptr); return buffer; } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::calibrate(const size_t& dlen) { size_t new_cap = dlen; if(this->capacity >= new_cap) { return; } // calculate new capacity int width = sizeof(size_t) << 3; int right_shift_bits = 1; new_cap--; while(right_shift_bits < width) { new_cap |= new_cap >> right_shift_bits; right_shift_bits = right_shift_bits << 1; } new_cap++; // resize this->buffer = (char*)realloc(buffer, new_cap); if(this->buffer == nullptr) { dbg_default_crit("{}:{} Failed to allocate delta buffer. errno={}", __FILE__, __LINE__, errno); throw derecho::derecho_exception("Failed to allocate delta buffer."); } else { this->capacity = new_cap; } } template <typename KT, typename VT, KT* IK, VT *IV> bool DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::is_empty() { return (this->len == 0); } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::clean() { this->len = 0; } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::_Delta::destroy() { if(this->capacity > 0) { free(this->buffer); } } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::initialize_delta() { delta.buffer = (char*)malloc(DEFAULT_DELTA_BUFFER_CAPACITY); if (delta.buffer == nullptr) { dbg_default_crit("{}:{} Failed to allocate delta buffer. errno={}", __FILE__, __LINE__, errno); throw derecho::derecho_exception("Failed to allocate delta buffer."); } delta.capacity = DEFAULT_DELTA_BUFFER_CAPACITY; delta.len = 0; } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::finalizeCurrentDelta(const persistent::DeltaFinalizer& df) { df(this->delta.buffer, this->delta.len); this->delta.clean(); } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::applyDelta(char const* const delta) { apply_ordered_put(*mutils::from_bytes<VT>(nullptr,delta)); mutils::deserialize_and_run(nullptr,delta,[this](const VT& value){ this->apply_ordered_put(value); }); } template <typename KT, typename VT, KT* IK, VT *IV> void DeltaCascadeStoreCore<KT,VT,IK,IV>::apply_ordered_put(const VT& value) { this->kv_map.erase(value.get_key_ref()); this->kv_map.emplace(value.get_key_ref(),value); } template <typename KT, typename VT, KT* IK, VT *IV> std::unique_ptr<DeltaCascadeStoreCore<KT,VT,IK,IV>> DeltaCascadeStoreCore<KT,VT,IK,IV>::create(mutils::DeserializationManager* dm) { if (dm != nullptr) { try { return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>(); } catch (...) { } } return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>(); } template <typename KT, typename VT, KT* IK, VT *IV> bool DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_put(const VT& value, persistent::version_t prev_ver) { // verify version MUST happen before updating it's previous versions (prev_ver,prev_ver_by_key). if constexpr (std::is_base_of<IVerifyPreviousVersion,VT>::value) { bool verify_result; if (kv_map.find(value.get_key_ref())!=this->kv_map.end()) { verify_result = value.verify_previous_version(prev_ver,this->kv_map.at(value.get_key_ref()).get_version()); } else { verify_result = value.verify_previous_version(prev_ver,persistent::INVALID_VERSION); } if (!verify_result) { // reject the package if verify failed. return false; } } if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) { persistent::version_t prev_ver_by_key = persistent::INVALID_VERSION; if (kv_map.find(value.get_key_ref()) != kv_map.end()) { prev_ver_by_key = kv_map.at(value.get_key_ref()).get_version(); } value.set_previous_version(prev_ver,prev_ver_by_key); } // create delta. assert(this->delta.is_empty()); this->delta.calibrate(mutils::bytes_size(value)); mutils::to_bytes(value,this->delta.data_ptr()); this->delta.set_data_len(mutils::bytes_size(value)); // apply_ordered_put apply_ordered_put(value); return true; } template <typename KT, typename VT, KT* IK, VT *IV> bool DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_remove(const VT& value, persistent::version_t prev_ver) { auto& key = value.get_key_ref(); // test if key exists if (kv_map.find(key) == kv_map.end()) { // skip it when no such key. return false; } else if (kv_map.at(key).is_null()) { // and skip the keys has been deleted already. return false; } if constexpr (std::is_base_of<IKeepPreviousVersion,VT>::value) { value.set_previous_version(prev_ver,kv_map.at(key).get_version()); } // create delta. assert(this->delta.is_empty()); this->delta.calibrate(mutils::bytes_size(value)); mutils::to_bytes(value,this->delta.data_ptr()); this->delta.set_data_len(mutils::bytes_size(value)); // apply_ordered_put apply_ordered_put(value); return true; } template <typename KT, typename VT, KT* IK, VT* IV> const VT DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_get(const KT& key) { if (kv_map.find(key) != kv_map.end()) { return kv_map.at(key); } else { return *IV; } } template <typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_list_keys() { std::vector<KT> key_list; for (auto& kv: kv_map) { key_list.push_back(kv.first); } return key_list; } template <typename KT, typename VT, KT* IK, VT* IV> uint64_t DeltaCascadeStoreCore<KT,VT,IK,IV>::ordered_get_size(const KT& key) { if (kv_map.find(key) != kv_map.end()) { return mutils::bytes_size(kv_map.at(key)); } else { return 0; } } template <typename KT, typename VT, KT* IK, VT* IV> DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore() { initialize_delta(); } template <typename KT, typename VT, KT* IK, VT* IV> DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore(const std::map<KT,VT>& _kv_map): kv_map(_kv_map) { initialize_delta(); } template <typename KT, typename VT, KT* IK, VT* IV> DeltaCascadeStoreCore<KT,VT,IK,IV>::DeltaCascadeStoreCore(std::map<KT,VT>&& _kv_map): kv_map(_kv_map) { initialize_delta(); } template<typename KT, typename VT, KT* IK, VT* IV> DeltaCascadeStoreCore<KT,VT,IK,IV>::~DeltaCascadeStoreCore() { if (this->delta.buffer != nullptr) { free(this->delta.buffer); } } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::put(const VT& value) const { debug_enter_func_with_args("value.get_key_ref()={}",value.get_key_ref()); derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_put)>(value); auto& replies = results.get(); std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0); // TODO: verfiy consistency ? for (auto& reply_pair : replies) { ret = reply_pair.second.get(); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret)); return ret; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::remove(const KT& key) const { debug_enter_func_with_args("key={}",key); derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_remove)>(key); auto& replies = results.get(); std::tuple<persistent::version_t,uint64_t> ret(CURRENT_VERSION,0); // TODO: verify consistency ? for (auto& reply_pair : replies) { ret = reply_pair.second.get(); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(ret),std::get<1>(ret)); return ret; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::get(const KT& key, const persistent::version_t& ver, bool exact) const { debug_enter_func_with_args("key={},ver=0x{:x}",key,ver); if (ver != CURRENT_VERSION) { debug_leave_func(); return persistent_core.template getDelta<VT>(ver, [&key,ver,exact,this](const VT& v){ if (key == v.get_key_ref()) { return v; } else { if (exact) { // return invalid object for EXACT search. return *IV; } else { // fall back to the slow path. auto versioned_state_ptr = persistent_core.get(ver); if (versioned_state_ptr->kv_map.find(key) != versioned_state_ptr->kv_map.end()) { return versioned_state_ptr->kv_map.at(key); } return *IV; } } }); } derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get)>(key); auto& replies = results.get(); // TODO: verify consistency ? // for (auto& reply_pair : replies) { // ret = reply_pair.second.get(); // } debug_leave_func(); return replies.begin()->second.get(); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::get_by_time(const KT& key, const uint64_t& ts_us) const { debug_enter_func_with_args("key={},ts_us={}",key,ts_us); const HLC hlc(ts_us,0ull); try { debug_leave_func(); uint64_t idx = persistent_core.getIndexAtTime({ts_us,0}); if (idx == persistent::INVALID_INDEX) { return *IV; } else { // Reconstructing the state is extremely slow!!! // TODO: get the version at time ts_us, and go back from there. auto versioned_state_ptr = persistent_core.get(hlc); if (versioned_state_ptr->kv_map.find(key) != versioned_state_ptr->kv_map.end()) { return versioned_state_ptr->kv_map.at(key); } return *IV; } } catch (const int64_t &ex) { dbg_default_warn("temporal query throws exception:0x{:x}. key={}, ts={}", ex, key, ts_us); } catch (...) { dbg_default_warn("temporal query throws unknown exception. key={}, ts={}", key, ts_us); } debug_leave_func(); return *IV; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::get_size(const KT& key, const persistent::version_t& ver, bool exact) const { debug_enter_func_with_args("key={},ver=0x{:x}",key,ver); if (ver != CURRENT_VERSION) { if (exact) { return persistent_core.template getDelta<VT>(ver,[](const VT& value){return mutils::bytes_size(value);}); } else { return mutils::bytes_size(persistent_core.get(ver)->kv_map.at(key)); } } derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_get_size)>(key); auto& replies = results.get(); // TODO: verify consistency ? // for (auto& reply_pair : replies) { // ret = reply_pair.second.get(); // } debug_leave_func(); return replies.begin()->second.get(); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::get_size_by_time(const KT& key, const uint64_t& ts_us) const { debug_enter_func_with_args("key={},ts_us={}",key,ts_us); const HLC hlc(ts_us,0ull); try { debug_leave_func(); return mutils::bytes_size(persistent_core.get(hlc)->kv_map.at(key)); } catch (const int64_t &ex) { dbg_default_warn("temporal query throws exception:0x{:x}. key={}, ts={}", ex, key, ts_us); } catch (...) { dbg_default_warn("temporal query throws unknown exception. key={}, ts={}", key, ts_us); } debug_leave_func(); return 0; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::list_keys(const persistent::version_t& ver) const { debug_enter_func_with_args("ver=0x{:x}.",ver); if (ver != CURRENT_VERSION) { std::vector<KT> key_list; auto kv_map = persistent_core.get(ver)->kv_map; for (auto& kv:kv_map) { key_list.push_back(kv.first); } debug_leave_func(); return key_list; } derecho::Replicated<PersistentCascadeStore>& subgroup_handle = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index); auto results = subgroup_handle.template ordered_send<RPC_NAME(ordered_list_keys)>(); auto& replies = results.get(); // TODO: verify consistency ? debug_leave_func(); return replies.begin()->second.get(); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::list_keys_by_time(const uint64_t& ts_us) const { debug_enter_func_with_args("ts_us={}",ts_us); const HLC hlc(ts_us,0ull); try { auto kv_map = persistent_core.get(hlc)->kv_map; std::vector<KT> key_list; for(auto& kv:kv_map) { key_list.push_back(kv.first); } debug_leave_func(); return key_list; } catch (const int64_t& ex) { dbg_default_warn("temporal query throws exception:0x{:x]. ts={}", ex, ts_us); } catch (...) { dbg_default_warn("temporal query throws unknown exception. ts={}", ts_us); } debug_leave_func(); return {}; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_put(const VT& value) { debug_enter_func_with_args("key={}",value.get_key_ref()); std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_next_version(); if constexpr (std::is_base_of<IKeepVersion,VT>::value) { value.set_version(std::get<0>(version_and_timestamp)); } if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) { value.set_timestamp(std::get<1>(version_and_timestamp)); } if (this->persistent_core->ordered_put(value,this->persistent_core.getLatestVersion()) == false) { // verification failed. S we return invalid versions. debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return {persistent::INVALID_VERSION,0}; } if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( // group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id this->subgroup_index, group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_shard_num(), value.get_key_ref(), value, cascade_context_ptr); } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return version_and_timestamp; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::tuple<persistent::version_t,uint64_t> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_remove(const KT& key) { debug_enter_func_with_args("key={}",key); std::tuple<persistent::version_t,uint64_t> version_and_timestamp = group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_next_version(); auto value = create_null_object_cb<KT,VT,IK,IV>(key); if constexpr (std::is_base_of<IKeepVersion,VT>::value) { value.set_version(std::get<0>(version_and_timestamp)); } if constexpr (std::is_base_of<IKeepTimestamp,VT>::value) { value.set_timestamp(std::get<1>(version_and_timestamp)); } if(this->persistent_core->ordered_remove(value,this->persistent_core.getLatestVersion())) { if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( // group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_subgroup_id(), // this is subgroup id this->subgroup_index, group->template get_subgroup<PersistentCascadeStore>(this->subgroup_index).get_shard_num(), key, value, cascade_context_ptr); } } debug_leave_func_with_value("version=0x{:x},timestamp={}",std::get<0>(version_and_timestamp), std::get<1>(version_and_timestamp)); return version_and_timestamp; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> const VT PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_get(const KT& key) { debug_enter_func_with_args("key={}",key); debug_leave_func(); return this->persistent_core->ordered_get(key); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> uint64_t PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_get_size(const KT& key) { debug_enter_func_with_args("key={}",key); debug_leave_func(); return this->persistent_core->ordered_get_size(key); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> void PersistentCascadeStore<KT,VT,IK,IV,ST>::trigger_put(const VT& value) const { debug_enter_func_with_args("key={}",value.get_key_ref()); if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( this->subgroup_index, group->template get_subgroup<PersistentCascadeStore<KT,VT,IK,IV,ST>>(this->subgroup_index).get_shard_num(), value.get_key_ref(), value, cascade_context_ptr, true); } debug_leave_func(); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::vector<KT> PersistentCascadeStore<KT,VT,IK,IV,ST>::ordered_list_keys() { debug_enter_func(); debug_leave_func(); return this->persistent_core->ordered_list_keys(); } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> std::unique_ptr<PersistentCascadeStore<KT,VT,IK,IV,ST>> PersistentCascadeStore<KT,VT,IK,IV,ST>::from_bytes(mutils::DeserializationManager* dsm, char const* buf) { auto persistent_core_ptr = mutils::from_bytes<persistent::Persistent<DeltaCascadeStoreCore<KT,VT,IK,IV>,ST>>(dsm,buf); auto persistent_cascade_store_ptr = std::make_unique<PersistentCascadeStore>(std::move(*persistent_core_ptr), dsm->registered<CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>>()):nullptr, dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr); return persistent_cascade_store_ptr; } template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> PersistentCascadeStore<KT,VT,IK,IV,ST>::PersistentCascadeStore( persistent::PersistentRegistry* pr, CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): persistent_core( [](){ return std::make_unique<DeltaCascadeStoreCore<KT,VT,IK,IV>>(); }, nullptr, pr), cascade_watcher_ptr(cw), cascade_context_ptr(cc) {} template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> PersistentCascadeStore<KT,VT,IK,IV,ST>::PersistentCascadeStore( persistent::Persistent<DeltaCascadeStoreCore<KT,VT,IK,IV>,ST>&& _persistent_core, CriticalDataPathObserver<PersistentCascadeStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): persistent_core(std::move(_persistent_core)), cascade_watcher_ptr(cw), cascade_context_ptr(cc) {} template<typename KT, typename VT, KT* IK, VT* IV, persistent::StorageType ST> PersistentCascadeStore<KT,VT,IK,IV,ST>::~PersistentCascadeStore() {} template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::put(const VT& value) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {persistent::INVALID_VERSION,0}; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::remove(const KT& key) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {persistent::INVALID_VERSION,0}; } template<typename KT, typename VT, KT* IK, VT* IV> const VT TriggerCascadeNoStore<KT,VT,IK,IV>::get(const KT& key, const persistent::version_t& ver, bool) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return *IV; } template<typename KT, typename VT, KT* IK, VT* IV> const VT TriggerCascadeNoStore<KT,VT,IK,IV>::get_by_time(const KT& key, const uint64_t& ts_us) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return *IV; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::list_keys(const persistent::version_t& ver) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::list_keys_by_time(const uint64_t& ts_us) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::get_size(const KT& key, const persistent::version_t& ver, bool) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return 0; } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::get_size_by_time(const KT& key, const uint64_t& ts_us) const { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return 0; } template<typename KT, typename VT, KT* IK, VT* IV> std::vector<KT> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_list_keys() { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_put(const VT& value) { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> std::tuple<persistent::version_t,uint64_t> TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_remove(const KT& key) { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return {}; } template<typename KT, typename VT, KT* IK, VT* IV> const VT TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_get(const KT& key) { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return *IV; } template<typename KT, typename VT, KT* IK, VT* IV> uint64_t TriggerCascadeNoStore<KT,VT,IK,IV>::ordered_get_size(const KT& key) { dbg_default_warn("Calling unsupported func:{}",__PRETTY_FUNCTION__); return 0; } template<typename KT, typename VT, KT* IK, VT* IV> void TriggerCascadeNoStore<KT,VT,IK,IV>::trigger_put(const VT& value) const { debug_enter_func_with_args("key={}",value.get_key_ref()); if (cascade_watcher_ptr) { (*cascade_watcher_ptr)( this->subgroup_index, group->template get_subgroup<TriggerCascadeNoStore<KT,VT,IK,IV>>(this->subgroup_index).get_shard_num(), value.get_key_ref(), value, cascade_context_ptr, true); } debug_leave_func(); } template<typename KT, typename VT, KT* IK, VT* IV> std::unique_ptr<TriggerCascadeNoStore<KT,VT,IK,IV>> TriggerCascadeNoStore<KT,VT,IK,IV>::from_bytes(mutils::DeserializationManager* dsm, char const* buf) { return std::make_unique<TriggerCascadeNoStore<KT,VT,IK,IV>>( dsm->registered<CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>>()?&(dsm->mgr<CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>>()):nullptr, dsm->registered<ICascadeContext>()?&(dsm->mgr<ICascadeContext>()):nullptr); } template<typename KT, typename VT, KT* IK, VT* IV> mutils::context_ptr<TriggerCascadeNoStore<KT,VT,IK,IV>> TriggerCascadeNoStore<KT,VT,IK,IV>::from_bytes_noalloc(mutils::DeserializationManager* dsm, char const* buf) { return mutils::context_ptr<TriggerCascadeNoStore>(from_bytes(dsm,buf)); } template<typename KT, typename VT, KT* IK, VT* IV> TriggerCascadeNoStore<KT,VT,IK,IV>::TriggerCascadeNoStore(CriticalDataPathObserver<TriggerCascadeNoStore<KT,VT,IK,IV>>* cw, ICascadeContext* cc): cascade_watcher_ptr(cw), cascade_context_ptr(cc) {} }//namespace cascade }//namespace derecho
43.564021
215
0.665225
Thompson-Liu
c49cffb82d3dd3f3c682c5b58a4d44a9bf7a4330
1,450
cpp
C++
codes/UVA/01001-01999/uva1327.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/01001-01999/uva1327.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/UVA/01001-01999/uva1327.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <vector> #include <stack> #include <algorithm> using namespace std; const int maxn = 4005; int N, pre[maxn], sccno[maxn], dfsclock, cntscc; vector<int> G[maxn]; stack<int> S; int dfs (int u) { int lowu = pre[u] = ++dfsclock; S.push(u); for (int i = 0; i < G[u].size(); i++) { int v = G[u][i]; if (!pre[v]) { int lowv = dfs(v); lowu = min(lowu, lowv); } else if (!sccno[v]) lowu = min(lowu, pre[v]); } if (lowu == pre[u]) { cntscc++; while (true) { int x = S.top(); S.pop(); sccno[x] = cntscc; if (x == u) break; } } return lowu; } void findSCC () { dfsclock = cntscc = 0; memset(pre, 0, sizeof(pre)); memset(sccno, 0, sizeof(sccno)); for (int i = 1; i <= 2*N; i++) if (!pre[i]) dfs(i); } int main () { while (scanf("%d", &N) == 1) { int t, x; for (int i = 1; i <= N; i++) { G[i].clear(); scanf("%d", &t); while (t--) { scanf("%d", &x); G[i].push_back(x + N); } } for (int i = 1; i <= N; i++) { scanf("%d", &x); G[x+N].clear(); G[x+N].push_back(i); } findSCC(); vector<int> ans; for (int i = 1; i <= N; i++) { ans.clear(); for (int j = 0; j < G[i].size(); j++) { if (sccno[i] == sccno[G[i][j]]) ans.push_back(G[i][j]-N); } printf("%lu", ans.size()); sort(ans.begin(), ans.end()); for (int j = 0; j < ans.size(); j++) printf(" %d", ans[j]); printf("\n"); } } return 0; }
17.682927
61
0.488966
JeraKrs
c49df0ee578b8acf93b362ebb177937ae76b8787
2,327
cpp
C++
Project6/proj6.cpp
nicky189/cs202
ecfb9b92e094bfa29102e586ffd615d719b45532
[ "MIT" ]
null
null
null
Project6/proj6.cpp
nicky189/cs202
ecfb9b92e094bfa29102e586ffd615d719b45532
[ "MIT" ]
null
null
null
Project6/proj6.cpp
nicky189/cs202
ecfb9b92e094bfa29102e586ffd615d719b45532
[ "MIT" ]
null
null
null
/** * @brief CS-202 Project 6 Test Driver * @Author Christos Papachristos (cpapachristos@unr.edu) * @date March, 2019 * * This file is a test driver for the Polymorphic classes prescribed in Project 6 of CS-202 */ #include <iostream> #include "Car.h" using namespace std; int main(){ cout << "\n" << "////////////////////////////////\n" << "///// Constructor Tests /////\n" << "////////////////////////////////" << endl; cout << endl << "Testing Derived Default ctor" << endl; Car c1; cout << endl << "Testing Derived Parametrized ctor" << endl; float lla_rno[3] = {39.54, 119.82, 4500.0}; Car c_rno(lla_rno); cout << endl << "Testing Derived Copy ctor" << endl; Car c_cpy( c_rno ); cout << endl << "Testing Derived Assignment operator" << endl; c1 = c_cpy; cout << "\n" << "/////////////////////////////////\n" << "///// Polymorphism Tests /////\n" << "/////////////////////////////////" << endl; cout << endl << "Testing VIRTUAL Move Function for DERIVED Class Objects" << endl; float lla_new[3] = {37.77, 122.42, 52.0}; c1.Move( lla_new ); cout << endl << "Testing Insertion operator<< Overload for BASE Class Objects" << endl; cout << c_rno << endl; // Just setting some distinct values to our objects again here float lla_ny[3] = {40.71, 74.00, 10.0}; c1.SetLLA( lla_ny ); float lla_la[3] = {34.05, 118.24, 71.01}; c_cpy.SetLLA( lla_la ); cout << "\n" << "///////////////////////////////////////////////////\n" << "///// Polymorphic Base Class Pointer Tests /////\n" << "///////////////////////////////////////////////////" << endl; Vehicle* vehicles_array[3]; vehicles_array[0] = &c1; vehicles_array[1] = &c_rno; vehicles_array[2] = &c_cpy; cout << endl << "Testing VIRTUAL Move Function on Base Class Pointers" << endl; for (int i=0; i<3; ++i){ vehicles_array[i]->Move( lla_new ); } cout << endl << "Testing Insertion operator<< Overload for Base Class Pointers" << endl; for (int i=0; i<3; ++i){ cout << *vehicles_array[i] << endl; } cout << "\n" << "////////////////////////////\n" << "///// Tests Done /////\n" << "////////////////////////////" << endl; return 0; }
28.036145
91
0.486034
nicky189
c49ee7391c8c55d8f56a4d693d874ecd89a8aec6
140
hpp
C++
BOB/Source/Library/TableHeaders.hpp
Null-LLC/Echo
07165b71332fed8e4dd641bd0bdddb38534abdf0
[ "MIT" ]
7
2021-08-15T01:35:56.000Z
2022-01-11T10:34:35.000Z
BOB/Source/Library/TableHeaders.hpp
Null-LLC/Echo
07165b71332fed8e4dd641bd0bdddb38534abdf0
[ "MIT" ]
1
2021-11-06T07:20:31.000Z
2021-11-07T10:13:46.000Z
BOB/Source/Library/TableHeaders.hpp
Null-LLC/Echo
07165b71332fed8e4dd641bd0bdddb38534abdf0
[ "MIT" ]
1
2021-12-07T07:04:47.000Z
2021-12-07T07:04:47.000Z
#ifndef TableHeaders struct TableHeaders { unsigned long long Signature; unsigned int Revision, HeaderSize, CRC32, Reserved; }; #endif
17.5
53
0.771429
Null-LLC
c49f61f78464023a16e0c2537f722ef596092efd
2,343
cpp
C++
test/EdgeTest.cpp
fmidev/smartmet-library-tron
1c92b6b474bd079cb58158fed916bd5af302f6a3
[ "MIT" ]
null
null
null
test/EdgeTest.cpp
fmidev/smartmet-library-tron
1c92b6b474bd079cb58158fed916bd5af302f6a3
[ "MIT" ]
null
null
null
test/EdgeTest.cpp
fmidev/smartmet-library-tron
1c92b6b474bd079cb58158fed916bd5af302f6a3
[ "MIT" ]
null
null
null
// ====================================================================== /*! * \file * \brief Regression tests for Tron::Edge */ // ====================================================================== #include "Edge.h" #include "Traits.h" #include <regression/tframe.h> #include <string> using namespace std; //! Protection against conflicts with global functions namespace EdgeTest { // ---------------------------------------------------------------------- /*! * \brief Test comparisons */ // ---------------------------------------------------------------------- void comparisons() { typedef Tron::Traits<int, int> MyTraits; Tron::Edge<MyTraits> e1(0, 0, 0, 1); Tron::Edge<MyTraits> e2(0, 0, 1, 0); Tron::Edge<MyTraits> e3(0, 1, 1, 1); Tron::Edge<MyTraits> e4(1, 0, 1, 1); Tron::Edge<MyTraits> g1(0, 1, 0, 0); Tron::Edge<MyTraits> g2(1, 0, 0, 0); Tron::Edge<MyTraits> g3(1, 1, 0, 1); Tron::Edge<MyTraits> g4(1, 1, 1, 0); if (!(e1 == g1)) TEST_FAILED("e1 == g1 failed"); if (!(e2 == g2)) TEST_FAILED("e2 == g2 failed"); if (!(e3 == g3)) TEST_FAILED("e3 == g3 failed"); if (!(e4 == g4)) TEST_FAILED("e4 == g4 failed"); if (!(e1 < e2)) TEST_FAILED("e1 < e2 failed"); if (!(e1 < e3)) TEST_FAILED("e1 < e3 failed"); if (!(e1 < e4)) TEST_FAILED("e1 < e4 failed"); if (!(e2 < e3)) TEST_FAILED("e2 < e3 failed"); if (!(e2 < e4)) TEST_FAILED("e2 < e4 failed"); if (!(e3 < e4)) TEST_FAILED("e3 < e4 failed"); if (e2 < e1) TEST_FAILED("e2 < e1 failed"); if (e3 < e1) TEST_FAILED("e3 < e1 failed"); if (e4 < e1) TEST_FAILED("e4 < e1 failed"); if (e3 < e2) TEST_FAILED("e3 < e2 failed"); if (e4 < e2) TEST_FAILED("e4 < e2 failed"); if (e4 < e3) TEST_FAILED("e4 < e3 failed"); TEST_PASSED(); } // ---------------------------------------------------------------------- /*! * The actual test suite */ // ---------------------------------------------------------------------- class tests : public tframe::tests { virtual const char* error_message_prefix() const { return "\n\t"; } void test(void) { TEST(comparisons); } }; } // namespace EdgeTest //! The main program int main(void) { using namespace std; cout << endl << "Edge" << endl << "====" << endl; EdgeTest::tests t; return t.run(); } // ======================================================================
27.892857
73
0.463508
fmidev
c4a02034615d3b94732c5150a6f1d534609ec0bb
637
cpp
C++
stlport/test/regression/list2.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
86
2018-05-24T12:03:44.000Z
2022-03-13T03:01:25.000Z
stlport/test/regression/list2.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
1
2019-05-30T01:38:40.000Z
2019-10-26T07:15:01.000Z
stlport/test/regression/list2.cpp
masscry/dmc
c7638f7c524a65bc2af0876c76621d8a11da42bb
[ "BSL-1.0" ]
14
2018-07-16T08:29:12.000Z
2021-08-23T06:21:30.000Z
// STLport regression testsuite component. // To compile as a separate example, please #define MAIN. #include <iostream> #include <list> #ifdef MAIN #define list2_test main #endif #if !defined (STLPORT) || defined(__STL_USE_NAMESPACES) using namespace std; #endif int list2_test(int, char**) { cout<<"Results of list2_test:"<<endl; int array1 [] = { 1, 16 }; int array2 [] = { 4, 9 }; list<int> l1(array1, array1 + 2); list<int> l2(array2, array2 + 2); std::list<int>::iterator i = l1.begin(); i++; l1.splice(i, l2, l2.begin(), l2.end()); i = l1.begin(); while(i != l1.end()) cout << *i++ << endl; return 0; }
21.233333
57
0.631083
masscry
c4a046f30eec2de42139330bfb9e93a49a5bc728
3,102
hpp
C++
sources/include/nx/nx/callbacks.hpp
chybz/nx
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
[ "MIT" ]
4
2016-11-07T09:50:03.000Z
2018-09-25T09:10:06.000Z
sources/include/nx/nx/callbacks.hpp
chybz/nx
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
[ "MIT" ]
null
null
null
sources/include/nx/nx/callbacks.hpp
chybz/nx
62d5a318eeda60ffb1b3ed093bc9df655f3371d2
[ "MIT" ]
3
2016-11-07T09:50:05.000Z
2022-01-18T16:51:45.000Z
#ifndef __NX_CALLBACKS_H__ #define __NX_CALLBACKS_H__ #include <functional> #include <tuple> #include <type_traits> #include <nx/tuple_utils.hpp> #include <nx/utils.hpp> namespace nx { struct callback_tag {}; template <typename Tag, typename... Args> class callback { public: static_assert( std::is_base_of<callback_tag, Tag>::value, "invalid callback tag" ); using this_type = callback<Tag, Args...>; using tag_type = Tag; using type = std::function<void(Args...)>; operator bool() const { return (bool) cb_; } operator type() const { return cb_; } bool operator()(Args... args) { bool called = false; if (cb_) { cb_(std::forward<Args>(args)...); called = true; } return called; } void reset() { cb_ = nullptr; } this_type& operator=(const type& cb) { cb_ = cb; return *this; } this_type& operator=(type&& cb) { cb_ = std::move(cb); return *this; } private: type cb_; }; template <typename... Callbacks> class callbacks { public: using callbacks_type = std::tuple<Callbacks...>; using tags_type = std::tuple<typename Callbacks::tag_type...>; void clear() { nx::for_each( cbs_, [](std::size_t pos, auto& cb) { cb.reset(); } ); } template <typename Tag> auto& get(const Tag& tag) { return get<Tag>(cbs_); } template <typename Tag> bool has(const Tag& tag) const { return (bool) get<Tag>(cbs_); } template <typename Tag, typename... Args> bool call(Args&&... args) { return get<Tag>(cbs_)(std::forward<Args>(args)...); } private: template <typename Tag, typename Functions> typename nx::tuple_element< Tag, Functions, tags_type >::type& get(Functions& functions) { using function_type = typename nx::tuple_element< Tag, Functions, tags_type >::type; return std::get<function_type>(functions); } template <typename Tag, typename Functions> const typename nx::tuple_element< Tag, Functions, tags_type >::type& get(const Functions& functions) const { using function_type = typename nx::tuple_element< Tag, Functions, tags_type >::type; return std::get<function_type>(functions); } callbacks_type cbs_; }; template <typename Tag, typename Callbacks> struct callback_element { using callbacks_type = typename Callbacks::callbacks_type; using tags_type = typename Callbacks::tags_type; using type = typename nx::tuple_element< Tag, callbacks_type, tags_type >::type; }; template <typename Tag, typename Class> struct callback_signature { using type = typename callback_element< Tag, typename Class::callbacks >::type::type; }; } // namespace nx #endif // __NX_CALLBACKS_H__
19.267081
66
0.579948
chybz
c4a798816987d1409158caa1dd12fa5977afb3e9
3,506
hpp
C++
search/retrieval.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
search/retrieval.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
search/retrieval.hpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "search/cbv.hpp" #include "search/feature_offset_match.hpp" #include "search/query_params.hpp" #include "platform/mwm_traits.hpp" #include "coding/reader.hpp" #include "geometry/rect2d.hpp" #include "base/cancellable.hpp" #include "base/checked_cast.hpp" #include "base/dfa_helpers.hpp" #include "base/levenshtein_dfa.hpp" #include <cstdint> #include <functional> #include <memory> #include <utility> class MwmValue; namespace search { class MwmContext; class TokenSlice; class Retrieval { public: template<typename Value> using TrieRoot = trie::Iterator<ValueList<Value>>; using Features = search::CBV; struct ExtendedFeatures { ExtendedFeatures() = default; ExtendedFeatures(ExtendedFeatures const &) = default; ExtendedFeatures(ExtendedFeatures &&) = default; explicit ExtendedFeatures(Features const & cbv) : m_features(cbv), m_exactMatchingFeatures(cbv) { } ExtendedFeatures(Features && features, Features && exactMatchingFeatures) : m_features(std::move(features)), m_exactMatchingFeatures(std::move(exactMatchingFeatures)) { } ExtendedFeatures & operator=(ExtendedFeatures const &) = default; ExtendedFeatures & operator=(ExtendedFeatures &&) = default; ExtendedFeatures Intersect(ExtendedFeatures const & rhs) const { ExtendedFeatures result; result.m_features = m_features.Intersect(rhs.m_features); result.m_exactMatchingFeatures = m_exactMatchingFeatures.Intersect(rhs.m_exactMatchingFeatures); return result; } ExtendedFeatures Intersect(Features const & cbv) const { ExtendedFeatures result; result.m_features = m_features.Intersect(cbv); result.m_exactMatchingFeatures = m_exactMatchingFeatures.Intersect(cbv); return result; } void SetFull() { m_features.SetFull(); m_exactMatchingFeatures.SetFull(); } void ForEach(std::function<void(uint32_t, bool)> const & f) const { m_features.ForEach([&](uint64_t id) { f(base::asserted_cast<uint32_t>(id), m_exactMatchingFeatures.HasBit(id)); }); } Features m_features; Features m_exactMatchingFeatures; }; Retrieval(MwmContext const & context, base::Cancellable const & cancellable); // Following functions retrieve all features matching to |request| from the search index. ExtendedFeatures RetrieveAddressFeatures( SearchTrieRequest<strings::UniStringDFA> const & request) const; ExtendedFeatures RetrieveAddressFeatures( SearchTrieRequest<strings::PrefixDFAModifier<strings::UniStringDFA>> const & request) const; ExtendedFeatures RetrieveAddressFeatures( SearchTrieRequest<strings::LevenshteinDFA> const & request) const; ExtendedFeatures RetrieveAddressFeatures( SearchTrieRequest<strings::PrefixDFAModifier<strings::LevenshteinDFA>> const & request) const; // Retrieves all postcodes matching to |slice| from the search index. Features RetrievePostcodeFeatures(TokenSlice const & slice) const; // Retrieves all features belonging to |rect| from the geometry index. Features RetrieveGeometryFeatures(m2::RectD const & rect, int scale) const; private: template <template <typename> class R, typename... Args> ExtendedFeatures Retrieve(Args &&... args) const; MwmContext const & m_context; base::Cancellable const & m_cancellable; ModelReaderPtr m_reader; std::unique_ptr<TrieRoot<Uint64IndexValue>> m_root; }; } // namespace search
28.975207
100
0.737022
smartyw
c4a809ff43a83ca6ff0cad8a8a181958f1e92633
3,332
hpp
C++
include/geographic_conversion/fix_converter_component.hpp
OUXT-Polaris/geographic_conversion
206ceef8bcec86534a88dd42aa47bd5b53f93665
[ "Apache-2.0" ]
null
null
null
include/geographic_conversion/fix_converter_component.hpp
OUXT-Polaris/geographic_conversion
206ceef8bcec86534a88dd42aa47bd5b53f93665
[ "Apache-2.0" ]
2
2019-05-26T23:38:02.000Z
2019-05-27T00:40:56.000Z
include/geographic_conversion/fix_converter_component.hpp
OUXT-Polaris/geographic_conversion
206ceef8bcec86534a88dd42aa47bd5b53f93665
[ "Apache-2.0" ]
null
null
null
// Copyright (c) 2019 OUXT Polaris // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_ #define GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_ // Headers in ROS #include <geometry_msgs/msg/point_stamped.hpp> #include <rclcpp/rclcpp.hpp> #include <sensor_msgs/msg/nav_sat_fix.hpp> #include <geodesy/utm.h> #include <ctype.h> // Headers in STL #include <string> #include <limits> #include <cmath> #if __cplusplus extern "C" { #endif // The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from // demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos #if defined _WIN32 || defined __CYGWIN__ #ifdef __GNUC__ #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __attribute__((dllexport)) #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT __attribute__((dllimport)) #else #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __declspec(dllexport) #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT __declspec(dllimport) #endif #ifdef GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_BUILDING_DLL #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC \ GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT #else #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC \ GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT #endif #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC_TYPE \ GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL #else #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_EXPORT __attribute__((visibility("default"))) #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_IMPORT #if __GNUC__ >= 4 #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC __attribute__((visibility("default"))) #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL __attribute__((visibility("hidden"))) #else #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_LOCAL #endif #define GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC_TYPE #endif #if __cplusplus } // extern "C" #endif namespace geographic_conversion { class FixConverterComponent : public rclcpp::Node { public: GEOGRAPHIC_CONVERSION_FIX_CONVERTER_COMPONENT_PUBLIC explicit FixConverterComponent(const rclcpp::NodeOptions & options); private: std::string map_frame_; std::string input_topic_; rclcpp::Publisher<geometry_msgs::msg::PointStamped>::SharedPtr point_pub_; rclcpp::Subscription<sensor_msgs::msg::NavSatFix>::SharedPtr fix_sub_; void fixCallback(const sensor_msgs::msg::NavSatFix::SharedPtr msg); }; } // namespace geographic_conversion #endif // GEOGRAPHIC_CONVERSION__FIX_CONVERTER_COMPONENT_HPP_
37.438202
99
0.836735
OUXT-Polaris
c4aab79d26c08d8f143aca03054b15ffd9b02d21
17,573
cxx
C++
main/sc/source/ui/miscdlgs/solveroptions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/sc/source/ui/miscdlgs/solveroptions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/sc/source/ui/miscdlgs/solveroptions.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sc.hxx" //------------------------------------------------------------------ #include "solveroptions.hxx" #include "solveroptions.hrc" #include "scresid.hxx" #include "global.hxx" #include "miscuno.hxx" #include "solverutil.hxx" #include <rtl/math.hxx> #include <vcl/msgbox.hxx> #include <unotools/collatorwrapper.hxx> #include <unotools/localedatawrapper.hxx> #include <algorithm> #include <com/sun/star/sheet/Solver.hpp> #include <com/sun/star/sheet/XSolverDescription.hpp> #include <com/sun/star/beans/PropertyValue.hpp> #include <com/sun/star/beans/XPropertySet.hpp> using namespace com::sun::star; //================================================================== /// Helper for sorting properties struct ScSolverOptionsEntry { sal_Int32 nPosition; rtl::OUString aDescription; ScSolverOptionsEntry() : nPosition(0) {} bool operator< (const ScSolverOptionsEntry& rOther) const { return ( ScGlobal::GetCollator()->compareString( aDescription, rOther.aDescription ) == COMPARE_LESS ); } }; //------------------------------------------------------------------ class ScSolverOptionsString : public SvLBoxString { bool mbIsDouble; double mfDoubleValue; sal_Int32 mnIntValue; public: ScSolverOptionsString( SvLBoxEntry* pEntry, sal_uInt16 nFlags, const String& rStr ) : SvLBoxString( pEntry, nFlags, rStr ), mbIsDouble( false ), mfDoubleValue( 0.0 ), mnIntValue( 0 ) {} bool IsDouble() const { return mbIsDouble; } double GetDoubleValue() const { return mfDoubleValue; } sal_Int32 GetIntValue() const { return mnIntValue; } void SetDoubleValue( double fNew ) { mbIsDouble = true; mfDoubleValue = fNew; } void SetIntValue( sal_Int32 nNew ) { mbIsDouble = false; mnIntValue = nNew; } // MT: Commented out SV_ITEM_ID_EXTENDRLBOXSTRING and GetExtendText() in svlbitem.hxx - needed? // virtual USHORT IsA() {return SV_ITEM_ID_EXTENDRLBOXSTRING;} // virtual XubString GetExtendText() const; virtual void Paint( const Point& rPos, SvLBox& rDev, sal_uInt16 nFlags, SvLBoxEntry* pEntry ); }; // MT: Commented out SV_ITEM_ID_EXTENDRLBOXSTRING and GetExtendText() in svlbitem.hxx - needed? /* XubString ScSolverOptionsString::GetExtendText() const { String aNormalStr( GetText() ); aNormalStr.Append( (sal_Unicode) ':' ); String sTxt( ' ' ); if ( mbIsDouble ) sTxt += (String)rtl::math::doubleToUString( mfDoubleValue, rtl_math_StringFormat_Automatic, rtl_math_DecimalPlaces_Max, ScGlobal::GetpLocaleData()->getNumDecimalSep().GetChar(0), true ); else sTxt += String::CreateFromInt32( mnIntValue ); aNormalStr.Append(sTxt); return aNormalStr; } */ void ScSolverOptionsString::Paint( const Point& rPos, SvLBox& rDev, sal_uInt16, SvLBoxEntry* /* pEntry */ ) { //! move position? (SvxLinguTabPage: aPos.X() += 20) String aNormalStr( GetText() ); aNormalStr.Append( (sal_Unicode) ':' ); rDev.DrawText( rPos, aNormalStr ); Point aNewPos( rPos ); aNewPos.X() += rDev.GetTextWidth( aNormalStr ); Font aOldFont( rDev.GetFont() ); Font aFont( aOldFont ); aFont.SetWeight( WEIGHT_BOLD ); String sTxt( ' ' ); if ( mbIsDouble ) sTxt += (String)rtl::math::doubleToUString( mfDoubleValue, rtl_math_StringFormat_Automatic, rtl_math_DecimalPlaces_Max, ScGlobal::GetpLocaleData()->getNumDecimalSep().GetChar(0), true ); else sTxt += String::CreateFromInt32( mnIntValue ); rDev.SetFont( aFont ); rDev.DrawText( aNewPos, sTxt ); rDev.SetFont( aOldFont ); } //------------------------------------------------------------------ ScSolverOptionsDialog::ScSolverOptionsDialog( Window* pParent, const uno::Sequence<rtl::OUString>& rImplNames, const uno::Sequence<rtl::OUString>& rDescriptions, const String& rEngine, const uno::Sequence<beans::PropertyValue>& rProperties ) : ModalDialog( pParent, ScResId( RID_SCDLG_SOLVEROPTIONS ) ), maFtEngine ( this, ScResId( FT_ENGINE ) ), maLbEngine ( this, ScResId( LB_ENGINE ) ), maFtSettings ( this, ScResId( FT_SETTINGS ) ), maLbSettings ( this, ScResId( LB_SETTINGS ) ), maBtnEdit ( this, ScResId( BTN_EDIT ) ), maFlButtons ( this, ScResId( FL_BUTTONS ) ), maBtnHelp ( this, ScResId( BTN_HELP ) ), maBtnOk ( this, ScResId( BTN_OK ) ), maBtnCancel ( this, ScResId( BTN_CANCEL ) ), mpCheckButtonData( NULL ), maImplNames( rImplNames ), maDescriptions( rDescriptions ), maEngine( rEngine ), maProperties( rProperties ) { maLbEngine.SetSelectHdl( LINK( this, ScSolverOptionsDialog, EngineSelectHdl ) ); maBtnEdit.SetClickHdl( LINK( this, ScSolverOptionsDialog, ButtonHdl ) ); maLbSettings.SetStyle( maLbSettings.GetStyle()|WB_CLIPCHILDREN|WB_FORCE_MAKEVISIBLE ); maLbSettings.SetHelpId( HID_SC_SOLVEROPTIONS_LB ); maLbSettings.SetHighlightRange(); maLbSettings.SetSelectHdl( LINK( this, ScSolverOptionsDialog, SettingsSelHdl ) ); maLbSettings.SetDoubleClickHdl( LINK( this, ScSolverOptionsDialog, SettingsDoubleClickHdl ) ); sal_Int32 nSelect = -1; sal_Int32 nImplCount = maImplNames.getLength(); for (sal_Int32 nImpl=0; nImpl<nImplCount; ++nImpl) { String aImplName( maImplNames[nImpl] ); String aDescription( maDescriptions[nImpl] ); // user-visible descriptions in list box maLbEngine.InsertEntry( aDescription ); if ( aImplName == maEngine ) nSelect = nImpl; } if ( nSelect < 0 ) // no (valid) engine given { if ( nImplCount > 0 ) { maEngine = maImplNames[0]; // use first implementation nSelect = 0; } else maEngine.Erase(); maProperties.realloc(0); // don't use options from different engine } if ( nSelect >= 0 ) // select in list box maLbEngine.SelectEntryPos( static_cast<sal_uInt16>(nSelect) ); if ( !maProperties.getLength() ) ReadFromComponent(); // fill maProperties from component (using maEngine) FillListBox(); // using maProperties FreeResource(); } ScSolverOptionsDialog::~ScSolverOptionsDialog() { delete mpCheckButtonData; } const String& ScSolverOptionsDialog::GetEngine() const { return maEngine; // already updated in selection handler } const uno::Sequence<beans::PropertyValue>& ScSolverOptionsDialog::GetProperties() { // update maProperties from list box content // order of entries in list box and maProperties is the same sal_Int32 nEntryCount = maProperties.getLength(); SvLBoxTreeList* pModel = maLbSettings.GetModel(); if ( nEntryCount == (sal_Int32)pModel->GetEntryCount() ) { for (sal_Int32 nEntryPos=0; nEntryPos<nEntryCount; ++nEntryPos) { uno::Any& rValue = maProperties[nEntryPos].Value; SvLBoxEntry* pEntry = pModel->GetEntry(nEntryPos); bool bHasData = false; sal_uInt16 nItemCount = pEntry->ItemCount(); for (sal_uInt16 nItemPos=0; nItemPos<nItemCount && !bHasData; ++nItemPos) { SvLBoxItem* pItem = pEntry->GetItem( nItemPos ); ScSolverOptionsString* pStringItem = dynamic_cast<ScSolverOptionsString*>(pItem); if ( pStringItem ) { if ( pStringItem->IsDouble() ) rValue <<= pStringItem->GetDoubleValue(); else rValue <<= pStringItem->GetIntValue(); bHasData = true; } } if ( !bHasData ) ScUnoHelpFunctions::SetBoolInAny( rValue, maLbSettings.GetCheckButtonState( pEntry ) == SV_BUTTON_CHECKED ); } } else { DBG_ERRORFILE( "wrong count" ); } return maProperties; } void ScSolverOptionsDialog::FillListBox() { // get property descriptions, sort by them uno::Reference<sheet::XSolverDescription> xDesc( ScSolverUtil::GetSolver( maEngine ), uno::UNO_QUERY ); sal_Int32 nCount = maProperties.getLength(); std::vector<ScSolverOptionsEntry> aDescriptions( nCount ); for (sal_Int32 nPos=0; nPos<nCount; nPos++) { rtl::OUString aPropName( maProperties[nPos].Name ); rtl::OUString aVisName; if ( xDesc.is() ) aVisName = xDesc->getPropertyDescription( aPropName ); if ( !aVisName.getLength() ) aVisName = aPropName; aDescriptions[nPos].nPosition = nPos; aDescriptions[nPos].aDescription = aVisName; } std::sort( aDescriptions.begin(), aDescriptions.end() ); // also update maProperties to the order of descriptions uno::Sequence<beans::PropertyValue> aNewSeq; aNewSeq.realloc( nCount ); for (sal_Int32 nPos=0; nPos<nCount; nPos++) aNewSeq[nPos] = maProperties[ aDescriptions[nPos].nPosition ]; maProperties = aNewSeq; // fill the list box maLbSettings.SetUpdateMode(sal_False); maLbSettings.Clear(); String sEmpty; if (!mpCheckButtonData) mpCheckButtonData = new SvLBoxButtonData( &maLbSettings ); SvLBoxTreeList* pModel = maLbSettings.GetModel(); SvLBoxEntry* pEntry = NULL; for (sal_Int32 nPos=0; nPos<nCount; nPos++) { rtl::OUString aVisName = aDescriptions[nPos].aDescription; uno::Any aValue = maProperties[nPos].Value; uno::TypeClass eClass = aValue.getValueTypeClass(); if ( eClass == uno::TypeClass_BOOLEAN ) { // check box entry pEntry = new SvLBoxEntry; SvLBoxButton* pButton = new SvLBoxButton( pEntry, SvLBoxButtonKind_enabledCheckbox, 0, mpCheckButtonData ); if ( ScUnoHelpFunctions::GetBoolFromAny( aValue ) ) pButton->SetStateChecked(); else pButton->SetStateUnchecked(); pEntry->AddItem( pButton ); pEntry->AddItem( new SvLBoxContextBmp( pEntry, 0, Image(), Image(), 0 ) ); pEntry->AddItem( new SvLBoxString( pEntry, 0, aVisName ) ); } else { // value entry pEntry = new SvLBoxEntry; pEntry->AddItem( new SvLBoxString( pEntry, 0, sEmpty ) ); // empty column pEntry->AddItem( new SvLBoxContextBmp( pEntry, 0, Image(), Image(), 0 ) ); ScSolverOptionsString* pItem = new ScSolverOptionsString( pEntry, 0, aVisName ); if ( eClass == uno::TypeClass_DOUBLE ) { double fDoubleValue = 0.0; if ( aValue >>= fDoubleValue ) pItem->SetDoubleValue( fDoubleValue ); } else { sal_Int32 nIntValue = 0; if ( aValue >>= nIntValue ) pItem->SetIntValue( nIntValue ); } pEntry->AddItem( pItem ); } pModel->Insert( pEntry ); } maLbSettings.SetUpdateMode(sal_True); } void ScSolverOptionsDialog::ReadFromComponent() { maProperties = ScSolverUtil::GetDefaults( maEngine ); } void ScSolverOptionsDialog::EditOption() { SvLBoxEntry* pEntry = maLbSettings.GetCurEntry(); if (pEntry) { sal_uInt16 nItemCount = pEntry->ItemCount(); for (sal_uInt16 nPos=0; nPos<nItemCount; ++nPos) { SvLBoxItem* pItem = pEntry->GetItem( nPos ); ScSolverOptionsString* pStringItem = dynamic_cast<ScSolverOptionsString*>(pItem); if ( pStringItem ) { if ( pStringItem->IsDouble() ) { ScSolverValueDialog aValDialog( this ); aValDialog.SetOptionName( pStringItem->GetText() ); aValDialog.SetValue( pStringItem->GetDoubleValue() ); if ( aValDialog.Execute() == RET_OK ) { pStringItem->SetDoubleValue( aValDialog.GetValue() ); maLbSettings.InvalidateEntry( pEntry ); } } else { ScSolverIntegerDialog aIntDialog( this ); aIntDialog.SetOptionName( pStringItem->GetText() ); aIntDialog.SetValue( pStringItem->GetIntValue() ); if ( aIntDialog.Execute() == RET_OK ) { pStringItem->SetIntValue( aIntDialog.GetValue() ); maLbSettings.InvalidateEntry( pEntry ); } } } } } } IMPL_LINK( ScSolverOptionsDialog, ButtonHdl, PushButton*, pBtn ) { if ( pBtn == &maBtnEdit ) EditOption(); return 0; } IMPL_LINK( ScSolverOptionsDialog, SettingsDoubleClickHdl, SvTreeListBox*, EMPTYARG ) { EditOption(); return 0; } IMPL_LINK( ScSolverOptionsDialog, EngineSelectHdl, ListBox*, EMPTYARG ) { sal_uInt16 nSelectPos = maLbEngine.GetSelectEntryPos(); if ( nSelectPos < maImplNames.getLength() ) { String aNewEngine( maImplNames[nSelectPos] ); if ( aNewEngine != maEngine ) { maEngine = aNewEngine; ReadFromComponent(); // fill maProperties from component (using maEngine) FillListBox(); // using maProperties } } return 0; } IMPL_LINK( ScSolverOptionsDialog, SettingsSelHdl, SvxCheckListBox*, EMPTYARG ) { sal_Bool bCheckbox = sal_False; SvLBoxEntry* pEntry = maLbSettings.GetCurEntry(); if (pEntry) { SvLBoxItem* pItem = pEntry->GetFirstItem(SV_ITEM_ID_LBOXBUTTON); if ( pItem && pItem->IsA() == SV_ITEM_ID_LBOXBUTTON ) bCheckbox = sal_True; } maBtnEdit.Enable( !bCheckbox ); return 0; } //------------------------------------------------------------------ ScSolverIntegerDialog::ScSolverIntegerDialog( Window * pParent ) : ModalDialog( pParent, ScResId( RID_SCDLG_SOLVER_INTEGER ) ), maFtName ( this, ScResId( FT_OPTIONNAME ) ), maNfValue ( this, ScResId( NF_VALUE ) ), maFlButtons ( this, ScResId( FL_BUTTONS ) ), maBtnOk ( this, ScResId( BTN_OK ) ), maBtnCancel ( this, ScResId( BTN_CANCEL ) ) { FreeResource(); } ScSolverIntegerDialog::~ScSolverIntegerDialog() { } void ScSolverIntegerDialog::SetOptionName( const String& rName ) { maFtName.SetText( rName ); } void ScSolverIntegerDialog::SetValue( sal_Int32 nValue ) { maNfValue.SetValue( nValue ); } sal_Int32 ScSolverIntegerDialog::GetValue() const { sal_Int64 nValue = maNfValue.GetValue(); if ( nValue < SAL_MIN_INT32 ) return SAL_MIN_INT32; if ( nValue > SAL_MAX_INT32 ) return SAL_MAX_INT32; return (sal_Int32) nValue; } //------------------------------------------------------------------ ScSolverValueDialog::ScSolverValueDialog( Window * pParent ) : ModalDialog( pParent, ScResId( RID_SCDLG_SOLVER_DOUBLE ) ), maFtName ( this, ScResId( FT_OPTIONNAME ) ), maEdValue ( this, ScResId( ED_VALUE ) ), maFlButtons ( this, ScResId( FL_BUTTONS ) ), maBtnOk ( this, ScResId( BTN_OK ) ), maBtnCancel ( this, ScResId( BTN_CANCEL ) ) { FreeResource(); } ScSolverValueDialog::~ScSolverValueDialog() { } void ScSolverValueDialog::SetOptionName( const String& rName ) { maFtName.SetText( rName ); } void ScSolverValueDialog::SetValue( double fValue ) { maEdValue.SetText( rtl::math::doubleToUString( fValue, rtl_math_StringFormat_Automatic, rtl_math_DecimalPlaces_Max, ScGlobal::GetpLocaleData()->getNumDecimalSep().GetChar(0), true ) ); } double ScSolverValueDialog::GetValue() const { String aInput = maEdValue.GetText(); const LocaleDataWrapper* pLocaleData = ScGlobal::GetpLocaleData(); rtl_math_ConversionStatus eStatus = rtl_math_ConversionStatus_Ok; double fValue = rtl::math::stringToDouble( aInput, pLocaleData->getNumDecimalSep().GetChar(0), pLocaleData->getNumThousandSep().GetChar(0), &eStatus, NULL ); return fValue; }
34.524558
119
0.608092
Grosskopf
c4aad6070636472f8edc0b1631b7b570c07f3248
274
cpp
C++
src/test/tutorial_slow_v1.cpp
vadi2/nanobench
954a82064141537330ab1a6ab27f01b21878bfa8
[ "MIT" ]
706
2019-10-08T05:29:49.000Z
2022-03-31T06:49:24.000Z
src/test/tutorial_slow_v1.cpp
vadi2/nanobench
954a82064141537330ab1a6ab27f01b21878bfa8
[ "MIT" ]
55
2019-10-08T05:30:36.000Z
2022-03-30T16:06:41.000Z
src/test/tutorial_slow_v1.cpp
vadi2/nanobench
954a82064141537330ab1a6ab27f01b21878bfa8
[ "MIT" ]
34
2019-10-12T13:50:08.000Z
2022-03-29T15:01:21.000Z
#include <nanobench.h> #include <thirdparty/doctest/doctest.h> #include <chrono> #include <thread> TEST_CASE("tutorial_slow_v1") { ankerl::nanobench::Bench().run("sleep 100ms, auto", [&] { std::this_thread::sleep_for(std::chrono::milliseconds(100)); }); }
22.833333
68
0.671533
vadi2
c4af4c8bb16f2782e83ac46ea60b8ad346c3e93c
2,427
cc
C++
nodes/PBX/main.cc
kgoba/roombreak
6936d7003d2541fd3fb44bda0a31bf66439f35dc
[ "MIT" ]
1
2021-06-16T07:55:28.000Z
2021-06-16T07:55:28.000Z
nodes/PBX/main.cc
kgoba/roombreak
6936d7003d2541fd3fb44bda0a31bf66439f35dc
[ "MIT" ]
3
2016-04-04T14:13:42.000Z
2016-04-04T15:07:24.000Z
nodes/PBX/main.cc
kgoba/roombreak
6936d7003d2541fd3fb44bda0a31bf66439f35dc
[ "MIT" ]
1
2021-06-16T07:55:30.000Z
2021-06-16T07:55:30.000Z
#include <avr/interrupt.h> #include <avr/io.h> #include <util/delay.h> #include <stdio.h> #include "config.h" #include <Common/config.h> #include <Common/task.h> #include <Common/ws2803s.h> #include "line.h" #include "user.h" using namespace PBXConfig; #define TICK_FREQ 1000 WS2803S<PIN_SDA, PIN_CLK> ioExpander; AudioPlayer player1(ioExpander, XPIN_TRSEL0, XPIN_TRSEL1, XPIN_TRSEL2, XPIN_TRSEL3, XPIN_TRSEL4); PLineConfig config1 = { .apinSense = PIN_SENSE1, .pinRing = PIN_RING1, .trackDial = TRACK_DIAL, .trackCall = TRACK_CALL, .trackBusy = TRACK_BUSY }; PLine line1(player1, config1); PLineConfig config2 = { .apinSense = PIN_SENSE2, .pinRing = PIN_RING2, .trackDial = TRACK_DIAL, .trackCall = TRACK_CALL, .trackBusy = TRACK_BUSY }; PLine line2(player1, config2); //PUser user1(line1); //PUser user2(line2); //VUser user3(NUMBER_FINISH); Operator oper(line1, line2); bool gSolved1; bool gSolved2; void taskComplete() { // gSolved1 = true; gSolved2 = true; } void taskRestart() { // gSolved1 = false; gSolved2 = false; } byte taskIsDone() { return gSolved1 && gSolved2; } byte taskCallback(byte cmd, byte nParams, byte *nResults, byte *busParams) { switch (cmd) { case CMD_DONE1: { if (nParams > 0) { gSolved1 = busParams[0]; } *nResults = 1; busParams[0] = gSolved1; break; } case CMD_DONE2: { if (nParams > 0) { gSolved2 = busParams[0]; } *nResults = 1; busParams[0] = gSolved2; break; } } return 0; } void setup() { pinMode(PIN_TALK, OUTPUT); ioExpander.setup(); player1.setup(); line1.setup(); line2.setup(); TIMER0_SETUP(TIMER0_FAST_PWM, TIMER0_PRESCALER(TICK_FREQ)); //TCCR0A = (1 << WGM01) | (1 << WGM00); //TCCR0B = (1 << CS02) | (1 << CS00) | (1 << WGM02); TIMSK0 = (1 << TOIE0); //OCR0A = (byte)(F_CPU / (1024UL * TICK_FREQ)) - 1; OCR0A = TIMER0_COUNTS(TICK_FREQ) - 1; //ADCSRA = (1 << ADEN) | (1 << ADPS2); // prescaler 16 ADCSRA = bit_mask2(ADPS2, ADPS0); bit_set(ADCSRA, ADEN); adcReference(); taskSetup(BUS_ADDRESS); taskRestart(); } void loop() { static byte id = 0; //_delay_ms(50); if (oper.getLastDialled() == 4) gSolved1 = true; if (oper.getLastDialled() == 5) gSolved2 = true; taskLoop(); } ISR(TIMER0_OVF_vect) { oper.tick(); } extern "C" void __cxa_pure_virtual() { while (1); }
19.731707
97
0.634528
kgoba
c4b34ef60f4cd615d409af1ee6e93208e9607e3b
41,346
cpp
C++
Tools/MakeDiscoLights/gk.cpp
AbePralle/FGB
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
[ "MIT" ]
null
null
null
Tools/MakeDiscoLights/gk.cpp
AbePralle/FGB
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
[ "MIT" ]
null
null
null
Tools/MakeDiscoLights/gk.cpp
AbePralle/FGB
52f004b8d9d4091a2a242a012dc8c1f90d4c160d
[ "MIT" ]
null
null
null
#include "gk.h" #include <stdlib.h> extern ofstream logFile; gkTransparencyTable gkBitmap::tranTable; struct BMP_header{ gkLONG fSize; //54 byte header + 4*numColors (1-8bit) + (w*h*bpp)/8 gkWORD zero1, zero2; //0,0 gkLONG offsetBytes; //should be header (54) plus Palette Size gkLONG headerSize; //size of remaining header (40) gkLONG width, height; //w,h in pixels gkWORD planes, bpp; //plane=1, bpp=1,2,4, or most commonly 8 gkLONG compression, imageSize; //compression to zero, size is w*h(8bit) gkLONG xpels, ypels, zero3, zero4; //set to 0,0,0,0 }; #ifdef _WIN32 gkFileInputBuffer::gkFileInputBuffer(char *filename){ buffer = 0; stin = 0; exists = 0; HANDLE handle = CreateFile(filename,GENERIC_READ,FILE_SHARE_READ,0, OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,0); if(handle==INVALID_HANDLE_VALUE) return; int size = GetFileSize(handle,0); buffer = new char[size]; unsigned long bytesRead; ReadFile(handle,buffer,size,&bytesRead,0); CloseHandle(handle); stin = new istrstream(buffer,size); exists = 1; } gkFileInputBuffer::~gkFileInputBuffer(){ if(stin){ delete stin; stin = 0; } if(buffer) delete buffer; buffer = 0; } gkFileOutputBuffer::gkFileOutputBuffer(char *filename){ exists = 0; handle = CreateFile(filename,GENERIC_WRITE,FILE_SHARE_READ,0, CREATE_ALWAYS,FILE_ATTRIBUTE_NORMAL,0); if(handle==INVALID_HANDLE_VALUE){ return; } exists = 1; } gkFileOutputBuffer::~gkFileOutputBuffer(){ if(handle==INVALID_HANDLE_VALUE) return; unsigned long written; WriteFile(handle,stout.str(),stout.tellp(),&written,0); //unfreeze the ostrstream so it will delete the array stout.rdbuf()->freeze(0); CloseHandle(handle); } #endif gkList::gkList(void){ head = tail = 0; numItems = 0; } gkList::~gkList(void){ Reset(); } void gkList::Reset(){ gkListItem *cur, *next; for(cur=head; cur; cur=next){ next = cur->NextItem(); delete cur; } head = tail = 0; } gkListItem *gkList::GetItem(int n){ if(n >= numItems) return 0; gkListItem *cur; cur = head; while(n-- > 0){ cur = cur->NextItem(); } return cur; } void gkList::AddItem(gkListItem *li){ numItems++; if(!head){ head = tail = li; }else{ tail->SetNextItem(li); tail = tail->NextItem(); li->SetNextItem(0); } } void gkList::DeleteItem(gkListItem *item){ gkListItem *cur, *prev; //is it the head? if(item==head){ head=head->GetNext(); if(!head) tail = 0; delete item; return; } //must be in body or tail prev = 0; for(cur=head; cur; cur=cur->GetNext()){ if(cur==item){ prev->SetNext(cur->GetNext()); if(cur==tail) tail=prev; delete cur; break; } prev = cur; } } int gkIO::ReadWord(istream &in){ int retval = in.get() << 8; return retval | (in.get() & 0xff); } int gkIO::ReadLong(istream &in){ int retval = ReadWord(in) << 16; return retval | (ReadWord(in) & 0xffff); } char *gkIO::ReadString(istream &in){ static char st[80]; int len = ReadWord(in); if(!len) return 0; in.read(st,len); st[len] = 0; return st; } char *gkIO::ReadNewString(istream &in){ int len = ReadWord(in); if(!len) return 0; char *st = new char[len+1]; in.read(st,len); st[len] = 0; return st; } void gkIO::WriteLong(ostream &out, int n){ WriteWord(out, n>>16); WriteWord(out, n); } void gkIO::WriteWord(ostream &out, int n){ out << (char) ((n>>8)&0xff); out << (char) (n&0xff); } void gkIO::WriteString(ostream &out, char *st){ WriteWord(out,strlen(st)); out.write(st,strlen(st)); } int gkRGB::Equals(int _r, int _g, int _b){ return _r==color.bytes.r && _g==color.bytes.g && _b==color.bytes.b; } void gkRGB::Combine(gkRGB c2, int alpha){ //mix alpha color.bytes.r += gkBitmap::tranTable.LookupTransparencyOffset(c2.GetR()-GetR(), alpha); color.bytes.g += gkBitmap::tranTable.LookupTransparencyOffset(c2.GetG()-GetG(), alpha); color.bytes.b += gkBitmap::tranTable.LookupTransparencyOffset(c2.GetB()-GetB(), alpha); } void gkRGB::SetFromGBColor(int gbColor){ color.bytes.r = (gbColor<<3) & 0xf8; color.bytes.g = (gbColor>>2) & 0xf8; color.bytes.b = (gbColor>>7) & 0xf8; } gkPalGenItem::gkPalGenItem(gkRGB _color){ color = _color; occurrences = 1; nextItem = 0; } gkPalGenItem::~gkPalGenItem(){ } gkRGB gkPalGenItem::GetColor(){ return color; } void gkPalGenItem::AddOccurrence(){ occurrences++; } int gkPalGenItem::GetOccurrences(){ return occurrences; } void gkPalGenItem::SetOccurrences(int n){ occurrences = n; } void gkPalGenItem::SetNextItem(gkPalGenItem *item){ nextItem = item; } gkPalGenItem *gkPalGenItem::GetNextItem(){ return nextItem; } int gkPalGenItem::GetCount(){ gkPalGenItem *cur; int count = 0; for(cur=this; cur; cur=cur->nextItem){ if(cur->occurrences) count++; } return count; } int gkPalGenItem::SortCallback(const void *e1, const void *e2){ gkPalGenItem *i1 = *((gkPalGenItem**) e1); gkPalGenItem *i2 = *((gkPalGenItem**) e2); if(i1->occurrences > i2->occurrences) return -1; if(i1->occurrences == i2->occurrences) return 0; return 1; } gkPaletteGenerator::gkPaletteGenerator(){ int i; for(i=0; i<52; i++){ colorCube[i] = 0; } } gkPaletteGenerator::~gkPaletteGenerator(){ Reset(); } void gkPaletteGenerator::Reset(){ int i; for(i=0; i<52; i++){ if(colorCube[i]){ gkPalGenItem *cur, *next; for(cur=colorCube[i]; cur; cur=next){ next = cur->GetNextItem(); delete cur; } colorCube[i] = 0; } } } void gkPaletteGenerator::AddColor(gkRGB color){ int i = GetHash(color); if(!colorCube[i]){ colorCube[i] = new gkPalGenItem(color); }else{ gkPalGenItem *cur, *prev; for(cur=colorCube[i]; cur; cur=cur->GetNextItem()){ if((cur->GetColor()) == color){ cur->AddOccurrence(); //Color already in list break; } prev = cur; } if(!cur){ //color not in list prev->SetNextItem(new gkPalGenItem(color)); } } } void gkPaletteGenerator::CreatePalette(gkRGB *palette, int numEntries){ if(numEntries<=0) return; //Set all entries to black int i; for(i=0; i<numEntries; i++) palette[i] = gkRGB(0,0,0); //1 entry from every this many indices double scaleFactor = 52.0 / numEntries; int curEntry = 0; while(curEntry < numEntries){ //Get first & last array indices for this section int first = (int) (scaleFactor * (curEntry)); int nextEntry = (int) (scaleFactor * (curEntry+1)); int last = nextEntry - 1; if(last < first) last = first; //Count total # of colors in this section int count = 0; for(i=first; i<=last; i++){ if(colorCube[i]) count += colorCube[i]->GetCount(); } while(!count){ //if no colors yet expand area of inclusion if(first==0 && last==51) return; //no colors anywhere! if(first>0){ first--; if(colorCube[first]) count += colorCube[first]->GetCount(); } if(last<51){ last++; if(colorCube[last]) count += colorCube[last]->GetCount(); } } //Create an array to hold all the colors for sorting purposes gkPalGenItem **colors = new gkPalGenItem*[count]; gkPalGenItem *cur; i = 0; int j; for(j=first; j<=last; j++){ if(colorCube[j]){ for(cur=colorCube[j]; cur; cur=cur->GetNextItem()){ if(cur->GetOccurrences()) colors[i++] = cur; } } } //figure out how many colors will come from this section of the cube int numToGrab = 1; int tempCurEntry = curEntry; while(nextEntry==first && tempCurEntry<(52-1)){ tempCurEntry++; nextEntry = (int) (scaleFactor * (tempCurEntry+1)); numToGrab++; } if(numToGrab > count) numToGrab = count; //sort colors into descending order and pick "num" most frequent qsort(colors, count, sizeof(gkPalGenItem*), gkPalGenItem::SortCallback); for(i=0; i<numToGrab; i++){ palette[curEntry++] = colors[i]->GetColor(); colors[i]->SetOccurrences(0); } //delete sorting table delete colors; } } int gkPaletteGenerator::GetNumColors(){ int num = 0, i; for(i=0; i<52; i++) if(colorCube[i]) num += colorCube[i]->GetCount(); return num; } int gkPaletteGenerator::GetHash(gkRGB color){ int r = color.GetR() >> 6; //rough categories 0-3 int g = color.GetG() >> 6; int b = color.GetB() >> 6; int highest = r; if(g > highest) highest = g; if(b > highest) highest = b; int hash; // r > (g < b) // r > (g = b) // r > (g > b) // g > (r < b) // g > (r = b) // g > (r > b) // b > (r < g) // b > (r = g) // b > (r > g) // (r = b) > g // (r = g) > b // (g = b) > r // (r = g) = b if(r > g && r > b){ //red high if(g < b) hash = 0; // r > (g < b) else if(g==b) hash = 1; // r > (g = b) else hash = 2; // r > (g > b) }else if(g > r && g > b){ //green high if(r < b) hash = 3; // g > (r < b) else if(r==b) hash = 4; // g > (r = b) else hash = 5; // g > (r > b) }else if(b > r && b > g){ //blue high if(r < g) hash = 6; // b > (r < g) else if(r==g) hash = 7; // b > (r = g) else hash = 8; // b > (r > g) }else if(r==b && b==g){ //r = g = b hash = 9; }else if(r==b){ //(r = b) > g hash = 10; }else if(r==g){ //(r = g) > b hash = 11; }else{ //(g = b) > r hash = 12; } //make room in each category for four levels of intensity (0-3) hash = hash*4 + highest; return hash; } int gkPaletteGenerator::ColorExists(gkRGB color){ int hash = GetHash(color); if(!colorCube[hash]) return 0; gkPalGenItem *cur; for(cur=colorCube[hash]; cur; cur=cur->GetNextItem()){ if(cur->GetColor()==color) return 1; //found exact color } return 0; } gkRGB gkPaletteGenerator::MatchColor(gkRGB color){ int hash = GetHash(color); int r = color.GetR(); int g = color.GetG(); int b = color.GetB(); if(colorCube[hash]){ //near colors; search just this section gkPalGenItem *cur, *bestMatch; int bestDiff; bestMatch = colorCube[hash]; int r2, g2, b2; r2 = abs(r - bestMatch->GetColor().GetR()); g2 = abs(g - bestMatch->GetColor().GetG()); b2 = abs(b - bestMatch->GetColor().GetB()); bestDiff = r2 + g2 + b2; for(cur=bestMatch->GetNextItem(); cur; cur=cur->GetNextItem()){ r2 = abs(r - cur->GetColor().GetR()); g2 = abs(g - cur->GetColor().GetG()); b2 = abs(b - cur->GetColor().GetB()); int curDiff = r2 + g2 + b2; if(curDiff < bestDiff){ bestDiff = curDiff; bestMatch = cur; if(!curDiff) return bestMatch->GetColor(); } } return bestMatch->GetColor(); }else{ //no colors nearby; expand search //Get it from ~greyscale if possible int first, last; first = last = 36 + (hash % 4); if(!colorCube[first]){ first = 0; //nothing there either; search everything last = 51; /* first = 36; last = 39; //first = hash - (hash%4); //different intensities, same color //last = first + 3; if(!colorCube[first] && !colorCube[first+1] && !colorCube[first+2] && !colorCube[last]){ first = 0; //nothing there either; search everything last = 51; } */ } gkPalGenItem *cur, *bestMatch; int bestDiff = 0x7fffffff; bestMatch = 0; int i; for(i=first; i<=last; i++){ for(cur=colorCube[i]; cur; cur=cur->GetNextItem()){ int r2 = abs(r - cur->GetColor().GetR()); int g2 = abs(g - cur->GetColor().GetG()); int b2 = abs(b - cur->GetColor().GetB()); int curDiff = r2 + g2 + b2; if(curDiff < bestDiff){ bestDiff = curDiff; bestMatch = cur; if(!curDiff) return bestMatch->GetColor(); } } } if(!bestMatch) return gkRGB(0,0,0); return bestMatch->GetColor(); } } gkTransparencyTable::gkTransparencyTable(){ lookup = new gkBYTE[256*256]; int baseOffset, alpha, i; i = 0; for(baseOffset=0; baseOffset<256; baseOffset++){ for(alpha=0; alpha<256; alpha++){ lookup[i++] = (baseOffset * alpha) / 255; } } } gkTransparencyTable::~gkTransparencyTable(){ if(lookup) delete lookup; lookup = 0; } int gkTransparencyTable::LookupTransparencyOffset(int baseOffset, int alpha){ return (baseOffset>=0) ? lookup[(baseOffset<<8)+alpha] : (-lookup[((-baseOffset)<<8)+alpha]); } gkBitmap::gkBitmap(){ data = 0; width = height = bpp = 0; } gkBitmap::~gkBitmap(){ FreeData(); } void gkBitmap::FreeData(){ if(data){ delete data; data = 0; } width = height = 0; } void gkBitmap::Create(int _width, int _height){ if(_width <= 0 || _height <= 0) return; FreeData(); width = _width; height = _height; //round up width to ensure multiple of 4 pixels width = (width + 3) & (~3); int size = (width*height)<<2; data = new gkBYTE[size]; //data = new gkBYTE[(width*height)<<2]; bpp = 32; } void gkBitmap::Cls(){ if(!this->data) return; gkLONG *dest = (gkLONG*) this->data; int i = this->width * this->height; while(i--){ *(dest++) = 0xff000000; } } void gkBitmap::Cls(gkRGB color){ if(!this->data) return; gkLONG *dest = (gkLONG*) this->data; int i = this->width * this->height; while(i--){ *(dest++) = color.GetARGB(); } } void gkBitmap::Plot(int x, int y, gkRGB color, int testBoundaries){ if(!data) return; if(testBoundaries){ if(x<0 || x>=width || y<0 || y>=height) return; } gkRGB *dest = (gkRGB*) (data + ((y*width + x) << 2)); *dest = color; } gkRGB gkBitmap::Point(int x, int y, int testBoundaries){ if(!data) return gkRGB(0,0,0); if(testBoundaries){ if(x<0 || x>=width || y<0 || y>=height) return gkRGB(0,0,0); } gkRGB *color = (gkRGB*) (data + ((y*width + x) << 2)); return *color; } void gkBitmap::Line(int x1, int y1, int x2, int y2, gkRGB color){ int temp; if(y1==y2){ //straight horizontal line if(x2 < x1) RectFill(x2,y1,(x1-x2)+1,1,color); else RectFill(x1,y1,(x2-x1)+1,1,color); return; }else if(x1==x2){ //straight vertical line if(y2 < y1) RectFill(x1,y2,1,(y1-y2)+1,color); else RectFill(x1,y1,1,(y2-y1)+1,color); return; } //clip line to screen if(y2 < y1){ //orient line to be drawn from top to temp = x1; x1 = x2; x2 = temp; //bottom for initial clipping tests temp = y1; y1 = y2; y2 = temp; } if(y2 < 0 || y1 >= height) return; double xdiff = x2-x1, ydiff = y2-y1; double slopexy = xdiff / ydiff; int diff; //perform vertical clipping diff = 0 - y1; if(diff > 0){ //y1 is above top boundary x1 += (int) (slopexy * diff); y1 = 0; } diff = (y2 - height) + 1; if(diff > 0){ //y2 is below bottom boundary x2 -= (int) (slopexy * diff); y2 = height - 1; } //reorient line to be drawn from left to right for horizontal clipping tests if(x2 < x1){ temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; xdiff = x2-x1; ydiff = y2-y1; } double slopeyx = ydiff / xdiff; if(x2 < 0 || x1 >= width) return; diff = 0 - x1; if(diff > 0){ //x1 is to left of left boundary y1 += (int) (slopeyx * diff); x1 = 0; } diff = (x2 - width) + 1; if(diff > 0){ //x2 is to right of right boundary y2 -= (int) (slopeyx * diff); x2 = width - 1; } //draw the line using Bresenham's //coordinates are now such that x increment is always positive int xdist = x2-x1; int ydist = y2-y1; int pitch = width; gkRGB *dest = (gkRGB*) (data + (((y1 * width) + x1) <<2)); if(ydist < 0){ ydist = -ydist; pitch = -pitch; } int err, i; if(xdist >= ydist){ //loop on x, change y every so often err = 0; for(i=xdist; i>=0; i--){ *(dest++) = color; err += ydist; if(err >= xdist){ err -= xdist; dest += pitch; } } }else{ //loop on y, change x every so often err = 0; for(i=ydist; i>=0; i--){ *dest = color; dest += pitch; err += xdist; if(err >= ydist){ err -= ydist; dest++; } } } } void gkBitmap::LineAlpha(int x1, int y1, int x2, int y2, gkRGB color, int alpha){ int temp; if(y1==y2){ //straight horizontal line if(x2 < x1) RectFill(x2,y1,(x1-x2)+1,1,color); else RectFill(x1,y1,(x2-x1)+1,1,color); return; }else if(x1==x2){ //straight vertical line if(y2 < y1) RectFill(x1,y2,1,(y1-y2)+1,color); else RectFill(x1,y1,1,(y2-y1)+1,color); return; } //clip line to screen if(y2 < y1){ //orient line to be drawn from top to temp = x1; x1 = x2; x2 = temp; //bottom for initial clipping tests temp = y1; y1 = y2; y2 = temp; } if(y2 < 0 || y1 >= height) return; double xdiff = x2-x1, ydiff = y2-y1; double slopexy = xdiff / ydiff; int diff; //perform vertical clipping diff = 0 - y1; if(diff > 0){ //y1 is above top boundary x1 += (int) (slopexy * diff); y1 = 0; } diff = (y2 - height) + 1; if(diff > 0){ //y2 is below bottom boundary x2 -= (int) (slopexy * diff); y2 = height - 1; } //reorient line to be drawn from left to right for horizontal clipping tests if(x2 < x1){ temp = x1; x1 = x2; x2 = temp; temp = y1; y1 = y2; y2 = temp; xdiff = x2-x1; ydiff = y2-y1; } double slopeyx = ydiff / xdiff; if(x2 < 0 || x1 >= width) return; diff = 0 - x1; if(diff > 0){ //x1 is to left of left boundary y1 += (int) (slopeyx * diff); x1 = 0; } diff = (x2 - width) + 1; if(diff > 0){ //x2 is to right of right boundary y2 -= (int) (slopeyx * diff); x2 = width - 1; } //draw the line using Bresenham's //coordinates are now such that x increment is always positive int xdist = x2-x1; int ydist = y2-y1; int pitch = width; gkRGB *dest = (gkRGB*) (data + (((y1 * width) + x1) <<2)); if(ydist < 0){ ydist = -ydist; pitch = -pitch; } int err, i; if(xdist >= ydist){ //loop on x, change y every so often err = 0; for(i=xdist; i>=0; i--){ dest->Combine(color,alpha); dest++; err += ydist; if(err >= xdist){ err -= xdist; dest += pitch; } } }else{ //loop on y, change x every so often err = 0; for(i=ydist; i>=0; i--){ dest->Combine(color,alpha); dest += pitch; err += xdist; if(err >= ydist){ err -= ydist; dest++; } } } } void gkBitmap::RectFrame(int x, int y, int w, int h, gkRGB color){ int x2 = x + w - 1; int y2 = y + h - 1; RectFill(x,y,w,1,color); RectFill(x,y2,w,1,color); RectFill(x,y,1,h,color); RectFill(x2,y,1,h,color); } void gkBitmap::RectFill(int x, int y, int w, int h, gkRGB color){ int x2 = (x + w) - 1; int y2 = (y + h) - 1; //Clip rectangle if(x < 0) x = 0; if(y < 0) y = 0; if(x2 >= width) x2 = width - 1; if(y2 >= height) y2 = height - 1; if(x2 < x || y2 < y) return; //Set pointers and offsets gkRGB *destStart = (gkRGB*) (data + (((y * width) + x) <<2)); gkRGB *dest; int numRows = (y2 - y) + 1; int rowWidth = (x2 - x) + 1; //do it while(numRows--){ dest = destStart; int i; for(i=0; i<rowWidth; i++){ *(dest++) = color; } destStart += width; } } void gkBitmap::RectFillAlpha(int x, int y, int w, int h, gkRGB color, int alpha){ int x2 = (x + w) - 1; int y2 = (y + h) - 1; //Clip rectangle if(x < 0) x = 0; if(y < 0) y = 0; if(x2 >= width) x2 = width - 1; if(y2 >= height) y2 = height - 1; if(x2 < x || y2 < y) return; //Set pointers and offsets gkRGB *destStart = (gkRGB*) (data + (((y * width) + x) <<2)); gkRGB *dest; int numRows = (y2 - y) + 1; int rowWidth = (x2 - x) + 1; //do it while(numRows--){ dest = destStart; int i; for(i=0; i<rowWidth; i++){ dest->Combine(color,alpha); dest++; } destStart += width; } } void gkBitmap::RectFillChannel(int x, int y, int w, int h, gkRGB color, int mask){ int x2 = (x + w) - 1; int y2 = (y + h) - 1; //Clip rectangle if(x < 0) x = 0; if(y < 0) y = 0; if(x2 >= width) x2 = width - 1; if(y2 >= height) y2 = height - 1; if(x2 < x || y2 < y) return; //Set pointers and offsets gkLONG *destStart = (gkLONG*) (data + (((y * width) + x) <<2)); gkLONG *dest; int numRows = (y2 - y) + 1; int rowWidth = (x2 - x) + 1; gkLONG srcColor = color.GetARGB() & mask; gkLONG destMask = ~mask; //do it while(numRows--){ dest = destStart; int i; for(i=0; i<rowWidth; i++){ *dest = (*dest & destMask) | (srcColor); dest++; } destStart += width; } } struct gkFillItem{ short int x, y; gkRGB *pos; inline gkFillItem(){} inline gkFillItem(int _x, int _y, gkRGB *_pos){ x = _x; y = _y; pos = _pos; } }; void gkBitmap::FloodFill(int x, int y, gkRGB color){ gkFillItem queue[16384]; int qHead=0, qTail=0; //not the color we're filling WITH, the color we're filling ON gkRGB fillColor = Point(x,y); if(color==fillColor) return; //enqueue the starting location queue[qTail++] = gkFillItem(x,y,(gkRGB *)(data + ((y*width + x) * 4))); //keep looping, filling current location & adding adjacent locations //until queue is empty while(qHead != qTail){ //dequeue an item gkFillItem cur = queue[qHead++]; qHead &= 16383; //out of bounds check if(cur.x<0 || cur.y<0 || cur.x>=width || cur.y>=height) continue; //filling correct color check if(!(*(cur.pos)==fillColor)) continue; //fill color & add adjacent *(cur.pos) = color; queue[qTail++] = gkFillItem(cur.x+1,cur.y,cur.pos+1); qTail &= 16383; queue[qTail++] = gkFillItem(cur.x-1,cur.y,cur.pos-1); qTail &= 16383; queue[qTail++] = gkFillItem(cur.x,cur.y+1,cur.pos+width); qTail &= 16383; queue[qTail++] = gkFillItem(cur.x,cur.y-1,cur.pos-width); qTail &= 16383; } } int gkBitmap::GetNumColors(){ gkPaletteGenerator palGen; int i = width * height; gkRGB *src = (gkRGB*) data; while(i--){ palGen.AddColor(*(src++)); } return palGen.GetNumColors(); } void gkBitmap::RemapColor(gkRGB oldColor, gkRGB newColor){ if(!data) return; gkRGB *src = (gkRGB*) data; int i, j; for(j=0; j<height; j++){ for(i=0; i<width; i++){ if(oldColor == (*src)){ *src = newColor; } src++; } } } int gkBitmap::GetPalette(gkRGB *palette, int maxColors){ gkPaletteGenerator palGen; int i = width * height; gkRGB *src = (gkRGB*) data; while(i--){ palGen.AddColor(*(src++)); } int num = palGen.GetNumColors(); palGen.CreatePalette(palette, maxColors); return num; } void gkBitmap::RemapToPalette(gkRGB *palette, int numColors){ //add palette colors to generator for matching purposes gkPaletteGenerator generator; int i = numColors; gkRGB *src = palette; while(i--){ generator.AddColor(*(src++)); } //find color in palette that best matches each pixel i = width * height; src = (gkRGB*) data; while(i--){ *src = generator.MatchColor(*src); src++; } } void gkBitmap::ReduceColors(int numColors){ gkPaletteGenerator generator; int i = width * height; gkRGB *src = (gkRGB*) data; while(i--){ generator.AddColor(*(src++)); } //gkRGB palette[256]; gkRGB *palette = new gkRGB[numColors]; generator.CreatePalette(palette, numColors); RemapToPalette(palette, numColors); delete palette; } void gkBitmap::ExchangeColors(gkRGB c1, gkRGB c2){ if(!data) return; gkRGB *src = (gkRGB*) data; int i, j; for(j=0; j<height; j++){ for(i=0; i<width; i++){ if(c1 == (*src)){ *src = c2; }else if(c2 == (*src)){ *src = c1; } src++; } } } void gkBitmap::SetAlpha(int alpha){ if(!data) return; gkRGB *src = (gkRGB*) data; int i = (width * height); while(i--){ (src++)->SetA(alpha); } } void gkBitmap::SetColorAlpha(gkRGB color, int alpha){ if(!data) return; gkRGB *src = (gkRGB*) data; int i, j; for(j=0; j<height; j++){ for(i=0; i<width; i++){ if(color == (*src)){ src->SetA(alpha); } src++; } } } void gkBitmap::SetAlphaEdges(float opacity, int iterations){ { //body in block to prevent recursive memory waste gkBitmap work; work.GetBitmap(this); gkRGB *src = (gkRGB*) work.data; gkRGB *dest = (gkRGB*) data; gkRGB alpha; int i, j; for(j=0; j<height; j++){ for(i=0; i<width; i++){ if(src->GetA()==255){ int alpha = 0; int samples = 0; if(i>0 && j>0){ alpha += work.Point(i-1,j-1).GetA(); samples++; } if(i>0 && j<height-1){ alpha += work.Point(i-1,j+1).GetA(); samples++; } if(i<width-1 && j>0){ alpha += work.Point(i+1,j-1).GetA(); samples++; } if(i<width-1 && j<height-1){ alpha += work.Point(i+1,j+1).GetA(); samples++; } if(samples==0) samples=1; //would only happen on 1x1 alpha /= samples; alpha = (int) (alpha * opacity); dest->SetA(alpha); } dest++; src++; } } } if(iterations>0) SetAlphaEdges(opacity, iterations-1); } void gkBitmap::MirrorH(){ gkRGB *buffer = new gkRGB[width]; if(!buffer) return; gkRGB *cur = (gkRGB*) data; int i,j,i2; for(j=0; j<height; j++){ for(i=0,i2=width-1; i<width; i++,i2--){ buffer[i2] = cur[i]; } for(i=0; i<width; i++){ cur[i] = buffer[i]; } cur += width; } delete buffer; } int gkBitmap::GetBitmap(gkBitmap *srcBitmap, int x, int y, int w, int h){ if(!srcBitmap || !srcBitmap->data) return 0; //adjust src rectangle until it fits within source data if(x<0){ w += x; x = 0; } if(y<0){ h += y; y = 0; } if(x + w > srcBitmap->width){ w = srcBitmap->width - x; } if(y + h > srcBitmap->height){ h = srcBitmap->height - y; } if(w<=0 || h<=0) return 0; FreeData(); Create(w, h); gkBYTE *src = srcBitmap->data + ((y*srcBitmap->width + x)<<2); gkBYTE *dest = this->data; int srcSkip = srcBitmap->width << 2; //4 bytes per pixel w <<= 2; //4 bytes per pixel while(h--){ memcpy(dest, src, w); dest += w; src += srcSkip; } return 1; } int gkBitmap::GetBitmap(gkBitmap *srcBitmap){ if(this->width != srcBitmap->width || this->height != srcBitmap->height || (!this->data) || (!srcBitmap->data)){ //mem needs to be reallocated FreeData(); memcpy(this, srcBitmap, sizeof(gkBitmap)); data = 0; if(srcBitmap->data){ data = new gkBYTE[(width * height) << 2]; memcpy(data, srcBitmap->data, (width * height) << 2 ); } }else{ //already got right size mem, just copy data over memcpy(data, srcBitmap->data, (width * height) << 2); fontSpacing = srcBitmap->fontSpacing; fontKerning = srcBitmap->fontKerning; x_handle = srcBitmap->x_handle; y_handle = srcBitmap->y_handle; } return data!=0; } int gkBitmap::SaveBitmap(char *filename){ ofstream outfile; outfile.open(filename, ios::out | ios::binary); if(!outfile) return 0; int result = SaveBitmap(outfile); outfile.close(); return result; } int gkBitmap::SaveBitmap(ostream &out){ int totalSize = ((width * height) << 2); out << "SHPE"; int skipSize = totalSize + 20; gkIO::WriteLong(out, skipSize); //Write shape header gkIO::WriteWord(out, 3); //type 3 gkIO::WriteWord(out, width); gkIO::WriteWord(out, height); gkIO::WriteWord(out, (bpp==8)?8:32); out << (char) fontSpacing << (char) fontKerning; gkIO::WriteWord(out, x_handle); gkIO::WriteWord(out, y_handle); gkIO::WriteWord(out, 0); //6 bytes of reserved space gkIO::WriteLong(out, 0); //Write data if(data){ int pitch = width << 2; gkLONG *src; gkBYTE *srcStart = data; int i,j; for(j=0; j<height; j++){ src = (gkLONG*) srcStart; for(i=0; i<width; i++){ gkIO::WriteLong(out, *(src++)); } srcStart += pitch; } } return 1; } int gkBitmap::LoadBitmap(char *filename){ ifstream infile(filename,ios::in|ios::binary|ios::nocreate); if(!infile) return 0; //gkFileInputBuffer gkInfile(filename); //if(!gkInfile.Exists()) return 0; //istream &infile = *gkInfile.GetIStream(); int result = this->LoadBitmap(infile); infile.close(); return result; } int gkBitmap::LoadBitmap(istream &infile){ FreeData(); if(infile.get() != 'S') return 0; if(infile.get() != 'H') return 0; if(infile.get() != 'P') return 0; if(infile.get() != 'E') return 0; gkIO::ReadLong(infile); //discard skipsize //Read shape header if(gkIO::ReadWord(infile) != 2) return 0; width = gkIO::ReadWord(infile); height = gkIO::ReadWord(infile); int filebpp = gkIO::ReadWord(infile); if(!bpp) bpp = filebpp; if(width && height){ Create(width,height); } fontSpacing = infile.get(); fontKerning = infile.get(); x_handle = gkIO::ReadWord(infile); y_handle = gkIO::ReadWord(infile); gkIO::ReadWord(infile); gkIO::ReadLong(infile); //discard reserved space if(!width || !height) return 1; //nothing to load, null shape int pitch = width << 2; gkBYTE *destStart = data; gkLONG *dest; int x,y; for(y=0; y<height; y++){ dest = (gkLONG*) destStart; for(x=0; x<width; x++){ *(dest++) = gkIO::ReadLong(infile); } destStart += pitch; } return 1; } int gkBitmap::LoadBMP(char *filename){ ifstream infile(filename,ios::in|ios::binary|ios::nocreate); if(!infile) return 0; //gkFileInputBuffer gkInfile(filename); //if(!gkInfile.Exists()) return 0; //istream &infile = *gkInfile.GetIStream(); int result = this->LoadBMP(infile); infile.close(); return result; } int gkBitmap::LoadBMP(istream &infile){ BMP_header header; if(gkIO::ReadWord(infile)!=0x424d){ //check for "BM" return 0; } infile.read((char*)&header, sizeof(BMP_header)); if(header.bpp != 24){ cout << "LoadBMP can only handle 24-bit files" << endl; return 0; } FreeData(); width = header.width; height = header.height; bpp = (char) header.bpp; Create(width,height); // load graphics, coverting every three (B,R,G) bytes to one ARGB value. // lines padded to even multiple of 4 bytes int srcPitch = ((header.width * 3) + 3) & (~3); gkBYTE *buffer = new gkBYTE[srcPitch * height]; gkBYTE *nextBuffPtr = buffer + ((height-1) * srcPitch); gkBYTE *buffPtr; infile.read(buffer, srcPitch * height); gkBYTE *nextDest = data; gkRGB *dest; int destPitch = (width << 2); int i, j; j = height; while(j--){ buffPtr = nextBuffPtr; nextBuffPtr -= srcPitch; dest = (gkRGB*) nextDest; nextDest += destPitch; i = header.width; while(i--){ dest->SetB(*(buffPtr++)); dest->SetG(*(buffPtr++)); dest->SetR(*(buffPtr++)); dest->SetA(0xff); dest++; } for(i=header.width; i<width; i++){ dest->SetARGB(0); dest++; } } delete buffer; return 1; } int gkBitmap::SaveBMP(char *filename){ if(!data) return 0; if(!filename) return 0; //open file ofstream outfile; outfile.open(filename, ios::out | ios::binary); if(!outfile) return 0; outfile << 'B' << 'M'; //"BM" (file type) BMP_header header; memset(&header,0,sizeof(header)); //clear everything to zero header.width = width; header.height = height; header.bpp = 24; header.planes = 1; header.imageSize = (header.width * header.height * header.bpp) / 8; header.headerSize = 40; header.offsetBytes = 54; //header + palette size header.fSize = 54 + header.imageSize; outfile.write((char*)&header, sizeof(BMP_header)); // save graphics as bottom-to-top, left-to-right // int y = height - 1; int pitch = width*4; gkBYTE *src = data + (y * pitch); //find bottom of buffer gkBYTE *d; //write brg bytes out int i; for(; y>=0; y--){ d = src; for(i=0; i<width; i++){ int r,g,b; b = *(d++); g = *(d++); r = *d; outfile << (char) b << (char) g << (char) r; d+=2; } src -= pitch; } outfile.close(); return 1; } void gkBitmap::Blit(gkBitmap *destBitmap, int x, int y, int flags){ if(!data || !destBitmap || !destBitmap->data) return; gkBYTE *src = 0; int srcWidth = this->width; int srcSkip = this->width; int lines = this->height; //clip left side if(x < 0){ src += -x; //times 4 later srcWidth -= -x; x = 0; } //clip right side int diff = (x + srcWidth) - destBitmap->width; if(diff > 0){ srcWidth -= diff; } if(srcWidth <= 0) return; //clip top if(y<0){ src += (-y * this->width); //times 4 later lines += y; //lines -= (-y) y = 0; } //clip bottom diff = (y + lines) - destBitmap->height; if(diff > 0){ lines -= diff; } if(lines <= 0) return; int destSkip = destBitmap->width; gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2); src = this->data + ((int)src << 2); srcWidth <<= 2; srcSkip <<= 2; destSkip <<= 2; if(flags & GKBLT_TRANSPARENT){ //blit using alpha 0 as fully transparent while(lines--){ MemCpyTrans(dest, src, srcWidth); src += srcSkip; dest += destSkip; } }else{ //blit without a transparent color while(lines--){ memcpy(dest, src, srcWidth); src += srcSkip; dest += destSkip; } } } ////////////////////////////////////////////////////////////////////// // Method: BlitColorToAlpha // Description: Converts this bitmap's colors into alpha values on // the destination bitmap. Black becomes transparent, // white fully opaque. ////////////////////////////////////////////////////////////////////// void gkBitmap::BlitColorToAlpha(gkBitmap *destBitmap, int x, int y){ if(!data || !destBitmap || !destBitmap->data) return; gkBYTE *src = 0; int srcWidth = this->width; int srcSkip = this->width; int lines = this->height; //clip left side if(x < 0){ src += -x; //times 4 later srcWidth -= -x; x = 0; } //clip right side int diff = (x + srcWidth) - destBitmap->width; if(diff > 0){ srcWidth -= diff; } if(srcWidth <= 0) return; //clip top if(y<0){ src += (-y * this->width); //times 4 later lines += y; //lines -= (-y) y = 0; } //clip bottom diff = (y + lines) - destBitmap->height; if(diff > 0){ lines -= diff; } if(lines <= 0) return; int destSkip = destBitmap->width; gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2); src = this->data + ((int)src << 2); srcWidth <<= 2; srcSkip <<= 2; destSkip <<= 2; //blit converting color(B) to alpha. while(lines--){ MemCpyColorToAlpha(dest, src, srcWidth); src += srcSkip; dest += destSkip; } } ////////////////////////////////////////////////////////////////////// // Function: BlitScale // Arguments: destBitmap // x // y // flags // scale - number of source pixels for every one // dest pixel, stored in 24:8 fixed point. // $100=100%, $200=200% (mag x2), $80=50% ////////////////////////////////////////////////////////////////////// void gkBitmap::BlitScale(gkBitmap *destBitmap, int x, int y, int scale, int flags){ if(!data || !destBitmap || !destBitmap->data || !scale) return; gkBYTE *src = 0; int srcSkip = this->width; int srcWidth = (this->width * scale) >> 8; int lines = (this->height * scale) >> 8; //clip left side if(x < 0){ src += (-x << 8) / scale; srcWidth -= -x; x = 0; } //clip right side int diff = (x + srcWidth) - destBitmap->width; if(diff > 0){ srcWidth -= diff; } if(srcWidth <= 0) return; //clip top if(y<0){ src += ((-y * this->width) << 8) / scale; lines += y; //lines -= (-y) y = 0; } //clip bottom diff = (y + lines) - destBitmap->height; if(diff > 0){ lines -= diff; } if(lines <= 0) return; int destSkip = destBitmap->width; gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2); src = this->data + ((int)src << 2); srcSkip <<= 2; destSkip <<= 2; int ratio = (int) ((1.0f / (((float) scale) / 256.0f)) * 256.0f); int lineError = 0; while(lines--){ BlitLineScale(dest, src, srcWidth, ratio); lineError += ratio; src += srcSkip * (lineError >> 8); lineError &= 0xff; dest += destSkip; } /* if(flags & GKBLT_TRANSPARENT){ //blit using alpha 0 as fully transparent while(lines--){ MemCpyTrans(dest, src, srcWidth); src += srcSkip; dest += destSkip; } }else{ //blit without a transparent color while(lines--){ memcpy(dest, src, srcWidth); src += srcSkip; dest += destSkip; } } */ } void gkBitmap::BlitScale(gkBitmap *destBitmap, int x, int y, float scale, int flags){ BlitScale(destBitmap,x,y,flags,(int) (256.0f * scale)); } void gkBitmap::BlitChannel(gkBitmap *destBitmap, int x, int y, int mask){ if(!data || !destBitmap || !destBitmap->data) return; gkBYTE *src = 0; int srcWidth = this->width; int srcSkip = this->width; int lines = this->height; //clip left side if(x < 0){ src += -x; srcWidth -= -x; x = 0; } //clip right side int diff = (x + srcWidth) - destBitmap->width; if(diff > 0){ srcWidth -= diff; } if(srcWidth <= 0) return; //clip top if(y<0){ src += (-y * this->width); lines += y; //lines -= (-y) y = 0; } //clip bottom diff = (y + lines) - destBitmap->height; if(diff > 0){ lines -= diff; } if(lines <= 0) return; int destSkip = destBitmap->width; gkBYTE *dest = destBitmap->data + (((y * destBitmap->width) + x) << 2); src = this->data + ((int)src << 2); srcSkip <<= 2; destSkip <<= 2; int inverseMask = ~mask; while(lines--){ gkLONG *curSrc = (gkLONG*) src; gkLONG *curDest = (gkLONG*) dest; int pixels = srcWidth; while(pixels--){ *curDest = (*curSrc & mask) | (*curDest & inverseMask); curSrc++; curDest++; } src += srcSkip; dest += destSkip; } } void gkBitmap::MemCpyTrans(gkBYTE *dest, gkBYTE *src, int numBytes){ //copies colors using the Alpha for transparency gkRGB *destColor = (gkRGB*) dest; gkRGB *srcColor = (gkRGB*) src; int numColors = numBytes >> 2; int c1; while(numColors--){ int alpha; switch(alpha = (srcColor->GetA())){ case 0: break; case 255: //Straight copy *destColor = *srcColor; break; default: //mix alpha c1 = destColor->GetR(); c1 += tranTable.LookupTransparencyOffset( srcColor->GetR()-c1, alpha); destColor->SetR(c1); c1 = destColor->GetG(); c1 += tranTable.LookupTransparencyOffset( srcColor->GetG()-c1, alpha); destColor->SetG(c1); c1 = destColor->GetB(); c1 += tranTable.LookupTransparencyOffset( srcColor->GetB()-c1, alpha); destColor->SetB(c1); break; } srcColor++; destColor++; } } void gkBitmap::MemCpyColorToAlpha(gkBYTE *dest, gkBYTE *src, int numBytes){ //converts blue to alpha during copy gkRGB *destColor = (gkRGB*) dest; gkRGB *srcColor = (gkRGB*) src; int numColors = numBytes >> 2; while(numColors--){ destColor->SetA(srcColor->GetB()); srcColor++; destColor++; } } void gkBitmap::BlitLineScale(gkBYTE *dest,gkBYTE *src,int pixels,int ratio){ gkRGB *srcRGB = (gkRGB*) src; gkRGB *destRGB = (gkRGB*) dest; int error = 0; while(pixels--){ *(destRGB++) = *srcRGB; error += ratio; srcRGB += error >> 8; error &= 0xff; } }
23.653318
80
0.551541
AbePralle
c4b50bedc3bb54bfbb59187ee501a5282bf48997
9,085
cpp
C++
src/stream/analysis/RtCurrentActivation.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
7
2015-02-10T17:00:49.000Z
2021-07-27T22:09:43.000Z
src/stream/analysis/RtCurrentActivation.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
11
2015-02-22T19:15:53.000Z
2021-08-04T17:26:18.000Z
src/stream/analysis/RtCurrentActivation.cpp
cdla/murfi2
45dba5eb90e7f573f01706a50e584265f0f8ffa7
[ "Apache-2.0" ]
8
2015-07-06T22:31:51.000Z
2019-04-22T21:22:07.000Z
/*========================================================================= * RtCurrentActivation.cpp is the implementation of a class * * ****************************************************************************/ #include "RtDesignMatrix.h" #include"RtCurrentActivation.h" #include"RtMRIImage.h" #include"RtActivation.h" #include"RtDataIDs.h" #include"RtExperiment.h" #include"RtElementAccess.h" #include"util/timer/timer.h" #include"debug_levels.h" string RtCurrentActivation::moduleString(ID_CURRENTACTIVATION); // default constructor RtCurrentActivation::RtCurrentActivation() : RtStreamComponent() { componentID = moduleString; steadyStateResidual = NULL; numDataPointsForErrEst = std::numeric_limits<unsigned int>::max(); } // destructor RtCurrentActivation::~RtCurrentActivation() { } // initialize the estimation algorithm for a particular image size void RtCurrentActivation::initEstimation(RtMRIImage &dat, RtMaskImage *mask) { } // process an option in name of the option to process val text of the option // node bool RtCurrentActivation::processOption(const string &name, const string &text, const map<string, string> &attrMap) { // look for known options if (name == "modelFitModuleID") { modelFitModuleID = text; return true; } if (name == "modelFitRoiID") { modelFitRoiID = text; return true; } if (name == "numDataPointsForErrEst") { return RtConfigVal::convert<unsigned int>(numDataPointsForErrEst, text); } if (name == "saveResult") { return RtConfigVal::convert<bool>(saveResult, text); } return RtStreamComponent::processOption(name, text, attrMap); } // validate the configuration bool RtCurrentActivation::validateComponentConfig() { bool result = true; if (modelFitModuleID.empty()) { cerr << "RtCurrentActivation::process: modelFitModuleID is empty" << endl; result = false; } if (modelFitRoiID.empty()) { cerr << "RtCurrentActivation::process: modelFitRoiID is empty" << endl; result = false; } return result; } // process a single acquisition int RtCurrentActivation::process(ACE_Message_Block *mb) { ACE_TRACE(("RtCurrentActivation::process")); timer tim; if(printTiming) { tim.start(); } // get pointer to message RtStreamMessage *msg = (RtStreamMessage*) mb->rd_ptr(); // get the current image to operate on RtMRIImage *dat = (RtMRIImage*) msg->getCurrentData(); // check for validity of data if (dat == NULL) { cerr << "RtCurrentActivation::process: data passed is NULL" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: data passed is NULL" << endl; log(logs); } return 0; } // get mask from msg RtMaskImage *mask = getMaskFromMessage(*msg); // check validity of mask if (mask == NULL) { cerr << "RtCurrentActivation::process: mask is NULL" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: mask is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } // initialize the computation if necessary if (needsInit) { initEstimation(*dat, mask); } // get design // TODO this may not work if there are more than one design matrix RtDataID tempDataID; tempDataID.setDataName(NAME_DESIGN); // debug // getDataStore().getAvailableData(); RtDesignMatrix *design = static_cast<RtDesignMatrix*>( getDataStore().getData(tempDataID)); if(design == NULL) { cerr << "error: could not find design matrix in datastore!" << endl; cerr << "searched for design matrix id: " << tempDataID << endl; return 0; } // allocate a new data image for the stats RtActivation *currentActivation = new RtActivation(*dat); // setup the data id currentActivation->getDataID().setFromInputData(*dat, *this); currentActivation->getDataID().setDataName(NAME_ACTIVATION); currentActivation->getDataID().setRoiID(modelFitRoiID); currentActivation->initToNans(); // get the residual and the beta images for discounting nuissance // signals // find the betas RtActivation **betas = new RtActivation*[design->getNumColumns()]; for(unsigned int j = 0; j < design->getNumColumns(); j++) { betas[j] = (RtActivation*) msg->getData(modelFitModuleID, string(NAME_BETA) + "_" + design->getColumnName(j), modelFitRoiID); // check for found if (betas[j] == NULL) { cerr << "RtCurrentActivation:process: beta " << j << " is null" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: beta " << j << " is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } } // get residual from message if timepoint is less than // numDataPointsForErrEst otherwise use the steady state // residual value RtActivation *residual; if (dat->getDataID().getTimePoint() < numDataPointsForErrEst) { // get residual off of msg residual = (RtActivation *) msg->getData(modelFitModuleID, NAME_RESIDUAL_MSE, modelFitRoiID); // save off residual steadyStateResidual = residual; } else { // post-numDataPointsForErrEst, use saved residual residual = steadyStateResidual; } // check that residual is not null if (residual == NULL) { cerr << "RtCurrentActivation:process: residual is null" << endl; if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation::process: residual is NULL at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } return 0; } // get this design matrix row vnl_vector<double> Xrow = design->getRow(dat->getDataID().getTimePoint()-1); // include this timepoint for each voxel RtElementAccess datAc(dat, mask); RtElementAccess resAc(residual, mask); vector<unsigned int> inds = datAc.getElementIndices(); for(vector<unsigned int>::iterator it = inds.begin(); it != inds.end(); it++) { // get voxel intensity double y = datAc.getDoubleElement(*it); double *betavals = new double[Xrow.size()]; // compute error double err = y; for (unsigned int j = 0; j < Xrow.size(); j++) { if (!design->isColumnOfInterest(j)) { double beta = betas[j]->getPixel(*it); err -= beta * Xrow[j]; betavals[j] = beta; } else { // for debug output betavals[j] = betas[j]->getPixel(*it); } } // compute the dev and current activation (magic happens here) double dev = sqrt(resAc.getDoubleElement(*it) / (residual->getDataID().getTimePoint())); currentActivation->setPixel(*it, err / dev); if (dumpAlgoVars && dat->getDataID().getTimePoint() > 2) { dumpFile << dat->getDataID().getTimePoint() << " " << *it << " " << y << " " << err << " " << Xrow[0] << " " << residual->getPixel(*it) << " " << dev << " " << currentActivation->getPixel(*it) << " "; for (unsigned int b = 0; b < design->getNumColumns(); b++) { dumpFile << betavals[b] << " "; } dumpFile << endl; } delete [] betavals; } setResult(msg, currentActivation); setResult(msg, residual); delete [] betas; if(printTiming) { tim.stop(); cout << "RtCurrentActivation process at tr " << dat->getDataID().getTimePoint() << " elapsed time: " << tim.elapsed_time()*1000 << "ms" << endl; } if(print) { cout << "RtCurrentActivation: done at tr " << dat->getDataID().getTimePoint() << endl; } if(logOutput) { stringstream logs(""); logs << "RtCurrentActivation: done at tr " << dat->getDataID().getTimePoint() << endl; log(logs); } if(saveResult) { string fn = getExperimentConfig().getVolFilename( dat->getDataID().getSeriesNum(), dat->getDataID().getTimePoint()); string stem = getExperimentConfig().get("study:volumeFileStem").str(); currentActivation->setFilename(fn.replace(fn.rfind(stem), stem.size(), "curact")); currentActivation->save(); } return 0; } // start a logfile void RtCurrentActivation::startDumpAlgoVarsFile() { dumpFile << "started at "; printNow(dumpFile); dumpFile << endl << "time_point " << "voxel_index " << "voxel_intensity " << "activation_signal " << "condition " << "residual " << "dev " << "current_activation "; // aka feedback for (int b = 0; b < 3; b++) { dumpFile << "beta[" << b << "] "; } dumpFile << "end" << endl; }
28.126935
80
0.597248
cdla
c4b5f33b24aadde546c1b0caea909adc5cbeaf3b
4,387
cpp
C++
csrc/codebase/mmocr/psenet.cpp
grimoire/mmdeploy
e84bc30f4a036dd19cb3af854203922a91098e84
[ "Apache-2.0" ]
746
2021-12-27T10:50:28.000Z
2022-03-31T13:34:14.000Z
csrc/codebase/mmocr/psenet.cpp
grimoire/mmdeploy
e84bc30f4a036dd19cb3af854203922a91098e84
[ "Apache-2.0" ]
253
2021-12-28T05:59:13.000Z
2022-03-31T18:22:25.000Z
csrc/codebase/mmocr/psenet.cpp
grimoire/mmdeploy
e84bc30f4a036dd19cb3af854203922a91098e84
[ "Apache-2.0" ]
147
2021-12-27T10:50:33.000Z
2022-03-30T10:44:20.000Z
// Copyright (c) OpenMMLab. All rights reserved. #include "codebase/mmocr/psenet.h" #include <algorithm> #include <opencv2/opencv.hpp> #include "codebase/mmocr/mmocr.h" #include "core/device.h" #include "core/registry.h" #include "core/serialization.h" #include "core/utils/device_utils.h" namespace mmdeploy { namespace mmocr { void contour_expand(const cv::Mat_<uint8_t>& kernel_masks, const cv::Mat_<int32_t>& kernel_label, const cv::Mat_<float>& score, int min_kernel_area, int kernel_num, std::vector<int>& text_areas, std::vector<float>& text_scores, std::vector<std::vector<int>>& text_points); class PSEHead : public MMOCR { public: explicit PSEHead(const Value& config) : MMOCR(config) { if (config.contains("params")) { auto& params = config["params"]; min_kernel_confidence_ = params.value("min_kernel_confidence", min_kernel_confidence_); min_text_avg_confidence_ = params.value("min_text_avg_confidence", min_text_avg_confidence_); min_kernel_area_ = params.value("min_kernel_area", min_kernel_area_); min_text_area_ = params.value("min_text_area", min_text_area_); rescale_ = params.value("rescale", rescale_); downsample_ratio_ = params.value("downsample_ratio", downsample_ratio_); } auto platform = Platform(device_.platform_id()).GetPlatformName(); auto creator = Registry<PseHeadImpl>::Get().GetCreator(platform); if (!creator) { MMDEPLOY_ERROR("PSEHead: implementation for platform \"{}\" not found", platform); throw_exception(eEntryNotFound); } impl_ = creator->Create(nullptr); impl_->Init(stream_); } Result<Value> operator()(const Value& _data, const Value& _pred) noexcept { auto _preds = _pred["output"].get<Tensor>(); if (_preds.shape().size() != 4 || _preds.shape(0) != 1 || _preds.data_type() != DataType::kFLOAT) { MMDEPLOY_ERROR("unsupported `output` tensor, shape: {}, dtype: {}", _preds.shape(), (int)_preds.data_type()); return Status(eNotSupported); } // drop batch dimension _preds.Squeeze(); cv::Mat_<uint8_t> masks; cv::Mat_<int> kernel_labels; cv::Mat_<float> score; int region_num = 0; OUTCOME_TRY( impl_->Process(_preds, min_kernel_confidence_, score, masks, kernel_labels, region_num)); std::vector<int> text_areas; std::vector<float> text_scores; std::vector<std::vector<int>> text_points; contour_expand(masks.rowRange(1, masks.rows), kernel_labels, score, min_kernel_area_, region_num, text_areas, text_scores, text_points); auto scale_w = _data["img_metas"]["scale_factor"][0].get<float>(); auto scale_h = _data["img_metas"]["scale_factor"][1].get<float>(); TextDetectorOutput output; for (int text_index = 1; text_index < region_num; ++text_index) { auto& text_point = text_points[text_index]; auto text_confidence = text_scores[text_index]; auto area = text_areas[text_index]; if (filter_instance(static_cast<float>(area), text_confidence, min_text_area_, min_text_avg_confidence_)) { continue; } cv::Mat_<int> points(text_point.size() / 2, 2, text_point.data()); cv::RotatedRect rect = cv::minAreaRect(points); std::vector<cv::Point2f> vertices(4); rect.points(vertices.data()); if (rescale_) { for (auto& p : vertices) { p.x /= scale_w * downsample_ratio_; p.y /= scale_h * downsample_ratio_; } } auto& bbox = output.boxes.emplace_back(); for (int i = 0; i < 4; ++i) { bbox[i * 2] = vertices[i].x; bbox[i * 2 + 1] = vertices[i].y; } output.scores.push_back(text_confidence); } return to_value(output); } static bool filter_instance(float area, float confidence, float min_area, float min_confidence) { return area < min_area || confidence < min_confidence; } float min_kernel_confidence_{.5f}; float min_text_avg_confidence_{0.85}; int min_kernel_area_{0}; float min_text_area_{16}; bool rescale_{true}; float downsample_ratio_{.25f}; std::unique_ptr<PseHeadImpl> impl_; }; REGISTER_CODEBASE_COMPONENT(MMOCR, PSEHead); } // namespace mmocr MMDEPLOY_DEFINE_REGISTRY(mmocr::PseHeadImpl); } // namespace mmdeploy
34.81746
99
0.664691
grimoire
c4b91738ebc06fe91231e1072a4b65a0566597cb
1,194
cpp
C++
src/pal/tests/palsuite/c_runtime/bsearch/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
159
2020-06-17T01:01:55.000Z
2022-03-28T10:33:37.000Z
src/pal/tests/palsuite/c_runtime/bsearch/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-06-27T01:16:35.000Z
2022-02-06T20:33:24.000Z
src/pal/tests/palsuite/c_runtime/bsearch/test1/test1.cpp
elinor-fung/coreclr
c1801e85024add717f518feb6a9caed60d54500f
[ "MIT" ]
19
2020-05-21T08:18:20.000Z
2021-06-29T01:13:13.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================================ ** ** Source: test1.c ** ** Purpose: Calls bsearch to find a character in a sorted buffer, and ** verifies that the correct position is returned. ** ** **==========================================================================*/ #include <palsuite.h> int __cdecl charcmp(const void *pa, const void *pb) { return memcmp(pa, pb, 1); } int __cdecl main(int argc, char **argv) { const char array[] = "abcdefghij"; char * found=NULL; /* * Initialize the PAL and return FAIL if this fails */ if (0 != (PAL_Initialize(argc, argv))) { return FAIL; } found = (char *)bsearch(&"d", array, sizeof(array) - 1, (sizeof(char)) , charcmp); if (found != array + 3) { Fail ("bsearch was unable to find a specified character in a " "sorted list.\n"); } PAL_Terminate(); return PASS; }
24.367347
78
0.519263
elinor-fung
c4bb7bcf6cb57c5008a5ca159b67cd36398adc91
5,164
cpp
C++
mods/core/objects/freeverb/ReverbModel.cpp
antisvin/er-301
54d1e553651b5b653afa318189d813f0b7e12a96
[ "MIT" ]
102
2021-03-01T10:39:56.000Z
2022-03-31T00:28:15.000Z
mods/core/objects/freeverb/ReverbModel.cpp
antisvin/er-301
54d1e553651b5b653afa318189d813f0b7e12a96
[ "MIT" ]
62
2021-03-01T19:38:54.000Z
2022-03-21T00:51:24.000Z
mods/core/objects/freeverb/ReverbModel.cpp
antisvin/er-301
54d1e553651b5b653afa318189d813f0b7e12a96
[ "MIT" ]
19
2021-03-01T19:52:10.000Z
2021-07-29T03:25:19.000Z
/* * ReverbModel.cpp * * Created on: 12 Dec 2017 * Author: clarkson */ #include <core/objects/freeverb/ReverbModel.h> #include <od/config.h> #include <hal/simd.h> namespace od { ReverbModel::ReverbModel() { comb[0].setLeftBuffer(bufcombL1, combtuningL1); comb[0].setRightBuffer(bufcombR1, combtuningR1); comb[1].setLeftBuffer(bufcombL2, combtuningL2); comb[1].setRightBuffer(bufcombR2, combtuningR2); comb[2].setLeftBuffer(bufcombL3, combtuningL3); comb[2].setRightBuffer(bufcombR3, combtuningR3); comb[3].setLeftBuffer(bufcombL4, combtuningL4); comb[3].setRightBuffer(bufcombR4, combtuningR4); comb[4].setLeftBuffer(bufcombL5, combtuningL5); comb[4].setRightBuffer(bufcombR5, combtuningR5); comb[5].setLeftBuffer(bufcombL6, combtuningL6); comb[5].setRightBuffer(bufcombR6, combtuningR6); comb[6].setLeftBuffer(bufcombL7, combtuningL7); comb[6].setRightBuffer(bufcombR7, combtuningR7); comb[7].setLeftBuffer(bufcombL8, combtuningL8); comb[7].setRightBuffer(bufcombR8, combtuningR8); allpass[0].setLeftBuffer(bufallpassL1, allpasstuningL1); allpass[0].setRightBuffer(bufallpassR1, allpasstuningR1); allpass[1].setLeftBuffer(bufallpassL2, allpasstuningL2); allpass[1].setRightBuffer(bufallpassR2, allpasstuningR2); allpass[2].setLeftBuffer(bufallpassL3, allpasstuningL3); allpass[2].setRightBuffer(bufallpassR3, allpasstuningR3); allpass[3].setLeftBuffer(bufallpassL4, allpasstuningL4); allpass[3].setRightBuffer(bufallpassR4, allpasstuningR4); set(initialroom, initialdamp, initialwidth); mute(); } ReverbModel::~ReverbModel() { } inline float32x2_t ReverbModel::processCombPair(float32x2_t input, ReverbModel::combPair &comb) { float32x2_t output = vld1_dup_f32(comb.bufferL + comb.bufidxL); output = vld1_lane_f32(comb.bufferR + comb.bufidxR, output, 1); comb.filterstore = vadd_f32(vmul_f32(output, combDamp2), vmul_f32(comb.filterstore, combDamp1)); float32x2_t bufin = vadd_f32(input, vmul_f32(comb.filterstore, combFeedback)); vst1_lane_f32(comb.bufferL + comb.bufidxL, bufin, 0); vst1_lane_f32(comb.bufferR + comb.bufidxR, bufin, 1); if (++comb.bufidxL >= comb.bufsizeL) comb.bufidxL = 0; if (++comb.bufidxR >= comb.bufsizeR) comb.bufidxR = 0; return output; } inline float32x2_t ReverbModel::processAllPassPair( float32x2_t input, ReverbModel::allpassPair &allpass) { float32x2_t bufout = vld1_dup_f32(allpass.bufferL + allpass.bufidxL); bufout = vld1_lane_f32(allpass.bufferR + allpass.bufidxR, bufout, 1); float32x2_t output = vsub_f32(bufout, input); float32x2_t half = vdup_n_f32(0.5f); float32x2_t bufin = vadd_f32(input, vmul_f32(bufout, half)); vst1_lane_f32(allpass.bufferL + allpass.bufidxL, bufin, 0); vst1_lane_f32(allpass.bufferR + allpass.bufidxR, bufin, 1); if (++allpass.bufidxL >= allpass.bufsizeL) allpass.bufidxL = 0; if (++allpass.bufidxR >= allpass.bufsizeR) allpass.bufidxR = 0; return output; } void ReverbModel::process(float *inputL, float *inputR, float *outputL, float *outputR) { float32x2_t zero = vdup_n_f32(0); float32x2_t mL = vdup_n_f32(mixL); float32x2_t mR = vdup_n_f32(mixR); float32x2_t G = vdup_n_f32(gain); for (int i = 0; i < FRAMELENGTH; i++) { float32x2_t input = vld1_dup_f32(inputL + i); input = vld1_lane_f32(inputR + i, input, 1); input = vmul_f32(input, G); float32x2_t output = zero; for (int j = 0; j < numcombs; j++) { output = vadd_f32(output, processCombPair(input, comb[j])); } for (int j = 0; j < numallpasses; j++) { output = processAllPassPair(output, allpass[j]); } float32x2_t swapped = vrev64_f32(output); output = vadd_f32(vmul_f32(output, mL), vmul_f32(swapped, mR)); vst1_lane_f32(outputL + i, output, 0); vst1_lane_f32(outputR + i, output, 1); } } void ReverbModel::mute() { for (int i = 0; i < numcombs; i++) { comb[i].mute(); comb[i].filterstore = vdup_n_f32(0); } for (int i = 0; i < numallpasses; i++) { allpass[i].mute(); } } void ReverbModel::update() { // Recalculate internal values after parameter change mixL = (width / 2 + 0.5f); mixR = ((1 - width) / 2); if (freeze) { roomsize1 = 1; damp1 = 0; gain = muted; } else { roomsize1 = roomsize; damp1 = damp; gain = fixedgain; } combFeedback = vdup_n_f32(roomsize1); combDamp1 = vdup_n_f32(damp1); combDamp2 = vdup_n_f32(1 - damp1); } void ReverbModel::set(float _size, float _damp, float _width) { roomsize = (_size * scaleroom) + offsetroom; damp = _damp * scaledamp; width = _width; update(); } } /* namespace od */
29.849711
101
0.634005
antisvin
c4bcd09ca73577998542021179cf2f89915ab43c
2,579
hpp
C++
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
src/backend/graph_compiler/core/src/compiler/ir/graph/tunable_op.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2020-2022 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_IR_GRAPH_TUNABLE_OP_HPP #define BACKEND_GRAPH_COMPILER_CORE_SRC_COMPILER_IR_GRAPH_TUNABLE_OP_HPP #include <algorithm> #include <memory> #include <string> #include <vector> #include <compiler/ir/graph/graph.hpp> #include <compiler/ir/graph/trait/configurable.hpp> #include <compiler/ir/graph/traits.hpp> #include <ops/body_generator.hpp> #include <util/utils.hpp> namespace sc { class SC_INTERNAL_API tunable_op_t : public sc_op, public op_traits::copyable_t, public op_traits::may_quantize_t, public op_traits::post_fusion_acceptable_t, public op_traits::configurable_t { public: tunable_op_t(const std::string &op_name, const std::vector<graph_tensor_ptr> &ins, const std::vector<graph_tensor_ptr> &outs, const any_map_t &attrs); sc_op_ptr copy(const std::vector<graph_tensor_ptr> &ins, const std::vector<graph_tensor_ptr> &outs, sc_graph_t &mgr) override; bool is_valid(const context_ptr &) override; ir_module_ptr get_func(context_ptr ctx, const std::shared_ptr<fusion_manager> &fuse_mgr, const std::string &func_name) override { throw std::runtime_error("unimplemented"); } ir_module_ptr get_func(context_ptr ctx) override; config_ptr get_config() override { return config_data_; } void set_config(const config_ptr &config) override; void set_config_if_empty(context_ptr ctx, body_generator_base_t *p); config_ptr get_default_config(context_ptr ctx) override; virtual body_generator_ptr create_generator() = 0; protected: config_ptr config_data_; }; } // namespace sc #endif
36.842857
81
0.659558
wuxun-zhang
c4bff15003d2c1ed21acb480e4e4e50165c28f2d
5,568
cpp
C++
wallet/unittests/util.cpp
akhavr/beam
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
[ "Apache-2.0" ]
null
null
null
wallet/unittests/util.cpp
akhavr/beam
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
[ "Apache-2.0" ]
null
null
null
wallet/unittests/util.cpp
akhavr/beam
99e427f6ba0a0ee1a0dbe598d0fa6d642e571d62
[ "Apache-2.0" ]
null
null
null
#include "util.h" #include "wallet/wallet.h" #include "core/ecc_native.h" #include "core/serialization_adapters.h" #include "utility/logger.h" #include <boost/filesystem.hpp> #include <iterator> #include <future> using namespace std; using namespace beam; using namespace ECC; namespace beam { struct TreasuryBlockGenerator { std::string m_sPath; IKeyChain* m_pKeyChain; std::vector<Block::Body> m_vBlocks; ECC::Scalar::Native m_Offset; std::vector<Coin> m_Coins; std::vector<std::pair<Height, ECC::Scalar::Native> > m_vIncubationAndKeys; std::mutex m_Mutex; std::vector<std::thread> m_vThreads; Block::Body& get_WriteBlock(); void FinishLastBlock(); int Generate(uint32_t nCount, Height dh); private: void Proceed(uint32_t i); }; bool ReadTreasury(std::vector<Block::Body>& vBlocks, const string& sPath) { if (sPath.empty()) return false; std::FStream f; if (!f.Open(sPath.c_str(), true)) return false; yas::binary_iarchive<std::FStream, SERIALIZE_OPTIONS> arc(f); arc & vBlocks; return true; } int TreasuryBlockGenerator::Generate(uint32_t nCount, Height dh) { if (m_sPath.empty()) { LOG_ERROR() << "Treasury block path not specified"; return -1; } boost::filesystem::path path{ m_sPath }; boost::filesystem::path dir = path.parent_path(); if (!dir.empty() && !boost::filesystem::exists(dir) && !boost::filesystem::create_directory(dir)) { LOG_ERROR() << "Failed to create directory: " << dir.c_str(); return -1; } if (ReadTreasury(m_vBlocks, m_sPath)) LOG_INFO() << "Treasury already contains " << m_vBlocks.size() << " blocks, appending."; if (!m_vBlocks.empty()) { m_Offset = m_vBlocks.back().m_Offset; m_Offset = -m_Offset; } LOG_INFO() << "Generating coins..."; m_Coins.resize(nCount); m_vIncubationAndKeys.resize(nCount); Height h = 0; for (uint32_t i = 0; i < nCount; i++, h += dh) { Coin& coin = m_Coins[i]; coin.m_key_type = KeyType::Regular; coin.m_amount = Rules::Coin * 10; coin.m_status = Coin::Unconfirmed; coin.m_createHeight = h + Rules::HeightGenesis; m_vIncubationAndKeys[i].first = h; } m_pKeyChain->store(m_Coins); // we get coin id only after store for (uint32_t i = 0; i < nCount; ++i) m_vIncubationAndKeys[i].second = m_pKeyChain->calcKey(m_Coins[i]); m_vThreads.resize(std::thread::hardware_concurrency()); assert(!m_vThreads.empty()); for (uint32_t i = 0; i < m_vThreads.size(); i++) m_vThreads[i] = std::thread(&TreasuryBlockGenerator::Proceed, this, i); for (uint32_t i = 0; i < m_vThreads.size(); i++) m_vThreads[i].join(); // at least 1 kernel { Coin dummy; // not a coin actually dummy.m_key_type = KeyType::Kernel; dummy.m_status = Coin::Unconfirmed; ECC::Scalar::Native k = m_pKeyChain->calcKey(dummy); TxKernel::Ptr pKrn(new TxKernel); pKrn->m_Excess = ECC::Point::Native(Context::get().G * k); Merkle::Hash hv; pKrn->get_Hash(hv); pKrn->m_Signature.Sign(hv, k); get_WriteBlock().m_vKernelsOutput.push_back(std::move(pKrn)); m_Offset += k; } FinishLastBlock(); for (auto i = 0u; i < m_vBlocks.size(); i++) { m_vBlocks[i].Sort(); m_vBlocks[i].DeleteIntermediateOutputs(); } std::FStream f; f.Open(m_sPath.c_str(), false, true); yas::binary_oarchive<std::FStream, SERIALIZE_OPTIONS> arc(f); arc & m_vBlocks; f.Flush(); /* for (auto i = 0; i < m_vBlocks.size(); i++) m_vBlocks[i].IsValid(i + 1, true); */ LOG_INFO() << "Done"; return 0; } void TreasuryBlockGenerator::FinishLastBlock() { m_Offset = -m_Offset; m_vBlocks.back().m_Offset = m_Offset; } Block::Body& TreasuryBlockGenerator::get_WriteBlock() { if (m_vBlocks.empty() || m_vBlocks.back().m_vOutputs.size() >= 1000) { if (!m_vBlocks.empty()) FinishLastBlock(); m_vBlocks.resize(m_vBlocks.size() + 1); m_vBlocks.back().ZeroInit(); m_Offset = Zero; } return m_vBlocks.back(); } void TreasuryBlockGenerator::Proceed(uint32_t i0) { std::vector<Output::Ptr> vOut; for (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size()) { const Coin& coin = m_Coins[i]; Output::Ptr pOutp(new Output); pOutp->m_Incubation = m_vIncubationAndKeys[i].first; const ECC::Scalar::Native& k = m_vIncubationAndKeys[i].second; pOutp->Create(k, coin.m_amount); vOut.push_back(std::move(pOutp)); //offset += k; //subBlock.m_Subsidy += coin.m_amount; } std::unique_lock<std::mutex> scope(m_Mutex); uint32_t iOutp = 0; for (uint32_t i = i0; i < m_Coins.size(); i += m_vThreads.size(), iOutp++) { Block::Body& block = get_WriteBlock(); block.m_vOutputs.push_back(std::move(vOut[iOutp])); block.m_Subsidy += m_Coins[i].m_amount; m_Offset += m_vIncubationAndKeys[i].second; } } IKeyChain::Ptr init_keychain(const std::string& path, uintBig* walletSeed) { static const std::string TEST_PASSWORD("12321"); if (boost::filesystem::exists(path)) boost::filesystem::remove_all(path); std::string password(TEST_PASSWORD); password += path; NoLeak<uintBig> seed; Hash::Value hv; Hash::Processor() << password.c_str() >> hv; seed.V = hv; auto keychain = Keychain::init(path, password, seed); if (walletSeed) { TreasuryBlockGenerator tbg; tbg.m_sPath = path + "_"; tbg.m_pKeyChain = keychain.get(); Height dh = 1; uint32_t nCount = 10; tbg.Generate(nCount, dh); *walletSeed = seed.V; } return keychain; } } //namespace std::ostream& operator<<(std::ostream& os, const ECC::Scalar::Native& sn) { Scalar s; sn.Export(s); os << s.m_Value; return os; }
22.91358
98
0.670079
akhavr
c4c0b522503bdaa8f32bdc1d1d27962a548fc734
1,470
cc
C++
grey_level_histogram.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
6
2019-03-06T23:54:01.000Z
2020-08-24T09:18:33.000Z
grey_level_histogram.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
6
2019-03-07T00:31:48.000Z
2021-01-10T13:28:41.000Z
grey_level_histogram.cc
jkloe/pageDistanceBasedContourGenerator
92e8768b596c98ffc09f4b5eeb7db8aafccda01a
[ "MIT" ]
8
2019-03-07T00:08:43.000Z
2021-05-13T12:14:08.000Z
#include "grey_level_histogram.hpp" namespace prhlt{ using namespace log4cxx; using namespace log4cxx::helpers; using namespace boost; Grey_Level_Histogram::Grey_Level_Histogram(){ this->logger = Logger::getLogger("PRHLT.Grey_Level_Histogram"); } Grey_Level_Histogram::Grey_Level_Histogram(cv::Mat &ex_image){ this->logger = Logger::getLogger("PRHLT.Grey_Level_Histogram"); this->image = ex_image; } Grey_Level_Histogram::~Grey_Level_Histogram(){ this->image.release(); this->histogram.clear(); } void Grey_Level_Histogram::set_image(cv::Mat &ex_image){ this->image = ex_image; } float Grey_Level_Histogram::run(){ return calculate_grey_level_histogram(); } float Grey_Level_Histogram::calculate_grey_level_histogram(){ this->histogram_sum = 0.0; for (int r=0; r < this->image.rows; r++) for (int c=0; c < this->image.cols; c++) this->histogram[this->image.at<uchar>(r,c)]+=1.0; int num_pixels = this->image.rows * this->image.cols; BOOST_FOREACH(sparse_histogram::value_type i, this->histogram){ this->histogram[i.first]= i.second/num_pixels; } BOOST_FOREACH(sparse_histogram::value_type i, this->histogram){ this->histogram_sum+= i.first * i.second; } return this->histogram_sum; } }
31.956522
71
0.619048
jkloe
c4c2b2870bd19b8d68185006073038d950283086
1,504
cpp
C++
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
1
2020-11-02T22:18:22.000Z
2020-11-02T22:18:22.000Z
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
Uva-10948 - The primary problem.cpp
Samim-Arefin/UVa-Problem-Solution
8556639b9e718299f4a52920034dfa0264e06f8e
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #define Max 1000001 std::bitset<Max> arr; std::vector<int> prime; void sieve() { arr[0]=true; arr[1]=true; for(int i=4;i<=Max;i+=2) { arr[i]=true; } for(int i=3;i*i<=Max;i++) { if(arr[i]==false) { for(int j=i*i;j<=Max;j+=i+i) { arr[j]=true; } } } prime.push_back(2); for(int i=3;i<=Max;i+=2) { if(arr[i]==false) { prime.push_back(i); } } } int main() { sieve(); freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); int num; while(std::cin>>num,num>0) { int beg=0,end=prime.size()-1,maximum=INT_MIN,a,b; bool check=false; while(beg<=end) { if((prime[beg]+prime[end])==num) { if((prime[end]-prime[beg])>maximum) { a=prime[beg]; b=prime[end]; maximum=(prime[end]-prime[beg]); check=true; break; } } else if((prime[beg]+prime[end])<num) { beg++; } else { end--; } } if(check==true) { std::cout<<num<<":\n"<<a<<"+"<<b<<'\n'; } else { std::cout<<num<<":\nNO WAY!\n"; } } }
19.282051
57
0.357713
Samim-Arefin
c4c3d286892a809e310541e6850a867b3a052036
7,599
hpp
C++
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
5
2015-08-02T03:10:26.000Z
2018-01-16T01:07:55.000Z
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
null
null
null
skynet/core/neighbor.hpp
zhangzhimin/skynet
a311b86433821a071002dd279d57333baba1f973
[ "MIT" ]
null
null
null
#pragma once #include <stdexcept> #include <array> #include <skynet/core/adaptor_types.hpp> namespace skynet{ template <typename B, typename size_t dim> class neighbor_adaptor : public iterator_adaptor<B> { public: typedef B neighbor_type; typedef point<size_t, dim> extent_type; typedef ptrdiff_t value_type; typedef const value_type & reference; typedef const value_type & const_reference; ptrdiff_t max_offset() const { return *std::max_element(begin(), end()); } ptrdiff_t min_offset() const { return *std::min_element(begin(), end()); } }; // * // * o * // * //It's the diamand_neighbors, star is neighbor, o is origin. template <typename size_t dim> class diamand_neighbor: public neighbor_adaptor<diamand_neighbor<dim>, dim>{ public: static const size_t neighbor_num = dim * 2; diamand_neighbor(){} diamand_neighbor &operator=(const diamand_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &size){ _extent = size; _offsets[0] = 1; _offsets[0+dim] = -1; for (int i = 1; i < dim; ++i){ _offsets[i] = _offsets[i-1] * _extent[i-1]; _offsets[i + dim] = -_offsets[i]; } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<ptrdiff_t, neighbor_num> _offsets; }; /* * * * * * It's the vertex_neighbors */ template <typename size_t dim> class vertex_neighbor: public neighbor_adaptor<vertex_neighbor<dim>,dim>{ public: static const size_t neighbor_num = extent_type::dim * 2 + 1; vertex_neighbor() {} vertex_neighbor(const int &r) : _radius(r){} vertex_neighbor &operator=(const vertex_neighbor &rhs){ this->rhs._radius; this->_extent = rhs._extent; this->_offsets = rhs._offsets; return *this; } const int &operator [](const size_t &index) const{ return _offsets[index]; } void attach(const extent_type &size) { _extent = size; _offsets[0] = _radius; _offsets[0+dim] = -_radius; _offsets[neighbor_num - 1] = 0; for (int i = 1; i < dim; ++i){ _offsets[i] = _offsets[i-1] * _extent[i-1]; _offsets[i + dim] = -_offsets[i]; } }; int get_radius(){ return _radius; } size_t size() const { return neighbor_num; } private: int _radius; extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <typename size_t dim_> class square_neighbor; template <> class square_neighbor<3>: public neighbor_adaptor<square_neighbor<3>, 3>{ public: static const size_t neighbor_num = 26; square_neighbor(){} square_neighbor &operator=(const square_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int shift_2 = get_slice_size(_extent); int pos = 0; for (int page = -1; page <= 1; ++page){ for (int row = -1; row <= 1; ++row){ for (int col = -1; col <= 1; ++col){ if (page == 0 && row == 0 && col == 0) continue; _offsets[pos] = col * shift_0 + row * shift_1 + page * shift_2; ++pos; } } } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <> class square_neighbor<2> : public neighbor_adaptor<square_neighbor<2>,2> { public: static const size_t neighbor_num = 8; square_neighbor(){} square_neighbor &operator=(const square_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int pos = 0; for (int row = -1; row <= 1; ++row){ for (int col = -1; col <= 1; ++col){ if (row == 0 && col == 0) continue; _offsets[pos] = col * shift_0 + row * shift_1; ++pos; } } } const int &operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return neighbor_num; } private: extent_type _extent; std::array<int, neighbor_num> _offsets; }; template <typename size_t dim_> class cube_neighbor; template <> class cube_neighbor<3>: public neighbor_adaptor<cube_neighbor<3>,3>{ public: cube_neighbor &operator=(const cube_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } cube_neighbor(const int radius = 1): _radius(radius){} void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; int shift_2 = get_slice_size(_extent); for (int page = -_radius; page <= _radius; ++page){ for (int row = -_radius; row <= _radius; ++row){ for (int col = -_radius; col <= _radius; ++col){ _offsets.push_back(col * shift_0 + row * shift_1 + page * shift_2); } } } } const int operator[](const size_t &index) const{ return _offsets[index]; } size_t size()const { return _offsets.size(); } private: extent_type _extent; std::vector<size_t> _offsets; int _radius; }; template <> class cube_neighbor<2>: public neighbor_adaptor<cube_neighbor<2>, 2>{ public: cube_neighbor &operator=(const cube_neighbor &rhs){ _extent = rhs._extent; _offsets = rhs._offsets; return *this; } cube_neighbor(const int radius = 1): _radius(radius){ // attach(extent); } void attach(const extent_type &extent){ _extent = extent; int shift_0 = 1; int shift_1 = _extent[0]; for (int row = -_radius; row <= _radius; ++row){ for (int col = -_radius; col <= _radius; ++col){ _offsets.push_back(col * shift_0 + row * shift_1); } } } const_reference operator[](const size_t &index) const{ return _offsets[index]; } size_t size() const { return _offsets.size(); } private: extent_type _extent; std::vector<size_t> _offsets; int _radius; }; template <size_t dim, typename Func> class custom_neighbor: public neighbor_adaptor<custom_neighbor<dim, Func>, dim>{ public: custom_neighbor(Func fun): _fun(fun) {} void attach(extent_type extent) { _fun(extent, std::ref(_offsets)); } const_reference operator[](size_t i) const { return _offsets[i]; } size_t size() const { return _offsets.size(); } public: extent_type _extent; std::vector<value_type> _offsets; Func _fun; }; template <size_t dim, typename Func> auto customize_neighbor(Func fun) { return custom_neighbor<dim, Func>(fun); } template <typename N, typename Func> void traverse_neighbors(const size_t &base, const N &neighbors, Func fun){ for (auto it = neighbors.begin(); it != neighbors.end(); ++it){ fun(base+(*it)); } } // }
24.12381
86
0.59521
zhangzhimin
c4c40717df4ee6e78b86d36465ce363f30d83772
872
cpp
C++
PAT/group_tianti/L1-007.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
1
2021-02-20T00:14:35.000Z
2021-02-20T00:14:35.000Z
PAT/group_tianti/L1-007.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
PAT/group_tianti/L1-007.cpp
haohaibo/learn
7a30489e76abeda1465fe610b1c5cf4c4de7e3b6
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; typedef struct { string pinyin; } NUMBER; int main() { NUMBER *Number = new NUMBER[10]; Number[0].pinyin = "ling"; Number[1].pinyin = "yi"; Number[2].pinyin = "er"; Number[3].pinyin = "san"; Number[4].pinyin = "si"; Number[5].pinyin = "wu"; Number[6].pinyin = "liu"; Number[7].pinyin = "qi"; Number[8].pinyin = "ba"; Number[9].pinyin = "jiu"; string input; cin >> input; for (int i = 0; i < input.size(); ++i) { if (i < input.size() - 1) { if (input[i] == '-') { cout << "fu "; } else { cout << Number[(int)(input[i] - '0')].pinyin << " "; } } else { if (input[i] == '-') { cout << "fu" << endl; } else { cout << Number[(int)(input[i] - '0')].pinyin << endl; } } } return 0; }
21.8
61
0.49656
haohaibo
c4c44ddee8bb17913f409a00a1b803ee5e5179a0
5,024
hh
C++
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
source/PPUtils/uniformobjectpool.hh
PerttuP/PPUtils
97971d6e2b662bab9a4966b4c39ac59509c01359
[ "MIT" ]
null
null
null
/* uniformobjectpool.hh * This header file defines the PPUtils::UniformObjectPool class template. This * class template can be used as a storage for complex objects or as a builder * class. * * Author: Perttu Paarlahti perttu.paarlahti@gmail.com * Created: 29-June-2015 */ #ifndef UNIFORMOBJECTPOOL_HH #define UNIFORMOBJECTPOOL_HH #include <vector> #include <memory> #include <functional> namespace PPUtils { /*! * \brief The UniformObjectPool class * This is a generic object pool. It may be used for storing complex objects * when repeatly constructing them would be too expensive. It may also used as * a builder/factory class. * * Note that there is no segmentation among stored objects i.e. all stored * objects are concerned equal and user cannot choose which kind of object he * is going to get next. If this kind of functionality is desired, use * ObjectPool instead. Objects are stored in their current state, so make sure * that stored objects are in a re-usable state when released to the pool * (or alternatively re-initialize all objects after reserveing them). * * This version of object pool is not thread safe. Use this version only from * one thread. If you need to access object pool from multiple threads, use * ConcurrentUniformObjectPool instead. * * Type arguments: * \p T: Type of stored objects. * * \p Builder: A functor class that is used to construct new objects when * needed. Builder must provide a function operator taking no arguments and * returning a dynamically allocated T-object. */ template <class T, class Builder = typename std::function<T*()> > class UniformObjectPool { public: /*! * \brief Constructor * \param builder Builder object that will be used to construct new objects. * Ownership of builder is passed to this object. * \pre builder != nullptr. */ explicit UniformObjectPool(Builder* builder); /*! * \brief Constructor * \param builder Builder object that will be used to construct new objects. * This object uses a copy of builder to do so (Builder must be * copy-constructible). */ explicit UniformObjectPool(const Builder& builder = DEFAULT_BUILDER); /*! * \brief Destructor destroys the pool and all its currently stored objects. */ virtual ~UniformObjectPool(); /*! * \brief Copy-constructor is forbidden. */ UniformObjectPool(const UniformObjectPool&) = delete; /*! * \brief Move-constructor. * \param other Moved object. * \pre None. * \post This object has the state that \p other used to have. \p other * is left into an unspecified. */ UniformObjectPool(UniformObjectPool&& other) noexcept; /*! * \brief Assignment operator is forbidden. */ UniformObjectPool& operator = (const UniformObjectPool&) = delete; /*! * \brief Move-assignment operator. * \param other Moved object. * \return Reference to this object. * \pre None. * \post This object has the state that \p other used to have. \p other * is left into a unspecified but valid state. */ UniformObjectPool& operator = (UniformObjectPool&& other) noexcept; /*! * \brief Reserve next object from pool. * \return Unique pointer to reserved object. Returned object may be re-used * or constructed using Builder. * \pre None. */ virtual typename std::unique_ptr<T> reserve(); /*! * \brief Return object (back) to the pool. * \param object Object returned to the pool. Object may be reserved from * the pool earlier or constructed other way. * \pre object != nullptr. * \post Object is stored in the pool and may be re-used calling the reserve * method. Object is stored in its current state. */ virtual void release(typename std::unique_ptr<T>&& object); /*! * \brief Return number of objects currently stored in the pool. * \pre None. */ virtual unsigned size() const final; /*! * \brief Destroy all objects currently stored in the pool. * \pre None. * \post All currently stored objects are destoyed and pool contains no * re-usable objects. */ virtual void clear(); protected: /*! * \brief DEFAULT_BUILDER * This functor constructs stored objects using their default constructor. * Instantiating this functor requires \p T to be default constructible. */ static const typename std::function<T*()> DEFAULT_BUILDER; /*! * \brief Returns pointer to the Builder object. * \pre None. */ Builder* getBuilder() const; private: typename std::vector<std::unique_ptr<T> > objects_; std::unique_ptr<Builder> builder_; }; } // Namespace PPUtils // Include template implementations. #include "uniformobjectpool_impl.hh" #endif // UNIFORMOBJECTPOOL_HH
31.204969
80
0.669785
PerttuP
c4c98bf909d8640f89568b12440a84765c8080d7
1,260
cpp
C++
test/detail/ApplyTupleTests.cpp
milleniumbug/rapidcheck
69ae4f77f57ee29609d8eb66dace6724feaf64d1
[ "BSD-2-Clause" ]
21
2017-10-27T18:54:11.000Z
2018-06-20T17:32:01.000Z
test/detail/ApplyTupleTests.cpp
milleniumbug/rapidcheck
69ae4f77f57ee29609d8eb66dace6724feaf64d1
[ "BSD-2-Clause" ]
1
2020-07-15T21:02:34.000Z
2021-06-22T16:08:58.000Z
test/detail/ApplyTupleTests.cpp
milleniumbug/rapidcheck
69ae4f77f57ee29609d8eb66dace6724feaf64d1
[ "BSD-2-Clause" ]
2
2019-12-19T01:26:56.000Z
2020-09-13T12:49:15.000Z
#include <catch.hpp> #include <rapidcheck/catch.h> #include "rapidcheck/detail/ApplyTuple.h" #include "util/Logger.h" using namespace rc; using namespace rc::test; using namespace rc::detail; namespace { std::tuple<int, std::string, std::vector<std::string>> myFunc(int x, int y, Logger logger) { return std::make_tuple(x + y, logger.id, logger.log); } } TEST_CASE("applyTuple") { auto tuple = std::make_tuple(40, 2, Logger("foobar")); std::tuple<int, std::string, std::vector<std::string>> result; std::vector<std::string> expectedLog; SECTION("std::tuple<...> &&") { result = applyTuple(std::move(tuple), &myFunc); expectedLog = { "constructed as foobar", "move constructed", "move constructed"}; } SECTION("std::tuple<...> &") { result = applyTuple(tuple, &myFunc); expectedLog = { "constructed as foobar", "move constructed", "copy constructed"}; } SECTION("const std::tuple<...> &") { const auto &constTuple = tuple; result = applyTuple(constTuple, &myFunc); expectedLog = { "constructed as foobar", "move constructed", "copy constructed"}; } REQUIRE(std::get<0>(result) == 42); REQUIRE(std::get<1>(result) == "foobar"); REQUIRE(std::get<2>(result) == expectedLog); }
26.808511
73
0.646032
milleniumbug
c4cad60c29bac9793c206a04a9b2f11f5bfaebef
11,928
cpp
C++
Engine/Source/Runtime/Foliage/Private/FoliageComponent.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Runtime/Foliage/Private/FoliageComponent.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Runtime/Foliage/Private/FoliageComponent.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= FoliageComponent.cpp: Foliage rendering implementation. =============================================================================*/ #include "CoreMinimal.h" #include "Engine/EngineTypes.h" #include "RenderingThread.h" #include "GameFramework/Controller.h" #include "Components/CapsuleComponent.h" #include "StaticMeshResources.h" #include "InteractiveFoliageActor.h" #include "InteractiveFoliageComponent.h" #include "Engine/StaticMesh.h" /** Scene proxy class for UInteractiveFoliageComponent. */ class FInteractiveFoliageSceneProxy : public FStaticMeshSceneProxy { public: FInteractiveFoliageSceneProxy(UInteractiveFoliageComponent* InComponent) : FStaticMeshSceneProxy(InComponent, false), FoliageImpluseDirection(0,0,0), FoliageNormalizedRotationAxisAndAngle(0,0,1,0) {} /** Accessor used by the rendering thread when setting foliage parameters for rendering. */ virtual void GetFoliageParameters(FVector& OutFoliageImpluseDirection, FVector4& OutFoliageNormalizedRotationAxisAndAngle) const { OutFoliageImpluseDirection = FoliageImpluseDirection; OutFoliageNormalizedRotationAxisAndAngle = FoliageNormalizedRotationAxisAndAngle; } /** Updates the scene proxy with new foliage parameters from the game thread. */ void UpdateParameters_GameThread(const FVector& NewFoliageImpluseDirection, const FVector4& NewFoliageNormalizedRotationAxisAndAngle) { checkSlow(IsInGameThread()); ENQUEUE_UNIQUE_RENDER_COMMAND_THREEPARAMETER( UpdateFoliageParameters, FInteractiveFoliageSceneProxy*,FoliageProxy,this, FVector,NewFoliageImpluseDirection,NewFoliageImpluseDirection, FVector4,NewFoliageNormalizedRotationAxisAndAngle,NewFoliageNormalizedRotationAxisAndAngle, { FoliageProxy->FoliageImpluseDirection = NewFoliageImpluseDirection; FoliageProxy->FoliageNormalizedRotationAxisAndAngle = NewFoliageNormalizedRotationAxisAndAngle; }); } protected: FVector FoliageImpluseDirection; FVector4 FoliageNormalizedRotationAxisAndAngle; }; UInteractiveFoliageComponent::UInteractiveFoliageComponent(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { } FPrimitiveSceneProxy* UInteractiveFoliageComponent::CreateSceneProxy() { // If a static mesh does not exist then this component cannot be added to the scene. if(GetStaticMesh() == NULL || GetStaticMesh()->RenderData == NULL || GetStaticMesh()->RenderData->LODResources.Num() == 0 || GetStaticMesh()->RenderData->LODResources[0].VertexBuffer.GetNumVertices() == 0) { return NULL; } // Store the foliage proxy so we can push updates to it during Tick FoliageSceneProxy = new FInteractiveFoliageSceneProxy(this); return FoliageSceneProxy; } void UInteractiveFoliageComponent::DestroyRenderState_Concurrent() { Super::DestroyRenderState_Concurrent(); FoliageSceneProxy = NULL; } float AInteractiveFoliageActor::TakeDamage(float DamageAmount, FDamageEvent const& DamageEvent, AController* EventInstigator, AActor* DamageCauser) { FHitResult Hit; FVector ImpulseDir; DamageEvent.GetBestHitInfo(this, (EventInstigator ? EventInstigator->GetPawn() : NULL), Hit, ImpulseDir); // Discard the magnitude of the momentum and use Damage as the length instead FVector DamageImpulse = ImpulseDir.GetSafeNormal() * DamageAmount * FoliageDamageImpulseScale; // Apply force magnitude clamps DamageImpulse.X = FMath::Clamp(DamageImpulse.X, -MaxDamageImpulse, MaxDamageImpulse); DamageImpulse.Y = FMath::Clamp(DamageImpulse.Y, -MaxDamageImpulse, MaxDamageImpulse); DamageImpulse.Z = FMath::Clamp(DamageImpulse.Z, -MaxDamageImpulse, MaxDamageImpulse); FoliageForce += DamageImpulse; // Bring this actor out of stasis so that it gets ticked now that a force has been applied SetActorTickEnabled(true); return 0.f; } void AInteractiveFoliageActor::CapsuleTouched(UPrimitiveComponent* OverlappedComp, AActor* Other, UPrimitiveComponent* OtherComp, int32 OtherBodyIndex, bool bFromSweep, const FHitResult& SweepResult) { if (Other != NULL && OtherComp != NULL) { UCapsuleComponent* const TouchingActorCapsule = Cast<UCapsuleComponent>(OtherComp); if (TouchingActorCapsule && CapsuleComponent) { const FVector CenterToTouching = FVector(TouchingActorCapsule->Bounds.Origin.X, TouchingActorCapsule->Bounds.Origin.Y, CapsuleComponent->Bounds.Origin.Z) - CapsuleComponent->Bounds.Origin; // Keep track of the first position on the collision cylinder that the touching actor intersected //@todo - need to handle multiple touching actors TouchingActorEntryPosition = GetRootComponent()->Bounds.Origin + CenterToTouching.GetSafeNormal() * CapsuleComponent->GetScaledCapsuleRadius(); } // Bring this actor out of stasis so that it gets ticked now that a force has been applied SetActorTickEnabled(true); } } void AInteractiveFoliageActor::SetupCollisionCylinder() { if (GetStaticMeshComponent()->GetStaticMesh()) { const FBoxSphereBounds MeshBounds = GetStaticMeshComponent()->GetStaticMesh()->GetBounds(); const FVector Scale3D = GetStaticMeshComponent()->RelativeScale3D; // Set the cylinder's radius based off of the static mesh's bounds radius // CollisionRadius is in world space so apply the actor's scale CapsuleComponent->SetCapsuleSize(MeshBounds.SphereRadius * .7f * FMath::Max(Scale3D.X, Scale3D.Y), MeshBounds.BoxExtent.Z * Scale3D.Z); // Ensure delegate is bound (just once) CapsuleComponent->OnComponentBeginOverlap.RemoveDynamic(this, &AInteractiveFoliageActor::CapsuleTouched); CapsuleComponent->OnComponentBeginOverlap.AddDynamic(this, &AInteractiveFoliageActor::CapsuleTouched); } } void AInteractiveFoliageActor::Tick(float DeltaSeconds) { UInteractiveFoliageComponent* const FoliageComponent = CastChecked<UInteractiveFoliageComponent>(GetStaticMeshComponent()); // Can only push updates to the scene proxy if we are being ticked while registered // The proxy will be NULL on dedicated server if (FoliageComponent->IsRegistered() && FoliageComponent->FoliageSceneProxy) { TSet<AActor*> Touching; GetOverlappingActors(Touching); for (AActor* TouchingActor : Touching) { if (TouchingActor != NULL && TouchingActor->GetRootComponent() != NULL) { const FVector TouchingActorPosition(TouchingActor->GetRootComponent()->Bounds.Origin.X, TouchingActor->GetRootComponent()->Bounds.Origin.Y, GetRootComponent()->Bounds.Origin.Z); //DrawDebugLine(GetWorld(), TouchingActorPosition, GetRootComponent()->Bounds.Origin, 255, 255, 255, false); // Operate on the touching actor's collision cylinder //@todo - handle touching actors without collision cylinders UCapsuleComponent* TouchingActorCapsule = Cast<UCapsuleComponent>(TouchingActor->GetRootComponent()); if (TouchingActorCapsule && CapsuleComponent) { FVector TouchingToCenter = GetRootComponent()->Bounds.Origin - TouchingActorPosition; // Force the simulated position to be in the XY plane for simplicity TouchingToCenter.Z = 0; // Position on the collision cylinder mirrored across the cylinder's center from the position that the touching actor entered const FVector OppositeTouchingEntryPosition = GetRootComponent()->Bounds.Origin + GetRootComponent()->Bounds.Origin - TouchingActorEntryPosition; // Project the touching actor's center onto the vector from where it first entered to OppositeTouchingEntryPosition // This results in the same directional force being applied for the duration of the other actor touching this foliage actor, // Which prevents strange movement that results from just comparing cylinder centers. const FVector ProjectedTouchingActorPosition = (TouchingActorPosition - OppositeTouchingEntryPosition).ProjectOnTo(TouchingActorEntryPosition - OppositeTouchingEntryPosition) + OppositeTouchingEntryPosition; // Find the furthest position on the cylinder of the touching actor from OppositeTouchingEntryPosition const FVector TouchingActorFurthestPosition = ProjectedTouchingActorPosition + (TouchingActorEntryPosition - OppositeTouchingEntryPosition).GetSafeNormal() * TouchingActorCapsule->GetScaledCapsuleRadius(); // Construct the impulse as the distance between the furthest cylinder positions minus the two cylinder's diameters const FVector ImpulseDirection = - (OppositeTouchingEntryPosition - TouchingActorFurthestPosition - (OppositeTouchingEntryPosition - TouchingActorFurthestPosition).GetSafeNormal() * 2.0f * (TouchingActorCapsule->GetScaledCapsuleRadius() + CapsuleComponent->GetScaledCapsuleRadius())); //DrawDebugLine(GetWorld(), GetRootComponent()->Bounds.Origin + FVector(0,0,100), GetRootComponent()->Bounds.Origin + ImpulseDirection + FVector(0,0,100), 100, 255, 100, false); // Scale and clamp the touch force FVector Impulse = ImpulseDirection * FoliageTouchImpulseScale; Impulse.X = FMath::Clamp(Impulse.X, -MaxTouchImpulse, MaxTouchImpulse); Impulse.Y = FMath::Clamp(Impulse.Y, -MaxTouchImpulse, MaxTouchImpulse); Impulse.Z = FMath::Clamp(Impulse.Z, -MaxTouchImpulse, MaxTouchImpulse); FoliageForce += Impulse; } } } // Apply spring stiffness, which is the force that pushes the simulated particle back to the origin FoliageForce += -FoliageStiffness * FoliagePosition; // Apply spring quadratic stiffness, which increases in magnitude with the square of the distance to the origin // This prevents the spring from being displaced too much by touch and damage forces FoliageForce += -FoliageStiffnessQuadratic * FoliagePosition.SizeSquared() * FoliagePosition.GetSafeNormal(); // Apply spring damping, which is like air resistance and causes the spring to lose energy over time FoliageForce += -FoliageDamping * FoliageVelocity; FoliageForce.X = FMath::Clamp(FoliageForce.X, -MaxForce, MaxForce); FoliageForce.Y = FMath::Clamp(FoliageForce.Y, -MaxForce, MaxForce); FoliageForce.Z = FMath::Clamp(FoliageForce.Z, -MaxForce, MaxForce); FoliageVelocity += FoliageForce * DeltaSeconds; FoliageForce = FVector::ZeroVector; const float MaxVelocity = 1000.0f; FoliageVelocity.X = FMath::Clamp(FoliageVelocity.X, -MaxVelocity, MaxVelocity); FoliageVelocity.Y = FMath::Clamp(FoliageVelocity.Y, -MaxVelocity, MaxVelocity); FoliageVelocity.Z = FMath::Clamp(FoliageVelocity.Z, -MaxVelocity, MaxVelocity); FoliagePosition += FoliageVelocity * DeltaSeconds; //DrawDebugLine(GetWorld(), GetRootComponent()->Bounds.Origin + FVector(0,0,100), GetRootComponent()->Bounds.Origin + FVector(0,0,100) + FoliagePosition, 255, 100, 100, false); //@todo - derive this height from the static mesh const float IntersectionHeight = 100.0f; // Calculate the rotation angle using Sin(Angle) = Opposite / Hypotenuse const float RotationAngle = -FMath::Asin(FoliagePosition.Size() / IntersectionHeight); // Use a rotation angle perpendicular to the impulse direction and the z axis const FVector NormalizedRotationAxis = FoliagePosition.SizeSquared() > KINDA_SMALL_NUMBER ? (FoliagePosition ^ FVector(0,0,1)).GetSafeNormal() : FVector(0,0,1); // Propagate the new rotation axis and angle to the rendering thread FoliageComponent->FoliageSceneProxy->UpdateParameters_GameThread(FoliagePosition, FVector4(NormalizedRotationAxis, RotationAngle)); if (FoliagePosition.SizeSquared() < FMath::Square(KINDA_SMALL_NUMBER * 10.0f) && FoliageVelocity.SizeSquared() < FMath::Square(KINDA_SMALL_NUMBER * 10.0f)) { // Go into stasis (will no longer be ticked) if this actor's spring simulation has stabilized SetActorTickEnabled(false); } } Super::Tick(DeltaSeconds); } void AInteractiveFoliageActor::PostActorCreated() { Super::PostActorCreated(); SetupCollisionCylinder(); } void AInteractiveFoliageActor::PostLoad() { Super::PostLoad(); SetupCollisionCylinder(); }
48.685714
212
0.776828
windystrife
c4cb821d32a32ac24ac34875608760ec342e8e3c
812
cpp
C++
clang-tools-extra/test/clang-tidy/checkers/concurrency-mt-unsafe-posix.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
2,338
2018-06-19T17:34:51.000Z
2022-03-31T11:00:37.000Z
clang-tools-extra/test/clang-tidy/checkers/concurrency-mt-unsafe-posix.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
3,740
2019-01-23T15:36:48.000Z
2022-03-31T22:01:13.000Z
clang-tools-extra/test/clang-tidy/checkers/concurrency-mt-unsafe-posix.cpp
mkinsner/llvm
589d48844edb12cd357b3024248b93d64b6760bf
[ "Apache-2.0" ]
500
2019-01-23T07:49:22.000Z
2022-03-30T02:59:37.000Z
// RUN: %check_clang_tidy %s concurrency-mt-unsafe %t -- -config='{CheckOptions: [{key: "concurrency-mt-unsafe.FunctionSet", value: "posix"}]}' extern unsigned int sleep (unsigned int __seconds); extern int *gmtime (const int *__timer); extern int *gmtime_r (const int *__timer, char*); extern char *dirname (char *__path); void foo() { sleep(2); ::sleep(2); auto tm = gmtime(nullptr); // CHECK-MESSAGES: :[[@LINE-1]]:13: warning: function is not thread safe [concurrency-mt-unsafe] tm = ::gmtime(nullptr); // CHECK-MESSAGES: :[[@LINE-1]]:8: warning: function is not thread safe [concurrency-mt-unsafe] tm = gmtime_r(nullptr, nullptr); tm = ::gmtime_r(nullptr, nullptr); dirname(nullptr); // CHECK-MESSAGES: :[[@LINE-1]]:3: warning: function is not thread safe [concurrency-mt-unsafe] }
35.304348
143
0.684729
mkinsner
c4cc576690912172f7e671be0ecf0af39a955e34
3,926
cpp
C++
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
6
2019-01-06T05:02:39.000Z
2020-10-01T11:45:32.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
209
2018-05-18T03:07:02.000Z
2022-03-26T11:42:41.000Z
src_smartcontract_db/scan_select/scan_planner/scanner/join/JoinOrCandidate.cpp
alinous-core/codablecash
04ca04c9bc179aa81d4277ed34320b4340628bd1
[ "MIT" ]
3
2019-07-06T09:16:36.000Z
2020-10-15T08:23:28.000Z
/* * JoinBranchCandidate.cpp * * Created on: 2020/09/01 * Author: iizuka */ #include "scan_select/scan_planner/scanner/join/JoinOrCandidate.h" #include "scan_select/scan_planner/scanner/join/AbstractJoinCandidateCollection.h" #include "scan_select/scan_planner/scanner/join/JoinCandidate.h" namespace codablecash { JoinOrCandidate::JoinOrCandidate(const JoinOrCandidate& inst) : AbstractJoinCandidate(inst.joinType) { int maxLoop = inst.list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = inst.list.get(i); AbstractJoinCandidateCollection* newCol = dynamic_cast<AbstractJoinCandidateCollection*>(col->copy()); this->list.addElement(newCol); } } JoinOrCandidate::JoinOrCandidate(int joinType) : AbstractJoinCandidate(joinType) { } JoinOrCandidate::~JoinOrCandidate() { this->list.deleteElements(); } AbstractJoinCandidate::CandidateType JoinOrCandidate::getCandidateType() const noexcept { return AbstractJoinCandidate::CandidateType::OR; } AbstractJoinCandidate* JoinOrCandidate::multiply(const AbstractJoinCandidate* other) const noexcept { JoinCandidate::CandidateType candidateType = other->getCandidateType(); if(candidateType == JoinCandidate::CandidateType::OR){ const JoinOrCandidate* orCandidate = dynamic_cast<const JoinOrCandidate*>(other); return multiplyOr(orCandidate); } JoinOrCandidate* newCond = new JoinOrCandidate(this->joinType); const AbstractJoinCandidateCollection* col = dynamic_cast<const AbstractJoinCandidateCollection*>(other); multiply(this, col, newCond); return newCond; } AbstractJoinCandidate* JoinOrCandidate::multiplyOr(const JoinOrCandidate* other) const noexcept { JoinOrCandidate* newCond = new JoinOrCandidate(this->joinType); int maxLoop = this->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = this->list.get(i); multiply(other, col, newCond); } return newCond; } void JoinOrCandidate::multiply(const JoinOrCandidate* other, const AbstractJoinCandidateCollection* col, JoinOrCandidate* newCond) const noexcept { int maxLoop = other->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* c = other->list.get(i); AbstractJoinCandidate* newC = c->multiply(col); AbstractJoinCandidateCollection* newCollection = dynamic_cast<AbstractJoinCandidateCollection*>(newC); newCond->list.addElement(newCollection); } } void JoinOrCandidate::add(const AbstractJoinCandidate* candidate) noexcept { JoinCandidate::CandidateType candidateType = candidate->getCandidateType(); if(candidateType == JoinCandidate::CandidateType::OR){ addOr(dynamic_cast<const JoinOrCandidate*>(candidate)); return; } AbstractJoinCandidateCollection* col = dynamic_cast<AbstractJoinCandidateCollection*>(candidate->copy()); this->list.addElement(col); } void JoinOrCandidate::addOr(const JoinOrCandidate* candidate) noexcept { int maxLoop = candidate->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = dynamic_cast<AbstractJoinCandidateCollection*>(candidate->list.get(i)->copy()); this->list.addElement(col); } } AbstractJoinCandidate* JoinOrCandidate::copy() const noexcept { return new JoinOrCandidate(*this); } int JoinOrCandidate::size() const noexcept { return this->list.size(); } const AbstractJoinCandidateCollection* JoinOrCandidate::get(int i) const noexcept { return this->list.get(i); } int JoinOrCandidate::getOverHeadScore(AbstractScanTableTarget* left, AbstractScanTableTarget* right) const noexcept { int score = 0; int maxLoop = this->list.size(); for(int i = 0; i != maxLoop; ++i){ AbstractJoinCandidateCollection* col = this->list.get(i); score += col->getOverHeadScore(left, right); } return score; } CdbTableIndex* JoinOrCandidate::getIndex(const AbstractScanTableTarget* right) const noexcept { return nullptr; } } /* namespace codablecash */
30.2
120
0.767448
alinous-core
c4cc5ad1375eda855b296c1ec353a95240ffc075
10,739
cpp
C++
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
null
null
null
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
1
2022-03-28T16:56:01.000Z
2022-03-28T16:57:07.000Z
folly/experimental/channels/test/ChannelTest.cpp
wangzhx123/folly
94d02fac4a4b3dcd4f0e76566ae36a9aa32196ea
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * 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 <folly/executors/ManualExecutor.h> #include <folly/experimental/channels/Channel.h> #include <folly/experimental/channels/test/ChannelTestUtil.h> #include <folly/experimental/coro/BlockingWait.h> #include <folly/portability/GTest.h> namespace folly { namespace channels { using namespace testing; class ChannelFixture : public Test, public WithParamInterface<ConsumptionMode>, public ChannelConsumerBase<int> { protected: ChannelFixture() : ChannelConsumerBase(GetParam()) {} ~ChannelFixture() override { cancellationSource_.requestCancellation(); if (!continueConsuming_.isFulfilled()) { continueConsuming_.setValue(false); } executor_.drain(); } folly::Executor::KeepAlive<> getExecutor() override { return &executor_; } void onNext(folly::Try<int> result) override { onNext_(std::move(result)); } folly::ManualExecutor executor_; StrictMock<MockNextCallback<int>> onNext_; }; TEST_P(ChannelFixture, SingleWriteBeforeNext_ThenCancelled) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onCancelled()); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST_P(ChannelFixture, SingleWriteAfterNext_ThenCancelled) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onCancelled()); sender.write(1); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST_P(ChannelFixture, MultipleWrites_ThenStopConsumingByReturningFalse) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onValue(2)); EXPECT_CALL(onNext_, onValue(3)); sender.write(1); sender.write(2); executor_.drain(); sender.write(3); sender.write(4); continueConsuming_ = folly::SharedPromise<bool>(); continueConsuming_.setValue(false); executor_.drain(); } TEST_P( ChannelFixture, MultipleWrites_ThenStopConsumingByThrowingOperationCancelled) { auto [receiver, sender] = Channel<int>::create(); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onValue(2)); EXPECT_CALL(onNext_, onValue(3)); sender.write(1); sender.write(2); executor_.drain(); sender.write(3); sender.write(4); continueConsuming_ = folly::SharedPromise<bool>(); continueConsuming_.setException(folly::OperationCancelled()); executor_.drain(); } TEST_P(ChannelFixture, Close_NoException_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); std::move(sender).close(); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_NoException_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); std::move(sender).close(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_DueToDestruction_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); { auto toDestroy = std::move(sender); } EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_DueToDestruction_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onClosed()); startConsuming(std::move(receiver)); sender.write(1); { auto toDestroy = std::move(sender); } executor_.drain(); } TEST_P(ChannelFixture, Close_Exception_BeforeSubscribe) { auto [receiver, sender] = Channel<int>::create(); std::move(sender).close(std::runtime_error("Error")); EXPECT_CALL(onNext_, onRuntimeError("std::runtime_error: Error")); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, Close_Exception_AfterSubscribeAndWrite) { auto [receiver, sender] = Channel<int>::create(); sender.write(1); std::move(sender).close(std::runtime_error("Error")); EXPECT_CALL(onNext_, onValue(1)); EXPECT_CALL(onNext_, onRuntimeError("std::runtime_error: Error")); startConsuming(std::move(receiver)); executor_.drain(); } TEST_P(ChannelFixture, CancellationRespected) { auto [receiver, sender] = Channel<int>::create(); EXPECT_CALL(onNext_, onValue(1)); continueConsuming_ = folly::SharedPromise<bool>(); sender.write(1); startConsuming(std::move(receiver)); executor_.drain(); EXPECT_FALSE(sender.isReceiverCancelled()); cancellationSource_.requestCancellation(); executor_.drain(); EXPECT_TRUE(sender.isReceiverCancelled()); } TEST(Channel, CancelNextWithoutClose) { folly::ManualExecutor executor; folly::CancellationSource cancelSource; auto [receiver, sender] = Channel<int>::create(); sender.write(1); EXPECT_EQ(folly::coro::blockingWait(receiver.next()).value(), 1); auto nextTask = folly::coro::co_withCancellation( cancelSource.getToken(), folly::coro::co_invoke( [&receiver = receiver]() -> folly::coro::Task<std::optional<int>> { co_return co_await receiver.next(false /* closeOnCancel */); })) .scheduleOn(&executor) .start(); executor.drain(); cancelSource.requestCancellation(); sender.write(2); executor.drain(); EXPECT_THROW( folly::coro::blockingWait(std::move(nextTask)), folly::OperationCancelled); EXPECT_EQ(folly::coro::blockingWait(receiver.next()).value(), 2); } INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithTry, ChannelFixture, testing::Values(ConsumptionMode::CoroWithTry)); INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithoutTry, ChannelFixture, testing::Values(ConsumptionMode::CoroWithoutTry)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandle, ChannelFixture, testing::Values(ConsumptionMode::CallbackWithHandle)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandleList, ChannelFixture, testing::Values(ConsumptionMode::CallbackWithHandleList)); class ChannelFixtureStress : public Test, public WithParamInterface<ConsumptionMode> { protected: ChannelFixtureStress() : producer_(std::make_unique<StressTestProducer<int>>( [value = 0]() mutable { return value++; })), consumer_(std::make_unique<StressTestConsumer<int>>( GetParam(), [lastReceived = -1](int value) mutable { EXPECT_EQ(value, ++lastReceived); })) {} static constexpr std::chrono::milliseconds kTestTimeout = std::chrono::milliseconds{5000}; std::unique_ptr<StressTestProducer<int>> producer_; std::unique_ptr<StressTestConsumer<int>> consumer_; }; TEST_P(ChannelFixtureStress, Close_NoException) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::NoException); } TEST_P(ChannelFixtureStress, Close_Exception) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::runtime_error("Error")); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::Exception); } TEST_P(ChannelFixtureStress, Cancelled) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); consumer_->cancel(); EXPECT_EQ(consumer_->waitForClose().get(), CloseType::Cancelled); producer_->stopProducing(); } TEST_P(ChannelFixtureStress, Close_NoException_ThenCancelledImmediately) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); producer_->stopProducing(); consumer_->cancel(); EXPECT_THAT( consumer_->waitForClose().get(), AnyOf(Eq(CloseType::NoException), Eq(CloseType::Cancelled))); } TEST_P(ChannelFixtureStress, Cancelled_ThenClosedImmediately_NoException) { auto [receiver, sender] = Channel<int>::create(); producer_->startProducing(std::move(sender), std::nullopt /* closeEx */); consumer_->startConsuming(std::move(receiver)); /* sleep override */ std::this_thread::sleep_for(kTestTimeout); consumer_->cancel(); producer_->stopProducing(); EXPECT_THAT( consumer_->waitForClose().get(), AnyOf(Eq(CloseType::NoException), Eq(CloseType::Cancelled))); } INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithTry, ChannelFixtureStress, testing::Values(ConsumptionMode::CoroWithTry)); INSTANTIATE_TEST_SUITE_P( Channel_Coro_WithoutTry, ChannelFixtureStress, testing::Values(ConsumptionMode::CoroWithoutTry)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandle, ChannelFixtureStress, testing::Values(ConsumptionMode::CallbackWithHandle)); INSTANTIATE_TEST_SUITE_P( Channel_Callback_WithHandleList, ChannelFixtureStress, testing::Values(ConsumptionMode::CallbackWithHandleList)); } // namespace channels } // namespace folly
28.186352
78
0.720086
wangzhx123
c4ce0dcfe681e79eb180beb08064f83d0460e66d
2,166
cpp
C++
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
NPSVisor/tools/svMaker/source/PDiagMirror.cpp
NPaolini/NPS_OpenSource
0c7da066b02b57ce282a1903a3901a563d04a28f
[ "Unlicense" ]
null
null
null
//----------- PDiagMirror.cpp ------------------------------------------------ //---------------------------------------------------------------------------- #include "precHeader.h" //---------------------------------------------------------------------------- #include "PDiagMirror.h" //---------------------------------------------------------------------------- PDiagMirror::PDiagMirror(PWin* parent, bool& all, uint& choose, bool hasSelected, uint resId, HINSTANCE hinstance) : baseClass(parent, resId, hinstance), All(all), Choose(choose), hasSelected(hasSelected) { } //---------------------------------------------------------------------------- PDiagMirror::~PDiagMirror() { } //---------------------------------------------------------------------------- bool PDiagMirror::create() { if(!baseClass::create()) return false; if(!hasSelected) { ENABLE(IDC_SELECTED, false); SET_CHECK(IDC_MIRROR_ALL); } else if(All) SET_CHECK(IDC_MIRROR_ALL); else SET_CHECK(IDC_SELECTED); if(!Choose) SET_CHECK(IDC_HORZ); else { if(Choose & emtVert) SET_CHECK(IDC_VERT); if(Choose & emtHorz) SET_CHECK(IDC_HORZ); } return true; } //---------------------------------------------------------------------------- LRESULT PDiagMirror::windowProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_COMMAND: switch(LOWORD(wParam)) { case IDC_VERT: if(!IS_CHECKED(IDC_VERT)) SET_CHECK(IDC_HORZ); break; case IDC_HORZ: if(!IS_CHECKED(IDC_HORZ)) SET_CHECK(IDC_VERT); break; } break; } return baseClass::windowProc(hwnd, message, wParam, lParam); } //---------------------------------------------------------------------------- void PDiagMirror::CmOk() { if(!IS_CHECKED(IDC_VERT) && !IS_CHECKED(IDC_HORZ)) return; Choose = 0; if(IS_CHECKED(IDC_VERT)) Choose = emtVert; if(IS_CHECKED(IDC_HORZ)) Choose |= emtHorz; All = IS_CHECKED(IDC_MIRROR_ALL); baseClass::CmOk(); } //----------------------------------------------------------------------------
30.083333
116
0.440443
NPaolini
c4cefe124afee36b4870a0708ece73c366bad328
3,735
cpp
C++
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
8
2019-01-16T07:09:39.000Z
2020-11-06T23:13:46.000Z
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
null
null
null
Features/src/Host/ClientConnection.cpp
ProtocolONE/cord.app
0defd4e2cbc25d4f414fa68f8c1dfe65eadc02e7
[ "Apache-2.0" ]
3
2019-09-30T02:45:09.000Z
2019-09-30T23:17:26.000Z
#include <Host/ClientConnection.h> #include <Host/Dbus/ConnectionBridgeProxy.h> #include <Host/Dbus/DbusConnection.h> #include <Core/UI/Message.h> #include <RestApi/ProtocolOneCredential.h> #include <QtCore/QDebug> using P1::Host::DBus::DBusConnection; using P1::RestApi::ProtocolOneCredential; namespace P1 { namespace Host { ClientConnection::ClientConnection(const QString &name, QObject* parent /*= 0*/) : QObject(parent) , _maxTimeoutFail(30) // 3 * 10 * 5000 = 3 * 50 sec , _timeoutFail(0) , _connection(nullptr) , _appName(name) { QObject::connect(&this->_timeoutTimer, &QTimer::timeout, this, &ClientConnection::timeoutTick); this->_timeoutTimer.setInterval(5000); QObject::connect(&this->_pingpongTimer, &QTimer::timeout, this, &ClientConnection::sendPing); this->_pingpongTimer.setInterval(5000); } ClientConnection::~ClientConnection() { } void ClientConnection::init() { QDBusConnection &connection = DBusConnection::bus(); QString dbusService("com.protocolone.launcher.dbus"); this->_connection = new ConnectionBridgeProxy(dbusService, "/connection", connection, this); this->_connection->setApplicationName(this->_appName); QObject::connect(this->_connection, &ConnectionBridgeProxy::pong, this, &ClientConnection::onPong); QObject::connect(this->_connection, &ConnectionBridgeProxy::authorizationError, this, &ClientConnection::authorizationError); this->sendPing(); this->_pingpongTimer.start(); this->_timeoutTimer.start(); } void ClientConnection::timeoutTick() { // HACK disabled. Debug works very poor. //this->_timeoutFail++; //if (this->_timeoutFail < this->_maxTimeoutFail) // return; //this->internalDisconnected(); } void ClientConnection::sendPing() { Q_CHECK_PTR(this->_connection); QDBusPendingReply<> result = this->_connection->ping(); if (!result.isError()) return; qDebug() << "Ping finished with error:" << result.error().name() << "message:" << result.error().message() << "code:" << result.error().type(); if (result.error().type() == QDBusError::Disconnected) this->internalDisconnected(); } void ClientConnection::onPong() { DEBUG_LOG << "!!!! ClientConnection::onPong()"; this->_timeoutTimer.start(); this->_timeoutFail = 0; } void ClientConnection::setCredential(const P1::RestApi::ProtocolOneCredential& value) { Q_CHECK_PTR(this->_connection); this->_connection->setCredential(value.acccessTokent(), value.accessTokenExpiredTimeAsString()); } void ClientConnection::updateCredential( const P1::RestApi::ProtocolOneCredential& valueOld, const P1::RestApi::ProtocolOneCredential& valueNew) { Q_CHECK_PTR(this->_connection); this->_connection->updateCredential( valueOld.acccessTokent(), valueOld.accessTokenExpiredTimeAsString() , valueNew.acccessTokent(), valueNew.accessTokenExpiredTimeAsString()); } void ClientConnection::close() { Q_ASSERT(this->_connection); this->_connection->close(); } void ClientConnection::internalDisconnected() { this->_timeoutTimer.stop(); this->_pingpongTimer.stop(); qDebug() << "Disconnected from host"; P1::Core::UI::Message::critical(tr("DBUS_DISCONNECTED_TITLE"), tr("DBUS_DISCONNECTED_TEXT")); emit this->disconnected(); } } }
29.179688
103
0.636145
ProtocolONE
c4d003c70bb9ecb84fd4c91c3a8084a2057014ab
2,159
cpp
C++
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
Code/Tools/Fileserve/Main.cpp
fereeh/ezEngine
14e46cb2a1492812888602796db7ddd66e2b7110
[ "MIT" ]
null
null
null
#include <FileservePCH.h> #include <Fileserve/Main.h> #include <Foundation/Configuration/Startup.h> #include <Foundation/IO/FileSystem/FileSystem.h> #include <Foundation/Utilities/CommandLineUtils.h> #ifdef EZ_USE_QT #include <Gui.moc.h> #include <QApplication> #include <Foundation/Basics/Platform/Win/IncludeWindows.h> #endif #ifdef EZ_USE_QT int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { #else int main(int argc, const char** argv) { #endif ezFileserverApp* pApp = new ezFileserverApp(); #ifdef EZ_USE_QT ezCommandLineUtils::GetGlobalInstance()->SetCommandLine(); int argc = 0; char** argv = nullptr; QApplication* pQtApplication = new QApplication(argc, const_cast<char**>(argv)); pQtApplication->setApplicationName("ezFileserve"); pQtApplication->setOrganizationDomain("www.ezEngine.net"); pQtApplication->setOrganizationName("ezEngine Project"); pQtApplication->setApplicationVersion("1.0.0"); ezRun_Startup(pApp); CreateFileserveMainWindow(pApp); pQtApplication->exec(); ezRun_Shutdown(pApp); #else pApp->SetCommandLineArguments((ezUInt32)argc, argv); ezRun(pApp); #endif const int iReturnCode = pApp->GetReturnCode(); if (iReturnCode != 0) { std::string text = pApp->TranslateReturnCode(); if (!text.empty()) printf("Return Code: '%s'\n", text.c_str()); } delete pApp; return iReturnCode; } ezResult ezFileserverApp::BeforeCoreSystemsStartup() { ezStartup::AddApplicationTag("tool"); ezStartup::AddApplicationTag("fileserve"); return SUPER::BeforeCoreSystemsStartup(); } void ezFileserverApp::FileserverEventHandler(const ezFileserverEvent& e) { switch (e.m_Type) { case ezFileserverEvent::Type::ClientConnected: case ezFileserverEvent::Type::ClientReconnected: ++m_uiConnections; m_TimeTillClosing.SetZero(); break; case ezFileserverEvent::Type::ClientDisconnected: --m_uiConnections; if (m_uiConnections == 0 && m_CloseAppTimeout.GetSeconds() > 0) { // reset the timer m_TimeTillClosing = ezTime::Now() + m_CloseAppTimeout; } break; } }
24.816092
95
0.725799
fereeh
c4d15326bff694e1d4f7cb78450af46269c24997
4,534
cpp
C++
src/qc_ovps.cpp
Samthos/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
1
2021-04-06T05:01:47.000Z
2021-04-06T05:01:47.000Z
src/qc_ovps.cpp
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
null
null
null
src/qc_ovps.cpp
spec-org/MC-MPn-Direct
cdf05c7ce7b33bf1b86b80f57f800634822c9cc6
[ "MIT" ]
3
2020-06-09T23:53:28.000Z
2022-03-02T05:44:55.000Z
#include <iostream> #include <functional> #include <algorithm> #include <cmath> #include "qc_ovps.h" template <template <typename, typename> typename Container, template <typename> typename Allocator> OVPS<Container, Allocator>::OVPS() { electron_pairs = 0; } template <template <typename, typename> typename Container, template <typename> typename Allocator> OVPS<Container, Allocator>::~OVPS() { } template <template <typename, typename> typename Container, template <typename> typename Allocator> void OVPS<Container, Allocator>::init(const int dimm, const int electron_pairs_) { electron_pairs = electron_pairs_; o_set.resize(dimm); v_set.resize(dimm); for (auto stop = 0; stop < dimm; stop++) { o_set[stop].resize(stop + 1); v_set[stop].resize(stop + 1); for (auto start = 0; start < stop + 1; start++) { o_set[stop][start].resize(electron_pairs); v_set[stop][start].resize(electron_pairs); } } } template <template <typename, typename> typename Container, template <typename> typename Allocator> void OVPS<Container, Allocator>::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { std::cerr << "Default OVPS update_ovsp not implemented\n"; exit(0); } template <> void OVPS_Host::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { auto iocc1 = electron_pair_psi1.iocc1; auto iocc2 = electron_pair_psi1.iocc2; auto ivir1 = electron_pair_psi1.ivir1; auto ivir2 = electron_pair_psi1.ivir2; auto lda = electron_pair_psi1.lda; for (auto stop = 0; stop < o_set.size(); stop++) { for (auto start = 0; start < o_set[stop].size(); start++) { auto t_val = tau->get_exp_tau(stop, start); std::transform(t_val.begin(), t_val.end(), t_val.begin(), [](double x){return sqrt(x);}); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi1.psi, iocc1, lda, t_val, iocc1, 1, electron_pair_psi1.psiTau, iocc1, lda); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi2.psi, iocc1, lda, t_val, iocc1, 1, electron_pair_psi2.psiTau, iocc1, lda); o_set[stop][start].update(electron_pair_psi1.psiTau, iocc1, electron_pair_psi2.psiTau, iocc1, iocc2 - iocc1, lda, blas_wrapper); v_set[stop][start].update(electron_pair_psi1.psiTau, ivir1, electron_pair_psi2.psiTau, ivir1, ivir2 - ivir1, lda, blas_wrapper); } } } #ifdef HAVE_CUDA template <> void OVPS_Device::update(Wavefunction_Type& electron_pair_psi1, Wavefunction_Type& electron_pair_psi2, Tau* tau) { auto iocc1 = electron_pair_psi1.iocc1; auto iocc2 = electron_pair_psi1.iocc2; auto ivir1 = electron_pair_psi1.ivir1; auto ivir2 = electron_pair_psi1.ivir2; auto lda = electron_pair_psi1.lda; for (auto stop = 0; stop < o_set.size(); stop++) { for (auto start = 0; start < o_set[stop].size(); start++) { auto t_val = tau->get_exp_tau(stop, start); std::transform(t_val.begin(), t_val.end(), t_val.begin(), [](double x){return sqrt(x);}); thrust::device_vector<double, thrust::device_allocator<double>> d_t_val = t_val; blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi1.psi, iocc1, lda, d_t_val, iocc1, 1, electron_pair_psi1.psiTau, iocc1, lda); blas_wrapper.ddgmm(BLAS_WRAPPER::LEFT_SIDE, ivir2 - iocc1, electron_pairs, electron_pair_psi2.psi, iocc1, lda, d_t_val, iocc1, 1, electron_pair_psi2.psiTau, iocc1, lda); o_set[stop][start].update(electron_pair_psi1.psiTau, iocc1, electron_pair_psi2.psiTau, iocc1, iocc2 - iocc1, lda, blas_wrapper); v_set[stop][start].update(electron_pair_psi1.psiTau, ivir1, electron_pair_psi2.psiTau, ivir1, ivir2 - ivir1, lda, blas_wrapper); } } } void copy_OVPS(OVPS_Host& src, OVPS_Device& dest) { for (int i = 0; i < src.o_set.size(); i++) { for (int j = 0; j < src.o_set[i].size(); j++) { copy_OVPS_Set(src.o_set[i][j], dest.o_set[i][j]); copy_OVPS_Set(src.v_set[i][j], dest.v_set[i][j]); } } } void copy_OVPS(OVPS_Device& src, OVPS_Host& dest) { for (int i = 0; i < src.o_set.size(); i++) { for (int j = 0; j < src.o_set[i].size(); j++) { copy_OVPS_Set(src.o_set[i][j], dest.o_set[i][j]); copy_OVPS_Set(src.v_set[i][j], dest.v_set[i][j]); } } } #endif
38.423729
134
0.679974
Samthos
c4d183b6269f9964875a695555203b9382224f0f
50,419
cc
C++
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
cow/src/components/audio_sink_pulse.cc
halleyzhao/alios-mm
bef2a6de0c207a5ae9bf4f63de2e562df864aa3e
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2017 Alibaba Group Holding Limited. 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 <math.h> #include "audio_sink_pulse.h" #include "multimedia/mm_types.h" #include "multimedia/mm_errors.h" #include "multimedia/mmlistener.h" #include "multimedia/mm_cpp_utils.h" #include "multimedia/media_buffer.h" #include "multimedia/media_meta.h" #include "multimedia/media_attr_str.h" #include "multimedia/mm_audio.h" #include <pulse/sample.h> #include <pulse/pulseaudio.h> #include <pulse/thread-mainloop.h> #include <pthread.h> #include <stdio.h> #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION #include <multimedia/mm_amhelper.h> #endif #ifndef MM_LOG_OUTPUT_V //#define MM_LOG_OUTPUT_V #endif #include <multimedia/mm_debug.h> namespace YUNOS_MM { MM_LOG_DEFINE_MODULE_NAME("MSP") static const char * COMPONENT_NAME = "AudioSinkPulse"; static const char * MMTHREAD_NAME = "AudioSinkPulse::Private::OutputThread"; #define DEFAULT_VOLUME 1.0 #define DEFAULT_MUTE false #define MAX_VOLUME 10.0 #define DEFAULT_SAMPLE_RATE 44100 #define DEFAULT_CHANNEL 2 #define CLOCK_TIME_NONE -1 #define PA_ERROR(_retcode, _info, _pa_err_no) do {\ ERROR("%s, retcode: %d, pa: %s\n", _info, _retcode, pa_strerror(_pa_err_no));\ return _retcode;\ }while(0) static const struct format_entry { snd_format_t spformat; pa_sample_format_t pa; } format_map[] = { {SND_FORMAT_PCM_16_BIT, PA_SAMPLE_S16LE}, {SND_FORMAT_PCM_32_BIT, PA_SAMPLE_S32LE}, {SND_FORMAT_PCM_8_BIT, PA_SAMPLE_U8}, {SND_FORMAT_INVALID, PA_SAMPLE_INVALID} }; #define ENTER() VERBOSE(">>>\n") #define EXIT() do {VERBOSE(" <<<\n"); return;}while(0) #define EXIT_AND_RETURN(_code) do {VERBOSE("<<<(status: %d)\n", (_code)); return (_code);}while(0) #define ENTER1() DEBUG(">>>\n") #define EXIT1() do {DEBUG(" <<<\n"); return;}while(0) #define EXIT_AND_RETURN1(_code) do {DEBUG("<<<(status: %d)\n", (_code)); return (_code);}while(0) #define setState(_param, _deststate) do {\ INFO("change state from %d to %s\n", _param, #_deststate);\ (_param) = (_deststate);\ }while(0) class PAMMAutoLock { public: explicit PAMMAutoLock(pa_threaded_mainloop* loop) : mPALoop(loop) { pa_threaded_mainloop_lock (mPALoop); } ~PAMMAutoLock() { pa_threaded_mainloop_unlock (mPALoop); } pa_threaded_mainloop* mPALoop; private: MM_DISALLOW_COPY(PAMMAutoLock); }; class AudioSinkPulse::Private { public: enum state_t { STATE_IDLE, STATE_PREPARED, STATE_STARTED, STATE_PAUSED, STATE_STOPED, }; struct QueueEntry { MediaBufferSP mBuffer; mm_status_t mFinalResult; }; /* start of outputthread*/ class OutputThread; typedef MMSharedPtr <OutputThread> OutputThreadSP; class OutputThread : public MMThread { public: OutputThread(Private* render) : MMThread(MMTHREAD_NAME) , mRender(render) , mContinue(true) { ENTER(); EXIT(); } ~OutputThread() { ENTER(); EXIT(); } void signalExit() { ENTER(); MMAutoLock locker(mRender->mLock); mContinue = false; mRender->mCondition.signal(); EXIT(); } void signalContinue() { ENTER(); mRender->mCondition.signal(); EXIT(); } protected: // Write PCM data to pulseaudio void main() { ENTER(); MediaBufferSP mediaBuffer; uint8_t *sourceBuf = NULL; int64_t pts = 0; int negative = 0; pa_usec_t latencyMicros = 0; int32_t offset = 0; int32_t size = 0; while(1) { { MMAutoLock locker(mRender->mLock); if (!mContinue) { break; } mRender->mPAWriteableSize = pa_stream_writable_size (mRender->mPAStream); if (mRender->mIsPaused || mRender->mAvailableSourceBuffers.empty()) { VERBOSE("waitting condition\n"); mRender->mCondition.wait(); VERBOSE("wakeup condition\n"); continue; } mediaBuffer = mRender->mAvailableSourceBuffers.front(); mediaBuffer->getBufferInfo((uintptr_t*)&sourceBuf, &offset, &size, 1); } if (!sourceBuf || size == 0) { if (mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS)) {// EOS frame PAMMAutoLock paLoop(mRender->mPALoop); mRender->streamDrain(); mRender->mAudioSink->notify(kEventEOS, 0, 0, nilParam); } { MMAutoLock locker(mRender->mLock); mRender->mAvailableSourceBuffers.pop(); } continue; } { MMAutoLock locker(mRender->mLock); if (mediaBuffer->type() != MediaBuffer::MBT_RawAudio) { ERROR("wrong buffer type %d", mediaBuffer->type()); mRender->mAvailableSourceBuffers.pop(); continue; } } sourceBuf += offset; VERBOSE("pcm buffer %p, offset %d, size %d, pts %" PRId64 " ms", sourceBuf, offset, size, mediaBuffer->pts()/1000ll); #ifdef DUMP_SINK_PULSE_DATA fwrite(sourceBuf,1,size,mRender->mDumpFile); fwrite(&size,4,1,mRender->mDumpFileSize); #endif pts = mediaBuffer->pts(); while (size > 0) { if ((mRender->mPAWriteableSize > 0) && (mRender->mScaledPlayRate == SCALED_PLAY_RATE)) { { PAMMAutoLock paLoop(mRender->mPALoop); int32_t writeSize = mRender->mPAWriteableSize < size ? mRender->mPAWriteableSize:size; if (pa_stream_get_latency(mRender->mPAStream, &latencyMicros, &negative) != 0) ERROR("get latency error"); pa_sample_format paFormat = mRender->convertFormatToPulse((snd_format_t)mRender->mFormat); pa_sample_spec sample_spec = { .format = paFormat, .rate = (uint32_t)mRender->mSampleRate, .channels = (uint8_t)mRender->mChannelCount }; int64_t duration = pa_bytes_to_usec((uint64_t)writeSize, &sample_spec); if (MM_LIKELY(!mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS))) { // Some packet->pts is -1 for TS file. So DO NOT set anchro time when pts is invalid. if (pts >= 0) { mRender->mClockWrapper->setAnchorTime(pts, Clock::getNowUs() + latencyMicros, pts + duration); } } pa_stream_write(mRender->mPAStream, sourceBuf, writeSize, NULL, 0LL, PA_SEEK_RELATIVE); size -= writeSize; if (size > 0) { sourceBuf += writeSize; mRender->mPAWriteableSize = 0; pts += duration/1000ll; } } if (size <= 0) { if (mediaBuffer->isFlagSet(MediaBuffer::MBFT_EOS)) {// EOS frame PAMMAutoLock paLoop(mRender->mPALoop); mRender->streamDrain(); mRender->mAudioSink->notify(kEventEOS, 0, 0, nilParam); } MMAutoLock locker(mRender->mLock); mRender->mAvailableSourceBuffers.pop(); break; } } else { MMAutoLock locker(mRender->mLock); VERBOSE("wait for writeable"); mRender->mCondition.wait(); VERBOSE("wait for writeable wakeup "); if (!mContinue || mRender->mAvailableSourceBuffers.empty()) { break; } if (!mRender->mIsPaused) mRender->mPAWriteableSize = pa_stream_writable_size (mRender->mPAStream); continue; } } } INFO("Output thread exited\n"); EXIT(); } private: AudioSinkPulse::Private *mRender; bool mContinue; }; /* end of outputthread*/ static PrivateSP create() { ENTER(); PrivateSP priv(new Private()); if (priv) { INFO("private create success"); } return priv; } mm_status_t init(AudioSinkPulse *audioSink) { ENTER(); mAudioSink = audioSink; #ifdef DUMP_SINK_PULSE_DATA mDumpFile = fopen("/data/audio_sink_pulse.pcm","wb"); mDumpFileSize = fopen("/data/audio_sink_pulse.size","wb"); #endif EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void uninit() { #ifdef DUMP_SINK_PULSE_DATA fclose(mDumpFile); fclose(mDumpFileSize); #endif } ~Private() { #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_CLEAN(); #endif } snd_format_t convertFormatFromPulse(pa_sample_format paFormat); pa_sample_format convertFormatToPulse(snd_format_t format); static void contextStateCallback(pa_context *c, void *userdata); static void contextSinkinputInfoCallback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata); static void contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata); static void contextSinkInfoCallback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata); static void streamStateCallback(pa_stream *s, void *userdata); static void streamLatencyUpdateCallback(pa_stream *s, void *userdata); static void streamUnderflowCallback(pa_stream *s, void *userdata); static void streamOverflowCallback(pa_stream *s, void *userdata); static void streamWriteCallback(pa_stream *s, size_t length, void *userdata); static void streamSuccessCallback(pa_stream*s, int success, void *userdata); static void streamSuspendedCallback (pa_stream * s, void *userdata); static void streamStartedCallback (pa_stream * s, void *userdata); static void streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata); mm_status_t creatPAContext(); mm_status_t creatPAStream(); mm_status_t release(); mm_status_t freePAContext(); mm_status_t freePASteam(); mm_status_t freePALoop(); mm_status_t streamFlush(); mm_status_t streamDrain(); static void streamFlushCallback(pa_stream*s, int success, void *userdata); static void streamDrainCallback(pa_stream*s, int success, void *userdata); mm_status_t cork(int b); static void streamCorkCallback(pa_stream*s, int success, void *userdata); void clearPACallback(); void clearSourceBuffers(); mm_status_t setVolume(double volume); double getVolume(); mm_status_t setMute(bool mute); bool getMute(); bool waitPAOperation(pa_operation *op); mm_status_t resumeInternal(); pa_threaded_mainloop *mPALoop; pa_context *mPAContext; pa_stream *mPAStream; //pa_sink_input_info mPASinkInfo; int32_t mPAWriteableSize; double mVolume; bool mMute; int32_t mFormat; int32_t mSampleRate; int32_t mChannelCount; int mCorkResult; int mFlushResult; int mDrainResult; bool mIsDraining; std::queue<MediaBufferSP> mAvailableSourceBuffers; ClockWrapperSP mClockWrapper; bool mIsPaused; Condition mCondition; Lock mLock; state_t mState; int32_t mTotalBuffersQueued; OutputThreadSP mOutputThread; AudioSinkPulse *mAudioSink; #ifdef DUMP_SINK_PULSE_DATA FILE* mDumpFile; FILE* mDumpFileSize; #endif int32_t mScaledPlayRate; std::string mAudioConnectionId; #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_DECLARE() #endif Private() :mPALoop(NULL), mPAContext(NULL), mPAStream(NULL), mPAWriteableSize(0), mVolume(DEFAULT_VOLUME), mMute(DEFAULT_MUTE), mFormat(SND_FORMAT_PCM_16_BIT), mSampleRate(DEFAULT_SAMPLE_RATE), mChannelCount(DEFAULT_CHANNEL), mCorkResult(0), mFlushResult(0), mDrainResult(0), mIsDraining(false), mIsPaused(true), mCondition(mLock), mState(STATE_IDLE), mTotalBuffersQueued(0), mAudioSink(NULL), mScaledPlayRate(SCALED_PLAY_RATE) { ENTER(); mClockWrapper.reset(new ClockWrapper()); #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_INIT(); #endif EXIT(); } MM_DISALLOW_COPY(Private); }; #define ASP_MSG_prepare (msg_type)1 #define ASP_MSG_start (msg_type)2 #define ASP_MSG_resume (msg_type)3 #define ASP_MSG_pause (msg_type)4 #define ASP_MSG_stop (msg_type)5 #define ASP_MSG_flush (msg_type)6 #define ASP_MSG_seek (msg_type)7 #define ASP_MSG_reset (msg_type)8 #define ASP_MSG_setParameters (msg_type)9 #define ASP_MSG_getParameters (msg_type)10 #define ASP_MSG_write (msg_type)11 #define ASP_MSG_setMetaData (msg_type)12 BEGIN_MSG_LOOP(AudioSinkPulse) MSG_ITEM(ASP_MSG_prepare, onPrepare) MSG_ITEM(ASP_MSG_start, onStart) MSG_ITEM(ASP_MSG_resume, onResume) MSG_ITEM(ASP_MSG_pause, onPause) MSG_ITEM(ASP_MSG_stop, onStop) MSG_ITEM(ASP_MSG_flush, onFlush) MSG_ITEM(ASP_MSG_seek, onSeek) MSG_ITEM(ASP_MSG_reset, onReset) MSG_ITEM(ASP_MSG_setParameters, onSetParameters) MSG_ITEM(ASP_MSG_getParameters, onGetParameters) MSG_ITEM(ASP_MSG_write, onWrite) MSG_ITEM(ASP_MSG_setMetaData, onSetMetaData) END_MSG_LOOP() AudioSinkPulse::AudioSinkPulse(const char *mimeType, bool isEncoder) : MMMsgThread(COMPONENT_NAME) , mComponentName(COMPONENT_NAME) { mPriv = Private::create(); if (!mPriv) ERROR("no render"); } AudioSinkPulse::~AudioSinkPulse() { //release(); } Component::WriterSP AudioSinkPulse::getWriter(MediaType mediaType) { ENTER(); if ( (int)mediaType != Component::kMediaTypeAudio ) { ERROR("not supported mediatype: %d\n", mediaType); return Component::WriterSP((Component::Writer*)NULL); } Component::WriterSP wd(new AudioSinkPulse::AudioSinkWriter(this)); return wd; } mm_status_t AudioSinkPulse::init() { if (!mPriv) return MM_ERROR_NO_COMPONENT; int ret = mPriv->init(this); // MMMsgThread->run(); if (ret) EXIT_AND_RETURN(MM_ERROR_OP_FAILED); ret = MMMsgThread::run(); if (ret != 0) { ERROR("init failed, ret %d", ret); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void AudioSinkPulse::uninit() { ENTER(); mPriv->uninit(); MMMsgThread::exit(); EXIT(); } const char * AudioSinkPulse::name() const { return mComponentName.c_str(); } ClockSP AudioSinkPulse::provideClock() { ENTER(); if (!mPriv) ERROR("no render"); return mPriv->mClockWrapper->provideClock(); } mm_status_t AudioSinkPulse::prepare() { postMsg(ASP_MSG_prepare, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::start() { postMsg(ASP_MSG_start, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::resume() { postMsg(ASP_MSG_resume, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::stop() { postMsg(ASP_MSG_stop, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::pause() { postMsg(ASP_MSG_pause, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::seek(int msec, int seekSequence) { postMsg(ASP_MSG_seek, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::reset() { postMsg(ASP_MSG_reset, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::flush() { postMsg(ASP_MSG_flush, 0, NULL); return MM_ERROR_ASYNC; } mm_status_t AudioSinkPulse::AudioSinkWriter::write(const MediaBufferSP & buf) { ENTER(); if (!mRender->mPriv) return MM_ERROR_NO_COMPONENT; AudioSinkPulse::Private::QueueEntry *pEntry = new AudioSinkPulse::Private::QueueEntry; pEntry->mBuffer = buf; ++mRender->mPriv->mTotalBuffersQueued; mRender->postMsg(ASP_MSG_write, 0, (param2_type)pEntry); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::AudioSinkWriter::setMetaData(const MediaMetaSP & metaData) { ENTER(); if (!mRender->mPriv) return MM_ERROR_NO_COMPONENT; int ret = metaData->getInt32(MEDIA_ATTR_SAMPLE_RATE, mRender->mPriv->mSampleRate); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_SAMPLE_RATE); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } ret = metaData->getInt32(MEDIA_ATTR_SAMPLE_FORMAT, mRender->mPriv->mFormat); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_SAMPLE_FORMAT); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } ret = metaData->getInt32(MEDIA_ATTR_CHANNEL_COUNT, mRender->mPriv->mChannelCount); if (!ret) { ERROR("fail to get int32_t data %s\n", MEDIA_ATTR_CHANNEL_COUNT); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } INFO("sampleRate %d, format %d, channel %d", mRender->mPriv->mSampleRate, mRender->mPriv->mFormat, mRender->mPriv->mChannelCount); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::setParameter(const MediaMetaSP & meta) { ENTER(); if (!mPriv) return MM_ERROR_NO_COMPONENT; //if (!mPriv->mPALoop) // EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); //PAMMAutoLock paLoop(mPriv->mPALoop);//remove these code to setVolume and setMute method. for ( MediaMeta::iterator i = meta->begin(); i != meta->end(); ++i ) { const MediaMeta::MetaItem & item = *i; if ( !strcmp(item.mName, MEDIA_ATTR_MUTE) ) { if ( item.mType != MediaMeta::MT_Int32 ) { WARNING("invalid type for %s\n", item.mName); continue; } mPriv->mMute = item.mValue.ii; mPriv->setMute(mPriv->mMute); INFO("key: %s, value: %d\n", item.mName, mPriv->mMute); } if ( !strcmp(item.mName, MEDIA_ATTR_VOLUME) ) { if ( item.mType != MediaMeta::MT_Int64 ) { WARNING("invalid type for %s\n", item.mName); continue; } mPriv->mVolume = item.mValue.ld; mPriv->setVolume(mPriv->mVolume); INFO("key: %s, value: %" PRId64 "\n", item.mName, mPriv->mMute); } if ( !strcmp(item.mName, MEDIA_ATTR_PALY_RATE) ) { if ( item.mType != MediaMeta::MT_Int32 ) { WARNING("invalid type for %s\n", item.mName); continue; } if (mPriv->mScaledPlayRate == item.mValue.ii) { DEBUG("play rate is already %d, just return\n", mPriv->mScaledPlayRate); continue; } mPriv->mScaledPlayRate = item.mValue.ii; DEBUG("key: %s, val: %d\n", item.mName, item.mValue.ii); continue; } } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::getParameter(MediaMetaSP & meta) const { ENTER(); if (!mPriv) return MM_ERROR_NO_COMPONENT; meta->setInt32(MEDIA_ATTR_MUTE, mPriv->mMute); meta->setInt64(MEDIA_ATTR_VOLUME, mPriv->mVolume); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } int64_t AudioSinkPulse::getCurrentPosition() { if (!mPriv) return MM_ERROR_NO_COMPONENT; PAMMAutoLock paLoop(mPriv->mPALoop); int64_t currentPosition = -1ll; if (mPriv->mClockWrapper && mPriv->mClockWrapper->getCurrentPosition(currentPosition) != MM_ERROR_SUCCESS) { ERROR("getCurrentPosition failed"); currentPosition = -1ll; } VERBOSE("getCurrentPosition %" PRId64 " ms", currentPosition/1000ll); return currentPosition; } void AudioSinkPulse::onSetMetaData(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); EXIT(); } void AudioSinkPulse::onPrepare(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); mPriv->mPAWriteableSize = 0; mm_status_t ret = mPriv->creatPAContext(); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create context\n"); notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam); EXIT1(); } ret = mPriv->creatPAStream(); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); notify(kEventError, MM_ERROR_NO_MEM, 0, nilParam); EXIT1(); } setState(mPriv->mState, mPriv->STATE_PREPARED); notify(kEventPrepareResult, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } mm_status_t AudioSinkPulse::Private::resumeInternal() { if (!mIsPaused || mIsDraining) { ERROR("Aready started\n"); mAudioSink->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t ret = cork(0); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); mAudioSink->notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); } if (mIsPaused && mClockWrapper) { mClockWrapper->resume(); } mIsPaused = false; setState(mState, STATE_STARTED); mAudioSink->notify(kEventStartResult, MM_ERROR_SUCCESS, 0, nilParam); mOutputThread->signalContinue(); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } void AudioSinkPulse::onStart(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); // create thread to handle output buffer if (!mPriv->mOutputThread) { mPriv->mOutputThread.reset (new AudioSinkPulse::Private::OutputThread(mPriv.get()), MMThread::releaseHelper); mPriv->mOutputThread->create(); } mPriv->resumeInternal(); EXIT1(); } void AudioSinkPulse::onResume(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); mPriv->resumeInternal(); EXIT1(); } void AudioSinkPulse::onStop(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { mPriv->mIsPaused = true; if (mPriv->mOutputThread) { mPriv->mOutputThread->signalExit(); mPriv->mOutputThread.reset(); } } PAMMAutoLock paLoop(mPriv->mPALoop); if (mPriv->mState == mPriv->STATE_IDLE || mPriv->mState == mPriv->STATE_STOPED || mPriv->mIsDraining) { notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } if (mPriv->mState == mPriv->STATE_STARTED) { mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } ret = mPriv->cork(1); if (MM_ERROR_SUCCESS != ret) { ERROR("cork fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } } mPriv->clearPACallback(); setState(mPriv->mState, mPriv->STATE_STOPED); notify(kEventStopped, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onPause(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); PAMMAutoLock paLoop(mPriv->mPALoop); mPriv->mIsPaused = true; if (mPriv->mState == mPriv->STATE_PAUSED || mPriv->mIsDraining) { notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } mm_status_t ret = mPriv->cork(1); if ( ret != MM_ERROR_SUCCESS ) { ERROR("failed to create stream\n"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->pause(); } setState(mPriv->mState, mPriv->STATE_PAUSED); notify(kEventPaused, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onFlush(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { PAMMAutoLock paLoop(mPriv->mPALoop); mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } } MMAutoLock locker(mPriv->mLock); mPriv->clearSourceBuffers(); notify(kEventFlushComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onSeek(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { PAMMAutoLock paLoop(mPriv->mPALoop); mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } } MMAutoLock locker(mPriv->mLock); mPriv->clearSourceBuffers(); notify(kEventSeekComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onReset(param1_type param1, param2_type param2, uint32_t rspId) { ENTER1(); { mPriv->mIsPaused = true; if (mPriv->mOutputThread) { mPriv->mOutputThread->signalExit(); mPriv->mOutputThread.reset(); } } { PAMMAutoLock paLoop(mPriv->mPALoop); if (mPriv->mState == mPriv->STATE_STARTED) { mm_status_t ret = mPriv->streamFlush(); if (MM_ERROR_SUCCESS != ret) { ERROR("flush fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } if (mPriv->mClockWrapper) { mPriv->mClockWrapper->flush(); } ret = mPriv->cork(1); if (MM_ERROR_SUCCESS != ret) { ERROR("cork fail"); notify(kEventError, MM_ERROR_OP_FAILED, 0, nilParam); EXIT1(); } } mPriv->clearPACallback(); } { MMAutoLock locker(mPriv->mLock); mPriv->mScaledPlayRate = SCALED_PLAY_RATE; mPriv->clearSourceBuffers(); } mPriv->release(); setState(mPriv->mState, mPriv->STATE_IDLE); notify(kEventResetComplete, MM_ERROR_SUCCESS, 0, nilParam); EXIT1(); } void AudioSinkPulse::onSetParameters(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); /* if (!strcmp((char *)param1, "setVolume")) { setVolume((double)param2); } else if (!strcmp((char *)param1, "setMute")) { setMute((bool)param2); } else if (!strcmp((char *)param1, "sampleRate")) { mSampleRate = (uint32_t)param2; } else if (!strcmp((char *)param1, "format")) { mFormat = (snd_format_t)param2; } else if (!strcmp((char *)param1, "channel")) { mChannelCount = (uint8_t)param2; } */ //notify(EVENT_SETPARAMETERSCOMPLETE, MM_ERROR_SUCCESS, 0, NULL); EXIT(); } void AudioSinkPulse::onGetParameters(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); //if (!strcmp((char *)param1, "getVolume")) { // notify(EVENT_GETPARAMETERSCOMPLETE, getVolume(), 0, NULL); //} else if (!strcmp((char *)param1, "getMute")) { // notify(EVENT_GETPARAMETERSCOMPLETE, getMute(), 0, NULL); //} EXIT(); } void AudioSinkPulse::onWrite(param1_type param1, param2_type param2, uint32_t rspId) { ENTER(); AudioSinkPulse::Private::QueueEntry *pEntry = (AudioSinkPulse::Private::QueueEntry *)param2; if (pEntry->mBuffer) { MMAutoLock locker(mPriv->mLock); mPriv->mAvailableSourceBuffers.push(pEntry->mBuffer); mPriv->mCondition.signal(); } else { WARNING("Write NULL buffer"); } delete pEntry; EXIT(); } bool AudioSinkPulse::Private::waitPAOperation(pa_operation *op) { if (!op) { return false; } pa_operation_state_t state = pa_operation_get_state(op); while (state == PA_OPERATION_RUNNING) { pa_threaded_mainloop_wait(mPALoop); state = pa_operation_get_state(op); } pa_operation_unref(op); return state == PA_OPERATION_DONE; } snd_format_t AudioSinkPulse::Private::convertFormatFromPulse(pa_sample_format paFormat) { ENTER(); for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) { if (format_map[i].pa == paFormat) EXIT_AND_RETURN(format_map[i].spformat); } EXIT_AND_RETURN(SND_FORMAT_INVALID); } pa_sample_format AudioSinkPulse::Private::convertFormatToPulse(snd_format_t format) { ENTER(); for (int i = 0; format_map[i].spformat != SND_FORMAT_INVALID; ++i) { if (format_map[i].spformat == format) EXIT_AND_RETURN(format_map[i].pa); } EXIT_AND_RETURN(PA_SAMPLE_INVALID); } void AudioSinkPulse::Private::contextStateCallback(pa_context *c, void *userdata) { ENTER(); if (c == NULL) { ERROR("invalid param\n"); return; } AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); switch (pa_context_get_state(c)) { case PA_CONTEXT_CONNECTING: case PA_CONTEXT_AUTHORIZING: case PA_CONTEXT_SETTING_NAME: break; case PA_CONTEXT_READY: case PA_CONTEXT_TERMINATED: case PA_CONTEXT_FAILED: pa_threaded_mainloop_signal (me->mPALoop, 0); break; default: break; } EXIT(); } void AudioSinkPulse::Private::contextSinkinputInfoCallback(pa_context *c, const pa_sink_input_info *i, int eol, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (!i) goto done; if (!me->mPAStream) goto done; if (i->index == pa_stream_get_index (me->mPAStream)) { me->mVolume = pa_sw_volume_to_linear (pa_cvolume_max (&i->volume)); me->mMute = i->mute; } done: pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } void AudioSinkPulse::Private::contextSubscribeCallback(pa_context *c, pa_subscription_event_type_t type, uint32_t idx, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); unsigned facility = type & PA_SUBSCRIPTION_EVENT_FACILITY_MASK; pa_subscription_event_type_t t = pa_subscription_event_type_t(type & PA_SUBSCRIPTION_EVENT_TYPE_MASK); switch (facility) { case PA_SUBSCRIPTION_EVENT_SINK: break; case PA_SUBSCRIPTION_EVENT_SINK_INPUT: if (me->mPAStream && idx == pa_stream_get_index(me->mPAStream )) { switch (t) { case PA_SUBSCRIPTION_EVENT_REMOVE: INFO("PulseAudio sink killed"); break; default: pa_operation *op = pa_context_get_sink_input_info(c, idx, contextSinkinputInfoCallback, me); if (!op) { ERROR("failed to get pa sink input info"); } break; } } break; case PA_SUBSCRIPTION_EVENT_CARD: INFO("PA_SUBSCRIPTION_EVENT_CARD"); break; default: break; } EXIT(); } void AudioSinkPulse::Private::contextSinkInfoCallback(pa_context *c, const pa_sink_input_info *i, int is_last, void *userdata) { ENTER(); INFO("context sink info"); EXIT(); } void AudioSinkPulse::Private::streamStateCallback(pa_stream *s, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); switch (pa_stream_get_state(s)) { case PA_STREAM_FAILED: INFO("pa stream failed"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; case PA_STREAM_READY: INFO("pa stream ready"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; case PA_STREAM_TERMINATED: INFO("pa stream terminated"); pa_threaded_mainloop_signal(me->mPALoop, 0); break; default: break; } EXIT(); } void AudioSinkPulse::Private::streamLatencyUpdateCallback(pa_stream *s, void *userdata) { ENTER(); #if 0 AudioSinkPulse *me = static_cast<AudioSinkPulse*>(userdata); MMASSERT(me); const pa_timing_info *info; pa_usec_t sink_usec; info = pa_stream_get_timing_info (s); if (!info) { return; } sink_usec = info->configured_sink_usec; VERBOSE("write_index_corrupt = %d write_index = %llu read_index_corrupt = %d read_index = %d info->sink_usec = %llu configured_sink_usec = %llu \n", info->write_index_corrupt, info->write_index, info->read_index_corrupt, info->read_index, info->sink_usec, sink_usec); #endif EXIT(); } void AudioSinkPulse::Private::streamUnderflowCallback(pa_stream *s, void *userdata) { ENTER(); INFO("under flow"); EXIT(); } void AudioSinkPulse::Private::streamOverflowCallback(pa_stream *s, void *userdata) { ENTER(); INFO("over flow"); EXIT(); } void AudioSinkPulse::Private::streamWriteCallback(pa_stream *s, size_t length, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (!me->mIsPaused) { MMAutoLock locker(me->mLock); if (!me->mAvailableSourceBuffers.empty()) { me->mCondition.signal(); } VERBOSE("stream write length = %d",length); } EXIT(); } void AudioSinkPulse::Private::streamSuspendedCallback (pa_stream * s, void *userdata) { ENTER(); AudioSinkPulse::Private *me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); if (pa_stream_is_suspended (s)) INFO ("stream suspended"); else INFO ("stream resumed"); EXIT(); } void AudioSinkPulse::Private::streamStartedCallback (pa_stream * s, void *userdata) { ENTER(); INFO ("stream started"); EXIT(); } void AudioSinkPulse::Private::streamEventCallback (pa_stream * s, const char *name, pa_proplist * pl, void *userdata) { ENTER(); INFO ("stream event name = %s",name); EXIT(); } mm_status_t AudioSinkPulse::Private::creatPAContext() { ENTER(); int ret; pa_mainloop_api *api; /* Set up a new main loop */ MMLOGV("newing pa thread main loop\n"); mPALoop = pa_threaded_mainloop_new(); if (mPALoop == NULL){ PA_ERROR(MM_ERROR_NO_MEM, "failed to get pa api", pa_context_errno(mPAContext)); } api = pa_threaded_mainloop_get_api(mPALoop); pa_proplist *proplist = pa_proplist_new(); if ( !proplist ) { PA_ERROR(MM_ERROR_NO_MEM, "failed to new proplist", pa_context_errno(mPAContext)); } ret = pa_proplist_sets(proplist, "log-backtrace", "10"); if ( ret < 0 ) { pa_proplist_free(proplist); PA_ERROR(MM_ERROR_NO_MEM, "failed to set proplist", ret); } mPAContext = pa_context_new_with_proplist(api, COMPONENT_NAME, proplist); pa_proplist_free(proplist); if (mPAContext == NULL) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa api", pa_context_errno(mPAContext)); } pa_context_set_state_callback(mPAContext, contextStateCallback, this); /* Connect the context */ INFO("connecting pa context\n"); ret = pa_context_connect(mPAContext, "127.0.0.1", PA_CONTEXT_NOFLAGS, NULL); if ( ret < 0) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to connect to context", ret); } INFO("starting pa mainloop\n"); ret = pa_threaded_mainloop_start(mPALoop); if(ret != 0){ PA_ERROR(MM_ERROR_OP_FAILED, "failed to start mainloop", ret); } mm_status_t result; INFO("waitting context ready\n"); PAMMAutoLock paLoop(mPALoop); while ( 1 ) { pa_context_state_t state = pa_context_get_state (mPAContext); INFO("now state: %d\n", state); if ( state == PA_CONTEXT_READY ) { INFO("ready\n"); result = MM_ERROR_SUCCESS; break; } else if ( state == PA_CONTEXT_TERMINATED || state == PA_CONTEXT_FAILED ) { INFO("terminated or failed\n"); result = MM_ERROR_OP_FAILED; break; } INFO("not expected state, wait\n"); pa_threaded_mainloop_wait (mPALoop); } EXIT_AND_RETURN(result); } mm_status_t AudioSinkPulse::Private::creatPAStream() { ENTER(); pa_format_info *format = pa_format_info_new(); format->encoding = PA_ENCODING_PCM; pa_sample_format paFormat = convertFormatToPulse((snd_format_t)mFormat); if (paFormat == PA_SAMPLE_INVALID) { ERROR("PulseAudio: invalid format"); EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); } pa_format_info_set_sample_format(format, paFormat); pa_format_info_set_channels(format, mChannelCount); pa_format_info_set_rate(format, mSampleRate); // pa_format_info_set_channel_map(fi, NULL); if (!pa_format_info_valid(format)) { ERROR("PulseAudio: invalid format"); pa_format_info_free(format); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_sample_spec ss; ss.channels = mChannelCount; ss.format = convertFormatToPulse((snd_format_t)mFormat); ss.rate = mSampleRate; pa_proplist *pl = pa_proplist_new(); if (pl) { pa_proplist_sets(pl, "log-backtrace", "10"); } #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_ENSURE(mAudioConnectionId, MMAMHelper::playChnnelMain()); #endif MMLOGI("device: %s\n", mAudioConnectionId.c_str()); pa_proplist_sets(pl, "connection_id", mAudioConnectionId.c_str()); mPAStream = pa_stream_new_with_proplist(mPAContext, "audio stream", &ss, NULL, pl); //mPAStream = pa_stream_new_extended(mPAContext, "audio stream", &format, 1, pl); if (!mPAStream) { pa_format_info_free(format); pa_proplist_free(pl); ERROR("PulseAudio: failed to create a stream"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_format_info_free(format); pa_proplist_free(pl); /* install essential callbacks */ pa_stream_set_write_callback(mPAStream, streamWriteCallback, this); pa_stream_set_state_callback(mPAStream, streamStateCallback, this); pa_stream_set_underflow_callback (mPAStream, streamUnderflowCallback, this); pa_stream_set_overflow_callback (mPAStream, streamOverflowCallback, this); //pa_stream_set_latency_update_callback (mPAStream, streamLatencyUpdateCallback, this); pa_stream_set_suspended_callback (mPAStream, streamSuspendedCallback, this); pa_stream_set_started_callback (mPAStream, streamStartedCallback, this); pa_stream_set_event_callback (mPAStream, streamEventCallback, this); pa_sample_spec sample_spec = { .format = paFormat, .rate = (uint32_t)mSampleRate, .channels = (uint8_t)mChannelCount }; pa_buffer_attr wanted; wanted.maxlength = (uint32_t)-1; // max buffer size on the server wanted.tlength = (uint32_t) pa_usec_to_bytes(PA_USEC_PER_MSEC * 200/*DEFAULT_TLENGTH_MSEC*/, &sample_spec); //wanted.tlength = (uint32_t)-1; // ? wanted.prebuf = 1;//(uint32_t)-1; // play as soon as possible wanted.minreq = (uint32_t)-1; wanted.fragsize = (uint32_t)-1; // PA_STREAM_NOT_MONOTONIC? pa_stream_flags_t flags = pa_stream_flags_t(PA_STREAM_NOT_MONOTONIC|PA_STREAM_INTERPOLATE_TIMING|PA_STREAM_AUTO_TIMING_UPDATE); if (pa_stream_connect_playback(mPAStream, NULL, &wanted, flags, NULL, NULL) < 0) { ERROR("PulseAudio failed: pa_stream_connect_playback"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } PAMMAutoLock paLoop(mPALoop); while (true) { const pa_stream_state_t st = pa_stream_get_state(mPAStream); if (st == PA_STREAM_READY) break; if (!PA_STREAM_IS_GOOD(st)) { ERROR("PulseAudio stream init failed"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } pa_threaded_mainloop_wait(mPALoop); } if (pa_stream_is_suspended(mPAStream)) { ERROR("PulseAudio stream is suspende"); EXIT_AND_RETURN(MM_ERROR_OP_FAILED); } INFO("over\n"); EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePAContext() { PAMMAutoLock paLoop(mPALoop); if (mPAContext) { pa_context_disconnect (mPAContext); pa_context_unref (mPAContext); mPAContext = NULL; } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePASteam() { ENTER(); PAMMAutoLock paLoop(mPALoop); if (mPAStream) { pa_stream_disconnect (mPAStream); pa_stream_unref(mPAStream); mPAStream = NULL; } #ifdef ENABLE_DEFAULT_AUDIO_CONNECTION ENSURE_AUDIO_DEF_CONNECTION_CLEAN(); #endif EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::freePALoop() { ENTER(); if (mPALoop) { pa_threaded_mainloop_stop(mPALoop); pa_threaded_mainloop_free(mPALoop); mPALoop = NULL; } EXIT_AND_RETURN(MM_ERROR_SUCCESS); } mm_status_t AudioSinkPulse::Private::streamFlush() { ENTER(); mFlushResult = 0; if (!waitPAOperation(pa_stream_flush(mPAStream, streamFlushCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); } INFO("result: %d\n", mFlushResult); EXIT_AND_RETURN(mFlushResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamFlushCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mFlushResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::cork(int b) { ENTER(); mCorkResult = 0; if (!waitPAOperation(pa_stream_cork(mPAStream, b, streamCorkCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); } INFO("result: %d\n", mCorkResult); EXIT_AND_RETURN(mCorkResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamCorkCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mCorkResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::streamDrain() { ENTER(); mDrainResult = 0; mIsDraining = true; if (!waitPAOperation(pa_stream_drain(mPAStream, streamDrainCallback, this))) { ERROR("fail to drain stream"); } INFO("mDrainResult= %d",mDrainResult); mIsDraining = false; EXIT_AND_RETURN(mFlushResult > 0 ? MM_ERROR_SUCCESS : MM_ERROR_OP_FAILED); } void AudioSinkPulse::Private::streamDrainCallback(pa_stream*s, int success, void *userdata) { ENTER(); AudioSinkPulse::Private * me = static_cast<AudioSinkPulse::Private*>(userdata); MMASSERT(me); me->mDrainResult = success ? 1 : -1; pa_threaded_mainloop_signal (me->mPALoop, 0); EXIT(); } mm_status_t AudioSinkPulse::Private::release() { ENTER(); mm_status_t ret; ret = freePASteam(); ret = freePAContext(); ret = freePALoop(); EXIT_AND_RETURN(ret); } void AudioSinkPulse::Private::clearPACallback() { if (mPAContext) { /* Make sure we don't get any further callbacks */ pa_context_set_state_callback (mPAContext, NULL, NULL); pa_context_set_subscribe_callback (mPAContext, NULL, NULL); } if (mPAStream) { /* Make sure we don't get any further callbacks */ pa_stream_set_state_callback(mPAStream, NULL, NULL); pa_stream_set_write_callback(mPAStream, NULL, NULL); pa_stream_set_underflow_callback(mPAStream, NULL, NULL); pa_stream_set_overflow_callback(mPAStream, NULL, NULL); pa_stream_set_latency_update_callback (mPAStream, NULL, NULL); pa_stream_set_suspended_callback (mPAStream, NULL, NULL); pa_stream_set_started_callback (mPAStream, NULL, NULL); pa_stream_set_event_callback (mPAStream, NULL, NULL); } } void AudioSinkPulse::Private::clearSourceBuffers() { while(!mAvailableSourceBuffers.empty()) { mAvailableSourceBuffers.pop(); } } mm_status_t AudioSinkPulse::Private::setVolume(double volume) { ENTER(); if (mPALoop) EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); PAMMAutoLock paLoop(mPALoop); pa_cvolume vol; pa_operation *o = NULL; uint32_t idx; mVolume = volume; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; pa_cvolume_reset(&vol, mChannelCount); pa_cvolume_set(&vol, mChannelCount, pa_volume_t(volume*double(PA_VOLUME_NORM))); if (!(o = pa_context_set_sink_input_volume (mPAContext, idx, &vol, NULL, NULL))) goto volume_failed; unlock: if (o) pa_operation_unref (o); EXIT_AND_RETURN(MM_ERROR_SUCCESS); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } volume_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } double AudioSinkPulse::Private::getVolume() { ENTER(); double v = DEFAULT_VOLUME; pa_operation *o = NULL; uint32_t idx; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!waitPAOperation(pa_context_get_sink_input_info(mPAContext, idx, contextSinkinputInfoCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto volume_failed; } unlock: v = mVolume; if (o) pa_operation_unref (o); EXIT_AND_RETURN(v); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } volume_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } mm_status_t AudioSinkPulse::Private::setMute(bool mute) { ENTER(); if (!mPALoop) EXIT_AND_RETURN(MM_ERROR_INVALID_PARAM); PAMMAutoLock paLoop(mPALoop); pa_operation *o = NULL; uint32_t idx; mMute = mute; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!(o = pa_context_set_sink_input_mute (mPAContext, idx, mute, NULL, NULL))) goto mute_failed; unlock: if (o) pa_operation_unref (o); EXIT_AND_RETURN(MM_ERROR_SUCCESS); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } mute_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } bool AudioSinkPulse::Private::getMute() { ENTER(); pa_operation *o = NULL; uint32_t idx; bool mute = mMute; if ((idx = pa_stream_get_index (mPAStream)) == PA_INVALID_INDEX) goto no_index; if (!waitPAOperation(pa_context_get_sink_input_info(mPAContext, idx, contextSinkinputInfoCallback, this))) { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto mute_failed; } unlock: mute = mMute; if (o) pa_operation_unref (o); EXIT_AND_RETURN(mute); /* ERRORS */ no_index: { INFO ("we don't have a stream index"); goto unlock; } mute_failed: { PA_ERROR(MM_ERROR_OP_FAILED, "failed to get pa sink input info", pa_context_errno(mPAContext)); goto unlock; } } mm_status_t AudioSinkPulse::setAudioConnectionId(const char * connectionId) { mPriv->mAudioConnectionId = connectionId; return MM_ERROR_SUCCESS; } const char * AudioSinkPulse::getAudioConnectionId() const { return mPriv->mAudioConnectionId.c_str(); } } ///////////////////////////////////////////////////////////////////////////////////// extern "C" { YUNOS_MM::Component* createComponent(const char* mimeType, bool isEncoder) { //INFO("createComponent"); YUNOS_MM::AudioSinkPulse *sinkComponent = new YUNOS_MM::AudioSinkPulse(mimeType, isEncoder); if (sinkComponent == NULL) { return NULL; } return static_cast<YUNOS_MM::Component*>(sinkComponent); } void releaseComponent(YUNOS_MM::Component *component) { //INFO("createComponent"); delete component; } }
30.227218
153
0.634364
halleyzhao
c4d6b54f3224dac53975338c6ce96e7c7edfd3de
6,653
cpp
C++
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
TetrisAI/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
7
2016-11-28T13:42:44.000Z
2021-08-05T02:34:11.000Z
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
null
null
null
StandardTetrisMSVC2005/StandardTetrisMSVC2005/source/CPF.StandardTetris.STTime.cpp
PowerOlive/StandardTetris
b5cbe25541ceb45517472fe7feabea0c81fd55b0
[ "MIT" ]
8
2015-07-31T02:53:14.000Z
2020-04-12T04:36:23.000Z
// All contents of this file written by Colin Fahey ( http://colinfahey.com ) // 2007 June 4 ; Visit web site to check for any updates to this file. #include "CPF.StandardTetris.STTime.h" #include <windows.h> #include <time.h> #include <winnt.h> namespace CPF { namespace StandardTetris { // Performance Counter Variables int STTime::m_iCounterExists = 0; LARGE_INTEGER STTime::m_LICounterFrequency = {0,0}; LARGE_INTEGER STTime::m_LICounterReferenceValue = {0,0}; // time(NULL) Variable int STTime::m_iSecondsSince1970ReferenceValue = 0; // Interval Duration LARGE_INTEGER STTime::m_LICounterIntervalReferenceValue = {0,0}; double STTime::m_double_IntervalSeconds = (0.0); float STTime::m_float_IntervalSeconds = (0.0f); // The following sets the reference time to the time of the call. // All future calls to GetTimeSecondsXXXXX() will be relative to // this reference time. void STTime::SetReferenceTimeToNow() { // Clear values STTime::m_iCounterExists = 0; STTime::m_LICounterFrequency.QuadPart = 0; STTime::m_LICounterReferenceValue.QuadPart = 0; STTime::m_iSecondsSince1970ReferenceValue = 0; STTime::m_LICounterIntervalReferenceValue.QuadPart = 0; STTime::m_double_IntervalSeconds = (0.0); STTime::m_float_IntervalSeconds = (0.0f); // Determine if we have a performance counter. // We do this by requesting the frequency. STTime::m_iCounterExists = (int) QueryPerformanceFrequency( (&(STTime::m_LICounterFrequency)) ); // If we have a performance counter, get the current // value for our starting value. This will be our // initial "current" value, too. if (STTime::m_iCounterExists) { QueryPerformanceCounter( (&(STTime::m_LICounterReferenceValue)) ); } // Set the time(NULL) reference value, too. STTime::m_iSecondsSince1970ReferenceValue = (int)(time(NULL)); // Set the Interval Duration Reference Time STTime::m_LICounterIntervalReferenceValue.QuadPart = (STTime::m_LICounterReferenceValue.QuadPart); STTime::m_double_IntervalSeconds = (0.0); STTime::m_float_IntervalSeconds = (0.0f); } double STTime::GetRelativeTimeSecondsDouble( ) { // If we don't have a performance counter, we can't honor this request. if (0 == (STTime::m_iCounterExists)) { // We don't have a performance counter. return( 0.0 ); } LARGE_INTEGER LICounterDeltaValue; QueryPerformanceCounter( (&(LICounterDeltaValue)) ); LICounterDeltaValue.QuadPart -= ((STTime::m_LICounterReferenceValue).QuadPart); double dSeconds = 0.0f; if ((STTime::m_LICounterFrequency.QuadPart) > 0) { dSeconds = (double)(LICounterDeltaValue.QuadPart) / (double)((STTime::m_LICounterFrequency.QuadPart)); } return( dSeconds ); } float STTime::GetRelativeTimeSecondsFloat( ) { return( ((float)(GetRelativeTimeSecondsDouble())) ); } int STTime::GetRelativeTimeSecondsInteger( ) { return( ((int)(GetRelativeTimeSecondsDouble())) ); } int STTime::GetTimeWallClockSecondsSince1970( ) { int iSecondsSince1970 = 0; iSecondsSince1970 = (int)time( NULL ); return ( iSecondsSince1970 ); } int STTime::GetWallClockReferenceValueSeconds( ) { return ( (STTime::m_iSecondsSince1970ReferenceValue) ); } int STTime::GetRelativeTimeWallClockSeconds( ) { int iSecondsSince1970 = 0; iSecondsSince1970 = (int)time( NULL ); return ( iSecondsSince1970 - (STTime::m_iSecondsSince1970ReferenceValue) ); } double STTime::GetIntervalDurationSecondsDouble( ) { // Return cached interval duration in seconds, as a 'double'. // ( 60fps --> 0.0166 sec/frame; 85fps --> 0.0117 sec/frame ) return( STTime::m_double_IntervalSeconds ); } float STTime::GetIntervalDurationSecondsFloat( ) { // Return cached interval duration in seconds, as a 'float'. // ( 60fps --> 0.0166 sec/frame; 85fps --> 0.0117 sec/frame ) return( STTime::m_float_IntervalSeconds ); } void STTime::NextIntervalBeginsNow( ) { // If we don't have a performance counter, we can't honor this request. if (0 == (STTime::m_iCounterExists)) { // We don't have a performance counter. return; } // Conter Value for "Now" LARGE_INTEGER LICounterValue; QueryPerformanceCounter( (&(LICounterValue)) ); // Difference between previous counter value and "Now" LARGE_INTEGER LICounterDeltaValue; LICounterDeltaValue.QuadPart = LICounterValue.QuadPart; LICounterDeltaValue.QuadPart -= ((STTime::m_LICounterIntervalReferenceValue).QuadPart); // Compute difference in seconds (double precision). double dSeconds = 0.0f; if ((STTime::m_LICounterFrequency.QuadPart) > 0) { dSeconds = (double)(LICounterDeltaValue.QuadPart) / (double)((STTime::m_LICounterFrequency.QuadPart)); } // Cast duration time to float (single precision). float fSeconds = ((float)(dSeconds)); // Cache both representations of interval duration value. STTime::m_double_IntervalSeconds = (dSeconds); STTime::m_float_IntervalSeconds = (fSeconds); // Set the interval reference value to "now". STTime::m_LICounterIntervalReferenceValue.QuadPart = LICounterValue.QuadPart; } int STTime::PerformanceCounterExists( ) { return( (STTime::m_iCounterExists) ); } void STTime::GetCounterFrequencyHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = ((STTime::m_LICounterFrequency).HighPart); refLow32 = ((STTime::m_LICounterFrequency).LowPart); } void STTime::GetCounterReferenceHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = ((STTime::m_LICounterReferenceValue).HighPart); refLow32 = ((STTime::m_LICounterReferenceValue).LowPart); } void STTime::GetCounterCurrentHighLow ( unsigned int &refHigh32, unsigned int &refLow32 ) { refHigh32 = 0; refLow32 = 0; if (0 == (STTime::m_iCounterExists)) return; LARGE_INTEGER LICounterCurrent; QueryPerformanceCounter( (&(LICounterCurrent)) ); refHigh32 = (LICounterCurrent.HighPart); refLow32 = (LICounterCurrent.LowPart); } } }
22.706485
78
0.654291
TetrisAI
c4d8f724b1ae9b3fdb11a760ac1d12c7d7f8e956
11,639
cpp
C++
c_src/wamr_sandbox_runtime.cpp
PLSysSec/rlbox_wamr_sandbox
774aa15528a198717cc5f257a17f0f1553fbac84
[ "MIT" ]
null
null
null
c_src/wamr_sandbox_runtime.cpp
PLSysSec/rlbox_wamr_sandbox
774aa15528a198717cc5f257a17f0f1553fbac84
[ "MIT" ]
null
null
null
c_src/wamr_sandbox_runtime.cpp
PLSysSec/rlbox_wamr_sandbox
774aa15528a198717cc5f257a17f0f1553fbac84
[ "MIT" ]
null
null
null
#include "aot_runtime.h" #include "wamr_sandbox.h" #include "wasm_c_api.h" #include "wasm_c_api_internal.h" #include <deque> #include <iostream> #include <map> #include <mutex> #include <optional> #include <stdio.h> #include <string> #define DYN_CHECK(check, msg) \ if (!(check)) { \ std::cerr << msg << std::endl; \ std::abort(); \ } struct WamrSandboxCallbackSlot { uint32_t callback_index; void** func_ptr_slot; uint32_t* func_type_slot; }; struct WamrSandboxInstance { wasm_engine_t* engine; wasm_store_t* store; wasm_module_t* wasm_module; wasm_instance_t* instance; WASMExecEnv* exec_env; std::mutex callback_slot_mutex; std::deque<WamrSandboxCallbackSlot> free_callback_slots; std::map<uint32_t, WamrSandboxCallbackSlot> used_callback_slots; std::map<void*, uint32_t> internal_callbacks; }; static std::mutex wamr_sandbox_create_mutex; static inline wasm_byte_vec_t wamr_get_vec_from_file( const char* wamr_module_path) { FILE* file = fopen(wamr_module_path, "rb"); DYN_CHECK(file != nullptr, "Could not open AOT sandbox file"); fseek(file, 0L, SEEK_END); size_t file_size = ftell(file); fseek(file, 0L, SEEK_SET); wasm_byte_vec_t binary; wasm_byte_vec_new_uninitialized(&binary, file_size); auto read_result = fread(binary.data, file_size, 1, file); DYN_CHECK(read_result == 1, "Could not read AOT sandbox file"); fclose(file); return binary; } static inline WamrSandboxCallbackSlot wamr_get_callback_slot( WamrSandboxInstance* sbx, void* reserved_pointer, const uint32_t callback_table_offset) { auto m = (AOTModule*)*(sbx->wasm_module); auto inst_aot = (AOTModuleInstance*)sbx->instance->inst_comm_rt; uint64_t indirect_func_table_start = m->import_func_count; uint64_t indirect_func_table_end = indirect_func_table_start + m->func_count; auto func_ptrs = (void**)inst_aot->func_ptrs.ptr; auto func_types = (uint32_t*)inst_aot->func_type_indexes.ptr; for (uint64_t idx = indirect_func_table_start, i = 0; idx < indirect_func_table_end; idx++, i++) { void* curr_func_ptr = func_ptrs[idx]; if (curr_func_ptr == reserved_pointer) { func_ptrs[idx] = nullptr; WamrSandboxCallbackSlot ret; ret.callback_index = i - callback_table_offset; ret.func_ptr_slot = &(func_ptrs[idx]); ret.func_type_slot = &(func_types[idx]); return ret; } } DYN_CHECK(false, "Could not locate reserved callback pointer"); } void* wamr_lookup_function(WamrSandboxInstance* sbx, const char* func_name) { auto inst_aot = (AOTModuleInstance*)sbx->instance->inst_comm_rt; for (size_t i = 0; i < inst_aot->export_func_count; i++) { auto func_comm_rt = ((AOTFunctionInstance*)inst_aot->export_funcs.ptr) + i; if (strcmp(func_name, func_comm_rt->func_name) == 0) { DYN_CHECK(!func_comm_rt->is_import_func, "Expected reserved callback slot to not be imported"); void* raw_pointer = func_comm_rt->u.func.func_ptr; return raw_pointer; } } DYN_CHECK(false, "Could not find raw pointer for function"); } // The callback table indexes are offset in some unspecified way // What looks like index 3 to the host seems to be index 1 to the sbx // Compute this offset static uint32_t wamr_compute_callback_table_offset(WamrSandboxInstance* sbx) { const char* func_name = "sandboxReservedCallbackSlot1"; // wasm_func_t* func_slot = wamr_lookup_function_metadata(sbx, func_name); // uint32_t expected_index = // wamr_run_function_return_u32(sbx, func_slot, 0, nullptr); void* reserved_pointer = wamr_lookup_function(sbx, func_name); using fn_cb_t = uint32_t (*)(uintptr_t); auto fn_ptr = (fn_cb_t) reserved_pointer; uint32_t expected_index = fn_ptr(wamr_get_func_call_env_param(sbx)); auto m = (AOTModule*)*(sbx->wasm_module); auto inst_aot = (AOTModuleInstance*)sbx->instance->inst_comm_rt; uint64_t indirect_func_table_start = m->import_func_count; uint64_t indirect_func_table_end = indirect_func_table_start + m->func_count; auto func_ptrs = (void**)inst_aot->func_ptrs.ptr; for (uint64_t idx = indirect_func_table_start, i = 0; idx < indirect_func_table_end; idx++, i++) { void* curr_func_ptr = func_ptrs[idx]; if (curr_func_ptr == reserved_pointer) { return i - expected_index; } } DYN_CHECK(false, "Could not compute callback table offset"); } static inline void wamr_initialize_callback_slots(WamrSandboxInstance* sbx) { const uint32_t callback_table_offset = wamr_compute_callback_table_offset(sbx); const std::string prefix = "sandboxReservedCallbackSlot"; for (size_t i = 1; i <= 128; i++) { const std::string func_name = prefix + std::to_string(i); void* raw_ptr = wamr_lookup_function(sbx, func_name.c_str()); WamrSandboxCallbackSlot slot = wamr_get_callback_slot(sbx, raw_ptr, callback_table_offset); sbx->free_callback_slots.push_back(slot); } } WamrSandboxInstance* wamr_load_module(const char* wamr_module_path) { const std::lock_guard<std::mutex> lock(wamr_sandbox_create_mutex); WamrSandboxInstance* ret = new WamrSandboxInstance(); auto engine = wasm_engine_new(); DYN_CHECK(engine != nullptr, "Could not create wasm engine"); ret->engine = engine; auto store = wasm_store_new(engine); DYN_CHECK(store != nullptr, "Could not create wasm store"); ret->store = store; wasm_byte_vec_t binary = wamr_get_vec_from_file(wamr_module_path); auto wasm_module = wasm_module_new(store, &binary); DYN_CHECK(wasm_module != nullptr, "Could not create wasm wasm_module"); ret->wasm_module = wasm_module; auto instance = wasm_instance_new(store, wasm_module, nullptr, nullptr); DYN_CHECK(instance != nullptr, "Could not create wasm instance"); ret->instance = instance; auto inst_aot = (AOTModuleInstance*)instance->inst_comm_rt; // Backtrace support (WAMR_BUILD_DUMP_CALL_STACK) is disabled as this adds a // lot of code to the TCB for very little gain. We should be able to set this // to zero, but its not clear that the wamr runtime would be ok with this. Set // this to something small so that any attempt to use this stack will fault. const uint32_t backtrace_stack_size = 1; auto exec_env = wasm_exec_env_create((WASMModuleInstanceCommon*)inst_aot, backtrace_stack_size); DYN_CHECK(exec_env != nullptr, "Could not create wasm exec_env"); ret->exec_env = exec_env; wamr_initialize_callback_slots(ret); wasm_byte_vec_delete(&binary); return ret; } void wamr_drop_module(WamrSandboxInstance* inst) { const std::lock_guard<std::mutex> lock(wamr_sandbox_create_mutex); wasm_exec_env_destroy(inst->exec_env); wasm_instance_delete(inst->instance); wasm_module_delete(inst->wasm_module); wasm_store_delete(inst->store); wasm_engine_delete(inst->engine); delete inst; } void* wamr_get_heap_base(WamrSandboxInstance* inst) { wasm_instance_t* instance = (wasm_instance_t*)inst->instance; AOTModuleInstance* module_inst = (AOTModuleInstance*)instance->inst_comm_rt; auto memory_count = module_inst->memory_count; DYN_CHECK(memory_count == 1, "Found multiple memories in wasm module. Expected 1."); void* heap_start = module_inst->global_table_data.memory_instances[0].memory_data.ptr; return heap_start; } size_t wamr_get_heap_size(WamrSandboxInstance* inst) { const size_t gb = 1 * 1024 * 1024 * 1024; return 4 * gb; } void wamr_set_curr_instance(WamrSandboxInstance* inst) {} void wamr_clear_curr_instance(WamrSandboxInstance* inst) {} uintptr_t wamr_get_func_call_env_param(WamrSandboxInstance* inst) { return (uintptr_t) inst->exec_env; } static inline bool wasm_type_matches(uint8 value_type, WamrValueType value_type2) { if (value_type == VALUE_TYPE_VOID && value_type2 == WamrValueType::WamrValueType_Void) { return true; } if (value_type == VALUE_TYPE_I32 && value_type2 == WamrValueType::WamrValueType_I32) { return true; } if (value_type == VALUE_TYPE_I64 && value_type2 == WamrValueType::WamrValueType_I64) { return true; } if (value_type == VALUE_TYPE_F32 && value_type2 == WamrValueType::WamrValueType_F32) { return true; } if (value_type == VALUE_TYPE_F64 && value_type2 == WamrValueType::WamrValueType_F64) { return true; } return false; } static inline bool wamr_signature_matches(AOTFuncType& func_type, WamrFunctionSignature& csig) { if (func_type.param_count != csig.parameter_cnt) { return false; } if (func_type.result_count == 0 && csig.ret != WamrValueType::WamrValueType_Void) { return false; } // don't support multi returns if (func_type.result_count > 1) { return false; } for (uint32_t i = 0; i < func_type.param_count; i++) { if (!wasm_type_matches(func_type.types[i], csig.parameters[i])) { return false; } } const uint64_t ret_types_start = func_type.param_count; const uint64_t ret_types_end = ret_types_start + func_type.result_count; for (uint64_t i = ret_types_start; i < ret_types_end; i++) { if (!wasm_type_matches(func_type.types[i], csig.ret)) { return false; } } return true; } static inline uint32_t wamr_find_type_index(WamrSandboxInstance* inst, WamrFunctionSignature& csig) { auto m = (AOTModule*)*(inst->wasm_module); uint64_t func_type_count = m->func_type_count; AOTFuncType** func_types = m->func_types; for (uint64_t i = 0; i < func_type_count; i++) { if (wamr_signature_matches(*(func_types[i]), csig)) { return i; } } DYN_CHECK(false, "Function type index not found"); } uint32_t wamr_register_callback(WamrSandboxInstance* inst, WamrFunctionSignature csig, const void* func_ptr) { uint32_t type_index = wamr_find_type_index(inst, csig); const std::lock_guard<std::mutex> lock(inst->callback_slot_mutex); DYN_CHECK(inst->free_callback_slots.size() > 0, "No free callback slots left"); WamrSandboxCallbackSlot slot = inst->free_callback_slots.front(); inst->free_callback_slots.pop_front(); inst->used_callback_slots[slot.callback_index] = slot; *slot.func_type_slot = type_index; *slot.func_ptr_slot = const_cast<void*>(func_ptr); return slot.callback_index; } void wamr_unregister_callback(WamrSandboxInstance* inst, uint32_t slot_num) { const std::lock_guard<std::mutex> lock(inst->callback_slot_mutex); auto iter = inst->used_callback_slots.find(slot_num); DYN_CHECK(iter != inst->used_callback_slots.end(), "Could not find the given callback slot to unregister"); WamrSandboxCallbackSlot slot = iter->second; inst->used_callback_slots.erase(iter); inst->free_callback_slots.push_back(slot); *slot.func_ptr_slot = nullptr; } uint32_t wamr_register_internal_callback(WamrSandboxInstance* inst, WamrFunctionSignature csig, const void* func_ptr) { auto iter = inst->internal_callbacks.find(const_cast<void*>(func_ptr)); if (iter != inst->internal_callbacks.end()) { // already created internal callback return iter->second; } auto ret = wamr_register_callback(inst, csig, func_ptr); return ret; }
31.627717
98
0.701521
PLSysSec
c4db9b92e93f7d7a1cbccfe9ebeecdd2b80d9af1
758
cpp
C++
ch09/0918ex.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
ch09/0918ex.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
null
null
null
ch09/0918ex.cpp
mallius/CppPrimer
0285fabe5934492dfed0a9cf67ba5650982a5f76
[ "MIT" ]
1
2022-01-25T15:51:34.000Z
2022-01-25T15:51:34.000Z
#include <iostream> #include <string> #include <vector> #include <list> #include <deque> using std::string; using std::vector; using std::list; using std::deque; using std::cout; using std::endl; using std::cin; int main(void) { int array[] = {1,2,3,4,5,6,7,8}; list<int> ilist(array, array+7); deque<int> d1, d2; for(list<int>::iterator it = ilist.begin(); it != ilist.end(); ++it) { cout << *it << ", "; if(*it%2==0) { d1.push_back(*it); } else { d2.push_back(*it); } } cout << endl; for(deque<int>::iterator dit = d1.begin(); dit != d1.end(); ++dit) { cout << *dit << ", "; } cout << endl; for(deque<int>::iterator dit = d2.begin(); dit != d2.end(); ++dit) { cout << *dit << ", "; } cout << endl; return 0; }
15.469388
69
0.558047
mallius
c4de62966a0e0c839e1d97b62f55390fd6d9de3e
1,001
cpp
C++
2020/prototype/src/robot-config.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
1
2021-12-13T06:24:19.000Z
2021-12-13T06:24:19.000Z
2020/prototype/src/robot-config.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
1
2021-06-03T00:17:19.000Z
2021-06-03T00:25:14.000Z
2020/prototype/src/robot-config.cpp
eshsrobotics/vex
bc3b03a6694924c59139c8a761929b8c9a1b6248
[ "MIT" ]
2
2018-10-28T23:59:13.000Z
2019-11-17T18:29:34.000Z
#include "vex.h" using namespace vex; using signature = vision::signature; using code = vision::code; // A global instance of brain used for printing to the V5 Brain screen brain Brain; // VEXcode device constructors motor RightFront = motor(PORT1, ratio18_1, true); motor LeftFront = motor(PORT19, ratio18_1, false); motor RightBack = motor(PORT3, ratio18_1, true); motor LeftBack = motor(PORT4, ratio18_1, false); controller Controller1 = controller(primary); line LeftLineTracker = line(Brain.ThreeWirePort.A); line MiddleLineTracker = line(Brain.ThreeWirePort.B); line RightLineTracker = line(Brain.ThreeWirePort.C); gyro GyroD = gyro(Brain.ThreeWirePort.D); // VEXcode generated functions // define variable for remote controller enable/disable bool RemoteControlCodeEnabled = true; /** * Used to initialize code/tasks/devices added using tools in VEXcode Pro. * * This should be called at the start of your int main function. */ void vexcodeInit( void ) { // nothing to initialize }
31.28125
74
0.764236
eshsrobotics
c4e349124c61bfeaf017fc7be7d766f4305914b5
7,495
cpp
C++
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
37
2017-02-04T09:42:48.000Z
2021-02-17T14:59:15.000Z
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
120
2017-11-09T19:46:40.000Z
2022-01-20T18:26:23.000Z
tests/reflection_tests.cpp
Revolution-Populi/fc
02b7593a96b02d9966358c59d22f344d86fa9a19
[ "BSL-1.0", "Apache-2.0", "Zlib" ]
109
2017-01-16T14:24:31.000Z
2022-03-18T21:10:07.000Z
#include <boost/test/unit_test.hpp> #include <fc/exception/exception.hpp> #include <type_traits> struct reflect_test_base { int x = 1; char y = 'a'; }; struct reflect_test_derived : reflect_test_base { double z = 3.14; }; struct reflect_layer_1 { reflect_test_base b; int32_t n; }; struct reflect_layer_2 { reflect_layer_1 l1; reflect_test_derived d; }; struct reflect_layer_3 { reflect_layer_2 l2; int32_t i; }; FC_REFLECT( reflect_test_base, (x)(y) ); FC_REFLECT_DERIVED( reflect_test_derived, (reflect_test_base), (z) ); FC_REFLECT( reflect_layer_1, (b)(n) ); FC_REFLECT( reflect_layer_2, (l1)(d) ); FC_REFLECT( reflect_layer_3, (l2)(i) ); BOOST_AUTO_TEST_SUITE( fc_reflection ) BOOST_AUTO_TEST_CASE( reflection_static_tests ) { // These are all compile-time tests, nothing actually happens here at runtime using base_reflection = fc::reflector<reflect_test_base>; using derived_reflection = fc::reflector<reflect_test_derived>; static_assert(fc::typelist::length<base_reflection::members>() == 2, ""); static_assert(fc::typelist::length<derived_reflection::members>() == 3, ""); static_assert(fc::typelist::at<derived_reflection::members, 0>::is_derived, ""); static_assert(std::is_same<fc::typelist::at<derived_reflection::members, 0>::field_container, reflect_test_base>::value, ""); static_assert(fc::typelist::at<derived_reflection::members, 1>::is_derived, ""); static_assert(std::is_same<fc::typelist::at<derived_reflection::members, 1>::field_container, reflect_test_base>::value, ""); static_assert(fc::typelist::at<derived_reflection::members, 2>::is_derived == false, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 1>, fc::typelist::list<int>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 2>, fc::typelist::list<int, bool>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 0, 3>, fc::typelist::list<int, bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1, 3>, fc::typelist::list<bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 2, 3>, fc::typelist::list<char>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1, 2>, fc::typelist::list<bool>>::value, ""); static_assert(std::is_same<fc::typelist::slice<fc::typelist::list<int, bool, char>, 1>, fc::typelist::list<bool, char>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<0>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<1>, fc::typelist::list<std::integral_constant<size_t, 0>>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<2>, fc::typelist::list<std::integral_constant<size_t, 0>, std::integral_constant<size_t, 1>>>::value, ""); static_assert(std::is_same<fc::typelist::make_sequence<3>, fc::typelist::list<std::integral_constant<size_t, 0>, std::integral_constant<size_t, 1>, std::integral_constant<size_t, 2>>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<>, fc::typelist::list<>>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<bool>, fc::typelist::list<char>>, fc::typelist::list<fc::typelist::list<bool, char>>>::value, ""); static_assert(std::is_same<fc::typelist::zip<fc::typelist::list<int, bool>, fc::typelist::list<char, double>>, fc::typelist::list<fc::typelist::list<int, char>, fc::typelist::list<bool, double>>>::value, ""); static_assert(std::is_same<fc::typelist::index<fc::typelist::list<>>, fc::typelist::list<>>::value, ""); static_assert(std::is_same<fc::typelist::index<fc::typelist::list<int, bool, char, double>>, fc::typelist::list<fc::typelist::list<std::integral_constant<size_t, 0>, int>, fc::typelist::list<std::integral_constant<size_t, 1>, bool>, fc::typelist::list<std::integral_constant<size_t, 2>, char>, fc::typelist::list<std::integral_constant<size_t, 3>, double>> >::value, ""); } BOOST_AUTO_TEST_CASE( typelist_dispatch_test ) { using list = fc::typelist::list<float, bool, char>; auto get_name = [](auto t) -> std::string { return fc::get_typename<typename decltype(t)::type>::name(); }; BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 0ul, get_name), "float"); BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 1ul, get_name), "bool"); BOOST_CHECK_EQUAL(fc::typelist::runtime::dispatch(list(), 2ul, get_name), "char"); } // Helper template to use fc::typelist::at without a comma, for macro friendliness template<typename T> struct index_from { template<std::size_t idx> using at = fc::typelist::at<T, idx>; }; BOOST_AUTO_TEST_CASE( reflection_get_test ) { try { reflect_test_derived derived; reflect_test_base& base = derived; using base_reflector = fc::reflector<reflect_test_base>; using derived_reflector = fc::reflector<reflect_test_derived>; BOOST_CHECK(index_from<base_reflector::members>::at<0>::get(base) == 1); BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'a'); fc::typelist::at<base_reflector::members, 0>::get(base) = 5; fc::typelist::at<base_reflector::members, 1>::get(base) = 'q'; BOOST_CHECK(index_from<base_reflector::members>::at<0>::get(base) == 5); BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'q'); BOOST_CHECK(index_from<derived_reflector::members>::at<0>::get(derived) == 5); BOOST_CHECK(index_from<derived_reflector::members>::at<1>::get(derived) == 'q'); BOOST_CHECK(index_from<derived_reflector::members>::at<2>::get(derived) == 3.14); fc::typelist::at<derived_reflector::members, 1>::get(derived) = 'X'; BOOST_CHECK(index_from<base_reflector::members>::at<1>::get(base) == 'X'); reflect_layer_3 l3; BOOST_CHECK(index_from<index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0> ::reflector::members>::at<0>::reflector::members>::at<0>::reflector::members>::at<1>::get(l3.l2.l1.b) == 'a'); BOOST_CHECK(index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0>::reflector::members> ::at<1>::reflector::members>::at<1>::get(l3.l2.d) == 'a'); BOOST_CHECK(index_from<index_from<index_from<fc::reflector<reflect_layer_3>::members>::at<0>::reflector::members> ::at<1>::reflector::members>::at<2>::get(l3.l2.d) == 3.14); } FC_CAPTURE_LOG_AND_RETHROW( (0) ) } BOOST_AUTO_TEST_SUITE_END()
59.015748
116
0.623616
Revolution-Populi
c4e5f434f6c43ca834c0c4c6709c294eed762910
15,230
cpp
C++
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
SRC/text/text_render.cpp
GlisGames/vbEngine
239659e154c08d1867418e611891a7961dbe8258
[ "MIT" ]
null
null
null
#include "text_render.h" //#include "scope_guard.h" #include "math.h" #include "rlgl.h" #include <assert.h> #include <ft2build.h> #include FT_FREETYPE_H #include FT_OUTLINE_H //#define TEXT_USE_SHADER #include <algorithm> #include <cstdlib> #include <cstdio> #if defined(PLATFORM_DESKTOP) #define GLSL_VERSION 330 #else // PLATFORM_RPI, PLATFORM_ANDROID, PLATFORM_WEB #define GLSL_VERSION 100 #endif //------------------------------------------------------------------------------ static const char* vertex_shader_string = R"( #version 100 attribute vec3 vertexPosition; attribute vec2 vertexTexCoord; attribute vec3 vertexNormal; attribute vec4 vertexColor; uniform mat4 mvp; varying vec2 fragTexCoord; varying vec4 fragColor; void main() { fragTexCoord = vertexTexCoord; fragColor = vertexColor; gl_Position = mvp*vec4(vertexPosition, 1.0); } )"; static const char* sdf_shader = R"( #version 100 precision mediump float; // Input vertex attributes (from vertex shader) varying vec2 fragTexCoord; varying vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 colDiffuse; // NOTE: Add here your custom variables const float smoothing = 1.0/16.0; void main() { // Texel color fetching from texture sampler // NOTE: Calculate alpha using signed distance field (SDF) float distance = texture2D(texture0, fragTexCoord).a; float alpha = smoothstep(0.5 - smoothing, 0.5 + smoothing, distance); // Calculate final fragment color //gl_FragColor = vec4(fragColor.rgb, fragColor.a*alpha); gl_FragColor = vec4(fragColor.rgb, texture2D(texture0, fragTexCoord).r*alpha); } )"; static const char* sdf_shader33 = R"( #version 330 // Input vertex attributes (from vertex shader) in vec2 fragTexCoord; in vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 colDiffuse; // Output fragment color out vec4 finalColor; // NOTE: Add here your custom variables void main() { // Texel color fetching from texture sampler // NOTE: Calculate alpha using signed distance field (SDF) float distanceFromOutline = texture(texture0, fragTexCoord).a - 0.5; float distanceChangePerFragment = length(vec2(dFdx(distanceFromOutline), dFdy(distanceFromOutline))); float alpha = smoothstep(-distanceChangePerFragment, distanceChangePerFragment, distanceFromOutline); // Calculate final fragment color //finalColor = vec4(fragColor.rgb, fragColor.a*alpha); finalColor = vec4(fragColor.rgb, texture2D(texture0, fragTexCoord).r*alpha); } )"; static const char* fragment_shader_string = R"( #version 100 precision mediump float; // Input vertex attributes (from vertex shader) varying vec2 fragTexCoord; varying vec4 fragColor; // Input uniform values uniform sampler2D texture0; uniform vec4 textColor; void main() { vec4 texelColor = vec4(1.0, 1.0, 1.0, texture2D(texture0, fragTexCoord).r); gl_FragColor = texelColor*textColor; } )"; const int TextureAtlasWidth = 1024; const int TextureAtlasHeight = 1024; //------------------------------------------------------------------------------ TextRender::TextRender() : texReq_(0), texHit_(0), texEvict_(0), line_(Glyph{}), lastTexID_(0) { } TextRender::~TextRender() { } bool TextRender::Init(int numTextureAtlas) { assert(numTextureAtlas > 0 && numTextureAtlas <= 16); std::string errorLog; #if !defined(PLATFORM_WEB) && !defined(PLATFORM_RPI) mys = LoadShader("vertex_shader.txt", "fragment_shader.txt");//FromMemory(vertex_shader_string, fragment_shader_string); //sdfShader = LoadShader("vertex_shader.txt", "fragment_shader.txt");//FromMemory(vertex_shader_string, fragment_shader_string); #else mys = LoadShaderFromMemory(vertex_shader_string, fragment_shader_string); #endif mysLocation = GetShaderLocation(mys, "textColor"); //for (int i = 0; i < numTextureAtlas; i++) //{ // std::unique_ptr<TextureAtlas> t(new TextureAtlas); // if (!t->Init(TextureAtlasWidth, TextureAtlasHeight)) // { // return false; // } // tex_.push_back(std::move(t)); // texGen_.push_back(0); //} line_.TexIdx = -1; return true; } void TextRender::DrawTextureFonthere(Texture2D texture, Rectangle source, Rectangle dest, Vector2 origin, float rotation, Color tint) { // Check if texture is valid if (texture.id > 0) { float width = (float)texture.width; float height = (float)texture.height; bool flipX = false; if (source.width < 0) { flipX = true; source.width *= -1; } if (source.height < 0) source.y -= source.height; Vector2 topLeft = { 0 }; Vector2 topRight = { 0 }; Vector2 bottomLeft = { 0 }; Vector2 bottomRight = { 0 }; // Only calculate rotation if needed if (rotation == 0.0f) { float x = dest.x - origin.x; float y = dest.y - origin.y; topLeft = { x, y }; topRight = { x + dest.width, y }; bottomLeft = { x, y + dest.height }; bottomRight = { x + dest.width, y + dest.height }; } else { float sinRotation = sinf(rotation * DEG2RAD); float cosRotation = cosf(rotation * DEG2RAD); float x = dest.x; float y = dest.y; float dx = -origin.x; float dy = -origin.y; topLeft.x = x + dx * cosRotation - dy * sinRotation; topLeft.y = y + dx * sinRotation + dy * cosRotation; topRight.x = x + (dx + dest.width) * cosRotation - dy * sinRotation; topRight.y = y + (dx + dest.width) * sinRotation + dy * cosRotation; bottomLeft.x = x + dx * cosRotation - (dy + dest.height) * sinRotation; bottomLeft.y = y + dx * sinRotation + (dy + dest.height) * cosRotation; bottomRight.x = x + (dx + dest.width) * cosRotation - (dy + dest.height) * sinRotation; bottomRight.y = y + (dx + dest.width) * sinRotation + (dy + dest.height) * cosRotation; } rlCheckRenderBatchLimit(4); // Make sure there is enough free space on the batch buffer rlBegin(RL_QUADS); rlSetTexture(texture.id); rlColor4ub(tint.r, tint.g, tint.b, tint.a); rlNormal3f(0.0f, 0.0f, 1.0f); // Normal vector pointing towards viewer // Top-left corner for texture and quad rlTexCoord2f(source.x, source.y); rlVertex2f(topLeft.x, topLeft.y); // Bottom-left corner for texture and quad rlTexCoord2f(source.x, (source.y + source.height)); rlVertex2f(bottomLeft.x, bottomLeft.y); // Bottom-right corner for texture and quad rlTexCoord2f((source.x + source.width), (source.y + source.height)); rlVertex2f(bottomRight.x, bottomRight.y); // Top-right corner for texture and quad rlTexCoord2f((source.x + source.width), source.y); rlVertex2f(topRight.x, topRight.y); rlEnd(); rlSetTexture(0); } } #define MEMCMP(a, b) memcmp((a), (b), (sizeof(a) < sizeof(b)) ? sizeof(a) : sizeof(b)) void TextRender::DrawTextBoundingAlfons(vbTextbox* text, float initialx, float initialy, Color color, float zoom, float rotation) { #ifdef TEXT_USE_SHADER BeginShaderMode(mys); if (MEMCMP(&color, &currentColor_) != 0) { currentColor_ = color; float tocolor[4] = { (float)color.r / 255.0f, (float)color.g / 255.0f, (float)color.b / 255.0f, (float)color.a / 255.0f, }; SetShaderValue(mys, this->mysLocation, tocolor, SHADER_UNIFORM_VEC4); } #endif text->draw(initialx, initialy); #ifdef TEXT_USE_SHADER EndShaderMode(); #endif if (text->debugBox) //debug bounding box DrawRectangleLinesEx({ initialx, initialy, text->getBoundingBox().x ,text->getBoundingBox().y }, 1, RED); //DrawLine(initialx, initialy, 1000, initialy, VIOLET); //Debug baseline } /* void TextRender::CacheText(vbTextbox* text) { // Iterate over each glyph. size_t glyph_count = text->GetGlyphCount(); float x = 0; float y = 0; float zoom = 1; float maxs = text->getMaxHeight(); Vector2 box = text->getPrintSize(); UnloadTexture(text->cachetxt); //------------------------------------- RenderTexture2D target = LoadRenderTexture(box.x, box.y); BeginTextureModePro(target); this->DrawText(text, 0, 0, text->colour, text->zoom, text->rotation); //text->cachetxt = target.texture; Image toflip = GetTextureData(target.texture); ImageFlipVertical(&toflip); text->cachetxt = LoadTextureFromImage(toflip); //void *data = rlReadScreenPixels(target.) EndTextureMode(); UnloadRenderTexture(target); //rlUnloadFramebuffer(target.id); return; /* //Image im = GenImageColor(box.x, box.y, CLITERAL(Color){ 255, 0, 0, 255 }); //im.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; text->cachetxt = LoadTextureFromImage(GenImageColor(box.x, box.y, BLANK)); //UpdateTexture for (size_t i = 0; i < glyph_count; i++) { GlyphInfo info; text->GetGlyph(i, info); Glyph g; if (!getGlyph(text->GetFont(), info.glyphid, g)) { // TODO: error log break; } if (g.Size.x > 0 && g.Size.y > 0) { TextureAtlas* t = tex_[g.TexIdx].get(); float glyph_x = (x + g.Bearing.x * zoom + info.x_offset * zoom); float glyph_y = y - (g.descent * zoom + g.Bearing.y * zoom) - info.y_offset * zoom; //OK NO FLIP glyph_y += (g.ff->bbox.yMax / 64.0f) * zoom; glyph_y += maxs; float glyph_w = (float)g.Size.x; float glyph_h = (float)g.Size.y; float tex_x = g.TexOffset.x; float tex_y = g.TexOffset.y; float tex_w = glyph_w * zoom; float tex_h = glyph_h * zoom; Rectangle source = { tex_x, tex_y, tex_w, tex_h }; Rectangle dest = { glyph_x, glyph_y, glyph_w * zoom, glyph_h * zoom }; UpdateTextureRec(text->cachetxt, dest, rlReadTexturePixelsRect(t->texture_, source)); //text->cachetxt.format = PIXELFORMAT_UNCOMPRESSED_GRAYSCALE; //UpdateTextureRec(text->cachetxt, dest, g.ff->glyph->bitmap.buffer); } // advance cursors for next glyph x += info.x_advance * zoom; y += info.y_advance * zoom; } } */ void TextRender::PrintStats() { fprintf(stdout, "\n"); fprintf(stdout, "----glyph texture cache stats----\n"); fprintf(stdout, "texture atlas size: %d %d\n", TextureAtlasWidth, TextureAtlasHeight); fprintf(stdout, "texture atlas count: %d\n", (int)tex_.size()); fprintf(stdout, "texture atlas occupancy:"); for (size_t i = 0; i < tex_.size(); i++) { //float rate = tex_[i]->get()->Occupancy() * 100.f; //HACK float rate = tex_[i]->Occupancy() * 100.f; fprintf(stdout, " %.1f%%", rate); } fprintf(stdout, "\n"); fprintf(stdout, "texture atlas evict: %llu\n", texEvict_); fprintf(stdout, "request: %llu\n", texReq_); fprintf(stdout, "hit : %llu (%.2f%%)\n", texHit_, (double)texHit_ / texReq_ * 100); fprintf(stdout, "\n"); } bool TextRender::getGlyph(vbFont *font, unsigned int glyph_index, Glyph& x) { GlyphKey key = GlyphKey{ font->getID(), glyph_index }; GlyphCache::iterator iter = glyphs_.find(key); if (iter != glyphs_.end()) { x = iter->second; if (x.TexIdx < 0) { return true; } else if (x.TexGen == texGen_[x.TexIdx]) // check texture atlas generation { texReq_++; texHit_++; return true; } } // load glyph FT_Face face = font->getFTFont(); if (FT_Load_Glyph(face, glyph_index, FT_LOAD_DEFAULT)) //FT_LOAD_DEFAULT { return false; } if (font->synthesisItalic()) { // horizontal shear FT_Matrix matrix; matrix.xx = 0x10000L; matrix.xy = (FT_Fixed)(0.3 * 0x10000L); matrix.yx = 0; matrix.yy = 0x10000L; FT_Outline_Transform(&face->glyph->outline, &matrix); } if (font->synthesisBold()) { FT_Outline_Embolden(&face->glyph->outline, (FT_Pos)(font->getSize() * 0.04 * 64)); } if (FT_Render_Glyph(face->glyph, FT_RENDER_MODE_NORMAL)) { return false; } int texIdx = -1; unsigned int texGen = 0; uint16_t texOffsetX = 0, texOffsetY = 0; if (face->glyph->bitmap.width > 0 && face->glyph->bitmap.rows > 0) { if (!addToTextureAtlas(face->glyph->bitmap.width, face->glyph->bitmap.rows, face->glyph->bitmap.buffer, texIdx, texGen, texOffsetX, texOffsetY)) { return false; } texReq_++; } // now store Glyph for later use x = Glyph{ {(float)face->glyph->bitmap.width,(float)face->glyph->bitmap.rows}, {(float)face->glyph->bitmap_left, (float)face->glyph->bitmap_top}, {(float)texOffsetX, (float)texOffsetY}, texIdx, texGen, (float)face->ascender/64.0f, (float)face->bbox.yMax/ 64.0f, (float)face->size->metrics.height / 64.0f, face }; glyphs_[key] = x; return true; } bool TextRender::setupLineGlyph() { if (line_.TexIdx >= 0 && line_.TexGen == texGen_[line_.TexIdx]) { return true; } static uint8_t data[4*4] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, }; uint16_t tex_x, tex_y; if (addToTextureAtlas(4, 4, data, line_.TexIdx, line_.TexGen, tex_x, tex_y)) { line_.Size.x = 4; line_.Size.y = 4; line_.TexOffset.x = tex_x; line_.TexOffset.y = tex_y; return true; } return false; } bool TextRender::addToTextureAtlas(uint16_t width, uint16_t height, const uint8_t *data, int &tex_idx, unsigned int &tex_gen, uint16_t &tex_x, uint16_t &tex_y) { for (size_t i = 0; i < tex_.size(); i++) { //TextureAtlas *t = tex_[i].get(); //HACK TextureAtlas *t = tex_[i]; if (t->AddRegion(width, height, data, tex_x, tex_y)) { tex_idx = (unsigned int)i; tex_gen = texGen_[i]; return true; } } // evict a random choosed one size_t index = (size_t)rand() % tex_.size(); //TextureAtlas *tex = tex_[index].get();// TextureAtlas *tex = tex_[index]; // clear contents tex->Clear(); // increment generation texGen_[index]++; texEvict_++; // retry if (tex->AddRegion(width, height, data, tex_x, tex_y)) { tex_idx = index; tex_gen = texGen_[index]; return true; } return false; } void TextRender::setTexID(unsigned int texID) { } void TextRender::commitDraw() { }
29.746094
133
0.599146
GlisGames
c4e619db5d837ef5c6ab9dc38cc3c34a47c6dc3b
2,233
cc
C++
test/test_rocks_storage.cc
UHH-ISS/beemaster-acu-portscan
f33dcddf490cfa1b768fcf16d91184ab47e20c9f
[ "MIT" ]
null
null
null
test/test_rocks_storage.cc
UHH-ISS/beemaster-acu-portscan
f33dcddf490cfa1b768fcf16d91184ab47e20c9f
[ "MIT" ]
null
null
null
test/test_rocks_storage.cc
UHH-ISS/beemaster-acu-portscan
f33dcddf490cfa1b768fcf16d91184ab47e20c9f
[ "MIT" ]
null
null
null
/* test_rocks_storage.cc * ACU Implementation (test) * * Test functionality of RocksStorage * * @author: 1wilkens, 0ortmann */ #include "catch.hpp" #include <rocks_storage.h> const std::string PATH = "/tmp/test_storage"; TEST_CASE("Testing RocksStorage initialisation", "[rocks_storage]") { // TODO FIXME XXX DIRTY AF std::system("rm -rf /tmp/test_storage"); auto storage = new beemaster::RocksStorage(PATH); delete storage; } TEST_CASE("Test RocksStorage write operations", "[rocks_storage]") { std::system("rm -rf /tmp/test_storage"); auto storage = new beemaster::RocksStorage(PATH); auto key = "KEY"; std::string value1 = "VALUE_1"; std::string value2 = "VALUE_2"; std::string value3 = "VAL_3"; SECTION("Append on empty field") { REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Get(key) == value1); delete storage; } SECTION("Append with merge") { REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Get(key) == value1 + "|" + value2); delete storage; } SECTION("Append ordered dedupe") { REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Get(key) == value1); REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Get(key) == value1 + "|" + value2); REQUIRE(storage->Append(key, value3)); REQUIRE(storage->Get(key) == value1 + "|" + value2 + "|" + value3); REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Append(key, value3)); REQUIRE(storage->Get(key) == value1 + "|" + value2 + "|" + value3); delete storage; } SECTION("Append unordered dedupe") { REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Append(key, value3)); REQUIRE(storage->Append(key, value3)); REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Append(key, value1)); REQUIRE(storage->Append(key, value2)); REQUIRE(storage->Get(key) == value2 + "|" + value1 + "|" + value3); delete storage; } }
28.628205
75
0.60815
UHH-ISS
c4e75411c33b92f88850d1171256d8664fa1b29c
5,550
cxx
C++
main/xmloff/source/transform/DeepTContext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
679
2015-01-06T06:34:58.000Z
2022-03-30T01:06:03.000Z
main/xmloff/source/transform/DeepTContext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
102
2017-11-07T08:51:31.000Z
2022-03-17T12:13:49.000Z
main/xmloff/source/transform/DeepTContext.cxx
Grosskopf/openoffice
93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7
[ "Apache-2.0" ]
331
2015-01-06T11:40:55.000Z
2022-03-14T04:07:51.000Z
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_xmloff.hxx" #include "DeepTContext.hxx" #ifndef _XMLOFF_FLATTTCONTEXT_HXX #include "FlatTContext.hxx" #endif #include "EventOOoTContext.hxx" #include "TransformerActions.hxx" #include "ElemTransformerAction.hxx" #include "PersMixedContentTContext.hxx" #ifndef _XMLOFF_TRANSFORMERBASE_HXX #include "TransformerBase.hxx" #endif using ::rtl::OUString; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::xml::sax; TYPEINIT1( XMLPersElemContentTContext, XMLPersAttrListTContext ); void XMLPersElemContentTContext::AddContent( XMLTransformerContext *pContext ) { OSL_ENSURE( pContext && pContext->IsPersistent(), "non-persistent context" ); XMLTransformerContextVector::value_type aVal( pContext ); m_aChildContexts.push_back( aVal ); } XMLPersElemContentTContext::XMLPersElemContentTContext( XMLTransformerBase& rImp, const OUString& rQName ) : XMLPersAttrListTContext( rImp, rQName ) { } XMLPersElemContentTContext::XMLPersElemContentTContext( XMLTransformerBase& rImp, const OUString& rQName, sal_uInt16 nActionMap ) : XMLPersAttrListTContext( rImp, rQName, nActionMap ) { } XMLPersElemContentTContext::XMLPersElemContentTContext( XMLTransformerBase& rImp, const OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken ) : XMLPersAttrListTContext( rImp, rQName, nPrefix, eToken ) { } XMLPersElemContentTContext::XMLPersElemContentTContext( XMLTransformerBase& rImp, const OUString& rQName, sal_uInt16 nPrefix, ::xmloff::token::XMLTokenEnum eToken, sal_uInt16 nActionMap ) : XMLPersAttrListTContext( rImp, rQName, nPrefix, eToken, nActionMap ) { } XMLPersElemContentTContext::~XMLPersElemContentTContext() { } XMLTransformerContext *XMLPersElemContentTContext::CreateChildContext( sal_uInt16 nPrefix, const OUString& rLocalName, const OUString& rQName, const Reference< XAttributeList >& ) { XMLTransformerContext *pContext = 0; XMLTransformerActions::key_type aKey( nPrefix, rLocalName ); XMLTransformerActions::const_iterator aIter = GetTransformer().GetElemActions().find( aKey ); if( !(aIter == GetTransformer().GetElemActions().end()) ) { switch( (*aIter).second.m_nActionType ) { case XML_ETACTION_COPY: pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName ); break; case XML_ETACTION_COPY_TEXT: pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName ); break; case XML_ETACTION_RENAME_ELEM: pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1() ); break; case XML_ETACTION_RENAME_ELEM_PROC_ATTRS: pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1(), static_cast< sal_uInt16 >( (*aIter).second.m_nParam2 ) ); break; case XML_ETACTION_RENAME_ELEM_ADD_PROC_ATTR: { XMLPersMixedContentTContext *pMC = new XMLPersMixedContentTContext( GetTransformer(), rQName, (*aIter).second.GetQNamePrefixFromParam1(), (*aIter).second.GetQNameTokenFromParam1(), static_cast< sal_uInt16 >( (*aIter).second.m_nParam3 >> 16 ) ); pMC->AddAttribute( (*aIter).second.GetQNamePrefixFromParam2(), (*aIter).second.GetQNameTokenFromParam2(), static_cast< ::xmloff::token::XMLTokenEnum >( (*aIter).second.m_nParam3 & 0xffff ) ); pContext = pMC; } break; case XML_ETACTION_PROC_ATTRS: pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName, static_cast< sal_uInt16 >( (*aIter).second.m_nParam1 ) ); break; default: pContext = GetTransformer().CreateUserDefinedContext( (*aIter).second, rQName, sal_True ); OSL_ENSURE( pContext && pContext->IsPersistent(), "unknown or not persistent action" ); if( pContext && !pContext->IsPersistent() ) { delete pContext; pContext = 0; } break; } } // default is copying if( !pContext ) pContext = new XMLPersMixedContentTContext( GetTransformer(), rQName ); XMLTransformerContextVector::value_type aVal( pContext ); m_aChildContexts.push_back( aVal ); return pContext; } void XMLPersElemContentTContext::ExportContent() { XMLTransformerContextVector::iterator aIter = m_aChildContexts.begin(); for( ; aIter != m_aChildContexts.end(); ++aIter ) { (*aIter)->Export(); } }
31.179775
78
0.71964
Grosskopf
c4e789272073d984d72598c4e43028f912886c60
2,198
hpp
C++
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
2
2022-03-10T05:51:24.000Z
2022-03-15T10:32:26.000Z
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
null
null
null
include/gaenari/supul/db/sqlite/sqlite.type.hpp
greenfish77/gaenari
cb9374498b6122800702ebcfc19543c9563345b4
[ "Apache-2.0" ]
null
null
null
#ifndef HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP #define HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP namespace supul { namespace db { namespace sqlite { // include sqlite3.h inside the namespace. #include "sqlite/sqlite3.h" // query type. enum class stmt { unknown, count_string_table, get_string_table_last_id, get_string_table, add_string_table, add_chunk, add_instance, add_instance_info, get_not_updated_instance, get_chunk, get_is_generation_empty, add_generation, update_generation, update_generation_etc, get_treenode_last_id, add_rule, add_leaf_node, add_treenode, get_instance_by_chunk_id, get_first_root_ref_treenode_id, get_treenode, update_instance_info, update_chunk, update_chunk_total_count, get_chunk_list, get_chunk_updated, update_leaf_info, get_weak_treenode, update_leaf_info_by_go_to_generation_id, get_instance_by_go_to_generation_id, get_correct_instance_count_by_go_to_generation_id, update_instance_info_with_weak_count_increment, get_root_ref_treenode_id, copy_rule, update_rule_value_integer, get_generation_id_by_treenode_id, get_leaf_info_by_chunk_id, get_total_count_by_chunk_id, delete_instance_by_chunk_id, delete_instance_info_by_chunk_id, delete_chunk_by_id, get_global_row_count, add_global_one_row, get_global, get_instance_count, get_instance_correct_count, get_updated_instance_count, get_sum_leaf_info_total_count, get_sum_weak_count, get_instance_actual_predicted, get_global_confusion_matrix, get_global_confusion_matrix_item_count, add_global_confusion_matrix_item, update_global_confusion_matrix_item_increment, get_chunk_initial_accuracy, get_chunk_last_id, get_chunk_by_id, get_chunk_for_report, get_generation_for_report, }; // implement the prepared statement to satisfy performance and security. // define statement information. // - stmt : sqlite statement object // - fields : fields of the query result. struct stmt_info { sqlite3_stmt* stmt = nullptr; type::fields fields; stmt_info(_in sqlite3_stmt* stmt, _in const type::fields& fields): stmt{stmt}, fields{fields} {} }; } // sqlite } // db } // gaenari #endif // HEADER_GAENARI_SUPUL_DB_SQLITE_SQLITE_TYPE_HPP
24.153846
97
0.838944
greenfish77
c4e81d482c8510a5cff5c89d3881eb64ceb96f41
6,058
cpp
C++
sources/day13.cpp
Gyebro/aoc19
59d00c525dd6539e121588984d2221494b0d265a
[ "MIT" ]
2
2019-12-09T16:21:46.000Z
2019-12-11T20:19:02.000Z
sources/day13.cpp
Gyebro/aoc19
59d00c525dd6539e121588984d2221494b0d265a
[ "MIT" ]
null
null
null
sources/day13.cpp
Gyebro/aoc19
59d00c525dd6539e121588984d2221494b0d265a
[ "MIT" ]
null
null
null
// // Created by Gyebro on 2019-12-13. // #include "day13.h" #include "intcode_vm.h" class display_packet { public: int64_t x; int64_t y; int64_t c; display_packet() : x(0), y(0), c(0) {} display_packet(int64_t X, int64_t Y, int64_t C) : x(X), y(Y), c(C) {} }; const string cTileChars = " +#=o "; const int64_t cJoyNeutral = 0; const int64_t cJoyLeft = -1; const int64_t cJoyRight = +1; const size_t cEmpty = 0; const size_t cWall = 1; const size_t cBlock = 2; const size_t cPaddle = 3; const size_t cBall = 4; void day13(bool part_two) { cout << "AoC D13: part " << (part_two ? "two" : "one") << endl; ifstream in("input13.txt"); if (in.is_open()) { IntcodeProgram program(in); program.reserveMemory(5000); if (!part_two) { // Part One while (!program.hasTerminated()) { program.run(); } vector<int64_t> outputs; size_t i=0; size_t blocks = 0; while (program.hasOutput()) { i++; int64_t o = program.getOutput(); if (i % 3 == 0) { switch (o) { case cEmpty:// Empty case cWall:// Wall case cPaddle:// Paddle case cBall:// Ball break; case cBlock:// Block blocks++; break; default: cout << "Error: Invalid output!\n"; break; } } outputs.push_back(o); } if (outputs.size() % 3 != 0) { cout << "Error: number of outputs is not divisible by 3!\n"; } cout << "Blocks drawn: " << blocks << endl; } else { // Configuration bool manual = false; bool print_display = false || manual; // Manual mode needs display program.writeReg(0,2); vector<display_packet> outputs; // Initialize displays program.sendInput(cJoyNeutral); program.setVerbose(false); program.run(); display_packet out(0,0,0); while (program.hasOutput()) { out.x = program.getOutput(); out.y = program.getOutput(); out.c = program.getOutput(); outputs.push_back(out); } // Find display bounds int64_t score = 0; int64_t w = 0, h = 0; for (display_packet& o : outputs) { if (o.x < 0) { score = o.c; } else { w = max(w, o.x); h = max(h, o.y); } } //cout << "Current score: " << score << endl; //cout << "Main display size: " << w << "x" << h << endl; // Build display string line(w+1,cTileChars[0]); string frame_line(w+1,'+'); vector<string> display(h+1,line); int paddle_x = 0; int ball_x = 0; for (display_packet& o : outputs) { if (o.x >= 0) { display[o.y][o.x]=cTileChars[o.c]; if (o.c == cBall) ball_x = o.x; if (o.c == cPaddle) paddle_x = o.x; } } // Print display if (print_display) { cout << frame_line << endl; cout << "+ SCORE: " << score << endl; for (const string &l : display) { cout << l << endl; } } // Play bool playing = true; while (playing) { if (manual) { cout << "Move paddle (asd): \n"; char c = getchar(); switch (c) { case 'a': program.sendInput(cJoyLeft); break; case 's': program.sendInput(cJoyNeutral); break; case 'd': program.sendInput(cJoyRight); break; default: // skip char break; } } else { // Automatic playing if (ball_x > paddle_x) { program.sendInput(cJoyRight); } else if (ball_x == paddle_x) { program.sendInput(cJoyNeutral); } else { program.sendInput(cJoyLeft); } } program.run(); if (program.hasTerminated()) playing = false; outputs.resize(0); while (program.hasOutput()) { out.x = program.getOutput(); out.y = program.getOutput(); out.c = program.getOutput(); outputs.push_back(out); } for (display_packet& o : outputs) { if (o.x >= 0) { display[o.y][o.x]=cTileChars[o.c]; if (o.c == cBall) ball_x = o.x; if (o.c == cPaddle) paddle_x = o.x; } else { score = o.c; } } if (print_display) { cout << frame_line << endl; cout << "+ SCORE: " << score << endl; for (const string &l : display) { cout << l << endl; } } } cout << "Final score: " << score << endl; } // if part_two } }
34.816092
78
0.382965
Gyebro
c4e941a3ea7ed2482032b80ed52b01701de9c04e
7,086
cpp
C++
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
libs/DiabloUI/src/selyesno.cpp
Chronimal/devilution
a7ef09e1403771f0b27d9fa1c7e5f04e8a26f9e8
[ "Unlicense" ]
null
null
null
#include "inc.h" // ref: 0x1000FA49 int __fastcall SelYesNo_YesNoDialog(HWND hWnd, char* dialogstr, char* hero, int nofocus) { yesno_dialog_string = dialogstr; yesno_hero_name = hero; yesno_remove_focus = nofocus; yesno_is_popup = 0; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SELYESNO_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FA87 LRESULT __stdcall SelYesNo_WndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) { HWND v4; // eax HWND v5; // eax int v7; // edx HWND v8; // eax LONG v9; // eax HWND v10; // ecx HWND v11; // eax if (Msg == 2) { SelYesNo_RemoveYNDialog(hWnd); return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } if (Msg > 0x103) { if (Msg <= 0x105) { v11 = (HWND)SDrawGetFrameWindow(NULL); SendMessageA(v11, Msg, wParam, lParam); return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } switch (Msg) { case 0x110u: SelYesNo_LoadSelYN_GFX(hWnd); return 0; case WM_COMMAND: if (HIWORD(wParam) == 7) { Focus_GetAndBlitSpin(hWnd, lParam); } else if (HIWORD(wParam) == 6) { Focus_CheckPlayMove(lParam); Focus_DoBlitSpinIncFrame(hWnd, (HWND)lParam); } else { v7 = 1; if ((WORD)wParam == 1) { v8 = GetFocus(); v9 = GetWindowLongA(v8, -12); v10 = hWnd; if (v9 == 1109) { v7 = 1; } else { v7 = 2; } } else { if ((WORD)wParam == 2) { v7 = 2; } else if ((WORD)wParam != 1109) { return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } v10 = hWnd; } SelYesNo_DoSelectYesNo(v10, v7); } break; case WM_TIMER: v4 = GetFocus(); if (!Focus_DoBlitSpinIncFrame(hWnd, v4)) { v5 = GetDlgItem(hWnd, 1109); if (!v5) { v5 = GetDlgItem(hWnd, 2); } SetFocus(v5); } return 0; } } return (LRESULT)SDlgDefDialogProc(hWnd, Msg, (HDC)wParam, (HWND)lParam); } // 10010382: using guessed type DWORD __stdcall SDrawGetFrameWindow(); // ref: 0x1000FBC7 void __fastcall SelYesNo_RemoveYNDialog(HWND hWnd) { HWND v1; // esi void** v2; // eax HWND v3; // eax v1 = hWnd; v2 = (void**)GetWindowLongA(hWnd, -21); local_FreeMemPtr(v2); if (yesno_remove_focus) { Focus_DeleteSpinners(); } Doom_DeleteFreeProcs(v1, yesno_msgtbl1); Doom_DeleteFreeProcs(v1, yesno_msgtbl2); if (yesno_hero_name) { v3 = GetParent(v1); SelHero_SetStringWithMsg(v3, 0); } } // 1002A500: using guessed type int yesno_remove_focus; // ref: 0x1000FC1C void __fastcall SelYesNo_LoadSelYN_GFX(HWND hWnd) { HWND v2; // eax DWORD* v3; // eax DWORD* v4; // edi const char* v5; // eax char* v6; // ST18_4 HWND v7; // eax v2 = GetParent(hWnd); if (yesno_hero_name) { SelHero_SetStringWithMsg(v2, yesno_hero_name); } v3 = local_AllocWndLongData(); v4 = v3; if (v3) { SetWindowLongA(hWnd, -21, (LONG)v3); if (yesno_is_popup) { if (DiabloUI_GetSpawned()) { v5 = "ui_art\\swmmpop.pcx"; } else { v5 = "ui_art\\mmpopup.pcx"; } } else { v5 = "ui_art\\black.pcx"; } local_LoadArtWithPal(hWnd, 0, "Popup", -1, 1, v5, (BYTE**)v4, v4 + 1, 1); } v6 = yesno_dialog_string; v7 = GetDlgItem(hWnd, 1026); SetWindowTextA(v7, v6); Doom_ParseWndProc3(hWnd, yesno_msgtbl2, AF_MEDGRAY); Doom_ParseWndProcs(hWnd, yesno_msgtbl1, AF_BIG, 1); if (yesno_remove_focus) { Focus_LoadSpinner("ui_art\\focus.pcx"); } else { Focus_ResetSpinToZero(); } SDlgSetTimer(hWnd, 1, 55, 0); local_DoUiWndProc2(hWnd, (DWORD*)yesno_msgtbl1); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FCF6 void __fastcall SelYesNo_DoSelectYesNo(HWND hWnd, int option) { HWND v4; // eax TitleSnd_PlaySelectSound(); SDlgKillTimer(hWnd, 1); if (option == 2) { if (!YesNoFunc) { goto LABEL_6; } YesNoFunc(); } if (option == 1) { v4 = GetFocus(); option = GetWindowLongA(v4, -12); } LABEL_6: SDlgEndDialog(hWnd, (HANDLE)option); } // 1002A508: using guessed type int (*YesNoFunc)(void); // ref: 0x1000FD39 int __fastcall SelYesNo_SelOkDialog(HWND hWnd, char* dialogstr, char* hero, int nofocus) { yesno_dialog_string = dialogstr; yesno_hero_name = hero; yesno_remove_focus = nofocus; yesno_is_popup = 0; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SELOK_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FD77 int __fastcall SelYesNo_SpawnErrDialog(HWND hWnd, int string_rsrc, int is_popup) { char Buffer[256]; // [esp+4h] [ebp-100h] LoadStringA(ghUiInst, string_rsrc, Buffer, 255); yesno_is_popup = is_popup; yesno_remove_focus = 0; yesno_hero_name = 0; yesno_dialog_string = Buffer; YesNoFunc = 0; return SDlgDialogBoxParam(ghUiInst, "SPAWNERR_DIALOG", hWnd, SelYesNo_WndProc, 0); } // 1002A500: using guessed type int yesno_remove_focus; // 1002A508: using guessed type int (*YesNoFunc)(void); // 1002A50C: using guessed type int yesno_is_popup; // ref: 0x1000FDE3 void __cdecl SelYesNo_cpp_init() { SelYesNo_cpp_float = SelYesNo_cpp_float_value; } // 1001F478: using guessed type int SelYesNo_cpp_float_value; // 1002A4FC: using guessed type int SelYesNo_cpp_float;
28.457831
100
0.530059
Chronimal
c4eb3145a84a203a033f3ed4f2842fecbab9fd67
540
cpp
C++
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
10 Days of Statistics/Day_6/CLT_2.cpp
yurkovak/HackerRank
a10136e508692f98e76e7c27d9cd801a3380f8ba
[ "MIT" ]
null
null
null
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> #include <math.h> // using namespace std; float CDF(float mean, float stdev, float x){ float erf_arg = (x - mean) / (pow(2, 0.5) * stdev); return (1 + erf(erf_arg))/2.; } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ float a, n; float mean, stdev; std::cin >> a >> n; std::cin >> mean >> stdev; printf ("%.4f\n", CDF(mean*n, stdev*pow(n, 0.5), a)); return 0; }
20.769231
79
0.588889
yurkovak
c4eef379800c3039198dc9a3ffe9d7eef52dccb3
680
cpp
C++
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
null
null
null
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
null
null
null
PostScrimmageBot/Commands/TurHop/Fire.cpp
FRC-Team-1410/UA2013-FRC1410-Robot
51afc88149e97ff474693ed6a69ff13ba65440e3
[ "BSD-3-Clause" ]
1
2020-05-21T09:24:15.000Z
2020-05-21T09:24:15.000Z
#include "Fire.h" Fire::Fire() { // Use requires() here to declare subsystem dependencies Requires(turhop); } // Called just before this Command runs the first time void Fire::Initialize() { } // Called repeatedly when this Command is scheduled to run void Fire::Execute() { turhop->FeederToggle(); } // Make this return true when this Command no longer needs to run execute() bool Fire::IsFinished() { return false; } // Called once after isFinished returns true void Fire::End() { turhop->SetFiringOff(); } // Called when another command which requires one or more of the same // subsystems is scheduled to run void Fire::Interrupted() { turhop->SetFiringOff(); }
20.606061
75
0.720588
FRC-Team-1410
c4f0337e7b61072e9779741064b4c624f93c7f94
6,578
hpp
C++
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
2
2017-10-02T03:18:55.000Z
2018-11-21T16:30:36.000Z
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
Code/Engine/EventSystem/NamedProperties.hpp
ntaylorbishop/Copycat
c02f2881f0700a33a2630fd18bc409177d80b8cd
[ "MIT" ]
null
null
null
#pragma once #include "Engine/General/Core/EngineCommon.hpp" #include <map> ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //ENUMS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// enum ePropertyGetResult { PGR_SUCCESS = 0, PGR_WRONG_TYPE, PGR_NOT_PRESENT, PGR_EMPTY }; enum ePropertySetResult { PSR_SET_EXISTING = 0, PSR_ADDED_NEW_PROPERTY, PSR_EXISTS_BUT_WRONG_TYPE }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //BASE AND TYPED BASE PROPERTY STRUCTS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct NamedBaseProperty { virtual ~NamedBaseProperty() { } }; template <typename T> struct TypedNamedProperty : public NamedBaseProperty { public: TypedNamedProperty(const T& data) : m_data(data) { } T m_data; }; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //NAMED PROPERTIES ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// class NamedProperties { public: //STRUCTORS NamedProperties() { } template <typename T> NamedProperties(const String& property1, const T& data1); template <typename T, typename S> NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2); template <typename T, typename S, typename U> NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2, const String& property3, const U& data3); inline ~NamedProperties(); //GET SET template <typename T> ePropertyGetResult GetProperty(const String& name, T& out); template <typename T> ePropertySetResult SetProperty(const String& name, const T& dataToSet); private: std::map<String, NamedBaseProperty*> m_properties; }; //////////////////////////////////////////////////// //------------------------------------------ //INLINES AND TEMPLATE DEFS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //STRUCTORS ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- template <typename T> NamedProperties::NamedProperties(const String& property1, const T& data1) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); } //--------------------------------------------------------------------------------------------------------------------------- template <typename T, typename S> NamedProperties::NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); NamedBaseProperty* newProperty2 = new TypedNamedProperty<S>(data2); m_properties.insert(std::pair<String, NamedBaseProperty*>(property2, newProperty2)); } //--------------------------------------------------------------------------------------------------------------------------- template <typename T, typename S, typename U> NamedProperties::NamedProperties(const String& property1, const T& data1, const String& property2, const S& data2, const String& property3, const U& data3) { NamedBaseProperty* newProperty1 = new TypedNamedProperty<T>(data1); m_properties.insert(std::pair<String, NamedBaseProperty*>(property1, newProperty1)); NamedBaseProperty* newProperty2 = new TypedNamedProperty<S>(data2); m_properties.insert(std::pair<String, NamedBaseProperty*>(property2, newProperty2)); NamedBaseProperty* newProperty3 = new TypedNamedProperty<U>(data3); m_properties.insert(std::pair<String, NamedBaseProperty*>(property3, newProperty3)); } //--------------------------------------------------------------------------------------------------------------------------- NamedProperties::~NamedProperties() { std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.begin(); for (propertyIt; propertyIt != m_properties.end(); ++propertyIt) { delete propertyIt->second; } } ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //GET SET ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //--------------------------------------------------------------------------------------------------------------------------- template <typename T> ePropertyGetResult NamedProperties::GetProperty(const String& name, T& out) { //First do find based on string //If not found return err not found //If found, we return a NamedPropertyBase if (m_properties.empty()) { return PGR_EMPTY; } std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.find(name); if (propertyIt != m_properties.end()) { NamedBaseProperty* baseProperty = propertyIt->second; TypedNamedProperty<T>* typedProperty = dynamic_cast<TypedNamedProperty<T>*>(baseProperty); if (!typedProperty) { return PGR_WRONG_TYPE; } else { out = typedProperty->m_data; return PGR_SUCCESS; } } else { return PGR_NOT_PRESENT; } } //--------------------------------------------------------------------------------------------------------------------------- template <typename T> ePropertySetResult NamedProperties::SetProperty(const String& name, const T& dataToSet) { std::map<String, NamedBaseProperty*>::iterator propertyIt = m_properties.find(name); if (propertyIt != m_properties.end()) { NamedBaseProperty* baseProperty = propertyIt->second; TypedNamedProperty<T>* typedProperty = dynamic_cast<TypedNamedProperty<T>*>(baseProperty); if (!typedProperty) { return PSR_EXISTS_BUT_WRONG_TYPE; } else { typedProperty->m_data = dataToSet; return PSR_SET_EXISTING; } } else { TypedNamedProperty<T>* newProperty = new TypedNamedProperty<T>(dataToSet); m_properties.insert(std::pair<String, NamedBaseProperty*>(name, newProperty)); return PSR_ADDED_NEW_PROPERTY; } }
36.142857
157
0.514746
ntaylorbishop
c4f08e23fd27972c57333bb17b3745a0234d01bb
1,106
cpp
C++
marsyas-vamp/marsyas/src/marsyas/marsystems/FlowToControl.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/FlowToControl.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
marsyas-vamp/marsyas/src/marsyas/marsystems/FlowToControl.cpp
jaouahbi/VampPlugins
27c2248d1c717417fe4d448cdfb4cb882a8a336a
[ "Apache-2.0" ]
null
null
null
#include "FlowToControl.h" namespace Marsyas { FlowToControl::FlowToControl(std::string name): MarSystem("FlowToControl", name) { addControl("mrs_natural/row", 0, m_row_ctl); addControl("mrs_natural/column", 0, m_col_ctl); addControl("mrs_real/value", 0.0, m_value_ctl); } FlowToControl::FlowToControl(const FlowToControl & other): MarSystem(other) { m_row_ctl = getControl("mrs_natural/row"); m_col_ctl = getControl("mrs_natural/column"); m_value_ctl = getControl("mrs_real/value"); } FlowToControl::~FlowToControl() {} MarSystem* FlowToControl::clone() const { return new FlowToControl(*this); } void FlowToControl::myUpdate(MarControlPtr sender) { if (sender() == m_row_ctl() || sender() == m_col_ctl()) return; MarSystem::myUpdate(sender); } void FlowToControl::myProcess(realvec &in, realvec &out) { out = in; mrs_natural row = m_row_ctl->to<mrs_natural>(); mrs_natural col = m_col_ctl->to<mrs_natural>(); if (row >= 0 && row < in.getRows() && col >= 0 && col < in.getCols() ) { m_value_ctl->setValue(in(row,col)); } } } // namespace Marsyas
21.686275
58
0.689873
jaouahbi
c4f1b0a742c5fe46d5cd1b537fabab5d1f254f29
684
hpp
C++
spotify_stream/src/web/model/playlist.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
2
2020-06-07T16:47:20.000Z
2021-03-20T10:41:34.000Z
spotify_stream/src/web/model/playlist.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
null
null
null
spotify_stream/src/web/model/playlist.hpp
Yanick-Salzmann/carpi
29f5e1bf1eb6243e45690f040e4df8e7c228e897
[ "Apache-2.0" ]
null
null
null
#ifndef CARPI_PLAYLIST_HPP #define CARPI_PLAYLIST_HPP #include <string> #include <nlohmann/json.hpp> #include <vector> #include "followers.hpp" #include "image.hpp" namespace carpi::spotify::web::model { struct playlist { bool collaborative; std::string description; std::vector<nlohmann::json> external_urls; followers fllwrs; std::string href; std::string id; std::vector<image> images; std::string name; nlohmann::json owner; bool is_public; std::string snapshot_id; nlohmann::json tracks; std::string type; std::string uri; }; } #endif //CARPI_PLAYLIST_HPP
22.8
50
0.631579
Yanick-Salzmann
c4f1c688bbdf3c982034716a61c40966dbeb6b72
1,626
cpp
C++
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
source/engine/resources/MusicLoader.cpp
AlexKoukoulas2074245K/Genesis
23c114cfe06b65b0b7b5f7807a9ceb4faf8cdf88
[ "MIT" ]
null
null
null
///------------------------------------------------------------------------------------------------ /// MusicLoader.cpp /// Genesis /// /// Created by Alex Koukoulas on 20/11/2019. ///------------------------------------------------------------------------------------------------ #include "MusicLoader.h" #include "MusicResource.h" #include "../common/utils/Logging.h" #include "../common/utils/OSMessageBox.h" #include <fstream> ///------------------------------------------------------------------------------------------------ namespace genesis { ///------------------------------------------------------------------------------------------------ namespace resources { ///------------------------------------------------------------------------------------------------ void MusicLoader::VInitialize() { } ///------------------------------------------------------------------------------------------------ std::unique_ptr<IResource> MusicLoader::VCreateAndLoadResource(const std::string& resourcePath) const { std::ifstream file(resourcePath); if (!file.good()) { ShowMessageBox(MessageBoxType::ERROR, "File could not be found", resourcePath.c_str()); return nullptr; } auto* loadedMusic = Mix_LoadMUS(resourcePath.c_str()); if (!loadedMusic) { ShowMessageBox(MessageBoxType::ERROR, "SDL_mixer could not load music", Mix_GetError()); return nullptr; } return std::unique_ptr<IResource>(new MusicResource(loadedMusic)); } ///------------------------------------------------------------------------------------------------ } }
28.034483
101
0.383764
AlexKoukoulas2074245K
c4f3a4ec94aa0c300e0be050432301af1d9f6203
443
hpp
C++
src/nativecoder.hpp
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
5
2021-02-02T18:44:13.000Z
2022-03-08T16:53:09.000Z
src/nativecoder.hpp
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
6
2021-01-28T04:38:48.000Z
2021-04-05T03:06:33.000Z
src/nativecoder.hpp
jamieleecho/mcbasic
b4c938497487109d2448894ce3fff8476c3e2f4e
[ "MIT" ]
3
2021-01-18T04:13:25.000Z
2021-10-29T23:25:49.000Z
// Copyright (C) 2021 Greg Dionne // Distributed under MIT License #ifndef NATIVECODER_HPP #define NATIVECODER_HPP #include "coder.hpp" // call the implementation via native instructions: // example: // // ldx #INTVAR_X // ldab #2 // jsr ld_ix_pb ; load integer destination with positive byte class NativeCoder : public Coder { public: using Coder::operate; protected: std::string defaultCode(Instruction *inst) override; }; #endif
18.458333
61
0.740406
jamieleecho
c4f3c2c68cb3a2b57c4d77d0d58d6d22cb853d15
3,852
cc
C++
garnet/drivers/video/amlogic-decoder/video_firmware_session.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
garnet/drivers/video/amlogic-decoder/video_firmware_session.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
garnet/drivers/video/amlogic-decoder/video_firmware_session.cc
opensource-assist/fuschia
66646c55b3d0b36aae90a4b6706b87f1a6261935
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "video_firmware_session.h" #include <zircon/assert.h> #include <cinttypes> #include <fbl/algorithm.h> #include "macros.h" constexpr TEEC_UUID kVideoFirmwareUuid = { 0x526fc4fc, 0x7ee6, 0x4a12, {0x96, 0xe3, 0x83, 0xda, 0x95, 0x65, 0xbc, 0xe8}}; // Defined by the TA. enum VideoFirmwareCommandIds { // Firmware for video decode HW. kVideoFirmwareCommandIdLoadVideoFirmware = 0, // Firmware for video encode HW. kVideoFirmwareCommandIdLoadVideoFirmwareEncoder = 1, // For normal builds of the TA, this isn't that useful, but it is a command. We probably won't // need to implement a method for this command. kVideoFirmwareCommandIdDebugVideoFirmware = 2, }; VideoFirmwareSession::VideoFirmwareSession(TEEC_Context* context) : context_(context) { // nothing else to do here } VideoFirmwareSession::~VideoFirmwareSession() { if (session_) { TEEC_CloseSession(&session_.value()); session_.reset(); } } zx_status_t VideoFirmwareSession::Init() { uint32_t return_origin; session_.emplace(); TEEC_Result result; result = TEEC_OpenSession(context_, &session_.value(), &kVideoFirmwareUuid, TEEC_LOGIN_PUBLIC, NULL, NULL, &return_origin); if (result != TEEC_SUCCESS) { session_.reset(); LOG(ERROR, "TEEC_OpenSession failed - Maybe bootloader version is incorrect - " "result: %" PRIx32 " origin: %" PRIu32, result, return_origin); return ZX_ERR_INVALID_ARGS; } return ZX_OK; } zx_status_t VideoFirmwareSession::LoadVideoFirmware(uint8_t* data, uint32_t size) { ZX_DEBUG_ASSERT(session_); constexpr uint32_t kSignatureSize = 256; if (size < kSignatureSize) { LOG(ERROR, "size < kSignatureSize -- size: %u", size); return ZX_ERR_INVALID_ARGS; } TEEC_Operation operation = {}; operation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE, TEEC_NONE); operation.params[0].tmpref.buffer = data + kSignatureSize; operation.params[0].tmpref.size = size - kSignatureSize; operation.params[1].tmpref.buffer = data; operation.params[1].tmpref.size = kSignatureSize; TEEC_Result res = TEEC_InvokeCommand( &session_.value(), kVideoFirmwareCommandIdLoadVideoFirmware, &operation, nullptr); if (res != TEEC_SUCCESS) { LOG(ERROR, "kVideoFirmwareCommandIdLoadVideoFirmware failed - res: 0x%x", res); return ZX_ERR_INTERNAL; } return ZX_OK; } zx_status_t VideoFirmwareSession::LoadVideoFirmwareEncoder(uint8_t* data, uint32_t size) { ZX_DEBUG_ASSERT(session_); constexpr uint32_t kAesIvSize = 16; constexpr uint32_t kSignatureSize = 256; if (size < kAesIvSize + kSignatureSize) { LOG(ERROR, "size < kAesIvSize + kSignatureSize -- size: %u", size); return ZX_ERR_INVALID_ARGS; } TEEC_Operation operation = {}; operation.paramTypes = TEEC_PARAM_TYPES(TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_MEMREF_TEMP_INPUT, TEEC_NONE); operation.params[0].tmpref.buffer = data; operation.params[0].tmpref.size = kAesIvSize; operation.params[1].tmpref.buffer = data + kAesIvSize; operation.params[1].tmpref.size = kSignatureSize; operation.params[2].tmpref.buffer = data + kAesIvSize + kSignatureSize; operation.params[2].tmpref.size = size - kAesIvSize - kSignatureSize; TEEC_Result res = TEEC_InvokeCommand( &session_.value(), kVideoFirmwareCommandIdLoadVideoFirmwareEncoder, &operation, nullptr); if (res != TEEC_SUCCESS) { LOG(ERROR, "kVideoFirmwareCommandIdLoadVideoFirmwareEncoder failed - res: 0x%x", res); return ZX_ERR_INTERNAL; } return ZX_OK; }
34.702703
97
0.720145
opensource-assist
c4f68e726acf92760962a2790d3daec79466c23b
667
hpp
C++
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-12-22T15:31:36.000Z
2017-12-22T15:31:36.000Z
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-12-26T23:18:53.000Z
2017-12-26T23:18:53.000Z
src/Move.hpp
PolyDevTeam/Polybasite
c705d1e0c7286e55c487ddbcd17cdcabfb057b7a
[ "MIT" ]
1
2017-11-20T21:21:01.000Z
2017-11-20T21:21:01.000Z
#ifndef __MOVE_HPP__ #define __MOVE_HPP__ #include <vector> #include <sstream> #include "Serializable.hpp" #include "Miner.hpp" enum DIRECTIONS { STILL = 0, NORTH = 1, EAST = 2, SOUTH = 3, WEST = 4, }; class Move : public Serializable { public: Move(); Move(unsigned minerId, DIRECTIONS directions); virtual ~Move(); virtual std::string serialize(); virtual void deserialize(std::string &serializable); void move(std::vector<Miner*> &miners) const; bool operator<(const Move& move) const; Move& operator=(const Move& move); DIRECTIONS m_directions; unsigned m_minerId; }; #endif /* __MOVE_HPP__ */
18.027027
56
0.661169
PolyDevTeam
c4f75585518af5f6afe024bfc40d2efdd21da4b2
5,870
cpp
C++
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
src/cpp/ports-runtime.cpp
friedolino78/rtosc
5006acfc030465944b45180942e439b3cf4d617a
[ "MIT" ]
null
null
null
#include "../util.h" #include <cstdarg> #include <cstring> #include <cassert> #include <rtosc/pretty-format.h> #include <rtosc/ports.h> #include <rtosc/ports-runtime.h> namespace rtosc { namespace helpers { //! RtData subclass to capture argument values pretty-printed from //! a runtime object class CapturePretty : public RtData { char* buffer; std::size_t buffersize; int cols_used; void reply(const char *) override { assert(false); } /* void replyArray(const char*, const char *args, rtosc_arg_t *vals) { size_t cur_idx = 0; for(const char* ptr = args; *ptr; ++ptr, ++cur_idx) { assert(cur_idx < max_args); arg_vals[cur_idx].type = *ptr; arg_vals[cur_idx].val = vals[cur_idx]; } // TODO: refactor code, also with Capture ? size_t wrt = rtosc_print_arg_vals(arg_vals, cur_idx, buffer, buffersize, NULL, cols_used); assert(wrt); }*/ void reply_va(const char *args, va_list va) { size_t nargs = strlen(args); STACKALLOC(rtosc_arg_val_t, arg_vals, nargs); rtosc_v2argvals(arg_vals, nargs, args, va); size_t wrt = rtosc_print_arg_vals(arg_vals, nargs, buffer, buffersize, NULL, cols_used); assert(wrt); (void)wrt; } void broadcast(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } void reply(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } public: //! Return the argument values, pretty-printed const char* value() const { return buffer; } CapturePretty(char* buffer, std::size_t size, int cols_used) : buffer(buffer), buffersize(size), cols_used(cols_used) {} }; const char* get_value_from_runtime(void* runtime, const Ports& ports, size_t loc_size, char* loc, char* buffer_with_port, std::size_t buffersize, int cols_used) { std::size_t addr_len = strlen(buffer_with_port); // use the port buffer to print the result, but do not overwrite the // port name CapturePretty d(buffer_with_port + addr_len, buffersize - addr_len, cols_used); d.obj = runtime; d.loc_size = loc_size; d.loc = loc; d.matches = 0; // does the message at least fit the arguments? assert(buffersize - addr_len >= 8); // append type memset(buffer_with_port + addr_len, 0, 8); // cover string end and arguments buffer_with_port[addr_len + (4-addr_len%4)] = ','; d.message = buffer_with_port; // buffer_with_port is a message in this call: ports.dispatch(buffer_with_port, d, false); return d.value(); } //! RtData subclass to capture argument values from a runtime object class Capture : public RtData { size_t max_args; rtosc_arg_val_t* arg_vals; int nargs; void chain(const char *path, const char *args, ...) override { nargs = 0; } void chain(const char *msg) override { nargs = 0; } void reply(const char *) override { assert(false); } void replyArray(const char*, const char *args, rtosc_arg_t *vals) override { size_t cur_idx = 0; for(const char* ptr = args; *ptr; ++ptr, ++cur_idx) { assert(cur_idx < max_args); arg_vals[cur_idx].type = *ptr; arg_vals[cur_idx].val = vals[cur_idx]; } nargs = cur_idx; } void reply_va(const char *args, va_list va) { nargs = strlen(args); assert((size_t)nargs <= max_args); rtosc_v2argvals(arg_vals, nargs, args, va); } void broadcast(const char *, const char *args, ...) override { va_list va; va_start(va, args); reply_va(args, va); va_end(va); } void reply(const char *, const char *args, ...) override { va_list va; va_start(va,args); reply_va(args, va); va_end(va); } public: //! Return the number of argument values stored int size() const { return nargs; } Capture(std::size_t max_args, rtosc_arg_val_t* arg_vals) : max_args(max_args), arg_vals(arg_vals), nargs(-1) {} //! Silence compiler warnings std::size_t dont_use_this_function() { return max_args; } }; size_t get_value_from_runtime(void* runtime, const Port& port, size_t loc_size, char* loc, const char* portname_from_base, char* buffer_with_port, std::size_t buffersize, std::size_t max_args, rtosc_arg_val_t* arg_vals) { fast_strcpy(buffer_with_port, portname_from_base, buffersize); std::size_t addr_len = strlen(buffer_with_port); Capture d(max_args, arg_vals); d.obj = runtime; d.loc_size = loc_size; d.loc = loc; d.port = &port; d.matches = 0; assert(*loc); // does the message at least fit the arguments? assert(buffersize - addr_len >= 8); // append type memset(buffer_with_port + addr_len, 0, 8); // cover string end and arguments buffer_with_port[addr_len + (4-addr_len%4)] = ','; // TODO? code duplication // buffer_with_port is a message in this call: d.message = buffer_with_port; port.cb(buffer_with_port, d); assert(d.size() >= 0); return d.size(); } } // namespace helpers } // namespace rtosc
28.086124
80
0.575468
friedolino78
c4f8c132bebfdb3f67ba9b18a4395f13570eac81
387
cpp
C++
C++/base_1/MoveCtor/0426-1/testClassA.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
C++/base_1/MoveCtor/0426-1/testClassA.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
C++/base_1/MoveCtor/0426-1/testClassA.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> #include "classA.h" static void func(classA objA) { std::cout << &objA << std::endl; objA.show(); } static classA func1() { classA obj(1, 2.0); return obj; } void testClassA() { std::cout << std::endl; classA obj(1, 1.1); std::cout << &obj << std::endl; func(obj); std::cout << std::endl; classA obj1(func1()); obj1.show(); std::cout << std::endl; }
13.344828
33
0.599483
liangjisheng
c4facf834dd49dc246cf62833602fc69b4658c77
885
cpp
C++
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
Hacke Rank Problems/Week Of Codes 34/maxgcd.cpp
anand434/-Algorithm-And-DataStructures
e4197db5342def163a8bd22de4187b90bc5ff1d3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; const int N = 1e6 + 6; int cnt[N]; int lmulA[N]; int lmulB[N]; int n; int ar[N]; int br[N]; int main(){ scanf("%d" , &n); for(int i = 1; i <= n; ++i) { scanf("%d" , ar + i); } for(int i = 1; i <= n; ++i) { scanf("%d" , br + i); } for(int i = 1; i <= n; ++i) { ++cnt[arr[i]]; } for(int i = 1; i < N; ++i) { for(int j = i; j < N; j += i) { if(cnt[j]) { lmulA[i] = max(lmulA[i] , j); } } } for(int i = 1; i <= n; ++i) { --cnt[arr[i]]; } for(int i = 1; i <= n; ++i) { ++cnt[brr[i]]; } for(int i = 1; i < N; ++i) { for(int j = i; j < N; j += i) { if(cnt[j]) { lmulB[i] = max(lmulB[i] , j); } } } int mx = 0; for(int i = 1; i < N; ++i) { if(lmulA[i] && lmulB[i]) { mx = i; } } printf("%d\n" , lmulA[mx] + lmulB[mx]); return 0; }
14.75
40
0.39322
anand434
c4fb967d0e8006b751b86b7b5ca5cbbd314615bd
1,143
cc
C++
src/logdoubletest.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
178
2018-05-25T09:51:13.000Z
2022-03-30T13:55:58.000Z
src/logdoubletest.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
249
2018-07-02T07:03:12.000Z
2022-03-30T00:01:01.000Z
src/logdoubletest.cc
sestaton/Augustus
893e0b21fa90bd57fcd0dff2c1e849e88bb02049
[ "Artistic-1.0" ]
95
2018-08-21T21:33:19.000Z
2022-03-30T13:56:00.000Z
/* * logdoubletest.cc * * License: Artistic License, see file LICENSE.TXT or * https://opensource.org/licenses/artistic-license-1.0 * * Description: */ #include "lldouble.hh" #include <iostream> int main() { LogDouble ld, lf=0.9999; LLDouble d, f=0.9999; ld = 0.25; d = 0.25; clock_t anfang, ende; cout << "sizeof(LLDouble) " << sizeof(LLDouble) << endl; cout << "sizeof(LogDouble) " << sizeof(LogDouble) << endl; cout << "sizeof(double) " << sizeof(double) << endl; cout << "sizeof(long double) " << sizeof(long double) << endl; anfang = clock(); for (int i=0; i<100000000; i++) { d = d * f; ld = ld * lf; } ende = clock(); cout << "both time " << ende - anfang << endl; anfang = clock(); for (int i=0; i<100000000; i++) { d = d * f; } ende = clock(); cout << "LLDouble " << d << " time " << ende - anfang << endl; anfang = clock(); for (int i=0; i<100000000; i++) { ld = ld * lf; } ende = clock(); cout << "LogDouble " << ld << " time " << ende - anfang << endl; return 0; } // saves about 1/3 of the time
21.980769
68
0.531059
sestaton
c4ffcd978b48424108f794dde17767d8aa8f8418
6,214
cpp
C++
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
Castlevania/Input.cpp
ctelotuong/CaslteVania
dd4631a4895b0b91d5d8f80ba505dad7c4d81fab
[ "MIT" ]
null
null
null
#include "Input.h" namespace input { Input::Input(core::CGame* game, core::SceneManager* scenes) { this->game = game; this->scenes = scenes; } Input::~Input() { } bool Input::Animation_Standby() { int status; scenes->Get_Simon()->GetStatus(status); if (status == UPDATE && scenes->Get_Simon()->animations[UPDATE]->IsOver(400)==false ) { return true; } //3 frames if (status == ATTACK && scenes->Get_Simon()->animations[ATTACK]->IsOver(300) == false) { return true; } if (status == ATTACK_SIT && scenes->Get_Simon()->animations[ATTACK_SIT]->IsOver(300) == false) { return true; } if (status == ATTACK_STAND && scenes->Get_Simon()->animations[ATTACK_STAND]->IsOver(300) == false) { return true; } if(status==STAIR_UP && scenes->Get_Simon()->animations[STAIR_UP]->IsOver(200)==false) { return true; } if (status == STAIR_DOWN && scenes->Get_Simon()->animations[STAIR_DOWN]->IsOver(200) == false) { return true; } return false; } bool Input::CanProcessKeyboard() { if (Animation_Standby() == true) { return false; } int status; scenes->Get_Simon()->GetStatus(status); //Nếu simon k chạm đất và đang dứng ( đánh trên không trung) hoặc k chạm dất và đang nhảy thì không xử lý if ((scenes->Get_Simon()->isOntheGround == false && status == STAND) || (scenes->Get_Simon()->isOntheGround == false && status == JUMP) || status==DEFLECT || scenes->Get_Simon()->isFalling==true) { return false; } return true; } void Input::KeyState(BYTE* state) { bool isCollideWithStair = false; simon::Simon* simon = scenes->Get_Simon(); vector<core::LPGAMEOBJECT>* listStairs = scenes->Get_List_Stairs(); if(simon->CheckCollisionSimonAndStair(listStairs)==true) { isCollideWithStair = true; } if (CanProcessKeyboard() == false) { return; } if (game->IsKeyDown(DIK_RIGHT)) { if (game->IsKeyDown(DIK_DOWN)) { scenes->Get_Simon()->SetOrientation_x(1); scenes->Get_Simon()->SetStatus(SIT); } else { scenes->Get_Simon()->SetOrientation_x(1); scenes->Get_Simon()->SetStatus(WALK); } } else if (game->IsKeyDown(DIK_LEFT)) { if (game->IsKeyDown(DIK_DOWN)) { scenes->Get_Simon()->SetOrientation_x(-1); scenes->Get_Simon()->SetStatus(SIT); } else { scenes->Get_Simon()->SetOrientation_x(-1); scenes->Get_Simon()->SetStatus(WALK); } } else if (game->IsKeyDown(DIK_DOWN)) { if(isCollideWithStair==true) { if(simon->Get_Is_Move_Down()==false) { return; } int status1; simon->GetStatus(status1); int prevState = status1; simon->SetOrientation_x(-simon->Get_Stair_Direction()); simon->SetStatus(STAIR_DOWN); if(simon->Get_Is_Onstair()==false) { simon->Set_On_Stair(true); simon->PositionCorrection(); } else if(prevState==STAIR_UP)//nếu simon đột nhien chuyển từ trang thai stairup sang stair down { simon->PositionCorrection(prevState); } return; } scenes->Get_Simon()->SetStatus(SIT); } else if (game->IsKeyDown(DIK_UP)) { int prevStave; simon->GetStatus(prevStave); if (isCollideWithStair == true) { if (simon->Get_Is_Move_Up() == false) { simon->SetStatus(STAND); if (prevStave == STAIR_UP) { float sx, sy; simon->GetPosition(sx, sy); int nx; simon->GetOrientation_x(nx); simon->SetPosition(sx + nx * 5.0f, sy - 5.0f); } return; } simon->SetOrientation_x(simon->Get_Stair_Direction()); simon->SetStatus(STAIR_UP); if (simon->Get_Is_Onstair() == false) { simon->Set_On_Stair(true); simon->PositionCorrection(); } else if (prevStave == STAIR_DOWN)//nếu simon dot nhien chuyển từ trang thái stairdown sang stairup { simon->PositionCorrection(prevStave); } } else { simon->SetStatus(STAND); } } else { int status2; simon->GetStatus(status2); if(isCollideWithStair==true &&(status2==STAIR_UP ||status2==STAIR_DOWN)) { simon->StandOnStair(); simon->animations[status2]->Reset(); return; } scenes->Get_Simon()->SetStatus(STAND); } } void Input::OnKeyDown(int KeyCode) { if (KeyCode != DIK_Z) { if (CanProcessKeyboard() == false) return; } DebugOut(L"[INFO] KeyDown: %d\n", KeyCode); int status; scenes->Get_Simon()->GetStatus(status); switch (KeyCode) { case DIK_SPACE: scenes->Get_Simon()->SetStatus(JUMP); break; case DIK_Z: if (!game->IsKeyDown(DIK_UP)) { if(status == JUMP || status == STAND) scenes->Get_Simon()->SetStatus(ATTACK_STAND); else if(status ==WALK) { scenes->Get_Simon()->SetStatus(ATTACK_STAND); scenes->Get_Simon()->vx = 0; } else if (status == SIT) { scenes->Get_Simon()->SetStatus(ATTACK_SIT); } } else if(game->IsKeyDown(DIK_UP)) { bool enable; scenes->Get_Sub_Weapon()->GetEnable(enable); int status; scenes->Get_Simon()->GetStatus(status); if (scenes->Get_Simon()->GetSubweapon() == -1 || scenes->Get_Simon()->GetMana() == 0 || enable==true) // không có vũ khí hoặc enery = 0 return; if (status == STAND || status == JUMP) { simon::Simon* simon = scenes->Get_Simon(); simon::SubWeapon* weapon = scenes->Get_Sub_Weapon(); float sx, sy; // position simon->GetPosition(sx, sy); weapon->SetPosition(sx, sy+10); int ox; simon->GetOrientation_x(ox); // orientation weapon->SetOrientation_x(ox); // state weapon weapon->SetState(simon->GetSubweapon()); weapon->SetEnable(true); int mana; mana= simon->GetMana(); simon->SetMana(mana-1); simon->SetStatus(ATTACK); } } break; case DIK_1: scenes->Get_Simon()->SetSubweapon(DAGGER); break; case DIK_2: scenes->Get_Simon()->SetSubweapon(FLYING_AXE); break; case DIK_3: scenes->Get_Simon()->SetSubweapon(BOOMERANG); break; case DIK_4: scenes->Get_Simon()->SetSubweapon(HOLY_WATER); break; case DIK_Q: scenes->Init(SCENE_1); break; } } void Input::OnKeyUp(int KeyCode) { DebugOut(L"[INFO] KeyUp: %d\n", KeyCode); } }
23.717557
139
0.623592
ctelotuong
f200dca299f9bad9b9e8fb62063a7d872d422d13
10,955
cpp
C++
hackathon/XuanZhao/compare_swc2/compare_swc2_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
1
2021-12-27T19:14:03.000Z
2021-12-27T19:14:03.000Z
hackathon/XuanZhao/compare_swc2/compare_swc2_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
hackathon/XuanZhao/compare_swc2/compare_swc2_plugin.cpp
zzhmark/vaa3d_tools
3ca418add85a59ac7e805d55a600b78330d7e53d
[ "MIT" ]
null
null
null
/* compare_swc2_plugin.cpp * This is a test plugin, you can use it as a demo. * 2020-3-12 : by YourName */ #include "v3d_message.h" #include <vector> #include "compare_swc2_plugin.h" #include "n_class.h" using namespace std; Q_EXPORT_PLUGIN2(compare_swc2, compare_swc); QStringList compare_swc::menulist() const { return QStringList() <<tr("menu1") <<tr("menu2") <<tr("about"); } QStringList compare_swc::funclist() const { return QStringList() <<tr("get_bifurcation_block") <<tr("get_un_bifurcation_block") <<tr("get_single_swc_block") <<tr("pipline") <<tr("help"); } void compare_swc::domenu(const QString &menu_name, V3DPluginCallback2 &callback, QWidget *parent) { if (menu_name == tr("menu1")) { v3d_msg("To be implemented."); } else if (menu_name == tr("menu2")) { v3d_msg("To be implemented."); } else { v3d_msg(tr("This is a test plugin, you can use it as a demo.. " "Developed by YourName, 2020-3-12")); } } bool compare_swc::dofunc(const QString & func_name, const V3DPluginArgList & input, V3DPluginArgList & output, V3DPluginCallback2 & callback, QWidget * parent) { vector<char*> infiles, inparas, outfiles; if(input.size() >= 1) infiles = *((vector<char*> *)input.at(0).p); if(input.size() >= 2) inparas = *((vector<char*> *)input.at(1).p); if(output.size() >= 1) outfiles = *((vector<char*> *)output.at(0).p); if (func_name == tr("get_bifurcation_block")) { QString swc = infiles[0]; QString braindir = infiles[1]; int resolutionX = atoi(inparas[0]); int resolutionY = atoi(inparas[1]); int resolutionZ = atoi(inparas[2]); bool all = (bool)atoi(inparas[3]); QString outdir = outfiles[0]; NeuronTree nt = readSWC_file(swc); SwcTree s; s.initialize(nt); s.get_bifurcation_image(outdir,resolutionX,resolutionY,resolutionZ,all,braindir,callback); } else if (func_name == tr("get_un_bifurcation_block")) { QString swc = infiles[0]; QString braindir = infiles[1]; int resolutionX = atoi(inparas[0]); int resolutionY = atoi(inparas[1]); int resolutionZ = atoi(inparas[2]); bool all = (bool)atoi(inparas[3]); QString outdir = outfiles[0]; NeuronTree nt = readSWC_file(swc); SwcTree s; s.initialize(nt); s.get_un_bifurcation_image(outdir,resolutionX,resolutionY,resolutionZ,all,braindir,callback); } else if (func_name == tr("get_single_swc_block")) { QString swc = infiles[0]; QString braindir = infiles[1]; NeuronTree nt = readSWC_file(swc); SwcTree s; s.initialize(nt); vector<int> resolutions ={30,40,50}; vector<QString> outdirs = {"D:\\ZX\\data\\bifurcation_block_30x30x30", "D:\\ZX\\data\\un_bifurcation_block_30x30x30", "D:\\ZX\\data\\bifurcation_block_40x40x40", "D:\\ZX\\data\\un_bifurcation_block_40x40x40", "D:\\ZX\\data\\bifurcation_block_50x50x50", "D:\\ZX\\data\\un_bifurcation_block_50x50x50"}; for(int i=0; i<resolutions.size(); ++i) { // qDebug()<<"resolution: "<<resolutions[i]<<" dir: "<<outdirs[i*2]<<" "<<outdirs[i*2+1]; s.get_bifurcation_image(outdirs[i*2],resolutions[i],resolutions[i],resolutions[i],true,braindir,callback); s.get_un_bifurcation_image(outdirs[i*2+1],resolutions[i],resolutions[i],resolutions[i],false,braindir,callback); } } else if (func_name == tr("pipline")) { vector<QString> swclist = { "D:\\ZX\\release_20191231\\17545_00023.ano.swc'", "D:\\ZX\\release_20191231\\17545_00024.ano.swc'", "D:\\ZX\\release_20191231\\17545_00025.ano.swc'", "D:\\ZX\\release_20191231\\17545_00026.ano.swc'", "D:\\ZX\\release_20191231\\17545_00027.ano.swc'", "D:\\ZX\\release_20191231\\17545_00028.ano.swc'", "D:\\ZX\\release_20191231\\17545_00029.ano.swc'", "D:\\ZX\\release_20191231\\17545_00030.ano.swc'", "D:\\ZX\\release_20191231\\17545_00040.ano.swc'", "D:\\ZX\\release_20191231\\17545_00041.ano.swc'", "D:\\ZX\\release_20191231\\17545_00044.ano.swc'", "D:\\ZX\\release_20191231\\17545_00045.ano.swc'", "D:\\ZX\\release_20191231\\17545_00046.ano.swc'", "D:\\ZX\\release_20191231\\17545_00047.ano.swc'", "D:\\ZX\\release_20191231\\17545_00048.ano.swc'", "D:\\ZX\\release_20191231\\17545_00050.ano.swc'", "D:\\ZX\\release_20191231\\17545_00052.ano.swc'", "D:\\ZX\\release_20191231\\17545_00053.ano.swc'", "D:\\ZX\\release_20191231\\17545_00054.ano.swc'", "D:\\ZX\\release_20191231\\17545_00055.ano.swc'", "D:\\ZX\\release_20191231\\17545_00056.ano.swc'", "D:\\ZX\\release_20191231\\17545_00058.ano.swc'", "D:\\ZX\\release_20191231\\17545_00059.ano.swc'", "D:\\ZX\\release_20191231\\17545_00060.ano.swc'", "D:\\ZX\\release_20191231\\17545_00063.ano.swc'", "D:\\ZX\\release_20191231\\17545_00064.ano.swc'", "D:\\ZX\\release_20191231\\17545_00065.ano.swc'", "D:\\ZX\\release_20191231\\17545_00066.ano.swc'", "D:\\ZX\\release_20191231\\17545_00067.ano.swc'", "D:\\ZX\\release_20191231\\17545_00068.ano.swc'", "D:\\ZX\\release_20191231\\17545_00071.ano.swc'", "D:\\ZX\\release_20191231\\17545_00073.ano.swc'", "D:\\ZX\\release_20191231\\17545_00074.ano.swc'", "D:\\ZX\\release_20191231\\17545_00075.ano.swc'", "D:\\ZX\\release_20191231\\17545_00078.ano.swc'", "D:\\ZX\\release_20191231\\17545_00081.ano.swc'", "D:\\ZX\\release_20191231\\17545_00082.ano.swc'", "D:\\ZX\\release_20191231\\17545_00088.ano.swc'", "D:\\ZX\\release_20191231\\17545_00089.ano.swc'", "D:\\ZX\\release_20191231\\17545_00090.ano.swc'", "D:\\ZX\\release_20191231\\17545_00091.ano.swc'", "D:\\ZX\\release_20191231\\17545_00092.ano.swc'", "D:\\ZX\\release_20191231\\17545_00093.ano.swc'", "D:\\ZX\\release_20191231\\17545_00094.ano.swc'", "D:\\ZX\\release_20191231\\17545_00095.ano.swc'", "D:\\ZX\\release_20191231\\17545_00110.ano.swc'", "D:\\ZX\\release_20191231\\17545_00111.ano.swc'", "D:\\ZX\\release_20191231\\17545_00113.ano.swc'", "D:\\ZX\\release_20191231\\17545_00115.ano.swc'", "D:\\ZX\\release_20191231\\17545_00116.ano.swc'", "D:\\ZX\\release_20191231\\17545_00118.ano.swc'", "D:\\ZX\\release_20191231\\17545_00119.ano.swc'", "D:\\ZX\\release_20191231\\17545_00120.ano.swc'", "D:\\ZX\\release_20191231\\17545_00121.ano.swc'", "D:\\ZX\\release_20191231\\17545_00122.ano.swc'", "D:\\ZX\\release_20191231\\17545_00124.ano.swc'", "D:\\ZX\\release_20191231\\17545_00125.ano.swc'", "D:\\ZX\\release_20191231\\17545_00126.ano.swc'", "D:\\ZX\\release_20191231\\17545_00129.ano.swc'", "D:\\ZX\\release_20191231\\17545_00130.ano.swc'", "D:\\ZX\\release_20191231\\17545_00131.ano.swc'", "D:\\ZX\\release_20191231\\17545_00132.ano.swc'", "D:\\ZX\\release_20191231\\17545_00136.ano.swc'", "D:\\ZX\\release_20191231\\17545_00138.ano.swc'", "D:\\ZX\\release_20191231\\17545_00140.ano.swc'", "D:\\ZX\\release_20191231\\17545_00142.ano.swc'", "D:\\ZX\\release_20191231\\17545_00143.ano.swc'", "D:\\ZX\\release_20191231\\17545_00144.ano.swc'", "D:\\ZX\\release_20191231\\17545_00145.ano.swc'", "D:\\ZX\\release_20191231\\17545_00146.ano.swc'", "D:\\ZX\\release_20191231\\17545_00147.ano.swc'", "D:\\ZX\\release_20191231\\17545_00149.ano.swc'", "D:\\ZX\\release_20191231\\17545_00150.ano.swc'", "D:\\ZX\\release_20191231\\17545_00154.ano.swc'", "D:\\ZX\\release_20191231\\17545_00155.ano.swc'", "D:\\ZX\\release_20191231\\17545_00158.ano.swc'", "D:\\ZX\\release_20191231\\17545_00159.ano.swc'", "D:\\ZX\\release_20191231\\17545_00162.ano.swc'", "D:\\ZX\\release_20191231\\17545_00163.ano.swc'", "D:\\ZX\\release_20191231\\17545_00164.ano.swc'", "D:\\ZX\\release_20191231\\17545_00165.ano.swc'", "D:\\ZX\\release_20191231\\17545_00166.ano.swc'", "D:\\ZX\\release_20191231\\17545_00168.ano.swc'", "D:\\ZX\\release_20191231\\17545_00169.ano.swc'", "D:\\ZX\\release_20191231\\17545_00170.ano.swc'", "D:\\ZX\\release_20191231\\17545_00172.ano.swc'", "D:\\ZX\\release_20191231\\17545_00173.ano.swc'", "D:\\ZX\\release_20191231\\17545_00174.ano.swc'", "D:\\ZX\\release_20191231\\17545_00175.ano.swc'", "D:\\ZX\\release_20191231\\17545_00177.ano.swc'", "D:\\ZX\\release_20191231\\17545_00179.ano.swc'", "D:\\ZX\\release_20191231\\17545_00180.ano.swc'" }; for(int i=0; i<swclist.size(); ++i){ QString swc = swclist[i].left(swclist[i].size() - 1); // qDebug()<<swclist[i]; QString braindir = "E:\\mouse17545_teraconvert\\RES(54600x35989x10750)"; NeuronTree nt = readSWC_file(swc); SwcTree s; s.initialize(nt); vector<int> resolutions ={30,40,50}; vector<QString> outdirs = {"D:\\ZX\\data\\bifurcation_block_30x30x30", "D:\\ZX\\data\\un_bifurcation_block_30x30x30", "D:\\ZX\\data\\bifurcation_block_40x40x40", "D:\\ZX\\data\\un_bifurcation_block_40x40x40", "D:\\ZX\\data\\bifurcation_block_50x50x50", "D:\\ZX\\data\\un_bifurcation_block_50x50x50"}; for(int i=0; i<resolutions.size(); ++i) { // qDebug()<<"resolution: "<<resolutions[i]<<" dir: "<<outdirs[i*2]<<" "<<outdirs[i*2+1]; s.get_bifurcation_image(outdirs[i*2],resolutions[i],resolutions[i],resolutions[i],true,braindir,callback); s.get_un_bifurcation_image(outdirs[i*2+1],resolutions[i],resolutions[i],resolutions[i],false,braindir,callback); } } } else if (func_name == tr("help")) { v3d_msg("To be implemented."); } else return false; return true; }
46.223629
160
0.578183
zzhmark
f2047d442b81465a2549c37263c825451b64f114
6,972
cpp
C++
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
lesson04/src/helper_functions.cpp
just-4-name/CPPExercises2021
4df4b93b470bde7f05de91e5e1ed76e63daf49d8
[ "MIT" ]
null
null
null
#include "helper_functions.h" #include <cstdlib> #include <ctime> #include <iostream> #include <libutils/rasserts.h> using namespace std; using namespace cv; cv::Mat makeAllBlackPixelsBlue(cv::Mat image) { // TODO реализуйте функцию которая каждый черный пиксель картинки сделает синим int height = image.rows, width = image.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = image.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; if (r < 30 && g < 30 && b < 30) { b = 255; r = g = 0; } image.at<Vec3b>(i, j) = Vec3b(b, g, r); } } // ниже приведен пример как узнать цвет отдельного пикселя - состоящий из тройки чисел BGR (Blue Green Red) // чем больше значение одного из трех чисел - тем насыщеннее его оттенок // всего их диапазон значений - от 0 до 255 включительно // т.е. один байт, поэтому мы используем ниже тип unsigned char - целое однобайтовое неотрицательное число // cv::Vec3b color = image.at<cv::Vec3b>(13, 5); // взяли и узнали что за цвет в пикселе в 14-ом ряду (т.к. индексация с нуля) и 6-ой колонке // unsigned char blue = color[0]; // если это число равно 255 - в пикселе много синего, если равно 0 - в пикселе нет синего // unsigned char green = color[1]; // unsigned char red = color[2]; // // // как получить белый цвет? как получить черный цвет? как получить желтый цвет? // // поэкспериментируйте! например можете всю картинку заполнить каким-то одним цветом // // // пример как заменить цвет по тем же координатам // red = 255; // // запустите эту версию функции и посмотрите на получившуюся картинку - lesson03/resultsData/01_blue_unicorn.jpg // // какой пиксель изменился? почему он не чисто красный? // image.at<cv::Vec3b>(13, 5) = cv::Vec3b(blue, green, red); return image; } cv::Mat invertImageColors(cv::Mat image) { // TODO реализуйте функцию которая каждый цвет картинки инвертирует: // т.е. пусть ночь станет днем, а сумрак рассеется // иначе говоря замените каждое значение яркости x на (255-x) (т.к находится в диапазоне от 0 до 255) int height = image.rows, width = image.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = image.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; b = 255 - b; g = 255 - g; r = 255 - r; image.at<Vec3b>(i, j) = Vec3b(b, g, r); } } return image; } cv::Mat addBackgroundInsteadOfBlackPixels(cv::Mat object, cv::Mat background) { // TODO реализуйте функцию которая все черные пиксели картинки-объекта заменяет на пиксели с картинки-фона // т.е. что-то вроде накладного фона получится // гарантируется что размеры картинок совпадают - проверьте это через rassert, вот например сверка ширины: rassert(object.cols == background.cols, 341241251251351); rassert(object.rows == background.rows, 341241251251351); int height = object.rows, width = object.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = object.at<Vec3b>(i, j); Vec3b color1 = background.at<Vec3b>(i,j); unsigned char b = color[0], g = color[1], r = color[2]; if(b<30 && r<30 && g<30){ object.at<Vec3b>(i,j) = color1; } } } return object; } cv::Mat addBackgroundInsteadOfBlackPixelsLargeBackground(cv::Mat object, cv::Mat largeBackground) { // теперь вам гарантируется что largeBackground гораздо больше - добавьте проверок этого инварианта (rassert-ов) // TODO реализуйте функцию так, чтобы нарисовался объект ровно по центру на данном фоне, при этом черные пиксели объекта не должны быть нарисованы int height = object.rows, width = object.cols; int height1 = largeBackground.rows, width1 = largeBackground.cols; for(int i = 0; i<height; ++i) { for (int j = 0; j < width; ++j) { Vec3b color = object.at<Vec3b>(i, j); unsigned char b = color[0], g = color[1], r = color[2]; if(!(b<30 && r<30 && g<30)){ largeBackground.at<Vec3b>(i+(height1-height)/2, j + (width1-width)/2) = color; } } } return largeBackground; } Mat drawNUnicorns(Mat object, Mat background, int n){ srand((unsigned)time(0)); for(int i=0;i<n;++i){ int x = (rand() % (background.cols - object.cols-5)); int y = (rand() % (background.rows - object.rows-5)); for(int j = 0;j<object.rows;++j){ for(int k = 0; k<object.cols;++k){ Vec3b color = object.at<Vec3b>(j, k); unsigned char b = color[0], g = color[1], r = color[2]; if(!(b<30 && r<30 && g<30)){ rassert(y+j>=0 && y+j<=background.rows,2131441) background.at<Vec3b>(y + j, x + k) = color; } } } } return background; } Mat makeBlackPixelsRand(Mat img){ srand((unsigned)time(0)); for(int i = 0;i<img.rows;++i){ for(int j = 0;j<img.cols;++j){ Vec3b color = img.at<Vec3b>(i,j); unsigned char b = color[0], g = color[1], r = color[2]; if(b<30 && r<30 && g<30){ r = rand()%256; g = rand()%256; b = rand()%256; img.at<Vec3b>(i,j) = Vec3b(b,g,r); } } }return img; } vector<vector<int>> dilate(vector<vector<int>> mask, int r){ //0 - обьект for(int i=0;i<mask.size();++i){ for(int j = 0;j<mask[i].size();++j){ for(int dy = -r;dy<=r;++dy){ for(int dx = -r;dx<=r;++dx){ int y = i + dy; int x = j + dx; if(y<0 || y>=mask.size()) continue; if(x<0 || x>=mask[i].size()) continue; if(mask[y][x] == 0){ mask[i][j] = 0; } } } } }return mask; } vector<vector<int>> erode(vector<vector<int>> mask, int r){ //0 - обьект for(int i=0;i<mask.size();++i){ for(int j = 0;j<mask[i].size();++j){ for(int dy = -r;dy<=r;++dy){ for(int dx = -r;dx<=r;++dx){ int y = i + dy; int x = j + dx; if(y<0 || y>=mask.size()) continue; if(x<0 || x>=mask[i].size()) continue; if(mask[y][x] == 1){ mask[i][j] = 1; } } } } }return mask; } bool equeal(Vec3b c1, Vec3b c2){ if(abs(c1[0] - c2[0])<20 && abs(c1[1] - c2[1])<20 && abs(c1[2] - c2[2])<20){ return 1; }else return 0; }
35.753846
150
0.535714
just-4-name
f20490673fc389cdb393578973c2b8d7488dbdcd
217
cpp
C++
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
null
null
null
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
null
null
null
Game_Girls_AutoChess_2019_06_04/Lib/UIObject.cpp
AhriHaran/Unity
90a84d8cabd5ef890f3fb7d9624437b1ef8157a9
[ "Unlicense" ]
2
2019-09-04T06:04:23.000Z
2019-09-16T07:44:16.000Z
#include "UIObject.h" namespace JEngine { UIObject::UIObject() { } UIObject::~UIObject() { } void UIObject::SetPos(int left, int top, int right, int bottom) { m_rcPos.Set(left, top, right, bottom); } }
11.421053
64
0.645161
AhriHaran
f2065ef3ba4d32ba05f9a7114fb2acfac53a9ccf
4,106
inl
C++
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
trunk/libs/angsys/include/ang/maths/implement/double4x4_simd.inl
ChuyX3/angsys
89b2eaee866bcfd11e66efda49b38acc7468c780
[ "Apache-2.0" ]
null
null
null
#ifndef __COFFE_GRAPH_MATHS_H__ #error ... #elif !defined __COFFE_GRAPH_MATHS_FLOAT4X4_HPP__ #define __COFFE_GRAPH_MATHS_FLOAT4X4_HPP__ inline coffe::math::float4x4::float4x4() { memset(_mat, 0, sizeof(_mat)); } inline coffe::math::float4x4::float4x4(float_t val) { _mat[0] = _mm_set1_ps(val); _mat[1] = _mm_set1_ps(val); _mat[2] = _mm_set1_ps(val); _mat[3] = _mm_set1_ps(val); } inline coffe::math::float4x4::float4x4(float4_t const& v0, float4_t const& v1, float4_t const& v2, float4_t const& v3) { _mat[0] = v0._vector; _mat[1] = v1._vector; _mat[2] = v2._vector; _mat[3] = v3._vector; } inline coffe::math::float4x4::float4x4(const float4x4& mat) { _mat[0] = mat._mat[0]; _mat[1] = mat._mat[1]; _mat[2] = mat._mat[2]; _mat[3] = mat._mat[3]; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator = (const float4x4_t& mat) { _mat[0] = mat._mat[0]; _mat[1] = mat._mat[1]; _mat[2] = mat._mat[2]; _mat[3] = mat._mat[3]; return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator += (const float4x4_t& mat) { _mat[0] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[1] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[2] = _mm_add_ps(_mat[0], mat._mat[0]); _mat[3] = _mm_add_ps(_mat[0], mat._mat[0]); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator -= (const float4x4_t& mat) { _mat[0] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[1] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[2] = _mm_sub_ps(_mat[0], mat._mat[0]); _mat[3] = _mm_sub_ps(_mat[0], mat._mat[0]); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator *= (float_t k) { _mat[0] = _mm_mul_ps(_mat[0], _mm_set1_ps(k)); _mat[1] = _mm_mul_ps(_mat[1], _mm_set1_ps(k)); _mat[2] = _mm_mul_ps(_mat[2], _mm_set1_ps(k)); _mat[3] = _mm_mul_ps(_mat[3], _mm_set1_ps(k)); return*this; } inline coffe::math::float4x4_t& coffe::math::float4x4::operator /= (float_t k) { _mat[0] = _mm_div_ps(_mat[0], _mm_set1_ps(k)); _mat[1] = _mm_div_ps(_mat[1], _mm_set1_ps(k)); _mat[2] = _mm_div_ps(_mat[2], _mm_set1_ps(k)); _mat[3] = _mm_div_ps(_mat[3], _mm_set1_ps(k)); return*this; } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<0>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[0]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<1>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[1]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<2>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[2]); } template<> inline coffe::math::float4_t& coffe::math::float4x4::get<3>() { return*reinterpret_cast<coffe::math::float4_t*>(&_mat[3]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<0>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[0]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<1>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[1]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<2>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[2]); } template<> inline coffe::math::float4_t const& coffe::math::float4x4::get<3>()const { return*reinterpret_cast<coffe::math::float4_t const*>(&_mat[3]); } inline coffe::math::float4_t& coffe::math::float4x4::operator [](coffe::int_t idx) { return *reinterpret_cast<coffe::math::float4_t*>(&_mat[idx]); } inline coffe::math::float4_t const& coffe::math::float4x4::operator [](coffe::int_t idx)const { return *reinterpret_cast<coffe::math::float4_t const*>(&_mat[idx]); } inline coffe::bool_t coffe::math::float4x4::operator == (const coffe::math::float4x4_t& mat)const { return get<0>() == mat.get<0>() && get<1>() == mat.get<1>() && get<2>() == mat.get<2>() && get<3>() == mat.get<3>(); } inline coffe::bool_t coffe::math::float4x4::operator != (const coffe::math::float4x4_t& mat)const { return get<0>() != mat.get<0>() || get<1>() != mat.get<1>() || get<2>() != mat.get<2>() || get<3>() != mat.get<3>(); } #endif//__COFFE_GRAPH_MATHS_FLOAT4X4_HPP__
38.735849
152
0.677058
ChuyX3
f206b5424336bef9ddea354fd51410339489df3e
4,569
hpp
C++
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2021-07-30T16:54:24.000Z
2021-09-08T15:48:17.000Z
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
null
null
null
src/tests-core/tests/packed/sequence/fse/pseq_test_base.hpp
victor-smirnov/memoria
c36a957c63532176b042b411b1646c536e71a658
[ "BSL-1.0", "Apache-2.0", "OLDAP-2.8", "BSD-3-Clause" ]
2
2020-03-14T15:15:25.000Z
2020-06-15T11:26:56.000Z
// Copyright 2013 Victor Smirnov // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #include <memoria/tests/tests.hpp> #include <memoria/tests/assertions.hpp> #include <memoria/core/packed/sseq/packed_fse_searchable_seq.hpp> #include <memoria/core/packed/tools/packed_struct_ptrs.hpp> #include <memoria/reactor/reactor.hpp> #include <memory> namespace memoria { namespace tests { template < int32_t Bits, typename IndexType, template <typename> class ReindexFnType, template <typename> class SelectFnType, template <typename> class RankFnType, template <typename> class ToolsFnType > class PackedSearchableSequenceTestBase: public TestState { using Base = TestState; typedef PackedSearchableSequenceTestBase< Bits, IndexType, ReindexFnType, SelectFnType, RankFnType, ToolsFnType > MyType; typedef PkdFSSeqTypes< Bits, 1024, IndexType, ReindexFnType, SelectFnType, RankFnType, ToolsFnType > Types; protected: using Seq = PkdFSSeq<Types>; using SeqPtr = PkdStructSPtr<Seq>; typedef typename Seq::Value Value; static const int32_t Blocks = Seq::Indexes; static const int32_t Symbols = 1 << Bits; static const int32_t VPB = Seq::ValuesPerBranch; int32_t iterations_ = 100; int64_t size_{32768}; public: MMA_STATE_FILEDS(size_, iterations_); SeqPtr createEmptySequence(int32_t block_size = 1024*1024) { return MakeSharedPackedStructByBlock<Seq>(block_size); } std::vector<int32_t> populate(SeqPtr& seq, int32_t size, Value value = 0) { std::vector<int32_t> symbols(size); for (auto& s: symbols) s = value; seq->clear().get_or_throw(); seq->insert(0, size, [&](){ return value; }).get_or_throw(); assertEqual(seq, symbols); assertIndexCorrect(MA_SRC, seq); return symbols; } std::vector<int32_t> populateRandom(SeqPtr& seq, int32_t size) { seq->clear().get_or_throw(); return fillRandom(seq, size); } std::vector<int32_t> fillRandom(SeqPtr& seq, int32_t size) { std::vector<int32_t> symbols; seq->insert(0, size, [&]() { int32_t sym = getRandom(Blocks); symbols.push_back(sym); return sym; }).get_or_throw(); seq->check().get_or_throw(); this->assertIndexCorrect(MA_SRC, seq); this->assertEqual(seq, symbols); return symbols; } int32_t rank(const SeqPtr& seq, int32_t start, int32_t end, int32_t symbol) { int32_t rank = 0; for (int32_t c = start; c < end; c++) { rank += seq->test(c, symbol); } return rank; } void assertIndexCorrect(const char* src, const SeqPtr& seq) { try { seq->check().get_or_throw(); } catch (Exception& e) { out() << "Sequence structure check failed" << std::endl; seq->dump(out()); throw e; } } void assertEmpty(const SeqPtr& seq) { assert_equals(seq->size(), 0); assert_equals(false, seq->has_index()); } void assertEqual(const SeqPtr& seq, const std::vector<int32_t>& symbols) { assert_equals(seq->size(), (int32_t)symbols.size()); try { for (int32_t c = 0; c < seq->size(); c++) { assert_equals((uint64_t)seq->symbol(c), (uint64_t)symbols[c], "Index: {}", c); } } catch(...) { seq->dump(this->out()); throw; } } }; }}
25.104396
94
0.562267
victor-smirnov
f20744bda621c2a5cbdec5b250d84e618ff76082
1,533
hh
C++
TFM/click-2.0.1/elements/grid/gridgatewayinfo.hh
wangyang2013/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
3
2018-04-14T14:43:31.000Z
2019-12-06T13:09:58.000Z
TFM/click-2.0.1/elements/grid/gridgatewayinfo.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
TFM/click-2.0.1/elements/grid/gridgatewayinfo.hh
nfvproject/TFM
cabca56229a7e4dafc76da8d631980fc453c9493
[ "BSD-3-Clause" ]
null
null
null
#ifndef GRIDGATEWAYINFO_HH #define GRIDGATEWAYINFO_HH #include <click/element.hh> #include "grid.hh" #include "gridgenericrt.hh" CLICK_DECLS /* * =c * GridGatewayInfo(ROUTETABLE, IS_GATEWAY) * =s Grid * Manage grid node gateway info. * * =d * * GridGatewayInfo performs two functions [probably indicating a bad * design!]: first, it determines whether this particular node is a * gateway (IS_GATEWAY argument); second, it sets the destinination IP * address annotation of incoming packets to be the best current * gateway known by the node's routing table (GridGenericRouteTable * argument). * * GridGenericRouteTable is this node's route table. * * IS_GATEWAY is a boolean representing whether or not this node * should advertise itself as a gateway. * * * =h is_gateway read/write * Returns or sets boolean value of whether or not this node is a * gateway. * * =a DSDVRouteTable, SetIPAddress */ class GridGatewayInfo : public Element { public: GridGatewayInfo(); ~GridGatewayInfo(); const char *class_name() const { return "GridGatewayInfo"; } const char *port_count() const { return PORTS_1_1; } const char *processing() const { return AGNOSTIC; } int configure(Vector<String> &, ErrorHandler *); bool can_live_reconfigure() const { return true; } void add_handlers(); bool is_gateway (); static String print_best_gateway(Element *f, void *); Packet *simple_action(Packet *); class GridGenericRouteTable *_rt; protected: bool _is_gateway; }; CLICK_ENDDECLS #endif
23.953125
70
0.733203
wangyang2013
f20745a76d6d68fcb0bf77b7addba4c2e9d6c8a7
6,427
hpp
C++
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
1
2020-12-17T07:25:03.000Z
2020-12-17T07:25:03.000Z
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
null
null
null
headers/rpnx/hsalsa.hpp
rpnx-net/rpnx-crypto
795487338f4d569d56886ab2b685bcd38a433142
[ "MIT" ]
null
null
null
// // Created by rnicholl on 12/16/20. // #ifndef RPNX_DJB_CRYPTO_HSALSA_HPP #define RPNX_DJB_CRYPTO_HSALSA_HPP #include <utility> #include <cinttypes> #include <tuple> #include <cstddef> #include "rpnx/crypto_common.hpp" #include <stdint.h> #include <stdlib.h> namespace rpnx::c_djb_crypto { template <std::size_t Rounds> void core_hsalsa(std::byte *out, const std::byte *in, const std::byte *k, const std::byte *c) { static_assert(Rounds % 2 == 0); std::uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; if (c == nullptr) { x0 = std::uint32_t(0x61707865u); x5 = std::uint32_t(0x3320646eu); x10 = std::uint32_t(0x79622d32u); x15 = std::uint32_t(0x6b206574u); } else { x0 = load_little_endian32(c + 0); x5 = load_little_endian32(c + 4); x10 = load_little_endian32(c + 8); x15 = load_little_endian32(c + 12); } x1 = load_little_endian32(k + 0); x2 = load_little_endian32(k + 4); x3 = load_little_endian32(k + 8); x4 = load_little_endian32(k + 12); x11 = load_little_endian32(k + 16); x12 = load_little_endian32(k + 20); x13 = load_little_endian32(k + 24); x14 = load_little_endian32(k + 28); x6 = load_little_endian32(in + 0); x7 = load_little_endian32(in + 4); x8 = load_little_endian32(in + 8); x9 = load_little_endian32(in + 12); for (int i = Rounds; i > 0; i -= 2) { x4 ^= rotate_up_32(x0 + x12, 7); x8 ^= rotate_up_32(x4 + x0, 9); x12 ^= rotate_up_32(x8 + x4, 13); x0 ^= rotate_up_32(x12 + x8, 18); x9 ^= rotate_up_32(x5 + x1, 7); x13 ^= rotate_up_32(x9 + x5, 9); x1 ^= rotate_up_32(x13 + x9, 13); x5 ^= rotate_up_32(x1 + x13, 18); x14 ^= rotate_up_32(x10 + x6, 7); x2 ^= rotate_up_32(x14 + x10, 9); x6 ^= rotate_up_32(x2 + x14, 13); x10 ^= rotate_up_32(x6 + x2, 18); x3 ^= rotate_up_32(x15 + x11, 7); x7 ^= rotate_up_32(x3 + x15, 9); x11 ^= rotate_up_32(x7 + x3, 13); x15 ^= rotate_up_32(x11 + x7, 18); x1 ^= rotate_up_32(x0 + x3, 7); x2 ^= rotate_up_32(x1 + x0, 9); x3 ^= rotate_up_32(x2 + x1, 13); x0 ^= rotate_up_32(x3 + x2, 18); x6 ^= rotate_up_32(x5 + x4, 7); x7 ^= rotate_up_32(x6 + x5, 9); x4 ^= rotate_up_32(x7 + x6, 13); x5 ^= rotate_up_32(x4 + x7, 18); x11 ^= rotate_up_32(x10 + x9, 7); x8 ^= rotate_up_32(x11 + x10, 9); x9 ^= rotate_up_32(x8 + x11, 13); x10 ^= rotate_up_32(x9 + x8, 18); x12 ^= rotate_up_32(x15 + x14, 7); x13 ^= rotate_up_32(x12 + x15, 9); x14 ^= rotate_up_32(x13 + x12, 13); x15 ^= rotate_up_32(x14 + x13, 18); } store_little_endian32(out + 0, x0); store_little_endian32(out + 4, x5); store_little_endian32(out + 8, x10); store_little_endian32(out + 12, x15); store_little_endian32(out + 16, x6); store_little_endian32(out + 20, x7); store_little_endian32(out + 24, x8); store_little_endian32(out + 28, x9); } } namespace rpnx::crypto { template <std::size_t Rounds, typename OutIt, typename InputIt, typename KeyIt > void core_hsalsa(OutIt out, InputIt in, KeyIt k) { static_assert(Rounds % 2 == 0); std::uint32_t x0, x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11, x12, x13, x14, x15; x0 = std::uint32_t(0x61707865u); x5 = std::uint32_t(0x3320646eu); x10 = std::uint32_t(0x79622d32u); x15 = std::uint32_t(0x6b206574u); x1 = load_little_endian32(k + 0); x2 = load_little_endian32(k + 4); x3 = load_little_endian32(k + 8); x4 = load_little_endian32(k + 12); x11 = load_little_endian32(k + 16); x12 = load_little_endian32(k + 20); x13 = load_little_endian32(k + 24); x14 = load_little_endian32(k + 28); x6 = load_little_endian32(in + 0); x7 = load_little_endian32(in + 4); x8 = load_little_endian32(in + 8); x9 = load_little_endian32(in + 12); for (int i = Rounds; i > 0; i -= 2) { x4 ^= rotate_up_32(x0 + x12, 7); x8 ^= rotate_up_32(x4 + x0, 9); x12 ^= rotate_up_32(x8 + x4, 13); x0 ^= rotate_up_32(x12 + x8, 18); x9 ^= rotate_up_32(x5 + x1, 7); x13 ^= rotate_up_32(x9 + x5, 9); x1 ^= rotate_up_32(x13 + x9, 13); x5 ^= rotate_up_32(x1 + x13, 18); x14 ^= rotate_up_32(x10 + x6, 7); x2 ^= rotate_up_32(x14 + x10, 9); x6 ^= rotate_up_32(x2 + x14, 13); x10 ^= rotate_up_32(x6 + x2, 18); x3 ^= rotate_up_32(x15 + x11, 7); x7 ^= rotate_up_32(x3 + x15, 9); x11 ^= rotate_up_32(x7 + x3, 13); x15 ^= rotate_up_32(x11 + x7, 18); x1 ^= rotate_up_32(x0 + x3, 7); x2 ^= rotate_up_32(x1 + x0, 9); x3 ^= rotate_up_32(x2 + x1, 13); x0 ^= rotate_up_32(x3 + x2, 18); x6 ^= rotate_up_32(x5 + x4, 7); x7 ^= rotate_up_32(x6 + x5, 9); x4 ^= rotate_up_32(x7 + x6, 13); x5 ^= rotate_up_32(x4 + x7, 18); x11 ^= rotate_up_32(x10 + x9, 7); x8 ^= rotate_up_32(x11 + x10, 9); x9 ^= rotate_up_32(x8 + x11, 13); x10 ^= rotate_up_32(x9 + x8, 18); x12 ^= rotate_up_32(x15 + x14, 7); x13 ^= rotate_up_32(x12 + x15, 9); x14 ^= rotate_up_32(x13 + x12, 13); x15 ^= rotate_up_32(x14 + x13, 18); } store_little_endian32(out + 0, x0); store_little_endian32(out + 4, x5); store_little_endian32(out + 8, x10); store_little_endian32(out + 12, x15); store_little_endian32(out + 16, x6); store_little_endian32(out + 20, x7); store_little_endian32(out + 24, x8); store_little_endian32(out + 28, x9); } } #endif
36.725714
84
0.512214
rpnx-net
f2075a00fc92920bb9bc55067dff1d81e2b85834
17,352
cpp
C++
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
3
2021-12-10T03:09:01.000Z
2021-12-27T17:24:22.000Z
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
null
null
null
Source/DBHandler/database.cpp
Iskeletu/SimpleDB
73429b63bb7c05617e2258c2bd33510044c1746c
[ "MIT" ]
null
null
null
/* Database managment file. All work done in the non-compressed database (.db) file is handled by this file. */ //Libraries #include <string> #include <vector> #include <fstream> #include <filesystem> //Header Files #include "database.h" //Local Database Base Direcaroty Reference const std::string basedir("./Data"); //Default directory databases are loaded from. //=====================Namespace==================== namespace fs = std::filesystem; //================================================== //====================Constructor=================== Database::Database(std::string dbname, std::string path, std::vector<Index> index_vector) : member_name(dbname), member_path(path), member_size(-1), member_last_insertion(-1), member_index(index_vector) {;} //================================================== //=================Database Creator================= Database Database::CreateDatabase(std::string dbname) { //Creates and return a reference to a database. std::string dbfolder(basedir + "/" + dbname); //!This will not work on windows. std::string dbfile(dbfolder + "/" + dbname + ".db"); //!This will not work on windows. if(!fs::exists(basedir)) { //Creates the base folder (default = .{ProjectRoot}/Data/) if it does not exist. fs::create_directory(basedir); } if(!fs::exists(dbfolder)) { //Creates database folder if it does not exist. fs::create_directory(dbfolder); } else { //Deletes contents in folder if it exits but a database creation was called. fs::remove_all(dbfolder); fs::create_directory(dbfolder); } //Creates a new database file and it's reference. std::ofstream ofile(dbfile, std::ios::binary); //Creates file and open as input and output. Database db(dbname, dbfolder, Index::CreateIndex(dbname)); //Creates database reference to previouly created file. //Formats as a default blank database file. db.member_size = 0; db.member_last_insertion = 0; size_t string_size = dbname.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "dbname" string. ofile.write(&dbname[0], string_size); //Inserts "dbname" string. ofile.write((char*)&db.member_size, sizeof(int)); //Inserts database size integer. ofile.flush(); if(!ofile.good()) { //Throws an exception if writing was not successful. throw std::runtime_error("Database::CreateDatabase=writingfailure"); } ofile.close(); //Closes file. //Return the new reference. return db; } //================================================== //==================Database Reader================= void ReadDatabase(Database* db, int* database_size, int* last_insertion, std::vector<Index>* newindex) { //This function loads database members store in binary database file to primary memory. //Slave function to "Database::LoadDatabase". std::string dbfile = (db->GetDirectory() + "/" + db->GetName() +".db"); //!This will not work on windows. std::ifstream ifile(dbfile, std::ios::binary); //Opens file as input. //Reads database size. size_t string_size; ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of database name string on file. ifile.seekg(sizeof(size_t) + string_size); //Sets read location to database size. ifile.read((char*)database_size, sizeof(int)); //Gets database size value. //Reads the number of the last inserted key. if(*database_size > 0) { //The database has at least one key stored. std::string key; int scan = (sizeof(size_t) + string_size + sizeof(int)); //Sets read location to the first key inserted. for(int i = 1; i < *database_size; i++) { //Goes to the last key stored. ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); scan = (scan + sizeof(size_t) + string_size + sizeof(int)); ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); scan = (scan + sizeof(size_t) + string_size); } ifile.seekg(scan); ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of key string on file. key.resize(string_size); ifile.read(&key[0], string_size); //Gets value of the last key string from file and store on "key". key.erase(0, 4); //Removes "key_" from "key" string for integer conversion. *last_insertion = std::stoi(key); //Defines "last_insertion" as the value of the integer conversion from "key" string. } else { //The database has no keys stored. *last_insertion = 0; } ifile.close(); //Closes file. *newindex = Index::LoadIndex(db->GetName(), dbfile, *database_size); //Generates a complete index for the database. //!(might slow down start up). } //================================================== //==================Database Loader================= Database Database::LoadDatabase(std::string dbname) { //Load and return a reference to an existing database. std::string dbfolder(basedir + "/" + dbname); //!This will not work on windows. std::string dbfile(dbfolder + "/" + dbname + ".db"); //!This will not work on windows. if(!fs::exists(dbfolder)) { //Throws a runtime error if the path the function is trying to load the database from does not exist. throw std::runtime_error("Database::LoadDatabase=inexistent_path"); } if(fs::exists(dbfile)) { //Checks if database file exists. //Checks if file is valid by comparing "dbname" with database name stored on the binary file. std::ifstream ifile(dbfile, std::ios::binary); //Opens file as input. size_t string_size; std::string temp; ifile.read((char*)&string_size, sizeof(size_t)); //Gets size of database name string on file. temp.resize(string_size); ifile.read(&temp[0], string_size); //Gets database name on file. ifile.close(); //Closes file. if(temp == dbname) { //The file exist and it's contents are valid. std::vector<Index> newindex = Index::CreateIndex(dbname); Database loadeddb(dbname, dbfolder, newindex); //Creates a database reference. //Loads relevant members to primary memory. int database_size, last_insertion; ReadDatabase(&loadeddb, &database_size, &last_insertion, &newindex); loadeddb.member_size = database_size; //Updates database size. loadeddb.member_last_insertion = last_insertion; //Updates last insertion value. loadeddb.member_index = newindex; //Updates index. return loadeddb; //Returns previouly created database reference. } else { //The file exist but it's contets are invalid. Throws a runtime error. throw std::runtime_error("Database::LoadDatabase=invalid_file"); } } else { //Throws a runtime error if the database the function is trying to load does no exist. throw std::runtime_error("Database::LoadDatabase=inexistent_file"); } } //================================================== //=================Get Name Function================ std::string Database::GetName() { //Returns the name of the database folder. return member_name; } //================================================== //=================Get Size Function================ int Database::GetSize() { //Returns size of the database. return member_size; } //================================================== //================Get Index Function================ std::vector<Index>* Database::GetIndex() { //Returns the database index. return &member_index; } //================================================== //=================Get Path Function================ std::string Database::GetDirectory() { //Returns the full path of the database folder. return member_path; } //================================================== //=================Generete New Key================= std::string Database::NewUniqueKey(void) { //Generates a ney unique key string; return("key_" + std::to_string(member_last_insertion + 1)); } //================================================== //=================Insert Key-Value================= void Database::InsertKeyValue(Datacell* newcell) { //Creates a folder with a name based on the "key" value and store "value" on it. std::string path = (member_path + "/" + member_name + ".db"); //!This will not work on windows. //Extract cell data to local variables. std::string key = newcell->GetKey(); int sorting_key = newcell->GetSortingKey(); std::string value = newcell->GetValue(); //Opens Database file std::ofstream ofile(path, std::ios::binary | std::ios::app); //Opens file as output and set to append to the end of the file. //Datacell insertion. size_t string_size = key.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "key" string. ofile.write(&key[0], string_size); //Inserts "key" strig. ofile.write((char*)&sorting_key, sizeof(int)); //Insert sorting key integer. string_size = value.size(); ofile.write((char*)&string_size, sizeof(size_t)); //Inserts size of "value" string. ofile.write(&value[0], string_size); //Inserts "value" string. if(!ofile.good()) { //Throws an exception if writing was not successful. throw std::runtime_error("Database::InsertKeyValue=writingfailure"); } ofile.close(); ofile.open(path, std::ios::binary | std::ios::in); //Reopens file as output and set to not overwrite unwanted data. member_size++; ofile.seekp(sizeof(size_t) + member_name.size()); //Sets write location to database size. ofile.write((char*)&member_size, sizeof(int)); //Overwrites database size. ofile.close(); //Closes file. //Updates value of the last insertion to the database. key.erase(0,4); //Removes "key_" from "key" string for integer conversion. member_last_insertion = std::stoi(key); //Defines "member_last_insertion" as the value of the integer conversion from "key" string. Index::InsertIndexKey(&member_index, newcell); //Updates index. } //================================================== //=================Search Key-Value================= bool Database::SearchKeyValue(Datacell* existingcell) { //Searchs and loads key value from database file, returns true if informed key exists within the database file and false if not. //Extracts index vector key location if it exists, recieves -1 if it does not. int search_result = Index::IsValidKey(&member_index, stoi((existingcell->GetKey()).erase(0,4))); //Checks if key exist within the index file. if(search_result != -1) { //Key exists, reads value from file and returns true. std::string dbfile(member_path + "/" + member_name + ".db"); //!This will not work on windows. std::string value; value.resize(member_index[search_result].GetValueSize()); std::ifstream ifile(dbfile, std::ios::binary); //Opes file as input. ifile.seekg(member_index[search_result].GetValuePosition()); //Sets read point to desired value. ifile.read(&value[0], member_index[search_result].GetValueSize()); //Reads value to "value" string. ifile.close(); //Closes file. //Updates existing cell. existingcell->UpdateValues(existingcell->GetKey(), member_index[search_result].GetSortingKey(), value); return true; } else { //Key does not exist, return false. return false; } } //================================================== //=================Remove Key-Value================= /*? Complex Function: This function removes the desied key frpom the index, it then uses the remaining values to create a temporary (.temp) file with the contents of main .db files with the exception of the key deleted. When the writing is done, this function replaces the existing .db file with the temporary file, the database then reloads itself (mainly to update index value positions). */ bool Database::RemoveKeyValue(Database* db, Datacell* existingcell) { //Deletes an existing key stored inside the database, returns true if informed key exists within the database file and false if not. //Local references std::string dbname = db->GetName(); std::string filewithoutextension = ((db->GetDirectory()) + "/" + dbname); //!This will not work on windows. std::vector<Index>* index = db->GetIndex(); int dbsize = (db->GetSize() - 1); //Extracts index vector key location if it exists, recieves -1 if it does not. int key = stoi((existingcell->GetKey()).erase(0,4)); int search_result = Index::IsValidKey(index, key); //Checks if key exist within the index file. if(search_result != -1) { //Key exists, deletes key and its values from file and returns true. //? Check function documentation above. size_t string_size; std::string tempstring; int tempint; //Opens database file as input and creates temporary file as output. std::ifstream ifile((filewithoutextension + ".db"), std::ios::binary); std::ofstream ofile((filewithoutextension + ".temp"), std::ios::binary); //Updates datacell information (Same as value search). string_size = (*index)[search_result].GetValueSize(); tempstring.resize(string_size); ifile.seekg((*index)[search_result].GetValuePosition()); ifile.read(&tempstring[0], string_size); existingcell->UpdateValues(existingcell->GetKey(), (*index)[search_result].GetSortingKey(), tempstring); Index::RemoveIndexKey(index, key); //Removes key from index. Index::SortIndex(index, 1); //Sorts index by main key values. //Header writing to temporary file (Same as database creation). string_size = dbname.size(); ofile.write((char*)&string_size, sizeof(size_t)); ofile.write(&dbname[0], string_size); ofile.write((char*)&dbsize, sizeof(int)); for(int i = 1; i < index->size(); i++) { //Writes index information to temporary file. //Key-value writing to temporary file (Same as key insertion). string_size = (*index)[i].GetKeySize(); ofile.write((char*)&string_size, sizeof(size_t)); tempstring = ("key_" + std::to_string((*index)[i].GetKey())); ofile.write(&tempstring[0], string_size); tempint = (*index)[i].GetSortingKey(); ofile.write((char*)&tempint, sizeof(int)); string_size = (*index)[i].GetValueSize(); ofile.write((char*)&string_size, sizeof(size_t)); tempstring.resize(string_size); ifile.seekg((*index)[i].GetValuePosition()); ifile.read(&tempstring[0], string_size); ofile.write(&tempstring[0], string_size); } //Closes files. ifile.close(); ofile.close(); //Replaces main database file with the newly generated temporary file. fs::rename(filewithoutextension + ".temp", filewithoutextension + ".db"); *db = Database::LoadDatabase(dbname); return true; } else { //Key does not exist, return false. return false; } } //================================================== //==================Erase Database================== void Database::Erase() { //Deletes all files and folders related to the database. if (fs::exists(member_path)) { fs::remove_all(member_path); } } //==================================================
43.707809
171
0.55423
Iskeletu
f20bff75d668a7720e9d7bf1a7cfa39d0dfece88
1,135
cpp
C++
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
6
2017-11-24T06:15:40.000Z
2021-01-05T04:47:21.000Z
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
null
null
null
Source/GameWindow.cpp
sergipa/The-Creator-3D
69acf8a4ac169f96ef8ed15e6eb1a47c3a372bda
[ "MIT" ]
3
2017-11-21T13:11:47.000Z
2019-07-01T09:22:49.000Z
#include "GameWindow.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "RenderTextureMSAA.h" #include "ComponentCamera.h" GameWindow::GameWindow() { active = true; window_name = "Game"; game_scene_width = 0; game_scene_height = 0; } GameWindow::~GameWindow() { } void GameWindow::DrawWindow() { if (ImGui::BeginDock(window_name.c_str(), false, false, false, ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { ImVec2 size = ImGui::GetContentRegionAvail(); if (game_scene_width != size.x || game_scene_height != size.y) { if (App->renderer3D->game_camera != nullptr) { App->renderer3D->OnResize(size.x, size.y, App->renderer3D->game_camera); } game_scene_width = size.x; game_scene_height = size.y; } App->renderer3D->SetActiveTexture2D(true); if (App->renderer3D->game_camera != nullptr && App->renderer3D->game_camera->GetViewportTexture() != nullptr) { ImGui::Image((void*)App->renderer3D->game_camera->GetViewportTexture()->GetTextureID(), size, ImVec2(0, 1), ImVec2(1, 0)); } App->renderer3D->SetActiveTexture2D(false); } ImGui::EndDock(); }
25.795455
125
0.711013
sergipa
f20cf856963535ffb585dff01fe1dff5d00d992b
3,535
cpp
C++
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
Banking101/GoodEvent.cpp
tiberius26/Banking101
2cc5e58b4d848643ba0409427381fd9a13c68c21
[ "MIT" ]
null
null
null
#include "GoodEvent.h" GoodEvent::GoodEvent()//set some random information for the event variables { std::srand(std::time(nullptr));//set a seed for the random number generation based on time m_EventName = ""; m_Description = ""; m_ItemName = ""; m_ItemCount = 0; } void GoodEvent::EventManager(Player* Player, Debug* Debug) { if (EventChance() == true)//checks if an event should happen and carries it out { ChooseEvent(Debug, Player); DisplayEvent(Debug, Player); EnactEvent(Player); ClearEvent(); } } bool GoodEvent::EventChance() { int chance = std::rand() % 100 + 1; if (chance <= 20)// 20% chance of a good event { return true; } return false; } void GoodEvent::ChooseEvent(Debug* Debug, Player* Player) { m_EventIndex = std::rand() % 12 + 1;//determines what event to load std::fstream EventData; std::string EventDataLine; char FileToLoad[50]; sprintf_s(FileToLoad, "data/GoodEvents/GoodEvent%d.ini", m_EventIndex);//loads the data of the event EventData.open(FileToLoad); if (!EventData.is_open()) { char Failure[50]; sprintf_s(Failure, "Error reading good event file %d", m_EventIndex);//error checking... Debug->Log(Failure, Serious); } while (!EventData.eof()) { std::getline(EventData, EventDataLine); auto LineSplitter = EventDataLine.find("="); std::string Id = EventDataLine.substr(0, LineSplitter);//where to start and how much to go m_EventData[Id] = EventDataLine.substr(LineSplitter + 1, EventDataLine.size() - (LineSplitter + 1));//stores the data from the read line } EventData.close(); } void GoodEvent::DisplayEvent(Debug* Debug, Player* Player) { std::cout << std::endl << "###################################" << std::endl; std::cout <<"!"<< m_EventData["EventName"]<<"!"<<std::endl; std::cout << m_EventData["Description"] << std::endl; if (Player->CheckItems(m_EventData["ItemName"]) == false) { Player->AddItem(m_EventData["ItemName"],1); std::fstream EventArt; std::string EventArtLineLine; std::string ToDraw; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 2); char FileToLoad[50]; sprintf_s(FileToLoad, "data/GoodEventArt/GoodEventArt%d.ini", m_EventIndex); //drawing here because I want to have different error messages and art locations without having extra checks EventArt.open(FileToLoad); if (!EventArt.is_open()) { char Failure[50]; sprintf_s(Failure, "Error reading good event art %d", m_EventIndex); Debug->Log(Failure, Serious); } while (!EventArt.eof()) { std::getline(EventArt, EventArtLineLine); ToDraw += EventArtLineLine + "\n"; } EventArt.close(); std::cout << "The item you got:" << std::endl; std::cout << ToDraw; SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), 7); } else { std::cout << "Unfortunatelly we cannot hold any more of these, so we sold it for 5000$ (not added to total below)" << std::endl; Player->SetMoney(5000); } } void GoodEvent::EnactEvent(Player* Player) { m_MoneyGained = stoi(m_EventData["MoneyGained"]);//aded it in a variable because I want a clear way of displaying it (line 92) instead of acessing it through the array Player->SetMoney(m_MoneyGained); std::cout << "This event brought the bank " << m_MoneyGained <<"$"<<std::endl; std::cout << std::endl << "###################################" << std::endl; system("pause"); } void GoodEvent::ClearEvent() //kept it separate so I can see it better { m_EventData.clear(); }
35.35
188
0.668741
tiberius26
f20f54b02370c97a0c316c14b2f0d563ac53bd25
1,049
cpp
C++
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/4044/dna.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #define maxn 101005 #define getl(x) min(w[(x)],min(r-(x)+1,(x)-l)) #define inf 1e9 using namespace std; int t,n,w[maxn]; char dna[maxn]; bool ok(char c){ return c=='A'||c=='T'||c=='C'||c=='G'; } int count(int l,int r){ int maxl=0; int ans=r-l+1; for(int i=l+1;i<=r;++i)maxl=max(maxl,getl(i)); if(maxl*2==r-l+1)return count(l,(l+r)/2)+1; for(int i=l+1;i<=r;++i){ int k=getl(i); if(k*2-int(ceil(log(k*2)/log(2)))>=maxl){ if(i-k!=l||i+k-1!=r)ans=min(ans,count(i-k,i+k-1)+r-(i+k-1)+i-k-l); } } return ans; } int main(){ scanf("%d",&t); for(int test=0;test<t;++test){ char ch=getchar(); while(!ok(ch))ch=getchar(); for(n=0;ok(ch);++n,ch=getchar())dna[n]=ch; int ms=1,r=0; memset(w,0,sizeof(w)); for(int i=1;i<n;++i){ w[i]=min(max(0,ms+r-i),w[2*ms-i]); while(i+w[i]<n&&i-w[i]-1>=0&&dna[i+w[i]]==dna[i-w[i]-1])++w[i]; if(i+w[i]>ms+r)ms=i,r=w[i]; } printf("%d\n",count(0,n-1)); } return 0; }
22.319149
70
0.527169
sjj118
f215b4985296643a7fbb822027e167bccb53b00b
137,447
cc
C++
third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor_test.cc
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// Copyright 2016 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 "third_party/blink/renderer/platform/graphics/compositing/paint_artifact_compositor.h" #include <memory> #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "cc/layers/layer.h" #include "cc/test/fake_layer_tree_frame_sink.h" #include "cc/test/geometry_test_utils.h" #include "cc/trees/clip_node.h" #include "cc/trees/effect_node.h" #include "cc/trees/layer_tree_host.h" #include "cc/trees/layer_tree_settings.h" #include "cc/trees/scroll_node.h" #include "cc/trees/transform_node.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/blink/renderer/platform/graphics/paint/effect_paint_property_node.h" #include "third_party/blink/renderer/platform/graphics/paint/paint_artifact.h" #include "third_party/blink/renderer/platform/graphics/paint/scroll_paint_property_node.h" #include "third_party/blink/renderer/platform/testing/fake_display_item_client.h" #include "third_party/blink/renderer/platform/testing/paint_property_test_helpers.h" #include "third_party/blink/renderer/platform/testing/picture_matchers.h" #include "third_party/blink/renderer/platform/testing/runtime_enabled_features_test_helpers.h" #include "third_party/blink/renderer/platform/testing/test_paint_artifact.h" #include "third_party/blink/renderer/platform/testing/web_layer_tree_view_impl_for_testing.h" #include "third_party/blink/renderer/platform/wtf/functional.h" namespace blink { using testing::Pointee; PaintChunk::Id DefaultId() { DEFINE_STATIC_LOCAL(FakeDisplayItemClient, fake_client, ()); return PaintChunk::Id(fake_client, DisplayItem::kDrawingFirst); } PaintChunk DefaultChunk() { return PaintChunk(0, 1, DefaultId(), PropertyTreeState::Root()); } gfx::Transform Translation(SkMScalar x, SkMScalar y) { gfx::Transform transform; transform.Translate(x, y); return transform; } class WebLayerTreeViewWithLayerTreeFrameSink : public WebLayerTreeViewImplForTesting { public: WebLayerTreeViewWithLayerTreeFrameSink(const cc::LayerTreeSettings& settings) : WebLayerTreeViewImplForTesting(settings) {} // cc::LayerTreeHostClient void RequestNewLayerTreeFrameSink() override { GetLayerTreeHost()->SetLayerTreeFrameSink( cc::FakeLayerTreeFrameSink::Create3d()); } }; class FakeScrollClient { public: FakeScrollClient() : did_scroll_count(0) {} void DidScroll(const gfx::ScrollOffset& offset, const CompositorElementId&) { did_scroll_count++; last_scroll_offset = offset; }; gfx::ScrollOffset last_scroll_offset; unsigned did_scroll_count; }; class PaintArtifactCompositorTest : public testing::Test, private ScopedSlimmingPaintV2ForTest { protected: PaintArtifactCompositorTest() : ScopedSlimmingPaintV2ForTest(true), task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_) {} void SetUp() override { // Delay constructing the compositor until after the feature is set. paint_artifact_compositor_ = PaintArtifactCompositor::Create(WTF::BindRepeating( &FakeScrollClient::DidScroll, WTF::Unretained(&scroll_client_))); paint_artifact_compositor_->EnableExtraDataForTesting(); cc::LayerTreeSettings settings = WebLayerTreeViewImplForTesting::DefaultLayerTreeSettings(); settings.single_thread_proxy_scheduler = false; settings.use_layer_lists = true; web_layer_tree_view_ = std::make_unique<WebLayerTreeViewWithLayerTreeFrameSink>(settings); web_layer_tree_view_->SetRootLayer( paint_artifact_compositor_->GetCcLayer()); } void TearDown() override { // Make sure we remove all child layers to satisfy destructor // child layer element id DCHECK. WillBeRemovedFromFrame(); } const cc::PropertyTrees& GetPropertyTrees() { return *web_layer_tree_view_->GetLayerTreeHost()->property_trees(); } const cc::LayerTreeHost& GetLayerTreeHost() { return *web_layer_tree_view_->GetLayerTreeHost(); } int ElementIdToEffectNodeIndex(CompositorElementId element_id) { return web_layer_tree_view_->GetLayerTreeHost() ->property_trees() ->element_id_to_effect_node_index[element_id]; } int ElementIdToTransformNodeIndex(CompositorElementId element_id) { return web_layer_tree_view_->GetLayerTreeHost() ->property_trees() ->element_id_to_transform_node_index[element_id]; } int ElementIdToScrollNodeIndex(CompositorElementId element_id) { return web_layer_tree_view_->GetLayerTreeHost() ->property_trees() ->element_id_to_scroll_node_index[element_id]; } const cc::TransformNode& GetTransformNode(const cc::Layer* layer) { return *GetPropertyTrees().transform_tree.Node( layer->transform_tree_index()); } void Update(const PaintArtifact& artifact) { CompositorElementIdSet element_ids; Update(artifact, element_ids); } void Update(const PaintArtifact& artifact, CompositorElementIdSet& element_ids) { paint_artifact_compositor_->Update(artifact, element_ids); web_layer_tree_view_->GetLayerTreeHost()->LayoutAndUpdateLayers(); } void WillBeRemovedFromFrame() { paint_artifact_compositor_->WillBeRemovedFromFrame(); } cc::Layer* RootLayer() { return paint_artifact_compositor_->RootLayer(); } size_t ContentLayerCount() { return paint_artifact_compositor_->GetExtraDataForTesting() ->content_layers.size(); } cc::Layer* ContentLayerAt(unsigned index) { return paint_artifact_compositor_->GetExtraDataForTesting() ->content_layers[index] .get(); } CompositorElementId ScrollElementId(unsigned id) { return CompositorElementIdFromUniqueObjectId( id, CompositorElementIdNamespace::kScroll); } size_t SynthesizedClipLayerCount() { return paint_artifact_compositor_->GetExtraDataForTesting() ->synthesized_clip_layers.size(); } cc::Layer* SynthesizedClipLayerAt(unsigned index) { return paint_artifact_compositor_->GetExtraDataForTesting() ->synthesized_clip_layers[index] .get(); } cc::Layer* ScrollHitTestLayerAt(unsigned index) { return paint_artifact_compositor_->GetExtraDataForTesting() ->scroll_hit_test_layers[index] .get(); } // Return the index of |layer| in the root layer list, or -1 if not found. int LayerIndex(const cc::Layer* layer) { for (size_t i = 0; i < RootLayer()->children().size(); ++i) { if (RootLayer()->children()[i] == layer) return i; } return -1; } void AddSimpleRectChunk(TestPaintArtifact& artifact) { artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); } void CreateSimpleArtifactWithOpacity(TestPaintArtifact& artifact, float opacity, bool include_preceding_chunk, bool include_subsequent_chunk) { if (include_preceding_chunk) AddSimpleRectChunk(artifact); auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), opacity); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); if (include_subsequent_chunk) AddSimpleRectChunk(artifact); Update(artifact.Build()); } using PendingLayer = PaintArtifactCompositor::PendingLayer; bool MightOverlap(const PendingLayer& a, const PendingLayer& b) { return PaintArtifactCompositor::MightOverlap(a, b); } FakeScrollClient& ScrollClient() { return scroll_client_; } private: FakeScrollClient scroll_client_; std::unique_ptr<PaintArtifactCompositor> paint_artifact_compositor_; scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; std::unique_ptr<WebLayerTreeViewWithLayerTreeFrameSink> web_layer_tree_view_; }; const auto kNotScrollingOnMain = MainThreadScrollingReason::kNotScrollingOnMain; // Convenient shorthands. const TransformPaintPropertyNode* t0() { return TransformPaintPropertyNode::Root(); } const ClipPaintPropertyNode* c0() { return ClipPaintPropertyNode::Root(); } const EffectPaintPropertyNode* e0() { return EffectPaintPropertyNode::Root(); } TEST_F(PaintArtifactCompositorTest, EmptyPaintArtifact) { PaintArtifact empty_artifact; Update(empty_artifact); EXPECT_TRUE(RootLayer()->children().empty()); } TEST_F(PaintArtifactCompositorTest, OneChunkWithAnOffset) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(50, -50, 100, 100), Color::kWhite); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* child = ContentLayerAt(0); EXPECT_THAT( child->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); EXPECT_EQ(Translation(50, -50), child->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(100, 100), child->bounds()); } TEST_F(PaintArtifactCompositorTest, OneTransform) { // A 90 degree clockwise rotation about (100, 100). auto transform = CreateTransform( TransformPaintPropertyNode::Root(), TransformationMatrix().Rotate(90), FloatPoint3D(100, 100, 0), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kGray); artifact .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(2u, ContentLayerCount()); { const cc::Layer* layer = ContentLayerAt(0); Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); rects_with_color.push_back( RectWithColor(FloatRect(100, 100, 200, 100), Color::kBlack)); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); gfx::RectF mapped_rect(0, 0, 100, 100); layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(100, 0, 100, 100), mapped_rect); } { const cc::Layer* layer = ContentLayerAt(1); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kGray))); EXPECT_EQ(gfx::Transform(), layer->ScreenSpaceTransform()); } } TEST_F(PaintArtifactCompositorTest, TransformCombining) { // A translation by (5, 5) within a 2x scale about (10, 10). auto transform1 = CreateTransform( TransformPaintPropertyNode::Root(), TransformationMatrix().Scale(2), FloatPoint3D(10, 10, 0), CompositingReason::k3DTransform); auto transform2 = CreateTransform(transform1, TransformationMatrix().Translate(5, 5), FloatPoint3D(), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact .Chunk(transform1, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kWhite); artifact .Chunk(transform2, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(2u, ContentLayerCount()); { const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kWhite))); gfx::RectF mapped_rect(0, 0, 300, 200); layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(-10, -10, 600, 400), mapped_rect); } { const cc::Layer* layer = ContentLayerAt(1); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kBlack))); gfx::RectF mapped_rect(0, 0, 300, 200); layer->ScreenSpaceTransform().TransformRect(&mapped_rect); EXPECT_EQ(gfx::RectF(0, 0, 600, 400), mapped_rect); } EXPECT_NE(ContentLayerAt(0)->transform_tree_index(), ContentLayerAt(1)->transform_tree_index()); } TEST_F(PaintArtifactCompositorTest, BackfaceVisibility) { TransformPaintPropertyNode::State backface_hidden_state; backface_hidden_state.backface_visibility = TransformPaintPropertyNode::BackfaceVisibility::kHidden; auto backface_hidden_transform = TransformPaintPropertyNode::Create( TransformPaintPropertyNode::Root(), std::move(backface_hidden_state)); auto backface_inherited_transform = TransformPaintPropertyNode::Create( backface_hidden_transform, TransformPaintPropertyNode::State{}); TransformPaintPropertyNode::State backface_visible_state; backface_visible_state.backface_visibility = TransformPaintPropertyNode::BackfaceVisibility::kVisible; auto backface_visible_transform = TransformPaintPropertyNode::Create( backface_hidden_transform, std::move(backface_visible_state)); TestPaintArtifact artifact; artifact .Chunk(backface_hidden_transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kWhite); artifact .Chunk(backface_inherited_transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(100, 100, 100, 100), Color::kBlack); artifact .Chunk(backface_visible_transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kDarkGray); Update(artifact.Build()); ASSERT_EQ(2u, ContentLayerCount()); EXPECT_THAT( ContentLayerAt(0)->GetPicture(), Pointee(DrawsRectangles(Vector<RectWithColor>{ RectWithColor(FloatRect(0, 0, 300, 200), Color::kWhite), RectWithColor(FloatRect(100, 100, 100, 100), Color::kBlack)}))); EXPECT_THAT( ContentLayerAt(1)->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kDarkGray))); } TEST_F(PaintArtifactCompositorTest, FlattensInheritedTransform) { for (bool transform_is_flattened : {true, false}) { SCOPED_TRACE(transform_is_flattened); // The flattens_inherited_transform bit corresponds to whether the _parent_ // transform node flattens the transform. This is because Blink's notion of // flattening determines whether content within the node's local transform // is flattened, while cc's notion applies in the parent's coordinate space. auto transform1 = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix()); auto transform2 = CreateTransform(transform1, TransformationMatrix().Rotate3d(0, 45, 0)); TransformPaintPropertyNode::State transform3_state; transform3_state.matrix = TransformationMatrix().Rotate3d(0, 45, 0); transform3_state.flattens_inherited_transform = transform_is_flattened; auto transform3 = TransformPaintPropertyNode::Create( transform2, std::move(transform3_state)); TestPaintArtifact artifact; artifact .Chunk(transform3, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kWhite); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kWhite))); // The leaf transform node should flatten its inherited transform node // if and only if the intermediate rotation transform in the Blink tree // flattens. const cc::TransformNode* transform_node3 = GetPropertyTrees().transform_tree.Node(layer->transform_tree_index()); EXPECT_EQ(transform_is_flattened, transform_node3->flattens_inherited_transform); // Given this, we should expect the correct screen space transform for // each case. If the transform was flattened, we should see it getting // an effective horizontal scale of 1/sqrt(2) each time, thus it gets // half as wide. If the transform was not flattened, we should see an // empty rectangle (as the total 90 degree rotation makes it // perpendicular to the viewport). gfx::RectF rect(0, 0, 100, 100); layer->ScreenSpaceTransform().TransformRect(&rect); if (transform_is_flattened) EXPECT_FLOAT_RECT_EQ(gfx::RectF(0, 0, 50, 100), rect); else EXPECT_TRUE(rect.IsEmpty()); } } TEST_F(PaintArtifactCompositorTest, SortingContextID) { // Has no 3D rendering context. auto transform1 = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix()); // Establishes a 3D rendering context. TransformPaintPropertyNode::State transform2_3_state; transform2_3_state.rendering_context_id = 1; transform2_3_state.direct_compositing_reasons = CompositingReason::k3DTransform; auto transform2 = TransformPaintPropertyNode::Create( transform1, std::move(transform2_3_state)); // Extends the 3D rendering context of transform2. auto transform3 = TransformPaintPropertyNode::Create( transform2, std::move(transform2_3_state)); // Establishes a 3D rendering context distinct from transform2. TransformPaintPropertyNode::State transform4_state; transform4_state.rendering_context_id = 2; transform4_state.direct_compositing_reasons = CompositingReason::k3DTransform; auto transform4 = TransformPaintPropertyNode::Create( transform2, std::move(transform4_state)); TestPaintArtifact artifact; artifact .Chunk(transform1, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kWhite); artifact .Chunk(transform2, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kLightGray); artifact .Chunk(transform3, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kDarkGray); artifact .Chunk(transform4, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 200), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(4u, ContentLayerCount()); // The white layer is not 3D sorted. const cc::Layer* white_layer = ContentLayerAt(0); EXPECT_THAT( white_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kWhite))); int white_sorting_context_id = GetTransformNode(white_layer).sorting_context_id; EXPECT_EQ(white_layer->sorting_context_id(), white_sorting_context_id); EXPECT_EQ(0, white_sorting_context_id); // The light gray layer is 3D sorted. const cc::Layer* light_gray_layer = ContentLayerAt(1); EXPECT_THAT( light_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kLightGray))); int light_gray_sorting_context_id = GetTransformNode(light_gray_layer).sorting_context_id; EXPECT_NE(0, light_gray_sorting_context_id); // The dark gray layer is 3D sorted with the light gray layer, but has a // separate transform node. const cc::Layer* dark_gray_layer = ContentLayerAt(2); EXPECT_THAT( dark_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kDarkGray))); int dark_gray_sorting_context_id = GetTransformNode(dark_gray_layer).sorting_context_id; EXPECT_EQ(light_gray_sorting_context_id, dark_gray_sorting_context_id); EXPECT_NE(light_gray_layer->transform_tree_index(), dark_gray_layer->transform_tree_index()); // The black layer is 3D sorted, but in a separate context from the previous // layers. const cc::Layer* black_layer = ContentLayerAt(3); EXPECT_THAT( black_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 200), Color::kBlack))); int black_sorting_context_id = GetTransformNode(black_layer).sorting_context_id; EXPECT_NE(0, black_sorting_context_id); EXPECT_NE(light_gray_sorting_context_id, black_sorting_context_id); } TEST_F(PaintArtifactCompositorTest, OneClip) { auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(100, 100, 300, 200)); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), clip, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(220, 80, 300, 200), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); // The layer is clipped. EXPECT_EQ(gfx::Size(180, 180), layer->bounds()); EXPECT_EQ(gfx::Vector2dF(220, 100), layer->offset_to_transform_parent()); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 300, 180), Color::kBlack))); EXPECT_EQ(Translation(220, 100), layer->ScreenSpaceTransform()); const cc::ClipNode* clip_node = GetPropertyTrees().clip_tree.Node(layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, clip_node->clip_type); EXPECT_EQ(gfx::RectF(100, 100, 300, 200), clip_node->clip); } TEST_F(PaintArtifactCompositorTest, NestedClips) { auto clip1 = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(100, 100, 700, 700), CompositingReason::kOverflowScrollingTouch); auto clip2 = CreateClip(clip1, TransformPaintPropertyNode::Root(), FloatRoundedRect(200, 200, 700, 700), CompositingReason::kOverflowScrollingTouch); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), clip1, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(300, 350, 100, 100), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), clip2, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(300, 350, 100, 100), Color::kLightGray); artifact .Chunk(TransformPaintPropertyNode::Root(), clip1, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(300, 350, 100, 100), Color::kDarkGray); artifact .Chunk(TransformPaintPropertyNode::Root(), clip2, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(300, 350, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(4u, ContentLayerCount()); const cc::Layer* white_layer = ContentLayerAt(0); EXPECT_THAT( white_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); EXPECT_EQ(Translation(300, 350), white_layer->ScreenSpaceTransform()); const cc::Layer* light_gray_layer = ContentLayerAt(1); EXPECT_THAT( light_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kLightGray))); EXPECT_EQ(Translation(300, 350), light_gray_layer->ScreenSpaceTransform()); const cc::Layer* dark_gray_layer = ContentLayerAt(2); EXPECT_THAT( dark_gray_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kDarkGray))); EXPECT_EQ(Translation(300, 350), dark_gray_layer->ScreenSpaceTransform()); const cc::Layer* black_layer = ContentLayerAt(3); EXPECT_THAT( black_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kBlack))); EXPECT_EQ(Translation(300, 350), black_layer->ScreenSpaceTransform()); EXPECT_EQ(white_layer->clip_tree_index(), dark_gray_layer->clip_tree_index()); const cc::ClipNode* outer_clip = GetPropertyTrees().clip_tree.Node(white_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, outer_clip->clip_type); EXPECT_EQ(gfx::RectF(100, 100, 700, 700), outer_clip->clip); EXPECT_EQ(light_gray_layer->clip_tree_index(), black_layer->clip_tree_index()); const cc::ClipNode* inner_clip = GetPropertyTrees().clip_tree.Node(black_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, inner_clip->clip_type); EXPECT_EQ(gfx::RectF(200, 200, 700, 700), inner_clip->clip); EXPECT_EQ(outer_clip->id, inner_clip->parent_id); } TEST_F(PaintArtifactCompositorTest, DeeplyNestedClips) { Vector<scoped_refptr<ClipPaintPropertyNode>> clips; for (unsigned i = 1; i <= 10; i++) { clips.push_back(CreateClip( clips.IsEmpty() ? ClipPaintPropertyNode::Root() : clips.back(), TransformPaintPropertyNode::Root(), FloatRoundedRect(5 * i, 0, 100, 200 - 10 * i))); } TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), clips.back(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 200), Color::kWhite); Update(artifact.Build()); // Check the drawing layer. It's clipped. ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* drawing_layer = ContentLayerAt(0); EXPECT_EQ(gfx::Size(100, 100), drawing_layer->bounds()); EXPECT_EQ(gfx::Vector2dF(50, 0), drawing_layer->offset_to_transform_parent()); EXPECT_THAT( drawing_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 150, 200), Color::kWhite))); EXPECT_EQ(Translation(50, 0), drawing_layer->ScreenSpaceTransform()); // Check the clip nodes. const cc::ClipNode* clip_node = GetPropertyTrees().clip_tree.Node(drawing_layer->clip_tree_index()); for (auto it = clips.rbegin(); it != clips.rend(); ++it) { const ClipPaintPropertyNode* paint_clip_node = it->get(); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, clip_node->clip_type); EXPECT_EQ(paint_clip_node->ClipRect().Rect(), clip_node->clip); clip_node = GetPropertyTrees().clip_tree.Node(clip_node->parent_id); } } TEST_F(PaintArtifactCompositorTest, SiblingClips) { auto common_clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(0, 0, 800, 600)); auto clip1 = CreateClip(common_clip, TransformPaintPropertyNode::Root(), FloatRoundedRect(0, 0, 400, 600)); auto clip2 = CreateClip(common_clip, TransformPaintPropertyNode::Root(), FloatRoundedRect(400, 0, 400, 600)); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), clip1, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 640, 480), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), clip2, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 640, 480), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(2u, ContentLayerCount()); const cc::Layer* white_layer = ContentLayerAt(0); EXPECT_THAT( white_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 640, 480), Color::kWhite))); EXPECT_EQ(gfx::Transform(), white_layer->ScreenSpaceTransform()); const cc::ClipNode* white_clip = GetPropertyTrees().clip_tree.Node(white_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, white_clip->clip_type); ASSERT_EQ(gfx::RectF(0, 0, 400, 600), white_clip->clip); const cc::Layer* black_layer = ContentLayerAt(1); // The layer is clipped. EXPECT_EQ(gfx::Size(240, 480), black_layer->bounds()); EXPECT_EQ(gfx::Vector2dF(400, 0), black_layer->offset_to_transform_parent()); EXPECT_THAT( black_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 240, 480), Color::kBlack))); EXPECT_EQ(Translation(400, 0), black_layer->ScreenSpaceTransform()); const cc::ClipNode* black_clip = GetPropertyTrees().clip_tree.Node(black_layer->clip_tree_index()); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, black_clip->clip_type); ASSERT_EQ(gfx::RectF(400, 0, 400, 600), black_clip->clip); EXPECT_EQ(white_clip->parent_id, black_clip->parent_id); const cc::ClipNode* common_clip_node = GetPropertyTrees().clip_tree.Node(white_clip->parent_id); EXPECT_EQ(cc::ClipNode::ClipType::APPLIES_LOCAL_CLIP, common_clip_node->clip_type); ASSERT_EQ(gfx::RectF(0, 0, 800, 600), common_clip_node->clip); } TEST_F(PaintArtifactCompositorTest, ForeignLayerPassesThrough) { scoped_refptr<cc::Layer> layer = cc::Layer::Create(); layer->SetIsDrawable(true); layer->SetBounds(gfx::Size(400, 300)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact.Chunk(PropertyTreeState::Root()) .ForeignLayer(FloatPoint(50, 60), IntSize(400, 300), layer); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(3u, ContentLayerCount()); EXPECT_EQ(layer, ContentLayerAt(1)); EXPECT_EQ(gfx::Size(400, 300), layer->bounds()); EXPECT_EQ(Translation(50, 60), layer->ScreenSpaceTransform()); } TEST_F(PaintArtifactCompositorTest, EffectTreeConversion) { EffectPaintPropertyNode::State effect1_state; effect1_state.local_transform_space = TransformPaintPropertyNode::Root(); effect1_state.output_clip = ClipPaintPropertyNode::Root(); effect1_state.opacity = 0.5; effect1_state.direct_compositing_reasons = CompositingReason::kAll; effect1_state.compositor_element_id = CompositorElementId(2); auto effect1 = EffectPaintPropertyNode::Create( EffectPaintPropertyNode::Root(), std::move(effect1_state)); auto effect2 = CreateOpacityEffect(effect1, 0.3, CompositingReason::kAll); auto effect3 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.2, CompositingReason::kAll); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect2.get()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect1.get()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect3.get()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); Update(artifact.Build()); ASSERT_EQ(3u, ContentLayerCount()); const cc::EffectTree& effect_tree = GetPropertyTrees().effect_tree; // Node #0 reserved for null; #1 for root render surface; #2 for // EffectPaintPropertyNode::root(), plus 3 nodes for those created by // this test. ASSERT_EQ(5u, effect_tree.size()); const cc::EffectNode& converted_root_effect = *effect_tree.Node(1); EXPECT_EQ(-1, converted_root_effect.parent_id); EXPECT_EQ(CompositorElementIdFromUniqueObjectId(1).ToInternalValue(), converted_root_effect.stable_id); const cc::EffectNode& converted_effect1 = *effect_tree.Node(2); EXPECT_EQ(converted_root_effect.id, converted_effect1.parent_id); EXPECT_FLOAT_EQ(0.5, converted_effect1.opacity); EXPECT_EQ(2u, converted_effect1.stable_id); const cc::EffectNode& converted_effect2 = *effect_tree.Node(3); EXPECT_EQ(converted_effect1.id, converted_effect2.parent_id); EXPECT_FLOAT_EQ(0.3, converted_effect2.opacity); const cc::EffectNode& converted_effect3 = *effect_tree.Node(4); EXPECT_EQ(converted_root_effect.id, converted_effect3.parent_id); EXPECT_FLOAT_EQ(0.2, converted_effect3.opacity); EXPECT_EQ(converted_effect2.id, ContentLayerAt(0)->effect_tree_index()); EXPECT_EQ(converted_effect1.id, ContentLayerAt(1)->effect_tree_index()); EXPECT_EQ(converted_effect3.id, ContentLayerAt(2)->effect_tree_index()); } // Returns a ScrollPaintPropertyNode::State with some arbitrary values. static ScrollPaintPropertyNode::State ScrollState1() { ScrollPaintPropertyNode::State state; state.container_rect = IntRect(3, 5, 11, 13); state.contents_rect = IntRect(-3, -5, 27, 31); state.user_scrollable_horizontal = true; return state; } // Returns a ScrollPaintPropertyNode::State with another set arbitrary values. static ScrollPaintPropertyNode::State ScrollState2() { ScrollPaintPropertyNode::State state; state.container_rect = IntRect(0, 0, 19, 23); state.contents_rect = IntRect(0, 0, 29, 31); state.user_scrollable_horizontal = true; return state; } static scoped_refptr<ScrollPaintPropertyNode> CreateScroll( scoped_refptr<const ScrollPaintPropertyNode> parent, const ScrollPaintPropertyNode::State& state_arg, MainThreadScrollingReasons main_thread_scrolling_reasons = MainThreadScrollingReason::kNotScrollingOnMain, CompositorElementId scroll_element_id = CompositorElementId()) { ScrollPaintPropertyNode::State state = state_arg; state.main_thread_scrolling_reasons = main_thread_scrolling_reasons; state.compositor_element_id = scroll_element_id; return ScrollPaintPropertyNode::Create(parent, std::move(state)); } static void CheckCcScrollNode(const ScrollPaintPropertyNode& blink_scroll, const cc::ScrollNode& cc_scroll) { EXPECT_EQ(static_cast<gfx::Size>(blink_scroll.ContainerRect().Size()), cc_scroll.container_bounds); EXPECT_EQ(static_cast<gfx::Size>(blink_scroll.ContentsRect().Size()), cc_scroll.bounds); EXPECT_EQ(blink_scroll.UserScrollableHorizontal(), cc_scroll.user_scrollable_horizontal); EXPECT_EQ(blink_scroll.UserScrollableVertical(), cc_scroll.user_scrollable_vertical); EXPECT_EQ(blink_scroll.GetCompositorElementId(), cc_scroll.element_id); EXPECT_EQ(blink_scroll.GetMainThreadScrollingReasons(), cc_scroll.main_thread_scrolling_reasons); } TEST_F(PaintArtifactCompositorTest, OneScrollNode) { CompositorElementId scroll_element_id = ScrollElementId(2); auto scroll = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState1(), kNotScrollingOnMain, scroll_element_id); auto scroll_translation = CreateScrollTranslation(TransformPaintPropertyNode::Root(), 7, 9, scroll); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation); artifact .Chunk(scroll_translation, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(-110, 12, 170, 19), Color::kWhite); Update(artifact.Build()); const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; // Node #0 reserved for null; #1 for root render surface. ASSERT_EQ(3u, scroll_tree.size()); const cc::ScrollNode& scroll_node = *scroll_tree.Node(2); CheckCcScrollNode(*scroll, scroll_node); EXPECT_EQ(1, scroll_node.parent_id); EXPECT_EQ(scroll_element_id, ScrollHitTestLayerAt(0)->element_id()); EXPECT_EQ(scroll_node.id, ElementIdToScrollNodeIndex(scroll_element_id)); const cc::TransformTree& transform_tree = GetPropertyTrees().transform_tree; const cc::TransformNode& transform_node = *transform_tree.Node(scroll_node.transform_id); EXPECT_TRUE(transform_node.local.IsIdentity()); EXPECT_EQ(gfx::ScrollOffset(-7, -9), transform_node.scroll_offset); EXPECT_EQ(kNotScrollingOnMain, scroll_node.main_thread_scrolling_reasons); auto* layer = ContentLayerAt(0); auto transform_node_index = layer->transform_tree_index(); EXPECT_EQ(transform_node_index, transform_node.id); auto scroll_node_index = layer->scroll_tree_index(); EXPECT_EQ(scroll_node_index, scroll_node.id); // The scrolling contents layer is clipped to the scrolling range. EXPECT_EQ(gfx::Size(27, 14), layer->bounds()); EXPECT_EQ(gfx::Vector2dF(-3, 12), layer->offset_to_transform_parent()); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 63, 19), Color::kWhite))); auto* scroll_layer = ScrollHitTestLayerAt(0); EXPECT_TRUE(scroll_layer->scrollable()); // The scroll layer should be sized to the container bounds. // TODO(pdr): The container bounds will not include scrollbars but the scroll // layer should extend below scrollbars. EXPECT_EQ(gfx::Size(11, 13), scroll_layer->bounds()); EXPECT_EQ(gfx::Vector2dF(3, 5), scroll_layer->offset_to_transform_parent()); EXPECT_EQ(scroll_layer->scroll_tree_index(), scroll_node.id); EXPECT_EQ(scroll_layer->transform_tree_index(), transform_node.parent_id); EXPECT_EQ(0u, ScrollClient().did_scroll_count); scroll_layer->SetScrollOffsetFromImplSide(gfx::ScrollOffset(1, 2)); EXPECT_EQ(1u, ScrollClient().did_scroll_count); EXPECT_EQ(gfx::ScrollOffset(1, 2), ScrollClient().last_scroll_offset); } TEST_F(PaintArtifactCompositorTest, TransformUnderScrollNode) { auto scroll = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState1()); auto scroll_translation = CreateScrollTranslation(TransformPaintPropertyNode::Root(), 7, 9, scroll); auto transform = CreateTransform(scroll_translation, TransformationMatrix(), FloatPoint3D(), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact .Chunk(scroll_translation, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(-20, 4, 60, 8), Color::kBlack) .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(1, -30, 5, 70), Color::kWhite); Update(artifact.Build()); const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; // Node #0 reserved for null; #1 for root render surface. ASSERT_EQ(3u, scroll_tree.size()); const cc::ScrollNode& scroll_node = *scroll_tree.Node(2); // Both layers should refer to the same scroll tree node. const auto* layer0 = ContentLayerAt(0); const auto* layer1 = ContentLayerAt(1); EXPECT_EQ(scroll_node.id, layer0->scroll_tree_index()); EXPECT_EQ(scroll_node.id, layer1->scroll_tree_index()); // The scrolling layer is clipped to the scrollable range. EXPECT_EQ(gfx::Vector2dF(-3, 4), layer0->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(27, 8), layer0->bounds()); EXPECT_THAT(layer0->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 43, 8), Color::kBlack))); // The layer under the transform without a scroll node is not clipped. EXPECT_EQ(gfx::Vector2dF(1, -30), layer1->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(5, 70), layer1->bounds()); EXPECT_THAT(layer1->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 5, 70), Color::kWhite))); const cc::TransformTree& transform_tree = GetPropertyTrees().transform_tree; const cc::TransformNode& scroll_transform_node = *transform_tree.Node(scroll_node.transform_id); // The layers have different transform nodes. EXPECT_EQ(scroll_transform_node.id, layer0->transform_tree_index()); EXPECT_NE(scroll_transform_node.id, layer1->transform_tree_index()); } TEST_F(PaintArtifactCompositorTest, NestedScrollNodes) { auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.5); CompositorElementId scroll_element_id_a = ScrollElementId(2); auto scroll_a = CreateScroll( ScrollPaintPropertyNode::Root(), ScrollState1(), MainThreadScrollingReason::kHasBackgroundAttachmentFixedObjects, scroll_element_id_a); auto scroll_translation_a = CreateScrollTranslation( TransformPaintPropertyNode::Root(), 11, 13, scroll_a, CompositingReason::kLayerForScrollingContents); CompositorElementId scroll_element_id_b = ScrollElementId(3); auto scroll_b = CreateScroll(scroll_a, ScrollState2(), kNotScrollingOnMain, scroll_element_id_b); auto scroll_translation_b = CreateScrollTranslation(scroll_translation_a, 37, 41, scroll_b); TestPaintArtifact artifact; artifact.Chunk(scroll_translation_a, ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(7, 11, 13, 17), Color::kWhite); artifact .Chunk(scroll_translation_a->Parent(), ClipPaintPropertyNode::Root(), effect) .ScrollHitTest(scroll_translation_a); artifact.Chunk(scroll_translation_b, ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(1, 2, 3, 5), Color::kWhite); artifact .Chunk(scroll_translation_b->Parent(), ClipPaintPropertyNode::Root(), effect) .ScrollHitTest(scroll_translation_b); Update(artifact.Build()); const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; // Node #0 reserved for null; #1 for root render surface. ASSERT_EQ(4u, scroll_tree.size()); const cc::ScrollNode& scroll_node_a = *scroll_tree.Node(2); CheckCcScrollNode(*scroll_a, scroll_node_a); EXPECT_EQ(1, scroll_node_a.parent_id); EXPECT_EQ(scroll_element_id_a, ScrollHitTestLayerAt(0)->element_id()); EXPECT_EQ(scroll_node_a.id, ElementIdToScrollNodeIndex(scroll_element_id_a)); const cc::TransformTree& transform_tree = GetPropertyTrees().transform_tree; const cc::TransformNode& transform_node_a = *transform_tree.Node(scroll_node_a.transform_id); EXPECT_TRUE(transform_node_a.local.IsIdentity()); EXPECT_EQ(gfx::ScrollOffset(-11, -13), transform_node_a.scroll_offset); const cc::ScrollNode& scroll_node_b = *scroll_tree.Node(3); CheckCcScrollNode(*scroll_b, scroll_node_b); EXPECT_EQ(scroll_node_a.id, scroll_node_b.parent_id); EXPECT_EQ(scroll_element_id_b, ScrollHitTestLayerAt(1)->element_id()); EXPECT_EQ(scroll_node_b.id, ElementIdToScrollNodeIndex(scroll_element_id_b)); const cc::TransformNode& transform_node_b = *transform_tree.Node(scroll_node_b.transform_id); EXPECT_TRUE(transform_node_b.local.IsIdentity()); EXPECT_EQ(gfx::ScrollOffset(-37, -41), transform_node_b.scroll_offset); } TEST_F(PaintArtifactCompositorTest, ScrollHitTestLayerOrder) { auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(0, 0, 100, 100)); CompositorElementId scroll_element_id = ScrollElementId(2); auto scroll = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState1(), kNotScrollingOnMain, scroll_element_id); auto scroll_translation = CreateScrollTranslation(TransformPaintPropertyNode::Root(), 7, 9, scroll, CompositingReason::kWillChangeCompositingHint); auto transform = CreateTransform( scroll_translation, TransformationMatrix().Translate(5, 5), FloatPoint3D(), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact.Chunk(scroll_translation, clip, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); artifact .Chunk(scroll_translation->Parent(), clip, EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation); artifact.Chunk(transform, clip, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 50, 50), Color::kBlack); Update(artifact.Build()); // The first content layer (background) should not have the scrolling element // id set. EXPECT_EQ(CompositorElementId(), ContentLayerAt(0)->element_id()); // The scroll layer should be after the first content layer (background). EXPECT_LT(LayerIndex(ContentLayerAt(0)), LayerIndex(ScrollHitTestLayerAt(0))); const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; auto* scroll_node = scroll_tree.Node(ScrollHitTestLayerAt(0)->scroll_tree_index()); ASSERT_EQ(scroll_element_id, scroll_node->element_id); EXPECT_EQ(scroll_element_id, ScrollHitTestLayerAt(0)->element_id()); // The second content layer should appear after the first. EXPECT_LT(LayerIndex(ScrollHitTestLayerAt(0)), LayerIndex(ContentLayerAt(1))); EXPECT_EQ(CompositorElementId(), ContentLayerAt(1)->element_id()); } TEST_F(PaintArtifactCompositorTest, NestedScrollHitTestLayerOrder) { auto clip_1 = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(0, 0, 100, 100)); CompositorElementId scroll_1_element_id = ScrollElementId(1); auto scroll_1 = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState1(), kNotScrollingOnMain, scroll_1_element_id); auto scroll_translation_1 = CreateScrollTranslation( TransformPaintPropertyNode::Root(), 7, 9, scroll_1, CompositingReason::kWillChangeCompositingHint); auto clip_2 = CreateClip(clip_1, scroll_translation_1, FloatRoundedRect(0, 0, 50, 50)); CompositorElementId scroll_2_element_id = ScrollElementId(2); auto scroll_2 = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState2(), kNotScrollingOnMain, scroll_2_element_id); auto scroll_translation_2 = CreateScrollTranslation( TransformPaintPropertyNode::Root(), 0, 0, scroll_2, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact .Chunk(scroll_translation_1->Parent(), clip_1->Parent(), EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation_1); artifact .Chunk(scroll_translation_2->Parent(), clip_2->Parent(), EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation_2); artifact.Chunk(scroll_translation_2, clip_2, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 50, 50), Color::kWhite); Update(artifact.Build()); // Two scroll layers should be created for each scroll translation node. const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; const cc::ClipTree& clip_tree = GetPropertyTrees().clip_tree; auto* scroll_1_node = scroll_tree.Node(ScrollHitTestLayerAt(0)->scroll_tree_index()); ASSERT_EQ(scroll_1_element_id, scroll_1_node->element_id); auto* scroll_1_clip_node = clip_tree.Node(ScrollHitTestLayerAt(0)->clip_tree_index()); // The scroll is not under clip_1. EXPECT_EQ(gfx::RectF(0, 0, 0, 0), scroll_1_clip_node->clip); auto* scroll_2_node = scroll_tree.Node(ScrollHitTestLayerAt(1)->scroll_tree_index()); ASSERT_EQ(scroll_2_element_id, scroll_2_node->element_id); auto* scroll_2_clip_node = clip_tree.Node(ScrollHitTestLayerAt(1)->clip_tree_index()); // The scroll is not under clip_2 but is under the parent clip, clip_1. EXPECT_EQ(gfx::RectF(0, 0, 100, 100), scroll_2_clip_node->clip); // The first layer should be before the second scroll layer. EXPECT_LT(LayerIndex(ScrollHitTestLayerAt(0)), LayerIndex(ScrollHitTestLayerAt(1))); // The content layer should be after the second scroll layer. EXPECT_LT(LayerIndex(ScrollHitTestLayerAt(1)), LayerIndex(ContentLayerAt(0))); } // If a scroll node is encountered before its parent, ensure the parent scroll // node is correctly created. TEST_F(PaintArtifactCompositorTest, AncestorScrollNodes) { CompositorElementId scroll_element_id_a = ScrollElementId(2); auto scroll_a = CreateScroll(ScrollPaintPropertyNode::Root(), ScrollState1(), kNotScrollingOnMain, scroll_element_id_a); auto scroll_translation_a = CreateScrollTranslation( TransformPaintPropertyNode::Root(), 11, 13, scroll_a, CompositingReason::kLayerForScrollingContents); CompositorElementId scroll_element_id_b = ScrollElementId(3); auto scroll_b = CreateScroll(scroll_a, ScrollState2(), kNotScrollingOnMain, scroll_element_id_b); auto scroll_translation_b = CreateScrollTranslation(scroll_translation_a, 37, 41, scroll_b); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation_b); artifact .Chunk(scroll_translation_b, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .ScrollHitTest(scroll_translation_a); Update(artifact.Build()); const cc::ScrollTree& scroll_tree = GetPropertyTrees().scroll_tree; // Node #0 reserved for null; #1 for root render surface. ASSERT_EQ(4u, scroll_tree.size()); const cc::ScrollNode& scroll_node_a = *scroll_tree.Node(2); EXPECT_EQ(1, scroll_node_a.parent_id); EXPECT_EQ(scroll_element_id_a, scroll_node_a.element_id); EXPECT_EQ(scroll_node_a.id, ElementIdToScrollNodeIndex(scroll_element_id_a)); // The second scroll hit test layer should be associated with the first // scroll node (a). EXPECT_EQ(scroll_element_id_a, ScrollHitTestLayerAt(1)->element_id()); const cc::TransformTree& transform_tree = GetPropertyTrees().transform_tree; const cc::TransformNode& transform_node_a = *transform_tree.Node(scroll_node_a.transform_id); EXPECT_TRUE(transform_node_a.local.IsIdentity()); EXPECT_EQ(gfx::ScrollOffset(-11, -13), transform_node_a.scroll_offset); const cc::ScrollNode& scroll_node_b = *scroll_tree.Node(3); EXPECT_EQ(scroll_node_a.id, scroll_node_b.parent_id); EXPECT_EQ(scroll_element_id_b, scroll_node_b.element_id); EXPECT_EQ(scroll_node_b.id, ElementIdToScrollNodeIndex(scroll_element_id_b)); // The first scroll hit test layer should be associated with the second scroll // node (b). EXPECT_EQ(scroll_element_id_b, ScrollHitTestLayerAt(0)->element_id()); const cc::TransformNode& transform_node_b = *transform_tree.Node(scroll_node_b.transform_id); EXPECT_TRUE(transform_node_b.local.IsIdentity()); EXPECT_EQ(gfx::ScrollOffset(-37, -41), transform_node_b.scroll_offset); } TEST_F(PaintArtifactCompositorTest, MergeSimpleChunks) { TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(2u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, MergeClip) { auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 20, 50, 60)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), clip.get(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // Clip is applied to this PaintChunk. rects_with_color.push_back( RectWithColor(FloatRect(10, 20, 50, 60), Color::kBlack)); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 300, 400), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, Merge2DTransform) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(50, 50), FloatPoint3D(100, 100, 0)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(transform.get(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // Transform is applied to this PaintChunk. rects_with_color.push_back( RectWithColor(FloatRect(50, 50, 100, 100), Color::kBlack)); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, Merge2DTransformDirectAncestor) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix(), FloatPoint3D(), CompositingReason::k3DTransform); auto transform2 = CreateTransform(transform.get(), TransformationMatrix().Translate(50, 50), FloatPoint3D(100, 100, 0)); TestPaintArtifact test_artifact; test_artifact .Chunk(transform.get(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); // The second chunk can merge into the first because it has a descendant // state of the first's transform and no direct compositing reason. test_artifact .Chunk(transform2.get(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(2u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // Transform is applied to this PaintChunk. rects_with_color.push_back( RectWithColor(FloatRect(50, 50, 100, 100), Color::kBlack)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, MergeTransformOrigin) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Rotate(45), FloatPoint3D(100, 100, 0)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(transform.get(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 42, 100, 100), Color::kWhite)); // Transform is applied to this PaintChunk. rects_with_color.push_back(RectWithColor( FloatRect(29.2893, 0.578644, 141.421, 141.421), Color::kBlack)); rects_with_color.push_back( RectWithColor(FloatRect(0, 42, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, MergeOpacity) { float opacity = 2.0 / 255.0; auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), opacity); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // Transform is applied to this PaintChunk. rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color(Color::kBlack).CombineWithAlpha(opacity).Rgb())); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, MergeNested) { // Tests merging of an opacity effect, inside of a clip, inside of a // transform. auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(50, 50), FloatPoint3D(100, 100, 0)); auto clip = CreateClip(ClipPaintPropertyNode::Root(), transform.get(), FloatRoundedRect(10, 20, 50, 60)); float opacity = 2.0 / 255.0; auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), transform, clip, opacity); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact.Chunk(transform.get(), clip.get(), effect.get()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // Transform is applied to this PaintChunk. rects_with_color.push_back( RectWithColor(FloatRect(60, 70, 50, 60), Color(Color::kBlack).CombineWithAlpha(opacity).Rgb())); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, ClipPushedUp) { // Tests merging of an element which has a clipapplied to it, // but has an ancestor transform of them. This can happen for fixed- // or absolute-position elements which escape scroll transforms. auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto transform2 = CreateTransform(transform.get(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto clip = CreateClip(ClipPaintPropertyNode::Root(), transform2.get(), FloatRoundedRect(10, 20, 50, 60)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), clip.get(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // The two transforms (combined translation of (40, 50)) are applied here, // before clipping. rects_with_color.push_back( RectWithColor(FloatRect(50, 70, 50, 60), Color(Color::kBlack))); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } // TODO(crbug.com/696842): The effect refuses to "decomposite" because it's in // a deeper transform space than its chunk. We should allow decomposite if // the two transform nodes share the same direct compositing ancestor. TEST_F(PaintArtifactCompositorTest, EffectPushedUp_DISABLED) { // Tests merging of an element which has an effect applied to it, // but has an ancestor transform of them. This can happen for fixed- // or absolute-position elements which escape scroll transforms. auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto transform2 = CreateTransform(transform.get(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); float opacity = 2.0 / 255.0; auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), transform2, ClipPaintPropertyNode::Root(), opacity); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 300, 400), Color(Color::kBlack).CombineWithAlpha(opacity).Rgb())); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } // TODO(crbug.com/696842): The effect refuses to "decomposite" because it's in // a deeper transform space than its chunk. We should allow decomposite if // the two transform nodes share the same direct compositing ancestor. TEST_F(PaintArtifactCompositorTest, EffectAndClipPushedUp_DISABLED) { // Tests merging of an element which has an effect applied to it, // but has an ancestor transform of them. This can happen for fixed- // or absolute-position elements which escape scroll transforms. auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto transform2 = CreateTransform(transform.get(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto clip = CreateClip(ClipPaintPropertyNode::Root(), transform.get(), FloatRoundedRect(10, 20, 50, 60)); float opacity = 2.0 / 255.0; auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), transform2, clip, opacity); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), clip.get(), effect.get()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // The clip is under |transform| but not |transform2|, so only an adjustment // of (20, 25) occurs. rects_with_color.push_back( RectWithColor(FloatRect(30, 45, 50, 60), Color(Color::kBlack).CombineWithAlpha(opacity).Rgb())); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, ClipAndEffectNoTransform) { // Tests merging of an element which has a clip and effect in the root // transform space. auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 20, 50, 60)); float opacity = 2.0 / 255.0; auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), clip, opacity); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), clip.get(), effect.get()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); rects_with_color.push_back( RectWithColor(FloatRect(10, 20, 50, 60), Color(Color::kBlack).CombineWithAlpha(opacity).Rgb())); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, TwoClips) { // Tests merging of an element which has two clips in the root // transform space. auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(20, 30, 10, 20)); auto clip2 = CreateClip(clip.get(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 20, 50, 60)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(TransformPaintPropertyNode::Root(), clip2.get(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); // The interesction of the two clips is (20, 30, 10, 20). rects_with_color.push_back( RectWithColor(FloatRect(20, 30, 10, 20), Color(Color::kBlack))); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, TwoTransformsClipBetween) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(0, 0, 50, 60)); auto transform2 = CreateTransform(transform.get(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); TestPaintArtifact test_artifact; test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(transform2.get(), clip.get(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 300, 400), Color::kBlack); test_artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); ASSERT_EQ(1u, ContentLayerCount()); { Vector<RectWithColor> rects_with_color; rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 100, 100), Color::kWhite)); rects_with_color.push_back( RectWithColor(FloatRect(40, 50, 10, 10), Color(Color::kBlack))); rects_with_color.push_back( RectWithColor(FloatRect(0, 0, 200, 300), Color::kGray)); const cc::Layer* layer = ContentLayerAt(0); EXPECT_THAT(layer->GetPicture(), Pointee(DrawsRectangles(rects_with_color))); } } TEST_F(PaintArtifactCompositorTest, OverlapTransform) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(50, 50), FloatPoint3D(100, 100, 0), CompositingReason::k3DTransform); TestPaintArtifact test_artifact; test_artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); test_artifact .Chunk(transform.get(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); test_artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(0, 0, 200, 300), Color::kGray); const PaintArtifact& artifact = test_artifact.Build(); ASSERT_EQ(3u, artifact.PaintChunks().size()); Update(artifact); // The third paint chunk overlaps the second but can't merge due to // incompatible transform. The second paint chunk can't merge into the first // due to a direct compositing reason. ASSERT_EQ(3u, ContentLayerCount()); } TEST_F(PaintArtifactCompositorTest, MightOverlap) { PaintChunk paint_chunk = DefaultChunk(); paint_chunk.bounds = FloatRect(0, 0, 100, 100); PendingLayer pending_layer(paint_chunk, 0, false); PaintChunk paint_chunk2 = DefaultChunk(); paint_chunk2.bounds = FloatRect(0, 0, 100, 100); { PendingLayer pending_layer2(paint_chunk2, 1, false); EXPECT_TRUE(MightOverlap(pending_layer, pending_layer2)); } auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(99, 0), FloatPoint3D(100, 100, 0)); { paint_chunk2.properties.SetTransform(transform.get()); PendingLayer pending_layer2(paint_chunk2, 1, false); EXPECT_TRUE(MightOverlap(pending_layer, pending_layer2)); } auto transform2 = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(100, 0), FloatPoint3D(100, 100, 0)); { paint_chunk2.properties.SetTransform(transform2.get()); PendingLayer pending_layer2(paint_chunk2, 1, false); EXPECT_FALSE(MightOverlap(pending_layer, pending_layer2)); } } TEST_F(PaintArtifactCompositorTest, PendingLayer) { PaintChunk chunk1 = DefaultChunk(); chunk1.properties = PropertyTreeState::Root(); chunk1.known_to_be_opaque = true; chunk1.bounds = FloatRect(0, 0, 30, 40); PendingLayer pending_layer(chunk1, 0, false); EXPECT_EQ(FloatRect(0, 0, 30, 40), pending_layer.bounds); EXPECT_EQ((Vector<size_t>{0}), pending_layer.paint_chunk_indices); EXPECT_EQ(pending_layer.bounds, pending_layer.rect_known_to_be_opaque); PaintChunk chunk2 = DefaultChunk(); chunk2.properties = chunk1.properties; chunk2.known_to_be_opaque = true; chunk2.bounds = FloatRect(10, 20, 30, 40); pending_layer.Merge(PendingLayer(chunk2, 1, false)); // Bounds not equal to one PaintChunk. EXPECT_EQ(FloatRect(0, 0, 40, 60), pending_layer.bounds); EXPECT_EQ((Vector<size_t>{0, 1}), pending_layer.paint_chunk_indices); EXPECT_NE(pending_layer.bounds, pending_layer.rect_known_to_be_opaque); PaintChunk chunk3 = DefaultChunk(); chunk3.properties = chunk1.properties; chunk3.known_to_be_opaque = true; chunk3.bounds = FloatRect(-5, -25, 20, 20); pending_layer.Merge(PendingLayer(chunk3, 2, false)); EXPECT_EQ(FloatRect(-5, -25, 45, 85), pending_layer.bounds); EXPECT_EQ((Vector<size_t>{0, 1, 2}), pending_layer.paint_chunk_indices); EXPECT_NE(pending_layer.bounds, pending_layer.rect_known_to_be_opaque); } TEST_F(PaintArtifactCompositorTest, PendingLayerWithGeometry) { auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix().Translate(20, 25), FloatPoint3D(100, 100, 0)); PaintChunk chunk1 = DefaultChunk(); chunk1.properties = PropertyTreeState(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()); chunk1.bounds = FloatRect(0, 0, 30, 40); PendingLayer pending_layer(chunk1, 0, false); EXPECT_EQ(FloatRect(0, 0, 30, 40), pending_layer.bounds); PaintChunk chunk2 = DefaultChunk(); chunk2.properties = chunk1.properties; chunk2.properties.SetTransform(transform); chunk2.bounds = FloatRect(0, 0, 50, 60); pending_layer.Merge(PendingLayer(chunk2, 1, false)); EXPECT_EQ(FloatRect(0, 0, 70, 85), pending_layer.bounds); } // TODO(crbug.com/701991): // The test is disabled because opaque rect mapping is not implemented yet. TEST_F(PaintArtifactCompositorTest, PendingLayerKnownOpaque_DISABLED) { PaintChunk chunk1 = DefaultChunk(); chunk1.properties = PropertyTreeState(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()); chunk1.bounds = FloatRect(0, 0, 30, 40); chunk1.known_to_be_opaque = false; PendingLayer pending_layer(chunk1, 0, false); EXPECT_TRUE(pending_layer.rect_known_to_be_opaque.IsEmpty()); PaintChunk chunk2 = DefaultChunk(); chunk2.properties = chunk1.properties; chunk2.bounds = FloatRect(0, 0, 25, 35); chunk2.known_to_be_opaque = true; pending_layer.Merge(PendingLayer(chunk2, 1, false)); // Chunk 2 doesn't cover the entire layer, so not opaque. EXPECT_EQ(chunk2.bounds, pending_layer.rect_known_to_be_opaque); EXPECT_NE(pending_layer.bounds, pending_layer.rect_known_to_be_opaque); PaintChunk chunk3 = DefaultChunk(); chunk3.properties = chunk1.properties; chunk3.bounds = FloatRect(0, 0, 50, 60); chunk3.known_to_be_opaque = true; pending_layer.Merge(PendingLayer(chunk3, 2, false)); // Chunk 3 covers the entire layer, so now it's opaque. EXPECT_EQ(chunk3.bounds, pending_layer.bounds); EXPECT_EQ(pending_layer.bounds, pending_layer.rect_known_to_be_opaque); } scoped_refptr<EffectPaintPropertyNode> CreateSampleEffectNodeWithElementId() { EffectPaintPropertyNode::State state; state.local_transform_space = TransformPaintPropertyNode::Root(); state.output_clip = ClipPaintPropertyNode::Root(); state.opacity = 2.0 / 255.0; state.direct_compositing_reasons = CompositingReason::kActiveOpacityAnimation; state.compositor_element_id = CompositorElementId(2); return EffectPaintPropertyNode::Create(EffectPaintPropertyNode::Root(), std::move(state)); } scoped_refptr<TransformPaintPropertyNode> CreateSampleTransformNodeWithElementId() { TransformPaintPropertyNode::State state; state.matrix.Rotate(90); state.origin = FloatPoint3D(100, 100, 0); state.direct_compositing_reasons = CompositingReason::k3DTransform; state.compositor_element_id = CompositorElementId(3); return TransformPaintPropertyNode::Create(TransformPaintPropertyNode::Root(), std::move(state)); } TEST_F(PaintArtifactCompositorTest, TransformWithElementId) { auto transform = CreateSampleTransformNodeWithElementId(); TestPaintArtifact artifact; artifact .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); Update(artifact.Build()); EXPECT_EQ(2, ElementIdToTransformNodeIndex(transform->GetCompositorElementId())); } TEST_F(PaintArtifactCompositorTest, EffectWithElementId) { auto effect = CreateSampleEffectNodeWithElementId(); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); Update(artifact.Build()); EXPECT_EQ(2, ElementIdToEffectNodeIndex(effect->GetCompositorElementId())); } TEST_F(PaintArtifactCompositorTest, CompositedLuminanceMask) { auto masked = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 1.0, CompositingReason::kIsolateCompositedDescendants); EffectPaintPropertyNode::State masking_state; masking_state.local_transform_space = TransformPaintPropertyNode::Root(); masking_state.output_clip = ClipPaintPropertyNode::Root(); masking_state.color_filter = kColorFilterLuminanceToAlpha; masking_state.blend_mode = SkBlendMode::kDstIn; masking_state.direct_compositing_reasons = CompositingReason::kSquashingDisallowed; auto masking = EffectPaintPropertyNode::Create(masked, std::move(masking_state)); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), masked.get()) .RectDrawing(FloatRect(100, 100, 200, 200), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), masking.get()) .RectDrawing(FloatRect(150, 150, 100, 100), Color::kWhite); Update(artifact.Build()); ASSERT_EQ(2u, ContentLayerCount()); const cc::Layer* masked_layer = ContentLayerAt(0); EXPECT_THAT(masked_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 200, 200), Color::kGray))); EXPECT_EQ(Translation(100, 100), masked_layer->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(200, 200), masked_layer->bounds()); const cc::EffectNode* masked_group = GetPropertyTrees().effect_tree.Node(masked_layer->effect_tree_index()); EXPECT_TRUE(masked_group->has_render_surface); const cc::Layer* masking_layer = ContentLayerAt(1); EXPECT_THAT( masking_layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 100, 100), Color::kWhite))); EXPECT_EQ(Translation(150, 150), masking_layer->ScreenSpaceTransform()); EXPECT_EQ(gfx::Size(100, 100), masking_layer->bounds()); const cc::EffectNode* masking_group = GetPropertyTrees().effect_tree.Node(masking_layer->effect_tree_index()); EXPECT_TRUE(masking_group->has_render_surface); EXPECT_EQ(masked_group->id, masking_group->parent_id); ASSERT_EQ(1u, masking_group->filters.size()); EXPECT_EQ(cc::FilterOperation::REFERENCE, masking_group->filters.at(0).type()); } TEST_F(PaintArtifactCompositorTest, UpdateProducesNewSequenceNumber) { // A 90 degree clockwise rotation about (100, 100). auto transform = CreateTransform( TransformPaintPropertyNode::Root(), TransformationMatrix().Rotate(90), FloatPoint3D(100, 100, 0), CompositingReason::k3DTransform); auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(100, 100, 300, 200)); auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.5); TestPaintArtifact artifact; artifact.Chunk(transform, clip, effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kWhite); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kGray); Update(artifact.Build()); // Two content layers for the differentiated rect drawings and three dummy // layers for each of the transform, clip and effect nodes. EXPECT_EQ(2u, RootLayer()->children().size()); int sequence_number = GetPropertyTrees().sequence_number; EXPECT_GT(sequence_number, 0); for (auto layer : RootLayer()->children()) { EXPECT_EQ(sequence_number, layer->property_tree_sequence_number()); } Update(artifact.Build()); EXPECT_EQ(2u, RootLayer()->children().size()); sequence_number++; EXPECT_EQ(sequence_number, GetPropertyTrees().sequence_number); for (auto layer : RootLayer()->children()) { EXPECT_EQ(sequence_number, layer->property_tree_sequence_number()); } Update(artifact.Build()); EXPECT_EQ(2u, RootLayer()->children().size()); sequence_number++; EXPECT_EQ(sequence_number, GetPropertyTrees().sequence_number); for (auto layer : RootLayer()->children()) { EXPECT_EQ(sequence_number, layer->property_tree_sequence_number()); } } TEST_F(PaintArtifactCompositorTest, DecompositeClip) { // A clipped paint chunk that gets merged into a previous layer should // only contribute clipped bounds to the layer bound. auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(75, 75, 100, 100)); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 50, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), clip.get(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(100, 100, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 50.f), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(125, 125), layer->bounds()); } TEST_F(PaintArtifactCompositorTest, DecompositeEffect) { // An effect node without direct compositing reason and does not need to // group compositing descendants should not be composited and can merge // with other chunks. auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.5); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 25, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(25, 75, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(75, 75, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(25.f, 25.f), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(150, 150), layer->bounds()); EXPECT_EQ(1, layer->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, DirectlyCompositedEffect) { // An effect node with direct compositing shall be composited. auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.5f, CompositingReason::kAll); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 25, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(25, 75, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(75, 75, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(3u, ContentLayerCount()); const cc::Layer* layer1 = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 25.f), layer1->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer1->bounds()); EXPECT_EQ(1, layer1->effect_tree_index()); const cc::Layer* layer2 = ContentLayerAt(1); EXPECT_EQ(gfx::Vector2dF(25.f, 75.f), layer2->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer2->bounds()); const cc::EffectNode* effect_node = GetPropertyTrees().effect_tree.Node(layer2->effect_tree_index()); EXPECT_EQ(1, effect_node->parent_id); EXPECT_EQ(0.5f, effect_node->opacity); const cc::Layer* layer3 = ContentLayerAt(2); EXPECT_EQ(gfx::Vector2dF(75.f, 75.f), layer3->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer3->bounds()); EXPECT_EQ(1, layer3->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, DecompositeDeepEffect) { // A paint chunk may enter multiple level effects with or without compositing // reasons. This test verifies we still decomposite effects without a direct // reason, but stop at a directly composited effect. auto effect1 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.1f); auto effect2 = CreateOpacityEffect(effect1, 0.2f, CompositingReason::kAll); auto effect3 = CreateOpacityEffect(effect2, 0.3f); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 25, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect3.get()) .RectDrawing(FloatRect(25, 75, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(75, 75, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(3u, ContentLayerCount()); const cc::Layer* layer1 = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 25.f), layer1->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer1->bounds()); EXPECT_EQ(1, layer1->effect_tree_index()); const cc::Layer* layer2 = ContentLayerAt(1); EXPECT_EQ(gfx::Vector2dF(25.f, 75.f), layer2->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer2->bounds()); const cc::EffectNode* effect_node2 = GetPropertyTrees().effect_tree.Node(layer2->effect_tree_index()); EXPECT_EQ(0.2f, effect_node2->opacity); const cc::EffectNode* effect_node1 = GetPropertyTrees().effect_tree.Node(effect_node2->parent_id); EXPECT_EQ(1, effect_node1->parent_id); EXPECT_EQ(0.1f, effect_node1->opacity); const cc::Layer* layer3 = ContentLayerAt(2); EXPECT_EQ(gfx::Vector2dF(75.f, 75.f), layer3->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer3->bounds()); EXPECT_EQ(1, layer3->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, IndirectlyCompositedEffect) { // An effect node without direct compositing still needs to be composited // for grouping, if some chunks need to be composited. auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.5f); auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix(), FloatPoint3D(), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 25, 100, 100), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(25, 75, 100, 100), Color::kGray); artifact.Chunk(transform.get(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(75, 75, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(3u, ContentLayerCount()); const cc::Layer* layer1 = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 25.f), layer1->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer1->bounds()); EXPECT_EQ(1, layer1->effect_tree_index()); const cc::Layer* layer2 = ContentLayerAt(1); EXPECT_EQ(gfx::Vector2dF(25.f, 75.f), layer2->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer2->bounds()); const cc::EffectNode* effect_node = GetPropertyTrees().effect_tree.Node(layer2->effect_tree_index()); EXPECT_EQ(1, effect_node->parent_id); EXPECT_EQ(0.5f, effect_node->opacity); const cc::Layer* layer3 = ContentLayerAt(2); EXPECT_EQ(gfx::Vector2dF(75.f, 75.f), layer3->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(100, 100), layer3->bounds()); EXPECT_EQ(effect_node->id, layer3->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, DecompositedEffectNotMergingDueToOverlap) { // This tests an effect that doesn't need to be composited, but needs // separate backing due to overlap with a previous composited effect. auto effect1 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.1f); auto effect2 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.2f); auto transform = CreateTransform(TransformPaintPropertyNode::Root(), TransformationMatrix(), FloatPoint3D(), CompositingReason::k3DTransform); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 50, 50), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect1.get()) .RectDrawing(FloatRect(100, 0, 50, 50), Color::kGray); // This chunk has a transform that must be composited, thus causing effect1 // to be composited too. artifact.Chunk(transform.get(), ClipPaintPropertyNode::Root(), effect1.get()) .RectDrawing(FloatRect(200, 0, 50, 50), Color::kGray); artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect2.get()) .RectDrawing(FloatRect(200, 100, 50, 50), Color::kGray); // This chunk overlaps with the 2nd chunk, but is seemingly safe to merge. // However because effect1 gets composited due to a composited transform, // we can't merge with effect1 nor skip it to merge with the first chunk. artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect2.get()) .RectDrawing(FloatRect(100, 0, 50, 50), Color::kGray); Update(artifact.Build()); ASSERT_EQ(4u, ContentLayerCount()); const cc::Layer* layer1 = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(0.f, 0.f), layer1->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(50, 50), layer1->bounds()); EXPECT_EQ(1, layer1->effect_tree_index()); const cc::Layer* layer2 = ContentLayerAt(1); EXPECT_EQ(gfx::Vector2dF(100.f, 0.f), layer2->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(50, 50), layer2->bounds()); const cc::EffectNode* effect_node = GetPropertyTrees().effect_tree.Node(layer2->effect_tree_index()); EXPECT_EQ(1, effect_node->parent_id); EXPECT_EQ(0.1f, effect_node->opacity); const cc::Layer* layer3 = ContentLayerAt(2); EXPECT_EQ(gfx::Vector2dF(200.f, 0.f), layer3->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(50, 50), layer3->bounds()); EXPECT_EQ(effect_node->id, layer3->effect_tree_index()); const cc::Layer* layer4 = ContentLayerAt(3); EXPECT_EQ(gfx::Vector2dF(100.f, 0.f), layer4->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(150, 150), layer4->bounds()); EXPECT_EQ(1, layer4->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, UpdatePopulatesCompositedElementIds) { auto transform = CreateSampleTransformNodeWithElementId(); auto effect = CreateSampleEffectNodeWithElementId(); TestPaintArtifact artifact; artifact .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack) .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); CompositorElementIdSet composited_element_ids; Update(artifact.Build(), composited_element_ids); EXPECT_EQ(2u, composited_element_ids.size()); EXPECT_TRUE( composited_element_ids.Contains(transform->GetCompositorElementId())); EXPECT_TRUE( composited_element_ids.Contains(effect->GetCompositorElementId())); } TEST_F(PaintArtifactCompositorTest, SkipChunkWithOpacityZero) { { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0, false, false); ASSERT_EQ(0u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0, true, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0, true, true); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0, false, true); ASSERT_EQ(1u, ContentLayerCount()); } } TEST_F(PaintArtifactCompositorTest, SkipChunkWithTinyOpacity) { { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0003f, false, false); ASSERT_EQ(0u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0003f, true, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0003f, true, true); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0003f, false, true); ASSERT_EQ(1u, ContentLayerCount()); } } TEST_F(PaintArtifactCompositorTest, DontSkipChunkWithMinimumOpacity) { { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0004f, false, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0004f, true, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0004f, true, true); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.0004f, false, true); ASSERT_EQ(1u, ContentLayerCount()); } } TEST_F(PaintArtifactCompositorTest, DontSkipChunkWithAboveMinimumOpacity) { { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.3f, false, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.3f, true, false); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.3f, true, true); ASSERT_EQ(1u, ContentLayerCount()); } { TestPaintArtifact artifact; CreateSimpleArtifactWithOpacity(artifact, 0.3f, false, true); ASSERT_EQ(1u, ContentLayerCount()); } } TEST_F(PaintArtifactCompositorTest, DontSkipChunkWithTinyOpacityAndDirectCompositingReason) { auto effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.0001f, CompositingReason::kCanvas); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); } TEST_F(PaintArtifactCompositorTest, SkipChunkWithTinyOpacityAndVisibleChildEffectNode) { auto tiny_effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.0001f, CompositingReason::kNone); auto visible_effect = CreateOpacityEffect(tiny_effect, 0.5f, CompositingReason::kNone); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), visible_effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(0u, ContentLayerCount()); } TEST_F( PaintArtifactCompositorTest, DontSkipChunkWithTinyOpacityAndVisibleChildEffectNodeWithCompositingParent) { auto tiny_effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.0001f, CompositingReason::kCanvas); auto visible_effect = CreateOpacityEffect(tiny_effect, 0.5f); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), visible_effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); } TEST_F(PaintArtifactCompositorTest, SkipChunkWithTinyOpacityAndVisibleChildEffectNodeWithCompositingChild) { auto tiny_effect = CreateOpacityEffect(EffectPaintPropertyNode::Root(), 0.0001f); auto visible_effect = CreateOpacityEffect(tiny_effect, 0.5f, CompositingReason::kCanvas); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), visible_effect) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(0u, ContentLayerCount()); } TEST_F(PaintArtifactCompositorTest, UpdateManagesLayerElementIds) { auto transform = CreateSampleTransformNodeWithElementId(); CompositorElementId element_id = transform->GetCompositorElementId(); { TestPaintArtifact artifact; artifact .Chunk(transform, ClipPaintPropertyNode::Root(), EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); ASSERT_TRUE(GetLayerTreeHost().LayerByElementId(element_id)); } { TestPaintArtifact artifact; ASSERT_TRUE(GetLayerTreeHost().LayerByElementId(element_id)); Update(artifact.Build()); ASSERT_EQ(0u, ContentLayerCount()); ASSERT_FALSE(GetLayerTreeHost().LayerByElementId(element_id)); } } TEST_F(PaintArtifactCompositorTest, SynthesizedClipSimple) { // This tests the simplist case that a single layer needs to be clipped // by a single composited rounded clip. FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l1 // l0 [ mask_effect_0 ] // [ mask_isolation_0 ] // [ e0 ] // One content layer, one clip mask. ASSERT_EQ(2u, RootLayer()->children().size()); ASSERT_EQ(1u, ContentLayerCount()); ASSERT_EQ(1u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[1].get(); constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipIndirectlyCompositedClipPath) { // This tests the case that a clip node needs to be synthesized due to // applying clip path to a composited effect. auto c1 = CreateClipPathClip(c0(), t0(), FloatRoundedRect(50, 50, 300, 200)); auto e1 = CreateOpacityEffect(e0(), t0(), c1, 1, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e1) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l0 l1 // [ e1 ][ mask_effect_0 ] // [ mask_isolation_0 ] // [ e0 ] // One content layer, one clip mask. ASSERT_EQ(2u, RootLayer()->children().size()); ASSERT_EQ(1u, ContentLayerCount()); ASSERT_EQ(1u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[1].get(); constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int e1_id = content0->effect_tree_index(); const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); EXPECT_EQ(c1_id, cc_e1.clip_id); int mask_isolation_0_id = cc_e1.parent_id; const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(c1_id, mask_isolation_0.clip_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(c1_id, mask_effect_0.clip_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipContiguous) { // This tests the case that a two back-to-back composited layers having // the same composited rounded clip can share the synthesized mask. auto t1 = CreateTransform(t0(), TransformationMatrix(), FloatPoint3D(), CompositingReason::kWillChangeCompositingHint); FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t1, c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l2 // l0 l1 [ mask_effect_0 ] // [ mask_isolation_0 ] // [ e0 ] // Two content layers, one clip mask. ASSERT_EQ(3u, RootLayer()->children().size()); ASSERT_EQ(2u, ContentLayerCount()); ASSERT_EQ(1u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* content1 = RootLayer()->children()[1].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[2].get(); constexpr int t0_id = 1; constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); EXPECT_EQ(t0_id, content0->transform_tree_index()); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(ContentLayerAt(1), content1); int t1_id = content1->transform_tree_index(); const cc::TransformNode& cc_t1 = *GetPropertyTrees().transform_tree.Node(t1_id); ASSERT_EQ(t0_id, cc_t1.parent_id); EXPECT_EQ(c1_id, content1->clip_tree_index()); EXPECT_EQ(mask_isolation_0_id, content1->effect_tree_index()); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(t0_id, clip_mask0->transform_tree_index()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipDiscontiguous) { // This tests the case that a two composited layers having the same // composited rounded clip cannot share the synthesized mask if there is // another layer in the middle. auto t1 = CreateTransform(t0(), TransformationMatrix(), FloatPoint3D(), CompositingReason::kWillChangeCompositingHint); FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t1, c0(), e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l1 l4 // l0 [ mask_effect_0 ] l3 [ mask_effect_1 ] // [ mask_isolation_0 ] l2 [ mask_isolation_1 ] // [ e0 ] // Three content layers, two clip mask. ASSERT_EQ(5u, RootLayer()->children().size()); ASSERT_EQ(3u, ContentLayerCount()); ASSERT_EQ(2u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[1].get(); const cc::Layer* content1 = RootLayer()->children()[2].get(); const cc::Layer* content2 = RootLayer()->children()[3].get(); const cc::Layer* clip_mask1 = RootLayer()->children()[4].get(); constexpr int t0_id = 1; constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); EXPECT_EQ(t0_id, content0->transform_tree_index()); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(t0_id, clip_mask0->transform_tree_index()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); EXPECT_EQ(ContentLayerAt(1), content1); int t1_id = content1->transform_tree_index(); const cc::TransformNode& cc_t1 = *GetPropertyTrees().transform_tree.Node(t1_id); ASSERT_EQ(t0_id, cc_t1.parent_id); EXPECT_EQ(c0_id, content1->clip_tree_index()); EXPECT_EQ(e0_id, content1->effect_tree_index()); EXPECT_EQ(ContentLayerAt(2), content2); EXPECT_EQ(t0_id, content2->transform_tree_index()); EXPECT_EQ(c1_id, content2->clip_tree_index()); int mask_isolation_1_id = content2->effect_tree_index(); const cc::EffectNode& mask_isolation_1 = *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); ASSERT_EQ(e0_id, mask_isolation_1.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_1.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); EXPECT_EQ(t0_id, clip_mask1->transform_tree_index()); EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); int mask_effect_1_id = clip_mask1->effect_tree_index(); const cc::EffectNode& mask_effect_1 = *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipAcrossChildEffect) { // This tests the case that an effect having the same output clip as the // layers before and after it can share the synthesized mask. FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); auto e1 = CreateOpacityEffect(e0(), t0(), c1, 1, CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e1) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l1 l3 // l0 [ e1 ] l2 [ mask_effect_0 ] // [ mask_isolation_0 ] // [ e0 ] // Three content layers, one clip mask. ASSERT_EQ(4u, RootLayer()->children().size()); ASSERT_EQ(3u, ContentLayerCount()); ASSERT_EQ(1u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* content1 = RootLayer()->children()[1].get(); const cc::Layer* content2 = RootLayer()->children()[2].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[3].get(); constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(ContentLayerAt(1), content1); EXPECT_EQ(c1_id, content1->clip_tree_index()); int e1_id = content1->effect_tree_index(); const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); ASSERT_EQ(mask_isolation_0_id, cc_e1.parent_id); EXPECT_EQ(ContentLayerAt(2), content2); EXPECT_EQ(c1_id, content2->clip_tree_index()); EXPECT_EQ(mask_isolation_0_id, content2->effect_tree_index()); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipRespectOutputClip) { // This tests the case that a layer cannot share the synthesized mask despite // having the same composited rounded clip if it's enclosed by an effect not // clipped by the common clip. FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); CompositorFilterOperations non_trivial_filter; non_trivial_filter.AppendBlurFilter(5); auto e1 = CreateFilterEffect(e0(), non_trivial_filter, FloatPoint(), CompositingReason::kWillChangeCompositingHint); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e1) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l3 // l1 l2 [ mask_effect_1 ] l5 // l0 [ mask_effect_0 ][ mask_isolation_1 ] l4 [ mask_effect_2 ] // [ mask_isolation_0 ][ e1 ][ mask_isolation_2 ] // [ e0 ] // Three content layers, three clip mask. ASSERT_EQ(6u, RootLayer()->children().size()); ASSERT_EQ(3u, ContentLayerCount()); ASSERT_EQ(3u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[1].get(); const cc::Layer* content1 = RootLayer()->children()[2].get(); const cc::Layer* clip_mask1 = RootLayer()->children()[3].get(); const cc::Layer* content2 = RootLayer()->children()[4].get(); const cc::Layer* clip_mask2 = RootLayer()->children()[5].get(); constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); EXPECT_EQ(ContentLayerAt(1), content1); EXPECT_EQ(c1_id, content1->clip_tree_index()); int mask_isolation_1_id = content1->effect_tree_index(); const cc::EffectNode& mask_isolation_1 = *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_1.blend_mode); int e1_id = mask_isolation_1.parent_id; const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); ASSERT_EQ(e0_id, cc_e1.parent_id); EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); int mask_effect_1_id = clip_mask1->effect_tree_index(); const cc::EffectNode& mask_effect_1 = *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); EXPECT_EQ(ContentLayerAt(2), content2); EXPECT_EQ(c1_id, content2->clip_tree_index()); int mask_isolation_2_id = content2->effect_tree_index(); const cc::EffectNode& mask_isolation_2 = *GetPropertyTrees().effect_tree.Node(mask_isolation_2_id); EXPECT_NE(mask_isolation_0_id, mask_isolation_2_id); EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); ASSERT_EQ(e0_id, mask_isolation_2.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_2.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(2), clip_mask2); EXPECT_EQ(gfx::Size(300, 200), clip_mask2->bounds()); EXPECT_EQ(c1_id, clip_mask2->clip_tree_index()); int mask_effect_2_id = clip_mask2->effect_tree_index(); const cc::EffectNode& mask_effect_2 = *GetPropertyTrees().effect_tree.Node(mask_effect_2_id); ASSERT_EQ(mask_isolation_2_id, mask_effect_2.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_2.blend_mode); } TEST_F(PaintArtifactCompositorTest, SynthesizedClipDelegateBlending) { // This tests the case that an effect with exotic blending cannot share // the synthesized mask with its siblings because its blending has to be // applied by the outermost mask. FloatSize corner(5, 5); FloatRoundedRect rrect(FloatRect(50, 50, 300, 200), corner, corner, corner, corner); auto c1 = CreateClip(c0(), t0(), rrect, CompositingReason::kWillChangeCompositingHint); EffectPaintPropertyNode::State e1_state; e1_state.local_transform_space = t0(); e1_state.output_clip = c1; e1_state.blend_mode = SkBlendMode::kMultiply; e1_state.direct_compositing_reasons = CompositingReason::kWillChangeCompositingHint; auto e1 = EffectPaintPropertyNode::Create(e0(), std::move(e1_state)); TestPaintArtifact artifact; artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e1) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); artifact.Chunk(t0(), c1, e0()) .RectDrawing(FloatRect(0, 0, 100, 100), Color::kBlack); Update(artifact.Build()); // Expectation in effect stack diagram: // l1 l2 l3 l5 // l0 [ mask_effect_0 ][ e1 ][ mask_effect_1 ] l4 [ mask_effect_2 ] // [ mask_isolation_0 ][ mask_isolation_1 ][ mask_isolation_2 ] // [ e0 ] // Three content layers, three clip mask. ASSERT_EQ(6u, RootLayer()->children().size()); ASSERT_EQ(3u, ContentLayerCount()); ASSERT_EQ(3u, SynthesizedClipLayerCount()); const cc::Layer* content0 = RootLayer()->children()[0].get(); const cc::Layer* clip_mask0 = RootLayer()->children()[1].get(); const cc::Layer* content1 = RootLayer()->children()[2].get(); const cc::Layer* clip_mask1 = RootLayer()->children()[3].get(); const cc::Layer* content2 = RootLayer()->children()[4].get(); const cc::Layer* clip_mask2 = RootLayer()->children()[5].get(); constexpr int c0_id = 1; constexpr int e0_id = 1; EXPECT_EQ(ContentLayerAt(0), content0); int c1_id = content0->clip_tree_index(); const cc::ClipNode& cc_c1 = *GetPropertyTrees().clip_tree.Node(c1_id); EXPECT_EQ(gfx::RectF(50, 50, 300, 200), cc_c1.clip); ASSERT_EQ(c0_id, cc_c1.parent_id); int mask_isolation_0_id = content0->effect_tree_index(); const cc::EffectNode& mask_isolation_0 = *GetPropertyTrees().effect_tree.Node(mask_isolation_0_id); ASSERT_EQ(e0_id, mask_isolation_0.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(0), clip_mask0); EXPECT_EQ(gfx::Size(300, 200), clip_mask0->bounds()); EXPECT_EQ(c1_id, clip_mask0->clip_tree_index()); int mask_effect_0_id = clip_mask0->effect_tree_index(); const cc::EffectNode& mask_effect_0 = *GetPropertyTrees().effect_tree.Node(mask_effect_0_id); ASSERT_EQ(mask_isolation_0_id, mask_effect_0.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_0.blend_mode); EXPECT_EQ(ContentLayerAt(1), content1); EXPECT_EQ(c1_id, content1->clip_tree_index()); int e1_id = content1->effect_tree_index(); const cc::EffectNode& cc_e1 = *GetPropertyTrees().effect_tree.Node(e1_id); EXPECT_EQ(SkBlendMode::kSrcOver, cc_e1.blend_mode); int mask_isolation_1_id = cc_e1.parent_id; const cc::EffectNode& mask_isolation_1 = *GetPropertyTrees().effect_tree.Node(mask_isolation_1_id); EXPECT_NE(mask_isolation_0_id, mask_isolation_1_id); ASSERT_EQ(e0_id, mask_isolation_1.parent_id); EXPECT_EQ(SkBlendMode::kMultiply, mask_isolation_1.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(1), clip_mask1); EXPECT_EQ(gfx::Size(300, 200), clip_mask1->bounds()); EXPECT_EQ(c1_id, clip_mask1->clip_tree_index()); int mask_effect_1_id = clip_mask1->effect_tree_index(); const cc::EffectNode& mask_effect_1 = *GetPropertyTrees().effect_tree.Node(mask_effect_1_id); ASSERT_EQ(mask_isolation_1_id, mask_effect_1.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_1.blend_mode); EXPECT_EQ(ContentLayerAt(2), content2); EXPECT_EQ(c1_id, content2->clip_tree_index()); int mask_isolation_2_id = content2->effect_tree_index(); const cc::EffectNode& mask_isolation_2 = *GetPropertyTrees().effect_tree.Node(mask_isolation_2_id); EXPECT_NE(mask_isolation_0_id, mask_isolation_2_id); EXPECT_NE(mask_isolation_1_id, mask_isolation_2_id); ASSERT_EQ(e0_id, mask_isolation_2.parent_id); EXPECT_EQ(SkBlendMode::kSrcOver, mask_isolation_0.blend_mode); EXPECT_EQ(SynthesizedClipLayerAt(2), clip_mask2); EXPECT_EQ(gfx::Size(300, 200), clip_mask2->bounds()); EXPECT_EQ(c1_id, clip_mask2->clip_tree_index()); int mask_effect_2_id = clip_mask2->effect_tree_index(); const cc::EffectNode& mask_effect_2 = *GetPropertyTrees().effect_tree.Node(mask_effect_2_id); ASSERT_EQ(mask_isolation_2_id, mask_effect_2.parent_id); EXPECT_EQ(SkBlendMode::kDstIn, mask_effect_2.blend_mode); } TEST_F(PaintArtifactCompositorTest, WillBeRemovedFromFrame) { auto effect = CreateSampleEffectNodeWithElementId(); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect.get()) .RectDrawing(FloatRect(100, 100, 200, 100), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); WillBeRemovedFromFrame(); // We would need a fake or mock LayerTreeHost to validate that we // unregister all element ids, so just check layer count for now. EXPECT_EQ(0u, ContentLayerCount()); } TEST_F(PaintArtifactCompositorTest, ContentsNonOpaque) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 200, 200), Color::kBlack); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_FALSE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, ContentsOpaque) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 200, 200), Color::kBlack) .KnownToBeOpaque(); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_TRUE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, ContentsOpaqueSubpixel) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100.5, 100.5, 200, 200), Color::kBlack) .KnownToBeOpaque(); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_EQ(gfx::Size(201, 201), ContentLayerAt(0)->bounds()); EXPECT_FALSE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, ContentsOpaqueUnitedNonOpaque) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 200, 200), Color::kBlack) .KnownToBeOpaque() .Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(200, 200, 200, 200), Color::kBlack) .KnownToBeOpaque(); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_EQ(gfx::Size(300, 300), ContentLayerAt(0)->bounds()); EXPECT_FALSE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, ContentsOpaqueUnitedOpaque1) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 300, 300), Color::kBlack) .KnownToBeOpaque() .Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(200, 200, 200, 200), Color::kBlack) .KnownToBeOpaque(); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_EQ(gfx::Size(300, 300), ContentLayerAt(0)->bounds()); EXPECT_TRUE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, ContentsOpaqueUnitedOpaque2) { TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 200, 200), Color::kBlack) .KnownToBeOpaque() .Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(100, 100, 300, 300), Color::kBlack) .KnownToBeOpaque(); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); EXPECT_EQ(gfx::Size(300, 300), ContentLayerAt(0)->bounds()); // TODO(crbug.com/701991): Upgrade GeometryMapper to make this test pass with // the following EXPECT_FALSE changed to EXPECT_TRUE. EXPECT_FALSE(ContentLayerAt(0)->contents_opaque()); } TEST_F(PaintArtifactCompositorTest, DecompositeEffectWithNoOutputClip) { // This test verifies effect nodes with no output clip correctly decomposites // if there is no compositing reasons. auto clip1 = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(75, 75, 100, 100)); auto effect1 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), nullptr, 0.5); TestPaintArtifact artifact; artifact.Chunk(PropertyTreeState::Root()) .RectDrawing(FloatRect(50, 50, 100, 100), Color::kGray); artifact.Chunk(TransformPaintPropertyNode::Root(), clip1.get(), effect1.get()) .RectDrawing(FloatRect(100, 100, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 50.f), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(125, 125), layer->bounds()); EXPECT_EQ(1, layer->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, CompositedEffectWithNoOutputClip) { // This test verifies effect nodes with no output clip but has compositing // reason correctly squash children chunks and assign clip node. auto clip1 = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(75, 75, 100, 100)); auto effect1 = CreateOpacityEffect(EffectPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), nullptr, 0.5, CompositingReason::kAll); TestPaintArtifact artifact; artifact .Chunk(TransformPaintPropertyNode::Root(), ClipPaintPropertyNode::Root(), effect1.get()) .RectDrawing(FloatRect(50, 50, 100, 100), Color::kGray); artifact.Chunk(TransformPaintPropertyNode::Root(), clip1.get(), effect1.get()) .RectDrawing(FloatRect(100, 100, 100, 100), Color::kGray); Update(artifact.Build()); ASSERT_EQ(1u, ContentLayerCount()); const cc::Layer* layer = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50.f, 50.f), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(125, 125), layer->bounds()); EXPECT_EQ(1, layer->clip_tree_index()); EXPECT_EQ(2, layer->effect_tree_index()); } TEST_F(PaintArtifactCompositorTest, LayerRasterInvalidationWithClip) { // The layer's painting is initially not clipped. auto clip = CreateClip(ClipPaintPropertyNode::Root(), TransformPaintPropertyNode::Root(), FloatRoundedRect(10, 20, 300, 400)); TestPaintArtifact artifact1; artifact1 .Chunk(TransformPaintPropertyNode::Root(), clip, EffectPaintPropertyNode::Root()) .RectDrawing(FloatRect(50, 50, 200, 200), Color::kBlack); Update(artifact1.Build()); ASSERT_EQ(1u, ContentLayerCount()); auto* layer = ContentLayerAt(0); EXPECT_EQ(gfx::Vector2dF(50, 50), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(200, 200), layer->bounds()); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 200, 200), Color::kBlack))); // The layer's painting overflows the left, top, right edges of the clip . TestPaintArtifact artifact2; artifact2 .Chunk(artifact1.Client(0), TransformPaintPropertyNode::Root(), clip, EffectPaintPropertyNode::Root()) .RectDrawing(artifact1.Client(1), FloatRect(0, 0, 400, 200), Color::kBlack); layer->ResetNeedsDisplayForTesting(); Update(artifact2.Build()); ASSERT_EQ(1u, ContentLayerCount()); ASSERT_EQ(layer, ContentLayerAt(0)); // Invalidate the first chunk because its transform in layer changed. EXPECT_EQ(gfx::Rect(0, 0, 300, 180), layer->update_rect()); EXPECT_EQ(gfx::Vector2dF(10, 20), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(300, 180), layer->bounds()); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 390, 180), Color::kBlack))); // The layer's painting overflows all edges of the clip. TestPaintArtifact artifact3; artifact3 .Chunk(artifact1.Client(0), TransformPaintPropertyNode::Root(), clip, EffectPaintPropertyNode::Root()) .RectDrawing(artifact1.Client(1), FloatRect(-100, -200, 500, 800), Color::kBlack); layer->ResetNeedsDisplayForTesting(); Update(artifact3.Build()); ASSERT_EQ(1u, ContentLayerCount()); ASSERT_EQ(layer, ContentLayerAt(0)); // We should not invalidate the layer because the origin didn't change // because of the clip. EXPECT_EQ(gfx::Rect(), layer->update_rect()); EXPECT_EQ(gfx::Vector2dF(10, 20), layer->offset_to_transform_parent()); EXPECT_EQ(gfx::Size(300, 400), layer->bounds()); EXPECT_THAT( layer->GetPicture(), Pointee(DrawsRectangle(FloatRect(0, 0, 390, 580), Color::kBlack))); } } // namespace blink
42.278376
95
0.710085
zipated
f216ab6b3df5c5c41380a9d098bcd33cbba95bb7
4,132
cpp
C++
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
matealex/MixedRealityCompanionKit
cbd61ca6b2a45f8dd6855995bf539cbdfe194ea7
[ "MIT" ]
204
2017-08-12T12:57:26.000Z
2019-04-25T20:22:12.000Z
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
Troy-Ferrell/MixedRealityCompanionKit
3ce06ce1e32e91b826d4370b6df5d28918982b2f
[ "MIT" ]
159
2017-08-12T09:38:46.000Z
2019-04-25T17:04:50.000Z
SpectatorView/Compositor/CompositorDLL/OpenCVFrameProvider.cpp
Troy-Ferrell/MixedRealityCompanionKit
3ce06ce1e32e91b826d4370b6df5d28918982b2f
[ "MIT" ]
159
2017-08-13T22:51:09.000Z
2019-05-02T02:32:55.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "stdafx.h" #include "OpenCVFrameProvider.h" #if USE_OPENCV OpenCVFrameProvider::OpenCVFrameProvider() { QueryPerformanceFrequency(&freq); rgbaFrame = cv::Mat(FRAME_HEIGHT, FRAME_WIDTH, CV_8UC4); for (int i = 0; i < 4; i++) { rgbaConversion[i * 2] = i; rgbaConversion[(i * 2) + 1] = i; } for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { bufferCache[i].buffer = new BYTE[FRAME_BUFSIZE]; bufferCache[i].timeStamp = 0; } captureFrameIndex = 0; } OpenCVFrameProvider::~OpenCVFrameProvider() { for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { delete[] bufferCache[i].buffer; } } HRESULT OpenCVFrameProvider::Initialize(ID3D11ShaderResourceView* srv) { if (IsEnabled()) { return S_OK; } _colorSRV = srv; if (_colorSRV != nullptr) { _colorSRV->GetDevice(&_device); } HRESULT hr = E_PENDING; videoCapture = new cv::VideoCapture(CAMERA_ID); for (int i = 0; i < MAX_NUM_CACHED_BUFFERS; i++) { ZeroMemory(bufferCache[i].buffer, FRAME_BUFSIZE); } captureFrameIndex = 0; if (videoCapture->open(CAMERA_ID)) { // Attempt to update camera resolution to desired resolution. // This must be called after opening. // Note: This may fail, and your capture will resume at the camera's native resolution. // In this case, the Update loop will print an error with the expected frame resolution. videoCapture->set(cv::CAP_PROP_FRAME_WIDTH, FRAME_WIDTH); videoCapture->set(cv::CAP_PROP_FRAME_HEIGHT, FRAME_HEIGHT); if (IsEnabled()) { hr = S_OK; } } return hr; } bool OpenCVFrameProvider::IsEnabled() { if (videoCapture != nullptr) { return videoCapture->isOpened(); } return false; } void OpenCVFrameProvider::Update(int compositeFrameIndex) { if (!IsEnabled() || _colorSRV == nullptr || _device == nullptr) { return; } concurrency::create_task([=] { if (videoCapture->grab()) { LARGE_INTEGER time; QueryPerformanceCounter(&time); if (videoCapture->retrieve(frame)) { latestTimeStamp = time.QuadPart; double width = videoCapture->get(cv::CAP_PROP_FRAME_WIDTH); double height = videoCapture->get(cv::CAP_PROP_FRAME_HEIGHT); if (width != FRAME_WIDTH) { OutputDebugString(L"ERROR: captured width does not equal FRAME_WIDTH. Expecting: "); OutputDebugString(std::to_wstring(width).c_str()); OutputDebugString(L"\n"); } if (height != FRAME_HEIGHT) { OutputDebugString(L"ERROR: captured height does not equal FRAME_HEIGHT. Expecting: "); OutputDebugString(std::to_wstring(height).c_str()); OutputDebugString(L"\n"); } // Convert from rgb to rgba mixChannels(&frame, 2, &rgbaFrame, 1, rgbaConversion, 4); captureFrameIndex++; BYTE* buffer = bufferCache[captureFrameIndex % MAX_NUM_CACHED_BUFFERS].buffer; memcpy(buffer, rgbaFrame.data, FRAME_BUFSIZE); bufferCache[captureFrameIndex % MAX_NUM_CACHED_BUFFERS].timeStamp = (latestTimeStamp * S2HNS) / freq.QuadPart; } } }); const BufferCache& buffer = bufferCache[compositeFrameIndex % MAX_NUM_CACHED_BUFFERS]; if (buffer.buffer != nullptr) { DirectXHelper::UpdateSRV(_device, _colorSRV, buffer.buffer, FRAME_WIDTH * FRAME_BPP); } } void OpenCVFrameProvider::Dispose() { if (videoCapture != nullptr) { videoCapture->release(); videoCapture = nullptr; } captureFrameIndex = 0; } #endif
26.658065
126
0.593901
matealex
35ea17c6b284d5f384918c1f343ff211c8c621e2
598
cpp
C++
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/UOJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
80
2015-01-07T01:18:40.000Z
2021-05-04T15:23:18.000Z
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
1
2019-01-07T01:13:32.000Z
2019-01-07T01:13:32.000Z
src/UOJ_1031 - (1619983) Accepted.cpp
miguelarauj1o/OJ
eb195754829c42c3dcf1a68616e63da1386cb5a9
[ "MIT" ]
28
2015-03-05T11:53:23.000Z
2020-07-05T15:50:42.000Z
#include <cstdio> #include <vector> #define PB push_back #define SC1(a) scanf("%d", &a) #define REP(i, a, b) for (int i = (a); i <= (b); ++i) using namespace std; typedef vector<int> VI; bool crisis(int n, int k) { int p = 0; VI v; REP(i, 1, n) v.PB(i); if(v.size() > 1){ do{ v.erase(v.begin() + p); p = (p - 1 + k) % v.size(); }while(v.size() > 1); } return (v[0] == 13); } int main(int argc, char const *argv[]) { int n, r; while(SC1(n) && n) { r = 1; while(!crisis(n, r)) r++; printf("%d\n", r); } return 0; }
13.590909
54
0.4699
miguelarauj1o
35ebb0c5e0efdacfc53b3be2fbcdef1937324c1d
1,503
cpp
C++
SOURCES/falclib/token.cpp
IsraelyFlightSimulator/Negev-Storm
86de63e195577339f6e4a94198bedd31833a8be8
[ "Unlicense" ]
1
2021-02-19T06:06:31.000Z
2021-02-19T06:06:31.000Z
src/falclib/token.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
null
null
null
src/falclib/token.cpp
markbb1957/FFalconSource
07b12e2c41a93fa3a95b912a2433a8056de5bc4d
[ "BSD-2-Clause" ]
2
2019-08-20T13:35:13.000Z
2021-04-24T07:32:04.000Z
#include <string.h> #include <stdlib.h> #include "token.h" // MLR 12/13/2003 - Simple token parsing char *tokenStr=0; float TokenF(float def) { return(TokenF(tokenStr,def)); } float TokenF(char *str, float def) { char *bs; tokenStr=0; if(bs=strtok(str," ,\t\n")) { return((float)atof(bs)); } return(def); } int TokenI(int def) { return(TokenI(tokenStr,def)); } int TokenI(char *str, int def) { char *bs; tokenStr=0; if(bs=strtok(str," ,\t\n")) { return(atoi(bs)); } return(def); } int TokenFlags(int def, char *flagstr) { return(TokenFlags(tokenStr, def, flagstr)); } int TokenFlags(char *str, int def, char *flagstr) { char *arg; int flags=0; tokenStr=0; if(arg=strtok(str," ,\t\n")) { while(*arg) { int l; for(l=0;l<32 && flagstr[l];l++) { if(*arg==flagstr[l]) { flags|=1<<l; } } arg++; } return(flags); } return(def); } int TokenEnum(char **enumnames, int def) { return(TokenEnum(tokenStr,enumnames,def)); } int TokenEnum(char *str, char **enumnames, int def) { char *arg; int i=0; tokenStr=0; if(arg=strtok(str," ,\t\n")) { while(*enumnames) { if(stricmp(arg,*enumnames)==0) { return i; } enumnames++; i++; } } return def; } void SetTokenString(char *str) { tokenStr = str; } char *TokenStr(char *def) { return(TokenStr(tokenStr,def)); } char *TokenStr(char *str, char *def) { char *bs; tokenStr=0; if(bs=strtok(str," :,\t\n")) { return(bs); } return(def); }
11.300752
51
0.590818
IsraelyFlightSimulator
35ec2db7c9a9f261e9d536da75413f2c18b3ee92
1,942
cpp
C++
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/PolygonOffset.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
3
2018-08-20T12:12:43.000Z
2021-06-06T09:43:27.000Z
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/PolygonOffset.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
null
null
null
deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/ive/PolygonOffset.cpp
UM-ARM-Lab/mab_ms
f199f05b88060182cfbb47706bd1ff3479032c43
[ "BSD-2-Clause" ]
1
2022-03-31T03:12:23.000Z
2022-03-31T03:12:23.000Z
/********************************************************************** * * FILE: PolygonOffset.cpp * * DESCRIPTION: Read/Write osg::PolygonOffset in binary format to disk. * * CREATED BY: Auto generated by iveGenerator * and later modified by Rune Schmidt Jensen. * * HISTORY: Created 27.3.2003 * * Copyright 2003 VR-C **********************************************************************/ #include "Exception.h" #include "PolygonOffset.h" #include "Object.h" using namespace ive; void PolygonOffset::write(DataOutputStream* out){ // Write CullFace's identification. out->writeInt(IVEPOLYGONOFFSET); // If the osg class is inherited by any other class we should also write this to file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->write(out); } else throw Exception("PolygonOffset::write(): Could not cast this osg::PolygonOffset to an osg::Object."); // Write PolygonOffset's properties. out->writeFloat(getFactor()); out->writeFloat(getUnits()); } void PolygonOffset::read(DataInputStream* in){ // Peek on PolygonOffset's identification. int id = in->peekInt(); if(id == IVEPOLYGONOFFSET){ // Read PolygonOffset's identification. id = in->readInt(); // If the osg class is inherited by any other class we should also read this from file. osg::Object* obj = dynamic_cast<osg::Object*>(this); if(obj){ ((ive::Object*)(obj))->read(in); } else throw Exception("PolygonOffset::read(): Could not cast this osg::PolygonOffset to an osg::Object."); // Read PolygonOffset's properties setFactor(in->readFloat()); setUnits(in->readFloat()); } else{ throw Exception("PolygonOffset::read(): Expected PolygonOffset identification."); } }
34.070175
112
0.57827
UM-ARM-Lab
35ef66e0dce1ecf20e864d6b5a57b6355995ad1d
10,419
hpp
C++
src/hotspot/share/gc/shenandoah/c2/shenandoahSupport.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/gc/shenandoah/c2/shenandoahSupport.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
src/hotspot/share/gc/shenandoah/c2/shenandoahSupport.hpp
siweilxy/openjdkstudy
8597674ec1d6809faf55cbee1f45f4e9149d670d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2015, 2018, Red Hat, Inc. All rights reserved. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. * */ #ifndef SHARE_GC_SHENANDOAH_C2_SHENANDOAHSUPPORT_HPP #define SHARE_GC_SHENANDOAH_C2_SHENANDOAHSUPPORT_HPP #include "memory/allocation.hpp" #include "opto/addnode.hpp" #include "opto/graphKit.hpp" #include "opto/machnode.hpp" #include "opto/memnode.hpp" #include "opto/multnode.hpp" #include "opto/node.hpp" class PhaseGVN; class MemoryGraphFixer; class ShenandoahBarrierC2Support : public AllStatic { private: #ifdef ASSERT enum verify_type { ShenandoahLoad, ShenandoahStore, ShenandoahValue, ShenandoahOopStore, ShenandoahNone }; static bool verify_helper(Node* in, Node_Stack& phis, VectorSet& visited, verify_type t, bool trace, Unique_Node_List& barriers_used); static void report_verify_failure(const char* msg, Node* n1 = NULL, Node* n2 = NULL); static void verify_raw_mem(RootNode* root); #endif static Node* dom_mem(Node* mem, Node* ctrl, int alias, Node*& mem_ctrl, PhaseIdealLoop* phase); static Node* no_branches(Node* c, Node* dom, bool allow_one_proj, PhaseIdealLoop* phase); static bool is_heap_state_test(Node* iff, int mask); static bool try_common_gc_state_load(Node *n, PhaseIdealLoop *phase); static bool has_safepoint_between(Node* start, Node* stop, PhaseIdealLoop *phase); static Node* find_bottom_mem(Node* ctrl, PhaseIdealLoop* phase); static void follow_barrier_uses(Node* n, Node* ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase); static void test_null(Node*& ctrl, Node* val, Node*& null_ctrl, PhaseIdealLoop* phase); static void test_heap_stable(Node*& ctrl, Node* raw_mem, Node*& heap_stable_ctrl, PhaseIdealLoop* phase); static void call_lrb_stub(Node*& ctrl, Node*& val, Node*& result_mem, Node* raw_mem, PhaseIdealLoop* phase); static Node* clone_null_check(Node*& c, Node* val, Node* unc_ctrl, PhaseIdealLoop* phase); static void fix_null_check(Node* unc, Node* unc_ctrl, Node* new_unc_ctrl, Unique_Node_List& uses, PhaseIdealLoop* phase); static void in_cset_fast_test(Node*& ctrl, Node*& not_cset_ctrl, Node* val, Node* raw_mem, PhaseIdealLoop* phase); static void move_heap_stable_test_out_of_loop(IfNode* iff, PhaseIdealLoop* phase); static void merge_back_to_back_tests(Node* n, PhaseIdealLoop* phase); static bool identical_backtoback_ifs(Node *n, PhaseIdealLoop* phase); static void fix_ctrl(Node* barrier, Node* region, const MemoryGraphFixer& fixer, Unique_Node_List& uses, Unique_Node_List& uses_to_ignore, uint last, PhaseIdealLoop* phase); static IfNode* find_unswitching_candidate(const IdealLoopTree *loop, PhaseIdealLoop* phase); public: static bool is_dominator(Node* d_c, Node* n_c, Node* d, Node* n, PhaseIdealLoop* phase); static bool is_dominator_same_ctrl(Node* c, Node* d, Node* n, PhaseIdealLoop* phase); static bool is_gc_state_load(Node* n); static bool is_heap_stable_test(Node* iff); static bool expand(Compile* C, PhaseIterGVN& igvn); static void pin_and_expand(PhaseIdealLoop* phase); static void optimize_after_expansion(VectorSet& visited, Node_Stack& nstack, Node_List& old_new, PhaseIdealLoop* phase); #ifdef ASSERT static void verify(RootNode* root); #endif }; class ShenandoahEnqueueBarrierNode : public Node { public: ShenandoahEnqueueBarrierNode(Node* val); const Type *bottom_type() const; const Type* Value(PhaseGVN* phase) const; Node* Identity(PhaseGVN* phase); int Opcode() const; private: enum { Needed, NotNeeded, MaybeNeeded }; static int needed(Node* n); static Node* next(Node* n); }; class MemoryGraphFixer : public ResourceObj { private: Node_List _memory_nodes; int _alias; PhaseIdealLoop* _phase; bool _include_lsm; void collect_memory_nodes(); Node* get_ctrl(Node* n) const; Node* ctrl_or_self(Node* n) const; bool mem_is_valid(Node* m, Node* c) const; MergeMemNode* allocate_merge_mem(Node* mem, Node* rep_proj, Node* rep_ctrl) const; MergeMemNode* clone_merge_mem(Node* u, Node* mem, Node* rep_proj, Node* rep_ctrl, DUIterator& i) const; void fix_memory_uses(Node* mem, Node* replacement, Node* rep_proj, Node* rep_ctrl) const; bool should_process_phi(Node* phi) const; bool has_mem_phi(Node* region) const; public: MemoryGraphFixer(int alias, bool include_lsm, PhaseIdealLoop* phase) : _alias(alias), _phase(phase), _include_lsm(include_lsm) { assert(_alias != Compile::AliasIdxBot, "unsupported"); collect_memory_nodes(); } Node* find_mem(Node* ctrl, Node* n) const; void fix_mem(Node* ctrl, Node* region, Node* mem, Node* mem_for_ctrl, Node* mem_phi, Unique_Node_List& uses); int alias() const { return _alias; } }; class ShenandoahCompareAndSwapPNode : public CompareAndSwapPNode { public: ShenandoahCompareAndSwapPNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : CompareAndSwapPNode(c, mem, adr, val, ex, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypePtr::NULL_PTR) { return new CompareAndSwapPNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahCompareAndSwapNNode : public CompareAndSwapNNode { public: ShenandoahCompareAndSwapNNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : CompareAndSwapNNode(c, mem, adr, val, ex, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypeNarrowOop::NULL_PTR) { return new CompareAndSwapNNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahWeakCompareAndSwapPNode : public WeakCompareAndSwapPNode { public: ShenandoahWeakCompareAndSwapPNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : WeakCompareAndSwapPNode(c, mem, adr, val, ex, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypePtr::NULL_PTR) { return new WeakCompareAndSwapPNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahWeakCompareAndSwapNNode : public WeakCompareAndSwapNNode { public: ShenandoahWeakCompareAndSwapNNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, MemNode::MemOrd mem_ord) : WeakCompareAndSwapNNode(c, mem, adr, val, ex, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypeNarrowOop::NULL_PTR) { return new WeakCompareAndSwapNNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahCompareAndExchangePNode : public CompareAndExchangePNode { public: ShenandoahCompareAndExchangePNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, const TypePtr* at, const Type* t, MemNode::MemOrd mem_ord) : CompareAndExchangePNode(c, mem, adr, val, ex, at, t, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypePtr::NULL_PTR) { return new CompareAndExchangePNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), adr_type(), bottom_type(), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahCompareAndExchangeNNode : public CompareAndExchangeNNode { public: ShenandoahCompareAndExchangeNNode(Node *c, Node *mem, Node *adr, Node *val, Node *ex, const TypePtr* at, const Type* t, MemNode::MemOrd mem_ord) : CompareAndExchangeNNode(c, mem, adr, val, ex, at, t, mem_ord) { } virtual Node *Ideal(PhaseGVN *phase, bool can_reshape) { if (in(ExpectedIn) != NULL && phase->type(in(ExpectedIn)) == TypeNarrowOop::NULL_PTR) { return new CompareAndExchangeNNode(in(MemNode::Control), in(MemNode::Memory), in(MemNode::Address), in(MemNode::ValueIn), in(ExpectedIn), adr_type(), bottom_type(), order()); } return NULL; } virtual int Opcode() const; }; class ShenandoahLoadReferenceBarrierNode : public Node { public: enum { Control, ValueIn }; enum Strength { NONE, WEAK, STRONG, NA }; ShenandoahLoadReferenceBarrierNode(Node* ctrl, Node* val); virtual int Opcode() const; virtual const Type* bottom_type() const; virtual const Type* Value(PhaseGVN* phase) const; virtual const class TypePtr *adr_type() const { return TypeOopPtr::BOTTOM; } virtual uint match_edge(uint idx) const { return idx >= ValueIn; } virtual uint ideal_reg() const { return Op_RegP; } virtual Node* Identity(PhaseGVN* phase); uint size_of() const { return sizeof(*this); } Strength get_barrier_strength(); CallStaticJavaNode* pin_and_expand_null_check(PhaseIterGVN& igvn); private: bool needs_barrier(PhaseGVN* phase, Node* n); bool needs_barrier_impl(PhaseGVN* phase, Node* n, Unique_Node_List &visited); }; #endif // SHARE_GC_SHENANDOAH_C2_SHENANDOAHSUPPORT_HPP
39.465909
180
0.730972
siweilxy
35f03bdb085df89844b085d19bd6ee4d3a630d3e
255
cpp
C++
UVa 10636 - Hello World/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2020-11-24T03:17:21.000Z
2020-11-24T03:17:21.000Z
UVa 10636 - Hello World/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
null
null
null
UVa 10636 - Hello World/sample/sol.cpp
tadvi/uva
0ac0cbdf593879b4fb02a3efc09adbb031cb47d5
[ "MIT" ]
1
2021-04-11T16:22:31.000Z
2021-04-11T16:22:31.000Z
#include <cstdio> #include <cmath> #include <algorithm> using namespace std; int main() { int n, cnt = 1; while (scanf("%d", &n), n >= 0) { printf("Case %d: %.0lf\n", cnt++, max(0.0, ceil(log(n) / log(2)))); } return 0; }
13.421053
75
0.505882
tadvi
35f0d56503f8e1476114f760b630a85adb39b170
11,127
cpp
C++
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
1
2019-05-20T11:52:35.000Z
2019-05-20T11:52:35.000Z
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
null
null
null
volante.cpp
AraragiRukasu/interfazLAC
abd0f3e98e659fbe0459c29afad3972197f864c7
[ "BSD-3-Clause" ]
null
null
null
#include "volante.h" #include "ui_volante.h" #include <QMessageBox> #include <QtCore> #include <QtGui> #include <QTimer> #include "PC.h" #include <QtMath> #include "assert.h" //Esta ventana es homologa a la del generador (pero mas simple), referirse //a aquella para entender el funcionamiento de esta volante::volante(QWidget *parent) : QDialog(parent), ui(new Ui::volante) { ui->setupUi(this); this->setWindowTitle("Volante de Inercia"); this->setWindowFlags(Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint); mw = qobject_cast<MainWindow*>(this->parent()); send_queries = true; //Inicializacion de Labels ui->label_vol_io->setText("----"); ui->label_vol_vo->setText("----"); ui->label_vol_ibat->setText("----"); ui->label_vol_po->setText("----"); ui->label_vol_vel->setText("----"); ui->label_vol_tor->setText("----"); ui->label_vol_ener->setText("----"); blockAllSpinSignals(true); ui->spin_vol_isd_ref->setMinimum(LACAN_VAR_VOL_ISD_MIN); ui->spin_vol_isd_ref->setMaximum(LACAN_VAR_VOL_ISD_MAX); ui->spin_vol_sbyspeed_ref->setMinimum(LACAN_VAR_VOL_STANDBY_W_MIN); ui->spin_vol_sbyspeed_ref->setMaximum(LACAN_VAR_VOL_STANDBY_W_MAX); //TIMER ENCARGADO DE REFRESCAR LOS VALORES Y DE ENVIAR LAS NUEVAS CONSULTAS time_2sec = new QTimer(); connect(time_2sec, SIGNAL(timeout()), this, SLOT(timer_handler())); time_2sec->start(2000); //velocidad de refresco (en ms) send_qry_variables(); //envio las primeras consultas send_qry_references(); referenceChanged=false; editHotKey = new QShortcut(QKeySequence(tr("Ctrl+E", "Edit")), this); connect(editHotKey, SIGNAL(activated()), this, SLOT(changeEditState())); ui->label_edit->setDisabled(true); //INICIALIZAR ICONO DEL BOTON STOP QPixmap pixmap(":/Imagenes/stop_normal.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } volante::~volante() { delete ui; disconnect(editHotKey, SIGNAL(activated()), this, SLOT(changeEditState())); delete editHotKey; disconnect(time_2sec, SIGNAL(timeout()), this, SLOT(timer_handler())); delete time_2sec; } void volante::timer_handler(){ static uint count = 0; if(mw->device_is_connected(LACAN_ID_VOLANTE)){ if(send_queries){ ui->pushButton_start->blockSignals(false); refresh_values(); //actualiza los valores de la pantalla count++; send_qry_variables(); if(count%5==0 || referenceChanged){ send_qry_references(); referenceChanged = false; count = 0; } } } else{ //si no esta conectado, se cierra la pantalla QMessageBox::StandardButton reply; reply = QMessageBox::warning(this,"Conexion perdida","El volante se ha desconectado de la red. Esta ventana se cerrara inmediatamente"); if(reply){ this->close(); } } } void volante::VOLpost_Handler(LACAN_MSG msg){ recibed_val.var_char[0]=msg.BYTE2; recibed_val.var_char[1]=msg.BYTE3; recibed_val.var_char[2]=msg.BYTE4; recibed_val.var_char[3]=msg.BYTE5; switch (msg.BYTE1) { case LACAN_VAR_VO_INST: vol_vo = recibed_val.var_float; break; case LACAN_VAR_IO_INST: vol_io = recibed_val.var_float; break; case LACAN_VAR_PO_INST: vol_po = recibed_val.var_float; break; case LACAN_VAR_W_INST: vol_vel = recibed_val.var_float; break; case LACAN_VAR_TORQ_INST: vol_tor = recibed_val.var_float; break; case LACAN_VAR_I_BAT_INST: vol_ibat = recibed_val.var_float; break; case LACAN_VAR_STANDBY_W_SETP: standby_ref=recibed_val.var_float; break; case LACAN_VAR_ISD_SETP: id_ref=recibed_val.var_float; break; case LACAN_VAR_MOD: actual_mode=recibed_val.var_char[0]; break; default: break; } refresh_values(); } void volante::send_qry_variables(){ mw->LACAN_Query(LACAN_VAR_VO_INST,false,dest); //vol_vo mw->LACAN_Query(LACAN_VAR_IO_INST,false,dest); //vol_io mw->LACAN_Query(LACAN_VAR_I_BAT_INST,false,dest); //vol_ibat mw->LACAN_Query(LACAN_VAR_W_INST,false,dest); //vol_vel mw->LACAN_Query(LACAN_VAR_TORQ_INST,false,dest); //vol_ibat mw->LACAN_Query(LACAN_VAR_PO_INST,false,dest); //vol_po mw->LACAN_Query(LACAN_VAR_MOD,false,dest); //modo } void volante::send_qry_references(){ mw->LACAN_Query(LACAN_VAR_ISD_SETP,false,dest); //id_ref mw->LACAN_Query(LACAN_VAR_STANDBY_W_SETP,false,dest); //standby_ref } void volante::refresh_values(){ if(double(id_ref) > refValue) ui->spin_vol_isd_ref->setEnabled(true); if(double(standby_ref) > refValue) ui->spin_vol_sbyspeed_ref->setEnabled(true); ui->spin_vol_sbyspeed_ref->setValue(double(standby_ref)); ui->spin_vol_isd_ref->setValue(double(id_ref)); double speedrev = double(vol_vel)*(2*M_PI/60); vol_ener = float(0.5 * J * speedrev * speedrev); if(double(vol_vo)>refValue) ui->label_vol_vo->setText(QString::number(double(vol_vo),'f',2)); if(double(vol_io)>refValue) ui->label_vol_io->setText(QString::number(double(vol_io),'f',2)); if(double(vol_ibat)>refValue) ui->label_vol_ibat->setText(QString::number(double(vol_ibat),'f',2)); if(double(vol_po)>refValue) ui->label_vol_po->setText(QString::number(double(vol_po),'f',2)); if(double(vol_tor)>refValue) ui->label_vol_tor->setText(QString::number(double(vol_tor),'f',2)); if(double(vol_vel)>refValue) ui->label_vol_vel->setText(QString::number(double(vol_vel),'f',2)); if(double(vol_ener)>refValue) ui->label_vol_ener->setText(QString::number(double(vol_ener),'f',2)); if(double(actual_mode)>refValue){ switch(actual_mode){ case LACAN_VAR_MOD_PREARRANQUE: ui->label_modo->setText("PREARRANQUE"); break; case LACAN_VAR_MOD_INICIO: ui->label_modo->setText("INICIO"); break; case LACAN_VAR_MOD_ARRANQUE: ui->label_modo->setText("ARRANQUE"); break; case LACAN_VAR_MOD_COMPENSACION: ui->label_modo->setText("CMPENSACION"); break; case LACAN_VAR_MOD_LIMITACION: ui->label_modo->setText("LIMITACION"); break; case LACAN_VAR_MOD_APAGADO: ui->label_modo->setText("APAGADO"); break; case LACAN_VAR_MOD_RECUPERACION: ui->label_modo->setText("RECUPERACION"); break; case LACAN_VAR_MOD_PROTEGIDO: ui->label_modo->setText("PROTEGIDO"); break; default: ui->label_modo->setText("DESCONCIDO"); } } } void volante::on_pushButton_start_clicked() { cmd=LACAN_CMD_START; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_stop_clicked() { cmd=LACAN_CMD_STOP; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_stop_released() { QPixmap pixmap(":/Imagenes/stop_normal.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } void volante::on_pushButton_stop_pressed() { QPixmap pixmap(":/Imagenes/stop_press.png"); QIcon ButtonIcon(pixmap); ui->pushButton_stop->setIcon(ButtonIcon); } void volante::on_pushButton_clicked() { cmd=LACAN_CMD_ENABLE; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_shutdown_clicked() { cmd=LACAN_CMD_SHUTDOWN; mw->LACAN_Do(cmd,false,dest); assert(mw->msg_ack.back()); connect(&(mw->msg_ack.back()->ack_timer),SIGNAL(timeout()), mw, SLOT(verificarACK())); mw->agregar_log_sent(); } void volante::on_pushButton_comandar_clicked() { Comandar *comwin = new Comandar(mw,dest); comwin->setAttribute(Qt::WA_DeleteOnClose); comwin->setModal(true); comwin->show(); } void volante::closeEvent(QCloseEvent *e){ time_2sec->stop(); emit volWindowsClosed(); QDialog::closeEvent(e); } void volante::processEditingFinished(QDoubleSpinBox* spin, uint16_t var, float prevValue) { blockAllSpinSignals(true); spin->clearFocus(); data_can data; float value = float(spin->value()); QMessageBox::StandardButton reply; QString str = "El valor a enviar es: "; str.append(QString::number(double(value))); str.append(". Confirma que desea enviar este valor?"); reply=QMessageBox::question(this,"Valor a enviar",str,QMessageBox::Yes|QMessageBox::No); if(reply==QMessageBox::Yes){ data.var_float = value; //si esta seleccionado algo que no sea modo, manda el valor de spin mw->LACAN_Set(var, data, 1, dest); mw->agregar_log_sent(); referenceChanged = true; } blockAllSpinSignals(false); spin->setValue(double(prevValue)); ui->edit_checkBox->setCheckState(Qt::CheckState::Unchecked); } void volante::blockAllSpinSignals(bool b){ ui->spin_vol_isd_ref->blockSignals(b); ui->spin_vol_sbyspeed_ref->blockSignals(b); } void volante::on_spin_vol_sbyspeed_ref_editingFinished() { processEditingFinished(ui->spin_vol_sbyspeed_ref, LACAN_VAR_STANDBY_W_SETP, standby_ref); } void volante::on_spin_vol_isd_ref_editingFinished() { processEditingFinished(ui->spin_vol_isd_ref, LACAN_VAR_ISD_SETP, id_ref); } void volante::on_edit_checkBox_stateChanged(int check) { if(check){ send_queries = false; ui->pushButton_start->blockSignals(true); ui->pushButton_comandar->setDisabled(true); ui->pushButton_start->setDisabled(true); ui->pushButton_stop->setDisabled(true); ui->pushButton_shutdown->setDisabled(true); ui->spin_vol_sbyspeed_ref->clearFocus(); ui->spin_vol_isd_ref->clearFocus(); blockAllSpinSignals(false); ui->spin_vol_sbyspeed_ref->setReadOnly(false); ui->spin_vol_isd_ref->setReadOnly(false); ui->label_edit->setEnabled(true); }else{ send_queries = true; ui->pushButton_comandar->setDisabled(false); ui->pushButton_start->setDisabled(false); ui->pushButton_stop->setDisabled(false); ui->pushButton_shutdown->setDisabled(false); blockAllSpinSignals(true); ui->spin_vol_sbyspeed_ref->setReadOnly(true); ui->spin_vol_isd_ref->setReadOnly(true); ui->label_edit->setDisabled(true); } } void volante::changeEditState() { ui->edit_checkBox->toggle(); }
30.652893
144
0.662892
AraragiRukasu
35f330bb55218bba78fc170664996e07040cac1c
1,462
cpp
C++
tests/code/registry.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
72
2016-02-04T00:41:02.000Z
2022-03-18T18:10:34.000Z
tests/code/registry.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
74
2016-01-11T16:04:46.000Z
2021-11-18T16:36:11.000Z
tests/code/registry.cpp
genisysram/odil
e6b12df698ce452f9c5d86858e896e9b6d28cdf0
[ "CECILL-B" ]
23
2016-04-27T07:14:56.000Z
2021-09-28T21:59:31.000Z
#define BOOST_TEST_MODULE registry #include <boost/test/unit_test.hpp> #include "odil/registry.h" #include "odil/Tag.h" BOOST_AUTO_TEST_CASE(PublicDictionary) { auto const iterator = odil::registry::public_dictionary.find( odil::registry::PatientName); BOOST_REQUIRE(iterator != odil::registry::public_dictionary.end()); auto const & entry = iterator->second; BOOST_REQUIRE_EQUAL(entry.name, "Patient's Name"); BOOST_REQUIRE_EQUAL(entry.keyword, "PatientName"); BOOST_REQUIRE_EQUAL(entry.vr, "PN"); BOOST_REQUIRE_EQUAL(entry.vm, "1"); } BOOST_AUTO_TEST_CASE(PublicDictionaryRepeatingGroup) { auto const iterator = odil::registry::public_dictionary.find( std::string("60xx0010")); BOOST_REQUIRE(iterator != odil::registry::public_dictionary.end()); auto const & entry = iterator->second; BOOST_REQUIRE_EQUAL(entry.name, "Overlay Rows"); BOOST_REQUIRE_EQUAL(entry.keyword, "OverlayRows"); BOOST_REQUIRE_EQUAL(entry.vr, "US"); BOOST_REQUIRE_EQUAL(entry.vm, "1"); } BOOST_AUTO_TEST_CASE(UIDsDictionary) { auto const iterator = odil::registry::uids_dictionary.find( odil::registry::MRImageStorage); BOOST_REQUIRE(iterator != odil::registry::uids_dictionary.end()); auto const & entry = iterator->second; BOOST_REQUIRE_EQUAL(entry.name, "MR Image Storage"); BOOST_REQUIRE_EQUAL(entry.keyword, "MRImageStorage"); BOOST_REQUIRE_EQUAL(entry.type, "SOP Class"); }
35.658537
71
0.728454
genisysram
35f78f425e52fe462ade87bf2df6da28376329b8
6,076
hpp
C++
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_Buff_GrabbedByBeam_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_Buff_GrabbedByBeam_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Buff_GrabbedByBeam.Buff_GrabbedByBeam_C // 0x0065 (0x09C5 - 0x0960) class ABuff_GrabbedByBeam_C : public ABuff_Base_C { public: float maxDistanceToApplyImpulse; // 0x0960(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxImpulseToInstigator; // 0x0964(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minImpulseToInstigator; // 0x0968(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minDistanceToApplyImpulse; // 0x096C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxAdditionalMultiplier; // 0x0970(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minAdditionalMultiplier; // 0x0974(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxWeightForCalculationns; // 0x0978(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minWeightForCalculations; // 0x097C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float logDeviation; // 0x0980(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float minProgressDeltaBasedOnDistance; // 0x0984(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressDeltaBasedOnDistance; // 0x0988(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgress; // 0x098C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float RequiredLookDirDotToCapture; // 0x0990(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressMultiplierForMinWeight; // 0x0994(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool bIsInitialized; // 0x0998(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x3]; // 0x0999(0x0003) MISSED OFFSET float CurrentBeamProgress; // 0x099C(0x0004) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float additionalMultiplier; // 0x09A0(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxProgressMultiplierForMaxWeight; // 0x09A4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float maxAngleForCalculations; // 0x09A8(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FVector ParentSkiff_CurrentBeamStartLoc; // 0x09AC(0x000C) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) struct FVector ParentSkiff_CurrentBeamEndLoc; // 0x09B8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) TEnumAsByte<E_HoverSkiffBeamState> ParentSkiff_CurrentBeamState; // 0x09C4(0x0001) (Edit, BlueprintVisible, ZeroConstructor, Transient, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Buff_GrabbedByBeam.Buff_GrabbedByBeam_C"); return ptr; } void ReceiveSkiffVars(const struct FVector& BeamStartLoc, const struct FVector& BeamEndLoc, TEnumAsByte<E_HoverSkiffBeamState> BeamState); void GetBeamCapturePercent(float* Percent); float GetOwnerDragWeight(); void GetMaxProgress(float* maxProgress); void Calculate_Progress(float timeDelta, float* NewProgress); void CalculateBeamProgressDelta(float timeDelta, float* ProgressDelta, bool* bInvalidProgress); void InitializeBuff(float MaxBeamLength); void BuffTickServer(float* DeltaTime); void UserConstructionScript(); void ExecuteUbergraph_Buff_GrabbedByBeam(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
85.577465
219
0.574062
2bite
35f7bedb4f686ef56aa86f604fc083e183e6ebaa
120
cpp
C++
src/arcstorage-ui/atreewidgetitem.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
null
null
null
src/arcstorage-ui/atreewidgetitem.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
null
null
null
src/arcstorage-ui/atreewidgetitem.cpp
Teemperor/arc-gui-clients
f9fa8396ac03eae3090f597d77766e3b00a44b31
[ "Apache-2.0" ]
1
2022-03-24T10:11:37.000Z
2022-03-24T10:11:37.000Z
#include "atreewidgetitem.h" ATreeWidgetItem::ATreeWidgetItem(QObject *parent) : QTreeWidgetItem(parent) { }
17.142857
52
0.725
Teemperor
35f7c327f9526a360f434307bc77d17a812dd57b
2,488
cc
C++
backend/inst-sched/local-list-eb/src/lib/dep.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
backend/inst-sched/local-list-eb/src/lib/dep.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
backend/inst-sched/local-list-eb/src/lib/dep.cc
obs145628/cle
4a4a18b2ab5a6fbf26629f6845147541edabd7c9
[ "MIT" ]
null
null
null
#include "dep.hh" #include <algorithm> #include <cassert> #include "ebb-view.hh" namespace { constexpr std::size_t INS_NONE = -1; std::string get_label(const isa::Ins &ins) { if (ins.args().size() == 1) return ins.args()[0]; return ins.args()[0] + ":" + ins.args()[1].substr(1); } std::size_t find_def_of(const EbbView &ebb, const std::string &reg, std::size_t ins_idx) { std::size_t first_idx = 0; for (std::size_t i = ins_idx - 1; i < ins_idx && i >= first_idx; --i) { isa::Ins ins(ebb.ctx(), ebb[i]); auto defs = ins.args_defs(); if (defs.size() == 1 && defs[0] == reg) return i; } return INS_NONE; } bool ins_use_reg(const EbbView &ebb, const std::string &reg, std::size_t ins_idx) { isa::Ins ins(ebb.ctx(), ebb[ins_idx]); auto uses = ins.args_uses(); return std::find(uses.begin(), uses.end(), reg) != uses.end(); } } // namespace Digraph make_dep_graph(const EbPaths::path_t &path) { EbbView ebb(path); Digraph g(ebb.size()); for (std::size_t ins_idx = 0; ins_idx < ebb.size(); ++ins_idx) { isa::Ins ins(ebb.ctx(), ebb[ins_idx]); g.labels_set_vertex_name(ins_idx, get_label(ins)); // Some searches for dependencies can start at bb begin // Because of the dependency between prev bb term and other ins std::size_t bb_beg_idx = ebb.offset_of(ebb.bb_of(ins_idx)); for (auto r : ins.args_uses()) { // Find def of all uses auto def = find_def_of(ebb, r, ins_idx); if (def != INS_NONE) { assert(def < ins_idx); g.add_edge(def, ins_idx); } } // x before y and y def is used in x (antidependant) auto defs = ins.args_defs(); if (defs.size() == 1) for (std::size_t prev = 0; prev < ins_idx; ++prev) if (ins_use_reg(ebb, defs.front(), prev)) g.add_edge(prev, ins_idx); // find store before a load if (ins.opname() == "load") for (std::size_t prev = bb_beg_idx; prev < ins_idx; ++prev) if (ebb[prev][0] == "store") g.add_edge(prev, ins_idx); // find any before last terminal if (ins_idx + 1 == ebb.size()) for (std::size_t prev = 0; prev < ins_idx; ++prev) if (g.succs_count(prev) == 0) g.add_edge(prev, ins_idx); // if ins has no preds, attach it to prev terminal bb // (also check if not first bb) if (bb_beg_idx && g.preds_count(ins_idx) == 0) g.add_edge(bb_beg_idx - 1, ins_idx); } return g; }
28.272727
73
0.59365
obs145628
35fa0fa040dadf8a7258780224d795dd69d2af02
3,008
cpp
C++
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
modules/task_2/belyaev_i_readers_writers/main.cpp
Gurgen-Arm/pp_2021_autumn
ad549e49d765612c4544f34b04c9eb9432ac0dc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2021 Belyaev Ilya #include <gtest/gtest.h> #include "./readers_writers.h" #include <gtest-mpi-listener.hpp> TEST(r_w_MPI, no_one) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, 1); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, equally) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank % 2 == 0) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, only_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { writers(rank); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, only_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { readers(rank); } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, one_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 1) { writers(rank); } else { readers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, two_w) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 2 || rank == 1) { writers(rank); } else { readers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, One_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 1) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } TEST(r_w_MPI, two_r) { int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); if (rank == 0) { storage(rank, size); } else { if (rank == 2 || rank == 1) { readers(rank); } else { writers(rank); } } MPI_Barrier(MPI_COMM_WORLD); ASSERT_NO_THROW(); } int main(int argc, char** argv) { ::testing::InitGoogleTest(&argc, argv); MPI_Init(&argc, &argv); std::srand(std::time(nullptr)); ::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment); ::testing::TestEventListeners& listeners = ::testing::UnitTest::GetInstance()->listeners(); listeners.Release(listeners.default_result_printer()); listeners.Release(listeners.default_xml_generator()); listeners.Append(new GTestMPIListener::MPIMinimalistPrinter); return RUN_ALL_TESTS(); }
18.918239
76
0.636636
Gurgen-Arm
35fa77ab7dcf25fb1f09a7989d6438fb113416f6
3,852
cpp
C++
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
2
2015-03-20T21:11:16.000Z
2020-01-20T08:05:41.000Z
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
src/type_lookup_table.cpp
syoummer/boost.actor
58f35499bac8871b8f5b0b024246a467b63c6fb0
[ "BSL-1.0" ]
null
null
null
/******************************************************************************\ * * * ____ _ _ _ * * | __ ) ___ ___ ___| |_ / \ ___| |_ ___ _ __ * * | _ \ / _ \ / _ \/ __| __| / _ \ / __| __/ _ \| '__| * * | |_) | (_) | (_) \__ \ |_ _ / ___ \ (__| || (_) | | * * |____/ \___/ \___/|___/\__(_)_/ \_\___|\__\___/|_| * * * * * * * * Copyright (C) 2011 - 2014 * * Dominik Charousset <dominik.charousset@haw-hamburg.de> * * * * Distributed under the Boost Software License, Version 1.0. See * * accompanying file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt * \******************************************************************************/ #include <algorithm> #include "boost/actor/singletons.hpp" #include "boost/actor/type_lookup_table.hpp" #include "boost/actor/detail/uniform_type_info_map.hpp" namespace boost { namespace actor { type_lookup_table::type_lookup_table() { auto uti_map = get_uniform_type_info_map(); auto get = [=](const char* cstr) { return uti_map->by_uniform_name(cstr); }; emplace(1, get("@<>+@atom")); emplace(2, get("@<>+@atom+@u32")); emplace(3, get("@<>+@atom+@proc")); emplace(4, get("@<>+@atom+@proc+@u32")); emplace(5, get("@<>+@atom+@proc+@u32+@u32")); emplace(6, get("@<>+@atom+@actor")); emplace(7, get("@<>+@atom+@u32+@str")); } auto type_lookup_table::by_id(std::uint32_t id) const -> pointer { auto i = find(id); return (i == m_data.end() || i->first != id) ? nullptr : i->second; } auto type_lookup_table::by_name(const std::string& name) const -> pointer { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second->name() == name; }); return (i != e) ? i->second : nullptr; } std::uint32_t type_lookup_table::id_of(const std::string& name) const { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second->name() == name; }); return (i != e) ? i->first : 0; } std::uint32_t type_lookup_table::id_of(pointer uti) const { auto e = m_data.end(); auto i = std::find_if(m_data.begin(), e, [&](const value_type& val) { return val.second == uti; }); return (i != e) ? i->first : 0; } void type_lookup_table::emplace(std::uint32_t id, pointer instance) { BOOST_ACTOR_REQUIRE(instance != nullptr); value_type kvp{id, instance}; auto i = find(id); if (i == m_data.end()) m_data.push_back(std::move(kvp)); else if (i->first == id) throw std::runtime_error("key already defined"); else m_data.insert(i, std::move(kvp)); } auto type_lookup_table::find(std::uint32_t arg) const -> const_iterator { return std::lower_bound(m_data.begin(), m_data.end(), arg, [](const value_type& lhs, std::uint32_t id) { return lhs.first < id; }); } auto type_lookup_table::find(std::uint32_t arg) -> iterator { return std::lower_bound(m_data.begin(), m_data.end(), arg, [](const value_type& lhs, std::uint32_t id) { return lhs.first < id; }); } std::uint32_t type_lookup_table::max_id() const { return m_data.empty() ? 0 : m_data.back().first; } } // namespace actor } // namespace boost
38.138614
108
0.482606
syoummer
35facbd9a9c7e6f5ce5145cf473a1c131a841db0
708
cxx
C++
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
cpp_fund/explicit.cxx
jsrdzhk/algo_snippet
a929f73db1ad14468f12ee45d503cdba8ed12f40
[ "MIT" ]
null
null
null
/* * @title: todo * @author: Rodney Cheung * @date: 2021-07-15 11:20:53 * @last_author: Rodney Cheung * @last_edit_time: 2021-07-15 11:41:04 */ #include "precompiled_headers.h" class SalesData{ private: std::string data; public: explicit SalesData(const std::string& d):data(d){ } explicit operator bool(){ return !data.empty(); } static void output(SalesData salesData){ std::cout<<salesData.data<<std::endl; } }; int main(){ SalesData::output(static_cast<SalesData>(std::string("kask"))); SalesData s(static_cast<SalesData>(std::string("kask"))); if(s){ std::cout<<std::boolalpha<<static_cast<bool>(s)<<std::endl; } }
20.228571
67
0.620056
jsrdzhk
35fc424d216a117737ceaf67217967c836a22f89
778
cpp
C++
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
quick-sort.cpp
zhiwei1988/leetcode_20211220
d158c5ec567381610f4d442d427df7fa035dcd84
[ "MIT" ]
null
null
null
// // Created by zhiwei on 1/6/2022. // #include "playground.h" int Partition(vector<int> &nums, int left, int right) { int pivot = nums[right]; // 每次取最右边的值为锚点 int wall = left; for (int i = left; i < right; i++) { if (nums[i] < pivot) { swap(nums[i], nums[wall]); wall++; } } swap(nums[wall], nums[right]); return wall; } void Helper(vector<int> &nums, int left, int right) { if (left >= right) { return; } int pivot = Partition(nums, left, right); Helper(nums, left, pivot - 1); Helper(nums, pivot + 1, right); } void QuickSort(vector<int> &nums) { Helper(nums, 0, nums.size() - 1); } int main() { vector<int> nums = {3, 2, 1, 4}; QuickSort(nums); return 0; }
16.913043
53
0.537275
zhiwei1988
35ff6451f672fd225ba93b2c849cf5ce598c786a
439
cpp
C++
xfa/fwl/core/cfwl_evtclick.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
38
2015-11-25T02:25:25.000Z
2022-01-04T01:11:15.000Z
xfa/fwl/core/cfwl_evtclick.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
1
2021-02-23T22:36:54.000Z
2021-02-23T22:36:54.000Z
xfa/fwl/core/cfwl_evtclick.cpp
isabella232/pdfium-1
d8f710cedd62c1d28beee15d7dc3d31ddd148437
[ "BSD-3-Clause" ]
13
2016-08-03T02:35:18.000Z
2020-12-17T10:14:04.000Z
// Copyright 2016 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fwl/core/cfwl_evtclick.h" CFWL_EvtClick::CFWL_EvtClick() {} CFWL_EvtClick::~CFWL_EvtClick() {} CFWL_EventType CFWL_EvtClick::GetClassID() const { return CFWL_EventType::Click; }
27.4375
80
0.76082
isabella232
c40066c5064027015912264a6e188cbdf6eec19a
1,128
cpp
C++
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
1,027
2015-01-05T02:52:17.000Z
2022-03-26T22:30:14.000Z
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
312
2015-01-01T08:58:12.000Z
2022-03-31T09:26:55.000Z
common/modifiers.cpp
kirmorozov/PHP-CPP
fde096ca0a23c33c63e7c5f529891e9b679601a1
[ "Apache-2.0" ]
324
2015-01-06T01:57:21.000Z
2022-03-31T14:13:49.000Z
/** * Modifiers.cpp * * In this file an enumeration type is with the possible * member modifiers * * @author Martijn Otto <martijn.otto@copernica.com> * @author Emiel Bruijntjes <emiel.bruijntjes@copernica.com> * * @copyright 2014 Copernica BV */ #include "includes.h" #include <php.h> /** * Set up namespace */ namespace Php { /** * The modifiers are constants */ #if PHP_VERSION_ID >= 70400 const int Static = 0x10; const int Abstract = 0x40; const int Final = 0x20; const int Public = 0x01; const int Protected = 0x02; const int Private = 0x04; const int Const = 0; #else const int Static = 0x01; const int Abstract = 0x02; const int Final = 0x04; const int Public = 0x100; const int Protected = 0x200; const int Private = 0x400; const int Const = 0; #endif /** * Modifiers that are supported for methods and properties */ const int MethodModifiers = Final | Public | Protected | Private | Static; const int PropertyModifiers = Final | Public | Protected | Private | Const | Static; /** * End namespace */ }
22.117647
94
0.643617
kirmorozov
c400796697348853cced91e259f6e266923dac4e
545
cpp
C++
Assignments/Assignment2/18f.cpp
PritishWadhwa/Code-For-Cause-CPP-TA-May-June-2021
be2552476478f83a324407d2af48f3516432f321
[ "CC0-1.0" ]
1
2022-01-03T08:33:01.000Z
2022-01-03T08:33:01.000Z
Assignments/Assignment2/18f.cpp
PritishWadhwa/Code-For-Cause-CPP-TA-May-June-2021
be2552476478f83a324407d2af48f3516432f321
[ "CC0-1.0" ]
null
null
null
Assignments/Assignment2/18f.cpp
PritishWadhwa/Code-For-Cause-CPP-TA-May-June-2021
be2552476478f83a324407d2af48f3516432f321
[ "CC0-1.0" ]
null
null
null
class Solution { public: vector<int> sortedSquares(vector<int>& nums) { int i = 0, j = nums.size() - 1; vector<int> arr; arr.reserve(nums.size()); while (i <= j) { if ((nums[i] * nums[i]) >= (nums[j] * nums[j])) { arr.insert(arr.begin(), nums[i] * nums[i]); i++; } else { arr.insert(arr.begin(), nums[j] * nums[j]); j--; } } return arr; } };
22.708333
59
0.361468
PritishWadhwa
c402043b18d94d4c0494ca395f02ff742d138ad8
8,995
hpp
C++
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
1
2022-03-18T23:56:54.000Z
2022-03-18T23:56:54.000Z
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
null
null
null
lib/strict_variant_0.3/include/strict_variant/variant_dispatch.hpp
garbageslam/libwml
c50bc4595c0c86864cd41dbfa80a522e674e0c2f
[ "WTFPL" ]
null
null
null
// (C) Copyright 2016 Christopher Beck // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <strict_variant/mpl/find_with.hpp> #include <strict_variant/mpl/nonstd_traits.hpp> #include <strict_variant/mpl/std_traits.hpp> #include <strict_variant/mpl/typelist.hpp> #include <strict_variant/mpl/ulist.hpp> #include <strict_variant/variant_fwd.hpp> #include <type_traits> #include <utility> #ifdef STRICT_VARIANT_DEBUG #include <cassert> #define STRICT_VARIANT_ASSERT(X) \ do { \ assert((X)); \ } while (0) #else // STRICT_VARIANT_DEBUG #define STRICT_VARIANT_ASSERT(X) \ do { \ static_cast<void>(X); \ } while (0) #endif // STRICT_VARIANT_DEBUG namespace strict_variant { namespace detail { /*** * Dispatch mechanism: * These two templates are used to dispatch visitor objects to * the variant's storage. The problem that is being solved here is, * how do we actually recover type information from the runtime * value of `m_which`, so that we can call the appropriate overload * of a visitor to the variant. */ /// Function which evaluates a visitor against a variant's internals /// Reinteprets the "storage" as a value of type T or const T, /// then applies the visitor object. #define RESULT_EXPR \ std::forward<Visitor>(v)(std::forward<Storage>(s).template get_value<index>(Internal())) template <unsigned index, typename Internal, typename Storage, typename Visitor> auto visitor_caller(Storage && s, Visitor && v) noexcept(noexcept(RESULT_EXPR)) -> decltype(RESULT_EXPR) { return RESULT_EXPR; } #undef RESULT_EXPR /// Helper which figures out the return type of multiple visitor calls /// It's better for this to be separate of the dispatch mechanism, because /// std::common_type can technically be order dependent. It's confusing if the /// return type can change depending on the dispatch strategy used, and it /// simplifies the dispatch code to only have to implement this once. template <typename Internal, typename Storage, typename Visitor> struct return_typer { #define RESULT_EXPR \ visitor_caller<index, Internal, Storage>(std::forward<Storage>(std::declval<Storage>()), \ std::forward<Visitor>(std::declval<Visitor>())) template <unsigned index> struct at_index { using type = decltype(RESULT_EXPR); }; template <unsigned index> struct noexcept_prop { static constexpr bool value = noexcept(RESULT_EXPR); using type = std::integral_constant<bool, value>; }; #undef RESULT_EXPR }; /// Helper object which dispatches a visitor object to the appropriate /// interpretation of our storage value, based on value of "which". /// /// The solution here is that for each possible value of `which`, we create an /// appropriate function using the above function template, and store them each /// in an array, using parameter pack expansion. (A little 'jump table'.) /// /// Then we dereference the array at index `m_which` and call that function. /// This means we pick out the right function very quickly, but it may not be /// inlined by the compiler even if it is small. template <typename return_t, typename Internal, typename ulist> struct jumptable_dispatch; template <typename return_t, typename Internal, unsigned... Indices> struct jumptable_dispatch<return_t, Internal, mpl::ulist<Indices...>> { template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { using whichCaller = return_t (*)(Storage, Visitor); static whichCaller callers[sizeof...(Indices)] = { &visitor_caller<Indices, Internal, Storage, Visitor>...}; STRICT_VARIANT_ASSERT(which < static_cast<unsigned int>(sizeof...(Indices))); return (*callers[which])(std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; /// Same as the above, but we use a different strategy based on a binary tree, /// and repeated testing of the "which" value. /// /// The idea is that if there are multiple types, we just test if we are looking /// in the first half or the second half, and branch to two different /// instantiations of the binary_search_dispatch object as appropriate. /// /// When arranged this way, the compiler can always inline the visitor calls, /// and so for variants with few types this may be significantly faster. /// /// The "which" value is not changed even as the type list gets smaller, /// instead, the "base" value is increased. template <typename return_t, typename Internal, unsigned int base, unsigned int num_types> struct binary_search_dispatch { static_assert(num_types >= 2, "Something wrong with binary search dispatch"); static constexpr unsigned int half = num_types / 2; template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { if (which < base + half) { return binary_search_dispatch<return_t, Internal, base, half>{}( which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } else { return binary_search_dispatch<return_t, Internal, base + half, num_types - half>{}( which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } } }; template <typename return_t, typename Internal, unsigned int base> struct binary_search_dispatch<return_t, Internal, base, 1u> { template <typename Storage, typename Visitor> return_t operator()(const unsigned int which, Storage && storage, Visitor && visitor) { STRICT_VARIANT_ASSERT(which == base); return visitor_caller<base, Internal, Storage, Visitor>(std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; /// Choose the jumptable dispatch strategy when the number of types is > switch /// point /// choose the binary search dispatch for less than that. /// Tentatively choosing 4 for switch point, potentially 8 is better... ? /// Needs more rigorous benchmarking template <typename Internal, size_t num_types> struct visitor_dispatch { // static constexpr unsigned int switch_point = 4; // Helper which takes the conjunction of a typelist of `std::integral_constant<bool>`. template <typename T> struct conjunction; template <typename... Types> struct conjunction<mpl::TypeList<Types...>> { template <typename T> struct is_false_prop : std::is_same<T, std::integral_constant<bool, false>> {}; static constexpr bool value = !mpl::Find_Any<is_false_prop, Types...>::value; }; // Helper which figures out return type and noexcept status, for given storage and visitor template <typename Storage, typename Visitor> struct call_helper { using rtyper = return_typer<Internal, Storage, Visitor>; using indices = mpl::count_t<num_types>; static constexpr bool noexcept_value = conjunction<mpl::ulist_map_t<rtyper::template noexcept_prop, indices>>::value; using return_type = typename mpl::typelist_fwd<mpl::common_return_type_t, mpl::ulist_map_t<rtyper::template at_index, indices>>::type; }; // Invoke the actual dispatcher template <typename Storage, typename Visitor> auto operator()(const unsigned int which, Storage && storage, Visitor && visitor) noexcept(call_helper<Storage, Visitor>::noexcept_value) -> typename call_helper<Storage, Visitor>::return_type { using return_t = typename call_helper<Storage, Visitor>::return_type; // using chosen_dispatch_t = jumptable_dispatch<return_t, Internal, mpl::count_t<num_types>>; // using chosen_dispatch_t = // typename std::conditional<(num_types > switch_point), // jumptable_dispatch<return_t, Internal, mpl::count_t<num_types>>, // binary_search_dispatch<return_t, Internal, 0, // num_types>>::type; using chosen_dispatch_t = binary_search_dispatch<return_t, Internal, 0, num_types>; return chosen_dispatch_t{}(which, std::forward<Storage>(storage), std::forward<Visitor>(visitor)); } }; } // end namespace detail } // end namespace strict_variant #undef STRICT_VARIANT_ASSERT
39.800885
100
0.662813
garbageslam
c403d60bd8b063114bf2ade736b18e9cdcfbec4f
3,495
hpp
C++
ios/Pods/boost-for-react-native/boost/geometry/geometries/adapted/boost_polygon/polygon.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
8,805
2015-11-03T00:52:29.000Z
2022-03-29T22:30:03.000Z
ios/Pods/boost-for-react-native/boost/geometry/geometries/adapted/boost_polygon/polygon.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
14,694
2015-02-24T15:13:42.000Z
2022-03-31T13:16:45.000Z
ios/Pods/boost-for-react-native/boost/geometry/geometries/adapted/boost_polygon/polygon.hpp
rudylee/expo
b3e65a7a5b205f14a3eb6cd6fa8d13c8d663b1cc
[ "Apache-2.0", "MIT" ]
1,329
2015-11-03T20:25:51.000Z
2022-03-31T18:10:38.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2010-2012 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP #define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP // Adapts Geometries from Boost.Polygon for usage in Boost.Geometry // boost::polygon::polygon_with_holes_data -> boost::geometry::polygon #include <boost/polygon/polygon.hpp> #include <boost/geometry/core/tags.hpp> #include <boost/geometry/core/ring_type.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/geometries/adapted/boost_polygon/ring_proxy.hpp> #include <boost/geometry/geometries/adapted/boost_polygon/hole_iterator.hpp> #include <boost/geometry/geometries/adapted/boost_polygon/holes_proxy.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS namespace traits { template <typename CoordinateType> struct tag<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef polygon_tag type; }; template <typename CoordinateType> struct ring_const_type<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef adapt::bp::ring_proxy<boost::polygon::polygon_with_holes_data<CoordinateType> const> type; }; template <typename CoordinateType> struct ring_mutable_type<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef adapt::bp::ring_proxy<boost::polygon::polygon_with_holes_data<CoordinateType> > type; }; template <typename CoordinateType> struct interior_const_type<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef adapt::bp::holes_proxy<boost::polygon::polygon_with_holes_data<CoordinateType> const> type; }; template <typename CoordinateType> struct interior_mutable_type<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef adapt::bp::holes_proxy<boost::polygon::polygon_with_holes_data<CoordinateType> > type; }; template <typename CoordinateType> struct exterior_ring<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef boost::polygon::polygon_with_holes_data<CoordinateType> polygon_type; typedef adapt::bp::ring_proxy<polygon_type> proxy; typedef adapt::bp::ring_proxy<polygon_type const> const_proxy; static inline proxy get(polygon_type& p) { return proxy(p); } static inline const_proxy get(polygon_type const& p) { return const_proxy(p); } }; template <typename CoordinateType> struct interior_rings<boost::polygon::polygon_with_holes_data<CoordinateType> > { typedef boost::polygon::polygon_with_holes_data<CoordinateType> polygon_type; typedef adapt::bp::holes_proxy<polygon_type> proxy; typedef adapt::bp::holes_proxy<polygon_type const> const_proxy; static inline proxy get(polygon_type& p) { return proxy(p); } static inline const_proxy get(polygon_type const& p) { return const_proxy(p); } }; } // namespace traits #endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS }} // namespace boost::geometry #endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_BOOST_POLYGON_POLYGON_HPP
31.205357
104
0.75794
rudylee