text
stringlengths
54
60.6k
<commit_before>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "ComputePolycrystalElasticityTensor.h" #include "RotationTensor.h" template<> InputParameters validParams<ComputePolycrystalElasticityTensor>() { InputParameters params = validParams<ComputeElasticityTensorBase>(); params.addClassDescription("Compute an evolving elasticity tensor coupled to a grain growth phase field model."); params.addRequiredParam<UserObjectName>("grain_tracker", "Name of GrainTracker user object that provides RankFourTensors"); params.addParam<Real>("length_scale", 1.0e-9, "Lengthscale of the problem, in meters"); params.addParam<Real>("pressure_scale", 1.0e6, "Pressure scale of the problem, in pa"); params.addRequiredCoupledVarWithAutoBuild("v", "var_name_base", "op_num", "Array of coupled variables"); return params; } ComputePolycrystalElasticityTensor::ComputePolycrystalElasticityTensor(const InputParameters & parameters) : ComputeElasticityTensorBase(parameters), _length_scale(getParam<Real>("length_scale")), _pressure_scale(getParam<Real>("pressure_scale")), _grain_tracker(getUserObject<GrainDataTracker<RankFourTensor>>("grain_tracker")), _op_num(coupledComponents("v")), _vals(_op_num), _D_elastic_tensor(_op_num), _JtoeV(6.24150974e18) { // Loop over variables (ops) for (unsigned int op = 0; op < _op_num; ++op) { // Initialize variables _vals[op] = &coupledValue("v", op); // declare elasticity tensor derivative properties _D_elastic_tensor[op] = &declarePropertyDerivative<RankFourTensor>(_elasticity_tensor_name, getVar("v", op)->name()); } } void ComputePolycrystalElasticityTensor::computeQpElasticityTensor() { // Get list of active order parameters from grain tracker const std::vector<std::pair<unsigned int, unsigned int> > & active_ops = _grain_tracker.getElementalValues(_current_elem->id()); unsigned int n_active_ops = active_ops.size(); if (n_active_ops < 1 && _t_step > 0) mooseError("No active order parameters"); // Calculate elasticity tensor _elasticity_tensor[_qp].zero(); Real sum_h = 0.0; for (unsigned int op = 0; op < n_active_ops; ++op) { const unsigned int grain_index = active_ops[op].first; const unsigned int op_index = active_ops[op].second; // Interpolation factor for elasticity tensors Real h = (1.0 + std::sin(libMesh::pi * ((*_vals[op_index])[_qp] - 0.5))) / 2.0; // Sum all rotated elasticity tensors _elasticity_tensor[_qp] += _grain_tracker.getData(grain_index) * h; sum_h += h; } const Real tol = 1.0e-10; sum_h = std::max(sum_h, tol); _elasticity_tensor[_qp] /= sum_h; // Calculate elasticity tensor derivative: Cderiv = dhdopi/sum_h * (Cop - _Cijkl) for (unsigned int op = 0; op < _op_num; ++op) (*_D_elastic_tensor[op])[_qp].zero(); for (unsigned int op = 0; op < n_active_ops; ++op) { const unsigned int grain_index = active_ops[op].first; const unsigned int op_index = active_ops[op].second; Real dhdopi = libMesh::pi * std::cos(libMesh::pi * ((*_vals[op_index])[_qp] - 0.5)) / 2.0; RankFourTensor & C_deriv = (*_D_elastic_tensor[op_index])[_qp]; C_deriv = (_grain_tracker.getData(grain_index) - _elasticity_tensor[_qp]) * dhdopi / sum_h; // Convert from XPa to eV/(xm)^3, where X is pressure scale and x is length scale; C_deriv *= _JtoeV * (_length_scale * _length_scale * _length_scale) * _pressure_scale; } } <commit_msg>removing error message (#7685)<commit_after>/****************************************************************/ /* MOOSE - Multiphysics Object Oriented Simulation Environment */ /* */ /* All contents are licensed under LGPL V2.1 */ /* See LICENSE for full restrictions */ /****************************************************************/ #include "ComputePolycrystalElasticityTensor.h" #include "RotationTensor.h" template<> InputParameters validParams<ComputePolycrystalElasticityTensor>() { InputParameters params = validParams<ComputeElasticityTensorBase>(); params.addClassDescription("Compute an evolving elasticity tensor coupled to a grain growth phase field model."); params.addRequiredParam<UserObjectName>("grain_tracker", "Name of GrainTracker user object that provides RankFourTensors"); params.addParam<Real>("length_scale", 1.0e-9, "Lengthscale of the problem, in meters"); params.addParam<Real>("pressure_scale", 1.0e6, "Pressure scale of the problem, in pa"); params.addRequiredCoupledVarWithAutoBuild("v", "var_name_base", "op_num", "Array of coupled variables"); return params; } ComputePolycrystalElasticityTensor::ComputePolycrystalElasticityTensor(const InputParameters & parameters) : ComputeElasticityTensorBase(parameters), _length_scale(getParam<Real>("length_scale")), _pressure_scale(getParam<Real>("pressure_scale")), _grain_tracker(getUserObject<GrainDataTracker<RankFourTensor>>("grain_tracker")), _op_num(coupledComponents("v")), _vals(_op_num), _D_elastic_tensor(_op_num), _JtoeV(6.24150974e18) { // Loop over variables (ops) for (unsigned int op = 0; op < _op_num; ++op) { // Initialize variables _vals[op] = &coupledValue("v", op); // declare elasticity tensor derivative properties _D_elastic_tensor[op] = &declarePropertyDerivative<RankFourTensor>(_elasticity_tensor_name, getVar("v", op)->name()); } } void ComputePolycrystalElasticityTensor::computeQpElasticityTensor() { // Get list of active order parameters from grain tracker const std::vector<std::pair<unsigned int, unsigned int> > & active_ops = _grain_tracker.getElementalValues(_current_elem->id()); unsigned int n_active_ops = active_ops.size(); // Calculate elasticity tensor _elasticity_tensor[_qp].zero(); Real sum_h = 0.0; for (unsigned int op = 0; op < n_active_ops; ++op) { const unsigned int grain_index = active_ops[op].first; const unsigned int op_index = active_ops[op].second; // Interpolation factor for elasticity tensors Real h = (1.0 + std::sin(libMesh::pi * ((*_vals[op_index])[_qp] - 0.5))) / 2.0; // Sum all rotated elasticity tensors _elasticity_tensor[_qp] += _grain_tracker.getData(grain_index) * h; sum_h += h; } const Real tol = 1.0e-10; sum_h = std::max(sum_h, tol); _elasticity_tensor[_qp] /= sum_h; // Calculate elasticity tensor derivative: Cderiv = dhdopi/sum_h * (Cop - _Cijkl) for (unsigned int op = 0; op < _op_num; ++op) (*_D_elastic_tensor[op])[_qp].zero(); for (unsigned int op = 0; op < n_active_ops; ++op) { const unsigned int grain_index = active_ops[op].first; const unsigned int op_index = active_ops[op].second; Real dhdopi = libMesh::pi * std::cos(libMesh::pi * ((*_vals[op_index])[_qp] - 0.5)) / 2.0; RankFourTensor & C_deriv = (*_D_elastic_tensor[op_index])[_qp]; C_deriv = (_grain_tracker.getData(grain_index) - _elasticity_tensor[_qp]) * dhdopi / sum_h; // Convert from XPa to eV/(xm)^3, where X is pressure scale and x is length scale; C_deriv *= _JtoeV * (_length_scale * _length_scale * _length_scale) * _pressure_scale; } } <|endoftext|>
<commit_before>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "precomp.h" using namespace Dml; TensorDesc::TensorDesc( DML_TENSOR_DATA_TYPE dataType, gsl::span<const uint32_t> sizes, std::optional<gsl::span<const uint32_t>> strides, uint32_t guaranteedBaseOffsetAlignment ) { m_tensorType = DML_TENSOR_TYPE_BUFFER; m_bufferTensorDesc.DataType = dataType; m_mlOperatorTensorDataType = GetMlDataTypeFromDmlDataType(dataType); ML_CHECK_VALID_ARGUMENT(gsl::narrow_cast<size_t>(sizes.size()) <= std::size(m_sizes)); std::copy(sizes.begin(), sizes.end(), m_sizes); m_bufferTensorDesc.Sizes = m_sizes; if (strides) { ML_CHECK_VALID_ARGUMENT(strides->size() == sizes.size()); std::copy(strides->begin(), strides->end(), m_strides); m_bufferTensorDesc.Strides = m_strides; } m_bufferTensorDesc.DimensionCount = gsl::narrow_cast<uint32_t>(sizes.size()); m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE; m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment; m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize( m_bufferTensorDesc.DataType, m_bufferTensorDesc.DimensionCount, m_sizes, strides ? m_strides : nullptr ); } TensorDesc::TensorDesc(MLOperatorTensorDataType dataType) { m_mlOperatorTensorDataType = dataType; m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType); // Leave all other fields deferred, including m_tensorType = DML_TENSOR_TYPE_INVALID. } TensorDesc::TensorDesc( MLOperatorTensorDataType dataType, gsl::span<const uint32_t> dimensions, gsl::span<const uint32_t> nonBroadcastDimensions, uint32_t coerceAxis, int32_t placement, // Adjustment offset of the passed dimensions within the minDimensionCount. int32_t leftAlignedDimensionCount, // Number of dimensions that remain left aligned when expanded to minimum count (INT32_MAX means all, 0 means all right aligned). uint32_t minDimensionCount, uint32_t guaranteedBaseOffsetAlignment ) { m_tensorType = DML_TENSOR_TYPE_BUFFER; m_mlOperatorTensorDataType = dataType; m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType); ML_CHECK_VALID_ARGUMENT(ApiTraits::IsValidEnumValue(m_bufferTensorDesc.DataType)); // Flattening coercion isn't always possible when striding is used to broadcast tensors. // Also, placement and split alignment is not implemented in combination with broadcasting. ML_CHECK_VALID_ARGUMENT((nonBroadcastDimensions == dimensions) || ((coerceAxis == TensorAxis::DoNotCoerce) && (placement == W) && (leftAlignedDimensionCount == RightAligned))); gsl::span<const uint32_t> sizes; // If needed, flatten the tensor dimensions to a 2D tensor of size [a_0 * ... * a_{coerceAxis-1}, a_{coerceAxis} * ... * a_{n-1}] // e.g. Flattening [1,2,3,4] with axis 2 yields [2,12]. uint32_t coercedSizes[2]; if (dimensions.size() > 1 && coerceAxis < gsl::narrow_cast<uint32_t>(dimensions.size())) { uint32_t dimension0 = 1u; uint32_t dimension1 = dimensions[coerceAxis]; for (uint32_t i = 0; i < coerceAxis; ++i) { dimension0 *= dimensions[i]; } for (size_t i = coerceAxis + 1, ci = dimensions.size(); i < ci; ++i) { dimension1 *= dimensions[i]; } coercedSizes[0] = dimension0; coercedSizes[1] = dimension1; sizes = coercedSizes; } else { sizes = dimensions; } // Determine the number of dimensions that should be aligned to the left edge when promoting to the minimum dimension count. // Negative values mean align from the right. const int32_t rank = gsl::narrow_cast<int32_t>(sizes.size()); leftAlignedDimensionCount = leftAlignedDimensionCount < 0 ? std::max(0, leftAlignedDimensionCount + rank) : std::min(rank, leftAlignedDimensionCount); ML_CHECK_VALID_ARGUMENT(rank <= MaximumDimensionCount); m_bufferTensorDesc.DimensionCount = std::max(rank, int32_t(minDimensionCount)); // Many DirectML operators accept only certain dimension counts, but it's very common for ONNX models // to have fewer dimensions than that. So this logic massages the dimension count up to what is needed // by filling unused dimensions with size 1, by left-aligning, right-aligning, or even mid-filling. // // e.g.: // // elementwise addition - [H W] -> [1 1 H W], leftAlignedCount = 0, placement = 0 // 1D convolution - [N C W] -> [N C 1 W], leftAlignedCount = 2, placement = 0 // batch normalization - [C] -> [1 C 1 1], leftAlignedCount = 1, placement = 1 // { // Compute the total number of additional dimensions to fill with 1's, // before, after, and in the middle. const int32_t totalFillerCount = m_bufferTensorDesc.DimensionCount - rank; const int32_t leadingFillerCount = std::clamp(placement, 0, totalFillerCount); const int32_t remainingFillerCount = totalFillerCount - leadingFillerCount; const int32_t trailingFillerCount = std::clamp(-placement, 0, remainingFillerCount); const int32_t middleFillerCount = remainingFillerCount - trailingFillerCount; const int32_t firstRightAlignedDim = leadingFillerCount + leftAlignedDimensionCount + middleFillerCount; int i = 0, j = 0; while (j < leadingFillerCount) { m_sizes[j++] = 1; } while (i < leftAlignedDimensionCount) { m_sizes[j++] = sizes[i++]; } while (j < firstRightAlignedDim) { m_sizes[j++] = 1; } while (i < rank) { m_sizes[j++] = sizes[i++]; } while (j < MaximumDimensionCount) { m_sizes[j++] = 1; } } // By default, assume strides are not necessary. bool useStrides = false; if (dimensions != nonBroadcastDimensions) { // If broadcasting is used, then strides are used. useStrides = true; // Walk backwards through both input shapes and broadcast or default each dimension auto nonBroadcastDimsIter = nonBroadcastDimensions.rbegin(); uint32_t elementCount = 1; for (int descDimIndex = m_bufferTensorDesc.DimensionCount - 1; descDimIndex >= 0; --descDimIndex) { if (nonBroadcastDimsIter == nonBroadcastDimensions.rend() || (*nonBroadcastDimsIter == 1)) { m_strides[descDimIndex] = 0; } else { m_strides[descDimIndex] = elementCount; elementCount *= (*nonBroadcastDimsIter); } if (nonBroadcastDimsIter != nonBroadcastDimensions.rend()) { ++nonBroadcastDimsIter; } } } uint64_t endPaddingInBytes = 0; if (dataType == MLOperatorTensorDataType::UInt64 || dataType == MLOperatorTensorDataType::Int64) { // DirectML doesn't support tensor of int64 because Direct3D doesn't support // the data type. A workaround is to use strides to fake 64-bit memory access // while only the lower 32 bits contains the data. This trick obviously doesn't // work if the data element is genuine 64-bit. It also doesn't work if the data // element is negative as the signed bit will be incorrectly interpreted. m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32; // If the strides haven't been calculated yet, initialize them as packed. if (!useStrides) { uint32_t stride = 1; for (int i = m_bufferTensorDesc.DimensionCount - 1; i >= 0; i--) { m_strides[i] = stride; stride *= m_sizes[i]; } } // Double the stride values to emulate 64-bit integer support. for (uint32_t i = 0; i < m_bufferTensorDesc.DimensionCount; ++i) { m_strides[i] *= 2; } useStrides = true; // The physical size of the tensor will have an extra 4 bytes at the end. // DMLCalcBufferTensorSize calculates the minimum implied size, which is based on the last // addressable element of the tensor plus the space for the last element. However, the size // of the last element is now halved from 8 bytes to 4 bytes. // // Example: // Original Tensor: size={2,3}, strides={3,1}, type=int64, size = (1+{1,2}*{3,1})*sizeof(int64) = 6 * 8 = 48 // Emulated Tensor: size={2,3}, strides={6,2}, type=int32, size = (1+{1,2}*{6,2})*sizeof(int32) = 11 * 4 = 44 // // DirectML itself won't read/write the last 4 bytes, but we want the total size to be accurate // so that the entire region can be zeroed. endPaddingInBytes = sizeof(uint32_t); } if (useStrides) { m_bufferTensorDesc.Strides = m_strides; } m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE; m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment; m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize( m_bufferTensorDesc.DataType, m_bufferTensorDesc.DimensionCount, m_sizes, useStrides ? m_strides : nullptr ) + endPaddingInBytes; } gsl::span<const uint32_t> TensorDesc::GetStrides() const { if (m_bufferTensorDesc.Strides == nullptr) { return {}; } return { m_strides, m_strides + m_bufferTensorDesc.DimensionCount }; } DML_TENSOR_DESC TensorDesc::GetDmlDesc() { if (m_tensorType == DML_TENSOR_TYPE_INVALID) { return { m_tensorType, nullptr }; } m_bufferTensorDesc.Sizes = m_sizes; if (m_bufferTensorDesc.Strides) { m_bufferTensorDesc.Strides = m_strides; } // Only buffer tensors are supported right now. assert(m_tensorType == DML_TENSOR_TYPE_BUFFER); return { m_tensorType, &m_bufferTensorDesc }; } // ONNX likes to use signed types for logically unsigned index data. DML avoids this inconsistency and therefore // requires coercion by the caller. void TensorDesc::ForceUnsignedDataType() { static_assert(ApiTraits::EnumValueCount<DML_TENSOR_DATA_TYPE> == 9, "New tensor data type. Update cases."); switch (m_bufferTensorDesc.DataType) { case DML_TENSOR_DATA_TYPE_INT32: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32; break; case DML_TENSOR_DATA_TYPE_INT16: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT16; break; case DML_TENSOR_DATA_TYPE_INT8: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT8; break; // Nothing to do if already unsigned case DML_TENSOR_DATA_TYPE_UINT32: case DML_TENSOR_DATA_TYPE_UINT16: case DML_TENSOR_DATA_TYPE_UINT8: break; default: ML_INVALID_ARGUMENT("Can't coerce unknown or non-integral data type"); } } <commit_msg>TensorDesc::Placement test failure - cherry pick Vibranium fix. (#2328)<commit_after>// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "precomp.h" using namespace Dml; TensorDesc::TensorDesc( DML_TENSOR_DATA_TYPE dataType, gsl::span<const uint32_t> sizes, std::optional<gsl::span<const uint32_t>> strides, uint32_t guaranteedBaseOffsetAlignment ) { m_tensorType = DML_TENSOR_TYPE_BUFFER; m_bufferTensorDesc.DataType = dataType; m_mlOperatorTensorDataType = GetMlDataTypeFromDmlDataType(dataType); ML_CHECK_VALID_ARGUMENT(gsl::narrow_cast<size_t>(sizes.size()) <= std::size(m_sizes)); std::copy(sizes.begin(), sizes.end(), m_sizes); m_bufferTensorDesc.Sizes = m_sizes; if (strides) { ML_CHECK_VALID_ARGUMENT(strides->size() == sizes.size()); std::copy(strides->begin(), strides->end(), m_strides); m_bufferTensorDesc.Strides = m_strides; } m_bufferTensorDesc.DimensionCount = gsl::narrow_cast<uint32_t>(sizes.size()); m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE; m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment; m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize( m_bufferTensorDesc.DataType, m_bufferTensorDesc.DimensionCount, m_sizes, strides ? m_strides : nullptr ); } TensorDesc::TensorDesc(MLOperatorTensorDataType dataType) { m_mlOperatorTensorDataType = dataType; m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType); // Leave all other fields deferred, including m_tensorType = DML_TENSOR_TYPE_INVALID. } TensorDesc::TensorDesc( MLOperatorTensorDataType dataType, gsl::span<const uint32_t> dimensions, // Desired dimensions gsl::span<const uint32_t> nonBroadcastDimensions, // Actual physical dimensions uint32_t coerceAxis, int32_t placement, // Adjustment offset of the passed dimensions within the minDimensionCount. int32_t leftAlignedDimensionCount, // Number of dimensions that remain left aligned when expanded to minimum count (INT32_MAX means all, 0 means all right aligned). uint32_t minDimensionCount, uint32_t guaranteedBaseOffsetAlignment ) { m_tensorType = DML_TENSOR_TYPE_BUFFER; m_mlOperatorTensorDataType = dataType; m_bufferTensorDesc.DataType = GetDmlDataTypeFromMlDataType(dataType); ML_CHECK_VALID_ARGUMENT(ApiTraits::IsValidEnumValue(m_bufferTensorDesc.DataType)); gsl::span<const uint32_t> sizes; // If needed, flatten the tensor dimensions to a 2D tensor of size [a_0 * ... * a_{coerceAxis-1}, a_{coerceAxis} * ... * a_{n-1}] // e.g. Flattening [1,2,3,4] with axis 2 yields [2,12]. uint32_t coercedSizes[2]; if (dimensions.size() > 1 && coerceAxis < gsl::narrow_cast<uint32_t>(dimensions.size())) { uint32_t dimension0 = 1u; uint32_t dimension1 = dimensions[coerceAxis]; for (uint32_t i = 0; i < coerceAxis; ++i) { dimension0 *= dimensions[i]; } for (size_t i = coerceAxis + 1, ci = dimensions.size(); i < ci; ++i) { dimension1 *= dimensions[i]; } coercedSizes[0] = dimension0; coercedSizes[1] = dimension1; sizes = coercedSizes; } else { sizes = dimensions; } //////////////////////////////////////// // Align dimensions // Determine the number of dimensions that should be aligned to the left edge when promoting to the minimum dimension count. // Negative values mean align from the right. const int32_t rank = gsl::narrow_cast<int32_t>(sizes.size()); leftAlignedDimensionCount = leftAlignedDimensionCount < 0 ? std::max(0, leftAlignedDimensionCount + rank) : std::min(rank, leftAlignedDimensionCount); ML_CHECK_VALID_ARGUMENT(rank <= MaximumDimensionCount); m_bufferTensorDesc.DimensionCount = std::max(rank, int32_t(minDimensionCount)); // Many DirectML operators accept only certain dimension counts, but it's very common for ONNX models // to have fewer dimensions than that. So this logic massages the dimension count up to what is needed // by filling unused dimensions with size 1, by left-aligning, right-aligning, or even mid-filling. // // e.g.: // // elementwise addition - [H W] -> [1 1 H W], leftAlignedCount = 0, placement = 0 // 1D convolution - [N C W] -> [N C 1 W], leftAlignedCount = 2, placement = 0 // batch normalization - [C] -> [1 C 1 1], leftAlignedCount = 1, placement = 1 // { // Compute the total number of additional dimensions to fill with 1's, // before, after, and in the middle. const int32_t totalFillerCount = m_bufferTensorDesc.DimensionCount - rank; const int32_t leadingFillerCount = std::clamp(placement, 0, totalFillerCount); const int32_t remainingFillerCount = totalFillerCount - leadingFillerCount; const int32_t trailingFillerCount = std::clamp(-placement, 0, remainingFillerCount); const int32_t middleFillerCount = remainingFillerCount - trailingFillerCount; const int32_t firstRightAlignedDim = leadingFillerCount + leftAlignedDimensionCount + middleFillerCount; int i = 0, j = 0; while (j < leadingFillerCount) { m_sizes[j++] = 1; } while (i < leftAlignedDimensionCount) { m_sizes[j++] = sizes[i++]; } while (j < firstRightAlignedDim) { m_sizes[j++] = 1; } while (i < rank) { m_sizes[j++] = sizes[i++]; } while (j < MaximumDimensionCount) { m_sizes[j++] = 1; } } //////////////////////////////////////// // Coerce the physical shape to the desired shape. // By default, assume strides are not necessary. bool useStrides = false; if (dimensions != nonBroadcastDimensions) { // This broadcasting and subset logic is only applicable to the simple case where all // dimensions are contiguously right aligned, which means no flattening coercion, // placement offset, or split alignment. In such cases, the right side of m_sizes // should match the original dimensions. ML_CHECK_VALID_ARGUMENT(std::equal( dimensions.begin(), dimensions.end(), &m_sizes[m_bufferTensorDesc.DimensionCount - rank], &m_sizes[m_bufferTensorDesc.DimensionCount] )); // Stretch any dimensions with a single element. // // e.g. physical [2,1,4] // desired [2,3,4] // output [2,3,4] // strides [4,0,1] // // If broadcasting is used, then strides are used. useStrides = true; // Walk backwards through both input shapes and broadcast or default each dimension. auto nonBroadcastDimsIter = nonBroadcastDimensions.rbegin(); uint32_t elementCount = 1; for (int descDimIndex = m_bufferTensorDesc.DimensionCount - 1; descDimIndex >= 0; --descDimIndex) { if (nonBroadcastDimsIter == nonBroadcastDimensions.rend() || (*nonBroadcastDimsIter == 1)) { m_strides[descDimIndex] = 0; } else { m_strides[descDimIndex] = elementCount; elementCount *= (*nonBroadcastDimsIter); } if (nonBroadcastDimsIter != nonBroadcastDimensions.rend()) { ++nonBroadcastDimsIter; } } } //////////////////////////////////////// // Handle 64-bit tensors. uint64_t endPaddingInBytes = 0; if (dataType == MLOperatorTensorDataType::UInt64 || dataType == MLOperatorTensorDataType::Int64) { // DirectML doesn't support tensor of int64 because Direct3D doesn't support // the data type. A workaround is to use strides to fake 64-bit memory access // while only the lower 32 bits contains the data. This trick obviously doesn't // work if the data element is genuine 64-bit. It also doesn't work if the data // element is negative as the signed bit will be incorrectly interpreted. m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32; // If the strides haven't been calculated yet, initialize them as packed. if (!useStrides) { uint32_t stride = 1; for (int i = m_bufferTensorDesc.DimensionCount - 1; i >= 0; i--) { m_strides[i] = stride; stride *= m_sizes[i]; } } // Double the stride values to emulate 64-bit integer support. for (uint32_t i = 0; i < m_bufferTensorDesc.DimensionCount; ++i) { m_strides[i] *= 2; } useStrides = true; // The physical size of the tensor will have an extra 4 bytes at the end. // DMLCalcBufferTensorSize calculates the minimum implied size, which is based on the last // addressable element of the tensor plus the space for the last element. However, the size // of the last element is now halved from 8 bytes to 4 bytes. // // Example: // Original Tensor: size={2,3}, strides={3,1}, type=int64, size = (1+{1,2}*{3,1})*sizeof(int64) = 6 * 8 = 48 // Emulated Tensor: size={2,3}, strides={6,2}, type=int32, size = (1+{1,2}*{6,2})*sizeof(int32) = 11 * 4 = 44 // // DirectML itself won't read/write the last 4 bytes, but we want the total size to be accurate // so that the entire region can be zeroed. endPaddingInBytes = sizeof(uint32_t); } if (useStrides) { m_bufferTensorDesc.Strides = m_strides; } m_bufferTensorDesc.Flags = DML_TENSOR_FLAG_NONE; m_bufferTensorDesc.GuaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignment; m_bufferTensorDesc.TotalTensorSizeInBytes = DMLCalcBufferTensorSize( m_bufferTensorDesc.DataType, m_bufferTensorDesc.DimensionCount, m_sizes, useStrides ? m_strides : nullptr ) + endPaddingInBytes; } gsl::span<const uint32_t> TensorDesc::GetStrides() const { if (m_bufferTensorDesc.Strides == nullptr) { return {}; } return { m_strides, m_strides + m_bufferTensorDesc.DimensionCount }; } DML_TENSOR_DESC TensorDesc::GetDmlDesc() { if (m_tensorType == DML_TENSOR_TYPE_INVALID) { return { m_tensorType, nullptr }; } m_bufferTensorDesc.Sizes = m_sizes; if (m_bufferTensorDesc.Strides) { m_bufferTensorDesc.Strides = m_strides; } // Only buffer tensors are supported right now. assert(m_tensorType == DML_TENSOR_TYPE_BUFFER); return { m_tensorType, &m_bufferTensorDesc }; } // ONNX likes to use signed types for logically unsigned index data. DML avoids this inconsistency and therefore // requires coercion by the caller. void TensorDesc::ForceUnsignedDataType() { static_assert(ApiTraits::EnumValueCount<DML_TENSOR_DATA_TYPE> == 9, "New tensor data type. Update cases."); switch (m_bufferTensorDesc.DataType) { case DML_TENSOR_DATA_TYPE_INT32: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT32; break; case DML_TENSOR_DATA_TYPE_INT16: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT16; break; case DML_TENSOR_DATA_TYPE_INT8: m_bufferTensorDesc.DataType = DML_TENSOR_DATA_TYPE_UINT8; break; // Nothing to do if already unsigned case DML_TENSOR_DATA_TYPE_UINT32: case DML_TENSOR_DATA_TYPE_UINT16: case DML_TENSOR_DATA_TYPE_UINT8: break; default: ML_INVALID_ARGUMENT("Can't coerce unknown or non-integral data type"); } } <|endoftext|>
<commit_before>// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. // // Copyright 2015 Heiko Fink, All Rights Reserved. // // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // // Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd. // // Description: // This code implements the Controller functions that are used to connect to the Perception Neuron (TM) Axis Player. // #include "ThirdPersonNeuron.h" #include "ThirdPersonNeuronController.h" // Sets default values AThirdPersonNeuronController::AThirdPersonNeuronController() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AThirdPersonNeuronController::BeginPlay() { Super::BeginPlay(); } // Called every frame void AThirdPersonNeuronController::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Read each tick a new motionline. Additionally motionlines are just discarded. if (bConnected == true) { uint32 BytesPending = 0; if (ReceiverSocket->HasPendingData(BytesPending) == true) { #define SIZEOFDATA 10000 uint8 Data[SIZEOFDATA]; int32 BytesRead = 0; bool bMotionLineBeginFound = false; bool bMotionLineEndFound = false; if (ReceiverSocket->Recv(Data, SIZEOFDATA, BytesRead) == true) { int32 i, j, k; if (MotionLineFormat == Neuron) { // Scan for the beginning of a motion line and synchronize to Avatarname // Neuron BVH output format: // 0 Avatarname 0.00 0.00 ... 0.00 || for (i = j = k = 0; i < BytesRead - 2; i++) { if ((Data[i] == '0') && (Data[i + 1] == ' ') && ((Data[i + 2] < '0') || (Data[i + 2] > '9') || (Data[i + 2] == '-'))) { bMotionLineBeginFound = true; // Skip Avatarname for (j = i + 2; j < BytesRead; j++) { if (Data[j] == ' ') break; } break; } } if (bMotionLineBeginFound == true) { // Scan for the end of the motion line for (k = j; k < BytesRead; k++) { if ((Data[k] == '|') || (Data[k] == '\n') || (Data[k] == '\r')) { bMotionLineEndFound = true; break; } } } } else { // Just synchronize to first float and check if floatcount matches bonecount else try next line // Standard BVH format: // 0.00 0.00 ... 0.00 i = j = k = 0; for (; i < BytesRead - 1;) { for (; i < BytesRead; i++) { if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) { j = i; bMotionLineBeginFound = true; break; } } if (bMotionLineBeginFound == true) { int32 t = 0; bMotionLineEndFound = false; // Scan for the end of the motion line and count empty spaces between floats for (i = j; i < BytesRead - 1; i++) { if (((Data[i] == ' ') || (Data[i] == '\t')) && (((Data[i + 1] >= '0') && (Data[i + 1] <= '9')) || (Data[i + 1] == '-') || (Data[i + 1] == '.'))) t++; if ((Data[i] == '\n') || (Data[i] == '\r')) { bMotionLineEndFound = true; break; } } if (bMotionLineEndFound) { int32 FloatsPerBone = 6; // 3 for x,y,z translation and 3 for x,y,z rotation int32 FloatsPerReference = 6; // 3 for x,y,z translation and 3 for x,y,z rotation if (bDisplacement == false) FloatsPerBone = 3; // If there is no displacement (translation) info we have only 3 floats for rotation left if (bReference == false) FloatsPerReference = 0; // Check if empty spaces matches bone count if (t == ((BoneNr * FloatsPerBone) + FloatsPerReference - 1)) { k = i; break; } } } } } if (bMotionLineEndFound == true) { // We have now a valid motion line captured between j and k // Forward to first value for (i = j; i < k; i++) if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) break; int32 m = 0; // Get all float values from motion line for (int32 f = 0; f < MAXFLOATS && i < k; f++) { // Read ASCII float value into float array if (f >= FloatSkip) { MotionLine[m] = atof((char *)&Data[i]); m++; } // Forward to end of value we read for (; i < k; i++) if (((Data[i] < '0') || (Data[i] > '9')) && (Data[i] != '-') && (Data[i] != '.')) break; // Forward to next value for (; i < k; i++) { // Sanitycheck for line ending if ((Data[i] == '|') || (Data[i] == '\n') || (Data[i] == '\r')) { i = k; // Stop scanning break; } if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) break; } } FloatCount = m; } // End bMotionLineEndFound // If we get more data then we can process per tick, read socket till no more data is left and ignore it while (ReceiverSocket->HasPendingData(BytesPending)) { ReceiverSocket->Recv(Data, SIZEOFDATA, BytesRead); // if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data skipped: %u"), BytesRead)); } } // End Recv } // End HasPendingData } // End bConnected } bool AThirdPersonNeuronController::ParseBVHFile(FString BVHFileName) { // Load BVH file TArray<FString> Lines; if (FFileHelper::LoadANSITextFileToStrings(*(FPaths::GameDir() + FString("Content/") + BVHFileName), NULL, Lines) != true) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Could not load BVH file:%s"), *(FPaths::GameDir() + FString("Content/") + BVHFileName))); } return false; } // Parse BVH file and get bone names, offsets and channels int32 bone = 0; bool bToggle = false; for (int32 i = 0; i < Lines.Num(); i++) { Lines[i].Trim(); if ((Lines[i].StartsWith(TEXT("ROOT"), ESearchCase::IgnoreCase) == true) || (Lines[i].StartsWith(TEXT("JOINT"), ESearchCase::IgnoreCase) == true)) { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 2) { Skeleton[bone].Name = Words[1]; bToggle = true; } } else if (Lines[i].StartsWith(TEXT("OFFSET"), ESearchCase::IgnoreCase) == true) { if (bToggle == true) // Ignore additional offsets from "End Site" { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 4) { Skeleton[bone].Offset[0] = FCString::Atof(*Words[1]); Skeleton[bone].Offset[1] = FCString::Atof(*Words[2]); Skeleton[bone].Offset[2] = FCString::Atof(*Words[3]); bToggle = false; } } } else if (Lines[i].StartsWith(TEXT("CHANNELS"), ESearchCase::IgnoreCase) == true) { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 4) { Skeleton[bone].ChannelCount = FCString::Atoi(*Words[1]); if (Skeleton[bone].ChannelCount != 6) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Channelcount must be 6 on bone:%u"), bone)); } return false; } Skeleton[bone].XPos = Skeleton[bone].YPos = Skeleton[bone].ZPos = 0; Skeleton[bone].XRot = Skeleton[bone].YRot = Skeleton[bone].ZRot = 0; for (int32 j = 0; j < Skeleton[bone].ChannelCount; j++) { // Detect channel order // E.g.: Xposition Yposition Zposition Xrotation Yrotation Zrotation if (Words[j + 2].StartsWith(TEXT("Xposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].XPos = j; else if (Words[j + 2].StartsWith(TEXT("Yposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].YPos = j; else if (Words[j + 2].StartsWith(TEXT("Zposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].ZPos = j; else if (Words[j + 2].StartsWith(TEXT("Xrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].XRot = j; else if (Words[j + 2].StartsWith(TEXT("Yrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].YRot = j; else if (Words[j + 2].StartsWith(TEXT("Zrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].ZRot = j; } // Check if we support rotation order if ((Skeleton[bone].XRot < Skeleton[bone].YRot) && (Skeleton[bone].YRot < Skeleton[bone].ZRot)) // e.g. 123 Skeleton[bone].RotOrder = XYZ; else if ((Skeleton[bone].ZRot < Skeleton[bone].XRot) && (Skeleton[bone].XRot < Skeleton[bone].YRot)) // e.g. 312 Skeleton[bone].RotOrder = ZXY; else if ((Skeleton[bone].YRot < Skeleton[bone].XRot) && (Skeleton[bone].XRot < Skeleton[bone].ZRot)) // e.g. 213 Skeleton[bone].RotOrder = YXZ; else { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Rotation order not supported on bone:%u"), bone)); } return false; } if (bone >= MAXBONES) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Too much bones in BVH file:%u"), bone)); } return false; } bone++; } } } // end of for BoneNr = bone; return true; } // Connect to BVH server (for e.g. Axis Neuron SW) bool AThirdPersonNeuronController::Connect(FString HostName, int32 Port) { if (bConnected == true) return false; // Set up reference bone handling // Template does not support transition for the reference bone yet // Should be no problem, because normally reference bone does not change values. if (bReference == true) { // Skip reference bone x,y,z translation and x,y,z rotation // regardless if displacement is active or not (Axis Neuron sends always 6 floats) FloatSkip = 6; } // Create TCP Socket and connect ISocketSubsystem* const SocketSubSystem = ISocketSubsystem::Get(); if (SocketSubSystem) { ReceiverSocket = SocketSubSystem->CreateSocket(NAME_Stream, TEXT("PerceptionNeuronSocket"), false); if (ReceiverSocket == NULL) return false; auto ResolveInfo = SocketSubSystem->GetHostByName(TCHAR_TO_ANSI(*HostName)); while (!ResolveInfo->IsComplete()); if (ResolveInfo->GetErrorCode() == 0) { const FInternetAddr* Addr = &ResolveInfo->GetResolvedAddress(); uint32 IP; Addr->GetIp(IP); TSharedRef<FInternetAddr> InetAddr = SocketSubSystem->CreateInternetAddr(); InetAddr->SetIp(IP); InetAddr->SetPort(Port); bConnected = ReceiverSocket->Connect(*InetAddr); } } return bConnected; } // Called when the game stops void AThirdPersonNeuronController::BeginDestroy() { Super::BeginDestroy(); Disconnect(); } // Disconnect from BVH server void AThirdPersonNeuronController::Disconnect(void) { if (bConnected == true) { bConnected = false; ReceiverSocket->Close(); } } <commit_msg>Fix a line ending bug in BVH standard format handling<commit_after>// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. // // Copyright 2015 Heiko Fink, All Rights Reserved. // // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // // Perception Neuron (TM) is a trademark of Beijing Noitom Technology Ltd. // // Description: // This code implements the Controller functions that are used to connect to the Perception Neuron (TM) Axis Player. // #include "ThirdPersonNeuron.h" #include "ThirdPersonNeuronController.h" // Sets default values AThirdPersonNeuronController::AThirdPersonNeuronController() { // Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AThirdPersonNeuronController::BeginPlay() { Super::BeginPlay(); } // Called every frame void AThirdPersonNeuronController::Tick(float DeltaTime) { Super::Tick(DeltaTime); // Read each tick a new motionline. Additionally motionlines are just discarded. if (bConnected == true) { uint32 BytesPending = 0; if (ReceiverSocket->HasPendingData(BytesPending) == true) { #define SIZEOFDATA 10000 uint8 Data[SIZEOFDATA]; int32 BytesRead = 0; bool bMotionLineBeginFound = false; bool bMotionLineEndFound = false; if (ReceiverSocket->Recv(Data, SIZEOFDATA, BytesRead) == true) { int32 i, j, k; if (MotionLineFormat == Neuron) { // Scan for the beginning of a motion line and synchronize to Avatarname // Neuron BVH output format: // 0 Avatarname 0.00 0.00 ... 0.00 || for (i = j = k = 0; i < BytesRead - 2; i++) { if ((Data[i] == '0') && (Data[i + 1] == ' ') && ((Data[i + 2] < '0') || (Data[i + 2] > '9') || (Data[i + 2] == '-'))) { bMotionLineBeginFound = true; // Skip Avatarname for (j = i + 2; j < BytesRead; j++) { if (Data[j] == ' ') break; } break; } } if (bMotionLineBeginFound == true) { // Scan for the end of the motion line for (k = j; k < BytesRead; k++) { if ((Data[k] == '|') || (Data[k] == '\n') || (Data[k] == '\r')) { bMotionLineEndFound = true; break; } } } } else { // Just synchronize to first float and check if floatcount matches bonecount else try next line // Standard BVH format: // 0.00 0.00 ... 0.00 i = j = k = 0; for (; i < BytesRead - 1;) { for (; i < BytesRead; i++) { if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) { j = i; bMotionLineBeginFound = true; break; } } if (bMotionLineBeginFound == true) { int32 t = 0; bMotionLineEndFound = false; // Scan for the end of the motion line and count empty spaces between floats for (i = j; i < BytesRead; i++) { if (i < (BytesRead - 1)) if (((Data[i] == ' ') || (Data[i] == '\t')) && (((Data[i + 1] >= '0') && (Data[i + 1] <= '9')) || (Data[i + 1] == '-') || (Data[i + 1] == '.'))) t++; if ((Data[i] == '\n') || (Data[i] == '\r')) { bMotionLineEndFound = true; break; } } if (bMotionLineEndFound) { int32 FloatsPerBone = 6; // 3 for x,y,z translation and 3 for x,y,z rotation int32 FloatsPerReference = 6; // 3 for x,y,z translation and 3 for x,y,z rotation if (bDisplacement == false) FloatsPerBone = 3; // If there is no displacement (translation) info we have only 3 floats for rotation left if (bReference == false) FloatsPerReference = 0; // Check if empty spaces matches bone count if (t == ((BoneNr * FloatsPerBone) + FloatsPerReference - 1)) { k = i; break; } } } } } if (bMotionLineEndFound == true) { // We have now a valid motion line captured between j and k // Forward to first value for (i = j; i < k; i++) if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) break; int32 m = 0; // Get all float values from motion line for (int32 f = 0; f < MAXFLOATS && i < k; f++) { // Read ASCII float value into float array if (f >= FloatSkip) { MotionLine[m] = atof((char *)&Data[i]); m++; } // Forward to end of value we read for (; i < k; i++) if (((Data[i] < '0') || (Data[i] > '9')) && (Data[i] != '-') && (Data[i] != '.')) break; // Forward to next value for (; i < k; i++) { // Sanitycheck for line ending if ((Data[i] == '|') || (Data[i] == '\n') || (Data[i] == '\r')) { i = k; // Stop scanning break; } if ((Data[i] >= '0') && (Data[i] <= '9') || (Data[i] == '-') || (Data[i] == '.')) break; } } FloatCount = m; } // End bMotionLineEndFound // If we get more data then we can process per tick, read socket till no more data is left and ignore it while (ReceiverSocket->HasPendingData(BytesPending)) { ReceiverSocket->Recv(Data, SIZEOFDATA, BytesRead); // if (GEngine) GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data skipped: %u"), BytesRead)); } } // End Recv } // End HasPendingData } // End bConnected } bool AThirdPersonNeuronController::ParseBVHFile(FString BVHFileName) { // Load BVH file TArray<FString> Lines; if (FFileHelper::LoadANSITextFileToStrings(*(FPaths::GameDir() + FString("Content/") + BVHFileName), NULL, Lines) != true) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Could not load BVH file:%s"), *(FPaths::GameDir() + FString("Content/") + BVHFileName))); } return false; } // Parse BVH file and get bone names, offsets and channels int32 bone = 0; bool bToggle = false; for (int32 i = 0; i < Lines.Num(); i++) { Lines[i].Trim(); if ((Lines[i].StartsWith(TEXT("ROOT"), ESearchCase::IgnoreCase) == true) || (Lines[i].StartsWith(TEXT("JOINT"), ESearchCase::IgnoreCase) == true)) { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 2) { Skeleton[bone].Name = Words[1]; bToggle = true; } } else if (Lines[i].StartsWith(TEXT("OFFSET"), ESearchCase::IgnoreCase) == true) { if (bToggle == true) // Ignore additional offsets from "End Site" { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 4) { Skeleton[bone].Offset[0] = FCString::Atof(*Words[1]); Skeleton[bone].Offset[1] = FCString::Atof(*Words[2]); Skeleton[bone].Offset[2] = FCString::Atof(*Words[3]); bToggle = false; } } } else if (Lines[i].StartsWith(TEXT("CHANNELS"), ESearchCase::IgnoreCase) == true) { TArray<FString> Words; if (Lines[i].ParseIntoArray(Words, TEXT(" "), false) >= 4) { Skeleton[bone].ChannelCount = FCString::Atoi(*Words[1]); if (Skeleton[bone].ChannelCount != 6) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Channelcount must be 6 on bone:%u"), bone)); } return false; } Skeleton[bone].XPos = Skeleton[bone].YPos = Skeleton[bone].ZPos = 0; Skeleton[bone].XRot = Skeleton[bone].YRot = Skeleton[bone].ZRot = 0; for (int32 j = 0; j < Skeleton[bone].ChannelCount; j++) { // Detect channel order // E.g.: Xposition Yposition Zposition Xrotation Yrotation Zrotation if (Words[j + 2].StartsWith(TEXT("Xposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].XPos = j; else if (Words[j + 2].StartsWith(TEXT("Yposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].YPos = j; else if (Words[j + 2].StartsWith(TEXT("Zposition"), ESearchCase::IgnoreCase) == true) Skeleton[bone].ZPos = j; else if (Words[j + 2].StartsWith(TEXT("Xrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].XRot = j; else if (Words[j + 2].StartsWith(TEXT("Yrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].YRot = j; else if (Words[j + 2].StartsWith(TEXT("Zrotation"), ESearchCase::IgnoreCase) == true) Skeleton[bone].ZRot = j; } // Check if we support rotation order if ((Skeleton[bone].XRot < Skeleton[bone].YRot) && (Skeleton[bone].YRot < Skeleton[bone].ZRot)) // e.g. 123 Skeleton[bone].RotOrder = XYZ; else if ((Skeleton[bone].ZRot < Skeleton[bone].XRot) && (Skeleton[bone].XRot < Skeleton[bone].YRot)) // e.g. 312 Skeleton[bone].RotOrder = ZXY; else if ((Skeleton[bone].YRot < Skeleton[bone].XRot) && (Skeleton[bone].XRot < Skeleton[bone].ZRot)) // e.g. 213 Skeleton[bone].RotOrder = YXZ; else { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Rotation order not supported on bone:%u"), bone)); } return false; } if (bone >= MAXBONES) { if (GEngine) { GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Too much bones in BVH file:%u"), bone)); } return false; } bone++; } } } // end of for BoneNr = bone; return true; } // Connect to BVH server (for e.g. Axis Neuron SW) bool AThirdPersonNeuronController::Connect(FString HostName, int32 Port) { if (bConnected == true) return false; // Set up reference bone handling // Template does not support transition for the reference bone yet // Should be no problem, because normally reference bone does not change values. if (bReference == true) { // Skip reference bone x,y,z translation and x,y,z rotation // regardless if displacement is active or not (Axis Neuron sends always 6 floats) FloatSkip = 6; } // Create TCP Socket and connect ISocketSubsystem* const SocketSubSystem = ISocketSubsystem::Get(); if (SocketSubSystem) { ReceiverSocket = SocketSubSystem->CreateSocket(NAME_Stream, TEXT("PerceptionNeuronSocket"), false); if (ReceiverSocket == NULL) return false; auto ResolveInfo = SocketSubSystem->GetHostByName(TCHAR_TO_ANSI(*HostName)); while (!ResolveInfo->IsComplete()); if (ResolveInfo->GetErrorCode() == 0) { const FInternetAddr* Addr = &ResolveInfo->GetResolvedAddress(); uint32 IP; Addr->GetIp(IP); TSharedRef<FInternetAddr> InetAddr = SocketSubSystem->CreateInternetAddr(); InetAddr->SetIp(IP); InetAddr->SetPort(Port); bConnected = ReceiverSocket->Connect(*InetAddr); } } return bConnected; } // Called when the game stops void AThirdPersonNeuronController::BeginDestroy() { Super::BeginDestroy(); Disconnect(); } // Disconnect from BVH server void AThirdPersonNeuronController::Disconnect(void) { if (bConnected == true) { bConnected = false; ReceiverSocket->Close(); } } <|endoftext|>
<commit_before>/* Copyright (c) 2017-2018 Andrew Depke */ #include "LinuxStackTrace.h" #include "../../Math/MathCore.h" #include <cxxabi.h> #include <execinfo.h> namespace Red { bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output) { if (!Output || MaxDepth <= 0) { return false; } size_t Frames = 0; void* RawStackTrace[128]; Frames = backtrace(RawStackTrace, Min(MaxDepth, 128)); if (Frames <= 0) { return false; } char** StackTrace = backtrace_symbols(RawStackTrace, Frames); for (size_t Iter = 0; Iter < Frames; ++Iter) { std::string FrameString = StackTrace[Iter]; StackFrame Frame; char FrameAddressBuffer[64]; snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]); // Assume 64 Bit Addresses. Frame.Address = FrameAddressBuffer; size_t ModuleNameEnd = FrameString.find('(') - 1; Frame.Module = FrameString.substr(0, ModuleNameEnd); size_t FunctionNameStart = FrameString.find('(') + 1; size_t FunctionNameEnd = FrameString.find('+') - 1; #ifdef HAVE_CXA_DEMANGLE int OperationStatus = 0; char* DemangledName = abi::__cxa_demangle(FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart).c_str(), nullptr, nullptr, &OperationStatus); if (OperationStatus == 0) { Frame.Function = DemangledName; free(DemangledName); } else { Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart); } #else Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart); #endif } return true; } } // namespace Red <commit_msg>Fixed Stack Tracer Not Outputting<commit_after>/* Copyright (c) 2017-2018 Andrew Depke */ #include "LinuxStackTrace.h" #include "../../Math/MathCore.h" #include <cxxabi.h> #include <execinfo.h> namespace Red { bool CaptureStackTrace(int MaxDepth, std::vector<StackFrame>* Output) { if (!Output || MaxDepth <= 0) { return false; } size_t Frames = 0; void* RawStackTrace[128]; Frames = backtrace(RawStackTrace, Min(MaxDepth, 128)); if (Frames <= 0) { return false; } char** StackTrace = backtrace_symbols(RawStackTrace, Frames); for (size_t Iter = 0; Iter < Frames; ++Iter) { std::string FrameString = StackTrace[Iter]; StackFrame Frame; char FrameAddressBuffer[64]; snprintf(FrameAddressBuffer, sizeof(FrameAddressBuffer), "0x%016llX", (unsigned long long int)RawStackTrace[Iter]); // Assume 64 Bit Addresses. Frame.Address = FrameAddressBuffer; size_t ModuleNameEnd = FrameString.find('(') - 1; Frame.Module = FrameString.substr(0, ModuleNameEnd); size_t FunctionNameStart = FrameString.find('(') + 1; size_t FunctionNameEnd = FrameString.find('+') - 1; #ifdef HAVE_CXA_DEMANGLE int OperationStatus = 0; char* DemangledName = abi::__cxa_demangle(FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart).c_str(), nullptr, nullptr, &OperationStatus); if (OperationStatus == 0) { Frame.Function = DemangledName; free(DemangledName); } else { Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart); } #else Frame.Function = FrameString.substr(FunctionNameStart, FunctionNameEnd - FunctionNameStart); #endif Output->push_back(Frame); } return true; } } // namespace Red <|endoftext|>
<commit_before>/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "cameracontrollercomponent.h" #include <core/debughelper.h> #include <graphics/camera.h> #include <engine/gameobject.h> #include <graphics/engine.h> REGISTER_OBJECTTYPE(GluonEngine, CameraControllerComponent) using namespace GluonEngine; class CameraControllerComponent::CameraControllerComponentPrivate { public: CameraControllerComponentPrivate() { camera = 0; active = false; } GluonGraphics::Camera *camera; bool active; static GluonGraphics::Camera *activeCamera; }; GluonGraphics::Camera* CameraControllerComponent::CameraControllerComponentPrivate::activeCamera = 0; CameraControllerComponent::CameraControllerComponent ( QObject* parent ) : Component ( parent ) { d = new CameraControllerComponentPrivate; } CameraControllerComponent::CameraControllerComponent ( const CameraControllerComponent& other ) : Component ( other ), d(other.d) { } CameraControllerComponent::~CameraControllerComponent() { delete d->camera; delete d; } void CameraControllerComponent::start() { if(!d->camera) d->camera = new GluonGraphics::Camera(); if(d->active) GluonGraphics::Engine::instance()->setActiveCamera(d->camera); } void CameraControllerComponent::draw ( int timeLapse ) { Q_UNUSED(timeLapse) #warning TODO: Set rotation/fov/all that crap d->camera->setPosition(gameObject()->position()); } void CameraControllerComponent::update ( int elapsedMilliseconds ) { Q_UNUSED(elapsedMilliseconds) } bool CameraControllerComponent::isActive() { return d->active; } void CameraControllerComponent::setActive(bool active) { d->active = active; if(active && d->camera) { CameraControllerComponentPrivate::activeCamera = d->camera; GluonGraphics::Engine::instance()->setActiveCamera(d->camera); } } Q_EXPORT_PLUGIN2(gluon_component_cameracontroller, GluonEngine::CameraControllerComponent); #include "cameracontrollercomponent.moc" <commit_msg>Check whether we actually have a camera. Avoids crashes. :)<commit_after>/* This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License version 2 as published by the Free Software Foundation. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "cameracontrollercomponent.h" #include <core/debughelper.h> #include <graphics/camera.h> #include <engine/gameobject.h> #include <graphics/engine.h> REGISTER_OBJECTTYPE(GluonEngine, CameraControllerComponent) using namespace GluonEngine; class CameraControllerComponent::CameraControllerComponentPrivate { public: CameraControllerComponentPrivate() { camera = 0; active = false; } GluonGraphics::Camera *camera; bool active; static GluonGraphics::Camera *activeCamera; }; GluonGraphics::Camera* CameraControllerComponent::CameraControllerComponentPrivate::activeCamera = 0; CameraControllerComponent::CameraControllerComponent ( QObject* parent ) : Component ( parent ) { d = new CameraControllerComponentPrivate; } CameraControllerComponent::CameraControllerComponent ( const CameraControllerComponent& other ) : Component ( other ), d(other.d) { } CameraControllerComponent::~CameraControllerComponent() { delete d->camera; delete d; } void CameraControllerComponent::start() { if(!d->camera) d->camera = new GluonGraphics::Camera(); if(d->active) GluonGraphics::Engine::instance()->setActiveCamera(d->camera); } void CameraControllerComponent::draw ( int timeLapse ) { Q_UNUSED(timeLapse) #warning TODO: Set rotation/fov/all that crap if(d->camera) d->camera->setPosition(gameObject()->position()); } void CameraControllerComponent::update ( int elapsedMilliseconds ) { Q_UNUSED(elapsedMilliseconds) } bool CameraControllerComponent::isActive() { return d->active; } void CameraControllerComponent::setActive(bool active) { d->active = active; if(active && d->camera) { CameraControllerComponentPrivate::activeCamera = d->camera; GluonGraphics::Engine::instance()->setActiveCamera(d->camera); } } Q_EXPORT_PLUGIN2(gluon_component_cameracontroller, GluonEngine::CameraControllerComponent); #include "cameracontrollercomponent.moc" <|endoftext|>
<commit_before>#ifndef _MSP_GPIO_HPP #define _MSP_GPIO_HPP #include <stdint.h> #include <msp430.h> #include "utilities/utilities.hpp" namespace McuPeripheral { template<uint8_t _input, uint8_t _select2> class McuPort { public: static const uint8_t mInputReg = _input; static const uint8_t mOutputReg = _input+1; static const uint8_t mDirectionReg = _input+2; static const uint8_t mIntFlagReg = _input+3; static const uint8_t mIntEdgeSelReg = _input+4; static const uint8_t mIntEnableReg = _input+5; static const uint8_t mSelectReg = _input+6; static const uint8_t mResistorReg = _input+7; static const uint8_t mSelect2Reg = _select2; }; template < class _port, uint8_t _pin > class McuPin { public: static void set() { *((volatile uint8_t*)_port::mOutputReg) |= _pin; } static bool read() { return *((volatile uint8_t*)_port::mInputReg) & _pin; } static void clear() { *((volatile uint8_t*)_port::mOutputReg) &= ~_pin; } static void toggle() { *((volatile uint8_t*)_port::mOutputReg) ^= _pin; } static void output() { *((volatile uint8_t*)_port::mDirectionReg) |= _pin; } static void input() { *((volatile uint8_t*)_port::mDirectionReg) &= ~_pin; } static void pullUp() { *((volatile uint8_t*)_port::mResistor) |= _pin; set(); } static void pullDown() { *((volatile uint8_t*)_port::mResistor) |= _pin; clear(); } static void pullOff() { *((volatile uint8_t*)_port::mResistor) &= ~_pin; } static void intEnable() { *((volatile uint8_t*)_port::mIntEnableReg) |= _pin; } static void intDisable() { *((volatile uint8_t*)_port::mIntEnableReg) &= ~_pin; } static void edgeHighToLow() { *((volatile uint8_t*)_port::mIntEdgeSelReg) |= _pin; } static void edgeLowToHigh() { *((volatile uint8_t*)_port::mIntEdgeSelReg) &= ~_pin; } static bool irqFlag() { return *((volatile uint8_t*)_port::mInputReg) & _pin; } static void selectOff() { *((volatile uint8_t*)_port::mSelectReg) &= ~_pin; } static void select2Off() { *((volatile uint8_t*)_port::mSelect2Reg) &= ~_pin; } static void selectOn() { *((volatile uint8_t*)_port::mSelectReg) |= _pin; } static void select2On() { *((volatile uint8_t*)_port::mSelect2Reg) |= _pin; } static void setPinIrqHandler(callback_t cb, callback_args_t args) { mPinHandler = cb; mPinArgs = args; } static callback_t mPinHandler; static callback_args_t mPinArgs; }; template < class _port, uint8_t _pin > callback_t McuPin<_port,_pin>::mPinHandler; template < class _port, uint8_t _pin > callback_args_t McuPin<_port,_pin>::mPinArgs; class FakePin { public: static void set() { return; } static bool read() { return true; } static void clear() { return; } static void toggle() { return; } static void output() { return; } static void input() { return; } static void pull_up() { return; } static void pull_down() { return; } static void pull_off() { return; } static void select_off() { return; } static void select2_off() { return; } static void selectOn() { return; } static void select2On() { return; } }; } using McuPort1 = McuPeripheral::McuPort<P1IN_,P1SEL2_>; using McuPort2 = McuPeripheral::McuPort<P2IN_,P2SEL2_>; #endif //_MSP_GPIO_HPP <commit_msg>Added ability to get gpio bit of pin, if fake pin then returns 0.<commit_after>#ifndef _MSP_GPIO_HPP #define _MSP_GPIO_HPP #include <stdint.h> #include <msp430.h> #include "utilities/utilities.hpp" namespace McuPeripheral { template<uint8_t _input, uint8_t _select2> class McuPort { public: static const uint8_t mInputReg = _input; static const uint8_t mOutputReg = _input+1; static const uint8_t mDirectionReg = _input+2; static const uint8_t mIntFlagReg = _input+3; static const uint8_t mIntEdgeSelReg = _input+4; static const uint8_t mIntEnableReg = _input+5; static const uint8_t mSelectReg = _input+6; static const uint8_t mResistorReg = _input+7; static const uint8_t mSelect2Reg = _select2; }; template < class _port, uint8_t _pin > class McuPin { public: static void set() { *((volatile uint8_t*)_port::mOutputReg) |= _pin; } static bool read() { return *((volatile uint8_t*)_port::mInputReg) & _pin; } static void clear() { *((volatile uint8_t*)_port::mOutputReg) &= ~_pin; } static void toggle() { *((volatile uint8_t*)_port::mOutputReg) ^= _pin; } static void output() { *((volatile uint8_t*)_port::mDirectionReg) |= _pin; } static void input() { *((volatile uint8_t*)_port::mDirectionReg) &= ~_pin; } static void pullUp() { *((volatile uint8_t*)_port::mResistor) |= _pin; set(); } static void pullDown() { *((volatile uint8_t*)_port::mResistor) |= _pin; clear(); } static void pullOff() { *((volatile uint8_t*)_port::mResistor) &= ~_pin; } static void intEnable() { *((volatile uint8_t*)_port::mIntEnableReg) |= _pin; } static void intDisable() { *((volatile uint8_t*)_port::mIntEnableReg) &= ~_pin; } static void edgeHighToLow() { *((volatile uint8_t*)_port::mIntEdgeSelReg) |= _pin; } static void edgeLowToHigh() { *((volatile uint8_t*)_port::mIntEdgeSelReg) &= ~_pin; } static bool irqFlag() { return *((volatile uint8_t*)_port::mInputReg) & _pin; } static void selectOff() { *((volatile uint8_t*)_port::mSelectReg) &= ~_pin; } static void select2Off() { *((volatile uint8_t*)_port::mSelect2Reg) &= ~_pin; } static void selectOn() { *((volatile uint8_t*)_port::mSelectReg) |= _pin; } static void select2On() { *((volatile uint8_t*)_port::mSelect2Reg) |= _pin; } static void setPinIrqHandler(callback_t cb, callback_args_t args) { mPinHandler = cb; mPinArgs = args; } static constexpr uint8_t getBitValue() { return _pin; } static callback_t mPinHandler; static callback_args_t mPinArgs; }; template < class _port, uint8_t _pin > callback_t McuPin<_port,_pin>::mPinHandler; template < class _port, uint8_t _pin > callback_args_t McuPin<_port,_pin>::mPinArgs; class FakePin { public: static void set() { return; } static bool read() { return true; } static void clear() { return; } static void toggle() { return; } static void output() { return; } static void input() { return; } static void pull_up() { return; } static void pull_down() { return; } static void pull_off() { return; } static void select_off() { return; } static void select2_off() { return; } static void selectOn() { return; } static void select2On() { return; } static constexpr uint8_t getBitValue() { return 0; } }; } using McuPort1 = McuPeripheral::McuPort<P1IN_,P1SEL2_>; using McuPort2 = McuPeripheral::McuPort<P2IN_,P2SEL2_>; #endif //_MSP_GPIO_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010 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/printing/print_job.h" #include "base/message_loop.h" #include "base/timer.h" #include "chrome/browser/printing/print_job_worker.h" #include "chrome/common/notification_service.h" #include "printing/printed_document.h" #include "printing/printed_page.h" using base::TimeDelta; namespace printing { PrintJob::PrintJob() : ui_message_loop_(MessageLoop::current()), source_(NULL), worker_(), settings_(), is_job_pending_(false), is_print_dialog_box_shown_(false), is_canceling_(false) { DCHECK(ui_message_loop_); // This is normally a UI message loop, but in unit tests, the message loop is // of the 'default' type. DCHECK(ui_message_loop_->type() == MessageLoop::TYPE_UI || ui_message_loop_->type() == MessageLoop::TYPE_DEFAULT); ui_message_loop_->AddDestructionObserver(this); } PrintJob::~PrintJob() { ui_message_loop_->RemoveDestructionObserver(this); // The job should be finished (or at least canceled) when it is destroyed. DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_canceling_); if (worker_.get()) DCHECK(worker_->message_loop() == NULL); DCHECK_EQ(ui_message_loop_, MessageLoop::current()); } void PrintJob::Initialize(PrintJobWorkerOwner* job, PrintedPagesSource* source) { DCHECK(!source_); DCHECK(!worker_.get()); DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_canceling_); DCHECK(!document_.get()); source_ = source; worker_.reset(job->DetachWorker(this)); settings_ = job->settings(); UpdatePrintedDocument(new PrintedDocument(settings_, source_, job->cookie())); // Don't forget to register to our own messages. registrar_.Add(this, NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this)); } void PrintJob::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); switch (type.value) { case NotificationType::PRINT_JOB_EVENT: { OnNotifyPrintJobEvent(*Details<JobEventDetails>(details).ptr()); break; } default: { break; } } } void PrintJob::GetSettingsDone(const PrintSettings& new_settings, PrintingContext::Result result) { NOTREACHED(); } PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) { NOTREACHED(); return NULL; } MessageLoop* PrintJob::message_loop() { return ui_message_loop_; } const PrintSettings& PrintJob::settings() const { return settings_; } int PrintJob::cookie() const { if (!document_.get()) // Always use an invalid cookie in this case. return 0; return document_->cookie(); } void PrintJob::WillDestroyCurrentMessageLoop() { NOTREACHED(); } void PrintJob::StartPrinting() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); DCHECK(worker_->message_loop()); DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); if (!worker_->message_loop() || is_job_pending_) return; // Real work is done in PrintJobWorker::StartPrinting(). worker_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::StartPrinting, document_)); // Set the flag right now. is_job_pending_ = true; // Tell everyone! scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); } void PrintJob::Stop() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); // Be sure to live long enough. scoped_refptr<PrintJob> handle(this); MessageLoop* worker_loop = worker_->message_loop(); if (worker_loop) { if (is_print_dialog_box_shown_) { // Make sure there is no Print... dialog box. worker_loop->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::DismissDialog)); is_print_dialog_box_shown_ = false; } ControlledWorkerShutdown(); is_job_pending_ = false; registrar_.Remove(this, NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this)); } // Flush the cached document. UpdatePrintedDocument(NULL); } void PrintJob::Cancel() { if (is_canceling_) return; is_canceling_ = true; // Be sure to live long enough. scoped_refptr<PrintJob> handle(this); DCHECK_EQ(ui_message_loop_, MessageLoop::current()); MessageLoop* worker_loop = worker_.get() ? worker_->message_loop() : NULL; if (worker_loop) { // Call this right now so it renders the context invalid. Do not use // InvokeLater since it would take too much time. worker_->Cancel(); } // Make sure a Cancel() is broadcast. scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::FAILED, NULL, NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); Stop(); is_canceling_ = false; } bool PrintJob::FlushJob(int timeout_ms) { // Make sure the object outlive this message loop. scoped_refptr<PrintJob> handle(this); // Stop() will eventually be called, which will get out of the inner message // loop. But, don't take it for granted and set a timer in case something goes // wrong. base::OneShotTimer<MessageLoop> quit_task; if (timeout_ms) { quit_task.Start(TimeDelta::FromMilliseconds(timeout_ms), MessageLoop::current(), &MessageLoop::Quit); } bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); MessageLoop::current()->Run(); // Restore task state. MessageLoop::current()->SetNestableTasksAllowed(old_state); return true; } void PrintJob::DisconnectSource() { source_ = NULL; if (document_.get()) document_->DisconnectSource(); } bool PrintJob::is_job_pending() const { return is_job_pending_; } bool PrintJob::is_print_dialog_box_shown() const { return is_print_dialog_box_shown_; } PrintedDocument* PrintJob::document() const { return document_.get(); } void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) { if (document_.get() == new_document) return; document_ = new_document; if (document_.get()) { settings_ = document_->settings(); } if (worker_.get() && worker_->message_loop()) { DCHECK(!is_job_pending_); // Sync the document with the worker. worker_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::OnDocumentChanged, document_)); } } void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) { switch (event_details.type()) { case JobEventDetails::FAILED: { settings_.Clear(); // Update internal state. is_print_dialog_box_shown_ = false; // No need to cancel since the worker already canceled itself. Stop(); break; } case JobEventDetails::USER_INIT_DONE: case JobEventDetails::DEFAULT_INIT_DONE: case JobEventDetails::USER_INIT_CANCELED: { DCHECK_EQ(event_details.document(), document_.get()); break; } case JobEventDetails::NEW_DOC: case JobEventDetails::NEW_PAGE: case JobEventDetails::PAGE_DONE: case JobEventDetails::JOB_DONE: case JobEventDetails::ALL_PAGES_REQUESTED: { // Don't care. break; } case JobEventDetails::DOC_DONE: { // This will call Stop() and broadcast a JOB_DONE message. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &PrintJob::OnDocumentDone)); break; } default: { NOTREACHED(); break; } } } void PrintJob::OnDocumentDone() { // Be sure to live long enough. The instance could be destroyed by the // JOB_DONE broadcast. scoped_refptr<PrintJob> handle(this); // Stop the worker thread. Stop(); scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); } void PrintJob::ControlledWorkerShutdown() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); // The deadlock this code works around is specific to window messaging on // Windows, so we aren't likely to need it on any other platforms. #if defined(OS_WIN) // We could easily get into a deadlock case if worker_->Stop() is used; the // printer driver created a window as a child of the browser window. By // canceling the job, the printer driver initiated dialog box is destroyed, // which sends a blocking message to its parent window. If the browser window // thread is not processing messages, a deadlock occurs. // // This function ensures that the dialog box will be destroyed in a timely // manner by the mere fact that the thread will terminate. So the potential // deadlock is eliminated. worker_->StopSoon(); // Run a tight message loop until the worker terminates. It may seems like a // hack but I see no other way to get it to work flawlessly. The issues here // are: // - We don't want to run tasks while the thread is quitting. // - We want this code path to wait on the thread to quit before continuing. MSG msg; HANDLE thread_handle = worker_->thread_handle(); for (; thread_handle;) { // Note that we don't do any kind of message priorization since we don't // execute any pending task or timer. DWORD result = MsgWaitForMultipleObjects(1, &thread_handle, FALSE, INFINITE, QS_ALLINPUT); if (result == WAIT_OBJECT_0 + 1) { while (PeekMessage(&msg, NULL, 0, 0, TRUE) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } // Continue looping. } else if (result == WAIT_OBJECT_0) { // The thread quit. break; } else { // An error occured. Assume the thread quit. NOTREACHED(); break; } } #endif // Now make sure the thread object is cleaned up. worker_->Stop(); } // Takes settings_ ownership and will be deleted in the receiving thread. JobEventDetails::JobEventDetails(Type type, PrintedDocument* document, PrintedPage* page) : document_(document), page_(page), type_(type) { } JobEventDetails::~JobEventDetails() { } PrintedDocument* JobEventDetails::document() const { return document_; } PrintedPage* JobEventDetails::page() const { return page_; } } // namespace printing <commit_msg>Printing: Allow file IO on the UI thread.<commit_after>// Copyright (c) 2010 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/printing/print_job.h" #include "base/message_loop.h" #include "base/thread_restrictions.h" #include "base/timer.h" #include "chrome/browser/printing/print_job_worker.h" #include "chrome/common/notification_service.h" #include "printing/printed_document.h" #include "printing/printed_page.h" using base::TimeDelta; namespace printing { PrintJob::PrintJob() : ui_message_loop_(MessageLoop::current()), source_(NULL), worker_(), settings_(), is_job_pending_(false), is_print_dialog_box_shown_(false), is_canceling_(false) { DCHECK(ui_message_loop_); // This is normally a UI message loop, but in unit tests, the message loop is // of the 'default' type. DCHECK(ui_message_loop_->type() == MessageLoop::TYPE_UI || ui_message_loop_->type() == MessageLoop::TYPE_DEFAULT); ui_message_loop_->AddDestructionObserver(this); } PrintJob::~PrintJob() { ui_message_loop_->RemoveDestructionObserver(this); // The job should be finished (or at least canceled) when it is destroyed. DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_canceling_); if (worker_.get()) DCHECK(worker_->message_loop() == NULL); DCHECK_EQ(ui_message_loop_, MessageLoop::current()); } void PrintJob::Initialize(PrintJobWorkerOwner* job, PrintedPagesSource* source) { DCHECK(!source_); DCHECK(!worker_.get()); DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); DCHECK(!is_canceling_); DCHECK(!document_.get()); source_ = source; worker_.reset(job->DetachWorker(this)); settings_ = job->settings(); UpdatePrintedDocument(new PrintedDocument(settings_, source_, job->cookie())); // Don't forget to register to our own messages. registrar_.Add(this, NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this)); } void PrintJob::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); switch (type.value) { case NotificationType::PRINT_JOB_EVENT: { OnNotifyPrintJobEvent(*Details<JobEventDetails>(details).ptr()); break; } default: { break; } } } void PrintJob::GetSettingsDone(const PrintSettings& new_settings, PrintingContext::Result result) { NOTREACHED(); } PrintJobWorker* PrintJob::DetachWorker(PrintJobWorkerOwner* new_owner) { NOTREACHED(); return NULL; } MessageLoop* PrintJob::message_loop() { return ui_message_loop_; } const PrintSettings& PrintJob::settings() const { return settings_; } int PrintJob::cookie() const { if (!document_.get()) // Always use an invalid cookie in this case. return 0; return document_->cookie(); } void PrintJob::WillDestroyCurrentMessageLoop() { NOTREACHED(); } void PrintJob::StartPrinting() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); DCHECK(worker_->message_loop()); DCHECK(!is_job_pending_); DCHECK(!is_print_dialog_box_shown_); if (!worker_->message_loop() || is_job_pending_) return; // Real work is done in PrintJobWorker::StartPrinting(). worker_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::StartPrinting, document_)); // Set the flag right now. is_job_pending_ = true; // Tell everyone! scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::NEW_DOC, document_.get(), NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); } void PrintJob::Stop() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); // Be sure to live long enough. scoped_refptr<PrintJob> handle(this); MessageLoop* worker_loop = worker_->message_loop(); if (worker_loop) { if (is_print_dialog_box_shown_) { // Make sure there is no Print... dialog box. worker_loop->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::DismissDialog)); is_print_dialog_box_shown_ = false; } ControlledWorkerShutdown(); is_job_pending_ = false; registrar_.Remove(this, NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this)); } // Flush the cached document. UpdatePrintedDocument(NULL); } void PrintJob::Cancel() { if (is_canceling_) return; is_canceling_ = true; // Be sure to live long enough. scoped_refptr<PrintJob> handle(this); DCHECK_EQ(ui_message_loop_, MessageLoop::current()); MessageLoop* worker_loop = worker_.get() ? worker_->message_loop() : NULL; if (worker_loop) { // Call this right now so it renders the context invalid. Do not use // InvokeLater since it would take too much time. worker_->Cancel(); } // Make sure a Cancel() is broadcast. scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::FAILED, NULL, NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); Stop(); is_canceling_ = false; } bool PrintJob::FlushJob(int timeout_ms) { // Make sure the object outlive this message loop. scoped_refptr<PrintJob> handle(this); // Stop() will eventually be called, which will get out of the inner message // loop. But, don't take it for granted and set a timer in case something goes // wrong. base::OneShotTimer<MessageLoop> quit_task; if (timeout_ms) { quit_task.Start(TimeDelta::FromMilliseconds(timeout_ms), MessageLoop::current(), &MessageLoop::Quit); } bool old_state = MessageLoop::current()->NestableTasksAllowed(); MessageLoop::current()->SetNestableTasksAllowed(true); MessageLoop::current()->Run(); // Restore task state. MessageLoop::current()->SetNestableTasksAllowed(old_state); return true; } void PrintJob::DisconnectSource() { source_ = NULL; if (document_.get()) document_->DisconnectSource(); } bool PrintJob::is_job_pending() const { return is_job_pending_; } bool PrintJob::is_print_dialog_box_shown() const { return is_print_dialog_box_shown_; } PrintedDocument* PrintJob::document() const { return document_.get(); } void PrintJob::UpdatePrintedDocument(PrintedDocument* new_document) { if (document_.get() == new_document) return; document_ = new_document; if (document_.get()) { settings_ = document_->settings(); } if (worker_.get() && worker_->message_loop()) { DCHECK(!is_job_pending_); // Sync the document with the worker. worker_->message_loop()->PostTask(FROM_HERE, NewRunnableMethod( worker_.get(), &PrintJobWorker::OnDocumentChanged, document_)); } } void PrintJob::OnNotifyPrintJobEvent(const JobEventDetails& event_details) { switch (event_details.type()) { case JobEventDetails::FAILED: { settings_.Clear(); // Update internal state. is_print_dialog_box_shown_ = false; // No need to cancel since the worker already canceled itself. Stop(); break; } case JobEventDetails::USER_INIT_DONE: case JobEventDetails::DEFAULT_INIT_DONE: case JobEventDetails::USER_INIT_CANCELED: { DCHECK_EQ(event_details.document(), document_.get()); break; } case JobEventDetails::NEW_DOC: case JobEventDetails::NEW_PAGE: case JobEventDetails::PAGE_DONE: case JobEventDetails::JOB_DONE: case JobEventDetails::ALL_PAGES_REQUESTED: { // Don't care. break; } case JobEventDetails::DOC_DONE: { // This will call Stop() and broadcast a JOB_DONE message. MessageLoop::current()->PostTask(FROM_HERE, NewRunnableMethod( this, &PrintJob::OnDocumentDone)); break; } default: { NOTREACHED(); break; } } } void PrintJob::OnDocumentDone() { // Be sure to live long enough. The instance could be destroyed by the // JOB_DONE broadcast. scoped_refptr<PrintJob> handle(this); // Stop the worker thread. Stop(); scoped_refptr<JobEventDetails> details( new JobEventDetails(JobEventDetails::JOB_DONE, document_.get(), NULL)); NotificationService::current()->Notify( NotificationType::PRINT_JOB_EVENT, Source<PrintJob>(this), Details<JobEventDetails>(details.get())); } void PrintJob::ControlledWorkerShutdown() { DCHECK_EQ(ui_message_loop_, MessageLoop::current()); // The deadlock this code works around is specific to window messaging on // Windows, so we aren't likely to need it on any other platforms. #if defined(OS_WIN) // We could easily get into a deadlock case if worker_->Stop() is used; the // printer driver created a window as a child of the browser window. By // canceling the job, the printer driver initiated dialog box is destroyed, // which sends a blocking message to its parent window. If the browser window // thread is not processing messages, a deadlock occurs. // // This function ensures that the dialog box will be destroyed in a timely // manner by the mere fact that the thread will terminate. So the potential // deadlock is eliminated. worker_->StopSoon(); // Run a tight message loop until the worker terminates. It may seems like a // hack but I see no other way to get it to work flawlessly. The issues here // are: // - We don't want to run tasks while the thread is quitting. // - We want this code path to wait on the thread to quit before continuing. MSG msg; HANDLE thread_handle = worker_->thread_handle(); for (; thread_handle;) { // Note that we don't do any kind of message priorization since we don't // execute any pending task or timer. DWORD result = MsgWaitForMultipleObjects(1, &thread_handle, FALSE, INFINITE, QS_ALLINPUT); if (result == WAIT_OBJECT_0 + 1) { while (PeekMessage(&msg, NULL, 0, 0, TRUE) > 0) { TranslateMessage(&msg); DispatchMessage(&msg); } // Continue looping. } else if (result == WAIT_OBJECT_0) { // The thread quit. break; } else { // An error occured. Assume the thread quit. NOTREACHED(); break; } } #endif // Temporarily allow it until we fix // http://code.google.com/p/chromium/issues/detail?id=67044 base::ThreadRestrictions::ScopedAllowIO allow_io; // Now make sure the thread object is cleaned up. worker_->Stop(); } // Takes settings_ ownership and will be deleted in the receiving thread. JobEventDetails::JobEventDetails(Type type, PrintedDocument* document, PrintedPage* page) : document_(document), page_(page), type_(type) { } JobEventDetails::~JobEventDetails() { } PrintedDocument* JobEventDetails::document() const { return document_; } PrintedPage* JobEventDetails::page() const { return page_; } } // namespace printing <|endoftext|>
<commit_before>// Copyright (c) 2010 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/common/process_watcher.h" #include "base/env_var.h" #include "base/message_loop.h" #include "base/object_watcher.h" #include "chrome/common/env_vars.h" #include "chrome/common/result_codes.h" // Maximum amount of time (in milliseconds) to wait for the process to exit. static const int kWaitInterval = 2000; namespace { class TimerExpiredTask : public Task, public base::ObjectWatcher::Delegate { public: explicit TimerExpiredTask(base::ProcessHandle process) : process_(process) { watcher_.StartWatching(process_, this); } virtual ~TimerExpiredTask() { if (process_) { KillProcess(); DCHECK(!process_) << "Make sure to close the handle."; } } // Task --------------------------------------------------------------------- virtual void Run() { if (process_) KillProcess(); } // MessageLoop::Watcher ----------------------------------------------------- virtual void OnObjectSignaled(HANDLE object) { // When we're called from KillProcess, the ObjectWatcher may still be // watching. the process handle, so make sure it has stopped. watcher_.StopWatching(); CloseHandle(process_); process_ = NULL; } private: void KillProcess() { scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); if (env->HasEnv(env_vars::kHeadless)) { // If running the distributed tests, give the renderer a little time // to figure out that the channel is shutdown and unwind. if (WaitForSingleObject(process_, kWaitInterval) == WAIT_OBJECT_0) { OnObjectSignaled(process_); return; } } // OK, time to get frisky. We don't actually care when the process // terminates. We just care that it eventually terminates, and that's what // TerminateProcess should do for us. Don't check for the result code since // it fails quite often. This should be investigated eventually. base::KillProcess(process_, ResultCodes::HUNG, false); // Now, just cleanup as if the process exited normally. OnObjectSignaled(process_); } // The process that we are watching. base::ProcessHandle process_; base::ObjectWatcher watcher_; DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask); }; } // namespace // static void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process) { DCHECK(process != GetCurrentProcess()); // If already signaled, then we are done! if (WaitForSingleObject(process, 0) == WAIT_OBJECT_0) { CloseHandle(process); return; } MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimerExpiredTask(process), kWaitInterval); } <commit_msg>Windows build fix<commit_after>// Copyright (c) 2010 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/common/process_watcher.h" #include "base/scoped_ptr.h" #include "base/env_var.h" #include "base/message_loop.h" #include "base/object_watcher.h" #include "chrome/common/env_vars.h" #include "chrome/common/result_codes.h" // Maximum amount of time (in milliseconds) to wait for the process to exit. static const int kWaitInterval = 2000; namespace { class TimerExpiredTask : public Task, public base::ObjectWatcher::Delegate { public: explicit TimerExpiredTask(base::ProcessHandle process) : process_(process) { watcher_.StartWatching(process_, this); } virtual ~TimerExpiredTask() { if (process_) { KillProcess(); DCHECK(!process_) << "Make sure to close the handle."; } } // Task --------------------------------------------------------------------- virtual void Run() { if (process_) KillProcess(); } // MessageLoop::Watcher ----------------------------------------------------- virtual void OnObjectSignaled(HANDLE object) { // When we're called from KillProcess, the ObjectWatcher may still be // watching. the process handle, so make sure it has stopped. watcher_.StopWatching(); CloseHandle(process_); process_ = NULL; } private: void KillProcess() { scoped_ptr<base::EnvVarGetter> env(base::EnvVarGetter::Create()); if (env->HasEnv(env_vars::kHeadless)) { // If running the distributed tests, give the renderer a little time // to figure out that the channel is shutdown and unwind. if (WaitForSingleObject(process_, kWaitInterval) == WAIT_OBJECT_0) { OnObjectSignaled(process_); return; } } // OK, time to get frisky. We don't actually care when the process // terminates. We just care that it eventually terminates, and that's what // TerminateProcess should do for us. Don't check for the result code since // it fails quite often. This should be investigated eventually. base::KillProcess(process_, ResultCodes::HUNG, false); // Now, just cleanup as if the process exited normally. OnObjectSignaled(process_); } // The process that we are watching. base::ProcessHandle process_; base::ObjectWatcher watcher_; DISALLOW_COPY_AND_ASSIGN(TimerExpiredTask); }; } // namespace // static void ProcessWatcher::EnsureProcessTerminated(base::ProcessHandle process) { DCHECK(process != GetCurrentProcess()); // If already signaled, then we are done! if (WaitForSingleObject(process, 0) == WAIT_OBJECT_0) { CloseHandle(process); return; } MessageLoop::current()->PostDelayedTask(FROM_HERE, new TimerExpiredTask(process), kWaitInterval); } <|endoftext|>
<commit_before>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkOnce.h" #include "SkOpts.h" #include "SkXfermode_opts.h" #if defined(SK_CPU_X86) #if defined(SK_BUILD_FOR_WIN32) #include <intrin.h> static void cpuid(uint32_t abcd[4]) { __cpuid((int*)abcd, 1); } #else #include <cpuid.h> static void cpuid(uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); } #endif #elif !defined(SK_ARM_HAS_NEON) && defined(SK_CPU_ARM32) && defined(SK_BUILD_FOR_ANDROID) #include <cpu-features.h> #endif namespace portable { // This helps identify methods from this file when debugging / profiling. static float rsqrt(float x) { // Get initial estimate. int i = *SkTCast<int*>(&x); i = 0x5F1FFFF9 - (i>>1); float estimate = *SkTCast<float*>(&i); // One step of Newton's method to refine. const float estimate_sq = estimate*estimate; estimate *= 0.703952253f*(2.38924456f-x*estimate_sq); return estimate; } template <typename T> static void memsetT(T dst[], T val, int n) { while (n --> 0) { *dst++ = val; } } } // namespace portable namespace SkOpts { // Define default function pointer values here... decltype(rsqrt) rsqrt = portable::rsqrt; decltype(memset16) memset16 = portable::memsetT<uint16_t>; decltype(memset32) memset32 = portable::memsetT<uint32_t>; decltype(create_xfermode) create_xfermode = SkCreate4pxXfermode; // Each Init_foo() is defined in src/opts/SkOpts_foo.cpp. void Init_sse2(); void Init_ssse3(); void Init_sse41(); void Init_neon(); //TODO: _dsp2, _armv7, _armv8, _x86, _x86_64, _sse42, _avx, avx2, ... ? static void init() { #if defined(SK_CPU_X86) uint32_t abcd[] = {0,0,0,0}; cpuid(abcd); if (abcd[3] & (1<<26)) { Init_sse2(); } if (abcd[2] & (1<< 9)) { Init_ssse3(); } if (abcd[2] & (1<<19)) { Init_sse41(); } #elif defined(SK_ARM_HAS_NEON) Init_neon(); #elif defined(SK_CPU_ARM32) && defined(SK_BUILD_FOR_ANDROID) if (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) { Init_neon(); } #endif } SK_DECLARE_STATIC_ONCE(gInitOnce); void Init() { SkOnce(&gInitOnce, init); } #if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS static struct AutoInit { AutoInit() { Init(); } } gAutoInit; #endif } <commit_msg>disable SkOpts on x86 iOS (simulator)<commit_after>/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkOnce.h" #include "SkOpts.h" #include "SkXfermode_opts.h" #if defined(SK_CPU_X86) #if defined(SK_BUILD_FOR_WIN32) #include <intrin.h> static void cpuid(uint32_t abcd[4]) { __cpuid((int*)abcd, 1); } #else #include <cpuid.h> static void cpuid(uint32_t abcd[4]) { __get_cpuid(1, abcd+0, abcd+1, abcd+2, abcd+3); } #endif #elif !defined(SK_ARM_HAS_NEON) && defined(SK_CPU_ARM32) && defined(SK_BUILD_FOR_ANDROID) #include <cpu-features.h> #endif namespace portable { // This helps identify methods from this file when debugging / profiling. static float rsqrt(float x) { // Get initial estimate. int i = *SkTCast<int*>(&x); i = 0x5F1FFFF9 - (i>>1); float estimate = *SkTCast<float*>(&i); // One step of Newton's method to refine. const float estimate_sq = estimate*estimate; estimate *= 0.703952253f*(2.38924456f-x*estimate_sq); return estimate; } template <typename T> static void memsetT(T dst[], T val, int n) { while (n --> 0) { *dst++ = val; } } } // namespace portable namespace SkOpts { // Define default function pointer values here... decltype(rsqrt) rsqrt = portable::rsqrt; decltype(memset16) memset16 = portable::memsetT<uint16_t>; decltype(memset32) memset32 = portable::memsetT<uint32_t>; decltype(create_xfermode) create_xfermode = SkCreate4pxXfermode; // Each Init_foo() is defined in src/opts/SkOpts_foo.cpp. void Init_sse2(); void Init_ssse3(); void Init_sse41(); void Init_neon(); //TODO: _dsp2, _armv7, _armv8, _x86, _x86_64, _sse42, _avx, avx2, ... ? static void init() { // TODO: Chrome's not linking _sse* opts on iOS simulator builds. Bug or feature? #if defined(SK_CPU_X86) && !defined(SK_BUILD_FOR_IOS) uint32_t abcd[] = {0,0,0,0}; cpuid(abcd); if (abcd[3] & (1<<26)) { Init_sse2(); } if (abcd[2] & (1<< 9)) { Init_ssse3(); } if (abcd[2] & (1<<19)) { Init_sse41(); } #elif defined(SK_ARM_HAS_NEON) Init_neon(); #elif defined(SK_CPU_ARM32) && defined(SK_BUILD_FOR_ANDROID) if (android_getCpuFeatures() & ANDROID_CPU_ARM_FEATURE_NEON) { Init_neon(); } #endif } SK_DECLARE_STATIC_ONCE(gInitOnce); void Init() { SkOnce(&gInitOnce, init); } #if SK_ALLOW_STATIC_GLOBAL_INITIALIZERS static struct AutoInit { AutoInit() { Init(); } } gAutoInit; #endif } <|endoftext|>
<commit_before>#include "stdafx.h" #include "CoreContext.h" #include "Autowired.h" #include "CoreThread.h" #include "GlobalCoreContext.h" #include "OutstandingCountTracker.h" #include "ThreadStatusMaintainer.h" #include <boost/thread.hpp> #include <algorithm> #include <memory> using namespace boost; thread_specific_ptr<std::shared_ptr<CoreContext> > CoreContext::s_curContext; CoreContext::CoreContext(std::shared_ptr<CoreContext> pParent): Autowirer(std::static_pointer_cast<Autowirer, CoreContext>(pParent)), m_shouldStop(true), m_refCount(0) { ASSERT(pParent.get() != this); } CoreContext::~CoreContext(void) { // The s_curContext pointer holds a shared_ptr to this--if we're in a ctor, and our caller // still holds a reference to us, then we have a serious problem. ASSERT( !s_curContext.get() || !s_curContext.get()->use_count() || s_curContext.get()->get() != this ); } std::shared_ptr<OutstandingCountTracker> CoreContext::IncrementOutstandingThreadCount(void) { std::shared_ptr<OutstandingCountTracker> retVal = m_outstanding.lock(); if(!m_outstanding.expired()) return retVal; boost::lock_guard<boost::mutex> lk(m_outstandingLock); retVal.reset( new OutstandingCountTracker( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ) ); m_outstanding = retVal; return retVal; } std::shared_ptr<CoreContext> CoreContext::Create(void) { // Create the context, first CoreContext* pContext = new CoreContext( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ); // Create the shared pointer for the context--do not add the context to itself, // this creates a dangerous cyclic reference. std::shared_ptr<CoreContext> retVal(pContext); pContext->m_self = retVal; return retVal; } void CoreContext::InitiateCoreThreads(void) { // Self-reference to ensure the context is not destroyed until all threads are gone std::shared_ptr<CoreContext> self = std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()); // Because the caller was able to invoke a method on this CoreContext, it must have // a shared_ptr to it. Thus, we can assert that the above lock operation succeeded. ASSERT(self); { lock_guard<mutex> lk(m_coreLock); if(m_refCount++) // Already running return; } if(m_pParent) // Start parent threads first // Parent MUST be a core context std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->InitiateCoreThreads(); // Set our stop flag before kicking off any threads: m_shouldStop = false; // Hold another lock to prevent m_threads from being modified while we sit on it lock_guard<mutex> lk(m_coreLock); for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); q++) (*q)->Start(); } void CoreContext::SignalShutdown(void) { { lock_guard<mutex> lk(m_coreLock); if(--m_refCount) // Someone else still depends on this return; // Global context is now "stop": m_shouldStop = true; m_stopping.notify_all(); // Also pass notice to all children: for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); q++) (*q)->Stop(); } if(m_pParent) // Signal parent that it's time to shut down std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->SignalShutdown(); } std::shared_ptr<CoreContext> CoreContext::CurrentContext(void) { if(!s_curContext.get()) return std::static_pointer_cast<CoreContext, GlobalCoreContext>(GetGlobalContext()); std::shared_ptr<CoreContext>* retVal = s_curContext.get(); ASSERT(retVal); ASSERT(*retVal); return *retVal; } void CoreContext::AddCoreThread(CoreThread* ptr, bool allowNotReady) { // We don't allow the insertion of a thread that isn't ready unless the user really // wants that behavior. ASSERT(allowNotReady || ptr->IsReady()); // Insert into the linked list of threads first: lock_guard<mutex> lk(m_coreLock); m_threads.push_front(ptr); if(!m_shouldStop) // We're already running, this means we're late to the game and need to start _now_. ptr->Start(); } std::shared_ptr<CoreContext> GetCurrentContext() { return CoreContext::CurrentContext(); } <commit_msg>Fixed another bug. Signalling shutdown on a child context should NOT terminate its parent.<commit_after>#include "stdafx.h" #include "CoreContext.h" #include "Autowired.h" #include "CoreThread.h" #include "GlobalCoreContext.h" #include "OutstandingCountTracker.h" #include "ThreadStatusMaintainer.h" #include <boost/thread.hpp> #include <algorithm> #include <memory> using namespace boost; thread_specific_ptr<std::shared_ptr<CoreContext> > CoreContext::s_curContext; CoreContext::CoreContext(std::shared_ptr<CoreContext> pParent): Autowirer(std::static_pointer_cast<Autowirer, CoreContext>(pParent)), m_shouldStop(true), m_refCount(0) { ASSERT(pParent.get() != this); } CoreContext::~CoreContext(void) { // The s_curContext pointer holds a shared_ptr to this--if we're in a ctor, and our caller // still holds a reference to us, then we have a serious problem. ASSERT( !s_curContext.get() || !s_curContext.get()->use_count() || s_curContext.get()->get() != this ); } std::shared_ptr<OutstandingCountTracker> CoreContext::IncrementOutstandingThreadCount(void) { std::shared_ptr<OutstandingCountTracker> retVal = m_outstanding.lock(); if(!m_outstanding.expired()) return retVal; boost::lock_guard<boost::mutex> lk(m_outstandingLock); retVal.reset( new OutstandingCountTracker( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ) ); m_outstanding = retVal; return retVal; } std::shared_ptr<CoreContext> CoreContext::Create(void) { // Create the context, first CoreContext* pContext = new CoreContext( std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()) ); // Create the shared pointer for the context--do not add the context to itself, // this creates a dangerous cyclic reference. std::shared_ptr<CoreContext> retVal(pContext); pContext->m_self = retVal; return retVal; } void CoreContext::InitiateCoreThreads(void) { // Self-reference to ensure the context is not destroyed until all threads are gone std::shared_ptr<CoreContext> self = std::static_pointer_cast<CoreContext, Autowirer>(m_self.lock()); // Because the caller was able to invoke a method on this CoreContext, it must have // a shared_ptr to it. Thus, we can assert that the above lock operation succeeded. ASSERT(self); { lock_guard<mutex> lk(m_coreLock); if(m_refCount++) // Already running return; } if(m_pParent) // Start parent threads first // Parent MUST be a core context std::static_pointer_cast<CoreContext, Autowirer>(m_pParent)->InitiateCoreThreads(); // Set our stop flag before kicking off any threads: m_shouldStop = false; // Hold another lock to prevent m_threads from being modified while we sit on it lock_guard<mutex> lk(m_coreLock); for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); q++) (*q)->Start(); } void CoreContext::SignalShutdown(void) { lock_guard<mutex> lk(m_coreLock); if(--m_refCount) // Someone else still depends on this return; // Global context is now "stop": m_shouldStop = true; m_stopping.notify_all(); // Also pass notice to all children: for(t_threadList::iterator q = m_threads.begin(); q != m_threads.end(); q++) (*q)->Stop(); } std::shared_ptr<CoreContext> CoreContext::CurrentContext(void) { if(!s_curContext.get()) return std::static_pointer_cast<CoreContext, GlobalCoreContext>(GetGlobalContext()); std::shared_ptr<CoreContext>* retVal = s_curContext.get(); ASSERT(retVal); ASSERT(*retVal); return *retVal; } void CoreContext::AddCoreThread(CoreThread* ptr, bool allowNotReady) { // We don't allow the insertion of a thread that isn't ready unless the user really // wants that behavior. ASSERT(allowNotReady || ptr->IsReady()); // Insert into the linked list of threads first: lock_guard<mutex> lk(m_coreLock); m_threads.push_front(ptr); if(!m_shouldStop) // We're already running, this means we're late to the game and need to start _now_. ptr->Start(); } std::shared_ptr<CoreContext> GetCurrentContext() { return CoreContext::CurrentContext(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "BindingHandler.h" namespace CefSharp { CefRefPtr<CefV8Value> BindingHandler::ConvertToCef(Type^ type, Object^ obj) { if(type == Void::typeid) { return CefV8Value::CreateUndefined(); } if(obj == nullptr) { return CefV8Value::CreateNull(); } if (type == Boolean::typeid) { return CefV8Value::CreateBool(safe_cast<bool>(obj)); } if (type == Int16::typeid || type == Int32::typeid) { return CefV8Value::CreateInt(safe_cast<int>(obj)); } if (type == Single::typeid || type == Double::typeid) { return CefV8Value::CreateDouble(safe_cast<double>(obj)); } if (type == String::typeid) { CefString str = convertFromString(safe_cast<String^>(obj)); return CefV8Value::CreateString(str); } //TODO: What exception type? throw gcnew Exception("Cannot convert object from CLR to Cef " + type->ToString() + "."); } Object^ BindingHandler::ConvertFromCef(CefRefPtr<CefV8Value> obj) { if (obj->IsNull() || obj->IsUndefined()) { return nullptr; } if (obj->IsBool()) return gcnew System::Boolean(obj->GetBoolValue()); if (obj->IsInt()) return gcnew System::Int32(obj->GetIntValue()); if (obj->IsDouble()) return gcnew System::Double(obj->GetDoubleValue()); if (obj->IsString()){ return convertToString(obj->GetStringValue()); } //TODO: What exception type? throw gcnew Exception("Cannot convert object from Cef to CLR."); } bool BindingHandler::Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) { CefRefPtr<BindingData> bindingData = reinterpret_cast<BindingData*>(object->GetUserData().get()); Object^ self = bindingData->Get(); if(self == nullptr) { exception = "Binding's CLR object is null."; return true; } String^ memberName = convertToString(name); Type^ type = self->GetType(); array<System::Reflection::MemberInfo^>^ members = type->GetMember(memberName, MemberTypes::Method, /* BindingFlags::IgnoreCase |*/ BindingFlags::Instance | BindingFlags::Public); if(members->Length == 0) { exception = convertFromString("No member named " + memberName + "."); return true; } array<System::Object^>^ suppliedArguments = gcnew array<Object^>(arguments.size()); try { for(int i = 0; i < suppliedArguments->Length; i++) { suppliedArguments[i] = ConvertFromCef(arguments[i]); } } catch(System::Exception^ err) { exception = convertFromString(err->Message); return true; } MethodInfo^ bestMethod; array<Object^>^ bestMethodArguments; int bestMethodMatchedArgs = -1; for (int i = 0; i < members->Length; i++) { MethodInfo^ method = (MethodInfo^) members[i]; array<ParameterInfo^>^ parametersInfo = method->GetParameters(); array<Object^>^ arguments; if (suppliedArguments->Length == parametersInfo->Length) { int match = 0; int failed = 0; arguments = gcnew array<Object^>(suppliedArguments->Length); for (int p = 0; p < suppliedArguments->Length; p++) { System::Type^ paramType = parametersInfo[p]->ParameterType; if (suppliedArguments[p] != nullptr) { System::Type^ suppliedType = suppliedArguments[p]->GetType(); if (suppliedType == paramType) { arguments[p] = suppliedArguments[p]; match++; } else { // TODO //arguments[p] = ConvertToType(suppliedArguments[p], paramType); //if (arguments[p] == nullptr) //{ failed++; break; //} } } } if (failed > 0) { continue; } if (match > bestMethodMatchedArgs) { bestMethod = method; bestMethodArguments = arguments; bestMethodMatchedArgs = match; } if (match == arguments->Length) break; } } if (bestMethod != nullptr) { try { Object^ result = bestMethod->Invoke(self, bestMethodArguments); retval = ConvertToCef(bestMethod->ReturnType, result); return true; } catch(System::Reflection::TargetInvocationException^ err) { exception = convertFromString(err->InnerException->Message); } catch(System::Exception^ err) { exception = convertFromString(err->Message); } } else { exception = convertFromString("Argument mismatch for method \"" + memberName + "\"."); } return true; } void BindingHandler::Bind(String^ name, Object^ obj, CefRefPtr<CefV8Value> window) { CefRefPtr<BindingData> bindingData = new BindingData(obj); CefRefPtr<CefBase> userData = static_cast<CefRefPtr<CefBase>>(bindingData); CefRefPtr<CefV8Value> wrappedObject = window->CreateObject(userData); CefRefPtr<CefV8Handler> handler = static_cast<CefV8Handler*>(new BindingHandler()); array<MethodInfo^>^ methods = obj->GetType()->GetMethods(BindingFlags::Instance | BindingFlags::Public); IList<String^>^ methodNames = gcnew List<String^>(); for each(MethodInfo^ method in methods) { if(!methodNames->Contains(method->Name)) { methodNames->Add(method->Name); } } for each(String^ methodName in methodNames) { CefString nameStr = convertFromString(methodName); wrappedObject->SetValue(nameStr, CefV8Value::CreateFunction(nameStr, handler)); } window->SetValue(convertFromString(name), wrappedObject); } }<commit_msg>Added some type handling in CLR object binding.<commit_after>#include "stdafx.h" #include "BindingHandler.h" namespace CefSharp { CefRefPtr<CefV8Value> BindingHandler::ConvertToCef(Type^ type, Object^ obj) { if(type == Void::typeid) { return CefV8Value::CreateUndefined(); } if(obj == nullptr) { return CefV8Value::CreateNull(); } Type^ underlyingType = Nullable::GetUnderlyingType(type); if(underlyingType!=nullptr)type = underlyingType; if (type == Boolean::typeid) { return CefV8Value::CreateBool(safe_cast<bool>(obj)); } if (type == Int32::typeid) { return CefV8Value::CreateInt(safe_cast<int>(obj)); } if (type == String::typeid) { CefString str = convertFromString(safe_cast<String^>(obj)); return CefV8Value::CreateString(str); } if (type == Double::typeid) { return CefV8Value::CreateDouble(safe_cast<double>(obj)); } if (type == Decimal::typeid) { return CefV8Value::CreateDouble( Convert::ToDouble(obj) ); } if (type == SByte::typeid) { return CefV8Value::CreateInt( Convert::ToInt32(obj) ); } if (type == Int16::typeid) { return CefV8Value::CreateInt( Convert::ToInt32(obj) ); } if (type == Int64::typeid) { return CefV8Value::CreateDouble( Convert::ToDouble(obj) ); } if (type == Byte::typeid) { return CefV8Value::CreateInt( Convert::ToInt32(obj) ); } if (type == UInt16::typeid) { return CefV8Value::CreateInt( Convert::ToInt32(obj) ); } if (type == UInt32::typeid) { return CefV8Value::CreateDouble( Convert::ToDouble(obj) ); } if (type == UInt64::typeid) { return CefV8Value::CreateDouble( Convert::ToDouble(obj) ); } if (type == Single::typeid) { return CefV8Value::CreateDouble( Convert::ToDouble(obj) ); } if (type == Char::typeid) { return CefV8Value::CreateInt( Convert::ToInt32(obj) ); } //TODO: What exception type? throw gcnew Exception("Cannot convert object from CLR to Cef " + type->ToString() + "."); } Object^ BindingHandler::ConvertFromCef(CefRefPtr<CefV8Value> obj) { if (obj->IsNull() || obj->IsUndefined()) { return nullptr; } if (obj->IsBool()) return gcnew System::Boolean(obj->GetBoolValue()); if (obj->IsInt()) return gcnew System::Int32(obj->GetIntValue()); if (obj->IsDouble()) return gcnew System::Double(obj->GetDoubleValue()); if (obj->IsString()){ return convertToString(obj->GetStringValue()); } //TODO: What exception type? throw gcnew Exception("Cannot convert object from Cef to CLR."); } bool BindingHandler::Execute(const CefString& name, CefRefPtr<CefV8Value> object, const CefV8ValueList& arguments, CefRefPtr<CefV8Value>& retval, CefString& exception) { CefRefPtr<BindingData> bindingData = reinterpret_cast<BindingData*>(object->GetUserData().get()); Object^ self = bindingData->Get(); if(self == nullptr) { exception = "Binding's CLR object is null."; return true; } String^ memberName = convertToString(name); Type^ type = self->GetType(); array<System::Reflection::MemberInfo^>^ members = type->GetMember(memberName, MemberTypes::Method, /* BindingFlags::IgnoreCase |*/ BindingFlags::Instance | BindingFlags::Public); if(members->Length == 0) { exception = convertFromString("No member named " + memberName + "."); return true; } //TODO: cache for type info here array<System::Object^>^ suppliedArguments = gcnew array<Object^>(arguments.size()); try { for(int i = 0; i < suppliedArguments->Length; i++) { suppliedArguments[i] = ConvertFromCef(arguments[i]); } } catch(System::Exception^ err) { exception = convertFromString(err->Message); return true; } // choose best method MethodInfo^ bestMethod; array<Object^>^ bestMethodArguments; int bestMethodMatchedArgs = -1; for (int i = 0; i < members->Length; i++) { MethodInfo^ method = (MethodInfo^) members[i]; array<ParameterInfo^>^ parametersInfo = method->GetParameters(); array<Object^>^ arguments; if (suppliedArguments->Length == parametersInfo->Length) { int match = 0; int failed = 0; arguments = gcnew array<Object^>(suppliedArguments->Length); for (int p = 0; p < suppliedArguments->Length; p++) { System::Type^ paramType = parametersInfo[p]->ParameterType; if (suppliedArguments[p] != nullptr) { System::Type^ suppliedType = suppliedArguments[p]->GetType(); if (paramType == suppliedType) { arguments[p] = suppliedArguments[p]; match++; } else { try { Type^ underlyingParamType = Nullable::GetUnderlyingType(paramType); arguments[p] = Convert::ChangeType(suppliedArguments[p], underlyingParamType!=nullptr?underlyingParamType : paramType); } catch (System::Exception^) { failed++; break; } match++; // TODO //arguments[p] = ConvertToType(suppliedArguments[p], paramType); //if (arguments[p] == nullptr) //{ // failed++; // break; //} } } else if(paramType->IsValueType == false || Nullable::GetUnderlyingType(paramType) != nullptr) { arguments[p] = suppliedArguments[p]; match++; } else { failed++; break; } } if (failed > 0) { continue; } if (match > bestMethodMatchedArgs) { bestMethod = method; bestMethodArguments = arguments; bestMethodMatchedArgs = match; } if (match == arguments->Length) break; } } if (bestMethod != nullptr) { try { Object^ result = bestMethod->Invoke(self, bestMethodArguments); retval = ConvertToCef(bestMethod->ReturnType, result); return true; } catch(System::Reflection::TargetInvocationException^ err) { exception = convertFromString(err->InnerException->Message); } catch(System::Exception^ err) { exception = convertFromString(err->Message); } } else { exception = convertFromString("Argument mismatch for method \"" + memberName + "\"."); } return true; } void BindingHandler::Bind(String^ name, Object^ obj, CefRefPtr<CefV8Value> window) { CefRefPtr<BindingData> bindingData = new BindingData(obj); CefRefPtr<CefBase> userData = static_cast<CefRefPtr<CefBase>>(bindingData); CefRefPtr<CefV8Value> wrappedObject = window->CreateObject(userData); CefRefPtr<CefV8Handler> handler = static_cast<CefV8Handler*>(new BindingHandler()); array<MethodInfo^>^ methods = obj->GetType()->GetMethods(BindingFlags::Instance | BindingFlags::Public); IList<String^>^ methodNames = gcnew List<String^>(); for each(MethodInfo^ method in methods) { if(!methodNames->Contains(method->Name)) { methodNames->Add(method->Name); } } for each(String^ methodName in methodNames) { CefString nameStr = convertFromString(methodName); wrappedObject->SetValue(nameStr, CefV8Value::CreateFunction(nameStr, handler)); } window->SetValue(convertFromString(name), wrappedObject); } }<|endoftext|>
<commit_before>#ifndef ALPHA_SCREENGLWIDGET_HEADER #define ALPHA_SCREENGLWIDGET_HEADER #include <QGLWidget> #include "../Box2.hpp" #include "Screen.hpp" namespace nt { namespace gl { /** * A Qt-specific wrapper of a Screen. * * ScreenGLWidget takes care of the Qt-specific setup and behavior * necessary to render an OpenGL scene. As such, it is a relatively * light class. Most of the heavyweight behavior is contained within * the screen and the render layers themselves. * * @see Screen * @see RenderLayer */ class ScreenGLWidget : public QGLWidget { Q_OBJECT const Screen* _screen; Box2<int> _screenArea; protected: void paintGL(); void initializeGL(); void resizeGL(int width, int height); public: ScreenGLWidget(QWidget* const parent = 0) : QGLWidget(parent), _screen(nullptr) { } void setScreen(const Screen* const screen); const Screen* getScreen() const; }; } // namespace gl } // namespace nt #endif // ALPHA_SCREENGLWIDGET_HEADER <commit_msg>Allow QGLFormat to be passed to ScreenGLWidget<commit_after>#ifndef ALPHA_SCREENGLWIDGET_HEADER #define ALPHA_SCREENGLWIDGET_HEADER #include <QGLWidget> #include "../Box2.hpp" #include "Screen.hpp" namespace nt { namespace gl { /** * A Qt-specific wrapper of a Screen. * * ScreenGLWidget takes care of the Qt-specific setup and behavior * necessary to render an OpenGL scene. As such, it is a relatively * light class. Most of the heavyweight behavior is contained within * the screen and the render layers themselves. * * @see Screen * @see RenderLayer */ class ScreenGLWidget : public QGLWidget { Q_OBJECT const Screen* _screen; Box2<int> _screenArea; protected: void paintGL(); void initializeGL(); void resizeGL(int width, int height); public: ScreenGLWidget(const QGLFormat& format, QWidget* const parent = 0) : QGLWidget(format, parent), _screen(nullptr) { } ScreenGLWidget(QWidget* const parent = 0) : QGLWidget(parent), _screen(nullptr) { } void setScreen(const Screen* const screen); const Screen* getScreen() const; }; } // namespace gl } // namespace nt #endif // ALPHA_SCREENGLWIDGET_HEADER <|endoftext|>
<commit_before>// Copyright 2013-2015 Stanford University // // 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 <array> #include "src/cost/latency.h" #include "src/ext/x64asm/include/x64asm.h" using namespace std; namespace { array<stoke::Cost, X64ASM_NUM_OPCODES> latencies_ {{ #include "src/cost/tables/haswell_latency.h" } }; } // namespace namespace stoke { LatencyCost::result_type LatencyCost::operator()(const Cfg& cfg, Cost max) { Cost latency = 0; const auto& code = cfg.get_code(); for (auto b = ++cfg.reachable_begin(), be = cfg.reachable_end(); b != be; ++b) { if (cfg.is_exit(*b)) { continue; } Cost block_latency = 0; const auto first = cfg.get_index(Cfg::loc_type(*b, 0)); for (size_t i = first, ie = first + cfg.num_instrs(*b); i < ie; ++i) { // Record latency for non nop instructions if (!code[i].is_nop()) { block_latency += latencies_[code[i].get_opcode()]; } } // Increment latency by block latency scaled by nesting penalty // The call to pow() is expensive, so we hide it behind a faster check const auto nd = cfg.nesting_depth(*b); if (nd > 1) { latency += block_latency * pow(nesting_penalty_, cfg.nesting_depth(*b)); } else { latency += block_latency; } if(latency >= max) { return result_type(true, max); } } return result_type(true, latency); } } //namespace stoke <commit_msg>fixes nesting depth bug<commit_after>// Copyright 2013-2015 Stanford University // // 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 <array> #include "src/cost/latency.h" #include "src/ext/x64asm/include/x64asm.h" using namespace std; namespace { array<stoke::Cost, X64ASM_NUM_OPCODES> latencies_ {{ #include "src/cost/tables/haswell_latency.h" } }; } // namespace namespace stoke { LatencyCost::result_type LatencyCost::operator()(const Cfg& cfg, Cost max) { Cost latency = 0; const auto& code = cfg.get_code(); for (auto b = ++cfg.reachable_begin(), be = cfg.reachable_end(); b != be; ++b) { if (cfg.is_exit(*b)) { continue; } Cost block_latency = 0; const auto first = cfg.get_index(Cfg::loc_type(*b, 0)); for (size_t i = first, ie = first + cfg.num_instrs(*b); i < ie; ++i) { // Record latency for non nop instructions if (!code[i].is_nop()) { block_latency += latencies_[code[i].get_opcode()]; } } // Increment latency by block latency scaled by nesting penalty // The call to pow() is expensive, so we hide it behind a faster check const auto nd = cfg.nesting_depth(*b); if (nd >= 1) { latency += block_latency * pow(nesting_penalty_, cfg.nesting_depth(*b)); } else { latency += block_latency; } if(latency >= max) { return result_type(true, max); } } return result_type(true, latency); } } //namespace stoke <|endoftext|>
<commit_before>/* * Copyright (c) 2007-2008 The Florida State University * 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 copyright holders 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 * OWNER 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. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/intregs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint16_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = NUM_ARCH_INTREGS; // The number of single precision floating point registers const int NumFloatArchRegs = 64; const int NumFloatSpecialRegs = 8; const int NumIntRegs = NUM_INTREGS; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = INTREG_SP; const int ReturnAddressReg = INTREG_LR; const int PCReg = INTREG_PC; const int ZeroReg = INTREG_ZERO; const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs * (MODE_MAXMODE + 1); const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; enum FPControlRegNums { FIR = NumFloatArchRegs, FCCR, FEXR, FENR, FCSR }; enum FCSRBits { Inexact = 1, Underflow, Overflow, DivideByZero, Invalid, Unimplemented }; enum FCSRFields { Flag_Field = 1, Enable_Field = 6, Cause_Field = 11 }; } // namespace ArmISA #endif <commit_msg>ARM: Eliminate some unused enums.<commit_after>/* * Copyright (c) 2007-2008 The Florida State University * 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 copyright holders 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 * OWNER 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. * * Authors: Stephen Hines */ #ifndef __ARCH_ARM_REGISTERS_HH__ #define __ARCH_ARM_REGISTERS_HH__ #include "arch/arm/max_inst_regs.hh" #include "arch/arm/intregs.hh" #include "arch/arm/miscregs.hh" namespace ArmISA { using ArmISAInst::MaxInstSrcRegs; using ArmISAInst::MaxInstDestRegs; typedef uint16_t RegIndex; typedef uint64_t IntReg; // floating point register file entry type typedef uint32_t FloatRegBits; typedef float FloatReg; // cop-0/cop-1 system control register typedef uint64_t MiscReg; // Constants Related to the number of registers const int NumIntArchRegs = NUM_ARCH_INTREGS; // The number of single precision floating point registers const int NumFloatArchRegs = 64; const int NumFloatSpecialRegs = 8; const int NumIntRegs = NUM_INTREGS; const int NumFloatRegs = NumFloatArchRegs + NumFloatSpecialRegs; const int NumMiscRegs = NUM_MISCREGS; // semantically meaningful register indices const int ReturnValueReg = 0; const int ReturnValueReg1 = 1; const int ReturnValueReg2 = 2; const int ArgumentReg0 = 0; const int ArgumentReg1 = 1; const int ArgumentReg2 = 2; const int ArgumentReg3 = 3; const int FramePointerReg = 11; const int StackPointerReg = INTREG_SP; const int ReturnAddressReg = INTREG_LR; const int PCReg = INTREG_PC; const int ZeroReg = INTREG_ZERO; const int SyscallNumReg = ReturnValueReg; const int SyscallPseudoReturnReg = ReturnValueReg; const int SyscallSuccessReg = ReturnValueReg; // These help enumerate all the registers for dependence tracking. const int FP_Base_DepTag = NumIntRegs * (MODE_MAXMODE + 1); const int Ctrl_Base_DepTag = FP_Base_DepTag + NumFloatRegs; typedef union { IntReg intreg; FloatReg fpreg; MiscReg ctrlreg; } AnyReg; } // namespace ArmISA #endif <|endoftext|>
<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2010, 2011, 2012, 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef ABC_NUMERIC_HXX #define ABC_NUMERIC_HXX #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abc/core.hxx> #include <type_traits> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::numeric globals namespace abc { namespace numeric { /** Returns true if the argument is negative. It avoids annoying compiler warnings if the argument will never be negative (i.e. T is unsigned). TODO: comment signature. */ template <typename T> static /*constexpr*/ bool is_negative( typename std::enable_if<std::is_signed<T>::value, T>::type t ) { return t < T(0); } template <typename T> static /*constexpr*/ bool is_negative( typename std::enable_if<!std::is_signed<T>::value, T>::type t ) { UNUSED_ARG(t); return false; } } //namespace numeric } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::numeric::min and abc::numeric::max namespace abc { namespace numeric { /** Defines the minimum value for a numeric type. */ template <typename T> struct min; /** Defines the maximum value for a numeric type. */ template <typename T> struct max; // Specialization of min and max for UTF character types (note: wchar_t is not among these). template <> struct min< char> : public std::integral_constant< char, CHAR_MIN> {}; template <> struct max< char> : public std::integral_constant< char, CHAR_MAX> {}; #ifdef ABC_CXX_CHAR16 template <> struct min<char16_t> : public std::integral_constant<char16_t, 0> {}; template <> struct max<char16_t> : public std::integral_constant<char16_t, #ifdef UINT_LEAST16_MAX UINT_LEAST16_MAX #else 0xffff #endif > {}; #endif //ifdef ABC_CXX_CHAR16 #ifdef ABC_CXX_CHAR32 template <> struct min<char32_t> : public std::integral_constant<char32_t, 0> {}; template <> struct max<char32_t> : public std::integral_constant<char32_t, #ifdef UINT_LEAST32_MAX UINT_LEAST32_MAX #else 0xffffffff #endif > {}; #endif //ifdef ABC_CXX_CHAR32 // Specialization of min and max for integer types. template <> struct min< signed char> : public std::integral_constant< signed char, SCHAR_MIN> {}; template <> struct max< signed char> : public std::integral_constant< signed char, SCHAR_MAX> {}; template <> struct min<unsigned char> : public std::integral_constant<unsigned char, 0> {}; template <> struct max<unsigned char> : public std::integral_constant<unsigned char, UCHAR_MAX> {}; template <> struct min< short> : public std::integral_constant< short, SHRT_MIN> {}; template <> struct max< short> : public std::integral_constant< short, SHRT_MAX> {}; template <> struct min<unsigned short> : public std::integral_constant<unsigned short, 0> {}; template <> struct max<unsigned short> : public std::integral_constant<unsigned short, USHRT_MAX> {}; template <> struct min< int> : public std::integral_constant< int, INT_MIN> {}; template <> struct max< int> : public std::integral_constant< int, INT_MAX> {}; template <> struct min<unsigned > : public std::integral_constant<unsigned , 0> {}; template <> struct max<unsigned > : public std::integral_constant<unsigned , UINT_MAX> {}; template <> struct min< long> : public std::integral_constant< long, LONG_MIN> {}; template <> struct max< long> : public std::integral_constant< long, LONG_MAX> {}; template <> struct min<unsigned long> : public std::integral_constant<unsigned long, 0> {}; template <> struct max<unsigned long> : public std::integral_constant<unsigned long, ULONG_MAX> {}; template <> struct min< long long> : public std::integral_constant< long long, LLONG_MIN> {}; template <> struct max< long long> : public std::integral_constant< long long, LLONG_MAX> {}; template <> struct min<unsigned long long> : public std::integral_constant<unsigned long long, 0> {}; template <> struct max<unsigned long long> : public std::integral_constant<unsigned long long, ULLONG_MAX> {}; } //namespace numeric } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef ABC_NUMERIC_HXX <commit_msg>Change from static to inline<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3 -*- Copyright 2010, 2011, 2012, 2013 Raffaello D. Di Napoli This file is part of Application-Building Components (henceforth referred to as ABC). ABC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ABC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ABC. If not, see <http://www.gnu.org/licenses/>. --------------------------------------------------------------------------------------------------*/ #ifndef ABC_NUMERIC_HXX #define ABC_NUMERIC_HXX #ifdef ABC_CXX_PRAGMA_ONCE #pragma once #endif #include <abc/core.hxx> #include <type_traits> //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::numeric globals namespace abc { namespace numeric { /** Returns true if the argument is negative. It avoids annoying compiler warnings if the argument will never be negative (i.e. T is unsigned). TODO: comment signature. */ template <typename T> inline /*constexpr*/ bool is_negative( typename std::enable_if<std::is_signed<T>::value, T>::type t ) { return t < T(0); } template <typename T> inline /*constexpr*/ bool is_negative( typename std::enable_if<!std::is_signed<T>::value, T>::type t ) { UNUSED_ARG(t); return false; } } //namespace numeric } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// // abc::numeric::min and abc::numeric::max namespace abc { namespace numeric { /** Defines the minimum value for a numeric type. */ template <typename T> struct min; /** Defines the maximum value for a numeric type. */ template <typename T> struct max; // Specialization of min and max for UTF character types (note: wchar_t is not among these). template <> struct min< char> : public std::integral_constant< char, CHAR_MIN> {}; template <> struct max< char> : public std::integral_constant< char, CHAR_MAX> {}; #ifdef ABC_CXX_CHAR16 template <> struct min<char16_t> : public std::integral_constant<char16_t, 0> {}; template <> struct max<char16_t> : public std::integral_constant<char16_t, #ifdef UINT_LEAST16_MAX UINT_LEAST16_MAX #else 0xffff #endif > {}; #endif //ifdef ABC_CXX_CHAR16 #ifdef ABC_CXX_CHAR32 template <> struct min<char32_t> : public std::integral_constant<char32_t, 0> {}; template <> struct max<char32_t> : public std::integral_constant<char32_t, #ifdef UINT_LEAST32_MAX UINT_LEAST32_MAX #else 0xffffffff #endif > {}; #endif //ifdef ABC_CXX_CHAR32 // Specialization of min and max for integer types. template <> struct min< signed char> : public std::integral_constant< signed char, SCHAR_MIN> {}; template <> struct max< signed char> : public std::integral_constant< signed char, SCHAR_MAX> {}; template <> struct min<unsigned char> : public std::integral_constant<unsigned char, 0> {}; template <> struct max<unsigned char> : public std::integral_constant<unsigned char, UCHAR_MAX> {}; template <> struct min< short> : public std::integral_constant< short, SHRT_MIN> {}; template <> struct max< short> : public std::integral_constant< short, SHRT_MAX> {}; template <> struct min<unsigned short> : public std::integral_constant<unsigned short, 0> {}; template <> struct max<unsigned short> : public std::integral_constant<unsigned short, USHRT_MAX> {}; template <> struct min< int> : public std::integral_constant< int, INT_MIN> {}; template <> struct max< int> : public std::integral_constant< int, INT_MAX> {}; template <> struct min<unsigned > : public std::integral_constant<unsigned , 0> {}; template <> struct max<unsigned > : public std::integral_constant<unsigned , UINT_MAX> {}; template <> struct min< long> : public std::integral_constant< long, LONG_MIN> {}; template <> struct max< long> : public std::integral_constant< long, LONG_MAX> {}; template <> struct min<unsigned long> : public std::integral_constant<unsigned long, 0> {}; template <> struct max<unsigned long> : public std::integral_constant<unsigned long, ULONG_MAX> {}; template <> struct min< long long> : public std::integral_constant< long long, LLONG_MIN> {}; template <> struct max< long long> : public std::integral_constant< long long, LLONG_MAX> {}; template <> struct min<unsigned long long> : public std::integral_constant<unsigned long long, 0> {}; template <> struct max<unsigned long long> : public std::integral_constant<unsigned long long, ULLONG_MAX> {}; } //namespace numeric } //namespace abc //////////////////////////////////////////////////////////////////////////////////////////////////// #endif //ifndef ABC_NUMERIC_HXX <|endoftext|>
<commit_before>/* * Copyright (c) 2001-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Steve Reinhardt * Lisa Hsu * Nathan Binkert * Steve Raasch */ #include <iomanip> #include "arch/isa_traits.hh" #include "arch/utility.hh" #include "base/loader/symtab.hh" #include "config/the_isa.hh" #include "cpu/base.hh" #include "cpu/exetrace.hh" #include "cpu/static_inst.hh" #include "cpu/thread_context.hh" #include "debug/ExecAll.hh" #include "enums/OpClass.hh" using namespace std; using namespace TheISA; namespace Trace { void ExeTracerRecord::dumpTicks(ostream &outs) { ccprintf(outs, "%7d: ", when); } void Trace::ExeTracerRecord::traceInst(StaticInstPtr inst, bool ran) { ostream &outs = Trace::output(); if (!Debug::ExecUser || !Debug::ExecKernel) { bool in_user_mode = TheISA::inUserMode(thread); if (in_user_mode && !Debug::ExecUser) return; if (!in_user_mode && !Debug::ExecKernel) return; } if (Debug::ExecTicks) dumpTicks(outs); outs << thread->getCpuPtr()->name() << " "; if (Debug::ExecSpeculative) outs << (misspeculating ? "-" : "+") << " "; if (Debug::ExecAsid) outs << "A" << dec << TheISA::getExecutingAsid(thread) << " "; if (Debug::ExecThread) outs << "T" << thread->threadId() << " : "; std::string sym_str; Addr sym_addr; Addr cur_pc = pc.instAddr(); if (debugSymbolTable && Debug::ExecSymbol && !inUserMode(thread) && debugSymbolTable->findNearestSymbol(cur_pc, sym_str, sym_addr)) { if (cur_pc != sym_addr) sym_str += csprintf("+%d",cur_pc - sym_addr); outs << "@" << sym_str; } else { outs << "0x" << hex << cur_pc; } if (inst->isMicroop()) { outs << "." << setw(2) << dec << pc.microPC(); } else { outs << " "; } outs << " : "; // // Print decoded instruction // outs << setw(26) << left; outs << inst->disassemble(cur_pc, debugSymbolTable); if (ran) { outs << " : "; if (Debug::ExecOpClass) { outs << Enums::OpClassStrings[inst->opClass()] << " : "; } if (Debug::ExecResult && predicate == false) { outs << "Predicated False"; } if (Debug::ExecResult && data_status != DataInvalid) { ccprintf(outs, " D=%#018x", data.as_int); } if (Debug::ExecEffAddr && addr_valid) outs << " A=0x" << hex << addr; if (Debug::ExecFetchSeq && fetch_seq_valid) outs << " FetchSeq=" << dec << fetch_seq; if (Debug::ExecCPSeq && cp_seq_valid) outs << " CPSeq=" << dec << cp_seq; } // // End of line... // outs << endl; } void Trace::ExeTracerRecord::dump() { /* * The behavior this check tries to achieve is that if ExecMacro is on, * the macroop will be printed. If it's on and microops are also on, it's * printed before the microops start printing to give context. If the * microops aren't printed, then it's printed only when the final microop * finishes. Macroops then behave like regular instructions and don't * complete/print when they fault. */ if (Debug::ExecMacro && staticInst->isMicroop() && ((Debug::ExecMicro && macroStaticInst && staticInst->isFirstMicroop()) || (!Debug::ExecMicro && macroStaticInst && staticInst->isLastMicroop()))) { traceInst(macroStaticInst, false); } if (Debug::ExecMicro || !staticInst->isMicroop()) { traceInst(staticInst, true); } } } // namespace Trace //////////////////////////////////////////////////////////////////////// // // ExeTracer Simulation Object // Trace::ExeTracer * ExeTracerParams::create() { return new Trace::ExeTracer(this); } <commit_msg>debug : Fixes the issue wherein Debug symbols were not getting dumped into trace files for SE mode<commit_after>/* * Copyright (c) 2001-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Steve Reinhardt * Lisa Hsu * Nathan Binkert * Steve Raasch */ #include <iomanip> #include "arch/isa_traits.hh" #include "arch/utility.hh" #include "base/loader/symtab.hh" #include "config/the_isa.hh" #include "cpu/base.hh" #include "cpu/exetrace.hh" #include "cpu/static_inst.hh" #include "cpu/thread_context.hh" #include "debug/ExecAll.hh" #include "enums/OpClass.hh" using namespace std; using namespace TheISA; namespace Trace { void ExeTracerRecord::dumpTicks(ostream &outs) { ccprintf(outs, "%7d: ", when); } void Trace::ExeTracerRecord::traceInst(StaticInstPtr inst, bool ran) { ostream &outs = Trace::output(); if (!Debug::ExecUser || !Debug::ExecKernel) { bool in_user_mode = TheISA::inUserMode(thread); if (in_user_mode && !Debug::ExecUser) return; if (!in_user_mode && !Debug::ExecKernel) return; } if (Debug::ExecTicks) dumpTicks(outs); outs << thread->getCpuPtr()->name() << " "; if (Debug::ExecSpeculative) outs << (misspeculating ? "-" : "+") << " "; if (Debug::ExecAsid) outs << "A" << dec << TheISA::getExecutingAsid(thread) << " "; if (Debug::ExecThread) outs << "T" << thread->threadId() << " : "; std::string sym_str; Addr sym_addr; Addr cur_pc = pc.instAddr(); if (debugSymbolTable && Debug::ExecSymbol && (!FullSystem || !inUserMode(thread)) && debugSymbolTable->findNearestSymbol(cur_pc, sym_str, sym_addr)) { if (cur_pc != sym_addr) sym_str += csprintf("+%d",cur_pc - sym_addr); outs << "@" << sym_str; } else { outs << "0x" << hex << cur_pc; } if (inst->isMicroop()) { outs << "." << setw(2) << dec << pc.microPC(); } else { outs << " "; } outs << " : "; // // Print decoded instruction // outs << setw(26) << left; outs << inst->disassemble(cur_pc, debugSymbolTable); if (ran) { outs << " : "; if (Debug::ExecOpClass) { outs << Enums::OpClassStrings[inst->opClass()] << " : "; } if (Debug::ExecResult && predicate == false) { outs << "Predicated False"; } if (Debug::ExecResult && data_status != DataInvalid) { ccprintf(outs, " D=%#018x", data.as_int); } if (Debug::ExecEffAddr && addr_valid) outs << " A=0x" << hex << addr; if (Debug::ExecFetchSeq && fetch_seq_valid) outs << " FetchSeq=" << dec << fetch_seq; if (Debug::ExecCPSeq && cp_seq_valid) outs << " CPSeq=" << dec << cp_seq; } // // End of line... // outs << endl; } void Trace::ExeTracerRecord::dump() { /* * The behavior this check tries to achieve is that if ExecMacro is on, * the macroop will be printed. If it's on and microops are also on, it's * printed before the microops start printing to give context. If the * microops aren't printed, then it's printed only when the final microop * finishes. Macroops then behave like regular instructions and don't * complete/print when they fault. */ if (Debug::ExecMacro && staticInst->isMicroop() && ((Debug::ExecMicro && macroStaticInst && staticInst->isFirstMicroop()) || (!Debug::ExecMicro && macroStaticInst && staticInst->isLastMicroop()))) { traceInst(macroStaticInst, false); } if (Debug::ExecMicro || !staticInst->isMicroop()) { traceInst(staticInst, true); } } } // namespace Trace //////////////////////////////////////////////////////////////////////// // // ExeTracer Simulation Object // Trace::ExeTracer * ExeTracerParams::create() { return new Trace::ExeTracer(this); } <|endoftext|>
<commit_before>/* Copyright (c) 2008, Arvid Norberg 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 author 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 OWNER 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. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #ifdef TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <commit_msg>another FreeBSD fix<commit_after>/* Copyright (c) 2008, Arvid Norberg 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 author 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 OWNER 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. */ #ifndef TORRENT_ALLOCA #include "libtorrent/config.hpp" #if defined TORRENT_WINDOWS #include <malloc.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(_alloca(sizeof(t) * (n))) #elif defined TORRENT_BSD #include <stdlib.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #else #include <alloca.h> #define TORRENT_ALLOCA(t, n) static_cast<t*>(alloca(sizeof(t) * (n))) #endif #endif <|endoftext|>
<commit_before>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 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 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 OWNER 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #ifndef __ARCH_M3_X86_SYSTEM_HH__ #define __ARCH_M3_X86_SYSTEM_HH__ #include <string> #include <vector> #include "arch/x86/system.hh" #include "params/M3X86System.hh" #include "mem/qport.hh" #include "mem/dtu/noc_addr.hh" #include "sim/dtu_memory.hh" class M3X86System : public X86System, public DTUMemory { protected: static const size_t MAX_MODS = 64; static const size_t MAX_PES = 64; static const size_t RT_SIZE = 0x2000; static const uintptr_t RT_START = 0x3000; static const size_t STACK_SIZE = 0x1000; static const uintptr_t STACK_AREA = RT_START + RT_SIZE; static const size_t HEAP_SIZE = 0x1000; static const unsigned RES_PAGES; class NoCMasterPort : public QueuedMasterPort { protected: ReqPacketQueue reqQueue; SnoopRespPacketQueue snoopRespQueue; public: NoCMasterPort(M3X86System &_sys); bool recvTimingResp(PacketPtr) override { // unused return true; } }; struct BootModule { char name[128]; uint64_t addr; uint64_t size; } M5_ATTR_PACKED; struct KernelEnv { enum { TYPE_IMEM = 0, TYPE_EMEM = 1, TYPE_MEM = 2, }; uint64_t mods[MAX_MODS]; uint64_t pe_count; uint32_t pes[MAX_PES]; } M5_ATTR_PACKED; struct StartEnv { uint64_t coreid; uint32_t argc; char **argv; uint64_t sp; uint64_t entry; uint64_t lambda; uint32_t pager_sess; uint32_t pager_gate; uint32_t mounts_len; uint64_t mounts; uint32_t fds_len; uint64_t fds; uint64_t eps; uint64_t caps; uint64_t exit; uint64_t heapsize; uint64_t backend; uint64_t kenv; uint32_t pe; } M5_ATTR_PACKED; NoCMasterPort nocPort; std::vector<Addr> pes; std::string commandLine; public: const unsigned coreId; const Addr modOffset; const Addr modSize; public: typedef M3X86SystemParams Params; M3X86System(Params *p); ~M3X86System(); BaseMasterPort& getMasterPort(const std::string &if_name, PortID idx = InvalidPortID) override; void initState(); private: bool isKernelArg(const std::string &arg); void mapMemory(); size_t getArgc() const; void writeRemote(Addr dest, const uint8_t *data, size_t size); void writeArg(Addr &args, size_t &i, Addr argv, const char *cmd, const char *begin); Addr loadModule(const std::string &path, const std::string &name, Addr addr); }; #endif <commit_msg>M3System: added isr64_handler to StartEnv.<commit_after>/* * Copyright (c) 2015, Nils Asmussen * All rights reserved. * * Redistribution and use in source and binary forms, with or without * * 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 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 OWNER 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ #ifndef __ARCH_M3_X86_SYSTEM_HH__ #define __ARCH_M3_X86_SYSTEM_HH__ #include <string> #include <vector> #include "arch/x86/system.hh" #include "params/M3X86System.hh" #include "mem/qport.hh" #include "mem/dtu/noc_addr.hh" #include "sim/dtu_memory.hh" class M3X86System : public X86System, public DTUMemory { protected: static const size_t MAX_MODS = 64; static const size_t MAX_PES = 64; static const size_t RT_SIZE = 0x2000; static const uintptr_t RT_START = 0x3000; static const size_t STACK_SIZE = 0x1000; static const uintptr_t STACK_AREA = RT_START + RT_SIZE; static const size_t HEAP_SIZE = 0x1000; static const unsigned RES_PAGES; class NoCMasterPort : public QueuedMasterPort { protected: ReqPacketQueue reqQueue; SnoopRespPacketQueue snoopRespQueue; public: NoCMasterPort(M3X86System &_sys); bool recvTimingResp(PacketPtr) override { // unused return true; } }; struct BootModule { char name[128]; uint64_t addr; uint64_t size; } M5_ATTR_PACKED; struct KernelEnv { enum { TYPE_IMEM = 0, TYPE_EMEM = 1, TYPE_MEM = 2, }; uint64_t mods[MAX_MODS]; uint64_t pe_count; uint32_t pes[MAX_PES]; } M5_ATTR_PACKED; struct StartEnv { uint64_t coreid; uint32_t argc; char **argv; uint64_t sp; uint64_t entry; uint64_t lambda; uint32_t pager_sess; uint32_t pager_gate; uint32_t mounts_len; uint64_t mounts; uint32_t fds_len; uint64_t fds; uint64_t eps; uint64_t caps; uint64_t exit; uint64_t heapsize; uint64_t backend; uint64_t kenv; uint32_t pe; uint64_t isr64_handler; } M5_ATTR_PACKED; NoCMasterPort nocPort; std::vector<Addr> pes; std::string commandLine; public: const unsigned coreId; const Addr modOffset; const Addr modSize; public: typedef M3X86SystemParams Params; M3X86System(Params *p); ~M3X86System(); BaseMasterPort& getMasterPort(const std::string &if_name, PortID idx = InvalidPortID) override; void initState(); private: bool isKernelArg(const std::string &arg); void mapMemory(); size_t getArgc() const; void writeRemote(Addr dest, const uint8_t *data, size_t size); void writeArg(Addr &args, size_t &i, Addr argv, const char *cmd, const char *begin); Addr loadModule(const std::string &path, const std::string &name, Addr addr); }; #endif <|endoftext|>
<commit_before>/* Copyright (c) 2005, Arvid Norberg 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 author 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 OWNER 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. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATORS #error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators #endif #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // SunPRO seems to have an overly-strict // definition of POD types and doesn't // seem to allow boost::array in unions #define TORRENT_BROKEN_UNIONS 1 // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #define TORRENT_USE_ICONV 0 // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #define TORRENT_USE_ICONV 0 #endif #define TORRENT_HAS_FALLOCATE 0 // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 #define TORRENT_HAS_FALLOCATE 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS #define TORRENT_COMPLETE_TYPES_REQUIRED 1 // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_ICONV 0 #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #ifndef TORRENT_BROKEN_UNIONS #define TORRENT_BROKEN_UNIONS 0 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_COMPLETE_TYPES_REQUIRED #define TORRENT_COMPLETE_TYPES_REQUIRED 0 #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif #if TORRENT_BROKEN_UNIONS #define TORRENT_UNION struct #else #define TORRENT_UNION union #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <commit_msg>fixed typo in config relating to buffer debug builds<commit_after>/* Copyright (c) 2005, Arvid Norberg 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 author 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 OWNER 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. */ #ifndef TORRENT_CONFIG_HPP_INCLUDED #define TORRENT_CONFIG_HPP_INCLUDED #include <boost/config.hpp> #include <boost/version.hpp> #include <stdio.h> // for snprintf #if defined TORRENT_DEBUG_BUFFERS && !defined TORRENT_DISABLE_POOL_ALLOCATOR #error TORRENT_DEBUG_BUFFERS only works if you also disable pool allocators #endif #ifndef WIN32 #define __STDC_FORMAT_MACROS #include <inttypes.h> #endif #ifndef PRId64 #ifdef _WIN32 #define PRId64 "I64d" #else #define PRId64 "lld" #endif #endif // ======= GCC ========= #if defined __GNUC__ # if __GNUC__ >= 3 # define TORRENT_DEPRECATED __attribute__ ((deprecated)) # endif // GCC pre 4.0 did not have support for the visibility attribute # if __GNUC__ >= 4 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __attribute__ ((visibility("default"))) # endif # endif // ======= SUNPRO ========= #elif defined __SUNPRO_CC # if __SUNPRO_CC >= 0x550 # if defined(TORRENT_BUILDING_SHARED) || defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __global # endif # endif // SunPRO seems to have an overly-strict // definition of POD types and doesn't // seem to allow boost::array in unions #define TORRENT_BROKEN_UNIONS 1 // ======= MSVC ========= #elif defined BOOST_MSVC #pragma warning(disable: 4258) #pragma warning(disable: 4251) # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #define TORRENT_DEPRECATED_PREFIX __declspec(deprecated) #endif // ======= PLATFORMS ========= // set up defines for target environments // ==== AMIGA === #if defined __AMIGA__ || defined __amigaos__ || defined __AROS__ #define TORRENT_AMIGA #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_WRITEV 0 #define TORRENT_USE_READV 0 #define TORRENT_USE_IPV6 0 #define TORRENT_USE_BOOST_THREAD 0 #define TORRENT_USE_IOSTREAM 0 // set this to 1 to disable all floating point operations // (disables some float-dependent APIs) #define TORRENT_NO_FPU 1 #define TORRENT_USE_I2P 0 #define TORRENT_USE_ICONV 0 // ==== Darwin/BSD === #elif (defined __APPLE__ && defined __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \ || defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__ \ || defined __FreeBSD_kernel__ #define TORRENT_BSD // we don't need iconv on mac, because // the locale is always utf-8 #if defined __APPLE__ #define TORRENT_USE_ICONV 0 #endif #define TORRENT_HAS_FALLOCATE 0 // ==== LINUX === #elif defined __linux__ #define TORRENT_LINUX // ==== MINGW === #elif defined __MINGW32__ #define TORRENT_MINGW #define TORRENT_WINDOWS #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 // ==== WINDOWS === #elif defined WIN32 #define TORRENT_WINDOWS // windows has its own functions to convert // apple uses utf-8 as its locale, so no conversion // is necessary #define TORRENT_USE_ICONV 0 #define TORRENT_USE_RLIMIT 0 #define TORRENT_HAS_FALLOCATE 0 // ==== SOLARIS === #elif defined sun || defined __sun #define TORRENT_SOLARIS #define TORRENT_COMPLETE_TYPES_REQUIRED 1 // ==== BEOS === #elif defined __BEOS__ || defined __HAIKU__ #define TORRENT_BEOS #include <storage/StorageDefs.h> // B_PATH_NAME_LENGTH #define TORRENT_HAS_FALLOCATE 0 #define TORRENT_USE_MLOCK 0 #define TORRENT_USE_ICONV 0 #if __GNUCC__ == 2 # if defined(TORRENT_BUILDING_SHARED) # define TORRENT_EXPORT __declspec(dllexport) # elif defined(TORRENT_LINKING_SHARED) # define TORRENT_EXPORT __declspec(dllimport) # endif #endif #else #warning unknown OS, assuming BSD #define TORRENT_BSD #endif // on windows, NAME_MAX refers to Unicode characters // on linux it refers to bytes (utf-8 encoded) // TODO: Make this count Unicode characters instead of bytes on windows // windows #if defined FILENAME_MAX #define TORRENT_MAX_PATH FILENAME_MAX // beos #elif defined B_PATH_NAME_LENGTH #define TORRENT_MAX_PATH B_PATH_NAME_LENGTH // solaris #elif defined MAXPATH #define TORRENT_MAX_PATH MAXPATH // posix #elif defined NAME_MAX #define TORRENT_MAX_PATH NAME_MAX // none of the above #else // this is the maximum number of characters in a // path element / filename on windows #define TORRENT_MAX_PATH 255 #warning unknown platform, assuming the longest path is 255 #endif #if defined TORRENT_WINDOWS && !defined TORRENT_MINGW // class X needs to have dll-interface to be used by clients of class Y #pragma warning(disable:4251) // '_vsnprintf': This function or variable may be unsafe #pragma warning(disable:4996) #include <stdarg.h> inline int snprintf(char* buf, int len, char const* fmt, ...) { va_list lp; va_start(lp, fmt); int ret = _vsnprintf(buf, len, fmt, lp); va_end(lp); if (ret < 0) { buf[len-1] = 0; ret = len-1; } return ret; } #define strtoll _strtoi64 #else #include <limits.h> #endif #if (defined(TORRENT_LOGGING) || defined(TORRENT_VERBOSE_LOGGING)) \ && !defined (TORRENT_UPNP_LOGGING) && TORRENT_USE_IOSTREAM #define TORRENT_UPNP_LOGGING #endif // libiconv presence, not implemented yet #ifndef TORRENT_USE_ICONV #define TORRENT_USE_ICONV 1 #endif #ifndef TORRENT_BROKEN_UNIONS #define TORRENT_BROKEN_UNIONS 0 #endif #if defined UNICODE && !defined BOOST_NO_STD_WSTRING #define TORRENT_USE_WSTRING 1 #else #define TORRENT_USE_WSTRING 0 #endif // UNICODE #ifndef TORRENT_HAS_FALLOCATE #define TORRENT_HAS_FALLOCATE 1 #endif #ifndef TORRENT_EXPORT # define TORRENT_EXPORT #endif #ifndef TORRENT_DEPRECATED_PREFIX #define TORRENT_DEPRECATED_PREFIX #endif #ifndef TORRENT_DEPRECATED #define TORRENT_DEPRECATED #endif #ifndef TORRENT_COMPLETE_TYPES_REQUIRED #define TORRENT_COMPLETE_TYPES_REQUIRED 0 #endif #ifndef TORRENT_USE_RLIMIT #define TORRENT_USE_RLIMIT 1 #endif #ifndef TORRENT_USE_IPV6 #define TORRENT_USE_IPV6 1 #endif #ifndef TORRENT_USE_MLOCK #define TORRENT_USE_MLOCK 1 #endif #ifndef TORRENT_USE_WRITEV #define TORRENT_USE_WRITEV 1 #endif #ifndef TORRENT_USE_READV #define TORRENT_USE_READV 1 #endif #ifndef TORRENT_NO_FPU #define TORRENT_NO_FPU 0 #endif #if !defined TORRENT_USE_IOSTREAM && !defined BOOST_NO_IOSTREAM #define TORRENT_USE_IOSTREAM 1 #else #define TORRENT_USE_IOSTREAM 0 #endif #ifndef TORRENT_USE_I2P #define TORRENT_USE_I2P 1 #endif #if !defined(TORRENT_READ_HANDLER_MAX_SIZE) # define TORRENT_READ_HANDLER_MAX_SIZE 256 #endif #if !defined(TORRENT_WRITE_HANDLER_MAX_SIZE) # define TORRENT_WRITE_HANDLER_MAX_SIZE 256 #endif #if defined _MSC_VER && _MSC_VER <= 1200 #define for if (false) {} else for #endif #if TORRENT_BROKEN_UNIONS #define TORRENT_UNION struct #else #define TORRENT_UNION union #endif // determine what timer implementation we can use // if one is already defined, don't pick one // autmatically. This lets the user control this // from the Jamfile #if !defined TORRENT_USE_ABSOLUTE_TIME \ && !defined TORRENT_USE_QUERY_PERFORMANCE_TIMER \ && !defined TORRENT_USE_CLOCK_GETTIME \ && !defined TORRENT_USE_BOOST_DATE_TIME \ && !defined TORRENT_USE_ECLOCK \ && !defined TORRENT_USE_SYSTEM_TIME #if defined(__MACH__) #define TORRENT_USE_ABSOLUTE_TIME 1 #elif defined(_WIN32) || defined TORRENT_MINGW #define TORRENT_USE_QUERY_PERFORMANCE_TIMER 1 #elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK >= 0 #define TORRENT_USE_CLOCK_GETTIME 1 #elif defined(TORRENT_AMIGA) #define TORRENT_USE_ECLOCK 1 #elif defined(TORRENT_BEOS) #define TORRENT_USE_SYSTEM_TIME 1 #else #define TORRENT_USE_BOOST_DATE_TIME 1 #endif #endif #endif // TORRENT_CONFIG_HPP_INCLUDED <|endoftext|>
<commit_before>/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "CodeGenerator.h" #include "../InstructionWalker.h" #include "../Module.h" #include "../Profiler.h" #include "GraphColoring.h" #include "KernelInfo.h" #include "log.h" #include "../../lib/vc4asm/src/Validator.h" #include <assert.h> #include <climits> #include <map> #include <sstream> using namespace vc4c; using namespace vc4c::qpu_asm; using namespace vc4c::intermediate; CodeGenerator::CodeGenerator(const Module& module, const Configuration& config) : config(config), module(module) {} static FastMap<const Local*, std::size_t> mapLabels(Method& method) { logging::debug() << "-----" << logging::endl; FastMap<const Local*, std::size_t> labelsMap; labelsMap.reserve(method.size()); // index is in bytes, so an increment of 1 instructions, increments by 8 bytes std::size_t index = 0; auto it = method.walkAllInstructions(); while(!it.isEndOfMethod()) { BranchLabel* label = it.isEndOfBlock() ? nullptr : it.get<BranchLabel>(); if(label != nullptr) { logging::debug() << "Mapping label '" << label->getLabel()->name << "' to byte-position " << index << logging::endl; labelsMap[label->getLabel()] = index; it.nextInMethod(); } else if(!it.isEndOfBlock() && it.has() && !it->mapsToASMInstruction()) { // an instruction which has no equivalent in machine code -> drop logging::debug() << "Dropping instruction not mapped to assembler: " << it->to_string() << logging::endl; it.erase(); } else { index += 8; it.nextInMethod(); } if(it.isEndOfBlock() && !it.isEndOfMethod()) // this handles empty basic blocks, so the index is not incremented in the next iteration it.nextInMethod(); } logging::debug() << "Mapped " << labelsMap.size() << " labels to positions" << logging::endl; return labelsMap; } const FastModificationList<std::unique_ptr<qpu_asm::Instruction>>& CodeGenerator::generateInstructions(Method& method) { PROFILE_COUNTER(vc4c::profiler::COUNTER_BACKEND + 0, "CodeGeneration (before)", method.countInstructions()); #ifdef MULTI_THREADED instructionsLock.lock(); #endif auto& generatedInstructions = allInstructions[&method]; #ifdef MULTI_THREADED instructionsLock.unlock(); #endif // check and fix possible errors with register-association PROFILE_START(initializeLocalsUses); GraphColoring coloring(method, method.walkAllInstructions()); PROFILE_END(initializeLocalsUses); PROFILE_START(colorGraph); std::size_t round = 0; while(round < config.additionalOptions.registerResolverMaxRounds && !coloring.colorGraph()) { if(coloring.fixErrors()) break; ++round; } if(round >= config.additionalOptions.registerResolverMaxRounds) { logging::warn() << "Register conflict resolver has exceeded its maximum rounds, there might still be errors!" << logging::endl; } PROFILE_END(colorGraph); // create label-map + remove labels const auto labelMap = mapLabels(method); // IMPORTANT: DO NOT OPTIMIZE, RE-ORDER, COMBINE, INSERT OR REMOVE ANY INSTRUCTION AFTER THIS POINT!!! // otherwise, labels/branches will be wrong // map to registers PROFILE_START(toRegisterMap); PROFILE_START(toRegisterMapGraph); auto registerMapping = coloring.toRegisterMap(); PROFILE_END(toRegisterMapGraph); PROFILE_END(toRegisterMap); logging::debug() << "-----" << logging::endl; std::size_t index = 0; std::string s = ""; for(auto bb_it = method.begin(); bb_it != method.end(); ++bb_it) { auto it = bb_it->begin(); if(it.getBasicBlock()->empty()) { s = s.empty() ? bb_it->getLabel()->to_string() : s + "," + bb_it->getLabel()->to_string(); continue; } auto label = dynamic_cast<intermediate::BranchLabel*>(it.get()); assert(label != nullptr); it.nextInBlock(); auto instr = it.get(); if(instr->mapsToASMInstruction()) { Instruction* mapped = instr->convertToAsm(registerMapping, labelMap, index); if(mapped != nullptr) { mapped->previousComment += s.empty() ? label->to_string() : s + ", " + label->to_string(); s = ""; generatedInstructions.emplace_back(mapped); } ++index; } it.nextInBlock(); while(!it.isEndOfBlock()) { auto instr = it.get(); if(instr->mapsToASMInstruction()) { Instruction* mapped = instr->convertToAsm(registerMapping, labelMap, index); if(mapped != nullptr) { generatedInstructions.emplace_back(mapped); } ++index; } it.nextInBlock(); } } logging::debug() << "-----" << logging::endl; index = 0; for(const auto& instr : generatedInstructions) { CPPLOG_LAZY( logging::Level::DEBUG, log << std::hex << index << " " << instr->toHexString(true) << logging::endl); index += 8; } logging::debug() << "Generated " << std::dec << generatedInstructions.size() << " instructions!" << logging::endl; PROFILE_COUNTER_WITH_PREV(vc4c::profiler::COUNTER_BACKEND + 1000, "CodeGeneration (after)", generatedInstructions.size(), vc4c::profiler::COUNTER_BACKEND + 0); return generatedInstructions; } std::size_t CodeGenerator::writeOutput(std::ostream& stream) { ModuleInfo moduleInfo; std::size_t maxStackSize = 0; for(const auto& m : module) maxStackSize = std::max(maxStackSize, m->calculateStackSize() * m->metaData.getWorkGroupSize()); if(maxStackSize / sizeof(uint64_t) > std::numeric_limits<uint16_t>::max() || maxStackSize % sizeof(uint64_t) != 0) throw CompilationError( CompilationStep::CODE_GENERATION, "Stack-frame has unsupported size of", std::to_string(maxStackSize)); moduleInfo.setStackFrameSize(Word(Byte(maxStackSize))); std::size_t numBytes = 0; // initial offset is zero std::size_t offset = 0; if(config.writeKernelInfo) { moduleInfo.kernelInfos.reserve(allInstructions.size()); // generate kernel-infos for(const auto& pair : allInstructions) { moduleInfo.addKernelInfo(getKernelInfos(*pair.first, offset, pair.second.size())); offset += pair.second.size(); } // add global offset (size of header) std::ostringstream dummyStream; offset = moduleInfo.write(dummyStream, config.outputMode, module.globalData, Byte(maxStackSize)); for(KernelInfo& info : moduleInfo.kernelInfos) info.setOffset(info.getOffset() + Word(offset)); } // prepend module header to output // also write, if writeKernelInfo is not set, since global-data is written in here too logging::debug() << "Writing module header..." << logging::endl; numBytes += moduleInfo.write(stream, config.outputMode, module.globalData, Byte(maxStackSize)) * sizeof(uint64_t); for(const auto& pair : allInstructions) { switch(config.outputMode) { case OutputMode::ASSEMBLER: for(const auto& instr : pair.second) { stream << instr->toASMString() << std::endl; numBytes += 0; // doesn't matter here, since the number of bytes is unused for assembler output } break; case OutputMode::BINARY: for(const auto& instr : pair.second) { const uint64_t binary = instr->toBinaryCode(); stream.write(reinterpret_cast<const char*>(&binary), 8); numBytes += 8; } break; case OutputMode::HEX: for(const auto& instr : pair.second) { stream << instr->toHexString(true) << std::endl; numBytes += 8; // doesn't matter here, since the number of bytes is unused for hexadecimal output } } } stream.flush(); return numBytes; } // register/instruction mapping void CodeGenerator::toMachineCode(Method& kernel) { kernel.cleanLocals(); const auto& instructions = generateInstructions(kernel); #ifdef VERIFIER_HEADER std::vector<uint64_t> hexData; hexData.reserve(instructions.size()); for(const auto& instr : instructions) { hexData.push_back(instr->toBinaryCode()); } Validator v; v.OnMessage = [&instructions](const Message& msg) -> void { const auto & validatorMessage = dynamic_cast<const Validator::Message&>(msg); if(validatorMessage.Loc >= 0) { auto it = instructions.begin(); std::advance(it, validatorMessage.Loc); logging::error() << "Validation-error '" << validatorMessage.Text << "' in: " << (*it)->toASMString() << logging::endl; if(validatorMessage.RefLoc >= 0) { it = instructions.begin(); std::advance(it, validatorMessage.RefLoc); logging::error() << "With reference to instruction: " << (*it)->toASMString() << logging::endl; } } throw CompilationError(CompilationStep::VERIFIER, "vc4asm verification error", msg.toString()); }; v.Instructions = &hexData; logging::info() << "Validation-output: " << logging::endl; v.Validate(); fflush(stderr); #endif } <commit_msg>Add: surpress exceptions when `--no-safe-stop` is enabled<commit_after>/* * Author: doe300 * * See the file "LICENSE" for the full license governing this code. */ #include "CodeGenerator.h" #include "../InstructionWalker.h" #include "../Module.h" #include "../Profiler.h" #include "GraphColoring.h" #include "KernelInfo.h" #include "log.h" #include "../../lib/vc4asm/src/Validator.h" #include <assert.h> #include <climits> #include <map> #include <sstream> using namespace vc4c; using namespace vc4c::qpu_asm; using namespace vc4c::intermediate; CodeGenerator::CodeGenerator(const Module& module, const Configuration& config) : config(config), module(module) {} static FastMap<const Local*, std::size_t> mapLabels(Method& method) { logging::debug() << "-----" << logging::endl; FastMap<const Local*, std::size_t> labelsMap; labelsMap.reserve(method.size()); // index is in bytes, so an increment of 1 instructions, increments by 8 bytes std::size_t index = 0; auto it = method.walkAllInstructions(); while(!it.isEndOfMethod()) { BranchLabel* label = it.isEndOfBlock() ? nullptr : it.get<BranchLabel>(); if(label != nullptr) { logging::debug() << "Mapping label '" << label->getLabel()->name << "' to byte-position " << index << logging::endl; labelsMap[label->getLabel()] = index; it.nextInMethod(); } else if(!it.isEndOfBlock() && it.has() && !it->mapsToASMInstruction()) { // an instruction which has no equivalent in machine code -> drop logging::debug() << "Dropping instruction not mapped to assembler: " << it->to_string() << logging::endl; it.erase(); } else { index += 8; it.nextInMethod(); } if(it.isEndOfBlock() && !it.isEndOfMethod()) // this handles empty basic blocks, so the index is not incremented in the next iteration it.nextInMethod(); } logging::debug() << "Mapped " << labelsMap.size() << " labels to positions" << logging::endl; return labelsMap; } const FastModificationList<std::unique_ptr<qpu_asm::Instruction>>& CodeGenerator::generateInstructions(Method& method) { PROFILE_COUNTER(vc4c::profiler::COUNTER_BACKEND + 0, "CodeGeneration (before)", method.countInstructions()); #ifdef MULTI_THREADED instructionsLock.lock(); #endif auto& generatedInstructions = allInstructions[&method]; #ifdef MULTI_THREADED instructionsLock.unlock(); #endif // check and fix possible errors with register-association PROFILE_START(initializeLocalsUses); GraphColoring coloring(method, method.walkAllInstructions()); PROFILE_END(initializeLocalsUses); PROFILE_START(colorGraph); std::size_t round = 0; while(round < config.additionalOptions.registerResolverMaxRounds && !coloring.colorGraph()) { if(coloring.fixErrors()) break; ++round; } if(round >= config.additionalOptions.registerResolverMaxRounds) { logging::warn() << "Register conflict resolver has exceeded its maximum rounds, there might still be errors!" << logging::endl; } PROFILE_END(colorGraph); // create label-map + remove labels const auto labelMap = mapLabels(method); // IMPORTANT: DO NOT OPTIMIZE, RE-ORDER, COMBINE, INSERT OR REMOVE ANY INSTRUCTION AFTER THIS POINT!!! // otherwise, labels/branches will be wrong // map to registers PROFILE_START(toRegisterMap); PROFILE_START(toRegisterMapGraph); auto registerMapping = coloring.toRegisterMap(); PROFILE_END(toRegisterMapGraph); PROFILE_END(toRegisterMap); logging::debug() << "-----" << logging::endl; std::size_t index = 0; std::string s = ""; for(auto bb_it = method.begin(); bb_it != method.end(); ++bb_it) { auto it = bb_it->begin(); if(it.getBasicBlock()->empty()) { s = s.empty() ? bb_it->getLabel()->to_string() : s + "," + bb_it->getLabel()->to_string(); continue; } auto label = dynamic_cast<intermediate::BranchLabel*>(it.get()); assert(label != nullptr); it.nextInBlock(); auto instr = it.get(); if(instr->mapsToASMInstruction()) { Instruction* mapped = instr->convertToAsm(registerMapping, labelMap, index); if(mapped != nullptr) { mapped->previousComment += s.empty() ? label->to_string() : s + ", " + label->to_string(); s = ""; generatedInstructions.emplace_back(mapped); } ++index; } it.nextInBlock(); while(!it.isEndOfBlock()) { auto instr = it.get(); if(instr->mapsToASMInstruction()) { Instruction* mapped = instr->convertToAsm(registerMapping, labelMap, index); if(mapped != nullptr) { generatedInstructions.emplace_back(mapped); } ++index; } it.nextInBlock(); } } logging::debug() << "-----" << logging::endl; index = 0; for(const auto& instr : generatedInstructions) { CPPLOG_LAZY( logging::Level::DEBUG, log << std::hex << index << " " << instr->toHexString(true) << logging::endl); index += 8; } logging::debug() << "Generated " << std::dec << generatedInstructions.size() << " instructions!" << logging::endl; PROFILE_COUNTER_WITH_PREV(vc4c::profiler::COUNTER_BACKEND + 1000, "CodeGeneration (after)", generatedInstructions.size(), vc4c::profiler::COUNTER_BACKEND + 0); return generatedInstructions; } std::size_t CodeGenerator::writeOutput(std::ostream& stream) { ModuleInfo moduleInfo; std::size_t maxStackSize = 0; for(const auto& m : module) maxStackSize = std::max(maxStackSize, m->calculateStackSize() * m->metaData.getWorkGroupSize()); if(maxStackSize / sizeof(uint64_t) > std::numeric_limits<uint16_t>::max() || maxStackSize % sizeof(uint64_t) != 0) throw CompilationError( CompilationStep::CODE_GENERATION, "Stack-frame has unsupported size of", std::to_string(maxStackSize)); moduleInfo.setStackFrameSize(Word(Byte(maxStackSize))); std::size_t numBytes = 0; // initial offset is zero std::size_t offset = 0; if(config.writeKernelInfo) { moduleInfo.kernelInfos.reserve(allInstructions.size()); // generate kernel-infos for(const auto& pair : allInstructions) { moduleInfo.addKernelInfo(getKernelInfos(*pair.first, offset, pair.second.size())); offset += pair.second.size(); } // add global offset (size of header) std::ostringstream dummyStream; offset = moduleInfo.write(dummyStream, config.outputMode, module.globalData, Byte(maxStackSize)); for(KernelInfo& info : moduleInfo.kernelInfos) info.setOffset(info.getOffset() + Word(offset)); } // prepend module header to output // also write, if writeKernelInfo is not set, since global-data is written in here too logging::debug() << "Writing module header..." << logging::endl; numBytes += moduleInfo.write(stream, config.outputMode, module.globalData, Byte(maxStackSize)) * sizeof(uint64_t); for(const auto& pair : allInstructions) { switch(config.outputMode) { case OutputMode::ASSEMBLER: for(const auto& instr : pair.second) { stream << instr->toASMString() << std::endl; numBytes += 0; // doesn't matter here, since the number of bytes is unused for assembler output } break; case OutputMode::BINARY: for(const auto& instr : pair.second) { const uint64_t binary = instr->toBinaryCode(); stream.write(reinterpret_cast<const char*>(&binary), 8); numBytes += 8; } break; case OutputMode::HEX: for(const auto& instr : pair.second) { stream << instr->toHexString(true) << std::endl; numBytes += 8; // doesn't matter here, since the number of bytes is unused for hexadecimal output } } } stream.flush(); return numBytes; } // register/instruction mapping void CodeGenerator::toMachineCode(Method& kernel) { kernel.cleanLocals(); const auto& instructions = generateInstructions(kernel); #ifdef VERIFIER_HEADER std::vector<uint64_t> hexData; hexData.reserve(instructions.size()); for(const auto& instr : instructions) { hexData.push_back(instr->toBinaryCode()); } Validator v; v.OnMessage = [&instructions, this](const Message& msg) -> void { const auto & validatorMessage = dynamic_cast<const Validator::Message&>(msg); if(validatorMessage.Loc >= 0) { auto it = instructions.begin(); std::advance(it, validatorMessage.Loc); logging::error() << "Validation-error '" << validatorMessage.Text << "' in: " << (*it)->toASMString() << logging::endl; if(validatorMessage.RefLoc >= 0) { it = instructions.begin(); std::advance(it, validatorMessage.RefLoc); logging::error() << "With reference to instruction: " << (*it)->toASMString() << logging::endl; } } if (config.stopWhenVerificationFailed) throw CompilationError(CompilationStep::VERIFIER, "vc4asm verification error", msg.toString()); }; v.Instructions = &hexData; logging::info() << "Validation-output: " << logging::endl; v.Validate(); fflush(stderr); #endif } <|endoftext|>
<commit_before>/* * Author: Mihai T Panu <mihai.tudor.panu@intel.com> * Copyright (c) 2015 Intel Corporation. * * 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 <unistd.h> #include <signal.h> #include <iostream> #include <string> #include <thread> #include <mutex> #include "grovemd.h" #include "jhd1313m1.h" #include "rfr359f.h" #include "hmc5883l.h" #include "grovevdiv.h" using namespace std; using namespace upm; mutex crit; bool running = true; bool blockedFL = false; bool blockedFR = false; bool blockedRL = false; bool blockedRR = false; bool batteryLow = true; const float batteryThreshold = 7.2f; const string heading = "--|--N--|--|--E--|--|--S--|--|--W--|--|--N--|--"; // Handler for POSIX signals void signalHandler(int signo) { if (signo == SIGINT){ running = false; } } // Heading display on LCD void displayHeading(Jhd1313m1 *lcd, Hmc5883l *compass){ // You can set your declination in radians for more accurate readings //compass->set_declination(0.2749); while(running){ compass->update(); // Round the heading returned by compass and turn it into an index // from 0 to 36 for the heading string int hdg = int(compass->heading() + 0.5f); int hdg_index = hdg / 10; // Write the heading on the first line, lcd->clear() is not needed since // we write the entire line crit.lock(); lcd->setCursor(0, 0); lcd->write("HDG: " + heading.substr(hdg_index, 11)); crit.unlock(); // Update readings and display every 250 ms usleep(250000); } } // Battery level display on LCD void displayBattery(Jhd1313m1 *lcd, GroveVDiv *divider){ // Variable used for flashing LCD red when battery is low uint8_t red = 0x3F; while(running){ // Read 50 samples each with 2 ms in between (100 ms total) int avgValue = divider->value(50); // Convert the value to voltage at 3x gain and 5V reference // Also subtract half a unit for improved accuracy in the 6~8V range float voltage = divider->computedValue(3, avgValue) - 0.5f; string displayStr = to_string(voltage); displayStr = displayStr.substr(0, 4); // Write the battery voltage on the second line of the display crit.lock(); lcd->setCursor(1, 0); lcd->write("Batt: " + displayStr + " V "); crit.unlock(); // Battery low, flash LCD and refresh more often if(voltage < 7.2f) { batteryLow = true; lcd->setColor(red, 0x00, 0x00); // Toggle red bits red = ~red; sleep(2); } else{ // Battery was considered low but new reading is above threshold // Thus return to normal operation mode and make the LCD green if(batteryLow){ lcd->setColor(0x00, 0xCF, 0x00); } batteryLow = false; // Refresh every 5 seconds sleep(5); } } } // IR sensors thread void distanceIR(GroveMD *motors, RFR359F *fl, RFR359F *fr, RFR359F *rl, RFR359F *rr){ while(running){ // Set the corresponding sensor variable when an object is detected if(fl->objectDetected()){ blockedFL = true; } else{ blockedFL = false; } if(fr->objectDetected()){ blockedFR = true; } else{ blockedFR = false; } if(rl->objectDetected()){ blockedRL = true; } else{ blockedRL = false; } if(rr->objectDetected()){ blockedRR = true; } else{ blockedRR = false; } // Stop the motors if any sensor was triggered if(blockedFL || blockedFR || blockedRL || blockedRR){ motors->setMotorSpeeds(0, 0); } // Refresh every 10 ms usleep(10000); } } int main(int argc, char **argv) { // Register signal handler signal(SIGINT, signalHandler); // Instantiate an I2C Grove Motor Driver on default I2C bus GroveMD *motors = new GroveMD(GROVEMD_I2C_BUS, GROVEMD_DEFAULT_I2C_ADDR); if(motors == NULL){ cerr << "Failed to initialize the motor driver." << endl; exit(EXIT_FAILURE); } // Initialize the Grove RGB Backlit LCD using implicit // 0x62 for RGB_ADDRESS and 0x3E for LCD_ADDRESS Jhd1313m1 *lcd = new upm::Jhd1313m1(0); if(lcd == NULL){ cerr << "Failed to initialize the LCD." << endl; exit(EXIT_FAILURE); } // Instantiate the HMC5883 compass on default bus Hmc5883l *compass = new Hmc5883l(0); if(compass == NULL){ cerr << "Failed to initialize the HMC5883 compass." << endl; exit(EXIT_FAILURE); } // Instantiate the Grove Voltage Divider on pin A0 GroveVDiv *divider = new GroveVDiv(0); if(divider == NULL){ cerr << "Failed to initialize the voltage divider." << endl; exit(EXIT_FAILURE); } // Instantiate 4 Grove IR Distance Interrupters on pins D2, D4, D6, D8 RFR359F *frontLeftIR = new RFR359F(2); RFR359F *frontRightIR = new RFR359F(4); RFR359F *rearLeftIR = new RFR359F(6); RFR359F *rearRightIR = new RFR359F(8); if(frontLeftIR == NULL || frontRightIR == NULL || rearLeftIR == NULL || rearRightIR == NULL){ cerr << "Failed to initialize one of the IR sensors." << endl; exit(EXIT_FAILURE); } // Start independent threads for the different components thread comp (displayHeading, lcd, compass); thread batt (displayBattery, lcd, divider); thread collision (distanceIR, motors, frontLeftIR, frontRightIR, rearLeftIR, rearRightIR); // Main event and control loop // Commands are given through stdin as tuples of the form <CMD_NAME SPEED> // Except for the <stop> command and are case sensitive while(running){ string command; int speed; // Wait command from stdin cin.clear(); cin >> command; if(command == "stop" || command.empty()){ // Stop rover motors->setMotorSpeeds(0, 0); cout << "Rover stopping!" << endl; continue; } // Read speed cin >> speed; // Check against non-numbers entered in string if(cin.fail()){ cerr << "Error: Bad input! Please check your command and try again." << endl; continue; } // Check for proper range if(speed < 0 || speed > 255){ cerr << "Error: Speed needs to be between 0 to 255." << endl; continue; } // Direction is set based on command/keyword if(command == "fwd" && (!blockedFL || !blockedFR)){ motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CW); motors->setMotorSpeeds(speed, speed); cout << "Rover going forward at speed " << speed << endl; } else if(command == "left" && (!blockedFL || !blockedRL)){ motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CW); motors->setMotorSpeeds(speed, speed); cout << "Rover turning left at speed " << speed << endl; } else if(command == "right" && (!blockedFR || !blockedRR)){ motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CCW); motors->setMotorSpeeds(speed, speed); cout << "Rover turning right at speed " << speed << endl; } else if(command == "rev" && (!blockedRL || !blockedRR)){ motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CCW); motors->setMotorSpeeds(speed, speed); cout << "Rover in reverse at speed " << speed << endl; } else{ motors->setMotorSpeeds(0, 0); cout << "Command not supported or direction blocked!" << endl; } } // Clean up and exit comp.join(); batt.join(); collision.join(); // Turn off LCD lcd->setColor(0x00, 0x00, 0x00); lcd->clear(); cout << "Exiting..." << endl; delete compass; delete divider; delete motors; return 0; } <commit_msg>robotics: updated motor directions and a few other changes<commit_after>/* * Author: Mihai T Panu <mihai.tudor.panu@intel.com> * Copyright (c) 2015 Intel Corporation. * * 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 <unistd.h> #include <signal.h> #include <iostream> #include <string> #include <thread> #include <mutex> #include "grovemd.h" #include "jhd1313m1.h" #include "rfr359f.h" #include "hmc5883l.h" #include "grovevdiv.h" using namespace std; using namespace upm; mutex crit; bool running = true; bool blockedFL = false; bool blockedFR = false; bool blockedRL = false; bool blockedRR = false; bool batteryLow = true; const float batteryThreshold = 7.2f; const string heading = "--|--N--|--|--E--|--|--S--|--|--W--|--|--N--|--"; // Handler for POSIX signals void signalHandler(int signo) { if (signo == SIGINT){ running = false; } } // Heading display on LCD void displayHeading(Jhd1313m1 *lcd, Hmc5883l *compass){ // You can set your declination in radians for more accurate readings //compass->set_declination(0.2749); while(running){ compass->update(); // Round the heading returned by compass and turn it into an index // from 0 to 36 for the heading string int hdg = int(compass->heading() + 0.5f); int hdg_index = hdg / 10; // Write the heading on the first line, lcd->clear() is not needed since // we write the entire line crit.lock(); lcd->setCursor(0, 0); lcd->write("HDG: " + heading.substr(hdg_index, 11)); crit.unlock(); // Update readings and display every 250 ms usleep(250000); } } // Battery level display on LCD void displayBattery(Jhd1313m1 *lcd, GroveVDiv *divider){ // Variable used for flashing LCD red when battery is low uint8_t red = 0x3F; while(running){ // Read 50 samples each with 2 ms in between (100 ms total) int avgValue = divider->value(50); // Convert the value to voltage at 3x gain and 5V reference float voltage = divider->computedValue(3, avgValue); string displayStr = to_string(voltage); displayStr = displayStr.substr(0, 4); // Write the battery voltage on the second line of the display crit.lock(); lcd->setCursor(1, 0); lcd->write("Batt: " + displayStr + " V "); crit.unlock(); // Battery low, flash LCD and refresh more often if(voltage < 7.2f) { batteryLow = true; lcd->setColor(red, 0x00, 0x00); // Toggle red bits red = ~red; sleep(2); } else{ // Battery was considered low but new reading is above threshold // Thus return to normal operation mode and make the LCD green if(batteryLow){ lcd->setColor(0x00, 0xCF, 0x00); } batteryLow = false; // Refresh every 5 seconds sleep(5); } } } // IR sensors thread void distanceIR(GroveMD *motors, RFR359F *fl, RFR359F *fr, RFR359F *rl, RFR359F *rr){ while(running){ // Set the corresponding sensor variable when an object is detected if(fl->objectDetected()){ blockedFL = true; } else{ blockedFL = false; } if(fr->objectDetected()){ blockedFR = true; } else{ blockedFR = false; } if(rl->objectDetected()){ blockedRL = true; } else{ blockedRL = false; } if(rr->objectDetected()){ blockedRR = true; } else{ blockedRR = false; } // Stop the motors if any sensor was triggered if(blockedFL || blockedFR || blockedRL || blockedRR){ motors->setMotorSpeeds(0, 0); } // Refresh every 10 ms usleep(10000); } } int main(int argc, char **argv) { // Register signal handler signal(SIGINT, signalHandler); // Instantiate an I2C Grove Motor Driver on default I2C bus // This will also set the I2C bus to 100 kHz for compatibility // Default address of 0x0f is used (all 4 switches in up position) GroveMD *motors = new GroveMD(GROVEMD_I2C_BUS, GROVEMD_DEFAULT_I2C_ADDR); if(motors == NULL){ cerr << "Failed to initialize the motor driver." << endl; exit(EXIT_FAILURE); } // Initialize the Grove RGB Backlit LCD using implicit // 0x62 for RGB_ADDRESS and 0x3E for LCD_ADDRESS Jhd1313m1 *lcd = new upm::Jhd1313m1(0); if(lcd == NULL){ cerr << "Failed to initialize the LCD." << endl; exit(EXIT_FAILURE); } // Instantiate the HMC5883 compass on default I2C bus // The compass requires an I2C level translator to 3.3V if used Hmc5883l *compass = new Hmc5883l(0); if(compass == NULL){ cerr << "Failed to initialize the HMC5883 compass." << endl; exit(EXIT_FAILURE); } // Instantiate the Grove Voltage Divider on pin A0 GroveVDiv *divider = new GroveVDiv(0); if(divider == NULL){ cerr << "Failed to initialize the voltage divider." << endl; exit(EXIT_FAILURE); } // Instantiate 4 Grove IR Distance Interrupters on pins D2, D4, D6, D8 RFR359F *frontLeftIR = new RFR359F(2); RFR359F *frontRightIR = new RFR359F(4); RFR359F *rearLeftIR = new RFR359F(6); RFR359F *rearRightIR = new RFR359F(8); if(frontLeftIR == NULL || frontRightIR == NULL || rearLeftIR == NULL || rearRightIR == NULL){ cerr << "Failed to initialize one of the IR sensors." << endl; exit(EXIT_FAILURE); } // Start independent threads for the different components // If you're not using a component comment out the corresponding thread call thread comp (displayHeading, lcd, compass); thread batt (displayBattery, lcd, divider); thread collision (distanceIR, motors, frontLeftIR, frontRightIR, rearLeftIR, rearRightIR); // Main event and control loop // Commands are given through stdin as tuples of the form <CMD_NAME SPEED> // Except for the <stop> command and are case sensitive while(running){ string command; int speed; // Wait command from stdin cin.clear(); cin >> command; if(command == "stop" || command.empty()){ // Stop rover motors->setMotorSpeeds(0, 0); cout << "Rover stopping!" << endl; continue; } // Read speed cin >> speed; // Check against non-numbers entered in string if(cin.fail()){ cerr << "Error: Bad input! Please check your command and try again." << endl; continue; } // Check for proper range if(speed < 0 || speed > 255){ cerr << "Error: Speed needs to be between 0 to 255." << endl; continue; } // Direction is set based on command/keyword if(command == "fwd" && (!blockedFL || !blockedFR)){ motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CW); motors->setMotorSpeeds(speed, speed); cout << "Rover going forward at speed " << speed << endl; } else if(command == "left" && (!blockedFL || !blockedRL)){ motors->setMotorDirections(GroveMD::DIR_CCW, GroveMD::DIR_CCW); motors->setMotorSpeeds(speed, speed); cout << "Rover turning left at speed " << speed << endl; } else if(command == "right" && (!blockedFR || !blockedRR)){ motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CW); motors->setMotorSpeeds(speed, speed); cout << "Rover turning right at speed " << speed << endl; } else if(command == "rev" && (!blockedRL || !blockedRR)){ motors->setMotorDirections(GroveMD::DIR_CW, GroveMD::DIR_CCW); motors->setMotorSpeeds(speed, speed); cout << "Rover in reverse at speed " << speed << endl; } else{ motors->setMotorSpeeds(0, 0); cout << "Command not supported or direction blocked!" << endl; } } // Wait for threads to join back // If you're not using a component comment out the corresponding join call comp.join(); batt.join(); collision.join(); cout << "Exiting..." << endl; // Clean up and exit delete lcd; delete compass; delete divider; delete motors; return 0; } <|endoftext|>
<commit_before>/******************************************************* * Copyright (c) 2015, Arrayfire * all rights reserved. * * This file is distributed under 3-clause bsd license. * the complete license agreement can be obtained at: * http://Arrayfire.com/licenses/bsd-3-clause ********************************************************/ #include <af/features.h> #include <Array.hpp> #include <cmath> #include <math.hpp> using af::features; namespace cpu { template<typename T> void susan_responses(T* resp_out, const T* in, const unsigned idim0, const unsigned idim1, const int radius, const float t, const float g, const unsigned border_len) { const unsigned r = border_len; const int rSqrd = radius*radius; for (unsigned y = r; y < idim1 - r; ++y) { for (unsigned x = r; x < idim0 - r; ++x) { const unsigned idx = y * idim0 + x; T m_0 = in[idx]; float nM = 0.0f; for (int i=-radius; i<=radius; ++i) { for (int j=-radius; j<=radius; ++j) { if (i*i + j*j < rSqrd) { int p = x + i; int q = y + j; T m = in[p + idim0 * q]; float exp_pow = std::pow((m - m_0)/t, 6.0); float cM = std::exp(-exp_pow); nM += cM; } } } resp_out[idx] = nM < g ? g - nM : T(0); } } } template<typename T> void non_maximal(float* x_out, float* y_out, float* resp_out, unsigned* count, const unsigned idim0, const unsigned idim1, const T* resp_in, const unsigned border_len, const unsigned max_corners) { // Responses on the border don't have 8-neighbors to compare, discard them const unsigned r = border_len + 1; for (unsigned y = r; y < idim1 - r; y++) { for (unsigned x = r; x < idim0 - r; x++) { const T v = resp_in[y * idim0 + x]; // Find maximum neighborhood response T max_v; max_v = max(resp_in[(y-1) * idim0 + x-1], resp_in[y * idim0 + x-1]); max_v = max(max_v, resp_in[(y+1) * idim0 + x-1]); max_v = max(max_v, resp_in[(y-1) * idim0 + x ]); max_v = max(max_v, resp_in[(y+1) * idim0 + x ]); max_v = max(max_v, resp_in[(y-1) * idim0 + x+1]); max_v = max(max_v, resp_in[(y) * idim0 + x+1]); max_v = max(max_v, resp_in[(y+1) * idim0 + x+1]); // Stores corner to {x,y,resp}_out if it's response is maximum compared // to its 8-neighborhood and greater or equal minimum response if (v > max_v) { const unsigned idx = *count; *count += 1; if (idx < max_corners) { x_out[idx] = (float)x; y_out[idx] = (float)y; resp_out[idx] = (float)v; } } } } } template<typename T> unsigned susan(Array<float> &x_out, Array<float> &y_out, Array<float> &resp_out, const Array<T> &in, const unsigned radius, const float diff_thr, const float geom_thr, const float feature_ratio, const unsigned edge) { dim4 idims = in.dims(); const unsigned corner_lim = in.elements() * feature_ratio; float* x_corners = memAlloc<float>(corner_lim); float* y_corners = memAlloc<float>(corner_lim); float* resp_corners = memAlloc<float>(corner_lim); T* resp = memAlloc<T>(in.elements()); unsigned corners_found = 0; susan_responses<T>(resp, in.get(), idims[0], idims[1], radius, diff_thr, geom_thr, edge); non_maximal<T>(x_corners, y_corners, resp_corners, &corners_found, idims[0], idims[1], resp, edge, corner_lim); memFree(resp); const unsigned corners_out = min(corners_found, corner_lim); if (corners_out == 0) { memFree(x_corners); memFree(y_corners); memFree(resp_corners); x_out = createEmptyArray<float>(dim4()); y_out = createEmptyArray<float>(dim4()); resp_out = createEmptyArray<float>(dim4()); return 0; } else { x_out = createDeviceDataArray<float>(dim4(corners_out), (void*)x_corners); y_out = createDeviceDataArray<float>(dim4(corners_out), (void*)y_corners); resp_out = createDeviceDataArray<float>(dim4(corners_out), (void*)resp_corners); return corners_out; } } #define INSTANTIATE(T) \ template unsigned susan<T>(Array<float> &x_out, Array<float> &y_out, Array<float> &score_out, \ const Array<T> &in, const unsigned radius, const float diff_thr, \ const float geom_thr, const float feature_ratio, const unsigned edge); INSTANTIATE(float ) INSTANTIATE(double) INSTANTIATE(char ) INSTANTIATE(int ) INSTANTIATE(uint ) INSTANTIATE(uchar ) INSTANTIATE(short) INSTANTIATE(ushort) } <commit_msg>converted susan fn in cpu backend to asynchronous call<commit_after>/******************************************************* * Copyright (c) 2015, Arrayfire * all rights reserved. * * This file is distributed under 3-clause bsd license. * the complete license agreement can be obtained at: * http://Arrayfire.com/licenses/bsd-3-clause ********************************************************/ #include <af/features.h> #include <Array.hpp> #include <cmath> #include <math.hpp> #include <memory> #include <platform.hpp> #include <async_queue.hpp> using af::features; using std::shared_ptr; namespace cpu { template<typename T> void susan_responses(Array<T> output, const Array<T> input, const unsigned idim0, const unsigned idim1, const int radius, const float t, const float g, const unsigned border_len) { T* resp_out = output.get(); const T* in = input.get(); const unsigned r = border_len; const int rSqrd = radius*radius; for (unsigned y = r; y < idim1 - r; ++y) { for (unsigned x = r; x < idim0 - r; ++x) { const unsigned idx = y * idim0 + x; T m_0 = in[idx]; float nM = 0.0f; for (int i=-radius; i<=radius; ++i) { for (int j=-radius; j<=radius; ++j) { if (i*i + j*j < rSqrd) { int p = x + i; int q = y + j; T m = in[p + idim0 * q]; float exp_pow = std::pow((m - m_0)/t, 6.0); float cM = std::exp(-exp_pow); nM += cM; } } } resp_out[idx] = nM < g ? g - nM : T(0); } } } template<typename T> void non_maximal(Array<float> xcoords, Array<float> ycoords, Array<float> response, shared_ptr<unsigned> counter, const unsigned idim0, const unsigned idim1, const Array<T> input, const unsigned border_len, const unsigned max_corners) { float* x_out = xcoords.get(); float* y_out = ycoords.get(); float* resp_out = response.get(); unsigned* count = counter.get(); const T* resp_in= input.get(); // Responses on the border don't have 8-neighbors to compare, discard them const unsigned r = border_len + 1; for (unsigned y = r; y < idim1 - r; y++) { for (unsigned x = r; x < idim0 - r; x++) { const T v = resp_in[y * idim0 + x]; // Find maximum neighborhood response T max_v; max_v = max(resp_in[(y-1) * idim0 + x-1], resp_in[y * idim0 + x-1]); max_v = max(max_v, resp_in[(y+1) * idim0 + x-1]); max_v = max(max_v, resp_in[(y-1) * idim0 + x ]); max_v = max(max_v, resp_in[(y+1) * idim0 + x ]); max_v = max(max_v, resp_in[(y-1) * idim0 + x+1]); max_v = max(max_v, resp_in[(y) * idim0 + x+1]); max_v = max(max_v, resp_in[(y+1) * idim0 + x+1]); // Stores corner to {x,y,resp}_out if it's response is maximum compared // to its 8-neighborhood and greater or equal minimum response if (v > max_v) { const unsigned idx = *count; *count += 1; if (idx < max_corners) { x_out[idx] = (float)x; y_out[idx] = (float)y; resp_out[idx] = (float)v; } } } } } template<typename T> unsigned susan(Array<float> &x_out, Array<float> &y_out, Array<float> &resp_out, const Array<T> &in, const unsigned radius, const float diff_thr, const float geom_thr, const float feature_ratio, const unsigned edge) { dim4 idims = in.dims(); const unsigned corner_lim = in.elements() * feature_ratio; auto x_corners = createEmptyArray<float>(dim4(corner_lim)); auto y_corners = createEmptyArray<float>(dim4(corner_lim)); auto resp_corners = createEmptyArray<float>(dim4(corner_lim)); auto response = createEmptyArray<T>(dim4(in.elements())); auto corners_found= std::shared_ptr<unsigned>(memAlloc<unsigned>(1), memFree<unsigned>); corners_found.get()[0] = 0; getQueue().enqueue(susan_responses<T>, response, in, idims[0], idims[1], radius, diff_thr, geom_thr, edge); getQueue().enqueue(non_maximal<T>, x_corners, y_corners, resp_corners, corners_found, idims[0], idims[1], response, edge, corner_lim); getQueue().sync(); const unsigned corners_out = min((corners_found.get())[0], corner_lim); if (corners_out == 0) { x_out = createEmptyArray<float>(dim4()); y_out = createEmptyArray<float>(dim4()); resp_out = createEmptyArray<float>(dim4()); return 0; } else { x_out = x_corners; y_out = y_corners; resp_out = resp_corners; x_out.resetDims(dim4(corners_out)); y_out.resetDims(dim4(corners_out)); resp_out.resetDims(dim4(corners_out)); return corners_out; } } #define INSTANTIATE(T) \ template unsigned susan<T>(Array<float> &x_out, Array<float> &y_out, Array<float> &score_out, \ const Array<T> &in, const unsigned radius, const float diff_thr, \ const float geom_thr, const float feature_ratio, const unsigned edge); INSTANTIATE(float ) INSTANTIATE(double) INSTANTIATE(char ) INSTANTIATE(int ) INSTANTIATE(uint ) INSTANTIATE(uchar ) INSTANTIATE(short) INSTANTIATE(ushort) } <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef MNIST_UTILS_HPP #define MNIST_UTILS_HPP #include <cmath> namespace mnist { template<typename Container> void binarize_each(Container& values, double threshold = 30.0){ for(auto& vec : values){ for(auto& v : vec){ v = v > threshold ? 1.0 : 0.0; } } } template<typename Container> double mean(const Container& container){ double mean = 0.0; for(auto& value : container){ mean += value; } return mean / container.size(); } template<typename Container> double stddev(const Container& container, double mean){ double std = 0.0; for(auto& value : container){ std += (value - mean) * (value - mean); } return std::sqrt(std / container.size()); } template<typename Container> void normalize_each(Container& values){ for(auto& vec : values){ //zero-mean auto m = mnist::mean(vec); for(auto& v : vec){ v -= m; } //unit variance auto s = stddev(vec, 0.0); for(auto& v : vec){ v /= s; } } } template<typename Dataset> void binarize_dataset(Dataset& dataset){ binarize_each(dataset.training_images); binarize_each(dataset.test_images); } template<typename Dataset> void normalize_dataset(Dataset& dataset){ normalize_each(dataset.training_images); normalize_each(dataset.test_images); } }; #endif<commit_msg>Be pedantic<commit_after>//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #ifndef MNIST_UTILS_HPP #define MNIST_UTILS_HPP #include <cmath> namespace mnist { template<typename Container> void binarize_each(Container& values, double threshold = 30.0){ for(auto& vec : values){ for(auto& v : vec){ v = v > threshold ? 1.0 : 0.0; } } } template<typename Container> double mean(const Container& container){ double mean = 0.0; for(auto& value : container){ mean += value; } return mean / container.size(); } template<typename Container> double stddev(const Container& container, double mean){ double std = 0.0; for(auto& value : container){ std += (value - mean) * (value - mean); } return std::sqrt(std / container.size()); } template<typename Container> void normalize_each(Container& values){ for(auto& vec : values){ //zero-mean auto m = mnist::mean(vec); for(auto& v : vec){ v -= m; } //unit variance auto s = stddev(vec, 0.0); for(auto& v : vec){ v /= s; } } } template<typename Dataset> void binarize_dataset(Dataset& dataset){ binarize_each(dataset.training_images); binarize_each(dataset.test_images); } template<typename Dataset> void normalize_dataset(Dataset& dataset){ normalize_each(dataset.training_images); normalize_each(dataset.test_images); } } #endif <|endoftext|>
<commit_before>#pragma once /** @file @brief converter between integer and string @author MITSUNARI Shigeo(@herumi) */ #include <memory.h> #include <limits> #include <cybozu/exception.hpp> namespace cybozu { namespace atoi_local { template<typename T, size_t n> T convertToInt(bool *b, const char *p, size_t size, const char (&max)[n], T min, T overflow1, char overflow2) { if (size > 0 && *p) { bool isMinus = false; size_t i = 0; if (*p == '-') { isMinus = true; i++; } if (i < size && p[i]) { // skip leading zero while (i < size && p[i] == '0') i++; // check minimum if (isMinus && size - i >= n - 1 && memcmp(max, &p[i], n - 1) == 0) { if (b) *b = true; return min; } T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return isMinus ? -x : x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToInt") << cybozu::exception::makeString(p, size); } } template<typename T> T convertToUint(bool *b, const char *p, size_t size, T overflow1, char overflow2) { if (size > 0 && *p) { size_t i = 0; // skip leading zero while (i < size && p[i] == '0') i++; T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToUint") << cybozu::exception::makeString(p, size); } } template<typename T> T convertHexToInt(bool *b, const char *p, size_t size) { if (size > 0 && *p) { size_t i = 0; T x = 0; for (;;) { unsigned int c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } if (c - 'A' <= 'F' - 'A') { c = (c - 'A') + 10; } else if (c - 'a' <= 'f' - 'a') { c = (c - 'a') + 10; } else if (c - '0' <= '9' - '0') { c = c - '0'; } else { break; } // avoid overflow if (x > (std::numeric_limits<T>::max)() / 16) break; x = x * 16 + T(c); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertHexToInt") << cybozu::exception::makeString(p, size); } } } // atoi_local /** auto detect return value class @note if you set bool pointer p then throw nothing and set *p = false if bad string */ class atoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: atoi(const char *p, size_t size = -1) { set(0, p, size); } atoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } atoi(const std::string& str) { set(0, str.c_str(), str.size()); } atoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } inline operator signed char() const { return atoi_local::convertToInt<signed char>(b_, p_, size_, "128", -128, 12, '8'); } inline operator unsigned char() const { return atoi_local::convertToUint<unsigned char>(b_, p_, size_, 25, '6'); } inline operator short() const { return atoi_local::convertToInt<short>(b_, p_, size_, "32768", -32768, 3276, '8'); } inline operator unsigned short() const { return atoi_local::convertToUint<unsigned short>(b_, p_, size_, 6553, '6'); } inline operator int() const { return atoi_local::convertToInt<int>(b_, p_, size_, "2147483648", /*INT_MIN*/-2147483648, 214748364, '8'); } inline operator unsigned int() const { return atoi_local::convertToUint<unsigned int>(b_, p_, size_, 429496729, '6'); } inline operator long long() const { return atoi_local::convertToInt<long long>(b_, p_, size_, "9223372036854775808", CYBOZU_LLONG_MIN, 922337203685477580LL, '8'); } inline operator unsigned long long() const { return atoi_local::convertToUint<unsigned long long>(b_, p_, size_, 1844674407370955161ULL, '6'); } #if defined(__SIZEOF_LONG__) && (__SIZEOF_LONG__ == 8) inline operator long() const { return static_cast<long>(static_cast<long long>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned long long>(*this)); } #else inline operator long() const { return static_cast<long>(static_cast<int>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned int>(*this)); } #endif }; class hextoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: hextoi(const char *p, size_t size = -1) { set(0, p, size); } hextoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } hextoi(const std::string& str) { set(0, str.c_str(), str.size()); } hextoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } operator unsigned char() const { return atoi_local::convertHexToInt<unsigned char>(b_, p_, size_); } operator unsigned short() const { return atoi_local::convertHexToInt<unsigned short>(b_, p_, size_); } operator unsigned int() const { return atoi_local::convertHexToInt<unsigned int>(b_, p_, size_); } operator unsigned long() const { return atoi_local::convertHexToInt<unsigned long>(b_, p_, size_); } operator unsigned long long() const { return atoi_local::convertHexToInt<unsigned long long>(b_, p_, size_); } operator char() const { return atoi_local::convertHexToInt<char>(b_, p_, size_); } operator signed char() const { return atoi_local::convertHexToInt<signed char>(b_, p_, size_); } operator short() const { return atoi_local::convertHexToInt<short>(b_, p_, size_); } operator int() const { return atoi_local::convertHexToInt<int>(b_, p_, size_); } operator long() const { return atoi_local::convertHexToInt<long>(b_, p_, size_); } operator long long() const { return atoi_local::convertHexToInt<long long>(b_, p_, size_); } }; } // cybozu <commit_msg>avoid warning for vc<commit_after>#pragma once /** @file @brief converter between integer and string @author MITSUNARI Shigeo(@herumi) */ #include <memory.h> #include <limits> #include <cybozu/exception.hpp> namespace cybozu { namespace atoi_local { template<typename T, size_t n> T convertToInt(bool *b, const char *p, size_t size, const char (&max)[n], T min, T overflow1, char overflow2) { if (size > 0 && *p) { bool isMinus = false; size_t i = 0; if (*p == '-') { isMinus = true; i++; } if (i < size && p[i]) { // skip leading zero while (i < size && p[i] == '0') i++; // check minimum if (isMinus && size - i >= n - 1 && memcmp(max, &p[i], n - 1) == 0) { if (b) *b = true; return min; } T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return isMinus ? -x : x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToInt") << cybozu::exception::makeString(p, size); } } template<typename T> T convertToUint(bool *b, const char *p, size_t size, T overflow1, char overflow2) { if (size > 0 && *p) { size_t i = 0; // skip leading zero while (i < size && p[i] == '0') i++; T x = 0; for (;;) { unsigned char c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } unsigned int y = c - '0'; if (y > 9 || x > overflow1 || (x == overflow1 && c >= overflow2)) { break; } x = x * 10 + T(y); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertToUint") << cybozu::exception::makeString(p, size); } } template<typename T> T convertHexToInt(bool *b, const char *p, size_t size) { if (size > 0 && *p) { size_t i = 0; T x = 0; for (;;) { unsigned int c; if (i == size || (c = static_cast<unsigned char>(p[i])) == '\0') { if (b) *b = true; return x; } if (c - 'A' <= 'F' - 'A') { c = (c - 'A') + 10; } else if (c - 'a' <= 'f' - 'a') { c = (c - 'a') + 10; } else if (c - '0' <= '9' - '0') { c = c - '0'; } else { break; } // avoid overflow if (x > (std::numeric_limits<T>::max)() / 16) break; x = x * 16 + T(c); i++; } } if (b) { *b = false; return 0; } else { throw cybozu::Exception("atoi::convertHexToInt") << cybozu::exception::makeString(p, size); } } } // atoi_local /** auto detect return value class @note if you set bool pointer p then throw nothing and set *p = false if bad string */ class atoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: atoi(const char *p, size_t size = -1) { set(0, p, size); } atoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } atoi(const std::string& str) { set(0, str.c_str(), str.size()); } atoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } inline operator signed char() const { return atoi_local::convertToInt<signed char>(b_, p_, size_, "128", -128, 12, '8'); } inline operator unsigned char() const { return atoi_local::convertToUint<unsigned char>(b_, p_, size_, 25, '6'); } inline operator short() const { return atoi_local::convertToInt<short>(b_, p_, size_, "32768", -32768, 3276, '8'); } inline operator unsigned short() const { return atoi_local::convertToUint<unsigned short>(b_, p_, size_, 6553, '6'); } inline operator int() const { return atoi_local::convertToInt<int>(b_, p_, size_, "2147483648", (std::numeric_limits<int>::min)() /* -2147483648 */, 214748364, '8'); } inline operator unsigned int() const { return atoi_local::convertToUint<unsigned int>(b_, p_, size_, 429496729, '6'); } inline operator long long() const { return atoi_local::convertToInt<long long>(b_, p_, size_, "9223372036854775808", CYBOZU_LLONG_MIN, 922337203685477580LL, '8'); } inline operator unsigned long long() const { return atoi_local::convertToUint<unsigned long long>(b_, p_, size_, 1844674407370955161ULL, '6'); } #if defined(__SIZEOF_LONG__) && (__SIZEOF_LONG__ == 8) inline operator long() const { return static_cast<long>(static_cast<long long>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned long long>(*this)); } #else inline operator long() const { return static_cast<long>(static_cast<int>(*this)); } inline operator unsigned long() const { return static_cast<unsigned long>(static_cast<unsigned int>(*this)); } #endif }; class hextoi { const char *p_; size_t size_; bool *b_; void set(bool *b, const char *p, size_t size) { b_ = b; p_ = p; size_ = size; } public: hextoi(const char *p, size_t size = -1) { set(0, p, size); } hextoi(bool *b, const char *p, size_t size = -1) { set(b, p, size); } hextoi(const std::string& str) { set(0, str.c_str(), str.size()); } hextoi(bool *b, const std::string& str) { set(b, str.c_str(), str.size()); } operator unsigned char() const { return atoi_local::convertHexToInt<unsigned char>(b_, p_, size_); } operator unsigned short() const { return atoi_local::convertHexToInt<unsigned short>(b_, p_, size_); } operator unsigned int() const { return atoi_local::convertHexToInt<unsigned int>(b_, p_, size_); } operator unsigned long() const { return atoi_local::convertHexToInt<unsigned long>(b_, p_, size_); } operator unsigned long long() const { return atoi_local::convertHexToInt<unsigned long long>(b_, p_, size_); } operator char() const { return atoi_local::convertHexToInt<char>(b_, p_, size_); } operator signed char() const { return atoi_local::convertHexToInt<signed char>(b_, p_, size_); } operator short() const { return atoi_local::convertHexToInt<short>(b_, p_, size_); } operator int() const { return atoi_local::convertHexToInt<int>(b_, p_, size_); } operator long() const { return atoi_local::convertHexToInt<long>(b_, p_, size_); } operator long long() const { return atoi_local::convertHexToInt<long long>(b_, p_, size_); } }; } // cybozu <|endoftext|>
<commit_before>/* * Copyright 2014-2019, CNRS * Copyright 2018-2020, INRIA */ #ifndef __eigenpy_map_hpp__ #define __eigenpy_map_hpp__ #include "eigenpy/fwd.hpp" #include "eigenpy/exception.hpp" #include "eigenpy/stride.hpp" namespace eigenpy { template<typename MatType, typename InputScalar, typename Stride, bool IsVector = MatType::IsVectorAtCompileTime> struct MapNumpyTraits {}; /* Wrap a numpy::array with an Eigen::Map. No memory copy. */ template<typename MatType, typename InputScalar, typename Stride = typename StrideType<MatType>::type> struct MapNumpy { typedef MapNumpyTraits<MatType, InputScalar, Stride> Impl; typedef typename Impl::EigenMap EigenMap; static EigenMap map(PyArrayObject* pyArray); }; } // namespace eigenpy /* --- DETAILS ------------------------------------------------------------------ */ /* --- DETAILS ------------------------------------------------------------------ */ /* --- DETAILS ------------------------------------------------------------------ */ namespace eigenpy { template<typename MatType, typename InputScalar, typename Stride> struct MapNumpyTraits<MatType,InputScalar,Stride,false> { typedef Eigen::Matrix<InputScalar,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime,MatType::Options> EquivalentInputMatrixType; typedef Eigen::Map<EquivalentInputMatrixType,EIGENPY_DEFAULT_ALIGNMENT_VALUE,Stride> EigenMap; static EigenMap mapImpl(PyArrayObject* pyArray) { enum { OuterStrideAtCompileTime = Stride::OuterStrideAtCompileTime, InnerStrideAtCompileTime = Stride::InnerStrideAtCompileTime, }; assert(PyArray_NDIM(pyArray) == 2 || PyArray_NDIM(pyArray) == 1); const long int itemsize = PyArray_ITEMSIZE(pyArray); int inner_stride = -1, outer_stride = -1; int rows = -1, cols = -1; if(PyArray_NDIM(pyArray) == 2) { assert( (PyArray_DIMS(pyArray)[0] < INT_MAX) && (PyArray_DIMS(pyArray)[1] < INT_MAX) && (PyArray_STRIDE(pyArray,0) < INT_MAX) && (PyArray_STRIDE(pyArray,1) < INT_MAX) ); rows = (int)PyArray_DIMS(pyArray)[0]; cols = (int)PyArray_DIMS(pyArray)[1]; if(EquivalentInputMatrixType::IsRowMajor) { inner_stride = (int)PyArray_STRIDE(pyArray, 1) / (int)itemsize; outer_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; } else { inner_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; outer_stride = (int)PyArray_STRIDE(pyArray, 1) / (int)itemsize; } } else if(PyArray_NDIM(pyArray) == 1) { assert( (PyArray_DIMS(pyArray)[0] < INT_MAX) && (PyArray_STRIDE(pyArray,0) < INT_MAX)); rows = (int)PyArray_DIMS(pyArray)[0]; cols = 1; inner_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; outer_stride = 0; } // Specific care for Eigen::Stride<-1,0> if(InnerStrideAtCompileTime==0 && OuterStrideAtCompileTime==Eigen::Dynamic) { outer_stride = std::max(inner_stride,outer_stride); inner_stride = 0; } Stride stride(OuterStrideAtCompileTime==Eigen::Dynamic?outer_stride:OuterStrideAtCompileTime, InnerStrideAtCompileTime==Eigen::Dynamic?inner_stride:InnerStrideAtCompileTime); if( (MatType::RowsAtCompileTime != rows) && (MatType::RowsAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of rows does not fit with the matrix type."); } if( (MatType::ColsAtCompileTime != cols) && (MatType::ColsAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of columns does not fit with the matrix type."); } InputScalar* pyData = reinterpret_cast<InputScalar*>(PyArray_DATA(pyArray)); return EigenMap(pyData, rows, cols, stride); } }; template<typename MatType, typename InputScalar, typename Stride> struct MapNumpyTraits<MatType,InputScalar,Stride,true> { typedef Eigen::Matrix<InputScalar,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime,MatType::Options> EquivalentInputMatrixType; typedef Eigen::Map<EquivalentInputMatrixType,EIGENPY_DEFAULT_ALIGNMENT_VALUE,Stride> EigenMap; static EigenMap mapImpl(PyArrayObject* pyArray) { assert( PyArray_NDIM(pyArray) <= 2 ); int rowMajor; if( PyArray_NDIM(pyArray)==1 ) rowMajor = 0; else if (PyArray_DIMS(pyArray)[0] == 0) rowMajor = 0; // handle zero-size vector else if (PyArray_DIMS(pyArray)[1] == 0) rowMajor = 1; // handle zero-size vector else rowMajor = (PyArray_DIMS(pyArray)[0]>PyArray_DIMS(pyArray)[1])?0:1; assert( (PyArray_DIMS(pyArray)[rowMajor]< INT_MAX) && (PyArray_STRIDE(pyArray, rowMajor) )); const int R = (int)PyArray_DIMS(pyArray)[rowMajor]; const long int itemsize = PyArray_ITEMSIZE(pyArray); const int stride = (int) PyArray_STRIDE(pyArray, rowMajor) / (int) itemsize;; if( (MatType::MaxSizeAtCompileTime != R) && (MatType::MaxSizeAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of elements does not fit with the vector type."); } InputScalar* pyData = reinterpret_cast<InputScalar*>(PyArray_DATA(pyArray)); return EigenMap( pyData, R, Stride(stride) ); } }; template<typename MatType, typename InputScalar, typename Stride> typename MapNumpy<MatType,InputScalar,Stride>::EigenMap MapNumpy<MatType,InputScalar,Stride>::map(PyArrayObject * pyArray) { return Impl::mapImpl(pyArray); } } // namespace eigenpy #endif // define __eigenpy_map_hpp__ <commit_msg>core: add template AlignmentValue to MapNumpy<commit_after>/* * Copyright 2014-2019, CNRS * Copyright 2018-2020, INRIA */ #ifndef __eigenpy_map_hpp__ #define __eigenpy_map_hpp__ #include "eigenpy/fwd.hpp" #include "eigenpy/exception.hpp" #include "eigenpy/stride.hpp" namespace eigenpy { template<typename MatType, typename InputScalar, int AlignmentValue, typename Stride, bool IsVector = MatType::IsVectorAtCompileTime> struct MapNumpyTraits {}; /* Wrap a numpy::array with an Eigen::Map. No memory copy. */ template<typename MatType, typename InputScalar, int AlignmentValue = EIGENPY_NO_ALIGNMENT_VALUE, typename Stride = typename StrideType<MatType>::type> struct MapNumpy { typedef MapNumpyTraits<MatType, InputScalar, AlignmentValue, Stride> Impl; typedef typename Impl::EigenMap EigenMap; static EigenMap map(PyArrayObject* pyArray); }; } // namespace eigenpy /* --- DETAILS ------------------------------------------------------------------ */ /* --- DETAILS ------------------------------------------------------------------ */ /* --- DETAILS ------------------------------------------------------------------ */ namespace eigenpy { template<typename MatType, typename InputScalar, int AlignmentValue, typename Stride> struct MapNumpyTraits<MatType,InputScalar,AlignmentValue,Stride,false> { typedef Eigen::Matrix<InputScalar,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime,MatType::Options> EquivalentInputMatrixType; typedef Eigen::Map<EquivalentInputMatrixType,AlignmentValue,Stride> EigenMap; static EigenMap mapImpl(PyArrayObject* pyArray) { enum { OuterStrideAtCompileTime = Stride::OuterStrideAtCompileTime, InnerStrideAtCompileTime = Stride::InnerStrideAtCompileTime, }; assert(PyArray_NDIM(pyArray) == 2 || PyArray_NDIM(pyArray) == 1); const long int itemsize = PyArray_ITEMSIZE(pyArray); int inner_stride = -1, outer_stride = -1; int rows = -1, cols = -1; if(PyArray_NDIM(pyArray) == 2) { assert( (PyArray_DIMS(pyArray)[0] < INT_MAX) && (PyArray_DIMS(pyArray)[1] < INT_MAX) && (PyArray_STRIDE(pyArray,0) < INT_MAX) && (PyArray_STRIDE(pyArray,1) < INT_MAX) ); rows = (int)PyArray_DIMS(pyArray)[0]; cols = (int)PyArray_DIMS(pyArray)[1]; if(EquivalentInputMatrixType::IsRowMajor) { inner_stride = (int)PyArray_STRIDE(pyArray, 1) / (int)itemsize; outer_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; } else { inner_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; outer_stride = (int)PyArray_STRIDE(pyArray, 1) / (int)itemsize; } } else if(PyArray_NDIM(pyArray) == 1) { assert( (PyArray_DIMS(pyArray)[0] < INT_MAX) && (PyArray_STRIDE(pyArray,0) < INT_MAX)); rows = (int)PyArray_DIMS(pyArray)[0]; cols = 1; inner_stride = (int)PyArray_STRIDE(pyArray, 0) / (int)itemsize; outer_stride = 0; } // Specific care for Eigen::Stride<-1,0> if(InnerStrideAtCompileTime==0 && OuterStrideAtCompileTime==Eigen::Dynamic) { outer_stride = std::max(inner_stride,outer_stride); inner_stride = 0; } Stride stride(OuterStrideAtCompileTime==Eigen::Dynamic?outer_stride:OuterStrideAtCompileTime, InnerStrideAtCompileTime==Eigen::Dynamic?inner_stride:InnerStrideAtCompileTime); if( (MatType::RowsAtCompileTime != rows) && (MatType::RowsAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of rows does not fit with the matrix type."); } if( (MatType::ColsAtCompileTime != cols) && (MatType::ColsAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of columns does not fit with the matrix type."); } InputScalar* pyData = reinterpret_cast<InputScalar*>(PyArray_DATA(pyArray)); std::cout << "OuterStrideAtCompileTime: " << OuterStrideAtCompileTime << std::endl; std::cout << "InnerStrideAtCompileTime: " << InnerStrideAtCompileTime << std::endl; std::cout << "rows: " << rows << std::endl; std::cout << "cols: " << cols << std::endl; std::cout << "inner_stride: " << inner_stride << std::endl; std::cout << "outer_stride: " << outer_stride << std::endl; return EigenMap(pyData, rows, cols, stride); } }; template<typename MatType, typename InputScalar, int AlignmentValue, typename Stride> struct MapNumpyTraits<MatType,InputScalar,AlignmentValue,Stride,true> { typedef Eigen::Matrix<InputScalar,MatType::RowsAtCompileTime,MatType::ColsAtCompileTime,MatType::Options> EquivalentInputMatrixType; typedef Eigen::Map<EquivalentInputMatrixType,AlignmentValue,Stride> EigenMap; static EigenMap mapImpl(PyArrayObject* pyArray) { assert( PyArray_NDIM(pyArray) <= 2 ); int rowMajor; if( PyArray_NDIM(pyArray)==1 ) rowMajor = 0; else if (PyArray_DIMS(pyArray)[0] == 0) rowMajor = 0; // handle zero-size vector else if (PyArray_DIMS(pyArray)[1] == 0) rowMajor = 1; // handle zero-size vector else rowMajor = (PyArray_DIMS(pyArray)[0]>PyArray_DIMS(pyArray)[1])?0:1; assert( (PyArray_DIMS(pyArray)[rowMajor]< INT_MAX) && (PyArray_STRIDE(pyArray, rowMajor) )); const int R = (int)PyArray_DIMS(pyArray)[rowMajor]; const long int itemsize = PyArray_ITEMSIZE(pyArray); const int stride = (int) PyArray_STRIDE(pyArray, rowMajor) / (int) itemsize;; if( (MatType::MaxSizeAtCompileTime != R) && (MatType::MaxSizeAtCompileTime != Eigen::Dynamic) ) { throw eigenpy::Exception("The number of elements does not fit with the vector type."); } InputScalar* pyData = reinterpret_cast<InputScalar*>(PyArray_DATA(pyArray)); return EigenMap( pyData, R, Stride(stride) ); } }; template<typename MatType, typename InputScalar, int AlignmentValue, typename Stride> typename MapNumpy<MatType,InputScalar,AlignmentValue,Stride>::EigenMap MapNumpy<MatType,InputScalar,AlignmentValue,Stride>::map(PyArrayObject * pyArray) { return Impl::mapImpl(pyArray); } } // namespace eigenpy #endif // define __eigenpy_map_hpp__ <|endoftext|>
<commit_before>#ifndef BROADCAST_HPP #define BROADCAST_HPP #include <utility> #include <tuple> #include <type_traits> #include <stdexcept> #include <iterator> #include <array> #include <algorithm> #include "xindex.hpp" #include "utils.hpp" namespace qs { /************************* * Broadcast functions *************************/ template <class S, size_t N> S broadcast_dim(std::array<S, N>& dim_list); template <class S> bool broadcast_shape(const xshape<S>& input, xshape<S>& output); template <class S> bool check_trivial_broadcast(const xstrides<S>& strides1, const xstrides<S>& strides2); /*************************** * xstepper ***************************/ namespace detail { template <class C> struct get_storage_iterator_impl { using type = typename C::storage_iterator; }; template <class C> struct get_storage_iterator_impl<const C> { using type = typename C::const_storage_iterator; }; } template <class C> using get_storage_iterator = typename detail::get_storage_iterator_impl<C>::type; template <class C> class xstepper { public: using container_type = C; using subiterator_type = get_storage_iterator<C>; using value_type = typename subiterator_type::value_type; using reference = typename subiterator_type::reference; using pointer = typename subiterator_type::pointer; using difference_type = typename subiterator_type::difference_type; using size_type = typename container_type::size_type; xstepper(container_type* c, subiterator_type it, size_type offset); reference operator*() const; void step(size_type i); void reset(size_type i); void to_end(); bool equal(const xstepper& rhs) const; private: container_type* p_c; subiterator_type m_it; size_type m_offset; }; template <class C> bool operator==(const xstepper<C>& lhs, const xstepper<C>& rhs); template <class C> bool operator!=(const xstepper<C>& lhs, const xstepper<C>& rhs); /********************** * xiterator **********************/ template <class It> class xiterator { public: using self_type = xiterator<It>; using subiterator_type = It; using value_type = typename subiterator_type::value_type; using reference = typename subiterator_type::reference; using pointer = typename subiterator_type::pointer; using difference_type = typename subiterator_type::difference_type; using size_type = typename subiterator_type::size_type; using iterator_category = std::input_iterator_tag; using shape_type = xshape<size_type>; xiterator(It it, const shape_type& shape); self_type& operator++(); self_type operator++(int); reference operator*() const; bool equal(const xiterator& rhs) const; private: subiterator_type m_it; shape_type m_shape; shape_type m_index; }; template <class It> bool operator==(const xiterator<It>& lhs, const xiterator<It>& rhs); template <class It> bool operator!=(const xiterator<It>& lhs, const xiterator<It>& rhs); /**************************************** * Broadcast functions implementation ****************************************/ template <class S, size_t N> inline S broadcast_dim(const std::array<S, N>& dim_list) { S ndim = std::accumulate(dim_list.begin(), dim_list.end(), S(0), [](S res, const S& dim) { return std::max(dim, res); }); return ndim; } template <class S> inline bool broadcast_shape(const xshape<S>& input, xshape<S>& output) { size_t size = output.size(); bool trivial_broadcast = (input.size() == output.size()); auto output_iter = output.rbegin(); auto input_rend = input.rend(); for(auto input_iter = input.rbegin(); input_iter != input_rend; ++input_iter, ++output_iter) { if(*output_iter == 1) { *output_iter = *input_iter; } else if((*input_iter != 1) && (*output_iter != *input_iter)) { throw std::runtime_error("broadcast error : incompatible dimension of arrays"); } trivial_broadcast = trivial_broadcast && (*output_iter == *input_iter); } return trivial_broadcast; } template <class S> inline bool check_trivial_broadcast(const xstrides<S>& strides1, const xstrides<S>& strides2) { return strides1 == strides2; } /***************************** * xstepper implementation *****************************/ template <class C> inline xstepper<C>::xstepper(container_type* c, subiterator_type it, size_type offset) : p_c(c), m_it(it), m_offset(offset) { } template <class C> inline auto xstepper<C>::operator*() const -> reference { return *m_it; } template <class C> inline void xstepper<C>::step(size_type dim) { if(dim >= m_offset) m_it += p_c->strides()[dim - m_offset]; } template <class C> inline void xstepper<C>::reset(size_type dim) { if(dim >= m_offset) m_it -= p_c->backstrides()[dim - m_offset]; } template <class C> inline void xstepper<C>::to_end() { m_it = p_c->storage_end(); } template <class C> inline bool xstepper<C>::equal(const xstepper& rhs) const { return p_c == rhs.p_c && m_it == rhs.m_it; } template <class C> inline bool operator==(const xstepper<C>& lhs, const xstepper<C>& rhs) { return lhs.equal(rhs); } template <class C> inline bool operator!=(const xstepper<C>& lhs, const xstepper<C>& rhs) { return !(lhs.equal(rhs)); } /************************************* * xiterator implementation *************************************/ template <class It> inline xiterator<It>::xiterator(It it, const shape_type& shape) : m_it(it), m_shape(shape), m_index(shape.size(), size_type(0)) { } template <class It> inline auto xiterator<It>::operator++() -> self_type& { for(size_type j = m_index.size(); j != 0; --j) { size_type i = j-1; if(++m_index[i] != m_shape[i]) { m_it.step(i); break; } else if (i == 0) { m_it.to_end(); } else { m_index[i] = 0; m_it.reset(i); } } } template <class It> inline auto xiterator<It>::operator++(int) -> self_type { self_type tmp(*this); ++(*this); return tmp; } template <class It> inline auto xiterator<It>::operator*() const -> reference { return *m_it; } template <class It> inline bool xiterator<It>::equal(const xiterator& rhs) const { return m_it == rhs.m_it && m_shape == rhs.m_shape; } template <class It> inline bool operator==(const xiterator<It>& lhs, const xiterator<It>& rhs) { return lhs.equal(rhs); } template <class It> inline bool operator!=(const xiterator<It>& lhs, const xiterator<It>& rhs) { return !(lhs.equal(rhs)); } } #endif <commit_msg>useless functions removed<commit_after>#ifndef BROADCAST_HPP #define BROADCAST_HPP #include <utility> #include <tuple> #include <type_traits> #include <stdexcept> #include <iterator> #include <array> #include <algorithm> #include "xindex.hpp" #include "utils.hpp" namespace qs { /************************* * Broadcast functions *************************/ template <class S> bool broadcast_shape(const xshape<S>& input, xshape<S>& output); /*************************** * xstepper ***************************/ namespace detail { template <class C> struct get_storage_iterator_impl { using type = typename C::storage_iterator; }; template <class C> struct get_storage_iterator_impl<const C> { using type = typename C::const_storage_iterator; }; } template <class C> using get_storage_iterator = typename detail::get_storage_iterator_impl<C>::type; template <class C> class xstepper { public: using container_type = C; using subiterator_type = get_storage_iterator<C>; using value_type = typename subiterator_type::value_type; using reference = typename subiterator_type::reference; using pointer = typename subiterator_type::pointer; using difference_type = typename subiterator_type::difference_type; using size_type = typename container_type::size_type; xstepper(container_type* c, subiterator_type it, size_type offset); reference operator*() const; void step(size_type i); void reset(size_type i); void to_end(); bool equal(const xstepper& rhs) const; private: container_type* p_c; subiterator_type m_it; size_type m_offset; }; template <class C> bool operator==(const xstepper<C>& lhs, const xstepper<C>& rhs); template <class C> bool operator!=(const xstepper<C>& lhs, const xstepper<C>& rhs); /********************** * xiterator **********************/ template <class It> class xiterator { public: using self_type = xiterator<It>; using subiterator_type = It; using value_type = typename subiterator_type::value_type; using reference = typename subiterator_type::reference; using pointer = typename subiterator_type::pointer; using difference_type = typename subiterator_type::difference_type; using size_type = typename subiterator_type::size_type; using iterator_category = std::input_iterator_tag; using shape_type = xshape<size_type>; xiterator(It it, const shape_type& shape); self_type& operator++(); self_type operator++(int); reference operator*() const; bool equal(const xiterator& rhs) const; private: subiterator_type m_it; shape_type m_shape; shape_type m_index; }; template <class It> bool operator==(const xiterator<It>& lhs, const xiterator<It>& rhs); template <class It> bool operator!=(const xiterator<It>& lhs, const xiterator<It>& rhs); /**************************************** * Broadcast functions implementation ****************************************/ template <class S> inline bool broadcast_shape(const xshape<S>& input, xshape<S>& output) { size_t size = output.size(); bool trivial_broadcast = (input.size() == output.size()); auto output_iter = output.rbegin(); auto input_rend = input.rend(); for(auto input_iter = input.rbegin(); input_iter != input_rend; ++input_iter, ++output_iter) { if(*output_iter == 1) { *output_iter = *input_iter; } else if((*input_iter != 1) && (*output_iter != *input_iter)) { throw std::runtime_error("broadcast error : incompatible dimension of arrays"); } trivial_broadcast = trivial_broadcast && (*output_iter == *input_iter); } return trivial_broadcast; } /***************************** * xstepper implementation *****************************/ template <class C> inline xstepper<C>::xstepper(container_type* c, subiterator_type it, size_type offset) : p_c(c), m_it(it), m_offset(offset) { } template <class C> inline auto xstepper<C>::operator*() const -> reference { return *m_it; } template <class C> inline void xstepper<C>::step(size_type dim) { if(dim >= m_offset) m_it += p_c->strides()[dim - m_offset]; } template <class C> inline void xstepper<C>::reset(size_type dim) { if(dim >= m_offset) m_it -= p_c->backstrides()[dim - m_offset]; } template <class C> inline void xstepper<C>::to_end() { m_it = p_c->storage_end(); } template <class C> inline bool xstepper<C>::equal(const xstepper& rhs) const { return p_c == rhs.p_c && m_it == rhs.m_it; } template <class C> inline bool operator==(const xstepper<C>& lhs, const xstepper<C>& rhs) { return lhs.equal(rhs); } template <class C> inline bool operator!=(const xstepper<C>& lhs, const xstepper<C>& rhs) { return !(lhs.equal(rhs)); } /************************************* * xiterator implementation *************************************/ template <class It> inline xiterator<It>::xiterator(It it, const shape_type& shape) : m_it(it), m_shape(shape), m_index(shape.size(), size_type(0)) { } template <class It> inline auto xiterator<It>::operator++() -> self_type& { for(size_type j = m_index.size(); j != 0; --j) { size_type i = j-1; if(++m_index[i] != m_shape[i]) { m_it.step(i); break; } else if (i == 0) { m_it.to_end(); } else { m_index[i] = 0; m_it.reset(i); } } } template <class It> inline auto xiterator<It>::operator++(int) -> self_type { self_type tmp(*this); ++(*this); return tmp; } template <class It> inline auto xiterator<It>::operator*() const -> reference { return *m_it; } template <class It> inline bool xiterator<It>::equal(const xiterator& rhs) const { return m_it == rhs.m_it && m_shape == rhs.m_shape; } template <class It> inline bool operator==(const xiterator<It>& lhs, const xiterator<It>& rhs) { return lhs.equal(rhs); } template <class It> inline bool operator!=(const xiterator<It>& lhs, const xiterator<It>& rhs) { return !(lhs.equal(rhs)); } } #endif <|endoftext|>
<commit_before>/* * Copyright 2019 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clustertest.h" #include "bucket.h" #include "cluster.h" #include <protocol/connection/client_connection.h> #include <protocol/connection/client_mcbp_commands.h> #include <protocol/connection/frameinfo.h> #include <condition_variable> #include <cstdlib> #include <string> /** * Get a frame info vector with a durability entry with Majority */ static FrameInfoVector GetMajorityDurabilityFrameInfoVector() { FrameInfoVector ret; ret.emplace_back(std::make_unique<DurabilityFrameInfo>( cb::durability::Level::Majority)); return ret; } class DurabilityTest : public cb::test::ClusterTest { protected: static void mutate(MemcachedConnection& conn, std::string id, MutationType type) { MutationInfo old{}; if (type != MutationType::Add) { old = conn.store(id, Vbid{0}, "", cb::mcbp::Datatype::Raw); } Document doc{}; doc.value = "body"; doc.info.id = std::move(id); doc.info.datatype = cb::mcbp::Datatype::Raw; const auto info = conn.mutate( doc, Vbid{0}, type, GetMajorityDurabilityFrameInfoVector); EXPECT_NE(0, info.cas); EXPECT_NE(old.cas, info.cas); } static void subdoc(MemcachedConnection& conn, std::string id, cb::mcbp::ClientOpcode opcode) { BinprotSubdocCommand cmd(opcode); cmd.setKey(std::move(id)); cmd.setPath("foo"); if (opcode != cb::mcbp::ClientOpcode::SubdocDelete) { cmd.setValue("1"); if (opcode == cb::mcbp::ClientOpcode::SubdocArrayInsert) { cmd.setPath("foo.[0]"); } else if (opcode != cb::mcbp::ClientOpcode::SubdocReplace) { cmd.addPathFlags(SUBDOC_FLAG_MKDIR_P); cmd.addDocFlags(mcbp::subdoc::doc_flag::Mkdoc); } } cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = conn.execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(0, rsp.getCas()); } static std::unique_ptr<MemcachedConnection> getConnection() { auto bucket = cluster->getBucket("default"); auto conn = bucket->getConnection(Vbid(0)); conn->authenticate("@admin", "password", "PLAIN"); conn->selectBucket(bucket->getName()); return conn; } }; TEST_F(DurabilityTest, Set) { mutate(*getConnection(), "Set", MutationType::Set); } TEST_F(DurabilityTest, Add) { mutate(*getConnection(), "Add", MutationType::Add); } TEST_F(DurabilityTest, Replace) { mutate(*getConnection(), "Replace", MutationType::Replace); } TEST_F(DurabilityTest, Append) { mutate(*getConnection(), "Append", MutationType::Append); } TEST_F(DurabilityTest, Prepend) { mutate(*getConnection(), "Prepend", MutationType::Prepend); } TEST_F(DurabilityTest, Delete) { auto conn = getConnection(); const auto old = conn->store("Delete", Vbid{0}, "", cb::mcbp::Datatype::Raw); auto info = getConnection()->remove( "Delete", Vbid{0}, 0, GetMajorityDurabilityFrameInfoVector); EXPECT_NE(0, info.cas); EXPECT_NE(old.cas, info.cas); } TEST_F(DurabilityTest, Increment) { auto conn = getConnection(); for (uint64_t ii = 0; ii < 10ULL; ++ii) EXPECT_EQ(ii, conn->increment("Increment", 1, 0, 0, nullptr, GetMajorityDurabilityFrameInfoVector)); } TEST_F(DurabilityTest, Decrement) { auto conn = getConnection(); for (uint64_t ii = 10; ii > 0ULL; --ii) EXPECT_EQ(ii, conn->decrement("Decrement", 1, 10, 0, nullptr, GetMajorityDurabilityFrameInfoVector)); } // MB-35548 blocks this TEST_F(DurabilityTest, DISABLED_Touch) { auto conn = getConnection(); const auto info = conn->store("Touch", Vbid{0}, "", cb::mcbp::Datatype::Raw); BinprotTouchCommand cmd; cmd.setKey("Touch"); cmd.setExpirytime(0x32); cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = conn->execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(info.cas, rsp.getCas()); EXPECT_NE(0, rsp.getCas()); } // MB-35548 blocks this TEST_F(DurabilityTest, DISABLED_Gat) { auto conn = getConnection(); const auto info = conn->store("GetAndTouch", Vbid{0}, "foo", cb::mcbp::Datatype::Raw); BinprotGetAndTouchCommand cmd; cmd.setKey("GetAndTouch"); cmd.setExpirytime(0x32); cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = conn->execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(info.cas, rsp.getCas()); EXPECT_NE(0, rsp.getCas()); EXPECT_EQ("foo", rsp.getDataString()); } TEST_F(DurabilityTest, SubdocDictAdd) { subdoc(*getConnection(), "SubdocDictAdd", cb::mcbp::ClientOpcode::SubdocDictAdd); } TEST_F(DurabilityTest, SubdocDictUpsert) { subdoc(*getConnection(), "SubdocDictUpsert", cb::mcbp::ClientOpcode::SubdocDictUpsert); } TEST_F(DurabilityTest, SubdocDelete) { auto conn = getConnection(); conn->store("SubdocDelete", Vbid{0}, R"({"foo":"bar"})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocDelete", cb::mcbp::ClientOpcode::SubdocDelete); } TEST_F(DurabilityTest, SubdocReplace) { auto conn = getConnection(); conn->store("SubdocReplace", Vbid{0}, R"({"foo":"bar"})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocReplace", cb::mcbp::ClientOpcode::SubdocReplace); } TEST_F(DurabilityTest, SubdocArrayPushLast) { subdoc(*getConnection(), "SubdocArrayPushLast", cb::mcbp::ClientOpcode::SubdocArrayPushLast); } TEST_F(DurabilityTest, SubdocArrayPushFirst) { subdoc(*getConnection(), "SubdocArrayPushFirst", cb::mcbp::ClientOpcode::SubdocArrayPushFirst); } TEST_F(DurabilityTest, SubdocArrayInsert) { auto conn = getConnection(); conn->store("SubdocArrayInsert", Vbid{0}, R"({"foo":[]})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocArrayInsert", cb::mcbp::ClientOpcode::SubdocArrayInsert); } TEST_F(DurabilityTest, SubdocArrayAddUnique) { subdoc(*getConnection(), "SubdocArrayAddUnique", cb::mcbp::ClientOpcode::SubdocArrayAddUnique); } TEST_F(DurabilityTest, SubdocCounter) { subdoc(*getConnection(), "SubdocCounter", cb::mcbp::ClientOpcode::SubdocCounter); } TEST_F(DurabilityTest, SubdocMultiMutation) { BinprotSubdocMultiMutationCommand cmd; cmd.setKey("SubdocMultiMutation"); cmd.addMutation(cb::mcbp::ClientOpcode::SubdocDictAdd, SUBDOC_FLAG_MKDIR_P, "foo", R"("value")"); cmd.addDocFlag(mcbp::subdoc::doc_flag::Mkdoc); cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = getConnection()->execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(0, rsp.getCas()); } /** * MB-34780 - Bucket delete fails if we've got pending sync writes * * As part of bucket deletion all of the DCP streams get torn down so * a sync write will _never_ complete. This caused bucket deletion to * block as the cookie was in an ewouldblock state */ TEST_F(DurabilityTest, MB34780) { cluster->deleteBucket("default"); std::mutex mutex; std::condition_variable cond; bool prepare_seen = false; auto bucket = cluster->createBucket( "default", {{"replicas", 2}, {"max_vbuckets", 8}}, [&mutex, &cond, &prepare_seen](const std::string& source, const std::string& destination, std::vector<uint8_t>& packet) { if (prepare_seen) { // Swallow everything.. packet.clear(); return; } const auto* h = reinterpret_cast<const cb::mcbp::Header*>( packet.data()); if (h->isRequest()) { const auto& req = h->getRequest(); if (req.getClientOpcode() == cb::mcbp::ClientOpcode::DcpPrepare) { std::lock_guard<std::mutex> guard(mutex); prepare_seen = true; cond.notify_all(); packet.clear(); } } }); ASSERT_TRUE(bucket) << "Failed to create bucket default"; auto conn = bucket->getConnection(Vbid(0)); conn->authenticate("@admin", "password", "PLAIN"); conn->selectBucket(bucket->getName()); BinprotMutationCommand command; command.setKey("MB34780"); command.setMutationType(MutationType::Set); DurabilityFrameInfo frameInfo(cb::durability::Level::Majority); command.addFrameInfo(frameInfo); conn->sendCommand(command); std::unique_lock<std::mutex> lock(mutex); cond.wait(lock, [&prepare_seen]() { return prepare_seen; }); // At this point we've sent the prepare, it is registered in the // durability manager.. We should be able to delete the bucket cluster->deleteBucket("default"); } <commit_msg>Remove disabled (and obsolete) tests<commit_after>/* * Copyright 2019 Couchbase, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "clustertest.h" #include "bucket.h" #include "cluster.h" #include <protocol/connection/client_connection.h> #include <protocol/connection/client_mcbp_commands.h> #include <protocol/connection/frameinfo.h> #include <condition_variable> #include <cstdlib> #include <string> /** * Get a frame info vector with a durability entry with Majority */ static FrameInfoVector GetMajorityDurabilityFrameInfoVector() { FrameInfoVector ret; ret.emplace_back(std::make_unique<DurabilityFrameInfo>( cb::durability::Level::Majority)); return ret; } class DurabilityTest : public cb::test::ClusterTest { protected: static void mutate(MemcachedConnection& conn, std::string id, MutationType type) { MutationInfo old{}; if (type != MutationType::Add) { old = conn.store(id, Vbid{0}, "", cb::mcbp::Datatype::Raw); } Document doc{}; doc.value = "body"; doc.info.id = std::move(id); doc.info.datatype = cb::mcbp::Datatype::Raw; const auto info = conn.mutate( doc, Vbid{0}, type, GetMajorityDurabilityFrameInfoVector); EXPECT_NE(0, info.cas); EXPECT_NE(old.cas, info.cas); } static void subdoc(MemcachedConnection& conn, std::string id, cb::mcbp::ClientOpcode opcode) { BinprotSubdocCommand cmd(opcode); cmd.setKey(std::move(id)); cmd.setPath("foo"); if (opcode != cb::mcbp::ClientOpcode::SubdocDelete) { cmd.setValue("1"); if (opcode == cb::mcbp::ClientOpcode::SubdocArrayInsert) { cmd.setPath("foo.[0]"); } else if (opcode != cb::mcbp::ClientOpcode::SubdocReplace) { cmd.addPathFlags(SUBDOC_FLAG_MKDIR_P); cmd.addDocFlags(mcbp::subdoc::doc_flag::Mkdoc); } } cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = conn.execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(0, rsp.getCas()); } static std::unique_ptr<MemcachedConnection> getConnection() { auto bucket = cluster->getBucket("default"); auto conn = bucket->getConnection(Vbid(0)); conn->authenticate("@admin", "password", "PLAIN"); conn->selectBucket(bucket->getName()); return conn; } }; TEST_F(DurabilityTest, Set) { mutate(*getConnection(), "Set", MutationType::Set); } TEST_F(DurabilityTest, Add) { mutate(*getConnection(), "Add", MutationType::Add); } TEST_F(DurabilityTest, Replace) { mutate(*getConnection(), "Replace", MutationType::Replace); } TEST_F(DurabilityTest, Append) { mutate(*getConnection(), "Append", MutationType::Append); } TEST_F(DurabilityTest, Prepend) { mutate(*getConnection(), "Prepend", MutationType::Prepend); } TEST_F(DurabilityTest, Delete) { auto conn = getConnection(); const auto old = conn->store("Delete", Vbid{0}, "", cb::mcbp::Datatype::Raw); auto info = getConnection()->remove( "Delete", Vbid{0}, 0, GetMajorityDurabilityFrameInfoVector); EXPECT_NE(0, info.cas); EXPECT_NE(old.cas, info.cas); } TEST_F(DurabilityTest, Increment) { auto conn = getConnection(); for (uint64_t ii = 0; ii < 10ULL; ++ii) EXPECT_EQ(ii, conn->increment("Increment", 1, 0, 0, nullptr, GetMajorityDurabilityFrameInfoVector)); } TEST_F(DurabilityTest, Decrement) { auto conn = getConnection(); for (uint64_t ii = 10; ii > 0ULL; --ii) EXPECT_EQ(ii, conn->decrement("Decrement", 1, 10, 0, nullptr, GetMajorityDurabilityFrameInfoVector)); } TEST_F(DurabilityTest, SubdocDictAdd) { subdoc(*getConnection(), "SubdocDictAdd", cb::mcbp::ClientOpcode::SubdocDictAdd); } TEST_F(DurabilityTest, SubdocDictUpsert) { subdoc(*getConnection(), "SubdocDictUpsert", cb::mcbp::ClientOpcode::SubdocDictUpsert); } TEST_F(DurabilityTest, SubdocDelete) { auto conn = getConnection(); conn->store("SubdocDelete", Vbid{0}, R"({"foo":"bar"})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocDelete", cb::mcbp::ClientOpcode::SubdocDelete); } TEST_F(DurabilityTest, SubdocReplace) { auto conn = getConnection(); conn->store("SubdocReplace", Vbid{0}, R"({"foo":"bar"})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocReplace", cb::mcbp::ClientOpcode::SubdocReplace); } TEST_F(DurabilityTest, SubdocArrayPushLast) { subdoc(*getConnection(), "SubdocArrayPushLast", cb::mcbp::ClientOpcode::SubdocArrayPushLast); } TEST_F(DurabilityTest, SubdocArrayPushFirst) { subdoc(*getConnection(), "SubdocArrayPushFirst", cb::mcbp::ClientOpcode::SubdocArrayPushFirst); } TEST_F(DurabilityTest, SubdocArrayInsert) { auto conn = getConnection(); conn->store("SubdocArrayInsert", Vbid{0}, R"({"foo":[]})", cb::mcbp::Datatype::JSON); subdoc(*conn, "SubdocArrayInsert", cb::mcbp::ClientOpcode::SubdocArrayInsert); } TEST_F(DurabilityTest, SubdocArrayAddUnique) { subdoc(*getConnection(), "SubdocArrayAddUnique", cb::mcbp::ClientOpcode::SubdocArrayAddUnique); } TEST_F(DurabilityTest, SubdocCounter) { subdoc(*getConnection(), "SubdocCounter", cb::mcbp::ClientOpcode::SubdocCounter); } TEST_F(DurabilityTest, SubdocMultiMutation) { BinprotSubdocMultiMutationCommand cmd; cmd.setKey("SubdocMultiMutation"); cmd.addMutation(cb::mcbp::ClientOpcode::SubdocDictAdd, SUBDOC_FLAG_MKDIR_P, "foo", R"("value")"); cmd.addDocFlag(mcbp::subdoc::doc_flag::Mkdoc); cmd.addFrameInfo(DurabilityFrameInfo{cb::durability::Level::Majority}); auto rsp = getConnection()->execute(cmd); EXPECT_TRUE(rsp.isSuccess()) << "Status: " << to_string(rsp.getStatus()) << std::endl << "Value: " << rsp.getDataString(); EXPECT_NE(0, rsp.getCas()); } /** * MB-34780 - Bucket delete fails if we've got pending sync writes * * As part of bucket deletion all of the DCP streams get torn down so * a sync write will _never_ complete. This caused bucket deletion to * block as the cookie was in an ewouldblock state */ TEST_F(DurabilityTest, MB34780) { cluster->deleteBucket("default"); std::mutex mutex; std::condition_variable cond; bool prepare_seen = false; auto bucket = cluster->createBucket( "default", {{"replicas", 2}, {"max_vbuckets", 8}}, [&mutex, &cond, &prepare_seen](const std::string& source, const std::string& destination, std::vector<uint8_t>& packet) { if (prepare_seen) { // Swallow everything.. packet.clear(); return; } const auto* h = reinterpret_cast<const cb::mcbp::Header*>( packet.data()); if (h->isRequest()) { const auto& req = h->getRequest(); if (req.getClientOpcode() == cb::mcbp::ClientOpcode::DcpPrepare) { std::lock_guard<std::mutex> guard(mutex); prepare_seen = true; cond.notify_all(); packet.clear(); } } }); ASSERT_TRUE(bucket) << "Failed to create bucket default"; auto conn = bucket->getConnection(Vbid(0)); conn->authenticate("@admin", "password", "PLAIN"); conn->selectBucket(bucket->getName()); BinprotMutationCommand command; command.setKey("MB34780"); command.setMutationType(MutationType::Set); DurabilityFrameInfo frameInfo(cb::durability::Level::Majority); command.addFrameInfo(frameInfo); conn->sendCommand(command); std::unique_lock<std::mutex> lock(mutex); cond.wait(lock, [&prepare_seen]() { return prepare_seen; }); // At this point we've sent the prepare, it is registered in the // durability manager.. We should be able to delete the bucket cluster->deleteBucket("default"); } <|endoftext|>
<commit_before>// $Id: GEOSNearestPointsTest.cpp 2424 2009-04-29 23:52:36Z mloskot $ // // Test Suite for C-API GEOSNearestPoints #include <tut/tut.hpp> // geos #include <geos_c.h> // std #include <cstdarg> #include <cstdio> #include <cstdlib> namespace tut { // // Test Group // // Common data used in test cases. struct test_capigeosnearestpoints_data { GEOSGeometry* geom1_; GEOSGeometry* geom2_; static void notice(const char* fmt, ...) { std::fprintf(stdout, "NOTICE: "); va_list ap; va_start(ap, fmt); std::vfprintf(stdout, fmt, ap); va_end(ap); std::fprintf(stdout, "\n"); } test_capigeosnearestpoints_data() : geom1_(nullptr), geom2_(nullptr) { initGEOS(notice, notice); } ~test_capigeosnearestpoints_data() { GEOSGeom_destroy(geom1_); GEOSGeom_destroy(geom2_); geom1_ = nullptr; geom2_ = nullptr; finishGEOS(); } }; typedef test_group<test_capigeosnearestpoints_data> group; typedef group::object object; group test_capigeosnearestpoints_group("capi::GEOSNearestPoints"); // // Test Cases // template<> template<> void object::test<1> () { geom1_ = GEOSGeomFromWKT("POLYGON EMPTY"); geom2_ = GEOSGeomFromWKT("POLYGON EMPTY"); ensure(nullptr != geom1_); ensure(nullptr != geom2_); GEOSCoordSequence* coords_; coords_ = GEOSNearestPoints(geom1_, geom2_); ensure(nullptr == coords_); } template<> template<> void object::test<2> () { geom1_ = GEOSGeomFromWKT("POLYGON((1 1,1 5,5 5,5 1,1 1))"); // geom2_ = GEOSGeomFromWKT("POINT(8 8)"); geom2_ = GEOSGeomFromWKT("POLYGON((8 8, 9 9, 9 10, 8 8))"); ensure(nullptr != geom1_); ensure(nullptr != geom2_); GEOSCoordSequence* coords_; coords_ = GEOSNearestPoints(geom1_, geom2_); ensure(nullptr != coords_); unsigned int size; GEOSCoordSeq_getSize(coords_, &size); ensure(2 == size); double x1, x2, y1, y2; /* Point in geom1_ */ GEOSCoordSeq_getOrdinate(coords_, 0, 0, &x1); GEOSCoordSeq_getOrdinate(coords_, 0, 1, &y1); /* Point in geom2_ */ GEOSCoordSeq_getOrdinate(coords_, 1, 0, &x2); GEOSCoordSeq_getOrdinate(coords_, 1, 1, &y2); ensure(5 == x1); ensure(5 == y1); ensure(8 == x2); ensure(8 == y2); GEOSCoordSeq_destroy(coords_); } } // namespace tut <commit_msg>Add GEOSNearestPoints test for point contained in polygon<commit_after>// $Id: GEOSNearestPointsTest.cpp 2424 2009-04-29 23:52:36Z mloskot $ // // Test Suite for C-API GEOSNearestPoints #include <tut/tut.hpp> // geos #include <geos_c.h> // std #include <cstdarg> #include <cstdio> #include <cstdlib> namespace tut { // // Test Group // // Common data used in test cases. struct test_capigeosnearestpoints_data { GEOSGeometry* geom1_; GEOSGeometry* geom2_; static void notice(const char* fmt, ...) { std::fprintf(stdout, "NOTICE: "); va_list ap; va_start(ap, fmt); std::vfprintf(stdout, fmt, ap); va_end(ap); std::fprintf(stdout, "\n"); } test_capigeosnearestpoints_data() : geom1_(nullptr), geom2_(nullptr) { initGEOS(notice, notice); } ~test_capigeosnearestpoints_data() { GEOSGeom_destroy(geom1_); GEOSGeom_destroy(geom2_); geom1_ = nullptr; geom2_ = nullptr; finishGEOS(); } }; typedef test_group<test_capigeosnearestpoints_data> group; typedef group::object object; group test_capigeosnearestpoints_group("capi::GEOSNearestPoints"); // // Test Cases // template<> template<> void object::test<1> () { geom1_ = GEOSGeomFromWKT("POLYGON EMPTY"); geom2_ = GEOSGeomFromWKT("POLYGON EMPTY"); ensure(nullptr != geom1_); ensure(nullptr != geom2_); GEOSCoordSequence* coords_; coords_ = GEOSNearestPoints(geom1_, geom2_); ensure(nullptr == coords_); } template<> template<> void object::test<2> () { geom1_ = GEOSGeomFromWKT("POLYGON((1 1,1 5,5 5,5 1,1 1))"); // geom2_ = GEOSGeomFromWKT("POINT(8 8)"); geom2_ = GEOSGeomFromWKT("POLYGON((8 8, 9 9, 9 10, 8 8))"); ensure(nullptr != geom1_); ensure(nullptr != geom2_); GEOSCoordSequence* coords_; coords_ = GEOSNearestPoints(geom1_, geom2_); ensure(nullptr != coords_); unsigned int size; GEOSCoordSeq_getSize(coords_, &size); ensure(2 == size); double x1, x2, y1, y2; /* Point in geom1_ */ GEOSCoordSeq_getOrdinate(coords_, 0, 0, &x1); GEOSCoordSeq_getOrdinate(coords_, 0, 1, &y1); /* Point in geom2_ */ GEOSCoordSeq_getOrdinate(coords_, 1, 0, &x2); GEOSCoordSeq_getOrdinate(coords_, 1, 1, &y2); ensure(5 == x1); ensure(5 == y1); ensure(8 == x2); ensure(8 == y2); GEOSCoordSeq_destroy(coords_); } template<> template<> void object::test<3> () { geom1_ = GEOSGeomFromWKT("POLYGON((1 1,1 5,5 5,5 1,1 1))"); geom2_ = GEOSGeomFromWKT("POINT(2 2)"); ensure(nullptr != geom1_); ensure(nullptr != geom2_); GEOSCoordSequence* coords_; coords_ = GEOSNearestPoints(geom1_, geom2_); ensure(nullptr != coords_); unsigned int size; GEOSCoordSeq_getSize(coords_, &size); ensure(2 == size); double x1, x2, y1, y2; /* Point in geom1_ */ GEOSCoordSeq_getOrdinate(coords_, 0, 0, &x1); GEOSCoordSeq_getOrdinate(coords_, 0, 1, &y1); /* Point in geom2_ */ GEOSCoordSeq_getOrdinate(coords_, 1, 0, &x2); GEOSCoordSeq_getOrdinate(coords_, 1, 1, &y2); ensure(2 == x1); ensure(2 == y1); ensure(2 == x2); ensure(2 == y2); GEOSCoordSeq_destroy(coords_); } } // namespace tut <|endoftext|>
<commit_before>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "unit_tests.hpp" #include "mfem.hpp" using namespace mfem; #ifdef MFEM_USE_SUITESPARSE #define DIRECT_SOLVE_SERIAL #endif #ifdef MFEM_USE_MUMPS #define DIRECT_SOLVE_PARALLEL #endif #ifdef MFEM_USE_SUPERLU #define DIRECT_SOLVE_PARALLEL #endif #if defined(DIRECT_SOLVE_SERIAL) || defined(DIRECT_SOLVE_PARALLEL) int dim; double uexact(const Vector& x) { double u; switch (dim) { case 1: u = 3.0 + 2.0 * x(0) - 0.5 * x(0) * x(0); break; case 2: u = 1.0 + 0.2 * x(0) - 0.9 * x(0) * x(1) + x(1) * x(1) * x(0); break; default: u = x(2) * x(2) * x(2) - 5.0 * x(0) * x(0) * x(1) * x(2); break; } return u; } void gradexact(const Vector& x, Vector & grad) { grad.SetSize(dim); switch (dim) { case 1: grad[0] = 2.0 - x(0); break; case 2: grad[0] = 0.2 - 0.9 * x(1) + x(1) * x (1); grad[1] = - 0.9 * x(0) + 2.0 * x(0) * x(1); break; default: grad[0] = -10.0 * x(0) * x(1) * x(2); grad[1] = - 5.0 * x(0) * x(0) * x(2); grad[2] = 3.0 * x(2) * x(2) - 5.0 * x(0) * x(0) * x(1); break; } } double d2uexact(const Vector& x) // retuns \Delta u { double d2u; switch (dim) { case 1: d2u = -1.0; break; case 2: d2u = 2.0 * x(0); break; default: d2u = -10.0 * x(1) * x(2) + 6.0 * x(2); break; } return d2u; } double fexact(const Vector& x) // retuns -\Delta u { double d2u = d2uexact(x); return -d2u; } #endif #ifdef DIRECT_SOLVE_SERIAL TEST_CASE("direct-serial","[CUDA]") { const int ne = 2; for (dim = 1; dim < 4; ++dim) { for (int order = 1; order < 4; ++order) { Mesh* mesh; if (dim == 1) { mesh = new Mesh(ne, 1.0); } else if (dim == 2) { mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0); } else { mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0); } FiniteElementCollection* fec = new H1_FECollection(order, dim); FiniteElementSpace fespace(mesh, fec); Array<int> ess_tdof_list; Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); FunctionCoefficient f(fexact); LinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(f)); b.Assemble(); BilinearForm a(&fespace); ConstantCoefficient one(1.0); a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.Assemble(); GridFunction x(&fespace); FunctionCoefficient uex(uexact); x = 0.0; x.ProjectBdrCoefficient(uex,ess_bdr); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); UMFPackSolver umf_solver; umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS; umf_solver.SetOperator(*A); umf_solver.Mult(B, X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); if (order == 3) { // recover polynomial exact solution if order>=3 a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); } delete fec; delete mesh; } } } #endif #ifdef DIRECT_SOLVE_PARALLEL TEST_CASE("direct-parallel", "[Parallel], [CUDA]") { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int ne = 2; for (dim = 1; dim < 4; ++dim) { for (int order = 1; order < 4; ++order) { Mesh* mesh; if (dim == 1) { mesh = new Mesh(ne, 1.0); } else if (dim == 2) { mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0); } else { mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0); } ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; FiniteElementCollection* fec = new H1_FECollection(order, dim); ParFiniteElementSpace fespace(pmesh, fec); Array<int> ess_tdof_list; Array<int> ess_bdr; if (pmesh->bdr_attributes.Size()) { ess_bdr.SetSize(pmesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } FunctionCoefficient f(fexact); ParLinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(f)); b.Assemble(); ParBilinearForm a(&fespace); ConstantCoefficient one(1.0); a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.Assemble(); ParGridFunction x(&fespace); FunctionCoefficient uex(uexact); x = 0.0; x.ProjectBdrCoefficient(uex,ess_bdr); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); #ifdef MFEM_USE_MUMPS { MUMPSSolver mumps; mumps.SetPrintLevel(0); mumps.SetOperator(*A.As<HypreParMatrix>()); mumps.Mult(B,X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); if (order == 3) { // recover polynomial exact solution if order>=3 a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); } } #endif #ifdef MFEM_USE_SUPERLU // Transform to monolithic HypreParMatrix { SuperLURowLocMatrix SA(*A.As<HypreParMatrix>()); SuperLUSolver superlu(MPI_COMM_WORLD); superlu.SetPrintStatistics(false); superlu.SetSymmetricPattern(false); superlu.SetColumnPermutation(superlu::PARMETIS); superlu.SetOperator(SA); superlu.Mult(B, X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); if (order == 3) { // recover polynomial exact solution if order>=3 a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); } } #endif delete fec; delete pmesh; } } } #endif<commit_msg>removing some tests<commit_after>// Copyright (c) 2010-2020, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. #include "unit_tests.hpp" #include "mfem.hpp" using namespace mfem; #ifdef MFEM_USE_SUITESPARSE #define DIRECT_SOLVE_SERIAL #endif #ifdef MFEM_USE_MUMPS #define DIRECT_SOLVE_PARALLEL #endif #ifdef MFEM_USE_SUPERLU #define DIRECT_SOLVE_PARALLEL #endif #if defined(DIRECT_SOLVE_SERIAL) || defined(DIRECT_SOLVE_PARALLEL) int dim; double uexact(const Vector& x) { double u; switch (dim) { case 1: u = 3.0 + 2.0 * x(0) - 0.5 * x(0) * x(0); break; case 2: u = 1.0 + 0.2 * x(0) - 0.9 * x(0) * x(1) + x(1) * x(1) * x(0); break; default: u = x(2) * x(2) * x(2) - 5.0 * x(0) * x(0) * x(1) * x(2); break; } return u; } void gradexact(const Vector& x, Vector & grad) { grad.SetSize(dim); switch (dim) { case 1: grad[0] = 2.0 - x(0); break; case 2: grad[0] = 0.2 - 0.9 * x(1) + x(1) * x (1); grad[1] = - 0.9 * x(0) + 2.0 * x(0) * x(1); break; default: grad[0] = -10.0 * x(0) * x(1) * x(2); grad[1] = - 5.0 * x(0) * x(0) * x(2); grad[2] = 3.0 * x(2) * x(2) - 5.0 * x(0) * x(0) * x(1); break; } } double d2uexact(const Vector& x) // retuns \Delta u { double d2u; switch (dim) { case 1: d2u = -1.0; break; case 2: d2u = 2.0 * x(0); break; default: d2u = -10.0 * x(1) * x(2) + 6.0 * x(2); break; } return d2u; } double fexact(const Vector& x) // retuns -\Delta u { double d2u = d2uexact(x); return -d2u; } #endif #ifdef DIRECT_SOLVE_SERIAL TEST_CASE("direct-serial","[CUDA]") { const int ne = 2; for (dim = 1; dim < 4; ++dim) { Mesh* mesh; if (dim == 1) { mesh = new Mesh(ne, 1.0); } else if (dim == 2) { mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0); } else { mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0); } int order = 3; FiniteElementCollection* fec = new H1_FECollection(order, dim); FiniteElementSpace fespace(mesh, fec); Array<int> ess_tdof_list; Array<int> ess_bdr(mesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); FunctionCoefficient f(fexact); LinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(f)); b.Assemble(); BilinearForm a(&fespace); ConstantCoefficient one(1.0); a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.Assemble(); GridFunction x(&fespace); FunctionCoefficient uex(uexact); x = 0.0; x.ProjectBdrCoefficient(uex,ess_bdr); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); UMFPackSolver umf_solver; umf_solver.Control[UMFPACK_ORDERING] = UMFPACK_ORDERING_METIS; umf_solver.SetOperator(*A); umf_solver.Mult(B, X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); delete fec; delete mesh; } } #endif #ifdef DIRECT_SOLVE_PARALLEL TEST_CASE("direct-parallel", "[Parallel], [CUDA]") { int rank; MPI_Comm_rank(MPI_COMM_WORLD, &rank); const int ne = 2; for (dim = 1; dim < 4; ++dim) { Mesh* mesh; if (dim == 1) { mesh = new Mesh(ne, 1.0); } else if (dim == 2) { mesh = new Mesh(ne, ne, Element::QUADRILATERAL, 1, 1.0, 1.0); } else { mesh = new Mesh(ne, ne, ne, Element::HEXAHEDRON, 1, 1.0, 1.0, 1.0); } ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); delete mesh; int order = 3; FiniteElementCollection* fec = new H1_FECollection(order, dim); ParFiniteElementSpace fespace(pmesh, fec); Array<int> ess_tdof_list; Array<int> ess_bdr; if (pmesh->bdr_attributes.Size()) { ess_bdr.SetSize(pmesh->bdr_attributes.Max()); ess_bdr = 1; fespace.GetEssentialTrueDofs(ess_bdr, ess_tdof_list); } FunctionCoefficient f(fexact); ParLinearForm b(&fespace); b.AddDomainIntegrator(new DomainLFIntegrator(f)); b.Assemble(); ParBilinearForm a(&fespace); ConstantCoefficient one(1.0); a.AddDomainIntegrator(new DiffusionIntegrator(one)); a.Assemble(); ParGridFunction x(&fespace); FunctionCoefficient uex(uexact); x = 0.0; x.ProjectBdrCoefficient(uex,ess_bdr); OperatorPtr A; Vector B, X; a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); #ifdef MFEM_USE_MUMPS { MUMPSSolver mumps; mumps.SetPrintLevel(0); mumps.SetOperator(*A.As<HypreParMatrix>()); mumps.Mult(B,X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); } #endif #ifdef MFEM_USE_SUPERLU // Transform to monolithic HypreParMatrix { SuperLURowLocMatrix SA(*A.As<HypreParMatrix>()); SuperLUSolver superlu(MPI_COMM_WORLD); superlu.SetPrintStatistics(false); superlu.SetSymmetricPattern(false); superlu.SetColumnPermutation(superlu::PARMETIS); superlu.SetOperator(SA); superlu.Mult(B, X); Vector Y(X.Size()); A->Mult(X,Y); Y-=B; REQUIRE(Y.Norml2() < 1.e-12); a.RecoverFEMSolution(X, b, x); VectorFunctionCoefficient grad(dim,gradexact); double err = x.ComputeH1Error(&uex,&grad); REQUIRE(err < 1.e-12); } #endif delete fec; delete pmesh; } } #endif<|endoftext|>
<commit_before>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // Network API based on boost::asio #ifndef LIBPORT_ASIO_HH # define LIBPORT_ASIO_HH # include <libport/config.h> # include <libport/sys/socket.h> # include <libport/iostream> // At least on OS X, many symbols are not available where we expect // them. And it is clearly connected to our using // -fvisibility=hidden. I (AD) could not exactly pinpoint the // problem, but at least I know one cure: do not play dirty visibility // tricks with Asio. # pragma GCC visibility push(default) # include <boost/asio.hpp> # if defined LIBPORT_ENABLE_SSL # include <boost/asio/ssl.hpp> # endif # pragma GCC visibility pop # include <boost/function.hpp> # include <libport/destructible.hh> # include <libport/export.hh> # include <libport/finally.hh> # include <libport/utime.hh> # include <boost/version.hpp> # if BOOST_VERSION >= 103600 # include <libport/rs232.hh> # endif namespace libport { class LIBPORT_API AsioDestructible: public Destructible { protected: virtual void doDestroy(); }; //FIXME: extend to provide a way to ensure workerThread not started. /** Get the io_service handling all asynchronous operations. * * \param startWorkerThread create a thread in which to run the io_service. * If \b startWorkerThread is false on \b first invocation, the user * is responsible for calling the work or poll methods of the io_service. */ LIBPORT_API boost::asio::io_service& get_io_service(bool startWorkerThread = true); /** BaseSocket class. * * This class has a callback-based API: onReadFunc() and onErrorFunc(). */ class LIBPORT_API BaseSocket: public AsioDestructible { public: virtual ~BaseSocket(){} libport::Finally deletor; /// Write data asynchronously to the socket. virtual void write(const void* data, unsigned int length) = 0; /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } /// Alias on close() for API compatibility. void disconnect() { close(); } /// Return if the socket is connected to a remote host. virtual bool isConnected() const = 0; /// Disconnect the socket from the remote host, calls onError. virtual void close() = 0; /// Get port of remote endpoint virtual unsigned short getRemotePort() const = 0; /// Get IP address of remote endpoint virtual std::string getRemoteHost() const = 0; /// Get port of local endpoint virtual unsigned short getLocalPort() const = 0; /// Get IP address of local endpoint virtual std::string getLocalHost() const = 0; virtual int stealFD() = 0; virtual int getFD() = 0; /// Callback function called each time new data is available. boost::function1<bool, boost::asio::streambuf&> onReadFunc; /// Callback function called in case of error on the socket. boost::function1<void, boost::system::error_code> onErrorFunc; /// Mutex to protect access to the above callbacks. Lockable callbackLock; }; /// Endpoint on an UDP socket. class LIBPORT_API UDPLink { public: virtual ~UDPLink() {} virtual void reply(const void* data, size_t length) = 0; void reply(const std::string& s) { reply(s.c_str(), s.length()); } }; /** Socket class with a higher API. * * It is recommended that you always asynchronously destroy Socket instances * by calling the destroy() method. If you want to put instances in the stack, * or explicitly call delete for whatever reason, you must in your destructor: * - call close() * - call wasDestroyed() * - call waitForDestructionPermission(), if the io_service is running in * another thread(the default behavior). */ class LIBPORT_API Socket: public AsioDestructible { public: Socket(boost::asio::io_service& io = libport::get_io_service()) : base_(0) , io_(io) {} virtual ~Socket(); /** Set underlying BaseSocket object, setup its callbacks to call our virtual functions. */ virtual void setBase(BaseSocket*); /** Called each time new data is received. * \return the number of bytes used in buffer. The remaining data will * be passed again to this function as soon as at least an extra byte * is available. */ virtual int onRead(const void*, size_t length) { return length; } /** Called in case of error on the socket. By default, do nothing. */ virtual void onError(boost::system::error_code); /** Called on socket connection */ virtual void onConnect() {} /// Ask for the asynchronous destruction of this object. virtual void destroy(); void write(const void* data, unsigned int length) { base_->write(data, length); } /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } void send(const std::string& s) { write(s.c_str(), s.length()); } void close() { if (base_) base_->close(); } unsigned short getRemotePort() const { return base_->getRemotePort();} std::string getRemoteHost() const { return base_->getRemoteHost();} unsigned short getLocalPort() const { return base_->getLocalPort();} std::string getLocalHost() const { return base_->getLocalHost();} bool isConnected() const {return base_ ? base_->isConnected() : false;} /** Connect to a remote host. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. * \param asynchronous make an asynchronous attempt. The function will * return immediately, and either onConnect will be called when the * connection succeeds, or onError() will be called. * \return an error code if the connection failed. * */ boost::system::error_code connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); boost::system::error_code connect(const std::string& host, unsigned port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); # if BOOST_VERSION >= 103600 boost::system::error_code open_serial(const std::string& device, unsigned int rate); # endif /** Make an asynchronous connection attempt to a remote host. * This API garantees that either the onConnect() or the onError() function * will be called. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. */ void async_connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0) { connect(host, port, udp, usTimeout, true); } typedef void* Handle; typedef boost::function0<Socket*> SocketFactory; /** Listen using udp. * Call onRead(data, length, link) for each new packet. Link can be used * to reply to the sender through its UDPLink::reply() method. */ static Handle listenUDP(const std::string& host, const std::string& port, boost::function3<void, const void*, int, boost::shared_ptr<UDPLink> > onRead, boost::system::error_code& erc); /** Listen using TCP or UDP. * * \param f a socket factory. For each new connection the function will * be called and the resulting socket object bound to the new connection. */ boost::system::error_code listen(SocketFactory f, const std::string& host, const std::string& port, bool udp = false); boost::system::error_code listen(SocketFactory f, const std::string& host, unsigned port, bool udp = false); #if defined LIBPORT_ENABLE_SSL boost::system::error_code listenSSL(SocketFactory f, const std::string& host, const std::string& port, boost::asio::ssl::context_base::method ctx = boost::asio::ssl::context::sslv23_server, boost::asio::ssl::context::options options = boost::asio::ssl::context::verify_none, const std::string& privateKeyFile = "", const std::string& certChainFile = "", const std::string& tmpDHFile = "" , const std::string& cipherList = ""); #endif /// Steal file descriptor from Socket. Return the file descriptor. int stealFD(); /// Get file descriptor from Socket. int getFD(); /// Set file descriptor template<class Sock> void setFD(int fd, typename Sock::protocol_type proto); /** Sleep for specified amount of time, polling if current thread is * the asio worker thread */ static void sleep(utime_t duration); boost::asio::io_service& get_io_service(); protected: bool onRead_(boost::asio::streambuf&); std::string buffer; BaseSocket* base_; private: template<typename Proto, typename BaseFactory> boost::system::error_code listenProto(SocketFactory f, const std::string& host, const std::string&port, BaseFactory bf); template<typename Proto, typename BaseFactory> boost::system::error_code connectProto(const std::string& host, const std::string& port, utime_t timeout, bool async, BaseFactory bf); boost::asio::io_service& io_; }; /** Wrapper of libport::Socket to be able to use Socket without inherit from * it. */ class LIBPORT_API ConcreteSocket: public Socket { public: typedef boost::function2<int, const void*, size_t> onread_type; typedef boost::function1<void, boost::system::error_code> onerror_type; typedef boost::function0<void> onconnect_type; typedef Socket super_type; ConcreteSocket(boost::asio::io_service& io = libport::get_io_service()) : Socket(io) , onconnect_(boost::bind(&super_type::onConnect, this)) , onerror_(boost::bind(&super_type::onError, this, _1)) , onread_(boost::bind(&super_type::onRead, this, _1, _2)) {} ConcreteSocket& onConnect(onconnect_type cb) { onconnect_ = cb; return *this; } ConcreteSocket& onError(onerror_type cb) { onerror_ = cb; return *this; } ConcreteSocket& onRead(onread_type cb) { onread_ = cb; return *this; } virtual void onConnect() { onconnect_(); } virtual void onError(boost::system::error_code erc) { onerror_(erc); } virtual int onRead(const void* data, size_t length) { return onread_(data, length); } private: onconnect_type onconnect_; onerror_type onerror_; onread_type onread_; }; LIBPORT_API bool isPollThread(); /** Poll on an io_service for given duration in microseconds. * @param duration max duration for which to poll in microseconds * @param once process at most one handler before returning if true */ LIBPORT_API void pollFor(utime_t duration, bool once = false, boost::asio::io_service& io = get_io_service()); typedef boost::shared_ptr<boost::asio::deadline_timer> AsyncCallHandler; /** Call \b callback() in \b usDelay microseconds. * If the method cancel() of the returned timer object is invoked before * expiration of the delay, the call is aborted and callback() is not * called. */ AsyncCallHandler asyncCall(boost::function0<void> callback, utime_t usDelay, boost::asio::io_service& io = get_io_service()); } # include "libport/asio.hxx" #endif <commit_msg>Do not use #pragma visibility under mingw and vcxx.<commit_after>/* * Copyright (C) 2009, Gostai S.A.S. * * This software is provided "as is" without warranty of any kind, * either expressed or implied, including but not limited to the * implied warranties of fitness for a particular purpose. * * See the LICENSE file for more information. */ // Network API based on boost::asio #ifndef LIBPORT_ASIO_HH # define LIBPORT_ASIO_HH # include <libport/config.h> # include <libport/sys/socket.h> # include <libport/iostream> // At least on OS X, many symbols are not available where we expect // them. And it is clearly connected to our using // -fvisibility=hidden. I (AD) could not exactly pinpoint the // problem, but at least I know one cure: do not play dirty visibility // tricks with Asio. # if ! defined WIN32 # pragma GCC visibility push(default) # endif # include <boost/asio.hpp> # if defined LIBPORT_ENABLE_SSL # include <boost/asio/ssl.hpp> # endif # if ! defined WIN32 # pragma GCC visibility pop # endif # include <boost/function.hpp> # include <libport/destructible.hh> # include <libport/export.hh> # include <libport/finally.hh> # include <libport/utime.hh> # include <boost/version.hpp> # if BOOST_VERSION >= 103600 # include <libport/rs232.hh> # endif namespace libport { class LIBPORT_API AsioDestructible: public Destructible { protected: virtual void doDestroy(); }; //FIXME: extend to provide a way to ensure workerThread not started. /** Get the io_service handling all asynchronous operations. * * \param startWorkerThread create a thread in which to run the io_service. * If \b startWorkerThread is false on \b first invocation, the user * is responsible for calling the work or poll methods of the io_service. */ LIBPORT_API boost::asio::io_service& get_io_service(bool startWorkerThread = true); /** BaseSocket class. * * This class has a callback-based API: onReadFunc() and onErrorFunc(). */ class LIBPORT_API BaseSocket: public AsioDestructible { public: virtual ~BaseSocket(){} libport::Finally deletor; /// Write data asynchronously to the socket. virtual void write(const void* data, unsigned int length) = 0; /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } /// Alias on close() for API compatibility. void disconnect() { close(); } /// Return if the socket is connected to a remote host. virtual bool isConnected() const = 0; /// Disconnect the socket from the remote host, calls onError. virtual void close() = 0; /// Get port of remote endpoint virtual unsigned short getRemotePort() const = 0; /// Get IP address of remote endpoint virtual std::string getRemoteHost() const = 0; /// Get port of local endpoint virtual unsigned short getLocalPort() const = 0; /// Get IP address of local endpoint virtual std::string getLocalHost() const = 0; virtual int stealFD() = 0; virtual int getFD() = 0; /// Callback function called each time new data is available. boost::function1<bool, boost::asio::streambuf&> onReadFunc; /// Callback function called in case of error on the socket. boost::function1<void, boost::system::error_code> onErrorFunc; /// Mutex to protect access to the above callbacks. Lockable callbackLock; }; /// Endpoint on an UDP socket. class LIBPORT_API UDPLink { public: virtual ~UDPLink() {} virtual void reply(const void* data, size_t length) = 0; void reply(const std::string& s) { reply(s.c_str(), s.length()); } }; /** Socket class with a higher API. * * It is recommended that you always asynchronously destroy Socket instances * by calling the destroy() method. If you want to put instances in the stack, * or explicitly call delete for whatever reason, you must in your destructor: * - call close() * - call wasDestroyed() * - call waitForDestructionPermission(), if the io_service is running in * another thread(the default behavior). */ class LIBPORT_API Socket: public AsioDestructible { public: Socket(boost::asio::io_service& io = libport::get_io_service()) : base_(0) , io_(io) {} virtual ~Socket(); /** Set underlying BaseSocket object, setup its callbacks to call our virtual functions. */ virtual void setBase(BaseSocket*); /** Called each time new data is received. * \return the number of bytes used in buffer. The remaining data will * be passed again to this function as soon as at least an extra byte * is available. */ virtual int onRead(const void*, size_t length) { return length; } /** Called in case of error on the socket. By default, do nothing. */ virtual void onError(boost::system::error_code); /** Called on socket connection */ virtual void onConnect() {} /// Ask for the asynchronous destruction of this object. virtual void destroy(); void write(const void* data, unsigned int length) { base_->write(data, length); } /// Alias on write() for API compatibility. void send(const void* addr, size_t len) { write(addr, len); } void send(const std::string& s) { write(s.c_str(), s.length()); } void close() { if (base_) base_->close(); } unsigned short getRemotePort() const { return base_->getRemotePort();} std::string getRemoteHost() const { return base_->getRemoteHost();} unsigned short getLocalPort() const { return base_->getLocalPort();} std::string getLocalHost() const { return base_->getLocalHost();} bool isConnected() const {return base_ ? base_->isConnected() : false;} /** Connect to a remote host. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. * \param asynchronous make an asynchronous attempt. The function will * return immediately, and either onConnect will be called when the * connection succeeds, or onError() will be called. * \return an error code if the connection failed. * */ boost::system::error_code connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); boost::system::error_code connect(const std::string& host, unsigned port, bool udp=false, utime_t usTimeout = 0, bool asynchronous = false); # if BOOST_VERSION >= 103600 boost::system::error_code open_serial(const std::string& device, unsigned int rate); # endif /** Make an asynchronous connection attempt to a remote host. * This API garantees that either the onConnect() or the onError() function * will be called. * \param host hostname to connect to. * \param port port to connect to, as a service name or an int. * \param usTimeout timeout in microseconds, 0 meaning none. */ void async_connect(const std::string& host, const std::string& port, bool udp=false, utime_t usTimeout = 0) { connect(host, port, udp, usTimeout, true); } typedef void* Handle; typedef boost::function0<Socket*> SocketFactory; /** Listen using udp. * Call onRead(data, length, link) for each new packet. Link can be used * to reply to the sender through its UDPLink::reply() method. */ static Handle listenUDP(const std::string& host, const std::string& port, boost::function3<void, const void*, int, boost::shared_ptr<UDPLink> > onRead, boost::system::error_code& erc); /** Listen using TCP or UDP. * * \param f a socket factory. For each new connection the function will * be called and the resulting socket object bound to the new connection. */ boost::system::error_code listen(SocketFactory f, const std::string& host, const std::string& port, bool udp = false); boost::system::error_code listen(SocketFactory f, const std::string& host, unsigned port, bool udp = false); #if defined LIBPORT_ENABLE_SSL boost::system::error_code listenSSL(SocketFactory f, const std::string& host, const std::string& port, boost::asio::ssl::context_base::method ctx = boost::asio::ssl::context::sslv23_server, boost::asio::ssl::context::options options = boost::asio::ssl::context::verify_none, const std::string& privateKeyFile = "", const std::string& certChainFile = "", const std::string& tmpDHFile = "" , const std::string& cipherList = ""); #endif /// Steal file descriptor from Socket. Return the file descriptor. int stealFD(); /// Get file descriptor from Socket. int getFD(); /// Set file descriptor template<class Sock> void setFD(int fd, typename Sock::protocol_type proto); /** Sleep for specified amount of time, polling if current thread is * the asio worker thread */ static void sleep(utime_t duration); boost::asio::io_service& get_io_service(); protected: bool onRead_(boost::asio::streambuf&); std::string buffer; BaseSocket* base_; private: template<typename Proto, typename BaseFactory> boost::system::error_code listenProto(SocketFactory f, const std::string& host, const std::string&port, BaseFactory bf); template<typename Proto, typename BaseFactory> boost::system::error_code connectProto(const std::string& host, const std::string& port, utime_t timeout, bool async, BaseFactory bf); boost::asio::io_service& io_; }; /** Wrapper of libport::Socket to be able to use Socket without inherit from * it. */ class LIBPORT_API ConcreteSocket: public Socket { public: typedef boost::function2<int, const void*, size_t> onread_type; typedef boost::function1<void, boost::system::error_code> onerror_type; typedef boost::function0<void> onconnect_type; typedef Socket super_type; ConcreteSocket(boost::asio::io_service& io = libport::get_io_service()) : Socket(io) , onconnect_(boost::bind(&super_type::onConnect, this)) , onerror_(boost::bind(&super_type::onError, this, _1)) , onread_(boost::bind(&super_type::onRead, this, _1, _2)) {} ConcreteSocket& onConnect(onconnect_type cb) { onconnect_ = cb; return *this; } ConcreteSocket& onError(onerror_type cb) { onerror_ = cb; return *this; } ConcreteSocket& onRead(onread_type cb) { onread_ = cb; return *this; } virtual void onConnect() { onconnect_(); } virtual void onError(boost::system::error_code erc) { onerror_(erc); } virtual int onRead(const void* data, size_t length) { return onread_(data, length); } private: onconnect_type onconnect_; onerror_type onerror_; onread_type onread_; }; LIBPORT_API bool isPollThread(); /** Poll on an io_service for given duration in microseconds. * @param duration max duration for which to poll in microseconds * @param once process at most one handler before returning if true */ LIBPORT_API void pollFor(utime_t duration, bool once = false, boost::asio::io_service& io = get_io_service()); typedef boost::shared_ptr<boost::asio::deadline_timer> AsyncCallHandler; /** Call \b callback() in \b usDelay microseconds. * If the method cancel() of the returned timer object is invoked before * expiration of the delay, the call is aborted and callback() is not * called. */ AsyncCallHandler asyncCall(boost::function0<void> callback, utime_t usDelay, boost::asio::io_service& io = get_io_service()); } # include "libport/asio.hxx" #endif <|endoftext|>
<commit_before>#include <vector> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin.hpp> #include <obelisk/zmq_message.hpp> #include "config.hpp" #define HEARTBEAT_LIVENESS 3 // 3-5 is reasonable #define HEARTBEAT_INTERVAL 1000 // msecs #define LOG_BALANCER "balancer" #if ZMQ_VERSION_MAJOR == 4 constexpr size_t zmq_uuid_size = 5; #else constexpr size_t zmq_uuid_size = 17; #endif using namespace bc; using namespace obelisk; typedef data_chunk worker_uuid; static void s_version_assert(int want_major, int want_minor) { int major, minor, patch; zmq_version (&major, &minor, &patch); if (major < want_major || (major == want_major && minor < want_minor)) { std::cout << "Current 0MQ version is " << major << "." << minor << std::endl; std::cout << "Application needs at least " << want_major << "." << want_minor << " - cannot continue" << std::endl; exit (EXIT_FAILURE); } } // Return current system clock as milliseconds static int64_t s_clock(void) { #if (defined (__WINDOWS__)) SYSTEMTIME st; GetSystemTime (&st); return (int64_t) st.wSecond * 1000 + st.wMilliseconds; #else struct timeval tv; gettimeofday (&tv, NULL); return (int64_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif } // This defines one active worker in our worker queue typedef struct { worker_uuid identity; // Address of worker int64_t expiry; // Expires at this time } worker_t; // Insert worker at end of queue, reset expiry // Worker must not already be in queue void s_worker_append(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { std::cout << "E: duplicate worker identity " << identity << std::endl; found = true; break; } } if (!found) { worker_t worker; worker.identity = identity; worker.expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; queue.push_back(worker); } } // Remove worker from queue, if present void s_worker_delete(std::vector<worker_t>& queue, const worker_uuid& identity) { for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it = queue.erase(it); break; } } } // Reset worker expiry, worker must be present void s_worker_refresh(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it->expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; found = true; break; } } if (!found) { std::cout << "E: worker " << identity << " not ready" << std::endl; } } // Pop next available worker off queue, return identity const worker_uuid s_worker_dequeue(std::vector<worker_t>& queue) { assert(queue.size()); const worker_uuid identity = queue[0].identity; queue.erase(queue.begin()); return identity; } // Look for & kill expired workers void s_queue_purge(std::vector<worker_t>& queue) { int64_t clock = s_clock(); for (auto it = queue.begin(); it < queue.end(); ++it) { if (clock > it->expiry) { it = queue.erase(it) - 1; } } } typedef std::vector<worker_t> worker_queue; void forward_request(zmq::socket_t& frontend, zmq::socket_t& backend, worker_queue& queue) { // Get client request. zmq_message msg_in; msg_in.recv(frontend); const data_stack& in_parts = msg_in.parts(); if (in_parts.size() != 6) { log_warning(LOG_BALANCER) << "Wrong sized message"; return; } // First item is client's identity. if (in_parts[0].size() != zmq_uuid_size) { log_warning(LOG_BALANCER) << "Client UUID malformed " << in_parts[0]; return; } // Second item is worker identity or nothing. if (in_parts[1].size() > 255) { log_warning(LOG_BALANCER) << "Worker UUID malformed"; return; } // We now deconstruct the request message to the backend // which looks like: // [CLIENT UUID] // [WORKER UUID] // ... // And create a new message that looks like: // [WORKER UUID] // [CLIENT UUID] // ... // Before sending it to the worker. // This is so the client can specify a worker to send their // request specifically to. zmq_message msg_out; // If second frame is nothing, then we select a random worker. if (in_parts[1].empty()) { // Route to next worker worker_uuid worker_identity = s_worker_dequeue(queue); msg_out.append(worker_identity); } else { // Route to client's preferred worker. msg_out.append(in_parts[1]); } msg_out.append(in_parts[0]); // Copy the remaining data. for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); msg_out.send(backend); } void handle_control_message(const data_stack& in_parts, worker_queue& queue, const worker_uuid& identity) { std::string command(in_parts[1].begin(), in_parts[1].end()); log_info(LOG_BALANCER) << "command: " << command; if (command == "READY") { s_worker_delete(queue, identity); s_worker_append(queue, identity); } else if (command == "HEARTBEAT") { s_worker_refresh(queue, identity); } else log_error(LOG_BALANCER) << "Invalid command from " << identity; } void passback_response(zmq::socket_t& backend, zmq::socket_t& frontend, worker_queue& queue) { zmq_message msg_in; msg_in.recv(backend); const data_stack& in_parts = msg_in.parts(); BITCOIN_ASSERT(in_parts.size() == 2 || in_parts.size() == 6); worker_uuid identity = in_parts[0]; // Return reply to client if it's not a control message if (in_parts.size() == 2) return handle_control_message(in_parts, queue, identity); // We now deconstruct the request message to the frontend // which looks like: // [WORKER UUID] // [CLIENT UUID] // ... // And create a new message that looks like: // [CLIENT UUID] // [WORKER UUID] // ... // Before sending it to the backend. // This is so the client will know which worker // responded to their request. BITCOIN_ASSERT(in_parts.size() == 6); zmq_message msg_out; BITCOIN_ASSERT(in_parts[1].size() == zmq_uuid_size); msg_out.append(in_parts[1]); BITCOIN_ASSERT(in_parts[0].size() > 0 && in_parts[0].size() < 256); msg_out.append(in_parts[0]); for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); BITCOIN_ASSERT(in_parts.size() == msg_out.parts().size()); msg_out.send(frontend); // Add worker back to available pool of workers. s_worker_append(queue, identity); } int main(int argc, char** argv) { s_version_assert(2, 1); config_map_type config; if (argc == 2) { std::cout << "Using config file: " << argv[1] << std::endl; load_config(config, argv[1]); } else { using boost::filesystem::path; path conf_filename = path(SYSCONFDIR) / "obelisk" / "balancer.cfg"; load_config(config, conf_filename.native()); } // Prepare our context and sockets zmq::context_t context(1); zmq::socket_t frontend(context, ZMQ_ROUTER); zmq::socket_t backend(context, ZMQ_ROUTER); // For clients frontend.bind(config["frontend"].c_str()); // For workers backend.bind(config["backend"].c_str()); // Queue of available workers worker_queue queue; // Send out heartbeats at regular intervals int64_t heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; while (1) { zmq::pollitem_t items[] = { { backend, 0, ZMQ_POLLIN, 0 }, { frontend, 0, ZMQ_POLLIN, 0 } }; // Poll frontend only if we have available workers if (queue.empty()) zmq::poll(items, 1, HEARTBEAT_INTERVAL * 1000); else zmq::poll(items, 2, HEARTBEAT_INTERVAL * 1000); // Handle worker activity on backend if (items [0].revents & ZMQ_POLLIN) passback_response(backend, frontend, queue); if (items [1].revents & ZMQ_POLLIN) forward_request(frontend, backend, queue); // Send heartbeats to idle workers if it's time if (s_clock() > heartbeat_at) { for (auto it = queue.begin(); it < queue.end(); ++it) { zmq_message msg; msg.append(it->identity); std::string command = "HEARTBEAT"; msg.append(data_chunk(command.begin(), command.end())); msg.send(backend); } heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; } s_queue_purge(queue); } // We never exit the main loop // But pretend to do the right shutdown anyhow queue.clear(); return 0; } <commit_msg>remove redundant info output about which config file is loaded.<commit_after>#include <vector> #include <boost/filesystem.hpp> #include <bitcoin/bitcoin.hpp> #include <obelisk/zmq_message.hpp> #include "config.hpp" #define HEARTBEAT_LIVENESS 3 // 3-5 is reasonable #define HEARTBEAT_INTERVAL 1000 // msecs #define LOG_BALANCER "balancer" #if ZMQ_VERSION_MAJOR == 4 constexpr size_t zmq_uuid_size = 5; #else constexpr size_t zmq_uuid_size = 17; #endif using namespace bc; using namespace obelisk; typedef data_chunk worker_uuid; static void s_version_assert(int want_major, int want_minor) { int major, minor, patch; zmq_version (&major, &minor, &patch); if (major < want_major || (major == want_major && minor < want_minor)) { std::cout << "Current 0MQ version is " << major << "." << minor << std::endl; std::cout << "Application needs at least " << want_major << "." << want_minor << " - cannot continue" << std::endl; exit (EXIT_FAILURE); } } // Return current system clock as milliseconds static int64_t s_clock(void) { #if (defined (__WINDOWS__)) SYSTEMTIME st; GetSystemTime (&st); return (int64_t) st.wSecond * 1000 + st.wMilliseconds; #else struct timeval tv; gettimeofday (&tv, NULL); return (int64_t) (tv.tv_sec * 1000 + tv.tv_usec / 1000); #endif } // This defines one active worker in our worker queue typedef struct { worker_uuid identity; // Address of worker int64_t expiry; // Expires at this time } worker_t; // Insert worker at end of queue, reset expiry // Worker must not already be in queue void s_worker_append(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { std::cout << "E: duplicate worker identity " << identity << std::endl; found = true; break; } } if (!found) { worker_t worker; worker.identity = identity; worker.expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; queue.push_back(worker); } } // Remove worker from queue, if present void s_worker_delete(std::vector<worker_t>& queue, const worker_uuid& identity) { for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it = queue.erase(it); break; } } } // Reset worker expiry, worker must be present void s_worker_refresh(std::vector<worker_t>& queue, const worker_uuid& identity) { bool found = false; for (auto it = queue.begin(); it < queue.end(); ++it) { if (it->identity == identity) { it->expiry = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS; found = true; break; } } if (!found) { std::cout << "E: worker " << identity << " not ready" << std::endl; } } // Pop next available worker off queue, return identity const worker_uuid s_worker_dequeue(std::vector<worker_t>& queue) { assert(queue.size()); const worker_uuid identity = queue[0].identity; queue.erase(queue.begin()); return identity; } // Look for & kill expired workers void s_queue_purge(std::vector<worker_t>& queue) { int64_t clock = s_clock(); for (auto it = queue.begin(); it < queue.end(); ++it) { if (clock > it->expiry) { it = queue.erase(it) - 1; } } } typedef std::vector<worker_t> worker_queue; void forward_request(zmq::socket_t& frontend, zmq::socket_t& backend, worker_queue& queue) { // Get client request. zmq_message msg_in; msg_in.recv(frontend); const data_stack& in_parts = msg_in.parts(); if (in_parts.size() != 6) { log_warning(LOG_BALANCER) << "Wrong sized message"; return; } // First item is client's identity. if (in_parts[0].size() != zmq_uuid_size) { log_warning(LOG_BALANCER) << "Client UUID malformed " << in_parts[0]; return; } // Second item is worker identity or nothing. if (in_parts[1].size() > 255) { log_warning(LOG_BALANCER) << "Worker UUID malformed"; return; } // We now deconstruct the request message to the backend // which looks like: // [CLIENT UUID] // [WORKER UUID] // ... // And create a new message that looks like: // [WORKER UUID] // [CLIENT UUID] // ... // Before sending it to the worker. // This is so the client can specify a worker to send their // request specifically to. zmq_message msg_out; // If second frame is nothing, then we select a random worker. if (in_parts[1].empty()) { // Route to next worker worker_uuid worker_identity = s_worker_dequeue(queue); msg_out.append(worker_identity); } else { // Route to client's preferred worker. msg_out.append(in_parts[1]); } msg_out.append(in_parts[0]); // Copy the remaining data. for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); msg_out.send(backend); } void handle_control_message(const data_stack& in_parts, worker_queue& queue, const worker_uuid& identity) { std::string command(in_parts[1].begin(), in_parts[1].end()); log_info(LOG_BALANCER) << "command: " << command; if (command == "READY") { s_worker_delete(queue, identity); s_worker_append(queue, identity); } else if (command == "HEARTBEAT") { s_worker_refresh(queue, identity); } else log_error(LOG_BALANCER) << "Invalid command from " << identity; } void passback_response(zmq::socket_t& backend, zmq::socket_t& frontend, worker_queue& queue) { zmq_message msg_in; msg_in.recv(backend); const data_stack& in_parts = msg_in.parts(); BITCOIN_ASSERT(in_parts.size() == 2 || in_parts.size() == 6); worker_uuid identity = in_parts[0]; // Return reply to client if it's not a control message if (in_parts.size() == 2) return handle_control_message(in_parts, queue, identity); // We now deconstruct the request message to the frontend // which looks like: // [WORKER UUID] // [CLIENT UUID] // ... // And create a new message that looks like: // [CLIENT UUID] // [WORKER UUID] // ... // Before sending it to the backend. // This is so the client will know which worker // responded to their request. BITCOIN_ASSERT(in_parts.size() == 6); zmq_message msg_out; BITCOIN_ASSERT(in_parts[1].size() == zmq_uuid_size); msg_out.append(in_parts[1]); BITCOIN_ASSERT(in_parts[0].size() > 0 && in_parts[0].size() < 256); msg_out.append(in_parts[0]); for (auto it = in_parts.begin() + 2; it != in_parts.end(); ++it) msg_out.append(*it); BITCOIN_ASSERT(in_parts.size() == msg_out.parts().size()); msg_out.send(frontend); // Add worker back to available pool of workers. s_worker_append(queue, identity); } int main(int argc, char** argv) { s_version_assert(2, 1); config_map_type config; if (argc == 2) load_config(config, argv[1]); else { using boost::filesystem::path; path conf_filename = path(SYSCONFDIR) / "obelisk" / "balancer.cfg"; load_config(config, conf_filename.native()); } // Prepare our context and sockets zmq::context_t context(1); zmq::socket_t frontend(context, ZMQ_ROUTER); zmq::socket_t backend(context, ZMQ_ROUTER); // For clients frontend.bind(config["frontend"].c_str()); // For workers backend.bind(config["backend"].c_str()); // Queue of available workers worker_queue queue; // Send out heartbeats at regular intervals int64_t heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; while (1) { zmq::pollitem_t items[] = { { backend, 0, ZMQ_POLLIN, 0 }, { frontend, 0, ZMQ_POLLIN, 0 } }; // Poll frontend only if we have available workers if (queue.empty()) zmq::poll(items, 1, HEARTBEAT_INTERVAL * 1000); else zmq::poll(items, 2, HEARTBEAT_INTERVAL * 1000); // Handle worker activity on backend if (items [0].revents & ZMQ_POLLIN) passback_response(backend, frontend, queue); if (items [1].revents & ZMQ_POLLIN) forward_request(frontend, backend, queue); // Send heartbeats to idle workers if it's time if (s_clock() > heartbeat_at) { for (auto it = queue.begin(); it < queue.end(); ++it) { zmq_message msg; msg.append(it->identity); std::string command = "HEARTBEAT"; msg.append(data_chunk(command.begin(), command.end())); msg.send(backend); } heartbeat_at = s_clock() + HEARTBEAT_INTERVAL; } s_queue_purge(queue); } // We never exit the main loop // But pretend to do the right shutdown anyhow queue.clear(); return 0; } <|endoftext|>
<commit_before>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef RULE_HPP #define RULE_HPP // stl #include <string> #include <vector> // boost #include <boost/shared_ptr.hpp> #include <boost/variant.hpp> // mapnik #include <mapnik/line_symbolizer.hpp> #include <mapnik/line_pattern_symbolizer.hpp> #include <mapnik/polygon_symbolizer.hpp> #include <mapnik/polygon_pattern_symbolizer.hpp> #include <mapnik/point_symbolizer.hpp> #include <mapnik/raster_symbolizer.hpp> #include <mapnik/shield_symbolizer.hpp> #include <mapnik/text_symbolizer.hpp> #include <mapnik/filter.hpp> #include <mapnik/filter_visitor.hpp> namespace mapnik { inline bool operator==(point_symbolizer const& lhs, point_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_symbolizer const& lhs, line_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_pattern_symbolizer const& lhs, line_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_symbolizer const& lhs, polygon_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_pattern_symbolizer const& lhs, polygon_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(raster_symbolizer const& lhs, raster_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(text_symbolizer const& lhs, text_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(shield_symbolizer const& lhs, shield_symbolizer const& rhs) { return (&lhs == &rhs); } typedef boost::variant<point_symbolizer, line_symbolizer, line_pattern_symbolizer, polygon_symbolizer, polygon_pattern_symbolizer, raster_symbolizer, shield_symbolizer, text_symbolizer> symbolizer; typedef std::vector<symbolizer> symbolizers; template <typename FeatureT> class all_filter; template <typename FeatureT,template <typename> class Filter> class rule { typedef Filter<FeatureT> filter_type; typedef boost::shared_ptr<filter_type> filter_ptr; private: std::string name_; std::string title_; std::string abstract_; double min_scale_; double max_scale_; symbolizers syms_; filter_ptr filter_; bool else_filter_; public: rule() : name_(), title_(), abstract_(), min_scale_(0), max_scale_(std::numeric_limits<double>::infinity()), syms_(), filter_(new all_filter<FeatureT>), else_filter_(false) {} rule(const std::string& name, const std::string& title="", double min_scale_denominator=0, double max_scale_denominator=std::numeric_limits<double>::infinity()) : name_(name), title_(title), min_scale_(min_scale_denominator), max_scale_(max_scale_denominator), syms_(), filter_(new all_filter<FeatureT>), else_filter_(false) {} rule(const rule& rhs) : name_(rhs.name_), title_(rhs.title_), abstract_(rhs.abstract_), min_scale_(rhs.min_scale_), max_scale_(rhs.max_scale_), syms_(rhs.syms_), filter_(rhs.filter_), else_filter_(rhs.else_filter_) {} rule& operator=(rule const& rhs) { rule tmp(rhs); swap(tmp); return *this; } bool operator==(rule const& other) { return (this == &other); } void set_max_scale(double scale) { max_scale_=scale; } double get_max_scale() const { return max_scale_; } void set_min_scale(double scale) { min_scale_=scale; } double get_min_scale() const { return min_scale_; } void set_name(std::string const& name) { name_=name; } std::string const& get_name() const { return name_; } std::string const& get_title() const { return title_; } void set_title(std::string const& title) { title_=title; } void set_abstract(std::string const& abstract) { abstract_=abstract; } std::string const& get_abstract() const { return abstract_; } void append(const symbolizer& sym) { syms_.push_back(sym); } void remove_at(size_t index) { if (index < syms_.size()) { syms_.erase(syms_.begin()+index); } } const symbolizers& get_symbolizers() const { return syms_; } symbolizers::const_iterator begin() { return syms_.begin(); } symbolizers::const_iterator end() { return syms_.end(); } void set_filter(const filter_ptr& filter) { filter_=filter; } filter_ptr const& get_filter() const { return filter_; } void set_else(bool else_filter) { else_filter_=else_filter; } bool has_else_filter() const { return else_filter_; } bool active(double scale) const { return ( scale > min_scale_ && scale < max_scale_ ); } void accept(filter_visitor<FeatureT>& v) const { v.visit(*this); } private: void swap(rule& rhs) throw() { name_=rhs.name_; title_=rhs.title_; abstract_=rhs.abstract_; min_scale_=rhs.min_scale_; max_scale_=rhs.max_scale_; syms_=rhs.syms_; filter_=rhs.filter_; else_filter_=rhs.else_filter_; } }; typedef rule<Feature,filter> rule_type; } #endif //RULE_HPP <commit_msg>fixed scale_denominator <commit_after>/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ #ifndef RULE_HPP #define RULE_HPP // stl #include <string> #include <vector> // boost #include <boost/shared_ptr.hpp> #include <boost/variant.hpp> // mapnik #include <mapnik/line_symbolizer.hpp> #include <mapnik/line_pattern_symbolizer.hpp> #include <mapnik/polygon_symbolizer.hpp> #include <mapnik/polygon_pattern_symbolizer.hpp> #include <mapnik/point_symbolizer.hpp> #include <mapnik/raster_symbolizer.hpp> #include <mapnik/shield_symbolizer.hpp> #include <mapnik/text_symbolizer.hpp> #include <mapnik/filter.hpp> #include <mapnik/filter_visitor.hpp> namespace mapnik { inline bool operator==(point_symbolizer const& lhs, point_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_symbolizer const& lhs, line_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(line_pattern_symbolizer const& lhs, line_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_symbolizer const& lhs, polygon_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(polygon_pattern_symbolizer const& lhs, polygon_pattern_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(raster_symbolizer const& lhs, raster_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(text_symbolizer const& lhs, text_symbolizer const& rhs) { return (&lhs == &rhs); } inline bool operator==(shield_symbolizer const& lhs, shield_symbolizer const& rhs) { return (&lhs == &rhs); } typedef boost::variant<point_symbolizer, line_symbolizer, line_pattern_symbolizer, polygon_symbolizer, polygon_pattern_symbolizer, raster_symbolizer, shield_symbolizer, text_symbolizer> symbolizer; typedef std::vector<symbolizer> symbolizers; template <typename FeatureT> class all_filter; template <typename FeatureT,template <typename> class Filter> class rule { typedef Filter<FeatureT> filter_type; typedef boost::shared_ptr<filter_type> filter_ptr; private: std::string name_; std::string title_; std::string abstract_; double min_scale_; double max_scale_; symbolizers syms_; filter_ptr filter_; bool else_filter_; public: rule() : name_(), title_(), abstract_(), min_scale_(0), max_scale_(std::numeric_limits<double>::infinity()), syms_(), filter_(new all_filter<FeatureT>), else_filter_(false) {} rule(const std::string& name, const std::string& title="", double min_scale_denominator=0, double max_scale_denominator=std::numeric_limits<double>::infinity()) : name_(name), title_(title), min_scale_(min_scale_denominator), max_scale_(max_scale_denominator), syms_(), filter_(new all_filter<FeatureT>), else_filter_(false) {} rule(const rule& rhs) : name_(rhs.name_), title_(rhs.title_), abstract_(rhs.abstract_), min_scale_(rhs.min_scale_), max_scale_(rhs.max_scale_), syms_(rhs.syms_), filter_(rhs.filter_), else_filter_(rhs.else_filter_) {} rule& operator=(rule const& rhs) { rule tmp(rhs); swap(tmp); return *this; } bool operator==(rule const& other) { return (this == &other); } void set_max_scale(double scale) { max_scale_=scale; } double get_max_scale() const { return max_scale_; } void set_min_scale(double scale) { min_scale_=scale; } double get_min_scale() const { return min_scale_; } void set_name(std::string const& name) { name_=name; } std::string const& get_name() const { return name_; } std::string const& get_title() const { return title_; } void set_title(std::string const& title) { title_=title; } void set_abstract(std::string const& abstract) { abstract_=abstract; } std::string const& get_abstract() const { return abstract_; } void append(const symbolizer& sym) { syms_.push_back(sym); } void remove_at(size_t index) { if (index < syms_.size()) { syms_.erase(syms_.begin()+index); } } const symbolizers& get_symbolizers() const { return syms_; } symbolizers::const_iterator begin() { return syms_.begin(); } symbolizers::const_iterator end() { return syms_.end(); } void set_filter(const filter_ptr& filter) { filter_=filter; } filter_ptr const& get_filter() const { return filter_; } void set_else(bool else_filter) { else_filter_=else_filter; } bool has_else_filter() const { return else_filter_; } bool active(double scale) const { return ( scale >= min_scale_ - 1e-6 && scale < max_scale_ + 1e-6); } void accept(filter_visitor<FeatureT>& v) const { v.visit(*this); } private: void swap(rule& rhs) throw() { name_=rhs.name_; title_=rhs.title_; abstract_=rhs.abstract_; min_scale_=rhs.min_scale_; max_scale_=rhs.max_scale_; syms_=rhs.syms_; filter_=rhs.filter_; else_filter_=rhs.else_filter_; } }; typedef rule<Feature,filter> rule_type; } #endif //RULE_HPP <|endoftext|>
<commit_before>#include <simcode/log/logging.h> using namespace simcode; using namespace log; static const char* LogLevelName[]={ "[TRACE]", "[DEBUG]", "[INFO]", "[WARN]", "[ERROR]", "[FATAL]" }; static const char* get_level_name(int level) { return LogLevelName[level]; } int Logging::Init(const std::string& filename, uint64_t rotate_size) { int ret; ret = logFile_.open(filename, rotate_size); if (0 != ret) return ret; } void Logging::log_out(int level, const char* filename, int linenum, const char* funcname, const char* msg) { char data[LogFile::LOG_BUF_LEN]; char buf[LogFile::LOG_BUF_LEN]; int len; len = snprintf(data, sizeof(data), "%s|%d|%s|%s", filename, linenum, funcname, msg); len = logFile_.logData(data, len, get_level_name(level), buf); { ScopeLock lock(mutex_); logFile_.logWrite(buf, len); } } int GlobalLogging::Init(const std::string& name, uint64_t rotate_size, int level) { simcode::GlobalLogger::set_level(level); Logging* logging = new Logging; if (0 != logging->Init(name, rotate_size)) { delete logging; return 1; } simcode::GlobalLogger::set_base_logger(logging); return 0; } <commit_msg>mod get_level_name<commit_after>#include <simcode/log/logging.h> using namespace simcode; using namespace log; static const char* LogLevelName[]={ "[TRACE]", "[DEBUG]", "[INFO]", "[WARN]", "[ERROR]", "[FATAL]" }; static const char* get_level_name(int level) { return LogLevelName[level-1]; } int Logging::Init(const std::string& filename, uint64_t rotate_size) { int ret; ret = logFile_.open(filename, rotate_size); if (0 != ret) return ret; } void Logging::log_out(int level, const char* filename, int linenum, const char* funcname, const char* msg) { char data[LogFile::LOG_BUF_LEN]; char buf[LogFile::LOG_BUF_LEN]; int len; len = snprintf(data, sizeof(data), "%s|%d|%s|%s", filename, linenum, funcname, msg); len = logFile_.logData(data, len, get_level_name(level), buf); { ScopeLock lock(mutex_); logFile_.logWrite(buf, len); } } int GlobalLogging::Init(const std::string& name, uint64_t rotate_size, int level) { simcode::GlobalLogger::set_level(level); Logging* logging = new Logging; if (0 != logging->Init(name, rotate_size)) { delete logging; return 1; } simcode::GlobalLogger::set_base_logger(logging); return 0; } <|endoftext|>
<commit_before>/****************************************************************************** * $Id$ * * Project: pdal - http://pdal.org - A BSD library for LAS format data. * Purpose: LAS bounds class * Author: Howard Butler, hobu.inc@gmail.com * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * 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 Martin Isenburg or Iowa Department * of Natural Resources 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 OWNER 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. ****************************************************************************/ #ifndef INCLUDED_BOUNDS_HPP #define INCLUDED_BOUNDS_HPP #include <pdal/pdal_internal.hpp> #include <cassert> #include <vector> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <pdal/Vector.hpp> #include <pdal/Range.hpp> namespace pdal { /// Bounds is for manipulating n-dimensional ranges of data. Typically /// used for defining the spatial extents of XYZ data, this class can also be /// used for defining bounds of other dimensions. template <typename T> class PDAL_DLL Bounds { public: typedef typename std::vector< Range<T> > RangeVector; private: RangeVector m_ranges; public: /** @name Constructors */ /// Constructs an empty Bounds instance /// with no dimensions Bounds<T>() { m_ranges.resize(0); } /// Copy constructor Bounds(Bounds const& other) : m_ranges(other.m_ranges) { } /// Constructs a Bounds instance from a vector /// of Range Bounds(RangeVector const& ranges) : m_ranges(ranges) { } /// Convenience constructor for typical 3D case Bounds( T minx, T miny, T minz, T maxx, T maxy, T maxz) { m_ranges.resize(3); m_ranges[0].setMinimum(minx); m_ranges[1].setMinimum(miny); m_ranges[2].setMinimum(minz); m_ranges[0].setMaximum(maxx); m_ranges[1].setMaximum(maxy); m_ranges[2].setMaximum(maxz); assert(verify()); } /// Convenience constructor for typical 2D case Bounds( T minx, T miny, T maxx, T maxy) { m_ranges.resize(2); m_ranges[0].setMinimum(minx); m_ranges[1].setMinimum(miny); m_ranges[0].setMaximum(maxx); m_ranges[1].setMaximum(maxy); assert(verify()); } /// Convenience constructor for Vector of minimum and maximum /// values. Bounds(const Vector<T>& minimum, const Vector<T>& maximum) { assert(minimum.size() == maximum.size()); m_ranges.resize(minimum.size()); for (std::size_t i=0; i<minimum.size(); i++) { m_ranges[i].setMinimum(minimum[i]); m_ranges[i].setMaximum(maximum[i]); } assert(verify()); } /** @name Data manipulation */ T getMinimum(std::size_t const& index) const { if (m_ranges.size() <= index) { // std::ostringstream msg; // msg << "Bounds dimensions, " << ranges.size() <<", is less " // << "than the given index, " << index; // throw pdal::bounds_error(msg.str()); return 0; } return m_ranges[index].getMinimum(); } void setMinimum(std::size_t const& index, T v) { if (m_ranges.size() <= index) { m_ranges.resize(index + 1); } m_ranges[index].setMinimum(v); } T getMaximum(std::size_t const& index) const { if (m_ranges.size() <= index) { // std::ostringstream msg; // msg << "Bounds dimensions, " << m_ranges.size() <<", is less " // << "than the given index, " << index; // throw pdal::bounds_error(msg.str()); return 0; } return m_ranges[index].getMaximum(); } void setMaximum(std::size_t const& index, T v) { if (m_ranges.size() <= index) { m_ranges.resize(index + 1); } m_ranges[index].setMaximum(v); } Vector<T> getMinimum() { std::vector<T> vec; for (std::size_t i=0; i<m_ranges.size(); i++) { vec.push_back(m_ranges[i].getMinimum()); } return Vector<T>(vec); } Vector<T> getMaximum() { std::vector<T> vec; for (std::size_t i=0; i<m_ranges.size(); i++) { vec.push_back(m_ranges[i].getMaximum()); } return Vector<T>(vec); } /** @name Equality */ inline bool operator==(Bounds<T> const& rhs) const { return equal(rhs); } inline bool operator!=(Bounds<T> const& rhs) const { return (!equal(rhs)); } /** @name Identity */ Bounds<T>& operator=(Bounds<T> const& rhs) { if (&rhs != this) { m_ranges = rhs.m_ranges; } return *this; } /** @name Data queries */ /// The vector of Range<T> for the Bounds RangeVector const& dimensions() const { return m_ranges; } /// The number of dimensions of the Bounds std::size_t size() const { return m_ranges.size(); } /// Is this Bounds equal to other? bool equal(Bounds<T> const& other) const { if (size() != other.size()) { return false; } for (std::size_t i = 0; i < size(); i++) { if (m_ranges[i] != other.m_ranges[i]) { return false; } } return true; } /// Synonym for intersects for now bool overlaps(Bounds const& other) const { if (other.size() != size()) { return false; } for (std::size_t i = 0; i < size(); i++) { if ( m_ranges[i].overlaps(other.m_ranges[i]) ) return true; } return false; } /// Does this Bounds contain a point? bool contains(Vector<T> point) const { if (point.size() != size()) return false; for (std::size_t i = 0; i < size(); i++) { // As soon as it is not contains, we're false if (! m_ranges[i].contains(point[i]) ) return false; } return true; } /// Does this Bounds contain other? bool contains(Bounds<T> const& other) const { for (std::size_t i = 0; i < size(); i++) { // As soon as it is not contains, we're false if (! m_ranges[i].contains(other.m_ranges[i]) ) return false; } return true; } /// Shift each dimension by a vector of deltas void shift(std::vector<T> deltas) { std::size_t i; if( size() != deltas.size()) { std::ostringstream msg; msg << "pdal::Bounds::shift: Delta vector size, " << deltas.size() << ", is larger than the dimensionality of the bounds, "<< size() << "."; throw pdal::bounds_error(msg.str()); } for (i = 0; i < deltas.size(); ++i) { m_ranges[i].shift(deltas[i]); } } /// Scale each dimension by a vector of deltas void scale(std::vector<T> deltas) { std::size_t i; if( size() != deltas.size()) { std::ostringstream msg; msg << "pdal::Bounds::scale: Delta vector size, " << deltas.size() << ", is larger than the dimensionality of the bounds, "<< size() << "."; throw pdal::bounds_error(msg.str()); } for (i = 0; i < deltas.size(); ++i) { m_ranges[i].scale(deltas[i]); } } /// Clip this Bounds to the extent of r void clip(Bounds const& r) { RangeVector ds = r.dimensions(); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].clip(ds[i]); } } /// Grow to the union of two pdal::Bounds void grow(Bounds const& r) { RangeVector ds = r.dimensions(); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].grow(ds[i]); } } /// Expand the pdal::Bounds to include this point void grow(Vector<T> const& point) { assert(point.size() == size()); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].grow(point[i]); } } /// Calculate a n-dimensional volume for the Bounds instance T volume() const { T output = T(1); for (std::size_t i = 0; i < size(); i++) { output = output * m_ranges[i].length(); } return output; } /// Returns true if the pdal::Bounds<T>::size() is 0 or /// all dimensions within the bounds are empty. bool empty() const { if (size()==0) { return true; } for (std::size_t i = 0; i < size(); i++) { if (m_ranges[i].empty()) { return true; } } return false; } /// Verifies that the minimums and maximums of each dimension within the /// bounds are not inverted (also works in the case where the bounds is /// at infinity or when the bounds is empty). bool verify() { for (std::size_t d = 0; d < size(); ++d) { if (getMinimum(d) > getMaximum(d) ) { // Check that we're not infinity either way if (Utils::compare_distance<T>(getMinimum(d), (std::numeric_limits<T>::max)()) || Utils::compare_distance<T>(getMaximum(d), -(std::numeric_limits<T>::max)())) { std::ostringstream msg; msg << "pdal::Bounds::verify: Minimum point at dimension " << d << "is greater than maximum point. Neither point is infinity."; throw pdal::bounds_error(msg.str()); } } } return true; } /** @name Default extent */ /// Returns a staticly-allocated Bounds extent that represents infinity static const Bounds<T>& getDefaultSpatialExtent() { static T minv((std::numeric_limits<T>::min)()); static T maxv((std::numeric_limits<T>::max)()); static Bounds v(minv,minv,minv,maxv,maxv,maxv); return v; } /** @name Summary and serialization */ /// Outputs a string-based boost::property_tree::ptree representation /// of the Bounds instance boost::property_tree::ptree toPTree() const { boost::property_tree::ptree tree; for (std::size_t i = 0; i < size(); ++i) { const Range<T>& r = dimensions()[i]; tree.add_child(boost::lexical_cast<std::string>(i), r.toPTree()); } return tree; } /// Outputs a string representation of the Bounds instance to std::cout void dump() const { std::cout << *this; } }; template<class T> std::ostream& operator<<(std::ostream& ostr, const Bounds<T>& bounds) { ostr << "("; for (std::size_t d = 0; d < bounds.size(); ++d) { const Range<T>& r = bounds.dimensions()[d]; ostr << r; if (d!=bounds.size()-1) ostr << ", "; } ostr << ")"; return ostr; } extern PDAL_DLL std::istream& operator>>(std::istream& istr, Bounds<double>& bounds); } // namespace pdal // Needed for C++ DLL exports #ifdef PDAL_COMPILER_MSVC template class PDAL_DLL pdal::Range<double>; template class PDAL_DLL pdal::Bounds<double>; #endif #endif <commit_msg>allow +inf, -inf bounds instances for cumulators<commit_after>/****************************************************************************** * $Id$ * * Project: pdal - http://pdal.org - A BSD library for LAS format data. * Purpose: LAS bounds class * Author: Howard Butler, hobu.inc@gmail.com * ****************************************************************************** * Copyright (c) 2010, Howard Butler * * 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 Martin Isenburg or Iowa Department * of Natural Resources 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 OWNER 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. ****************************************************************************/ #ifndef INCLUDED_BOUNDS_HPP #define INCLUDED_BOUNDS_HPP #include <pdal/pdal_internal.hpp> #include <cassert> #include <vector> #include <sstream> #include <boost/property_tree/ptree.hpp> #include <pdal/Vector.hpp> #include <pdal/Range.hpp> namespace pdal { /// Bounds is for manipulating n-dimensional ranges of data. Typically /// used for defining the spatial extents of XYZ data, this class can also be /// used for defining bounds of other dimensions. template <typename T> class PDAL_DLL Bounds { public: typedef typename std::vector< Range<T> > RangeVector; private: RangeVector m_ranges; public: /** @name Constructors */ /// Constructs an empty Bounds instance /// with no dimensions Bounds<T>() { m_ranges.resize(0); } /// Copy constructor Bounds(Bounds const& other) : m_ranges(other.m_ranges) { } /// Constructs a Bounds instance from a vector /// of Range Bounds(RangeVector const& ranges) : m_ranges(ranges) { } /// Convenience constructor for typical 3D case Bounds( T minx, T miny, T minz, T maxx, T maxy, T maxz) { m_ranges.resize(3); m_ranges[0].setMinimum(minx); m_ranges[1].setMinimum(miny); m_ranges[2].setMinimum(minz); m_ranges[0].setMaximum(maxx); m_ranges[1].setMaximum(maxy); m_ranges[2].setMaximum(maxz); assert(verify()); } /// Convenience constructor for typical 2D case Bounds( T minx, T miny, T maxx, T maxy) { m_ranges.resize(2); m_ranges[0].setMinimum(minx); m_ranges[1].setMinimum(miny); m_ranges[0].setMaximum(maxx); m_ranges[1].setMaximum(maxy); assert(verify()); } /// Convenience constructor for Vector of minimum and maximum /// values. Bounds(const Vector<T>& minimum, const Vector<T>& maximum) { assert(minimum.size() == maximum.size()); m_ranges.resize(minimum.size()); for (std::size_t i=0; i<minimum.size(); i++) { m_ranges[i].setMinimum(minimum[i]); m_ranges[i].setMaximum(maximum[i]); } assert(verify()); } /** @name Data manipulation */ T getMinimum(std::size_t const& index) const { if (m_ranges.size() <= index) { // std::ostringstream msg; // msg << "Bounds dimensions, " << ranges.size() <<", is less " // << "than the given index, " << index; // throw pdal::bounds_error(msg.str()); return 0; } return m_ranges[index].getMinimum(); } void setMinimum(std::size_t const& index, T v) { if (m_ranges.size() <= index) { m_ranges.resize(index + 1); } m_ranges[index].setMinimum(v); } T getMaximum(std::size_t const& index) const { if (m_ranges.size() <= index) { // std::ostringstream msg; // msg << "Bounds dimensions, " << m_ranges.size() <<", is less " // << "than the given index, " << index; // throw pdal::bounds_error(msg.str()); return 0; } return m_ranges[index].getMaximum(); } void setMaximum(std::size_t const& index, T v) { if (m_ranges.size() <= index) { m_ranges.resize(index + 1); } m_ranges[index].setMaximum(v); } Vector<T> getMinimum() { std::vector<T> vec; for (std::size_t i=0; i<m_ranges.size(); i++) { vec.push_back(m_ranges[i].getMinimum()); } return Vector<T>(vec); } Vector<T> getMaximum() { std::vector<T> vec; for (std::size_t i=0; i<m_ranges.size(); i++) { vec.push_back(m_ranges[i].getMaximum()); } return Vector<T>(vec); } /** @name Equality */ inline bool operator==(Bounds<T> const& rhs) const { return equal(rhs); } inline bool operator!=(Bounds<T> const& rhs) const { return (!equal(rhs)); } /** @name Identity */ Bounds<T>& operator=(Bounds<T> const& rhs) { if (&rhs != this) { m_ranges = rhs.m_ranges; } return *this; } /** @name Data queries */ /// The vector of Range<T> for the Bounds RangeVector const& dimensions() const { return m_ranges; } /// The number of dimensions of the Bounds std::size_t size() const { return m_ranges.size(); } /// Is this Bounds equal to other? bool equal(Bounds<T> const& other) const { if (size() != other.size()) { return false; } for (std::size_t i = 0; i < size(); i++) { if (m_ranges[i] != other.m_ranges[i]) { return false; } } return true; } /// Synonym for intersects for now bool overlaps(Bounds const& other) const { if (other.size() != size()) { return false; } for (std::size_t i = 0; i < size(); i++) { if ( m_ranges[i].overlaps(other.m_ranges[i]) ) return true; } return false; } /// Does this Bounds contain a point? bool contains(Vector<T> point) const { if (point.size() != size()) return false; for (std::size_t i = 0; i < size(); i++) { // As soon as it is not contains, we're false if (! m_ranges[i].contains(point[i]) ) return false; } return true; } /// Does this Bounds contain other? bool contains(Bounds<T> const& other) const { for (std::size_t i = 0; i < size(); i++) { // As soon as it is not contains, we're false if (! m_ranges[i].contains(other.m_ranges[i]) ) return false; } return true; } /// Shift each dimension by a vector of deltas void shift(std::vector<T> deltas) { std::size_t i; if( size() != deltas.size()) { std::ostringstream msg; msg << "pdal::Bounds::shift: Delta vector size, " << deltas.size() << ", is larger than the dimensionality of the bounds, "<< size() << "."; throw pdal::bounds_error(msg.str()); } for (i = 0; i < deltas.size(); ++i) { m_ranges[i].shift(deltas[i]); } } /// Scale each dimension by a vector of deltas void scale(std::vector<T> deltas) { std::size_t i; if( size() != deltas.size()) { std::ostringstream msg; msg << "pdal::Bounds::scale: Delta vector size, " << deltas.size() << ", is larger than the dimensionality of the bounds, "<< size() << "."; throw pdal::bounds_error(msg.str()); } for (i = 0; i < deltas.size(); ++i) { m_ranges[i].scale(deltas[i]); } } /// Clip this Bounds to the extent of r void clip(Bounds const& r) { RangeVector ds = r.dimensions(); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].clip(ds[i]); } } /// Grow to the union of two pdal::Bounds void grow(Bounds const& r) { RangeVector ds = r.dimensions(); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].grow(ds[i]); } } /// Expand the pdal::Bounds to include this point void grow(Vector<T> const& point) { assert(point.size() == size()); for (std::size_t i = 0; i < size(); ++i) { m_ranges[i].grow(point[i]); } } /// Calculate a n-dimensional volume for the Bounds instance T volume() const { T output = T(1); for (std::size_t i = 0; i < size(); i++) { output = output * m_ranges[i].length(); } return output; } /// Returns true if the pdal::Bounds<T>::size() is 0 or /// all dimensions within the bounds are empty. bool empty() const { if (size()==0) { return true; } for (std::size_t i = 0; i < size(); i++) { if (m_ranges[i].empty()) { return true; } } return false; } /// Verifies that the minimums and maximums of each dimension within the /// bounds are not inverted (allows min == +inf and max == -inf, however). bool verify() { for (std::size_t d = 0; d < size(); ++d) { if (getMinimum(d) > getMaximum(d) ) { // Allow infinity bounds if (!Utils::compare_distance<T>(getMinimum(d), (std::numeric_limits<T>::max)()) && !Utils::compare_distance<T>(getMaximum(d), -(std::numeric_limits<T>::min)())) { std::ostringstream msg; msg << "pdal::Bounds::verify: Minimum point at dimension " << d << " is greater than maximum point. Neither point is infinity."; throw pdal::bounds_error(msg.str()); } } } return true; } /** @name Default extent */ /// Returns a staticly-allocated Bounds extent that represents infinity static const Bounds<T>& getDefaultSpatialExtent() { static T minv((std::numeric_limits<T>::min)()); static T maxv((std::numeric_limits<T>::max)()); static Bounds v(minv,minv,minv,maxv,maxv,maxv); return v; } /** @name Summary and serialization */ /// Outputs a string-based boost::property_tree::ptree representation /// of the Bounds instance boost::property_tree::ptree toPTree() const { boost::property_tree::ptree tree; for (std::size_t i = 0; i < size(); ++i) { const Range<T>& r = dimensions()[i]; tree.add_child(boost::lexical_cast<std::string>(i), r.toPTree()); } return tree; } /// Outputs a string representation of the Bounds instance to std::cout void dump() const { std::cout << *this; } }; template<class T> std::ostream& operator<<(std::ostream& ostr, const Bounds<T>& bounds) { ostr << "("; for (std::size_t d = 0; d < bounds.size(); ++d) { const Range<T>& r = bounds.dimensions()[d]; ostr << r; if (d!=bounds.size()-1) ostr << ", "; } ostr << ")"; return ostr; } extern PDAL_DLL std::istream& operator>>(std::istream& istr, Bounds<double>& bounds); } // namespace pdal // Needed for C++ DLL exports #ifdef PDAL_COMPILER_MSVC template class PDAL_DLL pdal::Range<double>; template class PDAL_DLL pdal::Bounds<double>; #endif #endif <|endoftext|>
<commit_before>/* sunfish.cpp * * Kubo Ryosuke */ #include "sunfish.h" #include "config.h" #include "console/ConsoleManager.h" #include "program_options/ProgramOptions.h" #include "logger/Logger.h" #include <iostream> #include <string> using namespace sunfish; int play(const ConsoleManager::Config&); // book.cpp int generateBook(const std::string& directory); // network.cpp int network(); // learning.cpp int learn(); int analyzeEvalBin(); // solve.cpp int solve(const std::vector<std::string>& problems, const ConsoleManager::Config&); // profile.cpp int profile(const ConsoleManager::Config&, bool); // test.cpp int test(); // dev.cpp int exprMoveGenSpeed(); int generateZobrist(); int checkMoveGen(); /** * entry point */ int main(int argc, char** argv, char** /*envp*/) { std::cout << SUNFISH_NAME << ' '; std::cout << SUNFISH_VERSION << '\n'; std::cout << SUNFISH_COPYRIGHT << '\n'; std::cout << std::endl; // program options ProgramOptions po; po.addOption("in", "i", "record path", true); po.addOption("out", "o", "record path", true); po.addOption("black", "b", "[auto/manual]", true); po.addOption("white", "w", "[auto/manual]", true); po.addOption("depth", "d", "max depth (default: 15)", true); po.addOption("time", "t", "max time for 1 move (default: 3)", true); po.addOption("worker", "r", "the number of worker threads", true); po.addOption("book", "generate book", true); po.addOption("network", "n", "network mode"); #ifndef NLEARN po.addOption("learn", "l", "learning"); po.addOption("analyze", "a", ""); #endif // NLEARN po.addOption("problem", "p", "solve problems"); po.addOption("profile", "solve problems"); po.addOption("profile1", "solve one problem"); #ifndef NDEBUG po.addOption("test", "unit test"); po.addOption("dev", "development method", true); #endif po.addOption("help", "h", "show this help."); po.parse(argc, argv); for (const auto& invalidArg : po.getInvalidArgs()) { std::cerr << "WARNING: `" << invalidArg.arg << "' is invalid argument: " << invalidArg.reason << std::endl; } if (po.has("help")) { // show help std::cerr << po.help() << std::endl; return 0; } else if (po.has("book")) { std::string directory = po.getValue("book"); return generateBook(directory); } else if (po.has("network")) { return network(); #ifndef NLEARN } else if (po.has("learn")) { return learn(); } else if (po.has("analyze")) { return analyzeEvalBin(); #endif // NLEARN #ifndef NDEBUG } else if (po.has("test")) { // unit test return test(); } else if (po.has("dev")) { // development std::string code = po.getValue("dev"); if (code == "gen_speed_test") { return exprMoveGenSpeed(); } else if (code == "zobrist") { return generateZobrist(); } else if (code == "gen_check") { return checkMoveGen(); } else { std::cerr << '"' << code << "\" is unknown code." << std::endl; return 1; } #endif } auto config = ConsoleManager::getDefaultConfig(); // 起動時に読み込む棋譜ファイル if (po.has("in")) { config.inFileName = po.getValue("in"); config.autoBlack = false; config.autoWhite = false; } // 自動保存する棋譜ファイル if (po.has("out")) { config.outFileName = po.getValue("out"); } // 先手番自動対局 or マニュアル if (po.has("black")) { std::string value = po.getValue("black"); if (value == "auto") { config.autoBlack = true; } else if (value == "manual") { config.autoBlack = false; } else { std::cerr << value << " is unknown value for --black option." << std::endl; } } // 後手番自動対局 or マニュアル if (po.has("white")) { std::string value = po.getValue("white"); if (value == "auto") { config.autoWhite = true; } else if (value == "manual") { config.autoWhite = false; } else { std::cerr << value << " is unknown value for --white option." << std::endl; } } // 最大探索深さ if (po.has("depth")) { int depth = std::stoi(po.getValue("depth")); config.maxDepth = depth; } // worker if (po.has("worker")) { int worker = std::stoi(po.getValue("worker")); config.worker = worker; } // 最大思考時間 if (po.has("time")) { config.limitSeconds = std::stod(po.getValue("time")); } if (po.has("problem")) { // 問題解答 return solve(po.getStdArgs(), config); } if (po.has("profile")) { // profiling return profile(config, true); } if (po.has("profile1")) { // profiling return profile(config, false); } return play(config); } /** * コンソール上での対局を行います。 */ int play(const ConsoleManager::Config& config) { // init loggers Loggers::error.addStream(std::cerr, ESC_SEQ_COLOR_RED, ESC_SEQ_COLOR_RESET); Loggers::warning.addStream(std::cerr, ESC_SEQ_COLOR_YELLOW, ESC_SEQ_COLOR_RESET); Loggers::message.addStream(std::cerr); Loggers::send.addStream(std::cerr, true, true, ESC_SEQ_COLOR_BLUE, ESC_SEQ_COLOR_RESET); Loggers::receive.addStream(std::cerr, true, true, ESC_SEQ_COLOR_MAGENTA, ESC_SEQ_COLOR_RESET); #ifndef NDEBUG Loggers::debug.addStream(std::cerr, ESC_SEQ_COLOR_CYAN, ESC_SEQ_COLOR_RESET); Loggers::test.addStream(std::cerr, ESC_SEQ_COLOR_GREEN, ESC_SEQ_COLOR_RESET); Loggers::develop.addStream(std::cerr, ESC_SEQ_COLOR_WHITE, ESC_SEQ_COLOR_RESET); #endif ConsoleManager console; console.setConfig(config); bool ok = console.play(); return ok ? 0 : 1; } <commit_msg>Fix output stream<commit_after>/* sunfish.cpp * * Kubo Ryosuke */ #include "sunfish.h" #include "config.h" #include "console/ConsoleManager.h" #include "program_options/ProgramOptions.h" #include "logger/Logger.h" #include <iostream> #include <string> using namespace sunfish; int play(const ConsoleManager::Config&); // book.cpp int generateBook(const std::string& directory); // network.cpp int network(); // learning.cpp int learn(); int analyzeEvalBin(); // solve.cpp int solve(const std::vector<std::string>& problems, const ConsoleManager::Config&); // profile.cpp int profile(const ConsoleManager::Config&, bool); // test.cpp int test(); // dev.cpp int exprMoveGenSpeed(); int generateZobrist(); int checkMoveGen(); /** * entry point */ int main(int argc, char** argv, char** /*envp*/) { std::cerr << SUNFISH_NAME << ' '; std::cerr << SUNFISH_VERSION << '\n'; std::cerr << SUNFISH_COPYRIGHT << '\n'; std::cerr << std::endl; // program options ProgramOptions po; po.addOption("in", "i", "record path", true); po.addOption("out", "o", "record path", true); po.addOption("black", "b", "[auto/manual]", true); po.addOption("white", "w", "[auto/manual]", true); po.addOption("depth", "d", "max depth (default: 15)", true); po.addOption("time", "t", "max time for 1 move (default: 3)", true); po.addOption("worker", "r", "the number of worker threads", true); po.addOption("book", "generate book", true); po.addOption("network", "n", "network mode"); #ifndef NLEARN po.addOption("learn", "l", "learning"); po.addOption("analyze", "a", ""); #endif // NLEARN po.addOption("problem", "p", "solve problems"); po.addOption("profile", "solve problems"); po.addOption("profile1", "solve one problem"); #ifndef NDEBUG po.addOption("test", "unit test"); po.addOption("dev", "development method", true); #endif po.addOption("help", "h", "show this help."); po.parse(argc, argv); for (const auto& invalidArg : po.getInvalidArgs()) { std::cerr << "WARNING: `" << invalidArg.arg << "' is invalid argument: " << invalidArg.reason << std::endl; } if (po.has("help")) { // show help std::cerr << po.help() << std::endl; return 0; } else if (po.has("book")) { std::string directory = po.getValue("book"); return generateBook(directory); } else if (po.has("network")) { return network(); #ifndef NLEARN } else if (po.has("learn")) { return learn(); } else if (po.has("analyze")) { return analyzeEvalBin(); #endif // NLEARN #ifndef NDEBUG } else if (po.has("test")) { // unit test return test(); } else if (po.has("dev")) { // development std::string code = po.getValue("dev"); if (code == "gen_speed_test") { return exprMoveGenSpeed(); } else if (code == "zobrist") { return generateZobrist(); } else if (code == "gen_check") { return checkMoveGen(); } else { std::cerr << '"' << code << "\" is unknown code." << std::endl; return 1; } #endif } auto config = ConsoleManager::getDefaultConfig(); // 起動時に読み込む棋譜ファイル if (po.has("in")) { config.inFileName = po.getValue("in"); config.autoBlack = false; config.autoWhite = false; } // 自動保存する棋譜ファイル if (po.has("out")) { config.outFileName = po.getValue("out"); } // 先手番自動対局 or マニュアル if (po.has("black")) { std::string value = po.getValue("black"); if (value == "auto") { config.autoBlack = true; } else if (value == "manual") { config.autoBlack = false; } else { std::cerr << value << " is unknown value for --black option." << std::endl; } } // 後手番自動対局 or マニュアル if (po.has("white")) { std::string value = po.getValue("white"); if (value == "auto") { config.autoWhite = true; } else if (value == "manual") { config.autoWhite = false; } else { std::cerr << value << " is unknown value for --white option." << std::endl; } } // 最大探索深さ if (po.has("depth")) { int depth = std::stoi(po.getValue("depth")); config.maxDepth = depth; } // worker if (po.has("worker")) { int worker = std::stoi(po.getValue("worker")); config.worker = worker; } // 最大思考時間 if (po.has("time")) { config.limitSeconds = std::stod(po.getValue("time")); } if (po.has("problem")) { // 問題解答 return solve(po.getStdArgs(), config); } if (po.has("profile")) { // profiling return profile(config, true); } if (po.has("profile1")) { // profiling return profile(config, false); } return play(config); } /** * コンソール上での対局を行います。 */ int play(const ConsoleManager::Config& config) { // init loggers Loggers::error.addStream(std::cerr, ESC_SEQ_COLOR_RED, ESC_SEQ_COLOR_RESET); Loggers::warning.addStream(std::cerr, ESC_SEQ_COLOR_YELLOW, ESC_SEQ_COLOR_RESET); Loggers::message.addStream(std::cerr); Loggers::send.addStream(std::cerr, true, true, ESC_SEQ_COLOR_BLUE, ESC_SEQ_COLOR_RESET); Loggers::receive.addStream(std::cerr, true, true, ESC_SEQ_COLOR_MAGENTA, ESC_SEQ_COLOR_RESET); #ifndef NDEBUG Loggers::debug.addStream(std::cerr, ESC_SEQ_COLOR_CYAN, ESC_SEQ_COLOR_RESET); Loggers::test.addStream(std::cerr, ESC_SEQ_COLOR_GREEN, ESC_SEQ_COLOR_RESET); Loggers::develop.addStream(std::cerr, ESC_SEQ_COLOR_WHITE, ESC_SEQ_COLOR_RESET); #endif ConsoleManager console; console.setConfig(config); bool ok = console.play(); return ok ? 0 : 1; } <|endoftext|>
<commit_before>#include "ModuleManager.hpp" #include <QPluginLoader> #include <QApplication> #include <QObject> #include <QDir> #include <QObjectList> #include <QStringList> #include <string> #include "Logger.hpp" #include "ModuleBase.hpp" using namespace uipf; using namespace std; // loads the configuration and stores in the ModuleManager /* conf Configuration file, which has to be executed */ ModuleManager::ModuleManager(Configuration conf) : config_(conf) { initModules(); } // executes the Configuration file /* */ void ModuleManager::run(){ // TODO sort processing steps // get processing chain map<string, ProcessingStep> chain = config_.getProcessingChain(); Context context; // iterate over all modules and run them map<string, ProcessingStep>::iterator it = chain.begin(); for (; it!=chain.end(); ++it) { // load the module ModuleInterface* mod = loadModule(it->second.module); ModuleBase* modbase = dynamic_cast<ModuleBase*>(mod); if (modbase) modbase->setContext(&context); // TODO fill outputs with inputs from other modules map<string, Data::ptr > inputs; map<string, Data::ptr > outputs; LOG_I( "Running step '" + it->first + "'..." ); mod->run(inputs, it->second.params, outputs); LOG_I( "Done with step '" + it->first + "'." ); // TODO store outputs somewhere } } void ModuleManager::initModules() { QDir pluginsDir = QDir(qApp->applicationDirPath()); foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { Logger::instance()->Info("found: " + fileName.toStdString()); ModuleInterface* iModule = qobject_cast<ModuleInterface* >(plugin); //2DO: use metadata as key plugins_.insert( std::pair<std::string, ModuleInterface* >(iModule->name(), iModule) ); } } } ModuleInterface* ModuleManager::loadModule(const std::string& name){ Logger::instance()->Info("loadModule: " + name); return plugins_[name]; //2DO: safety, uppercase lowercase etc. } MetaData ModuleManager::getModuleMetaData(const std::string& name){ // TODO this is dummy map<string, Type> in; in.insert( pair<string, Type>("image", MATRIX) ); map<string, Type> out; out.insert( pair<string, Type>("image", MATRIX) ); MetaData meta("Dummy module description for " + name, in, out); return meta; } <commit_msg>implemented sorting + input/output matching in module manager<commit_after>#include "ModuleManager.hpp" #include <QPluginLoader> #include <QApplication> #include <QObject> #include <QDir> #include <QObjectList> #include <QStringList> #include <string> #include "Logger.hpp" #include "ModuleBase.hpp" using namespace uipf; using namespace std; // loads the configuration and stores in the ModuleManager /* conf Configuration file, which has to be executed */ ModuleManager::ModuleManager(Configuration conf) : config_(conf) { initModules(); } // executes the Configuration file /* */ void ModuleManager::run(){ // get processing chain map<string, ProcessingStep> chain = config_.getProcessingChain(); map<string, ProcessingStep> chainTmp; chainTmp.insert(chain.begin(), chain.end()); // contains the names of the processing steps in the correct order vector<string> sortedChain; // iterate over all processing steps and order them while(!chainTmp.empty()){ map<string, ProcessingStep>::iterator itProSt = chainTmp.begin(); for (; itProSt!=chainTmp.end(); ++itProSt) { // add all modules without any dependencies if(itProSt->second.inputs.size() == 0){ sortedChain.push_back(itProSt->first); chainTmp.erase(itProSt); } else { // go through dependencies, and add only the modules, where module // on which they depend have already been added map<string, pair<string,string> >::iterator it = itProSt->second.inputs.begin(); int i = 1; for (; it!=itProSt->second.inputs.end(); ++it) { if (sortedChain.count(it->second.first)){ i *=1; } else{ i *=0; } } if (i == 1){ sortedChain.push_back(itProSt->first); chainTmp.erase(itProSt); } } } } Context context; // contains the outputs of the processing steps map<string, map<string, Data::ptr> > stepsOutputs; // run over the sortedChain and run the modules in the order given by the chain for (int i=0; i<sortedChain.size(); i++){ ProcessingStep proSt = chain[sortedChain[i]]; // load the module ModuleInterface* mod = loadModule(proSt.module); ModuleBase* modbase = dynamic_cast<ModuleBase*>(mod); if (modbase){ modbase->setContext(&context); } map<string, Data::ptr > inputs; map<string, Data::ptr > outputs; // fill the inputs of the current processing step map<string, pair<string, string> >::iterator it = proSt.inputs.begin(); for (; it!=proSt.inputs.end(); ++it) { inputs.insert(pair<string, Data::ptr> (it->first, stepOutputs[it->second.first][it->second.second])); } LOG_I( "Running step '" + proSt.name + "'..." ); mod->run(inputs, proSt.params, outputs); LOG_I( "Done with step '" + proSt.name + "'." ); // fill the outputs of the current processing step stepOutputs.insert(pair<string, map<string, Data::ptr> > (proSt.name, outputs)); } } void ModuleManager::initModules() { QDir pluginsDir = QDir(qApp->applicationDirPath()); foreach (QString fileName, pluginsDir.entryList(QDir::Files)) { QPluginLoader loader(pluginsDir.absoluteFilePath(fileName)); QObject *plugin = loader.instance(); if (plugin) { Logger::instance()->Info("found: " + fileName.toStdString()); ModuleInterface* iModule = qobject_cast<ModuleInterface* >(plugin); //2DO: use metadata as key plugins_.insert( std::pair<std::string, ModuleInterface* >(iModule->name(), iModule) ); } } } ModuleInterface* ModuleManager::loadModule(const std::string& name){ Logger::instance()->Info("loadModule: " + name); return plugins_[name]; //2DO: safety, uppercase lowercase etc. } MetaData ModuleManager::getModuleMetaData(const std::string& name){ // TODO this is dummy map<string, Type> in; in.insert( pair<string, Type>("image", MATRIX) ); map<string, Type> out; out.insert( pair<string, Type>("image", MATRIX) ); MetaData meta("Dummy module description for " + name, in, out); return meta; } <|endoftext|>
<commit_before>#include "pch.h" #include "slide_menu.h" SlideMenu::SlideMenu() : _currentItemIndex(INVALID_ITEM_INDEX) , _animationDuration(0.2f) , _animationInterpolator(gameplay::Curve::QUARTIC_IN_OUT) , _itemScrollingClip(NULL) { } SlideMenu::~SlideMenu() { } const char * SlideMenu::getTypeName() const { return "SlideMenu"; } gameplay::Control * SlideMenu::create(gameplay::Theme::Style* style, gameplay::Properties* properties) { SlideMenu * res = new SlideMenu(); res->initialize(res->getTypeName(), style, properties); return res; } void SlideMenu::initialize(const char* typeName, gameplay::Theme::Style* style, gameplay::Properties* properties) { gameplay::Container::initialize(typeName, style, properties); if (properties) { const char * interpolator = properties->getString("animationInterpolator"); if (interpolator) { int type = gameplay::Curve::getInterpolationType(interpolator); if (type != -1) _animationInterpolator = static_cast<gameplay::Curve::InterpolationType>(type); } float duration = properties->getFloat("animationDuration"); if (duration > 0) _animationDuration = duration; } } void SlideMenu::scrollToItem(unsigned itemIndex, bool immediately) { if (itemIndex >= getControlCount() || itemIndex == _currentItemIndex) return; if (_itemScrollingClip && _itemScrollingClip->isPlaying()) { _itemScrollingClip->removeEndListener(this); _itemScrollingClip->stop(); _itemScrollingClip = NULL; } unsigned int lastItem = _currentItemIndex; if (_currentItemIndex != itemIndex) { _currentItemIndex = itemIndex; notifyListeners(gameplay::Control::Listener::VALUE_CHANGED); } if (!immediately && lastItem < getControlCount()) { auto fadeAnimation = _fadeAnimations.find(_controls[itemIndex]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } float from = _controls[itemIndex]->isVisible() ? _controls[itemIndex]->getOpacity() : 0.0f; float to = 1.0f; _fadeAnimations[_controls[itemIndex]] = _controls[itemIndex]->createAnimationFromTo("scroll-fade-in", ANIMATE_OPACITY, &from, &to, gameplay::Curve::LINEAR, _animationDuration)->getClip(); _fadeAnimations[_controls[itemIndex]]->play(); itemFadeIn(itemIndex); fadeAnimation = _fadeAnimations.find(_controls[lastItem]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } from = _controls[lastItem]->isVisible() ? _controls[lastItem]->getOpacity() : 1.0f; to = 0.0f; _fadeAnimations[_controls[lastItem]] = _controls[lastItem]->createAnimationFromTo("scroll-fade-out", ANIMATE_OPACITY, &from, &to, gameplay::Curve::LINEAR, _animationDuration)->getClip(); _fadeAnimations[_controls[lastItem]]->addEndListener(this); _fadeAnimations[_controls[lastItem]]->play(); itemFadeOut(lastItem); for (unsigned i = 0; i < getControlCount(); i++) { bool visible = i == _currentItemIndex || i == lastItem; // stop all fade animations for items that doesn't participate in this sliding if (_controls[i]->isVisible() && !visible) { fadeAnimation = _fadeAnimations.find(_controls[i]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } } _controls[i]->setVisible(visible); } from = 0.0f; to = 0.0f; if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { if ((_alignment & ALIGN_RIGHT) != 0) { if (itemIndex < lastItem) { from = 0.0f; to = _controls[lastItem]->getWidth() + _controls[lastItem]->getMargin().right + _controls[lastItem]->getMargin().left; } else { GP_ASSERT(itemIndex > lastItem); from = _controls[itemIndex]->getWidth() + _controls[itemIndex]->getMargin().right + _controls[itemIndex]->getMargin().left; to = 0.0f; } } else if ((_alignment & ALIGN_LEFT) != 0) { if (itemIndex < lastItem) { from = _controls[itemIndex]->getWidth() + _controls[itemIndex]->getMargin().right + _controls[itemIndex]->getMargin().left; to = 0.0f; } else { GP_ASSERT(itemIndex > lastItem); from = 0.0f; to = _controls[lastItem]->getWidth() + _controls[lastItem]->getMargin().right + _controls[lastItem]->getMargin().left; } } } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { if ((_alignment & ALIGN_BOTTOM) != 0) { if (itemIndex < lastItem) { from = 0.0f; to = _controls[lastItem]->getHeight() + _controls[lastItem]->getMargin().top + _controls[lastItem]->getMargin().bottom; } else { GP_ASSERT(itemIndex > lastItem); from = _controls[itemIndex]->getHeight() + _controls[itemIndex]->getMargin().top + _controls[itemIndex]->getMargin().bottom; to = 0.0f; } } else if ((_alignment & ALIGN_TOP) != 0) { if (itemIndex < lastItem) { from = _controls[itemIndex]->getHeight() + _controls[itemIndex]->getMargin().top + _controls[itemIndex]->getMargin().bottom; to = 0.0f; } else { GP_ASSERT(itemIndex > lastItem); from = 0.0f; to = _controls[lastItem]->getHeight() + _controls[lastItem]->getMargin().top + _controls[lastItem]->getMargin().bottom; } } } gameplay::Animation * animation = createAnimationFromTo("menu-slide", ANIMATE_MENU_SLIDE, &from, &to, _animationInterpolator, _animationDuration); _itemScrollingClip = animation->getClip(); _itemScrollingClip->play(); _itemScrollingClip->addEndListener(this); } else { for (unsigned i = 0; i < getControlCount(); i++) _controls[i]->setVisible(i == _currentItemIndex); } } void SlideMenu::previewItem(unsigned itemIndex) { // do not preview any items while scrolling if (_itemScrollingClip && _itemScrollingClip->isPlaying()) return; unsigned i = 0; gameplay::Theme::Margin extraMargin; for (i = 0; i < getControlCount(); i++) { if (i == _currentItemIndex) continue; auto currentFadeAnimation = _fadeAnimations.find(_controls[i]); if (_controls[i]->isVisible() && i != itemIndex) { float from = _controls[i]->getOpacity(); float to = 0.0f; if (currentFadeAnimation != _fadeAnimations.end()) { (*currentFadeAnimation).second->removeEndListener(this); (*currentFadeAnimation).second->stop(); } _fadeAnimations[_controls[i]] = _controls[i]->createAnimationFromTo("preview-fade-out", ANIMATE_OPACITY, &from, &to, gameplay::Curve::LINEAR, _animationDuration)->getClip(); _fadeAnimations[_controls[i]]->addEndListener(this); _fadeAnimations[_controls[i]]->play(); itemFadeOut(i); } else if (i == itemIndex) { float from = _controls[i]->isVisible() ? _controls[i]->getOpacity() : 0.0f; float to = 1.0f; if (currentFadeAnimation != _fadeAnimations.end()) { (*currentFadeAnimation).second->removeEndListener(this); (*currentFadeAnimation).second->stop(); } _controls[i]->setVisible(true); _fadeAnimations[_controls[i]] = _controls[i]->createAnimationFromTo("preview-fade-in", ANIMATE_OPACITY, &from, &to, gameplay::Curve::LINEAR, _animationDuration)->getClip(); _fadeAnimations[_controls[i]]->play(); itemFadeIn(i); } if (_controls[i]->isVisible()) { if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { float extraWidth = _controls[i]->getWidth() + _controls[i]->getMargin().right + _controls[i]->getMargin().left; if ((_alignment & ALIGN_LEFT) != 0 && i < _currentItemIndex) extraMargin.left -= extraWidth; else if ((_alignment & ALIGN_RIGHT) != 0 && i > _currentItemIndex) extraMargin.right -= extraWidth; } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { float extraWidth = _controls[i]->getHeight() + _controls[i]->getMargin().top + _controls[i]->getMargin().bottom; if ((_alignment & ALIGN_TOP) != 0 && i < _currentItemIndex) extraMargin.top -= extraWidth; else if ((_alignment & ALIGN_BOTTOM) != 0 && i > _currentItemIndex) extraMargin.bottom -= extraWidth; } } } gameplay::Container::setMargin(_defaultMargin.top + extraMargin.top, _defaultMargin.bottom + extraMargin.bottom, _defaultMargin.left + extraMargin.left, _defaultMargin.right + extraMargin.right); } void SlideMenu::bindMenuButton(gameplay::Control * control, unsigned int menuIndex) { bindControlEvent(control, gameplay::Control::Listener::PRESS, [=](gameplay::Control*){ this->previewItem(menuIndex); }); bindControlEvent(control, gameplay::Control::Listener::RELEASE, [=](gameplay::Control*){ this->previewItem(SlideMenu::INVALID_ITEM_INDEX); }); bindControlEvent(control, gameplay::Control::Listener::ENTER, [=](gameplay::Control* control){ if (control->getState() == gameplay::Control::ACTIVE) this->previewItem(menuIndex); }); bindControlEvent(control, gameplay::Control::Listener::LEAVE, [=](gameplay::Control* control){ if (control->getState() == gameplay::Control::ACTIVE) this->previewItem(SlideMenu::INVALID_ITEM_INDEX); }); bindControlEvent(control, gameplay::Control::Listener::CLICK, [=](gameplay::Control*){ this->scrollToItem(menuIndex); }); } void SlideMenu::unbindMenuButton(gameplay::Control * control) { unbindControlEvent(control, gameplay::Control::Listener::PRESS); unbindControlEvent(control, gameplay::Control::Listener::RELEASE); unbindControlEvent(control, gameplay::Control::Listener::ENTER); unbindControlEvent(control, gameplay::Control::Listener::LEAVE); unbindControlEvent(control, gameplay::Control::Listener::CLICK); } void SlideMenu::setMargin(float top, float bottom, float left, float right) { _defaultMargin.top = top; _defaultMargin.bottom = bottom; _defaultMargin.left = left; _defaultMargin.right = right; gameplay::Container::setMargin(top, bottom, left, right); } unsigned int SlideMenu::getAnimationPropertyComponentCount(int propertyId) const { switch (propertyId) { case ANIMATE_MENU_SLIDE: return 1; default: return Container::getAnimationPropertyComponentCount(propertyId); } } void SlideMenu::getAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value) { GP_ASSERT(value); switch (propertyId) { case ANIMATE_MENU_SLIDE: { const gameplay::Theme::Margin& margin = getMargin(); if (margin.left < _defaultMargin.left) value->setFloat(0, _defaultMargin.left - margin.left); else if (margin.right < _defaultMargin.right) value->setFloat(0, _defaultMargin.right - margin.right); else if (margin.top < _defaultMargin.top) value->setFloat(0, _defaultMargin.top - margin.top); else if (margin.bottom < _defaultMargin.bottom) value->setFloat(0, _defaultMargin.bottom - margin.bottom); } break; default: Container::getAnimationPropertyValue(propertyId, value); break; } } void SlideMenu::setAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value, float blendWeight) { GP_ASSERT(value); switch (propertyId) { case ANIMATE_MENU_SLIDE: if (_currentItemIndex < getControlCount()) { float margin = value->getFloat(0); gameplay::Theme::Margin extraMargin; if (_currentItemIndex != INVALID_ITEM_INDEX) { if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { if ((_alignment & ALIGN_RIGHT) != 0) extraMargin.right = -margin; else if ((_alignment & ALIGN_LEFT) != 0) extraMargin.left = -margin; } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { if ((_alignment & ALIGN_BOTTOM) != 0) extraMargin.bottom = -margin; else if ((_alignment & ALIGN_TOP) != 0) extraMargin.top = -margin; } } gameplay::Container::setMargin(_defaultMargin.top + extraMargin.top, _defaultMargin.bottom + extraMargin.bottom, _defaultMargin.left + extraMargin.left, _defaultMargin.right + extraMargin.right); } break; default: Container::setAnimationPropertyValue(propertyId, value, blendWeight); break; } } void SlideMenu::animationEvent(gameplay::AnimationClip* clip, gameplay::AnimationClip::Listener::EventType type) { GP_ASSERT(type == gameplay::AnimationClip::Listener::END); for (unsigned i = 0; i < getControlCount(); i++) _controls[i]->setVisible(i == _currentItemIndex); gameplay::Container::setMargin(_defaultMargin.top, _defaultMargin.bottom, _defaultMargin.left, _defaultMargin.right); }<commit_msg>using the same default animation values for SlideMenu as for other controls<commit_after>#include "pch.h" #include "slide_menu.h" SlideMenu::SlideMenu() : _currentItemIndex(INVALID_ITEM_INDEX) , _animationDuration(0.6f) , _animationInterpolator(gameplay::Curve::QUARTIC_IN_OUT) , _itemScrollingClip(NULL) { } SlideMenu::~SlideMenu() { } const char * SlideMenu::getTypeName() const { return "SlideMenu"; } gameplay::Control * SlideMenu::create(gameplay::Theme::Style* style, gameplay::Properties* properties) { SlideMenu * res = new SlideMenu(); res->initialize(res->getTypeName(), style, properties); return res; } void SlideMenu::initialize(const char* typeName, gameplay::Theme::Style* style, gameplay::Properties* properties) { gameplay::Container::initialize(typeName, style, properties); if (properties) { const char * interpolator = properties->getString("animationInterpolator"); if (interpolator) { int type = gameplay::Curve::getInterpolationType(interpolator); if (type != -1) _animationInterpolator = static_cast<gameplay::Curve::InterpolationType>(type); } float duration = properties->getFloat("animationDuration"); if (duration > 0) _animationDuration = duration; } } void SlideMenu::scrollToItem(unsigned itemIndex, bool immediately) { if (itemIndex >= getControlCount() || itemIndex == _currentItemIndex) return; if (_itemScrollingClip && _itemScrollingClip->isPlaying()) { _itemScrollingClip->removeEndListener(this); _itemScrollingClip->stop(); _itemScrollingClip = NULL; } unsigned int lastItem = _currentItemIndex; if (_currentItemIndex != itemIndex) { _currentItemIndex = itemIndex; notifyListeners(gameplay::Control::Listener::VALUE_CHANGED); } if (!immediately && lastItem < getControlCount()) { auto fadeAnimation = _fadeAnimations.find(_controls[itemIndex]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } float from = _controls[itemIndex]->isVisible() ? _controls[itemIndex]->getOpacity() : 0.0f; float to = 1.0f; _fadeAnimations[_controls[itemIndex]] = _controls[itemIndex]->createAnimationFromTo("scroll-fade-in", ANIMATE_OPACITY, &from, &to, _animationInterpolator, _animationDuration)->getClip(); _fadeAnimations[_controls[itemIndex]]->play(); itemFadeIn(itemIndex); fadeAnimation = _fadeAnimations.find(_controls[lastItem]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } from = _controls[lastItem]->isVisible() ? _controls[lastItem]->getOpacity() : 1.0f; to = 0.0f; _fadeAnimations[_controls[lastItem]] = _controls[lastItem]->createAnimationFromTo("scroll-fade-out", ANIMATE_OPACITY, &from, &to, _animationInterpolator, _animationDuration)->getClip(); _fadeAnimations[_controls[lastItem]]->addEndListener(this); _fadeAnimations[_controls[lastItem]]->play(); itemFadeOut(lastItem); for (unsigned i = 0; i < getControlCount(); i++) { bool visible = i == _currentItemIndex || i == lastItem; // stop all fade animations for items that doesn't participate in this sliding if (_controls[i]->isVisible() && !visible) { fadeAnimation = _fadeAnimations.find(_controls[i]); if (fadeAnimation != _fadeAnimations.end()) { (*fadeAnimation).second->removeEndListener(this); (*fadeAnimation).second->stop(); } } _controls[i]->setVisible(visible); } from = 0.0f; to = 0.0f; if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { if ((_alignment & ALIGN_RIGHT) != 0) { if (itemIndex < lastItem) { from = 0.0f; to = _controls[lastItem]->getWidth() + _controls[lastItem]->getMargin().right + _controls[lastItem]->getMargin().left; } else { GP_ASSERT(itemIndex > lastItem); from = _controls[itemIndex]->getWidth() + _controls[itemIndex]->getMargin().right + _controls[itemIndex]->getMargin().left; to = 0.0f; } } else if ((_alignment & ALIGN_LEFT) != 0) { if (itemIndex < lastItem) { from = _controls[itemIndex]->getWidth() + _controls[itemIndex]->getMargin().right + _controls[itemIndex]->getMargin().left; to = 0.0f; } else { GP_ASSERT(itemIndex > lastItem); from = 0.0f; to = _controls[lastItem]->getWidth() + _controls[lastItem]->getMargin().right + _controls[lastItem]->getMargin().left; } } } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { if ((_alignment & ALIGN_BOTTOM) != 0) { if (itemIndex < lastItem) { from = 0.0f; to = _controls[lastItem]->getHeight() + _controls[lastItem]->getMargin().top + _controls[lastItem]->getMargin().bottom; } else { GP_ASSERT(itemIndex > lastItem); from = _controls[itemIndex]->getHeight() + _controls[itemIndex]->getMargin().top + _controls[itemIndex]->getMargin().bottom; to = 0.0f; } } else if ((_alignment & ALIGN_TOP) != 0) { if (itemIndex < lastItem) { from = _controls[itemIndex]->getHeight() + _controls[itemIndex]->getMargin().top + _controls[itemIndex]->getMargin().bottom; to = 0.0f; } else { GP_ASSERT(itemIndex > lastItem); from = 0.0f; to = _controls[lastItem]->getHeight() + _controls[lastItem]->getMargin().top + _controls[lastItem]->getMargin().bottom; } } } gameplay::Animation * animation = createAnimationFromTo("menu-slide", ANIMATE_MENU_SLIDE, &from, &to, _animationInterpolator, _animationDuration); _itemScrollingClip = animation->getClip(); _itemScrollingClip->play(); _itemScrollingClip->addEndListener(this); } else { for (unsigned i = 0; i < getControlCount(); i++) _controls[i]->setVisible(i == _currentItemIndex); } } void SlideMenu::previewItem(unsigned itemIndex) { // do not preview any items while scrolling if (_itemScrollingClip && _itemScrollingClip->isPlaying()) return; unsigned i = 0; gameplay::Theme::Margin extraMargin; for (i = 0; i < getControlCount(); i++) { if (i == _currentItemIndex) continue; auto currentFadeAnimation = _fadeAnimations.find(_controls[i]); if (_controls[i]->isVisible() && i != itemIndex) { float from = _controls[i]->getOpacity(); float to = 0.0f; if (currentFadeAnimation != _fadeAnimations.end()) { (*currentFadeAnimation).second->removeEndListener(this); (*currentFadeAnimation).second->stop(); } _fadeAnimations[_controls[i]] = _controls[i]->createAnimationFromTo("preview-fade-out", ANIMATE_OPACITY, &from, &to, _animationInterpolator, _animationDuration)->getClip(); _fadeAnimations[_controls[i]]->addEndListener(this); _fadeAnimations[_controls[i]]->play(); itemFadeOut(i); } else if (i == itemIndex) { float from = _controls[i]->isVisible() ? _controls[i]->getOpacity() : 0.0f; float to = 1.0f; if (currentFadeAnimation != _fadeAnimations.end()) { (*currentFadeAnimation).second->removeEndListener(this); (*currentFadeAnimation).second->stop(); } _controls[i]->setVisible(true); _fadeAnimations[_controls[i]] = _controls[i]->createAnimationFromTo("preview-fade-in", ANIMATE_OPACITY, &from, &to, _animationInterpolator, _animationDuration)->getClip(); _fadeAnimations[_controls[i]]->play(); itemFadeIn(i); } if (_controls[i]->isVisible()) { if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { float extraWidth = _controls[i]->getWidth() + _controls[i]->getMargin().right + _controls[i]->getMargin().left; if ((_alignment & ALIGN_LEFT) != 0 && i < _currentItemIndex) extraMargin.left -= extraWidth; else if ((_alignment & ALIGN_RIGHT) != 0 && i > _currentItemIndex) extraMargin.right -= extraWidth; } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { float extraWidth = _controls[i]->getHeight() + _controls[i]->getMargin().top + _controls[i]->getMargin().bottom; if ((_alignment & ALIGN_TOP) != 0 && i < _currentItemIndex) extraMargin.top -= extraWidth; else if ((_alignment & ALIGN_BOTTOM) != 0 && i > _currentItemIndex) extraMargin.bottom -= extraWidth; } } } gameplay::Container::setMargin(_defaultMargin.top + extraMargin.top, _defaultMargin.bottom + extraMargin.bottom, _defaultMargin.left + extraMargin.left, _defaultMargin.right + extraMargin.right); } void SlideMenu::bindMenuButton(gameplay::Control * control, unsigned int menuIndex) { bindControlEvent(control, gameplay::Control::Listener::PRESS, [=](gameplay::Control*){ this->previewItem(menuIndex); }); bindControlEvent(control, gameplay::Control::Listener::RELEASE, [=](gameplay::Control*){ this->previewItem(SlideMenu::INVALID_ITEM_INDEX); }); bindControlEvent(control, gameplay::Control::Listener::ENTER, [=](gameplay::Control* control){ if (control->getState() == gameplay::Control::ACTIVE) this->previewItem(menuIndex); }); bindControlEvent(control, gameplay::Control::Listener::LEAVE, [=](gameplay::Control* control){ if (control->getState() == gameplay::Control::ACTIVE) this->previewItem(SlideMenu::INVALID_ITEM_INDEX); }); bindControlEvent(control, gameplay::Control::Listener::CLICK, [=](gameplay::Control*){ this->scrollToItem(menuIndex); }); } void SlideMenu::unbindMenuButton(gameplay::Control * control) { unbindControlEvent(control, gameplay::Control::Listener::PRESS); unbindControlEvent(control, gameplay::Control::Listener::RELEASE); unbindControlEvent(control, gameplay::Control::Listener::ENTER); unbindControlEvent(control, gameplay::Control::Listener::LEAVE); unbindControlEvent(control, gameplay::Control::Listener::CLICK); } void SlideMenu::setMargin(float top, float bottom, float left, float right) { _defaultMargin.top = top; _defaultMargin.bottom = bottom; _defaultMargin.left = left; _defaultMargin.right = right; gameplay::Container::setMargin(top, bottom, left, right); } unsigned int SlideMenu::getAnimationPropertyComponentCount(int propertyId) const { switch (propertyId) { case ANIMATE_MENU_SLIDE: return 1; default: return Container::getAnimationPropertyComponentCount(propertyId); } } void SlideMenu::getAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value) { GP_ASSERT(value); switch (propertyId) { case ANIMATE_MENU_SLIDE: { const gameplay::Theme::Margin& margin = getMargin(); if (margin.left < _defaultMargin.left) value->setFloat(0, _defaultMargin.left - margin.left); else if (margin.right < _defaultMargin.right) value->setFloat(0, _defaultMargin.right - margin.right); else if (margin.top < _defaultMargin.top) value->setFloat(0, _defaultMargin.top - margin.top); else if (margin.bottom < _defaultMargin.bottom) value->setFloat(0, _defaultMargin.bottom - margin.bottom); } break; default: Container::getAnimationPropertyValue(propertyId, value); break; } } void SlideMenu::setAnimationPropertyValue(int propertyId, gameplay::AnimationValue* value, float blendWeight) { GP_ASSERT(value); switch (propertyId) { case ANIMATE_MENU_SLIDE: if (_currentItemIndex < getControlCount()) { float margin = value->getFloat(0); gameplay::Theme::Margin extraMargin; if (_currentItemIndex != INVALID_ITEM_INDEX) { if (_layout->getType() == gameplay::Layout::LAYOUT_HORIZONTAL) { if ((_alignment & ALIGN_RIGHT) != 0) extraMargin.right = -margin; else if ((_alignment & ALIGN_LEFT) != 0) extraMargin.left = -margin; } else if (_layout->getType() == gameplay::Layout::LAYOUT_VERTICAL) { if ((_alignment & ALIGN_BOTTOM) != 0) extraMargin.bottom = -margin; else if ((_alignment & ALIGN_TOP) != 0) extraMargin.top = -margin; } } gameplay::Container::setMargin(_defaultMargin.top + extraMargin.top, _defaultMargin.bottom + extraMargin.bottom, _defaultMargin.left + extraMargin.left, _defaultMargin.right + extraMargin.right); } break; default: Container::setAnimationPropertyValue(propertyId, value, blendWeight); break; } } void SlideMenu::animationEvent(gameplay::AnimationClip* clip, gameplay::AnimationClip::Listener::EventType type) { GP_ASSERT(type == gameplay::AnimationClip::Listener::END); for (unsigned i = 0; i < getControlCount(); i++) _controls[i]->setVisible(i == _currentItemIndex); gameplay::Container::setMargin(_defaultMargin.top, _defaultMargin.bottom, _defaultMargin.left, _defaultMargin.right); }<|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2016-2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING #if defined(HAVE_CONFIG_H) #include "config/build-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "compat.h" #include "fs.h" #include "rpc/server.h" #include "init.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include "httpserver.h" #include "httprpc.h" #include "utilstrencodings.h" #include "net.h" #include <unity/appmanager.h> #include <boost/thread.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <stdio.h> #define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */ /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Gulden (https://www.gulden.com), * which enables instant payments to anyone, anywhere in the world. Gulden uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ int exitStatus = EXIT_SUCCESS; bool shutDownFinalised = false; static void handleFinalShutdown() { shutDownFinalised = true; } static void WaitForShutdown() { while (!shutDownFinalised) { MilliSleep(200); } } void handlePostInitMain() { } static void handleAppInitResult(bool bResult) { if (!bResult) { // InitError will have been called with detailed error, which ends up on console exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } handlePostInitMain(); } static bool handlePreInitMain() { return true; } ////////////////////////////////////////////////////////////////////////////// // // Start // static void AppInit(int argc, char* argv[]) { AppLifecycleManager appManager; appManager.signalAppInitializeResult.connect(boost::bind(handleAppInitResult, _1)); appManager.signalAboutToInitMain.connect(&handlePreInitMain); appManager.signalAppShutdownFinished.connect(&handleFinalShutdown); //fixme: (UNITY) - refactor this some more so that init is taken care of inside the app manager (like with qt app) // // Parameters // // If Qt is used, parameters/Gulden.conf are parsed in qt/Gulden.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " " + DAEMON_NAME + " [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HMM_GULDEND); } fprintf(stdout, "%s", strUsage.c_str()); return; } //NB! Must be set before AppInitMain. fNoUI = true; try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str()); exitStatus = EXIT_FAILURE; return; } try { ReadConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); exitStatus = EXIT_FAILURE; return; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); exitStatus = EXIT_FAILURE; return; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see GuldenD -h for a list of options.\n", argv[i]); exitStatus = EXIT_FAILURE; return; } } // -server defaults to true for GuldenD but not for the GUI so do this here SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); //fixme: (UNITY) - This is now duplicated, factor this out into a common helper. // NB! This has to happen before we deamonise // Make sure only a single Gulden process is using the data directory. { fs::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); try { static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) { fprintf(stderr, "ERROR: Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str()); exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } } catch(const boost::interprocess::interprocess_exception& e) { fprintf(stderr, "ERROR: Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str()); exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } } if (GetBoolArg("-daemon", false)) { fprintf(stdout, "Gulden server starting\n"); if (!AppLifecycleManager::gApp->daemonise()) { LogPrintf("Failed to daemonise\n"); exitStatus = EXIT_FAILURE; return; } } appManager.initialize(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } //fixme: (UNITY) - It would be much better to wait on a condition variable here. // Busy poll for shutdown and allow app to exit when we reach there. WaitForShutdown(); } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect GuldenD signal handlers noui_connect(); AppInit(argc, argv); return exitStatus; } //fixme: (HIGH) //Super gross workaround - for some reason our macos build keeps failing to provide '___cpu_model' symbol, so we just define it ourselves as a workaround until we can fix the issue. #ifdef MAC_OSX #include "llvm-cpumodel-hack.cpp" #endif <commit_msg>MISC: Minor renames<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. // // File contains modifications by: The Gulden developers // All modifications: // Copyright (c) 2016-2018 The Gulden developers // Authored by: Malcolm MacLeod (mmacleod@gmx.com) // Distributed under the GULDEN software license, see the accompanying // file COPYING #if defined(HAVE_CONFIG_H) #include "config/build-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "compat.h" #include "fs.h" #include "rpc/server.h" #include "init.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include "httpserver.h" #include "httprpc.h" #include "utilstrencodings.h" #include "net.h" #include <unity/appmanager.h> #include <boost/thread.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <stdio.h> #define _(x) std::string(x)/* Keep the _() around in case gettext or such will be used later to translate non-UI */ /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Novo (https://www.novocurrency.com), * which enables instant payments to anyone, anywhere in the world. Novo uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the Novo license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ int exitStatus = EXIT_SUCCESS; bool shutDownFinalised = false; static void handleFinalShutdown() { shutDownFinalised = true; } static void WaitForShutdown() { while (!shutDownFinalised) { MilliSleep(200); } } void handlePostInitMain() { } static void handleAppInitResult(bool bResult) { if (!bResult) { // InitError will have been called with detailed error, which ends up on console exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } handlePostInitMain(); } static bool handlePreInitMain() { return true; } ////////////////////////////////////////////////////////////////////////////// // // Start // static void AppInit(int argc, char* argv[]) { AppLifecycleManager appManager; appManager.signalAppInitializeResult.connect(boost::bind(handleAppInitResult, _1)); appManager.signalAboutToInitMain.connect(&handlePreInitMain); appManager.signalAppShutdownFinished.connect(&handleFinalShutdown); //fixme: (UNITY) - refactor this some more so that init is taken care of inside the app manager (like with qt app) // // Parameters // // If Qt is used, parameters/.conf are parsed in the qt clients main() implementation ParseParameters(argc, argv); // Process help and version before taking care about datadir if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " " + DAEMON_NAME + " [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HMM_GULDEND); } fprintf(stdout, "%s", strUsage.c_str()); return; } //NB! Must be set before AppInitMain. fNoUI = true; try { if (!fs::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str()); exitStatus = EXIT_FAILURE; return; } try { ReadConfigFile(GetArg("-conf", DEFAULT_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); exitStatus = EXIT_FAILURE; return; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); exitStatus = EXIT_FAILURE; return; } // Error out when loose non-argument tokens are encountered on command line for (int i = 1; i < argc; i++) { if (!IsSwitchChar(argv[i][0])) { fprintf(stderr, "Error: Command line contains unexpected token '%s', see " DAEMON_NAME " -h for a list of options.\n", argv[i]); exitStatus = EXIT_FAILURE; return; } } // -server defaults to true for daemon but not for the GUI so do this here SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); //fixme: (UNITY) - This is now duplicated, factor this out into a common helper. // NB! This has to happen before we deamonise // Make sure only a single process is using the data directory. { fs::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); try { static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) { fprintf(stderr, "ERROR: Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str()); exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } } catch(const boost::interprocess::interprocess_exception& e) { fprintf(stderr, "ERROR: Cannot obtain a lock on data directory %s. %s is probably already running.", GetDataDir().string().c_str(), _(PACKAGE_NAME).c_str()); exitStatus = EXIT_FAILURE; AppLifecycleManager::gApp->shutdown(); return; } } if (GetBoolArg("-daemon", false)) { fprintf(stdout, "%s server starting\n", _(PACKAGE_NAME)); if (!AppLifecycleManager::gApp->daemonise()) { LogPrintf("Failed to daemonise\n"); exitStatus = EXIT_FAILURE; return; } } appManager.initialize(); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } //fixme: (UNITY) - It would be much better to wait on a condition variable here. // Busy poll for shutdown and allow app to exit when we reach there. WaitForShutdown(); } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect daemon signal handlers noui_connect(); AppInit(argc, argv); return exitStatus; } //fixme: (HIGH) //Super gross workaround - for some reason our macos build keeps failing to provide '___cpu_model' symbol, so we just define it ourselves as a workaround until we can fix the issue. #ifdef MAC_OSX #include "llvm-cpumodel-hack.cpp" #endif <|endoftext|>
<commit_before>// // Copyright (c) 2008-2015 the Urho3D project. // // 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 "../Core/Mutex.h" #include "../Core/ProcessUtils.h" #include "../Math/MathDefs.h" #include <cstdio> #include <fcntl.h> #ifdef __APPLE__ #include "TargetConditionals.h" #endif #if defined(IOS) #include <mach/mach_host.h> #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) #include <LibCpuId/libcpuid.h> #endif #ifdef WIN32 #include <windows.h> #include <io.h> #else #include <unistd.h> #endif #if defined(_MSC_VER) #include <float.h> #elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN) // From http://stereopsis.com/FPU.html #define FPU_CW_PREC_MASK 0x0300 #define FPU_CW_PREC_SINGLE 0x0000 #define FPU_CW_PREC_DOUBLE 0x0200 #define FPU_CW_PREC_EXTENDED 0x0300 #define FPU_CW_ROUND_MASK 0x0c00 #define FPU_CW_ROUND_NEAR 0x0000 #define FPU_CW_ROUND_DOWN 0x0400 #define FPU_CW_ROUND_UP 0x0800 #define FPU_CW_ROUND_CHOP 0x0c00 inline unsigned GetFPUState() { unsigned control = 0; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return control; } inline void SetFPUState(unsigned control) { __asm__ __volatile__ ("fldcw %0" : : "m" (control)); } #endif #include "../DebugNew.h" namespace Urho3D { #ifdef WIN32 static bool consoleOpened = false; #endif static String currentLine; static Vector<String> arguments; #if defined(IOS) static void GetCPUData(host_basic_info_data_t* data) { mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount); } #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) static void GetCPUData(struct cpu_id_t* data) { if (cpu_identify(0, data) < 0) { data->num_logical_cpus = 1; data->num_cores = 1; } } #endif void InitFPU() { #if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN) // Make sure FPU is in round-to-nearest, single precision mode // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly #ifdef _MSC_VER _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC); #else unsigned control = GetFPUState(); control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK); control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR); SetFPUState(control); #endif #endif } void ErrorDialog(const String& title, const String& message) { #ifdef WIN32 MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0); #else PrintLine(message, true); #endif } void ErrorExit(const String& message, int exitCode) { if (!message.Empty()) PrintLine(message, true); exit(exitCode); } void OpenConsoleWindow() { #ifdef WIN32 if (consoleOpened) return; AllocConsole(); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT); FILE* outFile = _fdopen(hCrt, "w"); setvbuf(outFile, NULL, _IONBF, 1); *stdout = *outFile; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((size_t)hIn, _O_TEXT); FILE* inFile = _fdopen(hCrt, "r"); setvbuf(inFile, NULL, _IONBF, 128); *stdin = *inFile; consoleOpened = true; #endif } void PrintUnicode(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) #ifdef WIN32 HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); if (stream == INVALID_HANDLE_VALUE) return; WString strW(str); DWORD charsWritten; WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0); #else fprintf(error ? stderr : stdout, "%s", str.CString()); #endif #endif } void PrintUnicodeLine(const String& str, bool error) { PrintUnicode(str + '\n', error); } void PrintLine(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) fprintf(error ? stderr: stdout, "%s\n", str.CString()); #endif } const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument) { arguments.Clear(); unsigned cmdStart = 0, cmdEnd = 0; bool inCmd = false; bool inQuote = false; for (unsigned i = 0; i < cmdLine.Length(); ++i) { if (cmdLine[i] == '\"') inQuote = !inQuote; if (cmdLine[i] == ' ' && !inQuote) { if (inCmd) { inCmd = false; cmdEnd = i; // Do not store the first argument (executable name) if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); skipFirstArgument = false; } } else { if (!inCmd) { inCmd = true; cmdStart = i; } } } if (inCmd) { cmdEnd = cmdLine.Length(); if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); } // Strip double quotes from the arguments for (unsigned i = 0; i < arguments.Size(); ++i) arguments[i].Replace("\"", ""); return arguments; } const Vector<String>& ParseArguments(const char* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const WString& cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const wchar_t* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(int argc, char** argv) { String cmdLine; for (int i = 0; i < argc; ++i) cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]); return ParseArguments(cmdLine); } const Vector<String>& GetArguments() { return arguments; } String GetConsoleInput() { String ret; #ifdef URHO3D_TESTING // When we are running automated tests, reading the console may block. Just return empty in that case return ret; #endif #ifdef WIN32 HANDLE input = GetStdHandle(STD_INPUT_HANDLE); HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE) return ret; // Use char-based input SetConsoleMode(input, ENABLE_PROCESSED_INPUT); INPUT_RECORD record; DWORD events = 0; DWORD readEvents = 0; if (!GetNumberOfConsoleInputEvents(input, &events)) return ret; while (events--) { ReadConsoleInputW(input, &record, 1, &readEvents); if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { unsigned c = record.Event.KeyEvent.uChar.UnicodeChar; if (c) { if (c == '\b') { PrintUnicode("\b \b"); int length = currentLine.LengthUTF8(); if (length) currentLine = currentLine.SubstringUTF8(0, length - 1); } else if (c == '\r') { PrintUnicode("\n"); ret = currentLine; currentLine.Clear(); return ret; } else { // We have disabled echo, so echo manually wchar_t out = c; DWORD charsWritten; WriteConsoleW(output, &out, 1, &charsWritten, 0); currentLine.AppendUTF8(c); } } } } #elif !defined(ANDROID) && !defined(IOS) int flags = fcntl(STDIN_FILENO, F_GETFL); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int ch = fgetc(stdin); if (ch >= 0 && ch != '\n') ret += (char)ch; else break; } #endif return ret; } String GetPlatform() { #if defined(ANDROID) return "Android"; #elif defined(IOS) return "iOS"; #elif defined(WIN32) return "Windows"; #elif defined(__APPLE__) return "Mac OS X"; #elif defined(RPI) return "Raspberry Pi"; #elif defined(EMSCRIPTEN) return "HTML5"; #elif defined(__linux__) return "Linux"; #else return String::EMPTY; #endif } #if defined(ANDROID) || defined(RPI) static unsigned GetArmCPUCount() { FILE* fp; int res, i = -1, j = -1; fp = fopen("/sys/devices/system/cpu/present", "r"); // If failed, return at least 1 if (fp == 0) return 1; res = fscanf(fp, "%d-%d", &i, &j); fclose(fp); if (res == 1 && i == 0) return 1; else if (res == 2 && i == 0) return j + 1; // If failed, return at least 1 return 1; } #endif unsigned GetNumPhysicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) // Hardcoded to dual-core on simulator mode even if the host has more return Min(2, data.physical_cpu); #else return data.physical_cpu; #endif #elif defined(ANDROID) || defined(RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return data.num_cores; #else /// \todo Implement properly return 1; #endif } unsigned GetNumLogicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) return Min(2, data.logical_cpu); #else return data.logical_cpu; #endif #elif defined(ANDROID) || defined (RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return data.num_logical_cpus; #else /// \todo Implement properly return 1; #endif } } <commit_msg>On Windows, when stdout/stderr has been redirected, use fprintf instead of WriteConsoleW() to allow capturing log output from tools. Closes #703.<commit_after>// // Copyright (c) 2008-2015 the Urho3D project. // // 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 "../Core/Mutex.h" #include "../Core/ProcessUtils.h" #include "../Math/MathDefs.h" #include <cstdio> #include <fcntl.h> #ifdef __APPLE__ #include "TargetConditionals.h" #endif #if defined(IOS) #include <mach/mach_host.h> #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) #include <LibCpuId/libcpuid.h> #endif #ifdef WIN32 #include <windows.h> #include <io.h> #else #include <unistd.h> #endif #if defined(_MSC_VER) #include <float.h> #elif !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(EMSCRIPTEN) // From http://stereopsis.com/FPU.html #define FPU_CW_PREC_MASK 0x0300 #define FPU_CW_PREC_SINGLE 0x0000 #define FPU_CW_PREC_DOUBLE 0x0200 #define FPU_CW_PREC_EXTENDED 0x0300 #define FPU_CW_ROUND_MASK 0x0c00 #define FPU_CW_ROUND_NEAR 0x0000 #define FPU_CW_ROUND_DOWN 0x0400 #define FPU_CW_ROUND_UP 0x0800 #define FPU_CW_ROUND_CHOP 0x0c00 inline unsigned GetFPUState() { unsigned control = 0; __asm__ __volatile__ ("fnstcw %0" : "=m" (control)); return control; } inline void SetFPUState(unsigned control) { __asm__ __volatile__ ("fldcw %0" : : "m" (control)); } #endif #include "../DebugNew.h" namespace Urho3D { #ifdef WIN32 static bool consoleOpened = false; #endif static String currentLine; static Vector<String> arguments; #if defined(IOS) static void GetCPUData(host_basic_info_data_t* data) { mach_msg_type_number_t infoCount; infoCount = HOST_BASIC_INFO_COUNT; host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)data, &infoCount); } #elif !defined(ANDROID) && !defined(RPI) && !defined(EMSCRIPTEN) static void GetCPUData(struct cpu_id_t* data) { if (cpu_identify(0, data) < 0) { data->num_logical_cpus = 1; data->num_cores = 1; } } #endif void InitFPU() { #if !defined(URHO3D_LUAJIT) && !defined(ANDROID) && !defined(IOS) && !defined(RPI) && !defined(__x86_64__) && !defined(_M_AMD64) && !defined(EMSCRIPTEN) // Make sure FPU is in round-to-nearest, single precision mode // This ensures Direct3D and OpenGL behave similarly, and all threads behave similarly #ifdef _MSC_VER _controlfp(_RC_NEAR | _PC_24, _MCW_RC | _MCW_PC); #else unsigned control = GetFPUState(); control &= ~(FPU_CW_PREC_MASK | FPU_CW_ROUND_MASK); control |= (FPU_CW_PREC_SINGLE | FPU_CW_ROUND_NEAR); SetFPUState(control); #endif #endif } void ErrorDialog(const String& title, const String& message) { #ifdef WIN32 MessageBoxW(0, WString(message).CString(), WString(title).CString(), 0); #else PrintLine(message, true); #endif } void ErrorExit(const String& message, int exitCode) { if (!message.Empty()) PrintLine(message, true); exit(exitCode); } void OpenConsoleWindow() { #ifdef WIN32 if (consoleOpened) return; AllocConsole(); HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); int hCrt = _open_osfhandle((size_t)hOut, _O_TEXT); FILE* outFile = _fdopen(hCrt, "w"); setvbuf(outFile, NULL, _IONBF, 1); *stdout = *outFile; HANDLE hIn = GetStdHandle(STD_INPUT_HANDLE); hCrt = _open_osfhandle((size_t)hIn, _O_TEXT); FILE* inFile = _fdopen(hCrt, "r"); setvbuf(inFile, NULL, _IONBF, 128); *stdin = *inFile; consoleOpened = true; #endif } void PrintUnicode(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) #ifdef WIN32 // If the output stream has been redirected, use fprintf instead of WriteConsoleW, // though it means that proper Unicode output will not work FILE* out = error ? stderr : stdout; if (!_isatty(_fileno(out))) fprintf(out, "%s", str.CString()); else { HANDLE stream = GetStdHandle(error ? STD_ERROR_HANDLE : STD_OUTPUT_HANDLE); if (stream == INVALID_HANDLE_VALUE) return; WString strW(str); DWORD charsWritten; WriteConsoleW(stream, strW.CString(), strW.Length(), &charsWritten, 0); } #else fprintf(error ? stderr : stdout, "%s", str.CString()); #endif #endif } void PrintUnicodeLine(const String& str, bool error) { PrintUnicode(str + '\n', error); } void PrintLine(const String& str, bool error) { #if !defined(ANDROID) && !defined(IOS) fprintf(error ? stderr: stdout, "%s\n", str.CString()); #endif } const Vector<String>& ParseArguments(const String& cmdLine, bool skipFirstArgument) { arguments.Clear(); unsigned cmdStart = 0, cmdEnd = 0; bool inCmd = false; bool inQuote = false; for (unsigned i = 0; i < cmdLine.Length(); ++i) { if (cmdLine[i] == '\"') inQuote = !inQuote; if (cmdLine[i] == ' ' && !inQuote) { if (inCmd) { inCmd = false; cmdEnd = i; // Do not store the first argument (executable name) if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); skipFirstArgument = false; } } else { if (!inCmd) { inCmd = true; cmdStart = i; } } } if (inCmd) { cmdEnd = cmdLine.Length(); if (!skipFirstArgument) arguments.Push(cmdLine.Substring(cmdStart, cmdEnd - cmdStart)); } // Strip double quotes from the arguments for (unsigned i = 0; i < arguments.Size(); ++i) arguments[i].Replace("\"", ""); return arguments; } const Vector<String>& ParseArguments(const char* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const WString& cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(const wchar_t* cmdLine) { return ParseArguments(String(cmdLine)); } const Vector<String>& ParseArguments(int argc, char** argv) { String cmdLine; for (int i = 0; i < argc; ++i) cmdLine.AppendWithFormat("\"%s\" ", (const char*)argv[i]); return ParseArguments(cmdLine); } const Vector<String>& GetArguments() { return arguments; } String GetConsoleInput() { String ret; #ifdef URHO3D_TESTING // When we are running automated tests, reading the console may block. Just return empty in that case return ret; #endif #ifdef WIN32 HANDLE input = GetStdHandle(STD_INPUT_HANDLE); HANDLE output = GetStdHandle(STD_OUTPUT_HANDLE); if (input == INVALID_HANDLE_VALUE || output == INVALID_HANDLE_VALUE) return ret; // Use char-based input SetConsoleMode(input, ENABLE_PROCESSED_INPUT); INPUT_RECORD record; DWORD events = 0; DWORD readEvents = 0; if (!GetNumberOfConsoleInputEvents(input, &events)) return ret; while (events--) { ReadConsoleInputW(input, &record, 1, &readEvents); if (record.EventType == KEY_EVENT && record.Event.KeyEvent.bKeyDown) { unsigned c = record.Event.KeyEvent.uChar.UnicodeChar; if (c) { if (c == '\b') { PrintUnicode("\b \b"); int length = currentLine.LengthUTF8(); if (length) currentLine = currentLine.SubstringUTF8(0, length - 1); } else if (c == '\r') { PrintUnicode("\n"); ret = currentLine; currentLine.Clear(); return ret; } else { // We have disabled echo, so echo manually wchar_t out = c; DWORD charsWritten; WriteConsoleW(output, &out, 1, &charsWritten, 0); currentLine.AppendUTF8(c); } } } } #elif !defined(ANDROID) && !defined(IOS) int flags = fcntl(STDIN_FILENO, F_GETFL); fcntl(STDIN_FILENO, F_SETFL, flags | O_NONBLOCK); for (;;) { int ch = fgetc(stdin); if (ch >= 0 && ch != '\n') ret += (char)ch; else break; } #endif return ret; } String GetPlatform() { #if defined(ANDROID) return "Android"; #elif defined(IOS) return "iOS"; #elif defined(WIN32) return "Windows"; #elif defined(__APPLE__) return "Mac OS X"; #elif defined(RPI) return "Raspberry Pi"; #elif defined(EMSCRIPTEN) return "HTML5"; #elif defined(__linux__) return "Linux"; #else return String::EMPTY; #endif } #if defined(ANDROID) || defined(RPI) static unsigned GetArmCPUCount() { FILE* fp; int res, i = -1, j = -1; fp = fopen("/sys/devices/system/cpu/present", "r"); // If failed, return at least 1 if (fp == 0) return 1; res = fscanf(fp, "%d-%d", &i, &j); fclose(fp); if (res == 1 && i == 0) return 1; else if (res == 2 && i == 0) return j + 1; // If failed, return at least 1 return 1; } #endif unsigned GetNumPhysicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) // Hardcoded to dual-core on simulator mode even if the host has more return Min(2, data.physical_cpu); #else return data.physical_cpu; #endif #elif defined(ANDROID) || defined(RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return data.num_cores; #else /// \todo Implement properly return 1; #endif } unsigned GetNumLogicalCPUs() { #if defined(IOS) host_basic_info_data_t data; GetCPUData(&data); #if defined(TARGET_IPHONE_SIMULATOR) return Min(2, data.logical_cpu); #else return data.logical_cpu; #endif #elif defined(ANDROID) || defined (RPI) return GetArmCPUCount(); #elif !defined(EMSCRIPTEN) struct cpu_id_t data; GetCPUData(&data); return data.num_logical_cpus; #else /// \todo Implement properly return 1; #endif } } <|endoftext|>
<commit_before>/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Ali Saidi * Andrew Schultz * Miguel Serrano */ #include <sys/time.h> #include <ctime> #include <string> #include "base/bitfield.hh" #include "base/time.hh" #include "base/trace.hh" #include "debug/MC146818.hh" #include "dev/mc146818.hh" #include "dev/rtcreg.h" using namespace std; static uint8_t bcdize(uint8_t val) { uint8_t result; result = val % 10; result += (val / 10) << 4; return result; } static uint8_t unbcdize(uint8_t val) { uint8_t result; result = val & 0xf; result += (val >> 4) * 10; return result; } void MC146818::setTime(const struct tm time) { curTime = time; year = time.tm_year; // Unix is 0-11 for month, data seet says start at 1 mon = time.tm_mon + 1; mday = time.tm_mday; hour = time.tm_hour; min = time.tm_min; sec = time.tm_sec; // Datasheet says 1 is sunday wday = time.tm_wday + 1; if (!(stat_regB & RTCB_BIN)) { // The datasheet says that the year field can be either BCD or // years since 1900. Linux seems to be happy with years since // 1900. year = bcdize(year % 100); mon = bcdize(mon); mday = bcdize(mday); hour = bcdize(hour); min = bcdize(min); sec = bcdize(sec); } } MC146818::MC146818(EventManager *em, const string &n, const struct tm time, bool bcd, Tick frequency) : EventManager(em), _name(n), event(this, frequency), tickEvent(this) { memset(clock_data, 0, sizeof(clock_data)); stat_regA = RTCA_32768HZ | RTCA_1024HZ; stat_regB = RTCB_PRDC_IE | RTCB_24HR; if (!bcd) stat_regB |= RTCB_BIN; setTime(time); DPRINTFN("Real-time clock set to %s", asctime(&time)); } MC146818::~MC146818() { deschedule(tickEvent); deschedule(event); } void MC146818::writeData(const uint8_t addr, const uint8_t data) { if (addr < RTC_STAT_REGA) { clock_data[addr] = data; curTime.tm_sec = unbcdize(sec); curTime.tm_min = unbcdize(min); curTime.tm_hour = unbcdize(hour); curTime.tm_mday = unbcdize(mday); curTime.tm_mon = unbcdize(mon) - 1; curTime.tm_year = ((unbcdize(year) + 50) % 100) + 1950; curTime.tm_wday = unbcdize(wday) - 1; } else { switch (addr) { case RTC_STAT_REGA: // The "update in progress" bit is read only. if ((data & ~RTCA_UIP) != (RTCA_32768HZ | RTCA_1024HZ)) panic("Unimplemented RTC register A value write!\n"); replaceBits(stat_regA, data, 6, 0); break; case RTC_STAT_REGB: if ((data & ~(RTCB_PRDC_IE | RTCB_SQWE)) != RTCB_24HR) panic("Write to RTC reg B bits that are not implemented!\n"); if (data & RTCB_PRDC_IE) { if (!event.scheduled()) event.scheduleIntr(); } else { if (event.scheduled()) deschedule(event); } stat_regB = data; break; case RTC_STAT_REGC: case RTC_STAT_REGD: panic("RTC status registers C and D are not implemented.\n"); break; } } } uint8_t MC146818::readData(uint8_t addr) { if (addr < RTC_STAT_REGA) return clock_data[addr]; else { switch (addr) { case RTC_STAT_REGA: // toggle UIP bit for linux stat_regA ^= RTCA_UIP; return stat_regA; break; case RTC_STAT_REGB: return stat_regB; break; case RTC_STAT_REGC: case RTC_STAT_REGD: return 0x00; break; default: panic("Shouldn't be here"); } } } static time_t mkutctime(struct tm *time) { time_t ret; char *tz; tz = getenv("TZ"); setenv("TZ", "", 1); tzset(); ret = mktime(time); if (tz) setenv("TZ", tz, 1); else unsetenv("TZ"); tzset(); return ret; } void MC146818::tickClock() { if (stat_regB & RTCB_NO_UPDT) return; time_t calTime = mkutctime(&curTime); calTime++; setTime(*gmtime(&calTime)); } void MC146818::serialize(const string &base, ostream &os) { arrayParamOut(os, base + ".clock_data", clock_data, sizeof(clock_data)); paramOut(os, base + ".stat_regA", stat_regA); paramOut(os, base + ".stat_regB", stat_regB); // // save the timer tick and rtc clock tick values to correctly reschedule // them during unserialize // Tick rtcTimerInterruptTickOffset = event.when() - curTick(); SERIALIZE_SCALAR(rtcTimerInterruptTickOffset); Tick rtcClockTickOffset = event.when() - curTick(); SERIALIZE_SCALAR(rtcClockTickOffset); } void MC146818::unserialize(const string &base, Checkpoint *cp, const string &section) { arrayParamIn(cp, section, base + ".clock_data", clock_data, sizeof(clock_data)); paramIn(cp, section, base + ".stat_regA", stat_regA); paramIn(cp, section, base + ".stat_regB", stat_regB); // // properly schedule the timer and rtc clock events // Tick rtcTimerInterruptTickOffset; UNSERIALIZE_SCALAR(rtcTimerInterruptTickOffset); reschedule(event, curTick() + rtcTimerInterruptTickOffset); Tick rtcClockTickOffset; UNSERIALIZE_SCALAR(rtcClockTickOffset); reschedule(tickEvent, curTick() + rtcClockTickOffset); } MC146818::RTCEvent::RTCEvent(MC146818 * _parent, Tick i) : parent(_parent), interval(i) { DPRINTF(MC146818, "RTC Event Initilizing\n"); parent->schedule(this, curTick() + interval); } void MC146818::RTCEvent::scheduleIntr() { parent->schedule(this, curTick() + interval); } void MC146818::RTCEvent::process() { DPRINTF(MC146818, "RTC Timer Interrupt\n"); parent->schedule(this, curTick() + interval); parent->handleEvent(); } const char * MC146818::RTCEvent::description() const { return "RTC interrupt"; } void MC146818::RTCTickEvent::process() { DPRINTF(MC146818, "RTC clock tick\n"); parent->schedule(this, curTick() + SimClock::Int::s); parent->tickClock(); } const char * MC146818::RTCTickEvent::description() const { return "RTC clock tick"; } <commit_msg>mc146818: Correctly serialize tickEvent 'tickEvent' was not being serialized as in its place 'event' was being used. This patch rectifies this error.<commit_after>/* * Copyright (c) 2004-2005 The Regents of The University of Michigan * 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 copyright holders 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 * OWNER 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. * * Authors: Ali Saidi * Andrew Schultz * Miguel Serrano */ #include <sys/time.h> #include <ctime> #include <string> #include "base/bitfield.hh" #include "base/time.hh" #include "base/trace.hh" #include "debug/MC146818.hh" #include "dev/mc146818.hh" #include "dev/rtcreg.h" using namespace std; static uint8_t bcdize(uint8_t val) { uint8_t result; result = val % 10; result += (val / 10) << 4; return result; } static uint8_t unbcdize(uint8_t val) { uint8_t result; result = val & 0xf; result += (val >> 4) * 10; return result; } void MC146818::setTime(const struct tm time) { curTime = time; year = time.tm_year; // Unix is 0-11 for month, data seet says start at 1 mon = time.tm_mon + 1; mday = time.tm_mday; hour = time.tm_hour; min = time.tm_min; sec = time.tm_sec; // Datasheet says 1 is sunday wday = time.tm_wday + 1; if (!(stat_regB & RTCB_BIN)) { // The datasheet says that the year field can be either BCD or // years since 1900. Linux seems to be happy with years since // 1900. year = bcdize(year % 100); mon = bcdize(mon); mday = bcdize(mday); hour = bcdize(hour); min = bcdize(min); sec = bcdize(sec); } } MC146818::MC146818(EventManager *em, const string &n, const struct tm time, bool bcd, Tick frequency) : EventManager(em), _name(n), event(this, frequency), tickEvent(this) { memset(clock_data, 0, sizeof(clock_data)); stat_regA = RTCA_32768HZ | RTCA_1024HZ; stat_regB = RTCB_PRDC_IE | RTCB_24HR; if (!bcd) stat_regB |= RTCB_BIN; setTime(time); DPRINTFN("Real-time clock set to %s", asctime(&time)); } MC146818::~MC146818() { deschedule(tickEvent); deschedule(event); } void MC146818::writeData(const uint8_t addr, const uint8_t data) { if (addr < RTC_STAT_REGA) { clock_data[addr] = data; curTime.tm_sec = unbcdize(sec); curTime.tm_min = unbcdize(min); curTime.tm_hour = unbcdize(hour); curTime.tm_mday = unbcdize(mday); curTime.tm_mon = unbcdize(mon) - 1; curTime.tm_year = ((unbcdize(year) + 50) % 100) + 1950; curTime.tm_wday = unbcdize(wday) - 1; } else { switch (addr) { case RTC_STAT_REGA: // The "update in progress" bit is read only. if ((data & ~RTCA_UIP) != (RTCA_32768HZ | RTCA_1024HZ)) panic("Unimplemented RTC register A value write!\n"); replaceBits(stat_regA, data, 6, 0); break; case RTC_STAT_REGB: if ((data & ~(RTCB_PRDC_IE | RTCB_SQWE)) != RTCB_24HR) panic("Write to RTC reg B bits that are not implemented!\n"); if (data & RTCB_PRDC_IE) { if (!event.scheduled()) event.scheduleIntr(); } else { if (event.scheduled()) deschedule(event); } stat_regB = data; break; case RTC_STAT_REGC: case RTC_STAT_REGD: panic("RTC status registers C and D are not implemented.\n"); break; } } } uint8_t MC146818::readData(uint8_t addr) { if (addr < RTC_STAT_REGA) return clock_data[addr]; else { switch (addr) { case RTC_STAT_REGA: // toggle UIP bit for linux stat_regA ^= RTCA_UIP; return stat_regA; break; case RTC_STAT_REGB: return stat_regB; break; case RTC_STAT_REGC: case RTC_STAT_REGD: return 0x00; break; default: panic("Shouldn't be here"); } } } static time_t mkutctime(struct tm *time) { time_t ret; char *tz; tz = getenv("TZ"); setenv("TZ", "", 1); tzset(); ret = mktime(time); if (tz) setenv("TZ", tz, 1); else unsetenv("TZ"); tzset(); return ret; } void MC146818::tickClock() { if (stat_regB & RTCB_NO_UPDT) return; time_t calTime = mkutctime(&curTime); calTime++; setTime(*gmtime(&calTime)); } void MC146818::serialize(const string &base, ostream &os) { arrayParamOut(os, base + ".clock_data", clock_data, sizeof(clock_data)); paramOut(os, base + ".stat_regA", stat_regA); paramOut(os, base + ".stat_regB", stat_regB); // // save the timer tick and rtc clock tick values to correctly reschedule // them during unserialize // Tick rtcTimerInterruptTickOffset = event.when() - curTick(); SERIALIZE_SCALAR(rtcTimerInterruptTickOffset); Tick rtcClockTickOffset = tickEvent.when() - curTick(); SERIALIZE_SCALAR(rtcClockTickOffset); } void MC146818::unserialize(const string &base, Checkpoint *cp, const string &section) { arrayParamIn(cp, section, base + ".clock_data", clock_data, sizeof(clock_data)); paramIn(cp, section, base + ".stat_regA", stat_regA); paramIn(cp, section, base + ".stat_regB", stat_regB); // // properly schedule the timer and rtc clock events // Tick rtcTimerInterruptTickOffset; UNSERIALIZE_SCALAR(rtcTimerInterruptTickOffset); reschedule(event, curTick() + rtcTimerInterruptTickOffset); Tick rtcClockTickOffset; UNSERIALIZE_SCALAR(rtcClockTickOffset); reschedule(tickEvent, curTick() + rtcClockTickOffset); } MC146818::RTCEvent::RTCEvent(MC146818 * _parent, Tick i) : parent(_parent), interval(i) { DPRINTF(MC146818, "RTC Event Initilizing\n"); parent->schedule(this, curTick() + interval); } void MC146818::RTCEvent::scheduleIntr() { parent->schedule(this, curTick() + interval); } void MC146818::RTCEvent::process() { DPRINTF(MC146818, "RTC Timer Interrupt\n"); parent->schedule(this, curTick() + interval); parent->handleEvent(); } const char * MC146818::RTCEvent::description() const { return "RTC interrupt"; } void MC146818::RTCTickEvent::process() { DPRINTF(MC146818, "RTC clock tick\n"); parent->schedule(this, curTick() + SimClock::Int::s); parent->tickClock(); } const char * MC146818::RTCTickEvent::description() const { return "RTC clock tick"; } <|endoftext|>
<commit_before>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "task.h" using namespace Domain; Task::Task(QObject *parent) : Artifact(parent) { } Task::~Task() { } bool Task::isDone() const { return (status() == Complete); } void Task::setDone(bool done) { if (done) { setStatus(Complete); } else { setStatus(None); } } QDateTime Task::startDate() const { return m_startDate; } void Task::setStartDate(const QDateTime &startDate) { if (m_startDate == startDate) return; m_startDate = startDate; emit startDateChanged(startDate); } QDateTime Task::dueDate() const { return m_dueDate; } Task::Delegate Task::delegate() const { return m_delegate; } void Task::setDueDate(const QDateTime &dueDate) { if (m_dueDate == dueDate) return; m_dueDate = dueDate; emit dueDateChanged(dueDate); } void Task::setDelegate(const Task::Delegate &delegate) { if (m_delegate == delegate) return; m_delegate = delegate; emit delegateChanged(delegate); } int Task::progress() const { return m_progress; } void Task::setProgress(int progress) { if (m_progress == progress) return; m_progress = progress; emit progressChanged(progress); } Task::Status Task::status() const { return m_status; } void Task::setStatus(int status) { if (m_status == static_cast<Status>(status)) return; m_status = static_cast<Status>(status); emit statusChanged(status); } Task::Delegate::Delegate() { } Task::Delegate::Delegate(const QString &name, const QString &email) : m_name(name), m_email(email) { } Task::Delegate::Delegate(const Task::Delegate &other) : m_name(other.m_name), m_email(other.m_email) { } Task::Delegate &Task::Delegate::operator=(const Task::Delegate &other) { Delegate copy(other); std::swap(m_name, copy.m_name); std::swap(m_email, copy.m_email); return *this; } bool Task::Delegate::operator==(const Task::Delegate &other) const { return m_name == other.m_name && m_email == other.m_email; } bool Task::Delegate::isValid() const { return !m_email.isEmpty(); } QString Task::Delegate::display() const { return !isValid() ? QString() : !m_name.isEmpty() ? m_name : m_email; } QString Task::Delegate::name() const { return m_name; } void Task::Delegate::setName(const QString &name) { m_name = name; } QString Task::Delegate::email() const { return m_email; } void Task::Delegate::setEmail(const QString &email) { m_email = email; } <commit_msg>Default values for task status and progress<commit_after>/* This file is part of Zanshin Copyright 2014 Kevin Ottens <ervin@kde.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License or (at your option) version 3 or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), which shall act as a proxy defined in Section 14 of version 3 of the license. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "task.h" using namespace Domain; Task::Task(QObject *parent) : Artifact(parent), m_progress(0), m_status(None) { } Task::~Task() { } bool Task::isDone() const { return (status() == Complete); } void Task::setDone(bool done) { if (done) { setStatus(Complete); } else { setStatus(None); } } QDateTime Task::startDate() const { return m_startDate; } void Task::setStartDate(const QDateTime &startDate) { if (m_startDate == startDate) return; m_startDate = startDate; emit startDateChanged(startDate); } QDateTime Task::dueDate() const { return m_dueDate; } Task::Delegate Task::delegate() const { return m_delegate; } void Task::setDueDate(const QDateTime &dueDate) { if (m_dueDate == dueDate) return; m_dueDate = dueDate; emit dueDateChanged(dueDate); } void Task::setDelegate(const Task::Delegate &delegate) { if (m_delegate == delegate) return; m_delegate = delegate; emit delegateChanged(delegate); } int Task::progress() const { return m_progress; } void Task::setProgress(int progress) { if (m_progress == progress) return; m_progress = progress; emit progressChanged(progress); } Task::Status Task::status() const { return m_status; } void Task::setStatus(int status) { if (m_status == static_cast<Status>(status)) return; m_status = static_cast<Status>(status); emit statusChanged(status); } Task::Delegate::Delegate() { } Task::Delegate::Delegate(const QString &name, const QString &email) : m_name(name), m_email(email) { } Task::Delegate::Delegate(const Task::Delegate &other) : m_name(other.m_name), m_email(other.m_email) { } Task::Delegate &Task::Delegate::operator=(const Task::Delegate &other) { Delegate copy(other); std::swap(m_name, copy.m_name); std::swap(m_email, copy.m_email); return *this; } bool Task::Delegate::operator==(const Task::Delegate &other) const { return m_name == other.m_name && m_email == other.m_email; } bool Task::Delegate::isValid() const { return !m_email.isEmpty(); } QString Task::Delegate::display() const { return !isValid() ? QString() : !m_name.isEmpty() ? m_name : m_email; } QString Task::Delegate::name() const { return m_name; } void Task::Delegate::setName(const QString &name) { m_name = name; } QString Task::Delegate::email() const { return m_email; } void Task::Delegate::setEmail(const QString &email) { m_email = email; } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<<T>(std::ostream&, const BinaryTree<T>&); template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree { private: Node<T>*root; int CountElements = 0; public: BinaryTree(); ~BinaryTree(); Node<T>* root_(); unsigned int count() const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void deleteNode(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& output(std::ostream& ost, const Node<T>* temp); friend std::ostream& operator<<<T>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { //if (!temp) //{ //throw "error"; //} if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { //if (!temp.root) //throw "error"; output(ost, temp.root, 0); return ost; } <commit_msg>Update BinaryTree.hpp<commit_after>#include <iostream> #include <string> #include <fstream> #include <cstdint> using namespace std; template <typename T> class BinaryTree; template <typename T> std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); template <typename T> struct Node { Node *left; Node *right; T data; }; template <typename T> class BinaryTree { private: Node<T>*root; int CountElements = 0; public: BinaryTree(); ~BinaryTree(); Node<T>* root_(); unsigned int count() const; void insert_node(const T&x); Node<T> *find_node(const T&, Node<T>*)const; void deleteNode(Node<T>* temp); void writing(const std::string& filename)const; friend std::ostream& output(std::ostream& ost, const Node<T>* temp); friend std::ostream& operator<<<>(std::ostream&, const BinaryTree<T>&); }; template <typename T> BinaryTree<T>::BinaryTree() { root = nullptr; } template<typename T> Node<T>* BinaryTree<T>::root_() { return root; } template <typename T> BinaryTree<T>::~BinaryTree() { deleteNode(root); } template<typename T> void BinaryTree<T>::insert_node(const T&x) { if (find_node(x, root_())) return; Node<T>* MyTree = new Node<T>; MyTree->data = x; MyTree->left = MyTree->right = 0; Node<T>* buff = root; Node<T>* temp = root; while (temp) { buff = temp; if (x < temp->data) temp = temp->left; else temp = temp->right; } if (!buff) root = MyTree; else { if (x < buff->data) buff->left = MyTree; else buff->right = MyTree; } ++CountElements; } template<typename T> Node<T>* BinaryTree<T>::find_node(const T& value, Node<T>* temp) const { if (temp == 0 || value == temp->data) return temp; if (value > temp->data) return find_node(value, temp->right); else return find_node(value, temp->left); } template<typename T> void BinaryTree<T>::deleteNode(Node<T>* temp) { //if (!temp) //{ //throw "error"; //} if (temp->left) { deleteNode(temp->left); temp->left = nullptr; } if (temp->right) { deleteNode(temp->right); temp->right = nullptr; } delete temp; } template<typename T> void BinaryTree<T>::writing(const std::string& filename)const { ofstream file_1(filename); file_1 << CountElements << "\t"; output(file_1, root); file_1.close(); } template <typename T> std::ostream& output(std::ostream& ost, const Node<T>* node, unsigned int level) { if (!node) return ost; output(ost, node->right, level + 1); for (unsigned int i = 0; i < level; i++) ost << "\t"; ost << node->data << std::endl; output(ost, node->left, level + 1); return ost; } template <typename T> std::ostream& operator<<(std::ostream& ost, const BinaryTree<T>& temp) { //if (!temp.root) //throw "error"; output(ost, temp.root, 0); return ost; } <|endoftext|>
<commit_before>#pragma once #if defined(__arm__) # define __NR_pause 29 #elif defined(__x86_64__) # define __NR_pause 34 #else # error #endif <commit_msg>pause: not needed (yet)<commit_after><|endoftext|>
<commit_before>// Copyright (c) Google LLC 2019 // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "./ans_encode.h" #include <vector> #include <brunsli/types.h> #include "./histogram_encode.h" #include "./write_bits.h" namespace brunsli { namespace { void ANSBuildInfoTable(const int* counts, int alphabet_size, ANSEncSymbolInfo info[BRUNSLI_ANS_MAX_SYMBOLS]) { int total = 0; for (int s = 0; s < alphabet_size; ++s) { const uint32_t freq = counts[s]; info[s].freq_ = counts[s]; info[s].start_ = total; total += freq; #ifdef USE_MULT_BY_RECIPROCAL if (freq != 0) { info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) / info[s].freq_; } else { // Shouldn't matter for valid streams (symbol shouldn't occur). // Initialization allows to avoid undefined behavior on corrupted streams. info[s].ifreq_ = 1; } #endif } } } // namespace void BuildAndStoreANSEncodingData(const int* histogram, ANSTable* table, Storage* storage) { int num_symbols; int symbols[kMaxNumSymbolsForSmallCode] = {0}; std::vector<int> counts(histogram, histogram + BRUNSLI_ANS_MAX_SYMBOLS); int omit_pos; NormalizeCounts(&counts[0], &omit_pos, BRUNSLI_ANS_MAX_SYMBOLS, BRUNSLI_ANS_LOG_TAB_SIZE, &num_symbols, symbols); ANSBuildInfoTable(&counts[0], BRUNSLI_ANS_MAX_SYMBOLS, table->info_); EncodeCounts(&counts[0], omit_pos, num_symbols, symbols, storage); } } // namespace brunsli <commit_msg>Internal change<commit_after>// Copyright (c) Google LLC 2019 // // Use of this source code is governed by an MIT-style // license that can be found in the LICENSE file or at // https://opensource.org/licenses/MIT. #include "./ans_encode.h" #include <vector> #include <brunsli/types.h> #include "./histogram_encode.h" #include "./write_bits.h" namespace brunsli { namespace { void ANSBuildInfoTable(const int* counts, int alphabet_size, ANSEncSymbolInfo info[BRUNSLI_ANS_MAX_SYMBOLS]) { int total = 0; for (int s = 0; s < alphabet_size; ++s) { const uint32_t freq = counts[s]; info[s].freq_ = counts[s]; info[s].start_ = total; total += freq; #ifdef USE_MULT_BY_RECIPROCAL if (freq != 0) { info[s].ifreq_ = ((1ull << RECIPROCAL_PRECISION) + info[s].freq_ - 1) / info[s].freq_; } else { // Shouldn't matter for valid streams (symbol shouldn't occur). // Initialization allows to avoid undefined behavior on corrupted streams. info[s].ifreq_ = 1; } #endif } } } // namespace void BuildAndStoreANSEncodingData(const int* histogram, ANSTable* table, Storage* storage) { int num_symbols; int symbols[kMaxNumSymbolsForSmallCode] = {0}; std::vector<int> counts(histogram, histogram + BRUNSLI_ANS_MAX_SYMBOLS); int omit_pos = 0; // Initialization is not necessary, but makes MSAN happy. NormalizeCounts(&counts[0], &omit_pos, BRUNSLI_ANS_MAX_SYMBOLS, BRUNSLI_ANS_LOG_TAB_SIZE, &num_symbols, symbols); ANSBuildInfoTable(&counts[0], BRUNSLI_ANS_MAX_SYMBOLS, table->info_); EncodeCounts(&counts[0], omit_pos, num_symbols, symbols, storage); } } // namespace brunsli <|endoftext|>
<commit_before>/** @file gsFunctionExpr.hpp @brief Provides implementation of FunctionExpr class. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): A. Mantzaflaris */ #pragma once #include <gsCore/gsLinearAlgebra.h> #include <exprtk.hpp>// External file namespace gismo { template<typename T> class gsFunctionExprPrivate { public: T vars[6]; exprtk::symbol_table<T> symbol_table; exprtk::expression<T> expression; exprtk::expression<T> der_exp[6]; bool der_flag[6]; std::string string; int dim; }; /* / /AM: under construction template<typename T> class gsSymbolListPrivate { public: exprtk::symbol_table<T> symbol_table; std::vector<T> vars ; std::vector<T> params; }; template<typename T> gsSymbolList<T>::gsSymbolList() : my(new gsSymbolListPrivate<T>) {} template<typename T> gsSymbolList<T>::~gsSymbolList() { delete my; } template<typename T> void gsSymbolList<T>::setDefault() { my->symbol_table.clear(); // Identify symbol table my->symbol_table.add_variable("x",my->vars[0]); my->symbol_table.add_variable("y",my->vars[1]); my->symbol_table.add_variable("z",my->vars[2]); my->symbol_table.add_variable("w",my->vars[3]); my->symbol_table.add_variable("u",my->vars[4]); my->symbol_table.add_variable("v",my->vars[5]); //my->symbol_table.remove_variable("w",my->vars[3]); my->symbol_table.add_pi(); //my->symbol_table.add_constant("C", 1); } template<typename T> bool gsSymbolList<T>::addConstant(const std::string & constant_name, const T& value) { return my->symbol_table.add_constant(constant_name, value); } template<typename T> bool gsSymbolList<T>::addVariable(const std::string & variable_name) { my->vars.push_back(0.0); return my->symbol_table.add_variable(variable_name, my->vars.back() ); } template<typename T> bool gsSymbolList<T>::addParameter(const std::string & variable_name) { my->params.push_back(0.0); return my->symbol_table.add_variable(variable_name, my->params.back() ); } template<typename T> bool gsSymbolList<T>::hasSymbol(const std::string& symbol_name) { return true; } //*/ template<typename T> gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {} template<typename T> gsFunctionExpr<T>::gsFunctionExpr(const std::string & expression_string, int ddim) : my(new gsFunctionExprPrivate<T>) { // Keep string data my->string = expression_string; my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end()); stringReplace(my->string, "**", "^"); my->dim = ddim; init(); } template<typename T> gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other) { my = new gsFunctionExprPrivate<T>; my->string = other.my->string; my->dim = other.my->dim; init(); } template<typename T> gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other) { if (this != &other) { my->string = other.my->string; my->dim = other.my->dim; init(); } return *this; } template<typename T> gsFunctionExpr<T>::~gsFunctionExpr() { delete my; } // template<typename T> // void gsFunctionExpr<T>::init(variables,constants) template<typename T> void gsFunctionExpr<T>::init() { my->symbol_table.clear(); my->expression.release(); // Identify symbol table my->symbol_table.add_variable("x",my->vars[0]); my->symbol_table.add_variable("y",my->vars[1]); my->symbol_table.add_variable("z",my->vars[2]); my->symbol_table.add_variable("w",my->vars[3]); my->symbol_table.add_variable("u",my->vars[4]); my->symbol_table.add_variable("v",my->vars[5]); //my->symbol_table.remove_variable("w",my->vars[3]); my->symbol_table.add_pi(); //my->symbol_table.add_constant("C", 1); my->expression.register_symbol_table(my->symbol_table); exprtk::parser<T> parser; //parser.cache_symbols() = true; bool success = parser.compile(my->string, my->expression); if ( ! success ) std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl; /* AM: Changed in recent versions. std::vector<std::string> varlist; parser.expression_symbols(varlist); varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end()); my->dim = varlist.size(); */ my->der_flag[0]=false; my->der_flag[1]=false; my->der_flag[2]=false; my->der_flag[3]=false; my->der_flag[4]=false; my->der_flag[5]=false; } template<typename T> int gsFunctionExpr<T>::domainDim() const { return my->dim; } template<typename T> void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; } template<typename T> void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; } template<typename T> void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; } template<typename T> void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; } template<typename T> void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; } template<typename T> void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; } template<typename T> void gsFunctionExpr<T>::set_x_der (std::string expression_string) { my->der_exp[0].register_symbol_table(my->symbol_table); exprtk::parser<T> parser; bool success = parser.compile(expression_string, my->der_exp[0] ); if ( ! success ) std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl; else my->der_flag[0]=true; } template<typename T> void gsFunctionExpr<T>::set_y_der (std::string expression_string) { my->der_exp[1].register_symbol_table(my->symbol_table); exprtk::parser<T> parser; bool success = parser.compile(expression_string, my->der_exp[1] ); if ( ! success ) std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl; else my->der_flag[1]=true; } template<typename T> void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const { GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); result.resize(1, u.cols()); for ( int i = 0; i<u.cols(); i++ ) { for ( int j = 0; j<u.rows(); j++ ) { my->vars[j] =u(j,i); } result(0,i) = my->expression.value(); } } template<typename T> void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const { GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component"); result.resize(1, u.cols()); for ( int i = 0; i<u.cols(); i++ ) { for ( int j = 0; j<u.rows(); j++ ) { my->vars[j] =u(j,i); } result(0,i) = my->expression.value(); } } template<typename T> void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const { int n = u.rows(); GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); result.resize(1, n * u.cols()); for( int i=0; i < u.cols(); ++i ) { for ( int j = 0; j<n; j++ ) my->vars[j] =u(j,i); for( int j=0; j< n; ++j ) if ( my->der_flag[j] ) result(n*i+j) = my->der_exp[j].value(); else result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ; } } template<typename T> typename gsFunction<T>::uMatrixPtr gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const { GISMO_ENSURE(coord == 0, "Error, function is real"); // one column only.. int n = u.rows(); GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); gsMatrix<T> * res= new gsMatrix<T>(n,n) ; for ( int j = 0; j<n; j++ ) my->vars[j] =u(j,0); for( int j=0; j< n; ++j ) { (*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ; for( int k=0; k<j; ++k ) (*res)(k,j) = (*res)(j,k) = exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ; } return typename gsFunction<T>::uMatrixPtr(res); } ; template<typename T> gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const { gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ; for( index_t i=0; i< res->cols(); ++i ) { for ( int t = 0; t<u.rows(); t++ ) my->vars[t] =u(t,i); (*res)(0,i) = exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ; } return res; } ; template<typename T> gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const { gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ; res->setZero(); int n = u.rows(); for( index_t i=0; i< res->cols(); ++i ) for ( int j = 0; j<n; j++ ) { my->vars[j] =u(j,i); (*res)(0,i) += exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ; } return res; } template<typename T> T gsFunctionExpr<T>::value() const { return my->expression.value() ; } template<typename T> std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const { os << my->string ; return os; } }; // namespace gismo <commit_msg>another fix for the format change in format<commit_after>/** @file gsFunctionExpr.hpp @brief Provides implementation of FunctionExpr class. This file is part of the G+Smo library. This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Author(s): A. Mantzaflaris */ #pragma once #include <gsCore/gsLinearAlgebra.h> #include <exprtk.hpp>// External file namespace gismo { template<typename T> class gsFunctionExprPrivate { public: T vars[6]; exprtk::symbol_table<T> symbol_table; exprtk::expression<T> expression; exprtk::expression<T> der_exp[6]; bool der_flag[6]; std::string string; int dim; }; /* / /AM: under construction template<typename T> class gsSymbolListPrivate { public: exprtk::symbol_table<T> symbol_table; std::vector<T> vars ; std::vector<T> params; }; template<typename T> gsSymbolList<T>::gsSymbolList() : my(new gsSymbolListPrivate<T>) {} template<typename T> gsSymbolList<T>::~gsSymbolList() { delete my; } template<typename T> void gsSymbolList<T>::setDefault() { my->symbol_table.clear(); // Identify symbol table my->symbol_table.add_variable("x",my->vars[0]); my->symbol_table.add_variable("y",my->vars[1]); my->symbol_table.add_variable("z",my->vars[2]); my->symbol_table.add_variable("w",my->vars[3]); my->symbol_table.add_variable("u",my->vars[4]); my->symbol_table.add_variable("v",my->vars[5]); //my->symbol_table.remove_variable("w",my->vars[3]); my->symbol_table.add_pi(); //my->symbol_table.add_constant("C", 1); } template<typename T> bool gsSymbolList<T>::addConstant(const std::string & constant_name, const T& value) { return my->symbol_table.add_constant(constant_name, value); } template<typename T> bool gsSymbolList<T>::addVariable(const std::string & variable_name) { my->vars.push_back(0.0); return my->symbol_table.add_variable(variable_name, my->vars.back() ); } template<typename T> bool gsSymbolList<T>::addParameter(const std::string & variable_name) { my->params.push_back(0.0); return my->symbol_table.add_variable(variable_name, my->params.back() ); } template<typename T> bool gsSymbolList<T>::hasSymbol(const std::string& symbol_name) { return true; } //*/ template<typename T> gsFunctionExpr<T>::gsFunctionExpr() : my(new gsFunctionExprPrivate<T>) {} template<typename T> gsFunctionExpr<T>::gsFunctionExpr(const std::string & expression_string, int ddim) : my(new gsFunctionExprPrivate<T>) { // Keep string data my->string = expression_string; my->string.erase(std::remove(my->string.begin(),my->string.end(),' '),my->string.end()); stringReplace(my->string, "**", "^"); my->dim = ddim; init(); } template<typename T> gsFunctionExpr<T>::gsFunctionExpr(const gsFunctionExpr& other) { my = new gsFunctionExprPrivate<T>; my->string = other.my->string; my->dim = other.my->dim; init(); } template<typename T> gsFunctionExpr<T>& gsFunctionExpr<T>::operator=(const gsFunctionExpr& other) { if (this != &other) { my->string = other.my->string; my->dim = other.my->dim; init(); } return *this; } template<typename T> gsFunctionExpr<T>::~gsFunctionExpr() { delete my; } // template<typename T> // void gsFunctionExpr<T>::init(variables,constants) template<typename T> void gsFunctionExpr<T>::init() { my->symbol_table.clear(); my->expression.release(); // Identify symbol table my->symbol_table.add_variable("x",my->vars[0]); my->symbol_table.add_variable("y",my->vars[1]); my->symbol_table.add_variable("z",my->vars[2]); my->symbol_table.add_variable("w",my->vars[3]); my->symbol_table.add_variable("u",my->vars[4]); my->symbol_table.add_variable("v",my->vars[5]); //my->symbol_table.remove_variable("w",my->vars[3]); my->symbol_table.add_pi(); //my->symbol_table.add_constant("C", 1); my->expression.register_symbol_table(my->symbol_table); exprtk::parser<T> parser; //parser.cache_symbols() = true; bool success = parser.compile(my->string, my->expression); if ( ! success ) std::cout<<"gsFunctionExpr error: " <<parser.error() <<std::endl; /* AM: Changed in recent versions. std::vector<std::string> varlist; parser.expression_symbols(varlist); varlist.erase(std::remove(varlist.begin(), varlist.end(), "pi"), varlist.end()); my->dim = varlist.size(); */ my->der_flag[0]=false; my->der_flag[1]=false; my->der_flag[2]=false; my->der_flag[3]=false; my->der_flag[4]=false; my->der_flag[5]=false; } template<typename T> int gsFunctionExpr<T>::domainDim() const { return my->dim; } template<typename T> void gsFunctionExpr<T>::set_x (T const & v) const { my->vars[0]= v; } template<typename T> void gsFunctionExpr<T>::set_y (T const & v) const { my->vars[1]= v; } template<typename T> void gsFunctionExpr<T>::set_z (T const & v) const { my->vars[2]= v; } template<typename T> void gsFunctionExpr<T>::set_w (T const & v) const { my->vars[3]= v; } template<typename T> void gsFunctionExpr<T>::set_u (T const & v) const { my->vars[4]= v; } template<typename T> void gsFunctionExpr<T>::set_v (T const & v) const { my->vars[5]= v; } template<typename T> void gsFunctionExpr<T>::set_x_der (std::string expression_string) { my->der_exp[0].register_symbol_table(my->symbol_table); exprtk::parser<T> parser; bool success = parser.compile(expression_string, my->der_exp[0] ); if ( ! success ) std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl; else my->der_flag[0]=true; } template<typename T> void gsFunctionExpr<T>::set_y_der (std::string expression_string) { my->der_exp[1].register_symbol_table(my->symbol_table); exprtk::parser<T> parser; bool success = parser.compile(expression_string, my->der_exp[1] ); if ( ! success ) std::cout<<"gsFunctionExpr set_x_der(.) error: " <<parser.error() <<std::endl; else my->der_flag[1]=true; } template<typename T> void gsFunctionExpr<T>::eval_into(const gsMatrix<T>& u, gsMatrix<T>& result) const { GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); result.resize(1, u.cols()); for ( int i = 0; i<u.cols(); i++ ) { for ( int j = 0; j<u.rows(); j++ ) { my->vars[j] =u(j,i); } result(0,i) = my->expression.value(); } } template<typename T> void gsFunctionExpr<T>::eval_component_into(const gsMatrix<T>& u, const index_t comp, gsMatrix<T>& result) const { GISMO_ASSERT (comp == 0, "Given component number is too high. Only one component"); result.resize(1, u.cols()); for ( int i = 0; i<u.cols(); i++ ) { for ( int j = 0; j<u.rows(); j++ ) { my->vars[j] =u(j,i); } result(0,i) = my->expression.value(); } } template<typename T> void gsFunctionExpr<T>::deriv_into(const gsMatrix<T>& u, gsMatrix<T>& result) const { int n = u.rows(); GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); result.resize(1, n * u.cols()); for( int i=0; i < u.cols(); ++i ) { for ( int j = 0; j<n; j++ ) my->vars[j] =u(j,i); for( int j=0; j< n; ++j ) if ( my->der_flag[j] ) result(n*i+j) = my->der_exp[j].value(); else result(n*i+j) = exprtk::derivative<T>( my->expression, my->vars[j], 0.00001 ) ; } result.resize(n, u.cols()); } template<typename T> typename gsFunction<T>::uMatrixPtr gsFunctionExpr<T>::hess(const gsMatrix<T>& u, unsigned coord) const { GISMO_ENSURE(coord == 0, "Error, function is real"); // one column only.. int n = u.rows(); GISMO_ASSERT ( u.rows() < 7 && u.rows() > 0, "Inconsistent point size." ); gsMatrix<T> * res= new gsMatrix<T>(n,n) ; for ( int j = 0; j<n; j++ ) my->vars[j] =u(j,0); for( int j=0; j< n; ++j ) { (*res)(j,j) = exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ; for( int k=0; k<j; ++k ) (*res)(k,j) = (*res)(j,k) = exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ; } return typename gsFunction<T>::uMatrixPtr(res); } ; template<typename T> gsMatrix<T> * gsFunctionExpr<T>::mderiv(const gsMatrix<T>& u, const index_t &k, const index_t &j ) const { gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ; for( index_t i=0; i< res->cols(); ++i ) { for ( int t = 0; t<u.rows(); t++ ) my->vars[t] =u(t,i); (*res)(0,i) = exprtk::mixed_derivative<T>( my->expression, my->vars[k], my->vars[j], 0.00001 ) ; } return res; } ; template<typename T> gsMatrix<T> * gsFunctionExpr<T>::laplacian(const gsMatrix<T>& u) const { gsMatrix<T> * res= new gsMatrix<T>(1,u.cols()) ; res->setZero(); int n = u.rows(); for( index_t i=0; i< res->cols(); ++i ) for ( int j = 0; j<n; j++ ) { my->vars[j] =u(j,i); (*res)(0,i) += exprtk::second_derivative<T>( my->expression, my->vars[j], 0.00001 ) ; } return res; } template<typename T> T gsFunctionExpr<T>::value() const { return my->expression.value() ; } template<typename T> std::ostream & gsFunctionExpr<T>::print(std::ostream &os) const { os << my->string ; return os; } }; // namespace gismo <|endoftext|>
<commit_before>/* * Copyright (c) 2015-2018, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <nitro/env/process.hpp> extern "C" { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #include <windows.h> #include <tlhelp32.h> #else #include <unistd.h> #endif } namespace nitro { namespace env { int get_pid() { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) return GetCurrentProcessId(); #else return getpid(); #endif } int get_parent_pid() { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) HANDLE hSnapshot; PROCESSENTRY32 pe32; DWORD ppid = 0, pid = nitro::env::get_pid(); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); __try { if (hSnapshot == INVALID_HANDLE_VALUE) __leave; ZeroMemory(&pe32, sizeof(pe32)); pe32.dwSize = sizeof(pe32); if (!Process32First(hSnapshot, &pe32)) __leave; do { if (pe32.th32ProcessID == pid) { ppid = pe32.th32ParentProcessID; break; } } while (Process32Next(hSnapshot, &pe32)); } __finally { if (hSnapshot != INVALID_HANDLE_VALUE) CloseHandle(hSnapshot); } return ppid; #else return getppid(); #endif } int get_tid() { return nitro::env::get_pid(); } } // namespace env } // namespace nitro <commit_msg>Actually implement gettid for linux using syscall<commit_after>/* * Copyright (c) 2015-2018, Technische Universität Dresden, Germany * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted * provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this list of conditions * and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, this list of * conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to * endorse or promote products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <nitro/env/process.hpp> extern "C" { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) #include <windows.h> #include <tlhelp32.h> #else #include <unistd.h> #endif #ifdef __linux__ #include <sys/syscall.h> #include <sys/types.h> #endif } namespace nitro { namespace env { int get_pid() { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) return GetCurrentProcessId(); #else return getpid(); #endif } int get_parent_pid() { #if defined(_MSC_VER) || defined(_MSC_EXTENSIONS) HANDLE hSnapshot; PROCESSENTRY32 pe32; DWORD ppid = 0, pid = nitro::env::get_pid(); hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); __try { if (hSnapshot == INVALID_HANDLE_VALUE) __leave; ZeroMemory(&pe32, sizeof(pe32)); pe32.dwSize = sizeof(pe32); if (!Process32First(hSnapshot, &pe32)) __leave; do { if (pe32.th32ProcessID == pid) { ppid = pe32.th32ParentProcessID; break; } } while (Process32Next(hSnapshot, &pe32)); } __finally { if (hSnapshot != INVALID_HANDLE_VALUE) CloseHandle(hSnapshot); } return ppid; #else return getppid(); #endif } int get_tid() { #if __linux__ return syscall(SYS_gettid); #else return nitro::env::get_pid(); #endif } } // namespace env } // namespace nitro <|endoftext|>
<commit_before>/******************************************************************************* * c7a/api/context.hpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_CONTEXT_HEADER #define C7A_API_CONTEXT_HEADER #include <cassert> #include <fstream> #include <string> #include <vector> #include "c7a/data/data_manager.hpp" #include "c7a/core/job_manager.hpp" #include <stdio.h> #include <unistd.h> #define GetCurrentDir getcwd namespace c7a { class Context { public: Context() : job_manager_() { } virtual ~Context() { } data::DataManager & get_data_manager() { return job_manager_.get_data_manager(); } int number_worker() { return number_worker_; } core::JobManager & job_manager() { return job_manager_; } std::string get_current_dir() { char cCurrentPath[FILENAME_MAX]; if (!GetCurrentDir(cCurrentPath, sizeof(cCurrentPath))) { throw "unable to retrieve current directory"; } return GetCurrentDir(cCurrentPath, sizeof(cCurrentPath)); } private: core::JobManager job_manager_; //stub int number_worker_ = 1; }; } // namespace c7a #endif // !C7A_API_CONTEXT_HEADER /******************************************************************************/ <commit_msg>removed unnecessary define<commit_after>/******************************************************************************* * c7a/api/context.hpp * * Part of Project c7a. * * * This file has no license. Only Chuck Norris can compile it. ******************************************************************************/ #pragma once #ifndef C7A_API_CONTEXT_HEADER #define C7A_API_CONTEXT_HEADER #include <cassert> #include <fstream> #include <string> #include <vector> #include "c7a/data/data_manager.hpp" #include "c7a/core/job_manager.hpp" #include <stdio.h> #include <unistd.h> namespace c7a { class Context { public: Context() : job_manager_() { } virtual ~Context() { } data::DataManager & get_data_manager() { return job_manager_.get_data_manager(); } int number_worker() { return number_worker_; } core::JobManager & job_manager() { return job_manager_; } std::string get_current_dir() { char cCurrentPath[FILENAME_MAX]; if (!getcwd(cCurrentPath, sizeof(cCurrentPath))) { throw "unable to retrieve current directory"; } return getcwd(cCurrentPath, sizeof(cCurrentPath)); } private: core::JobManager job_manager_; //stub int number_worker_ = 1; }; } // namespace c7a #endif // !C7A_API_CONTEXT_HEADER /******************************************************************************/ <|endoftext|>
<commit_before>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical 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 (including the next * paragraph) 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 "xorg/gtest/xorg-gtest_environment.h" #include "xorg/gtest/xorg-gtest_process.h" #include "defines.h" #include <sys/types.h> #include <unistd.h> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <stdexcept> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { Private() : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE), path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) { } std::string path_to_conf; std::string path_to_log_file; std::string path_to_server; int display; Process process; }; xorg::testing::Environment::Environment() : d_(new Private) { } xorg::testing::Environment::~Environment() {} void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file) { d_->path_to_log_file = path_to_log_file; } const std::string& xorg::testing::Environment::log_file() const { return d_->path_to_log_file; } void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file) { d_->path_to_conf = path_conf_file; } const std::string& xorg::testing::Environment::conf_file() const { return d_->path_to_conf; } void xorg::testing::Environment::set_server(const std::string& path_to_server) { d_->path_to_server = path_to_server; } const std::string& xorg::testing::Environment::server() const { return d_->path_to_server; } void xorg::testing::Environment::set_display(int display_num) { d_->display = display_num; } int xorg::testing::Environment::display() const { return d_->display; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(), display_string, "-logfile", d_->path_to_log_file.c_str(), "-config", d_->path_to_conf.c_str(), NULL); Process::SetEnv("DISPLAY", display_string, true); for (int i = 0; i < 10; ++i) { Display* test_display = XOpenDisplay(NULL); if (test_display) { XCloseDisplay(test_display); return; } int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) { std::string message; message += "X server failed to start on display "; message += display_string; message += ". Ensure that the \"dummy\" video driver is installed. " "If the X.org server is older than 1.12, " "tests will need to be run as root. Check "; message += d_->path_to_log_file; message += " for any errors"; throw std::runtime_error(message); } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ } else if (pid == -1) { throw std::runtime_error("Could not get status of dummy X server " "process"); } else { throw std::runtime_error("Invalid child PID returned by Process::Wait()"); } } throw std::runtime_error("Unable to open connection to dummy X server"); } void xorg::testing::Environment::TearDown() { if (d_->process.Terminate()) { for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } } Kill(); } void xorg::testing::Environment::Kill() { if (!d_->process.Kill()) std::cerr << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno) << "\n"; for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } std::cerr << "Warning: Dummy X server did not shut down\n"; } <commit_msg>Check if a server is already running on the chosen display name<commit_after>/******************************************************************************* * * X testing environment - Google Test environment feat. dummy x server * * Copyright (C) 2011, 2012 Canonical 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 (including the next * paragraph) 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 "xorg/gtest/xorg-gtest_environment.h" #include "xorg/gtest/xorg-gtest_process.h" #include "defines.h" #include <sys/types.h> #include <unistd.h> #include <cerrno> #include <csignal> #include <cstdlib> #include <cstring> #include <iostream> #include <stdexcept> #include <X11/Xlib.h> struct xorg::testing::Environment::Private { Private() : path_to_conf(DUMMY_CONF_PATH), path_to_log_file(DEFAULT_XORG_LOGFILE), path_to_server(DEFAULT_XORG_SERVER), display(DEFAULT_DISPLAY) { } std::string path_to_conf; std::string path_to_log_file; std::string path_to_server; int display; Process process; }; xorg::testing::Environment::Environment() : d_(new Private) { } xorg::testing::Environment::~Environment() {} void xorg::testing::Environment::set_log_file(const std::string& path_to_log_file) { d_->path_to_log_file = path_to_log_file; } const std::string& xorg::testing::Environment::log_file() const { return d_->path_to_log_file; } void xorg::testing::Environment::set_conf_file(const std::string& path_conf_file) { d_->path_to_conf = path_conf_file; } const std::string& xorg::testing::Environment::conf_file() const { return d_->path_to_conf; } void xorg::testing::Environment::set_server(const std::string& path_to_server) { d_->path_to_server = path_to_server; } const std::string& xorg::testing::Environment::server() const { return d_->path_to_server; } void xorg::testing::Environment::set_display(int display_num) { d_->display = display_num; } int xorg::testing::Environment::display() const { return d_->display; } void xorg::testing::Environment::SetUp() { static char display_string[6]; snprintf(display_string, 6, ":%d", d_->display); Display* test_display = XOpenDisplay(display_string); if (test_display) { XCloseDisplay(test_display); std::string message; message += "A server is already running on "; message += display_string; message += "."; throw std::runtime_error(message); } d_->process.Start(d_->path_to_server, d_->path_to_server.c_str(), display_string, "-logfile", d_->path_to_log_file.c_str(), "-config", d_->path_to_conf.c_str(), NULL); Process::SetEnv("DISPLAY", display_string, true); for (int i = 0; i < 10; ++i) { test_display = XOpenDisplay(NULL); if (test_display) { XCloseDisplay(test_display); return; } int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) { std::string message; message += "X server failed to start on display "; message += display_string; message += ". Ensure that the \"dummy\" video driver is installed. " "If the X.org server is older than 1.12, " "tests will need to be run as root. Check "; message += d_->path_to_log_file; message += " for any errors"; throw std::runtime_error(message); } else if (pid == 0) { sleep(1); /* Give the dummy X server some time to start */ } else if (pid == -1) { throw std::runtime_error("Could not get status of dummy X server " "process"); } else { throw std::runtime_error("Invalid child PID returned by Process::Wait()"); } } throw std::runtime_error("Unable to open connection to dummy X server"); } void xorg::testing::Environment::TearDown() { if (d_->process.Terminate()) { for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } } Kill(); } void xorg::testing::Environment::Kill() { if (!d_->process.Kill()) std::cerr << "Warning: Failed to kill dummy Xorg server: " << std::strerror(errno) << "\n"; for (int i = 0; i < 10; i++) { int status; int pid = waitpid(d_->process.Pid(), &status, WNOHANG); if (pid == d_->process.Pid()) return; sleep(1); /* Give the dummy X server more time to shut down */ } std::cerr << "Warning: Dummy X server did not shut down\n"; } <|endoftext|>
<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attribute.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/attribute/attributevector.hpp> #include <vespa/searchlib/attribute/integerbase.h> #include <vespa/log/log.h> LOG_SETUP("attribute_compaction_test"); using search::IntegerAttribute; using search::AttributeVector; using search::attribute::Config; using search::attribute::BasicType; using search::attribute::CollectionType; using AttributePtr = AttributeVector::SP; using AttributeStatus = search::attribute::Status; namespace { template <typename VectorType> bool is(AttributePtr &v) { return dynamic_cast<VectorType *>(v.get()); } template <typename VectorType> VectorType &as(AttributePtr &v) { return dynamic_cast<VectorType &>(*v); } void populateAttribute(IntegerAttribute &v, uint32_t docIdLimit) { for(uint32_t docId = 0; docId < docIdLimit; ++docId) { uint32_t checkDocId = 0; EXPECT_TRUE(v.addDoc(checkDocId)); EXPECT_EQUAL(docId, checkDocId); v.clearDoc(docId); for (size_t vi = 0; vi <= 40; ++vi) { EXPECT_TRUE(v.append(docId, 42, 1) ); } } v.commit(true); v.incGeneration(); } void populateAttribute(AttributePtr &v, uint32_t docIdLimit) { if (is<IntegerAttribute>(v)) { populateAttribute(as<IntegerAttribute>(v), docIdLimit); } } void cleanAttribute(AttributeVector &v, uint32_t docIdLimit) { for (uint32_t docId = 0; docId < docIdLimit; ++docId) { v.clearDoc(docId); } v.commit(true); v.incGeneration(); } } class Fixture { public: AttributePtr _v; Fixture(Config cfg) : _v() { _v = search::AttributeFactory::createAttribute("test", cfg); } ~Fixture() { } void populate(uint32_t docIdLimit) { populateAttribute(_v, docIdLimit); } void clean(uint32_t docIdLimit) { cleanAttribute(*_v, docIdLimit); } AttributeStatus getStatus() { _v->commit(true); return _v->getStatus(); } AttributeStatus getStatus(const vespalib::string &prefix) { AttributeStatus status(getStatus()); LOG(info, "status %s: used=%zu, dead=%zu, onHold=%zu", prefix.c_str(), status.getUsed(), status.getDead(), status.getOnHold()); return status; } }; TEST_F("Test that compaction of integer array attribute reduces memory usage", Fixture({ BasicType::INT64, CollectionType::ARRAY })) { f.populate(3000); AttributeStatus beforeStatus = f.getStatus("before"); f.clean(2000); AttributeStatus afterStatus = f.getStatus("after"); EXPECT_LESS(afterStatus.getUsed(), beforeStatus.getUsed()); } TEST_MAIN() { TEST_RUN_ALL(); } <commit_msg>Unit test compaction triggered by address space usage.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #include <vespa/fastos/fastos.h> #include <vespa/vespalib/testkit/test_kit.h> #include <vespa/searchlib/attribute/attribute.h> #include <vespa/searchlib/attribute/attributefactory.h> #include <vespa/searchlib/attribute/attributevector.hpp> #include <vespa/searchlib/attribute/integerbase.h> #include <vespa/searchlib/attribute/address_space_usage.h> #include <vespa/log/log.h> LOG_SETUP("attribute_compaction_test"); using search::IntegerAttribute; using search::AttributeVector; using search::attribute::Config; using search::attribute::BasicType; using search::attribute::CollectionType; using search::AddressSpace; using AttributePtr = AttributeVector::SP; using AttributeStatus = search::attribute::Status; namespace { struct DocIdRange { uint32_t docIdStart; uint32_t docIdLimit; DocIdRange(uint32_t docIdStart_, uint32_t docIdLimit_) : docIdStart(docIdStart_), docIdLimit(docIdLimit_) { } uint32_t begin() { return docIdStart; } uint32_t end() { return docIdLimit; } uint32_t size() { return end() - begin(); } }; template <typename VectorType> bool is(AttributePtr &v) { return dynamic_cast<VectorType *>(v.get()); } template <typename VectorType> VectorType &as(AttributePtr &v) { return dynamic_cast<VectorType &>(*v); } void cleanAttribute(AttributeVector &v, DocIdRange range) { for (uint32_t docId = range.begin(); docId < range.end(); ++docId) { v.clearDoc(docId); } v.commit(true); v.incGeneration(); } DocIdRange addAttributeDocs(AttributePtr &v, uint32_t numDocs) { uint32_t startDoc = 0; uint32_t lastDoc = 0; EXPECT_TRUE(v->addDocs(startDoc, lastDoc, numDocs)); EXPECT_EQUAL(startDoc + numDocs - 1, lastDoc); DocIdRange range(startDoc, startDoc + numDocs); cleanAttribute(*v, range); return range; } void populateAttribute(IntegerAttribute &v, DocIdRange range, uint32_t values) { for(uint32_t docId = range.begin(); docId < range.end(); ++docId) { v.clearDoc(docId); for (uint32_t vi = 0; vi <= values; ++vi) { EXPECT_TRUE(v.append(docId, 42, 1) ); } if ((docId % 100) == 0) { v.commit(); } } v.commit(true); v.incGeneration(); } void populateAttribute(AttributePtr &v, DocIdRange range, uint32_t values) { if (is<IntegerAttribute>(v)) { populateAttribute(as<IntegerAttribute>(v), range, values); } } void hammerAttribute(IntegerAttribute &v, DocIdRange range, uint32_t count) { uint32_t work = 0; for (uint32_t i = 0; i < count; ++i) { for (uint32_t docId = range.begin(); docId < range.end(); ++docId) { v.clearDoc(docId); EXPECT_TRUE(v.append(docId, 42, 1)); } work += range.size(); if (work >= 100000) { v.commit(true); work = 0; } else { v.commit(); } } v.commit(true); v.incGeneration(); } void hammerAttribute(AttributePtr &v, DocIdRange range, uint32_t count) { if (is<IntegerAttribute>(v)) { hammerAttribute(as<IntegerAttribute>(v), range, count); } } Config compactAddressSpaceAttributeConfig(bool enableAddressSpaceCompact) { Config cfg(BasicType::INT8, CollectionType::ARRAY); cfg.setCompactionStrategy({ 1.0, (enableAddressSpaceCompact ? 0.2 : 1.0) }); return cfg; } } class Fixture { public: AttributePtr _v; Fixture(Config cfg) : _v() { _v = search::AttributeFactory::createAttribute("test", cfg); } ~Fixture() { } DocIdRange addDocs(uint32_t numDocs) { return addAttributeDocs(_v, numDocs); } void populate(DocIdRange range, uint32_t values) { populateAttribute(_v, range, values); } void hammer(DocIdRange range, uint32_t count) { hammerAttribute(_v, range, count); } void clean(DocIdRange range) { cleanAttribute(*_v, range); } AttributeStatus getStatus() { _v->commit(true); return _v->getStatus(); } AttributeStatus getStatus(const vespalib::string &prefix) { AttributeStatus status(getStatus()); LOG(info, "status %s: used=%zu, dead=%zu, onHold=%zu", prefix.c_str(), status.getUsed(), status.getDead(), status.getOnHold()); return status; } const Config &getConfig() const { return _v->getConfig(); } AddressSpace getMultiValueAddressSpaceUsage() const {return _v->getAddressSpaceUsage().multiValueUsage(); } AddressSpace getMultiValueAddressSpaceUsage(const vespalib::string &prefix) { AddressSpace usage(getMultiValueAddressSpaceUsage()); LOG(info, "address space usage %s: used=%zu, dead=%zu, limit=%zu, usage=%12.8f", prefix.c_str(), usage.used(), usage.dead(), usage.limit(), usage.usage()); return usage; } }; TEST_F("Test that compaction of integer array attribute reduces memory usage", Fixture({ BasicType::INT64, CollectionType::ARRAY })) { DocIdRange range1 = f.addDocs(2000); DocIdRange range2 = f.addDocs(1000); f.populate(range1, 40); f.populate(range2, 40); AttributeStatus beforeStatus = f.getStatus("before"); f.clean(range1); AttributeStatus afterStatus = f.getStatus("after"); EXPECT_LESS(afterStatus.getUsed(), beforeStatus.getUsed()); } TEST_F("Test that no compaction of int8 array attribute increases address space usage", Fixture(compactAddressSpaceAttributeConfig(false))) { DocIdRange range1 = f.addDocs(1000); DocIdRange range2 = f.addDocs(1000); f.populate(range1, 1000); f.hammer(range2, 101); AddressSpace afterSpace = f.getMultiValueAddressSpaceUsage("after"); EXPECT_EQUAL(100001, afterSpace.dead()); } TEST_F("Test that compaction of int8 array attribute limits address space usage", Fixture(compactAddressSpaceAttributeConfig(true))) { DocIdRange range1 = f.addDocs(1000); DocIdRange range2 = f.addDocs(1000); f.populate(range1, 1000); f.hammer(range2, 101); AddressSpace afterSpace = f.getMultiValueAddressSpaceUsage("after"); EXPECT_GREATER(65536, afterSpace.dead()); } TEST_MAIN() { TEST_RUN_ALL(); } <|endoftext|>
<commit_before>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2003 Christophe Hermier * * 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 <wx/intl.h> #include <wx/colour.h> #include <wx/utils.h> #include <wx/textfile.h> #include "catalog.h" namespace { // colours used in the list: // (FIXME: this is duplicated with code in edframe.cpp, get rid of this // duplication, preferably by making the colours customizable and stored // in wxConfig) #define g_darkColourFactor 0.95 #define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\ int((g)*g_darkColourFactor),\ int((b)*g_darkColourFactor))) #define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) } wxColour g_ItemColourNormal[2] = LIST_COLOURS(0xFF,0xFF,0xFF), // white g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue g_ItemColourFuzzy[2] = LIST_COLOURS(0xF4,0xF1,0xC1); // yellow // escape string for HTML: wxString Escape(const wxString& str) { wxString s(str); s.Replace(_T("&"), _T("&amp;")); s.Replace(_T("<"), _T("&lt;")); s.Replace(_T(">"), _T("&gt;")); return s; } } // anonymous namespace bool Catalog::ExportToHTML(const wxString& filename) { size_t i; wxTextFile f; if ( wxFileExists(filename) ) { wxRemoveFile ( filename); } if (!f.Create(filename)) { return false; } // TODO use some kind of HTML template system to allow different styles wxString line; // HTML HEADER f.AddLine(_T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")); f.AddLine(_T("<html>")); f.AddLine(_T("<head>")); line.Printf(_T("<title> %s - %s / %s - Poedit Export </title>"), Escape(m_header.Project).c_str(), Escape(m_header.Language).c_str(), Escape(m_header.Country).c_str()); f.AddLine(line); f.AddLine(_T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" ) ); f.AddLine(_T("</head>")); f.AddLine(_T("<body bgcolor='#FFFFFF'>")); line.Printf(_T("<h1> %s : %s / %s</h1>"), Escape(m_header.Project).c_str(), Escape(m_header.Language).c_str(), Escape(m_header.Country).c_str()); f.AddLine(line); // po file header information : // String here are duplicates from the ones in setting.xrc // TODO find a way if possible to synchronize them f.AddLine(_T("<table align=center border=1 cellspacing=2 cellpadding=4>")); line.Printf(_T("<tr><th colspan=2>%s</th></tr>"), _("Project info")); f.AddLine(line); wxString line_format = _T("<tr><td>%s</td><td>%s</td></tr>"); line.Printf(line_format, _("Project name and version:"), Escape(m_header.Project).c_str()); f.AddLine(line); line.Printf(line_format, _("Language:"), Escape(m_header.Language).c_str()); f.AddLine(line); line.Printf(line_format, _("Country:"), Escape(m_header.Country).c_str()); f.AddLine(line); line.Printf(line_format, _("Team:"), Escape(m_header.Team).c_str()); f.AddLine(line); line.Printf(_T("<tr><td>%s</td><td><a href=\"mailto:%s\">%s</a></td></tr>"), _("Team's email address:"), Escape(m_header.TeamEmail).c_str(), Escape(m_header.TeamEmail).c_str()); f.AddLine(line); line.Printf(line_format, _("Charset:"), Escape(m_header.Charset).c_str()); f.AddLine(line); f.AddLine( _T("</table>") ); // statistics int all = 0; int fuzzy = 0; int untranslated = 0; int badtokens = 0; int unfinished = 0; GetStatistics(&all, &fuzzy, &badtokens, &untranslated, &unfinished); int percent = (all == 0 ) ? 0 : (100 * (all - unfinished) / all); line.Printf(_("%i %% translated, %i strings (%i fuzzy, %i bad tokens, %i not translated)"), percent, all, fuzzy, badtokens, untranslated); f.AddLine(line); // data printed in a table : f.AddLine(_T("<table border=1 cellspacing=2 cellpadding=4>")); f.AddLine(_T("<tr>")); f.AddLine(_T("<th>")); f.AddLine(_("Source")); f.AddLine(_T("</th>")); f.AddLine(_T("<th>")); f.AddLine(_("Translation")); f.AddLine(_T("</th>")); f.AddLine(_T("</th>")); f.AddLine(_T("<th>")); f.AddLine(_("Notes")); f.AddLine(_T("</th>")); f.AddLine(_T("</tr>")); for (i = 0; i < GetCount(); i++) { const CatalogItem& data = m_items[i]; wxColour bgcolor = g_ItemColourNormal[i % 2]; wxString source_string = data.GetString(); wxString translation = data.GetTranslation(); if (translation.empty()) { translation = _T(" "); bgcolor = g_ItemColourUntranslated[i % 2]; } wxString flags; if (data.IsAutomatic()) { flags += _("Automatic translation"); flags += _T("<BR>"); } if (data.IsFuzzy()) { bgcolor = g_ItemColourFuzzy[i % 2]; flags += _("Fuzzy translation"); flags += _T("<BR>"); } if (flags.empty()) { flags = _T(" "); } wxString tr; tr.Printf(_T("<tr bgcolor='#%0X%0X%0X'>"), bgcolor.Red(), bgcolor.Green(), bgcolor.Blue()); f.AddLine(tr); f.AddLine(_T("<td>")); f.AddLine(Escape(source_string)); f.AddLine(_T("</td>")); f.AddLine(_T("<td>")); f.AddLine(Escape(translation)); f.AddLine(_T("</td>")); f.AddLine(_T("<td>")); f.AddLine(_T("<font size=\"-1\">")); f.AddLine(Escape(flags)); f.AddLine(_T("</font>")); f.AddLine(_T("</td>")); f.AddLine(_T("</tr>")); } f.AddLine(_T("</table>")); f.AddLine(_T("</body>")); f.AddLine(_T("</html>")); bool written = f.Write(wxTextFileType_None, wxConvUTF8); f.Close(); return written; } <commit_msg>Fix illegal markup in table header in HTML export.<commit_after>/* * This file is part of Poedit (http://www.poedit.net) * * Copyright (C) 2003 Christophe Hermier * * 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 <wx/intl.h> #include <wx/colour.h> #include <wx/utils.h> #include <wx/textfile.h> #include "catalog.h" namespace { // colours used in the list: // (FIXME: this is duplicated with code in edframe.cpp, get rid of this // duplication, preferably by making the colours customizable and stored // in wxConfig) #define g_darkColourFactor 0.95 #define DARKEN_COLOUR(r,g,b) (wxColour(int((r)*g_darkColourFactor),\ int((g)*g_darkColourFactor),\ int((b)*g_darkColourFactor))) #define LIST_COLOURS(r,g,b) { wxColour(r,g,b), DARKEN_COLOUR(r,g,b) } wxColour g_ItemColourNormal[2] = LIST_COLOURS(0xFF,0xFF,0xFF), // white g_ItemColourUntranslated[2] = LIST_COLOURS(0xA5,0xEA,0xEF), // blue g_ItemColourFuzzy[2] = LIST_COLOURS(0xF4,0xF1,0xC1); // yellow // escape string for HTML: wxString Escape(const wxString& str) { wxString s(str); s.Replace(_T("&"), _T("&amp;")); s.Replace(_T("<"), _T("&lt;")); s.Replace(_T(">"), _T("&gt;")); return s; } } // anonymous namespace bool Catalog::ExportToHTML(const wxString& filename) { size_t i; wxTextFile f; if ( wxFileExists(filename) ) { wxRemoveFile ( filename); } if (!f.Create(filename)) { return false; } // TODO use some kind of HTML template system to allow different styles wxString line; // HTML HEADER f.AddLine(_T("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">")); f.AddLine(_T("<html>")); f.AddLine(_T("<head>")); line.Printf(_T("<title> %s - %s / %s - Poedit Export </title>"), Escape(m_header.Project).c_str(), Escape(m_header.Language).c_str(), Escape(m_header.Country).c_str()); f.AddLine(line); f.AddLine(_T("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">" ) ); f.AddLine(_T("</head>")); f.AddLine(_T("<body bgcolor='#FFFFFF'>")); line.Printf(_T("<h1> %s : %s / %s</h1>"), Escape(m_header.Project).c_str(), Escape(m_header.Language).c_str(), Escape(m_header.Country).c_str()); f.AddLine(line); // po file header information : // String here are duplicates from the ones in setting.xrc // TODO find a way if possible to synchronize them f.AddLine(_T("<table align=center border=1 cellspacing=2 cellpadding=4>")); line.Printf(_T("<tr><th colspan=2>%s</th></tr>"), _("Project info")); f.AddLine(line); wxString line_format = _T("<tr><td>%s</td><td>%s</td></tr>"); line.Printf(line_format, _("Project name and version:"), Escape(m_header.Project).c_str()); f.AddLine(line); line.Printf(line_format, _("Language:"), Escape(m_header.Language).c_str()); f.AddLine(line); line.Printf(line_format, _("Country:"), Escape(m_header.Country).c_str()); f.AddLine(line); line.Printf(line_format, _("Team:"), Escape(m_header.Team).c_str()); f.AddLine(line); line.Printf(_T("<tr><td>%s</td><td><a href=\"mailto:%s\">%s</a></td></tr>"), _("Team's email address:"), Escape(m_header.TeamEmail).c_str(), Escape(m_header.TeamEmail).c_str()); f.AddLine(line); line.Printf(line_format, _("Charset:"), Escape(m_header.Charset).c_str()); f.AddLine(line); f.AddLine( _T("</table>") ); // statistics int all = 0; int fuzzy = 0; int untranslated = 0; int badtokens = 0; int unfinished = 0; GetStatistics(&all, &fuzzy, &badtokens, &untranslated, &unfinished); int percent = (all == 0 ) ? 0 : (100 * (all - unfinished) / all); line.Printf(_("%i %% translated, %i strings (%i fuzzy, %i bad tokens, %i not translated)"), percent, all, fuzzy, badtokens, untranslated); f.AddLine(line); // data printed in a table : f.AddLine(_T("<table border=1 cellspacing=2 cellpadding=4>")); f.AddLine(_T("<tr>")); f.AddLine(_T("<th>")); f.AddLine(_("Source")); f.AddLine(_T("</th>")); f.AddLine(_T("<th>")); f.AddLine(_("Translation")); f.AddLine(_T("</th>")); f.AddLine(_T("<th>")); f.AddLine(_("Notes")); f.AddLine(_T("</th>")); f.AddLine(_T("</tr>")); for (i = 0; i < GetCount(); i++) { const CatalogItem& data = m_items[i]; wxColour bgcolor = g_ItemColourNormal[i % 2]; wxString source_string = data.GetString(); wxString translation = data.GetTranslation(); if (translation.empty()) { translation = _T(" "); bgcolor = g_ItemColourUntranslated[i % 2]; } wxString flags; if (data.IsAutomatic()) { flags += _("Automatic translation"); flags += _T("<BR>"); } if (data.IsFuzzy()) { bgcolor = g_ItemColourFuzzy[i % 2]; flags += _("Fuzzy translation"); flags += _T("<BR>"); } if (flags.empty()) { flags = _T(" "); } wxString tr; tr.Printf(_T("<tr bgcolor='#%0X%0X%0X'>"), bgcolor.Red(), bgcolor.Green(), bgcolor.Blue()); f.AddLine(tr); f.AddLine(_T("<td>")); f.AddLine(Escape(source_string)); f.AddLine(_T("</td>")); f.AddLine(_T("<td>")); f.AddLine(Escape(translation)); f.AddLine(_T("</td>")); f.AddLine(_T("<td>")); f.AddLine(_T("<font size=\"-1\">")); f.AddLine(Escape(flags)); f.AddLine(_T("</font>")); f.AddLine(_T("</td>")); f.AddLine(_T("</tr>")); } f.AddLine(_T("</table>")); f.AddLine(_T("</body>")); f.AddLine(_T("</html>")); bool written = f.Write(wxTextFileType_None, wxConvUTF8); f.Close(); return written; } <|endoftext|>
<commit_before>#include "fake_player.hpp" #include <ctime> #include <boost/random/discrete_distribution.hpp> #include <boost/log/core.hpp> #include <boost/log/trivial.hpp> #include <boost/log/exceptions.hpp> #include <boost/log/sources/global_logger_storage.hpp> #include <boost/log/sources/logger.hpp> #include <boost/log/sources/severity_logger.hpp> #include "exception.hpp" #include "walk_move.hpp" #include "wall_move.hpp" BOOST_LOG_INLINE_GLOBAL_LOGGER_DEFAULT(my_logger, boost::log::sources::logger) namespace Quoridor { FakePlayer::FakePlayer(std::shared_ptr<Board> board, std::shared_ptr<Pawn> pawn) : board_(board), pawn_(pawn), goal_nodes_(), gen_() { board_->pawn_goal_nodes(pawn_, &goal_nodes_); gen_.seed(static_cast<unsigned int>(std::time(NULL))); } FakePlayer::~FakePlayer() { } IMove *FakePlayer::get_move() { boost::random::discrete_distribution<> dist{0.6, 0.6}; boost::log::sources::logger &lg = my_logger::get(); if (dist(gen_) == 0) { size_t min_path_len = 81; std::list<Pos> min_path; for (auto end_node : goal_nodes_) { std::list<Pos> path; if (board_->get_path(pawn_, end_node, &path)) { if (min_path_len > path.size()) { min_path_len = path.size(); min_path = path; } } } if (min_path.size() == 0) { throw Exception("all pathes are blocked"); } auto node_it = min_path.begin(); Pos next_node = *node_it; BOOST_LOG_SEV(lg, boost::log::trivial::info) << "moving to " << next_node.row() << ":" << next_node.col(); if (board_->is_occupied(next_node)) { // @todo } return new WalkMove(next_node); } else { boost::random::discrete_distribution<> dist_2{8, 2}; boost::random::uniform_int_distribution<> dist_9(0, 8); boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1}; return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2)); } } } /* namespace Quoridor */ <commit_msg>Fix logging in fake_player.cpp<commit_after>#include "fake_player.hpp" #include <ctime> #include <boost/random/discrete_distribution.hpp> #include "walk_move.hpp" #include "wall_move.hpp" #include "exception.hpp" #include "logger.hpp" static boost::log::sources::severity_logger<boost::log::trivial::severity_level> lg; namespace Quoridor { FakePlayer::FakePlayer(std::shared_ptr<Board> board, std::shared_ptr<Pawn> pawn) : board_(board), pawn_(pawn), goal_nodes_(), gen_() { board_->pawn_goal_nodes(pawn_, &goal_nodes_); gen_.seed(static_cast<unsigned int>(std::time(NULL))); } FakePlayer::~FakePlayer() { } IMove *FakePlayer::get_move() { boost::random::discrete_distribution<> dist{0.6, 0.6}; if (dist(gen_) == 0) { size_t min_path_len = 81; std::list<Pos> min_path; for (auto end_node : goal_nodes_) { std::list<Pos> path; if (board_->get_path(pawn_, end_node, &path)) { if (min_path_len > path.size()) { min_path_len = path.size(); min_path = path; } } } if (min_path.size() == 0) { throw Exception("all pathes are blocked"); } auto node_it = min_path.begin(); Pos next_node = *node_it; BOOST_LOG_SEV(lg, boost::log::trivial::info) << "moving to " << next_node.row() << ":" << next_node.col(); if (board_->is_occupied(next_node)) { // @todo } return new WalkMove(next_node); } else { boost::random::discrete_distribution<> dist_2{8, 2}; boost::random::uniform_int_distribution<> dist_9(0, 8); boost::random::discrete_distribution<> dist_8{1, 1, 2, 3, 3, 2, 1, 1}; return new WallMove(Wall(dist_2(gen_), dist_9(gen_), dist_8(gen_), 2)); } } } /* namespace Quoridor */ <|endoftext|>
<commit_before>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // Read input files for standards, skys and targets. // Try to read SS and SF before targets to avoid wasting time if these // smaller files can't be read. init_time_at(time,"# Read target, SS, SF files",t); MTL SStars = read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF = read_MTLfile(F.SkyFfile, F,0,1); MTL Targ = read_MTLfile(F.Targfile, F,0,0); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" Target size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" Standard Star size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" Sky Fiber size %d \n",M.size()); F.Ngal = M.size(); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); // Make a plan ---------------------------------------------------- print_time(t,"# Start assignment at : "); simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j);//suborder[jused] is jused-th used plate not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); //for(int i=0;i<F.NUsedplate;i++)printf(" jused %d j %d\n",i,A.suborder[i]); // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<3; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } init_time_at(time,"# assign SS and SF ",t); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } // Results -------------------------------------------------------*/ std::vector <int> total_used_by_class(M.priority_list.size(),0); int total_used_SS=0; int total_used_SF=0; for (int jused=0;jused<F.NUsedplate;++jused){ std::vector <int> used_by_class(M.priority_list.size(),0); int used_SS=0; int used_SF=0; int j=A.suborder[jused]; for(int k=0;k<F.Nfiber;++k){ int g=A.TF[j][k]; if(g!=-1){ if(M[g].SS){ total_used_SS++; used_SS++; } else if(M[g].SF){ used_SF++; total_used_SF++; } else{ used_by_class[M[g].priority_class]++; total_used_by_class[M[g].priority_class]++; } } } /* printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,used_by_class[pr]); } printf("\n"); */ } init_time_at(time,"# count SS and SF ",t); printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF); std::cout.flush(); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,total_used_by_class[pr]); std::cout.flush(); } printf("\n"); init_time_at(time,"# print txt files ",t); if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); } init_time_at(time,"# print fits files ",t); if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(j,F.outDir,M,P,pp,F,A); // Write output } print_time(t,"# Finished !... in"); return(0); } <commit_msg>debugging fiberassign<commit_after>#include <cstdlib> #include <cmath> #include <fstream> #include <sstream> #include <iostream> #include <iomanip> #include <string> #include <vector> #include <algorithm> #include <exception> #include <sys/time.h> #include "modules/htmTree.h" #include "modules/kdTree.h" #include "misc.h" #include "feat.h" #include "structs.h" #include "collision.h" #include "global.h" //reduce redistributes, updates 07/02/15 rnc int main(int argc, char **argv) { //// Initializations --------------------------------------------- srand48(1234); // Make sure we have reproducability check_args(argc); Time t, time; // t for global, time for local init_time(t); Feat F; MTL M; // Read parameters file // F.readInputFile(argv[1]); printFile(argv[1]); // debug failure to assign any fibers 8/22/16 FILE * FB; str s="/project/projectdirs/desi/users/rncahn/output.txt"; FB=fopen(s.c_str(),"w"); fprintf(FB,"test of output.txt\n"); // Read input files for standards, skys and targets. // Try to read SS and SF before targets to avoid wasting time if these // smaller files can't be read. init_time_at(time,"# Read target, SS, SF files",t); MTL SStars = read_MTLfile(F.SStarsfile,F,1,0); MTL SkyF = read_MTLfile(F.SkyFfile, F,0,1); MTL Targ = read_MTLfile(F.Targfile, F,0,0); print_time(time,"# ... took :"); //combine the three input files M=Targ; printf(" Target size %d \n",M.size()); M.insert(M.end(),SStars.begin(),SStars.end()); printf(" Standard Star size %d \n",M.size()); M.insert(M.end(),SkyF.begin(),SkyF.end()); printf(" Sky Fiber size %d \n",M.size()); F.Ngal = M.size(); assign_priority_class(M); std::vector <int> count_class(M.priority_list.size(),0); for(int i;i<M.size();++i){ if(!M[i].SS&&!M[i].SF){ count_class[M[i].priority_class]+=1; } } for(int i;i<M.priority_list.size();++i){ printf(" class %d number %d\n",i,count_class[i]); } print_time(time,"# ... took :"); // fiber positioners PP pp; pp.read_fiber_positions(F); F.Nfiber = pp.fp.size()/2; F.Npetal = max(pp.spectrom)+1; F.Nfbp = (int) (F.Nfiber/F.Npetal);// fibers per petal = 500 pp.get_neighbors(F); pp.compute_fibsofsp(F); //P is original list of plates Plates P = read_plate_centers(F); F.Nplate=P.size(); printf("# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); fprintf(FB,"# Read %s plate centers from %s and %d fibers from %s\n",f(F.Nplate).c_str(),F.tileFile.c_str(),F.Nfiber,F.fibFile.c_str()); // Computes geometries of cb and fh: pieces of positioner - used to determine possible collisions F.cb = create_cb(); // cb=central body F.fh = create_fh(); // fh=fiber holder //// Collect available galaxies <-> tilefibers -------------------- // HTM Tree of galaxies const double MinTreeSize = 0.01; init_time_at(time,"# Start building HTM tree",t); htmTree<struct target> T(M,MinTreeSize); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect galaxies at ",t); // For plates/fibers, collect available galaxies; done in parallel P[plate j].av_gal[k]=[g1,g2,..] collect_galaxies_for_all(M,T,P,pp,F); print_time(time,"# ... took :");//T.stats(); init_time_at(time,"# collect available tile-fibers at",t); // For each galaxy, computes available tilefibers G[i].av_tfs = [(j1,k1),(j2,k2),..] collect_available_tilefibers(M,P,F); //results_on_inputs("doc/figs/",G,P,F,true); //// Assignment ||||||||||||||||||||||||||||||||||||||||||||||||||| printf(" Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); fprintf(FB," Nplate %d Ngal %d Nfiber %d \n", F.Nplate, F.Ngal, F.Nfiber); Assignment A(M,F); // Make a plan ---------------------------------------------------- print_time(t,"# Start assignment at : "); simple_assign(M,P,pp,F,A); //check to see if there are tiles with no galaxies //need to keep mapping of old tile list to new tile list //and inverse map A.inv_order=initList(F.Nplate,-1); int inv_count=0; for (int j=0;j<F.Nplate ;++j){ bool not_done=true; for(int k=0;k<F.Nfiber && not_done;++k){ if(A.TF[j][k]!=-1){ A.suborder.push_back(j);//suborder[jused] is jused-th used plate fprintf(FB," j %d k %d used jused %d \n",j,k,inv_count); not_done=false; A.inv_order[j]=inv_count;//inv_order[j] is -1 unless used inv_count++; } } } F.NUsedplate=A.suborder.size(); printf(" Plates actually used %d \n",F.NUsedplate); fprintf(FB," Plates actually used %d \n",F.NUsedplate); for(int i=0;i<F.NUsedplate;i++)fprintf(FB," jused %d j %d\n",i,A.suborder[i]); // Smooth out distribution of free fibers, and increase the number of assignments for (int i=0; i<1; i++) redistribute_tf(M,P,pp,F,A,0);// more iterations will improve performance slightly for (int i=0; i<3; i++) { improve(M,P,pp,F,A,0); redistribute_tf(M,P,pp,F,A,0); } init_time_at(time,"# assign SS and SF ",t); //try assigning SF and SS before real time assignment for (int jused=0;jused<F.NUsedplate;++jused){ int j=A.suborder[jused]; assign_sf_ss(j,M,P,pp,F,A); // Assign SS and SF for each tile assign_unused(j,M,P,pp,F,A); } // Results -------------------------------------------------------*/ std::vector <int> total_used_by_class(M.priority_list.size(),0); int total_used_SS=0; int total_used_SF=0; for (int jused=0;jused<F.NUsedplate;++jused){ std::vector <int> used_by_class(M.priority_list.size(),0); int used_SS=0; int used_SF=0; int j=A.suborder[jused]; for(int k=0;k<F.Nfiber;++k){ int g=A.TF[j][k]; if(g!=-1){ if(M[g].SS){ total_used_SS++; used_SS++; } else if(M[g].SF){ used_SF++; total_used_SF++; } else{ used_by_class[M[g].priority_class]++; total_used_by_class[M[g].priority_class]++; } } } /* printf(" plate jused %5d j %5d SS %4d SF %4d",jused,j,used_SS,used_SF); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,used_by_class[pr]); } printf("\n"); */ } init_time_at(time,"# count SS and SF ",t); printf(" Totals SS %4d SF %4d",total_used_SS,total_used_SF); std::cout.flush(); for (int pr=0;pr<M.priority_list.size();++pr){ printf(" class %2d %5d",pr,total_used_by_class[pr]); std::cout.flush(); } printf("\n"); init_time_at(time,"# print txt files ",t); if (F.PrintAscii) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; write_FAtile_ascii(j,F.outDir,M,P,pp,F,A); } init_time_at(time,"# print fits files ",t); if (F.PrintFits) for (int jused=0; jused<F.NUsedplate; jused++){ int j=A.suborder[jused]; fa_write(j,F.outDir,M,P,pp,F,A); // Write output } print_time(t,"# Finished !... in"); return(0); } <|endoftext|>
<commit_before>/* * Copyright (C) 2016 deipi.com LLC and contributors. 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 "field_parser.h" #define DOUBLEDOTS ':' #define DOUBLEQUOTE '"' #define SINGLEQUOTE '\'' #define LEFT_SQUARE_BRACKET '[' #define RIGHT_SQUARE_BRACKET ']' #define COMMA ',' FieldParser::FieldParser(const std::string& p) : fstr(p), isEnd(false), len_field(0), off_field(nullptr), len_fieldot(0), off_fieldot(nullptr), len_value(0), off_value(nullptr), len_double_quote_value(0), off_double_quote_value(nullptr), len_single_quote_value(0), off_single_quote_value(nullptr), isrange(false) { } void FieldParser::parse() { auto currentState = FieldParser::State::INIT; auto oldState = currentState; auto currentSymbol = fstr.data(); char quote; while (true) { switch (currentState) { case FieldParser::State::INIT: switch (*currentSymbol) { case '_': currentState = FieldParser::State::FIELD; off_field = currentSymbol; off_fieldot = currentSymbol; ++len_field; ++len_fieldot; break; case LEFT_SQUARE_BRACKET: currentState = FieldParser::State::INIT_SQUARE_BRACKET; isrange = true; break; case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE; quote = DOUBLEQUOTE; off_double_quote_value = currentSymbol; off_value = currentSymbol + 1; ++len_double_quote_value; ++len_value; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE; quote = SINGLEQUOTE; off_single_quote_value = currentSymbol; off_value = currentSymbol + 1; ++len_single_quote_value; ++len_value; break; default: if (isalnum(*currentSymbol)) { currentState = FieldParser::State::FIELD; off_field = currentSymbol; off_fieldot = currentSymbol; ++len_field; ++len_fieldot; } else if (isspace(*currentSymbol)) { currentState = FieldParser::State::INIT; } else { throw MSG_FieldParserError("Syntax error in query"); } break; } break; case FieldParser::State::FIELD: switch (*currentSymbol) { case DOUBLEDOTS: currentState = FieldParser::State::STARTVALUE; ++len_fieldot; break; case '\0': len_value = len_field; off_value = off_field; len_field = len_fieldot = 0; off_field = off_fieldot = nullptr; return; default: if (*currentSymbol != ' ') { ++len_field; ++len_fieldot; } break; } break; case FieldParser::State::STARTVALUE: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE; quote = DOUBLEQUOTE; off_double_quote_value = currentSymbol; off_value = off_double_quote_value + 1; ++len_double_quote_value; ++len_value; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE; quote = SINGLEQUOTE; off_single_quote_value = currentSymbol; off_value = off_single_quote_value + 1; ++len_single_quote_value; ++len_value; break; case LEFT_SQUARE_BRACKET: currentState = FieldParser::State::INIT_SQUARE_BRACKET; isrange = true; break; default: currentState = FieldParser::State::VALUE; off_value = currentSymbol; ++len_value; break; } case FieldParser::State::QUOTE: switch (*currentSymbol) { case '\\': currentState = FieldParser::State::ESCAPE; oldState = FieldParser::State::QUOTE; ++len_value; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; break; case SINGLEQUOTE: ++len_single_quote_value; break; } break; case '\0': ++len_value; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; break; case SINGLEQUOTE: ++len_single_quote_value; break; } break; default: if (*currentSymbol == quote) { currentState = FieldParser::State::END; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; --len_value; // subtract the last quote count break; case SINGLEQUOTE: ++len_single_quote_value; --len_value; // subtract the last quote count break; } } else { throw MSG_FieldParserError("Expected symbol: '%c'", quote); } break; } break; case FieldParser::State::ESCAPE: if (*currentSymbol != '\0') { currentState = oldState; switch(currentState) { case FieldParser::State::QUOTE: ++len_value; if (quote == DOUBLEQUOTE) { ++len_double_quote_value; } else if (quote == SINGLEQUOTE) { ++len_single_quote_value; } break; case FieldParser::State::QUOTE_SQUARE_BRACKET: if (isEnd) { end += *currentSymbol; } else { start += *currentSymbol; } break; default: break; } } else { throw MSG_FieldParserError("Syntax error in query escaped"); } break; case FieldParser::State::VALUE: if (*currentSymbol == '\0') { currentState = FieldParser::State::END; } else if (!isspace(*currentSymbol)) { ++len_value; } else { throw MSG_FieldParserError("Syntax error in query"); } break; case FieldParser::State::INIT_SQUARE_BRACKET: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = DOUBLEQUOTE; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = SINGLEQUOTE; break; case COMMA: currentState = FieldParser::State::SQUARE_BRACKET; isEnd = true; break; case RIGHT_SQUARE_BRACKET: currentState = FieldParser::State::END; break; case '\0': start += *currentSymbol; break; default: throw MSG_FieldParserError("Syntax error in query"); } break; case FieldParser::State::SQUARE_BRACKET: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = DOUBLEQUOTE; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = SINGLEQUOTE; break; case RIGHT_SQUARE_BRACKET: currentState = FieldParser::State::END; break; case '\0': end += *currentSymbol; break; default: throw MSG_FieldParserError("Expected symbol: ']'"); } break; case FieldParser::State::QUOTE_SQUARE_BRACKET: switch (*currentSymbol) { case '\\': currentState = FieldParser::State::ESCAPE; oldState = FieldParser::State::QUOTE_SQUARE_BRACKET; break; case '\0': break; default: if (*currentSymbol == quote) { currentState = FieldParser::State::END_SQUARE_BRACKET; } else if (isEnd) { end += *currentSymbol; } else { start += *currentSymbol; } break; } break; case FieldParser::State::END_SQUARE_BRACKET: if (*currentSymbol == RIGHT_SQUARE_BRACKET) { currentState = FieldParser::State::END; } else { throw MSG_FieldParserError("Expected symbol: ']'"); } break; case FieldParser::State::END: { return; } } ++currentSymbol; } } <commit_msg>Fixing Bug in FieldParser<commit_after>/* * Copyright (C) 2016 deipi.com LLC and contributors. 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 "field_parser.h" #define DOUBLEDOTS ':' #define DOUBLEQUOTE '"' #define SINGLEQUOTE '\'' #define LEFT_SQUARE_BRACKET '[' #define RIGHT_SQUARE_BRACKET ']' #define COMMA ',' FieldParser::FieldParser(const std::string& p) : fstr(p), isEnd(false), len_field(0), off_field(nullptr), len_fieldot(0), off_fieldot(nullptr), len_value(0), off_value(nullptr), len_double_quote_value(0), off_double_quote_value(nullptr), len_single_quote_value(0), off_single_quote_value(nullptr), isrange(false) { } void FieldParser::parse() { auto currentState = FieldParser::State::INIT; auto oldState = currentState; auto currentSymbol = fstr.data(); char quote; while (true) { switch (currentState) { case FieldParser::State::INIT: switch (*currentSymbol) { case '_': currentState = FieldParser::State::FIELD; off_field = currentSymbol; off_fieldot = currentSymbol; ++len_field; ++len_fieldot; break; case LEFT_SQUARE_BRACKET: currentState = FieldParser::State::INIT_SQUARE_BRACKET; isrange = true; break; case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE; quote = DOUBLEQUOTE; off_double_quote_value = currentSymbol; off_value = currentSymbol + 1; ++len_double_quote_value; ++len_value; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE; quote = SINGLEQUOTE; off_single_quote_value = currentSymbol; off_value = currentSymbol + 1; ++len_single_quote_value; ++len_value; break; default: if (isalnum(*currentSymbol)) { currentState = FieldParser::State::FIELD; off_field = currentSymbol; off_fieldot = currentSymbol; ++len_field; ++len_fieldot; } else if (isspace(*currentSymbol)) { currentState = FieldParser::State::INIT; } else { throw MSG_FieldParserError("Syntax error in query"); } break; } break; case FieldParser::State::FIELD: switch (*currentSymbol) { case DOUBLEDOTS: currentState = FieldParser::State::STARTVALUE; ++len_fieldot; break; case '\0': len_value = len_field; off_value = off_field; len_field = len_fieldot = 0; off_field = off_fieldot = nullptr; return; default: if (*currentSymbol != ' ') { ++len_field; ++len_fieldot; } break; } break; case FieldParser::State::STARTVALUE: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE; quote = DOUBLEQUOTE; off_double_quote_value = currentSymbol; off_value = off_double_quote_value + 1; ++len_double_quote_value; ++len_value; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE; quote = SINGLEQUOTE; off_single_quote_value = currentSymbol; off_value = off_single_quote_value + 1; ++len_single_quote_value; ++len_value; break; case LEFT_SQUARE_BRACKET: currentState = FieldParser::State::INIT_SQUARE_BRACKET; isrange = true; break; default: currentState = FieldParser::State::VALUE; off_value = currentSymbol; ++len_value; break; } break; case FieldParser::State::QUOTE: switch (*currentSymbol) { case '\\': currentState = FieldParser::State::ESCAPE; oldState = FieldParser::State::QUOTE; ++len_value; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; break; case SINGLEQUOTE: ++len_single_quote_value; break; } break; case '\0': ++len_value; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; break; case SINGLEQUOTE: ++len_single_quote_value; break; } break; default: if (*currentSymbol == quote) { currentState = FieldParser::State::END; switch (quote) { case DOUBLEQUOTE: ++len_double_quote_value; --len_value; // subtract the last quote count break; case SINGLEQUOTE: ++len_single_quote_value; --len_value; // subtract the last quote count break; } } else { throw MSG_FieldParserError("Expected symbol: '%c'", quote); } break; } break; case FieldParser::State::ESCAPE: if (*currentSymbol != '\0') { currentState = oldState; switch(currentState) { case FieldParser::State::QUOTE: ++len_value; if (quote == DOUBLEQUOTE) { ++len_double_quote_value; } else if (quote == SINGLEQUOTE) { ++len_single_quote_value; } break; case FieldParser::State::QUOTE_SQUARE_BRACKET: if (isEnd) { end += *currentSymbol; } else { start += *currentSymbol; } break; default: break; } } else { throw MSG_FieldParserError("Syntax error in query escaped"); } break; case FieldParser::State::VALUE: if (*currentSymbol == '\0') { currentState = FieldParser::State::END; } else if (!isspace(*currentSymbol)) { ++len_value; } else { throw MSG_FieldParserError("Syntax error in query"); } break; case FieldParser::State::INIT_SQUARE_BRACKET: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = DOUBLEQUOTE; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = SINGLEQUOTE; break; case COMMA: currentState = FieldParser::State::SQUARE_BRACKET; isEnd = true; break; case RIGHT_SQUARE_BRACKET: currentState = FieldParser::State::END; break; case '\0': start += *currentSymbol; break; default: throw MSG_FieldParserError("Syntax error in query"); } break; case FieldParser::State::SQUARE_BRACKET: switch (*currentSymbol) { case DOUBLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = DOUBLEQUOTE; break; case SINGLEQUOTE: currentState = FieldParser::State::QUOTE_SQUARE_BRACKET; quote = SINGLEQUOTE; break; case RIGHT_SQUARE_BRACKET: currentState = FieldParser::State::END; break; case '\0': end += *currentSymbol; break; default: throw MSG_FieldParserError("Expected symbol: ']'"); } break; case FieldParser::State::QUOTE_SQUARE_BRACKET: switch (*currentSymbol) { case '\\': currentState = FieldParser::State::ESCAPE; oldState = FieldParser::State::QUOTE_SQUARE_BRACKET; break; case '\0': break; default: if (*currentSymbol == quote) { currentState = FieldParser::State::END_SQUARE_BRACKET; } else if (isEnd) { end += *currentSymbol; } else { start += *currentSymbol; } break; } break; case FieldParser::State::END_SQUARE_BRACKET: if (*currentSymbol == RIGHT_SQUARE_BRACKET) { currentState = FieldParser::State::END; } else { throw MSG_FieldParserError("Expected symbol: ']'"); } break; case FieldParser::State::END: { return; } } ++currentSymbol; } } <|endoftext|>
<commit_before>/* * Copyright (c)2015 - 2016 Oasis LMF Limited * 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 original author of this software 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 OWNER 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. */ /* Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <fcntl.h> #include <assert.h> #include "fmcalc.h" #include "../include/oasis.h" #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #include <signal.h> #include <string.h> #endif char *progname = 0; void help() { fprintf(stderr, "-a set allocrule (default none)\n" "-o run old fm_profile\n" "-M max level (optional)\n" "-p inputpath (relative or full path)\n" "-n feed net value (used for reinsurance)\n" "-O Alloc rule2 optimization off" "-d debug\n" "-v version\n" "-h help\n" ); } #if !defined(_MSC_VER) && !defined(__MINGW32__) void segfault_sigaction(int signal, siginfo_t *si, void *arg) { fprintf(stderr, "%s: Segment fault at address: %p\n", progname, si->si_addr); exit(0); } #endif int main(int argc, char* argv[]) { progname = argv[0]; int new_max = -1; int allocrule = 0; int opt; std::string inputpath; bool oldFMProfile = false; bool debug = false; bool allocruleOptimizationOff = false; bool netvalue = false; while ((opt = getopt(argc, argv, "dnvhoOM:p:a:")) != -1) { switch (opt) { case 'o': oldFMProfile = true; break; case 'O': allocruleOptimizationOff = true; break; case 'd': debug = true; break; case 'M': new_max = atoi(optarg); break; case 'a': allocrule = atoi(optarg); break; case 'v': fprintf(stderr, "%s : version: %s\n", argv[0], VERSION); exit(EXIT_FAILURE); break; case 'p': inputpath = optarg; break; case 'n': netvalue = true; break; case 'h': help(); exit(EXIT_FAILURE); default: help(); exit(EXIT_FAILURE); } } #if !defined(_MSC_VER) && !defined(__MINGW32__) struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = segfault_sigaction; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); #endif if (allocrule < 0 || allocrule > 2) { fprintf(stderr, "%s: Invalid allocrule %d\n", progname,allocrule); exit(1); } try { initstreams("", ""); fmcalc fc(new_max, allocrule, inputpath, netvalue, oldFMProfile,debug, allocruleOptimizationOff); fc.doit(); } catch (std::bad_alloc) { fprintf(stderr, "%s: Memory allocation failed\n", progname); exit(0); } return 0; } <commit_msg>Fix return code on fmcalc<commit_after>/* * Copyright (c)2015 - 2016 Oasis LMF Limited * 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 original author of this software 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 OWNER 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. */ /* Author: Ben Matharu email: ben.matharu@oasislmf.org */ #include <iostream> #include <fstream> #include <sstream> #include <stdio.h> #include <stdlib.h> #include <algorithm> #include <fcntl.h> #include <assert.h> #include "fmcalc.h" #include "../include/oasis.h" #if defined(_MSC_VER) #include "../wingetopt/wingetopt.h" #else #include <unistd.h> #include <signal.h> #include <string.h> #endif char *progname = 0; void help() { fprintf(stderr, "-a set allocrule (default none)\n" "-o run old fm_profile\n" "-M max level (optional)\n" "-p inputpath (relative or full path)\n" "-n feed net value (used for reinsurance)\n" "-O Alloc rule2 optimization off" "-d debug\n" "-v version\n" "-h help\n" ); } #if !defined(_MSC_VER) && !defined(__MINGW32__) void segfault_sigaction(int signal, siginfo_t *si, void *arg) { fprintf(stderr, "%s: Segment fault at address: %p\n", progname, si->si_addr); exit(0); } #endif int main(int argc, char* argv[]) { progname = argv[0]; int new_max = -1; int allocrule = 0; int opt; std::string inputpath; bool oldFMProfile = false; bool debug = false; bool allocruleOptimizationOff = false; bool netvalue = false; while ((opt = getopt(argc, argv, "dnvhoOM:p:a:")) != -1) { switch (opt) { case 'o': oldFMProfile = true; break; case 'O': allocruleOptimizationOff = true; break; case 'd': debug = true; break; case 'M': new_max = atoi(optarg); break; case 'a': allocrule = atoi(optarg); break; case 'v': fprintf(stderr, "%s : version: %s\n", argv[0], VERSION); exit(EXIT_FAILURE); break; case 'p': inputpath = optarg; break; case 'n': netvalue = true; break; case 'h': help(); exit(EXIT_FAILURE); default: help(); exit(EXIT_FAILURE); } } #if !defined(_MSC_VER) && !defined(__MINGW32__) struct sigaction sa; memset(&sa, 0, sizeof(struct sigaction)); sigemptyset(&sa.sa_mask); sa.sa_sigaction = segfault_sigaction; sa.sa_flags = SA_SIGINFO; sigaction(SIGSEGV, &sa, NULL); #endif if (allocrule < 0 || allocrule > 2) { fprintf(stderr, "%s: Invalid allocrule %d\n", progname,allocrule); exit(1); } try { initstreams("", ""); fmcalc fc(new_max, allocrule, inputpath, netvalue, oldFMProfile,debug, allocruleOptimizationOff); fc.doit(); } catch (std::bad_alloc) { fprintf(stderr, "%s: Memory allocation failed\n", progname); exit(1); } return 0; } <|endoftext|>
<commit_before>#include "likelihood.h" #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSet.h> #include <mkl.h> #include <cmath> template <class V, class M> Likelihood<V, M>::Likelihood(const char * prefix, const QUESO::VectorSet<V, M> & domainSet) : QUESO::BaseScalarFunction<V, M>(prefix, domainSet), m_observationParameter(1.0), m_num_simulations(10), m_simulations(m_num_simulations), m_simulationParameters(m_num_simulations), m_rho(0.5) { // Generate observational data double x = 0.25; // Observation location m_observation = m_observationParameter * std::sin(2.0 * M_PI * x); // Generate `simulation data' for (unsigned int i = 0; i < m_num_simulations; i++) { // Evenly spaced parameters between 0 and 2 m_simulationParameters[i] = i * 2.0 / (m_num_simulations - 1); // Observable is at the same location as the experiment m_simulations[i] = m_simulationParameters[i] * std::sin(2.0 * M_PI * x); } // Allocate memory for the covariance matrix // Exceptions will lead to memory leaks. lul m_covariance = (double *)malloc(sizeof(double) * (m_num_simulations + 1) * (m_num_simulations + 1)); if (m_covariance == NULL) { queso_error_msg("Could not allocate memory for covariance matrix"); } } template <class V, class M> Likelihood<V, M>::~Likelihood() { free(m_covariance); } template <class V, class M> double Likelihood<V, M>::lnValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { unsigned int total_dim = m_num_simulations + 1; // Plus 1 for one experiment // First, fill up the covariance matrix for (unsigned int i = 0; i < total_dim; i++) { double parameter1; // Deal with the single experiment if (i == 0) { // Difference in scenario variables is always zero. No need to handle it. // Deal with difference in parameters parameter1 = domainVector[0]; } else { // Subtract 1 because we have 1 experiment (observation) parameter1 = m_simulationParameters[i-1]; } for (unsigned int j = 0; j < total_dim; j++) { double parameter2; // Deal with the single experiment (observation) if (j == 0) { parameter2 = domainVector[0]; } else { // Subtract 1 because we have 1 experiment (observation) parameter2 = m_simulationParameters[j-1]; } double param_diff = parameter1 - parameter2; m_covariance[i*total_dim+j] = std::pow(m_rho, 4.0 * param_diff * param_diff); } } // We're letting MKL choose the workspace array at runtime // Assume unsigned int N converts to lapack_int int info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'U', total_dim, m_covariance, total_dim); std::cout << "LAPACKE_dpotrf return value is: " << info << std::endl; return 0; } template <class V, class M> double Likelihood<V, M>::actualValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return std::exp(this->lnValue(domainVector, domainDirection, gradVector, hessianMatrix, hessianEffect)); } template class Likelihood<QUESO::GslVector, QUESO::GslMatrix>; <commit_msg>Adding rest of likelihood implementation<commit_after>#include "likelihood.h" #include <queso/GslVector.h> #include <queso/GslMatrix.h> #include <queso/VectorSet.h> #include <mkl.h> #include <cmath> template <class V, class M> Likelihood<V, M>::Likelihood(const char * prefix, const QUESO::VectorSet<V, M> & domainSet) : QUESO::BaseScalarFunction<V, M>(prefix, domainSet), m_observationParameter(1.0), m_num_simulations(10), m_simulations(m_num_simulations), m_simulationParameters(m_num_simulations), m_rho(0.5) { // Generate observational data double x = 0.25; // Observation location m_observation = m_observationParameter * std::sin(2.0 * M_PI * x); // Generate `simulation data' for (unsigned int i = 0; i < m_num_simulations; i++) { // Evenly spaced parameters between 0 and 2 m_simulationParameters[i] = i * 2.0 / (m_num_simulations - 1); // Observable is at the same location as the experiment m_simulations[i] = m_simulationParameters[i] * std::sin(2.0 * M_PI * x); } // Allocate memory for the covariance matrix // Exceptions will lead to memory leaks. lul m_covariance = (double *)malloc(sizeof(double) * (m_num_simulations + 1) * (m_num_simulations + 1)); if (m_covariance == NULL) { queso_error_msg("Could not allocate memory for covariance matrix"); } } template <class V, class M> Likelihood<V, M>::~Likelihood() { free(m_covariance); } template <class V, class M> double Likelihood<V, M>::lnValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { unsigned int total_dim = m_num_simulations + 1; // Plus 1 for one experiment // First, fill up the covariance matrix for (unsigned int i = 0; i < total_dim; i++) { double parameter1; // Deal with the single experiment if (i == 0) { // Difference in scenario variables is always zero. No need to handle it. // Deal with difference in parameters parameter1 = domainVector[0]; } else { // Subtract 1 because we have 1 experiment (observation) parameter1 = m_simulationParameters[i-1]; } for (unsigned int j = 0; j < total_dim; j++) { double parameter2; // Deal with the single experiment (observation) if (j == 0) { parameter2 = domainVector[0]; } else { // Subtract 1 because we have 1 experiment (observation) parameter2 = m_simulationParameters[j-1]; } double param_diff = parameter1 - parameter2; m_covariance[i*total_dim+j] = std::pow(m_rho, 4.0 * param_diff * param_diff); } } int info; // We're letting MKL choose the workspace array at runtime // Assume unsigned int N converts to lapack_int info = LAPACKE_dpotrf(LAPACK_ROW_MAJOR, 'U', total_dim, m_covariance, total_dim); if (info == 0) { std::cout << "LAPACKE_dpotrf was successful" << std::endl; } else if (info < 0) { std::cout << "LAPACKE_dpotrf was unsuccessful." << " Parameter " << info << " had an illegal value." << std::endl; } else { // if (info > 0) { std::cout << "LAPACKE_dpotrf was unseccessful." << " The leading minor of order " << info << " is not pos. def." << " The Cholesky factorisation could not be completed." << std::endl; } // Compute the \infty-norm of m_covariance // All elements of m_covariance are nonnegative double norm = 0.0; for (unsigned int i = 0; i < total_dim; i++) { double tmp = 0.0; for (unsigned int j = 0; j < total_dim; j++) { tmp += m_covariance[i*total_dim+j]; } if (tmp > norm) { norm = tmp; } } // Estimate the condition number of m_covariance double cond; info = LAPACKE_dpocon(LAPACK_ROW_MAJOR, 'U', total_dim, m_covariance, total_dim, norm, &cond); if (info == 0) { std::cout << "Approximate reciprocal condition number of m_covariance is: " << cond << std::endl; } else { std::cout << "Condition number estimation failed." << " Parameter " << info << " had an illegal value." << std::endl; } // Now do y^T \Sigma^{-1} y // First solve \Sigma x = y for x double * y = (double *)malloc(sizeof(double) * total_dim); double * x = (double *)malloc(sizeof(double) * total_dim); y[0] = m_observation; x[0] = m_observation; for (unsigned int i = 0; i < m_num_simulations; i++) { y[i+1] = m_simulations[i]; x[i+1] = m_simulations[i]; } info = LAPACKE_dpotrs(LAPACK_ROW_MAJOR, 'U', total_dim, 1, m_covariance, total_dim, x, total_dim); if (info == 0) { std::cout << "LAPACKE_dpotrs successful" << std::endl; } else { std::cout << "LAPACKE_dpotrs unsuccessful. Parameter " << info << " had an illegal value" << std::endl; } // Second compute y^T x double llhd = cblas_ddot(total_dim, y, 1, x, 1); return -0.5 * llhd; } template <class V, class M> double Likelihood<V, M>::actualValue(const V & domainVector, const V * domainDirection, V * gradVector, M * hessianMatrix, V * hessianEffect) const { return std::exp(this->lnValue(domainVector, domainDirection, gradVector, hessianMatrix, hessianEffect)); } template class Likelihood<QUESO::GslVector, QUESO::GslMatrix>; <|endoftext|>
<commit_before><commit_msg>gui: display location with correct precision<commit_after><|endoftext|>
<commit_before>/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/platform.h> #include "../../PLN.h" #include "../Rule.h" #include "../Rules.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" namespace opencog { namespace pln { StrictImplicationBreakdownRule::StrictImplicationBreakdownRule(AtomSpaceWrapper *_asw) : Rule(_asw,false,true,"ModusPonensRule") { inputFilter.push_back(meta( new tree<Vertex>( mva((pHandle)IMPLICATION_LINK, mva((pHandle)ATOM), mva((pHandle)ATOM))) )); inputFilter.push_back(meta( new tree<Vertex>( mva((pHandle)ATOM)) )); } // Won't work since Rule::o2iMeta requires a target to have children // (and removing that restriction breaks other things). //meta StrictImplicationBreakdownRule::targetTemplate() const //{ // return(meta(new vtree(mva((pHandle)ATOM)))); //} Rule::setOfMPs StrictImplicationBreakdownRule::fullInputFilter() const { //meta outh(new vtree(mva((pHandle)ATOM))); MPs ret; Vertex myvar = CreateVar(asw); // It is necessary to use an FWVar rather than ATOM so that CCURule will match it. meta outh(new vtree(CreateVar(asw))); cprintf(4,"\n\nTo produce\n"); NMPrinter printer(NMP_HANDLE|NMP_TYPE_NAME); printer.print(outh->begin(), 4); ret.push_back(BBvtree(new BoundVTree(mva((pHandle)IMPLICATION_LINK, vtree(myvar),*outh)))); cprintf(4,"Need:\n"); ret.push_back(BBvtree(new BoundVTree(myvar))); printer.print(ret[0]->begin(), 4); printer.print(ret[1]->begin(), 4); cprintf(4,"-----\n"); return makeSingletonSet(ret); } Rule::setOfMPs StrictImplicationBreakdownRule::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { ///haxx:: (restricts internal implications // if (asw->isSubType(v2h(*outh->begin()), IMPLICATION_LINK)) // return Rule::setOfMPs(); MPs ret; Vertex myvar = CreateVar(asw); cprintf(4,"\n\nTo produce\n"); NMPrinter printer(NMP_HANDLE|NMP_TYPE_NAME); printer.print(outh->begin(), 4); ret.push_back(BBvtree(new BoundVTree(mva((pHandle)IMPLICATION_LINK, vtree(myvar),*outh)))); cprintf(4,"Need:\n"); ret.push_back(BBvtree(new BoundVTree(myvar))); printer.print(ret[0]->begin(), 4); printer.print(ret[1]->begin(), 4); cprintf(4,"-----\n"); overrideInputFilter = true; return makeSingletonSet(ret); } BoundVertex StrictImplicationBreakdownRule::compute(const std::vector<Vertex>& premiseArray, pHandle CX, bool fresh) const { assert(validate(premiseArray)); //printTree(premiseArray[0],0,1); cprintf(3,"StrictImplicationBreakdownRule::compute:"); NMPrinter printer(NMP_ALL); for (uint i=0;i<premiseArray.size();i++) printer.print(_v2h(premiseArray[i]), 3); //vtree vt1(make_vtree(_v2h(premiseArray[0]))), // vt2(make_vtree(_v2h(premiseArray[1]))); /** haxx:: \todo Temporarily disabled! This check does not hold if one of the args has been executed but the other one has not. Execution here means that Eval(!now) becomes Eval(35353). ! is a hacky shorthand for grounded predicates for now. The real solution will be tointroduce an equality check which considers the unexecuted and executed forms equal. */ #if 0 if (make_vtree(asw->getOutgoing(v2h(premiseArray[0]),0)) != make_vtree(v2h(premiseArray[1]))) { cprintf(0,"StrictImplicationBreakdownRule args fail:\n"); #if 0 printTree(v2h(premiseArray[0]),0,0); printTree(asw->getOutgoing(v2h(premiseArray[0]),0),0,0); printTree(v2h(premiseArray[1]),0,0); // rawPrint(premiseArray[0], premiseArray[0].begin(), 0); rawPrint(vt1, vt1.begin(), 0); rawPrint(vt2, vt2.begin(), 0); #else printer.print(v2h(premiseArray[0]), -10); printer.print(asw->getOutgoing(v2h(premiseArray[0]),0), -10); printer.print(v2h(premiseArray[1]), -10); // printer.print(premiseArray[0].begin()); printer.print(vt1.begin(), -10); printer.print(vt2.begin(), -10); #endif assert(0); } #endif pHandle implication = _v2h(premiseArray[0]); pHandle antecedant = _v2h(premiseArray[1]); pHandle conclusion = asw->getOutgoing(implication, 1); TruthValue* tvs[] = { (TruthValue*) &(asw->getTV(implication)), (TruthValue*) &(asw->getTV(antecedant)), (TruthValue*) &(asw->getTV(conclusion)) }; TruthValue* retTV = ImplicationBreakdownFormula().compute(tvs, 3); // update the TV of the conclusion. // Note that ret is different than conclusion, that is because a dummy // context is added and this is translated into a different resulting // pHandle (but of course they both correspond to the same atom). // See AtomSpaceWrapper.h for more info pHandle ret = asw->updateTV(conclusion, *retTV, fresh); delete retTV; printer.print(ret, 3); return Vertex(ret); } }} // namespace opencog { namespace pln { <commit_msg>PLN inference control: Disable support for nested implications, because it isn't used and slows things down.<commit_after>/* * Copyright (C) 2002-2007 Novamente LLC * Copyright (C) 2008 by Singularity Institute for Artificial Intelligence * All Rights Reserved * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/util/platform.h> #include "../../PLN.h" #include "../Rule.h" #include "../Rules.h" #include "../../AtomSpaceWrapper.h" #include "../../PLNatom.h" #include "../../BackInferenceTreeNode.h" namespace opencog { namespace pln { StrictImplicationBreakdownRule::StrictImplicationBreakdownRule(AtomSpaceWrapper *_asw) : Rule(_asw,false,true,"ModusPonensRule") { inputFilter.push_back(meta( new tree<Vertex>( mva((pHandle)IMPLICATION_LINK, mva((pHandle)ATOM), mva((pHandle)ATOM))) )); inputFilter.push_back(meta( new tree<Vertex>( mva((pHandle)ATOM)) )); } // Won't work since Rule::o2iMeta requires a target to have children // (and removing that restriction breaks other things). //meta StrictImplicationBreakdownRule::targetTemplate() const //{ // return(meta(new vtree(mva((pHandle)ATOM)))); //} Rule::setOfMPs StrictImplicationBreakdownRule::fullInputFilter() const { //meta outh(new vtree(mva((pHandle)ATOM))); MPs ret; Vertex myvar = CreateVar(asw); // It is necessary to use an FWVar rather than ATOM so that CCURule will match it. meta outh(new vtree(CreateVar(asw))); cprintf(4,"\n\nTo produce\n"); NMPrinter printer(NMP_HANDLE|NMP_TYPE_NAME); printer.print(outh->begin(), 4); ret.push_back(BBvtree(new BoundVTree(mva((pHandle)IMPLICATION_LINK, vtree(myvar),*outh)))); cprintf(4,"Need:\n"); ret.push_back(BBvtree(new BoundVTree(myvar))); printer.print(ret[0]->begin(), 4); printer.print(ret[1]->begin(), 4); cprintf(4,"-----\n"); return makeSingletonSet(ret); } Rule::setOfMPs StrictImplicationBreakdownRule::o2iMetaExtra(meta outh, bool& overrideInputFilter) const { ///haxx:: (restricts internal implications // - Leave it on for now, because it is not necessary (currently) and it makes // everything faster. if (asw->isSubType(_v2h(*outh->begin()), IMPLICATION_LINK)) return Rule::setOfMPs(); MPs ret; Vertex myvar = CreateVar(asw); cprintf(4,"\n\nTo produce\n"); NMPrinter printer(NMP_HANDLE|NMP_TYPE_NAME); printer.print(outh->begin(), 4); ret.push_back(BBvtree(new BoundVTree(mva((pHandle)IMPLICATION_LINK, vtree(myvar),*outh)))); cprintf(4,"Need:\n"); ret.push_back(BBvtree(new BoundVTree(myvar))); printer.print(ret[0]->begin(), 4); printer.print(ret[1]->begin(), 4); cprintf(4,"-----\n"); overrideInputFilter = true; return makeSingletonSet(ret); } BoundVertex StrictImplicationBreakdownRule::compute(const std::vector<Vertex>& premiseArray, pHandle CX, bool fresh) const { assert(validate(premiseArray)); //printTree(premiseArray[0],0,1); cprintf(3,"StrictImplicationBreakdownRule::compute:"); NMPrinter printer(NMP_ALL); for (uint i=0;i<premiseArray.size();i++) printer.print(_v2h(premiseArray[i]), 3); //vtree vt1(make_vtree(_v2h(premiseArray[0]))), // vt2(make_vtree(_v2h(premiseArray[1]))); /** haxx:: \todo Temporarily disabled! This check does not hold if one of the args has been executed but the other one has not. Execution here means that Eval(!now) becomes Eval(35353). ! is a hacky shorthand for grounded predicates for now. The real solution will be tointroduce an equality check which considers the unexecuted and executed forms equal. */ #if 0 if (make_vtree(asw->getOutgoing(v2h(premiseArray[0]),0)) != make_vtree(v2h(premiseArray[1]))) { cprintf(0,"StrictImplicationBreakdownRule args fail:\n"); #if 0 printTree(v2h(premiseArray[0]),0,0); printTree(asw->getOutgoing(v2h(premiseArray[0]),0),0,0); printTree(v2h(premiseArray[1]),0,0); // rawPrint(premiseArray[0], premiseArray[0].begin(), 0); rawPrint(vt1, vt1.begin(), 0); rawPrint(vt2, vt2.begin(), 0); #else printer.print(v2h(premiseArray[0]), -10); printer.print(asw->getOutgoing(v2h(premiseArray[0]),0), -10); printer.print(v2h(premiseArray[1]), -10); // printer.print(premiseArray[0].begin()); printer.print(vt1.begin(), -10); printer.print(vt2.begin(), -10); #endif assert(0); } #endif pHandle implication = _v2h(premiseArray[0]); pHandle antecedant = _v2h(premiseArray[1]); pHandle conclusion = asw->getOutgoing(implication, 1); TruthValue* tvs[] = { (TruthValue*) &(asw->getTV(implication)), (TruthValue*) &(asw->getTV(antecedant)), (TruthValue*) &(asw->getTV(conclusion)) }; TruthValue* retTV = ImplicationBreakdownFormula().compute(tvs, 3); // update the TV of the conclusion. // Note that ret is different than conclusion, that is because a dummy // context is added and this is translated into a different resulting // pHandle (but of course they both correspond to the same atom). // See AtomSpaceWrapper.h for more info pHandle ret = asw->updateTV(conclusion, *retTV, fresh); delete retTV; printer.print(ret, 3); return Vertex(ret); } }} // namespace opencog { namespace pln { <|endoftext|>
<commit_before>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrBackendSurface.h" #include "GrClip.h" #include "GrContext.h" #include "GrContextPriv.h" #include "GrRenderTargetContext.h" #include "GrTexture.h" #include "GrTextureAdjuster.h" #include "SkBitmapCache.h" #include "SkImage_Gpu.h" #include "SkImage_GpuBase.h" #include "SkReadPixelsRec.h" SkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID, SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs) : INHERITED(width, height, uniqueID) , fContext(std::move(context)) , fAlphaType(at) , fBudgeted(budgeted) , fColorSpace(std::move(cs)) {} SkImage_GpuBase::~SkImage_GpuBase() {} ////////////////////////////////////////////////////////////////////////////////////////////////// bool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex, GrPixelConfig* config, SkColorType ct, SkAlphaType at, sk_sp<SkColorSpace> cs) { if (!tex.isValid()) { return false; } // TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to // create a fake image info here. SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs); if (!SkImageInfoIsValid(info)) { return false; } return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config); } ////////////////////////////////////////////////////////////////////////////////////////////////// bool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const { if (!fContext->contextPriv().resourceProvider()) { // DDL TODO: buffer up the readback so it occurs when the DDL is drawn? return false; } // The SkColorSpace parameter "dstColorSpace" is really just a hint about how/where the bitmap // will be used. The client doesn't expect that we convert to that color space, it's intended // for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly // into that color space (to save the client some effort in whatever they're about to do), but // that would make our use of the bitmap cache incorrect (or much less efficient, assuming we // rolled the dstColorSpace into the key). const auto desc = SkBitmapCacheDesc::Make(this); if (SkBitmapCache::Find(desc, dst)) { SkASSERT(dst->isImmutable()); SkASSERT(dst->getPixels()); return true; } SkBitmapCache::RecPtr rec = nullptr; SkPixmap pmap; if (kAllow_CachingHint == chint) { rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap); if (!rec) { return false; } } else { if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) { return false; } } sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext( this->asTextureProxyRef(), fColorSpace); if (!sContext) { return false; } if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) { return false; } if (rec) { SkBitmapCache::Add(std::move(rec), dst); this->notifyAddedToRasterCache(); } return true; } sk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const { sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef(); GrSurfaceDesc desc; desc.fWidth = subset.width(); desc.fHeight = subset.height(); desc.fConfig = proxy->config(); sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext( desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted)); if (!sContext) { return nullptr; } if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) { return nullptr; } // MDB: this call is okay bc we know 'sContext' was kExact return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID, fAlphaType, sContext->asTextureProxyRef(), fColorSpace, fBudgeted); } static void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) { switch (info.colorType()) { case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: break; default: return; // nothing to do } // SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian, // and in either case, the alpha-byte is always in the same place, so we can safely call // SkPreMultiplyColor() // SkColor* row = (SkColor*)pixels; for (int y = 0; y < info.height(); ++y) { for (int x = 0; x < info.width(); ++x) { row[x] = SkPreMultiplyColor(row[x]); } row = (SkColor*)((char*)(row)+rowBytes); } } bool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB, int srcX, int srcY, CachingHint) const { if (!fContext->contextPriv().resourceProvider()) { // DDL TODO: buffer up the readback so it occurs when the DDL is drawn? return false; } if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) { return false; } SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY); if (!rec.trim(this->width(), this->height())) { return false; } // TODO: this seems to duplicate code in GrTextureContext::onReadPixels and // GrRenderTargetContext::onReadPixels uint32_t flags = 0; if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) { // let the GPU perform this transformation for us flags = GrContextPriv::kUnpremul_PixelOpsFlag; } sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext( this->asTextureProxyRef(), fColorSpace); if (!sContext) { return false; } if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) { return false; } // do we have to manually fix-up the alpha channel? // src dst // unpremul premul fix manually // premul unpremul done by kUnpremul_PixelOpsFlag // all other combos need to change. // // Should this be handled by Ganesh? todo:? // if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) { apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes); } return true; } sk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context, const GrSamplerState& params, SkColorSpace* dstColorSpace, sk_sp<SkColorSpace>* texColorSpace, SkScalar scaleAdjust[2]) const { if (context->uniqueID() != fContext->uniqueID()) { SkASSERT(0); return nullptr; } GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType, this->uniqueID(), fColorSpace.get()); return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust); } GrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO, GrSurfaceOrigin* origin) const { sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef(); SkASSERT(proxy); if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) { // This image was created with a DDL context and cannot be instantiated. return GrBackendTexture(); } if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) { return GrBackendTexture(); // invalid } GrTexture* texture = proxy->peekTexture(); if (texture) { if (flushPendingGrContextIO) { fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get()); } if (origin) { *origin = proxy->origin(); } return texture->getBackendTexture(); } return GrBackendTexture(); // invalid } GrTexture* SkImage_GpuBase::onGetTexture() const { GrTextureProxy* proxy = this->peekProxy(); if (!proxy) { return nullptr; } sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef(); if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) { // This image was created with a DDL context and cannot be instantiated. return nullptr; } if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) { return nullptr; } return proxy->peekTexture(); } sk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const { auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType, target.get(), fAlphaType); if (!xform) { return sk_ref_sp(const_cast<SkImage_GpuBase*>(this)); } sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef(); sk_sp<GrRenderTargetContext> renderTargetContext( fContext->contextPriv().makeDeferredRenderTargetContextWithFallback( SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr)); if (!renderTargetContext) { return nullptr; } GrPaint paint; paint.setPorterDuffXPFactory(SkBlendMode::kSrc); paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I()); paint.addColorFragmentProcessor(std::move(xform)); const SkRect rect = SkRect::MakeIWH(this->width(), this->height()); renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect); if (!renderTargetContext->asTextureProxy()) { return nullptr; } // MDB: this call is okay bc we know 'renderTargetContext' was exact return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID, fAlphaType, renderTargetContext->asTextureProxyRef(), std::move(target), fBudgeted); } bool SkImage_GpuBase::onIsValid(GrContext* context) const { // The base class has already checked that context isn't abandoned (if it's not nullptr) if (fContext->abandoned()) { return false; } if (context && context != fContext.get()) { return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// sk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider, GrPixelConfig config) { // Releases the promise helper if there are no outstanding hard refs. This means that we // don't have any ReleaseProcs waiting to be called so we will need to do a fulfill. if (fReleaseHelper && fReleaseHelper->weak_expired()) { this->resetReleaseHelper(); } sk_sp<GrTexture> tex; if (!fReleaseHelper) { fFulfillProc(fContext, &fBackendTex); fBackendTex.fConfig = config; if (!fBackendTex.isValid()) { // Even though the GrBackendTexture is not valid, we must call the release // proc to keep our contract of always calling Fulfill and Release in pairs. fReleaseProc(fContext); return sk_sp<GrTexture>(); } tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership); if (!tex) { // Even though the GrBackendTexture is not valid, we must call the release // proc to keep our contract of always calling Fulfill and Release in pairs. fReleaseProc(fContext); return sk_sp<GrTexture>(); } fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper); // Take a weak ref fReleaseHelper->weak_ref(); } else { SkASSERT(fBackendTex.isValid()); tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership); if (!tex) { // We weren't able to make a texture here, but since we are in this branch // of the calls (promiseHelper.fReleaseHelper is valid) there is already a // texture out there which will call the release proc so we don't need to // call it here. return sk_sp<GrTexture>(); } SkAssertResult(fReleaseHelper->try_ref()); } SkASSERT(tex); // Pass the hard ref off to the texture tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper)); return tex; } <commit_msg>Revert "Fix bug with makeColorSpace of GPU images with non-renderable configs"<commit_after>/* * Copyright 2018 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "GrBackendSurface.h" #include "GrClip.h" #include "GrContext.h" #include "GrContextPriv.h" #include "GrRenderTargetContext.h" #include "GrTexture.h" #include "GrTextureAdjuster.h" #include "SkBitmapCache.h" #include "SkImage_Gpu.h" #include "SkImage_GpuBase.h" #include "SkReadPixelsRec.h" SkImage_GpuBase::SkImage_GpuBase(sk_sp<GrContext> context, int width, int height, uint32_t uniqueID, SkAlphaType at, SkBudgeted budgeted, sk_sp<SkColorSpace> cs) : INHERITED(width, height, uniqueID) , fContext(std::move(context)) , fAlphaType(at) , fBudgeted(budgeted) , fColorSpace(std::move(cs)) {} SkImage_GpuBase::~SkImage_GpuBase() {} ////////////////////////////////////////////////////////////////////////////////////////////////// bool SkImage_GpuBase::ValidateBackendTexture(GrContext* ctx, const GrBackendTexture& tex, GrPixelConfig* config, SkColorType ct, SkAlphaType at, sk_sp<SkColorSpace> cs) { if (!tex.isValid()) { return false; } // TODO: Create a SkImageColorInfo struct for color, alpha, and color space so we don't need to // create a fake image info here. SkImageInfo info = SkImageInfo::Make(1, 1, ct, at, cs); if (!SkImageInfoIsValid(info)) { return false; } return ctx->contextPriv().caps()->validateBackendTexture(tex, ct, config); } ////////////////////////////////////////////////////////////////////////////////////////////////// bool SkImage_GpuBase::getROPixels(SkBitmap* dst, SkColorSpace*, CachingHint chint) const { if (!fContext->contextPriv().resourceProvider()) { // DDL TODO: buffer up the readback so it occurs when the DDL is drawn? return false; } // The SkColorSpace parameter "dstColorSpace" is really just a hint about how/where the bitmap // will be used. The client doesn't expect that we convert to that color space, it's intended // for codec-backed images, to drive our decoding heuristic. In theory we *could* read directly // into that color space (to save the client some effort in whatever they're about to do), but // that would make our use of the bitmap cache incorrect (or much less efficient, assuming we // rolled the dstColorSpace into the key). const auto desc = SkBitmapCacheDesc::Make(this); if (SkBitmapCache::Find(desc, dst)) { SkASSERT(dst->isImmutable()); SkASSERT(dst->getPixels()); return true; } SkBitmapCache::RecPtr rec = nullptr; SkPixmap pmap; if (kAllow_CachingHint == chint) { rec = SkBitmapCache::Alloc(desc, this->onImageInfo(), &pmap); if (!rec) { return false; } } else { if (!dst->tryAllocPixels(this->onImageInfo()) || !dst->peekPixels(&pmap)) { return false; } } sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext( this->asTextureProxyRef(), fColorSpace); if (!sContext) { return false; } if (!sContext->readPixels(pmap.info(), pmap.writable_addr(), pmap.rowBytes(), 0, 0)) { return false; } if (rec) { SkBitmapCache::Add(std::move(rec), dst); this->notifyAddedToRasterCache(); } return true; } sk_sp<SkImage> SkImage_GpuBase::onMakeSubset(const SkIRect& subset) const { sk_sp<GrSurfaceProxy> proxy = this->asTextureProxyRef(); GrSurfaceDesc desc; desc.fWidth = subset.width(); desc.fHeight = subset.height(); desc.fConfig = proxy->config(); sk_sp<GrSurfaceContext> sContext(fContext->contextPriv().makeDeferredSurfaceContext( desc, proxy->origin(), GrMipMapped::kNo, SkBackingFit::kExact, fBudgeted)); if (!sContext) { return nullptr; } if (!sContext->copy(proxy.get(), subset, SkIPoint::Make(0, 0))) { return nullptr; } // MDB: this call is okay bc we know 'sContext' was kExact return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID, fAlphaType, sContext->asTextureProxyRef(), fColorSpace, fBudgeted); } static void apply_premul(const SkImageInfo& info, void* pixels, size_t rowBytes) { switch (info.colorType()) { case kRGBA_8888_SkColorType: case kBGRA_8888_SkColorType: break; default: return; // nothing to do } // SkColor is not necesarily RGBA or BGRA, but it is one of them on little-endian, // and in either case, the alpha-byte is always in the same place, so we can safely call // SkPreMultiplyColor() // SkColor* row = (SkColor*)pixels; for (int y = 0; y < info.height(); ++y) { for (int x = 0; x < info.width(); ++x) { row[x] = SkPreMultiplyColor(row[x]); } row = (SkColor*)((char*)(row)+rowBytes); } } bool SkImage_GpuBase::onReadPixels(const SkImageInfo& dstInfo, void* dstPixels, size_t dstRB, int srcX, int srcY, CachingHint) const { if (!fContext->contextPriv().resourceProvider()) { // DDL TODO: buffer up the readback so it occurs when the DDL is drawn? return false; } if (!SkImageInfoValidConversion(dstInfo, this->onImageInfo())) { return false; } SkReadPixelsRec rec(dstInfo, dstPixels, dstRB, srcX, srcY); if (!rec.trim(this->width(), this->height())) { return false; } // TODO: this seems to duplicate code in GrTextureContext::onReadPixels and // GrRenderTargetContext::onReadPixels uint32_t flags = 0; if (kUnpremul_SkAlphaType == rec.fInfo.alphaType() && kPremul_SkAlphaType == fAlphaType) { // let the GPU perform this transformation for us flags = GrContextPriv::kUnpremul_PixelOpsFlag; } sk_sp<GrSurfaceContext> sContext = fContext->contextPriv().makeWrappedSurfaceContext( this->asTextureProxyRef(), fColorSpace); if (!sContext) { return false; } if (!sContext->readPixels(rec.fInfo, rec.fPixels, rec.fRowBytes, rec.fX, rec.fY, flags)) { return false; } // do we have to manually fix-up the alpha channel? // src dst // unpremul premul fix manually // premul unpremul done by kUnpremul_PixelOpsFlag // all other combos need to change. // // Should this be handled by Ganesh? todo:? // if (kPremul_SkAlphaType == rec.fInfo.alphaType() && kUnpremul_SkAlphaType == fAlphaType) { apply_premul(rec.fInfo, rec.fPixels, rec.fRowBytes); } return true; } sk_sp<GrTextureProxy> SkImage_GpuBase::asTextureProxyRef(GrContext* context, const GrSamplerState& params, SkColorSpace* dstColorSpace, sk_sp<SkColorSpace>* texColorSpace, SkScalar scaleAdjust[2]) const { if (context->uniqueID() != fContext->uniqueID()) { SkASSERT(0); return nullptr; } GrTextureAdjuster adjuster(fContext.get(), this->asTextureProxyRef(), fAlphaType, this->uniqueID(), fColorSpace.get()); return adjuster.refTextureProxyForParams(params, dstColorSpace, texColorSpace, scaleAdjust); } GrBackendTexture SkImage_GpuBase::onGetBackendTexture(bool flushPendingGrContextIO, GrSurfaceOrigin* origin) const { sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef(); SkASSERT(proxy); if (!fContext->contextPriv().resourceProvider() && !proxy->isInstantiated()) { // This image was created with a DDL context and cannot be instantiated. return GrBackendTexture(); } if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) { return GrBackendTexture(); // invalid } GrTexture* texture = proxy->peekTexture(); if (texture) { if (flushPendingGrContextIO) { fContext->contextPriv().prepareSurfaceForExternalIO(proxy.get()); } if (origin) { *origin = proxy->origin(); } return texture->getBackendTexture(); } return GrBackendTexture(); // invalid } GrTexture* SkImage_GpuBase::onGetTexture() const { GrTextureProxy* proxy = this->peekProxy(); if (!proxy) { return nullptr; } sk_sp<GrTextureProxy> proxyRef = this->asTextureProxyRef(); if (!fContext->contextPriv().resourceProvider() && !proxyRef->isInstantiated()) { // This image was created with a DDL context and cannot be instantiated. return nullptr; } if (!proxy->instantiate(fContext->contextPriv().resourceProvider())) { return nullptr; } return proxy->peekTexture(); } sk_sp<SkImage> SkImage_GpuBase::onMakeColorSpace(sk_sp<SkColorSpace> target) const { auto xform = GrColorSpaceXformEffect::Make(fColorSpace.get(), fAlphaType, target.get(), fAlphaType); if (!xform) { return sk_ref_sp(const_cast<SkImage_GpuBase*>(this)); } sk_sp<GrTextureProxy> proxy = this->asTextureProxyRef(); sk_sp<GrRenderTargetContext> renderTargetContext( fContext->contextPriv().makeDeferredRenderTargetContext( SkBackingFit::kExact, this->width(), this->height(), proxy->config(), nullptr)); if (!renderTargetContext) { return nullptr; } GrPaint paint; paint.setPorterDuffXPFactory(SkBlendMode::kSrc); paint.addColorTextureProcessor(std::move(proxy), SkMatrix::I()); paint.addColorFragmentProcessor(std::move(xform)); const SkRect rect = SkRect::MakeIWH(this->width(), this->height()); renderTargetContext->drawRect(GrNoClip(), std::move(paint), GrAA::kNo, SkMatrix::I(), rect); if (!renderTargetContext->asTextureProxy()) { return nullptr; } // MDB: this call is okay bc we know 'renderTargetContext' was exact return sk_make_sp<SkImage_Gpu>(fContext, kNeedNewImageUniqueID, fAlphaType, renderTargetContext->asTextureProxyRef(), std::move(target), fBudgeted); } bool SkImage_GpuBase::onIsValid(GrContext* context) const { // The base class has already checked that context isn't abandoned (if it's not nullptr) if (fContext->abandoned()) { return false; } if (context && context != fContext.get()) { return false; } return true; } ///////////////////////////////////////////////////////////////////////////////////////////////// sk_sp<GrTexture> SkPromiseImageHelper::getTexture(GrResourceProvider* resourceProvider, GrPixelConfig config) { // Releases the promise helper if there are no outstanding hard refs. This means that we // don't have any ReleaseProcs waiting to be called so we will need to do a fulfill. if (fReleaseHelper && fReleaseHelper->weak_expired()) { this->resetReleaseHelper(); } sk_sp<GrTexture> tex; if (!fReleaseHelper) { fFulfillProc(fContext, &fBackendTex); fBackendTex.fConfig = config; if (!fBackendTex.isValid()) { // Even though the GrBackendTexture is not valid, we must call the release // proc to keep our contract of always calling Fulfill and Release in pairs. fReleaseProc(fContext); return sk_sp<GrTexture>(); } tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership); if (!tex) { // Even though the GrBackendTexture is not valid, we must call the release // proc to keep our contract of always calling Fulfill and Release in pairs. fReleaseProc(fContext); return sk_sp<GrTexture>(); } fReleaseHelper = new SkPromiseReleaseProcHelper(fReleaseProc, fContext, fDoneHelper); // Take a weak ref fReleaseHelper->weak_ref(); } else { SkASSERT(fBackendTex.isValid()); tex = resourceProvider->wrapBackendTexture(fBackendTex, kBorrow_GrWrapOwnership); if (!tex) { // We weren't able to make a texture here, but since we are in this branch // of the calls (promiseHelper.fReleaseHelper is valid) there is already a // texture out there which will call the release proc so we don't need to // call it here. return sk_sp<GrTexture>(); } SkAssertResult(fReleaseHelper->try_ref()); } SkASSERT(tex); // Pass the hard ref off to the texture tex->setRelease(sk_sp<GrReleaseProcHelper>(fReleaseHelper)); return tex; } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------// //! //! \file MonteCarlo_CollisionHandler.cpp //! \author Alex Robinson //! \brief Collision handler class definition. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <stdexcept> // FRENSIE Includes #include "MonteCarlo_CollisionHandler.hpp" #include "Utility_ExceptionTestMacros.hpp" #include "Utility_ContractException.hpp" namespace MonteCarlo{ // Initialize the static member data CollisionHandler::CellIdNeutronMaterialMap CollisionHandler::master_neutron_map; CollisionHandler::CellIdPhotonMaterialMap CollisionHandler::master_photon_map; // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<NeutronMaterial>& material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointer is valid testPrecondition( !material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); for( unsigned i = 0u; i < cells_containing_material.size(); ++i ) { TEST_FOR_EXCEPTION( CollisionHandler::master_neutron_map.find(cells_containing_material[i])!= CollisionHandler::master_neutron_map.end(), std::logic_error, "Error: cell " << cells_containing_material[i] << " already has a " "material assigned!" ); CollisionHandler::master_neutron_map[cells_containing_material[i]] = material; } } // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<PhotonMaterial>& material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointer is valid testPrecondition( !material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); for( unsigned i = 0u; i < cells_containing_material.size(); ++i ) { TEST_FOR_EXCEPTION( CollisionHandler::master_photon_map.find(cells_containing_material[i]) != CollisionHandler::master_photon_map.end(), std::logic_error, "Error:: cell " << cells_containing_material[i] << " already has a " "material assigned!" ); CollisionHandler::master_photon_map[cells_containing_material[i]] = material; } } // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<NeutronMaterial>& neutron_material, const Teuchos::RCP<PhotonMaterial>& photon_material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointers are valid testPrecondition( !neutron_material.is_null() ); testPrecondition( !photon_material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); CollisionHandler::addMaterial( neutron_material, cells_containing_material ); CollisionHandler::addMaterial( photon_material, cells_containing_material ); } // Check if a cell is void bool CollisionHandler::isCellVoid( const Geometry::ModuleTraits::InternalCellHandle cell, const ParticleType particle_type ) { switch( particle_type ) { case NEUTRON: if( CollisionHandler::master_neutron_map.find( cell ) == CollisionHandler::master_neutron_map.end() ) return true; else return false; case PHOTON: if( CollisionHandler::master_photon_map.find( cell ) == CollisionHandler::master_photon_map.end() ) return true; else return false; default: return true; } } // Get the neutron material contained in a cell const Teuchos::RCP<NeutronMaterial>& CollisionHandler::getCellNeutronMaterial( const Geometry::ModuleTraits::InternalCellHandle cell ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( cell, NEUTRON ) ); return CollisionHandler::master_neutron_map.find( cell )->second; } // Get the photon material contained in a cell const Teuchos::RCP<PhotonMaterial>& CollisionHandler::getCellPhotonMaterial( const Geometry::ModuleTraits::InternalCellHandle cell ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( cell, PHOTON ) ); return CollisionHandler::master_photon_map.find( cell )->second; } // Get the total macroscopic cross section of a material double CollisionHandler::getMacroscopicTotalCrossSection( const NeutronState& particle ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), NEUTRON ) ); Teuchos::RCP<NeutronMaterial>& material = CollisionHandler::master_neutron_map.find( particle.getCell() )->second; } // Get the total macroscopic cross section of a material double CollisionHandler::getMacroscopicTotalCrossSection( const PhotonState& particle ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), PHOTON ) ); Teuchos::RCP<PhotonMaterial>& material = CollisionHandler::master_photon_map.find( particle.getCell() )->second; return material->getMacroscopicTotalCrossSection( particle.getEnergy() ); } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const NeutronState& particle, const NuclearReactionType reaction ) { CellIdNeutronMaterialMap::const_iterator it = CollisionHandler::master_neutron_map.find( particle.getCell() ); if( it != CollisionHandler::master_neutron_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const PhotonState& particle, const PhotoatomicReactionType reaction ) { CellIdPhotonMaterialMap::const_iterator it = CollisionHandler::master_photon_map.find( particle.getCell() ); if( it != CollisionHandler::master_photon_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const PhotonState& particle, const PhotonuclearReactionType reaction ) { CellIdPhotonMaterialMap::const_iterator it = CollisionHandler::master_photon_map.find( particle.getCell() ); if( it != CollisionHandler::master_photon_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Collide with the material in a cell void CollisionHandler::collideWithCellMaterial( NeutronState& particle, ParticleBank& bank, const bool analogue ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), NEUTRON ) ); const Teuchos::RCP<NeutronMaterial>& material = CollisionHandler::master_neutron_map.find( particle.getCell() )->second; if( analogue ) material->collideAnalogue( particle, bank ); else material->collideSurvivalBias( particle, bank ); } // Collide with the material in a cell void CollisionHandler::collideWithCellMaterial( PhotonState& particle, ParticleBank& bank, const bool analogue ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), PHOTON ) ); const Teuchos::RCP<PhotonMaterial>& material = CollisionHandler::master_photon_map.find( particle.getCell() )->second; if( analogue ) material->collideAnalogue( particle, bank ); else material->collideSurvivalBias( particle, bank ); } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_CollisionHandler.cpp //---------------------------------------------------------------------------// <commit_msg>Fixed broken collision handler unit tests.<commit_after>//---------------------------------------------------------------------------// //! //! \file MonteCarlo_CollisionHandler.cpp //! \author Alex Robinson //! \brief Collision handler class definition. //! //---------------------------------------------------------------------------// // Std Lib Includes #include <stdexcept> // FRENSIE Includes #include "MonteCarlo_CollisionHandler.hpp" #include "Utility_ExceptionTestMacros.hpp" #include "Utility_ContractException.hpp" namespace MonteCarlo{ // Initialize the static member data CollisionHandler::CellIdNeutronMaterialMap CollisionHandler::master_neutron_map; CollisionHandler::CellIdPhotonMaterialMap CollisionHandler::master_photon_map; // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<NeutronMaterial>& material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointer is valid testPrecondition( !material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); for( unsigned i = 0u; i < cells_containing_material.size(); ++i ) { TEST_FOR_EXCEPTION( CollisionHandler::master_neutron_map.find(cells_containing_material[i])!= CollisionHandler::master_neutron_map.end(), std::logic_error, "Error: cell " << cells_containing_material[i] << " already has a " "material assigned!" ); CollisionHandler::master_neutron_map[cells_containing_material[i]] = material; } } // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<PhotonMaterial>& material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointer is valid testPrecondition( !material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); for( unsigned i = 0u; i < cells_containing_material.size(); ++i ) { TEST_FOR_EXCEPTION( CollisionHandler::master_photon_map.find(cells_containing_material[i]) != CollisionHandler::master_photon_map.end(), std::logic_error, "Error:: cell " << cells_containing_material[i] << " already has a " "material assigned!" ); CollisionHandler::master_photon_map[cells_containing_material[i]] = material; } } // Add a material to the collision handler void CollisionHandler::addMaterial( const Teuchos::RCP<NeutronMaterial>& neutron_material, const Teuchos::RCP<PhotonMaterial>& photon_material, const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells_containing_material ) { // Make sure the material pointers are valid testPrecondition( !neutron_material.is_null() ); testPrecondition( !photon_material.is_null() ); // Make sure the cells are valid testPrecondition( cells_containing_material.size() > 0 ); CollisionHandler::addMaterial( neutron_material, cells_containing_material ); CollisionHandler::addMaterial( photon_material, cells_containing_material ); } // Check if a cell is void bool CollisionHandler::isCellVoid( const Geometry::ModuleTraits::InternalCellHandle cell, const ParticleType particle_type ) { switch( particle_type ) { case NEUTRON: if( CollisionHandler::master_neutron_map.find( cell ) == CollisionHandler::master_neutron_map.end() ) return true; else return false; case PHOTON: if( CollisionHandler::master_photon_map.find( cell ) == CollisionHandler::master_photon_map.end() ) return true; else return false; default: return true; } } // Get the neutron material contained in a cell const Teuchos::RCP<NeutronMaterial>& CollisionHandler::getCellNeutronMaterial( const Geometry::ModuleTraits::InternalCellHandle cell ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( cell, NEUTRON ) ); return CollisionHandler::master_neutron_map.find( cell )->second; } // Get the photon material contained in a cell const Teuchos::RCP<PhotonMaterial>& CollisionHandler::getCellPhotonMaterial( const Geometry::ModuleTraits::InternalCellHandle cell ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( cell, PHOTON ) ); return CollisionHandler::master_photon_map.find( cell )->second; } // Get the total macroscopic cross section of a material double CollisionHandler::getMacroscopicTotalCrossSection( const NeutronState& particle ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), NEUTRON ) ); Teuchos::RCP<NeutronMaterial>& material = CollisionHandler::master_neutron_map.find( particle.getCell() )->second; return material->getMacroscopicTotalCrossSection( particle.getEnergy() ); } // Get the total macroscopic cross section of a material double CollisionHandler::getMacroscopicTotalCrossSection( const PhotonState& particle ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), PHOTON ) ); Teuchos::RCP<PhotonMaterial>& material = CollisionHandler::master_photon_map.find( particle.getCell() )->second; return material->getMacroscopicTotalCrossSection( particle.getEnergy() ); } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const NeutronState& particle, const NuclearReactionType reaction ) { CellIdNeutronMaterialMap::const_iterator it = CollisionHandler::master_neutron_map.find( particle.getCell() ); if( it != CollisionHandler::master_neutron_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const PhotonState& particle, const PhotoatomicReactionType reaction ) { CellIdPhotonMaterialMap::const_iterator it = CollisionHandler::master_photon_map.find( particle.getCell() ); if( it != CollisionHandler::master_photon_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Get the macroscopic cross section for a specific reaction double CollisionHandler::getMacroscopicReactionCrossSection( const PhotonState& particle, const PhotonuclearReactionType reaction ) { CellIdPhotonMaterialMap::const_iterator it = CollisionHandler::master_photon_map.find( particle.getCell() ); if( it != CollisionHandler::master_photon_map.end() ) { return it->second->getMacroscopicReactionCrossSection(particle.getEnergy(), reaction ); } else return 0.0; } // Collide with the material in a cell void CollisionHandler::collideWithCellMaterial( NeutronState& particle, ParticleBank& bank, const bool analogue ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), NEUTRON ) ); const Teuchos::RCP<NeutronMaterial>& material = CollisionHandler::master_neutron_map.find( particle.getCell() )->second; if( analogue ) material->collideAnalogue( particle, bank ); else material->collideSurvivalBias( particle, bank ); } // Collide with the material in a cell void CollisionHandler::collideWithCellMaterial( PhotonState& particle, ParticleBank& bank, const bool analogue ) { // Make sure the cell is not void testPrecondition( !CollisionHandler::isCellVoid( particle.getCell(), PHOTON ) ); const Teuchos::RCP<PhotonMaterial>& material = CollisionHandler::master_photon_map.find( particle.getCell() )->second; if( analogue ) material->collideAnalogue( particle, bank ); else material->collideSurvivalBias( particle, bank ); } } // end MonteCarlo namespace //---------------------------------------------------------------------------// // end MonteCarlo_CollisionHandler.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>/* Copyright (C) 2002 by John Harger This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/vector3.h" #include "csplugincommon/opengl/glextmanager.h" #include "csplugincommon/opengl/glstates.h" #include "csutil/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "iutil/comp.h" #include "iutil/plugin.h" #include "ivideo/graph2d.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_ps1.h" #include "ps1_emu_ati.h" #include "ps1_emu_nv.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderPS1) { SCF_IMPLEMENT_FACTORY (csGLShader_PS1) csGLShader_PS1::csGLShader_PS1(iBase* parent) : scfImplementationType (this, parent) { enable = false; isOpen = false; } csGLShader_PS1::~csGLShader_PS1() { } void csGLShader_PS1::Report (int severity, const char* msg, ...) { va_list args; va_start (args, msg); csReportV (object_reg, severity, "crystalspace.graphics3d.shader.glps1", msg, args); va_end (args); } //////////////////////////////////////////////////////////////////// // iShaderProgramPlugin //////////////////////////////////////////////////////////////////// bool csGLShader_PS1::SupportType(const char* type) { if (!enable) return false; else if (strcasecmp (type, "fp") == 0) return true; return false; } csPtr<iShaderProgram> csGLShader_PS1::CreateProgram (const char* type) { if (strcasecmp (type, "fp") == 0) { Open(); if(ext->CS_GL_ATI_fragment_shader) return csPtr<iShaderProgram> (new csShaderGLPS1_ATI (this)); else if(ext->CS_GL_NV_register_combiners) return csPtr<iShaderProgram> (new csShaderGLPS1_NV (this)); } return 0; } void csGLShader_PS1::Open() { if (isOpen) return; if(!object_reg) return; if (!ext) return; csRef<iConfigManager> config (csQueryRegistry<iConfigManager> (object_reg)); ext->InitGL_NV_register_combiners (); ext->InitGL_NV_register_combiners2 (); ext->InitGL_NV_texture_shader (); ext->InitGL_NV_texture_shader2 (); ext->InitGL_NV_texture_shader3 (); if(ext->CS_GL_NV_register_combiners) { if (doVerbose) { GLint num_combiners; glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &num_combiners); Report(CS_REPORTER_SEVERITY_NOTIFY, "Max General Combiners: %d", num_combiners); } } ext->InitGL_ATI_fragment_shader (); useLists = config->GetBool ("Video.OpenGL.Shader.PS1.UseDisplayLists", true); if (doVerbose) Report(CS_REPORTER_SEVERITY_NOTIFY, "Display list usage %s", useLists ? "enabled" : "disabled"); dumpTo14ConverterOutput = config->GetBool ( "Video.OpenGL.Shader.PS1.Dump14ConverterOutput", false); if(ext->CS_GL_ATI_fragment_shader) supportedPSVersion = CS_PS_1_4; else if (ext->CS_GL_NV_register_combiners2 && ext->CS_GL_NV_texture_shader) { if (ext->CS_GL_NV_texture_shader3) supportedPSVersion = CS_PS_1_3; else supportedPSVersion = CS_PS_1_1; } if (doVerbose) { Report(CS_REPORTER_SEVERITY_NOTIFY, "Highest supported PS version: %s", PSVersionStr (supportedPSVersion)); } isOpen = true; } const char* csGLShader_PS1::PSVersionStr (csPixelShaderVersion ver) const { switch (ver) { case CS_PS_1_1: return "1.1"; break; case CS_PS_1_2: return "1.2"; break; case CS_PS_1_3: return "1.3"; break; case CS_PS_1_4: return "1.4"; break; } return 0; } //////////////////////////////////////////////////////////////////// // iComponent //////////////////////////////////////////////////////////////////// bool csGLShader_PS1::Initialize(iObjectRegistry* reg) { object_reg = reg; csRef<iGraphics3D> r = csQueryRegistry<iGraphics3D> (object_reg); csRef<iFactory> f = scfQueryInterface<iFactory> (r); if (f != 0 && strcmp ("crystalspace.graphics3d.opengl", f->QueryClassID ()) == 0) enable = true; else return false; r->GetDriver2D()->PerformExtension ("getextmanager", &ext); if(!ext) return false; r->GetDriver2D()->PerformExtension ("getstatecache", &stateCache); if(!stateCache) return false; csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (object_reg)); if (verbosemgr) doVerbose = verbosemgr->Enabled ("renderer.shader"); else doVerbose = false; return true; } } CS_PLUGIN_NAMESPACE_END(GLShaderPS1) <commit_msg>Warning fix<commit_after>/* Copyright (C) 2002 by John Harger This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "cssysdef.h" #include "csgeom/vector3.h" #include "csplugincommon/opengl/glextmanager.h" #include "csplugincommon/opengl/glstates.h" #include "csutil/objreg.h" #include "csutil/ref.h" #include "csutil/scf.h" #include "iutil/comp.h" #include "iutil/plugin.h" #include "ivideo/graph2d.h" #include "ivideo/graph3d.h" #include "ivideo/shader/shader.h" #include "glshader_ps1.h" #include "ps1_emu_ati.h" #include "ps1_emu_nv.h" CS_PLUGIN_NAMESPACE_BEGIN(GLShaderPS1) { SCF_IMPLEMENT_FACTORY (csGLShader_PS1) csGLShader_PS1::csGLShader_PS1(iBase* parent) : scfImplementationType (this, parent) { enable = false; isOpen = false; } csGLShader_PS1::~csGLShader_PS1() { } void csGLShader_PS1::Report (int severity, const char* msg, ...) { va_list args; va_start (args, msg); csReportV (object_reg, severity, "crystalspace.graphics3d.shader.glps1", msg, args); va_end (args); } //////////////////////////////////////////////////////////////////// // iShaderProgramPlugin //////////////////////////////////////////////////////////////////// bool csGLShader_PS1::SupportType(const char* type) { if (!enable) return false; else if (strcasecmp (type, "fp") == 0) return true; return false; } csPtr<iShaderProgram> csGLShader_PS1::CreateProgram (const char* type) { if (strcasecmp (type, "fp") == 0) { Open(); if(ext->CS_GL_ATI_fragment_shader) return csPtr<iShaderProgram> (new csShaderGLPS1_ATI (this)); else if(ext->CS_GL_NV_register_combiners) return csPtr<iShaderProgram> (new csShaderGLPS1_NV (this)); } return 0; } void csGLShader_PS1::Open() { if (isOpen) return; if(!object_reg) return; if (!ext) return; csRef<iConfigManager> config (csQueryRegistry<iConfigManager> (object_reg)); ext->InitGL_NV_register_combiners (); ext->InitGL_NV_register_combiners2 (); ext->InitGL_NV_texture_shader (); ext->InitGL_NV_texture_shader2 (); ext->InitGL_NV_texture_shader3 (); if(ext->CS_GL_NV_register_combiners) { if (doVerbose) { GLint num_combiners; glGetIntegerv(GL_MAX_GENERAL_COMBINERS_NV, &num_combiners); Report(CS_REPORTER_SEVERITY_NOTIFY, "Max General Combiners: %d", num_combiners); } } ext->InitGL_ATI_fragment_shader (); useLists = config->GetBool ("Video.OpenGL.Shader.PS1.UseDisplayLists", true); if (doVerbose) Report(CS_REPORTER_SEVERITY_NOTIFY, "Display list usage %s", useLists ? "enabled" : "disabled"); dumpTo14ConverterOutput = config->GetBool ( "Video.OpenGL.Shader.PS1.Dump14ConverterOutput", false); if(ext->CS_GL_ATI_fragment_shader) supportedPSVersion = CS_PS_1_4; else if (ext->CS_GL_NV_register_combiners2 && ext->CS_GL_NV_texture_shader) { if (ext->CS_GL_NV_texture_shader3) supportedPSVersion = CS_PS_1_3; else supportedPSVersion = CS_PS_1_1; } if (doVerbose) { Report(CS_REPORTER_SEVERITY_NOTIFY, "Highest supported PS version: %s", PSVersionStr (supportedPSVersion)); } isOpen = true; } const char* csGLShader_PS1::PSVersionStr (csPixelShaderVersion ver) const { switch (ver) { case CS_PS_1_1: return "1.1"; break; case CS_PS_1_2: return "1.2"; break; case CS_PS_1_3: return "1.3"; break; case CS_PS_1_4: return "1.4"; break; case CS_PS_INVALID: break; } return 0; } //////////////////////////////////////////////////////////////////// // iComponent //////////////////////////////////////////////////////////////////// bool csGLShader_PS1::Initialize(iObjectRegistry* reg) { object_reg = reg; csRef<iGraphics3D> r = csQueryRegistry<iGraphics3D> (object_reg); csRef<iFactory> f = scfQueryInterface<iFactory> (r); if (f != 0 && strcmp ("crystalspace.graphics3d.opengl", f->QueryClassID ()) == 0) enable = true; else return false; r->GetDriver2D()->PerformExtension ("getextmanager", &ext); if(!ext) return false; r->GetDriver2D()->PerformExtension ("getstatecache", &stateCache); if(!stateCache) return false; csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (object_reg)); if (verbosemgr) doVerbose = verbosemgr->Enabled ("renderer.shader"); else doVerbose = false; return true; } } CS_PLUGIN_NAMESPACE_END(GLShaderPS1) <|endoftext|>
<commit_before>/****************************************************************************** * Copyright (c) 2014, Howard Butler (howard@hobu.co) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 OWNER 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 <pdal/kernel/Diff.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/scoped_ptr.hpp> using boost::property_tree::ptree; namespace pdal { namespace kernel { Diff::Diff(int argc, const char* argv[]) : Application(argc, argv, "dif") , m_sourceFile("") , m_candidateFile("") , m_useXML(false) , m_useJSON(false) { return; } void Diff::validateSwitches() { if (!m_sourceFile.size()) throw app_runtime_error("No source file given!"); if (!m_candidateFile.size()) throw app_runtime_error("No candidate file given!"); return; } void Diff::addSwitches() { namespace po = boost::program_options; po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("source", po::value<std::string>(&m_sourceFile), "source file name") ("candidate", po::value<std::string>(&m_candidateFile), "candidate file name") ("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true), "dump XML") ("json", po::value<bool>(&m_useJSON)->zero_tokens()->implicit_value(true), "dump JSON") ; addSwitchSet(file_options); po::options_description* processing_options = new po::options_description("processing options"); processing_options->add_options() ; addSwitchSet(processing_options); addPositionalSwitch("source", 1); addPositionalSwitch("candidate", 2); return; } void Diff::checkPoints(const PointBuffer& source_data, const PointBuffer& candidate_data, ptree& errors) { uint32_t i(0); uint32_t MAX_BADBYTES(20); uint32_t badbytes(0); // Both schemas have already been determined to be equal, so are the // same size and in the same order. Dimension::IdList const& sourceDims = source_data.context().dims(); Dimension::IdList const& candidateDims = candidate_data.context().dims(); char sbuf[8]; char cbuf[8]; for (PointId idx = 0; idx < source_data.size(); ++idx) { for (size_t d = 0; d < sourceDims.size(); ++d) { Dimension::Id::Enum sd = sourceDims[d]; Dimension::Id::Enum cd = candidateDims[d]; source_data.getRawField(sd, idx, (void *)sbuf); candidate_data.getRawField(cd, idx, (void *)cbuf); Dimension::Type::Enum t = Dimension::defaultType(cd); size_t size = Dimension::size(t); if (memcmp(sbuf, cbuf, size)) { std::ostringstream oss; oss << "Point " << idx << " differs for dimension \"" << Dimension::name(sd) << "\" for source and candidate"; errors.put<std::string>("data.error", oss.str()); badbytes++; } } if (badbytes > MAX_BADBYTES ) break; } } int Diff::execute() { PointContext sourceCtx; Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> source(AppSupport::makeReader(sourceOptions)); source->prepare(sourceCtx); PointBufferSet sourceSet = source->execute(sourceCtx); ptree errors; PointContext candidateCtx; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> candidate(AppSupport::makeReader(candidateOptions)); candidate->prepare(candidateCtx); PointBufferSet candidateSet = candidate->execute(candidateCtx); assert(sourceSet.size() == 1); assert(candidateSet.size() == 1); PointBufferPtr sourceBuf = *sourceSet.begin(); PointBufferPtr candidateBuf = *candidateSet.begin(); if (candidateBuf->size() != sourceBuf->size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same point count"; errors.put<std::string>("count.error", oss.str()); errors.put<uint32_t>("count.candidate", candidateBuf->size()); errors.put<uint32_t>("count.source", sourceBuf->size()); } MetadataNode source_metadata = sourceCtx.metadata(); MetadataNode candidate_metadata = candidateCtx.metadata(); if (source_metadata != candidate_metadata) { std::ostringstream oss; oss << "Source and candidate files do not have the same metadata count"; //ABELL /** errors.put<std::string>("metadata.error", oss.str()); errors.put_child("metadata.source", source_metadata.toPTree()); errors.put_child("metadata.candidate", candidate_metadata.toPTree()); **/ } if (candidateCtx.dims().size() != sourceCtx.dims().size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same number of dimensions"; errors.put<std::string>("schema.error", oss.str()); // FIXME: Need to "ptree" the PointContext dimension list in some way // errors.put_child("schema.source", sourceCtx.schema()->toPTree()); // errors.put_child("schema.candidate", candidateCtx.schema()->toPTree()); } if (errors.size()) { write_json(std::cout, errors); return 1; } else { // If we made it this far with no errors, now we'll // check the points. checkPoints(*sourceBuf, *candidateBuf, errors); if (errors.size()) { write_json(std::cout, errors); return 1; } } return 0; } }} // pdal::kernel <commit_msg>Diff cleanup.<commit_after>/****************************************************************************** * Copyright (c) 2014, Howard Butler (howard@hobu.co) * * 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 Hobu, Inc. or Flaxen Geo Consulting 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 OWNER 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 <pdal/kernel/Diff.hpp> #include <boost/property_tree/ptree.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/xml_parser.hpp> #include <boost/scoped_ptr.hpp> using boost::property_tree::ptree; namespace pdal { namespace kernel { Diff::Diff(int argc, const char* argv[]) : Application(argc, argv, "dif") , m_sourceFile("") , m_candidateFile("") , m_useXML(false) , m_useJSON(false) {} void Diff::validateSwitches() { if (!m_sourceFile.size()) throw app_runtime_error("No source file given!"); if (!m_candidateFile.size()) throw app_runtime_error("No candidate file given!"); } void Diff::addSwitches() { namespace po = boost::program_options; po::options_description* file_options = new po::options_description("file options"); file_options->add_options() ("source", po::value<std::string>(&m_sourceFile), "source file name") ("candidate", po::value<std::string>(&m_candidateFile), "candidate file name") ("xml", po::value<bool>(&m_useXML)->zero_tokens()->implicit_value(true), "dump XML") ("json", po::value<bool>(&m_useJSON)->zero_tokens()->implicit_value(true), "dump JSON") ; addSwitchSet(file_options); po::options_description* processing_options = new po::options_description("processing options"); processing_options->add_options(); addSwitchSet(processing_options); addPositionalSwitch("source", 1); addPositionalSwitch("candidate", 2); } void Diff::checkPoints(const PointBuffer& source_data, const PointBuffer& candidate_data, ptree& errors) { uint32_t i(0); uint32_t MAX_BADBYTES(20); uint32_t badbytes(0); // Both schemas have already been determined to be equal, so are the // same size and in the same order. Dimension::IdList const& sourceDims = source_data.context().dims(); Dimension::IdList const& candidateDims = candidate_data.context().dims(); char sbuf[8]; char cbuf[8]; for (PointId idx = 0; idx < source_data.size(); ++idx) { for (size_t d = 0; d < sourceDims.size(); ++d) { Dimension::Id::Enum sd = sourceDims[d]; Dimension::Id::Enum cd = candidateDims[d]; source_data.getRawField(sd, idx, (void *)sbuf); candidate_data.getRawField(cd, idx, (void *)cbuf); Dimension::Type::Enum t = Dimension::defaultType(cd); size_t size = Dimension::size(t); if (memcmp(sbuf, cbuf, size)) { std::ostringstream oss; oss << "Point " << idx << " differs for dimension \"" << Dimension::name(sd) << "\" for source and candidate"; errors.put<std::string>("data.error", oss.str()); badbytes++; } } if (badbytes > MAX_BADBYTES ) break; } } int Diff::execute() { PointContext sourceCtx; Options sourceOptions; { sourceOptions.add<std::string>("filename", m_sourceFile); sourceOptions.add<bool>("debug", isDebug()); sourceOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> source(AppSupport::makeReader(sourceOptions)); source->prepare(sourceCtx); PointBufferSet sourceSet = source->execute(sourceCtx); ptree errors; PointContext candidateCtx; Options candidateOptions; { candidateOptions.add<std::string>("filename", m_candidateFile); candidateOptions.add<bool>("debug", isDebug()); candidateOptions.add<boost::uint32_t>("verbose", getVerboseLevel()); } std::unique_ptr<Stage> candidate(AppSupport::makeReader(candidateOptions)); candidate->prepare(candidateCtx); PointBufferSet candidateSet = candidate->execute(candidateCtx); assert(sourceSet.size() == 1); assert(candidateSet.size() == 1); PointBufferPtr sourceBuf = *sourceSet.begin(); PointBufferPtr candidateBuf = *candidateSet.begin(); if (candidateBuf->size() != sourceBuf->size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same point count"; errors.put("count.error", oss.str()); errors.put("count.candidate", candidateBuf->size()); errors.put("count.source", sourceBuf->size()); } MetadataNode source_metadata = sourceCtx.metadata(); MetadataNode candidate_metadata = candidateCtx.metadata(); if (source_metadata != candidate_metadata) { std::ostringstream oss; oss << "Source and candidate files do not have the same metadata count"; errors.put("metadata.error", oss.str()); errors.put_child("metadata.source", source_metadata.toPTree()); errors.put_child("metadata.candidate", candidate_metadata.toPTree()); } if (candidateCtx.dims().size() != sourceCtx.dims().size()) { std::ostringstream oss; oss << "Source and candidate files do not have the same " "number of dimensions"; errors.put<std::string>("schema.error", oss.str()); // FIXME: Need to "ptree" the PointContext dimension list in some way // errors.put_child("schema.source", sourceCtx.schema()->toPTree()); // errors.put_child("schema.candidate", // candidateCtx.schema()->toPTree()); } if (errors.size()) { write_json(std::cout, errors); return 1; } else { // If we made it this far with no errors, now we'll // check the points. checkPoints(*sourceBuf, *candidateBuf, errors); if (errors.size()) { write_json(std::cout, errors); return 1; } } return 0; } } // namespace kernel } // namespace pdal <|endoftext|>
<commit_before>#include <ignition/math/Pose3.hh> #include "gazebo/physics/physics.hh" #include "gazebo/common/common.hh" #include "gazebo/gazebo.hh" #include <ros/ros.h> #include <boost/bind/bind.hpp> #include <tf2_msgs/TFMessage.h> #include <tf/transform_listener.h> #include <boost/thread.hpp> namespace gazebo { struct tokens: std::ctype<char> { tokens(): std::ctype<char>(get_table()) {} static std::ctype_base::mask const* get_table() { typedef std::ctype<char> cctype; static const cctype::mask *const_rc= cctype::classic_table(); static cctype::mask rc[cctype::table_size]; std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask)); rc[','] = std::ctype_base::space; rc[' '] = std::ctype_base::space; return &rc[0]; } }; typedef struct { physics::WorldPtr parentWorld; std::vector<std::string> phantoms; tf::TransformListener listener; }tPhantomContext; tPhantomContext PhantomContext; class LabPhantoms; void onTFData2(const tf2_msgs::TFMessage::ConstPtr& msg); void onTFData(const tf2_msgs::TFMessage::ConstPtr& msg);//, LabPhantoms *plugin); math::Pose Msg2Pose(geometry_msgs::Transform const& msg) { math::Pose pose; math::Vector3 v; math::Quaternion q; v.x = msg.translation.x; v.y = msg.translation.y; v.z = msg.translation.z; q.w = msg.rotation.w; q.x = msg.rotation.x; q.y = msg.rotation.y; q.z = msg.rotation.z; pose.Set(v, q); return pose; } math::Pose StampedTransform2Pose(tf::StampedTransform const& transform) { tf::Vector3 vt = transform.getOrigin(); tf::Quaternion qt = transform.getRotation(); math::Vector3 v; math::Quaternion q; v.x = vt.x(); v.y = vt.y(); v.z = vt.z(); /*SUPER DIRTY HAXX*/ if(0.755 > v.z) v.z = 0.755; q.w = qt.w(); q.x = qt.x(); q.y = qt.y(); q.z = qt.z(); math::Pose pose; pose.Set(v, q); return pose; } class LabPhantoms : public WorldPlugin { protected: bool havePhantom(std::string const& name) { bool retq = false; int maxK = phantoms.size(); for(int k = 0; (!retq) && (k < maxK); k++) retq = (phantoms[k] == name); return retq; } public: LabPhantoms() { n = 0; parentWorld.reset(); } ~LabPhantoms() { running = false; if(n) delete n; } void monitorTFThread(void) { ros::Rate rate(0.5); while(running) { physics::WorldPtr world = parentWorld; std::vector<std::string> phantomsL = phantoms; tf::TransformListener listenerL; int maxK = phantomsL.size(); listenerL.waitForTransform("bottle_250ml_0_frame", "/map", ros::Time::now(), ros::Duration(3.0)); for(int k = 0; k < maxK; k++) { std::string childFrame = "/"; childFrame += phantomsL[k] + "_frame"; tf::StampedTransform transform; try { ros::Time now = ros::Time::now(); listenerL.lookupTransform("/map", childFrame, ros::Time(), transform); if(phantomsL[k] == "pipette_accumax") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "PIPETTE TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "bottle_250ml") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "BOTTLE_250ML TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "mixer_ikamag") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "MIXER_IKAMAG TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "flask_400ml_0") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "FLASK_400ml_0 TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } physics::ModelPtr childModel = world->GetModel(phantomsL[k]); if(childModel.get()) { math::Pose world2Child = StampedTransform2Pose(transform); childModel->SetWorldPose(world2Child); childModel->SetGravityMode(true); childModel->SetStatic(true); } } catch (tf::TransformException ex) { ROS_ERROR("%s", ex.what()); } } rate.sleep(); } } void onTFData(const tf2_msgs::TFMessageConstPtr& msg) { if(!(parentWorld.get())) return; physics::WorldPtr world = parentWorld; int maxK = msg->transforms.size(); for(int k = 0; k < maxK; k++) { geometry_msgs::TransformStamped transform = msg->transforms[k]; std::string parentFrame = transform.header.frame_id; std::string childFrame = transform.child_frame_id; /*DIRTY HAXXXXX TO BE REMOVED.*/ if("in_r_gripper_tool_frame" == parentFrame) parentFrame = "r_gripper_tool_frame"; if("in_l_gripper_tool_frame" == parentFrame) parentFrame = "l_gripper_tool_frame"; if(havePhantom(childFrame)) { physics::ModelPtr childModel = world->GetModel(childFrame); physics::ModelPtr parentModel = world->GetModel(parentFrame); if((childModel.get()) && (parentModel.get())) { math::Pose parent2Child = Msg2Pose(transform.transform); math::Pose world2Parent = parentModel->GetWorldPose(); childModel->SetWorldPose(parent2Child*world2Parent); } } } } void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) { parentWorld = _parent; pluginParameters = _sdf; char nodeName[] = "labphantoms"; char* argv[] = {nodeName}; int argc = 1; ros::init(argc, argv, "labphantoms"); n = new ros::NodeHandle(); //ros::Subscriber sub = n->subscribe("/tf", 1, &LabPhantoms::onTFData, this); if(pluginParameters->HasElement("trackedModels")) { std::string trackedModels = pluginParameters->Get<std::string>("trackedModels"); std::string dbgStr = "Tracked Models as given by launch file: "; dbgStr = dbgStr + trackedModels; std::cerr << dbgStr << "\n"; std::stringstream ss(trackedModels); ss.imbue(std::locale(std::locale(), new tokens())); std::istream_iterator<std::string> begin(ss); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cerr, "\n")); phantoms = vstrings; } running = true; boost::thread(&LabPhantoms::monitorTFThread, this); } protected: bool running; ros::NodeHandle *n; physics::WorldPtr parentWorld; sdf::ElementPtr pluginParameters; std::vector<std::string> phantoms; tf::TransformListener listener; }; // Register this plugin with the simulator GZ_REGISTER_WORLD_PLUGIN(LabPhantoms) } <commit_msg>Undid a dirty hack.<commit_after>#include <ignition/math/Pose3.hh> #include "gazebo/physics/physics.hh" #include "gazebo/common/common.hh" #include "gazebo/gazebo.hh" #include <ros/ros.h> #include <boost/bind/bind.hpp> #include <tf2_msgs/TFMessage.h> #include <tf/transform_listener.h> #include <boost/thread.hpp> namespace gazebo { struct tokens: std::ctype<char> { tokens(): std::ctype<char>(get_table()) {} static std::ctype_base::mask const* get_table() { typedef std::ctype<char> cctype; static const cctype::mask *const_rc= cctype::classic_table(); static cctype::mask rc[cctype::table_size]; std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask)); rc[','] = std::ctype_base::space; rc[' '] = std::ctype_base::space; return &rc[0]; } }; typedef struct { physics::WorldPtr parentWorld; std::vector<std::string> phantoms; tf::TransformListener listener; }tPhantomContext; tPhantomContext PhantomContext; class LabPhantoms; void onTFData2(const tf2_msgs::TFMessage::ConstPtr& msg); void onTFData(const tf2_msgs::TFMessage::ConstPtr& msg);//, LabPhantoms *plugin); math::Pose Msg2Pose(geometry_msgs::Transform const& msg) { math::Pose pose; math::Vector3 v; math::Quaternion q; v.x = msg.translation.x; v.y = msg.translation.y; v.z = msg.translation.z; q.w = msg.rotation.w; q.x = msg.rotation.x; q.y = msg.rotation.y; q.z = msg.rotation.z; pose.Set(v, q); return pose; } math::Pose StampedTransform2Pose(tf::StampedTransform const& transform) { tf::Vector3 vt = transform.getOrigin(); tf::Quaternion qt = transform.getRotation(); math::Vector3 v; math::Quaternion q; v.x = vt.x(); v.y = vt.y(); v.z = vt.z(); /*SUPER DIRTY HAXX*/ if(0.755 > v.z) v.z = 0.755; q.w = qt.w(); q.x = qt.x(); q.y = qt.y(); q.z = qt.z(); math::Pose pose; pose.Set(v, q); return pose; } class LabPhantoms : public WorldPlugin { protected: bool havePhantom(std::string const& name) { bool retq = false; int maxK = phantoms.size(); for(int k = 0; (!retq) && (k < maxK); k++) retq = (phantoms[k] == name); return retq; } public: LabPhantoms() { n = 0; parentWorld.reset(); } ~LabPhantoms() { running = false; if(n) delete n; } void monitorTFThread(void) { ros::Rate rate(0.5); while(running) { physics::WorldPtr world = parentWorld; std::vector<std::string> phantomsL = phantoms; tf::TransformListener listenerL; int maxK = phantomsL.size(); listenerL.waitForTransform("bottle_250ml_0_frame", "/map", ros::Time::now(), ros::Duration(3.0)); for(int k = 0; k < maxK; k++) { std::string childFrame = "/"; childFrame += phantomsL[k] + "_frame"; tf::StampedTransform transform; try { ros::Time now = ros::Time::now(); listenerL.lookupTransform("/map", childFrame, ros::Time(), transform); if(phantomsL[k] == "pipette_accumax") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "PIPETTE TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "bottle_250ml") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "BOTTLE_250ML TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "mixer_ikamag") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "MIXER_IKAMAG TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } if(phantomsL[k] == "flask_400ml_0") { math::Pose p = StampedTransform2Pose(transform); std::cerr << "FLASK_400ml_0 TRANSFORM to /map V(" << p.pos.x << " " << p.pos.y << " " << p.pos.z << ") Q(" << p.rot.w << " " << p.rot.x << " " << p.rot.y << " " << p.rot.z << ")" << std::endl; } physics::ModelPtr childModel = world->GetModel(phantomsL[k]); if(childModel.get()) { math::Pose world2Child = StampedTransform2Pose(transform); childModel->SetWorldPose(world2Child); childModel->SetStatic(true); childModel->SetGravityMode(false); } } catch (tf::TransformException ex) { ROS_ERROR("%s", ex.what()); } } rate.sleep(); } } void onTFData(const tf2_msgs::TFMessageConstPtr& msg) { if(!(parentWorld.get())) return; physics::WorldPtr world = parentWorld; int maxK = msg->transforms.size(); for(int k = 0; k < maxK; k++) { geometry_msgs::TransformStamped transform = msg->transforms[k]; std::string parentFrame = transform.header.frame_id; std::string childFrame = transform.child_frame_id; /*DIRTY HAXXXXX TO BE REMOVED.*/ if("in_r_gripper_tool_frame" == parentFrame) parentFrame = "r_gripper_tool_frame"; if("in_l_gripper_tool_frame" == parentFrame) parentFrame = "l_gripper_tool_frame"; if(havePhantom(childFrame)) { physics::ModelPtr childModel = world->GetModel(childFrame); physics::ModelPtr parentModel = world->GetModel(parentFrame); if((childModel.get()) && (parentModel.get())) { math::Pose parent2Child = Msg2Pose(transform.transform); math::Pose world2Parent = parentModel->GetWorldPose(); childModel->SetWorldPose(parent2Child*world2Parent); } } } } void Load(physics::WorldPtr _parent, sdf::ElementPtr _sdf) { parentWorld = _parent; pluginParameters = _sdf; char nodeName[] = "labphantoms"; char* argv[] = {nodeName}; int argc = 1; ros::init(argc, argv, "labphantoms"); n = new ros::NodeHandle(); //ros::Subscriber sub = n->subscribe("/tf", 1, &LabPhantoms::onTFData, this); if(pluginParameters->HasElement("trackedModels")) { std::string trackedModels = pluginParameters->Get<std::string>("trackedModels"); std::string dbgStr = "Tracked Models as given by launch file: "; dbgStr = dbgStr + trackedModels; std::cerr << dbgStr << "\n"; std::stringstream ss(trackedModels); ss.imbue(std::locale(std::locale(), new tokens())); std::istream_iterator<std::string> begin(ss); std::istream_iterator<std::string> end; std::vector<std::string> vstrings(begin, end); std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cerr, "\n")); phantoms = vstrings; } running = true; boost::thread(&LabPhantoms::monitorTFThread, this); } protected: bool running; ros::NodeHandle *n; physics::WorldPtr parentWorld; sdf::ElementPtr pluginParameters; std::vector<std::string> phantoms; tf::TransformListener listener; }; // Register this plugin with the simulator GZ_REGISTER_WORLD_PLUGIN(LabPhantoms) } <|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 13.07.2009 \brief RDOValue \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOValue_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_res_type.h" // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE(RDOValue_Test) BOOST_AUTO_TEST_CASE(RDOValue_String) { const tstring str1 = _T("qqq"); rdoRuntime::RDOValue value1(str1); BOOST_CHECK(value1.getString () == str1); BOOST_CHECK(value1.getAsString() == str1); rdoRuntime::RDOValue value2 = value1; BOOST_CHECK(value2.getString () == str1); BOOST_CHECK(value2.getAsString() == str1); BOOST_CHECK(value2 == value1); const tstring str2 = _T("aaa"); value2 += str2; BOOST_CHECK(value2.getString () == str1 + str2); BOOST_CHECK(value2.getAsString() == str1 + str2); } BOOST_AUTO_TEST_CASE(RDOValue_Resource) { using namespace rdoRuntime; LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPRDOResourceType pResourceType = rdo::Factory<RDOResourceType>::create(0); BOOST_CHECK(pResourceType); LPIResourceType pResourceFactory = pResourceType.interface_cast<IResourceType>(); BOOST_CHECK(pResourceFactory); std::vector<RDOValue> paramList; paramList.push_back(RDOValue(1 )); paramList.push_back(RDOValue(2.2 )); paramList.push_back(RDOValue(_T("3"))); LPRDOResource pResource = pResourceFactory->createRes(pRuntime, pRuntime->getResourceId(), paramList, true, true); BOOST_CHECK(pResource); RDOValue value1(pResourceType, pResource); LPRDOResourceType pType = value1.type().object_dynamic_cast<RDOResourceType>(); BOOST_CHECK(pType); LPRDOResource pResource1 = value1.getPointer<RDOResource>(); pRuntime = NULL; value1 = RDOValue(); pResource1 = NULL; BOOST_CHECK(pResource.owner()); pResource = NULL; } BOOST_AUTO_TEST_SUITE_END() //RDOValue_Resource <commit_msg> - добавлены тесты для типов int, uint, double, char, bool<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 13.07.2009 \brief RDOValue \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #include <boost/regex.hpp> #define BOOST_TEST_MODULE RDOValue_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_res_type.h" // -------------------------------------------------------------------------------- BOOST_AUTO_TEST_SUITE(RDOValue_Test) BOOST_AUTO_TEST_CASE(RDOValue_String) { const tstring str1 = _T("qqq"); rdoRuntime::RDOValue value1(str1); BOOST_CHECK(value1.getString () == str1); BOOST_CHECK(value1.getAsString() == str1); rdoRuntime::RDOValue value2 = value1; BOOST_CHECK(value2.getString () == str1); BOOST_CHECK(value2.getAsString() == str1); BOOST_CHECK(value2 == value1); const tstring str2 = _T("aaa"); value2 += str2; BOOST_CHECK(value2.getString () == str1 + str2); BOOST_CHECK(value2.getAsString() == str1 + str2); } BOOST_AUTO_TEST_CASE(RDOValue_Rsint) { const rsint int1 = 30; rdoRuntime::RDOValue value1(int1); BOOST_CHECK(value1.getInt() == int1); rdoRuntime::RDOValue value2 = value1; BOOST_CHECK(value2 == int1); BOOST_CHECK(value2 == value1); const rsint int2 = 20; value1 += int2; BOOST_CHECK(value1 == int1 + int2); const rsint int3 = 10; value1 -= int3; BOOST_CHECK(value1 == int1 + int2 - int3); const rsint int4 = 2; value2 = value1; value2 *= int4; BOOST_CHECK(value2 == value1 * int4); const rsint int5 = 5; value2 = value1; value2 /= int5; BOOST_CHECK(value2 == value1 / int5); value2 = value1; value2 --; BOOST_CHECK(value2 == value1 - 1); value2 ++; BOOST_CHECK(value2 == value1); value1 = int1; value2 = int2; BOOST_CHECK(value1 != value2); BOOST_CHECK(value1 > value2); BOOST_CHECK(value2 < value1); BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); value2 = int1; BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); } BOOST_AUTO_TEST_CASE(RDOValue_Ruint) { const ruint int1 = 30; rdoRuntime::RDOValue value1(int1); BOOST_CHECK(value1 == int1); rdoRuntime::RDOValue value2 = value1; BOOST_CHECK(value2 == int1); BOOST_CHECK(value2 == value1); const ruint int2 = 20; value1 += int2; BOOST_CHECK(value1 == int1 + int2); const ruint int3 = 10; value1 -= int3; BOOST_CHECK(value1 == int1 + int2 - int3); const ruint int4 = 2; value2 = value1; value2 *= int4; BOOST_CHECK(value2 == value1 * int4); const ruint int5 = 5; value2 = value1; value2 /= int5; BOOST_CHECK(value2 == value1 / int5); value2 = value1; value2 --; BOOST_CHECK(value2 == value1 - 1); value2 ++; BOOST_CHECK(value2 == value1); value1 = int1; value2 = int2; BOOST_CHECK(value1 != value2); BOOST_CHECK(value1 > value2); BOOST_CHECK(value2 < value1); BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); value2 = int1; BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); } BOOST_AUTO_TEST_CASE(RDOValue_Double) { const double doub1 = 30.2; rdoRuntime::RDOValue value1(doub1); BOOST_CHECK(value1 == doub1); rdoRuntime::RDOValue value2 = value1; BOOST_CHECK(value2 == doub1); BOOST_CHECK(value2 == value1); const double doub2 = 20.5; value1 += doub2; BOOST_CHECK(value1 == doub1 + doub2); const double doub3 = 10.3; value1 -= doub3; BOOST_CHECK(value1 == doub1 + doub2 - doub3); const double doub4 = 2.5; value2 = value1; value2 *= doub4; BOOST_CHECK(value2 == value1 * doub4); const double doub5 = 5; value2 = value1; value2 /= doub5; BOOST_CHECK(value2 == value1 / doub5); value2 = value1; value2 --; BOOST_CHECK(value2 == value1 - 1); value2 ++; BOOST_CHECK(value2 == value1); value1 = doub1; value2 = doub2; BOOST_CHECK(value1 != value2); BOOST_CHECK(value1 > value2); BOOST_CHECK(value2 < value1); BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); value2 = doub1; BOOST_CHECK(value1 >= value2); BOOST_CHECK(value2 <= value1); } BOOST_AUTO_TEST_CASE(RDOValue_Bool) { rbool bool1 = true; rbool bool2 = false; rbool bool3 = true; rbool bool4 = false; rdoRuntime::RDOValue value1(bool1); rdoRuntime::RDOValue value2(bool2); rdoRuntime::RDOValue value3(bool3); rdoRuntime::RDOValue value4(bool4); BOOST_CHECK(value1.getBool()); BOOST_CHECK(!value2); BOOST_CHECK(value2 == value4); BOOST_CHECK(value1 != value2); BOOST_CHECK(!(value1 == value2)); BOOST_CHECK(value1 && value3); BOOST_CHECK(!(value2 && value3)); BOOST_CHECK(value1 || value2); BOOST_CHECK(!(value2 || value4)); } BOOST_AUTO_TEST_CASE(RDOValue_Char) { tchar ch1 = 'a'; tchar ch2 = 'b'; rdoRuntime::RDOValue value1 = ch1; rdoRuntime::RDOValue value2 = ch2; BOOST_CHECK(value1 == ch1); BOOST_CHECK(value1 < value2); BOOST_CHECK(value2 > value1); BOOST_CHECK(value1 != value2); value1 = value2; BOOST_CHECK(value1 == value2); } BOOST_AUTO_TEST_CASE(RDOValue_Enum) { using namespace rdoRuntime; LPRDOEnumType pEnum = rdo::Factory<RDOEnumType>::create(); BOOST_CHECK(pEnum); pEnum->empty(); } /* BOOST_AUTO_TEST_CASE(RDOValue_Identificator) { } */ BOOST_AUTO_TEST_CASE(RDOValue_Resource) { using namespace rdoRuntime; LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPRDOResourceType pResourceType = rdo::Factory<RDOResourceType>::create(0); BOOST_CHECK(pResourceType); LPIResourceType pResourceFactory = pResourceType.interface_cast<IResourceType>(); BOOST_CHECK(pResourceFactory); std::vector<RDOValue> paramList; paramList.push_back(RDOValue(1 )); paramList.push_back(RDOValue(2.2 )); paramList.push_back(RDOValue(_T("3"))); LPRDOResource pResource = pResourceFactory->createRes(pRuntime, pRuntime->getResourceId(), paramList, true, true); BOOST_CHECK(pResource); RDOValue value1(pResourceType, pResource); LPRDOResourceType pType = value1.type().object_dynamic_cast<RDOResourceType>(); BOOST_CHECK(pType); LPRDOResource pResource1 = value1.getPointer<RDOResource>(); pRuntime = NULL; value1 = RDOValue(); pResource1 = NULL; BOOST_CHECK(pResource.owner()); pResource = NULL; } BOOST_AUTO_TEST_SUITE_END() //RDOValue_Resource <|endoftext|>
<commit_before>/* * copyright: (c) RDO-Team, 2011 * filename : statements.cpp * author : , * date : 16.04.11 * bref : * indent : 4T */ // ====================================================================== PCH #include "rdo_lib/rdo_runtime/pch.h" // ====================================================================== INCLUDES // ====================================================================== SYNOPSIS #include "rdo_lib/rdo_runtime/calc/statements.h" // =============================================================================== OPEN_RDO_RUNTIME_NAMESPACE // ---------------------------------------------------------------------------- // ---------- RDOCalcNoChange // ---------------------------------------------------------------------------- RDOCalcNoChange::RDOCalcNoChange() {} REF(RDOValue) RDOCalcNoChange::doCalc(PTR(RDORuntime) pRuntime) { m_value = RDOValue(0); return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcIf // ---------------------------------------------------------------------------- RDOCalcIf::RDOCalcIf(CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pStatement) : m_pCondition(pCondition) , m_pStatement(pStatement) { ASSERT(m_pCondition); ASSERT(m_pStatement); } REF(RDOValue) RDOCalcIf::doCalc(PTR(RDORuntime) pRuntime) { m_value = RDOValue(false); return (m_pCondition->calcValue(pRuntime).getAsBool()) ? m_pStatement->calcValue(pRuntime) : (m_value); } // ---------------------------------------------------------------------------- // ---------- RDOCalcIfElse // ---------------------------------------------------------------------------- RDOCalcIfElse::RDOCalcIfElse(CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pIfStatement, CREF(LPRDOCalc) pElseStatement) : m_pCondition (pCondition ) , m_pIfStatement (pIfStatement ) , m_pElseStatement(pElseStatement) { ASSERT(m_pCondition ); ASSERT(m_pIfStatement ); ASSERT(m_pElseStatement); } REF(RDOValue) RDOCalcIfElse::doCalc(PTR(RDORuntime) pRuntime) { return (m_pCondition->calcValue(pRuntime).getAsBool()) ? m_pIfStatement->calcValue(pRuntime) : m_pElseStatement->calcValue(pRuntime); } // ---------------------------------------------------------------------------- // ---------- RDOCalcFor // ---------------------------------------------------------------------------- RDOCalcFor::RDOCalcFor(CREF(LPRDOCalc) pDeclaration, CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pExpression, CREF(LPRDOCalc) pStatement) : m_pDeclaration(pDeclaration) , m_pCondition (pCondition ) , m_pExpression (pExpression ) , m_pStatement (pStatement ) { ASSERT(m_pDeclaration); ASSERT(m_pCondition ); ASSERT(m_pExpression ); ASSERT(m_pStatement ); } REF(RDOValue) RDOCalcFor::doCalc(PTR(RDORuntime) pRuntime) { if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_CONTINUE) { m_value = m_pDeclaration->calcValue(pRuntime); while (m_pCondition->calcValue(pRuntime).getAsBool()) { m_value = m_pStatement->calcValue(pRuntime); m_value = m_pExpression->calcValue(pRuntime); if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_BREAK) { pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); return m_value; } if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_RETURN) { return m_value; } } } return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcFunReturn // ---------------------------------------------------------------------------- RDOCalcFunReturn::RDOCalcFunReturn(CREF(LPRDOCalc) pReturn) : m_pReturn(pReturn) {} REF(RDOValue) RDOCalcFunReturn::doCalc(PTR(RDORuntime) pRuntime) { m_value = m_pReturn->calcValue(pRuntime); pRuntime->setFunBreakFlag(RDORuntime::FBF_RETURN); return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcFunBreak // ---------------------------------------------------------------------------- RDOCalcFunBreak::RDOCalcFunBreak() {} REF(RDOValue) RDOCalcFunBreak::doCalc(PTR(RDORuntime) pRuntime) { pRuntime->setFunBreakFlag(RDORuntime::FBF_BREAK); return m_value; } CLOSE_RDO_RUNTIME_NAMESPACE <commit_msg> - исправлена ошибка RDOCalcFor::doCalc<commit_after>/* * copyright: (c) RDO-Team, 2011 * filename : statements.cpp * author : , * date : 16.04.11 * bref : * indent : 4T */ // ====================================================================== PCH #include "rdo_lib/rdo_runtime/pch.h" // ====================================================================== INCLUDES // ====================================================================== SYNOPSIS #include "rdo_lib/rdo_runtime/calc/statements.h" // =============================================================================== OPEN_RDO_RUNTIME_NAMESPACE // ---------------------------------------------------------------------------- // ---------- RDOCalcNoChange // ---------------------------------------------------------------------------- RDOCalcNoChange::RDOCalcNoChange() {} REF(RDOValue) RDOCalcNoChange::doCalc(PTR(RDORuntime) pRuntime) { m_value = RDOValue(0); return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcIf // ---------------------------------------------------------------------------- RDOCalcIf::RDOCalcIf(CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pStatement) : m_pCondition(pCondition) , m_pStatement(pStatement) { ASSERT(m_pCondition); ASSERT(m_pStatement); } REF(RDOValue) RDOCalcIf::doCalc(PTR(RDORuntime) pRuntime) { m_value = RDOValue(false); return (m_pCondition->calcValue(pRuntime).getAsBool()) ? m_pStatement->calcValue(pRuntime) : (m_value); } // ---------------------------------------------------------------------------- // ---------- RDOCalcIfElse // ---------------------------------------------------------------------------- RDOCalcIfElse::RDOCalcIfElse(CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pIfStatement, CREF(LPRDOCalc) pElseStatement) : m_pCondition (pCondition ) , m_pIfStatement (pIfStatement ) , m_pElseStatement(pElseStatement) { ASSERT(m_pCondition ); ASSERT(m_pIfStatement ); ASSERT(m_pElseStatement); } REF(RDOValue) RDOCalcIfElse::doCalc(PTR(RDORuntime) pRuntime) { return (m_pCondition->calcValue(pRuntime).getAsBool()) ? m_pIfStatement->calcValue(pRuntime) : m_pElseStatement->calcValue(pRuntime); } // ---------------------------------------------------------------------------- // ---------- RDOCalcFor // ---------------------------------------------------------------------------- RDOCalcFor::RDOCalcFor(CREF(LPRDOCalc) pDeclaration, CREF(LPRDOCalc) pCondition, CREF(LPRDOCalc) pExpression, CREF(LPRDOCalc) pStatement) : m_pDeclaration(pDeclaration) , m_pCondition (pCondition ) , m_pExpression (pExpression ) , m_pStatement (pStatement ) { ASSERT(m_pDeclaration); ASSERT(m_pCondition ); ASSERT(m_pExpression ); ASSERT(m_pStatement ); } REF(RDOValue) RDOCalcFor::doCalc(PTR(RDORuntime) pRuntime) { if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_CONTINUE) { m_value = m_pDeclaration->calcValue(pRuntime); while (m_pCondition->calcValue(pRuntime).getAsBool()) { m_value = m_pStatement->calcValue(pRuntime); m_pExpression->calcValue(pRuntime); if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_BREAK) { pRuntime->setFunBreakFlag(RDORuntime::FBF_CONTINUE); return m_value; } if(pRuntime->getFunBreakFlag() == RDORuntime::FBF_RETURN) { return m_value; } } } return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcFunReturn // ---------------------------------------------------------------------------- RDOCalcFunReturn::RDOCalcFunReturn(CREF(LPRDOCalc) pReturn) : m_pReturn(pReturn) {} REF(RDOValue) RDOCalcFunReturn::doCalc(PTR(RDORuntime) pRuntime) { m_value = m_pReturn->calcValue(pRuntime); pRuntime->setFunBreakFlag(RDORuntime::FBF_RETURN); return m_value; } // ---------------------------------------------------------------------------- // ---------- RDOCalcFunBreak // ---------------------------------------------------------------------------- RDOCalcFunBreak::RDOCalcFunBreak() {} REF(RDOValue) RDOCalcFunBreak::doCalc(PTR(RDORuntime) pRuntime) { pRuntime->setFunBreakFlag(RDORuntime::FBF_BREAK); return m_value; } CLOSE_RDO_RUNTIME_NAMESPACE <|endoftext|>
<commit_before> #include <cassert> #ifdef _WIN32 #include <windows.h> #include <malloc.h> #endif #include "Process.h" #ifdef _WIN32 #include "Array.h" #include "Map.h" #include "File.h" #endif #ifdef _WIN32 static Array<HANDLE> runningProcessHandles; #endif Process::Process() { #ifdef _WIN32 assert(sizeof(hProcess) >= sizeof(HANDLE)); hProcess = INVALID_HANDLE_VALUE; #endif } Process::~Process() { #ifdef _WIN32 if(hProcess != INVALID_HANDLE_VALUE) { CloseHandle((HANDLE)hProcess); int index = runningProcessHandles.find(hProcess); assert(index >= 0); runningProcessHandles.remove(index); } #endif } unsigned int Process::start(const List<String>& command) { #ifdef _WIN32 struct Executable { static bool Executable::fileComplete(const String& searchName, bool testExtensions, String& result) { if(File::exists(searchName)) { result = searchName; return true; } if(testExtensions) { String testPath = searchName; testPath.append(".exe"); if(File::exists(testPath)) { result = testPath; return true; } testPath.setLength(searchName.getLength()); testPath.append(".com"); if(File::exists(testPath)) { result = testPath; return true; } } return false; } static const List<String>& getPathEnv() { static List<String> searchPaths; static bool loaded = false; if(!loaded) { char* pathVar = (char*)alloca(32767); GetEnvironmentVariable("PATH", pathVar, 32767); for(const char* str = pathVar; *str;) { const char* end = strchr(str, ';'); if(end) { if(end > str) searchPaths.append(String(str, end - str)); ++end; str = end; } else { searchPaths.append(String(str, -1)); break; } } loaded = true; } return searchPaths; } static bool resolveSymlink(const String& fileName, String& result) { String cygwinRoot = File::getDirname(File::getDirname(fileName)); result = fileName; bool success = false; for(;;) { File file; if(!file.open(result)) return success; const int len = 12 + MAX_PATH * 2 + 2; char buffer[len]; int i = file.read(buffer, len); if(i < 12 || strncmp(buffer, "!<symlink>", 12) != 0) return success; i &= ~1; wchar_t* wdest = (wchar_t*)(buffer + 12); wdest[(i - 12) >> 1] = 0; String dest; dest.format(i - 12, "%S", wdest); if(strncmp(dest.getData(), "/usr/bin/", 9) == 0) { result = cygwinRoot; result.append(dest.substr(4)); } else if(dest.getData()[0] == '/') { result = cygwinRoot; result.append(dest); } else { result = File::getDirname(result); result.append('/'); result.append(dest); } success = true; } return false; } static String find(const String& program) { String result = program; bool testExtensions = File::getExtension(program).isEmpty(); // check whether the given path is absolute if(program.getData()[0] == '/' || (program.getLength() > 2 && program.getData()[1] == ':')) { // absolute fileComplete(program, testExtensions, result); } else { // try each search path const List<String>& searchPaths = Executable::getPathEnv(); for(const List<String>::Node* i = searchPaths.getFirst(); i; i = i->getNext()) { String testPath = i->data; testPath.append('\\'); testPath.append(program); if(fileComplete(testPath, testExtensions, result)) break; } } return result; } }; String program, programPath; static Map<String, String> cachedProgramPaths; bool cachedProgramPath = false; if(command.isEmpty()) cachedProgramPath = true; else { program = command.getFirst()->data; const Map<String, String>::Node* i = cachedProgramPaths.find(program); if(i) { programPath = i->data; cachedProgramPath = true; } else programPath = Executable::find(program); } const List<String>::Node* i = command.getFirst(); String commandLine; if(i) { commandLine.append(i->data); for(i = i->getNext(); i; i = i->getNext()) { commandLine.append(' '); commandLine.append(i->data); } } commandLine.setCapacity(commandLine.getLength()); // enforce detach STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if(!CreateProcess(programPath.getData(), (char*)commandLine.getData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { if(!programPath.isEmpty()) { String resolvedSymlink; if(Executable::resolveSymlink(programPath, resolvedSymlink)) { programPath = resolvedSymlink; if(CreateProcess(programPath.getData(), (char*)commandLine.getData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) goto success; } } if(!cachedProgramPath) cachedProgramPaths.append(program, programPath); error = GetLastError(); return 0; } success: if(!cachedProgramPath) cachedProgramPaths.append(program, programPath); CloseHandle(pi.hThread); assert(pi.hProcess); hProcess = pi.hProcess; runningProcessHandles.append(pi.hProcess); return pi.dwProcessId; #endif } unsigned int Process::wait() { #ifdef _WIN32 if(hProcess == INVALID_HANDLE_VALUE) return 0; DWORD exitCode = 0; GetExitCodeProcess(hProcess, &exitCode); CloseHandle((HANDLE)hProcess); int index = runningProcessHandles.find(hProcess); assert(index >= 0); runningProcessHandles.remove(index); hProcess = INVALID_HANDLE_VALUE; return exitCode; #endif } unsigned int Process::waitOne() { #ifdef _WIN32 if(runningProcessHandles.isEmpty()) return 0; DWORD index = WaitForMultipleObjects(runningProcessHandles.getSize(), runningProcessHandles.getFirst(), FALSE, INFINITE); if(index == WAIT_FAILED) return 0; index -= WAIT_OBJECT_0; assert(index >= 0 && index < runningProcessHandles.getSize()); HANDLE handle = runningProcessHandles.getFirst()[index]; return GetProcessId(handle); #endif } unsigned int Process::getProcessorCount() { #ifdef _WIN32 SYSTEM_INFO si; GetSystemInfo(&si); return si.dwNumberOfProcessors; #elif defined(__linux__) return sysconf(_SC_NPROCESSORS_CONF); #else return 1; #endif } <commit_msg>Make Process::getProcessorCount compatible with cygwin<commit_after> #include <cassert> #ifdef _WIN32 #include <windows.h> #include <malloc.h> #else #include <unistd.h> #endif #include "Process.h" #ifdef _WIN32 #include "Array.h" #include "Map.h" #include "File.h" #endif #ifdef _WIN32 static Array<HANDLE> runningProcessHandles; #endif Process::Process() { #ifdef _WIN32 assert(sizeof(hProcess) >= sizeof(HANDLE)); hProcess = INVALID_HANDLE_VALUE; #endif } Process::~Process() { #ifdef _WIN32 if(hProcess != INVALID_HANDLE_VALUE) { CloseHandle((HANDLE)hProcess); int index = runningProcessHandles.find(hProcess); assert(index >= 0); runningProcessHandles.remove(index); } #endif } unsigned int Process::start(const List<String>& command) { #ifdef _WIN32 struct Executable { static bool Executable::fileComplete(const String& searchName, bool testExtensions, String& result) { if(File::exists(searchName)) { result = searchName; return true; } if(testExtensions) { String testPath = searchName; testPath.append(".exe"); if(File::exists(testPath)) { result = testPath; return true; } testPath.setLength(searchName.getLength()); testPath.append(".com"); if(File::exists(testPath)) { result = testPath; return true; } } return false; } static const List<String>& getPathEnv() { static List<String> searchPaths; static bool loaded = false; if(!loaded) { char* pathVar = (char*)alloca(32767); GetEnvironmentVariable("PATH", pathVar, 32767); for(const char* str = pathVar; *str;) { const char* end = strchr(str, ';'); if(end) { if(end > str) searchPaths.append(String(str, end - str)); ++end; str = end; } else { searchPaths.append(String(str, -1)); break; } } loaded = true; } return searchPaths; } static bool resolveSymlink(const String& fileName, String& result) { String cygwinRoot = File::getDirname(File::getDirname(fileName)); result = fileName; bool success = false; for(;;) { File file; if(!file.open(result)) return success; const int len = 12 + MAX_PATH * 2 + 2; char buffer[len]; int i = file.read(buffer, len); if(i < 12 || strncmp(buffer, "!<symlink>", 12) != 0) return success; i &= ~1; wchar_t* wdest = (wchar_t*)(buffer + 12); wdest[(i - 12) >> 1] = 0; String dest; dest.format(i - 12, "%S", wdest); if(strncmp(dest.getData(), "/usr/bin/", 9) == 0) { result = cygwinRoot; result.append(dest.substr(4)); } else if(dest.getData()[0] == '/') { result = cygwinRoot; result.append(dest); } else { result = File::getDirname(result); result.append('/'); result.append(dest); } success = true; } return false; } static String find(const String& program) { String result = program; bool testExtensions = File::getExtension(program).isEmpty(); // check whether the given path is absolute if(program.getData()[0] == '/' || (program.getLength() > 2 && program.getData()[1] == ':')) { // absolute fileComplete(program, testExtensions, result); } else { // try each search path const List<String>& searchPaths = Executable::getPathEnv(); for(const List<String>::Node* i = searchPaths.getFirst(); i; i = i->getNext()) { String testPath = i->data; testPath.append('\\'); testPath.append(program); if(fileComplete(testPath, testExtensions, result)) break; } } return result; } }; String program, programPath; static Map<String, String> cachedProgramPaths; bool cachedProgramPath = false; if(command.isEmpty()) cachedProgramPath = true; else { program = command.getFirst()->data; const Map<String, String>::Node* i = cachedProgramPaths.find(program); if(i) { programPath = i->data; cachedProgramPath = true; } else programPath = Executable::find(program); } const List<String>::Node* i = command.getFirst(); String commandLine; if(i) { commandLine.append(i->data); for(i = i->getNext(); i; i = i->getNext()) { commandLine.append(' '); commandLine.append(i->data); } } commandLine.setCapacity(commandLine.getLength()); // enforce detach STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); ZeroMemory(&pi, sizeof(pi)); if(!CreateProcess(programPath.getData(), (char*)commandLine.getData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) { if(!programPath.isEmpty()) { String resolvedSymlink; if(Executable::resolveSymlink(programPath, resolvedSymlink)) { programPath = resolvedSymlink; if(CreateProcess(programPath.getData(), (char*)commandLine.getData(), NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi)) goto success; } } if(!cachedProgramPath) cachedProgramPaths.append(program, programPath); error = GetLastError(); return 0; } success: if(!cachedProgramPath) cachedProgramPaths.append(program, programPath); CloseHandle(pi.hThread); assert(pi.hProcess); hProcess = pi.hProcess; runningProcessHandles.append(pi.hProcess); return pi.dwProcessId; #endif } unsigned int Process::wait() { #ifdef _WIN32 if(hProcess == INVALID_HANDLE_VALUE) return 0; DWORD exitCode = 0; GetExitCodeProcess(hProcess, &exitCode); CloseHandle((HANDLE)hProcess); int index = runningProcessHandles.find(hProcess); assert(index >= 0); runningProcessHandles.remove(index); hProcess = INVALID_HANDLE_VALUE; return exitCode; #endif } unsigned int Process::waitOne() { #ifdef _WIN32 if(runningProcessHandles.isEmpty()) return 0; DWORD index = WaitForMultipleObjects(runningProcessHandles.getSize(), runningProcessHandles.getFirst(), FALSE, INFINITE); if(index == WAIT_FAILED) return 0; index -= WAIT_OBJECT_0; assert(index >= 0 && index < runningProcessHandles.getSize()); HANDLE handle = runningProcessHandles.getFirst()[index]; return GetProcessId(handle); #endif } unsigned int Process::getProcessorCount() { #if defined(_WIN32) SYSTEM_INFO si; GetSystemInfo(&si); return si.dwNumberOfProcessors; //#elif defined(__linux) #else return sysconf(_SC_NPROCESSORS_CONF); //#else //return 1; #endif } <|endoftext|>
<commit_before>#include <sstream> #include "sprite_sheet.h" #include "game_window.h" SpriteSheet::SpriteSheet( std::string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay, GameWindow & owner) : owner(owner){ std::stringstream message; message << "Creating SpriteSheet " << this << " with path " << pPath << " owned by " << &owner; Logger::getInstance()->writeInformation(message.str()); this->path = pPath; texture = nullptr; initialized = false; this->pixel_ref_x = pixelRefX; this->pixel_ref_y = pixelRefY; this->alto_sprite = altoSprite; this->ancho_sprite = anchoSprite; this->total_sprites = cantSprites; this->fps = fps; // segundos this->delay = delay; // segundos this->currentFrame = 0; this->counter = 0; this->tick = 0; } SpriteSheet::~SpriteSheet(){ std::stringstream message; message << "Killing SpriteSheet " << this << " with path " << path << " owned by " << &owner; Logger::getInstance()->writeInformation(message.str()); clear(); } void SpriteSheet::clear(){ if(texture){ SDL_DestroyTexture( texture ); texture = nullptr; } } SDL_Texture* SpriteSheet::getLoadedTexture( SDL_Renderer* renderer ){ if( !initialized ) initialized = loadTexture( renderer ); return texture; } bool SpriteSheet::loadTexture( SDL_Renderer* renderer ) { // Libera la carga anterior, para poder recargar clear(); // Carga la imagen desde el path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); // Si no se cargo la imagen, cargo default if(!loadedSurface) { texture = nullptr; Logger::getInstance()->writeError( "No se puede cargar la imagen " + path + "! - " + IMG_GetError() ); loadedSurface = IMG_Load( ENTIDAD_DEFAULT_IMAGEN ); this->pixel_ref_x = ENTIDAD_DEFAULT_PIXEL_REF_X; this->pixel_ref_y = ENTIDAD_DEFAULT_PIXEL_REF_Y; this->alto_sprite = ENTIDAD_DEFAULT_ALTO_SPRITE; this->ancho_sprite = ENTIDAD_DEFAULT_ANCHO_SPRITE; this->total_sprites = ENTIDAD_DEFAULT_CANTIDAD_SPRITES; this->fps = ENTIDAD_DEFAULT_FPS; // segundos this->delay = ENTIDAD_DEFAULT_DELAY; // segundos this->currentFrame = 0; this->counter = 0; this->tick = 0; } // La default siempre deberia poder cargarla if(!loadedSurface) { texture = nullptr; Logger::getInstance()->writeError( "No se puede cargar la imagen Default ! " ); } else { // Textura de la superficie texture = SDL_CreateTextureFromSurface( renderer, loadedSurface ); // Libera la superficie SDL_FreeSurface( loadedSurface ); } return texture; } void SpriteSheet::render(Entity & entity, int frame, SDL_Renderer* renderer){ auto direction = entity.getDirection(); currentFrame = counter % total_sprites; //Aca se debe usar el frame actual desde el estado de la entidad // Conversion isometrica auto pos = entity.getPosition() - owner.getFocus(); auto x = pos.x; auto y = pos.y; int screenX = ((x - y) * TILE_WIDTH_DEFAULT / 2) + (owner.ancho_pantalla) / 2; int screenY = ((x + y) * TILE_HEIGHT_DEFAULT / 2) + (owner.alto_pantalla - TILE_HEIGHT_DEFAULT) / 2; // Ubicacion donde dibujar SDL_Rect renderQuad = { screenX - pixel_ref_x , screenY - pixel_ref_y, ancho_sprite, alto_sprite }; // Parte de la imagen a levantar SDL_Rect clip = { direction * ancho_sprite, currentFrame * alto_sprite, ancho_sprite, alto_sprite }; // Dibujado // TODO: Verificar si renderQuad realmente se pisa con la pantalla SDL_RenderCopy( renderer, getLoadedTexture( renderer ), &clip, &renderQuad ); } void SpriteSheet::update(){ // Todas las entidades del mismo tipo tienen el mismo fps y delay. auto currentTick = GameTimer::getCurrent(); auto diffTime = currentTick - this->tick; if ( ( (currentFrame != 0) || (diffTime >= (this->delay * 1000)) ) ) { if ( (this->fps == 0) || (diffTime >= (1000 / this->fps ) ) ) { // Actualizo el tick del sprite sheet this->tick = currentTick; counter++; } } } <commit_msg>validacion canidad de sprites mayor a cero<commit_after>#include <sstream> #include "sprite_sheet.h" #include "game_window.h" SpriteSheet::SpriteSheet( std::string pPath, int pixelRefX, int pixelRefY, int altoSprite, int anchoSprite, int cantSprites, double fps, double delay, GameWindow & owner) : owner(owner){ std::stringstream message; message << "Creating SpriteSheet " << this << " with path " << pPath << " owned by " << &owner; Logger::getInstance()->writeInformation(message.str()); this->path = pPath; texture = nullptr; initialized = false; this->pixel_ref_x = pixelRefX; this->pixel_ref_y = pixelRefY; this->alto_sprite = altoSprite; this->ancho_sprite = anchoSprite; this->total_sprites = cantSprites; this->fps = fps; // segundos this->delay = delay; // segundos this->currentFrame = 0; this->counter = 0; this->tick = 0; } SpriteSheet::~SpriteSheet(){ std::stringstream message; message << "Killing SpriteSheet " << this << " with path " << path << " owned by " << &owner; Logger::getInstance()->writeInformation(message.str()); clear(); } void SpriteSheet::clear(){ if(texture){ SDL_DestroyTexture( texture ); texture = nullptr; } } SDL_Texture* SpriteSheet::getLoadedTexture( SDL_Renderer* renderer ){ if( !initialized ) initialized = loadTexture( renderer ); return texture; } bool SpriteSheet::loadTexture( SDL_Renderer* renderer ) { // Libera la carga anterior, para poder recargar clear(); // Carga la imagen desde el path SDL_Surface* loadedSurface = IMG_Load( path.c_str() ); // Si no se cargo la imagen, cargo default if(!loadedSurface) { texture = nullptr; Logger::getInstance()->writeError( "No se puede cargar la imagen " + path + "! - " + IMG_GetError() ); loadedSurface = IMG_Load( ENTIDAD_DEFAULT_IMAGEN ); this->pixel_ref_x = ENTIDAD_DEFAULT_PIXEL_REF_X; this->pixel_ref_y = ENTIDAD_DEFAULT_PIXEL_REF_Y; this->alto_sprite = ENTIDAD_DEFAULT_ALTO_SPRITE; this->ancho_sprite = ENTIDAD_DEFAULT_ANCHO_SPRITE; this->total_sprites = ENTIDAD_DEFAULT_CANTIDAD_SPRITES; this->fps = ENTIDAD_DEFAULT_FPS; // segundos this->delay = ENTIDAD_DEFAULT_DELAY; // segundos this->currentFrame = 0; this->counter = 0; this->tick = 0; } // La default siempre deberia poder cargarla if(!loadedSurface) { texture = nullptr; Logger::getInstance()->writeError( "No se puede cargar la imagen Default ! " ); } else { // Textura de la superficie texture = SDL_CreateTextureFromSurface( renderer, loadedSurface ); // Libera la superficie SDL_FreeSurface( loadedSurface ); } return texture; } void SpriteSheet::render(Entity & entity, int frame, SDL_Renderer* renderer){ auto direction = entity.getDirection(); if (total_sprites == 0){ currentFrame = 0; Logger::getInstance()->writeWarning(" La cantidad de sprites debe ser mayor a cero " + path); }else currentFrame = counter % total_sprites; // Conversion isometrica auto pos = entity.getPosition() - owner.getFocus(); auto x = pos.x; auto y = pos.y; int screenX = ((x - y) * TILE_WIDTH_DEFAULT / 2) + (owner.ancho_pantalla) / 2; int screenY = ((x + y) * TILE_HEIGHT_DEFAULT / 2) + (owner.alto_pantalla - TILE_HEIGHT_DEFAULT) / 2; // Ubicacion donde dibujar SDL_Rect renderQuad = { screenX - pixel_ref_x , screenY - pixel_ref_y, ancho_sprite, alto_sprite }; // Parte de la imagen a levantar SDL_Rect clip = { direction * ancho_sprite, currentFrame * alto_sprite, ancho_sprite, alto_sprite }; // Dibujado // TODO: Verificar si renderQuad realmente se pisa con la pantalla SDL_RenderCopy( renderer, getLoadedTexture( renderer ), &clip, &renderQuad ); } void SpriteSheet::update(){ // Todas las entidades del mismo tipo tienen el mismo fps y delay. auto currentTick = GameTimer::getCurrent(); auto diffTime = currentTick - this->tick; if ( ( (currentFrame != 0) || (diffTime >= (this->delay * 1000)) ) ) { if ( (this->fps == 0) || (diffTime >= (1000 / this->fps ) ) ) { // Actualizo el tick del sprite sheet this->tick = currentTick; counter++; } } } <|endoftext|>
<commit_before><commit_msg>Formatting doc<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <cstring> #include <openssl/md5.h> #include <openssl/sha.h> #include "args.hh" #include "hash.hh" #include "archive.hh" #include "split.hh" #include "util.hh" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace nix { static size_t regularHashSize(HashType type) { switch (type) { case htMD5: return md5HashSize; case htSHA1: return sha1HashSize; case htSHA256: return sha256HashSize; case htSHA512: return sha512HashSize; } abort(); } std::set<std::string> hashTypes = { "md5", "sha1", "sha256", "sha512" }; Hash::Hash(HashType type) : type(type) { hashSize = regularHashSize(type); assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } bool Hash::operator == (const Hash & h2) const { if (hashSize != h2.hashSize) return false; for (unsigned int i = 0; i < hashSize; i++) if (hash[i] != h2.hash[i]) return false; return true; } bool Hash::operator != (const Hash & h2) const { return !(*this == h2); } bool Hash::operator < (const Hash & h) const { if (hashSize < h.hashSize) return true; if (hashSize > h.hashSize) return false; for (unsigned int i = 0; i < hashSize; i++) { if (hash[i] < h.hash[i]) return true; if (hash[i] > h.hash[i]) return false; } return false; } const string base16Chars = "0123456789abcdef"; static string printHash16(const Hash & hash) { char buf[hash.hashSize * 2]; for (unsigned int i = 0; i < hash.hashSize; i++) { buf[i * 2] = base16Chars[hash.hash[i] >> 4]; buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f]; } return string(buf, hash.hashSize * 2); } // omitted: E O U T const string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz"; static string printHash32(const Hash & hash) { assert(hash.hashSize); size_t len = hash.base32Len(); assert(len); string s; s.reserve(len); for (int n = (int) len - 1; n >= 0; n--) { unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; unsigned char c = (hash.hash[i] >> j) | (i >= hash.hashSize - 1 ? 0 : hash.hash[i + 1] << (8 - j)); s.push_back(base32Chars[c & 0x1f]); } return s; } string printHash16or32(const Hash & hash) { assert(hash.type); return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); } std::string Hash::to_string(Base base, bool includeType) const { std::string s; if (base == SRI || includeType) { s += printHashType(type); s += base == SRI ? '-' : ':'; } switch (base) { case Base16: s += printHash16(*this); break; case Base32: s += printHash32(*this); break; case Base64: case SRI: s += base64Encode(std::string((const char *) hash, hashSize)); break; } return s; } Hash Hash::dummy(htSHA256); Hash Hash::parseSRI(std::string_view original) { auto rest = original; // Parse the has type before the separater, if there was one. auto hashRaw = splitPrefixTo(rest, '-'); if (!hashRaw) throw BadHash("hash '%s' is not SRI", original); HashType parsedType = parseHashType(*hashRaw); return Hash(rest, parsedType, true); } // Mutates the string to eliminate the prefixes when found static std::pair<std::optional<HashType>, bool> getParsedTypeAndSRI(std::string_view & rest) { bool isSRI = false; // Parse the has type before the separater, if there was one. std::optional<HashType> optParsedType; { auto hashRaw = splitPrefixTo(rest, ':'); if (!hashRaw) { hashRaw = splitPrefixTo(rest, '-'); if (hashRaw) isSRI = true; } if (hashRaw) optParsedType = parseHashType(*hashRaw); } return {optParsedType, isSRI}; } Hash Hash::parseAnyPrefixed(std::string_view original) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType) throw BadHash("hash '%s' does not include a type", rest); return Hash(rest, *optParsedType, isSRI); } Hash Hash::parseAny(std::string_view original, std::optional<HashType> optType) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType && !optType) throw BadHash("hash '%s' does not include a type, nor is the type otherwise known from context.", rest); else if (optParsedType && optType && *optParsedType != *optType) throw BadHash("hash '%s' should have type '%s'", original, printHashType(*optType)); HashType hashType = optParsedType ? *optParsedType : *optType; return Hash(rest, hashType, isSRI); } Hash Hash::parseNonSRIUnprefixed(std::string_view s, HashType type) { return Hash(s, type, false); } Hash::Hash(std::string_view rest, HashType type, bool isSRI) : Hash(type) { if (!isSRI && rest.size() == base16Len()) { auto parseHexDigit = [&](char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; throw BadHash("invalid base-16 hash '%s'", rest); }; for (unsigned int i = 0; i < hashSize; i++) { hash[i] = parseHexDigit(rest[i * 2]) << 4 | parseHexDigit(rest[i * 2 + 1]); } } else if (!isSRI && rest.size() == base32Len()) { for (unsigned int n = 0; n < rest.size(); ++n) { char c = rest[rest.size() - n - 1]; unsigned char digit; for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ if (base32Chars[digit] == c) break; if (digit >= 32) throw BadHash("invalid base-32 hash '%s'", rest); unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; hash[i] |= digit << j; if (i < hashSize - 1) { hash[i + 1] |= digit >> (8 - j); } else { if (digit >> (8 - j)) throw BadHash("invalid base-32 hash '%s'", rest); } } } else if (isSRI || rest.size() == base64Len()) { auto d = base64Decode(rest); if (d.size() != hashSize) throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", rest); assert(hashSize); memcpy(hash, d.data(), hashSize); } else throw BadHash("hash '%s' has wrong length for hash type '%s'", rest, printHashType(this->type)); } Hash newHashAllowEmpty(std::string hashStr, std::optional<HashType> ht) { if (hashStr.empty()) { if (!ht) throw BadHash("empty hash requires explicit hash type"); Hash h(*ht); warn("found empty hash, assuming '%s'", h.to_string(SRI, true)); return h; } else return Hash::parseAny(hashStr, ht); } union Ctx { MD5_CTX md5; SHA_CTX sha1; SHA256_CTX sha256; SHA512_CTX sha512; }; static void start(HashType ht, Ctx & ctx) { if (ht == htMD5) MD5_Init(&ctx.md5); else if (ht == htSHA1) SHA1_Init(&ctx.sha1); else if (ht == htSHA256) SHA256_Init(&ctx.sha256); else if (ht == htSHA512) SHA512_Init(&ctx.sha512); } static void update(HashType ht, Ctx & ctx, const unsigned char * bytes, size_t len) { if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len); else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len); else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len); else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len); } static void finish(HashType ht, Ctx & ctx, unsigned char * hash) { if (ht == htMD5) MD5_Final(hash, &ctx.md5); else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1); else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256); else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512); } Hash hashString(HashType ht, std::string_view s) { Ctx ctx; Hash hash(ht); start(ht, ctx); update(ht, ctx, (const unsigned char *) s.data(), s.length()); finish(ht, ctx, hash.hash); return hash; } Hash hashFile(HashType ht, const Path & path) { HashSink sink(ht); readFile(path, sink); return sink.finish().first; } HashSink::HashSink(HashType ht) : ht(ht) { ctx = new Ctx; bytes = 0; start(ht, *ctx); } HashSink::~HashSink() { bufPos = 0; delete ctx; } void HashSink::write(const unsigned char * data, size_t len) { bytes += len; update(ht, *ctx, data, len); } HashResult HashSink::finish() { flush(); Hash hash(ht); nix::finish(ht, *ctx, hash.hash); return HashResult(hash, bytes); } HashResult HashSink::currentHash() { flush(); Ctx ctx2 = *ctx; Hash hash(ht); nix::finish(ht, ctx2, hash.hash); return HashResult(hash, bytes); } HashResult hashPath( HashType ht, const Path & path, PathFilter & filter) { HashSink sink(ht); dumpPath(path, sink, filter); return sink.finish(); } Hash compressHash(const Hash & hash, unsigned int newSize) { Hash h(hash.type); h.hashSize = newSize; for (unsigned int i = 0; i < hash.hashSize; ++i) h.hash[i % newSize] ^= hash.hash[i]; return h; } std::optional<HashType> parseHashTypeOpt(std::string_view s) { if (s == "md5") return htMD5; else if (s == "sha1") return htSHA1; else if (s == "sha256") return htSHA256; else if (s == "sha512") return htSHA512; else return std::optional<HashType> {}; } HashType parseHashType(std::string_view s) { auto opt_h = parseHashTypeOpt(s); if (opt_h) return *opt_h; else throw UsageError("unknown hash algorithm '%1%'", s); } string printHashType(HashType ht) { switch (ht) { case htMD5: return "md5"; case htSHA1: return "sha1"; case htSHA256: return "sha256"; case htSHA512: return "sha512"; default: // illegal hash type enum value internally, as opposed to external input // which should be validated with nice error message. assert(false); } } } <commit_msg>Consistency<commit_after>#include <iostream> #include <cstring> #include <openssl/md5.h> #include <openssl/sha.h> #include "args.hh" #include "hash.hh" #include "archive.hh" #include "split.hh" #include "util.hh" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> namespace nix { static size_t regularHashSize(HashType type) { switch (type) { case htMD5: return md5HashSize; case htSHA1: return sha1HashSize; case htSHA256: return sha256HashSize; case htSHA512: return sha512HashSize; } abort(); } std::set<std::string> hashTypes = { "md5", "sha1", "sha256", "sha512" }; Hash::Hash(HashType type) : type(type) { hashSize = regularHashSize(type); assert(hashSize <= maxHashSize); memset(hash, 0, maxHashSize); } bool Hash::operator == (const Hash & h2) const { if (hashSize != h2.hashSize) return false; for (unsigned int i = 0; i < hashSize; i++) if (hash[i] != h2.hash[i]) return false; return true; } bool Hash::operator != (const Hash & h2) const { return !(*this == h2); } bool Hash::operator < (const Hash & h) const { if (hashSize < h.hashSize) return true; if (hashSize > h.hashSize) return false; for (unsigned int i = 0; i < hashSize; i++) { if (hash[i] < h.hash[i]) return true; if (hash[i] > h.hash[i]) return false; } return false; } const string base16Chars = "0123456789abcdef"; static string printHash16(const Hash & hash) { char buf[hash.hashSize * 2]; for (unsigned int i = 0; i < hash.hashSize; i++) { buf[i * 2] = base16Chars[hash.hash[i] >> 4]; buf[i * 2 + 1] = base16Chars[hash.hash[i] & 0x0f]; } return string(buf, hash.hashSize * 2); } // omitted: E O U T const string base32Chars = "0123456789abcdfghijklmnpqrsvwxyz"; static string printHash32(const Hash & hash) { assert(hash.hashSize); size_t len = hash.base32Len(); assert(len); string s; s.reserve(len); for (int n = (int) len - 1; n >= 0; n--) { unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; unsigned char c = (hash.hash[i] >> j) | (i >= hash.hashSize - 1 ? 0 : hash.hash[i + 1] << (8 - j)); s.push_back(base32Chars[c & 0x1f]); } return s; } string printHash16or32(const Hash & hash) { assert(hash.type); return hash.to_string(hash.type == htMD5 ? Base16 : Base32, false); } std::string Hash::to_string(Base base, bool includeType) const { std::string s; if (base == SRI || includeType) { s += printHashType(type); s += base == SRI ? '-' : ':'; } switch (base) { case Base16: s += printHash16(*this); break; case Base32: s += printHash32(*this); break; case Base64: case SRI: s += base64Encode(std::string((const char *) hash, hashSize)); break; } return s; } Hash Hash::dummy(htSHA256); Hash Hash::parseSRI(std::string_view original) { auto rest = original; // Parse the has type before the separater, if there was one. auto hashRaw = splitPrefixTo(rest, '-'); if (!hashRaw) throw BadHash("hash '%s' is not SRI", original); HashType parsedType = parseHashType(*hashRaw); return Hash(rest, parsedType, true); } // Mutates the string to eliminate the prefixes when found static std::pair<std::optional<HashType>, bool> getParsedTypeAndSRI(std::string_view & rest) { bool isSRI = false; // Parse the has type before the separater, if there was one. std::optional<HashType> optParsedType; { auto hashRaw = splitPrefixTo(rest, ':'); if (!hashRaw) { hashRaw = splitPrefixTo(rest, '-'); if (hashRaw) isSRI = true; } if (hashRaw) optParsedType = parseHashType(*hashRaw); } return {optParsedType, isSRI}; } Hash Hash::parseAnyPrefixed(std::string_view original) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType) throw BadHash("hash '%s' does not include a type", rest); return Hash(rest, *optParsedType, isSRI); } Hash Hash::parseAny(std::string_view original, std::optional<HashType> optType) { auto rest = original; auto [optParsedType, isSRI] = getParsedTypeAndSRI(rest); // Either the string or user must provide the type, if they both do they // must agree. if (!optParsedType && !optType) throw BadHash("hash '%s' does not include a type, nor is the type otherwise known from context", rest); else if (optParsedType && optType && *optParsedType != *optType) throw BadHash("hash '%s' should have type '%s'", original, printHashType(*optType)); HashType hashType = optParsedType ? *optParsedType : *optType; return Hash(rest, hashType, isSRI); } Hash Hash::parseNonSRIUnprefixed(std::string_view s, HashType type) { return Hash(s, type, false); } Hash::Hash(std::string_view rest, HashType type, bool isSRI) : Hash(type) { if (!isSRI && rest.size() == base16Len()) { auto parseHexDigit = [&](char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'A' && c <= 'F') return c - 'A' + 10; if (c >= 'a' && c <= 'f') return c - 'a' + 10; throw BadHash("invalid base-16 hash '%s'", rest); }; for (unsigned int i = 0; i < hashSize; i++) { hash[i] = parseHexDigit(rest[i * 2]) << 4 | parseHexDigit(rest[i * 2 + 1]); } } else if (!isSRI && rest.size() == base32Len()) { for (unsigned int n = 0; n < rest.size(); ++n) { char c = rest[rest.size() - n - 1]; unsigned char digit; for (digit = 0; digit < base32Chars.size(); ++digit) /* !!! slow */ if (base32Chars[digit] == c) break; if (digit >= 32) throw BadHash("invalid base-32 hash '%s'", rest); unsigned int b = n * 5; unsigned int i = b / 8; unsigned int j = b % 8; hash[i] |= digit << j; if (i < hashSize - 1) { hash[i + 1] |= digit >> (8 - j); } else { if (digit >> (8 - j)) throw BadHash("invalid base-32 hash '%s'", rest); } } } else if (isSRI || rest.size() == base64Len()) { auto d = base64Decode(rest); if (d.size() != hashSize) throw BadHash("invalid %s hash '%s'", isSRI ? "SRI" : "base-64", rest); assert(hashSize); memcpy(hash, d.data(), hashSize); } else throw BadHash("hash '%s' has wrong length for hash type '%s'", rest, printHashType(this->type)); } Hash newHashAllowEmpty(std::string hashStr, std::optional<HashType> ht) { if (hashStr.empty()) { if (!ht) throw BadHash("empty hash requires explicit hash type"); Hash h(*ht); warn("found empty hash, assuming '%s'", h.to_string(SRI, true)); return h; } else return Hash::parseAny(hashStr, ht); } union Ctx { MD5_CTX md5; SHA_CTX sha1; SHA256_CTX sha256; SHA512_CTX sha512; }; static void start(HashType ht, Ctx & ctx) { if (ht == htMD5) MD5_Init(&ctx.md5); else if (ht == htSHA1) SHA1_Init(&ctx.sha1); else if (ht == htSHA256) SHA256_Init(&ctx.sha256); else if (ht == htSHA512) SHA512_Init(&ctx.sha512); } static void update(HashType ht, Ctx & ctx, const unsigned char * bytes, size_t len) { if (ht == htMD5) MD5_Update(&ctx.md5, bytes, len); else if (ht == htSHA1) SHA1_Update(&ctx.sha1, bytes, len); else if (ht == htSHA256) SHA256_Update(&ctx.sha256, bytes, len); else if (ht == htSHA512) SHA512_Update(&ctx.sha512, bytes, len); } static void finish(HashType ht, Ctx & ctx, unsigned char * hash) { if (ht == htMD5) MD5_Final(hash, &ctx.md5); else if (ht == htSHA1) SHA1_Final(hash, &ctx.sha1); else if (ht == htSHA256) SHA256_Final(hash, &ctx.sha256); else if (ht == htSHA512) SHA512_Final(hash, &ctx.sha512); } Hash hashString(HashType ht, std::string_view s) { Ctx ctx; Hash hash(ht); start(ht, ctx); update(ht, ctx, (const unsigned char *) s.data(), s.length()); finish(ht, ctx, hash.hash); return hash; } Hash hashFile(HashType ht, const Path & path) { HashSink sink(ht); readFile(path, sink); return sink.finish().first; } HashSink::HashSink(HashType ht) : ht(ht) { ctx = new Ctx; bytes = 0; start(ht, *ctx); } HashSink::~HashSink() { bufPos = 0; delete ctx; } void HashSink::write(const unsigned char * data, size_t len) { bytes += len; update(ht, *ctx, data, len); } HashResult HashSink::finish() { flush(); Hash hash(ht); nix::finish(ht, *ctx, hash.hash); return HashResult(hash, bytes); } HashResult HashSink::currentHash() { flush(); Ctx ctx2 = *ctx; Hash hash(ht); nix::finish(ht, ctx2, hash.hash); return HashResult(hash, bytes); } HashResult hashPath( HashType ht, const Path & path, PathFilter & filter) { HashSink sink(ht); dumpPath(path, sink, filter); return sink.finish(); } Hash compressHash(const Hash & hash, unsigned int newSize) { Hash h(hash.type); h.hashSize = newSize; for (unsigned int i = 0; i < hash.hashSize; ++i) h.hash[i % newSize] ^= hash.hash[i]; return h; } std::optional<HashType> parseHashTypeOpt(std::string_view s) { if (s == "md5") return htMD5; else if (s == "sha1") return htSHA1; else if (s == "sha256") return htSHA256; else if (s == "sha512") return htSHA512; else return std::optional<HashType> {}; } HashType parseHashType(std::string_view s) { auto opt_h = parseHashTypeOpt(s); if (opt_h) return *opt_h; else throw UsageError("unknown hash algorithm '%1%'", s); } string printHashType(HashType ht) { switch (ht) { case htMD5: return "md5"; case htSHA1: return "sha1"; case htSHA256: return "sha256"; case htSHA512: return "sha512"; default: // illegal hash type enum value internally, as opposed to external input // which should be validated with nice error message. assert(false); } } } <|endoftext|>
<commit_before>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <targetPAL.h> #include <corlib_native.h> #include "sys_dev_gpio_native_target.h" #include "nf_rt_events_native.h" #include "sys_dev_gpio_native.h" // just make it shorter and readable typedef Library_sys_dev_gpio_native_System_Device_Gpio_PinValue PinValue; // declared here as external // the implementation will be moved here when Windows.Devices.Gpio is removed extern void Gpio_Interupt_ISR(GPIO_PIN pinNumber, bool pinState, void *pArg); HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); CLR_RT_TypeDef_Index gpioPinTypeDef; CLR_RT_HeapBlock *hbObj; bool pinValue; CLR_RT_HeapBlock &top = stack.PushValue(); CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } NANOCLR_CHECK_HRESULT(Read(pThis, pinValue)); // find <GpioPin> type definition, don't bother checking the result as it exists for sure g_CLR_RT_TypeSystem.FindTypeDef("GpioPin", "System.Device.Gpio", gpioPinTypeDef); // create an instance of <GpioPin> NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, gpioPinTypeDef)); // dereference the object in order to reach its fields hbObj = top.Dereference(); hbObj[Library_sys_dev_gpio_native_System_Device_Gpio_PinValue::FIELD___value].NumericByRef().u1 = pinValue; NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[FIELD___pinMode].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if (driveMode >= GpioPinDriveMode_Output) { CPU_GPIO_TogglePinState(pinNumber); // fire event, only if there are callbacks registered if (pThis[FIELD___callbacks].Dereference() != NULL) { PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)CPU_GPIO_GetPinState(pinNumber)); } } } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // set pin to input to save power // clear interrupts // releases the pin GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, 0); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin:: NativeIsPinModeSupported___BOOLEAN__SystemDeviceGpioPinMode(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; // Return value to the managed application stack.SetResult_Boolean(CPU_GPIO_DriveModeSupported(pinNumber, driveMode)); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetPinMode___VOID__SystemDeviceGpioPinMode( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; NANOCLR_CHECK_HRESULT(SetPinMode(pThis, driveMode)); // protect this from GC so that the callback is where it's supposed to CLR_RT_ProtectFromGC gc(*pThis); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_UINT64 debounceTimeoutMilsec; CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(pThis[FIELD___debounceTimeout], debounceTimeoutMilsec)); // developer note: // the following call will FAIL if the pin hasn't been previously setup as input // that's OK because the debounce timeout will be eventually set when the pin is configured CPU_GPIO_SetPinDebounce(pinNumber, debounceTimeoutMilsec); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); GpioPinValue state; CLR_RT_HeapBlock *pinValue; CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get PinValue object from parameter pinValue = stack.Arg1().Dereference(); // access value field inside PinValue state = (GpioPinValue)pinValue[PinValue::FIELD___value].NumericByRef().u1; NANOCLR_CHECK_HRESULT(Write(pThis, state)); NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get pin number and take the port and pad references from that one int16_t pinNumber = pThis[FIELD___pinNumber].NumericByRefConst().s4; // get alternate function argument int32_t alternateFunction = stack.Arg1().NumericByRef().s4; CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, alternateFunction); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { GPIO_PIN pinNumber = (GPIO_PIN)stack.Arg1().NumericByRef().s4; // Return value to the managed application stack.SetResult_Boolean(CPU_GPIO_ReservePin(pinNumber, true)); } NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::ExtractDebounceTimeSpanValue( CLR_RT_HeapBlock &timeSpanValue, CLR_UINT64 &value) { NANOCLR_HEADER(); { // debounceTimeout field its a TimeSpan, which is a primitive type stored as an heap block, therefore needs to // be accessed indirectly CLR_INT64 *debounceValue = Library_corlib_native_System_TimeSpan::GetValuePtr(timeSpanValue); FAULT_ON_NULL(debounceValue); value = *(CLR_UINT64 *)debounceValue / TIME_CONVERSION__TO_MILLISECONDS; } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::SetPinMode( CLR_RT_HeapBlock *gpioPin, GpioPinDriveMode pinMode) { NANOCLR_HEADER(); bool validPin; CLR_UINT64 debounceTimeoutMilsec; bool callbacksRegistered = false; GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; if (pinMode >= (int)GpioPinDriveMode_Output) { validPin = CPU_GPIO_EnableOutputPin(pinNumber, GpioPinValue_Low, pinMode); } else { NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(gpioPin[FIELD___debounceTimeout], debounceTimeoutMilsec)); // flag to determine if there are any callbacks registered in managed code // this is use to determine if there is any need to setup and process INT handler callbacksRegistered = (gpioPin[FIELD___callbacks].Dereference() != NULL); validPin = CPU_GPIO_EnableInputPin( pinNumber, debounceTimeoutMilsec, callbacksRegistered ? Gpio_Interupt_ISR : NULL, NULL, GPIO_INT_EDGE_BOTH, pinMode); } if (validPin) { // all good, store pin mode in managed field gpioPin[FIELD___pinMode].NumericByRef().s4 = pinMode; } else { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Write(CLR_RT_HeapBlock *gpioPin, GpioPinValue pinValue) { GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)gpioPin[FIELD___pinMode].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode >= GpioPinDriveMode_Output)) { CPU_GPIO_SetPinState(pinNumber, pinValue); // fire event if there are callbacks registered if (gpioPin[FIELD___callbacks].Dereference() != NULL) { PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)pinValue); } } else { return CLR_E_INVALID_PARAMETER; } return S_OK; } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read(CLR_RT_HeapBlock *gpioPin, bool &pinValue) { GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; pinValue = CPU_GPIO_GetPinState(pinNumber); return S_OK; } <commit_msg>Fix wrong type in GpioPin.Read()<commit_after>// // Copyright (c) .NET Foundation and Contributors // Portions Copyright (c) Microsoft Corporation. All rights reserved. // See LICENSE file in the project root for full license information. // #include <targetPAL.h> #include <corlib_native.h> #include "sys_dev_gpio_native_target.h" #include "nf_rt_events_native.h" #include "sys_dev_gpio_native.h" // just make it shorter and readable typedef Library_sys_dev_gpio_native_System_Device_Gpio_PinValue PinValue; // declared here as external // the implementation will be moved here when Windows.Devices.Gpio is removed extern void Gpio_Interupt_ISR(GPIO_PIN pinNumber, bool pinState, void *pArg); HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read___SystemDeviceGpioPinValue( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); CLR_RT_TypeDef_Index pinValueTypeDef; CLR_RT_HeapBlock *hbObj; bool pinValue; CLR_RT_HeapBlock &top = stack.PushValue(); CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } NANOCLR_CHECK_HRESULT(Read(pThis, pinValue)); // find <GpioPin> type definition, don't bother checking the result as it exists for sure g_CLR_RT_TypeSystem.FindTypeDef("PinValue", "System.Device.Gpio", pinValueTypeDef); // create an instance of <GpioPin> NANOCLR_CHECK_HRESULT(g_CLR_RT_ExecutionEngine.NewObjectFromIndex(top, pinValueTypeDef)); // dereference the object in order to reach its fields hbObj = top.Dereference(); hbObj[Library_sys_dev_gpio_native_System_Device_Gpio_PinValue::FIELD___value].NumericByRef().u1 = pinValue; NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Toggle___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)pThis[FIELD___pinMode].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if (driveMode >= GpioPinDriveMode_Output) { CPU_GPIO_TogglePinState(pinNumber); // fire event, only if there are callbacks registered if (pThis[FIELD___callbacks].Dereference() != NULL) { PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)CPU_GPIO_GetPinState(pinNumber)); } } } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::DisposeNative___VOID(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // set pin to input to save power // clear interrupts // releases the pin GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, 0); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin:: NativeIsPinModeSupported___BOOLEAN__SystemDeviceGpioPinMode(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; // Return value to the managed application stack.SetResult_Boolean(CPU_GPIO_DriveModeSupported(pinNumber, driveMode)); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetPinMode___VOID__SystemDeviceGpioPinMode( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } GpioPinDriveMode driveMode = (GpioPinDriveMode)stack.Arg1().NumericByRef().s4; NANOCLR_CHECK_HRESULT(SetPinMode(pThis, driveMode)); // protect this from GC so that the callback is where it's supposed to CLR_RT_ProtectFromGC gc(*pThis); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetDebounceTimeout___VOID( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_UINT64 debounceTimeoutMilsec; CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); GPIO_PIN pinNumber = (GPIO_PIN)pThis[FIELD___pinNumber].NumericByRefConst().s4; NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(pThis[FIELD___debounceTimeout], debounceTimeoutMilsec)); // developer note: // the following call will FAIL if the pin hasn't been previously setup as input // that's OK because the debounce timeout will be eventually set when the pin is configured CPU_GPIO_SetPinDebounce(pinNumber, debounceTimeoutMilsec); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::WriteNative___VOID__SystemDeviceGpioPinValue( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); GpioPinValue state; CLR_RT_HeapBlock *pinValue; CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get PinValue object from parameter pinValue = stack.Arg1().Dereference(); // access value field inside PinValue state = (GpioPinValue)pinValue[PinValue::FIELD___value].NumericByRef().u1; NANOCLR_CHECK_HRESULT(Write(pThis, state)); NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeSetAlternateFunction___VOID__I4( CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { CLR_RT_HeapBlock *pThis = stack.This(); FAULT_ON_NULL(pThis); // check if object has been disposed if (pThis[FIELD___disposedValue].NumericByRef().u1 != 0) { NANOCLR_SET_AND_LEAVE(CLR_E_OBJECT_DISPOSED); } // get pin number and take the port and pad references from that one int16_t pinNumber = pThis[FIELD___pinNumber].NumericByRefConst().s4; // get alternate function argument int32_t alternateFunction = stack.Arg1().NumericByRef().s4; CPU_GPIO_DisablePin(pinNumber, GpioPinDriveMode_Input, alternateFunction); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::NativeInit___BOOLEAN__I4(CLR_RT_StackFrame &stack) { NANOCLR_HEADER(); { GPIO_PIN pinNumber = (GPIO_PIN)stack.Arg1().NumericByRef().s4; // Return value to the managed application stack.SetResult_Boolean(CPU_GPIO_ReservePin(pinNumber, true)); } NANOCLR_NOCLEANUP_NOLABEL(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::ExtractDebounceTimeSpanValue( CLR_RT_HeapBlock &timeSpanValue, CLR_UINT64 &value) { NANOCLR_HEADER(); { // debounceTimeout field its a TimeSpan, which is a primitive type stored as an heap block, therefore needs to // be accessed indirectly CLR_INT64 *debounceValue = Library_corlib_native_System_TimeSpan::GetValuePtr(timeSpanValue); FAULT_ON_NULL(debounceValue); value = *(CLR_UINT64 *)debounceValue / TIME_CONVERSION__TO_MILLISECONDS; } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::SetPinMode( CLR_RT_HeapBlock *gpioPin, GpioPinDriveMode pinMode) { NANOCLR_HEADER(); bool validPin; CLR_UINT64 debounceTimeoutMilsec; bool callbacksRegistered = false; GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; if (pinMode >= (int)GpioPinDriveMode_Output) { validPin = CPU_GPIO_EnableOutputPin(pinNumber, GpioPinValue_Low, pinMode); } else { NANOCLR_CHECK_HRESULT(ExtractDebounceTimeSpanValue(gpioPin[FIELD___debounceTimeout], debounceTimeoutMilsec)); // flag to determine if there are any callbacks registered in managed code // this is use to determine if there is any need to setup and process INT handler callbacksRegistered = (gpioPin[FIELD___callbacks].Dereference() != NULL); validPin = CPU_GPIO_EnableInputPin( pinNumber, debounceTimeoutMilsec, callbacksRegistered ? Gpio_Interupt_ISR : NULL, NULL, GPIO_INT_EDGE_BOTH, pinMode); } if (validPin) { // all good, store pin mode in managed field gpioPin[FIELD___pinMode].NumericByRef().s4 = pinMode; } else { NANOCLR_SET_AND_LEAVE(CLR_E_INVALID_PARAMETER); } NANOCLR_NOCLEANUP(); } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Write(CLR_RT_HeapBlock *gpioPin, GpioPinValue pinValue) { GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; GpioPinDriveMode driveMode = (GpioPinDriveMode)gpioPin[FIELD___pinMode].NumericByRefConst().s4; // sanity check for drive mode set to output so we don't mess up writing to an input pin if ((driveMode >= GpioPinDriveMode_Output)) { CPU_GPIO_SetPinState(pinNumber, pinValue); // fire event if there are callbacks registered if (gpioPin[FIELD___callbacks].Dereference() != NULL) { PostManagedEvent(EVENT_GPIO, 0, (uint16_t)pinNumber, (uint32_t)pinValue); } } else { return CLR_E_INVALID_PARAMETER; } return S_OK; } HRESULT Library_sys_dev_gpio_native_System_Device_Gpio_GpioPin::Read(CLR_RT_HeapBlock *gpioPin, bool &pinValue) { GPIO_PIN pinNumber = (GPIO_PIN)gpioPin[FIELD___pinNumber].NumericByRefConst().s4; pinValue = CPU_GPIO_GetPinState(pinNumber); return S_OK; } <|endoftext|>
<commit_before>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Compiler.h" using namespace clang; typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy; namespace { class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { RegionBindingsTy::Factory RBFactory; GRStateManager& StateMgr; MemRegionManager MRMgr; public: RegionStoreManager(GRStateManager& mgr) : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {} virtual ~RegionStoreManager() {} SVal getLValueVar(const GRState* St, const VarDecl* VD); SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base); SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D); SVal getLValueElement(const GRState* St, SVal Base, SVal Offset); SVal ArrayToPointer(SVal Array); SVal Retrieve(Store S, Loc L, QualType T); Store Bind(Store St, Loc LV, SVal V); Store getInitialStore(); Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count); Loc getVarLoc(const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } Loc getElementLoc(const VarDecl* VD, SVal Idx); static inline RegionBindingsTy GetRegionBindings(Store store) { return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store)); } }; } // end anonymous namespace StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) { // return new RegionStoreManager(StMgr); return 0; // Uncomment the above line when RegionStoreManager is not abstract. } Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) { MemRegion* R = MRMgr.getVarRegion(VD); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); return loc::MemRegionVal(ER); } SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base) { return UnknownVal(); } SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base, const FieldDecl* D) { if (Base.isUnknownOrUndef()) return Base; Loc BaseL = cast<Loc>(Base); const MemRegion* BaseR = 0; switch (BaseL.getSubKind()) { case loc::MemRegionKind: BaseR = cast<loc::MemRegionVal>(BaseL).getRegion(); break; case loc::SymbolValKind: BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol()); break; case loc::GotoLabelKind: case loc::FuncValKind: // These are anormal cases. Flag an undefined value. return UndefinedVal(); case loc::ConcreteIntKind: case loc::StringLiteralValKind: // While these seem funny, this can happen through casts. // FIXME: What we should return is the field offset. For example, // add the field offset to the integer value. That way funny things // like this work properly: &(((struct foo *) 0xa)->f) return Base; default: assert("Unhandled Base."); return Base; } return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR)); } SVal RegionStoreManager::getLValueElement(const GRState* St, SVal Base, SVal Offset) { if (Base.isUnknownOrUndef()) return Base; loc::MemRegionVal& BaseL = cast<loc::MemRegionVal>(Base); // We expect BaseR is an ElementRegion, not a base VarRegion. const ElementRegion* ElemR = cast<ElementRegion>(BaseL.getRegion()); SVal Idx = ElemR->getIndex(); nonloc::ConcreteInt *CI1, *CI2; // Only handle integer indices for now. if ((CI1 = dyn_cast<nonloc::ConcreteInt>(&Idx)) && (CI2 = dyn_cast<nonloc::ConcreteInt>(&Offset))) { SVal NewIdx = CI1->EvalBinOp(StateMgr.getBasicVals(), BinaryOperator::Add, *CI2); return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx, ElemR->getSuperRegion())); } return UnknownVal(); } // Cast 'pointer to array' to 'pointer to the first element of array'. SVal RegionStoreManager::ArrayToPointer(SVal Array) { const MemRegion* ArrayR = cast<loc::MemRegionVal>(&Array)->getRegion(); const VarDecl* D = cast<VarRegion>(ArrayR)->getDecl(); if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(D->getType().getTypePtr())) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); nonloc::ConcreteInt Idx(BasicVals.getValue(0, CAT->getSize().getBitWidth(), false)); ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR); return loc::MemRegionVal(ER); } return Array; } SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) { assert(!isa<UnknownVal>(L) && "location unknown"); assert(!isa<UndefinedVal>(L) && "location undefined"); switch (L.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion(); assert(R && "bad region"); RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S)); RegionBindingsTy::data_type* V = B.lookup(R); return V ? *V : UnknownVal(); } case loc::SymbolValKind: return UnknownVal(); case loc::ConcreteIntKind: return UndefinedVal(); // As in BasicStoreManager. case loc::FuncValKind: return L; case loc::StringLiteralValKind: return UnknownVal(); default: assert(false && "Invalid Location"); break; } } Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) { assert(LV.getSubKind() == loc::MemRegionKind); const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion(); if (!R) return store; RegionBindingsTy B = GetRegionBindings(store); return V.isUnknown() ? RBFactory.Remove(B, R).getRoot() : RBFactory.Add(B, R, V).getRoot(); } Store RegionStoreManager::getInitialStore() { typedef LiveVariables::AnalysisDataTy LVDataTy; LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData(); Store St = RBFactory.GetEmptyMap().getRoot(); for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) { NamedDecl* ND = const_cast<NamedDecl*>(I->first); if (VarDecl* VD = dyn_cast<VarDecl>(ND)) { // Punt on static variables for now. if (VD->getStorageClass() == VarDecl::Static) continue; QualType T = VD->getType(); // Only handle pointers and integers for now. if (Loc::IsLocType(T) || T->isIntegerType()) { // Initialize globals and parameters to symbolic values. // Initialize local variables to undefined. SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD)) ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD) : UndefinedVal(); St = Bind(St, getVarLoc(VD), X); } } } return St; } Store RegionStoreManager::AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SymbolManager& SymMgr = StateMgr.getSymbolManager(); if (VD->hasGlobalStorage()) { // Static global variables should not be visited here. assert(!(VD->getStorageClass() == VarDecl::Static && VD->isFileVarDecl())); // Process static variables. if (VD->getStorageClass() == VarDecl::Static) { if (!Ex) { // Only handle pointer and integer static variables. QualType T = VD->getType(); if (Loc::IsLocType(T)) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else if (T->isIntegerType()) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else assert("ignore other types of variables"); } else { store = Bind(store, getVarLoc(VD), InitVal); } } } else { // Process local variables. QualType T = VD->getType(); if (Loc::IsLocType(T) || T->isIntegerType()) { SVal V = Ex ? InitVal : UndefinedVal(); if (Ex && InitVal.isUnknown()) { // "Conjured" symbols. SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count); V = Loc::IsLocType(Ex->getType()) ? cast<SVal>(loc::SymbolVal(Sym)) : cast<SVal>(nonloc::SymbolVal(Sym)); } store = Bind(store, getVarLoc(VD), V); } else if (T->isArrayType()) { // Only handle constant size array. if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) { llvm::APInt Size = CAT->getSize(); for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth()); i != Size; ++i) { nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i))); store = Bind(store, getElementLoc(VD, Idx), UndefinedVal()); } } } else if (T->isStructureType()) { // FIXME: Implement struct initialization. } } return store; } <commit_msg>Add a bunch of dummy methods to make RegionStoreManager non-virtual.<commit_after>//== RegionStore.cpp - Field-sensitive store model --------------*- C++ -*--==// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines a basic region store model. In this model, we do have field // sensitivity. But we assume nothing about the heap shape. So recursive data // structures are largely ignored. Basically we do 1-limiting analysis. // Parameter pointers are assumed with no aliasing. Pointee objects of // parameters are created lazily. // //===----------------------------------------------------------------------===// #include "clang/Analysis/PathSensitive/MemRegion.h" #include "clang/Analysis/PathSensitive/GRState.h" #include "clang/Analysis/Analyses/LiveVariables.h" #include "llvm/ADT/ImmutableMap.h" #include "llvm/Support/Compiler.h" using namespace clang; typedef llvm::ImmutableMap<const MemRegion*, SVal> RegionBindingsTy; namespace { class VISIBILITY_HIDDEN RegionStoreManager : public StoreManager { RegionBindingsTy::Factory RBFactory; GRStateManager& StateMgr; MemRegionManager MRMgr; public: RegionStoreManager(GRStateManager& mgr) : StateMgr(mgr), MRMgr(StateMgr.getAllocator()) {} virtual ~RegionStoreManager() {} MemRegionManager& getRegionManager() { return MRMgr; } // FIXME: Is this function necessary? SVal GetRegionSVal(Store St, const MemRegion* R) { return Retrieve(St, loc::MemRegionVal(R)); } SVal getLValueVar(const GRState* St, const VarDecl* VD); SVal getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base); SVal getLValueField(const GRState* St, SVal Base, const FieldDecl* D); SVal getLValueElement(const GRState* St, SVal Base, SVal Offset); SVal ArrayToPointer(SVal Array); SVal Retrieve(Store S, Loc L, QualType T = QualType()); Store Bind(Store St, Loc LV, SVal V); Store Remove(Store store, Loc LV) { // FIXME: Implement. return store; } Store getInitialStore(); Store RemoveDeadBindings(Store store, Stmt* Loc, const LiveVariables& Live, llvm::SmallVectorImpl<const MemRegion*>& RegionRoots, LiveSymbolsTy& LSymbols, DeadSymbolsTy& DSymbols) { // FIXME: Implement this. return store; } Store AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count); Loc getVarLoc(const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } Loc getElementLoc(const VarDecl* VD, SVal Idx); static inline RegionBindingsTy GetRegionBindings(Store store) { return RegionBindingsTy(static_cast<const RegionBindingsTy::TreeTy*>(store)); } void print(Store store, std::ostream& Out, const char* nl, const char *sep) { // FIXME: Implement. } void iterBindings(Store store, BindingsHandler& f) { // FIXME: Implement. } }; } // end anonymous namespace StoreManager* clang::CreateRegionStoreManager(GRStateManager& StMgr) { return new RegionStoreManager(StMgr); } Loc RegionStoreManager::getElementLoc(const VarDecl* VD, SVal Idx) { MemRegion* R = MRMgr.getVarRegion(VD); ElementRegion* ER = MRMgr.getElementRegion(Idx, R); return loc::MemRegionVal(ER); } SVal RegionStoreManager::getLValueVar(const GRState* St, const VarDecl* VD) { return loc::MemRegionVal(MRMgr.getVarRegion(VD)); } SVal RegionStoreManager::getLValueIvar(const GRState* St, const ObjCIvarDecl* D, SVal Base) { return UnknownVal(); } SVal RegionStoreManager::getLValueField(const GRState* St, SVal Base, const FieldDecl* D) { if (Base.isUnknownOrUndef()) return Base; Loc BaseL = cast<Loc>(Base); const MemRegion* BaseR = 0; switch (BaseL.getSubKind()) { case loc::MemRegionKind: BaseR = cast<loc::MemRegionVal>(BaseL).getRegion(); break; case loc::SymbolValKind: BaseR = MRMgr.getSymbolicRegion(cast<loc::SymbolVal>(&BaseL)->getSymbol()); break; case loc::GotoLabelKind: case loc::FuncValKind: // These are anormal cases. Flag an undefined value. return UndefinedVal(); case loc::ConcreteIntKind: case loc::StringLiteralValKind: // While these seem funny, this can happen through casts. // FIXME: What we should return is the field offset. For example, // add the field offset to the integer value. That way funny things // like this work properly: &(((struct foo *) 0xa)->f) return Base; default: assert("Unhandled Base."); return Base; } return loc::MemRegionVal(MRMgr.getFieldRegion(D, BaseR)); } SVal RegionStoreManager::getLValueElement(const GRState* St, SVal Base, SVal Offset) { if (Base.isUnknownOrUndef()) return Base; loc::MemRegionVal& BaseL = cast<loc::MemRegionVal>(Base); // We expect BaseR is an ElementRegion, not a base VarRegion. const ElementRegion* ElemR = cast<ElementRegion>(BaseL.getRegion()); SVal Idx = ElemR->getIndex(); nonloc::ConcreteInt *CI1, *CI2; // Only handle integer indices for now. if ((CI1 = dyn_cast<nonloc::ConcreteInt>(&Idx)) && (CI2 = dyn_cast<nonloc::ConcreteInt>(&Offset))) { SVal NewIdx = CI1->EvalBinOp(StateMgr.getBasicVals(), BinaryOperator::Add, *CI2); return loc::MemRegionVal(MRMgr.getElementRegion(NewIdx, ElemR->getSuperRegion())); } return UnknownVal(); } // Cast 'pointer to array' to 'pointer to the first element of array'. SVal RegionStoreManager::ArrayToPointer(SVal Array) { const MemRegion* ArrayR = cast<loc::MemRegionVal>(&Array)->getRegion(); const VarDecl* D = cast<VarRegion>(ArrayR)->getDecl(); if (const ConstantArrayType* CAT = dyn_cast<ConstantArrayType>(D->getType().getTypePtr())) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); nonloc::ConcreteInt Idx(BasicVals.getValue(0, CAT->getSize().getBitWidth(), false)); ElementRegion* ER = MRMgr.getElementRegion(Idx, ArrayR); return loc::MemRegionVal(ER); } return Array; } SVal RegionStoreManager::Retrieve(Store S, Loc L, QualType T) { assert(!isa<UnknownVal>(L) && "location unknown"); assert(!isa<UndefinedVal>(L) && "location undefined"); switch (L.getSubKind()) { case loc::MemRegionKind: { const MemRegion* R = cast<loc::MemRegionVal>(L).getRegion(); assert(R && "bad region"); RegionBindingsTy B(static_cast<const RegionBindingsTy::TreeTy*>(S)); RegionBindingsTy::data_type* V = B.lookup(R); return V ? *V : UnknownVal(); } case loc::SymbolValKind: return UnknownVal(); case loc::ConcreteIntKind: return UndefinedVal(); // As in BasicStoreManager. case loc::FuncValKind: return L; case loc::StringLiteralValKind: return UnknownVal(); default: assert(false && "Invalid Location"); break; } } Store RegionStoreManager::Bind(Store store, Loc LV, SVal V) { assert(LV.getSubKind() == loc::MemRegionKind); const MemRegion* R = cast<loc::MemRegionVal>(LV).getRegion(); if (!R) return store; RegionBindingsTy B = GetRegionBindings(store); return V.isUnknown() ? RBFactory.Remove(B, R).getRoot() : RBFactory.Add(B, R, V).getRoot(); } Store RegionStoreManager::getInitialStore() { typedef LiveVariables::AnalysisDataTy LVDataTy; LVDataTy& D = StateMgr.getLiveVariables().getAnalysisData(); Store St = RBFactory.GetEmptyMap().getRoot(); for (LVDataTy::decl_iterator I=D.begin_decl(), E=D.end_decl(); I != E; ++I) { NamedDecl* ND = const_cast<NamedDecl*>(I->first); if (VarDecl* VD = dyn_cast<VarDecl>(ND)) { // Punt on static variables for now. if (VD->getStorageClass() == VarDecl::Static) continue; QualType T = VD->getType(); // Only handle pointers and integers for now. if (Loc::IsLocType(T) || T->isIntegerType()) { // Initialize globals and parameters to symbolic values. // Initialize local variables to undefined. SVal X = (VD->hasGlobalStorage() || isa<ParmVarDecl>(VD) || isa<ImplicitParamDecl>(VD)) ? SVal::GetSymbolValue(StateMgr.getSymbolManager(), VD) : UndefinedVal(); St = Bind(St, getVarLoc(VD), X); } } } return St; } Store RegionStoreManager::AddDecl(Store store, const VarDecl* VD, Expr* Ex, SVal InitVal, unsigned Count) { BasicValueFactory& BasicVals = StateMgr.getBasicVals(); SymbolManager& SymMgr = StateMgr.getSymbolManager(); if (VD->hasGlobalStorage()) { // Static global variables should not be visited here. assert(!(VD->getStorageClass() == VarDecl::Static && VD->isFileVarDecl())); // Process static variables. if (VD->getStorageClass() == VarDecl::Static) { if (!Ex) { // Only handle pointer and integer static variables. QualType T = VD->getType(); if (Loc::IsLocType(T)) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else if (T->isIntegerType()) store = Bind(store, getVarLoc(VD), loc::ConcreteInt(BasicVals.getValue(0, T))); else assert("ignore other types of variables"); } else { store = Bind(store, getVarLoc(VD), InitVal); } } } else { // Process local variables. QualType T = VD->getType(); if (Loc::IsLocType(T) || T->isIntegerType()) { SVal V = Ex ? InitVal : UndefinedVal(); if (Ex && InitVal.isUnknown()) { // "Conjured" symbols. SymbolID Sym = SymMgr.getConjuredSymbol(Ex, Count); V = Loc::IsLocType(Ex->getType()) ? cast<SVal>(loc::SymbolVal(Sym)) : cast<SVal>(nonloc::SymbolVal(Sym)); } store = Bind(store, getVarLoc(VD), V); } else if (T->isArrayType()) { // Only handle constant size array. if (ConstantArrayType* CAT=dyn_cast<ConstantArrayType>(T.getTypePtr())) { llvm::APInt Size = CAT->getSize(); for (llvm::APInt i = llvm::APInt::getNullValue(Size.getBitWidth()); i != Size; ++i) { nonloc::ConcreteInt Idx(BasicVals.getValue(llvm::APSInt(i))); store = Bind(store, getElementLoc(VD, Idx), UndefinedVal()); } } } else if (T->isStructureType()) { // FIXME: Implement struct initialization. } } return store; } <|endoftext|>
<commit_before>//===-- LowerSubregs.cpp - Subregister Lowering instruction pass ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lowersubregs" #include "llvm/CodeGen/Passes.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" using namespace llvm; namespace { struct VISIBILITY_HIDDEN LowerSubregsInstructionPass : public MachineFunctionPass { static char ID; // Pass identification, replacement for typeid LowerSubregsInstructionPass() : MachineFunctionPass((intptr_t)&ID) {} const char *getPassName() const { return "Subregister lowering instruction pass"; } /// runOnMachineFunction - pass entry point bool runOnMachineFunction(MachineFunction&); bool LowerExtract(MachineInstr *MI); bool LowerInsert(MachineInstr *MI); bool LowerSubregToReg(MachineInstr *MI); }; char LowerSubregsInstructionPass::ID = 0; } FunctionPass *llvm::createLowerSubregsPass() { return new LowerSubregsInstructionPass(); } bool LowerSubregsInstructionPass::LowerExtract(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert(MI->getOperand(0).isRegister() && MI->getOperand(0).isDef() && MI->getOperand(1).isRegister() && MI->getOperand(1).isUse() && MI->getOperand(2).isImmediate() && "Malformed extract_subreg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned SuperReg = MI->getOperand(1).getReg(); unsigned SubIdx = MI->getOperand(2).getImm(); unsigned SrcReg = TRI.getSubReg(SuperReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(SuperReg) && "Extract supperg source must be a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && "Insert destination must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; if (SrcReg != DstReg) { const TargetRegisterClass *TRC = TRI.getPhysicalRegisterRegClass(DstReg); assert(TRC == TRI.getPhysicalRegisterRegClass(SrcReg) && "Extract subreg and Dst must be of same register class"); TII.copyRegToReg(*MBB, MI, DstReg, SrcReg, TRC, TRC); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif } DOUT << "\n"; MBB->remove(MI); return true; } bool LowerSubregsInstructionPass::LowerSubregToReg(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert((MI->getOperand(0).isRegister() && MI->getOperand(0).isDef()) && MI->getOperand(1).isImmediate() && (MI->getOperand(2).isRegister() && MI->getOperand(2).isUse()) && MI->getOperand(3).isImmediate() && "Invalid subreg_to_reg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned InsReg = MI->getOperand(2).getReg(); unsigned SubIdx = MI->getOperand(3).getImm(); assert(SubIdx != 0 && "Invalid index for insert_subreg"); unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && "Insert destination must be in a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(InsReg) && "Inserted value must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; // Insert sub-register copy const TargetRegisterClass *TRC0 = TRI.getPhysicalRegisterRegClass(DstSubReg); const TargetRegisterClass *TRC1 = TRI.getPhysicalRegisterRegClass(InsReg); TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif DOUT << "\n"; MBB->remove(MI); return true; } bool LowerSubregsInstructionPass::LowerInsert(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert((MI->getOperand(0).isRegister() && MI->getOperand(0).isDef()) && (MI->getOperand(1).isRegister() && MI->getOperand(1).isUse()) && (MI->getOperand(2).isRegister() && MI->getOperand(2).isUse()) && MI->getOperand(3).isImmediate() && "Invalid insert_subreg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned SrcReg = MI->getOperand(1).getReg(); unsigned InsReg = MI->getOperand(2).getReg(); unsigned SubIdx = MI->getOperand(3).getImm(); assert(DstReg == SrcReg && "insert_subreg not a two-address instruction?"); assert(SubIdx != 0 && "Invalid index for insert_subreg"); unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) && "Insert superreg source must be in a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(InsReg) && "Inserted value must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; // Insert sub-register copy const TargetRegisterClass *TRC0 = TRI.getPhysicalRegisterRegClass(DstSubReg); const TargetRegisterClass *TRC1 = TRI.getPhysicalRegisterRegClass(InsReg); TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif DOUT << "\n"; MBB->remove(MI); return true; } /// runOnMachineFunction - Reduce subregister inserts and extracts to register /// copies. /// bool LowerSubregsInstructionPass::runOnMachineFunction(MachineFunction &MF) { DOUT << "Machine Function\n"; bool MadeChange = false; DOUT << "********** LOWERING SUBREG INSTRS **********\n"; DOUT << "********** Function: " << MF.getFunction()->getName() << '\n'; for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end(); mbbi != mbbe; ++mbbi) { for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end(); mi != me;) { MachineInstr *MI = mi++; if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { MadeChange |= LowerExtract(MI); } else if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) { MadeChange |= LowerInsert(MI); } else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) { MadeChange |= LowerSubregToReg(MI); } } } return MadeChange; } <commit_msg>LowerSubregs should not clobber any analysis.<commit_after>//===-- LowerSubregs.cpp - Subregister Lowering instruction pass ----------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "lowersubregs" #include "llvm/CodeGen/Passes.h" #include "llvm/Function.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Target/TargetInstrInfo.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Compiler.h" using namespace llvm; namespace { struct VISIBILITY_HIDDEN LowerSubregsInstructionPass : public MachineFunctionPass { static char ID; // Pass identification, replacement for typeid LowerSubregsInstructionPass() : MachineFunctionPass((intptr_t)&ID) {} const char *getPassName() const { return "Subregister lowering instruction pass"; } void getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesAll(); } /// runOnMachineFunction - pass entry point bool runOnMachineFunction(MachineFunction&); bool LowerExtract(MachineInstr *MI); bool LowerInsert(MachineInstr *MI); bool LowerSubregToReg(MachineInstr *MI); }; char LowerSubregsInstructionPass::ID = 0; } FunctionPass *llvm::createLowerSubregsPass() { return new LowerSubregsInstructionPass(); } bool LowerSubregsInstructionPass::LowerExtract(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert(MI->getOperand(0).isRegister() && MI->getOperand(0).isDef() && MI->getOperand(1).isRegister() && MI->getOperand(1).isUse() && MI->getOperand(2).isImmediate() && "Malformed extract_subreg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned SuperReg = MI->getOperand(1).getReg(); unsigned SubIdx = MI->getOperand(2).getImm(); unsigned SrcReg = TRI.getSubReg(SuperReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(SuperReg) && "Extract supperg source must be a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && "Insert destination must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; if (SrcReg != DstReg) { const TargetRegisterClass *TRC = TRI.getPhysicalRegisterRegClass(DstReg); assert(TRC == TRI.getPhysicalRegisterRegClass(SrcReg) && "Extract subreg and Dst must be of same register class"); TII.copyRegToReg(*MBB, MI, DstReg, SrcReg, TRC, TRC); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif } DOUT << "\n"; MBB->remove(MI); return true; } bool LowerSubregsInstructionPass::LowerSubregToReg(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert((MI->getOperand(0).isRegister() && MI->getOperand(0).isDef()) && MI->getOperand(1).isImmediate() && (MI->getOperand(2).isRegister() && MI->getOperand(2).isUse()) && MI->getOperand(3).isImmediate() && "Invalid subreg_to_reg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned InsReg = MI->getOperand(2).getReg(); unsigned SubIdx = MI->getOperand(3).getImm(); assert(SubIdx != 0 && "Invalid index for insert_subreg"); unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(DstReg) && "Insert destination must be in a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(InsReg) && "Inserted value must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; // Insert sub-register copy const TargetRegisterClass *TRC0 = TRI.getPhysicalRegisterRegClass(DstSubReg); const TargetRegisterClass *TRC1 = TRI.getPhysicalRegisterRegClass(InsReg); TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif DOUT << "\n"; MBB->remove(MI); return true; } bool LowerSubregsInstructionPass::LowerInsert(MachineInstr *MI) { MachineBasicBlock *MBB = MI->getParent(); MachineFunction &MF = *MBB->getParent(); const TargetRegisterInfo &TRI = *MF.getTarget().getRegisterInfo(); const TargetInstrInfo &TII = *MF.getTarget().getInstrInfo(); assert((MI->getOperand(0).isRegister() && MI->getOperand(0).isDef()) && (MI->getOperand(1).isRegister() && MI->getOperand(1).isUse()) && (MI->getOperand(2).isRegister() && MI->getOperand(2).isUse()) && MI->getOperand(3).isImmediate() && "Invalid insert_subreg"); unsigned DstReg = MI->getOperand(0).getReg(); unsigned SrcReg = MI->getOperand(1).getReg(); unsigned InsReg = MI->getOperand(2).getReg(); unsigned SubIdx = MI->getOperand(3).getImm(); assert(DstReg == SrcReg && "insert_subreg not a two-address instruction?"); assert(SubIdx != 0 && "Invalid index for insert_subreg"); unsigned DstSubReg = TRI.getSubReg(DstReg, SubIdx); assert(TargetRegisterInfo::isPhysicalRegister(SrcReg) && "Insert superreg source must be in a physical register"); assert(TargetRegisterInfo::isPhysicalRegister(InsReg) && "Inserted value must be in a physical register"); DOUT << "subreg: CONVERTING: " << *MI; // Insert sub-register copy const TargetRegisterClass *TRC0 = TRI.getPhysicalRegisterRegClass(DstSubReg); const TargetRegisterClass *TRC1 = TRI.getPhysicalRegisterRegClass(InsReg); TII.copyRegToReg(*MBB, MI, DstSubReg, InsReg, TRC0, TRC1); #ifndef NDEBUG MachineBasicBlock::iterator dMI = MI; DOUT << "subreg: " << *(--dMI); #endif DOUT << "\n"; MBB->remove(MI); return true; } /// runOnMachineFunction - Reduce subregister inserts and extracts to register /// copies. /// bool LowerSubregsInstructionPass::runOnMachineFunction(MachineFunction &MF) { DOUT << "Machine Function\n"; bool MadeChange = false; DOUT << "********** LOWERING SUBREG INSTRS **********\n"; DOUT << "********** Function: " << MF.getFunction()->getName() << '\n'; for (MachineFunction::iterator mbbi = MF.begin(), mbbe = MF.end(); mbbi != mbbe; ++mbbi) { for (MachineBasicBlock::iterator mi = mbbi->begin(), me = mbbi->end(); mi != me;) { MachineInstr *MI = mi++; if (MI->getOpcode() == TargetInstrInfo::EXTRACT_SUBREG) { MadeChange |= LowerExtract(MI); } else if (MI->getOpcode() == TargetInstrInfo::INSERT_SUBREG) { MadeChange |= LowerInsert(MI); } else if (MI->getOpcode() == TargetInstrInfo::SUBREG_TO_REG) { MadeChange |= LowerSubregToReg(MI); } } } return MadeChange; } <|endoftext|>
<commit_before>//===-- RegAllocBase.cpp - Register Allocator Base Class ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RegAllocBase class which provides comon functionality // for LiveIntervalUnion-based register allocators. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "RegAllocBase.h" #include "Spiller.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/LiveRangeEdit.h" #include "llvm/CodeGen/LiveRegMatrix.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/VirtRegMap.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #ifndef NDEBUG #include "llvm/ADT/SparseBitVector.h" #endif #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Timer.h" using namespace llvm; STATISTIC(NumNewQueued , "Number of new live ranges queued"); // Temporary verification option until we can put verification inside // MachineVerifier. static cl::opt<bool, true> VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled), cl::desc("Verify during register allocation")); const char RegAllocBase::TimerGroupName[] = "Register Allocation"; bool RegAllocBase::VerifyEnabled = false; //===----------------------------------------------------------------------===// // RegAllocBase Implementation //===----------------------------------------------------------------------===// // Pin the vtable to this file. void RegAllocBase::anchor() {} void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat) { TRI = &vrm.getTargetRegInfo(); MRI = &vrm.getRegInfo(); VRM = &vrm; LIS = &lis; Matrix = &mat; MRI->freezeReservedRegs(vrm.getMachineFunction()); RegClassInfo.runOnMachineFunction(vrm.getMachineFunction()); } // Visit all the live registers. If they are already assigned to a physical // register, unify them with the corresponding LiveIntervalUnion, otherwise push // them on the priority queue for later assignment. void RegAllocBase::seedLiveRegs() { NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled); for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { unsigned Reg = TargetRegisterInfo::index2VirtReg(i); if (MRI->reg_nodbg_empty(Reg)) continue; enqueue(&LIS->getInterval(Reg)); } } // Top-level driver to manage the queue of unassigned VirtRegs and call the // selectOrSplit implementation. void RegAllocBase::allocatePhysRegs() { seedLiveRegs(); // Continue assigning vregs one at a time to available physical registers. while (LiveInterval *VirtReg = dequeue()) { assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned"); // Unused registers can appear when the spiller coalesces snippets. if (MRI->reg_nodbg_empty(VirtReg->reg)) { DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n'); LIS->removeInterval(VirtReg->reg); continue; } // Invalidate all interference queries, live ranges could have changed. Matrix->invalidateVirtRegs(); // selectOrSplit requests the allocator to return an available physical // register if possible and populate a list of new live intervals that // result from splitting. DEBUG(dbgs() << "\nselectOrSplit " << MRI->getRegClass(VirtReg->reg)->getName() << ':' << *VirtReg << " w=" << VirtReg->weight << '\n'); typedef SmallVector<unsigned, 4> VirtRegVec; VirtRegVec SplitVRegs; unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs); if (AvailablePhysReg == ~0u) { // selectOrSplit failed to find a register! // Probably caused by an inline asm. MachineInstr *MI; for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(VirtReg->reg); (MI = I.skipInstruction());) if (MI->isInlineAsm()) break; if (MI) MI->emitError("inline assembly requires more registers than available"); else report_fatal_error("ran out of registers during register allocation"); // Keep going after reporting the error. VRM->assignVirt2Phys(VirtReg->reg, RegClassInfo.getOrder(MRI->getRegClass(VirtReg->reg)).front()); continue; } if (AvailablePhysReg) Matrix->assign(*VirtReg, AvailablePhysReg); for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end(); I != E; ++I) { LiveInterval *SplitVirtReg = &LIS->getInterval(*I); assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned"); if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) { DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n'); LIS->removeInterval(SplitVirtReg->reg); continue; } DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n"); assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) && "expect split value in virtual register"); enqueue(SplitVirtReg); ++NumNewQueued; } } } <commit_msg>Fix typo<commit_after>//===-- RegAllocBase.cpp - Register Allocator Base Class ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RegAllocBase class which provides common functionality // for LiveIntervalUnion-based register allocators. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "RegAllocBase.h" #include "Spiller.h" #include "llvm/ADT/Statistic.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/LiveRangeEdit.h" #include "llvm/CodeGen/LiveRegMatrix.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/VirtRegMap.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetRegisterInfo.h" #ifndef NDEBUG #include "llvm/ADT/SparseBitVector.h" #endif #include "llvm/Support/CommandLine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Support/Timer.h" using namespace llvm; STATISTIC(NumNewQueued , "Number of new live ranges queued"); // Temporary verification option until we can put verification inside // MachineVerifier. static cl::opt<bool, true> VerifyRegAlloc("verify-regalloc", cl::location(RegAllocBase::VerifyEnabled), cl::desc("Verify during register allocation")); const char RegAllocBase::TimerGroupName[] = "Register Allocation"; bool RegAllocBase::VerifyEnabled = false; //===----------------------------------------------------------------------===// // RegAllocBase Implementation //===----------------------------------------------------------------------===// // Pin the vtable to this file. void RegAllocBase::anchor() {} void RegAllocBase::init(VirtRegMap &vrm, LiveIntervals &lis, LiveRegMatrix &mat) { TRI = &vrm.getTargetRegInfo(); MRI = &vrm.getRegInfo(); VRM = &vrm; LIS = &lis; Matrix = &mat; MRI->freezeReservedRegs(vrm.getMachineFunction()); RegClassInfo.runOnMachineFunction(vrm.getMachineFunction()); } // Visit all the live registers. If they are already assigned to a physical // register, unify them with the corresponding LiveIntervalUnion, otherwise push // them on the priority queue for later assignment. void RegAllocBase::seedLiveRegs() { NamedRegionTimer T("Seed Live Regs", TimerGroupName, TimePassesIsEnabled); for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) { unsigned Reg = TargetRegisterInfo::index2VirtReg(i); if (MRI->reg_nodbg_empty(Reg)) continue; enqueue(&LIS->getInterval(Reg)); } } // Top-level driver to manage the queue of unassigned VirtRegs and call the // selectOrSplit implementation. void RegAllocBase::allocatePhysRegs() { seedLiveRegs(); // Continue assigning vregs one at a time to available physical registers. while (LiveInterval *VirtReg = dequeue()) { assert(!VRM->hasPhys(VirtReg->reg) && "Register already assigned"); // Unused registers can appear when the spiller coalesces snippets. if (MRI->reg_nodbg_empty(VirtReg->reg)) { DEBUG(dbgs() << "Dropping unused " << *VirtReg << '\n'); LIS->removeInterval(VirtReg->reg); continue; } // Invalidate all interference queries, live ranges could have changed. Matrix->invalidateVirtRegs(); // selectOrSplit requests the allocator to return an available physical // register if possible and populate a list of new live intervals that // result from splitting. DEBUG(dbgs() << "\nselectOrSplit " << MRI->getRegClass(VirtReg->reg)->getName() << ':' << *VirtReg << " w=" << VirtReg->weight << '\n'); typedef SmallVector<unsigned, 4> VirtRegVec; VirtRegVec SplitVRegs; unsigned AvailablePhysReg = selectOrSplit(*VirtReg, SplitVRegs); if (AvailablePhysReg == ~0u) { // selectOrSplit failed to find a register! // Probably caused by an inline asm. MachineInstr *MI; for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(VirtReg->reg); (MI = I.skipInstruction());) if (MI->isInlineAsm()) break; if (MI) MI->emitError("inline assembly requires more registers than available"); else report_fatal_error("ran out of registers during register allocation"); // Keep going after reporting the error. VRM->assignVirt2Phys(VirtReg->reg, RegClassInfo.getOrder(MRI->getRegClass(VirtReg->reg)).front()); continue; } if (AvailablePhysReg) Matrix->assign(*VirtReg, AvailablePhysReg); for (VirtRegVec::iterator I = SplitVRegs.begin(), E = SplitVRegs.end(); I != E; ++I) { LiveInterval *SplitVirtReg = &LIS->getInterval(*I); assert(!VRM->hasPhys(SplitVirtReg->reg) && "Register already assigned"); if (MRI->reg_nodbg_empty(SplitVirtReg->reg)) { DEBUG(dbgs() << "not queueing unused " << *SplitVirtReg << '\n'); LIS->removeInterval(SplitVirtReg->reg); continue; } DEBUG(dbgs() << "queuing new interval: " << *SplitVirtReg << "\n"); assert(TargetRegisterInfo::isVirtualRegister(SplitVirtReg->reg) && "expect split value in virtual register"); enqueue(SplitVirtReg); ++NumNewQueued; } } } <|endoftext|>
<commit_before>/* Copyright 2021 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. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <memory> #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/strings/cord.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow/lite/kernels/builtin_op_kernels.h" #include "tensorflow/lite/mutable_op_resolver.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_api_factory.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/core/tflite_engine.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" #include <fstream> namespace tflite { namespace task { namespace processor { namespace { using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::testing::Optional; using ::tflite::support::kTfLiteSupportPayload; using ::tflite::support::StatusOr; using ::tflite::support::TfLiteSupportStatus; using ::tflite::task::JoinPath; using ::tflite::task::core::PopulateTensor; using ::tflite::task::core::TaskAPIFactory; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_, ImagePreprocessor::Create(engine_.get(), {0})); } protected: std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr; std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if input tensor dims signature for height and width is -1 // because it is so in the model. TEST_F(DynamicInputTest, InputHeightAndWidthMutable) { const TfLiteIntArray *input_dims_signature = engine_->GetInputs()[0]->dims_signature; EXPECT_EQ(input_dims_signature->data[1], -1); EXPECT_EQ(input_dims_signature->data[2], -1); } // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); absl::Status status = engine_->interpreter_wrapper()->InvokeWithoutFallback(); EXPECT_TRUE(status.ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); std::string file_path = JoinPath("./" /*test src dir*/, kTestDataDirectory, "burger_normalized.bin"); std::ifstream golden_image(file_path); std::string curr_line; bool is_equal = true; float epsilon = 0.1f; while (std::getline(golden_image, curr_line)) { float val = std::stof(curr_line); is_equal &= std::fabs(val - *processed_input_data) <= epsilon; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <commit_msg>Unable to read file otherwise test pass.<commit_after>/* Copyright 2021 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. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <fstream> #include <memory> #include "absl/flags/flag.h" #include "absl/status/status.h" #include "absl/strings/cord.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow/lite/kernels/builtin_op_kernels.h" #include "tensorflow/lite/mutable_op_resolver.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_api_factory.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/core/tflite_engine.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" namespace tflite { namespace task { namespace processor { namespace { using ::testing::ElementsAreArray; using ::testing::HasSubstr; using ::testing::Optional; using ::tflite::support::kTfLiteSupportPayload; using ::tflite::support::StatusOr; using ::tflite::support::TfLiteSupportStatus; using ::tflite::task::JoinPath; using ::tflite::task::core::PopulateTensor; using ::tflite::task::core::TaskAPIFactory; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(preprocessor_, ImagePreprocessor::Create(engine_.get(), {0})); } protected: std::unique_ptr<ImagePreprocessor> preprocessor_ = nullptr; std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if input tensor dims signature for height and width is -1 // because it is so in the model. TEST_F(DynamicInputTest, InputHeightAndWidthMutable) { const TfLiteIntArray *input_dims_signature = engine_->GetInputs()[0]->dims_signature; EXPECT_EQ(input_dims_signature->data[1], -1); EXPECT_EQ(input_dims_signature->data[2], -1); } // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); absl::Status status = engine_->interpreter_wrapper()->InvokeWithoutFallback(); EXPECT_TRUE(status.ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor_->Preprocess(*image_frame_buffer); // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); bool is_equal = true; float epsilon = 0.1f; std::string file_path = JoinPath("./", kTestDataDirectory, "burger_normalized.bin"); std::ifstream golden_image(file_path, std::ios::binary); // Input read success check. is_equal &= golden_image.peek() != std::ifstream::traits_type::eof(); std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(golden_image), {}); float *val_ptr = reinterpret_cast<float *>(buffer.data()); for (size_t i = 0; i < buffer.size() / sizeof(float); ++i) { is_equal &= std::fabs(*val_ptr - *processed_input_data) <= epsilon; ++val_ptr; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <|endoftext|>
<commit_before>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #if OPENSSL_VERSION_MAJOR >= 3 #include <openssl/provider.h> #endif #endif #include "../../Debug/Assertions.h" #include "../../Execution/Exceptions.h" #include "LibraryContext.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { optional<String> GetCiphrName_ (CipherAlgorithm a) { if (auto i = ::EVP_CIPHER_name (a)) { return String::FromASCII (i); } return nullopt; } } /* ******************************************************************************** ******************* Cryptography::OpenSSL::LibraryContext ********************** ******************************************************************************** */ LibraryContext LibraryContext::sDefault; LibraryContext::LibraryContext () : pAvailableAlgorithms{ [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms); shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj}; Set<String> ciphers; ::EVP_CIPHER_do_all_provided ( nullptr, [] (EVP_CIPHER* ciph, void* arg) { Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg); if (ciph != nullptr) { DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph)); if (auto cipherName = GetCiphrName_ (ciph)) { if (auto provider = ::EVP_CIPHER_provider (ciph)) { DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider)); } int flags = ::EVP_CIPHER_flags (ciph); DbgTrace ("flags=%x", flags); ciphers->Add (*cipherName); } } }, &ciphers); DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ()); auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); }; Traversal::Iterable<int> yyy{}; Set<int> resultyyy{yyy}; using namespace Configuration; static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>); using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>; //Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa; #if 1 Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })}; WeakAssert (result.size () == ciphers.size ()); #endif return result; }} { LoadProvider (kDefaultProvider); } LibraryContext ::~LibraryContext () { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 for (auto i : fLoadedProviders_) { Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1); } #endif } void LibraryContext::LoadProvider (const String& providerName) { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ()); static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv}; Execution::ThrowIfNull (p, kErr_); if (auto l = fLoadedProviders_.Lookup (providerName)) { l->second++; fLoadedProviders_.Add (providerName, *l); } else { fLoadedProviders_.Add (providerName, {p, 1}); } #else Require (providerName == kDefaultProvider or providerName == kLegacyProvider); #endif } void LibraryContext ::UnLoadProvider (const String& providerName) { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 Require (fLoadedProviders_.ContainsKey (providerName)); auto l = fLoadedProviders_.Lookup (providerName); Assert (l); l->second--; if (l->second == 0) { fLoadedProviders_.Remove (providerName); Verify (::OSSL_PROVIDER_unload (l->first) == 1); } else { fLoadedProviders_.Add (providerName, *l); } #endif } #endif <commit_msg>Tweaks to openssl code for non-ssl3<commit_after>/* * Copyright(c) Sophist Solutions, Inc. 1990-2021. All rights reserved */ #include "../../StroikaPreComp.h" #if qHasFeature_OpenSSL #include <openssl/evp.h> #if OPENSSL_VERSION_MAJOR >= 3 #include <openssl/provider.h> #endif #endif #include "../../Debug/Assertions.h" #include "../../Execution/Exceptions.h" #include "LibraryContext.h" using namespace Stroika::Foundation; using namespace Stroika::Foundation::Cryptography; using namespace Stroika::Foundation::Cryptography::OpenSSL; #if qHasFeature_OpenSSL && defined(_MSC_VER) // Use #pragma comment lib instead of explicit entry in the lib entry of the project file #if OPENSSL_VERSION_NUMBER < 0x1010000fL #pragma comment(lib, "libeay32.lib") #pragma comment(lib, "ssleay32.lib") #else #pragma comment(lib, "libcrypto.lib") #pragma comment(lib, "libssl.lib") #pragma comment(lib, "ws2_32.lib") #pragma comment(lib, "crypt32.lib") #endif #endif #if qHasFeature_OpenSSL namespace { optional<String> GetCiphrName_ (CipherAlgorithm a) { if (auto i = ::EVP_CIPHER_name (a)) { return String::FromASCII (i); } return nullopt; } } /* ******************************************************************************** ******************* Cryptography::OpenSSL::LibraryContext ********************** ******************************************************************************** */ LibraryContext LibraryContext::sDefault; LibraryContext::LibraryContext () : pAvailableAlgorithms{ [qStroika_Foundation_Common_Property_ExtraCaptureStuff] ([[maybe_unused]] const auto* property) -> Set<CipherAlgorithm> { const LibraryContext* thisObj = qStroika_Foundation_Common_Property_OuterObjPtr (property, &LibraryContext::pAvailableAlgorithms); shared_lock<const AssertExternallySynchronizedLock> critSec{*thisObj}; Set<String> ciphers; ::EVP_CIPHER_do_all_provided ( nullptr, [] (EVP_CIPHER* ciph, void* arg) { Set<String>* ciphers = reinterpret_cast<Set<String>*> (arg); if (ciph != nullptr) { DbgTrace (L"cipher: %p (name: %s), provider: %p", ciph, CipherAlgorithm{ciph}.pName ().c_str (), ::EVP_CIPHER_provider (ciph)); Assert (GetCiphrName_ (ciph)); if (auto cipherName = GetCiphrName_ (ciph)) { #if OPENSSL_VERSION_MAJOR >= 3 if (auto provider = ::EVP_CIPHER_provider (ciph)) { DbgTrace ("providername = %s", ::OSSL_PROVIDER_name (provider)); } #endif int flags = ::EVP_CIPHER_flags (ciph); DbgTrace ("flags=%x", flags); ciphers->Add (*cipherName); } } }, &ciphers); DbgTrace (L"Found kAllLoadedCiphers=%s", Characters::ToString (ciphers).c_str ()); auto fn = [] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); }; Traversal::Iterable<int> yyy{}; Set<int> resultyyy{yyy}; using namespace Configuration; static_assert (IsIterable_v<Traversal::Iterable<CipherAlgorithm>>); using ITERABLE_OF_T = Traversal::Iterable<CipherAlgorithm>; //Configuration::Private:: IsIterableOfT_Impl2_<set<int>, int> aa; #if 1 Set<CipherAlgorithm> result{ciphers.Select<CipherAlgorithm> ([] (const String& n) -> optional<CipherAlgorithm> { return OpenSSL::GetCipherByNameQuietly (n); })}; WeakAssert (result.size () == ciphers.size ()); #endif return result; }} { LoadProvider (kDefaultProvider); } LibraryContext ::~LibraryContext () { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 for (auto i : fLoadedProviders_) { Verify (::OSSL_PROVIDER_unload (i.fValue.first) == 1); } #endif } void LibraryContext::LoadProvider (const String& providerName) { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 OSSL_PROVIDER* p = ::OSSL_PROVIDER_load (NULL, providerName.AsNarrowSDKString ().c_str ()); static const Execution::RuntimeErrorException kErr_{L"No such SSL provider"sv}; Execution::ThrowIfNull (p, kErr_); if (auto l = fLoadedProviders_.Lookup (providerName)) { l->second++; fLoadedProviders_.Add (providerName, *l); } else { fLoadedProviders_.Add (providerName, {p, 1}); } #else Require (providerName == kDefaultProvider or providerName == kLegacyProvider); #endif } void LibraryContext ::UnLoadProvider (const String& providerName) { lock_guard<const AssertExternallySynchronizedLock> critSec{*this}; #if OPENSSL_VERSION_MAJOR >= 3 Require (fLoadedProviders_.ContainsKey (providerName)); auto l = fLoadedProviders_.Lookup (providerName); Assert (l); l->second--; if (l->second == 0) { fLoadedProviders_.Remove (providerName); Verify (::OSSL_PROVIDER_unload (l->first) == 1); } else { fLoadedProviders_.Add (providerName, *l); } #endif } #endif <|endoftext|>
<commit_before>// The MIT License (MIT) // // Copyright (c) 2013 Patrick Van Oosterwijck // // 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 <node.h> #include <node_buffer.h> #include <v8.h> #include <openssl/evp.h> using namespace v8; using namespace node; // Authentication tag length #define AUTH_TAG_LEN 16 // Exception shortcut Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Free callback to release memory once a Buffer created by MakeBuffer // is released void FreeCallback(char *data, void *hint) { delete [] data; } // Helper function to create a Buffer // Source: https://gist.github.com/drewish/2732711 // Adjusted to prevent save memcpy from source data into Buffer static Local<Object> MakeBuffer(unsigned char *data, size_t size) { HandleScope scope; // It ends up being kind of a pain to convert a slow buffer into a fast // one since the fast part is implemented in JavaScript. Local<Buffer> slowBuffer = Buffer::New((char *)data, size, FreeCallback, NULL); // First get the Buffer from global scope... Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> b = Local<Function>::Cast(bv); // ...call Buffer() with the slow buffer and get a fast buffer back... Handle<Value> argv[3] = { slowBuffer->handle_, Integer::New(size), Integer::New(0) }; Local<Object> fastBuffer = b->NewInstance(3, argv); return scope.Close(fastBuffer); } // Perform GCM mode AES-128 encryption using the provided key, IV, plaintext // and auth_data buffers, and return an object containing "ciphertext" // and "auth_tag" buffers. Handle<Value> GcmEncrypt(const Arguments& args) { HandleScope scope; // We want 4 buffer arguments, key needs to be 16 bytes and IV needs to be // 12 bytes if (args.Length() < 4 || !Buffer::HasInstance(args[0]) || !Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) || !Buffer::HasInstance(args[3]) || Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12) { return VException("encrypt requires a 16-byte key Buffer, a 12-byte " \ "IV Buffer, a plaintext Buffer and an auth_data " \ "Buffer parameter"); } // Make a buffer for the ciphertext that is the same size as the // plaintext, but padded to 16 byte increments size_t plaintext_len = Buffer::Length(args[2]); size_t ciphertext_len = (((plaintext_len - 1) / 16) + 1) * 16; unsigned char *ciphertext = new unsigned char[ciphertext_len]; // Make a authentication tag buffer unsigned char *auth_tag = new unsigned char[AUTH_TAG_LEN]; // Init OpenSSL interace with 128-bit AES GCM cipher and give it the // key and IV int outl; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Pass additional authenticated data // There is some extra complication here because Buffer::Data seems to // return NULL for empty buffers, and NULL makes update not work as we // expect it to. So we force a valid non-NULL pointer for empty buffers. EVP_EncryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ? (unsigned char *)Buffer::Data(args[3]) : auth_tag, Buffer::Length(args[3])); // Encrypt plaintext EVP_EncryptUpdate(ctx, ciphertext, &outl, (unsigned char *)Buffer::Data(args[2]), Buffer::Length(args[2])); // Finalize EVP_EncryptFinal_ex(ctx, ciphertext + outl, &outl); // Get the authentication tag EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, AUTH_TAG_LEN, auth_tag); // Free the OpenSSL interface structure EVP_CIPHER_CTX_free(ctx); // Create the return buffers and object // We strip padding from the ciphertext Local<Object> ciphertext_buf = MakeBuffer(ciphertext, plaintext_len); Local<Object> auth_tag_buf = MakeBuffer(auth_tag, AUTH_TAG_LEN); Local<Object> return_obj = Object::New(); return_obj->Set(String::NewSymbol("ciphertext"), ciphertext_buf); return_obj->Set(String::NewSymbol("auth_tag"), auth_tag_buf); // Return it return scope.Close(return_obj); } // Perform GCM mode AES-128 decryption using the provided key, IV, ciphertext, // auth_data and auth_tag buffers, and return an object containing a "plaintext" // buffer and an "auth_ok" boolean. Handle<Value> GcmDecrypt(const Arguments& args) { HandleScope scope; // We want 5 buffer arguments, key needs to be 16 bytes, IV needs to be // 12 bytes, auth_tag needs to be 16 bytes if (args.Length() < 5 || !Buffer::HasInstance(args[0]) || !Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) || !Buffer::HasInstance(args[3]) || !Buffer::HasInstance(args[4]) || Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12 || Buffer::Length(args[4]) != 16) { return VException("decrypt requires a 16-byte key Buffer, a 12-byte " \ "IV Buffer, a ciphertext Buffer, an auth_data " \ "Buffer and a 16-byte auth_tag Buffer parameter"); } // Make a buffer for the plaintext that is the same size as the // ciphertext, but padded to 16 byte increments size_t ciphertext_len = Buffer::Length(args[2]); size_t plaintext_len = (((ciphertext_len - 1) / 16) + 1) * 16; unsigned char *plaintext = new unsigned char[plaintext_len]; // Init OpenSSL interace with 128-bit AES GCM cipher and give it the // key and IV int outl; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Set the input reference authentication tag EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AUTH_TAG_LEN, Buffer::Data(args[4])); // Example showed we needed to do init again EVP_DecryptInit(ctx, NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Pass additional authenticated data // There is some extra complication here because Buffer::Data seems to // return NULL for empty buffers, and NULL makes update not work as we // expect it to. So we force a valid non-NULL pointer for empty buffers. EVP_DecryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ? (unsigned char *)Buffer::Data(args[3]) : plaintext, Buffer::Length(args[3])); // Decrypt ciphertext EVP_DecryptUpdate(ctx, plaintext, &outl, (unsigned char *)Buffer::Data(args[2]), Buffer::Length(args[2])); // Finalize bool auth_ok = EVP_DecryptFinal_ex(ctx, plaintext + outl, &outl); // Free the OpenSSL interface structure EVP_CIPHER_CTX_free(ctx); // Create the return buffer and object // We strip padding from the plaintext Local<Object> plaintext_buf = MakeBuffer(plaintext, ciphertext_len); Local<Object> return_obj = Object::New(); return_obj->Set(String::NewSymbol("plaintext"), plaintext_buf); return_obj->Set(String::NewSymbol("auth_ok"), Boolean::New(auth_ok)); // Return it return scope.Close(return_obj); } // Module init function void Init(Handle<Object> exports, Handle<Value> module) { exports->Set(String::NewSymbol("encrypt"), FunctionTemplate::New(GcmEncrypt)->GetFunction()); exports->Set(String::NewSymbol("decrypt"), FunctionTemplate::New(GcmDecrypt)->GetFunction()); } NODE_MODULE(node_aes_gcm, Init) <commit_msg>Switched from another deprecated OpenSSL call<commit_after>// The MIT License (MIT) // // Copyright (c) 2013 Patrick Van Oosterwijck // // 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 <node.h> #include <node_buffer.h> #include <v8.h> #include <openssl/evp.h> using namespace v8; using namespace node; // Authentication tag length #define AUTH_TAG_LEN 16 // Exception shortcut Handle<Value> VException(const char *msg) { HandleScope scope; return ThrowException(Exception::Error(String::New(msg))); } // Free callback to release memory once a Buffer created by MakeBuffer // is released void FreeCallback(char *data, void *hint) { delete [] data; } // Helper function to create a Buffer // Source: https://gist.github.com/drewish/2732711 // Adjusted to prevent save memcpy from source data into Buffer static Local<Object> MakeBuffer(unsigned char *data, size_t size) { HandleScope scope; // It ends up being kind of a pain to convert a slow buffer into a fast // one since the fast part is implemented in JavaScript. Local<Buffer> slowBuffer = Buffer::New((char *)data, size, FreeCallback, NULL); // First get the Buffer from global scope... Local<Object> global = Context::GetCurrent()->Global(); Local<Value> bv = global->Get(String::NewSymbol("Buffer")); assert(bv->IsFunction()); Local<Function> b = Local<Function>::Cast(bv); // ...call Buffer() with the slow buffer and get a fast buffer back... Handle<Value> argv[3] = { slowBuffer->handle_, Integer::New(size), Integer::New(0) }; Local<Object> fastBuffer = b->NewInstance(3, argv); return scope.Close(fastBuffer); } // Perform GCM mode AES-128 encryption using the provided key, IV, plaintext // and auth_data buffers, and return an object containing "ciphertext" // and "auth_tag" buffers. Handle<Value> GcmEncrypt(const Arguments& args) { HandleScope scope; // We want 4 buffer arguments, key needs to be 16 bytes and IV needs to be // 12 bytes if (args.Length() < 4 || !Buffer::HasInstance(args[0]) || !Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) || !Buffer::HasInstance(args[3]) || Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12) { return VException("encrypt requires a 16-byte key Buffer, a 12-byte " \ "IV Buffer, a plaintext Buffer and an auth_data " \ "Buffer parameter"); } // Make a buffer for the ciphertext that is the same size as the // plaintext, but padded to 16 byte increments size_t plaintext_len = Buffer::Length(args[2]); size_t ciphertext_len = (((plaintext_len - 1) / 16) + 1) * 16; unsigned char *ciphertext = new unsigned char[ciphertext_len]; // Make a authentication tag buffer unsigned char *auth_tag = new unsigned char[AUTH_TAG_LEN]; // Init OpenSSL interace with 128-bit AES GCM cipher and give it the // key and IV int outl; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_EncryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Pass additional authenticated data // There is some extra complication here because Buffer::Data seems to // return NULL for empty buffers, and NULL makes update not work as we // expect it to. So we force a valid non-NULL pointer for empty buffers. EVP_EncryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ? (unsigned char *)Buffer::Data(args[3]) : auth_tag, Buffer::Length(args[3])); // Encrypt plaintext EVP_EncryptUpdate(ctx, ciphertext, &outl, (unsigned char *)Buffer::Data(args[2]), Buffer::Length(args[2])); // Finalize EVP_EncryptFinal_ex(ctx, ciphertext + outl, &outl); // Get the authentication tag EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, AUTH_TAG_LEN, auth_tag); // Free the OpenSSL interface structure EVP_CIPHER_CTX_free(ctx); // Create the return buffers and object // We strip padding from the ciphertext Local<Object> ciphertext_buf = MakeBuffer(ciphertext, plaintext_len); Local<Object> auth_tag_buf = MakeBuffer(auth_tag, AUTH_TAG_LEN); Local<Object> return_obj = Object::New(); return_obj->Set(String::NewSymbol("ciphertext"), ciphertext_buf); return_obj->Set(String::NewSymbol("auth_tag"), auth_tag_buf); // Return it return scope.Close(return_obj); } // Perform GCM mode AES-128 decryption using the provided key, IV, ciphertext, // auth_data and auth_tag buffers, and return an object containing a "plaintext" // buffer and an "auth_ok" boolean. Handle<Value> GcmDecrypt(const Arguments& args) { HandleScope scope; // We want 5 buffer arguments, key needs to be 16 bytes, IV needs to be // 12 bytes, auth_tag needs to be 16 bytes if (args.Length() < 5 || !Buffer::HasInstance(args[0]) || !Buffer::HasInstance(args[1]) || !Buffer::HasInstance(args[2]) || !Buffer::HasInstance(args[3]) || !Buffer::HasInstance(args[4]) || Buffer::Length(args[0]) != 16 || Buffer::Length(args[1]) != 12 || Buffer::Length(args[4]) != 16) { return VException("decrypt requires a 16-byte key Buffer, a 12-byte " \ "IV Buffer, a ciphertext Buffer, an auth_data " \ "Buffer and a 16-byte auth_tag Buffer parameter"); } // Make a buffer for the plaintext that is the same size as the // ciphertext, but padded to 16 byte increments size_t ciphertext_len = Buffer::Length(args[2]); size_t plaintext_len = (((ciphertext_len - 1) / 16) + 1) * 16; unsigned char *plaintext = new unsigned char[plaintext_len]; // Init OpenSSL interace with 128-bit AES GCM cipher and give it the // key and IV int outl; EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); EVP_DecryptInit_ex(ctx, EVP_aes_128_gcm(), NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Set the input reference authentication tag EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, AUTH_TAG_LEN, Buffer::Data(args[4])); // Example showed we needed to do init again EVP_DecryptInit_ex(ctx, NULL, NULL, (unsigned char *)Buffer::Data(args[0]), (unsigned char *)Buffer::Data(args[1])); // Pass additional authenticated data // There is some extra complication here because Buffer::Data seems to // return NULL for empty buffers, and NULL makes update not work as we // expect it to. So we force a valid non-NULL pointer for empty buffers. EVP_DecryptUpdate(ctx, NULL, &outl, Buffer::Length(args[3]) ? (unsigned char *)Buffer::Data(args[3]) : plaintext, Buffer::Length(args[3])); // Decrypt ciphertext EVP_DecryptUpdate(ctx, plaintext, &outl, (unsigned char *)Buffer::Data(args[2]), Buffer::Length(args[2])); // Finalize bool auth_ok = EVP_DecryptFinal_ex(ctx, plaintext + outl, &outl); // Free the OpenSSL interface structure EVP_CIPHER_CTX_free(ctx); // Create the return buffer and object // We strip padding from the plaintext Local<Object> plaintext_buf = MakeBuffer(plaintext, ciphertext_len); Local<Object> return_obj = Object::New(); return_obj->Set(String::NewSymbol("plaintext"), plaintext_buf); return_obj->Set(String::NewSymbol("auth_ok"), Boolean::New(auth_ok)); // Return it return scope.Close(return_obj); } // Module init function void Init(Handle<Object> exports, Handle<Value> module) { exports->Set(String::NewSymbol("encrypt"), FunctionTemplate::New(GcmEncrypt)->GetFunction()); exports->Set(String::NewSymbol("decrypt"), FunctionTemplate::New(GcmDecrypt)->GetFunction()); } NODE_MODULE(node_aes_gcm, Init) <|endoftext|>
<commit_before>/* indent-tabs-mode: nil -*- */ /* odbc-module.cpp Qore ODBC module Copyright (C) 2016 Ondrej Musil 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 <sql.h> #include <sqlext.h> #include "qore/Qore.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ODBCConnection.h" #include "ODBCPreparedStatement.h" QoreStringNode *odbc_module_init(); void odbc_module_ns_init(QoreNamespace *rns, QoreNamespace *qns); void odbc_module_delete(); // qore module symbols DLLEXPORT char qore_module_name[] = "odbc"; DLLEXPORT char qore_module_version[] = PACKAGE_VERSION; DLLEXPORT char qore_module_description[] = "ODBC database driver module"; DLLEXPORT char qore_module_author[] = "Ondrej Musil <ondrej.musil@qoretechnologies.com>"; DLLEXPORT char qore_module_url[] = "http://qore.org"; DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR; DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR; DLLEXPORT qore_module_init_t qore_module_init = odbc_module_init; DLLEXPORT qore_module_ns_init_t qore_module_ns_init = odbc_module_ns_init; DLLEXPORT qore_module_delete_t qore_module_delete = odbc_module_delete; DLLEXPORT qore_license_t qore_module_license = QL_MIT; DLLEXPORT char qore_module_license_str[] = "MIT"; static DBIDriver* DBID_ODBC; // capabilities of this driver int DBI_ODBC_CAPS = DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER | DBI_CAP_HAS_ARRAY_BIND | DBI_CAP_HAS_NUMBER_SUPPORT | DBI_CAP_AUTORECONNECT #ifdef _QORE_HAS_DBI_EXECRAW | DBI_CAP_HAS_EXECRAW #endif #ifdef _QORE_HAS_TIME_ZONES | DBI_CAP_TIME_ZONE_SUPPORT #endif #ifdef _QORE_HAS_FIND_CREATE_TIMEZONE | DBI_CAP_SERVER_TIME_ZONE #endif ; static int odbc_open(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = new ODBCConnection(ds, xsink); if (*xsink) { delete conn; return -1; } ds->setPrivateData((void*)conn); return 0; } static int odbc_close(Datasource* ds) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); ds->setPrivateData(0); delete conn; return 0; } static AbstractQoreNode* odbc_select(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->exec(qstr, args, xsink); } #ifdef _QORE_HAS_DBI_SELECT_ROW static QoreHashNode* odbc_select_row(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->selectRow(qstr, args, xsink); } #endif static AbstractQoreNode* odbc_select_rows(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->selectRows(qstr, args, xsink); } static AbstractQoreNode* odbc_exec(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->exec(qstr, args, xsink); } #ifdef _QORE_HAS_DBI_EXECRAW static AbstractQoreNode* odbc_execRaw(Datasource* ds, const QoreString* qstr, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->execRaw(qstr, xsink); } #endif static int odbc_begin_transaction(Datasource* ds, ExceptionSink* xsink) { return 0; } static int odbc_commit(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->commit(xsink); } static int odbc_rollback(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->rollback(xsink); } static AbstractQoreNode* odbc_get_client_version(const Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return new QoreBigIntNode(conn->getClientVersion()); } static AbstractQoreNode* odbc_get_server_version(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return new QoreBigIntNode(conn->getServerVersion()); } static int odbc_stmt_prepare(SQLStatement* stmt, const QoreString& str, const QoreListNode* args, ExceptionSink* xsink) { assert(!stmt->getPrivateData()); ODBCPreparedStatement* ps = new ODBCPreparedStatement(stmt->getDatasource(), xsink); if (*xsink) { delete ps; return -1; } stmt->setPrivateData(ps); return ps->prepare(str, args, xsink); } static int odbc_stmt_prepare_raw(SQLStatement* stmt, const QoreString& str, ExceptionSink* xsink) { assert(!stmt->getPrivateData()); ODBCPreparedStatement* ps = new ODBCPreparedStatement(stmt->getDatasource(), xsink); if (*xsink) { delete ps; return -1; } stmt->setPrivateData(ps); return ps->prepare(str, 0, xsink); } static int odbc_stmt_bind(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->bind(args, xsink); } static int odbc_stmt_bind_placeholders(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { xsink->raiseException("DBI:ODBC:BIND-PLACEHHODERS-ERROR", "binding placeholders is not necessary or supported with the odbc driver"); return -1; } static int odbc_stmt_bind_values(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->bind(args, xsink); } static int odbc_stmt_exec(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->exec(xsink); } static int odbc_stmt_define(SQLStatement* stmt, ExceptionSink* xsink) { // define is a noop in the odbc driver return 0; } static int odbc_stmt_affected_rows(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->rowsAffected(); } static QoreHashNode* odbc_stmt_get_output(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->getOutputHash(xsink, false); } static QoreHashNode* odbc_stmt_get_output_rows(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->getOutputHash(xsink, false); } static QoreHashNode* odbc_stmt_fetch_row(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchRow(xsink); } static QoreListNode* odbc_stmt_fetch_rows(SQLStatement* stmt, int maxRows, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchRows(maxRows, xsink); } static QoreHashNode* odbc_stmt_fetch_columns(SQLStatement* stmt, int maxRows, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchColumns(maxRows, xsink); } static QoreHashNode* odbc_stmt_describe(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->describe(xsink); } static bool odbc_stmt_next(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->next(xsink); } static int odbc_stmt_close(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); delete ps; stmt->setPrivateData(0); return *xsink ? -1 : 0; } static int odbc_opt_set(Datasource* ds, const char* opt, const AbstractQoreNode* val, ExceptionSink* xsink) { ODBCConnection* conn = (ODBCConnection*)ds->getPrivateData(); return conn->setOption(opt, val, xsink); } static AbstractQoreNode* odbc_opt_get(const Datasource* ds, const char* opt) { ODBCConnection* conn = (ODBCConnection*)ds->getPrivateData(); return conn->getOption(opt); } QoreNamespace OdbcNS("odbc"); QoreStringNode *odbc_module_init() { qore_dbi_method_list methods; methods.add(QDBI_METHOD_OPEN, odbc_open); methods.add(QDBI_METHOD_CLOSE, odbc_close); methods.add(QDBI_METHOD_SELECT, odbc_exec); #ifdef _QORE_HAS_DBI_SELECT_ROW methods.add(QDBI_METHOD_SELECT_ROW, odbc_select_row); #endif methods.add(QDBI_METHOD_SELECT_ROWS, odbc_select_rows); methods.add(QDBI_METHOD_EXEC, odbc_exec); #ifdef _QORE_HAS_DBI_EXECRAW methods.add(QDBI_METHOD_EXECRAW, odbc_execRaw); #endif methods.add(QDBI_METHOD_COMMIT, odbc_commit); methods.add(QDBI_METHOD_ROLLBACK, odbc_rollback); methods.add(QDBI_METHOD_BEGIN_TRANSACTION, odbc_begin_transaction); methods.add(QDBI_METHOD_ABORT_TRANSACTION_START, odbc_rollback); methods.add(QDBI_METHOD_GET_CLIENT_VERSION, odbc_get_client_version); methods.add(QDBI_METHOD_GET_SERVER_VERSION, odbc_get_server_version); methods.add(QDBI_METHOD_STMT_PREPARE, odbc_stmt_prepare); methods.add(QDBI_METHOD_STMT_PREPARE_RAW, odbc_stmt_prepare_raw); methods.add(QDBI_METHOD_STMT_BIND, odbc_stmt_bind); methods.add(QDBI_METHOD_STMT_BIND_PLACEHOLDERS, odbc_stmt_bind_placeholders); methods.add(QDBI_METHOD_STMT_BIND_VALUES, odbc_stmt_bind_values); methods.add(QDBI_METHOD_STMT_EXEC, odbc_stmt_exec); methods.add(QDBI_METHOD_STMT_DEFINE, odbc_stmt_define); methods.add(QDBI_METHOD_STMT_FETCH_ROW, odbc_stmt_fetch_row); methods.add(QDBI_METHOD_STMT_FETCH_ROWS, odbc_stmt_fetch_rows); methods.add(QDBI_METHOD_STMT_FETCH_COLUMNS, odbc_stmt_fetch_columns); methods.add(QDBI_METHOD_STMT_DESCRIBE, odbc_stmt_describe); methods.add(QDBI_METHOD_STMT_NEXT, odbc_stmt_next); methods.add(QDBI_METHOD_STMT_CLOSE, odbc_stmt_close); methods.add(QDBI_METHOD_STMT_AFFECTED_ROWS, odbc_stmt_affected_rows); methods.add(QDBI_METHOD_STMT_GET_OUTPUT, odbc_stmt_get_output); methods.add(QDBI_METHOD_STMT_GET_OUTPUT_ROWS, odbc_stmt_get_output_rows); methods.add(QDBI_METHOD_OPT_SET, odbc_opt_set); methods.add(QDBI_METHOD_OPT_GET, odbc_opt_get); methods.registerOption(DBI_OPT_NUMBER_OPT, "when set, numeric/decimal values are returned as integers if possible, otherwise as arbitrary-precision number values; the argument is ignored; setting this option turns it on and turns off 'string-numbers' and 'numeric-numbers'"); methods.registerOption(DBI_OPT_NUMBER_STRING, "when set, numeric/decimal values are returned as strings for backwards-compatibility; the argument is ignored; setting this option turns it on and turns off 'optimal-numbers' and 'numeric-numbers'"); methods.registerOption(DBI_OPT_NUMBER_NUMERIC, "when set, numeric/decimal values are returned as arbitrary-precision number values; the argument is ignored; setting this option turns it on and turns off 'string-numbers' and 'optimal-numbers'"); DBID_ODBC = DBI.registerDriver("odbc", methods, DBI_ODBC_CAPS); return 0; } void odbc_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) { qns->addNamespace(OdbcNS.copy()); } void odbc_module_delete() { // nothing to do here in this case } <commit_msg>Fixed whitespace.<commit_after>/* indent-tabs-mode: nil -*- */ /* odbc-module.cpp Qore ODBC module Copyright (C) 2016 Ondrej Musil 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 <sql.h> #include <sqlext.h> #include "qore/Qore.h" #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "ODBCConnection.h" #include "ODBCPreparedStatement.h" QoreStringNode *odbc_module_init(); void odbc_module_ns_init(QoreNamespace *rns, QoreNamespace *qns); void odbc_module_delete(); // qore module symbols DLLEXPORT char qore_module_name[] = "odbc"; DLLEXPORT char qore_module_version[] = PACKAGE_VERSION; DLLEXPORT char qore_module_description[] = "ODBC database driver module"; DLLEXPORT char qore_module_author[] = "Ondrej Musil <ondrej.musil@qoretechnologies.com>"; DLLEXPORT char qore_module_url[] = "http://qore.org"; DLLEXPORT int qore_module_api_major = QORE_MODULE_API_MAJOR; DLLEXPORT int qore_module_api_minor = QORE_MODULE_API_MINOR; DLLEXPORT qore_module_init_t qore_module_init = odbc_module_init; DLLEXPORT qore_module_ns_init_t qore_module_ns_init = odbc_module_ns_init; DLLEXPORT qore_module_delete_t qore_module_delete = odbc_module_delete; DLLEXPORT qore_license_t qore_module_license = QL_MIT; DLLEXPORT char qore_module_license_str[] = "MIT"; static DBIDriver* DBID_ODBC; // capabilities of this driver int DBI_ODBC_CAPS = DBI_CAP_TRANSACTION_MANAGEMENT | DBI_CAP_CHARSET_SUPPORT | DBI_CAP_LOB_SUPPORT | DBI_CAP_STORED_PROCEDURES | DBI_CAP_BIND_BY_VALUE | DBI_CAP_BIND_BY_PLACEHOLDER | DBI_CAP_HAS_ARRAY_BIND | DBI_CAP_HAS_NUMBER_SUPPORT | DBI_CAP_AUTORECONNECT #ifdef _QORE_HAS_DBI_EXECRAW | DBI_CAP_HAS_EXECRAW #endif #ifdef _QORE_HAS_TIME_ZONES | DBI_CAP_TIME_ZONE_SUPPORT #endif #ifdef _QORE_HAS_FIND_CREATE_TIMEZONE | DBI_CAP_SERVER_TIME_ZONE #endif ; static int odbc_open(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = new ODBCConnection(ds, xsink); if (*xsink) { delete conn; return -1; } ds->setPrivateData((void*)conn); return 0; } static int odbc_close(Datasource* ds) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); ds->setPrivateData(0); delete conn; return 0; } static AbstractQoreNode* odbc_select(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->exec(qstr, args, xsink); } #ifdef _QORE_HAS_DBI_SELECT_ROW static QoreHashNode* odbc_select_row(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->selectRow(qstr, args, xsink); } #endif static AbstractQoreNode* odbc_select_rows(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->selectRows(qstr, args, xsink); } static AbstractQoreNode* odbc_exec(Datasource* ds, const QoreString* qstr, const QoreListNode* args, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->exec(qstr, args, xsink); } #ifdef _QORE_HAS_DBI_EXECRAW static AbstractQoreNode* odbc_execRaw(Datasource* ds, const QoreString* qstr, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->execRaw(qstr, xsink); } #endif static int odbc_begin_transaction(Datasource* ds, ExceptionSink* xsink) { return 0; } static int odbc_commit(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->commit(xsink); } static int odbc_rollback(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return conn->rollback(xsink); } static AbstractQoreNode* odbc_get_client_version(const Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return new QoreBigIntNode(conn->getClientVersion()); } static AbstractQoreNode* odbc_get_server_version(Datasource* ds, ExceptionSink* xsink) { ODBCConnection* conn = static_cast<ODBCConnection *>(ds->getPrivateData()); return new QoreBigIntNode(conn->getServerVersion()); } static int odbc_stmt_prepare(SQLStatement* stmt, const QoreString& str, const QoreListNode* args, ExceptionSink* xsink) { assert(!stmt->getPrivateData()); ODBCPreparedStatement* ps = new ODBCPreparedStatement(stmt->getDatasource(), xsink); if (*xsink) { delete ps; return -1; } stmt->setPrivateData(ps); return ps->prepare(str, args, xsink); } static int odbc_stmt_prepare_raw(SQLStatement* stmt, const QoreString& str, ExceptionSink* xsink) { assert(!stmt->getPrivateData()); ODBCPreparedStatement* ps = new ODBCPreparedStatement(stmt->getDatasource(), xsink); if (*xsink) { delete ps; return -1; } stmt->setPrivateData(ps); return ps->prepare(str, 0, xsink); } static int odbc_stmt_bind(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->bind(args, xsink); } static int odbc_stmt_bind_placeholders(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { xsink->raiseException("DBI:ODBC:BIND-PLACEHHODERS-ERROR", "binding placeholders is not necessary or supported with the odbc driver"); return -1; } static int odbc_stmt_bind_values(SQLStatement* stmt, const QoreListNode& args, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->bind(args, xsink); } static int odbc_stmt_exec(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->exec(xsink); } static int odbc_stmt_define(SQLStatement* stmt, ExceptionSink* xsink) { // define is a noop in the odbc driver return 0; } static int odbc_stmt_affected_rows(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->rowsAffected(); } static QoreHashNode* odbc_stmt_get_output(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->getOutputHash(xsink, false); } static QoreHashNode* odbc_stmt_get_output_rows(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->getOutputHash(xsink, false); } static QoreHashNode* odbc_stmt_fetch_row(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchRow(xsink); } static QoreListNode* odbc_stmt_fetch_rows(SQLStatement* stmt, int maxRows, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchRows(maxRows, xsink); } static QoreHashNode* odbc_stmt_fetch_columns(SQLStatement* stmt, int maxRows, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->fetchColumns(maxRows, xsink); } static QoreHashNode* odbc_stmt_describe(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->describe(xsink); } static bool odbc_stmt_next(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); return ps->next(xsink); } static int odbc_stmt_close(SQLStatement* stmt, ExceptionSink* xsink) { ODBCPreparedStatement* ps = static_cast<ODBCPreparedStatement*>(stmt->getPrivateData()); assert(ps); delete ps; stmt->setPrivateData(0); return *xsink ? -1 : 0; } static int odbc_opt_set(Datasource* ds, const char* opt, const AbstractQoreNode* val, ExceptionSink* xsink) { ODBCConnection* conn = (ODBCConnection*)ds->getPrivateData(); return conn->setOption(opt, val, xsink); } static AbstractQoreNode* odbc_opt_get(const Datasource* ds, const char* opt) { ODBCConnection* conn = (ODBCConnection*)ds->getPrivateData(); return conn->getOption(opt); } QoreNamespace OdbcNS("odbc"); QoreStringNode *odbc_module_init() { qore_dbi_method_list methods; methods.add(QDBI_METHOD_OPEN, odbc_open); methods.add(QDBI_METHOD_CLOSE, odbc_close); methods.add(QDBI_METHOD_SELECT, odbc_exec); #ifdef _QORE_HAS_DBI_SELECT_ROW methods.add(QDBI_METHOD_SELECT_ROW, odbc_select_row); #endif methods.add(QDBI_METHOD_SELECT_ROWS, odbc_select_rows); methods.add(QDBI_METHOD_EXEC, odbc_exec); #ifdef _QORE_HAS_DBI_EXECRAW methods.add(QDBI_METHOD_EXECRAW, odbc_execRaw); #endif methods.add(QDBI_METHOD_COMMIT, odbc_commit); methods.add(QDBI_METHOD_ROLLBACK, odbc_rollback); methods.add(QDBI_METHOD_BEGIN_TRANSACTION, odbc_begin_transaction); methods.add(QDBI_METHOD_ABORT_TRANSACTION_START, odbc_rollback); methods.add(QDBI_METHOD_GET_CLIENT_VERSION, odbc_get_client_version); methods.add(QDBI_METHOD_GET_SERVER_VERSION, odbc_get_server_version); methods.add(QDBI_METHOD_STMT_PREPARE, odbc_stmt_prepare); methods.add(QDBI_METHOD_STMT_PREPARE_RAW, odbc_stmt_prepare_raw); methods.add(QDBI_METHOD_STMT_BIND, odbc_stmt_bind); methods.add(QDBI_METHOD_STMT_BIND_PLACEHOLDERS, odbc_stmt_bind_placeholders); methods.add(QDBI_METHOD_STMT_BIND_VALUES, odbc_stmt_bind_values); methods.add(QDBI_METHOD_STMT_EXEC, odbc_stmt_exec); methods.add(QDBI_METHOD_STMT_DEFINE, odbc_stmt_define); methods.add(QDBI_METHOD_STMT_FETCH_ROW, odbc_stmt_fetch_row); methods.add(QDBI_METHOD_STMT_FETCH_ROWS, odbc_stmt_fetch_rows); methods.add(QDBI_METHOD_STMT_FETCH_COLUMNS, odbc_stmt_fetch_columns); methods.add(QDBI_METHOD_STMT_DESCRIBE, odbc_stmt_describe); methods.add(QDBI_METHOD_STMT_NEXT, odbc_stmt_next); methods.add(QDBI_METHOD_STMT_CLOSE, odbc_stmt_close); methods.add(QDBI_METHOD_STMT_AFFECTED_ROWS, odbc_stmt_affected_rows); methods.add(QDBI_METHOD_STMT_GET_OUTPUT, odbc_stmt_get_output); methods.add(QDBI_METHOD_STMT_GET_OUTPUT_ROWS, odbc_stmt_get_output_rows); methods.add(QDBI_METHOD_OPT_SET, odbc_opt_set); methods.add(QDBI_METHOD_OPT_GET, odbc_opt_get); methods.registerOption(DBI_OPT_NUMBER_OPT, "when set, numeric/decimal values are returned as integers if possible, otherwise as arbitrary-precision number values; the argument is ignored; setting this option turns it on and turns off 'string-numbers' and 'numeric-numbers'"); methods.registerOption(DBI_OPT_NUMBER_STRING, "when set, numeric/decimal values are returned as strings for backwards-compatibility; the argument is ignored; setting this option turns it on and turns off 'optimal-numbers' and 'numeric-numbers'"); methods.registerOption(DBI_OPT_NUMBER_NUMERIC, "when set, numeric/decimal values are returned as arbitrary-precision number values; the argument is ignored; setting this option turns it on and turns off 'string-numbers' and 'optimal-numbers'"); DBID_ODBC = DBI.registerDriver("odbc", methods, DBI_ODBC_CAPS); return 0; } void odbc_module_ns_init(QoreNamespace *rns, QoreNamespace *qns) { qns->addNamespace(OdbcNS.copy()); } void odbc_module_delete() { // nothing to do here in this case } <|endoftext|>
<commit_before>/*! \file omproutines.cxx * \brief this file contains routines used with OpenMP compilation. OpenMP routines pertaining to complex OpenMP calls. */ #ifdef USEOPENMP //-- For MPI #include "stf.h" /// \name routines which check to see if some search region overlaps with local mpi domain //@{ ///construct omp domains OMP_Domain *OpenMPBuildDomains(Options &opt, const Int_t numompregions, KDTree *&tree, const Double_t rdist) { OMP_Domain *ompdomain = new OMP_Domain[numompregions]; Int_t noffset=0; Node *np; for (auto i=0;i<numompregions;i++) { np = (tree->FindLeafNode(noffset)); ompdomain[i].ncount = np->GetCount(); ompdomain[i].noffset = noffset; for (int j=0;j<3;j++) { ompdomain[i].bnd[j][0]=np->GetBoundary(j,0)*0.99; ompdomain[i].bnd[j][1]=np->GetBoundary(j,1)*1.01; } noffset+=ompdomain[i].ncount; } //determine for each omp region, what are neighbour omp regions within rdist Double_t xsearch[3][2]; for (auto i=0;i<numompregions;i++) { for (auto k=0;k<3;k++) {xsearch[k][0]=ompdomain[i].bnd[k][0]-rdist;xsearch[k][0]=ompdomain[i].bnd[k][1]+rdist;} for (auto j=0;j<numompregions;j++) if (j!=i){ if (OpenMPSearchForOverlap(xsearch,ompdomain[j].bnd, opt.p)) ompdomain[i].neighbour.push_back(j); } noffset+=ompdomain[i].ncount; } np=NULL; return ompdomain; } KDTree **OpenMPBuildLocalTrees(Options &opt, const Int_t numompregions, vector<Particle> &Part, OMP_Domain *ompdomain, Double_t *period) { KDTree **tree3dfofomp = new KDTree*[numompregions]; Int_t i; //get fof in each region #pragma omp parallel default(shared) \ private(i) { #pragma omp for schedule(dynamic) nowait for (i=0;i<numompregions;i++) { tree3dfofomp[i] = new KDTree(&Part.data()[ompdomain[i].noffset],ompdomain[i].ncount,opt.Bsize,tree3dfofomp[i]->TPHYS,tree3dfofomp[i]->KEPAN,100,0,0,0,period); } } return tree3dfofomp; } ///search if some region is in the local mpi domain int OpenMPSearchForOverlap(Double_t xsearch[3][2], Double_t bnd[3][2], Double_t period){ Double_t xsearchp[3][2]; if (!((bnd[0][1] < xsearch[0][0]) || (bnd[0][0] > xsearch[0][1]) || (bnd[1][1] < xsearch[1][0]) || (bnd[1][0] > xsearch[1][1]) || (bnd[2][1] < xsearch[2][0]) || (bnd[2][0] > xsearch[2][1]))) return 1; else { if (period==0) return 0; else { for (int j=0;j<3;j++) {xsearchp[j][0]=xsearch[j][0];xsearchp[j][1]=xsearch[j][1];} for (int j=0;j<3;j++) { if (!((bnd[j][1] < xsearch[j][0]+period) || (bnd[j][0] > xsearch[j][1]+period))) {xsearchp[j][0]+=period;xsearchp[j][1]+=period;} else if (!((bnd[j][1] < xsearch[j][0]-period) || (bnd[j][0] > xsearch[j][1]-period))) {xsearchp[j][0]-=period;xsearchp[j][1]-=period;} } if (!((bnd[0][1] < xsearchp[0][0]) || (bnd[0][0] > xsearchp[0][1]) || (bnd[1][1] < xsearchp[1][0]) || (bnd[1][0] > xsearchp[1][1]) || (bnd[2][1] < xsearchp[2][0]) || (bnd[2][0] > xsearchp[2][1]))) return 1; else return 0; } } } /// Determine if a particle needs to be exported to another mpi domain based on a physical search radius int OpenMPSearchForOverlap(Particle &Part, Double_t bnd[3][2], Double_t rdist, Double_t period){ Double_t xsearch[3][2]; for (auto k=0;k<3;k++) {xsearch[k][0]=Part.GetPosition(k)-rdist;xsearch[k][1]=Part.GetPosition(k)+rdist;} return OpenMPSearchForOverlap(xsearch,bnd,period); } ///Saerch particles to see if they overlap other OpenMP domains Particle *OpenMPImportParticles(Options &opt, const Int_t nbodies, vector<Particle> &Part, Int_t * &pfof, Int_t *&storetype, const Int_t numompregions, OMP_Domain *&ompdomain, const Double_t rdist, Int_t *&omp_nrecv_total, Int_t *&omp_nrecv_offset) { Int_t i,orgIndex; int omptask; Int_t importtotal=0; double time1=MyGetTime(); Particle *Partompimport; Int_t *Partompimportindex; #ifndef USEMPI int ThisTask=0,NProcs=1; #endif cout<<ThisTask<<": Starting import build "<<endl; for (i=0;i<numompregions;i++) omp_nrecv_total[i]=omp_nrecv_offset[i]=0; #pragma omp parallel default(shared) \ private(i,orgIndex,omptask) { #pragma omp for for (i=0;i<numompregions;i++) { for (auto j=ompdomain[i].noffset;j<ompdomain[i].noffset+ompdomain[i].ncount;j++) { orgIndex = storetype[Part[j].GetID()+ompdomain[i].noffset]; if (pfof[orgIndex] == 0) continue; //for (auto k=0;k<numompregions;k++) if (k!=i) { for (auto k: ompdomain[i].neighbour) { if (OpenMPSearchForOverlap(Part[i],ompdomain[k].bnd,rdist,opt.p)) omp_nrecv_total[k] += 1; } } } } for (i=1;i<numompregions;i++) omp_nrecv_offset[i] = omp_nrecv_offset[i-1]+omp_nrecv_total[i-1]; for (i=0;i<numompregions;i++) { if (opt.iverbose > 1) cout<<ThisTask<<" omp region "<<i<<" is importing "<<omp_nrecv_total[i]<<endl; importtotal += omp_nrecv_total[i]; omp_nrecv_total[i] = 0; } Partompimport = new Particle[importtotal]; #pragma omp parallel default(shared) \ private(i,orgIndex,omptask) { #pragma omp for for (i=0;i<numompregions;i++) { for (auto j=ompdomain[i].noffset;j<ompdomain[i].noffset+ompdomain[i].ncount;j++) { orgIndex = storetype[Part[j].GetID()+ompdomain[i].noffset]; if (pfof[orgIndex] == 0) continue; //for (auto k=0;k<numompregions;k++) if (k!=i) { for (auto k: ompdomain[i].neighbour) { if (OpenMPSearchForOverlap(Part[i],ompdomain[k].bnd,rdist,opt.p)) { Partompimport[omp_nrecv_total[k]+omp_nrecv_offset[k]] = Part[j]; Partompimport[omp_nrecv_total[k]+omp_nrecv_offset[k]].SetID(pfof[orgIndex]); omp_nrecv_total[k] += 1; } } } } } cout<<ThisTask<<" finished import "<<MyGetTime()-time1<<endl; return Partompimport; } void OpenMPLinkAcross(Options &opt, Int_t nbodies, vector<Particle> &Part, Int_t * &pfof, Int_t *&storetype, Int_tree_t *&Head, Int_tree_t *&Next, Double_t *param, FOFcheckfunc &fofcheck, const Int_t numompregions, OMP_Domain *&ompdomain, KDTree **tree3dfofomp, Int_t *&omp_nrecv_total, Int_t *&omp_nrecv_offset, Particle* &Partompimport) { //now begin linking across Int_t i; Int_t omp_links_across_total; Int_t nt, orgIndex, curIndex, *nn=new Int_t[nbodies]; Coordinate x; double time1=MyGetTime(); #ifndef USEMPI int ThisTask=0,NProcs=1; #endif cout<<ThisTask<<": Starting linking across OpenMP domains"<<endl; do { omp_links_across_total = 0; #pragma omp parallel default(shared) \ private(i,orgIndex,curIndex, x, nt) { #pragma omp for schedule(dynamic,1) nowait reduction(+:omp_links_across_total) for (i=0;i<numompregions;i++) { for (auto j=0;j<omp_nrecv_total[i];j++) { //for each imported particle, find all particles within search window for (auto k=0;k<3;k++) x[k]=Partompimport[omp_nrecv_offset[i]+j].GetPosition(k); nt=tree3dfofomp[i]->SearchBallPosTagged(x, param[1], &nn[ompdomain[i].noffset]); for (auto k=0;k<nt;k++) { curIndex=nn[k+ompdomain[i].noffset]+ompdomain[i].noffset; //check that at least on of the particles meets the type criterion if necessary if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (fofcheck(Part[curIndex],param)!=0 && fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)!=0) continue; orgIndex = storetype[Part[curIndex].GetID()+ompdomain[i].noffset]; //otherwise, change these particles to local group id if local group id smaller //if local particle in a group if (pfof[orgIndex]>0) { //only change if both particles are appropriate type and group ids indicate local needs to be exported if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (!(fofcheck(Part[curIndex],param)==0 && fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)==0)) continue; //if local group id is larger, change locally if(pfof[orgIndex] > Partompimport[omp_nrecv_offset[i]+j].GetPID()) { Int_t ss = Head[nn[k+ompdomain[i].noffset]+ompdomain[i].noffset]; do{ orgIndex = storetype[Part[ss+ompdomain[i].noffset].GetID()+ompdomain[i].noffset]; pfof[orgIndex]=Partompimport[omp_nrecv_offset[i]+j].GetPID(); }while((ss = Next[ss+ompdomain[i].noffset]) >= 0); omp_links_across_total++; } } //if local particle not in a group and export is appropriate type, link else { if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)!=0) continue; pfof[orgIndex]=Partompimport[omp_nrecv_offset[i]+j].GetPID(); omp_links_across_total++; } } } } } }while(omp_links_across_total>0); delete[] nn; cout<<ThisTask<<" finished linking "<<MyGetTime()-time1<<endl; } Int_t OpenMPResortParticleandGroups(Int_t nbodies, vector<Particle> &Part, Int_t *&pfof, Int_t minsize) { Int_t start, ngroups=0; Int_t *numingroup, **plist; //now get number of groups and reorder group ids for (auto i=0;i<nbodies;i++) Part[i].SetID(-pfof[i]); //used to use ID store store group id info qsort(Part.data(),nbodies,sizeof(Particle),IDCompare); //determine the # of groups, their size and the current group ID for (auto i=0,start=0;i<nbodies;i++) { if (Part[i].GetID()!=Part[start].GetID()) { //if group is too small set type to zero, which currently is used to store the group id if ((i-start)<minsize) for (Int_t j=start;j<i;j++) Part[j].SetID(0); else ngroups++; start=i; } if (Part[i].GetID()==0) break; } //again resort to move untagged particles to the end. qsort(Part.data(),nbodies,sizeof(Particle),IDCompare); //now adjust pfof and ids. for (auto i=0;i<nbodies;i++) {pfof[i]=-Part[i].GetID();Part[i].SetID(i);} numingroup=new Int_t[ngroups+1]; plist=new Int_t*[ngroups+1]; ngroups=1;//offset as group zero is untagged for (auto i=0,start=0;i<nbodies;i++) { if (pfof[i]!=pfof[start]) { numingroup[ngroups]=i-start; plist[ngroups]=new Int_t[numingroup[ngroups]]; for (auto j=start,count=0;j<i;j++) plist[ngroups][count++]=j; ngroups++; start=i; } if (pfof[i]==0) break; } ngroups--; //reorder groups ids according to size ReorderGroupIDs(ngroups,ngroups,numingroup,pfof,plist); for (auto i=1;i<=ngroups;i++) delete[] plist[i]; delete[] plist; delete[] numingroup; return ngroups; } //@} #endif <commit_msg>bug fix<commit_after>/*! \file omproutines.cxx * \brief this file contains routines used with OpenMP compilation. OpenMP routines pertaining to complex OpenMP calls. */ #ifdef USEOPENMP //-- For MPI #include "stf.h" /// \name routines which check to see if some search region overlaps with local mpi domain //@{ ///construct omp domains OMP_Domain *OpenMPBuildDomains(Options &opt, const Int_t numompregions, KDTree *&tree, const Double_t rdist) { OMP_Domain *ompdomain = new OMP_Domain[numompregions]; Int_t noffset=0; Node *np; for (auto i=0;i<numompregions;i++) { np = (tree->FindLeafNode(noffset)); ompdomain[i].ncount = np->GetCount(); ompdomain[i].noffset = noffset; for (int j=0;j<3;j++) { ompdomain[i].bnd[j][0]=np->GetBoundary(j,0)*0.99; ompdomain[i].bnd[j][1]=np->GetBoundary(j,1)*1.01; } noffset+=ompdomain[i].ncount; } //determine for each omp region, what are neighbour omp regions within rdist Double_t xsearch[3][2]; for (auto i=0;i<numompregions;i++) { for (auto k=0;k<3;k++) {xsearch[k][0]=ompdomain[i].bnd[k][0]-rdist;xsearch[k][1]=ompdomain[i].bnd[k][1]+rdist;} for (auto j=0;j<numompregions;j++) if (j!=i){ if (OpenMPSearchForOverlap(xsearch,ompdomain[j].bnd, opt.p)) ompdomain[i].neighbour.push_back(j); } noffset+=ompdomain[i].ncount; } np=NULL; return ompdomain; } KDTree **OpenMPBuildLocalTrees(Options &opt, const Int_t numompregions, vector<Particle> &Part, OMP_Domain *ompdomain, Double_t *period) { KDTree **tree3dfofomp = new KDTree*[numompregions]; Int_t i; //get fof in each region #pragma omp parallel default(shared) \ private(i) { #pragma omp for schedule(dynamic) nowait for (i=0;i<numompregions;i++) { tree3dfofomp[i] = new KDTree(&Part.data()[ompdomain[i].noffset],ompdomain[i].ncount,opt.Bsize,tree3dfofomp[i]->TPHYS,tree3dfofomp[i]->KEPAN,100,0,0,0,period); } } return tree3dfofomp; } ///search if some region is in the local mpi domain int OpenMPSearchForOverlap(Double_t xsearch[3][2], Double_t bnd[3][2], Double_t period){ Double_t xsearchp[3][2]; if (!((bnd[0][1] < xsearch[0][0]) || (bnd[0][0] > xsearch[0][1]) || (bnd[1][1] < xsearch[1][0]) || (bnd[1][0] > xsearch[1][1]) || (bnd[2][1] < xsearch[2][0]) || (bnd[2][0] > xsearch[2][1]))) return 1; else { if (period==0) return 0; else { for (int j=0;j<3;j++) {xsearchp[j][0]=xsearch[j][0];xsearchp[j][1]=xsearch[j][1];} for (int j=0;j<3;j++) { if (!((bnd[j][1] < xsearch[j][0]+period) || (bnd[j][0] > xsearch[j][1]+period))) {xsearchp[j][0]+=period;xsearchp[j][1]+=period;} else if (!((bnd[j][1] < xsearch[j][0]-period) || (bnd[j][0] > xsearch[j][1]-period))) {xsearchp[j][0]-=period;xsearchp[j][1]-=period;} } if (!((bnd[0][1] < xsearchp[0][0]) || (bnd[0][0] > xsearchp[0][1]) || (bnd[1][1] < xsearchp[1][0]) || (bnd[1][0] > xsearchp[1][1]) || (bnd[2][1] < xsearchp[2][0]) || (bnd[2][0] > xsearchp[2][1]))) return 1; else return 0; } } } /// Determine if a particle needs to be exported to another mpi domain based on a physical search radius int OpenMPSearchForOverlap(Particle &Part, Double_t bnd[3][2], Double_t rdist, Double_t period){ Double_t xsearch[3][2]; for (auto k=0;k<3;k++) {xsearch[k][0]=Part.GetPosition(k)-rdist;xsearch[k][1]=Part.GetPosition(k)+rdist;} return OpenMPSearchForOverlap(xsearch,bnd,period); } ///Saerch particles to see if they overlap other OpenMP domains Particle *OpenMPImportParticles(Options &opt, const Int_t nbodies, vector<Particle> &Part, Int_t * &pfof, Int_t *&storetype, const Int_t numompregions, OMP_Domain *&ompdomain, const Double_t rdist, Int_t *&omp_nrecv_total, Int_t *&omp_nrecv_offset) { Int_t i,orgIndex; int omptask; Int_t importtotal=0; double time1=MyGetTime(); Particle *Partompimport; Int_t *Partompimportindex; #ifndef USEMPI int ThisTask=0,NProcs=1; #endif cout<<ThisTask<<": Starting import build "<<endl; for (i=0;i<numompregions;i++) omp_nrecv_total[i]=omp_nrecv_offset[i]=0; #pragma omp parallel default(shared) \ private(i,orgIndex,omptask) { #pragma omp for for (i=0;i<numompregions;i++) { for (auto j=ompdomain[i].noffset;j<ompdomain[i].noffset+ompdomain[i].ncount;j++) { orgIndex = storetype[Part[j].GetID()+ompdomain[i].noffset]; if (pfof[orgIndex] == 0) continue; //for (auto k=0;k<numompregions;k++) if (k!=i) { for (auto k: ompdomain[i].neighbour) { if (OpenMPSearchForOverlap(Part[i],ompdomain[k].bnd,rdist,opt.p)) omp_nrecv_total[k] += 1; } } } } for (i=1;i<numompregions;i++) omp_nrecv_offset[i] = omp_nrecv_offset[i-1]+omp_nrecv_total[i-1]; for (i=0;i<numompregions;i++) { if (opt.iverbose > 1) cout<<ThisTask<<" omp region "<<i<<" is importing "<<omp_nrecv_total[i]<<endl; importtotal += omp_nrecv_total[i]; omp_nrecv_total[i] = 0; } Partompimport = new Particle[importtotal]; #pragma omp parallel default(shared) \ private(i,orgIndex,omptask) { #pragma omp for for (i=0;i<numompregions;i++) { for (auto j=ompdomain[i].noffset;j<ompdomain[i].noffset+ompdomain[i].ncount;j++) { orgIndex = storetype[Part[j].GetID()+ompdomain[i].noffset]; if (pfof[orgIndex] == 0) continue; //for (auto k=0;k<numompregions;k++) if (k!=i) { for (auto k: ompdomain[i].neighbour) { if (OpenMPSearchForOverlap(Part[i],ompdomain[k].bnd,rdist,opt.p)) { Partompimport[omp_nrecv_total[k]+omp_nrecv_offset[k]] = Part[j]; Partompimport[omp_nrecv_total[k]+omp_nrecv_offset[k]].SetID(pfof[orgIndex]); omp_nrecv_total[k] += 1; } } } } } cout<<ThisTask<<" finished import "<<MyGetTime()-time1<<endl; return Partompimport; } void OpenMPLinkAcross(Options &opt, Int_t nbodies, vector<Particle> &Part, Int_t * &pfof, Int_t *&storetype, Int_tree_t *&Head, Int_tree_t *&Next, Double_t *param, FOFcheckfunc &fofcheck, const Int_t numompregions, OMP_Domain *&ompdomain, KDTree **tree3dfofomp, Int_t *&omp_nrecv_total, Int_t *&omp_nrecv_offset, Particle* &Partompimport) { //now begin linking across Int_t i; Int_t omp_links_across_total; Int_t nt, orgIndex, curIndex, *nn=new Int_t[nbodies]; Coordinate x; double time1=MyGetTime(); #ifndef USEMPI int ThisTask=0,NProcs=1; #endif cout<<ThisTask<<": Starting linking across OpenMP domains"<<endl; do { omp_links_across_total = 0; #pragma omp parallel default(shared) \ private(i,orgIndex,curIndex, x, nt) { #pragma omp for schedule(dynamic,1) nowait reduction(+:omp_links_across_total) for (i=0;i<numompregions;i++) { for (auto j=0;j<omp_nrecv_total[i];j++) { //for each imported particle, find all particles within search window for (auto k=0;k<3;k++) x[k]=Partompimport[omp_nrecv_offset[i]+j].GetPosition(k); nt=tree3dfofomp[i]->SearchBallPosTagged(x, param[1], &nn[ompdomain[i].noffset]); for (auto k=0;k<nt;k++) { curIndex=nn[k+ompdomain[i].noffset]+ompdomain[i].noffset; //check that at least on of the particles meets the type criterion if necessary if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (fofcheck(Part[curIndex],param)!=0 && fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)!=0) continue; orgIndex = storetype[Part[curIndex].GetID()+ompdomain[i].noffset]; //otherwise, change these particles to local group id if local group id smaller //if local particle in a group if (pfof[orgIndex]>0) { //only change if both particles are appropriate type and group ids indicate local needs to be exported if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (!(fofcheck(Part[curIndex],param)==0 && fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)==0)) continue; //if local group id is larger, change locally if(pfof[orgIndex] > Partompimport[omp_nrecv_offset[i]+j].GetPID()) { Int_t ss = Head[nn[k+ompdomain[i].noffset]+ompdomain[i].noffset]; do{ orgIndex = storetype[Part[ss+ompdomain[i].noffset].GetID()+ompdomain[i].noffset]; pfof[orgIndex]=Partompimport[omp_nrecv_offset[i]+j].GetPID(); }while((ss = Next[ss+ompdomain[i].noffset]) >= 0); omp_links_across_total++; } } //if local particle not in a group and export is appropriate type, link else { if (opt.partsearchtype==PSTALL && opt.iBaryonSearch>1) if (fofcheck(Partompimport[omp_nrecv_offset[i]+j],param)!=0) continue; pfof[orgIndex]=Partompimport[omp_nrecv_offset[i]+j].GetPID(); omp_links_across_total++; } } } } } }while(omp_links_across_total>0); delete[] nn; cout<<ThisTask<<" finished linking "<<MyGetTime()-time1<<endl; } Int_t OpenMPResortParticleandGroups(Int_t nbodies, vector<Particle> &Part, Int_t *&pfof, Int_t minsize) { Int_t start, ngroups=0; Int_t *numingroup, **plist; //now get number of groups and reorder group ids for (auto i=0;i<nbodies;i++) Part[i].SetID(-pfof[i]); //used to use ID store store group id info qsort(Part.data(),nbodies,sizeof(Particle),IDCompare); //determine the # of groups, their size and the current group ID for (auto i=0,start=0;i<nbodies;i++) { if (Part[i].GetID()!=Part[start].GetID()) { //if group is too small set type to zero, which currently is used to store the group id if ((i-start)<minsize) for (Int_t j=start;j<i;j++) Part[j].SetID(0); else ngroups++; start=i; } if (Part[i].GetID()==0) break; } //again resort to move untagged particles to the end. qsort(Part.data(),nbodies,sizeof(Particle),IDCompare); //now adjust pfof and ids. for (auto i=0;i<nbodies;i++) {pfof[i]=-Part[i].GetID();Part[i].SetID(i);} numingroup=new Int_t[ngroups+1]; plist=new Int_t*[ngroups+1]; ngroups=1;//offset as group zero is untagged for (auto i=0,start=0;i<nbodies;i++) { if (pfof[i]!=pfof[start]) { numingroup[ngroups]=i-start; plist[ngroups]=new Int_t[numingroup[ngroups]]; for (auto j=start,count=0;j<i;j++) plist[ngroups][count++]=j; ngroups++; start=i; } if (pfof[i]==0) break; } ngroups--; //reorder groups ids according to size ReorderGroupIDs(ngroups,ngroups,numingroup,pfof,plist); for (auto i=1;i<=ngroups;i++) delete[] plist[i]; delete[] plist; delete[] numingroup; return ngroups; } //@} #endif <|endoftext|>
<commit_before>#ifndef SRC_ONLINE_AROW_HPP_ #define SRC_ONLINE_AROW_HPP_ #include <Eigen/Dense> #include <cstdbool> #include <boost/serialization/serialization.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/split_member.hpp> #include <boost/serialization/vector.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <fstream> #include "utility.hpp" class AROW { private : const std::size_t kDim; const double kR; private : Eigen::VectorXd _covariances; Eigen::VectorXd _means; public : AROW(const std::size_t dim, const double r) : kDim(dim), kR(r), _covariances(Eigen::VectorXd::Ones(kDim)), _means(Eigen::VectorXd::Zero(kDim)) { static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)"); static_assert(std::numeric_limits<decltype(r)>::max() > 0, "Hyper Parameter Error. (r > 0)"); assert(dim > 0); assert(r > 0); } virtual ~AROW() { } double suffer_loss(const double margin, const int label) const { return margin * label; } double calculate_margin(const Eigen::VectorXd& x) const { return _means.dot(x); } double calculate_confidence(const Eigen::VectorXd& feature) const { auto confidence = 0.0; utility::enumerate(feature.data(), feature.data() + feature.size(), 0, [&](const int index, const double value) { confidence += _covariances[index] * value * value; }); return confidence; } bool update(const Eigen::VectorXd& feature, const int label) { const auto margin = calculate_margin(feature); if (suffer_loss(margin, label) >= 1.0) { return false; } const auto confidence = calculate_confidence(feature); const auto beta = 1.0 / (confidence + kR); const auto alpha = std::max(0.0, 1.0 - label * margin) * beta; utility::enumerate(feature.data(), feature.data() + feature.size(), 0, [&](const int index, const double value) { const auto v = _covariances[index] * value; _means[index] += alpha * label * v; _covariances[index] -= beta * v * v; }); return true; } int predict(Eigen::VectorXd& x) const { return calculate_margin(x) > 0.0 ? 1 : -1; } void save(const std::string& filename) { std::ofstream ofs(filename); assert(ofs); boost::archive::text_oarchive oa(ofs); oa << *this; ofs.close(); } void load(const std::string& filename) { std::ifstream ifs(filename); assert(ifs); boost::archive::text_iarchive ia(ifs); ia >> *this; ifs.close(); } private : friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template <class Archive> void save(Archive& ar, const unsigned int version) const { std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size()); std::vector<double> means_vector(_means.data(), _means.data() + _means.size()); ar & boost::serialization::make_nvp("covariances", covariances_vector); ar & boost::serialization::make_nvp("means", means_vector); ar & boost::serialization::make_nvp("Dimension", const_cast<std::size_t&>(kDim)); ar & boost::serialization::make_nvp("R", const_cast<double&>(kR)); } template <class Archive> void load(Archive& ar, const unsigned int version) { std::vector<double> covariances_vector; std::vector<double> means_vector; ar & boost::serialization::make_nvp("covariances", covariances_vector); ar & boost::serialization::make_nvp("means", means_vector); ar & boost::serialization::make_nvp("Dimension", const_cast<std::size_t&>(kDim)); ar & boost::serialization::make_nvp("R", const_cast<double&>(kR)); _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size()); _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size()); } }; #endif //SRC_ONLINE_AROW_HPP_ <commit_msg>コメントのミスを修正<commit_after>#ifndef SRC_ONLINE_AROW_HPP_ #define SRC_ONLINE_AROW_HPP_ #include <Eigen/Dense> #include <cstdbool> #include <boost/serialization/serialization.hpp> #include <boost/serialization/nvp.hpp> #include <boost/serialization/split_member.hpp> #include <boost/serialization/vector.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/text_iarchive.hpp> #include <fstream> #include "utility.hpp" class AROW { private : const std::size_t kDim; const double kR; private : Eigen::VectorXd _covariances; Eigen::VectorXd _means; public : AROW(const std::size_t dim, const double r) : kDim(dim), kR(r), _covariances(Eigen::VectorXd::Ones(kDim)), _means(Eigen::VectorXd::Zero(kDim)) { static_assert(std::numeric_limits<decltype(dim)>::max() > 0, "Dimension Error. (Dimension > 0)"); static_assert(std::numeric_limits<decltype(r)>::max() > 0, "Hyper Parameter Error. (r > 0)"); assert(dim > 0); assert(r > 0); } virtual ~AROW() { } double suffer_loss(const double margin, const int label) const { return margin * label; } double calculate_margin(const Eigen::VectorXd& x) const { return _means.dot(x); } double calculate_confidence(const Eigen::VectorXd& feature) const { auto confidence = 0.0; utility::enumerate(feature.data(), feature.data() + feature.size(), 0, [&](const int index, const double value) { confidence += _covariances[index] * value * value; }); return confidence; } bool update(const Eigen::VectorXd& feature, const int label) { const auto margin = calculate_margin(feature); if (suffer_loss(margin, label) >= 1.0) { return false; } const auto confidence = calculate_confidence(feature); const auto beta = 1.0 / (confidence + kR); const auto alpha = std::max(0.0, 1.0 - label * margin) * beta; utility::enumerate(feature.data(), feature.data() + feature.size(), 0, [&](const int index, const double value) { const auto v = _covariances[index] * value; _means[index] += alpha * label * v; _covariances[index] -= beta * v * v; }); return true; } int predict(Eigen::VectorXd& x) const { return calculate_margin(x) > 0.0 ? 1 : -1; } void save(const std::string& filename) { std::ofstream ofs(filename); assert(ofs); boost::archive::text_oarchive oa(ofs); oa << *this; ofs.close(); } void load(const std::string& filename) { std::ifstream ifs(filename); assert(ifs); boost::archive::text_iarchive ia(ifs); ia >> *this; ifs.close(); } private : friend class boost::serialization::access; BOOST_SERIALIZATION_SPLIT_MEMBER(); template <class Archive> void save(Archive& ar, const unsigned int version) const { std::vector<double> covariances_vector(_covariances.data(), _covariances.data() + _covariances.size()); std::vector<double> means_vector(_means.data(), _means.data() + _means.size()); ar & boost::serialization::make_nvp("covariances", covariances_vector); ar & boost::serialization::make_nvp("means", means_vector); ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim)); ar & boost::serialization::make_nvp("r", const_cast<double&>(kR)); } template <class Archive> void load(Archive& ar, const unsigned int version) { std::vector<double> covariances_vector; std::vector<double> means_vector; ar & boost::serialization::make_nvp("covariances", covariances_vector); ar & boost::serialization::make_nvp("means", means_vector); ar & boost::serialization::make_nvp("dimension", const_cast<std::size_t&>(kDim)); ar & boost::serialization::make_nvp("r", const_cast<double&>(kR)); _covariances = Eigen::Map<Eigen::VectorXd>(&covariances_vector[0], covariances_vector.size()); _means = Eigen::Map<Eigen::VectorXd>(&means_vector[0], means_vector.size()); } }; #endif //SRC_ONLINE_AROW_HPP_ <|endoftext|>
<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/Version> #include <string> extern "C" { const char* osgGetVersion() { static char osg_version[256]; static int osg_version_init = 1; if (osg_version_init) { if (OSG_VERSION_RELEASE==0) { if (OSG_VERSION_REVISION==0) { sprintf(osg_version,"%d.%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR); } else { sprintf(osg_version,"%d.%d-%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR,OSG_VERSION_REVISION); } } else { if (OSG_VERSION_REVISION==0) { sprintf(osg_version,"%d.%d.%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR,OSG_VERSION_RELEASE); } else { sprintf(osg_version,"%d.%d.%d-%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR,OSG_VERSION_RELEASE,OSG_VERSION_REVISION); } } osg_version_init = 0; } return osg_version; } const char* osgGetLibraryName() { return "OpenSceneGraph Library"; } } <commit_msg>Changed the version format.<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield * * This library is open source and may be redistributed and/or modified under * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or * (at your option) any later version. The full license is in LICENSE file * included with this distribution, and on the openscenegraph.org website. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * OpenSceneGraph Public License for more details. */ #include <osg/Version> #include <string> extern "C" { const char* osgGetVersion() { static char osg_version[256]; static int osg_version_init = 1; if (osg_version_init) { if (OSG_VERSION_REVISION==0) { sprintf(osg_version,"%d.%d.%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR,OSG_VERSION_RELEASE); } else { sprintf(osg_version,"%d.%d.%d-%d",OSG_VERSION_MAJOR,OSG_VERSION_MINOR,OSG_VERSION_RELEASE,OSG_VERSION_REVISION); } osg_version_init = 0; } return osg_version; } const char* osgGetLibraryName() { return "OpenSceneGraph Library"; } } <|endoftext|>
<commit_before>#include <stdarg.h> #include <list> #include "errors.hpp" #include <boost/bind.hpp> #include <boost/tokenizer.hpp> #include "arch/runtime/coroutines.hpp" #include "containers/scoped.hpp" #include "logger.hpp" #include "perfmon/core.hpp" /* Constructor and destructor register and deregister the perfmon. */ perfmon_t::perfmon_t() { } perfmon_t::~perfmon_t() { } struct stats_collection_context_t : public home_thread_mixin_t { stats_collection_context_t(rwi_lock_t *constituents_lock, size_t size) : contexts(new void *[size]), lock_sentry(constituents_lock) { } ~stats_collection_context_t() { delete[] contexts; } void **contexts; private: rwi_lock_t::read_acq_t lock_sentry; }; perfmon_collection_t::perfmon_collection_t() { } void *perfmon_collection_t::begin_stats() { stats_collection_context_t *ctx; { on_thread_t thread_switcher(home_thread()); ctx = new stats_collection_context_t(&constituents_access, constituents.size()); } size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { ctx->contexts[i] = p->get()->begin_stats(); } return ctx; } void perfmon_collection_t::visit_stats(void *_context) { stats_collection_context_t *ctx = reinterpret_cast<stats_collection_context_t*>(_context); size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { p->get()->visit_stats(ctx->contexts[i]); } } perfmon_result_t * perfmon_collection_t::end_stats(void *_context) { stats_collection_context_t *ctx = reinterpret_cast<stats_collection_context_t*>(_context); perfmon_result_t *map; perfmon_result_t::alloc_map_result(&map); size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { perfmon_result_t * stat = p->get()->end_stats(ctx->contexts[i]); if (p->splice()) { stat->splice_into(map); delete stat; // `stat` is empty now, we can delete it safely } else { map->insert(p->name, stat); } } { on_thread_t thread_switcher(home_thread()); delete ctx; // cleans up, unlocks } return map; } void perfmon_collection_t::add(perfmon_membership_t *perfmon) { scoped_ptr_t<on_thread_t> thread_switcher; if (coroutines_have_been_initialized()) { thread_switcher.init(new on_thread_t(home_thread())); } rwi_lock_t::write_acq_t write_acq(&constituents_access); constituents.push_back(perfmon); } void perfmon_collection_t::remove(perfmon_membership_t *perfmon) { scoped_ptr_t<on_thread_t> thread_switcher; if (coroutines_have_been_initialized()) { thread_switcher.init(new on_thread_t(home_thread())); } rwi_lock_t::write_acq_t write_acq(&constituents_access); constituents.remove(perfmon); } perfmon_membership_t::perfmon_membership_t(perfmon_collection_t *_parent, perfmon_t *_perfmon, const char *_name, bool _own_the_perfmon) : name(_name != NULL ? _name : ""), parent(_parent), perfmon(_perfmon), own_the_perfmon(_own_the_perfmon) { parent->add(this); } perfmon_membership_t::perfmon_membership_t(perfmon_collection_t *_parent, perfmon_t *_perfmon, const std::string &_name, bool _own_the_perfmon) : name(_name), parent(_parent), perfmon(_perfmon), own_the_perfmon(_own_the_perfmon) { parent->add(this); } perfmon_membership_t::~perfmon_membership_t() { parent->remove(this); if (own_the_perfmon) delete perfmon; } perfmon_t *perfmon_membership_t::get() { return perfmon; } bool perfmon_membership_t::splice() { return name.length() == 0; } perfmon_multi_membership_t::perfmon_multi_membership_t(perfmon_collection_t *collection, perfmon_t *perfmon, const char *name, ...) { // Create membership for the first provided perfmon first memberships.push_back(new perfmon_membership_t(collection, perfmon, name)); va_list args; va_start(args, name); // Now go through varargs list until we read NULL while ((perfmon = va_arg(args, perfmon_t *)) != NULL) { name = va_arg(args, const char *); memberships.push_back(new perfmon_membership_t(collection, perfmon, name)); } va_end(args); } perfmon_multi_membership_t::~perfmon_multi_membership_t() { for (std::vector<perfmon_membership_t*>::const_iterator it = memberships.begin(); it != memberships.end(); ++it) { delete *it; } } perfmon_result_t::perfmon_result_t() { type = type_value; } perfmon_result_t::perfmon_result_t(const perfmon_result_t &copyee) : type(copyee.type), value_(copyee.value_), map_() { for (perfmon_result_t::internal_map_t::const_iterator it = copyee.map_.begin(); it != copyee.map_.end(); ++it) { perfmon_result_t *subcopy = new perfmon_result_t(*it->second); map_.insert(std::pair<std::string, perfmon_result_t *>(it->first, subcopy)); } } perfmon_result_t::perfmon_result_t(const std::string &s) { type = type_value; value_ = s; } perfmon_result_t::perfmon_result_t(const std::map<std::string, perfmon_result_t *> &m) { type = type_map; map_ = m; } perfmon_result_t::~perfmon_result_t() { if (type == type_map) { clear_map(); } rassert(map_.empty()); } void perfmon_result_t::clear_map() { for (perfmon_result_t::internal_map_t::iterator it = map_.begin(); it != map_.end(); ++it) { delete it->second; } map_.clear(); } void perfmon_result_t::erase(perfmon_result_t::iterator it) { delete it->second; map_.erase(it); } perfmon_result_t perfmon_result_t::make_string() { return perfmon_result_t(std::string()); } void perfmon_result_t::alloc_string_result(perfmon_result_t **out) { *out = new perfmon_result_t(std::string()); } perfmon_result_t perfmon_result_t::make_map() { return perfmon_result_t(perfmon_result_t::internal_map_t()); } void perfmon_result_t::alloc_map_result(perfmon_result_t **out) { *out = new perfmon_result_t(perfmon_result_t::internal_map_t()); } std::string *perfmon_result_t::get_string() { rassert(type == type_value); return &value_; } const std::string *perfmon_result_t::get_string() const { rassert(type == type_value); return &value_; } perfmon_result_t::internal_map_t *perfmon_result_t::get_map() { rassert(type == type_map); return &map_; } const perfmon_result_t::internal_map_t *perfmon_result_t::get_map() const { rassert(type == type_map); return &map_; } size_t perfmon_result_t::get_map_size() const { rassert(type == type_map); return map_.size(); } bool perfmon_result_t::is_string() const { return type == type_value; } bool perfmon_result_t::is_map() const { return type == type_map; } perfmon_result_t::perfmon_result_type_t perfmon_result_t::get_type() const { return type; } void perfmon_result_t::reset_type(perfmon_result_type_t new_type) { value_.clear(); clear_map(); type = new_type; } std::pair<perfmon_result_t::iterator, bool> perfmon_result_t::insert(const std::string &name, perfmon_result_t *val) { std::string s(name); perfmon_result_t::internal_map_t *map = get_map(); rassert(map->count(name) == 0); return map->insert(std::pair<std::string, perfmon_result_t *>(s, val)); } perfmon_result_t::iterator perfmon_result_t::begin() { return map_.begin(); } perfmon_result_t::iterator perfmon_result_t::end() { return map_.end(); } perfmon_result_t::const_iterator perfmon_result_t::begin() const { return map_.begin(); } perfmon_result_t::const_iterator perfmon_result_t::end() const { return map_.end(); } void perfmon_result_t::splice_into(perfmon_result_t *map) { rassert(type == type_map); // Transfer all elements from the internal map to the passed map. // Unfortunately we can't use here std::map::insert(InputIterator first, InputIterator last), // because that way we can overwrite an entry in the target map and thus leak a // perfmon_result_t value. for (const_iterator it = begin(); it != end(); ++it) { map->insert(it->first, it->second); } map_.clear(); } /* Construct a filter from a set of paths. Paths are of the form foo/bar/baz, where each of those can be a regular expression. They act a lot like XPath expressions, but for perfmon_t objects. */ perfmon_filter_t::perfmon_filter_t(const std::set<std::string> &paths) { typedef boost::escaped_list_separator<char> separator_t; typedef boost::tokenizer<separator_t> tokenizer_t; separator_t slashes("\\", "/", ""); for (std::set<std::string>::const_iterator str = paths.begin(); str != paths.end(); ++str) { regexps.push_back(std::vector<scoped_regex_t *>()); std::vector<scoped_regex_t *> *path = &regexps.back(); try { tokenizer_t t(*str, slashes); for (tokenizer_t::const_iterator it = t.begin(); it != t.end(); ++it) { path->push_back(new scoped_regex_t("^"+(*it)+"$")); } } catch (const boost::escaped_list_error &e) { logINF("Error: Could not parse %s (%s), skipping.", sanitize_for_logger(*str).c_str(), e.what()); continue; //Skip this path } } } perfmon_filter_t::~perfmon_filter_t() { for (std::vector<std::vector<scoped_regex_t *> >::const_iterator it = regexps.begin(); it != regexps.end(); ++it) { for (std::vector<scoped_regex_t *>::const_iterator regexp = it->begin(); regexp != it->end(); ++regexp) { delete *regexp; } } } /* Filter a [perfmon_result_t]. [depth] is how deep we are in the paths that the [perfmon_filter_t] was constructed from, and [active] is the set of paths that are still active (i.e. that haven't failed a match yet). This should only be called by [filter]. */ perfmon_result_t *perfmon_filter_t::subfilter( perfmon_result_t *p, size_t depth, std::vector<bool> active) const { bool keep_this_perfmon = true; if (p->is_string()) { std::string *str = p->get_string(); for (size_t i = 0; i < regexps.size(); ++i) { if (!active[i]) continue; if (depth >= regexps[i].size()) return p; if (depth == regexps[i].size() && regexps[i][depth]->matches(*str)) return p; } keep_this_perfmon = false; } else if (p->is_map()) { std::list<perfmon_result_t::iterator> to_delete; for (perfmon_result_t::iterator it = p->begin(); it != p->end(); ++it) { std::vector<bool> subactive = active; bool some_subpath = false; for (size_t i = 0; i < regexps.size(); ++i) { if (!active[i]) continue; if (depth >= regexps[i].size()) return p; subactive[i] = regexps[i][depth]->matches(it->first); some_subpath |= subactive[i]; } if (some_subpath) it->second = subfilter(it->second, depth+1, subactive); if (!some_subpath || !it->second) to_delete.push_back(it); } for (std::list<perfmon_result_t::iterator>::const_iterator it = to_delete.begin(); it != to_delete.end(); ++it) { p->erase(*it); } if (p->get_map()->empty()) keep_this_perfmon = false; } if (!keep_this_perfmon && depth > 0) { //Never delete topmost node delete p; return 0; } else { return p; } } void perfmon_filter_t::filter(perfmon_result_t *p) const { subfilter(p, 0, std::vector<bool>(regexps.size(), true)); } perfmon_collection_t &get_global_perfmon_collection() { // Getter function so that we can be sure that `collection` is initialized // before it is needed, as advised by the C++ FAQ. Otherwise, a `perfmon_t` // might be initialized before `collection` was initialized. // FIXME: probably use "new" to create the perfmon_collection_t. For more info check out C++ FAQ Lite answer 10.16. static perfmon_collection_t collection; return collection; } <commit_msg>Minor cosmetic improvements.<commit_after>#include <stdarg.h> #include <list> #include "errors.hpp" #include <boost/bind.hpp> #include <boost/tokenizer.hpp> #include "arch/runtime/coroutines.hpp" #include "containers/scoped.hpp" #include "logger.hpp" #include "perfmon/core.hpp" /* Constructor and destructor register and deregister the perfmon. */ perfmon_t::perfmon_t() { } perfmon_t::~perfmon_t() { } struct stats_collection_context_t : public home_thread_mixin_t { stats_collection_context_t(rwi_lock_t *constituents_lock, size_t size) : contexts(new void *[size]), lock_sentry(constituents_lock) { } ~stats_collection_context_t() { delete[] contexts; } void **contexts; private: rwi_lock_t::read_acq_t lock_sentry; }; perfmon_collection_t::perfmon_collection_t() { } void *perfmon_collection_t::begin_stats() { stats_collection_context_t *ctx; { on_thread_t thread_switcher(home_thread()); ctx = new stats_collection_context_t(&constituents_access, constituents.size()); } size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { ctx->contexts[i] = p->get()->begin_stats(); } return ctx; } void perfmon_collection_t::visit_stats(void *_context) { stats_collection_context_t *ctx = reinterpret_cast<stats_collection_context_t*>(_context); size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { p->get()->visit_stats(ctx->contexts[i]); } } perfmon_result_t * perfmon_collection_t::end_stats(void *_context) { stats_collection_context_t *ctx = reinterpret_cast<stats_collection_context_t*>(_context); perfmon_result_t *map; perfmon_result_t::alloc_map_result(&map); size_t i = 0; for (perfmon_membership_t *p = constituents.head(); p; p = constituents.next(p), ++i) { perfmon_result_t * stat = p->get()->end_stats(ctx->contexts[i]); if (p->splice()) { stat->splice_into(map); delete stat; // `stat` is empty now, we can delete it safely } else { map->insert(p->name, stat); } } { on_thread_t thread_switcher(home_thread()); delete ctx; // cleans up, unlocks } return map; } void perfmon_collection_t::add(perfmon_membership_t *perfmon) { scoped_ptr_t<on_thread_t> thread_switcher; if (coroutines_have_been_initialized()) { thread_switcher.init(new on_thread_t(home_thread())); } rwi_lock_t::write_acq_t write_acq(&constituents_access); constituents.push_back(perfmon); } void perfmon_collection_t::remove(perfmon_membership_t *perfmon) { scoped_ptr_t<on_thread_t> thread_switcher; if (coroutines_have_been_initialized()) { thread_switcher.init(new on_thread_t(home_thread())); } rwi_lock_t::write_acq_t write_acq(&constituents_access); constituents.remove(perfmon); } perfmon_membership_t::perfmon_membership_t(perfmon_collection_t *_parent, perfmon_t *_perfmon, const char *_name, bool _own_the_perfmon) : name(_name != NULL ? _name : ""), parent(_parent), perfmon(_perfmon), own_the_perfmon(_own_the_perfmon) { parent->add(this); } perfmon_membership_t::perfmon_membership_t(perfmon_collection_t *_parent, perfmon_t *_perfmon, const std::string &_name, bool _own_the_perfmon) : name(_name), parent(_parent), perfmon(_perfmon), own_the_perfmon(_own_the_perfmon) { parent->add(this); } perfmon_membership_t::~perfmon_membership_t() { parent->remove(this); if (own_the_perfmon) delete perfmon; } perfmon_t *perfmon_membership_t::get() { return perfmon; } bool perfmon_membership_t::splice() { return name.length() == 0; } perfmon_multi_membership_t::perfmon_multi_membership_t(perfmon_collection_t *collection, perfmon_t *perfmon, const char *name, ...) { // Create membership for the first provided perfmon first memberships.push_back(new perfmon_membership_t(collection, perfmon, name)); va_list args; va_start(args, name); // Now go through varargs list until we read NULL while ((perfmon = va_arg(args, perfmon_t *)) != NULL) { name = va_arg(args, const char *); memberships.push_back(new perfmon_membership_t(collection, perfmon, name)); } va_end(args); } perfmon_multi_membership_t::~perfmon_multi_membership_t() { for (std::vector<perfmon_membership_t*>::const_iterator it = memberships.begin(); it != memberships.end(); ++it) { delete *it; } } perfmon_result_t::perfmon_result_t() { type = type_value; } perfmon_result_t::perfmon_result_t(const perfmon_result_t &copyee) : type(copyee.type), value_(copyee.value_), map_() { for (perfmon_result_t::internal_map_t::const_iterator it = copyee.map_.begin(); it != copyee.map_.end(); ++it) { perfmon_result_t *subcopy = new perfmon_result_t(*it->second); map_.insert(std::pair<std::string, perfmon_result_t *>(it->first, subcopy)); } } perfmon_result_t::perfmon_result_t(const std::string &s) { type = type_value; value_ = s; } perfmon_result_t::perfmon_result_t(const std::map<std::string, perfmon_result_t *> &m) { type = type_map; map_ = m; } perfmon_result_t::~perfmon_result_t() { if (type == type_map) { clear_map(); } rassert(map_.empty()); } void perfmon_result_t::clear_map() { for (perfmon_result_t::internal_map_t::iterator it = map_.begin(); it != map_.end(); ++it) { delete it->second; } map_.clear(); } void perfmon_result_t::erase(perfmon_result_t::iterator it) { delete it->second; map_.erase(it); } perfmon_result_t perfmon_result_t::make_string() { return perfmon_result_t(std::string()); } void perfmon_result_t::alloc_string_result(perfmon_result_t **out) { *out = new perfmon_result_t(std::string()); } perfmon_result_t perfmon_result_t::make_map() { return perfmon_result_t(perfmon_result_t::internal_map_t()); } void perfmon_result_t::alloc_map_result(perfmon_result_t **out) { *out = new perfmon_result_t(perfmon_result_t::internal_map_t()); } std::string *perfmon_result_t::get_string() { rassert(type == type_value); return &value_; } const std::string *perfmon_result_t::get_string() const { rassert(type == type_value); return &value_; } perfmon_result_t::internal_map_t *perfmon_result_t::get_map() { rassert(type == type_map); return &map_; } const perfmon_result_t::internal_map_t *perfmon_result_t::get_map() const { rassert(type == type_map); return &map_; } size_t perfmon_result_t::get_map_size() const { rassert(type == type_map); return map_.size(); } bool perfmon_result_t::is_string() const { return type == type_value; } bool perfmon_result_t::is_map() const { return type == type_map; } perfmon_result_t::perfmon_result_type_t perfmon_result_t::get_type() const { return type; } void perfmon_result_t::reset_type(perfmon_result_type_t new_type) { value_.clear(); clear_map(); type = new_type; } std::pair<perfmon_result_t::iterator, bool> perfmon_result_t::insert(const std::string &name, perfmon_result_t *val) { std::string s(name); perfmon_result_t::internal_map_t *map = get_map(); rassert(map->count(name) == 0); return map->insert(std::pair<std::string, perfmon_result_t *>(s, val)); } perfmon_result_t::iterator perfmon_result_t::begin() { return map_.begin(); } perfmon_result_t::iterator perfmon_result_t::end() { return map_.end(); } perfmon_result_t::const_iterator perfmon_result_t::begin() const { return map_.begin(); } perfmon_result_t::const_iterator perfmon_result_t::end() const { return map_.end(); } void perfmon_result_t::splice_into(perfmon_result_t *map) { rassert(type == type_map); // Transfer all elements from the internal map to the passed map. // Unfortunately we can't use here std::map::insert(InputIterator first, InputIterator last), // because that way we can overwrite an entry in the target map and thus leak a // perfmon_result_t value. for (const_iterator it = begin(); it != end(); ++it) { map->insert(it->first, it->second); } map_.clear(); } /* Construct a filter from a set of paths. Paths are of the form foo/bar/baz, where each of those can be a regular expression. They act a lot like XPath expressions, but for perfmon_t objects. */ perfmon_filter_t::perfmon_filter_t(const std::set<std::string> &paths) { typedef boost::escaped_list_separator<char> separator_t; typedef boost::tokenizer<separator_t> tokenizer_t; separator_t slashes("\\", "/", ""); for (std::set<std::string>::const_iterator str = paths.begin(); str != paths.end(); ++str) { regexps.push_back(std::vector<scoped_regex_t *>()); std::vector<scoped_regex_t *> *path = &regexps.back(); try { tokenizer_t t(*str, slashes); for (tokenizer_t::const_iterator it = t.begin(); it != t.end(); ++it) { path->push_back(new scoped_regex_t("^"+(*it)+"$")); } } catch (const boost::escaped_list_error &e) { logINF("Error: Could not parse %s (%s), skipping.", sanitize_for_logger(*str).c_str(), e.what()); continue; //Skip this path } } } perfmon_filter_t::~perfmon_filter_t() { for (std::vector<std::vector<scoped_regex_t *> >::const_iterator it = regexps.begin(); it != regexps.end(); ++it) { for (std::vector<scoped_regex_t *>::const_iterator regexp = it->begin(); regexp != it->end(); ++regexp) { delete *regexp; } } } /* Filter a [perfmon_result_t]. [depth] is how deep we are in the paths that the [perfmon_filter_t] was constructed from, and [active] is the set of paths that are still active (i.e. that haven't failed a match yet). This should only be called by [filter]. */ perfmon_result_t *perfmon_filter_t::subfilter( perfmon_result_t *p, size_t depth, std::vector<bool> active) const { bool keep_this_perfmon = true; if (p->is_string()) { std::string *str = p->get_string(); for (size_t i = 0; i < regexps.size(); ++i) { if (!active[i]) continue; if (depth >= regexps[i].size()) return p; if (depth == regexps[i].size() && regexps[i][depth]->matches(*str)) return p; } keep_this_perfmon = false; } else if (p->is_map()) { std::list<perfmon_result_t::iterator> to_delete; for (perfmon_result_t::iterator it = p->begin(); it != p->end(); ++it) { std::vector<bool> subactive = active; bool some_subpath = false; for (size_t i = 0; i < regexps.size(); ++i) { if (!active[i]) continue; if (depth >= regexps[i].size()) return p; subactive[i] = regexps[i][depth]->matches(it->first); some_subpath |= subactive[i]; } if (some_subpath) it->second = subfilter(it->second, depth + 1, subactive); if (!some_subpath || !it->second) to_delete.push_back(it); } for (std::list<perfmon_result_t::iterator>::const_iterator it = to_delete.begin(); it != to_delete.end(); ++it) { p->erase(*it); } if (p->get_map()->empty()) keep_this_perfmon = false; } if (!keep_this_perfmon && depth > 0) { //Never delete topmost node delete p; return 0; } else { return p; } } void perfmon_filter_t::filter(perfmon_result_t *p) const { subfilter(p, 0, std::vector<bool>(regexps.size(), true)); } perfmon_collection_t &get_global_perfmon_collection() { // Getter function so that we can be sure that `collection` is initialized // before it is needed, as advised by the C++ FAQ. Otherwise, a `perfmon_t` // might be initialized before `collection` was initialized. // FIXME: probably use "new" to create the perfmon_collection_t. For more info check out C++ FAQ Lite answer 10.16. static perfmon_collection_t collection; return collection; } <|endoftext|>
<commit_before>#ifndef _TEST_H_ #define _TEST_H_ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <cmath> #include "utils.hpp" #include "debug.hpp" #include "constants.hpp" static const u8 *global_keys_pressed = 0; typedef struct { float red; float green; float blue; float alpha; } color_t; static color_t background_color; typedef struct { double x; double y; double speed; SDL_Texture *image_path; int w; int h; } ball_t; static ball_t global_ball; void test_initialize(SDL_Renderer *renderer, const u8 *keys_pressed) { global_ball.image_path = IMG_LoadTexture(renderer, BALL_IMG_PATH); SDL_QueryTexture(global_ball.image_path, 0, 0, &global_ball.w, &global_ball.h); global_ball.speed = BALL_SPEED; debug_initialize_text(renderer); global_keys_pressed = keys_pressed; background_color.red = 127; background_color.green = 0; background_color.blue = 127; background_color.alpha = 255; } void test_update(double dt) { if (global_keys_pressed[SDL_SCANCODE_UP]) { global_ball.y -= global_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_DOWN]) { global_ball.y += global_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_LEFT]) { global_ball.x -= global_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_RIGHT]) { global_ball.x += global_ball.speed * dt; } double multiplier = 0.1; static bool red_decreasing = false; if (red_decreasing) { background_color.red -= multiplier * dt; if (background_color.red < 5) red_decreasing = false; } else { background_color.red += multiplier * dt; if (background_color.red > 250) red_decreasing = true; } static bool blue_decreasing = false; if (blue_decreasing) { background_color.blue -= multiplier * dt; if (background_color.blue < 5) blue_decreasing = false; } else { background_color.blue += multiplier * dt; if (background_color.blue > 250) blue_decreasing = true; } } void test_render(SDL_Renderer *renderer, double dt) { SDL_SetRenderDrawColor(renderer, (u8) round(background_color.red), (u8) round(background_color.green), (u8) round(background_color.blue), (u8) round(background_color.alpha)); SDL_RenderClear(renderer); SDL_Rect ball_rect; ball_rect.x = round(global_ball.x); ball_rect.y = round(global_ball.y); ball_rect.w = round(BALL_SCALE * global_ball.w); ball_rect.h = round(BALL_SCALE * global_ball.h); SDL_RenderCopy(renderer, global_ball.image_path, 0, &ball_rect); debug_draw_fps(dt); } #endif <commit_msg>Add an example of mouse input handling<commit_after>#ifndef _TEST_H_ #define _TEST_H_ #include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include <cmath> #include "utils.hpp" #include "debug.hpp" #include "constants.hpp" static const u8 *global_keys_pressed = 0; typedef struct { float red; float green; float blue; float alpha; } color_t; static color_t background_color; typedef struct { double x; double y; double speed; SDL_Texture *image_path; int w; int h; } ball_t; static ball_t global_keybd_ball; static ball_t global_mouse_ball; void test_initialize(SDL_Renderer *renderer, const u8 *keys_pressed) { // keyboard controlled ball global_keybd_ball.image_path = IMG_LoadTexture(renderer, BALL_IMG_PATH); SDL_QueryTexture(global_keybd_ball.image_path, 0, 0, &global_keybd_ball.w, &global_keybd_ball.h); global_keybd_ball.x = 40; global_keybd_ball.y = 40; global_keybd_ball.speed = BALL_SPEED; // keyboard controlled ball global_mouse_ball.image_path = IMG_LoadTexture(renderer, BALL_IMG_PATH); SDL_QueryTexture(global_mouse_ball.image_path, 0, 0, &global_mouse_ball.w, &global_mouse_ball.h); global_mouse_ball.speed = BALL_SPEED; // FIXME: verify if needed debug_initialize_text(renderer); global_keys_pressed = keys_pressed; background_color.red = 127; background_color.green = 0; background_color.blue = 127; background_color.alpha = 255; } void test_update(double dt) { if (global_keys_pressed[SDL_SCANCODE_UP]) { global_keybd_ball.y -= global_keybd_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_DOWN]) { global_keybd_ball.y += global_keybd_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_LEFT]) { global_keybd_ball.x -= global_keybd_ball.speed * dt; } if (global_keys_pressed[SDL_SCANCODE_RIGHT]) { global_keybd_ball.x += global_keybd_ball.speed * dt; } int mouse_x, mouse_y; SDL_GetMouseState(&mouse_x, &mouse_y); global_mouse_ball.x = mouse_x; global_mouse_ball.y = mouse_y; double multiplier = 0.1; static bool red_decreasing = false; if (red_decreasing) { background_color.red -= multiplier * dt; if (background_color.red < 5) red_decreasing = false; } else { background_color.red += multiplier * dt; if (background_color.red > 250) red_decreasing = true; } static bool blue_decreasing = false; if (blue_decreasing) { background_color.blue -= multiplier * dt; if (background_color.blue < 5) blue_decreasing = false; } else { background_color.blue += multiplier * dt; if (background_color.blue > 250) blue_decreasing = true; } } void test_render(SDL_Renderer *renderer, double dt) { // repaint background SDL_SetRenderDrawColor(renderer, (u8) round(background_color.red), (u8) round(background_color.green), (u8) round(background_color.blue), (u8) round(background_color.alpha)); SDL_RenderClear(renderer); // draw balls { SDL_Rect ball_rect; // keyboard ball ball_rect.x = round(global_keybd_ball.x - (BALL_SCALE * global_keybd_ball.w) / 2); ball_rect.y = round(global_keybd_ball.y - (BALL_SCALE * global_keybd_ball.h) / 2); ball_rect.w = round(BALL_SCALE * global_keybd_ball.w); ball_rect.h = round(BALL_SCALE * global_keybd_ball.h); SDL_RenderCopy(renderer, global_keybd_ball.image_path, 0, &ball_rect); // mouse ball ball_rect.x = round(global_mouse_ball.x - (BALL_SCALE * global_mouse_ball.w) / 2); ball_rect.y = round(global_mouse_ball.y - (BALL_SCALE * global_mouse_ball.h) / 2); ball_rect.w = round(BALL_SCALE * global_mouse_ball.w); ball_rect.h = round(BALL_SCALE * global_mouse_ball.h); SDL_RenderCopy(renderer, global_mouse_ball.image_path, 0, &ball_rect); } debug_draw_fps(dt); } #endif <|endoftext|>
<commit_before>/**************************************************************************** ** ** This file is part of the $PACKAGE_NAME$. ** ** Copyright (C) $THISYEAR$ $COMPANY_NAME$. ** ** $QT_EXTENDED_DUAL_LICENSE$ ** ****************************************************************************/ #include "qcoordinate.h" #include <QDateTime> #include <QHash> #include <QDebug> #include <qnumeric.h> #include <math.h> static const double QCoordinate_EARTH_MEAN_RADIUS = 6371.0072; inline static double QCoordinate_degToRad(double deg) { return deg * M_PI / 180; } inline static double QCoordinate_radToDeg(double rad) { return rad * 180 / M_PI; } class QCoordinatePrivate { public: double lat; double lng; double alt; }; /*! \class QCoordinate \brief The QCoordinate class defines a geographical position on the surface of the Earth. A QCoordinate is defined by latitude, longitude, and optionally, altitude. Use type() to determine whether a coordinate is a 2D coordinate (has latitude and longitude only) or 3D coordinate (has latitude, longitude and altitude). Use distanceTo() and azimuthTo() to calculate the distance and bearing between coordinates. The coordinate values should be specified using the WGS84 datum. */ /*! \enum QCoordinate::CoordinateType Defines the types of a coordinate. \value InvalidCoordinate An invalid coordinate. A coordinate is invalid if its latitude or longitude values are invalid. \value Coordinate2D A coordinate with valid latitude and longitude values. \value Coordinate3D A coordinate with valid latitude and longitude values, and also an altitude value. */ /*! \enum QCoordinate::CoordinateFormat Defines the possible formatting options for toString(). \value DecimalDegrees Returns a string representation of the coordinates in decimal degrees format. \value DecimalDegreesWithHemisphere Returns a string representation of the coordinates in decimal degrees format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \value DegreesMinutes Returns a string representation of the coordinates in degrees-minutes format. \value DegreesMinutesWithHemisphere Returns a string representation of the coordinates in degrees-minutes format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \value DegreesMinutesSeconds Returns a string representation of the coordinates in degrees-minutes-seconds format. \value DegreesMinutesSecondsWithHemisphere Returns a string representation of the coordinates in degrees-minutes-seconds format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \sa toString() */ /*! Constructs a coordinate. The coordinate will be invalid until setLatitude() and setLongitude() have been called. */ QCoordinate::QCoordinate() : d(new QCoordinatePrivate) { d->lat = qQNaN(); d->lng = qQNaN(); d->alt = qQNaN(); } /*! Constructs a coordinate with the given \a latitude and \a longitude. */ QCoordinate::QCoordinate(double latitude, double longitude) : d(new QCoordinatePrivate) { d->lat = latitude; d->lng = longitude; d->alt = qQNaN(); } /*! Constructs a coordinate with the given \a latitude, \a longitude and \a altitude. */ QCoordinate::QCoordinate(double latitude, double longitude, double altitude) : d(new QCoordinatePrivate) { d->lat = latitude; d->lng = longitude; d->alt = altitude; } /*! Constructs a coordinate from the contents of \a other. */ QCoordinate::QCoordinate(const QCoordinate &other) : d(new QCoordinatePrivate) { operator=(other); } /*! Destroys the coordinate object. */ QCoordinate::~QCoordinate() { delete d; } /*! Assigns \a other to this coordinate and returns a reference to this coordinate. */ QCoordinate &QCoordinate::operator=(const QCoordinate &other) { if (this == &other) return *this; d->lat = other.d->lat; d->lng = other.d->lng; d->alt = other.d->alt; return *this; } /*! Returns true if the type() is Coordinate2D or Coordinate3D. */ bool QCoordinate::isValid() const { CoordinateType t = type(); return t == Coordinate2D || t == Coordinate3D; } /*! Returns the type of this coordinate. */ QCoordinate::CoordinateType QCoordinate::type() const { if ( (d->lat >= -90 && d->lat <= 90) && (d->lng >= -180 && d->lng <= 180) ) { if (qIsNaN(d->alt)) return Coordinate2D; return Coordinate3D; } return InvalidCoordinate; } /*! Returns the latitude, in decimal degrees. The return value is undefined if the latitude has not been set. A positive latitude indicates the Northern Hemisphere, and a negative latitude indicates the Southern Hemisphere. \sa setLatitude(), type() */ double QCoordinate::latitude() const { return d->lat; } /*! Sets the latitude (in decimal degrees) to \a latitude. The value should be in the WGS84 datum. To be valid, the latitude must be between -90 to 90 inclusive. \sa latitude() */ void QCoordinate::setLatitude(double latitude) { d->lat = latitude; } /*! Returns the longitude, in decimal degrees. The return value is undefined if the longitude has not been set. A positive longitude indicates the Eastern Hemisphere, and a negative longitude indicates the Western Hemisphere. \sa setLongitude(), type() */ double QCoordinate::longitude() const { return d->lng; } /*! Sets the longitude (in decimal degrees) to \a longitude. The value should be in the WGS84 datum. To be valid, the longitude must be between -180 to 180 inclusive. \sa longitude() */ void QCoordinate::setLongitude(double longitude) { d->lng = longitude; } /*! Returns the altitude (meters above sea level). The return value is undefined if the altitude has not been set. \sa setAltitude(), type() */ double QCoordinate::altitude() const { return d->alt; } /*! Sets the altitude (meters above sea level) to \a altitude. \sa altitude() */ void QCoordinate::setAltitude(double altitude) { d->alt = altitude; } /*! Returns the distance (in meters) from this coordinate to the coordinate specified by \a other. Altitude is not used in the calculation. This calculation returns the great-circle distance between the two coordinates, with an assumption that the Earth is spherical for the purpose of this calculation. Returns 0 if the type of this coordinate or the type of \a other is QCoordinate::InvalidCoordinate. */ qreal QCoordinate::distanceTo(const QCoordinate &other) const { if (type() == QCoordinate::InvalidCoordinate || other.type() == QCoordinate::InvalidCoordinate) { return 0; } // Haversine formula double dlat = QCoordinate_degToRad(other.d->lat - d->lat); double dlon = QCoordinate_degToRad(other.d->lng - d->lng); double y = sin(dlat/2) * sin(dlat/2) + cos(QCoordinate_degToRad(d->lat)) * cos(QCoordinate_degToRad(other.d->lat)) * sin(dlon/2) * sin(dlon/2); double x = 2 * atan2(sqrt(y), sqrt(1-y)); return qreal(x * QCoordinate_EARTH_MEAN_RADIUS * 1000); } /*! Returns the azimuth (or bearing) in degrees from this coordinate to the coordinate specified by \a other. Altitude is not used in the calculation. There is an assumption that the Earth is spherical for the purpose of this calculation. Returns 0 if the type of this coordinate or the type of \a other is QCoordinate::InvalidCoordinate. */ qreal QCoordinate::azimuthTo(const QCoordinate &other) const { if (type() == QCoordinate::InvalidCoordinate || other.type() == QCoordinate::InvalidCoordinate) { return 0; } double dlon = QCoordinate_degToRad(other.d->lng - d->lng); double lat1Rad = QCoordinate_degToRad(d->lat); double lat2Rad = QCoordinate_degToRad(other.d->lat); double y = sin(dlon) * cos(lat2Rad); double x = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dlon); double whole; double fraction = modf(QCoordinate_radToDeg(atan2(y, x)), &whole); return qreal((int(whole + 360) % 360) + fraction); } /*! Returns this coordinate as a string in the specified \a format. For example, if this coordinate latitude-longitude coordinates of (-27.46758\unicode{0xB0}, 153.027892\unicode{0xB0}), these are the strings that are returned depending on \a format: \table \header \o \a format value \o Returned string \row \o \l DecimalDegrees \o -27.46758\unicode{0xB0}, 153.02789\unicode{0xB0} \row \o \l DecimalDegreesWithHemisphere \o 27.46758\unicode{0xB0} S, 153.02789\unicode{0xB0} E \row \o \l DegreesMinutes \o -27\unicode{0xB0} 28.054', 153\unicode{0xB0} 1.673' \row \o \l DegreesMinutesWithHemisphere \o 27\unicode{0xB0} 28.054 S', 153\unicode{0xB0} 1.673' E \row \o \l DegreesMinutesSeconds \o -27\unicode{0xB0} 28' 3.2", 153\unicode{0xB0} 1' 40.4" \row \o \l DegreesMinutesSecondsWithHemisphere \o 27\unicode{0xB0} 28' 3.2" S, 153\unicode{0xB0} 1' 40.4" E \endtable */ QString QCoordinate::toString(CoordinateFormat format) const { if (type() == QCoordinate::InvalidCoordinate) return QObject::tr("<Invalid coordinate>"); QString latStr; QString longStr; double absLat = qAbs(d->lat); double absLng = qAbs(d->lng); QChar symbol(0x00B0); // degrees symbol switch (format) { case DecimalDegrees: case DecimalDegreesWithHemisphere: { latStr = QString::number(absLat, 'f', 5) + symbol; longStr = QString::number(absLng, 'f', 5) + symbol; break; } case DegreesMinutes: case DegreesMinutesWithHemisphere: { double latMin = (absLat - int(absLat)) * 60; double lngMin = (absLng - int(absLng)) * 60; latStr = QString("%1%2 %3'") .arg(QString::number(int(absLat))) .arg(symbol) .arg(QString::number(latMin, 'f', 3)); longStr = QString("%1%2 %3'") .arg(QString::number(int(absLng))) .arg(symbol) .arg(QString::number(lngMin, 'f', 3)); break; } case DegreesMinutesSeconds: case DegreesMinutesSecondsWithHemisphere: { double latMin = (absLat - int(absLat)) * 60; double lngMin = (absLng - int(absLng)) * 60; double latSec = (latMin - int(latMin)) * 60; double lngSec = (lngMin - int(lngMin)) * 60; latStr = QString("%1%2 %3' %4\"") .arg(QString::number(int(absLat))) .arg(symbol) .arg(QString::number(int(latMin))) .arg(QString::number(latSec, 'f', 1)); longStr = QString("%1%2 %3' %4\"") .arg(QString::number(int(absLng))) .arg(symbol) .arg(QString::number(int(lngMin))) .arg(QString::number(lngSec, 'f', 1)); break; } } // now add the "-" to the start, or append the hemisphere char switch (format) { case DecimalDegrees: case DegreesMinutes: case DegreesMinutesSeconds: { if (d->lat < 0) latStr.insert(0, "-"); if (d->lng < 0) longStr.insert(0, "-"); break; } case DecimalDegreesWithHemisphere: case DegreesMinutesWithHemisphere: case DegreesMinutesSecondsWithHemisphere: { if (d->lat < 0) latStr.append(" S"); else if (d->lat > 0) latStr.append(" N"); if (d->lng < 0) longStr.append(" W"); else if (d->lng > 0) longStr.append(" E"); break; } } return QString("%1, %2").arg(latStr, longStr); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QCoordinate &coord) { dbg.nospace() << "QCoordinate(" << coord.latitude(); dbg.nospace() << ", "; dbg.nospace() << coord.longitude(); dbg.nospace() << ", "; if (coord.type() == QCoordinate::Coordinate3D) dbg.nospace() << coord.altitude(); else dbg.nospace() << '?'; dbg.nospace() << ')'; return dbg; } #endif <commit_msg>Define M_PI myself for when it's not found in math.h (causing build failure on Windows).<commit_after>/**************************************************************************** ** ** This file is part of the $PACKAGE_NAME$. ** ** Copyright (C) $THISYEAR$ $COMPANY_NAME$. ** ** $QT_EXTENDED_DUAL_LICENSE$ ** ****************************************************************************/ #include "qcoordinate.h" #include <QDateTime> #include <QHash> #include <QDebug> #include <qnumeric.h> #ifndef M_PI #define M_PI 3.14159265358979323846 #endif static const double QCoordinate_EARTH_MEAN_RADIUS = 6371.0072; inline static double QCoordinate_degToRad(double deg) { return deg * M_PI / 180; } inline static double QCoordinate_radToDeg(double rad) { return rad * 180 / M_PI; } class QCoordinatePrivate { public: double lat; double lng; double alt; }; /*! \class QCoordinate \brief The QCoordinate class defines a geographical position on the surface of the Earth. A QCoordinate is defined by latitude, longitude, and optionally, altitude. Use type() to determine whether a coordinate is a 2D coordinate (has latitude and longitude only) or 3D coordinate (has latitude, longitude and altitude). Use distanceTo() and azimuthTo() to calculate the distance and bearing between coordinates. The coordinate values should be specified using the WGS84 datum. */ /*! \enum QCoordinate::CoordinateType Defines the types of a coordinate. \value InvalidCoordinate An invalid coordinate. A coordinate is invalid if its latitude or longitude values are invalid. \value Coordinate2D A coordinate with valid latitude and longitude values. \value Coordinate3D A coordinate with valid latitude and longitude values, and also an altitude value. */ /*! \enum QCoordinate::CoordinateFormat Defines the possible formatting options for toString(). \value DecimalDegrees Returns a string representation of the coordinates in decimal degrees format. \value DecimalDegreesWithHemisphere Returns a string representation of the coordinates in decimal degrees format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \value DegreesMinutes Returns a string representation of the coordinates in degrees-minutes format. \value DegreesMinutesWithHemisphere Returns a string representation of the coordinates in degrees-minutes format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \value DegreesMinutesSeconds Returns a string representation of the coordinates in degrees-minutes-seconds format. \value DegreesMinutesSecondsWithHemisphere Returns a string representation of the coordinates in degrees-minutes-seconds format, using 'N', 'S', 'E' or 'W' to indicate the hemispheres of the coordinates. \sa toString() */ /*! Constructs a coordinate. The coordinate will be invalid until setLatitude() and setLongitude() have been called. */ QCoordinate::QCoordinate() : d(new QCoordinatePrivate) { d->lat = qQNaN(); d->lng = qQNaN(); d->alt = qQNaN(); } /*! Constructs a coordinate with the given \a latitude and \a longitude. */ QCoordinate::QCoordinate(double latitude, double longitude) : d(new QCoordinatePrivate) { d->lat = latitude; d->lng = longitude; d->alt = qQNaN(); } /*! Constructs a coordinate with the given \a latitude, \a longitude and \a altitude. */ QCoordinate::QCoordinate(double latitude, double longitude, double altitude) : d(new QCoordinatePrivate) { d->lat = latitude; d->lng = longitude; d->alt = altitude; } /*! Constructs a coordinate from the contents of \a other. */ QCoordinate::QCoordinate(const QCoordinate &other) : d(new QCoordinatePrivate) { operator=(other); } /*! Destroys the coordinate object. */ QCoordinate::~QCoordinate() { delete d; } /*! Assigns \a other to this coordinate and returns a reference to this coordinate. */ QCoordinate &QCoordinate::operator=(const QCoordinate &other) { if (this == &other) return *this; d->lat = other.d->lat; d->lng = other.d->lng; d->alt = other.d->alt; return *this; } /*! Returns true if the type() is Coordinate2D or Coordinate3D. */ bool QCoordinate::isValid() const { CoordinateType t = type(); return t == Coordinate2D || t == Coordinate3D; } /*! Returns the type of this coordinate. */ QCoordinate::CoordinateType QCoordinate::type() const { if ( (d->lat >= -90 && d->lat <= 90) && (d->lng >= -180 && d->lng <= 180) ) { if (qIsNaN(d->alt)) return Coordinate2D; return Coordinate3D; } return InvalidCoordinate; } /*! Returns the latitude, in decimal degrees. The return value is undefined if the latitude has not been set. A positive latitude indicates the Northern Hemisphere, and a negative latitude indicates the Southern Hemisphere. \sa setLatitude(), type() */ double QCoordinate::latitude() const { return d->lat; } /*! Sets the latitude (in decimal degrees) to \a latitude. The value should be in the WGS84 datum. To be valid, the latitude must be between -90 to 90 inclusive. \sa latitude() */ void QCoordinate::setLatitude(double latitude) { d->lat = latitude; } /*! Returns the longitude, in decimal degrees. The return value is undefined if the longitude has not been set. A positive longitude indicates the Eastern Hemisphere, and a negative longitude indicates the Western Hemisphere. \sa setLongitude(), type() */ double QCoordinate::longitude() const { return d->lng; } /*! Sets the longitude (in decimal degrees) to \a longitude. The value should be in the WGS84 datum. To be valid, the longitude must be between -180 to 180 inclusive. \sa longitude() */ void QCoordinate::setLongitude(double longitude) { d->lng = longitude; } /*! Returns the altitude (meters above sea level). The return value is undefined if the altitude has not been set. \sa setAltitude(), type() */ double QCoordinate::altitude() const { return d->alt; } /*! Sets the altitude (meters above sea level) to \a altitude. \sa altitude() */ void QCoordinate::setAltitude(double altitude) { d->alt = altitude; } /*! Returns the distance (in meters) from this coordinate to the coordinate specified by \a other. Altitude is not used in the calculation. This calculation returns the great-circle distance between the two coordinates, with an assumption that the Earth is spherical for the purpose of this calculation. Returns 0 if the type of this coordinate or the type of \a other is QCoordinate::InvalidCoordinate. */ qreal QCoordinate::distanceTo(const QCoordinate &other) const { if (type() == QCoordinate::InvalidCoordinate || other.type() == QCoordinate::InvalidCoordinate) { return 0; } // Haversine formula double dlat = QCoordinate_degToRad(other.d->lat - d->lat); double dlon = QCoordinate_degToRad(other.d->lng - d->lng); double y = sin(dlat/2) * sin(dlat/2) + cos(QCoordinate_degToRad(d->lat)) * cos(QCoordinate_degToRad(other.d->lat)) * sin(dlon/2) * sin(dlon/2); double x = 2 * atan2(sqrt(y), sqrt(1-y)); return qreal(x * QCoordinate_EARTH_MEAN_RADIUS * 1000); } /*! Returns the azimuth (or bearing) in degrees from this coordinate to the coordinate specified by \a other. Altitude is not used in the calculation. There is an assumption that the Earth is spherical for the purpose of this calculation. Returns 0 if the type of this coordinate or the type of \a other is QCoordinate::InvalidCoordinate. */ qreal QCoordinate::azimuthTo(const QCoordinate &other) const { if (type() == QCoordinate::InvalidCoordinate || other.type() == QCoordinate::InvalidCoordinate) { return 0; } double dlon = QCoordinate_degToRad(other.d->lng - d->lng); double lat1Rad = QCoordinate_degToRad(d->lat); double lat2Rad = QCoordinate_degToRad(other.d->lat); double y = sin(dlon) * cos(lat2Rad); double x = cos(lat1Rad) * sin(lat2Rad) - sin(lat1Rad) * cos(lat2Rad) * cos(dlon); double whole; double fraction = modf(QCoordinate_radToDeg(atan2(y, x)), &whole); return qreal((int(whole + 360) % 360) + fraction); } /*! Returns this coordinate as a string in the specified \a format. For example, if this coordinate latitude-longitude coordinates of (-27.46758\unicode{0xB0}, 153.027892\unicode{0xB0}), these are the strings that are returned depending on \a format: \table \header \o \a format value \o Returned string \row \o \l DecimalDegrees \o -27.46758\unicode{0xB0}, 153.02789\unicode{0xB0} \row \o \l DecimalDegreesWithHemisphere \o 27.46758\unicode{0xB0} S, 153.02789\unicode{0xB0} E \row \o \l DegreesMinutes \o -27\unicode{0xB0} 28.054', 153\unicode{0xB0} 1.673' \row \o \l DegreesMinutesWithHemisphere \o 27\unicode{0xB0} 28.054 S', 153\unicode{0xB0} 1.673' E \row \o \l DegreesMinutesSeconds \o -27\unicode{0xB0} 28' 3.2", 153\unicode{0xB0} 1' 40.4" \row \o \l DegreesMinutesSecondsWithHemisphere \o 27\unicode{0xB0} 28' 3.2" S, 153\unicode{0xB0} 1' 40.4" E \endtable */ QString QCoordinate::toString(CoordinateFormat format) const { if (type() == QCoordinate::InvalidCoordinate) return QObject::tr("<Invalid coordinate>"); QString latStr; QString longStr; double absLat = qAbs(d->lat); double absLng = qAbs(d->lng); QChar symbol(0x00B0); // degrees symbol switch (format) { case DecimalDegrees: case DecimalDegreesWithHemisphere: { latStr = QString::number(absLat, 'f', 5) + symbol; longStr = QString::number(absLng, 'f', 5) + symbol; break; } case DegreesMinutes: case DegreesMinutesWithHemisphere: { double latMin = (absLat - int(absLat)) * 60; double lngMin = (absLng - int(absLng)) * 60; latStr = QString("%1%2 %3'") .arg(QString::number(int(absLat))) .arg(symbol) .arg(QString::number(latMin, 'f', 3)); longStr = QString("%1%2 %3'") .arg(QString::number(int(absLng))) .arg(symbol) .arg(QString::number(lngMin, 'f', 3)); break; } case DegreesMinutesSeconds: case DegreesMinutesSecondsWithHemisphere: { double latMin = (absLat - int(absLat)) * 60; double lngMin = (absLng - int(absLng)) * 60; double latSec = (latMin - int(latMin)) * 60; double lngSec = (lngMin - int(lngMin)) * 60; latStr = QString("%1%2 %3' %4\"") .arg(QString::number(int(absLat))) .arg(symbol) .arg(QString::number(int(latMin))) .arg(QString::number(latSec, 'f', 1)); longStr = QString("%1%2 %3' %4\"") .arg(QString::number(int(absLng))) .arg(symbol) .arg(QString::number(int(lngMin))) .arg(QString::number(lngSec, 'f', 1)); break; } } // now add the "-" to the start, or append the hemisphere char switch (format) { case DecimalDegrees: case DegreesMinutes: case DegreesMinutesSeconds: { if (d->lat < 0) latStr.insert(0, "-"); if (d->lng < 0) longStr.insert(0, "-"); break; } case DecimalDegreesWithHemisphere: case DegreesMinutesWithHemisphere: case DegreesMinutesSecondsWithHemisphere: { if (d->lat < 0) latStr.append(" S"); else if (d->lat > 0) latStr.append(" N"); if (d->lng < 0) longStr.append(" W"); else if (d->lng > 0) longStr.append(" E"); break; } } return QString("%1, %2").arg(latStr, longStr); } #ifndef QT_NO_DEBUG_STREAM QDebug operator<<(QDebug dbg, const QCoordinate &coord) { dbg.nospace() << "QCoordinate(" << coord.latitude(); dbg.nospace() << ", "; dbg.nospace() << coord.longitude(); dbg.nospace() << ", "; if (coord.type() == QCoordinate::Coordinate3D) dbg.nospace() << coord.altitude(); else dbg.nospace() << '?'; dbg.nospace() << ')'; return dbg; } #endif <|endoftext|>
<commit_before>#include "queueloader.h" #include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <libgen.h> #include <unistd.h> #include "config.h" #include "configcontainer.h" #include "logger.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { QueueLoader::QueueLoader(const std::string& file, ConfigContainer& cfg_, std::function<void()> cb_require_view_update_) : queuefile(file) , cfg(cfg_) , cb_require_view_update(cb_require_view_update_) { } void QueueLoader::reload(std::vector<Download>& downloads, bool remove_unplayed) { std::vector<Download> dltemp; std::vector<Download> deletion_list; std::fstream f; for (const auto& dl : downloads) { // we are not allowed to reload if a download is in progress! if (dl.status() == DlStatus::DOWNLOADING) { LOG(Level::INFO, "QueueLoader::reload: aborting reload due to " "DlStatus::DOWNLOADING status"); return; } bool keep_entry = false; switch (dl.status()) { case DlStatus::QUEUED: case DlStatus::CANCELLED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: case DlStatus::READY: LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; break; case DlStatus::PLAYED: case DlStatus::FINISHED: if (!remove_unplayed) { LOG(Level::DEBUG, "QueueLoader::reload: storing %s to " "new " "vector", dl.url()); keep_entry = true; } break; default: break; } if (keep_entry) { dltemp.push_back(dl); } else { deletion_list.push_back(dl); } } f.open(queuefile.c_str(), std::fstream::in); bool comments_ignored = false; if (f.is_open()) { std::string line; do { std::getline(f, line); if (!f.eof() && line.length() > 0) { LOG(Level::DEBUG, "QueueLoader::reload: loaded `%s' from " "queue file", line); std::vector<std::string> fields = utils::tokenize_quoted(line); bool url_found = false; if (fields.empty()) { if (!comments_ignored) { std::cout << strprintf::fmt( _("WARNING: Comment found " "in %s. The queue file is regenerated " "when podboat exits and comments will " "be deleted. Press Enter to continue or " "Ctrl+C to abort"), queuefile) << std::endl; std::cin.ignore(); comments_ignored = true; } continue; } for (const auto& dl : dltemp) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' in old " "vector", fields[0]); url_found = true; break; } } for (const auto& dl : deletion_list) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' in scheduled for deletion " "vector", fields[0]); url_found = true; break; } } if (!url_found) { LOG(Level::INFO, "QueueLoader::reload: found " "`%s' " "nowhere -> storing to new " "vector", line); Download d(cb_require_view_update); std::string fn; if (fields.size() == 1) { fn = get_filename(fields[0]); } else { fn = fields[1]; } d.set_filename(fn); if (access(fn.c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' on file " "system " "-> mark as already " "downloaded", fn); if (fields.size() >= 3) { if (fields[2] == "downloaded") d.set_status( DlStatus:: READY); if (fields[2] == "played") d.set_status( DlStatus:: PLAYED); if (fields[2] == "finished") d.set_status( DlStatus:: FINISHED); } else d.set_status(DlStatus:: ALREADY_DOWNLOADED); // TODO: scrap DlStatus::ALREADY_DOWNLOADED state } else if ( access((fn + ConfigContainer:: PARTIAL_FILE_SUFFIX) .c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' on file " "system " "-> mark as partially " "downloaded", fn + ConfigContainer:: PARTIAL_FILE_SUFFIX); d.set_status(DlStatus:: ALREADY_DOWNLOADED); } d.set_url(fields[0]); dltemp.push_back(d); } } } while (!f.eof()); f.close(); } f.open(queuefile.c_str(), std::fstream::out); if (f.is_open()) { for (const auto& dl : dltemp) { f << dl.url() << " " << utils::quote(dl.filename()); if (dl.status() == DlStatus::READY) { f << " downloaded"; } if (dl.status() == DlStatus::PLAYED) { f << " played"; } if (dl.status() == DlStatus::FINISHED) { f << " finished"; } f << std::endl; } f.close(); } if (cfg.get_configvalue_as_bool("delete-played-files")) { for (const auto& dl : deletion_list) { const std::string filename = dl.filename(); LOG(Level::INFO, "Deleting file %s", filename); if (std::remove(filename.c_str()) != 0) { if (errno != ENOENT) { LOG(Level::ERROR, "Failed to delete file %s, error code: %d (%s)", filename, errno, strerror(errno)); } } } } downloads = dltemp; } std::string QueueLoader::get_filename(const std::string& str) { std::string fn = cfg.get_configvalue("download-path"); if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP) { fn.push_back(NEWSBEUTER_PATH_SEP); } char buf[1024]; snprintf(buf, sizeof(buf), "%s", str.c_str()); char* base = basename(buf); if (!base || strlen(base) == 0) { time_t t = time(nullptr); fn.append(utils::mt_strf_localtime("%Y-%b-%d-%H%M%S.unknown", t)); } else { fn.append(utils::replace_all(base, "'", "%27")); } return fn; } } // namespace podboat <commit_msg>pb-purge: Don't delete played files when they are not marked as finished<commit_after>#include "queueloader.h" #include <cerrno> #include <cstdlib> #include <cstdio> #include <cstring> #include <fstream> #include <iostream> #include <libgen.h> #include <unistd.h> #include "config.h" #include "configcontainer.h" #include "logger.h" #include "stflpp.h" #include "strprintf.h" #include "utils.h" using namespace newsboat; namespace podboat { QueueLoader::QueueLoader(const std::string& file, ConfigContainer& cfg_, std::function<void()> cb_require_view_update_) : queuefile(file) , cfg(cfg_) , cb_require_view_update(cb_require_view_update_) { } void QueueLoader::reload(std::vector<Download>& downloads, bool remove_unplayed) { std::vector<Download> dltemp; std::vector<Download> deletion_list; std::fstream f; for (const auto& dl : downloads) { // we are not allowed to reload if a download is in progress! if (dl.status() == DlStatus::DOWNLOADING) { LOG(Level::INFO, "QueueLoader::reload: aborting reload due to " "DlStatus::DOWNLOADING status"); return; } bool keep_entry = false; switch (dl.status()) { case DlStatus::QUEUED: case DlStatus::CANCELLED: case DlStatus::FAILED: case DlStatus::ALREADY_DOWNLOADED: case DlStatus::READY: case DlStatus::PLAYED: LOG(Level::DEBUG, "QueueLoader::reload: storing %s to new vector", dl.url()); keep_entry = true; break; case DlStatus::FINISHED: if (!remove_unplayed) { LOG(Level::DEBUG, "QueueLoader::reload: storing %s to " "new " "vector", dl.url()); keep_entry = true; } break; default: break; } if (keep_entry) { dltemp.push_back(dl); } else { deletion_list.push_back(dl); } } f.open(queuefile.c_str(), std::fstream::in); bool comments_ignored = false; if (f.is_open()) { std::string line; do { std::getline(f, line); if (!f.eof() && line.length() > 0) { LOG(Level::DEBUG, "QueueLoader::reload: loaded `%s' from " "queue file", line); std::vector<std::string> fields = utils::tokenize_quoted(line); bool url_found = false; if (fields.empty()) { if (!comments_ignored) { std::cout << strprintf::fmt( _("WARNING: Comment found " "in %s. The queue file is regenerated " "when podboat exits and comments will " "be deleted. Press Enter to continue or " "Ctrl+C to abort"), queuefile) << std::endl; std::cin.ignore(); comments_ignored = true; } continue; } for (const auto& dl : dltemp) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' in old " "vector", fields[0]); url_found = true; break; } } for (const auto& dl : deletion_list) { if (fields[0] == dl.url()) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' in scheduled for deletion " "vector", fields[0]); url_found = true; break; } } if (!url_found) { LOG(Level::INFO, "QueueLoader::reload: found " "`%s' " "nowhere -> storing to new " "vector", line); Download d(cb_require_view_update); std::string fn; if (fields.size() == 1) { fn = get_filename(fields[0]); } else { fn = fields[1]; } d.set_filename(fn); if (access(fn.c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' on file " "system " "-> mark as already " "downloaded", fn); if (fields.size() >= 3) { if (fields[2] == "downloaded") d.set_status( DlStatus:: READY); if (fields[2] == "played") d.set_status( DlStatus:: PLAYED); if (fields[2] == "finished") d.set_status( DlStatus:: FINISHED); } else d.set_status(DlStatus:: ALREADY_DOWNLOADED); // TODO: scrap DlStatus::ALREADY_DOWNLOADED state } else if ( access((fn + ConfigContainer:: PARTIAL_FILE_SUFFIX) .c_str(), F_OK) == 0) { LOG(Level::INFO, "QueueLoader::reload: " "found `%s' on file " "system " "-> mark as partially " "downloaded", fn + ConfigContainer:: PARTIAL_FILE_SUFFIX); d.set_status(DlStatus:: ALREADY_DOWNLOADED); } d.set_url(fields[0]); dltemp.push_back(d); } } } while (!f.eof()); f.close(); } f.open(queuefile.c_str(), std::fstream::out); if (f.is_open()) { for (const auto& dl : dltemp) { f << dl.url() << " " << utils::quote(dl.filename()); if (dl.status() == DlStatus::READY) { f << " downloaded"; } if (dl.status() == DlStatus::PLAYED) { f << " played"; } if (dl.status() == DlStatus::FINISHED) { f << " finished"; } f << std::endl; } f.close(); } if (cfg.get_configvalue_as_bool("delete-played-files")) { for (const auto& dl : deletion_list) { const std::string filename = dl.filename(); LOG(Level::INFO, "Deleting file %s", filename); if (std::remove(filename.c_str()) != 0) { if (errno != ENOENT) { LOG(Level::ERROR, "Failed to delete file %s, error code: %d (%s)", filename, errno, strerror(errno)); } } } } downloads = dltemp; } std::string QueueLoader::get_filename(const std::string& str) { std::string fn = cfg.get_configvalue("download-path"); if (fn[fn.length() - 1] != NEWSBEUTER_PATH_SEP) { fn.push_back(NEWSBEUTER_PATH_SEP); } char buf[1024]; snprintf(buf, sizeof(buf), "%s", str.c_str()); char* base = basename(buf); if (!base || strlen(base) == 0) { time_t t = time(nullptr); fn.append(utils::mt_strf_localtime("%Y-%b-%d-%H%M%S.unknown", t)); } else { fn.append(utils::replace_all(base, "'", "%27")); } return fn; } } // namespace podboat <|endoftext|>
<commit_before>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole_cxx.h" #include "async.h" #include "coroutine_c_api.h" #include "coroutine_socket.h" #include "coroutine_system.h" using swoole::CallbackManager; using swoole::coroutine::Socket; using swoole::coroutine::System; #ifdef SW_USE_MALLOC_TRIM #ifdef __APPLE__ #include <sys/malloc.h> #else #include <malloc.h> #endif #endif static void reactor_timeout(swReactor *reactor); static void reactor_finish(swReactor *reactor); static void reactor_begin(swReactor *reactor); static void defer_task_do(swReactor *reactor); static void defer_task_add(swReactor *reactor, swCallback callback, void *data); int swReactor_create(swReactor *reactor, int max_event) { int ret; bzero(reactor, sizeof(swReactor)); #ifdef HAVE_EPOLL ret = swReactorEpoll_create(reactor, max_event); #elif defined(HAVE_KQUEUE) ret = swReactorKqueue_create(reactor, max_event); #elif defined(HAVE_POLL) ret = swReactorPoll_create(reactor, max_event); #else ret = swReactorSelect_create(reactor); #endif reactor->running = 1; reactor->onFinish = reactor_finish; reactor->onTimeout = reactor_timeout; reactor->is_empty = swReactor_empty; reactor->can_exit = SwooleG.reactor_can_exit; reactor->write = swReactor_write; reactor->close = swReactor_close; reactor->defer = defer_task_add; reactor->defer_tasks = nullptr; reactor->default_write_handler = swReactor_onWrite; Socket::init_reactor(reactor); System::init_reactor(reactor); swClient_init_reactor(reactor); if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_REACTOR_CREATE]) { swoole_call_hook(SW_GLOBAL_HOOK_ON_REACTOR_CREATE, reactor); } return ret; } int swReactor_set_handler(swReactor *reactor, int _fdtype, swReactor_handler handle) { int fdtype = swReactor_fdtype(_fdtype); if (fdtype >= SW_MAX_FDTYPE) { swWarn("fdtype > SW_MAX_FDTYPE[%d]", SW_MAX_FDTYPE); return SW_ERR; } if (swReactor_event_read(_fdtype)) { reactor->read_handler[fdtype] = handle; } else if (swReactor_event_write(_fdtype)) { reactor->write_handler[fdtype] = handle; } else if (swReactor_event_error(_fdtype)) { reactor->error_handler[fdtype] = handle; } else { swWarn("unknow fdtype"); return SW_ERR; } return SW_OK; } int swReactor_empty(swReactor *reactor) { if (reactor->timer && reactor->timer->num > 0) { return SW_FALSE; } if (reactor->defer_tasks) { return SW_FALSE; } if (swoole_coroutine_wait_count() > 0) { return SW_FALSE; } if (SwooleTG.reactor->co_signal_listener_num > 0) { return SW_FALSE; } int event_num = reactor->event_num; int empty = SW_FALSE; //aio thread pool if (SwooleTG.aio_init && SwooleTG.aio_task_num == 0) { event_num--; } //signalfd if (swReactor_isset_handler(reactor, SW_FD_SIGNAL)) { event_num--; } //no event if (event_num == 0) { empty = SW_TRUE; } //custom if (reactor->can_exit && !reactor->can_exit(reactor)) { empty = SW_FALSE; } return empty; } /** * execute when reactor timeout and reactor finish */ static void reactor_finish(swReactor *reactor) { //check timer if (reactor->check_timer) { swTimer_select(reactor->timer); } //defer tasks if (reactor->defer_tasks) { defer_task_do(reactor); } //callback at the end if (reactor->idle_task.callback) { reactor->idle_task.callback(reactor->idle_task.data); } //check signal if (sw_unlikely(reactor->singal_no)) { swSignal_callback(reactor->singal_no); reactor->singal_no = 0; } //the event loop is empty if (reactor->wait_exit && reactor->is_empty(reactor)) { reactor->running = 0; } #ifdef SW_USE_MALLOC_TRIM time_t now = time(NULL); if (reactor->last_malloc_trim_time < now - SW_MALLOC_TRIM_INTERVAL) { malloc_trim(SW_MALLOC_TRIM_PAD); reactor->last_malloc_trim_time = now; } #endif } static void reactor_timeout(swReactor *reactor) { reactor_finish(reactor); } void swReactor_activate_future_task(swReactor *reactor) { reactor->onBegin = reactor_begin; } static void reactor_begin(swReactor *reactor) { if (reactor->future_task.callback) { reactor->future_task.callback(reactor->future_task.data); } } int swReactor_close(swReactor *reactor, swSocket *socket) { if (socket->out_buffer) { swBuffer_free(socket->out_buffer); } if (socket->in_buffer) { swBuffer_free(socket->in_buffer); } swTraceLog(SW_TRACE_CLOSE, "fd=%d", socket->fd); swSocket_free(socket); return SW_OK; } int swReactor_write(swReactor *reactor, swSocket *socket, const void *buf, int n) { int ret; swBuffer *buffer = socket->out_buffer; const char *ptr = (const char *) buf; int fd = socket->fd; if (socket->buffer_size == 0) { socket->buffer_size = SwooleG.socket_buffer_size; } if (socket->nonblock == 0) { swoole_fcntl_set_option(socket->fd, 1, -1); socket->nonblock = 1; } if ((uint32_t) n > socket->buffer_size) { swoole_error_log(SW_LOG_WARNING, SW_ERROR_PACKAGE_LENGTH_TOO_LARGE, "data is too large, cannot exceed buffer size"); return SW_ERR; } if (swBuffer_empty(buffer)) { #ifdef SW_USE_OPENSSL if (socket->ssl_send) { goto _do_buffer; } #endif _do_send: ret = swSocket_send(socket, ptr, n, 0); if (ret > 0) { if (n == ret) { return ret; } else { ptr += ret; n -= ret; goto _do_buffer; } } else if (swSocket_error(errno) == SW_WAIT) { _do_buffer: if (!socket->out_buffer) { buffer = swBuffer_new(socket->chunk_size); if (!buffer) { swWarn("create worker buffer failed"); return SW_ERR; } socket->out_buffer = buffer; } swReactor_add_write_event(reactor, socket); goto _append_buffer; } else if (errno == EINTR) { goto _do_send; } else { SwooleG.error = errno; return SW_ERR; } } else { _append_buffer: if (buffer->length > socket->buffer_size) { if (socket->dontwait) { SwooleG.error = SW_ERROR_OUTPUT_BUFFER_OVERFLOW; return SW_ERR; } else { swoole_error_log(SW_LOG_WARNING, SW_ERROR_OUTPUT_BUFFER_OVERFLOW, "socket#%d output buffer overflow", fd); swYield(); swSocket_wait(socket->fd, SW_SOCKET_OVERFLOW_WAIT, SW_EVENT_WRITE); } } if (swBuffer_append(buffer, ptr, n) < 0) { return SW_ERR; } } return SW_OK; } int swReactor_onWrite(swReactor *reactor, swEvent *ev) { int ret; swSocket *socket = ev->socket; swBuffer_chunk *chunk = NULL; swBuffer *buffer = socket->out_buffer; //send to socket while (!swBuffer_empty(buffer)) { chunk = swBuffer_get_chunk(buffer); if (chunk->type == SW_CHUNK_CLOSE) { _close_fd: reactor->close(reactor, ev->socket); return SW_OK; } else if (chunk->type == SW_CHUNK_SENDFILE) { ret = swSocket_onSendfile(socket, chunk); } else { ret = swSocket_buffer_send(socket); } if (ret < 0) { if (socket->close_wait) { goto _close_fd; } else if (socket->send_wait) { return SW_OK; } } } //remove EPOLLOUT event if (swBuffer_empty(buffer)) { swReactor_remove_write_event(reactor, ev->socket); } return SW_OK; } int swReactor_wait_write_buffer(swReactor *reactor, swSocket *socket) { swEvent event; if (!swBuffer_empty(socket->out_buffer)) { swSocket_set_block(socket); event.fd = socket->fd; return swReactor_onWrite(reactor, &event); } return SW_OK; } void swReactor_add_destroy_callback(swReactor *reactor, swCallback cb, void *data) { CallbackManager *cm = (CallbackManager *) reactor->destroy_callbacks; if (cm == nullptr) { cm = new CallbackManager; reactor->destroy_callbacks = cm; } cm->append(cb, data); } static void defer_task_do(swReactor *reactor) { CallbackManager *cm = (CallbackManager *) reactor->defer_tasks; reactor->defer_tasks = nullptr; cm->execute(); delete cm; } static void defer_task_add(swReactor *reactor, swCallback callback, void *data) { CallbackManager *cm = (CallbackManager *) reactor->defer_tasks; if (cm == nullptr) { cm = new CallbackManager; reactor->defer_tasks = cm; } cm->append(callback, data); } void swReactor_destroy(swReactor *reactor) { if (reactor->destroy_callbacks) { CallbackManager *cm = (CallbackManager *) reactor->destroy_callbacks; cm->execute(); reactor->destroy_callbacks = nullptr; delete cm; } reactor->free(reactor); } <commit_msg>improve: set buffer NULL (#3210)<commit_after>/* +----------------------------------------------------------------------+ | Swoole | +----------------------------------------------------------------------+ | This source file is subject to version 2.0 of the Apache license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.apache.org/licenses/LICENSE-2.0.html | | If you did not receive a copy of the Apache2.0 license and are unable| | to obtain it through the world-wide-web, please send a note to | | license@swoole.com so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Tianfeng Han <mikan.tenny@gmail.com> | +----------------------------------------------------------------------+ */ #include "swoole_cxx.h" #include "async.h" #include "coroutine_c_api.h" #include "coroutine_socket.h" #include "coroutine_system.h" using swoole::CallbackManager; using swoole::coroutine::Socket; using swoole::coroutine::System; #ifdef SW_USE_MALLOC_TRIM #ifdef __APPLE__ #include <sys/malloc.h> #else #include <malloc.h> #endif #endif static void reactor_timeout(swReactor *reactor); static void reactor_finish(swReactor *reactor); static void reactor_begin(swReactor *reactor); static void defer_task_do(swReactor *reactor); static void defer_task_add(swReactor *reactor, swCallback callback, void *data); int swReactor_create(swReactor *reactor, int max_event) { int ret; bzero(reactor, sizeof(swReactor)); #ifdef HAVE_EPOLL ret = swReactorEpoll_create(reactor, max_event); #elif defined(HAVE_KQUEUE) ret = swReactorKqueue_create(reactor, max_event); #elif defined(HAVE_POLL) ret = swReactorPoll_create(reactor, max_event); #else ret = swReactorSelect_create(reactor); #endif reactor->running = 1; reactor->onFinish = reactor_finish; reactor->onTimeout = reactor_timeout; reactor->is_empty = swReactor_empty; reactor->can_exit = SwooleG.reactor_can_exit; reactor->write = swReactor_write; reactor->close = swReactor_close; reactor->defer = defer_task_add; reactor->defer_tasks = nullptr; reactor->default_write_handler = swReactor_onWrite; Socket::init_reactor(reactor); System::init_reactor(reactor); swClient_init_reactor(reactor); if (SwooleG.hooks[SW_GLOBAL_HOOK_ON_REACTOR_CREATE]) { swoole_call_hook(SW_GLOBAL_HOOK_ON_REACTOR_CREATE, reactor); } return ret; } int swReactor_set_handler(swReactor *reactor, int _fdtype, swReactor_handler handle) { int fdtype = swReactor_fdtype(_fdtype); if (fdtype >= SW_MAX_FDTYPE) { swWarn("fdtype > SW_MAX_FDTYPE[%d]", SW_MAX_FDTYPE); return SW_ERR; } if (swReactor_event_read(_fdtype)) { reactor->read_handler[fdtype] = handle; } else if (swReactor_event_write(_fdtype)) { reactor->write_handler[fdtype] = handle; } else if (swReactor_event_error(_fdtype)) { reactor->error_handler[fdtype] = handle; } else { swWarn("unknow fdtype"); return SW_ERR; } return SW_OK; } int swReactor_empty(swReactor *reactor) { if (reactor->timer && reactor->timer->num > 0) { return SW_FALSE; } if (reactor->defer_tasks) { return SW_FALSE; } if (swoole_coroutine_wait_count() > 0) { return SW_FALSE; } if (SwooleTG.reactor->co_signal_listener_num > 0) { return SW_FALSE; } int event_num = reactor->event_num; int empty = SW_FALSE; //aio thread pool if (SwooleTG.aio_init && SwooleTG.aio_task_num == 0) { event_num--; } //signalfd if (swReactor_isset_handler(reactor, SW_FD_SIGNAL)) { event_num--; } //no event if (event_num == 0) { empty = SW_TRUE; } //custom if (reactor->can_exit && !reactor->can_exit(reactor)) { empty = SW_FALSE; } return empty; } /** * execute when reactor timeout and reactor finish */ static void reactor_finish(swReactor *reactor) { //check timer if (reactor->check_timer) { swTimer_select(reactor->timer); } //defer tasks if (reactor->defer_tasks) { defer_task_do(reactor); } //callback at the end if (reactor->idle_task.callback) { reactor->idle_task.callback(reactor->idle_task.data); } //check signal if (sw_unlikely(reactor->singal_no)) { swSignal_callback(reactor->singal_no); reactor->singal_no = 0; } //the event loop is empty if (reactor->wait_exit && reactor->is_empty(reactor)) { reactor->running = 0; } #ifdef SW_USE_MALLOC_TRIM time_t now = time(NULL); if (reactor->last_malloc_trim_time < now - SW_MALLOC_TRIM_INTERVAL) { malloc_trim(SW_MALLOC_TRIM_PAD); reactor->last_malloc_trim_time = now; } #endif } static void reactor_timeout(swReactor *reactor) { reactor_finish(reactor); } void swReactor_activate_future_task(swReactor *reactor) { reactor->onBegin = reactor_begin; } static void reactor_begin(swReactor *reactor) { if (reactor->future_task.callback) { reactor->future_task.callback(reactor->future_task.data); } } int swReactor_close(swReactor *reactor, swSocket *socket) { if (socket->out_buffer) { swBuffer_free(socket->out_buffer); socket->out_buffer = NULL; } if (socket->in_buffer) { swBuffer_free(socket->in_buffer); socket->in_buffer = NULL; } swTraceLog(SW_TRACE_CLOSE, "fd=%d", socket->fd); swSocket_free(socket); return SW_OK; } int swReactor_write(swReactor *reactor, swSocket *socket, const void *buf, int n) { int ret; swBuffer *buffer = socket->out_buffer; const char *ptr = (const char *) buf; int fd = socket->fd; if (socket->buffer_size == 0) { socket->buffer_size = SwooleG.socket_buffer_size; } if (socket->nonblock == 0) { swoole_fcntl_set_option(socket->fd, 1, -1); socket->nonblock = 1; } if ((uint32_t) n > socket->buffer_size) { swoole_error_log(SW_LOG_WARNING, SW_ERROR_PACKAGE_LENGTH_TOO_LARGE, "data is too large, cannot exceed buffer size"); return SW_ERR; } if (swBuffer_empty(buffer)) { #ifdef SW_USE_OPENSSL if (socket->ssl_send) { goto _do_buffer; } #endif _do_send: ret = swSocket_send(socket, ptr, n, 0); if (ret > 0) { if (n == ret) { return ret; } else { ptr += ret; n -= ret; goto _do_buffer; } } else if (swSocket_error(errno) == SW_WAIT) { _do_buffer: if (!socket->out_buffer) { buffer = swBuffer_new(socket->chunk_size); if (!buffer) { swWarn("create worker buffer failed"); return SW_ERR; } socket->out_buffer = buffer; } swReactor_add_write_event(reactor, socket); goto _append_buffer; } else if (errno == EINTR) { goto _do_send; } else { SwooleG.error = errno; return SW_ERR; } } else { _append_buffer: if (buffer->length > socket->buffer_size) { if (socket->dontwait) { SwooleG.error = SW_ERROR_OUTPUT_BUFFER_OVERFLOW; return SW_ERR; } else { swoole_error_log(SW_LOG_WARNING, SW_ERROR_OUTPUT_BUFFER_OVERFLOW, "socket#%d output buffer overflow", fd); swYield(); swSocket_wait(socket->fd, SW_SOCKET_OVERFLOW_WAIT, SW_EVENT_WRITE); } } if (swBuffer_append(buffer, ptr, n) < 0) { return SW_ERR; } } return SW_OK; } int swReactor_onWrite(swReactor *reactor, swEvent *ev) { int ret; swSocket *socket = ev->socket; swBuffer_chunk *chunk = NULL; swBuffer *buffer = socket->out_buffer; //send to socket while (!swBuffer_empty(buffer)) { chunk = swBuffer_get_chunk(buffer); if (chunk->type == SW_CHUNK_CLOSE) { _close_fd: reactor->close(reactor, ev->socket); return SW_OK; } else if (chunk->type == SW_CHUNK_SENDFILE) { ret = swSocket_onSendfile(socket, chunk); } else { ret = swSocket_buffer_send(socket); } if (ret < 0) { if (socket->close_wait) { goto _close_fd; } else if (socket->send_wait) { return SW_OK; } } } //remove EPOLLOUT event if (swBuffer_empty(buffer)) { swReactor_remove_write_event(reactor, ev->socket); } return SW_OK; } int swReactor_wait_write_buffer(swReactor *reactor, swSocket *socket) { swEvent event; if (!swBuffer_empty(socket->out_buffer)) { swSocket_set_block(socket); event.fd = socket->fd; return swReactor_onWrite(reactor, &event); } return SW_OK; } void swReactor_add_destroy_callback(swReactor *reactor, swCallback cb, void *data) { CallbackManager *cm = (CallbackManager *) reactor->destroy_callbacks; if (cm == nullptr) { cm = new CallbackManager; reactor->destroy_callbacks = cm; } cm->append(cb, data); } static void defer_task_do(swReactor *reactor) { CallbackManager *cm = (CallbackManager *) reactor->defer_tasks; reactor->defer_tasks = nullptr; cm->execute(); delete cm; } static void defer_task_add(swReactor *reactor, swCallback callback, void *data) { CallbackManager *cm = (CallbackManager *) reactor->defer_tasks; if (cm == nullptr) { cm = new CallbackManager; reactor->defer_tasks = cm; } cm->append(callback, data); } void swReactor_destroy(swReactor *reactor) { if (reactor->destroy_callbacks) { CallbackManager *cm = (CallbackManager *) reactor->destroy_callbacks; cm->execute(); reactor->destroy_callbacks = nullptr; delete cm; } reactor->free(reactor); } <|endoftext|>
<commit_before>/* * Copyright (c) 2016 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include <unicode/ucsdet.h> # include <unicode/ucnv.h> #else # ifdef _MSC_VER # error MSVC builds require ICU # endif #endif #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> #else # ifndef LCF_SUPPORT_ICU # include <iconv.h> # endif # include <locale> #endif #include <cstdlib> #include <cstdio> #include <sstream> #include <vector> #include "data.h" #include "inireader.h" #include "ldb_reader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); if (codepage == 932) { #ifdef LCF_SUPPORT_ICU return "ibm-943_P15A-2003"; #else return "SHIFT_JIS"; #endif } if (codepage == 949) { #ifdef LCF_SUPPORT_ICU return "windows-949-2000"; #else return "cp949"; #endif } std::ostringstream out; #ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; #else out << "CP" << codepage; #endif // Looks like a valid codepage std::string outs = out.str(); return outs; } std::string ReaderUtil::DetectEncoding(const std::string& database_file) { std::string encoding; #ifdef LCF_SUPPORT_ICU std::ostringstream text; //Populate Data::terms and Data::system or will empty by default even if load fails LDB_Reader::Load(database_file, ""); text << Data::terms.menu_save << " " << Data::terms.menu_quit << " " << Data::terms.new_game << " " << Data::terms.load_game << " " << Data::terms.exit_game << " " << Data::terms.status << " " << Data::terms.row << " " << Data::terms.order << " " << Data::terms.wait_on << " " << Data::terms.wait_off << " " << Data::terms.level << " " << Data::terms.health_points << " " << Data::terms.spirit_points << " " << Data::terms.normal_status << " " << Data::terms.exp_short << " " << Data::terms.lvl_short << " " << Data::terms.hp_short << " " << Data::terms.sp_short << " " << Data::terms.sp_cost << " " << Data::terms.attack << " " << Data::terms.defense << " " << Data::terms.spirit << " " << Data::terms.agility << " " << Data::terms.weapon << " " << Data::terms.shield << " " << Data::terms.armor << " " << Data::terms.helmet << " " << Data::terms.accessory << " " << Data::terms.save_game_message << " " << Data::terms.load_game_message << " " << Data::terms.file << " " << Data::terms.exit_game_message << " " << Data::terms.yes << " " << Data::terms.no << " " << Data::system.boat_name << " " << Data::system.ship_name << " " << Data::system.airship_name << " " << Data::system.title_name << " " << Data::system.gameover_name << " " << Data::system.system_name << " " << Data::system.system2_name << " " << Data::system.battletest_background << " " << Data::system.frame_name; // Checks if there are more than the above 42 spaces (no data) if (text.str().size() > 42) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); std::string s = text.str(); ucsdet_setText(detector, s.c_str(), s.length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); // Fixes to ensure proper Windows encodings if (encoding == "Shift_JIS") { encoding = "ibm-943_P15A-2003"; // Japanese with \ as backslash } else if (encoding == "EUC-KR") { encoding = "windows-949-2000"; // Korean with \ as backlash } else if (encoding == "ISO-8859-1" || encoding == "windows-1252") { encoding = "ibm-5348_P100-1997"; // Occidental with Euro } else if (encoding == "ISO-8859-2" || encoding == "windows-1250") { encoding = "ibm-5346_P100-1998"; // Central Europe with Euro } else if (encoding == "ISO-8859-5" || encoding == "windows-1251") { encoding = "ibm-5347_P100-1998"; // Cyrillic with Euro } else if (encoding == "ISO-8859-6" || encoding == "windows-1256") { encoding = "ibm-9448_X100-2005"; // Arabic with Euro + 8 chars } else if (encoding == "ISO-8859-7" || encoding == "windows-1253") { encoding = "ibm-5349_P100-1998"; // Greek with Euro } else if (encoding == "ISO-8859-8" || encoding == "windows-1255") { encoding = "ibm-9447_P100-2002"; // Hebrew with Euro } } #endif return encoding; } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 int codepage = GetACP(); #elif __ANDROID__ // No std::locale support in NDK // Doesn't really matter because the Android version auto-detects via ICU int codepage = 1252; #else int codepage = 1252; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") codepage = 874; else if (loc_lang == "ja") codepage = 932; else if (loc_full == "zh_CN" || loc_full == "zh_SG") codepage = 936; else if (loc_lang == "ko") codepage = 949; else if (loc_full == "zh_TW" || loc_full == "zh_HK") codepage = 950; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") codepage = 1250; else if (loc_lang == "ru") codepage = 1251; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") codepage = 1252; else if (loc_lang == "el") codepage = 1253; else if (loc_lang == "tr") codepage = 1254; else if (loc_lang == "he") codepage = 1255; else if (loc_lang == "ar") codepage = 1256; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") codepage = 1257; else if (loc_lang == "vi") codepage = 1258; #endif return CodepageToEncoding(codepage); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string src_enc_str = src_enc; std::string dst_enc_str = dst_enc; if (src_enc.empty() || dst_enc.empty() || str_to_encode.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { src_enc_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } if (atoi(dst_enc.c_str()) > 0) { dst_enc_str = ReaderUtil::CodepageToEncoding(atoi(dst_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar* unicode_str = new UChar[size]; UConverter *conv; int length; std::string result_str; conv = ucnv_open(src_enc_str.c_str(), &status); if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) { fprintf(stderr, "liblcf: ucnv_open() error for source encoding \"%s\": %s\n", src_enc_str.c_str(), u_errorName(status)); return std::string(); } status = U_ZERO_ERROR; length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) { fprintf(stderr, "liblcf: ucnv_toUChars() error when encoding \"%s\": %s\n", str_to_encode.c_str(), u_errorName(status)); delete[] unicode_str; return std::string(); } char* result = new char[length * 4]; conv = ucnv_open(dst_enc_str.c_str(), &status); if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) { fprintf(stderr, "liblcf: ucnv_open() error for destination encoding \"%s\": %s\n", dst_enc_str.c_str(), u_errorName(status)); delete[] unicode_str; delete[] result; return std::string(); } status = U_ZERO_ERROR; ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) { fprintf(stderr, "liblcf: ucnv_fromUChars() error: %s\n", u_errorName(status)); delete[] unicode_str; delete[] result; return std::string(); } result_str = result; delete[] unicode_str; delete[] result; return std::string(result_str); #else iconv_t cd = iconv_open(dst_enc_str.c_str(), src_enc_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; #endif } <commit_msg>Remove unnecesary spaces in the text for the encoding detector<commit_after>/* * Copyright (c) 2016 liblcf authors * This file is released under the MIT License * http://opensource.org/licenses/MIT */ #include "reader_options.h" #ifdef LCF_SUPPORT_ICU # include <unicode/ucsdet.h> # include <unicode/ucnv.h> #else # ifdef _MSC_VER # error MSVC builds require ICU # endif #endif #ifdef _WIN32 # define WIN32_LEAN_AND_MEAN # ifndef NOMINMAX # define NOMINMAX # endif # include <windows.h> #else # ifndef LCF_SUPPORT_ICU # include <iconv.h> # endif # include <locale> #endif #include <cstdlib> #include <cstdio> #include <sstream> #include <vector> #include "data.h" #include "inireader.h" #include "ldb_reader.h" #include "reader_util.h" namespace ReaderUtil { } std::string ReaderUtil::CodepageToEncoding(int codepage) { if (codepage == 0) return std::string(); if (codepage == 932) { #ifdef LCF_SUPPORT_ICU return "ibm-943_P15A-2003"; #else return "SHIFT_JIS"; #endif } if (codepage == 949) { #ifdef LCF_SUPPORT_ICU return "windows-949-2000"; #else return "cp949"; #endif } std::ostringstream out; #ifdef LCF_SUPPORT_ICU out << "windows-" << codepage; #else out << "CP" << codepage; #endif // Looks like a valid codepage std::string outs = out.str(); return outs; } std::string ReaderUtil::DetectEncoding(const std::string& database_file) { std::string encoding; #ifdef LCF_SUPPORT_ICU std::ostringstream text; //Populate Data::terms and Data::system or will empty by default even if load fails LDB_Reader::Load(database_file, ""); text << Data::terms.menu_save << Data::terms.menu_quit << Data::terms.new_game << Data::terms.load_game << Data::terms.exit_game << Data::terms.status << Data::terms.row << Data::terms.order << Data::terms.wait_on << Data::terms.wait_off << Data::terms.level << Data::terms.health_points << Data::terms.spirit_points << Data::terms.normal_status << Data::terms.exp_short << Data::terms.lvl_short << Data::terms.hp_short << Data::terms.sp_short << Data::terms.sp_cost << Data::terms.attack << Data::terms.defense << Data::terms.spirit << Data::terms.agility << Data::terms.weapon << Data::terms.shield << Data::terms.armor << Data::terms.helmet << Data::terms.accessory << Data::terms.save_game_message << Data::terms.load_game_message << Data::terms.file << Data::terms.exit_game_message << Data::terms.yes << Data::terms.no << Data::system.boat_name << Data::system.ship_name << Data::system.airship_name << Data::system.title_name << Data::system.gameover_name << Data::system.system_name << Data::system.system2_name << Data::system.battletest_background << Data::system.frame_name; if (!text.str().empty()) { UErrorCode status = U_ZERO_ERROR; UCharsetDetector* detector = ucsdet_open(&status); std::string s = text.str(); ucsdet_setText(detector, s.c_str(), s.length(), &status); const UCharsetMatch* match = ucsdet_detect(detector, &status); if (match != NULL) { encoding = ucsdet_getName(match, &status); } ucsdet_close(detector); // Fixes to ensure proper Windows encodings if (encoding == "Shift_JIS") { encoding = "ibm-943_P15A-2003"; // Japanese with \ as backslash } else if (encoding == "EUC-KR") { encoding = "windows-949-2000"; // Korean with \ as backlash } else if (encoding == "ISO-8859-1" || encoding == "windows-1252") { encoding = "ibm-5348_P100-1997"; // Occidental with Euro } else if (encoding == "ISO-8859-2" || encoding == "windows-1250") { encoding = "ibm-5346_P100-1998"; // Central Europe with Euro } else if (encoding == "ISO-8859-5" || encoding == "windows-1251") { encoding = "ibm-5347_P100-1998"; // Cyrillic with Euro } else if (encoding == "ISO-8859-6" || encoding == "windows-1256") { encoding = "ibm-9448_X100-2005"; // Arabic with Euro + 8 chars } else if (encoding == "ISO-8859-7" || encoding == "windows-1253") { encoding = "ibm-5349_P100-1998"; // Greek with Euro } else if (encoding == "ISO-8859-8" || encoding == "windows-1255") { encoding = "ibm-9447_P100-2002"; // Hebrew with Euro } } #endif return encoding; } std::string ReaderUtil::GetEncoding(const std::string& ini_file) { INIReader ini(ini_file); if (ini.ParseError() != -1) { std::string encoding = ini.Get("EasyRPG", "Encoding", std::string()); if (!encoding.empty()) { return ReaderUtil::CodepageToEncoding(atoi(encoding.c_str())); } } return std::string(); } std::string ReaderUtil::GetLocaleEncoding() { #ifdef _WIN32 int codepage = GetACP(); #elif __ANDROID__ // No std::locale support in NDK // Doesn't really matter because the Android version auto-detects via ICU int codepage = 1252; #else int codepage = 1252; std::locale loc = std::locale(""); // Gets the language and culture part only std::string loc_full = loc.name().substr(0, loc.name().find_first_of("@.")); // Gets the language part only std::string loc_lang = loc.name().substr(0, loc.name().find_first_of("_")); if (loc_lang == "th") codepage = 874; else if (loc_lang == "ja") codepage = 932; else if (loc_full == "zh_CN" || loc_full == "zh_SG") codepage = 936; else if (loc_lang == "ko") codepage = 949; else if (loc_full == "zh_TW" || loc_full == "zh_HK") codepage = 950; else if (loc_lang == "cs" || loc_lang == "hu" || loc_lang == "pl" || loc_lang == "ro" || loc_lang == "hr" || loc_lang == "sk" || loc_lang == "sl") codepage = 1250; else if (loc_lang == "ru") codepage = 1251; else if (loc_lang == "ca" || loc_lang == "da" || loc_lang == "de" || loc_lang == "en" || loc_lang == "es" || loc_lang == "fi" || loc_lang == "fr" || loc_lang == "it" || loc_lang == "nl" || loc_lang == "nb" || loc_lang == "pt" || loc_lang == "sv" || loc_lang == "eu") codepage = 1252; else if (loc_lang == "el") codepage = 1253; else if (loc_lang == "tr") codepage = 1254; else if (loc_lang == "he") codepage = 1255; else if (loc_lang == "ar") codepage = 1256; else if (loc_lang == "et" || loc_lang == "lt" || loc_lang == "lv") codepage = 1257; else if (loc_lang == "vi") codepage = 1258; #endif return CodepageToEncoding(codepage); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& source_encoding) { return ReaderUtil::Recode(str_to_encode, source_encoding, "UTF-8"); } std::string ReaderUtil::Recode(const std::string& str_to_encode, const std::string& src_enc, const std::string& dst_enc) { std::string src_enc_str = src_enc; std::string dst_enc_str = dst_enc; if (src_enc.empty() || dst_enc.empty() || str_to_encode.empty()) { return str_to_encode; } if (atoi(src_enc.c_str()) > 0) { src_enc_str = ReaderUtil::CodepageToEncoding(atoi(src_enc.c_str())); } if (atoi(dst_enc.c_str()) > 0) { dst_enc_str = ReaderUtil::CodepageToEncoding(atoi(dst_enc.c_str())); } #ifdef LCF_SUPPORT_ICU UErrorCode status = U_ZERO_ERROR; int size = str_to_encode.size() * 4; UChar* unicode_str = new UChar[size]; UConverter *conv; int length; std::string result_str; conv = ucnv_open(src_enc_str.c_str(), &status); if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) { fprintf(stderr, "liblcf: ucnv_open() error for source encoding \"%s\": %s\n", src_enc_str.c_str(), u_errorName(status)); return std::string(); } status = U_ZERO_ERROR; length = ucnv_toUChars(conv, unicode_str, size, str_to_encode.c_str(), -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) { fprintf(stderr, "liblcf: ucnv_toUChars() error when encoding \"%s\": %s\n", str_to_encode.c_str(), u_errorName(status)); delete[] unicode_str; return std::string(); } char* result = new char[length * 4]; conv = ucnv_open(dst_enc_str.c_str(), &status); if (status != U_ZERO_ERROR && status != U_AMBIGUOUS_ALIAS_WARNING) { fprintf(stderr, "liblcf: ucnv_open() error for destination encoding \"%s\": %s\n", dst_enc_str.c_str(), u_errorName(status)); delete[] unicode_str; delete[] result; return std::string(); } status = U_ZERO_ERROR; ucnv_fromUChars(conv, result, length * 4, unicode_str, -1, &status); ucnv_close(conv); if (status != U_ZERO_ERROR) { fprintf(stderr, "liblcf: ucnv_fromUChars() error: %s\n", u_errorName(status)); delete[] unicode_str; delete[] result; return std::string(); } result_str = result; delete[] unicode_str; delete[] result; return std::string(result_str); #else iconv_t cd = iconv_open(dst_enc_str.c_str(), src_enc_str.c_str()); if (cd == (iconv_t)-1) return str_to_encode; char *src = const_cast<char *>(str_to_encode.c_str()); size_t src_left = str_to_encode.size(); size_t dst_size = str_to_encode.size() * 5 + 10; char *dst = new char[dst_size]; size_t dst_left = dst_size; # ifdef ICONV_CONST char ICONV_CONST *p = src; # else char *p = src; # endif char *q = dst; size_t status = iconv(cd, &p, &src_left, &q, &dst_left); iconv_close(cd); if (status == (size_t) -1 || src_left > 0) { delete[] dst; return std::string(); } *q++ = '\0'; std::string result(dst); delete[] dst; return result; #endif } <|endoftext|>
<commit_before>#include "reidmanager.h" #include <iostream> #include <fstream> #include <list> using namespace std; static const float thresholdValueSamePerson = 0.5; ReidManager::ReidManager() { Features::getInstance(); } void ReidManager::computeNext() { // Get the next received sequence string nextSeqString = getNextSeqString(); if(nextSeqString.empty()) { return; } cout << "Compute: " << nextSeqString << endl; size_t sizeArray = 0; float *arrayReceived = reconstructArray(nextSeqString, sizeArray); // Extractions on the features vector<FeaturesElement> listCurrentSequenceFeatures; Features::getInstance().extractArray(arrayReceived, sizeArray, listCurrentSequenceFeatures); delete arrayReceived; // Match with the dataset bool newPers = true; // Not recognize yet for(PersonElement currentPers : database) { float meanPrediction = 0.0; for(FeaturesElement featuresDatabase : currentPers.features) { for(FeaturesElement featuresSequence : listCurrentSequenceFeatures) { meanPrediction += Features::getInstance().computeDistance(featuresDatabase, featuresSequence); } } meanPrediction /= (currentPers.features.size() * listCurrentSequenceFeatures.size()); // Match. Update database ? if(meanPrediction > thresholdValueSamePerson) { cout << "Match (" << meanPrediction << ") : " << currentPers.name << endl; newPers = false; } } // No match if(newPers) { cout << "No match: Add the new person to the dataset" << endl; // Add the new person to the database database.push_back(PersonElement()); database.back().features.swap(listCurrentSequenceFeatures); database.back().name = std::to_string(database.size()); } } string ReidManager::getNextSeqString() const { string nextSeqString; // Read all lines ifstream receivedFileIn("../../Data/Received/received.txt", ios::in); if(!receivedFileIn.is_open()) { cout << "Unable to open the file (please, check your working directory)" << endl; } else { string line; list<std::string> filelines; while (receivedFileIn) { getline(receivedFileIn, line); if(!line.empty()) { filelines.push_back(line); } } receivedFileIn.close(); // Extract the current element if(!filelines.empty()) { nextSeqString = filelines.front(); filelines.pop_front(); } // Save the file ofstream receivedFileOut("../../Data/Received/received.txt", ios::out | ios::trunc); if(!receivedFileOut.is_open()) { cout << "Unable to open the file (please, check your working directory)" << endl; } for(string currentLine : filelines) { receivedFileOut << currentLine << endl; } receivedFileOut.close(); } return nextSeqString; } float *ReidManager::reconstructArray(const string &seqId, size_t &sizeOut) const { // Extraction of the received array ifstream seqFile("../../Data/Received/seq" + seqId + ".txt", ios_base::in); if(!seqFile.is_open()) { cout << "Unable to open the sequence file (please, check your working directory)" << endl; return nullptr; } size_t arrayReceivedSize = 0; float *arrayReceived = nullptr; seqFile >> arrayReceivedSize; arrayReceived = new float[arrayReceivedSize]; for(size_t i = 0 ; i < arrayReceivedSize ; ++i) { seqFile >> arrayReceived[i]; } sizeOut = arrayReceivedSize; return arrayReceived; } <commit_msg>Get the id (hash code) associated with the person of the received sequence<commit_after>#include "reidmanager.h" #include <iostream> #include <fstream> #include <list> using namespace std; static const float thresholdValueSamePerson = 0.5; ReidManager::ReidManager() { Features::getInstance(); } void ReidManager::computeNext() { // Get the next received sequence string nextSeqString = getNextSeqString(); if(nextSeqString.empty()) { return; } cout << "Compute: " << nextSeqString << endl; size_t sizeArray = 0; float *arrayReceived = reconstructArray(nextSeqString, sizeArray); // Extractions on the features float hashSeqId = arrayReceived[0]; // Get the id of the sequence vector<FeaturesElement> listCurrentSequenceFeatures; size_t offset = 1; Features::getInstance().extractArray(&arrayReceived[offset], sizeArray-offset, listCurrentSequenceFeatures); delete arrayReceived; // Match with the dataset bool newPers = true; // Not recognize yet for(PersonElement currentPers : database) { float meanPrediction = 0.0; for(FeaturesElement featuresDatabase : currentPers.features) { for(FeaturesElement featuresSequence : listCurrentSequenceFeatures) { meanPrediction += Features::getInstance().computeDistance(featuresDatabase, featuresSequence); } } meanPrediction /= (currentPers.features.size() * listCurrentSequenceFeatures.size()); // Match. Update database ? if(meanPrediction > thresholdValueSamePerson) { cout << "Match (" << meanPrediction << ") : " << currentPers.name << endl; newPers = false; } } // No match if(newPers) { cout << "No match: Add the new person to the dataset" << endl; // Add the new person to the database database.push_back(PersonElement()); database.back().features.swap(listCurrentSequenceFeatures); database.back().name = std::to_string(database.size()); } } string ReidManager::getNextSeqString() const { string nextSeqString; // Read all lines ifstream receivedFileIn("../../Data/Received/received.txt", ios::in); if(!receivedFileIn.is_open()) { cout << "Unable to open the file (please, check your working directory)" << endl; } else { string line; list<std::string> filelines; while (receivedFileIn) { getline(receivedFileIn, line); if(!line.empty()) { filelines.push_back(line); } } receivedFileIn.close(); // Extract the current element if(!filelines.empty()) { nextSeqString = filelines.front(); filelines.pop_front(); } // Save the file ofstream receivedFileOut("../../Data/Received/received.txt", ios::out | ios::trunc); if(!receivedFileOut.is_open()) { cout << "Unable to open the file (please, check your working directory)" << endl; } for(string currentLine : filelines) { receivedFileOut << currentLine << endl; } receivedFileOut.close(); } return nextSeqString; } float *ReidManager::reconstructArray(const string &seqId, size_t &sizeOut) const { // Extraction of the received array ifstream seqFile("../../Data/Received/seq" + seqId + ".txt", ios_base::in); if(!seqFile.is_open()) { cout << "Unable to open the sequence file (please, check your working directory)" << endl; return nullptr; } size_t arrayReceivedSize = 0; float *arrayReceived = nullptr; seqFile >> arrayReceivedSize; arrayReceived = new float[arrayReceivedSize]; for(size_t i = 0 ; i < arrayReceivedSize ; ++i) { seqFile >> arrayReceived[i]; } sizeOut = arrayReceivedSize; return arrayReceived; } <|endoftext|>
<commit_before>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkDescriptor.h" #include "SkFontDescriptor.h" #include "SkGlyph.h" #include "SkMask.h" // #include "SkOTUtils.h" #include "SkScalerContext.h" #include "SkTestScalerContext.h" #include "SkTypefaceCache.h" SkTestFont::SkTestFont(const SkTestFontData& fontData) : INHERITED() , fCharCodes(fontData.fCharCodes) , fCharCodesCount(fontData.fCharCodesCount) , fWidths(fontData.fWidths) , fMetrics(fontData.fMetrics) , fName(fontData.fName) , fPaths(NULL) { init(fontData.fPoints, fontData.fVerbs); #ifdef SK_DEBUG sk_bzero(fDebugBits, sizeof(fDebugBits)); sk_bzero(fDebugOverage, sizeof(fDebugOverage)); #endif } SkTestFont::~SkTestFont() { for (unsigned index = 0; index < fCharCodesCount; ++index) { SkDELETE(fPaths[index]); } SkDELETE_ARRAY(fPaths); } #ifdef SK_DEBUG #include "SkThread.h" SK_DECLARE_STATIC_MUTEX(gUsedCharsMutex); #endif int SkTestFont::codeToIndex(SkUnichar charCode) const { #ifdef SK_DEBUG // detect missing test font data { SkAutoMutexAcquire ac(gUsedCharsMutex); if (charCode >= ' ' && charCode <= '~') { int bitOffset = charCode - ' '; fDebugBits[bitOffset >> 3] |= 1 << (bitOffset & 7); } else { int index = 0; while (fDebugOverage[index] != 0 && fDebugOverage[index] != charCode && index < (int) sizeof(fDebugOverage)) { ++index; } SkASSERT(index < (int) sizeof(fDebugOverage)); if (fDebugOverage[index] == 0) { fDebugOverage[index] = charCode; } } } #endif for (unsigned index = 0; index < fCharCodesCount; ++index) { if (fCharCodes[index] == (unsigned) charCode) { return (int) index; } } SkDEBUGF(("missing '%c' (%d) from %s %d\n", (char) charCode, charCode, fDebugName, fDebugStyle)); return 0; } void SkTestFont::init(const SkScalar* pts, const unsigned char* verbs) { fPaths = SkNEW_ARRAY(SkPath*, fCharCodesCount); for (unsigned index = 0; index < fCharCodesCount; ++index) { SkPath* path = SkNEW(SkPath); SkPath::Verb verb; while ((verb = (SkPath::Verb) *verbs++) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: path->moveTo(pts[0], pts[1]); pts += 2; break; case SkPath::kLine_Verb: path->lineTo(pts[0], pts[1]); pts += 2; break; case SkPath::kQuad_Verb: path->quadTo(pts[0], pts[1], pts[2], pts[3]); pts += 4; break; case SkPath::kCubic_Verb: path->cubicTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); pts += 6; break; case SkPath::kClose_Verb: path->close(); break; default: SkDEBUGFAIL("bad verb"); return; } } fPaths[index] = path; } } SkTestTypeface::SkTestTypeface(SkTestFont* testFont, const SkFontStyle& style) : SkTypeface(style, SkTypefaceCache::NewFontID(), false) , fTestFont(testFont) { } void SkTestTypeface::getAdvance(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getFontMetrics(SkPaint::FontMetrics* metrics) { *metrics = fTestFont->fMetrics; } void SkTestTypeface::getMetrics(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getPath(const SkGlyph& glyph, SkPath* path) { *path = *fTestFont->fPaths[glyph.getGlyphID()]; } void SkTestTypeface::onFilterRec(SkScalerContextRec* rec) const { rec->setHinting(SkPaint::kNo_Hinting); } SkAdvancedTypefaceMetrics* SkTestTypeface::onGetAdvancedTypefaceMetrics( PerGlyphInfo , const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { // pdf only SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; info->fFontName.set(fTestFont->fName); info->fType = SkAdvancedTypefaceMetrics::kOther_Font; info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag; info->fLastGlyphID = static_cast<uint16_t>(fTestFont->fCharCodesCount - 1); info->fEmSize = 0; info->fLastGlyphID = SkToU16(onCountGlyphs() - 1); info->fStyle = 0; info->fItalicAngle = 0; info->fAscent = 0; info->fDescent = 0; info->fStemV = 0; info->fCapHeight = 0; info->fBBox = SkIRect::MakeEmpty(); return info; } void SkTestTypeface::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const { desc->setFamilyName(fTestFont->fName); *isLocal = false; } int SkTestTypeface::onCharsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[], int glyphCount) const { SkASSERT(encoding == kUTF16_Encoding); for (int index = 0; index < glyphCount; ++index) { SkUnichar ch = ((SkUnichar*) chars)[index]; glyphs[index] = fTestFont->codeToIndex(ch); } return glyphCount; } void SkTestTypeface::onGetFamilyName(SkString* familyName) const { *familyName = fTestFont->fName; } SkTypeface::LocalizedStrings* SkTestTypeface::onCreateFamilyNameIterator() const { SkString familyName(fTestFont->fName); SkString language("und"); //undetermined SkASSERT(0); // incomplete return NULL; // return new SkOTUtils::LocalizedStrings_SingleName(familyName, language); } class SkTestScalerContext : public SkScalerContext { public: SkTestScalerContext(SkTestTypeface* face, const SkDescriptor* desc) : SkScalerContext(face, desc) , fFace(face) { fRec.getSingleMatrix(&fMatrix); this->forceGenerateImageFromPath(); } virtual ~SkTestScalerContext() { } protected: unsigned generateGlyphCount() override { return fFace->onCountGlyphs(); } uint16_t generateCharToGlyph(SkUnichar uni) override { uint16_t glyph; (void) fFace->onCharsToGlyphs((const void *) &uni, SkTypeface::kUTF16_Encoding, &glyph, 1); return glyph; } void generateAdvance(SkGlyph* glyph) override { fFace->getAdvance(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); } void generateMetrics(SkGlyph* glyph) override { fFace->getMetrics(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); SkPath path; fFace->getPath(*glyph, &path); path.transform(fMatrix); SkRect storage; const SkPaint paint; const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style); SkIRect ibounds; newBounds.roundOut(&ibounds); glyph->fLeft = ibounds.fLeft; glyph->fTop = ibounds.fTop; glyph->fWidth = ibounds.width(); glyph->fHeight = ibounds.height(); } void generateImage(const SkGlyph& glyph) override { SkPath path; fFace->getPath(glyph, &path); SkBitmap bm; bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight), glyph.fImage, glyph.rowBytes()); bm.eraseColor(0); SkCanvas canvas(bm); canvas.translate(-SkIntToScalar(glyph.fLeft), -SkIntToScalar(glyph.fTop)); canvas.concat(fMatrix); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } void generatePath(const SkGlyph& glyph, SkPath* path) override { fFace->getPath(glyph, path); path->transform(fMatrix); } void generateFontMetrics(SkPaint::FontMetrics* metrics) override { fFace->getFontMetrics(metrics); if (metrics) { SkScalar scale = fMatrix.getScaleY(); metrics->fTop = SkScalarMul(metrics->fTop, scale); metrics->fAscent = SkScalarMul(metrics->fAscent, scale); metrics->fDescent = SkScalarMul(metrics->fDescent, scale); metrics->fBottom = SkScalarMul(metrics->fBottom, scale); metrics->fLeading = SkScalarMul(metrics->fLeading, scale); metrics->fAvgCharWidth = SkScalarMul(metrics->fAvgCharWidth, scale); metrics->fXMin = SkScalarMul(metrics->fXMin, scale); metrics->fXMax = SkScalarMul(metrics->fXMax, scale); metrics->fXHeight = SkScalarMul(metrics->fXHeight, scale); } } private: SkTestTypeface* fFace; SkMatrix fMatrix; }; SkScalerContext* SkTestTypeface::onCreateScalerContext(const SkDescriptor* desc) const { return SkNEW_ARGS(SkTestScalerContext, (const_cast<SkTestTypeface*>(this), desc)); } <commit_msg>remove duplicate assign of fLastGlyphID<commit_after>/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "SkAdvancedTypefaceMetrics.h" #include "SkBitmap.h" #include "SkCanvas.h" #include "SkDescriptor.h" #include "SkFontDescriptor.h" #include "SkGlyph.h" #include "SkMask.h" // #include "SkOTUtils.h" #include "SkScalerContext.h" #include "SkTestScalerContext.h" #include "SkTypefaceCache.h" SkTestFont::SkTestFont(const SkTestFontData& fontData) : INHERITED() , fCharCodes(fontData.fCharCodes) , fCharCodesCount(fontData.fCharCodesCount) , fWidths(fontData.fWidths) , fMetrics(fontData.fMetrics) , fName(fontData.fName) , fPaths(NULL) { init(fontData.fPoints, fontData.fVerbs); #ifdef SK_DEBUG sk_bzero(fDebugBits, sizeof(fDebugBits)); sk_bzero(fDebugOverage, sizeof(fDebugOverage)); #endif } SkTestFont::~SkTestFont() { for (unsigned index = 0; index < fCharCodesCount; ++index) { SkDELETE(fPaths[index]); } SkDELETE_ARRAY(fPaths); } #ifdef SK_DEBUG #include "SkThread.h" SK_DECLARE_STATIC_MUTEX(gUsedCharsMutex); #endif int SkTestFont::codeToIndex(SkUnichar charCode) const { #ifdef SK_DEBUG // detect missing test font data { SkAutoMutexAcquire ac(gUsedCharsMutex); if (charCode >= ' ' && charCode <= '~') { int bitOffset = charCode - ' '; fDebugBits[bitOffset >> 3] |= 1 << (bitOffset & 7); } else { int index = 0; while (fDebugOverage[index] != 0 && fDebugOverage[index] != charCode && index < (int) sizeof(fDebugOverage)) { ++index; } SkASSERT(index < (int) sizeof(fDebugOverage)); if (fDebugOverage[index] == 0) { fDebugOverage[index] = charCode; } } } #endif for (unsigned index = 0; index < fCharCodesCount; ++index) { if (fCharCodes[index] == (unsigned) charCode) { return (int) index; } } SkDEBUGF(("missing '%c' (%d) from %s %d\n", (char) charCode, charCode, fDebugName, fDebugStyle)); return 0; } void SkTestFont::init(const SkScalar* pts, const unsigned char* verbs) { fPaths = SkNEW_ARRAY(SkPath*, fCharCodesCount); for (unsigned index = 0; index < fCharCodesCount; ++index) { SkPath* path = SkNEW(SkPath); SkPath::Verb verb; while ((verb = (SkPath::Verb) *verbs++) != SkPath::kDone_Verb) { switch (verb) { case SkPath::kMove_Verb: path->moveTo(pts[0], pts[1]); pts += 2; break; case SkPath::kLine_Verb: path->lineTo(pts[0], pts[1]); pts += 2; break; case SkPath::kQuad_Verb: path->quadTo(pts[0], pts[1], pts[2], pts[3]); pts += 4; break; case SkPath::kCubic_Verb: path->cubicTo(pts[0], pts[1], pts[2], pts[3], pts[4], pts[5]); pts += 6; break; case SkPath::kClose_Verb: path->close(); break; default: SkDEBUGFAIL("bad verb"); return; } } fPaths[index] = path; } } SkTestTypeface::SkTestTypeface(SkTestFont* testFont, const SkFontStyle& style) : SkTypeface(style, SkTypefaceCache::NewFontID(), false) , fTestFont(testFont) { } void SkTestTypeface::getAdvance(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getFontMetrics(SkPaint::FontMetrics* metrics) { *metrics = fTestFont->fMetrics; } void SkTestTypeface::getMetrics(SkGlyph* glyph) { glyph->fAdvanceX = fTestFont->fWidths[glyph->getGlyphID()]; glyph->fAdvanceY = 0; } void SkTestTypeface::getPath(const SkGlyph& glyph, SkPath* path) { *path = *fTestFont->fPaths[glyph.getGlyphID()]; } void SkTestTypeface::onFilterRec(SkScalerContextRec* rec) const { rec->setHinting(SkPaint::kNo_Hinting); } SkAdvancedTypefaceMetrics* SkTestTypeface::onGetAdvancedTypefaceMetrics( PerGlyphInfo , const uint32_t* glyphIDs, uint32_t glyphIDsCount) const { // pdf only SkAdvancedTypefaceMetrics* info = new SkAdvancedTypefaceMetrics; info->fFontName.set(fTestFont->fName); info->fType = SkAdvancedTypefaceMetrics::kOther_Font; info->fFlags = SkAdvancedTypefaceMetrics::kEmpty_FontFlag; info->fLastGlyphID = SkToU16(onCountGlyphs() - 1); info->fEmSize = 0; info->fStyle = 0; info->fItalicAngle = 0; info->fAscent = 0; info->fDescent = 0; info->fStemV = 0; info->fCapHeight = 0; info->fBBox = SkIRect::MakeEmpty(); return info; } void SkTestTypeface::onGetFontDescriptor(SkFontDescriptor* desc, bool* isLocal) const { desc->setFamilyName(fTestFont->fName); *isLocal = false; } int SkTestTypeface::onCharsToGlyphs(const void* chars, Encoding encoding, uint16_t glyphs[], int glyphCount) const { SkASSERT(encoding == kUTF16_Encoding); for (int index = 0; index < glyphCount; ++index) { SkUnichar ch = ((SkUnichar*) chars)[index]; glyphs[index] = fTestFont->codeToIndex(ch); } return glyphCount; } void SkTestTypeface::onGetFamilyName(SkString* familyName) const { *familyName = fTestFont->fName; } SkTypeface::LocalizedStrings* SkTestTypeface::onCreateFamilyNameIterator() const { SkString familyName(fTestFont->fName); SkString language("und"); //undetermined SkASSERT(0); // incomplete return NULL; // return new SkOTUtils::LocalizedStrings_SingleName(familyName, language); } class SkTestScalerContext : public SkScalerContext { public: SkTestScalerContext(SkTestTypeface* face, const SkDescriptor* desc) : SkScalerContext(face, desc) , fFace(face) { fRec.getSingleMatrix(&fMatrix); this->forceGenerateImageFromPath(); } virtual ~SkTestScalerContext() { } protected: unsigned generateGlyphCount() override { return fFace->onCountGlyphs(); } uint16_t generateCharToGlyph(SkUnichar uni) override { uint16_t glyph; (void) fFace->onCharsToGlyphs((const void *) &uni, SkTypeface::kUTF16_Encoding, &glyph, 1); return glyph; } void generateAdvance(SkGlyph* glyph) override { fFace->getAdvance(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); } void generateMetrics(SkGlyph* glyph) override { fFace->getMetrics(glyph); const SkVector advance = fMatrix.mapXY(SkFixedToScalar(glyph->fAdvanceX), SkFixedToScalar(glyph->fAdvanceY)); glyph->fAdvanceX = SkScalarToFixed(advance.fX); glyph->fAdvanceY = SkScalarToFixed(advance.fY); SkPath path; fFace->getPath(*glyph, &path); path.transform(fMatrix); SkRect storage; const SkPaint paint; const SkRect& newBounds = paint.doComputeFastBounds(path.getBounds(), &storage, SkPaint::kFill_Style); SkIRect ibounds; newBounds.roundOut(&ibounds); glyph->fLeft = ibounds.fLeft; glyph->fTop = ibounds.fTop; glyph->fWidth = ibounds.width(); glyph->fHeight = ibounds.height(); } void generateImage(const SkGlyph& glyph) override { SkPath path; fFace->getPath(glyph, &path); SkBitmap bm; bm.installPixels(SkImageInfo::MakeN32Premul(glyph.fWidth, glyph.fHeight), glyph.fImage, glyph.rowBytes()); bm.eraseColor(0); SkCanvas canvas(bm); canvas.translate(-SkIntToScalar(glyph.fLeft), -SkIntToScalar(glyph.fTop)); canvas.concat(fMatrix); SkPaint paint; paint.setAntiAlias(true); canvas.drawPath(path, paint); } void generatePath(const SkGlyph& glyph, SkPath* path) override { fFace->getPath(glyph, path); path->transform(fMatrix); } void generateFontMetrics(SkPaint::FontMetrics* metrics) override { fFace->getFontMetrics(metrics); if (metrics) { SkScalar scale = fMatrix.getScaleY(); metrics->fTop = SkScalarMul(metrics->fTop, scale); metrics->fAscent = SkScalarMul(metrics->fAscent, scale); metrics->fDescent = SkScalarMul(metrics->fDescent, scale); metrics->fBottom = SkScalarMul(metrics->fBottom, scale); metrics->fLeading = SkScalarMul(metrics->fLeading, scale); metrics->fAvgCharWidth = SkScalarMul(metrics->fAvgCharWidth, scale); metrics->fXMin = SkScalarMul(metrics->fXMin, scale); metrics->fXMax = SkScalarMul(metrics->fXMax, scale); metrics->fXHeight = SkScalarMul(metrics->fXHeight, scale); } } private: SkTestTypeface* fFace; SkMatrix fMatrix; }; SkScalerContext* SkTestTypeface::onCreateScalerContext(const SkDescriptor* desc) const { return SkNEW_ARGS(SkTestScalerContext, (const_cast<SkTestTypeface*>(this), desc)); } <|endoftext|>
<commit_before>#include "motion.h" #include "util.h" #include "godot_vim.h" Motion::Pos Motion::_move_forward(Motion::matchFunction function, bool accept_empty) { int next_cc = vim->_cursor_get_column() + 1; int next_cl = vim->_cursor_get_line(); String line_text = vim->_get_line(next_cl); for (int i = next_cl; i < vim->_get_line_count(); i++) { line_text = vim->_get_line(i); if (line_text.length() == 0 || next_cc >= line_text.length()) { if (line_text.length() == 0 && accept_empty && i > vim->_cursor_get_line()) return Pos(i, 0); next_cc = 0; continue; } for (int j = next_cc; j < line_text.length(); j++) { if ((function)(j, line_text)) { print_line("setting cursor to " + itos(j) + ", " + itos(i)); return Pos(i, j); } } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_backward(Motion::matchFunction function, bool accept_empty) { int next_cc = vim->_cursor_get_column() - 1; int next_cl = vim->_cursor_get_line(); String line_text = vim->_get_line(next_cl); bool needs_cc = false; for (int i = next_cl; i >= 0; i--) { line_text = vim->_get_line(i); if (needs_cc) next_cc = line_text.length() - 1; if (line_text.length() == 0) { if (accept_empty && i < vim->_cursor_get_line()) return Pos(i, 0); needs_cc = true; continue; } for (int j = next_cc; j >= 0; j--) { if ((function)(j, line_text)) { print_line("setting cursor to " + itos(j) + ", " + itos(i)); vim->_cursor_set_line(i); vim->_cursor_set_column(j); return Pos(i, j); } } needs_cc = true; } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_to_first_non_blank(int line) { String line_text = vim->_get_line(line); if (vim->_cursor_get_line() != line) vim->_cursor_set_line(line); for (int i = 0; i < line_text.length(); i++) { CharType c = line_text[i]; if (!_is_space(c)) { vim->_cursor_set_column(i); return Pos(line, i); } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_by_columns(int cols) { int col = CLAMP(vim->_cursor_get_column() + cols, 0, vim->_get_current_line_length() - 1); return Pos(vim->_cursor_get_line(), col); } Motion::Pos Motion::_move_by_lines(int lines) { int line = CLAMP(vim->_cursor_get_line() + lines, 0, vim->_get_line_count() - 1); return Pos(line, vim->_cursor_get_column()); } Motion::Pos Motion::_move_left() { return _move_by_columns(-1); } Motion::Pos Motion::_move_right() { return _move_by_columns(1); } Motion::Pos Motion::_move_down() { return _move_by_lines(1); } Motion::Pos Motion::_move_up() { return _move_by_lines(-1); } Motion::Pos Motion::_move_to_line_start() { return Pos(vim->_cursor_get_line(), 0); } Motion::Pos Motion::_move_to_line_end() { return Pos(vim->_cursor_get_line(), vim->_get_current_line_length() - 1); } Motion::Pos Motion::_move_word_right() { return _move_forward(&_is_beginning_of_word, true); } Motion::Pos Motion::_move_word_right_big() { return _move_forward(&_is_beginning_of_big_word, true); } Motion::Pos Motion::_move_word_end() { return _move_forward(&_is_end_of_word); } Motion::Pos Motion::_move_word_end_big() { return _move_forward(&_is_end_of_big_word); } Motion::Pos Motion::_move_word_end_backward() { return _move_backward(&_is_end_of_word); } Motion::Pos Motion::_move_word_end_big_backward() { return _move_backward(&_is_end_of_big_word); } Motion::Pos Motion::_move_word_beginning() { return _move_backward(&_is_beginning_of_word, true); } Motion::Pos Motion::_move_word_beginning_big() { return _move_backward(&_is_beginning_of_big_word, true); } Motion::Pos Motion::_move_paragraph_up() { int next_cl = vim->_cursor_get_line(); bool has_text = false; for (int i = next_cl; i >= 0; i--) { String line_text = vim->_get_line(i); if (line_text.size() == 0) { if (has_text) { return Pos(i, 0); } } else { has_text = true; } } return Pos(0, 0); } Motion::Pos Motion::_move_paragraph_down() { int next_cl = vim->_cursor_get_line(); bool has_text = false; for (int i = next_cl; i < vim->_get_line_count(); i++) { String line_text = vim->_get_line(i); if (line_text.size() == 0) { if (has_text) { return Pos(i, 0); } } else { has_text = true; } } int last_line = vim->_get_line_count() - 1; return Pos(last_line, vim->_get_line(last_line).length() - 1); } Motion::Pos Motion::_move_to_matching_pair() { String line_text = vim->_get_line(vim->_cursor_get_line()); int col = vim->_cursor_get_column(); CharType c = line_text[col]; if (_is_pair_left_symbol(c)) { CharType m = _get_right_pair_symbol(c); col++; int count = 1; for (int i = vim->_cursor_get_line(); i < vim->_get_line_count(); i++) { line_text = vim->_get_line(i); for (int j = col; j < line_text.length(); j++) { CharType cur = line_text[j]; if (cur == c) { count++; } else if (cur == m) { count--; if (count == 0) { return Pos(i, j); } } } col = 0; } } else if (_is_pair_right_symbol(c)) { CharType m = _get_left_pair_symbol(c); col--; int count = 1; bool needs_col = false; for (int i = vim->_cursor_get_line(); i >= 0; i--) { line_text = vim->_get_line(i); if (needs_col) col = line_text.length(); for (int j = col; j >= 0; j--) { CharType cur = line_text[j]; if (cur == c) { count++; } else if (cur == m) { count--; if (count == 0) { return Pos(i, j); } } } needs_col = true; } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_to_first_non_blank() { return _move_to_first_non_blank(vim->_cursor_get_line()); } Motion::Pos Motion::_move_to_beginning_of_last_line() { return _move_to_first_non_blank(vim->_get_line_count() - 1); } Motion::Pos Motion::_move_to_beginning_of_first_line() { return _move_to_first_non_blank(0); } Motion::Pos Motion::_move_to_beginning_of_previous_line() { if (vim->_cursor_get_line() > 0) { return _move_to_first_non_blank(vim->_cursor_get_line() - 1); } return _move_to_first_non_blank(); } Motion::Pos Motion::_move_to_beginning_of_next_line() { if (vim->_cursor_get_line() < vim->_get_line_count() - 1) { _move_to_first_non_blank(vim->_cursor_get_line() + 1); } return _move_to_first_non_blank(); } Motion::Pos Motion::_move_to_last_searched_char() { } Motion::Pos Motion::_move_to_last_searched_char_backward() { } Motion::Pos Motion::_move_to_column() { String line_text = vim->_get_current_line(); if (vim->get_input_state().repeat_count - 1 < line_text.length()) { vim->_cursor_set_column(vim->get_input_state().repeat_count - 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::search_word_under_cursor() { String word = vim->get_text_edit()->get_word_under_cursor(); int r_l = vim->_cursor_get_line(); int r_c = vim->_cursor_get_column(); if (vim->get_text_edit()->search(word, 0, vim->_cursor_get_line(), vim->_cursor_get_column(), r_l, r_c)) { print_line("word found"); return Pos(r_l, r_c); } return Pos(r_l, r_c); } Motion::Pos Motion::search_word_under_cursor_backward() { } Motion::Pos Motion::find_next() { } Motion::Pos Motion::find_previous() { } Motion::Pos Motion::find_char() { int n = find_in_line(vim->_get_current_line(), vim->get_input_state().input_char, vim->_cursor_get_column() + 1); if (n >= 0) { return Pos(vim->_cursor_get_line(), n); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_char_backward() { int n = find_in_line(vim->_get_current_line().substr(0, vim->_cursor_get_column()), vim->get_input_state().input_char); if (n >= 0) { return Pos(vim->_cursor_get_line(), n); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_till_char() { int n = find_in_line(vim->_get_current_line(), vim->get_input_state().input_char, vim->_cursor_get_column()); if (n >= 0) { return Pos(vim->_cursor_get_line(), n - 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_till_char_backward() { int n = find_in_line(vim->_get_current_line().substr(0, vim->_cursor_get_column()), vim->get_input_state().input_char); if (n >= 0) { return Pos(vim->_cursor_get_line(), n + 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } bool Motion::is_inclusive() { return flags & INCLUSIVE; } bool Motion::is_linewise() { return flags & LINEWISE; } bool Motion::is_text_object() { return flags & TEXT_OBJECT; } Motion::Pos Motion::apply() { return (this->*fcn)(); } Motion::Range Motion::get_range() { Pos cur_pos = Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); Pos pos = apply(); Range range = pos < cur_pos ? Range(pos, cur_pos) : Range(cur_pos, pos); range.inclusive = is_inclusive(); range.linewise = is_linewise(); range.text_object = is_text_object(); return range; } void Motion::run() { Pos pos = apply(); vim->_cursor_set_line(pos.row); vim->_cursor_set_column(pos.col); } Motion::Motion(GodotVim *vim, int flags, motionFcn fcn, int cmd_flags) : Command(vim, cmd_flags), flags(flags), fcn(fcn) { } Motion * Motion::create_motion(GodotVim *vim, int flags, Motion::motionFcn fcn, int cmd_flags) { Motion *motion = memnew(Motion(vim, flags, fcn, cmd_flags)); return motion; } <commit_msg>Implement repeat count for motions<commit_after>#include "motion.h" #include "util.h" #include "godot_vim.h" Motion::Pos Motion::_move_forward(Motion::matchFunction function, bool accept_empty) { int next_cc = vim->_cursor_get_column() + 1; int next_cl = vim->_cursor_get_line(); String line_text = vim->_get_line(next_cl); for (int i = next_cl; i < vim->_get_line_count(); i++) { line_text = vim->_get_line(i); if (line_text.length() == 0 || next_cc >= line_text.length()) { if (line_text.length() == 0 && accept_empty && i > vim->_cursor_get_line()) return Pos(i, 0); next_cc = 0; continue; } for (int j = next_cc; j < line_text.length(); j++) { if ((function)(j, line_text)) { print_line("setting cursor to " + itos(j) + ", " + itos(i)); return Pos(i, j); } } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_backward(Motion::matchFunction function, bool accept_empty) { int next_cc = vim->_cursor_get_column() - 1; int next_cl = vim->_cursor_get_line(); String line_text = vim->_get_line(next_cl); bool needs_cc = false; for (int i = next_cl; i >= 0; i--) { line_text = vim->_get_line(i); if (needs_cc) next_cc = line_text.length() - 1; if (line_text.length() == 0) { if (accept_empty && i < vim->_cursor_get_line()) return Pos(i, 0); needs_cc = true; continue; } for (int j = next_cc; j >= 0; j--) { if ((function)(j, line_text)) { print_line("setting cursor to " + itos(j) + ", " + itos(i)); vim->_cursor_set_line(i); vim->_cursor_set_column(j); return Pos(i, j); } } needs_cc = true; } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_to_first_non_blank(int line) { String line_text = vim->_get_line(line); if (vim->_cursor_get_line() != line) vim->_cursor_set_line(line); for (int i = 0; i < line_text.length(); i++) { CharType c = line_text[i]; if (!_is_space(c)) { vim->_cursor_set_column(i); return Pos(line, i); } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_by_columns(int cols) { int col = CLAMP(vim->_cursor_get_column() + cols, 0, vim->_get_current_line_length() - 1); return Pos(vim->_cursor_get_line(), col); } Motion::Pos Motion::_move_by_lines(int lines) { int line = CLAMP(vim->_cursor_get_line() + lines, 0, vim->_get_line_count() - 1); return Pos(line, vim->_cursor_get_column()); } Motion::Pos Motion::_move_left() { return _move_by_columns(-1); } Motion::Pos Motion::_move_right() { return _move_by_columns(1); } Motion::Pos Motion::_move_down() { return _move_by_lines(1); } Motion::Pos Motion::_move_up() { return _move_by_lines(-1); } Motion::Pos Motion::_move_to_line_start() { return Pos(vim->_cursor_get_line(), 0); } Motion::Pos Motion::_move_to_line_end() { return Pos(vim->_cursor_get_line(), vim->_get_current_line_length() - 1); } Motion::Pos Motion::_move_word_right() { return _move_forward(&_is_beginning_of_word, true); } Motion::Pos Motion::_move_word_right_big() { return _move_forward(&_is_beginning_of_big_word, true); } Motion::Pos Motion::_move_word_end() { return _move_forward(&_is_end_of_word); } Motion::Pos Motion::_move_word_end_big() { return _move_forward(&_is_end_of_big_word); } Motion::Pos Motion::_move_word_end_backward() { return _move_backward(&_is_end_of_word); } Motion::Pos Motion::_move_word_end_big_backward() { return _move_backward(&_is_end_of_big_word); } Motion::Pos Motion::_move_word_beginning() { return _move_backward(&_is_beginning_of_word, true); } Motion::Pos Motion::_move_word_beginning_big() { return _move_backward(&_is_beginning_of_big_word, true); } Motion::Pos Motion::_move_paragraph_up() { int next_cl = vim->_cursor_get_line(); bool has_text = false; for (int i = next_cl; i >= 0; i--) { String line_text = vim->_get_line(i); if (line_text.size() == 0) { if (has_text) { return Pos(i, 0); } } else { has_text = true; } } return Pos(0, 0); } Motion::Pos Motion::_move_paragraph_down() { int next_cl = vim->_cursor_get_line(); bool has_text = false; for (int i = next_cl; i < vim->_get_line_count(); i++) { String line_text = vim->_get_line(i); if (line_text.size() == 0) { if (has_text) { return Pos(i, 0); } } else { has_text = true; } } int last_line = vim->_get_line_count() - 1; return Pos(last_line, vim->_get_line(last_line).length() - 1); } Motion::Pos Motion::_move_to_matching_pair() { String line_text = vim->_get_line(vim->_cursor_get_line()); int col = vim->_cursor_get_column(); CharType c = line_text[col]; if (_is_pair_left_symbol(c)) { CharType m = _get_right_pair_symbol(c); col++; int count = 1; for (int i = vim->_cursor_get_line(); i < vim->_get_line_count(); i++) { line_text = vim->_get_line(i); for (int j = col; j < line_text.length(); j++) { CharType cur = line_text[j]; if (cur == c) { count++; } else if (cur == m) { count--; if (count == 0) { return Pos(i, j); } } } col = 0; } } else if (_is_pair_right_symbol(c)) { CharType m = _get_left_pair_symbol(c); col--; int count = 1; bool needs_col = false; for (int i = vim->_cursor_get_line(); i >= 0; i--) { line_text = vim->_get_line(i); if (needs_col) col = line_text.length(); for (int j = col; j >= 0; j--) { CharType cur = line_text[j]; if (cur == c) { count++; } else if (cur == m) { count--; if (count == 0) { return Pos(i, j); } } } needs_col = true; } } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::_move_to_first_non_blank() { return _move_to_first_non_blank(vim->_cursor_get_line()); } Motion::Pos Motion::_move_to_beginning_of_last_line() { return _move_to_first_non_blank(vim->_get_line_count() - 1); } Motion::Pos Motion::_move_to_beginning_of_first_line() { return _move_to_first_non_blank(0); } Motion::Pos Motion::_move_to_beginning_of_previous_line() { if (vim->_cursor_get_line() > 0) { return _move_to_first_non_blank(vim->_cursor_get_line() - 1); } return _move_to_first_non_blank(); } Motion::Pos Motion::_move_to_beginning_of_next_line() { if (vim->_cursor_get_line() < vim->_get_line_count() - 1) { _move_to_first_non_blank(vim->_cursor_get_line() + 1); } return _move_to_first_non_blank(); } Motion::Pos Motion::_move_to_last_searched_char() { } Motion::Pos Motion::_move_to_last_searched_char_backward() { } Motion::Pos Motion::_move_to_column() { String line_text = vim->_get_current_line(); if (vim->get_input_state().repeat_count - 1 < line_text.length()) { vim->_cursor_set_column(vim->get_input_state().repeat_count - 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::search_word_under_cursor() { String word = vim->get_text_edit()->get_word_under_cursor(); int r_l = vim->_cursor_get_line(); int r_c = vim->_cursor_get_column(); if (vim->get_text_edit()->search(word, 0, vim->_cursor_get_line(), vim->_cursor_get_column(), r_l, r_c)) { print_line("word found"); return Pos(r_l, r_c); } return Pos(r_l, r_c); } Motion::Pos Motion::search_word_under_cursor_backward() { } Motion::Pos Motion::find_next() { } Motion::Pos Motion::find_previous() { } Motion::Pos Motion::find_char() { int n = find_in_line(vim->_get_current_line(), vim->get_input_state().input_char, vim->_cursor_get_column() + 1); if (n >= 0) { return Pos(vim->_cursor_get_line(), n); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_char_backward() { int n = find_in_line(vim->_get_current_line().substr(0, vim->_cursor_get_column()), vim->get_input_state().input_char); if (n >= 0) { return Pos(vim->_cursor_get_line(), n); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_till_char() { int n = find_in_line(vim->_get_current_line(), vim->get_input_state().input_char, vim->_cursor_get_column()); if (n >= 0) { return Pos(vim->_cursor_get_line(), n - 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } Motion::Pos Motion::find_till_char_backward() { int n = find_in_line(vim->_get_current_line().substr(0, vim->_cursor_get_column()), vim->get_input_state().input_char); if (n >= 0) { return Pos(vim->_cursor_get_line(), n + 1); } return Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); } bool Motion::is_inclusive() { return flags & INCLUSIVE; } bool Motion::is_linewise() { return flags & LINEWISE; } bool Motion::is_text_object() { return flags & TEXT_OBJECT; } Motion::Pos Motion::apply() { Pos pos = Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); int repeat = vim->get_input_state().repeat_count; if (repeat < 1) repeat = 1; for (int i = 0; i < repeat; i++) { vim->_cursor_set_line(pos.row); vim->_cursor_set_column(pos.col); pos = (this->*fcn)(); } return pos; } Motion::Range Motion::get_range() { Pos cur_pos = Pos(vim->_cursor_get_line(), vim->_cursor_get_column()); Pos pos = apply(); Range range = pos < cur_pos ? Range(pos, cur_pos) : Range(cur_pos, pos); range.inclusive = is_inclusive(); range.linewise = is_linewise(); range.text_object = is_text_object(); return range; } void Motion::run() { Pos pos = apply(); vim->_cursor_set_line(pos.row); vim->_cursor_set_column(pos.col); } Motion::Motion(GodotVim *vim, int flags, motionFcn fcn, int cmd_flags) : Command(vim, cmd_flags), flags(flags), fcn(fcn) { } Motion * Motion::create_motion(GodotVim *vim, int flags, Motion::motionFcn fcn, int cmd_flags) { Motion *motion = memnew(Motion(vim, flags, fcn, cmd_flags)); return motion; } <|endoftext|>
<commit_before>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImageToPointCloudFilter.h" #include <itkImageIterator.h> #include <itkImageRegionIterator.h> #include <mitkDataNode.h> #include <mitkImageAccessByItk.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkImageStatisticsCalculator.h> mitk::ImageToPointCloudFilter::ImageToPointCloudFilter(): m_NumberOfExtractedPoints(0) { m_PointSurface = mitk::Surface::New(); m_Method = DetectConstant(0); m_EdgeImage = mitk::Image::New(); m_EdgePoints = mitk::Image::New(); this->SetNumberOfRequiredInputs(1); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, m_PointSurface); } mitk::ImageToPointCloudFilter::~ImageToPointCloudFilter(){} void mitk::ImageToPointCloudFilter::GenerateData() { mitk::Image::ConstPointer image = ImageToSurfaceFilter::GetInput(); m_Geometry = image->GetGeometry(); if ( image.IsNull() ) { MITK_ERROR << "mitk::ImageToContourFilter: No input available. " "Please set the input!" << std::endl; return; } switch(m_Method) { case 0: this->LaplacianStdDev(image, 2); break; case 1: this->LaplacianStdDev(image, 3); break; default: this->LaplacianStdDev(image, 2); break; } } void mitk::ImageToPointCloudFilter:: LaplacianStdDev(mitk::Image::ConstPointer image, int amount) { mitk::Image::Pointer notConstImage = image->Clone(); AccessByItk_1(notConstImage.GetPointer(), StdDeviations, amount) } template<typename TPixel, unsigned int VImageDimension> void mitk::ImageToPointCloudFilter:: StdDeviations(itk::Image<TPixel, VImageDimension>* image, int amount) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typedef itk::CastImageFilter< InputImageType, FloatImageType > ImagePTypeToFloatPTypeCasterType; typename LaplacianFilterType::Pointer lapFilter = LaplacianFilterType::New(); typename ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New(); caster->SetInput( image ); caster->Update(); FloatImageType::Pointer fImage = caster->GetOutput(); lapFilter->SetInput(fImage); lapFilter->UpdateLargestPossibleRegion(); m_EdgeImage = mitk::ImportItkImage(lapFilter->GetOutput())->Clone(); mitk::ImageStatisticsCalculator::Pointer statCalc = mitk::ImageStatisticsCalculator::New(); statCalc->SetImage(m_EdgeImage); statCalc->ComputeStatistics(); mitk::ImageStatisticsCalculator::Statistics stats = statCalc->GetStatistics(); double mean = stats.GetMean(); double stdDev = stats.GetSigma(); double upperThreshold = mean + stdDev * amount; double lowerThreshold = mean - stdDev * amount; typename itk::ImageRegionIterator<FloatImageType> it(lapFilter->GetOutput(), lapFilter->GetOutput()->GetRequestedRegion()); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); it.GoToBegin(); while( !it.IsAtEnd() ) { if(it.Get() > lowerThreshold && it.Get() < upperThreshold) { it.Set(0); } else { it.Set(1); mitk::Point3D imagePoint; mitk::Point3D worldPoint; imagePoint[0] = it.GetIndex()[0]; imagePoint[1] = it.GetIndex()[1]; imagePoint[2] = it.GetIndex()[2]; m_Geometry->IndexToWorld(imagePoint, worldPoint); points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]); m_NumberOfExtractedPoints++; } ++it; } m_EdgePoints = mitk::ImportItkImage(lapFilter->GetOutput())->Clone(); vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); polyData->SetPoints(points); polyData->BuildCells(); polyData->BuildLinks(); m_PointSurface->SetVtkPolyData(polyData); } void mitk::ImageToPointCloudFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } <commit_msg>added lines between the polydata points for correct visualization<commit_after>/*=================================================================== The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt or http://www.mitk.org for details. ===================================================================*/ #include "mitkImageToPointCloudFilter.h" #include <itkImageIterator.h> #include <itkImageRegionIterator.h> #include <vtkPolyLine.h> #include <mitkDataNode.h> #include <mitkImageAccessByItk.h> #include <mitkImageCast.h> #include <mitkITKImageImport.h> #include <mitkImageStatisticsCalculator.h> #include <vtkCellArray.h> mitk::ImageToPointCloudFilter::ImageToPointCloudFilter(): m_NumberOfExtractedPoints(0) { m_PointSurface = mitk::Surface::New(); m_Method = DetectConstant(0); m_EdgeImage = mitk::Image::New(); m_EdgePoints = mitk::Image::New(); this->SetNumberOfRequiredInputs(1); this->SetNumberOfRequiredOutputs(1); this->SetNthOutput(0, m_PointSurface); } mitk::ImageToPointCloudFilter::~ImageToPointCloudFilter(){} void mitk::ImageToPointCloudFilter::GenerateData() { mitk::Image::ConstPointer image = ImageToSurfaceFilter::GetInput(); m_Geometry = image->GetGeometry(); if ( image.IsNull() ) { MITK_ERROR << "mitk::ImageToContourFilter: No input available. " "Please set the input!" << std::endl; return; } switch(m_Method) { case 0: this->LaplacianStdDev(image, 2); break; case 1: this->LaplacianStdDev(image, 3); break; default: this->LaplacianStdDev(image, 2); break; } } void mitk::ImageToPointCloudFilter:: LaplacianStdDev(mitk::Image::ConstPointer image, int amount) { mitk::Image::Pointer notConstImage = image->Clone(); AccessByItk_1(notConstImage.GetPointer(), StdDeviations, amount) } template<typename TPixel, unsigned int VImageDimension> void mitk::ImageToPointCloudFilter:: StdDeviations(itk::Image<TPixel, VImageDimension>* image, int amount) { typedef itk::Image<TPixel, VImageDimension> InputImageType; typedef itk::CastImageFilter< InputImageType, FloatImageType > ImagePTypeToFloatPTypeCasterType; typename LaplacianFilterType::Pointer lapFilter = LaplacianFilterType::New(); typename ImagePTypeToFloatPTypeCasterType::Pointer caster = ImagePTypeToFloatPTypeCasterType::New(); caster->SetInput( image ); caster->Update(); FloatImageType::Pointer fImage = caster->GetOutput(); lapFilter->SetInput(fImage); lapFilter->UpdateLargestPossibleRegion(); m_EdgeImage = mitk::ImportItkImage(lapFilter->GetOutput())->Clone(); mitk::ImageStatisticsCalculator::Pointer statCalc = mitk::ImageStatisticsCalculator::New(); statCalc->SetImage(m_EdgeImage); statCalc->ComputeStatistics(); mitk::ImageStatisticsCalculator::Statistics stats = statCalc->GetStatistics(); double mean = stats.GetMean(); double stdDev = stats.GetSigma(); double upperThreshold = mean + stdDev * amount; double lowerThreshold = mean - stdDev * amount; typename itk::ImageRegionIterator<FloatImageType> it(lapFilter->GetOutput(), lapFilter->GetOutput()->GetRequestedRegion()); vtkSmartPointer<vtkPoints> points = vtkSmartPointer<vtkPoints>::New(); it.GoToBegin(); while( !it.IsAtEnd() ) { if(it.Get() > lowerThreshold && it.Get() < upperThreshold) { it.Set(0); } else { it.Set(1); mitk::Point3D imagePoint; mitk::Point3D worldPoint; imagePoint[0] = it.GetIndex()[0]; imagePoint[1] = it.GetIndex()[1]; imagePoint[2] = it.GetIndex()[2]; m_Geometry->IndexToWorld(imagePoint, worldPoint); points->InsertNextPoint(worldPoint[0],worldPoint[1],worldPoint[2]); m_NumberOfExtractedPoints++; } ++it; } vtkSmartPointer<vtkPolyLine> polyLine = vtkSmartPointer<vtkPolyLine>::New(); polyLine->GetPointIds()->SetNumberOfIds(m_NumberOfExtractedPoints); for(unsigned int i = 0; i < m_NumberOfExtractedPoints; i++) { polyLine->GetPointIds()->SetId(i,i); } vtkSmartPointer<vtkCellArray> cells = vtkSmartPointer<vtkCellArray>::New(); cells->InsertNextCell(polyLine); vtkSmartPointer<vtkPolyData> polyData = vtkSmartPointer<vtkPolyData>::New(); polyData->SetPoints(points); polyData->SetLines(cells); m_EdgePoints = mitk::ImportItkImage(lapFilter->GetOutput())->Clone(); polyData->BuildCells(); polyData->BuildLinks(); m_PointSurface->SetVtkPolyData(polyData); } void mitk::ImageToPointCloudFilter::GenerateOutputInformation() { Superclass::GenerateOutputInformation(); } <|endoftext|>
<commit_before>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <curl/curl.h> #include "fcgiapp.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/config.h" #include "common/errno.h" #include "common/Thread.h" #include "rgw_common.h" #include "rgw_access.h" #include "rgw_acl.h" #include "rgw_user.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_os.h" #include "rgw_log.h" #include <map> #include <string> #include <vector> #include <iostream> #include <sstream> #include "include/types.h" #include "common/BackTrace.h" using namespace std; static sighandler_t sighandler_usr1; static sighandler_t sighandler_alrm; static void godown_handler(int signum) { FCGX_ShutdownPending(); signal(signum, sighandler_usr1); alarm(5); } static void godown_alarm(int signum) { _exit(0); } class RGWThread : public Thread { FCGX_Request *fcgx; public: RGWThread(FCGX_Request *_f) : fcgx(_f) {} ~RGWThread() { delete fcgx; } void *entry(); }; class RGWProcess { vector<RGWThread *> m_threads; public: RGWProcess() {} void start(int num_threads); void join(); }; void RGWProcess::start(int num_threads) { #if 0 string sock = "/tmp/.radosgw.sock"; int s = FCGX_OpenSocket(sock.c_str(), 100); if (s < 0) { RGW_LOG(0) << "ERROR: FCGX_OpenSocket (" << sock << ") returned " << s << dendl; return; } #endif for (;;) { FCGX_Request *fcgx = new FCGX_Request; // FCGX_InitRequest(fcgx, s, 0); FCGX_InitRequest(fcgx, 0, 0); int ret = FCGX_Accept_r(fcgx); if (ret < 0) return; RGWThread *thread = new RGWThread(fcgx); m_threads.push_back(thread); thread->create(); } } void RGWProcess::join() { vector<RGWThread *>::iterator iter; for (iter = m_threads.begin(); iter != m_threads.end(); ++iter) { RGWThread *thr = *iter; int ret = thr->join(); delete thr; if (ret < 0) { cerr << "WARNING: thread join returned " << ret << std::endl; } } } void *RGWThread::entry() { RGWRESTMgr rest; RGW_LOG(0) << "thread started thread_id=" << hex << (uint64_t)get_thread_id() << dec << dendl; int ret; { rgw_env.reinit(fcgx->envp); struct req_state *s = new req_state; RGWOp *op = NULL; int init_error = 0; RGWHandler *handler = rest.get_handler(s, fcgx, &init_error); if (init_error != 0) { abort_early(s, init_error); goto done; } if (!handler->authorize()) { RGW_LOG(10) << "failed to authorize request" << dendl; abort_early(s, -EPERM); goto done; } if (s->user.suspended) { RGW_LOG(10) << "user is suspended, uid=" << s->user.user_id << dendl; abort_early(s, -ERR_USER_SUSPENDED); goto done; } ret = handler->read_permissions(); if (ret < 0) { abort_early(s, ret); goto done; } op = handler->get_op(); if (op) { ret = op->verify_permission(); if (ret < 0) { abort_early(s, ret); goto done; } if (s->expect_cont) dump_continue(s); op->execute(); } else { abort_early(s, -ERR_METHOD_NOT_ALLOWED); } done: rgw_log_op(s); handler->put_op(op); delete s; FCGX_Finish_r(fcgx); } return NULL; } /* * start up the RADOS connection and then handle HTTP messages as they come in */ int main(int argc, const char **argv) { curl_global_init(CURL_GLOBAL_ALL); // dout() messages will be sent to stderr, but FCGX wants messages on stdout // Redirect stderr to stdout. TEMP_FAILURE_RETRY(close(STDERR_FILENO)); if (TEMP_FAILURE_RETRY(dup2(STDOUT_FILENO, STDERR_FILENO) < 0)) { int err = errno; cout << "failed to redirect stderr to stdout: " << cpp_strerror(err) << std::endl; return ENOSYS; } vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); common_init_finish(g_ceph_context); sighandler_usr1 = signal(SIGUSR1, godown_handler); sighandler_alrm = signal(SIGALRM, godown_alarm); FCGX_Init(); RGWStoreManager store_manager; if (!store_manager.init("rados", g_ceph_context)) { derr << "Couldn't init storage provider (RADOS)" << dendl; return EIO; } RGWProcess process; process.start(20); process.join(); return 0; } <commit_msg>rgw: use thread pool for rgw work<commit_after>#include <stdlib.h> #include <stdio.h> #include <string.h> #include <stdarg.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <errno.h> #include <signal.h> #include <curl/curl.h> #include "fcgiapp.h" #include "common/ceph_argparse.h" #include "global/global_init.h" #include "common/config.h" #include "common/errno.h" #include "common/WorkQueue.h" #include "rgw_common.h" #include "rgw_access.h" #include "rgw_acl.h" #include "rgw_user.h" #include "rgw_op.h" #include "rgw_rest.h" #include "rgw_os.h" #include "rgw_log.h" #include <map> #include <string> #include <vector> #include <iostream> #include <sstream> #include "include/types.h" #include "common/BackTrace.h" using namespace std; static sighandler_t sighandler_usr1; static sighandler_t sighandler_alrm; #define SOCKET_NAME "/tmp/.radosgw.sock" #define SOCKET_BACKLOG 20 static void godown_handler(int signum) { FCGX_ShutdownPending(); signal(signum, sighandler_usr1); alarm(5); } static void godown_alarm(int signum) { _exit(0); } class RGWProcess { deque<FCGX_Request*> m_fcgx_queue; ThreadPool m_tp; struct RGWWQ : public ThreadPool::WorkQueue<FCGX_Request> { RGWProcess *process; RGWWQ(RGWProcess *p, ThreadPool *tp) : ThreadPool::WorkQueue<FCGX_Request>("RGWWQ", tp), process(p) {} bool _enqueue(FCGX_Request *req) { process->m_fcgx_queue.push_back(req); return true; } void _dequeue(FCGX_Request *req) { assert(0); } bool _empty() { return process->m_fcgx_queue.empty(); } FCGX_Request *_dequeue() { if (process->m_fcgx_queue.empty()) return NULL; FCGX_Request *req = process->m_fcgx_queue.front(); process->m_fcgx_queue.pop_front(); return req; } void _process(FCGX_Request *fcgx) { process->handle_request(fcgx); } void _clear() { assert(process->m_fcgx_queue.empty()); } } req_wq; public: RGWProcess(CephContext *cct, int num_threads) : m_tp(cct, "RGWProcess::m_tp", num_threads), req_wq(this, &m_tp) {} void run(); void handle_request(FCGX_Request *fcgx); }; void RGWProcess::run() { const char *sock = SOCKET_NAME; int s = FCGX_OpenSocket(sock, SOCKET_BACKLOG); if (s < 0) { RGW_LOG(0) << "ERROR: FCGX_OpenSocket (" << sock << ") returned " << s << dendl; return; } if (chmod(sock, 0777) < 0) { RGW_LOG(0) << "WARNING: couldn't set permissions on unix domain socket" << dendl; } m_tp.start(); for (;;) { FCGX_Request *fcgx = new FCGX_Request; FCGX_InitRequest(fcgx, s, 0); int ret = FCGX_Accept_r(fcgx); if (ret < 0) return; req_wq.queue(fcgx); } } void RGWProcess::handle_request(FCGX_Request *fcgx) { RGWRESTMgr rest; int ret; rgw_env.reinit(fcgx->envp); struct req_state *s = new req_state; RGWOp *op = NULL; int init_error = 0; RGWHandler *handler = rest.get_handler(s, fcgx, &init_error); if (init_error != 0) { abort_early(s, init_error); goto done; } if (!handler->authorize()) { RGW_LOG(10) << "failed to authorize request" << dendl; abort_early(s, -EPERM); goto done; } if (s->user.suspended) { RGW_LOG(10) << "user is suspended, uid=" << s->user.user_id << dendl; abort_early(s, -ERR_USER_SUSPENDED); goto done; } ret = handler->read_permissions(); if (ret < 0) { abort_early(s, ret); goto done; } op = handler->get_op(); if (op) { ret = op->verify_permission(); if (ret < 0) { abort_early(s, ret); goto done; } if (s->expect_cont) dump_continue(s); op->execute(); } else { abort_early(s, -ERR_METHOD_NOT_ALLOWED); } done: rgw_log_op(s); handler->put_op(op); delete s; FCGX_Finish_r(fcgx); delete fcgx; } /* * start up the RADOS connection and then handle HTTP messages as they come in */ int main(int argc, const char **argv) { curl_global_init(CURL_GLOBAL_ALL); // dout() messages will be sent to stderr, but FCGX wants messages on stdout // Redirect stderr to stdout. TEMP_FAILURE_RETRY(close(STDERR_FILENO)); if (TEMP_FAILURE_RETRY(dup2(STDOUT_FILENO, STDERR_FILENO) < 0)) { int err = errno; cout << "failed to redirect stderr to stdout: " << cpp_strerror(err) << std::endl; return ENOSYS; } vector<const char*> args; argv_to_vec(argc, argv, args); env_to_vec(args); global_init(args, CEPH_ENTITY_TYPE_CLIENT, CODE_ENVIRONMENT_UTILITY, 0); common_init_finish(g_ceph_context); sighandler_usr1 = signal(SIGUSR1, godown_handler); sighandler_alrm = signal(SIGALRM, godown_alarm); FCGX_Init(); RGWStoreManager store_manager; if (!store_manager.init("rados", g_ceph_context)) { derr << "Couldn't init storage provider (RADOS)" << dendl; return EIO; } RGWProcess process(g_ceph_context, 20); process.run(); return 0; } <|endoftext|>
<commit_before>/* * File: histograms.cpp * Author: claas * * Created on 9. Juli 2009, 13:40 */ #include "Histograms.h" // debug #include "Tools/Debug/DebugRequest.h" #include "Tools/Debug/DebugImageDrawings.h" using namespace naoth; using namespace std; Histograms::Histograms() { std::stringstream dbgString; std::stringstream descString; for(int color = 0; color < ColorClasses::numOfColors; color++) { dbgString.str(""); dbgString << "ImageProcessor:Histogram:x:" << ColorClasses::getColorName((ColorClasses::Color) color); descString.str(""); descString << "draw X axis histogram of " << ColorClasses::getColorName((ColorClasses::Color) color) << " pixels"; DEBUG_REQUEST_REGISTER(dbgString.str(), descString.str(), false); dbgString.str(""); dbgString << "ImageProcessor:Histogram:y:" << ColorClasses::getColorName((ColorClasses::Color) color); descString.str(""); descString << "draw Y axis histogram of " << ColorClasses::getColorName((ColorClasses::Color) color) << " pixels"; DEBUG_REQUEST_REGISTER(dbgString.str(), descString.str(), false); } //DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:colorChannelHistogramCr", "draw X axis rate histogram of the V (Cr) color channel from the field", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotY", "plot Y channel histogram bottom image", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotU", "plot U channel histogram bottom image", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotV", "plot V channel histogram bottom image", false); init(); } void Histograms::init() { colorChannelIsUptodate = false; for(int c = 0; c < ColorClasses::numOfColors; c++) { xHistogram[c].clear(); yHistogram[c].clear(); } }//end init void Histograms::execute() { init(); } void Histograms::showDebugInfos(const UniformGrid& grid, const CameraInfo& cameraInfo) const { std::stringstream dbgString; bool drawXHist = false; bool drawYHist = false; bool drawChannelHist = false; DEBUG_REQUEST("ImageProcessor:Histogram:plotY", histogramY.plot("Histograms:Y"); ); DEBUG_REQUEST("ImageProcessor:Histogram:plotU", histogramU.plot("Histograms:U"); ); DEBUG_REQUEST("ImageProcessor:Histogram:plotV", histogramV.plot("Histograms:V"); ); for(int color = 0; color < ColorClasses::numOfColors; color++) { dbgString.str(""); dbgString << "ImageProcessor:Histogram:x:" << ColorClasses::getColorName( (ColorClasses::Color) color); DEBUG_REQUEST_GENERIC(dbgString.str(), drawXHist = true; Vector2<int> last(cameraInfo.resolutionWidth - (xHistogram[color].rawData[0] * 1), 0); for(unsigned int y = 1; y < (grid.height * 1); y += 1) { LINE_PX ( (ColorClasses::Color) color, last.x, last.y, cameraInfo.resolutionWidth - (xHistogram[color].rawData[y] * 1), y ); last.x = cameraInfo.resolutionWidth - (xHistogram[color].rawData[y] * 1); last.y = y; } ); dbgString.str(""); dbgString << "ImageProcessor:Histogram:y:" << ColorClasses::getColorName((ColorClasses::Color) color); DEBUG_REQUEST_GENERIC(dbgString.str(), drawYHist = true; Vector2<int> last(0, cameraInfo.resolutionHeight - (yHistogram[color].rawData[0] * 1) ); for(unsigned int x = 1; x < (grid.width * 1); x += 1) { LINE_PX ( (ColorClasses::Color) color, last.x, last.y, x, cameraInfo.resolutionHeight - (yHistogram[color].rawData[x] * 1) ); last.x = x; last.y = cameraInfo.resolutionHeight - (yHistogram[color].rawData[x] * 1); } ); } //DEBUG_REQUEST("ImageProcessor:Histogram:colorChannelHistogramCr", // drawChannelHist = true; // Vector2<int> last(0, Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[0], 0, (int)cameraInfo.resolutionHeight)); // for(unsigned int x = 1; x < COLOR_CHANNEL_VALUE_COUNT; x ++) // { // LINE_PX // ( // ColorClasses::red, // last.x, // last.y, // x, // Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[x], 0, (int)cameraInfo.resolutionHeight) // ); // last.x = x; // last.y = Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[x], 0, (int)cameraInfo.resolutionHeight); // } //); //if(drawChannelHist) //{ // RECT_PX // ( // ColorClasses::black, // 0, // cameraInfo.resolutionHeight, // COLOR_CHANNEL_VALUE_COUNT, // 0 // ); //} if(drawXHist) { RECT_PX( ColorClasses::black, cameraInfo.resolutionWidth - (grid.width * 1), 0, cameraInfo.resolutionWidth, grid.height * 1 ); } if(drawYHist) { RECT_PX ( ColorClasses::black, 0, cameraInfo.resolutionHeight - (grid.height * 1), (grid.width * 1), cameraInfo.resolutionHeight ); } }//end showDebugInfos inline void Histograms::createFromColoredGrid(const ColoredGrid& coloredGrid) { for(int color = 0; color < ColorClasses::numOfColors; color++) { for (unsigned int pixelIndex = 0; pixelIndex < coloredGrid.numberOfColorPoints[color]; pixelIndex++) { const Vector2<int>& gridPoint = coloredGrid.uniformGrid.getGridCoordinates(pixelIndex); increaseValue(gridPoint, (ColorClasses::Color) color); } } }//end createFromColoredGrid void Histograms::print(ostream& stream) const { stream << "Histogram"; }//end print <commit_msg>fixed build error<commit_after>/* * File: histograms.cpp * Author: claas * * Created on 9. Juli 2009, 13:40 */ #include "Histograms.h" // debug #include "Tools/Debug/DebugRequest.h" #include "Tools/Debug/DebugImageDrawings.h" using namespace naoth; using namespace std; Histograms::Histograms() { std::stringstream dbgString; std::stringstream descString; for(int color = 0; color < ColorClasses::numOfColors; color++) { dbgString.str(""); dbgString << "ImageProcessor:Histogram:x:" << ColorClasses::getColorName((ColorClasses::Color) color); descString.str(""); descString << "draw X axis histogram of " << ColorClasses::getColorName((ColorClasses::Color) color) << " pixels"; DEBUG_REQUEST_REGISTER(dbgString.str(), descString.str(), false); dbgString.str(""); dbgString << "ImageProcessor:Histogram:y:" << ColorClasses::getColorName((ColorClasses::Color) color); descString.str(""); descString << "draw Y axis histogram of " << ColorClasses::getColorName((ColorClasses::Color) color) << " pixels"; DEBUG_REQUEST_REGISTER(dbgString.str(), descString.str(), false); } //DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:colorChannelHistogramCr", "draw X axis rate histogram of the V (Cr) color channel from the field", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotY", "plot Y channel histogram bottom image", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotU", "plot U channel histogram bottom image", false); DEBUG_REQUEST_REGISTER("ImageProcessor:Histogram:plotV", "plot V channel histogram bottom image", false); init(); } void Histograms::init() { colorChannelIsUptodate = false; for(int c = 0; c < ColorClasses::numOfColors; c++) { xHistogram[c].clear(); yHistogram[c].clear(); } }//end init void Histograms::execute() { init(); } void Histograms::showDebugInfos(const UniformGrid& grid, const CameraInfo& cameraInfo) const { std::stringstream dbgString; bool drawXHist = false; bool drawYHist = false; //bool drawChannelHist = false; DEBUG_REQUEST("ImageProcessor:Histogram:plotY", histogramY.plot("Histograms:Y"); ); DEBUG_REQUEST("ImageProcessor:Histogram:plotU", histogramU.plot("Histograms:U"); ); DEBUG_REQUEST("ImageProcessor:Histogram:plotV", histogramV.plot("Histograms:V"); ); for(int color = 0; color < ColorClasses::numOfColors; color++) { dbgString.str(""); dbgString << "ImageProcessor:Histogram:x:" << ColorClasses::getColorName( (ColorClasses::Color) color); DEBUG_REQUEST_GENERIC(dbgString.str(), drawXHist = true; Vector2<int> last(cameraInfo.resolutionWidth - (xHistogram[color].rawData[0] * 1), 0); for(unsigned int y = 1; y < (grid.height * 1); y += 1) { LINE_PX ( (ColorClasses::Color) color, last.x, last.y, cameraInfo.resolutionWidth - (xHistogram[color].rawData[y] * 1), y ); last.x = cameraInfo.resolutionWidth - (xHistogram[color].rawData[y] * 1); last.y = y; } ); dbgString.str(""); dbgString << "ImageProcessor:Histogram:y:" << ColorClasses::getColorName((ColorClasses::Color) color); DEBUG_REQUEST_GENERIC(dbgString.str(), drawYHist = true; Vector2<int> last(0, cameraInfo.resolutionHeight - (yHistogram[color].rawData[0] * 1) ); for(unsigned int x = 1; x < (grid.width * 1); x += 1) { LINE_PX ( (ColorClasses::Color) color, last.x, last.y, x, cameraInfo.resolutionHeight - (yHistogram[color].rawData[x] * 1) ); last.x = x; last.y = cameraInfo.resolutionHeight - (yHistogram[color].rawData[x] * 1); } ); } //DEBUG_REQUEST("ImageProcessor:Histogram:colorChannelHistogramCr", // drawChannelHist = true; // Vector2<int> last(0, Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[0], 0, (int)cameraInfo.resolutionHeight)); // for(unsigned int x = 1; x < COLOR_CHANNEL_VALUE_COUNT; x ++) // { // LINE_PX // ( // ColorClasses::red, // last.x, // last.y, // x, // Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[x], 0, (int)cameraInfo.resolutionHeight) // ); // last.x = x; // last.y = Math::clamp((int)cameraInfo.resolutionHeight - (int) colorChannelHistogramCr[x], 0, (int)cameraInfo.resolutionHeight); // } //); //if(drawChannelHist) //{ // RECT_PX // ( // ColorClasses::black, // 0, // cameraInfo.resolutionHeight, // COLOR_CHANNEL_VALUE_COUNT, // 0 // ); //} if(drawXHist) { RECT_PX( ColorClasses::black, cameraInfo.resolutionWidth - (grid.width * 1), 0, cameraInfo.resolutionWidth, grid.height * 1 ); } if(drawYHist) { RECT_PX ( ColorClasses::black, 0, cameraInfo.resolutionHeight - (grid.height * 1), (grid.width * 1), cameraInfo.resolutionHeight ); } }//end showDebugInfos inline void Histograms::createFromColoredGrid(const ColoredGrid& coloredGrid) { for(int color = 0; color < ColorClasses::numOfColors; color++) { for (unsigned int pixelIndex = 0; pixelIndex < coloredGrid.numberOfColorPoints[color]; pixelIndex++) { const Vector2<int>& gridPoint = coloredGrid.uniformGrid.getGridCoordinates(pixelIndex); increaseValue(gridPoint, (ColorClasses::Color) color); } } }//end createFromColoredGrid void Histograms::print(ostream& stream) const { stream << "Histogram"; }//end print <|endoftext|>
<commit_before>#define AODSelector_cxx // The class definition in AODSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("AODSelector.cxx") // Root > T->Process("AODSelector.cxx","some options") // Root > T->Process("AODSelector.cxx+") // #include "AODSelector.h" #include <TH2.h> #include <TStyle.h> #include <TMath.h> #include <TAxis.h> #include <TH2F.h> #include <TH3F.h> #include <TH1F.h> #include <TF1.h> #include <TCanvas.h> #include <TRandom3.h> static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg / TMath::Sqrt(1. + bg * bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1. / bg,kp5); bb = TMath::Log(kp3 + bb); return (kp2 - aa - bb) * kp1 / aa; } Double_t DeuteronTPC(Double_t *x, Double_t *) { // Deuteron expected signal in TPC, taken from AntiHe4 task return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7); } unsigned int Log2Int(const unsigned int v) { // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000}; unsigned int r = (v & b[0]) != 0; r |= ((v & b[4]) != 0) << 4; r |= ((v & b[3]) != 0) << 3; r |= ((v & b[2]) != 0) << 2; r |= ((v & b[1]) != 0) << 1; return r; } void AODSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } Int_t AODSelector::GetCentBin(float cent) { if (cent < fCentralityBins[0]) return -1; for (int i = 0; i < kNCent; ++i) if (cent <= fCentralityBins[i + 1]) return i; return -1; } Int_t AODSelector::GetPtBin(float pt) { for (int i = 0; i < kNBins; ++i) { if (pt < fBins[i+1] && pt >= fBins[i]) { return i; } } return -1; } Bool_t AODSelector::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; return gRandom->Rndm() > prob[int(cent)]; } void AODSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); const Int_t nPtBins = kNBins; const Int_t nCentBins = kNCent; const Double_t *pTbins = fBins; const Double_t *centBins = fCentralityBins; const Int_t nDCAbins = 80; const Float_t range = 0.5; Double_t dcaBins[nDCAbins+1]; for (int i = 0; i <= nDCAbins; ++i) dcaBins[i] = i * range * 2 / nDCAbins - range; fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); GetOutputList()->Add(fCentrality); GetOutputList()->Add(fCentralityClasses); GetOutputList()->Add(fFlattenedCentrality); const int tofNbins = 75; const float tofLowBoundary = -2.4,tofHighBoundary = 3.6; Double_t tofBins[tofNbins + 1]; const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins; for (int i = 0; i <= tofNbins; ++i) tofBins[i] = i * deltaTOF + tofLowBoundary; const int dcaZnBins = 400; const float dcaZlimit = 10.; Double_t dcazBins[dcaZnBins + 1]; const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins; for (int i = 0; i <= dcaZnBins; ++i) dcazBins[i] = i * deltaDCAz - dcaZlimit; const int nTpcBins = 500; Double_t tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = i * 5; } fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500); fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); GetOutputList()->Add(fATOFsignal); GetOutputList()->Add(fATPCcounts); GetOutputList()->Add(fMDCAxy); GetOutputList()->Add(fMDCAz); GetOutputList()->Add(fMTOFsignal); GetOutputList()->Add(fMTPCcounts); GetOutputList()->Add(fTPCSignal); fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0); } Bool_t AODSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); if (centrality < 0) { fSkipEvent = kFALSE; if (-centrality < 13.f) fSkipEvent = Flatten(-centrality); if (!fSkipEvent) { fFlattenedCentrality->Fill(-centrality); fCentralityClasses->Fill(-centrality); } fCentrality->Fill(-centrality); } if (fSkipEvent) return kTRUE; const int cent = GetCentBin(TMath::Abs(centrality)); if (cent < 0) return kTRUE; if (TMath::Abs(eta) > 0.8) return kTRUE; if (TMath::Abs(chi2NDF) > kChi2Cut) return kTRUE; Double_t pz = TMath::Sqrt(p * p - pT * pT); Double_t e = TMath::Sqrt(p * p + M2D); Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz)); if (TMath::Abs(y) > 0.5) { return kTRUE; } if (TPCnSignal < kTPCsig) return kTRUE; if (ITSnClust - ITSnSignal <= 0) return kTRUE; if (TMath::Abs(DCAz) > kDCAz) return kTRUE; if (TMath::Abs(DCAxy) > 0.5f) return kTRUE; Float_t c_pT = pT; if (c_pT > 0) { c_pT -= fCorrectionD(c_pT); } else { c_pT += fCorrectionAD(-c_pT); } fTPCSignal->Fill(pTPC, TPCsignal); if (TPCsignal > 0.76f * fDeutBB->Eval(pTPC) && TPCsignal < 1.24f * fDeutBB->Eval(pTPC)) { if(c_pT > 0.) { fMTPCcounts->Fill(centrality,c_pT,TPCsignal); fMDCAxy->Fill(centrality,c_pT,DCAxy); fMDCAz->Fill(centrality,c_pT,DCAz); } else { fATPCcounts->Fill(centrality,-c_pT,TPCsignal); } if (TOFtime > 0.f && length > 350.f) { Float_t beta = length / (2.99792457999999984e-02f * TOFtime); if (beta < (1.f - EPSILON)) { Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta)); const float dm = p * p / (beta * beta * gamma * gamma) - M2D; if(c_pT > 0.) { fMTOFsignal->Fill(centrality,c_pT,dm); } else { fATOFsignal->Fill(centrality,-c_pT,dm); } } } } return kTRUE; } void AODSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void AODSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("nuclei.root","update"); f.mkdir(kName.Data()); f.cd(kName.Data()); ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write(); f.Close(); fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal"); fTPCSignal->Draw("colz"); fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0); fDeutBB->Draw("same"); } <commit_msg>Added ITS selection<commit_after>#define AODSelector_cxx // The class definition in AODSelector.h has been generated automatically // by the ROOT utility TTree::MakeSelector(). This class is derived // from the ROOT class TSelector. For more information on the TSelector // framework see $ROOTSYS/README/README.SELECTOR or the ROOT User Manual. // The following methods are defined in this file: // Begin(): called every time a loop on the tree starts, // a convenient place to create your histograms. // SlaveBegin(): called after Begin(), when on PROOF called only on the // slave servers. // Process(): called for each event, in this function you decide what // to read and fill your histograms. // SlaveTerminate: called at the end of the loop on the tree, when on PROOF // called only on the slave servers. // Terminate(): called at the end of the loop on the tree, // a convenient place to draw/fit your histograms. // // To use this file, try the following session on your Tree T: // // Root > T->Process("AODSelector.cxx") // Root > T->Process("AODSelector.cxx","some options") // Root > T->Process("AODSelector.cxx+") // #include "AODSelector.h" #include <TH2.h> #include <TStyle.h> #include <TMath.h> #include <TAxis.h> #include <TH2F.h> #include <TH3F.h> #include <TH1F.h> #include <TF1.h> #include <TCanvas.h> #include <TRandom3.h> static void BinLogAxis(const TH1 *h) { // // Method for the correct logarithmic binning of histograms // TAxis *axis = const_cast<TAxis*>(h->GetXaxis()); const Int_t bins = axis->GetNbins(); const Double_t from = axis->GetXmin(); const Double_t to = axis->GetXmax(); Double_t *newBins = new Double_t[bins + 1]; newBins[0] = from; Double_t factor = pow(to / from, 1. / bins); for (Int_t i = 1; i <= bins; i++) { newBins[i] = factor * newBins[i - 1]; } axis->Set(bins, newBins); delete [] newBins; } Double_t BetheBlochAleph(Double_t bg, Double_t kp1, Double_t kp2, Double_t kp3, Double_t kp4, Double_t kp5) { Double_t beta = bg / TMath::Sqrt(1. + bg * bg); Double_t aa = TMath::Power(beta,kp4); Double_t bb = TMath::Power(1. / bg,kp5); bb = TMath::Log(kp3 + bb); return (kp2 - aa - bb) * kp1 / aa; } Double_t DeuteronTPC(Double_t *x, Double_t *) { // Deuteron expected signal in TPC, taken from AntiHe4 task return BetheBlochAleph(x[0] / MD ,4.69637,7.51827,0.0183746,2.60,2.7); } unsigned int Log2Int(const unsigned int v) { // Taken from https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogObvious static const unsigned int b[] = {0xAAAAAAAA, 0xCCCCCCCC, 0xF0F0F0F0, 0xFF00FF00, 0xFFFF0000}; unsigned int r = (v & b[0]) != 0; r |= ((v & b[4]) != 0) << 4; r |= ((v & b[3]) != 0) << 3; r |= ((v & b[2]) != 0) << 2; r |= ((v & b[1]) != 0) << 1; return r; } void AODSelector::Begin(TTree * /*tree*/) { // The Begin() function is called at the start of the query. // When running with PROOF Begin() is only called on the client. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); } Int_t AODSelector::GetCentBin(float cent) { if (cent < fCentralityBins[0]) return -1; for (int i = 0; i < kNCent; ++i) if (cent <= fCentralityBins[i + 1]) return i; return -1; } Int_t AODSelector::GetPtBin(float pt) { for (int i = 0; i < kNBins; ++i) { if (pt < fBins[i+1] && pt >= fBins[i]) { return i; } } return -1; } Bool_t AODSelector::Flatten(float cent) { float prob[13] = { 0.855566,0.846964,0.829618,0.829259,0.830984, 0.85094,0.844346,0.851818,0.874758,1, 0.374767,0.650491,0.946963 }; return gRandom->Rndm() > prob[int(cent)]; } void AODSelector::SlaveBegin(TTree * /*tree*/) { // The SlaveBegin() function is called after the Begin() function. // When running with PROOF SlaveBegin() is called on each slave server. // The tree argument is deprecated (on PROOF 0 is passed). TString option = GetOption(); const Int_t nPtBins = kNBins; const Int_t nCentBins = kNCent; const Double_t *pTbins = fBins; const Double_t *centBins = fCentralityBins; const Int_t nDCAbins = 80; const Float_t range = 0.5; Double_t dcaBins[nDCAbins+1]; for (int i = 0; i <= nDCAbins; ++i) dcaBins[i] = i * range * 2 / nDCAbins - range; fCentrality = new TH1F("fCentrality",";Centrality (%);Events / 1%;",100,0.,100.); fCentralityClasses = new TH1F("fCentralityClasses",";Centrality classes(%);Events / Class;",nCentBins,centBins); fFlattenedCentrality = new TH1F("fFlattenCentrality","Centrality distribution after the flattening;Centrality (%);Events / 1%;",100,0.,100.); GetOutputList()->Add(fCentrality); GetOutputList()->Add(fCentralityClasses); GetOutputList()->Add(fFlattenedCentrality); const int tofNbins = 75; const float tofLowBoundary = -2.4,tofHighBoundary = 3.6; Double_t tofBins[tofNbins + 1]; const float deltaTOF = (tofHighBoundary - tofLowBoundary) / tofNbins; for (int i = 0; i <= tofNbins; ++i) tofBins[i] = i * deltaTOF + tofLowBoundary; const int dcaZnBins = 400; const float dcaZlimit = 10.; Double_t dcazBins[dcaZnBins + 1]; const float deltaDCAz = 2.f * dcaZlimit / dcaZnBins; for (int i = 0; i <= dcaZnBins; ++i) dcazBins[i] = i * deltaDCAz - dcaZlimit; const int nTpcBins = 500; Double_t tpcBins[nTpcBins + 1]; for (int i = 0; i <= nTpcBins; ++i) { tpcBins[i] = i * 5; } fTPCSignal = new TH2F("fTPCSignal","p_{T} (GeV/c);dE/dx (a.u.)",nPtBins,pTbins,500,0,2500); fATOFsignal = new TH3F("fATOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fATPCcounts = new TH3F("fATPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); fMDCAxy = new TH3F("fMDCAxy",";Centrality (%);p_{T} (GeV/c); DCA_{xy} (cm)", nCentBins,centBins,nPtBins,pTbins,nDCAbins,dcaBins); fMDCAz = new TH3F("fMDCAz",";Centrality (%);p_{T} (GeV/c); DCA_{z} (cm)", nCentBins,centBins,nPtBins,pTbins,dcaZnBins,dcazBins); fMTOFsignal = new TH3F("fMTOFsignal", ";Centrality (%);p_{T} (GeV/c);m_{TOF}^{2}-m_{PDG}^{2} (GeV/c^{2})^{2}", nCentBins,centBins,nPtBins,pTbins,tofNbins,tofBins); fMTPCcounts = new TH3F("fMTPCcounts",";Centrality (%);p_{T} (GeV/c); TPC dE/dx (a.u.)", nCentBins,centBins,nPtBins,pTbins,nTpcBins,tpcBins); GetOutputList()->Add(fATOFsignal); GetOutputList()->Add(fATPCcounts); GetOutputList()->Add(fMDCAxy); GetOutputList()->Add(fMDCAz); GetOutputList()->Add(fMTOFsignal); GetOutputList()->Add(fMTPCcounts); GetOutputList()->Add(fTPCSignal); fDeutBB = new TF1("fDeutBB",DeuteronTPC,0.3,6,0); } Bool_t AODSelector::Process(Long64_t entry) { // The Process() function is called for each entry in the tree (or possibly // keyed object in the case of PROOF) to be processed. The entry argument // specifies which entry in the currently loaded tree is to be processed. // It can be passed to either AODSelector::GetEntry() or TBranch::GetEntry() // to read either all or the required parts of the data. When processing // keyed objects with PROOF, the object is already loaded and is available // via the fObject pointer. // // This function should contain the "body" of the analysis. It can contain // simple or elaborate selection criteria, run algorithms on the data // of the event and typically fill histograms. // // The processing can be stopped by calling Abort(). // // Use fStatus to set the return value of TTree::Process(). // // The return value is currently not used. GetEntry(entry); if (centrality < 0) { fSkipEvent = kFALSE; if (-centrality < 13.f) fSkipEvent = Flatten(-centrality); if (!fSkipEvent) { fFlattenedCentrality->Fill(-centrality); fCentralityClasses->Fill(-centrality); } fCentrality->Fill(-centrality); } if (fSkipEvent) return kTRUE; const int cent = GetCentBin(TMath::Abs(centrality)); if (cent < 0) return kTRUE; if (TMath::Abs(eta) > 0.8) return kTRUE; if (TMath::Abs(chi2NDF) > kChi2Cut) return kTRUE; Double_t pz = TMath::Sqrt(p * p - pT * pT); Double_t e = TMath::Sqrt(p * p + M2D); Double_t y = 0.5 * TMath::Log((e + pz) / (e - pz)); if (TMath::Abs(y) > 0.5) { return kTRUE; } if (TPCnSignal < kTPCsig) return kTRUE; if (ITSnClust - ITSnSignal <= 0) return kTRUE; if (TMath::Abs(DCAz) > kDCAz) return kTRUE; if (TMath::Abs(DCAxy) > 0.5f) return kTRUE; Float_t c_pT = pT; if (c_pT > 0) { c_pT -= fCorrectionD(c_pT); } else { c_pT += fCorrectionAD(-c_pT); } fTPCSignal->Fill(pTPC, TPCsignal); if (TPCsignal > 0.76f * fDeutBB->Eval(pTPC) && TPCsignal < 1.24f * fDeutBB->Eval(pTPC)) { if (pTPC < 1.4 && TMath::Abs(ITSsigmad) > 3.) { return kTRUE; } if(c_pT > 0.) { fMTPCcounts->Fill(centrality,c_pT,TPCsignal); fMDCAxy->Fill(centrality,c_pT,DCAxy); fMDCAz->Fill(centrality,c_pT,DCAz); } else { fATPCcounts->Fill(centrality,-c_pT,TPCsignal); } if (TOFtime > 0.f && length > 350.f) { Float_t beta = length / (2.99792457999999984e-02f * TOFtime); if (beta < (1.f - EPSILON)) { Float_t gamma = 1. / TMath::Sqrt(1.f - (beta * beta)); const float dm = p * p / (beta * beta * gamma * gamma) - M2D; if(c_pT > 0.) { fMTOFsignal->Fill(centrality,c_pT,dm); } else { fATOFsignal->Fill(centrality,-c_pT,dm); } } } } return kTRUE; } void AODSelector::SlaveTerminate() { // The SlaveTerminate() function is called after all entries or objects // have been processed. When running with PROOF SlaveTerminate() is called // on each slave server. } void AODSelector::Terminate() { // The Terminate() function is the last function to be called during // a query. It always runs on the client, it can be used to present // the results graphically or save the results to file. TFile f("nuclei.root","update"); f.mkdir(kName.Data()); f.cd(kName.Data()); ((TH1F*)GetOutputList()->FindObject("fCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fFlattenCentrality"))->Write(); ((TH1F*)GetOutputList()->FindObject("fCentralityClasses"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fATPCcounts"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAxy"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMDCAz"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTOFsignal"))->Write(); ((TH3F*)GetOutputList()->FindObject("fMTPCcounts"))->Write(); f.Close(); fTPCSignal = (TH2F*)GetOutputList()->FindObject("fTPCSignal"); fTPCSignal->Draw("colz"); fDeutBB = new TF1("deutTPC",DeuteronTPC,0.4,6,0); fDeutBB->Draw("same"); } <|endoftext|>
<commit_before>//===----------------------------------------------------------------------===// // // Peloton // // string_functions.cpp // // Identification: src/function/string_functions.cpp // // Copyright (c) 2015-2017, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cctype> #include <string> #include <algorithm> #include "function/string_functions.h" #include "type/value_factory.h" #define NextByte(p, plen) ((p)++, (plen)--) namespace peloton { namespace function { uint32_t StringFunctions::Ascii(const char *str, uint32_t length) { PL_ASSERT(str != nullptr); return length <= 1 ? 0 : static_cast<uint32_t>(str[0]); } // ASCII code of the first character of the argument. type::Value StringFunctions::_Ascii(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } uint32_t ret = Ascii(args[0].GetAs<const char *>(), args[0].GetLength()); return type::ValueFactory::GetIntegerValue(ret); } bool StringFunctions::Like(const char *t, uint32_t tlen, const char *p, uint32_t plen) { PL_ASSERT(t != nullptr); PL_ASSERT(p != nullptr); if (plen == 1 && *p == '%') return true; while (tlen > 0 && plen > 0) { if (*p == '\\') { NextByte(p, plen); if (plen <= 0) return false; if (tolower(*p) != tolower(*t)) return false; } else if (*p == '%') { char firstpat; NextByte(p, plen); while (plen > 0) { if (*p == '%') NextByte(p, plen); else if (*p == '_') { if (tlen <= 0) return false; NextByte(t, tlen); NextByte(p, plen); } else break; } if (plen <= 0) return true; if (*p == '\\') { if (plen < 2) return false; firstpat = tolower(p[1]); } else firstpat = tolower(*p); while (tlen > 0) { if (tolower(*t) == firstpat) { int matched = Like(t, tlen, p, plen); if (matched != false) return matched; } NextByte(t, tlen); } return false; } else if (*p == '_') { NextByte(t, tlen); NextByte(p, plen); continue; } else if (tolower(*p) != tolower(*t)) { return false; } NextByte(t, tlen); NextByte(p, plen); } if (tlen > 0) return false; while (plen > 0 && *p == '%') NextByte(p, plen); if (plen <= 0) return true; return false; } type::Value StringFunctions::_Like(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } bool ret = Like(args[0].GetAs<const char *>(), args[0].GetLength(), args[1].GetAs<const char *>(), args[1].GetLength()); return type::ValueFactory::GetBooleanValue(ret); } // Get Character from integer type::Value StringFunctions::Chr(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } int32_t val = args[0].GetAs<int32_t>(); std::string str(1, static_cast<char>(val)); return type::ValueFactory::GetVarcharValue(str); } // substring type::Value StringFunctions::Substr(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 3); if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); int32_t from = args[1].GetAs<int32_t>() - 1; int32_t len = args[2].GetAs<int32_t>(); return type::ValueFactory::GetVarcharValue(str.substr(from, len)); } // Number of characters in string type::Value StringFunctions::CharLength(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } std::string str = args[0].ToString(); int32_t len = str.length(); return (type::ValueFactory::GetIntegerValue(len)); } // Concatenate two strings type::Value StringFunctions::Concat(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString() + args[1].ToString(); return (type::ValueFactory::GetVarcharValue(str)); } // Number of bytes in string type::Value StringFunctions::OctetLength(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); std::string str = args[0].ToString(); int32_t len = str.length(); return (type::ValueFactory::GetIntegerValue(len)); } // Repeat string the specified number of times type::Value StringFunctions::Repeat(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); int32_t num = args[1].GetAs<int32_t>(); std::string ret = ""; while (num--) { ret = ret + str; } return (type::ValueFactory::GetVarcharValue(ret)); } // Replace all occurrences in string of substring from with substring to type::Value StringFunctions::Replace(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 3); if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); std::string from = args[1].ToString(); std::string to = args[2].ToString(); size_t pos = 0; while ((pos = str.find(from, pos)) != std::string::npos) { str.replace(pos, from.length(), to); pos += to.length(); } return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string containing only characters from characters // from the start of string type::Value StringFunctions::LTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); std::string from = args[1].ToString(); size_t pos = 0; bool erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos++; } if (erase) str.erase(0, pos); return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string containing only characters from characters // from the end of string type::Value StringFunctions::RTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args.at(0).ToString(); std::string from = args.at(1).ToString(); if (str.length() == 0) return (type::ValueFactory::GetVarcharValue("")); size_t pos = str.length() - 1; bool erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos--; } if (erase) str.erase(pos + 1, str.length() - pos - 1); return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string consisting only of characters in characters // from the start and end of string StringFunctions::StrWithLen StringFunctions::BTrim( const char *str, uint32_t str_len, const char *from, UNUSED_ATTRIBUTE uint32_t from_len) { PL_ASSERT(str != nullptr && from != nullptr); if (str_len == 0) { return StringFunctions::StrWithLen(nullptr, 0); } int tail = str_len - 1, head = 0; while (tail >= 0 && strchr(from, str[tail]) != NULL) tail--; tail++; while (head < (int)str_len && strchr(from, str[head]) != NULL) head++; return StringFunctions::StrWithLen(str + head, std::max(tail - head + 1, 0)); } type::Value StringFunctions::_BTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args.at(0).ToString(); std::string from = args.at(1).ToString(); if (str.length() == 0) return (type::ValueFactory::GetVarcharValue("")); size_t pos = str.length() - 1; bool erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos--; } if (erase) str.erase(pos + 1, str.length() - pos - 1); pos = 0; erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos++; } if (erase) str.erase(0, pos); return (type::ValueFactory::GetVarcharValue(str)); } uint32_t StringFunctions::Length(UNUSED_ATTRIBUTE const char *str, uint32_t length) { PL_ASSERT(str != nullptr); return length; } // The length of the string type::Value StringFunctions::_Length(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } uint32_t ret = Length(args[0].GetAs<const char *>(), args[0].GetLength()); return type::ValueFactory::GetIntegerValue(ret); } } // namespace function } // namespace peloton <commit_msg>fix length and use BTrim within _BTrim<commit_after>//===----------------------------------------------------------------------===// // // Peloton // // string_functions.cpp // // Identification: src/function/string_functions.cpp // // Copyright (c) 2015-2017, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #include <cctype> #include <string> #include <algorithm> #include "function/string_functions.h" #include "type/value_factory.h" #define NextByte(p, plen) ((p)++, (plen)--) namespace peloton { namespace function { uint32_t StringFunctions::Ascii(const char *str, uint32_t length) { PL_ASSERT(str != nullptr); return length <= 1 ? 0 : static_cast<uint32_t>(str[0]); } // ASCII code of the first character of the argument. type::Value StringFunctions::_Ascii(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } uint32_t ret = Ascii(args[0].GetAs<const char *>(), args[0].GetLength()); return type::ValueFactory::GetIntegerValue(ret); } bool StringFunctions::Like(const char *t, uint32_t tlen, const char *p, uint32_t plen) { PL_ASSERT(t != nullptr); PL_ASSERT(p != nullptr); if (plen == 1 && *p == '%') return true; while (tlen > 0 && plen > 0) { if (*p == '\\') { NextByte(p, plen); if (plen <= 0) return false; if (tolower(*p) != tolower(*t)) return false; } else if (*p == '%') { char firstpat; NextByte(p, plen); while (plen > 0) { if (*p == '%') NextByte(p, plen); else if (*p == '_') { if (tlen <= 0) return false; NextByte(t, tlen); NextByte(p, plen); } else break; } if (plen <= 0) return true; if (*p == '\\') { if (plen < 2) return false; firstpat = tolower(p[1]); } else firstpat = tolower(*p); while (tlen > 0) { if (tolower(*t) == firstpat) { int matched = Like(t, tlen, p, plen); if (matched != false) return matched; } NextByte(t, tlen); } return false; } else if (*p == '_') { NextByte(t, tlen); NextByte(p, plen); continue; } else if (tolower(*p) != tolower(*t)) { return false; } NextByte(t, tlen); NextByte(p, plen); } if (tlen > 0) return false; while (plen > 0 && *p == '%') NextByte(p, plen); if (plen <= 0) return true; return false; } type::Value StringFunctions::_Like(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } bool ret = Like(args[0].GetAs<const char *>(), args[0].GetLength(), args[1].GetAs<const char *>(), args[1].GetLength()); return type::ValueFactory::GetBooleanValue(ret); } // Get Character from integer type::Value StringFunctions::Chr(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } int32_t val = args[0].GetAs<int32_t>(); std::string str(1, static_cast<char>(val)); return type::ValueFactory::GetVarcharValue(str); } // substring type::Value StringFunctions::Substr(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 3); if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); int32_t from = args[1].GetAs<int32_t>() - 1; int32_t len = args[2].GetAs<int32_t>(); return type::ValueFactory::GetVarcharValue(str.substr(from, len)); } // Number of characters in string type::Value StringFunctions::CharLength(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } std::string str = args[0].ToString(); int32_t len = str.length(); return (type::ValueFactory::GetIntegerValue(len)); } // Concatenate two strings type::Value StringFunctions::Concat(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString() + args[1].ToString(); return (type::ValueFactory::GetVarcharValue(str)); } // Number of bytes in string type::Value StringFunctions::OctetLength(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); std::string str = args[0].ToString(); int32_t len = str.length(); return (type::ValueFactory::GetIntegerValue(len)); } // Repeat string the specified number of times type::Value StringFunctions::Repeat(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); int32_t num = args[1].GetAs<int32_t>(); std::string ret = ""; while (num--) { ret = ret + str; } return (type::ValueFactory::GetVarcharValue(ret)); } // Replace all occurrences in string of substring from with substring to type::Value StringFunctions::Replace(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 3); if (args[0].IsNull() || args[1].IsNull() || args[2].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); std::string from = args[1].ToString(); std::string to = args[2].ToString(); size_t pos = 0; while ((pos = str.find(from, pos)) != std::string::npos) { str.replace(pos, from.length(), to); pos += to.length(); } return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string containing only characters from characters // from the start of string type::Value StringFunctions::LTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args[0].ToString(); std::string from = args[1].ToString(); size_t pos = 0; bool erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos++; } if (erase) str.erase(0, pos); return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string containing only characters from characters // from the end of string type::Value StringFunctions::RTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } std::string str = args.at(0).ToString(); std::string from = args.at(1).ToString(); if (str.length() == 0) return (type::ValueFactory::GetVarcharValue("")); size_t pos = str.length() - 1; bool erase = 0; while (from.find(str[pos]) != std::string::npos) { erase = 1; pos--; } if (erase) str.erase(pos + 1, str.length() - pos - 1); return (type::ValueFactory::GetVarcharValue(str)); } // Remove the longest string consisting only of characters in characters // from the start and end of string StringFunctions::StrWithLen StringFunctions::BTrim( const char *str, uint32_t str_len, const char *from, UNUSED_ATTRIBUTE uint32_t from_len) { PL_ASSERT(str != nullptr && from != nullptr); str_len--; // skip the tailing 0 if (str_len == 0) { return StringFunctions::StrWithLen(str, 1); } int tail = str_len - 1, head = 0; while (tail >= 0 && strchr(from, str[tail]) != NULL) tail--; while (head < (int)str_len && strchr(from, str[head]) != NULL) head++; return StringFunctions::StrWithLen(str + head, std::max(tail - head + 1, 0) + 1); } type::Value StringFunctions::_BTrim(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 2); if (args[0].IsNull() || args[1].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::VARCHAR); } StrWithLen ret = BTrim(args.at(0).GetData(), strlen(args.at(0).GetData() + 1), args.at(1).GetData(), strlen(args.at(1).GetData()) + 1); std::string str(ret.str, ret.length - 1); return type::ValueFactory::GetVarcharValue(str); } uint32_t StringFunctions::Length(UNUSED_ATTRIBUTE const char *str, uint32_t length) { PL_ASSERT(str != nullptr); return length; } // The length of the string type::Value StringFunctions::_Length(const std::vector<type::Value> &args) { PL_ASSERT(args.size() == 1); if (args[0].IsNull()) { return type::ValueFactory::GetNullValueByType(type::TypeId::INTEGER); } uint32_t ret = Length(args[0].GetAs<const char *>(), args[0].GetLength()); return type::ValueFactory::GetIntegerValue(ret); } } // namespace function } // namespace peloton <|endoftext|>
<commit_before>/* * simple_tree.cpp * * Created on: Aug 12, 2010 * Author: programmer */ #include "../system/discursive_system.h" #include "./initial_agents.h" #include "repository_access.h" #include <Magick++.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "../model/surrogate_tree_node.h" #include "../dec/spatial_displacement.h" #include "../draw/scanline_artist.h" #include "../gen/space_colonizer.h" using namespace Magick; int debugLevel; // display our command usage void display_usage( void ) { std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n"; usage_string += "where option can be any of the following"; usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n"; usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n"; usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n"; usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n"; usage_string += "\n-i option - interactive mode (asks you questions) \n"; usage_string += "\n-d option - debug level, defaults to 1\n"; usage_string += "\n-o or -O option - output file name, defaults to tree.jpg\n"; usage_string += "\n-m option - output the creation of the current tree one step at a time via many .jpgs in sequence\n"; usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5 \n"; usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n"; usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n"; usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n"; usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .jpgs in sequence\n"; usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5 \n"; usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n"; usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n"; usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n"; usage_string += "\n-l option - spatial displacement scaling levels, expects W1:H1:W2:H2 defaults to 5000:5000:4500:4200\n"; usage_string += "\n----------------where W1 is the start width\n"; usage_string += "\n----------------where H1 is the start height\n"; usage_string += "\n----------------where W2 is the end width\n"; usage_string += "\n----------------where H2 is the end height\n"; usage_string += "\n-z option - image size , expects WxH, defaults to 500x500 \n"; DiscursivePrint("%s",usage_string.c_str()); DiscursiveError("Copyright Discursive Labs LLC, 2010"); } int main(int argc, char **argv) { // set the debug level SetDiscursiveDebugLevel(0); // agentName equates to the passed command line parameter argument string char *agentName = NULL; // type of agent to use, ie command line options or interactive int agentType = 0; // scaling factors to use for spatial displacement int startWidth = 5000; int startHeight = 5000; int endWidth = 4500; int endHeight = 4250; // image size options for jpg output int imageWidth = 500; int imageHeight = 500; // our filename for output file std::string fileName = "tree.jpg"; // should we make many jpgs? int manyJpgs = 0; // options for many jpgs int jpgStep = 1; int jpgStart = 3; int jpgStop = 10000; // should we output a jpg per revision? int revJpgs = 0; // options for jpg per revison int revStep = 1; int revStart = 2; int revStop = 10000; // our option string static const char *optString = "g:G:S:C:O:o:m:R:l:z:ridh?"; // loop over our command options in the normal unix way int opt; opt = getopt( argc, argv, optString ); while( opt != -1 ) { switch( opt ) { case 'g': agentName = optarg; agentType = 1; break; case 'G': agentName = optarg; agentType = 2; break; case 'S': agentName = optarg; agentType = 3; break; case 'C': agentName = optarg; agentType = 4; break; case 'l': sscanf(optarg,"%d:%d:%d:%d",&startWidth,&startHeight,&endWidth,&endHeight); break; case 'z': sscanf(optarg,"%dx%d",&imageWidth,&imageHeight); break; case 'm': manyJpgs = 1; sscanf(optarg,"%d:%d:%d",&jpgStart,&jpgStop,&jpgStep); if(jpgStart < 3) { jpgStart = 3; } break; case 'R': revJpgs = 1; sscanf(optarg,"%d:%d:%d",&revStart,&revStop,&revStep); if(revStart < 3) { revStart = 3; } break; case 'r': revJpgs = 1; revStart = 3; revStop = 100000; revStep = 1; break; case 'o': case 'O': fileName = optarg; break; case 'd': // set the debug level SetDiscursiveDebugLevel(1); break; case 'i': // set the interactivity level agentType = 5; break; case 'h': /* fall-through is intentional */ case '?': display_usage(); break; default: DiscursiveError("bad cli, bad!"); break; } // get the next Command Line option opt = getopt( argc, argv, optString ); } // Tree Generation pipeline // create an abstract method for repository access RepositoryAccess* git; // let an interactive or command line agent create the repository access type switch(agentType) { case 5: git = interactive_agent(); break; case 1: case 2: case 3: case 4: DiscursiveDebugPrint("%s\n",agentName); git = noninteractive_agent(agentType, agentName); break; case 0: display_usage(); break; default: /* You won't actually get here. */ DiscursiveError("an impossibility occured in error processing"); break; } // set our scaling factor from our received or default options double widthRescaling = endWidth/(double)startWidth; double heightRescaling = endHeight/(double)startHeight; // set our repository single or manyjpg options git->snapshotJpgs = manyJpgs; git->jpgIndex = 1000; git->scaleHeight = heightRescaling; git->scaleWidth = widthRescaling; git->fileName = (char*)fileName.c_str(); git->globalInserts = 0; git->localInserts = 0; git->insertTarget = 0; git->revJpgs = revJpgs; git->globalRevs = 0; git->localRevs = 0; git->revTarget = 0; git->currentTreeSize = 0; git->logGenerated = 0; // retrieve our source tree DiscursivePrint("Retrieving From Server, Please Wait...\n"); git->source = git->retrieve(); // output tree info DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str()); DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts); // create loop step variables generically for any jpg looping type int loopStart = 0; int loopStop = 1; int loopStep = 1; int executeLoopType = 1; // check for our custom loop types if(manyJpgs) { loopStart = jpgStart; loopStop = jpgStop; loopStep = jpgStep; executeLoopType = 2; } else if(revJpgs) { loopStart = revStart; loopStop = revStop; loopStep = revStep; executeLoopType = 3; } // check for too many global inserts or revisions if((executeLoopType == 2) && (loopStop >= git->globalInserts)) { loopStop = git->globalInserts-1; } DiscursiveDebugPrint("Total revs in repo = %d and loopstop = %d\n",git->globalRevs,loopStop); if((executeLoopType == 3) && (loopStop >= git->globalRevs)) { loopStop = git->globalRevs-1; } // loop over a bunch of increasingly large trees for debug or revision tree generation // use our user-set parameters to define our step for(int i = loopStart; i<loopStop;i+= loopStep) { // reset our insert variables if(executeLoopType == 2) { git->localInserts = 0; git->insertTarget = i; } else if(executeLoopType == 3) { git->localRevs = 0; git->revTarget = i; } // retrieve our source tree git->source = git->retrieve(); DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,loopStop,loopStep); // Decorate surrogate tree nodes with locations SpatialDisplacement* disp = new SpatialDisplacement(imageWidth,imageHeight,widthRescaling,heightRescaling); disp->decorate(git->source); // Digitize decorated surrogate tree into line segment tree DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,loopStop,loopStep); SpaceColonizer *digitizer = new SpaceColonizer(1); DrawableData* lines = digitizer->digitize(git->source); // Transform // Draw tree DiscursivePrint("Drawing Tree %d out of %d step value %d",i,loopStop,loopStep); Image canvas(Geometry(imageWidth,imageHeight),"white"); ScanlineArtist artist; artist.draw(canvas, lines); // actually generate a tree DiscursivePrint("Writing Tree %d out of %d step value %d\n",i,loopStop,loopStep); git->WriteJPGFromCanvas(&canvas); } return 0; } <commit_msg>updated simple tree to be jpg again<commit_after>/* * simple_tree.cpp * * Created on: Aug 12, 2010 * Author: programmer */ #include "../system/discursive_system.h" #include "./initial_agents.h" #include "repository_access.h" #include <Magick++.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "../model/surrogate_tree_node.h" #include "../dec/spatial_displacement.h" #include "../draw/scanline_artist.h" #include "../gen/space_colonizer.h" using namespace Magick; int debugLevel; // display our command usage void display_usage( void ) { std::string usage_string = "\nsimple_tree [option] [optionstringorint] \n"; usage_string += "where option can be any of the following"; usage_string += "\n-g option - expects ~/Projects/source_tree_vis\n"; usage_string += "\n-G option - expects gitHubusername:gitHubprojectname\n"; usage_string += "\n-S option - expects http://hkit.googlecode.com/svn/trunk/\n"; usage_string += "\n-C option - expects pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n"; usage_string += "\n-i option - interactive mode (asks you questions) \n"; usage_string += "\n-d option - debug level, defaults to 1\n"; usage_string += "\n-o or -O option - output file name, defaults to tree.jpg\n"; usage_string += "\n-m option - output the creation of the current tree one step at a time via many .images in sequence\n"; usage_string += "\n--------------also expects the following start:stop:step i.e. 1:400:5 \n"; usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n"; usage_string += "\n----------------finish number for many jpg tree rendering, default is treesize\n"; usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n"; usage_string += "\n-R and -r option -output the creation of the current tree one revision at a time via many .images in sequence\n"; usage_string += "\n-------------- -R also expects the following start:stop:step i.e. 1:400:5 \n"; usage_string += "\n----------------start number for many jpg tree rendering, default is 3\n"; usage_string += "\n----------------finish number for many jpg tree rendering, default is currentrevision\n"; usage_string += "\n----------------step value for many jpg tree rendering, default is 1\n"; usage_string += "\n-l option - spatial displacement scaling levels, expects W1:H1:W2:H2 defaults to 5000:5000:4500:4200\n"; usage_string += "\n----------------where W1 is the start width\n"; usage_string += "\n----------------where H1 is the start height\n"; usage_string += "\n----------------where W2 is the end width\n"; usage_string += "\n----------------where H2 is the end height\n"; usage_string += "\n-z option - image size , expects WxH, defaults to 500x500 \n"; DiscursivePrint("%s",usage_string.c_str()); DiscursiveError("Copyright Discursive Labs LLC, 2010"); } int main(int argc, char **argv) { // set the debug level SetDiscursiveDebugLevel(0); // agentName equates to the passed command line parameter argument string char *agentName = NULL; // type of agent to use, ie command line options or interactive int agentType = 0; // scaling factors to use for spatial displacement int startWidth = 5000; int startHeight = 5000; int endWidth = 4500; int endHeight = 4250; // image size options for jpg output int imageWidth = 500; int imageHeight = 500; // our filename for output file std::string fileName = "tree.jpg"; // should we make many jpgs? int manyJpgs = 0; // options for many jpgs int jpgStep = 1; int jpgStart = 3; int jpgStop = 10000; // should we output a jpg per revision? int revJpgs = 0; // options for jpg per revison int revStep = 1; int revStart = 2; int revStop = 10000; // our option string static const char *optString = "g:G:S:C:O:o:m:R:l:z:ridh?"; // loop over our command options in the normal unix way int opt; opt = getopt( argc, argv, optString ); while( opt != -1 ) { switch( opt ) { case 'g': agentName = optarg; agentType = 1; break; case 'G': agentName = optarg; agentType = 2; break; case 'S': agentName = optarg; agentType = 3; break; case 'C': agentName = optarg; agentType = 4; break; case 'l': sscanf(optarg,"%d:%d:%d:%d",&startWidth,&startHeight,&endWidth,&endHeight); break; case 'z': sscanf(optarg,"%dx%d",&imageWidth,&imageHeight); break; case 'm': manyJpgs = 1; sscanf(optarg,"%d:%d:%d",&jpgStart,&jpgStop,&jpgStep); if(jpgStart < 3) { jpgStart = 3; } break; case 'R': revJpgs = 1; sscanf(optarg,"%d:%d:%d",&revStart,&revStop,&revStep); if(revStart < 3) { revStart = 3; } break; case 'r': revJpgs = 1; revStart = 3; revStop = 100000; revStep = 1; break; case 'o': case 'O': fileName = optarg; break; case 'd': // set the debug level SetDiscursiveDebugLevel(1); break; case 'i': // set the interactivity level agentType = 5; break; case 'h': /* fall-through is intentional */ case '?': display_usage(); break; default: DiscursiveError("bad cli, bad!"); break; } // get the next Command Line option opt = getopt( argc, argv, optString ); } // Tree Generation pipeline // create an abstract method for repository access RepositoryAccess* git; // let an interactive or command line agent create the repository access type switch(agentType) { case 5: git = interactive_agent(); break; case 1: case 2: case 3: case 4: DiscursiveDebugPrint("%s\n",agentName); git = noninteractive_agent(agentType, agentName); break; case 0: display_usage(); break; default: /* You won't actually get here. */ DiscursiveError("an impossibility occured in error processing"); break; } // set our scaling factor from our received or default options double widthRescaling = endWidth/(double)startWidth; double heightRescaling = endHeight/(double)startHeight; // set our repository single or manyjpg options git->snapshotJpgs = manyJpgs; git->jpgIndex = 1000; git->scaleHeight = heightRescaling; git->scaleWidth = widthRescaling; git->fileName = (char*)fileName.c_str(); git->globalInserts = 0; git->localInserts = 0; git->insertTarget = 0; git->revJpgs = revJpgs; git->globalRevs = 0; git->localRevs = 0; git->revTarget = 0; git->currentTreeSize = 0; git->logGenerated = 0; // retrieve our source tree DiscursivePrint("Retrieving From Server, Please Wait...\n"); git->source = git->retrieve(); // output tree info DiscursivePrint("Source tree name is %s\n", git->source->data["name"].c_str()); DiscursivePrint("Source tree has %d revisions which require %d tree inserts\n",git->globalRevs,git->globalInserts); // create loop step variables generically for any jpg looping type int loopStart = 0; int loopStop = 1; int loopStep = 1; int executeLoopType = 1; // check for our custom loop types if(manyJpgs) { loopStart = jpgStart; loopStop = jpgStop; loopStep = jpgStep; executeLoopType = 2; } else if(revJpgs) { loopStart = revStart; loopStop = revStop; loopStep = revStep; executeLoopType = 3; } // check for too many global inserts or revisions if((executeLoopType == 2) && (loopStop >= git->globalInserts)) { loopStop = git->globalInserts-1; } DiscursiveDebugPrint("Total revs in repo = %d and loopstop = %d\n",git->globalRevs,loopStop); if((executeLoopType == 3) && (loopStop >= git->globalRevs)) { loopStop = git->globalRevs-1; } // loop over a bunch of increasingly large trees for debug or revision tree generation // use our user-set parameters to define our step for(int i = loopStart; i<loopStop;i+= loopStep) { // reset our insert variables if(executeLoopType == 2) { git->localInserts = 0; git->insertTarget = i; } else if(executeLoopType == 3) { git->localRevs = 0; git->revTarget = i; } // retrieve our source tree git->source = git->retrieve(); DiscursivePrint("Decorating surrogate trees %d out of %d step value %d\n",i,loopStop,loopStep); // Decorate surrogate tree nodes with locations SpatialDisplacement* disp = new SpatialDisplacement(imageWidth,imageHeight,widthRescaling,heightRescaling); disp->decorate(git->source); // Digitize decorated surrogate tree into line segment tree DiscursivePrint("Digitizing decorated surrogate trees into line segment trees %d out of %d step value %d\n",i,loopStop,loopStep); SpaceColonizer *digitizer = new SpaceColonizer(1); DrawableData* lines = digitizer->digitize(git->source); // Transform // Draw tree DiscursivePrint("Drawing Tree %d out of %d step value %d",i,loopStop,loopStep); Image canvas(Geometry(imageWidth,imageHeight),"white"); ScanlineArtist artist; artist.draw(canvas, lines); // actually generate a tree DiscursivePrint("Writing Tree %d out of %d step value %d\n",i,loopStop,loopStep); git->WriteJPGFromCanvas(&canvas); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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/browser.h" #include "chrome/browser/profile.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/ui_test_utils.h" namespace { // Theme ID used for testing. const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad"; } // namespace class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest { public: // Checks that a theme info bar is currently visible and issues an undo to // revert to the previous theme. void VerifyThemeInfoBarAndUndoInstall() { TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents); ASSERT_EQ(1, tab_contents->infobar_delegate_count()); ThemeInstalledInfoBarDelegate* delegate = tab_contents-> GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate(); ASSERT_TRUE(delegate); delegate->Cancel(); ASSERT_EQ(0, tab_contents->infobar_delegate_count()); } }; // Flaky, http://crbug.com/43441. IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, FLAKY_TestThemeInstallUndoResetsToDefault) { // Install theme once and undo to verify we go back to default theme. FilePath theme_path = test_data_dir_.AppendASCII("theme.crx"); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1)); Extension* theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, browser()->profile()->GetTheme()); // Set the same theme twice and undo to verify we go back to default theme. // We set the |expected_change| to zero in these 'InstallExtensionWithUI' // calls since the theme has already been installed above and this is an // overinstall to set the active theme. ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0)); theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0)); theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, browser()->profile()->GetTheme()); } <commit_msg>Disable ExtensionInstallUIBrowserTest.TestThemeInstallUndoResetsToDefault because of crashiness.<commit_after>// Copyright (c) 2010 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/browser.h" #include "chrome/browser/profile.h" #include "chrome/browser/extensions/extension_browsertest.h" #include "chrome/browser/extensions/extensions_service.h" #include "chrome/browser/extensions/theme_installed_infobar_delegate.h" #include "chrome/browser/tab_contents/tab_contents.h" #include "chrome/test/ui_test_utils.h" namespace { // Theme ID used for testing. const char* const theme_crx = "iamefpfkojoapidjnbafmgkgncegbkad"; } // namespace class ExtensionInstallUIBrowserTest : public ExtensionBrowserTest { public: // Checks that a theme info bar is currently visible and issues an undo to // revert to the previous theme. void VerifyThemeInfoBarAndUndoInstall() { TabContents* tab_contents = browser()->GetSelectedTabContents(); ASSERT_TRUE(tab_contents); ASSERT_EQ(1, tab_contents->infobar_delegate_count()); ThemeInstalledInfoBarDelegate* delegate = tab_contents-> GetInfoBarDelegateAt(0)->AsThemePreviewInfobarDelegate(); ASSERT_TRUE(delegate); delegate->Cancel(); ASSERT_EQ(0, tab_contents->infobar_delegate_count()); } }; // Flaky, http://crbug.com/43441. // Crashy, http://crbug.com/44548. IN_PROC_BROWSER_TEST_F(ExtensionInstallUIBrowserTest, DISABLED_TestThemeInstallUndoResetsToDefault) { // Install theme once and undo to verify we go back to default theme. FilePath theme_path = test_data_dir_.AppendASCII("theme.crx"); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 1)); Extension* theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, browser()->profile()->GetTheme()); // Set the same theme twice and undo to verify we go back to default theme. // We set the |expected_change| to zero in these 'InstallExtensionWithUI' // calls since the theme has already been installed above and this is an // overinstall to set the active theme. ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0)); theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); ASSERT_TRUE(InstallExtensionWithUI(theme_path, 0)); theme = browser()->profile()->GetTheme(); ASSERT_TRUE(theme); ASSERT_EQ(theme_crx, theme->id()); VerifyThemeInfoBarAndUndoInstall(); ASSERT_EQ(NULL, browser()->profile()->GetTheme()); } <|endoftext|>
<commit_before>/* * simple_tree.cpp * * Created on: Aug 12, 2010 * Author: programmer */ #include <Magick++.h> #include "../model/surrogate_tree_node.h" #include "../io/git_repository_access.h" #include "../io/github_repository_access.h" #include "../io/svn_remote_repository_access.h" #include "../io/cvs_remote_repository_access.h" #include "../dec/spatial_displacement.h" #include "../draw/scanline_artist.h" #include "../gen/space_colonizer.h" #include "../system/discursive_system.h" using namespace Magick; int main(int argc, char **argv) { // Tree image size parameters int WIDTH = 500; int HEIGHT = 500; // Tree Generation pipeline // Retrieve tree from GIT and create surrogate tree // for now, ask the user if local files or github project cout << "\n1==local git\n2==grit git remote Project\n3==any github project"; cout << "\n4==http://hkit.googlecode.com/svn/trunk/\n5==any SVN url"; cout << "\n6==pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd"; cout << "\n7==any CVS url\n"; int answer = 0 * argc; cin >> answer; RepositoryAccess* git; if(answer == 1) { git = new GitRepositoryAccess("~/Projects/source_tree_vis"); } else if(answer == 2) { git = new GitHubRepositoryAccess("mojombo","grit"); } else if(answer == 3) { // allow user to pick github user name/project char userNameBuffer[255]; char projectNameBuffer[255]; cout << "\nEnter the github user name\n"; cin >> userNameBuffer; cout << "\nEnter the github project name\n"; cin >> projectNameBuffer; git = new GitHubRepositoryAccess(userNameBuffer,projectNameBuffer); } else if(answer == 4) { git = new SvnRemoteRepositoryAccess(" http://hkit.googlecode.com/svn/trunk/"); } else if(answer == 5) { char svnRepoBuffer[255]; cout << "\nEnter a SVN url like http://hkit.googlecode.com/svn/trunk/\n"; cin >> svnRepoBuffer; git = new SvnRemoteRepositoryAccess(svnRepoBuffer); } else if(answer == 6) { git = new CvsRemoteRepositoryAccess("pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd"); } else if(answer == 7) { char cvsRepoBuffer[255]; cout << "\nEnter a qualified CVS url like pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n"; cin >> cvsRepoBuffer; git = new CvsRemoteRepositoryAccess(cvsRepoBuffer); } SurrogateTreeNode* source = git->retrieve(); printf("Source tree name is %s\n", source->data["name"].c_str()); // Decorate surrogate tree nodes with locations SpatialDisplacement* disp = new SpatialDisplacement(WIDTH,HEIGHT); disp->decorate(source); // Digitize decorated surrogate tree into line segment tree SpaceColonizer* digitizer = new SpaceColonizer(2); DrawableData* lines = digitizer->digitize(source); // Transform // Draw tree InitializeMagick(*argv); Image canvas(Geometry(WIDTH,HEIGHT),"white"); ScanlineArtist* artist = new ScanlineArtist(); artist->draw(canvas, lines); try { // Write the image to a file canvas.write( "out/tree.jpg" ); } catch( Exception &error_ ) { DiscursiveError(error_.what()); } return 0; } <commit_msg>updated call to set debug level<commit_after>/* * simple_tree.cpp * * Created on: Aug 12, 2010 * Author: programmer */ #include <Magick++.h> #include "../model/surrogate_tree_node.h" #include "../io/git_repository_access.h" #include "../io/github_repository_access.h" #include "../io/svn_remote_repository_access.h" #include "../io/cvs_remote_repository_access.h" #include "../dec/spatial_displacement.h" #include "../draw/scanline_artist.h" #include "../gen/space_colonizer.h" #include "../system/discursive_system.h" using namespace Magick; int main(int argc, char **argv) { // set the debug level SetDiscursiveDebugLevel(1); // Tree image size parameters int WIDTH = 500; int HEIGHT = 500; // Tree Generation pipeline // Retrieve tree from GIT and create surrogate tree // for now, ask the user if local files or github project cout << "\n1==local git\n2==grit git remote Project\n3==any github project"; cout << "\n4==http://hkit.googlecode.com/svn/trunk/\n5==any SVN url"; cout << "\n6==pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd"; cout << "\n7==any CVS url\n"; int answer = 0 * argc; cin >> answer; RepositoryAccess* git; if(answer == 1) { git = new GitRepositoryAccess("~/Projects/source_tree_vis"); } else if(answer == 2) { git = new GitHubRepositoryAccess("mojombo","grit"); } else if(answer == 3) { // allow user to pick github user name/project char userNameBuffer[255]; char projectNameBuffer[255]; cout << "\nEnter the github user name\n"; cin >> userNameBuffer; cout << "\nEnter the github project name\n"; cin >> projectNameBuffer; git = new GitHubRepositoryAccess(userNameBuffer,projectNameBuffer); } else if(answer == 4) { git = new SvnRemoteRepositoryAccess(" http://hkit.googlecode.com/svn/trunk/"); } else if(answer == 5) { char svnRepoBuffer[255]; cout << "\nEnter a SVN url like http://hkit.googlecode.com/svn/trunk/\n"; cin >> svnRepoBuffer; git = new SvnRemoteRepositoryAccess(svnRepoBuffer); } else if(answer == 6) { git = new CvsRemoteRepositoryAccess("pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd"); } else if(answer == 7) { char cvsRepoBuffer[255]; cout << "\nEnter a qualified CVS url like pserver:anonymous@bnetd.cvs.sourceforge.net:/cvsroot/bnetd\n"; cin >> cvsRepoBuffer; git = new CvsRemoteRepositoryAccess(cvsRepoBuffer); } SurrogateTreeNode* source = git->retrieve(); printf("Source tree name is %s\n", source->data["name"].c_str()); // Decorate surrogate tree nodes with locations SpatialDisplacement* disp = new SpatialDisplacement(WIDTH,HEIGHT); disp->decorate(source); // Digitize decorated surrogate tree into line segment tree SpaceColonizer* digitizer = new SpaceColonizer(2); DrawableData* lines = digitizer->digitize(source); // Transform // Draw tree InitializeMagick(*argv); Image canvas(Geometry(WIDTH,HEIGHT),"white"); ScanlineArtist* artist = new ScanlineArtist(); artist->draw(canvas, lines); try { // Write the image to a file canvas.write( "out/tree.jpg" ); } catch( Exception &error_ ) { DiscursiveError(error_.what()); } return 0; } <|endoftext|>
<commit_before>// Copyright (c) 2010 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/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" IN_PROC_BROWSER_TEST_F(ExtensionApiTest, JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; } <commit_msg>Disable ExtensionApiTest.JavaScriptURLPermissions, it flakily hits an assertion.<commit_after>// Copyright (c) 2010 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/extensions/extension_apitest.h" #include "net/base/mock_host_resolver.h" // Disabled, http://crbug.com/63589. IN_PROC_BROWSER_TEST_F(ExtensionApiTest, DISABLED_JavaScriptURLPermissions) { host_resolver()->AddRule("a.com", "127.0.0.1"); host_resolver()->AddRule("b.com", "127.0.0.1"); ASSERT_TRUE(StartTestServer()); ASSERT_TRUE(RunExtensionTest("tabs/javascript_url_permissions")) << message_; } <|endoftext|>
<commit_before>// Copyright (c) 2009 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/views/extensions/extension_installed_bubble.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/location_bar_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/image_button.h" #include "views/controls/label.h" #include "views/standard_layout.h" #include "views/view.h" namespace { const int kIconSize = 43; const int kRightColumnWidth = 285; // The InfoBubble uses a BubbleBorder which adds about 6 pixels of whitespace // around the content view. We compensate by reducing our outer borders by this // amount. const int kBubbleBorderInsert = 6; const int kHorizOuterMargin = kPanelHorizMargin - kBubbleBorderInsert; const int kVertOuterMargin = kPanelVertMargin - kBubbleBorderInsert; // The image we use for the close button has three pixels of whitespace padding. const int kCloseButtonPadding = 3; // InstalledBubbleContent is the content view which is placed in the // ExtensionInstalledBubble. It displays the install icon and explanatory // text about the installed extension. class InstalledBubbleContent : public views::View, public views::ButtonListener { public: InstalledBubbleContent(Extension* extension, ExtensionInstalledBubble::BubbleType type, SkBitmap* icon) : type_(type), info_(NULL) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont); // Scale down to 43x43, but allow smaller icons (don't scale up). gfx::Size size(icon->width(), icon->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); icon_ = new views::ImageView(); icon_->SetImageSize(size); icon_->SetImage(*icon); AddChildView(icon_); heading_ = new views::Label( l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING, UTF8ToWide(extension->name()))); heading_->SetFont(font.DeriveFont(3, gfx::Font::NORMAL)); heading_->SetMultiLine(true); heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(heading_); if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { info_ = new views::Label(l10n_util::GetString( IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO)); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); } manage_ = new views::Label(l10n_util::GetString( IDS_EXTENSION_INSTALLED_MANAGE_INFO)); manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetBitmapNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetBitmapNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetBitmapNamed(IDR_CLOSE_BAR_P)); AddChildView(close_button_); } virtual void ButtonPressed( views::Button* sender, const views::Event& event) { GetWidget()->Close(); } private: virtual gfx::Size GetPreferredSize() { int width = kRightColumnWidth + kHorizOuterMargin + kHorizOuterMargin; width += kIconSize; width += kPanelHorizMargin; width += close_button_->GetPreferredSize().width(); width -= 2 * kCloseButtonPadding; width += kPanelHorizMargin; int height = kVertOuterMargin * 2; height += heading_->GetHeightForWidth(kRightColumnWidth); height += kPanelVertMargin; if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { height += info_->GetHeightForWidth(kRightColumnWidth); height += kPanelVertMargin; } height += manage_->GetHeightForWidth(kRightColumnWidth); return gfx::Size(width, std::max(height, kIconSize + kVertOuterMargin * 2)); } virtual void Layout() { int x = kHorizOuterMargin; int y = kVertOuterMargin; icon_->SetBounds(x, y, kIconSize, kIconSize); x += kIconSize; x += kPanelHorizMargin; heading_->SizeToFit(kRightColumnWidth); heading_->SetX(x); heading_->SetY(y); y += heading_->height(); y += kPanelVertMargin; if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { info_->SizeToFit(kRightColumnWidth); info_->SetX(x); info_->SetY(y); y += info_->height(); y += kPanelVertMargin; } manage_->SizeToFit(kRightColumnWidth); manage_->SetX(x); manage_->SetY(y); x += kRightColumnWidth + kPanelHorizMargin; y = kVertOuterMargin; gfx::Size sz = close_button_->GetPreferredSize(); close_button_->SetBounds(x - kCloseButtonPadding, y - kCloseButtonPadding, sz.width(), sz.height()); } ExtensionInstalledBubble::BubbleType type_; views::ImageView* icon_; views::Label* heading_; views::Label* info_; views::Label* manage_; views::ImageButton* close_button_; DISALLOW_COPY_AND_ASSIGN(InstalledBubbleContent); }; } // namespace void ExtensionInstalledBubble::Show(Extension *extension, Browser *browser, SkBitmap icon) { new ExtensionInstalledBubble(extension, browser, icon); } ExtensionInstalledBubble::ExtensionInstalledBubble(Extension *extension, Browser *browser, SkBitmap icon) : extension_(extension), browser_(browser), icon_(icon) { AddRef(); // Balanced in InfoBubbleClosing. if (extension_->browser_action()) { type_ = BROWSER_ACTION; } else if (extension->page_action() && !extension->page_action()->default_icon_path().empty()) { type_ = PAGE_ACTION; } else { type_ = GENERIC; } // |extension| has been initialized but not loaded at this point. We need // to wait on showing the Bubble until not only the EXTENSION_LOADED gets // fired, but all of the EXTENSION_LOADED Observers have run. Only then can we // be sure that a BrowserAction or PageAction has had views created which we // can inspect for the purpose of previewing of pointing to them. registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); } void ExtensionInstalledBubble::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::EXTENSION_LOADED) { Extension* extension = Details<Extension>(details).ptr(); if (extension == extension_) { // PostTask to ourself to allow all EXTENSION_LOADED Observers to run. MessageLoopForUI::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &ExtensionInstalledBubble::ShowInternal)); } } else { NOTREACHED() << L"Received unexpected notification"; } } void ExtensionInstalledBubble::ShowInternal() { BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow( browser_->window()->GetNativeHandle()); views::View* reference_view = NULL; if (type_ == BROWSER_ACTION) { reference_view = browser_view->GetToolbarView()->browser_actions() ->GetBrowserActionView(extension_); DCHECK(reference_view); } else if (type_ == PAGE_ACTION) { LocationBarView* location_bar_view = browser_view->GetLocationBarView(); location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(), true); // preview_enabled reference_view = location_bar_view->GetPageActionView( extension_->page_action()); DCHECK(reference_view); } // Default case. if (reference_view == NULL) reference_view = browser_view->GetToolbarView()->app_menu(); gfx::Point origin; views::View::ConvertPointToScreen(reference_view, &origin); gfx::Rect bounds = reference_view->bounds(); bounds.set_x(origin.x()); bounds.set_y(origin.y()); views::View* bubble_content = new InstalledBubbleContent(extension_, type_, &icon_); InfoBubble::Show(browser_view->GetWindow(), bounds, bubble_content, this); } // InfoBubbleDelegate void ExtensionInstalledBubble::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { if (extension_->page_action()) { BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow( browser_->window()->GetNativeHandle()); browser_view->GetLocationBarView()->SetPreviewEnabledPageAction( extension_->page_action(), false); // preview_enabled } Release(); // Balanced in ctor. } <commit_msg>ExtensionInstalledBubble border/sizing polish<commit_after>// Copyright (c) 2009 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/views/extensions/extension_installed_bubble.h" #include "app/l10n_util.h" #include "app/resource_bundle.h" #include "base/message_loop.h" #include "chrome/browser/browser.h" #include "chrome/browser/browser_window.h" #include "chrome/browser/views/browser_actions_container.h" #include "chrome/browser/views/frame/browser_view.h" #include "chrome/browser/views/location_bar_view.h" #include "chrome/browser/views/toolbar_view.h" #include "chrome/common/notification_service.h" #include "chrome/common/notification_type.h" #include "grit/generated_resources.h" #include "grit/theme_resources.h" #include "views/controls/button/image_button.h" #include "views/controls/label.h" #include "views/standard_layout.h" #include "views/view.h" namespace { const int kIconSize = 43; const int kRightColumnWidth = 285; // The InfoBubble uses a BubbleBorder which adds about 6 pixels of whitespace // around the content view. We compensate by reducing our outer borders by this // amount + 4px. const int kOuterMarginInset = 10; const int kHorizOuterMargin = kPanelHorizMargin - kOuterMarginInset; const int kVertOuterMargin = kPanelVertMargin - kOuterMarginInset; // Interior vertical margin is 8px smaller than standard const int kVertInnerMargin = kPanelVertMargin - 8; // The image we use for the close button has three pixels of whitespace padding. const int kCloseButtonPadding = 3; // We want to shift the right column (which contains the header and text) up // 4px to align with icon. const int kRightcolumnVerticalShift = -4; // InstalledBubbleContent is the content view which is placed in the // ExtensionInstalledBubble. It displays the install icon and explanatory // text about the installed extension. class InstalledBubbleContent : public views::View, public views::ButtonListener { public: InstalledBubbleContent(Extension* extension, ExtensionInstalledBubble::BubbleType type, SkBitmap* icon) : type_(type), info_(NULL) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); const gfx::Font& font = rb.GetFont(ResourceBundle::BaseFont); // Scale down to 43x43, but allow smaller icons (don't scale up). gfx::Size size(icon->width(), icon->height()); if (size.width() > kIconSize || size.height() > kIconSize) size = gfx::Size(kIconSize, kIconSize); icon_ = new views::ImageView(); icon_->SetImageSize(size); icon_->SetImage(*icon); AddChildView(icon_); heading_ = new views::Label( l10n_util::GetStringF(IDS_EXTENSION_INSTALLED_HEADING, UTF8ToWide(extension->name()))); heading_->SetFont(font.DeriveFont(3, gfx::Font::NORMAL)); heading_->SetMultiLine(true); heading_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(heading_); if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { info_ = new views::Label(l10n_util::GetString( IDS_EXTENSION_INSTALLED_PAGE_ACTION_INFO)); info_->SetFont(font); info_->SetMultiLine(true); info_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(info_); } manage_ = new views::Label(l10n_util::GetString( IDS_EXTENSION_INSTALLED_MANAGE_INFO)); manage_->SetFont(font); manage_->SetMultiLine(true); manage_->SetHorizontalAlignment(views::Label::ALIGN_LEFT); AddChildView(manage_); close_button_ = new views::ImageButton(this); close_button_->SetImage(views::CustomButton::BS_NORMAL, rb.GetBitmapNamed(IDR_CLOSE_BAR)); close_button_->SetImage(views::CustomButton::BS_HOT, rb.GetBitmapNamed(IDR_CLOSE_BAR_H)); close_button_->SetImage(views::CustomButton::BS_PUSHED, rb.GetBitmapNamed(IDR_CLOSE_BAR_P)); AddChildView(close_button_); } virtual void ButtonPressed( views::Button* sender, const views::Event& event) { GetWidget()->Close(); } private: virtual gfx::Size GetPreferredSize() { int width = kHorizOuterMargin; width += kIconSize; width += kPanelHorizMargin; width += kRightColumnWidth; width += 2*kPanelHorizMargin; width += kHorizOuterMargin; int height = kVertOuterMargin; height += heading_->GetHeightForWidth(kRightColumnWidth); height += kVertInnerMargin; if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { height += info_->GetHeightForWidth(kRightColumnWidth); height += kVertInnerMargin; } height += manage_->GetHeightForWidth(kRightColumnWidth); height += kVertOuterMargin; return gfx::Size(width, std::max(height, kIconSize + 2 * kVertOuterMargin)); } virtual void Layout() { int x = kHorizOuterMargin; int y = kVertOuterMargin; icon_->SetBounds(x, y, kIconSize, kIconSize); x += kIconSize; x += kPanelHorizMargin; y += kRightcolumnVerticalShift; heading_->SizeToFit(kRightColumnWidth); heading_->SetX(x); heading_->SetY(y); y += heading_->height(); y += kVertInnerMargin; if (type_ == ExtensionInstalledBubble::PAGE_ACTION) { info_->SizeToFit(kRightColumnWidth); info_->SetX(x); info_->SetY(y); y += info_->height(); y += kVertInnerMargin; } manage_->SizeToFit(kRightColumnWidth); manage_->SetX(x); manage_->SetY(y); x += kRightColumnWidth + 2*kPanelHorizMargin + kHorizOuterMargin - close_button_->GetPreferredSize().width(); y = kVertOuterMargin; gfx::Size sz = close_button_->GetPreferredSize(); // x-1 & y-1 is just slop to get the close button visually aligned with the // title text and bubble arrow. close_button_->SetBounds(x - 1, y - 1, sz.width(), sz.height()); } ExtensionInstalledBubble::BubbleType type_; views::ImageView* icon_; views::Label* heading_; views::Label* info_; views::Label* manage_; views::ImageButton* close_button_; DISALLOW_COPY_AND_ASSIGN(InstalledBubbleContent); }; } // namespace void ExtensionInstalledBubble::Show(Extension *extension, Browser *browser, SkBitmap icon) { new ExtensionInstalledBubble(extension, browser, icon); } ExtensionInstalledBubble::ExtensionInstalledBubble(Extension *extension, Browser *browser, SkBitmap icon) : extension_(extension), browser_(browser), icon_(icon) { AddRef(); // Balanced in InfoBubbleClosing. if (extension_->browser_action()) { type_ = BROWSER_ACTION; } else if (extension->page_action() && !extension->page_action()->default_icon_path().empty()) { type_ = PAGE_ACTION; } else { type_ = GENERIC; } // |extension| has been initialized but not loaded at this point. We need // to wait on showing the Bubble until not only the EXTENSION_LOADED gets // fired, but all of the EXTENSION_LOADED Observers have run. Only then can we // be sure that a BrowserAction or PageAction has had views created which we // can inspect for the purpose of previewing of pointing to them. registrar_.Add(this, NotificationType::EXTENSION_LOADED, NotificationService::AllSources()); } void ExtensionInstalledBubble::Observe(NotificationType type, const NotificationSource& source, const NotificationDetails& details) { if (type == NotificationType::EXTENSION_LOADED) { Extension* extension = Details<Extension>(details).ptr(); if (extension == extension_) { // PostTask to ourself to allow all EXTENSION_LOADED Observers to run. MessageLoopForUI::current()->PostTask(FROM_HERE, NewRunnableMethod(this, &ExtensionInstalledBubble::ShowInternal)); } } else { NOTREACHED() << L"Received unexpected notification"; } } void ExtensionInstalledBubble::ShowInternal() { BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow( browser_->window()->GetNativeHandle()); views::View* reference_view = NULL; if (type_ == BROWSER_ACTION) { reference_view = browser_view->GetToolbarView()->browser_actions() ->GetBrowserActionView(extension_); DCHECK(reference_view); } else if (type_ == PAGE_ACTION) { LocationBarView* location_bar_view = browser_view->GetLocationBarView(); location_bar_view->SetPreviewEnabledPageAction(extension_->page_action(), true); // preview_enabled reference_view = location_bar_view->GetPageActionView( extension_->page_action()); DCHECK(reference_view); } // Default case. if (reference_view == NULL) reference_view = browser_view->GetToolbarView()->app_menu(); gfx::Point origin; views::View::ConvertPointToScreen(reference_view, &origin); gfx::Rect bounds = reference_view->bounds(); bounds.set_x(origin.x()); bounds.set_y(origin.y()); views::View* bubble_content = new InstalledBubbleContent(extension_, type_, &icon_); InfoBubble::Show(browser_view->GetWindow(), bounds, bubble_content, this); } // InfoBubbleDelegate void ExtensionInstalledBubble::InfoBubbleClosing(InfoBubble* info_bubble, bool closed_by_escape) { if (extension_->page_action()) { BrowserView* browser_view = BrowserView::GetBrowserViewForNativeWindow( browser_->window()->GetNativeHandle()); browser_view->GetLocationBarView()->SetPreviewEnabledPageAction( extension_->page_action(), false); // preview_enabled } Release(); // Balanced in ctor. } <|endoftext|>
<commit_before>/* * CityRegionImplementation.cpp * * Created on: Feb 9, 2012 * Author: xyborn */ #include "CityRegion.h" #include "events/CityUpdateEvent.h" #include "server/chat/StringIdChatParameter.h" #include "server/ServerCore.h" #include "server/zone/managers/city/CityManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/planet/PlanetTravelPoint.h" #include "server/zone/managers/stringid/StringIdManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/commands/BoardShuttleCommand.h" #include "server/zone/objects/creature/commands/QueueCommand.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/region/Region.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/objects/tangible/components/vendor/AuctionTerminalDataComponent.h" #include "server/zone/templates/tangible/SharedStructureObjectTemplate.h" #include "server/zone/Zone.h" int BoardShuttleCommand::MAXIMUM_PLAYER_COUNT = 3000; void CityRegionImplementation::initializeTransientMembers() { ManagedObjectImplementation::initializeTransientMembers(); loaded = false; } void CityRegionImplementation::notifyLoadFromDatabase() { ManagedObjectImplementation::notifyLoadFromDatabase(); if (cityRank == CityManager::CLIENT) return; //if (zone !=) Zone* zone = getZone(); if (zone == NULL) return; zone->addCityRegionToUpdate(_this.get()); if (isRegistered()) zone->getPlanetManager()->addRegion(_this.get()); //Add taxes if they dont exist. if (taxes.size() <= 0) { info("Adding taxes for existing city that had no taxes.", true); taxes.add(0); taxes.add(0); taxes.add(0); taxes.add(0); taxes.add(0); } /* int seconds = -1 * round(nextUpdateTime.miliDifference() / 1000.f); if (seconds < 0) //If the update occurred in the past, force an immediate update. seconds = 0; rescheduleUpdateEvent(seconds); */ if (hasShuttle){ CreatureObject* shuttle = cast<CreatureObject*>( zone->getZoneServer()->getObject(shuttleID, false)); if (shuttle == NULL) { hasShuttle = false; shuttleID = 0; return; } float x = shuttle->getWorldPositionX(); float y = shuttle->getWorldPositionY(); float z = shuttle->getWorldPositionZ(); Vector3 arrivalVector(x, y, z); PlanetTravelPoint* planetTravelPoint = new PlanetTravelPoint(zone->getZoneName(), getRegionName(), arrivalVector, arrivalVector, shuttle); zone->getPlanetManager()->addPlayerCityTravelPoint(planetTravelPoint); if (shuttle != NULL) zone->getPlanetManager()->scheduleShuttle(shuttle); } } void CityRegionImplementation::initialize() { zoningEnabled = true; registered = false; cityTreasury = 0; cityRank = RANK_CLIENT; //Default to client city cityHall = NULL; mayorID = 0; shuttleID = 0; hasShuttle = false; zone = NULL; cityUpdateEvent = NULL; zoningRights.setAllowOverwriteInsertPlan(); zoningRights.setNullValue(0); cityMissionTerminals.setNoDuplicateInsertPlan(); cityDecorations.setNoDuplicateInsertPlan(); citySkillTrainers.setNoDuplicateInsertPlan(); bazaars.setNoDuplicateInsertPlan(); bazaars.setNullValue(NULL); setLoggingName("CityRegion"); setLogging(true); } Region* CityRegionImplementation::addRegion(float x, float y, float radius, bool persistent) { if (zone == NULL) { return NULL; } String temp = "object/region_area.iff"; ManagedReference<SceneObject*> obj = zone->getZoneServer()->createObject(temp.hashCode(), persistent ? 1 : 0); if (obj == NULL || !obj->isRegion()) { return NULL; } ManagedReference<Region*> region = cast<Region*>(obj.get()); region->setCityRegion(_this.get()); region->setRadius(radius); region->initializePosition(x, 0, y); region->setObjectName(regionName); if (isClientRegion()) region->setNoBuildArea(true); zone->transferObject(region, -1, false); regions.put(region); return region; } void CityRegionImplementation::rescheduleUpdateEvent(uint32 seconds) { if (cityRank == CityManager::CLIENT) return; if (cityUpdateEvent == NULL) { cityUpdateEvent = new CityUpdateEvent(_this.get(), ServerCore::getZoneServer()); } else if (cityUpdateEvent->isScheduled()) { cityUpdateEvent->cancel(); } cityUpdateEvent->schedule(seconds * 1000); Core::getTaskManager()->getNextExecutionTime(cityUpdateEvent, nextUpdateTime); } int CityRegionImplementation::getTimeToUpdate() { return round(nextUpdateTime.miliDifference() / -1000.f); } void CityRegionImplementation::notifyEnter(SceneObject* object) { object->setCityRegion(_this.get()); if (object->isBazaarTerminal() || object->isVendor()) { if (object->isBazaarTerminal()) bazaars.put(object->getObjectID(), cast<TangibleObject*>(object)); AuctionTerminalDataComponent* terminalData = NULL; DataObjectComponentReference* data = object->getDataObjectComponent(); if(data != NULL && data->get() != NULL && data->get()->isAuctionTerminalData()) terminalData = cast<AuctionTerminalDataComponent*>(data->get()); if(terminalData != NULL) terminalData->updateUID(); } if (object->isPlayerCreature()) currentPlayers.increment(); if (isClientRegion()) return; if (object->isCreatureObject()){ CreatureObject* creature = cast<CreatureObject*>(object); StringIdChatParameter params("city/city", "city_enter_city"); //You have entered %TT (%TO). params.setTT(getRegionName()); UnicodeString strRank = StringIdManager::instance()->getStringId(String("@city/city:rank" + String::valueOf(cityRank)).hashCode()); if (citySpecialization.isEmpty()) { params.setTO(strRank); } else { UnicodeString citySpec = StringIdManager::instance()->getStringId(citySpecialization.hashCode()); params.setTO(strRank + ", " + citySpec); } creature->sendSystemMessage(params); applySpecializationModifiers(creature); } if (object->isStructureObject()){ StructureObject* structure = cast<StructureObject*>(object); /*uint64 creatureID = structure->getOwnerObjectID(); if (structure->isBuildingObject() && !citizenList.contains(creatureID)) { BuildingObject* building = cast<BuildingObject*>(object); CreatureObject* owner = building->getOwnerCreatureObject(); if (owner != NULL) { PlayerObject* playerObject = owner->getPlayerObject(); if (playerObject != NULL && playerObject->getDeclaredResidence() == building) { addCitizen(creatureID); } } }*/ if (structure->isCivicStructure()) addStructure(structure); } } void CityRegionImplementation::notifyExit(SceneObject* object) { //pre: no 2 different city regions should ever overlap, only 2 Regions of the same city region ManagedReference<Region*> activeRegion = cast<Region*>(object->getActiveRegion()); if (activeRegion != NULL) { ManagedReference<CityRegion*> city = activeRegion->getCityRegion(); object->setCityRegion(city); if (city == _this.get()) // if its the same city we wait till the object exits the last region return; } else { object->setCityRegion(NULL); } if (object->isBazaarTerminal() || object->isVendor()) { if (object->isBazaarTerminal()) bazaars.drop(object->getObjectID()); AuctionTerminalDataComponent* terminalData = NULL; DataObjectComponentReference* data = object->getDataObjectComponent(); if(data != NULL && data->get() != NULL && data->get()->isAuctionTerminalData()) terminalData = cast<AuctionTerminalDataComponent*>(data->get()); if(terminalData != NULL) terminalData->updateUID(); } if (object->isPlayerCreature()) currentPlayers.decrement(); if (isClientRegion()) return; if (object->isCreatureObject()){ CreatureObject* creature = cast<CreatureObject*>(object); StringIdChatParameter params("city/city", "city_leave_city"); //You have left %TO. params.setTO(getRegionName()); creature->sendSystemMessage(params); removeSpecializationModifiers(creature); } if (object->isStructureObject()) { float x = object->getWorldPositionX(); float y = object->getWorldPositionY(); //StructureObject* structure = cast<StructureObject*>(object); StructureObject* structure = cast<StructureObject*>(object); /*uint64 creatureID = structure->getOwnerObjectID(); if (structure->isBuildingObject() && citizenList.contains(creatureID)) { BuildingObject* building = cast<BuildingObject*>(object); CreatureObject* owner = building->getOwnerCreatureObject(); if (owner != NULL) { PlayerObject* playerObject = owner->getPlayerObject(); if (playerObject != NULL && playerObject->getDeclaredResidence() == building){ removeCitizen(creatureID); } } }*/ if (structure->isCivicStructure()) removeStructure(structure); } } void CityRegionImplementation::setRegionName(const StringId& name) { regionName = name; } Vector<ManagedReference<TangibleObject*> >* CityRegionImplementation::getVendorsInCity() { Vector<ManagedReference<TangibleObject*> >* vendors = new Vector<ManagedReference<TangibleObject*> >(); return vendors; } void CityRegionImplementation::addZoningRights(uint64 objectid, uint32 duration) { Time now; zoningRights.put(objectid, duration + now.getTime()); } bool CityRegionImplementation::hasZoningRights(uint64 objectid) { if (isMilitiaMember(objectid)) return true; uint32 timestamp = zoningRights.get(objectid); if (timestamp == 0) return false; Time now; return (now.getTime() <= timestamp); } void CityRegionImplementation::setZone(Zone* zne) { zone = zne; } void CityRegionImplementation::setRadius(float rad) { if (regions.size() <= 0) return; ManagedReference<ActiveArea*> aa = regions.get(0).get(); aa->setRadius(rad); zone->removeObject(aa, NULL, false); zone->transferObject(aa, -1, false); } void CityRegionImplementation::destroyActiveAreas() { for (int i = 0; i < regions.size(); ++i) { ManagedReference<Region*> aa = regions.get(i); if (aa != NULL) { aa->destroyObjectFromWorld(false); aa->destroyObjectFromDatabase(true); regions.drop(aa); } } } String CityRegionImplementation::getRegionName() { if(!customRegionName.isEmpty()) return customRegionName; return regionName.getFullPath(); } bool CityRegionImplementation::hasUniqueStructure(uint32 crc){ Locker locker(_this.get()); for (int i = 0; i < structures.size(); ++i) { ManagedReference<StructureObject*> structure = structures.get(i); if (structure->getObjectTemplate()->getServerObjectCRC() == crc) return true; } return false; } void CityRegionImplementation::destroyAllStructuresForRank(uint8 rank){ Locker locker(_this.get()); if (zone == NULL) return; StructureManager* structureManager = StructureManager::instance(); for (int i = structures.size(); i >= 0; --i) { ManagedReference<StructureObject*> structure = structures.get(i); SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(structure->getObjectTemplate()); //We only want to destroy civic structures. if (ssot == NULL || ssot->getCityRankRequired() < rank || !ssot->isCivicStructure()) continue; Locker _clocker(structure, _this.get()); structureManager->destroyStructure(structure); structures.drop(structure); } } void CityRegionImplementation::updateMilitia(){ Locker locker (_this.get()); uint64 objectID; for (int i = militiaMembers.size() - 1;i >= 0; --i){ objectID = militiaMembers.get(i); if (!isCitizen(objectID)) removeMilitiaMember(objectID); } } void CityRegionImplementation::removeAllTerminals(){ for (int i = 0; i < cityMissionTerminals.size(); i++){ cityMissionTerminals.get(i)->destroyObjectFromWorld(false); cityMissionTerminals.get(i)->destroyObjectFromDatabase(false); } cityMissionTerminals.removeAll(); } void CityRegionImplementation::removeAllSkillTrainers(){ for (int i = 0; i < citySkillTrainers.size(); i++){ citySkillTrainers.get(i)->destroyObjectFromWorld(false); citySkillTrainers.get(i)->destroyObjectFromDatabase(false); } citySkillTrainers.removeAll(); } void CityRegionImplementation::resetVotingPeriod() { nextInauguration.updateToCurrentTime(); nextInauguration.addMiliTime(CityManagerImplementation::cityVotingDuration * 60000); } void CityRegionImplementation::applySpecializationModifiers(CreatureObject* creature) { if (getZone() == NULL) return; CityManager* cityManager = getZone()->getZoneServer()->getCityManager(); CitySpecialization* cityspec = cityManager->getCitySpecialization(citySpecialization); if (cityspec == NULL) return; //Remove all current city skillmods creature->removeAllSkillModsOfType(SkillModManager::CITY); VectorMap<String, int>* mods = cityspec->getSkillMods(); for (int i = 0; i < mods->size(); ++i) { VectorMapEntry<String, int> entry = mods->elementAt(i); creature->addSkillMod(SkillModManager::CITY, entry.getKey(), entry.getValue()); } } void CityRegionImplementation::removeSpecializationModifiers(CreatureObject* creature) { creature->removeAllSkillModsOfType(SkillModManager::CITY); } <commit_msg>(unstable) [fixed] issue destroying city hall and city<commit_after>/* * CityRegionImplementation.cpp * * Created on: Feb 9, 2012 * Author: xyborn */ #include "CityRegion.h" #include "events/CityUpdateEvent.h" #include "server/chat/StringIdChatParameter.h" #include "server/ServerCore.h" #include "server/zone/managers/city/CityManager.h" #include "server/zone/managers/planet/PlanetManager.h" #include "server/zone/managers/planet/PlanetTravelPoint.h" #include "server/zone/managers/stringid/StringIdManager.h" #include "server/zone/managers/structure/StructureManager.h" #include "server/zone/objects/area/ActiveArea.h" #include "server/zone/objects/building/BuildingObject.h" #include "server/zone/objects/creature/commands/BoardShuttleCommand.h" #include "server/zone/objects/creature/commands/QueueCommand.h" #include "server/zone/objects/creature/CreatureObject.h" #include "server/zone/objects/player/PlayerObject.h" #include "server/zone/objects/region/Region.h" #include "server/zone/objects/scene/SceneObject.h" #include "server/zone/objects/structure/StructureObject.h" #include "server/zone/objects/tangible/components/vendor/AuctionTerminalDataComponent.h" #include "server/zone/templates/tangible/SharedStructureObjectTemplate.h" #include "server/zone/Zone.h" int BoardShuttleCommand::MAXIMUM_PLAYER_COUNT = 3000; void CityRegionImplementation::initializeTransientMembers() { ManagedObjectImplementation::initializeTransientMembers(); loaded = false; } void CityRegionImplementation::notifyLoadFromDatabase() { ManagedObjectImplementation::notifyLoadFromDatabase(); if (cityRank == CityManager::CLIENT) return; //if (zone !=) Zone* zone = getZone(); if (zone == NULL) return; zone->addCityRegionToUpdate(_this.get()); if (isRegistered()) zone->getPlanetManager()->addRegion(_this.get()); //Add taxes if they dont exist. if (taxes.size() <= 0) { info("Adding taxes for existing city that had no taxes.", true); taxes.add(0); taxes.add(0); taxes.add(0); taxes.add(0); taxes.add(0); } /* int seconds = -1 * round(nextUpdateTime.miliDifference() / 1000.f); if (seconds < 0) //If the update occurred in the past, force an immediate update. seconds = 0; rescheduleUpdateEvent(seconds); */ if (hasShuttle){ CreatureObject* shuttle = cast<CreatureObject*>( zone->getZoneServer()->getObject(shuttleID, false)); if (shuttle == NULL) { hasShuttle = false; shuttleID = 0; return; } float x = shuttle->getWorldPositionX(); float y = shuttle->getWorldPositionY(); float z = shuttle->getWorldPositionZ(); Vector3 arrivalVector(x, y, z); PlanetTravelPoint* planetTravelPoint = new PlanetTravelPoint(zone->getZoneName(), getRegionName(), arrivalVector, arrivalVector, shuttle); zone->getPlanetManager()->addPlayerCityTravelPoint(planetTravelPoint); if (shuttle != NULL) zone->getPlanetManager()->scheduleShuttle(shuttle); } } void CityRegionImplementation::initialize() { zoningEnabled = true; registered = false; cityTreasury = 0; cityRank = RANK_CLIENT; //Default to client city cityHall = NULL; mayorID = 0; shuttleID = 0; hasShuttle = false; zone = NULL; cityUpdateEvent = NULL; zoningRights.setAllowOverwriteInsertPlan(); zoningRights.setNullValue(0); cityMissionTerminals.setNoDuplicateInsertPlan(); cityDecorations.setNoDuplicateInsertPlan(); citySkillTrainers.setNoDuplicateInsertPlan(); bazaars.setNoDuplicateInsertPlan(); bazaars.setNullValue(NULL); setLoggingName("CityRegion"); setLogging(true); } Region* CityRegionImplementation::addRegion(float x, float y, float radius, bool persistent) { if (zone == NULL) { return NULL; } String temp = "object/region_area.iff"; ManagedReference<SceneObject*> obj = zone->getZoneServer()->createObject(temp.hashCode(), persistent ? 1 : 0); if (obj == NULL || !obj->isRegion()) { return NULL; } ManagedReference<Region*> region = cast<Region*>(obj.get()); region->setCityRegion(_this.get()); region->setRadius(radius); region->initializePosition(x, 0, y); region->setObjectName(regionName); if (isClientRegion()) region->setNoBuildArea(true); zone->transferObject(region, -1, false); regions.put(region); return region; } void CityRegionImplementation::rescheduleUpdateEvent(uint32 seconds) { if (cityRank == CityManager::CLIENT) return; if (cityUpdateEvent == NULL) { cityUpdateEvent = new CityUpdateEvent(_this.get(), ServerCore::getZoneServer()); } else if (cityUpdateEvent->isScheduled()) { cityUpdateEvent->cancel(); } cityUpdateEvent->schedule(seconds * 1000); Core::getTaskManager()->getNextExecutionTime(cityUpdateEvent, nextUpdateTime); } int CityRegionImplementation::getTimeToUpdate() { return round(nextUpdateTime.miliDifference() / -1000.f); } void CityRegionImplementation::notifyEnter(SceneObject* object) { object->setCityRegion(_this.get()); if (object->isBazaarTerminal() || object->isVendor()) { if (object->isBazaarTerminal()) bazaars.put(object->getObjectID(), cast<TangibleObject*>(object)); AuctionTerminalDataComponent* terminalData = NULL; DataObjectComponentReference* data = object->getDataObjectComponent(); if(data != NULL && data->get() != NULL && data->get()->isAuctionTerminalData()) terminalData = cast<AuctionTerminalDataComponent*>(data->get()); if(terminalData != NULL) terminalData->updateUID(); } if (object->isPlayerCreature()) currentPlayers.increment(); if (isClientRegion()) return; if (object->isCreatureObject()){ CreatureObject* creature = cast<CreatureObject*>(object); StringIdChatParameter params("city/city", "city_enter_city"); //You have entered %TT (%TO). params.setTT(getRegionName()); UnicodeString strRank = StringIdManager::instance()->getStringId(String("@city/city:rank" + String::valueOf(cityRank)).hashCode()); if (citySpecialization.isEmpty()) { params.setTO(strRank); } else { UnicodeString citySpec = StringIdManager::instance()->getStringId(citySpecialization.hashCode()); params.setTO(strRank + ", " + citySpec); } creature->sendSystemMessage(params); applySpecializationModifiers(creature); } if (object->isStructureObject()){ StructureObject* structure = cast<StructureObject*>(object); /*uint64 creatureID = structure->getOwnerObjectID(); if (structure->isBuildingObject() && !citizenList.contains(creatureID)) { BuildingObject* building = cast<BuildingObject*>(object); CreatureObject* owner = building->getOwnerCreatureObject(); if (owner != NULL) { PlayerObject* playerObject = owner->getPlayerObject(); if (playerObject != NULL && playerObject->getDeclaredResidence() == building) { addCitizen(creatureID); } } }*/ if (structure->isCivicStructure()) addStructure(structure); } } void CityRegionImplementation::notifyExit(SceneObject* object) { //pre: no 2 different city regions should ever overlap, only 2 Regions of the same city region ManagedReference<Region*> activeRegion = cast<Region*>(object->getActiveRegion()); if (activeRegion != NULL) { ManagedReference<CityRegion*> city = activeRegion->getCityRegion(); object->setCityRegion(city); if (city == _this.get()) // if its the same city we wait till the object exits the last region return; } else { object->setCityRegion(NULL); } if (object->isBazaarTerminal() || object->isVendor()) { if (object->isBazaarTerminal()) bazaars.drop(object->getObjectID()); AuctionTerminalDataComponent* terminalData = NULL; DataObjectComponentReference* data = object->getDataObjectComponent(); if(data != NULL && data->get() != NULL && data->get()->isAuctionTerminalData()) terminalData = cast<AuctionTerminalDataComponent*>(data->get()); if(terminalData != NULL) terminalData->updateUID(); } if (object->isPlayerCreature()) currentPlayers.decrement(); if (isClientRegion()) return; if (object->isCreatureObject()){ CreatureObject* creature = cast<CreatureObject*>(object); StringIdChatParameter params("city/city", "city_leave_city"); //You have left %TO. params.setTO(getRegionName()); creature->sendSystemMessage(params); removeSpecializationModifiers(creature); } if (object->isStructureObject()) { float x = object->getWorldPositionX(); float y = object->getWorldPositionY(); //StructureObject* structure = cast<StructureObject*>(object); StructureObject* structure = cast<StructureObject*>(object); /*uint64 creatureID = structure->getOwnerObjectID(); if (structure->isBuildingObject() && citizenList.contains(creatureID)) { BuildingObject* building = cast<BuildingObject*>(object); CreatureObject* owner = building->getOwnerCreatureObject(); if (owner != NULL) { PlayerObject* playerObject = owner->getPlayerObject(); if (playerObject != NULL && playerObject->getDeclaredResidence() == building){ removeCitizen(creatureID); } } }*/ if (structure->isCivicStructure()) removeStructure(structure); } } void CityRegionImplementation::setRegionName(const StringId& name) { regionName = name; } Vector<ManagedReference<TangibleObject*> >* CityRegionImplementation::getVendorsInCity() { Vector<ManagedReference<TangibleObject*> >* vendors = new Vector<ManagedReference<TangibleObject*> >(); return vendors; } void CityRegionImplementation::addZoningRights(uint64 objectid, uint32 duration) { Time now; zoningRights.put(objectid, duration + now.getTime()); } bool CityRegionImplementation::hasZoningRights(uint64 objectid) { if (isMilitiaMember(objectid)) return true; uint32 timestamp = zoningRights.get(objectid); if (timestamp == 0) return false; Time now; return (now.getTime() <= timestamp); } void CityRegionImplementation::setZone(Zone* zne) { zone = zne; } void CityRegionImplementation::setRadius(float rad) { if (regions.size() <= 0) return; ManagedReference<ActiveArea*> aa = regions.get(0).get(); aa->setRadius(rad); zone->removeObject(aa, NULL, false); zone->transferObject(aa, -1, false); } void CityRegionImplementation::destroyActiveAreas() { for (int i = 0; i < regions.size(); ++i) { ManagedReference<Region*> aa = regions.get(i); if (aa != NULL) { aa->destroyObjectFromWorld(false); aa->destroyObjectFromDatabase(true); regions.drop(aa); } } } String CityRegionImplementation::getRegionName() { if(!customRegionName.isEmpty()) return customRegionName; return regionName.getFullPath(); } bool CityRegionImplementation::hasUniqueStructure(uint32 crc){ Locker locker(_this.get()); for (int i = 0; i < structures.size(); ++i) { ManagedReference<StructureObject*> structure = structures.get(i); if (structure->getObjectTemplate()->getServerObjectCRC() == crc) return true; } return false; } void CityRegionImplementation::destroyAllStructuresForRank(uint8 rank){ Locker locker(_this.get()); if (zone == NULL) return; StructureManager* structureManager = StructureManager::instance(); for (int i = structures.size() - 1; i >= 0; --i) { ManagedReference<StructureObject*> structure = structures.get(i); SharedStructureObjectTemplate* ssot = dynamic_cast<SharedStructureObjectTemplate*>(structure->getObjectTemplate()); //We only want to destroy civic structures. if (ssot == NULL || ssot->getCityRankRequired() < rank || !ssot->isCivicStructure()) continue; Locker _clocker(structure, _this.get()); structureManager->destroyStructure(structure); structures.drop(structure); } } void CityRegionImplementation::updateMilitia(){ Locker locker (_this.get()); uint64 objectID; for (int i = militiaMembers.size() - 1;i >= 0; --i){ objectID = militiaMembers.get(i); if (!isCitizen(objectID)) removeMilitiaMember(objectID); } } void CityRegionImplementation::removeAllTerminals(){ for (int i = 0; i < cityMissionTerminals.size(); i++){ cityMissionTerminals.get(i)->destroyObjectFromWorld(false); cityMissionTerminals.get(i)->destroyObjectFromDatabase(false); } cityMissionTerminals.removeAll(); } void CityRegionImplementation::removeAllSkillTrainers(){ for (int i = 0; i < citySkillTrainers.size(); i++){ citySkillTrainers.get(i)->destroyObjectFromWorld(false); citySkillTrainers.get(i)->destroyObjectFromDatabase(false); } citySkillTrainers.removeAll(); } void CityRegionImplementation::resetVotingPeriod() { nextInauguration.updateToCurrentTime(); nextInauguration.addMiliTime(CityManagerImplementation::cityVotingDuration * 60000); } void CityRegionImplementation::applySpecializationModifiers(CreatureObject* creature) { if (getZone() == NULL) return; CityManager* cityManager = getZone()->getZoneServer()->getCityManager(); CitySpecialization* cityspec = cityManager->getCitySpecialization(citySpecialization); if (cityspec == NULL) return; //Remove all current city skillmods creature->removeAllSkillModsOfType(SkillModManager::CITY); VectorMap<String, int>* mods = cityspec->getSkillMods(); for (int i = 0; i < mods->size(); ++i) { VectorMapEntry<String, int> entry = mods->elementAt(i); creature->addSkillMod(SkillModManager::CITY, entry.getKey(), entry.getValue()); } } void CityRegionImplementation::removeSpecializationModifiers(CreatureObject* creature) { creature->removeAllSkillModsOfType(SkillModManager::CITY); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbClassKMeansBase.h" namespace otb { namespace Wrapper { class KMeansClassification: public ClassKMeansBase { public: /** Standard class typedefs. */ typedef KMeansClassification Self; typedef ClassKMeansBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Self, Superclass); private: void DoInit() ITK_OVERRIDE { SetName("KMeansClassification"); SetDescription("Unsupervised KMeans image classification"); SetDocName("Unsupervised KMeans image classification"); SetDocLongDescription("Performs unsupervised KMeans image classification." "KMeansClassification is a composite application, " "using an existing training and classification application." "The SharkKMeans model is used.\n" "The steps of this composite application :\n" "1) ImageEnveloppe : create a shapefile (1 polygon),\n" "2) PolygonClassStatistics : compute the statistics,\n" "3) SampleSelection : select the samples by constant strategy in the shapefile " "(1000000 samples max),\n" "4) SamplesExtraction : extract the samples descriptors (update of SampleSelection output file),\n" "5) ComputeImagesStatistics : compute images second order statistics,\n" "6) TrainVectorClassifier : train the SharkKMeans model,\n" "7) ImageClassifier : performs the classification of the input image " "according to a model file.\n\n" "It's possible to choice random/periodic modes of the SampleSelection application.\n" "If you want keep the temporary files (sample selected, model file, ...), " "initialize cleanup parameter.\n" "For more information on shark KMeans algorithm [1]."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("ImageEnveloppe PolygonClassStatistics SampleSelection SamplesExtraction " "PolygonClassStatistics TrainVectorClassifier ImageClassifier\n" "[1] http://image.diku.dk/shark/sphinx_pages/build/html/rest_sources/tutorials/algorithms/kmeans.html"); AddDocTag(Tags::Learning); AddDocTag(Tags::Segmentation); // Perform initialization ClearApplications(); // initialisation parameters and synchronizes parameters initKMParams(); AddRANDParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("ts", "1000"); SetDocExampleParameterValue("nc", "5"); SetDocExampleParameterValue("maxit", "1000"); SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif uint8"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { } void DoExecute() ITK_OVERRIDE { if (IsParameterEnabled("vm") && HasValue("vm")) ConnectKMClassificationMask(); KMeansFileNamesHandler fileNames; std::string fieldName = "field"; fileNames.CreateTemporaryFileNames(GetParameterString( "out" )); // Create an image envelope ComputeImageEnvelope(fileNames.tmpVectorFile); // Add a new field at the ImageEnvelope output file ComputeAddField(fileNames.tmpVectorFile, fieldName); // Compute PolygonStatistics app UpdateKMPolygonClassStatisticsParameters(fileNames.tmpVectorFile); ComputePolygonStatistics(fileNames.polyStatOutput, fieldName); // Compute number of sample max for KMeans const int theoricNBSamplesForKMeans = GetParameterInt("ts"); const int upperThresholdNBSamplesForKMeans = 1000 * 1000; const int actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans, upperThresholdNBSamplesForKMeans); otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." \ << std::endl); // Compute SampleSelection and SampleExtraction app SelectAndExtractSamples(fileNames.polyStatOutput, fieldName, fileNames.sampleOutput, actualNBSamplesForKMeans); // Compute Images second order statistics ComputeImageStatistics(GetParameterString("in"), fileNames.imgStatOutput); // Compute a train model with TrainVectorClassifier app TrainKMModel(GetParameterImage("in"), fileNames.sampleOutput, fileNames.modelFile); // Compute a classification of the input image according to a model file KMeansClassif(); // Create the output text file containing centroids positions CreateOutMeansFile(GetParameterImage("in"), fileNames.modelFile, GetParameterInt("nc")); // Remove all tempory files if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); fileNames.clear(); } } private : void UpdateKMPolygonClassStatisticsParameters(const std::string &vectorFileName) { GetInternalApplication( "polystats" )->SetParameterString( "vec", vectorFileName, false ); UpdateInternalParameters( "polystats" ); } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification) <commit_msg>ENH: add const at the param in KMeansClassification<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * 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 "otbClassKMeansBase.h" namespace otb { namespace Wrapper { class KMeansClassification: public ClassKMeansBase { public: /** Standard class typedefs. */ typedef KMeansClassification Self; typedef ClassKMeansBase Superclass; typedef itk::SmartPointer<Self> Pointer; typedef itk::SmartPointer<const Self> ConstPointer; /** Standard macro */ itkNewMacro(Self); itkTypeMacro(Self, Superclass); private: void DoInit() ITK_OVERRIDE { SetName("KMeansClassification"); SetDescription("Unsupervised KMeans image classification"); SetDocName("Unsupervised KMeans image classification"); SetDocLongDescription("Performs unsupervised KMeans image classification." "KMeansClassification is a composite application, " "using an existing training and classification application." "The SharkKMeans model is used.\n" "The steps of this composite application :\n" "1) ImageEnveloppe : create a shapefile (1 polygon),\n" "2) PolygonClassStatistics : compute the statistics,\n" "3) SampleSelection : select the samples by constant strategy in the shapefile " "(1000000 samples max),\n" "4) SamplesExtraction : extract the samples descriptors (update of SampleSelection output file),\n" "5) ComputeImagesStatistics : compute images second order statistics,\n" "6) TrainVectorClassifier : train the SharkKMeans model,\n" "7) ImageClassifier : performs the classification of the input image " "according to a model file.\n\n" "It's possible to choice random/periodic modes of the SampleSelection application.\n" "If you want keep the temporary files (sample selected, model file, ...), " "initialize cleanup parameter.\n" "For more information on shark KMeans algorithm [1]."); SetDocLimitations("None"); SetDocAuthors("OTB-Team"); SetDocSeeAlso("ImageEnveloppe PolygonClassStatistics SampleSelection SamplesExtraction " "PolygonClassStatistics TrainVectorClassifier ImageClassifier\n" "[1] http://image.diku.dk/shark/sphinx_pages/build/html/rest_sources/tutorials/algorithms/kmeans.html"); AddDocTag(Tags::Learning); AddDocTag(Tags::Segmentation); // Perform initialization ClearApplications(); // initialisation parameters and synchronizes parameters initKMParams(); AddRANDParameter(); // Doc example parameter settings SetDocExampleParameterValue("in", "QB_1_ortho.tif"); SetDocExampleParameterValue("ts", "1000"); SetDocExampleParameterValue("nc", "5"); SetDocExampleParameterValue("maxit", "1000"); SetDocExampleParameterValue("out", "ClassificationFilterOutput.tif uint8"); SetOfficialDocLink(); } void DoUpdateParameters() ITK_OVERRIDE { } void DoExecute() ITK_OVERRIDE { if (IsParameterEnabled("vm") && HasValue("vm")) ConnectKMClassificationMask(); KMeansFileNamesHandler fileNames; const std::string fieldName = "field"; fileNames.CreateTemporaryFileNames(GetParameterString( "out" )); // Create an image envelope ComputeImageEnvelope(fileNames.tmpVectorFile); // Add a new field at the ImageEnvelope output file ComputeAddField(fileNames.tmpVectorFile, fieldName); // Compute PolygonStatistics app UpdateKMPolygonClassStatisticsParameters(fileNames.tmpVectorFile); ComputePolygonStatistics(fileNames.polyStatOutput, fieldName); // Compute number of sample max for KMeans const int theoricNBSamplesForKMeans = GetParameterInt("ts"); const int upperThresholdNBSamplesForKMeans = 1000 * 1000; const int actualNBSamplesForKMeans = std::min(theoricNBSamplesForKMeans, upperThresholdNBSamplesForKMeans); otbAppLogINFO(<< actualNBSamplesForKMeans << " is the maximum sample size that will be used." \ << std::endl); // Compute SampleSelection and SampleExtraction app SelectAndExtractSamples(fileNames.polyStatOutput, fieldName, fileNames.sampleOutput, actualNBSamplesForKMeans); // Compute Images second order statistics ComputeImageStatistics(GetParameterString("in"), fileNames.imgStatOutput); // Compute a train model with TrainVectorClassifier app TrainKMModel(GetParameterImage("in"), fileNames.sampleOutput, fileNames.modelFile); // Compute a classification of the input image according to a model file KMeansClassif(); // Create the output text file containing centroids positions CreateOutMeansFile(GetParameterImage("in"), fileNames.modelFile, GetParameterInt("nc")); // Remove all tempory files if( IsParameterEnabled( "cleanup" ) ) { otbAppLogINFO( <<"Final clean-up ..." ); fileNames.clear(); } } private : void UpdateKMPolygonClassStatisticsParameters(const std::string &vectorFileName) { GetInternalApplication( "polystats" )->SetParameterString( "vec", vectorFileName, false ); UpdateInternalParameters( "polystats" ); } }; } } OTB_APPLICATION_EXPORT(otb::Wrapper::KMeansClassification) <|endoftext|>