text
stringlengths
54
60.6k
<commit_before>/* Copyright 2018 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/compiler/jit/xla_launch_util.h" #include <memory> #include "absl/memory/memory.h" #include "tensorflow/compiler/jit/defs.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_compiler.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/gpu_device_context.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/util/stream_executor_util.h" namespace tensorflow { namespace { using xla::ScopedShapedBuffer; using xla::ShapedBuffer; } // anonymous namespace std::map<int, OptionalTensor> SnapshotResourceVariables( OpKernelContext* ctx, const std::vector<int>& variables) { std::map<int, OptionalTensor> snapshot; for (int i : variables) { Var* variable = nullptr; ResourceHandle handle = HandleFromInput(ctx, i); OptionalTensor& tensor = snapshot[i]; if (LookupResource(ctx, handle, &variable).ok()) { tf_shared_lock lock(*variable->mu()); tensor.name = handle.name(); tensor.present = true; tensor.value = *variable->tensor(); } } return snapshot; } XlaAllocator::XlaAllocator(const se::Platform* platform, Allocator* wrapped) : xla::DeviceMemoryAllocator(platform), wrapped_(wrapped) {} XlaAllocator::~XlaAllocator() {} xla::StatusOr<xla::OwningDeviceMemory> XlaAllocator::Allocate( int device_ordinal, uint64 size, bool retry_on_failure) { AllocationAttributes attrs; attrs.no_retry_on_failure = !retry_on_failure; void* data = nullptr; if (size != 0) { data = wrapped_->AllocateRaw(Allocator::kAllocatorAlignment, size, attrs); if (data == nullptr) { return errors::ResourceExhausted( "Out of memory while trying to allocate ", size, " bytes."); } } return xla::OwningDeviceMemory(se::DeviceMemoryBase(data, size), device_ordinal, this); } Status XlaAllocator::Deallocate(int device_ordinal, se::DeviceMemoryBase mem) { wrapped_->DeallocateRaw(mem.opaque()); return Status::OK(); } namespace internal { // Return the 'index''th subtree of the given ShapedBuffer as a // ScopedShapedBuffer. The returned ScopedShapedBuffer takes ownership of the // subtree, and sets the input's buffer pointers to nullptr for the subtree. ScopedShapedBuffer ExtractSubShapedBuffer( ShapedBuffer* shaped_buffer, int index, xla::DeviceMemoryAllocator* allocator) { const xla::Shape& on_host_shape = xla::ShapeUtil::GetTupleElementShape( shaped_buffer->on_host_shape(), index); const xla::Shape& on_device_shape = xla::ShapeUtil::GetTupleElementShape( shaped_buffer->on_device_shape(), index); ShapedBuffer sub_shaped_buffer(on_host_shape, on_device_shape, shaped_buffer->platform(), shaped_buffer->device_ordinal()); auto& shape_tree = shaped_buffer->buffers(); auto& sub_shape_tree = sub_shaped_buffer.buffers(); sub_shape_tree.CopySubtreeFrom(shape_tree, /*source_base_index=*/{index}, /*target_base_index=*/{}); shape_tree.ForEachMutableElement( [index](const xla::ShapeIndex& shape_index, tensorflow::se::DeviceMemoryBase* data) { // shape_index is empty for the root node. Ignore that. if (!shape_index.empty() && shape_index[0] == index) { *data = tensorflow::se::DeviceMemoryBase(nullptr, 0); } }); return ScopedShapedBuffer(std::move(sub_shaped_buffer), allocator); } } // namespace internal using internal::ExtractSubShapedBuffer; XlaComputationLaunchContext::XlaComputationLaunchContext( xla::LocalClient* client, xla::DeviceMemoryAllocator* xla_allocator, bool allocate_xla_tensors, bool use_multiple_streams) : client_(client), xla_allocator_(xla_allocator), allocate_xla_tensors_(allocate_xla_tensors), use_multiple_streams_(use_multiple_streams) { if (use_multiple_streams_) { CHECK(allocate_xla_tensors_) << "To use multiple streams correctly we must " "be allocating XLA tensors!"; } } void XlaComputationLaunchContext::PopulateInputs( OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel, const std::map<int, OptionalTensor>& variables) { se::Stream* stream = ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr; // Build ShapedBuffers that point directly to the Tensor buffers. arg_buffers_.reserve(kernel->xla_input_shapes.size() + 1); arg_buffers_.resize(kernel->xla_input_shapes.size()); arg_ptrs_ = std::vector<ShapedBuffer*>(arg_buffers_.size()); // Pass remaining parameters. const Tensor* t; for (int i = 0; i < kernel->xla_input_shapes.size(); ++i) { int arg_num = kernel->input_mapping[i]; const xla::Shape& shape = kernel->xla_input_shapes[i]; if (variables.count(arg_num)) { t = &(variables.at(arg_num).value); CHECK(t); } else { t = &(ctx->input(arg_num)); } if (use_multiple_streams_) { CHECK(stream) << "Must have a stream available when using XLA tensors!"; XlaTensor* xla_tensor = XlaTensor::FromTensor(t); CHECK(xla_tensor); if (se::Event* event = xla_tensor->GetDefinitionEvent(stream)) { stream->ThenWaitFor(event); xla_tensor->SetDefinedOn(stream); } } const xla::Shape on_device_shape = client_->backend().transfer_manager()->HostShapeToDeviceShape(shape); if (xla::ShapeUtil::IsTuple(on_device_shape)) { const XlaTensor* xla_tensor = XlaTensor::FromTensor(t); CHECK(xla_tensor && xla_tensor->has_shaped_buffer()); arg_ptrs_[i] = const_cast<ShapedBuffer*>(&xla_tensor->shaped_buffer()); } else { CHECK(xla::ShapeUtil::Equal(shape, on_device_shape)) << "On-device shape " << xla::ShapeUtil::HumanStringWithLayout(on_device_shape) << " not the same as on-host shape " << xla::ShapeUtil::HumanStringWithLayout(shape); se::DeviceMemoryBase dmem = XlaTensor::DeviceMemoryFromTensor(*t); arg_buffers_[i] = absl::make_unique<ShapedBuffer>( /*on_host_shape=*/shape, /*on_device_shape=*/shape, client_->platform(), client_->default_device_ordinal()); arg_buffers_[i]->set_buffer(dmem, /*index=*/{}); arg_ptrs_[i] = arg_buffers_[i].get(); } } } Status XlaComputationLaunchContext::PopulateOutputs( OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel, ScopedShapedBuffer output) { se::Stream* stream = ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr; // Computation output should always be a tuple. if (VLOG_IS_ON(2)) { VLOG(2) << "Result tuple shape: " << output.on_host_shape().DebugString(); VLOG(2) << "Result tuple shape (on device): " << output.on_device_shape().DebugString(); } CHECK_EQ(ctx->num_outputs(), kernel->outputs.size()); // If the on-host-shape isn't a tuple, create a new single-element tuple // buffer with a nullptr root index table. This allows the code below to treat // output as a tuple unconditionally. if (!xla::ShapeUtil::IsTuple(output.on_host_shape())) { ShapedBuffer nontuple_buffer = output.release(); ShapedBuffer buffer( xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_host_shape()}), xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_device_shape()}), output.platform(), output.device_ordinal()); buffer.buffers().CopySubtreeFrom(nontuple_buffer.buffers(), /*source_base_index=*/{}, /*target_base_index=*/{0}); output = ScopedShapedBuffer(std::move(buffer), output.memory_allocator()); } std::shared_ptr<se::Event> definition_event; if (use_multiple_streams_) { definition_event = std::make_shared<se::Event>(stream->parent()); if (!definition_event->Init()) { return errors::Internal("Failed to initialize tensor definition event."); } stream->ThenRecordEvent(definition_event.get()); } // Copy XLA results to the OpOutputList. int output_num = 0; for (int i = 0; i < ctx->num_outputs(); ++i) { Allocator* allocator = ctx->device()->GetAllocator({}); if (kernel->outputs[i].is_constant) { // Output is a constant. const Tensor& const_tensor = kernel->outputs[i].constant_value; Tensor* output_tensor; const size_t total_bytes = const_tensor.TotalBytes(); if (stream && total_bytes > 0) { // Copy host -> device. (Empty tensors don't have backing buffers.) // Manually allocate memory using an XlaTensorBuffer so we can allocate // as much memory as the device requires (as given by // GetByteSizeRequirement). This avoids XlaTransferManager having to // reallocate the device buffer later. VLOG(1) << "Constant output tensor on device"; TF_RETURN_IF_ERROR( ctx->allocate_output(i, const_tensor.shape(), &output_tensor)); Device* device = dynamic_cast<Device*>(ctx->device()); if (device == nullptr) { return errors::Internal("DeviceBase was not a Device."); } ctx->op_device_context()->CopyCPUTensorToDevice( &const_tensor, device, output_tensor, [&](Status status) { TF_CHECK_OK(status); }); if (device->device_type() == DEVICE_GPU) { // The GPUDeviceContext enqueues the host->device transfer in a // separate stream from the main compute stream. We must ensure the // compute stream is synchronized with the host->device transfer // stream now otherwise we will create a race condition. auto* gpu_device_context = static_cast<GPUDeviceContext*>(ctx->op_device_context()); gpu_device_context->stream()->ThenWaitFor( gpu_device_context->host_to_device_stream()); } } else { // No copy required. ctx->set_output(i, const_tensor); output_tensor = ctx->mutable_output(i); } if (XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor)) { xla_tensor->set_host_tensor(const_tensor); } } else { const TensorShape& shape = kernel->outputs[i].shape; const DataType& type = kernel->outputs[i].type; VLOG(2) << "Retval " << i << " shape " << shape.DebugString() << " type " << DataTypeString(type); if (type == DT_RESOURCE) { ctx->set_output(i, ctx->input(kernel->outputs[i].input_index)); } else { se::DeviceMemoryBase buffer = output.buffer({output_num}); if (allocate_xla_tensors_) { Tensor* output_tensor; TF_RETURN_IF_ERROR(ctx->allocate_output(i, shape, &output_tensor)); XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor); if (xla_tensor) { xla_tensor->set_shaped_buffer(ScopedShapedBuffer( ExtractSubShapedBuffer(&output, output_num, xla_allocator_))); if (use_multiple_streams_) { xla_tensor->SetDefinedOn(stream, definition_event); } } else { // xla_tensor wasn't valid, which must mean this is a zero-element // tensor. CHECK_EQ(output_tensor->TotalBytes(), 0); } } else { Tensor output_tensor = XlaTensorBuffer::MakeTensor( ctx->expected_output_dtype(i), shape, buffer, allocator); output.set_buffer(xla::OwningDeviceMemory(), {output_num}); ctx->set_output(i, output_tensor); } ++output_num; } } if (VLOG_IS_ON(3)) { VLOG(3) << ctx->mutable_output(i)->DebugString(); } } // Apply variable updates, if any. VLOG(2) << "Applying variable updates"; for (int i = 0; i < kernel->resource_updates.size(); ++i) { Allocator* allocator = ctx->device()->GetAllocator({}); const XlaCompiler::ResourceUpdate& write = kernel->resource_updates[i]; if (write.input_index < 0 || write.input_index >= ctx->num_inputs()) { return errors::Internal("Invalid input index for variable write."); } se::DeviceMemoryBase buffer = output.buffer({output_num}); Var* variable = nullptr; // TODO(b/35625933): tensorflow::Var should contain a PersistentTensor, // not a Tensor. TF_RETURN_IF_ERROR(LookupOrCreateResource<Var>( ctx, HandleFromInput(ctx, write.input_index), &variable, [&write](Var** ptr) { *ptr = new Var(write.type); return Status::OK(); })); core::ScopedUnref s(variable); mutex_lock ml(*variable->mu()); if (variable->tensor()->dtype() != write.type) { return errors::Internal("Mismatched type in variable write"); } if (allocate_xla_tensors_) { Tensor output_tensor; TF_RETURN_IF_ERROR( ctx->allocate_temp(write.type, write.shape, &output_tensor)); XlaTensor* xla_tensor = XlaTensor::FromTensor(&output_tensor); CHECK(xla_tensor); xla_tensor->set_shaped_buffer( ExtractSubShapedBuffer(&output, output_num, xla_allocator_)); if (use_multiple_streams_) { xla_tensor->SetDefinedOn(stream, definition_event); } *variable->tensor() = output_tensor; } else { Tensor output_tensor = XlaTensorBuffer::MakeTensor( write.type, write.shape, buffer, allocator); output.set_buffer(xla::OwningDeviceMemory(), {output_num}); *variable->tensor() = output_tensor; } ++output_num; } return Status::OK(); } } // namespace tensorflow <commit_msg>Return error message with illegal input rather than check-failing in op_kernel.<commit_after>/* Copyright 2018 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/compiler/jit/xla_launch_util.h" #include <memory> #include "absl/memory/memory.h" #include "tensorflow/compiler/jit/defs.h" #include "tensorflow/compiler/tf2xla/shape_util.h" #include "tensorflow/compiler/tf2xla/xla_compiler.h" #include "tensorflow/compiler/xla/client/client_library.h" #include "tensorflow/compiler/xla/client/local_client.h" #include "tensorflow/compiler/xla/statusor.h" #include "tensorflow/core/common_runtime/dma_helper.h" #include "tensorflow/core/common_runtime/function.h" #include "tensorflow/core/common_runtime/gpu_device_context.h" #include "tensorflow/core/framework/allocator.h" #include "tensorflow/core/framework/node_def_util.h" #include "tensorflow/core/framework/op.h" #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/util/stream_executor_util.h" namespace tensorflow { namespace { using xla::ScopedShapedBuffer; using xla::ShapedBuffer; } // anonymous namespace std::map<int, OptionalTensor> SnapshotResourceVariables( OpKernelContext* ctx, const std::vector<int>& variables) { std::map<int, OptionalTensor> snapshot; for (int i : variables) { Var* variable = nullptr; ResourceHandle handle = HandleFromInput(ctx, i); OptionalTensor& tensor = snapshot[i]; if (LookupResource(ctx, handle, &variable).ok()) { tf_shared_lock lock(*variable->mu()); tensor.name = handle.name(); tensor.present = true; tensor.value = *variable->tensor(); } } return snapshot; } XlaAllocator::XlaAllocator(const se::Platform* platform, Allocator* wrapped) : xla::DeviceMemoryAllocator(platform), wrapped_(wrapped) {} XlaAllocator::~XlaAllocator() {} xla::StatusOr<xla::OwningDeviceMemory> XlaAllocator::Allocate( int device_ordinal, uint64 size, bool retry_on_failure) { AllocationAttributes attrs; attrs.no_retry_on_failure = !retry_on_failure; void* data = nullptr; if (size != 0) { data = wrapped_->AllocateRaw(Allocator::kAllocatorAlignment, size, attrs); if (data == nullptr) { return errors::ResourceExhausted( "Out of memory while trying to allocate ", size, " bytes."); } } return xla::OwningDeviceMemory(se::DeviceMemoryBase(data, size), device_ordinal, this); } Status XlaAllocator::Deallocate(int device_ordinal, se::DeviceMemoryBase mem) { wrapped_->DeallocateRaw(mem.opaque()); return Status::OK(); } namespace internal { // Return the 'index''th subtree of the given ShapedBuffer as a // ScopedShapedBuffer. The returned ScopedShapedBuffer takes ownership of the // subtree, and sets the input's buffer pointers to nullptr for the subtree. ScopedShapedBuffer ExtractSubShapedBuffer( ShapedBuffer* shaped_buffer, int index, xla::DeviceMemoryAllocator* allocator) { const xla::Shape& on_host_shape = xla::ShapeUtil::GetTupleElementShape( shaped_buffer->on_host_shape(), index); const xla::Shape& on_device_shape = xla::ShapeUtil::GetTupleElementShape( shaped_buffer->on_device_shape(), index); ShapedBuffer sub_shaped_buffer(on_host_shape, on_device_shape, shaped_buffer->platform(), shaped_buffer->device_ordinal()); auto& shape_tree = shaped_buffer->buffers(); auto& sub_shape_tree = sub_shaped_buffer.buffers(); sub_shape_tree.CopySubtreeFrom(shape_tree, /*source_base_index=*/{index}, /*target_base_index=*/{}); shape_tree.ForEachMutableElement( [index](const xla::ShapeIndex& shape_index, tensorflow::se::DeviceMemoryBase* data) { // shape_index is empty for the root node. Ignore that. if (!shape_index.empty() && shape_index[0] == index) { *data = tensorflow::se::DeviceMemoryBase(nullptr, 0); } }); return ScopedShapedBuffer(std::move(sub_shaped_buffer), allocator); } } // namespace internal using internal::ExtractSubShapedBuffer; XlaComputationLaunchContext::XlaComputationLaunchContext( xla::LocalClient* client, xla::DeviceMemoryAllocator* xla_allocator, bool allocate_xla_tensors, bool use_multiple_streams) : client_(client), xla_allocator_(xla_allocator), allocate_xla_tensors_(allocate_xla_tensors), use_multiple_streams_(use_multiple_streams) { if (use_multiple_streams_) { CHECK(allocate_xla_tensors_) << "To use multiple streams correctly we must " "be allocating XLA tensors!"; } } void XlaComputationLaunchContext::PopulateInputs( OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel, const std::map<int, OptionalTensor>& variables) { se::Stream* stream = ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr; // Build ShapedBuffers that point directly to the Tensor buffers. arg_buffers_.reserve(kernel->xla_input_shapes.size() + 1); arg_buffers_.resize(kernel->xla_input_shapes.size()); arg_ptrs_ = std::vector<ShapedBuffer*>(arg_buffers_.size()); // Pass remaining parameters. const Tensor* t; for (int i = 0; i < kernel->xla_input_shapes.size(); ++i) { int arg_num = kernel->input_mapping[i]; const xla::Shape& shape = kernel->xla_input_shapes[i]; if (variables.count(arg_num)) { t = &(variables.at(arg_num).value); CHECK(t); } else { t = &(ctx->input(arg_num)); } if (use_multiple_streams_) { CHECK(stream) << "Must have a stream available when using XLA tensors!"; XlaTensor* xla_tensor = XlaTensor::FromTensor(t); CHECK(xla_tensor); if (se::Event* event = xla_tensor->GetDefinitionEvent(stream)) { stream->ThenWaitFor(event); xla_tensor->SetDefinedOn(stream); } } const xla::Shape on_device_shape = client_->backend().transfer_manager()->HostShapeToDeviceShape(shape); if (xla::ShapeUtil::IsTuple(on_device_shape)) { const XlaTensor* xla_tensor = XlaTensor::FromTensor(t); CHECK(xla_tensor && xla_tensor->has_shaped_buffer()); arg_ptrs_[i] = const_cast<ShapedBuffer*>(&xla_tensor->shaped_buffer()); } else { CHECK(xla::ShapeUtil::Equal(shape, on_device_shape)) << "On-device shape " << xla::ShapeUtil::HumanStringWithLayout(on_device_shape) << " not the same as on-host shape " << xla::ShapeUtil::HumanStringWithLayout(shape); se::DeviceMemoryBase dmem = XlaTensor::DeviceMemoryFromTensor(*t); arg_buffers_[i] = absl::make_unique<ShapedBuffer>( /*on_host_shape=*/shape, /*on_device_shape=*/shape, client_->platform(), client_->default_device_ordinal()); arg_buffers_[i]->set_buffer(dmem, /*index=*/{}); arg_ptrs_[i] = arg_buffers_[i].get(); } } } Status XlaComputationLaunchContext::PopulateOutputs( OpKernelContext* ctx, const XlaCompiler::CompilationResult* kernel, ScopedShapedBuffer output) { se::Stream* stream = ctx->op_device_context() ? ctx->op_device_context()->stream() : nullptr; // Computation output should always be a tuple. if (VLOG_IS_ON(2)) { VLOG(2) << "Result tuple shape: " << output.on_host_shape().DebugString(); VLOG(2) << "Result tuple shape (on device): " << output.on_device_shape().DebugString(); } CHECK_EQ(ctx->num_outputs(), kernel->outputs.size()); // If the on-host-shape isn't a tuple, create a new single-element tuple // buffer with a nullptr root index table. This allows the code below to treat // output as a tuple unconditionally. if (!xla::ShapeUtil::IsTuple(output.on_host_shape())) { ShapedBuffer nontuple_buffer = output.release(); ShapedBuffer buffer( xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_host_shape()}), xla::ShapeUtil::MakeTupleShape({nontuple_buffer.on_device_shape()}), output.platform(), output.device_ordinal()); buffer.buffers().CopySubtreeFrom(nontuple_buffer.buffers(), /*source_base_index=*/{}, /*target_base_index=*/{0}); output = ScopedShapedBuffer(std::move(buffer), output.memory_allocator()); } std::shared_ptr<se::Event> definition_event; if (use_multiple_streams_) { definition_event = std::make_shared<se::Event>(stream->parent()); if (!definition_event->Init()) { return errors::Internal("Failed to initialize tensor definition event."); } stream->ThenRecordEvent(definition_event.get()); } // Copy XLA results to the OpOutputList. int output_num = 0; for (int i = 0; i < ctx->num_outputs(); ++i) { Allocator* allocator = ctx->device()->GetAllocator({}); if (kernel->outputs[i].is_constant) { // Output is a constant. const Tensor& const_tensor = kernel->outputs[i].constant_value; Tensor* output_tensor; const size_t total_bytes = const_tensor.TotalBytes(); if (stream && total_bytes > 0) { // Copy host -> device. (Empty tensors don't have backing buffers.) // Manually allocate memory using an XlaTensorBuffer so we can allocate // as much memory as the device requires (as given by // GetByteSizeRequirement). This avoids XlaTransferManager having to // reallocate the device buffer later. VLOG(1) << "Constant output tensor on device"; TF_RETURN_IF_ERROR( ctx->allocate_output(i, const_tensor.shape(), &output_tensor)); Device* device = dynamic_cast<Device*>(ctx->device()); if (device == nullptr) { return errors::Internal("DeviceBase was not a Device."); } ctx->op_device_context()->CopyCPUTensorToDevice( &const_tensor, device, output_tensor, [&](Status status) { TF_CHECK_OK(status); }); if (device->device_type() == DEVICE_GPU) { // The GPUDeviceContext enqueues the host->device transfer in a // separate stream from the main compute stream. We must ensure the // compute stream is synchronized with the host->device transfer // stream now otherwise we will create a race condition. auto* gpu_device_context = static_cast<GPUDeviceContext*>(ctx->op_device_context()); gpu_device_context->stream()->ThenWaitFor( gpu_device_context->host_to_device_stream()); } } else { // No copy required. ctx->set_output(i, const_tensor); output_tensor = ctx->mutable_output(i); } if (XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor)) { xla_tensor->set_host_tensor(const_tensor); } } else { const TensorShape& shape = kernel->outputs[i].shape; const DataType& type = kernel->outputs[i].type; VLOG(2) << "Retval " << i << " shape " << shape.DebugString() << " type " << DataTypeString(type); if (type == DT_RESOURCE) { TF_RET_CHECK(kernel->outputs[i].input_index >= 0) << "Invalid input for outputs " << i; ctx->set_output(i, ctx->input(kernel->outputs[i].input_index)); } else { se::DeviceMemoryBase buffer = output.buffer({output_num}); if (allocate_xla_tensors_) { Tensor* output_tensor; TF_RETURN_IF_ERROR(ctx->allocate_output(i, shape, &output_tensor)); XlaTensor* xla_tensor = XlaTensor::FromTensor(output_tensor); if (xla_tensor) { xla_tensor->set_shaped_buffer(ScopedShapedBuffer( ExtractSubShapedBuffer(&output, output_num, xla_allocator_))); if (use_multiple_streams_) { xla_tensor->SetDefinedOn(stream, definition_event); } } else { // xla_tensor wasn't valid, which must mean this is a zero-element // tensor. CHECK_EQ(output_tensor->TotalBytes(), 0); } } else { Tensor output_tensor = XlaTensorBuffer::MakeTensor( ctx->expected_output_dtype(i), shape, buffer, allocator); output.set_buffer(xla::OwningDeviceMemory(), {output_num}); ctx->set_output(i, output_tensor); } ++output_num; } } if (VLOG_IS_ON(3)) { VLOG(3) << ctx->mutable_output(i)->DebugString(); } } // Apply variable updates, if any. VLOG(2) << "Applying variable updates"; for (int i = 0; i < kernel->resource_updates.size(); ++i) { Allocator* allocator = ctx->device()->GetAllocator({}); const XlaCompiler::ResourceUpdate& write = kernel->resource_updates[i]; if (write.input_index < 0 || write.input_index >= ctx->num_inputs()) { return errors::Internal("Invalid input index for variable write."); } se::DeviceMemoryBase buffer = output.buffer({output_num}); Var* variable = nullptr; // TODO(b/35625933): tensorflow::Var should contain a PersistentTensor, // not a Tensor. TF_RETURN_IF_ERROR(LookupOrCreateResource<Var>( ctx, HandleFromInput(ctx, write.input_index), &variable, [&write](Var** ptr) { *ptr = new Var(write.type); return Status::OK(); })); core::ScopedUnref s(variable); mutex_lock ml(*variable->mu()); if (variable->tensor()->dtype() != write.type) { return errors::Internal("Mismatched type in variable write"); } if (allocate_xla_tensors_) { Tensor output_tensor; TF_RETURN_IF_ERROR( ctx->allocate_temp(write.type, write.shape, &output_tensor)); XlaTensor* xla_tensor = XlaTensor::FromTensor(&output_tensor); CHECK(xla_tensor); xla_tensor->set_shaped_buffer( ExtractSubShapedBuffer(&output, output_num, xla_allocator_)); if (use_multiple_streams_) { xla_tensor->SetDefinedOn(stream, definition_event); } *variable->tensor() = output_tensor; } else { Tensor output_tensor = XlaTensorBuffer::MakeTensor( write.type, write.shape, buffer, allocator); output.set_buffer(xla::OwningDeviceMemory(), {output_num}); *variable->tensor() = output_tensor; } ++output_num; } return Status::OK(); } } // namespace tensorflow <|endoftext|>
<commit_before>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetTreeHeader.cpp */ #include "JPetTreeHeader.h" #include "../JPetCommonTools/JPetCommonTools.h" #include <sstream> ClassImp(JPetTreeHeader); JPetTreeHeader::JPetTreeHeader(): fRunNo(-1), fBaseFilename("filename not set something"), fSourcePosition(-1), emptyStage({"module not set", "description not set", -1, "-1"}) { } JPetTreeHeader::JPetTreeHeader(int run): fRunNo(run), fBaseFilename("filename not set"), fSourcePosition(-1), emptyStage({"module not set", "description not set", -1, "-1"}) { } std::string JPetTreeHeader::stringify() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n" ; tmp<<"------------------------- General Info --------------------------\n" ; tmp<<"-----------------------------------------------------------------\n" ; tmp<< "Run number : " << JPetCommonTools::Itoa(fRunNo) <<"\n"; tmp<< "Base file name : "<<getBaseFileName()<<"\n"; tmp<< "Source (if any) position: "<< Form("%lf",getSourcePosition())<<"\n"; tmp << stringifyHistory(); tmp << stringifyDictionary(); return tmp.str(); } void JPetTreeHeader::addStageInfo(std::string p_name, std::string p_title, int p_version, std::string p_time_stamp ) { ProcessingStageInfo stage; stage.fModuleName = p_name; stage.fModuleDescription = p_title; stage.fModuleVersion = p_version; stage.fCreationTime = p_time_stamp; fStages.push_back( stage ); } std::string JPetTreeHeader::stringifyDictionary() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n"; tmp<<"--------------------- User-defined variables --------------------\n"; tmp<<"-----------------------------------------------------------------\n"; for(auto const &entry : fDictionary){ tmp<<entry.first << " = " << entry.second <<"\n"; tmp<<"-----------------------------------------------------------------\n"; } return tmp.str(); } std::string JPetTreeHeader::stringifyHistory() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n"; tmp<<"-------------- Processing history (oldest first) ----------------\n"; tmp<<"-----------------------------------------------------------------\n"; for (int i = 0; i < getStagesNb(); i++ ) { const ProcessingStageInfo & info = getProcessingStageInfo(i); tmp<< "Module Name : " << info.fModuleName<<"\n"; tmp<< "Module desc. : " << info.fModuleDescription<<"\n"; tmp<< "Module version : " << JPetCommonTools::Itoa( info.fModuleVersion ) <<"\n"; tmp<< "Started processing : " << info.fCreationTime <<"\n"; tmp<<"-----------------------------------------------------------------\n"; } return tmp.str(); } /** * @brief Sets the textual value of an existing variable named 'name' or * creates such variable if it was nonexistent * * @param name name of the variable (existing or not) * @param value value of the variable * * Use this method to store any additional information in the TreeHeader. * All values must be encoded as text. * * Example: * header.setVariable("source position", "X=10cm; Y=2cm; Z=20cm") * */ void JPetTreeHeader::setVariable(std::string name, std::string value){ fDictionary[name] = value; } /** * @brief Returns the textual value of a variable (see the setVariable method) * * @param name name of the variable * * Use this method to access any additional information previously stored * in the TreeHeader with the setVariable method. If a name of a non-existent variable * is provided, an empty string will be returned. * */ std::string JPetTreeHeader::getVariable(std::string name) const { if(fDictionary.find(name)!= fDictionary.end()) return fDictionary.at(name); else return ""; } <commit_msg>ParseXML is working; back to previes, working code<commit_after>/** * @copyright Copyright 2016 The J-PET Framework 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 find a copy of the License in the LICENCE file. * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @file JPetTreeHeader.cpp */ #include "JPetTreeHeader.h" #include "../JPetCommonTools/JPetCommonTools.h" #include <sstream> ClassImp(JPetTreeHeader); JPetTreeHeader::JPetTreeHeader(): fRunNo(-1), fBaseFilename("filename not set"), fSourcePosition(-1), emptyStage({"module not set", "description not set", -1, "-1"}) { } JPetTreeHeader::JPetTreeHeader(int run): fRunNo(run), fBaseFilename("filename not set"), fSourcePosition(-1), emptyStage({"module not set", "description not set", -1, "-1"}) { } std::string JPetTreeHeader::stringify() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n" ; tmp<<"------------------------- General Info --------------------------\n" ; tmp<<"-----------------------------------------------------------------\n" ; tmp<< "Run number : " << JPetCommonTools::Itoa(fRunNo) <<"\n"; tmp<< "Base file name : "<<getBaseFileName()<<"\n"; tmp<< "Source (if any) position: "<< Form("%lf",getSourcePosition())<<"\n"; tmp << stringifyHistory(); tmp << stringifyDictionary(); return tmp.str(); } void JPetTreeHeader::addStageInfo(std::string p_name, std::string p_title, int p_version, std::string p_time_stamp ) { ProcessingStageInfo stage; stage.fModuleName = p_name; stage.fModuleDescription = p_title; stage.fModuleVersion = p_version; stage.fCreationTime = p_time_stamp; fStages.push_back( stage ); } std::string JPetTreeHeader::stringifyDictionary() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n"; tmp<<"--------------------- User-defined variables --------------------\n"; tmp<<"-----------------------------------------------------------------\n"; for(auto const &entry : fDictionary){ tmp<<entry.first << " = " << entry.second <<"\n"; tmp<<"-----------------------------------------------------------------\n"; } return tmp.str(); } std::string JPetTreeHeader::stringifyHistory() const { std::ostringstream tmp; tmp<<"-----------------------------------------------------------------\n"; tmp<<"-------------- Processing history (oldest first) ----------------\n"; tmp<<"-----------------------------------------------------------------\n"; for (int i = 0; i < getStagesNb(); i++ ) { const ProcessingStageInfo & info = getProcessingStageInfo(i); tmp<< "Module Name : " << info.fModuleName<<"\n"; tmp<< "Module desc. : " << info.fModuleDescription<<"\n"; tmp<< "Module version : " << JPetCommonTools::Itoa( info.fModuleVersion ) <<"\n"; tmp<< "Started processing : " << info.fCreationTime <<"\n"; tmp<<"-----------------------------------------------------------------\n"; } return tmp.str(); } /** * @brief Sets the textual value of an existing variable named 'name' or * creates such variable if it was nonexistent * * @param name name of the variable (existing or not) * @param value value of the variable * * Use this method to store any additional information in the TreeHeader. * All values must be encoded as text. * * Example: * header.setVariable("source position", "X=10cm; Y=2cm; Z=20cm") * */ void JPetTreeHeader::setVariable(std::string name, std::string value){ fDictionary[name] = value; } /** * @brief Returns the textual value of a variable (see the setVariable method) * * @param name name of the variable * * Use this method to access any additional information previously stored * in the TreeHeader with the setVariable method. If a name of a non-existent variable * is provided, an empty string will be returned. * */ std::string JPetTreeHeader::getVariable(std::string name) const { if(fDictionary.find(name)!= fDictionary.end()) return fDictionary.at(name); else return ""; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyanimationnode.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2006-07-26 07:36:24 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "propertyanimationnode.hxx" #include "animationfactory.hxx" using namespace com::sun::star; namespace presentation { namespace internal { AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const { // Create AnimationActivity from common XAnimate parameters: ActivitiesFactory::CommonParameters aParms( fillCommonParameters() ); uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode(); rtl::OUString const attrName( xAnimateNode->getAttributeName() ); AttributableShapeSharedPtr const pShape( getShape() ); switch (AnimationFactory::classifyAttributeName( attrName )) { default: case AnimationFactory::CLASS_UNKNOWN_PROPERTY: ENSURE_AND_THROW( false, "Unexpected attribute class (unknown or empty attribute name)" ); break; case AnimationFactory::CLASS_NUMBER_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createNumberPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_ENUM_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createEnumPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_COLOR_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createColorPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_STRING_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createStringPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_BOOL_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createBoolPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); } return AnimationActivitySharedPtr(); } } // namespace internal } // namespace presentation <commit_msg>INTEGRATION: CWS pchfix02 (1.4.10); FILE MERGED 2006/09/01 17:39:39 kaib 1.4.10.1: #i68856# Added header markers and pch files<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: propertyanimationnode.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2006-09-17 08:36:37 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_slideshow.hxx" // must be first #include "canvas/debug.hxx" #include "canvas/verbosetrace.hxx" #include "propertyanimationnode.hxx" #include "animationfactory.hxx" using namespace com::sun::star; namespace presentation { namespace internal { AnimationActivitySharedPtr PropertyAnimationNode::createActivity() const { // Create AnimationActivity from common XAnimate parameters: ActivitiesFactory::CommonParameters aParms( fillCommonParameters() ); uno::Reference<animations::XAnimate> const& xAnimateNode =getXAnimateNode(); rtl::OUString const attrName( xAnimateNode->getAttributeName() ); AttributableShapeSharedPtr const pShape( getShape() ); switch (AnimationFactory::classifyAttributeName( attrName )) { default: case AnimationFactory::CLASS_UNKNOWN_PROPERTY: ENSURE_AND_THROW( false, "Unexpected attribute class (unknown or empty attribute name)" ); break; case AnimationFactory::CLASS_NUMBER_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createNumberPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_ENUM_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createEnumPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_COLOR_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createColorPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_STRING_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createStringPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); case AnimationFactory::CLASS_BOOL_PROPERTY: return ActivitiesFactory::createAnimateActivity( aParms, AnimationFactory::createBoolPropertyAnimation( attrName, pShape, getContext().mpLayerManager ), xAnimateNode ); } return AnimationActivitySharedPtr(); } } // namespace internal } // namespace presentation <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: checkinstall.cxx,v $ * * $Revision: 1.2 $ * * last change: $Author: rt $ $Date: 2005-09-08 17:05:06 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "checkinstall.hxx" #ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_ #include <com/sun/star/beans/XExactName.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_ #include <com/sun/star/beans/XMaterialHolder.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XContentEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace desktop { sal_Bool CheckInstallation( OUString& rTitle ) { Reference< XMultiServiceFactory > xSMgr = ::comphelper::getProcessServiceFactory(); Reference< XExactName > xExactName( xSMgr->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.Evaluation" ))), UNO_QUERY ); if ( xExactName.is() ) { try { rTitle = xExactName->getExactName( rTitle ); Reference< XMaterialHolder > xMaterialHolder( xExactName, UNO_QUERY ); if ( xMaterialHolder.is() ) { com::sun::star::util::Date aExpirationDate; Any a = xMaterialHolder->getMaterial(); if ( a >>= aExpirationDate ) { Date aToday; Date aTimeBombDate( aExpirationDate.Day, aExpirationDate.Month, aExpirationDate.Year ); if ( aToday > aTimeBombDate ) { InfoBox aInfoBox( NULL, String::CreateFromAscii( "This version has expired" ) ); aInfoBox.Execute(); return sal_False; } } return sal_True; } else { InfoBox aInfoBox( NULL, rTitle ); aInfoBox.Execute(); return sal_False; } } catch ( RuntimeException& ) { // Evaluation version expired! return sal_False; } } else { Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY ); if( rContent.is() ) { OUString sEvalService = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.office.Evaluation" ) ); Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sEvalService ); if ( rEnum.is() ) { InfoBox aInfoBox( NULL, rTitle ); aInfoBox.Execute(); return sal_False; } } } return sal_True; } } // namespace desktop <commit_msg>INTEGRATION: CWS internatiodel (1.1.670); FILE MERGED 2006/01/19 17:52:07 er 1.1.670.2: RESYNC: (1.1-1.2); FILE MERGED 2005/06/29 11:14:33 er 1.1.670.1: #i50205# get rid of class International<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: checkinstall.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: vg $ $Date: 2006-04-07 14:43:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include "checkinstall.hxx" #ifndef _COM_SUN_STAR_BEANS_XEXACTNAME_HPP_ #include <com/sun/star/beans/XExactName.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMATERIALHOLDER_HPP_ #include <com/sun/star/beans/XMaterialHolder.hpp> #endif #ifndef _COM_SUN_STAR_CONTAINER_XCONTENTENUMERATIONACCESS_HPP_ #include <com/sun/star/container/XContentEnumerationAccess.hpp> #endif #ifndef _COM_SUN_STAR_UTIL_DATE_HPP_ #include <com/sun/star/util/Date.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XMULTISERVICEFACTORY_HPP_ #include <com/sun/star/lang/XMultiServiceFactory.hpp> #endif #ifndef _COMPHELPER_PROCESSFACTORY_HXX_ #include <comphelper/processfactory.hxx> #endif #ifndef _SV_MSGBOX_HXX #include <vcl/msgbox.hxx> #endif #ifndef _DATE_HXX #include <tools/date.hxx> #endif using namespace rtl; using namespace com::sun::star::uno; using namespace com::sun::star::lang; using namespace com::sun::star::beans; namespace desktop { sal_Bool CheckInstallation( OUString& rTitle ) { Reference< XMultiServiceFactory > xSMgr = ::comphelper::getProcessServiceFactory(); Reference< XExactName > xExactName( xSMgr->createInstance( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.comp.desktop.Evaluation" ))), UNO_QUERY ); if ( xExactName.is() ) { try { rTitle = xExactName->getExactName( rTitle ); Reference< XMaterialHolder > xMaterialHolder( xExactName, UNO_QUERY ); if ( xMaterialHolder.is() ) { com::sun::star::util::Date aExpirationDate; Any a = xMaterialHolder->getMaterial(); if ( a >>= aExpirationDate ) { Date aToday; Date aTimeBombDate( aExpirationDate.Day, aExpirationDate.Month, aExpirationDate.Year ); if ( aToday > aTimeBombDate ) { InfoBox aInfoBox( NULL, String::CreateFromAscii( "This version has expired" ) ); aInfoBox.Execute(); return sal_False; } } return sal_True; } else { InfoBox aInfoBox( NULL, rTitle ); aInfoBox.Execute(); return sal_False; } } catch ( RuntimeException& ) { // Evaluation version expired! return sal_False; } } else { Reference< com::sun::star::container::XContentEnumerationAccess > rContent( xSMgr , UNO_QUERY ); if( rContent.is() ) { OUString sEvalService = OUString( RTL_CONSTASCII_USTRINGPARAM( "com.sun.star.office.Evaluation" ) ); Reference < com::sun::star::container::XEnumeration > rEnum = rContent->createContentEnumeration( sEvalService ); if ( rEnum.is() ) { InfoBox aInfoBox( NULL, rTitle ); aInfoBox.Execute(); return sal_False; } } } return sal_True; } } // namespace desktop <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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. * * $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $ * */ #include <sensor_msgs/PointCloud2.h> #include <pcl/io/pcd_io.h> #include <pcl/features/boundary.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; int default_k = 0; double default_radius = 0.0; double default_angle = M_PI/2.0; Eigen::Vector4f translation; Eigen::Quaternionf orientation; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: "); print_value ("%f", default_radius); print_info (")\n"); print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: "); print_value ("%d", default_k); print_info (")\n"); print_info (" -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: "); print_value ("%f", default_angle); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud, translation, orientation) < 0) return (false); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); // Check if the dataset has normals if (pcl::getFieldIndex (cloud, "normal_x") == -1) { print_error ("The input dataset does not contain normal information!\n"); return (false); } return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output, int k, double radius, double angle) { // Convert data to PointCloud<T> PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>); fromROSMsg (*input, *xyznormals); // Estimate TicToc tt; tt.tic (); print_highlight (stderr, "Computing "); BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne; ne.setInputCloud (xyznormals); ne.setInputNormals (xyznormals); ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>)); ne.setKSearch (k); ne.setRadiusSearch (radius); PointCloud<Boundary> boundaries; ne.compute (boundaries); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n"); // Convert data back sensor_msgs::PointCloud2 output_boundaries; toROSMsg (boundaries, output_boundaries); concatenateFields (*input, output_boundaries, output); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output, translation, orientation, true); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]); bool help = false; parse_argument (argc, argv, "-h", help); if (argc < 3 || help) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input PCD file and one output PCD file to continue.\n"); return (-1); } // Command line parsing int k = default_k; double radius = default_radius; double angle = default_angle; parse_argument (argc, argv, "-k", k); parse_argument (argc, argv, "-radius", radius); parse_argument (argc, argv, "-thresh", angle); // Load the first file sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2); if (!loadCloud (argv[p_file_indices[0]], *cloud)) return (-1); // Perform the feature estimation sensor_msgs::PointCloud2 output; compute (cloud, output, k, radius, angle); // Save into the second file saveCloud (argv[p_file_indices[1]], output); } <commit_msg>save as ascii in an attempt to catch a bug<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2010-2011, Willow Garage, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT 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. * * $Id: boundary_estimation.cpp 1032 2011-05-18 22:43:27Z marton $ * */ #include <sensor_msgs/PointCloud2.h> #include <pcl/io/pcd_io.h> #include <pcl/features/boundary.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> using namespace pcl; using namespace pcl::io; using namespace pcl::console; int default_k = 0; double default_radius = 0.0; double default_angle = M_PI/2.0; Eigen::Vector4f translation; Eigen::Quaternionf orientation; void printHelp (int argc, char **argv) { print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -radius X = use a radius of Xm around each point to determine the neighborhood (default: "); print_value ("%f", default_radius); print_info (")\n"); print_info (" -k X = use a fixed number of X-nearest neighbors around each point (default: "); print_value ("%d", default_k); print_info (")\n"); print_info (" -thresh X = the decision boundary (angle threshold) that marks points as boundary or regular (default: "); print_value ("%f", default_angle); print_info (")\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud, translation, orientation) < 0) return (false); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", cloud.width * cloud.height); print_info (" points]\n"); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); // Check if the dataset has normals if (pcl::getFieldIndex (cloud, "normal_x") == -1) { print_error ("The input dataset does not contain normal information!\n"); return (false); } return (true); } void compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output, int k, double radius, double angle) { // Convert data to PointCloud<T> PointCloud<PointNormal>::Ptr xyznormals (new PointCloud<PointNormal>); fromROSMsg (*input, *xyznormals); // Estimate TicToc tt; tt.tic (); print_highlight (stderr, "Computing "); BoundaryEstimation<pcl::PointNormal, pcl::PointNormal, pcl::Boundary> ne; ne.setInputCloud (xyznormals); ne.setInputNormals (xyznormals); ne.setSearchMethod (pcl::KdTreeFLANN<pcl::PointNormal>::Ptr (new pcl::KdTreeFLANN<pcl::PointNormal>)); ne.setKSearch (k); ne.setRadiusSearch (radius); PointCloud<Boundary> boundaries; ne.compute (boundaries); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", boundaries.width * boundaries.height); print_info (" points]\n"); // Convert data back sensor_msgs::PointCloud2 output_boundaries; toROSMsg (boundaries, output_boundaries); concatenateFields (*input, output_boundaries, output); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output, translation, orientation, false); print_info ("[done, "); print_value ("%g", tt.toc ()); print_info (" seconds : "); print_value ("%d", output.width * output.height); print_info (" points]\n"); } /* ---[ */ int main (int argc, char** argv) { print_info ("Estimate boundary points using pcl::BoundaryEstimation. For more information, use: %s -h\n", argv[0]); bool help = false; parse_argument (argc, argv, "-h", help); if (argc < 3 || help) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input PCD file and one output PCD file to continue.\n"); return (-1); } // Command line parsing int k = default_k; double radius = default_radius; double angle = default_angle; parse_argument (argc, argv, "-k", k); parse_argument (argc, argv, "-radius", radius); parse_argument (argc, argv, "-thresh", angle); // Load the first file sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2); if (!loadCloud (argv[p_file_indices[0]], *cloud)) return (-1); // Perform the feature estimation sensor_msgs::PointCloud2 output; compute (cloud, output, k, radius, angle); // Save into the second file saveCloud (argv[p_file_indices[1]], output); } <|endoftext|>
<commit_before>#include <KameMix.h> #include <cmath> #include <cassert> #include <thread> #include <chrono> #include <iostream> using namespace KameMix; using std::cout; using std::cerr; void onSoundFinished(Sound *sound, void *udata) { cout << "sound finished\n"; assert(!sound->isPlaying()); } void onStreamFinished(Stream *stream, void *udata) { cout << "stream finished\n"; assert(!stream->isPlaying()); } int main(int argc, char *argv[]) { //OutAudioFormat format = OutFormat_S16; OutAudioFormat format = OutFormat_Float; if (!System::init(44100, 2048, format)) { cout << "System::init failed\n"; return 1; } cout << "Initialized KameMix\n"; System::setSoundFinished(onSoundFinished, nullptr); System::setStreamFinished(onStreamFinished, nullptr); assert(System::getMasterVolume() == 1.0); System::setMasterVolume(.5); assert(System::getMasterVolume() == .5); System::setMasterVolume(1.0); const char *file_path = "sound/spell1.wav"; Stream spell1(file_path); if (!spell1.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } file_path = "sound/spell3.wav"; Sound spell3(file_path); if (!spell3.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } file_path = "sound/cow.ogg"; Sound cow(file_path); if (!cow.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } file_path = "sound/duck.ogg"; Stream duck(file_path); if (!duck.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } file_path = "sound/dark fallout.ogg"; Stream music1(file_path); if (!music1.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } file_path = "sound/a new beginning.ogg"; Sound music2(file_path); if (!music2.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return EXIT_FAILURE; } int group1 = System::createGroup(); System::setGroupVolume(group1, .75); assert(System::getGroupVolume(group1) == .75); spell1.play(6); spell1.setGroup(group1); assert(spell1.isPlaying()); assert(spell1.getGroup() == group1); cout << "play spell1 7 times\n"; spell3.play(6); assert(spell3.isPlaying()); assert(spell3.getGroup() == -1); cout << "play spell3 7 times\n"; cow.play(6); assert(cow.isPlaying()); cout << "play cow 7 times\n"; duck.play(6); assert(duck.isPlaying()); duck.setVolume(1.25f); assert(duck.getVolume() == 1.25f); cout << "play duck 7 times\n"; double time_ms = 0.0; int count = 0; const int frame_ms = 17; const double frames_per_sec = 1000.0/frame_ms; float listener_x = .5f; float listener_y = .5f; System::setListenerPos(listener_x, listener_y); { float a, b; System::getListenerPos(a, b); assert(a == listener_x && b == listener_y); } float x = listener_x; float y = .75f; bool going_left = true; while (true) { System::update(); std::this_thread::sleep_for(std::chrono::milliseconds(frame_ms)); time_ms += frame_ms; if (time_ms > 10000 && count == 0) { cout << "play music1 starting at 40sec for 10secs\n"; time_ms = 0.0; count++; music1.playAt(40); } else if (time_ms > 10000 && count == 1) { cout << "Fadeout music1 over 10 secs\n"; time_ms = 0.0; count++; music1.fadeout(10); } else if (time_ms > 10000 && count == 2) { cout << "Fadein music2 over 10 secs, pause after 5 secs\n"; time_ms = 0.0; count++; music2.fadein(10.0); } else if (time_ms > 5000 && count == 3) { cout << "pause music2 for 3 secs\n"; time_ms = 0.0; count++; music2.pause(); } else if (time_ms > 3000 && count == 4) { cout << "unpause music2, and continue fadein over 5 secs\n"; time_ms = 0.0; count++; music2.unpause(); } else if (time_ms > 5000 && count == 5) { cout << "fadein complete, play for 5 secs and then stop\n"; time_ms = 0.0; count++; } else if (time_ms > 5000 && count == 6) { cout << "stop music2\n"; time_ms = 0.0; count++; music2.stop(); cout << "play spell1 moving left to right and back for 20secs\n"; spell1.setMaxDistance(1.0f); spell1.play(-1); } else if (count == 7) { spell1.setPos(x, y); // 1 cycle in 10 secs float dx = (float)(2*spell1.getMaxDistance() / 10 / frames_per_sec); if (going_left) { x -= dx; } else { x += dx; } if (std::abs(listener_x - x) >= spell1.getMaxDistance() * 1.05) { going_left = !going_left; } if (time_ms > 20000) { spell1.stop(); count++; } } else if (count == 8) { if (System::numberPlaying() == 0) { cout << "Test complete\n"; break; } } } System::shutdown(); cout << "Shutdown KameMix\n"; return 0; } <commit_msg>Improved and added more tests<commit_after>#include <KameMix.h> #include <cmath> #include <cassert> #include <thread> #include <chrono> #include <iostream> using namespace KameMix; using std::cout; using std::cerr; void onSoundFinished(Sound *sound, void *udata) { cout << "sound finished\n"; assert(!sound->isPlaying()); } void onStreamFinished(Stream *stream, void *udata) { cout << "stream finished\n"; assert(!stream->isPlaying()); } Sound spell1; Sound spell3; Sound cow; Stream duck; Stream music1; Sound music2; const int frames_per_sec = 60; const double frame_ms = 1000.0 / frames_per_sec; double update_ms(double msec); bool loadAudio(); void test1(); void test2(); void test3(); void test4(); void test5(); int main(int argc, char *argv[]) { //OutAudioFormat format = OutFormat_S16; OutAudioFormat format = OutFormat_Float; if (!System::init(44100, 2048, format)) { cout << "System::init failed\n"; return 1; } cout << "Initialized KameMix\n"; if (!loadAudio()) { return EXIT_FAILURE; } System::setSoundFinished(onSoundFinished, nullptr); System::setStreamFinished(onStreamFinished, nullptr); assert(System::getMasterVolume() == 1.0f); System::setMasterVolume(.5f); assert(System::getMasterVolume() == .5f); System::setMasterVolume(1.0f); { float a, b; System::getListenerPos(a, b); assert(a == 0 && b == 0); System::setListenerPos(.5f, .75f); System::getListenerPos(a, b); assert(a == .5f && b == .75f); } int group1 = System::createGroup(); System::setGroupVolume(group1, .75f); assert(System::getGroupVolume(group1) == .75f); assert(spell1.getGroup() == -1); spell1.setGroup(group1); assert(spell1.getGroup() == group1); duck.setVolume(1.5); assert(duck.getVolume() == 1.5); //test1(); //test2(); //test3(); //test4(); test5(); cout << "Test complete\n"; System::shutdown(); cout << "Shutdown KameMix\n"; return 0; } bool loadAudio() { const char *file_path = "sound/spell1.wav"; spell1.load(file_path); if (!spell1.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } file_path = "sound/spell3.wav"; spell3.load(file_path); if (!spell3.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } file_path = "sound/cow.ogg"; cow.load(file_path); if (!cow.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } file_path = "sound/duck.ogg"; duck.load(file_path); if (!duck.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } file_path = "sound/dark fallout.ogg"; music1.load(file_path); if (!music1.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } file_path = "sound/a new beginning.ogg"; music2.load(file_path); if (!music2.isLoaded()) { cerr << "Couldn't load " << file_path << "\n"; return false; } return true; } double update_ms(double msec) { const std::chrono::duration<double, std::milli> sleep_duration(frame_ms); double total_time = 0; while (true) { System::update(); std::this_thread::sleep_for(sleep_duration); total_time += frame_ms; if (total_time >= msec) { break; } } return total_time; } void test1() { cout << "play spell1 7 times\n"; spell1.play(6); assert(spell1.isPlaying()); cout << "play spell3 7 times\n"; spell3.play(6); assert(spell3.isPlaying()); cout << "play cow 7 times\n"; cow.play(6); assert(cow.isPlaying()); cout << "play duck 7 times\n"; duck.play(6); assert(duck.isPlaying()); while (true) { update_ms(1000); if (System::numberPlaying() == 0) { break; } } } void test2() { cout << "Play music1 starting at 40sec for 10secs\n"; music1.playAt(40); update_ms(10000); cout << "Fadeout music1 over 10 secs\n"; music1.fadeout(10); update_ms(10000); cout << "Fadein music2 over 10 secs, pause after 5 secs\n"; music2.fadein(10.0); update_ms(5000); cout << "Pause music2 for 3 secs\n"; music2.pause(); update_ms(3000); cout << "Unpause music2, and continue fadein over 5 secs\n"; music2.unpause(); update_ms(5000); cout << "Fadein complete, play for 5 secs and then stop\n"; update_ms(5000); cout << "Stop music2\n"; music2.stop(); } void test3() { float listener_x = .5f; float listener_y = .5f; System::setListenerPos(listener_x, listener_y); float x = listener_x; float y = listener_y + .25f; cout << "Play spell1 moving left to right and back for 20secs\n"; spell1.setMaxDistance(1.0f); spell1.setPos(x, y); spell1.play(-1); bool going_left = true; double total_time = 0; while (true) { // 2 cycle in 10 secs float dx = (float)(4*spell1.getMaxDistance() / 10 / frames_per_sec); if (going_left) { x -= dx; } else { x += dx; } if (std::abs(listener_x - x) >= spell1.getMaxDistance() * 1.05) { going_left = !going_left; } total_time += update_ms(frame_ms); if (total_time > 20000) { spell1.stop(); break; } spell1.setPos(x, y); } } void test4() { float listener_x = .5f; float listener_y = .5f; System::setListenerPos(listener_x, listener_y); float lx = listener_x - .5f; float rx = listener_x + .5f; float y = listener_y; cout << "Play duck for 12 secs, swapping sides every 3 secs\n"; duck.setMaxDistance(1.0f); duck.setPos(lx, y); duck.play(-1); update_ms(3000); duck.setPos(rx, y); update_ms(3000); duck.setPos(lx, y); update_ms(3000); duck.setPos(rx, y); update_ms(3000); duck.setPos(lx, y); update_ms(3000); cout << "Stop duck\n"; duck.stop(); } void test5() { cout << "Play music1 for 5 secs at 100% volume\n"; music1.setVolume(1.0f); music1.setGroup(-1); music1.play(-1); update_ms(5000); cout << "Set music1 volume to 0% for 3 secs\n"; music1.setVolume(0); update_ms(3000); cout << "Set music1 volume to 100% for 5 secs\n"; music1.setVolume(1.0f); update_ms(5000); cout << "Set music1 volume to 25% for 5 secs\n"; music1.setVolume(.25f); update_ms(5000); cout << "Set music1 volume to 100% for 5 secs\n"; music1.setVolume(1.0f); update_ms(5000); cout << "Stop music1\n"; music1.stop(); }<|endoftext|>
<commit_before>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_SELECTION_GENERATOR_HPP_ #define CLOTHO_SELECTION_GENERATOR_HPP_ #include <boost/property_tree/ptree.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <vector> namespace clotho { namespace genetics { /** * Random selection */ template < class RNG, class GeneticSpaceType > class SelectionGenerator { public: typedef RNG random_engine_type; typedef GeneticSpaceType genetic_space_type; typedef typename genetic_space_type::individual_id_type individual_id_type; typedef std::vector< std::pair< individual_id_type, individual_id_type > > mate_pair_vector; typedef typename mate_pair_vector::iterator parent_iterator; typedef typename mate_pair_vector::const_iterator const_parent_iterator; typedef typename genetic_space_type::fitness_score_type fitness_score_type; typedef typename genetic_space_type::fitness_scores fitness_scores; typedef boost::random::uniform_int_distribution< size_t > distribution_type; SelectionGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) : m_rand( rng ) { } void update( genetic_space_type * parents, size_t count ) { // distribution generates numbers in range [0, N] // therefore N needs to be the maximum index (individual_count - 1) distribution_type dist( 0, parents->individual_count() - 1 ); m_pairs.clear(); while( count-- ) { individual_id_type id0 = m_dist( *m_rand ); individual_id_type id1 = m_dist( *m_rand ); m_pairs.push_back( std::make_pair( id0, id1 ) ); } } parent_iterator begin() { return m_pairs.begin(); } parent_iterator end() { return m_pairs.end(); } const_parent_iterator begin() const { return m_pairs.begin(); } const_parent_iterator end() const { return m_pairs.end(); } mate_pair_vector & getMatePairs() { return m_pairs; } size_t size() const { return m_pairs.size(); } virtual ~SelectionGenerator() {} protected: random_engine_type * m_rand; mate_pair_vector m_pairs; }; } // namespace genetics } // namespace clotho #endif // CLOTHO_SELECTION_GENERATOR_HPP_ <commit_msg>Fixed to use local variable<commit_after>// Copyright 2015 Patrick Putnam // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef CLOTHO_SELECTION_GENERATOR_HPP_ #define CLOTHO_SELECTION_GENERATOR_HPP_ #include <boost/property_tree/ptree.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <vector> namespace clotho { namespace genetics { /** * Random selection */ template < class RNG, class GeneticSpaceType > class SelectionGenerator { public: typedef RNG random_engine_type; typedef GeneticSpaceType genetic_space_type; typedef typename genetic_space_type::individual_id_type individual_id_type; typedef std::vector< std::pair< individual_id_type, individual_id_type > > mate_pair_vector; typedef typename mate_pair_vector::iterator parent_iterator; typedef typename mate_pair_vector::const_iterator const_parent_iterator; typedef typename genetic_space_type::fitness_score_type fitness_score_type; typedef typename genetic_space_type::fitness_scores fitness_scores; typedef boost::random::uniform_int_distribution< size_t > distribution_type; SelectionGenerator( random_engine_type * rng, boost::property_tree::ptree & config ) : m_rand( rng ) { } void update( genetic_space_type * parents, size_t count ) { // distribution generates numbers in range [0, N] // therefore N needs to be the maximum index (individual_count - 1) distribution_type dist( 0, parents->individual_count() - 1 ); m_pairs.clear(); while( count-- ) { individual_id_type id0 = dist( *m_rand ); individual_id_type id1 = dist( *m_rand ); m_pairs.push_back( std::make_pair( id0, id1 ) ); } } parent_iterator begin() { return m_pairs.begin(); } parent_iterator end() { return m_pairs.end(); } const_parent_iterator begin() const { return m_pairs.begin(); } const_parent_iterator end() const { return m_pairs.end(); } mate_pair_vector & getMatePairs() { return m_pairs; } size_t size() const { return m_pairs.size(); } virtual ~SelectionGenerator() {} protected: random_engine_type * m_rand; mate_pair_vector m_pairs; }; } // namespace genetics } // namespace clotho #endif // CLOTHO_SELECTION_GENERATOR_HPP_ <|endoftext|>
<commit_before>// @(#)root/tree:$Id$ // Author: Rene Brun 05/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // A TSelector object is used by the TTree::Draw, TTree::Scan, // // TTree::Process to navigate in a TTree and make selections. // // It contains the following main methods: // // // // void TSelector::Init(TTree *t). Called every time a new TTree is // // attached. // // // // void TSelector::SlaveBegin(). Create e.g. histograms in this method. // // This method is called (with or without PROOF) before looping on the // // entries in the Tree. When using PROOF, this method is called on // // each worker node. // // void TSelector::Begin(). Mostly for backward compatibility; use // // SlaveBegin() instead. Both methods are called before looping on the // // entries in the Tree. When using PROOF, Begin() is called on the // // client only. // // // // Bool_t TSelector::Notify(). This method is called at the first entry // // of a new file in a chain. // // // // Bool_t TSelector::Process(Long64_t entry). This method is called // // to process an entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // Once the entry is in memory one can apply a selection and if the // // entry is selected histograms can be filled. Processing stops // // when this function returns kFALSE. This function combines the // // next two functions in one, avoiding to have to maintain state // // in the class to communicate between these two functions. // // See WARNING below about entry. // // This method is used by PROOF. // // Bool_t TSelector::ProcessCut(Long64_t entry). This method is called // // before processing entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // The function returns kTRUE if the entry must be processed, // // kFALSE otherwise. This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::ProcessFill(Long64_t entry). This method is called // // for all selected entries. User fills histograms in this function. // // This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::SlaveTerminate(). This method is called at the end of // // the loop on all PROOF worker nodes. In local mode this method is // // called on the client too. // // void TSelector::Terminate(). This method is called at the end of // // the loop on all entries. When using PROOF Terminate() is call on // // the client only. Typically one performs the fits on the produced // // histograms or write the histograms to file in this method. // // // // WARNING when a selector is used with a TChain: // // in the Process, ProcessCut, ProcessFill function, you must use // // the pointer to the current Tree to call GetEntry(entry). // // entry is always the local entry number in the current tree. // // Assuming that fChain is the pointer to the TChain being processed, // // use fChain->GetTree()->GetEntry(entry); // // // //////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "TError.h" #include "TSelectorCint.h" #include "TClass.h" #include "TInterpreter.h" ClassImp(TSelector) //______________________________________________________________________________ TSelector::TSelector() : TObject() { // Default selector ctor. fStatus = 0; fAbort = kContinue; fObject = 0; fInput = 0; fOutput = new TSelectorList; fOutput->SetOwner(); } //______________________________________________________________________________ TSelector::~TSelector() { // Selector destructor. delete fOutput; } //______________________________________________________________________________ void TSelector::Abort(const char *why, EAbort what) { // Abort processing. If what = kAbortProcess, the Process() loop will be // aborted. If what = kAbortFile, the current file in a chain will be // aborted and the processing will continue with the next file, if there // is no next file then Process() will be aborted. Abort() can also be // called from Begin(), SlaveBegin(), Init() and Notify(). After abort // the SlaveTerminate() and Terminate() are always called. The abort flag // can be checked in these methods using GetAbort(). fAbort = what; TString mess = "Abort"; if (fAbort == kAbortProcess) mess = "AbortProcess"; else if (fAbort == kAbortFile) mess = "AbortFile"; Info(mess, "%s", why); } //______________________________________________________________________________ TSelector *TSelector::GetSelector(const char *filename) { // The code in filename is loaded (interpreted or compiled, see below), // filename must contain a valid class implementation derived from TSelector. // // If filename is of the form file.C, the file will be interpreted. // If filename is of the form file.C++, the file file.C will be compiled // and dynamically loaded. The corresponding binary file and shared // library will be deleted at the end of the function. // If filename is of the form file.C+, the file file.C will be compiled // and dynamically loaded. At next call, if file.C is older than file.o // and file.so, the file.C is not compiled, only file.so is loaded. // // The static function returns a pointer to a TSelector object // If the filename does not contain "." assume class is compiled in TString localname; Bool_t fromFile = kFALSE; if (strchr(filename, '.') != 0) { //Interpret/compile filename via CINT localname = ".L "; localname += filename; gROOT->ProcessLine(localname); fromFile = kTRUE; } //loop on all classes known to CINT to find the class on filename //that derives from TSelector const char *basename = gSystem->BaseName(filename); if (!basename) { ::Error("TSelector::GetSelector","unable to determine the classname for file %s", filename); return 0; } TString aclicmode,args,io; localname = gSystem->SplitAclicMode(basename,aclicmode,args,io); Bool_t isCompiled = !fromFile || aclicmode.Length()>0; if (localname.Last('.') != kNPOS) localname.Remove(localname.Last('.')); // if a file was not specified, try to load the class via the interpreter; // this returns 0 (== failure) in the case the class is already in memory // but does not have a dictionary, so we just raise a flag for better // diagnostic in the case the class is not found in the CINT ClassInfo table. Bool_t autoloaderr = kFALSE; if (!fromFile && gCint->AutoLoad(localname) != 1) autoloaderr = kTRUE; ClassInfo_t *cl = gCint->ClassInfo_Factory(); Bool_t ok = kFALSE; while (gCint->ClassInfo_Next(cl)) { if (localname == gCint->ClassInfo_FullName(cl)) { if (gCint->ClassInfo_IsBase(cl,"TSelector")) ok = kTRUE; break; } } if (!ok) { if (fromFile) { ::Error("TSelector::GetSelector", "file %s does not have a valid class deriving from TSelector", filename); } else { if (autoloaderr) ::Error("TSelector::GetSelector", "class %s could not be loaded", filename); else ::Error("TSelector::GetSelector", "class %s does not exist or does not derive from TSelector", filename); } return 0; } // we can now create an instance of the class TSelector *selector = (TSelector*)gCint->ClassInfo_New(cl); if (!selector || isCompiled) return selector; //interpreted selector: cannot be used as such //create a fake selector TSelectorCint *select = new TSelectorCint(); select->Build(selector, cl); gCint->ClassInfo_Delete(cl); return select; } //______________________________________________________________________________ Bool_t TSelector::IsStandardDraw(const char *selec) { // Find out if this is a standard selection used for Draw actions // (either TSelectorDraw, TProofDraw or deriving from them). // Make sure we have a name if (!selec) { ::Info("TSelector::IsStandardDraw", "selector name undefined - do nothing"); return kFALSE; } Bool_t stdselec = kFALSE; if (!strchr(selec, '.')) { if (strstr(selec, "TSelectorDraw")) { stdselec = kTRUE; } else { TClass *cl = TClass::GetClass(selec); if (cl && (cl->InheritsFrom("TProofDraw") || cl->InheritsFrom("TSelectorDraw"))) stdselec = kTRUE; } } // We are done return stdselec; } <commit_msg>In TSelector::GetSelector give more specific error message if we can't find a class derived from TSelector in the input source file<commit_after>// @(#)root/tree:$Id$ // Author: Rene Brun 05/02/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ //////////////////////////////////////////////////////////////////////////// // // // A TSelector object is used by the TTree::Draw, TTree::Scan, // // TTree::Process to navigate in a TTree and make selections. // // It contains the following main methods: // // // // void TSelector::Init(TTree *t). Called every time a new TTree is // // attached. // // // // void TSelector::SlaveBegin(). Create e.g. histograms in this method. // // This method is called (with or without PROOF) before looping on the // // entries in the Tree. When using PROOF, this method is called on // // each worker node. // // void TSelector::Begin(). Mostly for backward compatibility; use // // SlaveBegin() instead. Both methods are called before looping on the // // entries in the Tree. When using PROOF, Begin() is called on the // // client only. // // // // Bool_t TSelector::Notify(). This method is called at the first entry // // of a new file in a chain. // // // // Bool_t TSelector::Process(Long64_t entry). This method is called // // to process an entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // Once the entry is in memory one can apply a selection and if the // // entry is selected histograms can be filled. Processing stops // // when this function returns kFALSE. This function combines the // // next two functions in one, avoiding to have to maintain state // // in the class to communicate between these two functions. // // See WARNING below about entry. // // This method is used by PROOF. // // Bool_t TSelector::ProcessCut(Long64_t entry). This method is called // // before processing entry. It is the user's responsability to read // // the corresponding entry in memory (may be just a partial read). // // The function returns kTRUE if the entry must be processed, // // kFALSE otherwise. This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::ProcessFill(Long64_t entry). This method is called // // for all selected entries. User fills histograms in this function. // // This method is obsolete, use Process(). // // See WARNING below about entry. // // void TSelector::SlaveTerminate(). This method is called at the end of // // the loop on all PROOF worker nodes. In local mode this method is // // called on the client too. // // void TSelector::Terminate(). This method is called at the end of // // the loop on all entries. When using PROOF Terminate() is call on // // the client only. Typically one performs the fits on the produced // // histograms or write the histograms to file in this method. // // // // WARNING when a selector is used with a TChain: // // in the Process, ProcessCut, ProcessFill function, you must use // // the pointer to the current Tree to call GetEntry(entry). // // entry is always the local entry number in the current tree. // // Assuming that fChain is the pointer to the TChain being processed, // // use fChain->GetTree()->GetEntry(entry); // // // //////////////////////////////////////////////////////////////////////////// #include "TROOT.h" #include "TSystem.h" #include "TTree.h" #include "TError.h" #include "TSelectorCint.h" #include "TClass.h" #include "TInterpreter.h" ClassImp(TSelector) //______________________________________________________________________________ TSelector::TSelector() : TObject() { // Default selector ctor. fStatus = 0; fAbort = kContinue; fObject = 0; fInput = 0; fOutput = new TSelectorList; fOutput->SetOwner(); } //______________________________________________________________________________ TSelector::~TSelector() { // Selector destructor. delete fOutput; } //______________________________________________________________________________ void TSelector::Abort(const char *why, EAbort what) { // Abort processing. If what = kAbortProcess, the Process() loop will be // aborted. If what = kAbortFile, the current file in a chain will be // aborted and the processing will continue with the next file, if there // is no next file then Process() will be aborted. Abort() can also be // called from Begin(), SlaveBegin(), Init() and Notify(). After abort // the SlaveTerminate() and Terminate() are always called. The abort flag // can be checked in these methods using GetAbort(). fAbort = what; TString mess = "Abort"; if (fAbort == kAbortProcess) mess = "AbortProcess"; else if (fAbort == kAbortFile) mess = "AbortFile"; Info(mess, "%s", why); } //______________________________________________________________________________ TSelector *TSelector::GetSelector(const char *filename) { // The code in filename is loaded (interpreted or compiled, see below), // filename must contain a valid class implementation derived from TSelector. // // If filename is of the form file.C, the file will be interpreted. // If filename is of the form file.C++, the file file.C will be compiled // and dynamically loaded. The corresponding binary file and shared // library will be deleted at the end of the function. // If filename is of the form file.C+, the file file.C will be compiled // and dynamically loaded. At next call, if file.C is older than file.o // and file.so, the file.C is not compiled, only file.so is loaded. // // The static function returns a pointer to a TSelector object // If the filename does not contain "." assume class is compiled in TString localname; Bool_t fromFile = kFALSE; if (strchr(filename, '.') != 0) { //Interpret/compile filename via CINT localname = ".L "; localname += filename; gROOT->ProcessLine(localname); fromFile = kTRUE; } //loop on all classes known to CINT to find the class on filename //that derives from TSelector const char *basename = gSystem->BaseName(filename); if (!basename) { ::Error("TSelector::GetSelector","unable to determine the classname for file %s", filename); return 0; } TString aclicmode,args,io; localname = gSystem->SplitAclicMode(basename,aclicmode,args,io); Bool_t isCompiled = !fromFile || aclicmode.Length()>0; if (localname.Last('.') != kNPOS) localname.Remove(localname.Last('.')); // if a file was not specified, try to load the class via the interpreter; // this returns 0 (== failure) in the case the class is already in memory // but does not have a dictionary, so we just raise a flag for better // diagnostic in the case the class is not found in the CINT ClassInfo table. Bool_t autoloaderr = kFALSE; if (!fromFile && gCint->AutoLoad(localname) != 1) autoloaderr = kTRUE; ClassInfo_t *cl = gCint->ClassInfo_Factory(); Bool_t ok = kFALSE; Bool_t nameFound = kFALSE; while (gCint->ClassInfo_Next(cl)) { if (localname == gCint->ClassInfo_FullName(cl)) { nameFound = kTRUE; if (gCint->ClassInfo_IsBase(cl,"TSelector")) ok = kTRUE; break; } } if (!ok) { if (fromFile) { if (nameFound) { ::Error("TSelector::GetSelector", "The class %s in file %s does not derive from TSelector.", localname.Data(), filename); } else { ::Error("TSelector::GetSelector", "The file %s does not define a class named %s.", filename, localname.Data()); } } else { if (autoloaderr) ::Error("TSelector::GetSelector", "class %s could not be loaded", filename); else ::Error("TSelector::GetSelector", "class %s does not exist or does not derive from TSelector", filename); } return 0; } // we can now create an instance of the class TSelector *selector = (TSelector*)gCint->ClassInfo_New(cl); if (!selector || isCompiled) return selector; //interpreted selector: cannot be used as such //create a fake selector TSelectorCint *select = new TSelectorCint(); select->Build(selector, cl); gCint->ClassInfo_Delete(cl); return select; } //______________________________________________________________________________ Bool_t TSelector::IsStandardDraw(const char *selec) { // Find out if this is a standard selection used for Draw actions // (either TSelectorDraw, TProofDraw or deriving from them). // Make sure we have a name if (!selec) { ::Info("TSelector::IsStandardDraw", "selector name undefined - do nothing"); return kFALSE; } Bool_t stdselec = kFALSE; if (!strchr(selec, '.')) { if (strstr(selec, "TSelectorDraw")) { stdselec = kTRUE; } else { TClass *cl = TClass::GetClass(selec); if (cl && (cl->InheritsFrom("TProofDraw") || cl->InheritsFrom("TSelectorDraw"))) stdselec = kTRUE; } } // We are done return stdselec; } <|endoftext|>
<commit_before>//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility may be invoked in the following manner: // llvm-link a.bc b.bc c.bc -o x.bc // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/AutoUpgrade.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/ModuleSummaryIndex.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Linker/Linker.h" #include "llvm/Object/ModuleSummaryIndexObjectFile.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SystemUtils.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Transforms/Utils/FunctionImportUtils.h" #include <memory> using namespace llvm; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::list<std::string> OverridingInputs( "override", cl::ZeroOrMore, cl::value_desc("filename"), cl::desc( "input bitcode file which can override previously defined symbol(s)")); // Option to simulate function importing for testing. This enables using // llvm-link to simulate ThinLTO backend processes. static cl::list<std::string> Imports( "import", cl::ZeroOrMore, cl::value_desc("function:filename"), cl::desc("Pair of function name and filename, where function should be " "imported from bitcode in filename")); // Option to support testing of function importing. The module summary // must be specified in the case were we request imports via the -import // option, as well as when compiling any module with functions that may be // exported (imported by a different llvm-link -import invocation), to ensure // consistent promotion and renaming of locals. static cl::opt<std::string> SummaryIndex("summary-index", cl::desc("Module summary index filename"), cl::init(""), cl::value_desc("filename")); static cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::init("-"), cl::value_desc("filename")); static cl::opt<bool> Internalize("internalize", cl::desc("Internalize linked symbols")); static cl::opt<bool> OnlyNeeded("only-needed", cl::desc("Link only needed symbols")); static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals")); static cl::opt<bool> OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden); static cl::opt<bool> Verbose("v", cl::desc("Print information about actions taken")); static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden); static cl::opt<bool> SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"), cl::init(false)); static cl::opt<bool> PreserveModules("preserve-modules", cl::desc("Preserve linked modules for testing")); static cl::opt<bool> PreserveBitcodeUseListOrder( "preserve-bc-uselistorder", cl::desc("Preserve use-list order when writing LLVM bitcode."), cl::init(true), cl::Hidden); static cl::opt<bool> PreserveAssemblyUseListOrder( "preserve-ll-uselistorder", cl::desc("Preserve use-list order when writing LLVM assembly."), cl::init(false), cl::Hidden); // Read the specified bitcode file in and return it. This routine searches the // link path for the specified file to try to find it... // static std::unique_ptr<Module> loadFile(const char *argv0, const std::string &FN, LLVMContext &Context, bool MaterializeMetadata = true) { SMDiagnostic Err; if (Verbose) errs() << "Loading '" << FN << "'\n"; std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata); if (!Result) Err.print(argv0, errs()); if (MaterializeMetadata) { Result->materializeMetadata(); UpgradeDebugInfo(*Result); } return Result; } static void diagnosticHandler(const DiagnosticInfo &DI) { unsigned Severity = DI.getSeverity(); switch (Severity) { case DS_Error: errs() << "ERROR: "; break; case DS_Warning: if (SuppressWarnings) return; errs() << "WARNING: "; break; case DS_Remark: case DS_Note: llvm_unreachable("Only expecting warnings and errors"); } DiagnosticPrinterRawOStream DP(errs()); DI.print(DP); errs() << '\n'; } static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) { diagnosticHandler(DI); } /// Import any functions requested via the -import option. static bool importFunctions(const char *argv0, LLVMContext &Context, Linker &L) { StringMap<std::unique_ptr<DenseMap<unsigned, MDNode *>>> ModuleToTempMDValsMap; for (const auto &Import : Imports) { // Identify the requested function and its bitcode source file. size_t Idx = Import.find(':'); if (Idx == std::string::npos) { errs() << "Import parameter bad format: " << Import << "\n"; return false; } std::string FunctionName = Import.substr(0, Idx); std::string FileName = Import.substr(Idx + 1, std::string::npos); // Load the specified source module. std::unique_ptr<Module> M = loadFile(argv0, FileName, Context, false); if (!M.get()) { errs() << argv0 << ": error loading file '" << FileName << "'\n"; return false; } if (verifyModule(*M, &errs())) { errs() << argv0 << ": " << FileName << ": error: input module is broken!\n"; return false; } Function *F = M->getFunction(FunctionName); if (!F) { errs() << "Ignoring import request for non-existent function " << FunctionName << " from " << FileName << "\n"; continue; } // We cannot import weak_any functions without possibly affecting the // order they are seen and selected by the linker, changing program // semantics. if (F->hasWeakAnyLinkage()) { errs() << "Ignoring import request for weak-any function " << FunctionName << " from " << FileName << "\n"; continue; } if (Verbose) errs() << "Importing " << FunctionName << " from " << FileName << "\n"; // Link in the specified function. DenseSet<const GlobalValue *> GlobalsToImport; GlobalsToImport.insert(F); if (!SummaryIndex.empty()) { ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler); std::error_code EC = IndexOrErr.getError(); if (EC) { errs() << EC.message() << '\n'; return false; } auto Index = std::move(IndexOrErr.get()); // Linkage Promotion and renaming if (renameModuleForThinLTO(*M, *Index, &GlobalsToImport)) return true; } // Save the mapping of value ids to temporary metadata created when // importing this function. If we have already imported from this module, // add new temporary metadata to the existing mapping. auto &TempMDVals = ModuleToTempMDValsMap[FileName]; if (!TempMDVals) TempMDVals = llvm::make_unique<DenseMap<unsigned, MDNode *>>(); if (L.linkInModule(std::move(M), Linker::Flags::None, &GlobalsToImport, TempMDVals.get())) return false; } // Now link in metadata for all modules from which we imported functions. for (StringMapEntry<std::unique_ptr<DenseMap<unsigned, MDNode *>>> &SME : ModuleToTempMDValsMap) { // Load the specified source module. std::unique_ptr<Module> M = loadFile(argv0, SME.getKey(), Context, true); if (!M.get()) { errs() << argv0 << ": error loading file '" << SME.getKey() << "'\n"; return false; } if (verifyModule(*M, &errs())) { errs() << argv0 << ": " << SME.getKey() << ": error: input module is broken!\n"; return false; } // Link in all necessary metadata from this module. if (L.linkInMetadata(std::move(M), SME.getValue().get())) return false; } return true; } static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L, const cl::list<std::string> &Files, unsigned Flags) { // Filter out flags that don't apply to the first file we load. unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc; for (const auto &File : Files) { std::unique_ptr<Module> M = loadFile(argv0, File, Context); if (!M.get()) { errs() << argv0 << ": error loading file '" << File << "'\n"; return false; } if (verifyModule(*M, &errs())) { errs() << argv0 << ": " << File << ": error: input module is broken!\n"; return false; } // If a module summary index is supplied, load it so linkInModule can treat // local functions/variables as exported and promote if necessary. if (!SummaryIndex.empty()) { ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler); std::error_code EC = IndexOrErr.getError(); if (EC) { errs() << EC.message() << '\n'; return false; } auto Index = std::move(IndexOrErr.get()); // Promotion if (renameModuleForThinLTO(*M, *Index)) return true; } if (Verbose) errs() << "Linking in '" << File << "'\n"; if (L.linkInModule(std::move(M), ApplicableFlags)) return false; // All linker flags apply to linking of subsequent files. ApplicableFlags = Flags; // If requested for testing, preserve modules by releasing them from // the unique_ptr before the are freed. This can help catch any // cross-module references from e.g. unneeded metadata references // that aren't properly set to null but instead mapped to the source // module version. The bitcode writer will assert if it finds any such // cross-module references. if (PreserveModules) M.release(); } return true; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm linker\n"); auto Composite = make_unique<Module>("llvm-link", Context); Linker L(*Composite); unsigned Flags = Linker::Flags::None; if (Internalize) Flags |= Linker::Flags::InternalizeLinkedSymbols; if (OnlyNeeded) Flags |= Linker::Flags::LinkOnlyNeeded; // First add all the regular input files if (!linkFiles(argv[0], Context, L, InputFilenames, Flags)) return 1; // Next the -override ones. if (!linkFiles(argv[0], Context, L, OverridingInputs, Flags | Linker::Flags::OverrideFromSrc)) return 1; // Import any functions requested via -import if (!importFunctions(argv[0], Context, L)) return 1; if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite; std::error_code EC; tool_output_file Out(OutputFilename, EC, sys::fs::F_None); if (EC) { errs() << EC.message() << '\n'; return 1; } if (verifyModule(*Composite, &errs())) { errs() << argv[0] << ": error: linked module is broken!\n"; return 1; } if (Verbose) errs() << "Writing bitcode...\n"; if (OutputAssembly) { Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder); } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true)) WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder); // Declare success. Out.keep(); return 0; } <commit_msg>[ThinLTO] Use bulk importing in llvm-link<commit_after>//===- llvm-link.cpp - Low-level LLVM linker ------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility may be invoked in the following manner: // llvm-link a.bc b.bc c.bc -o x.bc // //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/Bitcode/ReaderWriter.h" #include "llvm/IR/AutoUpgrade.h" #include "llvm/IR/DiagnosticInfo.h" #include "llvm/IR/DiagnosticPrinter.h" #include "llvm/IR/LLVMContext.h" #include "llvm/IR/Module.h" #include "llvm/IR/ModuleSummaryIndex.h" #include "llvm/IR/Verifier.h" #include "llvm/IRReader/IRReader.h" #include "llvm/Linker/Linker.h" #include "llvm/Object/ModuleSummaryIndexObjectFile.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SystemUtils.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Transforms/Utils/FunctionImportUtils.h" #include <memory> using namespace llvm; static cl::list<std::string> InputFilenames(cl::Positional, cl::OneOrMore, cl::desc("<input bitcode files>")); static cl::list<std::string> OverridingInputs( "override", cl::ZeroOrMore, cl::value_desc("filename"), cl::desc( "input bitcode file which can override previously defined symbol(s)")); // Option to simulate function importing for testing. This enables using // llvm-link to simulate ThinLTO backend processes. static cl::list<std::string> Imports( "import", cl::ZeroOrMore, cl::value_desc("function:filename"), cl::desc("Pair of function name and filename, where function should be " "imported from bitcode in filename")); // Option to support testing of function importing. The module summary // must be specified in the case were we request imports via the -import // option, as well as when compiling any module with functions that may be // exported (imported by a different llvm-link -import invocation), to ensure // consistent promotion and renaming of locals. static cl::opt<std::string> SummaryIndex("summary-index", cl::desc("Module summary index filename"), cl::init(""), cl::value_desc("filename")); static cl::opt<std::string> OutputFilename("o", cl::desc("Override output filename"), cl::init("-"), cl::value_desc("filename")); static cl::opt<bool> Internalize("internalize", cl::desc("Internalize linked symbols")); static cl::opt<bool> OnlyNeeded("only-needed", cl::desc("Link only needed symbols")); static cl::opt<bool> Force("f", cl::desc("Enable binary output on terminals")); static cl::opt<bool> OutputAssembly("S", cl::desc("Write output as LLVM assembly"), cl::Hidden); static cl::opt<bool> Verbose("v", cl::desc("Print information about actions taken")); static cl::opt<bool> DumpAsm("d", cl::desc("Print assembly as linked"), cl::Hidden); static cl::opt<bool> SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"), cl::init(false)); static cl::opt<bool> PreserveModules("preserve-modules", cl::desc("Preserve linked modules for testing")); static cl::opt<bool> PreserveBitcodeUseListOrder( "preserve-bc-uselistorder", cl::desc("Preserve use-list order when writing LLVM bitcode."), cl::init(true), cl::Hidden); static cl::opt<bool> PreserveAssemblyUseListOrder( "preserve-ll-uselistorder", cl::desc("Preserve use-list order when writing LLVM assembly."), cl::init(false), cl::Hidden); // Read the specified bitcode file in and return it. This routine searches the // link path for the specified file to try to find it... // static std::unique_ptr<Module> loadFile(const char *argv0, const std::string &FN, LLVMContext &Context, bool MaterializeMetadata = true) { SMDiagnostic Err; if (Verbose) errs() << "Loading '" << FN << "'\n"; std::unique_ptr<Module> Result = getLazyIRFileModule(FN, Err, Context, !MaterializeMetadata); if (!Result) { Err.print(argv0, errs()); return nullptr; } if (MaterializeMetadata) { Result->materializeMetadata(); UpgradeDebugInfo(*Result); } return Result; } namespace { /// Helper to load on demand a Module from file and cache it for subsequent /// queries during function importing. class ModuleLazyLoaderCache { /// Cache of lazily loaded module for import. StringMap<std::unique_ptr<Module>> ModuleMap; /// Retrieve a Module from the cache or lazily load it on demand. std::function<std::unique_ptr<Module>(const char *argv0, const std::string &FileName)> createLazyModule; public: /// Create the loader, Module will be initialized in \p Context. ModuleLazyLoaderCache(std::function<std::unique_ptr<Module>( const char *argv0, const std::string &FileName)> createLazyModule) : createLazyModule(createLazyModule) {} /// Retrieve a Module from the cache or lazily load it on demand. Module &operator()(const char *argv0, const std::string &FileName); std::unique_ptr<Module> takeModule(const std::string &FileName) { auto I = ModuleMap.find(FileName); assert(I != ModuleMap.end()); std::unique_ptr<Module> Ret = std::move(I->second); ModuleMap.erase(I); return Ret; } }; // Get a Module for \p FileName from the cache, or load it lazily. Module &ModuleLazyLoaderCache::operator()(const char *argv0, const std::string &Identifier) { auto &Module = ModuleMap[Identifier]; if (!Module) Module = createLazyModule(argv0, Identifier); return *Module; } } // anonymous namespace static void diagnosticHandler(const DiagnosticInfo &DI) { unsigned Severity = DI.getSeverity(); switch (Severity) { case DS_Error: errs() << "ERROR: "; break; case DS_Warning: if (SuppressWarnings) return; errs() << "WARNING: "; break; case DS_Remark: case DS_Note: llvm_unreachable("Only expecting warnings and errors"); } DiagnosticPrinterRawOStream DP(errs()); DI.print(DP); errs() << '\n'; } static void diagnosticHandlerWithContext(const DiagnosticInfo &DI, void *C) { diagnosticHandler(DI); } /// Import any functions requested via the -import option. static bool importFunctions(const char *argv0, LLVMContext &Context, Linker &L) { if (SummaryIndex.empty()) return true; ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler); std::error_code EC = IndexOrErr.getError(); if (EC) { errs() << EC.message() << '\n'; return false; } auto Index = std::move(IndexOrErr.get()); // Map of Module -> List of globals to import from the Module std::map<StringRef, DenseSet<const GlobalValue *>> ModuleToGlobalsToImportMap; auto ModuleLoader = [&Context](const char *argv0, const std::string &Identifier) { return loadFile(argv0, Identifier, Context, false); }; ModuleLazyLoaderCache ModuleLoaderCache(ModuleLoader); for (const auto &Import : Imports) { // Identify the requested function and its bitcode source file. size_t Idx = Import.find(':'); if (Idx == std::string::npos) { errs() << "Import parameter bad format: " << Import << "\n"; return false; } std::string FunctionName = Import.substr(0, Idx); std::string FileName = Import.substr(Idx + 1, std::string::npos); // Load the specified source module. auto &SrcModule = ModuleLoaderCache(argv0, FileName); if (verifyModule(SrcModule, &errs())) { errs() << argv0 << ": " << FileName << ": error: input module is broken!\n"; return false; } Function *F = SrcModule.getFunction(FunctionName); if (!F) { errs() << "Ignoring import request for non-existent function " << FunctionName << " from " << FileName << "\n"; continue; } // We cannot import weak_any functions without possibly affecting the // order they are seen and selected by the linker, changing program // semantics. if (F->hasWeakAnyLinkage()) { errs() << "Ignoring import request for weak-any function " << FunctionName << " from " << FileName << "\n"; continue; } if (Verbose) errs() << "Importing " << FunctionName << " from " << FileName << "\n"; auto &Entry = ModuleToGlobalsToImportMap[SrcModule.getModuleIdentifier()]; Entry.insert(F); F->materialize(); } // Do the actual import of globals now, one Module at a time for (auto &GlobalsToImportPerModule : ModuleToGlobalsToImportMap) { // Get the module for the import auto &GlobalsToImport = GlobalsToImportPerModule.second; std::unique_ptr<Module> SrcModule = ModuleLoaderCache.takeModule(GlobalsToImportPerModule.first); assert(&Context == &SrcModule->getContext() && "Context mismatch"); // If modules were created with lazy metadata loading, materialize it // now, before linking it (otherwise this will be a noop). SrcModule->materializeMetadata(); UpgradeDebugInfo(*SrcModule); // Linkage Promotion and renaming if (renameModuleForThinLTO(*SrcModule, *Index, &GlobalsToImport)) return true; if (L.linkInModule(std::move(SrcModule), Linker::Flags::None, &GlobalsToImport)) return false; } return true; } static bool linkFiles(const char *argv0, LLVMContext &Context, Linker &L, const cl::list<std::string> &Files, unsigned Flags) { // Filter out flags that don't apply to the first file we load. unsigned ApplicableFlags = Flags & Linker::Flags::OverrideFromSrc; for (const auto &File : Files) { std::unique_ptr<Module> M = loadFile(argv0, File, Context); if (!M.get()) { errs() << argv0 << ": error loading file '" << File << "'\n"; return false; } if (verifyModule(*M, &errs())) { errs() << argv0 << ": " << File << ": error: input module is broken!\n"; return false; } // If a module summary index is supplied, load it so linkInModule can treat // local functions/variables as exported and promote if necessary. if (!SummaryIndex.empty()) { ErrorOr<std::unique_ptr<ModuleSummaryIndex>> IndexOrErr = llvm::getModuleSummaryIndexForFile(SummaryIndex, diagnosticHandler); std::error_code EC = IndexOrErr.getError(); if (EC) { errs() << EC.message() << '\n'; return false; } auto Index = std::move(IndexOrErr.get()); // Promotion if (renameModuleForThinLTO(*M, *Index)) return true; } if (Verbose) errs() << "Linking in '" << File << "'\n"; if (L.linkInModule(std::move(M), ApplicableFlags)) return false; // All linker flags apply to linking of subsequent files. ApplicableFlags = Flags; // If requested for testing, preserve modules by releasing them from // the unique_ptr before the are freed. This can help catch any // cross-module references from e.g. unneeded metadata references // that aren't properly set to null but instead mapped to the source // module version. The bitcode writer will assert if it finds any such // cross-module references. if (PreserveModules) M.release(); } return true; } int main(int argc, char **argv) { // Print a stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(); PrettyStackTraceProgram X(argc, argv); LLVMContext &Context = getGlobalContext(); Context.setDiagnosticHandler(diagnosticHandlerWithContext, nullptr, true); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. cl::ParseCommandLineOptions(argc, argv, "llvm linker\n"); auto Composite = make_unique<Module>("llvm-link", Context); Linker L(*Composite); unsigned Flags = Linker::Flags::None; if (Internalize) Flags |= Linker::Flags::InternalizeLinkedSymbols; if (OnlyNeeded) Flags |= Linker::Flags::LinkOnlyNeeded; // First add all the regular input files if (!linkFiles(argv[0], Context, L, InputFilenames, Flags)) return 1; // Next the -override ones. if (!linkFiles(argv[0], Context, L, OverridingInputs, Flags | Linker::Flags::OverrideFromSrc)) return 1; // Import any functions requested via -import if (!importFunctions(argv[0], Context, L)) return 1; if (DumpAsm) errs() << "Here's the assembly:\n" << *Composite; std::error_code EC; tool_output_file Out(OutputFilename, EC, sys::fs::F_None); if (EC) { errs() << EC.message() << '\n'; return 1; } if (verifyModule(*Composite, &errs())) { errs() << argv[0] << ": error: linked module is broken!\n"; return 1; } if (Verbose) errs() << "Writing bitcode...\n"; if (OutputAssembly) { Composite->print(Out.os(), nullptr, PreserveAssemblyUseListOrder); } else if (Force || !CheckBitcodeOutputToConsole(Out.os(), true)) WriteBitcodeToFile(Composite.get(), Out.os(), PreserveBitcodeUseListOrder); // Declare success. Out.keep(); return 0; } <|endoftext|>
<commit_before>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice 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 Rice University 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: Ioan Sucan */ #include "ompl/base/StateSampler.h" #include "ompl/base/StateSpace.h" void ompl::base::CompoundStateSampler::addSampler(const StateSamplerPtr &sampler, double weightImportance) { samplers_.push_back(sampler); weightImportance_.push_back(weightImportance); samplerCount_ = samplers_.size(); } void ompl::base::CompoundStateSampler::sampleUniform(State *state) { State **comps = state->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i) samplers_[i]->sampleUniform(comps[i]); } void ompl::base::CompoundStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { State **comps = state->as<CompoundState>()->components; State **nearComps = near->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i){ std::cout << "weightInportance[" << i << "] : " << weightImportance_[i] << std::endl; if (weightImportance_[i] > std::numeric_limits<double>::epsilon()) samplers_[i]->sampleUniformNear(comps[i], nearComps[i], distance * weightImportance_[i]); else samplers_[i]->sampleUniform(comps[i]); } } void ompl::base::CompoundStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { State **comps = state->as<CompoundState>()->components; State **meanComps = mean->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i) samplers_[i]->sampleGaussian(comps[i], meanComps[i], stdDev * weightImportance_[i]); } ompl::base::SubspaceStateSampler::SubspaceStateSampler(const StateSpace *space, const StateSpace *subspace, double weight) : StateSampler(space), subspace_(subspace), weight_(weight) { work_ = subspace_->allocState(); work2_ = subspace_->allocState(); subspaceSampler_ = subspace_->allocStateSampler(); space_->getCommonSubspaces(subspace_, subspaces_); if (subspaces_.empty()) OMPL_WARN("Subspace state sampler did not find any common subspaces. Sampling will have no effect."); } ompl::base::SubspaceStateSampler::~SubspaceStateSampler() { subspace_->freeState(work_); subspace_->freeState(work2_); } void ompl::base::SubspaceStateSampler::sampleUniform(State *state) { subspaceSampler_->sampleUniform(work_); copyStateData(space_, state, subspace_, work_, subspaces_); } void ompl::base::SubspaceStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { copyStateData(subspace_, work2_, space_, near); subspaceSampler_->sampleUniformNear(work_, work2_, distance * weight_); copyStateData(space_, state, subspace_, work_, subspaces_); } void ompl::base::SubspaceStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { copyStateData(subspace_, work2_, space_, mean); subspaceSampler_->sampleGaussian(work_, work2_, stdDev * weight_); copyStateData(space_, state, subspace_, work_, subspaces_); } <commit_msg>[modify] delete comment fase<commit_after>/********************************************************************* * Software License Agreement (BSD License) * * Copyright (c) 2010, Rice 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 Rice University 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: Ioan Sucan */ #include "ompl/base/StateSampler.h" #include "ompl/base/StateSpace.h" void ompl::base::CompoundStateSampler::addSampler(const StateSamplerPtr &sampler, double weightImportance) { samplers_.push_back(sampler); weightImportance_.push_back(weightImportance); samplerCount_ = samplers_.size(); } void ompl::base::CompoundStateSampler::sampleUniform(State *state) { State **comps = state->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i) samplers_[i]->sampleUniform(comps[i]); } void ompl::base::CompoundStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { State **comps = state->as<CompoundState>()->components; State **nearComps = near->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i){ if (weightImportance_[i] > std::numeric_limits<double>::epsilon()) samplers_[i]->sampleUniformNear(comps[i], nearComps[i], distance * weightImportance_[i]); else samplers_[i]->sampleUniform(comps[i]); } } void ompl::base::CompoundStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { State **comps = state->as<CompoundState>()->components; State **meanComps = mean->as<CompoundState>()->components; for (unsigned int i = 0 ; i < samplerCount_ ; ++i) samplers_[i]->sampleGaussian(comps[i], meanComps[i], stdDev * weightImportance_[i]); } ompl::base::SubspaceStateSampler::SubspaceStateSampler(const StateSpace *space, const StateSpace *subspace, double weight) : StateSampler(space), subspace_(subspace), weight_(weight) { work_ = subspace_->allocState(); work2_ = subspace_->allocState(); subspaceSampler_ = subspace_->allocStateSampler(); space_->getCommonSubspaces(subspace_, subspaces_); if (subspaces_.empty()) OMPL_WARN("Subspace state sampler did not find any common subspaces. Sampling will have no effect."); } ompl::base::SubspaceStateSampler::~SubspaceStateSampler() { subspace_->freeState(work_); subspace_->freeState(work2_); } void ompl::base::SubspaceStateSampler::sampleUniform(State *state) { subspaceSampler_->sampleUniform(work_); copyStateData(space_, state, subspace_, work_, subspaces_); } void ompl::base::SubspaceStateSampler::sampleUniformNear(State *state, const State *near, const double distance) { copyStateData(subspace_, work2_, space_, near); subspaceSampler_->sampleUniformNear(work_, work2_, distance * weight_); copyStateData(space_, state, subspace_, work_, subspaces_); } void ompl::base::SubspaceStateSampler::sampleGaussian(State *state, const State *mean, const double stdDev) { copyStateData(subspace_, work2_, space_, mean); subspaceSampler_->sampleGaussian(work_, work2_, stdDev * weight_); copyStateData(space_, state, subspace_, work_, subspaces_); } <|endoftext|>
<commit_before>#include "FilenameTools.h" #include "Settings.h" #include "common/tools.h" #include "common/Exception.h" #include <wx/filename.h> #include <wx/dir.h> namespace d2d { wxString FilenameTools::getFilenameAddTag(const wxString& filename, const wxString& tag, const wxString& extension) { wxString fixed; int start = filename.find_last_of('_'); if (start != -1) { wxString check = filename.substr(start + 1, filename.find_last_of('.') - start - 1); if (check == tag) fixed = filename; else fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension); } else { fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension); } return fixed; } wxString FilenameTools::getFilenameTag(const wxString& filepath) { const size_t start = filepath.find_last_of('_') + 1, end = filepath.find_last_of('.'); return filepath.substr(start, end - start); } wxString FilenameTools::getFilename(const wxString& filepath) { const size_t start = filepath.find_last_of('\\') + 1, end = filepath.find_last_of('.'); return filepath.substr(start, end - start); } wxString FilenameTools::getFilenameWithExtension(const wxString& filepath) { return filepath.substr(filepath.find_last_of('\\') + 1); } wxString FilenameTools::getRelativePath(const wxString& dir, const wxString& absolute) { // size_t start = 0; // while (dir.size() > start && filepath.size() > start && dir[start] == filepath[start]) // ++start; // wxString ret = filepath.substr(start); // ret.Replace('\\', '/'); // return ret; ////////////////////////////////////////////////////////////////////////// wxFileName filename(absolute); filename.MakeRelativeTo(dir); return filename.GetFullPath().ToStdString(); } wxString FilenameTools::getAbsolutePath(const wxString& dir, const wxString& relative) { wxFileName filename(relative); filename.MakeAbsolute(dir); filename.Normalize(); wxString filepath = filename.GetFullPath(); if (!isExist(filepath)) return getExistFilepath(relative, dir); else return filepath; } wxString FilenameTools::getAbsolutePathFromFile(const wxString& base, const wxString& relative) { wxString dir = d2d::FilenameTools::getFileDir(base); return d2d::FilenameTools::getAbsolutePath(dir, relative); } wxString FilenameTools::getFilePathExceptExtension(const wxString& filepath) { return filepath.substr(0, filepath.find_last_of('.')); } wxString FilenameTools::getExtension(const wxString& filepath) { return filepath.substr(filepath.find_last_of('.') + 1); } wxString FilenameTools::getFileDir(const wxString& filepath) { return filepath.substr(0, filepath.find_last_of('\\')); } bool FilenameTools::isExist(const wxString& filepath) { return wxFileName::FileExists(filepath); } wxString FilenameTools::getExistFilepath(const wxString& filepath, const wxString& dir /*= wxEmptyString*/) { wxString filepathFixed = filepath; if (!isExist(filepathFixed)) { wxString filename = filepathFixed = getFilenameWithExtension(filepathFixed); if (!isExist(filepathFixed)) { wxString cwd = wxFileName::GetCwd(); std::set<wxString>::iterator itr = Settings::RESOURCE_PATH.begin(); for ( ; itr != Settings::RESOURCE_PATH.end(); ++itr) { filepathFixed = *itr + filename; if (isExist(filepathFixed)) return filepathFixed; filepathFixed = cwd + *itr + filename; if (isExist(filepathFixed)) return filepathFixed; } if (dir != wxEmptyString) { filepathFixed = dir + filename; if (isExist(filepathFixed)) return filepathFixed; } throw Exception("File: %s don't exist!", filepath.ToStdString().c_str()); return wxEmptyString; } else { return filepathFixed; } } else { return filepathFixed; } } void FilenameTools::formatSeparators(std::string& filepath) { // StringTools::toLower(filepath); const std::string oldVal = "\\", newVal = "/"; for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length()) { if((pos = filepath.find(oldVal, pos)) != std::string::npos) filepath.replace(pos, oldVal.length(), newVal); else break; } } void FilenameTools::fetchAllFiles(const std::string& dirpath, wxArrayString& files) { class DirTraverser : public wxDirTraverser { public: DirTraverser(wxArrayString& files) : _files(files) {} virtual wxDirTraverseResult OnFile(const wxString& filename) { _files.Add(filename); return wxDIR_CONTINUE; } virtual wxDirTraverseResult OnDir(const wxString& dirname) { return wxDIR_CONTINUE; } private: wxArrayString& _files; }; // DirTraverser DirTraverser traverser(files); wxDir dir(dirpath); dir.Traverse(traverser); } } // d2d<commit_msg>[FIXED] FileNameTools兼容'/'<commit_after>#include "FilenameTools.h" #include "Settings.h" #include "common/tools.h" #include "common/Exception.h" #include <wx/filename.h> #include <wx/dir.h> namespace d2d { wxString FilenameTools::getFilenameAddTag(const wxString& filename, const wxString& tag, const wxString& extension) { wxString fixed; int start = filename.find_last_of('_'); if (start != -1) { wxString check = filename.substr(start + 1, filename.find_last_of('.') - start - 1); if (check == tag) fixed = filename; else fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension); } else { fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension); } return fixed; } wxString FilenameTools::getFilenameTag(const wxString& filepath) { const size_t start = filepath.find_last_of('_') + 1, end = filepath.find_last_of('.'); return filepath.substr(start, end - start); } wxString FilenameTools::getFilename(const wxString& filepath) { int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\')); const size_t start = pos_divide + 1, end = filepath.find_last_of('.'); return filepath.substr(start, end - start); } wxString FilenameTools::getFilenameWithExtension(const wxString& filepath) { int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\')); return filepath.substr(pos_divide + 1); } wxString FilenameTools::getRelativePath(const wxString& dir, const wxString& absolute) { wxFileName filename(absolute); filename.MakeRelativeTo(dir); return filename.GetFullPath().ToStdString(); } wxString FilenameTools::getAbsolutePath(const wxString& dir, const wxString& relative) { wxFileName filename(relative); filename.MakeAbsolute(dir); filename.Normalize(); wxString filepath = filename.GetFullPath(); if (!isExist(filepath)) return getExistFilepath(relative, dir); else return filepath; } wxString FilenameTools::getAbsolutePathFromFile(const wxString& base, const wxString& relative) { wxString dir = d2d::FilenameTools::getFileDir(base); return d2d::FilenameTools::getAbsolutePath(dir, relative); } wxString FilenameTools::getFilePathExceptExtension(const wxString& filepath) { return filepath.substr(0, filepath.find_last_of('.')); } wxString FilenameTools::getExtension(const wxString& filepath) { return filepath.substr(filepath.find_last_of('.') + 1); } wxString FilenameTools::getFileDir(const wxString& filepath) { int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\')); return filepath.substr(0, pos_divide); } bool FilenameTools::isExist(const wxString& filepath) { return wxFileName::FileExists(filepath); } wxString FilenameTools::getExistFilepath(const wxString& filepath, const wxString& dir /*= wxEmptyString*/) { wxString filepathFixed = filepath; if (!isExist(filepathFixed)) { wxString filename = filepathFixed = getFilenameWithExtension(filepathFixed); if (!isExist(filepathFixed)) { wxString cwd = wxFileName::GetCwd(); std::set<wxString>::iterator itr = Settings::RESOURCE_PATH.begin(); for ( ; itr != Settings::RESOURCE_PATH.end(); ++itr) { filepathFixed = *itr + filename; if (isExist(filepathFixed)) return filepathFixed; filepathFixed = cwd + *itr + filename; if (isExist(filepathFixed)) return filepathFixed; } if (dir != wxEmptyString) { filepathFixed = dir + filename; if (isExist(filepathFixed)) return filepathFixed; } throw Exception("File: %s don't exist!", filepath.ToStdString().c_str()); return wxEmptyString; } else { return filepathFixed; } } else { return filepathFixed; } } void FilenameTools::formatSeparators(std::string& filepath) { // StringTools::toLower(filepath); const std::string oldVal = "\\", newVal = "/"; for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length()) { if((pos = filepath.find(oldVal, pos)) != std::string::npos) filepath.replace(pos, oldVal.length(), newVal); else break; } } void FilenameTools::fetchAllFiles(const std::string& dirpath, wxArrayString& files) { class DirTraverser : public wxDirTraverser { public: DirTraverser(wxArrayString& files) : _files(files) {} virtual wxDirTraverseResult OnFile(const wxString& filename) { _files.Add(filename); return wxDIR_CONTINUE; } virtual wxDirTraverseResult OnDir(const wxString& dirname) { return wxDIR_CONTINUE; } private: wxArrayString& _files; }; // DirTraverser DirTraverser traverser(files); wxDir dir(dirpath); dir.Traverse(traverser); } } // d2d<|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Graphical Effects module. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "pngdumper.h" #include <QtQml/qqml.h> ItemCapturer::ItemCapturer(QQuickItem *parent): QQuickItem(parent) { } ItemCapturer::~ItemCapturer() { } void ItemCapturer::grabItem(QQuickItem *item, QString filename) { QImage img = canvas()->grabFrameBuffer(); while (img.width() * img.height() == 0) img = canvas()->grabFrameBuffer(); QQuickItem *rootItem = canvas()->rootItem(); QRectF rectf = rootItem->mapRectFromItem(item, QRectF(0, 0, item->width(), item->height())); QDir pwd = QDir().dirName(); pwd.mkdir("output"); img = img.copy(rectf.toRect()); img.save("output/" + filename); emit imageSaved(); } void ItemCapturer::document(QString s) { printf(s.toAscii().data()); } <commit_msg>Change uses of {to,from}Ascii to {to,from}Latin1<commit_after>/**************************************************************************** ** ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/ ** ** This file is part of the Qt Graphical Effects module. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "pngdumper.h" #include <QtQml/qqml.h> ItemCapturer::ItemCapturer(QQuickItem *parent): QQuickItem(parent) { } ItemCapturer::~ItemCapturer() { } void ItemCapturer::grabItem(QQuickItem *item, QString filename) { QImage img = canvas()->grabFrameBuffer(); while (img.width() * img.height() == 0) img = canvas()->grabFrameBuffer(); QQuickItem *rootItem = canvas()->rootItem(); QRectF rectf = rootItem->mapRectFromItem(item, QRectF(0, 0, item->width(), item->height())); QDir pwd = QDir().dirName(); pwd.mkdir("output"); img = img.copy(rectf.toRect()); img.save("output/" + filename); emit imageSaved(); } void ItemCapturer::document(QString s) { printf(s.toLatin1().data()); } <|endoftext|>
<commit_before>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //ODA [ BIM BIM-EX RX DB ] #include <BimCommon.h> #include <Common/BmBuildSettings.h> #include <Gs/Gs.h> #include <Database/BmDatabase.h> #include <Database/BmUnitUtils.h> #include <Database/Entities/BmDBDrawing.h> #include <Database/Entities/BmUnitsElem.h> #include <Database/GiContextForBmDatabase.h> #include <Database/Managers/BmUnitsTracking.h> #include <DynamicLinker.h> #include <ExBimHostAppServices.h> #include <ExSystemServices.h> #include <ModelerGeometry/BmModelerModule.h> #include <OdaCommon.h> #include <RxDynamicModule.h> #include <RxDynamicModule.h> #include <RxInit.h> #include <RxObjectImpl.h> #include <StaticRxObject.h> #include "Database/BmGsManager.h" //3d repo bouncer #include "file_processor_rvt.h" #include "data_processor_rvt.h" //help #include "vectorise_device_rvt.h" using namespace repo::manipulator::modelconvertor::odaHelper; const bool USE_NEW_TESSELLATION = true; const double TRIANGULATION_EDGE_LENGTH = 1; const double ROUNDING_ACCURACY = 0.000001; class StubDeviceModuleRvt : public OdGsBaseModule { private: OdBmDatabasePtr database; GeometryCollector *collector; public: void init(GeometryCollector* const collector, OdBmDatabasePtr database) { this->collector = collector; this->database = database; } protected: OdSmartPtr<OdGsBaseVectorizeDevice> createDeviceObject() { return OdRxObjectImpl<VectoriseDeviceRvt, OdGsBaseVectorizeDevice>::createObject(); } OdSmartPtr<OdGsViewImpl> createViewObject() { OdSmartPtr<OdGsViewImpl> pP = OdRxObjectImpl<DataProcessorRvt, OdGsViewImpl>::createObject(); ((DataProcessorRvt*)pP.get())->init(collector, database); return pP; } }; ODRX_DEFINE_PSEUDO_STATIC_MODULE(StubDeviceModuleRvt); class RepoRvtServices : public ExSystemServices, public OdExBimHostAppServices { protected: ODRX_USING_HEAP_OPERATORS(ExSystemServices); }; OdString Get3DLayout(OdDbBaseDatabasePEPtr baseDatabase, OdBmDatabasePtr bimDatabase) { OdString layoutName; OdRxIteratorPtr layouts = baseDatabase->layouts(bimDatabase); for (; !layouts->done(); layouts->next()) { OdBmDBDrawingPtr pDBDrawing = layouts->object(); OdDbBaseLayoutPEPtr pLayout(layouts->object()); if (pDBDrawing->getBaseViewNameFormat() == OdBm::ViewType::_3d) { //set first 3D view available if (layoutName.isEmpty()) layoutName = pLayout->name(layouts->object()); //3D View called "3D" has precedence if (pDBDrawing->getName().find(L"3D") != -1) layoutName = pLayout->name(layouts->object()); //3D view called "3D Repo" should return straight away if (pDBDrawing->getName().find(L"3D Repo") != -1) return pLayout->name(layouts->object()); } } return layoutName; } repo::manipulator::modelconvertor::odaHelper::FileProcessorRvt::~FileProcessorRvt() { } void FileProcessorRvt::setTessellationParams(wrTriangulationParams params) { OdSmartPtr<BmModelerModule> pModModule; OdRxModulePtr pModule = odrxDynamicLinker()->loadModule(OdBmModelerModuleName); if (pModule.get()) { pModModule = BmModelerModule::cast(pModule); pModModule->setTriangulationParams(params); } } void setupUnitsFormat(OdBmDatabasePtr pDb, double accuracy) { OdBmUnitsTrackingPtr pUnitsTracking = pDb->getAppInfo(OdBm::ManagerType::UnitsTracking); OdBmUnitsElemPtr pUnitsElem = pUnitsTracking->getUnitsElemId().safeOpenObject(); if (pUnitsElem.isNull()) return; OdBmAUnitsPtr units = pUnitsElem->getUnits(); if (units.isNull()) return; OdBmFormatOptionsPtrArray formatOptionsArr; units->getFormatOptionsArr(formatOptionsArr); for (uint32_t i = 0; i < formatOptionsArr.size(); i++) { OdBmFormatOptions* formatOptions = formatOptionsArr[i]; //.. NOTE: Here the format of units is configured formatOptions->setAccuracy(accuracy); formatOptions->setRoundingMethod(OdBm::RoundingMethod::Nearest); } } void setupRenderMode(OdBmDatabasePtr database, OdGsDevicePtr device, OdGiContextForBmDatabasePtr bimContext, OdGsView::RenderMode renderMode) { OdGsBmDBDrawingHelperPtr drawingHelper = OdGsBmDBDrawingHelper::setupDBDrawingViews(database->getActiveDBDrawingId(), device, bimContext); auto view = drawingHelper->activeView(); view->setMode(renderMode); } uint8_t FileProcessorRvt::readFile() { int nRes = REPOERR_OK; OdStaticRxObject<RepoRvtServices> svcs; odrxInitialize(&svcs); OdRxModule* pModule = ::odrxDynamicLinker()->loadModule(OdBmLoaderModuleName, false); try { //.. change tessellation params here wrTriangulationParams triParams(USE_NEW_TESSELLATION); setTessellationParams(triParams); odgsInitialize(); OdBmDatabasePtr pDb = svcs.readFile(OdString(file.c_str())); if (!pDb.isNull()) { OdDbBaseDatabasePEPtr pDbPE(pDb); OdString layout = Get3DLayout(pDbPE, pDb); if (layout.isEmpty()) return REPOERR_VALID_3D_VIEW_NOT_FOUND; pDbPE->setCurrentLayout(pDb, layout); OdGiContextForBmDatabasePtr pBimContext = OdGiContextForBmDatabase::createObject(); OdGsModulePtr pGsModule = ODRX_STATIC_MODULE_ENTRY_POINT(StubDeviceModuleRvt)(OD_T("StubDeviceModuleRvt")); ((StubDeviceModuleRvt*)pGsModule.get())->init(collector, pDb); OdGsDevicePtr pDevice = pGsModule->createDevice(); pBimContext->setDatabase(pDb); pDevice = pDbPE->setupActiveLayoutViews(pDevice, pBimContext); // NOTE: Render mode can be kFlatShaded, kGouraudShaded, kFlatShadedWithWireframe, kGouraudShadedWithWireframe // kHiddenLine mode prevents materails from being uploaded // Uncomment the setupRenderMode function call to change render mode //setupRenderMode(pDb, pDevice, pBimContext, OdGsView::kFlatShaded); OdGsDCRect screenRect(OdGsDCPoint(0, 0), OdGsDCPoint(1000, 1000)); //Set the screen space to the borders of the scene pDevice->onSize(screenRect); setupUnitsFormat(pDb, ROUNDING_ACCURACY); pDevice->update(); } } catch (OdError& e) { nRes = REPOERR_LOAD_SCENE_FAIL; repoError << e.description().c_str(); } return nRes; } <commit_msg>ISSUE #315<commit_after>/** * Copyright (C) 2018 3D Repo Ltd * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ //ODA [ BIM BIM-EX RX DB ] #include <BimCommon.h> #include <Common/BmBuildSettings.h> #include <Gs/Gs.h> #include <Database/BmDatabase.h> #include <Database/BmUnitUtils.h> #include <Database/Entities/BmDBDrawing.h> #include <Database/Entities/BmUnitsElem.h> #include <Database/GiContextForBmDatabase.h> #include <Database/Managers/BmUnitsTracking.h> #include <DynamicLinker.h> #include <ExBimHostAppServices.h> #include <ExSystemServices.h> #include <ModelerGeometry/BmModelerModule.h> #include <OdaCommon.h> #include <RxDynamicModule.h> #include <RxDynamicModule.h> #include <RxInit.h> #include <RxObjectImpl.h> #include <StaticRxObject.h> #include "Database/BmGsManager.h" //3d repo bouncer #include "file_processor_rvt.h" #include "data_processor_rvt.h" //help #include "vectorise_device_rvt.h" using namespace repo::manipulator::modelconvertor::odaHelper; const bool USE_NEW_TESSELLATION = true; const double TRIANGULATION_EDGE_LENGTH = 1; const double ROUNDING_ACCURACY = 0.000001; class StubDeviceModuleRvt : public OdGsBaseModule { private: OdBmDatabasePtr database; GeometryCollector *collector; public: void init(GeometryCollector* const collector, OdBmDatabasePtr database) { this->collector = collector; this->database = database; } protected: OdSmartPtr<OdGsBaseVectorizeDevice> createDeviceObject() { return OdRxObjectImpl<VectoriseDeviceRvt, OdGsBaseVectorizeDevice>::createObject(); } OdSmartPtr<OdGsViewImpl> createViewObject() { OdSmartPtr<OdGsViewImpl> pP = OdRxObjectImpl<DataProcessorRvt, OdGsViewImpl>::createObject(); ((DataProcessorRvt*)pP.get())->init(collector, database); return pP; } }; ODRX_DEFINE_PSEUDO_STATIC_MODULE(StubDeviceModuleRvt); class RepoRvtServices : public ExSystemServices, public OdExBimHostAppServices { protected: ODRX_USING_HEAP_OPERATORS(ExSystemServices); }; OdString Get3DLayout(OdDbBaseDatabasePEPtr baseDatabase, OdBmDatabasePtr bimDatabase) { OdString layoutName; OdRxIteratorPtr layouts = baseDatabase->layouts(bimDatabase); for (; !layouts->done(); layouts->next()) { OdBmDBDrawingPtr pDBDrawing = layouts->object(); OdDbBaseLayoutPEPtr pLayout(layouts->object()); if (pDBDrawing->getBaseViewNameFormat() == OdBm::ViewType::_3d) { //set first 3D view available if (layoutName.isEmpty()) layoutName = pLayout->name(layouts->object()); //3D View called "3D" has precedence if (pDBDrawing->getName().iCompare("{3D}") == 0) { repoInfo << "Found default named 3D view."; layoutName = pLayout->name(layouts->object()); } //3D view called "3D Repo" should return straight away if (pDBDrawing->getName().iCompare("3D Repo") == 0) { repoInfo << "Found 3D view named 3D Repo."; return pLayout->name(layouts->object()); } } } return layoutName; } repo::manipulator::modelconvertor::odaHelper::FileProcessorRvt::~FileProcessorRvt() { } void FileProcessorRvt::setTessellationParams(wrTriangulationParams params) { OdSmartPtr<BmModelerModule> pModModule; OdRxModulePtr pModule = odrxDynamicLinker()->loadModule(OdBmModelerModuleName); if (pModule.get()) { pModModule = BmModelerModule::cast(pModule); pModModule->setTriangulationParams(params); } } void setupUnitsFormat(OdBmDatabasePtr pDb, double accuracy) { OdBmUnitsTrackingPtr pUnitsTracking = pDb->getAppInfo(OdBm::ManagerType::UnitsTracking); OdBmUnitsElemPtr pUnitsElem = pUnitsTracking->getUnitsElemId().safeOpenObject(); if (pUnitsElem.isNull()) return; OdBmAUnitsPtr units = pUnitsElem->getUnits(); if (units.isNull()) return; OdBmFormatOptionsPtrArray formatOptionsArr; units->getFormatOptionsArr(formatOptionsArr); for (uint32_t i = 0; i < formatOptionsArr.size(); i++) { OdBmFormatOptions* formatOptions = formatOptionsArr[i]; //.. NOTE: Here the format of units is configured formatOptions->setAccuracy(accuracy); formatOptions->setRoundingMethod(OdBm::RoundingMethod::Nearest); } } void setupRenderMode(OdBmDatabasePtr database, OdGsDevicePtr device, OdGiContextForBmDatabasePtr bimContext, OdGsView::RenderMode renderMode) { OdGsBmDBDrawingHelperPtr drawingHelper = OdGsBmDBDrawingHelper::setupDBDrawingViews(database->getActiveDBDrawingId(), device, bimContext); auto view = drawingHelper->activeView(); view->setMode(renderMode); } uint8_t FileProcessorRvt::readFile() { int nRes = REPOERR_OK; OdStaticRxObject<RepoRvtServices> svcs; odrxInitialize(&svcs); OdRxModule* pModule = ::odrxDynamicLinker()->loadModule(OdBmLoaderModuleName, false); try { //.. change tessellation params here wrTriangulationParams triParams(USE_NEW_TESSELLATION); setTessellationParams(triParams); odgsInitialize(); OdBmDatabasePtr pDb = svcs.readFile(OdString(file.c_str())); if (!pDb.isNull()) { OdDbBaseDatabasePEPtr pDbPE(pDb); OdString layout = Get3DLayout(pDbPE, pDb); repoInfo << "Using 3D View: " << convertToStdString(layout); if (layout.isEmpty()) return REPOERR_VALID_3D_VIEW_NOT_FOUND; pDbPE->setCurrentLayout(pDb, layout); OdGiContextForBmDatabasePtr pBimContext = OdGiContextForBmDatabase::createObject(); OdGsModulePtr pGsModule = ODRX_STATIC_MODULE_ENTRY_POINT(StubDeviceModuleRvt)(OD_T("StubDeviceModuleRvt")); ((StubDeviceModuleRvt*)pGsModule.get())->init(collector, pDb); OdGsDevicePtr pDevice = pGsModule->createDevice(); pBimContext->setDatabase(pDb); pDevice = pDbPE->setupActiveLayoutViews(pDevice, pBimContext); // NOTE: Render mode can be kFlatShaded, kGouraudShaded, kFlatShadedWithWireframe, kGouraudShadedWithWireframe // kHiddenLine mode prevents materails from being uploaded // Uncomment the setupRenderMode function call to change render mode //setupRenderMode(pDb, pDevice, pBimContext, OdGsView::kFlatShaded); OdGsDCRect screenRect(OdGsDCPoint(0, 0), OdGsDCPoint(1000, 1000)); //Set the screen space to the borders of the scene pDevice->onSize(screenRect); setupUnitsFormat(pDb, ROUNDING_ACCURACY); pDevice->update(); } } catch (OdError& e) { nRes = REPOERR_LOAD_SCENE_FAIL; repoError << e.description().c_str(); } return nRes; } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: swframeposstrings.hxx,v $ * * $Revision: 1.3 $ * * last change: $Author: od $ $Date: 2004-08-12 14:00:55 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVXSWFRAMEPOSSTRINGS_HXX #define _SVXSWFRAMEPOSSTRINGS_HXX #ifndef _STRING_HXX #include <tools/string.hxx> #endif /* -----------------04.03.2004 12:58----------------- contains strings needed for positioning dialogs of frames and drawing in Writer --------------------------------------------------*/ class SvxSwFramePosString_Impl; class SvxSwFramePosString { SvxSwFramePosString_Impl* pImpl; public: SvxSwFramePosString(); ~SvxSwFramePosString(); enum StringId { LEFT , RIGHT , FROMLEFT , MIR_LEFT , MIR_RIGHT , MIR_FROMLEFT , FRAME , PRTAREA , REL_PG_LEFT , REL_PG_RIGHT , REL_FRM_LEFT , REL_FRM_RIGHT , MIR_REL_PG_LEFT , MIR_REL_PG_RIGHT , MIR_REL_FRM_LEFT , MIR_REL_FRM_RIGHT , REL_PG_FRAME , REL_PG_PRTAREA , REL_BASE , REL_CHAR , REL_ROW , REL_BORDER , REL_PRTAREA , FLY_REL_PG_LEFT , FLY_REL_PG_RIGHT , FLY_REL_PG_FRAME , FLY_REL_PG_PRTAREA , FLY_MIR_REL_PG_LEFT , FLY_MIR_REL_PG_RIGHT , TOP, BOTTOM, CENTER_HORI, CENTER_VERT, FROMTOP, FROMBOTTOM, BELOW, FROMRIGHT, REL_PG_TOP, REL_PG_BOTTOM, REL_FRM_TOP, REL_FRM_BOTTOM, REL_LINE, STR_MAX }; const String& GetString(StringId eId); }; #endif <commit_msg>INTEGRATION: CWS visibility01 (1.3.118); FILE MERGED 2004/12/06 08:10:49 mnicel 1.3.118.1: Part of symbol visibility markup - #i35758#<commit_after>/************************************************************************* * * $RCSfile: swframeposstrings.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 15:36:09 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SVXSWFRAMEPOSSTRINGS_HXX #define _SVXSWFRAMEPOSSTRINGS_HXX #ifndef _STRING_HXX #include <tools/string.hxx> #endif #ifndef INCLUDED_SVXDLLAPI_H #include "svx/svxdllapi.h" #endif /* -----------------04.03.2004 12:58----------------- contains strings needed for positioning dialogs of frames and drawing in Writer --------------------------------------------------*/ class SvxSwFramePosString_Impl; class SVX_DLLPUBLIC SvxSwFramePosString { SvxSwFramePosString_Impl* pImpl; public: SvxSwFramePosString(); ~SvxSwFramePosString(); enum StringId { LEFT , RIGHT , FROMLEFT , MIR_LEFT , MIR_RIGHT , MIR_FROMLEFT , FRAME , PRTAREA , REL_PG_LEFT , REL_PG_RIGHT , REL_FRM_LEFT , REL_FRM_RIGHT , MIR_REL_PG_LEFT , MIR_REL_PG_RIGHT , MIR_REL_FRM_LEFT , MIR_REL_FRM_RIGHT , REL_PG_FRAME , REL_PG_PRTAREA , REL_BASE , REL_CHAR , REL_ROW , REL_BORDER , REL_PRTAREA , FLY_REL_PG_LEFT , FLY_REL_PG_RIGHT , FLY_REL_PG_FRAME , FLY_REL_PG_PRTAREA , FLY_MIR_REL_PG_LEFT , FLY_MIR_REL_PG_RIGHT , TOP, BOTTOM, CENTER_HORI, CENTER_VERT, FROMTOP, FROMBOTTOM, BELOW, FROMRIGHT, REL_PG_TOP, REL_PG_BOTTOM, REL_FRM_TOP, REL_FRM_BOTTOM, REL_LINE, STR_MAX }; const String& GetString(StringId eId); }; #endif <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: dialmgr.cxx,v $ * * $Revision: 1.3 $ * * last change: $Author: hjs $ $Date: 2004-06-25 11:52:21 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ // include --------------------------------------------------------------- #include "dialmgr.hxx" #include <tools/rc.hxx> #include <svtools/solar.hrc> #include <vcl/svapp.hxx> static ResMgr* pResMgr=0; // struct DialogsResMgr -------------------------------------------------- ResMgr* DialogsResMgr::GetResMgr() { if ( !pResMgr ) { ByteString aName( "svx" ); INT32 nSolarUpd(SOLARUPD); aName += ByteString::CreateFromInt32( nSolarUpd ); pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILocale() ); } return pResMgr; } <commit_msg>INTEGRATION: CWS visibility01 (1.3.224); FILE MERGED 2004/12/06 08:11:25 mnicel 1.3.224.2: Part of symbol visibility markup - #i35758# 2004/11/01 20:17:17 mhu 1.3.224.1: #i35758# Undefine SVX_DLLIMPLEMENTATION for objects going into 'cui' library.<commit_after>/************************************************************************* * * $RCSfile: dialmgr.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: kz $ $Date: 2005-01-21 16:34:33 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ //#ifdef SVX_DLLIMPLEMENTATION //#undef SVX_DLLIMPLEMENTATION //#endif // include --------------------------------------------------------------- #include "dialmgr.hxx" #include <tools/rc.hxx> #include <svtools/solar.hrc> #include <vcl/svapp.hxx> static ResMgr* pResMgr=0; // struct DialogsResMgr -------------------------------------------------- ResMgr* DialogsResMgr::GetResMgr() { if ( !pResMgr ) { ByteString aName( "svx" ); INT32 nSolarUpd(SOLARUPD); aName += ByteString::CreateFromInt32( nSolarUpd ); pResMgr = ResMgr::CreateResMgr( aName.GetBuffer(), Application::GetSettings().GetUILocale() ); } return pResMgr; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optdict.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: hr $ $Date: 2007-06-27 17:26:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _SVX_OPTDICT_HXX #define _SVX_OPTDICT_HXX // include --------------------------------------------------------------- #ifndef _SV_DIALOG_HXX //autogen #include <vcl/dialog.hxx> #endif #ifndef _SV_FIXED_HXX //autogen #include <vcl/fixed.hxx> #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #ifndef _SV_GROUP_HXX //autogen #include <vcl/group.hxx> #endif #ifndef _SV_COMBOBOX_HXX //autogen #include <vcl/combobox.hxx> #endif #ifndef _SV_TIMER_HXX //autogen #include <vcl/timer.hxx> #endif #ifndef _SV_EDIT_HXX //autogen #include <vcl/edit.hxx> #endif #ifndef _SV_DECOVIEW_HXX //autogen #include <vcl/decoview.hxx> #endif #ifndef _COM_SUN_STAR_UTIL_LANGUAGE_HPP_ #include <com/sun/star/util/Language.hpp> #endif #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_UNO_SEQUENCE_HXX_ #include <com/sun/star/uno/Sequence.hxx> #endif #ifndef _SVX_SIMPTABL_HXX #include <svx/simptabl.hxx> #endif #ifndef _SVX_LANGBOX_HXX #include <svx/langbox.hxx> #endif namespace com{namespace sun{namespace star{ namespace linguistic2{ class XDictionary; class XDictionary1; class XSpellChecker1; class XSpellChecker; }}}} // forward --------------------------------------------------------------- // class SvxNewDictionaryDialog ------------------------------------------ class SvxNewDictionaryDialog : public ModalDialog { private: FixedText aNameText; Edit aNameEdit; FixedText aLanguageText; SvxLanguageBox aLanguageLB; CheckBox aExceptBtn; FixedLine aNewDictBox; OKButton aOKBtn; CancelButton aCancelBtn; HelpButton aHelpBtn; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpell; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > xNewDic; #ifdef _SVX_OPTDICT_CXX DECL_LINK( OKHdl_Impl, Button * ); DECL_LINK( ModifyHdl_Impl, Edit * ); #endif public: SvxNewDictionaryDialog( Window* pParent, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xSpl ); ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > GetNewDictionary() { return xNewDic; } }; // class SvxDictEdit ---------------------------------------------------- class SvxDictEdit : public Edit { Link aActionLink; sal_Bool bSpaces; public: SvxDictEdit(Window* pParent, const ResId& rResId) : Edit(pParent, rResId), bSpaces(sal_False){} void SetActionHdl( const Link& rLink ) { aActionLink = rLink;} void SetSpaces(sal_Bool bSet) {bSpaces = bSet;} virtual void KeyInput( const KeyEvent& rKEvent ); }; // class SvxEditDictionaryDialog ----------------------------------------- class SvxEditDictionaryDialog : public ModalDialog { private: FixedText aBookFT; ListBox aAllDictsLB; FixedText aLangFT; SvxLanguageBox aLangLB; FixedText aWordFT; SvxDictEdit aWordED; FixedText aReplaceFT; SvxDictEdit aReplaceED; SvTabListBox aWordsLB; PushButton aNewReplacePB; PushButton aDeletePB; FixedLine aEditDictsBox; CancelButton aCloseBtn; HelpButton aHelpBtn; String sModify; String sNew; DecorationView aDecoView; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary > > aDics; //! snapshot copy to work on ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpell; short nOld; long nWidth; sal_Bool bFirstSelect; sal_Bool bDoNothing; BOOL bDicIsReadonly; #ifdef _SVX_OPTDICT_CXX DECL_LINK( SelectBookHdl_Impl, ListBox * ); DECL_LINK( SelectLangHdl_Impl, ListBox * ); DECL_LINK(SelectHdl, SvTabListBox*); DECL_LINK(NewDelHdl, PushButton*); DECL_LINK(ModifyHdl, Edit*); void ShowWords_Impl( sal_uInt16 nId ); void SetLanguage_Impl( ::com::sun::star::util::Language nLanguage ); sal_Bool IsDicReadonly_Impl() const { return bDicIsReadonly; } void SetDicReadonly_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > &xDic ); void RemoveDictEntry(SvLBoxEntry* pEntry); USHORT GetLBInsertPos(const String &rDicWord); #endif protected: virtual void Paint( const Rectangle& rRect ); public: SvxEditDictionaryDialog( Window* pParent, const String& rName, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1> &xSpl ); ~SvxEditDictionaryDialog(); sal_uInt16 GetSelectedDict() {return aAllDictsLB.GetSelectEntryPos();} }; #endif <commit_msg>INTEGRATION: CWS changefileheader (1.4.368); FILE MERGED 2008/04/01 15:50:27 thb 1.4.368.3: #i85898# Stripping all external header guards 2008/04/01 12:48:17 thb 1.4.368.2: #i85898# Stripping all external header guards 2008/03/31 14:19:58 rt 1.4.368.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: optdict.hxx,v $ * $Revision: 1.5 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef _SVX_OPTDICT_HXX #define _SVX_OPTDICT_HXX // include --------------------------------------------------------------- #include <vcl/dialog.hxx> #include <vcl/fixed.hxx> #include <vcl/lstbox.hxx> #ifndef _SV_BUTTON_HXX //autogen #include <vcl/button.hxx> #endif #include <vcl/group.hxx> #include <vcl/combobox.hxx> #include <vcl/timer.hxx> #include <vcl/edit.hxx> #include <vcl/decoview.hxx> #include <com/sun/star/util/Language.hpp> #include <com/sun/star/uno/Reference.hxx> #include <com/sun/star/uno/Sequence.hxx> #include <svx/simptabl.hxx> #include <svx/langbox.hxx> namespace com{namespace sun{namespace star{ namespace linguistic2{ class XDictionary; class XDictionary1; class XSpellChecker1; class XSpellChecker; }}}} // forward --------------------------------------------------------------- // class SvxNewDictionaryDialog ------------------------------------------ class SvxNewDictionaryDialog : public ModalDialog { private: FixedText aNameText; Edit aNameEdit; FixedText aLanguageText; SvxLanguageBox aLanguageLB; CheckBox aExceptBtn; FixedLine aNewDictBox; OKButton aOKBtn; CancelButton aCancelBtn; HelpButton aHelpBtn; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpell; ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > xNewDic; #ifdef _SVX_OPTDICT_CXX DECL_LINK( OKHdl_Impl, Button * ); DECL_LINK( ModifyHdl_Impl, Edit * ); #endif public: SvxNewDictionaryDialog( Window* pParent, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > &xSpl ); ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > GetNewDictionary() { return xNewDic; } }; // class SvxDictEdit ---------------------------------------------------- class SvxDictEdit : public Edit { Link aActionLink; sal_Bool bSpaces; public: SvxDictEdit(Window* pParent, const ResId& rResId) : Edit(pParent, rResId), bSpaces(sal_False){} void SetActionHdl( const Link& rLink ) { aActionLink = rLink;} void SetSpaces(sal_Bool bSet) {bSpaces = bSet;} virtual void KeyInput( const KeyEvent& rKEvent ); }; // class SvxEditDictionaryDialog ----------------------------------------- class SvxEditDictionaryDialog : public ModalDialog { private: FixedText aBookFT; ListBox aAllDictsLB; FixedText aLangFT; SvxLanguageBox aLangLB; FixedText aWordFT; SvxDictEdit aWordED; FixedText aReplaceFT; SvxDictEdit aReplaceED; SvTabListBox aWordsLB; PushButton aNewReplacePB; PushButton aDeletePB; FixedLine aEditDictsBox; CancelButton aCloseBtn; HelpButton aHelpBtn; String sModify; String sNew; DecorationView aDecoView; ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary > > aDics; //! snapshot copy to work on ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1 > xSpell; short nOld; long nWidth; sal_Bool bFirstSelect; sal_Bool bDoNothing; BOOL bDicIsReadonly; #ifdef _SVX_OPTDICT_CXX DECL_LINK( SelectBookHdl_Impl, ListBox * ); DECL_LINK( SelectLangHdl_Impl, ListBox * ); DECL_LINK(SelectHdl, SvTabListBox*); DECL_LINK(NewDelHdl, PushButton*); DECL_LINK(ModifyHdl, Edit*); void ShowWords_Impl( sal_uInt16 nId ); void SetLanguage_Impl( ::com::sun::star::util::Language nLanguage ); sal_Bool IsDicReadonly_Impl() const { return bDicIsReadonly; } void SetDicReadonly_Impl( ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XDictionary1 > &xDic ); void RemoveDictEntry(SvLBoxEntry* pEntry); USHORT GetLBInsertPos(const String &rDicWord); #endif protected: virtual void Paint( const Rectangle& rRect ); public: SvxEditDictionaryDialog( Window* pParent, const String& rName, ::com::sun::star::uno::Reference< ::com::sun::star::linguistic2::XSpellChecker1> &xSpl ); ~SvxEditDictionaryDialog(); sal_uInt16 GetSelectedDict() {return aAllDictsLB.GetSelectEntryPos();} }; #endif <|endoftext|>
<commit_before>/* * transform_ext.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/reflexion_basis/rebin_pixels.h> #include <dials/algorithms/reflexion_basis/map_frames.h> #include <dials/algorithms/reflexion_basis/beam_vector_map.h> #include <dials/algorithms/reflexion_basis/map_pixels.h> #include <dials/algorithms/reflexion_basis/forward.h> namespace dials { namespace algorithms { namespace reflexion_basis { namespace transform { namespace boost_python { using namespace boost::python; using scitbx::af::int2; using scitbx::af::flex_grid; inline flex_double rebin_pixels_wrapper(const flex_double &input, const flex_vec2_double &inputxy, int2 size) { flex_double output(flex_grid<>(size[0], size[1])); rebin_pixels(output, input, inputxy); return output; } void export_rebin_pixels() { def("rebin_pixels", &rebin_pixels_wrapper, ( arg("input"), arg("inputxy"), arg("size"))); } void export_map_frames() { class_<MapFramesForward>( "MapFramesForward", no_init) .def(init<double, double, double, double, int>(( arg("starting_angle"), arg("oscillation"), arg("mosaicity"), arg("n_sigma"), arg("grid_size_e3")))) .def("__call__", &MapFramesForward::operator(), ( arg("frames"), arg("phi"), arg("zeta"))); class_<MapFramesReverse>( "MapFramesReverse", no_init) .def(init<double, double, double, double, int>(( arg("starting_angle"), arg("oscillation"), arg("mosaicity"), arg("n_sigma"), arg("grid_size_e3")))) .def("__call__", &MapFramesReverse::operator(), ( arg("frames"), arg("phi"), arg("zeta"))); } void export_beam_vector_map() { flex_vec3_double (*overload1)(const Detector&, const Beam&, std::size_t, bool) = &beam_vector_map; flex_vec3_double (*overload2)(const Detector&, const Beam&, bool) = &beam_vector_map; flex_vec3_double (*overload3)(const Detector&, const Beam&) = &beam_vector_map; def("beam_vector_map", overload1, ( arg("detector"), arg("beam"), arg("n_div"), arg("corners"))); def("beam_vector_map", overload2, ( arg("detector"), arg("beam"), arg("corners"))); def("beam_vector_map", overload3, ( arg("detector"), arg("beam"))); } void export_map_pixels() { class_<GridIndexGenerator>("GridIndexGenerator", no_init) .def(init<const CoordinateSystem&, int, int, vec2<double>, std::size_t, const flex_vec3_double>(( arg("cs"), arg("x0"), arg("y0"), arg("step_size"), arg("grid_half_size"), arg("s1_map")))) .def("__call__", &GridIndexGenerator::operator()); flex_double (MapPixelsForward::*call_forward)(const CoordinateSystem&, int6, const flex_double&, const flex_bool&, const flex_double&) const = &MapPixelsForward::operator(); flex_double (MapPixelsReverse::*call_reverse)(const CoordinateSystem&, int6, const flex_double&, const flex_double&) const = &MapPixelsReverse::operator(); class_<MapPixelsForward>("MapPixelsForward", no_init) .def(init<const flex_vec3_double &, std::size_t, vec2<double> >(( arg("s1_map"), arg("grid_half_size"), arg("step_size")))) .def("__call__", call_forward, ( arg("cs"), arg("bbox"), arg("image"), arg("mask"))); class_<MapPixelsReverse>("MapPixelsReverse", no_init) .def(init<const flex_vec3_double &, std::size_t, vec2<double> >(( arg("s1_map"), arg("grid_half_size"), arg("step_size")))) .def("__call__", call_reverse, ( arg("cs"), arg("bbox"), arg("grid"))); } void export_transform() { class_<Forward>("Forward", no_init) .def(init<const Beam&, const Detector&, const Scan&, double, std::size_t, std::size_t>(( arg("beam"), arg("detector"), arg("scan"), arg("mosaicity"), arg("n_sigma"), arg("grid_half_size")))) .def("__call__", &Forward::operator(), ( arg("cs"), arg("bbox"), arg("image"), arg("mask"))); class_<Reverse>("Reverse", no_init) .def(init<const Beam&, const Detector&, const Scan&, double, std::size_t, std::size_t>(( arg("beam"), arg("detector"), arg("scan"), arg("mosaicity"), arg("n_sigma"), arg("grid_half_size")))) .def("__call__", &Forward::operator(), ( arg("cs"), arg("bbox"), arg("grid"))); } BOOST_PYTHON_MODULE(dials_algorithms_reflexion_basis_transform_ext) { export_rebin_pixels(); export_map_frames(); export_beam_vector_map(); export_map_pixels(); } }}}}} // namespace = dials::algorithms::reflexion_basis::transform::boost_python <commit_msg>Modified #include for transform.h<commit_after>/* * transform_ext.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/reflexion_basis/rebin_pixels.h> #include <dials/algorithms/reflexion_basis/map_frames.h> #include <dials/algorithms/reflexion_basis/beam_vector_map.h> #include <dials/algorithms/reflexion_basis/map_pixels.h> #include <dials/algorithms/reflexion_basis/transform.h> namespace dials { namespace algorithms { namespace reflexion_basis { namespace transform { namespace boost_python { using namespace boost::python; using scitbx::af::int2; using scitbx::af::flex_grid; inline flex_double rebin_pixels_wrapper(const flex_double &input, const flex_vec2_double &inputxy, int2 size) { flex_double output(flex_grid<>(size[0], size[1])); rebin_pixels(output, input, inputxy); return output; } void export_rebin_pixels() { def("rebin_pixels", &rebin_pixels_wrapper, ( arg("input"), arg("inputxy"), arg("size"))); } void export_map_frames() { class_<MapFramesForward>( "MapFramesForward", no_init) .def(init<double, double, double, double, int>(( arg("starting_angle"), arg("oscillation"), arg("mosaicity"), arg("n_sigma"), arg("grid_size_e3")))) .def("__call__", &MapFramesForward::operator(), ( arg("frames"), arg("phi"), arg("zeta"))); class_<MapFramesReverse>( "MapFramesReverse", no_init) .def(init<double, double, double, double, int>(( arg("starting_angle"), arg("oscillation"), arg("mosaicity"), arg("n_sigma"), arg("grid_size_e3")))) .def("__call__", &MapFramesReverse::operator(), ( arg("frames"), arg("phi"), arg("zeta"))); } void export_beam_vector_map() { flex_vec3_double (*overload1)(const Detector&, const Beam&, std::size_t, bool) = &beam_vector_map; flex_vec3_double (*overload2)(const Detector&, const Beam&, bool) = &beam_vector_map; flex_vec3_double (*overload3)(const Detector&, const Beam&) = &beam_vector_map; def("beam_vector_map", overload1, ( arg("detector"), arg("beam"), arg("n_div"), arg("corners"))); def("beam_vector_map", overload2, ( arg("detector"), arg("beam"), arg("corners"))); def("beam_vector_map", overload3, ( arg("detector"), arg("beam"))); } void export_map_pixels() { class_<GridIndexGenerator>("GridIndexGenerator", no_init) .def(init<const CoordinateSystem&, int, int, vec2<double>, std::size_t, const flex_vec3_double>(( arg("cs"), arg("x0"), arg("y0"), arg("step_size"), arg("grid_half_size"), arg("s1_map")))) .def("__call__", &GridIndexGenerator::operator()); flex_double (MapPixelsForward::*call_forward)(const CoordinateSystem&, int6, const flex_double&, const flex_bool&, const flex_double&) const = &MapPixelsForward::operator(); flex_double (MapPixelsReverse::*call_reverse)(const CoordinateSystem&, int6, const flex_double&, const flex_double&) const = &MapPixelsReverse::operator(); class_<MapPixelsForward>("MapPixelsForward", no_init) .def(init<const flex_vec3_double &, std::size_t, vec2<double> >(( arg("s1_map"), arg("grid_half_size"), arg("step_size")))) .def("__call__", call_forward, ( arg("cs"), arg("bbox"), arg("image"), arg("mask"))); class_<MapPixelsReverse>("MapPixelsReverse", no_init) .def(init<const flex_vec3_double &, std::size_t, vec2<double> >(( arg("s1_map"), arg("grid_half_size"), arg("step_size")))) .def("__call__", call_reverse, ( arg("cs"), arg("bbox"), arg("grid"))); } void export_transform() { class_<Forward>("Forward", no_init) .def(init<const Beam&, const Detector&, const Scan&, double, std::size_t, std::size_t>(( arg("beam"), arg("detector"), arg("scan"), arg("mosaicity"), arg("n_sigma"), arg("grid_half_size")))) .def("__call__", &Forward::operator(), ( arg("cs"), arg("bbox"), arg("image"), arg("mask"))); class_<Reverse>("Reverse", no_init) .def(init<const Beam&, const Detector&, const Scan&, double, std::size_t, std::size_t>(( arg("beam"), arg("detector"), arg("scan"), arg("mosaicity"), arg("n_sigma"), arg("grid_half_size")))) .def("__call__", &Forward::operator(), ( arg("cs"), arg("bbox"), arg("grid"))); } BOOST_PYTHON_MODULE(dials_algorithms_reflexion_basis_transform_ext) { export_rebin_pixels(); export_map_frames(); export_beam_vector_map(); export_map_pixels(); } }}}}} // namespace = dials::algorithms::reflexion_basis::transform::boost_python <|endoftext|>
<commit_before>void fun(); class Smurf { public: Smurf(); ~Smurf() {} }; namespace foo { void gun(); namespace bar { class Smurf { public: Smurf(); ~Smurf() {} }; } // NS: bar } // NS: foo <commit_msg>test: comment class_func.hpp<commit_after>// should ignore C++ code in global namespace void fun(); class Smurf { public: Smurf(); ~Smurf() {} }; namespace foo { void gun(); namespace bar { class Smurf { public: Smurf(); ~Smurf() {} }; } // NS: bar } // NS: foo <|endoftext|>
<commit_before>/* Copyright (c) 2017, EPL-Vizards * 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 EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file networkgraphmodel.cpp */ #include "networkgraphmodel.hpp" #include "mainwindow.hpp" using namespace EPL_Viz; using namespace EPL_DataCollect; NetworkGraphModel::NetworkGraphModel(MainWindow *mw) { graph = mw->getNetworkGraph(); } NetworkGraphModel::~NetworkGraphModel() {} void NetworkGraphModel::init() {} void NetworkGraphModel::update(Cycle *cycle) { auto list = cycle->getNodeList(); for (uint8_t id : list) { Node *n = cycle->getNode(id); auto s = nodeMap.find(id); if (s == nodeMap.end() || s.key() != id) { // The node is not yet added as a widget and has to be created NodeWidget *nw = new NodeWidget(n, graph); nodeMap.insert(id, nw); graph->layout()->addWidget(nw); } else { // The node is added as widget and has to be updated nodeMap[id]->updateData(n); } } } <commit_msg>Added highlighting to the network graph model<commit_after>/* Copyright (c) 2017, EPL-Vizards * 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 EPL-Vizards 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 EPL-Vizards 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. */ /*! * \file networkgraphmodel.cpp */ #include "networkgraphmodel.hpp" #include "mainwindow.hpp" using namespace EPL_Viz; using namespace EPL_DataCollect; NetworkGraphModel::NetworkGraphModel(MainWindow *mw) { graph = mw->getNetworkGraph(); } NetworkGraphModel::~NetworkGraphModel() {} void NetworkGraphModel::init() {} void NetworkGraphModel::update(Cycle *cycle) { auto list = cycle->getNodeList(); for (uint8_t id : list) { Node *n = cycle->getNode(id); auto s = nodeMap.find(id); if (s == nodeMap.end() || s.key() != id) { // The node is not yet added as a widget and has to be created NodeWidget *nw = new NodeWidget(n, graph); nodeMap.insert(id, nw); graph->layout()->addWidget(nw); } else { // The node is added as widget and has to be updated nodeMap[id]->updateData(n); } nodeMap[id]->setHighlightingLevel(0); } auto events = cycle->getActiveEvents(); for (auto event : events) { switch (event->getType()) { case EvType::VIEW_EV_HIGHLIGHT_MN: case EvType::VIEW_EV_HIGHLIGHT_CN: { uint64_t node = event->getEventFlags(); // EventFlags is the NodeID for these events int level = std::stoi(event->getDescription()); // Description is the highlighting level for these events // Invalid node if (cycle->getNode(node) == nullptr) break; // Check if event valid if ((event->getType() == EvType::VIEW_EV_HIGHLIGHT_CN && node < 240) || (event->getType() == EvType::VIEW_EV_HIGHLIGHT_CN && node == 240)) { // Set highlighting nodeMap[node]->setHighlightingLevel(level); } break; } default: break; } } for (uint8_t id : list) { nodeMap[id]->updateStyleSheet(); } } <|endoftext|>
<commit_before>/* sbus.cpp Copyright (c) 2017, Fabrizio Di Vittorio ([email protected]) 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 */ #include "sbus.h" // quick IO functions #define portOfPin(P) (((P) >= 0 && (P) < 8) ? &PORTD : (((P) > 7 && (P) < 14) ? &PORTB : &PORTC)) #define ddrOfPin(P) (((P) >= 0 && (P) < 8) ? &DDRD : (((P) > 7 && (P) < 14) ? &DDRB : &DDRC)) #define pinOfPin(P) (((P) >= 0 && (P) < 8) ? &PIND : (((P) > 7 && (P) < 14) ? &PINB : &PINC)) #define pinIndex(P) ((uint8_t)(P > 13 ? P - 14 : P & 7)) #define pinMask(P) ((uint8_t)(1 << pinIndex(P))) #define pinAsInput(P) (*(ddrOfPin(P)) &= ~pinMask(P)) #define pinAsInputPullUp(P) (*(ddrOfPin(P)) &= ~pinMask(P); digitalHigh(P)) #define pinAsOutput(P) (*(ddrOfPin(P)) |= pinMask(P)) #define digitalLow(P) (*(portOfPin(P)) &= ~pinMask(P)) #define digitalHigh(P) (*(portOfPin(P)) |= pinMask(P)) #define isHigh(P) ((*(pinOfPin(P)) & pinMask(P)) > 0) #define isLow(P) ((*(pinOfPin(P)) & pinMask(P)) == 0) #define pinGet(pin, mask) (((*(pin)) & (mask)) > 0) static uint8_t * s_pin; static uint8_t s_pinMask; static uint8_t s_PCICRMask; static volatile mode_t s_mode; // contains which word is currently receiving (0..24, 24 is the last word) static volatile uint8_t s_receivingWordIndex = 0; // received frame static volatile uint8_t s_frame[23]; struct chinfo_t { uint8_t idx; uint8_t shift1; uint8_t shift2; uint8_t shift3; // 11 = byte 3 ignored }; static const chinfo_t CHINFO[16] PROGMEM = { {0, 0, 8, 11}, {1, 3, 5, 11}, {2, 6, 2, 10}, {4, 1, 7, 11}, {5, 4, 4, 11}, {6, 7, 1, 9}, {8, 2, 6, 11}, {9, 5, 3, 11}, {11, 0, 8, 11}, {12, 3, 5, 11}, {13, 6, 2, 10}, {15, 1, 7, 11}, {16, 4, 4, 11}, {17, 7, 1, 9}, {19, 2, 6, 11}, {20, 5, 3, 11} }; // flag field #define FLAG_CHANNEL_17 1 #define FLAG_CHANNEL_18 2 #define FLAG_SIGNAL_LOSS 4 #define FLAG_FAILSAFE 8 #define CHANNEL_MIN 173 #define CHANNEL_MAX 1812 inline void enablePinChangeInterrupts() { // clear any outstanding interrupt PCIFR |= s_PCICRMask; // enable interrupt for the group PCICR |= s_PCICRMask; } inline void disablePinChangeInterrupts() { PCICR &= ~s_PCICRMask; } // handle pin change interrupt for D0 to D7 here ISR(PCINT2_vect) { // start bit? if (pinGet(s_pin, s_pinMask) > 0) { // reset timer 2 counter TCNT2 = 0; // start bit received uint8_t receivedBitIndex = 1; uint8_t receivingWord = 0; // receive other bits // reset OCF2A flag by writing "1" TIFR2 |= 1 << OCF2A; uint8_t calc_parity = 0xFF; while (true) { // wait for TCNT2 == OCR2A while (!(TIFR2 & (1 << OCF2A))) ; // reset OCF2A flag by writing "1" TIFR2 |= 1 << OCF2A; // sample current bit if (receivedBitIndex >= 1 && receivedBitIndex <= 8) { if (pinGet(s_pin, s_pinMask) > 0) receivingWord |= 1 << (receivedBitIndex - 1); else calc_parity = ~calc_parity; } // last bit? if (receivedBitIndex == 9) { // check parity uint8_t in_parity = pinGet(s_pin, s_pinMask) > 0; if ((calc_parity && !in_parity) || (!calc_parity && in_parity)) { // parity check failed! s_receivingWordIndex = 0; break; } receivingWord = ~receivingWord; if (s_receivingWordIndex == 0) { // start byte (must be 0x0F) if (receivingWord != 0x0F) { // wrong start byte, restart word count s_receivingWordIndex = 0; break; } } else if (s_receivingWordIndex == 24) { // last word, restart word count if (s_mode == sbusBlocking) disablePinChangeInterrupts(); s_receivingWordIndex = 0; break; } else { // channels and flags s_frame[s_receivingWordIndex - 1] = receivingWord; } // prepare for the next word ++s_receivingWordIndex; break; } else { // other bits required, continue loop ++receivedBitIndex; } // exit loop, a pin change (start bit) is required to restart } // reset pin change interrupt flag PCIFR = 0xFF; } } // used only for blocking operations (mode = sbusBlocking) bool SBUS::waitFrame(uint32_t timeOut) { if (s_mode == sbusBlocking) { enablePinChangeInterrupts(); // wait until Pin change bit return back to 0 uint32_t t0 = millis(); while (PCICR & s_PCICRMask) if (millis() - t0 >= timeOut) // note: this millis() compare is overflow safe due unsigned diffs return false; // timeout! } return true; } // channels start from 1 to 18 // returns value 173..1812 (a received by SBUS) uint16_t SBUS::getChannelRaw(uint8_t channelIndex) { if (channelIndex >= 1 && channelIndex <= 16) { chinfo_t chinfo; memcpy_P(&chinfo, CHINFO + channelIndex - 1, sizeof(chinfo_t)); uint8_t idx = chinfo.idx; noInterrupts(); uint8_t b1 = s_frame[idx++]; uint8_t b2 = s_frame[idx++]; uint8_t b3 = s_frame[idx]; interrupts(); return ((b1 >> chinfo.shift1) | (b2 << chinfo.shift2) | (b3 << chinfo.shift3)) & 0x7FF; } else if (channelIndex == 17 || channelIndex == 18) { if (channelIndex == 17) return s_frame[22] & FLAG_CHANNEL_17 ? CHANNEL_MAX : CHANNEL_MIN; else return s_frame[22] & FLAG_CHANNEL_18 ? CHANNEL_MAX : CHANNEL_MIN; } else return 0; // error } // channels start from 1 to 18 // returns value 988..2012 (cleanflight friendly) uint16_t SBUS::getChannel(uint8_t channelIndex) { return 5 * getChannelRaw(channelIndex) / 8 + 880; } bool SBUS::signalLossActive() { return s_frame[22] & FLAG_SIGNAL_LOSS; } bool SBUS::failsafeActive() { return s_frame[22] & FLAG_FAILSAFE; } // if mode = sbusNonBlocking, an interrupt is always generated for every frame received. getChannel (or getChannelRaw) is no-blocking // if mode = sbusBlocking, interrupts are enabled only inside getChannel (or getChannelRaw), which becomes blocking (until arrive of a new frame) void SBUS::begin(uint8_t pin, mode_t mode) { s_mode = mode; s_pin = pinOfPin(pin); s_pinMask = pinMask(pin); s_PCICRMask = 1 << digitalPinToPCICRbit(pin); //// setup TIMER 2 CTC // select "Clear Timer on Compare (CTC)" mode TCCR2A = 1 << WGM21; // no prescaling TCCR2B = 1 << CS20; // set TOP timer 2 value // with no-prescaler 1/16000000=0.00000000625, each bit requires 10us, so reset timer 2 every 10us, so reset timer every 10/0.0625 = 160 ticks OCR2A = F_CPU / 1000000 * 10 - 1; // for 16MHz = 159; //// setup pin change interrupt pinAsInput(pin); // enable pin *digitalPinToPCMSK(pin) |= 1 << digitalPinToPCMSKbit(pin); if (mode == sbusNonBlocking) enablePinChangeInterrupts(); } <commit_msg>improved compatibility with Servo library<commit_after>/* sbus.cpp Copyright (c) 2017, Fabrizio Di Vittorio ([email protected]) 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 */ #include "sbus.h" // quick IO functions #define portOfPin(P) (((P) >= 0 && (P) < 8) ? &PORTD : (((P) > 7 && (P) < 14) ? &PORTB : &PORTC)) #define ddrOfPin(P) (((P) >= 0 && (P) < 8) ? &DDRD : (((P) > 7 && (P) < 14) ? &DDRB : &DDRC)) #define pinOfPin(P) (((P) >= 0 && (P) < 8) ? &PIND : (((P) > 7 && (P) < 14) ? &PINB : &PINC)) #define pinIndex(P) ((uint8_t)(P > 13 ? P - 14 : P & 7)) #define pinMask(P) ((uint8_t)(1 << pinIndex(P))) #define pinAsInput(P) (*(ddrOfPin(P)) &= ~pinMask(P)) #define pinAsInputPullUp(P) (*(ddrOfPin(P)) &= ~pinMask(P); digitalHigh(P)) #define pinAsOutput(P) (*(ddrOfPin(P)) |= pinMask(P)) #define digitalLow(P) (*(portOfPin(P)) &= ~pinMask(P)) #define digitalHigh(P) (*(portOfPin(P)) |= pinMask(P)) #define isHigh(P) ((*(pinOfPin(P)) & pinMask(P)) > 0) #define isLow(P) ((*(pinOfPin(P)) & pinMask(P)) == 0) #define pinGet(pin, mask) (((*(pin)) & (mask)) > 0) static uint8_t * s_pin; static uint8_t s_pinMask; static uint8_t s_PCICRMask; static volatile mode_t s_mode; // contains which word is currently receiving (0..24, 24 is the last word) static volatile uint8_t s_receivingWordIndex = 0; // received frame static volatile uint8_t s_frame[23]; struct chinfo_t { uint8_t idx; uint8_t shift1; uint8_t shift2; uint8_t shift3; // 11 = byte 3 ignored }; static const chinfo_t CHINFO[16] PROGMEM = { {0, 0, 8, 11}, {1, 3, 5, 11}, {2, 6, 2, 10}, {4, 1, 7, 11}, {5, 4, 4, 11}, {6, 7, 1, 9}, {8, 2, 6, 11}, {9, 5, 3, 11}, {11, 0, 8, 11}, {12, 3, 5, 11}, {13, 6, 2, 10}, {15, 1, 7, 11}, {16, 4, 4, 11}, {17, 7, 1, 9}, {19, 2, 6, 11}, {20, 5, 3, 11} }; // flag field #define FLAG_CHANNEL_17 1 #define FLAG_CHANNEL_18 2 #define FLAG_SIGNAL_LOSS 4 #define FLAG_FAILSAFE 8 #define CHANNEL_MIN 173 #define CHANNEL_MAX 1812 inline void enablePinChangeInterrupts() { // clear any outstanding interrupt PCIFR |= s_PCICRMask; // enable interrupt for the group PCICR |= s_PCICRMask; } inline void disablePinChangeInterrupts() { PCICR &= ~s_PCICRMask; } // handle pin change interrupt for D0 to D7 here ISR(PCINT2_vect) { // start bit? if (pinGet(s_pin, s_pinMask)) { // reset timer 2 counter TCNT2 = 0; disablePinChangeInterrupts(); // start bit received uint8_t receivingWord = 0; // reset OCF2A flag by writing "1" TIFR2 |= 1 << OCF2A; uint8_t parity = 0xFF; // receive other bits (including parity bit, ignore stop bits) for (uint8_t receivedBitIndex = 0; receivedBitIndex < 9; ++receivedBitIndex) { // wait for TCNT2 == OCR2A // warn: inside this loop interrupts are re-enabled to allow other libraries to work correctly (ie Servo library) interrupts(); while (!(TIFR2 & (1 << OCF2A))) ; noInterrupts(); // reset OCF2A flag by writing "1" TIFR2 |= 1 << OCF2A; // sample current bit if (pinGet(s_pin, s_pinMask)) receivingWord |= 1 << receivedBitIndex; // parity shift here as >7 bit, so it is just discarded else parity = ~parity; } // check parity if (!parity) { // parity check failed! s_receivingWordIndex = 0; } else { // parity ok receivingWord = ~receivingWord; if (s_receivingWordIndex == 0) { // check start word (must be 0x0F) if (receivingWord == 0x0F) ++s_receivingWordIndex; // bypass this word } else if (s_receivingWordIndex == 24) { if (receivingWord == 0x00) ++s_receivingWordIndex; // bypass this word } else { // save channels and flags and last ending word s_frame[s_receivingWordIndex - 1] = receivingWord; // next word ++s_receivingWordIndex; } } // reset pin change interrupt flag PCIFR |= s_PCICRMask; if (s_receivingWordIndex < 25 || s_mode == sbusNonBlocking) enablePinChangeInterrupts(); if (s_receivingWordIndex == 25) s_receivingWordIndex = 0; // last word, restart word count } } // used only for blocking operations (mode = sbusBlocking) bool SBUS::waitFrame(uint32_t timeOut) { if (s_mode == sbusBlocking) { // will be disabled inside the ISR enablePinChangeInterrupts(); // wait until Pin change bit return back to 0 uint32_t t0 = millis(); while (PCICR & s_PCICRMask) if (millis() - t0 >= timeOut) // note: this millis() compare is overflow safe due unsigned diffs return false; // timeout! } return true; } // channels start from 1 to 18 // returns value 173..1812 (a received by SBUS) uint16_t SBUS::getChannelRaw(uint8_t channelIndex) { if (channelIndex >= 1 && channelIndex <= 16) { chinfo_t chinfo; memcpy_P(&chinfo, CHINFO + channelIndex - 1, sizeof(chinfo_t)); uint8_t idx = chinfo.idx; noInterrupts(); uint8_t b1 = s_frame[idx++]; uint8_t b2 = s_frame[idx++]; uint8_t b3 = s_frame[idx]; interrupts(); return ((b1 >> chinfo.shift1) | (b2 << chinfo.shift2) | (b3 << chinfo.shift3)) & 0x7FF; } else if (channelIndex == 17 || channelIndex == 18) { if (channelIndex == 17) return s_frame[22] & FLAG_CHANNEL_17 ? CHANNEL_MAX : CHANNEL_MIN; else return s_frame[22] & FLAG_CHANNEL_18 ? CHANNEL_MAX : CHANNEL_MIN; } else return 0; // error } // channels start from 1 to 18 // returns value 988..2012 (cleanflight friendly) uint16_t SBUS::getChannel(uint8_t channelIndex) { return 5 * getChannelRaw(channelIndex) / 8 + 880; } bool SBUS::signalLossActive() { return s_frame[22] & FLAG_SIGNAL_LOSS; } bool SBUS::failsafeActive() { return s_frame[22] & FLAG_FAILSAFE; } // if mode = sbusNonBlocking, an interrupt is always generated for every frame received. getChannel (or getChannelRaw) is no-blocking // if mode = sbusBlocking, interrupts are enabled only inside getChannel (or getChannelRaw), which becomes blocking (until arrive of a new frame) void SBUS::begin(uint8_t pin, mode_t mode) { s_mode = mode; s_pin = pinOfPin(pin); s_pinMask = pinMask(pin); s_PCICRMask = 1 << digitalPinToPCICRbit(pin); //// setup TIMER 2 CTC // select "Clear Timer on Compare (CTC)" mode TCCR2A = 1 << WGM21; // no prescaling TCCR2B = 1 << CS20; // set TOP timer 2 value // with no-prescaler 1/16000000=0.00000000625, each bit requires 10us, so reset timer 2 every 10us, so reset timer every 10/0.0625 = 160 ticks OCR2A = F_CPU / 1000000 * 10 - 1; // for 16MHz = 159; //// setup pin change interrupt pinAsInput(pin); // enable pin *digitalPinToPCMSK(pin) |= 1 << digitalPinToPCMSKbit(pin); if (mode == sbusNonBlocking) enablePinChangeInterrupts(); } <|endoftext|>
<commit_before>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_client.hxx" #include "http_headers.hxx" #include "HttpResponseHandler.hxx" #include "lease.hxx" #include "direct.hxx" #include "PInstance.hxx" #include "pool/pool.hxx" #include "istream/UnusedPtr.hxx" #include "istream/HeadIstream.hxx" #include "istream/BlockIstream.hxx" #include "istream/istream_catch.hxx" #include "istream/Sink.hxx" #include "fb_pool.hxx" #include "fs/FilteredSocket.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include <functional> #include <stdio.h> #include <stdlib.h> class Instance final : HttpServerConnectionHandler, Lease, BufferedSocketHandler { struct pool *pool; HttpServerConnection *connection = nullptr; std::function<void(HttpServerRequest &request, CancellablePointer &cancel_ptr)> request_handler; FilteredSocket client_fs; bool client_fs_released = false; public: Instance(struct pool &_pool, EventLoop &event_loop); ~Instance() noexcept { CheckCloseConnection(); } struct pool &GetPool() noexcept { return *pool; } template<typename T> void SetRequestHandler(T &&handler) noexcept { request_handler = std::forward<T>(handler); } void CloseConnection() noexcept { http_server_connection_close(connection); connection = nullptr; } void CheckCloseConnection() noexcept { if (connection != nullptr) CloseConnection(); } void SendRequest(http_method_t method, const char *uri, HttpHeaders &&headers, UnusedIstreamPtr body, bool expect_100, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) noexcept { http_client_request(*pool, client_fs, *this, "foo", method, uri, std::move(headers), std::move(body), expect_100, handler, cancel_ptr); } void CloseClientSocket() noexcept { if (client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Close(); client_fs.Destroy(); } } private: /* virtual methods from class HttpServerConnectionHandler */ void HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) noexcept override; void LogHttpRequest(HttpServerRequest &, http_status_t, int64_t, uint64_t, uint64_t) noexcept override {} void HttpConnectionError(std::exception_ptr e) noexcept override; void HttpConnectionClosed() noexcept override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) noexcept override { client_fs_released = true; if (reuse && client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this); client_fs.UnscheduleWrite(); } else { CloseClientSocket(); } } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override { fprintf(stderr, "unexpected data in idle TCP connection"); CloseClientSocket(); return BufferedResult::CLOSED; } bool OnBufferedClosed() noexcept override { CloseClientSocket(); return false; } gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override { PrintException(e); CloseClientSocket(); } }; class Client final : HttpResponseHandler, IstreamSink { CancellablePointer client_cancel_ptr; std::exception_ptr response_error; std::string response_body; http_status_t status{}; bool response_eof = false; public: void SendRequest(Instance &instance, http_method_t method, const char *uri, HttpHeaders &&headers, UnusedIstreamPtr body, bool expect_100=false) noexcept { instance.SendRequest(method, uri, std::move(headers), std::move(body), expect_100, *this, client_cancel_ptr); } bool IsClientDone() const noexcept { return response_error || response_eof; } void RethrowResponseError() const { if (response_error) std::rethrow_exception(response_error); } private: /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t _status, StringMap &&headers, UnusedIstreamPtr body) noexcept override { status = _status; (void)headers; IstreamSink::SetInput(std::move(body)); input.Read(); } void OnHttpError(std::exception_ptr ep) noexcept override { response_error = std::move(ep); } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override { response_body.append((const char *)data, length); return length; } void OnEof() noexcept override { IstreamSink::ClearInput(); response_eof = true; } void OnError(std::exception_ptr ep) noexcept override { IstreamSink::ClearInput(); response_error = std::move(ep); } }; Instance::Instance(struct pool &_pool, EventLoop &event_loop) :pool(pool_new_libc(&_pool, "catch")), client_fs(event_loop) { UniqueSocketDescriptor client_socket, server_socket; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0, client_socket, server_socket)) throw MakeErrno("socketpair() failed"); connection = http_server_connection_new(pool, event_loop, std::move(server_socket), FdType::FD_SOCKET, nullptr, nullptr, nullptr, true, *this); client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET); pool_unref(pool); } static std::exception_ptr catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept { PrintException(ep); return {}; } void Instance::HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) noexcept { request_handler(request, cancel_ptr); } void Instance::HttpConnectionError(std::exception_ptr e) noexcept { connection = nullptr; PrintException(e); } void Instance::HttpConnectionClosed() noexcept { connection = nullptr; } static void test_catch(EventLoop &event_loop, struct pool *_pool) { Instance instance(*_pool, event_loop); instance.SetRequestHandler([&instance](HttpServerRequest &request, CancellablePointer &) noexcept { http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool), istream_catch_new(&request.pool, std::move(request.body), catch_callback, nullptr)); instance.CloseConnection(); }); Client client; client.SendRequest(instance, HTTP_METHOD_POST, "/", HttpHeaders(instance.GetPool()), istream_head_new(instance.GetPool(), istream_block_new(instance.GetPool()), 1024, true)); while (!client.IsClientDone()) event_loop.LoopOnce(); instance.CloseClientSocket(); client.RethrowResponseError(); event_loop.Dispatch(); } int main(int argc, char **argv) noexcept try { (void)argc; (void)argv; direct_global_init(); const ScopeFbPoolInit fb_pool_init; PInstance instance; test_catch(instance.event_loop, instance.root_pool); } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <commit_msg>test/t_http_server: rename Instance to Server<commit_after>/* * Copyright 2007-2017 Content Management AG * All rights reserved. * * author: Max Kellermann <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "http_server/http_server.hxx" #include "http_server/Request.hxx" #include "http_server/Handler.hxx" #include "http_client.hxx" #include "http_headers.hxx" #include "HttpResponseHandler.hxx" #include "lease.hxx" #include "direct.hxx" #include "PInstance.hxx" #include "pool/pool.hxx" #include "istream/UnusedPtr.hxx" #include "istream/HeadIstream.hxx" #include "istream/BlockIstream.hxx" #include "istream/istream_catch.hxx" #include "istream/Sink.hxx" #include "fb_pool.hxx" #include "fs/FilteredSocket.hxx" #include "net/UniqueSocketDescriptor.hxx" #include "system/Error.hxx" #include "util/Cancellable.hxx" #include "util/PrintException.hxx" #include <functional> #include <stdio.h> #include <stdlib.h> class Server final : HttpServerConnectionHandler, Lease, BufferedSocketHandler { struct pool *pool; HttpServerConnection *connection = nullptr; std::function<void(HttpServerRequest &request, CancellablePointer &cancel_ptr)> request_handler; FilteredSocket client_fs; bool client_fs_released = false; public: Server(struct pool &_pool, EventLoop &event_loop); ~Server() noexcept { CheckCloseConnection(); } struct pool &GetPool() noexcept { return *pool; } template<typename T> void SetRequestHandler(T &&handler) noexcept { request_handler = std::forward<T>(handler); } void CloseConnection() noexcept { http_server_connection_close(connection); connection = nullptr; } void CheckCloseConnection() noexcept { if (connection != nullptr) CloseConnection(); } void SendRequest(http_method_t method, const char *uri, HttpHeaders &&headers, UnusedIstreamPtr body, bool expect_100, HttpResponseHandler &handler, CancellablePointer &cancel_ptr) noexcept { http_client_request(*pool, client_fs, *this, "foo", method, uri, std::move(headers), std::move(body), expect_100, handler, cancel_ptr); } void CloseClientSocket() noexcept { if (client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Close(); client_fs.Destroy(); } } private: /* virtual methods from class HttpServerConnectionHandler */ void HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) noexcept override; void LogHttpRequest(HttpServerRequest &, http_status_t, int64_t, uint64_t, uint64_t) noexcept override {} void HttpConnectionError(std::exception_ptr e) noexcept override; void HttpConnectionClosed() noexcept override; /* virtual methods from class Lease */ void ReleaseLease(bool reuse) noexcept override { client_fs_released = true; if (reuse && client_fs.IsValid() && client_fs.IsConnected()) { client_fs.Reinit(Event::Duration(-1), Event::Duration(-1), *this); client_fs.UnscheduleWrite(); } else { CloseClientSocket(); } } /* virtual methods from class BufferedSocketHandler */ BufferedResult OnBufferedData() override { fprintf(stderr, "unexpected data in idle TCP connection"); CloseClientSocket(); return BufferedResult::CLOSED; } bool OnBufferedClosed() noexcept override { CloseClientSocket(); return false; } gcc_noreturn bool OnBufferedWrite() override { /* should never be reached because we never schedule writing */ gcc_unreachable(); } void OnBufferedError(std::exception_ptr e) noexcept override { PrintException(e); CloseClientSocket(); } }; class Client final : HttpResponseHandler, IstreamSink { CancellablePointer client_cancel_ptr; std::exception_ptr response_error; std::string response_body; http_status_t status{}; bool response_eof = false; public: void SendRequest(Server &server, http_method_t method, const char *uri, HttpHeaders &&headers, UnusedIstreamPtr body, bool expect_100=false) noexcept { server.SendRequest(method, uri, std::move(headers), std::move(body), expect_100, *this, client_cancel_ptr); } bool IsClientDone() const noexcept { return response_error || response_eof; } void RethrowResponseError() const { if (response_error) std::rethrow_exception(response_error); } private: /* virtual methods from class HttpResponseHandler */ void OnHttpResponse(http_status_t _status, StringMap &&headers, UnusedIstreamPtr body) noexcept override { status = _status; (void)headers; IstreamSink::SetInput(std::move(body)); input.Read(); } void OnHttpError(std::exception_ptr ep) noexcept override { response_error = std::move(ep); } /* virtual methods from class IstreamHandler */ size_t OnData(const void *data, size_t length) override { response_body.append((const char *)data, length); return length; } void OnEof() noexcept override { IstreamSink::ClearInput(); response_eof = true; } void OnError(std::exception_ptr ep) noexcept override { IstreamSink::ClearInput(); response_error = std::move(ep); } }; Server::Server(struct pool &_pool, EventLoop &event_loop) :pool(pool_new_libc(&_pool, "catch")), client_fs(event_loop) { UniqueSocketDescriptor client_socket, server_socket; if (!UniqueSocketDescriptor::CreateSocketPair(AF_LOCAL, SOCK_STREAM, 0, client_socket, server_socket)) throw MakeErrno("socketpair() failed"); connection = http_server_connection_new(pool, event_loop, std::move(server_socket), FdType::FD_SOCKET, nullptr, nullptr, nullptr, true, *this); client_fs.InitDummy(client_socket.Release(), FdType::FD_SOCKET); pool_unref(pool); } static std::exception_ptr catch_callback(std::exception_ptr ep, gcc_unused void *ctx) noexcept { PrintException(ep); return {}; } void Server::HandleHttpRequest(HttpServerRequest &request, CancellablePointer &cancel_ptr) noexcept { request_handler(request, cancel_ptr); } void Server::HttpConnectionError(std::exception_ptr e) noexcept { connection = nullptr; PrintException(e); } void Server::HttpConnectionClosed() noexcept { connection = nullptr; } static void test_catch(EventLoop &event_loop, struct pool *_pool) { Server server(*_pool, event_loop); server.SetRequestHandler([&server](HttpServerRequest &request, CancellablePointer &) noexcept { http_server_response(&request, HTTP_STATUS_OK, HttpHeaders(request.pool), istream_catch_new(&request.pool, std::move(request.body), catch_callback, nullptr)); server.CloseConnection(); }); Client client; client.SendRequest(server, HTTP_METHOD_POST, "/", HttpHeaders(server.GetPool()), istream_head_new(server.GetPool(), istream_block_new(server.GetPool()), 1024, true)); while (!client.IsClientDone()) event_loop.LoopOnce(); server.CloseClientSocket(); client.RethrowResponseError(); event_loop.Dispatch(); } int main(int argc, char **argv) noexcept try { (void)argc; (void)argv; direct_global_init(); const ScopeFbPoolInit fb_pool_init; PInstance instance; test_catch(instance.event_loop, instance.root_pool); } catch (...) { PrintException(std::current_exception()); return EXIT_FAILURE; } <|endoftext|>
<commit_before>#include <stan/math/prim/meta.hpp> #include <test/unit/math/prim/fun/expect_matrix_eq.hpp> #include <gtest/gtest.h> TEST(MathMetaPrim, ref_type_non_eigen) { using stan::ref_type_t; std::vector<int> a{1, 2, 3}; ref_type_t<std::vector<int>> a_ref1 = a; ref_type_t<std::vector<int>&> a_ref2 = a; ref_type_t<std::vector<int>&&> a_ref3 = std::vector<int>{1, 2, 3}; double b = 3; ref_type_t<double> b_ref1 = b; ref_type_t<double&> b_ref2 = b; ref_type_t<double&&> b_ref3 = 3; const std::vector<double> c{0.5, 4, 0.7}; ref_type_t<const std::vector<double>> c_ref1 = c; ref_type_t<const std::vector<double>&> c_ref2 = c; expect_std_vector_eq(a_ref1, a); expect_std_vector_eq(a_ref2, a); expect_std_vector_eq(a_ref3, a); EXPECT_EQ(b_ref1, b); EXPECT_EQ(b_ref2, b); EXPECT_EQ(b_ref3, b); expect_std_vector_eq(c_ref1, c); expect_std_vector_eq(c_ref2, c); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double&>>::value); EXPECT_FALSE(std::is_reference<ref_type_t<double&&>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<const std::vector<double>>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<const std::vector<double>&>>::value); EXPECT_FALSE(std::is_reference<ref_type_t<const std::vector<double>&&>>::value); } TEST(MathMetaPrim, ref_type_eigen_directly_accessible) { using stan::ref_type_t; Eigen::MatrixXd a(3, 3); a << 1, 2, 3, 4, 5, 6, 7, 8, 9; Eigen::MatrixXd a2 = a; ref_type_t<Eigen::MatrixXd> a_ref1 = a; ref_type_t<Eigen::MatrixXd&> a_ref2 = a; ref_type_t<Eigen::MatrixXd&&> a_ref3 = std::move(a2); auto b = a.block(1, 0, 2, 2); ref_type_t<decltype(b)> b_ref1 = b; ref_type_t<decltype(b)&> b_ref2 = b; ref_type_t<decltype(b)&&> b_ref3 = a.block(1, 0, 2, 2); Eigen::Ref<Eigen::MatrixXd> c = a; Eigen::Ref<Eigen::MatrixXd> c2 = a; ref_type_t<Eigen::Ref<Eigen::MatrixXd>> c_ref1 = c; ref_type_t<Eigen::Ref<Eigen::MatrixXd>&> c_ref2 = c; ref_type_t<Eigen::Ref<Eigen::MatrixXd>&&> c_ref3 = std::move(c2); expect_matrix_eq(a_ref1, a); expect_matrix_eq(a_ref2, a); expect_matrix_eq(a_ref3, a); expect_matrix_eq(b_ref1, b); expect_matrix_eq(b_ref2, b); expect_matrix_eq(b_ref3, b); expect_matrix_eq(c_ref1, c); expect_matrix_eq(c_ref2, c); expect_matrix_eq(c_ref3, c); EXPECT_TRUE((std::is_same<decltype(a), ref_type_t<decltype(a)&&>>::value)); EXPECT_TRUE((std::is_same<decltype(b), ref_type_t<decltype(b)&&>>::value)); EXPECT_TRUE((std::is_same<decltype(c), ref_type_t<decltype(c)&&>>::value)); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd&>>::value); EXPECT_FALSE(std::is_reference<ref_type_t<Eigen::MatrixXd&&>>::value); } TEST(MathMetaPrim, ref_type_eigen_expression) { using stan::plain_type_t; using stan::ref_type_t; Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; auto a = m * 3; ref_type_t<decltype(a)> a_ref1 = a; ref_type_t<decltype(a)&> a_ref2 = a; ref_type_t<decltype(a)&&> a_ref3 = m * 3; Eigen::MatrixXd a_eval = a; expect_matrix_eq(a_ref1, a_eval); expect_matrix_eq(a_ref2, a_eval); expect_matrix_eq(a_ref3, a_eval); EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)>>::value)); EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)&>>::value)); EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)&&>>::value)); } <commit_msg>[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2 (tags/RELEASE_600/final)<commit_after>#include <stan/math/prim/meta.hpp> #include <test/unit/math/prim/fun/expect_matrix_eq.hpp> #include <gtest/gtest.h> TEST(MathMetaPrim, ref_type_non_eigen) { using stan::ref_type_t; std::vector<int> a{1, 2, 3}; ref_type_t<std::vector<int>> a_ref1 = a; ref_type_t<std::vector<int>&> a_ref2 = a; ref_type_t<std::vector<int>&&> a_ref3 = std::vector<int>{1, 2, 3}; double b = 3; ref_type_t<double> b_ref1 = b; ref_type_t<double&> b_ref2 = b; ref_type_t<double&&> b_ref3 = 3; const std::vector<double> c{0.5, 4, 0.7}; ref_type_t<const std::vector<double>> c_ref1 = c; ref_type_t<const std::vector<double>&> c_ref2 = c; expect_std_vector_eq(a_ref1, a); expect_std_vector_eq(a_ref2, a); expect_std_vector_eq(a_ref3, a); EXPECT_EQ(b_ref1, b); EXPECT_EQ(b_ref2, b); EXPECT_EQ(b_ref3, b); expect_std_vector_eq(c_ref1, c); expect_std_vector_eq(c_ref2, c); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<double&>>::value); EXPECT_FALSE(std::is_reference<ref_type_t<double&&>>::value); EXPECT_TRUE( std::is_lvalue_reference<ref_type_t<const std::vector<double>>>::value); EXPECT_TRUE( std::is_lvalue_reference<ref_type_t<const std::vector<double>&>>::value); EXPECT_FALSE( std::is_reference<ref_type_t<const std::vector<double>&&>>::value); } TEST(MathMetaPrim, ref_type_eigen_directly_accessible) { using stan::ref_type_t; Eigen::MatrixXd a(3, 3); a << 1, 2, 3, 4, 5, 6, 7, 8, 9; Eigen::MatrixXd a2 = a; ref_type_t<Eigen::MatrixXd> a_ref1 = a; ref_type_t<Eigen::MatrixXd&> a_ref2 = a; ref_type_t<Eigen::MatrixXd&&> a_ref3 = std::move(a2); auto b = a.block(1, 0, 2, 2); ref_type_t<decltype(b)> b_ref1 = b; ref_type_t<decltype(b)&> b_ref2 = b; ref_type_t<decltype(b)&&> b_ref3 = a.block(1, 0, 2, 2); Eigen::Ref<Eigen::MatrixXd> c = a; Eigen::Ref<Eigen::MatrixXd> c2 = a; ref_type_t<Eigen::Ref<Eigen::MatrixXd>> c_ref1 = c; ref_type_t<Eigen::Ref<Eigen::MatrixXd>&> c_ref2 = c; ref_type_t<Eigen::Ref<Eigen::MatrixXd>&&> c_ref3 = std::move(c2); expect_matrix_eq(a_ref1, a); expect_matrix_eq(a_ref2, a); expect_matrix_eq(a_ref3, a); expect_matrix_eq(b_ref1, b); expect_matrix_eq(b_ref2, b); expect_matrix_eq(b_ref3, b); expect_matrix_eq(c_ref1, c); expect_matrix_eq(c_ref2, c); expect_matrix_eq(c_ref3, c); EXPECT_TRUE((std::is_same<decltype(a), ref_type_t<decltype(a)&&>>::value)); EXPECT_TRUE((std::is_same<decltype(b), ref_type_t<decltype(b)&&>>::value)); EXPECT_TRUE((std::is_same<decltype(c), ref_type_t<decltype(c)&&>>::value)); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd>>::value); EXPECT_TRUE(std::is_lvalue_reference<ref_type_t<Eigen::MatrixXd&>>::value); EXPECT_FALSE(std::is_reference<ref_type_t<Eigen::MatrixXd&&>>::value); } TEST(MathMetaPrim, ref_type_eigen_expression) { using stan::plain_type_t; using stan::ref_type_t; Eigen::MatrixXd m(3, 3); m << 1, 2, 3, 4, 5, 6, 7, 8, 9; auto a = m * 3; ref_type_t<decltype(a)> a_ref1 = a; ref_type_t<decltype(a)&> a_ref2 = a; ref_type_t<decltype(a)&&> a_ref3 = m * 3; Eigen::MatrixXd a_eval = a; expect_matrix_eq(a_ref1, a_eval); expect_matrix_eq(a_ref2, a_eval); expect_matrix_eq(a_ref3, a_eval); EXPECT_TRUE(( std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)>>::value)); EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)&>>::value)); EXPECT_TRUE((std::is_same<plain_type_t<decltype(a)>, ref_type_t<decltype(a)&&>>::value)); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: xmlcnitm.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: obo $ $Date: 2004-01-20 13:18:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _COM_SUN_STAR_XML_ATTRIBUTEDATA_HPP_ #include <com/sun/star/xml/AttributeData.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _XMLOFF_XMLCNIMP_HXX #include <xmloff/xmlcnimp.hxx> #endif #ifndef _XMLOFF_XMLCNITM_HXX #include <xmloff/unoatrcn.hxx> #endif #include "xmlcnitm.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::xml; // ------------------------------------------------------------------------ TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem); SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT nWhich ) : SfxPoolItem( nWhich ) { pImpl = new SvXMLAttrContainerData; } SvXMLAttrContainerItem::SvXMLAttrContainerItem( const SvXMLAttrContainerItem& rItem ) : SfxPoolItem( rItem ) { pImpl = new SvXMLAttrContainerData( *rItem.pImpl ); } SvXMLAttrContainerItem::~SvXMLAttrContainerItem() { delete pImpl; } int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const { DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem), "SvXMLAttrContainerItem::operator ==(): Bad type"); return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl; } int SvXMLAttrContainerItem::Compare( const SfxPoolItem &rWith ) const { DBG_ASSERT( !this, "not yet implemented" ); return 0; } SfxItemPresentation SvXMLAttrContainerItem::GetPresentation( SfxItemPresentation ePresentation, SfxMapUnit eCoreMetric, SfxMapUnit ePresentationMetric, XubString &rText, const IntlWrapper *pIntlWrapper ) const { return SFX_ITEM_PRESENTATION_NONE; } USHORT SvXMLAttrContainerItem::GetVersion( USHORT nFileFormatVersion ) const { // This item should never be stored return USHRT_MAX; } BOOL SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { Reference<XNameContainer> xContainer = new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) ); rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) ); return TRUE; } BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { Reference<XInterface> xRef; SvUnoAttributeContainer* pContainer = NULL; if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE ) { xRef = *(Reference<XInterface>*)rVal.getValue(); Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY); if( xTunnel.is() ) pContainer = (SvUnoAttributeContainer*)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId()); } if( pContainer ) { delete pImpl; pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() ); } else { SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData; try { Reference<XNameContainer> xContainer( xRef, UNO_QUERY ); if( !xContainer.is() ) return FALSE; const Sequence< OUString > aNameSequence( xContainer->getElementNames() ); const OUString* pNames = aNameSequence.getConstArray(); const INT32 nCount = aNameSequence.getLength(); Any aAny; AttributeData* pData; INT32 nAttr; for( nAttr = 0; nAttr < nCount; nAttr++ ) { const OUString aName( *pNames++ ); aAny = xContainer->getByName( aName ); if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) ) return FALSE; pData = (AttributeData*)aAny.getValue(); USHORT pos = aName.indexOf( sal_Unicode(':') ); if( pos != -1 ) { const OUString aPrefix( aName.copy( 0, pos )); const OUString aLName( aName.copy( pos+1 )); if( pData->Namespace.getLength() == 0 ) { if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) ) break; } else { if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) ) break; } } else { if( !pNewImpl->AddAttr( aName, pData->Value ) ) break; } } if( nAttr == nCount ) { delete pImpl; pImpl = pNewImpl; } else { delete pNewImpl; return FALSE; } } catch(...) { delete pNewImpl; return FALSE; } } return TRUE; } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rLName, rValue ); } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix, const OUString& rNamespace, const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue ); } USHORT SvXMLAttrContainerItem::GetAttrCount() const { return (USHORT)pImpl->GetAttrCount(); } OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const { return pImpl->GetAttrNamespace( i ); } OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const { return pImpl->GetAttrPrefix( i ); } const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const { return pImpl->GetAttrLName( i ); } const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const { return pImpl->GetAttrValue( i ); } USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const { return pImpl->GetFirstNamespaceIndex(); } USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const { return pImpl->GetNextNamespaceIndex( nIdx ); } const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const { return pImpl->GetNamespace( i ); } const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const { return pImpl->GetPrefix( i ); } <commit_msg>INTEGRATION: CWS ooo19126 (1.4.1054); FILE MERGED 2005/09/05 14:25:51 rt 1.4.1054.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: xmlcnitm.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-08 23:42:11 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef _COM_SUN_STAR_XML_ATTRIBUTEDATA_HPP_ #include <com/sun/star/xml/AttributeData.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_ #include <com/sun/star/lang/XUnoTunnel.hpp> #endif #ifndef _XMLOFF_XMLCNIMP_HXX #include <xmloff/xmlcnimp.hxx> #endif #ifndef _XMLOFF_XMLCNITM_HXX #include <xmloff/unoatrcn.hxx> #endif #include "xmlcnitm.hxx" using namespace rtl; using namespace ::com::sun::star::uno; using namespace ::com::sun::star::container; using namespace ::com::sun::star::lang; using namespace ::com::sun::star::xml; // ------------------------------------------------------------------------ TYPEINIT1(SvXMLAttrContainerItem, SfxPoolItem); SvXMLAttrContainerItem::SvXMLAttrContainerItem( USHORT nWhich ) : SfxPoolItem( nWhich ) { pImpl = new SvXMLAttrContainerData; } SvXMLAttrContainerItem::SvXMLAttrContainerItem( const SvXMLAttrContainerItem& rItem ) : SfxPoolItem( rItem ) { pImpl = new SvXMLAttrContainerData( *rItem.pImpl ); } SvXMLAttrContainerItem::~SvXMLAttrContainerItem() { delete pImpl; } int SvXMLAttrContainerItem::operator==( const SfxPoolItem& rItem ) const { DBG_ASSERT( rItem.ISA(SvXMLAttrContainerItem), "SvXMLAttrContainerItem::operator ==(): Bad type"); return *pImpl == *((const SvXMLAttrContainerItem&)rItem).pImpl; } int SvXMLAttrContainerItem::Compare( const SfxPoolItem &rWith ) const { DBG_ASSERT( !this, "not yet implemented" ); return 0; } SfxItemPresentation SvXMLAttrContainerItem::GetPresentation( SfxItemPresentation ePresentation, SfxMapUnit eCoreMetric, SfxMapUnit ePresentationMetric, XubString &rText, const IntlWrapper *pIntlWrapper ) const { return SFX_ITEM_PRESENTATION_NONE; } USHORT SvXMLAttrContainerItem::GetVersion( USHORT nFileFormatVersion ) const { // This item should never be stored return USHRT_MAX; } BOOL SvXMLAttrContainerItem::QueryValue( com::sun::star::uno::Any& rVal, BYTE nMemberId ) const { Reference<XNameContainer> xContainer = new SvUnoAttributeContainer( new SvXMLAttrContainerData( *pImpl ) ); rVal.setValue( &xContainer, ::getCppuType((Reference<XNameContainer>*)0) ); return TRUE; } BOOL SvXMLAttrContainerItem::PutValue( const com::sun::star::uno::Any& rVal, BYTE nMemberId ) { Reference<XInterface> xRef; SvUnoAttributeContainer* pContainer = NULL; if( rVal.getValue() != NULL && rVal.getValueType().getTypeClass() == TypeClass_INTERFACE ) { xRef = *(Reference<XInterface>*)rVal.getValue(); Reference<XUnoTunnel> xTunnel(xRef, UNO_QUERY); if( xTunnel.is() ) pContainer = (SvUnoAttributeContainer*)xTunnel->getSomething(SvUnoAttributeContainer::getUnoTunnelId()); } if( pContainer ) { delete pImpl; pImpl = new SvXMLAttrContainerData( * pContainer->GetContainerImpl() ); } else { SvXMLAttrContainerData* pNewImpl = new SvXMLAttrContainerData; try { Reference<XNameContainer> xContainer( xRef, UNO_QUERY ); if( !xContainer.is() ) return FALSE; const Sequence< OUString > aNameSequence( xContainer->getElementNames() ); const OUString* pNames = aNameSequence.getConstArray(); const INT32 nCount = aNameSequence.getLength(); Any aAny; AttributeData* pData; INT32 nAttr; for( nAttr = 0; nAttr < nCount; nAttr++ ) { const OUString aName( *pNames++ ); aAny = xContainer->getByName( aName ); if( aAny.getValue() == NULL || aAny.getValueType() != ::getCppuType((AttributeData*)0) ) return FALSE; pData = (AttributeData*)aAny.getValue(); USHORT pos = aName.indexOf( sal_Unicode(':') ); if( pos != -1 ) { const OUString aPrefix( aName.copy( 0, pos )); const OUString aLName( aName.copy( pos+1 )); if( pData->Namespace.getLength() == 0 ) { if( !pNewImpl->AddAttr( aPrefix, aLName, pData->Value ) ) break; } else { if( !pNewImpl->AddAttr( aPrefix, pData->Namespace, aLName, pData->Value ) ) break; } } else { if( !pNewImpl->AddAttr( aName, pData->Value ) ) break; } } if( nAttr == nCount ) { delete pImpl; pImpl = pNewImpl; } else { delete pNewImpl; return FALSE; } } catch(...) { delete pNewImpl; return FALSE; } } return TRUE; } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rLName, rValue ); } BOOL SvXMLAttrContainerItem::AddAttr( const OUString& rPrefix, const OUString& rNamespace, const OUString& rLName, const OUString& rValue ) { return pImpl->AddAttr( rPrefix, rNamespace, rLName, rValue ); } USHORT SvXMLAttrContainerItem::GetAttrCount() const { return (USHORT)pImpl->GetAttrCount(); } OUString SvXMLAttrContainerItem::GetAttrNamespace( USHORT i ) const { return pImpl->GetAttrNamespace( i ); } OUString SvXMLAttrContainerItem::GetAttrPrefix( USHORT i ) const { return pImpl->GetAttrPrefix( i ); } const OUString& SvXMLAttrContainerItem::GetAttrLName( USHORT i ) const { return pImpl->GetAttrLName( i ); } const OUString& SvXMLAttrContainerItem::GetAttrValue( USHORT i ) const { return pImpl->GetAttrValue( i ); } USHORT SvXMLAttrContainerItem::GetFirstNamespaceIndex() const { return pImpl->GetFirstNamespaceIndex(); } USHORT SvXMLAttrContainerItem::GetNextNamespaceIndex( USHORT nIdx ) const { return pImpl->GetNextNamespaceIndex( nIdx ); } const OUString& SvXMLAttrContainerItem::GetNamespace( USHORT i ) const { return pImpl->GetNamespace( i ); } const OUString& SvXMLAttrContainerItem::GetPrefix( USHORT i ) const { return pImpl->GetPrefix( i ); } <|endoftext|>
<commit_before>// // Copyright (c) 2017 The Khronos Group 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 "testBase.h" #include "action_classes.h" extern const char *IGetStatusString( cl_int status ); #define PRINT_OPS 0 int test_waitlist( cl_device_id device, cl_context context, cl_command_queue queue, Action *actionToTest, bool multiple ) { NDRangeKernelAction actions[ 2 ]; clEventWrapper events[ 3 ]; cl_int status[ 3 ]; cl_int error; if (multiple) log_info("\tExecuting reference event 0, then reference event 1 with reference event 0 in its waitlist, then test event 2 with reference events 0 and 1 in its waitlist.\n"); else log_info("\tExecuting reference event 0, then test event 2 with reference event 0 in its waitlist.\n"); // Set up the first base action to wait against error = actions[ 0 ].Setup( device, context, queue ); test_error( error, "Unable to setup base event to wait against" ); if( multiple ) { // Set up a second event to wait against error = actions[ 1 ].Setup( device, context, queue ); test_error( error, "Unable to setup second base event to wait against" ); } // Now set up the actual action to test error = actionToTest->Setup( device, context, queue ); test_error( error, "Unable to set up test event" ); // Execute all events now if (PRINT_OPS) log_info("\tExecuting action 0...\n"); error = actions[ 0 ].Execute( queue, 0, NULL, &events[ 0 ] ); test_error( error, "Unable to execute first event" ); if( multiple ) { if (PRINT_OPS) log_info("\tExecuting action 1...\n"); error = actions[ 1 ].Execute( queue, 1, &events[0], &events[ 1 ] ); test_error( error, "Unable to execute second event" ); } // Sanity check if( multiple ) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error( error, "Unable to get event status" ); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error( error, "Unable to get event status" ); log_info("\t\tEvent status after starting reference events: reference event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString( status[ 0 ] ), (multiple ? IGetStatusString( status[ 1 ] ) : "N/A"), "N/A"); if( ( status[ 0 ] == CL_COMPLETE ) || ( multiple && status[ 1 ] == CL_COMPLETE ) ) { log_info( "WARNING: Reference event(s) already completed before we could execute test event! Possible that the reference event blocked (implicitly passing)\n" ); return 0; } if (PRINT_OPS) log_info("\tExecuting action to test...\n"); error = actionToTest->Execute( queue, ( multiple ) ? 2 : 1, &events[ 0 ], &events[ 2 ] ); test_error( error, "Unable to execute test event" ); // Hopefully, the first event is still running if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); if( multiple ) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error( error, "Unable to get event status" ); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error( error, "Unable to get event status" ); log_info("\t\tEvent status after starting test event: reference event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString( status[ 0 ] ), (multiple ? IGetStatusString( status[ 1 ] ) : "N/A"), IGetStatusString( status[ 2 ] )); if( multiple ) { if( status[ 0 ] == CL_COMPLETE && status[ 1 ] == CL_COMPLETE ) { log_info( "WARNING: Both events completed, so unable to test further (implicitly passing).\n" ); clFinish( queue ); return 0; } if(status[1] == CL_COMPLETE && status[0] != CL_COMPLETE) { log_error("ERROR: Test failed because the second wait event is complete and the first is not.(status: 0: %s and 1: %s)\n", IGetStatusString( status[ 0 ] ), IGetStatusString( status[ 1 ] ) ); clFinish( queue ); return -1; } } else { if( status[ 0 ] == CL_COMPLETE ) { log_info( "WARNING: Reference event completed, so unable to test further (implicitly passing).\n" ); clFinish( queue ); return 0; } if( status[ 0 ] != CL_RUNNING && status[ 0 ] != CL_QUEUED && status[ 0 ] != CL_SUBMITTED ) { log_error( "ERROR: Test failed because first wait event is not currently running, queued, or submitted! (status: 0: %s)\n", IGetStatusString( status[ 0 ] ) ); clFinish( queue ); return -1; } } if( status[ 2 ] != CL_QUEUED && status[ 2 ] != CL_SUBMITTED ) { log_error( "ERROR: Test event is not waiting to run! (status: 2: %s)\n", IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Now wait for the first reference event if (PRINT_OPS) log_info("\tWaiting for action 1 to finish...\n"); error = clWaitForEvents( 1, &events[ 0 ] ); test_error( error, "Unable to wait for reference event" ); // Grab statuses again if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); if( multiple ) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error( error, "Unable to get event status" ); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error( error, "Unable to get event status" ); log_info("\t\tEvent status after waiting for reference event 0: reference event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString( status[ 0 ] ), (multiple ? IGetStatusString( status[ 1 ] ) : "N/A"), IGetStatusString( status[ 2 ] )); // Sanity if( status[ 0 ] != CL_COMPLETE ) { log_error( "ERROR: Waited for first event but it's not complete (status: 0: %s)\n", IGetStatusString( status[ 0 ] ) ); clFinish( queue ); return -1; } // If we're multiple, and the second event isn't complete, then our test event should still be queued if( multiple && status[ 1 ] != CL_COMPLETE ) { if( status[ 1 ] == CL_RUNNING && status[ 2 ] == CL_RUNNING ) { log_error("ERROR: Test event and second event are both running.\n"); clFinish( queue ); return -1; } if( status[ 2 ] != CL_QUEUED && status[ 2 ] != CL_SUBMITTED ) { log_error( "ERROR: Test event did not wait for second event before starting! (status of ref: 1: %s, of test: 2: %s)\n", IGetStatusString( status[ 1 ] ), IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Now wait for second event to complete, too if (PRINT_OPS) log_info("\tWaiting for action 1 to finish...\n"); error = clWaitForEvents( 1, &events[ 1 ] ); test_error( error, "Unable to wait for second reference event" ); // Grab statuses again if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); if( multiple ) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error( error, "Unable to get event status" ); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error( error, "Unable to get event status" ); log_info("\t\tEvent status after waiting for reference event 1: reference event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString( status[ 0 ] ), (multiple ? IGetStatusString( status[ 1 ] ) : "N/A"), IGetStatusString( status[ 2 ] )); // Sanity if( status[ 1 ] != CL_COMPLETE ) { log_error( "ERROR: Waited for second reference event but it didn't complete (status: 1: %s)\n", IGetStatusString( status[ 1 ] ) ); clFinish( queue ); return -1; } } // At this point, the test event SHOULD be running, but if it completed, we consider it a pass if( status[ 2 ] == CL_COMPLETE ) { log_info( "WARNING: Test event already completed. Assumed valid.\n" ); clFinish( queue ); return 0; } if( status[ 2 ] != CL_RUNNING && status[ 2 ] != CL_SUBMITTED && status[ 2 ] != CL_QUEUED) { log_error( "ERROR: Second event did not start running after reference event(s) completed! (status: 2: %s)\n", IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Wait for the test event, then return if (PRINT_OPS) log_info("\tWaiting for action 2 to test to finish...\n"); error = clWaitForEvents( 1, &events[ 2 ] ); test_error( error, "Unable to wait for test event" ); error |= clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); log_info("\t\tEvent status after waiting for test event: reference event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString( status[ 0 ] ), (multiple ? IGetStatusString( status[ 1 ] ) : "N/A"), IGetStatusString( status[ 2 ] )); // Sanity if( status[ 2 ] != CL_COMPLETE ) { log_error( "ERROR: Test event didn't complete (status: 2: %s)\n", IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } clFinish(queue); return 0; } #define TEST_ACTION( name ) \ { \ name##Action action; \ log_info( "-- Testing " #name " (waiting on 1 event)...\n" ); \ if( ( error = test_waitlist( deviceID, context, queue, &action, false ) ) != CL_SUCCESS ) \ retVal++; \ clFinish( queue ); \ } \ if( error == CL_SUCCESS ) /* Only run multiples test if single test passed */ \ { \ name##Action action; \ log_info( "-- Testing " #name " (waiting on 2 events)...\n" ); \ if( ( error = test_waitlist( deviceID, context, queue, &action, true ) ) != CL_SUCCESS ) \ retVal++; \ clFinish( queue ); \ } int test_waitlists( cl_device_id deviceID, cl_context context, cl_command_queue oldQueue, int num_elements ) { cl_int error; int retVal = 0; cl_command_queue_properties props = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; if( !checkDeviceForQueueSupport( deviceID, props ) ) { log_info( "WARNING: Device does not support out-of-order exec mode; skipping test.\n" ); return 0; } clCommandQueueWrapper queue = clCreateCommandQueue( context, deviceID, props, &error ); test_error(error, "Unable to create out-of-order queue"); log_info( "\n" ); TEST_ACTION( NDRangeKernel ) TEST_ACTION( ReadBuffer ) TEST_ACTION( WriteBuffer ) TEST_ACTION( MapBuffer ) TEST_ACTION( UnmapBuffer ) if( checkForImageSupport( deviceID ) == CL_IMAGE_FORMAT_NOT_SUPPORTED ) { log_info( "\nNote: device does not support images. Skipping remainder of waitlist tests...\n" ); } else { TEST_ACTION( ReadImage2D ) TEST_ACTION( WriteImage2D ) TEST_ACTION( CopyImage2Dto2D ) TEST_ACTION( Copy2DImageToBuffer ) TEST_ACTION( CopyBufferTo2DImage ) TEST_ACTION( MapImage ) if( checkFor3DImageSupport( deviceID ) == CL_IMAGE_FORMAT_NOT_SUPPORTED ) log_info("Device does not support 3D images. Skipping remainder of waitlist tests...\n"); else { TEST_ACTION( ReadImage3D ) TEST_ACTION( WriteImage3D ) TEST_ACTION( CopyImage2Dto3D ) TEST_ACTION( CopyImage3Dto2D ) TEST_ACTION( CopyImage3Dto3D ) TEST_ACTION( Copy3DImageToBuffer ) TEST_ACTION( CopyBufferTo3DImage ) } } return retVal; } <commit_msg>Fix indentation of test_waitlists.cpp (#1459)<commit_after>// // Copyright (c) 2017 The Khronos Group 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 "testBase.h" #include "action_classes.h" extern const char *IGetStatusString( cl_int status ); #define PRINT_OPS 0 int test_waitlist( cl_device_id device, cl_context context, cl_command_queue queue, Action *actionToTest, bool multiple ) { NDRangeKernelAction actions[ 2 ]; clEventWrapper events[ 3 ]; cl_int status[ 3 ]; cl_int error; if (multiple) log_info("\tExecuting reference event 0, then reference event 1 with " "reference event 0 in its waitlist, then test event 2 with " "reference events 0 and 1 in its waitlist.\n"); else log_info("\tExecuting reference event 0, then test event 2 with " "reference event 0 in its waitlist.\n"); // Set up the first base action to wait against error = actions[ 0 ].Setup( device, context, queue ); test_error( error, "Unable to setup base event to wait against" ); if( multiple ) { // Set up a second event to wait against error = actions[ 1 ].Setup( device, context, queue ); test_error( error, "Unable to setup second base event to wait against" ); } // Now set up the actual action to test error = actionToTest->Setup( device, context, queue ); test_error( error, "Unable to set up test event" ); // Execute all events now if (PRINT_OPS) log_info("\tExecuting action 0...\n"); error = actions[ 0 ].Execute( queue, 0, NULL, &events[ 0 ] ); test_error( error, "Unable to execute first event" ); if( multiple ) { if (PRINT_OPS) log_info("\tExecuting action 1...\n"); error = actions[ 1 ].Execute( queue, 1, &events[0], &events[ 1 ] ); test_error( error, "Unable to execute second event" ); } // Sanity check if (multiple) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error(error, "Unable to get event status"); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error(error, "Unable to get event status"); log_info("\t\tEvent status after starting reference events: reference " "event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString(status[0]), (multiple ? IGetStatusString(status[1]) : "N/A"), "N/A"); if( ( status[ 0 ] == CL_COMPLETE ) || ( multiple && status[ 1 ] == CL_COMPLETE ) ) { log_info( "WARNING: Reference event(s) already completed before we could execute test event! Possible that the reference event blocked (implicitly passing)\n" ); return 0; } if (PRINT_OPS) log_info("\tExecuting action to test...\n"); error = actionToTest->Execute( queue, ( multiple ) ? 2 : 1, &events[ 0 ], &events[ 2 ] ); test_error( error, "Unable to execute test event" ); // Hopefully, the first event is still running if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); if (multiple) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error(error, "Unable to get event status"); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error(error, "Unable to get event status"); log_info("\t\tEvent status after starting test event: reference event 0: " "%s, reference event 1: %s, test event 2: %s.\n", IGetStatusString(status[0]), (multiple ? IGetStatusString(status[1]) : "N/A"), IGetStatusString(status[2])); if( multiple ) { if( status[ 0 ] == CL_COMPLETE && status[ 1 ] == CL_COMPLETE ) { log_info( "WARNING: Both events completed, so unable to test further (implicitly passing).\n" ); clFinish( queue ); return 0; } if (status[1] == CL_COMPLETE && status[0] != CL_COMPLETE) { log_error( "ERROR: Test failed because the second wait event is complete " "and the first is not.(status: 0: %s and 1: %s)\n", IGetStatusString(status[0]), IGetStatusString(status[1])); clFinish( queue ); return -1; } } else { if( status[ 0 ] == CL_COMPLETE ) { log_info( "WARNING: Reference event completed, so unable to test further (implicitly passing).\n" ); clFinish( queue ); return 0; } if( status[ 0 ] != CL_RUNNING && status[ 0 ] != CL_QUEUED && status[ 0 ] != CL_SUBMITTED ) { log_error( "ERROR: Test failed because first wait event is not currently running, queued, or submitted! (status: 0: %s)\n", IGetStatusString( status[ 0 ] ) ); clFinish( queue ); return -1; } } if( status[ 2 ] != CL_QUEUED && status[ 2 ] != CL_SUBMITTED ) { log_error( "ERROR: Test event is not waiting to run! (status: 2: %s)\n", IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Now wait for the first reference event if (PRINT_OPS) log_info("\tWaiting for action 1 to finish...\n"); error = clWaitForEvents( 1, &events[ 0 ] ); test_error( error, "Unable to wait for reference event" ); // Grab statuses again if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo( events[ 2 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 2 ] ), &status[ 2 ], NULL ); test_error( error, "Unable to get event status" ); if (multiple) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo( events[ 1 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 1 ] ), &status[ 1 ], NULL ); test_error(error, "Unable to get event status"); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo( events[ 0 ], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof( status[ 0 ] ), &status[ 0 ], NULL ); test_error(error, "Unable to get event status"); log_info("\t\tEvent status after waiting for reference event 0: reference " "event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString(status[0]), (multiple ? IGetStatusString(status[1]) : "N/A"), IGetStatusString(status[2])); // Sanity if( status[ 0 ] != CL_COMPLETE ) { log_error( "ERROR: Waited for first event but it's not complete (status: 0: %s)\n", IGetStatusString( status[ 0 ] ) ); clFinish( queue ); return -1; } // If we're multiple, and the second event isn't complete, then our test event should still be queued if( multiple && status[ 1 ] != CL_COMPLETE ) { if (status[1] == CL_RUNNING && status[2] == CL_RUNNING) { log_error("ERROR: Test event and second event are both running.\n"); clFinish(queue); return -1; } if( status[ 2 ] != CL_QUEUED && status[ 2 ] != CL_SUBMITTED ) { log_error( "ERROR: Test event did not wait for second event before starting! (status of ref: 1: %s, of test: 2: %s)\n", IGetStatusString( status[ 1 ] ), IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Now wait for second event to complete, too if (PRINT_OPS) log_info("\tWaiting for action 1 to finish...\n"); error = clWaitForEvents( 1, &events[ 1 ] ); test_error( error, "Unable to wait for second reference event" ); // Grab statuses again if (PRINT_OPS) log_info("\tChecking status of action to test 2...\n"); error = clGetEventInfo(events[2], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status[2]), &status[2], NULL); test_error(error, "Unable to get event status"); if (multiple) { if (PRINT_OPS) log_info("\tChecking status of action 1...\n"); error = clGetEventInfo(events[1], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status[1]), &status[1], NULL); test_error(error, "Unable to get event status"); } if (PRINT_OPS) log_info("\tChecking status of action 0...\n"); error = clGetEventInfo(events[0], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status[0]), &status[0], NULL); test_error(error, "Unable to get event status"); log_info( "\t\tEvent status after waiting for reference event 1: reference " "event 0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString(status[0]), (multiple ? IGetStatusString(status[1]) : "N/A"), IGetStatusString(status[2])); // Sanity if( status[ 1 ] != CL_COMPLETE ) { log_error( "ERROR: Waited for second reference event but it didn't complete (status: 1: %s)\n", IGetStatusString( status[ 1 ] ) ); clFinish( queue ); return -1; } } // At this point, the test event SHOULD be running, but if it completed, we consider it a pass if( status[ 2 ] == CL_COMPLETE ) { log_info( "WARNING: Test event already completed. Assumed valid.\n" ); clFinish( queue ); return 0; } if( status[ 2 ] != CL_RUNNING && status[ 2 ] != CL_SUBMITTED && status[ 2 ] != CL_QUEUED) { log_error( "ERROR: Second event did not start running after reference event(s) completed! (status: 2: %s)\n", IGetStatusString( status[ 2 ] ) ); clFinish( queue ); return -1; } // Wait for the test event, then return if (PRINT_OPS) log_info("\tWaiting for action 2 to test to finish...\n"); error = clWaitForEvents( 1, &events[ 2 ] ); test_error( error, "Unable to wait for test event" ); error |= clGetEventInfo(events[2], CL_EVENT_COMMAND_EXECUTION_STATUS, sizeof(status[2]), &status[2], NULL); test_error(error, "Unable to get event status"); log_info("\t\tEvent status after waiting for test event: reference event " "0: %s, reference event 1: %s, test event 2: %s.\n", IGetStatusString(status[0]), (multiple ? IGetStatusString(status[1]) : "N/A"), IGetStatusString(status[2])); // Sanity if (status[2] != CL_COMPLETE) { log_error("ERROR: Test event didn't complete (status: 2: %s)\n", IGetStatusString(status[2])); clFinish(queue); return -1; } clFinish(queue); return 0; } #define TEST_ACTION( name ) \ { \ name##Action action; \ log_info( "-- Testing " #name " (waiting on 1 event)...\n" ); \ if( ( error = test_waitlist( deviceID, context, queue, &action, false ) ) != CL_SUCCESS ) \ retVal++; \ clFinish( queue ); \ } \ if( error == CL_SUCCESS ) /* Only run multiples test if single test passed */ \ { \ name##Action action; \ log_info( "-- Testing " #name " (waiting on 2 events)...\n" ); \ if( ( error = test_waitlist( deviceID, context, queue, &action, true ) ) != CL_SUCCESS ) \ retVal++; \ clFinish( queue ); \ } int test_waitlists( cl_device_id deviceID, cl_context context, cl_command_queue oldQueue, int num_elements ) { cl_int error; int retVal = 0; cl_command_queue_properties props = CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE; if( !checkDeviceForQueueSupport( deviceID, props ) ) { log_info( "WARNING: Device does not support out-of-order exec mode; skipping test.\n" ); return 0; } clCommandQueueWrapper queue = clCreateCommandQueue( context, deviceID, props, &error ); test_error(error, "Unable to create out-of-order queue"); log_info( "\n" ); TEST_ACTION( NDRangeKernel ) TEST_ACTION( ReadBuffer ) TEST_ACTION( WriteBuffer ) TEST_ACTION( MapBuffer ) TEST_ACTION( UnmapBuffer ) if( checkForImageSupport( deviceID ) == CL_IMAGE_FORMAT_NOT_SUPPORTED ) { log_info( "\nNote: device does not support images. Skipping remainder of waitlist tests...\n" ); } else { TEST_ACTION( ReadImage2D ) TEST_ACTION( WriteImage2D ) TEST_ACTION( CopyImage2Dto2D ) TEST_ACTION( Copy2DImageToBuffer ) TEST_ACTION( CopyBufferTo2DImage ) TEST_ACTION( MapImage ) if( checkFor3DImageSupport( deviceID ) == CL_IMAGE_FORMAT_NOT_SUPPORTED ) log_info("Device does not support 3D images. Skipping remainder of waitlist tests...\n"); else { TEST_ACTION( ReadImage3D ) TEST_ACTION( WriteImage3D ) TEST_ACTION( CopyImage2Dto3D ) TEST_ACTION( CopyImage3Dto2D ) TEST_ACTION( CopyImage3Dto3D ) TEST_ACTION( Copy3DImageToBuffer ) TEST_ACTION( CopyBufferTo3DImage ) } } return retVal; } <|endoftext|>
<commit_before>/** * @file NetworkHttpTest.cpp * @brief NetworkHttp class tester. * @author zer0 * @date 2017-05-19 */ #include <gtest/gtest.h> #include <tester/DemoAsset.hpp> #include <libtbag/log/Log.hpp> #include <libtbag/network/http/HttpClient.hpp> #include <libtbag/network/http/HttpServer.hpp> #include <libtbag/network/http/HttpBuilder.hpp> #include <libtbag/uvpp/Loop.hpp> #include <iostream> #include <thread> using namespace libtbag; using namespace libtbag::network; using namespace libtbag::network::http; TEST(NetworkHttpTest, HttpClient) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); HttpResponse response; auto result = http::requestWithSync("http://osom8979.github.io", 10000, response); ASSERT_EQ(Err::E_SUCCESS, result); ASSERT_EQ(200, response.status); } static bool runSimpleServerTest(HttpServer::StreamType type, std::string const & bind, std::string const & method) { uvpp::Loop loop; HttpServer server(loop, type); server.init(bind.c_str()); std::string request_url = "http://localhost:"; request_url += std::to_string(server.getPort()); request_url += "/"; int on_open = 0; int on_request = 0; int on_close = 0; server.setOnOpen([&](HttpServer::WeakClient node){ ++on_open; }); server.setOnRequest([&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ ++on_request; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName()); timeout = 1000; }); server.setOnClose([&](HttpServer::WeakClient node){ ++on_close; server.close(); }); Err server_result = Err::E_UNKNOWN; Err client_result = Err::E_UNKNOWN; HttpResponse response; HttpRequest request; request.method = method; std::thread server_thread([&](){ server_result = loop.run(); }); std::thread client_thread([&](){ if (HttpServer::StreamType::PIPE == type) { client_result = http::requestWithSync(type, bind, 0, Uri(request_url), request, 1000, response); } else { client_result = http::requestWithSync(request_url, request, 1000, response); } }); client_thread.join(); server_thread.join(); if (Err::E_SUCCESS != server_result) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Server result {} error", method, getErrName(server_result)); return false; } if (Err::E_SUCCESS != client_result) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Client result {} error", method, getErrName(client_result)); return false; } if (200 != response.status) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Response is not OK({}).", method, response.status); return false; } if (response.body != method) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Response body error({}).", method, response.body); return false; } if (on_open != 1 || on_request != 1 || on_close != 1) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Counter error({}/{}/{}).", method, on_open, on_request, on_close); return false; } return true; } TEST(NetworkHttpTest, TcpHttpServer) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); runSimpleServerTest(HttpServer::StreamType::TCP, details::ANY_IPV4, "GET"); runSimpleServerTest(HttpServer::StreamType::TCP, details::ANY_IPV4, "POST"); } TEST(NetworkHttpTest, PipeHttpServer) { #if defined(TBAG_PLATFORM_WINDOWS) char const * const PATH = "\\\\.\\pipe\\HTTP_TEST"; #else char const * const TEST_FILENAME = "http.sock"; tttDir(true, true); auto const PATH = tttDirGet() / TEST_FILENAME; #endif log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); runSimpleServerTest(HttpServer::StreamType::PIPE, PATH, "GET"); runSimpleServerTest(HttpServer::StreamType::PIPE, PATH, "POST"); } TEST(NetworkHttpTest, RoutingServer) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); uvpp::Loop loop; HttpServer server(loop); int on_open = 0; int on_close = 0; int on_request = 0; int on_request_doc = 0; int on_request_down_get = 0; int on_request_down_post = 0; server.init(details::ANY_IPV4, 0); int const SERVER_PORT = server.getPort(); std::string request_url = "http://localhost:"; request_url += std::to_string(SERVER_PORT); request_url += "/"; std::string const REQUEST_URL_DOC = request_url + "Documents"; std::string const REQUEST_URL_DOWN = request_url + "Downloads"; std::cout << "Request URL: " << request_url << std::endl; server.setOnOpen([&](HttpServer::WeakClient node){ ++on_open; }); server.setOnRequest([&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest()\n"; ++on_request; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("/Documents", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest(/Documents)\n"; ++on_request_doc; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("GET", "/Downloads", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest([GET]/Downloads)\n"; ++on_request_down_get; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("POST", "/Downloads", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest([POST]/Downloads)\n"; ++on_request_down_post; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnClose([&](HttpServer::WeakClient node){ ++on_close; if (on_close == 5) { server.close(); } }); Err server_result = Err::E_UNKNOWN; Err client_result = Err::E_UNKNOWN; HttpResponse response; HttpResponse response_doc_get; HttpResponse response_doc_post; HttpResponse response_down_get; HttpResponse response_down_post; HttpRequest request_get; request_get.method = "GET"; HttpRequest request_post; request_post.method = "POST"; std::thread server_thread([&](){ server_result = loop.run(); }); std::thread client1_thread([&](){ client_result = http::requestWithSync(request_url, 1000, response); }); std::thread client2_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOC, request_get, 1000, response_doc_get); }); std::thread client3_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOC, request_post, 1000, response_doc_post); }); std::thread client4_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOWN, request_get, 1000, response_down_get); }); std::thread client5_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOWN, request_post, 1000, response_down_post); }); client1_thread.join(); client2_thread.join(); client3_thread.join(); client4_thread.join(); client5_thread.join(); server_thread.join(); ASSERT_EQ(200, response.status); ASSERT_EQ(200, response_doc_get.status); ASSERT_EQ(200, response_doc_post.status); ASSERT_EQ(200, response_down_get.status); ASSERT_EQ(200, response_down_post.status); ASSERT_EQ(5, on_open ); ASSERT_EQ(1, on_request ); ASSERT_EQ(2, on_request_doc ); ASSERT_EQ(1, on_request_down_get ); ASSERT_EQ(1, on_request_down_post); ASSERT_EQ(5, on_close ); } <commit_msg>Trivial commit.<commit_after>/** * @file NetworkHttpTest.cpp * @brief NetworkHttp class tester. * @author zer0 * @date 2017-05-19 */ #include <gtest/gtest.h> #include <tester/DemoAsset.hpp> #include <libtbag/log/Log.hpp> #include <libtbag/network/http/HttpClient.hpp> #include <libtbag/network/http/HttpServer.hpp> #include <libtbag/network/http/HttpBuilder.hpp> #include <libtbag/uvpp/Loop.hpp> #include <iostream> #include <thread> using namespace libtbag; using namespace libtbag::network; using namespace libtbag::network::http; TEST(NetworkHttpTest, HttpClient) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); HttpResponse response; auto result = http::requestWithSync("http://osom8979.github.io", 10000, response); ASSERT_EQ(Err::E_SUCCESS, result); ASSERT_EQ(200, response.status); } static bool runSimpleServerTest(HttpServer::StreamType type, std::string const & bind, std::string const & method) { uvpp::Loop loop; HttpServer server(loop, type); server.init(bind.c_str()); std::string request_url = "http://localhost:"; request_url += std::to_string(server.getPort()); request_url += "/"; int on_open = 0; int on_request = 0; int on_close = 0; server.setOnOpen([&](HttpServer::WeakClient node){ ++on_open; }); server.setOnRequest([&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ ++on_request; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName()); timeout = 1000; }); server.setOnClose([&](HttpServer::WeakClient node){ ++on_close; server.close(); }); Err server_result = Err::E_UNKNOWN; Err client_result = Err::E_UNKNOWN; HttpResponse response; HttpRequest request; request.method = method; std::thread server_thread([&](){ server_result = loop.run(); }); std::thread client_thread([&](){ if (HttpServer::StreamType::PIPE == type) { client_result = http::requestWithSync(type, bind, 0, Uri(request_url), request, 1000, response); } else { client_result = http::requestWithSync(request_url, request, 1000, response); } }); client_thread.join(); server_thread.join(); if (Err::E_SUCCESS != server_result) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Server result {} error", method, getErrName(server_result)); return false; } if (Err::E_SUCCESS != client_result) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Client result {} error", method, getErrName(client_result)); return false; } if (200 != response.status) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Response is not OK({}).", method, response.status); return false; } if (response.body != method) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Response body error({}).", method, response.body); return false; } if (on_open != 1 || on_request != 1 || on_close != 1) { tDLogA("NetworkHttpTest.runSimpleServerTest({}) Counter error({}/{}/{}).", method, on_open, on_request, on_close); return false; } return true; } TEST(NetworkHttpTest, TcpHttpServer) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); ASSERT_TRUE(runSimpleServerTest(HttpServer::StreamType::TCP, details::ANY_IPV4, "GET")); ASSERT_TRUE(runSimpleServerTest(HttpServer::StreamType::TCP, details::ANY_IPV4, "POST")); } TEST(NetworkHttpTest, PipeHttpServer) { #if defined(TBAG_PLATFORM_WINDOWS) char const * const PATH = "\\\\.\\pipe\\HTTP_TEST"; #else char const * const TEST_FILENAME = "http.sock"; tttDir(true, true); auto const PATH = tttDirGet() / TEST_FILENAME; #endif log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); ASSERT_TRUE(runSimpleServerTest(HttpServer::StreamType::PIPE, PATH, "GET")); ASSERT_TRUE(runSimpleServerTest(HttpServer::StreamType::PIPE, PATH, "POST")); } TEST(NetworkHttpTest, RoutingServer) { log::SeverityGuard guard(log::TBAG_DEFAULT_LOGGER_NAME, log::INFO_SEVERITY); uvpp::Loop loop; HttpServer server(loop); int on_open = 0; int on_close = 0; int on_request = 0; int on_request_doc = 0; int on_request_down_get = 0; int on_request_down_post = 0; server.init(details::ANY_IPV4, 0); int const SERVER_PORT = server.getPort(); std::string request_url = "http://localhost:"; request_url += std::to_string(SERVER_PORT); request_url += "/"; std::string const REQUEST_URL_DOC = request_url + "Documents"; std::string const REQUEST_URL_DOWN = request_url + "Downloads"; std::cout << "Request URL: " << request_url << std::endl; server.setOnOpen([&](HttpServer::WeakClient node){ ++on_open; }); server.setOnRequest([&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest()\n"; ++on_request; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("/Documents", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest(/Documents)\n"; ++on_request_doc; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("GET", "/Downloads", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest([GET]/Downloads)\n"; ++on_request_down_get; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnRequest("POST", "/Downloads", [&](Err code, HttpServer::WeakClient node, HttpParser const & request, HttpBuilder & response, uint64_t & timeout){ std::cout << "Server.OnRequest([POST]/Downloads)\n"; ++on_request_down_post; response.setStatus(200); response.setReason("OK"); response.setBody(request.getMethodName() + request.getUrl()); timeout = 1000; }); server.setOnClose([&](HttpServer::WeakClient node){ ++on_close; if (on_close == 5) { server.close(); } }); Err server_result = Err::E_UNKNOWN; Err client_result = Err::E_UNKNOWN; HttpResponse response; HttpResponse response_doc_get; HttpResponse response_doc_post; HttpResponse response_down_get; HttpResponse response_down_post; HttpRequest request_get; request_get.method = "GET"; HttpRequest request_post; request_post.method = "POST"; std::thread server_thread([&](){ server_result = loop.run(); }); std::thread client1_thread([&](){ client_result = http::requestWithSync(request_url, 1000, response); }); std::thread client2_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOC, request_get, 1000, response_doc_get); }); std::thread client3_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOC, request_post, 1000, response_doc_post); }); std::thread client4_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOWN, request_get, 1000, response_down_get); }); std::thread client5_thread([&](){ client_result = http::requestWithSync(REQUEST_URL_DOWN, request_post, 1000, response_down_post); }); client1_thread.join(); client2_thread.join(); client3_thread.join(); client4_thread.join(); client5_thread.join(); server_thread.join(); ASSERT_EQ(200, response.status); ASSERT_EQ(200, response_doc_get.status); ASSERT_EQ(200, response_doc_post.status); ASSERT_EQ(200, response_down_get.status); ASSERT_EQ(200, response_down_post.status); ASSERT_EQ(5, on_open ); ASSERT_EQ(1, on_request ); ASSERT_EQ(2, on_request_doc ); ASSERT_EQ(1, on_request_down_get ); ASSERT_EQ(1, on_request_down_post); ASSERT_EQ(5, on_close ); } <|endoftext|>
<commit_before>// RUN: %clang_cc1 -fsyntax-only -verify %s // PR7800 class NoDestroy { ~NoDestroy(); }; // expected-note {{declared private here}} struct A { virtual ~A(); }; struct B : public virtual A { NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}} }; struct D : public virtual B { virtual void foo(); ~D(); }; void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}} } <commit_msg>Make this test check a few more cases which didn't work correctly before r110526.<commit_after>// RUN: %clang_cc1 -fsyntax-only -verify %s // PR7800 class NoDestroy { ~NoDestroy(); }; // expected-note 3 {{declared private here}} struct A { virtual ~A(); }; struct B : public virtual A { NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}} }; struct D : public virtual B { virtual void foo(); ~D(); }; void D::foo() { // expected-note {{implicit default destructor for 'B' first required here}} } struct E : public virtual A { NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}} }; struct F : public E { // expected-note {{implicit default destructor for 'E' first required here}} }; struct G : public virtual F { virtual void foo(); ~G(); }; void G::foo() { // expected-note {{implicit default destructor for 'F' first required here}} } struct H : public virtual A { NoDestroy x; // expected-error {{field of type 'NoDestroy' has private destructor}} }; struct I : public virtual H { ~I(); }; struct J : public I { virtual void foo(); ~J(); }; void J::foo() { // expected-note {{implicit default destructor for 'H' first required here}} } <|endoftext|>
<commit_before>#include <bits/stdc++.h> #define UN(v) sort(all(v)), (v).erase(unique(all(v)), (v).end()) #define FOR(i, a, b) for (decltype(a) i(a), _B_##i(b); i < _B_##i; ++i) #define CL(a, b) memset(a, b, sizeof a) #define all(a) (a).begin(), (a).end() #define REP(i, n) FOR(i, 0, n) #define sz(a) int((a).size()) #define ll int64_t #define pb push_back #define Y second #define X first using namespace std; typedef pair<int, int> pii; int mod; int add(int x, int y) { return (x += y) < mod ? x : x - mod; } int sub(int x, int y) { return (x -= y) < 0 ? x + mod : x; } int mul(int x, int y) { return (ll)x * y % mod; } template <class X> X qpow(X x, X n) { X y{1}; for (; n; n /= 2) { if (n & 1) y = mul(x, y); x = mul(x, x); } return y; } int inv(int x) { return qpow(x, mod - 2); } template <class X> struct LinearRecurrence { vector<X> s, f = {1}, g = {1}; int m = 1; X q = 1; void preduce(vector<X> &a) const { for (int n = sz(a); n -->= sz(f); a.pop_back()) { FOR (i, 1, sz(f)) a[n - i] = sub(a[n - i], mul(a.back(), f[i])); } } vector<X> pmul(vector<X> &a, vector<X> &b) const { vector<X> r(sz(a) + sz(b)); REP (i, sz(a)) REP (j, sz(b)) { r[i + j] = add(r[i + j], mul(a[i], b[j])); } preduce(r); return r; } X solve(ll n) const { return solve(n, n + 1)[0]; } vector<X> solve(ll from, ll to) const { vector<X> x = {0, 1}, r = {1}; for (ll n = from; n; n /= 2) { if (n & 1) r = pmul(r, x); x = pmul(x, x); } vector<X> res; FOR (n, from, to) { res.emplace_back(); REP (i, sz(r)) res.back() = add(res.back(), mul(r[i], s[i])); r.emplace(r.begin()); preduce(r); } return res; } bool next(X x) { int k = sz(s); s.pb(x); X p = 0; REP (i, sz(f)) p = add(p, mul(f[i], s[k - i])); if (p) { auto t = f; f.resize(max(sz(f), sz(g) + m)); X z = mul(p, inv(q)); REP (i, sz(g)) f[i + m] = sub(f[i + m], mul(g[i], z)); g = t; q = p; m = 1; } else if (++m > 128) { return false; } return true; } }; void test1() { mod = 1e9 + 7; LinearRecurrence<int> a; auto f = [](ll x) { return qpow(x % mod, x % 10); }; for (int x = 0; a.next(f(x)); ++x); assert(sz(a.f) == 101); REP (i, 100) { ll x = 1000000ll + i * 65537; assert(f(x) == a.solve(x)); } } uint32_t xorshift128() { static uint32_t x = 123456, y = 234567, z = 345678, w = 456789; uint32_t t = x ^ (x << 11); t ^= t >> 8; x = y; y = z; z = w; return w ^= (w >> 19) ^ t; } void test2() { mod = 2; LinearRecurrence<int> r; ll n = 0; for (; ; ) { uint32_t x = xorshift128(); bool ok = true; REP (i, 32) ok &= r.next((x >> i) & 1); n += 32; if (!ok) break; } const int SKIP = 10000000; const int N = 100; REP (k, SKIP) { xorshift128(); n += 32; } vector<int> c = r.solve(n, n + 32 * N); REP (k, N) { uint32_t x = 0; REP (i, 32) x |= c[k * 32 + i] << i; assert(xorshift128() == x); } } int main() { test1(); test2(); return 0; } <commit_msg>Little optimize.<commit_after>#include <bits/stdc++.h> #define UN(v) sort(all(v)), (v).erase(unique(all(v)), (v).end()) #define FOR(i, a, b) for (decltype(a) i(a), _B_##i(b); i < _B_##i; ++i) #define CL(a, b) memset(a, b, sizeof a) #define all(a) (a).begin(), (a).end() #define REP(i, n) FOR(i, 0, n) #define sz(a) int((a).size()) #define ll int64_t #define pb push_back #define Y second #define X first using namespace std; typedef pair<int, int> pii; int mod; int add(int x, int y) { return (x += y) < mod ? x : x - mod; } int sub(int x, int y) { return (x -= y) < 0 ? x + mod : x; } int mul(int x, int y) { return (ll)x * y % mod; } template <class X> X qpow(X x, X n) { X y{1}; for (; n; n /= 2) { if (n & 1) y = mul(x, y); x = mul(x, x); } return y; } int inv(int x) { return qpow(x, mod - 2); } template <class X> struct LinearRecurrence { vector<X> s, f = {1}, g = {1}; int m = 1; X q = 1; void preduce(vector<X> &a) const { for (int n = sz(a); n -->= sz(f); a.pop_back()) { FOR (i, 1, sz(f)) a[n - i] = sub(a[n - i], mul(a.back(), f[i])); } } vector<X> pmul(vector<X> &a, vector<X> &b) const { vector<X> r(sz(a) + sz(b)); REP (i, sz(a)) REP (j, sz(b)) { r[i + j] = add(r[i + j], mul(a[i], b[j])); } preduce(r); return r; } X solve(ll n) const { return solve(n, n + 1)[0]; } vector<X> solve(ll from, ll to) const { vector<X> x = {0, 1}, r = {1}; for (ll n = from; n; n /= 2) { if (n & 1) r = pmul(r, x); x = pmul(x, x); } vector<X> res; FOR (n, from, to) { res.emplace_back(); REP (i, sz(r)) res.back() = add(res.back(), mul(r[i], s[i])); r.emplace(r.begin()); preduce(r); } return res; } bool next(X x) { int k = sz(s); s.pb(x); X p = 0; REP (i, sz(f)) p = add(p, mul(f[i], s[k - i])); if (p) { auto t = f; f.resize(max(sz(f), sz(g) + m)); X z = mul(p, inv(q)); REP (i, sz(g)) f[i + m] = sub(f[i + m], mul(g[i], z)); for (; f.back() == 0; f.pop_back()); g = t; q = p; m = 1; } else if (++m > 128) { return false; } return true; } }; void test1() { mod = 1e9 + 7; LinearRecurrence<int> a; auto f = [](ll x) { return qpow(x % mod, x % 10); }; for (int x = 0; a.next(f(x)); ++x); assert(sz(a.f) == 101); REP (i, 100) { ll x = 1000000ll + i * 65537; assert(f(x) == a.solve(x)); } } uint32_t xorshift128() { static uint32_t x = 123456, y = 234567, z = 345678, w = 456789; uint32_t t = x ^ (x << 11); t ^= t >> 8; x = y; y = z; z = w; return w ^= (w >> 19) ^ t; } void test2() { mod = 2; LinearRecurrence<int> r; ll n = 0; for (; ; ) { uint32_t x = xorshift128(); bool ok = true; REP (i, 32) ok &= r.next((x >> i) & 1); n += 32; if (!ok) break; } const int SKIP = 10000000; const int N = 100; REP (k, SKIP) { xorshift128(); n += 32; } vector<int> c = r.solve(n, n + 32 * N); REP (k, N) { uint32_t x = 0; REP (i, 32) x |= c[k * 32 + i] << i; assert(xorshift128() == x); } } int main() { test1(); test2(); return 0; } <|endoftext|>
<commit_before>/* * Copyright (C) 2008-2013 The Communi Project * * This test is free, and not covered by the LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. */ #include "irclagtimer.h" #include "ircconnection.h" #include <QtTest/QtTest> class tst_IrcLagTimer : public QObject { Q_OBJECT private slots: void testDefaults(); void testInterval(); void testConnection(); }; void tst_IrcLagTimer::testDefaults() { IrcLagTimer timer; QCOMPARE(timer.lag(), -1); QVERIFY(!timer.connection()); QCOMPARE(timer.interval(), 60); } void tst_IrcLagTimer::testInterval() { IrcLagTimer timer; timer.setInterval(INT_MIN); QCOMPARE(timer.interval(), INT_MIN); timer.setInterval(0); QCOMPARE(timer.interval(), 0); timer.setInterval(INT_MAX); QCOMPARE(timer.interval(), INT_MAX); } void tst_IrcLagTimer::testConnection() { IrcLagTimer timer; IrcConnection* connection = new IrcConnection(&timer); timer.setConnection(connection); QCOMPARE(timer.connection(), connection); timer.setConnection(0); QVERIFY(!timer.connection()); } QTEST_MAIN(tst_IrcLagTimer) #include "tst_irclagtimer.moc" <commit_msg>Fix build<commit_after>/* * Copyright (C) 2008-2013 The Communi Project * * This test is free, and not covered by the LGPL license. There is no * restriction applied to their modification, redistribution, using and so on. * You can study them, modify them, use them in your own program - either * completely or partially. */ #include "irclagtimer.h" #include "ircconnection.h" #include <QtTest/QtTest> class tst_IrcLagTimer : public QObject { Q_OBJECT private slots: void testDefaults(); void testInterval(); void testConnection(); }; void tst_IrcLagTimer::testDefaults() { IrcLagTimer timer; QCOMPARE(timer.lag(), qint64(-1)); QVERIFY(!timer.connection()); QCOMPARE(timer.interval(), 60); } void tst_IrcLagTimer::testInterval() { IrcLagTimer timer; timer.setInterval(INT_MIN); QCOMPARE(timer.interval(), INT_MIN); timer.setInterval(0); QCOMPARE(timer.interval(), 0); timer.setInterval(INT_MAX); QCOMPARE(timer.interval(), INT_MAX); } void tst_IrcLagTimer::testConnection() { IrcLagTimer timer; IrcConnection* connection = new IrcConnection(&timer); timer.setConnection(connection); QCOMPARE(timer.connection(), connection); timer.setConnection(0); QVERIFY(!timer.connection()); } QTEST_MAIN(tst_IrcLagTimer) #include "tst_irclagtimer.moc" <|endoftext|>
<commit_before>#include <FalconEngine/Platform/Direct3D/Direct3DRendererState.h> #if defined(FALCON_ENGINE_API_DIRECT3D) #include <FalconEngine/Graphics/Renderer/State/BlendState.h> #include <FalconEngine/Graphics/Renderer/State/CullState.h> #include <FalconEngine/Graphics/Renderer/State/DepthTestState.h> #include <FalconEngine/Graphics/Renderer/State/OffsetState.h> #include <FalconEngine/Graphics/Renderer/State/StencilTestState.h> #include <FalconEngine/Graphics/Renderer/State/WireframeState.h> #include <FalconEngine/Platform/Direct3D/Direct3DMapping.h> namespace FalconEngine { /************************************************************************/ /* Constructors and Destructor */ /************************************************************************/ PlatformRendererState::PlatformRendererState() { } /************************************************************************/ /* Public Members */ /************************************************************************/ void PlatformRendererState::Initialize(ID3D11DeviceContext4 *context, ID3D11Device4 *device, const BlendState *blendState, const CullState *cullState, const DepthTestState *depthTestState, const OffsetState *offsetState, const StencilTestState *stencilTestState, const WireframeState *wireframeState) { // Blend State D3D11_BLEND_DESC1 blendDesc; ZeroMemory(&blendDesc, sizeof blendDesc); blendDesc.AlphaToCoverageEnable = false; // NEW(Wuxiang): Support MRT blending. blendDesc.IndependentBlendEnable = false; D3D11_RENDER_TARGET_BLEND_DESC1 blendDescRt; ZeroMemory(&blendDescRt, sizeof blendDescRt); blendDescRt.BlendEnable = blendState->mEnabled; blendDescRt.LogicOpEnable = false; blendDescRt.SrcBlend = Direct3DBlendFactor[BlendFactorIndex(blendState->mSourceFactor)]; blendDescRt.DestBlend = Direct3DBlendFactor[BlendFactorIndex(blendState->mDestinationFactor)]; blendDescRt.BlendOp = Direct3DBlendOperator[BlendOperatorIndex(blendState->mOperator)]; blendDescRt.SrcBlendAlpha = Direct3DBlendFactor[BlendFactorIndex(blendState->mSourceFactorAlpha)];; blendDescRt.DestBlendAlpha = Direct3DBlendFactor[BlendFactorIndex(blendState->mDestinationFactorAlpha)]; blendDescRt.BlendOpAlpha = Direct3DBlendOperator[BlendOperatorIndex(blendState->mOperatorAlpha)];; blendDescRt.LogicOp; UINT8 RenderTargetWriteMask; blendDesc.RenderTarget[0] = blendDescRt; device->CreateBlendState1(&blendDesc, mBlendState.ReleaseAndGetAddressOf()); context->OMSetBlendState(mBlendState.Get(), nullptr, 0xffffffff); // Depth Stencil State D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof depthStencilDesc); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = false; depthStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; depthStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; device->CreateDepthStencilState(&depthStencilDesc, mDepthStencilState.ReleaseAndGetAddressOf()); context->OMSetDepthStencilState(mDepthStencilState.Get(), 0); // Rasterizer State D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof rasterizerDesc); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.ScissorEnable = false; rasterizerDesc.MultisampleEnable = false; device->CreateRasterizerState(&rasterizerDesc, mRasterizerState.ReleaseAndGetAddressOf()); context->RSSetState(mRasterizerState.Get()); } } #endif<commit_msg>Finished Blend state initialization in D3D.<commit_after>#include <FalconEngine/Platform/Direct3D/Direct3DRendererState.h> #if defined(FALCON_ENGINE_API_DIRECT3D) #include <FalconEngine/Graphics/Renderer/State/BlendState.h> #include <FalconEngine/Graphics/Renderer/State/CullState.h> #include <FalconEngine/Graphics/Renderer/State/DepthTestState.h> #include <FalconEngine/Graphics/Renderer/State/OffsetState.h> #include <FalconEngine/Graphics/Renderer/State/StencilTestState.h> #include <FalconEngine/Graphics/Renderer/State/WireframeState.h> #include <FalconEngine/Platform/Direct3D/Direct3DMapping.h> namespace FalconEngine { /************************************************************************/ /* Constructors and Destructor */ /************************************************************************/ PlatformRendererState::PlatformRendererState() { } /************************************************************************/ /* Public Members */ /************************************************************************/ void PlatformRendererState::Initialize(ID3D11DeviceContext4 *context, ID3D11Device4 *device, const BlendState *blendState, const CullState *cullState, const DepthTestState *depthTestState, const OffsetState *offsetState, const StencilTestState *stencilTestState, const WireframeState *wireframeState) { // Blend State D3D11_BLEND_DESC1 blendDesc; ZeroMemory(&blendDesc, sizeof blendDesc); // NEW(Wuxiang): Add alpha to coverage support. blendDesc.AlphaToCoverageEnable = false; // NEW(Wuxiang): Support MRT blending. blendDesc.IndependentBlendEnable = false; D3D11_RENDER_TARGET_BLEND_DESC1 blendDescRt; ZeroMemory(&blendDescRt, sizeof blendDescRt); blendDescRt.BlendEnable = blendState->mEnabled; blendDescRt.BlendOp = Direct3DBlendOperator[BlendOperatorIndex(blendState->mOperator)]; blendDescRt.SrcBlend = Direct3DBlendFactor[BlendFactorIndex(blendState->mSourceFactor)]; blendDescRt.SrcBlendAlpha = Direct3DBlendFactor[BlendFactorIndex(blendState->mSourceFactorAlpha)];; blendDescRt.DestBlend = Direct3DBlendFactor[BlendFactorIndex(blendState->mDestinationFactor)]; blendDescRt.DestBlendAlpha = Direct3DBlendFactor[BlendFactorIndex(blendState->mDestinationFactorAlpha)]; blendDescRt.BlendOpAlpha = Direct3DBlendOperator[BlendOperatorIndex(blendState->mOperatorAlpha)];; blendDescRt.LogicOpEnable = blendState->mLogicEnabled; blendDescRt.LogicOp = Direct3DLogicOperator[LogicOperatorIndex(blendState->mLogicOperator)]; blendDescRt.RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL; blendDesc.RenderTarget[0] = blendDescRt; device->CreateBlendState1(&blendDesc, mBlendState.ReleaseAndGetAddressOf()); // NEW(Wuxiang): Add alpha to coverage support. context->OMSetBlendState(mBlendState.Get(), blendState->mConstantFactor.Data(), 0xffffffff); // Depth Stencil State D3D11_DEPTH_STENCIL_DESC depthStencilDesc; ZeroMemory(&depthStencilDesc, sizeof depthStencilDesc); depthStencilDesc.DepthEnable = true; depthStencilDesc.DepthWriteMask = D3D11_DEPTH_WRITE_MASK_ALL; depthStencilDesc.DepthFunc = D3D11_COMPARISON_LESS; depthStencilDesc.StencilEnable = false; depthStencilDesc.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; depthStencilDesc.StencilWriteMask = D3D11_DEFAULT_STENCIL_WRITE_MASK; depthStencilDesc.BackFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.BackFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.BackFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilDepthFailOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFunc = D3D11_COMPARISON_ALWAYS; depthStencilDesc.FrontFace.StencilPassOp = D3D11_STENCIL_OP_KEEP; depthStencilDesc.FrontFace.StencilFailOp = D3D11_STENCIL_OP_KEEP; device->CreateDepthStencilState(&depthStencilDesc, mDepthStencilState.ReleaseAndGetAddressOf()); context->OMSetDepthStencilState(mDepthStencilState.Get(), 0); // Rasterizer State D3D11_RASTERIZER_DESC rasterizerDesc; ZeroMemory(&rasterizerDesc, sizeof rasterizerDesc); rasterizerDesc.AntialiasedLineEnable = false; rasterizerDesc.CullMode = D3D11_CULL_BACK; rasterizerDesc.FillMode = D3D11_FILL_SOLID; rasterizerDesc.FrontCounterClockwise = false; rasterizerDesc.DepthBias = 0; rasterizerDesc.DepthBiasClamp = 0.0f; rasterizerDesc.DepthClipEnable = true; rasterizerDesc.ScissorEnable = false; rasterizerDesc.MultisampleEnable = false; device->CreateRasterizerState(&rasterizerDesc, mRasterizerState.ReleaseAndGetAddressOf()); context->RSSetState(mRasterizerState.Get()); } } #endif<|endoftext|>
<commit_before>#define BOOST_TEST_MODULE send_recv #include <boost/test/included/unit_test.hpp> #include <iostream> #include <limits> #include <cstddef> #include <complex> #include <mpl/mpl.hpp> template<typename T> bool send_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.send(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool bsend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) { const int size{comm_world.bsend_size<T>()}; mpl::bsend_buffer<> buff(size); comm_world.bsend(data, 1); } if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool ssend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.ssend(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool rsend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.rsend(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool sendrecv_test() { const mpl::communicator &comm_world=mpl::environment::comm_world(); int rank=comm_world.rank(); int size=comm_world.size(); T x[2]={T(rank), T(rank)}; comm_world.sendrecv(x[1], (rank+1)%size, mpl::tag(0), x[0], (rank-1+size)%size, mpl::tag(0)); return x[0]==T((rank-1+size)%size) and x[1]==T(rank); } BOOST_AUTO_TEST_CASE(send_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(send_recv_test(std::byte(77))); #endif BOOST_TEST(send_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(send_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(send_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(send_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(send_recv_test(static_cast<float>(3.14))); BOOST_TEST(send_recv_test(static_cast<double>(3.14))); BOOST_TEST(send_recv_test(static_cast<long double>(3.14))); BOOST_TEST(send_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(send_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(send_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(send_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(send_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(bsend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(bsend_recv_test(std::byte(77))); #endif BOOST_TEST(bsend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(bsend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(bsend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(bsend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(bsend_recv_test(static_cast<float>(3.14))); BOOST_TEST(bsend_recv_test(static_cast<double>(3.14))); BOOST_TEST(bsend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(bsend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(bsend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(bsend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(bsend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(bsend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(ssend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(ssend_recv_test(std::byte(77))); #endif BOOST_TEST(ssend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(ssend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(ssend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(ssend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(ssend_recv_test(static_cast<float>(3.14))); BOOST_TEST(ssend_recv_test(static_cast<double>(3.14))); BOOST_TEST(ssend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(ssend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(ssend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(ssend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(ssend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(ssend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(rsend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(rsend_recv_test(std::byte(77))); #endif BOOST_TEST(rsend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(rsend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(rsend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(rsend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(rsend_recv_test(static_cast<float>(3.14))); BOOST_TEST(rsend_recv_test(static_cast<double>(3.14))); BOOST_TEST(rsend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(rsend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(rsend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(rsend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(rsend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(rsend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(sendrecv) { // integer types #if __cplusplus>=201703L BOOST_TEST(sendrecv_test<std::byte>()); #endif BOOST_TEST(sendrecv_test<char>()); BOOST_TEST(sendrecv_test<signed char>()); BOOST_TEST(sendrecv_test<unsigned char>()); BOOST_TEST(sendrecv_test<signed short>()); BOOST_TEST(sendrecv_test<unsigned short>()); BOOST_TEST(sendrecv_test<signed int>()); BOOST_TEST(sendrecv_test<unsigned int>()); BOOST_TEST(sendrecv_test<signed long>()); BOOST_TEST(sendrecv_test<unsigned long>()); BOOST_TEST(sendrecv_test<signed long long>()); BOOST_TEST(sendrecv_test<unsigned long long>()); // character types BOOST_TEST(sendrecv_test<wchar_t>()); BOOST_TEST(sendrecv_test<char16_t>()); BOOST_TEST(sendrecv_test<char32_t>()); // floating point number types BOOST_TEST(sendrecv_test<float>()); BOOST_TEST(sendrecv_test<double>()); BOOST_TEST(sendrecv_test<long double>()); BOOST_TEST(sendrecv_test<float>()); BOOST_TEST(sendrecv_test<double>()); BOOST_TEST(sendrecv_test<long double>()); // logical type BOOST_TEST(sendrecv_test<bool>()); } <commit_msg>add test for sendrecv_replace<commit_after>#define BOOST_TEST_MODULE send_recv #include <boost/test/included/unit_test.hpp> #include <iostream> #include <limits> #include <cstddef> #include <complex> #include <mpl/mpl.hpp> template<typename T> bool send_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.send(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool bsend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) { const int size{comm_world.bsend_size<T>()}; mpl::bsend_buffer<> buff(size); comm_world.bsend(data, 1); } if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool ssend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.ssend(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool rsend_recv_test(const T &data) { const mpl::communicator &comm_world=mpl::environment::comm_world(); if (comm_world.size()<2) false; if (comm_world.rank()==0) comm_world.rsend(data, 1); if (comm_world.rank()==1) { T data_r; comm_world.recv(data_r, 0); return data_r==data; } return true; } template<typename T> bool sendrecv_test() { const mpl::communicator &comm_world=mpl::environment::comm_world(); int rank=comm_world.rank(); int size=comm_world.size(); T x[2]={T(rank), T(rank)}; comm_world.sendrecv(x[1], (rank+1)%size, mpl::tag(0), x[0], (rank-1+size)%size, mpl::tag(0)); return x[0]==T((rank-1+size)%size) and x[1]==T(rank); } template<typename T> bool sendrecv_replace_test() { const mpl::communicator &comm_world=mpl::environment::comm_world(); int rank=comm_world.rank(); int size=comm_world.size(); T x{T(rank)}; comm_world.sendrecv_replace(x, (rank+1)%size, mpl::tag(0), (rank-1+size)%size, mpl::tag(0)); return x==T((rank-1+size)%size); } BOOST_AUTO_TEST_CASE(send_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(send_recv_test(std::byte(77))); #endif BOOST_TEST(send_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(send_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(send_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(send_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(send_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(send_recv_test(static_cast<float>(3.14))); BOOST_TEST(send_recv_test(static_cast<double>(3.14))); BOOST_TEST(send_recv_test(static_cast<long double>(3.14))); BOOST_TEST(send_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(send_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(send_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(send_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(send_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(bsend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(bsend_recv_test(std::byte(77))); #endif BOOST_TEST(bsend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(bsend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(bsend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(bsend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(bsend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(bsend_recv_test(static_cast<float>(3.14))); BOOST_TEST(bsend_recv_test(static_cast<double>(3.14))); BOOST_TEST(bsend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(bsend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(bsend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(bsend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(bsend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(bsend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(ssend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(ssend_recv_test(std::byte(77))); #endif BOOST_TEST(ssend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(ssend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(ssend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(ssend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(ssend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(ssend_recv_test(static_cast<float>(3.14))); BOOST_TEST(ssend_recv_test(static_cast<double>(3.14))); BOOST_TEST(ssend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(ssend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(ssend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(ssend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(ssend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(ssend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(rsend_recv) { // integer types #if __cplusplus>=201703L BOOST_TEST(rsend_recv_test(std::byte(77))); #endif BOOST_TEST(rsend_recv_test(std::numeric_limits<char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned char>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed short>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned short>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed int>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned int>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<signed long long>::max()-1)); BOOST_TEST(rsend_recv_test(std::numeric_limits<unsigned long long>::max()-1)); // character types BOOST_TEST(rsend_recv_test(static_cast<wchar_t>('A'))); BOOST_TEST(rsend_recv_test(static_cast<char16_t>('A'))); BOOST_TEST(rsend_recv_test(static_cast<char32_t>('A'))); // floating point number types BOOST_TEST(rsend_recv_test(static_cast<float>(3.14))); BOOST_TEST(rsend_recv_test(static_cast<double>(3.14))); BOOST_TEST(rsend_recv_test(static_cast<long double>(3.14))); BOOST_TEST(rsend_recv_test(std::complex<float>(3.14, 2.72))); BOOST_TEST(rsend_recv_test(std::complex<double>(3.14, 2.72))); BOOST_TEST(rsend_recv_test(std::complex<long double>(3.14, 2.72))); // logical type BOOST_TEST(rsend_recv_test(true)); // enums enum class my_enum : int { val=std::numeric_limits<int>::max()-1 }; BOOST_TEST(rsend_recv_test(my_enum::val)); } BOOST_AUTO_TEST_CASE(sendrecv) { // integer types #if __cplusplus>=201703L BOOST_TEST(sendrecv_test<std::byte>()); #endif BOOST_TEST(sendrecv_test<char>()); BOOST_TEST(sendrecv_test<signed char>()); BOOST_TEST(sendrecv_test<unsigned char>()); BOOST_TEST(sendrecv_test<signed short>()); BOOST_TEST(sendrecv_test<unsigned short>()); BOOST_TEST(sendrecv_test<signed int>()); BOOST_TEST(sendrecv_test<unsigned int>()); BOOST_TEST(sendrecv_test<signed long>()); BOOST_TEST(sendrecv_test<unsigned long>()); BOOST_TEST(sendrecv_test<signed long long>()); BOOST_TEST(sendrecv_test<unsigned long long>()); // character types BOOST_TEST(sendrecv_test<wchar_t>()); BOOST_TEST(sendrecv_test<char16_t>()); BOOST_TEST(sendrecv_test<char32_t>()); // floating point number types BOOST_TEST(sendrecv_test<float>()); BOOST_TEST(sendrecv_test<double>()); BOOST_TEST(sendrecv_test<long double>()); BOOST_TEST(sendrecv_test<float>()); BOOST_TEST(sendrecv_test<double>()); BOOST_TEST(sendrecv_test<long double>()); // logical type BOOST_TEST(sendrecv_test<bool>()); } BOOST_AUTO_TEST_CASE(sendrecv_replace) { // integer types #if __cplusplus>=201703L BOOST_TEST(sendrecv_replace_test<std::byte>()); #endif BOOST_TEST(sendrecv_replace_test<char>()); BOOST_TEST(sendrecv_replace_test<signed char>()); BOOST_TEST(sendrecv_replace_test<unsigned char>()); BOOST_TEST(sendrecv_replace_test<signed short>()); BOOST_TEST(sendrecv_replace_test<unsigned short>()); BOOST_TEST(sendrecv_replace_test<signed int>()); BOOST_TEST(sendrecv_replace_test<unsigned int>()); BOOST_TEST(sendrecv_replace_test<signed long>()); BOOST_TEST(sendrecv_replace_test<unsigned long>()); BOOST_TEST(sendrecv_replace_test<signed long long>()); BOOST_TEST(sendrecv_replace_test<unsigned long long>()); // character types BOOST_TEST(sendrecv_replace_test<wchar_t>()); BOOST_TEST(sendrecv_replace_test<char16_t>()); BOOST_TEST(sendrecv_replace_test<char32_t>()); // floating point number types BOOST_TEST(sendrecv_replace_test<float>()); BOOST_TEST(sendrecv_replace_test<double>()); BOOST_TEST(sendrecv_replace_test<long double>()); BOOST_TEST(sendrecv_replace_test<float>()); BOOST_TEST(sendrecv_replace_test<double>()); BOOST_TEST(sendrecv_replace_test<long double>()); // logical type BOOST_TEST(sendrecv_replace_test<bool>()); } <|endoftext|>
<commit_before>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 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 * 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 * */ #include "contextc.h" #include "context.h" #include "logging.h" using namespace ContextProvider; QStringList *serviceKeyList = NULL; QString *serviceBusName = NULL; QDBusConnection::BusType serviceBusType; /// Initializes the service for the given \a name. \a is_system /// (1 or 0) specifies if this is a system service (system bus or session bus). The \a keys /// is a pointer to an array of pointers to NULL-terminated strings with key names. /// \a key_count specifies the number of items in the \a keys array. /// Returns 1 on success, 0 otherwise. This function internally calls Context::initService. int context_init_service (int is_system, const char *name, const char** keys, int key_count) { // Build the key string list QStringList keyList; int i; for (i = 0; i < key_count; i++) keyList.append(QString(keys[i])); QDBusConnection::BusType busType = (is_system) ? QDBusConnection::SystemBus : QDBusConnection::SessionBus; return Context::initService(busType, QString(name), keyList); } /// Creates a new ContextPtr handle that can be used to set/get values. \a name /// is a NULL-terminated key name. Returns the new allocated ContextPtr. Will never /// return NULL. You're supposed to destroy the ContextPtr with context_free. ContextPtr* context_new (const char *name) { Context *c = new Context(name); return (ContextPtr*) c; } /// Frees the provided \a ptr. Note that destroying the ContextPtr will not destroy /// the key itself. It's just the handle that's being destroyed. void context_free (ContextPtr *ptr) { delete ((Context*) ptr); } /// Returns the key that this context property \a ptr represents. /// The caller is responsible for freeing the returned string when /// it's not needed anymore. char* context_get_key (ContextPtr *ptr) { QString key = ((Context*) ptr)->getKey(); return qstrdup(key.toUtf8().constData()); } /// Returns 1 if the context property referenced by \a ptr is valid. int context_is_valid (ContextPtr *ptr) { return ((Context*) ptr)->isValid(); } /// Returns 1 if the context property referenced by \a ptr is set (it's not undetermined). int context_is_set (ContextPtr *ptr) { return ((Context*) ptr)->isSet(); } /// Unsets the context property referenced by \a ptr. The property value /// becomes undeterined. void context_unset (ContextPtr *ptr) { ((Context*) ptr)->unset(); } /// Sets the context property referenced by \a ptr to a new integer value \a v. /// Calls Context::set internally. void context_set_int(ContextPtr *ptr, int v) { ((Context*) ptr)->set(QVariant(v)); } /// Sets the context property referenced by \a ptr to a new bool value \a v. /// Calls Context::set internally. void context_set_bool(ContextPtr *ptr, int v) { ((Context*) ptr)->set(QVariant((bool) v)); } /// Sets the context property referenced by \a ptr to a new double value \a v. /// Calls Context::set internally. void context_set_double(ContextPtr *ptr, double v) { ((Context*) ptr)->set(QVariant(v)); } /// Sets the context property referenced by \a ptr to a new string value \a v. /// Calls Context::set internally. void context_set_string(ContextPtr *ptr, const char *v) { ((Context*) ptr)->set(QVariant(QString(v))); } /// Obtains the integer value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new integer value. int context_get_int (ContextPtr *ptr, int *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toInt(); return 1; } else { *v = 0; return 0; } } /// Obtains the string value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a point to a new NULL-terminated string. You have to \b destroy this string /// when done dealing with it. int context_get_string (ContextPtr *ptr, char **v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { QString str = var.toString(); *v = qstrdup(str.toUtf8().constData()); return 1; } else { *v = 0; return 0; } } /// Obtains the bool value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new bool (1, 0) value. int context_get_bool (ContextPtr *ptr, int *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toBool(); return 1; } else { *v = 0; return 0; } } /// Obtains the double value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new double value. int context_get_double (ContextPtr *ptr, double *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toDouble(); return 1; } else { *v = 0.0; return 0; } } static int reinitialize_service() { if (serviceKeyList->length() > 0) Context::stopService(*serviceBusName); return Context::initService(serviceBusType, *serviceBusName, *serviceKeyList); } int context_provider_init (DBusBusType bus_type, const char* bus_name) { if (serviceBusName != NULL) { contextCritical() << "Service already initialize. You can only initialize one service with C API"; return 0; } serviceBusType = (bus_type == DBUS_BUS_SESSION) ? QDBusConnection::SessionBus : QDBusConnection::SystemBus; serviceBusName = new QString(bus_name); serviceKeyList = new QStringList(); return reinitialize_service(); } void context_provider_stop (void) { contextDebug() << "Stopping service"; if (serviceBusName) { Context::stopService(*serviceBusName); } delete serviceBusName; serviceBusName = NULL; delete serviceKeyList; serviceKeyList = NULL; } void context_provider_install_key (const char* key, int clear_values_on_subscribe, ContextProviderSubscriptionChangedCallback subscription_changed_cb, void* subscription_changed_cb_target) { if (! serviceKeyList) { contextCritical() << "Can't install key:" << key << "because no service started."; return; } if (serviceKeyList->contains(QString(key))) { contextCritical() << "Key:" << key << "is already installed"; return; } serviceKeyList->append(key); reinitialize_service(); // FIXME Does not register the callback yet } <commit_msg>context_provider_install_key works like advertised.<commit_after>/* * Copyright (C) 2008 Nokia Corporation. * * Contact: Marius Vollmer <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public License * version 2.1 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 * 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 * */ #include "contextc.h" #include "context.h" #include "logging.h" #include "sconnect.h" using namespace ContextProvider; class ContextListener; QStringList *serviceKeyList = NULL; QString *serviceBusName = NULL; QDBusConnection::BusType serviceBusType; QList<ContextListener*> *contextListeners = NULL; class ContextListener : public QObject { Q_OBJECT public: ContextListener(const QString &k, ContextProviderSubscriptionChangedCallback cb, void *dt) : callback(cb), user_data(dt), key(k) { sconnect(&key, SIGNAL(firstSubscriberAppeared()), this, SLOT(onFirstSubscriberAppeared)); sconnect(&key, SIGNAL(lastSubscriberDisappeared()), this, SLOT(onLastSubscriberDisappeared)); } public slots: void onFirstSubscriberAppeared() { callback(1, user_data); } void onLastSubscriberDisappeared() { callback(0, user_data); } private: ContextProviderSubscriptionChangedCallback callback; void *user_data; Context key; }; /// Initializes the service for the given \a name. \a is_system /// (1 or 0) specifies if this is a system service (system bus or session bus). The \a keys /// is a pointer to an array of pointers to NULL-terminated strings with key names. /// \a key_count specifies the number of items in the \a keys array. /// Returns 1 on success, 0 otherwise. This function internally calls Context::initService. int context_init_service (int is_system, const char *name, const char** keys, int key_count) { // Build the key string list QStringList keyList; int i; for (i = 0; i < key_count; i++) keyList.append(QString(keys[i])); QDBusConnection::BusType busType = (is_system) ? QDBusConnection::SystemBus : QDBusConnection::SessionBus; return Context::initService(busType, QString(name), keyList); } /// Creates a new ContextPtr handle that can be used to set/get values. \a name /// is a NULL-terminated key name. Returns the new allocated ContextPtr. Will never /// return NULL. You're supposed to destroy the ContextPtr with context_free. ContextPtr* context_new (const char *name) { Context *c = new Context(name); return (ContextPtr*) c; } /// Frees the provided \a ptr. Note that destroying the ContextPtr will not destroy /// the key itself. It's just the handle that's being destroyed. void context_free (ContextPtr *ptr) { delete ((Context*) ptr); } /// Returns the key that this context property \a ptr represents. /// The caller is responsible for freeing the returned string when /// it's not needed anymore. char* context_get_key (ContextPtr *ptr) { QString key = ((Context*) ptr)->getKey(); return qstrdup(key.toUtf8().constData()); } /// Returns 1 if the context property referenced by \a ptr is valid. int context_is_valid (ContextPtr *ptr) { return ((Context*) ptr)->isValid(); } /// Returns 1 if the context property referenced by \a ptr is set (it's not undetermined). int context_is_set (ContextPtr *ptr) { return ((Context*) ptr)->isSet(); } /// Unsets the context property referenced by \a ptr. The property value /// becomes undeterined. void context_unset (ContextPtr *ptr) { ((Context*) ptr)->unset(); } /// Sets the context property referenced by \a ptr to a new integer value \a v. /// Calls Context::set internally. void context_set_int(ContextPtr *ptr, int v) { ((Context*) ptr)->set(QVariant(v)); } /// Sets the context property referenced by \a ptr to a new bool value \a v. /// Calls Context::set internally. void context_set_bool(ContextPtr *ptr, int v) { ((Context*) ptr)->set(QVariant((bool) v)); } /// Sets the context property referenced by \a ptr to a new double value \a v. /// Calls Context::set internally. void context_set_double(ContextPtr *ptr, double v) { ((Context*) ptr)->set(QVariant(v)); } /// Sets the context property referenced by \a ptr to a new string value \a v. /// Calls Context::set internally. void context_set_string(ContextPtr *ptr, const char *v) { ((Context*) ptr)->set(QVariant(QString(v))); } /// Obtains the integer value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new integer value. int context_get_int (ContextPtr *ptr, int *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toInt(); return 1; } else { *v = 0; return 0; } } /// Obtains the string value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a point to a new NULL-terminated string. You have to \b destroy this string /// when done dealing with it. int context_get_string (ContextPtr *ptr, char **v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { QString str = var.toString(); *v = qstrdup(str.toUtf8().constData()); return 1; } else { *v = 0; return 0; } } /// Obtains the bool value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new bool (1, 0) value. int context_get_bool (ContextPtr *ptr, int *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toBool(); return 1; } else { *v = 0; return 0; } } /// Obtains the double value of the context property described by the \a ptr. /// Returns 1 if the property retrieval was succesful. 0 when property /// value is \b Undetermined. When retrieval was succesful, \a v is set /// to a new double value. int context_get_double (ContextPtr *ptr, double *v) { QVariant var = ((Context*) ptr)->get(); if (var.isValid()) { *v = var.toDouble(); return 1; } else { *v = 0.0; return 0; } } static int reinitialize_service() { if (serviceKeyList->length() > 0) Context::stopService(*serviceBusName); return Context::initService(serviceBusType, *serviceBusName, *serviceKeyList); } int context_provider_init (DBusBusType bus_type, const char* bus_name) { if (serviceBusName != NULL) { contextCritical() << "Service already initialize. You can only initialize one service with C API"; return 0; } serviceBusType = (bus_type == DBUS_BUS_SESSION) ? QDBusConnection::SessionBus : QDBusConnection::SystemBus; serviceBusName = new QString(bus_name); serviceKeyList = new QStringList(); contextListeners = new QList<ContextListener*>; return reinitialize_service(); } void context_provider_stop (void) { contextDebug() << "Stopping service"; if (serviceBusName) { Context::stopService(*serviceBusName); } // Delete all listeners foreach (ContextListener *listener, *contextListeners) delete listener; delete serviceBusName; serviceBusName = NULL; delete serviceKeyList; serviceKeyList = NULL; delete contextListeners; contextListeners = NULL; } void context_provider_install_key (const char* key, int clear_values_on_subscribe, ContextProviderSubscriptionChangedCallback subscription_changed_cb, void* subscription_changed_cb_target) { if (! serviceKeyList) { contextCritical() << "Can't install key:" << key << "because no service started."; return; } if (serviceKeyList->contains(QString(key))) { contextCritical() << "Key:" << key << "is already installed"; return; } serviceKeyList->append(key); reinitialize_service(); contextListeners->append(new ContextListener(key, subscription_changed_cb, subscription_changed_cb_target)); } <|endoftext|>
<commit_before>/* * Copyright 2000-2008, François Revol, <[email protected]>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "Utils.h" #include <FindDirectory.h> #include <Path.h> #include <String.h> #include <BeBuild.h> #include <malloc.h> #include <stdio.h> // some private font information structs namespace BPrivate { typedef struct font_folder_info { //char name[256]; char *name; uint32 flags; } font_folder_info; typedef struct font_file_info { char *name; uint32 flags; font_family family; font_style style; uint32 dummy; } font_file_info; }; using namespace BPrivate; // this is PRIVATE to libbe and NOT in R5!!! extern long _count_font_folders_(void); extern long _count_font_files_(long); extern status_t _get_nth_font_file_(long, font_file_info **); extern status_t _get_nth_font_folder_(long, font_folder_info **); status_t find_font_file(entry_ref *to, font_family family, font_style style, float size) { #ifdef B_BEOS_VERSION_DANO status_t err = ENOENT; long i, fontcount, foldercount; font_file_info *ffi; font_folder_info *fdi; bool found = false; (void)size; fontcount = _count_font_files_(0); for (i = 0; i < fontcount; i++) { err = _get_nth_font_file_(i, &ffi); if (err) continue; if (strcmp(ffi->family, family) || strcmp(ffi->style, style)) continue; found = true; break; } if (!found) return ENOENT; foldercount = _count_font_folders_(); for (i = 0; i < fontcount; i++) { err = _get_nth_font_folder_(i, &fdi); if (err) continue; BPath ffile(fdi->name); ffile.Append(ffi->name); printf("find_font_file: looking for '%s' in '%s'\n", ffi->name, fdi->name); BEntry ent(ffile.Path()); if (ent.InitCheck()) continue; printf("find_font_file: found\n."); return ent.GetRef(to); } #endif return ENOENT; } #define _BORK(_t) \ err = find_directory(_t, &path); \ if (!err && (s = dir->FindFirst(path.Path())) >= 0) { \ printf("found %s\n", #_t); \ dir->Remove(s, strlen(path.Path()) - s); \ BString tok(#_t); \ tok.Prepend("${"); \ tok.Append("}"); \ dir->Insert(tok, s); \ return B_OK; \ } \ status_t escape_find_directory(BString *dir) { status_t err; BPath path; int32 s; _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); //_BORK(B_ROOT_DIRECTORY); //_BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_DIRECTORY); // same for the whole block, prefer user over common _BORK(B_COMMON_BOOT_DIRECTORY); _BORK(B_COMMON_FONTS_DIRECTORY); _BORK(B_COMMON_LIB_DIRECTORY); _BORK(B_COMMON_SERVERS_DIRECTORY); _BORK(B_COMMON_BIN_DIRECTORY); _BORK(B_COMMON_ETC_DIRECTORY); _BORK(B_COMMON_DOCUMENTATION_DIRECTORY); _BORK(B_COMMON_SETTINGS_DIRECTORY); _BORK(B_COMMON_DEVELOP_DIRECTORY); _BORK(B_COMMON_LOG_DIRECTORY); _BORK(B_COMMON_SPOOL_DIRECTORY); _BORK(B_COMMON_TEMP_DIRECTORY); _BORK(B_COMMON_VAR_DIRECTORY); _BORK(B_COMMON_TRANSLATORS_DIRECTORY); _BORK(B_COMMON_MEDIA_NODES_DIRECTORY); _BORK(B_COMMON_SOUNDS_DIRECTORY); // _BORK(B_COMMON_ADDONS_DIRECTORY); _BORK(B_COMMON_SYSTEM_DIRECTORY); _BORK(B_COMMON_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); return B_OK; } #undef _BORK #define _BORK(_t) \ if (tok == #_t) { \ err = find_directory(_t, &path); \ if (err) return err; \ dir->Remove(s, e - s + 1); \ dir->Insert(path.Path(), s); \ return B_OK; \ } \ status_t unescape_find_directory(BString *dir) { status_t err = B_ERROR; int32 s, e; BString tok; BPath path; s = dir->FindFirst("${"); if (s < 0) return B_OK; e = dir->FindFirst("}", s); if (e < 0) return B_OK; dir->CopyInto(tok, s + 2, e - s - 2); //printf("tok '%s'\n", tok.String()); _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); #ifdef B_BEOS_VERSION_DANO _BORK(B_ROOT_DIRECTORY); #endif _BORK(B_BEOS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_COMMON_DIRECTORY); _BORK(B_COMMON_SYSTEM_DIRECTORY); _BORK(B_COMMON_ADDONS_DIRECTORY); _BORK(B_COMMON_BOOT_DIRECTORY); _BORK(B_COMMON_FONTS_DIRECTORY); _BORK(B_COMMON_LIB_DIRECTORY); _BORK(B_COMMON_SERVERS_DIRECTORY); _BORK(B_COMMON_BIN_DIRECTORY); _BORK(B_COMMON_ETC_DIRECTORY); _BORK(B_COMMON_DOCUMENTATION_DIRECTORY); _BORK(B_COMMON_SETTINGS_DIRECTORY); _BORK(B_COMMON_DEVELOP_DIRECTORY); _BORK(B_COMMON_LOG_DIRECTORY); _BORK(B_COMMON_SPOOL_DIRECTORY); _BORK(B_COMMON_TEMP_DIRECTORY); _BORK(B_COMMON_VAR_DIRECTORY); _BORK(B_COMMON_TRANSLATORS_DIRECTORY); _BORK(B_COMMON_MEDIA_NODES_DIRECTORY); _BORK(B_COMMON_SOUNDS_DIRECTORY); _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); return B_OK; } #undef _BORK // copy a file including its attributes #define BUFF_SZ 1024*1024 status_t copy_file(entry_ref *ref, const char *to) { char *buff; status_t err = B_OK; //off_t off; //size_t got; (void)ref; (void)to; buff = (char *)malloc(BUFF_SZ); // XXX: TODO free(buff); return err; } int testhook() { status_t err; BString str("/boot/home/config/fonts/ttfonts/toto.ttf"); err = escape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); err = unescape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); return 0; } status_t FindRGBColor(BMessage &message, const char *name, int32 index, rgb_color *c) { #ifdef B_BEOS_VERSION_DANO return message.FindRGBColor(name, index, c); #else const void *data; ssize_t len; status_t err; err = message.FindData(name, B_RGB_COLOR_TYPE, index, &data, &len); if (err < B_OK) return err; if (len > (ssize_t)sizeof(*c)) return E2BIG; // Hack memcpy((void *)c, data, len); return B_OK; #endif } status_t AddRGBColor(BMessage &message, const char *name, rgb_color a_color, type_code type) { #ifdef B_BEOS_VERSION_DANO return message.AddRGBColor(name, a_color, type); #else return message.AddData(name, type, &a_color, sizeof(a_color)); #endif } status_t FindFont(BMessage &message, const char *name, int32 index, BFont *f) { #ifdef B_BEOS_VERSION_DANO return message.FindFlat(name, index, f); #else const void *data; ssize_t len; status_t err = message.FindData(name, 'FONt', index, &data, &len); #define DERR(e) { PRINT(("%s: err: %s\n", __FUNCTION__, strerror(e))); } if (err < B_OK) return err; if (len > (ssize_t)sizeof(*f)) return E2BIG; // Hack: only Dano has BFont : public BFlattenable memcpy((void *)f, data, len); return B_OK; #endif } status_t AddFont(BMessage &message, const char *name, BFont *f, int32 count) { #ifdef B_BEOS_VERSION_DANO return message.AddFlat(name, f, count); #else return message.AddData(name, 'FONt', (void *)&f, sizeof(f), true, count); #endif } <commit_msg>Sync directory listing to that in FindDirectory.h<commit_after>/* * Copyright 2000-2008, François Revol, <[email protected]>. All rights reserved. * Distributed under the terms of the MIT License. */ #include "Utils.h" #include <FindDirectory.h> #include <Path.h> #include <String.h> #include <BeBuild.h> #include <malloc.h> #include <stdio.h> // some private font information structs namespace BPrivate { typedef struct font_folder_info { //char name[256]; char *name; uint32 flags; } font_folder_info; typedef struct font_file_info { char *name; uint32 flags; font_family family; font_style style; uint32 dummy; } font_file_info; }; using namespace BPrivate; // this is PRIVATE to libbe and NOT in R5!!! extern long _count_font_folders_(void); extern long _count_font_files_(long); extern status_t _get_nth_font_file_(long, font_file_info **); extern status_t _get_nth_font_folder_(long, font_folder_info **); status_t find_font_file(entry_ref *to, font_family family, font_style style, float size) { #ifdef B_BEOS_VERSION_DANO status_t err = ENOENT; long i, fontcount, foldercount; font_file_info *ffi; font_folder_info *fdi; bool found = false; (void)size; fontcount = _count_font_files_(0); for (i = 0; i < fontcount; i++) { err = _get_nth_font_file_(i, &ffi); if (err) continue; if (strcmp(ffi->family, family) || strcmp(ffi->style, style)) continue; found = true; break; } if (!found) return ENOENT; foldercount = _count_font_folders_(); for (i = 0; i < fontcount; i++) { err = _get_nth_font_folder_(i, &fdi); if (err) continue; BPath ffile(fdi->name); ffile.Append(ffi->name); printf("find_font_file: looking for '%s' in '%s'\n", ffi->name, fdi->name); BEntry ent(ffile.Path()); if (ent.InitCheck()) continue; printf("find_font_file: found\n."); return ent.GetRef(to); } #endif return ENOENT; } #define _BORK(_t) \ err = find_directory(_t, &path); \ if (!err && (s = dir->FindFirst(path.Path())) >= 0) { \ printf("found %s\n", #_t); \ dir->Remove(s, strlen(path.Path()) - s); \ BString tok(#_t); \ tok.Prepend("${"); \ tok.Append("}"); \ dir->Insert(tok, s); \ return B_OK; \ } \ status_t escape_find_directory(BString *dir) { status_t err; BPath path; int32 s; /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_BEOS_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK #define _BORK(_t) \ if (tok == #_t) { \ err = find_directory(_t, &path); \ if (err) return err; \ dir->Remove(s, e - s + 1); \ dir->Insert(path.Path(), s); \ return B_OK; \ } \ status_t unescape_find_directory(BString *dir) { status_t err = B_ERROR; int32 s, e; BString tok; BPath path; s = dir->FindFirst("${"); if (s < 0) return B_OK; e = dir->FindFirst("}", s); if (e < 0) return B_OK; dir->CopyInto(tok, s + 2, e - s - 2); //printf("tok '%s'\n", tok.String()); /* This is just the entire directory_which from FindDirectory.h */ _BORK(B_DESKTOP_DIRECTORY); _BORK(B_TRASH_DIRECTORY); _BORK(B_BEOS_BOOT_DIRECTORY); _BORK(B_BEOS_FONTS_DIRECTORY); _BORK(B_BEOS_LIB_DIRECTORY); _BORK(B_BEOS_SERVERS_DIRECTORY); _BORK(B_BEOS_APPS_DIRECTORY); _BORK(B_BEOS_BIN_DIRECTORY); _BORK(B_BEOS_ETC_DIRECTORY); _BORK(B_BEOS_DOCUMENTATION_DIRECTORY); _BORK(B_BEOS_PREFERENCES_DIRECTORY); _BORK(B_BEOS_TRANSLATORS_DIRECTORY); _BORK(B_BEOS_MEDIA_NODES_DIRECTORY); _BORK(B_BEOS_SOUNDS_DIRECTORY); _BORK(B_BEOS_DATA_DIRECTORY); // not in the declared order, so others are picked first _BORK(B_BEOS_ADDONS_DIRECTORY); _BORK(B_BEOS_SYSTEM_DIRECTORY); _BORK(B_BEOS_DIRECTORY); _BORK(B_USER_BOOT_DIRECTORY); _BORK(B_USER_FONTS_DIRECTORY); _BORK(B_USER_LIB_DIRECTORY); _BORK(B_USER_SETTINGS_DIRECTORY); _BORK(B_USER_DESKBAR_DIRECTORY); _BORK(B_USER_PRINTERS_DIRECTORY); _BORK(B_USER_TRANSLATORS_DIRECTORY); _BORK(B_USER_MEDIA_NODES_DIRECTORY); _BORK(B_USER_SOUNDS_DIRECTORY); // Out of order again. _BORK(B_USER_DIRECTORY); _BORK(B_USER_CONFIG_DIRECTORY); _BORK(B_USER_ADDONS_DIRECTORY); _BORK(B_USER_DATA_DIRECTORY); _BORK(B_USER_CACHE_DIRECTORY); _BORK(B_USER_PACKAGES_DIRECTORY); _BORK(B_USER_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DIRECTORY); _BORK(B_USER_NONPACKAGED_ADDONS_DIRECTORY); _BORK(B_USER_NONPACKAGED_TRANSLATORS_DIRECTORY); _BORK(B_USER_NONPACKAGED_MEDIA_NODES_DIRECTORY); _BORK(B_USER_NONPACKAGED_BIN_DIRECTORY); _BORK(B_USER_NONPACKAGED_DATA_DIRECTORY); _BORK(B_USER_NONPACKAGED_FONTS_DIRECTORY); _BORK(B_USER_NONPACKAGED_SOUNDS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DOCUMENTATION_DIRECTORY); _BORK(B_USER_NONPACKAGED_LIB_DIRECTORY); _BORK(B_USER_NONPACKAGED_HEADERS_DIRECTORY); _BORK(B_USER_NONPACKAGED_DEVELOP_DIRECTORY); _BORK(B_USER_DEVELOP_DIRECTORY); _BORK(B_USER_DOCUMENTATION_DIRECTORY); _BORK(B_USER_SERVERS_DIRECTORY); _BORK(B_USER_APPS_DIRECTORY); _BORK(B_USER_BIN_DIRECTORY); _BORK(B_USER_PREFERENCES_DIRECTORY); _BORK(B_USER_ETC_DIRECTORY); _BORK(B_USER_LOG_DIRECTORY); _BORK(B_USER_SPOOL_DIRECTORY); _BORK(B_USER_VAR_DIRECTORY); _BORK(B_APPS_DIRECTORY); _BORK(B_PREFERENCES_DIRECTORY); _BORK(B_UTILITIES_DIRECTORY); _BORK(B_PACKAGE_LINKS_DIRECTORY); return B_OK; } #undef _BORK // copy a file including its attributes #define BUFF_SZ 1024*1024 status_t copy_file(entry_ref *ref, const char *to) { char *buff; status_t err = B_OK; //off_t off; //size_t got; (void)ref; (void)to; buff = (char *)malloc(BUFF_SZ); // XXX: TODO free(buff); return err; } int testhook() { status_t err; BString str("/boot/home/config/fonts/ttfonts/toto.ttf"); err = escape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); err = unescape_find_directory(&str); printf("error 0x%08lx %s\n", err, str.String()); return 0; } status_t FindRGBColor(BMessage &message, const char *name, int32 index, rgb_color *c) { #ifdef B_BEOS_VERSION_DANO return message.FindRGBColor(name, index, c); #else const void *data; ssize_t len; status_t err; err = message.FindData(name, B_RGB_COLOR_TYPE, index, &data, &len); if (err < B_OK) return err; if (len > (ssize_t)sizeof(*c)) return E2BIG; // Hack memcpy((void *)c, data, len); return B_OK; #endif } status_t AddRGBColor(BMessage &message, const char *name, rgb_color a_color, type_code type) { #ifdef B_BEOS_VERSION_DANO return message.AddRGBColor(name, a_color, type); #else return message.AddData(name, type, &a_color, sizeof(a_color)); #endif } status_t FindFont(BMessage &message, const char *name, int32 index, BFont *f) { #ifdef B_BEOS_VERSION_DANO return message.FindFlat(name, index, f); #else const void *data; ssize_t len; status_t err = message.FindData(name, 'FONt', index, &data, &len); #define DERR(e) { PRINT(("%s: err: %s\n", __FUNCTION__, strerror(e))); } if (err < B_OK) return err; if (len > (ssize_t)sizeof(*f)) return E2BIG; // Hack: only Dano has BFont : public BFlattenable memcpy((void *)f, data, len); return B_OK; #endif } status_t AddFont(BMessage &message, const char *name, BFont *f, int32 count) { #ifdef B_BEOS_VERSION_DANO return message.AddFlat(name, f, count); #else return message.AddData(name, 'FONt', (void *)&f, sizeof(f), true, count); #endif } <|endoftext|>
<commit_before>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, 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 holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // $Id$ // $URL$ // Maintainer: joaander /*! \file PDBDumpWriter.cc \brief Defines the PDBDumpWriter class */ // this file was written from scratch, but some error checks and PDB snprintf strings were copied from VMD's molfile plugin // it is used under the following license // University of Illinois Open Source License // Copyright 2003 Theoretical and Computational Biophysics Group, // All rights reserved. // Developed by: Theoretical and Computational Biophysics Group // University of Illinois at Urbana-Champaign // http://www.ks.uiuc.edu/ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4244 ) #endif #include <boost/python.hpp> using namespace boost::python; #include <string> #include <fstream> #include <iomanip> #include <stdio.h> #include "PDBDumpWriter.h" #include "BondData.h" using namespace std; using namespace boost; /*! \param sysdef System definition containing particle data to write \param base_fname Base filename to expand with **timestep**.pdb when writing */ PDBDumpWriter::PDBDumpWriter(boost::shared_ptr<SystemDefinition> sysdef, std::string base_fname) : Analyzer(sysdef), m_base_fname(base_fname), m_output_bond(false) { } /*! \param timestep Current time step of the simulation analzye() constructs af file name m_base_fname.**timestep**.pdb and writes out the current state of the system to that file. */ void PDBDumpWriter::analyze(unsigned int timestep) { if (m_prof) m_prof->push("Dump PDB"); ostringstream full_fname; string filetype = ".pdb"; // Generate a filename with the timestep padded to ten zeros full_fname << m_base_fname << "." << setfill('0') << setw(10) << timestep << filetype; // then write the file writeFile(full_fname.str()); if (m_prof) m_prof->pop(); } /*! \param fname File name to write Writes the current state of the system to the pdb file \a fname */ void PDBDumpWriter::writeFile(std::string fname) { // open the file for writing ofstream f(fname.c_str()); f.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit ); if (!f.good()) { cerr << endl << "***Error! Unable to open dump file for writing: " << fname << endl << endl; throw runtime_error("Error writting pdb dump file"); } // acquire the particle data ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); // get the box dimensions Scalar Lx,Ly,Lz; BoxDim box = m_pdata->getBox(); Lx=Scalar(box.xhi-box.xlo); Ly=Scalar(box.yhi-box.ylo); Lz=Scalar(box.zhi-box.zlo); // start writing the heinous PDB format const int linesize = 82; char buf[linesize]; // output the box dimensions snprintf(buf, linesize, "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1 1\n", Lx,Ly,Lz, 90.0, 90.0, 90.0); f << buf; // write out all the atoms for (unsigned int i = 0; i < m_pdata->getN(); i++) { // first check that everything will fit into the PDB output if (arrays.x[i] < -999.9994f || arrays.x[i] > 9999.9994f || arrays.y[i] < -999.9994f || arrays.y[i] > 9999.9994f || arrays.z[i] < -999.9994f || arrays.z[i] > 9999.9994f) { cerr << "***Error! Coordinate " << arrays.x[i] << " " << arrays.y[i] << " " << arrays.z[i] << " is out of range for PDB writing" << endl << endl; throw runtime_error("Error writing PDB file"); } // check the length of the type name const string &type_name = m_pdata->getNameByType(arrays.type[i]); if (type_name.size() > 4) { cerr << "***Error! Type " << type_name << " is too long for PDB writing" << endl << endl; throw runtime_error("Error writing PDB file"); } // start preparing the stuff to write (copied from VMD's molfile plugin) char indexbuf[32]; char residbuf[32]; char segnamebuf[5]; char altlocchar; /* XXX */ /* if the atom or residue indices exceed the legal PDB spec, we */ /* start emitting asterisks or hexadecimal strings rather than */ /* aborting. This is not really legal, but is an accepted hack */ /* among various other programs that deal with large PDB files */ /* If we run out of hexadecimal indices, then we just print */ /* asterisks. */ if (i < 100000) { sprintf(indexbuf, "%5d", i); } else if (i < 1048576) { sprintf(indexbuf, "%05x", i); } else { sprintf(indexbuf, "*****"); } /*if (resid < 10000) { sprintf(residbuf, "%4d", resid); } else if (resid < 65536) { sprintf(residbuf, "%04x", resid); } else { sprintf(residbuf, "****"); }*/ sprintf(residbuf, "%4d", 1); //altlocchar = altloc[0]; //if (altlocchar == '\0') { altlocchar = ' '; //} /* make sure the segname does not overflow the format */ sprintf(segnamebuf, "SEG "); snprintf(buf, linesize, "%-6s%5s %4s%c%-4s%c%4s%c %8.3f%8.3f%8.3f%6.2f%6.2f %-4s%2s\n", "ATOM ", indexbuf, type_name.c_str(), altlocchar, "RES", ' ', residbuf, ' ', arrays.x[i], arrays.y[i], arrays.z[i], 0.0f, 0.0f, segnamebuf, " "); f << buf; } if (m_output_bond) { // error check: pdb files cannot contain bonds with 100,000 or more atom records if (m_pdata->getN() >= 100000) { cerr << endl << "***Error! PDB files with bonds cannot hold more than 99,999 atoms!" << endl << endl; throw runtime_error("Error dumping PDB file"); } // grab the bond data shared_ptr<BondData> bond_data = m_sysdef->getBondData(); for (unsigned int i = 0; i < bond_data->getNumBonds(); i++) { Bond bond = bond_data->getBond(i); snprintf(buf, linesize, "CONECT%1$5d%2$5d\n", bond.a, bond.b); f << buf; } } // release the particle data m_pdata->release(); } void export_PDBDumpWriter() { class_<PDBDumpWriter, boost::shared_ptr<PDBDumpWriter>, bases<Analyzer>, boost::noncopyable> ("PDBDumpWriter", init< boost::shared_ptr<SystemDefinition>, std::string >()) .def("setOutputBond", &PDBDumpWriter::setOutputBond) .def("writeFile", &PDBDumpWriter::writeFile) ; } #ifdef WIN32 #pragma warning( pop ) #endif <commit_msg>Fixed a bug where dump.pdb wrote coordinates in the wrong order. Ticket #422<commit_after>/* Highly Optimized Object-oriented Many-particle Dynamics -- Blue Edition (HOOMD-blue) Open Source Software License Copyright 2008, 2009 Ames Laboratory Iowa State University and The Regents of the University of Michigan All rights reserved. HOOMD-blue may contain modifications ("Contributions") provided, and to which copyright is held, by various Contributors who have granted The Regents of the University of Michigan the right to modify and/or distribute such Contributions. Redistribution and use of HOOMD-blue, 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 holder nor the names of HOOMD-blue's contributors may be used to endorse or promote products derived from this software without specific prior written permission. Disclaimer THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND/OR ANY WARRANTIES THAT THIS SOFTWARE IS FREE OF INFRINGEMENT 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. */ // $Id$ // $URL$ // Maintainer: joaander /*! \file PDBDumpWriter.cc \brief Defines the PDBDumpWriter class */ // this file was written from scratch, but some error checks and PDB snprintf strings were copied from VMD's molfile plugin // it is used under the following license // University of Illinois Open Source License // Copyright 2003 Theoretical and Computational Biophysics Group, // All rights reserved. // Developed by: Theoretical and Computational Biophysics Group // University of Illinois at Urbana-Champaign // http://www.ks.uiuc.edu/ #ifdef WIN32 #pragma warning( push ) #pragma warning( disable : 4244 ) #endif #include <boost/python.hpp> using namespace boost::python; #include <string> #include <fstream> #include <iomanip> #include <stdio.h> #include "PDBDumpWriter.h" #include "BondData.h" using namespace std; using namespace boost; /*! \param sysdef System definition containing particle data to write \param base_fname Base filename to expand with **timestep**.pdb when writing */ PDBDumpWriter::PDBDumpWriter(boost::shared_ptr<SystemDefinition> sysdef, std::string base_fname) : Analyzer(sysdef), m_base_fname(base_fname), m_output_bond(false) { } /*! \param timestep Current time step of the simulation analzye() constructs af file name m_base_fname.**timestep**.pdb and writes out the current state of the system to that file. */ void PDBDumpWriter::analyze(unsigned int timestep) { if (m_prof) m_prof->push("Dump PDB"); ostringstream full_fname; string filetype = ".pdb"; // Generate a filename with the timestep padded to ten zeros full_fname << m_base_fname << "." << setfill('0') << setw(10) << timestep << filetype; // then write the file writeFile(full_fname.str()); if (m_prof) m_prof->pop(); } /*! \param fname File name to write Writes the current state of the system to the pdb file \a fname */ void PDBDumpWriter::writeFile(std::string fname) { // open the file for writing ofstream f(fname.c_str()); f.exceptions ( ifstream::eofbit | ifstream::failbit | ifstream::badbit ); if (!f.good()) { cerr << endl << "***Error! Unable to open dump file for writing: " << fname << endl << endl; throw runtime_error("Error writting pdb dump file"); } // acquire the particle data ParticleDataArraysConst arrays = m_pdata->acquireReadOnly(); // get the box dimensions Scalar Lx,Ly,Lz; BoxDim box = m_pdata->getBox(); Lx=Scalar(box.xhi-box.xlo); Ly=Scalar(box.yhi-box.ylo); Lz=Scalar(box.zhi-box.zlo); // start writing the heinous PDB format const int linesize = 82; char buf[linesize]; // output the box dimensions snprintf(buf, linesize, "CRYST1%9.3f%9.3f%9.3f%7.2f%7.2f%7.2f P 1 1\n", Lx,Ly,Lz, 90.0, 90.0, 90.0); f << buf; // write out all the atoms for (unsigned int j = 0; j < m_pdata->getN(); j++) { int i; i= arrays.rtag[j]; // first check that everything will fit into the PDB output if (arrays.x[i] < -999.9994f || arrays.x[i] > 9999.9994f || arrays.y[i] < -999.9994f || arrays.y[i] > 9999.9994f || arrays.z[i] < -999.9994f || arrays.z[i] > 9999.9994f) { cerr << "***Error! Coordinate " << arrays.x[i] << " " << arrays.y[i] << " " << arrays.z[i] << " is out of range for PDB writing" << endl << endl; throw runtime_error("Error writing PDB file"); } // check the length of the type name const string &type_name = m_pdata->getNameByType(arrays.type[i]); if (type_name.size() > 4) { cerr << "***Error! Type " << type_name << " is too long for PDB writing" << endl << endl; throw runtime_error("Error writing PDB file"); } // start preparing the stuff to write (copied from VMD's molfile plugin) char indexbuf[32]; char residbuf[32]; char segnamebuf[5]; char altlocchar; /* XXX */ /* if the atom or residue indices exceed the legal PDB spec, we */ /* start emitting asterisks or hexadecimal strings rather than */ /* aborting. This is not really legal, but is an accepted hack */ /* among various other programs that deal with large PDB files */ /* If we run out of hexadecimal indices, then we just print */ /* asterisks. */ if (i < 100000) { sprintf(indexbuf, "%5d", i); } else if (i < 1048576) { sprintf(indexbuf, "%05x", i); } else { sprintf(indexbuf, "*****"); } /*if (resid < 10000) { sprintf(residbuf, "%4d", resid); } else if (resid < 65536) { sprintf(residbuf, "%04x", resid); } else { sprintf(residbuf, "****"); }*/ sprintf(residbuf, "%4d", 1); //altlocchar = altloc[0]; //if (altlocchar == '\0') { altlocchar = ' '; //} /* make sure the segname does not overflow the format */ sprintf(segnamebuf, "SEG "); snprintf(buf, linesize, "%-6s%5s %4s%c%-4s%c%4s%c %8.3f%8.3f%8.3f%6.2f%6.2f %-4s%2s\n", "ATOM ", indexbuf, type_name.c_str(), altlocchar, "RES", ' ', residbuf, ' ', arrays.x[i], arrays.y[i], arrays.z[i], 0.0f, 0.0f, segnamebuf, " "); f << buf; } if (m_output_bond) { // error check: pdb files cannot contain bonds with 100,000 or more atom records if (m_pdata->getN() >= 100000) { cerr << endl << "***Error! PDB files with bonds cannot hold more than 99,999 atoms!" << endl << endl; throw runtime_error("Error dumping PDB file"); } // grab the bond data shared_ptr<BondData> bond_data = m_sysdef->getBondData(); for (unsigned int i = 0; i < bond_data->getNumBonds(); i++) { Bond bond = bond_data->getBond(i); snprintf(buf, linesize, "CONECT%1$5d%2$5d\n", bond.a, bond.b); f << buf; } } // release the particle data m_pdata->release(); } void export_PDBDumpWriter() { class_<PDBDumpWriter, boost::shared_ptr<PDBDumpWriter>, bases<Analyzer>, boost::noncopyable> ("PDBDumpWriter", init< boost::shared_ptr<SystemDefinition>, std::string >()) .def("setOutputBond", &PDBDumpWriter::setOutputBond) .def("writeFile", &PDBDumpWriter::writeFile) ; } #ifdef WIN32 #pragma warning( pop ) #endif <|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. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; using boost::filesystem::create_directory; using namespace libtorrent; using boost::tuples::ignore; // test the maximum transfer rate void test_rate() { session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48575, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49575, 50000)); torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_transfer"); std::ofstream file("./tmp1_transfer/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 4 * 1024 * 1024, 50); file.close(); boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_transfer", 0, &t); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); ptime start = time_now(); for (int i = 0; i < 40; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "up: \033[33m" << st1.upload_payload_rate / 1000000.f << "MB/s " << " down: \033[32m" << st2.download_payload_rate / 1000000.f << "MB/s " << "\033[0m" << int(st2.progress * 100) << "% " << std::endl; if (st1.paused) break; if (tor2.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); time_duration dt = time_now() - start; std::cerr << "downloaded " << t->total_size() << " bytes " "in " << (total_milliseconds(dt) / 1000.f) << " seconds" << std::endl; std::cerr << "average download rate: " << (t->total_size() / total_milliseconds(dt)) << " kB/s" << std::endl; } void test_transfer() { session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000)); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_transfer"); std::ofstream file("./tmp1_transfer/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024); file.close(); // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_transfer", 8 * 1024, &t); // set half of the pieces to priority 0 int num_pieces = tor2.get_torrent_info().num_pieces(); std::vector<int> priorities(num_pieces, 1); std::fill(priorities.begin(), priorities.begin() + num_pieces / 2, 0); tor2.prioritize_pieces(priorities); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); for (int i = 0; i < 30; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << std::endl; if (tor2.is_finished()) break; TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::downloading); test_sleep(1000); } TEST_CHECK(!tor2.is_seed()); std::cerr << "torrent is finished (50% complete)" << std::endl; tor2.pause(); alert const* a = ses2.wait_for_alert(seconds(10)); while (a) { std::auto_ptr<alert> holder = ses2.pop_alert(); std::cerr << "ses2: " << a->message() << std::endl; if (dynamic_cast<torrent_paused_alert const*>(a)) break; a = ses2.wait_for_alert(seconds(10)); } tor2.save_resume_data(); std::vector<char> resume_data; a = ses2.wait_for_alert(seconds(10)); while (a) { std::auto_ptr<alert> holder = ses2.pop_alert(); std::cerr << "ses2: " << a->message() << std::endl; if (dynamic_cast<save_resume_data_alert const*>(a)) { bencode(std::back_inserter(resume_data) , *dynamic_cast<save_resume_data_alert const*>(a)->resume_data); break; } a = ses2.wait_for_alert(seconds(10)); } std::cerr << "saved resume data" << std::endl; ses2.remove_torrent(tor2); std::cerr << "removed" << std::endl; test_sleep(1000); std::cout << "re-adding" << std::endl; add_torrent_params p; p.ti = t; p.save_path = "./tmp2_transfer"; p.resume_data = &resume_data; tor2 = ses2.add_torrent(p); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); tor2.prioritize_pieces(priorities); std::cout << "resetting priorities" << std::endl; tor2.resume(); test_sleep(1000); for (int i = 0; i < 5; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::finished); test_sleep(1000); } TEST_CHECK(!tor2.is_seed()); std::fill(priorities.begin(), priorities.end(), 1); tor2.prioritize_pieces(priorities); std::cout << "setting priorities to 1" << std::endl; for (int i = 0; i < 130; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << std::endl; if (tor2.is_finished()) break; TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::downloading); test_sleep(1000); } TEST_CHECK(tor2.is_seed()); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} #ifdef NDEBUG // test rate only makes sense in release mode test_rate(); try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} #endif test_transfer(); try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} return 0; } <commit_msg>added test that exposes bug where priorities are cleared when a torrent is force-rechecked<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. */ #include "libtorrent/session.hpp" #include "libtorrent/session_settings.hpp" #include "libtorrent/hasher.hpp" #include "libtorrent/alert_types.hpp" #include "libtorrent/bencode.hpp" #include <boost/thread.hpp> #include <boost/tuple/tuple.hpp> #include <boost/filesystem/operations.hpp> #include "test.hpp" #include "setup_transfer.hpp" using boost::filesystem::remove_all; using boost::filesystem::exists; using boost::filesystem::create_directory; using namespace libtorrent; using boost::tuples::ignore; // test the maximum transfer rate void test_rate() { session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48575, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49575, 50000)); torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_transfer"); std::ofstream file("./tmp1_transfer/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 4 * 1024 * 1024, 50); file.close(); boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_transfer", 0, &t); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); ptime start = time_now(); for (int i = 0; i < 40; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "up: \033[33m" << st1.upload_payload_rate / 1000000.f << "MB/s " << " down: \033[32m" << st2.download_payload_rate / 1000000.f << "MB/s " << "\033[0m" << int(st2.progress * 100) << "% " << std::endl; if (st1.paused) break; if (tor2.is_seed()) break; test_sleep(1000); } TEST_CHECK(tor2.is_seed()); time_duration dt = time_now() - start; std::cerr << "downloaded " << t->total_size() << " bytes " "in " << (total_milliseconds(dt) / 1000.f) << " seconds" << std::endl; std::cerr << "average download rate: " << (t->total_size() / total_milliseconds(dt)) << " kB/s" << std::endl; } void test_transfer() { session ses1(fingerprint("LT", 0, 1, 0, 0), std::make_pair(48075, 49000)); session ses2(fingerprint("LT", 0, 1, 0, 0), std::make_pair(49075, 50000)); #ifndef TORRENT_DISABLE_ENCRYPTION pe_settings pes; pes.out_enc_policy = pe_settings::forced; pes.in_enc_policy = pe_settings::forced; ses1.set_pe_settings(pes); ses2.set_pe_settings(pes); #endif torrent_handle tor1; torrent_handle tor2; create_directory("./tmp1_transfer"); std::ofstream file("./tmp1_transfer/temporary"); boost::intrusive_ptr<torrent_info> t = ::create_torrent(&file, 16 * 1024); file.close(); // test using piece sizes smaller than 16kB boost::tie(tor1, tor2, ignore) = setup_transfer(&ses1, &ses2, 0 , true, false, true, "_transfer", 8 * 1024, &t); // set half of the pieces to priority 0 int num_pieces = tor2.get_torrent_info().num_pieces(); std::vector<int> priorities(num_pieces, 1); std::fill(priorities.begin(), priorities.begin() + num_pieces / 2, 0); tor2.prioritize_pieces(priorities); ses1.set_alert_mask(alert::all_categories & ~alert::progress_notification); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); for (int i = 0; i < 30; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << std::endl; if (tor2.is_finished()) break; TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::downloading); test_sleep(1000); } TEST_CHECK(!tor2.is_seed()); std::cerr << "torrent is finished (50% complete)" << std::endl; tor2.force_recheck(); for (int i = 0; i < 10; ++i) { test_sleep(1000); print_alerts(ses2, "ses2"); torrent_status st2 = tor2.status(); std::cerr << "\033[0m" << int(st2.progress * 100) << "% " << std::endl; if (st2.state != torrent_status::checking_files) break; } std::vector<int> priorities2 = tor2.piece_priorities(); TEST_CHECK(std::equal(priorities.begin(), priorities.end(), priorities2.begin())); for (int i = 0; i < 5; ++i) { print_alerts(ses2, "ses2"); torrent_status st2 = tor2.status(); std::cerr << "\033[0m" << int(st2.progress * 100) << "% " << std::endl; TEST_CHECK(st2.state == torrent_status::finished); test_sleep(1000); } tor2.pause(); alert const* a = ses2.wait_for_alert(seconds(10)); while (a) { std::auto_ptr<alert> holder = ses2.pop_alert(); std::cerr << "ses2: " << a->message() << std::endl; if (dynamic_cast<torrent_paused_alert const*>(a)) break; a = ses2.wait_for_alert(seconds(10)); } tor2.save_resume_data(); std::vector<char> resume_data; a = ses2.wait_for_alert(seconds(10)); while (a) { std::auto_ptr<alert> holder = ses2.pop_alert(); std::cerr << "ses2: " << a->message() << std::endl; if (dynamic_cast<save_resume_data_alert const*>(a)) { bencode(std::back_inserter(resume_data) , *dynamic_cast<save_resume_data_alert const*>(a)->resume_data); break; } a = ses2.wait_for_alert(seconds(10)); } std::cerr << "saved resume data" << std::endl; ses2.remove_torrent(tor2); std::cerr << "removed" << std::endl; test_sleep(1000); std::cout << "re-adding" << std::endl; add_torrent_params p; p.ti = t; p.save_path = "./tmp2_transfer"; p.resume_data = &resume_data; tor2 = ses2.add_torrent(p); ses2.set_alert_mask(alert::all_categories & ~alert::progress_notification); tor2.prioritize_pieces(priorities); std::cout << "resetting priorities" << std::endl; tor2.resume(); test_sleep(1000); for (int i = 0; i < 5; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::finished); test_sleep(1000); } TEST_CHECK(!tor2.is_seed()); std::fill(priorities.begin(), priorities.end(), 1); tor2.prioritize_pieces(priorities); std::cout << "setting priorities to 1" << std::endl; for (int i = 0; i < 130; ++i) { print_alerts(ses1, "ses1"); print_alerts(ses2, "ses2"); torrent_status st1 = tor1.status(); torrent_status st2 = tor2.status(); std::cerr << "\033[32m" << int(st1.download_payload_rate / 1000.f) << "kB/s " << "\033[33m" << int(st1.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st1.progress * 100) << "% " << st1.num_peers << ": " << "\033[32m" << int(st2.download_payload_rate / 1000.f) << "kB/s " << "\033[31m" << int(st2.upload_payload_rate / 1000.f) << "kB/s " << "\033[0m" << int(st2.progress * 100) << "% " << st2.num_peers << std::endl; if (tor2.is_finished()) break; TEST_CHECK(st1.state == torrent_status::seeding); TEST_CHECK(st2.state == torrent_status::downloading); test_sleep(1000); } TEST_CHECK(tor2.is_seed()); } int test_main() { using namespace libtorrent; using namespace boost::filesystem; // in case the previous run was terminated try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} #ifdef NDEBUG // test rate only makes sense in release mode test_rate(); try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} #endif test_transfer(); try { remove_all("./tmp1_transfer"); } catch (std::exception&) {} try { remove_all("./tmp2_transfer"); } catch (std::exception&) {} return 0; } <|endoftext|>
<commit_before>//////////////////////////////////////////////////////////////////////////////// // Prime Generator // Use Sieve Eratosthenes - can find all the primes within range (1, 2^31 - 1) // Reference: http://zobayer.blogspot.in/2009/09/segmented-sieve.html //////////////////////////////////////////////////////////////////////////////// #include <string.h> #include <iostream> #include <cassert> using namespace std; template <int MAX_RANGE> class PrimeGenerator { #define SQ(x) ((x)*(x)) #define MSET(x,v) memset(x,v,sizeof(x)) #define CHKC(x,n) (x[n>>6]&(1<<((n>>1)&31))) #define SETC(x,n) (x[n>>6]|=(1<<((n>>1)&31))) static const int MAX = 46656; // around sqrt(2^31 - 1) static const int LMT = 216; // sqrt(MAX) static const int LEN = 4830; // number of necessary primes (primes under MAX) unsigned base[MAX/64], segment[MAX_RANGE/64], primes[LEN]; public: PrimeGenerator() { internal_sieve(); } // Returns the number of primes within range [a, b] and marks them in segment[] // Stores all the primes in the user array (it not NULL) int segmented_sieve(int a, int b, int *user) { unsigned i, j, k, cnt = (a <= 2 && 2 <= b)? 1 : 0; if (a <= 2 && 2 <= b) { if (user) user[cnt - 1] = 2; } if (b < 2) return 0; if (a < 3) a = 3; if (a % 2 == 0) a++; MSET(segment, 0); for (i = 0; SQ(primes[i]) <= b; i++) { j = primes[i] * ((a + primes[i] - 1) / primes[i]); if (j % 2 == 0) j += primes[i]; for (k = primes[i]<<1; j <= b; j += k) if (j != primes[i]) SETC(segment, (j - a)); } if (b - a >= 0) { for(i = 0; i <= b - a; i += 2) { if(!CHKC(segment, i)) { if (user) user[cnt] = i + a; cnt++; } } } return cnt; } private: // Generates all the necessary prime numbers and marks them in base[] void internal_sieve() { unsigned i, j, k; for (i = 3; i < LMT; i += 2) if (!CHKC(base, i)) for (j = i * i, k = i<<1; j < MAX; j += k) SETC(base, j); for (i = 3, j = 0; i < MAX; i += 2) if (!CHKC(base, i)) primes[j++] = i; } }; int primes[1000005]; int main() { PrimeGenerator<10000000> pg; // range 10,000,000 for testing - might wanna change it int num_p = pg.segmented_sieve(1, 100, primes); for (int i = 0; i < num_p; i++) { cout << primes[i] << endl; } cout << "count: " << num_p << endl; assert(pg.segmented_sieve(2, 2, NULL) == 1); assert(pg.segmented_sieve(2, 3, NULL) == 2); assert(pg.segmented_sieve(5, 10, NULL) == 2); assert(pg.segmented_sieve(1, 10, NULL) == 4); assert(pg.segmented_sieve(1, 50, NULL) == 15); assert(pg.segmented_sieve(1, 100, NULL) == 25); assert(pg.segmented_sieve(1, 1000000, NULL) == 78498); assert(pg.segmented_sieve(1, 10000000, NULL) == 664579); assert(pg.segmented_sieve(2000000000, 2000000000, NULL) == 0); assert(pg.segmented_sieve(2000000001, 2000000001, NULL) == 0); assert(pg.segmented_sieve(2000000000, 2010000000, NULL) == 467612); return 0; } <commit_msg>Deleted prime generator.<commit_after><|endoftext|>
<commit_before>#include "GMSAssetResourceManagementSystem.hpp" #include "../AssetResources/TextureInfoResource.hpp" #include "../AssetResources/GMSRoomResource.hpp" #include "../AssetResources/GMSObjectResource.hpp" #include "../CommandLineOptions.hpp" #include <KEngine/Events/OtherGraphicsEvents.hpp> #include <KEngine/App.hpp> #include <KEngine/Utility/FileSystemHelper.hpp> #include <KEngine/Log/Log.hpp> #include <SFML/Graphics/Image.hpp> #include <algorithm> #include <execution> #include <filesystem> #include <fstream> #include <limits> #include <utility> namespace fs = std::filesystem; namespace { ke::Colour gmsColourStrToColour(const ke::String & p_colourStr) { assert(p_colourStr.length() == 9); assert(p_colourStr[0] == '#'); ke::Colour roomColour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(p_colourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(7, 2), nullptr, 16)) }; return roomColour; } } namespace pf { bool GMSAssetResourceManagementSystem::initialise() { ke::Log::instance()->info("Scanning assets..."); this->loadTextureAssets(); this->loadRoomAssets(); this->loadObjectAssets(); ke::Log::instance()->info("Scanning assets... DONE"); return true; } void GMSAssetResourceManagementSystem::shutdown() { } void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime) { KE_UNUSED(elapsedTime); } void GMSAssetResourceManagementSystem::loadTextureAssets(void) { ke::Log::instance()->info("Scanning texture assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto texturesRootDirPath = fs::path{ assetDirPath } / "textures"; sf::Image tempImage; std::hash<ke::String> hasher; for (const auto & texDirPath : ke::FileSystemHelper::getChildPaths(texturesRootDirPath)) { ke::Log::instance()->info("Discovered texture asset: {}", texDirPath.string()); auto textureFilePaths = ke::FileSystemHelper::getFilePaths(texDirPath); if (textureFilePaths.size() == 1) { auto texPath = textureFilePaths[0]; auto textureResource = std::make_shared<TextureInfoResource>(); textureResource->setName(texPath.stem().string()); textureResource->setTextureId(hasher(textureResource->getName())); textureResource->setSourcePath(texPath.string()); // retrieve size bool ret = tempImage.loadFromFile(texPath.string()); assert(ret); TextureInfoResource::DimensionType dimension; dimension.width = tempImage.getSize().x; dimension.height = tempImage.getSize().y; textureResource->setTextureSize(dimension); ke::App::instance()->getResourceManager()->registerResource(textureResource); } else { // ignore when there're multiple texture files in a single dir for now. } } } void GMSAssetResourceManagementSystem::loadRoomAssets(void) { ke::Log::instance()->info("Scanning GM:S room assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto gmsRoomsRootDirPath = fs::path{ assetDirPath } / "rooms"; const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath); std::hash<ke::String> hasher; std::for_each(std::execution::par_unseq, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath) { ke::Log::instance()->info("Discovered GM:S room asset: {}", gmsRoomPath.string()); auto roomResource = std::make_shared<GMSRoomResource>(); roomResource->setName(gmsRoomPath.stem().string()); roomResource->setSourcePath(gmsRoomPath.string()); std::ifstream roomFileStream{ gmsRoomPath }; ke::json roomJson; roomFileStream >> roomJson; // // Load general room info. // GMSRoomResource::SizeType roomSize; roomSize.width = roomJson["size"]["width"].get<unsigned>(); roomSize.height = roomJson["size"]["height"].get<unsigned>(); roomResource->setSize(roomSize); roomResource->setSpeed(roomJson["speed"].get<int>()); auto roomColourStr = roomJson["colour"].get<ke::String>(); roomResource->setColour(::gmsColourStrToColour(roomColourStr)); // // load background info // const auto & roomBackgroundsJson = roomJson["bgs"]; for (const auto & backgroundJson : roomBackgroundsJson) { GMSRoomBackgroundInfo backgroundInfo; backgroundInfo.enabled = backgroundJson["enabled"].get<bool>(); backgroundInfo.foreground = backgroundJson["foreground"].get<bool>(); backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() }; backgroundInfo.tilex = backgroundJson["tilex"].get<bool>(); backgroundInfo.tiley = backgroundJson["tiley"].get<bool>(); backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() }; backgroundInfo.stretch = backgroundJson["stretch"].get<bool>(); backgroundInfo.bg = backgroundJson.value("bg", ""); backgroundInfo.bg_hash = hasher(backgroundInfo.bg); roomResource->addBackgroundInfo(backgroundInfo); } // // load tile instances // const auto & roomTilesJson = roomJson["tiles"]; roomResource->tiles.reserve(roomTilesJson.size()); for (const auto & tileJson : roomTilesJson) { pf::GMSRoomTileInstance newTile; newTile.instanceid = tileJson["instanceid"].get<unsigned>(); // Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates. // I.e. y-down to y-up. // Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left. newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() }; newTile.bg = tileJson["bg"].get<ke::String>(); newTile.bg_hash = hasher(newTile.bg); newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates. newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() }; newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() }; newTile.colour = ::gmsColourStrToColour(tileJson["colour"].get<ke::String>()); // Here convert GM:S' depth system to KEngine's depth system. // GM:S depth value: larger == further back. // KEngine depth value: larger == further in front. newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>(); roomResource->addTile(newTile); } // // load object instances // const auto & roomObjsJson = roomJson["objs"]; roomResource->objects.reserve(roomObjsJson.size()); for (const auto & objJson : roomObjsJson) { pf::GMSRoomObjectInstance obj; obj.instanceid = objJson["instanceid"].get<ke::EntityId>(); obj.obj = objJson["obj"].get<ke::String>(); obj.pos = { objJson["pos"]["x"].get<int>(), -objJson["pos"]["y"].get<int>() }; obj.scale = { objJson["scale"]["x"].get<float>(), objJson["scale"]["y"].get<float>() }; obj.rotation = objJson["rotation"].get<float>(); obj.colour = ::gmsColourStrToColour(objJson["colour"].get<ke::String>()); roomResource->addObject(obj); } ke::App::instance()->getResourceManager()->registerResource(roomResource); }); } void GMSAssetResourceManagementSystem::loadObjectAssets(void) { ke::Log::instance()->info("Scanning GM:S object assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto gmsObjectRootDirPath = fs::path{ assetDirPath } / "object"; const auto gmsObjectPaths = ke::FileSystemHelper::getFilePaths(gmsObjectRootDirPath); std::for_each(std::execution::par_unseq, std::begin(gmsObjectPaths), std::end(gmsObjectPaths), [&](const auto & gmsObjectPath) { ke::Log::instance()->info("Discovered GM:S object asset: {}", gmsObjectPath.string()); std::ifstream objectFileStream{ gmsObjectPath }; ke::json objectJson; objectFileStream >> objectJson; auto objectResource = std::make_shared<pf::GMSObjectResource>(fs::path(gmsObjectPath).stem().string(), gmsObjectPath.string()); objectResource->sprite = objectJson["sprite"].get<ke::String>(); objectResource->visible = objectJson["visible"].get<bool>(); objectResource->solid = objectJson["solid"].get<bool>(); objectResource->depth = objectJson["depth"].get<decltype(objectResource->depth)>(); objectResource->persist = objectJson["persist"].get<bool>(); objectResource->sensor = objectJson["sensor"].get<bool>(); objectResource->colshape = objectJson["colshape"].get<ke::String>(); ke::App::instance()->getResourceManager()->registerResource(objectResource); }); } }<commit_msg>handle allowing non-directory path when loading textures.<commit_after>#include "GMSAssetResourceManagementSystem.hpp" #include "../AssetResources/TextureInfoResource.hpp" #include "../AssetResources/GMSRoomResource.hpp" #include "../AssetResources/GMSObjectResource.hpp" #include "../CommandLineOptions.hpp" #include <KEngine/Events/OtherGraphicsEvents.hpp> #include <KEngine/App.hpp> #include <KEngine/Utility/FileSystemHelper.hpp> #include <KEngine/Log/Log.hpp> #include <SFML/Graphics/Image.hpp> #include <algorithm> #include <execution> #include <filesystem> #include <fstream> #include <limits> #include <utility> namespace fs = std::filesystem; namespace { ke::Colour gmsColourStrToColour(const ke::String & p_colourStr) { assert(p_colourStr.length() == 9); assert(p_colourStr[0] == '#'); ke::Colour roomColour = { // assume colour is in hex RGBA starting with the '#' symbol. static_cast<uint8_t>(std::stol(p_colourStr.substr(1, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(3, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(5, 2), nullptr, 16)), static_cast<uint8_t>(std::stol(p_colourStr.substr(7, 2), nullptr, 16)) }; return roomColour; } } namespace pf { bool GMSAssetResourceManagementSystem::initialise() { ke::Log::instance()->info("Scanning assets..."); this->loadTextureAssets(); this->loadRoomAssets(); this->loadObjectAssets(); ke::Log::instance()->info("Scanning assets... DONE"); return true; } void GMSAssetResourceManagementSystem::shutdown() { } void GMSAssetResourceManagementSystem::update(ke::Time elapsedTime) { KE_UNUSED(elapsedTime); } void GMSAssetResourceManagementSystem::loadTextureAssets(void) { ke::Log::instance()->info("Scanning texture assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto texturesRootDirPath = fs::path{ assetDirPath } / "textures"; sf::Image tempImage; std::hash<ke::String> hasher; for (const auto & texDirPath : ke::FileSystemHelper::getChildPaths(texturesRootDirPath)) { if (fs::is_directory(texDirPath)) { ke::Log::instance()->info("Discovered texture asset: {}", texDirPath.string()); auto textureFilePaths = ke::FileSystemHelper::getFilePaths(texDirPath); if (textureFilePaths.size() == 1) { auto texPath = textureFilePaths[0]; auto textureResource = std::make_shared<TextureInfoResource>(); textureResource->setName(texPath.stem().string()); textureResource->setTextureId(hasher(textureResource->getName())); textureResource->setSourcePath(texPath.string()); // retrieve size bool ret = tempImage.loadFromFile(texPath.string()); assert(ret); TextureInfoResource::DimensionType dimension; dimension.width = tempImage.getSize().x; dimension.height = tempImage.getSize().y; textureResource->setTextureSize(dimension); ke::App::instance()->getResourceManager()->registerResource(textureResource); } else { // ignore when there're multiple texture files in a single dir for now. } } } } void GMSAssetResourceManagementSystem::loadRoomAssets(void) { ke::Log::instance()->info("Scanning GM:S room assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto gmsRoomsRootDirPath = fs::path{ assetDirPath } / "rooms"; const auto gmsRoomPaths = ke::FileSystemHelper::getFilePaths(gmsRoomsRootDirPath); std::hash<ke::String> hasher; std::for_each(std::execution::par_unseq, std::begin(gmsRoomPaths), std::end(gmsRoomPaths), [&](const auto & gmsRoomPath) { ke::Log::instance()->info("Discovered GM:S room asset: {}", gmsRoomPath.string()); auto roomResource = std::make_shared<GMSRoomResource>(); roomResource->setName(gmsRoomPath.stem().string()); roomResource->setSourcePath(gmsRoomPath.string()); std::ifstream roomFileStream{ gmsRoomPath }; ke::json roomJson; roomFileStream >> roomJson; // // Load general room info. // GMSRoomResource::SizeType roomSize; roomSize.width = roomJson["size"]["width"].get<unsigned>(); roomSize.height = roomJson["size"]["height"].get<unsigned>(); roomResource->setSize(roomSize); roomResource->setSpeed(roomJson["speed"].get<int>()); auto roomColourStr = roomJson["colour"].get<ke::String>(); roomResource->setColour(::gmsColourStrToColour(roomColourStr)); // // load background info // const auto & roomBackgroundsJson = roomJson["bgs"]; for (const auto & backgroundJson : roomBackgroundsJson) { GMSRoomBackgroundInfo backgroundInfo; backgroundInfo.enabled = backgroundJson["enabled"].get<bool>(); backgroundInfo.foreground = backgroundJson["foreground"].get<bool>(); backgroundInfo.pos = { backgroundJson["pos"]["x"].get<int>(), -backgroundJson["pos"]["y"].get<int>() }; backgroundInfo.tilex = backgroundJson["tilex"].get<bool>(); backgroundInfo.tiley = backgroundJson["tiley"].get<bool>(); backgroundInfo.speed = { backgroundJson["speed"]["x"].get<int>(), -backgroundJson["speed"]["y"].get<int>() }; backgroundInfo.stretch = backgroundJson["stretch"].get<bool>(); backgroundInfo.bg = backgroundJson.value("bg", ""); backgroundInfo.bg_hash = hasher(backgroundInfo.bg); roomResource->addBackgroundInfo(backgroundInfo); } // // load tile instances // const auto & roomTilesJson = roomJson["tiles"]; roomResource->tiles.reserve(roomTilesJson.size()); for (const auto & tileJson : roomTilesJson) { pf::GMSRoomTileInstance newTile; newTile.instanceid = tileJson["instanceid"].get<unsigned>(); // Here we make sure to convert the GM:S room coordinates to KEngine's world coordinates. // I.e. y-down to y-up. // Texture coordinates are the same at the moment at y-down. I.e. (0,0) at top left. newTile.pos = { tileJson["pos"]["x"].get<int>(), -tileJson["pos"]["y"].get<int>() }; newTile.bg = tileJson["bg"].get<ke::String>(); newTile.bg_hash = hasher(newTile.bg); newTile.sourcepos = { tileJson["sourcepos"]["x"].get<int>(), tileJson["sourcepos"]["y"].get<int>() }; // sourcepos is y-down local image coordinates. newTile.size = { tileJson["size"]["width"].get<int>(), tileJson["size"]["height"].get<int>() }; newTile.scale = { tileJson["scale"]["x"].get<float>(), tileJson["scale"]["y"].get<float>() }; newTile.colour = ::gmsColourStrToColour(tileJson["colour"].get<ke::String>()); // Here convert GM:S' depth system to KEngine's depth system. // GM:S depth value: larger == further back. // KEngine depth value: larger == further in front. newTile.tiledepth = -tileJson["tiledepth"].get<ke::graphics::DepthType>(); roomResource->addTile(newTile); } // // load object instances // const auto & roomObjsJson = roomJson["objs"]; roomResource->objects.reserve(roomObjsJson.size()); for (const auto & objJson : roomObjsJson) { pf::GMSRoomObjectInstance obj; obj.instanceid = objJson["instanceid"].get<ke::EntityId>(); obj.obj = objJson["obj"].get<ke::String>(); obj.pos = { objJson["pos"]["x"].get<int>(), -objJson["pos"]["y"].get<int>() }; obj.scale = { objJson["scale"]["x"].get<float>(), objJson["scale"]["y"].get<float>() }; obj.rotation = objJson["rotation"].get<float>(); obj.colour = ::gmsColourStrToColour(objJson["colour"].get<ke::String>()); roomResource->addObject(obj); } ke::App::instance()->getResourceManager()->registerResource(roomResource); }); } void GMSAssetResourceManagementSystem::loadObjectAssets(void) { ke::Log::instance()->info("Scanning GM:S object assets..."); const auto assetDirPath = ke::App::getCommandLineArgValue(pf::cli::ExecAssetsPath).as<ke::String>(); const auto gmsObjectRootDirPath = fs::path{ assetDirPath } / "object"; const auto gmsObjectPaths = ke::FileSystemHelper::getFilePaths(gmsObjectRootDirPath); std::for_each(std::execution::par_unseq, std::begin(gmsObjectPaths), std::end(gmsObjectPaths), [&](const auto & gmsObjectPath) { ke::Log::instance()->info("Discovered GM:S object asset: {}", gmsObjectPath.string()); std::ifstream objectFileStream{ gmsObjectPath }; ke::json objectJson; objectFileStream >> objectJson; auto objectResource = std::make_shared<pf::GMSObjectResource>(fs::path(gmsObjectPath).stem().string(), gmsObjectPath.string()); objectResource->sprite = objectJson["sprite"].get<ke::String>(); objectResource->visible = objectJson["visible"].get<bool>(); objectResource->solid = objectJson["solid"].get<bool>(); objectResource->depth = objectJson["depth"].get<decltype(objectResource->depth)>(); objectResource->persist = objectJson["persist"].get<bool>(); objectResource->sensor = objectJson["sensor"].get<bool>(); objectResource->colshape = objectJson["colshape"].get<ke::String>(); ke::App::instance()->getResourceManager()->registerResource(objectResource); }); } }<|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: drawbase.hxx,v $ * * $Revision: 1.4 $ * * last change: $Author: os $ $Date: 2002-10-25 13:09:46 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SW_DRAWBASE_HXX #define _SW_DRAWBASE_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif class SwView; class SwWrtShell; class SwEditWin; class KeyEvent; class MouseEvent; #define MIN_FREEHAND_DISTANCE 10 /************************************************************************* |* |* Basisklasse fuer alle Funktionen |* \************************************************************************/ class SwDrawBase { protected: SwView* pView; SwWrtShell* pSh; SwEditWin* pWin; Point aStartPos; // Position von BeginCreate Point aMDPos; // Position von MouseButtonDown USHORT nSlotId; BOOL bCreateObj :1; BOOL bInsForm :1; Point GetDefaultCenterPos(); public: SwDrawBase(SwWrtShell *pSh, SwEditWin* pWin, SwView* pView); virtual ~SwDrawBase(); void SetDrawPointer(); void EnterSelectMode(const MouseEvent& rMEvt); inline BOOL IsInsertForm() const { return bInsForm; } inline BOOL IsCreateObj() const { return bCreateObj; } // Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); void BreakCreate(); void SetSlotId(USHORT nSlot) {nSlotId = nSlot;} virtual void Activate(const USHORT nSlotId); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void CreateDefaultObject(); }; #endif // _SW_DRAWBASE_HXX <commit_msg>INTEGRATION: CWS aw020 (1.4.914); FILE MERGED 2004/10/26 13:13:02 aw 1.4.914.1: #i33136#<commit_after>/************************************************************************* * * $RCSfile: drawbase.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-11-17 09:38:58 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, 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 * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SW_DRAWBASE_HXX #define _SW_DRAWBASE_HXX #ifndef _GEN_HXX //autogen #include <tools/gen.hxx> #endif class SwView; class SwWrtShell; class SwEditWin; class KeyEvent; class MouseEvent; #define MIN_FREEHAND_DISTANCE 10 /************************************************************************* |* |* Basisklasse fuer alle Funktionen |* \************************************************************************/ class SwDrawBase { protected: SwView* pView; SwWrtShell* pSh; SwEditWin* pWin; Point aStartPos; // Position von BeginCreate Point aMDPos; // Position von MouseButtonDown USHORT nSlotId; BOOL bCreateObj :1; BOOL bInsForm :1; Point GetDefaultCenterPos(); public: SwDrawBase(SwWrtShell *pSh, SwEditWin* pWin, SwView* pView); virtual ~SwDrawBase(); void SetDrawPointer(); void EnterSelectMode(const MouseEvent& rMEvt); inline BOOL IsInsertForm() const { return bInsForm; } inline BOOL IsCreateObj() const { return bCreateObj; } // Mouse- & Key-Events; Returnwert=TRUE: Event wurde bearbeitet virtual BOOL KeyInput(const KeyEvent& rKEvt); virtual BOOL MouseMove(const MouseEvent& rMEvt); virtual BOOL MouseButtonUp(const MouseEvent& rMEvt); virtual BOOL MouseButtonDown(const MouseEvent& rMEvt); void BreakCreate(); void SetSlotId(USHORT nSlot) {nSlotId = nSlot;} virtual void Activate(const USHORT nSlotId); // Function aktivieren virtual void Deactivate(); // Function deaktivieren virtual void CreateDefaultObject(); // #i33136# virtual bool doConstructOrthogonal() const; }; #endif // _SW_DRAWBASE_HXX <|endoftext|>
<commit_before>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012-2013 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/labels/BinaryLabels.h> #include <gtest/gtest.h> using namespace shogun; TEST(BinaryLabels,scores_to_probabilities) { CBinaryLabels* labels=new CBinaryLabels(10); labels->set_values(SGVector<float64_t>(labels->get_num_labels())); for (index_t i=0; i<labels->get_num_labels(); ++i) labels->set_value(i%2==0 ? 1 : -1, i); labels->get_values().display_vector("scores"); // call with 0,0 to make the method compute sigmoid parameters itself // g-test somehow does not allow std parameters labels->scores_to_probabilities(0,0); /* only two probabilities will be the result. Results from implementation that * comes with the original paper, see BinaryLabels documentation */ EXPECT_NEAR(labels->get_value(0), 0.8571428439385661, 10E-15); EXPECT_NEAR(labels->get_value(1), 0.14285715606143384, 10E-15); SG_UNREF(labels); } <commit_msg>removed print<commit_after>/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * Written (W) 2012-2013 Heiko Strathmann */ #include <shogun/base/init.h> #include <shogun/labels/BinaryLabels.h> #include <gtest/gtest.h> using namespace shogun; TEST(BinaryLabels,scores_to_probabilities) { CBinaryLabels* labels=new CBinaryLabels(10); labels->set_values(SGVector<float64_t>(labels->get_num_labels())); for (index_t i=0; i<labels->get_num_labels(); ++i) labels->set_value(i%2==0 ? 1 : -1, i); //labels->get_values().display_vector("scores"); // call with 0,0 to make the method compute sigmoid parameters itself // g-test somehow does not allow std parameters labels->scores_to_probabilities(0,0); /* only two probabilities will be the result. Results from implementation that * comes with the original paper, see BinaryLabels documentation */ EXPECT_NEAR(labels->get_value(0), 0.8571428439385661, 10E-15); EXPECT_NEAR(labels->get_value(1), 0.14285715606143384, 10E-15); SG_UNREF(labels); } <|endoftext|>
<commit_before>// @(#)root/tree:$Id$ // Author: Rene Brun 17/03/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a variable length string. // ////////////////////////////////////////////////////////////////////////// #include "TLeafC.h" #include "TBranch.h" #include "TBasket.h" #include "TClonesArray.h" #include "Riostream.h" #include <string> ClassImp(TLeafC) //______________________________________________________________________________ TLeafC::TLeafC(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::TLeafC(TBranch *parent, const char *name, const char *type) :TLeaf(parent, name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::~TLeafC() { //*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafC::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ==================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================== if (fPointer) fValue = *fPointer; Int_t len = strlen(fValue); if (len >= fMaximum) fMaximum = len+1; if (len >= fLen) fLen = len+1; b.WriteFastArrayString(fValue,len); } //______________________________________________________________________________ const char *TLeafC::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "UChar_t"; return "Char_t"; } //______________________________________________________________________________ void TLeafC::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::PrintValue(Int_t) const { // Prints leaf value. char *value = (char*)GetValuePointer(); printf("%s",value); } //______________________________________________________________________________ void TLeafC::ReadBasket(TBuffer &b) { // Read leaf elements from Basket input buffer. // Try to deal with the file written during the time where len was not // written to disk when len was == 0. Int_t readbasket = GetBranch()->GetReadBasket(); TBasket *basket = GetBranch()->GetBasket(readbasket); Int_t* entryOffset = basket->GetEntryOffset(); if (entryOffset) { Long64_t first = GetBranch()->GetBasketEntry()[readbasket]; Long64_t entry = GetBranch()->GetReadEntry(); if ( ( ( (readbasket == GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetEntries()) /* Very last entry */ || (readbasket < GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetBasketEntry()[readbasket+1] ) /* Last entry of the basket */ ) && ( entryOffset[entry-first] == basket->GetLast() ) /* The 'read' point is at the end of the basket */ ) || ( entryOffset[entry-first] == entryOffset[entry-first+1] ) /* This string did not use up any space in the buffer */ ) { // Empty string fValue[0] = '\0'; return; } } b.ReadFastArrayString(fValue,fLen); } //______________________________________________________________________________ void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { // Read leaf elements from Basket input buffer // and export buffer to TClonesArray objects. UChar_t len; b >> len; if (len) { if (len >= fLen) len = fLen-1; b.ReadFastArray(fValue,len); fValue[len] = 0; } else { fValue[0] = 0; } Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::ReadValue(istream &s) { // Read a string from istream s and store it into the branch buffer. string temp; s >> temp; if ( TestBit(kNewValue) && (temp.size()+1 > ((UInt_t)fNdata))) { // Grow buffer if needed and we created the buffer. fNdata = temp.size() + 1; if (TestBit(kIndirectAddress) && fPointer) { delete [] *fPointer; *fPointer = new char[fNdata]; } else { fValue = new char[fNdata]; } } strlcpy(fValue,temp.c_str(),fNdata); } //______________________________________________________________________________ void TLeafC::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (char**)add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) || ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new char[fNdata]; } fValue = *fPointer; } else { fValue = (char*)add; } } else { fValue = new char[fNdata]; fValue[0] = 0; } } <commit_msg>Avoid uninitialized memory read (past the array end) in TLeafC::ReadBasket<commit_after>// @(#)root/tree:$Id$ // Author: Rene Brun 17/03/97 /************************************************************************* * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. * * All rights reserved. * * * * For the licensing terms see $ROOTSYS/LICENSE. * * For the list of contributors see $ROOTSYS/README/CREDITS. * *************************************************************************/ ////////////////////////////////////////////////////////////////////////// // // // A TLeaf for a variable length string. // ////////////////////////////////////////////////////////////////////////// #include "TLeafC.h" #include "TBranch.h" #include "TBasket.h" #include "TClonesArray.h" #include "Riostream.h" #include <string> ClassImp(TLeafC) //______________________________________________________________________________ TLeafC::TLeafC(): TLeaf() { //*-*-*-*-*-*Default constructor for LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============================ fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::TLeafC(TBranch *parent, const char *name, const char *type) :TLeaf(parent, name,type) { //*-*-*-*-*-*-*-*-*-*-*-*-*Create a LeafC*-*-*-*-*-*-*-*-*-*-*-*-*-*-* //*-* ============== //*-* fLenType = 1; fMinimum = 0; fMaximum = 0; fValue = 0; fPointer = 0; } //______________________________________________________________________________ TLeafC::~TLeafC() { //*-*-*-*-*-*Default destructor for a LeafC*-*-*-*-*-*-*-*-*-*-*-* //*-* =============================== if (ResetAddress(0,kTRUE)) delete [] fValue; } //______________________________________________________________________________ void TLeafC::Export(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Export element from local leaf buffer to ClonesArray*-*-*-*-* //*-* ==================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::FillBasket(TBuffer &b) { //*-*-*-*-*-*-*-*-*-*-*Pack leaf elements in Basket output buffer*-*-*-*-*-*-* //*-* ========================================== if (fPointer) fValue = *fPointer; Int_t len = strlen(fValue); if (len >= fMaximum) fMaximum = len+1; if (len >= fLen) fLen = len+1; b.WriteFastArrayString(fValue,len); } //______________________________________________________________________________ const char *TLeafC::GetTypeName() const { //*-*-*-*-*-*-*-*Returns name of leaf type*-*-*-*-*-*-*-*-*-*-*-* //*-* ========================= if (fIsUnsigned) return "UChar_t"; return "Char_t"; } //______________________________________________________________________________ void TLeafC::Import(TClonesArray *list, Int_t n) { //*-*-*-*-*-*Import element from ClonesArray into local leaf buffer*-*-*-*-* //*-* ====================================================== Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy(&fValue[j],(char*)list->UncheckedAt(i) + fOffset, 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::PrintValue(Int_t) const { // Prints leaf value. char *value = (char*)GetValuePointer(); printf("%s",value); } //______________________________________________________________________________ void TLeafC::ReadBasket(TBuffer &b) { // Read leaf elements from Basket input buffer. // Try to deal with the file written during the time where len was not // written to disk when len was == 0. Int_t readbasket = GetBranch()->GetReadBasket(); TBasket *basket = GetBranch()->GetBasket(readbasket); Int_t* entryOffset = basket->GetEntryOffset(); if (entryOffset) { Long64_t first = GetBranch()->GetBasketEntry()[readbasket]; Long64_t entry = GetBranch()->GetReadEntry(); if ( (readbasket == GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetEntries()) /* Very last entry */ || (readbasket < GetBranch()->GetWriteBasket() && (entry+1) == GetBranch()->GetBasketEntry()[readbasket+1] ) /* Last entry of the basket */ ) { if ( entryOffset[entry-first] == basket->GetLast() ) /* The 'read' point is at the end of the basket */ { // Empty string fValue[0] = '\0'; return; } } else if ( entryOffset[entry-first] == entryOffset[entry-first+1] ) /* This string did not use up any space in the buffer */ { // Empty string fValue[0] = '\0'; return; } } b.ReadFastArrayString(fValue,fLen); } //______________________________________________________________________________ void TLeafC::ReadBasketExport(TBuffer &b, TClonesArray *list, Int_t n) { // Read leaf elements from Basket input buffer // and export buffer to TClonesArray objects. UChar_t len; b >> len; if (len) { if (len >= fLen) len = fLen-1; b.ReadFastArray(fValue,len); fValue[len] = 0; } else { fValue[0] = 0; } Int_t j = 0; for (Int_t i=0;i<n;i++) { memcpy((char*)list->UncheckedAt(i) + fOffset,&fValue[j], 1); j += fLen; } } //______________________________________________________________________________ void TLeafC::ReadValue(istream &s) { // Read a string from istream s and store it into the branch buffer. string temp; s >> temp; if ( TestBit(kNewValue) && (temp.size()+1 > ((UInt_t)fNdata))) { // Grow buffer if needed and we created the buffer. fNdata = temp.size() + 1; if (TestBit(kIndirectAddress) && fPointer) { delete [] *fPointer; *fPointer = new char[fNdata]; } else { fValue = new char[fNdata]; } } strlcpy(fValue,temp.c_str(),fNdata); } //______________________________________________________________________________ void TLeafC::SetAddress(void *add) { //*-*-*-*-*-*-*-*-*-*-*Set leaf buffer data address*-*-*-*-*-* //*-* ============================ if (ResetAddress(add)) { delete [] fValue; } if (add) { if (TestBit(kIndirectAddress)) { fPointer = (char**)add; Int_t ncountmax = fLen; if (fLeafCount) ncountmax = fLen*(fLeafCount->GetMaximum() + 1); if ((fLeafCount && ncountmax > Int_t(fLeafCount->GetValue())) || ncountmax > fNdata || *fPointer == 0) { if (*fPointer) delete [] *fPointer; if (ncountmax > fNdata) fNdata = ncountmax; *fPointer = new char[fNdata]; } fValue = *fPointer; } else { fValue = (char*)add; } } else { fValue = new char[fNdata]; fValue[0] = 0; } } <|endoftext|>
<commit_before><commit_msg>fix duplicate after merge<commit_after><|endoftext|>
<commit_before><commit_msg>Simplify calulations of paddingBox and borderBox in InspectorOverlay.cpp<commit_after><|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include "Binding_GridTopology.h" #include "Binding_MeshTopology.h" using namespace sofa::component::topology; using namespace sofa::core::objectmodel; extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nx,ny,nz; if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz)) { PyErr_BadArgument(); return NULL; } obj->setSize(nx,ny,nz); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNx()); } extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNx(nb); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNy()); } extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNy(nb); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNz()); } extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNz(nb); Py_RETURN_NONE; } SP_CLASS_METHODS_BEGIN(GridTopology) SP_CLASS_METHOD(GridTopology,setSize) SP_CLASS_METHOD(GridTopology,getNx) SP_CLASS_METHOD(GridTopology,getNy) SP_CLASS_METHOD(GridTopology,getNz) SP_CLASS_METHOD(GridTopology,setNx) SP_CLASS_METHOD(GridTopology,setNy) SP_CLASS_METHOD(GridTopology,setNz) SP_CLASS_METHODS_END SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology) <commit_msg>[SofaPython] proper error handling<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, development version * * (c) 2006-2017 INRIA, USTL, UJF, CNRS, MGH * * * * This program 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 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 Lesser General Public License * * for more details. * * * * You should have received a copy of the GNU Lesser General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************* * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include "Binding_GridTopology.h" #include "Binding_MeshTopology.h" using namespace sofa::component::topology; using namespace sofa::core::objectmodel; extern "C" PyObject * GridTopology_setSize(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nx,ny,nz; if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz)) { PyErr_BadArgument(); return NULL; } obj->setSize(nx,ny,nz); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_setNumVertices(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nx,ny,nz; if (!PyArg_ParseTuple(args, "iii",&nx,&ny,&nz)) { PyErr_BadArgument(); return NULL; } obj->setNumVertices(nx,ny,nz); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNx(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNx()); } extern "C" PyObject * GridTopology_setNx(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNx(nb); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNy(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNy()); } extern "C" PyObject * GridTopology_setNy(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNy(nb); Py_RETURN_NONE; } extern "C" PyObject * GridTopology_getNz(PyObject *self, PyObject * /*args*/) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); return PyInt_FromLong(obj->getNz()); } extern "C" PyObject * GridTopology_setNz(PyObject *self, PyObject * args) { GridTopology* obj=down_cast<GridTopology>(((PySPtr<Base>*)self)->object->toTopology()); int nb; if (!PyArg_ParseTuple(args, "i",&nb)) { PyErr_BadArgument(); return NULL; } obj->setNz(nb); Py_RETURN_NONE; } SP_CLASS_METHODS_BEGIN(GridTopology) SP_CLASS_METHOD(GridTopology,setSize) SP_CLASS_METHOD(GridTopology,setNumVertices) SP_CLASS_METHOD(GridTopology,getNx) SP_CLASS_METHOD(GridTopology,getNy) SP_CLASS_METHOD(GridTopology,getNz) SP_CLASS_METHOD(GridTopology,setNx) SP_CLASS_METHOD(GridTopology,setNy) SP_CLASS_METHOD(GridTopology,setNz) SP_CLASS_METHODS_END SP_CLASS_TYPE_SPTR(GridTopology,GridTopology,MeshTopology) <|endoftext|>
<commit_before>#include "backends.hpp" #include<string> #include<armadillo> using namespace std; using namespace arma; #define DIM_NAME "__hide" #define ATTR_NAME "sample" #define ROW_NAME "samples" #define COL_NAME "channels" #define RANGE_SIZE 4 string TileDBBackend::mrn_to_array_name(string mrn) { return mrn + "-tiledb"; } string TileDBBackend::get_workspace() { return DATADIR; } int TileDBBackend::get_fs(string mrn) { return 256; // TODO(joshblum) store this in TileDB metadata when it's implemented } int TileDBBackend::get_array_len(string mrn) { return 84992; // TODO(joshblum) store this in TileDB metadata when it's implemented } void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata) { } void TileDBBackend::open_array(string mrn) { if (in_cache(mrn)) { return; } TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); string group = ""; string workspace = get_workspace(); string array_name = mrn_to_array_name(mrn); const char* mode = "r"; int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id)); } void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf) { tiledb_cache_pair cache_pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = cache_pair.first; int array_id = cache_pair.second; double* range = new double[RANGE_SIZE]; range[0] = CH_REVERSE_IDX[ch]; range[1] = CH_REVERSE_IDX[ch]; range[2] = start_offset; range[3] = end_offset; const char* dim_names = DIM_NAME; int dim_names_num = 1; const char* attribute_names = ATTR_NAME; int attribute_names_num = 1; size_t cell_buf_size = sizeof(float) * buf.n_elem; tiledb_subarray_buf(tiledb_ctx, array_id, range, RANGE_SIZE, &dim_names, dim_names_num, &attribute_names, attribute_names_num, buf.memptr(), &cell_buf_size); } void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf) { } void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf) { } void TileDBBackend::close_array(string mrn) { if (in_cache(mrn)) { tiledb_cache_pair pair = get_cache(mrn); tiledb_array_close(pair.first, pair.second); pop_cache(mrn); } } void TileDBBackend::edf_to_array(string mrn) { EDFBackend edf_backend; edf_backend.open_array(mrn); int nchannels = NCHANNELS; int nsamples = edf_backend.get_array_len(mrn); int fs = edf_backend.get_fs(mrn); // TODO(joshblum) store this in TileDB metadata when it's implemented cout << "Writing " << nsamples << " samples with fs=" << fs << "." << endl; string group = ""; string workspace = get_workspace(); string array_name = mrn_to_array_name(mrn); // csv of array schema string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(nsamples) + ",0," + to_string(nchannels) + ",float32,int32,*,column-major,*,*,*,*"; // Initialize TileDB TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); cout << "Defining TileDB schema." << endl; // Store the array schema if (tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str())) { tiledb_ctx_finalize(tiledb_ctx); return; } cout << "Opening TileDB array." << endl; const char* mode = "a"; int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); cout << "Writing cells to TileDB." << endl; int ch, start_offset, end_offset; cell_t cell; for (int i = 0; i < nchannels; i++) { ch = CHANNEL_ARRAY[i]; start_offset = 0; end_offset = min(nsamples, CHUNK_SIZE); frowvec chunk_buf = frowvec(end_offset); // store samples from each channel here // read chunks from each signal and write them for (; end_offset <= nsamples; end_offset = min(end_offset + CHUNK_SIZE, nsamples)) { if (end_offset - start_offset != CHUNK_SIZE) { chunk_buf.resize(end_offset - start_offset); } edf_backend.read_array(mrn, ch, start_offset, end_offset, chunk_buf); // write chunk_mat to file for (uword i = 0; i < chunk_buf.n_elem; i++) { // x coord, y coord, attribute cell.x = CH_REVERSE_IDX[ch]; cell.y = start_offset + i; cell.sample = chunk_buf(i); tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell); } start_offset = end_offset; // ensure we write the last part of the samples if (end_offset == nsamples) { break; } if (!(ch % 2 || (end_offset / CHUNK_SIZE) % 10)) // print for even channels every 10 chunks (40MB) { cout << "Wrote " << end_offset / CHUNK_SIZE << " chunks for ch: " << ch << endl; } } } // Finalize TileDB tiledb_array_close(tiledb_ctx, array_id); tiledb_ctx_finalize(tiledb_ctx); cout << "Conversion complete." << endl; } <commit_msg>read/write mode on tiledb<commit_after>#include "backends.hpp" #include<string> #include<armadillo> using namespace std; using namespace arma; #define DIM_NAME "__hide" #define ATTR_NAME "sample" #define ROW_NAME "samples" #define COL_NAME "channels" #define RANGE_SIZE 4 string TileDBBackend::mrn_to_array_name(string mrn) { return mrn + "-tiledb"; } string TileDBBackend::get_workspace() { return DATADIR; } int TileDBBackend::get_fs(string mrn) { return 256; // TODO(joshblum) store this in TileDB metadata when it's implemented } int TileDBBackend::get_array_len(string mrn) { return 84992; // TODO(joshblum) store this in TileDB metadata when it's implemented } void TileDBBackend::create_array(string mrn, ArrayMetadata* metadata) { } void TileDBBackend::open_array(string mrn) { if (in_cache(mrn)) { return; } TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); string group = ""; string workspace = get_workspace(); string array_name = mrn_to_array_name(mrn); const char* mode = "r"; // TODO(joshblum): if read/write available this would be better int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); put_cache(mrn, tiledb_cache_pair(tiledb_ctx, array_id)); } void TileDBBackend::read_array(string mrn, int ch, int start_offset, int end_offset, frowvec& buf) { tiledb_cache_pair cache_pair = get_cache(mrn); TileDB_CTX* tiledb_ctx = cache_pair.first; int array_id = cache_pair.second; double* range = new double[RANGE_SIZE]; range[0] = CH_REVERSE_IDX[ch]; range[1] = CH_REVERSE_IDX[ch]; range[2] = start_offset; range[3] = end_offset; const char* dim_names = DIM_NAME; int dim_names_num = 1; const char* attribute_names = ATTR_NAME; int attribute_names_num = 1; size_t cell_buf_size = sizeof(float) * buf.n_elem; tiledb_subarray_buf(tiledb_ctx, array_id, range, RANGE_SIZE, &dim_names, dim_names_num, &attribute_names, attribute_names_num, buf.memptr(), &cell_buf_size); } void TileDBBackend::read_array(string mrn, int start_offset, int end_offset, fmat& buf) { } void TileDBBackend::write_array(string mrn, int ch, int start_offset, int end_offset, fmat& buf) { } void TileDBBackend::close_array(string mrn) { if (in_cache(mrn)) { tiledb_cache_pair pair = get_cache(mrn); tiledb_array_close(pair.first, pair.second); pop_cache(mrn); } } void TileDBBackend::edf_to_array(string mrn) { EDFBackend edf_backend; edf_backend.open_array(mrn); int nchannels = NCHANNELS; int nsamples = edf_backend.get_array_len(mrn); int fs = edf_backend.get_fs(mrn); // TODO(joshblum) store this in TileDB metadata when it's implemented cout << "Writing " << nsamples << " samples with fs=" << fs << "." << endl; string group = ""; string workspace = get_workspace(); string array_name = mrn_to_array_name(mrn); // csv of array schema string array_schema_str = array_name + ",1," + ATTR_NAME + ",2," + COL_NAME + "," + ROW_NAME + ",0," + to_string(nsamples) + ",0," + to_string(nchannels) + ",float32,int32,*,column-major,*,*,*,*"; // Initialize TileDB TileDB_CTX* tiledb_ctx; tiledb_ctx_init(tiledb_ctx); cout << "Defining TileDB schema." << endl; // Store the array schema if (tiledb_array_define(tiledb_ctx, workspace.c_str(), group.c_str(), array_schema_str.c_str())) { tiledb_ctx_finalize(tiledb_ctx); return; } cout << "Opening TileDB array." << endl; const char* mode = "a"; int array_id = tiledb_array_open(tiledb_ctx, workspace.c_str(), group.c_str(), array_name.c_str(), mode); cout << "Writing cells to TileDB." << endl; int ch, start_offset, end_offset; cell_t cell; for (int i = 0; i < nchannels; i++) { ch = CHANNEL_ARRAY[i]; start_offset = 0; end_offset = min(nsamples, CHUNK_SIZE); frowvec chunk_buf = frowvec(end_offset); // store samples from each channel here // read chunks from each signal and write them for (; end_offset <= nsamples; end_offset = min(end_offset + CHUNK_SIZE, nsamples)) { if (end_offset - start_offset != CHUNK_SIZE) { chunk_buf.resize(end_offset - start_offset); } edf_backend.read_array(mrn, ch, start_offset, end_offset, chunk_buf); // write chunk_mat to file for (uword i = 0; i < chunk_buf.n_elem; i++) { // x coord, y coord, attribute cell.x = CH_REVERSE_IDX[ch]; cell.y = start_offset + i; cell.sample = chunk_buf(i); tiledb_cell_write_sorted(tiledb_ctx, array_id, &cell); } start_offset = end_offset; // ensure we write the last part of the samples if (end_offset == nsamples) { break; } if (!(ch % 2 || (end_offset / CHUNK_SIZE) % 10)) // print for even channels every 10 chunks (40MB) { cout << "Wrote " << end_offset / CHUNK_SIZE << " chunks for ch: " << ch << endl; } } } // Finalize TileDB tiledb_array_close(tiledb_ctx, array_id); tiledb_ctx_finalize(tiledb_ctx); cout << "Conversion complete." << endl; } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ //Own #include "submarine.h" #include "submarine_p.h" #include "torpedo.h" #include "pixmapitem.h" #include "graphicsscene.h" #include "animationmanager.h" #include "custompropertyanimation.h" #include "qanimationstate.h" #include <QtCore/QPropertyAnimation> #include <QtCore/QStateMachine> #include <QtCore/QFinalState> #include <QtCore/QSequentialAnimationGroup> static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) { QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); #if QT_VERSION >=0x040500 PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub); step1->setZValue(6); PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub); step2->setZValue(6); PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub); step3->setZValue(6); PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub); step4->setZValue(6); step1->setOpacity(0); step2->setOpacity(0); step3->setOpacity(0); step4->setOpacity(0); CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub); anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim1->setDuration(100); anim1->setEndValue(1); CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub); anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim2->setDuration(100); anim2->setEndValue(1); CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub); anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim3->setDuration(100); anim3->setEndValue(1); CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub); anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim4->setDuration(100); anim4->setEndValue(1); group->addAnimation(anim1); group->addAnimation(anim2); group->addAnimation(anim3); group->addAnimation(anim4); #else // work around for a bug where we don't transition if the duration is zero. QtPauseAnimation *anim = new QtPauseAnimation(group); anim->setDuration(1); group->addAnimation(anim); #endif AnimationManager::self()->registerAnimation(group); return group; } SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags) : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) { pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setZValue(5); setFlags(QGraphicsItem::ItemIsMovable); resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height()); setTransformOriginPoint(boundingRect().center()); graphicsRotation = new QGraphicsRotation(this); graphicsRotation->setAxis(QVector3D(0, 1, 0)); graphicsRotation->setOrigin(QPointF(size().width()/2, size().height()/2)); QList<QGraphicsTransform *> r; r.append(graphicsRotation); setTransformations(r); //We setup the state machine of the submarine QStateMachine *machine = new QStateMachine(this); //This state is when the boat is moving/rotating QState *moving = new QState(machine); //This state is when the boat is moving from left to right MovementState *movement = new MovementState(this, moving); //This state is when the boat is moving from left to right ReturnState *rotation = new ReturnState(this, moving); //This is the initial state of the moving root state moving->setInitialState(movement); movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); //This is the initial state of the machine machine->setInitialState(moving); //End QFinalState *final = new QFinalState(machine); //If the moving animation is finished we move to the return state movement->addTransition(movement, SIGNAL(animationFinished()), rotation); //If the return animation is finished we move to the moving state rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); //This state play the destroyed animation QAnimationState *destroyedState = new QAnimationState(machine); destroyedState->setAnimation(setupDestroyAnimation(this)); //Play a nice animation when the submarine is destroyed moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); //Transition to final state when the destroyed animation is finished destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); //The machine has finished to be executed, then the submarine is dead connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); machine->start(); } int SubMarine::points() { return subPoints; } void SubMarine::setCurrentDirection(SubMarine::Movement direction) { if (this->direction == direction) return; if (direction == SubMarine::Right && this->direction == SubMarine::None) { graphicsRotation->setAngle(180); } this->direction = direction; } enum SubMarine::Movement SubMarine::currentDirection() const { return direction; } void SubMarine::setCurrentSpeed(int speed) { if (speed < 0 || speed > 3) { qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); } this->speed = speed; emit subMarineStateChanged(); } int SubMarine::currentSpeed() const { return speed; } void SubMarine::launchTorpedo(int speed) { Torpedo * torp = new Torpedo(); GraphicsScene *scene = static_cast<GraphicsScene *>(this->scene()); scene->addItem(torp); torp->setPos(x(), y()); torp->setCurrentSpeed(speed); torp->launch(); } void SubMarine::destroy() { emit subMarineDestroyed(); } int SubMarine::type() const { return Type; } <commit_msg>Fix sub-attaq after the QGraphicsTransform changes<commit_after>/**************************************************************************** ** ** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies). ** Contact: Nokia Corporation ([email protected]) ** ** This file is part of the QtCore module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** No Commercial Usage ** This file contains pre-release code and may not be distributed. ** You may use this file in accordance with the terms and conditions ** contained in the either Technology Preview License Agreement or the ** Beta Release License Agreement. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain ** additional rights. These rights are described in the Nokia Qt LGPL ** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this ** package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** $QT_END_LICENSE$ ** ****************************************************************************/ //Own #include "submarine.h" #include "submarine_p.h" #include "torpedo.h" #include "pixmapitem.h" #include "graphicsscene.h" #include "animationmanager.h" #include "custompropertyanimation.h" #include "qanimationstate.h" #include <QtCore/QPropertyAnimation> #include <QtCore/QStateMachine> #include <QtCore/QFinalState> #include <QtCore/QSequentialAnimationGroup> static QAbstractAnimation *setupDestroyAnimation(SubMarine *sub) { QSequentialAnimationGroup *group = new QSequentialAnimationGroup(sub); #if QT_VERSION >=0x040500 PixmapItem *step1 = new PixmapItem(QString("explosion/submarine/step1"),GraphicsScene::Big, sub); step1->setZValue(6); PixmapItem *step2 = new PixmapItem(QString("explosion/submarine/step2"),GraphicsScene::Big, sub); step2->setZValue(6); PixmapItem *step3 = new PixmapItem(QString("explosion/submarine/step3"),GraphicsScene::Big, sub); step3->setZValue(6); PixmapItem *step4 = new PixmapItem(QString("explosion/submarine/step4"),GraphicsScene::Big, sub); step4->setZValue(6); step1->setOpacity(0); step2->setOpacity(0); step3->setOpacity(0); step4->setOpacity(0); CustomPropertyAnimation *anim1 = new CustomPropertyAnimation(sub); anim1->setMemberFunctions((QGraphicsItem*)step1, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim1->setDuration(100); anim1->setEndValue(1); CustomPropertyAnimation *anim2 = new CustomPropertyAnimation(sub); anim2->setMemberFunctions((QGraphicsItem*)step2, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim2->setDuration(100); anim2->setEndValue(1); CustomPropertyAnimation *anim3 = new CustomPropertyAnimation(sub); anim3->setMemberFunctions((QGraphicsItem*)step3, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim3->setDuration(100); anim3->setEndValue(1); CustomPropertyAnimation *anim4 = new CustomPropertyAnimation(sub); anim4->setMemberFunctions((QGraphicsItem*)step4, &QGraphicsItem::opacity, &QGraphicsItem::setOpacity); anim4->setDuration(100); anim4->setEndValue(1); group->addAnimation(anim1); group->addAnimation(anim2); group->addAnimation(anim3); group->addAnimation(anim4); #else // work around for a bug where we don't transition if the duration is zero. QtPauseAnimation *anim = new QtPauseAnimation(group); anim->setDuration(1); group->addAnimation(anim); #endif AnimationManager::self()->registerAnimation(group); return group; } SubMarine::SubMarine(int type, const QString &name, int points, QGraphicsItem * parent, Qt::WindowFlags wFlags) : QGraphicsWidget(parent,wFlags), subType(type), subName(name), subPoints(points), speed(0), direction(SubMarine::None) { pixmapItem = new PixmapItem(QString("submarine"),GraphicsScene::Big, this); setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); setZValue(5); setFlags(QGraphicsItem::ItemIsMovable); resize(pixmapItem->boundingRect().width(),pixmapItem->boundingRect().height()); setTransformOriginPoint(boundingRect().center()); graphicsRotation = new QGraphicsRotation(this); graphicsRotation->setAxis(QVector3D(0, 1, 0)); graphicsRotation->setOrigin(QVector3D(size().width()/2, size().height()/2, 0)); QList<QGraphicsTransform *> r; r.append(graphicsRotation); setTransformations(r); //We setup the state machine of the submarine QStateMachine *machine = new QStateMachine(this); //This state is when the boat is moving/rotating QState *moving = new QState(machine); //This state is when the boat is moving from left to right MovementState *movement = new MovementState(this, moving); //This state is when the boat is moving from left to right ReturnState *rotation = new ReturnState(this, moving); //This is the initial state of the moving root state moving->setInitialState(movement); movement->addTransition(this, SIGNAL(subMarineStateChanged()), moving); //This is the initial state of the machine machine->setInitialState(moving); //End QFinalState *final = new QFinalState(machine); //If the moving animation is finished we move to the return state movement->addTransition(movement, SIGNAL(animationFinished()), rotation); //If the return animation is finished we move to the moving state rotation->addTransition(rotation, SIGNAL(animationFinished()), movement); //This state play the destroyed animation QAnimationState *destroyedState = new QAnimationState(machine); destroyedState->setAnimation(setupDestroyAnimation(this)); //Play a nice animation when the submarine is destroyed moving->addTransition(this, SIGNAL(subMarineDestroyed()), destroyedState); //Transition to final state when the destroyed animation is finished destroyedState->addTransition(destroyedState, SIGNAL(animationFinished()), final); //The machine has finished to be executed, then the submarine is dead connect(machine,SIGNAL(finished()),this, SIGNAL(subMarineExecutionFinished())); machine->start(); } int SubMarine::points() { return subPoints; } void SubMarine::setCurrentDirection(SubMarine::Movement direction) { if (this->direction == direction) return; if (direction == SubMarine::Right && this->direction == SubMarine::None) { graphicsRotation->setAngle(180); } this->direction = direction; } enum SubMarine::Movement SubMarine::currentDirection() const { return direction; } void SubMarine::setCurrentSpeed(int speed) { if (speed < 0 || speed > 3) { qWarning("SubMarine::setCurrentSpeed : The speed is invalid"); } this->speed = speed; emit subMarineStateChanged(); } int SubMarine::currentSpeed() const { return speed; } void SubMarine::launchTorpedo(int speed) { Torpedo * torp = new Torpedo(); GraphicsScene *scene = static_cast<GraphicsScene *>(this->scene()); scene->addItem(torp); torp->setPos(x(), y()); torp->setCurrentSpeed(speed); torp->launch(); } void SubMarine::destroy() { emit subMarineDestroyed(); } int SubMarine::type() const { return Type; } <|endoftext|>
<commit_before><commit_msg>TODO-697: minimising SPI activity<commit_after><|endoftext|>
<commit_before><commit_msg>no extra UI feedback right after POST<commit_after><|endoftext|>
<commit_before>#include <gtest/gtest.h> #include <unistd.h> #include <string> #include <tbb/atomic.h> #include <iostream> // TODO: remove me! #include "../../cvmfs/util.h" #include "../../cvmfs/upload_spooler_definition.h" #include "../../cvmfs/upload_local.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/file_processing/char_buffer.h" #include "testutil.h" #include "c_file_sandbox.h" using namespace upload; class UploadCallbacks { public: UploadCallbacks() { simple_upload_invocations = 0; } void SimpleUploadClosure(const UploaderResults &results, UploaderResults expected) { EXPECT_EQ (expected.return_code, results.return_code); EXPECT_EQ (expected.local_path, results.local_path); ++simple_upload_invocations; } public: tbb::atomic<unsigned int> simple_upload_invocations; }; class T_LocalUploader : public FileSandbox { private: static const std::string sandbox_path; static const std::string dest_dir; static const std::string tmp_dir; public: T_LocalUploader() : FileSandbox(T_LocalUploader::sandbox_path) {} protected: virtual void SetUp() { CreateSandbox(T_LocalUploader::tmp_dir); const bool success = MkdirDeep(T_LocalUploader::dest_dir, 0700); ASSERT_TRUE (success) << "Failed to create uploader destination dir"; InitializeStorageBackend(); uploader_ = AbstractUploader::Construct(GetSpoolerDefinition()); ASSERT_NE (static_cast<AbstractUploader*>(NULL), uploader_); } virtual void TearDown() { if (uploader_ != NULL) { uploader_->TearDown(); delete uploader_; uploader_ = NULL; } RemoveSandbox(T_LocalUploader::tmp_dir); } void InitializeStorageBackend() { const std::string &dir = T_LocalUploader::dest_dir + "/data"; bool success = MkdirDeep(dir + "/txn", 0700); ASSERT_TRUE (success) << "Failed to create transaction tmp dir"; for (unsigned int i = 0; i <= 255; ++i) { success = MkdirDeep(dir + "/" + ByteToHex(static_cast<char>(i)), 0700); ASSERT_TRUE (success); } } SpoolerDefinition GetSpoolerDefinition() const { const std::string spl_type = "local"; const std::string spl_tmp = T_LocalUploader::tmp_dir; const std::string spl_cfg = T_LocalUploader::dest_dir; const std::string definition = spl_type + "," + spl_tmp + "," + spl_cfg; const bool use_file_chunking = true; const size_t min_chunk_size = 0; // chunking does not matter here, we are const size_t avg_chunk_size = 1; // only testing the upload module. const size_t max_chunk_size = 2; return SpoolerDefinition(definition, use_file_chunking, min_chunk_size, avg_chunk_size, max_chunk_size); } bool CheckFile(const std::string &remote_path) const { const std::string absolute_path = AbsoluteDestinationPath(remote_path); return FileExists(absolute_path); } bool CompareFileContents(const std::string &testee_path, const std::string &reference_path) const { shash::Any testee_hash = HashFile(testee_path); shash::Any reference_hash = HashFile(reference_path); return testee_hash == reference_hash; } std::string AbsoluteDestinationPath(const std::string &remote_path) const { return T_LocalUploader::dest_dir + "/" + remote_path; } private: std::string ByteToHex(const unsigned char byte) { const char pos_1 = byte / 16; const char pos_0 = byte % 16; const char hex[3] = { (pos_1 <= 9) ? '0' + pos_1 : 'a' + (pos_1 - 10), (pos_0 <= 9) ? '0' + pos_0 : 'a' + (pos_0 - 10), 0 }; return std::string(hex); } shash::Any HashFile(const std::string &path) const { shash::Any result(shash::kMd5); // googletest requires method that use EXPECT_* or ASSERT_* to return void HashFileInternal (path, &result); return result; } void HashFileInternal(const std::string &path, shash::Any *hash) const { const bool successful = shash::HashFile(path, hash); ASSERT_TRUE (successful); } protected: AbstractUploader *uploader_; UploadCallbacks delegate_; }; const std::string T_LocalUploader::sandbox_path = "/tmp/cvmfs_ut_localuploader"; const std::string T_LocalUploader::tmp_dir = T_LocalUploader::sandbox_path + "/tmp"; const std::string T_LocalUploader::dest_dir = T_LocalUploader::sandbox_path + "/dest"; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, Initialize) { // nothing to do here... initialization runs completely in the fixture! } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, SimpleFileUpload) { const std::string big_file_path = GetBigFile(); const std::string dest_name = "big_file"; uploader_->Upload(big_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, big_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(big_file_path, AbsoluteDestinationPath(dest_name))); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, PeekIntoStorage) { const std::string small_file_path = GetSmallFile(); const std::string dest_name = "small_file"; uploader_->Upload(small_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, small_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(small_file_path, AbsoluteDestinationPath(dest_name))); const bool file_exists = uploader_->Peek(dest_name); EXPECT_TRUE (file_exists); const bool file_doesnt_exist = uploader_->Peek("alien"); EXPECT_FALSE (file_doesnt_exist); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, RemoveFromStorage) { const std::string small_file_path = GetSmallFile(); const std::string dest_name = "also_small_file"; uploader_->Upload(small_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, small_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(small_file_path, AbsoluteDestinationPath(dest_name))); const bool file_exists = uploader_->Peek(dest_name); EXPECT_TRUE (file_exists); const bool removed_successfully = uploader_->Remove(dest_name); EXPECT_TRUE (removed_successfully); EXPECT_FALSE(CheckFile(dest_name)); const bool file_still_exists = uploader_->Peek(dest_name); EXPECT_FALSE (file_still_exists); } <commit_msg>TEST: edge cases: huge file and empty file upload<commit_after>#include <gtest/gtest.h> #include <unistd.h> #include <string> #include <tbb/atomic.h> #include <iostream> // TODO: remove me! #include "../../cvmfs/util.h" #include "../../cvmfs/upload_spooler_definition.h" #include "../../cvmfs/upload_local.h" #include "../../cvmfs/hash.h" #include "../../cvmfs/file_processing/char_buffer.h" #include "testutil.h" #include "c_file_sandbox.h" using namespace upload; class UploadCallbacks { public: UploadCallbacks() { simple_upload_invocations = 0; } void SimpleUploadClosure(const UploaderResults &results, UploaderResults expected) { EXPECT_EQ (expected.return_code, results.return_code); EXPECT_EQ (expected.local_path, results.local_path); ++simple_upload_invocations; } public: tbb::atomic<unsigned int> simple_upload_invocations; }; class T_LocalUploader : public FileSandbox { private: static const std::string sandbox_path; static const std::string dest_dir; static const std::string tmp_dir; public: T_LocalUploader() : FileSandbox(T_LocalUploader::sandbox_path) {} protected: virtual void SetUp() { CreateSandbox(T_LocalUploader::tmp_dir); const bool success = MkdirDeep(T_LocalUploader::dest_dir, 0700); ASSERT_TRUE (success) << "Failed to create uploader destination dir"; InitializeStorageBackend(); uploader_ = AbstractUploader::Construct(GetSpoolerDefinition()); ASSERT_NE (static_cast<AbstractUploader*>(NULL), uploader_); } virtual void TearDown() { if (uploader_ != NULL) { uploader_->TearDown(); delete uploader_; uploader_ = NULL; } RemoveSandbox(T_LocalUploader::tmp_dir); } void InitializeStorageBackend() { const std::string &dir = T_LocalUploader::dest_dir + "/data"; bool success = MkdirDeep(dir + "/txn", 0700); ASSERT_TRUE (success) << "Failed to create transaction tmp dir"; for (unsigned int i = 0; i <= 255; ++i) { success = MkdirDeep(dir + "/" + ByteToHex(static_cast<char>(i)), 0700); ASSERT_TRUE (success); } } SpoolerDefinition GetSpoolerDefinition() const { const std::string spl_type = "local"; const std::string spl_tmp = T_LocalUploader::tmp_dir; const std::string spl_cfg = T_LocalUploader::dest_dir; const std::string definition = spl_type + "," + spl_tmp + "," + spl_cfg; const bool use_file_chunking = true; const size_t min_chunk_size = 0; // chunking does not matter here, we are const size_t avg_chunk_size = 1; // only testing the upload module. const size_t max_chunk_size = 2; return SpoolerDefinition(definition, use_file_chunking, min_chunk_size, avg_chunk_size, max_chunk_size); } bool CheckFile(const std::string &remote_path) const { const std::string absolute_path = AbsoluteDestinationPath(remote_path); return FileExists(absolute_path); } bool CompareFileContents(const std::string &testee_path, const std::string &reference_path) const { shash::Any testee_hash = HashFile(testee_path); shash::Any reference_hash = HashFile(reference_path); return testee_hash == reference_hash; } std::string AbsoluteDestinationPath(const std::string &remote_path) const { return T_LocalUploader::dest_dir + "/" + remote_path; } private: std::string ByteToHex(const unsigned char byte) { const char pos_1 = byte / 16; const char pos_0 = byte % 16; const char hex[3] = { (pos_1 <= 9) ? '0' + pos_1 : 'a' + (pos_1 - 10), (pos_0 <= 9) ? '0' + pos_0 : 'a' + (pos_0 - 10), 0 }; return std::string(hex); } shash::Any HashFile(const std::string &path) const { shash::Any result(shash::kMd5); // googletest requires method that use EXPECT_* or ASSERT_* to return void HashFileInternal (path, &result); return result; } void HashFileInternal(const std::string &path, shash::Any *hash) const { const bool successful = shash::HashFile(path, hash); ASSERT_TRUE (successful); } protected: AbstractUploader *uploader_; UploadCallbacks delegate_; }; const std::string T_LocalUploader::sandbox_path = "/tmp/cvmfs_ut_localuploader"; const std::string T_LocalUploader::tmp_dir = T_LocalUploader::sandbox_path + "/tmp"; const std::string T_LocalUploader::dest_dir = T_LocalUploader::sandbox_path + "/dest"; // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, Initialize) { // nothing to do here... initialization runs completely in the fixture! } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, SimpleFileUpload) { const std::string big_file_path = GetBigFile(); const std::string dest_name = "big_file"; uploader_->Upload(big_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, big_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(big_file_path, AbsoluteDestinationPath(dest_name))); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, PeekIntoStorage) { const std::string small_file_path = GetSmallFile(); const std::string dest_name = "small_file"; uploader_->Upload(small_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, small_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(small_file_path, AbsoluteDestinationPath(dest_name))); const bool file_exists = uploader_->Peek(dest_name); EXPECT_TRUE (file_exists); const bool file_doesnt_exist = uploader_->Peek("alien"); EXPECT_FALSE (file_doesnt_exist); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, RemoveFromStorage) { const std::string small_file_path = GetSmallFile(); const std::string dest_name = "also_small_file"; uploader_->Upload(small_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, small_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(small_file_path, AbsoluteDestinationPath(dest_name))); const bool file_exists = uploader_->Peek(dest_name); EXPECT_TRUE (file_exists); const bool removed_successfully = uploader_->Remove(dest_name); EXPECT_TRUE (removed_successfully); EXPECT_FALSE(CheckFile(dest_name)); const bool file_still_exists = uploader_->Peek(dest_name); EXPECT_FALSE (file_still_exists); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, UploadEmptyFile) { const std::string empty_file_path = GetEmptyFile(); const std::string dest_name = "empty_file"; uploader_->Upload(empty_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, empty_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(empty_file_path, AbsoluteDestinationPath(dest_name))); EXPECT_EQ (0, GetFileSize(AbsoluteDestinationPath(dest_name))); } // // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - // TEST_F(T_LocalUploader, UploadHugeFile) { const std::string huge_file_path = GetHugeFile(); const std::string dest_name = "huge_file"; uploader_->Upload(huge_file_path, dest_name, AbstractUploader::MakeClosure(&UploadCallbacks::SimpleUploadClosure, &delegate_, UploaderResults(0, huge_file_path))); uploader_->WaitForUpload(); EXPECT_TRUE (CheckFile(dest_name)); EXPECT_EQ (1u, delegate_.simple_upload_invocations); EXPECT_TRUE (CompareFileContents(huge_file_path, AbsoluteDestinationPath(dest_name))); } <|endoftext|>
<commit_before>#include "base/logging.hpp" #include "indexer/feature.hpp" #include "editor/changeset_wrapper.hpp" #include "std/algorithm.hpp" #include "std/sstream.hpp" #include "std/map.hpp" #include "geometry/mercator.hpp" #include "private.h" using editor::XMLFeature; namespace { double ScoreLatLon(XMLFeature const & xmlFt, ms::LatLon const & latLon) { double constexpr eps = MercatorBounds::GetCellID2PointAbsEpsilon(); return latLon.EqualDxDy(xmlFt.GetCenter(), eps); } double ScoreNames(XMLFeature const & xmlFt, StringUtf8Multilang const & names) { double score = 0; names.ForEachRef([&score, &xmlFt](uint8_t const langCode, string const & name) { if (xmlFt.GetName(langCode) == name) score += 1; return true; }); // TODO(mgsergio): Deafult name match should have greater wieght. Should it? return score; } vector<string> GetOsmOriginalTagsForType(feature::Metadata::EType const et) { static multimap<feature::Metadata::EType, string> const kFmd2Osm = { {feature::Metadata::EType::FMD_CUISINE, "cuisine"}, {feature::Metadata::EType::FMD_OPEN_HOURS, "opening_hours"}, {feature::Metadata::EType::FMD_PHONE_NUMBER, "phone"}, {feature::Metadata::EType::FMD_PHONE_NUMBER, "contact:phone"}, {feature::Metadata::EType::FMD_FAX_NUMBER, "fax"}, {feature::Metadata::EType::FMD_FAX_NUMBER, "contact:fax"}, {feature::Metadata::EType::FMD_STARS, "stars"}, {feature::Metadata::EType::FMD_OPERATOR, "operator"}, {feature::Metadata::EType::FMD_URL, "url"}, {feature::Metadata::EType::FMD_WEBSITE, "website"}, {feature::Metadata::EType::FMD_WEBSITE, "contact:website"}, // TODO: {feature::Metadata::EType::FMD_INTERNET, ""}, {feature::Metadata::EType::FMD_ELE, "ele"}, {feature::Metadata::EType::FMD_TURN_LANES, "turn:lanes"}, {feature::Metadata::EType::FMD_TURN_LANES_FORWARD, "turn:lanes:forward"}, {feature::Metadata::EType::FMD_TURN_LANES_BACKWARD, "turn:lanes:backward"}, {feature::Metadata::EType::FMD_EMAIL, "email"}, {feature::Metadata::EType::FMD_EMAIL, "contact:email"}, {feature::Metadata::EType::FMD_POSTCODE, "addr:postcode"}, {feature::Metadata::EType::FMD_WIKIPEDIA, "wikipedia"}, {feature::Metadata::EType::FMD_MAXSPEED, "maxspeed"}, {feature::Metadata::EType::FMD_FLATS, "addr:flats"}, {feature::Metadata::EType::FMD_HEIGHT, "height"}, {feature::Metadata::EType::FMD_MIN_HEIGHT, "min_height"}, {feature::Metadata::EType::FMD_MIN_HEIGHT, "building:min_level"}, {feature::Metadata::EType::FMD_DENOMINATION, "denomination"}, {feature::Metadata::EType::FMD_BUILDING_LEVELS, "building:levels"}, }; vector<string> result; auto const range = kFmd2Osm.equal_range(et); for (auto it = range.first; it != range.second; ++it) result.emplace_back(it->second); return result; } double ScoreMetadata(XMLFeature const & xmlFt, feature::Metadata const & metadata) { double score = 0; for (auto const type : metadata.GetPresentTypes()) { for (auto const osm_tag : GetOsmOriginalTagsForType(static_cast<feature::Metadata::EType>(type))) { if (xmlFt.GetTagValue(osm_tag) == metadata.Get(type)) { score += 1; break; } } } return score; } bool TypesEqual(XMLFeature const & xmlFt, feature::TypesHolder const & types) { return false; } pugi::xml_node GetBestOsmNode(pugi::xml_document const & osmResponse, FeatureType const & ft) { double bestScore = -1; pugi::xml_node bestMatchNode; for (auto const & xNode : osmResponse.select_nodes("node")) { try { XMLFeature xmlFt(xNode.node()); if (!TypesEqual(xmlFt, feature::TypesHolder(ft))) continue; double nodeScore = ScoreLatLon(xmlFt, MercatorBounds::ToLatLon(ft.GetCenter())); if (nodeScore < 0) continue; nodeScore += ScoreNames(xmlFt, ft.GetNames()); nodeScore += ScoreMetadata(xmlFt, ft.GetMetadata()); if (bestScore < nodeScore) { bestScore = nodeScore; bestMatchNode = xNode.node(); } } catch (editor::XMLFeatureNoLatLonError const & ex) { LOG(LWARNING, ("No lat/lon attribute in osm response node.", ex.Msg())); continue; } } // TODO(mgsergio): Add a properly defined threshold. // if (bestScore < minimumScoreThreshold) // return pugi::xml_node; return bestMatchNode; } } // namespace string DebugPrint(pugi::xml_document const & doc) { ostringstream stream; doc.print(stream, " "); return stream.str(); } namespace osm { ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret, ServerApi06::TKeyValueTags const & comments) : m_changesetComments(comments), m_api(OsmOAuth::ServerAuth().SetToken(keySecret)) { } ChangesetWrapper::~ChangesetWrapper() { if (m_changesetId) m_api.CloseChangeSet(m_changesetId); } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc) { auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon); if (response.first == OsmOAuth::ResponseCode::NetworkError) MYTHROW(NetworkErrorException, ("NetworkError with GetXmlFeaturesAtLatLon request.")); if (response.first != OsmOAuth::ResponseCode::OK) MYTHROW(HttpErrorException, ("HTTP error", response.first, "with GetXmlFeaturesAtLatLon", ll)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second)); } XMLFeature ChangesetWrapper::GetMatchingFeatureFromOSM(XMLFeature const & ourPatch, FeatureType const & feature) { if (feature.GetFeatureType() == feature::EGeomType::GEOM_POINT) { // Match with OSM node. ms::LatLon const ll = ourPatch.GetCenter(); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); // feature must be the original one, not patched! pugi::xml_node const bestNode = GetBestOsmNode(doc, feature); if (bestNode.empty()) MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc)); return XMLFeature(bestNode); } else if (feature.GetFeatureType() == feature::EGeomType::GEOM_AREA) { using m2::PointD; // Set filters out duplicate points for closed ways or triangles' vertices. set<PointD> geometry; feature.ForEachTriangle([&geometry](PointD const & p1, PointD const & p2, PointD const & p3) { geometry.insert(p1); geometry.insert(p2); geometry.insert(p3); }, FeatureType::BEST_GEOMETRY); ASSERT_GREATER_OR_EQUAL(geometry.size(), 3, ("Is it an area feature?")); for (auto const & pt : geometry) { ms::LatLon const ll = MercatorBounds::ToLatLon(pt); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); // TODO(AlexZ): Select best matching OSM way from possible many ways. pugi::xml_node const firstWay = doc.child("osm").child("way"); if (firstWay.empty()) continue; XMLFeature const way(firstWay); if (!way.IsArea()) continue; // TODO: Check that this way is really match our feature. return way; } MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature", feature)); } MYTHROW(LinearFeaturesAreNotSupportedException, ("We don't edit linear features yet.")); } void ChangesetWrapper::ModifyNode(XMLFeature node) { // TODO(AlexZ): ServerApi can be much better with exceptions. if (m_changesetId == kInvalidChangesetId && !m_api.CreateChangeSet(m_changesetComments, m_changesetId)) MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException")); uint64_t nodeId; if (!strings::to_uint64(node.GetAttribute("id"), nodeId)) MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException")); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); if (!m_api.ModifyNode(node.ToOSMString(), nodeId)) MYTHROW(ModifyNodeFailedException, ("ModifyNodeFailedException")); } } // namespace osm <commit_msg>Fix after rebase.<commit_after>#include "base/logging.hpp" #include "indexer/feature.hpp" #include "editor/changeset_wrapper.hpp" #include "std/algorithm.hpp" #include "std/sstream.hpp" #include "std/map.hpp" #include "geometry/mercator.hpp" #include "private.h" using editor::XMLFeature; namespace { double ScoreLatLon(XMLFeature const & xmlFt, ms::LatLon const & latLon) { double constexpr eps = MercatorBounds::GetCellID2PointAbsEpsilon(); return latLon.EqualDxDy(xmlFt.GetCenter(), eps); } double ScoreNames(XMLFeature const & xmlFt, StringUtf8Multilang const & names) { double score = 0; names.ForEach([&score, &xmlFt](uint8_t const langCode, string const & name) { if (xmlFt.GetName(langCode) == name) score += 1; return true; }); // TODO(mgsergio): Deafult name match should have greater wieght. Should it? return score; } vector<string> GetOsmOriginalTagsForType(feature::Metadata::EType const et) { static multimap<feature::Metadata::EType, string> const kFmd2Osm = { {feature::Metadata::EType::FMD_CUISINE, "cuisine"}, {feature::Metadata::EType::FMD_OPEN_HOURS, "opening_hours"}, {feature::Metadata::EType::FMD_PHONE_NUMBER, "phone"}, {feature::Metadata::EType::FMD_PHONE_NUMBER, "contact:phone"}, {feature::Metadata::EType::FMD_FAX_NUMBER, "fax"}, {feature::Metadata::EType::FMD_FAX_NUMBER, "contact:fax"}, {feature::Metadata::EType::FMD_STARS, "stars"}, {feature::Metadata::EType::FMD_OPERATOR, "operator"}, {feature::Metadata::EType::FMD_URL, "url"}, {feature::Metadata::EType::FMD_WEBSITE, "website"}, {feature::Metadata::EType::FMD_WEBSITE, "contact:website"}, // TODO: {feature::Metadata::EType::FMD_INTERNET, ""}, {feature::Metadata::EType::FMD_ELE, "ele"}, {feature::Metadata::EType::FMD_TURN_LANES, "turn:lanes"}, {feature::Metadata::EType::FMD_TURN_LANES_FORWARD, "turn:lanes:forward"}, {feature::Metadata::EType::FMD_TURN_LANES_BACKWARD, "turn:lanes:backward"}, {feature::Metadata::EType::FMD_EMAIL, "email"}, {feature::Metadata::EType::FMD_EMAIL, "contact:email"}, {feature::Metadata::EType::FMD_POSTCODE, "addr:postcode"}, {feature::Metadata::EType::FMD_WIKIPEDIA, "wikipedia"}, {feature::Metadata::EType::FMD_MAXSPEED, "maxspeed"}, {feature::Metadata::EType::FMD_FLATS, "addr:flats"}, {feature::Metadata::EType::FMD_HEIGHT, "height"}, {feature::Metadata::EType::FMD_MIN_HEIGHT, "min_height"}, {feature::Metadata::EType::FMD_MIN_HEIGHT, "building:min_level"}, {feature::Metadata::EType::FMD_DENOMINATION, "denomination"}, {feature::Metadata::EType::FMD_BUILDING_LEVELS, "building:levels"}, }; vector<string> result; auto const range = kFmd2Osm.equal_range(et); for (auto it = range.first; it != range.second; ++it) result.emplace_back(it->second); return result; } double ScoreMetadata(XMLFeature const & xmlFt, feature::Metadata const & metadata) { double score = 0; for (auto const type : metadata.GetPresentTypes()) { for (auto const osm_tag : GetOsmOriginalTagsForType(static_cast<feature::Metadata::EType>(type))) { if (xmlFt.GetTagValue(osm_tag) == metadata.Get(type)) { score += 1; break; } } } return score; } bool TypesEqual(XMLFeature const & xmlFt, feature::TypesHolder const & types) { return false; } pugi::xml_node GetBestOsmNode(pugi::xml_document const & osmResponse, FeatureType const & ft) { double bestScore = -1; pugi::xml_node bestMatchNode; for (auto const & xNode : osmResponse.select_nodes("node")) { try { XMLFeature xmlFt(xNode.node()); if (!TypesEqual(xmlFt, feature::TypesHolder(ft))) continue; double nodeScore = ScoreLatLon(xmlFt, MercatorBounds::ToLatLon(ft.GetCenter())); if (nodeScore < 0) continue; nodeScore += ScoreNames(xmlFt, ft.GetNames()); nodeScore += ScoreMetadata(xmlFt, ft.GetMetadata()); if (bestScore < nodeScore) { bestScore = nodeScore; bestMatchNode = xNode.node(); } } catch (editor::XMLFeatureNoLatLonError const & ex) { LOG(LWARNING, ("No lat/lon attribute in osm response node.", ex.Msg())); continue; } } // TODO(mgsergio): Add a properly defined threshold. // if (bestScore < minimumScoreThreshold) // return pugi::xml_node; return bestMatchNode; } } // namespace string DebugPrint(pugi::xml_document const & doc) { ostringstream stream; doc.print(stream, " "); return stream.str(); } namespace osm { ChangesetWrapper::ChangesetWrapper(TKeySecret const & keySecret, ServerApi06::TKeyValueTags const & comments) : m_changesetComments(comments), m_api(OsmOAuth::ServerAuth().SetToken(keySecret)) { } ChangesetWrapper::~ChangesetWrapper() { if (m_changesetId) m_api.CloseChangeSet(m_changesetId); } void ChangesetWrapper::LoadXmlFromOSM(ms::LatLon const & ll, pugi::xml_document & doc) { auto const response = m_api.GetXmlFeaturesAtLatLon(ll.lat, ll.lon); if (response.first == OsmOAuth::ResponseCode::NetworkError) MYTHROW(NetworkErrorException, ("NetworkError with GetXmlFeaturesAtLatLon request.")); if (response.first != OsmOAuth::ResponseCode::OK) MYTHROW(HttpErrorException, ("HTTP error", response.first, "with GetXmlFeaturesAtLatLon", ll)); if (pugi::status_ok != doc.load(response.second.c_str()).status) MYTHROW(OsmXmlParseException, ("Can't parse OSM server response for GetXmlFeaturesAtLatLon request", response.second)); } XMLFeature ChangesetWrapper::GetMatchingFeatureFromOSM(XMLFeature const & ourPatch, FeatureType const & feature) { if (feature.GetFeatureType() == feature::EGeomType::GEOM_POINT) { // Match with OSM node. ms::LatLon const ll = ourPatch.GetCenter(); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); // feature must be the original one, not patched! pugi::xml_node const bestNode = GetBestOsmNode(doc, feature); if (bestNode.empty()) MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any nodes at the coordinates", ll, ", server has returned:", doc)); return XMLFeature(bestNode); } else if (feature.GetFeatureType() == feature::EGeomType::GEOM_AREA) { using m2::PointD; // Set filters out duplicate points for closed ways or triangles' vertices. set<PointD> geometry; feature.ForEachTriangle([&geometry](PointD const & p1, PointD const & p2, PointD const & p3) { geometry.insert(p1); geometry.insert(p2); geometry.insert(p3); }, FeatureType::BEST_GEOMETRY); ASSERT_GREATER_OR_EQUAL(geometry.size(), 3, ("Is it an area feature?")); for (auto const & pt : geometry) { ms::LatLon const ll = MercatorBounds::ToLatLon(pt); pugi::xml_document doc; // Throws! LoadXmlFromOSM(ll, doc); // TODO(AlexZ): Select best matching OSM way from possible many ways. pugi::xml_node const firstWay = doc.child("osm").child("way"); if (firstWay.empty()) continue; XMLFeature const way(firstWay); if (!way.IsArea()) continue; // TODO: Check that this way is really match our feature. return way; } MYTHROW(OsmObjectWasDeletedException, ("OSM does not have any matching way for feature", feature)); } MYTHROW(LinearFeaturesAreNotSupportedException, ("We don't edit linear features yet.")); } void ChangesetWrapper::ModifyNode(XMLFeature node) { // TODO(AlexZ): ServerApi can be much better with exceptions. if (m_changesetId == kInvalidChangesetId && !m_api.CreateChangeSet(m_changesetComments, m_changesetId)) MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException")); uint64_t nodeId; if (!strings::to_uint64(node.GetAttribute("id"), nodeId)) MYTHROW(CreateChangeSetFailedException, ("CreateChangeSetFailedException")); // Changeset id should be updated for every OSM server commit. node.SetAttribute("changeset", strings::to_string(m_changesetId)); if (!m_api.ModifyNode(node.ToOSMString(), nodeId)) MYTHROW(ModifyNodeFailedException, ("ModifyNodeFailedException")); } } // namespace osm <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/dreamview/backend/util/trajectory_point_collector.h" #include <cmath> #include "gtest/gtest.h" #include "modules/common/configs/vehicle_config_helper.h" using apollo::common::TrajectoryPoint; namespace apollo { namespace dreamview { namespace util { class TrajectoryPointCollectorTest : public ::testing::Test { public: virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); } }; TEST_F(TrajectoryPointCollectorTest, ThreePoints) { SimulationWorld world; TrajectoryPointCollector collector(&world); const double base_time = 1000.0; for (int i = 0; i < 4; ++i) { TrajectoryPoint point; point.mutable_path_point()->set_x(i * 100.0); point.mutable_path_point()->set_y(i * 100.0 + 100.0); point.set_relative_time(i * 1000.0); collector.Collect(point, base_time); } EXPECT_EQ(world.planning_trajectory_size(), 3); { const Object &point = world.planning_trajectory(0); EXPECT_DOUBLE_EQ(0.0, point.position_x()); EXPECT_DOUBLE_EQ(100.0, point.position_y()); EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } { const Object &point = world.planning_trajectory(1); EXPECT_DOUBLE_EQ(100.0, point.position_x()); EXPECT_DOUBLE_EQ(200.0, point.position_y()); EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } { const Object &point = world.planning_trajectory(2); EXPECT_DOUBLE_EQ(200.0, point.position_x()); EXPECT_DOUBLE_EQ(300.0, point.position_y()); EXPECT_DOUBLE_EQ(4000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } } } // namespace util } // namespace dreamview } // namespace apollo <commit_msg>Dreamview: fixed a unit test<commit_after>/****************************************************************************** * Copyright 2017 The Apollo 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 "modules/dreamview/backend/util/trajectory_point_collector.h" #include <cmath> #include "gtest/gtest.h" #include "modules/common/configs/vehicle_config_helper.h" using apollo::common::TrajectoryPoint; namespace apollo { namespace dreamview { namespace util { class TrajectoryPointCollectorTest : public ::testing::Test { public: virtual void SetUp() { apollo::common::VehicleConfigHelper::Init(); } }; TEST_F(TrajectoryPointCollectorTest, ThreePoints) { SimulationWorld world; TrajectoryPointCollector collector(&world); const double base_time = 1000.0; for (int i = 0; i < 4; ++i) { TrajectoryPoint point; point.mutable_path_point()->set_x(i * 100.0); point.mutable_path_point()->set_y(i * 100.0 + 100.0); point.set_relative_time(i * 1000.0); collector.Collect(point, base_time); } EXPECT_EQ(world.planning_trajectory_size(), 3); { const Object &point = world.planning_trajectory(0); EXPECT_DOUBLE_EQ(0.0, point.position_x()); EXPECT_DOUBLE_EQ(100.0, point.position_y()); EXPECT_DOUBLE_EQ(1000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } { const Object &point = world.planning_trajectory(1); EXPECT_DOUBLE_EQ(100.0, point.position_x()); EXPECT_DOUBLE_EQ(200.0, point.position_y()); EXPECT_DOUBLE_EQ(2000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } { const Object &point = world.planning_trajectory(2); EXPECT_DOUBLE_EQ(200.0, point.position_x()); EXPECT_DOUBLE_EQ(300.0, point.position_y()); EXPECT_DOUBLE_EQ(3000.0, point.timestamp_sec()); EXPECT_DOUBLE_EQ(atan2(100.0, 100.0), point.heading()); } } } // namespace util } // namespace dreamview } // namespace apollo <|endoftext|>
<commit_before>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/component/constraintset/LMConstraintDirectSolver.h> #include <sofa/component/constraintset/ContactDescription.h> #include <sofa/core/ObjectFactory.h> #include <Eigen/QR> #include <Eigen/SVD> namespace sofa { namespace component { namespace constraintset { LMConstraintDirectSolver::LMConstraintDirectSolver(): solverAlgorithm(initData(&solverAlgorithm, "solverAlgorithm", "Algorithm used to solve the system W.Lambda=c")) { sofa::helper::OptionsGroup algo(2,"SVD","QR"); solverAlgorithm.setValue(algo); } bool LMConstraintDirectSolver::buildSystem(double dt, VecId id, core::behavior::BaseConstraintSet::ConstOrder order) { bool sucess=LMConstraintSolver::buildSystem(dt,id,order); return sucess; } bool LMConstraintDirectSolver::solveSystem(double dt, VecId id, core::behavior::BaseConstraintSet::ConstOrder order) { //First, do n iterations of Gauss Seidel bool success=LMConstraintSolver::solveSystem(dt,id,order); if (order != core::behavior::BaseConstraintSet::VEL) return success; //Then process to a direct solution of the system //We need to find all the constraint related to contact // 1. extract the information about the state of the contact and build the new L, L^T matrices // 2. build the full system // 3. solve //------------------------------------------------------------------ // extract the information about the state of the contact //------------------------------------------------------------------ //************************************************************ #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printNode("AnalyseConstraints"); #endif const helper::vector< BaseLMConstraint* > &LMConstraints=LMConstraintVisitor.getConstraints(); JacobianRows rowsL ; rowsL.reserve(numConstraint); JacobianRows rowsLT; rowsLT.reserve(numConstraint); helper::vector< unsigned int > rightHandElements; analyseConstraints(LMConstraints, order, rowsL, rowsLT, rightHandElements); #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("AnalyseConstraints"); #endif if (rowsL.empty() || rowsLT.empty()) return success; #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printNode("BuildFullSystem"); #endif //------------------------------------------------------------------ // build c: right hand term //------------------------------------------------------------------ VectorEigen previousC(c); //TODO: change newC by c c=VectorEigen::Zero(rowsL.size()); unsigned int idx=0; for (helper::vector<unsigned int >::const_iterator it=rightHandElements.begin(); it!=rightHandElements.end(); ++it) c[idx++]=previousC[*it]; //------------------------------------------------------------------ // build the L and LT matrices //------------------------------------------------------------------ DofToMatrix LMatricesDirectSolver; DofToMatrix LTMatricesDirectSolver; for (DofToMatrix::iterator it=LMatrices.begin(); it!=LMatrices.end(); ++it) { //------------------------------------------------------------------ const SparseMatrixEigen& matrix= it->second; //Init the manipulator with the full matrix linearsolver::LMatrixManipulator manip; manip.init(matrix); //------------------------------------------------------------------ SparseMatrixEigen L (rowsL.size(), matrix.cols()); L.startFill(rowsL.size()*matrix.cols()); manip.buildLMatrix(rowsL ,L); L.endFill(); LMatricesDirectSolver.insert (std::make_pair(it->first,L )); //------------------------------------------------------------------ SparseMatrixEigen LT(rowsLT.size(), matrix.cols()); LT.startFill(rowsLT.size()*matrix.cols()); manip.buildLMatrix(rowsLT,LT); LT.endFill(); LTMatricesDirectSolver.insert(std::make_pair(it->first,LT)); } //------------------------------------------------------------------ // build the full system //------------------------------------------------------------------ const int rows=rowsL.size(); const int cols=rowsLT.size(); SparseColMajorMatrixEigen Wsparse(rows,cols); buildLeftRectangularMatrix(invMassMatrix, LMatricesDirectSolver, LTMatricesDirectSolver, Wsparse,invMass_Ltrans); //------------------------------------------------------------------ // conversion from sparse to dense matrix //------------------------------------------------------------------ Lambda=VectorEigen::Zero(rows); W=MatrixEigen::Zero(rows,cols); SparseMatrixEigen Wresult(Wsparse); for (int k=0; k<Wresult.outerSize(); ++k) for (SparseMatrixEigen::InnerIterator it(Wresult,k); it; ++it) W(it.row(),it.col()) = it.value(); #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("BuildFullSystem"); #endif //------------------------------------------------------------------ // Solve the system //------------------------------------------------------------------ const std::string &algo=solverAlgorithm.getValue().getSelectedItem() ; #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::TRACE_ARGUMENT arg1; arg1.push_back(std::make_pair("Algorithm", algo)); arg1.push_back(std::make_pair("Dimension", printDimension(W))); sofa::simulation::Visitor::printNode("DirectSolveSystem", "",arg1); #endif if (algo == "QR") { Eigen::QR< MatrixEigen > solverQR(W); if (this->f_printLog.getValue()) sout << printDimension(W) << " is W invertible? " << std::boolalpha << solverQR.isInvertible() << sendl; if (solverQR.isInvertible()) solverQR.solve(c, &Lambda); else { if (this->f_printLog.getValue()) sout << "Fallback on SVD decomposition" << sendl; Eigen::SVD< MatrixEigen > solverSVD(W); solverSVD.solve(c, &Lambda); } } else if(algo == "SVD") { Eigen::SVD< MatrixEigen > solverSVD(W); solverSVD.solve(c, &Lambda); } if (this->f_printLog.getValue()) { sout << "W" << printDimension(W) << " Lambda" << printDimension(Lambda) << " c" << printDimension(c) << sendl; sout << "\nW ===============================================\n" << W << "\nLambda===============================================\n" << Lambda << "\nc ===============================================\n" << c << sendl; } #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("DirectSolveSystem"); #endif return success; } void LMConstraintDirectSolver::analyseConstraints(const helper::vector< BaseLMConstraint* > &LMConstraints, core::behavior::BaseConstraintSet::ConstOrder order, JacobianRows &rowsL,JacobianRows &rowsLT, helper::vector< unsigned int > &rightHandElements) const { //Iterate among all the Sofa LMConstraint for (unsigned int componentConstraint=0; componentConstraint<LMConstraints.size(); ++componentConstraint) { BaseLMConstraint *constraint=LMConstraints[componentConstraint]; //Find the constraint dealing with contact if (ContactDescriptionHandler* contactDescriptor=dynamic_cast<ContactDescriptionHandler*>(constraint)) { const helper::vector< BaseLMConstraint::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order); //Iterate among all the contacts for (helper::vector< BaseLMConstraint::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup) { const BaseLMConstraint::ConstraintGroup* group=*itGroup; const ContactDescription& contact=contactDescriptor->getContactDescription(group); const unsigned int idxEquation=group->getConstraint(0).idx; switch(contact.state) { case VANISHING: { // serr <<"Constraint " << idxEquation << " VANISHING" << sendl; //0 equation break; } case STICKING: { // serr << "Constraint " <<idxEquation << " STICKING" << sendl; const unsigned int i=rowsL.size(); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation )); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1)); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2)); //3 equations rowsLT.push_back(rowsL[i ]); rowsLT.push_back(rowsL[i+1]); rowsLT.push_back(rowsL[i+2]); rightHandElements.push_back(idxEquation ); rightHandElements.push_back(idxEquation+1); rightHandElements.push_back(idxEquation+2); break; } case SLIDING: { // serr << "Constraint " <<idxEquation << " SLIDING" << sendl; rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation )); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1)); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2)); //1 equation with the response force along the Coulomb friction cone rowsLT.push_back(linearsolver::LLineManipulator() .addCombination(idxEquation ,contact.coeff[0]) .addCombination(idxEquation+1,contact.coeff[1]) .addCombination(idxEquation+2,contact.coeff[2])); rightHandElements.push_back(idxEquation ); rightHandElements.push_back(idxEquation+1); rightHandElements.push_back(idxEquation+2); break; } } } } else { //Non contact constraints: we add all the equations const helper::vector< BaseLMConstraint::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order); for (helper::vector< BaseLMConstraint::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup) { const BaseLMConstraint::ConstraintGroup* group=*itGroup; std::pair< BaseLMConstraint::ConstraintGroup::EquationConstIterator,BaseLMConstraint::ConstraintGroup::EquationConstIterator> range=group->data(); for ( BaseLMConstraint::ConstraintGroup::EquationConstIterator it=range.first; it!=range.second; ++it) { rowsL.push_back(linearsolver::LLineManipulator().addCombination(it->idx)); rowsLT.push_back(rowsL.back()); } } } } } void LMConstraintDirectSolver::buildLeftRectangularMatrix(const DofToMatrix& invMassMatrix, DofToMatrix& LMatrix, DofToMatrix& LTMatrix, SparseColMajorMatrixEigen &LeftMatrix, DofToMatrix &invMass_Ltrans) const { invMass_Ltrans.clear(); for (SetDof::const_iterator itDofs=setDofs.begin(); itDofs!=setDofs.end(); ++itDofs) { const sofa::core::behavior::BaseMechanicalState* dofs=*itDofs; const SparseMatrixEigen &invMass=invMassMatrix.find(dofs)->second; SparseMatrixEigen &L =LMatrix[dofs]; L.endFill(); SparseMatrixEigen &LT=LTMatrix[dofs]; LT.endFill(); const SparseMatrixEigen &invMass_LT=invMass.marked<Eigen::SelfAdjoint|Eigen::UpperTriangular>()*LT.transpose(); invMass_Ltrans.insert(std::make_pair(dofs, invMass_LT)); const SparseColMajorMatrixEigen& temp=L*invMass_LT; LeftMatrix += temp; } } int LMConstraintDirectSolverClass = core::RegisterObject("A Direct Constraint Solver working specifically with LMConstraint based components") .add< LMConstraintDirectSolver >(); SOFA_DECL_CLASS(LMConstraintDirectSolver); } // namespace constraintset } // namespace component } // namespace sofa <commit_msg>r7951/sofa-dev : FIX: bug in DirectSolver<commit_after>/****************************************************************************** * SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 * * (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS * * * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. * ******************************************************************************* * SOFA :: Modules * * * * Authors: The SOFA Team and external contributors (see Authors.txt) * * * * Contact information: [email protected] * ******************************************************************************/ #include <sofa/component/constraintset/LMConstraintDirectSolver.h> #include <sofa/component/constraintset/ContactDescription.h> #include <sofa/core/ObjectFactory.h> #include <Eigen/QR> #include <Eigen/SVD> namespace sofa { namespace component { namespace constraintset { LMConstraintDirectSolver::LMConstraintDirectSolver(): solverAlgorithm(initData(&solverAlgorithm, "solverAlgorithm", "Algorithm used to solve the system W.Lambda=c")) { sofa::helper::OptionsGroup algo(2,"SVD","QR"); solverAlgorithm.setValue(algo); } bool LMConstraintDirectSolver::buildSystem(double dt, VecId id, core::behavior::BaseConstraintSet::ConstOrder order) { bool sucess=LMConstraintSolver::buildSystem(dt,id,order); return sucess; } bool LMConstraintDirectSolver::solveSystem(double dt, VecId id, core::behavior::BaseConstraintSet::ConstOrder order) { //First, do n iterations of Gauss Seidel bool success=LMConstraintSolver::solveSystem(dt,id,order); if (order != core::behavior::BaseConstraintSet::VEL) return success; //Then process to a direct solution of the system //We need to find all the constraint related to contact // 1. extract the information about the state of the contact and build the new L, L^T matrices // 2. build the full system // 3. solve //------------------------------------------------------------------ // extract the information about the state of the contact //------------------------------------------------------------------ //************************************************************ #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printNode("AnalyseConstraints"); #endif const helper::vector< BaseLMConstraint* > &LMConstraints=LMConstraintVisitor.getConstraints(); JacobianRows rowsL ; rowsL.reserve(numConstraint); JacobianRows rowsLT; rowsLT.reserve(numConstraint); helper::vector< unsigned int > rightHandElements; analyseConstraints(LMConstraints, order, rowsL, rowsLT, rightHandElements); #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("AnalyseConstraints"); #endif if (rowsL.empty() || rowsLT.empty()) return success; #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printNode("BuildFullSystem"); #endif //------------------------------------------------------------------ // build c: right hand term //------------------------------------------------------------------ VectorEigen previousC(c); //TODO: change newC by c c=VectorEigen::Zero(rowsL.size()); unsigned int idx=0; for (helper::vector<unsigned int >::const_iterator it=rightHandElements.begin(); it!=rightHandElements.end(); ++it) c[idx++]=previousC[*it]; //------------------------------------------------------------------ // build the L and LT matrices //------------------------------------------------------------------ DofToMatrix LMatricesDirectSolver; DofToMatrix LTMatricesDirectSolver; for (DofToMatrix::iterator it=LMatrices.begin(); it!=LMatrices.end(); ++it) { //------------------------------------------------------------------ const SparseMatrixEigen& matrix= it->second; //Init the manipulator with the full matrix linearsolver::LMatrixManipulator manip; manip.init(matrix); //------------------------------------------------------------------ SparseMatrixEigen L (rowsL.size(), matrix.cols()); L.startFill(rowsL.size()*matrix.cols()); manip.buildLMatrix(rowsL ,L); L.endFill(); LMatricesDirectSolver.insert (std::make_pair(it->first,L )); //------------------------------------------------------------------ SparseMatrixEigen LT(rowsLT.size(), matrix.cols()); LT.startFill(rowsLT.size()*matrix.cols()); manip.buildLMatrix(rowsLT,LT); LT.endFill(); LTMatricesDirectSolver.insert(std::make_pair(it->first,LT)); } //------------------------------------------------------------------ // build the full system //------------------------------------------------------------------ const int rows=rowsL.size(); const int cols=rowsLT.size(); SparseColMajorMatrixEigen Wsparse(rows,cols); buildLeftRectangularMatrix(invMassMatrix, LMatricesDirectSolver, LTMatricesDirectSolver, Wsparse,invMass_Ltrans); //------------------------------------------------------------------ // conversion from sparse to dense matrix //------------------------------------------------------------------ Lambda=VectorEigen::Zero(rows); W=MatrixEigen::Zero(rows,cols); SparseMatrixEigen Wresult(Wsparse); for (int k=0; k<Wresult.outerSize(); ++k) for (SparseMatrixEigen::InnerIterator it(Wresult,k); it; ++it) W(it.row(),it.col()) = it.value(); #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("BuildFullSystem"); #endif //------------------------------------------------------------------ // Solve the system //------------------------------------------------------------------ const std::string &algo=solverAlgorithm.getValue().getSelectedItem() ; #ifdef SOFA_DUMP_VISITOR_INFO simulation::Visitor::TRACE_ARGUMENT arg1; arg1.push_back(std::make_pair("Algorithm", algo)); arg1.push_back(std::make_pair("Dimension", printDimension(W))); sofa::simulation::Visitor::printNode("DirectSolveSystem", "",arg1); #endif if (algo == "QR") { Eigen::QR< MatrixEigen > solverQR(W); if (this->f_printLog.getValue()) sout << printDimension(W) << " is W invertible? " << std::boolalpha << solverQR.isInvertible() << sendl; if (solverQR.isInvertible()) solverQR.solve(c, &Lambda); else { if (this->f_printLog.getValue()) sout << "Fallback on SVD decomposition" << sendl; Eigen::SVD< MatrixEigen > solverSVD(W); solverSVD.solve(c, &Lambda); } } else if(algo == "SVD") { Eigen::SVD< MatrixEigen > solverSVD(W); solverSVD.solve(c, &Lambda); } if (this->f_printLog.getValue()) { sout << "W" << printDimension(W) << " Lambda" << printDimension(Lambda) << " c" << printDimension(c) << sendl; sout << "\nW ===============================================\n" << W << "\nLambda===============================================\n" << Lambda << "\nc ===============================================\n" << c << sendl; } #ifdef SOFA_DUMP_VISITOR_INFO sofa::simulation::Visitor::printCloseNode("DirectSolveSystem"); #endif return success; } void LMConstraintDirectSolver::analyseConstraints(const helper::vector< BaseLMConstraint* > &LMConstraints, core::behavior::BaseConstraintSet::ConstOrder order, JacobianRows &rowsL,JacobianRows &rowsLT, helper::vector< unsigned int > &rightHandElements) const { //Iterate among all the Sofa LMConstraint for (unsigned int componentConstraint=0; componentConstraint<LMConstraints.size(); ++componentConstraint) { BaseLMConstraint *constraint=LMConstraints[componentConstraint]; //Find the constraint dealing with contact if (ContactDescriptionHandler* contactDescriptor=dynamic_cast<ContactDescriptionHandler*>(constraint)) { const helper::vector< BaseLMConstraint::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order); //Iterate among all the contacts for (helper::vector< BaseLMConstraint::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup) { const BaseLMConstraint::ConstraintGroup* group=*itGroup; const ContactDescription& contact=contactDescriptor->getContactDescription(group); const unsigned int idxEquation=group->getConstraint(0).idx; switch(contact.state) { case VANISHING: { // serr <<"Constraint " << idxEquation << " VANISHING" << sendl; //0 equation break; } case STICKING: { // serr << "Constraint " <<idxEquation << " STICKING" << sendl; const unsigned int i=rowsL.size(); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation )); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1)); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2)); //3 equations rowsLT.push_back(rowsL[i ]); rowsLT.push_back(rowsL[i+1]); rowsLT.push_back(rowsL[i+2]); rightHandElements.push_back(idxEquation ); rightHandElements.push_back(idxEquation+1); rightHandElements.push_back(idxEquation+2); break; } case SLIDING: { // serr << "Constraint " <<idxEquation << " SLIDING" << sendl; rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation )); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+1)); rowsL.push_back(linearsolver::LLineManipulator().addCombination(idxEquation+2)); //1 equation with the response force along the Coulomb friction cone rowsLT.push_back(linearsolver::LLineManipulator() .addCombination(idxEquation ,contact.coeff[0]) .addCombination(idxEquation+1,contact.coeff[1]) .addCombination(idxEquation+2,contact.coeff[2])); rightHandElements.push_back(idxEquation ); rightHandElements.push_back(idxEquation+1); rightHandElements.push_back(idxEquation+2); break; } } } } else { //Non contact constraints: we add all the equations const helper::vector< BaseLMConstraint::ConstraintGroup* > &constraintOrder=constraint->getConstraintsOrder(order); for (helper::vector< BaseLMConstraint::ConstraintGroup* >::const_iterator itGroup=constraintOrder.begin(); itGroup!=constraintOrder.end(); ++itGroup) { const BaseLMConstraint::ConstraintGroup* group=*itGroup; std::pair< BaseLMConstraint::ConstraintGroup::EquationConstIterator,BaseLMConstraint::ConstraintGroup::EquationConstIterator> range=group->data(); for ( BaseLMConstraint::ConstraintGroup::EquationConstIterator it=range.first; it!=range.second; ++it) { rowsL.push_back(linearsolver::LLineManipulator().addCombination(it->idx)); rowsLT.push_back(rowsL.back()); rightHandElements.push_back(it->idx); } } } } } void LMConstraintDirectSolver::buildLeftRectangularMatrix(const DofToMatrix& invMassMatrix, DofToMatrix& LMatrix, DofToMatrix& LTMatrix, SparseColMajorMatrixEigen &LeftMatrix, DofToMatrix &invMass_Ltrans) const { invMass_Ltrans.clear(); for (SetDof::const_iterator itDofs=setDofs.begin(); itDofs!=setDofs.end(); ++itDofs) { const sofa::core::behavior::BaseMechanicalState* dofs=*itDofs; const SparseMatrixEigen &invMass=invMassMatrix.find(dofs)->second; SparseMatrixEigen &L =LMatrix[dofs]; L.endFill(); SparseMatrixEigen &LT=LTMatrix[dofs]; LT.endFill(); const SparseMatrixEigen &invMass_LT=invMass.marked<Eigen::SelfAdjoint|Eigen::UpperTriangular>()*LT.transpose(); invMass_Ltrans.insert(std::make_pair(dofs, invMass_LT)); const SparseColMajorMatrixEigen& temp=L*invMass_LT; LeftMatrix += temp; } } int LMConstraintDirectSolverClass = core::RegisterObject("A Direct Constraint Solver working specifically with LMConstraint based components") .add< LMConstraintDirectSolver >(); SOFA_DECL_CLASS(LMConstraintDirectSolver); } // namespace constraintset } // namespace component } // namespace sofa <|endoftext|>
<commit_before>/******************************************************************************* * BSD 3-Clause License * * Copyright (c) 2019, Los Alamos National Security, LLC * 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 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. *******************************************************************************/ /* Title : collision_check_thread.cpp * Project : moveit_jog_arm * Created : 1/11/2019 * Author : Brian O'Neil, Andy Zelenak, Blake Anderson */ #include <moveit_jog_arm/collision_check_thread.h> static const std::string LOGNAME = "collision_check_thread"; static const double MIN_RECOMMENDED_COLLISION_RATE = 10; namespace moveit_jog_arm { // Constructor for the class that handles collision checking CollisionCheckThread::CollisionCheckThread( const moveit_jog_arm::JogArmParameters& parameters, const planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor) : parameters_(parameters), planning_scene_monitor_(planning_scene_monitor) { if (parameters_.collision_check_rate < MIN_RECOMMENDED_COLLISION_RATE) ROS_WARN_STREAM_THROTTLE_NAMED(5, LOGNAME, "Collision check rate is low, increase it in yaml file if CPU allows"); } planning_scene_monitor::LockedPlanningSceneRO CollisionCheckThread::getLockedPlanningSceneRO() const { return planning_scene_monitor::LockedPlanningSceneRO(planning_scene_monitor_); } void CollisionCheckThread::startMainLoop(JogArmShared& shared_variables) { // Reset loop termination flag stop_requested_ = false; // Init collision request collision_detection::CollisionRequest collision_request; collision_request.group_name = parameters_.move_group_name; collision_detection::CollisionResult collision_result; // Copy the planning scene's version of current state into new memory moveit::core::RobotState current_state(getLockedPlanningSceneRO()->getCurrentState()); double velocity_scale_coefficient = -log(0.001) / parameters_.collision_proximity_threshold; ros::Rate collision_rate(parameters_.collision_check_rate); double collision_distance = 0; // Scale robot velocity according to collision proximity and user-defined thresholds. // I scaled exponentially (cubic power) so velocity drops off quickly after the threshold. // Proximity decreasing --> decelerate double velocity_scale = 1; ///////////////////////////////////////////////// // Spin while checking collisions ///////////////////////////////////////////////// while (ros::ok() && !stop_requested_) { shared_variables.lock(); sensor_msgs::JointState jts = shared_variables.joints; shared_variables.unlock(); for (std::size_t i = 0; i < jts.position.size(); ++i) current_state.setJointPositions(jts.name[i], &jts.position[i]); collision_result.clear(); current_state.updateCollisionBodyTransforms(); // Do a thread-safe distance-based collision detection collision_request.distance = true; getLockedPlanningSceneRO()->checkCollision(collision_request, collision_result, current_state); collision_distance = collision_result.distance; // Do a binary collision detection (helps with strange edge cases like being in collision initially) collision_request.distance = false; getLockedPlanningSceneRO()->checkCollision(collision_request, collision_result, current_state); // If we're definitely in collision, stop immediately if (collision_result.collision) { velocity_scale = 0; } // If we are far from a collision, velocity_scale should be 1. // If we are very close to a collision, velocity_scale should be ~zero. // When collision_proximity_threshold is breached, start decelerating exponentially. else if (collision_distance < parameters_.collision_proximity_threshold) { // velocity_scale = e ^ k * (collision_distance - threshold) // k = - ln(0.001) / collision_proximity_threshold // velocity_scale should equal one when collision_distance is at collision_proximity_threshold. // velocity_scale should equal 0.001 when collision_distance is at zero. velocity_scale = exp(velocity_scale_coefficient * (collision_distance - parameters_.collision_proximity_threshold)); } shared_variables.lock(); shared_variables.collision_velocity_scale = velocity_scale; shared_variables.unlock(); collision_rate.sleep(); } } void CollisionCheckThread::stopMainLoop() { stop_requested_ = true; } } // namespace moveit_jog_arm <commit_msg>Remove duplicate collision check in JogArm (#1986)<commit_after>/******************************************************************************* * BSD 3-Clause License * * Copyright (c) 2019, Los Alamos National Security, LLC * 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 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. *******************************************************************************/ /* Title : collision_check_thread.cpp * Project : moveit_jog_arm * Created : 1/11/2019 * Author : Brian O'Neil, Andy Zelenak, Blake Anderson */ #include <moveit_jog_arm/collision_check_thread.h> static const std::string LOGNAME = "collision_check_thread"; static const double MIN_RECOMMENDED_COLLISION_RATE = 10; namespace moveit_jog_arm { // Constructor for the class that handles collision checking CollisionCheckThread::CollisionCheckThread( const moveit_jog_arm::JogArmParameters& parameters, const planning_scene_monitor::PlanningSceneMonitorPtr& planning_scene_monitor) : parameters_(parameters), planning_scene_monitor_(planning_scene_monitor) { if (parameters_.collision_check_rate < MIN_RECOMMENDED_COLLISION_RATE) ROS_WARN_STREAM_THROTTLE_NAMED(5, LOGNAME, "Collision check rate is low, increase it in yaml file if CPU allows"); } planning_scene_monitor::LockedPlanningSceneRO CollisionCheckThread::getLockedPlanningSceneRO() const { return planning_scene_monitor::LockedPlanningSceneRO(planning_scene_monitor_); } void CollisionCheckThread::startMainLoop(JogArmShared& shared_variables) { // Reset loop termination flag stop_requested_ = false; // Init collision request collision_detection::CollisionRequest collision_request; collision_request.group_name = parameters_.move_group_name; collision_request.distance = true; // enable distance-based collision checking collision_detection::CollisionResult collision_result; // Copy the planning scene's version of current state into new memory moveit::core::RobotState current_state(getLockedPlanningSceneRO()->getCurrentState()); double velocity_scale_coefficient = -log(0.001) / parameters_.collision_proximity_threshold; ros::Rate collision_rate(parameters_.collision_check_rate); // Scale robot velocity according to collision proximity and user-defined thresholds. // I scaled exponentially (cubic power) so velocity drops off quickly after the threshold. // Proximity decreasing --> decelerate double velocity_scale = 1; ///////////////////////////////////////////////// // Spin while checking collisions ///////////////////////////////////////////////// while (ros::ok() && !stop_requested_) { shared_variables.lock(); sensor_msgs::JointState jts = shared_variables.joints; shared_variables.unlock(); for (std::size_t i = 0; i < jts.position.size(); ++i) current_state.setJointPositions(jts.name[i], &jts.position[i]); collision_result.clear(); current_state.updateCollisionBodyTransforms(); // Do a thread-safe distance-based collision detection getLockedPlanningSceneRO()->checkCollision(collision_request, collision_result, current_state); // If we're definitely in collision, stop immediately if (collision_result.collision) { velocity_scale = 0; } // If we are far from a collision, velocity_scale should be 1. // If we are very close to a collision, velocity_scale should be ~zero. // When collision_proximity_threshold is breached, start decelerating exponentially. else if (collision_result.distance < parameters_.collision_proximity_threshold) { // velocity_scale = e ^ k * (collision_result.distance - threshold) // k = - ln(0.001) / collision_proximity_threshold // velocity_scale should equal one when collision_result.distance is at collision_proximity_threshold. // velocity_scale should equal 0.001 when collision_result.distance is at zero. velocity_scale = exp(velocity_scale_coefficient * (collision_result.distance - parameters_.collision_proximity_threshold)); } shared_variables.lock(); shared_variables.collision_velocity_scale = velocity_scale; shared_variables.unlock(); collision_rate.sleep(); } } void CollisionCheckThread::stopMainLoop() { stop_requested_ = true; } } // namespace moveit_jog_arm <|endoftext|>
<commit_before>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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: Ioan Sucan */ #include <moveit/point_containment_filter/shape_mask.h> #include <geometric_shapes/body_operations.h> #include <ros/console.h> point_containment_filter::ShapeMask::ShapeMask(const TransformCallback& transform_callback) : transform_callback_(transform_callback), next_handle_ (1), min_handle_ (1) { } point_containment_filter::ShapeMask::~ShapeMask() { freeMemory(); } void point_containment_filter::ShapeMask::freeMemory() { for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) delete it->body; bodies_.clear(); } point_containment_filter::ShapeHandle point_containment_filter::ShapeMask::addShape(const shapes::ShapeConstPtr &shape, double scale, double padding) { SeeShape ss; ss.body = bodies::createBodyFromShape(shape.get()); if (ss.body) { ss.body->setScale(scale); ss.body->setPadding(padding); ss.volume = ss.body->computeVolume(); ss.handle = next_handle_; used_handles_[next_handle_] = bodies_.insert(ss).first; } else return 0; ShapeHandle ret = next_handle_; const std::size_t sz = min_handle_ + bodies_.size() + 1; for (std::size_t i = min_handle_ ; i < sz ; ++i) if (used_handles_.find(i) == used_handles_.end()) { next_handle_ = i; break; } min_handle_ = next_handle_; return ret; } void point_containment_filter::ShapeMask::removeShape(ShapeHandle handle) { std::map<ShapeHandle, std::set<SeeShape, SortBodies>::iterator>::iterator it = used_handles_.find(handle); if (it != used_handles_.end()) { delete it->second->body; bodies_.erase(it->second); used_handles_.erase(it); min_handle_ = handle; } } void point_containment_filter::ShapeMask::maskContainment(const pcl::PointCloud<pcl::PointXYZ>& data_in, const Eigen::Vector3d &sensor_origin, const double min_sensor_dist, const double max_sensor_dist, std::vector<int> &mask) { mask.resize(data_in.points.size()); if (bodies_.empty()) std::fill(mask.begin(), mask.end(), (int)OUTSIDE); else { Eigen::Affine3d tmp; bspheres_.resize(bodies_.size()); std::size_t j = 0; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) { if (transform_callback_(it->handle, tmp)) { it->body->setPose(tmp); it->body->computeBoundingSphere(bspheres_[j++]); } } const unsigned int np = data_in.points.size(); // compute a sphere that bounds the entire robot bodies::BoundingSphere bound; bodies::mergeBoundingSpheres(bspheres_, bound); const double radiusSquared = bound.radius * bound.radius; // we now decide which points we keep #pragma omp parallel for schedule(dynamic) for (int i = 0 ; i < (int)np ; ++i) { Eigen::Vector3d pt = Eigen::Vector3d(data_in.points[i].x, data_in.points[i].y, data_in.points[i].z); int out = OUTSIDE; if ((bound.center - pt).squaredNorm() < radiusSquared) { double d = (sensor_origin - pt).norm(); if (d < min_sensor_dist || d > max_sensor_dist) { out = CLIP; } else for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) { if (it->body->containsPoint(pt)) { out = INSIDE; } } } mask[i] = out; } } } int point_containment_filter::ShapeMask::getMaskContainment(const Eigen::Vector3d &pt) const { int out = OUTSIDE; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; return out; } int point_containment_filter::ShapeMask::getMaskContainment(double x, double y, double z) const { return getMaskContainment(Eigen::Vector3d(x, y, z)); } <commit_msg>add forgotten function<commit_after>/* * Copyright (c) 2008, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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: Ioan Sucan */ #include <moveit/point_containment_filter/shape_mask.h> #include <geometric_shapes/body_operations.h> #include <ros/console.h> point_containment_filter::ShapeMask::ShapeMask(const TransformCallback& transform_callback) : transform_callback_(transform_callback), next_handle_ (1), min_handle_ (1) { } point_containment_filter::ShapeMask::~ShapeMask() { freeMemory(); } void point_containment_filter::ShapeMask::freeMemory() { for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) delete it->body; bodies_.clear(); } void point_containment_filter::ShapeMask::setTransformCallback(const TransformCallback& transform_callback) { transform_callback_ = transform_callback; } point_containment_filter::ShapeHandle point_containment_filter::ShapeMask::addShape(const shapes::ShapeConstPtr &shape, double scale, double padding) { SeeShape ss; ss.body = bodies::createBodyFromShape(shape.get()); if (ss.body) { ss.body->setScale(scale); ss.body->setPadding(padding); ss.volume = ss.body->computeVolume(); ss.handle = next_handle_; used_handles_[next_handle_] = bodies_.insert(ss).first; } else return 0; ShapeHandle ret = next_handle_; const std::size_t sz = min_handle_ + bodies_.size() + 1; for (std::size_t i = min_handle_ ; i < sz ; ++i) if (used_handles_.find(i) == used_handles_.end()) { next_handle_ = i; break; } min_handle_ = next_handle_; return ret; } void point_containment_filter::ShapeMask::removeShape(ShapeHandle handle) { std::map<ShapeHandle, std::set<SeeShape, SortBodies>::iterator>::iterator it = used_handles_.find(handle); if (it != used_handles_.end()) { delete it->second->body; bodies_.erase(it->second); used_handles_.erase(it); min_handle_ = handle; } } void point_containment_filter::ShapeMask::maskContainment(const pcl::PointCloud<pcl::PointXYZ>& data_in, const Eigen::Vector3d &sensor_origin, const double min_sensor_dist, const double max_sensor_dist, std::vector<int> &mask) { mask.resize(data_in.points.size()); if (bodies_.empty()) std::fill(mask.begin(), mask.end(), (int)OUTSIDE); else { Eigen::Affine3d tmp; bspheres_.resize(bodies_.size()); std::size_t j = 0; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() ; ++it) { if (transform_callback_(it->handle, tmp)) { it->body->setPose(tmp); it->body->computeBoundingSphere(bspheres_[j++]); } } const unsigned int np = data_in.points.size(); // compute a sphere that bounds the entire robot bodies::BoundingSphere bound; bodies::mergeBoundingSpheres(bspheres_, bound); const double radiusSquared = bound.radius * bound.radius; // we now decide which points we keep #pragma omp parallel for schedule(dynamic) for (int i = 0 ; i < (int)np ; ++i) { Eigen::Vector3d pt = Eigen::Vector3d(data_in.points[i].x, data_in.points[i].y, data_in.points[i].z); int out = OUTSIDE; if ((bound.center - pt).squaredNorm() < radiusSquared) { double d = (sensor_origin - pt).norm(); if (d < min_sensor_dist || d > max_sensor_dist) { out = CLIP; } else for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) { if (it->body->containsPoint(pt)) { out = INSIDE; } } } mask[i] = out; } } } int point_containment_filter::ShapeMask::getMaskContainment(const Eigen::Vector3d &pt) const { int out = OUTSIDE; for (std::set<SeeShape>::const_iterator it = bodies_.begin() ; it != bodies_.end() && out == OUTSIDE ; ++it) if (it->body->containsPoint(pt)) out = INSIDE; return out; } int point_containment_filter::ShapeMask::getMaskContainment(double x, double y, double z) const { return getMaskContainment(Eigen::Vector3d(x, y, z)); } <|endoftext|>
<commit_before>// File: btBoostDynamicsShapes.hpp #ifndef _btBoostDynamicsShapes_hpp #define _btBoostDynamicsShapes_hpp #include <btBulletDynamicsCommon.h> #include <BulletCollision/CollisionShapes/btBox2dShape.h> #include <BulletCollision/CollisionShapes/btConvex2dShape.h> #include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h> #include <boost/python.hpp> #include "array_helpers.hpp" #include "btBoostLinearMathAlignedObjectArray.hpp" using namespace boost::python; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(chullshape_addPoint_overloads, btConvexHullShape::addPoint, 1, 2) btTransform& (btCompoundShape::*cs_getChildTransformRef)(int) = &btCompoundShape::getChildTransform; btTransform& (btCompoundShape::*cs_getChildTransformConstRef)(int) = &btCompoundShape::getChildTransform; btCollisionShape* (btCompoundShape::*cs_getChildShapeRef)(int) = &btCompoundShape::getChildShape; const btCollisionShape* (btCompoundShape::*cs_getChildShapeConstRef)(int) const = &btCompoundShape::getChildShape; btDbvt* (btCompoundShape::*cs_getDynamicAabbTree)() = &btCompoundShape::getDynamicAabbTree; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(compoundshape_updateChildTransform_overloads, btCompoundShape::updateChildTransform, 2, 3) void cs_removeChildShape(btCompoundShape& cs, btCollisionShape& shape) { return cs.removeChildShape(&shape); } btConvex2dShape* make_btConvex2dShape(btConvexShape& childShape) { return new btConvex2dShape(&childShape); } btConvexShape* (btConvex2dShape::*c2ds_getChildShapeRef)() = &btConvex2dShape::getChildShape; typedef btAlignedObjectArray<btCompoundShapeChild> btCompoundShapeChildArray; void defineShapes() { // Base classes, not for developer use class_<btCollisionShape, boost::noncopyable> ("btCollisionShape", no_init) .def_readonly("polyhedral", &btCollisionShape::isPolyhedral) .def_readonly("convex2d", &btCollisionShape::isConvex2d) .def_readonly("convex", &btCollisionShape::isConvex) .def_readonly("non_moving", &btCollisionShape::isNonMoving) .def_readonly("concave", &btCollisionShape::isConcave) .def_readonly("compound", &btCollisionShape::isCompound) .def_readonly("soft_body", &btCollisionShape::isSoftBody) .def_readonly("infinite", &btCollisionShape::isInfinite) .def_readonly("shape_type", &btCollisionShape::getShapeType) .add_property("margin", &btCollisionShape::getMargin, &btCollisionShape::setMargin) .def("get_aabb", &btCollisionShape::getAabb) .def_readonly("aabb", &btCollisionShape::getAabb) .def("get_bounding_sphere", &btCollisionShape::getBoundingSphere) .def_readonly("angular_motion_disc", &btCollisionShape::getAngularMotionDisc) .def("get_contact_breaking_threshold", &btCollisionShape::getContactBreakingThreshold) .def("calculate_temporal_aabb", &btCollisionShape::calculateTemporalAabb) .add_property("local_scaling", make_function(&btCollisionShape::getLocalScaling, return_value_policy<copy_const_reference>()), &btCollisionShape::setLocalScaling) .def("calculate_local_inertia", &btCollisionShape::calculateLocalInertia) .def("anisotropic_rolling_friction_direction", &btCollisionShape::getAnisotropicRollingFrictionDirection) ; class_<btConvexShape, bases<btCollisionShape>, boost::noncopyable> ("btConvexShape", no_init) .def("local_get_supporting_vertex", &btConvexShape::localGetSupportingVertexWithoutMargin) .def("local_get_supporting_vertex_without_margin_non_virtual", &btConvexShape::localGetSupportVertexWithoutMarginNonVirtual) .def("local_get_support_vertex_non_virtual", &btConvexShape::localGetSupportVertexNonVirtual) .def("get_margin_non_virtual", &btConvexShape::getMarginNonVirtual) .def("get_aabb_non_virtual", &btConvexShape::getAabbNonVirtual) .def("project", &btConvexShape::project) .def("batched_unit_vector_get_supporting_vertex_without_margin", &btConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin) .def("get_aabb_slow", &btConvexShape::getAabbSlow) ; class_<btConvexInternalShape, bases<btConvexShape>, boost::noncopyable> ("btConvexInternalShape", no_init) .add_property("implicit_shape_dimensions", make_function(&btConvexInternalShape::getImplicitShapeDimensions, return_value_policy<copy_const_reference>()), &btConvexInternalShape::setImplicitShapeDimensions) // TODO: wrap setSafeMargin overloads .def_readonly("local_scaling_non_virtual", make_function(&btConvexInternalShape::getLocalScalingNV, return_value_policy<copy_const_reference>())) .def_readonly("margin_non_virtual", make_function(&btConvexInternalShape::getMarginNV, return_value_policy<return_by_value>())) .def_readonly("num_preferred_penetration_directions", &btConvexInternalShape::getNumPreferredPenetrationDirections) .def("get_preferred_penetration_direction", &btConvexInternalShape::getPreferredPenetrationDirection) ; class_<btPolyhedralConvexShape, bases<btConvexInternalShape>, boost::noncopyable> ("btPolyhedralConvexShape", no_init) .def_readonly("num_vertices", &btPolyhedralConvexShape::getNumVertices) .def_readonly("num_edges", &btPolyhedralConvexShape::getNumEdges) .def("get_edge", &btPolyhedralConvexShape::getEdge) .def("get_vertex", &btPolyhedralConvexShape::getVertex) .def_readonly("num_planes", &btPolyhedralConvexShape::getNumPlanes) .def("get_plane", &btPolyhedralConvexShape::getPlane) .def_readonly("is_inside", &btPolyhedralConvexShape::isInside) ; class_<btPolyhedralConvexAabbCachingShape, bases<btPolyhedralConvexShape>, boost::noncopyable> ("btPolyhedralConvexAabbCachingShape", no_init) .def("get_nonvirtual_aabb", &btPolyhedralConvexAabbCachingShape::getNonvirtualAabb) .def("recalc_local_aabb", &btPolyhedralConvexAabbCachingShape::getAabb) ; class_<btConcaveShape, bases<btCollisionShape>, boost::noncopyable> ("btConcaveShape", no_init) ; class_<btTriangleMeshShape, bases<btConcaveShape>, boost::noncopyable> ("btTriangleMeshShape", no_init) ; // End base classes // Some internal data passing classes class_<btCompoundShapeChild>("btCompoundShapeChild") .def(self == other<btCompoundShapeChild>()) .def_readwrite("transform", &btCompoundShapeChild::m_transform) .add_property("child_shape", make_getter(&btCompoundShapeChild::m_childShape, return_value_policy<reference_existing_object>()), make_setter(&btCompoundShapeChild::m_childShape, return_value_policy<reference_existing_object>())) .def_readwrite("child_shape_type", &btCompoundShapeChild::m_childShapeType) .def_readwrite("child_margin", &btCompoundShapeChild::m_childMargin) .add_property("node", make_getter(&btCompoundShapeChild::m_node, return_value_policy<reference_existing_object>()), make_setter(&btCompoundShapeChild::m_node, return_value_policy<reference_existing_object>())) ; class_<btCompoundShapeChildArray>("btCompoundShapeChildArray") .def(init<btCompoundShapeChildArray>()) .def(bt_ref_index_suite<btCompoundShapeChildArray>()) .def("append", &btCompoundShapeChildArray::push_back) ; // End internal data passing // TODO: Add tests class_<btConvexHullShape, bases<btPolyhedralConvexAabbCachingShape> > ("btConvexHullShape") .def("add_point", &btConvexHullShape::addPoint, chullshape_addPoint_overloads()) .def("get_unscaled_points", &btConvexHullShape::getUnscaledPoints_wrap, return_internal_reference<>()) .def("get_scaled_point", &btConvexHullShape::getScaledPoint) .def("get_num_points", &btConvexHullShape::getNumPoints) ; // TODO: Add tests class_<btBox2dShape, bases<btPolyhedralConvexShape> > ("btBox2dShape", init<const btVector3&>()) .def_readonly("half_extents_with_margin", make_function(&btBox2dShape::getHalfExtentsWithMargin, return_value_policy<return_by_value>())) .def_readonly("half_extents_without_margin", make_function(&btBox2dShape::getHalfExtentsWithoutMargin, return_internal_reference<>())) ; // TODO: Add tests class_<btBoxShape, bases<btPolyhedralConvexShape> > ("btBoxShape", init<const btVector3&>()) .def_readonly("half_extents_with_margin", make_function(&btBoxShape::getHalfExtentsWithMargin, return_value_policy<return_by_value>())) .def_readonly("half_extents_without_margin", make_function(&btBoxShape::getHalfExtentsWithoutMargin, return_internal_reference<>())) ; class_<btBvhTriangleMeshShape, bases<btTriangleMeshShape>, boost::noncopyable> ("btBvhTriangleMeshShape", no_init) ; // TODO: Implement - left empty while deciding whether to define and wrap btStridingMeshInterface // TODO: Implement tests class_<btCapsuleShape, bases<btConvexInternalShape> > ("btCapsuleShape", init<btScalar, btScalar>()) .def_readonly("up_axis", &btCapsuleShape::getUpAxis) .def_readonly("radius", &btCapsuleShape::getRadius) .def_readonly("half_height", &btCapsuleShape::getHalfHeight) ; // TODO: Implement tests class_<btCapsuleShapeX, bases<btCapsuleShape> > ("btCapsuleShapeX", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btCapsuleShapeZ, bases<btCapsuleShape> > ("btCapsuleShapeZ", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btCompoundShape, bases<btCollisionShape> > ("btCompoundShape") .def(init<bool>()) .def("add_child_shape", &btCompoundShape::addChildShape) .def("remove_child_shape_by_index", &btCompoundShape::removeChildShapeByIndex) .def("remove_child_shape", cs_removeChildShape) .def_readonly("num_child_shapes", &btCompoundShape::getNumChildShapes) // TODO: Check implementation of // const btCollisionShape* getChildShape(int) const .def("get_child_shape", make_function(cs_getChildShapeRef, return_value_policy<reference_existing_object>())) // TODO: Same goes for this one, but we can't prevent python callers from // modifying internal references, we'd just get a stack dump... .def("get_child_transform", make_function(cs_getChildTransformRef, return_internal_reference<>())) .def("update_child_transform", &btCompoundShape::updateChildTransform, compoundshape_updateChildTransform_overloads()) .def("get_child_list", &btCompoundShape::getChildListRef, return_internal_reference<>()) .def_readonly("children", make_function(&btCompoundShape::getChildListRef, return_internal_reference<>())) .def_readonly("dynamic_aabb_tree", make_function(cs_getDynamicAabbTree, return_value_policy<reference_existing_object>())) .def("create_aabb_from_children", &btCompoundShape::createAabbTreeFromChildren) // TODO: Investigate implementation of calculatePrincipalAxisTransform .def_readonly("update_revision", &btCompoundShape::getUpdateRevision) ; // TODO: Implement tests class_<btConeShape, bases<btConvexInternalShape> > ("btConeShape", init<btScalar, btScalar>()) .def_readonly("radius", &btConeShape::getRadius) .def_readonly("height", &btConeShape::getHeight) .def_readonly("cone_up_index", &btConeShape::getConeUpIndex) ; class_<btConeShapeX, bases<btConeShape> > ("btConeShapeX", init<btScalar, btScalar>()) ; class_<btConeShapeZ, bases<btConeShape> > ("btConeShapeZ", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btConvex2dShape, bases<btConvexShape> > ("btConvex2dShape", no_init) .def("__init__", make_constructor(&make_btConvex2dShape)) .def_readonly("child_shape", make_function(c2ds_getChildShapeRef, return_value_policy<reference_existing_object>())) ; class_<btConvexPointCloudShape, bases<btPolyhedralConvexAabbCachingShape> > ("btConvexPointCloudShape") // NOTE: This does not implement the pointer referencing ctors // or getter/setter methods .def_readonly("num_points", &btConvexPointCloudShape::getNumPoints) .def("get_scaled_point", &btConvexPointCloudShape::getScaledPoint) ; } #endif // _btBoostDynamicsShapes_hpp <commit_msg>Added convex polyhedron.<commit_after>// File: btBoostDynamicsShapes.hpp #ifndef _btBoostDynamicsShapes_hpp #define _btBoostDynamicsShapes_hpp #include <btBulletDynamicsCommon.h> #include <BulletCollision/CollisionShapes/btBox2dShape.h> #include <BulletCollision/CollisionShapes/btConvex2dShape.h> #include <BulletCollision/CollisionShapes/btConvexPointCloudShape.h> #include <BulletCollision/CollisionShapes/btConvexPolyhedron.h> #include <boost/python.hpp> #include "array_helpers.hpp" #include "btBoostLinearMathAlignedObjectArray.hpp" using namespace boost::python; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(chullshape_addPoint_overloads, btConvexHullShape::addPoint, 1, 2) btTransform& (btCompoundShape::*cs_getChildTransformRef)(int) = &btCompoundShape::getChildTransform; btTransform& (btCompoundShape::*cs_getChildTransformConstRef)(int) = &btCompoundShape::getChildTransform; btCollisionShape* (btCompoundShape::*cs_getChildShapeRef)(int) = &btCompoundShape::getChildShape; const btCollisionShape* (btCompoundShape::*cs_getChildShapeConstRef)(int) const = &btCompoundShape::getChildShape; btDbvt* (btCompoundShape::*cs_getDynamicAabbTree)() = &btCompoundShape::getDynamicAabbTree; BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(compoundshape_updateChildTransform_overloads, btCompoundShape::updateChildTransform, 2, 3) void cs_removeChildShape(btCompoundShape& cs, btCollisionShape& shape) { return cs.removeChildShape(&shape); } btConvex2dShape* make_btConvex2dShape(btConvexShape& childShape) { return new btConvex2dShape(&childShape); } btConvexShape* (btConvex2dShape::*c2ds_getChildShapeRef)() = &btConvex2dShape::getChildShape; typedef btAlignedObjectArray<btCompoundShapeChild> btCompoundShapeChildArray; typedef btAlignedObjectArray<btFace> btFaceArray; tuple btConvexPolyhedron_project(btConvexPolyhedron& self, const btTransform& trans, const btVector3& dir, btScalar& minProj, btScalar& maxProj, btVector3& witnesPtMin, btVector3& witnesPtMax) { self.project(trans, dir, minProj, maxProj, witnesPtMin, witnesPtMax); return make_tuple(minProj, maxProj); } void defineShapes() { // Base classes, not for developer use class_<btCollisionShape, boost::noncopyable> ("btCollisionShape", no_init) .def_readonly("polyhedral", &btCollisionShape::isPolyhedral) .def_readonly("convex2d", &btCollisionShape::isConvex2d) .def_readonly("convex", &btCollisionShape::isConvex) .def_readonly("non_moving", &btCollisionShape::isNonMoving) .def_readonly("concave", &btCollisionShape::isConcave) .def_readonly("compound", &btCollisionShape::isCompound) .def_readonly("soft_body", &btCollisionShape::isSoftBody) .def_readonly("infinite", &btCollisionShape::isInfinite) .def_readonly("shape_type", &btCollisionShape::getShapeType) .add_property("margin", &btCollisionShape::getMargin, &btCollisionShape::setMargin) .def("get_aabb", &btCollisionShape::getAabb) .def_readonly("aabb", &btCollisionShape::getAabb) .def("get_bounding_sphere", &btCollisionShape::getBoundingSphere) .def_readonly("angular_motion_disc", &btCollisionShape::getAngularMotionDisc) .def("get_contact_breaking_threshold", &btCollisionShape::getContactBreakingThreshold) .def("calculate_temporal_aabb", &btCollisionShape::calculateTemporalAabb) .add_property("local_scaling", make_function(&btCollisionShape::getLocalScaling, return_value_policy<copy_const_reference>()), &btCollisionShape::setLocalScaling) .def("calculate_local_inertia", &btCollisionShape::calculateLocalInertia) .def("anisotropic_rolling_friction_direction", &btCollisionShape::getAnisotropicRollingFrictionDirection) ; class_<btConvexShape, bases<btCollisionShape>, boost::noncopyable> ("btConvexShape", no_init) .def("local_get_supporting_vertex", &btConvexShape::localGetSupportingVertexWithoutMargin) .def("local_get_supporting_vertex_without_margin_non_virtual", &btConvexShape::localGetSupportVertexWithoutMarginNonVirtual) .def("local_get_support_vertex_non_virtual", &btConvexShape::localGetSupportVertexNonVirtual) .def("get_margin_non_virtual", &btConvexShape::getMarginNonVirtual) .def("get_aabb_non_virtual", &btConvexShape::getAabbNonVirtual) .def("project", &btConvexShape::project) .def("batched_unit_vector_get_supporting_vertex_without_margin", &btConvexShape::batchedUnitVectorGetSupportingVertexWithoutMargin) .def("get_aabb_slow", &btConvexShape::getAabbSlow) ; class_<btConvexInternalShape, bases<btConvexShape>, boost::noncopyable> ("btConvexInternalShape", no_init) .add_property("implicit_shape_dimensions", make_function(&btConvexInternalShape::getImplicitShapeDimensions, return_value_policy<copy_const_reference>()), &btConvexInternalShape::setImplicitShapeDimensions) // TODO: wrap setSafeMargin overloads .def_readonly("local_scaling_non_virtual", make_function(&btConvexInternalShape::getLocalScalingNV, return_value_policy<copy_const_reference>())) .def_readonly("margin_non_virtual", make_function(&btConvexInternalShape::getMarginNV, return_value_policy<return_by_value>())) .def_readonly("num_preferred_penetration_directions", &btConvexInternalShape::getNumPreferredPenetrationDirections) .def("get_preferred_penetration_direction", &btConvexInternalShape::getPreferredPenetrationDirection) ; class_<btPolyhedralConvexShape, bases<btConvexInternalShape>, boost::noncopyable> ("btPolyhedralConvexShape", no_init) .def_readonly("num_vertices", &btPolyhedralConvexShape::getNumVertices) .def_readonly("num_edges", &btPolyhedralConvexShape::getNumEdges) .def("get_edge", &btPolyhedralConvexShape::getEdge) .def("get_vertex", &btPolyhedralConvexShape::getVertex) .def_readonly("num_planes", &btPolyhedralConvexShape::getNumPlanes) .def("get_plane", &btPolyhedralConvexShape::getPlane) .def_readonly("is_inside", &btPolyhedralConvexShape::isInside) ; class_<btPolyhedralConvexAabbCachingShape, bases<btPolyhedralConvexShape>, boost::noncopyable> ("btPolyhedralConvexAabbCachingShape", no_init) .def("get_nonvirtual_aabb", &btPolyhedralConvexAabbCachingShape::getNonvirtualAabb) .def("recalc_local_aabb", &btPolyhedralConvexAabbCachingShape::getAabb) ; class_<btConcaveShape, bases<btCollisionShape>, boost::noncopyable> ("btConcaveShape", no_init) ; class_<btTriangleMeshShape, bases<btConcaveShape>, boost::noncopyable> ("btTriangleMeshShape", no_init) ; // End base classes // Some internal data passing classes class_<btCompoundShapeChild>("btCompoundShapeChild") .def(self == other<btCompoundShapeChild>()) .def_readwrite("transform", &btCompoundShapeChild::m_transform) .add_property("child_shape", make_getter(&btCompoundShapeChild::m_childShape, return_value_policy<reference_existing_object>()), make_setter(&btCompoundShapeChild::m_childShape, return_value_policy<reference_existing_object>())) .def_readwrite("child_shape_type", &btCompoundShapeChild::m_childShapeType) .def_readwrite("child_margin", &btCompoundShapeChild::m_childMargin) .add_property("node", make_getter(&btCompoundShapeChild::m_node, return_value_policy<reference_existing_object>()), make_setter(&btCompoundShapeChild::m_node, return_value_policy<reference_existing_object>())) ; class_<btCompoundShapeChildArray>("btCompoundShapeChildArray") .def(init<btCompoundShapeChildArray>()) .def(bt_ref_index_suite<btCompoundShapeChildArray>()) .def("append", &btCompoundShapeChildArray::push_back) ; // End internal data passing // TODO: Add tests class_<btConvexHullShape, bases<btPolyhedralConvexAabbCachingShape> > ("btConvexHullShape") .def("add_point", &btConvexHullShape::addPoint, chullshape_addPoint_overloads()) .def("get_unscaled_points", &btConvexHullShape::getUnscaledPoints_wrap, return_internal_reference<>()) .def("get_scaled_point", &btConvexHullShape::getScaledPoint) .def("get_num_points", &btConvexHullShape::getNumPoints) ; // TODO: Add tests class_<btBox2dShape, bases<btPolyhedralConvexShape> > ("btBox2dShape", init<const btVector3&>()) .def_readonly("half_extents_with_margin", make_function(&btBox2dShape::getHalfExtentsWithMargin, return_value_policy<return_by_value>())) .def_readonly("half_extents_without_margin", make_function(&btBox2dShape::getHalfExtentsWithoutMargin, return_internal_reference<>())) ; // TODO: Add tests class_<btBoxShape, bases<btPolyhedralConvexShape> > ("btBoxShape", init<const btVector3&>()) .def_readonly("half_extents_with_margin", make_function(&btBoxShape::getHalfExtentsWithMargin, return_value_policy<return_by_value>())) .def_readonly("half_extents_without_margin", make_function(&btBoxShape::getHalfExtentsWithoutMargin, return_internal_reference<>())) ; class_<btBvhTriangleMeshShape, bases<btTriangleMeshShape>, boost::noncopyable> ("btBvhTriangleMeshShape", no_init) ; // TODO: Implement - left empty while deciding whether to define and wrap btStridingMeshInterface // TODO: Implement tests class_<btCapsuleShape, bases<btConvexInternalShape> > ("btCapsuleShape", init<btScalar, btScalar>()) .def_readonly("up_axis", &btCapsuleShape::getUpAxis) .def_readonly("radius", &btCapsuleShape::getRadius) .def_readonly("half_height", &btCapsuleShape::getHalfHeight) ; // TODO: Implement tests class_<btCapsuleShapeX, bases<btCapsuleShape> > ("btCapsuleShapeX", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btCapsuleShapeZ, bases<btCapsuleShape> > ("btCapsuleShapeZ", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btCompoundShape, bases<btCollisionShape> > ("btCompoundShape") .def(init<bool>()) .def("add_child_shape", &btCompoundShape::addChildShape) .def("remove_child_shape_by_index", &btCompoundShape::removeChildShapeByIndex) .def("remove_child_shape", cs_removeChildShape) .def_readonly("num_child_shapes", &btCompoundShape::getNumChildShapes) // TODO: Check implementation of // const btCollisionShape* getChildShape(int) const .def("get_child_shape", make_function(cs_getChildShapeRef, return_value_policy<reference_existing_object>())) // TODO: Same goes for this one, but we can't prevent python callers from // modifying internal references, we'd just get a stack dump... .def("get_child_transform", make_function(cs_getChildTransformRef, return_internal_reference<>())) .def("update_child_transform", &btCompoundShape::updateChildTransform, compoundshape_updateChildTransform_overloads()) .def("get_child_list", &btCompoundShape::getChildListRef, return_internal_reference<>()) .def_readonly("children", make_function(&btCompoundShape::getChildListRef, return_internal_reference<>())) .def_readonly("dynamic_aabb_tree", make_function(cs_getDynamicAabbTree, return_value_policy<reference_existing_object>())) .def("create_aabb_from_children", &btCompoundShape::createAabbTreeFromChildren) // TODO: Investigate implementation of calculatePrincipalAxisTransform .def_readonly("update_revision", &btCompoundShape::getUpdateRevision) ; // TODO: Implement tests class_<btConeShape, bases<btConvexInternalShape> > ("btConeShape", init<btScalar, btScalar>()) .def_readonly("radius", &btConeShape::getRadius) .def_readonly("height", &btConeShape::getHeight) .def_readonly("cone_up_index", &btConeShape::getConeUpIndex) ; class_<btConeShapeX, bases<btConeShape> > ("btConeShapeX", init<btScalar, btScalar>()) ; class_<btConeShapeZ, bases<btConeShape> > ("btConeShapeZ", init<btScalar, btScalar>()) ; // TODO: Implement tests class_<btConvex2dShape, bases<btConvexShape> > ("btConvex2dShape", no_init) .def("__init__", make_constructor(&make_btConvex2dShape)) .def_readonly("child_shape", make_function(c2ds_getChildShapeRef, return_value_policy<reference_existing_object>())) ; // TODO: Implement tests class_<btConvexPointCloudShape, bases<btPolyhedralConvexAabbCachingShape> > ("btConvexPointCloudShape") // NOTE: This does not implement the pointer referencing ctors // or getter/setter methods .def_readonly("num_points", &btConvexPointCloudShape::getNumPoints) .def("get_scaled_point", &btConvexPointCloudShape::getScaledPoint) ; // TODO: Implement tests class_<btConvexPolyhedron> ("btConvexPolyhedron") .def_readwrite("vertices", &btConvexPolyhedron::m_vertices) .def_readwrite("faces", &btConvexPolyhedron::m_faces) .def_readwrite("unique_edges", &btConvexPolyhedron::m_uniqueEdges) .def_readwrite("local_center", &btConvexPolyhedron::m_localCenter) .def_readwrite("extents", &btConvexPolyhedron::m_extents) .def_readwrite("radius", &btConvexPolyhedron::m_radius) .def_readwrite("mC", &btConvexPolyhedron::mC) .def_readwrite("mE", &btConvexPolyhedron::mE) .def("initialize", &btConvexPolyhedron::initialize) .def("test_containment", &btConvexPolyhedron::testContainment) .def("project", &btConvexPolyhedron_project) ; } #endif // _btBoostDynamicsShapes_hpp <|endoftext|>
<commit_before>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2012, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2012, MAPIR group, University of Malaga | | Copyright (c) 2012, University of Almeria | | 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 HOLDERS 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 <mrpt/base.h> // Precompiled headers #include <mrpt/utils/CTimeLogger.h> #include <mrpt/utils/CFileOutputStream.h> #include <mrpt/system/string_utils.h> using namespace mrpt; using namespace mrpt::utils; using namespace mrpt::system; using namespace std; CTimeLogger mrpt::utils::global_profiler; namespace mrpt { namespace utils { void global_profiler_enter(const char *func_name) MRPT_NO_THROWS { global_profiler.enter(func_name); } void global_profiler_leave(const char *func_name) MRPT_NO_THROWS { global_profiler.leave(func_name); } } } CTimeLogger::CTimeLogger(bool enabled) : m_tictac(), m_enabled(enabled) { m_tictac.Tic(); } CTimeLogger::~CTimeLogger() { // Dump all stats: if (!m_data.empty()) // If logging is disabled, do nothing... dumpAllStats(); } void CTimeLogger::clear(bool deep_clear) { if (deep_clear) m_data.clear(); else { for (map<string,TCallData>::iterator i=m_data.begin();i!=m_data.end();++i) i->second = TCallData(); } } std::string aux_format_string_multilines(const std::string &s, const size_t len) { std::string ret; for (size_t p=0;p<s.size();p+=len) { ret+=rightPad(s.c_str()+p,len,true); if (p+len<s.size()) ret+="\n"; } return ret; } void CTimeLogger::getStats(std::map<std::string,TCallStats> &out_stats) const { out_stats.clear(); for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { TCallStats &cs = out_stats[i->first]; cs.min_t = i->second.min_t; cs.max_t = i->second.max_t; cs.total_t = i->second.mean_t; cs.mean_t = i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0; cs.n_calls = i->second.n_calls; } } std::string CTimeLogger::getStatsAsText(const size_t column_width) const { std::string s; s+="--------------------------- MRPT CTimeLogger report --------------------------\n"; s+=" FUNCTION #CALLS MIN.T MEAN.T MAX.T TOTAL \n"; s+="------------------------------------------------------------------------------\n"; for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { const string sMinT = unitsFormat(i->second.min_t,1,false); const string sMaxT = unitsFormat(i->second.max_t,1,false); const string sTotalT = unitsFormat(i->second.mean_t,1,false); const string sMeanT = unitsFormat(i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0,1,false); s+=format("%s %7u %6ss %6ss %6ss %6ss\n", aux_format_string_multilines(i->first,40).c_str(), static_cast<unsigned int>(i->second.n_calls), sMinT.c_str(), sMeanT.c_str(), sMaxT.c_str(), sTotalT.c_str() ); } s+="---------------------- End of MRPT CTimeLogger report ------------------------\n"; return s; } void CTimeLogger::saveToCSVFile(const std::string &csv_file) const { std::string s; s+="FUNCTION, #CALLS, MIN.T, MEAN.T, MAX.T, TOTAL.T\n"; for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { s+=format("\"%s\",\"%7u\",\"%e\",\"%e\",\"%e\",\"%e\"\n", i->first.c_str(), static_cast<unsigned int>(i->second.n_calls), i->second.min_t, i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0, i->second.max_t, i->second.mean_t ); } CFileOutputStream(csv_file).printf("%s",s.c_str() ); } void CTimeLogger::dumpAllStats(const size_t column_width) const { string s = getStatsAsText(column_width); printf_debug("\n%s\n", s.c_str() ); } void CTimeLogger::do_enter(const char *func_name) { const string s = func_name; TCallData &d = m_data[s]; d.n_calls++; d.open_calls.push(0); // Dummy value, it'll be written below d.open_calls.top() = m_tictac.Tac(); // to avoid possible delays. } double CTimeLogger::do_leave(const char *func_name) { const double tim = m_tictac.Tac(); const string s = func_name; TCallData &d = m_data[s]; if (!d.open_calls.empty()) { const double At = tim - d.open_calls.top(); d.open_calls.pop(); d.mean_t+=At; if (d.n_calls==1) { d.min_t= At; d.max_t= At; } else { mrpt::utils::keep_min( d.min_t, At); mrpt::utils::keep_max( d.max_t, At); } return At; } else return 0; // This shouldn't happen! } CTimeLogger::TCallData::TCallData() : n_calls (0), min_t (0), max_t (0), mean_t (0) { } double CTimeLogger::getMeanTime(const std::string &name) const { map<string,TCallData>::const_iterator it = m_data.find(name); if (it==m_data.end()) return 0; else return it->second.n_calls ? it->second.mean_t/it->second.n_calls : 0; } <commit_msg>minor formating fix in CTimeLogger output<commit_after>/* +---------------------------------------------------------------------------+ | The Mobile Robot Programming Toolkit (MRPT) | | | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2012, Individual contributors, see AUTHORS file | | Copyright (c) 2005-2012, MAPIR group, University of Malaga | | Copyright (c) 2012, University of Almeria | | 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 HOLDERS 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 <mrpt/base.h> // Precompiled headers #include <mrpt/utils/CTimeLogger.h> #include <mrpt/utils/CFileOutputStream.h> #include <mrpt/system/string_utils.h> using namespace mrpt; using namespace mrpt::utils; using namespace mrpt::system; using namespace std; CTimeLogger mrpt::utils::global_profiler; namespace mrpt { namespace utils { void global_profiler_enter(const char *func_name) MRPT_NO_THROWS { global_profiler.enter(func_name); } void global_profiler_leave(const char *func_name) MRPT_NO_THROWS { global_profiler.leave(func_name); } } } CTimeLogger::CTimeLogger(bool enabled) : m_tictac(), m_enabled(enabled) { m_tictac.Tic(); } CTimeLogger::~CTimeLogger() { // Dump all stats: if (!m_data.empty()) // If logging is disabled, do nothing... dumpAllStats(); } void CTimeLogger::clear(bool deep_clear) { if (deep_clear) m_data.clear(); else { for (map<string,TCallData>::iterator i=m_data.begin();i!=m_data.end();++i) i->second = TCallData(); } } std::string aux_format_string_multilines(const std::string &s, const size_t len) { std::string ret; for (size_t p=0;p<s.size();p+=len) { ret+=rightPad(s.c_str()+p,len,true); if (p+len<s.size()) ret+="\n"; } return ret; } void CTimeLogger::getStats(std::map<std::string,TCallStats> &out_stats) const { out_stats.clear(); for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { TCallStats &cs = out_stats[i->first]; cs.min_t = i->second.min_t; cs.max_t = i->second.max_t; cs.total_t = i->second.mean_t; cs.mean_t = i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0; cs.n_calls = i->second.n_calls; } } std::string CTimeLogger::getStatsAsText(const size_t column_width) const { std::string s; s+="--------------------------- MRPT CTimeLogger report --------------------------\n"; s+=" FUNCTION #CALLS MIN.T MEAN.T MAX.T TOTAL \n"; s+="------------------------------------------------------------------------------\n"; for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { const string sMinT = unitsFormat(i->second.min_t,1,false); const string sMaxT = unitsFormat(i->second.max_t,1,false); const string sTotalT = unitsFormat(i->second.mean_t,1,false); const string sMeanT = unitsFormat(i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0,1,false); s+=format("%s %7u %6ss %6ss %6ss %6ss\n", aux_format_string_multilines(i->first,39).c_str(), static_cast<unsigned int>(i->second.n_calls), sMinT.c_str(), sMeanT.c_str(), sMaxT.c_str(), sTotalT.c_str() ); } s+="---------------------- End of MRPT CTimeLogger report ------------------------\n"; return s; } void CTimeLogger::saveToCSVFile(const std::string &csv_file) const { std::string s; s+="FUNCTION, #CALLS, MIN.T, MEAN.T, MAX.T, TOTAL.T\n"; for (map<string,TCallData>::const_iterator i=m_data.begin();i!=m_data.end();++i) { s+=format("\"%s\",\"%7u\",\"%e\",\"%e\",\"%e\",\"%e\"\n", i->first.c_str(), static_cast<unsigned int>(i->second.n_calls), i->second.min_t, i->second.n_calls ? i->second.mean_t/i->second.n_calls : 0, i->second.max_t, i->second.mean_t ); } CFileOutputStream(csv_file).printf("%s",s.c_str() ); } void CTimeLogger::dumpAllStats(const size_t column_width) const { string s = getStatsAsText(column_width); printf_debug("\n%s\n", s.c_str() ); } void CTimeLogger::do_enter(const char *func_name) { const string s = func_name; TCallData &d = m_data[s]; d.n_calls++; d.open_calls.push(0); // Dummy value, it'll be written below d.open_calls.top() = m_tictac.Tac(); // to avoid possible delays. } double CTimeLogger::do_leave(const char *func_name) { const double tim = m_tictac.Tac(); const string s = func_name; TCallData &d = m_data[s]; if (!d.open_calls.empty()) { const double At = tim - d.open_calls.top(); d.open_calls.pop(); d.mean_t+=At; if (d.n_calls==1) { d.min_t= At; d.max_t= At; } else { mrpt::utils::keep_min( d.min_t, At); mrpt::utils::keep_max( d.max_t, At); } return At; } else return 0; // This shouldn't happen! } CTimeLogger::TCallData::TCallData() : n_calls (0), min_t (0), max_t (0), mean_t (0) { } double CTimeLogger::getMeanTime(const std::string &name) const { map<string,TCallData>::const_iterator it = m_data.find(name); if (it==m_data.end()) return 0; else return it->second.n_calls ? it->second.mean_t/it->second.n_calls : 0; } <|endoftext|>
<commit_before><commit_msg>gltfio: clean up finalize().<commit_after><|endoftext|>
<commit_before>#include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal_priv.h> #include <cpl_conv.h> #include <ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile_id>" << endl; return 1;} string tile_id = argv[1]; // carbon pools string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string deadc_name = tile_id + "_deadwood.tif"; string soilc_name = tile_id + "_soil.tif"; string litterc_name = tile_id + "_litter.tif"; // aux data string lossyear_name = tile_id + "_loss.tif"; string lossclass_name = tile_id + "_res_forest_model.tif"; string peatdran_name = tile_id + "_res_peatdrainage.tif"; string hist_name = tile_id + "_res_hwsd_histosoles.tif"; string climate_name = tile_id + "_res_climate_zone.tif"; string ecozone_name = tile_id + "_res_fao_ecozones_bor_tem_tro.tif"; // set output file name string out_wildfire_name = tile_id + "_wildfire.tif"; string out_forestry_name = tile_id + "_forestry.tif"; string out_conversion_name = tile_id + "_conversion.tif"; //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; GDALDataset *INGDAL6; GDALRasterBand *INBAND6; //loss GDALDataset *INGDAL7; GDALRasterBand *INBAND7; // lossclass GDALDataset *INGDAL8; GDALRasterBand *INBAND8; // peatdran GDALDataset *INGDAL9; GDALRasterBand *INBAND9; // histosoles GDALDataset *INGDAL10; GDALRasterBand *INBAND10; // climate GDALDataset *INGDAL11; GDALRasterBand *INBAND11; // eco zone //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); xsize=INBAND->GetXSize(); ysize=INBAND->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; INGDAL2 = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(deadc_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(litterc_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(soilc_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); INGDAL6 = (GDALDataset *) GDALOpen(lossyear_name.c_str(), GA_ReadOnly ); INBAND6 = INGDAL6->GetRasterBand(1); INGDAL7 = (GDALDataset *) GDALOpen(lossclass_name.c_str(), GA_ReadOnly ); INBAND7 = INGDAL7->GetRasterBand(1); INGDAL8 = (GDALDataset *) GDALOpen(peatdran_name.c_str(), GA_ReadOnly ); INBAND8 = INGDAL8->GetRasterBand(1); INGDAL9 = (GDALDataset *) GDALOpen(hist_name.c_str(), GA_ReadOnly ); INBAND9 = INGDAL9->GetRasterBand(1); INGDAL10 = (GDALDataset *) GDALOpen(climate_name.c_str(), GA_ReadOnly ); INBAND10 = INGDAL10->GetRasterBand(1); INGDAL11 = (GDALDataset *) GDALOpen(ecozone_name.c_str(), GA_ReadOnly ); INBAND11 = INGDAL11->GetRasterBand(1); //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALDataset *OUTGDAL2; GDALDataset *OUTGDAL3; GDALRasterBand *OUTBAND1; GDALRasterBand *OUTBAND2; GDALRasterBand *OUTBAND3; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_wildfire_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); OUTGDAL2 = OUTDRIVER->Create( out_forestry_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ); OUTBAND2 = OUTGDAL2->GetRasterBand(1); OUTBAND2->SetNoDataValue(-9999); OUTGDAL3 = OUTDRIVER->Create( out_conversion_name.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL3->SetGeoTransform(adfGeoTransform); OUTGDAL3->SetProjection(OUTPRJ); OUTBAND3 = OUTGDAL3->GetRasterBand(1); OUTBAND3->SetNoDataValue(-9999); //read/write data float bgc_data[xsize]; float agc_data[xsize]; float deadc_data[xsize]; float litterc_data[xsize]; float soilc_data[xsize]; float loss_data[xsize]; float lossclass_data[xsize]; float peatdran_data[xsize]; float hist_data[xsize]; float climate_data[xsize]; float ecozone_data[xsize]; float out_wildfire_data[xsize]; float out_forestry_data[xsize]; float out_conversion_data[xsize]; for(y=0; y<4; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, deadc_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, litterc_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, soilc_data, xsize, 1, GDT_Float32, 0, 0); INBAND6->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND7->RasterIO(GF_Read, 0, y, xsize, 1, lossclass_data, xsize, 1, GDT_Float32, 0, 0); INBAND8->RasterIO(GF_Read, 0, y, xsize, 1, peatdran_data, xsize, 1, GDT_Float32, 0, 0); INBAND9->RasterIO(GF_Read, 0, y, xsize, 1, hist_data, xsize, 1, GDT_Float32, 0, 0); INBAND10->RasterIO(GF_Read, 0, y, xsize, 1, climate_data, xsize, 1, GDT_Float32, 0, 0); INBAND11->RasterIO(GF_Read, 0, y, xsize, 1, ecozone_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { if (loss_data[x] > 0) { if (lossclass_data[x] = 1) // forestry { if (peatdran_data[x] != 0) // on peat { if (peatdran_data[x] != 0) // change to burned areas once I get the data { cout << "on peat drainage: "; out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]) + 917; // qc'd this with 10N_100E - passed cout << out_forestry_data[x] << "\n"; } else { out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peatdran_data[x]); } } else { if (hist_data[x] != 0) // on histosoles { if (ecozone_data[x] = 1) // tropics { out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 55); } if (ecozone_data[x] = 2) // boreal { out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 2.16); } if (ecozone_data[x] = 3) // temperate { out_forestry_data[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * 6.27); } } else // not on peat, not on histosoles { out_forestry_data[x] = -9999; } } } if (lossclass_data[x] = 2) // conversion { if (peatdran_data[x] != 0) // on peat { if (peatdran_data[x] != 0) // change to burned areas once I get the data { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (15 - loss_data[x] * peatdran_data[x]) + 917; } else // not on burned areas { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (15 - loss_data[x] * peatdran_data[x]); } } else // not on peat { if (hist_data[x] != 0) // on histosoles { if ((ecozone_data[x] = 2) || (ecozone_data[x] = 3)) // boreal or temperate { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + 29; } if (ecozone_data[x] = 1) // tropics { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + 55; } } else // not on histosoles { if ((climate_data[x] = 2) || (climate_data[x] = 4) || (climate_data[x] = 8)) // warm/cool temperate/boreal dry { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.8)) * 3.67; } if ((climate_data[x] = 1) || (climate_data[x] = 3) || (climate_data[x] = 7)) // warm/cool temperate/boreal moist { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.69)) * 3.67; } if (climate_data[x] = 12) // tropical dry { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.58)) * 3.67; } if ((climate_data[x] = 10) || (climate_data[x] = 11)) // tropical moist/wet { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.48)) * 3.67; } if (climate_data[x] = 9) // tropical montane { out_conversion_data[x] = ((agc_data[x] + bgc_data[x] + deadc_data[x] + litterc_data[xsize]) -5) * 3.67 + (soilc_data[xsize] - (soilc_data[xsize] * 0.64)) * 3.67; } } } } } else { out_forestry_data[x] = -9999; } //closes for x loop } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_forestry_data, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_wildfire_data, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND3->RasterIO( GF_Write, 0, y, xsize, 1, out_conversion_data, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); return 0; } <commit_msg>success in testing if forest class = 1 but with some dummy data for peat<commit_after> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <fstream> #include <sys/stat.h> #include <math.h> #include <algorithm> #include <string.h> #include <stdint.h> #include <sstream> #include <iomanip> #include <gdal/gdal_priv.h> #include <gdal/cpl_conv.h> #include <gdal/ogr_spatialref.h> using namespace std; //to compile: c++ raster_math.cpp -o raster_math -lgdal // ./dead_wood_c_stock.exe 00N_000E_biomass.tif 00N_000E_res_ecozone.tif 00N_000E_res_srtm.tif 00N_000E_res_srtm.tif test.tif > values.txt int main(int argc, char* argv[]) { //passing arguments if (argc != 2){cout << "Use <program name> <tile id>" << endl; return 1;} string agb_name=argv[1]; string tile_id = argv[1]; string forestmodel_name = tile_id + "_res_forest_model.tif"; string bgc_name = tile_id + "_bgc.tif"; string agc_name = tile_id + "_carbon.tif"; string loss_name = tile_id + "_loss.tif"; string peat_name = tile_id + "_res_peatdrainage.tif"; //either parse this var from inputs or send it in string out_name1="test1.tif"; string out_name2 = "test2.tif"; //setting variables int x, y; int xsize, ysize; double GeoTransform[6]; double ulx, uly; double pixelsize; //initialize GDAL for reading GDALAllRegister(); GDALDataset *INGDAL; GDALRasterBand *INBAND; GDALDataset *INGDAL2; GDALRasterBand *INBAND2; GDALDataset *INGDAL3; GDALRasterBand *INBAND3; GDALDataset *INGDAL4; GDALRasterBand *INBAND4; GDALDataset *INGDAL5; GDALRasterBand *INBAND5; //open file and get extent and projection INGDAL = (GDALDataset *) GDALOpen(agc_name.c_str(), GA_ReadOnly ); INBAND = INGDAL->GetRasterBand(1); INGDAL2 = (GDALDataset *) GDALOpen(bgc_name.c_str(), GA_ReadOnly ); INBAND2 = INGDAL2->GetRasterBand(1); INGDAL3 = (GDALDataset *) GDALOpen(forestmodel_name.c_str(), GA_ReadOnly ); INBAND3 = INGDAL3->GetRasterBand(1); INGDAL4 = (GDALDataset *) GDALOpen(loss_name.c_str(), GA_ReadOnly ); INBAND4 = INGDAL4->GetRasterBand(1); INGDAL5 = (GDALDataset *) GDALOpen(peat_name.c_str(), GA_ReadOnly ); INBAND5 = INGDAL5->GetRasterBand(1); xsize=INBAND->GetXSize(); ysize=INBAND->GetYSize(); INGDAL->GetGeoTransform(GeoTransform); ulx=GeoTransform[0]; uly=GeoTransform[3]; pixelsize=GeoTransform[1]; cout << xsize <<", "<< ysize <<", "<< ulx <<", "<< uly << ", "<< pixelsize << endl; //initialize GDAL for writing GDALDriver *OUTDRIVER; GDALDataset *OUTGDAL; GDALDataset *OUTGDAL2; GDALRasterBand *OUTBAND1; GDALRasterBand *OUTBAND2; OGRSpatialReference oSRS; char *OUTPRJ = NULL; char **papszOptions = NULL; papszOptions = CSLSetNameValue( papszOptions, "COMPRESS", "LZW" ); OUTDRIVER = GetGDALDriverManager()->GetDriverByName("GTIFF"); if( OUTDRIVER == NULL ) {cout << "no driver" << endl; exit( 1 );}; oSRS.SetWellKnownGeogCS( "WGS84" ); oSRS.exportToWkt( &OUTPRJ ); double adfGeoTransform[6] = { ulx, pixelsize, 0, uly, 0, -1*pixelsize }; OUTGDAL = OUTDRIVER->Create( out_name1.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL->SetGeoTransform(adfGeoTransform); OUTGDAL->SetProjection(OUTPRJ); OUTBAND1 = OUTGDAL->GetRasterBand(1); OUTBAND1->SetNoDataValue(-9999); OUTGDAL2 = OUTDRIVER->Create( out_name2.c_str(), xsize, ysize, 1, GDT_Float32, papszOptions ); OUTGDAL2->SetGeoTransform(adfGeoTransform); OUTGDAL2->SetProjection(OUTPRJ); OUTBAND2 = OUTGDAL2->GetRasterBand(1); OUTBAND2->SetNoDataValue(-9999); //read/write data float agb_data[xsize]; float agc_data[xsize]; float bgc_data[xsize]; float loss_data[xsize]; float peat_data[xsize]; float forestmodel_data[xsize]; float out_data1[xsize]; float out_data2[xsize]; for(y=37943; y<37946; y++) { INBAND->RasterIO(GF_Read, 0, y, xsize, 1, agc_data, xsize, 1, GDT_Float32, 0, 0); INBAND2->RasterIO(GF_Read, 0, y, xsize, 1, bgc_data, xsize, 1, GDT_Float32, 0, 0); INBAND3->RasterIO(GF_Read, 0, y, xsize, 1, forestmodel_data, xsize, 1, GDT_Float32, 0, 0); INBAND4->RasterIO(GF_Read, 0, y, xsize, 1, loss_data, xsize, 1, GDT_Float32, 0, 0); INBAND5->RasterIO(GF_Read, 0, y, xsize, 1, peat_data, xsize, 1, GDT_Float32, 0, 0); for(x=0; x<xsize; x++) { if (forestmodel_data[x] == 1) // forestry { cout << "forest model data is 1: " << forestmodel_data[x] << "\n"; if (agc_data[x] == -9999) { cout << "abc data is -9999: " << agc_data[x] << "\n"; out_data1[x] = -9999; } else { if (peat_data[x] = -9999) { cout << "peat data is -9999: " << peat_data[x] << "\n"; peat_data[x] = 0; } out_data1[x] = ((agc_data[x] + bgc_data[x]) * 3.67) + (15 - loss_data[x] * peat_data[x]); cout << "agc: " << agc_data[x] << "\n"; cout << "bgc: " << bgc_data[x] << "\n"; cout << "loss: " << loss_data[x] << "\n"; cout << "peat: " << peat_data[x] << "\n"; cout << "out data: " << out_data1[x] << "\n"; } } else if (forestmodel_data[x] == 2) { cout << "forest model data is 2: " << forestmodel_data[x] << "\n"; out_data2[x] = 2; } else { cout << "forest model data is not 1 or 2: " << forestmodel_data[x] << "\n"; out_data2[x] = -9999; } } OUTBAND1->RasterIO( GF_Write, 0, y, xsize, 1, out_data1, xsize, 1, GDT_Float32, 0, 0 ); OUTBAND2->RasterIO( GF_Write, 0, y, xsize, 1, out_data2, xsize, 1, GDT_Float32, 0, 0 ); //closes for y loop } //close GDAL GDALClose(INGDAL); GDALClose((GDALDatasetH)OUTGDAL); GDALClose((GDALDatasetH)OUTGDAL2); return 0; } <|endoftext|>
<commit_before>// bdlqq_recursivemuteximpl_pthread.cpp -*-C++-*- #include <bdlqq_recursivemuteximpl_pthread.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlqq_recursivemuteximpl_pthread_cpp,"$Id$ $CSID$") #ifdef BDLQQ_PLATFORM_POSIX_THREADS namespace BloombergLP { // ------------------------------------------------ // class RecursiveMutexImpl<Platform::PosixThreads> // ------------------------------------------------ // CREATORS bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::RecursiveMutexImpl() : d_spin(bsls::SpinLock::s_unlocked) { pthread_mutexattr_t attribute; pthread_mutexattr_init(&attribute); #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutexattr_settype(&attribute,PTHREAD_MUTEX_RECURSIVE); #else d_lockCount = 0; #endif pthread_mutex_init(&d_lock, &attribute); pthread_mutexattr_destroy(&attribute); } // MANIPULATORS void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::lock() { #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutex_lock(&d_lock); #else if (pthread_mutex_trylock(&d_lock)) { d_spin.lock(); if (d_lockCount && pthread_equal(d_owner,pthread_self())) { ++d_lockCount; d_spin.unlock(); return; // RETURN } d_spin.unlock(); pthread_mutex_lock(&d_lock); } d_spin.lock(); d_owner = pthread_self(); d_lockCount = 1; d_spin.unlock(); #endif } int bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::tryLock() { #ifdef PTHREAD_MUTEX_RECURSIVE return pthread_mutex_trylock(&d_lock); // RETURN #else if (pthread_mutex_trylock(&d_lock)) { d_spin.lock(); if (d_lockCount && pthread_equal(d_owner,pthread_self())) { ++d_lockCount; d_spin.unlock(); return 0; // RETURN } else { d_spin.unlock(); return 1; // RETURN } } else { d_spin.lock(); d_owner = pthread_self(); d_lockCount = 1; d_spin.unlock(); return 0; // RETURN } #endif } void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::unlock() { #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutex_unlock(&d_lock); #else d_spin.lock(); if (!--d_lockCount) { d_spin.unlock(); pthread_mutex_unlock(&d_lock); return; // RETURN } d_spin.unlock(); #endif } } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <commit_msg>bdlqq_recursivemuteximpl_pthread: complining on aix<commit_after>// bdlqq_recursivemuteximpl_pthread.cpp -*-C++-*- #include <bdlqq_recursivemuteximpl_pthread.h> #include <bsls_ident.h> BSLS_IDENT_RCSID(bdlqq_recursivemuteximpl_pthread_cpp,"$Id$ $CSID$") #ifdef BDLQQ_PLATFORM_POSIX_THREADS namespace BloombergLP { // ------------------------------------------------ // class RecursiveMutexImpl<Platform::PosixThreads> // ------------------------------------------------ // CREATORS bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::RecursiveMutexImpl() #ifndef PTHREAD_MUTEX_RECURSIVE : d_spin(bsls::SpinLock::s_unlocked) #endif { pthread_mutexattr_t attribute; pthread_mutexattr_init(&attribute); #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutexattr_settype(&attribute,PTHREAD_MUTEX_RECURSIVE); #else d_lockCount = 0; #endif pthread_mutex_init(&d_lock, &attribute); pthread_mutexattr_destroy(&attribute); } // MANIPULATORS void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::lock() { #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutex_lock(&d_lock); #else if (pthread_mutex_trylock(&d_lock)) { d_spin.lock(); if (d_lockCount && pthread_equal(d_owner,pthread_self())) { ++d_lockCount; d_spin.unlock(); return; // RETURN } d_spin.unlock(); pthread_mutex_lock(&d_lock); } d_spin.lock(); d_owner = pthread_self(); d_lockCount = 1; d_spin.unlock(); #endif } int bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::tryLock() { #ifdef PTHREAD_MUTEX_RECURSIVE return pthread_mutex_trylock(&d_lock); // RETURN #else if (pthread_mutex_trylock(&d_lock)) { d_spin.lock(); if (d_lockCount && pthread_equal(d_owner,pthread_self())) { ++d_lockCount; d_spin.unlock(); return 0; // RETURN } else { d_spin.unlock(); return 1; // RETURN } } else { d_spin.lock(); d_owner = pthread_self(); d_lockCount = 1; d_spin.unlock(); return 0; // RETURN } #endif } void bdlqq::RecursiveMutexImpl<bdlqq::Platform::PosixThreads>::unlock() { #ifdef PTHREAD_MUTEX_RECURSIVE pthread_mutex_unlock(&d_lock); #else d_spin.lock(); if (!--d_lockCount) { d_spin.unlock(); pthread_mutex_unlock(&d_lock); return; // RETURN } d_spin.unlock(); #endif } } // close enterprise namespace #endif // ---------------------------------------------------------------------------- // Copyright 2015 Bloomberg Finance L.P. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ----------------------------- END-OF-FILE ---------------------------------- <|endoftext|>
<commit_before>#pragma once #include "feature_info.hpp" #include "../graphics/color.hpp" #include "../graphics/screen.hpp" #include "../std/list.hpp" #include "../std/string.hpp" #include "../std/shared_ptr.hpp" #include "../std/map.hpp" class ScreenBase; namespace drule { class BaseRule; } namespace graphics { namespace gl { class FrameBuffer; class BaseTexture; } class ResourceManager; } class Drawer { double m_visualScale; int m_level; scoped_ptr<graphics::Screen> m_pScreen; static void ClearResourceCache(size_t threadSlot, uint8_t pipelineID); protected: void drawSymbol(m2::PointD const & pt, graphics::EPosition pos, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawCircle(m2::PointD const & pt, graphics::EPosition pos, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawPath(di::PathInfo const & path, di::DrawRule const * rules, size_t count); void drawArea(di::AreaInfo const & area, di::DrawRule const & rule); void drawText(m2::PointD const & pt, graphics::EPosition pos, di::FeatureStyler const & fs, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawPathText(di::PathInfo const & info, di::FeatureStyler const & fs, di::DrawRule const & rule); void drawPathNumber(di::PathInfo const & path, di::FeatureStyler const & fs); typedef shared_ptr<graphics::gl::BaseTexture> texture_t; typedef shared_ptr<graphics::gl::FrameBuffer> frame_buffer_t; public: struct Params : graphics::Screen::Params { double m_visualScale; Params(); }; Drawer(Params const & params = Params()); double VisualScale() const; void SetScale(int level); int ThreadSlot() const; void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255), bool clearRT = true, float depth = 1.0f, bool clearDepth = true); graphics::Screen * screen() const; void drawSymbol(m2::PointD const & pt, string const & symbolName, graphics::EPosition pos, double depth); void beginFrame(); void endFrame(); void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255), bool clearRT = true, float depth = -1.0f, bool clearDepth = true); void onSize(int w, int h); }; <commit_msg>Minor fixes after merge.<commit_after>#pragma once #include "feature_info.hpp" #include "../graphics/color.hpp" #include "../graphics/screen.hpp" #include "../std/list.hpp" #include "../std/string.hpp" #include "../std/shared_ptr.hpp" #include "../std/map.hpp" class ScreenBase; namespace drule { class BaseRule; } namespace graphics { namespace gl { class FrameBuffer; class BaseTexture; } class ResourceManager; } class Drawer { double m_visualScale; int m_level; scoped_ptr<graphics::Screen> m_pScreen; static void ClearResourceCache(size_t threadSlot, uint8_t pipelineID); protected: void drawSymbol(m2::PointD const & pt, graphics::EPosition pos, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawCircle(m2::PointD const & pt, graphics::EPosition pos, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawPath(di::PathInfo const & path, di::DrawRule const * rules, size_t count); void drawArea(di::AreaInfo const & area, di::DrawRule const & rule); void drawText(m2::PointD const & pt, graphics::EPosition pos, di::FeatureStyler const & fs, di::DrawRule const & rule, di::FeatureInfo::FeatureID const & id); void drawPathText(di::PathInfo const & info, di::FeatureStyler const & fs, di::DrawRule const & rule); void drawPathNumber(di::PathInfo const & path, di::FeatureStyler const & fs); typedef shared_ptr<graphics::gl::BaseTexture> texture_t; typedef shared_ptr<graphics::gl::FrameBuffer> frame_buffer_t; public: struct Params : graphics::Screen::Params { double m_visualScale; Params(); }; Drawer(Params const & params = Params()); double VisualScale() const; void SetScale(int level); int ThreadSlot() const; graphics::Screen * screen() const; void drawSymbol(m2::PointD const & pt, string const & symbolName, graphics::EPosition pos, double depth); void beginFrame(); void endFrame(); void clear(graphics::Color const & c = graphics::Color(187, 187, 187, 255), bool clearRT = true, float depth = 1.0f, bool clearDepth = true); void onSize(int w, int h); void Draw(di::FeatureInfo const & fi); }; <|endoftext|>
<commit_before>#include "Patterns.h" #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> void PatchStreams( char* streams, uint32_t count ) { const size_t SCRATCH_PAD_SIZE = 32767; const size_t MAX_ENTRY_SIZE = 24; char* buf = new char[ SCRATCH_PAD_SIZE ]; GetPrivateProfileSectionA( "Samples", buf, SCRATCH_PAD_SIZE, "audio/audio-samples.ini" ); uint32_t entriesRead = 0; for( char* raw = buf; *raw != '\0'; ++raw ) { char* stream = streams; for ( size_t i = 0; i < MAX_ENTRY_SIZE; ++i ) { *stream++ = *raw++; if ( *raw == '\0' ) break; } *stream = '\0'; streams += MAX_ENTRY_SIZE+1; if ( ++entriesRead >= count ) break; } delete[] buf; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if ( reason == DLL_PROCESS_ATTACH) { using namespace hook; char* streamNames = *get_pattern<char*>( "8D 0C 49 01 C1 8D 44 24 04 81 C1", 11 ); uint32_t* streamsCountVC = get_pattern<uint32_t>( "0F 84 D5 00 00 00 81 FD ? ? ? ? 0F 83 C9 00 00 00", 8 ); uint8_t* streamsCountIII = get_pattern<uint8_t>( "0F 84 2E 03 00 00 80 BC 24 1C 01 00 00 ?", 13 ); uint32_t numStreams; if ( streamsCountIII != nullptr ) numStreams = *streamsCountIII; else if ( streamsCountVC != nullptr ) numStreams = *streamsCountVC; else return FALSE; // Not III nor VC? PatchStreams( streamNames, numStreams ); } return TRUE; }<commit_msg>Reject too long strings (>24 characters)<commit_after>#include "Patterns.h" #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <windows.h> void PatchStreams( char* streams, uint32_t count ) { const size_t SCRATCH_PAD_SIZE = 32767; const size_t MAX_ENTRY_SIZE = 24; char* buf = new char[ SCRATCH_PAD_SIZE ]; GetPrivateProfileSectionA( "Samples", buf, SCRATCH_PAD_SIZE, "audio/audio-samples.ini" ); uint32_t entriesRead = 0; for( char* raw = buf; *raw != '\0'; ++raw ) { char thisStream[MAX_ENTRY_SIZE+1]; char* stream = thisStream; for ( size_t i = 0; i < MAX_ENTRY_SIZE; ++i ) { *stream++ = *raw++; if ( *raw == '\0' ) break; } *stream = '\0'; bool rejectEntry = false; if ( *raw != '\0' ) { rejectEntry = true; while ( *++raw != '\0' ); } if ( !rejectEntry ) { strcpy_s( streams, MAX_ENTRY_SIZE+1, thisStream ); } streams += MAX_ENTRY_SIZE+1; if ( ++entriesRead >= count ) break; } delete[] buf; } BOOL APIENTRY DllMain(HMODULE hModule, DWORD reason, LPVOID lpReserved) { if ( reason == DLL_PROCESS_ATTACH) { using namespace hook; char* streamNames = *get_pattern<char*>( "8D 0C 49 01 C1 8D 44 24 04 81 C1", 11 ); uint32_t* streamsCountVC = get_pattern<uint32_t>( "0F 84 D5 00 00 00 81 FD ? ? ? ? 0F 83 C9 00 00 00", 8 ); uint8_t* streamsCountIII = get_pattern<uint8_t>( "0F 84 2E 03 00 00 80 BC 24 1C 01 00 00 ?", 13 ); uint32_t numStreams; if ( streamsCountIII != nullptr ) numStreams = *streamsCountIII; else if ( streamsCountVC != nullptr ) numStreams = *streamsCountVC; else return FALSE; // Not III nor VC? PatchStreams( streamNames, numStreams ); } return TRUE; }<|endoftext|>
<commit_before>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/perv/p10_set_fsi_gp_shadow.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_set_fsi_gp_shadow.C /// @brief Setup initial values for RC and RC_copy registers //------------------------------------------------------------------------------ // *HWP HW Maintainer : Anusha Reddy ([email protected]) // *HWP FW Maintainer : Raja Das ([email protected]) // *HWP Consumed by : FSP //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_set_fsi_gp_shadow.H> #include "p10_scom_perv_0.H" #include "p10_scom_perv_1.H" #include "p10_scom_perv_2.H" #include "p10_scom_perv_3.H" #include "p10_scom_perv_4.H" #include "p10_scom_perv_5.H" #include "p10_scom_perv_6.H" #include "p10_scom_perv_8.H" #include "p10_scom_perv_9.H" #include "p10_scom_perv_c.H" #include "p10_scom_perv_d.H" #include "p10_scom_perv_e.H" using namespace scomt; using namespace scomt::perv; struct { uint32_t reg_addr, reg_copy_addr, value; } P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES[] = { { FSXCOMP_FSXLOG_ROOT_CTRL0_FSI, FSXCOMP_FSXLOG_ROOT_CTRL0_COPY_FSI, 0x80FF6007}, { FSXCOMP_FSXLOG_ROOT_CTRL1_FSI, FSXCOMP_FSXLOG_ROOT_CTRL1_COPY_FSI, 0x00180020}, { FSXCOMP_FSXLOG_ROOT_CTRL2_FSI, FSXCOMP_FSXLOG_ROOT_CTRL2_COPY_FSI, 0x04000000}, { FSXCOMP_FSXLOG_ROOT_CTRL3_FSI, FSXCOMP_FSXLOG_ROOT_CTRL3_COPY_FSI, 0xEFEEEEFF}, { FSXCOMP_FSXLOG_ROOT_CTRL8_FSI, FSXCOMP_FSXLOG_ROOT_CTRL8_COPY_FSI, 0x00000000}, { FSXCOMP_FSXLOG_PERV_CTRL0_FSI, FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI, 0x7C022020}, { FSXCOMP_FSXLOG_PERV_CTRL1_FSI, FSXCOMP_FSXLOG_PERV_CTRL1_COPY_FSI, 0x60000000} }; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p10_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("p10_set_fsi_gp_shadow: Entering"); for (auto rc : P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES) { fapi2::buffer<uint32_t> l_data = rc.value; FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_addr, l_data)); FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_copy_addr, l_data)); } FAPI_INF("p10_set_fsi_gp_shadow: Exiting"); fapi_try_exit: return fapi2::current_err; } <commit_msg>Don't Set CFAM Protection Bit In Root Ctrl<commit_after>/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/import/chips/p10/procedures/hwp/perv/p10_set_fsi_gp_shadow.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2016,2021 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* 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. */ /* */ /* IBM_PROLOG_END_TAG */ /// /// @file p10_set_fsi_gp_shadow.C /// @brief Setup initial values for RC and RC_copy registers //------------------------------------------------------------------------------ // *HWP HW Maintainer : Anusha Reddy ([email protected]) // *HWP FW Maintainer : Raja Das ([email protected]) // *HWP Consumed by : FSP //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // Includes //------------------------------------------------------------------------------ #include <p10_set_fsi_gp_shadow.H> #include "p10_scom_perv_0.H" #include "p10_scom_perv_1.H" #include "p10_scom_perv_2.H" #include "p10_scom_perv_3.H" #include "p10_scom_perv_4.H" #include "p10_scom_perv_5.H" #include "p10_scom_perv_6.H" #include "p10_scom_perv_8.H" #include "p10_scom_perv_9.H" #include "p10_scom_perv_c.H" #include "p10_scom_perv_d.H" #include "p10_scom_perv_e.H" using namespace scomt; using namespace scomt::perv; struct { uint32_t reg_addr, reg_copy_addr, value; } P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES[] = { { FSXCOMP_FSXLOG_ROOT_CTRL0_FSI, FSXCOMP_FSXLOG_ROOT_CTRL0_COPY_FSI, 0x00FF6007}, { FSXCOMP_FSXLOG_ROOT_CTRL1_FSI, FSXCOMP_FSXLOG_ROOT_CTRL1_COPY_FSI, 0x00180020}, { FSXCOMP_FSXLOG_ROOT_CTRL2_FSI, FSXCOMP_FSXLOG_ROOT_CTRL2_COPY_FSI, 0x04000000}, { FSXCOMP_FSXLOG_ROOT_CTRL3_FSI, FSXCOMP_FSXLOG_ROOT_CTRL3_COPY_FSI, 0xEFEEEEFF}, { FSXCOMP_FSXLOG_ROOT_CTRL8_FSI, FSXCOMP_FSXLOG_ROOT_CTRL8_COPY_FSI, 0x00000000}, { FSXCOMP_FSXLOG_PERV_CTRL0_FSI, FSXCOMP_FSXLOG_PERV_CTRL0_COPY_FSI, 0x7C022020}, { FSXCOMP_FSXLOG_PERV_CTRL1_FSI, FSXCOMP_FSXLOG_PERV_CTRL1_COPY_FSI, 0x60000000} }; //------------------------------------------------------------------------------ // Function definitions //------------------------------------------------------------------------------ fapi2::ReturnCode p10_set_fsi_gp_shadow(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target) { FAPI_INF("p10_set_fsi_gp_shadow: Entering"); for (auto rc : P10_SET_FSI_GP_SHADOW_GPREG_INITVALUES) { fapi2::buffer<uint32_t> l_data = rc.value; FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_addr, l_data)); FAPI_TRY(fapi2::putCfamRegister(i_target, rc.reg_copy_addr, l_data)); } FAPI_INF("p10_set_fsi_gp_shadow: Exiting"); fapi_try_exit: return fapi2::current_err; } <|endoftext|>
<commit_before>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_POSH_MEPOO_MEPOO_SEGMENT_INL #define IOX_POSH_MEPOO_MEPOO_SEGMENT_INL #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_posh/mepoo/memory_info.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_utils/error_handling/error_handling.hpp" #include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp" namespace iox { namespace mepoo { template <typename SharedMemoryObjectType, typename MemoryManagerType> inline MePooSegment<SharedMemoryObjectType, MemoryManagerType>::MePooSegment(const MePooConfig& f_mempoolConfig, posix::Allocator* f_managementAllocator, const posix::PosixGroup& f_readerGroup, const posix::PosixGroup& f_writerGroup, const iox::mepoo::MemoryInfo& memoryInfo) : m_sharedMemoryObject(createSharedMemoryObject(f_mempoolConfig, f_writerGroup)) , m_readerGroup(f_readerGroup) , m_writerGroup(f_writerGroup) , m_memoryInfo(memoryInfo) { using namespace posix; AccessController f_accessController; if (!(f_readerGroup == f_writerGroup)) { f_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READ, f_readerGroup.getName()); } f_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, f_writerGroup.getName()); f_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); f_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READWRITE); f_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); if (!f_accessController.writePermissionsToFile(m_sharedMemoryObject.getFileHandle())) { errorHandler(Error::kMEPOO__SEGMENT_COULD_NOT_APPLY_POSIX_RIGHTS_TO_SHARED_MEMORY); } m_memoryManager.configureMemoryManager(f_mempoolConfig, f_managementAllocator, m_sharedMemoryObject.getAllocator()); m_sharedMemoryObject.finalizeAllocation(); } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline SharedMemoryObjectType MePooSegment<SharedMemoryObjectType, MemoryManagerType>::createSharedMemoryObject( const MePooConfig& f_mempoolConfig, const posix::PosixGroup& f_writerGroup) { // we let the OS decide where to map the shm segments constexpr void* BASE_ADDRESS_HINT{nullptr}; // on qnx the current working directory will be added to the /dev/shmem path if the leading slash is missing auto shmName = "/" + f_writerGroup.getName(); return std::move( SharedMemoryObjectType::create(shmName.c_str(), MemoryManager::requiredChunkMemorySize(f_mempoolConfig), posix::AccessMode::readWrite, posix::OwnerShip::mine, BASE_ADDRESS_HINT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) .and_then([this](auto& sharedMemoryObject) { setSegmentId(iox::RelativePointer::registerPtr(sharedMemoryObject.getBaseAddress(), sharedMemoryObject.getSizeInBytes())); LogDebug() << "Roudi registered payload segment " << iox::log::HexFormat(reinterpret_cast<uint64_t>(sharedMemoryObject.getBaseAddress())) << " with size " << sharedMemoryObject.getSizeInBytes() << " to id " << m_segmentId; }) .or_else([](auto&) { errorHandler(Error::kMEPOO__SEGMENT_UNABLE_TO_CREATE_SHARED_MEMORY_OBJECT); }) .value()); } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getWriterGroup() const { return m_writerGroup; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getReaderGroup() const { return m_readerGroup; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline MemoryManagerType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getMemoryManager() { return m_memoryManager; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline const SharedMemoryObjectType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSharedMemoryObject() const { return m_sharedMemoryObject; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline uint64_t MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSegmentId() const { return m_segmentId; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline void MePooSegment<SharedMemoryObjectType, MemoryManagerType>::setSegmentId(const uint64_t segmentId) { m_segmentId = segmentId; } } // namespace mepoo } // namespace iox #endif // IOX_POSH_MEPOO_MEPOO_SEGMENT_INL <commit_msg>iox-#542 fixed clang conversion warning<commit_after>// Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved. // Copyright (c) 2021 by Apex.AI Inc. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // SPDX-License-Identifier: Apache-2.0 #ifndef IOX_POSH_MEPOO_MEPOO_SEGMENT_INL #define IOX_POSH_MEPOO_MEPOO_SEGMENT_INL #include "iceoryx_posh/internal/log/posh_logging.hpp" #include "iceoryx_posh/mepoo/memory_info.hpp" #include "iceoryx_posh/mepoo/mepoo_config.hpp" #include "iceoryx_utils/error_handling/error_handling.hpp" #include "iceoryx_utils/internal/relocatable_pointer/relative_ptr.hpp" namespace iox { namespace mepoo { template <typename SharedMemoryObjectType, typename MemoryManagerType> inline MePooSegment<SharedMemoryObjectType, MemoryManagerType>::MePooSegment(const MePooConfig& f_mempoolConfig, posix::Allocator* f_managementAllocator, const posix::PosixGroup& f_readerGroup, const posix::PosixGroup& f_writerGroup, const iox::mepoo::MemoryInfo& memoryInfo) : m_sharedMemoryObject(createSharedMemoryObject(f_mempoolConfig, f_writerGroup)) , m_readerGroup(f_readerGroup) , m_writerGroup(f_writerGroup) , m_memoryInfo(memoryInfo) { using namespace posix; AccessController f_accessController; if (!(f_readerGroup == f_writerGroup)) { f_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READ, f_readerGroup.getName()); } f_accessController.addPermissionEntry( AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, f_writerGroup.getName()); f_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE); f_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READWRITE); f_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE); if (!f_accessController.writePermissionsToFile(m_sharedMemoryObject.getFileHandle())) { errorHandler(Error::kMEPOO__SEGMENT_COULD_NOT_APPLY_POSIX_RIGHTS_TO_SHARED_MEMORY); } m_memoryManager.configureMemoryManager(f_mempoolConfig, f_managementAllocator, m_sharedMemoryObject.getAllocator()); m_sharedMemoryObject.finalizeAllocation(); } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline SharedMemoryObjectType MePooSegment<SharedMemoryObjectType, MemoryManagerType>::createSharedMemoryObject( const MePooConfig& f_mempoolConfig, const posix::PosixGroup& f_writerGroup) { // we let the OS decide where to map the shm segments constexpr void* BASE_ADDRESS_HINT{nullptr}; // on qnx the current working directory will be added to the /dev/shmem path if the leading slash is missing auto shmName = "/" + f_writerGroup.getName(); return std::move( SharedMemoryObjectType::create(shmName.c_str(), MemoryManager::requiredChunkMemorySize(f_mempoolConfig), posix::AccessMode::readWrite, posix::OwnerShip::mine, BASE_ADDRESS_HINT, static_cast<mode_t>(S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP)) .and_then([this](auto& sharedMemoryObject) { setSegmentId(iox::RelativePointer::registerPtr(sharedMemoryObject.getBaseAddress(), sharedMemoryObject.getSizeInBytes())); LogDebug() << "Roudi registered payload segment " << iox::log::HexFormat(reinterpret_cast<uint64_t>(sharedMemoryObject.getBaseAddress())) << " with size " << sharedMemoryObject.getSizeInBytes() << " to id " << m_segmentId; }) .or_else([](auto&) { errorHandler(Error::kMEPOO__SEGMENT_UNABLE_TO_CREATE_SHARED_MEMORY_OBJECT); }) .value()); } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getWriterGroup() const { return m_writerGroup; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline posix::PosixGroup MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getReaderGroup() const { return m_readerGroup; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline MemoryManagerType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getMemoryManager() { return m_memoryManager; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline const SharedMemoryObjectType& MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSharedMemoryObject() const { return m_sharedMemoryObject; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline uint64_t MePooSegment<SharedMemoryObjectType, MemoryManagerType>::getSegmentId() const { return m_segmentId; } template <typename SharedMemoryObjectType, typename MemoryManagerType> inline void MePooSegment<SharedMemoryObjectType, MemoryManagerType>::setSegmentId(const uint64_t segmentId) { m_segmentId = segmentId; } } // namespace mepoo } // namespace iox #endif // IOX_POSH_MEPOO_MEPOO_SEGMENT_INL <|endoftext|>
<commit_before> #include "rts_object_system.h" #include "cocos2d.h" #include "CCGLProgramStateCache.h" #include "cor_system/sources/logger.h" #include "cor_type/sources/primitive/box.h" #include "cor_cocos2dx_converter/sources/type_converter.h" namespace cor { namespace cocos2dx_converter { struct RtsObjectSystemItnl { }; RtsObjectSystem::RtsObjectSystem() : itnl(new RtsObjectSystemItnl()) { } RtsObjectSystem::~RtsObjectSystem() { } void RtsObjectSystem::setup_rts_rendering_state() { cocos2d::Director::getInstance()->setDepthTest(false); cocos2d::Director::getInstance()->setAlphaBlending(true); } cocos2d::GLProgram* rts_object_system_alpha_test_shader = NULL; cocos2d::GLProgram* rts_object_system_round_shader = NULL; #define STRINGIFY(A) #A void rts_object_system_load_shader() { { static const char* my_frag_shader = STRINGIFY( \n#ifdef GL_ES\n precision lowp float; \n#endif\n varying vec4 v_fragmentColor; varying vec2 v_texCoord; /*uniform float cc_alpha_value;*/ void main() { vec4 texColor = texture2D(CC_Texture0, v_texCoord); float cc_alpha_value = 0.5; if(texColor.a <= cc_alpha_value) discard; texColor.a = 1.0; gl_FragColor = texColor * v_fragmentColor; } ); if(rts_object_system_alpha_test_shader) { rts_object_system_alpha_test_shader->release(); } auto ss = cocos2d::GLProgram::createWithByteArrays(cocos2d::ccPositionTextureColor_noMVP_vert, my_frag_shader); rts_object_system_alpha_test_shader = ss; ss->retain(); } { const char* my_vert_shader = STRINGIFY( attribute vec4 a_position; attribute vec2 a_texCoord; attribute vec4 a_color; \n#ifdef GL_ES\n varying lowp vec4 v_fragmentColor; varying mediump vec2 v_texCoord; \n#else\n varying vec4 v_fragmentColor; varying vec2 v_texCoord; \n#endif\n void main() { gl_Position = CC_PMatrix * a_position; gl_Position.x *= 400.0; gl_Position.y *= 240.0; gl_Position.xy = floor(gl_Position.xy + vec2(0.5, 0.5)); gl_Position.x /= 400.0; gl_Position.y /= 240.0; v_fragmentColor = a_color; v_texCoord = a_texCoord; } ); if(rts_object_system_round_shader) { rts_object_system_round_shader->release(); } auto ss = cocos2d::GLProgram::createWithByteArrays(my_vert_shader, cocos2d::ccPositionTextureColor_noMVP_frag); rts_object_system_round_shader = ss; ss->retain(); } } void RtsObjectSystem::setup_sprite_alphatest(cocos2d::Sprite* sprite) { static cocos2d::GLProgramState* s = NULL; if(!s) { rts_object_system_load_shader(); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(rts_object_system_alpha_test_shader); s->retain(); } sprite->setGLProgramState(s); } void RtsObjectSystem::setup_sprite_round(cocos2d::Sprite* sprite) { static cocos2d::GLProgramState* s = NULL; static RBool need_reset = rfalse; auto p_need_reset = &need_reset; auto ps = &s; if(!s) { auto shader = &rts_object_system_round_shader; rts_object_system_load_shader(); log_debug("shader ", (*shader)->getProgram()); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader); s->retain(); auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { *p_need_reset = rtrue; }); cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -2); { // todo: comfirm on android auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { auto scn = cocos2d::Director::getInstance()->getRunningScene(); scn->enumerateChildren("//[[:alnum:]]+", [&](cocos2d::Node* n){ if(n->getGLProgramState() == s) { n->setGLProgramState( cocos2d::GLProgramState::getOrCreateWithGLProgramName( cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); } return false; }); }); cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3); } } sprite->setGLProgramState(s); { //auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { // sprite->setGLProgramState( // cocos2d::GLProgramState::getOrCreateWithGLProgramName( // cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); //}); //// Memory leak. //sprite->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3); } { auto shader = &rts_object_system_round_shader; auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { RtsObjectSystem::delay_call(sprite, 0.01f, [=](){ if(*p_need_reset) { auto s = *ps; s->release(); cocos2d::GLProgramStateCache::getInstance()->removeUnusedGLProgramState(); rts_object_system_load_shader(); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader); s->retain(); *ps = s; *p_need_reset = rfalse; } sprite->setGLProgramState(*ps); }); }); sprite->getEventDispatcher()->addEventListenerWithSceneGraphPriority(backToForegroundlistener, sprite); } } void RtsObjectSystem::setup_avoid_blur_texture(cocos2d::Texture2D* texture) { cocos2d::Texture2D::TexParams p; p.minFilter = GL_NEAREST; p.magFilter = GL_LINEAR; p.wrapS = GL_CLAMP_TO_EDGE; p.wrapT = GL_CLAMP_TO_EDGE; texture->setTexParameters(p); } cocos2d::Rect RtsObjectSystem::node_rect(cocos2d::Node* node) { auto bb = node->getBoundingBox(); type::Matrix4x4F mat; convert(node->getNodeToWorldTransform(), mat); auto imat = mat.affine_inverse(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F ab; type::Box2F tb; if(bb.size.width > 0) { //tb.set_rect(imat, b); ab = b; } node->enumerateChildren("//.*", [&](cocos2d::Node* n){ type::Matrix4x4F m; convert(n->getParent()->getNodeToWorldTransform(), m); type::Matrix4x4F tm; tm = imat * m; auto bb = n->getBoundingBox(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F tb; tb.set_rect(tm, b); ab.add_rect(tb); return false; }); return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y); } cocos2d::Rect RtsObjectSystem::nodes_rect(cocos2d::Vector<cocos2d::Node*> nodes) { //depricated if(nodes.size() > 0) { type::Box2F aab; for(auto node : nodes) { auto bb = node->getBoundingBox(); type::Matrix4x4F mat; convert(node->getNodeToWorldTransform(), mat); auto imat = mat.affine_inverse(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F ab; type::Box2F tb; tb.set_rect(imat, b); ab = tb; node->enumerateChildren("//.*", [&](cocos2d::Node* n){ type::Matrix4x4F m; convert(n->getParent()->getNodeToWorldTransform(), m); type::Matrix4x4F tm; tm = imat * m; auto bb = n->getBoundingBox(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F tb; tb.set_rect(tm, b); ab.add_rect(tb); return false; }); tb.set_rect(mat, b); ab = tb; aab.add_rect(ab); } auto ab = aab; return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y); } return cocos2d::Rect(); } cocos2d::Action* RtsObjectSystem::delay_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback) { cocos2d::Vector<cocos2d::FiniteTimeAction*> a; a.pushBack(cocos2d::DelayTime::create(interval)); a.pushBack(cocos2d::CallFunc::create([=](){callback(); })); return node->runAction(cocos2d::Sequence::create( a )); } cocos2d::Action* RtsObjectSystem::interval_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback) { cocos2d::Vector<cocos2d::FiniteTimeAction*> a; a.pushBack(cocos2d::DelayTime::create(interval)); a.pushBack(cocos2d::CallFunc::create([=](){callback(); })); return node->runAction( cocos2d::RepeatForever::create(cocos2d::Sequence::create( a ))); } void RtsObjectSystem::on_active() { //log_debug("RtsObjectSystem::on_active"); //rts_object_system_load_shader(); } } } <commit_msg>restore shader on android.<commit_after> #include "rts_object_system.h" #include "cocos2d.h" #include "CCGLProgramStateCache.h" #include "cor_system/sources/logger.h" #include "cor_type/sources/primitive/box.h" #include "cor_cocos2dx_converter/sources/type_converter.h" namespace cor { namespace cocos2dx_converter { struct RtsObjectSystemItnl { }; RtsObjectSystem::RtsObjectSystem() : itnl(new RtsObjectSystemItnl()) { } RtsObjectSystem::~RtsObjectSystem() { } void RtsObjectSystem::setup_rts_rendering_state() { cocos2d::Director::getInstance()->setDepthTest(false); cocos2d::Director::getInstance()->setAlphaBlending(true); } cocos2d::GLProgram* rts_object_system_alpha_test_shader = NULL; cocos2d::GLProgram* rts_object_system_round_shader = NULL; #define STRINGIFY(A) #A void rts_object_system_load_shader() { { static const char* my_frag_shader = STRINGIFY( \n#ifdef GL_ES\n precision lowp float; \n#endif\n varying vec4 v_fragmentColor; varying vec2 v_texCoord; /*uniform float cc_alpha_value;*/ void main() { vec4 texColor = texture2D(CC_Texture0, v_texCoord); float cc_alpha_value = 0.5; if(texColor.a <= cc_alpha_value) discard; texColor.a = 1.0; gl_FragColor = texColor * v_fragmentColor; } ); if(rts_object_system_alpha_test_shader) { rts_object_system_alpha_test_shader->release(); } auto ss = cocos2d::GLProgram::createWithByteArrays(cocos2d::ccPositionTextureColor_noMVP_vert, my_frag_shader); rts_object_system_alpha_test_shader = ss; ss->retain(); } { const char* my_vert_shader = STRINGIFY( attribute vec4 a_position; attribute vec2 a_texCoord; attribute vec4 a_color; \n#ifdef GL_ES\n varying lowp vec4 v_fragmentColor; varying mediump vec2 v_texCoord; \n#else\n varying vec4 v_fragmentColor; varying vec2 v_texCoord; \n#endif\n void main() { gl_Position = CC_PMatrix * a_position; gl_Position.x *= 400.0; gl_Position.y *= 240.0; gl_Position.xy = floor(gl_Position.xy + vec2(0.5, 0.5)); gl_Position.x /= 400.0; gl_Position.y /= 240.0; v_fragmentColor = a_color; v_texCoord = a_texCoord; } ); if(rts_object_system_round_shader) { rts_object_system_round_shader->release(); } auto ss = cocos2d::GLProgram::createWithByteArrays(my_vert_shader, cocos2d::ccPositionTextureColor_noMVP_frag); rts_object_system_round_shader = ss; ss->retain(); } } void RtsObjectSystem::setup_sprite_alphatest(cocos2d::Sprite* sprite) { static cocos2d::GLProgramState* s = NULL; if(!s) { rts_object_system_load_shader(); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(rts_object_system_alpha_test_shader); s->retain(); } sprite->setGLProgramState(s); } void RtsObjectSystem::setup_sprite_round(cocos2d::Sprite* sprite) { static cocos2d::GLProgramState* s = NULL; static RBool need_reset = rfalse; auto p_need_reset = &need_reset; auto ps = &s; if(!s) { auto shader = &rts_object_system_round_shader; rts_object_system_load_shader(); log_debug("shader ", (*shader)->getProgram()); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader); s->retain(); auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { log_debug("backToForegroundlistener -2"); *p_need_reset = rtrue; }); cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -2); { // todo: comfirm on android auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { log_debug("backToForegroundlistener -3"); auto scn = cocos2d::Director::getInstance()->getRunningScene(); log_debug("scn ", scn); scn->enumerateChildren("//.*", [&](cocos2d::Node* n){ log_debug("n ", n); if(n->getGLProgramState() == s) { log_debug("eq"); n->setGLProgramState( cocos2d::GLProgramState::getOrCreateWithGLProgramName( cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); } return false; }); log_debug("scn ed ", scn); }); cocos2d::Director::getInstance()->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3); } } sprite->setGLProgramState(s); { //auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { // sprite->setGLProgramState( // cocos2d::GLProgramState::getOrCreateWithGLProgramName( // cocos2d::GLProgram::SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP)); //}); //// Memory leak. //sprite->getEventDispatcher()->addEventListenerWithFixedPriority(backToForegroundlistener, -3); } { auto shader = &rts_object_system_round_shader; auto backToForegroundlistener = cocos2d::EventListenerCustom::create(EVENT_RENDERER_RECREATED, [=](cocos2d::EventCustom*) { RtsObjectSystem::delay_call(sprite, 0.01f, [=](){ log_debug("backToForegroundlistener sg"); if(*p_need_reset) { auto s = *ps; s->release(); cocos2d::GLProgramStateCache::getInstance()->removeUnusedGLProgramState(); rts_object_system_load_shader(); s = cocos2d::GLProgramStateCache::getInstance()->getGLProgramState(*shader); s->retain(); *ps = s; *p_need_reset = rfalse; } sprite->setGLProgramState(*ps); }); }); sprite->getEventDispatcher()->addEventListenerWithSceneGraphPriority(backToForegroundlistener, sprite); } } void RtsObjectSystem::setup_avoid_blur_texture(cocos2d::Texture2D* texture) { cocos2d::Texture2D::TexParams p; p.minFilter = GL_NEAREST; p.magFilter = GL_LINEAR; p.wrapS = GL_CLAMP_TO_EDGE; p.wrapT = GL_CLAMP_TO_EDGE; texture->setTexParameters(p); } cocos2d::Rect RtsObjectSystem::node_rect(cocos2d::Node* node) { auto bb = node->getBoundingBox(); type::Matrix4x4F mat; convert(node->getNodeToWorldTransform(), mat); auto imat = mat.affine_inverse(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F ab; type::Box2F tb; if(bb.size.width > 0) { //tb.set_rect(imat, b); ab = b; } node->enumerateChildren("//.*", [&](cocos2d::Node* n){ type::Matrix4x4F m; convert(n->getParent()->getNodeToWorldTransform(), m); type::Matrix4x4F tm; tm = imat * m; auto bb = n->getBoundingBox(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F tb; tb.set_rect(tm, b); ab.add_rect(tb); return false; }); return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y); } cocos2d::Rect RtsObjectSystem::nodes_rect(cocos2d::Vector<cocos2d::Node*> nodes) { //depricated if(nodes.size() > 0) { type::Box2F aab; for(auto node : nodes) { auto bb = node->getBoundingBox(); type::Matrix4x4F mat; convert(node->getNodeToWorldTransform(), mat); auto imat = mat.affine_inverse(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F ab; type::Box2F tb; tb.set_rect(imat, b); ab = tb; node->enumerateChildren("//.*", [&](cocos2d::Node* n){ type::Matrix4x4F m; convert(n->getParent()->getNodeToWorldTransform(), m); type::Matrix4x4F tm; tm = imat * m; auto bb = n->getBoundingBox(); type::Box2F b(type::Vector2F(bb.origin.x, bb.origin.y), type::Vector2F(bb.size.width, bb.size.height)); type::Box2F tb; tb.set_rect(tm, b); ab.add_rect(tb); return false; }); tb.set_rect(mat, b); ab = tb; aab.add_rect(ab); } auto ab = aab; return cocos2d::Rect(ab.p.x, ab.p.y, ab.w.x, ab.w.y); } return cocos2d::Rect(); } cocos2d::Action* RtsObjectSystem::delay_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback) { cocos2d::Vector<cocos2d::FiniteTimeAction*> a; a.pushBack(cocos2d::DelayTime::create(interval)); a.pushBack(cocos2d::CallFunc::create([=](){callback(); })); return node->runAction(cocos2d::Sequence::create( a )); } cocos2d::Action* RtsObjectSystem::interval_call(cocos2d::Node* node, RFloat interval, std::function<void()> callback) { cocos2d::Vector<cocos2d::FiniteTimeAction*> a; a.pushBack(cocos2d::DelayTime::create(interval)); a.pushBack(cocos2d::CallFunc::create([=](){callback(); })); return node->runAction( cocos2d::RepeatForever::create(cocos2d::Sequence::create( a ))); } void RtsObjectSystem::on_active() { //log_debug("RtsObjectSystem::on_active"); //rts_object_system_load_shader(); } } } <|endoftext|>
<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/constants.hpp> namespace stan { namespace prob { // NegBinomial(n|alpha,beta) [alpha > 0; beta > 0; n >= 0] template <bool propto, typename T_n, typename T_shape, typename T_inv_scale, class Policy> typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const Policy&) { static const char* function = "stan::prob::neg_binomial_log(%1%)"; using stan::math::check_finite; using stan::math::check_nonnegative; using stan::math::check_positive; using stan::math::value_of; using stan::math::check_consistent_sizes; using stan::prob::include_summand; // check if any vectors are zero length if (!(stan::length(n) && stan::length(alpha) && stan::length(beta))) return 0.0; typename return_type<T_shape, T_inv_scale>::type logp(0.0); if (!check_nonnegative(function, n, "Failures variable", &logp, Policy())) return logp; if (!check_finite(function, alpha, "Shape parameter", &logp, Policy())) return logp; if (!check_positive(function, alpha, "Shape parameter", &logp, Policy())) return logp; if (!check_finite(function, beta, "Inverse scale parameter", &logp, Policy())) return logp; if (!check_positive(function, beta, "Inverse scale parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, n,alpha,beta, "Failures variable","Shape parameter","Inverse scale parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_shape,T_inv_scale>::value) return 0.0; using stan::math::multiply_log; using stan::math::binomial_coefficient_log; // set up template expressions wrapping scalars into vector views VectorView<const T_n> n_vec(n); VectorView<const T_shape> alpha_vec(alpha); VectorView<const T_inv_scale> beta_vec(beta); size_t size = max_size(n, alpha, beta); for (size_t i = 0; i < size; i++) { // Special case where negative binomial reduces to Poisson if (alpha_vec[i] > 1e10) { if (include_summand<propto>::value) logp -= lgamma(n_vec[i] + 1.0); if (include_summand<propto,T_shape>::value || include_summand<propto,T_inv_scale>::value) { typename return_type<T_shape, T_inv_scale>::type lambda; lambda = alpha_vec[i] / beta_vec[i]; logp += multiply_log(n_vec[i], lambda) - lambda; } } // More typical cases if (include_summand<propto,T_shape>::value) if (n_vec[i] != 0) logp += binomial_coefficient_log<typename scalar_type<T_shape>::type> (n_vec[i] + alpha_vec[i] - 1.0, n_vec[i]); if (include_summand<propto,T_shape,T_inv_scale>::value) logp += -n_vec[i] * log1p(beta_vec[i]) + alpha_vec[i] * log(beta_vec[i] / (1 + beta_vec[i])); } return logp; } template <bool propto, typename T_n, typename T_shape, typename T_inv_scale> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_log<propto>(n,alpha,beta, stan::math::default_policy()); } template <typename T_n, typename T_shape, typename T_inv_scale, class Policy> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const Policy&) { return neg_binomial_log<false>(n,alpha,beta,Policy()); } template <typename T_n, typename T_shape, typename T_inv_scale> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_log<false>(n,alpha,beta, stan::math::default_policy()); } } } #endif <commit_msg>updating neg_binomial distribution<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__ #define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__DISCRETE__NEG_BINOMIAL_HPP__ #include <stan/agrad.hpp> #include <stan/math/error_handling.hpp> #include <stan/math/special_functions.hpp> #include <stan/meta/traits.hpp> #include <stan/prob/traits.hpp> #include <stan/prob/constants.hpp> namespace stan { namespace prob { // NegBinomial(n|alpha,beta) [alpha > 0; beta > 0; n >= 0] template <bool propto, typename T_n, typename T_shape, typename T_inv_scale, class Policy> typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const Policy&) { static const char* function = "stan::prob::neg_binomial_log(%1%)"; using stan::math::check_finite; using stan::math::check_nonnegative; using stan::math::check_positive; using stan::math::value_of; using stan::math::check_consistent_sizes; using stan::prob::include_summand; // check if any vectors are zero length if (!(stan::length(n) && stan::length(alpha) && stan::length(beta))) return 0.0; typename return_type<T_shape, T_inv_scale>::type logp(0.0); if (!check_nonnegative(function, n, "Failures variable", &logp, Policy())) return logp; if (!check_finite(function, alpha, "Shape parameter", &logp, Policy())) return logp; if (!check_positive(function, alpha, "Shape parameter", &logp, Policy())) return logp; if (!check_finite(function, beta, "Inverse scale parameter", &logp, Policy())) return logp; if (!check_positive(function, beta, "Inverse scale parameter", &logp, Policy())) return logp; if (!(check_consistent_sizes(function, n,alpha,beta, "Failures variable","Shape parameter","Inverse scale parameter", &logp, Policy()))) return logp; // check if no variables are involved and prop-to if (!include_summand<propto,T_shape,T_inv_scale>::value) return 0.0; using stan::math::multiply_log; using stan::math::binomial_coefficient_log; // set up template expressions wrapping scalars into vector views VectorView<const T_n> n_vec(n); VectorView<const T_shape> alpha_vec(alpha); VectorView<const T_inv_scale> beta_vec(beta); size_t size = max_size(n, alpha, beta); for (size_t i = 0; i < size; i++) { // Special case where negative binomial reduces to Poisson if (alpha_vec[i] > 1e10) { if (include_summand<propto>::value) logp -= lgamma(n_vec[i] + 1.0); if (include_summand<propto,T_shape>::value || include_summand<propto,T_inv_scale>::value) { typename return_type<T_shape, T_inv_scale>::type lambda; lambda = alpha_vec[i] / beta_vec[i]; logp += multiply_log(n_vec[i], lambda) - lambda; } } else { // More typical cases if (include_summand<propto,T_shape>::value) if (n_vec[i] != 0) logp += binomial_coefficient_log<typename scalar_type<T_shape>::type> (n_vec[i] + alpha_vec[i] - 1.0, n_vec[i]); if (include_summand<propto,T_shape,T_inv_scale>::value) logp += -n_vec[i] * log1p(beta_vec[i]) + alpha_vec[i] * log(beta_vec[i] / (1 + beta_vec[i])); } } return logp; } template <bool propto, typename T_n, typename T_shape, typename T_inv_scale> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_log<propto>(n,alpha,beta, stan::math::default_policy()); } template <typename T_n, typename T_shape, typename T_inv_scale, class Policy> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta, const Policy&) { return neg_binomial_log<false>(n,alpha,beta,Policy()); } template <typename T_n, typename T_shape, typename T_inv_scale> inline typename return_type<T_shape, T_inv_scale>::type neg_binomial_log(const T_n& n, const T_shape& alpha, const T_inv_scale& beta) { return neg_binomial_log<false>(n,alpha,beta, stan::math::default_policy()); } } } #endif <|endoftext|>
<commit_before>/* Copyright 2022 The MediaPipe 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 "mediapipe/tasks/cc/vision/gesture_recognizer/gesture_recognizer.h" #include <memory> #include <type_traits> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "mediapipe/framework/api2/builder.h" #include "mediapipe/framework/api2/port.h" #include "mediapipe/framework/formats/classification.pb.h" #include "mediapipe/framework/formats/image.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/packet.h" #include "mediapipe/tasks/cc/common.h" #include "mediapipe/tasks/cc/components/image_preprocessing.h" #include "mediapipe/tasks/cc/components/processors/proto/classifier_options.pb.h" #include "mediapipe/tasks/cc/core/base_task_api.h" #include "mediapipe/tasks/cc/core/model_resources.h" #include "mediapipe/tasks/cc/core/proto/inference_subgraph.pb.h" #include "mediapipe/tasks/cc/core/task_runner.h" #include "mediapipe/tasks/cc/core/utils.h" #include "mediapipe/tasks/cc/vision/core/base_vision_task_api.h" #include "mediapipe/tasks/cc/vision/core/vision_task_api_factory.h" #include "mediapipe/tasks/cc/vision/gesture_recognizer/proto/gesture_recognizer_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/gesture_recognizer/proto/hand_gesture_recognizer_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_detector/proto/hand_detector_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_landmarker/proto/hand_landmarker_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_landmarker/proto/hand_landmarks_detector_graph_options.pb.h" namespace mediapipe { namespace tasks { namespace vision { namespace gesture_recognizer { namespace { using GestureRecognizerGraphOptionsProto = ::mediapipe::tasks::vision:: gesture_recognizer::proto::GestureRecognizerGraphOptions; using ::mediapipe::tasks::components::containers::GestureRecognitionResult; constexpr char kHandGestureSubgraphTypeName[] = "mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"; constexpr char kImageTag[] = "IMAGE"; constexpr char kImageInStreamName[] = "image_in"; constexpr char kImageOutStreamName[] = "image_out"; constexpr char kHandGesturesTag[] = "HAND_GESTURES"; constexpr char kHandGesturesStreamName[] = "hand_gestures"; constexpr char kHandednessTag[] = "HANDEDNESS"; constexpr char kHandednessStreamName[] = "handedness"; constexpr char kHandLandmarksTag[] = "LANDMARKS"; constexpr char kHandLandmarksStreamName[] = "landmarks"; constexpr char kHandWorldLandmarksTag[] = "WORLD_LANDMARKS"; constexpr char kHandWorldLandmarksStreamName[] = "world_landmarks"; constexpr int kMicroSecondsPerMilliSecond = 1000; // Creates a MediaPipe graph config that contains a subgraph node of // "mediapipe.tasks.vision.GestureRecognizerGraph". If the task is running // in the live stream mode, a "FlowLimiterCalculator" will be added to limit the // number of frames in flight. CalculatorGraphConfig CreateGraphConfig( std::unique_ptr<GestureRecognizerGraphOptionsProto> options, bool enable_flow_limiting) { api2::builder::Graph graph; auto& subgraph = graph.AddNode(kHandGestureSubgraphTypeName); subgraph.GetOptions<GestureRecognizerGraphOptionsProto>().Swap(options.get()); graph.In(kImageTag).SetName(kImageInStreamName); subgraph.Out(kHandGesturesTag).SetName(kHandGesturesStreamName) >> graph.Out(kHandGesturesTag); subgraph.Out(kHandednessTag).SetName(kHandednessStreamName) >> graph.Out(kHandednessTag); subgraph.Out(kHandLandmarksTag).SetName(kHandLandmarksStreamName) >> graph.Out(kHandLandmarksTag); subgraph.Out(kHandWorldLandmarksTag).SetName(kHandWorldLandmarksStreamName) >> graph.Out(kHandWorldLandmarksTag); subgraph.Out(kImageTag).SetName(kImageOutStreamName) >> graph.Out(kImageTag); if (enable_flow_limiting) { return tasks::core::AddFlowLimiterCalculator(graph, subgraph, {kImageTag}, kHandGesturesTag); } graph.In(kImageTag) >> subgraph.In(kImageTag); return graph.GetConfig(); } // Converts the user-facing GestureRecognizerOptions struct to the internal // GestureRecognizerGraphOptions proto. std::unique_ptr<GestureRecognizerGraphOptionsProto> ConvertGestureRecognizerGraphOptionsProto(GestureRecognizerOptions* options) { auto options_proto = std::make_unique<GestureRecognizerGraphOptionsProto>(); bool use_stream_mode = options->running_mode != core::RunningMode::IMAGE; // TODO remove these workarounds for base options of subgraphs. // Configure hand detector options. auto base_options_proto_for_hand_detector = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_hand_detector))); base_options_proto_for_hand_detector->set_use_stream_mode(use_stream_mode); auto* hand_detector_graph_options = options_proto->mutable_hand_landmarker_graph_options() ->mutable_hand_detector_graph_options(); hand_detector_graph_options->mutable_base_options()->Swap( base_options_proto_for_hand_detector.get()); hand_detector_graph_options->set_num_hands(options->num_hands); hand_detector_graph_options->set_min_detection_confidence( options->min_hand_detection_confidence); // Configure hand landmark detector options. auto base_options_proto_for_hand_landmarker = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_hand_landmarker))); base_options_proto_for_hand_landmarker->set_use_stream_mode(use_stream_mode); auto* hand_landmarks_detector_graph_options = options_proto->mutable_hand_landmarker_graph_options() ->mutable_hand_landmarks_detector_graph_options(); hand_landmarks_detector_graph_options->mutable_base_options()->Swap( base_options_proto_for_hand_landmarker.get()); hand_landmarks_detector_graph_options->set_min_detection_confidence( options->min_hand_presence_confidence); auto* hand_landmarker_graph_options = options_proto->mutable_hand_landmarker_graph_options(); hand_landmarker_graph_options->set_min_tracking_confidence( options->min_tracking_confidence); // Configure hand gesture recognizer options. auto base_options_proto_for_gesture_recognizer = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_gesture_recognizer))); base_options_proto_for_gesture_recognizer->set_use_stream_mode( use_stream_mode); auto* hand_gesture_recognizer_graph_options = options_proto->mutable_hand_gesture_recognizer_graph_options(); hand_gesture_recognizer_graph_options->mutable_base_options()->Swap( base_options_proto_for_gesture_recognizer.get()); if (options->min_gesture_confidence >= 0) { hand_gesture_recognizer_graph_options->mutable_classifier_options() ->set_score_threshold(options->min_gesture_confidence); } return options_proto; } } // namespace absl::StatusOr<std::unique_ptr<GestureRecognizer>> GestureRecognizer::Create( std::unique_ptr<GestureRecognizerOptions> options) { auto options_proto = ConvertGestureRecognizerGraphOptionsProto(options.get()); tasks::core::PacketsCallback packets_callback = nullptr; if (options->result_callback) { auto result_callback = options->result_callback; packets_callback = [=](absl::StatusOr<tasks::core::PacketMap> status_or_packets) { if (!status_or_packets.ok()) { Image image; result_callback(status_or_packets.status(), image, Timestamp::Unset().Value()); return; } if (status_or_packets.value()[kImageOutStreamName].IsEmpty()) { return; } Packet gesture_packet = status_or_packets.value()[kHandGesturesStreamName]; Packet handedness_packet = status_or_packets.value()[kHandednessStreamName]; Packet hand_landmarks_packet = status_or_packets.value()[kHandLandmarksStreamName]; Packet hand_world_landmarks_packet = status_or_packets.value()[kHandWorldLandmarksStreamName]; Packet image_packet = status_or_packets.value()[kImageOutStreamName]; result_callback( {{gesture_packet.Get<std::vector<ClassificationList>>(), handedness_packet.Get<std::vector<ClassificationList>>(), hand_landmarks_packet.Get<std::vector<NormalizedLandmarkList>>(), hand_world_landmarks_packet.Get<std::vector<LandmarkList>>()}}, image_packet.Get<Image>(), gesture_packet.Timestamp().Value() / kMicroSecondsPerMilliSecond); }; } return core::VisionTaskApiFactory::Create<GestureRecognizer, GestureRecognizerGraphOptionsProto>( CreateGraphConfig( std::move(options_proto), options->running_mode == core::RunningMode::LIVE_STREAM), std::move(options->base_options.op_resolver), options->running_mode, std::move(packets_callback)); } absl::StatusOr<GestureRecognitionResult> GestureRecognizer::Recognize( mediapipe::Image image) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, "GPU input images are currently not supported.", MediaPipeTasksStatus::kRunnerUnexpectedInputError); } ASSIGN_OR_RETURN(auto output_packets, ProcessImageData({{kImageInStreamName, MakePacket<Image>(std::move(image))}})); return { {/* gestures= */ {output_packets[kHandGesturesStreamName] .Get<std::vector<ClassificationList>>()}, /* handedness= */ {output_packets[kHandednessStreamName] .Get<std::vector<mediapipe::ClassificationList>>()}, /* hand_landmarks= */ {output_packets[kHandLandmarksStreamName] .Get<std::vector<mediapipe::NormalizedLandmarkList>>()}, /* hand_world_landmarks */ {output_packets[kHandWorldLandmarksStreamName] .Get<std::vector<mediapipe::LandmarkList>>()}}, }; } absl::StatusOr<GestureRecognitionResult> GestureRecognizer::RecognizeForVideo( mediapipe::Image image, int64 timestamp_ms) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, absl::StrCat("GPU input images are currently not supported."), MediaPipeTasksStatus::kRunnerUnexpectedInputError); } ASSIGN_OR_RETURN( auto output_packets, ProcessVideoData( {{kImageInStreamName, MakePacket<Image>(std::move(image)) .At(Timestamp(timestamp_ms * kMicroSecondsPerMilliSecond))}})); return { {/* gestures= */ {output_packets[kHandGesturesStreamName] .Get<std::vector<ClassificationList>>()}, /* handedness= */ {output_packets[kHandednessStreamName] .Get<std::vector<mediapipe::ClassificationList>>()}, /* hand_landmarks= */ {output_packets[kHandLandmarksStreamName] .Get<std::vector<mediapipe::NormalizedLandmarkList>>()}, /* hand_world_landmarks */ {output_packets[kHandWorldLandmarksStreamName] .Get<std::vector<mediapipe::LandmarkList>>()}}, }; } absl::Status GestureRecognizer::RecognizeAsync(mediapipe::Image image, int64 timestamp_ms) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, absl::StrCat("GPU input images are currently not supported."), MediaPipeTasksStatus::kRunnerUnexpectedInputError); } return SendLiveStreamData( {{kImageInStreamName, MakePacket<Image>(std::move(image)) .At(Timestamp(timestamp_ms * kMicroSecondsPerMilliSecond))}}); } } // namespace gesture_recognizer } // namespace vision } // namespace tasks } // namespace mediapipe <commit_msg>Fix empty packet bug with no hands detected.<commit_after>/* Copyright 2022 The MediaPipe 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 "mediapipe/tasks/cc/vision/gesture_recognizer/gesture_recognizer.h" #include <memory> #include <type_traits> #include <vector> #include "absl/memory/memory.h" #include "absl/status/status.h" #include "absl/status/statusor.h" #include "mediapipe/framework/api2/builder.h" #include "mediapipe/framework/api2/port.h" #include "mediapipe/framework/formats/classification.pb.h" #include "mediapipe/framework/formats/image.h" #include "mediapipe/framework/formats/landmark.pb.h" #include "mediapipe/framework/packet.h" #include "mediapipe/tasks/cc/common.h" #include "mediapipe/tasks/cc/components/image_preprocessing.h" #include "mediapipe/tasks/cc/components/processors/proto/classifier_options.pb.h" #include "mediapipe/tasks/cc/core/base_task_api.h" #include "mediapipe/tasks/cc/core/model_resources.h" #include "mediapipe/tasks/cc/core/proto/inference_subgraph.pb.h" #include "mediapipe/tasks/cc/core/task_runner.h" #include "mediapipe/tasks/cc/core/utils.h" #include "mediapipe/tasks/cc/vision/core/base_vision_task_api.h" #include "mediapipe/tasks/cc/vision/core/vision_task_api_factory.h" #include "mediapipe/tasks/cc/vision/gesture_recognizer/proto/gesture_recognizer_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/gesture_recognizer/proto/hand_gesture_recognizer_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_detector/proto/hand_detector_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_landmarker/proto/hand_landmarker_graph_options.pb.h" #include "mediapipe/tasks/cc/vision/hand_landmarker/proto/hand_landmarks_detector_graph_options.pb.h" namespace mediapipe { namespace tasks { namespace vision { namespace gesture_recognizer { namespace { using GestureRecognizerGraphOptionsProto = ::mediapipe::tasks::vision:: gesture_recognizer::proto::GestureRecognizerGraphOptions; using ::mediapipe::tasks::components::containers::GestureRecognitionResult; constexpr char kHandGestureSubgraphTypeName[] = "mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"; constexpr char kImageTag[] = "IMAGE"; constexpr char kImageInStreamName[] = "image_in"; constexpr char kImageOutStreamName[] = "image_out"; constexpr char kHandGesturesTag[] = "HAND_GESTURES"; constexpr char kHandGesturesStreamName[] = "hand_gestures"; constexpr char kHandednessTag[] = "HANDEDNESS"; constexpr char kHandednessStreamName[] = "handedness"; constexpr char kHandLandmarksTag[] = "LANDMARKS"; constexpr char kHandLandmarksStreamName[] = "landmarks"; constexpr char kHandWorldLandmarksTag[] = "WORLD_LANDMARKS"; constexpr char kHandWorldLandmarksStreamName[] = "world_landmarks"; constexpr int kMicroSecondsPerMilliSecond = 1000; // Creates a MediaPipe graph config that contains a subgraph node of // "mediapipe.tasks.vision.GestureRecognizerGraph". If the task is running // in the live stream mode, a "FlowLimiterCalculator" will be added to limit the // number of frames in flight. CalculatorGraphConfig CreateGraphConfig( std::unique_ptr<GestureRecognizerGraphOptionsProto> options, bool enable_flow_limiting) { api2::builder::Graph graph; auto& subgraph = graph.AddNode(kHandGestureSubgraphTypeName); subgraph.GetOptions<GestureRecognizerGraphOptionsProto>().Swap(options.get()); graph.In(kImageTag).SetName(kImageInStreamName); subgraph.Out(kHandGesturesTag).SetName(kHandGesturesStreamName) >> graph.Out(kHandGesturesTag); subgraph.Out(kHandednessTag).SetName(kHandednessStreamName) >> graph.Out(kHandednessTag); subgraph.Out(kHandLandmarksTag).SetName(kHandLandmarksStreamName) >> graph.Out(kHandLandmarksTag); subgraph.Out(kHandWorldLandmarksTag).SetName(kHandWorldLandmarksStreamName) >> graph.Out(kHandWorldLandmarksTag); subgraph.Out(kImageTag).SetName(kImageOutStreamName) >> graph.Out(kImageTag); if (enable_flow_limiting) { return tasks::core::AddFlowLimiterCalculator(graph, subgraph, {kImageTag}, kHandGesturesTag); } graph.In(kImageTag) >> subgraph.In(kImageTag); return graph.GetConfig(); } // Converts the user-facing GestureRecognizerOptions struct to the internal // GestureRecognizerGraphOptions proto. std::unique_ptr<GestureRecognizerGraphOptionsProto> ConvertGestureRecognizerGraphOptionsProto(GestureRecognizerOptions* options) { auto options_proto = std::make_unique<GestureRecognizerGraphOptionsProto>(); bool use_stream_mode = options->running_mode != core::RunningMode::IMAGE; // TODO remove these workarounds for base options of subgraphs. // Configure hand detector options. auto base_options_proto_for_hand_detector = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_hand_detector))); base_options_proto_for_hand_detector->set_use_stream_mode(use_stream_mode); auto* hand_detector_graph_options = options_proto->mutable_hand_landmarker_graph_options() ->mutable_hand_detector_graph_options(); hand_detector_graph_options->mutable_base_options()->Swap( base_options_proto_for_hand_detector.get()); hand_detector_graph_options->set_num_hands(options->num_hands); hand_detector_graph_options->set_min_detection_confidence( options->min_hand_detection_confidence); // Configure hand landmark detector options. auto base_options_proto_for_hand_landmarker = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_hand_landmarker))); base_options_proto_for_hand_landmarker->set_use_stream_mode(use_stream_mode); auto* hand_landmarks_detector_graph_options = options_proto->mutable_hand_landmarker_graph_options() ->mutable_hand_landmarks_detector_graph_options(); hand_landmarks_detector_graph_options->mutable_base_options()->Swap( base_options_proto_for_hand_landmarker.get()); hand_landmarks_detector_graph_options->set_min_detection_confidence( options->min_hand_presence_confidence); auto* hand_landmarker_graph_options = options_proto->mutable_hand_landmarker_graph_options(); hand_landmarker_graph_options->set_min_tracking_confidence( options->min_tracking_confidence); // Configure hand gesture recognizer options. auto base_options_proto_for_gesture_recognizer = std::make_unique<tasks::core::proto::BaseOptions>( tasks::core::ConvertBaseOptionsToProto( &(options->base_options_for_gesture_recognizer))); base_options_proto_for_gesture_recognizer->set_use_stream_mode( use_stream_mode); auto* hand_gesture_recognizer_graph_options = options_proto->mutable_hand_gesture_recognizer_graph_options(); hand_gesture_recognizer_graph_options->mutable_base_options()->Swap( base_options_proto_for_gesture_recognizer.get()); if (options->min_gesture_confidence >= 0) { hand_gesture_recognizer_graph_options->mutable_classifier_options() ->set_score_threshold(options->min_gesture_confidence); } return options_proto; } } // namespace absl::StatusOr<std::unique_ptr<GestureRecognizer>> GestureRecognizer::Create( std::unique_ptr<GestureRecognizerOptions> options) { auto options_proto = ConvertGestureRecognizerGraphOptionsProto(options.get()); tasks::core::PacketsCallback packets_callback = nullptr; if (options->result_callback) { auto result_callback = options->result_callback; packets_callback = [=](absl::StatusOr<tasks::core::PacketMap> status_or_packets) { if (!status_or_packets.ok()) { Image image; result_callback(status_or_packets.status(), image, Timestamp::Unset().Value()); return; } if (status_or_packets.value()[kImageOutStreamName].IsEmpty()) { return; } Packet image_packet = status_or_packets.value()[kImageOutStreamName]; if (status_or_packets.value()[kHandGesturesStreamName].IsEmpty()) { Packet empty_packet = status_or_packets.value()[kHandGesturesStreamName]; result_callback( {{{}, {}, {}, {}}}, image_packet.Get<Image>(), empty_packet.Timestamp().Value() / kMicroSecondsPerMilliSecond); return; } Packet gesture_packet = status_or_packets.value()[kHandGesturesStreamName]; Packet handedness_packet = status_or_packets.value()[kHandednessStreamName]; Packet hand_landmarks_packet = status_or_packets.value()[kHandLandmarksStreamName]; Packet hand_world_landmarks_packet = status_or_packets.value()[kHandWorldLandmarksStreamName]; result_callback( {{gesture_packet.Get<std::vector<ClassificationList>>(), handedness_packet.Get<std::vector<ClassificationList>>(), hand_landmarks_packet.Get<std::vector<NormalizedLandmarkList>>(), hand_world_landmarks_packet.Get<std::vector<LandmarkList>>()}}, image_packet.Get<Image>(), gesture_packet.Timestamp().Value() / kMicroSecondsPerMilliSecond); }; } return core::VisionTaskApiFactory::Create<GestureRecognizer, GestureRecognizerGraphOptionsProto>( CreateGraphConfig( std::move(options_proto), options->running_mode == core::RunningMode::LIVE_STREAM), std::move(options->base_options.op_resolver), options->running_mode, std::move(packets_callback)); } absl::StatusOr<GestureRecognitionResult> GestureRecognizer::Recognize( mediapipe::Image image) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, "GPU input images are currently not supported.", MediaPipeTasksStatus::kRunnerUnexpectedInputError); } ASSIGN_OR_RETURN(auto output_packets, ProcessImageData({{kImageInStreamName, MakePacket<Image>(std::move(image))}})); if (output_packets[kHandGesturesStreamName].IsEmpty()) { return {{{}, {}, {}, {}}}; } return { {/* gestures= */ {output_packets[kHandGesturesStreamName] .Get<std::vector<ClassificationList>>()}, /* handedness= */ {output_packets[kHandednessStreamName] .Get<std::vector<mediapipe::ClassificationList>>()}, /* hand_landmarks= */ {output_packets[kHandLandmarksStreamName] .Get<std::vector<mediapipe::NormalizedLandmarkList>>()}, /* hand_world_landmarks */ {output_packets[kHandWorldLandmarksStreamName] .Get<std::vector<mediapipe::LandmarkList>>()}}, }; } absl::StatusOr<GestureRecognitionResult> GestureRecognizer::RecognizeForVideo( mediapipe::Image image, int64 timestamp_ms) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, absl::StrCat("GPU input images are currently not supported."), MediaPipeTasksStatus::kRunnerUnexpectedInputError); } ASSIGN_OR_RETURN( auto output_packets, ProcessVideoData( {{kImageInStreamName, MakePacket<Image>(std::move(image)) .At(Timestamp(timestamp_ms * kMicroSecondsPerMilliSecond))}})); if (output_packets[kHandGesturesStreamName].IsEmpty()) { return {{{}, {}, {}, {}}}; } return { {/* gestures= */ {output_packets[kHandGesturesStreamName] .Get<std::vector<ClassificationList>>()}, /* handedness= */ {output_packets[kHandednessStreamName] .Get<std::vector<mediapipe::ClassificationList>>()}, /* hand_landmarks= */ {output_packets[kHandLandmarksStreamName] .Get<std::vector<mediapipe::NormalizedLandmarkList>>()}, /* hand_world_landmarks */ {output_packets[kHandWorldLandmarksStreamName] .Get<std::vector<mediapipe::LandmarkList>>()}}, }; } absl::Status GestureRecognizer::RecognizeAsync(mediapipe::Image image, int64 timestamp_ms) { if (image.UsesGpu()) { return CreateStatusWithPayload( absl::StatusCode::kInvalidArgument, absl::StrCat("GPU input images are currently not supported."), MediaPipeTasksStatus::kRunnerUnexpectedInputError); } return SendLiveStreamData( {{kImageInStreamName, MakePacket<Image>(std::move(image)) .At(Timestamp(timestamp_ms * kMicroSecondsPerMilliSecond))}}); } } // namespace gesture_recognizer } // namespace vision } // namespace tasks } // namespace mediapipe <|endoftext|>
<commit_before><commit_msg>Planning: reduced the distance for cost calculation.<commit_after><|endoftext|>
<commit_before><commit_msg>prediction: bug fix for null pointer issue in FeatureExtractor<commit_after><|endoftext|>
<commit_before>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditoritem.h" #include "formeditorscene.h" #include "formeditornodeinstanceview.h" #include "selectiontool.h" #include <modelnode.h> #include <nodemetainfo.h> #include <widgetqueryview.h> #include <QGraphicsSceneMouseEvent> #include <QDebug> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QGraphicsView> #include <QTimeLine> #include <cmath> #include <invalidmodelnodeexception.h> #include <invalidnodestateexception.h> namespace QmlDesigner { FormEditorScene *FormEditorItem::scene() const { return qobject_cast<FormEditorScene*>(QGraphicsItem::scene()); } FormEditorItem::FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene* scene) : QGraphicsObject(scene->formLayerItem()), m_snappingLineCreator(this), m_qmlItemNode(qmlItemNode), m_borderWidth(1.0), m_opacity(0.6) { setCacheMode(QGraphicsItem::DeviceCoordinateCache); setup(); } void FormEditorItem::setup() { if (qmlItemNode().hasInstanceParent()) setParentItem(scene()->itemForQmlItemNode(qmlItemNode().instanceParent().toQmlItemNode())); if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = 0.0; setFlag(QGraphicsItem::ItemIsMovable, true); updateGeometry(); updateVisibilty(); } QRectF FormEditorItem::boundingRect() const { return m_boundingRect; } void FormEditorItem::updateGeometry() { prepareGeometryChange(); m_boundingRect = qmlItemNode().instanceBoundingRect().adjusted(0, 0, 1., 1.); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); //the property for zValue is called z in QGraphicsObject Q_ASSERT(qmlItemNode().instanceValue("z").isValid()); setZValue(qmlItemNode().instanceValue("z").toDouble()); } void FormEditorItem::updateVisibilty() { // setVisible(nodeInstance().isVisible()); // setOpacity(nodeInstance().opacity()); } void FormEditorItem::showAttention() { if (m_attentionTimeLine.isNull()) { m_attentionTimeLine = new QTimeLine(500, this); m_attentionTimeLine->setCurveShape(QTimeLine::SineCurve); connect(m_attentionTimeLine.data(), SIGNAL(valueChanged(qreal)), SLOT(changeAttention(qreal))); connect(m_attentionTimeLine.data(), SIGNAL(finished()), m_attentionTimeLine.data(), SLOT(deleteLater())); m_attentionTimeLine->start(); } } void FormEditorItem::changeAttention(qreal value) { if (QGraphicsItem::parentItem() == scene()->formLayerItem()) { setAttentionHighlight(value); } else { setAttentionHighlight(value); setAttentionScale(value); } } FormEditorView *FormEditorItem::formEditorView() const { return scene()->editorView(); } void FormEditorItem::setAttentionScale(double sinusScale) { if (!qFuzzyIsNull(sinusScale)) { double scale = std::sqrt(sinusScale); m_attentionTransform.reset(); QPointF centerPoint(qmlItemNode().instanceBoundingRect().center()); m_attentionTransform.translate(centerPoint.x(), centerPoint.y()); m_attentionTransform.scale(scale * 0.15 + 1.0, scale * 0.15 + 1.0); m_attentionTransform.translate(-centerPoint.x(), -centerPoint.y()); m_inverseAttentionTransform = m_attentionTransform.inverted(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); } else { m_attentionTransform.reset(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); } } void FormEditorItem::setAttentionHighlight(double value) { m_opacity = 0.6 + value; if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = value * 4; else m_borderWidth = 1. + value * 3; update(); } void FormEditorItem::setHighlightBoundingRect(bool highlight) { if (m_highlightBoundingRect != highlight) { m_highlightBoundingRect = highlight; update(); } } FormEditorItem::~FormEditorItem() { scene()->removeItemFromHash(this); } /* \brief returns the parent item skipping all proxyItem*/ FormEditorItem *FormEditorItem::parentItem() const { return qgraphicsitem_cast<FormEditorItem*> (QGraphicsItem::parentItem()); } FormEditorItem* FormEditorItem::fromQGraphicsItem(QGraphicsItem *graphicsItem) { return qgraphicsitem_cast<FormEditorItem*>(graphicsItem); } //static QRectF alignedRect(const QRectF &rect) //{ // QRectF alignedRect(rect); // alignedRect.setTop(std::floor(rect.top()) + 0.5); // alignedRect.setBottom(std::floor(rect.bottom()) + 0.5); // alignedRect.setLeft(std::floor(rect.left()) + 0.5); // alignedRect.setRight(std::floor(rect.right()) + 0.5); // // return alignedRect; //} void FormEditorItem::paintBoundingRect(QPainter *painter) const { if (QGraphicsItem::parentItem() == scene()->formLayerItem() && qFuzzyIsNull(m_borderWidth)) return; QPen pen; pen.setJoinStyle(Qt::MiterJoin); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: { pen.setColor(Qt::black); pen.setWidth(m_borderWidth); } break; case FormEditorScene::NormalMode: { if (m_highlightBoundingRect) pen.setColor("#AAAAAA"); else pen.setColor("#888888"); } break; } painter->setPen(pen); // int offset = m_borderWidth / 2; painter->drawRect(boundingRect().adjusted(0., 0., -1., -1.)); } void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (!qmlItemNode().isValid()) return; painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: painter->setOpacity(m_opacity); break; case FormEditorScene::NormalMode: painter->setOpacity(qmlItemNode().instanceValue("opacity").toDouble()); break; } qmlItemNode().paintInstance(painter); painter->setRenderHint(QPainter::Antialiasing, false); if (scene()->showBoundingRects() || m_highlightBoundingRect) paintBoundingRect(painter); painter->restore(); } AbstractFormEditorTool* FormEditorItem::tool() const { return static_cast<FormEditorScene*>(scene())->currentTool(); } SnapLineMap FormEditorItem::topSnappingLines() const { return m_snappingLineCreator.topLines(); } SnapLineMap FormEditorItem::bottomSnappingLines() const { return m_snappingLineCreator.bottomLines(); } SnapLineMap FormEditorItem::leftSnappingLines() const { return m_snappingLineCreator.leftLines(); } SnapLineMap FormEditorItem::rightSnappingLines() const { return m_snappingLineCreator.rightLines(); } SnapLineMap FormEditorItem::horizontalCenterSnappingLines() const { return m_snappingLineCreator.horizontalCenterLines(); } SnapLineMap FormEditorItem::verticalCenterSnappingLines() const { return m_snappingLineCreator.verticalCenterLines(); } SnapLineMap FormEditorItem::topSnappingOffsets() const { return m_snappingLineCreator.topOffsets(); } SnapLineMap FormEditorItem::bottomSnappingOffsets() const { return m_snappingLineCreator.bottomOffsets(); } SnapLineMap FormEditorItem::leftSnappingOffsets() const { return m_snappingLineCreator.leftOffsets(); } SnapLineMap FormEditorItem::rightSnappingOffsets() const { return m_snappingLineCreator.rightOffsets(); } void FormEditorItem::updateSnappingLines(const QList<FormEditorItem*> &exceptionList, FormEditorItem *transformationSpaceItem) { m_snappingLineCreator.update(exceptionList, transformationSpaceItem); } QList<FormEditorItem*> FormEditorItem::childFormEditorItems() const { QList<FormEditorItem*> formEditorItemList; foreach (QGraphicsItem *item, childItems()) { FormEditorItem *formEditorItem = fromQGraphicsItem(item); if (formEditorItem) formEditorItemList.append(formEditorItem); } return formEditorItemList; } bool FormEditorItem::isContainer() const { return qmlItemNode().modelNode().metaInfo().isContainer(); } QmlItemNode FormEditorItem::qmlItemNode() const { return m_qmlItemNode; } } <commit_msg>Fix drawing bug in bounding rect for form editor items<commit_after>/************************************************************************** ** ** This file is part of Qt Creator ** ** Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies). ** ** Contact: Nokia Corporation ([email protected]) ** ** Commercial Usage ** ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** If you are unsure which license is appropriate for your use, please ** contact the sales department at http://qt.nokia.com/contact. ** **************************************************************************/ #include "formeditoritem.h" #include "formeditorscene.h" #include "formeditornodeinstanceview.h" #include "selectiontool.h" #include <modelnode.h> #include <nodemetainfo.h> #include <widgetqueryview.h> #include <QGraphicsSceneMouseEvent> #include <QDebug> #include <QPainter> #include <QStyleOptionGraphicsItem> #include <QGraphicsView> #include <QTimeLine> #include <cmath> #include <invalidmodelnodeexception.h> #include <invalidnodestateexception.h> namespace QmlDesigner { FormEditorScene *FormEditorItem::scene() const { return qobject_cast<FormEditorScene*>(QGraphicsItem::scene()); } FormEditorItem::FormEditorItem(const QmlItemNode &qmlItemNode, FormEditorScene* scene) : QGraphicsObject(scene->formLayerItem()), m_snappingLineCreator(this), m_qmlItemNode(qmlItemNode), m_borderWidth(1.0), m_opacity(0.6), m_highlightBoundingRect(false) { setCacheMode(QGraphicsItem::DeviceCoordinateCache); setup(); } void FormEditorItem::setup() { if (qmlItemNode().hasInstanceParent()) setParentItem(scene()->itemForQmlItemNode(qmlItemNode().instanceParent().toQmlItemNode())); if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = 0.0; setFlag(QGraphicsItem::ItemIsMovable, true); updateGeometry(); updateVisibilty(); } QRectF FormEditorItem::boundingRect() const { return m_boundingRect; } void FormEditorItem::updateGeometry() { prepareGeometryChange(); m_boundingRect = qmlItemNode().instanceBoundingRect().adjusted(0, 0, 1., 1.); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); //the property for zValue is called z in QGraphicsObject Q_ASSERT(qmlItemNode().instanceValue("z").isValid()); setZValue(qmlItemNode().instanceValue("z").toDouble()); } void FormEditorItem::updateVisibilty() { // setVisible(nodeInstance().isVisible()); // setOpacity(nodeInstance().opacity()); } void FormEditorItem::showAttention() { if (m_attentionTimeLine.isNull()) { m_attentionTimeLine = new QTimeLine(500, this); m_attentionTimeLine->setCurveShape(QTimeLine::SineCurve); connect(m_attentionTimeLine.data(), SIGNAL(valueChanged(qreal)), SLOT(changeAttention(qreal))); connect(m_attentionTimeLine.data(), SIGNAL(finished()), m_attentionTimeLine.data(), SLOT(deleteLater())); m_attentionTimeLine->start(); } } void FormEditorItem::changeAttention(qreal value) { if (QGraphicsItem::parentItem() == scene()->formLayerItem()) { setAttentionHighlight(value); } else { setAttentionHighlight(value); setAttentionScale(value); } } FormEditorView *FormEditorItem::formEditorView() const { return scene()->editorView(); } void FormEditorItem::setAttentionScale(double sinusScale) { if (!qFuzzyIsNull(sinusScale)) { double scale = std::sqrt(sinusScale); m_attentionTransform.reset(); QPointF centerPoint(qmlItemNode().instanceBoundingRect().center()); m_attentionTransform.translate(centerPoint.x(), centerPoint.y()); m_attentionTransform.scale(scale * 0.15 + 1.0, scale * 0.15 + 1.0); m_attentionTransform.translate(-centerPoint.x(), -centerPoint.y()); m_inverseAttentionTransform = m_attentionTransform.inverted(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); setTransform(m_attentionTransform, true); } else { m_attentionTransform.reset(); prepareGeometryChange(); setTransform(qmlItemNode().instanceTransform()); } } void FormEditorItem::setAttentionHighlight(double value) { m_opacity = 0.6 + value; if (QGraphicsItem::parentItem() == scene()->formLayerItem()) m_borderWidth = value * 4; else m_borderWidth = 1. + value * 3; update(); } void FormEditorItem::setHighlightBoundingRect(bool highlight) { if (m_highlightBoundingRect != highlight) { m_highlightBoundingRect = highlight; update(); } } FormEditorItem::~FormEditorItem() { scene()->removeItemFromHash(this); } /* \brief returns the parent item skipping all proxyItem*/ FormEditorItem *FormEditorItem::parentItem() const { return qgraphicsitem_cast<FormEditorItem*> (QGraphicsItem::parentItem()); } FormEditorItem* FormEditorItem::fromQGraphicsItem(QGraphicsItem *graphicsItem) { return qgraphicsitem_cast<FormEditorItem*>(graphicsItem); } //static QRectF alignedRect(const QRectF &rect) //{ // QRectF alignedRect(rect); // alignedRect.setTop(std::floor(rect.top()) + 0.5); // alignedRect.setBottom(std::floor(rect.bottom()) + 0.5); // alignedRect.setLeft(std::floor(rect.left()) + 0.5); // alignedRect.setRight(std::floor(rect.right()) + 0.5); // // return alignedRect; //} void FormEditorItem::paintBoundingRect(QPainter *painter) const { if (QGraphicsItem::parentItem() == scene()->formLayerItem() && qFuzzyIsNull(m_borderWidth)) return; QPen pen; pen.setJoinStyle(Qt::MiterJoin); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: { pen.setColor(Qt::black); pen.setWidth(m_borderWidth); } break; case FormEditorScene::NormalMode: { if (scene()->showBoundingRects()) { if (m_highlightBoundingRect) pen.setColor("#AAAAAA"); else pen.setColor("#888888"); } else { if (m_highlightBoundingRect) pen.setColor("#AAAAAA"); else pen.setColor(Qt::transparent); } } break; } painter->setPen(pen); // int offset = m_borderWidth / 2; painter->drawRect(boundingRect().adjusted(0., 0., -1., -1.)); } void FormEditorItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *) { if (!qmlItemNode().isValid()) return; painter->save(); painter->setRenderHint(QPainter::Antialiasing, true); switch(scene()->paintMode()) { case FormEditorScene::AnchorMode: painter->setOpacity(m_opacity); break; case FormEditorScene::NormalMode: painter->setOpacity(qmlItemNode().instanceValue("opacity").toDouble()); break; } qmlItemNode().paintInstance(painter); painter->setRenderHint(QPainter::Antialiasing, false); paintBoundingRect(painter); painter->restore(); } AbstractFormEditorTool* FormEditorItem::tool() const { return static_cast<FormEditorScene*>(scene())->currentTool(); } SnapLineMap FormEditorItem::topSnappingLines() const { return m_snappingLineCreator.topLines(); } SnapLineMap FormEditorItem::bottomSnappingLines() const { return m_snappingLineCreator.bottomLines(); } SnapLineMap FormEditorItem::leftSnappingLines() const { return m_snappingLineCreator.leftLines(); } SnapLineMap FormEditorItem::rightSnappingLines() const { return m_snappingLineCreator.rightLines(); } SnapLineMap FormEditorItem::horizontalCenterSnappingLines() const { return m_snappingLineCreator.horizontalCenterLines(); } SnapLineMap FormEditorItem::verticalCenterSnappingLines() const { return m_snappingLineCreator.verticalCenterLines(); } SnapLineMap FormEditorItem::topSnappingOffsets() const { return m_snappingLineCreator.topOffsets(); } SnapLineMap FormEditorItem::bottomSnappingOffsets() const { return m_snappingLineCreator.bottomOffsets(); } SnapLineMap FormEditorItem::leftSnappingOffsets() const { return m_snappingLineCreator.leftOffsets(); } SnapLineMap FormEditorItem::rightSnappingOffsets() const { return m_snappingLineCreator.rightOffsets(); } void FormEditorItem::updateSnappingLines(const QList<FormEditorItem*> &exceptionList, FormEditorItem *transformationSpaceItem) { m_snappingLineCreator.update(exceptionList, transformationSpaceItem); } QList<FormEditorItem*> FormEditorItem::childFormEditorItems() const { QList<FormEditorItem*> formEditorItemList; foreach (QGraphicsItem *item, childItems()) { FormEditorItem *formEditorItem = fromQGraphicsItem(item); if (formEditorItem) formEditorItemList.append(formEditorItem); } return formEditorItemList; } bool FormEditorItem::isContainer() const { return qmlItemNode().modelNode().metaInfo().isContainer(); } QmlItemNode FormEditorItem::qmlItemNode() const { return m_qmlItemNode; } } <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "puppetcreator.h" #include <QProcess> #include <QTemporaryDir> #include <QCoreApplication> #include <QCryptographicHash> #include <QDateTime> #include <QMessageBox> #include <QThread> #include <projectexplorer/kit.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <coreplugin/icore.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include <coreplugin/icore.h> #include <qmldesignerwarning.h> #include "puppetbuildprogressdialog.h" namespace QmlDesigner { bool PuppetCreator::m_useOnlyFallbackPuppet = !qgetenv("USE_ONLY_FALLBACK_PUPPET").isEmpty(); QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml1PuppetForKitPuppetHash; QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml2PuppetForKitPuppetHash; QByteArray PuppetCreator::qtHash() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QCryptographicHash::hash(currentQtVersion->qmakeProperty("QT_INSTALL_DATA").toUtf8(), QCryptographicHash::Sha1).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); } return QByteArray(); } QDateTime PuppetCreator::qtLastModified() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QFileInfo(currentQtVersion->qmakeProperty("QT_INSTALL_LIBS")).lastModified(); } return QDateTime(); } PuppetCreator::PuppetCreator(ProjectExplorer::Kit *kit, const QString &qtCreatorVersion) : m_qtCreatorVersion(qtCreatorVersion), m_kit(kit), m_availablePuppetType(FallbackPuppet) { } PuppetCreator::~PuppetCreator() { } void PuppetCreator::createPuppetExecutableIfMissing(PuppetCreator::QmlPuppetVersion puppetVersion) { if (puppetVersion == Qml1Puppet) createQml1PuppetExecutableIfMissing(); else createQml2PuppetExecutableIfMissing(); } QProcess *PuppetCreator::createPuppetProcess(PuppetCreator::QmlPuppetVersion puppetVersion, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QString puppetPath; if (puppetVersion == Qml1Puppet) puppetPath = qmlpuppetPath(m_availablePuppetType); else puppetPath = qml2puppetPath(m_availablePuppetType); return puppetProcess(puppetPath, puppetMode, socketToken, handlerObject, outputSlot, finishSlot); } QProcess *PuppetCreator::puppetProcess(const QString &puppetPath, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QProcess *puppetProcess = new QProcess; puppetProcess->setObjectName(puppetMode); puppetProcess->setProcessEnvironment(processEnvironment()); QObject::connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), puppetProcess, SLOT(kill())); QObject::connect(puppetProcess, SIGNAL(finished(int,QProcess::ExitStatus)), handlerObject, finishSlot); bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty(); if (fowardQmlpuppetOutput) { puppetProcess->setProcessChannelMode(QProcess::MergedChannels); QObject::connect(puppetProcess, SIGNAL(readyRead()), handlerObject, outputSlot); } puppetProcess->start(puppetPath, QStringList() << socketToken << puppetMode << "-graphicssystem raster"); if (!qgetenv("DEBUG_QML_PUPPET").isEmpty()) QMessageBox::information(Core::ICore::dialogParent(), QStringLiteral("Puppet is starting ..."), QStringLiteral("You can now attach your debugger to the puppet.")); return puppetProcess; } static QString idealProcessCount() { int processCount = QThread::idealThreadCount() + 1; if (processCount < 1) processCount = 4; return QString::number(processCount); } bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const { PuppetBuildProgressDialog progressDialog; m_compileLog.clear(); QTemporaryDir buildDirectory; bool buildSucceeded = false; if (qtIsSupported()) { if (buildDirectory.isValid()) { QStringList qmakeArguments; qmakeArguments.append(QStringLiteral("-r")); qmakeArguments.append(QStringLiteral("-after")); qmakeArguments.append(QStringLiteral("DESTDIR=") + qmlpuppetDirectory(UserSpacePuppet)); #ifndef QT_DEBUG qmakeArguments.append(QStringLiteral("CONFIG+=release")); #endif qmakeArguments.append(qmlPuppetProjectFilePath); buildSucceeded = startBuildProcess(buildDirectory.path(), qmakeCommand(), qmakeArguments); if (buildSucceeded) { progressDialog.show(); QString buildingCommand = buildCommand(); QStringList buildArguments; if (buildingCommand.contains("make")) { buildArguments.append(QStringLiteral("-j")); buildArguments.append(idealProcessCount()); } buildSucceeded = startBuildProcess(buildDirectory.path(), buildingCommand, buildArguments, &progressDialog); progressDialog.close(); } if (!buildSucceeded) QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Emulation layer building was unsuccessful"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built. " "The fallback emulation layer, which does not support all features, will be used." )); } } else { QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Qt Version is not supported"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built because the Qt version is too old " "or it cannot run natively on your computer. " "The fallback emulation layer, which does not support all features, will be used." )); } return buildSucceeded; } static void warnAboutInvalidKit() { QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Kit is invalid"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built because the kit is not configured correctly. " "For example the compiler can be misconfigured. " "Fix the kit configuration and restart Qt Creator. " "Otherwise, the fallback emulation layer, which does not support all features, will be used." )); } void PuppetCreator::createQml1PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml1PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml1PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQmlpuppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { if (m_kit->isValid()) { bool buildSucceeded = build(qmlpuppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } else { warnAboutInvalidKit(); m_availablePuppetType = FallbackPuppet; } m_qml1PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } } else { m_availablePuppetType = FallbackPuppet; } } void PuppetCreator::createQml2PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml2PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml2PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQml2puppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { if (m_kit->isValid()) { bool buildSucceeded = build(qml2puppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } else { warnAboutInvalidKit(); m_availablePuppetType = FallbackPuppet; } m_qml2PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } } else { m_availablePuppetType = FallbackPuppet; } } QString PuppetCreator::qmlpuppetDirectory(PuppetType puppetType) const { if (puppetType == UserSpacePuppet) return Core::ICore::userResourcePath() + QStringLiteral("/qmlpuppet/") + QCoreApplication::applicationVersion() + QStringLiteral("/") + qtHash(); return qmlpuppetFallbackDirectory(); } QString PuppetCreator::qmlpuppetFallbackDirectory() const { return QCoreApplication::applicationDirPath(); } QString PuppetCreator::qml2puppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qml2puppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QString PuppetCreator::qmlpuppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qmlpuppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QProcessEnvironment PuppetCreator::processEnvironment() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); environment.set("QML_BAD_GUI_RENDER_LOOP", "true"); environment.set("QML_USE_MOCKUPS", "true"); environment.set("QML_PUPPET_MODE", "true"); return environment.toProcessEnvironment(); } QString PuppetCreator::buildCommand() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); ProjectExplorer::ToolChain *toolChain = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit); if (toolChain) return toolChain->makeCommand(environment); return QString(); } QString PuppetCreator::qmakeCommand() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return currentQtVersion->qmakeCommand().toString(); return QString(); } QString PuppetCreator::compileLog() const { return m_compileLog; } bool PuppetCreator::startBuildProcess(const QString &buildDirectoryPath, const QString &command, const QStringList &processArguments, PuppetBuildProgressDialog *progressDialog) const { if (command.isEmpty()) return false; QProcess process; process.setProcessChannelMode(QProcess::SeparateChannels); process.setProcessEnvironment(processEnvironment()); process.setWorkingDirectory(buildDirectoryPath); process.start(command, processArguments); process.waitForStarted(); while (process.waitForReadyRead(-1)) { QByteArray newOutput = process.readAllStandardOutput(); if (progressDialog) progressDialog->newBuildOutput(newOutput); m_compileLog.append(newOutput); } process.waitForFinished(); if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) return true; else return false; } QString PuppetCreator::puppetSourceDirectoryPath() { return Core::ICore::resourcePath() + QStringLiteral("/qml/qmlpuppet"); } QString PuppetCreator::qml2puppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qml2puppet/qml2puppet.pro"); } QString PuppetCreator::qmlpuppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qmlpuppet/qmlpuppet.pro"); } bool PuppetCreator::checkPuppetIsReady(const QString &puppetPath) const { QFileInfo puppetFileInfo(puppetPath); return puppetFileInfo.exists() && puppetFileInfo.lastModified() > qtLastModified(); } bool PuppetCreator::checkQml2puppetIsReady() const { return checkPuppetIsReady(qml2puppetPath(UserSpacePuppet)); } bool PuppetCreator::checkQmlpuppetIsReady() const { return checkPuppetIsReady(qmlpuppetPath(UserSpacePuppet)); } bool PuppetCreator::qtIsSupported() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion && currentQtVersion->isValid() && currentQtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0) && (currentQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT) || currentQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))) return true; return false; } bool PuppetCreator::checkPuppetVersion(const QString &qmlPuppetPath) { QProcess qmlPuppetVersionProcess; qmlPuppetVersionProcess.start(qmlPuppetPath, QStringList() << "--version"); qmlPuppetVersionProcess.waitForReadyRead(6000); QByteArray versionString = qmlPuppetVersionProcess.readAll(); bool canConvert; unsigned int versionNumber = versionString.toUInt(&canConvert); return canConvert && versionNumber == 2; } } // namespace QmlDesigner <commit_msg>QmlDesigner: Use -j X only for make<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "puppetcreator.h" #include <QProcess> #include <QTemporaryDir> #include <QCoreApplication> #include <QCryptographicHash> #include <QDateTime> #include <QMessageBox> #include <QThread> #include <projectexplorer/kit.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <coreplugin/icore.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include <coreplugin/icore.h> #include <qmldesignerwarning.h> #include "puppetbuildprogressdialog.h" namespace QmlDesigner { bool PuppetCreator::m_useOnlyFallbackPuppet = !qgetenv("USE_ONLY_FALLBACK_PUPPET").isEmpty(); QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml1PuppetForKitPuppetHash; QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml2PuppetForKitPuppetHash; QByteArray PuppetCreator::qtHash() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QCryptographicHash::hash(currentQtVersion->qmakeProperty("QT_INSTALL_DATA").toUtf8(), QCryptographicHash::Sha1).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); } return QByteArray(); } QDateTime PuppetCreator::qtLastModified() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QFileInfo(currentQtVersion->qmakeProperty("QT_INSTALL_LIBS")).lastModified(); } return QDateTime(); } PuppetCreator::PuppetCreator(ProjectExplorer::Kit *kit, const QString &qtCreatorVersion) : m_qtCreatorVersion(qtCreatorVersion), m_kit(kit), m_availablePuppetType(FallbackPuppet) { } PuppetCreator::~PuppetCreator() { } void PuppetCreator::createPuppetExecutableIfMissing(PuppetCreator::QmlPuppetVersion puppetVersion) { if (puppetVersion == Qml1Puppet) createQml1PuppetExecutableIfMissing(); else createQml2PuppetExecutableIfMissing(); } QProcess *PuppetCreator::createPuppetProcess(PuppetCreator::QmlPuppetVersion puppetVersion, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QString puppetPath; if (puppetVersion == Qml1Puppet) puppetPath = qmlpuppetPath(m_availablePuppetType); else puppetPath = qml2puppetPath(m_availablePuppetType); return puppetProcess(puppetPath, puppetMode, socketToken, handlerObject, outputSlot, finishSlot); } QProcess *PuppetCreator::puppetProcess(const QString &puppetPath, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QProcess *puppetProcess = new QProcess; puppetProcess->setObjectName(puppetMode); puppetProcess->setProcessEnvironment(processEnvironment()); QObject::connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), puppetProcess, SLOT(kill())); QObject::connect(puppetProcess, SIGNAL(finished(int,QProcess::ExitStatus)), handlerObject, finishSlot); bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty(); if (fowardQmlpuppetOutput) { puppetProcess->setProcessChannelMode(QProcess::MergedChannels); QObject::connect(puppetProcess, SIGNAL(readyRead()), handlerObject, outputSlot); } puppetProcess->start(puppetPath, QStringList() << socketToken << puppetMode << "-graphicssystem raster"); if (!qgetenv("DEBUG_QML_PUPPET").isEmpty()) QMessageBox::information(Core::ICore::dialogParent(), QStringLiteral("Puppet is starting ..."), QStringLiteral("You can now attach your debugger to the puppet.")); return puppetProcess; } static QString idealProcessCount() { int processCount = QThread::idealThreadCount() + 1; if (processCount < 1) processCount = 4; return QString::number(processCount); } bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const { PuppetBuildProgressDialog progressDialog; m_compileLog.clear(); QTemporaryDir buildDirectory; bool buildSucceeded = false; if (qtIsSupported()) { if (buildDirectory.isValid()) { QStringList qmakeArguments; qmakeArguments.append(QStringLiteral("-r")); qmakeArguments.append(QStringLiteral("-after")); qmakeArguments.append(QStringLiteral("DESTDIR=") + qmlpuppetDirectory(UserSpacePuppet)); #ifndef QT_DEBUG qmakeArguments.append(QStringLiteral("CONFIG+=release")); #endif qmakeArguments.append(qmlPuppetProjectFilePath); buildSucceeded = startBuildProcess(buildDirectory.path(), qmakeCommand(), qmakeArguments); if (buildSucceeded) { progressDialog.show(); QString buildingCommand = buildCommand(); QStringList buildArguments; if (buildingCommand == QStringLiteral("make")) { buildArguments.append(QStringLiteral("-j")); buildArguments.append(idealProcessCount()); } buildSucceeded = startBuildProcess(buildDirectory.path(), buildingCommand, buildArguments, &progressDialog); progressDialog.close(); } if (!buildSucceeded) QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Emulation layer building was unsuccessful"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built. " "The fallback emulation layer, which does not support all features, will be used." )); } } else { QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Qt Version is not supported"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built because the Qt version is too old " "or it cannot run natively on your computer. " "The fallback emulation layer, which does not support all features, will be used." )); } return buildSucceeded; } static void warnAboutInvalidKit() { QmlDesignerWarning::show(QCoreApplication::translate("PuppetCreator", "Kit is invalid"), QCoreApplication::translate("PuppetCreator", "The emulation layer (Qml Puppet) cannot be built because the kit is not configured correctly. " "For example the compiler can be misconfigured. " "Fix the kit configuration and restart Qt Creator. " "Otherwise, the fallback emulation layer, which does not support all features, will be used." )); } void PuppetCreator::createQml1PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml1PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml1PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQmlpuppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { if (m_kit->isValid()) { bool buildSucceeded = build(qmlpuppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } else { warnAboutInvalidKit(); m_availablePuppetType = FallbackPuppet; } m_qml1PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } } else { m_availablePuppetType = FallbackPuppet; } } void PuppetCreator::createQml2PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml2PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml2PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQml2puppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { if (m_kit->isValid()) { bool buildSucceeded = build(qml2puppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } else { warnAboutInvalidKit(); m_availablePuppetType = FallbackPuppet; } m_qml2PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } } else { m_availablePuppetType = FallbackPuppet; } } QString PuppetCreator::qmlpuppetDirectory(PuppetType puppetType) const { if (puppetType == UserSpacePuppet) return Core::ICore::userResourcePath() + QStringLiteral("/qmlpuppet/") + QCoreApplication::applicationVersion() + QStringLiteral("/") + qtHash(); return qmlpuppetFallbackDirectory(); } QString PuppetCreator::qmlpuppetFallbackDirectory() const { return QCoreApplication::applicationDirPath(); } QString PuppetCreator::qml2puppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qml2puppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QString PuppetCreator::qmlpuppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qmlpuppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QProcessEnvironment PuppetCreator::processEnvironment() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); environment.set("QML_BAD_GUI_RENDER_LOOP", "true"); environment.set("QML_USE_MOCKUPS", "true"); environment.set("QML_PUPPET_MODE", "true"); return environment.toProcessEnvironment(); } QString PuppetCreator::buildCommand() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); ProjectExplorer::ToolChain *toolChain = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit); if (toolChain) return toolChain->makeCommand(environment); return QString(); } QString PuppetCreator::qmakeCommand() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return currentQtVersion->qmakeCommand().toString(); return QString(); } QString PuppetCreator::compileLog() const { return m_compileLog; } bool PuppetCreator::startBuildProcess(const QString &buildDirectoryPath, const QString &command, const QStringList &processArguments, PuppetBuildProgressDialog *progressDialog) const { if (command.isEmpty()) return false; QProcess process; process.setProcessChannelMode(QProcess::SeparateChannels); process.setProcessEnvironment(processEnvironment()); process.setWorkingDirectory(buildDirectoryPath); process.start(command, processArguments); process.waitForStarted(); while (process.waitForReadyRead(-1)) { QByteArray newOutput = process.readAllStandardOutput(); if (progressDialog) progressDialog->newBuildOutput(newOutput); m_compileLog.append(newOutput); } process.waitForFinished(); if (process.exitStatus() == QProcess::NormalExit && process.exitCode() == 0) return true; else return false; } QString PuppetCreator::puppetSourceDirectoryPath() { return Core::ICore::resourcePath() + QStringLiteral("/qml/qmlpuppet"); } QString PuppetCreator::qml2puppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qml2puppet/qml2puppet.pro"); } QString PuppetCreator::qmlpuppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qmlpuppet/qmlpuppet.pro"); } bool PuppetCreator::checkPuppetIsReady(const QString &puppetPath) const { QFileInfo puppetFileInfo(puppetPath); return puppetFileInfo.exists() && puppetFileInfo.lastModified() > qtLastModified(); } bool PuppetCreator::checkQml2puppetIsReady() const { return checkPuppetIsReady(qml2puppetPath(UserSpacePuppet)); } bool PuppetCreator::checkQmlpuppetIsReady() const { return checkPuppetIsReady(qmlpuppetPath(UserSpacePuppet)); } bool PuppetCreator::qtIsSupported() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion && currentQtVersion->isValid() && currentQtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0) && (currentQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT) || currentQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))) return true; return false; } bool PuppetCreator::checkPuppetVersion(const QString &qmlPuppetPath) { QProcess qmlPuppetVersionProcess; qmlPuppetVersionProcess.start(qmlPuppetPath, QStringList() << "--version"); qmlPuppetVersionProcess.waitForReadyRead(6000); QByteArray versionString = qmlPuppetVersionProcess.readAll(); bool canConvert; unsigned int versionNumber = versionString.toUInt(&canConvert); return canConvert && versionNumber == 2; } } // namespace QmlDesigner <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "puppetcreator.h" #include <QProcess> #include <QTemporaryDir> #include <QCoreApplication> #include <QCryptographicHash> #include <QDateTime> #include <projectexplorer/kit.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <coreplugin/icore.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include "puppetbuildprogressdialog.h" #include <QtDebug> namespace QmlDesigner { bool PuppetCreator::m_useOnlyFallbackPuppet = !qgetenv("USE_ONLY_FALLBACK_PUPPET").isEmpty(); QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml1PuppetForKitPuppetHash; QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml2PuppetForKitPuppetHash; QByteArray PuppetCreator::qtHash() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QCryptographicHash::hash(currentQtVersion->qmakeProperty("QT_INSTALL_DATA").toUtf8(), QCryptographicHash::Sha1).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); } return QByteArray(); } QDateTime PuppetCreator::qtLastModified() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QFileInfo(currentQtVersion->qmakeProperty("QT_INSTALL_LIBS")).lastModified(); } return QDateTime(); } PuppetCreator::PuppetCreator(ProjectExplorer::Kit *kit, const QString &qtCreatorVersion) : m_qtCreatorVersion(qtCreatorVersion), m_kit(kit), m_availablePuppetType(FallbackPuppet) { } PuppetCreator::~PuppetCreator() { } void PuppetCreator::createPuppetExecutableIfMissing(PuppetCreator::QmlPuppetVersion puppetVersion) { if (puppetVersion == Qml1Puppet) createQml1PuppetExecutableIfMissing(); else createQml2PuppetExecutableIfMissing(); } QProcess *PuppetCreator::createPuppetProcess(PuppetCreator::QmlPuppetVersion puppetVersion, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QString puppetPath; if (puppetVersion == Qml1Puppet) puppetPath = qmlpuppetPath(m_availablePuppetType); else puppetPath = qml2puppetPath(m_availablePuppetType); return puppetProcess(puppetPath, puppetMode, socketToken, handlerObject, outputSlot, finishSlot); } QProcess *PuppetCreator::puppetProcess(const QString &puppetPath, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QProcess *puppetProcess = new QProcess; puppetProcess->setObjectName(puppetMode); puppetProcess->setProcessEnvironment(processEnvironment()); QObject::connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), puppetProcess, SLOT(kill())); QObject::connect(puppetProcess, SIGNAL(finished(int,QProcess::ExitStatus)), handlerObject, finishSlot); bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty(); if (fowardQmlpuppetOutput) { puppetProcess->setProcessChannelMode(QProcess::MergedChannels); QObject::connect(puppetProcess, SIGNAL(readyRead()), handlerObject, outputSlot); } puppetProcess->start(puppetPath, QStringList() << socketToken << puppetMode << "-graphicssystem raster"); return puppetProcess; } bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const { PuppetBuildProgressDialog progressDialog; m_compileLog.clear(); QTemporaryDir buildDirectory; bool buildSucceeded = false; if (qtIsSupported()) { if (buildDirectory.isValid()) { QStringList qmakeArguments; qmakeArguments.append(QStringLiteral("-r")); qmakeArguments.append(QStringLiteral("-after")); qmakeArguments.append(QStringLiteral("DESTDIR=") + qmlpuppetDirectory(UserSpacePuppet)); #ifndef QT_DEBUG qmakeArguments.append(QStringLiteral("CONFIG+=release")); #endif qmakeArguments.append(qmlPuppetProjectFilePath); buildSucceeded = startBuildProcess(buildDirectory.path(), qmakeCommand(), qmakeArguments); if (buildSucceeded) { progressDialog.show(); buildSucceeded = startBuildProcess(buildDirectory.path(), buildCommand(), QStringList(), &progressDialog); progressDialog.hide(); } } else { buildSucceeded = true; } } return buildSucceeded; } void PuppetCreator::createQml1PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml1PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml1PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQmlpuppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { bool buildSucceeded = build(qmlpuppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } m_qml1PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } else { m_availablePuppetType = FallbackPuppet; } } void PuppetCreator::createQml2PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml2PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml2PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQml2puppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { bool buildSucceeded = build(qml2puppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } m_qml2PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } else { m_availablePuppetType = FallbackPuppet; } } QString PuppetCreator::qmlpuppetDirectory(PuppetType puppetType) const { if (puppetType == UserSpacePuppet) return Core::ICore::userResourcePath() + QStringLiteral("/qmlpuppet/") + QCoreApplication::applicationVersion() + QStringLiteral("/") + qtHash(); return qmlpuppetFallbackDirectory(); } QString PuppetCreator::qmlpuppetFallbackDirectory() const { return QCoreApplication::applicationDirPath(); } QString PuppetCreator::qml2puppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qml2puppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QString PuppetCreator::qmlpuppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qmlpuppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QProcessEnvironment PuppetCreator::processEnvironment() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); environment.set("QML_BAD_GUI_RENDER_LOOP", "true"); environment.set("QML_USE_MOCKUPS", "true"); environment.set("QML_PUPPET_MODE", "true"); return environment.toProcessEnvironment(); } QString PuppetCreator::buildCommand() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); ProjectExplorer::ToolChain *toolChain = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit); if (toolChain) return toolChain->makeCommand(environment); return QString(); } QString PuppetCreator::qmakeCommand() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return currentQtVersion->qmakeCommand().toString(); return QString(); } QString PuppetCreator::compileLog() const { return m_compileLog; } bool PuppetCreator::startBuildProcess(const QString &buildDirectoryPath, const QString &command, const QStringList &processArguments, PuppetBuildProgressDialog *progressDialog) const { if (command.isEmpty()) return false; QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); process.setProcessEnvironment(processEnvironment()); process.setWorkingDirectory(buildDirectoryPath); process.start(command, processArguments); process.waitForStarted(); while (process.waitForReadyRead(-1)) { QByteArray newOutput = process.readAllStandardOutput(); if (progressDialog) progressDialog->newBuildOutput(newOutput); m_compileLog.append(newOutput); } process.waitForFinished(1000); if (process.exitStatus() == QProcess::NormalExit || process.exitCode() == 0) return true; else return false; } QString PuppetCreator::puppetSourceDirectoryPath() { return Core::ICore::resourcePath() + QStringLiteral("/qml/qmlpuppet"); } QString PuppetCreator::qml2puppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qml2puppet/qml2puppet.pro"); } QString PuppetCreator::qmlpuppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qmlpuppet/qmlpuppet.pro"); } bool PuppetCreator::checkPuppetIsReady(const QString &puppetPath) const { QFileInfo puppetFileInfo(puppetPath); return puppetFileInfo.exists() && puppetFileInfo.lastModified() > qtLastModified(); } bool PuppetCreator::checkQml2puppetIsReady() const { return checkPuppetIsReady(qml2puppetPath(UserSpacePuppet)); } bool PuppetCreator::checkQmlpuppetIsReady() const { return checkPuppetIsReady(qmlpuppetPath(UserSpacePuppet)); } bool PuppetCreator::qtIsSupported() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion && currentQtVersion->isValid() && currentQtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0) && (currentQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT) || currentQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))) return true; return false; } bool PuppetCreator::checkPuppetVersion(const QString &qmlPuppetPath) { QProcess qmlPuppetVersionProcess; qmlPuppetVersionProcess.start(qmlPuppetPath, QStringList() << "--version"); qmlPuppetVersionProcess.waitForReadyRead(6000); QByteArray versionString = qmlPuppetVersionProcess.readAll(); bool canConvert; unsigned int versionNumber = versionString.toUInt(&canConvert); return canConvert && versionNumber == 2; } } // namespace QmlDesigner <commit_msg>QmlDesigner: Increase timeout for puppet creation<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of Qt Creator. ** ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ****************************************************************************/ #include "puppetcreator.h" #include <QProcess> #include <QTemporaryDir> #include <QCoreApplication> #include <QCryptographicHash> #include <QDateTime> #include <projectexplorer/kit.h> #include <projectexplorer/toolchain.h> #include <utils/environment.h> #include <coreplugin/icore.h> #include <qtsupport/baseqtversion.h> #include <qtsupport/qtkitinformation.h> #include <qtsupport/qtsupportconstants.h> #include "puppetbuildprogressdialog.h" #include <QtDebug> namespace QmlDesigner { bool PuppetCreator::m_useOnlyFallbackPuppet = !qgetenv("USE_ONLY_FALLBACK_PUPPET").isEmpty(); QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml1PuppetForKitPuppetHash; QHash<Core::Id, PuppetCreator::PuppetType> PuppetCreator::m_qml2PuppetForKitPuppetHash; QByteArray PuppetCreator::qtHash() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QCryptographicHash::hash(currentQtVersion->qmakeProperty("QT_INSTALL_DATA").toUtf8(), QCryptographicHash::Sha1).toBase64(QByteArray::Base64UrlEncoding | QByteArray::OmitTrailingEquals); } return QByteArray(); } QDateTime PuppetCreator::qtLastModified() const { if (m_kit) { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return QFileInfo(currentQtVersion->qmakeProperty("QT_INSTALL_LIBS")).lastModified(); } return QDateTime(); } PuppetCreator::PuppetCreator(ProjectExplorer::Kit *kit, const QString &qtCreatorVersion) : m_qtCreatorVersion(qtCreatorVersion), m_kit(kit), m_availablePuppetType(FallbackPuppet) { } PuppetCreator::~PuppetCreator() { } void PuppetCreator::createPuppetExecutableIfMissing(PuppetCreator::QmlPuppetVersion puppetVersion) { if (puppetVersion == Qml1Puppet) createQml1PuppetExecutableIfMissing(); else createQml2PuppetExecutableIfMissing(); } QProcess *PuppetCreator::createPuppetProcess(PuppetCreator::QmlPuppetVersion puppetVersion, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QString puppetPath; if (puppetVersion == Qml1Puppet) puppetPath = qmlpuppetPath(m_availablePuppetType); else puppetPath = qml2puppetPath(m_availablePuppetType); return puppetProcess(puppetPath, puppetMode, socketToken, handlerObject, outputSlot, finishSlot); } QProcess *PuppetCreator::puppetProcess(const QString &puppetPath, const QString &puppetMode, const QString &socketToken, QObject *handlerObject, const char *outputSlot, const char *finishSlot) const { QProcess *puppetProcess = new QProcess; puppetProcess->setObjectName(puppetMode); puppetProcess->setProcessEnvironment(processEnvironment()); QObject::connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), puppetProcess, SLOT(kill())); QObject::connect(puppetProcess, SIGNAL(finished(int,QProcess::ExitStatus)), handlerObject, finishSlot); bool fowardQmlpuppetOutput = !qgetenv("FORWARD_QMLPUPPET_OUTPUT").isEmpty(); if (fowardQmlpuppetOutput) { puppetProcess->setProcessChannelMode(QProcess::MergedChannels); QObject::connect(puppetProcess, SIGNAL(readyRead()), handlerObject, outputSlot); } puppetProcess->start(puppetPath, QStringList() << socketToken << puppetMode << "-graphicssystem raster"); return puppetProcess; } bool PuppetCreator::build(const QString &qmlPuppetProjectFilePath) const { PuppetBuildProgressDialog progressDialog; m_compileLog.clear(); QTemporaryDir buildDirectory; bool buildSucceeded = false; if (qtIsSupported()) { if (buildDirectory.isValid()) { QStringList qmakeArguments; qmakeArguments.append(QStringLiteral("-r")); qmakeArguments.append(QStringLiteral("-after")); qmakeArguments.append(QStringLiteral("DESTDIR=") + qmlpuppetDirectory(UserSpacePuppet)); #ifndef QT_DEBUG qmakeArguments.append(QStringLiteral("CONFIG+=release")); #endif qmakeArguments.append(qmlPuppetProjectFilePath); buildSucceeded = startBuildProcess(buildDirectory.path(), qmakeCommand(), qmakeArguments); if (buildSucceeded) { progressDialog.show(); buildSucceeded = startBuildProcess(buildDirectory.path(), buildCommand(), QStringList(), &progressDialog); progressDialog.hide(); } } else { buildSucceeded = true; } } return buildSucceeded; } void PuppetCreator::createQml1PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml1PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml1PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQmlpuppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { bool buildSucceeded = build(qmlpuppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } m_qml1PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } else { m_availablePuppetType = FallbackPuppet; } } void PuppetCreator::createQml2PuppetExecutableIfMissing() { if (!m_useOnlyFallbackPuppet && m_kit) { if (m_qml2PuppetForKitPuppetHash.contains(m_kit->id())) { m_availablePuppetType = m_qml2PuppetForKitPuppetHash.value(m_kit->id()); } else if (checkQml2puppetIsReady()) { m_availablePuppetType = UserSpacePuppet; } else { bool buildSucceeded = build(qml2puppetProjectFile()); if (buildSucceeded) m_availablePuppetType = UserSpacePuppet; else m_availablePuppetType = FallbackPuppet; } m_qml2PuppetForKitPuppetHash.insert(m_kit->id(), m_availablePuppetType); } else { m_availablePuppetType = FallbackPuppet; } } QString PuppetCreator::qmlpuppetDirectory(PuppetType puppetType) const { if (puppetType == UserSpacePuppet) return Core::ICore::userResourcePath() + QStringLiteral("/qmlpuppet/") + QCoreApplication::applicationVersion() + QStringLiteral("/") + qtHash(); return qmlpuppetFallbackDirectory(); } QString PuppetCreator::qmlpuppetFallbackDirectory() const { return QCoreApplication::applicationDirPath(); } QString PuppetCreator::qml2puppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qml2puppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QString PuppetCreator::qmlpuppetPath(PuppetType puppetType) const { return qmlpuppetDirectory(puppetType) + QStringLiteral("/qmlpuppet") + QStringLiteral(QTC_HOST_EXE_SUFFIX); } QProcessEnvironment PuppetCreator::processEnvironment() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); environment.set("QML_BAD_GUI_RENDER_LOOP", "true"); environment.set("QML_USE_MOCKUPS", "true"); environment.set("QML_PUPPET_MODE", "true"); return environment.toProcessEnvironment(); } QString PuppetCreator::buildCommand() const { Utils::Environment environment = Utils::Environment::systemEnvironment(); m_kit->addToEnvironment(environment); ProjectExplorer::ToolChain *toolChain = ProjectExplorer::ToolChainKitInformation::toolChain(m_kit); if (toolChain) return toolChain->makeCommand(environment); return QString(); } QString PuppetCreator::qmakeCommand() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion) return currentQtVersion->qmakeCommand().toString(); return QString(); } QString PuppetCreator::compileLog() const { return m_compileLog; } bool PuppetCreator::startBuildProcess(const QString &buildDirectoryPath, const QString &command, const QStringList &processArguments, PuppetBuildProgressDialog *progressDialog) const { if (command.isEmpty()) return false; QProcess process; process.setProcessChannelMode(QProcess::MergedChannels); process.setProcessEnvironment(processEnvironment()); process.setWorkingDirectory(buildDirectoryPath); process.start(command, processArguments); process.waitForStarted(); while (process.waitForReadyRead(-1)) { QByteArray newOutput = process.readAllStandardOutput(); if (progressDialog) progressDialog->newBuildOutput(newOutput); m_compileLog.append(newOutput); } process.waitForFinished(); if (process.exitStatus() == QProcess::NormalExit || process.exitCode() == 0) return true; else return false; } QString PuppetCreator::puppetSourceDirectoryPath() { return Core::ICore::resourcePath() + QStringLiteral("/qml/qmlpuppet"); } QString PuppetCreator::qml2puppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qml2puppet/qml2puppet.pro"); } QString PuppetCreator::qmlpuppetProjectFile() { return puppetSourceDirectoryPath() + QStringLiteral("/qmlpuppet/qmlpuppet.pro"); } bool PuppetCreator::checkPuppetIsReady(const QString &puppetPath) const { QFileInfo puppetFileInfo(puppetPath); return puppetFileInfo.exists() && puppetFileInfo.lastModified() > qtLastModified(); } bool PuppetCreator::checkQml2puppetIsReady() const { return checkPuppetIsReady(qml2puppetPath(UserSpacePuppet)); } bool PuppetCreator::checkQmlpuppetIsReady() const { return checkPuppetIsReady(qmlpuppetPath(UserSpacePuppet)); } bool PuppetCreator::qtIsSupported() const { QtSupport::BaseQtVersion *currentQtVersion = QtSupport::QtKitInformation::qtVersion(m_kit); if (currentQtVersion && currentQtVersion->isValid() && currentQtVersion->qtVersion() >= QtSupport::QtVersionNumber(5, 2, 0) && (currentQtVersion->type() == QLatin1String(QtSupport::Constants::DESKTOPQT) || currentQtVersion->type() == QLatin1String(QtSupport::Constants::SIMULATORQT))) return true; return false; } bool PuppetCreator::checkPuppetVersion(const QString &qmlPuppetPath) { QProcess qmlPuppetVersionProcess; qmlPuppetVersionProcess.start(qmlPuppetPath, QStringList() << "--version"); qmlPuppetVersionProcess.waitForReadyRead(6000); QByteArray versionString = qmlPuppetVersionProcess.readAll(); bool canConvert; unsigned int versionNumber = versionString.toUInt(&canConvert); return canConvert && versionNumber == 2; } } // namespace QmlDesigner <|endoftext|>
<commit_before>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Chris Adams <[email protected]> ** ****************************************************************************/ #include "twitternotificationsplugin.h" #include "twittermentiontimelinesyncadaptor.h" #include "socialnetworksyncadaptor.h" extern "C" TwitterNotificationsPlugin* createPlugin(const QString& pluginName, const Buteo::SyncProfile& profile, Buteo::PluginCbInterface *callbackInterface) { return new TwitterNotificationsPlugin(pluginName, profile, callbackInterface); } extern "C" void destroyPlugin(TwitterNotificationsPlugin* plugin) { delete plugin; } TwitterNotificationsPlugin::TwitterNotificationsPlugin(const QString& pluginName, const Buteo::SyncProfile& profile, Buteo::PluginCbInterface *callbackInterface) : SocialdButeoPlugin(pluginName, profile, callbackInterface, QStringLiteral("twitter"), SocialNetworkSyncAdaptor::dataTypeName(SocialNetworkSyncAdaptor::Notifications)) { } TwitterNotificationsPlugin::~TwitterNotificationsPlugin() { } SocialNetworkSyncAdaptor *TwitterNotificationsPlugin::createSocialNetworkSyncAdaptor() { return new TwitterMentionTimelineSyncAdaptor(this); } <commit_msg>[sociald] Load translator for Twitter notifications. Contributes to JB#19139<commit_after>/**************************************************************************** ** ** Copyright (C) 2014 Jolla Ltd. ** Contact: Chris Adams <[email protected]> ** ****************************************************************************/ #include "twitternotificationsplugin.h" #include "twittermentiontimelinesyncadaptor.h" #include "socialnetworksyncadaptor.h" #include <QTranslator> #include <QCoreApplication> extern "C" TwitterNotificationsPlugin* createPlugin(const QString& pluginName, const Buteo::SyncProfile& profile, Buteo::PluginCbInterface *callbackInterface) { return new TwitterNotificationsPlugin(pluginName, profile, callbackInterface); } extern "C" void destroyPlugin(TwitterNotificationsPlugin* plugin) { delete plugin; } TwitterNotificationsPlugin::TwitterNotificationsPlugin(const QString& pluginName, const Buteo::SyncProfile& profile, Buteo::PluginCbInterface *callbackInterface) : SocialdButeoPlugin(pluginName, profile, callbackInterface, QStringLiteral("twitter"), SocialNetworkSyncAdaptor::dataTypeName(SocialNetworkSyncAdaptor::Notifications)) { QString translationPath("/usr/share/translations/"); // QTranslator life-cycle: owned by ButeoSocial and removed by its own destructor QTranslator *engineeringEnglish = new QTranslator(this); engineeringEnglish->load("lipstick-jolla-home-twitter-notif_eng_en", translationPath); QCoreApplication::instance()->installTranslator(engineeringEnglish); QTranslator *translator = new QTranslator(this); translator->load(QLocale(), "lipstick-jolla-home-twitter-notif", "-", translationPath); QCoreApplication::instance()->installTranslator(translator); } TwitterNotificationsPlugin::~TwitterNotificationsPlugin() { } SocialNetworkSyncAdaptor *TwitterNotificationsPlugin::createSocialNetworkSyncAdaptor() { return new TwitterMentionTimelineSyncAdaptor(this); } <|endoftext|>
<commit_before>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreD3D11HardwareVertexBuffer.h" #include "OgreD3D11HardwareBuffer.h" #include "OgreD3D11Device.h" namespace Ogre { //--------------------------------------------------------------------- D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device, bool useSystemMemory, bool useShadowBuffer) : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer) { // everything is done via internal generalisation mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER, mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer); } //--------------------------------------------------------------------- D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer() { delete mBufferImpl; } //--------------------------------------------------------------------- void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options) { return mBufferImpl->lock(offset, length, options); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::unlock(void) { mBufferImpl->unlock(); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest) { mBufferImpl->readData(offset, length, pDest); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, size_t length, bool discardWholeBuffer) { D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer); mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer); } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::isLocked(void) const { return mBufferImpl->isLocked(); } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void) { /* if (mD3DPool == D3DPOOL_DEFAULT) { SAFE_RELEASE(mlpD3DBuffer); return true; } return false; */ return true; } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device) { /* if (mD3DPool == D3DPOOL_DEFAULT) { // Create the Index buffer HRESULT hr = device->CreateIndexBuffer( static_cast<UINT>(mSizeInBytes), D3D11Mappings::get(mUsage), D3D11Mappings::get(mIndexType), mD3DPool, &mlpD3DBuffer, NULL ); if (FAILED(hr)) { String msg = DXGetErrorDescription(hr); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot create D3D11 Index buffer: " + msg, "D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer"); } return true; } return false; */ return true; } //--------------------------------------------------------------------- ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const { return mBufferImpl->getD3DBuffer(); } //--------------------------------------------------------------------- } <commit_msg>D3D11 render system: Added code to support copy of vertex buffers that where allocated in system memory. (The terrain sample does such a copy).<commit_after>/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2009 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreD3D11HardwareVertexBuffer.h" #include "OgreD3D11HardwareBuffer.h" #include "OgreD3D11Device.h" namespace Ogre { //--------------------------------------------------------------------- D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer(HardwareBufferManagerBase* mgr, size_t vertexSize, size_t numVertices, HardwareBuffer::Usage usage, D3D11Device & device, bool useSystemMemory, bool useShadowBuffer) : HardwareVertexBuffer(mgr, vertexSize, numVertices, usage, useSystemMemory, useShadowBuffer), mBufferImpl(0) { // everything is done via internal generalisation mBufferImpl = new D3D11HardwareBuffer(D3D11HardwareBuffer::VERTEX_BUFFER, mSizeInBytes, mUsage, device, useSystemMemory, useShadowBuffer); } //--------------------------------------------------------------------- D3D11HardwareVertexBuffer::~D3D11HardwareVertexBuffer() { SAFE_DELETE(mBufferImpl); } //--------------------------------------------------------------------- void* D3D11HardwareVertexBuffer::lock(size_t offset, size_t length, LockOptions options) { return mBufferImpl->lock(offset, length, options); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::unlock(void) { mBufferImpl->unlock(); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::readData(size_t offset, size_t length, void* pDest) { mBufferImpl->readData(offset, length, pDest); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::writeData(size_t offset, size_t length, const void* pSource, bool discardWholeBuffer) { mBufferImpl->writeData(offset, length, pSource, discardWholeBuffer); } //--------------------------------------------------------------------- void D3D11HardwareVertexBuffer::copyData(HardwareBuffer& srcBuffer, size_t srcOffset, size_t dstOffset, size_t length, bool discardWholeBuffer) { // check if the other buffer is also a D3D11HardwareVertexBuffer if (srcBuffer.isSystemMemory()) { // src is not not a D3D11HardwareVertexBuffer - use default copy HardwareBuffer::copyData(srcBuffer, srcOffset, dstOffset, length, discardWholeBuffer); } else { // src is a D3D11HardwareVertexBuffer use d3d11 optimized copy D3D11HardwareVertexBuffer& d3dBuf = static_cast<D3D11HardwareVertexBuffer&>(srcBuffer); mBufferImpl->copyData(*(d3dBuf.mBufferImpl), srcOffset, dstOffset, length, discardWholeBuffer); } } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::isLocked(void) const { return mBufferImpl->isLocked(); } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::releaseIfDefaultPool(void) { /* if (mD3DPool == D3DPOOL_DEFAULT) { SAFE_RELEASE(mlpD3DBuffer); return true; } return false; */ return true; } //--------------------------------------------------------------------- bool D3D11HardwareVertexBuffer::recreateIfDefaultPool(D3D11Device & device) { /* if (mD3DPool == D3DPOOL_DEFAULT) { // Create the Index buffer HRESULT hr = device->CreateIndexBuffer( static_cast<UINT>(mSizeInBytes), D3D11Mappings::get(mUsage), D3D11Mappings::get(mIndexType), mD3DPool, &mlpD3DBuffer, NULL ); if (FAILED(hr)) { String msg = DXGetErrorDescription(hr); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "Cannot create D3D11 Index buffer: " + msg, "D3D11HardwareVertexBuffer::D3D11HardwareVertexBuffer"); } return true; } return false; */ return true; } //--------------------------------------------------------------------- ID3D11Buffer * D3D11HardwareVertexBuffer::getD3DVertexBuffer( void ) const { return mBufferImpl->getD3DBuffer(); } //--------------------------------------------------------------------- } <|endoftext|>
<commit_before>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "mbed-drivers/mbed.h" #include "ble/BLE.h" BLE ble; DigitalOut led1(LED1, 1); InterruptIn button(BUTTON1); uint8_t count; const char DEVICE_NAME[] = "Button"; void buttonPressedCallback(void) { count++; ble.gap().updateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, &count, sizeof(count)); } void blinkCallback(void) { led1 = !led1; /* Do blinky on LED1 to indicate system aliveness. */ } void app_start(int, char**) { ble.init(); /* setup advertising */ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); /* 1000ms. */ count = 0; ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, &count, sizeof(count)); minar::Scheduler::postCallback(blinkCallback).period(minar::milliseconds(500)); button.rise(buttonPressedCallback); ble.gap().startAdvertising(); } <commit_msg>Change device name to GapButton to uniquely identify this demo.<commit_after>/* mbed Microcontroller Library * Copyright (c) 2006-2013 ARM Limited * * 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 "mbed-drivers/mbed.h" #include "ble/BLE.h" BLE ble; DigitalOut led1(LED1, 1); InterruptIn button(BUTTON1); uint8_t count; const char DEVICE_NAME[] = "GapButton"; void buttonPressedCallback(void) { count++; ble.gap().updateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, &count, sizeof(count)); } void blinkCallback(void) { led1 = !led1; /* Do blinky on LED1 to indicate system aliveness. */ } void app_start(int, char**) { ble.init(); /* setup advertising */ ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED | GapAdvertisingData::LE_GENERAL_DISCOVERABLE); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LOCAL_NAME, (uint8_t *)DEVICE_NAME, sizeof(DEVICE_NAME)); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_NON_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); /* 1000ms. */ count = 0; ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::MANUFACTURER_SPECIFIC_DATA, &count, sizeof(count)); minar::Scheduler::postCallback(blinkCallback).period(minar::milliseconds(500)); button.rise(buttonPressedCallback); ble.gap().startAdvertising(); } <|endoftext|>
<commit_before>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkGaussianDerivativeImageFunction_hxx #define __itkGaussianDerivativeImageFunction_hxx #include "itkGaussianDerivativeImageFunction.h" #include "itkCompensatedSummation.h" namespace itk { /** Set the Input Image */ template< typename TInputImage, typename TOutput > GaussianDerivativeImageFunction< TInputImage, TOutput > ::GaussianDerivativeImageFunction() { typename GaussianFunctionType::ArrayType mean; mean[0] = 0.0; for ( unsigned int i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = 1.0; m_Extent[i] = 1.0; } m_UseImageSpacing = true; m_GaussianDerivativeFunction = GaussianDerivativeFunctionType::New(); m_GaussianFunction = GaussianFunctionType::New(); m_OperatorImageFunction = OperatorImageFunctionType::New(); m_GaussianFunction->SetMean(mean); m_GaussianFunction->SetNormalized(false); // faster m_GaussianDerivativeFunction->SetNormalized(false); // faster this->RecomputeGaussianKernel(); } /** Print self method */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::PrintSelf(std::ostream & os, Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Extent: " << m_Extent << std::endl; os << indent << "OperatorArray: " << m_OperatorArray << std::endl; os << indent << "ContinuousOperatorArray: " << m_ContinuousOperatorArray << std::endl; os << indent << "OperatorImageFunction: " << m_OperatorImageFunction << std::endl; os << indent << "GaussianDerivativeFunction: " << m_GaussianDerivativeFunction << std::endl; os << indent << "GaussianFunction: " << m_GaussianFunction << std::endl; } /** Set the input image */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetInputImage(const InputImageType *ptr) { Superclass::SetInputImage(ptr); m_OperatorImageFunction->SetInputImage(ptr); } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double *sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma[i] != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma[i]; } this->RecomputeGaussianKernel(); } } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double *extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent[i] != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent[i]; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent; } this->RecomputeGaussianKernel(); } } /** Recompute the gaussian kernel used to evaluate indexes * This should use a fastest Derivative Gaussian operator */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeGaussianKernel() { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename NeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int i = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++i; ++it; } m_OperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); i = 0; double sum = 0.0; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++i; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); while ( it != gaussianNeighborhood.End() ) { ( *it ) /= sum; ++it; } m_OperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed index */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtIndex(const IndexType & index) const { OutputType gradient; for ( unsigned int ii = 0; ii < itkGetStaticConstMacro(ImageDimension2); ++ii ) { // Apply each gaussian kernel to a subset of the image InputPixelType value = static_cast< double >( this->GetInputImage()->GetPixel(index) ); // gaussian blurring first for ( unsigned int direction = 0; direction < itkGetStaticConstMacro(ImageDimension2); ++direction ) { if ( ii != direction ) { const unsigned int idx = 2 * direction + 1; // select only gaussian kernel; const unsigned int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[direction] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; } } // then derivative in the direction const unsigned int idx = 2 * ii; const signed int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[ii] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; gradient[ii] = value; } return gradient; } /** Recompute the gaussian kernel used to evaluate indexes * The variance should be uniform */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeContinuousGaussianKernel( const double *offset) const { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename OperatorNeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int ii = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++ii; ++it; } m_ContinuousOperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); ii = 0; double sum = 0; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++ii; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); while ( it != gaussianNeighborhood.End() ) { ( *it ) /= sum; ++it; } m_ContinuousOperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed point */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::Evaluate(const PointType & point) const { IndexType index; this->ConvertPointToNearestIndex(point, index); return this->EvaluateAtIndex (index); } /** Evaluate the function at specified ContinousIndex position.*/ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtContinuousIndex(const ContinuousIndexType & cindex) const { IndexType index; this->ConvertContinuousIndexToNearestIndex(cindex, index); return this->EvaluateAtIndex(index); } } // end namespace itk #endif <commit_msg>ENH: Use CompensatedSummation in GaussianDerivativeImageFunction.<commit_after>/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkGaussianDerivativeImageFunction_hxx #define __itkGaussianDerivativeImageFunction_hxx #include "itkGaussianDerivativeImageFunction.h" #include "itkCompensatedSummation.h" namespace itk { /** Set the Input Image */ template< typename TInputImage, typename TOutput > GaussianDerivativeImageFunction< TInputImage, TOutput > ::GaussianDerivativeImageFunction() { typename GaussianFunctionType::ArrayType mean; mean[0] = 0.0; for ( unsigned int i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = 1.0; m_Extent[i] = 1.0; } m_UseImageSpacing = true; m_GaussianDerivativeFunction = GaussianDerivativeFunctionType::New(); m_GaussianFunction = GaussianFunctionType::New(); m_OperatorImageFunction = OperatorImageFunctionType::New(); m_GaussianFunction->SetMean(mean); m_GaussianFunction->SetNormalized(false); // faster m_GaussianDerivativeFunction->SetNormalized(false); // faster this->RecomputeGaussianKernel(); } /** Print self method */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::PrintSelf(std::ostream & os, Indent indent) const { this->Superclass::PrintSelf(os, indent); os << indent << "UseImageSpacing: " << m_UseImageSpacing << std::endl; os << indent << "Sigma: " << m_Sigma << std::endl; os << indent << "Extent: " << m_Extent << std::endl; os << indent << "OperatorArray: " << m_OperatorArray << std::endl; os << indent << "ContinuousOperatorArray: " << m_ContinuousOperatorArray << std::endl; os << indent << "OperatorImageFunction: " << m_OperatorImageFunction << std::endl; os << indent << "GaussianDerivativeFunction: " << m_GaussianDerivativeFunction << std::endl; os << indent << "GaussianFunction: " << m_GaussianFunction << std::endl; } /** Set the input image */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetInputImage(const InputImageType *ptr) { Superclass::SetInputImage(ptr); m_OperatorImageFunction->SetInputImage(ptr); } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double *sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma[i] != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma[i]; } this->RecomputeGaussianKernel(); } } /** Set the variance of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetSigma(const double sigma) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( sigma != m_Sigma[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Sigma[i] = sigma; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double *extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent[i] != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent[i]; } this->RecomputeGaussianKernel(); } } /** Set the extent of the gaussian in each direction */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::SetExtent(const double extent) { unsigned int i; for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { if ( extent != m_Extent[i] ) { break; } } if ( i < itkGetStaticConstMacro(ImageDimension2) ) { for ( i = 0; i < itkGetStaticConstMacro(ImageDimension2); i++ ) { m_Extent[i] = extent; } this->RecomputeGaussianKernel(); } } /** Recompute the gaussian kernel used to evaluate indexes * This should use a fastest Derivative Gaussian operator */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeGaussianKernel() { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename NeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int i = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++i; ++it; } m_OperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); i = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(i)[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++i; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_OperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed index */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtIndex(const IndexType & index) const { OutputType gradient; for ( unsigned int ii = 0; ii < itkGetStaticConstMacro(ImageDimension2); ++ii ) { // Apply each gaussian kernel to a subset of the image InputPixelType value = static_cast< double >( this->GetInputImage()->GetPixel(index) ); // gaussian blurring first for ( unsigned int direction = 0; direction < itkGetStaticConstMacro(ImageDimension2); ++direction ) { if ( ii != direction ) { const unsigned int idx = 2 * direction + 1; // select only gaussian kernel; const unsigned int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[direction] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; } } // then derivative in the direction const unsigned int idx = 2 * ii; const signed int center = (unsigned int)( ( m_OperatorArray[idx].GetSize()[ii] - 1 ) / 2 ); TOutput centerval = m_OperatorArray[idx].GetCenterValue(); m_OperatorArray[idx][center] = 0; m_OperatorImageFunction->SetOperator(m_OperatorArray[idx]); value = m_OperatorImageFunction->EvaluateAtIndex(index) + centerval * value; gradient[ii] = value; } return gradient; } /** Recompute the gaussian kernel used to evaluate indexes * The variance should be uniform */ template< typename TInputImage, typename TOutput > void GaussianDerivativeImageFunction< TInputImage, TOutput > ::RecomputeContinuousGaussianKernel( const double *offset) const { unsigned int direction = 0; for ( unsigned int op = 0; op < itkGetStaticConstMacro(ImageDimension2); ++op ) { // Set the derivative of the gaussian first OperatorNeighborhoodType dogNeighborhood; typename GaussianDerivativeFunctionType::InputType pt; typename OperatorNeighborhoodType::SizeType size; size.Fill(0); size[direction] = static_cast<SizeValueType>( m_Sigma[direction] * m_Extent[direction] ); dogNeighborhood.SetRadius(size); typename GaussianDerivativeFunctionType::ArrayType s; s[0] = m_Sigma[direction]; m_GaussianDerivativeFunction->SetSigma(s); typename OperatorNeighborhoodType::Iterator it = dogNeighborhood.Begin(); unsigned int ii = 0; while ( it != dogNeighborhood.End() ) { pt[0] = dogNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianDerivativeFunction->Evaluate(pt); ++ii; ++it; } m_ContinuousOperatorArray[op * 2] = dogNeighborhood; // Set the gaussian operator m_GaussianFunction->SetSigma(s); OperatorNeighborhoodType gaussianNeighborhood; gaussianNeighborhood.SetRadius(size); it = gaussianNeighborhood.Begin(); ii = 0; CompensatedSummation< TOutput > sum; while ( it != gaussianNeighborhood.End() ) { pt[0] = gaussianNeighborhood.GetOffset(ii)[direction] - offset[direction]; if ( ( m_UseImageSpacing == true ) && ( this->GetInputImage() ) ) { if ( this->GetInputImage()->GetSpacing()[direction] == 0.0 ) { itkExceptionMacro(<< "Pixel spacing cannot be zero"); } else { pt[0] *= this->GetInputImage()->GetSpacing()[direction]; } } ( *it ) = m_GaussianFunction->Evaluate(pt); sum += ( *it ); ++ii; ++it; } // Make the filter DC-Constant it = gaussianNeighborhood.Begin(); const TOutput sumInverse = 1. / sum.GetSum(); while ( it != gaussianNeighborhood.End() ) { ( *it ) *= sumInverse; ++it; } m_ContinuousOperatorArray[op * 2 + 1] = gaussianNeighborhood; ++direction; } } /** Evaluate the function at the specifed point */ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::Evaluate(const PointType & point) const { IndexType index; this->ConvertPointToNearestIndex(point, index); return this->EvaluateAtIndex (index); } /** Evaluate the function at specified ContinousIndex position.*/ template< typename TInputImage, typename TOutput > typename GaussianDerivativeImageFunction< TInputImage, TOutput >::OutputType GaussianDerivativeImageFunction< TInputImage, TOutput > ::EvaluateAtContinuousIndex(const ContinuousIndexType & cindex) const { IndexType index; this->ConvertContinuousIndexToNearestIndex(cindex, index); return this->EvaluateAtIndex(index); } } // end namespace itk #endif <|endoftext|>
<commit_before>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <mitkManualSegmentationToSurfaceFilter.h> #include <vtkImageShiftScale.h> #include <vtkSmartPointer.h> #include "mitkProgressBar.h" mitk::ManualSegmentationToSurfaceFilter::ManualSegmentationToSurfaceFilter() { m_MedianFilter3D = false; m_MedianKernelSizeX = 3; m_MedianKernelSizeY = 3; m_MedianKernelSizeZ = 3; m_UseGaussianImageSmooth = false; m_GaussianStandardDeviation = 1.5; m_Interpolation = false; m_InterpolationX = 1.0f; m_InterpolationY = 1.0f; m_InterpolationZ = 1.0f; }; mitk::ManualSegmentationToSurfaceFilter::~ManualSegmentationToSurfaceFilter(){}; void mitk::ManualSegmentationToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); auto *image = (mitk::Image *)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart = outputRegion.GetIndex(3); int tmax = tstart + outputRegion.GetSize(3); // GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgeloest ScalarType thresholdExpanded = this->m_Threshold; if ((tmax - tstart) > 0) { ProgressBar::GetInstance()->AddStepsToDo(4 * (tmax - tstart)); } else { ProgressBar::GetInstance()->AddStepsToDo(4); } for (int t = tstart; t < tmax; ++t) { vtkSmartPointer<vtkImageData> vtkimage = image->GetVtkImageData(t); // Median -->smooth 3D // MITK_INFO << (m_MedianFilter3D ? "Applying median..." : "No median filtering"); if (m_MedianFilter3D) { vtkImageMedian3D *median = vtkImageMedian3D::New(); median->SetInputData(vtkimage); // RC++ (VTK < 5.0) median->SetKernelSize(m_MedianKernelSizeX, m_MedianKernelSizeY, m_MedianKernelSizeZ); // Std: 3x3x3 median->ReleaseDataFlagOn(); median->UpdateInformation(); median->Update(); vtkimage = median->GetOutput(); //->Out median->Delete(); } ProgressBar::GetInstance()->Progress(); // Interpolate image spacing // MITK_INFO << (m_Interpolation ? "Resampling..." : "No resampling"); if (m_Interpolation) { vtkImageResample *imageresample = vtkImageResample::New(); imageresample->SetInputData(vtkimage); // Set Spacing Manual to 1mm in each direction (Original spacing is lost during image processing) imageresample->SetAxisOutputSpacing(0, m_InterpolationX); imageresample->SetAxisOutputSpacing(1, m_InterpolationY); imageresample->SetAxisOutputSpacing(2, m_InterpolationZ); imageresample->UpdateInformation(); imageresample->Update(); vtkimage = imageresample->GetOutput(); //->Output imageresample->Delete(); } ProgressBar::GetInstance()->Progress(); // MITK_INFO << (m_UseGaussianImageSmooth ? "Applying gaussian smoothing..." : "No gaussian smoothing"); if (m_UseGaussianImageSmooth) // gauss { vtkImageShiftScale *scalefilter = vtkImageShiftScale::New(); scalefilter->SetScale(100); scalefilter->SetInputData(vtkimage); scalefilter->Update(); vtkImageGaussianSmooth *gaussian = vtkImageGaussianSmooth::New(); gaussian->SetInputConnection(scalefilter->GetOutputPort()); gaussian->SetDimensionality(3); gaussian->SetRadiusFactor(0.49); gaussian->SetStandardDeviation(m_GaussianStandardDeviation); gaussian->ReleaseDataFlagOn(); gaussian->UpdateInformation(); gaussian->Update(); vtkimage = scalefilter->GetOutput(); double range[2]; vtkimage->GetScalarRange(range); if (range[1] != 0) // too little slices, image smoothing eliminates all segmentation pixels { vtkimage = gaussian->GetOutput(); //->Out } else { MITK_INFO << "Smoothing would remove all pixels of the segmentation. Use unsmoothed result instead."; } gaussian->Delete(); scalefilter->Delete(); } ProgressBar::GetInstance()->Progress(); // Create surface for t-Slice CreateSurface(t, vtkimage, surface, thresholdExpanded); ProgressBar::GetInstance()->Progress(); } // MITK_INFO << "Updating Time Geometry to ensure right timely displaying"; // Fixing wrong time geometry TimeGeometry *surfaceTG = surface->GetTimeGeometry(); auto *surfacePTG = dynamic_cast<ProportionalTimeGeometry *>(surfaceTG); TimeGeometry *imageTG = image->GetTimeGeometry(); auto *imagePTG = dynamic_cast<ProportionalTimeGeometry *>(imageTG); // Requires ProportionalTimeGeometries to work. May not be available for all steps. assert(surfacePTG != nullptr); assert(imagePTG != nullptr); if ((surfacePTG != nullptr) && (imagePTG != nullptr)) { TimePointType firstTime = imagePTG->GetFirstTimePoint(); TimePointType duration = imagePTG->GetStepDuration(); surfacePTG->SetFirstTimePoint(firstTime); surfacePTG->SetStepDuration(duration); // MITK_INFO << "First Time Point: " << firstTime << " Duration: " << duration; } }; void mitk::ManualSegmentationToSurfaceFilter::SetMedianKernelSize(int x, int y, int z) { m_MedianKernelSizeX = x; m_MedianKernelSizeY = y; m_MedianKernelSizeZ = z; } void mitk::ManualSegmentationToSurfaceFilter::SetInterpolation(vtkDouble x, vtkDouble y, vtkDouble z) { m_InterpolationX = x; m_InterpolationY = y; m_InterpolationZ = z; } <commit_msg>Pad single-sliced images with empty slice to make them 3-d for VTK<commit_after>/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include <array> #include <mitkManualSegmentationToSurfaceFilter.h> #include <vtkImageShiftScale.h> #include <vtkImageConstantPad.h> #include <vtkSmartPointer.h> #include "mitkProgressBar.h" mitk::ManualSegmentationToSurfaceFilter::ManualSegmentationToSurfaceFilter() { m_MedianFilter3D = false; m_MedianKernelSizeX = 3; m_MedianKernelSizeY = 3; m_MedianKernelSizeZ = 3; m_UseGaussianImageSmooth = false; m_GaussianStandardDeviation = 1.5; m_Interpolation = false; m_InterpolationX = 1.0f; m_InterpolationY = 1.0f; m_InterpolationZ = 1.0f; }; mitk::ManualSegmentationToSurfaceFilter::~ManualSegmentationToSurfaceFilter(){}; void mitk::ManualSegmentationToSurfaceFilter::GenerateData() { mitk::Surface *surface = this->GetOutput(); auto *image = (mitk::Image *)GetInput(); mitk::Image::RegionType outputRegion = image->GetRequestedRegion(); int tstart = outputRegion.GetIndex(3); int tmax = tstart + outputRegion.GetSize(3); // GetSize()==1 - will aber 0 haben, wenn nicht zeitaufgeloest ScalarType thresholdExpanded = this->m_Threshold; if ((tmax - tstart) > 0) { ProgressBar::GetInstance()->AddStepsToDo(4 * (tmax - tstart)); } else { ProgressBar::GetInstance()->AddStepsToDo(4); } for (int t = tstart; t < tmax; ++t) { vtkSmartPointer<vtkImageData> vtkimage = image->GetVtkImageData(t); // If the image has a single slice, pad it with an empty slice to explicitly make it // recognizable as 3-d by VTK. Otherwise, the vtkMarchingCubes filter will // complain about dimensionality and won't produce any output. if (2 == vtkimage->GetDataDimension()) { std::array<int, 6> extent; vtkimage->GetExtent(extent.data()); extent[5] = 1; auto padFilter = vtkSmartPointer<vtkImageConstantPad>::New(); padFilter->SetInputData(vtkimage); padFilter->SetOutputWholeExtent(extent.data()); padFilter->UpdateInformation(); padFilter->Update(); vtkimage = padFilter->GetOutput(); } // Median -->smooth 3D // MITK_INFO << (m_MedianFilter3D ? "Applying median..." : "No median filtering"); if (m_MedianFilter3D) { vtkImageMedian3D *median = vtkImageMedian3D::New(); median->SetInputData(vtkimage); // RC++ (VTK < 5.0) median->SetKernelSize(m_MedianKernelSizeX, m_MedianKernelSizeY, m_MedianKernelSizeZ); // Std: 3x3x3 median->ReleaseDataFlagOn(); median->UpdateInformation(); median->Update(); vtkimage = median->GetOutput(); //->Out median->Delete(); } ProgressBar::GetInstance()->Progress(); // Interpolate image spacing // MITK_INFO << (m_Interpolation ? "Resampling..." : "No resampling"); if (m_Interpolation) { vtkImageResample *imageresample = vtkImageResample::New(); imageresample->SetInputData(vtkimage); // Set Spacing Manual to 1mm in each direction (Original spacing is lost during image processing) imageresample->SetAxisOutputSpacing(0, m_InterpolationX); imageresample->SetAxisOutputSpacing(1, m_InterpolationY); imageresample->SetAxisOutputSpacing(2, m_InterpolationZ); imageresample->UpdateInformation(); imageresample->Update(); vtkimage = imageresample->GetOutput(); //->Output imageresample->Delete(); } ProgressBar::GetInstance()->Progress(); // MITK_INFO << (m_UseGaussianImageSmooth ? "Applying gaussian smoothing..." : "No gaussian smoothing"); if (m_UseGaussianImageSmooth) // gauss { vtkImageShiftScale *scalefilter = vtkImageShiftScale::New(); scalefilter->SetScale(100); scalefilter->SetInputData(vtkimage); scalefilter->Update(); vtkImageGaussianSmooth *gaussian = vtkImageGaussianSmooth::New(); gaussian->SetInputConnection(scalefilter->GetOutputPort()); gaussian->SetDimensionality(3); gaussian->SetRadiusFactor(0.49); gaussian->SetStandardDeviation(m_GaussianStandardDeviation); gaussian->ReleaseDataFlagOn(); gaussian->UpdateInformation(); gaussian->Update(); vtkimage = scalefilter->GetOutput(); double range[2]; vtkimage->GetScalarRange(range); if (range[1] != 0) // too little slices, image smoothing eliminates all segmentation pixels { vtkimage = gaussian->GetOutput(); //->Out } else { MITK_INFO << "Smoothing would remove all pixels of the segmentation. Use unsmoothed result instead."; } gaussian->Delete(); scalefilter->Delete(); } ProgressBar::GetInstance()->Progress(); // Create surface for t-Slice CreateSurface(t, vtkimage, surface, thresholdExpanded); ProgressBar::GetInstance()->Progress(); } // MITK_INFO << "Updating Time Geometry to ensure right timely displaying"; // Fixing wrong time geometry TimeGeometry *surfaceTG = surface->GetTimeGeometry(); auto *surfacePTG = dynamic_cast<ProportionalTimeGeometry *>(surfaceTG); TimeGeometry *imageTG = image->GetTimeGeometry(); auto *imagePTG = dynamic_cast<ProportionalTimeGeometry *>(imageTG); // Requires ProportionalTimeGeometries to work. May not be available for all steps. assert(surfacePTG != nullptr); assert(imagePTG != nullptr); if ((surfacePTG != nullptr) && (imagePTG != nullptr)) { TimePointType firstTime = imagePTG->GetFirstTimePoint(); TimePointType duration = imagePTG->GetStepDuration(); surfacePTG->SetFirstTimePoint(firstTime); surfacePTG->SetStepDuration(duration); // MITK_INFO << "First Time Point: " << firstTime << " Duration: " << duration; } }; void mitk::ManualSegmentationToSurfaceFilter::SetMedianKernelSize(int x, int y, int z) { m_MedianKernelSizeX = x; m_MedianKernelSizeY = y; m_MedianKernelSizeZ = z; } void mitk::ManualSegmentationToSurfaceFilter::SetInterpolation(vtkDouble x, vtkDouble y, vtkDouble z) { m_InterpolationX = x; m_InterpolationY = y; m_InterpolationZ = z; } <|endoftext|>
<commit_before>// UVa1587 - Box // Time: O(1) // Space: O(1) #include <iostream> #include <unordered_set> #include <unordered_map> #include <algorithm> using namespace std; struct HashPair { size_t operator()(const pair<int, int>& p) const { return hash<int>()(p.first) ^ hash<int>()(p.second); } }; int main() { int w, h; while (cin >> w >> h) { unordered_set<int> edge; unordered_map<pair<int, int>, int, HashPair> area; if (w > h) { swap(w, h); } edge.insert(w), edge.insert(h); ++area[make_pair(w, h)]; int count = 5; while (count--) { cin >> w >> h; if (w > h) { swap(w, h); } edge.insert(w), edge.insert(h); ++area[make_pair(w, h)]; } bool is_ok = false; // Make sure all of (w, h) has pairs and at most 3 different lengths of w, h, l. if (all_of(area.cbegin(), area.cend(), [](const pair<pair<int, int>, int>& p){ return p.second % 2 == 0; }) && edge.size() <= 3) { is_ok = true; // Make sure all pairs of l, w, h exist. for (auto it = edge.cbegin(); is_ok && it != edge.cend(); ++it) { auto jt = it; ++jt; for (; is_ok && jt != edge.cend(); ++jt) { if (area.find(make_pair(*it, *jt)) == area.cend() && area.find(make_pair(*jt, *it)) == area.cend()) { // Some of (w, h) does not exist. is_ok = false; } } } } if (is_ok) { cout << "POSSIBLE" << endl; } else { cout << "IMPOSSIBLE" << endl; } } return 0; }<commit_msg>Update UVa1587.cpp<commit_after>// UVa1587 - Box // Time: O(1) // Space: O(1) #include <iostream> #include <unordered_set> #include <unordered_map> #include <algorithm> using namespace std; struct HashPair { size_t operator()(const pair<int, int>& p) const { return hash<int>()(p.first) ^ hash<int>()(p.second); } }; void CheckBox(unordered_set<int>& edge, unordered_map<pair<int, int>, int, HashPair>& area) { bool is_ok = false; // Make sure all of (w, h) has pairs and at most 3 different lengths of w, h, l. if (all_of(area.cbegin(), area.cend(), [](const pair<pair<int, int>, int>& p){ return p.second % 2 == 0; }) && edge.size() <= 3) { is_ok = true; // Make sure all pairs of l, w, h exist. for (auto it = edge.cbegin(); is_ok && it != edge.cend(); ++it) { auto jt = it; ++jt; for (; is_ok && jt != edge.cend(); ++jt) { if (area.find(make_pair(*it, *jt)) == area.cend() && area.find(make_pair(*jt, *it)) == area.cend()) { // Some of (w, h) does not exist. is_ok = false; } } } } if (is_ok) { cout << "POSSIBLE" << endl; } else { cout << "IMPOSSIBLE" << endl; } } int main() { int w, h; while (cin >> w >> h) { unordered_set<int> edge; unordered_map<pair<int, int>, int, HashPair> area; int count = 0; do { if (w > h) { swap(w, h); } edge.insert(w), edge.insert(h); ++area[make_pair(w, h)]; if (++count == 6) { break; } } while(cin >> w >> h); CheckBox(edge, area); } return 0; } <|endoftext|>
<commit_before>// UVa1588 - Kickdown // Time: O(m * n) // Space: O(1) #include <iostream> #include <string> using namespace std; bool IsValid(int k, const string& s1, const string& s2){ for (int i = 0; k + i < s1.length() && i < s2.length(); ++i) { if ((s1[k + i] - '0') + (s2[i] - '0') > 3) { return false; } } return true; } size_t Cut(const string& s1, const string& s2){ int k = 0; while (!IsValid(k, s1, s2)) { ++k; } return max(s1.length(), s2.length() + k); } int main(){ string bottom, top; while (cin >> bottom >> top) { cout << min(Cut(bottom, top), Cut(top, bottom)) << endl; } return 0; }<commit_msg>update<commit_after>// Copyright (c) 2015 kamyu. All rights reserved. /* * UVa1588 - Kickdown * http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=4463 * * Time : O(m * n) * Space : O(1) * */ #include <iostream> #include <string> #include <algorithm> using std::cin; using std::cout; using std::endl; using std::string; using std::max; using std::min; bool IsValid(const int k, const string& s1, const string& s2) { for (int i = 0; k + i < s1.length() && i < s2.length(); ++i) { if ((s1[k + i] - '0') + (s2[i] - '0') > 3) { return false; } } return true; } size_t Cut(const string& s1, const string& s2) { int k = 0; while (!IsValid(k, s1, s2)) { ++k; } return max(s1.length(), s2.length() + k); } int main() { string bottom, top; while (cin >> bottom >> top) { cout << min(Cut(bottom, top), Cut(top, bottom)) << endl; } return 0; } <|endoftext|>
<commit_before>// Time: O(n * k), k is length of the common prefix // Space: O(1) // BFS class Solution { public: /** * @param strs: A list of strings * @return: The longest common prefix */ string longestCommonPrefix(vector<string> &strs) { if (strs.empty()) { return ""; } for (int i = 0; i < strs[0].length(); ++i) { for (const auto& str : strs) { if (i >= str.length() || str[i] != strs[0][i]) { return strs[0].substr(0, i); } } } return strs[0]; } }; // Time: O(n * l), l is the max length of strings // Space: O(1) // DFS class Solution2 { public: /** * @param strs: A list of strings * @return: The longest common prefix */ string longestCommonPrefix(vector<string> &strs) { if (strs.empty()) { return ""; } auto prefix_len = strs[0].length(); for (const auto& str : strs) { auto i = 0; for (; i < str.length() && i < prefix_len && str[i] == strs[0][i]; ++i); if (i < prefix_len) { prefix_len = i; } } return strs[0].substr(0, prefix_len); } }; <commit_msg>Update longest-common-prefix.cpp<commit_after>// Time: O(n * k), k is the length of the common prefix // Space: O(1) // BFS class Solution { public: /** * @param strs: A list of strings * @return: The longest common prefix */ string longestCommonPrefix(vector<string> &strs) { if (strs.empty()) { return ""; } for (int i = 0; i < strs[0].length(); ++i) { for (const auto& str : strs) { if (i >= str.length() || str[i] != strs[0][i]) { return strs[0].substr(0, i); } } } return strs[0]; } }; // Time: O(n * l), l is the max length of strings // Space: O(1) // DFS class Solution2 { public: /** * @param strs: A list of strings * @return: The longest common prefix */ string longestCommonPrefix(vector<string> &strs) { if (strs.empty()) { return ""; } auto prefix_len = strs[0].length(); for (const auto& str : strs) { auto i = 0; for (; i < str.length() && i < prefix_len && str[i] == strs[0][i]; ++i); if (i < prefix_len) { prefix_len = i; } } return strs[0].substr(0, prefix_len); } }; <|endoftext|>
<commit_before>// Time: O(N * m * n) // Space: O(m * n) class Solution { public: int findPaths(int m, int n, int N, int i, int j) { const auto M = 1000000000 + 7; vector<vector<vector<int>>> dp(2, vector<vector<int>>(m, vector<int>(n))); for (int moves = 0; moves < N; ++moves) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j]) + (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; } } } return dp[N % 2][i][j]; } }; <commit_msg>Update out-of-boundary-paths.cpp<commit_after>// Time: O(N * m * n) // Space: O(m * n) class Solution { public: int findPaths(int m, int n, int N, int x, int y) { const auto M = 1000000000 + 7; vector<vector<vector<int>>> dp(2, vector<vector<int>>(m, vector<int>(n))); int result = 0; for (int moves = 0; moves < N; ++moves) { for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { dp[(moves + 1) % 2][i][j] = (((i == 0 ? 1 : dp[moves % 2][i - 1][j]) + (i == m - 1 ? 1 : dp[moves % 2][i + 1][j])) % M + ((j == 0 ? 1 : dp[moves % 2][i][j - 1]) + (j == n - 1 ? 1 : dp[moves % 2][i][j + 1])) % M) % M; } } } return dp[N % 2][x][y]; } }; <|endoftext|>
<commit_before>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkParameterFileParser_cxx #define __itkParameterFileParser_cxx #include "itkParameterFileParser.h" #include <itksys/SystemTools.hxx> #include <itksys/RegularExpression.hxx> namespace itk { /** * **************** Constructor *************** */ ParameterFileParser ::ParameterFileParser() { this->m_ParameterFileName = ""; this->m_ParameterMap.clear(); } // end Constructor() /** * **************** Destructor *************** */ ParameterFileParser ::~ParameterFileParser() { if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.close(); } } // end Destructor() /** * **************** GetParameterMap *************** */ const ParameterFileParser::ParameterMapType & ParameterFileParser ::GetParameterMap( void ) const { return this->m_ParameterMap; } // end GetParameterMap() /** * **************** ReadParameterFile *************** */ void ParameterFileParser ::ReadParameterFile( void ) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } this->m_ParameterFile.open( this->m_ParameterFileName, std::fstream::in ); /** Check if it opened. */ if( !this->m_ParameterFile.is_open() ) { itkExceptionMacro( << "ERROR: could not open " << this->m_ParameterFileName << " for reading." ); } /** Clear the map. */ this->m_ParameterMap.clear(); /** Loop over the parameter file, line by line. */ std::string lineIn = ""; std::string lineOut = ""; while( this->m_ParameterFile.good() ) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, lineIn ); /** Check this line. */ bool validLine = this->CheckLine( lineIn, lineOut ); if( validLine ) { /** Get the parameter name from this line and store it. */ this->GetParameterFromLine( lineIn, lineOut ); } // Otherwise, we simply ignore this line } /** Close the parameter file. */ this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } // end ReadParameterFile() /** * **************** BasicFileChecking *************** */ void ParameterFileParser ::BasicFileChecking( void ) const { /** Check if the file name is given. */ if( this->m_ParameterFileName == "" ) { itkExceptionMacro( << "ERROR: FileName has not been set." ); } /** Basic error checking: existence. */ bool exists = itksys::SystemTools::FileExists( this->m_ParameterFileName ); if( !exists ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " does not exist." ); } /** Basic error checking: file or directory. */ bool isDir = itksys::SystemTools::FileIsDirectory( this->m_ParameterFileName ); if( isDir ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " is a directory." ); } /** Check the extension. */ std::string ext = itksys::SystemTools::GetFilenameLastExtension( this->m_ParameterFileName ); if( ext != ".txt" ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " should be a text file (*.txt)." ); } } // end BasicFileChecking() /** * **************** CheckLine *************** */ bool ParameterFileParser ::CheckLine( const std::string & lineIn, std::string & lineOut ) const { /** Preprocessing of lineIn: * 1) Replace tabs with spaces * 2) Remove everything after comment sign // * 3) Remove leading spaces * 4) Remove trailing spaces */ lineOut = lineIn; itksys::SystemTools::ReplaceString( lineOut, "\t", " " ); itksys::RegularExpression commentPart( "//" ); if( commentPart.find( lineOut ) ) { lineOut = lineOut.substr( 0, commentPart.start() ); } itksys::RegularExpression leadingSpaces( "^[ ]*(.*)" ); leadingSpaces.find( lineOut ); lineOut = leadingSpaces.match( 1 ); itksys::RegularExpression trailingSpaces( "[ \t]+$" ); if( trailingSpaces.find( lineOut ) ) { lineOut = lineOut.substr( 0, trailingSpaces.start() ); } /** * Checks: * 1. Empty line -> false * 2. Comment (line starts with "//") -> false * 3. Line is not between brackets (...) -> exception * 4. Line contains less than two words -> exception * * Otherwise return true. */ /** 1. Check for non-empty lines. */ itksys::RegularExpression reNonEmptyLine( "[^ ]+" ); bool match1 = reNonEmptyLine.find( lineOut ); if( !match1 ) { return false; } /** 2. Check for comments. */ itksys::RegularExpression reComment( "^//" ); bool match2 = reComment.find( lineOut ); if( match2 ) { return false; } /** 3. Check if line is between brackets. */ if( !itksys::SystemTools::StringStartsWith( lineOut, "(" ) || !itksys::SystemTools::StringEndsWith( lineOut, ")" ) ) { std::string hint = "Line is not between brackets: \"(...)\"."; this->ThrowException( lineIn, hint ); } /** Remove brackets. */ lineOut = lineOut.substr( 1, lineOut.size() - 2 ); /** 4. Check: the line should contain at least two words. */ itksys::RegularExpression reTwoWords( "([ ]+)([^ ]+)" ); bool match4 = reTwoWords.find( lineOut ); if( !match4 ) { std::string hint = "Line does not contain a parameter name and value."; this->ThrowException( lineIn, hint ); } /** At this point we know its at least a line containing a parameter. * However, this line can still be invalid, for example: * (string &^%^*) * This will be checked later. */ return true; } // end CheckLine() /** * **************** GetParameterFromLine *************** */ void ParameterFileParser ::GetParameterFromLine( const std::string & fullLine, const std::string & line ) { /** A line has a parameter name followed by one or more parameters. * They are all separated by one or more spaces (all tabs have been * removed previously) or by quotes in case of strings. So, * 1) we split the line at the spaces or quotes * 2) the first one is the parameter name * 3) the other strings that are not a series of spaces, are parameter values */ /** 1) Split the line. */ std::vector< std::string > splittedLine; this->SplitLine( fullLine, line, splittedLine ); /** 2) Get the parameter name. */ std::string parameterName = splittedLine[ 0 ]; itksys::SystemTools::ReplaceString( parameterName, " ", "" ); splittedLine.erase( splittedLine.begin() ); /** 3) Get the parameter values. */ std::vector< std::string > parameterValues; for( unsigned int i = 0; i < splittedLine.size(); ++i ) { if( splittedLine[ i ] != "" ) { parameterValues.push_back( splittedLine[ i ] ); } } /** 4) Perform some checks on the parameter name. */ itksys::RegularExpression reInvalidCharacters1( "[.,:;!@#$%^&-+|<>?]" ); bool match = reInvalidCharacters1.find( parameterName ); if( match ) { std::string hint = "The parameter \"" + parameterName + "\" contains invalid characters (.,:;!@#$%^&-+|<>?)."; this->ThrowException( fullLine, hint ); } /** 5) Perform checks on the parameter values. */ itksys::RegularExpression reInvalidCharacters2( "[,;!@#$%&|<>?]" ); for( unsigned int i = 0; i < parameterValues.size(); ++i ) { /** For all entries some characters are not allowed. */ if( reInvalidCharacters2.find( parameterValues[ i ] ) ) { std::string hint = "The parameter value \"" + parameterValues[ i ] + "\" contains invalid characters (,;!@#$%&|<>?)."; this->ThrowException( fullLine, hint ); } } /** 6) Insert this combination in the parameter map. */ if( this->m_ParameterMap.count( parameterName ) ) { std::string hint = "The parameter \"" + parameterName + "\" is specified more than once."; this->ThrowException( fullLine, hint ); } else { this->m_ParameterMap.insert( make_pair( parameterName, parameterValues ) ); } } // end GetParameterFromLine() /** * **************** SplitLine *************** */ void ParameterFileParser ::SplitLine( const std::string & fullLine, const std::string & line, std::vector< std::string > & splittedLine ) const { splittedLine.clear(); splittedLine.resize( 1 ); /** Count the number of quotes in the line. If it is an odd value, the * line contains an error; strings should start and end with a quote, so * the total number of quotes is even. */ std::size_t numQuotes = itksys::SystemTools::CountChar( line.c_str(), '"' ); if( numQuotes % 2 == 1 ) { /** An invalid parameter line. */ std::string hint = "This line has an odd number of quotes (\")."; this->ThrowException( fullLine, hint ); } /** Loop over the line. */ std::string::const_iterator it; unsigned int index = 0; numQuotes = 0; for( it = line.begin(); it < line.end(); ++it ) { if( *it == '"' ) { /** Start a new element. */ splittedLine.push_back( "" ); index++; numQuotes++; } else if( *it == ' ' ) { /** Only start a new element if it is not a quote, otherwise just add * the space to the string. */ if( numQuotes % 2 == 0 ) { splittedLine.push_back( "" ); index++; } else { splittedLine[ index ].push_back( *it ); } } else { /** Add this character to the element. */ splittedLine[ index ].push_back( *it ); } } } // end SplitLine() /** * **************** ThrowException *************** */ void ParameterFileParser ::ThrowException( const std::string & line, const std::string & hint ) const { /** Construct an error message. */ std::string errorMessage = "ERROR: the following line in your parameter file is invalid: \n\"" + line + "\"\n" + hint + "\nPlease correct you parameter file!"; /** Throw exception. */ itkExceptionMacro( << errorMessage ); } // end ThrowException() /** * **************** ReturnParameterFileAsString *************** */ std::string ParameterFileParser ::ReturnParameterFileAsString( void ) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } this->m_ParameterFile.open( this->m_ParameterFileName, std::fstream::in ); /** Check if it opened. */ if( !this->m_ParameterFile.is_open() ) { itkExceptionMacro( << "ERROR: could not open " << this->m_ParameterFileName << " for reading." ); } /** Loop over the parameter file, line by line. */ std::string line = ""; std::string output; while( this->m_ParameterFile.good() ) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, line ); // \todo: returns bool output += line + "\n"; } /** Close the parameter file. */ this->m_ParameterFile.clear(); this->m_ParameterFile.close(); /** Return the string. */ return output; } // end ReturnParameterFileAsString() } // end namespace itk #endif // end __itkParameterFileParser_cxx <commit_msg>STYLE: Replace comparisons to "" by empty() calls in ParameterFileParser<commit_after>/*========================================================================= * * Copyright UMC Utrecht and contributors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkParameterFileParser_cxx #define __itkParameterFileParser_cxx #include "itkParameterFileParser.h" #include <itksys/SystemTools.hxx> #include <itksys/RegularExpression.hxx> namespace itk { /** * **************** Constructor *************** */ ParameterFileParser ::ParameterFileParser() { this->m_ParameterFileName = ""; this->m_ParameterMap.clear(); } // end Constructor() /** * **************** Destructor *************** */ ParameterFileParser ::~ParameterFileParser() { if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.close(); } } // end Destructor() /** * **************** GetParameterMap *************** */ const ParameterFileParser::ParameterMapType & ParameterFileParser ::GetParameterMap( void ) const { return this->m_ParameterMap; } // end GetParameterMap() /** * **************** ReadParameterFile *************** */ void ParameterFileParser ::ReadParameterFile( void ) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } this->m_ParameterFile.open( this->m_ParameterFileName, std::fstream::in ); /** Check if it opened. */ if( !this->m_ParameterFile.is_open() ) { itkExceptionMacro( << "ERROR: could not open " << this->m_ParameterFileName << " for reading." ); } /** Clear the map. */ this->m_ParameterMap.clear(); /** Loop over the parameter file, line by line. */ std::string lineIn = ""; std::string lineOut = ""; while( this->m_ParameterFile.good() ) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, lineIn ); /** Check this line. */ bool validLine = this->CheckLine( lineIn, lineOut ); if( validLine ) { /** Get the parameter name from this line and store it. */ this->GetParameterFromLine( lineIn, lineOut ); } // Otherwise, we simply ignore this line } /** Close the parameter file. */ this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } // end ReadParameterFile() /** * **************** BasicFileChecking *************** */ void ParameterFileParser ::BasicFileChecking( void ) const { /** Check if the file name is given. */ if( this->m_ParameterFileName.empty() ) { itkExceptionMacro( << "ERROR: FileName has not been set." ); } /** Basic error checking: existence. */ bool exists = itksys::SystemTools::FileExists( this->m_ParameterFileName ); if( !exists ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " does not exist." ); } /** Basic error checking: file or directory. */ bool isDir = itksys::SystemTools::FileIsDirectory( this->m_ParameterFileName ); if( isDir ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " is a directory." ); } /** Check the extension. */ std::string ext = itksys::SystemTools::GetFilenameLastExtension( this->m_ParameterFileName ); if( ext != ".txt" ) { itkExceptionMacro( << "ERROR: the file " << this->m_ParameterFileName << " should be a text file (*.txt)." ); } } // end BasicFileChecking() /** * **************** CheckLine *************** */ bool ParameterFileParser ::CheckLine( const std::string & lineIn, std::string & lineOut ) const { /** Preprocessing of lineIn: * 1) Replace tabs with spaces * 2) Remove everything after comment sign // * 3) Remove leading spaces * 4) Remove trailing spaces */ lineOut = lineIn; itksys::SystemTools::ReplaceString( lineOut, "\t", " " ); itksys::RegularExpression commentPart( "//" ); if( commentPart.find( lineOut ) ) { lineOut = lineOut.substr( 0, commentPart.start() ); } itksys::RegularExpression leadingSpaces( "^[ ]*(.*)" ); leadingSpaces.find( lineOut ); lineOut = leadingSpaces.match( 1 ); itksys::RegularExpression trailingSpaces( "[ \t]+$" ); if( trailingSpaces.find( lineOut ) ) { lineOut = lineOut.substr( 0, trailingSpaces.start() ); } /** * Checks: * 1. Empty line -> false * 2. Comment (line starts with "//") -> false * 3. Line is not between brackets (...) -> exception * 4. Line contains less than two words -> exception * * Otherwise return true. */ /** 1. Check for non-empty lines. */ itksys::RegularExpression reNonEmptyLine( "[^ ]+" ); bool match1 = reNonEmptyLine.find( lineOut ); if( !match1 ) { return false; } /** 2. Check for comments. */ itksys::RegularExpression reComment( "^//" ); bool match2 = reComment.find( lineOut ); if( match2 ) { return false; } /** 3. Check if line is between brackets. */ if( !itksys::SystemTools::StringStartsWith( lineOut, "(" ) || !itksys::SystemTools::StringEndsWith( lineOut, ")" ) ) { std::string hint = "Line is not between brackets: \"(...)\"."; this->ThrowException( lineIn, hint ); } /** Remove brackets. */ lineOut = lineOut.substr( 1, lineOut.size() - 2 ); /** 4. Check: the line should contain at least two words. */ itksys::RegularExpression reTwoWords( "([ ]+)([^ ]+)" ); bool match4 = reTwoWords.find( lineOut ); if( !match4 ) { std::string hint = "Line does not contain a parameter name and value."; this->ThrowException( lineIn, hint ); } /** At this point we know its at least a line containing a parameter. * However, this line can still be invalid, for example: * (string &^%^*) * This will be checked later. */ return true; } // end CheckLine() /** * **************** GetParameterFromLine *************** */ void ParameterFileParser ::GetParameterFromLine( const std::string & fullLine, const std::string & line ) { /** A line has a parameter name followed by one or more parameters. * They are all separated by one or more spaces (all tabs have been * removed previously) or by quotes in case of strings. So, * 1) we split the line at the spaces or quotes * 2) the first one is the parameter name * 3) the other strings that are not a series of spaces, are parameter values */ /** 1) Split the line. */ std::vector< std::string > splittedLine; this->SplitLine( fullLine, line, splittedLine ); /** 2) Get the parameter name. */ std::string parameterName = splittedLine[ 0 ]; itksys::SystemTools::ReplaceString( parameterName, " ", "" ); splittedLine.erase( splittedLine.begin() ); /** 3) Get the parameter values. */ std::vector< std::string > parameterValues; for( unsigned int i = 0; i < splittedLine.size(); ++i ) { if( ! splittedLine[ i ].empty() ) { parameterValues.push_back( splittedLine[ i ] ); } } /** 4) Perform some checks on the parameter name. */ itksys::RegularExpression reInvalidCharacters1( "[.,:;!@#$%^&-+|<>?]" ); bool match = reInvalidCharacters1.find( parameterName ); if( match ) { std::string hint = "The parameter \"" + parameterName + "\" contains invalid characters (.,:;!@#$%^&-+|<>?)."; this->ThrowException( fullLine, hint ); } /** 5) Perform checks on the parameter values. */ itksys::RegularExpression reInvalidCharacters2( "[,;!@#$%&|<>?]" ); for( unsigned int i = 0; i < parameterValues.size(); ++i ) { /** For all entries some characters are not allowed. */ if( reInvalidCharacters2.find( parameterValues[ i ] ) ) { std::string hint = "The parameter value \"" + parameterValues[ i ] + "\" contains invalid characters (,;!@#$%&|<>?)."; this->ThrowException( fullLine, hint ); } } /** 6) Insert this combination in the parameter map. */ if( this->m_ParameterMap.count( parameterName ) ) { std::string hint = "The parameter \"" + parameterName + "\" is specified more than once."; this->ThrowException( fullLine, hint ); } else { this->m_ParameterMap.insert( make_pair( parameterName, parameterValues ) ); } } // end GetParameterFromLine() /** * **************** SplitLine *************** */ void ParameterFileParser ::SplitLine( const std::string & fullLine, const std::string & line, std::vector< std::string > & splittedLine ) const { splittedLine.clear(); splittedLine.resize( 1 ); /** Count the number of quotes in the line. If it is an odd value, the * line contains an error; strings should start and end with a quote, so * the total number of quotes is even. */ std::size_t numQuotes = itksys::SystemTools::CountChar( line.c_str(), '"' ); if( numQuotes % 2 == 1 ) { /** An invalid parameter line. */ std::string hint = "This line has an odd number of quotes (\")."; this->ThrowException( fullLine, hint ); } /** Loop over the line. */ std::string::const_iterator it; unsigned int index = 0; numQuotes = 0; for( it = line.begin(); it < line.end(); ++it ) { if( *it == '"' ) { /** Start a new element. */ splittedLine.push_back( "" ); index++; numQuotes++; } else if( *it == ' ' ) { /** Only start a new element if it is not a quote, otherwise just add * the space to the string. */ if( numQuotes % 2 == 0 ) { splittedLine.push_back( "" ); index++; } else { splittedLine[ index ].push_back( *it ); } } else { /** Add this character to the element. */ splittedLine[ index ].push_back( *it ); } } } // end SplitLine() /** * **************** ThrowException *************** */ void ParameterFileParser ::ThrowException( const std::string & line, const std::string & hint ) const { /** Construct an error message. */ std::string errorMessage = "ERROR: the following line in your parameter file is invalid: \n\"" + line + "\"\n" + hint + "\nPlease correct you parameter file!"; /** Throw exception. */ itkExceptionMacro( << errorMessage ); } // end ThrowException() /** * **************** ReturnParameterFileAsString *************** */ std::string ParameterFileParser ::ReturnParameterFileAsString( void ) { /** Perform some basic checks. */ this->BasicFileChecking(); /** Open the parameter file for reading. */ if( this->m_ParameterFile.is_open() ) { this->m_ParameterFile.clear(); this->m_ParameterFile.close(); } this->m_ParameterFile.open( this->m_ParameterFileName, std::fstream::in ); /** Check if it opened. */ if( !this->m_ParameterFile.is_open() ) { itkExceptionMacro( << "ERROR: could not open " << this->m_ParameterFileName << " for reading." ); } /** Loop over the parameter file, line by line. */ std::string line = ""; std::string output; while( this->m_ParameterFile.good() ) { /** Extract a line. */ itksys::SystemTools::GetLineFromStream( this->m_ParameterFile, line ); // \todo: returns bool output += line + "\n"; } /** Close the parameter file. */ this->m_ParameterFile.clear(); this->m_ParameterFile.close(); /** Return the string. */ return output; } // end ReturnParameterFileAsString() } // end namespace itk #endif // end __itkParameterFileParser_cxx <|endoftext|>
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <hadesmem/find_pattern.hpp> #include <hadesmem/find_pattern.hpp> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/detail/lightweight_test.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/config.hpp> #include <hadesmem/error.hpp> #include <hadesmem/process.hpp> // TODO: Clean up, expand, fix, etc these tests. // TODO: Add more tests. // TODO: Fix this hack properly. #if defined(HADESMEM_INTEL) #pragma warning(push) #pragma warning(disable: 1345) #endif // #if defined(HADESMEM_INTEL) void TestFindPattern() { hadesmem::Process const process(::GetCurrentProcessId()); std::uintptr_t const process_base = reinterpret_cast<std::uintptr_t>(::GetModuleHandleW(nullptr)); void* nop = hadesmem::Find(process, L"", L"90", hadesmem::PatternFlags::kNone, 0U); BOOST_TEST_NE(nop, static_cast<void*>(nullptr)); BOOST_TEST(nop > reinterpret_cast<void*>(process_base)); void* nop_second = hadesmem::Find(process, L"", L"90", hadesmem::PatternFlags::kNone, reinterpret_cast<std::uintptr_t>(nop) - process_base); BOOST_TEST_NE(nop_second, static_cast<void*>(nullptr)); BOOST_TEST_NE(nop_second, nop); BOOST_TEST(nop_second > nop); BOOST_TEST(nop_second > reinterpret_cast<void*>(process_base)); void* find_pattern_string = hadesmem::Find(process, L"", L"46 ?? 6E 64 50 61 74 74 65 72 6E", hadesmem::PatternFlags::kScanData, 0U); BOOST_TEST_NE(find_pattern_string, static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern_string, nop); BOOST_TEST(find_pattern_string > reinterpret_cast<void*>(process_base)); BOOST_TEST_EQ(hadesmem::Find(process, L"", L"11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", hadesmem::PatternFlags::kNone, 0U), static_cast<void*>(nullptr)); BOOST_TEST_THROWS( hadesmem::Find(process, L"", L"11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", hadesmem::PatternFlags::kThrowOnUnmatch, 0U), hadesmem::Error); void* rtl_random_string = hadesmem::Find(process, L"ntdll.dll", L"52 74 6c 52 61 6e ?? 6f 6d", hadesmem::PatternFlags::kRelativeAddress, 0U); BOOST_TEST_NE(rtl_random_string, static_cast<void*>(nullptr)); BOOST_TEST_NE(rtl_random_string, find_pattern_string); HMODULE const ntdll_mod = ::GetModuleHandleW(L"ntdll"); std::uintptr_t const ntdll_base = reinterpret_cast<std::uintptr_t>(ntdll_mod); BOOST_TEST_NE(ntdll_mod, static_cast<HMODULE>(nullptr)); std::string const rtlrandom = "RtlRandom"; void* const rtl_random_string_absolute = static_cast<std::uint8_t*>(rtl_random_string) + ntdll_base; BOOST_TEST(std::equal(std::begin(rtlrandom), std::end(rtlrandom), static_cast<char const*>(rtl_random_string_absolute))); // Todo: Lea test std::wstring const pattern_file_data = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="First Call" Data="E8"> <Manipulator Name="Add" Operand1="1"/> <Manipulator Name="Rel" Operand1="5" Operand2="1"/> </Pattern> <Pattern Name="Zeros New" Data="00 ?? 00"> <Manipulator Name="Add" Operand1="1"/> <Manipulator Name="Sub" Operand1="1"/> </Pattern> <Pattern Name="Nop Other" Data="90"/> <Pattern Name="Nop Second" Data="90" Start="Nop Other"/> <Pattern Name="FindPattern String" Data="46 ?? 6E 64 50 61 74 74 65 72 6E"> <Flag Name="ScanData"/> </Pattern> </FindPattern> <FindPattern Module="ntdll.dll"> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Int3 Then Nop" Data="CC 90"/> <Pattern Name="RtlRandom String" Data="52 74 6c 52 61 6e ?? 6f 6d"/> <Pattern Name="Int3 Then Nop 0x1000" Data="CC 90" StartRVA="0x1000"/> </FindPattern> </HadesMem> )"; // TODO: Actually validate that the results are correct. hadesmem::FindPattern find_pattern(process, pattern_file_data, true); find_pattern = hadesmem::FindPattern(process, pattern_file_data, true); BOOST_TEST_EQ(find_pattern.GetModuleMap().size(), 2UL); BOOST_TEST_EQ(find_pattern.GetPatternMap(L"").size(), 5UL); BOOST_TEST_NE(find_pattern.Lookup(L"", L"First Call"), static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Zeros New"), static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Zeros New"), find_pattern.Lookup(L"", L"First Call")); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), static_cast<void*>(nullptr)); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"Nop Other"), static_cast<void*>(static_cast<std::uint8_t*>(nop) - process_base)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), find_pattern.Lookup(L"", L"First Call")); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), find_pattern.Lookup(L"", L"Zeros New")); BOOST_TEST(find_pattern.Lookup(L"", L"Nop Second") > find_pattern.Lookup(L"", L"Nop Other")); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"Nop Second"), static_cast<void*>(static_cast<std::uint8_t*>(nop_second) - process_base)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"FindPattern String"), static_cast<void*>(nullptr)); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"FindPattern String"), static_cast<void*>(static_cast<std::uint8_t*>(find_pattern_string) - process_base)); BOOST_TEST_EQ(find_pattern.GetPatternMap(L"ntdll.dll").size(), 3UL); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop"), static_cast<void*>(nullptr)); auto const int3_then_nop = find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop"); BOOST_TEST_EQ(*static_cast<char const*>(int3_then_nop), '\xCC'); BOOST_TEST_EQ(*(static_cast<char const*>(int3_then_nop) + 1), '\x90'); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), static_cast<void*>(nullptr)); BOOST_TEST(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String") > ntdll_mod); BOOST_TEST_EQ(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), rtl_random_string_absolute); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), find_pattern.Lookup(L"", L"FindPattern String")); BOOST_TEST_THROWS(find_pattern.Lookup(L"DoesNotExist", L"RtlRandom String"), hadesmem::Error); BOOST_TEST_THROWS(find_pattern.Lookup(L"ntdll.dll", L"DoesNotExist"), hadesmem::Error); auto const int3_then_nop_0x1000 = find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop 0x1000"); BOOST_TEST_EQ(*static_cast<char const*>(int3_then_nop_0x1000), '\xCC'); BOOST_TEST_EQ(*(static_cast<char const*>(int3_then_nop_0x1000)+1), '\x90'); auto const int3_then_nop_0x1000_rel = reinterpret_cast<std::uintptr_t>(int3_then_nop_0x1000)-ntdll_base; BOOST_TEST(int3_then_nop_0x1000_rel >= 0x1000U); // TODO: Fix the test to ensure we get the error we're expecting, rather // than just any error. std::wstring const pattern_file_data_invalid1 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="InvalidFlag"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid1, true), hadesmem::Error); std::wstring const pattern_file_data_invalid2 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Foo2" Data="ZZ"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid2, true), hadesmem::Error); std::wstring const pattern_file_data_invalid3 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid3, true), hadesmem::Error); std::wstring const pattern_file_data_invalid4 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Foo4" Data="90" Start="DoesNotExist"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid4, true), hadesmem::Error); // Todo: LoadFile test } int main() { TestFindPattern(); return boost::report_errors(); } #if defined(HADESMEM_INTEL) #pragma warning(pop) #endif // #if defined(HADESMEM_INTEL) <commit_msg>* [FindPattern] Add another pattern for Start. This time not using RelativeAddress.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce. // See the file COPYING for copying permission. #include <hadesmem/find_pattern.hpp> #include <hadesmem/find_pattern.hpp> #include <hadesmem/detail/warning_disable_prefix.hpp> #include <boost/detail/lightweight_test.hpp> #include <hadesmem/detail/warning_disable_suffix.hpp> #include <hadesmem/config.hpp> #include <hadesmem/error.hpp> #include <hadesmem/process.hpp> // TODO: Clean up, expand, fix, etc these tests. // TODO: Add more tests. // TODO: Fix this hack properly. #if defined(HADESMEM_INTEL) #pragma warning(push) #pragma warning(disable: 1345) #endif // #if defined(HADESMEM_INTEL) void TestFindPattern() { hadesmem::Process const process(::GetCurrentProcessId()); std::uintptr_t const process_base = reinterpret_cast<std::uintptr_t>(::GetModuleHandleW(nullptr)); void* nop = hadesmem::Find(process, L"", L"90", hadesmem::PatternFlags::kNone, 0U); BOOST_TEST_NE(nop, static_cast<void*>(nullptr)); BOOST_TEST(nop > reinterpret_cast<void*>(process_base)); void* nop_second = hadesmem::Find(process, L"", L"90", hadesmem::PatternFlags::kNone, reinterpret_cast<std::uintptr_t>(nop) - process_base); BOOST_TEST_NE(nop_second, static_cast<void*>(nullptr)); BOOST_TEST_NE(nop_second, nop); BOOST_TEST(nop_second > nop); BOOST_TEST(nop_second > reinterpret_cast<void*>(process_base)); void* find_pattern_string = hadesmem::Find(process, L"", L"46 ?? 6E 64 50 61 74 74 65 72 6E", hadesmem::PatternFlags::kScanData, 0U); BOOST_TEST_NE(find_pattern_string, static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern_string, nop); BOOST_TEST(find_pattern_string > reinterpret_cast<void*>(process_base)); BOOST_TEST_EQ(hadesmem::Find(process, L"", L"11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", hadesmem::PatternFlags::kNone, 0U), static_cast<void*>(nullptr)); BOOST_TEST_THROWS( hadesmem::Find(process, L"", L"11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF", hadesmem::PatternFlags::kThrowOnUnmatch, 0U), hadesmem::Error); void* rtl_random_string = hadesmem::Find(process, L"ntdll.dll", L"52 74 6c 52 61 6e ?? 6f 6d", hadesmem::PatternFlags::kRelativeAddress, 0U); BOOST_TEST_NE(rtl_random_string, static_cast<void*>(nullptr)); BOOST_TEST_NE(rtl_random_string, find_pattern_string); HMODULE const ntdll_mod = ::GetModuleHandleW(L"ntdll"); std::uintptr_t const ntdll_base = reinterpret_cast<std::uintptr_t>(ntdll_mod); BOOST_TEST_NE(ntdll_mod, static_cast<HMODULE>(nullptr)); std::string const rtlrandom = "RtlRandom"; void* const rtl_random_string_absolute = static_cast<std::uint8_t*>(rtl_random_string) + ntdll_base; BOOST_TEST(std::equal(std::begin(rtlrandom), std::end(rtlrandom), static_cast<char const*>(rtl_random_string_absolute))); // Todo: Lea test std::wstring const pattern_file_data = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="First Call" Data="E8"> <Manipulator Name="Add" Operand1="1"/> <Manipulator Name="Rel" Operand1="5" Operand2="1"/> </Pattern> <Pattern Name="Zeros New" Data="00 ?? 00"> <Manipulator Name="Add" Operand1="1"/> <Manipulator Name="Sub" Operand1="1"/> </Pattern> <Pattern Name="Nop Other" Data="90"/> <Pattern Name="Nop Second" Data="90" Start="Nop Other"/> <Pattern Name="FindPattern String" Data="46 ?? 6E 64 50 61 74 74 65 72 6E"> <Flag Name="ScanData"/> </Pattern> </FindPattern> <FindPattern Module="ntdll.dll"> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Int3 Then Nop" Data="CC 90"/> <Pattern Name="Int3 Then Nop Next" Data="??" Start="Int3 Then Nop"/> <Pattern Name="RtlRandom String" Data="52 74 6c 52 61 6e ?? 6f 6d"/> <Pattern Name="Int3 Then Nop 0x1000" Data="CC 90" StartRVA="0x1000"/> </FindPattern> </HadesMem> )"; // TODO: Actually validate that the results are correct. hadesmem::FindPattern find_pattern(process, pattern_file_data, true); find_pattern = hadesmem::FindPattern(process, pattern_file_data, true); BOOST_TEST_EQ(find_pattern.GetModuleMap().size(), 2UL); BOOST_TEST_EQ(find_pattern.GetPatternMap(L"").size(), 5UL); BOOST_TEST_NE(find_pattern.Lookup(L"", L"First Call"), static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Zeros New"), static_cast<void*>(nullptr)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Zeros New"), find_pattern.Lookup(L"", L"First Call")); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), static_cast<void*>(nullptr)); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"Nop Other"), static_cast<void*>(static_cast<std::uint8_t*>(nop) - process_base)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), find_pattern.Lookup(L"", L"First Call")); BOOST_TEST_NE(find_pattern.Lookup(L"", L"Nop Other"), find_pattern.Lookup(L"", L"Zeros New")); BOOST_TEST(find_pattern.Lookup(L"", L"Nop Second") > find_pattern.Lookup(L"", L"Nop Other")); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"Nop Second"), static_cast<void*>(static_cast<std::uint8_t*>(nop_second) - process_base)); BOOST_TEST_NE(find_pattern.Lookup(L"", L"FindPattern String"), static_cast<void*>(nullptr)); BOOST_TEST_EQ( find_pattern.Lookup(L"", L"FindPattern String"), static_cast<void*>(static_cast<std::uint8_t*>(find_pattern_string) - process_base)); BOOST_TEST_EQ(find_pattern.GetPatternMap(L"ntdll.dll").size(), 4UL); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop"), static_cast<void*>(nullptr)); auto const int3_then_nop = find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop"); BOOST_TEST_EQ(*static_cast<char const*>(int3_then_nop), '\xCC'); BOOST_TEST_EQ(*(static_cast<char const*>(int3_then_nop)+1), '\x90'); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop Next"), static_cast<void*>(nullptr)); BOOST_TEST(find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop Next") > find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop")); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), static_cast<void*>(nullptr)); BOOST_TEST(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String") > ntdll_mod); BOOST_TEST_EQ(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), rtl_random_string_absolute); BOOST_TEST_NE(find_pattern.Lookup(L"ntdll.dll", L"RtlRandom String"), find_pattern.Lookup(L"", L"FindPattern String")); BOOST_TEST_THROWS(find_pattern.Lookup(L"DoesNotExist", L"RtlRandom String"), hadesmem::Error); BOOST_TEST_THROWS(find_pattern.Lookup(L"ntdll.dll", L"DoesNotExist"), hadesmem::Error); auto const int3_then_nop_0x1000 = find_pattern.Lookup(L"ntdll.dll", L"Int3 Then Nop 0x1000"); BOOST_TEST_EQ(*static_cast<char const*>(int3_then_nop_0x1000), '\xCC'); BOOST_TEST_EQ(*(static_cast<char const*>(int3_then_nop_0x1000)+1), '\x90'); auto const int3_then_nop_0x1000_rel = reinterpret_cast<std::uintptr_t>(int3_then_nop_0x1000)-ntdll_base; BOOST_TEST(int3_then_nop_0x1000_rel >= 0x1000U); // TODO: Fix the test to ensure we get the error we're expecting, rather // than just any error. std::wstring const pattern_file_data_invalid1 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="InvalidFlag"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid1, true), hadesmem::Error); std::wstring const pattern_file_data_invalid2 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Foo2" Data="ZZ"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid2, true), hadesmem::Error); std::wstring const pattern_file_data_invalid3 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid3, true), hadesmem::Error); std::wstring const pattern_file_data_invalid4 = LR"( <?xml version="1.0" encoding="utf-8"?> <HadesMem> <FindPattern> <Flag Name="RelativeAddress"/> <Flag Name="ThrowOnUnmatch"/> <Pattern Name="Foo4" Data="90" Start="DoesNotExist"/> </FindPattern> </HadesMem> )"; BOOST_TEST_THROWS( hadesmem::FindPattern(process, pattern_file_data_invalid4, true), hadesmem::Error); // Todo: LoadFile test } int main() { TestFindPattern(); return boost::report_errors(); } #if defined(HADESMEM_INTEL) #pragma warning(pop) #endif // #if defined(HADESMEM_INTEL) <|endoftext|>
<commit_before>#include <bx/bx.h> #include <bx/timer.h> #include <bx/handlealloc.h> #include <bx/maputil.h> #include <tinystl/allocator.h> #include <tinystl/unordered_map.h> #include <unordered_map> #include <stdio.h> #include <assert.h> int main() { const uint32_t numElements = 4<<10; const uint32_t numIterations = 16; // { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef tinystl::unordered_map<uint64_t, uint16_t> TinyStlUnorderedMap; TinyStlUnorderedMap map; // map.reserve(numElements); for (uint32_t jj = 0; jj < numElements; ++jj) { tinystl::pair<TinyStlUnorderedMap::iterator, bool> ok = map.insert(tinystl::make_pair(uint64_t(jj), uint16_t(jj) ) ); assert(ok.second); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = bx::mapRemove(map, uint64_t(jj) ); assert(ok); } assert(map.size() == 0); } elapsed += bx::getHPCounter(); printf(" TinyStl: %15f\n", double(elapsed) ); } /// { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef std::unordered_map<uint64_t, uint16_t> StdUnorderedMap; StdUnorderedMap map; map.reserve(numElements); for (uint32_t jj = 0; jj < numElements; ++jj) { std::pair<StdUnorderedMap::iterator, bool> ok = map.insert(std::make_pair(uint64_t(jj), uint16_t(jj) ) ); assert(ok.second); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = bx::mapRemove(map, uint64_t(jj) ); assert(ok); } assert(map.size() == 0); } elapsed += bx::getHPCounter(); printf(" STL: %15f\n", double(elapsed) ); } /// { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef bx::HandleHashMapT<numElements+numElements/2, uint64_t> HandleHashMap; HandleHashMap map; for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = map.insert(jj, uint16_t(jj) ); assert(ok); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = map.removeByKey(uint64_t(jj) ); assert(ok); } assert(map.getNumElements() == 0); } elapsed += bx::getHPCounter(); printf("HandleHashMap: %15f\n", double(elapsed) ); } return EXIT_SUCCESS; } <commit_msg>Fixed build.<commit_after>#include <bx/bx.h> #include <bx/timer.h> #include <bx/handlealloc.h> #include <bx/maputil.h> #include <tinystl/allocator.h> #include <tinystl/unordered_map.h> #include <unordered_map> #include <stdio.h> #include <assert.h> int main() { const uint32_t numElements = 4<<10; const uint32_t numIterations = 16; // { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef tinystl::unordered_map<uint64_t, uint16_t> TinyStlUnorderedMap; TinyStlUnorderedMap map; // map.reserve(numElements); for (uint32_t jj = 0; jj < numElements; ++jj) { tinystl::pair<TinyStlUnorderedMap::iterator, bool> ok = map.insert(tinystl::make_pair(uint64_t(jj), uint16_t(jj) ) ); assert(ok.second); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = bx::mapRemove(map, uint64_t(jj) ); assert(ok); } assert(map.size() == 0); } elapsed += bx::getHPCounter(); printf(" TinyStl: %15f\n", double(elapsed) ); } /// { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef std::unordered_map<uint64_t, uint16_t> StdUnorderedMap; StdUnorderedMap map; // map.reserve(numElements); for (uint32_t jj = 0; jj < numElements; ++jj) { std::pair<StdUnorderedMap::iterator, bool> ok = map.insert(std::make_pair(uint64_t(jj), uint16_t(jj) ) ); assert(ok.second); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = bx::mapRemove(map, uint64_t(jj) ); assert(ok); } assert(map.size() == 0); } elapsed += bx::getHPCounter(); printf(" STL: %15f\n", double(elapsed) ); } /// { int64_t elapsed = -bx::getHPCounter(); for (uint32_t ii = 0; ii < numIterations; ++ii) { typedef bx::HandleHashMapT<numElements+numElements/2, uint64_t> HandleHashMap; HandleHashMap map; for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = map.insert(jj, uint16_t(jj) ); assert(ok); } for (uint32_t jj = 0; jj < numElements; ++jj) { bool ok = map.removeByKey(uint64_t(jj) ); assert(ok); } assert(map.getNumElements() == 0); } elapsed += bx::getHPCounter(); printf("HandleHashMap: %15f\n", double(elapsed) ); } return EXIT_SUCCESS; } <|endoftext|>
<commit_before>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "iotests.h" #include <gtest/gtest.h> #include <avogadro/core/matrix.h> #include <avogadro/core/molecule.h> #include <avogadro/io/cjsonformat.h> using Avogadro::Core::Molecule; using Avogadro::Core::Atom; using Avogadro::Core::Bond; using Avogadro::Io::CjsonFormat; using Avogadro::MatrixX; TEST(CjsonTest, readFile) { CjsonFormat cjson; Molecule molecule; cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_EQ(molecule.data("name").type(), Avogadro::Core::Variant::String); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.data("inchi").type(), Avogadro::Core::Variant::String); EXPECT_EQ(molecule.data("inchi").toString(), "1/C2H6/c1-2/h1-2H3"); } TEST(CjsonTest, atoms) { CjsonFormat cjson; Molecule molecule; cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); Atom atom = molecule.atom(0); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); atom = molecule.atom(1); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(6)); EXPECT_EQ(atom.position3d().x(), 0.751621); EXPECT_EQ(atom.position3d().y(), -0.022441); EXPECT_EQ(atom.position3d().z(), -0.020839); atom = molecule.atom(7); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); EXPECT_EQ(atom.position3d().x(), -1.184988); EXPECT_EQ(atom.position3d().y(), 0.004424); EXPECT_EQ(atom.position3d().z(), -0.987522); } TEST(CjsonTest, bonds) { CjsonFormat cjson; Molecule molecule; cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); EXPECT_EQ(molecule.bondCount(), static_cast<size_t>(7)); Bond bond = molecule.bond(0); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(0)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(1)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); bond = molecule.bond(6); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(4)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(7)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); } TEST(CjsonTest, saveFile) { CjsonFormat cjson; Molecule savedMolecule, molecule; cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", savedMolecule); cjson.writeFile("ethanetmp.cjson", savedMolecule); // Now read the file back in and check a few key values are still present. cjson.readFile("ethanetmp.cjson", molecule); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); EXPECT_EQ(molecule.bondCount(), static_cast<size_t>(7)); Atom atom = molecule.atom(7); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); EXPECT_EQ(atom.position3d().x(), -1.184988); EXPECT_EQ(atom.position3d().y(), 0.004424); EXPECT_EQ(atom.position3d().z(), -0.987522); Bond bond = molecule.bond(0); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(0)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(1)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); } <commit_msg>Check return value from read and write calls<commit_after>/****************************************************************************** This source file is part of the Avogadro project. Copyright 2012 Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "iotests.h" #include <gtest/gtest.h> #include <avogadro/core/matrix.h> #include <avogadro/core/molecule.h> #include <avogadro/io/cjsonformat.h> using Avogadro::Core::Molecule; using Avogadro::Core::Atom; using Avogadro::Core::Bond; using Avogadro::Io::CjsonFormat; using Avogadro::MatrixX; TEST(CjsonTest, readFile) { CjsonFormat cjson; Molecule molecule; bool success = cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); EXPECT_EQ(molecule.data("name").type(), Avogadro::Core::Variant::String); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.data("inchi").type(), Avogadro::Core::Variant::String); EXPECT_EQ(molecule.data("inchi").toString(), "1/C2H6/c1-2/h1-2H3"); } TEST(CjsonTest, atoms) { CjsonFormat cjson; Molecule molecule; bool success = cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); Atom atom = molecule.atom(0); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); atom = molecule.atom(1); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(6)); EXPECT_EQ(atom.position3d().x(), 0.751621); EXPECT_EQ(atom.position3d().y(), -0.022441); EXPECT_EQ(atom.position3d().z(), -0.020839); atom = molecule.atom(7); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); EXPECT_EQ(atom.position3d().x(), -1.184988); EXPECT_EQ(atom.position3d().y(), 0.004424); EXPECT_EQ(atom.position3d().z(), -0.987522); } TEST(CjsonTest, bonds) { CjsonFormat cjson; Molecule molecule; bool success = cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", molecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); EXPECT_EQ(molecule.bondCount(), static_cast<size_t>(7)); Bond bond = molecule.bond(0); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(0)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(1)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); bond = molecule.bond(6); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(4)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(7)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); } TEST(CjsonTest, saveFile) { CjsonFormat cjson; Molecule savedMolecule, molecule; bool success = cjson.readFile(std::string(AVOGADRO_DATA) + "/data/ethane.cjson", savedMolecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); success = cjson.writeFile("ethanetmp.cjson", savedMolecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); // Now read the file back in and check a few key values are still present. success = cjson.readFile("ethanetmp.cjson", molecule); EXPECT_TRUE(success); EXPECT_EQ(cjson.error(), ""); EXPECT_EQ(molecule.data("name").toString(), "Ethane"); EXPECT_EQ(molecule.atomCount(), static_cast<size_t>(8)); EXPECT_EQ(molecule.bondCount(), static_cast<size_t>(7)); Atom atom = molecule.atom(7); EXPECT_EQ(atom.atomicNumber(), static_cast<unsigned char>(1)); EXPECT_EQ(atom.position3d().x(), -1.184988); EXPECT_EQ(atom.position3d().y(), 0.004424); EXPECT_EQ(atom.position3d().z(), -0.987522); Bond bond = molecule.bond(0); EXPECT_EQ(bond.atom1().index(), static_cast<size_t>(0)); EXPECT_EQ(bond.atom2().index(), static_cast<size_t>(1)); EXPECT_EQ(bond.order(), static_cast<unsigned char>(1)); } <|endoftext|>
<commit_before>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQLayoutsWidget.cpp,v $ // $Revision: 1.2 $ // $Name: $ // $Author: gauges $ // $Date: 2008/09/09 03:41:52 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQLayoutsWidget.h" #include <qlayout.h> #include <qwidget.h> #include <qfont.h> #include <qpushbutton.h> #include <qaction.h> #include <qregexp.h> #include <qvalidator.h> #include <iostream> #include "CQMessageBox.h" #include "listviews.h" #include "qtUtilities.h" #include "copasi/layout/CLayout.h" #include "copasi/layout/CListOfLayouts.h" #include "copasi/report/CKeyFactory.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/layoutUI/CQLayoutMainWindow.h" #define COL_MARK 0 #define COL_NAME 1 #define COL_SHOW 2 std::vector<const CCopasiObject*> CQLayoutsWidget::getObjects() const { CListOfLayouts* pListOfLayouts = CCopasiDataModel::Global->getListOfLayouts(); std::vector<const CCopasiObject*> ret; C_INT32 i, imax = pListOfLayouts->size(); for (i = 0; i < imax; ++i) ret.push_back((*pListOfLayouts)[i]); return ret; } void CQLayoutsWidget::init() { this->btnNew->hide(); mOT = ListViews::LAYOUT; numCols = 3; table->setNumCols(numCols); //Setting table headers QHeader *tableHeader = table->horizontalHeader(); tableHeader->setLabel(COL_MARK, "Status"); tableHeader->setLabel(COL_NAME, "Name"); tableHeader->setLabel(COL_SHOW, "Show"); } void CQLayoutsWidget::updateHeaderUnits() { // no units, so we do nothing } void CQLayoutsWidget::tableLineFromObject(const CCopasiObject* obj, unsigned C_INT32 row) { if (!obj) return; const CLayout * pLayout = static_cast< const CLayout * >(obj); // Name table->setText(row, COL_NAME, FROM_UTF8(pLayout->getObjectName())); CQShowLayoutButton* pButton = new CQShowLayoutButton(row, NULL); pButton->setText("Show"); table->setCellWidget(row, COL_SHOW, pButton); connect(pButton, SIGNAL(signal_show(int)), this, SLOT(slot_show(int))); std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(obj->getKey()); // if this layout does not have an entry in the layout window map, add one if (pos == this->mLayoutWindowMap.end()) { this->mLayoutWindowMap.insert(std::pair<std::string, CQLayoutMainWindow*>(obj->getKey(), NULL)); } } void CQLayoutsWidget::tableLineToObject(unsigned C_INT32 /*row*/, CCopasiObject* /*obj*/) { // I don't know what this is supposed to do, but right now it does nothing //if (!obj) return; //CLayout * pLayout = static_cast< CLayout * >(obj); } void CQLayoutsWidget::defaultTableLineContent(unsigned C_INT32 /*row*/, unsigned C_INT32 /*exc*/) { // nothin to do here } QString CQLayoutsWidget::defaultObjectName() const { return "layout"; } CCopasiObject* CQLayoutsWidget::createNewObject(const std::string & /*name*/) { /* * Can't create layouts yet. std::string nname = name; int i = 0; CLayout* playout; while (!(pLayout = CCopasiDataModel::Global->createLayout(nname))) { i++; nname = name + "_"; nname += (const char *)QString::number(i).utf8(); } return pLayout; */ return NULL; } void CQLayoutsWidget::deleteObjects(const std::vector<std::string> & keys) { if (keys.size() == 0) return; QString layoutList = "Are you sure you want to delete listed LAYOUT(S) ?\n"; unsigned C_INT32 i, imax = keys.size(); for (i = 0; i < imax; i++) //all compartments { CLayout* pLayout = dynamic_cast< CLayout *>(GlobalKeys.get(keys[i])); layoutList.append(FROM_UTF8(pLayout->getObjectName())); layoutList.append(", "); } layoutList.remove(layoutList.length() - 2, 2); QString msg = layoutList; C_INT32 choice = 0; switch (choice) { case 0: // Yes or Enter { for (i = 0; i < imax; i++) { CCopasiDataModel::Global->removeLayout(keys[i]); std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(keys[i]); if (pos != this->mLayoutWindowMap.end() && pos->second != NULL) { // close the window pos->second->close(); } } for (i = 0; i < imax; i++) protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, keys[i]); mChanged = true; break; } default: // No or Escape break; } } void CQLayoutsWidget::valueChanged(unsigned C_INT32 /*row*/, unsigned C_INT32 /*col*/) { /* * Does nothing at the moment. switch (col) { default: break; } */ return; } /** * We overwrite the slotDoubleClicked from CopasiTableWidget since we don't * want to switch to another folder in the ListView but we want to open or display a layout window. */ void CQLayoutsWidget::slotDoubleClicked(int row, int C_UNUSED(col), int C_UNUSED(m), const QPoint & C_UNUSED(n)) { if (row >= table->numRows() || row < 0) return; if (mRO && (row == table->numRows() - 1)) return; std::string key = mKeys[row]; bool flagNew = false; if (mFlagNew[row]) { saveTable(); fillTable(); return; //TODO: When double clicking on a new object the object should be created. } if (mFlagDelete[row]) { return; } if (row == table->numRows() - 1) //new Object { flagNew = true; resizeTable(table->numRows() + 1); mFlagNew[row] = true; table->setText(row, 1, createNewName(defaultObjectName())); defaultTableLineContent(row, 0); } saveTable(); if (flagNew) { key = mKeys[row]; } fillTable(); this->slot_show(row); } void CQLayoutsWidget::slot_show(int row) { std::string key = mKeys[row]; CLayout* pLayout = dynamic_cast<CLayout*>(GlobalKeys.get(key)); if (pLayout != NULL) { // check if we already have a widget for the layout // if yes, open it, else create one and add it to the map bool createNew = false; std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(key); if (pos != this->mLayoutWindowMap.end()) { if (pos->second == NULL) { createNew = true; } else { pos->second->show(); pos->second->showNormal(); pos->second->setActiveWindow(); } } else { createNew = true; } if (createNew) { CQLayoutMainWindow* pWin = new CQLayoutMainWindow(pLayout, this, pLayout->getObjectName().c_str()); pWin->resize(900, 430); pWin->show(); this->mLayoutWindowMap[key] = pWin; } } else { std::cerr << "Could not find layout." << std::endl; } } void CQShowLayoutButton::slot_clicked() { emit signal_show(this->mRow); } CQShowLayoutButton::CQShowLayoutButton(unsigned int row, QWidget* pParent, const char* name): QToolButton(pParent, name), mRow(row) { this->setTextLabel("Show"); connect(this, SIGNAL(clicked()), this, SLOT(slot_clicked())); } <commit_msg>Changed the default size for the layout windows.<commit_after>// Begin CVS Header // $Source: /Volumes/Home/Users/shoops/cvs/copasi_dev/copasi/UI/CQLayoutsWidget.cpp,v $ // $Revision: 1.3 $ // $Name: $ // $Author: gauges $ // $Date: 2008/09/09 09:15:16 $ // End CVS Header // Copyright (C) 2008 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQLayoutsWidget.h" #include <qlayout.h> #include <qwidget.h> #include <qfont.h> #include <qpushbutton.h> #include <qaction.h> #include <qregexp.h> #include <qvalidator.h> #include <iostream> #include "CQMessageBox.h" #include "listviews.h" #include "qtUtilities.h" #include "copasi/layout/CLayout.h" #include "copasi/layout/CListOfLayouts.h" #include "copasi/report/CKeyFactory.h" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/layoutUI/CQLayoutMainWindow.h" #define COL_MARK 0 #define COL_NAME 1 #define COL_SHOW 2 std::vector<const CCopasiObject*> CQLayoutsWidget::getObjects() const { CListOfLayouts* pListOfLayouts = CCopasiDataModel::Global->getListOfLayouts(); std::vector<const CCopasiObject*> ret; C_INT32 i, imax = pListOfLayouts->size(); for (i = 0; i < imax; ++i) ret.push_back((*pListOfLayouts)[i]); return ret; } void CQLayoutsWidget::init() { this->btnNew->hide(); mOT = ListViews::LAYOUT; numCols = 3; table->setNumCols(numCols); //Setting table headers QHeader *tableHeader = table->horizontalHeader(); tableHeader->setLabel(COL_MARK, "Status"); tableHeader->setLabel(COL_NAME, "Name"); tableHeader->setLabel(COL_SHOW, "Show"); } void CQLayoutsWidget::updateHeaderUnits() { // no units, so we do nothing } void CQLayoutsWidget::tableLineFromObject(const CCopasiObject* obj, unsigned C_INT32 row) { if (!obj) return; const CLayout * pLayout = static_cast< const CLayout * >(obj); // Name table->setText(row, COL_NAME, FROM_UTF8(pLayout->getObjectName())); CQShowLayoutButton* pButton = new CQShowLayoutButton(row, NULL); pButton->setText("Show"); table->setCellWidget(row, COL_SHOW, pButton); connect(pButton, SIGNAL(signal_show(int)), this, SLOT(slot_show(int))); std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(obj->getKey()); // if this layout does not have an entry in the layout window map, add one if (pos == this->mLayoutWindowMap.end()) { this->mLayoutWindowMap.insert(std::pair<std::string, CQLayoutMainWindow*>(obj->getKey(), NULL)); } } void CQLayoutsWidget::tableLineToObject(unsigned C_INT32 /*row*/, CCopasiObject* /*obj*/) { // I don't know what this is supposed to do, but right now it does nothing //if (!obj) return; //CLayout * pLayout = static_cast< CLayout * >(obj); } void CQLayoutsWidget::defaultTableLineContent(unsigned C_INT32 /*row*/, unsigned C_INT32 /*exc*/) { // nothin to do here } QString CQLayoutsWidget::defaultObjectName() const { return "layout"; } CCopasiObject* CQLayoutsWidget::createNewObject(const std::string & /*name*/) { /* * Can't create layouts yet. std::string nname = name; int i = 0; CLayout* playout; while (!(pLayout = CCopasiDataModel::Global->createLayout(nname))) { i++; nname = name + "_"; nname += (const char *)QString::number(i).utf8(); } return pLayout; */ return NULL; } void CQLayoutsWidget::deleteObjects(const std::vector<std::string> & keys) { if (keys.size() == 0) return; QString layoutList = "Are you sure you want to delete listed LAYOUT(S) ?\n"; unsigned C_INT32 i, imax = keys.size(); for (i = 0; i < imax; i++) //all compartments { CLayout* pLayout = dynamic_cast< CLayout *>(GlobalKeys.get(keys[i])); layoutList.append(FROM_UTF8(pLayout->getObjectName())); layoutList.append(", "); } layoutList.remove(layoutList.length() - 2, 2); QString msg = layoutList; C_INT32 choice = 0; switch (choice) { case 0: // Yes or Enter { for (i = 0; i < imax; i++) { CCopasiDataModel::Global->removeLayout(keys[i]); std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(keys[i]); if (pos != this->mLayoutWindowMap.end() && pos->second != NULL) { // close the window pos->second->close(); } } for (i = 0; i < imax; i++) protectedNotify(ListViews::COMPARTMENT, ListViews::DELETE, keys[i]); mChanged = true; break; } default: // No or Escape break; } } void CQLayoutsWidget::valueChanged(unsigned C_INT32 /*row*/, unsigned C_INT32 /*col*/) { /* * Does nothing at the moment. switch (col) { default: break; } */ return; } /** * We overwrite the slotDoubleClicked from CopasiTableWidget since we don't * want to switch to another folder in the ListView but we want to open or display a layout window. */ void CQLayoutsWidget::slotDoubleClicked(int row, int C_UNUSED(col), int C_UNUSED(m), const QPoint & C_UNUSED(n)) { if (row >= table->numRows() || row < 0) return; if (mRO && (row == table->numRows() - 1)) return; std::string key = mKeys[row]; bool flagNew = false; if (mFlagNew[row]) { saveTable(); fillTable(); return; //TODO: When double clicking on a new object the object should be created. } if (mFlagDelete[row]) { return; } if (row == table->numRows() - 1) //new Object { flagNew = true; resizeTable(table->numRows() + 1); mFlagNew[row] = true; table->setText(row, 1, createNewName(defaultObjectName())); defaultTableLineContent(row, 0); } saveTable(); if (flagNew) { key = mKeys[row]; } fillTable(); this->slot_show(row); } void CQLayoutsWidget::slot_show(int row) { std::string key = mKeys[row]; CLayout* pLayout = dynamic_cast<CLayout*>(GlobalKeys.get(key)); if (pLayout != NULL) { // check if we already have a widget for the layout // if yes, open it, else create one and add it to the map bool createNew = false; std::map<std::string, CQLayoutMainWindow*>::iterator pos = this->mLayoutWindowMap.find(key); if (pos != this->mLayoutWindowMap.end()) { if (pos->second == NULL) { createNew = true; } else { pos->second->show(); pos->second->showNormal(); pos->second->setActiveWindow(); } } else { createNew = true; } if (createNew) { CQLayoutMainWindow* pWin = new CQLayoutMainWindow(pLayout, this, pLayout->getObjectName().c_str()); pWin->resize(900, 600); pWin->show(); this->mLayoutWindowMap[key] = pWin; } } else { std::cerr << "Could not find layout." << std::endl; } } void CQShowLayoutButton::slot_clicked() { emit signal_show(this->mRow); } CQShowLayoutButton::CQShowLayoutButton(unsigned int row, QWidget* pParent, const char* name): QToolButton(pParent, name), mRow(row) { this->setTextLabel("Show"); connect(this, SIGNAL(clicked()), this, SLOT(slot_clicked())); } <|endoftext|>
<commit_before>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQSpeciesWidget.h" #include <QtGui/QHeaderView> #include <QtGui/QClipboard> #include <QtGui/QKeyEvent> #include "copasi.h" #include "qtUtilities.h" #include "CQMessageBox.h" #include "model/CModel.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "copasiui3window.h" /* * Constructs a CQSpeciesWidget which is a child of 'parent', with the * name 'name'.' */ CQSpeciesWidget::CQSpeciesWidget(QWidget* parent, const char* name) : CopasiWidget(parent, name) { setupUi(this); //Create Source Data Model. mpSpecieDM = new CQSpecieDM(this); //Create the Proxy Model for sorting/filtering and set its properties. mpProxyModel = new CQSortFilterProxyModel(); mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); mpProxyModel->setFilterKeyColumn(-1); mpProxyModel->setSourceModel(mpSpecieDM); mpTblSpecies->setModel(mpProxyModel); //Setting values for Compartment comboBox mpCompartmentDelegate = new CQComboDelegate(this, mCompartments); mpTblSpecies->setItemDelegateForColumn(COL_COMPARTMENT, mpCompartmentDelegate); //Setting values for Types comboBox mpTypeDelegate = new CQIndexComboDelegate(this, mpSpecieDM->getTypes()); mpTblSpecies->setItemDelegateForColumn(COL_TYPE_SPECIES, mpTypeDelegate); mpTblSpecies->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTblSpecies->verticalHeader()->hide(); mpTblSpecies->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); // Connect the table widget connect(mpSpecieDM, SIGNAL(notifyGUI(ListViews::ObjectType, ListViews::Action, const std::string)), this, SLOT(protectedNotify(ListViews::ObjectType, ListViews::Action, const std::string))); connect(mpSpecieDM, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&))); connect(mpLEFilter, SIGNAL(textChanged(const QString &)), this, SLOT(slotFilterChanged())); CopasiUI3Window * pWindow = dynamic_cast<CopasiUI3Window * >(parent->parent()); mpSpecieDM->setUndoStack(pWindow->getUndoStack()); } /* * Destroys the object and frees any allocated resources */ CQSpeciesWidget::~CQSpeciesWidget() { pdelete(mpCompartmentDelegate); pdelete(mpTypeDelegate); pdelete(mpProxyModel); pdelete(mpSpecieDM); // no need to delete child widgets, Qt does it all for us } void CQSpeciesWidget::slotBtnNewClicked() { mpSpecieDM->insertRow(mpSpecieDM->rowCount() - 1, QModelIndex()); updateDeleteBtns(); } void CQSpeciesWidget::slotBtnDeleteClicked() { if (mpTblSpecies->hasFocus()) {deleteSelectedSpecies();} updateDeleteBtns(); } void CQSpeciesWidget::deleteSelectedSpecies() { const QItemSelectionModel * pSelectionModel = mpTblSpecies->selectionModel(); QModelIndexList mappedSelRows; size_t i, imax = mpSpecieDM->rowCount(); for (i = 0; i < imax; i++) { if (pSelectionModel->isRowSelected((int) i, QModelIndex())) { mappedSelRows.append(mpProxyModel->mapToSource(mpProxyModel->index((int) i, 0))); } } if (mappedSelRows.empty()) {return;} mpSpecieDM->removeRows(mappedSelRows); } void CQSpeciesWidget::slotBtnClearClicked() { int ret = CQMessageBox::question(this, tr("Confirm Delete"), "Delete all Species?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpSpecieDM->clear(); } updateDeleteBtns(); } bool CQSpeciesWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { if (!mIgnoreUpdates && isVisible()) { enterProtected(); } return true; } bool CQSpeciesWidget::leave() { return true; } bool CQSpeciesWidget::enterProtected() { if (mpTblSpecies->selectionModel() != NULL) { disconnect(mpTblSpecies->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(slotSelectionChanged(const QItemSelection&, const QItemSelection&))); } mpProxyModel->setSourceModel(mpSpecieDM); //Set Model for the TableView mpTblSpecies->setModel(NULL); mpTblSpecies->setModel(mpProxyModel); connect(mpTblSpecies->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(slotSelectionChanged(const QItemSelection&, const QItemSelection&))); updateDeleteBtns(); mpTblSpecies->resizeColumnsToContents(); setFramework(mFramework); refreshCompartments(); return true; } void CQSpeciesWidget::updateDeleteBtns() { bool selected = false; QModelIndexList selRows = mpTblSpecies->selectionModel()->selectedRows(); if (selRows.size() == 0) selected = false; else { if (selRows.size() == 1) { if (mpSpecieDM->isDefaultRow(mpProxyModel->mapToSource(selRows[0]))) selected = false; else selected = true; } else selected = true; } mpBtnDelete->setEnabled(selected); if (mpProxyModel->rowCount() - 1) mpBtnClear->setEnabled(true); else mpBtnClear->setEnabled(false); } void CQSpeciesWidget::slotSelectionChanged(const QItemSelection& C_UNUSED(selected), const QItemSelection& C_UNUSED(deselected)) { updateDeleteBtns(); } void CQSpeciesWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft), const QModelIndex& C_UNUSED(bottomRight)) { mpTblSpecies->resizeColumnsToContents(); setFramework(mFramework); refreshCompartments(); updateDeleteBtns(); } void CQSpeciesWidget::slotDoubleClicked(const QModelIndex proxyIndex) { QModelIndex index = mpProxyModel->mapToSource(proxyIndex); if (index.row() < 0) return; if (mpSpecieDM->isDefaultRow(index)) { slotBtnNewClicked(); } assert(CCopasiRootContainer::getDatamodelList()->size() > 0); CCopasiDataModel* pDataModel = &CCopasiRootContainer::getDatamodelList()->operator[](0); assert(pDataModel != NULL); CModel * pModel = pDataModel->getModel(); if (pModel == NULL) return; std::string key = pModel->getMetabolites()[index.row()].getKey(); if (CCopasiRootContainer::getKeyFactory()->get(key)) mpListView->switchToOtherWidget(C_INVALID_INDEX, key); } void CQSpeciesWidget::keyPressEvent(QKeyEvent* ev) { if (ev->key() == Qt::Key_Delete) slotBtnDeleteClicked(); else if (ev->key() == Qt::Key_C && (ev->modifiers() & Qt::ControlModifier)) { QModelIndexList selRows = mpTblSpecies->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QString str; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) { for (int x = 0; x < mpSpecieDM->columnCount(); ++x) { if (!mpTblSpecies->isColumnHidden(x)) { if (!str.isEmpty()) str += "\t"; str += mpSpecieDM->index(mpProxyModel->mapToSource(*i).row(), x).data().toString(); } } str += "\n"; } QApplication::clipboard()->setText(str); } } void CQSpeciesWidget::slotFilterChanged() { QRegExp regExp(mpLEFilter->text() + "|New Species", Qt::CaseInsensitive, QRegExp::RegExp); mpProxyModel->setFilterRegExp(regExp); } void CQSpeciesWidget::setFramework(int framework) { CopasiWidget::setFramework(framework); switch (mFramework) { case 0: mpTblSpecies->showColumn(COL_ICONCENTRATION); mpTblSpecies->showColumn(COL_CONCENTRATION); mpTblSpecies->showColumn(COL_CRATE); mpTblSpecies->hideColumn(COL_INUMBER); mpTblSpecies->hideColumn(COL_NUMBER); mpTblSpecies->hideColumn(COL_NRATE); mpSpecieDM->setFlagConc(true); break; case 1: mpTblSpecies->hideColumn(COL_ICONCENTRATION); mpTblSpecies->hideColumn(COL_CONCENTRATION); mpTblSpecies->hideColumn(COL_CRATE); mpTblSpecies->showColumn(COL_INUMBER); mpTblSpecies->showColumn(COL_NUMBER); mpTblSpecies->showColumn(COL_NRATE); mpSpecieDM->setFlagConc(false); break; } } void CQSpeciesWidget::refreshCompartments() { const CCopasiVector < CCompartment > & compartments = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel()->getCompartments(); mCompartments.clear(); for (unsigned C_INT32 jj = 0; jj < compartments.size(); jj++) mCompartments.push_back(FROM_UTF8(compartments[jj].getObjectName())); mpCompartmentDelegate->setItems(-1, mCompartments); } <commit_msg>- disable commit on select, as otherwise the species will be removed before the editor disapears resulting in two species being assigned the new type.<commit_after>// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. // Copyright (C) 2009 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., EML Research, gGmbH, University of Heidelberg, // and The University of Manchester. // All rights reserved. #include "CQSpeciesWidget.h" #include <QtGui/QHeaderView> #include <QtGui/QClipboard> #include <QtGui/QKeyEvent> #include "copasi.h" #include "qtUtilities.h" #include "CQMessageBox.h" #include "model/CModel.h" #include "CopasiDataModel/CCopasiDataModel.h" #include "report/CCopasiRootContainer.h" #include "copasiui3window.h" /* * Constructs a CQSpeciesWidget which is a child of 'parent', with the * name 'name'.' */ CQSpeciesWidget::CQSpeciesWidget(QWidget* parent, const char* name) : CopasiWidget(parent, name) { setupUi(this); //Create Source Data Model. mpSpecieDM = new CQSpecieDM(this); //Create the Proxy Model for sorting/filtering and set its properties. mpProxyModel = new CQSortFilterProxyModel(); mpProxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); mpProxyModel->setFilterKeyColumn(-1); mpProxyModel->setSourceModel(mpSpecieDM); mpTblSpecies->setModel(mpProxyModel); //Setting values for Compartment comboBox mpCompartmentDelegate = new CQComboDelegate(this, mCompartments); mpTblSpecies->setItemDelegateForColumn(COL_COMPARTMENT, mpCompartmentDelegate); //Setting values for Types comboBox mpTypeDelegate = new CQIndexComboDelegate(this, mpSpecieDM->getTypes(), false); mpTblSpecies->setItemDelegateForColumn(COL_TYPE_SPECIES, mpTypeDelegate); mpTblSpecies->verticalHeader()->setResizeMode(QHeaderView::ResizeToContents); mpTblSpecies->verticalHeader()->hide(); mpTblSpecies->sortByColumn(COL_ROW_NUMBER, Qt::AscendingOrder); // Connect the table widget connect(mpSpecieDM, SIGNAL(notifyGUI(ListViews::ObjectType, ListViews::Action, const std::string)), this, SLOT(protectedNotify(ListViews::ObjectType, ListViews::Action, const std::string))); connect(mpSpecieDM, SIGNAL(dataChanged(const QModelIndex&, const QModelIndex&)), this, SLOT(dataChanged(const QModelIndex&, const QModelIndex&))); connect(mpLEFilter, SIGNAL(textChanged(const QString &)), this, SLOT(slotFilterChanged())); CopasiUI3Window * pWindow = dynamic_cast<CopasiUI3Window * >(parent->parent()); mpSpecieDM->setUndoStack(pWindow->getUndoStack()); } /* * Destroys the object and frees any allocated resources */ CQSpeciesWidget::~CQSpeciesWidget() { pdelete(mpCompartmentDelegate); pdelete(mpTypeDelegate); pdelete(mpProxyModel); pdelete(mpSpecieDM); // no need to delete child widgets, Qt does it all for us } void CQSpeciesWidget::slotBtnNewClicked() { mpSpecieDM->insertRow(mpSpecieDM->rowCount() - 1, QModelIndex()); updateDeleteBtns(); } void CQSpeciesWidget::slotBtnDeleteClicked() { if (mpTblSpecies->hasFocus()) {deleteSelectedSpecies();} updateDeleteBtns(); } void CQSpeciesWidget::deleteSelectedSpecies() { const QItemSelectionModel * pSelectionModel = mpTblSpecies->selectionModel(); QModelIndexList mappedSelRows; size_t i, imax = mpSpecieDM->rowCount(); for (i = 0; i < imax; i++) { if (pSelectionModel->isRowSelected((int) i, QModelIndex())) { mappedSelRows.append(mpProxyModel->mapToSource(mpProxyModel->index((int) i, 0))); } } if (mappedSelRows.empty()) {return;} mpSpecieDM->removeRows(mappedSelRows); } void CQSpeciesWidget::slotBtnClearClicked() { int ret = CQMessageBox::question(this, tr("Confirm Delete"), "Delete all Species?", QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (ret == QMessageBox::Yes) { mpSpecieDM->clear(); } updateDeleteBtns(); } bool CQSpeciesWidget::update(ListViews::ObjectType C_UNUSED(objectType), ListViews::Action C_UNUSED(action), const std::string & C_UNUSED(key)) { if (!mIgnoreUpdates && isVisible()) { enterProtected(); } return true; } bool CQSpeciesWidget::leave() { return true; } bool CQSpeciesWidget::enterProtected() { if (mpTblSpecies->selectionModel() != NULL) { disconnect(mpTblSpecies->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(slotSelectionChanged(const QItemSelection&, const QItemSelection&))); } mpProxyModel->setSourceModel(mpSpecieDM); //Set Model for the TableView mpTblSpecies->setModel(NULL); mpTblSpecies->setModel(mpProxyModel); connect(mpTblSpecies->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(slotSelectionChanged(const QItemSelection&, const QItemSelection&))); updateDeleteBtns(); mpTblSpecies->resizeColumnsToContents(); setFramework(mFramework); refreshCompartments(); return true; } void CQSpeciesWidget::updateDeleteBtns() { bool selected = false; QModelIndexList selRows = mpTblSpecies->selectionModel()->selectedRows(); if (selRows.size() == 0) selected = false; else { if (selRows.size() == 1) { if (mpSpecieDM->isDefaultRow(mpProxyModel->mapToSource(selRows[0]))) selected = false; else selected = true; } else selected = true; } mpBtnDelete->setEnabled(selected); if (mpProxyModel->rowCount() - 1) mpBtnClear->setEnabled(true); else mpBtnClear->setEnabled(false); } void CQSpeciesWidget::slotSelectionChanged(const QItemSelection& C_UNUSED(selected), const QItemSelection& C_UNUSED(deselected)) { updateDeleteBtns(); } void CQSpeciesWidget::dataChanged(const QModelIndex& C_UNUSED(topLeft), const QModelIndex& C_UNUSED(bottomRight)) { mpTblSpecies->resizeColumnsToContents(); setFramework(mFramework); refreshCompartments(); updateDeleteBtns(); } void CQSpeciesWidget::slotDoubleClicked(const QModelIndex proxyIndex) { QModelIndex index = mpProxyModel->mapToSource(proxyIndex); if (index.row() < 0) return; if (mpSpecieDM->isDefaultRow(index)) { slotBtnNewClicked(); } assert(CCopasiRootContainer::getDatamodelList()->size() > 0); CCopasiDataModel* pDataModel = &CCopasiRootContainer::getDatamodelList()->operator[](0); assert(pDataModel != NULL); CModel * pModel = pDataModel->getModel(); if (pModel == NULL) return; std::string key = pModel->getMetabolites()[index.row()].getKey(); if (CCopasiRootContainer::getKeyFactory()->get(key)) mpListView->switchToOtherWidget(C_INVALID_INDEX, key); } void CQSpeciesWidget::keyPressEvent(QKeyEvent* ev) { if (ev->key() == Qt::Key_Delete) slotBtnDeleteClicked(); else if (ev->key() == Qt::Key_C && (ev->modifiers() & Qt::ControlModifier)) { QModelIndexList selRows = mpTblSpecies->selectionModel()->selectedRows(0); if (selRows.empty()) {return;} QString str; QModelIndexList::const_iterator i; for (i = selRows.begin(); i != selRows.end(); ++i) { for (int x = 0; x < mpSpecieDM->columnCount(); ++x) { if (!mpTblSpecies->isColumnHidden(x)) { if (!str.isEmpty()) str += "\t"; str += mpSpecieDM->index(mpProxyModel->mapToSource(*i).row(), x).data().toString(); } } str += "\n"; } QApplication::clipboard()->setText(str); } } void CQSpeciesWidget::slotFilterChanged() { QRegExp regExp(mpLEFilter->text() + "|New Species", Qt::CaseInsensitive, QRegExp::RegExp); mpProxyModel->setFilterRegExp(regExp); } void CQSpeciesWidget::setFramework(int framework) { CopasiWidget::setFramework(framework); switch (mFramework) { case 0: mpTblSpecies->showColumn(COL_ICONCENTRATION); mpTblSpecies->showColumn(COL_CONCENTRATION); mpTblSpecies->showColumn(COL_CRATE); mpTblSpecies->hideColumn(COL_INUMBER); mpTblSpecies->hideColumn(COL_NUMBER); mpTblSpecies->hideColumn(COL_NRATE); mpSpecieDM->setFlagConc(true); break; case 1: mpTblSpecies->hideColumn(COL_ICONCENTRATION); mpTblSpecies->hideColumn(COL_CONCENTRATION); mpTblSpecies->hideColumn(COL_CRATE); mpTblSpecies->showColumn(COL_INUMBER); mpTblSpecies->showColumn(COL_NUMBER); mpTblSpecies->showColumn(COL_NRATE); mpSpecieDM->setFlagConc(false); break; } } void CQSpeciesWidget::refreshCompartments() { const CCopasiVector < CCompartment > & compartments = CCopasiRootContainer::getDatamodelList()->operator[](0).getModel()->getCompartments(); mCompartments.clear(); for (unsigned C_INT32 jj = 0; jj < compartments.size(); jj++) mCompartments.push_back(FROM_UTF8(compartments[jj].getObjectName())); mpCompartmentDelegate->setItems(-1, mCompartments); } <|endoftext|>
<commit_before>#include "bulkDataCallback.h" BulkDataCallback::BulkDataCallback() { ACS_TRACE("BulkDataCallback::BulkDataCallback"); state_m = CB_UNS; substate_m = CB_SUB_UNS; dim_m = 0; count_m = 0; loop_m = 5; waitPeriod_m.set(0L, 400000L); frameCount_m = 0; bufParam_p = 0; timeout_m = false; working_m = false; error_m = false; errorCounter_m = 0; errComp_p = 0; } BulkDataCallback::~BulkDataCallback() { ACS_TRACE("BulkDataCallback::~BulkDataCallback"); if (error_m == true) { if (errComp_p != 0) delete errComp_p; } } int BulkDataCallback::handle_start(void) { //ACS_TRACE("BulkDataCallback::handle_start"); // cout << "BulkDataCallback::handle_start - state_m: " << state_m << endl; //if(timeout_m == true) //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_start - timeout_m == true !!!")); timeout_m = false; if (error_m == true) { if (errComp_p != 0) delete errComp_p; } // error is cleared error_m = false; state_m = CB_UNS; substate_m = CB_SUB_UNS; frameCount_m = 1; // we need to wait for 1 following frame before doing anything else return 0; } int BulkDataCallback::handle_stop (void) { //ACS_TRACE("BulkDataCallback::handle_stop"); // cout << "CCCCCCCCCCCCCCCCC enter stop state " << state_m << " " << substate_m << endl; try { int locLoop; int res; locLoop = loop_m; while ( (frameCount_m != 0) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } // we didn't receive the first frame yet if(state_m == CB_UNS) { int res = cbStop(); errorCounter_m = 0; return res; } if((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA)) { if (substate_m == CB_SUB_INIT) { substate_m = CB_SUB_UNS; return 0; } locLoop = loop_m; while((count_m != dim_m) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } if ( locLoop == 0 ) { ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_stop timeout expired, not all data received")); timeout_m = true; //cleaning the recv buffer ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); //cout << "sssssss: " << bufSize << endl; int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); //cout << "nnnnnnn: " << nn << endl; } //return -1; } if(state_m == CB_SEND_PARAM) { //res ignored by reactor if (dim_m != 0) res = cbStart(bufParam_p); if(bufParam_p) bufParam_p->release(); } state_m = CB_UNS; substate_m = CB_SUB_UNS; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.log(); /* TBD what do to after several attempts ? */ errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } // add to the completion errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "BulkDataCallback::handle_stop"); error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::handle_stop"); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } return 0; } int BulkDataCallback::handle_destroy (void) { //ACS_TRACE("BulkDataCallback::handle_destroy"); //cout << "BulkDataCallback::handle_destroy" << endl; if (error_m == true) { if (errComp_p != 0) delete errComp_p; } error_m = false; delete this; return 0; } int BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &) { working_m = true; /* if(error_m == true) { cleanRecvBuffer(); return 0; } */ //ACS_TRACE("BulkDataCallback::receive_frame"); //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::receive_frame for flow %s", flowname_m.c_str())); // cout << "BulkDataCallback::receive_frame - state_m: " << state_m << endl; if(timeout_m == true) ACS_SHORT_LOG((LM_INFO, "BulkDataCallback::receive_frame - timeout_m true !!!")); try { CORBA::ULong val1, val2; int res; if(state_m == CB_UNS) { char tmp[255]; ACE_OS::strcpy(tmp, frame->rd_ptr()); string strDataInfo(tmp); istringstream iss(strDataInfo); iss >> val1 >> val2; // cout << "CCCCCCCCCCCCCCC " << val1 << " " << val2 << endl; if(val1 == 1) { state_m = CB_SEND_PARAM; substate_m = CB_SUB_INIT; if(val2 != 0) bufParam_p = new ACE_Message_Block(val2); else bufParam_p = 0; } else if(val1 == 2) { state_m = CB_SEND_DATA; substate_m = CB_SUB_INIT; } else { state_m = CB_UNS; substate_m = CB_SUB_UNS; } dim_m = val2; count_m = 0; frameCount_m = 0; working_m = false; return 0; } if(state_m == CB_SEND_PARAM) { if ( dim_m == 0 ) { res = cbStart(); errorCounter_m = 0; working_m = false; return 0; } bufParam_p->copy(frame->rd_ptr(),frame->length()); count_m += frame->length(); errorCounter_m = 0; working_m = false; return 0; } if (state_m == CB_SEND_DATA) { res = cbReceive(frame); // if(timeout_m == true) // { // //cout << "!!!!!!! in receive_frame timeout_m == true after timeout - set it to false" << endl; // timeout_m = false; // } count_m += frame->length(); errorCounter_m = 0; working_m = false; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.log(); /* TBD what do to after several attempts ? */ errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } // add to the completion errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "BulkDataCallback::handle_stop"); error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::receive_frame"); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } working_m = false; return 0; } void BulkDataCallback::setFlowname (const char * flowname_p) { ACS_TRACE("BulkDataCallback::setFlowname"); //ACS_SHORT_LOG((LM_INFO,"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s", flow_name)); flowname_m = flowname_p; string flwName(flowname_p); string flwNumber(flwName, 4, 1); flowNumber_m = atol(flwNumber.c_str()); } void BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod) { ACS_TRACE("BulkDataCallback::setSleepTime"); waitPeriod_m = locWaitPeriod; } void BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop) { ACS_TRACE("BulkDataCallback::setSafeTimeout"); loop_m = locLoop; } CORBA::Boolean BulkDataCallback::isTimeout() { ACS_TRACE("BulkDataCallback::isTimeout"); return timeout_m; } CORBA::Boolean BulkDataCallback::isWorking() { ACS_TRACE("BulkDataCallback::isWorking"); return working_m; } CORBA::Boolean BulkDataCallback::isError() { // ACS_TRACE("BulkDataCallback::isError"); return error_m; } CompletionImpl *BulkDataCallback::getErrorCompletion() { ACS_TRACE("BulkDataCallback::getErrorCompletion"); // error is cleared; completion cannot be retrieved two times error_m = false; return errComp_p; } void BulkDataCallback::cleanRecvBuffer() { ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); } } <commit_msg>corrected bug<commit_after>#include "bulkDataCallback.h" BulkDataCallback::BulkDataCallback() { ACS_TRACE("BulkDataCallback::BulkDataCallback"); state_m = CB_UNS; substate_m = CB_SUB_UNS; dim_m = 0; count_m = 0; loop_m = 5; waitPeriod_m.set(0L, 400000L); frameCount_m = 0; bufParam_p = 0; timeout_m = false; working_m = false; error_m = false; errorCounter_m = 0; errComp_p = 0; } BulkDataCallback::~BulkDataCallback() { ACS_TRACE("BulkDataCallback::~BulkDataCallback"); if (error_m == true) { if (errComp_p != 0) delete errComp_p; } } int BulkDataCallback::handle_start(void) { //ACS_TRACE("BulkDataCallback::handle_start"); // cout << "BulkDataCallback::handle_start - state_m: " << state_m << endl; //if(timeout_m == true) //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_start - timeout_m == true !!!")); timeout_m = false; if (error_m == true) { if (errComp_p != 0) delete errComp_p; } // error is cleared error_m = false; state_m = CB_UNS; substate_m = CB_SUB_UNS; frameCount_m = 1; // we need to wait for 1 following frame before doing anything else return 0; } int BulkDataCallback::handle_stop (void) { //ACS_TRACE("BulkDataCallback::handle_stop"); // cout << "CCCCCCCCCCCCCCCCC enter stop state " << state_m << " " << substate_m << endl; try { int locLoop; int res; locLoop = loop_m; while ( (frameCount_m != 0) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } // we didn't receive the first frame yet if(state_m == CB_UNS) { int res = cbStop(); errorCounter_m = 0; return res; } if((state_m == CB_SEND_PARAM) || (state_m == CB_SEND_DATA)) { if (substate_m == CB_SUB_INIT) { substate_m = CB_SUB_UNS; return 0; } locLoop = loop_m; while((count_m != dim_m) && locLoop > 0) { ACE_OS::sleep(waitPeriod_m); locLoop--; } if ( locLoop == 0 ) { ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::handle_stop timeout expired, not all data received")); timeout_m = true; //cleaning the recv buffer ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); //cout << "sssssss: " << bufSize << endl; int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); //cout << "nnnnnnn: " << nn << endl; } //return -1; } if(state_m == CB_SEND_PARAM) { //res ignored by reactor if (dim_m != 0) res = cbStart(bufParam_p); if(bufParam_p) bufParam_p->release(); } state_m = CB_UNS; substate_m = CB_SUB_UNS; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.log(); /* TBD what do to after several attempts ? */ errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } // add to the completion errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "BulkDataCallback::handle_stop"); error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::handle_stop"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::handle_stop"); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } return 0; } int BulkDataCallback::handle_destroy (void) { //ACS_TRACE("BulkDataCallback::handle_destroy"); //cout << "BulkDataCallback::handle_destroy" << endl; if (error_m == true) { if (errComp_p != 0) delete errComp_p; } error_m = false; delete this; return 0; } int BulkDataCallback::receive_frame (ACE_Message_Block *frame, TAO_AV_frame_info *frame_info, const ACE_Addr &) { working_m = true; if(error_m == true) { cleanRecvBuffer(); working_m = false; return 0; } //ACS_TRACE("BulkDataCallback::receive_frame"); //ACS_SHORT_LOG((LM_INFO,"BulkDataCallback::receive_frame for flow %s", flowname_m.c_str())); // cout << "BulkDataCallback::receive_frame - state_m: " << state_m << endl; if(timeout_m == true) ACS_SHORT_LOG((LM_INFO, "BulkDataCallback::receive_frame - timeout_m true !!!")); try { CORBA::ULong val1, val2; int res; if(state_m == CB_UNS) { char tmp[255]; ACE_OS::strcpy(tmp, frame->rd_ptr()); string strDataInfo(tmp); istringstream iss(strDataInfo); iss >> val1 >> val2; // cout << "CCCCCCCCCCCCCCC " << val1 << " " << val2 << endl; if(val1 == 1) { state_m = CB_SEND_PARAM; substate_m = CB_SUB_INIT; if(val2 != 0) bufParam_p = new ACE_Message_Block(val2); else bufParam_p = 0; } else if(val1 == 2) { state_m = CB_SEND_DATA; substate_m = CB_SUB_INIT; } else { state_m = CB_UNS; substate_m = CB_SUB_UNS; } dim_m = val2; count_m = 0; frameCount_m = 0; working_m = false; return 0; } if(state_m == CB_SEND_PARAM) { if ( dim_m == 0 ) { res = cbStart(); errorCounter_m = 0; working_m = false; return 0; } bufParam_p->copy(frame->rd_ptr(),frame->length()); count_m += frame->length(); errorCounter_m = 0; working_m = false; return 0; } if (state_m == CB_SEND_DATA) { res = cbReceive(frame); // if(timeout_m == true) // { // //cout << "!!!!!!! in receive_frame timeout_m == true after timeout - set it to false" << endl; // timeout_m = false; // } count_m += frame->length(); errorCounter_m = 0; working_m = false; return 0; } } catch(ACSErr::ACSbaseExImpl &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(ex,__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.log(); /* TBD what do to after several attempts ? */ errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } // add to the completion errComp_p = new AVCbErrorCompletion(err, __FILE__, __LINE__, "BulkDataCallback::handle_stop"); error_m = true; } catch(CORBA::Exception &ex) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("CORBA::Exception", ex._info()); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } catch(...) { AVCallbackErrorExImpl err = AVCallbackErrorExImpl(__FILE__,__LINE__,"BulkDataCallback::receive_frame"); err.addData("UNKNOWN Exception", "Unknown ex in BulkDataCallback::receive_frame"); err.log(); errorCounter_m++; if(errorCounter_m == maxErrorRepetition) { errorCounter_m = 0; //return 0; } error_m = true; } working_m = false; return 0; } void BulkDataCallback::setFlowname (const char * flowname_p) { ACS_TRACE("BulkDataCallback::setFlowname"); //ACS_SHORT_LOG((LM_INFO,"RRRRRRRRRRRRRRRRR BulkDataCallback::flowname for flow %s", flow_name)); flowname_m = flowname_p; string flwName(flowname_p); string flwNumber(flwName, 4, 1); flowNumber_m = atol(flwNumber.c_str()); } void BulkDataCallback::setSleepTime(ACE_Time_Value locWaitPeriod) { ACS_TRACE("BulkDataCallback::setSleepTime"); waitPeriod_m = locWaitPeriod; } void BulkDataCallback::setSafeTimeout(CORBA::ULong locLoop) { ACS_TRACE("BulkDataCallback::setSafeTimeout"); loop_m = locLoop; } CORBA::Boolean BulkDataCallback::isTimeout() { ACS_TRACE("BulkDataCallback::isTimeout"); return timeout_m; } CORBA::Boolean BulkDataCallback::isWorking() { ACS_TRACE("BulkDataCallback::isWorking"); return working_m; } CORBA::Boolean BulkDataCallback::isError() { // ACS_TRACE("BulkDataCallback::isError"); return error_m; } CompletionImpl *BulkDataCallback::getErrorCompletion() { ACS_TRACE("BulkDataCallback::getErrorCompletion"); // error is cleared; completion cannot be retrieved two times error_m = false; return errComp_p; } void BulkDataCallback::cleanRecvBuffer() { ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *svch = dynamic_cast<ACE_Svc_Handler<ACE_SOCK_STREAM,ACE_NULL_SYNCH> *>(handler_); char buf[BUFSIZ]; int bufSize = sizeof(buf); int nn = 1; while(nn > 0) { nn = svch->peer().recv(buf,bufSize); } } <|endoftext|>
<commit_before>#include "main.hpp" void GridlabDFederate::initialize( void ) { GridlabDFederateATRCallback gldfedATRCb( *this ); putAdvanceTimeRequest( _currentTime, gldfedATRCb ); readyToPopulate(); readyToRun(); } void GridlabDFederate::execute( void ) { // update class variables _currentTime += 1; // init temporary variables InteractionRoot::SP interactionRootSP; char tmpBuf[1024]; std::string gld_url_base = "http://" + _gld_ip + ":" + _gld_port + "/"; gld_obj object; int intf_retval = 0; std::string gld_url, date, time; // STEP GLD date = "2000-01-01 "; sprintf( tmpBuf, "%02d:%02d:%02d", (int)( ( _currentTime / 60 ) / 60 ), (int)( _currentTime / 60 ), (int)fmod(_currentTime, 60)); time = std::string(tmpBuf); gld_url = gld_url_base + "control/pauseat=" + date + time; intf_retval = call_gld(gld_url, object); // GET MESSAGES HERE FROM HLA while ( (interactionRootSP = getNextInteraction() ) != 0 ) { boost::shared_ptr<GridlabDInput> gldSP( boost::static_pointer_cast<GridlabDInput>( interactionRootSP ) ); std::string objectName = gldSP->get_ObjectName(); std::string parameterName = gldSP->get_Parameter(); double value = gldSP->get_Value(); std::string units = gldSP->get_Units(); int operation = gldSP->get_Operation(); // operation: // 0 : GET // 1 : SET // ... : UNDEFINED std::cout << "GLDFederate: Received GridlabDInput interaction: " << objectName << "/" << parameterName << ": " << value << units << ": " << operation << std::endl; // SEND DATA TO GLD; GET DATA FROM GLD memset(tmpBuf, 0, 1024); sprintf(tmpBuf, "%f", value); gld_url = gld_url_base + objectName + "/" + parameterName; if (operation == 1) gld_url += "=" + std::string(tmpBuf) + units; intf_retval = call_gld(gld_url, object); if (intf_retval) // everything went well { if (object.has_data) { GridlabDOutputSP output = create_GridlabDOutput(); output->set_ObjectName( object.object ); output->set_Parameter( object.name ); // need to split the value into value and units char *pEnd = 0; value = strtod(object.value.c_str(), &pEnd); output->set_Value( value ); if (pEnd) { output->set_Units( std::string(pEnd) ); // there is always a space between the value and units } output->set_Operation( 0 ); std::cout << "GLDFederate: Sending GridlabDOutput interaction: " << output->get_ObjectName() << "/" << output->get_Parameter() << ": " << output->get_Value() << output->get_Units() << ": " << output->get_Operation() << std::endl; output->sendInteraction( getRTI(), _currentTime + getLookAhead() ); } } } // Advance Time GridlabDFederateATRCallback gldfedATRcb( *this ); putAdvanceTimeRequest( _currentTime, gldfedATRcb ); } bool GridlabDFederate::call_gld(std::string gld_url, gld_obj& ret_obj) // in-out param { ret_obj.has_data = false; ret_obj.type = ""; ret_obj.object = ""; ret_obj.name = ""; ret_obj.value = ""; // std::cout << "Connecting to: " << gld_url << std::endl; using namespace boost::network; http::client client; http::client::request request(gld_url); request << header("Connection", "close"); http::client::response response = client.get(request); std::string text = body(response); if (text.length()) { rapidxml::xml_document<> doc; doc.parse<0>((char *)text.c_str()); rapidxml::xml_node<> *_type = doc.first_node("property"); rapidxml::xml_node<> *_name, *_val, *_object; if (_type) { _object = _type->first_node("object"); _name = _type->first_node("name"); _val = _type->first_node("value"); ret_obj.has_data = true; ret_obj.type = "property"; ret_obj.object = _object->value(); ret_obj.name = _name->value(); ret_obj.value = _val->value(); } else { _type = doc.first_node("globalvar"); _name = _type->first_node("name"); _val = _type->first_node("value"); ret_obj.has_data = true; ret_obj.type = "globalvar"; ret_obj.name = _name->value(); ret_obj.value = _val->value(); } } return true; } int main(int argc, char** argv) { pid_t pID = fork(); if (pID == 0) { char *args[4]; char process[] = "/usr/local/bin/gridlabd"; char model[] = "/home/c2wt/Projects/c2wt/examples/GridlabDHelloWorld/models/gridlab-d/IEEE_13_Node_With_Houses.glm"; char option[] = "--server"; args[0] = process; args[1] = model; args[2] = option; args[3] = 0; execv(args[0], args); } std::cout << "Creating GridlabDFederate Object" << std::endl; GridlabDFederate gldfed( argc, argv ); std::cout << "GridlabDFederate created" << std::endl; std::cout << "Initializing GridlabDFederate" << std::endl; gldfed.initialize(); std::cout << "GridlabDFederate initialized" << std::endl; std::cout << "Running GridlabDFederate" << std::endl; gldfed.run(); kill(0, SIGKILL); return 0; } <commit_msg>minor update for output.<commit_after>#include "main.hpp" void GridlabDFederate::initialize( void ) { GridlabDFederateATRCallback gldfedATRCb( *this ); putAdvanceTimeRequest( _currentTime, gldfedATRCb ); readyToPopulate(); readyToRun(); } void GridlabDFederate::execute( void ) { // update class variables _currentTime += 1; // init temporary variables InteractionRoot::SP interactionRootSP; char tmpBuf[1024]; std::string gld_url_base = "http://" + _gld_ip + ":" + _gld_port + "/"; gld_obj object; int intf_retval = 0; std::string gld_url, date, time; // STEP GLD date = "2000-01-01 "; sprintf( tmpBuf, "%02d:%02d:%02d", (int)( ( _currentTime / 60 ) / 60 ), (int)( _currentTime / 60 ), (int)fmod(_currentTime, 60)); time = std::string(tmpBuf); gld_url = gld_url_base + "control/pauseat=" + date + time; std::cout << "GLDFederate: Stepping GLD to " << date + time << std::endl; intf_retval = call_gld(gld_url, object); // GET MESSAGES HERE FROM HLA while ( (interactionRootSP = getNextInteraction() ) != 0 ) { boost::shared_ptr<GridlabDInput> gldSP( boost::static_pointer_cast<GridlabDInput>( interactionRootSP ) ); std::string objectName = gldSP->get_ObjectName(); std::string parameterName = gldSP->get_Parameter(); double value = gldSP->get_Value(); std::string units = gldSP->get_Units(); int operation = gldSP->get_Operation(); // operation: // 0 : GET // 1 : SET // ... : UNDEFINED std::cout << "GLDFederate: Received GridlabDInput interaction: " << objectName << "/" << parameterName << ": " << value << units << ": " << operation << std::endl; // SEND DATA TO GLD; GET DATA FROM GLD memset(tmpBuf, 0, 1024); sprintf(tmpBuf, "%f", value); gld_url = gld_url_base + objectName + "/" + parameterName; if (operation == 1) gld_url += "=" + std::string(tmpBuf) + units; intf_retval = call_gld(gld_url, object); if (intf_retval) // everything went well { if (object.has_data) { GridlabDOutputSP output = create_GridlabDOutput(); output->set_ObjectName( object.object ); output->set_Parameter( object.name ); // need to split the value into value and units char *pEnd = 0; value = strtod(object.value.c_str(), &pEnd); output->set_Value( value ); if (pEnd) { output->set_Units( std::string(pEnd) ); // there is always a space between the value and units } output->set_Operation( 0 ); std::cout << "GLDFederate: Sending GridlabDOutput interaction: " << output->get_ObjectName() << "/" << output->get_Parameter() << ": " << output->get_Value() << output->get_Units() << ": " << output->get_Operation() << std::endl; output->sendInteraction( getRTI(), _currentTime + getLookAhead() ); } } } // Advance Time GridlabDFederateATRCallback gldfedATRcb( *this ); putAdvanceTimeRequest( _currentTime, gldfedATRcb ); } bool GridlabDFederate::call_gld(std::string gld_url, gld_obj& ret_obj) // in-out param { ret_obj.has_data = false; ret_obj.type = ""; ret_obj.object = ""; ret_obj.name = ""; ret_obj.value = ""; // std::cout << "Connecting to: " << gld_url << std::endl; using namespace boost::network; http::client client; http::client::request request(gld_url); request << header("Connection", "close"); http::client::response response = client.get(request); std::string text = body(response); if (text.length()) { rapidxml::xml_document<> doc; doc.parse<0>((char *)text.c_str()); rapidxml::xml_node<> *_type = doc.first_node("property"); rapidxml::xml_node<> *_name, *_val, *_object; if (_type) { _object = _type->first_node("object"); _name = _type->first_node("name"); _val = _type->first_node("value"); ret_obj.has_data = true; ret_obj.type = "property"; ret_obj.object = _object->value(); ret_obj.name = _name->value(); ret_obj.value = _val->value(); } else { _type = doc.first_node("globalvar"); _name = _type->first_node("name"); _val = _type->first_node("value"); ret_obj.has_data = true; ret_obj.type = "globalvar"; ret_obj.name = _name->value(); ret_obj.value = _val->value(); } } return true; } int main(int argc, char** argv) { pid_t pID = fork(); if (pID == 0) { char *args[4]; char process[] = "/usr/local/bin/gridlabd"; char model[] = "/home/c2wt/Projects/c2wt/examples/GridlabDHelloWorld/models/gridlab-d/IEEE_13_Node_With_Houses.glm"; char option[] = "--server"; args[0] = process; args[1] = model; args[2] = option; args[3] = 0; execv(args[0], args); } std::cout << "Creating GridlabDFederate Object" << std::endl; GridlabDFederate gldfed( argc, argv ); std::cout << "GridlabDFederate created" << std::endl; std::cout << "Initializing GridlabDFederate" << std::endl; gldfed.initialize(); std::cout << "GridlabDFederate initialized" << std::endl; std::cout << "Running GridlabDFederate" << std::endl; gldfed.run(); kill(0, SIGKILL); return 0; } <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $ Version: $Revision: 13129 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkNavigationDataRecorder.h" #include <fstream> #include <mitkTimeStamp.h> #include <tinyxml.h> #include <itksys/SystemTools.hxx> mitk::NavigationDataRecorder::NavigationDataRecorder() { //set default values m_NumberOfInputs = 0; m_RecordingMode = NormalFile; m_Recording = false; m_NumberOfRecordedFiles = 0; m_Stream = NULL; m_FileName = ""; m_SystemTimeClock = RealTimeClock::New(); m_OutputFormat = mitk::NavigationDataRecorder::xml; m_RecordCounter = 0; m_RecordCountLimit = -1; //To get a start time mitk::TimeStamp::GetInstance()->Start(this); } mitk::NavigationDataRecorder::~NavigationDataRecorder() { } void mitk::NavigationDataRecorder::GenerateData() { } void mitk::NavigationDataRecorder::AddNavigationData( const NavigationData* nd ) { // Process object is not const-correct so the const_cast is required here this->SetNthInput(m_NumberOfInputs, const_cast< mitk::NavigationData * >( nd ) ); m_NumberOfInputs++; this->Modified(); } void mitk::NavigationDataRecorder::SetRecordingMode( RecordingMode mode ) { m_RecordingMode = mode; this->Modified(); } void mitk::NavigationDataRecorder::Update() { if (m_Recording) { DataObjectPointerArray inputs = this->GetInputs(); //get all inputs mitk::NavigationData::TimeStampType timestamp=0.0; // timestamp for mitk time timestamp = mitk::TimeStamp::GetInstance()->GetElapsed(); mitk::NavigationData::TimeStampType sysTimestamp = 0.0; // timestamp for system time sysTimestamp = m_SystemTimeClock->GetCurrentStamp(); // cast system time double value to stringstream to avoid low precision rounding std::ostringstream strs; strs.precision(15); // rounding precision for system time double value strs << sysTimestamp; std::string sysTimeStr = strs.str(); //if csv-mode: write csv header and timpstamp at beginning if (m_OutputFormat == mitk::NavigationDataRecorder::csv) { //write header only when it's the first line if (m_firstLine) { m_firstLine = false; *m_Stream << "TimeStamp"; for (unsigned int index = 0; index < inputs.size(); index++){ *m_Stream << ";Valid_Tool" << index << ";X_Tool" << index << ";Y_Tool" << index << ";Z_Tool" << index << ";QX_Tool" << index << ";QY_Tool" << index << ";QZ_Tool" << index << ";QR_Tool" << index;} *m_Stream << "\n"; } //write timestamp (always) *m_Stream << timestamp; } //write tool data for every tool for (unsigned int index = 0; index < inputs.size(); index++) { mitk::NavigationData* nd = dynamic_cast<mitk::NavigationData*>(inputs[index].GetPointer()); nd->Update(); // call update to propagate update to previous filters mitk::NavigationData::PositionType position; mitk::NavigationData::OrientationType orientation(0.0, 0.0, 0.0, 0.0); mitk::NavigationData::CovarianceMatrixType matrix; bool hasPosition = true; bool hasOrientation = true; bool dataValid = false; position.Fill(0.0); matrix.SetIdentity(); position = nd->GetPosition(); orientation = nd->GetOrientation(); matrix = nd->GetCovErrorMatrix(); hasPosition = nd->GetHasPosition(); hasOrientation = nd->GetHasOrientation(); dataValid = nd->IsDataValid(); //use this one if you want the timestamps of the source //timestamp = nd->GetTimeStamp(); //a timestamp is never < 0! this case happens only if you are using the timestamp of the nd object instead of getting a new one if (timestamp >= 0) { if (this->m_OutputFormat == mitk::NavigationDataRecorder::xml) { TiXmlElement* elem = new TiXmlElement("ND"); elem->SetDoubleAttribute("Time", timestamp); elem->SetAttribute("SystemTime", sysTimeStr); // tag for system time elem->SetDoubleAttribute("Tool", index); elem->SetDoubleAttribute("X", position[0]); elem->SetDoubleAttribute("Y", position[1]); elem->SetDoubleAttribute("Z", position[2]); elem->SetDoubleAttribute("QX", orientation[0]); elem->SetDoubleAttribute("QY", orientation[1]); elem->SetDoubleAttribute("QZ", orientation[2]); elem->SetDoubleAttribute("QR", orientation[3]); elem->SetDoubleAttribute("C00", matrix[0][0]); elem->SetDoubleAttribute("C01", matrix[0][1]); elem->SetDoubleAttribute("C02", matrix[0][2]); elem->SetDoubleAttribute("C03", matrix[0][3]); elem->SetDoubleAttribute("C04", matrix[0][4]); elem->SetDoubleAttribute("C05", matrix[0][5]); elem->SetDoubleAttribute("C10", matrix[1][0]); elem->SetDoubleAttribute("C11", matrix[1][1]); elem->SetDoubleAttribute("C12", matrix[1][2]); elem->SetDoubleAttribute("C13", matrix[1][3]); elem->SetDoubleAttribute("C14", matrix[1][4]); elem->SetDoubleAttribute("C15", matrix[1][5]); if (dataValid) elem->SetAttribute("Valid",1); else elem->SetAttribute("Valid",0); if (hasOrientation) elem->SetAttribute("hO",1); else elem->SetAttribute("hO",0); if (hasPosition) elem->SetAttribute("hP",1); else elem->SetAttribute("hP",0); *m_Stream << " " << *elem << std::endl; delete elem; } else if (this->m_OutputFormat == mitk::NavigationDataRecorder::csv) { *m_Stream << ";" << dataValid << ";" << position[0] << ";" << position[1] << ";" << position[2] << ";" << orientation[0] << ";" << orientation[1] << ";" << orientation[2] << ";" << orientation[3]; } } } if (this->m_OutputFormat == mitk::NavigationDataRecorder::csv) { *m_Stream << "\n"; } } m_RecordCounter++; if ((m_RecordCountLimit<=m_RecordCounter)&&(m_RecordCountLimit != -1)) {StopRecording();} } void mitk::NavigationDataRecorder::StartRecording() { if (m_Recording) { std::cout << "Already recording please stop before start new recording session" << std::endl; return; } if (m_Stream == NULL) { std::stringstream ss; std::ostream* stream; //An existing extension will be cut and replaced with .xml std::string tmpPath = itksys::SystemTools::GetFilenamePath(m_FileName); m_FileName = itksys::SystemTools::GetFilenameWithoutExtension(m_FileName); if (m_OutputFormat == mitk::NavigationDataRecorder::csv) ss << tmpPath << "/" << m_FileName << "-" << m_NumberOfRecordedFiles << ".csv"; else ss << tmpPath << "/" << m_FileName << "-" << m_NumberOfRecordedFiles << ".xml"; switch(m_RecordingMode) { case Console: stream = &std::cout; break; case NormalFile: //Check if there is a file name and path if (m_FileName == "") { stream = &std::cout; std::cout << "No file name or file path set the output is redirected to the console"; } else { stream = new std::ofstream(ss.str().c_str()); } break; case ZipFile: stream = &std::cout; std::cout << "Sorry no ZipFile support yet"; break; default: stream = &std::cout; break; } m_firstLine = true; m_RecordCounter = 0; StartRecording(stream); } } void mitk::NavigationDataRecorder::StartRecording(std::ostream* stream) { if (m_Recording) { std::cout << "Already recording please stop before start new recording session" << std::endl; return; } m_Stream = stream; m_Stream->precision(10); //TODO store date and GMT time if (m_Stream) { if (m_OutputFormat == mitk::NavigationDataRecorder::xml) { *m_Stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" << std::endl; /**m_Stream << "<Version Ver=\"1\" />" << std::endl;*/ // should be a generic version, meaning a member variable, which has the actual version *m_Stream << " " << "<Data ToolCount=\"" << (m_NumberOfInputs) << "\" version=\"1.0\">" << std::endl; } m_Recording = true; } } void mitk::NavigationDataRecorder::StopRecording() { if (!m_Recording) { std::cout << "You have to start a recording first" << std::endl; return; } if ((m_Stream) && (m_OutputFormat == mitk::NavigationDataRecorder::xml)) { *m_Stream << "</Data>" << std::endl; } m_NumberOfRecordedFiles++; m_Recording = false; m_Stream->flush(); m_Stream = NULL; }<commit_msg>changed tag name "ND" to unambiguous name NaviagtionData<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date: 2007-12-11 14:46:19 +0100 (Di, 11 Dez 2007) $ Version: $Revision: 13129 $ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkNavigationDataRecorder.h" #include <fstream> #include <mitkTimeStamp.h> #include <tinyxml.h> #include <itksys/SystemTools.hxx> mitk::NavigationDataRecorder::NavigationDataRecorder() { //set default values m_NumberOfInputs = 0; m_RecordingMode = NormalFile; m_Recording = false; m_NumberOfRecordedFiles = 0; m_Stream = NULL; m_FileName = ""; m_SystemTimeClock = RealTimeClock::New(); m_OutputFormat = mitk::NavigationDataRecorder::xml; m_RecordCounter = 0; m_RecordCountLimit = -1; //To get a start time mitk::TimeStamp::GetInstance()->Start(this); } mitk::NavigationDataRecorder::~NavigationDataRecorder() { } void mitk::NavigationDataRecorder::GenerateData() { } void mitk::NavigationDataRecorder::AddNavigationData( const NavigationData* nd ) { // Process object is not const-correct so the const_cast is required here this->SetNthInput(m_NumberOfInputs, const_cast< mitk::NavigationData * >( nd ) ); m_NumberOfInputs++; this->Modified(); } void mitk::NavigationDataRecorder::SetRecordingMode( RecordingMode mode ) { m_RecordingMode = mode; this->Modified(); } void mitk::NavigationDataRecorder::Update() { if (m_Recording) { DataObjectPointerArray inputs = this->GetInputs(); //get all inputs mitk::NavigationData::TimeStampType timestamp=0.0; // timestamp for mitk time timestamp = mitk::TimeStamp::GetInstance()->GetElapsed(); mitk::NavigationData::TimeStampType sysTimestamp = 0.0; // timestamp for system time sysTimestamp = m_SystemTimeClock->GetCurrentStamp(); // cast system time double value to stringstream to avoid low precision rounding std::ostringstream strs; strs.precision(15); // rounding precision for system time double value strs << sysTimestamp; std::string sysTimeStr = strs.str(); //if csv-mode: write csv header and timpstamp at beginning if (m_OutputFormat == mitk::NavigationDataRecorder::csv) { //write header only when it's the first line if (m_firstLine) { m_firstLine = false; *m_Stream << "TimeStamp"; for (unsigned int index = 0; index < inputs.size(); index++){ *m_Stream << ";Valid_Tool" << index << ";X_Tool" << index << ";Y_Tool" << index << ";Z_Tool" << index << ";QX_Tool" << index << ";QY_Tool" << index << ";QZ_Tool" << index << ";QR_Tool" << index;} *m_Stream << "\n"; } //write timestamp (always) *m_Stream << timestamp; } //write tool data for every tool for (unsigned int index = 0; index < inputs.size(); index++) { mitk::NavigationData* nd = dynamic_cast<mitk::NavigationData*>(inputs[index].GetPointer()); nd->Update(); // call update to propagate update to previous filters mitk::NavigationData::PositionType position; mitk::NavigationData::OrientationType orientation(0.0, 0.0, 0.0, 0.0); mitk::NavigationData::CovarianceMatrixType matrix; bool hasPosition = true; bool hasOrientation = true; bool dataValid = false; position.Fill(0.0); matrix.SetIdentity(); position = nd->GetPosition(); orientation = nd->GetOrientation(); matrix = nd->GetCovErrorMatrix(); hasPosition = nd->GetHasPosition(); hasOrientation = nd->GetHasOrientation(); dataValid = nd->IsDataValid(); //use this one if you want the timestamps of the source //timestamp = nd->GetTimeStamp(); //a timestamp is never < 0! this case happens only if you are using the timestamp of the nd object instead of getting a new one if (timestamp >= 0) { if (this->m_OutputFormat == mitk::NavigationDataRecorder::xml) { TiXmlElement* elem = new TiXmlElement("NavigationData"); elem->SetDoubleAttribute("Time", timestamp); elem->SetAttribute("SystemTime", sysTimeStr); // tag for system time elem->SetDoubleAttribute("Tool", index); elem->SetDoubleAttribute("X", position[0]); elem->SetDoubleAttribute("Y", position[1]); elem->SetDoubleAttribute("Z", position[2]); elem->SetDoubleAttribute("QX", orientation[0]); elem->SetDoubleAttribute("QY", orientation[1]); elem->SetDoubleAttribute("QZ", orientation[2]); elem->SetDoubleAttribute("QR", orientation[3]); elem->SetDoubleAttribute("C00", matrix[0][0]); elem->SetDoubleAttribute("C01", matrix[0][1]); elem->SetDoubleAttribute("C02", matrix[0][2]); elem->SetDoubleAttribute("C03", matrix[0][3]); elem->SetDoubleAttribute("C04", matrix[0][4]); elem->SetDoubleAttribute("C05", matrix[0][5]); elem->SetDoubleAttribute("C10", matrix[1][0]); elem->SetDoubleAttribute("C11", matrix[1][1]); elem->SetDoubleAttribute("C12", matrix[1][2]); elem->SetDoubleAttribute("C13", matrix[1][3]); elem->SetDoubleAttribute("C14", matrix[1][4]); elem->SetDoubleAttribute("C15", matrix[1][5]); if (dataValid) elem->SetAttribute("Valid",1); else elem->SetAttribute("Valid",0); if (hasOrientation) elem->SetAttribute("hO",1); else elem->SetAttribute("hO",0); if (hasPosition) elem->SetAttribute("hP",1); else elem->SetAttribute("hP",0); *m_Stream << " " << *elem << std::endl; delete elem; } else if (this->m_OutputFormat == mitk::NavigationDataRecorder::csv) { *m_Stream << ";" << dataValid << ";" << position[0] << ";" << position[1] << ";" << position[2] << ";" << orientation[0] << ";" << orientation[1] << ";" << orientation[2] << ";" << orientation[3]; } } } if (this->m_OutputFormat == mitk::NavigationDataRecorder::csv) { *m_Stream << "\n"; } } m_RecordCounter++; if ((m_RecordCountLimit<=m_RecordCounter)&&(m_RecordCountLimit != -1)) {StopRecording();} } void mitk::NavigationDataRecorder::StartRecording() { if (m_Recording) { std::cout << "Already recording please stop before start new recording session" << std::endl; return; } if (m_Stream == NULL) { std::stringstream ss; std::ostream* stream; //An existing extension will be cut and replaced with .xml std::string tmpPath = itksys::SystemTools::GetFilenamePath(m_FileName); m_FileName = itksys::SystemTools::GetFilenameWithoutExtension(m_FileName); if (m_OutputFormat == mitk::NavigationDataRecorder::csv) ss << tmpPath << "/" << m_FileName << "-" << m_NumberOfRecordedFiles << ".csv"; else ss << tmpPath << "/" << m_FileName << "-" << m_NumberOfRecordedFiles << ".xml"; switch(m_RecordingMode) { case Console: stream = &std::cout; break; case NormalFile: //Check if there is a file name and path if (m_FileName == "") { stream = &std::cout; std::cout << "No file name or file path set the output is redirected to the console"; } else { stream = new std::ofstream(ss.str().c_str()); } break; case ZipFile: stream = &std::cout; std::cout << "Sorry no ZipFile support yet"; break; default: stream = &std::cout; break; } m_firstLine = true; m_RecordCounter = 0; StartRecording(stream); } } void mitk::NavigationDataRecorder::StartRecording(std::ostream* stream) { if (m_Recording) { std::cout << "Already recording please stop before start new recording session" << std::endl; return; } m_Stream = stream; m_Stream->precision(10); //TODO store date and GMT time if (m_Stream) { if (m_OutputFormat == mitk::NavigationDataRecorder::xml) { *m_Stream << "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" << std::endl; /**m_Stream << "<Version Ver=\"1\" />" << std::endl;*/ // should be a generic version, meaning a member variable, which has the actual version *m_Stream << " " << "<Data ToolCount=\"" << (m_NumberOfInputs) << "\" version=\"1.0\">" << std::endl; } m_Recording = true; } } void mitk::NavigationDataRecorder::StopRecording() { if (!m_Recording) { std::cout << "You have to start a recording first" << std::endl; return; } if ((m_Stream) && (m_OutputFormat == mitk::NavigationDataRecorder::xml)) { *m_Stream << "</Data>" << std::endl; } m_NumberOfRecordedFiles++; m_Recording = false; m_Stream->flush(); m_Stream = NULL; }<|endoftext|>
<commit_before>/// HEADER #include "time_plot.h" /// PROJECT #include <csapex/msg/io.h> #include <csapex_opencv/cv_mat_message.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/view/utility/QtCvImageConverter.h> #include <csapex/msg/generic_vector_message.hpp> /// SYSTEM #include <qwt_scale_engine.h> CSAPEX_REGISTER_CLASS(csapex::TimePlot, csapex::Node) using namespace csapex; using namespace csapex::connection_types; void TimePlot::setup(NodeModifier &node_modifier) { in_ = node_modifier.addMultiInput<double, GenericVectorMessage>("Double"); out_ = node_modifier.addOutput<CvMatMessage>("Plot"); initialize_ = true; num_plots_ = 1; basic_line_color_changed_ = true; color_line_.resize(1); } void TimePlot::setupParameters(Parameterizable &parameters) { parameters.addParameter(param::ParameterFactory::declareRange ("~plot/width", 128, 4096, 640, 1), [this](param::Parameter* p) { width_ = p->as<int>(); update(); }); parameters.addParameter(param::ParameterFactory::declareRange ("~plot/height", 128, 4096, 320, 1), [this](param::Parameter* p) { height_ = p->as<int>(); update(); }); auto setColor = [this](QColor& color) { return [&](param::Parameter* p) { std::vector<int> c = p->as<std::vector<int>>(); color.setRed(c[0]); color.setGreen(c[1]); color.setBlue(c[2]); update(); }; }; std::function<void(param::Parameter* p)> setLineColors= [this](param::Parameter* p){ std::vector<int> c = p->as<std::vector<int>>(); basic_line_color_.setRed(c[0]); basic_line_color_.setGreen(c[1]); basic_line_color_.setBlue(c[2]); calculateLineColors(); basic_line_color_changed_ = true; update(); }; parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/background", 255, 255, 255), setColor(color_bg_)); parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/line", 100, 100, 255), setLineColors); parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/fill", 200, 200, 200), setColor(color_fill_)); parameters.addParameter(param::ParameterFactory::declareRange( "~plot/line/width", 0.0, 10.0, 0.0, 0.01), line_width_); parameters.addParameter(param::ParameterFactory::declareBool ("~output/time/relative", param::ParameterDescription("Use time relative to the first entry"), true), time_relative_); parameters.addParameter(param::ParameterFactory::declareBool ("~output/time/seconds", param::ParameterDescription("Convert the time to seconds"), true), time_seconds_); parameters.addParameter(param::ParameterFactory::declareTrigger("reset"), [this](param::Parameter*) { reset(); }); } void TimePlot::process() { timepoint time = std::chrono::system_clock::now(); double value; if(msg::isValue<double>(in_)) { value = msg::getValue<double>(in_); if(initialize_){ data_v_.resize(1); num_plots_ = 1; initialize_ = false; color_line_.resize(1); calculateLineColors(); } data_v_.at(0).push_back(value); } else { GenericVectorMessage::ConstPtr message = msg::getMessage<GenericVectorMessage>(in_); apex_assert(std::dynamic_pointer_cast<GenericValueMessage<double>>(message->nestedType())); if(initialize_){ num_plots_ = message->nestedValueCount(); data_v_.resize(num_plots_); color_line_.resize(num_plots_); calculateLineColors(); initialize_ = false; } for(std::size_t num_plot = 0; num_plot < num_plots_; ++num_plot){ auto pval = std::dynamic_pointer_cast<GenericValueMessage<double> const>(message->nestedValue(num_plot)); if(pval){ double val = pval->value; data_v_.at(num_plot).push_back(val); } // double val = tval-> } } double ms = std::chrono::duration_cast<std::chrono::microseconds>(time.time_since_epoch()).count(); data_t_raw_.push_back(ms); preparePlot(); if(msg::isConnected(out_)) { renderAndSend(); } display_request(); } void TimePlot::reset() { data_t_raw_.clear(); data_v_.clear(); initialize_ = true; num_plots_ = 1; init(); } void TimePlot::init() { auto now = std::chrono::system_clock::now(); start_t_ = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count(); } void TimePlot::preparePlot() { std::size_t n = data_t_raw_.size(); data_t_.resize(n, 0.0); double time_offset = time_relative_ ? data_t_raw_.front() : 0.0; double time_scale = time_seconds_ ? 1e-6 : 1.0; for(std::size_t i = 0; i < n; ++i) { data_t_[i] = (data_t_raw_[i] - time_offset) * time_scale; } std::vector<double> min_list; std::vector<double> max_list; for(auto data: data_v_) { if(data.size() != 0) { min_list.push_back(std::min(0.0, *std::min_element(data.begin(), data.end()))); max_list.push_back(std::max(0.0, *std::max_element(data.begin(), data.end()))); } } double min = std::min(0.0, *std::min_element(min_list.begin(), min_list.end())); double max = std::max(0.0, *std::max_element(max_list.begin(), max_list.end())); x_map.setScaleInterval(data_t_.front(), data_t_.back()); y_map.setScaleInterval(min - 1, max + 1); } void TimePlot::renderAndSend() { QImage image(width_, height_, QImage::Format_RGB32); QPainter painter; painter.begin(&image); painter.fillRect(image.rect(), color_bg_); QRect r(0, 0, image.width(), image.height()); x_map.setPaintInterval( r.left(), r.right() ); y_map.setPaintInterval( r.bottom(), r.top() ); if(basic_line_color_changed_) { calculateLineColors(); } QwtPlotCurve curve[data_v_.size()]; for(std::size_t num_plot= 0; num_plot < data_v_.size(); ++num_plot) { painter.setRenderHint( QPainter::Antialiasing, curve[num_plot].testRenderHint( QwtPlotItem::RenderAntialiased ) ); painter.setRenderHint( QPainter::HighQualityAntialiasing, curve[num_plot].testRenderHint( QwtPlotItem::RenderAntialiased ) ); curve[num_plot].setBaseline(0.0); curve[num_plot].setPen(color_line_.at(num_plot), line_width_); curve[num_plot].setStyle(QwtPlotCurve::Lines); curve[num_plot].setBrush(QBrush(color_fill_, Qt::SolidPattern)); curve[num_plot].setRawSamples(data_t_.data(), data_v_.at(num_plot).data(), data_t_.size()); curve[num_plot].draw(&painter, x_map, y_map, r); } QwtLinearScaleEngine e; QwtPlotScaleItem scale_time(QwtScaleDraw::TopScale, y_map.s1()); scale_time.setScaleDiv(e.divideScale(x_map.s1(), x_map.s2(), 10, 10)); QwtPlotScaleItem scale_value(QwtScaleDraw::RightScale, x_map.s1()); scale_value.setScaleDiv(e.divideScale(y_map.s1(), y_map.s2(), 10, 10)); scale_time.draw(&painter, x_map, y_map, r); scale_value.draw(&painter, x_map, y_map, r); CvMatMessage::Ptr out_msg = std::make_shared<CvMatMessage>(enc::bgr, 0); out_msg->value = QtCvImageConverter::Converter<QImage>::QImage2Mat(image); msg::publish(out_, out_msg); } int TimePlot::getWidth() const { return width_; } int TimePlot::getHeight() const { return height_; } double TimePlot::getLineWidth() const { return line_width_; } QColor TimePlot::getBackgroundColor() const { return color_bg_; } QColor TimePlot::getLineColor(std::size_t idx) const { return color_line_[idx]; } QColor TimePlot::getFillColor() const { return color_fill_; } const double* TimePlot::getTData() const { return data_t_.data(); } const double* TimePlot::getVData(std::size_t idx) const { return data_v_.at(idx).data(); } std::size_t TimePlot::getVDataCountNumCurves() const { return data_v_.size(); } std::size_t TimePlot::getCount() const { return data_t_.size(); } const QwtScaleMap& TimePlot::getXMap() const { return x_map; } const QwtScaleMap& TimePlot::getYMap() const { return y_map; } void TimePlot::calculateLineColors() { int r,g,b,a; basic_line_color_.getRgb(&r,&g,&b,&a); QColor color; color.setRed(r); color.setGreen(g); color.setBlue(b); int h,s,v; color.getHsv(&h,&s,&v); for(std::size_t i = 0; i < num_plots_; ++i) { double hnew = h + i * 360/num_plots_; while (hnew > 359 || hnew < 0) { if(hnew > 359) { hnew -= 360; } else if(hnew < 0) { hnew += 360; } } color.setHsv(hnew,s,v); color_line_[i] = color; } basic_line_color_changed_ = false; update(); } <commit_msg>minor<commit_after>/// HEADER #include "time_plot.h" /// PROJECT #include <csapex/msg/io.h> #include <csapex_opencv/cv_mat_message.h> #include <csapex/param/parameter_factory.h> #include <csapex/model/node_modifier.h> #include <csapex/utility/register_apex_plugin.h> #include <csapex/msg/generic_value_message.hpp> #include <csapex/view/utility/QtCvImageConverter.h> #include <csapex/msg/generic_vector_message.hpp> /// SYSTEM #include <qwt_scale_engine.h> CSAPEX_REGISTER_CLASS(csapex::TimePlot, csapex::Node) using namespace csapex; using namespace csapex::connection_types; void TimePlot::setup(NodeModifier &node_modifier) { in_ = node_modifier.addMultiInput<double, GenericVectorMessage>("Double"); out_ = node_modifier.addOutput<CvMatMessage>("Plot"); initialize_ = true; num_plots_ = 1; basic_line_color_changed_ = true; color_line_.resize(1); } void TimePlot::setupParameters(Parameterizable &parameters) { parameters.addParameter(param::ParameterFactory::declareRange ("~plot/width", 128, 4096, 640, 1), [this](param::Parameter* p) { width_ = p->as<int>(); update(); }); parameters.addParameter(param::ParameterFactory::declareRange ("~plot/height", 128, 4096, 320, 1), [this](param::Parameter* p) { height_ = p->as<int>(); update(); }); auto setColor = [this](QColor& color) { return [&](param::Parameter* p) { std::vector<int> c = p->as<std::vector<int>>(); color.setRed(c[0]); color.setGreen(c[1]); color.setBlue(c[2]); update(); }; }; std::function<void(param::Parameter* p)> setLineColors= [this](param::Parameter* p){ std::vector<int> c = p->as<std::vector<int>>(); basic_line_color_.setRed(c[0]); basic_line_color_.setGreen(c[1]); basic_line_color_.setBlue(c[2]); calculateLineColors(); basic_line_color_changed_ = true; update(); }; parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/background", 255, 255, 255), setColor(color_bg_)); parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/line", 100, 100, 255), setLineColors); parameters.addParameter(param::ParameterFactory::declareColorParameter( "~plot/color/fill", 200, 200, 200), setColor(color_fill_)); parameters.addParameter(param::ParameterFactory::declareRange( "~plot/line/width", 0.0, 10.0, 0.0, 0.01), line_width_); parameters.addParameter(param::ParameterFactory::declareBool ("~output/time/relative", param::ParameterDescription("Use time relative to the first entry"), true), time_relative_); parameters.addParameter(param::ParameterFactory::declareBool ("~output/time/seconds", param::ParameterDescription("Convert the time to seconds"), true), time_seconds_); parameters.addParameter(param::ParameterFactory::declareTrigger("reset"), [this](param::Parameter*) { reset(); }); } void TimePlot::process() { timepoint time = std::chrono::system_clock::now(); double value; if(msg::isValue<double>(in_)) { value = msg::getValue<double>(in_); if(initialize_){ data_v_.resize(1); num_plots_ = 1; initialize_ = false; color_line_.resize(1); calculateLineColors(); } data_v_.at(0).push_back(value); } else { GenericVectorMessage::ConstPtr message = msg::getMessage<GenericVectorMessage>(in_); apex_assert(std::dynamic_pointer_cast<GenericValueMessage<double>>(message->nestedType())); if(initialize_){ num_plots_ = message->nestedValueCount(); data_v_.resize(num_plots_); color_line_.resize(num_plots_); calculateLineColors(); initialize_ = false; } for(std::size_t num_plot = 0; num_plot < num_plots_; ++num_plot){ auto pval = std::dynamic_pointer_cast<GenericValueMessage<double> const>(message->nestedValue(num_plot)); if(pval){ double val = pval->value; data_v_.at(num_plot).push_back(val); } // double val = tval-> } } double ms = std::chrono::duration_cast<std::chrono::microseconds>(time.time_since_epoch()).count(); data_t_raw_.push_back(ms); preparePlot(); if(msg::isConnected(out_)) { renderAndSend(); } display_request(); } void TimePlot::reset() { data_t_raw_.clear(); data_v_.clear(); initialize_ = true; num_plots_ = 1; init(); } void TimePlot::init() { auto now = std::chrono::system_clock::now(); start_t_ = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch()).count(); } void TimePlot::preparePlot() { std::size_t n = data_t_raw_.size(); data_t_.resize(n, 0.0); color_fill_.setAlpha(100); double time_offset = time_relative_ ? data_t_raw_.front() : 0.0; double time_scale = time_seconds_ ? 1e-6 : 1.0; for(std::size_t i = 0; i < n; ++i) { data_t_[i] = (data_t_raw_[i] - time_offset) * time_scale; } std::vector<double> min_list; std::vector<double> max_list; for(auto data: data_v_) { if(data.size() != 0) { min_list.push_back(std::min(0.0, *std::min_element(data.begin(), data.end()))); max_list.push_back(std::max(0.0, *std::max_element(data.begin(), data.end()))); } } double min = std::min(0.0, *std::min_element(min_list.begin(), min_list.end())); double max = std::max(0.0, *std::max_element(max_list.begin(), max_list.end())); x_map.setScaleInterval(data_t_.front(), data_t_.back()); y_map.setScaleInterval(min - 1, max + 1); } void TimePlot::renderAndSend() { QImage image(width_, height_, QImage::Format_RGB32); QPainter painter; painter.begin(&image); painter.fillRect(image.rect(), color_bg_); QRect r(0, 0, image.width(), image.height()); x_map.setPaintInterval( r.left(), r.right() ); y_map.setPaintInterval( r.bottom(), r.top() ); if(basic_line_color_changed_) { calculateLineColors(); } QwtPlotCurve curve[data_v_.size()]; for(std::size_t num_plot= 0; num_plot < data_v_.size(); ++num_plot) { painter.setRenderHint( QPainter::Antialiasing, curve[num_plot].testRenderHint( QwtPlotItem::RenderAntialiased ) ); painter.setRenderHint( QPainter::HighQualityAntialiasing, curve[num_plot].testRenderHint( QwtPlotItem::RenderAntialiased ) ); curve[num_plot].setBaseline(0.0); curve[num_plot].setPen(color_line_.at(num_plot), line_width_); curve[num_plot].setStyle(QwtPlotCurve::Lines); curve[num_plot].setBrush(QBrush(color_fill_, Qt::SolidPattern)); curve[num_plot].setRawSamples(data_t_.data(), data_v_.at(num_plot).data(), data_t_.size()); curve[num_plot].draw(&painter, x_map, y_map, r); } QwtLinearScaleEngine e; QwtPlotScaleItem scale_time(QwtScaleDraw::TopScale, y_map.s1()); scale_time.setScaleDiv(e.divideScale(x_map.s1(), x_map.s2(), 10, 10)); QwtPlotScaleItem scale_value(QwtScaleDraw::RightScale, x_map.s1()); scale_value.setScaleDiv(e.divideScale(y_map.s1(), y_map.s2(), 10, 10)); scale_time.draw(&painter, x_map, y_map, r); scale_value.draw(&painter, x_map, y_map, r); CvMatMessage::Ptr out_msg = std::make_shared<CvMatMessage>(enc::bgr, 0); out_msg->value = QtCvImageConverter::Converter<QImage>::QImage2Mat(image); msg::publish(out_, out_msg); } int TimePlot::getWidth() const { return width_; } int TimePlot::getHeight() const { return height_; } double TimePlot::getLineWidth() const { return line_width_; } QColor TimePlot::getBackgroundColor() const { return color_bg_; } QColor TimePlot::getLineColor(std::size_t idx) const { return color_line_[idx]; } QColor TimePlot::getFillColor() const { return color_fill_; } const double* TimePlot::getTData() const { return data_t_.data(); } const double* TimePlot::getVData(std::size_t idx) const { return data_v_.at(idx).data(); } std::size_t TimePlot::getVDataCountNumCurves() const { return data_v_.size(); } std::size_t TimePlot::getCount() const { return data_t_.size(); } const QwtScaleMap& TimePlot::getXMap() const { return x_map; } const QwtScaleMap& TimePlot::getYMap() const { return y_map; } void TimePlot::calculateLineColors() { int r,g,b,a; basic_line_color_.getRgb(&r,&g,&b,&a); QColor color; color.setRed(r); color.setGreen(g); color.setBlue(b); int h,s,v; color.getHsv(&h,&s,&v); for(std::size_t i = 0; i < num_plots_; ++i) { double hnew = h + i * 360/num_plots_; while (hnew > 359 || hnew < 0) { if(hnew > 359) { hnew -= 360; } else if(hnew < 0) { hnew += 360; } } color.setHsv(hnew,s,v); color_line_[i] = color; } basic_line_color_changed_ = false; update(); } <|endoftext|>
<commit_before>/** * The MIT License (MIT) * * Copyright © 2018-2019 Ruben Van Boxem * * 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. **/ /* * Boost.Spirit.X3 std::variant compatibility * See https://github.com/boostorg/spirit/issues/270#issuecomment-439160933. * This is incomplete, yet enables the enough functionality for its uses here. */ #ifndef SKUI_CSS_GRAMMAR_X3_STDVARIANT_H #define SKUI_CSS_GRAMMAR_X3_STDVARIANT_H #include <variant> #include <boost/mpl/vector.hpp> #include <boost/spirit/home/x3/support/traits/is_variant.hpp> #include <boost/spirit/home/x3/support/traits/tuple_traits.hpp> #include <boost/spirit/home/x3/support/traits/variant_find_substitute.hpp> #include <boost/spirit/home/x3/support/traits/variant_has_substitute.hpp> // Based on: boost/spirit/home/x3/support/traits/variant_find_substitute.hpp namespace boost::spirit::x3::traits { template<typename... Ts> struct is_variant<std::variant<Ts...>> : mpl::true_ {}; template<typename... Ts, typename Attribute> struct variant_find_substitute<std::variant<Ts...>, Attribute> { using variant_type = std::variant<Ts...>; using types = mpl::vector<Ts...>; using end = typename mpl::end<types>::type; using iter_1 = typename mpl::find_if<types, is_same<mpl::_1, Attribute>>::type; using iter = typename mpl::eval_if<is_same<iter_1, end>, mpl::find_if<types, traits::is_substitute<mpl::_1, Attribute>>, mpl::identity<iter_1>>::type; using type = typename mpl::eval_if<is_same<iter, end>, mpl::identity<Attribute>, mpl::deref<iter>>::type; }; template<typename... Ts> struct variant_find_substitute<std::variant<Ts...>, std::variant<Ts...>> : mpl::identity<std::variant<Ts...>> {}; template<typename... Ts, typename Attribute> struct variant_has_substitute_impl<std::variant<Ts...>, Attribute> { // Find a type from the variant that can be a substitute for Attribute. // return true_ if one is found, else false_ using types = mpl::vector<Ts...>; using end = typename mpl::end<types>::type; using iter_1 = typename mpl::find_if<types, is_same<mpl::_1, Attribute>>::type; using iter = typename mpl::eval_if<is_same<iter_1, end>, mpl::find_if<types, traits::is_substitute<mpl::_1, Attribute>>, mpl::identity<iter_1>>::type; using type = mpl::not_<is_same<iter, end>>; }; } #endif <commit_msg>Let std::variant work when BOOST_SPIRIT_X3_DEBUG is defined.<commit_after>/** * The MIT License (MIT) * * Copyright © 2018-2019 Ruben Van Boxem * * 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. **/ /* * Boost.Spirit.X3 std::variant compatibility * See https://github.com/boostorg/spirit/issues/270#issuecomment-439160933. * This is incomplete, yet enables the enough functionality for its uses here. */ #ifndef SKUI_CSS_GRAMMAR_X3_STDVARIANT_H #define SKUI_CSS_GRAMMAR_X3_STDVARIANT_H #include <variant> #include <boost/mpl/vector.hpp> #include <boost/spirit/home/x3/support/traits/is_variant.hpp> #include <boost/spirit/home/x3/support/traits/tuple_traits.hpp> #include <boost/spirit/home/x3/support/traits/variant_find_substitute.hpp> #include <boost/spirit/home/x3/support/traits/variant_has_substitute.hpp> // Based on: boost/spirit/home/x3/support/traits/variant_find_substitute.hpp namespace boost::spirit::x3::traits { template<typename... Ts> struct is_variant<std::variant<Ts...>> : mpl::true_ {}; template<typename... Ts, typename Attribute> struct variant_find_substitute<std::variant<Ts...>, Attribute> { using variant_type = std::variant<Ts...>; using types = mpl::vector<Ts...>; using end = typename mpl::end<types>::type; using iter_1 = typename mpl::find_if<types, is_same<mpl::_1, Attribute>>::type; using iter = typename mpl::eval_if<is_same<iter_1, end>, mpl::find_if<types, traits::is_substitute<mpl::_1, Attribute>>, mpl::identity<iter_1>>::type; using type = typename mpl::eval_if<is_same<iter, end>, mpl::identity<Attribute>, mpl::deref<iter>>::type; }; template<typename... Ts> struct variant_find_substitute<std::variant<Ts...>, std::variant<Ts...>> : mpl::identity<std::variant<Ts...>> {}; template<typename... Ts, typename Attribute> struct variant_has_substitute_impl<std::variant<Ts...>, Attribute> { // Find a type from the variant that can be a substitute for Attribute. // return true_ if one is found, else false_ using types = mpl::vector<Ts...>; using end = typename mpl::end<types>::type; using iter_1 = typename mpl::find_if<types, is_same<mpl::_1, Attribute>>::type; using iter = typename mpl::eval_if<is_same<iter_1, end>, mpl::find_if<types, traits::is_substitute<mpl::_1, Attribute>>, mpl::identity<iter_1>>::type; using type = mpl::not_<is_same<iter, end>>; }; template<typename Out, typename... Ts> void print_attribute(Out& out, const std::variant<Ts...>& variant) { std::visit([&out](const auto& value) { out << value; }, variant); } } #endif <|endoftext|>
<commit_before><commit_msg>Use more ScopedTempDirs.<commit_after><|endoftext|>
<commit_before><commit_msg>Mark AutomatedUITestBase.OpenCloseBrowserWindowWithAccelerator as a flakey crash, as it has been failing on vista debug bots consistently.<commit_after><|endoftext|>
<commit_before>#include "Image.h" #include "ImageLoader.h" #include "dataset/TPNode.h" #include "render/GL10.h" #include "render/Shader.h" #include "render/ShaderMgr.h" //#include "render/DynamicTexture.h" #include "render/DynamicTexAndFont.h" #include "render/RenderList.h" #include "common/tools.h" #include "common/Exception.h" #include "common/Math.h" #include "common/Config.h" #include "common/SettingData.h" #include "common/TodoConfig.h" #include <fstream> #include <SOIL/SOIL.h> #include <easyimage.h> #include <wx/filename.h> //#define USE_SOIL namespace d2d { Image::Image() : m_pixels(NULL) { m_textureID = 0; m_width = m_height = 0; } Image::~Image() { ImageMgr::Instance()->removeItem(m_filepath); delete m_pixels; } bool Image::loadFromFile(const wxString& filepath) { if (!wxFileName::FileExists(filepath)) { throw Exception("File: %s don't exist!", filepath.ToStdString().c_str()); } m_filepath = filepath; // m_region.xMin = - m_width * 0.5f; // m_region.xMax = m_width * 0.5f; // m_region.yMin = - m_height * 0.5f; // m_region.yMax = m_height * 0.5f; #ifdef NOT_LOAD_IMAGE return true; #endif reload(); if (m_textureID == 0) { // assert(0); // m_width = m_height = 0; return true; } else { #ifdef USE_SOIL GL10::BindTexture(GL10::GL_TEXTURE_2D, m_textureID); GL10::GetTexLevelParameteriv(GL10::GL_TEXTURE_2D, 0, GL10::GL_TEXTURE_WIDTH, &m_width); GL10::GetTexLevelParameteriv(GL10::GL_TEXTURE_2D, 0, GL10::GL_TEXTURE_HEIGHT, &m_height); GL10::BindTexture(GL10::GL_TEXTURE_2D, NULL); #endif if (Config::Instance()->GetSettings().open_image_edge_clip) { eimage::ImageProcessor processor(this); d2d::Rect r = processor.trim(); if (r.isValid()) { r.translate(d2d::Vector(-m_width*0.5f, -m_height*0.5f)); m_region = r; } } else { m_region.xMin = - m_width * 0.5f; m_region.xMax = m_width * 0.5f; m_region.yMin = - m_height * 0.5f; m_region.yMax = m_height * 0.5f; } // // todo // DynamicTexture::Instance()->Insert(this); if (Config::Instance()->IsUseDTex()) { DynamicTexAndFont::Instance()->AddImage(this); } return true; } } void Image::reload() { #ifdef USE_SOIL m_textureID = SOIL_load_OGL_texture ( m_filepath.c_str(), SOIL_LOAD_AUTO, m_textureID, SOIL_FLAG_INVERT_Y ); #else m_pixels = ImageLoader::loadTexture(m_filepath.ToStdString(), m_width, m_height, m_textureID, m_channels); m_region.xMin = - m_width * 0.5f; m_region.xMax = m_width * 0.5f; m_region.yMin = - m_height * 0.5f; m_region.yMax = m_height * 0.5f; #endif } void Image::draw(const Matrix& mt, const Rect& r) const { //////////////////////////////////////////////////////////////////////////// //// ԭʼ ֱӻ // ShaderMgr* shader = ShaderMgr::Instance(); // shader->sprite(); // // float tot_hw = m_width * 0.5f, // tot_hh = m_height * 0.5f; // float txmin = (r.xMin + tot_hw) / m_width, // txmax = (r.xMax + tot_hw) / m_width, // tymin = (r.yMin + tot_hh) / m_height, // tymax = (r.yMax + tot_hh) / m_height; // // d2d::Vector vertices[4]; // vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); // vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); // vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); // vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); // // for (int i = 0; i < 4; ++i) { // scr.TransPosForRender(vertices[i]); // } // // float vb[16]; // vb[0] = vertices[0].x; // vb[1] = vertices[0].y; // vb[2] = txmin; // vb[3] = tymin; // vb[4] = vertices[1].x; // vb[5] = vertices[1].y; // vb[6] = txmax; // vb[7] = tymin; // vb[8] = vertices[2].x; // vb[9] = vertices[2].y; // vb[10] = txmax; // vb[11] = tymax; // vb[12] = vertices[3].x; // vb[13] = vertices[3].y; // vb[14] = txmin; // vb[15] = tymax; // // shader->Draw(vb, m_textureID); ////////////////////////////////////////////////////////////////////////// // renderlist // d2d::Vector vertices[4]; // vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); // vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); // vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); // vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); // for (int i = 0; i < 4; ++i) { // scr.TransPosForRender(vertices[i]); // } // // d2d::Vector texcoords[4]; // float tot_hw = m_width * 0.5f, // tot_hh = m_height * 0.5f; // float txmin = (r.xMin + tot_hw) / m_width, // txmax = (r.xMax + tot_hw) / m_width, // tymin = (r.yMin + tot_hh) / m_height, // tymax = (r.yMax + tot_hh) / m_height; // texcoords[0].set(txmin, tymin); // texcoords[1].set(txmax, tymin); // texcoords[2].set(txmax, tymax); // texcoords[3].set(txmin, tymax); // // RenderList::Instance()->Insert(m_textureID, vertices, texcoords); ////////////////////////////////////////////////////////////////////////// // dtex d2d::Vector vertices[4]; vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); int texid; d2d::Vector texcoords[4]; float txmin, txmax, tymin, tymax; //DynamicTexture* dt = DynamicTexture::Instance(); DynamicTexAndFont* dt = DynamicTexAndFont::Instance(); const TPNode* n = dt->Query(m_filepath); if (n) { float padding = dt->GetPadding(); int width = dt->GetWidth(); int height = dt->GetHeight(); texid = dt->GetTextureID(); txmin = (n->GetMinX()+padding+0.5f) / width; txmax = (n->GetMaxX()-padding-0.5f) / width; tymin = (n->GetMinY()+padding+0.5f) / height; tymax = (n->GetMaxY()-padding-0.5f) / height; if (texid != 1) { wxLogDebug(_T("img dt's tex = %d"), texid); } if (n->IsRotated()) { d2d::Vector tmp = vertices[3]; vertices[3] = vertices[2]; vertices[2] = vertices[1]; vertices[1] = vertices[0]; vertices[0] = tmp; } } else { wxLogDebug("Fail to insert dtex: %s", m_filepath.c_str()); texid = m_textureID; d2d::Vector texcoords[4]; float tot_hw = m_width * 0.5f, tot_hh = m_height * 0.5f; txmin = (r.xMin + tot_hw) / m_width; txmax = (r.xMax + tot_hw) / m_width; tymin = (r.yMin + tot_hh) / m_height; tymax = (r.yMax + tot_hh) / m_height; } texcoords[0].set(txmin, tymin); texcoords[1].set(txmax, tymin); texcoords[2].set(txmax, tymax); texcoords[3].set(txmin, tymax); // RenderList::Instance()->Insert(texid, vertices, texcoords); ShaderMgr* shader = ShaderMgr::Instance(); shader->sprite(); shader->Draw(vertices, texcoords, texid); } } // d2d<commit_msg>[FIXED] 打包是不读image,image范围不对,导致offset sprite错误<commit_after>#include "Image.h" #include "ImageLoader.h" #include "dataset/TPNode.h" #include "render/GL10.h" #include "render/Shader.h" #include "render/ShaderMgr.h" //#include "render/DynamicTexture.h" #include "render/DynamicTexAndFont.h" #include "render/RenderList.h" #include "common/tools.h" #include "common/Exception.h" #include "common/Math.h" #include "common/Config.h" #include "common/SettingData.h" #include "common/TodoConfig.h" #include <fstream> #include <SOIL/SOIL.h> #include <easyimage.h> #include <wx/filename.h> //#define USE_SOIL namespace d2d { Image::Image() : m_pixels(NULL) { m_textureID = 0; m_width = m_height = 0; } Image::~Image() { ImageMgr::Instance()->removeItem(m_filepath); delete m_pixels; } bool Image::loadFromFile(const wxString& filepath) { if (filepath.Contains("1107_1") == 0) { int zz = 0; } if (!wxFileName::FileExists(filepath)) { throw Exception("File: %s don't exist!", filepath.ToStdString().c_str()); } m_filepath = filepath; #ifdef NOT_LOAD_IMAGE // todo m_region.xMin = m_region.xMax = m_region.yMin = m_region.yMax = 0; return true; #endif reload(); if (m_textureID == 0) { // assert(0); // m_width = m_height = 0; return true; } else { #ifdef USE_SOIL GL10::BindTexture(GL10::GL_TEXTURE_2D, m_textureID); GL10::GetTexLevelParameteriv(GL10::GL_TEXTURE_2D, 0, GL10::GL_TEXTURE_WIDTH, &m_width); GL10::GetTexLevelParameteriv(GL10::GL_TEXTURE_2D, 0, GL10::GL_TEXTURE_HEIGHT, &m_height); GL10::BindTexture(GL10::GL_TEXTURE_2D, NULL); #endif if (Config::Instance()->GetSettings().open_image_edge_clip) { eimage::ImageProcessor processor(this); d2d::Rect r = processor.trim(); if (r.isValid()) { r.translate(d2d::Vector(-m_width*0.5f, -m_height*0.5f)); m_region = r; } } else { m_region.xMin = - m_width * 0.5f; m_region.xMax = m_width * 0.5f; m_region.yMin = - m_height * 0.5f; m_region.yMax = m_height * 0.5f; } // // todo // DynamicTexture::Instance()->Insert(this); if (Config::Instance()->IsUseDTex()) { DynamicTexAndFont::Instance()->AddImage(this); } return true; } } void Image::reload() { #ifdef USE_SOIL m_textureID = SOIL_load_OGL_texture ( m_filepath.c_str(), SOIL_LOAD_AUTO, m_textureID, SOIL_FLAG_INVERT_Y ); #else m_pixels = ImageLoader::loadTexture(m_filepath.ToStdString(), m_width, m_height, m_textureID, m_channels); m_region.xMin = - m_width * 0.5f; m_region.xMax = m_width * 0.5f; m_region.yMin = - m_height * 0.5f; m_region.yMax = m_height * 0.5f; #endif } void Image::draw(const Matrix& mt, const Rect& r) const { //////////////////////////////////////////////////////////////////////////// //// ԭʼ ֱӻ // ShaderMgr* shader = ShaderMgr::Instance(); // shader->sprite(); // // float tot_hw = m_width * 0.5f, // tot_hh = m_height * 0.5f; // float txmin = (r.xMin + tot_hw) / m_width, // txmax = (r.xMax + tot_hw) / m_width, // tymin = (r.yMin + tot_hh) / m_height, // tymax = (r.yMax + tot_hh) / m_height; // // d2d::Vector vertices[4]; // vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); // vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); // vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); // vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); // // for (int i = 0; i < 4; ++i) { // scr.TransPosForRender(vertices[i]); // } // // float vb[16]; // vb[0] = vertices[0].x; // vb[1] = vertices[0].y; // vb[2] = txmin; // vb[3] = tymin; // vb[4] = vertices[1].x; // vb[5] = vertices[1].y; // vb[6] = txmax; // vb[7] = tymin; // vb[8] = vertices[2].x; // vb[9] = vertices[2].y; // vb[10] = txmax; // vb[11] = tymax; // vb[12] = vertices[3].x; // vb[13] = vertices[3].y; // vb[14] = txmin; // vb[15] = tymax; // // shader->Draw(vb, m_textureID); ////////////////////////////////////////////////////////////////////////// // renderlist // d2d::Vector vertices[4]; // vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); // vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); // vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); // vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); // for (int i = 0; i < 4; ++i) { // scr.TransPosForRender(vertices[i]); // } // // d2d::Vector texcoords[4]; // float tot_hw = m_width * 0.5f, // tot_hh = m_height * 0.5f; // float txmin = (r.xMin + tot_hw) / m_width, // txmax = (r.xMax + tot_hw) / m_width, // tymin = (r.yMin + tot_hh) / m_height, // tymax = (r.yMax + tot_hh) / m_height; // texcoords[0].set(txmin, tymin); // texcoords[1].set(txmax, tymin); // texcoords[2].set(txmax, tymax); // texcoords[3].set(txmin, tymax); // // RenderList::Instance()->Insert(m_textureID, vertices, texcoords); ////////////////////////////////////////////////////////////////////////// // dtex d2d::Vector vertices[4]; vertices[0] = Math::transVector(Vector(r.xMin, r.yMin), mt); vertices[1] = Math::transVector(Vector(r.xMax, r.yMin), mt); vertices[2] = Math::transVector(Vector(r.xMax, r.yMax), mt); vertices[3] = Math::transVector(Vector(r.xMin, r.yMax), mt); int texid; d2d::Vector texcoords[4]; float txmin, txmax, tymin, tymax; //DynamicTexture* dt = DynamicTexture::Instance(); DynamicTexAndFont* dt = DynamicTexAndFont::Instance(); const TPNode* n = dt->Query(m_filepath); if (n) { float padding = dt->GetPadding(); int width = dt->GetWidth(); int height = dt->GetHeight(); texid = dt->GetTextureID(); txmin = (n->GetMinX()+padding+0.5f) / width; txmax = (n->GetMaxX()-padding-0.5f) / width; tymin = (n->GetMinY()+padding+0.5f) / height; tymax = (n->GetMaxY()-padding-0.5f) / height; if (texid != 1) { wxLogDebug(_T("img dt's tex = %d"), texid); } if (n->IsRotated()) { d2d::Vector tmp = vertices[3]; vertices[3] = vertices[2]; vertices[2] = vertices[1]; vertices[1] = vertices[0]; vertices[0] = tmp; } } else { wxLogDebug("Fail to insert dtex: %s", m_filepath.c_str()); texid = m_textureID; d2d::Vector texcoords[4]; float tot_hw = m_width * 0.5f, tot_hh = m_height * 0.5f; txmin = (r.xMin + tot_hw) / m_width; txmax = (r.xMax + tot_hw) / m_width; tymin = (r.yMin + tot_hh) / m_height; tymax = (r.yMax + tot_hh) / m_height; } texcoords[0].set(txmin, tymin); texcoords[1].set(txmax, tymin); texcoords[2].set(txmax, tymax); texcoords[3].set(txmin, tymax); // RenderList::Instance()->Insert(texid, vertices, texcoords); ShaderMgr* shader = ShaderMgr::Instance(); shader->sprite(); shader->Draw(vertices, texcoords, texid); } } // d2d<|endoftext|>
<commit_before>#include "kinetic_scroller.hpp" #include "visual_params.hpp" #include "indexer/scales.hpp" #include "base/logging.hpp" namespace df { double const kKineticDuration = 0.375; double const kKineticFeedbackStart = 0.1; double const kKineticFeedbackEnd = 0.5; double const kKineticFadeoff = 5.0; double const kKineticThreshold = 10.0; double const kKineticInertia = 0.8; double const kKineticMaxSpeed = 2000.0; // pixels per second double CalculateKineticFeedback(ScreenBase const & modelView) { double const kMinZoom = 1.0; double const kMaxZoom = scales::UPPER_STYLE_SCALE + 1.0; double const zoomLevel = my::clamp(fabs(log(modelView.GetScale()) / log(2.0)), kMinZoom, kMaxZoom); double const lerpCoef = 1.0 - ((zoomLevel - kMinZoom) / (kMaxZoom - kMinZoom)); return kKineticFeedbackStart * lerpCoef + kKineticFeedbackEnd * (1.0 - lerpCoef); } class KineticScrollAnimation : public BaseModelViewAnimation { public: // startRect - mercator visible on screen rect in moment when user release fingers // direction - mercator space direction of moving. length(direction) - mercator distance on wich map will be offset KineticScrollAnimation(m2::AnyRectD const & startRect, m2::PointD const & direction, double duration) : BaseModelViewAnimation(duration) , m_targetCenter(startRect.GlobalCenter() + direction) , m_angle(startRect.Angle()) , m_localRect(startRect.GetLocalRect()) , m_direction(direction) { } m2::AnyRectD GetCurrentRect(ScreenBase const & screen) const override { // current position = target position - amplutide * e ^ (elapsed / duration) // we calculate current position not based on start position, but based on target position return m2::AnyRectD(m_targetCenter - m_direction * exp(-kKineticFadeoff * GetT()), m_angle, m_localRect); } m2::AnyRectD GetTargetRect(ScreenBase const & screen) const override { return GetCurrentRect(screen); } private: m2::PointD m_targetCenter; ang::AngleD m_angle; m2::RectD m_localRect; m2::PointD m_direction; }; KineticScroller::KineticScroller() : m_lastTimestamp(-1.0) , m_direction(m2::PointD::Zero()) { } void KineticScroller::InitGrab(ScreenBase const & modelView, double timeStamp) { ASSERT_LESS(m_lastTimestamp, 0.0, ()); m_lastTimestamp = timeStamp; m_lastRect = modelView.GlobalRect(); } bool KineticScroller::IsActive() const { return m_lastTimestamp > 0.0; } void KineticScroller::GrabViewRect(ScreenBase const & modelView, double timeStamp) { // In KineitcScroller we store m_direction in mixed state // Direction in mercator space, and length(m_direction) in pixel space // We need same reaction on different zoom levels, and should calculate velocity on pixel space ASSERT_GREATER(m_lastTimestamp, 0.0, ()); ASSERT_GREATER(timeStamp, m_lastTimestamp, ()); double elapsed = timeStamp - m_lastTimestamp; m2::PointD lastCenter = m_lastRect.GlobalCenter(); m2::PointD currentCenter = modelView.GlobalRect().GlobalCenter(); double pxDeltaLength = (modelView.GtoP(currentCenter) - modelView.GtoP(lastCenter)).Length(); m2::PointD delta = (currentCenter - lastCenter); if (!delta.IsAlmostZero()) delta = delta.Normalize(); // velocity on pixels double v = pxDeltaLength / elapsed; if (v > kKineticMaxSpeed) v = kKineticMaxSpeed; // at this point length(m_direction) already in pixel space, and delta normalized m_direction = delta * kKineticInertia * v + m_direction * (1.0 - kKineticInertia); m_lastTimestamp = timeStamp; m_lastRect = modelView.GlobalRect(); } void KineticScroller::CancelGrab() { m_lastTimestamp = -1; m_direction = m2::PointD::Zero(); } unique_ptr<BaseModelViewAnimation> KineticScroller::CreateKineticAnimation(ScreenBase const & modelView) { static double kVelocityThreshold = kKineticThreshold * VisualParams::Instance().GetVisualScale(); if (m_direction.Length() < kVelocityThreshold) return unique_ptr<BaseModelViewAnimation>(); // Before we start animation we have to convert length(m_direction) from pixel space to mercator space m2::PointD center = m_lastRect.GlobalCenter(); double glbLength = CalculateKineticFeedback(modelView) * (modelView.PtoG(modelView.GtoP(center) + m_direction) - center).Length(); m2::PointD glbDirection = m_direction.Normalize() * glbLength; m2::PointD targetCenter = center + glbDirection; if (!df::GetWorldRect().IsPointInside(targetCenter)) return unique_ptr<BaseModelViewAnimation>(); return unique_ptr<BaseModelViewAnimation>(new KineticScrollAnimation(m_lastRect, glbDirection, kKineticDuration)); } } // namespace df <commit_msg>Review fixes<commit_after>#include "kinetic_scroller.hpp" #include "visual_params.hpp" #include "indexer/scales.hpp" #include "base/logging.hpp" namespace df { double const kKineticDuration = 0.375; double const kKineticFeedbackStart = 0.1; double const kKineticFeedbackEnd = 0.5; double const kKineticFadeoff = 5.0; double const kKineticThreshold = 10.0; double const kKineticInertia = 0.8; double const kKineticMaxSpeed = 2000.0; // pixels per second double CalculateKineticFeedback(ScreenBase const & modelView) { double const kMinZoom = 1.0; double const kMaxZoom = scales::UPPER_STYLE_SCALE + 1.0; double const zoomLevel = my::clamp(fabs(log(modelView.GetScale()) / log(2.0)), kMinZoom, kMaxZoom); double const lerpCoef = 1.0 - ((zoomLevel - kMinZoom) / (kMaxZoom - kMinZoom)); return kKineticFeedbackStart * lerpCoef + kKineticFeedbackEnd * (1.0 - lerpCoef); } class KineticScrollAnimation : public BaseModelViewAnimation { public: // startRect - mercator visible on screen rect in moment when user release fingers // direction - mercator space direction of moving. length(direction) - mercator distance on wich map will be offset KineticScrollAnimation(m2::AnyRectD const & startRect, m2::PointD const & direction, double duration) : BaseModelViewAnimation(duration) , m_targetCenter(startRect.GlobalCenter() + direction) , m_angle(startRect.Angle()) , m_localRect(startRect.GetLocalRect()) , m_direction(direction) { } m2::AnyRectD GetCurrentRect(ScreenBase const & screen) const override { // current position = target position - amplutide * e ^ (elapsed / duration) // we calculate current position not based on start position, but based on target position return m2::AnyRectD(m_targetCenter - m_direction * exp(-kKineticFadeoff * GetT()), m_angle, m_localRect); } m2::AnyRectD GetTargetRect(ScreenBase const & screen) const override { return GetCurrentRect(screen); } private: m2::PointD m_targetCenter; ang::AngleD m_angle; m2::RectD m_localRect; m2::PointD m_direction; }; KineticScroller::KineticScroller() : m_lastTimestamp(-1.0) , m_direction(m2::PointD::Zero()) { } void KineticScroller::InitGrab(ScreenBase const & modelView, double timeStamp) { ASSERT_LESS(m_lastTimestamp, 0.0, ()); m_lastTimestamp = timeStamp; m_lastRect = modelView.GlobalRect(); } bool KineticScroller::IsActive() const { return m_lastTimestamp > 0.0; } void KineticScroller::GrabViewRect(ScreenBase const & modelView, double timeStamp) { // In KineitcScroller we store m_direction in mixed state // Direction in mercator space, and length(m_direction) in pixel space // We need same reaction on different zoom levels, and should calculate velocity on pixel space ASSERT_GREATER(m_lastTimestamp, 0.0, ()); ASSERT_GREATER(timeStamp, m_lastTimestamp, ()); double elapsed = timeStamp - m_lastTimestamp; m2::PointD lastCenter = m_lastRect.GlobalCenter(); m2::PointD currentCenter = modelView.GlobalRect().GlobalCenter(); double pxDeltaLength = (modelView.GtoP(currentCenter) - modelView.GtoP(lastCenter)).Length(); m2::PointD delta = (currentCenter - lastCenter); if (!delta.IsAlmostZero()) delta = delta.Normalize(); // velocity on pixels double v = min(pxDeltaLength / elapsed, kKineticMaxSpeed); // at this point length(m_direction) already in pixel space, and delta normalized m_direction = delta * kKineticInertia * v + m_direction * (1.0 - kKineticInertia); m_lastTimestamp = timeStamp; m_lastRect = modelView.GlobalRect(); } void KineticScroller::CancelGrab() { m_lastTimestamp = -1; m_direction = m2::PointD::Zero(); } unique_ptr<BaseModelViewAnimation> KineticScroller::CreateKineticAnimation(ScreenBase const & modelView) { static double kVelocityThreshold = kKineticThreshold * VisualParams::Instance().GetVisualScale(); if (m_direction.Length() < kVelocityThreshold) return unique_ptr<BaseModelViewAnimation>(); // Before we start animation we have to convert length(m_direction) from pixel space to mercator space m2::PointD center = m_lastRect.GlobalCenter(); double glbLength = CalculateKineticFeedback(modelView) * (modelView.PtoG(modelView.GtoP(center) + m_direction) - center).Length(); m2::PointD glbDirection = m_direction.Normalize() * glbLength; m2::PointD targetCenter = center + glbDirection; if (!df::GetWorldRect().IsPointInside(targetCenter)) return unique_ptr<BaseModelViewAnimation>(); return unique_ptr<BaseModelViewAnimation>(new KineticScrollAnimation(m_lastRect, glbDirection, kKineticDuration)); } } // namespace df <|endoftext|>
<commit_before>#include <stdio.h> #include <stdlib.h> #include "../make_random_data/make_random_data.hpp" #include "../sort/merge.hpp" #include "../sort/selection.hpp" #include "../sort/insertion.hpp" #include "../sort/bubble.hpp" #define SORT merge #define SIZE 10 int main(void) { int *data = make_random_data(SIZE); for(int i = 0; i < SIZE; ++i) printf("%d\n", data[i]); putchar('\n'); SORT(data, SIZE); for(int i = 0; i < SIZE; ++i) printf("%d\n", data[i]); free_random_data(data); return 0; } <commit_msg>Remove main_for_testing_sort.cpp<commit_after><|endoftext|>
<commit_before>#include <iostream> #include "velocypack/vpack.h" #include "velocypack/velocypack-exception-macros.h" using namespace arangodb::velocypack; // this is our handler for custom types struct MyCustomTypeHandler : public CustomTypeHandler { // serialize a custom type into JSON static int const myMagicNumber = 42; std::string toString(Slice const& value, Options const*, Slice const&) override final { if (value.head() == 0xf0) { return std::to_string(myMagicNumber); } if (value.head() == 0xf4) { char const* start = value.startAs<char const>(); // read string length uint8_t length = *(value.start() + 1); // append string (don't care about escaping here...) return std::string(start, length); } throw "unknown type!"; } void dump(Slice const& value, Dumper* dumper, Slice const&) override final { Sink* sink = dumper->sink(); if (value.head() == 0xf0) { sink->append(std::to_string(myMagicNumber)); return; } if (value.head() == 0xf4) { char const* start = value.startAs<char const>(); // read string length uint8_t length = *(value.start() + 1); // append string (don't care about escaping here...) sink->push_back('"'); sink->append(start + 2, static_cast<ValueLength>(length)); sink->push_back('"'); return; } throw "unknown type!"; } }; int main(int, char* []) { VELOCYPACK_GLOBAL_EXCEPTION_TRY MyCustomTypeHandler handler; Options options; options.customTypeHandler = &handler; Builder b(&options); b(Value(ValueType::Object)); uint8_t* p; // create an attribute "custom1" of type 0xf0 with bytesize 1 // this type will be serialized into the value of 42 p = b.add("custom1", ValuePair(2ULL, ValueType::Custom)); *p = 0xf0; // create an attribute "custom2" of type 0xf1 with bytesize 8 // this type will be contain a user-defined string type, with // one byte of string length information following the Slice's // head byte, and the string bytes are it. p = b.add("custom2", ValuePair(8ULL, ValueType::Custom)); *p++ = 0xf4; // fill it with something useful... *p++ = static_cast<uint8_t>(6); // length of following string *p++ = 'f'; *p++ = 'o'; *p++ = 'o'; *p++ = 'b'; *p++ = 'a'; *p++ = 'r'; // another 0xf1 value p = b.add("custom3", ValuePair(5ULL, ValueType::Custom)); *p++ = 0xf4; *p++ = static_cast<uint8_t>(3); // length of following string *p++ = 'q'; *p++ = 'u'; *p++ = 'x'; b.close(); Slice s = b.slice(); // now print 'custom1': std::cout << "'custom1': byteSize: " << s.get("custom1").byteSize() << ", JSON: " << s.get("custom1").toJson() << std::endl; // and 'custom2': std::cout << "'custom2': byteSize: " << s.get("custom2").byteSize() << ", JSON: " << s.get("custom2").toJson() << std::endl; // and 'custom3': std::cout << "'custom3': byteSize: " << s.get("custom3").byteSize() << ", JSON: " << s.get("custom3").toJson() << std::endl; VELOCYPACK_GLOBAL_EXCEPTION_CATCH } <commit_msg>Make exampleCustom.cpp work<commit_after>#include <iostream> #include "velocypack/vpack.h" #include "velocypack/velocypack-exception-macros.h" using namespace arangodb::velocypack; // this is our handler for custom types struct MyCustomTypeHandler : public CustomTypeHandler { // serialize a custom type into JSON static int const myMagicNumber = 42; std::string toString(Slice const& value, Options const*, Slice const&) override final { if (value.head() == 0xf0) { return std::to_string(myMagicNumber); } if (value.head() == 0xf4) { char const* start = value.startAs<char const>(); // read string length uint8_t length = *(value.start() + 1); // append string (don't care about escaping here...) return std::string(start, length); } throw "unknown type!"; } void dump(Slice const& value, Dumper* dumper, Slice const&) override final { Sink* sink = dumper->sink(); if (value.head() == 0xf0) { sink->append(std::to_string(myMagicNumber)); return; } if (value.head() == 0xf4) { char const* start = value.startAs<char const>(); // read string length uint8_t length = *(value.start() + 1); // append string (don't care about escaping here...) sink->push_back('"'); sink->append(start + 2, static_cast<ValueLength>(length)); sink->push_back('"'); return; } throw "unknown type!"; } }; int main(int, char* []) { VELOCYPACK_GLOBAL_EXCEPTION_TRY MyCustomTypeHandler handler; Options options; options.customTypeHandler = &handler; Builder b(&options); b(Value(ValueType::Object)); uint8_t* p; // create an attribute "custom1" of type 0xf0 with bytesize 1 // this type will be serialized into the value of 42 p = b.add("custom1", ValuePair(2ULL, ValueType::Custom)); *p = 0xf0; // create an attribute "custom2" of type 0xf1 with bytesize 8 // this type will be contain a user-defined string type, with // one byte of string length information following the Slice's // head byte, and the string bytes are it. p = b.add("custom2", ValuePair(8ULL, ValueType::Custom)); *p++ = 0xf4; // fill it with something useful... *p++ = static_cast<uint8_t>(6); // length of following string *p++ = 'f'; *p++ = 'o'; *p++ = 'o'; *p++ = 'b'; *p++ = 'a'; *p++ = 'r'; // another 0xf1 value p = b.add("custom3", ValuePair(5ULL, ValueType::Custom)); *p++ = 0xf4; *p++ = static_cast<uint8_t>(3); // length of following string *p++ = 'q'; *p++ = 'u'; *p++ = 'x'; b.close(); Slice s = b.slice(); // now print 'custom1': std::cout << "'custom1': byteSize: " << s.get("custom1").byteSize() << ", JSON: " << s.get("custom1").toJson(&options) << std::endl; // and 'custom2': std::cout << "'custom2': byteSize: " << s.get("custom2").byteSize() << ", JSON: " << s.get("custom2").toJson(&options) << std::endl; // and 'custom3': std::cout << "'custom3': byteSize: " << s.get("custom3").byteSize() << ", JSON: " << s.get("custom3").toJson(&options) << std::endl; VELOCYPACK_GLOBAL_EXCEPTION_CATCH } <|endoftext|>
<commit_before>#include "SDL.h" #include "SDL_image.h" #include <iostream> #include <assert.h> #include "shared/path_creator.hpp" #include "shared/tdmap.hpp" #include "shared/sizes.h" #include <map> #include <set> #include <boost/foreach.hpp> #include "graphics/graphics_path.hpp" using namespace std; class GUI { private: void logSDLError(std::ostream &os, const std::string &msg) { os << msg << " error: " << SDL_GetError() << std::endl; } std::map<std::string, SDL_Texture *> loaded_textures; std::string resPath; SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren) { SDL_Texture *texture; if(loaded_textures.find(file) != loaded_textures.end()) { texture = loaded_textures[file]; } else { texture = IMG_LoadTexture(ren, (resPath + file).c_str()); if (texture == nullptr) { logSDLError(std::cout, "LoadTexture"); } loaded_textures[file] = texture; } return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height * @param tex The source texture we want to draw * @param ren The renderer we want to draw to * @param x The x Coordinate to draw to * @param y The y Coordinate to draw to */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh) { //Setup the destination rectangle to be at the position we want SDL_Rect dst; dst.x = x; dst.y = y; dst.w = rw; dst.h = rh; SDL_RenderCopy(ren, tex, NULL, &dst); } int row_width; int row_height; SDL_Renderer * ren; Path * main_path; int numrows; int numcols; Coordinate screen_to_game_coord(Coordinate c) { return Coordinate(c.x / row_width, c.y / row_height); } void re_render() { std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() ); diff_coords.assign( diff_coords.begin(), diff_coords.end() ); BOOST_FOREACH(Coordinate &screen_cord, diff_coords) { Coordinate game_coord = screen_to_game_coord(screen_cord); renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height); if(main_path->in(game_coord.x, game_coord.y)) { renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height); } Tile& t = map->at(game_coord.x, game_coord.y); if(t.tower != nullptr) { SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren); if(texture != nullptr) { renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height); } } } } void fill_screen_tiles() { for(int i = 0; i < numrows; i++) { for(int j = 0; j < numcols; j++) { Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j)); renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height); if(main_path->in(i, j)) { renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height); } Tile& t = map->at(i, j); if(t.tower != nullptr) { SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren); Coordinate current_cord = game_to_screen_coord(Coordinate(i, j)); if(texture != nullptr) { renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height); } } } } } TDMap * map; int current_anim_frame; SDL_Texture * tile; SDL_Texture * background; public: GUI(int rows, int columns, Path * path, TDMap * map) { assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr); current_anim_frame = 0; row_width = DEFAULT_WIDTH/rows; row_height = DEFAULT_HEIGHT/columns; resPath = GRAPHICS_PATH; numrows = rows; numcols = columns; this->map = map; SDL_Window *win; main_path = path; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSDLError(std::cout, "SDL_Init"); exit(1); } win = SDL_CreateWindow("Tower Defense", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (win == nullptr) { logSDLError(std::cout, "CreateWindow"); SDL_Quit(); exit(1); } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { logSDLError(std::cout, "CreateRenderer"); //TODO free window SDL_Quit(); exit(1); } background = loadTexture("grass.png", ren); tile = loadTexture("tile.png", ren); if (background == nullptr || tile == nullptr) { logSDLError(std::cout, "Getting Images"); //TODO cleanup SDL_Quit(); exit(1); } fill_screen_tiles(); SDL_RenderPresent(ren); } typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type; std::vector<anim_type> animations; std::vector<Coordinate> diff_coords; // takes pixel coords. // pls take care while using. void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff) { animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to))); diff_coords.push_back(from); diff_coords.push_back(to); } void clear_attack_animations() { animations.clear(); } #define ANIMATION_CONSTANT 10 bool show_animations() { re_render(); BOOST_FOREACH(anim_type & animation, animations) { SDL_Texture * tex = animation.first.first; auto from_to = animation.second; int hdiff = from_to.second.x - from_to.first.x; int vdiff = from_to.second.y - from_to.first.y; hdiff = hdiff/ANIMATION_CONSTANT; vdiff = vdiff/ANIMATION_CONSTANT; animation.first.second.x += hdiff; animation.first.second.y += vdiff; renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height); } if(++current_anim_frame < ANIMATION_CONSTANT) { //SDL_Delay(1); return false; } return true; } void Update() { current_anim_frame = 0; for(int i = 0; i < NUM_ROWS; i++) { for(int j = 0; j < NUM_COLS; j++) { Tile& t = map->at(i, j); if(t.tower != nullptr) { Coordinate current_cord = game_to_screen_coord(Coordinate(i, j)); SDL_Texture * attack_texture = loadTexture(t.tower->get_attack_image_string(), ren); BOOST_FOREACH(Coordinate c, t.tower->get_attack_tiles()) { Coordinate screen_cord = game_to_screen_coord(c); set_up_animation(attack_texture, current_cord, screen_cord, true); } } BOOST_FOREACH(Sprite * s, t.sprites) { SDL_Texture * sprite_texture = loadTexture(s->image_string, ren); Coordinate previous_cord = game_to_screen_coord(s->get_previous_position()); set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true); } } } while(!show_animations()) { SDL_RenderPresent(ren); SDL_RenderPresent(ren); } re_render(); SDL_RenderPresent(ren); clear_attack_animations(); } Coordinate game_to_screen_coord(Coordinate game_coord) { return Coordinate(game_coord.x * row_width, game_coord.y * row_height); } Coordinate game_to_screen_coord(int x, int y) { return game_to_screen_coord(Coordinate(x, y)); } }; <commit_msg>too fast<commit_after>#include "SDL.h" #include "SDL_image.h" #include <iostream> #include <assert.h> #include "shared/path_creator.hpp" #include "shared/tdmap.hpp" #include "shared/sizes.h" #include <map> #include <set> #include <boost/foreach.hpp> #include "graphics/graphics_path.hpp" using namespace std; class GUI { private: void logSDLError(std::ostream &os, const std::string &msg) { os << msg << " error: " << SDL_GetError() << std::endl; } std::map<std::string, SDL_Texture *> loaded_textures; std::string resPath; SDL_Texture* loadTexture(const std::string &file, SDL_Renderer *ren) { SDL_Texture *texture; if(loaded_textures.find(file) != loaded_textures.end()) { texture = loaded_textures[file]; } else { texture = IMG_LoadTexture(ren, (resPath + file).c_str()); if (texture == nullptr) { logSDLError(std::cout, "LoadTexture"); } loaded_textures[file] = texture; } return texture; } /** * Draw an SDL_Texture to an SDL_Renderer at position x, y, preserving * the texture's width and height * @param tex The source texture we want to draw * @param ren The renderer we want to draw to * @param x The x Coordinate to draw to * @param y The y Coordinate to draw to */ void renderTexture(SDL_Texture *tex, SDL_Renderer *ren, int x, int y, int rw, int rh) { //Setup the destination rectangle to be at the position we want SDL_Rect dst; dst.x = x; dst.y = y; dst.w = rw; dst.h = rh; SDL_RenderCopy(ren, tex, NULL, &dst); } int row_width; int row_height; SDL_Renderer * ren; Path * main_path; int numrows; int numcols; Coordinate screen_to_game_coord(Coordinate c) { return Coordinate(c.x / row_width, c.y / row_height); } void re_render() { std::set<Coordinate> s( diff_coords.begin(), diff_coords.end() ); diff_coords.assign( diff_coords.begin(), diff_coords.end() ); BOOST_FOREACH(Coordinate &screen_cord, diff_coords) { Coordinate game_coord = screen_to_game_coord(screen_cord); renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height); if(main_path->in(game_coord.x, game_coord.y)) { renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height); } Tile& t = map->at(game_coord.x, game_coord.y); if(t.tower != nullptr) { SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren); if(texture != nullptr) { renderTexture(texture, ren, screen_cord.x, screen_cord.y, row_width, row_height); } } } } void fill_screen_tiles() { for(int i = 0; i < numrows; i++) { for(int j = 0; j < numcols; j++) { Coordinate screen_cord = game_to_screen_coord(Coordinate(i, j)); renderTexture(background, ren, screen_cord.x, screen_cord.y, row_width, row_height); if(main_path->in(i, j)) { renderTexture(tile, ren, screen_cord.x, screen_cord.y, row_width, row_height); } Tile& t = map->at(i, j); if(t.tower != nullptr) { SDL_Texture * texture = loadTexture(t.tower->get_image_string(), ren); Coordinate current_cord = game_to_screen_coord(Coordinate(i, j)); if(texture != nullptr) { renderTexture(texture, ren, current_cord.x, current_cord.y, row_width, row_height); } } } } } TDMap * map; int current_anim_frame; SDL_Texture * tile; SDL_Texture * background; public: GUI(int rows, int columns, Path * path, TDMap * map) { assert(rows > 0 && columns > 0 && path != nullptr && map != nullptr); current_anim_frame = 0; row_width = DEFAULT_WIDTH/rows; row_height = DEFAULT_HEIGHT/columns; resPath = GRAPHICS_PATH; numrows = rows; numcols = columns; this->map = map; SDL_Window *win; main_path = path; if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { logSDLError(std::cout, "SDL_Init"); exit(1); } win = SDL_CreateWindow("Tower Defense", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, DEFAULT_WIDTH, DEFAULT_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALLOW_HIGHDPI); if (win == nullptr) { logSDLError(std::cout, "CreateWindow"); SDL_Quit(); exit(1); } ren = SDL_CreateRenderer(win, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC); if (ren == nullptr) { logSDLError(std::cout, "CreateRenderer"); //TODO free window SDL_Quit(); exit(1); } background = loadTexture("grass.png", ren); tile = loadTexture("tile.png", ren); if (background == nullptr || tile == nullptr) { logSDLError(std::cout, "Getting Images"); //TODO cleanup SDL_Quit(); exit(1); } fill_screen_tiles(); SDL_RenderPresent(ren); } typedef std::pair<std::pair<SDL_Texture *, Coordinate> , std::pair<Coordinate, Coordinate>> anim_type; std::vector<anim_type> animations; std::vector<Coordinate> diff_coords; // takes pixel coords. // pls take care while using. void set_up_animation(SDL_Texture * texture, Coordinate from, Coordinate to, bool addToDiff) { animations.push_back(anim_type(std::make_pair(texture, from), std::make_pair(from, to))); diff_coords.push_back(from); diff_coords.push_back(to); } void clear_attack_animations() { animations.clear(); } #define ANIMATION_CONSTANT 10 bool show_animations() { re_render(); BOOST_FOREACH(anim_type & animation, animations) { SDL_Texture * tex = animation.first.first; auto from_to = animation.second; int hdiff = from_to.second.x - from_to.first.x; int vdiff = from_to.second.y - from_to.first.y; hdiff = hdiff/ANIMATION_CONSTANT; vdiff = vdiff/ANIMATION_CONSTANT; animation.first.second.x += hdiff; animation.first.second.y += vdiff; renderTexture(tex, ren, animation.first.second.x, animation.first.second.y, row_width, row_height); } if(++current_anim_frame < ANIMATION_CONSTANT) { //SDL_Delay(1); return false; } return true; } void Update() { current_anim_frame = 0; for(int i = 0; i < NUM_ROWS; i++) { for(int j = 0; j < NUM_COLS; j++) { Tile& t = map->at(i, j); if(t.tower != nullptr) { Coordinate current_cord = game_to_screen_coord(Coordinate(i, j)); SDL_Texture * attack_texture = loadTexture(t.tower->get_attack_image_string(), ren); BOOST_FOREACH(Coordinate c, t.tower->get_attack_tiles()) { Coordinate screen_cord = game_to_screen_coord(c); set_up_animation(attack_texture, current_cord, screen_cord, true); } } BOOST_FOREACH(Sprite * s, t.sprites) { SDL_Texture * sprite_texture = loadTexture(s->image_string, ren); Coordinate previous_cord = game_to_screen_coord(s->get_previous_position()); set_up_animation(sprite_texture, previous_cord, game_to_screen_coord(s->get_coordinate()), true); } } } while(!show_animations()) { SDL_RenderPresent(ren); } re_render(); SDL_RenderPresent(ren); clear_attack_animations(); } Coordinate game_to_screen_coord(Coordinate game_coord) { return Coordinate(game_coord.x * row_width, game_coord.y * row_height); } Coordinate game_to_screen_coord(int x, int y) { return game_to_screen_coord(Coordinate(x, y)); } }; <|endoftext|>
<commit_before>// Copyright 2016-2020 Jean-Francois Poilpret // // 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. /* * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device. * This program uses FastArduino VL53L0X support API. * It first asks user to input (through USB console) various VL53L0X settings, * then it uses these settings to start continuous ranging and display distance * measurements conitnuously (until reset). * * Wiring: * - on ATmega328P based boards (including Arduino UNO): * - A4 (PC4, SDA): connected to VL53L0X SDA pin * - A5 (PC5, SCL): connected to VL53L0X SCL pin * - direct USB access */ #include <fastarduino/time.h> #include <fastarduino/uart.h> #include <fastarduino/i2c_handler.h> #include <fastarduino/devices/vl53l0x.h> // #define FORCE_SYNC static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST; static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; static constexpr const uint8_t INPUT_BUFFER_SIZE = 32; static char input_buffer[INPUT_BUFFER_SIZE]; REGISTER_UART_ISR(0) #if I2C_TRUE_ASYNC and not defined(FORCE_SYNC) using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>; static constexpr const uint8_t I2C_BUFFER_SIZE = 32; static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE]; REGISTER_I2C_ISR(MANAGER) #else using MANAGER = i2c::I2CSyncManager<MODE>; #endif using streams::dec; using streams::hex; using streams::fixed; using streams::endl; using streams::flush; using namespace devices::vl53l0x; using TOF = VL53L0X<MANAGER>; #define CHECK_OK(STATEMENT) if (! STATEMENT) out << F(#STATEMENT) << F(" ERROR!") << endl static void display_status(streams::ostream& out, TOF& tof) { DeviceStatus status; bool ok = tof.get_range_status(status); out << F("tof.get_range_status(status) = ") << ok << F(", error = ") << dec << status.error() << F(", data_ready = ") << status.data_ready() << endl; } static bool yes_no(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label) { while (true) { out << label << flush; char answer = 0; in >> answer; switch (answer) { case 'y': case 'Y': out << endl; return true; case 'n': case 'N': out << endl; return false; default: out << F("Only Y or N are allowed!") << endl; } } } static constexpr uint8_t PRE_RANGE_VCSEL_VALUES[] = {12, 14, 16, 18}; static constexpr uint8_t PRE_RANGE_VCSEL_COUNT = sizeof(PRE_RANGE_VCSEL_VALUES); static constexpr uint8_t FINAL_RANGE_VCSEL_VALUES[] = {8, 10, 12, 14}; static constexpr uint8_t FINAL_RANGE_VCSEL_COUNT = sizeof(FINAL_RANGE_VCSEL_VALUES); static uint8_t vcsel_period(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label, uint8_t current, const uint8_t* values, uint8_t count) { while (true) { out << label << F("("); for (uint8_t i = 0; i < count; ++i) out << values[i] << ", "; out << F("current = ") << current << F("): ") << flush; uint16_t answer = 0; in >> answer; for (uint8_t i = 0; i < count; ++i) if (answer == values[i]) { out << endl; return answer; } out << F("Unauthorized value entered!") << endl; } } static float signal_rate(streams::ostream& out, streams::istream& in, float current) { while (true) { out << F("Signal rate (float in ]0;1], current = ") << current << F("): ") << flush; double answer = 0; in >> answer; if (answer > 0.0 && answer <= 1.0) { out << endl; return answer; } out << F("Only floats in ]0;1] are allowed!") << endl; } } static uint32_t timing_budget(streams::ostream& out, streams::istream& in, uint32_t current) { while (true) { out << F("Measurement timing budget in us (current = ") << current << F("us): ") << flush; uint32_t budget = 0; in >> budget; if (budget > 0) { out << endl; return budget; } out << F("Only positive numbers are allowed!") << endl; } } int main() __attribute__((OS_main)); int main() { board::init(); sei(); // open UART for traces serial::hard::UART<UART> uart{input_buffer, output_buffer}; streams::ostream out = uart.out(); streams::istream in = uart.in(); uart.begin(115200); out << streams::boolalpha; // Initialize I2C async handler #if I2C_TRUE_ASYNC and not defined(FORCE_SYNC) MANAGER manager{i2c_buffer}; #else MANAGER manager; #endif out << F("Instantiate VL53L0X") << endl; TOF tof{manager}; out << F("Start I2C manager") << endl; manager.begin(); out << F("Define VL53L0X parameters...\n") << endl; // Define steps for init_static_second() SequenceSteps steps = SequenceSteps::create(); out << F("Sequence steps:") << endl; if (yes_no(out, in, F(" TCC (Y/N): "))) steps = steps.tcc(); if (yes_no(out, in, F(" DSS (Y/N): "))) steps = steps.dss(); if (yes_no(out, in, F(" MSRC (Y/N): "))) steps = steps.msrc(); if (yes_no(out, in, F(" PRE-RANGE (Y/N): "))) steps = steps.pre_range(); if (yes_no(out, in, F(" FINAL-RANGE (Y/N): "))) steps = steps.final_range(); // Initialize VL53L0X chip out << F("Initialize VL53L0X chip...\n") << endl; CHECK_OK(tof.init_data_first()); CHECK_OK(tof.init_static_second(GPIOSettings::sample_ready(), steps)); CHECK_OK(tof.perform_ref_calibration()); // set_vcsel_pulse_period PRE-RANGE/FINAL-RANGE out << F("VCSEL pulse period:") << endl; uint8_t current_period = 0; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period)); uint8_t period = vcsel_period( out, in, F(" PRE-RANGE "), current_period, PRE_RANGE_VCSEL_VALUES, PRE_RANGE_VCSEL_COUNT); CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(period)); current_period = 0; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period)); period = vcsel_period( out, in, F(" FINAL-RANGE "), current_period, FINAL_RANGE_VCSEL_VALUES, FINAL_RANGE_VCSEL_COUNT); CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(period)); float rate = 0.0; CHECK_OK(tof.get_signal_rate_limit(rate)); rate = signal_rate(out, in, rate); CHECK_OK(tof.set_signal_rate_limit(rate)); uint32_t budget = 0; CHECK_OK(tof.get_measurement_timing_budget(budget)); budget = timing_budget(out, in, budget); CHECK_OK(tof.set_measurement_timing_budget(budget)); display_status(out, tof); // Perform reference calibration CHECK_OK(tof.perform_ref_calibration()); display_status(out, tof); // Start continuous ranging CHECK_OK(tof.start_continuous_ranging(1000U)); while (true) { time::delay_ms(995U); // Read continuous ranges now uint16_t range = 0; if (tof.await_continuous_range(range)) out << F("Range = ") << dec << range << F("mm") << endl; display_status(out, tof); } } <commit_msg>Display all settings in VL53L0X example<commit_after>// Copyright 2016-2020 Jean-Francois Poilpret // // 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. /* * Simple ranger example, using VL53L0X Time-of-flight range sensor I2C device. * This program uses FastArduino VL53L0X support API. * It first asks user to input (through USB console) various VL53L0X settings, * then it uses these settings to start continuous ranging and display distance * measurements conitnuously (until reset). * * Wiring: * - on ATmega328P based boards (including Arduino UNO): * - A4 (PC4, SDA): connected to VL53L0X SDA pin * - A5 (PC5, SCL): connected to VL53L0X SCL pin * - direct USB access */ #include <fastarduino/time.h> #include <fastarduino/uart.h> #include <fastarduino/i2c_handler.h> #include <fastarduino/devices/vl53l0x.h> // #define FORCE_SYNC static constexpr const i2c::I2CMode MODE = i2c::I2CMode::FAST; static constexpr const board::USART UART = board::USART::USART0; static constexpr const uint8_t OUTPUT_BUFFER_SIZE = 128; static char output_buffer[OUTPUT_BUFFER_SIZE]; static constexpr const uint8_t INPUT_BUFFER_SIZE = 32; static char input_buffer[INPUT_BUFFER_SIZE]; REGISTER_UART_ISR(0) #if I2C_TRUE_ASYNC and not defined(FORCE_SYNC) using MANAGER = i2c::I2CAsyncManager<MODE, i2c::I2CErrorPolicy::CLEAR_ALL_COMMANDS>; static constexpr const uint8_t I2C_BUFFER_SIZE = 32; static MANAGER::I2CCOMMAND i2c_buffer[I2C_BUFFER_SIZE]; REGISTER_I2C_ISR(MANAGER) #else using MANAGER = i2c::I2CSyncManager<MODE>; #endif using streams::dec; using streams::hex; using streams::fixed; using streams::endl; using streams::flush; using namespace devices::vl53l0x; using TOF = VL53L0X<MANAGER>; #define CHECK_OK(STATEMENT) if (! STATEMENT) out << F(#STATEMENT) << F(" ERROR!") << endl static void display_status(streams::ostream& out, TOF& tof) { DeviceStatus status; bool ok = tof.get_range_status(status); out << F("tof.get_range_status(status) = ") << ok << F(", error = ") << dec << status.error() << F(", data_ready = ") << status.data_ready() << endl; } static bool yes_no(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label) { while (true) { out << label << flush; char answer = 0; in >> answer; switch (answer) { case 'y': case 'Y': out << endl; return true; case 'n': case 'N': out << endl; return false; default: out << F("Only Y or N are allowed!") << endl; } } } static constexpr uint8_t PRE_RANGE_VCSEL_VALUES[] = {12, 14, 16, 18}; static constexpr uint8_t PRE_RANGE_VCSEL_COUNT = sizeof(PRE_RANGE_VCSEL_VALUES); static constexpr uint8_t FINAL_RANGE_VCSEL_VALUES[] = {8, 10, 12, 14}; static constexpr uint8_t FINAL_RANGE_VCSEL_COUNT = sizeof(FINAL_RANGE_VCSEL_VALUES); static uint8_t vcsel_period(streams::ostream& out, streams::istream& in, const flash::FlashStorage* label, uint8_t current, const uint8_t* values, uint8_t count) { while (true) { out << label << F("("); for (uint8_t i = 0; i < count; ++i) out << values[i] << ", "; out << F("current = ") << current << F("): ") << flush; uint16_t answer = 0; in >> answer; for (uint8_t i = 0; i < count; ++i) if (answer == values[i]) { out << endl; return answer; } out << F("Unauthorized value entered!") << endl; } } static float signal_rate(streams::ostream& out, streams::istream& in, float current) { while (true) { out << F("Signal rate (float in ]0;1], current = ") << current << F("): ") << flush; double answer = 0; in >> answer; if (answer > 0.0 && answer <= 1.0) { out << endl; return answer; } out << F("Only floats in ]0;1] are allowed!") << endl; } } static uint32_t timing_budget(streams::ostream& out, streams::istream& in, uint32_t current) { while (true) { out << F("Measurement timing budget in us (current = ") << current << F("us): ") << flush; uint32_t budget = 0; in >> budget; if (budget > 0) { out << endl; return budget; } out << F("Only positive numbers are allowed!") << endl; } } int main() __attribute__((OS_main)); int main() { board::init(); sei(); // open UART for traces serial::hard::UART<UART> uart{input_buffer, output_buffer}; streams::ostream out = uart.out(); streams::istream in = uart.in(); uart.begin(115200); out << streams::boolalpha; // Initialize I2C async handler #if I2C_TRUE_ASYNC and not defined(FORCE_SYNC) MANAGER manager{i2c_buffer}; #else MANAGER manager; #endif out << F("Instantiate VL53L0X") << endl; TOF tof{manager}; out << F("Start I2C manager") << endl; manager.begin(); out << F("Define VL53L0X parameters...\n") << endl; // Define steps for init_static_second() SequenceSteps steps = SequenceSteps::create(); out << F("Sequence steps:") << endl; if (yes_no(out, in, F(" TCC (Y/N): "))) steps = steps.tcc(); if (yes_no(out, in, F(" DSS (Y/N): "))) steps = steps.dss(); if (yes_no(out, in, F(" MSRC (Y/N): "))) steps = steps.msrc(); if (yes_no(out, in, F(" PRE-RANGE (Y/N): "))) steps = steps.pre_range(); if (yes_no(out, in, F(" FINAL-RANGE (Y/N): "))) steps = steps.final_range(); // Initialize VL53L0X chip out << F("Initialize VL53L0X chip...\n") << endl; CHECK_OK(tof.init_data_first()); CHECK_OK(tof.init_static_second(GPIOSettings::sample_ready(), steps)); CHECK_OK(tof.perform_ref_calibration()); // set_vcsel_pulse_period PRE-RANGE/FINAL-RANGE out << F("VCSEL pulse period:") << endl; uint8_t current_period = 0; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period)); uint8_t period = vcsel_period( out, in, F(" PRE-RANGE "), current_period, PRE_RANGE_VCSEL_VALUES, PRE_RANGE_VCSEL_COUNT); CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(period)); current_period = 0; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period)); period = vcsel_period( out, in, F(" FINAL-RANGE "), current_period, FINAL_RANGE_VCSEL_VALUES, FINAL_RANGE_VCSEL_COUNT); CHECK_OK(tof.set_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(period)); float rate = 0.0; CHECK_OK(tof.get_signal_rate_limit(rate)); rate = signal_rate(out, in, rate); CHECK_OK(tof.set_signal_rate_limit(rate)); uint32_t budget = 0; CHECK_OK(tof.get_measurement_timing_budget(budget)); budget = timing_budget(out, in, budget); CHECK_OK(tof.set_measurement_timing_budget(budget)); display_status(out, tof); // Perform reference calibration //TODO is that really useful? // CHECK_OK(tof.perform_ref_calibration()); display_status(out, tof); // Feedback on all settings out << F("Final settings") << endl; out << F("Steps = ") << steps << endl; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::PRE_RANGE>(current_period)); out << F("VCSEL PRE-RANGE pulse period = ") << current_period << endl; CHECK_OK(tof.get_vcsel_pulse_period<VcselPeriodType::FINAL_RANGE>(current_period)); out << F("VCSEL FINAL-RANGE pulse period = ") << current_period << endl; CHECK_OK(tof.get_signal_rate_limit(rate)); out << F("Signal rate limit = ") << rate << endl; CHECK_OK(tof.get_measurement_timing_budget(budget)); out << F("Measurement timing budget = ") << budget << F("us") << endl; SequenceStepsTimeout timeouts; CHECK_OK(tof.get_sequence_steps_timeout(timeouts)); out << F("Timeouts for each step = ") << timeouts << endl; // Start continuous ranging CHECK_OK(tof.start_continuous_ranging(1000U)); while (true) { time::delay_ms(995U); // Read continuous ranges now uint16_t range = 0; if (tof.await_continuous_range(range)) out << F("Range = ") << dec << range << F("mm") << endl; display_status(out, tof); } } <|endoftext|>
<commit_before> // Copyright (c) 2014 Quanta Research Cambridge, Inc. // 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 <MmRequestProxy.h> #include <MmIndicationWrapper.h> #include <MmDebugIndicationWrapper.h> #include <MmDebugRequestProxy.h> #include <DmaConfigProxy.h> #include <GeneratedTypes.h> //#include <DmaIndicationWrapper.h> #include <StdDmaIndication.h> #include <stdio.h> #include <sys/mman.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #include <errno.h> #include <math.h> // frexp(), fabs() #include <assert.h> #include "portalmat.h" #include "mnist.h" static int verbose = 0; class SigmoidIndication; class MmIndication; class MmDebugIndication; RbmRequestProxy *rbmdevice = 0; MmRequestProxy *mmdevice = 0; MmDebugRequestProxy *mmdebug = 0; SigmoidIndication *sigmoidindication = 0; SigmoidRequestProxy *sigmoiddevice = 0; TimerRequestProxy *timerdevice = 0; MmIndication *mmdeviceIndication = 0; MmDebugIndication *mmDebugIndication = 0; TimerIndication *timerdeviceIndication = 0; DmaConfigProxy *dma = 0; DmaIndicationWrapper *dmaIndication = 0; long dotprod = 0; void dump(const char *prefix, char *buf, size_t len) { fprintf(stderr, "%s ", prefix); for (int i = 0; i < (len > 64 ? 64 : len) ; i++) { fprintf(stderr, "%02x", (unsigned char)buf[i]); if (i % 4 == 3) fprintf(stderr, " "); } fprintf(stderr, "\n"); } void *dbgThread(void *) { while (1) { sleep(2); if (dma) { dma->getStateDbg(ChannelType_Read); } if (mmdebug) { fprintf(stderr, "Calling mmdebug->debug()\n"); mmdebug->debug(); } } return 0; } int main(int argc, const char **argv) { unsigned int srcGen = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal); mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal); mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal); mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal); timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal); timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal); dma = new DmaConfigProxy(IfcNames_DmaConfigPortal); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal); if(sem_init(&mul_sem, 1, 0)){ fprintf(stderr, "failed to init mul_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } pthread_t dbgtid; fprintf(stderr, "creating debug thread\n"); if(pthread_create(&dbgtid, NULL, dbgThread, NULL)){ fprintf(stderr, "error creating debug thread\n"); exit(1); } matAllocator = new PortalMatAllocator(dma); #define LARGE_MAT #ifdef LARGE_MAT int A = 32; int B = 16; if (argc > 1) { B = strtoul(argv[1], 0, 0); A = 2*B; } cv::Mat m1(A,B,CV_32F); cv::Mat m2(B,A,CV_32F); int v = 0; for(int a = 0; a < A; a++){ for(int b = 0; b < B; b++){ m2.at<float>(b,a) = v+(A*B);; m1.at<float>(a,b) = v++; } } #else cv::Mat m1 = (cv::Mat_<float>(4,8) << 11,12,13,14,15,16,17,18, 21,22,23,24,25,26,27,28, 31,32,33,34,35,36,37,38, 41,42,43,44,45,46,47,48 ); cv::Mat m2 = (cv::Mat_<float>(8,4) << 51,62,53,54, 55,56,57,58, 61,62,63,64, 65,66,67,68, 71,72,73,74, 75,76,77,78, 81,82,83,84, 85,86,87,88 ); #endif cv::Mat m3 = m1 * m2; //dumpMatF<int>("m1", "%08x", m1, stdout); //dumpMatF<int>("m2", "%08x", m2, stdout); fflush(stdout); PortalMat pm1(m1); PortalMat pm2t(m2.t()); PortalMat pm3; start_timer(0); pm3.multf(pm1, pm2t, mmdeviceIndication); uint64_t hw_cycles = lap_timer(0); uint64_t read_beats = dma->show_mem_stats(ChannelType_Read); uint64_t write_beats = dma->show_mem_stats(ChannelType_Write); float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt; float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt; fprintf(stderr, "memory read beats %ld utilization (beats/cycle): %f\n", read_beats, read_util); fprintf(stderr, "memory write beats %ld utilization (beats/cycle): %f\n", write_beats, write_util); if (0) { dumpMat<float>("pm1 * pm2", "%5.1f", pm3); dumpMat<float>("m1 * m2", "%5.1f", m3); } bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>()); //dumpMat<int>("pm3", "%08x", pm3); fprintf(stderr, "eq=%d\n", eq); //device->finish(); exit(!eq); } <commit_msg>use PortalMat::compare and increase LARGE_MAT size on non-bluesim platforms<commit_after> // Copyright (c) 2014 Quanta Research Cambridge, Inc. // 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 <MmRequestProxy.h> #include <MmIndicationWrapper.h> #include <MmDebugIndicationWrapper.h> #include <MmDebugRequestProxy.h> #include <DmaConfigProxy.h> #include <GeneratedTypes.h> //#include <DmaIndicationWrapper.h> #include <StdDmaIndication.h> #include <stdio.h> #include <sys/mman.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <semaphore.h> #include <pthread.h> #include <errno.h> #include <math.h> // frexp(), fabs() #include <assert.h> #include "portalmat.h" #include "mnist.h" static int verbose = 0; class SigmoidIndication; class MmIndication; class MmDebugIndication; RbmRequestProxy *rbmdevice = 0; MmRequestProxy *mmdevice = 0; MmDebugRequestProxy *mmdebug = 0; SigmoidIndication *sigmoidindication = 0; SigmoidRequestProxy *sigmoiddevice = 0; TimerRequestProxy *timerdevice = 0; MmIndication *mmdeviceIndication = 0; MmDebugIndication *mmDebugIndication = 0; TimerIndication *timerdeviceIndication = 0; DmaConfigProxy *dma = 0; DmaIndicationWrapper *dmaIndication = 0; long dotprod = 0; void dump(const char *prefix, char *buf, size_t len) { fprintf(stderr, "%s ", prefix); for (int i = 0; i < (len > 64 ? 64 : len) ; i++) { fprintf(stderr, "%02x", (unsigned char)buf[i]); if (i % 4 == 3) fprintf(stderr, " "); } fprintf(stderr, "\n"); } void *dbgThread(void *) { while (1) { sleep(2); if (dma) { dma->getStateDbg(ChannelType_Read); } if (mmdebug) { fprintf(stderr, "Calling mmdebug->debug()\n"); mmdebug->debug(); } } return 0; } int main(int argc, const char **argv) { unsigned int srcGen = 0; fprintf(stderr, "%s %s\n", __DATE__, __TIME__); mmdevice = new MmRequestProxy(IfcNames_MmRequestPortal); mmdebug = new MmDebugRequestProxy(IfcNames_MmDebugRequestPortal); mmdeviceIndication = new MmIndication(IfcNames_MmIndicationPortal); mmDebugIndication = new MmDebugIndication(IfcNames_MmDebugIndicationPortal); timerdevice = new TimerRequestProxy(IfcNames_TimerRequestPortal); timerdeviceIndication = new TimerIndication(IfcNames_TimerIndicationPortal); dma = new DmaConfigProxy(IfcNames_DmaConfigPortal); dmaIndication = new DmaIndication(dma, IfcNames_DmaIndicationPortal); if(sem_init(&mul_sem, 1, 0)){ fprintf(stderr, "failed to init mul_sem\n"); return -1; } pthread_t tid; fprintf(stderr, "creating exec thread\n"); if(pthread_create(&tid, NULL, portalExec, NULL)){ fprintf(stderr, "error creating exec thread\n"); exit(1); } pthread_t dbgtid; fprintf(stderr, "creating debug thread\n"); if(pthread_create(&dbgtid, NULL, dbgThread, NULL)){ fprintf(stderr, "error creating debug thread\n"); exit(1); } matAllocator = new PortalMatAllocator(dma); #define LARGE_MAT #ifdef LARGE_MAT #ifdef BSIM int A = 32; int B = 16; #else int A = 512; int B = 256; #endif if (argc > 1) { B = strtoul(argv[1], 0, 0); A = 2*B; } cv::Mat m1(A,B,CV_32F); cv::Mat m2(B,A,CV_32F); int v = 0; for(int a = 0; a < A; a++){ for(int b = 0; b < B; b++){ m2.at<float>(b,a) = v+(A*B);; m1.at<float>(a,b) = v++; } } #else cv::Mat m1 = (cv::Mat_<float>(4,8) << 11,12,13,14,15,16,17,18, 21,22,23,24,25,26,27,28, 31,32,33,34,35,36,37,38, 41,42,43,44,45,46,47,48 ); cv::Mat m2 = (cv::Mat_<float>(8,4) << 51,62,53,54, 55,56,57,58, 61,62,63,64, 65,66,67,68, 71,72,73,74, 75,76,77,78, 81,82,83,84, 85,86,87,88 ); #endif cv::Mat m3 = m1 * m2; //dumpMatF<int>("m1", "%08x", m1, stdout); //dumpMatF<int>("m2", "%08x", m2, stdout); fflush(stdout); PortalMat pm1(m1); PortalMat pm2t(m2.t()); PortalMat pm3; start_timer(0); pm3.multf(pm1, pm2t, mmdeviceIndication); uint64_t hw_cycles = lap_timer(0); uint64_t read_beats = dma->show_mem_stats(ChannelType_Read); uint64_t write_beats = dma->show_mem_stats(ChannelType_Write); float read_util = (float)read_beats/(float)mmdeviceIndication->ccnt; float write_util = (float)write_beats/(float)mmdeviceIndication->ccnt; fprintf(stderr, "memory read beats %ld utilization (beats/cycle): %f\n", read_beats, read_util); fprintf(stderr, "memory write beats %ld utilization (beats/cycle): %f\n", write_beats, write_util); if (0) { dumpMat<float>("pm1 * pm2", "%5.1f", pm3); dumpMat<float>("m1 * m2", "%5.1f", m3); } //bool eq = std::equal(m3.begin<float>(), m3.end<float>(), pm3.begin<float>()); bool eq = pm3.compare(m3); //dumpMat<int>("pm3", "%08x", pm3); fprintf(stderr, "eq=%d\n", eq); //device->finish(); exit(!eq); } <|endoftext|>
<commit_before>/* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "make_random_string.hh" #include "schema.hh" #include "keys.hh" #include "streamed_mutation.hh" #include "mutation.hh" #include "schema_builder.hh" #include "streamed_mutation.hh" // Helper for working with the following table: // // CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck)); // class simple_schema { schema_ptr _s; api::timestamp_type _timestamp = api::min_timestamp; const column_definition& _v_def; private: api::timestamp_type new_timestamp() { return _timestamp++; } public: simple_schema() : _s(schema_builder("ks", "cf") .with_column("pk", utf8_type, column_kind::partition_key) .with_column("ck", utf8_type, column_kind::clustering_key) .with_column("s1", utf8_type, column_kind::static_column) .with_column("v", utf8_type) .build()) , _v_def(*_s->get_column_definition(to_bytes("v"))) { } clustering_key make_ckey(sstring ck) { return clustering_key::from_single_value(*_s, data_value(ck).serialize()); } // Make a clustering_key which is n-th in some arbitrary sequence of keys clustering_key make_ckey(uint32_t n) { return make_ckey(sprint("ck%010d", n)); } // Make a partition key which is n-th in some arbitrary sequence of keys. // There is no particular order for the keys, they're not in ring order. dht::decorated_key make_pkey(uint32_t n) { return make_pkey(sprint("pk%010d", n)); } dht::decorated_key make_pkey(sstring pk) { auto key = partition_key::from_single_value(*_s, data_value(pk).serialize()); return dht::global_partitioner().decorate_key(*_s, key); } void add_row(mutation& m, const clustering_key& key, sstring v) { m.set_clustered_cell(key, _v_def, atomic_cell::make_live(new_timestamp(), data_value(v).serialize())); } std::pair<sstring, api::timestamp_type> get_value(const clustering_row& row) { auto cell = row.cells().find_cell(_v_def.id); if (!cell) { throw std::runtime_error("cell not found"); } atomic_cell_view ac = cell->as_atomic_cell(); if (!ac.is_live()) { throw std::runtime_error("cell is dead"); } return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value())), ac.timestamp()); } mutation_fragment make_row(const clustering_key& key, sstring v) { auto row = clustering_row(key); row.cells().apply(*_s->get_column_definition(to_bytes(sstring("v"))), atomic_cell::make_live(new_timestamp(), data_value(v).serialize())); return mutation_fragment(std::move(row)); } void add_static_row(mutation& m, sstring s1) { m.set_static_cell(to_bytes("s1"), data_value(s1), new_timestamp()); } range_tombstone delete_range(mutation& m, const query::clustering_range& range) { auto rt = make_range_tombstone(range); m.partition().apply_delete(*_s, rt); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range) { auto bv_range = bound_view::from_range(range); range_tombstone rt(bv_range.first, bv_range.second, tombstone(new_timestamp(), gc_clock::now())); return rt; } mutation new_mutation(sstring pk) { return mutation(make_pkey(pk), _s); } schema_ptr schema() { return _s; } // Creates a sequence of keys in ring order std::vector<dht::decorated_key> make_pkeys(int n) { std::vector<dht::decorated_key> keys; for (int i = 0; i < n; ++i) { keys.push_back(make_pkey(i)); } std::sort(keys.begin(), keys.end(), dht::decorated_key::less_comparator(_s)); return keys; } }; <commit_msg>tests: simple_schema: Introduce make_ckeys()<commit_after>/* * Copyright (C) 2017 ScyllaDB * * Modified by ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>. */ #pragma once #include "make_random_string.hh" #include "schema.hh" #include "keys.hh" #include "streamed_mutation.hh" #include "mutation.hh" #include "schema_builder.hh" #include "streamed_mutation.hh" // Helper for working with the following table: // // CREATE TABLE ks.cf (pk text, ck text, v text, s1 text static, PRIMARY KEY (pk, ck)); // class simple_schema { schema_ptr _s; api::timestamp_type _timestamp = api::min_timestamp; const column_definition& _v_def; private: api::timestamp_type new_timestamp() { return _timestamp++; } public: simple_schema() : _s(schema_builder("ks", "cf") .with_column("pk", utf8_type, column_kind::partition_key) .with_column("ck", utf8_type, column_kind::clustering_key) .with_column("s1", utf8_type, column_kind::static_column) .with_column("v", utf8_type) .build()) , _v_def(*_s->get_column_definition(to_bytes("v"))) { } clustering_key make_ckey(sstring ck) { return clustering_key::from_single_value(*_s, data_value(ck).serialize()); } // Make a clustering_key which is n-th in some arbitrary sequence of keys clustering_key make_ckey(uint32_t n) { return make_ckey(sprint("ck%010d", n)); } // Make a partition key which is n-th in some arbitrary sequence of keys. // There is no particular order for the keys, they're not in ring order. dht::decorated_key make_pkey(uint32_t n) { return make_pkey(sprint("pk%010d", n)); } dht::decorated_key make_pkey(sstring pk) { auto key = partition_key::from_single_value(*_s, data_value(pk).serialize()); return dht::global_partitioner().decorate_key(*_s, key); } void add_row(mutation& m, const clustering_key& key, sstring v) { m.set_clustered_cell(key, _v_def, atomic_cell::make_live(new_timestamp(), data_value(v).serialize())); } std::pair<sstring, api::timestamp_type> get_value(const clustering_row& row) { auto cell = row.cells().find_cell(_v_def.id); if (!cell) { throw std::runtime_error("cell not found"); } atomic_cell_view ac = cell->as_atomic_cell(); if (!ac.is_live()) { throw std::runtime_error("cell is dead"); } return std::make_pair(value_cast<sstring>(utf8_type->deserialize(ac.value())), ac.timestamp()); } mutation_fragment make_row(const clustering_key& key, sstring v) { auto row = clustering_row(key); row.cells().apply(*_s->get_column_definition(to_bytes(sstring("v"))), atomic_cell::make_live(new_timestamp(), data_value(v).serialize())); return mutation_fragment(std::move(row)); } void add_static_row(mutation& m, sstring s1) { m.set_static_cell(to_bytes("s1"), data_value(s1), new_timestamp()); } range_tombstone delete_range(mutation& m, const query::clustering_range& range) { auto rt = make_range_tombstone(range); m.partition().apply_delete(*_s, rt); return rt; } range_tombstone make_range_tombstone(const query::clustering_range& range) { auto bv_range = bound_view::from_range(range); range_tombstone rt(bv_range.first, bv_range.second, tombstone(new_timestamp(), gc_clock::now())); return rt; } mutation new_mutation(sstring pk) { return mutation(make_pkey(pk), _s); } schema_ptr schema() { return _s; } // Creates a sequence of keys in ring order std::vector<dht::decorated_key> make_pkeys(int n) { std::vector<dht::decorated_key> keys; for (int i = 0; i < n; ++i) { keys.push_back(make_pkey(i)); } std::sort(keys.begin(), keys.end(), dht::decorated_key::less_comparator(_s)); return keys; } // Returns n clustering keys in their natural order std::vector<clustering_key> make_ckeys(int n) { std::vector<clustering_key> keys; for (int i = 0; i < n; ++i) { keys.push_back(make_ckey(i)); } return keys; } }; <|endoftext|>
<commit_before> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // appleseed.renderer headers. #include "renderer/modeling/project/project.h" #include "renderer/modeling/project/projectfilereader.h" #include "renderer/modeling/project/projectfilewriter.h" // appleseed.foundation headers. #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/test.h" #include "foundation/utility/testutils.h" // Boost headers #include "boost/filesystem.hpp" // Standard headers #include <exception> using namespace foundation; using namespace renderer; namespace bf = boost::filesystem; TEST_SUITE(Renderer_Modeling_Project_ProjectFileReader) { TEST_CASE(ParsingOfConfigurationBlocks) { ProjectFileReader reader; auto_release_ptr<Project> project = reader.read( "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed", "../../../schemas/project.xsd"); // path relative to input file ASSERT_NEQ(0, project.get()); const bool success = ProjectFileWriter::write( project.ref(), "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed", ProjectFileWriter::OmitHeaderComment); ASSERT_TRUE(success); const bool identical = compare_text_files( "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed", "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed"); EXPECT_TRUE(identical); } TEST_CASE(ReadValidPackedProject) { const char* project = "unit tests/inputs/test_packed_project_valid.appleseedz"; const char* project_unpacked = "unit tests/inputs/test_packed_project_valid.appleseedz.unpacked"; try { ProjectFileReader reader; auto_release_ptr<Project> project_success = reader.read( project, "../../../../schemas/project.xsd"); // path relative to input file EXPECT_NEQ(0, project_success.get()); bf::remove_all(bf::path(project_unpacked)); } catch (std::exception e) { bf::remove_all(bf::path(project_unpacked)); throw e; } } // Test waits for a brilliant solution of how to invoke it without emitting error message // TEST_CASE(ReadInvalidPackedProject) // { // const char* project = "unit tests/inputs/test_packed_project_invalid.appleseedz"; // const char* project_unpacked = "unit tests/inputs/test_packed_project_invalid.appleseedz.unpacked"; // try // { // ProjectFileReader reader; // auto_release_ptr<Project> project_fail = // reader.read( // project, // "../../../../schemas/project.xsd"); // path relative to input file // EXPECT_EQ(0, project_fail.get()); // bf::remove_all(bf::path(project_unpacked)); // } // catch (std::exception e) // { // bf::remove_all(bf::path(project_unpacked)); // throw e; // } // } } <commit_msg>Change unpacked directory for test<commit_after> // // This source file is part of appleseed. // Visit http://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited // Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // appleseed.renderer headers. #include "renderer/modeling/project/project.h" #include "renderer/modeling/project/projectfilereader.h" #include "renderer/modeling/project/projectfilewriter.h" // appleseed.foundation headers. #include "foundation/utility/autoreleaseptr.h" #include "foundation/utility/test.h" #include "foundation/utility/testutils.h" // Boost headers #include "boost/filesystem.hpp" // Standard headers #include <exception> using namespace foundation; using namespace renderer; namespace bf = boost::filesystem; TEST_SUITE(Renderer_Modeling_Project_ProjectFileReader) { TEST_CASE(ParsingOfConfigurationBlocks) { ProjectFileReader reader; auto_release_ptr<Project> project = reader.read( "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed", "../../../schemas/project.xsd"); // path relative to input file ASSERT_NEQ(0, project.get()); const bool success = ProjectFileWriter::write( project.ref(), "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed", ProjectFileWriter::OmitHeaderComment); ASSERT_TRUE(success); const bool identical = compare_text_files( "unit tests/inputs/test_projectfilereader_configurationblocks.appleseed", "unit tests/outputs/test_projectfilereader_configurationblocks.appleseed"); EXPECT_TRUE(identical); } TEST_CASE(ReadValidPackedProject) { const char* project = "unit tests/inputs/test_packed_project_valid.appleseedz"; const char* project_unpacked = "unit tests/inputs/test_packed_project_valid.unpacked"; try { ProjectFileReader reader; auto_release_ptr<Project> project_success = reader.read( project, "../../../../schemas/project.xsd"); // path relative to input file EXPECT_NEQ(0, project_success.get()); bf::remove_all(bf::path(project_unpacked)); } catch (std::exception e) { bf::remove_all(bf::path(project_unpacked)); throw e; } } // Test waits for a brilliant solution of how to invoke it without emitting error message // TEST_CASE(ReadInvalidPackedProject) // { // const char* project = "unit tests/inputs/test_packed_project_invalid.appleseedz"; // const char* project_unpacked = "unit tests/inputs/test_packed_project_invalid.appleseedz.unpacked"; // try // { // ProjectFileReader reader; // auto_release_ptr<Project> project_fail = // reader.read( // project, // "../../../../schemas/project.xsd"); // path relative to input file // EXPECT_EQ(0, project_fail.get()); // bf::remove_all(bf::path(project_unpacked)); // } // catch (std::exception e) // { // bf::remove_all(bf::path(project_unpacked)); // throw e; // } // } } <|endoftext|>