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
c1eb064191533e5c5cc156e350e664c2772c8c64
297
hpp
C++
hiro/reference/popup-menu.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
hiro/reference/popup-menu.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
hiro/reference/popup-menu.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
namespace phoenix { struct pPopupMenu : public pObject { PopupMenu& popupMenu; void append(Action& action); void remove(Action& action); void setVisible(); pPopupMenu(PopupMenu& popupMenu) : pObject(popupMenu), popupMenu(popupMenu) {} void constructor(); void destructor(); }; }
18.5625
80
0.713805
mp-lee
c1eb0c0f4b9c7f7d610f56c1ff3fd0c93f7860fe
1,270
cpp
C++
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
2
2018-11-08T05:57:22.000Z
2018-11-08T05:57:27.000Z
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
// simple dp #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define fi first #define se second #define pb push_back #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", 1.0*clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector<string> vs; const int INF = 1e9; const int MAXN = 500 + 9; const int MOD = 1e9 + 7; bool used[MAXN]; int n, m; ll dp[MAXN][MAXN]; void precalc() { for(int i = 1; i < MAXN; i++) { dp[i][0] = dp[0][i] = 1; } for(int i = 1; i < MAXN; i++) { for(int j = 1; j < MAXN; j++) { dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD; } } } void solve() { cin >> n >> m; cout << dp[n][m] << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else //freopen("xxx.in", "r", stdin); //freopen("xxx.out", "w", stdout); #endif precalc(); int t; cin >> t; while(t--) { solve(); } return 0; }
19.84375
91
0.549606
Zovube
c1ed592b965e247d6105e416c0e74d888d2993f8
17,878
cc
C++
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
10
2021-05-25T17:43:04.000Z
2022-03-08T10:46:09.000Z
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
1,056
2019-12-15T01:20:31.000Z
2022-02-10T02:06:28.000Z
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
6
2016-09-07T04:00:15.000Z
2022-01-12T01:47:38.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/sparse_fill_empty_rows_op.h" #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRows<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, const Tensor& default_value_t, const Tensor& indices_t, const Tensor& values_t, const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done) { (void)done; // Unused (only used in GPU implementation) const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<Tindex>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<Tindex>(); const Tindex N = indices_t.shape().dim_size(0); const Tindex dense_rows = dense_shape(0); bool* empty_row_indicator = nullptr; if (context->output_required(kEmptyRowIndicatorOutput)) { Tensor* empty_row_indicator_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); empty_row_indicator = empty_row_indicator_t->vec<bool>().data(); } Tindex* reverse_index_map = nullptr; if (context->output_required(kReverseIndexMapOutput)) { Tensor* reverse_index_map_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output( kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); reverse_index_map = reverse_index_map_t->vec<Tindex>().data(); } int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { if (N != 0) { return errors::InvalidArgument( "Received SparseTensor with dense_shape[0] = 0 but " "indices.shape[0] = ", N); } Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return Status::OK(); } bool rows_are_ordered = true; Tindex last_indices_row = 0; std::vector<Tindex> csr_offset(dense_rows, 0); for (int i = 0; i < N; ++i) { const Tindex row = indices(i, 0); if (row < 0 || row >= dense_rows) { return errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows); } ++csr_offset[row]; rows_are_ordered = rows_are_ordered & (row >= last_indices_row); last_indices_row = row; } bool all_rows_full = true; for (int row = 0; row < dense_rows; ++row) { // csr_offset here describes the number of elements in this dense row bool row_empty = (csr_offset[row] == 0); if (empty_row_indicator) { empty_row_indicator[row] = row_empty; } all_rows_full = all_rows_full & !row_empty; // In filled version, each row has at least one element. csr_offset[row] = std::max(csr_offset[row], Tindex{1}); // Update csr_offset to represent the number of elements up to and // including dense_row + 1: // csr_offset(0) == #{elements of row 0} // csr_offset(1) == #{elements of row 1} + #{elements of row 0} // .. // csr_offset(i) == starting index for elements in row i + 1. if (row > 0) { csr_offset[row] += csr_offset[row - 1]; } } if (all_rows_full && rows_are_ordered) { context->set_output(kOutputIndicesOutput, indices_t); context->set_output(kOutputValuesOutput, values_t); if (reverse_index_map) { for (Tindex i = 0; i < N; ++i) { reverse_index_map[i] = i; } } } else { Tensor* output_indices_t; const Tindex N_full = csr_offset[dense_rows - 1]; TensorShape output_indices_shape({N_full, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<Tindex>(); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); std::vector<Tindex> filled_count(dense_rows, 0); // Fill in values for rows that are not missing for (Tindex i = 0; i < N; ++i) { const Tindex row = indices(i, 0); Tindex& offset = filled_count[row]; const Tindex output_i = ((row == 0) ? 0 : csr_offset[row - 1]) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. if (reverse_index_map) { reverse_index_map[i] = output_i; } } // Fill in values for rows that are missing for (Tindex row = 0; row < dense_rows; ++row) { const Tindex row_count = filled_count[row]; if (row_count == 0) { // We haven't filled this row const Tindex starting_index = (row == 0) ? 0 : csr_offset[row - 1]; // Remaining index values were set to zero already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; for (Tindex col = 1; col < rank; ++col) { output_indices(starting_index, col) = 0; } output_values(starting_index) = default_value; } } } return Status::OK(); } }; } // namespace functor namespace { template <typename Device, typename T, typename Tindex> void SparseFillEmptyRowsOpImpl(OpKernelContext* context, AsyncOpKernel::DoneCallback done = nullptr) { // Note that setting this empty lambda as the default parameter value directly // can cause strange compiler/linker errors, so we do it like this instead. if (!done) { done = [] {}; } const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString()), done); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString()), done); // TODO(ebrevdo): add shape checks between values, indices, // Also add check that dense rank > 0. OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0, errors::InvalidArgument("Dense shape cannot be empty."), done); using FunctorType = functor::SparseFillEmptyRows<Device, T, Tindex>; OP_REQUIRES_OK_ASYNC(context, FunctorType()(context, default_value_t, indices_t, values_t, dense_shape_t, done), done); } } // namespace template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { SparseFillEmptyRowsOpImpl<Device, T, Tindex>(context); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_##D) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_ALL_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // The GPU implementation is async because it requires waiting for a // host->device memcpy before the output is allocated (similar to // SegmentSumGPUOp). template <typename T, typename Tindex> class SparseFillEmptyRowsGPUOp : public AsyncOpKernel { public: explicit SparseFillEmptyRowsGPUOp(OpKernelConstruction* context) : AsyncOpKernel(context) {} void ComputeAsync(OpKernelContext* context, DoneCallback done) override { SparseFillEmptyRowsOpImpl<GPUDevice, T, Tindex>(context, done); } }; #define REGISTER_KERNELS(T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_GPU) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGPUOp<T, Tindex>) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRows<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, const Tensor& default_value_t, \ const Tensor& indices_t, const Tensor& values_t, \ const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done); \ extern template struct SparseFillEmptyRows<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_POD_TYPES(DECLARE_GPU_SPEC_INT64) #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_KERNELS_TINDEX(T) REGISTER_KERNELS(T, int64) TF_CALL_POD_TYPES(REGISTER_KERNELS_TINDEX) #undef REGISTER_KERNELS_TINDEX #undef REGISTER_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRowsGrad<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, typename TTypes<Tindex>::ConstVec reverse_index_map, typename TTypes<T>::ConstVec grad_values, typename TTypes<T>::Vec d_values, typename TTypes<T>::Scalar d_default_value) { const CPUDevice& device = context->eigen_device<CPUDevice>(); const Tindex N = reverse_index_map.dimension(0); const Tindex N_full = grad_values.dimension(0); T& d_default_value_scalar = d_default_value(); d_default_value_scalar = T(); Tensor visited_t; TF_RETURN_IF_ERROR( context->allocate_temp(DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(device) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. int64 reverse_index = reverse_index_map(i); if (reverse_index < 0 || reverse_index >= N_full) { return errors::InvalidArgument( "Elements in reverse index must be in [0, ", N_full, ") but got ", reverse_index); } d_values(i) = grad_values(reverse_index); visited(reverse_index) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value_scalar += grad_values(j); } } return Status::OK(); } }; } // namespace functor template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()), errors::InvalidArgument("grad_values must be a vector, saw: ", grad_values_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<Tindex>(); const auto grad_values = grad_values_t->vec<T>(); const Tindex N = reverse_index_map_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); auto d_default_value = d_default_value_t->scalar<T>(); OP_REQUIRES_OK(context, functor::SparseFillEmptyRowsGrad<Device, T, Tindex>()( context, reverse_index_map, grad_values, d_values, d_default_value)); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_##D) \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGradOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, \ typename TTypes<Tindex>::ConstVec reverse_index_map, \ typename TTypes<T>::ConstVec grad_values, \ typename TTypes<T>::Vec d_values, \ typename TTypes<T>::Scalar d_default_value); \ extern template struct SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_REAL_NUMBER_TYPES(DECLARE_GPU_SPEC_INT64); #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_GPU_KERNELS(T) REGISTER_KERNELS(GPU, T, int64) TF_CALL_REAL_NUMBER_TYPES(REGISTER_GPU_KERNELS); #undef REGISTER_GPU_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #undef REGISTER_KERNELS } // namespace tensorflow
40.265766
80
0.639277
AdaAlarm
c1eed8184c2b2aafdf58f16ecf2d8030a13da7e5
611
hpp
C++
lib/STL+/strings/print_basic.hpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
3
2018-05-07T19:09:23.000Z
2019-05-03T14:19:38.000Z
deps/stlplus/strings/print_basic.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
deps/stlplus/strings/print_basic.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
#ifndef STLPLUS_PRINT_BASIC #define STLPLUS_PRINT_BASIC //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // Utilities for converting printing basic C types //////////////////////////////////////////////////////////////////////////////// #include "print_bool.hpp" #include "print_cstring.hpp" #include "print_float.hpp" #include "print_int.hpp" #include "print_pointer.hpp" #endif
29.095238
80
0.517185
knela96
c1eef41280d3d3c2fab97e760c7765473cf58862
4,015
hpp
C++
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
1
2019-11-05T10:59:14.000Z
2019-11-05T10:59:14.000Z
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
null
null
null
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <ulocal/http_header_table.hpp> #include <ulocal/http_request.hpp> #include <ulocal/string_stream.hpp> #include <ulocal/url_args.hpp> namespace ulocal { namespace detail { enum class RequestState { Start, StatusLineMethod, StatusLineResource, StatusLineHttpVersion, HeaderName, HeaderValue, Content }; } // namespace detail class HttpRequestParser { public: HttpRequestParser() : _state(detail::RequestState::Start) {} HttpRequestParser(const HttpRequestParser&) = delete; HttpRequestParser(HttpRequestParser&&) noexcept = default; HttpRequestParser& operator=(const HttpRequestParser&) = delete; HttpRequestParser& operator=(HttpRequestParser&&) noexcept = default; std::optional<HttpRequest> parse(StringStream& stream) { bool continue_parsing = true; while (continue_parsing) { switch (_state) { case detail::RequestState::Start: { _method.clear(); _resource.clear(); _http_version.clear(); _header_name.clear(); _header_value.clear(); _headers.clear(); _content.clear(); _content_length = 0; _state = detail::RequestState::StatusLineMethod; break; } case detail::RequestState::StatusLineMethod: { auto [str, found_space] = stream.read_until(' '); _method += str; if (found_space) { _state = detail::RequestState::StatusLineResource; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineResource: { auto [str, found_space] = stream.read_until(' '); _resource += str; if (found_space) { _state = detail::RequestState::StatusLineHttpVersion; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineHttpVersion: { auto [str, found_newline] = stream.read_until("\r\n"); _http_version += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); } else continue_parsing = false; break; } case detail::RequestState::HeaderName: { if (stream.as_string_view(2) == "\r\n") { stream.skip(2); _state = detail::RequestState::Content; auto content_length_header = _headers.get_header("content-length"); if (content_length_header) _content_length = content_length_header->get_value_as<std::uint64_t>(); } else if (stream.as_string_view(1) == "\r") { continue_parsing = false; } else { auto [str, found_colon] = stream.read_until(':'); _header_name += str; if (found_colon) { _state = detail::RequestState::HeaderValue; stream.skip(1); } else continue_parsing = false; } break; } case detail::RequestState::HeaderValue: { auto [str, found_newline] = stream.read_until("\r\n"); _header_value += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); _headers.add_header(std::move(_header_name), lstrip(_header_value)); _header_name.clear(); _header_value.clear(); } else continue_parsing = false; break; } case detail::RequestState::Content: { auto str = stream.read(_content_length - _content.length()); _content += str; if (_content.length() == _content_length) { _state = detail::RequestState::Start; return HttpRequest{ std::move(_method), std::move(_resource), std::move(_headers), std::move(_content) }; } else continue_parsing = false; break; } } } stream.realign(); return std::nullopt; } private: detail::RequestState _state; std::string _method, _resource, _http_version, _header_name, _header_value, _content; HttpHeaderTable _headers; std::uint64_t _content_length; }; } // namespace ulocal
23.074713
86
0.637111
metthal
c1efaf1f0e22efa51831b570b21b463797966ad9
9,379
cpp
C++
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
null
null
null
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
12
2020-03-22T04:11:45.000Z
2022-03-13T12:45:49.000Z
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
null
null
null
#include "unpack.hpp" #include <memory> #include <iomanip> #include <archive.h> #include <archive_entry.h> #include <cpprest/http_client.h> #include <cpprest/rawptrstream.h> #include <boost/filesystem.hpp> #include "types.hpp" #include "exception.hpp" #include "text.hpp" const uint64_t CHUNK_SIZE = 65536; class Context { public: Context (uint16_t port, const std::string & id); web::http::http_response & getResponse (); int64_t readChunk (const void ** buffer); int64_t seek (int64_t offset, int whence); void reset (); private: web::uri base; web::uri path; web::http::http_response response; int64_t offset; int64_t length; std::array<uint8_t, CHUNK_SIZE> chunk; }; using ContextHandle = std::shared_ptr<Context>; ArchiveHandle createArchiveReader (ContextHandle context); ArchiveHandle createDiskWriter (); std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName); void extractArchive (ArchiveHandle reader, ArchiveHandle writer); web::uri makeBase (uint16_t port); web::uri makePath (const std::string & id); int openCallback (struct archive * handle, void * context); int closeCallback (struct archive * handle, void * context); la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer); la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence); void unpackTo (uint16_t port, const std::string & id, const std::string & localPath) { ContextHandle context = std::make_shared<Context>(port, id); Text text; auto reader = createArchiveReader(context); auto writer = createDiskWriter(); for (;;) { struct archive_entry * entry = nullptr; int rv = archive_read_next_header(reader.get(), &entry); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_next_header"); } // skip folders auto fileType = archive_entry_filetype(entry); if (fileType & AE_IFDIR) { continue; } const char * entryName = archive_entry_pathname(entry); if (!entryName) { throw EntryError("archive_entry_pathname", "nullptr"); } auto entryPath = resolvePath(text, localPath, id, entryName); rv = archive_entry_update_pathname_utf8(entry, entryPath.c_str()); if (!rv) { throw EntryError("archive_entry_update_pathname_utf8", entryPath); } rv = archive_write_header(writer.get(), entry); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_header"); } extractArchive(reader, writer); rv = archive_write_finish_entry(writer.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_finish_entry"); } } } ArchiveHandle createArchiveReader (ContextHandle context) { int rv = 0; ArchiveHandle handle( archive_read_new(), [](ArchiveHandle::element_type * p) -> void { archive_read_free(p); }); rv = archive_read_support_filter_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_filter_all"); } rv = archive_read_support_format_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_format_all"); } rv = archive_read_set_open_callback(handle.get(), openCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_open_callback"); } rv = archive_read_set_close_callback(handle.get(), closeCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_close_callback"); } rv = archive_read_set_read_callback(handle.get(), readCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_read_callback"); } rv = archive_read_set_seek_callback(handle.get(), seekCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_seek_callback"); } rv = archive_read_set_callback_data(handle.get(), context.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_callback_data"); } rv = archive_read_open1(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_open1"); } return handle; } ArchiveHandle createDiskWriter () { ArchiveHandle handle( archive_write_disk_new(), [](ArchiveHandle::element_type * p) -> void { archive_write_free(p); }); return handle; } void extractArchive (ArchiveHandle reader, ArchiveHandle writer) { for (;;) { int rv = 0; const void * chunk = nullptr; size_t length = 0; la_int64_t offset = 0; rv = archive_read_data_block(reader.get(), &chunk, &length, &offset); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_data_block"); } rv = archive_write_data_block(writer.get(), chunk, length, offset); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_data_block"); } } } int openCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } int closeCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer) { auto ctx = static_cast<Context *>(context); try { return ctx->readChunk(buffer); } catch (std::exception & e) { fprintf(stderr, "readCallback %s\n", e.what()); return ARCHIVE_FATAL; } } la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence) { auto ctx = static_cast<Context *>(context); auto rv = ctx->seek(offset, whence); if (rv < 0) { return ARCHIVE_FATAL; } return rv; } web::uri makeBase (uint16_t port) { web::uri_builder builder; builder.set_scheme("http"); builder.set_host("localhost"); builder.set_port(port); return builder.to_uri(); } web::uri makePath (const std::string & id) { std::ostringstream sout; sout << "/api/v1/nodes/" << id << "/stream"; web::uri_builder builder; builder.set_path(sout.str()); return builder.to_uri(); } std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName) { auto newEntryName = text.toUtf8(entryName); boost::filesystem::path path = localPath; path /= id; path /= newEntryName; return path.string(); } Context::Context (uint16_t port, const std::string & id) : base(makeBase(port)) , path(makePath(id)) , response() , offset(0) , length(-1) , chunk() {} web::http::http_response & Context::getResponse () { auto status = this->response.status_code(); if (status == web::http::status_codes::OK || status == web::http::status_codes::PartialContent) { return this->response; } web::http::http_request request; request.set_method(web::http::methods::GET); request.set_request_uri(this->path); if (this->length >= 0) { std::ostringstream sout; sout << "bytes=" << this->offset << "-" << (this->length - 1); request.headers().add("Range", sout.str()); } web::http::client::http_client_config cfg; cfg.set_timeout(std::chrono::minutes(1)); web::http::client::http_client client(this->base, cfg); this->response = client.request(request).get(); status = this->response.status_code(); if (status == web::http::status_codes::OK) { this->length = this->response.headers().content_length(); } else if (status != web::http::status_codes::PartialContent) { throw HttpError(status, this->response.reason_phrase()); } return this->response; } int64_t Context::readChunk (const void ** buffer) { using Buffer = Concurrency::streams::rawptr_buffer<uint8_t>; auto & response = this->getResponse(); Buffer glue(&this->chunk[0], CHUNK_SIZE); auto length = response.body().read(glue, CHUNK_SIZE).get(); *buffer = &this->chunk[0]; this->offset += length; return length; } int64_t Context::seek (int64_t offset, int whence) { this->response = web::http::http_response(); switch (whence) { case SEEK_SET: this->offset = offset; break; case SEEK_CUR: this->offset += offset; break; case SEEK_END: if (this->length < 0) { return -1; } this->offset = this->length + offset; break; default: return -1; } return this->offset; } void Context::reset () { this->response = web::http::http_response(); this->offset = 0; this->length = -1; }
27.748521
80
0.624693
legnaleurc
c1f055550b53d0e0ab5c404bcdb07a72e097e8ee
18,025
cpp
C++
external/webkit/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
null
null
null
external/webkit/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
null
null
null
external/webkit/Source/WebCore/loader/appcache/ApplicationCacheHost.cpp
ghsecuritylab/android_platform_sony_nicki
526381be7808e5202d7865aa10303cb5d249388a
[ "Apache-2.0" ]
1
2020-03-08T00:59:27.000Z
2020-03-08T00:59:27.000Z
/* * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ApplicationCacheHost.h" #if ENABLE(OFFLINE_WEB_APPLICATIONS) #include "ApplicationCache.h" #include "ApplicationCacheGroup.h" #include "ApplicationCacheResource.h" #include "DocumentLoader.h" #include "DOMApplicationCache.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "MainResourceLoader.h" #include "ProgressEvent.h" #include "ResourceLoader.h" #include "ResourceRequest.h" #include "Settings.h" namespace WebCore { ApplicationCacheHost::ApplicationCacheHost(DocumentLoader* documentLoader) : m_domApplicationCache(0) , m_documentLoader(documentLoader) , m_defersEvents(true) , m_candidateApplicationCacheGroup(0) { ASSERT(m_documentLoader); } ApplicationCacheHost::~ApplicationCacheHost() { ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup); if (m_applicationCache) m_applicationCache->group()->disassociateDocumentLoader(m_documentLoader); else if (m_candidateApplicationCacheGroup) m_candidateApplicationCacheGroup->disassociateDocumentLoader(m_documentLoader); } void ApplicationCacheHost::selectCacheWithoutManifest() { ApplicationCacheGroup::selectCacheWithoutManifestURL(m_documentLoader->frame()); } void ApplicationCacheHost::selectCacheWithManifest(const KURL& manifestURL) { ApplicationCacheGroup::selectCache(m_documentLoader->frame(), manifestURL); } void ApplicationCacheHost::maybeLoadMainResource(ResourceRequest& request, SubstituteData& substituteData) { // Check if this request should be loaded from the application cache if (!substituteData.isValid() && isApplicationCacheEnabled()) { ASSERT(!m_mainResourceApplicationCache); m_mainResourceApplicationCache = ApplicationCacheGroup::cacheForMainRequest(request, m_documentLoader); if (m_mainResourceApplicationCache) { // Get the resource from the application cache. By definition, cacheForMainRequest() returns a cache that contains the resource. ApplicationCacheResource* resource = m_mainResourceApplicationCache->resourceForRequest(request); substituteData = SubstituteData(resource->data(), resource->response().mimeType(), resource->response().textEncodingName(), KURL()); } } } void ApplicationCacheHost::maybeLoadMainResourceForRedirect(ResourceRequest& request, SubstituteData& substituteData) { ASSERT(status() == UNCACHED); maybeLoadMainResource(request, substituteData); } bool ApplicationCacheHost::maybeLoadFallbackForMainResponse(const ResourceRequest& request, const ResourceResponse& r) { if (r.httpStatusCode() / 100 == 4 || r.httpStatusCode() / 100 == 5) { ASSERT(!m_mainResourceApplicationCache); if (isApplicationCacheEnabled()) { m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, documentLoader()); if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get())) return true; } } return false; } bool ApplicationCacheHost::maybeLoadFallbackForMainError(const ResourceRequest& request, const ResourceError& error) { if (!error.isCancellation()) { ASSERT(!m_mainResourceApplicationCache); if (isApplicationCacheEnabled()) { m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, m_documentLoader); if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get())) return true; } } return false; } void ApplicationCacheHost::mainResourceDataReceived(const char*, int, long long, bool) { // This method is here to facilitate alternate implemetations of this interface by the host browser. } void ApplicationCacheHost::failedLoadingMainResource() { ApplicationCacheGroup* group = m_candidateApplicationCacheGroup; if (!group && m_applicationCache) { if (mainResourceApplicationCache()) { // Even when the main resource is being loaded from an application cache, loading can fail if aborted. return; } group = m_applicationCache->group(); } if (group) group->failedLoadingMainResource(m_documentLoader); } void ApplicationCacheHost::finishedLoadingMainResource() { ApplicationCacheGroup* group = candidateApplicationCacheGroup(); if (!group && applicationCache() && !mainResourceApplicationCache()) group = applicationCache()->group(); if (group) group->finishedLoadingMainResource(m_documentLoader); } bool ApplicationCacheHost::maybeLoadResource(ResourceLoader* loader, ResourceRequest& request, const KURL& originalURL) { if (!isApplicationCacheEnabled()) return false; if (request.url() != originalURL) return false; ApplicationCacheResource* resource; if (!shouldLoadResourceFromApplicationCache(request, resource)) return false; m_documentLoader->m_pendingSubstituteResources.set(loader, resource); m_documentLoader->deliverSubstituteResourcesAfterDelay(); return true; } bool ApplicationCacheHost::maybeLoadFallbackForRedirect(ResourceLoader* resourceLoader, ResourceRequest& request, const ResourceResponse& redirectResponse) { if (!redirectResponse.isNull() && !protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadFallbackForResponse(ResourceLoader* resourceLoader, const ResourceResponse& response) { if (response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadFallbackForError(ResourceLoader* resourceLoader, const ResourceError& error) { if (!error.isCancellation()) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadSynchronously(ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data) { ApplicationCacheResource* resource; if (shouldLoadResourceFromApplicationCache(request, resource)) { if (resource) { response = resource->response(); data.append(resource->data()->data(), resource->data()->size()); } else { error = documentLoader()->frameLoader()->client()->cannotShowURLError(request); } return true; } return false; } void ApplicationCacheHost::maybeLoadFallbackSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data) { // If normal loading results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code or equivalent, // or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry // corresponding to the matched namespace. if ((!error.isNull() && !error.isCancellation()) || response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5 || !protocolHostAndPortAreEqual(request.url(), response.url())) { ApplicationCacheResource* resource; if (getApplicationCacheFallbackResource(request, resource)) { response = resource->response(); data.clear(); data.append(resource->data()->data(), resource->data()->size()); } } } bool ApplicationCacheHost::canCacheInPageCache() const { return !applicationCache() && !candidateApplicationCacheGroup(); } void ApplicationCacheHost::setDOMApplicationCache(DOMApplicationCache* domApplicationCache) { ASSERT(!m_domApplicationCache || !domApplicationCache); m_domApplicationCache = domApplicationCache; } void ApplicationCacheHost::notifyDOMApplicationCache(EventID id, int total, int done) { if (m_defersEvents) { // Event dispatching is deferred until document.onload has fired. m_deferredEvents.append(DeferredEvent(id, total, done)); return; } dispatchDOMEvent(id, total, done); } void ApplicationCacheHost::stopLoadingInFrame(Frame* frame) { ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup); if (m_candidateApplicationCacheGroup) m_candidateApplicationCacheGroup->stopLoadingInFrame(frame); else if (m_applicationCache) m_applicationCache->group()->stopLoadingInFrame(frame); } void ApplicationCacheHost::stopDeferringEvents() { RefPtr<DocumentLoader> protect(documentLoader()); for (unsigned i = 0; i < m_deferredEvents.size(); ++i) { const DeferredEvent& deferred = m_deferredEvents[i]; dispatchDOMEvent(deferred.eventID, deferred.progressTotal, deferred.progressDone); } m_deferredEvents.clear(); m_defersEvents = false; } #if ENABLE(INSPECTOR) void ApplicationCacheHost::fillResourceList(ResourceInfoList* resources) { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return; ApplicationCache::ResourceMap::const_iterator end = cache->end(); for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) { RefPtr<ApplicationCacheResource> resource = it->second; unsigned type = resource->type(); bool isMaster = type & ApplicationCacheResource::Master; bool isManifest = type & ApplicationCacheResource::Manifest; bool isExplicit = type & ApplicationCacheResource::Explicit; bool isForeign = type & ApplicationCacheResource::Foreign; bool isFallback = type & ApplicationCacheResource::Fallback; resources->append(ResourceInfo(resource->url(), isMaster, isManifest, isFallback, isForeign, isExplicit, resource->estimatedSizeInStorage())); } } ApplicationCacheHost::CacheInfo ApplicationCacheHost::applicationCacheInfo() { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return CacheInfo(KURL(), 0, 0, 0); // FIXME: Add "Creation Time" and "Update Time" to Application Caches. return CacheInfo(cache->manifestResource()->url(), 0, 0, cache->estimatedSizeInStorage()); } #endif void ApplicationCacheHost::dispatchDOMEvent(EventID id, int total, int done) { if (m_domApplicationCache) { const AtomicString& eventType = DOMApplicationCache::toEventType(id); ExceptionCode ec = 0; RefPtr<Event> event; if (id == PROGRESS_EVENT) event = ProgressEvent::create(eventType, true, done, total); else event = Event::create(eventType, false, false); m_domApplicationCache->dispatchEvent(event, ec); ASSERT(!ec); } } void ApplicationCacheHost::setCandidateApplicationCacheGroup(ApplicationCacheGroup* group) { ASSERT(!m_applicationCache); m_candidateApplicationCacheGroup = group; } void ApplicationCacheHost::setApplicationCache(PassRefPtr<ApplicationCache> applicationCache) { if (m_candidateApplicationCacheGroup) { ASSERT(!m_applicationCache); m_candidateApplicationCacheGroup = 0; } m_applicationCache = applicationCache; } bool ApplicationCacheHost::shouldLoadResourceFromApplicationCache(const ResourceRequest& request, ApplicationCacheResource*& resource) { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return false; // If the resource is not to be fetched using the HTTP GET mechanism or equivalent, or if its URL has a different // <scheme> component than the application cache's manifest, then fetch the resource normally. // +{ ASD-NET-JC-JLO_JB.1257-01 if (!cache->manifestResource() || (!ApplicationCache::requestIsHTTPOrHTTPSGet(request) || !equalIgnoringCase(request.url().protocol(), cache->manifestResource()->url().protocol()))) // if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request) || !equalIgnoringCase(request.url().protocol(), cache->manifestResource()->url().protocol())) // ASD-NET-JC-JLO_JB.1257-01 }+ return false; // If the resource's URL is an master entry, the manifest, an explicit entry, or a fallback entry // in the application cache, then get the resource from the cache (instead of fetching it). resource = cache->resourceForURL(request.url()); // Resources that match fallback namespaces or online whitelist entries are fetched from the network, // unless they are also cached. if (!resource && (cache->allowsAllNetworkRequests() || cache->urlMatchesFallbackNamespace(request.url()) || cache->isURLInOnlineWhitelist(request.url()))) return false; // Resources that are not present in the manifest will always fail to load (at least, after the // cache has been primed the first time), making the testing of offline applications simpler. return true; } bool ApplicationCacheHost::getApplicationCacheFallbackResource(const ResourceRequest& request, ApplicationCacheResource*& resource, ApplicationCache* cache) { if (!cache) { cache = applicationCache(); if (!cache) return false; } if (!cache->isComplete()) return false; // If the resource is not a HTTP/HTTPS GET, then abort if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return false; KURL fallbackURL; if (cache->isURLInOnlineWhitelist(request.url())) return false; if (!cache->urlMatchesFallbackNamespace(request.url(), &fallbackURL)) return false; resource = cache->resourceForURL(fallbackURL); ASSERT(resource); return true; } bool ApplicationCacheHost::scheduleLoadFallbackResourceFromApplicationCache(ResourceLoader* loader, ApplicationCache* cache) { if (!isApplicationCacheEnabled()) return false; ApplicationCacheResource* resource; if (!getApplicationCacheFallbackResource(loader->request(), resource, cache)) return false; m_documentLoader->m_pendingSubstituteResources.set(loader, resource); m_documentLoader->deliverSubstituteResourcesAfterDelay(); loader->handle()->cancel(); return true; } ApplicationCacheHost::Status ApplicationCacheHost::status() const { ApplicationCache* cache = applicationCache(); if (!cache) return UNCACHED; switch (cache->group()->updateStatus()) { case ApplicationCacheGroup::Checking: return CHECKING; case ApplicationCacheGroup::Downloading: return DOWNLOADING; case ApplicationCacheGroup::Idle: { if (cache->group()->isObsolete()) return OBSOLETE; if (cache != cache->group()->newestCache()) return UPDATEREADY; return IDLE; } } ASSERT_NOT_REACHED(); return UNCACHED; } bool ApplicationCacheHost::update() { ApplicationCache* cache = applicationCache(); if (!cache) return false; cache->group()->update(m_documentLoader->frame(), ApplicationCacheUpdateWithoutBrowsingContext); return true; } bool ApplicationCacheHost::swapCache() { ApplicationCache* cache = applicationCache(); if (!cache) return false; // If the group of application caches to which cache belongs has the lifecycle status obsolete, unassociate document from cache. if (cache->group()->isObsolete()) { cache->group()->disassociateDocumentLoader(m_documentLoader); return true; } // If there is no newer cache, raise an INVALID_STATE_ERR exception. ApplicationCache* newestCache = cache->group()->newestCache(); if (cache == newestCache) return false; ASSERT(cache->group() == newestCache->group()); setApplicationCache(newestCache); return true; } bool ApplicationCacheHost::isApplicationCacheEnabled() { return m_documentLoader->frame()->settings() && m_documentLoader->frame()->settings()->offlineWebApplicationCacheEnabled(); } } // namespace WebCore #endif // ENABLE(OFFLINE_WEB_APPLICATIONS)
38.188559
185
0.718502
ghsecuritylab
c1f163bac44b15fbc3bb22e2350cd315de115ae2
3,329
cpp
C++
config_parser.cpp
skordal/bacteria
dbeb929f04acd945a8a122ad767134db993e4819
[ "MIT" ]
1
2020-05-11T10:13:30.000Z
2020-05-11T10:13:30.000Z
config_parser.cpp
skordal/bacteria
dbeb929f04acd945a8a122ad767134db993e4819
[ "MIT" ]
null
null
null
config_parser.cpp
skordal/bacteria
dbeb929f04acd945a8a122ad767134db993e4819
[ "MIT" ]
null
null
null
/*************************************************/ /* Bacteria - The interesting bacteria simulator */ /* (c) Kristian K. Skordal 2009 - 2012 */ /*************************************************/ #include "config_parser.h" using namespace std; config_parser::config_parser(const string & filename) : filename(filename) { assert(!filename.empty()); } bool config_parser::parse() { ifstream config_file(filename.c_str(), ios::in); string input_line; int line_number = 0; if(!config_file.good()) { cerr << "ERROR: Could not open configuration file: " << filename << endl; return false; } while(config_file.good() && !config_file.eof()) { size_t equal_sign_index; string attribute_name; string attribute_value; getline(config_file, input_line); ++line_number; // Check for empty lines or comments: if(input_line.length() == 0 || input_line.at(0) == '\n' || input_line.at(0) == '\r' || input_line.at(0) == '#') continue; equal_sign_index = input_line.find_first_of('='); if(equal_sign_index == string::npos) { cerr << "ERROR: Missing assignment on line " << input_line << endl; return false; } size_t name_start = input_line.find_first_not_of(" \t"); if(name_start == string::npos && input_line[name_start] == '=') { cerr << "ERROR: Missing attribute name on line " << input_line << endl; return false; } size_t name_end = input_line.find_first_of(" =\t", name_start); if(name_end == string::npos) { cerr << "ERROR: End of attribute name not found on line " << input_line << endl; return false; } attribute_name = input_line.substr(name_start, name_end); size_t value_start = input_line.find_first_not_of(" \t", equal_sign_index + 1); if(value_start == string::npos) { cerr << "ERROR: No value found for attribute " << attribute_name << " on line " << input_line << endl; return false; } size_t value_end = input_line.find_first_of("\n\r\t ", value_start); attribute_value = input_line.substr(value_start, value_end); // Check the name and type of the parsed attribute and value: config_type_t type = config_db::get_type(attribute_name); if(type == TYPE_INVALID) { cerr << "ERROR: Unrecognized attribute name: " << attribute_name << " on line " << input_line << endl; return false; } istringstream value_extractor(attribute_value); switch(type) { case TYPE_INTEGER: int intval; value_extractor >> intval; config_db::get().set_value(attribute_name, intval); break; case TYPE_FLOAT: float floatval; value_extractor >> floatval; config_db::get().set_value(attribute_name, floatval); break; case TYPE_BOOLEAN: transform(attribute_value.begin(), attribute_value.end(), attribute_value.begin(), ptr_fun<int, int>(tolower)); if(attribute_value == "true") config_db::get().set_value(attribute_name, true); else if(attribute_value == "false") config_db::get().set_value(attribute_name, false); else { cerr << "ERROR: Unrecognized boolean value for attribute " << attribute_name << " on line " << input_line << endl; return false; } break; case TYPE_STRING: config_db::get().set_value(attribute_name, attribute_value.c_str()); break; } } config_file.close(); return true; }
27.065041
85
0.650045
skordal
c1f16d92c41bbed005a894f23bb4ae192ca2bbb4
1,314
hpp
C++
src/graphics/al_stb_font.hpp
AlloSphere-Research-Group/al_lib
94d23fe71b79d3464a658f16ca34c2040e6d7334
[ "BSD-3-Clause" ]
26
2018-11-05T23:29:43.000Z
2022-03-17T18:16:49.000Z
src/graphics/al_stb_font.hpp
yangevelyn/allolib
1654be795b6515c058eb8243751b903a2aa6efdc
[ "BSD-3-Clause" ]
41
2018-01-19T18:34:41.000Z
2022-01-27T23:52:01.000Z
src/graphics/al_stb_font.hpp
yangevelyn/allolib
1654be795b6515c058eb8243751b903a2aa6efdc
[ "BSD-3-Clause" ]
11
2018-01-05T16:42:19.000Z
2022-01-27T22:08:01.000Z
#ifndef INCLUDE_LOAD_FONT_MODULE_HPP #define INCLUDE_LOAD_FONT_MODULE_HPP #include <vector> #include <cstdint> namespace al_stb { // Wrapper for all the data needed for font rendering struct FontData { struct BakedChar { unsigned short x0, y0, x1, y1; float xoff, yoff, xadvance; }; // to be casted to stbtt_bakedchar in the implementation // user will not need to use this struct float pixelHeight = -1; int width = -1, height = -1; // of bitmap pixel data std::vector<uint8_t> bitmap; // 1 channel bitmap data std::vector<BakedChar> charData; }; // info about a chracter, calculated from font data struct CharData { float x0, y0, x1, y1; // packing rect corners, x towards right, y towards down float s0, t0, s1, t1; // texcoords float xAdvance; // how much to go horizontally after this character }; // pixelHeight is max height of each character in font texture // value larger than 128 might result not all fonts fitting in the texture FontData loadFont(const char* filename, float pixelHeight, int bitmapSize); // caching the results of this function might give better performance // x0, y0, x1, y1, and xAdvance of returned CharData are in fontData.pixelHeight scale CharData getCharData(FontData* fontData, int charIndex); } #endif
32.04878
86
0.7207
AlloSphere-Research-Group
c1f21d7f4348df96f7be5c0adb1b9650304048e0
1,912
cc
C++
ui/gfx/mojom/ca_layer_params_mojom_traits.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
ui/gfx/mojom/ca_layer_params_mojom_traits.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ui/gfx/mojom/ca_layer_params_mojom_traits.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2017 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 "ui/gfx/mojom/ca_layer_params_mojom_traits.h" #include "build/build_config.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ui/gfx/geometry/mojom/geometry_mojom_traits.h" namespace mojo { gfx::mojom::CALayerContentPtr StructTraits<gfx::mojom::CALayerParamsDataView, gfx::CALayerParams>::content( const gfx::CALayerParams& ca_layer_params) { #if defined(OS_MAC) if (ca_layer_params.io_surface_mach_port) { DCHECK(!ca_layer_params.ca_context_id); return gfx::mojom::CALayerContent::NewIoSurfaceMachPort( mojo::PlatformHandle(base::mac::RetainMachSendRight( ca_layer_params.io_surface_mach_port.get()))); } #endif return gfx::mojom::CALayerContent::NewCaContextId( ca_layer_params.ca_context_id); } bool StructTraits<gfx::mojom::CALayerParamsDataView, gfx::CALayerParams>::Read( gfx::mojom::CALayerParamsDataView data, gfx::CALayerParams* out) { out->is_empty = data.is_empty(); gfx::mojom::CALayerContentDataView content_data; data.GetContentDataView(&content_data); switch (content_data.tag()) { case gfx::mojom::CALayerContentDataView::Tag::CA_CONTEXT_ID: out->ca_context_id = content_data.ca_context_id(); break; case gfx::mojom::CALayerContentDataView::Tag::IO_SURFACE_MACH_PORT: #if defined(OS_MAC) mojo::PlatformHandle platform_handle = content_data.TakeIoSurfaceMachPort(); if (!platform_handle.is_mach_send()) return false; out->io_surface_mach_port.reset(platform_handle.ReleaseMachSendRight()); break; #else return false; #endif } if (!data.ReadPixelSize(&out->pixel_size)) return false; out->scale_factor = data.scale_factor(); return true; } } // namespace mojo
31.866667
79
0.737448
zealoussnow
c1f221e503a8d9d84ac2315241bf0f00542e1849
12,257
cxx
C++
Plugins/SciberQuestToolKit/SciberQuest/vtkSQSeedPointLatice.cxx
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
1
2020-05-21T20:20:59.000Z
2020-05-21T20:20:59.000Z
Plugins/SciberQuestToolKit/SciberQuest/vtkSQSeedPointLatice.cxx
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
null
null
null
Plugins/SciberQuestToolKit/SciberQuest/vtkSQSeedPointLatice.cxx
mathstuf/ParaView
e867e280545ada10c4ed137f6a966d9d2f3db4cb
[ "Apache-2.0" ]
5
2016-04-14T13:42:37.000Z
2021-05-22T04:59:42.000Z
/* ____ _ __ ____ __ ____ / __/___(_) / ___ ____/ __ \__ _____ ___ / /_ / _/__ ____ _\ \/ __/ / _ \/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \/ __/ /___/\__/_/_.__/\__/_/ \___\_\_,_/\__/___/\__/ /___/_//_/\__(_) Copyright 2012 SciberQuest Inc. */ /*===================== Program: Visualization Toolkit Module: $RCSfile: vtkSQSeedPointLatice.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =====================*/ #include "vtkSQSeedPointLatice.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkMultiProcessController.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkIdTypeArray.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkType.h" #include "Tuple.hxx" #include "vtkPVInformationKeys.h" // #define SQTK_DEBUG //***************************************************************************** static inline void indexToIJK(int idx, int nx, int nxy, int &i, int &j, int &k) { // convert a flat array index into a i,j,k three space tuple. k=idx/nxy; j=(idx-k*nxy)/nx; i=idx-k*nxy-j*nx; } //***************************************************************************** template <typename T> static void linspace(T lo, T hi, int n, T *data) { if (n==1) { data[0]=(hi+lo)/((T)2); return; } T delta=(hi-lo)/((T)(n-1)); for (int i=0; i<n; ++i) { data[i]=lo+((T)i)*delta; } } //***************************************************************************** template <typename T> static void logspace(T lo, T hi, int n, T p, T *data) { int mid=n/2; int nlo=mid; int nhi=n-mid; T s=hi-lo; T rhi=((T)pow(((T)10),p)); linspace<T>(((T)1),((T)0.99)*rhi,nlo,data); linspace<T>(1.0,rhi,nhi,data+nlo); int i=0; for (; i<nlo; ++i) { data[i]=lo+s*(((T)0.5)*((T)log10(data[i]))/p); } for (; i<n; ++i) { data[i]=lo+s*(((T)1)-((T)log10(data[i]))/(((T)2)*p)); } } //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkSQSeedPointLatice); //---------------------------------------------------------------------------- vtkSQSeedPointLatice::vtkSQSeedPointLatice() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::vtkSQSeedPointLatice" << std::endl; #endif this->NX[0]=this->NX[1]=this->NX[2]=4; this->Bounds[0]=this->Bounds[2]=this->Bounds[4]=0.0; this->Bounds[1]=this->Bounds[3]=this->Bounds[5]=1.0; this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //---------------------------------------------------------------------------- vtkSQSeedPointLatice::~vtkSQSeedPointLatice() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::~vtkSQSeedPointLatice" << std::endl; #endif } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetTransformPower(double itp, double jtp, double ktp) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetTransformPower" << std::endl; #endif double tp[3]={itp,jtp,ktp}; this->SetTransformPower(tp); } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetTransformPower(double *tp) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetTransformPower" << std::endl; #endif if (tp[0]<0.0) vtkErrorMacro("Negative transform power i unsupported."); if (tp[1]<0.0) vtkErrorMacro("Negative transform power j unsupported."); if (tp[2]<0.0) vtkErrorMacro("Negative transform power k unsupported."); this->Power[0]=tp[0]; this->Power[1]=tp[1]; this->Power[2]=tp[2]; this->Transform[0]=(tp[0]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Transform[1]=(tp[1]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Transform[2]=(tp[2]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Modified(); } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetIBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetIBounds" << std::endl; #endif this->Bounds[0]=lo; this->Bounds[1]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetIBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetIBounds" << std::endl; #endif return this->Bounds; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetJBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetJBounds" << std::endl; #endif this->Bounds[2]=lo; this->Bounds[3]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetJBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetJBounds" << std::endl; #endif return this->Bounds+2; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetKBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetKBounds" << std::endl; #endif this->Bounds[4]=lo; this->Bounds[5]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetKBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetKBounds" << std::endl; #endif return this->Bounds+4; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::FillInputPortInformation( int /*port*/, vtkInformation *info) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::FillInputPortInformation" << std::endl; #endif // The input is optional,if present it will be used // for bounds. info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkDataSet"); info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(),1); return 1; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::RequestInformation( vtkInformation * /*req*/, vtkInformationVector ** /*inInfos*/, vtkInformationVector *outInfos) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::RequestInformation" << std::endl; #endif // tell the excutive that we are handling our own paralelization. vtkInformation *outInfo=outInfos->GetInformationObject(0); outInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); // TODO extract bounds and set if the input data set is present. return 1; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::RequestData( vtkInformation * /*req*/, vtkInformationVector **inInfos, vtkInformationVector *outInfos) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::RequestData" << std::endl; #endif vtkInformation *outInfo=outInfos->GetInformationObject(0); vtkPolyData *output = dynamic_cast<vtkPolyData*>(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (output==NULL) { vtkErrorMacro("Empty output."); return 1; } // paralelize by piece information. int pieceNo = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); int nPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // sanity - the requst cannot be fullfilled if (pieceNo>=nPieces) { output->Initialize(); return 1; } // domain decomposition int nPoints=this->NX[0]*this->NX[1]*this->NX[2]; int pieceSize=nPoints/nPieces; int nLarge=nPoints%nPieces; int nLocal=pieceSize+(pieceNo<nLarge?1:0); int startId=pieceSize*pieceNo+(pieceNo<nLarge?pieceNo:nLarge); int endId=startId+nLocal; // If the input is present then use it for bounds // otherwise we assume the user has previously set // desired bounds. vtkInformation *inInfo=0; if (inInfos[0]->GetNumberOfInformationObjects()) { inInfo=inInfos[0]->GetInformationObject(0); vtkDataSet *input = dynamic_cast<vtkDataSet*>(inInfo->Get(vtkDataObject::DATA_OBJECT())); if (input) { if (!inInfo->Has(vtkPVInformationKeys::WHOLE_BOUNDING_BOX())) { vtkErrorMacro("Input must have WHOLE_BOUNDING_BOX set."); return 1; } double bounds[6]; inInfo->Get(vtkPVInformationKeys::WHOLE_BOUNDING_BOX(),bounds); double dX[3]; dX[0]=(this->Bounds[1]-this->Bounds[0])/((double)this->NX[0]); dX[1]=(this->Bounds[3]-this->Bounds[2])/((double)this->NX[1]); dX[2]=(this->Bounds[5]-this->Bounds[4])/((double)this->NX[2]); bounds[0]+=dX[0]/2.0; bounds[1]-=dX[0]/2.0; bounds[2]+=dX[1]/2.0; bounds[3]-=dX[1]/2.0; bounds[4]+=dX[2]/2.0; bounds[5]-=dX[2]/2.0; this->SetBounds(bounds); } } // generate the i,j,k coordinate axes // note these are not decompoesed, TODO decomposition. float *axes[3]={NULL}; for (int q=0; q<3; ++q) { axes[q]=new float [this->NX[q]]; switch (this->Transform[q]) { case TRANSFORM_NONE: linspace<float>( ((float)this->Bounds[2*q]), ((float)this->Bounds[2*q+1]), this->NX[q], axes[q]); break; case TRANSFORM_LOG: logspace<float>( ((float)this->Bounds[2*q]), ((float)this->Bounds[2*q+1]), this->NX[q], ((float)this->Power[q]), axes[q]); break; default: vtkErrorMacro("Unsupported transform."); return 1; } } // Configure the output vtkFloatArray *X=vtkFloatArray::New(); X->SetNumberOfComponents(3); X->SetNumberOfTuples(nLocal); float *pX=X->GetPointer(0); vtkPoints *pts=vtkPoints::New(); pts->SetData(X); X->Delete(); output->SetPoints(pts); pts->Delete(); vtkIdTypeArray *ia=vtkIdTypeArray::New(); ia->SetNumberOfComponents(1); ia->SetNumberOfTuples(2*nLocal); vtkIdType *pIa=ia->GetPointer(0); vtkCellArray *verts=vtkCellArray::New(); verts->SetCells(nLocal,ia); ia->Delete(); output->SetVerts(verts); verts->Delete(); int nx=this->NX[0]; int nxy=this->NX[0]*this->NX[1]; double prog=0.0; double progUnit=1.0/nLocal; double progRepUnit=0.1; double progRepLevel=0.1; // generate the point set for (int idx=startId,pid=0; idx<endId; ++idx,++pid,prog+=progUnit) { // update PV progress if (prog>=progRepLevel) { this->UpdateProgress(prog); progRepLevel+=progRepUnit; } int i,j,k; indexToIJK(idx,nx,nxy,i,j,k); // new latice point pX[0]=(axes[0])[i]; pX[1]=(axes[1])[j]; pX[2]=(axes[2])[k]; pX+=3; // insert the cell pIa[0]=1; pIa[1]=pid; pIa+=2; } delete [] axes[0]; delete [] axes[1]; delete [] axes[2]; #ifdef SQTK_DEBUG int rank=vtkMultiProcessController::GetGlobalController()->GetLocalProcessId(); std::cerr << "pieceNo = " << pieceNo << std::endl << "nPieces = " << nPieces << std::endl << "rank = " << rank << std::endl << "nLocal = " << nLocal << std::endl << "startId = " << startId << std::endl << "endId = " << endId << std::endl << "NX=" << Tuple<int>(this->NX,3) << std::endl << "Bounds=" << Tuple<double>(this->Bounds,6) << std::endl; #endif return 1; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::PrintSelf(ostream& os, vtkIndent indent) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::PrintSelf" << std::endl; #endif this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfPoints: " << this->NumberOfPoints << "\n"; }
25.913319
84
0.558048
mathstuf
c1f96a7f659ea493bcef1b4a2b79323f2082816b
3,568
hpp
C++
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
#ifndef DOXYGENSCRAPER_HPP #define DOXYGENSCRAPER_HPP #include "ApplicationPrinter.hpp" #include <sapi/var.hpp> class DoxygenScraperKey { public: DoxygenScraperKey(const String &key, const String &kind, bool is_array) { m_key = key; m_kind = kind; m_is_array = is_array; } const String &key() const { return m_key; } const String &kind() const { return m_kind; } bool is_array() const { return m_is_array; } private: String m_key; String m_kind; bool m_is_array = false; }; class DoxygenScraperObject { public: DoxygenScraperObject(const String &name) { m_name = name; } bool operator==(const DoxygenScraperObject &a) const { return m_name == a.m_name; } void add_key(const String &key, const String &kind, bool is_array = false) { for (size_t i = 0; i < m_keys.count(); i++) { if (m_keys.at(i).key() == key) { // key already exists return; } } m_keys.push_back(DoxygenScraperKey(key, kind, is_array)); } const String &name() const { return m_name; } String constructors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " {\n"; result += " JsonArray json_array = object.at(\"" + key.key() + "\").to_array();\n"; result += " for(u32 i=0; i < json_array.count(); i++){\n"; result += " m_" + translate_name(output_key) + ".push_back(" + key.kind() + "(json_array.at(i).to_object()));\n"; result += " }\n"; result += " }\n"; } else if (key.kind() == "String") { result += " m_" + translate_name(output_key) + " = object.at(\"" + key.key() + "\").to_string();\n"; } else { result += " m_" + translate_name(output_key) + " = " + key.kind() + "(object.at(\"" + key.key() + "\").to_object());\n"; } } return result; } String accessors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); result += " const " + key.kind() + "& " + translate_name(output_key) + "() const { return m_" + translate_name(output_key) + "; }\n"; } return result; } String members() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " Vector<" + key.kind() + "> m_" + translate_name(output_key) + ";\n"; } else { result += " " + key.kind() + " m_" + translate_name(output_key) + ";\n"; } } return result; } static String translate_name(const String &name, bool is_class = false); const Vector<DoxygenScraperKey> &keys() const { return m_keys; } private: String to_output_key(const String &key) const { String result = key; result.replace(String::ToErase("@"), String::ToInsert("a_")); result.replace(String::ToErase("#"), String::ToInsert("h_")); result.replace(String::ToErase(":"), String::ToInsert("_")); return result; } String m_name; Vector<DoxygenScraperKey> m_keys; }; class DoxygenScraper : public ApplicationPrinter { public: DoxygenScraper(); void generate_code(const String &file); private: int generate_code_object( const String &object_key, const JsonObject &object, int depth); Vector<DoxygenScraperObject> m_objects; }; #endif // DOXYGENSCRAPER_HPP
28.31746
80
0.584361
StratifyLabs
c1f976aba1888c50ac559a3e5f0b2f2581c55bc0
4,553
cpp
C++
saber/funcs/impl/amd/saber_pooling_with_index.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
533
2018-05-18T06:14:04.000Z
2022-03-23T11:46:30.000Z
saber/funcs/impl/amd/saber_pooling_with_index.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
100
2018-05-26T08:32:48.000Z
2022-03-17T03:26:25.000Z
saber/funcs/impl/amd/saber_pooling_with_index.cpp
baajur/Anakin
5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730
[ "Apache-2.0" ]
167
2018-05-18T06:14:35.000Z
2022-02-14T01:44:20.000Z
/* Copyright (c) 2018 Anakin Authors, Inc. 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 "include/saber_pooling_with_index.h" namespace anakin { namespace saber { template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::init( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& param, Context<AMD>& ctx) { this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::create( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& power_param, Context<AMD>& ctx) { const int count = outputs[0]->size(); Shape out_stride = outputs[0]->get_stride(); Shape in_stride = inputs[0]->get_stride(); int in_n_index = inputs[0]->num_index(); int in_c_index = inputs[0]->channel_index(); int in_h_index = inputs[0]->height_index(); int in_w_index = inputs[0]->width_index(); int out_n_index = outputs[0]->num_index(); int out_c_index = outputs[0]->channel_index(); int out_h_index = outputs[0]->height_index(); int out_w_index = outputs[0]->width_index(); _in_n_stride = in_stride[in_n_index]; _in_c_stride = in_stride[in_c_index]; _in_h_stride = in_stride[in_h_index]; _in_w_stride = in_stride[in_w_index]; _out_n_stride = out_stride[out_n_index]; _out_c_stride = out_stride[out_c_index]; _out_h_stride = out_stride[out_h_index]; _out_w_stride = out_stride[out_w_index]; KernelInfo kernelInfo; kernelInfo.kernel_file = "Pooling_with_index.cl"; kernelInfo.kernel_name = "Pooling_with_index"; kernelInfo.wk_dim = 1; kernelInfo.l_wk = {AMD_NUM_THREADS}; kernelInfo.g_wk = { (count + kernelInfo.l_wk[0] - 1) / kernelInfo.l_wk[0]* kernelInfo.l_wk[0], 1, 1 }; AMDKernelPtr kptr = CreateKernel(inputs[0]->device_id(), &kernelInfo); if (!kptr.get()->isInit()) { LOG(ERROR) << "Failed to load program"; return SaberInvalidValue; } _kernel_poo1ing_with_index = kptr; LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE CREATE KERNEL"; return SaberSuccess; } template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::dispatch( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& param) { bool err; AMD_API::stream_t cm = this->_ctx->get_compute_stream(); amd_kernel_list list; // To set the argument cl_mem memObjects[3]; cl_mem in_data = (cl_mem)inputs[0]->data(); cl_mem out_data = (cl_mem)outputs[0]->mutable_data(); cl_mem out_index = (cl_mem)outputs[1]->mutable_data(); // To set the argument int count = outputs[0]->valid_size(); int out_n = outputs[0]->num(); int out_c = outputs[0]->channel(); int out_h = outputs[0]->height(); int out_w = outputs[0]->width(); int in_h = inputs[0]->height(); int in_w = inputs[0]->width(); AMDKernel* kernel = _kernel_poo1ing_with_index.get(); kernel->SetKernelArgs( out_data, out_index, in_data, _in_n_stride, _in_c_stride, _in_h_stride, _in_w_stride, in_h, in_w, _out_n_stride, _out_c_stride, _out_h_stride, _out_w_stride, out_h, out_w, out_n, out_c, param.pad_h, param.pad_w, param.stride_h, param.stride_w, param.window_h, param.window_w, count); list.push_back(_kernel_poo1ing_with_index); err = LaunchKernel(cm, list); if (!err) { LOG(ERROR) << "Fialed to set execution."; return SaberInvalidValue; } list.clear(); LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE EXECUTION"; return SaberSuccess; } } // namespace saber } // namespace anakin
30.557047
87
0.652976
baajur
c1f9b3b68535bcee5705bcab7e10873b017b4daa
4,573
cpp
C++
cvt/vision/slam/stereo/ORBTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
11
2017-04-04T16:38:31.000Z
2021-08-04T11:31:26.000Z
cvt/vision/slam/stereo/ORBTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
null
null
null
cvt/vision/slam/stereo/ORBTracking.cpp
tuxmike/cvt
c6a5df38af4653345e795883b8babd67433746e9
[ "MIT" ]
8
2016-04-11T00:58:27.000Z
2022-02-22T07:35:40.000Z
/* The MIT License (MIT) Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <cvt/vision/slam/stereo/ORBTracking.h> namespace cvt { ORBTracking::ORBTracking() : _maxDescDistance( 80 ), _windowRadius( 100 ), _orbOctaves( 3 ), _orbScaleFactor( 0.5f ), _orbCornerThreshold( 15 ), _orbMaxFeatures( 2000 ), _orbNonMaxSuppression( true ) { } ORBTracking::~ORBTracking() { } void ORBTracking::trackFeatures( PointSet2d& trackedPositions, std::vector<size_t>& trackedFeatureIds, const std::vector<Vector2f>& predictedPositions, const std::vector<size_t>& predictedIds, const Image& img ) { // create the ORB //_orb0.update( img ); // we want to find the best matching orb feature from current, that lies // within a certain distance from the "predicted" position std::vector<size_t>::const_iterator currentId = predictedIds.begin(); std::vector<size_t>::const_iterator tEnd = predictedIds.end(); std::vector<Vector2f>::const_iterator pred = predictedPositions.begin(); // keep track of already assigned indices to avoid double associations _orb0MatchedIds.clear(); while( currentId != tEnd ){ FeatureMatch m; const ORBFeature & desc = _descriptors.descriptor( *currentId ); m.feature0 = &desc; int matchedIdx = matchInWindow( m, *pred, _orb0, _orb0MatchedIds ); if( matchedIdx != -1 ){ _orb0MatchedIds.insert( ( size_t )matchedIdx ); trackedPositions.add( Vector2d( m.feature1->pt.x, m.feature1->pt.y ) ); trackedFeatureIds.push_back( *currentId ); } ++currentId; ++pred; } } void ORBTracking::addFeatureToDatabase( const Vector2f & f, size_t id ) { // this is odd, we need to search the closest feature in orb0 size_t closestIdx = 0; float distsqr = Math::MAXF; for( size_t i = 0; i < _orb0.size(); ++i ){ float currd = ( _orb0[ i ].pt - f ).lengthSqr(); if( currd < distsqr ){ closestIdx = i; distsqr = currd; } } _descriptors.addDescriptor( _orb0[ closestIdx ], id ); } int ORBTracking::matchInWindow( FeatureMatch& match, const Vector2f & p, const ORB & orb, const std::set<size_t> & used ) const { const ORBFeature * f = (ORBFeature*)match.feature0; match.feature1 = 0; match.distance = _maxDescDistance; size_t currDist; const std::set<size_t>::const_iterator usedEnd = used.end(); size_t matchedId = 0; for( size_t i = 0; i < orb.size(); i++ ){ if( used.find( i ) == usedEnd ){ if( ( p - orb[ i ].pt ).length() < _windowRadius ){ // try to match currDist = f->distance( orb[ i ] ); if( currDist < match.distance ){ match.feature1 = &orb[ i ]; match.distance = currDist; matchedId = i; } } } } // to ensure unique matches if( match.distance < _maxDescDistance ){ return matchedId; } return -1; } void ORBTracking::clear() { _descriptors.clear(); _orb0MatchedIds.clear(); } }
35.726563
130
0.604417
tuxmike
c1f9f7513a2a54aedbe9b6e87fb09dc7446d4a19
2,304
cpp
C++
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <sstream> #include <gtest/gtest.h> #include <test/utility.hpp> using cmdstan::test::get_path_separator; using cmdstan::test::run_command; using cmdstan::test::run_command_output; TEST(CommandDiagnose, corr_gauss) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "corr_gauss_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/corr_gauss.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, eight_schools) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "eight_schools_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/eight_schools.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, mix) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "mix_output.*"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/mix.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); }
29.538462
87
0.692708
danluu
c1fa62ee8eb65bd86710c7feb664722db9d09a5f
9,908
hpp
C++
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
3,358
2015-12-18T02:56:17.000Z
2022-03-31T02:42:47.000Z
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
965
2015-12-21T10:35:28.000Z
2022-03-30T02:47:00.000Z
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
1,663
2015-12-17T17:45:38.000Z
2022-03-31T07:58:29.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2009 StatPro Italia srl Copyright (C) 2009 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file defaultevent.hpp \brief Classes for default-event description. */ #ifndef quantlib_default_event_hpp #define quantlib_default_event_hpp #include <ql/event.hpp> #include <ql/currency.hpp> #include <ql/math/comparison.hpp> #include <ql/experimental/credit/defaulttype.hpp> #include <ql/experimental/credit/defaultprobabilitykey.hpp> #include <map> namespace QuantLib { /** @class DefaultEvent @brief Credit event on a bond of a certain seniority(ies)/currency Represents a credit event affecting all bonds with a given \ seniority and currency. It assumes that all such bonds suffer \ the event simultaneously. Some events affect all seniorities and this has to be encoded through a different set of events of the same event type. The event is an actual realization, not a contractual reference, as such it contains only an atomic type. */ class DefaultEvent : public Event { public: class DefaultSettlement : public Event { public: friend class DefaultEvent; protected: /*! Default settlement events encode the settlement date and the recovery rates for the affected seniorities. Specific events might require different sets of recoveries to be present. The way these objects are constructed is a prerogative of the particular event class. */ DefaultSettlement(const Date& date, const std::map<Seniority, Real>& recoveryRates); /*! When NoSeniority is passed all seniorities are assumed to have settled to the recovery passed. */ DefaultSettlement(const Date& date = Date(), Seniority seniority = NoSeniority, Real recoveryRate = 0.4); public: Date date() const override; /*! Returns the recovery rate of a default event which has already settled. */ Real recoveryRate(Seniority sen) const; void accept(AcyclicVisitor&) override; private: Date settlementDate_; //! Realized recovery rates std::map<Seniority, Real> recoveryRates_; }; private: // for some reason, gcc chokes on the default parameter below // unless we use the typedef typedef std::map<Seniority, Real> rate_map; public: /*! Credit event with optional settlement information. Represents a credit event that has taken place. Realized events are of an atomic type. If the settlement information is given seniorities present are the seniorities/bonds affected by the event. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), const std::map<Seniority, Real>& recoveryRates = rate_map()); /*! Use NoSeniority to settle to all seniorities with that recovery. In that case the event is assumed to have affected all seniorities. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), Real recoveryRate = 0.4); Date date() const override; bool isRestructuring() const { return eventType_.isRestructuring(); } bool isDefault() const { return !isRestructuring();} bool hasSettled() const { return defSettlement_.date() != Null<Date>(); } const DefaultSettlement& settlement() const { return defSettlement_; } const DefaultType& defaultType() const { return eventType_; } //! returns the currency of the bond this event refers to. const Currency& currency() const { return bondsCurrency_; } //! returns the seniority of the bond that triggered the event. Seniority eventSeniority() const { return bondsSeniority_; } /*! returns a value if the event lead to a settlement for the requested seniority. Specializations on the default atomics and recoveries could change the default policy. */ virtual Real recoveryRate(Seniority seniority) const { if(hasSettled()) { return defSettlement_.recoveryRate(seniority); } return Null<Real>(); } /*! matches the event if this event would trigger a contract related to the requested event type. Notice the contractual event types are not neccesarily atomic. Notice it does not check seniority or currency only event type. typically used from Issuer */ virtual bool matchesEventType( const ext::shared_ptr<DefaultType>& contractEvType) const { // remember we are made of an atomic type. // behaviour by default... return contractEvType->containsRestructuringType( eventType_.restructuringType()) && contractEvType->containsDefaultType( eventType_.defaultType()); } /*! Returns true if this event would trigger a contract with the arguments characteristics. */ virtual bool matchesDefaultKey(const DefaultProbKey& contractKey) const; void accept(AcyclicVisitor&) override; protected: Currency bondsCurrency_; Date defaultDate_; DefaultType eventType_; Seniority bondsSeniority_; DefaultSettlement defSettlement_; }; /*! Two credit events are the same independently of their settlement member data. This has the side effect of overwritting different settlements from the same credit event when, say, inserting in a map. But on the other hand one given event can only have one settlement. This means we can not have two restructuring events on a bond on the same date. */ bool operator==(const DefaultEvent& lhs, const DefaultEvent& rhs); inline bool operator!=(const DefaultEvent& lhs, const DefaultEvent& rhs) { return !(lhs == rhs); } template<> struct earlier_than<DefaultEvent> { bool operator()(const DefaultEvent& e1, const DefaultEvent& e2) const { return e1.date() < e2.date(); } }; // ------------------------------------------------------------------------ class FailureToPayEvent : public DefaultEvent { public: FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, Real recoveryRates); Real amountDefaulted() const {return defaultedAmount_;} bool matchesEventType(const ext::shared_ptr<DefaultType>& contractEvType) const override; private: Real defaultedAmount_; }; // ------------------------------------------------------------------------ class BankruptcyEvent : public DefaultEvent { public: BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, // means same for all Real recoveryRates); //! This is a stronger than all event and will trigger all of them. bool matchesEventType(const ext::shared_ptr<DefaultType>&) const override { return true; } }; } #endif
40.11336
98
0.587707
jiangjiali
c1fa9f585bebd1676f0db76abb1cdc07616d0165
564
hpp
C++
Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/arc_exceptions.hpp
473867143/Prometheus
df1e1b0d861490223ac8b94d8cc4796537172292
[ "BSD-3-Clause" ]
1,217
2020-07-02T13:15:18.000Z
2022-03-31T06:17:44.000Z
Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/arc_exceptions.hpp
473867143/Prometheus
df1e1b0d861490223ac8b94d8cc4796537172292
[ "BSD-3-Clause" ]
167
2020-07-12T15:35:43.000Z
2022-03-31T11:57:40.000Z
Modules/planning/FastPlanner/plan_env/ThirdParty/arc_utilities/include/arc_utilities/arc_exceptions.hpp
473867143/Prometheus
df1e1b0d861490223ac8b94d8cc4796537172292
[ "BSD-3-Clause" ]
270
2020-07-02T13:28:00.000Z
2022-03-28T05:43:08.000Z
#include <stdexcept> #include <string> #include <sstream> #ifndef ARC_EXCEPTIONS_HPP #define ARC_EXCEPTIONS_HPP #define throw_arc_exception(type, ...) arc_exceptions::ArcException<type>(__FILE__, __LINE__, __VA_ARGS__) namespace arc_exceptions { template <typename ExceptionType> inline void ArcException(const char* file, const std::size_t line, const std::string& message) { std::ostringstream stream; stream << message << ": " << file << ": " << line; throw ExceptionType(stream.str()); } } #endif // ARC_EXCEPTIONS_HPP
25.636364
106
0.702128
473867143
c1fbe2baa36ea9540f5790c317ca70f0a7a1c796
6,798
cpp
C++
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
#include "runtime/allocators/FreeListAllocator.h" #include <fmt/format.h> #include <cassert> #include <unistd.h> using namespace Shiny; using namespace Shiny::FreeListImpl; //------------------------------------------------------------------------------ FreeListAllocator::~FreeListAllocator() { reset(); } //------------------------------------------------------------------------------ void* FreeListAllocator::allocate(size_t requestedSizeInBytes) { // Support zero sized byte allocations by rounding up to one. auto sizeInBytes = (requestedSizeInBytes > 0 ? requestedSizeInBytes : 1); // Ensure the requested allocation size is rounded up to the nearest aligned // size. auto alignedSizeInBytes = align(sizeInBytes); // Search for an available free block to reuse before allocating a new block. auto block = findFreeBlock(alignedSizeInBytes); if (block == nullptr) { // No free block found - allocate a new block for this request. block = allocateBlock(alignedSizeInBytes); byteCount_ += requestedSizeInBytes; // Track the original requested byte count. // Set the start of the heap to this block if the heap hasn't been // initialized (ie this is the first allocation). if (heapRoot_ == nullptr) { heapRoot_ = block; } // Append the block to the back of the heap so it can be tracked. if (heapBack_ != nullptr) { heapBack_->next = block; } heapBack_ = block; } // Mark block as being used before returning the payload poriton back to the // caller. block->isUsed = true; return reinterpret_cast<void*>(block->data); } //------------------------------------------------------------------------------ Block* FreeListAllocator::allocateBlock(size_t sizeInBytes) { assert(sizeInBytes > 0); // Get a pointer to the current heap break (end of the heap). This will be the // beginning position of our newly allocated block. auto block = reinterpret_cast<Block*>(sbrk(0)); // Bump the heap break by the number of bytes required for this allocation, // and check for a failed allocation after doing this. auto actualSizeInBytes = getAllocationSizeInBytes(sizeInBytes); if (sbrk(actualSizeInBytes) == reinterpret_cast<void*>(-1)) { throw OutOfMemoryException( fmt::format( "Allocation {} bytes failed because out of memory", sizeInBytes), EXCEPTION_CALLSITE_ARGS); } // Initialize header. block->sizeInBytes = sizeInBytes; block->isUsed = true; block->next = nullptr; // Update statistics before returning the block. blockCount_++; actualByteCount_ += actualSizeInBytes; return block; } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFreeBlock(size_t sizeInBytes) { return findFirstFreeFitBlock(sizeInBytes); } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFirstFreeFitBlock(size_t sizeInBytes) { // Search begins where the last block was allocated, or at the start of the // heap if this is the first find. if (findStart_ == nullptr) { findStart_ = heapRoot_; } // Look for the first block that can fit the request. // O(n) linear search. auto block = findStart_; while (block != nullptr) { // Check if this block is free and of the right size to be re-used. if (!block->isUsed && block->sizeInBytes >= sizeInBytes) { findStart_ = block; return block; } // Break out once we reach the block where the start began. if (block->next == findStart_ || (block->next == nullptr && findStart_ == heapRoot_)) { break; } // Move to the next block, or go back to the start if we've reached the end // of the heap. if (block->next == nullptr) { block = heapRoot_; } else { block = block->next; } } // Failed to find a block. return nullptr; } //------------------------------------------------------------------------------ void FreeListAllocator::destroy(void* userPointer) { // Nothing needs to be done when destroying a null pointer. if (userPointer == nullptr) { return; } freeBlock(getHeader(userPointer)); } //------------------------------------------------------------------------------ void FreeListAllocator::reset() { // Nothing to do if already reset. if (heapRoot_ == nullptr) { return; } // Check if blocks should be freed before reset. if (freeBeforeReset_) { freeHeap(); } // Reset the program data segment pointer back to where it was prior to any // allocation by this allocator. // TODO: Switch to mmap to enable multiple concurrent heaps. brk(heapRoot_); heapRoot_ = nullptr; heapBack_ = nullptr; findStart_ = nullptr; blockCount_ = 0; byteCount_ = 0; actualByteCount_ = 0; } //------------------------------------------------------------------------------ void FreeListAllocator::freeHeap() { auto block = heapRoot_; while (block != nullptr) { auto nextBlock = block->next; if (block->isUsed) { freeBlock(block); } block = nextBlock; } // TODO: Return the used space back to the operating system. // (probably once we switch to mmap). } //------------------------------------------------------------------------------ void FreeListAllocator::freeBlock(Block* block) { assert(block != nullptr); // Don't let a block be freed more than once. if (!block->isUsed) { throw DoubleFreeException( reinterpret_cast<void*>(block->data), EXCEPTION_CALLSITE_ARGS); } // Mark as free to let allocator reuse the block. block->isUsed = false; // Clear memory contents if requested. if (clearAfterFree_) { memset(reinterpret_cast<void*>(block->data), 0xC0FEFE, block->sizeInBytes); } } //------------------------------------------------------------------------------ const Block* FreeListAllocator::getHeader(void* userPointer) const { return reinterpret_cast<const Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ Block* FreeListAllocator::getHeader(void* userPointer) { return reinterpret_cast<Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ size_t FreeListAllocator::getAllocationSizeInBytes(size_t userSizeInBytes) { // Since the block structure includes the first word of user data (C++ // doesn't allow zero sized arrays), we subtract it from the size request. return userSizeInBytes + sizeof(Block) - sizeof(std::declval<Block>().data); }
31.041096
80
0.59135
smacdo
c1fd3b80a2e768b6cee18df6ee91978b3b682e92
22,473
hpp
C++
support-lib/jni/djinni_support.hpp
skabbes/djinni
814ea3571c6d936cb549fe9b17c4150178f3b4d2
[ "Apache-2.0" ]
null
null
null
support-lib/jni/djinni_support.hpp
skabbes/djinni
814ea3571c6d936cb549fe9b17c4150178f3b4d2
[ "Apache-2.0" ]
null
null
null
support-lib/jni/djinni_support.hpp
skabbes/djinni
814ea3571c6d936cb549fe9b17c4150178f3b4d2
[ "Apache-2.0" ]
null
null
null
// // Copyright 2014 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <cassert> #include <exception> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <jni.h> // work-around for missing noexcept and constexpr support in MSVC prior to 2015 #if (defined _MSC_VER) && (_MSC_VER < 1900) # define noexcept _NOEXCEPT # define constexpr #endif /* * Djinni support library */ // jni.h should really put extern "C" in JNIEXPORT, but it doesn't. :( #define CJNIEXPORT extern "C" JNIEXPORT namespace djinni { /* * Global initialization and shutdown. Call these from JNI_OnLoad and JNI_OnUnload. */ void jniInit(JavaVM * jvm); void jniShutdown(); /* * Get the JNIEnv for the invoking thread. Should only be called on Java-created threads. */ JNIEnv * jniGetThreadEnv(); /* * Exception to indicate that a Java exception is pending in the JVM. */ class jni_exception_pending : public std::exception {}; /* * Throw jni_exception_pending if any Java exception is pending in the JVM. */ void jniExceptionCheck(JNIEnv * env); /* * Set an AssertionError in env with message message, and then throw jni_exception_pending. */ #ifdef _MSC_VER __declspec(noreturn) #else __attribute__((noreturn)) #endif void jniThrowAssertionError(JNIEnv * env, const char * file, int line, const char * check); #define DJINNI_ASSERT(check, env) \ do { \ djinni::jniExceptionCheck(env); \ const bool check__res = bool(check); \ djinni::jniExceptionCheck(env); \ if (!check__res) { \ djinni::jniThrowAssertionError(env, __FILE__, __LINE__, #check); \ } \ } while(false) /* * Global and local reference guard objects. * * A GlobalRef<T> is constructed with a local reference; the constructor upgrades the local * reference to a global reference, and the destructor deletes the local ref. * * A LocalRef<T> should be constructed with a new local reference. The local reference will * be deleted when the LocalRef is deleted. */ struct GlobalRefDeleter { void operator() (jobject globalRef) noexcept; }; template <typename PointerType> class GlobalRef : public std::unique_ptr<typename std::remove_pointer<PointerType>::type, GlobalRefDeleter> { public: GlobalRef() {} GlobalRef(GlobalRef && obj) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::GlobalRefDeleter>( std::move(obj) ) {} GlobalRef(JNIEnv * env, PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::GlobalRefDeleter>( static_cast<PointerType>(env->NewGlobalRef(localRef)), ::djinni::GlobalRefDeleter{} ) {} }; struct LocalRefDeleter { void operator() (jobject localRef) noexcept; }; template <typename PointerType> class LocalRef : public std::unique_ptr<typename std::remove_pointer<PointerType>::type, LocalRefDeleter> { public: LocalRef() {} LocalRef(JNIEnv * /*env*/, PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::LocalRefDeleter>( localRef) {} explicit LocalRef(PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, LocalRefDeleter>( localRef) {} }; /* * Helper for JniClassInitializer. Copied from Oxygen. */ template <class Key, class T> class static_registration { public: using registration_map = std::unordered_map<Key, T *>; static registration_map get_all() { const std::lock_guard<std::mutex> lock(get_mutex()); return get_map(); } static_registration(const Key & key, T * obj) : m_key(key) { const std::lock_guard<std::mutex> lock(get_mutex()); get_map().emplace(key, obj); } ~static_registration() { const std::lock_guard<std::mutex> lock(get_mutex()); get_map().erase(m_key); } private: const Key m_key; static registration_map & get_map() { static registration_map m; return m; } static std::mutex & get_mutex() { static std::mutex mtx; return mtx; } }; /* * Helper for JniClass. (This can't be a subclass because it needs to not be templatized.) */ class JniClassInitializer { private: using Registration = static_registration<void *, const JniClassInitializer>; const std::function<void()> init; const Registration reg; JniClassInitializer(const std::function<void()> & init) : init(init), reg(this, this) {} template <class C> friend class JniClass; friend void jniInit(JavaVM *); }; /* * Each instantiation of this template produces a singleton object of type C which * will be initialized by djinni::jniInit(). For example: * * struct JavaFooInfo { * jmethodID foo; * JavaFooInfo() // initialize clazz and foo from jniGetThreadEnv * } * * To use this in a JNI function or callback, invoke: * * CallVoidMethod(object, JniClass<JavaFooInfo>::get().foo, ...); * * This uses C++'s template instantiation behavior to guarantee that any T for which * JniClass<T>::get() is *used* anywhere in the program will be *initialized* by init_all(). * Therefore, it's always safe to compile in wrappers for all known Java types - the library * will only depend on the presence of those actually needed. */ template <class C> class JniClass { public: static const C & get() { (void)s_initializer; // ensure that initializer is actually instantiated assert(s_singleton); return *s_singleton; } private: static const JniClassInitializer s_initializer; static std::unique_ptr<C> s_singleton; static void allocate() { // We can't use make_unique here, because C will have a private constructor and // list JniClass as a friend; so we have to allocate it by hand. s_singleton = std::unique_ptr<C>(new C()); } }; template <class C> const JniClassInitializer JniClass<C>::s_initializer ( allocate ); template <class C> std::unique_ptr<C> JniClass<C>::s_singleton; /* * Exception-checking helpers. These will throw if an exception is pending. */ GlobalRef<jclass> jniFindClass(const char * name); jmethodID jniGetStaticMethodID(jclass clazz, const char * name, const char * sig); jmethodID jniGetMethodID(jclass clazz, const char * name, const char * sig); jfieldID jniGetFieldID(jclass clazz, const char * name, const char * sig); /* * Helper for maintaining shared_ptrs to wrapped Java objects. * * This is used for automatically wrapping a Java object that exposes some interface * with a C++ object that calls back into the JVM, such as a listener. Calling * JavaProxyCache<T>::get(jobj, ...) the first time will construct a T and return a * shared_ptr to it, and also save a weak_ptr to the new object internally. The constructed * T contains a strong GlobalRef to jobj. As long as something in C++ maintains a strong * reference to the wrapper, future calls to get(jobj) will return the *same* wrapper object. * * Java | C++ * | ________________________ ___________ * _____________ | | | | | * | | | | JniImplFooListener | <=========== | Foo | * | FooListener | <============ | : public FooListener, | shared_ptr |___________| * |_____________| GlobalRef | JavaProxyCacheEntry | * | |________________________| * | ^ ______________________ * | \ | | * | - - - - - - | JavaProxyCache | * | weak_ptr | <JniImplFooListener> | * | |______________________| * * As long as the C++ FooListener has references, the Java FooListener is kept alive. * * We use a custom unordered_map with Java objects (jobject) as keys, and JNI object * identity and hashing functions. This means that as long as a key is in the map, * we must have some other GlobalRef keeping it alive. To ensure safety, the Entry * destructor removes *itself* from the map - destruction order guarantees that this * will happen before the contained global reference becomes invalid (by destruction of * the GlobalRefGuard). */ /* * Look up an entry in the global JNI wrapper cache. If none is found, create one with factory, * save it, and return it. * * The contract of `factory` is: The parameter to factory is a local ref. The factory returns * a shared_ptr to the object (JniImplFooListener, in the diagram above), as well as the * jobject *global* ref contained inside. */ std::shared_ptr<void> javaProxyCacheLookup(jobject obj, std::pair<std::shared_ptr<void>, jobject>(*factory)(jobject)); class JavaProxyCacheEntry { public: jobject getGlobalRef() { return m_globalRef.get(); } protected: JavaProxyCacheEntry(jobject localRef, JNIEnv * env); // env used only for construction JavaProxyCacheEntry(jobject localRef); virtual ~JavaProxyCacheEntry() noexcept; JavaProxyCacheEntry(const JavaProxyCacheEntry & other) = delete; JavaProxyCacheEntry & operator=(const JavaProxyCacheEntry & other) = delete; private: const GlobalRef<jobject> m_globalRef; }; template <class T> class JavaProxyCache { public: using Entry = JavaProxyCacheEntry; static std::pair<std::shared_ptr<void>, jobject> factory(jobject obj) { std::shared_ptr<T> ret = std::make_shared<T>(obj); return { ret, ret->getGlobalRef() }; } /* * Check whether a wrapped T exists for obj. If one is found, return it; if not, * construct a new one with obj, save it, and return it. */ static std::shared_ptr<T> get(jobject obj) { static_assert(std::is_base_of<JavaProxyCacheEntry, T>::value, "JavaProxyCache can only be used with T if T derives from Entry<T>"); return std::static_pointer_cast<T>(javaProxyCacheLookup(obj, &factory)); } }; /* * Cache for CppProxy objects. This is the inverse of the JavaProxyCache mechanism above, * ensuring that each time we pass an interface from Java to C++, we get the *same* CppProxy * object on the Java side: * * Java | C++ * | * ______________ | ________________ ___________ * | | | | | | | * | Foo.CppProxy | ------------> | CppProxyHandle | =============> | Foo | * |______________| (jlong) | <Foo> | (shared_ptr) |___________| * ^ | |________________| * \ | * _________ | __________________ * | | | | | * | WeakRef | <------------------------- | jniCppProxyCache | * |_________| (GlobalRef) |__________________| * | * * We don't use JNI WeakGlobalRef objects, because they last longer than is safe - a * WeakGlobalRef can still be upgraded to a strong reference even during finalization, which * leads to use-after-free. Java WeakRefs provide the right lifetime guarantee. */ /* * Information needed to use a CppProxy class. * * In an ideal world, this object would be properly always-valid RAII, and we'd use an * optional<CppProxyClassInfo> where needed. Unfortunately we don't want to depend on optional * here, so this object has an invalid state and default constructor. */ struct CppProxyClassInfo { const GlobalRef<jclass> clazz; const jmethodID constructor; const jfieldID idField; CppProxyClassInfo(const char * className); CppProxyClassInfo(); ~CppProxyClassInfo(); // Validity check explicit operator bool() const { return bool(clazz); } }; /* * Proxy cache implementation. These functions are used by CppProxyHandle::~CppProxyHandle() * and JniInterface::_toJava, respectively. They're declared in a separate class to avoid * having to templatize them. This way, all the map lookup code is only generated once, * rather than once for each T, saving substantially on binary size. (We do something simiar * in the other direction too; see javaProxyCacheLookup() above.) * * The data used by this class is declared only in djinni_support.cpp, since it's global and * opaque to all other code. */ class JniCppProxyCache { private: template <class T> friend class CppProxyHandle; static void erase(void * key); template <class I, class Self> friend class JniInterface; static jobject get(const std::shared_ptr<void> & cppObj, JNIEnv * jniEnv, const CppProxyClassInfo & proxyClass, jobject (*factory)(const std::shared_ptr<void> &, JNIEnv *, const CppProxyClassInfo &)); /* This "class" is basically a namespace, to make clear that get() and erase() should only * be used by the helper infrastructure below. */ JniCppProxyCache() = delete; }; template <class T> class CppProxyHandle { public: CppProxyHandle(std::shared_ptr<T> obj) : m_obj(move(obj)) {} ~CppProxyHandle() { JniCppProxyCache::erase(m_obj.get()); } static const std::shared_ptr<T> & get(jlong handle) { return reinterpret_cast<const CppProxyHandle<T> *>(handle)->m_obj; } private: const std::shared_ptr<T> m_obj; }; /* * Base class for Java <-> C++ interface adapters. * * I is the C++ base class (interface) being adapted; Self is the interface adapter class * derived from JniInterface (using CRTP). For example: * * class NativeToken final : djinni::JniInterface<Token, NativeToken> { ... } */ template <class I, class Self> class JniInterface { public: /* * Given a C++ object, find or create a Java version. The cases here are: * 1. Null * 2. The provided C++ object is actually a JavaProxy (C++-side proxy for Java impl) * 3. The provided C++ object has an existing CppProxy (Java-side proxy for C++ impl) * 4. The provided C++ object needs a new CppProxy allocated */ jobject _toJava(JNIEnv* jniEnv, const std::shared_ptr<I> & c) const { // Case 1 - null if (!c) { return nullptr; } // Case 2 - already a JavaProxy. Only possible if Self::JavaProxy exists. if (jobject impl = _unwrapJavaProxy<Self>(&c)) { return jniEnv->NewLocalRef(impl); } // Cases 3 and 4. assert(m_cppProxyClass); return JniCppProxyCache::get(c, jniEnv, m_cppProxyClass, &newCppProxy); } /* * Given a Java object, find or create a C++ version. The cases here are: * 1. Null * 2. The provided Java object is actually a CppProxy (Java-side proxy for a C++ impl) * 3. The provided Java object has an existing JavaProxy (C++-side proxy for a Java impl) * 4. The provided Java object needs a new JavaProxy allocated */ std::shared_ptr<I> _fromJava(JNIEnv* jniEnv, jobject j) const { // Case 1 - null if (!j) { return nullptr; } // Case 2 - already a Java proxy; we just need to pull the C++ impl out. (This case // is only possible if we were constructed with a cppProxyClassName parameter.) if (m_cppProxyClass && jniEnv->IsSameObject(jniEnv->GetObjectClass(j), m_cppProxyClass.clazz.get())) { jlong handle = jniEnv->GetLongField(j, m_cppProxyClass.idField); jniExceptionCheck(jniEnv); return CppProxyHandle<I>::get(handle); } // Cases 3 and 4 - see _getJavaProxy helper below. JavaProxyCache is responsible for // distinguishing between the two cases. Only possible if Self::JavaProxy exists. return _getJavaProxy<Self>(j); } // Constructor for interfaces for which a Java-side CppProxy class exists JniInterface(const char * cppProxyClassName) : m_cppProxyClass(cppProxyClassName) {} // Constructor for interfaces without a Java proxy class JniInterface() : m_cppProxyClass{} {} private: /* * Helpers for _toJava above. The possibility that an object is already a C++-side proxy * only exists if the code generator emitted one (if Self::JavaProxy exists). */ template <typename S, typename = typename S::JavaProxy> jobject _unwrapJavaProxy(const std::shared_ptr<I> * c) const { if (auto proxy = dynamic_cast<typename S::JavaProxy *>(c->get())) { return proxy->getGlobalRef(); } else { return nullptr; } } template <typename S> jobject _unwrapJavaProxy(...) const { return nullptr; } /* * Helper for _toJava above: given a C++ object, allocate a CppProxy on the Java side for * it. This is actually called by jniCppProxyCacheGet, which holds a lock on the global * C++-to-Java proxy map object. */ static jobject newCppProxy(const std::shared_ptr<void> & cppObj, JNIEnv * jniEnv, const CppProxyClassInfo & proxyClass) { std::unique_ptr<CppProxyHandle<I>> to_encapsulate( new CppProxyHandle<I>(std::static_pointer_cast<I>(cppObj))); jlong handle = static_cast<jlong>(reinterpret_cast<uintptr_t>(to_encapsulate.get())); jobject cppProxy = jniEnv->NewObject(proxyClass.clazz.get(), proxyClass.constructor, handle); jniExceptionCheck(jniEnv); to_encapsulate.release(); return cppProxy; } /* * Helpers for _fromJava above. We can only produce a C++-side proxy if the code generator * emitted one (if Self::JavaProxy exists). */ template <typename S, typename = typename S::JavaProxy> std::shared_ptr<I> _getJavaProxy(jobject j) const { return JavaProxyCache<typename S::JavaProxy>::get(j); } template <typename S> std::shared_ptr<I> _getJavaProxy(...) const { assert(false); return nullptr; } const CppProxyClassInfo m_cppProxyClass; }; /* * Guard object which automatically begins and ends a JNI local frame when * it is created and destroyed, using PushLocalFrame and PopLocalFrame. * * Local frame creation can fail. The throwOnError parameter specifies how * errors are reported: * - true (default): throws on failure * - false: queues a JNI exception on failure; the user must call checkSuccess() * * The JNIEnv given at construction is expected to still be valid at * destruction, so this class isn't suitable for use across threads. * It is intended for use on the stack. * * All JNI local references created within the defined scope will be * released at the end of the scope. This class doesn't support * the jobject return value supported by PopLocalFrame(), because * the destructor cannot return the new reference value for the parent * frame. */ class JniLocalScope { public: /* * Create the guard object and begin the local frame. * * @param p_env the JNIEnv for the current thread. * @param capacity the initial number of local references to * allocate. */ JniLocalScope(JNIEnv* p_env, jint capacity, bool throwOnError = true); bool checkSuccess() const { return m_success; } ~JniLocalScope(); private: JniLocalScope(const JniLocalScope& other); JniLocalScope& operator=(const JniLocalScope& other); static bool _pushLocalFrame(JNIEnv* const env, jint capacity); static void _popLocalFrame(JNIEnv* const env, jobject returnRef); JNIEnv* const m_env; const bool m_success; }; jstring jniStringFromUTF8(JNIEnv * env, const std::string & str); std::string jniUTF8FromString(JNIEnv * env, const jstring jstr); class JniEnum { public: /* * Given a Java object, find its numeric value. This returns a jint, which the caller can * static_cast<> into the necessary C++ enum type. */ jint ordinal(JNIEnv * env, jobject obj) const; /* * Create a Java value of the wrapped class with the given value. */ LocalRef<jobject> create(JNIEnv * env, jint value) const; protected: JniEnum(const std::string & name); private: const GlobalRef<jclass> m_clazz; const jmethodID m_staticmethValues; const jmethodID m_methOrdinal; }; #define DJINNI_FUNCTION_PROLOGUE0(env_) #define DJINNI_FUNCTION_PROLOGUE1(env_, arg1_) // Helper for JNI_TRANSLATE_EXCEPTIONS_RETURN. Do not call directly. void jniSetPendingFromCurrent(JNIEnv * env, const char * ctx) noexcept; /* Catch C++ exceptions and translate them to Java exceptions. * * All functions called by Java must be fully wrapped by an outer try...catch block like so: * * try { * ... * } JNI_TRANSLATE_EXCEPTIONS_RETURN(env, 0) * ... or JNI_TRANSLATE_EXCEPTIONS_RETURN(env, ) for functions returning void * * The second parameter is a default return value to be used if an exception is caught and * converted. (For JNI outer-layer calls, this result will always be ignored by JNI, so * it can safely be 0 for any function with a non-void return value.) */ #define JNI_TRANSLATE_EXCEPTIONS_RETURN(env, ret) \ catch (const std::exception &) { \ ::djinni::jniSetPendingFromCurrent(env, __func__); \ return ret; \ } } // namespace djinni
37.268657
103
0.650158
skabbes
c1fd8772618988d03f9f93e386b7fc4c4abe81d5
15,364
hpp
C++
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
#ifndef LT_MATH_HPP #define LT_MATH_HPP #include <stdio.h> #include <cmath> #include <iostream> #include <iomanip> #include <cstring> #include <type_traits> #include <limits> #include "lt_core.hpp" #include "math.h" #ifndef LT_PI #define LT_PI 3.14159265358979323846 #endif struct Point3f { f32 x, y, z; explicit Point3f(f32 x, f32 y, f32 z) : x(x), y(y), z(z) {} }; struct Size2f { f32 width, height; explicit Size2f(f32 width, f32 height) : width(width), height(height) {} }; template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, T epsilon = std::numeric_limits<T>::epsilon()) { // http://realtimecollisiondetection.net/blog/?p=89 bool almost = std::abs(x - y) <= epsilon * std::max(std::max(static_cast<T>(1), std::abs(x)), std::abs(y)); return almost; } ///////////////////////////////////////////////////////// // // Vector2 // // Definition of a vector structure. // template<typename T> union Vec2 { T val[2]; struct { T x, y; }; Vec2(): x(0), y(0) {} explicit Vec2(T k): x(k), y(k) {} explicit Vec2(T x, T y): x(x), y(y) {} inline Vec2<T> operator-(Vec2<T> rhs) const {return Vec2<T>(x - rhs.x, y - rhs.y);} }; template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f32 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f64 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator+(const Vec2<T> &a, const Vec2<T> &b) { return Vec2<T>(a.x + b.x, a.y + b.y); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec2<T> &v) { os << "(" << v.x << ", " << v.y << ")"; return os; } ///////////////////////////////////////////////////////// // // Vector3 // // Definition of a vector structure. // template<typename T> union Vec4; template<typename T> struct Vec3 { union { T val[3]; struct { T x, y, z; }; struct { T r, g, b; }; struct { T i, j, k; }; struct { Vec2<T> xy; f32 _ignored_z; }; struct { f32 _ignored_x; Vec2<T> yz; }; }; Vec3() noexcept : x(0), y(0), z(0) {} explicit Vec3(T val) noexcept : x(val), y(val), z(val) {} explicit Vec3(T x, T y, T z) noexcept : x(x), y(y), z(z) {} explicit Vec3(Vec4<T> v) noexcept : x(v.x), y(v.y), z(v.z) {} explicit Vec3(Vec2<T> v, T z) noexcept : x(v.x), y(v.y), z(z) {} inline Vec3<T> operator-(const Vec3<T>& rhs) const { return Vec3<T>(x-rhs.x, y-rhs.y, z-rhs.z); } inline Vec3<T> operator-() const { return Vec3<T>(-x, -y, -z); } inline Vec3<T> operator+(const Vec3<T>& rhs) const { return Vec3<T>(x+rhs.x, y+rhs.y, z+rhs.z); } inline Vec2<T> xz() const { return Vec2<T>(x, z); } inline void operator-=(const Vec3<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; } inline void operator+=(const Vec3<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; } }; template<typename T> inline bool operator==(const Vec3<T> &a, const Vec3<T> &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } template<> inline bool operator==<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<> inline bool operator==<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<typename T> inline bool operator!=(const Vec3<T> &a, const Vec3<T> &b) { return a.x != b.x && a.y != b.y && a.z != b.z; } template<> inline bool operator!=<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<> inline bool operator!=<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec3<T> &v) { os << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return os; } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f32 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f32 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f64 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f64 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } ///////////////////////////////////////////////////////// // // Vector4 // // Definition of a vector structure. // template<typename T> union Vec4 { T val[4]; struct { T x, y, z, w; }; struct { T r, g, b, a; }; Vec4(): x(0), y(0), z(0), w(0) {} explicit Vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {} explicit Vec4(const Vec3<T>& v, T w): x(v.x), y(v.y), z(v.z), w(w) {} }; namespace lt { template<typename T> inline T norm(const Vec4<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); } template<typename T> inline T norm(const Vec3<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } template<typename T> inline T norm(const Vec2<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y); } template<typename T> inline Vec2<T> normalize(const Vec2<T>& v) { return Vec2<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v)); } template<typename T> inline Vec3<T> normalize(const Vec3<T>& v) { const f32 EPSILON = 0.0001f; f32 length = lt::norm(v); if (length <= EPSILON) return v; return Vec3<T>(v.x/length, v.y/length, v.z/length); } template<typename T> inline Vec4<T> normalize(const Vec4<T>& v) { return Vec4<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v), v.w /lt::norm(v)); } template<typename T> inline T radians(T angle) { return angle * (static_cast<T>(M_PI) / static_cast<T>(180)); } template<typename T> inline T degrees(T angle) { return angle * (static_cast<T>(180) / static_cast<T>(M_PI)); } template<typename T> inline T dot(const Vec2<T>& a, const Vec2<T>& b) { return (a.x * b.x) + (a.y * b.y); } template<typename T> inline T dot(const Vec3<T>& lhs, const Vec3<T>& rhs) { return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z); } template<typename T> inline Vec2<T> projection(const Vec2<T>& p, const Vec2<T>& plane) { f32 alpha = lt::dot(p, plane) / lt::dot(plane, plane); return alpha * plane; } template<typename T> inline Vec3<T> cross(const Vec3<T>& a, const Vec3<T>& b) { return Vec3<T>((a.y * b.z) - (a.z * b.y), (a.z * b.x) - (a.x * b.z), (a.x * b.y) - (a.y * b.x)); } } ///////////////////////////////////////////////////////// // // Matrix // // Column major // union Mat4f { Mat4f(); explicit Mat4f(f32 diag); explicit Mat4f(f32 m00, f32 m01, f32 m02, f32 m03, f32 m10, f32 m11, f32 m12, f32 m13, f32 m20, f32 m21, f32 m22, f32 m23, f32 m30, f32 m31, f32 m32, f32 m33); inline f32 operator()(isize row, isize col) const { return m_col[col].val[row]; } inline f32& operator()(isize row, isize col) { return m_col[col].val[row]; } inline Vec4<f32> col(isize col) { return m_col[col]; } inline f32 *data() const { return (f32*)&m_col[0].val[0]; } Mat4f operator*(const Mat4f& rhs); private: Vec4<f32> m_col[4]; }; inline std::ostream &operator<<(std::ostream& os, const Mat4f &mat) { for (i32 row = 0; row < 4; row++) { os << "| "; for (i32 col = 0; col < 4; col++) { os << std::setw(9) << std::setprecision(3) << mat(row, col) << " "; } os << "|\n"; } return os; } inline Mat4f operator*(const Mat4f &lhs, const Mat4f &rhs) { Mat4f ret(1.0); // First row ret(0,0) = lhs(0,0)*rhs(0,0) + lhs(0,1)*rhs(1,0) + lhs(0,2)*rhs(2,0) + lhs(0,3)*rhs(3,0); ret(0,1) = lhs(0,0)*rhs(0,1) + lhs(0,1)*rhs(1,1) + lhs(0,2)*rhs(2,1) + lhs(0,3)*rhs(3,1); ret(0,2) = lhs(0,0)*rhs(0,2) + lhs(0,1)*rhs(1,2) + lhs(0,2)*rhs(2,2) + lhs(0,3)*rhs(3,2); ret(0,3) = lhs(0,0)*rhs(0,3) + lhs(0,1)*rhs(1,3) + lhs(0,2)*rhs(2,3) + lhs(0,3)*rhs(3,3); // Second row ret(1,0) = lhs(1,0)*rhs(0,0) + lhs(1,1)*rhs(1,0) + lhs(1,2)*rhs(2,0) + lhs(1,3)*rhs(3,0); ret(1,1) = lhs(1,0)*rhs(0,1) + lhs(1,1)*rhs(1,1) + lhs(1,2)*rhs(2,1) + lhs(1,3)*rhs(3,1); ret(1,2) = lhs(1,0)*rhs(0,2) + lhs(1,1)*rhs(1,2) + lhs(1,2)*rhs(2,2) + lhs(1,3)*rhs(3,2); ret(1,3) = lhs(1,0)*rhs(0,3) + lhs(1,1)*rhs(1,3) + lhs(1,2)*rhs(2,3) + lhs(1,3)*rhs(3,3); // Third row ret(2,0) = lhs(2,0)*rhs(0,0) + lhs(2,1)*rhs(1,0) + lhs(2,2)*rhs(2,0) + lhs(2,3)*rhs(3,0); ret(2,1) = lhs(2,0)*rhs(0,1) + lhs(2,1)*rhs(1,1) + lhs(2,2)*rhs(2,1) + lhs(2,3)*rhs(3,1); ret(2,2) = lhs(2,0)*rhs(0,2) + lhs(2,1)*rhs(1,2) + lhs(2,2)*rhs(2,2) + lhs(2,3)*rhs(3,2); ret(2,3) = lhs(2,0)*rhs(0,3) + lhs(2,1)*rhs(1,3) + lhs(2,2)*rhs(2,3) + lhs(2,3)*rhs(3,3); // Fourth row ret(3,0) = lhs(3,0)*rhs(0,0) + lhs(3,1)*rhs(1,0) + lhs(3,2)*rhs(2,0) + lhs(3,3)*rhs(3,0); ret(3,1) = lhs(3,0)*rhs(0,1) + lhs(3,1)*rhs(1,1) + lhs(3,2)*rhs(2,1) + lhs(3,3)*rhs(3,1); ret(3,2) = lhs(3,0)*rhs(0,2) + lhs(3,1)*rhs(1,2) + lhs(3,2)*rhs(2,2) + lhs(3,3)*rhs(3,2); ret(3,3) = lhs(3,0)*rhs(0,3) + lhs(3,1)*rhs(1,3) + lhs(3,2)*rhs(2,3) + lhs(3,3)*rhs(3,3); return ret; } namespace lt { Mat4f perspective(f32 fovy, f32 aspect_ratio, f32 znear, f32 zfar); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top, f32 near, f32 far); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top); Mat4f look_at(const Vec3<f32> eye, const Vec3<f32> center, const Vec3<f32> up); Mat4f translation(const Mat4f &in_mat, Vec3<f32> amount); Mat4f scale(const Mat4f &in_mat, Vec3<f32> scale); inline Mat4f rotation_x(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(1, 0, 0, 0, 0, cos(rad), -sin(rad), 0, 0, sin(rad), cos(rad), 0, 0, 0, 0, 1); } inline Mat4f rotation_y(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(cos(rad), 0, sin(rad), 0, 0, 1, 0, 0, -sin(rad), 0, cos(rad), 0, 0, 0, 0, 1); } } ///////////////////////////////////////////////////////// // // Quaternion // // Definition of a quaternion structure. // // Some properties (not necessarily complete): // - Not comutative (q1q2 != q2q1) // - Associative ((q1q2)q3 == q1(q2q3)) // - The quaternion (1, 0, 0, 0) maps to the identity matrix. // template<typename T> union Quat { T val[4]; struct { T s; Vec3<T> v; }; explicit Quat(T s, T i, T j, T k) : val{s, i, j, k} {} explicit Quat(T s, const Vec3<T>& v) : s(s), v(v) {} Quat() : s(0), v(Vec3<T>(0, 0, 0)) {} static inline Quat<T> identity() { return Quat<T>(1, 0, 0, 0); } static inline Quat<T> rotation(T angle, const Vec3<T>& axis) { Vec3<T> sin_axis = axis * std::sin(angle/static_cast<T>(2)); return Quat<T>(std::cos(angle/static_cast<T>(2)), sin_axis); } Mat4f to_mat4() const { return Mat4f(s, -v.i, -v.j, -v.k, v.i, s, -v.k, v.j, v.j, v.k, s, -v.i, v.k, -v.j, v.i, s); } inline Quat<T> operator+(const Quat<T>& rhs) const { return Quat<T>(s+rhs.s, v.i+rhs.v.i, v.j+rhs.v.j, v.k+rhs.v.k); } inline Quat<T> operator/(T k) const { return Quat<T>(val[0]/k, val[1]/k, val[2]/k, val[3]/k); } }; template<typename T> inline Quat<T> operator*(const Quat<T> &q, T k) { return Quat<T>(q.s*k, q.v*k); } template<typename T> inline Quat<T> operator*(T k, const Quat<T> &q) { return Quat<T>(q.s*k, q.v*k); } template<typename T> static inline Quat<T> operator*(const Quat<T>& lhs, const Quat<T>& rhs) { return Quat<T>((lhs.s*rhs.s) - lt::dot(lhs.v, rhs.v), rhs.s*lhs.v + lhs.s*rhs.v + lt::cross(lhs.v, rhs.v)); } template<typename T> inline std::ostream & operator<<(std::ostream &os, const Quat<T> &q) { os << "(" << std::setprecision(3) << q.val[0] << ", "; os << q.val[1] << ", " << q.val[2] << ", " << q.val[3] << ")"; return os; } template<typename T> inline bool operator==(const Quat<T> &a, const Quat<T> &b) { return (a.val[0] == b.val[0]) && (a.val[1] == b.val[1]) && (a.val[2] == b.val[2]) && (a.val[3] == b.val[3]); } template<> inline bool operator==<f32>(const Quat<f32> &a, const Quat<f32> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } template<> inline bool operator==<f64>(const Quat<f64> &a, const Quat<f64> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } namespace lt { template<typename T> inline T norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return std::sqrt(v); } template<typename T> inline T sqr_norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return v; } template<typename T> inline Quat<T> normalize(const Quat<T> &q) { return Quat<T>(q.s/lt::norm(q), q.v.i/lt::norm(q), q.v.j/lt::norm(q), q.v.k/lt::norm(q)); } template<typename T> inline Quat<T> conjugate(const Quat<T> &q) { return Quat<T>(q.s, -q.v); } template<typename T> inline Quat<T> inverse(const Quat<T> &q) { Quat<T> inv = lt::conjugate(q) / lt::sqr_norm(q); LT_Assert(q*inv == Quat<T>::identity()); return inv; } template<typename T> inline Quat<T> rotate(const Quat<T> &q, T angle, const Quat<T> &axis) { const Quat<T> rotor = Quat<T>::rotation(angle, axis.v); return rotor * q * lt::inverse(rotor); } template<typename T> T dot(const Quat<T> &a, const Quat<T> &b) { return a.val[0]*b.val[0] + a.val[1]*b.val[1] + a.val[2]*b.val[2] + a.val[3]*b.val[3]; } template<typename T> Quat<T> slerp(const Quat<T> &start_q, const Quat<T> &end_q, T t) { LT_Assert(t >= 0); LT_Assert(t <= 1); const T EPSILON = static_cast<T>(0.0001); // FIXME: Find a more specific epsilon value here. T start_dot_end = lt::dot(start_q, end_q); if (start_dot_end < 1-EPSILON) { T angle = std::acos(start_dot_end); LT_Assert(angle != static_cast<T>(0)); return (std::sin((static_cast<T>(1) - t) * angle) * start_q + std::sin(t * angle) * end_q) / std::sin(angle); } else { return start_q; } } } typedef Vec2<i32> Vec2i; typedef Vec2<f32> Vec2f; typedef Vec3<i32> Vec3i; typedef Vec3<f32> Vec3f; typedef Vec4<i32> Vec4i; typedef Vec4<f32> Vec4f; typedef Quat<f32> Quatf; typedef Quat<f64> Quatd; #endif // LT_MATH_HPP
25.269737
108
0.545236
leohahn
c1fdca1d9b2367b6916e34a6037e56024d0d6e57
1,190
cpp
C++
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
1
2021-08-31T22:32:22.000Z
2021-08-31T22:32:22.000Z
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
null
null
null
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define LINHAS 2 #define COLUNAS 50 void calculeAreas(double triangulos[LINHAS][COLUNAS], double areas[]) { for (int i = 0; i < COLUNAS; i++) { areas[i] = (triangulos[0][i] * triangulos[1][i]) / 2; cout << "A área do " << i + 1 << "º triângulo é " << areas[i] << endl; } } void imprimaMatriz(double matriz[LINHAS][COLUNAS]) { int j = 0; cout << "[" << endl; for (int i = 0; i < LINHAS; i++) { j = 0; cout << "[" << matriz[i][j] << ", "; for (j = 1; j < COLUNAS - 1; j++) { cout << matriz[i][j] << ", "; } cout << matriz[i][j] << "]," << endl; } cout << "]" << endl; } int main() { double matriz[LINHAS][COLUNAS] = { {12, 5, 6, 7, 6, 9, 8, 3, 6, 10, 2, 7, 6, 9, 2, 5, 9, 5, 9, 5, 9, 6, 3, 10, 7, 10, 4, 5, 1, 9, 6, 6, 5, 1, 4, 10, 9, 1, 2, 7, 3, 6, 3, 8, 6, 4, 5, 5, 10, 3}, {23, 8, 10, 5, 8, 7, 4, 3, 1, 4, 3, 8, 2, 7, 1, 5, 6, 1, 8, 10, 7, 10, 7, 9, 9, 2, 5, 3, 8, 4, 7, 8, 2, 9, 2, 1, 5, 5, 3, 7, 1, 5, 4, 4, 3, 4, 10, 10, 7, 7}}; double areas[COLUNAS] = {}; imprimaMatriz(matriz); calculeAreas(matriz, areas); return 0; }
28.333333
74
0.457983
GE28
c1fe001e93703950318908c961a80d6fb92f1ba1
520
hpp
C++
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
#pragma once #include <string_view> #include <opencv2/opencv.hpp> #include "GeneratorStage.hpp" #include "FilterStage.hpp" #include "ContourDetectionStage.hpp" class ContourPlotStage : public FilterStage { public: ContourPlotStage(GeneratorStage &input, ContourDetectionStage &contour); void Execute(); std::string_view GetStageName() const { return "ContourPlotStage"; }; cv::Mat GetOutputImage() { return output; }; private: cv::Mat output; ContourDetectionStage contour; cv::RNG rng; };
24.761905
76
0.736538
edroque93
c1ffdcade3e2d8f7923a37f7155b08bf8740d39f
2,228
cpp
C++
aws-cpp-sdk-macie2/source/model/IpAddressDetails.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-macie2/source/model/IpAddressDetails.cpp
lintonv/aws-sdk-cpp
15e19c265ffce19d2046b18aa1b7307fc5377e58
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-macie2/source/model/IpAddressDetails.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/macie2/model/IpAddressDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Macie2 { namespace Model { IpAddressDetails::IpAddressDetails() : m_ipAddressV4HasBeenSet(false), m_ipCityHasBeenSet(false), m_ipCountryHasBeenSet(false), m_ipGeoLocationHasBeenSet(false), m_ipOwnerHasBeenSet(false) { } IpAddressDetails::IpAddressDetails(JsonView jsonValue) : m_ipAddressV4HasBeenSet(false), m_ipCityHasBeenSet(false), m_ipCountryHasBeenSet(false), m_ipGeoLocationHasBeenSet(false), m_ipOwnerHasBeenSet(false) { *this = jsonValue; } IpAddressDetails& IpAddressDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ipAddressV4")) { m_ipAddressV4 = jsonValue.GetString("ipAddressV4"); m_ipAddressV4HasBeenSet = true; } if(jsonValue.ValueExists("ipCity")) { m_ipCity = jsonValue.GetObject("ipCity"); m_ipCityHasBeenSet = true; } if(jsonValue.ValueExists("ipCountry")) { m_ipCountry = jsonValue.GetObject("ipCountry"); m_ipCountryHasBeenSet = true; } if(jsonValue.ValueExists("ipGeoLocation")) { m_ipGeoLocation = jsonValue.GetObject("ipGeoLocation"); m_ipGeoLocationHasBeenSet = true; } if(jsonValue.ValueExists("ipOwner")) { m_ipOwner = jsonValue.GetObject("ipOwner"); m_ipOwnerHasBeenSet = true; } return *this; } JsonValue IpAddressDetails::Jsonize() const { JsonValue payload; if(m_ipAddressV4HasBeenSet) { payload.WithString("ipAddressV4", m_ipAddressV4); } if(m_ipCityHasBeenSet) { payload.WithObject("ipCity", m_ipCity.Jsonize()); } if(m_ipCountryHasBeenSet) { payload.WithObject("ipCountry", m_ipCountry.Jsonize()); } if(m_ipGeoLocationHasBeenSet) { payload.WithObject("ipGeoLocation", m_ipGeoLocation.Jsonize()); } if(m_ipOwnerHasBeenSet) { payload.WithObject("ipOwner", m_ipOwner.Jsonize()); } return payload; } } // namespace Model } // namespace Macie2 } // namespace Aws
18.566667
69
0.716338
lintonv
de007515b2da63587cc6a500ff9665679cf2c254
86,107
cpp
C++
Src/lunaui/cards/CardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/lunaui/cards/CardWindowManager.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/cards/CardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * LICENSE@@@ */ #include "Common.h" #include "CardWindowManager.h" #include <QGesture> #include "ApplicationDescription.h" #include "AnimationSettings.h" #include "CardWindow.h" #include "HostBase.h" #include "Logging.h" #include "Settings.h" #include "SoundPlayerPool.h" #include "SystemService.h" #include "SystemUiController.h" #include "Time.h" #include "Window.h" #include "WindowServer.h" #include "Utils.h" #include "CardWindowManagerStates.h" #include "CardGroup.h" #include "FlickGesture.h" #include "GhostCard.h" #include "IMEController.h" #include <QTapGesture> #include <QTapAndHoldGesture> #include <QPropertyAnimation> static int kGapBetweenGroups = 0; static qreal kActiveScale = 0.659; static qreal kNonActiveScale = 0.61; static const qreal kWindowOriginRatio = 0.40; static int kWindowOrigin = 0; static int kWindowOriginMax = 0; static const qreal kMinimumWindowScale = 0.26; static int kMinimumHeight = 0; static const int kFlickToCloseWindowVelocityThreshold = -1100; static const int kFlickToCloseWindowDistanceThreshold = -50; static const int kFlickToCloseWindowMinimumVelocity = -500; static const int kModalWindowAnimationTimeout = 45; static const int s_marginSlice = 5; int kAngryCardThreshold = 0; // ------------------------------------------------------------------------------------------------------------- CardWindowManager::CardWindowManager(int maxWidth, int maxHeight) : WindowManagerBase(maxWidth, maxHeight) , m_activeGroup(0) , m_draggedWin(0) , m_penDown(false) , m_cardToRestoreToMaximized(0) , m_lowResMode(false) , m_movement(MovementUnlocked) , m_trackWithinGroup(true) , m_seenFlickOrTap(false) , m_activeGroupPivot(0) , m_reorderZone(ReorderZone_Center) , m_stateMachine(0) , m_minimizeState(0) , m_maximizeState(0) , m_preparingState(0) , m_loadingState(0) , m_focusState(0) , m_reorderState(0) , m_curState(0) , m_addingModalWindow(false) , m_initModalMaximizing(false) , m_parentOfModalCard(0) , m_modalDismissInProgress(false) , m_modalDimissed(false) , m_dismissModalImmediately(-1) , m_animateWindowForModalDismisal(true) , m_modalWindowState(NoModalWindow) , m_playedAngryCardStretchSound(false) , m_animationsActive(false) { setObjectName("CardWindowManager"); SystemUiController* sysui = SystemUiController::instance(); connect(sysui, SIGNAL(signalPositiveSpaceAboutToChange(const QRect&, bool, bool)), SLOT(slotPositiveSpaceAboutToChange(const QRect&, bool, bool))); connect(sysui, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)), SLOT(slotPositiveSpaceChangeFinished(const QRect&))); connect(sysui, SIGNAL(signalPositiveSpaceChanged(const QRect&)), SLOT(slotPositiveSpaceChanged(const QRect&))); connect(sysui, SIGNAL(signalLauncherVisible(bool, bool)), SLOT(slotLauncherVisible(bool, bool))); connect(sysui, SIGNAL(signalLauncherShown(bool)), SLOT(slotLauncherShown(bool))); connect(sysui, SIGNAL(signalMaximizeActiveCardWindow()), SLOT(slotMaximizeActiveCardWindow())); connect(sysui, SIGNAL(signalMinimizeActiveCardWindow()), SLOT(slotMinimizeActiveCardWindow())); connect(sysui, SIGNAL(signalChangeCardWindow(bool)), SLOT(slotChangeCardWindow(bool))); connect(sysui, SIGNAL(signalFocusMaximizedCardWindow(bool)), SLOT(slotFocusMaximizedCardWindow(bool))); connect(SystemService::instance(), SIGNAL(signalTouchToShareAppUrlTransfered(const std::string&)), SLOT(slotTouchToShareAppUrlTransfered(const std::string&))); connect(SystemService::instance(), SIGNAL(signalDismissModalDialog()), SLOT(slotDismissActiveModalWindow())); connect(SystemService::instance(), SIGNAL(signalStopModalDismissTimer()), SLOT(slotDismissModalTimerStopped())); connect(&m_anims, SIGNAL(finished()), SLOT(slotAnimationsFinished())); grabGesture(Qt::TapGesture); grabGesture(Qt::TapAndHoldGesture); grabGesture((Qt::GestureType) SysMgrGestureFlick); } CardWindowManager::~CardWindowManager() { // doesn't reach here } void CardWindowManager::init() { kGapBetweenGroups = Settings::LunaSettings()->gapBetweenCardGroups; if (g_file_test(Settings::LunaSettings()->firstCardLaunch.c_str(), G_FILE_TEST_EXISTS)){ m_dismissedFirstCard=true; } else{ m_dismissedFirstCard=false; } // register CardWindow::Position types for use as Q_PROPERTY's qRegisterMetaType<CardWindow::Position>("CardWindow::Position"); qRegisterAnimationInterpolator<CardWindow::Position>(positionInterpolator); // needed in order for CardWindow pointers to be used with queued signal and slot // connections, i.e. QStateMachine signal transitions qRegisterMetaType<CardWindow*>("CardWindow*"); m_stateMachine = new QStateMachine(this); // setup our states m_minimizeState = new MinimizeState(this); m_maximizeState = new MaximizeState(this); m_preparingState = new PreparingState(this); m_loadingState = new LoadingState(this); m_focusState = new FocusState(this); m_reorderState = new ReorderState(this); m_stateMachine->addState(m_minimizeState); m_stateMachine->addState(m_maximizeState); m_stateMachine->addState(m_preparingState); m_stateMachine->addState(m_loadingState); m_stateMachine->addState(m_focusState); m_stateMachine->addState(m_reorderState); // connect allowed state transitions m_minimizeState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_minimizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_minimizeState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_minimizeState->addTransition(this, SIGNAL(signalEnterReorder(QPoint, int)), m_reorderState); m_maximizeState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_maximizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_maximizeState->addTransition(new MaximizeToFocusTransition(this, m_focusState)); m_focusState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_focusState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_focusState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_focusState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_preparingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_preparingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalLoadingActiveWindow()), m_loadingState); m_loadingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_loadingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_loadingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_reorderState->addTransition(this, SIGNAL(signalExitReorder(bool)), m_minimizeState); // start off minimized m_stateMachine->setInitialState(m_minimizeState); m_stateMachine->start(); updateAngryCardThreshold(); } bool CardWindowManager::handleNavigationEvent(QKeyEvent* keyEvent, bool& propogate) { propogate = false; return m_curState->handleKeyNavigation(keyEvent); } bool CardWindowManager::okToResize() { if(m_anims.state() != QAbstractAnimation::Stopped) return false; return true; } void CardWindowManager::updateAngryCardThreshold() { kAngryCardThreshold = ((boundingRect().height() / 2) * 0.30); } void CardWindowManager::resize(int width, int height) { // accept requests for resizing to the current dimensions, in case we are doing a force resize due to // previous cancelation of Card Window flip operations. WindowManagerBase::resize(width, height); m_normalScreenBounds = QRect(0, Settings::LunaSettings()->positiveSpaceTopPadding, SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight() - Settings::LunaSettings()->positiveSpaceTopPadding); kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = SystemUiController::instance()->positiveSpaceBounds(); kWindowOrigin = boundingRect().y() + ((m_normalScreenBounds.y() + 48) + (int) ((m_normalScreenBounds.height() - 48) * kWindowOriginRatio)); updateAngryCardThreshold(); if(m_groups.size() > 0) { int index = m_groups.indexOf(m_activeGroup); // first resize the active group m_groups[index]->resize(width, height, m_normalScreenBounds); m_groups[index]->setY(kWindowOrigin); // resize the group to the left of the active group if(index > 0) { m_groups[index-1]->resize(width, height, m_normalScreenBounds); m_groups[index-1]->setY(kWindowOrigin); } // resize the group to the right of the active group if(index < m_groups.size()-1) { m_groups[index+1]->resize(width, height, m_normalScreenBounds); m_groups[index+1]->setY(kWindowOrigin); } // now resize the other groups, if there are any if(index-1 > 0) { // left side for(int x = index-2; x >= 0; x--) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } if(index+1 < m_groups.size()-1) { // right side for(int x = index+2; x < m_groups.size(); x++) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } } m_curState->relayout(m_boundingRect, false); } void CardWindowManager::removeAnimationForWindow(CardWindow* win, bool includeDeletedAnimations) { if ((m_curState != m_maximizeState) && m_penDown && !includeDeletedAnimations) win->allowUpdates(false); else win->allowUpdates(true); if (m_cardAnimMap.contains(win)) { QPropertyAnimation* a = m_cardAnimMap.value(win); m_anims.removeAnimation(a); m_cardAnimMap.remove(win); delete a; } if (includeDeletedAnimations) { QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.find(win); if (it != m_deletedAnimMap.end()) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (a) { m_deletedAnimMap.erase(it); delete a; } } } } bool CardWindowManager::windowHasAnimation(CardWindow* win) const { return m_cardAnimMap.contains(win) || m_deletedAnimMap.contains(win); } void CardWindowManager::setAnimationForWindow(CardWindow* win, QPropertyAnimation* anim) { removeAnimationForWindow(win); m_cardAnimMap.insert(win, anim); m_anims.addAnimation(anim); } void CardWindowManager::setAnimationForGroup(CardGroup* group, QPropertyAnimation* anim) { removeAnimationForGroup(group); m_groupAnimMap.insert(group, anim); m_anims.addAnimation(anim); } void CardWindowManager::removeAnimationForGroup(CardGroup* group) { if (m_groupAnimMap.contains(group)) { QPropertyAnimation* a = m_groupAnimMap.value(group); m_anims.removeAnimation(a); m_groupAnimMap.remove(group); delete a; } } bool CardWindowManager::groupHasAnimation(CardGroup* group) const { return m_groupAnimMap.contains(group); } void CardWindowManager::startAnimations() { m_animationsActive = true; updateAllowWindowUpdates(); m_anims.start(); } void CardWindowManager::clearAnimations() { m_anims.stop(); m_anims.clear(); m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::resetMouseTrackState() { m_draggedWin = 0; m_penDown = false; updateAllowWindowUpdates(); m_trackWithinGroup = true; m_seenFlickOrTap = false; m_playedAngryCardStretchSound = false; m_movement = MovementUnlocked; } int CardWindowManager::proceedToAddModalWindow(CardWindow* win) { Window* maxCardWindow = SystemUiController::instance()->maximizedCardWindow(); CardWindow* activeWin = activeWindow(); // Check if we have an active card if(!maxCardWindow || !activeWin) return SystemUiController::NoMaximizedCard; // Check if the active window is the same as the maximized window if(activeWin != maxCardWindow) return SystemUiController::ParentDifferent; // Get the id of the currently active window ApplicationDescription* desc = activeWin->appDescription(); if(desc) { std::string id = desc->id(); if(id.length() > 0) { // Compare with what the card thinks it's caller is if((0 == win->launchingAppId().compare(id) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } else { // If it's a PDK app and we have no appDescription, comparing to appId if(activeWin->isHost()) { if((0 == win->launchingAppId().compare(activeWin->appId()) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } return SystemUiController::LaunchUnknown; } void CardWindowManager::prepareAddWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; if ((card->hostWindowData() != 0) && !card->isHost() && (card->type() != Window::Type_ModalChildWindowCard) && (card->getCardFixedOrientation() == Event::Orientation_Invalid)) { // safeguard code in case the data card was launched right before we changed orientation, resulting // in possibly a landscape card in portrait mode or vice versa bool isCardLandscape = card->hostWindowData()->width() >= card->hostWindowData()->height(); bool isUiLandscape = SystemUiController::instance()->currentUiWidth() >= SystemUiController::instance()->currentUiHeight(); if(isCardLandscape != isUiLandscape) { // we need to resize this card card->flipEventSync(); } } // Proxy cards don't have to wait if (!card->isHost()) { // delay adding a new card if (card->delayPrepare()) { return; } } // If we have a modal card and we cannot add it for whatever reason, just return if(Window::Type_ModalChildWindowCard == win->type() && (SystemUiController::NoErr != (m_dismissModalImmediately = proceedToAddModalWindow(card)))) { m_modalWindowState = ModalWindowAddInitCheckFail; notifySysControllerOfModalStatus(m_dismissModalImmediately, false, ModalLaunch, win); return; } Q_EMIT signalExitReorder(); card->enableShadow(); // Do this ONLY if we are not adding a MODAL window if(Window::Type_ModalChildWindowCard != card->type()) { // If the currently active card is a modal card, make sure we dismiss it as we are going to get a new active card - don't restore the state as the new card will be the active card if(activeWindow() && Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedParentSwitched; notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } card->setParentItem(this); } else { m_parentOfModalCard = activeWindow(); // Set the desired fields for the modal card. card->setModalParent(m_parentOfModalCard); // Set the desired fields for the parent of the modal card. m_parentOfModalCard->setCardIsModalParent(true); m_parentOfModalCard->setModalChild(card); m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedNotAcceptingInput); // Let the modal window compute it's initial position card->computeModalWindowPlacementInf(-1); // Set the fact that we are adding a modal window m_addingModalWindow = true; } disableCardRestoreToMaximized(); Q_EMIT signalPreparingWindow(card); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::prepareAddWindowSibling(CardWindow* win) { if (m_activeGroup && !win->launchInNewGroup()) { CardWindow* activeWin = m_activeGroup->activeCard(); if(Window::Type_ModalChildWindowCard != win->type()) { if ((activeWin->focused() && (win->launchingProcessId() == activeWin->processId() || (win->launchingAppId() == activeWin->appId())))) { // add to active group m_activeGroup->addToFront(win); setActiveGroup(m_activeGroup); m_cardToRestoreToMaximized = activeWin; } else { // spawn new group to the right of active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.insert(m_groups.indexOf(m_activeGroup)+1, newGroup); setActiveGroup(newGroup); } queueFocusAction(activeWin, false); setActiveCardOffScreen(); slideAllGroups(false); startAnimations(); } else { queueFocusAction(activeWin, false); } } else { CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.append(newGroup); setActiveGroup(newGroup); setActiveCardOffScreen(); } SystemUiController::instance()->setCardWindowAboutToMaximize(); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::addWindowTimedOut(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); // Host windows shouldn't fire this handler anyways if (card->isHost()) return; if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalExitReorder(); m_curState->windowTimedOut(card); SystemUiController::instance()->cardWindowTimeout(); } void CardWindowManager::addWindowTimedOutNormal(CardWindow* win) { m_penDown = false; updateAllowWindowUpdates(); Q_ASSERT(m_activeGroup && m_activeGroup->activeCard() == win); if(Window::Type_ModalChildWindowCard != win->type()) { setActiveCardOffScreen(false); slideAllGroups(); } if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalLoadingActiveWindow(); } void CardWindowManager::addWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); card->setAddedToWindowManager(); // process addWindow once preparing has finished if (!card->isHost() && !card->prepareAddedToWindowManager()) return; Q_EMIT signalExitReorder(); m_curState->windowAdded(card); } void CardWindowManager::removeWindow(Window* win) { if(!win) return; CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; Q_EMIT signalExitReorder(); // Either there are no modal window(s) OR we are not deleting the modal parent - default to the plain vanilla delete. if((win->type() != Window::Type_ModalChildWindowCard && false == m_addingModalWindow) || (win->type() != Window::Type_ModalChildWindowCard && false == card->isCardModalParent())) { removeWindowNoModality(card); } else removeWindowWithModality(card); } void CardWindowManager::removeWindowNoModality(CardWindow* win) { if(!win) return; QPropertyAnimation* anim = NULL; if(false == performCommonWindowRemovalTasks(win, true)) return; // slide card off the top of the screen CardWindow::Position pos = win->position(); QRectF r = pos.toTransform().mapRect(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); anim = new QPropertyAnimation(win, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); m_curState->windowRemoved(win); } void CardWindowManager::removeWindowWithModality(CardWindow* win) { CardWindow* card = NULL, *activeCard = NULL; QPropertyAnimation* anim = NULL; bool restore = false; if(!win) return; activeCard = activeWindow(); if(!activeCard) return; card = win; restore = (activeCard == card && Window::Type_ModalChildWindowCard == card->type()) ? true:false; // If the modal card was deleted because it's parent was deleted externally, don't run any of these, simply remove the modal and return if(Window::Type_ModalChildWindowCard == card->type() && m_modalWindowState == ModalParentDimissedWaitForChildDismissal && NULL == m_parentOfModalCard) { handleModalRemovalForDeletedParent(card); m_modalWindowState = NoModalWindow; return; } /* This function is called externally by some component when it wants the CardWindow to go away. Also when ::closeWindow's call to win->close will result in a call to this function. For the modal windows, we have 2 cases to consider. 1) ::removeWindow is called on a modal window by an external component. 2) ::removeWindow is called on a modal window by as a result of a call to ::closeWindow. We also need to consider the case if the modal was even added. */ // This is not a part of a call to closeWindow and came by externally. This means there is NO need to call close on the window again. if(false == m_modalDismissInProgress) { SystemUiController::ModalWinDismissErrorReason dismiss = SystemUiController::DismissUnknown; // We are removing a modal card externally if(Window::Type_ModalChildWindowCard == card->type()) { m_modalWindowState = ModalWindowDismissedExternally; } // check if w is a modal parent else if(true == card->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; dismiss = SystemUiController::ParentCardDismissed; } notifySysControllerOfModalStatus(dismiss, restore, ModalDismissNoAnimate); } else { m_modalDismissInProgress = false; } // Signal that we no longer have an active modal window - Either the modal is getting dismissed/parent is getting dismissed/modal add failed as the parent was different etc if(true == restore || m_modalWindowState == ModalParentDismissed || m_modalWindowState == ModalWindowAddInitCheckFail || m_modalWindowState == ModalWindowDismissedParentSwitched) SystemUiController::instance()->notifyModalWindowDeactivated(); // Reset in different ways (if true == restore => modal card was added successfully and is the card being deleted. if(true == restore) resetModalFlags(); // If we are deleting the modal card because of a failure during initialization, just reset the flags here. else if(m_modalWindowState == ModalWindowAddInitCheckFail) resetModalFlags(true); else if(m_modalWindowState == ModalParentDismissed) { // modal parent is deleted - Do the following to make things smoother. // 1 - Make the modal card invisible. // 2 - Set that the parent no longer has a modal child. (Don't reset the state) activeCard->setVisible(false); if(m_parentOfModalCard) { m_parentOfModalCard->setCardIsModalParent(false); m_parentOfModalCard->setModalChild(NULL); m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } else if(m_modalWindowState == ModalWindowDismissedParentSwitched) { resetModalFlags(true); } if(false == performCommonWindowRemovalTasks(card, (m_modalWindowState == ModalParentDismissed)?true:false)) return; if(Window::Type_ModalChildWindowCard != card->type()) { // slide card off the top of the screen CardWindow::Position pos = card->position(); QRectF r = pos.toTransform().mapRect(card->boundingRect()); qreal offTop = boundingRect().y() - (card->y() + (r.height()/2)); anim = new QPropertyAnimation(card, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); } else if(true == m_animateWindowForModalDismisal){ anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(card, anim); if(true == m_animateWindowForModalDismisal) anim->start(); m_curState->windowRemoved(card); // Finally if we are deleting a modal parent, clean reset the state if(m_modalWindowState == ModalParentDismissed) { resetModalFlags(true); m_modalWindowState = ModalParentDimissedWaitForChildDismissal; } } void CardWindowManager::handleModalRemovalForDeletedParent(CardWindow* card) { if(NULL == card || Window::Type_ModalChildWindowCard != card->type()) return; // ignore the return value. performCommonWindowRemovalTasks(card, false); } bool CardWindowManager::performCommonWindowRemovalTasks(CardWindow* card, bool checkCardGroup) { if(!card) return false; removePendingActionWindow(card); // Mark window as removed. Its safe to delete this now card->setRemoved(); // Is it already on the deleted animation list? if (m_deletedAnimMap.contains(card)) { // if it is animating, let it finish which will delete it QPropertyAnimation* a = m_deletedAnimMap.value(card); if (a && a->state() != QAbstractAnimation::Running) { // nuke the animation removeAnimationForWindow(card, true); delete card; } return false; } if(true == checkCardGroup) Q_ASSERT(card->cardGroup() != 0); removeAnimationForWindow(card); return true; } void CardWindowManager::initiateRemovalOfActiveModalWindow() { // Ensure that the last window we added was a modal window if(true == m_addingModalWindow) { CardWindow* activeWin = activeWindow(); // ERROR. DONT KNOW WHICH CARD WILL BE THE NEW ACTIVE CARD if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); return; } // Techinically this should never happen, but just in case. if(!m_parentOfModalCard) m_parentOfModalCard = static_cast<CardWindow*>(activeWin->parentItem()); if(!m_parentOfModalCard) { g_warning("Unable to get parent of active modal window %s", __PRETTY_FUNCTION__); return; } // Start an animation for the opacity of the currently active modal window QPropertyAnimation* winAnim = new QPropertyAnimation(activeWin, "opacity"); winAnim->setEndValue(0.0); winAnim->setDuration(kModalWindowAnimationTimeout); // connect to the slot that gets called when this animation gets done. connect(winAnim, SIGNAL(finished()), SLOT(slotOpacityAnimationFinished())); // start the animation winAnim->start(QAbstractAnimation::DeleteWhenStopped); } } void CardWindowManager::resetModalFlags(bool forceReset) { m_addingModalWindow = false; m_initModalMaximizing = false; m_modalDismissInProgress = false; m_modalDimissed = false; m_dismissModalImmediately = -1; if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } if(true == forceReset) m_parentOfModalCard = NULL; } void CardWindowManager::performPostModalWindowRemovedActions(Window* win, bool restore) { CardWindow* activeWin = (NULL != win)? (static_cast<CardWindow*>(win)) : activeWindow(); if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); // Set the parent to the first card of the active card group. if(m_activeGroup) m_activeGroup->makeBackCardActive(); return; } // call close ONLY if the modal was deleted internally if(ModalWindowDismissedExternally != m_modalWindowState || NoModalWindow != m_modalWindowState) { closeWindow(activeWin); } // Make the parent card as the active card. Notify SysUiController of this fact as well. No animations are needed as the parent is already the active card in full screen if(true == restore && NULL != m_parentOfModalCard) { m_modalDimissed = true; // Just set this flag so that the parent doesn't forward events to the modal card anymore m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); // Set the new maximized/active cards. SystemUiController::instance()->setMaximizedCardWindow(m_parentOfModalCard); SystemUiController::instance()->setActiveCardWindow(m_parentOfModalCard); // PDK apps need both Focus and Maximized events to be sent to them to direct render. The call above will give focus, disable DR here and resetModalFlags will re-enable DR on the parent if(m_parentOfModalCard->isHost()) { SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, m_parentOfModalCard, false); } // If we are restoring the parent state coz of active card being switched, don't start an animation, but do all the actions in sequence if(ModalWindowDismissedParentSwitched != m_modalWindowState) { // Queue up the fact that we need to give focus back to the parent queueFocusAction(m_parentOfModalCard, true); // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus back to the parent. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); m_anims.start(); } else { // we have a modal card as the active card and a new card is being added to the system. Perform all the actions here. if (m_activeGroup) { m_activeGroup->raiseCards(); } m_parentOfModalCard->aboutToFocusEvent(true); m_parentOfModalCard->queueFocusAction(true); m_parentOfModalCard->performPendingFocusAction(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; } } else { if(!((ModalWindowAddInitCheckFail == m_modalWindowState) || (ModalParentDismissed == m_modalWindowState) || (ModalWindowDismissedParentSwitched == m_modalWindowState))) { resetModalFlags(); } } // Finally - if the modal was dismissed externally then make it invisible here so that it doesn't linger around. ResetModal() will clear out the flags on the parent if((ModalWindowDismissedExternally == m_modalWindowState || ModalWindowDismissedParentSwitched == m_modalWindowState) && (activeWin->type() == Window::Type_ModalChildWindowCard)) activeWin->setVisible(false); } void CardWindowManager::slotOpacityAnimationFinished() { performPostModalWindowRemovedActions(NULL, true); } void CardWindowManager::removeCardFromGroup(CardWindow* win, bool adjustLayout) { if(Window::Type_ModalChildWindowCard == win->type()) return; CardGroup* group = win->cardGroup(); luna_assert(group != 0); group->removeFromGroup(win); if (group->empty()) { // clean up this group m_groups.remove(m_groups.indexOf(group)); removeAnimationForGroup(group); delete group; } // make sure we aren't holding a reference to a soon to be deleted card if (m_draggedWin == win) { // clear any dragging state resetMouseTrackState(); } // If we are removing a modal dialog , we don't need these. if(adjustLayout) { // select a new active group setActiveGroup(groupClosestToCenterHorizontally()); // make sure everything is positioned properly slideAllGroups(); } } void CardWindowManager::removeCardFromGroupMaximized(CardWindow* win) { IMEController::instance()->removeClient(win); if(Window::Type_ModalChildWindowCard == win->type()) return; // Switch out only if we are the active window if (activeWindow() == win) { Q_EMIT signalMinimizeActiveWindow(); removeCardFromGroup(win); return; }else if(NULL != m_parentOfModalCard && m_parentOfModalCard == win && true == m_parentOfModalCard->isCardModalParent()) { removeCardFromGroup(win); return; } removeCardFromGroup(win, false); } void CardWindowManager::layoutGroups(qreal xDiff) { if (!m_activeGroup || m_groups.empty()) return; int activeGroupPosition = m_groups.indexOf(m_activeGroup); removeAnimationForGroup(m_activeGroup); m_activeGroup->setX(m_activeGroup->x() + xDiff); int centerX = -m_activeGroup->left() - kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition-1; i>=0; i--) { centerX += -m_groups[i]->right(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::maximizeActiveWindow(bool animate) { if (!m_activeGroup) return; Q_EMIT signalExitReorder(); QRect r; // If the currently active card window is a modal window, don't do any of these operations except If we are doing this as a part of rotation if(activeWindow()->type() != Window::Type_ModalChildWindowCard || (activeWindow()->type() == Window::Type_ModalChildWindowCard && true == SystemUiController::instance()->isUiRotating())) { m_activeGroup->raiseCards(); setActiveGroup(m_activeGroup); if(animate) slideAllGroups(false); else layoutAllGroups(false); if(activeWindow()->type() != Window::Type_ModalChildWindowCard) r = normalOrScreenBounds(m_activeGroup->activeCard()); else if(NULL != m_parentOfModalCard) r = normalOrScreenBounds(m_parentOfModalCard); if(animate) { QList<QPropertyAnimation*> maxAnims = m_activeGroup->maximizeActiveCard(r.y()/2); Q_FOREACH(QPropertyAnimation* anim, maxAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } startAnimations(); } else { m_activeGroup->maximizeActiveCardNoAnimation(r.y()/2); } } else { // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus to the active card. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); if(false == m_initModalMaximizing) { // Notify SystemUiController that the modal window was added successfully. if(true == m_addingModalWindow) { // Notify SysUiController that we have setup a modal notifySysControllerOfModalStatus(SystemUiController::NoErr, false, ModalLaunch, activeWindow()); } m_initModalMaximizing = true; } // start the animations startAnimations(); } Q_EMIT signalMaximizeActiveWindow(); } void CardWindowManager::slotMaximizeActiveCardWindow() { if(false == m_addingModalWindow) maximizeActiveWindow(); } void CardWindowManager::minimizeActiveWindow(bool animate) { disableCardRestoreToMaximized(); Q_EMIT signalExitReorder(); if (m_activeGroup) m_activeGroup->raiseCards(); // always allow transitions to minimized mode if(false == m_addingModalWindow) { Q_EMIT signalMinimizeActiveWindow(); if(animate) slideAllGroups(); else layoutAllGroups(); } else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::UiMinimized, true, ModalDismissAnimate); } } void CardWindowManager::markFirstCardDone() { g_message("[%s]: DEBUG: staring markFirstCardDone.", __PRETTY_FUNCTION__); m_dismissedFirstCard=true; // For first-use mode, touch a marker file on the filesystem //if (Settings::LunaSettings()->uiType == Settings::UI_MINIMAL) { g_mkdir_with_parents(Settings::LunaSettings()->lunaPrefsPath.c_str(), 0755); FILE* f = fopen(Settings::LunaSettings()->firstCardLaunch.c_str(), "w"); fclose(f); //} } void CardWindowManager::firstCardAlert() { if(!m_dismissedFirstCard){ Q_EMIT signalFirstCardRun(); markFirstCardDone(); } } void CardWindowManager::handleKeyNavigationMinimized(QKeyEvent* keyEvent) { if (!m_activeGroup || keyEvent->type() != QEvent::KeyPress) return; switch (keyEvent->key()) { case Qt::Key_Left: switchToPrevApp(); break; case Qt::Key_Right: switchToNextApp(); break; case Qt::Key_Return: if (!keyEvent->isAutoRepeat()) maximizeActiveWindow(); break; case Qt::Key_Backspace: if ((keyEvent->modifiers() & Qt::ControlModifier) && !keyEvent->isAutoRepeat()) closeWindow(activeWindow()); break; default: break; } } void CardWindowManager::slotMinimizeActiveCardWindow() { if(false == m_addingModalWindow) minimizeActiveWindow(); else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::HomeButtonPressed, true, ModalDismissAnimate); } } void CardWindowManager::setActiveCardOffScreen(bool fullsize) { CardWindow* activeCard = activeWindow(); if (!activeCard) return; // safety precaution removeAnimationForWindow(activeCard); CardWindow::Position pos; qreal yOffset = boundingRect().bottom() - activeCard->y(); pos.trans.setZ(fullsize ? 1.0 : kActiveScale); pos.trans.setY(yOffset - activeCard->boundingRect().y() * pos.trans.z()); activeCard->setPosition(pos); } void CardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event) { // We may get a second pen down. Just ignore it. if (m_penDown) return; resetMouseTrackState(); if (m_groups.empty() || !m_activeGroup) return; m_penDown = true; updateAllowWindowUpdates(); m_curState->mousePressEvent(event); } void CardWindowManager::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { mousePressEvent(event); } void CardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (!m_penDown || m_seenFlickOrTap) return; m_curState->mouseMoveEvent(event); } void CardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if (m_penDown) m_curState->mouseReleaseEvent(event); resetMouseTrackState(); } bool CardWindowManager::playAngryCardSounds() const { return WindowServer::instance()->getUiOrientation() == OrientationEvent::Orientation_Down; } bool CardWindowManager::sceneEvent(QEvent* event) { if (event->type() == QEvent::GestureOverride && m_curState != m_maximizeState) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { event->accept(); return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { event->accept(); return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { event->accept(); return true; } } else if (event->type() == QEvent::Gesture) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { QTapGesture* tap = static_cast<QTapGesture*>(g); if (tap->state() == Qt::GestureFinished) { tapGestureEvent(tap); } return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { QTapAndHoldGesture* hold = static_cast<QTapAndHoldGesture*>(g); if (hold->state() == Qt::GestureFinished) { tapAndHoldGestureEvent(hold); } return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { FlickGesture* flick = static_cast<FlickGesture*>(g); if (flick->state() == Qt::GestureFinished) { flickGestureEvent(ge); } return true; } } return QGraphicsObject::sceneEvent(event); } void CardWindowManager::tapGestureEvent(QTapGesture* event) { if (!m_penDown) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapGestureEvent(event); } void CardWindowManager::tapAndHoldGestureEvent(QTapAndHoldGesture* event) { if (!m_penDown) return; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapAndHoldGestureEvent(event); } void CardWindowManager::handleTapAndHoldGestureMinimized(QTapAndHoldGesture* event) { QPoint pt = mapFromScene(event->position()).toPoint(); if (m_activeGroup->setActiveCard(event->position())) { // start reordering the active card Q_EMIT signalEnterReorder(pt, s_marginSlice); } else if (pt.x() < 0) { switchToPrevGroup(); } else { switchToNextGroup(); } } void CardWindowManager::flickGestureEvent(QGestureEvent* event) { g_message("%s", __PRETTY_FUNCTION__); if (!m_penDown || m_seenFlickOrTap) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->flickGestureEvent(event); } void CardWindowManager::handleFlickGestureMinimized(QGestureEvent* event) { QGesture* g = event->gesture((Qt::GestureType) SysMgrGestureFlick); if (!g) return; FlickGesture* flick = static_cast<FlickGesture*>(g); if (m_movement == MovementVLocked) { if (!m_draggedWin) { slideAllGroups(); return; } QPointF start = mapFromScene(event->mapToGraphicsScene(flick->hotSpot())); QPointF end = mapFromScene(event->mapToGraphicsScene(flick->endPos())); int distanceY = end.y() - start.y(); static const int flickDistanceVelocityMultiplied = kFlickToCloseWindowVelocityThreshold * kFlickToCloseWindowDistanceThreshold; QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if (distanceY < kFlickToCloseWindowDistanceThreshold && flick->velocity().y() < kFlickToCloseWindowMinimumVelocity && flick->velocity().y() < (flickDistanceVelocityMultiplied / distanceY)) { closeWindow(m_draggedWin); } else if (pr.center().y() > boundingRect().bottom()) { closeWindow(m_draggedWin, true); } else if (pr.center().y() < boundingRect().top()) { closeWindow(m_draggedWin); } else { slideAllGroups(); } } else if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { // adjust the fanning position within the group based on the users flick velocity m_activeGroup->flick(flick->velocity().x()); setActiveGroup(m_activeGroup); slideAllGroups(); } else { // advance to the next/previous group if we are Outer Locked or were still unbiased horizontally if (flick->velocity().x() > 0) switchToPrevGroup(); else switchToNextGroup(); } } } void CardWindowManager::handleMousePressMinimized(QGraphicsSceneMouseEvent* event) { // try to capture the card the user first touched if (m_activeGroup && m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); } void CardWindowManager::handleMouseMoveMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.isEmpty() || !m_activeGroup) return; QPoint delta = (event->pos() - event->buttonDownPos(Qt::LeftButton)).toPoint(); QPoint diff; // distance move between last and current mouse position // lock movement to an axis if (m_movement == MovementUnlocked) { if ((delta.x() * delta.x() + delta.y() * delta.y()) < Settings::LunaSettings()->tapRadiusSquared) return; if (abs(delta.x()) > 0.866 * abs(delta.y())) { m_movement = MovementHLocked; m_activeGroupPivot = m_activeGroup->x(); } else { m_movement = MovementVLocked; } diff = delta; } else { diff = (event->pos() - event->lastPos()).toPoint(); } if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { m_trackWithinGroup = !m_activeGroup->atEdge(diff.x()); if (m_trackWithinGroup) { // shift cards within the active group m_activeGroup->adjustHorizontally(diff.x()); slideAllGroups(); } else { m_activeGroupPivot = m_activeGroup->x(); } } if (!m_trackWithinGroup) { m_activeGroupPivot += diff.x(); slideAllGroupsTo(m_activeGroupPivot); } } else if (m_movement == MovementVLocked) { if (!m_draggedWin) { if (m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); if (!m_draggedWin) return; } // ignore pen movements outside the vertical pillar around the active window QPointF mappedPos = m_draggedWin->mapFromParent(event->pos()); if (mappedPos.x() < m_draggedWin->boundingRect().x() || mappedPos.x() >= m_draggedWin->boundingRect().right()) { return; } if (delta.y() == 0) return; if (!m_playedAngryCardStretchSound && (delta.y() > kAngryCardThreshold) && playAngryCardSounds()) { SoundPlayerPool::instance()->playFeedback("carddrag"); m_playedAngryCardStretchSound = true; } removeAnimationForWindow(m_draggedWin); // cards are always offset from the parents origin CardWindow::Position pos = m_draggedWin->position(); pos.trans.setY(delta.y()); m_draggedWin->setPosition(pos); } } void CardWindowManager::handleMouseMoveReorder(QGraphicsSceneMouseEvent* event) { CardWindow* activeWin = activeWindow(); if (!activeWin) return; // track the active window under the users finger QPoint delta = (event->pos() - event->lastPos()).toPoint(); CardWindow::Position pos; pos.trans = QVector3D(activeWin->position().trans.x() + delta.x(), activeWin->position().trans.y() + delta.y(), kActiveScale); activeWin->setPosition(pos); // should we switch zones? ReorderZone newZone = getReorderZone(event->pos().toPoint()); if (newZone == m_reorderZone && newZone == ReorderZone_Center) { moveReorderSlotCenter(event->pos()); } else if (newZone != m_reorderZone) { if (newZone == ReorderZone_Right) { m_reorderZone = newZone; moveReorderSlotRight(); } else if (newZone == ReorderZone_Left) { m_reorderZone = newZone; moveReorderSlotLeft(); } else { m_reorderZone = newZone; } } } CardWindowManager::ReorderZone CardWindowManager::getReorderZone(QPoint pt) { qreal section = boundingRect().width() / s_marginSlice; if (pt.x() < boundingRect().left() + section) { return ReorderZone_Left; } else if (pt.x() > boundingRect().right() - section) { return ReorderZone_Right; } return ReorderZone_Center; } void CardWindowManager::enterReorder(QPoint pt) { CardWindow* activeWin = activeWindow(); luna_assert(activeWin != 0); activeWin->setOpacity(0.8); activeWin->disableShadow(); activeWin->setAttachedToGroup(false); // get our initial zone m_reorderZone = getReorderZone(pt); } void CardWindowManager::cycleReorderSlot() { if (m_reorderZone == ReorderZone_Right) moveReorderSlotRight(); else if (m_reorderZone == ReorderZone_Left) moveReorderSlotLeft(); } void CardWindowManager::moveReorderSlotCenter(QPointF pt) { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; // NOTE: it is assumed that the active card has already // been repositioned when making this check if (m_activeGroup->moveActiveCard()) { m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } setActiveGroup(m_activeGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotRight() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the top card in the group? if (m_activeGroup->moveActiveCard(1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.last() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group. m_groups.remove(activeIndex); delete m_activeGroup; newActiveGroup = m_groups[activeIndex]; } else { // this was an existing group. // insert a new group to the right of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex+1, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToBack(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotLeft() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the bottom card in the group? if (m_activeGroup->moveActiveCard(-1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.first() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group m_groups.remove(activeIndex); delete m_activeGroup; // the previous group is the new active group newActiveGroup = m_groups[qMax(0, activeIndex-1)]; } else { // this was an existing group. // insert a new group to the left of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToFront(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::arrangeWindowsAfterReorderChange(int duration, QEasingCurve::Type curve) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardShuffleReorderCurve)); anim->setDuration(AS(cardShuffleReorderDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(duration, curve, false); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::handleMouseReleaseMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.empty() || m_seenFlickOrTap) return; if (m_movement == MovementVLocked) { // Did we go too close to the top? if (m_draggedWin) { QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if ((!event->canceled()) && (pr.center().y() > boundingRect().bottom())) { closeWindow(m_draggedWin, true); } else if ((!event->canceled()) && (pr.center().y() < boundingRect().top())) { closeWindow(m_draggedWin); } else { // else just restore all windows back to original position slideAllGroups(); } } } else if (m_movement == MovementHLocked) { if(!event->canceled()) setActiveGroup(groupClosestToCenterHorizontally()); slideAllGroups(); } } void CardWindowManager::handleMouseReleaseReorder(QGraphicsSceneMouseEvent* event) { Q_UNUSED(event) Q_EMIT signalExitReorder(false); CardWindow* activeWin = activeWindow(); if (!activeWin) return; // TODO: fix the y for the draggedWin activeWin->setOpacity(1.0); activeWin->enableShadow(); activeWin->setAttachedToGroup(true); slideAllGroups(); } void CardWindowManager::handleTapGestureMinimized(QTapGesture* event) { if (!m_activeGroup) return; //Things that must be done here: //--Perform a hit test to determine if the current active group was hit if (m_activeGroup->testHit(event->position())) { //--If it was, then we need to see if the card hit was in a reasonable // range of the active card. If it was then maximize it. If it was not // slide the card fan over to make it more visible. if (m_activeGroup->shouldMaximizeOrScroll(event->position())) { m_activeGroup->setActiveCard(event->position()); m_activeGroup->moveToActiveCard(); maximizeActiveWindow(); } else { slideAllGroups(); } } else { // first test to see if the tap is not above/below the active group QPointF pt = mapFromScene(event->position()); if (!m_activeGroup->withinColumn(pt)) { if (pt.x() < 0) { // tapped to the left of the active group switchToPrevGroup(); } else { // tapped to the right of the active group switchToNextGroup(); } } else { // poke the groups to make sure they animate to their final positions slideAllGroups(); } } } CardGroup* CardWindowManager::groupClosestToCenterHorizontally() const { if (m_groups.empty()) return 0; qreal deltaX = FLT_MAX; qreal curDeltaX = 0; CardGroup* grp = 0; Q_FOREACH(CardGroup* cg, m_groups) { curDeltaX = qAbs(cg->pos().x()); if (curDeltaX < deltaX) { grp = cg; deltaX = curDeltaX; } } return grp; } void CardWindowManager::setActiveGroup(CardGroup* group) { m_activeGroup = group; SystemUiController::instance()->setActiveCardWindow(m_activeGroup ? m_activeGroup->activeCard() : 0); } void CardWindowManager::switchToNextApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makeNextCardActive()) { // couldn't move, switch to the next group int index = m_groups.indexOf(m_activeGroup); if (index < m_groups.size() - 1) { m_activeGroup = m_groups[index + 1]; m_activeGroup->makeBackCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToPrevApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makePreviousCardActive()) { // couldn't move, switch to the previous group int index = m_groups.indexOf(m_activeGroup); if (index > 0) { m_activeGroup = m_groups[index - 1]; m_activeGroup->makeFrontCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToNextGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.last()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex++; activeGroupIndex = qMin(activeGroupIndex, m_groups.size() - 1); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToPrevGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.first()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex--; activeGroupIndex = qMax(activeGroupIndex, 0); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToNextAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); if(!oldActiveCard) return; // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makeNextCardActive()) { if (m_activeGroup == m_groups.last()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() - 40); oldActiveCard->setPosition(pos); } else { // switch to the bottom card of the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index+1]); m_activeGroup->makeBackCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::switchToPrevAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makePreviousCardActive()) { if (m_activeGroup == m_groups.first()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() + 40); oldActiveCard->setPosition(pos); } else { // shift to the bottom card in the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index-1]); m_activeGroup->makeFrontCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { // current maximized card QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::slideAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(200, QEasingCurve::OutCubic, includeActiveCard); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } if (includeActiveCard) startAnimations(); } void CardWindowManager::slideAllGroupsTo(int xOffset) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(xOffset); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), xOffset); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups + xOffset; for (int i=activeGrpIndex-1; i>=0;i--) { centerX += -m_groups[i]->right(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + xOffset; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::layoutAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); m_activeGroup->layoutCards(true, includeActiveCard); int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { m_groups[i]->layoutCards(false, false); centerX += -m_groups[i]->right(); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { m_groups[i]->layoutCards(false, false); centerX += m_groups[i]->left(); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::slideToActiveCard() { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::focusWindow(Window* win) { Q_EMIT signalExitReorder(); disableCardRestoreToMaximized(); // make sure this are window has already been group'd CardWindow* card = static_cast<CardWindow*>(win); if (!m_groups.contains(card->cardGroup()) || !m_activeGroup) return; // If the active card is a modal window and we are focusing another window, we need to dismiss the modal first. if(Window::Type_ModalChildWindowCard == activeWindow()->type() && card != activeWindow()) { // Cehck if we are trying to focus the parent m_modalWindowState = ModalWindowDismissedParentSwitched; if(m_parentOfModalCard != card) { // Some other card is being focussed so no need to restore the state of the parent notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; m_modalDimissed = true; } } else { // Someone tried to give focus to the parent. notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); return; } } Q_EMIT signalFocusWindow(card); } void CardWindowManager::slotPositiveSpaceAboutToChange(const QRect& r, bool fullScreenMode, bool screenResizing) { Q_EMIT signalExitReorder(); m_targetPositiveSpace = r; if (m_curState) m_curState->positiveSpaceAboutToChange(r, fullScreenMode); } void CardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r) { Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChangeFinished(r); } void CardWindowManager::slotPositiveSpaceChanged(const QRect& r) { static bool initialBounds = true; static qreal kActiveWindowScale = Settings::LunaSettings()->activeCardWindowRatio; static qreal kNonActiveWindowScale = Settings::LunaSettings()->nonActiveCardWindowRatio; if (initialBounds) { initialBounds = false; m_normalScreenBounds = r; kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = r; // TODO: this is a temporary solution to fake the existence of the search pill // which happens to be 48 pixels tall kActiveScale = ((qreal) (r.height() - 48) * kActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kActiveScale = qMax(kMinimumWindowScale, kActiveScale); kNonActiveScale = ((qreal) (r.height() - 48) * kNonActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kNonActiveScale = qMax(kMinimumWindowScale, kNonActiveScale); // allow groups to shift up to a maximum so the tops of cards don't go off the screen kWindowOriginMax = (boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio))) - Settings::LunaSettings()->positiveSpaceTopPadding - Settings::LunaSettings()->positiveSpaceBottomPadding; kWindowOrigin = boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio)); } QRect rect = r; if (rect.height() < kMinimumHeight) { rect.setHeight(kMinimumHeight); } Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChanged(rect); } void CardWindowManager::disableCardRestoreToMaximized() { m_cardToRestoreToMaximized = 0; } void CardWindowManager::restoreCardToMaximized() { if (!m_cardToRestoreToMaximized || !m_activeGroup) return; if (m_activeGroup->setActiveCard(m_cardToRestoreToMaximized)) maximizeActiveWindow(); disableCardRestoreToMaximized(); } QRect CardWindowManager::normalOrScreenBounds(CardWindow* win) const { if (win && win->fullScreen() && win->type() != Window::Type_ModalChildWindowCard) { return QRect(m_targetPositiveSpace.x(), m_targetPositiveSpace.y(), SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight()); } return m_normalScreenBounds; } void CardWindowManager::cancelReorder(bool dueToPenCancel) { handleMouseReleaseReorder(NULL); } void CardWindowManager::closeWindow(CardWindow* win, bool angryCard) { if(!win) return; QPropertyAnimation* anim = NULL; /*// The only case we need to worry about here is if a modal parent called closeWindow() on itself. Then we need to close the child first and then continue if(true == win->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; notifySysControllerOfModalStatus(SystemUiController::ParentCardDismissed, false, ModalDismissNoAnimate); win->setCardIsModalParent(false); win->setModalChild(NULL); win->setModalAcceptInputState(CardWindow::NoModalWindow); }*/ if (angryCard) win->setDisableKeepAlive(); win->close(); // remove the window from the current animation list removeAnimationForWindow(win, true); if(Window::Type_ModalChildWindowCard != win->type()) { CardWindow::Position pos = win->position(); QRectF r = win->mapRectToParent(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); pos.trans.setY(offTop); anim = new QPropertyAnimation(win, "position"); QVariant end; end.setValue(pos); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setDuration(AS(cardDeleteDuration)); anim->setEndValue(end); } else { anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); // Modal cards are not a part of any card group. if(Window::Type_ModalChildWindowCard != win->type()) { removeCardFromGroup(win); } if (angryCard && playAngryCardSounds()) SoundPlayerPool::instance()->playFeedback("birdappclose"); else if (!Settings::LunaSettings()->lunaSystemSoundAppClose.empty()) SoundPlayerPool::instance()->playFeedback(Settings::LunaSettings()->lunaSystemSoundAppClose); } void CardWindowManager::queueFocusAction(CardWindow* win, bool focused) { if (win->removed()) return; win->aboutToFocusEvent(focused); win->queueFocusAction(focused); if (!m_pendingActionWinSet.contains(win)) m_pendingActionWinSet.insert(win); } void CardWindowManager::performPendingFocusActions() { Q_FOREACH(CardWindow* card, m_pendingActionWinSet) { card->performPendingFocusAction(); } m_pendingActionWinSet.clear(); } void CardWindowManager::queueTouchToShareAction(CardWindow* win) { if (win->removed()) return; if (!m_pendingTouchToShareWinSet.contains(win)) m_pendingTouchToShareWinSet.insert(win); } void CardWindowManager::performPendingTouchToShareActions() { Q_FOREACH(CardWindow* card, m_pendingTouchToShareWinSet) { GhostCard* ghost = card->createGhost(); if (ghost) { // place the ghost on top of the card we're sharing ghost->setParentItem(card->parentItem()); ghost->stackBefore(card); card->stackBefore(ghost); // anchor the ghost within it's parent's group CardGroup* group = card->cardGroup(); ghost->setPos((group ? group->pos() : QPointF(0,0))); ghost->setOpacity(0.5); QPropertyAnimation* anim = new QPropertyAnimation(ghost, "position"); anim->setDuration(AS(cardGhostDuration)); anim->setEasingCurve(AS_CURVE(cardGhostCurve)); // animate the ghost off the top of the screen CardWindow::Position pos; QRectF r = ghost->mapRectToParent(ghost->boundingRect()); qreal offTop = boundingRect().y() - (ghost->y() + (r.height()/2)); pos.trans.setY(offTop); pos.trans.setZ(Settings::LunaSettings()->ghostCardFinalRatio); QVariant end; end.setValue(pos); anim->setEndValue(end); connect(anim, SIGNAL(finished()), SLOT(slotTouchToShareAnimationFinished())); anim->start(); } } m_pendingTouchToShareWinSet.clear(); } void CardWindowManager::removePendingActionWindow(CardWindow* win) { QSet<CardWindow*>::iterator it = m_pendingActionWinSet.find(win); if (it != m_pendingActionWinSet.end()) m_pendingActionWinSet.erase(it); it = m_pendingTouchToShareWinSet.find(win); if (it != m_pendingTouchToShareWinSet.end()) m_pendingTouchToShareWinSet.erase(it); } CardWindow* CardWindowManager::activeWindow() const { CardWindow* activeCard = NULL; CardWindow* w = NULL; if((NULL == m_activeGroup) || (NULL == (activeCard = m_activeGroup->activeCard()))) { return NULL; } else { w = activeCard->getModalChild(); return( NULL != w)? w: activeCard; } } CardGroup* CardWindowManager::activeGroup() const { return m_activeGroup; } void CardWindowManager::slotAnimationsFinished() { if(false == m_addingModalWindow) { if (m_anims.animationCount() == 0) { return; } } m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_anims.clear(); // make sure the active group stays at the top of the stacking order if (m_activeGroup) { m_activeGroup->raiseCards(); } performPendingFocusActions(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::slotDeletedAnimationFinished() { QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); // find the card whose animation finished and delete it if webkit already told us we can QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.begin(); for (; it != m_deletedAnimMap.end(); ++it) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (anim == a) { CardWindow* w = static_cast<CardWindow*>(it.key()); if (w->removed()) { m_deletedAnimMap.erase(it); delete w; delete a; } else { // since we don't adjust these when ui orientation changes, make sure they remain // invisible until the reaper comes to collect them w->setVisible(false); } break; } } } void CardWindowManager::slotTouchToShareAnimationFinished() { g_debug("%s: deleting TapToShare Ghost", __PRETTY_FUNCTION__); QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); GhostCard* target = static_cast<GhostCard*>(anim->targetObject()); delete anim; if (target) { delete target; } } void CardWindowManager::slotLauncherVisible(bool val, bool fullyVisible) { if (fullyVisible && !m_lowResMode) { m_lowResMode = true; Q_FOREACH(CardGroup* group, m_groups) { group->disableShadows(); } } else if (!fullyVisible && m_lowResMode) { m_lowResMode = false; Q_FOREACH(CardGroup* group, m_groups) { group->enableShadows(); } } } void CardWindowManager::slotLauncherShown(bool val) { if (!val) return; if (m_curState && m_curState->supportLauncherOverlay()) return; minimizeActiveWindow(); } void CardWindowManager::slotChangeCardWindow(bool next) { if (m_curState) m_curState->changeCardWindow(next); } void CardWindowManager::slotFocusMaximizedCardWindow(bool focus) { if (m_curState) m_curState->focusMaximizedCardWindow(focus); } void CardWindowManager::slotTouchToShareAppUrlTransfered(const std::string& appId) { if (m_curState) m_curState->processTouchToShareTransfer(appId); } void CardWindowManager::slotDismissActiveModalWindow() { if(Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::ServiceDismissedModalCard, true, ModalDismissAnimate); } else { resetModalFlags(); } } void CardWindowManager::slotDismissModalTimerStopped() { CardWindow* activeWin = activeWindow(); if(activeWin && (Window::Type_ModalChildWindowCard == activeWin->type()) && m_parentOfModalCard) { m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedAcceptingInput); } } void CardWindowManager::setInModeAnimation(bool animating) { if (animating) { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_SourceOver); } } else { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_Source); } } } void CardWindowManager::notifySysControllerOfModalStatus(int reason, bool restore, NotifySystemUiControllerAction type, Window* win) { if(type == Invalid) return; if(type == ModalLaunch) { // Notify SystemUiController of the result of the modal launch SystemUiController::instance()->setModalWindowLaunchErrReason((SystemUiController::ModalWinLaunchErrorReason)(reason)); // Signal that we no longer have an active modal window only if the reason is NoErr, else remove the window if(SystemUiController::NoErr == ((SystemUiController::ModalWinLaunchErrorReason)(reason))) { SystemUiController::instance()->notifyModalWindowActivated(m_parentOfModalCard); } else { // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; performPostModalWindowRemovedActions(win, restore); } return; } // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; // Notify SystemUiController of the reason why the modal was dismissed SystemUiController::instance()->setModalWindowDismissErrReason((SystemUiController::ModalWinDismissErrorReason)(reason)); if(type == ModalDismissAnimate) { // We need to animate the removal of the modal. So call this function, which will call performPostModalWindowRemovedActions(restore) with the correct params initiateRemovalOfActiveModalWindow(); } else { // directly get rid of the modal card performPostModalWindowRemovedActions(NULL, restore); } } void CardWindowManager::updateAllowWindowUpdates() { bool allow = true; if (m_animationsActive) allow = false; else if ((m_curState != m_maximizeState) && m_penDown) allow = false; Q_FOREACH(CardGroup* cg, m_groups) { Q_FOREACH(CardWindow* w, cg->cards()) w->allowUpdates(allow); } }
29.960682
189
0.732066
ericblade
de039450ccb7ee81838d6dffa3d0cba18eddfc5a
1,560
cpp
C++
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
#include "TarsServantName.h" #include "TarsTest/TestcaseServer/RPCTest.h" #include "gtest/gtest.h" #include "servant/AdminF.h" #include "servant/Application.h" #include <cassert> #include <iostream> #include "util/tc_pack.h" using namespace std; using namespace tars; using namespace TarsTest; TEST(TarsUtilTestcase, UT_TC_Pack) { bool b = true; char c = 'a'; short si = 3; int ii = 4; char cn[] = "abc"; string sn = "def"; TC_PackIn pi; pi << b << c << si << ii << cn << sn; string s = pi.topacket(); TC_PackOut po(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; po >> si; assert(si == 3); cout << "short OK" << endl; po >> ii; assert(ii == 4); cout << "int OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> sn; assert(sn == "def"); cout << "string OK" << endl; { pi.clear(); pi << b << c; pi.insert(1) << cn; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; } { pi.clear(); pi << b << c; pi.replace(1) << 'b'; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'b'); cout << "char OK" << endl; } }
17.333333
44
0.507692
hfcrwx
de048781cc5c3f9937c1008ba847870104bb8ca7
648
cpp
C++
CSES/Number Spiral.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
1
2020-08-27T06:59:52.000Z
2020-08-27T06:59:52.000Z
CSES/Number Spiral.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
CSES/Number Spiral.cpp
XitizVerma/Data-Structures-and-Algorithms-Advanced
610225eeb7e0b4ade229ec86355901ad1ca38784
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> #include<iostream> using namespace std; #define mod 10000000007 #define all(x) (x).begin(), (x).end() typedef long long ll; void subMain(){ ll r, c; cin >> r; cin >> c; ll ans = 0; ll z = max(r, c); ll z2 = (z - 1) * (z - 1); if (z % 2 == 0) { if (z == c) { ans = z2 + r; } else { ans = z2 + 2 * z - c; } } else { if (r == z) { ans = z2 + c; } else { ans = z2 + 2 * z - r; } } cout << ans << endl; } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t; cin >> t; while(t-- > 0){ subMain(); } //subMain(); return 0; }
12
37
0.467593
XitizVerma
de04fc4c98a15ef101d3a636183d07cab467c68f
2,253
cpp
C++
basic/3.cpp
happylittlecat2333/pokemon
f5c297aa5b7e5fe999974a9dd568c37c27f4b1da
[ "MIT" ]
null
null
null
basic/3.cpp
happylittlecat2333/pokemon
f5c297aa5b7e5fe999974a9dd568c37c27f4b1da
[ "MIT" ]
null
null
null
basic/3.cpp
happylittlecat2333/pokemon
f5c297aa5b7e5fe999974a9dd568c37c27f4b1da
[ "MIT" ]
null
null
null
#include<iostream> #include<cmath> #define pi 3.14 using namespace std; class Shape { protected: float area; //派生类可以访问protected,外部访问不了;派生类共有 public: Shape(); //构造函数 float Area(); //同名隐藏;输出area ~Shape(); //析构函数 }; class Rectangle : public Shape { private: float length, width; //长宽 public: Rectangle(float length, float width); //构造 float Area(); //计算area,并输出 ~Rectangle(); //析构 }; class Round : public Shape { private: float radius; //半径 public: Round(float radius); //构造 float Area(); //计算area,并输出 ~Round(); //析构 }; class Square : public Rectangle { private: float l; //边长 public: Square(float l); //构造 float Area(); //计算area,并输出 ~Square(); //析构 }; Shape::Shape(){ cout << "construct Shape\n"; area=0; } float Shape::Area(){ cout << "Shape Area:" << area << endl; return area; } Shape::~Shape(){ cout << "deleting Shape\n"; area=0; } Round::Round(float radius){ cout << "construct Round\n"; this->radius=radius; } float Round::Area(){ area=pi*radius*radius; cout << "Round Area:" << area << endl; return area; } Round::~Round(){ cout << "deleting Round\n"; } Rectangle::Rectangle(float length, float width){ cout << "construct Rectangle\n"; this->length=length, this->width=width; } float Rectangle::Area(){ area=length*width; cout << "Rectangle Area:" << area << endl; return area; } Rectangle::~Rectangle(){ cout << "deleting Rectangle\n"; } Square::Square(float l):Rectangle(l ,l){ //派生类的构造函数;同时赋值给基类Rectangle cout << "construct Square\n"; this->l = l; } float Square::Area(){ area=l*l; cout << "Square Area:"<< area << endl; return area; } Square::~Square(){ cout << "deleting Square\n"; } int main(){ float l; cout << "input square length:\n"; cin >> l; Square square(l); cout << endl; square.Area(); //同名隐藏规则 square.Rectangle::Area(); //限定类名 square.Shape::Area(); float r; cout << "\ninput Round radius:\n"; cin >> r; Round round(r); cout << endl; round.Area(); //同名隐藏规则 round.Shape::Area(); //限定类名 float length, width; cout << "input Rectangle (length, width):\n"; cin >> length >> width; Rectangle rectanle(length, width); cout << endl; rectanle.Area(); //同名隐藏规则 rectanle.Shape::Area(); //限定类名 cout << endl; return 0; }
16.566176
68
0.628939
happylittlecat2333
de05a19de88130412aa239bdc84607cb88268214
1,984
cpp
C++
src/Core/Scene/CSceneIterator.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
32
2018-12-17T20:22:32.000Z
2019-06-14T06:48:25.000Z
src/Core/Scene/CSceneIterator.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
10
2019-11-25T04:54:05.000Z
2022-02-12T20:20:56.000Z
src/Core/Scene/CSceneIterator.cpp
henriquegemignani/PrimeWorldEditor
741185e8d695c5bc86b7efbfadaf4e5dcd67d4d9
[ "MIT" ]
10
2019-11-22T09:16:00.000Z
2021-11-21T22:55:54.000Z
#include "CSceneIterator.h" #include "CScene.h" CSceneIterator::CSceneIterator(CScene *pScene, FNodeFlags AllowedNodeTypes /*= eAllNodeTypes*/, bool AllowHiddenNodes /*= false*/) : mpScene(pScene) , mAllowHiddenNodes(AllowHiddenNodes) , mNodeFlags(AllowedNodeTypes) , mpCurNode(nullptr) { mMapIterator = mpScene->mNodes.begin(); while (mMapIterator != mpScene->mNodes.end()) { if (mMapIterator->first & AllowedNodeTypes) break; mMapIterator++; } if (mMapIterator != mpScene->mNodes.end()) { mVectorIterator = (mMapIterator->second).begin(); Next(); // Find first node } } // ************ PROTECTED ************ void CSceneIterator::InternalFindNext() { // This function does most of the heavy lifting. We continue from where we left off last time this function was called. while (mMapIterator != mpScene->mNodes.end()) { // Iterate over each node in the vector. std::vector<CSceneNode*>& rVector = mMapIterator->second; bool FoundNext = false; while (mVectorIterator != rVector.end()) { CSceneNode *pNode = *mVectorIterator; // Check node visibility if (mAllowHiddenNodes || pNode->IsVisible()) { mpCurNode = pNode; FoundNext = true; } mVectorIterator++; if (FoundNext) return; } // We've reached the end of this node vector, so advance the map iterator while (true) { mMapIterator++; if (mMapIterator == mpScene->mNodes.end()) { break; } if (mNodeFlags & mMapIterator->first) { mVectorIterator = mMapIterator->second.begin(); break; } } } // If we're down here, then it seems we're done iterating the scene. mpCurNode = nullptr; }
27.178082
130
0.55998
henriquegemignani
de06835940a08947464fa22014aecaf987652ba1
17,397
cc
C++
components/offline_pages/background/pick_request_task_unittest.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-01-07T18:51:03.000Z
2021-01-07T18:51:03.000Z
components/offline_pages/background/pick_request_task_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
components/offline_pages/background/pick_request_task_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// 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 "components/offline_pages/background/pick_request_task.h" #include <memory> #include <set> #include "base/bind.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/offline_pages/background/device_conditions.h" #include "components/offline_pages/background/offliner_policy.h" #include "components/offline_pages/background/request_coordinator.h" #include "components/offline_pages/background/request_coordinator_event_logger.h" #include "components/offline_pages/background/request_notifier.h" #include "components/offline_pages/background/request_queue_in_memory_store.h" #include "components/offline_pages/background/request_queue_store.h" #include "components/offline_pages/background/save_page_request.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { namespace { // Data for request 1. const int64_t kRequestId1 = 17; const GURL kUrl1("https://google.com"); const ClientId kClientId1("bookmark", "1234"); // Data for request 2. const int64_t kRequestId2 = 42; const GURL kUrl2("http://nytimes.com"); const ClientId kClientId2("bookmark", "5678"); const bool kUserRequested = true; const int kAttemptCount = 1; const int kMaxStartedTries = 5; const int kMaxCompletedTries = 1; // Constants for policy values - These settings represent the default values. const bool kPreferUntried = false; const bool kPreferEarlier = true; const bool kPreferRetryCount = true; const int kBackgroundProcessingTimeBudgetSeconds = 170; // Default request const SavePageRequest kEmptyRequest(0UL, GURL(""), ClientId("", ""), base::Time(), true); } // namespace // Helper class needed by the PickRequestTask class RequestNotifierStub : public RequestNotifier { public: RequestNotifierStub() : last_expired_request_(kEmptyRequest), total_expired_requests_(0) {} void NotifyAdded(const SavePageRequest& request) override {} void NotifyChanged(const SavePageRequest& request) override {} void NotifyCompleted(const SavePageRequest& request, BackgroundSavePageResult status) override { last_expired_request_ = request; last_request_expiration_status_ = status; total_expired_requests_++; } const SavePageRequest& last_expired_request() { return last_expired_request_; } RequestCoordinator::BackgroundSavePageResult last_request_expiration_status() { return last_request_expiration_status_; } int32_t total_expired_requests() { return total_expired_requests_; } private: BackgroundSavePageResult last_request_expiration_status_; SavePageRequest last_expired_request_; int32_t total_expired_requests_; }; class PickRequestTaskTest : public testing::Test { public: PickRequestTaskTest(); ~PickRequestTaskTest() override; void SetUp() override; void PumpLoop(); void AddRequestDone(ItemActionStatus status); void RequestPicked(const SavePageRequest& request); void RequestNotPicked(const bool non_user_requested_tasks_remaining); void RequestCountCallback(size_t total_count, size_t available_count); void QueueRequests(const SavePageRequest& request1, const SavePageRequest& request2); // Reset the factory and the task using the current policy. void MakeFactoryAndTask(); RequestNotifierStub* GetNotifier() { return notifier_.get(); } PickRequestTask* task() { return task_.get(); } void TaskCompletionCallback(Task* completed_task); protected: std::unique_ptr<RequestQueueStore> store_; std::unique_ptr<RequestNotifierStub> notifier_; std::unique_ptr<SavePageRequest> last_picked_; std::unique_ptr<OfflinerPolicy> policy_; RequestCoordinatorEventLogger event_logger_; std::set<int64_t> disabled_requests_; std::unique_ptr<PickRequestTaskFactory> factory_; std::unique_ptr<PickRequestTask> task_; bool request_queue_not_picked_called_; size_t total_request_count_; size_t available_request_count_; bool task_complete_called_; private: scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; }; PickRequestTaskTest::PickRequestTaskTest() : task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_) {} PickRequestTaskTest::~PickRequestTaskTest() {} void PickRequestTaskTest::SetUp() { DeviceConditions conditions; store_.reset(new RequestQueueInMemoryStore()); policy_.reset(new OfflinerPolicy()); notifier_.reset(new RequestNotifierStub()); MakeFactoryAndTask(); request_queue_not_picked_called_ = false; total_request_count_ = 9999; available_request_count_ = 9999; task_complete_called_ = false; last_picked_.reset(); } void PickRequestTaskTest::PumpLoop() { task_runner_->RunUntilIdle(); } void PickRequestTaskTest::TaskCompletionCallback(Task* completed_task) { task_complete_called_ = true; } void PickRequestTaskTest::AddRequestDone(ItemActionStatus status) {} void PickRequestTaskTest::RequestPicked(const SavePageRequest& request) { last_picked_.reset(new SavePageRequest(request)); } void PickRequestTaskTest::RequestNotPicked( const bool non_user_requested_tasks_remaining) { request_queue_not_picked_called_ = true; } void PickRequestTaskTest::RequestCountCallback(size_t total_count, size_t available_count) { total_request_count_ = total_count; available_request_count_ = available_count; } // Test helper to queue the two given requests. void PickRequestTaskTest::QueueRequests(const SavePageRequest& request1, const SavePageRequest& request2) { DeviceConditions conditions; std::set<int64_t> disabled_requests; // Add test requests on the Queue. store_->AddRequest(request1, base::Bind(&PickRequestTaskTest::AddRequestDone, base::Unretained(this))); store_->AddRequest(request2, base::Bind(&PickRequestTaskTest::AddRequestDone, base::Unretained(this))); // Pump the loop to give the async queue the opportunity to do the adds. PumpLoop(); } void PickRequestTaskTest::MakeFactoryAndTask() { factory_.reset(new PickRequestTaskFactory(policy_.get(), notifier_.get(), &event_logger_)); DeviceConditions conditions; task_ = factory_->CreatePickerTask( store_.get(), base::Bind(&PickRequestTaskTest::RequestPicked, base::Unretained(this)), base::Bind(&PickRequestTaskTest::RequestNotPicked, base::Unretained(this)), base::Bind(&PickRequestTaskTest::RequestCountCallback, base::Unretained(this)), conditions, disabled_requests_); task_->SetTaskCompletionCallbackForTesting( task_runner_.get(), base::Bind(&PickRequestTaskTest::TaskCompletionCallback, base::Unretained(this))); } TEST_F(PickRequestTaskTest, PickFromEmptyQueue) { task()->Run(); PumpLoop(); // Pump the loop again to give the async queue the opportunity to return // results from the Get operation, and for the picker to call the "QueueEmpty" // callback. PumpLoop(); EXPECT_TRUE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 0, total_request_count_); EXPECT_EQ((size_t) 0, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithHigherRetryCount) { // Set up policy to prefer higher retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 2, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithSameRetryCountButEarlier) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseEarlierRequest) { // We need a custom policy object prefering recency to retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseSameTimeRequestWithHigherRetryCount) { // We need a custom policy object preferring recency to retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithLowerRetryCount) { // We need a custom policy object preferring lower retry count. policy_.reset(new OfflinerPolicy( !kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseLaterRequest) { // We need a custom policy preferring recency over retry, and later requests. policy_.reset(new OfflinerPolicy( kPreferUntried, !kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseNonExpiredRequest) { base::Time creation_time = base::Time::Now(); base::Time expired_time = creation_time - base::TimeDelta::FromSeconds( policy_->GetRequestExpirationTimeInSeconds() + 60); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, expired_time, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ(kRequestId2, GetNotifier()->last_expired_request().request_id()); EXPECT_EQ(RequestNotifier::BackgroundSavePageResult::EXPIRED, GetNotifier()->last_request_expiration_status()); EXPECT_EQ(1, GetNotifier()->total_expired_requests()); EXPECT_EQ((size_t) 1, total_request_count_); EXPECT_EQ((size_t) 1, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatHasNotExceededStartLimit) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(1); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); // With default policy settings, we should choose the earlier request. // However, we will make the earlier reqeust exceed the limit. request1.set_started_attempt_count(policy_->GetMaxStartedTries()); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); // TODO(dougarnett): Counts should be 1 here once requests exceeding start // count get cleaned up from the queue. EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 2, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatHasNotExceededCompletionLimit) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(1); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); // With default policy settings, we should choose the earlier request. // However, we will make the earlier reqeust exceed the limit. request1.set_completed_attempt_count(policy_->GetMaxCompletedTries()); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatIsNotDisabled) { policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); // put request 2 on disabled list, ensure request1 picked instead, // even though policy would prefer 2. disabled_requests_.insert(kRequestId2); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); // Add test requests on the Queue. QueueRequests(request1, request2); task()->Run(); PumpLoop(); // Pump the loop again to give the async queue the opportunity to return // results from the Get operation, and for the picker to call the "picked" // callback. PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 1, available_request_count_); EXPECT_TRUE(task_complete_called_); } } // namespace offline_pages
36.018634
81
0.737656
xzhan96
900356520d1644a56ff7e1a5bb5c4b0431d176a4
3,882
cc
C++
chrome/browser/sync_file_system/drive_backend/metadata_db_migration_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/sync_file_system/drive_backend/metadata_db_migration_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
chrome/browser/sync_file_system/drive_backend/metadata_db_migration_util.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/sync_file_system/drive_backend/metadata_db_migration_util.h" #include <memory> #include "base/files/file_path.h" #include "base/strings/string_util.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_util.h" #include "storage/common/file_system/file_system_types.h" #include "storage/common/file_system/file_system_util.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" #include "url/gurl.h" namespace sync_file_system { namespace drive_backend { SyncStatusCode MigrateDatabaseFromV4ToV3(leveldb::DB* db) { // Rollback from version 4 to version 3. // Please see metadata_database_index.cc for version 3 format, and // metadata_database_index_on_disk.cc for version 4 format. const char kDatabaseVersionKey[] = "VERSION"; const char kServiceMetadataKey[] = "SERVICE"; const char kFileMetadataKeyPrefix[] = "FILE: "; const char kFileTrackerKeyPrefix[] = "TRACKER: "; // Key prefixes used in version 4. const char kAppRootIDByAppIDKeyPrefix[] = "APP_ROOT: "; const char kActiveTrackerIDByFileIDKeyPrefix[] = "ACTIVE_FILE: "; const char kTrackerIDByFileIDKeyPrefix[] = "TRACKER_FILE: "; const char kMultiTrackerByFileIDKeyPrefix[] = "MULTI_FILE: "; const char kActiveTrackerIDByParentAndTitleKeyPrefix[] = "ACTIVE_PATH: "; const char kTrackerIDByParentAndTitleKeyPrefix[] = "TRACKER_PATH: "; const char kMultiBackingParentAndTitleKeyPrefix[] = "MULTI_PATH: "; const char kDirtyIDKeyPrefix[] = "DIRTY: "; const char kDemotedDirtyIDKeyPrefix[] = "DEMOTED_DIRTY: "; leveldb::WriteBatch write_batch; write_batch.Put(kDatabaseVersionKey, "3"); std::unique_ptr<leveldb::Iterator> itr( db->NewIterator(leveldb::ReadOptions())); for (itr->SeekToFirst(); itr->Valid(); itr->Next()) { std::string key = itr->key().ToString(); // Do nothing for valid entries in both versions. if (base::StartsWith(key, kServiceMetadataKey, base::CompareCase::SENSITIVE) || base::StartsWith(key, kFileMetadataKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kFileTrackerKeyPrefix, base::CompareCase::SENSITIVE)) { continue; } // Drop entries used in version 4 only. if (base::StartsWith(key, kAppRootIDByAppIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kActiveTrackerIDByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kTrackerIDByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kMultiTrackerByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kActiveTrackerIDByParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kTrackerIDByParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kMultiBackingParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kDirtyIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kDemotedDirtyIDKeyPrefix, base::CompareCase::SENSITIVE)) { write_batch.Delete(key); continue; } DVLOG(3) << "Unknown key: " << key << " was found."; } return LevelDBStatusToSyncStatusCode( db->Write(leveldb::WriteOptions(), &write_batch)); } } // namespace drive_backend } // namespace sync_file_system
42.195652
85
0.684956
zealoussnow
90044551c41793b722cde64188cefbb72f5c5e1c
1,132
cpp
C++
iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.cpp
KKimj/iree
0d6768c194489225eaa12b3d8eda5752099ae10a
[ "Apache-2.0" ]
1
2021-07-20T23:37:11.000Z
2021-07-20T23:37:11.000Z
iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.cpp
KoolJBlack/iree
f300aee8c9d0da48179737b77abe690ab58e12f2
[ "Apache-2.0" ]
null
null
null
iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.cpp
KoolJBlack/iree
f300aee8c9d0da48179737b77abe690ab58e12f2
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.h" #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/SourceMgr.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/OpDefinition.h" #include "mlir/IR/OpImplementation.h" #include "mlir/Parser.h" #include "mlir/Transforms/InliningUtils.h" namespace mlir { namespace iree_compiler { namespace linalg_ext { LinalgExtDialect::LinalgExtDialect(MLIRContext *context) : Dialect(getDialectNamespace(), context, TypeID::get<LinalgExtDialect>()) { // TODO(hanchung): Add interface to the dialect. // addInterfaces<IREEInlinerInterface>(); #define GET_OP_LIST addOperations< #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp.inc" >(); } } // namespace linalg_ext } // namespace iree_compiler } // namespace mlir
31.444444
80
0.764134
KKimj
9005aa0ee10d0b20e9cd22bc685fe0053a2cfbb5
6,516
cpp
C++
cpp/oneapi/dal/algo/kmeans/test/batch.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
188
2016-04-16T12:11:48.000Z
2018-01-12T12:42:55.000Z
cpp/oneapi/dal/algo/kmeans/test/batch.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
1,198
2020-03-24T17:26:18.000Z
2022-03-31T08:06:15.000Z
cpp/oneapi/dal/algo/kmeans/test/batch.cpp
cmsxbc/oneDAL
eeb8523285907dc359c84ca4894579d5d1d9f57e
[ "Apache-2.0" ]
93
2018-01-23T01:59:23.000Z
2020-03-16T11:04:19.000Z
/******************************************************************************* * Copyright 2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/algo/kmeans/test/fixture.hpp" namespace oneapi::dal::kmeans::test { template <typename TestType> class kmeans_batch_test : public kmeans_test<TestType, kmeans_batch_test<TestType>> {}; /* TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans degenerated test", "[kmeans][batch]", kmeans_types) { // number of observations is equal to number of centroids (obvious clustering) SKIP_IF(this->not_float64_friendly()); using Float = std::tuple_element_t<0, TestType>; Float data[] = { 0.0, 5.0, 0.0, 0.0, 0.0, 1.0, 1.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 5.0, 1.0 }; const auto x = homogen_table::wrap(data, 3, 5); Float responses[] = { 0, 1, 2 }; const auto y = homogen_table::wrap(responses, 3, 1); this->exact_checks(x, x, x, y, 3, 2, 0.0, 0.0, false); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans relocation test", "[kmeans][batch]", kmeans_types) { // relocation of empty cluster to the best candidate SKIP_IF(this->not_float64_friendly()); using Float = std::tuple_element_t<0, TestType>; Float data[] = { 0, 0, 0.5, 0, 0.5, 1, 1, 1 }; const auto x = homogen_table::wrap(data, 4, 2); Float initial_centroids[] = { 0.5, 0.5, 3, 3 }; const auto c_init = homogen_table::wrap(initial_centroids, 2, 2); Float final_centroids[] = { 0.25, 0, 0.75, 1 }; const auto c_final = homogen_table::wrap(final_centroids, 2, 2); std::int64_t responses[] = { 0, 0, 1, 1 }; const auto y = homogen_table::wrap(responses, 4, 1); Float expected_obj_function = 0.25; std::int64_t expected_n_iters = 4; this->exact_checks_with_reordering(x, c_init, c_final, y, 2, expected_n_iters + 1, 0.0, expected_obj_function, false); } */ TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans empty clusters test", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_empty_clusters(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans smoke train/infer test", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_on_smoke_data(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans train/infer on gold data", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_on_gold_data(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans block test", "[kmeans][batch][nightly][block]", kmeans_types) { // This test is not stable on CPU // TODO: Remove the following `SKIP_IF` once stability problem is resolved SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->check_on_large_data_with_one_cluster(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans partial centroids stress test", "[kmeans][batch][nightly][stress]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->partial_centroids_stress_test(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "higgs: samples=1M, iters=3", "[kmeans][batch][external-dataset][higgs]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 3; const std::string higgs_path = "workloads/higgs/dataset/higgs_1m_test.csv"; SECTION("clusters=10") { this->test_on_dataset(higgs_path, 10, iters, 3.1997724684, 14717484.0); } SECTION("clusters=100") { this->test_on_dataset(higgs_path, 100, iters, 2.7450205195, 10704352.0); } SECTION("cluster=250") { this->test_on_dataset(higgs_path, 250, iters, 2.5923397174, 9335216.0); } } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "susy: samples=0.5M, iters=10", "[kmeans][nightly][batch][external-dataset][susy]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 10; const std::string susy_path = "workloads/susy/dataset/susy_test.csv"; SECTION("clusters=10") { this->test_on_dataset(susy_path, 10, iters, 1.7730860782, 3183696.0); } SECTION("clusters=100") { this->test_on_dataset(susy_path, 100, iters, 1.9384844916, 1757022.625); } SECTION("cluster=250") { this->test_on_dataset(susy_path, 250, iters, 1.8950113604, 1400958.5); } } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "epsilon: samples=80K, iters=2", "[kmeans][nightly][batch][external-dataset][epsilon]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 2; const std::string epsilon_path = "workloads/epsilon/dataset/epsilon_80k_train.csv"; SECTION("clusters=512") { this->test_on_dataset(epsilon_path, 512, iters, 6.9367580565, 50128.640625, 1.0e-3); } SECTION("clusters=1024") { this->test_on_dataset(epsilon_path, 1024, iters, 5.59003873, 49518.75, 1.0e-3); } SECTION("cluster=2048") { this->test_on_dataset(epsilon_path, 2048, iters, 4.3202752143, 48437.6015625, 1.0e-3); } } } // namespace oneapi::dal::kmeans::test
35.606557
100
0.585635
cmsxbc
9007f010fc70494b9cb03902e9bd5a1b000e3a32
4,206
hxx
C++
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
1
2022-03-15T22:54:39.000Z
2022-03-15T22:54:39.000Z
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
null
null
null
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "pg/AsyncConnection.hxx" #include "event/FineTimerEvent.hxx" #include "io/Logger.hxx" #include <unordered_set> #include <unordered_map> #include <set> #include <string> #include <mutex> struct CertDatabaseConfig; class CertNameCacheHandler { public: virtual void OnCertModified(const std::string &name, bool deleted) noexcept = 0; }; /** * A frontend for #CertDatabase which establishes a cache of all host * names and keeps it up to date. * * All modifications run asynchronously in the main thread, and * std::unordered_set queries may be executed from any thread * (protected by the mutex). */ class CertNameCache final : Pg::AsyncConnectionHandler, Pg::AsyncResultHandler { const LLogger logger; CertNameCacheHandler &handler; Pg::AsyncConnection conn; FineTimerEvent update_timer; mutable std::mutex mutex; /** * A list of host names found in the database. */ std::unordered_set<std::string> names; /** * A list of alt_names found in the database. Each alt_name maps * to a list of common_name values it appears in. */ std::unordered_map<std::string, std::set<std::string>> alt_names; /** * The latest timestamp seen in a record. This is used for * incremental updates. */ std::string latest = "1971-01-01"; unsigned n_added, n_updated, n_deleted; /** * This flag is set to true as soon as the cached name list has * become complete for the first time. With an incomplete cache, * Lookup() will always return true, because we don't know yet if * the desired name is just not yet loaded. */ bool complete = false; public: CertNameCache(EventLoop &event_loop, const CertDatabaseConfig &config, CertNameCacheHandler &_handler) noexcept; auto &GetEventLoop() const noexcept { return update_timer.GetEventLoop(); } void Connect() noexcept { conn.Connect(); } void Disconnect() noexcept { conn.Disconnect(); update_timer.Cancel(); } /** * Check if the given name exists in the database. */ bool Lookup(const char *host) const noexcept; private: void OnUpdateTimer() noexcept; void ScheduleUpdate() noexcept; void UnscheduleUpdate() noexcept { update_timer.Cancel(); } void AddAltName(const std::string &common_name, std::string &&alt_name) noexcept; void RemoveAltName(const std::string &common_name, const std::string &alt_name) noexcept; /* virtual methods from Pg::AsyncConnectionHandler */ void OnConnect() override; void OnDisconnect() noexcept override; void OnNotify(const char *name) override; void OnError(std::exception_ptr e) noexcept override; /* virtual methods from Pg::AsyncResultHandler */ void OnResult(Pg::Result &&result) override; void OnResultEnd() override; void OnResultError() noexcept override; };
28.612245
80
0.737993
nn6n
901059cbdf1a351c4e96ca22bab157173cfa00e8
2,603
cc
C++
StRoot/StMcEvent/StMcSvtLadderHitCollection.cc
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
2
2018-12-24T19:37:00.000Z
2022-02-28T06:57:20.000Z
StRoot/StMcEvent/StMcSvtLadderHitCollection.cc
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
StRoot/StMcEvent/StMcSvtLadderHitCollection.cc
xiaohaijin/RHIC-STAR
a305cb0a6ac15c8165bd8f0d074d7075d5e58752
[ "MIT" ]
null
null
null
/*************************************************************************** * * $Id: StMcSvtLadderHitCollection.cc,v 2.5 2005/01/27 23:40:48 calderon Exp $ * * Author: Manuel Calderon de la Barca Sanchez, Oct 1999 *************************************************************************** * * Description: Monte Carlo Svt Ladder Hit Collection class * *************************************************************************** * * $Log: StMcSvtLadderHitCollection.cc,v $ * Revision 2.5 2005/01/27 23:40:48 calderon * Adding persistency to StMcEvent as a step for Virtual MonteCarlo. * * Revision 2.4 2000/04/19 14:34:48 calderon * More corrections for the SSD, thanks Helen * * Revision 2.3 2000/03/06 18:05:22 calderon * 1) Modified SVT Hits storage scheme from layer-ladder-wafer to * barrel-ladder-wafer. * 2) Added Rich Hit class and collection, and links to them in other * classes. * * Revision 2.2 1999/12/14 07:04:49 calderon * Numbering scheme as per SVT request. * * Revision 2.1 1999/11/19 19:06:33 calderon * Recommit after redoing the files. * * Revision 2.0 1999/11/17 02:01:00 calderon * Completely revised for new StEvent * * **************************************************************************/ #include "StMcSvtLadderHitCollection.hh" static const char rcsid[] = "$Id: StMcSvtLadderHitCollection.cc,v 2.5 2005/01/27 23:40:48 calderon Exp $"; ClassImp(StMcSvtLadderHitCollection); StMcSvtLadderHitCollection::StMcSvtLadderHitCollection() { mBarrelNumber = -1; } StMcSvtLadderHitCollection::~StMcSvtLadderHitCollection() { /* noop */ } void StMcSvtLadderHitCollection::setBarrelNumber(int i) { if (mBarrelNumber == -1) mBarrelNumber = i; } unsigned int StMcSvtLadderHitCollection::numberOfWafers() const { switch (mBarrelNumber) { case 0: return 4; break; case 1: return 6; break; case 2: return 7; break; case 3: // SSD return 16; break; default: return 0; } } unsigned long StMcSvtLadderHitCollection::numberOfHits() const { unsigned long sum = 0; for (unsigned int j=0; j<numberOfWafers(); j++) { sum += mWafers[j].hits().size(); } return sum; } StMcSvtWaferHitCollection* StMcSvtLadderHitCollection::wafer(unsigned int i) { if (i < numberOfWafers()) return &(mWafers[i]); else return 0; } const StMcSvtWaferHitCollection* StMcSvtLadderHitCollection::wafer(unsigned int i) const { if (i < numberOfWafers()) return &(mWafers[i]); else return 0; }
25.519608
106
0.594698
xiaohaijin
90183a01785e0cb09c6d13539f9d2eabbdb6540f
2,117
cpp
C++
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
2
2017-06-01T16:43:37.000Z
2017-06-07T16:17:51.000Z
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
#include "raytracer.hpp" #include "ray.hpp" #include "scene.hpp" #include "primitive/iprimitive.hpp" namespace Rendering { RayTracer::RayTracer(unsigned long pixelWidth, unsigned long pixelHeight, double width, double height, double depth) : m_pixel_width(pixelWidth) , m_pixel_height(pixelHeight) , width(width) , height(height) , depth(depth) { origin.fill(0.); direction.fill(0.); direction(2) = 1; updateParameters(); } RayTracer::~RayTracer() = default; Image RayTracer::draw() const { Image res{Eigen::Index(m_pixel_height), Eigen::Index(m_pixel_width)}; for(std::size_t j = 0; j < m_pixel_height; ++j) { for(std::size_t i = 0; i < m_pixel_width; ++i) { res(j, i) = computeColor(generateRay(i, j)); } } return res; } void RayTracer::setViewer(double width, double height, const Math::Vector3d& origin, const Math::Vector3d& direction) { this->width = width; this->height = height; this->origin = origin; this->direction = direction; updateParameters(); } void RayTracer::setResolution(unsigned long pixelWidth, unsigned long pixelHeight) { m_pixel_width = pixelWidth; m_pixel_height = pixelHeight; updateParameters(); } void RayTracer::setScene(Scene* scene) { m_scene = scene; } Ray RayTracer::generateRay(const std::size_t x, const std::size_t y) const { Math::Vector3d dir = Math::createPoint(precompWidth * (x - m_pixel_width / 2.), precompHeight * (y - m_pixel_height / 2.), depth); return Ray(origin, Math::normalize(dir)); } Color RayTracer::computeColor(const Ray& ray) const { Color color; color.fill(0.); double distance; const auto index = m_scene->getFirstCollision(ray, distance); if(index) { Math::Vector3d normal; auto& primitive = m_scene->getPrimitive(*index); primitive.computeColorNormal(ray, distance, color, normal); } return color; } void RayTracer::updateParameters() { precompWidth = width / m_pixel_width; precompHeight = height / m_pixel_height; } } // Rendering
23.522222
119
0.665092
julienlopez
901864f6c5ebaa32c3709ad8528b0c4cc0ce91fc
5,268
cpp
C++
src/unittest.cpp
mdavidsaver/pvsx
3329b4d4ca9a7caa8658a993ff88fbbbac764f98
[ "BSD-3-Clause" ]
null
null
null
src/unittest.cpp
mdavidsaver/pvsx
3329b4d4ca9a7caa8658a993ff88fbbbac764f98
[ "BSD-3-Clause" ]
null
null
null
src/unittest.cpp
mdavidsaver/pvsx
3329b4d4ca9a7caa8658a993ff88fbbbac764f98
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright - See the COPYRIGHT that is included with this distribution. * pvxs is distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. */ #include "pvxs/version.h" #if !defined(GCC_VERSION) || GCC_VERSION>VERSION_INT(4,9,0,0) # include <regex> #else // GCC 4.8 provides the regex header and symbols, but with a no-op implementation // so fill in the gap with POSIX regex # include <sys/types.h> # include <regex.h> # define USE_POSIX_REGEX #endif #include <epicsUnitTest.h> #include "pvxs/unittest.h" #include "utilpvt.h" #include "udp_collector.h" namespace pvxs { void testSetup() { #ifdef _WIN32 // One of the SEM_* options, either SEM_FAILCRITICALERRORS or SEM_NOGPFAULTERRORBOX, // depending on who you ask, acts to disable Windows Error Reporting entirely. // This also prevents the AeDebug facility from triggering. UINT prev = SetErrorMode(0); if(prev) testDiag("SetErrorMode() disables 0x%x\n", (unsigned)prev); #endif } void cleanup_for_valgrind() { for(auto& pair : instanceSnapshot()) { // This will mess up test counts, but is the only way // 'prove' will print the result in CI runs. if(pair.second!=0) testFail("Instance leak %s : %zu", pair.first.c_str(), pair.second); } #if LIBEVENT_VERSION_NUMBER >= 0x02010000 libevent_global_shutdown(); #endif impl::logger_shutdown(); impl::UDPManager::cleanup(); IfaceMap::cleanup(); } testCase::testCase() :result(Diag) {} testCase::testCase(bool result) :result(result ? Pass : Fail) {} testCase::testCase(testCase&& o) noexcept :result(o.result) #if !GCC_VERSION || GCC_VERSION>=VERSION_INT(4,10,0,0) ,msg(std::move(o.msg)) #else // gcc 4.8 (at least) doesn't provide a move ctor yet ,msg(o.msg.str()) #endif { o.result = Nothing; } testCase& testCase::operator=(testCase&& o) noexcept { if(this!=&o) { result = o.result; o.result = Nothing; #if !GCC_VERSION || GCC_VERSION>=VERSION_INT(4,10,0,0) msg = std::move(o.msg); #else msg.seekp(0); msg.str(o.msg.str()); #endif } return *this; } testCase::~testCase() { if(result==Nothing) return; std::istringstream strm(msg.str()); for(std::string line; std::getline(strm, line);) { if(result==Diag) { testDiag("%s", line.c_str()); } else { testOk(result==Pass, "%s", line.c_str()); result=Diag; } } } testCase& testCase::setPassMatch(const std::string& expr, const std::string& inp) { #ifdef USE_POSIX_REGEX regex_t ex{}; if(auto err = regcomp(&ex, expr.c_str(), REG_EXTENDED|REG_NOSUB)) { auto len = regerror(err, &ex, nullptr, 0u); std::vector<char> msg(len+1); (void)regerror(err, &ex, msg.data(), len); msg[len] = '\0'; // paranoia setPass(false); (*this)<<" expression error: "<<msg.data()<<" :"; } else { setPass(regexec(&ex, inp.c_str(), 0, nullptr, 0)!=REG_NOMATCH); regfree(&ex); } #else std::regex ex; try { ex.assign(expr, std::regex_constants::extended); setPass(std::regex_match(inp, ex)); }catch(std::regex_error& e) { setPass(false); (*this)<<" expression error: "<<e.what()<<" :"; } #endif return *this; } namespace detail { size_t findNextLine(const std::string& s, size_t pos=0u) { size_t next = s.find_first_of('\n', pos); if(next!=std::string::npos) next++; return next; } testCase _testStrTest(unsigned op, const char *sLHS, const char* rlhs, const char *sRHS, const char* rrhs) { bool eq; if(rlhs==rrhs) // same string. handles NULL==NULL eq = true; else if(!rlhs ^ !rrhs) // one NULL eq = false; else eq = strcmp(rlhs, rrhs)==0; testCase ret(eq==op); ret<<sLHS<<(op ? " == " : " != ")<<sRHS<<"\n"; std::string lhs(rlhs ? rlhs : "<null>"); std::string rhs(rrhs ? rrhs : "<null>"); size_t posL=0u, posR=0u; while(posL<lhs.size() && posR<rhs.size()) { size_t eolL = findNextLine(lhs, posL); size_t eolR = findNextLine(rhs, posR); auto L = lhs.substr(posL, eolL-posL); auto R = rhs.substr(posR, eolR-posR); if(L==R) { ret<<" \""<<escape(L)<<"\"\n"; } else { ret<<"+ \""<<escape(R)<<"\"\n"; ret<<"- \""<<escape(L)<<"\"\n"; } posL = eolL; posR = eolR; } while(posR<rhs.size()) { size_t eol = findNextLine(rhs, posR); auto line = rhs.substr(posR, eol-posR); ret<<"+ \""<<escape(line)<<"\"\n"; posR = eol; } while(posL<lhs.size()) { size_t eol = findNextLine(lhs, posL); auto line = lhs.substr(posL, eol-posL); ret<<"- \""<<escape(line)<<"\"\n"; posL = eol; } return ret; } testCase _testStrMatch(const char *spat, const std::string& pat, const char *sstr, const std::string& str) { testCase ret; ret.setPassMatch(pat, str); ret<<spat<<" (\""<<pat<<"\") match "<<str<<" (\""<<escape(str)<<"\")"; return ret; } } // namespace detail } // namespace pvxs
24.502326
106
0.583523
mdavidsaver
901a5e5c825e9912d1fd0125af06fc595a81657e
6,612
cpp
C++
src/editor/src/material/material_thumbnail.cpp
AirGuanZ/Atrc
a0c4bc1b7bb96ddffff8bb1350f88b651b94d993
[ "MIT" ]
358
2018-11-29T08:15:05.000Z
2022-03-31T07:48:37.000Z
src/editor/src/material/material_thumbnail.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
23
2019-04-06T17:23:58.000Z
2022-02-08T14:22:46.000Z
src/editor/src/material/material_thumbnail.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
22
2019-03-04T01:47:56.000Z
2022-01-13T06:06:49.000Z
#include <agz/editor/material/material_thumbnail.h> #include <agz/tracer/core/intersection.h> #include <agz/tracer/core/bsdf.h> #include <agz/tracer/core/light.h> #include <agz/tracer/core/sampler.h> #include <agz/tracer/create/envir_light.h> #include <agz/tracer/create/texture2d.h> #include <agz/tracer/utility/sphere_aux.h> #include <agz-utils/image.h> AGZ_EDITOR_BEGIN namespace { class MaterialThumbnailEnvLight { RC<const tracer::EnvirLight> env_light_; public: MaterialThumbnailEnvLight() { const unsigned char data[] = { #include "./material_thumbnail_env.txt" }; auto tex_data = img::load_rgb_from_hdr_memory(data, sizeof(data)); auto img_data = newRC<Image2D<math::color3f>>(std::move(tex_data)); auto tex = tracer::create_hdr_texture({}, img_data, "linear"); env_light_ = create_ibl_light(tex); } const tracer::EnvirLight *operator->() const { return env_light_.get(); } }; Spectrum illum( const Vec3 &wo, const Vec3 &nor, const tracer::BSDF *bsdf, const MaterialThumbnailEnvLight &light, tracer::Sampler &sampler) { Spectrum bsdf_illum, light_illum; const auto bsdf_sample = bsdf->sample_all( wo, tracer::TransMode::Radiance, sampler.sample3()); if(!bsdf_sample.f.is_black()) { const real cos_v = std::abs(cos(bsdf_sample.dir, nor)); const Spectrum env = light->radiance({}, bsdf_sample.dir); if(bsdf->is_delta()) bsdf_illum = bsdf_sample.f * cos_v * env / bsdf_sample.pdf; else { const real env_pdf = light->pdf({}, bsdf_sample.dir); bsdf_illum = bsdf_sample.f * cos_v * env / (bsdf_sample.pdf + env_pdf); } } const auto light_sample = light->sample({}, sampler.sample5()); if(!light_sample.radiance.is_black()) { const Vec3 wi = light_sample.ref_to_light(); const Spectrum f = bsdf->eval_all(wi, wo, tracer::TransMode::Radiance); const real cos_v = std::abs(cos(wi, nor)); const real bsdf_pdf = bsdf->pdf_all(wi, wo); light_illum = light_sample.radiance * f * cos_v / (light_sample.pdf + bsdf_pdf); } return bsdf_illum + light_illum; } } // IMPROVE: bssrdf is not handled void MaterialThumbnailProvider::run_one_iter(int spp) { static const MaterialThumbnailEnvLight env; tracer::Arena arena; real init_xf, zf, df; if(width_ < height_) { df = real(6) / width_; init_xf = -3 + df / 2; zf = real(height_) / width_ * 3 - df / 2; } else { df = real(6) / height_; zf = 3 - df / 2; init_xf = -real(width_) / height_ * 3 + df / 2; } for(int y = 0; y < height_; ++y) { real xf = init_xf; if(exit_) return; for(int x = 0; x < width_; ++x) { for(int s = 0; s < spp; ++s) { const real pxf = xf + (sampler_->sample1().u - 1) * df; const real pzf = zf + (sampler_->sample1().u - 1) * df; if(pxf * pxf + pzf * pzf < 4) { const real pyf = -std::sqrt(4 - pxf * pxf - pzf * pzf); tracer::FCoord coord; Vec2 uv; tracer::sphere::local_geometry_uv_and_coord( { pxf, pyf, pzf }, &uv, &coord, 2); tracer::SurfacePoint spt; spt.pos = { pxf, pyf, pzf }; spt.uv = uv; spt.geometry_coord = coord; spt.user_coord = coord; tracer::EntityIntersection inct; (tracer::SurfacePoint &)inct = spt; inct.entity = nullptr; inct.material = mat_.get(); inct.medium_in = nullptr; inct.medium_out = nullptr; inct.wr = { 0, 0, 1 }; inct.t = 1; auto shd = mat_->shade(inct, arena); Spectrum color; for(int j = 0; j < 4; ++j) { color += illum( { 0, -1, 0 }, spt.geometry_coord.z, shd.bsdf, env, *sampler_); } accum_color_(y, x) += real(0.25) * color; } else accum_color_(y, x) += Spectrum(real(0.2)); } xf += df; } zf -= df; } ++finished_iters_; finished_spp_ += spp; } QPixmap MaterialThumbnailProvider::compute_pixmap() { assert(finished_iters_ > 0); const real ratio = real(1) / finished_spp_; QImage img(width_, height_, QImage::Format_RGB888); for(int y = 0; y < height_; ++y) { for(int x = 0; x < width_; ++x) { const Spectrum color = accum_color_(y, x).map([=](real c) { return std::pow(c * ratio, 1 / real(2.2)); }).saturate(); img.setPixelColor(x, y, QColor::fromRgbF(color.r, color.g, color.b)); } } QPixmap ret; ret.convertFromImage(img); return ret; } MaterialThumbnailProvider::MaterialThumbnailProvider( int width, int height, RC<const tracer::Material> mat, int iter_spp, int iter_count) : width_(width), height_(height), mat_(std::move(mat)), exit_(false) { iter_spp_ = iter_spp; iter_count_ = iter_count; finished_iters_ = 0; finished_spp_ = 0; } MaterialThumbnailProvider::~MaterialThumbnailProvider() { assert(!exit_); exit_ = true; if(render_thread_.joinable()) render_thread_.join(); } QPixmap MaterialThumbnailProvider::start() { assert(!exit_); accum_color_.initialize(height_, width_, Spectrum()); sampler_ = newRC<tracer::NativeSampler>(42, false); run_one_iter(1); auto ret = compute_pixmap(); render_thread_ = std::thread([=] { for(;;) { if(exit_) return; if(finished_iters_ >= iter_count_) return; run_one_iter(iter_spp_); if(exit_) return; emit update_thumbnail(compute_pixmap()); } }); return ret; } AGZ_EDITOR_END
27.781513
83
0.515578
AirGuanZ
901b8d620c5436fbb9d5e84d41d8def00b92882e
10,680
cpp
C++
aten/src/TH/generic/THTensorLapack.cpp
deltabravozulu/pytorch
c6eef589971e45bbedacc7f65533d1b8f80a6895
[ "Intel" ]
6
2021-09-05T06:00:59.000Z
2022-01-07T07:05:18.000Z
aten/src/TH/generic/THTensorLapack.cpp
deltabravozulu/pytorch
c6eef589971e45bbedacc7f65533d1b8f80a6895
[ "Intel" ]
2
2022-01-10T03:56:45.000Z
2022-02-01T03:39:54.000Z
aten/src/TH/generic/THTensorLapack.cpp
deltabravozulu/pytorch
c6eef589971e45bbedacc7f65533d1b8f80a6895
[ "Intel" ]
2
2021-07-02T10:18:21.000Z
2021-08-18T10:10:28.000Z
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "TH/generic/THTensorLapack.cpp" #else /* Check if self is transpose of a contiguous matrix */ static int THTensor_(isTransposedContiguous)(THTensor *self) { return self->stride(0) == 1 && self->stride(1) == self->size(0); } /* Check if self contains any inf or NaN values */ static int THTensor_(isFinite)(THTensor *self) { std::atomic<int> finite{1}; TH_TENSOR_APPLY(scalar_t, self, if (finite && !std::isfinite(*self_data)) { finite = 0; TH_TENSOR_APPLY_hasFinished = 1; break; }); return finite; } /* If a matrix is a regular contiguous matrix, make sure it is transposed because this is what we return from Lapack calls. */ static void THTensor_(checkTransposed)(THTensor *self) { if(THTensor_(isContiguous)(self)) THTensor_(transpose)(self, NULL, 0, 1); return; } /* newContiguous followed by transpose Similar to (newContiguous), but checks if the transpose of the matrix is contiguous and also limited to 2D matrices. */ static THTensor *THTensor_(newTransposedContiguous)(THTensor *self) { THTensor *tensor; if(THTensor_(isTransposedContiguous)(self)) { THTensor_(retain)(self); tensor = self; } else { tensor = THTensor_(newContiguous)(self); THTensor_(transpose)(tensor, NULL, 0, 1); } return tensor; } /* Given the result tensor and src tensor, decide if the lapack call should use the provided result tensor or should allocate a new space to put the result in. The returned tensor have to be freed by the calling function. nrows is required, because some lapack calls, require output space smaller than input space, like underdetermined gels. */ static THTensor *THTensor_(checkLapackClone)(THTensor *result, THTensor *src, int nrows) { /* check if user wants to reuse src and if it is correct shape/size */ if (src == result && THTensor_(isTransposedContiguous)(src) && src->size(1) == nrows) THTensor_(retain)(result); else if(src == result || result == NULL) /* in this case, user wants reuse of src, but its structure is not OK */ result = THTensor_(new)(); else THTensor_(retain)(result); return result; } /* Same as cloneColumnMajor, but accepts nrows argument, because some lapack calls require the resulting tensor to be larger than src. */ static THTensor *THTensor_(cloneColumnMajorNrows)(THTensor *self, THTensor *src, int nrows) { THTensor *result; THTensor *view; if (src == NULL) src = self; result = THTensor_(checkLapackClone)(self, src, nrows); if (src == result) return result; THTensor_(resize2d)(result, src->size(1), nrows); THTensor_(checkTransposed)(result); if (src->size(0) == nrows) { at::Tensor result_wrap = THTensor_wrap(result); at::Tensor src_wrap = THTensor_wrap(src); at::native::copy_(result_wrap, src_wrap); } else { view = THTensor_(newNarrow)(result, 0, 0, src->size(0)); at::Tensor view_wrap = THTensor_wrap(view); at::Tensor src_wrap = THTensor_wrap(src); at::native::copy_(view_wrap, src_wrap); c10::raw::intrusive_ptr::decref(view); } return result; } /* Create a clone of src in self column major order for use with Lapack. If src == self, a new tensor is allocated, in any case, the return tensor should be freed by calling function. */ static THTensor *THTensor_(cloneColumnMajor)(THTensor *self, THTensor *src) { return THTensor_(cloneColumnMajorNrows)(self, src, src->size(0)); } void THTensor_(gels)(THTensor *rb_, THTensor *ra_, THTensor *b, THTensor *a) { int free_b = 0; // Note that a = NULL is interpreted as a = ra_, and b = NULL as b = rb_. if (a == NULL) a = ra_; if (b == NULL) b = rb_; THArgCheck(a->dim() == 2, 2, "A should have 2 dimensions, but has %d", a->dim()); THArgCheck(!a->is_empty(), 2, "A should not be empty"); THArgCheck(b->dim() == 1 || b->dim() == 2, 1, "B should have 1 or 2 " "dimensions, but has %d", b->dim()); THArgCheck(!b->is_empty(), 1, "B should not be empty"); TORCH_CHECK(a->size(0) == b->size(0), "Expected A and b to have same size " "at dim 0, but A has ", a->size(0), " rows and B has ", b->size(0), " rows"); if (b->dim() == 1) { b = THTensor_wrap(b).unsqueeze(1).unsafeReleaseTensorImpl(); free_b = 1; } int m, n, nrhs, lda, ldb, info, lwork; THTensor *work = NULL; scalar_t wkopt = 0; THTensor *ra__ = NULL; // working version of A matrix to be passed into lapack GELS THTensor *rb__ = NULL; // working version of B matrix to be passed into lapack GELS ra__ = THTensor_(cloneColumnMajor)(ra_, a); m = ra__->size(0); n = ra__->size(1); lda = m; ldb = (m > n) ? m : n; rb__ = THTensor_(cloneColumnMajorNrows)(rb_, b, ldb); nrhs = rb__->size(1); info = 0; /* get optimal workspace size */ THLapack_(gels)('N', m, n, nrhs, ra__->data<scalar_t>(), lda, rb__->data<scalar_t>(), ldb, &wkopt, -1, &info); lwork = (int)wkopt; work = THTensor_(newWithSize1d)(lwork); THLapack_(gels)('N', m, n, nrhs, ra__->data<scalar_t>(), lda, rb__->data<scalar_t>(), ldb, work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup("Lapack Error in %s : The %d-th diagonal element of the triangular factor of A is zero", THCleanup(c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(rb__); c10::raw::intrusive_ptr::decref(work); if (free_b) c10::raw::intrusive_ptr::decref(b);), "gels", info,""); /* * In the m < n case, if the input b is used as the result (so b == _rb), * then rb_ was originally m by nrhs but now should be n by nrhs. * This is larger than before, so we need to expose the new rows by resizing. */ if (m < n && b == rb_) { THTensor_(resize2d)(rb_, n, nrhs); } THTensor_(freeCopyTo)(ra__, ra_); THTensor_(freeCopyTo)(rb__, rb_); c10::raw::intrusive_ptr::decref(work); if (free_b) c10::raw::intrusive_ptr::decref(b); } /* The geqrf function does the main work of QR-decomposing a matrix. However, rather than producing a Q matrix directly, it produces a sequence of elementary reflectors which may later be composed to construct Q - for example with the orgqr function, below. Args: * `ra_` - Result matrix which will contain: i) The elements of R, on and above the diagonal. ii) Directions of the reflectors implicitly defining Q. * `rtau_` - Result tensor which will contain the magnitudes of the reflectors implicitly defining Q. * `a` - Input matrix, to decompose. If NULL, `ra_` is used as input. For further details, please see the LAPACK documentation. */ void THTensor_(geqrf)(THTensor *ra_, THTensor *rtau_, THTensor *a) { if (a == NULL) ra_ = a; THArgCheck(a->dim() == 2, 1, "A should be 2 dimensional"); THArgCheck(!a->is_empty(), 1, "A should not be empty"); THTensor *ra__ = NULL; /* Prepare the input for LAPACK, making a copy if necessary. */ ra__ = THTensor_(cloneColumnMajor)(ra_, a); int m = ra__->size(0); int n = ra__->size(1); int k = (m < n ? m : n); int lda = m; THTensor_(resize1d)(rtau_, k); /* Dry-run to query the suggested size of the workspace. */ int info = 0; scalar_t wkopt = 0; THLapack_(geqrf)(m, n, ra__->data<scalar_t>(), lda, rtau_->data<scalar_t>(), &wkopt, -1, &info); /* Allocate the workspace and call LAPACK to do the real work. */ int lwork = (int)wkopt; THTensor *work = THTensor_(newWithSize1d)(lwork); THLapack_(geqrf)(m, n, ra__->data<scalar_t>(), lda, rtau_->data<scalar_t>(), work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup("Lapack Error %s : unknown Lapack error. info = %i", THCleanup( c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(work);), "geqrf", info,""); THTensor_(freeCopyTo)(ra__, ra_); c10::raw::intrusive_ptr::decref(work); } /* The ormqr function multiplies Q with another matrix from a sequence of elementary reflectors, such as is produced by the geqrf function. Args: * `ra_` - result Tensor, which will contain the matrix Q' c. * `a` - input Tensor, which should be a matrix with the directions of the elementary reflectors below the diagonal. If NULL, `ra_` is used as input. * `tau` - input Tensor, containing the magnitudes of the elementary reflectors. * `c` - input Tensor, containing the matrix to be multiplied. * `left` - bool, determining whether c is left- or right-multiplied with Q. * `transpose` - bool, determining whether to transpose Q before multiplying. For further details, please see the LAPACK documentation. */ void THTensor_(ormqr)(THTensor *ra_, THTensor *a, THTensor *tau, THTensor *c, bool left, bool transpose) { char side = left ? 'L' : 'R'; char trans = transpose ? 'T' : 'N'; if (a == NULL) a = ra_; THArgCheck(THTensor_nDimensionLegacyAll(a) == 2, 1, "A should be 2 dimensional"); THTensor *ra__ = NULL; ra__ = THTensor_(cloneColumnMajor)(ra_, c); int m = c->size(0); int n = c->size(1); int k = THTensor_sizeLegacyNoScalars(tau, 0); int lda; if (side == 'L') { lda = m; } else { lda = n; } int ldc = m; /* Dry-run to query the suggested size of the workspace. */ int info = 0; scalar_t wkopt = 0; THLapack_(ormqr)(side, trans, m, n, k, a->data<scalar_t>(), lda, tau->data<scalar_t>(), ra__->data<scalar_t>(), ldc, &wkopt, -1, &info); /* Allocate the workspace and call LAPACK to do the real work. */ int lwork = (int)wkopt; THTensor *work = THTensor_(newWithSize1d)(lwork); THLapack_(ormqr)(side, trans, m, n, k, a->data<scalar_t>(), lda, tau->data<scalar_t>(), ra__->data<scalar_t>(), ldc, work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup(" Lapack Error %s : unknown Lapack error. info = %i", THCleanup( c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(work);), "ormqr", info,""); THTensor_(freeCopyTo)(ra__, ra_); c10::raw::intrusive_ptr::decref(work); } #endif
33.584906
115
0.625375
deltabravozulu
901c99d9ebe505fde0a6c9311fd970357766b100
27,140
cpp
C++
src/SpecialFormat.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
52
2016-05-26T19:24:37.000Z
2022-03-24T16:13:48.000Z
src/SpecialFormat.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
17
2017-02-04T00:10:50.000Z
2022-01-19T09:56:18.000Z
src/SpecialFormat.cpp
simonowen/samdisk
9b1391dd233015db633cb83b43d62c15a98f4e3a
[ "MIT" ]
9
2016-05-13T02:16:05.000Z
2020-08-30T11:34:34.000Z
// Copy-protected formats that require special support // // Contains detection and generation for each track format. // Output will be in bitstream or flux format (or both), // depending on the format requirements. #include "SAMdisk.h" #include "IBMPC.h" #include "BitstreamTrackBuilder.h" #include "FluxTrackBuilder.h" //////////////////////////////////////////////////////////////////////////////// bool IsEmptyTrack(const Track& track) { return track.size() == 0; } TrackData GenerateEmptyTrack(const CylHead& cylhead, const Track& track) { assert(IsEmptyTrack(track)); (void)track; // Generate a DD track full of gap filler. It shouldn't really matter // which datarate and encoding as long as there are no sync marks. BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addBlock(0x4e, 6250); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // KBI-19 protection (19 valid sectors on CPC+PC, plus 1 error sector on PC) bool IsKBI19Track(const Track& track) { static const uint8_t ids[]{ 0,1,4,7,10,13,16,2,5,8,11,14,17,3,6,9,12,15,18,19 }; // CPC version has 19 sectors, PC version has 20 (with bad sector 19). if (track.size() != arraysize(ids) && track.size() != arraysize(ids) - 1) return false; int idx = 0; for (auto& s : track.sectors()) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.sector != ids[idx++] || s.size() != 512 || (!s.has_good_data() && s.header.sector != 19)) return false; } if (opt.debug) util::cout << "detected KBI-19 track\n"; return true; } TrackData GenerateKBI19Track(const CylHead& cylhead, const Track& track) { assert(IsKBI19Track(track)); static const Data gap2_sig{ 0x20,0x4B,0x42,0x49,0x20 }; // " KBI " BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); // Track start with slightly shorter gap4a. bitbuf.addGap(64); bitbuf.addIAM(); bitbuf.addGap(50); int sector_index = 0; for (auto& s : track) { bitbuf.addSectorHeader(s.header); if (s.header.sector == 0) { bitbuf.addGap(17); bitbuf.addBlock(gap2_sig); } else { bitbuf.addGap(8); bitbuf.addBlock(gap2_sig); bitbuf.addGap(9); } bitbuf.addAM(s.dam); auto data = s.data_copy(); // Short or full sector data? if (sector_index++ % 3) { data.resize(61); bitbuf.addBlock(data); } else { if (s.header.sector == 0) { data.resize(s.size()); bitbuf.addBlock(data); bitbuf.addCrc(3 + 1 + 512); } else { auto crc_block_size = 3 + 1 + s.size(); bitbuf.addBlock({ data.begin() + 0, data.begin() + 0x10e }); bitbuf.addCrc(crc_block_size); bitbuf.addBlock({ data.begin() + 0x110, data.begin() + 0x187 }); bitbuf.addCrc(crc_block_size); bitbuf.addBlock({ data.begin() + 0x189, data.begin() + s.size() }); bitbuf.addCrc(crc_block_size); bitbuf.addGap(80); } } } // Pad up to normal track size. bitbuf.addGap(90); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Sega System 24 track? (currently just 0x2f00 variant) bool IsSystem24Track(const Track& track) { static const uint8_t sizes[] = { 4,4,4,4,4,3,1 }; auto i = 0; if (track.size() != arraysize(sizes)) return false; for (auto& s : track) { if (s.datarate != DataRate::_500K || s.encoding != Encoding::MFM || s.header.size != sizes[i++] || !s.has_data()) return false; } if (opt.debug) util::cout << "detected System-24 track\n"; return true; } TrackData GenerateSystem24Track(const CylHead& cylhead, const Track& track) { assert(IsSystem24Track(track)); BitstreamTrackBuilder bitbuf(DataRate::_500K, Encoding::MFM); for (auto& s : track) { auto gap3{ (s.header.sector < 6) ? 52 : 41 }; bitbuf.addSector(s, gap3); } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Speedlock weak sector for Spectrum +3? bool IsSpectrumSpeedlockTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector0 = track[0]; auto& sector1 = track[1]; if (sector0.encoding != Encoding::MFM || sector1.encoding != Encoding::MFM || sector0.datarate != DataRate::_250K || sector1.datarate != DataRate::_250K || sector0.size() != 512 || sector1.size() != 512 || sector0.data_size() < 512 || sector1.data_size() < 512 || !sector1.has_baddatacrc()) // weak sector return false; auto& data0 = sector0.data_copy(); auto& data1 = sector1.data_copy(); // Check for signature in the 2 known positions if (memcmp(data0.data() + 304, "SPEEDLOCK", 9) && memcmp(data0.data() + 176, "SPEEDLOCK", 9)) return false; // If there's no common block at the start, assume fully random // Buggy Boy has only 255, so don't check the full first half! if (memcmp(data1.data(), data1.data() + 1, (sector1.size() / 2) - 1)) { // -512 weak_offset = 0; weak_size = 512; } else { // =256 -33 +47 -176 weak_offset = 336; weak_size = 32; } if (opt.debug) util::cout << "detected Spectrum Speedlock track\n"; return true; } TrackData GenerateSpectrumSpeedlockTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsSpectrumSpeedlockTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[1] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[5]) { auto& sector1{ track[1] }; auto data1{ sector1.data_copy() }; std::fill(data1.begin() + weak_offset, data1.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector1.header, data1, 0x2e, sector1.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Speedlock weak sector for Amstrad CPC? bool IsCpcSpeedlockTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector0 = track[0]; auto& sector7 = track[7]; if (sector0.encoding != Encoding::MFM || sector7.encoding != Encoding::MFM || sector0.datarate != DataRate::_250K || sector7.datarate != DataRate::_250K || sector0.size() != 512 || sector7.size() != 512 || sector0.data_size() < 512 || sector7.data_size() < 512 || !sector7.has_baddatacrc()) // weak sector return false; auto& data0 = sector0.data_copy(); auto& data7 = sector7.data_copy(); // Check for signature in the boot sector if (memcmp(data0.data() + 257, "SPEEDLOCK", 9) && memcmp(data0.data() + 129, "SPEEDLOCK", 9)) { // If that's missing, look for a code signature if (memcmp(data0.data() + 208, "\x4a\x00\x09\x46\x00\x00\x00\x42\x02\x47\x2a\xff", 12) || CRC16(data0.data() + 49, 220 - 49) != 0x62c2) return false; } // If there's no common block at the start, assume fully random // Buggy Boy has only 255, so don't check the full first half! if (memcmp(data7.data(), data7.data() + 1, (sector7.size() / 2) - 1)) { // -512 weak_offset = 0; weak_size = 512; } else if (data0[129] == 'S') { // =256 -256 weak_offset = 256; weak_size = 256; } else { // =256 -33 +47 -176 weak_offset = 336; weak_size = 32; } if (opt.debug) util::cout << "detected CPC Speedlock track\n"; return true; } TrackData GenerateCpcSpeedlockTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsCpcSpeedlockTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[7] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[1]) { auto& sector7{ track[7] }; auto data7{ sector7.data_copy() }; std::fill(data7.begin() + weak_offset, data7.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector7.header, data7, 0x2e, sector7.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Rainbow Arts weak sector for CPC? bool IsRainbowArtsTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector1 = track[1]; auto& sector3 = track[3]; if (sector1.encoding != Encoding::MFM || sector3.encoding != Encoding::MFM || sector1.datarate != DataRate::_250K || sector3.datarate != DataRate::_250K || sector1.size() != 512 || sector3.size() != 512 || sector1.data_size() < 512 || sector3.data_size() < 512 || sector1.header.sector != 198 || !sector1.has_baddatacrc()) // weak sector 198 return false; auto& data3 = sector3.data_copy(); // Check for code signature at the start of the 4th sector if (memcmp(data3.data(), "\x2a\x6d\xa7\x01\x30\x01\xaf\xed\x42\x4d\x44\x21\x70\x01", 14)) return false; // The first 100 bytes are constant weak_offset = 100; // =100 -258 +151 -3 weak_size = 256; if (opt.debug) util::cout << "detected Rainbow Arts weak sector track\n"; return true; } TrackData GenerateRainbowArtsTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsRainbowArtsTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[1] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[5]) { // Add a duplicate of the weak sector, with different data from the weak position auto& sector1{ track[1] }; auto data1{ sector1.data_copy() }; std::fill(data1.begin() + weak_offset, data1.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector1.header, data1, 0x2e, sector1.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // KBI-10 weak sector for CPC? bool IsKBIWeakSectorTrack(const Track& track, int& weak_offset, int& weak_size) { auto sectors = track.size(); // Most titles use the 10-sector version, but some have 3x2K sectors. int size_code; if (sectors == 3) size_code = 4; else if (sectors == 10) size_code = 2; else return false; // Weak sector is always last on track and 256 bytes auto& sectorW = track[sectors - 1]; if (sectorW.encoding != Encoding::MFM || sectorW.datarate != DataRate::_250K || sectorW.header.size != 1 || sectorW.data_size() < 256 || !sectorW.has_baddatacrc()) { return false; } // The remaining sector must be the correct type and size code. for (int i = 0; i < sectors - 1; ++i) { auto& sector = track[i]; if (sector.encoding != Encoding::MFM || sector.datarate != DataRate::_250K || sector.header.size != size_code || sector.data_size() < Sector::SizeCodeToLength(size_code)) { return false; } } auto& dataW = sectorW.data_copy(); // The first character of the weak sector is 'K', and the next two are alphabetic. if (dataW[0] != 'K' || !std::isalpha(static_cast<uint8_t>(dataW[1])) || !std::isalpha(static_cast<uint8_t>(dataW[2]))) { return false; } // =4 -4 =124 -4 =120 weak_offset = 4; weak_size = 4; if (opt.debug) util::cout << "detected KBI weak sector track\n"; return true; } TrackData GenerateKBIWeakSectorTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsKBIWeakSectorTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); auto sectors = track.size(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak = sector.header.size == 1; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 1, sector.dam, is_weak); // Insert the duplicate sector earlier on the track. if (&sector == &track[((sectors - 1) / 2) - 1]) { auto& sectorW = track[sectors - 1]; auto dataW{ sectorW.data_copy() }; std::fill(dataW.begin() + weak_offset, dataW.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sectorW.header, dataW, 1, sectorW.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Logo Professor track? bool IsLogoProfTrack(const Track& track) { // Accept track with or without placeholder sector if (track.size() != 10 && track.size() != 11) return false; // First non-placeholder sector id. int id = 2; for (auto& s : track) { // Check for placeholder sector, present in old EDSK images. if (track.size() == 11 && s.header.sector == 1) { // It must have a bad ID header CRC. if (s.has_badidcrc()) continue; else return false; } // Ensure each sector is double-density MFM, 512-bytes, with good data if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.sector != id++ || s.size() != 512 || !s.has_good_data()) return false; } // If there's no placeholder, the first sector must begin late if (track.size() == 10) { // Determine an offset considered late auto min_offset = Sector::SizeCodeToLength(1) + GetSectorOverhead(Encoding::MFM); // Reject if first sector doesn't start late on the track if (track[0].offset < (min_offset * 16)) return false; } if (opt.debug) util::cout << "detected Logo Professor track\n"; return true; } TrackData GenerateLogoProfTrack(const CylHead& cylhead, const Track& track) { assert(IsLogoProfTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); bitbuf.addGap(600); for (auto& sector : track) { if (sector.header.sector != 1) bitbuf.addSector(sector, 0x20); } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // OperaSoft track with 32K sector bool IsOperaSoftTrack(const Track& track) { uint32_t sector_mask = 0; int i = 0; if (track.size() != 9) return false; for (auto& s : track) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM) return false; static const uint8_t sizes[] = { 1,1,1,1,1,1,1,1,8 }; if (s.header.size != sizes[i++]) return false; sector_mask |= (1 << s.header.sector); } // Sectors must be numbered 0 to 8 if (sector_mask != ((1 << 9) - 1)) return false; if (opt.debug) util::cout << "detected OperaSoft track with 32K sector\n"; return true; } TrackData GenerateOperaSoftTrack(const CylHead& cylhead, const Track& track) { assert(IsOperaSoftTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { if (sector.header.sector != 8) bitbuf.addSector(sector, 0xf0); else { auto& sector7 = track[7]; auto& sector8 = track[8]; bitbuf.addSectorUpToData(sector8.header, sector8.dam); bitbuf.addBlock(Data(256, 0x55)); bitbuf.addCrc(4 + 256); bitbuf.addBlock(Data(0x512 - 256 - 2, 0x4e)); bitbuf.addBlock(sector7.data_copy()); } } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // 8K sector track? bool Is8KSectorTrack(const Track& track) { // There must only be 1 sector. if (track.size() != 1) return false; auto& sector{ track[0] }; if (sector.datarate != DataRate::_250K || sector.encoding != Encoding::MFM || sector.size() != 8192 || !sector.has_data()) return false; if (opt.debug) util::cout << "detected 8K sector track\n"; return true; } TrackData Generate8KSectorTrack(const CylHead& cylhead, const Track& track) { assert(Is8KSectorTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addGap(16); // gap 4a bitbuf.addIAM(); bitbuf.addGap(16); // gap 1 auto& sector{ track[0] }; bitbuf.addSectorUpToData(sector.header, sector.dam); // Maximum size of long-track version used by Coin-Op Hits static constexpr auto max_size{ 0x18a3 }; auto data = sector.data_copy(); if (data.size() > max_size) data.resize(max_size); bitbuf.addBlock(data); bitbuf.addGap(max_size - data.size()); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Titus Prehistorik protection, which may be followed by unused KBI-19 sectors. // The KBI format isn't tested, so this seems to be a disk mastering error. bool IsPrehistorikTrack(const Track& track) { bool found_12{ false }; for (auto& s : track.sectors()) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.size != (s.has_baddatacrc() ? 5 : 2)) return false; // The 4K sector 12 contains the protection signature. if (s.header.sector == 12 && s.header.size == 5) { found_12 = true; auto& data12 = s.data_copy(); if (memcmp(data12.data() + 0x1b, "Titus", 5)) return false; } } if (!found_12) return false; if (opt.debug) util::cout << "detected Prehistorik track\n"; return true; } TrackData GeneratePrehistorikTrack(const CylHead& cylhead, const Track& track) { assert(IsPrehistorikTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); auto gap3 = (track.size() == 11) ? 106 : 30; for (auto& sector : track) { if (sector.header.sector != 12) bitbuf.addSector(sector, gap3); else { bitbuf.addSector(sector.header, sector.data_copy(), gap3, sector.dam, true); break; } } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// bool Is11SectorTrack(const Track& track) { if (track.size() != 11) return false; for (auto& s : track) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.size() != 512 || !s.has_good_data()) { return false; } } if (opt.debug) util::cout << "detected 11-sector tight track\n"; return true; } TrackData Generate11SectorTrack(const CylHead& cylhead, const Track& track) { assert(Is11SectorTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(true); for (auto& sector : track) bitbuf.addSector(sector, 1); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// #if 0 /* We don't currently use these functions, as patching the protection code gives a simpler and more reliable writing solution. The protection reads 8K from cyl 38 sector 1 and takes a byte at offset 0x1f9f. It then reads cyl 39 sector 195 and reads a byte at offset 0x1ff. If the two bytes don't match the protection fails and the computer is reset. The byte sampled from sector 1 is part of 2K of E5 filler bytes, so the byte read from the second track revolution will be one of the 16 possible MFM data or clock patterns: E5 CB 97 2F 5E BC 79 F2 10 20 40 80 01 02 04 08. To write the protection we must read the byte from sector 1 and ensure the correct byte is written to the end of sector 195. If the track splice sync isn't reliable for sector 1 it may need to be formatted multiple times. */ // Reussir protection with leading 8K sector. bool IsReussirProtectedTrack(const Track& track) { if (track.size() != 2) return false; auto& sector1 = track[0]; auto& sector2 = track[1]; if (sector1.header.sector != 1 || sector1.datarate != DataRate::_250K || sector1.encoding != Encoding::MFM || sector1.size() != 8192 || !sector1.has_data() || !sector1.has_baddatacrc()) return false; if (sector2.header.sector != 2 || sector2.datarate != DataRate::_250K || sector2.encoding != Encoding::MFM || sector2.size() != 512 || !sector2.has_data() || !sector2.has_baddatacrc()) return false; if (opt.debug) util::cout << "detected Reussir protected track\n"; return true; } // This format isn't difficult to create, but we need to ensure it's close to // the correct length so the sampling point is comfortably within sector 1. TrackData GenerateReussirProtectedTrack(const CylHead& cylhead, const Track& track) { assert(IsReussirProtectedTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addGap(80); // gap 4a bitbuf.addIAM(); bitbuf.addGap(50); // gap 1 auto& sector1 = track[0]; bitbuf.addSectorUpToData(sector1.header, sector1.dam); bitbuf.addBlockUpdateCrc(0x4e, 2048); bitbuf.addCrcBytes(); bitbuf.addGap(82); auto& sector2 = track[1]; bitbuf.addSectorUpToData(sector2.header, sector2.dam); bitbuf.addBlockUpdateCrc(0x4e, 2048); bitbuf.addCrcBytes(); bitbuf.addGap(1802); return TrackData(cylhead, std::move(bitbuf.buffer())); } #endif ////////////////////////////////////////////////////////////////////////////////
31.303345
116
0.583567
simonowen
901efcd4a787e99a1fcef91d96c5071343ed3ada
1,918
cpp
C++
src/cpp_solver/Solver/GroupNodes/CubeNodeG2.cpp
pabloqb2000/py-rubik_solver
c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f
[ "Apache-2.0" ]
3
2021-09-11T14:44:40.000Z
2021-12-28T00:51:02.000Z
src/cpp_solver/Solver/GroupNodes/CubeNodeG2.cpp
pabloqb2000/py-rubik_solver
c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f
[ "Apache-2.0" ]
null
null
null
src/cpp_solver/Solver/GroupNodes/CubeNodeG2.cpp
pabloqb2000/py-rubik_solver
c1cf83fa62b6ff0dce9859fe59296c85a57f8d3f
[ "Apache-2.0" ]
4
2021-09-12T02:29:24.000Z
2021-12-18T13:39:46.000Z
#include "CubeNodeG2.h" /** * Create a CubeNode from a Cube * @param cube base cube */ CubeNodeG2::CubeNodeG2 (const Cube& cube) : CubeNode(cube) { } bool CubeNodeG2::isGoal() { typedef Cube::FACE FACE; // IDEA: replace this->getColor with this->cube[idx]; in all CubeNode files // Corners, left and right facets. FACE LUB = this->getColor(FACE::L, 0, 0); FACE LUF = this->getColor(FACE::L, 0, 2); FACE LDB = this->getColor(FACE::L, 2, 0); FACE LDF = this->getColor(FACE::L, 2, 2); FACE RUB = this->getColor(FACE::R, 0, 2); FACE RUF = this->getColor(FACE::R, 0, 0); FACE RDB = this->getColor(FACE::R, 2, 2); FACE RDF = this->getColor(FACE::R, 2, 0); // Edges in the M slice (between R and L). FACE UF = this->getColor(FACE::U, 2, 1); FACE FU = this->getColor(FACE::F, 0, 1); FACE UB = this->getColor(FACE::U, 0, 1); FACE BU = this->getColor(FACE::B, 0, 1); FACE DF = this->getColor(FACE::D, 0, 1); FACE FD = this->getColor(FACE::F, 2, 1); FACE DB = this->getColor(FACE::D, 2, 1); FACE BD = this->getColor(FACE::B, 2, 1); return // All left/right corner facets either blue or green. (LUB == FACE::R || LUB == FACE::L) && (LUF == FACE::R || LUF == FACE::L) && (LDB == FACE::R || LDB == FACE::L) && (LDF == FACE::R || LDF == FACE::L) && (RUB == FACE::R || RUB == FACE::L) && (RUF == FACE::R || RUF == FACE::L) && (RDB == FACE::R || RDB == FACE::L) && (RDF == FACE::R || RDF == FACE::L) && // UF, UB, DF, DB in the M slice. Note that the edges // are already oriented. (UF == FACE::F || UF == FACE::B) && (FU == FACE::U || FU == FACE::D) && (UB == FACE::F || UB == FACE::B) && (BU == FACE::U || BU == FACE::D) && (DF == FACE::F || DF == FACE::B) && (FD == FACE::U || FD == FACE::D) && (DB == FACE::F || DB == FACE::B) && (BD == FACE::U || BD == FACE::D); }
29.96875
77
0.521376
pabloqb2000
901f101e6158d262e259036cc96ba9a9dcb35690
2,026
cpp
C++
pnpoly.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
pnpoly.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
pnpoly.cpp
alexkaiser/heart_valves
53f30ec3680503542890a84949b7fb51d1734272
[ "BSD-3-Clause" ]
null
null
null
int pnpoly(int nvert, double *vertx, double *verty, double testx, double testy){ // Source: https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html // modified here for double precision // Copyright (c) 1970-2003, Wm. Randolph Franklin // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the // Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimers. // 2. Redistributions in binary form must reproduce the above copyright notice // in the documentation and/or other materials provided with the distribution. // 3. The name of W. Randolph Franklin may not be used to endorse or promote // products derived from this Software without specific prior written permission. // // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR // IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; }
48.238095
96
0.674235
alexkaiser
901feb3289d07ded85985c67c72e8adb8b78afa2
758
cpp
C++
Game/Game/PlayerMovingStopState.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
1
2021-02-17T13:06:38.000Z
2021-02-17T13:06:38.000Z
Game/Game/PlayerMovingStopState.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
26
2019-09-28T09:02:09.000Z
2019-12-27T07:24:22.000Z
Game/Game/PlayerMovingStopState.cpp
nguyenlamlll/directx-game
984942291a8dda1b6814dda9fc26215f067b9228
[ "MIT" ]
null
null
null
#include "stdafx.h" #include "PlayerMovingStopState.h" PlayerMovingStopState::PlayerMovingStopState(Player* player, Animation* animation) { m_player = player; m_animation = animation; } PlayerMovingStopState::~PlayerMovingStopState() { } void PlayerMovingStopState::Update(float deltaTime) { m_animation->setPositionX(m_player->getPosition().x); m_animation->setPositionY(m_player->getPosition().y); m_animation->Update(deltaTime); } void PlayerMovingStopState::Draw() { m_animation->Draw(); } PlayerStates PlayerMovingStopState::GetState() { return PlayerStates::MovingStop; } void PlayerMovingStopState::PreCollision(GameObject * entity, float deltaTime) { } void PlayerMovingStopState::OnCollision(GameObject* entity, float deltaTime) { }
18.95
82
0.783641
nguyenlamlll
9020cc40228d66a0aee9e49b4b2e3e331d86a334
5,596
cpp
C++
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
6
2022-02-26T09:21:40.000Z
2022-02-28T11:03:23.000Z
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
#include "LuaWrapper.hpp" namespace LuaSTGPlus::LuaWrapper { std::string_view const ParticleSystemWrapper::ClassID("lstg.ParticleSystemInstance"); ParticleSystemWrapper::UserData* ParticleSystemWrapper::Cast(lua_State* L, int idx) { return (UserData*)luaL_checkudata(L, idx, ClassID.data()); } ParticleSystemWrapper::UserData* ParticleSystemWrapper::Create(lua_State* L) { UserData* self = (UserData*)lua_newuserdata(L, sizeof(UserData)); // udata self->res = nullptr; self->ptr = nullptr; luaL_getmetatable(L, ClassID.data()); // udata mt lua_setmetatable(L, -2); // udata return self; } void ParticleSystemWrapper::Register(lua_State* L) { struct Wrapper { static int SetInactive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetInactive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetActive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetActive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetAliveCount(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { size_t const alive = self->ptr->GetAliveCount(); lua_pushinteger(L, (lua_Integer)alive); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = (float)luaL_checknumber(L, 2); self->ptr->SetEmission(emi); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = self->ptr->GetEmission(); lua_pushnumber(L, emi); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int Update(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const x = (float)luaL_checknumber(L, 2); float const y = (float)luaL_checknumber(L, 3); float const rot = (float)luaL_checknumber(L, 4); float const delta = (float)luaL_optnumber(L, 5, 1.0 / 60.0); self->ptr->SetRotation((float)rot); if (self->ptr->IsActived()) // 兼容性处理 { self->ptr->SetInactive(); self->ptr->SetCenter(fcyVec2(x, y)); self->ptr->SetActive(); } else { self->ptr->SetCenter(fcyVec2(x, y)); } self->ptr->Update(delta); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int Render(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const scale = (float)luaL_checknumber(L, 2); LAPP.Render(self->ptr, scale, scale); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int __tostring(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { lua_pushfstring(L, "lstg.ParticleSystemInstance(\"%s\")", self->res->GetResName().c_str()); } else { lua_pushstring(L, "lstg.ParticleSystemInstance"); } return 1; } static int __gc(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { if (self->ptr) { self->res->FreeInstance(self->ptr); } self->res->Release(); } self->res = nullptr; self->ptr = nullptr; return 0; } static int ParticleSystemInstance(lua_State* L) { char const* ps_name = luaL_checkstring(L, 1); auto p_res = LRES.FindParticle(ps_name); if (!p_res) return luaL_error(L, "particle system '%s' not found.", ps_name); try { auto* p_obj = p_res->AllocInstance(); auto* p_lud = Create(L); p_lud->res = *p_res; p_lud->res->AddRef(); p_lud->ptr = p_obj; } catch (const std::bad_alloc&) { return luaL_error(L, "create particle system instance of '%s' failed, memory allocation failed.", ps_name); } return 1; } }; luaL_Reg const lib[] = { { "SetInactive", &Wrapper::SetInactive }, { "SetActive", &Wrapper::SetActive }, { "GetAliveCount", &Wrapper::GetAliveCount }, { "SetEmission", &Wrapper::SetEmission }, { "GetEmission", &Wrapper::GetEmission }, { "Update", &Wrapper::Update }, { "Render", &Wrapper::Render }, { NULL, NULL } }; luaL_Reg const mt[] = { { "__tostring", &Wrapper::__tostring }, { "__gc", &Wrapper::__gc }, { NULL, NULL }, }; luaL_Reg const ins[] = { { "ParticleSystemInstance", Wrapper::ParticleSystemInstance }, { NULL, NULL } }; luaL_register(L, "lstg", ins); // ??? lstg RegisterClassIntoTable(L, ".ParticleSystemInstance", lib, ClassID.data(), mt); lua_pop(L, 1); } }
25.907407
113
0.580593
Legacy-LuaSTG-Engine
9022058d0badf93cb70ad6ae677ef30a406c68c4
2,560
cpp
C++
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
// CS32 lab06 // Completed by: Kevin Lu and Kevin Lai #include <iostream> #include <string> #include <fstream> #include <vector> #include <memory> #include "demogData.h" #include "psData.h" #include "parse.h" #include "dataAQ.h" using namespace std; int main() { /*//Deboog output ofstream myfile; myfile.open("output.txt");*/ dataAQ theAnswers; //read in a csv file and create a vector of objects representing each counties data std::vector<shared_ptr<regionData>> theDemogData = read_csv( "county_demographics.csv", DEMOG); std::vector<shared_ptr<regionData>> thePoliceData = read_csv( "police_shootings_cleaned.csv", POLICE); /*//Deboog print for (auto obj : theDemogData) { myfile << *dynamic_pointer_cast<demogData>(obj) << std::endl; } for (auto obj : thePoliceData) { myfile << *dynamic_pointer_cast<psData>(obj) << std::endl; } */ std::vector<shared_ptr<demogData>> castedDemogData; std::vector<shared_ptr<psData>> castedPoliceData; for (auto entry : theDemogData) { castedDemogData.push_back(static_pointer_cast<demogData>(entry)); } for (auto entry : thePoliceData) { castedPoliceData.push_back(static_pointer_cast<psData>(entry)); } theAnswers.createComboDemogData(castedDemogData); theAnswers.createComboPoliceData(castedPoliceData); //cout << theAnswers << endl; theAnswers.comboReport(92); //myfile.close(); /* cout << "*** the state that needs the most pre-schools**" << endl; string needPK = theAnswers.youngestPop(); cout << *(theAnswers.getStateData(needPK)) << endl; cout << "*** the state that needs the most high schools**" << endl; string needHS = theAnswers.teenPop(); cout << *(theAnswers.getStateData(needHS)) << endl; cout << "*** the state that needs the most vaccines**" << endl; string needV = theAnswers.wisePop(); cout << *(theAnswers.getStateData(needV)) << endl; cout << "*** the state that needs the most help with education**" << endl; string noHS = theAnswers.underServeHS(); cout << *(theAnswers.getStateData(noHS)) << endl; cout << "*** the state with most college grads**" << endl; string grads = theAnswers.collegeGrads(); cout << *(theAnswers.getStateData(grads)) << endl; cout << "*** the state with most population below the poverty line**" << endl; string belowPov = theAnswers.belowPoverty(); cout << *(theAnswers.getStateData(belowPov)) << endl; */ return 0; }
32.820513
87
0.657031
kevinyxlu
90228f4eb56d6f1a331f8cec173e6cf50f980f8a
1,264
cpp
C++
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// DFS binary_searching // https://open.kattis.com/problems/muddyhike #include <bits/stdc++.h> #define For(i, n) for (int i = 0; i < n; ++i) #define Forcase int __t = 0; cin >> __t; while (__t--) #define pb push_back #define ll long long #define ull unsigned long long #define ar array using namespace std; const int MOD = 1e9;//1e9 + 7; const ll INF = 1e18; int n, m; int tb[1010][1010]; bool vst[1010][1010]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; void dfs(int x, int y, int d) { vst[x][y] = 1; For (i, 4) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (tb[nx][ny] <= d && !vst[nx][ny]) { dfs(nx, ny, d); } } } bool ok(int d) { For (i, n) For (j, m) vst[i][j] = 0; For (i, n) if (tb[i][0] <= d) dfs(i, 0, d); For (i, n) if (vst[i][m - 1]) return 1; return 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; For (i, n) For (j, m) cin >> tb[i][j]; int l = 0, r = 1000000; while (l < r) { int mid = (l + r) / 2; if (ok(mid)) { r = mid; } else { l = mid + 1; } } cout << l << '\n'; return 0; }
21.423729
61
0.459652
YourName0729
9023b99e394de3e5e6a43839576352f0d51e0556
25,489
cc
C++
components/services/storage/service_worker/service_worker_resource_ops.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/services/storage/service_worker/service_worker_resource_ops.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/services/storage/service_worker/service_worker_resource_ops.cc
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/services/storage/service_worker/service_worker_resource_ops.h" #include "base/numerics/checked_math.h" #include "base/pickle.h" #include "components/services/storage/public/cpp/big_io_buffer.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/http/http_response_info.h" #include "services/network/public/cpp/net_adapters.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/blob/blob_utils.h" namespace storage { namespace { // Disk cache entry data indices. // // This enum pertains to data persisted on disk. Do not remove or reuse values. enum { kResponseInfoIndex = 0, kResponseContentIndex = 1, kResponseMetadataIndex = 2, }; // Convert an HttpResponseInfo retrieved from disk_cache to URLResponseHead. network::mojom::URLResponseHeadPtr ConvertHttpResponseInfo( const net::HttpResponseInfo& http_info, int64_t response_data_size) { auto response_head = network::mojom::URLResponseHead::New(); response_head->request_time = http_info.request_time; response_head->response_time = http_info.response_time; response_head->headers = http_info.headers; response_head->headers->GetMimeType(&response_head->mime_type); response_head->headers->GetCharset(&response_head->charset); response_head->content_length = response_data_size; response_head->was_fetched_via_spdy = http_info.was_fetched_via_spdy; response_head->was_alpn_negotiated = http_info.was_alpn_negotiated; response_head->connection_info = http_info.connection_info; response_head->alpn_negotiated_protocol = http_info.alpn_negotiated_protocol; response_head->remote_endpoint = http_info.remote_endpoint; response_head->cert_status = http_info.ssl_info.cert_status; // See ConvertToPickle(), where an invalid ssl_info is put into storage in // case of |response_head->ssl_info| being nullptr. Here we restore // |response_head->ssl_info| to nullptr if we got the invalid ssl_info from // storage. if (http_info.ssl_info.is_valid()) response_head->ssl_info = http_info.ssl_info; return response_head; } // Convert a URLResponseHead to base::Pickle. Used to persist the response to // disk. std::unique_ptr<base::Pickle> ConvertToPickle( network::mojom::URLResponseHeadPtr response_head) { net::HttpResponseInfo response_info; response_info.headers = response_head->headers; if (response_head->ssl_info.has_value()) { response_info.ssl_info = *response_head->ssl_info; DCHECK(response_info.ssl_info.is_valid()); } response_info.was_fetched_via_spdy = response_head->was_fetched_via_spdy; response_info.was_alpn_negotiated = response_head->was_alpn_negotiated; response_info.alpn_negotiated_protocol = response_head->alpn_negotiated_protocol; response_info.connection_info = response_head->connection_info; response_info.remote_endpoint = response_head->remote_endpoint; response_info.response_time = response_head->response_time; const bool kSkipTransientHeaders = true; const bool kTruncated = false; auto pickle = std::make_unique<base::Pickle>(); response_info.Persist(pickle.get(), kSkipTransientHeaders, kTruncated); return pickle; } // An IOBuffer that wraps a pickle's data. Used to write URLResponseHead. class WrappedPickleIOBuffer : public net::WrappedIOBuffer { public: explicit WrappedPickleIOBuffer(std::unique_ptr<const base::Pickle> pickle) : net::WrappedIOBuffer(reinterpret_cast<const char*>(pickle->data())), pickle_(std::move(pickle)) { DCHECK(pickle_->data()); } size_t size() const { return pickle_->size(); } private: ~WrappedPickleIOBuffer() override = default; const std::unique_ptr<const base::Pickle> pickle_; }; } // namespace DiskEntryCreator::DiskEntryCreator( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache) : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); DCHECK(disk_cache_); } DiskEntryCreator::~DiskEntryCreator() = default; void DiskEntryCreator::EnsureEntryIsCreated(base::OnceClosure callback) { DCHECK(creation_phase_ == CreationPhase::kNoAttempt || creation_phase_ == CreationPhase::kDone); DCHECK(!ensure_entry_is_created_callback_); ensure_entry_is_created_callback_ = std::move(callback); if (entry_) { RunEnsureEntryIsCreatedCallback(); return; } if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } creation_phase_ = CreationPhase::kInitialAttempt; disk_cache_->CreateEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidCreateEntryForFirstAttempt, weak_factory_.GetWeakPtr())); } void DiskEntryCreator::DidCreateEntryForFirstAttempt( int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { DCHECK_EQ(creation_phase_, CreationPhase::kInitialAttempt); DCHECK(!entry_); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } if (rv != net::OK) { // The first attempt to create an entry is failed. Try to overwrite the // existing entry. creation_phase_ = CreationPhase::kDoomExisting; disk_cache_->DoomEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidDoomExistingEntry, weak_factory_.GetWeakPtr())); return; } DCHECK(entry); entry_ = std::move(entry); RunEnsureEntryIsCreatedCallback(); } void DiskEntryCreator::DidDoomExistingEntry(int rv) { DCHECK_EQ(creation_phase_, CreationPhase::kDoomExisting); DCHECK(!entry_); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } creation_phase_ = CreationPhase::kSecondAttempt; disk_cache_->CreateEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidCreateEntryForSecondAttempt, weak_factory_.GetWeakPtr())); } void DiskEntryCreator::DidCreateEntryForSecondAttempt( int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { DCHECK_EQ(creation_phase_, CreationPhase::kSecondAttempt); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } if (rv != net::OK) { // The second attempt is also failed. Give up creating an entry. entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } DCHECK(!entry_); DCHECK(entry); entry_ = std::move(entry); RunEnsureEntryIsCreatedCallback(); } void DiskEntryCreator::RunEnsureEntryIsCreatedCallback() { creation_phase_ = CreationPhase::kDone; std::move(ensure_entry_is_created_callback_).Run(); } DiskEntryOpener::DiskEntryOpener( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache) : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); DCHECK(disk_cache_); } DiskEntryOpener::~DiskEntryOpener() = default; void DiskEntryOpener::EnsureEntryIsOpen(base::OnceClosure callback) { if (entry_) { std::move(callback).Run(); return; } if (!disk_cache_) { std::move(callback).Run(); return; } disk_cache_->OpenEntry( resource_id_, base::BindOnce(&DiskEntryOpener::DidOpenEntry, weak_factory_.GetWeakPtr(), std::move(callback))); } void DiskEntryOpener::DidOpenEntry( base::OnceClosure callback, int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { if (!entry_ && rv == net::OK) { DCHECK(entry); entry_ = std::move(entry); } std::move(callback).Run(); } class ServiceWorkerResourceReaderImpl::DataReader { public: DataReader( base::WeakPtr<ServiceWorkerResourceReaderImpl> owner, size_t total_bytes_to_read, mojo::PendingRemote<mojom::ServiceWorkerDataPipeStateNotifier> notifier, mojo::ScopedDataPipeProducerHandle producer_handle) : owner_(std::move(owner)), total_bytes_to_read_(total_bytes_to_read), notifier_(std::move(notifier)), producer_handle_(std::move(producer_handle)), watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()) { DCHECK(owner_); DCHECK(notifier_); } ~DataReader() = default; DataReader(const DataReader&) = delete; DataReader operator=(const DataReader&) = delete; void Start() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kInitialized); state_ = State::kStarted; #endif owner_->entry_opener_.EnsureEntryIsOpen(base::BindOnce( &DataReader::ContinueReadData, weak_factory_.GetWeakPtr())); } private: void ContinueReadData() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kStarted); state_ = State::kCacheEntryOpened; #endif if (!owner_) { Complete(net::ERR_ABORTED); return; } if (!owner_->entry_opener_.entry()) { Complete(net::ERR_CACHE_MISS); return; } watcher_.Watch(producer_handle_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, base::BindRepeating(&DataReader::OnWritable, weak_factory_.GetWeakPtr())); watcher_.ArmOrNotify(); } void OnWritable(MojoResult) { #if DCHECK_IS_ON() DCHECK(state_ == State::kCacheEntryOpened || state_ == State::kDataRead); state_ = State::kProducerWritable; #endif DCHECK(producer_handle_.is_valid()); DCHECK(!pending_buffer_); if (!owner_ || !owner_->entry_opener_.entry()) { Complete(net::ERR_ABORTED); return; } uint32_t num_bytes = 0; MojoResult rv = network::NetToMojoPendingBuffer::BeginWrite( &producer_handle_, &pending_buffer_, &num_bytes); switch (rv) { case MOJO_RESULT_INVALID_ARGUMENT: case MOJO_RESULT_BUSY: NOTREACHED(); return; case MOJO_RESULT_FAILED_PRECONDITION: Complete(net::ERR_ABORTED); return; case MOJO_RESULT_SHOULD_WAIT: watcher_.ArmOrNotify(); return; case MOJO_RESULT_OK: // |producer__handle_| must have been taken by |pending_buffer_|. DCHECK(pending_buffer_); DCHECK(!producer_handle_.is_valid()); break; } num_bytes = std::min(num_bytes, blink::BlobUtils::GetDataPipeChunkSize()); scoped_refptr<network::NetToMojoIOBuffer> buffer = base::MakeRefCounted<network::NetToMojoIOBuffer>(pending_buffer_.get()); net::IOBuffer* raw_buffer = buffer.get(); int read_bytes = owner_->entry_opener_.entry()->Read( kResponseContentIndex, current_bytes_read_, raw_buffer, num_bytes, base::BindOnce(&DataReader::DidReadData, weak_factory_.GetWeakPtr(), buffer)); if (read_bytes != net::ERR_IO_PENDING) { DidReadData(std::move(buffer), read_bytes); } } void DidReadData(scoped_refptr<network::NetToMojoIOBuffer> buffer, int read_bytes) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kProducerWritable); state_ = State::kDataRead; #endif if (read_bytes < 0) { Complete(read_bytes); return; } producer_handle_ = pending_buffer_->Complete(read_bytes); DCHECK(producer_handle_.is_valid()); pending_buffer_.reset(); current_bytes_read_ += read_bytes; if (read_bytes == 0 || current_bytes_read_ == total_bytes_to_read_) { // All data has been read. Complete(current_bytes_read_); return; } watcher_.ArmOrNotify(); } void Complete(int status) { #if DCHECK_IS_ON() DCHECK_NE(state_, State::kComplete); state_ = State::kComplete; #endif watcher_.Cancel(); producer_handle_.reset(); if (notifier_.is_connected()) { notifier_->OnComplete(status); } if (owner_) { owner_->DidReadDataComplete(); } } base::WeakPtr<ServiceWorkerResourceReaderImpl> owner_; const size_t total_bytes_to_read_; size_t current_bytes_read_ = 0; mojo::Remote<mojom::ServiceWorkerDataPipeStateNotifier> notifier_; mojo::ScopedDataPipeProducerHandle producer_handle_; mojo::SimpleWatcher watcher_; scoped_refptr<network::NetToMojoPendingBuffer> pending_buffer_; #if DCHECK_IS_ON() enum class State { kInitialized, kStarted, kCacheEntryOpened, kProducerWritable, kDataRead, kComplete, }; State state_ = State::kInitialized; #endif // DCHECK_IS_ON() base::WeakPtrFactory<DataReader> weak_factory_{this}; }; ServiceWorkerResourceReaderImpl::ServiceWorkerResourceReaderImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceReader> receiver, base::OnceClosure disconnect_handler) : entry_opener_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceReaderImpl::~ServiceWorkerResourceReaderImpl() = default; void ServiceWorkerResourceReaderImpl::ReadResponseHead( ReadResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kReadResponseHeadStarted; #endif DCHECK(!read_response_head_callback_) << __func__ << " already called"; DCHECK(!response_head_) << " another ReadResponseHead() in progress"; DCHECK(!metadata_buffer_); DCHECK(!data_reader_); read_response_head_callback_ = std::move(callback); entry_opener_.EnsureEntryIsOpen( base::BindOnce(&ServiceWorkerResourceReaderImpl::ContinueReadResponseHead, weak_factory_.GetWeakPtr())); } void ServiceWorkerResourceReaderImpl::ReadData( int64_t size, mojo::PendingRemote<mojom::ServiceWorkerDataPipeStateNotifier> notifier, ReadDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kReadDataStarted; #endif DCHECK(!read_response_head_callback_) << "ReadResponseHead() being operating"; DCHECK(!response_head_); DCHECK(!metadata_buffer_); DCHECK(!data_reader_); MojoCreateDataPipeOptions options; options.struct_size = sizeof(MojoCreateDataPipeOptions); options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; options.element_num_bytes = 1; options.capacity_num_bytes = blink::BlobUtils::GetDataPipeCapacity(size); mojo::ScopedDataPipeConsumerHandle consumer_handle; mojo::ScopedDataPipeProducerHandle producer_handle; MojoResult rv = mojo::CreateDataPipe(&options, producer_handle, consumer_handle); if (rv != MOJO_RESULT_OK) { std::move(callback).Run(mojo::ScopedDataPipeConsumerHandle()); return; } data_reader_ = std::make_unique<DataReader>(weak_factory_.GetWeakPtr(), size, std::move(notifier), std::move(producer_handle)); data_reader_->Start(); std::move(callback).Run(std::move(consumer_handle)); } void ServiceWorkerResourceReaderImpl::ContinueReadResponseHead() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kReadResponseHeadStarted); state_ = State::kCacheEntryOpened; #endif DCHECK(read_response_head_callback_); if (!entry_opener_.entry()) { FailReadResponseHead(net::ERR_CACHE_MISS); return; } int64_t size = entry_opener_.entry()->GetSize(kResponseInfoIndex); if (size <= 0) { FailReadResponseHead(net::ERR_CACHE_MISS); return; } auto buffer = base::MakeRefCounted<net::IOBuffer>(base::checked_cast<size_t>(size)); int rv = entry_opener_.entry()->Read( kResponseInfoIndex, /*offset=*/0, buffer.get(), size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadHttpResponseInfo, weak_factory_.GetWeakPtr(), buffer)); if (rv != net::ERR_IO_PENDING) { DidReadHttpResponseInfo(std::move(buffer), rv); } } void ServiceWorkerResourceReaderImpl::DidReadHttpResponseInfo( scoped_refptr<net::IOBuffer> buffer, int status) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kCacheEntryOpened); state_ = State::kResponseInfoRead; #endif DCHECK(read_response_head_callback_); DCHECK(entry_opener_.entry()); if (status < 0) { FailReadResponseHead(status); return; } // Deserialize the http info structure, ensuring we got headers. base::Pickle pickle(buffer->data(), status); auto http_info = std::make_unique<net::HttpResponseInfo>(); bool response_truncated = false; if (!http_info->InitFromPickle(pickle, &response_truncated) || !http_info->headers.get()) { FailReadResponseHead(net::ERR_FAILED); return; } DCHECK(!response_truncated); int64_t response_data_size = entry_opener_.entry()->GetSize(kResponseContentIndex); response_head_ = ConvertHttpResponseInfo(*http_info, response_data_size); int64_t metadata_size = entry_opener_.entry()->GetSize(kResponseMetadataIndex); DCHECK_GE(metadata_size, 0); if (metadata_size <= 0) { CompleteReadResponseHead(status); return; } // Read metadata. metadata_buffer_ = base::MakeRefCounted<BigIOBuffer>( mojo_base::BigBuffer(base::checked_cast<size_t>(metadata_size))); int rv = entry_opener_.entry()->Read( kResponseMetadataIndex, /*offset=*/0, metadata_buffer_.get(), metadata_size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadMetadata, weak_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) { DidReadMetadata(rv); } } void ServiceWorkerResourceReaderImpl::DidReadMetadata(int status) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kResponseInfoRead); state_ = State::kMetadataRead; #endif DCHECK(read_response_head_callback_); DCHECK(metadata_buffer_); if (status < 0) { FailReadResponseHead(status); return; } CompleteReadResponseHead(status); } void ServiceWorkerResourceReaderImpl::FailReadResponseHead(int status) { DCHECK_NE(net::OK, status); response_head_ = nullptr; metadata_buffer_ = nullptr; CompleteReadResponseHead(status); } void ServiceWorkerResourceReaderImpl::CompleteReadResponseHead(int status) { #if DCHECK_IS_ON() DCHECK_NE(state_, State::kIdle); state_ = State::kIdle; #endif DCHECK(read_response_head_callback_); absl::optional<mojo_base::BigBuffer> metadata = metadata_buffer_ ? absl::optional<mojo_base::BigBuffer>(metadata_buffer_->TakeBuffer()) : absl::nullopt; metadata_buffer_ = nullptr; std::move(read_response_head_callback_) .Run(status, std::move(response_head_), std::move(metadata)); } void ServiceWorkerResourceReaderImpl::DidReadDataComplete() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kReadDataStarted); state_ = State::kIdle; #endif DCHECK(data_reader_); data_reader_.reset(); } ServiceWorkerResourceWriterImpl::ServiceWorkerResourceWriterImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceWriter> receiver, base::OnceClosure disconnect_handler) : entry_creator_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceWriterImpl::~ServiceWorkerResourceWriterImpl() = default; void ServiceWorkerResourceWriterImpl::WriteResponseHead( network::mojom::URLResponseHeadPtr response_head, WriteResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteResponseHeadStarted; #endif entry_creator_.EnsureEntryIsCreated( base::BindOnce(&ServiceWorkerResourceWriterImpl::WriteResponseHeadToEntry, weak_factory_.GetWeakPtr(), std::move(response_head), std::move(callback))); } void ServiceWorkerResourceWriterImpl::WriteData(mojo_base::BigBuffer data, WriteDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteDataStarted; #endif entry_creator_.EnsureEntryIsCreated(base::BindOnce( &ServiceWorkerResourceWriterImpl::WriteDataToEntry, weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); } void ServiceWorkerResourceWriterImpl::WriteResponseHeadToEntry( network::mojom::URLResponseHeadPtr response_head, WriteResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteResponseHeadStarted); state_ = State::kWriteResponseHeadHasEntry; #endif if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_callback_); write_callback_ = std::move(callback); std::unique_ptr<const base::Pickle> pickle = ConvertToPickle(std::move(response_head)); auto buffer = base::MakeRefCounted<WrappedPickleIOBuffer>(std::move(pickle)); size_t write_amount = buffer->size(); int rv = entry_creator_.entry()->Write( kResponseInfoIndex, /*offset=*/0, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteResponseHead, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteResponseHead(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceWriterImpl::DidWriteResponseHead( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteResponseHeadHasEntry); state_ = State::kIdle; #endif DCHECK(write_callback_); DCHECK(rv < 0 || base::checked_cast<size_t>(rv) == write_amount); std::move(write_callback_).Run(rv); } void ServiceWorkerResourceWriterImpl::WriteDataToEntry( mojo_base::BigBuffer data, WriteDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteDataStarted); state_ = State::kWriteDataHasEntry; #endif if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_callback_); write_callback_ = std::move(callback); size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); int rv = entry_creator_.entry()->Write( kResponseContentIndex, write_position_, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteData, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteData(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceWriterImpl::DidWriteData( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteDataHasEntry); state_ = State::kIdle; #endif DCHECK(write_callback_); if (rv >= 0) { DCHECK(base::checked_cast<size_t>(rv) == write_amount); write_position_ += write_amount; } std::move(write_callback_).Run(rv); } ServiceWorkerResourceMetadataWriterImpl:: ServiceWorkerResourceMetadataWriterImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceMetadataWriter> receiver, base::OnceClosure disconnect_handler) : entry_opener_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceMetadataWriterImpl:: ~ServiceWorkerResourceMetadataWriterImpl() = default; void ServiceWorkerResourceMetadataWriterImpl::WriteMetadata( mojo_base::BigBuffer data, WriteMetadataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteMetadataStarted; #endif entry_opener_.EnsureEntryIsOpen(base::BindOnce( &ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata, weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); } void ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata( mojo_base::BigBuffer data, WriteMetadataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteMetadataStarted); state_ = State::kWriteMetadataHasEntry; #endif if (!entry_opener_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_metadata_callback_); write_metadata_callback_ = std::move(callback); size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); int rv = entry_opener_.entry()->Write( kResponseMetadataIndex, /*offset=*/0, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteMetadata(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteMetadataHasEntry); state_ = State::kIdle; #endif DCHECK(rv < 0 || base::checked_cast<size_t>(rv) == write_amount); DCHECK(write_metadata_callback_); std::move(write_metadata_callback_).Run(rv); } } // namespace storage
31.901126
83
0.725725
zealoussnow
902490ec381baf78b59811adc1193eeaf38ca22a
4,940
cpp
C++
src/core/NEON/kernels/NEDepthConcatenateKernel.cpp
Acidburn0zzz/ComputeLibrary
f4a254c2745aeaab6f7276a675147d707002fe7a
[ "MIT" ]
1
2017-09-07T09:13:53.000Z
2017-09-07T09:13:53.000Z
src/core/NEON/kernels/NEDepthConcatenateKernel.cpp
jialiang19/test_armComputeLibrary
5dbb9970a01289f292429f8083e83921a3ccd9e4
[ "MIT" ]
null
null
null
src/core/NEON/kernels/NEDepthConcatenateKernel.cpp
jialiang19/test_armComputeLibrary
5dbb9970a01289f292429f8083e83921a3ccd9e4
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 ARM Limited. * * SPDX-License-Identifier: MIT * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "arm_compute/core/NEON/kernels/NEDepthConcatenateKernel.h" #include "arm_compute/core/Error.h" #include "arm_compute/core/Helpers.h" #include "arm_compute/core/IAccessWindow.h" #include "arm_compute/core/ITensor.h" #include "arm_compute/core/TensorInfo.h" #include "arm_compute/core/Utils.h" #include "arm_compute/core/Validate.h" #include "arm_compute/core/Window.h" #include <arm_neon.h> using namespace arm_compute; NEDepthConcatenateKernel::NEDepthConcatenateKernel() : _input(nullptr), _output(nullptr), _top_bottom(0), _left_right(0), _depth_offset(0) { } BorderSize NEDepthConcatenateKernel::border_size() const { return BorderSize(_top_bottom, _left_right); } void NEDepthConcatenateKernel::configure(const ITensor *input, unsigned int depth_offset, ITensor *output) { ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::F32); ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(output, 1, DataType::F32); ARM_COMPUTE_ERROR_ON(input->info()->dimension(2) + depth_offset > output->info()->dimension(2)); ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) > output->info()->dimension(0)); ARM_COMPUTE_ERROR_ON(input->info()->dimension(1) > output->info()->dimension(1)); ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(3, input, output); // The gaps between the two lowest dimensions of input and output need to be divisible by 2 // Otherwise it is not clear how the padding should be added onto the input tensor ARM_COMPUTE_ERROR_ON((output->info()->dimension(0) - input->info()->dimension(0)) % 2); ARM_COMPUTE_ERROR_ON((output->info()->dimension(1) - input->info()->dimension(1)) % 2); _input = input; _output = output; _depth_offset = depth_offset; _left_right = (output->info()->dimension(0) - input->info()->dimension(0)) / 2; _top_bottom = (output->info()->dimension(1) - input->info()->dimension(1)) / 2; const unsigned int num_elems_processed_per_iteration = 4; const unsigned int num_elems_read_per_iteration = 4; const unsigned int num_rows_read_per_iteration = 1; // The window needs to be based on input as we copy all the depths of input Window win = calculate_max_enlarged_window(*input->info(), Steps(num_elems_processed_per_iteration), border_size()); AccessWindowRectangle input_access(input->info(), -_left_right, -_top_bottom, num_elems_read_per_iteration, num_rows_read_per_iteration); AccessWindowHorizontal output_access(output->info(), 0, num_elems_processed_per_iteration); update_window_and_padding(win, input_access, output_access); output_access.set_valid_region(win, ValidRegion(Coordinates(0, 0), output->info()->tensor_shape())); INEKernel::configure(win); } void NEDepthConcatenateKernel::run(const Window &window) { ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window); // Offset output const unsigned int offset_to_first_elements_in_bytes = _output->info()->offset_first_element_in_bytes() + _left_right * _output->info()->strides_in_bytes()[0] + _top_bottom * _output->info()->strides_in_bytes()[1] + _depth_offset * _output->info()->strides_in_bytes()[2]; uint8_t *output_ptr = _output->buffer() + offset_to_first_elements_in_bytes; Iterator input(_input, window); Iterator output(_output, window); execute_window_loop(window, [&](const Coordinates & id) { const auto in_ptr = reinterpret_cast<const float *>(input.ptr()); const auto out_ptr = reinterpret_cast<float *>(output_ptr + output.offset()); vst1q_f32(out_ptr, vld1q_f32(in_ptr)); }, input, output); }
46.603774
178
0.729352
Acidburn0zzz
902543871d7490ae6a429f7702bfe3d0595a67e9
6,780
hpp
C++
include/AndroidHalStreamOut.hpp
hidenorly/AndroidAudioHalHelper
f3ea1c4833382bea76aea3d145d0f0bef9faa02e
[ "Apache-2.0" ]
null
null
null
include/AndroidHalStreamOut.hpp
hidenorly/AndroidAudioHalHelper
f3ea1c4833382bea76aea3d145d0f0bef9faa02e
[ "Apache-2.0" ]
null
null
null
include/AndroidHalStreamOut.hpp
hidenorly/AndroidAudioHalHelper
f3ea1c4833382bea76aea3d145d0f0bef9faa02e
[ "Apache-2.0" ]
null
null
null
/* Copyright (C) 2021 hidenorly 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 __ANDROID_HAL_STREAM_OUT_HPP__ #define __ANDROID_HAL_STREAM_OUT_HPP__ #include "AndroidHalStream.hpp" #include <fmq/MessageQueue.h> #include <vector> #include <system/audio.h> #include <stdint.h> #include "Strategy.hpp" #include "Pipe.hpp" #include "Source.hpp" #include "Sink.hpp" #include "PlaybackRateFilter.hpp" #include "DualMonoFilter.hpp" #include <fmq/EventFlag.h> #include "deleters.hpp" class IStreamOut : public IStream { public: class IStreamOutCallback { public: virtual void onWriteReady(void); virtual void onDrainReady(void); virtual void onError(void); }; class IStreamOutEventCallback { public: virtual void onCodecFormatChanged(std::vector<uint8_t> audioMetadata); }; enum WriteCommand { WRITE, GET_PRESENTATION_POSITION, GET_LATENCY }; struct WriteStatus { HalResult retval; WriteCommand replyTo; union Reply { uint64_t written; PresentationPosition presentationPosition; uint32_t latencyMs; } reply; WriteStatus():retval(HalResult::OK), replyTo(WriteCommand::WRITE), reply{0}{}; }; typedef android::hardware::MessageQueue<IStreamOut::WriteCommand, android::hardware::kSynchronizedReadWrite> CommandMQ; typedef android::hardware::MessageQueue<IStreamOut::WriteStatus, android::hardware::kSynchronizedReadWrite> StatusMQ; typedef android::hardware::MessageQueue<uint8_t, android::hardware::kSynchronizedReadWrite> DataMQ; class WritePipeInfo { public: std::shared_ptr<CommandMQ> commandMQ; std::shared_ptr<DataMQ> dataMQ; std::shared_ptr<StatusMQ> statusMQ; //ThreadInfo threadInfo; WritePipeInfo( std::shared_ptr<CommandMQ> commandMQ = std::make_shared<CommandMQ>(1), std::shared_ptr<DataMQ> dataMQ = std::make_shared<DataMQ>(1), std::shared_ptr<StatusMQ> statusMQ = std::make_shared<StatusMQ>(4096, true)) : commandMQ(commandMQ), dataMQ(dataMQ), statusMQ(statusMQ){}; virtual ~WritePipeInfo(){}; }; class AndroidAudioSource : public ISource { protected: std::shared_ptr<DataMQ> mDataMQ; std::shared_ptr<StatusMQ> mStatusMQ; std::unique_ptr<::android::hardware::EventFlag, deleters::forEventFlag> mEfGroup; long mLastWritePts; public: AndroidAudioSource(std::shared_ptr<DataMQ> dataMQ = nullptr, std::shared_ptr<StatusMQ> statusMQ = nullptr) : mDataMQ(dataMQ), mStatusMQ(statusMQ), mLastWritePts(0){ android::hardware::EventFlag* rawEfGroup = nullptr; android::hardware::EventFlag::createEventFlag( mDataMQ->getEventFlagWord(), &rawEfGroup ); mEfGroup.reset( rawEfGroup ); }; virtual ~AndroidAudioSource(){ mDataMQ.reset(); mStatusMQ.reset(); }; virtual bool isAvailableFormat(AudioFormat format){ return true; }; virtual void notifyDoRead(void); virtual void notifyNextCommand(void); virtual void resetWritePts(void){ mLastWritePts = 0; }; long getWritePresentationTimeUsec(void){ return mLastWritePts; }; protected: virtual void readPrimitive(IAudioBuffer& buf); virtual long getDeltaPtsUsecByBytes(int64_t bytes); }; protected: std::weak_ptr<IStreamOutCallback> mCallback; std::weak_ptr<IStreamOutEventCallback> mEventCallback; std::shared_ptr<WritePipeInfo> mWritePipeInfo; std::shared_ptr<AndroidAudioSource> mSource; std::shared_ptr<ISink> mSink; AudioOutputFlags mOutputFlags; SourceMetadata mSourceMetadata; float mAudioDescMixLevlDb; PlaybackRate mPlaybackRate; std::shared_ptr<PlaybackRateFilter> mPlaybackRateFilter; DualMonoMode mDualMonoMode; std::shared_ptr<DualMonoFilter> mDualMonoFilter; int32_t mPresentationId; int32_t mProgramId; long mLastPts; long mLastWritePtsBase; protected: virtual void process(void); public: IStreamOut(AudioIoHandle ioHandle = 0, DeviceAddress device=DeviceAddress(), AudioConfig config={0}, AudioOutputFlags flags=AUDIO_OUTPUT_FLAG_NONE, SourceMetadata sourceMetadata=SourceMetadata(), std::shared_ptr<StreamSessionHandler> pSessionHandler = nullptr, std::shared_ptr<ISink> pSink = nullptr); virtual ~IStreamOut(){}; virtual std::shared_ptr<WritePipeInfo> prepareForWriting(uint32_t frameSize, uint32_t framesCount); // capability check virtual bool supportsPause(void); virtual bool supportsResume(void); virtual bool supportsDrain(void); // operation virtual HalResult pause(void); virtual HalResult resume(void); virtual HalResult drain(AudioDrain type); virtual HalResult flush(void); // callback virtual HalResult setCallback(std::weak_ptr<IStreamOutCallback> callback); virtual HalResult clearCallback(void); virtual HalResult setEventCallback(std::weak_ptr<IStreamOutEventCallback> callback); // get status virtual int64_t getNextWriteTimestampUsec(); virtual uint32_t getLatencyMsec(void); virtual uint32_t getRenderPositionDspFrames(void); virtual PresentationPosition getPresentationPosition(void); virtual HalResult setVolume(float left, float right); virtual PlaybackRate getPlaybackRateParameters(void); virtual HalResult setPlaybackRateParameters(PlaybackRate playbackRate); virtual DualMonoMode getDualMonoMode(void); virtual HalResult setDualMonoMode(DualMonoMode mode); virtual HalResult selectPresentation(int32_t presentationId, int32_t programId); virtual float getAudioDescriptionMixLevelDb(void); virtual HalResult setAudioDescriptionMixLevel(float leveldB); virtual void updateSourceMetadata(SourceMetadata sourceMetadata); virtual std::vector<DeviceAddress> getDevices(void); virtual HalResult setDevices(std::vector<DeviceAddress> devices); virtual HalResult streamClose(void); }; class StreamOutContext : public StrategyContext { public: AudioIoHandle ioHandle; DeviceAddress device; AudioConfig config; AudioOutputFlags flags; SourceMetadata sourceMetadata; public: StreamOutContext(AudioIoHandle ioHandle, DeviceAddress device, AudioConfig config, AudioOutputFlags flags, SourceMetadata sourceMetadata):ioHandle(ioHandle), device(device), config(config), flags(flags), sourceMetadata(sourceMetadata){}; virtual ~StreamOutContext(){}; }; #endif /* __ANDROID_HAL_STREAM_OUT_HPP__ */
32.596154
303
0.765339
hidenorly
9025dc4a8b2d99bb948acee1c9ea6a716cb0fb77
552
cpp
C++
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <mtt/editorLib/EditorApplication.h> #include <MainWindow.h> int main(int argc, char* argv[]) { VkPhysicalDeviceFeatures features{}; features.samplerAnisotropy = VK_TRUE; features.geometryShader = VK_TRUE; mtt::EditorApplication application( argc, argv, "Mtt particles editor", { 0, 0, 0 }, features); MainWindow mainWindow; mainWindow.show(); return application.exec(); }
25.090909
61
0.530797
AluminiumRat
902694d213826185749d052ae9ae56617ae2ad58
16,817
cc
C++
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __PHYSX_COMMIT__ #include "PxRigidDynamic.h" #include "PhysicsDynamic.h" #include "PhysicsServer.h" #include "PhysicsShape.h" #include "PxScene.h" #include "PxShape.h" #include "PxFlags.h" #include "PxRigidBodyExt.h" #include "PxRigidDynamic.h" #include "PhysicsUtil.h" #include "physXfeature/PhysicsBodyComponent.h" namespace App { __ImplementClass(PhysicsDynamic, 'PYDY', PhysicsEntity); PhysicsDynamic::PhysicsDynamic() : m_pPxActor(NULL) , m_bJointFather(false) , m_bUseGravity(true) , m_bKinematic(false) , m_fLinearDamping(0.0f) , m_fAngularDamping(0.05f) , m_vContantForce(0.f) , m_vContantVelocity(0.f) , m_vContantTorques(0.f) , m_vContantAngularVel(0.f) { m_eType = PHYSICSDYNAMIC; m_fMaxAngularVel = PhysicsServer::Instance()->GetMaxAngularVelocity(); m_fSleepThreshold = PhysicsServer::Instance()->GetSleepThreshold(); } PhysicsDynamic::~PhysicsDynamic() { OnDestory(); } PxRigidActor* PhysicsDynamic::GetRigidActor() { return m_pPxActor; } bool PhysicsDynamic::OnCreate(GPtr<PhysicsBodyComponent> body) { if ( !m_bJointFather && body.isvalid() && body->GetActor() ) { OnDestory(); PxPhysics* pSDK = PhysicsServer::Instance()->GetPhysics(); n_assert(pSDK); Math::vector pos = body->GetActor()->GetWorldPosition(); Math::quaternion rot = body->GetActor()->GetWorldRotation(); PxTransform _ActorPose(PxVec3(pos.x(), pos.y(), pos.z()), PxQuat(rot.x(), rot.y(), rot.z(), rot.w())); m_pPxActor = pSDK->createRigidDynamic(_ActorPose); n_assert(m_pPxActor) m_pPxActor->userData = body.get(); m_pPxActor->setActorFlag(PxActorFlag::eVISUALIZATION, true); if ( m_bKinematic ) { m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, m_bKinematic); } else { m_pPxActor->setAngularDamping (m_fAngularDamping); m_pPxActor->setLinearDamping(m_fLinearDamping ); m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false); m_pPxActor->setMaxAngularVelocity(PhysicsServer::Instance()->GetMaxAngularVelocity()); m_pPxActor->setSleepThreshold(PhysicsServer::Instance()->GetSleepThreshold()); m_pPxActor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_bUseGravity); } for ( int i=0; i<m_arrPhysicsShapePtr.Size(); ++i ) { if (!m_arrPhysicsShapePtr[i]->IsValid()) { m_arrPhysicsShapePtr[i]->OnCreate(body); } m_arrPhysicsShapePtr[i]->SetPhysicsEntity(this); m_arrPhysicsShapePtr[i]->CreatePxShape(m_pPxActor, GetGroupID()); } UpdateEntityMass(); // Not using // CaptureShapeFromChildren(); return true; } return m_bJointFather; } void PhysicsDynamic::CaptureShapeFromChildren() { if ( m_pPxActor == NULL ) { return; } for ( int i=0; i<m_pComponent->GetActor()->GetChildCount(); ++i ) { GPtr<PhysicsEntity> _pChildEntity = GetEntityInActor(m_pComponent->GetActor()->GetChild(i)); if ( _pChildEntity.isvalid() && _pChildEntity->GetType()&m_eType ) { GPtr<PhysicsDynamic> _pDynamic = _pChildEntity.downcast<PhysicsDynamic>(); if ( !_pDynamic->IsJointFather() ) { continue; } for ( int i=0; i<_pChildEntity->GetShapeCount(); ++i ) { _pChildEntity->GetShape(i)->CreatePxShape(m_pPxActor, GetGroupID()); } } } } bool PhysicsDynamic::OnDestory() { if ( IsValid() ) { Super::OnDestory(); //ReleaseChildShape(); m_pPxActor->release(); m_pPxActor = NULL; } return true; } void PhysicsDynamic::OnShapeReBuild(PhysicsShape* shape) { if ( GetRigidActor() && shape != NULL) { shape->CreatePxShape(GetRigidActor(),m_eGroup); UpdateEntityMass(); } } void PhysicsDynamic::ReleaseChildShape() { if ( m_pPxActor == NULL || m_pComponent == NULL || !m_pComponent->GetActor() ) { return; } for ( int i=0; i<m_pComponent->GetActor()->GetChildCount(); ++i ) { GPtr<PhysicsEntity> _pChildEntity = GetEntityInActor(m_pComponent->GetActor()->GetChild(i)); if ( _pChildEntity.isvalid() && _pChildEntity->GetType()&m_eType ) { GPtr<PhysicsDynamic> _pDynamic = _pChildEntity.downcast<PhysicsDynamic>(); if ( !_pDynamic->IsJointFather() ) { continue; } for ( int i=0; i<_pChildEntity->GetShapeCount(); ++i ) { _pChildEntity->GetShape(i)->ReleasePxShape(); } } } } void PhysicsDynamic::SetKinematic( bool kinematic ) { m_bKinematic = kinematic; if ( m_pPxActor ) { m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, m_bKinematic); } } void PhysicsDynamic::SetJointFather( bool joint ) { if ( m_bJointFather == joint ) { return; } m_bJointFather = joint; OnCreate(m_pComponent); } void PhysicsDynamic::SetUseGravity( bool usege ) { m_bUseGravity = usege; if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_bUseGravity); m_pPxActor->wakeUp(); } } void PhysicsDynamic::SetLinearVelocity( Math::float3& vel ) { if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setLinearVelocity(PxVec3(vel.x(),vel.y(),vel.z())); } } void PhysicsDynamic::SetAngularVelocity( Math::float3& vel ) { if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setAngularVelocity(PxVec3(vel.x(),vel.y(),vel.z())); } } Math::float3 PhysicsDynamic::GetLinearVelocity() const { Math::float3 vel(0.0f,0.0f,0.0f); if ( m_pPxActor && !m_bKinematic ) { PxVec3 v = m_pPxActor->getLinearVelocity(); vel.x() = v.x; vel.y() = v.y; vel.z() = v.z; } return vel; } Math::float3 PhysicsDynamic::GetAngularVelocity() const { Math::float3 vel(0.0f,0.0f,0.0f); if ( m_pPxActor && !m_bKinematic ) { PxVec3 v = m_pPxActor->getAngularVelocity(); vel.x() = v.x; vel.y() = v.y; vel.z() = v.z; } return vel; } void PhysicsDynamic::SetLinearDamping( float damping ) { if ( damping < 0.f ) { damping = 0.f; } m_fLinearDamping = damping; if ( m_pPxActor ) { m_pPxActor->setLinearDamping(m_fLinearDamping); } } void PhysicsDynamic::SetAngularDamping( float damping ) { if ( damping < 0.f ) { damping = 0.f; } m_fAngularDamping = damping; if ( m_pPxActor ) { m_pPxActor->setAngularDamping(m_fAngularDamping); } } void PhysicsDynamic::SetMaxAngularVel( float vel ) { if ( vel < 0.f ) { vel = 0.f; } m_fMaxAngularVel = vel; if ( m_pPxActor ) { m_pPxActor->setMaxAngularVelocity(m_fMaxAngularVel); } } void PhysicsDynamic::SetSleepThreshold( float threshold ) { if (threshold < 0.f) { threshold = 0.f; } m_fSleepThreshold = threshold; if ( m_pPxActor ) { m_pPxActor->setSleepThreshold(m_fSleepThreshold); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForce( const Math::float3& force,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/ ) { if (NULL != m_pPxActor && !m_bKinematic) { m_pPxActor->addForce(PxVec3(force.x(),force.y(),force.z()),(PxForceMode::Enum)forcetype,bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForceAtPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addForceAtPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForceAtLocalPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addForceAtLocalPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddLocalForceAtPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addLocalForceAtPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddLocalForceAtLocalPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addLocalForceAtLocalPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } void PhysicsDynamic::AddTorque( const Math::float3& torque,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/ ) { if ( NULL != m_pPxActor && !m_bKinematic) { m_pPxActor->addTorque(PxVec3(torque.x(),torque.y(),torque.z()),(PxForceMode::Enum)forcetype,bWakeUp); } } void PhysicsDynamic::Move( const Math::float3& dir ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.p.x += dir.x(); _pos.p.y += dir.y(); _pos.p.z += dir.z(); if ( !m_bKinematic ) { m_pPxActor->setGlobalPose(_pos); } else { m_pPxActor->setKinematicTarget(_pos); } } } void PhysicsDynamic::MoveToPostion( const Math::float3& pos ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.p.x = pos.x(); _pos.p.y = pos.y(); _pos.p.z = pos.z(); m_pPxActor->setGlobalPose(_pos); } } void PhysicsDynamic::Rotate( const Math::quaternion& quat ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); Math::quaternion _quat = Math::quaternion::multiply(PxQuatToQuat(_pos.q), quat); _pos.q.x = _quat.x(); _pos.q.y = _quat.y(); _pos.q.z = _quat.z(); _pos.q.w = _quat.w(); if ( !m_bKinematic ) { m_pPxActor->setGlobalPose(_pos); } else { m_pPxActor->setKinematicTarget(_pos); } } } void PhysicsDynamic::RotateToRotation( const Math::quaternion& quat ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.q.x = quat.x(); _pos.q.y = quat.y(); _pos.q.z = quat.z(); _pos.q.w = quat.w(); m_pPxActor->setGlobalPose(_pos); } } void PhysicsDynamic::Tick( float time ) { if ( m_pPxActor ) { if ( !m_bKinematic ) { if ( m_vContantForce.length() > 0.01f ) { m_pPxActor->addForce((PxVec3&)m_vContantForce); } else if ( m_vContantVelocity.length() > 0.01f ) { m_pPxActor->setLinearVelocity((PxVec3&)m_vContantVelocity); } if ( m_vContantTorques.length() > 0.01f ) { m_pPxActor->addTorque((PxVec3&)m_vContantTorques); } else if ( m_vContantAngularVel.length() > 0.01f ) { m_pPxActor->setAngularVelocity((PxVec3&)m_vContantAngularVel); } } if ( m_pComponent && m_pComponent->GetActor() ) { PxTransform _GlobalPos = m_pPxActor->getGlobalPose(); Math::float4 pos(_GlobalPos.p.x, _GlobalPos.p.y, _GlobalPos.p.z, 1.0f); Math::quaternion rot(_GlobalPos.q.x, _GlobalPos.q.y, _GlobalPos.q.z, _GlobalPos.q.w); m_pComponent->GetActor()->SetWorldPosition(pos); m_pComponent->GetActor()->SetWorldRotation(rot); } } } bool PhysicsDynamic::CopyFrom( GPtr<PhysicsEntity> src ) { if ( !src.isvalid() || src->GetType() != m_eType ) { return false; } Super::CopyFrom(src); GPtr<PhysicsDynamic> _pSrc = src.downcast<PhysicsDynamic>(); this->m_bJointFather = _pSrc->IsJointFather(); this->m_bUseGravity = _pSrc->IsUseGravity(); this->m_bKinematic = _pSrc->IsKinematic(); this->m_fLinearDamping = _pSrc->GetLinearDamping(); this->m_fAngularDamping = _pSrc->GetAngularDamping(); this->m_fMaxAngularVel = _pSrc->GetMaxAngularVel(); this->m_fSleepThreshold = _pSrc->GetSleepThreshold(); this->m_vContantForce = _pSrc->GetConstantForce(); this->m_vContantVelocity = _pSrc->GetConstantVelocity(); this->m_vContantTorques = _pSrc->GetConstantTorques(); this->m_vContantAngularVel = _pSrc->GetConstantAngularVel(); return true; } void PhysicsDynamic::UpdateEntityMass() { if (m_pPxActor != NULL) { int cnt = m_arrPhysicsShapePtr.Size(); int nb = m_pPxActor->getNbShapes(); PxReal* fDensities = new PxReal[nb]; PxShape** mShapes = new PxShape*[nb]; m_pPxActor->getShapes(mShapes,nb*sizeof(PxShape*)); int k=0; for(int i=0;i<nb;i++) { int j=0; for(j=0;j<cnt;j++) { if ( !m_arrPhysicsShapePtr[j]->IsValid() ) { continue; } if(m_arrPhysicsShapePtr[j]->GetName() == mShapes[i]->getName()) break; } if(j>=cnt) { delete []fDensities; delete []mShapes; m_pPxActor->setMass(0.01f); return; } if((PxU8)(mShapes[i]->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) == 0) { continue; } fDensities[k++] = m_arrPhysicsShapePtr[j]->GetDensity(); } if(k<=0) { delete []fDensities; delete []mShapes; m_pPxActor->setMass(0.01f); return; } PxRigidBodyExt::updateMassAndInertia(*m_pPxActor, fDensities,k); delete []fDensities; delete []mShapes; } } float PhysicsDynamic::GetMass() { if ( m_pPxActor == NULL ) { return 0.01f; } bool _needUpdate = false; for ( int i=0; i<m_arrPhysicsShapePtr.Size(); ++i ) { if ( !m_arrPhysicsShapePtr[i]->IsValid() ) { //m_pPxActor->setMass(0.01f); //return 0.01f; continue; } if ( m_arrPhysicsShapePtr[i]->IsMassUpdate() ) { _needUpdate = true; m_arrPhysicsShapePtr[i]->UpdateMass(); } } if ( _needUpdate ) { UpdateEntityMass(); } return m_pPxActor->getMass(); } void PhysicsDynamic::Save( AppWriter* pSerialize ) { Super::Save(pSerialize); pSerialize->SerializeBool("JointFather", m_bJointFather); pSerialize->SerializeBool("UseGravity", m_bUseGravity); pSerialize->SerializeBool("Kinematic", m_bKinematic); pSerialize->SerializeFloat("LinearDamp", m_fLinearDamping); pSerialize->SerializeFloat("AngularDamp", m_fAngularDamping); pSerialize->SerializeFloat("MaxAngularVel", m_fMaxAngularVel); pSerialize->SerializeFloat("SleepThrehold", m_fSleepThreshold); pSerialize->SerializeFloat3("ContantForce", m_vContantForce); pSerialize->SerializeFloat3("ContantVelocity", m_vContantVelocity); pSerialize->SerializeFloat3("ContantTorques", m_vContantTorques); pSerialize->SerializeFloat3("ContantAngularVel", m_vContantAngularVel); } void PhysicsDynamic::Load( Version ver, AppReader* pReader ) { Super::Load(ver,pReader); pReader->SerializeBool("JointFather", m_bJointFather); pReader->SerializeBool("UseGravity", m_bUseGravity); pReader->SerializeBool("Kinematic", m_bKinematic); pReader->SerializeFloat("LinearDamp", m_fLinearDamping); pReader->SerializeFloat("AngularDamp", m_fAngularDamping); pReader->SerializeFloat("MaxAngularVel", m_fMaxAngularVel); pReader->SerializeFloat("SleepThrehold", m_fSleepThreshold); pReader->SerializeFloat3("ContantForce", m_vContantForce); pReader->SerializeFloat3("ContantVelocity", m_vContantVelocity); pReader->SerializeFloat3("ContantTorques", m_vContantTorques); pReader->SerializeFloat3("ContantAngularVel", m_vContantAngularVel); } } #endif
28.263866
159
0.662068
BikkyS
9026bfaae15f2420e5935d7435da17d74021a30d
2,528
cpp
C++
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
47
2018-10-05T01:54:17.000Z
2022-02-19T04:53:24.000Z
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
36
2018-10-05T03:43:24.000Z
2021-04-23T19:19:47.000Z
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
12
2018-10-08T11:45:24.000Z
2021-09-21T08:08:40.000Z
// MIT License (c) 2019 BYU PCCL see LICENSE file #include "Holodeck.h" #include "RangeFinderSensor.h" #include "Json.h" URangeFinderSensor::URangeFinderSensor() { SensorName = "RangeFinderSensor"; } // Allows sensor parameters to be set programmatically from client. void URangeFinderSensor::ParseSensorParms(FString ParmsJson) { Super::ParseSensorParms(ParmsJson); TSharedPtr<FJsonObject> JsonParsed; TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ParmsJson); if (FJsonSerializer::Deserialize(JsonReader, JsonParsed)) { if (JsonParsed->HasTypedField<EJson::Number>("LaserCount")) { LaserCount = JsonParsed->GetIntegerField("LaserCount"); } if (JsonParsed->HasTypedField<EJson::Number>("LaserAngle")) { LaserAngle = -JsonParsed->GetIntegerField("LaserAngle"); // in client positive angles point up } if (JsonParsed->HasTypedField<EJson::Number>("LaserMaxDistance")) { LaserMaxDistance = JsonParsed->GetIntegerField("LaserMaxDistance") * 100; // meters to centimeters } if (JsonParsed->HasTypedField<EJson::Boolean>("LaserDebug")) { LaserDebug = JsonParsed->GetBoolField("LaserDebug"); } } else { UE_LOG(LogHolodeck, Fatal, TEXT("URangeFinderSensor::ParseSensorParms:: Unable to parse json.")); } } void URangeFinderSensor::InitializeSensor() { Super::InitializeSensor(); //You need to get the pointer to the object you are attached to. Parent = this->GetAttachmentRootActor(); } void URangeFinderSensor::TickSensorComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { float* FloatBuffer = static_cast<float*>(Buffer); for (int i = 0; i < LaserCount; i++) { FVector start = GetComponentLocation(); FVector end = GetForwardVector(); FVector right = GetRightVector(); end = end.RotateAngleAxis(360 * i / LaserCount, GetUpVector()); right = right.RotateAngleAxis(360 * i / LaserCount, GetUpVector()); end = end.RotateAngleAxis(LaserAngle, right); end = end * LaserMaxDistance; end = start + end; FCollisionQueryParams QueryParams = FCollisionQueryParams(); QueryParams.AddIgnoredActor(Parent); FHitResult Hit = FHitResult(); bool TraceResult = GetWorld()->LineTraceSingleByChannel(Hit, start, end, ECollisionChannel::ECC_Visibility, QueryParams); FloatBuffer[i] = (TraceResult ? Hit.Distance : LaserMaxDistance) / 100; // centimeter to meters if (LaserDebug) { DrawDebugLine(GetWorld(), start, end, FColor::Green, false, .01, ECC_WorldStatic, 1.f); } } }
33.263158
131
0.741297
AdrianSchoisengeier
9027979e51cf74adfe0e6bc3b083d48950c71fee
755
cpp
C++
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
/** * (210704) 로프 * https://www.acmicpc.net/problem/2217 * * [풀이] * 로프문제는 각 로프를 선택해서 최대중량을 알아내는 문제입니다. * 여기서 최대중량은 선택한 로프 중 최소중량을 가진 로프의 * 중량에 선택한 로프의 개수를 곱하면 얼마나 중량을 버틸수 있는지 * 계산할 수 있습니다. * * 어떤 로프들을 사용해야 최대중량을 얻을 수 있는지 알고리즘은 * 다음과 같습니다. * * 1) 입력받은 숫자들을 배열에 넣고 오름차순으로 정렬합니다. * 2) 차례대로 배열을 순회하면서 (로프의 개수)-(현재 index) * 를 곱하고 이를 저장합니다. * 3) 배열안에서 최대값을 정답으로 출력합니다. */ #include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; int main() { int N; scanf("%d", &N); int* ropes = (int*)malloc(sizeof(int)*N); for (int i=0; i<N; i++) { scanf("%d", ropes+i); } sort(ropes, ropes+N); for (int i=0; i<N; i++) { ropes[i] *= N-i; } printf("%d\n", *max_element(ropes, ropes+N)); free(ropes); return 0; }
16.413043
46
0.590728
yejun614
9027d77ab257fa763445f46ae0d08c6a882c0dbc
423
cpp
C++
leetcode/SubsetSums.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
leetcode/SubsetSums.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
leetcode/SubsetSums.cpp
atpk/CP
0eee3af02bb0466c85aeb8dd86cf3620567a354c
[ "MIT" ]
null
null
null
class Solution { public: vector<int> res; void subset(vector<int> arr, int l, int r, int sum){ if(l>r){ res.push_back(sum); return; } subset(arr, l+1, r, sum + arr[l]); subset(arr, l+1, r, sum); } vector<int> subsetSums(vector<int> arr, int N) { // Write Your Code here subset(arr, 0, N-1, 0); return res; } };
21.15
56
0.472813
atpk
9028e5bdb9c61b0fe6c16d878f84453c1a6d71ec
3,076
cpp
C++
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
/* =========================================================================== * The MIT License (MIT) * * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * ===========================================================================*/ #include "Models/modelsrepo.h" #include "QmlHelpers/systemintegrator.h" #include <QApplication> #include <QHash> #include <QObject> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QtQml> #include <QQuickWindow> int main(int argc, char *argv[]) { // uncomment and modify for additional logging // see: http://doc.qt.io/qt-5/qloggingcategory.html // qputenv("QT_LOGGING_RULES", "qt.scenegraph.general=false;qt.scenegraph.time.renderloop=false;qt.scenegraph.time.renderer=false;qt.qpa.gl=true"); // Smoother rendering when resizing the window using the basic render loop // see: http://doc.qt.io/qt-5/qtquick-visualcanvas-scenegraph.html // for details of how it works qputenv("QSG_RENDER_LOOP", "basic"); // Qt::AA_UseSoftwareOpenGL will attempt to force the use of opengl32sw.dll // can be deployed with the llvm mesa library // QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); // Setting the scene graph backend to software will use the internal Qt // QSG software renderer // QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software); QApplication app(argc, argv); using namespace staticpendulum; qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator"); qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo", &ModelsRepo::qmlInstance); QQmlApplicationEngine engine; // Add import path to resolve Qml modules, note: using qrc path engine.addImportPath("qrc:/Qml/"); engine.rootContext()->setContextProperty("applicationDirPath", qApp->applicationDirPath()); engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml"))); return app.exec(); }
42.722222
148
0.698635
jbuckmccready
902bc378ac077708962ba3869cf4561fddce47bc
1,544
cpp
C++
src/GameState/GPaddleProcess.cpp
isabella232/boin
380a6d73dcf9f613f842ba4d7d5bb4b683d75c8b
[ "MIT" ]
null
null
null
src/GameState/GPaddleProcess.cpp
isabella232/boin
380a6d73dcf9f613f842ba4d7d5bb4b683d75c8b
[ "MIT" ]
1
2021-02-24T05:30:19.000Z
2021-02-24T05:30:19.000Z
src/GameState/GPaddleProcess.cpp
isabella232/boing
380a6d73dcf9f613f842ba4d7d5bb4b683d75c8b
[ "MIT" ]
null
null
null
#include "GPaddleProcess.h" static const TInt DELTA_X = 4; GPaddleProcess::GPaddleProcess(GGameState *aGameState) { mGameState = aGameState; mState = MOVE_STATE; mSprite = new BSprite(0, PLAYER_SLOT, IMG_PADDLE, STYPE_PLAYER); mSprite->w = 8; mSprite->h = 32; mSprite->flags |= SFLAG_RENDER | SFLAG_CHECK; mSprite->cMask |= STYPE_EBULLET; mGameState->AddSprite(mSprite); Reset(); } GPaddleProcess::~GPaddleProcess() { mSprite->Remove(); delete mSprite; } void GPaddleProcess::Reset() { mSprite->x = 8; mSprite->y = (SCREEN_HEIGHT / 2) - 16; } void GPaddleProcess::Pause(TBool aPause) { if (aPause) { mSprite->flags &= ~SFLAG_RENDER; mState = WAIT_STATE; } else { mSprite->flags |= SFLAG_RENDER; mState = MOVE_STATE; } } TBool GPaddleProcess::WaitState() { return ETrue; } TBool GPaddleProcess::MoveState() { if (mGameState->GameOver()) { return ETrue; } if (mSprite->cType) { mSprite->cType = 0; } if (gControls.IsPressed(JOYUP)) { mSprite->y = mSprite->y - DELTA_X; if (mSprite->y < 0) { mSprite->y = 0; } } else if (gControls.IsPressed(JOYDOWN)) { mSprite->y = mSprite->y + DELTA_X; if (mSprite->y > (SCREEN_HEIGHT - 32)) { mSprite->y = SCREEN_HEIGHT - 32; } } return ETrue; } TBool GPaddleProcess::RunBefore() { return ETrue; } TBool GPaddleProcess::RunAfter() { switch (mState) { case MOVE_STATE: return MoveState(); case WAIT_STATE: return WaitState(); default: return EFalse; } }
19.544304
66
0.639249
isabella232
902c1a162f3a5c576154f5b74ee99898f82fbf01
16,504
cpp
C++
Engine/AI/Pathfinding/NavigationGrid.cpp
vitei/Usa
c44f893d5b3d8080529ecf0e227f983fddb829d4
[ "MIT" ]
47
2018-04-27T02:16:26.000Z
2022-02-28T05:21:24.000Z
Engine/AI/Pathfinding/NavigationGrid.cpp
vitei/Usa
c44f893d5b3d8080529ecf0e227f983fddb829d4
[ "MIT" ]
2
2018-11-13T18:46:41.000Z
2022-03-12T00:04:44.000Z
Engine/AI/Pathfinding/NavigationGrid.cpp
vitei/Usa
c44f893d5b3d8080529ecf0e227f983fddb829d4
[ "MIT" ]
6
2019-08-10T21:56:23.000Z
2020-10-21T11:18:29.000Z
/**************************************************************************** // Usagi Engine, Copyright © Vitei, Inc. 2013 ****************************************************************************/ // NavigationGrid.cpp #include "Engine/Common/Common.h" #include "Engine/Debug/Rendering/DebugRender.h" #include "NavigationGrid.h" #include "Path.h" #include <float.h> namespace usg { namespace ai { NavigationGrid::NavigationGrid() : m_uBlockingAreaUIDCounter(0), m_blocks(NavigationGrid::MaxNumBlocks), m_waypoints(NavigationGrid::MaxNumWaypoints) { } NavigationGrid::~NavigationGrid() { m_blocks.Clear(); m_waypoints.Clear(); } #ifdef DEBUG_BUILD bool NavigationGrid::CheckIntegrity() { for (FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { const Waypoint* pWaypoint = (*it); if (!CanPlacePoint(pWaypoint->GetPosition())) { DEBUG_PRINT("Waypoint at (%f,%f) is inside blocking area.\n",pWaypoint->GetPosition().x,pWaypoint->GetPosition().y); return false; } } return true; } #endif bool NavigationGrid::CreateWaypoint(const Vector3f& vPos, uint32 uNameHash) { return CreateWaypoint(Vector2f(vPos.x, vPos.z), uNameHash); } const Waypoint* NavigationGrid::GetWaypoint(uint32 uNameHash) const { for (FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { const Waypoint* pWaypoint = *it; if (pWaypoint->GetNameHash() == uNameHash) { return pWaypoint; } } return NULL; } bool NavigationGrid::CreateWaypoint(const Vector2f& vPos, uint32 uNameHash) { Waypoint* pWaypoint = m_waypoints.Alloc(); pWaypoint->SetPosition(vPos); pWaypoint->SetNameHash(uNameHash); return true; } Waypoint* NavigationGrid::GetClosestWaypointAccessibleFrom(const Vector2f& vPos) const { Waypoint* pWaypoint = NULL; Line line; line.m_vFrom = vPos; float fMinSqrDist = FLT_MAX; for (FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { const Vector2f& vWaypointPosition = (*it)->GetPosition(); const float fSqrDist = vPos.GetSquaredDistanceFrom(vWaypointPosition); if (fSqrDist < fMinSqrDist) { line.m_vTo = vWaypointPosition; if (!LineTest(line)) { fMinSqrDist = fSqrDist; pWaypoint = (*it); } } } return pWaypoint; } Waypoint* NavigationGrid::GetClosestWaypoint(const Vector2f& vPos) const { Waypoint* pWaypoint = NULL; float fMinSqrDist = FLT_MAX; for(FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { const float fSqrDist = vPos.GetSquaredDistanceFrom((*it)->GetPosition()); if(fSqrDist < fMinSqrDist) { fMinSqrDist = fSqrDist; pWaypoint = (*it); } } return pWaypoint; } int NavigationGrid::FindPath(const Vector3f& vStart, const Vector3f& vEnd, usg::ai::Path& path) const { Vector2f vStartV2(vStart.x, vStart.z); Vector2f vEndV2(vEnd.x, vEnd.z); return FindPath(vStartV2, vEndV2, path); } int NavigationGrid::FindPath(const Vector2f& vStart, const Vector2f& vEnd, usg::ai::Path& path) const { int rval = NAVIGATION_SUCCESS; path.Reset(); Waypoint start(vStart); Waypoint end(vEnd); // An important optimization: if you can go straight to target, construct a minimal path: if (!LineTest(usg::ai::Line(vStart, vEnd))) { path.AddLast(vEnd); return NAVIGATION_SUCCESS; } // Test if start/end point is inside blocking area. If yes, go to nearest waypoint as a fallback. Waypoint* pClosestToStart = GetClosestWaypointAccessibleFrom(vStart); if (pClosestToStart == NULL) pClosestToStart = GetClosestWaypoint(vStart); if (!pClosestToStart) { path.AddLast(vEnd); return NAVIGATION_START_BLOCKED; } Waypoint* pClosestToEnd = GetClosestWaypointAccessibleFrom(vEnd); if (pClosestToEnd == NULL) pClosestToEnd = GetClosestWaypoint(vEnd); if (!CanPlacePoint(vEnd)) { if (pClosestToEnd != NULL) { const float fDistToToTarget = vStart.GetSquaredDistanceFrom(vEnd); const float fDistToToClosestWaypoint = vStart.GetSquaredDistanceFrom(pClosestToEnd->GetPosition()); if (fDistToToClosestWaypoint > fDistToToTarget) { // At least going to nearest waypoint takes us closer to target, so let path.AddLast(vEnd); return NAVIGATION_END_BLOCKED; } } else { path.AddLast(vEnd); return NAVIGATION_END_BLOCKED; } } FindPath(pClosestToStart, pClosestToEnd, path); path.AddFirst(&start); path.AddLast(&end); SubdividePath(path); SubdividePath(path); PathVisibility(path); path.GetNext(); // remove the first position because this is basically where we are standing right now, unless we changed it return rval; } void NavigationGrid::SubdividePath(usg::ai::Path& path) const { usg::ai::Path res; Vector2f* pvPrev = NULL; for(Vector2f* it = path.Begin(); it != path.End(); ++it) { const Vector2f& vPos = (*it); if(pvPrev != NULL) { res.AddLast(Vector2f((pvPrev->x + vPos.x) * 0.5f, (pvPrev->y + vPos.y) * 0.5f)); } res.AddLast(vPos); pvPrev = it; } path = res; } void NavigationGrid::PathVisibility(usg::ai::Path& path) const { usg::ai::Path res; for (Vector2f* it = path.Begin(); it != path.End(); ++it) { res.AddLast(*it); } Vector2f* pvPrev = NULL; Vector2f* pvPrevPrev = NULL; Vector2f* pvCurrent = NULL; Vector2f* pvNext = NULL; Vector2f* pvLast = NULL; path.Reset(); pvPrev = (res.Begin()); pvCurrent = (res.Last()); if (!LineTest(usg::ai::Line(*pvCurrent, *pvPrev))) { path.AddLast(*pvPrev); path.AddLast(*pvCurrent); return; } pvCurrent = res.Begin(); path.AddLast(*pvCurrent); pvLast = (res.Last()); Vector2f* nextIt = res.Begin(); Vector2f* prevIt = res.Begin(); int iT = 0; while (pvCurrent != NULL && nextIt != res.End()) { ++nextIt; pvNext = nextIt; if (!LineTest(usg::ai::Line(*pvCurrent, *pvNext))) { pvPrev = pvNext; prevIt = nextIt; } else { // If the previous of the previous location is the same, then the subdivision probably slightly pushed it inside a block se lets just move on. if (pvPrev != pvPrevPrev) { path.AddLast(*pvPrev); pvPrevPrev = pvPrev; pvCurrent = pvPrev; nextIt = prevIt; } else { pvPrev = pvNext; prevIt = nextIt; } } if (pvNext == pvLast) { break; } } path.AddLast(*pvLast); } const BlockingArea& NavigationGrid::CreateBlock(const Vector3f& vPos, float fWidth, float fHeight, float fAngle, bool bAddWaypoints) { Vector2f vPosV2(vPos.x, vPos.z); return CreateBlock(vPosV2, fWidth, fHeight, fAngle, bAddWaypoints); } const BlockingArea& NavigationGrid::CreateBlock(float fX, float fY, float fWidth, float fHeight, float fAngle, bool bAddWaypoints) { return CreateBlock(Vector2f(fX, fY), fWidth, fHeight, fAngle, bAddWaypoints); } void NavigationGrid::RemoveBlock(uint32 uUID) { for (FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { if ((*it)->uUID == uUID) { m_blocks.Free(*it); break; } } } const BlockingArea& NavigationGrid::CreateBlock(const Vector2f& vPos, float fWidth, float fHeight, float fAngle, bool bAddWaypoints) { usg::ai::BlockingArea* pNewBlockingArea = m_blocks.Alloc(); pNewBlockingArea->uUID = m_uBlockingAreaUIDCounter++; usg::ai::OBB* pOBB = &pNewBlockingArea->shape; pOBB->SetCenter(vPos); pOBB->SetScale(Vector2f(fWidth, fHeight)); pOBB->SetRotation(fAngle); if(bAddWaypoints) { const uint32 uCount = pOBB->GetNumVerts(); const Vector2f* pVerts = pOBB->GetVerts(); const float fOffset = 2.5f; for(uint32 i = 0; i < uCount; i++) { Vector2f vPoint = vPos + pVerts[i]; const Vector2f vDirToCenter = (vPoint - vPos).GetNormalised(); vPoint += vDirToCenter * fOffset; CreateWaypoint(vPoint,0); } } return *pNewBlockingArea; } void NavigationGrid::FindPath(Waypoint* pStart, Waypoint* pEnd, usg::ai::Path& path) const { if(!pStart || !pEnd) { return; } Reset(); pStart->SetG(0.0f); pStart->SetF(0.0f); pStart->SetOpen(true); m_openList.AddToEnd(pStart); Waypoint* pCurrent = NULL; while(m_openList.GetSize() > 0) { float fDistance = FLT_MAX; for(List<Waypoint>::Iterator it = m_openList.Begin(); !it.IsEnd(); ++it) { Waypoint* pWp = (*it); if(pWp->F() < fDistance) { pCurrent = pWp; fDistance = pWp->F(); } } if(pCurrent == pEnd) { while(pCurrent != NULL) { #ifdef DEBUG_BUILD pCurrent->m_debugDrawColor = Color::Red; #endif path.AddFirst(pCurrent); pCurrent = pCurrent->GetParent(); } return; } m_openList.Remove(pCurrent); pCurrent->SetClosed(true); pCurrent->SetOpen(false); for(FastPool<Link>::Iterator it = pCurrent->GetLinkIterator(); !it.IsEnd(); ++it) { Link* pLink = (*it); Waypoint* pLinkWp = pLink->GetWaypoint(); if(!pLinkWp->IsClosed()) { const float fTentativeG = pCurrent->G() + pLink->Distance(); bool bIsBetter = false; if(!pLinkWp->IsOpen()) { m_openList.AddToFront(pLinkWp); pLinkWp->SetOpen(true); pLinkWp->SetClosed(false); bIsBetter = true; } else { if(fTentativeG < pLinkWp->G()) { bIsBetter = true; } } if(bIsBetter) { pLinkWp->SetParent(pCurrent); pLinkWp->SetG(fTentativeG); pLinkWp->SetF(pLinkWp->G() + pLinkWp->GetPosition().Distance(pEnd->GetPosition())); } } } } pCurrent = pEnd; while(pCurrent != NULL) { path.AddFirst(pCurrent); #ifdef DEBUG_BUILD pCurrent->m_debugDrawColor = Color::Red; #endif pCurrent = pCurrent->GetParent(); } } void NavigationGrid::BuildLinks() { for(FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { Waypoint* pCurrent = (*it); pCurrent->ClearLinks(); const Vector2f vFrom = pCurrent->GetPosition(); for(FastPool<Waypoint>::Iterator it2 = m_waypoints.Begin(); !it2.IsEnd(); ++it2) { Waypoint* pTarget = (*it2); if(pCurrent != pTarget) { const Vector2f vTo = pTarget->GetPosition(); if(!LineTest(usg::ai::Line(vFrom, vTo))) { const float fDistance = vFrom.Distance(vTo); pCurrent->AddLink((pTarget), fDistance); } } } } } bool NavigationGrid::LineTest(const Vector2f& vFrom, const Vector2f& vTo) const { Line line; line.m_vFrom = vFrom; line.m_vTo = vTo; return LineTest(line); } bool NavigationGrid::LineTest(const usg::ai::Line& line) const { IShape* pShapes[32]; uint32 uSize = GetOverlappingShapes(&pShapes[0], 32, line); for (uint32 i = 0; i < uSize; i++) { if (pShapes[i]->Intersects(line)) { return true; } } return false; } bool NavigationGrid::CanPlacePoint(const Vector2f& vPoint) const { const uint64 uPointMask = shape_details::ComputeGridMask(vPoint); for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { const bool bMaskFail = ((*it)->shape.GetGridMask() & uPointMask) == 0; if (!bMaskFail) { if ((*it)->shape.Intersects(vPoint)) { return false; } } } return true; } uint32 NavigationGrid::GetOverlappingShapes(IShape** pShapes, uint32 uSize, usg::ai::Line line) const { uint32 uCounter = 0; Vector2f hit; const uint64 uLineMask = shape_details::ComputeGridMask(line.m_vFrom, line.m_vTo); for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd() && (uCounter < uSize); ++it) { const bool bMaskFail = ((*it)->shape.GetGridMask() & uLineMask) == 0; if (!bMaskFail) { if ((*it)->shape.Intersects(line, hit)) { pShapes[uCounter++] = &(*it)->shape; } } } return uCounter; } const usg::ai::OBB* NavigationGrid::GetNearestOBB(const Vector3f& vPos) const { return GetNearestOBB(Vector2f(vPos.x, vPos.z)); } const usg::ai::OBB* NavigationGrid::GetNearestOBB(const Vector2f& vPos) const { float fDistance = FLT_MAX; const usg::ai::OBB* pClosestOBB = NULL; for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { const usg::ai::OBB* pOBB = &(*it)->shape; const Vector2f& vOBB = pOBB->GetCenter(); const float fDistanceToTargetSq = (vOBB - vPos).MagnitudeSquared(); if(fDistanceToTargetSq < fDistance) { fDistance = fDistanceToTargetSq; pClosestOBB = pOBB; } } return pClosestOBB; } uint32 NavigationGrid::GetNearestOBBs(const Vector2f& vPos, usg::ai::OBB** pBuffer, uint32 uSize) const { if (uSize == 0) { return 0; } float fDistance = FLT_MAX; for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { usg::ai::OBB* pOBB = &(*it)->shape; const float fDistanceToTargetSq = pOBB->GetSquaredDistanceToPoint(vPos); if(fDistanceToTargetSq < fDistance) { fDistance = fDistanceToTargetSq; utl::MoveElements(pBuffer, 1, 0, uSize - 1); pBuffer[0] = pOBB; } else { for(uint32 i = 1; i < uSize; i++) { if(pBuffer[i] == NULL) { pBuffer[i] = pOBB; break; } else if(fDistanceToTargetSq < pBuffer[i]->GetSquaredDistanceToPoint(vPos)) { if(i < uSize - 2) { utl::MoveElements(pBuffer, i + 1, i, uSize - i - 1); } pBuffer[i] = pOBB; break; } } } } if (pBuffer[uSize - 1] != NULL) { // Super likely return uSize; } uint32 uCount = 0; for (uint32 i = 1; i < uSize; i++) { if (pBuffer[i] != NULL) { uCount++; } } return uCount; } uint32 NavigationGrid::GetNearestOBBs(const Vector3f& vPos, usg::ai::OBB** pBuffer, uint32 uSize) const { return GetNearestOBBs(Vector2f(vPos.x, vPos.z), pBuffer, uSize); } const usg::ai::OBB* NavigationGrid::GetNearestIntersectingOBB(const Vector3f& vPos) const { return GetNearestIntersectingOBB(Vector2f(vPos.x, vPos.z)); } const usg::ai::OBB* NavigationGrid::GetNearestIntersectingOBB(const Vector2f& vPos) const { const uint64 uPointMask = shape_details::ComputeGridMask(vPos); for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { const bool bMaskFail = ((*it)->shape.GetGridMask() & uPointMask) == 0; if (bMaskFail) { continue; } if((*it)->shape.Intersects(vPos)) { return &(*it)->shape; } } return NULL; } void NavigationGrid::Reset() const { for(FastPool<Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { (*it)->Reset(); } m_openList.Clear(); } void NavigationGrid::DebugDrawBlocks(Debug3D* pDebugRender) const { ASSERT(pDebugRender != NULL); Color blue = Color::Blue; blue.m_fA = 0.5f; for(FastPool<usg::ai::BlockingArea>::Iterator it = m_blocks.Begin(); !it.IsEnd(); ++it) { const usg::ai::OBB* pOBB = &(*it)->shape; const Vector2f vPos = pOBB->GetCenter(); const Vector2f vScale = pOBB->GetScale(); const float fAngle = pOBB->GetAngle(); usg::Matrix4x4 m; m.LoadIdentity(); m.MakeRotateY(usg::Math::DegToRad(fAngle)); m.Scale(vScale.x * 0.5f, 20.0f, vScale.y * 0.5f, 1.0f); m.SetPos(usg::Vector3f(vPos.x, 10.0f, vPos.y)); pDebugRender->AddCube(m, blue); } } void NavigationGrid::DebugDrawWaypoints(Debug3D* pDebugRender) const { #ifdef DEBUG_BUILD ASSERT(pDebugRender != NULL); for(FastPool<usg::ai::Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { usg::ai::Waypoint& wp = *(*it); const Vector2f& vPos = wp.GetPosition(); usg::Matrix4x4 m; m.LoadIdentity(); m.Scale(1.0f,1.0f,1.0f, 1.0f); m.SetPos(usg::Vector3f(vPos.x, 10.0f, vPos.y)); Color green = wp.m_debugDrawColor; green.m_fA = 0.5f; pDebugRender->AddCube(m, green); } #endif } void NavigationGrid::DebugDrawLinks(Debug3D* pDebugRender) const { ASSERT(pDebugRender != NULL); Color red = Color::Red; red.m_fA = 0.5f; for(FastPool<usg::ai::Waypoint>::Iterator it = m_waypoints.Begin(); !it.IsEnd(); ++it) { usg::ai::Waypoint& wp = *(*it); const Vector2f& vPos = wp.GetPosition(); FastPool<usg::ai::Link>::Iterator it2 = wp.GetLinkIterator(); for(; !it2.IsEnd(); ++it2) { const Vector2f vV = (*it2)->GetWaypoint()->GetPosition(); pDebugRender->AddLine(Vector3f(vPos.x, 20.0f, vPos.y), Vector3f(vV.x, 20.0f, vV.y), red, 1.0f); } } } bool NavigationGrid::GetNearestValidPoint(const IShape* pShape, const Vector2f& vPoint, const Vector2f& vOrigin, Vector2f& vOutPoint) const { const IShape* pOBB = (pShape == NULL) ? GetNearestIntersectingOBB(vPoint) : pShape; if(pOBB != NULL) { Vector2f vIP1, vIP2; usg::ai::Line line; line.m_vFrom = vOrigin; line.m_vTo = vPoint; int iIntersectionCount = pOBB->Intersects(line, vIP1, vIP2); if (iIntersectionCount == 1) { // Great! Move slightly toward vOrigin from the intersection points vOutPoint = vIP1 + (vOrigin-vIP1)*0.001f; return true; } } return false; } } // namespace ai } // namespace usg
23.815296
145
0.667172
vitei
902c3e72905ac8887c9c8dc833f2224fb09a59e8
2,953
cpp
C++
TAO/tests/Portable_Interceptors/PICurrent/ClientRequestInterceptor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tests/Portable_Interceptors/PICurrent/ClientRequestInterceptor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tests/Portable_Interceptors/PICurrent/ClientRequestInterceptor.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// $Id: ClientRequestInterceptor.cpp 91652 2010-09-08 14:42:59Z johnnyw $ #include "ClientRequestInterceptor.h" #include "tao/CORBA_String.h" #include "ace/Log_Msg.h" #include "ace/OS_NS_string.h" ClientRequestInterceptor::ClientRequestInterceptor ( PortableInterceptor::SlotId id, PortableInterceptor::Current_ptr pi_current) : slot_id_ (id), pi_current_ (PortableInterceptor::Current::_duplicate (pi_current)) { } char * ClientRequestInterceptor::name () { return CORBA::string_dup ("ClientRequestInterceptor"); } void ClientRequestInterceptor::destroy (void) { } void ClientRequestInterceptor::send_request ( PortableInterceptor::ClientRequestInfo_ptr ri) { CORBA::String_var op = ri->operation (); if (ACE_OS::strcmp (op.in (), "invoke_me") != 0) return; // Don't mess with PICurrent if not invoking test method. try { // Retrieve data from the RSC (request scope current). CORBA::Long number = 0; CORBA::Any_var data = ri->get_slot (this->slot_id_); if (!(data.in () >>= number)) { ACE_ERROR ((LM_ERROR, "(%P|%t) ERROR: Unable to extract data from Any.\n")); throw CORBA::INTERNAL (); } ACE_DEBUG ((LM_DEBUG, "(%P|%t) Extracted <%d> from RSC slot %u\n", number, this->slot_id_)); CORBA::Any new_data; CORBA::String_var s = CORBA::string_dup ("Et tu Brute?"); new_data <<= s.in (); // Now reset the contents of our slot in the thread-scope // current (TSC). this->pi_current_->set_slot (this->slot_id_, new_data); // Now retrieve the data from the RSC again. It should not have // changed! CORBA::Long number2 = -1; CORBA::Any_var data2 = ri->get_slot (this->slot_id_); if (!(data2.in () >>= number2) || number != number2) { ACE_ERROR ((LM_ERROR, "(%P|%t) ERROR: RSC was modified after " "TSC was modified.\n")); throw CORBA::INTERNAL (); } } catch (const PortableInterceptor::InvalidSlot& ex) { ex._tao_print_exception ("Exception thrown in ""send_request()\n"); ACE_DEBUG ((LM_DEBUG, "Invalid slot: %u\n", this->slot_id_)); throw CORBA::INTERNAL (); } ACE_DEBUG ((LM_INFO, "(%P|%t) Client side RSC/TSC semantics appear " "to be correct.\n")); } void ClientRequestInterceptor::send_poll ( PortableInterceptor::ClientRequestInfo_ptr) { } void ClientRequestInterceptor::receive_reply ( PortableInterceptor::ClientRequestInfo_ptr) { } void ClientRequestInterceptor::receive_exception ( PortableInterceptor::ClientRequestInfo_ptr) { } void ClientRequestInterceptor::receive_other ( PortableInterceptor::ClientRequestInfo_ptr) { }
23.814516
76
0.608872
cflowe
902cd5a585d087fb3212da81977fbf035171d5f7
2,820
cpp
C++
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
6
2021-01-19T21:47:37.000Z
2022-01-30T21:20:35.000Z
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
5
2020-09-18T16:23:35.000Z
2022-02-16T13:44:17.000Z
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
4
2020-05-22T09:57:56.000Z
2021-08-19T04:05:22.000Z
// Copyright (c) 2021 Chadwick Boulay #include "LSLOutletComponent.h" #include "LSLPrivatePCH.h" #include <string> // Sets default values for this component's properties ULSLOutletComponent::ULSLOutletComponent() : StreamName(), StreamType(), SamplingRate(LSL_IRREGULAR_RATE), ChannelFormat(EChannelFormat::cfmt_float32), StreamID("NoStreamID") { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. bWantsInitializeComponent = true; } // Called when the game starts void ULSLOutletComponent::BeginPlay() { Super::BeginPlay(); //lsl_streaminfo lsl_myinfo = lsl_create_streaminfo(TCHAR_TO_ANSI(*StreamName), TCHAR_TO_ANSI(*StreamType), ChannelCount, SamplingRate, (lsl_channel_format_t)ChannelFormat, TCHAR_TO_ANSI(*StreamID)); UE_LOG(LogLSL, Log, TEXT("Attempting to create stream outlet with name %s, type %s, sampling rate %d."), *StreamName, *StreamType, SamplingRate); lsl::stream_info data_info( TCHAR_TO_ANSI(*StreamName), TCHAR_TO_ANSI(*StreamType), (int16)Channels.Num(), (double)SamplingRate, lsl::channel_format_t(ChannelFormat), TCHAR_TO_ANSI(*StreamID) ); lsl::xml_element channels = data_info.desc().append_child("channels"); for (auto& ch : Channels) { channels.append_child("channel") .append_child_value("label", TCHAR_TO_UTF8(*(ch.Label))) .append_child_value("unit", TCHAR_TO_UTF8(*(ch.Unit))); } //TODO: Check to see if the stream already exists. my_outlet = new lsl::stream_outlet(data_info); } void ULSLOutletComponent::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (my_outlet != nullptr) { delete my_outlet; my_outlet = nullptr; } Super::EndPlay(EndPlayReason); } //push_sample functions void ULSLOutletComponent::PushSampleFloat(TArray<float> data) { my_outlet->push_sample(data.GetData()); } /* void ULSLOutletComponent::PushSampleDouble(TArray<double> data) { my_outlet->push_sample(data.GetData()); } */ void ULSLOutletComponent::PushSampleLong(TArray<int32> data) { my_outlet->push_sample(data.GetData()); } /* void ULSLOutletComponent::PushSampleInt(TArray<int16> data) { my_outlet->push_sample(data.GetData()); } */ /* void ULSLOutletComponent::PushSampleShort(TArray<int16> data) { my_outlet->push_sample(data.GetData()); } */ void ULSLOutletComponent::PushSampleString(TArray<FString> data) { std::vector<std::string> strVec; int32 b; for(b=0; b < data.Num(); b++) { strVec.push_back(TCHAR_TO_UTF8(*data[b])); } my_outlet->push_sample(strVec); } /* void ULSLOutletComponent::PushSampleChar(TArray<char> data) { lsl_push_sample_ctp(lsl_myoutlet,const_cast<char*>(data),0.0,true); } */
26.603774
203
0.724823
brifsttar
902ec8b78de2dbf6959b99b085cec39bf3b5a3a8
2,510
tcc
C++
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
95
2015-05-14T15:21:44.000Z
2022-03-17T08:02:08.000Z
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
4
2020-06-25T14:59:49.000Z
2022-02-16T12:45:00.000Z
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
40
2015-09-14T02:43:43.000Z
2021-12-26T11:43:36.000Z
#ifndef ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC #define ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC 1 #include <ulmblas/level3/ukernel/ugemm.h> #include <ulmblas/level3/mkernel/mtrlsm.h> #include <ulmblas/level3/ukernel/utrlsm.h> namespace ulmBLAS { template <typename IndexType, typename T, typename TB> void mtrlsm(IndexType mc, IndexType nc, const T &alpha, const T *A_, T *B_, TB *B, IndexType incRowB, IndexType incColB) { const IndexType MR = BlockSizeUGemm<T>::MR; const IndexType NR = BlockSizeUGemm<T>::NR; const IndexType mp = (mc+MR-1) / MR; const IndexType np = (nc+NR-1) / NR; const IndexType mr_ = mc % MR; const IndexType nr_ = nc % NR; IndexType mr, nr; IndexType kc; const T *nextA; const T *nextB; for (IndexType j=0; j<np; ++j) { nr = (j!=np-1 || nr_==0) ? NR : nr_; nextB = &B_[j*mc*NR]; IndexType ia = 0; for (IndexType i=0; i<mp; ++i) { mr = (i!=mp-1 || mr_==0) ? MR : mr_; kc = std::min(i*MR, mc-mr); nextA = &A_[(ia+i+1)*MR*MR]; if (i==mp-1) { nextA = A_; nextB = &B_[(j+1)*mc*NR]; if (j==np-1) { nextB = B_; } } if (mr==MR && nr==NR) { ugemm(kc, T(-1), &A_[ia*MR*MR], &B_[j*mc*NR], alpha, &B_[(j*mc+kc)*NR], NR, IndexType(1), nextA, nextB); utrlsm(&A_[(ia*MR+kc)*MR], &B_[(j*mc+kc)*NR], &B_[(j*mc+kc)*NR], NR, IndexType(1)); } else { // Call buffered micro kernels ugemm(mr, nr, kc, T(-1), &A_[ia*MR*MR], &B_[j*mc*NR], alpha, &B_[(j*mc+kc)*NR], NR, IndexType(1), nextA, nextB); utrlsm(mr, nr, &A_[(ia*MR+kc)*MR], &B_[(j*mc+kc)*NR], &B_[(j*mc+kc)*NR], NR, IndexType(1)); } ia += i+1; } } for (IndexType j=0; j<np; ++j) { nr = (j!=np-1 || nr_==0) ? NR : nr_; gecopy(mc, nr, false, &B_[j*mc*NR], NR, IndexType(1), &B[j*NR*incColB], incRowB, incColB); } } } // namespace ulmBLAS #endif // ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC
26.989247
61
0.436653
sneha0401
90322515c4e788b9ffda2393041910b55f07f5a3
3,829
hpp
C++
CSGOSimple/IGameTypes.hpp
YMY1666527646/CustomHooks-csgo
c79cb831dbcab044969abf556b5bfe6fab5b187c
[ "MIT" ]
7
2022-02-08T18:19:07.000Z
2022-03-25T22:17:55.000Z
CSGOSimple/IGameTypes.hpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
null
null
null
CSGOSimple/IGameTypes.hpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
5
2022-02-04T09:29:11.000Z
2022-03-21T15:09:13.000Z
#pragma once class IGameTypes { public: virtual ~IGameTypes() {} virtual bool Initialize(bool force) = 0; virtual bool IsInitialized() const = 0; virtual bool SetGameTypeAndMode(const char* gameType, const char* gameMode) = 0; virtual bool GetGameTypeAndModeFromAlias(const char* alias, int& gameType, int& gameMode) = 0; virtual bool SetGameTypeAndMode(int gameType, int gameMode) = 0; virtual void SetAndParseExtendedServerInfo(void* pExtendedServerInfo) = 0; virtual bool CheckShouldSetDefaultGameModeAndType(const char* mapName) = 0; virtual int GetCurrentGameType() const = 0; virtual int GetCurrentGameMode() const = 0; virtual const char* GetCurrentMapName() = 0; virtual const char* GetCurrentGameTypeNameID() = 0; virtual const char* GetCurrentGameModeNameID() = 0; virtual bool ApplyConvarsForCurrentMode(bool isMultiplayer) = 0; virtual void DisplayConvarsForCurrentMode() = 0; virtual const void* GetWeaponProgressionForCurrentModeCT() = 0; virtual const void* GetWeaponProgressionForCurrentModeT() = 0; virtual int GetNoResetVoteThresholdForCurrentModeCT() = 0; virtual int GetNoResetVoteThresholdForCurrentModeT() = 0; virtual const char* GetGameTypeFromInt(int gameType) = 0; virtual const char* GetGameModeFromInt(int gameType, int gameMode) = 0; virtual bool GetGameModeAndTypeIntsFromStrings(const char* szGameType, const char* szGameMode, int& iOutGameType, int& iOutGameMode) = 0; virtual bool GetGameModeAndTypeNameIdsFromStrings(const char* szGameType, const char* szGameMode, const char*& szOutGameTypeNameId, const char*& szOutGameModeNameId) = 0; virtual void CreateOrUpdateWorkshopMapGroup(const char* mapGroup, const void* mapList) = 0; virtual bool IsWorkshopMapGroup(const char* mapGroup) = 0; virtual const char* GetRandomMapGroup(const char* gameType, const char* gameMode) = 0; virtual const char* GetFirstMap(const char* mapGroup) = 0; virtual const char* GetRandomMap(const char* mapGroup) = 0; virtual const char* GetNextMap(const char* mapGroup, const char* mapName) = 0; virtual int GetMaxPlayersForTypeAndMode(int iType, int iMode) = 0; virtual bool IsValidMapGroupName(const char* mapGroup) = 0; virtual bool IsValidMapInMapGroup(const char* mapGroup, const char* mapName) = 0; virtual bool IsValidMapGroupForTypeAndMode(const char* mapGroup, const char* gameType, const char* gameMode) = 0; virtual bool ApplyConvarsForMap(const char* mapName, bool isMultiplayer) = 0; virtual bool GetMapInfo(const char* mapName, unsigned int& richPresence) = 0; virtual const void* GetTModelsForMap(const char* mapName) = 0; virtual const void* GetCTModelsForMap(const char* mapName) = 0; virtual const void* GetHostageModelsForMap(const char* mapName) = 0; virtual int GetDefaultGameTypeForMap(const char* mapName) = 0; virtual int GetDefaultGameModeForMap(const char* mapName) = 0; virtual const char* GetTViewModelArmsForMap(const char* mapName) = 0; virtual const char* GetCTViewModelArmsForMap(const char* mapName) = 0; virtual const char* GetRequiredAttrForMap(const char* mapName) = 0; virtual int GetRequiredAttrValueForMap(const char* mapName) = 0; virtual const char* GetRequiredAttrRewardForMap(const char* mapName) = 0; virtual int GetRewardDropListForMap(const char* mapName) = 0; virtual const void* GetMapGroupMapList(const char* mapGroup) = 0; virtual bool GetRunMapWithDefaultGametype() = 0; virtual void SetRunMapWithDefaultGameType(bool bUseDefault) = 0; virtual bool GetLoadingScreenDataIsCorrect() = 0; virtual void SetLoadingScreenDataIsCorrect(bool bIsCorrect) = 0; virtual bool SetCustomBotDifficulty(int botDiff) = 0; virtual int GetCustomBotDifficulty() = 0; virtual int GetCurrentServerNumSlots() = 0; virtual int GetCurrentServerSettingInt(const char* settingName, int defaultValue) = 0; };
42.076923
171
0.785061
YMY1666527646
9036671551e843ee603b0533bcce09b44366a71f
7,020
cpp
C++
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2014-2018 Esteban Tovagliari, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // Interface header. #include "oslshadergroupexec.h" // appleseed.renderer headers. #include "renderer/kernel/shading/closures.h" #include "renderer/kernel/shading/oslshadingsystem.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/modeling/bsdf/bsdf.h" #include "renderer/modeling/shadergroup/shadergroup.h" // Standard headers. #include <cassert> using namespace foundation; namespace renderer { // // OSLShaderGroupExec class implementation. // OSLShaderGroupExec::OSLShaderGroupExec(OSLShadingSystem& shading_system, Arena& arena) : m_osl_shading_system(shading_system) , m_arena(arena) , m_osl_thread_info(shading_system.create_thread_info()) , m_osl_shading_context(shading_system.get_context(m_osl_thread_info)) { } OSLShaderGroupExec::~OSLShaderGroupExec() { if (m_osl_shading_context) m_osl_shading_system.release_context(m_osl_shading_context); if (m_osl_thread_info) m_osl_shading_system.destroy_thread_info(m_osl_thread_info); } void OSLShaderGroupExec::execute_shading( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, shading_point.get_ray().m_flags); } void OSLShaderGroupExec::execute_subsurface( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, VisibilityFlags::SubsurfaceRay); } void OSLShaderGroupExec::execute_transparency( const ShaderGroup& shader_group, const ShadingPoint& shading_point, Alpha& alpha, float* holdout) const { do_execute( shader_group, shading_point, VisibilityFlags::TransparencyRay); process_transparency_tree(shading_point.get_osl_shader_globals().Ci, alpha); if (holdout) *holdout = process_holdout_tree(shading_point.get_osl_shader_globals().Ci); } void OSLShaderGroupExec::execute_shadow( const ShaderGroup& shader_group, const ShadingPoint& shading_point, Alpha& alpha) const { do_execute( shader_group, shading_point, VisibilityFlags::ShadowRay); process_transparency_tree(shading_point.get_osl_shader_globals().Ci, alpha); } void OSLShaderGroupExec::execute_emission( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, VisibilityFlags::LightRay); } void OSLShaderGroupExec::execute_bump( const ShaderGroup& shader_group, const ShadingPoint& shading_point, const Vector2f& s) const { // Choose between BSSRDF and BSDF. if (shader_group.has_subsurface() && s[0] < 0.5f) { do_execute( shader_group, shading_point, VisibilityFlags::SubsurfaceRay); CompositeSubsurfaceClosure c( Basis3f(shading_point.get_shading_basis()), shading_point.get_osl_shader_globals().Ci, m_arena); // Pick a shading basis from one of the BSSRDF closures. if (c.get_closure_count() > 0) { const size_t index = c.choose_closure(s[1]); shading_point.set_shading_basis( Basis3d(c.get_closure_shading_basis(index))); } } else { do_execute( shader_group, shading_point, VisibilityFlags::CameraRay); choose_bsdf_closure_shading_basis(shading_point, s); } } Color3f OSLShaderGroupExec::execute_background( const ShaderGroup& shader_group, const Vector3f& outgoing) const { assert(m_osl_shading_context); assert(m_osl_thread_info); OSL::ShaderGlobals sg; memset(&sg, 0, sizeof(OSL::ShaderGlobals)); sg.I = outgoing; sg.renderer = m_osl_shading_system.renderer(); sg.raytype = VisibilityFlags::CameraRay; m_osl_shading_system.execute( m_osl_shading_context, *reinterpret_cast<OSL::ShaderGroup*>(shader_group.osl_shader_group()), sg); return process_background_tree(sg.Ci); } void OSLShaderGroupExec::do_execute( const ShaderGroup& shader_group, const ShadingPoint& shading_point, const VisibilityFlags::Type ray_flags) const { assert(m_osl_shading_context); assert(m_osl_thread_info); shading_point.initialize_osl_shader_globals( shader_group, ray_flags, m_osl_shading_system.renderer()); m_osl_shading_system.execute( m_osl_shading_context, *reinterpret_cast<OSL::ShaderGroup*>(shader_group.osl_shader_group()), shading_point.get_osl_shader_globals()); } void OSLShaderGroupExec::choose_bsdf_closure_shading_basis( const ShadingPoint& shading_point, const Vector2f& s) const { CompositeSurfaceClosure c( Basis3f(shading_point.get_shading_basis()), shading_point.get_osl_shader_globals().Ci, m_arena); float pdfs[CompositeSurfaceClosure::MaxClosureEntries]; const size_t num_closures = c.compute_pdfs(ScatteringMode::All, pdfs); if (num_closures == 0) return; const size_t index = c.choose_closure(s[1], num_closures, pdfs); shading_point.set_shading_basis( Basis3d(c.get_closure_shading_basis(index))); } } // namespace renderer
31.061947
86
0.687037
dcoeurjo
9037b221b6c9246a2dff9a8cb96c035ec5390146
6,125
cpp
C++
src/hvr_avl_tree.cpp
agrippa/hoover
f8adcad8d125f68c66b875600c27e4c5caf147e5
[ "BSD-3-Clause" ]
4
2018-05-22T02:01:26.000Z
2020-10-13T04:55:30.000Z
src/hvr_avl_tree.cpp
agrippa/hoover
f8adcad8d125f68c66b875600c27e4c5caf147e5
[ "BSD-3-Clause" ]
1
2018-08-16T22:36:03.000Z
2018-08-16T22:36:03.000Z
src/hvr_avl_tree.cpp
agrippa/hoover
f8adcad8d125f68c66b875600c27e4c5caf147e5
[ "BSD-3-Clause" ]
7
2018-05-21T23:37:38.000Z
2021-03-18T01:45:56.000Z
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <string.h> #include "hvr_avl_tree.h" struct hvr_avl_node dummy = { {&dummy, &dummy}, 0, 0, 0 }, *nnil = &dummy; static struct hvr_avl_node *new_node(uint32_t key, uint64_t value, hvr_avl_node_allocator *tracker) { struct hvr_avl_node *n = hvr_avl_node_allocator_alloc(tracker); n->kid[0] = nnil; n->kid[1] = nnil; n->value = value; n->key = key; n->height = 1; return n; } static inline int16_t max(int16_t a, int16_t b) { return a > b ? a : b; } static inline void set_height(struct hvr_avl_node *n) { n->height = 1 + max(n->kid[0]->height, n->kid[1]->height); } static inline int balance(struct hvr_avl_node *n) { return n->kid[0]->height - n->kid[1]->height; } // rotate a subtree according to dir; if new root is nil, old root is freed static struct hvr_avl_node * rotate(struct hvr_avl_node **rootp, int dir, hvr_avl_node_allocator *tracker) { struct hvr_avl_node *old_r = *rootp, *new_r = old_r->kid[dir]; if (nnil == (*rootp = new_r)) hvr_avl_node_allocator_free(old_r, tracker); else { old_r->kid[dir] = new_r->kid[!dir]; set_height(old_r); new_r->kid[!dir] = old_r; } return new_r; } static void adjust_balance(struct hvr_avl_node **rootp, hvr_avl_node_allocator *tracker) { struct hvr_avl_node *root = *rootp; int b = balance(root)/2; if (b) { int dir = (1 - b)/2; if (balance(root->kid[dir]) == -b) { rotate(&root->kid[dir], !dir, tracker); } root = rotate(rootp, dir, tracker); } if (root != nnil) set_height(root); } // find the node that contains value as payload; or returns 0 static struct hvr_avl_node *query(struct hvr_avl_node *root, uint32_t key) { return root == nnil ? 0 : root->key == key ? root : query(root->kid[key > root->key], key); } int hvr_avl_insert(struct hvr_avl_node **rootp, uint32_t key, uint64_t value, hvr_avl_node_allocator *tracker) { int result; struct hvr_avl_node *root = *rootp; if (root == nnil) { *rootp = new_node(key, value, tracker); result = 1; } else if (key != root->key) { // don't allow dup keys result = hvr_avl_insert(&root->kid[key > root->key], key, value, tracker); adjust_balance(rootp, tracker); } else { // Duplicate key result = 0; } return result; } int hvr_avl_delete(struct hvr_avl_node **rootp, uint32_t key, hvr_avl_node_allocator *tracker) { struct hvr_avl_node *root = *rootp; if (root == nnil) return 0; // not found // if this is the node we want, rotate until off the tree if (root->key == key) if (nnil == (root = rotate(rootp, balance(root) < 0, tracker))) return 1; int success = hvr_avl_delete(&root->kid[key > root->key], key, tracker); adjust_balance(rootp, tracker); return success; } void hvr_avl_delete_all(struct hvr_avl_node *root, hvr_avl_node_allocator *tracker) { if (root == nnil) return; hvr_avl_delete_all(root->kid[0], tracker); hvr_avl_delete_all(root->kid[1], tracker); hvr_avl_node_allocator_free(root, tracker); } static void hvr_avl_serialize_helper(struct hvr_avl_node *root, uint64_t *values, int arr_capacity, int *index) { if (root == nnil) return; assert(*index < arr_capacity); values[*index] = root->value; *index += 1; hvr_avl_serialize_helper(root->kid[0], values, arr_capacity, index); hvr_avl_serialize_helper(root->kid[1], values, arr_capacity, index); } int hvr_avl_serialize(struct hvr_avl_node *root, uint64_t *values, int arr_capacity) { int index = 0; hvr_avl_serialize_helper(root, values, arr_capacity, &index); return index; } struct hvr_avl_node *hvr_avl_find(const struct hvr_avl_node *root, const uint32_t key) { while (root != nnil && root->key != key) { root = hvr_avl_find(root->kid[key > root->key], key); } return (struct hvr_avl_node *)root; /* if (root == nnil) { return nnil; } else if (root->key == key) { return (struct hvr_avl_node *)root; } else { return hvr_avl_find(root->kid[key > root->key], key); } */ } static void hvr_avl_size_helper(struct hvr_avl_node *curr, unsigned *counter) { if (curr != nnil) { *counter += 1; hvr_avl_size_helper(curr->kid[0], counter); hvr_avl_size_helper(curr->kid[1], counter); } } unsigned hvr_avl_size(struct hvr_avl_node *root) { unsigned counter = 0; hvr_avl_size_helper(root, &counter); return counter; } void hvr_avl_node_allocator_init(hvr_avl_node_allocator *allocator, size_t pool_size, const char *envvar) { struct hvr_avl_node *pool = (struct hvr_avl_node *)malloc_helper( pool_size * sizeof(*pool)); assert(pool); allocator->head = pool; for (size_t i = 0; i < pool_size - 1; i++) { pool[i].kid[0] = &pool[i + 1]; } pool[pool_size - 1].kid[0] = NULL; allocator->mem = pool; allocator->pool_size = pool_size; allocator->n_reserved = 0; allocator->envvar = (char *)malloc(strlen(envvar) + 1); memcpy(allocator->envvar, envvar, strlen(envvar) + 1); } struct hvr_avl_node *hvr_avl_node_allocator_alloc( hvr_avl_node_allocator *allocator) { struct hvr_avl_node *result = allocator->head; if (!result) { fprintf(stderr, "ERROR failed allocating AVL node. Increase %s " "(%lu).\n", allocator->envvar, allocator->pool_size); abort(); } allocator->head = result->kid[0]; allocator->n_reserved += 1; return result; } void hvr_avl_node_allocator_free(struct hvr_avl_node *node, hvr_avl_node_allocator *allocator) { node->kid[0] = allocator->head; allocator->head = node; allocator->n_reserved -= 1; } void hvr_avl_node_allocator_bytes_usage(hvr_avl_node_allocator *allocator, size_t *out_allocated, size_t *out_used) { *out_used = allocator->n_reserved * sizeof(struct hvr_avl_node); *out_allocated = allocator->pool_size * sizeof(struct hvr_avl_node); }
28.755869
79
0.651592
agrippa
9037c2602116afcb72a7d62db2d00c3a1ba311d7
2,677
cc
C++
ui/aura/window_port_local.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
ui/aura/window_port_local.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
ui/aura/window_port_local.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.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 "ui/aura/window_port_local.h" #include "ui/aura/client/cursor_client.h" #include "ui/aura/env.h" #include "ui/aura/window.h" #include "ui/aura/window_delegate.h" #include "ui/display/display.h" #include "ui/display/screen.h" namespace aura { namespace { class ScopedCursorHider { public: explicit ScopedCursorHider(Window* window) : window_(window), hid_cursor_(false) { if (!window_->IsRootWindow()) return; const bool cursor_is_in_bounds = window_->GetBoundsInScreen().Contains( Env::GetInstance()->last_mouse_location()); client::CursorClient* cursor_client = client::GetCursorClient(window_); if (cursor_is_in_bounds && cursor_client && cursor_client->IsCursorVisible()) { cursor_client->HideCursor(); hid_cursor_ = true; } } ~ScopedCursorHider() { if (!window_->IsRootWindow()) return; // Update the device scale factor of the cursor client only when the last // mouse location is on this root window. if (hid_cursor_) { client::CursorClient* cursor_client = client::GetCursorClient(window_); if (cursor_client) { const display::Display& display = display::Screen::GetScreen()->GetDisplayNearestWindow(window_); cursor_client->SetDisplay(display); cursor_client->ShowCursor(); } } } private: Window* window_; bool hid_cursor_; DISALLOW_COPY_AND_ASSIGN(ScopedCursorHider); }; } // namespace WindowPortLocal::WindowPortLocal(Window* window) : window_(window) {} WindowPortLocal::~WindowPortLocal() {} void WindowPortLocal::OnPreInit(Window* window) {} void WindowPortLocal::OnDeviceScaleFactorChanged(float device_scale_factor) { ScopedCursorHider hider(window_); if (window_->delegate()) window_->delegate()->OnDeviceScaleFactorChanged(device_scale_factor); } void WindowPortLocal::OnWillAddChild(Window* child) {} void WindowPortLocal::OnWillRemoveChild(Window* child) {} void WindowPortLocal::OnWillMoveChild(size_t current_index, size_t dest_index) { } void WindowPortLocal::OnVisibilityChanged(bool visible) {} void WindowPortLocal::OnDidChangeBounds(const gfx::Rect& old_bounds, const gfx::Rect& new_bounds) {} std::unique_ptr<WindowPortPropertyData> WindowPortLocal::OnWillChangeProperty( const void* key) { return nullptr; } void WindowPortLocal::OnPropertyChanged( const void* key, std::unique_ptr<WindowPortPropertyData> data) {} } // namespace aura
29.097826
80
0.7161
google-ar
9037d20577c7e61345a3e8273e147d6fae44841b
847
cc
C++
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file SPn/spn/Fixed_Source_Solver.pt.cc * \author Thomas M. Evans * \date Fri Feb 21 14:41:20 2014 * \brief Fixed_Source_Solver explicit instantiation. * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "Fixed_Source_Solver.t.hh" #include "solvers/LinAlgTypedefs.hh" namespace profugus { template class Fixed_Source_Solver<EpetraTypes>; template class Fixed_Source_Solver<TpetraTypes>; } // end namespace profugus //---------------------------------------------------------------------------// // end of Fixed_Source_Solver.pt.cc //---------------------------------------------------------------------------//
33.88
79
0.455726
GCZhang
903b27b7c3f2be22668ea126222a03a54ddcedb3
1,920
cpp
C++
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
#include "Sprite.h" #include "ResourceManager.h" Sprite::Sprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as<aie::Texture>()->getWidth(); m_sheetHeight = m_texture->as<aie::Texture>()->getHeight(); m_spriteWidth = m_texture->as<aie::Texture>()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as<aie::Texture>()->getHeight() / m_rowCount; } void Sprite::changeSprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as<aie::Texture>()->getWidth(); m_sheetHeight = m_texture->as<aie::Texture>()->getHeight(); m_spriteWidth = m_texture->as<aie::Texture>()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as<aie::Texture>()->getHeight() / m_rowCount; } void Sprite::updateUVRect(aie::Renderer2D* renderer) { //get size of single frame as percentage of total spritesheet float width = 1.0f / m_columnCount; float height = 1.0f / m_rowCount; //initialise renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); //play animation if (m_timer > m_animSpeed) { ++m_currentCol; if (m_currentCol == m_columnCount) { ++m_currentRow; m_currentCol = 0; } if (m_currentRow == m_rowCount) m_currentRow = 0; renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); m_timer = 0; } } void Sprite::draw(GameObject* gameObject, aie::Renderer2D* renderer) { updateUVRect(renderer); renderer->drawSpriteTransformed3x3(m_texture->as<aie::Texture>(), gameObject->getGlobalTransformFloat(), m_spriteWidth, m_spriteHeight); renderer->setUVRect(1, 1, 1, 1); //reset UV }
28.656716
82
0.732292
PotatoesBasket
903f230540dc19a1d0e8ebdb1d733b4d165c4bed
1,457
cpp
C++
NaoTHSoccer/Source/Cognition/Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
15
2015-01-12T10:46:29.000Z
2022-03-28T05:13:14.000Z
NaoTHSoccer/Source/Cognition/Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
2
2019-01-20T21:07:50.000Z
2020-01-22T14:00:28.000Z
NaoTHSoccer/Source/Cognition/Modules/Infrastructure/TeamCommunicator/TeamCommReceiveEmulator.cpp
tarsoly/NaoTH
dcd2b67ef6bf9953c81d3e1b26e543b5922b7d52
[ "ECL-2.0", "Apache-2.0" ]
5
2018-02-07T18:18:10.000Z
2019-10-15T17:01:41.000Z
/** * @file TeamCommReceiveEmulator.cpp */ #include "TeamCommReceiveEmulator.h" unsigned int robotNumber = 999; //An arbitrary robot number that does not stand in conflict with real robots' messages TeamCommReceiveEmulator::TeamCommReceiveEmulator(): nextMessageTime(getFrameInfo().getTime()) {} TeamCommReceiveEmulator::~TeamCommReceiveEmulator() {} void TeamCommReceiveEmulator::execute() { //If enough time has passed, place another message in the inbox if (nextMessageTime <= getFrameInfo().getTime()) { TeamMessageData messageData; messageData.playerNumber = robotNumber; messageData.frameInfo = getFrameInfo(); getTeamMessage().data[messageData.playerNumber] = messageData; //Generate the frame number, at which we are going to receive the next message if (parameters.normalDistribution) { getFrameInfo().getFrameNumber(); nextMessageTime = getFrameInfo().getTime() + ((unsigned int) fabs(floor( Math::sampleNormalDistribution(parameters.standardDeviation) + parameters.mean + 0.5))); } if (parameters.uniformDistribution) { nextMessageTime = getFrameInfo().getTime() + ((unsigned int) fabs(floor( Math::random(parameters.uniformMin, parameters.uniformMax) + 0.5))); } if (parameters.randomPerturbations) { //TODO: Implement other perturbations in the message intervals } }//endIf }//endExecute void TeamCommReceiveEmulator::reset() { }
29.734694
118
0.724777
tarsoly
9040d3facda72fcc84f533e9ed78e70d9a9b4e93
958
hpp
C++
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
#pragma once #include <UniqueID.hpp> #include <Collections/Dynarray.hpp> #include <ECS/ComponentBase.hpp> #include <Rendering/MeshRenderingComponent.hpp> #include <Rendering/PostprocessSettingsComponent.hpp> #include <Rendering/Lighting/LightSourceComponent.hpp> using namespace Poly; class GameManagerWorldComponent : public ComponentBase { public: SafePtr<Entity> Camera; PostprocessSettingsComponent* PostCmp; SafePtr<Entity> Model; bool IsDrawingDebugMeshes = true; Dynarray<SafePtr<Entity>> GameEntities; ParticleComponent* particleDefault; ParticleComponent* particleAmbient; ParticleComponent* particleAmbientWind; ParticleComponent* particleLocalSpace; ParticleComponent* particleWorldSpace; ParticleComponent* particleHeart; ParticleComponent* particleHeartImpact0; ParticleComponent* particleHeartImpact1; ParticleComponent* particleHeartImpact2; Dynarray<Vector> LightsStartPositions; Dynarray<Entity*> PointLightEntities; };
28.176471
54
0.836117
filu005
9044b364bb9b18c0c19e1e27c7ebbfa22acdec0e
43,741
cpp
C++
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Android.com.fuse.ExperimentalHttp.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Android.com.fuse.ExperimentalHttp.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/jni/Android.com.fuse.ExperimentalHttp.g.cpp
marferfer/SpinOff-LoL
a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8
[ "Apache-2.0" ]
null
null
null
// This file was generated based on '(multiple files)'. // WARNING: Changes might be lost if you edit this file directly. #include <Android.Base.AndroidB-e9b6d531.h> #include <Android.Base.JNI.h> #include <Android.Base.Primitiv-2b9696be.h> #include <Android.Base.Primitiv-45253430.h> #include <Android.Base.Primitiv-e437692f.h> #include <Android.Base.Wrappers.JWrapper.h> #include <Android.com.fuse.Expe-9d584358.h> #include <Uno.Bool.h> #include <Uno.Exception.h> #include <Uno.Int.h> #include <Uno.Long.h> #include <Uno.Type.h> //~Callbacks forHttpRequest //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnDataReceived(Android.Base.Wrappers.IJWrapper,int):IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnDataReceived44285,jlong ujPtr, jobject arg0, jint arg1, jlong arg2, jlong arg3) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JARG_TO_UNO(arg2,uObject*,((::g::Android::Base::Wrappers::JWrapper*)::g::Android::Base::Wrappers::JWrapper::New2(arg0, (uType*)::g::Android::Base::Wrappers::JWrapper_typeof(), false, false, true))); JTRY uPtr->OnDataReceived(tmparg2, ((int32_t)arg1)); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnAborted():IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnAborted44286,jlong ujPtr) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JTRY uPtr->OnAborted(); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnError(Android.Base.Wrappers.IJWrapper):IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnError44287,jlong ujPtr, jobject arg0, jlong arg1) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JARG_TO_UNO(arg1,uObject*,((::g::Android::Base::Wrappers::JWrapper*)::g::Android::Base::Wrappers::JWrapper::New2(arg0, (uType*)::g::Android::Base::Wrappers::JWrapper_typeof(), false, false, true))); JTRY uPtr->OnError(tmparg1); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnTimeout():IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnTimeout44288,jlong ujPtr) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JTRY uPtr->OnTimeout(); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnDone():IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnDone44289,jlong ujPtr) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JTRY uPtr->OnDone(); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnHeadersReceived():IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnHeadersReceived44290,jlong ujPtr) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JTRY uPtr->OnHeadersReceived(); JCATCH } //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnProgress(int,int,bool):IsStripped} JNFUN(void,Android_com_fuse_ExperimentalHttp_HttpRequest__OnProgress44291,jlong ujPtr, jint arg0, jint arg1, jboolean arg2, jlong arg3, jlong arg4, jlong arg5) { INITCALLBACK(uPtr,::g::Android::com::fuse::ExperimentalHttp::HttpRequest*); JTRY uPtr->OnProgress(((int32_t)arg0), ((int32_t)arg1), ((bool)arg2)); JCATCH } //#endi namespace g{ namespace Android{ namespace com{ namespace fuse{ namespace ExperimentalHttp{ // C:\Users\JuanJose\AppData\Local\Fusetools\Packages\Uno.Net.Http\1.9.0\Implementation\Android\ExperimentalHttp\HttpRequest.uno // ----------------------------------------------------------------------------------------------------------------------------- // public abstract extern class HttpRequest :7 // { static void HttpRequest_build(uType* type) { type->SetInterfaces( ::g::Android::Base::Wrappers::IJWrapper_typeof(), offsetof(HttpRequest_type, interface0), ::g::Uno::IDisposable_typeof(), offsetof(HttpRequest_type, interface1)); type->SetFields(4, ::g::Android::Base::Primitives::ujclass_typeof(), (uintptr_t)&HttpRequest::_javaClass1_, uFieldFlagsStatic, ::g::Android::Base::Primitives::ujclass_typeof(), (uintptr_t)&HttpRequest::_javaProxyClass1_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::InstallCache_44279_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::HttpRequest_44284_ID_c_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::HttpRequest_44284_ID_c_prox_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SetResponseType_44292_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SetHeader_44293_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SetTimeout_44294_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SetCaching_44295_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::GetResponseString_44297_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SendAsync_44299_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SendAsyncBuf_44300_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::SendAsyncStr_44301_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::Abort_44305_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::GetResponseStatus_44306_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::GetResponseHeader_44307_ID_, uFieldFlagsStatic, ::g::Android::Base::Primitives::jmethodID_typeof(), (uintptr_t)&HttpRequest::GetResponseHeaders_44308_ID_, uFieldFlagsStatic); type->Reflection.SetFunctions(37, new uFunction("_Init", NULL, (void*)HttpRequest___Init1_fn, 0, true, uVoid_typeof(), 0), new uFunction("_InitProxy", NULL, (void*)HttpRequest___InitProxy1_fn, 0, true, uVoid_typeof(), 0), new uFunction("_IsThisType", NULL, (void*)HttpRequest___IsThisType1_fn, 0, true, ::g::Uno::Bool_typeof(), 1, ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("Abort", NULL, (void*)HttpRequest__Abort_fn, 0, false, uVoid_typeof(), 0), new uFunction("Abort_IMPL_44305", NULL, (void*)HttpRequest__Abort_IMPL_44305_fn, 0, true, uVoid_typeof(), 2, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof()), new uFunction("GetResponseHeader", NULL, (void*)HttpRequest__GetResponseHeader_fn, 0, false, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 1, ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("GetResponseHeader_IMPL_44307", NULL, (void*)HttpRequest__GetResponseHeader_IMPL_44307_fn, 0, true, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("GetResponseHeaders", NULL, (void*)HttpRequest__GetResponseHeaders_fn, 0, false, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 0), new uFunction("GetResponseHeaders_IMPL_44308", NULL, (void*)HttpRequest__GetResponseHeaders_IMPL_44308_fn, 0, true, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 2, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof()), new uFunction("GetResponseStatus", NULL, (void*)HttpRequest__GetResponseStatus_fn, 0, false, ::g::Uno::Int_typeof(), 0), new uFunction("GetResponseStatus_IMPL_44306", NULL, (void*)HttpRequest__GetResponseStatus_IMPL_44306_fn, 0, true, ::g::Uno::Int_typeof(), 2, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof()), new uFunction("GetResponseString", NULL, (void*)HttpRequest__GetResponseString_fn, 0, false, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 0), new uFunction("GetResponseString_IMPL_44297", NULL, (void*)HttpRequest__GetResponseString_IMPL_44297_fn, 0, true, ::g::Android::Base::Wrappers::IJWrapper_typeof(), 2, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof()), new uFunction("HttpRequest_IMPL_44284", NULL, (void*)HttpRequest__HttpRequest_IMPL_44284_fn, 0, true, ::g::Android::Base::Primitives::ujobject_typeof(), 4, ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("InstallCache", NULL, (void*)HttpRequest__InstallCache_fn, 0, true, ::g::Uno::Bool_typeof(), 2, ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Uno::Long_typeof()), new uFunction("InstallCache_IMPL_44279", NULL, (void*)HttpRequest__InstallCache_IMPL_44279_fn, 0, true, ::g::Uno::Bool_typeof(), 2, ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Uno::Long_typeof()), new uFunction("OnAborted", NULL, NULL, offsetof(HttpRequest_type, fp_OnAborted), false, uVoid_typeof(), 0), new uFunction("OnDataReceived", NULL, NULL, offsetof(HttpRequest_type, fp_OnDataReceived), false, uVoid_typeof(), 2, ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Uno::Int_typeof()), new uFunction("OnDone", NULL, NULL, offsetof(HttpRequest_type, fp_OnDone), false, uVoid_typeof(), 0), new uFunction("OnError", NULL, NULL, offsetof(HttpRequest_type, fp_OnError), false, uVoid_typeof(), 1, ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("OnHeadersReceived", NULL, NULL, offsetof(HttpRequest_type, fp_OnHeadersReceived), false, uVoid_typeof(), 0), new uFunction("OnProgress", NULL, NULL, offsetof(HttpRequest_type, fp_OnProgress), false, uVoid_typeof(), 3, ::g::Uno::Int_typeof(), ::g::Uno::Int_typeof(), ::g::Uno::Bool_typeof()), new uFunction("OnTimeout", NULL, NULL, offsetof(HttpRequest_type, fp_OnTimeout), false, uVoid_typeof(), 0), new uFunction("SendAsync", NULL, (void*)HttpRequest__SendAsync_fn, 0, false, uVoid_typeof(), 0), new uFunction("SendAsync_IMPL_44299", NULL, (void*)HttpRequest__SendAsync_IMPL_44299_fn, 0, true, uVoid_typeof(), 2, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof()), new uFunction("SendAsyncBuf", NULL, (void*)HttpRequest__SendAsyncBuf_fn, 0, false, uVoid_typeof(), 1, ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SendAsyncBuf_IMPL_44300", NULL, (void*)HttpRequest__SendAsyncBuf_IMPL_44300_fn, 0, true, uVoid_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SendAsyncStr", NULL, (void*)HttpRequest__SendAsyncStr_fn, 0, false, uVoid_typeof(), 1, ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SendAsyncStr_IMPL_44301", NULL, (void*)HttpRequest__SendAsyncStr_IMPL_44301_fn, 0, true, uVoid_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SetCaching", NULL, (void*)HttpRequest__SetCaching_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Bool_typeof()), new uFunction("SetCaching_IMPL_44295", NULL, (void*)HttpRequest__SetCaching_IMPL_44295_fn, 0, true, uVoid_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Bool_typeof()), new uFunction("SetHeader", NULL, (void*)HttpRequest__SetHeader_fn, 0, false, uVoid_typeof(), 2, ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SetHeader_IMPL_44293", NULL, (void*)HttpRequest__SetHeader_IMPL_44293_fn, 0, true, uVoid_typeof(), 4, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof(), ::g::Android::Base::Wrappers::IJWrapper_typeof()), new uFunction("SetResponseType", NULL, (void*)HttpRequest__SetResponseType_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Int_typeof()), new uFunction("SetResponseType_IMPL_44292", NULL, (void*)HttpRequest__SetResponseType_IMPL_44292_fn, 0, true, uVoid_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Int_typeof()), new uFunction("SetTimeout", NULL, (void*)HttpRequest__SetTimeout_fn, 0, false, uVoid_typeof(), 1, ::g::Uno::Int_typeof()), new uFunction("SetTimeout_IMPL_44294", NULL, (void*)HttpRequest__SetTimeout_IMPL_44294_fn, 0, true, uVoid_typeof(), 3, ::g::Uno::Bool_typeof(), ::g::Android::Base::Primitives::ujobject_typeof(), ::g::Uno::Int_typeof())); } HttpRequest_type* HttpRequest_typeof() { static uSStrong<HttpRequest_type*> type; if (type != NULL) return type; uTypeOptions options; options.BaseDefinition = ::g::Android::Base::Wrappers::JWrapper_typeof(); options.FieldCount = 21; options.InterfaceCount = 2; options.ObjectSize = sizeof(HttpRequest); options.TypeSize = sizeof(HttpRequest_type); type = (HttpRequest_type*)uClassType::New("Android.com.fuse.ExperimentalHttp.HttpRequest", options); type->fp_build_ = HttpRequest_build; type->interface1.fp_Dispose = (void(*)(uObject*))::g::Android::Base::Wrappers::JWrapper__UnoIDisposableDispose_fn; type->interface0.fp__GetJavaObject = (void(*)(uObject*, jobject*))::g::Android::Base::Wrappers::JWrapper___GetJavaObject_fn; type->interface0.fp__IsSubclassed = (void(*)(uObject*, bool*))::g::Android::Base::Wrappers::JWrapper___IsSubclassed_fn; return type; } // protected HttpRequest(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1, Android.Base.Wrappers.IJWrapper arg2) :59 void HttpRequest__ctor_4_fn(HttpRequest* __this, uObject* arg0, uObject* arg1, uObject* arg2) { __this->ctor_4(arg0, arg1, arg2); } // public static extern new void _Init() :17 void HttpRequest___Init1_fn() { HttpRequest::_Init1(); } // public static extern new void _InitProxy() :13 void HttpRequest___InitProxy1_fn() { HttpRequest::_InitProxy1(); } // public static extern new bool _IsThisType(Android.Base.Wrappers.IJWrapper obj) :15 void HttpRequest___IsThisType1_fn(uObject* obj_, bool* __retval) { *__retval = HttpRequest::_IsThisType1(obj_); } // public void Abort() :141 void HttpRequest__Abort_fn(HttpRequest* __this) { __this->Abort(); } // public static extern void Abort_IMPL_44305(bool arg0, Android.Base.Primitives.ujobject arg1) :230 void HttpRequest__Abort_IMPL_44305_fn(bool* arg0_, jobject* arg1_) { HttpRequest::Abort_IMPL_44305(*arg0_, *arg1_); } // public Android.Base.Wrappers.IJWrapper GetResponseHeader(Android.Base.Wrappers.IJWrapper arg0) :151 void HttpRequest__GetResponseHeader_fn(HttpRequest* __this, uObject* arg0, uObject** __retval) { *__retval = __this->GetResponseHeader(arg0); } // public static extern Android.Base.Wrappers.IJWrapper GetResponseHeader_IMPL_44307(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) :236 void HttpRequest__GetResponseHeader_IMPL_44307_fn(bool* arg0_, jobject* arg1_, uObject* arg2_, uObject** __retval) { *__retval = HttpRequest::GetResponseHeader_IMPL_44307(*arg0_, *arg1_, arg2_); } // public Android.Base.Wrappers.IJWrapper GetResponseHeaders() :156 void HttpRequest__GetResponseHeaders_fn(HttpRequest* __this, uObject** __retval) { *__retval = __this->GetResponseHeaders(); } // public static extern Android.Base.Wrappers.IJWrapper GetResponseHeaders_IMPL_44308(bool arg0, Android.Base.Primitives.ujobject arg1) :239 void HttpRequest__GetResponseHeaders_IMPL_44308_fn(bool* arg0_, jobject* arg1_, uObject** __retval) { *__retval = HttpRequest::GetResponseHeaders_IMPL_44308(*arg0_, *arg1_); } // public int GetResponseStatus() :146 void HttpRequest__GetResponseStatus_fn(HttpRequest* __this, int32_t* __retval) { *__retval = __this->GetResponseStatus(); } // public static extern int GetResponseStatus_IMPL_44306(bool arg0, Android.Base.Primitives.ujobject arg1) :233 void HttpRequest__GetResponseStatus_IMPL_44306_fn(bool* arg0_, jobject* arg1_, int32_t* __retval) { *__retval = HttpRequest::GetResponseStatus_IMPL_44306(*arg0_, *arg1_); } // public Android.Base.Wrappers.IJWrapper GetResponseString() :106 void HttpRequest__GetResponseString_fn(HttpRequest* __this, uObject** __retval) { *__retval = __this->GetResponseString(); } // public static extern Android.Base.Wrappers.IJWrapper GetResponseString_IMPL_44297(bool arg0, Android.Base.Primitives.ujobject arg1) :209 void HttpRequest__GetResponseString_IMPL_44297_fn(bool* arg0_, jobject* arg1_, uObject** __retval) { *__retval = HttpRequest::GetResponseString_IMPL_44297(*arg0_, *arg1_); } // public static extern Android.Base.Primitives.ujobject HttpRequest_IMPL_44284(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1, Android.Base.Wrappers.IJWrapper arg2, Android.Base.Wrappers.IJWrapper arg3) :191 void HttpRequest__HttpRequest_IMPL_44284_fn(uObject* arg0_, uObject* arg1_, uObject* arg2_, uObject* arg3_, jobject* __retval) { *__retval = HttpRequest::HttpRequest_IMPL_44284(arg0_, arg1_, arg2_, arg3_); } // public static bool InstallCache(Android.Base.Wrappers.IJWrapper arg0, long arg1) :34 void HttpRequest__InstallCache_fn(uObject* arg0, int64_t* arg1, bool* __retval) { *__retval = HttpRequest::InstallCache(arg0, *arg1); } // public static extern bool InstallCache_IMPL_44279(Android.Base.Wrappers.IJWrapper arg0, long arg1) :175 void HttpRequest__InstallCache_IMPL_44279_fn(uObject* arg0_, int64_t* arg1_, bool* __retval) { *__retval = HttpRequest::InstallCache_IMPL_44279(arg0_, *arg1_); } // public void SendAsync() :111 void HttpRequest__SendAsync_fn(HttpRequest* __this) { __this->SendAsync(); } // public static extern void SendAsync_IMPL_44299(bool arg0, Android.Base.Primitives.ujobject arg1) :212 void HttpRequest__SendAsync_IMPL_44299_fn(bool* arg0_, jobject* arg1_) { HttpRequest::SendAsync_IMPL_44299(*arg0_, *arg1_); } // public void SendAsyncBuf(Android.Base.Wrappers.IJWrapper arg0) :116 void HttpRequest__SendAsyncBuf_fn(HttpRequest* __this, uObject* arg0) { __this->SendAsyncBuf(arg0); } // public static extern void SendAsyncBuf_IMPL_44300(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) :215 void HttpRequest__SendAsyncBuf_IMPL_44300_fn(bool* arg0_, jobject* arg1_, uObject* arg2_) { HttpRequest::SendAsyncBuf_IMPL_44300(*arg0_, *arg1_, arg2_); } // public void SendAsyncStr(Android.Base.Wrappers.IJWrapper arg0) :121 void HttpRequest__SendAsyncStr_fn(HttpRequest* __this, uObject* arg0) { __this->SendAsyncStr(arg0); } // public static extern void SendAsyncStr_IMPL_44301(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) :218 void HttpRequest__SendAsyncStr_IMPL_44301_fn(bool* arg0_, jobject* arg1_, uObject* arg2_) { HttpRequest::SendAsyncStr_IMPL_44301(*arg0_, *arg1_, arg2_); } // public void SetCaching(bool arg0) :96 void HttpRequest__SetCaching_fn(HttpRequest* __this, bool* arg0) { __this->SetCaching(*arg0); } // public static extern void SetCaching_IMPL_44295(bool arg0, Android.Base.Primitives.ujobject arg1, bool arg2) :203 void HttpRequest__SetCaching_IMPL_44295_fn(bool* arg0_, jobject* arg1_, bool* arg2_) { HttpRequest::SetCaching_IMPL_44295(*arg0_, *arg1_, *arg2_); } // public void SetHeader(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1) :86 void HttpRequest__SetHeader_fn(HttpRequest* __this, uObject* arg0, uObject* arg1) { __this->SetHeader(arg0, arg1); } // public static extern void SetHeader_IMPL_44293(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2, Android.Base.Wrappers.IJWrapper arg3) :197 void HttpRequest__SetHeader_IMPL_44293_fn(bool* arg0_, jobject* arg1_, uObject* arg2_, uObject* arg3_) { HttpRequest::SetHeader_IMPL_44293(*arg0_, *arg1_, arg2_, arg3_); } // public void SetResponseType(int arg0) :81 void HttpRequest__SetResponseType_fn(HttpRequest* __this, int32_t* arg0) { __this->SetResponseType(*arg0); } // public static extern void SetResponseType_IMPL_44292(bool arg0, Android.Base.Primitives.ujobject arg1, int arg2) :194 void HttpRequest__SetResponseType_IMPL_44292_fn(bool* arg0_, jobject* arg1_, int32_t* arg2_) { HttpRequest::SetResponseType_IMPL_44292(*arg0_, *arg1_, *arg2_); } // public void SetTimeout(int arg0) :91 void HttpRequest__SetTimeout_fn(HttpRequest* __this, int32_t* arg0) { __this->SetTimeout(*arg0); } // public static extern void SetTimeout_IMPL_44294(bool arg0, Android.Base.Primitives.ujobject arg1, int arg2) :200 void HttpRequest__SetTimeout_IMPL_44294_fn(bool* arg0_, jobject* arg1_, int32_t* arg2_) { HttpRequest::SetTimeout_IMPL_44294(*arg0_, *arg1_, *arg2_); } jclass HttpRequest::_javaClass1_; jclass HttpRequest::_javaProxyClass1_; jmethodID HttpRequest::InstallCache_44279_ID_; jmethodID HttpRequest::HttpRequest_44284_ID_c_; jmethodID HttpRequest::HttpRequest_44284_ID_c_prox_; jmethodID HttpRequest::SetResponseType_44292_ID_; jmethodID HttpRequest::SetHeader_44293_ID_; jmethodID HttpRequest::SetTimeout_44294_ID_; jmethodID HttpRequest::SetCaching_44295_ID_; jmethodID HttpRequest::GetResponseString_44297_ID_; jmethodID HttpRequest::SendAsync_44299_ID_; jmethodID HttpRequest::SendAsyncBuf_44300_ID_; jmethodID HttpRequest::SendAsyncStr_44301_ID_; jmethodID HttpRequest::Abort_44305_ID_; jmethodID HttpRequest::GetResponseStatus_44306_ID_; jmethodID HttpRequest::GetResponseHeader_44307_ID_; jmethodID HttpRequest::GetResponseHeaders_44308_ID_; // protected HttpRequest(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1, Android.Base.Wrappers.IJWrapper arg2) [instance] :59 void HttpRequest::ctor_4(uObject* arg0, uObject* arg1, uObject* arg2) { uStackFrame __("Android.com.fuse.ExperimentalHttp.HttpRequest", ".ctor(Android.Base.Wrappers.IJWrapper,Android.Base.Wrappers.IJWrapper,Android.Base.Wrappers.IJWrapper)"); ctor_1(::g::Android::Base::JNI::GetDefaultObject(), ::g::Android::Base::JNI::GetDefaultType(), false, false); _subclassed = HttpRequest::_IsThisType1((uObject*)this); HttpRequest* wrapper = _subclassed ? this : NULL; _javaObject = HttpRequest::HttpRequest_IMPL_44284((uObject*)wrapper, arg0, arg1, arg2); } // public void Abort() [instance] :141 void HttpRequest::Abort() { HttpRequest::Abort_IMPL_44305(_subclassed, _javaObject); } // public Android.Base.Wrappers.IJWrapper GetResponseHeader(Android.Base.Wrappers.IJWrapper arg0) [instance] :151 uObject* HttpRequest::GetResponseHeader(uObject* arg0) { return HttpRequest::GetResponseHeader_IMPL_44307(_subclassed, _javaObject, arg0); } // public Android.Base.Wrappers.IJWrapper GetResponseHeaders() [instance] :156 uObject* HttpRequest::GetResponseHeaders() { return HttpRequest::GetResponseHeaders_IMPL_44308(_subclassed, _javaObject); } // public int GetResponseStatus() [instance] :146 int32_t HttpRequest::GetResponseStatus() { return HttpRequest::GetResponseStatus_IMPL_44306(_subclassed, _javaObject); } // public Android.Base.Wrappers.IJWrapper GetResponseString() [instance] :106 uObject* HttpRequest::GetResponseString() { return HttpRequest::GetResponseString_IMPL_44297(_subclassed, _javaObject); } // public void SendAsync() [instance] :111 void HttpRequest::SendAsync() { HttpRequest::SendAsync_IMPL_44299(_subclassed, _javaObject); } // public void SendAsyncBuf(Android.Base.Wrappers.IJWrapper arg0) [instance] :116 void HttpRequest::SendAsyncBuf(uObject* arg0) { HttpRequest::SendAsyncBuf_IMPL_44300(_subclassed, _javaObject, arg0); } // public void SendAsyncStr(Android.Base.Wrappers.IJWrapper arg0) [instance] :121 void HttpRequest::SendAsyncStr(uObject* arg0) { HttpRequest::SendAsyncStr_IMPL_44301(_subclassed, _javaObject, arg0); } // public void SetCaching(bool arg0) [instance] :96 void HttpRequest::SetCaching(bool arg0) { bool arg0_ = arg0; HttpRequest::SetCaching_IMPL_44295(_subclassed, _javaObject, arg0_); } // public void SetHeader(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1) [instance] :86 void HttpRequest::SetHeader(uObject* arg0, uObject* arg1) { HttpRequest::SetHeader_IMPL_44293(_subclassed, _javaObject, arg0, arg1); } // public void SetResponseType(int arg0) [instance] :81 void HttpRequest::SetResponseType(int32_t arg0) { int32_t arg0_ = arg0; HttpRequest::SetResponseType_IMPL_44292(_subclassed, _javaObject, arg0_); } // public void SetTimeout(int arg0) [instance] :91 void HttpRequest::SetTimeout(int32_t arg0) { int32_t arg0_ = arg0; HttpRequest::SetTimeout_IMPL_44294(_subclassed, _javaObject, arg0_); } // public static extern new void _Init() [static] :17 void HttpRequest::_Init1() { if (HttpRequest::_javaClass1_) { return; } INIT_JNI; HttpRequest::_javaClass1_ = NEW_GLOBAL_REF(jclass,LOAD_SYS_CLASS("com/fuse/ExperimentalHttp/HttpRequest")); ::g::Android::Base::JNI::CheckException1(U_JNIVAR); if (!HttpRequest::_javaClass1_) { THROW_UNO_EXCEPTION("Unable to cache class 'com.fuse.ExperimentalHttp.HttpRequest'", 61);; } } // public static extern new void _InitProxy() [static] :13 void HttpRequest::_InitProxy1() { if (HttpRequest::_javaProxyClass1_) { return; } INIT_JNI; HttpRequest::_javaProxyClass1_ = NEW_GLOBAL_REF(jclass,::g::Android::Base::JNI::LoadClass(jni, "com.Bindings.Android_com_fuse_ExperimentalHttp_HttpRequest")); ::g::Android::Base::JNI::CheckException1(U_JNIVAR); if (!HttpRequest::_javaProxyClass1_) { THROW_UNO_EXCEPTION("Unable to cache class 'Android_com_fuse_ExperimentalHttp_HttpRequest'", 69);; } BEGIN_REG_MTD(7); //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnDataReceived(Android.Base.Wrappers.IJWrapper,int):IsStripped} REG_MTD(0,"__n_OnDataReceived","(J[BIJJ)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnDataReceived44285); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnAborted():IsStripped} REG_MTD(1,"__n_OnAborted","(J)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnAborted44286); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnError(Android.Base.Wrappers.IJWrapper):IsStripped} REG_MTD(2,"__n_OnError","(JLjava/lang/String;J)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnError44287); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnTimeout():IsStripped} REG_MTD(3,"__n_OnTimeout","(J)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnTimeout44288); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnDone():IsStripped} REG_MTD(4,"__n_OnDone","(J)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnDone44289); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnHeadersReceived():IsStripped} REG_MTD(5,"__n_OnHeadersReceived","(J)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnHeadersReceived44290); //#endif //#if !#{Android.com.fuse.ExperimentalHttp.HttpRequest.OnProgress(int,int,bool):IsStripped} REG_MTD(6,"__n_OnProgress","(JIIZJJJ)V",::Android_com_fuse_ExperimentalHttp_HttpRequest__OnProgress44291); //#endif COMMIT_REG_MTD(HttpRequest::_javaProxyClass1_); } // public static extern new bool _IsThisType(Android.Base.Wrappers.IJWrapper obj) [static] :15 bool HttpRequest::_IsThisType1(uObject* obj_) { int N = 44; const char* typ = "Android.com.fuse.ExperimentalHttp.HttpRequest"; const char* potential = obj_->__type->FullName; for (int i = 0; i < N; ++i) { if (potential[i]==0 || (potential[i] != typ[i])) { return true; } } return false; } // public static extern void Abort_IMPL_44305(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :230 void HttpRequest::Abort_IMPL_44305(bool arg0_, jobject arg1_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::Abort_44305_ID_,HttpRequest::_javaClass1_,"Abort","()V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.Abort could not be cached",86); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::Abort_44305_ID_); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::Abort_44305_ID_); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern Android.Base.Wrappers.IJWrapper GetResponseHeader_IMPL_44307(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) [static] :236 uObject* HttpRequest::GetResponseHeader_IMPL_44307(bool arg0_, jobject arg1_, uObject* arg2_) { INIT_JNI; jobject _obArg2 = ((!arg2_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg2_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); uObject* result; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::GetResponseHeader_44307_ID_,HttpRequest::_javaClass1_,"GetResponseHeader","(Ljava/lang/String;)Ljava/lang/String;",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.GetResponseHeader could not be cached",98); if (arg0_) { NEW_UNO(U_JNIVAR->CallNonvirtualObjectMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::GetResponseHeader_44307_ID_, _obArg2),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } else { NEW_UNO(U_JNIVAR->CallObjectMethod(arg1_, HttpRequest::GetResponseHeader_44307_ID_, _obArg2),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); return result; } // public static extern Android.Base.Wrappers.IJWrapper GetResponseHeaders_IMPL_44308(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :239 uObject* HttpRequest::GetResponseHeaders_IMPL_44308(bool arg0_, jobject arg1_) { INIT_JNI; uObject* result; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::GetResponseHeaders_44308_ID_,HttpRequest::_javaClass1_,"GetResponseHeaders","()Ljava/lang/String;",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.GetResponseHeaders could not be cached",99); if (arg0_) { NEW_UNO(U_JNIVAR->CallNonvirtualObjectMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::GetResponseHeaders_44308_ID_),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } else { NEW_UNO(U_JNIVAR->CallObjectMethod(arg1_, HttpRequest::GetResponseHeaders_44308_ID_),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); return result; } // public static extern int GetResponseStatus_IMPL_44306(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :233 int32_t HttpRequest::GetResponseStatus_IMPL_44306(bool arg0_, jobject arg1_) { INIT_JNI; int32_t result; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::GetResponseStatus_44306_ID_,HttpRequest::_javaClass1_,"GetResponseStatus","()I",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.GetResponseStatus could not be cached",98); if (arg0_) { result = ((int32_t)U_JNIVAR->CallNonvirtualIntMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::GetResponseStatus_44306_ID_)); } else { result = ((int32_t)U_JNIVAR->CallIntMethod(arg1_, HttpRequest::GetResponseStatus_44306_ID_)); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); return result; } // public static extern Android.Base.Wrappers.IJWrapper GetResponseString_IMPL_44297(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :209 uObject* HttpRequest::GetResponseString_IMPL_44297(bool arg0_, jobject arg1_) { INIT_JNI; uObject* result; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::GetResponseString_44297_ID_,HttpRequest::_javaClass1_,"GetResponseString","()Ljava/lang/String;",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.GetResponseString could not be cached",98); if (arg0_) { NEW_UNO(U_JNIVAR->CallNonvirtualObjectMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::GetResponseString_44297_ID_),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } else { NEW_UNO(U_JNIVAR->CallObjectMethod(arg1_, HttpRequest::GetResponseString_44297_ID_),result,::g::Android::Base::Wrappers::JWrapper_typeof(),::g::Android::Base::Wrappers::JWrapper*,false,false); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); return result; } // public static extern Android.Base.Primitives.ujobject HttpRequest_IMPL_44284(Android.Base.Wrappers.IJWrapper arg0, Android.Base.Wrappers.IJWrapper arg1, Android.Base.Wrappers.IJWrapper arg2, Android.Base.Wrappers.IJWrapper arg3) [static] :191 jobject HttpRequest::HttpRequest_IMPL_44284(uObject* arg0_, uObject* arg1_, uObject* arg2_, uObject* arg3_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::HttpRequest_44284_ID_c_,HttpRequest::_javaClass1_,"<init>","(Landroid/app/Activity;Ljava/lang/String;Ljava/lang/String;)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.<init> could not be cached",87); if (arg0_) { CLASS_INIT(HttpRequest::_javaProxyClass1_,HttpRequest::_InitProxy1()); CACHE_METHOD(HttpRequest::HttpRequest_44284_ID_c_prox_,HttpRequest::_javaProxyClass1_,"<init>","(JLandroid/app/Activity;Ljava/lang/String;Ljava/lang/String;)V",GetMethodID,"Proxy Id for method Android_com_fuse_ExperimentalHttp_HttpRequest.HttpRequest_44284_ID_c_prox could not be cached",113); } jobject _obArg1 = ((!arg1_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg1_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); jobject _obArg2 = ((!arg2_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg2_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); jobject _obArg3 = ((!arg3_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg3_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); jobject result; jobject _tmp; if (!arg0_) { _tmp = U_JNIVAR->NewObject(HttpRequest::_javaClass1_, HttpRequest::HttpRequest_44284_ID_c_, _obArg1, _obArg2, _obArg3); result = NEW_GLOBAL_REF(jobject,_tmp); ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } else { _tmp = U_JNIVAR->NewObject(HttpRequest::_javaProxyClass1_, HttpRequest::HttpRequest_44284_ID_c_prox_, (jlong)arg0_->__weakptr, _obArg1, _obArg2, _obArg3); result = NEW_GLOBAL_REF(jobject,_tmp); ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } U_JNIVAR->DeleteLocalRef(_tmp); return result; } // public static bool InstallCache(Android.Base.Wrappers.IJWrapper arg0, long arg1) [static] :34 bool HttpRequest::InstallCache(uObject* arg0, int64_t arg1) { return HttpRequest::InstallCache_IMPL_44279(arg0, arg1); } // public static extern bool InstallCache_IMPL_44279(Android.Base.Wrappers.IJWrapper arg0, long arg1) [static] :175 bool HttpRequest::InstallCache_IMPL_44279(uObject* arg0_, int64_t arg1_) { INIT_JNI; jobject _obArg0 = ((!arg0_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg0_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); bool result; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::InstallCache_44279_ID_,HttpRequest::_javaClass1_,"InstallCache","(Landroid/app/Activity;J)Z",GetStaticMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.InstallCache could not be cached",93); result = ((bool)U_JNIVAR->CallStaticBooleanMethod(HttpRequest::_javaClass1_, HttpRequest::InstallCache_44279_ID_, _obArg0, ((jlong)arg1_))); ::g::Android::Base::JNI::CheckException1(U_JNIVAR); return result; } // public static extern void SendAsync_IMPL_44299(bool arg0, Android.Base.Primitives.ujobject arg1) [static] :212 void HttpRequest::SendAsync_IMPL_44299(bool arg0_, jobject arg1_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SendAsync_44299_ID_,HttpRequest::_javaClass1_,"SendAsync","()V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SendAsync could not be cached",90); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SendAsync_44299_ID_); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SendAsync_44299_ID_); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SendAsyncBuf_IMPL_44300(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) [static] :215 void HttpRequest::SendAsyncBuf_IMPL_44300(bool arg0_, jobject arg1_, uObject* arg2_) { INIT_JNI; jobject _obArg2 = ((!arg2_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg2_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SendAsyncBuf_44300_ID_,HttpRequest::_javaClass1_,"SendAsyncBuf","(Ljava/nio/ByteBuffer;)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SendAsyncBuf could not be cached",93); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SendAsyncBuf_44300_ID_, _obArg2); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SendAsyncBuf_44300_ID_, _obArg2); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SendAsyncStr_IMPL_44301(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2) [static] :218 void HttpRequest::SendAsyncStr_IMPL_44301(bool arg0_, jobject arg1_, uObject* arg2_) { INIT_JNI; jobject _obArg2 = ((!arg2_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg2_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SendAsyncStr_44301_ID_,HttpRequest::_javaClass1_,"SendAsyncStr","(Ljava/lang/String;)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SendAsyncStr could not be cached",93); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SendAsyncStr_44301_ID_, _obArg2); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SendAsyncStr_44301_ID_, _obArg2); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SetCaching_IMPL_44295(bool arg0, Android.Base.Primitives.ujobject arg1, bool arg2) [static] :203 void HttpRequest::SetCaching_IMPL_44295(bool arg0_, jobject arg1_, bool arg2_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SetCaching_44295_ID_,HttpRequest::_javaClass1_,"SetCaching","(Z)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SetCaching could not be cached",91); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SetCaching_44295_ID_, ((jboolean)arg2_)); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SetCaching_44295_ID_, ((jboolean)arg2_)); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SetHeader_IMPL_44293(bool arg0, Android.Base.Primitives.ujobject arg1, Android.Base.Wrappers.IJWrapper arg2, Android.Base.Wrappers.IJWrapper arg3) [static] :197 void HttpRequest::SetHeader_IMPL_44293(bool arg0_, jobject arg1_, uObject* arg2_, uObject* arg3_) { INIT_JNI; jobject _obArg2 = ((!arg2_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg2_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); jobject _obArg3 = ((!arg3_) ? NULL : ::g::Android::Base::Wrappers::IJWrapper::_GetJavaObject(uInterface(arg3_, ::g::Android::Base::Wrappers::IJWrapper_typeof()))); CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SetHeader_44293_ID_,HttpRequest::_javaClass1_,"SetHeader","(Ljava/lang/String;Ljava/lang/String;)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SetHeader could not be cached",90); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SetHeader_44293_ID_, _obArg2, _obArg3); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SetHeader_44293_ID_, _obArg2, _obArg3); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SetResponseType_IMPL_44292(bool arg0, Android.Base.Primitives.ujobject arg1, int arg2) [static] :194 void HttpRequest::SetResponseType_IMPL_44292(bool arg0_, jobject arg1_, int32_t arg2_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SetResponseType_44292_ID_,HttpRequest::_javaClass1_,"SetResponseType","(I)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SetResponseType could not be cached",96); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SetResponseType_44292_ID_, ((jint)arg2_)); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SetResponseType_44292_ID_, ((jint)arg2_)); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // public static extern void SetTimeout_IMPL_44294(bool arg0, Android.Base.Primitives.ujobject arg1, int arg2) [static] :200 void HttpRequest::SetTimeout_IMPL_44294(bool arg0_, jobject arg1_, int32_t arg2_) { INIT_JNI; CLASS_INIT(HttpRequest::_javaClass1_,HttpRequest::_Init1()); CACHE_METHOD(HttpRequest::SetTimeout_44294_ID_,HttpRequest::_javaClass1_,"SetTimeout","(I)V",GetMethodID,"Id for fallback method com.fuse.ExperimentalHttp.HttpRequest.SetTimeout could not be cached",91); if (arg0_) { U_JNIVAR->CallNonvirtualVoidMethod(arg1_, HttpRequest::_javaClass1_, HttpRequest::SetTimeout_44294_ID_, ((jint)arg2_)); } else { U_JNIVAR->CallVoidMethod(arg1_, HttpRequest::SetTimeout_44294_ID_, ((jint)arg2_)); } ::g::Android::Base::JNI::CheckException1(U_JNIVAR); } // } }}}}} // ::g::Android::com::fuse::ExperimentalHttp
55.020126
364
0.751835
marferfer
90486f4bb552f7863fce45307fe01193fbb0c9fb
1,491
cpp
C++
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
3
2018-05-08T14:08:50.000Z
2019-02-28T00:10:14.000Z
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <cstdio> #include <cassert> class Solution { public: std::string longestPalindrome(std::string s) { int slen = s.length(); if (slen == 0) return s; // at least one. int beginInd = 0, endInd = 0, maxLen = 1; // try odds first. for (int i = 0; i < slen; ++i) { int j; // try different lengths for (j = 1; i-j >= 0 && i+j < slen; ++j) { if (s[i-j] != s[i+j]) break; } // either j just outside of range or we have a mismatch --j; if (i-j >= 0 && i+j < slen && j*2+1 > maxLen) { beginInd = i-j; endInd = i+j; maxLen = j*2 + 1; } } // try evens for (int i = 0; i < slen; ++i) { int j; // now i stands for using s[i] | s[i+1] as middle point. for (j = 1; i-j+1 >= 0 && i+j < slen; ++j) { if (s[i-j+1] != s[i+j]) break; } --j; if (i-j+1 >= 0 && i+j < slen && j*2 > maxLen) { beginInd = i-j+1; endInd = i+j; maxLen = j*2; } } return s.substr(beginInd, maxLen); } }; int main() { Solution s = Solution(); std::cout << s.longestPalindrome("fasdffdsafcabacgg"); return 0; }
25.706897
68
0.389671
Javran
9049331e22900bb730fc03015c128deff987fd69
99
hh
C++
F/src/server.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
114
2015-04-14T10:30:05.000Z
2021-06-11T02:57:59.000Z
F/src/server.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
null
null
null
F/src/server.hh
vaginessa/Ctrl-Alt-Test
b981ebdbc6b0678f004c4052d70ebb56af2d89a0
[ "Apache-2.0" ]
11
2015-07-26T02:11:32.000Z
2020-04-02T21:06:15.000Z
#ifndef SERVER_HH_ # define SERVER_HH_ namespace Server { void init(); void doIO(); } #endif
9
19
0.686869
vaginessa
90494eff9b6b4378bd3aed6255336a356df90957
16,367
cpp
C++
compute/tensor/src/fully_connected.cpp
chillingche/bolt
255307a3a02264dab665a2399f5cd49d57317697
[ "MIT" ]
1
2021-05-14T06:31:37.000Z
2021-05-14T06:31:37.000Z
compute/tensor/src/fully_connected.cpp
jianfeifeng/bolt
08577f80291a8a99f64fc24454a17832c56eb02b
[ "MIT" ]
null
null
null
compute/tensor/src/fully_connected.cpp
jianfeifeng/bolt
08577f80291a8a99f64fc24454a17832c56eb02b
[ "MIT" ]
null
null
null
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include <string.h> #include "tensor_computing.h" #include "blas_enhance.h" #ifdef _USE_MALI #include "gpu/mali/tensor_computing_mali.h" #endif // input format: NCHW|NCHWC8|NORMAL // weight(filter) format: NORMAL // result format: NORMAL inline EE fully_connected_infer_output_size_cpu( TensorDesc inputDesc, TensorDesc filterDesc, TensorDesc *outputDesc) { if (outputDesc == nullptr) { CHECK_STATUS(NULL_POINTER); } DataType idt, fdt; DataFormat idf, fdf; U32 in, ic, ih, iw; U32 fh, fw; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = 1; ih = 1; } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); if (idf != DF_NCHW && idf != DF_NCHWC8) { CHECK_STATUS(NOT_MATCH); } } else { return NOT_MATCH; } CHECK_REQUIREMENT(tensorIs2d(filterDesc)); CHECK_STATUS(tensor2dGet(filterDesc, &fdt, &fdf, &fh, &fw)); if (fdf != DF_TRANSPOSE) { CHECK_STATUS(NOT_MATCH); } if (fw != ic * ih * iw) { CHECK_STATUS(NOT_MATCH); } *outputDesc = tensor2df(idt, DF_NORMAL, in, fh); return SUCCESS; } EE fully_connected_infer_output_size( Tensor *inputTensor, Tensor filterTensor, Tensor *outputTensor, ArchInfo_t archInfo) { if (inputTensor == nullptr) { CHECK_STATUS(NULL_POINTER); } if (outputTensor == nullptr) { CHECK_STATUS(NULL_POINTER); } TensorDesc inputDesc = inputTensor->get_desc(); TensorDesc filterDesc = filterTensor.get_desc(); TensorDesc outputDesc = outputTensor->get_desc(); EE ret = NOT_SUPPORTED; if (IS_MALI_GPU(archInfo->arch)) { #ifdef _USE_MALI GCLMemDesc gclmemInputDesc = ocl_get_desc(*inputTensor); GCLMemDesc gclmemOutputDesc = ocl_get_desc(*outputTensor); ret = fully_connected_infer_output_size_mali( inputDesc, filterDesc, &outputDesc, &gclmemInputDesc, &gclmemOutputDesc); ocl_set_desc(inputTensor, gclmemInputDesc); ocl_set_desc(outputTensor, gclmemOutputDesc); #endif } else { ret = fully_connected_infer_output_size_cpu(inputDesc, filterDesc, &outputDesc); } outputTensor->resize(outputDesc); return ret; } EE fully_connected_infer_forward_algorithm( Tensor inputTensor, Tensor filterTensor, Tensor outputTensor, ArchInfo_t archInfo) { EE ret = NOT_SUPPORTED; if (IS_MALI_GPU(archInfo->arch)) { #ifdef _USE_MALI TensorDesc inputDesc = inputTensor.get_desc(); TensorDesc filterDesc = filterTensor.get_desc(); TensorDesc outputDesc = outputTensor.get_desc(); GCLMemDesc gclmemInputDesc = ocl_get_desc(inputTensor); GCLMemDesc gclmemOutputDesc = ocl_get_desc(outputTensor); ret = fully_connected_infer_forward_algorithm_mali( ((MaliPara_t)(archInfo->archPara))->handle, inputDesc, filterDesc, outputDesc, gclmemInputDesc, gclmemOutputDesc, ((MaliPara_t)(archInfo->archPara))->forwardRunInfo); #endif } else { UNUSED(inputTensor); UNUSED(filterTensor); UNUSED(outputTensor); } return ret; } EE fully_connected_infer_forward_tmp_bytes( Tensor inputTensor, Tensor filterTensor, U32 *bytes, ArchInfo_t archInfo) { TensorDesc inputDesc = inputTensor.get_desc(); TensorDesc filterDesc = filterTensor.get_desc(); // Match dt in int8 inference inputDesc.dt = filterDesc.dt; EE ret = NOT_SUPPORTED; if (IS_MALI_GPU(archInfo->arch)) { #ifdef _USE_MALI ret = fully_connected_infer_forward_tmp_bytes_mali( inputDesc, filterDesc, bytes, ((MaliPara_t)(archInfo->archPara))->forwardRunInfo); #endif } else { if (bytes == nullptr) { CHECK_STATUS(NULL_POINTER); } DataType idt; DataFormat idf; U32 in, ic, ih, iw; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = ih = 1; } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { return NOT_MATCH; } if (in != 1) { // call gemm TensorDesc in_desc = tensor2df(idt, DF_NORMAL, in, ic * ih * iw); ret = matrix_matrix_multiply_tmp_bytes(in_desc, filterDesc, bytes, archInfo->arch); } else { // call gemv TensorDesc in_desc = tensor1d(idt, ic * ih * iw); ret = matrix_vector_multiply_tmp_bytes(filterDesc, in_desc, bytes, archInfo->arch); } if (DT_I8 == filterDesc.dt) { if (DT_F16 == inputTensor.get_desc().dt) { *bytes += tensorNumBytes(inputDesc); } *bytes += filterDesc.dims[0] * bytesOf(DT_I32); // Bias *bytes += in * filterDesc.dims[1] * bytesOf(DT_I32); // Results before quantization } } return ret; } EE fully_connected_transform_filter_bytes(Tensor filterTensor, U32 *bytes, ArchInfo_t archInfo) { TensorDesc filterDesc = filterTensor.get_desc(); if (IS_MALI_GPU(archInfo->arch)) { #ifdef _USE_MALI CHECK_STATUS(fully_connected_transform_filter_bytes_mali(filterDesc, ((MaliPara_t)(archInfo->archPara))->gclmemFilterDesc, bytes, ((MaliPara_t)(archInfo->archPara))->forwardRunInfo)); #endif } else { if (bytes == nullptr) { CHECK_STATUS(NULL_POINTER); } *bytes = tensorNumBytes(filterDesc) + 32; } return SUCCESS; } template <typename T> EE fully_connected_transform_filter_kernel(TensorDesc inputDesc, TensorDesc filterDesc, const void *filter, TensorDesc *ftmDesc, void *filterTransformed) { if (filter == nullptr || ftmDesc == nullptr || filterTransformed == nullptr) { CHECK_STATUS(NULL_POINTER); } DataType idt, fdt; DataFormat idf, fdf; U32 in, ic, ih, iw; U32 fh, fw; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = ih = 1; } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { return NOT_MATCH; } CHECK_STATUS(tensor2dGet(filterDesc, &fdt, &fdf, &fh, &fw)); if (fw != ic * ih * iw) { CHECK_STATUS(NOT_MATCH); } bool need_transpose = false; if (in > 1) { need_transpose = true; } if (idf == DF_NCHW || idf == DF_NORMAL) { if (need_transpose) { T *f_ptr = (T *)filter; T *ftm_ptr = (T *)filterTransformed; for (U32 h = 0; h < fh; h++) { for (U32 w = 0; w < fw; w++) { U32 f_index = h * fw + w; U32 ftm_index = w * fh + h; ftm_ptr[ftm_index] = f_ptr[f_index]; } } } else { memcpy(filterTransformed, filter, tensorNumBytes(filterDesc)); } } else if (idf == DF_NCHWC8) { U32 align = 8; if (ic % align != 0) { align = 1; } U32 ic_new = ic / align; T *f_ptr = (T *)filter; T *ftm_ptr = (T *)filterTransformed; for (U32 h = 0; h < fh; h++) { for (U32 w = 0; w < fw; w++) { U32 i_n = w / (ic * ih * iw); U32 remain = w % (ic * ih * iw); U32 i_c = remain / (ih * iw); remain = remain % (ih * iw); U32 i_h = remain / iw; U32 i_w = remain % iw; U32 i_c_outer = i_c / align; U32 i_c_inner = i_c % align; U32 h_new = h; U32 w_new = (((i_n * ic_new + i_c_outer) * ih + i_h) * iw + i_w) * align + i_c_inner; U32 ld = fw; if (need_transpose) { U32 tmp = h_new; h_new = w_new; w_new = tmp; ld = fh; } U32 f_index = h * fw + w; U32 ftm_index = h_new * ld + w_new; ftm_ptr[ftm_index] = f_ptr[f_index]; } } } else { return NOT_MATCH; } U32 fh_after = fh; U32 fw_after = fw; if (need_transpose) { fh_after = fw; fw_after = fh; } *ftmDesc = tensor2df(fdt, DF_NORMAL, fh_after, fw_after); return SUCCESS; } EE fully_connected_transform_filter( Tensor inputTensor, Tensor filterTensor, Tensor *ftmTensor, ArchInfo_t archInfo) { auto arch = archInfo->arch; TensorDesc inputDesc = inputTensor.get_desc(); TensorDesc filterDesc = filterTensor.get_desc(); void *filter = get_ptr_from_tensor(filterTensor, arch); TensorDesc ftmDesc = ftmTensor->get_desc(); void *filterTransformed = get_ptr_from_tensor(*ftmTensor, arch); EE ret = NOT_SUPPORTED; if (IS_MALI_GPU(arch)) { #ifdef _USE_MALI ret = fully_connected_transform_filter_mali(((MaliPara_t)(archInfo->archPara))->handle, filterDesc, (GCLMem_t)filter, &ftmDesc, (GCLMem_t)filterTransformed, ((MaliPara_t)(archInfo->archPara))->forwardRunInfo); #endif } else { switch (filterDesc.dt) { #ifdef _USE_FP16 case DT_F16: { ret = fully_connected_transform_filter_kernel<F16>( inputDesc, filterDesc, filter, &ftmDesc, filterTransformed); break; } #endif #ifdef _USE_FP32 case DT_F32: { ret = fully_connected_transform_filter_kernel<F32>( inputDesc, filterDesc, filter, &ftmDesc, filterTransformed); break; } #endif default: ret = NOT_SUPPORTED; break; } } ftmTensor->resize(ftmDesc); return ret; } EE fully_connected(Tensor inputTensor, Tensor filterTensor, Tensor biasTensor, Tensor tmpTensor, Tensor outputTensor, ArchInfo_t archInfo) { auto arch = archInfo->arch; TensorDesc inputDesc = inputTensor.get_desc(); void *input = get_ptr_from_tensor(inputTensor, arch); TensorDesc filterDesc = filterTensor.get_desc(); void *filter = get_ptr_from_tensor(filterTensor, arch); TensorDesc biasDesc = biasTensor.get_desc(); void *bias = get_ptr_from_tensor(biasTensor, arch); U32 tmpBytes = tmpTensor.bytes(); void *tmp = get_ptr_from_tensor(tmpTensor, arch); TensorDesc outputDesc = outputTensor.get_desc(); void *output = get_ptr_from_tensor(outputTensor, arch); EE ret = NOT_SUPPORTED; if (IS_MALI_GPU(arch)) { #ifdef _USE_MALI ret = fully_connected_mali(((MaliPara_t)(archInfo->archPara))->handle, inputDesc, (GCLMem_t)input, filterDesc, (GCLMem_t)filter, biasDesc, (GCLMem_t)bias, tmpBytes, (GCLMem_t)tmp, outputDesc, (GCLMem_t)output, ((MaliPara_t)(archInfo->archPara))->forwardRunInfo); #endif } else { if (input == nullptr || filter == nullptr || output == nullptr) { CHECK_STATUS(NULL_POINTER); } #ifdef _USE_INT8 F32 scaleI = inputTensor.get_scale(); if (DT_I8 == filterDesc.dt) { if (DT_F16 == inputDesc.dt) { F16 *inD = (F16 *)input; INT8 *inQ = (INT8 *)tmp; F16 scale = scaleI; quantize_tensor(inputDesc, inD, &inputDesc, inQ, &scale); scaleI = scale; input = (U8 *)tmp; tmp = (U8 *)tmp + tensorNumBytes(inputDesc); } if (nullptr != bias) { if (DT_F16 == outputDesc.dt) { // dequantize and then add bias bias = nullptr; } else { CHECK_REQUIREMENT(DT_I8 == outputDesc.dt); biasDesc.dt = DT_I32; F16 *biasF = (F16 *)bias; I32 *biasI = (I32 *)tmp; F32 scale = scaleI * filterTensor.get_scale(); for (U32 i = 0; i < tensorNumElements(biasDesc); i++) { biasI[i] = round(scale * biasF[i]); } bias = tmp; tmp = (U8 *)tmp + tensorNumBytes(biasDesc); } } outputDesc.dt = DT_I32; output = tmp; tmp = (U8 *)tmp + tensorNumBytes(outputDesc); } #endif U32 in, ic, ih, iw; U32 oh, ow; U32 fh, fw, bw; DataType idt, fdt, odt, bdt; DataFormat idf, fdf, odf, bdf; if (tensorIs2d(inputDesc)) { CHECK_STATUS(tensor2dGet(inputDesc, &idt, &idf, &in, &iw)); ic = ih = 1; } else if (tensorIs4d(inputDesc)) { CHECK_STATUS(tensor4dGet(inputDesc, &idt, &idf, &in, &ic, &ih, &iw)); } else { CHECK_STATUS(NOT_MATCH); } CHECK_REQUIREMENT(tensorIs2d(filterDesc)); CHECK_STATUS(tensor2dGet(filterDesc, &fdt, &fdf, &fh, &fw)); CHECK_STATUS(tensor2dGet(outputDesc, &odt, &odf, &oh, &ow)); if (bias != nullptr) { CHECK_STATUS(tensor1dGet(biasDesc, &bdt, &bdf, &bw)); if (bw != ow) { CHECK_STATUS(NOT_MATCH); } else { U8 *outArray = (U8 *)output; U32 size = tensorNumBytes(biasDesc); for (U32 i = 0; i < in; i++) { memcpy(outArray + i * size, bias, size); } } } else { memset(output, 0, tensorNumBytes(outputDesc)); } if (in == 1 && fdf != targetFormat4MatrixB(fdt)) { // If weight is transformed for mmm, don't run as mvm TensorDesc vectorDesc = tensor1d(idt, ic * ih * iw); TensorDesc resultDesc = tensor1d(odt, ow); ret = matrix_vector_multiply(filterDesc, filter, vectorDesc, input, tmpBytes, tmp, resultDesc, output, archInfo->arch); } else { TensorDesc in_desc = tensor2df(idt, DF_NORMAL, in, ic * ih * iw); ret = matrix_matrix_multiply(in_desc, input, filterDesc, filter, tmpBytes, tmp, outputDesc, output, archInfo->arch); } #ifdef _USE_INT8 F32 scale = scaleI * filterTensor.get_scale(); if (DT_I8 == filterDesc.dt) { if (DT_I8 == outputTensor.get_desc().dt) { CHECK_STATUS(quantize_tensor(outputDesc, output, &outputDesc, get_ptr_from_tensor(outputTensor, arch), &scale)); outputTensor.set_scale(scale); } else { CHECK_REQUIREMENT(DT_F16 == outputTensor.get_desc().dt); F16 *biasF = (F16 *)get_ptr_from_tensor(biasTensor, arch); U32 biasLen = nullptr == biasF ? 0 : tensorNumElements(biasDesc); dequantize_int32_to_fp16(tensorNumElements(outputDesc), (I32 *)output, scale, (F16 *)get_ptr_from_tensor(outputTensor, arch), biasLen, biasF); } } #endif } return ret; }
36.615213
149
0.586546
chillingche
9049599bcbcfa042e94b3d9a5075f66afe9a7745
2,668
cpp
C++
LeetCode/C++/852. Peak Index in a Mountain Array.cpp
shreejitverma/GeeksforGeeks
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-18T05:14:28.000Z
2022-03-08T07:00:08.000Z
LeetCode/C++/852. Peak Index in a Mountain Array.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
6
2022-01-13T04:31:04.000Z
2022-03-12T01:06:16.000Z
LeetCode/C++/852. Peak Index in a Mountain Array.cpp
shivaniverma1/Competitive-Programming-1
d7bcb166369fffa9a031a258e925b6aff8d44e6c
[ "MIT" ]
2
2022-02-14T19:53:53.000Z
2022-02-18T05:14:30.000Z
/** Let's call an array A a mountain if the following properties hold: A.length >= 3 There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1] Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]. Example 1: Input: [0,1,0] Output: 1 Example 2: Input: [0,2,1,0] Output: 1 Note: 3 <= A.length <= 10000 0 <= A[i] <= 10^6 A is a mountain, as defined above. **/ //Your runtime beats 52.46 % of cpp submissions. class Solution { public: int peakIndexInMountainArray(vector<int>& A) { //binary search int low = 0; int up = A.size()-1; int cur = A.size()/2; // cout << low << " " << up << " " << cur << endl; while(true){ // cout << low << " " << up << " " << cur << endl; if(A[cur-1] < A[cur] && A[cur] < A[cur+1]){ //left side of mountain low = cur; cur = (cur+up)/2; }else if(A[cur-1] > A[cur] && A[cur] > A[cur+1]){ //right side up = cur; cur = (cur+low)/2; }else{ return cur; } } } }; /** Approach 1: Linear Scan Intuition and Algorithm The mountain increases until it doesn't. The point at which it stops increasing is the peak. //Java class Solution { public int peakIndexInMountainArray(int[] A) { int i = 0; while (A[i] < A[i+1]) i++; return i; } } Complexity Analysis Time Complexity: O(N), where N is the length of A. Space Complexity: O(1). Approach 2: Binary Search Intuition and Algorithm The comparison A[i] < A[i+1] in a mountain array looks like [True, True, True, ..., True, False, False, ..., False]: 1 or more boolean Trues, followed by 1 or more boolean False. For example, in the mountain array [1, 2, 3, 4, 1], the comparisons A[i] < A[i+1] would be True, True, True, False. We can binary search over this array of comparisons, to find the largest index i such that A[i] < A[i+1]. For more on binary search, see the LeetCode explore topic here. //Your runtime beats 52.46 % of cpp submissions. class Solution { public: int peakIndexInMountainArray(vector<int>& A) { //binary search int low = 0; int up = A.size()-1; while(low < up){ int mi = (low+up)/2; if(A[mi] < A[mi+1]){ low = mi+1; }else{ up = mi; } } return low; } }; Complexity Analysis Time Complexity: O(logN), where N is the length of A. Space Complexity: O(1). **/
25.902913
134
0.545727
shreejitverma
904be75537e53684ca7b8993089986dcd5fc166c
2,714
cc
C++
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2013,2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include <cmath> #include <cstdlib> #include "com/centreon/broker/neb/host_status.hh" using namespace com::centreon::broker; /** * Check host_status' default constructor. * * @return EXIT_SUCCESS on success. */ int main() { // Object. neb::host_status hs; // Check. return (((hs.source_id != 0) || (hs.destination_id != 0) || hs.acknowledged || (hs.acknowledgement_type != 0) || hs.active_checks_enabled || !hs.check_command.isEmpty() || (fabs(hs.check_interval) > 0.0001) || !hs.check_period.isEmpty() || (hs.check_type != 0) || (hs.current_check_attempt != 0) || (hs.current_state != 4) || (hs.downtime_depth != 0) || !hs.enabled || !hs.event_handler.isEmpty() || hs.event_handler_enabled || (fabs(hs.execution_time) > 0.0001) || hs.flap_detection_enabled || hs.has_been_checked || (hs.host_id != 0) || hs.is_flapping || (hs.last_check != 0) || (hs.last_hard_state != 4) || (hs.last_hard_state_change != 0) || (hs.last_notification != 0) || (hs.last_state_change != 0) || (hs.last_time_down != 0) || (hs.last_time_unreachable != 0) || (hs.last_time_up != 0) || (hs.last_update != 0) || (fabs(hs.latency) > 0.0001) || (hs.max_check_attempts != 0) || (hs.next_check != 0) || (hs.next_notification != 0) || hs.no_more_notifications || (hs.notification_number != 0) || hs.notifications_enabled || hs.obsess_over || !hs.output.isEmpty() || hs.passive_checks_enabled || (fabs(hs.percent_state_change) > 0.0001) || !hs.perf_data.isEmpty() || (fabs(hs.retry_interval) > 0.0001) || hs.should_be_scheduled || (hs.state_type != 0)) ? EXIT_FAILURE : EXIT_SUCCESS); }
33.097561
75
0.565954
sdelafond
904befbc82b10499dee8fb798dfb4f5198dcf60b
2,773
cpp
C++
src/test/resources/botan/symm_block_cipher.cpp
oxisto/cpg
60ec86139dfa657122d58d3739f9353efd7323f8
[ "Apache-2.0" ]
96
2019-12-06T19:05:41.000Z
2022-03-29T16:35:06.000Z
src/test/resources/botan/symm_block_cipher.cpp
oxisto/cpg
60ec86139dfa657122d58d3739f9353efd7323f8
[ "Apache-2.0" ]
660
2019-12-11T13:33:43.000Z
2022-03-31T07:06:10.000Z
src/test/resources/botan/symm_block_cipher.cpp
oxisto/cpg
60ec86139dfa657122d58d3739f9353efd7323f8
[ "Apache-2.0" ]
34
2019-12-12T14:34:05.000Z
2022-03-24T12:46:47.000Z
#include <iostream> #include <stdexcept> #include <cassert> #include <botan/aead.h> #include <botan/hex.h> #include <botan/block_cipher.h> #include <botan/auto_rng.h> /*BAD example MS1(BlockCiphers) #define __CIPHER "Twofish/CBC" */ #define __CIPHER "AES-256/CBC" #define __KEY_LENGTH 32 #define __IV_LENGTH 16 /* BAD example MS1(UseRandomIV) Botan::InitializationVector __IV("deadbeefdeadbeefdeadbeefdeadbeef"); */ Botan::InitializationVector __IV; Botan::secure_vector<uint8_t> do_crypt(const std::string &cipher, const std::vector<uint8_t> &input, const Botan::SymmetricKey &key, const Botan::InitializationVector &iv, Botan::Cipher_Dir direction) { if(iv.size() == 0) throw std::runtime_error("IV must not be empty"); std::unique_ptr<Botan::Cipher_Mode> processor(Botan::get_cipher_mode(cipher, direction)); if(!processor) throw std::runtime_error("Cipher algorithm not found"); // Set key processor->set_key(key); // Set IV processor->start(iv.bits_of()); Botan::secure_vector<uint8_t> buf(input.begin(), input.end()); processor->finish(buf); return buf; } std::string encrypt(std::string cleartext) { const std::string key_hex = "f00dbabef00dbabef00dbabef00dbabef00dbabef00dbabef00dbabef00dbabe"; const Botan::SymmetricKey key(key_hex); assert(key.length() == __KEY_LENGTH); Botan::AutoSeeded_RNG rng; __IV = rng.random_vec(__IV_LENGTH); const std::vector<uint8_t> input(cleartext.begin(), cleartext.end()); std::cerr << "Got " << input.size() << " bytes of input data.\n"; Botan::secure_vector<uint8_t> cipherblob = do_crypt(__CIPHER, input, key, __IV, Botan::Cipher_Dir::ENCRYPTION); return Botan::hex_encode(cipherblob); } std::string decrypt(const std::string& ciphertext) { const std::string key_hex = "f00dbabef00dbabef00dbabef00dbabef00dbabef00dbabef00dbabef00dbabe"; const Botan::SymmetricKey key(key_hex); assert(key.length() == __KEY_LENGTH); const std::vector<uint8_t> input = Botan::hex_decode(ciphertext); std::cerr << "Got " << input.size() << " bytes of ciphertext data.\n"; Botan::secure_vector<uint8_t> clearblob = do_crypt(__CIPHER, input, key, __IV, Botan::Cipher_Dir::DECRYPTION); return std::string(clearblob.begin(), clearblob.end()); } int main() { std::string cleartext = "Hello World"; auto ciphertext = encrypt(cleartext); std::cout << "ciphertext: " << ciphertext << std::endl; auto cleartext_decrypted = decrypt(ciphertext); std::cout << "cleartext_decrypted: " << cleartext_decrypted << std::endl; return 0; }
31.511364
115
0.665705
oxisto
904c01640bec1b7e437075078a10dabc531e405f
289
cpp
C++
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-06-03T17:33:51.000Z
2021-06-03T17:33:51.000Z
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-07-28T01:31:26.000Z
2021-07-28T01:31:26.000Z
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-12-19T15:34:50.000Z
2021-12-19T15:34:50.000Z
#include<iostream> #include<string> using namespace std; int main(){ //Array of string //Method 1 char *str[3]={"Hi","Hello","Bye"}; for(int i=0;i<3;i++){ cout << str[i]; } //Method 2 char s[3][10]={"Hi","Hello","Bye"}; for(int i=0;i<3;i++){ cout << s[i]; } return 0; }
15.210526
36
0.546713
suubh
904ef6abd8a9694a1d90e916290f1b867639a77b
983
cpp
C++
LEDA/test/graphics/window/lclock.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
LEDA/test/graphics/window/lclock.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
LEDA/test/graphics/window/lclock.cpp
2ashish/smallest_enclosing_circle
889916a3011ab2b649ab7f1fc1e042f879acecce
[ "MIT" ]
null
null
null
/******************************************************************************* + + LEDA 6.3 + + + lclock.c + + + Copyright (c) 1995-2010 + by Algorithmic Solutions Software GmbH + All rights reserved. + *******************************************************************************/ #include <LEDA/graphics/window.h> using namespace leda; #if defined(LEDA_STD_HEADERS) #include <ctime> #else #include <time.h> #endif #if defined(__BORLANDC__) #include <time.h> #endif static void display_time(window* wp) { time_t clock; time(&clock); tm* T = localtime(&clock); int s = T->tm_sec; int m = T->tm_min; int h = T->tm_hour; //double x = (wp->xmax() - wp->xmin())/2; //double y = (wp->ymax() - wp->ymin())/2; string time("%02d:%02d:%02d",h,m,s); wp->set_frame_label(time); } int main() { panel P; P.button("continue"); P.button("exit"); P.buttons_per_line(2); P.display(); P.start_timer(1000,display_time); P.read_mouse(); return 0; }
18.203704
80
0.525941
2ashish
904fbe01774a8a69afaee24e524997fd64c9e880
11,227
cpp
C++
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
/* * Modification History * * 2002-May-25 Jason Rohrer * Changed to use minorGems endian.h * Added a function for hashing an entire string to a hex digest. * Added a function for getting a raw digest. * Fixed a deletion bug. * * 2003-August-24 Jason Rohrer * Switched to use minorGems hex encoding. * * 2003-September-15 Jason Rohrer * Added support for hashing raw (non-string) data. * * 2003-September-21 Jason Rohrer * Fixed bug that was causing overwrite of input data. * * 2004-January-13 Jason Rohrer * Fixed system includes. * * 2013-January-7 Jason Rohrer * Added HMAC-SHA1 implementation. */ /* * sha1.c * * Originally witten by Steve Reid <steve@edmweb.com> * * Modified by Aaron D. Gifford <agifford@infowest.com> * * NO COPYRIGHT - THIS IS 100% IN THE PUBLIC DOMAIN * * The original unmodified version is available at: * ftp://ftp.funet.fi/pub/crypt/hash/sha/sha1.c * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR(S) OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ #include "sha1.h" #include <string.h> #include <stdio.h> // for hex encoding #include "minorGems/formats/encodingUtils.h" #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ #if __BYTE_ORDER == __LITTLE_ENDIAN #define blk0(i) (block->l[i] = (rol(block->l[i],24)&(sha1_quadbyte)0xFF00FF00) \ |(rol(block->l[i],8)&(sha1_quadbyte)0x00FF00FF)) #else #define blk0(i) block->l[i] #endif #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); typedef union _BYTE64QUAD16 { sha1_byte c[64]; sha1_quadbyte l[16]; } BYTE64QUAD16; /* Hash a single 512-bit block. This is the core of the algorithm. */ void SHA1_Transform(sha1_quadbyte state[5], sha1_byte buffer[64]) { sha1_quadbyte a, b, c, d, e; BYTE64QUAD16 *block; block = (BYTE64QUAD16*)buffer; /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; } /* SHA1_Init - Initialize new context */ void SHA1_Init(SHA_CTX* context) { /* SHA1 initialization constants */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } /* Run your data through this. */ void SHA1_Update(SHA_CTX *context, sha1_byte *data, unsigned int len) { unsigned int i, j; j = (context->count[0] >> 3) & 63; if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++; context->count[1] += (len >> 29); if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64-j)); SHA1_Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { SHA1_Transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } /* Add padding and return the message digest. */ void SHA1_Final(sha1_byte digest[SHA1_DIGEST_LENGTH], SHA_CTX *context) { sha1_quadbyte i, j; sha1_byte finalcount[8]; for (i = 0; i < 8; i++) { finalcount[i] = (sha1_byte)((context->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ } SHA1_Update(context, (sha1_byte *)"\200", 1); while ((context->count[0] & 504) != 448) { SHA1_Update(context, (sha1_byte *)"\0", 1); } /* Should cause a SHA1_Transform() */ SHA1_Update(context, finalcount, 8); for (i = 0; i < SHA1_DIGEST_LENGTH; i++) { digest[i] = (sha1_byte) ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } /* Wipe variables */ i = j = 0; memset(context->buffer, 0, SHA1_BLOCK_LENGTH); memset(context->state, 0, SHA1_DIGEST_LENGTH); memset(context->count, 0, 8); memset(&finalcount, 0, 8); } unsigned char *computeRawSHA1Digest( unsigned char *inData, int inDataLength ) { SHA_CTX context; SHA1_Init( &context ); // copy into buffer, since this SHA1 implementation seems to overwrite // parts of the data buffer. unsigned char *buffer = new unsigned char[ inDataLength ]; memcpy( (void *)buffer, (void *)inData, inDataLength ); SHA1_Update( &context, buffer, inDataLength ); delete [] buffer; unsigned char *digest = new unsigned char[ SHA1_DIGEST_LENGTH ]; SHA1_Final( digest, &context ); return digest; } unsigned char *computeRawSHA1Digest( char *inString ) { SHA_CTX context; SHA1_Init( &context ); // copy into buffer, since this SHA1 implementation seems to overwrite // parts of the data buffer. int dataLength = strlen( inString ); unsigned char *buffer = new unsigned char[ dataLength ]; memcpy( (void *)buffer, (void *)inString, dataLength ); SHA1_Update( &context, buffer, strlen( inString ) ); delete [] buffer; unsigned char *digest = new unsigned char[ SHA1_DIGEST_LENGTH ]; SHA1_Final( digest, &context ); return digest; } char *computeSHA1Digest( char *inString ) { unsigned char *digest = computeRawSHA1Digest( inString ); char *digestHexString = hexEncode( digest, SHA1_DIGEST_LENGTH ); delete [] digest; return digestHexString; } char *computeSHA1Digest( unsigned char *inData, int inDataLength ) { unsigned char *digest = computeRawSHA1Digest( inData, inDataLength ); char *digestHexString = hexEncode( digest, SHA1_DIGEST_LENGTH ); delete [] digest; return digestHexString; } // returns new data buffer of length inALength + inBLength static unsigned char *dataConcat( unsigned char *inA, int inALength, unsigned char *inB, int inBLength ) { int netLength = inALength + inBLength; unsigned char *netData = new unsigned char[ netLength ]; int i=0; for( int j=0; j<inALength; j++ ) { netData[i] = inA[j]; i++; } for( int j=0; j<inBLength; j++ ) { netData[i] = inB[j]; i++; } return netData; } #include "minorGems/util/stringUtils.h" char *hmac_sha1( const char *inKey, const char *inData ) { unsigned char *keyRaw = (unsigned char*)stringDuplicate( inKey ); int keyLength = strlen( inKey ); //unsigned char *computeRawSHA1Digest( unsigned char *inData, int inDataLength // shorten long keys down to 20 byte hash of key, if needed if( keyLength > SHA1_BLOCK_LENGTH ) { unsigned char *newKey = computeRawSHA1Digest( keyRaw, keyLength ); delete [] keyRaw; keyRaw = newKey; keyLength = SHA1_DIGEST_LENGTH; } // pad key out to blocksize with zeros if( keyLength < SHA1_BLOCK_LENGTH ) { unsigned char *newKey = new unsigned char[ SHA1_BLOCK_LENGTH ]; memset( newKey, 0, SHA1_BLOCK_LENGTH ); memcpy( newKey, keyRaw, keyLength ); delete [] keyRaw; keyRaw = newKey; keyLength = SHA1_BLOCK_LENGTH; } // computer inner and outer keys by XORing with data block unsigned char *outerKey = new unsigned char[ keyLength ]; unsigned char *innerKey = new unsigned char[ keyLength ]; for( int i=0; i<keyLength; i++ ) { outerKey[i] = 0x5c ^ keyRaw[i]; innerKey[i] = 0x36 ^ keyRaw[i]; } delete [] keyRaw; int dataLength = strlen( inData ); int innerDataLength = keyLength +dataLength; unsigned char *innerData = dataConcat( innerKey, keyLength, (unsigned char*)inData, dataLength ); delete [] innerKey; unsigned char *innerHash = computeRawSHA1Digest( innerData, innerDataLength ); delete [] innerData; int outerDataLength = keyLength + SHA1_DIGEST_LENGTH; unsigned char *outerData = dataConcat( outerKey, keyLength, innerHash, SHA1_DIGEST_LENGTH ); delete [] outerKey; delete [] innerHash; char *digest = computeSHA1Digest( outerData, outerDataLength ); delete [] outerData; return digest; }
30.180108
84
0.607999
PhilipLudington
9056532d5533384a189b6b5822ec03d8b0ba92e2
4,137
cpp
C++
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
/* * Copyright 2018 Mike Reed */ #include "GPath.h" #include "GMatrix.h" GPath::GPath() {} GPath::~GPath() {} GPath& GPath::operator=(const GPath& src) { if (this != &src) { fPts = src.fPts; fVbs = src.fVbs; } return *this; } GPath& GPath::reset() { fPts.clear(); fVbs.clear(); return *this; } void GPath::dump() const { Iter iter(*this); GPoint pts[GPath::kMaxNextPoints]; for (;;) { switch (iter.next(pts)) { case kMove: printf("M %g %g\n", pts[0].fX, pts[0].fY); break; case kLine: printf("L %g %g\n", pts[1].fX, pts[1].fY); break; case kQuad: printf("Q %g %g %g %g\n", pts[1].fX, pts[1].fY, pts[2].fX, pts[2].fY); break; case kCubic: printf("C %g %g %g %g %g %g\n", pts[1].fX, pts[1].fY, pts[2].fX, pts[2].fY, pts[3].fX, pts[3].fY); break; case kDone: return; } } } GPath& GPath::quadTo(GPoint p1, GPoint p2) { assert(fVbs.size() > 0); fPts.push_back(p1); fPts.push_back(p2); fVbs.push_back(kQuad); return *this; } GPath& GPath::cubicTo(GPoint p1, GPoint p2, GPoint p3) { assert(fVbs.size() > 0); fPts.push_back(p1); fPts.push_back(p2); fPts.push_back(p3); fVbs.push_back(kCubic); return *this; } ///////////////////////////////////////////////////////////////// GPath::Iter::Iter(const GPath& path) { fPrevMove = nullptr; fCurrPt = path.fPts.data(); fCurrVb = path.fVbs.data(); fStopVb = fCurrVb + path.fVbs.size(); } GPath::Verb GPath::Iter::next(GPoint pts[]) { assert(fCurrVb <= fStopVb); if (fCurrVb == fStopVb) { return kDone; } Verb v = *fCurrVb++; switch (v) { case kMove: fPrevMove = fCurrPt; pts[0] = *fCurrPt++; break; case kLine: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; break; case kQuad: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; break; case kCubic: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; pts[3] = *fCurrPt++; break; case kDone: assert(false); // not reached } return v; } GPath::Edger::Edger(const GPath& path) { fPrevMove = nullptr; fCurrPt = path.fPts.data(); fCurrVb = path.fVbs.data(); fStopVb = fCurrVb + path.fVbs.size(); fPrevVerb = kDone; } GPath::Verb GPath::Edger::next(GPoint pts[]) { assert(fCurrVb <= fStopVb); bool do_return = false; while (fCurrVb < fStopVb) { switch (*fCurrVb++) { case kMove: if (fPrevVerb == kLine) { pts[0] = fCurrPt[-1]; pts[1] = *fPrevMove; do_return = true; } fPrevMove = fCurrPt++; fPrevVerb = kMove; break; case kLine: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; fPrevVerb = kLine; return kLine; case kQuad: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; fPrevVerb = kQuad; return kQuad; case kCubic: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; pts[3] = *fCurrPt++; fPrevVerb = kCubic; return kCubic; default: assert(false); // not reached } if (do_return) { return kLine; } } if (fPrevVerb >= kLine && fPrevVerb <= kCubic) { pts[0] = fCurrPt[-1]; pts[1] = *fPrevMove; fPrevVerb = kDone; return kLine; } else { return kDone; } }
25.22561
87
0.435581
jkchang62
90566595bade6f3dbd13606257fd7518e62bbca4
3,508
cc
C++
SimFastTiming/FastTimingCommon/src/MTDShapeBase.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-24T19:10:26.000Z
2019-02-19T11:45:32.000Z
SimFastTiming/FastTimingCommon/src/MTDShapeBase.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
3
2018-08-23T13:40:24.000Z
2019-12-05T21:16:03.000Z
SimFastTiming/FastTimingCommon/src/MTDShapeBase.cc
nistefan/cmssw
ea13af97f7f2117a4f590a5e654e06ecd9825a5b
[ "Apache-2.0" ]
5
2018-08-21T16:37:52.000Z
2020-01-09T13:33:17.000Z
#include "FWCore/MessageLogger/interface/MessageLogger.h" #include "SimFastTiming/FastTimingCommon/interface/MTDShapeBase.h" MTDShapeBase::~MTDShapeBase() { } MTDShapeBase::MTDShapeBase() : qNSecPerBin_ ( 1./kNBinsPerNSec ), indexOfMax_ ( 0 ), timeOfMax_ ( 0. ), shape_ ( DVec(k1NSecBinsTotal, 0.0) ) { } std::array<float,3> MTDShapeBase::timeAtThr(const float scale, const float threshold1, const float threshold2) const { std::array<float,3> times_tmp = { {0., 0., 0.} }; // --- Check if the pulse amplitude is greater than threshold 2 if ( shape_[indexOfMax_]*scale < threshold2 ) return times_tmp; // --- Find the times corresponding to thresholds 1 and 2 on the pulse leading edge // NB: To speed up the search we loop only on the rising edge unsigned int index_LT1 = 0; unsigned int index_LT2 = 0; for( unsigned int i=0; i<indexOfMax_; ++i ){ float amplitude = shape_[i]*scale; if( amplitude > threshold1 && index_LT1 == 0 ) index_LT1 = i; if( amplitude > threshold2 && index_LT2 == 0 ){ index_LT2 = i; break; } } // --- Find the time corresponding to thresholds 1 on the pulse falling edge unsigned int index_FT1 = 0; for( unsigned int i=shape_.size()-1; i>indexOfMax_; i-- ){ float amplitude = shape_[i]*scale; if( amplitude>threshold1 && index_FT1==0){ index_FT1 = i+1; break; } } if ( index_LT1 != 0 ) times_tmp[0] = linear_interpolation( threshold1, (index_LT1-1)*qNSecPerBin_, index_LT1*qNSecPerBin_, shape_[index_LT1-1]*scale, shape_[index_LT1]*scale ); if ( index_LT2 != 0 ) times_tmp[1] = linear_interpolation( threshold2, (index_LT2-1)*qNSecPerBin_, index_LT2*qNSecPerBin_, shape_[index_LT2-1]*scale, shape_[index_LT2]*scale ); if ( index_FT1 != 0 ) times_tmp[2] = linear_interpolation( threshold1, (index_FT1-1)*qNSecPerBin_, index_FT1*qNSecPerBin_, shape_[index_FT1-1]*scale, shape_[index_FT1]*scale ); return times_tmp; } unsigned int MTDShapeBase::indexOfMax() const { return indexOfMax_; } double MTDShapeBase::timeOfMax() const { return timeOfMax_; } void MTDShapeBase::buildMe() { // --- Fill the vector with the pulse shape fillShape( shape_ ); // --- Find the index of maximum for( unsigned int i=0; i<shape_.size(); ++i ) { if( shape_[indexOfMax_] < shape_[i] ) indexOfMax_ = i; } if ( indexOfMax_ != 0 ) timeOfMax_ = indexOfMax_*qNSecPerBin_; } unsigned int MTDShapeBase::timeIndex( double aTime ) const { const unsigned int index = aTime*kNBinsPerNSec; const bool bad = ( k1NSecBinsTotal <= index ); if( bad ) LogDebug("MTDShapeBase") << " MTD pulse shape requested for out of range time " << aTime; return ( bad ? k1NSecBinsTotal : index ) ; } double MTDShapeBase::operator() ( double aTime ) const { // return pulse amplitude for request time in ns const unsigned int index ( timeIndex( aTime ) ) ; return ( k1NSecBinsTotal == index ? 0 : shape_[ index ] ) ; } double MTDShapeBase::linear_interpolation(const double& y, const double& x1, const double& x2, const double& y1, const double& y2) const { if ( x1 == x2 ) throw cms::Exception("BadValue") << " MTDShapeBase: Trying to interpolate two points with the same x coordinate!"; double a = (y2-y1)/(x2-x1); double b = y1 - a*x1; return (y-b)/a; }
21.78882
118
0.645667
nistefan
905730d5bb507964f80cdf24c2ed765b7ebbdd09
614
cpp
C++
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
1
2021-10-05T10:09:32.000Z
2021-10-05T10:09:32.000Z
#include <bits/stdc++.h> using namespace std; void all(int a[], int n, int x, int i) { if (n == 0) return; if (a[0] == x) { cout << i << " "; } i++; return all(a + 1, n - 1, x, i); } void all1(int a[], int n, int x) { if (n == 0) return; if (a[n - 1] == x) cout << n - 1 << " "; return all1(a, n - 1, x); } int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int x; cin >> x; int i = 0; all(a, n, x, i); cout << endl; all1(a, n, x); cout << endl; }
14.27907
38
0.369707
Mitushi-23
905aafcc250a9489837ef2f8c9bc61b823efb726
13,683
cpp
C++
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "gmock/gmock.h" #include <utilities/zip.h> #include <communication/communication.h> #include <cstring> #include <fstream> #include <sys/time.h> // Mock function that is only available using root privilages int settimeofday (const struct timeval *__tv, const struct timezone *__tz) __THROW { (void)__tv; (void)__tz; return 0; } using namespace comm; namespace { const char compressed_file_name[] = "compressed_123.mp3"; int LinesCount(std::string& s) { return std::count(s.begin(), s.end(), '\n'); } std::string ReadLine(std::string& s, int line_num) { std::istringstream f(s); std::string line; int line_count = 0; while (std::getline(f, line)) { ++line_count; if (line_count == line_num) { return line; } } return ""; } } class CommunicationFixture : public ::testing::Test { public: CommunicationFixture() : logger_m(false, true) , config_manager_m(logger_m) { utils::ZipCompress("123.mp3", compressed_file_name); config_manager_m.ParseConfigFile("audio_app_cfg.xml"); } ~CommunicationFixture() { std::string file_to_remove = "rm /tmp/"; file_to_remove += compressed_file_name; system(file_to_remove.c_str()); } virtual void SetUp() {} virtual void TearDown() {} protected: utils::Logger logger_m; config::ConfigManager config_manager_m; }; // Wrong command structure TEST_F (CommunicationFixture, EmptyCommand) { // Empty Command: // "" comm::Communication communication(config_manager_m, logger_m); char command[1024] = ""; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, WrongCommand) { // Wrong Command: // TCP_STATUS\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, WrongCommandStructure) { // Wrong Command: // TCP_STATUS\n // WWRONG_ATTR\n // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nWWRONG_ATTR\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, NoNewLineAtEndOfCommand) { // Wrong Command: // TCP_STATUS\n // END comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nEND"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, MissingNewLineInCommand) { // Wrong Command: // TCP_STATUS // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUSEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } // TCP_STATUS TEST_F (CommunicationFixture, StatusCommand) { // Command: // TCP_STATUS\n // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_7_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } //TCP_PLAY TEST_F (CommunicationFixture, PlayOncePlayOncePlayWrongFileCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // ONCE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); // Rename file to try open file that no longer exists rename("/tmp/compressed_123.mp3", "/tmp/tmp.mp3"); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:3" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); rename("/tmp/tmp.mp3", "/tmp/compressed_123.mp3"); } TEST_F (CommunicationFixture, PlayInLoopCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // ONCE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nIN_LOOP\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_IN_LOOP" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } TEST_F (CommunicationFixture, PlayWrongModeCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // WRONG_MODE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nWRONG_MODE\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:2" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } // TCP_STOP TEST_F (CommunicationFixture, StopPlayStopCommand) { // Command: // TCP_STOP\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_STOP\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_2_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_STOP\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_2_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } //TCP_SET_TIME TEST_F (CommunicationFixture, SetTimeCommand) { // Command: //TCP_SET_TIME\n //GG:MM:SS_DD.MM.RRRR\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_SET_TIME\n12:12:12_01.01.1971\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_0_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); } // TCP_SET_CFG TEST_F (CommunicationFixture, SetCfgCommand) { // Command: // TCP_SET_CFG\n // length_in_bytes\n // charactes_of_configuration\n // END\n std::string config = "<?xml version=\"1.0\"?>\n" "<audio_app_cfg>\n" "\t<network>\n" "\t\t<ip>127.0.0.1</ip>\n" "\t\t<mask>255.255.255.0</mask>\n" "\t\t<gateway>192.168.0.1</gateway>\n" "\t\t<port>9999</port>\n" "\t</network>\n" "\t<sounds>\n" "\t\t<sound>file1</sound>\n" "\t\t<sound>file2</sound>\n" "\t\t<sound>file3</sound>\n" "\t\t<sound>file4</sound>\n" "\t</sounds>\n" "</audio_app_cfg>\n"; std::string msg_cmd = "TCP_SET_CFG\n"; std::ostringstream oss; oss << config.length() << std::endl; msg_cmd += oss.str(); msg_cmd += config; msg_cmd += "END\n"; comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand(msg_cmd.c_str(), reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_3_RECEIVED" ,ReadLine(reply_str, 1).c_str()); // Error code was not tested as on real system file can exists ath this will succes on others will fail writtung EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); } // TCP_GET_CFG TEST_F (CommunicationFixture, GetCfgCommand) { // Command: //TCP_GET_CFG\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_GET_CFG\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(6, lines_count); EXPECT_STREQ("COMMAND_4_RECEIVED" ,ReadLine(reply_str, 1).c_str()); // Do not test following lines as it vary depending on sytem it runs tests // 2nd line: Time // 3rd line: size // 4th line: config content EXPECT_STREQ("END" ,ReadLine(reply_str, 6).c_str()); } // TCP_SET_VOLUME TEST_F (CommunicationFixture, SetVolumeCommand) { // Command: //TCP_SET_VOLUME\n //20\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_SET_VOLUME\n20\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_5_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } // TCP_RESET TEST_F (CommunicationFixture, RebootCallback) { // Command: // TCP_RESET\n // END\n bool reboot_called = false; comm::Communication communication(config_manager_m, logger_m, [&reboot_called]() { reboot_called = true; }); char command[1024] = "TCP_RESET\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_6_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); EXPECT_TRUE(reboot_called); }
32.044496
116
0.66652
Kurossa
905d187b46cf46d791d0e4c0eb5f5f6e7b1b3dca
7,092
cpp
C++
src/QPMatrix.cpp
Isaac-Kwon/c-qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
null
null
null
src/QPMatrix.cpp
Isaac-Kwon/c-qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
1
2021-04-12T07:24:39.000Z
2021-04-12T07:25:01.000Z
src/QPMatrix.cpp
Isaac-Kwon/qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
null
null
null
#include "iostream" #include "stdlib.h" #include "stdarg.h" #include "sstream" #include "QPMatrix.hpp" QPMatrix::QPMatrix(): fElement(0), fM(0), fN(0){ // Init(); } QPMatrix::QPMatrix(const int n): fElement(0), fM(n), fN(n){ Init(); } QPMatrix::QPMatrix(const int m, const int n): fElement(0), fM(m), fN(n){ Init(); } QPMatrix::QPMatrix(const int m, const int n, const int npassed, ...): fElement(0), fM(m), fN(n){ Init(); va_list vl; va_start( vl, npassed ); for(int i=0; i<m*n && i<npassed; i++){ fElement[i] = va_arg(vl, double); } va_end(vl); } QPMatrix::QPMatrix(QPVector& vec, int ncomp): fElement(0), fM(ncomp), fN(1){ Init(); for(int i=0; i<ncomp && i<3; i++){ fElement[i] = vec(i); } } QPMatrix::QPMatrix(const QPMatrix& other): fElement(0), fM(other.fM), fN(other.fN){ Init(); int fMN = fM*fN; for(int i=0; i<fMN; i++){ fElement[i] = other.fElement[i]; } } QPMatrix& QPMatrix::operator=(const QPMatrix& other){ Freeing(); fM = other.fM; fN = other.fN; Init(); for(int i=0; i<fM*fN; i++){ fElement[i] = other.fElement[i]; // std::cout<<"COPIED\t"<<fElement[i]<<"\t"<<At(i)<<std::endl; } return *this; } QPMatrix::~QPMatrix(){ Freeing(); } void QPMatrix::Init(){ fElement = (double*) std::malloc(fM*fN*sizeof(double)); for(int i=0; i<fN*fM; i++){ fElement[i] = 0.; } } void QPMatrix::Freeing(){ // if(fElement == nullptr){ // return; // } std::free(fElement); } bool QPMatrix::IsInside(int i){ if(i >= 0 && i< fN*fM) return true; return false; } bool QPMatrix::IsInside(int i, int j){ if (i>=0 && i<fM && j>=0 && j<fN){ return true; } return false; } double QPMatrix::At(int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::At(1) - Out if index"<<"["<<i<<"]"<<std::endl; return -1; } return fElement[i]; } double QPMatrix::At(int i, int j){ if( !IsInside(i,j) ){ std::cout<<"QPMatrix::At(2) - Out if index "<<"["<<i<<","<<j<<"]"<<std::endl; return -1; } return fElement[i*fN+j]; } bool QPMatrix::IsSameShape(QPMatrix & other){ if(fN == other.fN && fM == other.fM) return true; return false; } bool QPMatrix::IsTransShape(QPMatrix & other){ if(fN == other.fM && fM == other.fN) return true; return false; } double& QPMatrix::operator[](int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::operator[](1) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i]; } double& QPMatrix::operator()(int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::operator()(1) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i]; } double& QPMatrix::operator()(int i, int j){ if( !IsInside(i, j) ){ std::cout<<"QPMatrix::operator()(2) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i*fM+j]; } double QPMatrix::Det(){ if(fM != fN){ std::cout<<"QPMatrix::Det() - Determinant can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return 0.; } if(fM==0) return 0.; if(fM==1) return At(0); if(fM==2){ return At(0,0)*At(1,1) - At(0,1)*At(1,0); } double ans = 0; for(int i=0; i<fN; i++){ ans += pow(-1, i)*At(0,i)*SubMatrix(0, i).Det(); } return ans; } double QPMatrix::Trace(){ double ans = 0; int ii = fN>fM ? fM : fN; for(int i=0; i<ii; i++){ ans += operator()(i,i); } return ans; } QPMatrix QPMatrix::SubMatrix(const int i_, const int j_){ QPMatrix ans = QPMatrix(fM-1, fN-1); for(int i=0; i<fM-1; i++){ for(int j=0; j<fN-1; j++){ ans(i,j) = At( i < i_ ? i : i+1, j < j_ ? j : j+1 ); } } return ans; } double QPMatrix::Cofactor(const int i, const int j){ if(fM != fN){ std::cout<<"QPMatrix::Cofactor() - Cofactor can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return 0; } return pow(-1, i+j) * (SubMatrix(i,j).Det()); } QPMatrix QPMatrix::Inverse(){ if(fM != fN){ std::cout<<"QPMatrix::Inverse() - Inverse can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return QPMatrix(); } double det = Det(); if(det<0.0000000001 && det>-0.0000000001 ){ std::cout<<"QPMatrix::Inverse() - Determinant is near zero. No inverse matrix "<<"["<<det<<"]"<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(fM, fN); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ ans(i,j) = Cofactor(j,i); } } ans*=(1/Det()); return ans; } QPMatrix QPMatrix::Transpose(){ QPMatrix ans(fN, fM); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ ans(j,i) = At(i,j); } } return ans; } QPMatrix operator*(QPMatrix self, double other){ QPMatrix ans = QPMatrix(self); for(int i=0; i<(self.fN*self.fM); i++){ ans(i) *= other; } return ans; } QPMatrix operator*(double other, QPMatrix self){ QPMatrix ans = QPMatrix(self); for(int i=0; i<(self.fN*self.fM); i++){ ans(i) *= other; } return ans; } QPMatrix operator*(QPMatrix self, QPMatrix other){ if(self.fN != other.fM){ std::cout<<"QPMatrix::operator*()(3) - inner part of 2 matrices are not same : "<<self.fN<<", "<<other.fM<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(self.fM, other.fN); for(int i=0; i<(ans.fM); i++){ for(int j=0; j<(ans.fN); j++){ for(int k=0; k<(self.fN); k++){ ans(i,j)+= self.At(i,k) * other.At(k,j); } } } return ans; } QPMatrix operator+(QPMatrix & self, QPMatrix & other){ if(! self.IsSameShape(other) ){ std::cout<<"operator+ (QPMatrix&, QPMatrix&) - Not same shape"<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(self.fM, self.fN); int length = self.fN * self.fM; for(int i=0; i<length; i++){ ans[i] = self[i] + other[i]; } return ans; } QPMatrix operator-(QPMatrix & self, QPMatrix & other){ if(! self.IsSameShape(other) ){ std::cout<<"operator- (QPMatrix&, QPMatrix&) - Not same shape"<<std::endl; return QPMatrix(); } QPMatrix ans(self.fM, self.fN); int length = self.fN * self.fM; for(int i=0; i<length; i++){ ans[i] = self[i] - other[i]; } return ans; } std::string QPMatrix::Print(bool quite){ std::ostringstream anss; anss.precision(4); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ anss << At(i,j) << "\t"; } anss<<std::endl; } anss.unsetf(std::ios::fixed); std::string ans = anss.str(); if(!quite){ std::cout<<ans; } return ans; }
21.754601
126
0.516356
Isaac-Kwon
905d8c3c349e1684c79a64080eeff8a41ca4e8a2
6,485
cpp
C++
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
643
2021-08-02T05:04:20.000Z
2022-03-27T22:56:02.000Z
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
13
2021-09-01T12:41:42.000Z
2022-03-28T11:08:44.000Z
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
16
2021-08-31T07:08:45.000Z
2022-02-14T12:36:15.000Z
/* * Copyright (C) 1994-2021 OpenTV, Inc. and Nagravision S.A. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "RSkTextLayoutManager.h" using namespace skia::textlayout; namespace facebook { namespace react { Point calculateFramePoint( Point origin , Size rect , float layoutWidth) { /* Calculate the (x,y) cordinates of fragment attachments,based on the fragment width provided*/ if(origin.x + rect.width < layoutWidth) origin.x += rect.width ; else { auto delta = layoutWidth - origin.x ; origin.x = rect.width - delta ; origin.y += rect.height; } return origin; } TextAlign convertTextAlign (TextAlignment alignment) { switch(alignment) { case TextAlignment::Natural : case TextAlignment::Left : return TextAlign::kLeft; case TextAlignment::Center : return TextAlign::kCenter; case TextAlignment::Right : return TextAlign::kRight; case TextAlignment::Justified : return TextAlign::kJustify; } return TextAlign::kLeft; } SkPaint convertTextColor ( SharedColor textColor ) { SkPaint paint; float ratio = 255.9999; auto color = colorComponentsFromColor(textColor); paint.setColor(SkColorSetARGB( color.alpha * ratio, color.red * ratio, color.green * ratio, color.blue * ratio)); paint.setAntiAlias(true); return paint; } RSkTextLayoutManager::RSkTextLayoutManager() { /* Set default font collection */ collection_ = sk_make_sp<FontCollection>(); collection_->setDefaultFontManager(SkFontMgr::RefDefault()); } TextMeasurement RSkTextLayoutManager::doMeasure (AttributedString attributedString, ParagraphAttributes paragraphAttributes, LayoutConstraints layoutConstraints) const { TextMeasurement::Attachments attachments; ParagraphStyle paraStyle; Size size; std::shared_ptr<ParagraphBuilder> builder = std::static_pointer_cast<ParagraphBuilder>(std::make_shared<ParagraphBuilderImpl>(paraStyle,collection_)); buildParagraph(attributedString, paragraphAttributes, false, builder); auto paragraph = builder->Build(); paragraph->layout(layoutConstraints.maximumSize.width); size.width = paragraph->getMaxIntrinsicWidth() < paragraph->getMaxWidth() ? paragraph->getMaxIntrinsicWidth() : paragraph->getMaxWidth(); size.height = paragraph->getHeight(); Point attachmentPoint = calculateFramePoint({0,0}, size, layoutConstraints.maximumSize.width); for (auto const &fragment : attributedString.getFragments()) { if (fragment.isAttachment()) { Rect rect; rect.size.width = fragment.parentShadowView.layoutMetrics.frame.size.width; rect.size.height = fragment.parentShadowView.layoutMetrics.frame.size.height; /* TODO : We will be unable to calculate exact (x,y) cordinates for the attachments*/ /* Reason : attachment fragment width is clamped width wrt layout width; */ /* so we do not know actual position at which the previous attachment cordinate ends*/ /* But we need to still calculate total container height here, from all attachments */ /* NOTE : height value calculated would be approximate,since we lack the knowledge of actual frag width here*/ attachmentPoint = calculateFramePoint(attachmentPoint, rect.size, layoutConstraints.maximumSize.width); attachments.push_back(TextMeasurement::Attachment{rect, false}); } } /* Update the container height from all attachments */ if(!attachments.empty()) { size.height = attachmentPoint.y + attachments[attachments.size()-1].frame.size.height; } return TextMeasurement{size, attachments}; } uint32_t RSkTextLayoutManager::buildParagraph (AttributedString attributedString, ParagraphAttributes paragraphAttributes, bool fontDecorationRequired, std::shared_ptr<ParagraphBuilder> builder) const { uint32_t attachmentCount = 0; std::unique_ptr<Paragraph> fPara; TextStyle style; ParagraphStyle paraStyle; auto fontSize = TextAttributes::defaultTextAttributes().fontSize; auto fontSizeMultiplier = TextAttributes::defaultTextAttributes().fontSizeMultiplier; for(auto &fragment: attributedString.getFragments()) { if(fragment.isAttachment()) { attachmentCount++; continue; } fontSize = !std::isnan(fragment.textAttributes.fontSize) ? fragment.textAttributes.fontSize : TextAttributes::defaultTextAttributes().fontSize; fontSizeMultiplier = !std::isnan(fragment.textAttributes.fontSizeMultiplier) ? fragment.textAttributes.fontSizeMultiplier : TextAttributes::defaultTextAttributes().fontSizeMultiplier; style.setFontSize(fontSize * fontSizeMultiplier); style.setFontFamilies({SkString(fragment.textAttributes.fontFamily.c_str())}); /* Build paragraph considering text decoration attributes*/ /* Required during text paint */ if(fontDecorationRequired) { style.setForegroundColor(convertTextColor(fragment.textAttributes.foregroundColor ? fragment.textAttributes.foregroundColor : TextAttributes::defaultTextAttributes().foregroundColor)); style.setBackgroundColor(convertTextColor(fragment.textAttributes.backgroundColor ? fragment.textAttributes.backgroundColor : TextAttributes::defaultTextAttributes().backgroundColor)); } if(fragment.textAttributes.alignment.has_value()) paraStyle.setTextAlign(convertTextAlign(fragment.textAttributes.alignment.value())); builder->setParagraphStyle(paraStyle); builder->pushStyle(style); builder->addText(fragment.string.c_str(),fragment.string.length()); } return attachmentCount; } } // namespace react } // namespace facebook
42.94702
227
0.658751
react-native-skia
905fc45188fbb58d1eeab6f6c0ab850029cf3ed6
2,344
cc
C++
ehpc/src/model/ListInvocationStatusResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-02-02T03:54:39.000Z
2021-12-13T01:32:55.000Z
ehpc/src/model/ListInvocationStatusResult.cc
iamzken/aliyun-openapi-cpp-sdk
3c991c9ca949b6003c8f498ce7a672ea88162bf1
[ "Apache-2.0" ]
89
2018-03-14T07:44:54.000Z
2021-11-26T07:43:25.000Z
ehpc/src/model/ListInvocationStatusResult.cc
aliyun/aliyun-openapi-cpp-sdk
0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36
[ "Apache-2.0" ]
69
2018-01-22T09:45:52.000Z
2022-03-28T07:58:38.000Z
/* * Copyright 2009-2017 Alibaba Cloud 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 <alibabacloud/ehpc/model/ListInvocationStatusResult.h> #include <json/json.h> using namespace AlibabaCloud::EHPC; using namespace AlibabaCloud::EHPC::Model; ListInvocationStatusResult::ListInvocationStatusResult() : ServiceResult() {} ListInvocationStatusResult::ListInvocationStatusResult(const std::string &payload) : ServiceResult() { parse(payload); } ListInvocationStatusResult::~ListInvocationStatusResult() {} void ListInvocationStatusResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allInvokeInstancesNode = value["InvokeInstances"]["InvokeInstance"]; for (auto valueInvokeInstancesInvokeInstance : allInvokeInstancesNode) { InvokeInstance invokeInstancesObject; if(!valueInvokeInstancesInvokeInstance["InstanceId"].isNull()) invokeInstancesObject.instanceId = valueInvokeInstancesInvokeInstance["InstanceId"].asString(); if(!valueInvokeInstancesInvokeInstance["InstanceInvokeStatus"].isNull()) invokeInstancesObject.instanceInvokeStatus = valueInvokeInstancesInvokeInstance["InstanceInvokeStatus"].asString(); invokeInstances_.push_back(invokeInstancesObject); } if(!value["CommandId"].isNull()) commandId_ = value["CommandId"].asString(); if(!value["InvokeStatus"].isNull()) invokeStatus_ = value["InvokeStatus"].asString(); } std::string ListInvocationStatusResult::getInvokeStatus()const { return invokeStatus_; } std::string ListInvocationStatusResult::getCommandId()const { return commandId_; } std::vector<ListInvocationStatusResult::InvokeInstance> ListInvocationStatusResult::getInvokeInstances()const { return invokeInstances_; }
31.675676
118
0.784556
iamzken
9061d5688be35392bb652f23bd14aedb69460002
3,943
cpp
C++
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
12
2021-07-24T18:33:22.000Z
2022-03-12T16:20:49.000Z
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
null
null
null
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
3
2021-08-04T02:27:12.000Z
2022-03-13T08:43:24.000Z
// Copyright 2021 NVIDIA CORPORATION // SPDX-License-Identifier: Apache-2.0 // Implementation functions for Julia Set compute shader. #include "julia.hpp" #include "nvh/container_utils.hpp" #include "make_compute_pipeline.hpp" // GLSL polyglot #include "shaders/julia.h" Julia::Julia(VkDevice device, VkPhysicalDevice physicalDevice, bool dumpPipelineStats, uint32_t textureWidth, uint32_t textureHeight) : m_device(device) , m_scopedImage(device, physicalDevice) { // Push constant defaults update(0.0, 64); // Set up color texture. m_scopedImage.reallocImage(textureWidth, textureHeight); // Set up compute pipeline. uint32_t pcSize = uint32_t(sizeof(JuliaPushConstant)); VkPushConstantRange range = {VK_SHADER_STAGE_COMPUTE_BIT, 0, pcSize}; VkDescriptorSetLayout descriptorLayout = m_scopedImage.getStorageDescriptorSetLayout(); makeComputePipeline(m_device, "julia.comp.spv", dumpPipelineStats, 1, &descriptorLayout, 1, &range, &m_pipeline, &m_pipelineLayout); } Julia::~Julia() { // Destroy pipelines. vkDestroyPipelineLayout(m_device, m_pipelineLayout, nullptr); vkDestroyPipeline(m_device, m_pipeline, nullptr); } void Julia::resize(uint32_t x, uint32_t y) { m_scopedImage.reallocImage(x, y); update(0.0, 0); } uint32_t Julia::getWidth() const { return m_scopedImage.getImageWidth(); } uint32_t Julia::getHeight() const { return m_scopedImage.getImageHeight(); } void Julia::update(double dt, int maxIterations) { m_alphaNormalized += uint32_t(dt * 0x0600'0000); double alphaRadians = m_alphaNormalized * 1.4629180792671596e-09; m_pushConstant.c_real = float(0.7885 * sin(alphaRadians)); m_pushConstant.c_imag = float(0.7885 * cos(alphaRadians)); float textureWidth = float(m_scopedImage.getImageWidth()); float textureHeight = float(m_scopedImage.getImageHeight()); m_pushConstant.offset_real = -2.0f; m_pushConstant.scale = 4.0f / textureWidth; m_pushConstant.offset_imag = 2.0f * textureHeight / textureWidth; if (maxIterations > 0) m_pushConstant.maxIterations = int32_t(maxIterations); } void Julia::cmdFillColorTexture(VkCommandBuffer cmdBuf) { // Transition color texture image to general layout, protect // earlier reads. VkImageMemoryBarrier imageBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, 0, 0, m_scopedImage.getImage(), {VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, 1} }; vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageBarrier); // Bind pipeline, push constant, and descriptors. vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, m_pipeline); VkDescriptorSet descriptorSet = m_scopedImage.getStorageDescriptorSet(); vkCmdPushConstants(cmdBuf, m_pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(m_pushConstant), &m_pushConstant); vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, m_pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); // Fill the image. vkCmdDispatch(cmdBuf, (m_scopedImage.getImageWidth() + 15) / 16, (m_scopedImage.getImageHeight() + 15) / 16, 1); // Pipeline barrier. VkMemoryBarrier barrier = { VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT }; vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); }
35.522523
75
0.70454
nvpro-samples
90622b97132a1cf7946f4a85652e79249a2fc218
171
hpp
C++
include/wmma_extension/tcec/detail/wmma_extension_include.hpp
enp1s0/wmma_extension
665a7a1f469ecffb8eaf609ba07f9b9720c52813
[ "MIT" ]
7
2020-02-18T00:09:28.000Z
2021-02-19T17:33:01.000Z
include/wmma_extension/tcec/detail/wmma_extension_include.hpp
wmmae/wmma_extension
665a7a1f469ecffb8eaf609ba07f9b9720c52813
[ "MIT" ]
null
null
null
include/wmma_extension/tcec/detail/wmma_extension_include.hpp
wmmae/wmma_extension
665a7a1f469ecffb8eaf609ba07f9b9720c52813
[ "MIT" ]
1
2021-01-13T12:22:49.000Z
2021-01-13T12:22:49.000Z
#ifndef __WMMAE_MMA_F32_F32_DETAIL_INCLUDE_HPP__ #define __WMMAE_MMA_F32_F32_DETAIL_INCLUDE_HPP__ #include "../../wmma_extension.hpp" #include "../../wmma_mma.hpp" #endif
28.5
48
0.812865
enp1s0
9064c34ea8bc0c4ea87d9425f1f54f02ef7ef46b
9,953
cpp
C++
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
3
2019-01-19T20:21:24.000Z
2021-08-10T02:11:32.000Z
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
1
2021-08-10T02:11:33.000Z
2021-08-10T02:11:33.000Z
/**************************************************************************************************************************************************** * Copyright (c) 2015 Freescale Semiconductor, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the Freescale Semiconductor, Inc. nor the names of * its contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************************************************************************************/ #include <FslBase/Exceptions.hpp> #include <FslBase/Log/Log.hpp> #include <FslDemoApp/Base/Service/Content/IContentManager.hpp> #include <FslDemoApp/Base/Service/Graphics/IGraphicsService.hpp> #include <FslGraphics/Bitmap/Bitmap.hpp> #include <FslGraphics/Vertices/VertexPositionTexture.hpp> #include "GausianHelper.hpp" #include "VBHelper.hpp" #include "TwoPassLinearScaledBlurredDraw.hpp" #include <FslGraphics/Exceptions.hpp> #include <algorithm> #include <cassert> #include <iostream> namespace Fsl { using namespace GLES2; int UpdateScaledKernelLength(const int32_t kernelLength) { int32_t moddedKernelLength = std::max(kernelLength, 5); int32_t newKernelLength = ((moddedKernelLength / 4) * 4) + 1; return (newKernelLength < moddedKernelLength ? newKernelLength + 4 : newKernelLength); } int UpdateKernelLength(const int32_t kernelLength) { int32_t moddedKernelLength = UpdateScaledKernelLength(kernelLength / 2); moddedKernelLength = (moddedKernelLength * 2) + 1; return moddedKernelLength; } //! Uses the two pass linear technique and further reduces the bandwidth requirement by //! downscaling the 'source image' to 1/4 its size (1/2w x 1/2h) before applying the blur and //! and then upscaling the blurred image to provide the final image. //! This works well for large kernel sizes and relatively high sigma's but the downscaling //! produces visible artifacts with low sigma's TwoPassLinearScaledBlurredDraw::TwoPassLinearScaledBlurredDraw(const DemoAppConfig& config, const Config& blurConfig) : ABlurredDraw("Two pass linear scaled") , m_batch2D(std::dynamic_pointer_cast<NativeBatch2D>(config.DemoServiceProvider.Get<IGraphicsService>()->GetNativeBatch2D())) , m_screenResolution(config.ScreenResolution) , m_framebufferOrg(Point2(m_screenResolution.X, m_screenResolution.Y), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565, GL_DEPTH_COMPONENT16) , m_framebufferBlur1() , m_framebufferBlur2() , m_shaders() { if (!m_batch2D) throw std::runtime_error("NativeBatch2D unavailable"); // Ensure that the kernel size is correct int moddedKernelLength = UpdateKernelLength(blurConfig.KernelLength); FSLLOG_WARNING_IF(moddedKernelLength != blurConfig.KernelLength, "The two pass linear scaled shader is not compatible with the supplied kernel length of " << blurConfig.KernelLength << " using " << moddedKernelLength); // Simplistic scaling of the kernel so it handles the down-sampling of the image correctly moddedKernelLength = UpdateScaledKernelLength(moddedKernelLength / 2); float moddedSigma = blurConfig.Sigma / 2.0f; FSLLOG("Scaled actual kernel length: " << moddedKernelLength << " which becomes a " << ((moddedKernelLength / 2)+1) << " linear kernel" ); // The downscaled framebuffer needs to contain 'half of the kernel width' extra pixels on the left to ensure that we can use // them for the blur calc of the first pixel we are interested in const int quadWidth = m_screenResolution.X / 4; int blurFBWidth = quadWidth + (moddedKernelLength / 2); blurFBWidth += ((blurFBWidth % 16) != 0 ? (16 - (blurFBWidth % 16)) : 0); int addedPixels = blurFBWidth - quadWidth; m_framebufferBlur1.Reset(Point2(blurFBWidth, m_screenResolution.Y / 2), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565); m_framebufferBlur2.Reset(Point2(blurFBWidth, m_screenResolution.Y / 2), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565); // Prepare the shaders const std::shared_ptr<IContentManager> contentManager = config.DemoServiceProvider.Get<IContentManager>(); moddedSigma = blurConfig.UseOptimalSigma ? -1.0f : moddedSigma; m_shaders.Reset(contentManager, moddedKernelLength, moddedSigma, m_framebufferBlur1.GetSize(), m_framebufferBlur2.GetSize(), TwoPassShaders::Linear, blurConfig.TheShaderType); const float xOrg = ((m_framebufferOrg.GetSize().X - ((m_framebufferOrg.GetSize().X / 2) + addedPixels * 2)) / float(m_framebufferOrg.GetSize().X)); const float xFinal = addedPixels / float(m_framebufferBlur2.GetSize().X); VBHelper::BuildVB(m_vertexBufferLeft, BoxF(-1, -1, 0, 1), BoxF(0.0f, 0.0f, 0.5f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightX, BoxF(-1, -1, 1, 1), BoxF(xOrg, 0.0f, 1.0f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightX2, BoxF(-1, -1, 1, 1), BoxF(0.0f, 0.0f, 1.0f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightY, BoxF(0, -1, 1, 1), BoxF(xFinal, 0.0f, 1.0f, 1.0f)); } void TwoPassLinearScaledBlurredDraw::Draw(AScene*const pScene) { assert(pScene != nullptr); // Render the 'source' image that we want to partially blur glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferOrg.Get()); { glViewport(0, 0, m_framebufferOrg.GetSize().X, m_framebufferOrg.GetSize().Y); pScene->Draw(); } // Since we are only doing opaque 2d-composition type operations we can disable blend and depth testing glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // Downscale the right side of the image to 1/4 of its size (1/2w x 1/2h) glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur1.Get()); { glViewport(0, 0, m_framebufferBlur1.GetSize().X, m_framebufferBlur1.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferOrg.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferRightX.GetTarget(), m_vertexBufferRightX.Get()); m_vertexBufferRightX.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Blur the scaled image in X glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur2.Get()); { glViewport(0, 0, m_framebufferBlur2.GetSize().X, m_framebufferBlur2.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur1.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramBlurX.Get()); glBindBuffer(m_vertexBufferRightX2.GetTarget(), m_vertexBufferRightX2.Get()); m_vertexBufferRightX2.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Blur the scaled image in Y glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur1.Get()); { glViewport(0, 0, m_framebufferBlur1.GetSize().X, m_framebufferBlur1.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur2.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramBlurY.Get()); glBindBuffer(m_vertexBufferRightX2.GetTarget(), m_vertexBufferRightX2.Get()); m_vertexBufferRightX2.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Since we are only doing opaque non-overlapping 2d-composition type operations we can disable blend and depth testing glBindFramebuffer(GL_FRAMEBUFFER, 0); { glViewport(0, 0, m_screenResolution.X, m_screenResolution.Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferOrg.GetTextureInfo().Handle); // Draw the left side using the normal shader glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferLeft.GetTarget(), m_vertexBufferLeft.Get()); m_vertexBufferLeft.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw the right side using a normal shader, scaling the blurred image back to normal size glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur1.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferRightY.GetTarget(), m_vertexBufferRightY.Get()); m_vertexBufferRightY.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } } }
48.55122
222
0.721491
alejandrolozano2
90678e8dbdf6b7c018d4b960b9b7ad41ef5f5b4a
3,200
cxx
C++
Modules/Core/Common/test/itkIndexGTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
1
2015-02-04T14:15:35.000Z
2015-02-04T14:15:35.000Z
Modules/Core/Common/test/itkIndexGTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
null
null
null
Modules/Core/Common/test/itkIndexGTest.cxx
ferdymercury/ITK
b0a86ded2edd698a6f4a3e58a9db23523a7eb871
[ "Apache-2.0" ]
null
null
null
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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. * *=========================================================================*/ // First include the header file to be tested: #include "itkIndex.h" #include <gtest/gtest.h> #include <initializer_list> #include <limits> namespace { template <unsigned int VDimension> void Expect_Filled_returns_Index_with_specified_value_for_each_element() { using itk::IndexValueType; using IndexType = itk::Index<VDimension>; // Tests that all elements from IndexType::Filled(indexValue) get the specified value. const auto Expect_Filled_with_value = [](const IndexValueType indexValue) { for (const auto filledIndexValue : IndexType::Filled(indexValue)) { EXPECT_EQ(filledIndexValue, indexValue); } }; // Test for indexValue 0, 1, 2, and its maximum. for (IndexValueType indexValue = 0; indexValue <= 2; ++indexValue) { Expect_Filled_with_value(indexValue); } Expect_Filled_with_value(std::numeric_limits<IndexValueType>::max()); } template <itk::IndexValueType VFillValue> constexpr bool Is_Filled_Index_correctly_filled() { for (const auto actualValue : itk::Index<>::Filled(VFillValue).m_InternalArray) { if (actualValue != VFillValue) { return false; } } return true; } } // namespace static_assert(Is_Filled_Index_correctly_filled<0>() && Is_Filled_Index_correctly_filled<1>() && Is_Filled_Index_correctly_filled<std::numeric_limits<itk::IndexValueType>::min()>() && Is_Filled_Index_correctly_filled<std::numeric_limits<itk::IndexValueType>::max()>(), "itk::Index::Filled(value) should be correctly filled at compile-time"); // Tests that itk::Index::Filled(value) returns an itk::Index with the // specified value for each element. TEST(Index, FilledReturnsIndexWithSpecifiedValueForEachElement) { // Test for 1-D and 3-D. Expect_Filled_returns_Index_with_specified_value_for_each_element<1>(); Expect_Filled_returns_Index_with_specified_value_for_each_element<3>(); } TEST(Index, Make) { static_assert((decltype(itk::MakeIndex(1, 1))::Dimension == 2) && (decltype(itk::MakeIndex(1, 1, 1))::Dimension == 3), "The dimension of the created itk::Size should equal the number of arguments"); EXPECT_EQ(itk::MakeIndex(0, 0), itk::Index<2>()); EXPECT_EQ(itk::MakeIndex(0, 0, 0), itk::Index<3>()); const auto itkIndex = itk::MakeIndex(1, 2, 3, 4); const auto values = { 1, 2, 3, 4 }; EXPECT_TRUE(std::equal(itkIndex.begin(), itkIndex.end(), values.begin(), values.end())); }
33.333333
120
0.68125
ferdymercury
9068d9dc5f44f41a912c3b0f30b5604817200057
48,623
cpp
C++
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
consensus/server/src/consensusobject.cpp
joydit/solidframe
0539b0a1e77663ac4c701a88f56723d3e3688e8c
[ "BSL-1.0" ]
null
null
null
// consensus/server/src/consensusobject.cpp // // Copyright (c) 2011, 2012 Valentin Palade (vipalade @ gmail . com) // // This file is part of SolidFrame framework. // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt. // #include <deque> #include <queue> #include <vector> #include <algorithm> #include "system/common.hpp" #include "system/exception.hpp" #ifdef HAS_CPP11 #include <unordered_map> #include <unordered_set> #else #include <map> #include <set> #endif #include "system/timespec.hpp" #include "serialization/binary.hpp" #include "frame/object.hpp" #include "frame/manager.hpp" #include "frame/message.hpp" #include "frame/ipc/ipcservice.hpp" #include "utility/stack.hpp" #include "utility/queue.hpp" #include "utility/timerqueue.hpp" #include "consensus/consensusregistrar.hpp" #include "consensus/consensusrequest.hpp" #include "consensus/server/consensusobject.hpp" #include "consensusmessages.hpp" using namespace std; namespace solid{ namespace consensus{ namespace server{ struct TimerValue{ TimerValue( uint32 _idx = 0, uint16 _uid = 0, uint16 _val = 0 ):index(_idx), uid(_uid), value(_val){} uint32 index; uint16 uid; uint16 value; }; typedef TimerQueue<TimerValue> TimerQueueT; typedef DynamicPointer<consensus::WriteRequestMessage> WriteRequestMessagePointerT; //======================================================== struct RequestStub{ enum{ InitState = 0, WaitProposeState, WaitProposeConfirmState, WaitAcceptState, WaitAcceptConfirmState, AcceptWaitRequestState, AcceptState, AcceptPendingState, AcceptRunState, EraseState, }; enum{ SignaledEvent = 1, TimeoutEvent = 2, }; enum{ HaveRequestFlag = 1, HaveProposeFlag = 2, HaveAcceptFlag = 4, }; RequestStub( ): evs(0), flags(0), proposeid(0xffffffff/2), acceptid(-1), timerid(0), recvpropconf(0), recvpropdecl(0), st(InitState){} RequestStub( DynamicPointer<consensus::WriteRequestMessage> &_rmsgptr ): msgptr(_rmsgptr), evs(0), flags(0), proposeid(-1), acceptid(-1), timerid(0), recvpropconf(0), recvpropdecl(0), st(InitState){} bool hasRequest()const{ return flags & HaveRequestFlag; } void reinit(){ evs = 0; flags = 0; st = InitState; proposeid = -1; acceptid = -1; recvpropconf = 0; } void state(uint8 _st); uint8 state()const{ return st; } bool isValidProposeState()const; bool isValidProposeConfirmState()const; bool isValidProposeDeclineState()const; bool isValidAcceptState()const; bool isValidFastAcceptState()const; bool isValidAcceptConfirmState()const; bool isValidAcceptDeclineState()const; WriteRequestMessagePointerT msgptr; uint16 evs; uint16 flags; uint32 proposeid; uint32 acceptid; uint16 timerid; uint8 recvpropconf;//received accepts for propose uint8 recvpropdecl;//received accepts for propose private: uint8 st; }; void RequestStub::state(uint8 _st){ //checking the safetyness of state change switch(_st){ //case WaitProposeState: //case WaitProposeConfirmState: //case WaitAcceptConfirmState: //case AcceptWaitRequestState: case AcceptState: if( st == InitState || st == WaitProposeState || st == WaitAcceptConfirmState || st == WaitAcceptState || st == AcceptPendingState ){ break; }else{ THROW_EXCEPTION_EX("Invalid state for request ", (int)st); break; } //case AcceptPendingState: //case EraseState: default: break; } st = _st; } inline bool RequestStub::isValidProposeState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: case WaitAcceptConfirmState: case WaitAcceptState: return true; default: return false; } } inline bool RequestStub::isValidProposeConfirmState()const{ switch(st){ case InitState: case WaitProposeState: return false; case WaitProposeConfirmState: return true; case WaitAcceptConfirmState: case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidProposeDeclineState()const{ return isValidProposeConfirmState(); } inline bool RequestStub::isValidAcceptState()const{ switch(st){ case WaitAcceptState: return true; case AcceptWaitRequestState: case AcceptState: case AcceptPendingState: default: return false; } } inline bool RequestStub::isValidFastAcceptState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: return true; case WaitAcceptConfirmState: case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidAcceptConfirmState()const{ switch(st){ case InitState: case WaitProposeState: case WaitProposeConfirmState: return false; case WaitAcceptConfirmState: return true; case WaitAcceptState: default: return false; } } inline bool RequestStub::isValidAcceptDeclineState()const{ return isValidAcceptConfirmState(); } typedef std::deque<RequestStub> RequestStubVectorT; typedef DynamicPointer<Configuration> ConfigurationPointerT; struct Object::Data{ enum{ ProposeOperation = 1, ProposeConfirmOperation, ProposeDeclineOperation, AcceptOperation, FastAcceptOperation, AcceptConfirmOperation, AcceptDeclineOperation, }; struct ReqCmpEqual{ bool operator()(const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2)const; }; struct ReqCmpLess{ bool operator()(const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2)const; }; struct ReqHash{ size_t operator()(const consensus::RequestId* const & _req1)const; }; struct SenderCmpEqual{ bool operator()(const consensus::RequestId & _req1, const consensus::RequestId& _req2)const; }; struct SenderCmpLess{ bool operator()(const consensus::RequestId& _req1, const consensus::RequestId& _req2)const; }; struct SenderHash{ size_t operator()(const consensus::RequestId& _req1)const; }; #ifdef HAS_CPP11 typedef std::unordered_map<const consensus::RequestId*, size_t, ReqHash, ReqCmpEqual> RequestStubMapT; typedef std::unordered_set<consensus::RequestId, SenderHash, SenderCmpEqual> SenderSetT; #else typedef std::map<const consensus::RequestId*, size_t, ReqCmpLess> RequestStubMapT; typedef std::set<consensus::RequestId, SenderCmpLess> SenderSetT; #endif typedef Stack<size_t> SizeTStackT; typedef Queue<size_t> SizeTQueueT; typedef std::vector<DynamicPointer<> > DynamicPointerVectorT; //methods: Data(DynamicPointer<Configuration> &_rcfgptr); ~Data(); bool insertRequestStub(DynamicPointer<WriteRequestMessage> &_rmsgptr, size_t &_ridx); void eraseRequestStub(const size_t _idx); RequestStub& requestStub(const size_t _idx); RequestStub& safeRequestStub(const consensus::RequestId &_reqid, size_t &_rreqidx); RequestStub* requestStubPointer(const consensus::RequestId &_reqid, size_t &_rreqidx); const RequestStub& requestStub(const size_t _idx)const; bool checkAlreadyReceived(DynamicPointer<WriteRequestMessage> &_rmsgptr); bool isCoordinator()const; bool canSendFastAccept()const; void coordinatorId(int8 _coordid); //data: ConfigurationPointerT cfgptr; DynamicPointerVectorT dv; uint32 proposeid; frame::IndexT srvidx; uint32 acceptid; uint32 proposedacceptid; uint32 confirmedacceptid; uint32 continuousacceptedproposes; size_t pendingacceptwaitidx; int8 coordinatorid; int8 distancefromcoordinator; uint8 acceptpendingcnt;//the number of stubs in waitrequest state bool isnotjuststarted; TimeSpec lastaccepttime; RequestStubMapT reqmap; RequestStubVectorT reqvec; SizeTQueueT reqq; SizeTStackT freeposstk; SenderSetT senderset; TimerQueueT timerq; int state; }; inline bool Object::Data::ReqCmpEqual::operator()( const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2 )const{ return *_req1 == *_req2; } inline bool Object::Data::ReqCmpLess::operator()( const consensus::RequestId* const & _req1, const consensus::RequestId* const & _req2 )const{ return *_req1 < *_req2; } inline size_t Object::Data::ReqHash::operator()( const consensus::RequestId* const & _req1 )const{ return _req1->hash(); } inline bool Object::Data::SenderCmpEqual::operator()( const consensus::RequestId & _req1, const consensus::RequestId& _req2 )const{ return _req1.senderEqual(_req2); } inline bool Object::Data::SenderCmpLess::operator()( const consensus::RequestId& _req1, const consensus::RequestId& _req2 )const{ return _req1.senderLess(_req2); } inline size_t Object::Data::SenderHash::operator()( const consensus::RequestId& _req1 )const{ return _req1.senderHash(); } /* NOTE: the 0 value for proposeid is only valid for the beginning of the algorithm. A replica should only accept a proposeid==0 if its proposeid is 0. On overflow, the proposeid should skip the 0 value. */ Object::Data::Data(DynamicPointer<Configuration> &_rcfgptr): cfgptr(_rcfgptr), proposeid(0), srvidx(INVALID_INDEX), acceptid(0), proposedacceptid(0), confirmedacceptid(0), continuousacceptedproposes(0), pendingacceptwaitidx(-1), coordinatorid(-2), distancefromcoordinator(-1), acceptpendingcnt(0), isnotjuststarted(false) { if(cfgptr->crtidx){ coordinatorId(0); }else{ coordinatorId(-1); } } Object::Data::~Data(){ } void Object::Data::coordinatorId(int8 _coordid){ coordinatorid = _coordid; if(_coordid != (int8)-1){ int8 maxsz(cfgptr->addrvec.size()); distancefromcoordinator = circular_distance(static_cast<int8>(cfgptr->crtidx), coordinatorid, maxsz); idbg("non-coordinator with distance from coordinator: "<<(int)distancefromcoordinator); }else{ distancefromcoordinator = -1; idbg("coordinator"); } } bool Object::Data::insertRequestStub(DynamicPointer<WriteRequestMessage> &_rmsgptr, size_t &_ridx){ RequestStubMapT::iterator it(reqmap.find(&_rmsgptr->consensusRequestId())); if(it != reqmap.end()){ _ridx = it->second; reqmap.erase(it); RequestStub &rreq(requestStub(_ridx)); if(rreq.flags & RequestStub::HaveRequestFlag){ edbg("conflict "<<_rmsgptr->consensusRequestId()<<" against existing "<<rreq.msgptr->consensusRequestId()<<" idx = "<<_ridx); } cassert(!(rreq.flags & RequestStub::HaveRequestFlag)); rreq.msgptr = _rmsgptr; reqmap[&rreq.msgptr->consensusRequestId()] = _ridx; return false; } if(freeposstk.size()){ _ridx = freeposstk.top(); freeposstk.pop(); RequestStub &rreq(requestStub(_ridx)); rreq.reinit(); rreq.msgptr = _rmsgptr; }else{ _ridx = reqvec.size(); reqvec.push_back(RequestStub(_rmsgptr)); } reqmap[&requestStub(_ridx).msgptr->consensusRequestId()] = _ridx; return true; } void Object::Data::eraseRequestStub(const size_t _idx){ RequestStub &rreq(requestStub(_idx)); //cassert(rreq.sig.get()); if(rreq.msgptr.get()){ reqmap.erase(&rreq.msgptr->consensusRequestId()); } rreq.msgptr.clear(); rreq.state(RequestStub::InitState); ++rreq.timerid; freeposstk.push(_idx); } inline RequestStub& Object::Data::requestStub(const size_t _idx){ cassert(_idx < reqvec.size()); return reqvec[_idx]; } inline const RequestStub& Object::Data::requestStub(const size_t _idx)const{ cassert(_idx < reqvec.size()); return reqvec[_idx]; } inline bool Object::Data::isCoordinator()const{ return coordinatorid == -1; } bool Object::Data::checkAlreadyReceived(DynamicPointer<WriteRequestMessage> &_rmsgptr){ SenderSetT::iterator it(senderset.find(_rmsgptr->consensusRequestId())); if(it != senderset.end()){ if(overflow_safe_less(_rmsgptr->consensusRequestId().requid, it->requid)){ return true; } senderset.erase(it); senderset.insert(_rmsgptr->consensusRequestId()); }else{ senderset.insert(_rmsgptr->consensusRequestId()); } return false; } bool Object::Data::canSendFastAccept()const{ TimeSpec ct(frame::Object::currentTime()); ct -= lastaccepttime; idbg("continuousacceptedproposes = "<<continuousacceptedproposes<<" ct.sec = "<<ct.seconds()); return (continuousacceptedproposes >= 5) && ct.seconds() < 60; } struct DummyWriteRequestMessage: public WriteRequestMessage{ DummyWriteRequestMessage(const consensus::RequestId &_reqid):WriteRequestMessage(_reqid){} /*virtual*/ void consensusNotifyServerWithThis(){} /*virtual*/ void consensusNotifyClientWithThis(){} /*virtual*/ void consensusNotifyClientWithFail(){} }; RequestStub& Object::Data::safeRequestStub(const consensus::RequestId &_reqid, size_t &_rreqidx){ RequestStubMapT::const_iterator it(reqmap.find(&_reqid)); if(it != reqmap.end()){ _rreqidx = it->second; }else{ DynamicPointer<WriteRequestMessage> reqsig(new DummyWriteRequestMessage(_reqid)); insertRequestStub(reqsig, _rreqidx); } return requestStub(_rreqidx); } RequestStub* Object::Data::requestStubPointer(const consensus::RequestId &_reqid, size_t &_rreqidx){ RequestStubMapT::const_iterator it(reqmap.find(&_reqid)); if(it != reqmap.end()){ _rreqidx = it->second; return &requestStub(it->second); }else{ return NULL; } } //======================================================== //Runntime data struct Object::RunData{ enum{ OperationCapacity = 32 }; struct OperationStub{ size_t reqidx; uint8 operation; uint32 proposeid; uint32 acceptid; }; RunData( ulong _sig, TimeSpec const &_rts, int8 _coordinatorid ):signals(_sig), rtimepos(_rts), coordinatorid(_coordinatorid), opcnt(0), crtacceptincrement(1){} bool isOperationsTableFull()const{ return opcnt == OperationCapacity; } bool isCoordinator()const{ return coordinatorid == -1; } ulong signals; TimeSpec const &rtimepos; int8 coordinatorid; size_t opcnt; size_t crtacceptincrement; OperationStub ops[OperationCapacity]; }; //======================================================== Object::DynamicMapperT Object::dm; /*static*/ void Object::dynamicRegister(){ dm.insert<WriteRequestMessage, Object>(); dm.insert<ReadRequestMessage, Object>(); dm.insert<OperationMessage<1>, Object>(); dm.insert<OperationMessage<2>, Object>(); dm.insert<OperationMessage<4>, Object>(); dm.insert<OperationMessage<8>, Object>(); dm.insert<OperationMessage<16>, Object>(); dm.insert<OperationMessage<32>, Object>(); //TODO: add here the other consensus Messages } /*static*/ void Object::registerMessages(frame::ipc::Service &_ripcsvc){ _ripcsvc.registerMessageType<OperationMessage<1> >(); _ripcsvc.registerMessageType<OperationMessage<2> >(); _ripcsvc.registerMessageType<OperationMessage<4> >(); _ripcsvc.registerMessageType<OperationMessage<8> >(); _ripcsvc.registerMessageType<OperationMessage<16> >(); _ripcsvc.registerMessageType<OperationMessage<32> >(); } Object::Object(DynamicPointer<Configuration> &_rcfgptr):d(*(new Data(_rcfgptr))){ idbg((void*)this); } //--------------------------------------------------------- Object::~Object(){ Registrar::the().unregisterObject(d.srvidx); delete &d; idbg((void*)this); } //--------------------------------------------------------- void Object::state(int _st){ d.state = _st; } //--------------------------------------------------------- int Object::state()const{ return d.state; } //--------------------------------------------------------- void Object::serverIndex(const frame::IndexT &_ridx){ d.srvidx = _ridx; } //--------------------------------------------------------- frame::IndexT Object::serverIndex()const{ return d.srvidx; } //--------------------------------------------------------- bool Object::isRecoveryState()const{ return state() >= PrepareRecoveryState && state() <= LastRecoveryState; } //--------------------------------------------------------- void Object::dynamicHandle(DynamicPointer<> &_dp, RunData &_rrd){ } //--------------------------------------------------------- void Object::dynamicHandle(DynamicPointer<WriteRequestMessage> &_rmsgptr, RunData &_rrd){ if(d.checkAlreadyReceived(_rmsgptr)) return; size_t idx; bool alreadyexisted(!d.insertRequestStub(_rmsgptr, idx)); RequestStub &rreq(d.requestStub(idx)); idbg("adding new request "<<rreq.msgptr->consensusRequestId()<<" on idx = "<<idx<<" existing = "<<alreadyexisted); rreq.flags |= RequestStub::HaveRequestFlag; if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(idx); } } void Object::dynamicHandle(DynamicPointer<ReadRequestMessage> &_rmsgptr, RunData &_rrd){ } void Object::dynamicHandle(DynamicPointer<OperationMessage<1> > &_rmsgptr, RunData &_rrd){ idbg("opcount = 1"); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op); } void Object::dynamicHandle(DynamicPointer<OperationMessage<2> > &_rmsgptr, RunData &_rrd){ idbg("opcount = 2"); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[0]); doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[1]); } void Object::dynamicHandle(DynamicPointer<OperationMessage<4> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<8> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<16> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::dynamicHandle(DynamicPointer<OperationMessage<32> > &_rmsgptr, RunData &_rrd){ idbg("opcount = "<<_rmsgptr->opsz); for(size_t i(0); i < _rmsgptr->opsz; ++i){ doExecuteOperation(_rrd, _rmsgptr->replicaidx, _rmsgptr->op[i]); } } void Object::doExecuteOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ switch(_rop.operation){ case Data::ProposeOperation: doExecuteProposeOperation(_rd, _replicaidx, _rop); break; case Data::ProposeConfirmOperation: doExecuteProposeConfirmOperation(_rd, _replicaidx, _rop); break; case Data::ProposeDeclineOperation: doExecuteProposeDeclineOperation(_rd, _replicaidx, _rop); break; case Data::AcceptOperation: doExecuteAcceptOperation(_rd, _replicaidx, _rop); break; case Data::FastAcceptOperation: doExecuteFastAcceptOperation(_rd, _replicaidx, _rop); break; case Data::AcceptConfirmOperation: doExecuteAcceptConfirmOperation(_rd, _replicaidx, _rop); break; case Data::AcceptDeclineOperation: doExecuteAcceptDeclineOperation(_rd, _replicaidx, _rop); break; default: THROW_EXCEPTION_EX("Unknown operation ", (int)_rop.operation); } } //on replica void Object::doExecuteProposeOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'<<" crtproposeid = "<<d.proposeid); if(!_rop.proposeid && d.proposeid/* && !isRecoveryState()*/){ idbg(""); doSendDeclinePropose(_rd, _replicaidx, _rop); return; } if(overflow_safe_less(_rop.proposeid, d.proposeid)/* && !isRecoveryState()*/){ idbg(""); //we cannot accept the propose doSendDeclinePropose(_rd, _replicaidx, _rop); return; } size_t reqidx; //we can accept the propose d.proposeid = _rop.proposeid; d.isnotjuststarted = true; RequestStub &rreq(d.safeRequestStub(_rop.reqid, reqidx)); if(!rreq.isValidProposeState() && !isRecoveryState()){ wdbg("Invalid state "<<rreq.state()<<" for reqidx "<<reqidx); return; } rreq.proposeid = d.proposeid; rreq.flags |= RequestStub::HaveProposeFlag; if(!(rreq.flags & RequestStub::HaveAcceptFlag)){ ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; } rreq.state(RequestStub::WaitAcceptState); ++rreq.timerid; TimeSpec ts(frame::Object::currentTime()); ts += 10 * 1000;//ms d.timerq.push(ts, TimerValue(reqidx, rreq.timerid)); doSendConfirmPropose(_rd, _replicaidx, reqidx); } //on coordinator void Object::doExecuteProposeConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(!preq->isValidProposeConfirmState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } cassert(preq->flags & RequestStub::HaveAcceptFlag); cassert(preq->flags & RequestStub::HaveProposeFlag); const uint32 tmpaccid = overflow_safe_max(preq->acceptid, _rop.acceptid); // if(_rop.acceptid != tmpaccid){ // idbg("ignore a propose confirm operation from an outdated replica "<<tmpaccid<<" > "<<_rop.acceptid); // return; // } preq->acceptid = tmpaccid; ++preq->recvpropconf; if(preq->recvpropconf == d.cfgptr->quorum){ ++d.continuousacceptedproposes; preq->state(RequestStub::WaitAcceptConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms ++preq->timerid; d.timerq.push(ts, TimerValue(reqidx, preq->timerid)); doSendAccept(_rd, reqidx); } } //on coordinator void Object::doExecuteProposeDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(!preq->isValidProposeDeclineState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } if( preq->proposeid == 0 && preq->proposeid != _rop.proposeid && d.acceptid != _rop.acceptid ){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); doEnterRecoveryState(); return; } ++preq->recvpropdecl; if(preq->recvpropdecl == d.cfgptr->quorum){ ++preq->timerid; preq->state(RequestStub::InitState); d.continuousacceptedproposes = 0; if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } } return; } //on replica void Object::doExecuteAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); if(!isRecoveryState()){ doSendDeclineAccept(_rd, _replicaidx, _rop); } return; } if(preq->proposeid != _rop.proposeid && !isRecoveryState()){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); doSendDeclineAccept(_rd, _replicaidx, _rop); return; } if(!preq->isValidAcceptState() && !isRecoveryState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } preq->acceptid = _rop.acceptid; preq->flags |= RequestStub::HaveAcceptFlag; preq->state(RequestStub::AcceptState); if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } doSendConfirmAccept(_rd, _replicaidx, reqidx); } //on replica void Object::doExecuteFastAcceptOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(!isRecoveryState() && !overflow_safe_less(d.proposeid, _rop.proposeid)){ //we cannot accept the propose doSendDeclineAccept(_rd, _replicaidx, _rop); return; } size_t reqidx; //we can accept the propose d.proposeid = _rop.proposeid; RequestStub &rreq(d.safeRequestStub(_rop.reqid, reqidx)); if(!rreq.isValidFastAcceptState() && !isRecoveryState()){ wdbg("Invalid state "<<(int)rreq.state()<<" for reqidx "<<reqidx); return; } rreq.proposeid = _rop.proposeid; rreq.acceptid = _rop.acceptid; d.proposedacceptid = overflow_safe_max(d.proposedacceptid, _rop.acceptid); rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); rreq.state(RequestStub::AcceptState); if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } doSendConfirmAccept(_rd, _replicaidx, reqidx); } //on coordinator void Object::doExecuteAcceptConfirmOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid || preq->acceptid != _rop.acceptid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(preq->acceptid != _rop.acceptid){ idbg("req->acceptid("<<preq->acceptid<<") != _rop.acceptid("<<_rop.acceptid<<")"); return; } if(!preq->isValidAcceptConfirmState()){ wdbg("Invalid state "<<(int)preq->state()<<" for reqidx "<<reqidx); return; } preq->state(RequestStub::AcceptState); if(!(preq->evs & RequestStub::SignaledEvent)){ preq->evs |= RequestStub::SignaledEvent; d.reqq.push(reqidx); } } //on coordinator void Object::doExecuteAcceptDeclineOperation(RunData &_rd, const uint8 _replicaidx, OperationStub &_rop){ idbg("op = ("<<(int)_rop.operation<<' '<<_rop.proposeid<<' '<<'('<<_rop.reqid<<')'); if(isRecoveryState()){ idbg("Recovery state!!!"); return; } size_t reqidx; RequestStub *preq(d.requestStubPointer(_rop.reqid, reqidx)); if(!preq){ idbg("no such request"); return; } if(preq->proposeid != _rop.proposeid || preq->acceptid != _rop.acceptid){ idbg("req->proposeid("<<preq->proposeid<<") != _rop.proposeid("<<_rop.proposeid<<")"); return; } if(preq->acceptid != _rop.acceptid){ idbg("req->acceptid("<<preq->acceptid<<") != _rop.acceptid("<<_rop.acceptid<<")"); return; } if(!preq->isValidAcceptConfirmState()){ wdbg("Invalid state "<<preq->state()<<" for reqidx "<<reqidx); return; } //do nothing for now return; } //--------------------------------------------------------- /*virtual*/ bool Object::notify(DynamicPointer<frame::Message> &_rmsgptr){ if(this->state() < 0){ _rmsgptr.clear(); return false;//no reason to raise the pool thread!! } DynamicPointer<> dp(_rmsgptr); d.dv.push_back(dp); return frame::Object::notify(frame::S_SIG | frame::S_RAISE); } //--------------------------------------------------------- /*virtual*/ void Object::init(){ } //--------------------------------------------------------- /*virtual*/ void Object::prepareRun(){ } //--------------------------------------------------------- /*virtual*/ void Object::prepareRecovery(){ } //--------------------------------------------------------- /*virtual*/ void Object::execute(ExecuteContext &_rexectx){ frame::Manager &rm(frame::Manager::specific()); RunData rd(_rexectx.eventMask(), _rexectx.currentTime(), d.coordinatorid); if(notified()){//we've received a signal ulong sm(0); DynamicHandler<DynamicMapperT> dh(dm); if(state() != InitState && state() != PrepareRunState && state() != PrepareRecoveryState){ Locker<Mutex> lock(rm.mutex(*this)); sm = grabSignalMask(0);//grab all bits of the signal mask if(sm & frame::S_KILL){ _rexectx.close(); return; } if(sm & frame::S_SIG){//we have signals dh.init(d.dv.begin(), d.dv.end()); d.dv.clear(); } } if(sm & frame::S_SIG){//we've grabed signals, execute them for(size_t i = 0; i < dh.size(); ++i){ dh.handle(*this, i, rd); } } } AsyncE rv; switch(state()){ case InitState: rv = doInit(rd); break; case PrepareRunState: rv = doPrepareRun(rd); break; case RunState: rv = doRun(rd); break; case PrepareRecoveryState: rv = doPrepareRecovery(rd); break; default: if(state() >= FirstRecoveryState && state() <= LastRecoveryState){ rv = doRecovery(rd); } break; } if(rv == AsyncSuccess){ _rexectx.reschedule(); }else if(rv == AsyncError){ _rexectx.close(); }else if(d.timerq.size()){ if(d.timerq.isHit(_rexectx.currentTime())){ _rexectx.reschedule(); return; } _rexectx.waitUntil(d.timerq.frontTime()); } } //--------------------------------------------------------- bool Object::isCoordinator()const{ return d.isCoordinator(); } uint32 Object::acceptId()const{ return d.acceptid; } uint32 Object::proposeId()const{ return d.proposeid; } //--------------------------------------------------------- AsyncE Object::doInit(RunData &_rd){ this->init(); state(PrepareRunState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doPrepareRun(RunData &_rd){ this->prepareRun(); state(RunState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doRun(RunData &_rd){ idbg(""); //first we scan for timeout: while(d.timerq.isHit(_rd.rtimepos)){ RequestStub &rreq(d.requestStub(d.timerq.frontValue().index)); if(rreq.timerid == d.timerq.frontValue().uid){ rreq.evs |= RequestStub::TimeoutEvent; if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(d.timerq.frontValue().index); } } d.timerq.pop(); } //next we process all requests size_t cnt(d.reqq.size()); while(cnt--){ size_t pos(d.reqq.front()); d.reqq.pop(); doProcessRequest(_rd, pos); } doFlushOperations(_rd); if(d.reqq.size()) return AsyncSuccess; return AsyncWait; } //--------------------------------------------------------- AsyncE Object::doPrepareRecovery(RunData &_rd){ //erase all requests in erase state for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if(rreq.state() == RequestStub::EraseState){ d.eraseRequestStub(it - d.reqvec.begin()); } } prepareRecovery(); state(FirstRecoveryState); return AsyncSuccess; } //--------------------------------------------------------- AsyncE Object::doRecovery(RunData &_rd){ idbg(""); return recovery(); } //--------------------------------------------------------- void Object::doProcessRequest(RunData &_rd, const size_t _reqidx){ RequestStub &rreq(d.requestStub(_reqidx)); uint32 events = rreq.evs; rreq.evs = 0; switch(rreq.state()){ case RequestStub::InitState://any if(d.isCoordinator()){ if(d.canSendFastAccept()){ idbg("InitState coordinator - send fast accept for "<<rreq.msgptr->consensusRequestId()); doSendFastAccept(_rd, _reqidx); rreq.state(RequestStub::WaitAcceptConfirmState); }else{ idbg("InitState coordinator - send propose for "<<rreq.msgptr->consensusRequestId()); doSendPropose(_rd, _reqidx); rreq.state(RequestStub::WaitProposeConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); rreq.recvpropconf = 1;//one is the propose_accept from current coordinator } }else{ idbg("InitState non-coordinator - wait propose/accept for "<<rreq.msgptr->consensusRequestId()) rreq.state(RequestStub::WaitProposeState); TimeSpec ts(frame::Object::currentTime()); ts += d.distancefromcoordinator * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); } break; case RequestStub::WaitProposeState://on replica idbg("WaitProposeState for "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeState - timeout for "<<rreq.msgptr->consensusRequestId()); doSendPropose(_rd, _reqidx); rreq.state(RequestStub::WaitProposeConfirmState); TimeSpec ts(frame::Object::currentTime()); ts += 60 * 1000;//ms d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); rreq.recvpropconf = 1;//one is the propose_accept from current coordinator break; } break; case RequestStub::WaitProposeConfirmState://on coordinator idbg("WaitProposeAcceptState for "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeAcceptState - timeout: erase request "<<rreq.msgptr->consensusRequestId()); doEraseRequest(_rd, _reqidx); break; } break; case RequestStub::WaitAcceptState://on replica if(events & RequestStub::TimeoutEvent){ idbg("WaitAcceptState - timeout "<<rreq.msgptr->consensusRequestId()); rreq.state(RequestStub::WaitProposeState); TimeSpec ts(frame::Object::currentTime()); ts += d.distancefromcoordinator * 1000;//ms ++rreq.timerid; d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); break; } break; case RequestStub::WaitAcceptConfirmState://on coordinator idbg("WaitProposeAcceptConfirmState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("WaitProposeAcceptConfirmState - timeout: erase request "<<rreq.msgptr->consensusRequestId()); doEraseRequest(_rd, _reqidx); break; } break; case RequestStub::AcceptWaitRequestState://any idbg("AcceptWaitRequestState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("AcceptWaitRequestState - timeout: enter recovery state "<<rreq.msgptr->consensusRequestId()); doEnterRecoveryState(); break; } if(!(rreq.flags & RequestStub::HaveRequestFlag)){ break; } case RequestStub::AcceptState://any idbg("AcceptState "<<_reqidx<<" "<<rreq.msgptr->consensusRequestId()<<" rreq.acceptid = "<<rreq.acceptid<<" d.acceptid = "<<d.acceptid<<" acceptpendingcnt = "<<(int)d.acceptpendingcnt); ++rreq.timerid; //for recovery reasons, we do this check before //haverequestflag check if(overflow_safe_less(rreq.acceptid, d.acceptid + 1)){ doEraseRequest(_rd, _reqidx); break; } if(!(rreq.flags & RequestStub::HaveRequestFlag)){ idbg("norequestflag "<<_reqidx<<" acceptpendingcnt "<<(int)d.acceptpendingcnt); rreq.state(RequestStub::AcceptWaitRequestState); TimeSpec ts(frame::Object::currentTime()); ts.add(60);//60 secs d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } break; } if(d.acceptid + _rd.crtacceptincrement != rreq.acceptid){ idbg("enterpending "<<_reqidx); rreq.state(RequestStub::AcceptPendingState); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } if(d.acceptpendingcnt == 1){ cassert(d.pendingacceptwaitidx == -1); d.pendingacceptwaitidx = _reqidx; TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(_reqidx, rreq.timerid)); if(d.acceptpendingcnt < 255){ ++d.acceptpendingcnt; } } break; } d.lastaccepttime = frame::Object::currentTime(); ++_rd.crtacceptincrement; //we cannot do erase or Accept here, we must wait for the //send operations to be flushed away rreq.state(RequestStub::AcceptRunState); if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(_reqidx); } break; case RequestStub::AcceptPendingState: idbg("AcceptPendingState "<<rreq.msgptr->consensusRequestId()); if(events & RequestStub::TimeoutEvent){ idbg("AcceptPendingState - timeout: enter recovery state "<<rreq.msgptr->consensusRequestId()); doEnterRecoveryState(); break; } //the status is changed within doScanPendingRequests break; case RequestStub::AcceptRunState: doAcceptRequest(_rd, _reqidx); if(d.acceptpendingcnt){ if(d.pendingacceptwaitidx == _reqidx){ d.pendingacceptwaitidx = -1; } doScanPendingRequests(_rd); } case RequestStub::EraseState: doEraseRequest(_rd, _reqidx); break; default: THROW_EXCEPTION_EX("Unknown state ",rreq.state()); } } void Object::doSendAccept(RunData &_rd, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ idbg(""); doFlushOperations(_rd); _rd.coordinatorid = -1; } d.coordinatorId(-1); RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<_reqidx<<" rreq.proposeid = "<<rreq.proposeid<<" rreq.acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::AcceptOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ idbg(""); doFlushOperations(_rd); } } void Object::doSendFastAccept(RunData &_rd, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ doFlushOperations(_rd); _rd.coordinatorid = -1; } RequestStub &rreq(d.requestStub(_reqidx)); ++d.proposeid; if(!d.proposeid) d.proposeid = 1; ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; rreq.proposeid = d.proposeid; rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); idbg(""<<_reqidx<<" rreq.proposeid = "<<rreq.proposeid<<" rreq.acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::FastAcceptOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendPropose(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(!_rd.isCoordinator()){ doFlushOperations(_rd); _rd.coordinatorid = -1; } RequestStub &rreq(d.requestStub(_reqidx)); if(d.isnotjuststarted){ ++d.proposeid; if(!d.proposeid) d.proposeid = 1; }else{ d.isnotjuststarted = true; } ++d.proposedacceptid; rreq.acceptid = d.proposedacceptid; rreq.proposeid = d.proposeid; rreq.flags |= (RequestStub::HaveProposeFlag | RequestStub::HaveAcceptFlag); idbg("sendpropose: proposeid = "<<rreq.proposeid<<" acceptid = "<<rreq.acceptid<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::ProposeOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendConfirmPropose(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(_rd.coordinatorid != _replicaidx){ doFlushOperations(_rd); _rd.coordinatorid = _replicaidx; } RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<_reqidx<<" "<<(int)_replicaidx<<" "<<rreq.msgptr->consensusRequestId()); //rreq.state = _rd.ops[_rd.opcnt].operation = Data::ProposeConfirmOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendDeclinePropose(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop){ idbg(""<<(int)_replicaidx<<" "<<_rop.reqid); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } OperationMessage<1> *po(new OperationMessage<1>); po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = Data::ProposeDeclineOperation; po->op.proposeid = d.proposeid; po->op.acceptid = d.acceptid; po->op.reqid = _rop.reqid; DynamicPointer<frame::ipc::Message> msgptr(po); this->doSendMessage(msgptr, d.cfgptr->addrvec[_replicaidx]); } void Object::doSendConfirmAccept(RunData &_rd, const uint8 _replicaidx, const size_t _reqidx){ if(isRecoveryState()){ idbg("recovery state: no sends"); return; } if(_rd.coordinatorid != _replicaidx){ doFlushOperations(_rd); _rd.coordinatorid = _replicaidx; } d.coordinatorId(_replicaidx); RequestStub &rreq(d.requestStub(_reqidx)); idbg(""<<(int)_replicaidx<<" "<<_reqidx<<" "<<rreq.msgptr->consensusRequestId()); _rd.ops[_rd.opcnt].operation = Data::AcceptConfirmOperation; _rd.ops[_rd.opcnt].acceptid = rreq.acceptid; _rd.ops[_rd.opcnt].proposeid = rreq.proposeid; _rd.ops[_rd.opcnt].reqidx = _reqidx; ++_rd.opcnt; if(_rd.isOperationsTableFull()){ doFlushOperations(_rd); } } void Object::doSendDeclineAccept(RunData &_rd, const uint8 _replicaidx, const OperationStub &_rop){ idbg(""<<(int)_replicaidx<<" "<<_rop.reqid); if(isRecoveryState()){ idbg("recovery state: no sends"); return; } OperationMessage<1> *po(new OperationMessage<1>); po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = Data::AcceptDeclineOperation; po->op.proposeid = d.proposeid; po->op.acceptid = d.acceptid; po->op.reqid = _rop.reqid; DynamicPointer<frame::ipc::Message> msgptr(po); this->doSendMessage(msgptr, d.cfgptr->addrvec[_replicaidx]); } void Object::doFlushOperations(RunData &_rd){ idbg(""); Message *pm(NULL); OperationStub *pos(NULL); const size_t opcnt = _rd.opcnt; _rd.opcnt = 0; if(opcnt == 0){ return; }else if(opcnt == 1){ OperationMessage<1> *po(new OperationMessage<1>); RequestStub &rreq(d.requestStub(_rd.ops[0].reqidx)); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->op.operation = _rd.ops[0].operation; po->op.acceptid = _rd.ops[0].acceptid; po->op.proposeid = _rd.ops[0].proposeid; po->op.reqid = rreq.msgptr->consensusRequestId(); }else if(opcnt == 2){ OperationMessage<2> *po(new OperationMessage<2>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); pos = po->op; }else if(opcnt <= 4){ OperationMessage<4> *po(new OperationMessage<4>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 8){ OperationMessage<8> *po(new OperationMessage<8>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 16){ OperationMessage<16> *po(new OperationMessage<16>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else if(opcnt <= 32){ OperationMessage<32> *po(new OperationMessage<32>); pm = po; po->replicaidx = d.cfgptr->crtidx; po->srvidx = serverIndex(); po->opsz = opcnt; pos = po->op; }else{ THROW_EXCEPTION_EX("invalid opcnt ",opcnt); } if(pos){ for(size_t i(0); i < opcnt; ++i){ RequestStub &rreq(d.requestStub(_rd.ops[i].reqidx)); //po->oparr.push_back(OperationStub()); pos[i].operation = _rd.ops[i].operation; pos[i].acceptid = _rd.ops[i].acceptid; pos[i].proposeid = _rd.ops[i].proposeid; pos[i].reqid = rreq.msgptr->consensusRequestId(); idbg("pos["<<i<<"].operation = "<<(int)pos[i].operation<<" proposeid = "<<pos[i].proposeid); } } if(_rd.isCoordinator()){ DynamicSharedPointer<Message> sharedmsgptr(pm); idbg("broadcast to other replicas"); //broadcast to replicas for(uint i(0); i < d.cfgptr->addrvec.size(); ++i){ if(i != d.cfgptr->crtidx){ DynamicPointer<frame::ipc::Message> msgptr(sharedmsgptr); this->doSendMessage(msgptr, d.cfgptr->addrvec[i]); } } }else{ idbg("send to "<<(int)_rd.coordinatorid); DynamicPointer<frame::ipc::Message> msgptr(pm); this->doSendMessage(msgptr, d.cfgptr->addrvec[_rd.coordinatorid]); } } /* Scans all the requests for acceptpending requests, and pushes em onto d.reqq */ struct RequestStubAcceptCmp{ const RequestStubVectorT &rreqvec; RequestStubAcceptCmp(const RequestStubVectorT &_rreqvec):rreqvec(_rreqvec){} bool operator()(const size_t &_ridx1, const size_t &_ridx2)const{ return overflow_safe_less(rreqvec[_ridx1].acceptid, rreqvec[_ridx2].acceptid); } }; void Object::doScanPendingRequests(RunData &_rd){ idbg(""<<(int)d.acceptpendingcnt); const size_t accpendcnt = d.acceptpendingcnt; size_t cnt(0); d.acceptpendingcnt = 0; if(accpendcnt != 255){ size_t posarr[256]; size_t idx(0); for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if( rreq.state() == RequestStub::AcceptPendingState ){ posarr[idx] = it - d.reqvec.begin(); ++idx; }else if(rreq.state() == RequestStub::AcceptWaitRequestState){ ++cnt; } } RequestStubAcceptCmp cmp(d.reqvec); std::sort(posarr, posarr + idx, cmp); uint32 crtacceptid(d.acceptid); for(size_t i(0); i < idx; ++i){ RequestStub &rreq(d.reqvec[posarr[i]]); ++crtacceptid; if(crtacceptid == rreq.acceptid){ if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(posarr[i]); } rreq.state(RequestStub::AcceptState); if(d.pendingacceptwaitidx == posarr[i]){ d.pendingacceptwaitidx = -1; } }else{ const size_t tmp = cnt + idx - i; d.acceptpendingcnt = tmp <= 255 ? tmp : 255; if(tmp != cnt && d.pendingacceptwaitidx == -1){ //we have at least one pending request wich is not in waitrequest state RequestStub &rreq(d.requestStub(posarr[i])); TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(posarr[i], rreq.timerid)); d.pendingacceptwaitidx = posarr[i]; } break; } } idbg("d.acceptpendingcnt = "<<(int)d.acceptpendingcnt<<" d.pendingacceptwaitidx = "<<d.pendingacceptwaitidx); }else{ std::deque<size_t> posvec; for(RequestStubVectorT::const_iterator it(d.reqvec.begin()); it != d.reqvec.end(); ++it){ const RequestStub &rreq(*it); if(rreq.state() == RequestStub::AcceptPendingState){ posvec.push_back(it - d.reqvec.begin()); }else if(rreq.state() == RequestStub::AcceptWaitRequestState){ ++cnt; } } RequestStubAcceptCmp cmp(d.reqvec); std::sort(posvec.begin(), posvec.end(), cmp); uint32 crtacceptid(d.acceptid); for(std::deque<size_t>::const_iterator it(posvec.begin()); it != posvec.end(); ++it){ RequestStub &rreq(d.reqvec[*it]); ++crtacceptid; if(crtacceptid == rreq.acceptid){ if(!(rreq.evs & RequestStub::SignaledEvent)){ rreq.evs |= RequestStub::SignaledEvent; d.reqq.push(*it); } if(d.pendingacceptwaitidx == *it){ d.pendingacceptwaitidx = -1; } rreq.state(RequestStub::AcceptState); }else{ size_t sz(it - posvec.begin()); size_t tmp = cnt + posvec.size() - sz; d.acceptpendingcnt = tmp <= 255 ? tmp : 255;; if(tmp != cnt && d.pendingacceptwaitidx == -1){ //we have at least one pending request wich is not in waitrequest state RequestStub &rreq(d.requestStub(*it)); TimeSpec ts(frame::Object::currentTime()); ts.add(2*60);//2 mins d.timerq.push(ts, TimerValue(*it, rreq.timerid)); d.pendingacceptwaitidx = *it; } break; } } } } void Object::doAcceptRequest(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); RequestStub &rreq(d.requestStub(_reqidx)); cassert(rreq.flags & RequestStub::HaveRequestFlag); cassert(rreq.acceptid == d.acceptid + 1); ++d.acceptid; d.reqmap.erase(&rreq.msgptr->consensusRequestId()); this->accept(rreq.msgptr); rreq.msgptr.clear(); rreq.flags &= (~RequestStub::HaveRequestFlag); } void Object::doEraseRequest(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); if(d.pendingacceptwaitidx == _reqidx){ d.pendingacceptwaitidx = -1; } d.eraseRequestStub(_reqidx); } void Object::doStartCoordinate(RunData &_rd, const size_t _reqidx){ idbg(""<<_reqidx); } void Object::doEnterRecoveryState(){ idbg("ENTER RECOVERY STATE"); state(PrepareRecoveryState); } void Object::enterRunState(){ idbg(""); state(PrepareRunState); } //======================================================== }//namespace server }//namespace consensus }//namespace distributed
29.612058
188
0.682681
joydit
9069b46b940fe044853abc6156c0f29c116f85e9
1,471
cpp
C++
pylib/kpoints/PyKPoints.cpp
mirzaelahi/quest
c433175802014386c2b1bf3c8932cd66b0d37c8e
[ "Apache-2.0" ]
null
null
null
pylib/kpoints/PyKPoints.cpp
mirzaelahi/quest
c433175802014386c2b1bf3c8932cd66b0d37c8e
[ "Apache-2.0" ]
null
null
null
pylib/kpoints/PyKPoints.cpp
mirzaelahi/quest
c433175802014386c2b1bf3c8932cd66b0d37c8e
[ "Apache-2.0" ]
null
null
null
/* * File: KPoints.cpp * Copyright (C) 2014 K M Masum Habib <masum.habib@gmail.com> * * Created on February 17, 2014, 12:21 AM */ #include "kpoints/KPoints.h" #include "boostpython.hpp" /** * Python exporters. */ namespace qmicad{ namespace python{ using namespace kpoints; void export_KPoints(){ void (KPoints::*KPoints_addKLine1)(const point&, const point&, double) = &KPoints::addKLine; void (KPoints::*KPoints_addKLine2)(const point&, const point&, uint) = &KPoints::addKLine; void (KPoints::*KPoints_addKRect1)(const point&, const point&, double, double) = &KPoints::addKRect; void (KPoints::*KPoints_addKRect2)(const point&, const point&, uint, uint) = &KPoints::addKRect; class_<KPoints, bases<Printable>, shared_ptr<KPoints>, noncopyable>("KPoints", init<optional<const string&> >()) .def("addKPoint", &KPoints::addKPoint) .def("addKLine", KPoints_addKLine1, "Creates k-grid along a line for a given interval.") .def("addKLine", KPoints_addKLine2, "Creates k-grid along a line for a given number of k-points.") .def("addKRect", KPoints_addKRect1, "Creates a rectangular k-grid for a given interval.") .def("addKRect", KPoints_addKRect2, "Creates a rectangular k-grid for a given number of k-points.") .add_property("kp", &KPoints::kp, "k-points property, readonly.") .add_property("N", &KPoints::N, "Total number of k-points, readonly.") ; } } }
35.878049
107
0.673012
mirzaelahi
906e1cfa9e83c695cee152ea62736128521e988b
1,632
hpp
C++
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
include/GlobalNamespace/IMultiplayerRichPresenceData.hpp
darknight1050/BeatSaber-Quest-Codegen
a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes // Including type: IRichPresenceData #include "GlobalNamespace/IRichPresenceData.hpp" // Completed includes // Begin il2cpp-utils forward declares struct Il2CppString; // Completed il2cpp-utils forward declares // Type namespace: namespace GlobalNamespace { // Size: 0x0 #pragma pack(push, 1) // Autogenerated type: IMultiplayerRichPresenceData class IMultiplayerRichPresenceData/*, public GlobalNamespace::IRichPresenceData*/ { public: // Creating value type constructor for type: IMultiplayerRichPresenceData IMultiplayerRichPresenceData() noexcept {} // Creating interface conversion operator: operator GlobalNamespace::IRichPresenceData operator GlobalNamespace::IRichPresenceData() noexcept { return *reinterpret_cast<GlobalNamespace::IRichPresenceData*>(this); } // public System.String get_multiplayerLobbyCode() // Offset: 0xFFFFFFFF ::Il2CppString* get_multiplayerLobbyCode(); // public System.Void set_multiplayerLobbyCode(System.String value) // Offset: 0xFFFFFFFF void set_multiplayerLobbyCode(::Il2CppString* value); // public System.Boolean get_isJoinable() // Offset: 0xFFFFFFFF bool get_isJoinable(); }; // IMultiplayerRichPresenceData #pragma pack(pop) } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(GlobalNamespace::IMultiplayerRichPresenceData*, "", "IMultiplayerRichPresenceData");
41.846154
108
0.718137
darknight1050
906e2d942116c7f284b401c3a8afdab5b092e0ae
1,345
hpp
C++
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
impl/jamtemplate/common/camera.hpp
Thunraz/JamTemplateCpp
ee516d8a57dcfa6e7997585ab9bd7ff7df3640ea
[ "CC0-1.0" ]
null
null
null
#ifndef GUARD_JAMTEMPLATE_CAMERA_HPP_GUARD #define GUARD_JAMTEMPLATE_CAMERA_HPP_GUARD #include "cam_interface.hpp" #include <functional> namespace jt { class Camera : public CamInterface { public: /// Constructor explicit Camera(float zoom = 1.0f); jt::Vector2 getCamOffset() override; void setCamOffset(jt::Vector2 const& ofs) override; void move(jt::Vector2 const& v) override; float getZoom() const override; void setZoom(float zoom) override; void shake(float t, float strength, float shakeInterval = 0.005f) override; jt::Vector2 getShakeOffset() override; void reset() override; void update(float elapsed) override; /// Set random function that will be used to determine the cam displacement /// \param randomFunction the random function void setRandomFunction(std::function<float(float)> randomFunction); private: jt::Vector2 m_CamOffset { 0.0f, 0.0f }; float m_zoom { 1.0f }; float m_shakeTimer { -1.0f }; float m_shakeStrength { 0.0f }; float m_shakeInterval { 0.0f }; float m_shakeIntervalMax { 0.0f }; jt::Vector2 m_shakeOffset { 0, 0 }; std::function<float(float)> m_randomFunc = nullptr; virtual void updateShake(float elapsed); virtual void resetShake(); void setDefaultRandomFunction(); }; } // namespace jt #endif
26.372549
79
0.704833
Thunraz
90753cdc2933595a3400c49ac5ef9b130ffd0061
4,593
cpp
C++
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
2019/cpp/day_3.cpp
rmottus/advent-of-code
6b803ed61867125375028ce8943c919b1d8ae365
[ "MIT" ]
null
null
null
#include <vector> #include <utility> #include <iostream> #include <sstream> #include <climits> using namespace std; typedef pair<int, int> intpair; // This is using a much better algorithm that I did used in python // Instead of creating an array tracking each point each wire covers, then looping over these for both wires to find cross points, // we just track the endpoints of each movement of each wire, then calculate intersection points between them vector<string> tokenize(const string &str) { vector<string> tokens; stringstream splitter(str); string token; while(getline(splitter, token, ',')) { tokens.push_back(token); } return tokens; } vector<intpair> create_wire_points(const vector<string> &path) { vector<intpair> wire = { {0, 0} }; int x = 0, y = 0; for (auto s: path) { char dir = s[0]; int dist = stoi((char *)&s[1]); switch(dir) { case 'U': y += dist; wire.push_back({ x, y }); break; case 'D': y -= dist; wire.push_back({ x, y }); break; case 'L': x -= dist; wire.push_back({ x, y }); break; case 'R': x += dist; wire.push_back({ x, y }); break; default: throw "Unkown direction"; } } return wire; } bool is_between(const int &i, const int &j, const int &k) { if (i <= j) { return i <= k && k <= j; } return j <= k && k <= i; } vector<intpair> find_cp(const vector<intpair> &first_wire, const vector<intpair> &second_wire) { vector<intpair> result; int a_dist = 0; for (int i = 0; i < first_wire.size() - 1; i++) { intpair a_first_point = first_wire[i], a_second_point = first_wire[i+1]; int a_x_1 = a_first_point.first, a_y_1 = a_first_point.second; int a_x_2 = a_second_point.first, a_y_2 = a_second_point.second; bool a_vert = a_x_1 == a_x_2; int b_dist = 0; for (int j = 0; j < second_wire.size() - 1; j++) { intpair b_first_point = second_wire[j], b_second_point = second_wire[j+1]; int b_x_1 = b_first_point.first, b_y_1 = b_first_point.second; int b_x_2 = b_second_point.first, b_y_2 = b_second_point.second; bool b_vert = b_x_1 == b_x_2; if (a_vert != b_vert) { if (a_vert) { // intpair cp = { a_x_1, b_y_1 }; if (is_between(b_x_1, b_x_2, a_x_1) && is_between(a_y_1, a_y_2, b_y_1)) { result.push_back({ abs(a_x_1) + abs(b_y_1), a_dist + abs(a_y_1 - b_y_1) + b_dist + abs(b_x_1 - a_x_1) }); } } else { // intpair cp = { b_x_1, a_y_1 }; if (is_between(a_x_1, a_x_2, b_x_1) && is_between(b_y_1, b_y_2, a_y_1)) { result.push_back({ abs(b_x_1) + abs(a_y_1), a_dist + abs(a_x_1 - b_x_1) + b_dist + abs(b_y_1 - a_y_1) }); } } } b_dist += (b_vert ? abs(b_y_1 - b_y_2) : abs(b_x_1 - b_x_2)); } a_dist += (a_vert ? abs(a_y_1 - a_y_2) : abs(a_x_1 - a_x_2)); } return result; } int main() { string first_line, second_line; getline(cin, first_line); getline(cin, second_line); auto first_path = tokenize(first_line); auto second_path = tokenize(second_line); auto first_wire = create_wire_points(first_path); auto second_wire = create_wire_points(second_path); std::cout << first_wire.size() << " " << second_wire.size() << endl; auto crosspoints = find_cp(first_wire, second_wire); int man_min = INT_MAX; int len_min = INT_MAX; for (auto cp: crosspoints) { int man_dist = cp.first; if (man_dist < man_min) { man_min = man_dist; } int len_dist = cp.second; if (len_dist < len_min) { len_min = len_dist; } } std::cout << "The nearest cross intpair by Manhatten distance is this far away: " << man_min << endl; std::cout << "The nearest cross intpair by wire length is this far away: " << len_min << endl; }
31.033784
131
0.515567
rmottus
9076137103080706ca67045aa9119ec3eeb43666
4,669
cpp
C++
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
OgreMain/src/Compositor/Pass/OgreCompositorPassDef.cpp
jondo2010/ogre
c1e836d453b2bca0d4e2eb6a32424fe967092b52
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "Compositor/Pass/OgreCompositorPassDef.h" #include "Compositor/Pass/PassClear/OgreCompositorPassClearDef.h" #include "Compositor/Pass/PassCompute/OgreCompositorPassComputeDef.h" #include "Compositor/Pass/PassDepthCopy/OgreCompositorPassDepthCopyDef.h" #include "Compositor/Pass/PassMipmap/OgreCompositorPassMipmapDef.h" #include "Compositor/Pass/PassQuad/OgreCompositorPassQuadDef.h" #include "Compositor/Pass/PassScene/OgreCompositorPassSceneDef.h" #include "Compositor/Pass/PassStencil/OgreCompositorPassStencilDef.h" #include "Compositor/Pass/PassUav/OgreCompositorPassUavDef.h" #include "Compositor/OgreCompositorNodeDef.h" #include "Compositor/OgreCompositorManager2.h" #include "Compositor/Pass/OgreCompositorPassProvider.h" namespace Ogre { CompositorTargetDef::~CompositorTargetDef() { CompositorPassDefVec::const_iterator itor = mCompositorPasses.begin(); CompositorPassDefVec::const_iterator end = mCompositorPasses.end(); while( itor != end ) { OGRE_DELETE *itor; ++itor; } mCompositorPasses.clear(); } //----------------------------------------------------------------------------------- CompositorPassDef* CompositorTargetDef::addPass( CompositorPassType passType, IdString customId ) { CompositorPassDef *retVal = 0; switch( passType ) { case PASS_CLEAR: retVal = OGRE_NEW CompositorPassClearDef( mRtIndex ); break; case PASS_QUAD: retVal = OGRE_NEW CompositorPassQuadDef( mParentNodeDef, mRtIndex ); break; case PASS_SCENE: retVal = OGRE_NEW CompositorPassSceneDef( mRtIndex ); break; case PASS_STENCIL: retVal = OGRE_NEW CompositorPassStencilDef( mRtIndex ); break; case PASS_DEPTHCOPY: retVal = OGRE_NEW CompositorPassDepthCopyDef( mParentNodeDef, mRtIndex ); break; case PASS_UAV: retVal = OGRE_NEW CompositorPassUavDef( mParentNodeDef, mRtIndex ); break; case PASS_MIPMAP: retVal = OGRE_NEW CompositorPassMipmapDef(); break; case PASS_COMPUTE: retVal = OGRE_NEW CompositorPassComputeDef( mParentNodeDef, mRtIndex ); break; case PASS_CUSTOM: { CompositorPassProvider *passProvider = mParentNodeDef->getCompositorManager()-> getCompositorPassProvider(); if( !passProvider ) { OGRE_EXCEPT( Exception::ERR_INVALID_STATE, "Using custom compositor passes but no provider is set", "CompositorTargetDef::addPass" ); } retVal = passProvider->addPassDef( passType, customId, mRtIndex, mParentNodeDef ); } break; default: break; } mParentNodeDef->postInitializePassDef( retVal ); mCompositorPasses.push_back( retVal ); return retVal; } //----------------------------------------------------------------------------------- }
40.25
101
0.627758
jondo2010
907aee87765ac5d6b56251594e16ce2c64ea646b
1,477
cpp
C++
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
fibercore/lib_utils.cpp
Wiladams/fiberdyne
916a257f6f00a5fa639a627240423e6d16961199
[ "Apache-2.0" ]
null
null
null
#include "utils.h" #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /** * Check to see if the input starts with "0x"; if it does, return the decoded * bytes of the following data (presumed to be hex coded). If not, just return * the contents. This routine allocates memory, so has to be free'd. */ bool hex_decode( const uint8_t *input, uint8_t **decoded, uint64_t &len) { if (!decoded) return false; uint8_t *output = *decoded; if (output == nullptr) return false; if ((input[0] != '0') && (input[1] != 'x')) { len = strlen((char *)input); *decoded = (uint8_t *)calloc(1, (size_t)len+1); memcpy(*decoded, input, (size_t)len); } else { len = ( strlen((const char *)input ) >> 1 ) - 1; *decoded = (uint8_t *)malloc( (size_t)len ); for ( size_t i = 2; i < strlen( (const char *)input ); i += 2 ) { output[ ( ( i / 2 ) - 1 ) ] = ( ( ( input[ i ] <= '9' ) ? input[ i ] - '0' : ( ( tolower( input[ i ] ) ) - 'a' + 10 ) ) << 4 ) | ( ( input[ i + 1 ] <= '9' ) ? input[ i + 1 ] - '0' : ( ( tolower( input[ i + 1 ] ) ) - 'a' + 10 ) ); } } return true; } bool hex_print( const uint8_t *data, uint64_t length ) { while ( length-- ) { printf( "%.02x", *data++ ); } return true; } bool hex_puts( const uint8_t *data, uint64_t length ) { hex_print(data, length); printf("\n"); return true; }
25.912281
78
0.525389
Wiladams
907d8fcf48b8be9db4026a6dbf17b57af31bfb53
3,964
cpp
C++
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
modules/boost/simd/sdk/unit/memory/utility/make_aligned.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/simd/sdk/config/types.hpp> #include <boost/simd/memory/allocate.hpp> #include <boost/simd/memory/align_ptr.hpp> #include <boost/simd/memory/deallocate.hpp> #include <boost/simd/memory/is_aligned.hpp> #include <boost/simd/preprocessor/aligned_type.hpp> #include <boost/simd/meta/align_ptr.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/unit/tests/basic.hpp> #include <nt2/sdk/unit/tests/relation.hpp> //////////////////////////////////////////////////////////////////////////////// // Test make_aligned on simple type //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(make_aligned) { using boost::simd::is_aligned; BOOST_SIMD_ALIGNED_TYPE(double ) ad; BOOST_SIMD_ALIGNED_TYPE(float ) af; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint64_t) aui64; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint32_t) aui32; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint16_t) aui16; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint8_t ) aui8; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int64_t ) ai64; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int32_t ) ai32; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int16_t ) ai16; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int8_t ) ai8; BOOST_SIMD_ALIGNED_TYPE(bool ) ab; NT2_TEST( is_aligned(&ad) ); NT2_TEST( is_aligned(&af) ); NT2_TEST( is_aligned(&aui64) ); NT2_TEST( is_aligned(&aui32) ); NT2_TEST( is_aligned(&aui16) ); NT2_TEST( is_aligned(&aui8) ); NT2_TEST( is_aligned(&ai64) ); NT2_TEST( is_aligned(&ai32) ); NT2_TEST( is_aligned(&ai16) ); NT2_TEST( is_aligned(&ai8) ); NT2_TEST( is_aligned(&ab) ); } //////////////////////////////////////////////////////////////////////////////// // Test make_aligned on array type //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(make_aligned_array) { using boost::simd::is_aligned; BOOST_SIMD_ALIGNED_TYPE(double ) ad[3]; BOOST_SIMD_ALIGNED_TYPE(float ) af[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint64_t) aui64[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint32_t) aui32[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint16_t) aui16[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::uint8_t ) aui8[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int64_t ) ai64[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int32_t ) ai32[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int16_t ) ai16[3]; BOOST_SIMD_ALIGNED_TYPE(boost::simd::int8_t ) ai8[3]; BOOST_SIMD_ALIGNED_TYPE(bool ) ab[3]; NT2_TEST( is_aligned(&ad[0]) ); NT2_TEST( is_aligned(&af[0]) ); NT2_TEST( is_aligned(&aui64[0]) ); NT2_TEST( is_aligned(&aui32[0]) ); NT2_TEST( is_aligned(&aui16[0]) ); NT2_TEST( is_aligned(&aui8[0]) ); NT2_TEST( is_aligned(&ai64[0]) ); NT2_TEST( is_aligned(&ai32[0]) ); NT2_TEST( is_aligned(&ai16[0]) ); NT2_TEST( is_aligned(&ai8[0]) ); NT2_TEST( is_aligned(&ab[0]) ); } //////////////////////////////////////////////////////////////////////////////// // Test make_aligned metafunction //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(align_ptr) { using boost::simd::is_aligned; using boost::simd::align_ptr; using boost::simd::allocate; using boost::simd::deallocate; void* ptr = allocate(15, 32); boost::simd::meta::align_ptr<void, 32>::type p = align_ptr<32>(ptr); NT2_TEST( is_aligned(p, 32) ); NT2_TEST_EQUAL(p, ptr); deallocate(ptr); }
38.862745
80
0.589051
psiha
907fa619951534d8911fe1f039e67a7a9e814c0f
792
cpp
C++
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
23
2018-10-28T00:47:58.000Z
2021-06-07T04:54:32.000Z
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
null
null
null
Source/EstCore/Private/EstCore.cpp
edgarbarney/Estranged.Core
289c672da77f30789f19c317815ea8f973885a25
[ "MIT" ]
3
2020-04-11T17:19:43.000Z
2021-09-21T10:47:26.000Z
#include "EstCore.h" #include "Modules/ModuleManager.h" extern ENGINE_API float GAverageFPS; IMPLEMENT_GAME_MODULE(FEstCoreModule, EstCore); // Default to something low so we don't start at zero float FEstCoreModule::LongAverageFrameRate = 25.f; void FEstCoreModule::StartupModule() { TickDelegate = FTickerDelegate::CreateRaw(this, &FEstCoreModule::Tick); TickDelegateHandle = FTicker::GetCoreTicker().AddTicker(TickDelegate); } bool FEstCoreModule::Tick(float DeltaTime) { LongAverageFrameRate = LongAverageFrameRate * .99f + GAverageFPS * .01f; return true; } void FEstCoreModule::ShutdownModule() { FTicker::GetCoreTicker().RemoveTicker(TickDelegateHandle); } DEFINE_LOG_CATEGORY(LogEstGeneral); ESTCORE_API const FEstImpactEffect FEstImpactEffect::None = FEstImpactEffect();
26.4
79
0.79798
edgarbarney
9082f1387eeb7e26821d0043d1af9626a3b86c24
3,521
cpp
C++
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
70
2020-05-07T03:09:09.000Z
2022-02-11T01:04:54.000Z
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
3
2020-06-01T00:34:01.000Z
2020-10-08T07:43:32.000Z
Core/MAGESLAM/Source/Image/OrbFeatureDetector.cpp
syntheticmagus/mageslam
ba79a4e6315689c072c29749de18d70279a4c5e4
[ "MIT" ]
16
2020-05-07T03:09:13.000Z
2022-03-31T15:36:49.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. //------------------------------------------------------------------------------ // OrbFeatureDetector.cpp // // The feature detector detects the orb features in an image and // also computes the BRIEF descriptors for them. The init settings // control the properties of the features. //------------------------------------------------------------------------------ #include "OrbFeatureDetector.h" #include "MageSettings.h" #include <opencv2/core/core.hpp> #include <opencv2/features2d/features2d.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/core.hpp> #include "Utils/Logging.h" #include "OpenCVModified.h" #include "Analysis/DataFlow.h" #include <gsl/gsl_algorithm> namespace mage { void OrbFeatureDetector::UndistortKeypoints( gsl::span<cv::KeyPoint> inoutKeypoints, const CameraCalibration& distortedCalibration, const CameraCalibration& undistortedCalibration, thread_memory memory) { SCOPE_TIMER(OrbFeatureDetector::UndistortKeypoints); assert(distortedCalibration.GetDistortionType() != mage::calibration::DistortionType::None && "expecting distorted keypoints to undistort"); if (inoutKeypoints.empty()) { return; } auto sourceMem = memory.stack_buffer<cv::Point2f>(inoutKeypoints.size()); for (size_t i = 0; i < sourceMem.size(); ++i) { sourceMem[i] = inoutKeypoints[i].pt; } cv::Mat distortedPointsMat{ (int)sourceMem.size(), 1, CV_32FC2, sourceMem.data() }; auto destMem = memory.stack_buffer<cv::Point2f>(inoutKeypoints.size()); cv::Mat undistortedPointsMat{ (int)destMem.size(), 1, CV_32FC2, destMem.data() }; undistortPoints(distortedPointsMat, undistortedPointsMat, distortedCalibration.GetCameraMatrix(), distortedCalibration.GetCVDistortionCoeffs(), cv::noArray(), undistortedCalibration.GetCameraMatrix()); // now adjust the points in undistorted for (size_t i = 0; i < destMem.size(); ++i) { inoutKeypoints[i].pt = destMem[i]; } } OrbFeatureDetector::OrbFeatureDetector(const FeatureExtractorSettings& settings) : m_detector{ settings.GaussianKernelSize, (unsigned int)settings.NumFeatures, settings.ScaleFactor, settings.NumLevels, settings.PatchSize, settings.FastThreshold, settings.UseOrientation, settings.FeatureFactor, settings.FeatureStrength, settings.StrongResponse, settings.MinRobustnessFactor, settings.MaxRobustnessFactor, settings.NumCellsX, settings.NumCellsY } { } void OrbFeatureDetector::Process(const CameraCalibration& distortedCalibration, const CameraCalibration& undistortedCalibration, thread_memory memory, ImageHandle& imageData, const cv::Mat& image) { SCOPE_TIMER(OrbFeatureDetector::Process); assert(undistortedCalibration.GetDistortionType() == calibration::DistortionType::None && "Expecting undistorted cal to be undistorted"); DATAFLOW( DF_OUTPUT(imageData->GetKeypoints()) ); m_detector.DetectAndCompute(memory, *imageData, image); if(distortedCalibration != undistortedCalibration) { UndistortKeypoints(imageData->GetKeypoints(), distortedCalibration, undistortedCalibration, memory); } } }
34.519608
210
0.652087
syntheticmagus
9087a52c279a863d67cda2f3404293017382bd0b
32,049
cc
C++
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
4
2020-06-05T14:08:23.000Z
2021-06-26T22:15:31.000Z
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
2
2021-06-25T15:14:01.000Z
2021-07-01T17:43:20.000Z
Lodestar/io/proto/ls.proto.systems.pb.cc
helkebir/Lodestar
6b325d3e7a388676ed31d44eac1146630ee4bb2c
[ "BSD-3-Clause" ]
1
2021-06-16T03:15:23.000Z
2021-06-16T03:15:23.000Z
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: ls.proto.systems.proto #include "ls.proto.systems.pb.h" #include <algorithm> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.h> #include <google/protobuf/wire_format_lite.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/generated_message_reflection.h> #include <google/protobuf/reflection_ops.h> #include <google/protobuf/wire_format.h> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> PROTOBUF_PRAGMA_INIT_SEG namespace ls { namespace proto { namespace systems { constexpr StateSpace::StateSpace( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : a_(nullptr) , b_(nullptr) , c_(nullptr) , d_(nullptr) , dt_(0) , isdiscrete_(false){} struct StateSpaceDefaultTypeInternal { constexpr StateSpaceDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~StateSpaceDefaultTypeInternal() {} union { StateSpace _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT StateSpaceDefaultTypeInternal _StateSpace_default_instance_; constexpr TransferFunction::TransferFunction( ::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized) : num_(nullptr) , den_(nullptr){} struct TransferFunctionDefaultTypeInternal { constexpr TransferFunctionDefaultTypeInternal() : _instance(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized{}) {} ~TransferFunctionDefaultTypeInternal() {} union { TransferFunction _instance; }; }; PROTOBUF_ATTRIBUTE_NO_DESTROY PROTOBUF_CONSTINIT TransferFunctionDefaultTypeInternal _TransferFunction_default_instance_; } // namespace systems } // namespace proto } // namespace ls static ::PROTOBUF_NAMESPACE_ID::Metadata file_level_metadata_ls_2eproto_2esystems_2eproto[2]; static constexpr ::PROTOBUF_NAMESPACE_ID::EnumDescriptor const** file_level_enum_descriptors_ls_2eproto_2esystems_2eproto = nullptr; static constexpr ::PROTOBUF_NAMESPACE_ID::ServiceDescriptor const** file_level_service_descriptors_ls_2eproto_2esystems_2eproto = nullptr; const ::PROTOBUF_NAMESPACE_ID::uint32 TableStruct_ls_2eproto_2esystems_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, _has_bits_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, a_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, b_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, c_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, d_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, isdiscrete_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::StateSpace, dt_), 0, 1, 2, 3, 5, 4, PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, _has_bits_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, num_), PROTOBUF_FIELD_OFFSET(::ls::proto::systems::TransferFunction, den_), 0, 1, }; static const ::PROTOBUF_NAMESPACE_ID::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, 11, sizeof(::ls::proto::systems::StateSpace)}, { 17, 24, sizeof(::ls::proto::systems::TransferFunction)}, }; static ::PROTOBUF_NAMESPACE_ID::Message const * const file_default_instances[] = { reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::ls::proto::systems::_StateSpace_default_instance_), reinterpret_cast<const ::PROTOBUF_NAMESPACE_ID::Message*>(&::ls::proto::systems::_TransferFunction_default_instance_), }; const char descriptor_table_protodef_ls_2eproto_2esystems_2eproto[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = "\n\026ls.proto.systems.proto\022\020ls.proto.syste" "ms\032\024ls.proto.eigen.proto\"\214\002\n\nStateSpace\022" "(\n\001A\030\001 \001(\0132\030.ls.proto.eigen.MatrixXdH\000\210\001" "\001\022(\n\001B\030\002 \001(\0132\030.ls.proto.eigen.MatrixXdH\001" "\210\001\001\022(\n\001C\030\003 \001(\0132\030.ls.proto.eigen.MatrixXd" "H\002\210\001\001\022(\n\001D\030\004 \001(\0132\030.ls.proto.eigen.Matrix" "XdH\003\210\001\001\022\027\n\nisDiscrete\030\005 \001(\010H\004\210\001\001\022\017\n\002dt\030\006" " \001(\001H\005\210\001\001B\004\n\002_AB\004\n\002_BB\004\n\002_CB\004\n\002_DB\r\n\013_is" "DiscreteB\005\n\003_dt\"z\n\020TransferFunction\022*\n\003n" "um\030\001 \001(\0132\030.ls.proto.eigen.VectorXdH\000\210\001\001\022" "*\n\003den\030\002 \001(\0132\030.ls.proto.eigen.VectorXdH\001" "\210\001\001B\006\n\004_numB\006\n\004_denb\006proto3" ; static const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable*const descriptor_table_ls_2eproto_2esystems_2eproto_deps[1] = { &::descriptor_table_ls_2eproto_2eeigen_2eproto, }; static ::PROTOBUF_NAMESPACE_ID::internal::once_flag descriptor_table_ls_2eproto_2esystems_2eproto_once; const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_ls_2eproto_2esystems_2eproto = { false, false, 467, descriptor_table_protodef_ls_2eproto_2esystems_2eproto, "ls.proto.systems.proto", &descriptor_table_ls_2eproto_2esystems_2eproto_once, descriptor_table_ls_2eproto_2esystems_2eproto_deps, 1, 2, schemas, file_default_instances, TableStruct_ls_2eproto_2esystems_2eproto::offsets, file_level_metadata_ls_2eproto_2esystems_2eproto, file_level_enum_descriptors_ls_2eproto_2esystems_2eproto, file_level_service_descriptors_ls_2eproto_2esystems_2eproto, }; PROTOBUF_ATTRIBUTE_WEAK const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable* descriptor_table_ls_2eproto_2esystems_2eproto_getter() { return &descriptor_table_ls_2eproto_2esystems_2eproto; } // Force running AddDescriptors() at dynamic initialization time. PROTOBUF_ATTRIBUTE_INIT_PRIORITY static ::PROTOBUF_NAMESPACE_ID::internal::AddDescriptorsRunner dynamic_init_dummy_ls_2eproto_2esystems_2eproto(&descriptor_table_ls_2eproto_2esystems_2eproto); namespace ls { namespace proto { namespace systems { // =================================================================== class StateSpace::_Internal { public: using HasBits = decltype(std::declval<StateSpace>()._has_bits_); static const ::ls::proto::eigen::MatrixXd& a(const StateSpace* msg); static void set_has_a(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static const ::ls::proto::eigen::MatrixXd& b(const StateSpace* msg); static void set_has_b(HasBits* has_bits) { (*has_bits)[0] |= 2u; } static const ::ls::proto::eigen::MatrixXd& c(const StateSpace* msg); static void set_has_c(HasBits* has_bits) { (*has_bits)[0] |= 4u; } static const ::ls::proto::eigen::MatrixXd& d(const StateSpace* msg); static void set_has_d(HasBits* has_bits) { (*has_bits)[0] |= 8u; } static void set_has_isdiscrete(HasBits* has_bits) { (*has_bits)[0] |= 32u; } static void set_has_dt(HasBits* has_bits) { (*has_bits)[0] |= 16u; } }; const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::a(const StateSpace* msg) { return *msg->a_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::b(const StateSpace* msg) { return *msg->b_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::c(const StateSpace* msg) { return *msg->c_; } const ::ls::proto::eigen::MatrixXd& StateSpace::_Internal::d(const StateSpace* msg) { return *msg->d_; } void StateSpace::clear_a() { if (a_ != nullptr) a_->Clear(); _has_bits_[0] &= ~0x00000001u; } void StateSpace::clear_b() { if (b_ != nullptr) b_->Clear(); _has_bits_[0] &= ~0x00000002u; } void StateSpace::clear_c() { if (c_ != nullptr) c_->Clear(); _has_bits_[0] &= ~0x00000004u; } void StateSpace::clear_d() { if (d_ != nullptr) d_->Clear(); _has_bits_[0] &= ~0x00000008u; } StateSpace::StateSpace(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:ls.proto.systems.StateSpace) } StateSpace::StateSpace(const StateSpace& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_a()) { a_ = new ::ls::proto::eigen::MatrixXd(*from.a_); } else { a_ = nullptr; } if (from._internal_has_b()) { b_ = new ::ls::proto::eigen::MatrixXd(*from.b_); } else { b_ = nullptr; } if (from._internal_has_c()) { c_ = new ::ls::proto::eigen::MatrixXd(*from.c_); } else { c_ = nullptr; } if (from._internal_has_d()) { d_ = new ::ls::proto::eigen::MatrixXd(*from.d_); } else { d_ = nullptr; } ::memcpy(&dt_, &from.dt_, static_cast<size_t>(reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&dt_)) + sizeof(isdiscrete_)); // @@protoc_insertion_point(copy_constructor:ls.proto.systems.StateSpace) } void StateSpace::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&a_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&a_)) + sizeof(isdiscrete_)); } StateSpace::~StateSpace() { // @@protoc_insertion_point(destructor:ls.proto.systems.StateSpace) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void StateSpace::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete a_; if (this != internal_default_instance()) delete b_; if (this != internal_default_instance()) delete c_; if (this != internal_default_instance()) delete d_; } void StateSpace::ArenaDtor(void* object) { StateSpace* _this = reinterpret_cast< StateSpace* >(object); (void)_this; } void StateSpace::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void StateSpace::SetCachedSize(int size) const { _cached_size_.Set(size); } void StateSpace::Clear() { // @@protoc_insertion_point(message_clear_start:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000000fu) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(a_ != nullptr); a_->Clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(b_ != nullptr); b_->Clear(); } if (cached_has_bits & 0x00000004u) { GOOGLE_DCHECK(c_ != nullptr); c_->Clear(); } if (cached_has_bits & 0x00000008u) { GOOGLE_DCHECK(d_ != nullptr); d_->Clear(); } } if (cached_has_bits & 0x00000030u) { ::memset(&dt_, 0, static_cast<size_t>( reinterpret_cast<char*>(&isdiscrete_) - reinterpret_cast<char*>(&dt_)) + sizeof(isdiscrete_)); } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* StateSpace::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .ls.proto.eigen.MatrixXd A = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_a(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd B = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_b(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd C = 3; case 3: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 26)) { ptr = ctx->ParseMessage(_internal_mutable_c(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.MatrixXd D = 4; case 4: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 34)) { ptr = ctx->ParseMessage(_internal_mutable_d(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional bool isDiscrete = 5; case 5: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 40)) { _Internal::set_has_isdiscrete(&has_bits); isdiscrete_ = ::PROTOBUF_NAMESPACE_ID::internal::ReadVarint64(&ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional double dt = 6; case 6: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 49)) { _Internal::set_has_dt(&has_bits); dt_ = ::PROTOBUF_NAMESPACE_ID::internal::UnalignedLoad<double>(ptr); ptr += sizeof(double); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* StateSpace::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // optional .ls.proto.eigen.MatrixXd A = 1; if (_internal_has_a()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::a(this), target, stream); } // optional .ls.proto.eigen.MatrixXd B = 2; if (_internal_has_b()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::b(this), target, stream); } // optional .ls.proto.eigen.MatrixXd C = 3; if (_internal_has_c()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 3, _Internal::c(this), target, stream); } // optional .ls.proto.eigen.MatrixXd D = 4; if (_internal_has_d()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 4, _Internal::d(this), target, stream); } // optional bool isDiscrete = 5; if (_internal_has_isdiscrete()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteBoolToArray(5, this->_internal_isdiscrete(), target); } // optional double dt = 6; if (_internal_has_dt()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::WriteDoubleToArray(6, this->_internal_dt(), target); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:ls.proto.systems.StateSpace) return target; } size_t StateSpace::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:ls.proto.systems.StateSpace) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x0000003fu) { // optional .ls.proto.eigen.MatrixXd A = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *a_); } // optional .ls.proto.eigen.MatrixXd B = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *b_); } // optional .ls.proto.eigen.MatrixXd C = 3; if (cached_has_bits & 0x00000004u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *c_); } // optional .ls.proto.eigen.MatrixXd D = 4; if (cached_has_bits & 0x00000008u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *d_); } // optional double dt = 6; if (cached_has_bits & 0x00000010u) { total_size += 1 + 8; } // optional bool isDiscrete = 5; if (cached_has_bits & 0x00000020u) { total_size += 1 + 1; } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StateSpace::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:ls.proto.systems.StateSpace) GOOGLE_DCHECK_NE(&from, this); const StateSpace* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<StateSpace>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:ls.proto.systems.StateSpace) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:ls.proto.systems.StateSpace) MergeFrom(*source); } } void StateSpace::MergeFrom(const StateSpace& from) { // @@protoc_insertion_point(class_specific_merge_from_start:ls.proto.systems.StateSpace) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x0000003fu) { if (cached_has_bits & 0x00000001u) { _internal_mutable_a()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_a()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_b()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_b()); } if (cached_has_bits & 0x00000004u) { _internal_mutable_c()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_c()); } if (cached_has_bits & 0x00000008u) { _internal_mutable_d()->::ls::proto::eigen::MatrixXd::MergeFrom(from._internal_d()); } if (cached_has_bits & 0x00000010u) { dt_ = from.dt_; } if (cached_has_bits & 0x00000020u) { isdiscrete_ = from.isdiscrete_; } _has_bits_[0] |= cached_has_bits; } } void StateSpace::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:ls.proto.systems.StateSpace) if (&from == this) return; Clear(); MergeFrom(from); } void StateSpace::CopyFrom(const StateSpace& from) { // @@protoc_insertion_point(class_specific_copy_from_start:ls.proto.systems.StateSpace) if (&from == this) return; Clear(); MergeFrom(from); } bool StateSpace::IsInitialized() const { return true; } void StateSpace::InternalSwap(StateSpace* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(StateSpace, isdiscrete_) + sizeof(StateSpace::isdiscrete_) - PROTOBUF_FIELD_OFFSET(StateSpace, a_)>( reinterpret_cast<char*>(&a_), reinterpret_cast<char*>(&other->a_)); } ::PROTOBUF_NAMESPACE_ID::Metadata StateSpace::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_ls_2eproto_2esystems_2eproto_getter, &descriptor_table_ls_2eproto_2esystems_2eproto_once, file_level_metadata_ls_2eproto_2esystems_2eproto[0]); } // =================================================================== class TransferFunction::_Internal { public: using HasBits = decltype(std::declval<TransferFunction>()._has_bits_); static const ::ls::proto::eigen::VectorXd& num(const TransferFunction* msg); static void set_has_num(HasBits* has_bits) { (*has_bits)[0] |= 1u; } static const ::ls::proto::eigen::VectorXd& den(const TransferFunction* msg); static void set_has_den(HasBits* has_bits) { (*has_bits)[0] |= 2u; } }; const ::ls::proto::eigen::VectorXd& TransferFunction::_Internal::num(const TransferFunction* msg) { return *msg->num_; } const ::ls::proto::eigen::VectorXd& TransferFunction::_Internal::den(const TransferFunction* msg) { return *msg->den_; } void TransferFunction::clear_num() { if (num_ != nullptr) num_->Clear(); _has_bits_[0] &= ~0x00000001u; } void TransferFunction::clear_den() { if (den_ != nullptr) den_->Clear(); _has_bits_[0] &= ~0x00000002u; } TransferFunction::TransferFunction(::PROTOBUF_NAMESPACE_ID::Arena* arena) : ::PROTOBUF_NAMESPACE_ID::Message(arena) { SharedCtor(); RegisterArenaDtor(arena); // @@protoc_insertion_point(arena_constructor:ls.proto.systems.TransferFunction) } TransferFunction::TransferFunction(const TransferFunction& from) : ::PROTOBUF_NAMESPACE_ID::Message(), _has_bits_(from._has_bits_) { _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); if (from._internal_has_num()) { num_ = new ::ls::proto::eigen::VectorXd(*from.num_); } else { num_ = nullptr; } if (from._internal_has_den()) { den_ = new ::ls::proto::eigen::VectorXd(*from.den_); } else { den_ = nullptr; } // @@protoc_insertion_point(copy_constructor:ls.proto.systems.TransferFunction) } void TransferFunction::SharedCtor() { ::memset(reinterpret_cast<char*>(this) + static_cast<size_t>( reinterpret_cast<char*>(&num_) - reinterpret_cast<char*>(this)), 0, static_cast<size_t>(reinterpret_cast<char*>(&den_) - reinterpret_cast<char*>(&num_)) + sizeof(den_)); } TransferFunction::~TransferFunction() { // @@protoc_insertion_point(destructor:ls.proto.systems.TransferFunction) SharedDtor(); _internal_metadata_.Delete<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } void TransferFunction::SharedDtor() { GOOGLE_DCHECK(GetArenaForAllocation() == nullptr); if (this != internal_default_instance()) delete num_; if (this != internal_default_instance()) delete den_; } void TransferFunction::ArenaDtor(void* object) { TransferFunction* _this = reinterpret_cast< TransferFunction* >(object); (void)_this; } void TransferFunction::RegisterArenaDtor(::PROTOBUF_NAMESPACE_ID::Arena*) { } void TransferFunction::SetCachedSize(int size) const { _cached_size_.Set(size); } void TransferFunction::Clear() { // @@protoc_insertion_point(message_clear_start:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { GOOGLE_DCHECK(num_ != nullptr); num_->Clear(); } if (cached_has_bits & 0x00000002u) { GOOGLE_DCHECK(den_ != nullptr); den_->Clear(); } } _has_bits_.Clear(); _internal_metadata_.Clear<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(); } const char* TransferFunction::_InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) { #define CHK_(x) if (PROTOBUF_PREDICT_FALSE(!(x))) goto failure _Internal::HasBits has_bits{}; while (!ctx->Done(&ptr)) { ::PROTOBUF_NAMESPACE_ID::uint32 tag; ptr = ::PROTOBUF_NAMESPACE_ID::internal::ReadTag(ptr, &tag); switch (tag >> 3) { // optional .ls.proto.eigen.VectorXd num = 1; case 1: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 10)) { ptr = ctx->ParseMessage(_internal_mutable_num(), ptr); CHK_(ptr); } else goto handle_unusual; continue; // optional .ls.proto.eigen.VectorXd den = 2; case 2: if (PROTOBUF_PREDICT_TRUE(static_cast<::PROTOBUF_NAMESPACE_ID::uint8>(tag) == 18)) { ptr = ctx->ParseMessage(_internal_mutable_den(), ptr); CHK_(ptr); } else goto handle_unusual; continue; default: { handle_unusual: if ((tag == 0) || ((tag & 7) == 4)) { CHK_(ptr); ctx->SetLastTag(tag); goto success; } ptr = UnknownFieldParse(tag, _internal_metadata_.mutable_unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(), ptr, ctx); CHK_(ptr != nullptr); continue; } } // switch } // while success: _has_bits_.Or(has_bits); return ptr; failure: ptr = nullptr; goto success; #undef CHK_ } ::PROTOBUF_NAMESPACE_ID::uint8* TransferFunction::_InternalSerialize( ::PROTOBUF_NAMESPACE_ID::uint8* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const { // @@protoc_insertion_point(serialize_to_array_start:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; // optional .ls.proto.eigen.VectorXd num = 1; if (_internal_has_num()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 1, _Internal::num(this), target, stream); } // optional .ls.proto.eigen.VectorXd den = 2; if (_internal_has_den()) { target = stream->EnsureSpace(target); target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite:: InternalWriteMessage( 2, _Internal::den(this), target, stream); } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { target = ::PROTOBUF_NAMESPACE_ID::internal::WireFormat::InternalSerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(::PROTOBUF_NAMESPACE_ID::UnknownFieldSet::default_instance), target, stream); } // @@protoc_insertion_point(serialize_to_array_end:ls.proto.systems.TransferFunction) return target; } size_t TransferFunction::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:ls.proto.systems.TransferFunction) size_t total_size = 0; ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; cached_has_bits = _has_bits_[0]; if (cached_has_bits & 0x00000003u) { // optional .ls.proto.eigen.VectorXd num = 1; if (cached_has_bits & 0x00000001u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *num_); } // optional .ls.proto.eigen.VectorXd den = 2; if (cached_has_bits & 0x00000002u) { total_size += 1 + ::PROTOBUF_NAMESPACE_ID::internal::WireFormatLite::MessageSize( *den_); } } if (PROTOBUF_PREDICT_FALSE(_internal_metadata_.have_unknown_fields())) { return ::PROTOBUF_NAMESPACE_ID::internal::ComputeUnknownFieldsSize( _internal_metadata_, total_size, &_cached_size_); } int cached_size = ::PROTOBUF_NAMESPACE_ID::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TransferFunction::MergeFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:ls.proto.systems.TransferFunction) GOOGLE_DCHECK_NE(&from, this); const TransferFunction* source = ::PROTOBUF_NAMESPACE_ID::DynamicCastToGenerated<TransferFunction>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:ls.proto.systems.TransferFunction) ::PROTOBUF_NAMESPACE_ID::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:ls.proto.systems.TransferFunction) MergeFrom(*source); } } void TransferFunction::MergeFrom(const TransferFunction& from) { // @@protoc_insertion_point(class_specific_merge_from_start:ls.proto.systems.TransferFunction) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom<::PROTOBUF_NAMESPACE_ID::UnknownFieldSet>(from._internal_metadata_); ::PROTOBUF_NAMESPACE_ID::uint32 cached_has_bits = 0; (void) cached_has_bits; cached_has_bits = from._has_bits_[0]; if (cached_has_bits & 0x00000003u) { if (cached_has_bits & 0x00000001u) { _internal_mutable_num()->::ls::proto::eigen::VectorXd::MergeFrom(from._internal_num()); } if (cached_has_bits & 0x00000002u) { _internal_mutable_den()->::ls::proto::eigen::VectorXd::MergeFrom(from._internal_den()); } } } void TransferFunction::CopyFrom(const ::PROTOBUF_NAMESPACE_ID::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:ls.proto.systems.TransferFunction) if (&from == this) return; Clear(); MergeFrom(from); } void TransferFunction::CopyFrom(const TransferFunction& from) { // @@protoc_insertion_point(class_specific_copy_from_start:ls.proto.systems.TransferFunction) if (&from == this) return; Clear(); MergeFrom(from); } bool TransferFunction::IsInitialized() const { return true; } void TransferFunction::InternalSwap(TransferFunction* other) { using std::swap; _internal_metadata_.InternalSwap(&other->_internal_metadata_); swap(_has_bits_[0], other->_has_bits_[0]); ::PROTOBUF_NAMESPACE_ID::internal::memswap< PROTOBUF_FIELD_OFFSET(TransferFunction, den_) + sizeof(TransferFunction::den_) - PROTOBUF_FIELD_OFFSET(TransferFunction, num_)>( reinterpret_cast<char*>(&num_), reinterpret_cast<char*>(&other->num_)); } ::PROTOBUF_NAMESPACE_ID::Metadata TransferFunction::GetMetadata() const { return ::PROTOBUF_NAMESPACE_ID::internal::AssignDescriptors( &descriptor_table_ls_2eproto_2esystems_2eproto_getter, &descriptor_table_ls_2eproto_2esystems_2eproto_once, file_level_metadata_ls_2eproto_2esystems_2eproto[1]); } // @@protoc_insertion_point(namespace_scope) } // namespace systems } // namespace proto } // namespace ls PROTOBUF_NAMESPACE_OPEN template<> PROTOBUF_NOINLINE ::ls::proto::systems::StateSpace* Arena::CreateMaybeMessage< ::ls::proto::systems::StateSpace >(Arena* arena) { return Arena::CreateMessageInternal< ::ls::proto::systems::StateSpace >(arena); } template<> PROTOBUF_NOINLINE ::ls::proto::systems::TransferFunction* Arena::CreateMaybeMessage< ::ls::proto::systems::TransferFunction >(Arena* arena) { return Arena::CreateMessageInternal< ::ls::proto::systems::TransferFunction >(arena); } PROTOBUF_NAMESPACE_CLOSE // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
37.136732
192
0.714718
helkebir
9087e0d2276d874818d343f315eff0fe1715ea4c
4,155
cpp
C++
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
1
2021-01-24T10:37:25.000Z
2021-01-24T10:37:25.000Z
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
1
2022-03-28T16:10:27.000Z
2022-03-29T02:53:23.000Z
test/main.cpp
AdamYuan/VulkanQueueSelector
e6c51175cfbb887d08c48a285126c8e9ea2fa033
[ "Unlicense" ]
null
null
null
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN #include "doctest.h" #include "vk_queue_selector.h" #include <cstdio> #include <vector> static void fakeGetPhysicalDeviceQueueFamilyProperties0(VkPhysicalDevice, uint32_t *pQueueFamilyPropertyCount, VkQueueFamilyProperties *pQueueFamilyProperties) { if(pQueueFamilyPropertyCount) *pQueueFamilyPropertyCount = 4; if(pQueueFamilyProperties) { pQueueFamilyProperties[0].queueFlags = VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT; pQueueFamilyProperties[0].queueCount = 10; pQueueFamilyProperties[1].queueFlags = VK_QUEUE_GRAPHICS_BIT; pQueueFamilyProperties[1].queueCount = 3; pQueueFamilyProperties[2].queueFlags = VK_QUEUE_TRANSFER_BIT; pQueueFamilyProperties[2].queueCount = 2; pQueueFamilyProperties[3].queueFlags = VK_QUEUE_COMPUTE_BIT; pQueueFamilyProperties[3].queueCount = 1; } } static VkResult fakeGetPhysicalDeviceSurfaceSupportKHR0(VkPhysicalDevice, uint32_t queueFamilyIndex, VkSurfaceKHR, VkBool32 *pSupported) { constexpr VkBool32 kSurfaceSupport[] = {0, 1, 0, 0}; *pSupported = kSurfaceSupport[queueFamilyIndex]; return VK_SUCCESS; } TEST_CASE("Large requirements and different priorities") { VqsVulkanFunctions functions = {}; functions.vkGetPhysicalDeviceQueueFamilyProperties = fakeGetPhysicalDeviceQueueFamilyProperties0; functions.vkGetPhysicalDeviceSurfaceSupportKHR = fakeGetPhysicalDeviceSurfaceSupportKHR0; VqsQueryCreateInfo createInfo = {}; createInfo.physicalDevice = NULL; VqsQueueRequirements requirements[] = { {VK_QUEUE_GRAPHICS_BIT, 1.0f, (VkSurfaceKHR)(main)}, {VK_QUEUE_GRAPHICS_BIT, 0.8f, (VkSurfaceKHR)(main)}, {VK_QUEUE_COMPUTE_BIT, 1.0f, (VkSurfaceKHR)(main)}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 1.0f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_COMPUTE_BIT, 0.5f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, {VK_QUEUE_TRANSFER_BIT, 1.0f, nullptr}, }; createInfo.queueRequirementCount = std::size(requirements); createInfo.pQueueRequirements = requirements; createInfo.pVulkanFunctions = &functions; VqsQuery query; REQUIRE( vqsCreateQuery(&createInfo, &query) == VK_SUCCESS ); REQUIRE( vqsPerformQuery(query) == VK_SUCCESS ); std::vector<VqsQueueSelection> selections; selections.resize(std::size(requirements)); vqsGetQueueSelections(query, selections.data()); printf("Selections:\n"); for(const VqsQueueSelection &i : selections) { printf("{familyIndex:%d, queueIndex:%d, presentFamilyIndex:%d, presentQueueIndex:%d}\n", i.queueFamilyIndex, i.queueIndex, i.presentQueueFamilyIndex, i.presentQueueIndex); } uint32_t queueCreateInfoCount, queuePriorityCount; vqsEnumerateDeviceQueueCreateInfos(query, &queueCreateInfoCount, nullptr, &queuePriorityCount, nullptr); std::vector<VkDeviceQueueCreateInfo> queueCreateInfos(queueCreateInfoCount); std::vector<float> queuePriorities(queuePriorityCount); vqsEnumerateDeviceQueueCreateInfos(query, &queueCreateInfoCount, queueCreateInfos.data(), &queuePriorityCount, queuePriorities.data()); printf("Creations:\n"); for(const VkDeviceQueueCreateInfo &i : queueCreateInfos) { printf("{familyIndex:%u, queueCount:%u, queuePriorities:[", i.queueFamilyIndex, i.queueCount); for(uint32_t j = 0; j < i.queueCount; ++j) { printf("%.2f", i.pQueuePriorities[j]); if(j < i.queueCount - 1) printf(", "); } printf("]}\n"); } vqsDestroyQuery(query); REQUIRE( queueCreateInfos[2].queueCount == 2 ); REQUIRE( selections[11].queueFamilyIndex == 3 ); }
39.951923
161
0.776895
AdamYuan