text
stringlengths
54
60.6k
<commit_before>#include <algorithm> #include <iostream> #include "../shared/util.h" #include "../../include/ctf.hpp" tCTF_ScheduleBase* global_schedule; template<typename dtype> void tCTF_Schedule<dtype>::record() { global_schedule = this; } template<typename dtype> inline void tCTF_Schedule<dtype>::schedule_op_successors(tCTF_TensorOperation<dtype>* op) { assert(op->dependency_left == 0); typename std::vector<tCTF_TensorOperation<dtype>* >::iterator it; for (it=op->successors.begin(); it!=op->successors.end(); it++) { (*it)->dependency_left--; assert((*it)->dependency_left >= 0); if ((*it)->dependency_left == 0) { ready_tasks.push_back(*it); } } } template<typename dtype> bool tensor_op_cost_greater(tCTF_TensorOperation<dtype>* A, tCTF_TensorOperation<dtype>* B) { return A->estimate_cost() > B->estimate_cost(); //return A->successors.size() > B->successors.size(); } /** * \brief Data structure containing what each partition is going to do. */ template<typename dtype> struct tCTF_PartitionOps { int color; tCTF_World<dtype>* world; std::vector<tCTF_TensorOperation<dtype>*> ops; // operations to execute std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> local_tensors; // all local tensors used std::map<tCTF_Tensor<dtype>*, tCTF_Tensor<dtype>*> remap; // mapping from global tensor -> local tensor std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> global_tensors; // all referenced tensors stored as global tensors std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> output_tensors; // tensors to be written back out, stored as global tensors }; template<typename dtype> tCTF_ScheduleTimer tCTF_Schedule<dtype>::partition_and_execute() { tCTF_ScheduleTimer schedule_timer; schedule_timer.total_time = MPI_Wtime(); int rank, size; MPI_Comm_rank(world->comm, &rank); MPI_Comm_size(world->comm, &size); // Partition operations into worlds, and do split std::vector<tCTF_PartitionOps<dtype> > comm_ops; // operations for each subcomm int max_colors = size <= ready_tasks.size()? size : ready_tasks.size(); if (partitions > 0 && max_colors > partitions) { max_colors = partitions; } // Sort tasks by descending runtime std::sort(ready_tasks.begin(), ready_tasks.end(), tensor_op_cost_greater<dtype>); // Maximum load imbalance algorithm: // Keep attempting to add the next available task until either reached max_colors // (user-specified parameter or number of nodes) or the next added node would // require less than one processor's worth of compute int starting_task; int max_starting_task = 0; int max_num_tasks = 0; int max_cost = 0; // Try to find the longest sequence of tasks that aren't too imbalanced for (int starting_task=0; starting_task<max_colors; starting_task++) { long_int sum_cost = 0; long_int min_cost = 0; int num_tasks = 0; for (int i=starting_task; i<max_colors; i++) { long_int this_cost = ready_tasks[i]->estimate_cost(); if (min_cost == 0 || this_cost < min_cost) { min_cost = this_cost; } if (min_cost < (this_cost + sum_cost) / size) { break; } else { num_tasks = i - starting_task + 1; sum_cost += this_cost; } } if (num_tasks > max_num_tasks) { max_num_tasks = num_tasks; max_starting_task = starting_task; max_cost = sum_cost; } } // Do processor division according to estimated cost // Algorithm: divide sum_cost into size blocks, and each processor samples the // middle of its block to determine which task it works on int color_sample_point = (max_cost / size) * rank + (max_cost / size / 2); int my_color = 0; for (int i=0; i<max_num_tasks; i++) { my_color = i; if (color_sample_point < ready_tasks[max_starting_task+i]->estimate_cost()) { break; } else { color_sample_point -= ready_tasks[max_starting_task+i]->estimate_cost(); } } MPI_Comm my_comm; MPI_Comm_split(world->comm, my_color, rank, &my_comm); if (rank == 0) { std::cout << "Maxparts " << max_colors << ", start " << max_starting_task << ", tasks " << max_num_tasks << " // "; for (auto it : ready_tasks) { std::cout << it->name() << "(" << it->estimate_cost() << ") "; } std::cout << std::endl; } for (int color=0; color<max_num_tasks; color++) { comm_ops.push_back(tCTF_PartitionOps<dtype>()); comm_ops[color].color = color; if (color == my_color) { comm_ops[color].world = new tCTF_World<dtype>(my_comm); } else { comm_ops[color].world = NULL; } comm_ops[color].ops.push_back(ready_tasks[max_starting_task + color]); ready_tasks.erase(ready_tasks.begin() + max_starting_task + color); } // Initialize local data structures for (auto &comm_op : comm_ops) { // gather required tensors for (auto &op : comm_op.ops) { assert(op != NULL); op->get_inputs(&comm_op.global_tensors); op->get_outputs(&comm_op.global_tensors); op->get_outputs(&comm_op.output_tensors); } } // Create and communicate tensors to subworlds schedule_timer.comm_down_time = MPI_Wtime(); for (auto &comm_op : comm_ops) { for (auto &global_tensor : comm_op.global_tensors) { tCTF_Tensor<dtype>* local_clone; if (comm_op.world != NULL) { local_clone = new tCTF_Tensor<dtype>(*global_tensor, *comm_op.world); } else { local_clone = NULL; } comm_op.local_tensors.insert(local_clone); comm_op.remap[global_tensor] = local_clone; global_tensor->add_to_subworld(local_clone, 1, 0); } for (auto &output_tensor : comm_op.output_tensors) { assert(comm_op.remap.find(output_tensor) != comm_op.remap.end()); } } schedule_timer.comm_down_time = MPI_Wtime() - schedule_timer.comm_down_time; // Run my tasks MPI_Barrier(world->comm); schedule_timer.exec_time = MPI_Wtime(); if (comm_ops.size() > my_color) { for (auto &op : comm_ops[my_color].ops) { op->execute(&comm_ops[my_color].remap); } } MPI_Barrier(world->comm); schedule_timer.exec_time = MPI_Wtime() - schedule_timer.exec_time; // Communicate results back into global schedule_timer.comm_up_time = MPI_Wtime(); for (auto &comm_op : comm_ops) { for (auto &output_tensor : comm_op.output_tensors) { output_tensor->add_from_subworld(comm_op.remap[output_tensor], 1, 0); } } schedule_timer.comm_up_time = MPI_Wtime() - schedule_timer.comm_up_time; // Clean up local tensors & world if (comm_ops.size() > my_color) { for (auto &local_tensor : comm_ops[my_color].local_tensors) { delete local_tensor; } delete comm_ops[my_color].world; } // Update ready tasks for (auto &comm_op : comm_ops) { for (auto &op : comm_op.ops) { schedule_op_successors(op); } } schedule_timer.total_time = MPI_Wtime() - schedule_timer.total_time; return schedule_timer; } /* // The dead simple scheduler template<typename dtype> void tCTF_Schedule<dtype>::partition_and_execute() { while (ready_tasks.size() >= 1) { tCTF_TensorOperation<dtype>* op = ready_tasks.front(); ready_tasks.pop_front(); op->execute(); schedule_op_successors(op); } } */ template<typename dtype> tCTF_ScheduleTimer tCTF_Schedule<dtype>::execute() { tCTF_ScheduleTimer schedule_timer; global_schedule = NULL; typename std::deque<tCTF_TensorOperation<dtype>*>::iterator it; // Initialize all tasks & initial ready queue for (it = steps_original.begin(); it != steps_original.end(); it++) { (*it)->dependency_left = (*it)->dependency_count; } ready_tasks = root_tasks; // Preprocess dummy operations while (!ready_tasks.empty()) { if (ready_tasks.front()->is_dummy()) { schedule_op_successors(ready_tasks.front()); ready_tasks.pop_front(); } else { break; } } while (!ready_tasks.empty()) { int rank; MPI_Comm_rank(world->comm, &rank); schedule_timer += partition_and_execute(); } return schedule_timer; } template<typename dtype> void tCTF_Schedule<dtype>::add_operation_typed(tCTF_TensorOperation<dtype>* op) { steps_original.push_back(op); std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> op_lhs_set; op->get_outputs(&op_lhs_set); assert(op_lhs_set.size() == 1); // limited case to make this a bit easier tCTF_Tensor<dtype>* op_lhs = *op_lhs_set.begin(); std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> op_deps; op->get_inputs(&op_deps); typename std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>::iterator deps_iter; for (deps_iter = op_deps.begin(); deps_iter != op_deps.end(); deps_iter++) { tCTF_Tensor<dtype>* dep = *deps_iter; typename std::map<tCTF_Tensor<dtype>*, tCTF_TensorOperation<dtype>*>::iterator dep_loc = latest_write.find(dep); tCTF_TensorOperation<dtype>* dep_op; if (dep_loc != latest_write.end()) { dep_op = dep_loc->second; } else { // create dummy operation to serve as a root dependency // TODO: this can be optimized away dep_op = new tCTF_TensorOperation<dtype>(TENSOR_OP_NONE, NULL, NULL); latest_write[dep] = dep_op; root_tasks.push_back(dep_op); steps_original.push_back(dep_op); } dep_op->successors.push_back(op); dep_op->reads.push_back(op); op->dependency_count++; } typename std::map<tCTF_Tensor<dtype>*, tCTF_TensorOperation<dtype>*>::iterator prev_loc = latest_write.find(op_lhs); if (prev_loc != latest_write.end()) { // if there was a previous write, add its dependencies to my dependencies // to ensure that I don't clobber values that a ready dependency needs std::vector<tCTF_TensorOperation<dtype>*>* prev_reads = &(prev_loc->second->reads); typename std::vector<tCTF_TensorOperation<dtype>*>::iterator prev_iter; for (prev_iter = prev_reads->begin(); prev_iter != prev_reads->end(); prev_iter++) { if (*prev_iter != op) { (*prev_iter)->successors.push_back(op); op->dependency_count++; } } } latest_write[op_lhs] = op; } template<typename dtype> void tCTF_Schedule<dtype>::add_operation(tCTF_TensorOperationBase* op) { tCTF_TensorOperation<dtype>* op_typed = dynamic_cast<tCTF_TensorOperation<dtype>* >(op); assert(op_typed != NULL); add_operation_typed(op_typed); } template<typename dtype> void tCTF_TensorOperation<dtype>::execute(std::map<tCTF_Tensor<dtype>*, tCTF_Tensor<dtype>*>* remap) { assert(global_schedule == NULL); // ensure this isn't going into a record() tCTF_Idx_Tensor<dtype>* remapped_lhs = lhs; const tCTF_Term<dtype>* remapped_rhs = rhs; if (remap != NULL) { remapped_lhs = dynamic_cast<tCTF_Idx_Tensor<dtype>* >(remapped_lhs->clone(remap)); assert(remapped_lhs != NULL); remapped_rhs = remapped_rhs->clone(remap); } switch (op) { case TENSOR_OP_NONE: break; case TENSOR_OP_SET: *remapped_lhs = *remapped_rhs; break; case TENSOR_OP_SUM: *remapped_lhs += *remapped_rhs; break; case TENSOR_OP_SUBTRACT: *remapped_lhs -= *remapped_rhs; break; case TENSOR_OP_MULTIPLY: *remapped_lhs *= *remapped_rhs; break; default: std::cerr << "tCTF_TensorOperation::execute(): unexpected op: " << op << std::endl; assert(false); } } template<typename dtype> void tCTF_TensorOperation<dtype>::get_outputs(std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>* outputs_set) const { assert(lhs->parent); assert(outputs_set != NULL); outputs_set->insert(lhs->parent); } template<typename dtype> void tCTF_TensorOperation<dtype>::get_inputs(std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>* inputs_set) const { assert(this != NULL); assert(rhs != NULL); assert(inputs_set != NULL); rhs->get_inputs(inputs_set); switch (op) { case TENSOR_OP_SET: break; case TENSOR_OP_SUM: case TENSOR_OP_SUBTRACT: case TENSOR_OP_MULTIPLY: assert(lhs != NULL && lhs->parent != NULL); inputs_set->insert(lhs->parent); break; default: std::cerr << "tCTF_TensorOperation::get_inputs(): unexpected op: " << op << std::endl; assert(false); } } template<typename dtype> long_int tCTF_TensorOperation<dtype>::estimate_cost() { if (cached_estimated_cost == 0) { assert(rhs != NULL); assert(lhs != NULL); cached_estimated_cost = rhs->estimate_cost(*lhs); assert(cached_estimated_cost > 0); } return cached_estimated_cost; } template class tCTF_Schedule<double>; #ifdef CTF_COMPLEX template class tCTF_Schedule< std::complex<double> >; #endif <commit_msg>yet more asserts<commit_after>#include <algorithm> #include <iostream> #include "../shared/util.h" #include "../../include/ctf.hpp" tCTF_ScheduleBase* global_schedule; template<typename dtype> void tCTF_Schedule<dtype>::record() { global_schedule = this; } template<typename dtype> inline void tCTF_Schedule<dtype>::schedule_op_successors(tCTF_TensorOperation<dtype>* op) { assert(op->dependency_left == 0); typename std::vector<tCTF_TensorOperation<dtype>* >::iterator it; for (it=op->successors.begin(); it!=op->successors.end(); it++) { (*it)->dependency_left--; assert((*it)->dependency_left >= 0); if ((*it)->dependency_left == 0) { ready_tasks.push_back(*it); } } } template<typename dtype> bool tensor_op_cost_greater(tCTF_TensorOperation<dtype>* A, tCTF_TensorOperation<dtype>* B) { return A->estimate_cost() > B->estimate_cost(); //return A->successors.size() > B->successors.size(); } /** * \brief Data structure containing what each partition is going to do. */ template<typename dtype> struct tCTF_PartitionOps { int color; tCTF_World<dtype>* world; std::vector<tCTF_TensorOperation<dtype>*> ops; // operations to execute std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> local_tensors; // all local tensors used std::map<tCTF_Tensor<dtype>*, tCTF_Tensor<dtype>*> remap; // mapping from global tensor -> local tensor std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> global_tensors; // all referenced tensors stored as global tensors std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> output_tensors; // tensors to be written back out, stored as global tensors }; template<typename dtype> tCTF_ScheduleTimer tCTF_Schedule<dtype>::partition_and_execute() { tCTF_ScheduleTimer schedule_timer; schedule_timer.total_time = MPI_Wtime(); int rank, size; MPI_Comm_rank(world->comm, &rank); MPI_Comm_size(world->comm, &size); // Partition operations into worlds, and do split std::vector<tCTF_PartitionOps<dtype> > comm_ops; // operations for each subcomm int max_colors = size <= ready_tasks.size()? size : ready_tasks.size(); if (partitions > 0 && max_colors > partitions) { max_colors = partitions; } // Sort tasks by descending runtime std::sort(ready_tasks.begin(), ready_tasks.end(), tensor_op_cost_greater<dtype>); // Maximum load imbalance algorithm: // Keep attempting to add the next available task until either reached max_colors // (user-specified parameter or number of nodes) or the next added node would // require less than one processor's worth of compute int starting_task; int max_starting_task = 0; int max_num_tasks = 0; int max_cost = 0; // Try to find the longest sequence of tasks that aren't too imbalanced for (int starting_task=0; starting_task<max_colors; starting_task++) { long_int sum_cost = 0; long_int min_cost = 0; int num_tasks = 0; for (int i=starting_task; i<max_colors; i++) { long_int this_cost = ready_tasks[i]->estimate_cost(); if (min_cost == 0 || this_cost < min_cost) { min_cost = this_cost; } if (min_cost < (this_cost + sum_cost) / size) { break; } else { num_tasks = i - starting_task + 1; sum_cost += this_cost; } } if (num_tasks > max_num_tasks) { max_num_tasks = num_tasks; max_starting_task = starting_task; max_cost = sum_cost; } } // Do processor division according to estimated cost // Algorithm: divide sum_cost into size blocks, and each processor samples the // middle of its block to determine which task it works on int color_sample_point = (max_cost / size) * rank + (max_cost / size / 2); int my_color = 0; for (int i=0; i<max_num_tasks; i++) { my_color = i; if (color_sample_point < ready_tasks[max_starting_task+i]->estimate_cost()) { break; } else { color_sample_point -= ready_tasks[max_starting_task+i]->estimate_cost(); } } MPI_Comm my_comm; MPI_Comm_split(world->comm, my_color, rank, &my_comm); if (rank == 0) { std::cout << "Maxparts " << max_colors << ", start " << max_starting_task << ", tasks " << max_num_tasks << " // "; for (auto it : ready_tasks) { std::cout << it->name() << "(" << it->estimate_cost() << ") "; } std::cout << std::endl; } for (int color=0; color<max_num_tasks; color++) { comm_ops.push_back(tCTF_PartitionOps<dtype>()); comm_ops[color].color = color; if (color == my_color) { comm_ops[color].world = new tCTF_World<dtype>(my_comm); } else { comm_ops[color].world = NULL; } assert(max_starting_task + color < ready_tasks.size()); comm_ops[color].ops.push_back(ready_tasks[max_starting_task + color]); ready_tasks.erase(ready_tasks.begin() + max_starting_task + color); } // Initialize local data structures for (auto &comm_op : comm_ops) { // gather required tensors for (auto &op : comm_op.ops) { assert(op != NULL); op->get_inputs(&comm_op.global_tensors); op->get_outputs(&comm_op.global_tensors); op->get_outputs(&comm_op.output_tensors); } } // Create and communicate tensors to subworlds schedule_timer.comm_down_time = MPI_Wtime(); for (auto &comm_op : comm_ops) { for (auto &global_tensor : comm_op.global_tensors) { tCTF_Tensor<dtype>* local_clone; if (comm_op.world != NULL) { local_clone = new tCTF_Tensor<dtype>(*global_tensor, *comm_op.world); } else { local_clone = NULL; } comm_op.local_tensors.insert(local_clone); comm_op.remap[global_tensor] = local_clone; global_tensor->add_to_subworld(local_clone, 1, 0); } for (auto &output_tensor : comm_op.output_tensors) { assert(comm_op.remap.find(output_tensor) != comm_op.remap.end()); } } schedule_timer.comm_down_time = MPI_Wtime() - schedule_timer.comm_down_time; // Run my tasks MPI_Barrier(world->comm); schedule_timer.exec_time = MPI_Wtime(); if (comm_ops.size() > my_color) { for (auto &op : comm_ops[my_color].ops) { op->execute(&comm_ops[my_color].remap); } } MPI_Barrier(world->comm); schedule_timer.exec_time = MPI_Wtime() - schedule_timer.exec_time; // Communicate results back into global schedule_timer.comm_up_time = MPI_Wtime(); for (auto &comm_op : comm_ops) { for (auto &output_tensor : comm_op.output_tensors) { output_tensor->add_from_subworld(comm_op.remap[output_tensor], 1, 0); } } schedule_timer.comm_up_time = MPI_Wtime() - schedule_timer.comm_up_time; // Clean up local tensors & world if (comm_ops.size() > my_color) { for (auto &local_tensor : comm_ops[my_color].local_tensors) { delete local_tensor; } delete comm_ops[my_color].world; } // Update ready tasks for (auto &comm_op : comm_ops) { for (auto &op : comm_op.ops) { schedule_op_successors(op); } } schedule_timer.total_time = MPI_Wtime() - schedule_timer.total_time; return schedule_timer; } /* // The dead simple scheduler template<typename dtype> void tCTF_Schedule<dtype>::partition_and_execute() { while (ready_tasks.size() >= 1) { tCTF_TensorOperation<dtype>* op = ready_tasks.front(); ready_tasks.pop_front(); op->execute(); schedule_op_successors(op); } } */ template<typename dtype> tCTF_ScheduleTimer tCTF_Schedule<dtype>::execute() { tCTF_ScheduleTimer schedule_timer; global_schedule = NULL; typename std::deque<tCTF_TensorOperation<dtype>*>::iterator it; // Initialize all tasks & initial ready queue for (it = steps_original.begin(); it != steps_original.end(); it++) { (*it)->dependency_left = (*it)->dependency_count; } ready_tasks = root_tasks; // Preprocess dummy operations while (!ready_tasks.empty()) { if (ready_tasks.front()->is_dummy()) { schedule_op_successors(ready_tasks.front()); ready_tasks.pop_front(); } else { break; } } while (!ready_tasks.empty()) { int rank; MPI_Comm_rank(world->comm, &rank); schedule_timer += partition_and_execute(); } return schedule_timer; } template<typename dtype> void tCTF_Schedule<dtype>::add_operation_typed(tCTF_TensorOperation<dtype>* op) { steps_original.push_back(op); std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> op_lhs_set; op->get_outputs(&op_lhs_set); assert(op_lhs_set.size() == 1); // limited case to make this a bit easier tCTF_Tensor<dtype>* op_lhs = *op_lhs_set.begin(); std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>> op_deps; op->get_inputs(&op_deps); typename std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>::iterator deps_iter; for (deps_iter = op_deps.begin(); deps_iter != op_deps.end(); deps_iter++) { tCTF_Tensor<dtype>* dep = *deps_iter; typename std::map<tCTF_Tensor<dtype>*, tCTF_TensorOperation<dtype>*>::iterator dep_loc = latest_write.find(dep); tCTF_TensorOperation<dtype>* dep_op; if (dep_loc != latest_write.end()) { dep_op = dep_loc->second; } else { // create dummy operation to serve as a root dependency // TODO: this can be optimized away dep_op = new tCTF_TensorOperation<dtype>(TENSOR_OP_NONE, NULL, NULL); latest_write[dep] = dep_op; root_tasks.push_back(dep_op); steps_original.push_back(dep_op); } dep_op->successors.push_back(op); dep_op->reads.push_back(op); op->dependency_count++; } typename std::map<tCTF_Tensor<dtype>*, tCTF_TensorOperation<dtype>*>::iterator prev_loc = latest_write.find(op_lhs); if (prev_loc != latest_write.end()) { // if there was a previous write, add its dependencies to my dependencies // to ensure that I don't clobber values that a ready dependency needs std::vector<tCTF_TensorOperation<dtype>*>* prev_reads = &(prev_loc->second->reads); typename std::vector<tCTF_TensorOperation<dtype>*>::iterator prev_iter; for (prev_iter = prev_reads->begin(); prev_iter != prev_reads->end(); prev_iter++) { if (*prev_iter != op) { (*prev_iter)->successors.push_back(op); op->dependency_count++; } } } latest_write[op_lhs] = op; } template<typename dtype> void tCTF_Schedule<dtype>::add_operation(tCTF_TensorOperationBase* op) { tCTF_TensorOperation<dtype>* op_typed = dynamic_cast<tCTF_TensorOperation<dtype>* >(op); assert(op_typed != NULL); add_operation_typed(op_typed); } template<typename dtype> void tCTF_TensorOperation<dtype>::execute(std::map<tCTF_Tensor<dtype>*, tCTF_Tensor<dtype>*>* remap) { assert(global_schedule == NULL); // ensure this isn't going into a record() tCTF_Idx_Tensor<dtype>* remapped_lhs = lhs; const tCTF_Term<dtype>* remapped_rhs = rhs; if (remap != NULL) { remapped_lhs = dynamic_cast<tCTF_Idx_Tensor<dtype>* >(remapped_lhs->clone(remap)); assert(remapped_lhs != NULL); remapped_rhs = remapped_rhs->clone(remap); } switch (op) { case TENSOR_OP_NONE: break; case TENSOR_OP_SET: *remapped_lhs = *remapped_rhs; break; case TENSOR_OP_SUM: *remapped_lhs += *remapped_rhs; break; case TENSOR_OP_SUBTRACT: *remapped_lhs -= *remapped_rhs; break; case TENSOR_OP_MULTIPLY: *remapped_lhs *= *remapped_rhs; break; default: std::cerr << "tCTF_TensorOperation::execute(): unexpected op: " << op << std::endl; assert(false); } } template<typename dtype> void tCTF_TensorOperation<dtype>::get_outputs(std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>* outputs_set) const { assert(lhs->parent); assert(outputs_set != NULL); outputs_set->insert(lhs->parent); } template<typename dtype> void tCTF_TensorOperation<dtype>::get_inputs(std::set<tCTF_Tensor<dtype>*, tensor_tid_less<dtype>>* inputs_set) const { assert(this != NULL); assert(rhs != NULL); assert(inputs_set != NULL); rhs->get_inputs(inputs_set); switch (op) { case TENSOR_OP_SET: break; case TENSOR_OP_SUM: case TENSOR_OP_SUBTRACT: case TENSOR_OP_MULTIPLY: assert(lhs != NULL && lhs->parent != NULL); inputs_set->insert(lhs->parent); break; default: std::cerr << "tCTF_TensorOperation::get_inputs(): unexpected op: " << op << std::endl; assert(false); } } template<typename dtype> long_int tCTF_TensorOperation<dtype>::estimate_cost() { if (cached_estimated_cost == 0) { assert(rhs != NULL); assert(lhs != NULL); cached_estimated_cost = rhs->estimate_cost(*lhs); assert(cached_estimated_cost > 0); } return cached_estimated_cost; } template class tCTF_Schedule<double>; #ifdef CTF_COMPLEX template class tCTF_Schedule< std::complex<double> >; #endif <|endoftext|>
<commit_before><commit_msg>Add version to window title if version.txt exists<commit_after><|endoftext|>
<commit_before><commit_msg>Updated version number and date.<commit_after><|endoftext|>
<commit_before><commit_msg>NEW removed MPI C++ binding and replaced them by C<commit_after><|endoftext|>
<commit_before><commit_msg>Remove a redundant test.<commit_after><|endoftext|>
<commit_before>// LAF Base Library // Copyright (c) 2001-2016 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/rw_lock.h" // Uncomment this line in case that you want TRACE() lock/unlock // operations. //#define DEBUG_OBJECT_LOCKS #include "base/scoped_lock.h" #include "base/thread.h" namespace base { RWLock::RWLock() : m_write_lock(false) , m_read_locks(0) , m_weak_lock(nullptr) { } RWLock::~RWLock() { ASSERT(!m_write_lock); ASSERT(m_read_locks == 0); ASSERT(m_weak_lock == nullptr); } bool RWLock::lock(LockType lockType, int timeout) { while (timeout >= 0) { { scoped_lock lock(m_mutex); // Check that there is no weak lock if (m_weak_lock) { if (*m_weak_lock == WeakLocked) *m_weak_lock = WeakUnlocking; // Wait some time if (*m_weak_lock == WeakUnlocking) goto go_wait; ASSERT(*m_weak_lock == WeakUnlocked); } switch (lockType) { case ReadLock: // If no body is writting the object... if (!m_write_lock) { // We can read it ++m_read_locks; return true; } break; case WriteLock: // If no body is reading and writting... if (m_read_locks == 0 && !m_write_lock) { // We can start writting the object... m_write_lock = true; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: Locked <%p> to write\n", this); #endif return true; } break; } go_wait:; } if (timeout > 0) { int delay = MIN(100, timeout); timeout -= delay; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: wait 100 msecs for <%p>\n", this); #endif base::this_thread::sleep_for(double(delay) / 1000.0); } else break; } #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: Cannot lock <%p> to %s (has %d read locks and %d write locks)\n", this, (lockType == ReadLock ? "read": "write"), m_read_locks, m_write_lock); #endif return false; } void RWLock::downgradeToRead() { scoped_lock lock(m_mutex); ASSERT(m_read_locks == 0); ASSERT(m_write_lock); m_write_lock = false; m_read_locks = 1; } void RWLock::unlock() { scoped_lock lock(m_mutex); if (m_write_lock) { m_write_lock = false; } else if (m_read_locks > 0) { --m_read_locks; } else { ASSERT(false); } } bool RWLock::weakLock(WeakLock* weak_lock_flag) { scoped_lock lock(m_mutex); if (m_weak_lock || m_write_lock || m_read_locks > 0) return false; m_weak_lock = weak_lock_flag; *m_weak_lock = WeakLocked; return true; } void RWLock::weakUnlock() { ASSERT(m_weak_lock); ASSERT(*m_weak_lock != WeakLock::WeakUnlocked); ASSERT(!m_write_lock); ASSERT(m_read_locks == 0); if (m_weak_lock) { *m_weak_lock = WeakLock::WeakUnlocked; m_weak_lock = nullptr; } } bool RWLock::upgradeToWrite(int timeout) { while (timeout >= 0) { { scoped_lock lock(m_mutex); // Check that there is no weak lock if (m_weak_lock) { if (*m_weak_lock == WeakLocked) *m_weak_lock = WeakUnlocking; // Wait some time if (*m_weak_lock == WeakUnlocking) goto go_wait; ASSERT(*m_weak_lock == WeakUnlocked); } // this only is possible if there are just one reader if (m_read_locks == 1) { ASSERT(!m_write_lock); m_read_locks = 0; m_write_lock = true; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: Locked <%p> to write\n", this); #endif return true; } go_wait:; } if (timeout > 0) { int delay = MIN(100, timeout); timeout -= delay; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: wait 100 msecs for <%p>\n", this); #endif base::this_thread::sleep_for(double(delay) / 1000.0); } else break; } #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: Cannot lock <%p> to write (has %d read locks and %d write locks)\n", this, m_read_locks, m_write_lock); #endif return false; } } // namespace base <commit_msg>Include base/debug.h to use ASSERT() in rw_lock.cpp<commit_after>// LAF Base Library // Copyright (c) 2001-2016 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "base/rw_lock.h" // Uncomment this line in case that you want TRACE() lock/unlock // operations. //#define DEBUG_OBJECT_LOCKS #include "base/debug.h" #include "base/scoped_lock.h" #include "base/thread.h" namespace base { RWLock::RWLock() : m_write_lock(false) , m_read_locks(0) , m_weak_lock(nullptr) { } RWLock::~RWLock() { ASSERT(!m_write_lock); ASSERT(m_read_locks == 0); ASSERT(m_weak_lock == nullptr); } bool RWLock::lock(LockType lockType, int timeout) { while (timeout >= 0) { { scoped_lock lock(m_mutex); // Check that there is no weak lock if (m_weak_lock) { if (*m_weak_lock == WeakLocked) *m_weak_lock = WeakUnlocking; // Wait some time if (*m_weak_lock == WeakUnlocking) goto go_wait; ASSERT(*m_weak_lock == WeakUnlocked); } switch (lockType) { case ReadLock: // If no body is writting the object... if (!m_write_lock) { // We can read it ++m_read_locks; return true; } break; case WriteLock: // If no body is reading and writting... if (m_read_locks == 0 && !m_write_lock) { // We can start writting the object... m_write_lock = true; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: Locked <%p> to write\n", this); #endif return true; } break; } go_wait:; } if (timeout > 0) { int delay = MIN(100, timeout); timeout -= delay; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: wait 100 msecs for <%p>\n", this); #endif base::this_thread::sleep_for(double(delay) / 1000.0); } else break; } #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: lock: Cannot lock <%p> to %s (has %d read locks and %d write locks)\n", this, (lockType == ReadLock ? "read": "write"), m_read_locks, m_write_lock); #endif return false; } void RWLock::downgradeToRead() { scoped_lock lock(m_mutex); ASSERT(m_read_locks == 0); ASSERT(m_write_lock); m_write_lock = false; m_read_locks = 1; } void RWLock::unlock() { scoped_lock lock(m_mutex); if (m_write_lock) { m_write_lock = false; } else if (m_read_locks > 0) { --m_read_locks; } else { ASSERT(false); } } bool RWLock::weakLock(WeakLock* weak_lock_flag) { scoped_lock lock(m_mutex); if (m_weak_lock || m_write_lock || m_read_locks > 0) return false; m_weak_lock = weak_lock_flag; *m_weak_lock = WeakLocked; return true; } void RWLock::weakUnlock() { ASSERT(m_weak_lock); ASSERT(*m_weak_lock != WeakLock::WeakUnlocked); ASSERT(!m_write_lock); ASSERT(m_read_locks == 0); if (m_weak_lock) { *m_weak_lock = WeakLock::WeakUnlocked; m_weak_lock = nullptr; } } bool RWLock::upgradeToWrite(int timeout) { while (timeout >= 0) { { scoped_lock lock(m_mutex); // Check that there is no weak lock if (m_weak_lock) { if (*m_weak_lock == WeakLocked) *m_weak_lock = WeakUnlocking; // Wait some time if (*m_weak_lock == WeakUnlocking) goto go_wait; ASSERT(*m_weak_lock == WeakUnlocked); } // this only is possible if there are just one reader if (m_read_locks == 1) { ASSERT(!m_write_lock); m_read_locks = 0; m_write_lock = true; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: Locked <%p> to write\n", this); #endif return true; } go_wait:; } if (timeout > 0) { int delay = MIN(100, timeout); timeout -= delay; #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: wait 100 msecs for <%p>\n", this); #endif base::this_thread::sleep_for(double(delay) / 1000.0); } else break; } #ifdef DEBUG_OBJECT_LOCKS TRACE("LCK: upgradeToWrite: Cannot lock <%p> to write (has %d read locks and %d write locks)\n", this, m_read_locks, m_write_lock); #endif return false; } } // namespace base <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string16.h" #if defined(WCHAR_T_IS_UTF16) #error This file should not be used on 2-byte wchar_t systems // If this winds up being needed on 2-byte wchar_t systems, either the // definitions below can be used, or the host system's wide character // functions like wmemcmp can be wrapped. #elif defined(WCHAR_T_IS_UTF32) #include "base/utf_string_conversions.h" namespace base { int c16memcmp(const char16* s1, const char16* s2, size_t n) { // We cannot call memcmp because that changes the semantics. while (n-- > 0) { if (*s1 != *s2) { // We cannot use (*s1 - *s2) because char16 is unsigned. return ((*s1 < *s2) ? -1 : 1); } ++s1; ++s2; } return 0; } size_t c16len(const char16* s) { const char16 *s_orig = s; while (*s) { ++s; } return s - s_orig; } const char16* c16memchr(const char16* s, char16 c, size_t n) { while (n-- > 0) { if (*s == c) { return s; } ++s; } return 0; } char16* c16memmove(char16* s1, const char16* s2, size_t n) { return reinterpret_cast<char16*>(memmove(s1, s2, n * sizeof(char16))); } char16* c16memcpy(char16* s1, const char16* s2, size_t n) { return reinterpret_cast<char16*>(memcpy(s1, s2, n * sizeof(char16))); } char16* c16memset(char16* s, char16 c, size_t n) { char16 *s_orig = s; while (n-- > 0) { *s = c; ++s; } return s_orig; } } // namespace base template class std::basic_string<char16, base::string16_char_traits>; namespace base { std::ostream& operator<<(std::ostream& out, const string16& str) { return out << UTF16ToUTF8(str); } } #endif // WCHAR_T_IS_UTF32 <commit_msg>#include <ostream> in base/string16.cc. This is required for the Mac OS X 10.6 SDK build. Otherwise, various bits of <ostream> that would be needed are declared but not defined.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/string16.h" #if defined(WCHAR_T_IS_UTF16) #error This file should not be used on 2-byte wchar_t systems // If this winds up being needed on 2-byte wchar_t systems, either the // definitions below can be used, or the host system's wide character // functions like wmemcmp can be wrapped. #elif defined(WCHAR_T_IS_UTF32) #include <ostream> #include "base/utf_string_conversions.h" namespace base { int c16memcmp(const char16* s1, const char16* s2, size_t n) { // We cannot call memcmp because that changes the semantics. while (n-- > 0) { if (*s1 != *s2) { // We cannot use (*s1 - *s2) because char16 is unsigned. return ((*s1 < *s2) ? -1 : 1); } ++s1; ++s2; } return 0; } size_t c16len(const char16* s) { const char16 *s_orig = s; while (*s) { ++s; } return s - s_orig; } const char16* c16memchr(const char16* s, char16 c, size_t n) { while (n-- > 0) { if (*s == c) { return s; } ++s; } return 0; } char16* c16memmove(char16* s1, const char16* s2, size_t n) { return reinterpret_cast<char16*>(memmove(s1, s2, n * sizeof(char16))); } char16* c16memcpy(char16* s1, const char16* s2, size_t n) { return reinterpret_cast<char16*>(memcpy(s1, s2, n * sizeof(char16))); } char16* c16memset(char16* s, char16 c, size_t n) { char16 *s_orig = s; while (n-- > 0) { *s = c; ++s; } return s_orig; } } // namespace base template class std::basic_string<char16, base::string16_char_traits>; namespace base { std::ostream& operator<<(std::ostream& out, const string16& str) { return out << UTF16ToUTF8(str); } } #endif // WCHAR_T_IS_UTF32 <|endoftext|>
<commit_before>#ifndef LAYER_HPP_ #define LAYER_HPP_ #include "tensor.cu" #include <vector> // TODO: discuss and finalize interfaces: forward() & backward() template <class Dtype> class Layer { public: virtual void Forward(Tensor<Dtype>* bottom, Tensor<Dtype>* top) = 0; // virtual std::vector<Tensor<Dtype>* > Forward(const std::vector<Tensor<Dtype> *> &bottom) = 0; // virtual void Backward(Packet& bottom, Packet& top) = 0; }; #endif // LAYER_HPP_ <commit_msg>layer.hpp<commit_after>#ifndef LAYER_HPP_ #define LAYER_HPP_ #include "tensor.cu" #include <vector> // TODO: discuss and finalize interfaces: forward() & backward() template <class Dtype> class Layer { public: virtual void Forward(std::vector<Tensor<Dtype>*> &bottom, std::vector<Tensor<Dtype>*> &top) = 0; // virtual std::vector<Tensor<Dtype>* > Forward(const std::vector<Tensor<Dtype> *> &bottom) = 0; // virtual void Backward(Packet& bottom, Packet& top) = 0; }; #endif // LAYER_HPP_ <|endoftext|>
<commit_before>/* ########## Copyright (C) 2015 Vincenzo Pacella ## ## Distributed under MIT license, see file LICENSE ## ## or <http://opensource.org/licenses/MIT> ## ## ########## ############################################################# shaduzlabs.com #####*/ #include <catch.hpp> #include <unMIDIfy.hpp> using namespace std::placeholders; namespace sl { namespace midi { namespace test { class TestMidiListenerCallbacks : public Unmidifier { public: void onNoteOff(NoteOff msg_) override { CHECK(msg_.getType() == MidiMessage::Type::NoteOff); MidiNote note(MidiNote::Name::CSharp, 6); CHECK(note == msg_.getNote()); CHECK(0x41 == msg_.getVelocity()); CHECK(3 == msg_.data().size()); } void onNoteOn(NoteOn msg_) override { CHECK(msg_.getType() == MidiMessage::Type::NoteOn); MidiNote note(MidiNote::Name::D, 6); CHECK(note == msg_.getNote()); CHECK(0x42 == msg_.getVelocity()); CHECK(3 == msg_.data().size()); } void onPolyPressure(PolyPressure msg_) override { CHECK(msg_.getType() == MidiMessage::Type::PolyPressure); CHECK(0x63 == msg_.getNote()); CHECK(0x43 == msg_.getPressure()); CHECK(3 == msg_.data().size()); } void onControlChange(ControlChange msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ControlChange); CHECK(0x64 == msg_.getControl()); CHECK(0x44 == msg_.getValue()); CHECK(3 == msg_.data().size()); } void onProgramChange(ProgramChange msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ProgramChange); CHECK(0x65 == msg_.getProgram()); CHECK(2 == msg_.data().size()); } void onChannelPressure(ChannelPressure msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ChannelPressure); CHECK(0x66 == msg_.getPressure()); CHECK(2 == msg_.data().size()); } void onPitchBend(PitchBend msg_) override { CHECK(msg_.getType() == MidiMessage::Type::PitchBend); CHECK(0x8FF == msg_.getPitch()); CHECK(3 == msg_.data().size()); } }; //-------------------------------------------------------------------------------------------------- TEST_CASE("Test MidiMessageListener callbacks", "[midi]") { TestMidiListenerCallbacks midiListener; NoteOff msgNoteOff(MidiMessage::Channel::Ch1, 0x61, 0x41); midiListener.process(msgNoteOff.data()); NoteOn msgNoteOn(MidiMessage::Channel::Ch2, 0x62, 0x42); midiListener.process(msgNoteOn.data()); PolyPressure msgPolyPressure(MidiMessage::Channel::Ch3, 0x63, 0x43); midiListener.process(msgPolyPressure.data()); ControlChange msgControlChange(MidiMessage::Channel::Ch4, 0x64, 0x44); midiListener.process(msgControlChange.data()); ProgramChange msgProgramChange(MidiMessage::Channel::Ch5, 0x65); midiListener.process(msgProgramChange.data()); ChannelPressure msgChannelPressure(MidiMessage::Channel::Ch6, 0x66); midiListener.process(msgChannelPressure.data()); PitchBend msgPitchBend(MidiMessage::Channel::Ch7, 0x7F, 0x11); midiListener.process(msgPitchBend.data()); } //-------------------------------------------------------------------------------------------------- TEST_CASE("Test SysEx messages", "[midi]") { // 0x00 0x21 0x02 - Mutable Instruments SysEx msgSysEx_1( {0xF0, 0x00, 0x21, 0x02, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xf7}); SysEx msgSysEx_2( {0xF0, 0x00, 0x21, 0x02, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}); CHECK(3 == msgSysEx_1.getHeader().size()); CHECK(11 == msgSysEx_1.getPayload().size()); CHECK(3 == msgSysEx_2.getHeader().size()); CHECK(11 == msgSysEx_2.getPayload().size()); CHECK(msgSysEx_1.getPayload().size() == msgSysEx_2.getPayload().size()); // 0x41 - Roland Corporation SysEx msgSysEx_3( {0xF0, 0x41, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xf7}); CHECK(1 == msgSysEx_3.getHeader().size()); CHECK(11 == msgSysEx_3.getPayload().size()); } //-------------------------------------------------------------------------------------------------- } // test } // midi } // sl <commit_msg>fixed unit tests<commit_after>/* ########## Copyright (C) 2015 Vincenzo Pacella ## ## Distributed under MIT license, see file LICENSE ## ## or <http://opensource.org/licenses/MIT> ## ## ########## ############################################################# shaduzlabs.com #####*/ #include <catch.hpp> #include <unMIDIfy.hpp> using namespace std::placeholders; namespace sl { namespace midi { namespace test { class TestMidiListenerCallbacks : public Unmidifier { public: void onNoteOff(NoteOff msg_) override { CHECK(msg_.getType() == MidiMessage::Type::NoteOff); MidiNote note(MidiNote::Name::CSharp, 5); CHECK(note == msg_.getNote()); CHECK(0x41 == msg_.getVelocity()); CHECK(3 == msg_.data().size()); } void onNoteOn(NoteOn msg_) override { CHECK(msg_.getType() == MidiMessage::Type::NoteOn); MidiNote note(MidiNote::Name::D, 5); CHECK(note == msg_.getNote()); CHECK(0x42 == msg_.getVelocity()); CHECK(3 == msg_.data().size()); } void onPolyPressure(PolyPressure msg_) override { CHECK(msg_.getType() == MidiMessage::Type::PolyPressure); CHECK(0x63 == msg_.getNote()); CHECK(0x43 == msg_.getPressure()); CHECK(3 == msg_.data().size()); } void onControlChange(ControlChange msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ControlChange); CHECK(0x64 == msg_.getControl()); CHECK(0x44 == msg_.getValue()); CHECK(3 == msg_.data().size()); } void onProgramChange(ProgramChange msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ProgramChange); CHECK(0x65 == msg_.getProgram()); CHECK(2 == msg_.data().size()); } void onChannelPressure(ChannelPressure msg_) override { CHECK(msg_.getType() == MidiMessage::Type::ChannelPressure); CHECK(0x66 == msg_.getPressure()); CHECK(2 == msg_.data().size()); } void onPitchBend(PitchBend msg_) override { CHECK(msg_.getType() == MidiMessage::Type::PitchBend); CHECK(0x8FF == msg_.getPitch()); CHECK(3 == msg_.data().size()); } }; //-------------------------------------------------------------------------------------------------- TEST_CASE("Test MidiMessageListener callbacks", "[midi]") { TestMidiListenerCallbacks midiListener; NoteOff msgNoteOff(MidiMessage::Channel::Ch1, 0x61, 0x41); midiListener.process(msgNoteOff.data()); NoteOn msgNoteOn(MidiMessage::Channel::Ch2, 0x62, 0x42); midiListener.process(msgNoteOn.data()); PolyPressure msgPolyPressure(MidiMessage::Channel::Ch3, 0x63, 0x43); midiListener.process(msgPolyPressure.data()); ControlChange msgControlChange(MidiMessage::Channel::Ch4, 0x64, 0x44); midiListener.process(msgControlChange.data()); ProgramChange msgProgramChange(MidiMessage::Channel::Ch5, 0x65); midiListener.process(msgProgramChange.data()); ChannelPressure msgChannelPressure(MidiMessage::Channel::Ch6, 0x66); midiListener.process(msgChannelPressure.data()); PitchBend msgPitchBend(MidiMessage::Channel::Ch7, 0x7F, 0x11); midiListener.process(msgPitchBend.data()); } //-------------------------------------------------------------------------------------------------- TEST_CASE("Test SysEx messages", "[midi]") { // 0x00 0x21 0x02 - Mutable Instruments SysEx msgSysEx_1( {0xF0, 0x00, 0x21, 0x02, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xf7}); SysEx msgSysEx_2( {0xF0, 0x00, 0x21, 0x02, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09}); CHECK(3 == msgSysEx_1.getHeader().size()); CHECK(11 == msgSysEx_1.getPayload().size()); CHECK(3 == msgSysEx_2.getHeader().size()); CHECK(11 == msgSysEx_2.getPayload().size()); CHECK(msgSysEx_1.getPayload().size() == msgSysEx_2.getPayload().size()); // 0x41 - Roland Corporation SysEx msgSysEx_3( {0xF0, 0x41, 0x00, 0x02, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0xf7}); CHECK(1 == msgSysEx_3.getHeader().size()); CHECK(11 == msgSysEx_3.getPayload().size()); } //-------------------------------------------------------------------------------------------------- } // test } // midi } // sl <|endoftext|>
<commit_before>#include <cmath> #include "mbed.h" #include "motor.h" #include "encoder.h" #include "irsensor.h" Serial serial(PA_9, PA_10); Motor left_motor(PB_6, PA_7, 3); Motor right_motor(PC_7, PB_10); Encoder left_encoder(PA_1, PC_4, Encoder::X2, 1.72); Encoder right_encoder(PA_15, PB_3, Encoder::X0); Ticker interrupts; IRSensor left_irsensor(PC_0, PB_7); IRSensor front_left_irsensor(PC_1, PB_0); IRSensor front_right_irsensor(PA_4, PC_11); IRSensor right_irsensor(PA_0, PC_10); const float IR_READ_DELAY = 0.1; void forward(int); void right_turn(int); void ir_update(); int main() { interrupts.attach(&ir_update, IR_READ_DELAY); forward(100000); } void forward(int cells) { const float P = 0.002; const float I = 0; const float D = 0; const int CELL_LENGTH = 500; const float SPEED = 0.1; const float DELAY = 0.005; const int LEFT_STOP = 950; const int RIGHT_STOP = 1140; // Divisor is to ignore small errors between left & right, multiplier is for error weighting const int IR_DIVISOR = 100; const int IR_MULTIPLIER = 2; int prev_error = 0; int integral = 0; left_encoder.reset(); right_encoder.reset(); while(left_encoder.count() < CELL_LENGTH * cells) { if (front_left_irsensor.getValue() >= LEFT_STOP || front_right_irsensor.getValue() >= RIGHT_STOP) { left_motor.set_speed(0); right_motor.set_speed(0); continue; } int error = left_encoder.count() - right_encoder.count(); error += IR_MULTIPLIER * ((right_irsensor.getValue() - left_irsensor.getValue()) / IR_DIVISOR); integral += error; float correction = P * error + I * integral + D * (error - prev_error); if(correction > SPEED) { correction = SPEED; } else if(correction < -1 * SPEED) { correction = -1 * SPEED; } prev_error = error; left_motor.set_speed(SPEED - correction); right_motor.set_speed(SPEED + correction); wait(DELAY); } left_motor.set_speed(0); right_motor.set_speed(0); wait(0.1); } void right_turn(int times) { int dir = (times > 0) ? 1 : -1; left_encoder.reset(); right_encoder.reset(); left_motor.set_speed(dir * 0.05); right_motor.set_speed(dir * -0.05); while(abs(left_encoder.count() - right_encoder.count()) < 200 * abs(times)); left_motor.set_speed(0); right_motor.set_speed(0); wait(0.5); } void ir_update() { left_irsensor.read(); front_left_irsensor.read(); front_right_irsensor.read(); right_irsensor.read(); } <commit_msg>super sketch code that somehow got 1st place<commit_after>#include <cmath> #include "mbed.h" #include "motor.h" #include "encoder.h" #include "irsensor.h" Serial serial(PA_9, PA_10); Motor left_motor(PB_6, PA_7, 3); Motor right_motor(PC_7, PB_10); Encoder left_encoder(PA_1, PC_4, Encoder::X2, 1.72); Encoder right_encoder(PA_15, PB_3, Encoder::X0); Ticker interrupts; IRSensor left_irsensor(PC_0, PB_7); IRSensor front_left_irsensor(PC_1, PB_0); IRSensor front_right_irsensor(PA_4, PC_11); IRSensor right_irsensor(PA_0, PC_10); const int SIDE_BIAS = 0; enum Direction { LEFT, RIGHT }; void forward(); void backward(); void turn(Direction); void ir_update(); int main() { const float IR_READ_DELAY = 0.1; interrupts.attach(&ir_update, IR_READ_DELAY); while(true) { forward(); backward(); if(left_irsensor.getValue() < right_irsensor.getValue()) { turn(LEFT); } else { turn(RIGHT); } } } inline bool is_wall() { const int LEFT_STOP = 1050; const int RIGHT_STOP = 1250; return front_left_irsensor.getValue() >= LEFT_STOP || front_right_irsensor.getValue() >= RIGHT_STOP; } inline bool is_crashed() { return front_left_irsensor.getValue() > 3800 || front_right_irsensor.getValue() > 3800; } void backward() { const float BACKWARD_SPEED = 0.05; while(is_crashed()) { left_motor.set_speed(-1*BACKWARD_SPEED); right_motor.set_speed(-1*BACKWARD_SPEED); } left_motor.set_speed(0); right_motor.set_speed(0); wait(0.1); } void forward() { const float P = 0.002; const float I = 0; const float D = 0; const float SPEED = 0.1; const int CELL_LENGTH = 500; const float DELAY = 0.005; const float IR_MULTIPLIER = 0.025; int prev_error = 0; int integral = 0; left_encoder.reset(); right_encoder.reset(); while(!is_wall()) { int error = left_encoder.count() - right_encoder.count(); error += IR_MULTIPLIER * (right_irsensor.getValue() - left_irsensor.getValue() - SIDE_BIAS); integral += error; float correction = P * error + I * integral + D * (error - prev_error); if(correction > SPEED) { correction = SPEED; } else if(correction < -1 * SPEED) { correction = -1 * SPEED; } prev_error = error; left_motor.set_speed(SPEED - correction); right_motor.set_speed(SPEED + correction); wait(DELAY); } left_motor.set_speed(0); right_motor.set_speed(0); wait(0.1); } void turn(Direction d) { const float TURN_SPEED = 0.03; const float RIGHT_SPEED = 0.05; const int TURN_COUNT = 134; int dir = (d == RIGHT) ? 1 : -1; left_encoder.reset(); right_encoder.reset(); left_motor.set_speed(dir * TURN_SPEED); right_motor.set_speed(dir * -1*RIGHT_SPEED); while(is_wall()) { if(is_crashed()) { break; } } left_motor.set_speed(0); right_motor.set_speed(0); wait(0.1); } void ir_update() { left_irsensor.read(); front_left_irsensor.read(); front_right_irsensor.read(); right_irsensor.read(); } <|endoftext|>
<commit_before>//---------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001, 2002, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------------------- #include <base/logstream.h> #include <lac/vector.h> #include <lac/block_vector.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <dofs/dof_renumbering.h> #include <fe/fe_dgp.h> #include <fe/fe_dgq.h> #include <fe/fe_q.h> #include <fe/fe_system.h> #include <multigrid/mg_dof_handler.h> #include <multigrid/mg_transfer.h> #include <multigrid/mg_dof_tools.h> #include <fstream> #include <iostream> #include <algorithm> template <int dim> void check_simple(const FiniteElement<dim>& fe) { deallog << fe.get_name() << std::endl; Triangulation<dim> tr; GridGenerator::hyper_cube(tr); tr.refine_global(2); MGDoFHandler<dim> mgdof(tr); mgdof.distribute_dofs(fe); MGTransferPrebuilt<double> transfer; transfer.build_matrices(mgdof); Vector<double> u2(mgdof.n_dofs(2)); Vector<double> u1(mgdof.n_dofs(1)); Vector<double> u0(mgdof.n_dofs(0)); u0 = 1; transfer.prolongate(1,u1,u0); transfer.prolongate(2,u2,u1); deallog << "u0 " << u0.l2_norm() << "\tu1 " << u1.l2_norm() << "\tu2 " << u2.l2_norm(); u1 = 0.; u0 = 0.; transfer.restrict_and_add(2,u1,u2); transfer.restrict_and_add(1,u0,u1); deallog << "\tu1 " << u1.l2_norm() << "\tu0 " << u0.l2_norm() << std::endl; } template <int dim> void check_select(const FiniteElement<dim>& fe, std::vector<unsigned int> target_component) { deallog << fe.get_name() << std::endl; Triangulation<dim> tr; GridGenerator::hyper_cube(tr); tr.refine_global(2); MGDoFHandler<dim> mgdof(tr); mgdof.distribute_dofs(fe); DoFRenumbering::component_wise(mgdof, target_component); for (unsigned int l=0;l<tr.n_levels();++l) DoFRenumbering::component_wise(mgdof, l, target_component); std::vector<std::vector<unsigned int> > ndofs(mgdof.get_tria().n_levels()); MGTools::count_dofs_per_component(mgdof, ndofs, target_component); for (unsigned int l=0;l<ndofs.size();++l) { deallog << "Level " << l << " dofs:"; for (unsigned int i=0;i<ndofs[l].size();++i) deallog << ' ' << ndofs[l][i]; deallog << std::endl; } MGTransferSelect<double> transfer; transfer.build_matrices(mgdof, 0, target_component); Vector<double> u2(ndofs[2][0]); Vector<double> u1(ndofs[1][0]); Vector<double> u0(ndofs[0][0]); u0 = 1; transfer.prolongate(1,u1,u0); transfer.prolongate(2,u2,u1); deallog << "u0 " << u0.l2_norm() << "\tu1 " << u1.l2_norm() << "\tu2 " << u2.l2_norm(); u1 = 0.; u0 = 0.; transfer.restrict_and_add(2,u1,u2); transfer.restrict_and_add(1,u0,u1); deallog << "\tu1 " << u1.l2_norm() << "\tu0 " << u0.l2_norm() << std::endl; } int main() { // check_simple (FE_DGP<2>(0)); // check_simple (FE_DGP<2>(1)); check_simple (FE_DGQ<2>(1)); // check_simple (FE_DGQ<2>(2)); // check_simple (FE_Q<2>(1)); // check_simple (FE_Q<2>(2)); std::vector<unsigned int> v1(4); std::vector<unsigned int> v2(4); std::vector<unsigned int> v3(4); for (unsigned int i=0;i<4;++i) { v1[i] = i; v2[i] = 0; v3[i] = i/2; } check_select (FESystem<2>(FE_DGQ<2>(1), 4), v1); check_select (FESystem<2>(FE_DGQ<2>(1), 4), v2); check_select (FESystem<2>(FE_DGQ<2>(1), 4), v3); } <commit_msg>first multigrid test<commit_after>//---------------------------------------------------------------------------- // $Id$ // Version: $Name$ // // Copyright (C) 2000, 2001, 2002, 2003 by the deal.II authors // // This file is subject to QPL and may not be distributed // without copyright and license information. Please refer // to the file deal.II/doc/license.html for the text and // further information on this license. // //---------------------------------------------------------------------------- #include <base/logstream.h> #include <lac/vector.h> #include <lac/block_vector.h> #include <grid/tria.h> #include <grid/grid_generator.h> #include <dofs/dof_renumbering.h> #include <fe/fe_dgp.h> #include <fe/fe_dgq.h> #include <fe/fe_q.h> #include <fe/fe_system.h> #include <multigrid/mg_dof_handler.h> #include <multigrid/mg_transfer.h> #include <multigrid/mg_dof_tools.h> #include <fstream> #include <iostream> #include <algorithm> template <int dim> void check_simple(const FiniteElement<dim>& fe) { deallog << fe.get_name() << std::endl; Triangulation<dim> tr; GridGenerator::hyper_cube(tr); tr.refine_global(2); MGDoFHandler<dim> mgdof(tr); mgdof.distribute_dofs(fe); MGTransferPrebuilt<double> transfer; transfer.build_matrices(mgdof); Vector<double> u2(mgdof.n_dofs(2)); Vector<double> u1(mgdof.n_dofs(1)); Vector<double> u0(mgdof.n_dofs(0)); u0 = 1; transfer.prolongate(1,u1,u0); transfer.prolongate(2,u2,u1); deallog << "u0 " << u0.l2_norm() << "\tu1 " << u1.l2_norm() << "\tu2 " << u2.l2_norm(); u1 = 0.; u0 = 0.; transfer.restrict_and_add(2,u1,u2); transfer.restrict_and_add(1,u0,u1); deallog << "\tu1 " << u1.l2_norm() << "\tu0 " << u0.l2_norm() << std::endl; } template <int dim> void check_select(const FiniteElement<dim>& fe, std::vector<unsigned int> target_component, std::vector<unsigned int> mg_target_component) { deallog << fe.get_name() << std::endl; Triangulation<dim> tr; GridGenerator::hyper_cube(tr); tr.refine_global(2); MGDoFHandler<dim> mgdof(tr); mgdof.distribute_dofs(fe); DoFRenumbering::component_wise(mgdof, target_component); for (unsigned int l=0;l<tr.n_levels();++l) DoFRenumbering::component_wise(mgdof, l, mg_target_component); std::vector<std::vector<unsigned int> > ndofs(mgdof.get_tria().n_levels()); MGTools::count_dofs_per_component(mgdof, ndofs, mg_target_component); for (unsigned int l=0;l<ndofs.size();++l) { deallog << "Level " << l << " dofs:"; for (unsigned int i=0;i<ndofs[l].size();++i) deallog << ' ' << ndofs[l][i]; deallog << std::endl; } MGTransferSelect<double> transfer; transfer.build_matrices(mgdof, 0, mg_target_component); Vector<double> u2(ndofs[2][0]); Vector<double> u1(ndofs[1][0]); Vector<double> u0(ndofs[0][0]); u0 = 1; transfer.prolongate(1,u1,u0); transfer.prolongate(2,u2,u1); deallog << "u0 " << u0.l2_norm() << "\tu1 " << u1.l2_norm() << "\tu2 " << u2.l2_norm(); u1 = 0.; u0 = 0.; transfer.restrict_and_add(2,u1,u2); transfer.restrict_and_add(1,u0,u1); deallog << "\tu1 " << u1.l2_norm() << "\tu0 " << u0.l2_norm() << std::endl; } int main() { std::ofstream logfile("transfer.output"); logfile.precision(3); deallog.attach(logfile); deallog.depth_console(100); // check_simple (FE_DGP<2>(0)); // check_simple (FE_DGP<2>(1)); check_simple (FE_DGQ<2>(1)); // check_simple (FE_DGQ<2>(2)); // check_simple (FE_Q<2>(1)); // check_simple (FE_Q<2>(2)); std::vector<unsigned int> v1(4); std::vector<unsigned int> v2(4); std::vector<unsigned int> v3(4); for (unsigned int i=0;i<4;++i) { v1[i] = i; v2[i] = 0; v3[i] = i/2; } check_select (FESystem<2>(FE_DGQ<2>(1), 4), v1, v1); check_select (FESystem<2>(FE_DGQ<2>(1), 4), v2, v2); check_select (FESystem<2>(FE_DGQ<2>(1), 4), v3, v3); } <|endoftext|>
<commit_before>#include <algorithm> #include <ostream> #include <iostream> #include "mjolnir/edgeinfobuilder.h" namespace valhalla { namespace mjolnir { // Constructor EdgeInfoBuilder::EdgeInfoBuilder() { } // Set the reference node (start) of the edge. void EdgeInfoBuilder::set_nodea(const baldr::GraphId& nodea) { nodea_ = nodea; } // Set the end node of the edge. void EdgeInfoBuilder::set_nodeb(const baldr::GraphId& nodeb) { nodeb_ = nodeb; } // Set the indexes to names used by this edge. TODO - move? void EdgeInfoBuilder::set_street_name_offset_list( const std::vector<size_t>& street_name_offset_list) { // TODO - move street_name_offset_list_.clear(); if (!street_name_offset_list.empty()) { street_name_offset_list_.insert(street_name_offset_list_.end(), street_name_offset_list.begin(), street_name_offset_list.end()); } // Set the street name offset list offset item_.fields.street_name_offset_list_offset = sizeof(GraphId) + sizeof(GraphId) + sizeof(PackedItem); // Set the name count item_.fields.name_count = street_name_offset_list_.size(); } // Set the shape of the edge. TODO - move? void EdgeInfoBuilder::set_shape(const std::vector<PointLL>& shape) { // Set the shape shape_.assign(shape.begin(), shape.end()); // Set the shape count item_.fields.shape_count = shape_.size(); } std::size_t EdgeInfoBuilder::SizeOf() const { std::size_t size = 0; size += sizeof(GraphId); // nodea_ size += sizeof(GraphId); // nodeb_ size += sizeof(PackedItem); // item_ size += (street_name_offset_list_.size() * sizeof(size_t)); // street_name_offset_list_ size += (shape_.size() * sizeof(PointLL)); // shape_ size += (exit_signs_.size() * sizeof(ExitSign)); // exit_signs_ return size; } void EdgeInfoBuilder::SerializeToOstream(std::ostream& out) const { // TODO - rm later /*std::cout << "------------------------------------------------------" << std::endl; std::cout << __FILE__ << ":" << __LINE__ << std::endl; std::cout << "nodea=" << nodea_.value() << " nodea_.tileid=" << nodea_.tileid() << " nodea_.level=" << nodea_.level() << " nodea_.id=" << nodea_.id() << std::endl; std::cout << "nodeb=" << nodeb_.value() << " nodeb_.tileid=" << nodeb_.tileid() << " nodeb_.level=" << nodeb_.level() << " nodeb_.id=" << nodeb_.id() << std::endl; std::cout << "item_=" << item_.value << std::endl; std::cout << "street_name_offset_list_offset=" << street_name_offset_list_offset() << " name_count=" << street_name_offset_list_.size() << std::endl; for (auto name_offset : street_name_offset_list_) { std::cout << " name_offset=" << name_offset << std::endl; } std::cout << "shape_count=" << shape_.size() << std::endl; for (const auto& ll : shape_) { std::cout << " ll=" << ll.lat() << "," << ll.lng() << std::endl; } std::cout << "exit_sign_count=" << exit_signs_.size() << std::endl; std::cout << "=======================================================" << std::endl;*/ out.write(reinterpret_cast<const char*>(&nodea_), sizeof(GraphId)); out.write(reinterpret_cast<const char*>(&nodeb_), sizeof(GraphId)); out.write(reinterpret_cast<const char*>(&item_), sizeof(PackedItem)); out.write(reinterpret_cast<const char*>(&street_name_offset_list_[0]), (street_name_offset_list_.size() * sizeof(size_t))); out.write(reinterpret_cast<const char*>(&shape_[0]), (shape_.size() * sizeof(PointLL))); out.write(reinterpret_cast<const char*>(&exit_signs_[0]), (exit_signs_.size() * sizeof(ExitSign))); } } } <commit_msg>Debug updates<commit_after>#include <algorithm> #include <ostream> #include <iostream> #include "mjolnir/edgeinfobuilder.h" namespace valhalla { namespace mjolnir { // Constructor EdgeInfoBuilder::EdgeInfoBuilder() { } // Set the reference node (start) of the edge. void EdgeInfoBuilder::set_nodea(const baldr::GraphId& nodea) { nodea_ = nodea; } // Set the end node of the edge. void EdgeInfoBuilder::set_nodeb(const baldr::GraphId& nodeb) { nodeb_ = nodeb; } // Set the indexes to names used by this edge. TODO - move? void EdgeInfoBuilder::set_street_name_offset_list( const std::vector<size_t>& street_name_offset_list) { // TODO - move street_name_offset_list_.clear(); if (!street_name_offset_list.empty()) { street_name_offset_list_.insert(street_name_offset_list_.end(), street_name_offset_list.begin(), street_name_offset_list.end()); } // Set the street name offset list offset item_.fields.street_name_offset_list_offset = sizeof(GraphId) + sizeof(GraphId) + sizeof(PackedItem); // Set the name count item_.fields.name_count = street_name_offset_list_.size(); } // Set the shape of the edge. TODO - move? void EdgeInfoBuilder::set_shape(const std::vector<PointLL>& shape) { // Set the shape shape_.assign(shape.begin(), shape.end()); // Set the shape count item_.fields.shape_count = shape_.size(); } std::size_t EdgeInfoBuilder::SizeOf() const { std::size_t size = 0; size += sizeof(GraphId); // nodea_ size += sizeof(GraphId); // nodeb_ size += sizeof(PackedItem); // item_ size += (street_name_offset_list_.size() * sizeof(size_t)); // street_name_offset_list_ size += (shape_.size() * sizeof(PointLL)); // shape_ size += (exit_signs_.size() * sizeof(ExitSign)); // exit_signs_ return size; } void EdgeInfoBuilder::SerializeToOstream(std::ostream& out) const { // TODO - rm later std::cout << "------------------------------------------------------" << std::endl; std::cout << __FILE__ << ":" << __LINE__ << std::endl; std::cout << "EdgeInfoBuilder::SizeOf=" << SizeOf() << std::endl; std::cout << "nodea=" << nodea_.value() << " nodea_.tileid=" << nodea_.tileid() << " nodea_.level=" << nodea_.level() << " nodea_.id=" << nodea_.id() << std::endl; std::cout << "nodeb=" << nodeb_.value() << " nodeb_.tileid=" << nodeb_.tileid() << " nodeb_.level=" << nodeb_.level() << " nodeb_.id=" << nodeb_.id() << std::endl; std::cout << "item_=" << item_.value << std::endl; std::cout << "street_name_offset_list_offset=" << street_name_offset_list_offset() << " name_count=" << street_name_offset_list_.size() << std::endl; for (auto name_offset : street_name_offset_list_) { std::cout << " name_offset=" << name_offset << std::endl; } std::cout << "shape_count=" << shape_.size() << std::endl; for (const auto& ll : shape_) { std::cout << " ll=" << ll.lat() << "," << ll.lng() << std::endl; } std::cout << "exit_sign_count=" << exit_signs_.size() << std::endl; std::cout << "=======================================================" << std::endl; out.write(reinterpret_cast<const char*>(&nodea_), sizeof(GraphId)); out.write(reinterpret_cast<const char*>(&nodeb_), sizeof(GraphId)); out.write(reinterpret_cast<const char*>(&item_), sizeof(PackedItem)); out.write(reinterpret_cast<const char*>(&street_name_offset_list_[0]), (street_name_offset_list_.size() * sizeof(size_t))); out.write(reinterpret_cast<const char*>(&shape_[0]), (shape_.size() * sizeof(PointLL))); out.write(reinterpret_cast<const char*>(&exit_signs_[0]), (exit_signs_.size() * sizeof(ExitSign))); } } } <|endoftext|>
<commit_before>#ifndef VXL_ROTATION_HPP # define VXL_ROTATION_HPP # pragma once #include "cross.hpp" #include "quat.hpp" #include "sinf.hpp" namespace vxl { enum struct ea { XYZ, XZY, YXZ, YZX, ZXY, ZYX }; namespace detail { template <typename T> constexpr inline auto rot_x(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ T(1), T(0), T(0), T(0), T(0), sc.second(0), -sc.first(0), T(0), T(0), sc.first(0), sc.second(0), T(0), T(0), T(0), T(0), T(1) }; } template <typename T> constexpr inline auto rot_y(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ sc.second(1), T(0), sc.first(1), T(0), T(0), T(1), T(0), T(0), -sc.first(1), T(0), sc.second(1), T(0), T(0), T(0), T(0), T(1) }; } template <typename T> constexpr inline auto rot_z(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ sc.second(2), -sc.first(2), T(0), T(0), sc.first(2), sc.second(2), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1) }; } } // Euler angle to rotation matrix conversions. WARNING: Blender XYZ is ZYX // with angles negated, this is because Blender caters to artists. ////////////////////////////////////////////////////////////////////////////// template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::XYZ, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_x(sc) * detail::rot_y(sc) * detail::rot_z(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::XZY, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_x(sc) * detail::rot_z(sc) * detail::rot_y(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::YXZ, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_y(sc) * detail::rot_x(sc) * detail::rot_z(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::YZX, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_y(sc) * detail::rot_z(sc) * detail::rot_x(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::ZXY, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_z(sc) * detail::rot_x(sc) * detail::rot_y(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::ZYX, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_z(sc) * detail::rot_y(sc) * detail::rot_x(sc); } // convert axis angle to quaternion ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline quat<T> to_quat(vector<T, 3> const a, T const angle) noexcept { using vector_type = typename vector_traits<T, 4>::vector_type; auto const p(csincos(vector<T, 1>{T(.5) * angle})); return { vector_type{p.first.data_, p.first.data_, p.first.data_, p.second.data_} * vector_type{a.data_[0], a.data_[1], a.data_[2], T(1)} }; } ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline vector<T, 3> rotated(quat<T> const& q, vector<T, 3> const& v) noexcept { auto const vq(vec(q)); auto const t(ccross(vq, v)); auto const u(scalar_vector<T, 3>(q) * t.data_ + ccross(vq, t).data_); return {v.data_ + u + u}; } ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline vector<T, 3>& rotate(quat<T> const& q, vector<T, 3>& v) noexcept { auto const vq(vec(q)); auto const t(ccross(vq, v)); auto const u(scalar_vector<T, 3>(q) * t.data_ + ccross(vq, t).data_); v.data_ += u + u; return v; } } #endif // VXL_ROTATION_HPP <commit_msg>some fixes<commit_after>#ifndef VXL_ROTATION_HPP # define VXL_ROTATION_HPP # pragma once #include "cross.hpp" #include "quat.hpp" #include "sinf.hpp" namespace vxl { enum struct ea { XYZ, XZY, YXZ, YZX, ZXY, ZYX }; struct scale; namespace detail { template <typename T> constexpr inline auto rot_x(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ T(1), T(0), T(0), T(0), T(0), sc.second(0), -sc.first(0), T(0), T(0), sc.first(0), sc.second(0), T(0), T(0), T(0), T(0), T(1) }; } template <typename T> constexpr inline auto rot_y(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ sc.second(1), T(0), sc.first(1), T(0), T(0), T(1), T(0), T(0), -sc.first(1), T(0), sc.second(1), T(0), T(0), T(0), T(0), T(1) }; } template <typename T> constexpr inline auto rot_z(std::pair<vxl::vector<T, 3>, vxl::vector<T, 3>> const& sc) noexcept { return vxl::matrix<T, 4, 4>{ sc.second(2), -sc.first(2), T(0), T(0), sc.first(2), sc.second(2), T(0), T(0), T(0), T(0), T(1), T(0), T(0), T(0), T(0), T(1) }; } } // Euler angle to rotation matrix conversions. WARNING: Blender XYZ is ZYX // with angles negated, this is because Blender caters to artists. ////////////////////////////////////////////////////////////////////////////// template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::XYZ, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_x(sc) * detail::rot_y(sc) * detail::rot_z(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::XZY, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_x(sc) * detail::rot_z(sc) * detail::rot_y(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::YXZ, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_y(sc) * detail::rot_x(sc) * detail::rot_z(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::YZX, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_y(sc) * detail::rot_z(sc) * detail::rot_x(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::ZXY, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_z(sc) * detail::rot_x(sc) * detail::rot_y(sc); } template <enum ea E, typename T> constexpr inline std::enable_if_t<E == ea::ZYX, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& a) noexcept { auto const sc(csincos(a)); return detail::rot_z(sc) * detail::rot_y(sc) * detail::rot_x(sc); } template <typename E, typename T> constexpr inline std::enable_if_t<std::is_same<E, scale>{}, matrix<T, 4, 4>> to_matrix(vxl::vector<T, 3> const& s) noexcept { matrix<T, 4, 4> r{{}}; r.set_element(0, 0, s(0)); r.set_element(1, 1, s(1)); r.set_element(2, 2, s(2)); r.set_element(3, 3, T(1)); return r; } // convert axis angle to quaternion ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline quat<T> to_quat(vector<T, 3> const a, T const angle) noexcept { using vector_type = typename vector_traits<T, 4>::vector_type; auto const p(csincos(vector<T, 1>{T(.5) * angle})); return { vector_type{p.first.data_, p.first.data_, p.first.data_, p.second.data_} * vector_type{a.data_[0], a.data_[1], a.data_[2], T(1)} }; } ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline vector<T, 3> rotated(quat<T> const& q, vector<T, 3> const& v) noexcept { auto const vq(vec(q)); auto const t(ccross(vq, v)); auto const u(scalar_vector<T, 3>(q) * t.data_ + ccross(vq, t).data_); return {v.data_ + u + u}; } ////////////////////////////////////////////////////////////////////////////// template <typename T> //__attribute__ ((noinline)) inline vector<T, 3>& rotate(quat<T> const& q, vector<T, 3>& v) noexcept { auto const vq(vec(q)); auto const t(ccross(vq, v)); auto const u(scalar_vector<T, 3>(q) * t.data_ + ccross(vq, t).data_); v.data_ += u + u; return v; } } #endif // VXL_ROTATION_HPP <|endoftext|>
<commit_before><commit_msg>bfd_section_vma is not macro<commit_after><|endoftext|>
<commit_before><commit_msg>Work in progress<commit_after><|endoftext|>
<commit_before><commit_msg>Refactorings<commit_after><|endoftext|>
<commit_before><commit_msg>java: constant pool tags<commit_after><|endoftext|>
<commit_before><commit_msg>update r697<commit_after><|endoftext|>
<commit_before>//---------------------------------------------------------------------------// /*! * \file tstMeshContainer.cpp * \author Stuart R. Slattery * \brief MeshContainer unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <set> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <DTK_MeshContainer.hpp> #include <DTK_RendezvousMesh.hpp> #include <DTK_MeshTypes.hpp> #include <DTK_MeshTraits.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_TypeTraits.hpp> #include <MBRange.hpp> //---------------------------------------------------------------------------// // MPI Setup //---------------------------------------------------------------------------// template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // Mesh contianer creation funciton. //---------------------------------------------------------------------------// DataTransferKit::MeshContainer<int> buildMeshContainer() { using namespace DataTransferKit; // Make some nodes. Teuchos::Array<int> node_handles; std::vector<double> coords; node_handles.push_back( 0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); node_handles.push_back( 1 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); node_handles.push_back( 2 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); node_handles.push_back( 3 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); node_handles.push_back( 4 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); node_handles.push_back( 5 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); node_handles.push_back( 6 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); node_handles.push_back( 7 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); node_handles.push_back( 8 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 2.0 ); node_handles.push_back( 9 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 2.0 ); node_handles.push_back( 10 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); node_handles.push_back( 11 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); // Make 2 hexahedrons. Teuchos::Array<int> hex_handles; std::vector<int> hex_connectivity; hex_handles.push_back( 0 ); hex_connectivity.push_back( 0 ); hex_connectivity.push_back( 1 ); hex_connectivity.push_back( 2 ); hex_connectivity.push_back( 3 ); hex_connectivity.push_back( 4 ); hex_connectivity.push_back( 5 ); hex_connectivity.push_back( 6 ); hex_connectivity.push_back( 7 ); hex_handles.push_back( 1 ); hex_connectivity.push_back( 4 ); hex_connectivity.push_back( 5 ); hex_connectivity.push_back( 6 ); hex_connectivity.push_back( 7 ); hex_connectivity.push_back( 8 ); hex_connectivity.push_back( 9 ); hex_connectivity.push_back( 10 ); hex_connectivity.push_back( 11 ); Teuchos::ArrayRCP<int> node_handle_array( node_handles.size() ); std::copy( node_handles.begin(), node_handles.end(), node_handle_array.begin() ); Teuchos::ArrayRCP<double> coords_array( coords.size() ); std::copy( coords.begin(), coords.end(), coords_array.begin() ); Teuchos::ArrayRCP<int> hex_handle_array( hex_handles.size() ); std::copy( hex_handles.begin(), hex_handles.end(), hex_handle_array.begin() ); Teuchos::ArrayRCP<int> connectivity_array( hex_connectivity.size() ); std::copy( hex_connectivity.begin(), hex_connectivity.end(), connectivity_array.begin() ); return MeshContainer<int>( node_handle_array, coords_array, DTK_REGION, DTK_HEXAHEDRON, 8, hex_handle_array, connectivity_array ); } //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( MeshContainer, mesh_container_test ) { using namespace DataTransferKit; // Create a mesh container. typedef MeshTraits< MeshContainer<int> > MT; MeshContainer<int> mesh_container = buildMeshContainer(); Teuchos::RCP< RendezvousMesh<MT::handle_type> > mesh = createRendezvousMesh( mesh_container ); // Get the moab interface. moab::ErrorCode error; RendezvousMesh<MT::handle_type>::RCP_Moab moab = mesh->getMoab(); // Grab the elements. moab::Range mesh_elements = mesh->getElements(); // Check the moab mesh element data. moab::Range::const_iterator element_iterator; MT::handle_type native_handle = 0; for ( element_iterator = mesh_elements.begin(); element_iterator != mesh_elements.end(); ++element_iterator, ++native_handle ) { TEST_ASSERT( mesh->getNativeHandle( *element_iterator ) == native_handle ); TEST_ASSERT( moab->type_from_handle( *element_iterator ) == moab::MBHEX ); } // Check the moab mesh vertex data. moab::Range connectivity; error = moab->get_connectivity( mesh_elements, connectivity ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double> vertex_coords( 3 * connectivity.size() ); error = moab->get_coords( connectivity, &vertex_coords[0] ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double>::const_iterator moab_coord_iterator = vertex_coords.begin(); typename MT::const_coordinate_iterator coord_iterator; for ( coord_iterator = MT::coordsBegin( mesh_container ); coord_iterator != MT::coordsEnd( mesh_container ); ++coord_iterator, ++moab_coord_iterator ) { TEST_ASSERT( *coord_iterator == *moab_coord_iterator ); } } //---------------------------------------------------------------------------// // end tstMeshContainer.cpp //---------------------------------------------------------------------------// <commit_msg>Updated RendezvousMesh test for blocked data interface<commit_after>//---------------------------------------------------------------------------// /*! * \file tstMeshContainer.cpp * \author Stuart R. Slattery * \brief MeshContainer unit tests. */ //---------------------------------------------------------------------------// #include <iostream> #include <vector> #include <set> #include <cmath> #include <sstream> #include <algorithm> #include <cassert> #include <DTK_MeshContainer.hpp> #include <DTK_RendezvousMesh.hpp> #include <DTK_MeshTypes.hpp> #include <DTK_MeshTraits.hpp> #include <Teuchos_UnitTestHarness.hpp> #include <Teuchos_DefaultComm.hpp> #include <Teuchos_DefaultMpiComm.hpp> #include <Teuchos_RCP.hpp> #include <Teuchos_ArrayRCP.hpp> #include <Teuchos_TypeTraits.hpp> #include <MBRange.hpp> //---------------------------------------------------------------------------// // MPI Setup //---------------------------------------------------------------------------// template<class Ordinal> Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm() { #ifdef HAVE_MPI return Teuchos::DefaultComm<Ordinal>::getComm(); #else return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() ); #endif } //---------------------------------------------------------------------------// // Mesh contianer creation funciton. //---------------------------------------------------------------------------// DataTransferKit::MeshContainer<int> buildMeshContainer() { using namespace DataTransferKit; // Make some nodes. Teuchos::Array<int> node_handles; Teuchos::Array<double> coords; // handles for ( int i = 0; i < 12; ++i ) { node_handles.push_back( i ); } // x coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); // y coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); // z coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 0.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 1.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); coords.push_back( 2.0 ); // Make 2 hexahedrons. Teuchos::Array<int> hex_handles; Teuchos::Array<int> hex_connectivity; // handles hex_handles.push_back( 0 ); hex_handles.push_back( 1 ); // 0 hex_connectivity.push_back( 0 ); hex_connectivity.push_back( 4 ); // 1 hex_connectivity.push_back( 1 ); hex_connectivity.push_back( 5 ); // 2 hex_connectivity.push_back( 2 ); hex_connectivity.push_back( 6 ); // 3 hex_connectivity.push_back( 3 ); hex_connectivity.push_back( 7 ); // 4 hex_connectivity.push_back( 4 ); hex_connectivity.push_back( 8 ); // 5 hex_connectivity.push_back( 5 ); hex_connectivity.push_back( 9 ); // 6 hex_connectivity.push_back( 6 ); hex_connectivity.push_back( 10 ); // 7 hex_connectivity.push_back( 7 ); hex_connectivity.push_back( 11 ); Teuchos::ArrayRCP<int> node_handle_array( node_handles.size() ); std::copy( node_handles.begin(), node_handles.end(), node_handle_array.begin() ); Teuchos::ArrayRCP<double> coords_array( coords.size() ); std::copy( coords.begin(), coords.end(), coords_array.begin() ); Teuchos::ArrayRCP<int> hex_handle_array( hex_handles.size() ); std::copy( hex_handles.begin(), hex_handles.end(), hex_handle_array.begin() ); Teuchos::ArrayRCP<int> connectivity_array( hex_connectivity.size() ); std::copy( hex_connectivity.begin(), hex_connectivity.end(), connectivity_array.begin() ); return MeshContainer<int>( node_handle_array, coords_array, DTK_REGION, DTK_HEXAHEDRON, 8, hex_handle_array, connectivity_array ); } //---------------------------------------------------------------------------// // Tests //---------------------------------------------------------------------------// TEUCHOS_UNIT_TEST( MeshContainer, mesh_container_test ) { using namespace DataTransferKit; // Create a mesh container. typedef MeshTraits< MeshContainer<int> > MT; MeshContainer<int> mesh_container = buildMeshContainer(); Teuchos::RCP< RendezvousMesh<MT::handle_type> > mesh = createRendezvousMesh( mesh_container ); // Get the moab interface. moab::ErrorCode error; RendezvousMesh<MT::handle_type>::RCP_Moab moab = mesh->getMoab(); // Grab the elements. moab::Range mesh_elements = mesh->getElements(); // Check the moab mesh element data. moab::Range::const_iterator element_iterator; MT::handle_type native_handle = 0; for ( element_iterator = mesh_elements.begin(); element_iterator != mesh_elements.end(); ++element_iterator, ++native_handle ) { TEST_ASSERT( mesh->getNativeHandle( *element_iterator ) == native_handle ); TEST_ASSERT( moab->type_from_handle( *element_iterator ) == moab::MBHEX ); } // Check the moab mesh vertex data. moab::Range connectivity; error = moab->get_connectivity( mesh_elements, connectivity ); TEST_ASSERT( moab::MB_SUCCESS == error ); std::vector<double> vertex_coords( 3 * connectivity.size() ); error = moab->get_coords( connectivity, &vertex_coords[0] ); TEST_ASSERT( moab::MB_SUCCESS == error ); int num_nodes = connectivity.size(); std::vector<double>::const_iterator moab_coord_iterator; typename MT::const_coordinate_iterator coord_iterator = MT::coordsBegin( mesh_container ); int i = 0; for ( moab_coord_iterator = vertex_coords.begin(); moab_coord_iterator != vertex_coords.end(); ++i ) { for ( int d = 0; d < 3; ++d, ++moab_coord_iterator ) { TEST_ASSERT( coord_iterator[d*num_nodes + i] == *moab_coord_iterator ); } } } //---------------------------------------------------------------------------// // end tstMeshContainer.cpp //---------------------------------------------------------------------------// <|endoftext|>
<commit_before>// // GameplayScene.cpp // MasmorraDados // // Created by Marlon Andrade on 16/02/2015. // // #include "GameplayScene.h" #include "BackgroundLayer.h" #include "CharacterDiceSprite.h" #include "RoomPlacement.h" USING_NS_CC; #pragma mark - Public Interface bool GameplayScene::init() { if (!Scene::init()) { return false; } this->_enableInteractions(); auto game = Game::createWithRoomPlacedDelegate([&](Vector<RoomPlacement*> placements) { this->_disableInteractions(); float delayTime = 0; int zOrder = placements.size(); for (auto placement : placements) { auto room = placement->getRoom(); auto position = placement->getPosition(); auto roomSprite = Sprite::create(room->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(position); roomSprite->setName(name); auto size = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); auto deckPosition = Vec2(origin.x + size.width - TILE_DIMENSION / 2 - 20, origin.y + size.height - TILE_DIMENSION / 2 - 20); roomSprite->setPosition(deckPosition); this->_getObjectsLayer()->addChild(roomSprite, zOrder); auto spritePosition = this->_positionInScene(position); auto delay = DelayTime::create(delayTime); auto animationStarted = CallFunc::create([=]() { this->_disableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER + 10); }); auto easeMove = EaseBackIn::create(MoveTo::create(PLACE_ROOM_DURATION, spritePosition)); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER); }); roomSprite->runAction(Sequence::create(delay, animationStarted, easeMove, animationEnded, NULL)); delayTime += PLACE_ROOM_DURATION; zOrder--; } }); this->setGame(game); this->adjustInitialLayers(); return true; } #pragma mark - Private Interface void GameplayScene::adjustInitialLayers() { auto center = this->_centerOfScene(); auto backgroundLayer = BackgroundLayer::create(); this->addChild(backgroundLayer, -2); auto objectsLayer = this->_createObjectsLayer(); this->addChild(objectsLayer, -1); auto controlsLayer = this->_createControlsLayer(); this->addChild(controlsLayer, 1); this->getGame()->setCharacterPosition(INITIAL_POSITION); this->_adjustCharacterDiceSpritePosition(); } Layer* GameplayScene::_createObjectsLayer() { auto objectsLayer = Layer::create(); objectsLayer->setTag(OBJECTS_LAYER_TAG); auto initialRoom = this->getGame()->getDungeon()->getInitialRoom(); auto initialPosition = INITIAL_POSITION; auto initialSprite = Sprite::create(initialRoom->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(initialPosition); initialSprite->setName(name); initialSprite->setPosition(this->_positionInScene(INITIAL_POSITION)); objectsLayer->addChild(initialSprite, DUNGEON_ROOM_Z_ORDER); objectsLayer->addChild(this->_createCharacterDiceSprite(), GAME_OBJECTS_Z_ORDER); return objectsLayer; } Layer* GameplayScene::_createControlsLayer() { auto controlsLayer = Layer::create(); controlsLayer->setTag(CONTROLS_LAYER_TAG); return controlsLayer; } Node* GameplayScene::_createCharacterDiceSprite() { auto sprite = CharacterDiceSprite::create(); sprite->setTag(CHARACTER_DICE_SPRITE_TAG); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = [&](Touch* touch, Event* event) { auto bounds = event->getCurrentTarget()->getBoundingBox(); auto touchInSprite = bounds.containsPoint(touch->getLocation()); bool containsBoot = true; auto canMove = this->_isInteractionEnabled() && touchInSprite && containsBoot; if (canMove) { Vector<Node*> visibleNodes; visibleNodes.pushBack(this->_getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG)); visibleNodes.pushBack(this->_getNodeForCharacterPosition()); visibleNodes.pushBack(this->_getNodesForAdjacentCharacterPosition()); this->_addOverlayWithVisibleNodes(visibleNodes); } return canMove; }; touchListener->onTouchMoved = [=](Touch* touch, Event* event) { auto touchLocation = touch->getLocation(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { Color3B color = Color3B::WHITE; if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { color = Color3B(170, 255, 170); } adjacentNode->setColor(color); } sprite->setPosition(touch->getLocation()); }; touchListener->onTouchEnded = [=](Touch* touch, Event* event) { bool characterMoved = false; auto touchLocation = touch->getLocation(); auto coordinate = this->getGame()->getCharacterPosition(); auto scenePosition = this->_positionInScene(coordinate); this->_removeOverlay(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { adjacentNode->setColor(Color3B::WHITE); if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { characterMoved = true; auto newCoordinate = this->_positionInGameCoordinate(touchLocation); auto newPosition = this->_positionInScene(newCoordinate); auto moveNewPosition = MoveTo::create(RETURN_CHARACTER_DURATION, newPosition); auto actionEnded = CallFunc::create([=]() { this->getGame()->setCharacterPosition(newCoordinate); }); sprite->runAction(Sequence::create(moveNewPosition, actionEnded, NULL)); } } if (!characterMoved) { auto moveBack = MoveTo::create(RETURN_CHARACTER_DURATION, scenePosition); sprite->runAction(moveBack); } }; auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, sprite); return sprite; } Layer* GameplayScene::_getObjectsLayer() { return (Layer*) this->getChildByTag(OBJECTS_LAYER_TAG); } Layer* GameplayScene::_getControlsLayer() { return (Layer*) this->getChildByTag(CONTROLS_LAYER_TAG); } Vec2 GameplayScene::_positionInScene(Vec2 gameCoordinate) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = gameCoordinate.x - centerPosition.x; auto offsetY = gameCoordinate.y - centerPosition.y; return Vec2(centerOfScene.x + offsetX * TILE_DIMENSION, centerOfScene.y + offsetY * TILE_DIMENSION); } Vec2 GameplayScene::_positionInGameCoordinate(Vec2 scenePosition) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = scenePosition.x - centerOfScene.x; auto offsetY = scenePosition.y - centerOfScene.y; auto halfTileDimension = TILE_DIMENSION / 2; offsetX > halfTileDimension ? offsetX += halfTileDimension : offsetX -= halfTileDimension; offsetY > halfTileDimension ? offsetY += halfTileDimension : offsetY -= halfTileDimension; return Vec2(centerPosition.x + int(offsetX / TILE_DIMENSION), centerPosition.y + int(offsetY / TILE_DIMENSION)); } void GameplayScene::_adjustCharacterDiceSpritePosition() { auto sprite = this->_getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG); auto characterPosition = this->getGame()->getCharacterPosition(); sprite->setPosition(this->_positionInScene(characterPosition)); } void GameplayScene::_addOverlayWithVisibleNodes(Vector<Node *> visibleNodes) { auto overlayLayer = LayerColor::create(Color4B(0, 0, 0, 0)); overlayLayer->setTag(OVERLAY_LAYER_TAG); this->_getObjectsLayer()->addChild(overlayLayer, OVERLAY_Z_ORDER); auto fadeIn = FadeTo::create(OVERLAY_DURATION, OVERLAY_OPACITY); overlayLayer->runAction(fadeIn); for (auto visibleNode : visibleNodes) { auto newZOrder = visibleNode->getLocalZOrder() + OVERLAY_Z_ORDER; visibleNode->setLocalZOrder(newZOrder); } this->setInteractableNodes(visibleNodes); } void GameplayScene::_removeOverlay() { this->_disableInteractions(); auto overlayLayer = this->_getObjectsLayer()->getChildByTag(OVERLAY_LAYER_TAG); auto fadeOut = FadeOut::create(OVERLAY_DURATION); auto changeLayer = CallFunc::create([=]() { for (auto node : this->getInteractableNodes()) { auto oldZOrder = node->getLocalZOrder() - OVERLAY_Z_ORDER; node->setLocalZOrder(oldZOrder); } }); auto removeSelf = RemoveSelf::create(); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); }); overlayLayer->runAction(Sequence::create(fadeOut, changeLayer, removeSelf, animationEnded, NULL)); } Vec2 GameplayScene::_centerOfScene() { Vec2 visibleOrigin = Director::getInstance()->getVisibleOrigin(); Size visibleSize = Director::getInstance()->getVisibleSize(); return Vec2(visibleSize.width / 2 + visibleOrigin.x, visibleSize.height / 2 + visibleOrigin.y); } Node* GameplayScene::_getNodeForCharacterPosition() { auto position = this->getGame()->getCharacterPosition(); auto name = this->getGame()->getDungeon()->nameForPosition(position); return this->_getObjectsLayer()->getChildByName(name); } Vector<Node*> GameplayScene::_getNodesForAdjacentCharacterPosition() { Node* activeLayer = this->_getObjectsLayer(); auto overlayLayer = this->getChildByTag(OVERLAY_LAYER_TAG); if (overlayLayer) { activeLayer = overlayLayer; } Vector<Node*> nodes; auto position = this->getGame()->getCharacterPosition(); auto adjacentPositions = this->getGame()->getDungeon()->adjacentPositionsTo(position); for (auto adjacentPosition : adjacentPositions) { auto name = this->getGame()->getDungeon()->nameForPosition(adjacentPosition); nodes.pushBack(activeLayer->getChildByName(name)); } return nodes; } bool GameplayScene::_isInteractionEnabled() { return _userInteractionEnabled; } void GameplayScene::_disableInteractions() { _userInteractionEnabled = false; } void GameplayScene::_enableInteractions() { _userInteractionEnabled = true; }<commit_msg>Permitindo mover a 'camera' na cena.<commit_after>// // GameplayScene.cpp // MasmorraDados // // Created by Marlon Andrade on 16/02/2015. // // #include "GameplayScene.h" #include "BackgroundLayer.h" #include "CharacterDiceSprite.h" #include "RoomPlacement.h" USING_NS_CC; #pragma mark - Public Interface bool GameplayScene::init() { if (!Scene::init()) { return false; } this->_enableInteractions(); auto game = Game::createWithRoomPlacedDelegate([&](Vector<RoomPlacement*> placements) { if (placements.size() > 0) { this->_disableInteractions(); } float delayTime = 0; int zOrder = placements.size(); for (auto placement : placements) { auto room = placement->getRoom(); auto position = placement->getPosition(); auto roomSprite = Sprite::create(room->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(position); roomSprite->setName(name); auto size = Director::getInstance()->getVisibleSize(); auto origin = Director::getInstance()->getVisibleOrigin(); auto deckPosition = Vec2(origin.x + size.width - TILE_DIMENSION / 2 - 20, origin.y + size.height - TILE_DIMENSION / 2 - 20); roomSprite->setPosition(deckPosition); this->_getObjectsLayer()->addChild(roomSprite, zOrder); auto spritePosition = this->_positionInScene(position); auto delay = DelayTime::create(delayTime); auto animationStarted = CallFunc::create([=]() { this->_disableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER + 10); }); auto easeMove = EaseBackIn::create(MoveTo::create(PLACE_ROOM_DURATION, spritePosition)); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); roomSprite->setLocalZOrder(DUNGEON_ROOM_Z_ORDER); }); roomSprite->runAction(Sequence::create(delay, animationStarted, easeMove, animationEnded, NULL)); delayTime += PLACE_ROOM_DURATION; zOrder--; } }); this->setGame(game); this->adjustInitialLayers(); return true; } #pragma mark - Private Interface void GameplayScene::adjustInitialLayers() { auto center = this->_centerOfScene(); auto backgroundLayer = BackgroundLayer::create(); this->addChild(backgroundLayer, -2); auto objectsLayer = this->_createObjectsLayer(); this->addChild(objectsLayer, -1); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->onTouchBegan = [=](Touch* touch, Event* event) { return true; }; touchListener->onTouchMoved = [=](Touch* touch, Event* event) { auto delta = touch->getDelta(); auto currentPosition = objectsLayer->getPosition(); auto newPosition = Vec2(currentPosition.x + delta.x, currentPosition.y + delta.y); backgroundLayer->setPosition(newPosition); objectsLayer->setPosition(newPosition); }; auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, objectsLayer); auto controlsLayer = this->_createControlsLayer(); this->addChild(controlsLayer, 1); this->getGame()->setCharacterPosition(INITIAL_POSITION); this->_adjustCharacterDiceSpritePosition(); } Layer* GameplayScene::_createObjectsLayer() { auto objectsLayer = Layer::create(); objectsLayer->setTag(OBJECTS_LAYER_TAG); auto initialRoom = this->getGame()->getDungeon()->getInitialRoom(); auto initialPosition = INITIAL_POSITION; auto initialSprite = Sprite::create(initialRoom->getImagePath()); auto name = this->getGame()->getDungeon()->nameForPosition(initialPosition); initialSprite->setName(name); initialSprite->setPosition(this->_positionInScene(INITIAL_POSITION)); objectsLayer->addChild(initialSprite, DUNGEON_ROOM_Z_ORDER); objectsLayer->addChild(this->_createCharacterDiceSprite(), GAME_OBJECTS_Z_ORDER); return objectsLayer; } Layer* GameplayScene::_createControlsLayer() { auto controlsLayer = Layer::create(); controlsLayer->setTag(CONTROLS_LAYER_TAG); return controlsLayer; } Node* GameplayScene::_createCharacterDiceSprite() { auto sprite = CharacterDiceSprite::create(); sprite->setTag(CHARACTER_DICE_SPRITE_TAG); auto touchListener = EventListenerTouchOneByOne::create(); touchListener->setSwallowTouches(true); touchListener->onTouchBegan = [&](Touch* touch, Event* event) { auto target = event->getCurrentTarget(); auto layer = target->getParent(); auto bounds = target->getBoundingBox(); auto touchLocation = layer->convertTouchToNodeSpace(touch); auto touchInSprite = bounds.containsPoint(touchLocation); log("%d", touchInSprite); bool containsBoot = true; auto canMove = this->_isInteractionEnabled() && touchInSprite && containsBoot; if (canMove) { Vector<Node*> visibleNodes; visibleNodes.pushBack(this->_getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG)); visibleNodes.pushBack(this->_getNodeForCharacterPosition()); visibleNodes.pushBack(this->_getNodesForAdjacentCharacterPosition()); this->_addOverlayWithVisibleNodes(visibleNodes); } return canMove; }; touchListener->onTouchMoved = [=](Touch* touch, Event* event) { auto target = event->getCurrentTarget(); auto layer = target->getParent(); auto bounds = target->getBoundingBox(); auto touchLocation = layer->convertTouchToNodeSpace(touch); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { Color3B color = Color3B::WHITE; if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { color = Color3B(170, 255, 170); } adjacentNode->setColor(color); } sprite->setPosition(touchLocation); }; touchListener->onTouchEnded = [=](Touch* touch, Event* event) { auto target = event->getCurrentTarget(); auto layer = target->getParent(); auto bounds = target->getBoundingBox(); auto touchLocation = layer->convertTouchToNodeSpace(touch); bool characterMoved = false; auto coordinate = this->getGame()->getCharacterPosition(); auto scenePosition = this->_positionInScene(coordinate); this->_removeOverlay(); for (auto adjacentNode : this->_getNodesForAdjacentCharacterPosition()) { adjacentNode->setColor(Color3B::WHITE); if (adjacentNode->getBoundingBox().containsPoint(touchLocation)) { characterMoved = true; auto newCoordinate = this->_positionInGameCoordinate(touchLocation); auto newPosition = this->_positionInScene(newCoordinate); auto moveNewPosition = MoveTo::create(RETURN_CHARACTER_DURATION, newPosition); auto actionEnded = CallFunc::create([=]() { this->getGame()->setCharacterPosition(newCoordinate); }); sprite->runAction(Sequence::create(moveNewPosition, actionEnded, NULL)); } } if (!characterMoved) { auto moveBack = MoveTo::create(RETURN_CHARACTER_DURATION, scenePosition); sprite->runAction(moveBack); } }; auto dispatcher = Director::getInstance()->getEventDispatcher(); dispatcher->addEventListenerWithSceneGraphPriority(touchListener, sprite); return sprite; } Layer* GameplayScene::_getObjectsLayer() { return (Layer*) this->getChildByTag(OBJECTS_LAYER_TAG); } Layer* GameplayScene::_getControlsLayer() { return (Layer*) this->getChildByTag(CONTROLS_LAYER_TAG); } Vec2 GameplayScene::_positionInScene(Vec2 gameCoordinate) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = gameCoordinate.x - centerPosition.x; auto offsetY = gameCoordinate.y - centerPosition.y; return Vec2(centerOfScene.x + offsetX * TILE_DIMENSION, centerOfScene.y + offsetY * TILE_DIMENSION); } Vec2 GameplayScene::_positionInGameCoordinate(Vec2 scenePosition) { auto centerPosition = INITIAL_POSITION; auto centerOfScene = this->_centerOfScene(); auto offsetX = scenePosition.x - centerOfScene.x; auto offsetY = scenePosition.y - centerOfScene.y; auto halfTileDimension = TILE_DIMENSION / 2; offsetX > halfTileDimension ? offsetX += halfTileDimension : offsetX -= halfTileDimension; offsetY > halfTileDimension ? offsetY += halfTileDimension : offsetY -= halfTileDimension; return Vec2(centerPosition.x + int(offsetX / TILE_DIMENSION), centerPosition.y + int(offsetY / TILE_DIMENSION)); } void GameplayScene::_adjustCharacterDiceSpritePosition() { auto sprite = this->_getObjectsLayer()->getChildByTag(CHARACTER_DICE_SPRITE_TAG); auto characterPosition = this->getGame()->getCharacterPosition(); sprite->setPosition(this->_positionInScene(characterPosition)); } void GameplayScene::_addOverlayWithVisibleNodes(Vector<Node *> visibleNodes) { auto objectsLayer = this->_getObjectsLayer(); auto overlayLayer = LayerColor::create(Color4B(0, 0, 0, 0)); overlayLayer->setTag(OVERLAY_LAYER_TAG); overlayLayer->setPosition(Vec2(-objectsLayer->getPosition().x, -objectsLayer->getPosition().y)); objectsLayer->addChild(overlayLayer, OVERLAY_Z_ORDER); auto fadeIn = FadeTo::create(OVERLAY_DURATION, OVERLAY_OPACITY); overlayLayer->runAction(fadeIn); for (auto visibleNode : visibleNodes) { auto newZOrder = visibleNode->getLocalZOrder() + OVERLAY_Z_ORDER; visibleNode->setLocalZOrder(newZOrder); } this->setInteractableNodes(visibleNodes); } void GameplayScene::_removeOverlay() { this->_disableInteractions(); auto overlayLayer = this->_getObjectsLayer()->getChildByTag(OVERLAY_LAYER_TAG); auto fadeOut = FadeOut::create(OVERLAY_DURATION); auto changeLayer = CallFunc::create([=]() { for (auto node : this->getInteractableNodes()) { auto oldZOrder = node->getLocalZOrder() - OVERLAY_Z_ORDER; node->setLocalZOrder(oldZOrder); } }); auto removeSelf = RemoveSelf::create(); auto animationEnded = CallFunc::create([=]() { this->_enableInteractions(); }); overlayLayer->runAction(Sequence::create(fadeOut, changeLayer, removeSelf, animationEnded, NULL)); } Vec2 GameplayScene::_centerOfScene() { Vec2 visibleOrigin = Director::getInstance()->getVisibleOrigin(); Size visibleSize = Director::getInstance()->getVisibleSize(); return Vec2(visibleSize.width / 2 + visibleOrigin.x, visibleSize.height / 2 + visibleOrigin.y); } Node* GameplayScene::_getNodeForCharacterPosition() { auto position = this->getGame()->getCharacterPosition(); auto name = this->getGame()->getDungeon()->nameForPosition(position); return this->_getObjectsLayer()->getChildByName(name); } Vector<Node*> GameplayScene::_getNodesForAdjacentCharacterPosition() { Node* activeLayer = this->_getObjectsLayer(); auto overlayLayer = this->getChildByTag(OVERLAY_LAYER_TAG); if (overlayLayer) { activeLayer = overlayLayer; } Vector<Node*> nodes; auto position = this->getGame()->getCharacterPosition(); auto adjacentPositions = this->getGame()->getDungeon()->adjacentPositionsTo(position); for (auto adjacentPosition : adjacentPositions) { auto name = this->getGame()->getDungeon()->nameForPosition(adjacentPosition); nodes.pushBack(activeLayer->getChildByName(name)); } return nodes; } bool GameplayScene::_isInteractionEnabled() { return _userInteractionEnabled; } void GameplayScene::_disableInteractions() { _userInteractionEnabled = false; } void GameplayScene::_enableInteractions() { _userInteractionEnabled = true; }<|endoftext|>
<commit_before>/* * MinimumSpanningTrees.cpp - Main entry point for the program * * Built for EECS2510 - Nonlinear Data Structures * at The University of Toledo, Spring 2016 * * Copyright (c) 2016 Nathan Lowe * * 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 "stdafx.h" #include <cassert> #include <iostream> #include <fstream> #include "LinkedList.h" #include "Options.h" #include "WeightedGraph.h" #include "SpanningTree.h" #include "Verbose.h" #include "PrimVertex.h" using namespace std; // Since the verbose namespace is used multiple times in different files, // we need to define an implementation of the enable flag in exactly one // translation unit so that it is shared between all units namespace verbose { bool enable = false; } // Forward-declare these functions so main can be at the top as required by the project spec void printHelp(); void Kruskal(WeightedGraph& graph); void Prim(WeightedGraph& graph); int main(int argc, char* argv[]) { // parse the command-line arguments auto opts = Options(argc, argv); if (opts.help) { printHelp(); return 0; } if(opts.errors) { cout << "One or more errors occurred while parsing arguments: " << endl; cout << opts.errorMessage; cout << endl; cout << "Call with --help for help" << endl; return -1; } if (opts.verboseEnable) verbose::enable = true; ifstream reader; reader.open(opts.TestFilePath, std::ios::in); if(!reader.good()) { reader.close(); cout << "Unable to open graph for read: '" << opts.TestFilePath << "'" << endl; return -1; } // Load the graph WeightedGraph g(reader); reader.close(); cout << "Finding minimum spanning tree using Kruskal's algorithm..." << endl; try { Kruskal(g); } catch (exception ex) { cout << "Unable to calculate minimum spanning tree: " << ex.what() << endl; } cout << endl << "Finding minimum spanning tree using Prim's algorithm..." << endl; try { Prim(g); } catch (exception ex) { cout << "Unable to calculate minimum spanning tree: " << ex.what() << endl; } return 0; } void printHelp() { cout << "MinimumSpanningTrees <-f path> [-q]" << endl; cout << "Parameters:" << endl; cout << "\t-f, --file\t\tThe input file to test" << endl; cout << "\t-v, --verbose\t\tEnable verbose output" << endl; cout << endl; cout << "At the end of each algorithm, the generated minimum spanning tree in addition to its total" << endl; cout << "weight is printed to standard out. To suppress the printing of the tree, specify the -q flag" << endl; } // Calculate and print out a minimum weight spanning tree of the specified graph using // Kruskal's algorithm: // // For each edge sorted by edge weight ascending // If the edge connects two verticies that are not already in the same group // add them to the tree void Kruskal(WeightedGraph& graph) { auto sets = new LinkedList<Vertex>*[graph.VertexCount]{nullptr}; for(auto i = 0; i < graph.VertexCount; i++) { sets[i] = new LinkedList<Vertex>(); sets[i]->add(graph.Vertices[i]); } verbose::write("[Kruskal] Obtaining edges..."); // Get the edges from the graph // This is a minimum priority queue sorted on edge weight auto edges = graph.Edges(); auto tree = new SpanningTree(); while (!edges->isEmpty()) { // Find the set containing A and B from this edge LinkedList<Vertex> *a = nullptr, *b = nullptr; auto edge = edges->dequeue(); // Locate the vertex sets that contain the vertices of this edge size_t aIndex = 0; size_t bIndex = 0; for(auto index = 0; index < graph.VertexCount; index++) { if(sets[index] != nullptr) { if (sets[index]->Contains(const_cast<Vertex*>(edge->A))) { a = sets[index]; aIndex = index; } if (sets[index]->Contains(const_cast<Vertex*>(edge->B))) { b = sets[index]; bIndex = index; } // If we found the sets that contain this vertex, we can break early if (a != nullptr && b != nullptr) break; } } assert(a != nullptr && b != nullptr && edge != nullptr); if (aIndex != bIndex) { // If the edges belong to different sets, take it verbose::write("[Kruskal] Picking edge " + edge->A->Name + "-" + edge->B->Name + ": " + std::to_string(edge->EdgeWeight)); a->addAll(*b); sets[bIndex] = nullptr; tree->accept(edge); } else { // Otherwise, the edge is redundant verbose::write("[Kruskal] Edge " + edge->A->Name + "-" + edge->B->Name + ": " + std::to_string(edge->EdgeWeight) + " is redundant"); } } // Done! Print out the tree verbose::write("[Kruskal] Done"); tree->print(); } // Calculate and print out a minimum weight spanning tree of the specified graph using // Prim's algorithm: // // Start at any vertex // Until all vertices have been considered // Take the lowest edge connecting the tree to any unconnected vertex void Prim(WeightedGraph& graph) { verbose::write("[Prim] Initializing vertices..."); // We need a queue on a property that gets updated frequently // Wrap the vertices in PrimVertex structures and create a queue for this structure auto pvs = new PrimVertex*[graph.VertexCount]{ nullptr }; auto Q = new MinPriorityQueue<PrimVertex>([](PrimVertex* lhs, PrimVertex* rhs) { return lhs->QKey - rhs->QKey; }, graph.VertexCount); // Initialize all vertices for(auto i = 0; i < graph.VertexCount; i++) { auto pv = new PrimVertex(graph.Vertices[i]); if (i == 0) pv->QKey = 0; pvs[i] = pv; Q->enqueue(pv); } auto tree = new SpanningTree(); // And start taking edges while(!Q->isEmpty()) { auto u = Q->dequeue(); verbose::write("[Prim] Now analyzing connections from " + u->Name + " (local weight: " + to_string(u->QKey) + ")"); // Look at all vertices reachable from the specified vertex for(auto c = 0; c < graph.VertexCount; c++) { auto w = graph.GetWeight(u->ID, c); if (w == 0) continue; auto v = pvs[c]; // Check to see if this is a better way to reach this vertex if(Q->contains(v) && w < v->QKey) { verbose::write( "[Prim] Discovered a better way to get to " + v->Name + " (via " + u->Name + " with weight " + to_string(w) + (v->QKey == INT64_MAX ? "" : ", previous best was " + to_string(v->QKey) + (v->pi == nullptr ? "" : " via " + v->pi->Name)) + ")" ); v->pi = u; v->QKey = w; Q->notifyPriorityUpdated(v); } } } // Now simply work backwards taking the vertex and its parent as an edge for(int i = graph.VertexCount - 1; i >= 0; i--) { auto v = pvs[i]; if (v->pi != nullptr) tree->accept(new VertexPair(v->pi, v, v->QKey)); } // Done! Print the tree verbose::write("[Prim] Done"); tree->print(); } <commit_msg>Fix help<commit_after>/* * MinimumSpanningTrees.cpp - Main entry point for the program * * Built for EECS2510 - Nonlinear Data Structures * at The University of Toledo, Spring 2016 * * Copyright (c) 2016 Nathan Lowe * * 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 "stdafx.h" #include <cassert> #include <iostream> #include <fstream> #include "LinkedList.h" #include "Options.h" #include "WeightedGraph.h" #include "SpanningTree.h" #include "Verbose.h" #include "PrimVertex.h" using namespace std; // Since the verbose namespace is used multiple times in different files, // we need to define an implementation of the enable flag in exactly one // translation unit so that it is shared between all units namespace verbose { bool enable = false; } // Forward-declare these functions so main can be at the top as required by the project spec void printHelp(); void Kruskal(WeightedGraph& graph); void Prim(WeightedGraph& graph); int main(int argc, char* argv[]) { // parse the command-line arguments auto opts = Options(argc, argv); if (opts.help) { printHelp(); return 0; } if(opts.errors) { cout << "One or more errors occurred while parsing arguments: " << endl; cout << opts.errorMessage; cout << endl; cout << "Call with --help for help" << endl; return -1; } if (opts.verboseEnable) verbose::enable = true; ifstream reader; reader.open(opts.TestFilePath, std::ios::in); if(!reader.good()) { reader.close(); cout << "Unable to open graph for read: '" << opts.TestFilePath << "'" << endl; return -1; } // Load the graph WeightedGraph g(reader); reader.close(); cout << "Finding minimum spanning tree using Kruskal's algorithm..." << endl; try { Kruskal(g); } catch (exception ex) { cout << "Unable to calculate minimum spanning tree: " << ex.what() << endl; } cout << endl << "Finding minimum spanning tree using Prim's algorithm..." << endl; try { Prim(g); } catch (exception ex) { cout << "Unable to calculate minimum spanning tree: " << ex.what() << endl; } return 0; } void printHelp() { cout << "MinimumSpanningTrees <-f path> [-v]" << endl; cout << "Parameters:" << endl; cout << "\t-f, --file\t\tThe input file to test" << endl; cout << "\t-v, --verbose\t\tEnable verbose output" << endl; cout << endl; cout << "At the end of each algorithm, the generated minimum spanning tree in addition to its total" << endl; cout << "weight is printed to standard out. To suppress the printing of the tree, specify the -q flag" << endl; } // Calculate and print out a minimum weight spanning tree of the specified graph using // Kruskal's algorithm: // // For each edge sorted by edge weight ascending // If the edge connects two verticies that are not already in the same group // add them to the tree void Kruskal(WeightedGraph& graph) { auto sets = new LinkedList<Vertex>*[graph.VertexCount]{nullptr}; for(auto i = 0; i < graph.VertexCount; i++) { sets[i] = new LinkedList<Vertex>(); sets[i]->add(graph.Vertices[i]); } verbose::write("[Kruskal] Obtaining edges..."); // Get the edges from the graph // This is a minimum priority queue sorted on edge weight auto edges = graph.Edges(); auto tree = new SpanningTree(); while (!edges->isEmpty()) { // Find the set containing A and B from this edge LinkedList<Vertex> *a = nullptr, *b = nullptr; auto edge = edges->dequeue(); // Locate the vertex sets that contain the vertices of this edge size_t aIndex = 0; size_t bIndex = 0; for(auto index = 0; index < graph.VertexCount; index++) { if(sets[index] != nullptr) { if (sets[index]->Contains(const_cast<Vertex*>(edge->A))) { a = sets[index]; aIndex = index; } if (sets[index]->Contains(const_cast<Vertex*>(edge->B))) { b = sets[index]; bIndex = index; } // If we found the sets that contain this vertex, we can break early if (a != nullptr && b != nullptr) break; } } assert(a != nullptr && b != nullptr && edge != nullptr); if (aIndex != bIndex) { // If the edges belong to different sets, take it verbose::write("[Kruskal] Picking edge " + edge->A->Name + "-" + edge->B->Name + ": " + std::to_string(edge->EdgeWeight)); a->addAll(*b); sets[bIndex] = nullptr; tree->accept(edge); } else { // Otherwise, the edge is redundant verbose::write("[Kruskal] Edge " + edge->A->Name + "-" + edge->B->Name + ": " + std::to_string(edge->EdgeWeight) + " is redundant"); } } // Done! Print out the tree verbose::write("[Kruskal] Done"); tree->print(); } // Calculate and print out a minimum weight spanning tree of the specified graph using // Prim's algorithm: // // Start at any vertex // Until all vertices have been considered // Take the lowest edge connecting the tree to any unconnected vertex void Prim(WeightedGraph& graph) { verbose::write("[Prim] Initializing vertices..."); // We need a queue on a property that gets updated frequently // Wrap the vertices in PrimVertex structures and create a queue for this structure auto pvs = new PrimVertex*[graph.VertexCount]{ nullptr }; auto Q = new MinPriorityQueue<PrimVertex>([](PrimVertex* lhs, PrimVertex* rhs) { return lhs->QKey - rhs->QKey; }, graph.VertexCount); // Initialize all vertices for(auto i = 0; i < graph.VertexCount; i++) { auto pv = new PrimVertex(graph.Vertices[i]); if (i == 0) pv->QKey = 0; pvs[i] = pv; Q->enqueue(pv); } auto tree = new SpanningTree(); // And start taking edges while(!Q->isEmpty()) { auto u = Q->dequeue(); verbose::write("[Prim] Now analyzing connections from " + u->Name + " (local weight: " + to_string(u->QKey) + ")"); // Look at all vertices reachable from the specified vertex for(auto c = 0; c < graph.VertexCount; c++) { auto w = graph.GetWeight(u->ID, c); if (w == 0) continue; auto v = pvs[c]; // Check to see if this is a better way to reach this vertex if(Q->contains(v) && w < v->QKey) { verbose::write( "[Prim] Discovered a better way to get to " + v->Name + " (via " + u->Name + " with weight " + to_string(w) + (v->QKey == INT64_MAX ? "" : ", previous best was " + to_string(v->QKey) + (v->pi == nullptr ? "" : " via " + v->pi->Name)) + ")" ); v->pi = u; v->QKey = w; Q->notifyPriorityUpdated(v); } } } // Now simply work backwards taking the vertex and its parent as an edge for(int i = graph.VertexCount - 1; i >= 0; i--) { auto v = pvs[i]; if (v->pi != nullptr) tree->accept(new VertexPair(v->pi, v, v->QKey)); } // Done! Print the tree verbose::write("[Prim] Done"); tree->print(); } <|endoftext|>
<commit_before>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cassert> #include <iostream> #include <cstdlib> #if 0 #include <unistd.h> #include "itkTimeProbe.h" #endif #include "itkMacro.h" #include "otbStopwatch.h" int otbStopwatchTest(int itkNotUsed(argc), char * itkNotUsed(argv)[]) { otb::Stopwatch sw; assert( !sw.IsRunning() ); assert( sw.GetElapsedMilliseconds() == 0 ); sw.Start(); assert( sw.IsRunning() ); sw.Stop(); sw.Reset(); assert( !sw.IsRunning() ); assert( sw.GetElapsedMilliseconds() == 0 ); sw = otb::Stopwatch::StartNew(); assert( sw.IsRunning() ); sw.Stop(); #if 0 // We have no portable sleep() and otbThreads is not linked here sw.Start(); usleep(500 * 1000); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 450 && sw.GetElapsedMilliseconds() < 550 ); sw.Start(); usleep(500 * 1000); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 900 && sw.GetElapsedMilliseconds() < 1100 ); sw.Restart(); usleep(500 * 1000); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 450 && sw.GetElapsedMilliseconds() < 550 ); const int iterations = 100000; sw.Restart(); for (int i = 0; i < iterations; i++) { itk::TimeProbe chrono; chrono.Start(); chrono.Stop(); } std::cerr << "itk::TimeProbe time: " << sw.GetElapsedMilliseconds() << std::endl; sw.Restart(); for (int i = 0; i < iterations; i++) { auto chrono = otb::Stopwatch::StartNew(); chrono.Stop(); } std::cerr << "otb::Stopwatch time: " << sw.GetElapsedMilliseconds() << std::endl; #endif return EXIT_SUCCESS; } <commit_msg>ENH: Enable otb::Stopwatch tests<commit_after>/* * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES) * * This file is part of Orfeo Toolbox * * https://www.orfeo-toolbox.org/ * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cassert> #include <chrono> #include <iostream> #include <cstdlib> #include <thread> #include "itkMacro.h" #include "otbStopwatch.h" using namespace std::chrono_literals; int otbStopwatchTest(int itkNotUsed(argc), char * itkNotUsed(argv)[]) { otb::Stopwatch sw; assert( !sw.IsRunning() ); assert( sw.GetElapsedMilliseconds() == 0 ); sw.Start(); assert( sw.IsRunning() ); sw.Stop(); sw.Reset(); assert( !sw.IsRunning() ); assert( sw.GetElapsedMilliseconds() == 0 ); sw = otb::Stopwatch::StartNew(); assert( sw.IsRunning() ); sw.Stop(); // We have no portable sleep() and otbThreads is not linked here sw.Start(); std::this_thread::sleep_for(500ms); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 450 && sw.GetElapsedMilliseconds() < 550 ); sw.Start(); std::this_thread::sleep_for(500ms); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 900 && sw.GetElapsedMilliseconds() < 1100 ); sw.Restart(); std::this_thread::sleep_for(500ms); sw.Stop(); assert( sw.GetElapsedMilliseconds() > 450 && sw.GetElapsedMilliseconds() < 550 ); return EXIT_SUCCESS; } <|endoftext|>
<commit_before> #include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/UFile.h> #include <rtabmap/core/CameraThread.h> #include <rtabmap/core/CameraRGBD.h> #include <rtabmap/core/Camera.h> #include <rtabmap/core/CameraThread.h> #include <rtabmap/gui/DataRecorder.h> #include <QtGui/QApplication> #include <signal.h> using namespace rtabmap; void showUsage() { printf("\nUsage:\n" "dataRecorder [options] output.db\n" "Options:\n" " -hide Don't display the current cloud recorded.\n" " -debug Set debug level for the logger.\n" " -rate #.# Input rate Hz (default 0=inf)\n" " -openni Use openni camera instead of the usb camera.\n"); exit(1); } rtabmap::CameraThread * cam = 0; QApplication * app = 0; // catch ctrl-c void sighandler(int sig) { printf("\nSignal %d caught...\n", sig); if(cam) { cam->join(true); } if(app) { QMetaObject::invokeMethod(app, "quit"); } } int main (int argc, char * argv[]) { ULogger::setType(ULogger::kTypeConsole); ULogger::setLevel(ULogger::kInfo); // parse arguments QString fileName; bool show = true; bool openni = false; float rate = 0.0f; if(argc < 2) { showUsage(); } for(int i=1; i<argc-1; ++i) { if(strcmp(argv[i], "-rate") == 0) { ++i; if(i < argc) { rate = std::atof(argv[i]); if(rate < 0.0f) { showUsage(); } } else { showUsage(); } continue; } if(strcmp(argv[i], "-debug") == 0) { ULogger::setLevel(ULogger::kDebug); continue; } if(strcmp(argv[i], "-hide") == 0) { show = false; continue; } if(strcmp(argv[i], "-openni") == 0) { openni = true; continue; } printf("Unrecognized option : %s\n", argv[i]); showUsage(); } fileName = argv[argc-1]; // the last is the output path if(UFile::getExtension(fileName.toStdString()).compare("db") != 0) { printf("Database names must end with .db extension\n"); showUsage(); } UINFO("Output = %s", fileName.toStdString().c_str()); UINFO("Show = %s", show?"true":"false"); UINFO("Openni = %s", openni?"true":"false"); UINFO("Rate =%f Hz", rate); app = new QApplication(argc, argv); // Catch ctrl-c to close the gui // (Place this after QApplication's constructor) signal(SIGABRT, &sighandler); signal(SIGTERM, &sighandler); signal(SIGINT, &sighandler); if(openni) { cam = new rtabmap::CameraThread(new rtabmap::CameraOpenni("", rate, rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0))); } else { cam = new rtabmap::CameraThread(new rtabmap::CameraVideo(0, rate)); } DataRecorder recorder; if(recorder.init(fileName)) { recorder.registerToEventsManager(); if(show) { recorder.setWindowTitle("Cloud viewer"); recorder.setMinimumWidth(500); recorder.setMinimumHeight(300); recorder.showNormal(); app->processEvents(); } if(cam->init()) { cam->start(); app->exec(); UINFO("Closing..."); recorder.close(); } else { UERROR("Cannot initialize the camera!"); } } else { UERROR("Cannot initialize the recorder! Maybe the path is wrong: \"%s\"", fileName.toStdString().c_str()); } if(cam) { delete cam; } return 0; } <commit_msg>added openni2 option to dataRecorder app<commit_after> #include <rtabmap/utilite/ULogger.h> #include <rtabmap/utilite/UFile.h> #include <rtabmap/core/CameraThread.h> #include <rtabmap/core/CameraRGBD.h> #include <rtabmap/core/Camera.h> #include <rtabmap/core/CameraThread.h> #include <rtabmap/gui/DataRecorder.h> #include <QtGui/QApplication> #include <signal.h> using namespace rtabmap; void showUsage() { printf("\nUsage:\n" "dataRecorder [options] output.db\n" "Options:\n" " -hide Don't display the current cloud recorded.\n" " -debug Set debug level for the logger.\n" " -rate #.# Input rate Hz (default 0=inf)\n" " -openni Use openni camera instead of the usb camera.\n" " -openni2 Use openni2 camera instead of the usb camera.\n"); exit(1); } rtabmap::CameraThread * cam = 0; QApplication * app = 0; // catch ctrl-c void sighandler(int sig) { printf("\nSignal %d caught...\n", sig); if(cam) { cam->join(true); } if(app) { QMetaObject::invokeMethod(app, "quit"); } } int main (int argc, char * argv[]) { ULogger::setType(ULogger::kTypeConsole); ULogger::setLevel(ULogger::kInfo); // parse arguments QString fileName; bool show = true; bool openni = false; bool openni2 = false; float rate = 0.0f; if(argc < 2) { showUsage(); } for(int i=1; i<argc-1; ++i) { if(strcmp(argv[i], "-rate") == 0) { ++i; if(i < argc) { rate = std::atof(argv[i]); if(rate < 0.0f) { showUsage(); } } else { showUsage(); } continue; } if(strcmp(argv[i], "-debug") == 0) { ULogger::setLevel(ULogger::kDebug); continue; } if(strcmp(argv[i], "-hide") == 0) { show = false; continue; } if(strcmp(argv[i], "-openni") == 0) { openni = true; continue; } if(strcmp(argv[i], "-openni2") == 0) { openni2 = true; continue; } printf("Unrecognized option : %s\n", argv[i]); showUsage(); } fileName = argv[argc-1]; // the last is the output path if(UFile::getExtension(fileName.toStdString()).compare("db") != 0) { printf("Database names must end with .db extension\n"); showUsage(); } UINFO("Output = %s", fileName.toStdString().c_str()); UINFO("Show = %s", show?"true":"false"); UINFO("Openni = %s", openni?"true":"false"); UINFO("Rate =%f Hz", rate); app = new QApplication(argc, argv); // Catch ctrl-c to close the gui // (Place this after QApplication's constructor) signal(SIGABRT, &sighandler); signal(SIGTERM, &sighandler); signal(SIGINT, &sighandler); if(openni2) { cam = new rtabmap::CameraThread(new rtabmap::CameraOpenNI2(rate, rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0))); } else if(openni) { cam = new rtabmap::CameraThread(new rtabmap::CameraOpenni("", rate, rtabmap::Transform(0,0,1,0, -1,0,0,0, 0,-1,0,0))); } else { cam = new rtabmap::CameraThread(new rtabmap::CameraVideo(0, rate)); } DataRecorder recorder; if(recorder.init(fileName)) { recorder.registerToEventsManager(); if(show) { recorder.setWindowTitle("Cloud viewer"); recorder.setMinimumWidth(500); recorder.setMinimumHeight(300); recorder.showNormal(); app->processEvents(); } if(cam->init()) { cam->start(); app->exec(); UINFO("Closing..."); recorder.close(); } else { UERROR("Cannot initialize the camera!"); } } else { UERROR("Cannot initialize the recorder! Maybe the path is wrong: \"%s\"", fileName.toStdString().c_str()); } if(cam) { delete cam; } return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; template <class Simplex> std::string formatSimplex( const Simplex& s ) { std::ostringstream stream; stream << "{"; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) stream << ","; stream << *it; } stream << "}"; return stream.str(); } int main( int argc, char** argv ) { if( argc <= 2 ) { // TODO: Show usage return -1; } std::string filename = argv[1]; double threshold = std::stod( argv[2] ); SimplicialComplex K; // Input ------------------------------------------------------------- // // TODO: This is copied from the clique persistence diagram // calculation. It would make sense to share some functions // between the two applications. std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; // Thresholding ------------------------------------------------------ { std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "..."; std::vector<Simplex> simplices; std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ), [&threshold] ( const Simplex& s ) { return s.data() > threshold; } ); K = SimplicialComplex( simplices.begin(), simplices.end() ); std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- unsigned maxK = 12; aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; auto uf = aleph::topology::calculateConnectedComponents( C ); std::set<VertexType> roots; uf.roots( std::inserter( roots, roots.begin() ) ); std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n"; for( auto&& root : roots ) { // The vertex IDs stored in the Union--Find data structure // correspond to the indices of the simplicial complex. It // thus suffices to map them back. std::set<VertexType> vertices; uf.get( root, std::inserter( vertices, vertices.begin() ) ); std::vector<Simplex> simplices; std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ), [&K] ( VertexType v ) { return K.at(v); } ); std::sort( simplices.begin(), simplices.end() ); std::cout << "["; for( auto it = simplices.begin(); it != simplices.end(); ++it ) { if( it != simplices.begin() ) std::cout << ","; std::cout << formatSimplex( *it ); } std::cout << "]\n"; } std::cout << "\n\n"; } } <commit_msg>Added usage information & maximum k parameter<commit_after>#include <algorithm> #include <fstream> #include <iostream> #include <iterator> #include <set> #include <string> #include <sstream> #include <cmath> #include "filtrations/Data.hh" #include "geometry/RipsExpander.hh" #include "persistentHomology/ConnectedComponents.hh" #include "topology/CliqueGraph.hh" #include "topology/ConnectedComponents.hh" #include "topology/Simplex.hh" #include "topology/SimplicialComplex.hh" #include "topology/io/EdgeLists.hh" #include "topology/io/GML.hh" #include "utilities/Filesystem.hh" using DataType = double; using VertexType = unsigned; using Simplex = aleph::topology::Simplex<DataType, VertexType>; using SimplicialComplex = aleph::topology::SimplicialComplex<Simplex>; template <class Simplex> std::string formatSimplex( const Simplex& s ) { std::ostringstream stream; stream << "{"; for( auto it = s.begin(); it != s.end(); ++it ) { if( it != s.begin() ) stream << ","; stream << *it; } stream << "}"; return stream.str(); } void usage() { std::cerr << "Usage: clique_communities FILE THRESHOLD K\n" << "\n" << "Extracts clique communities from FILE, which is supposed to be\n" << "a weighted graph. In the subsequent calculation, an edge whose\n" << "weight is larger than THRESHOLD will be ignored. K denotes the\n" << "maximum dimension of a simplex for the clique graph extraction\n" << "and the clique community calculation. This does not correspond\n" << "to the dimensionality of the clique. Hence, a parameter of K=2\n" << "will result in calculating 3-clique communities because all of\n" << "the 2-simplices have 3 vertices.\n\n"; } int main( int argc, char** argv ) { if( argc <= 3 ) { usage(); return -1; } std::string filename = argv[1]; double threshold = std::stod( argv[2] ); unsigned maxK = static_cast<unsigned>( std::stoul( argv[3] ) ); SimplicialComplex K; // Input ------------------------------------------------------------- // // TODO: This is copied from the clique persistence diagram // calculation. It would make sense to share some functions // between the two applications. std::cerr << "* Reading '" << filename << "'..."; if( aleph::utilities::extension( filename ) == ".gml" ) { aleph::topology::io::GMLReader reader; reader( filename, K ); } else { aleph::io::EdgeListReader reader; reader.setReadWeights( true ); reader.setTrimLines( true ); reader( filename, K ); } std::cerr << "finished\n"; // Thresholding ------------------------------------------------------ { std::cerr << "* Filtering input data to threshold epsilon=" << threshold << "..."; std::vector<Simplex> simplices; std::remove_copy_if( K.begin(), K.end(), std::back_inserter( simplices ), [&threshold] ( const Simplex& s ) { return s.data() > threshold; } ); K = SimplicialComplex( simplices.begin(), simplices.end() ); std::cerr << "finished\n"; } // Expansion --------------------------------------------------------- aleph::geometry::RipsExpander<SimplicialComplex> ripsExpander; K = ripsExpander( K, maxK ); K = ripsExpander.assignMaximumWeight( K ); K.sort( aleph::filtrations::Data<Simplex>() ); for( unsigned k = 1; k <= maxK; k++ ) { std::cerr << "* Extracting " << k << "-cliques graph..."; auto C = aleph::topology::getCliqueGraph( K, k ); C.sort( aleph::filtrations::Data<Simplex>() ); std::cerr << "finished\n"; std::cerr << "* " << k << "-cliques graph has " << C.size() << " simplices\n"; auto uf = aleph::topology::calculateConnectedComponents( C ); std::set<VertexType> roots; uf.roots( std::inserter( roots, roots.begin() ) ); std::cerr << "* " << k << "-cliques graph has " << roots.size() << " connected components\n"; for( auto&& root : roots ) { // The vertex IDs stored in the Union--Find data structure // correspond to the indices of the simplicial complex. It // thus suffices to map them back. std::set<VertexType> vertices; uf.get( root, std::inserter( vertices, vertices.begin() ) ); std::vector<Simplex> simplices; std::transform( vertices.begin(), vertices.end(), std::back_inserter( simplices ), [&K] ( VertexType v ) { return K.at(v); } ); std::sort( simplices.begin(), simplices.end() ); std::cout << "["; for( auto it = simplices.begin(); it != simplices.end(); ++it ) { if( it != simplices.begin() ) std::cout << ","; std::cout << formatSimplex( *it ); } std::cout << "]\n"; } std::cout << "\n\n"; } } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <unistd.h> #include <vector> #include <atomic> #include <signal.h> #include <getopt.h> #include "zcm/zcm-cpp.hpp" using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { vector<string> Achannels; vector<string> Bchannels; string Aurl = ""; string Burl = ""; bool parse(int argc, char *argv[]) { // set some defaults const char *optstring = "hA:B:a:b:"; struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "A-endpt", required_argument, 0, 'A'}, { "B-endpt", required_argument, 0, 'B'}, { "A-channel", required_argument, 0, 'a' }, { "B-channel", required_argument, 0, 'b' }, { 0, 0, 0, 0 } }; int c; while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) { switch (c) { case 'A': Aurl = optarg; break; case 'B': Burl = optarg; break; case 'a': Achannels.push_back(optarg); break; case 'b': Bchannels.push_back(optarg); break; case 'h': default: return false; }; } if (Aurl == "") { cerr << "Please specify A endpt url with the -A option" << endl; return false; } if (Burl == "") { cerr << "Please specify B endpt url with the -B option" << endl; return false; } if (Aurl == Burl) { cerr << "A and B endpoint urls must be unique" << endl; return false; } return true; } }; struct Bridge { Args args; zcm::ZCM *zcmA = nullptr; zcm::ZCM *zcmB = nullptr; Bridge() {} ~Bridge() { if (zcmA) delete zcmA; if (zcmB) delete zcmB; } bool init(int argc, char *argv[]) { if (!args.parse(argc, argv)) return false; // A endpoint network zcmA = new zcm::ZCM(args.Aurl); if (!zcmA->good()) { cerr << "Couldn't initialize A endpoint ZCM network! " "Please check your A endpoint transport url." << endl << endl; delete zcmA; zcmA = nullptr; return false; } // B endpoint network zcmB = new zcm::ZCM(args.Burl); if (!zcmB->good()) { cerr << "Couldn't initialize B endpoint ZCM network! " "Please check your B endpoint transport url." << endl << endl; delete zcmB; zcmB = nullptr; return false; } return true; } static void handler(const zcm::ReceiveBuffer* rbuf, const string& channel, void* usr) { ((zcm::ZCM*)usr)->publish(channel, rbuf->data, rbuf->data_size); } void run() { if (args.Achannels.size() == 0) { zcmA->subscribe(".*", &handler, zcmB); } else { for (auto iter : args.Achannels) zcmA->subscribe(iter, &handler, zcmB); } if (args.Bchannels.size() == 0) { zcmB->subscribe(".*", &handler, zcmA); } else { for (auto iter : args.Bchannels) zcmB->subscribe(iter, &handler, zcmA); } zcmA->start(); zcmB->start(); while (!done) usleep(1e6); zcmA->stop(); zcmB->stop(); zcmA->flush(); zcmB->flush(); } }; static void usage() { cerr << "usage: zcm-bridge [options]" << endl << "" << endl << " ZCM bridge utility. Bridges all data from one ZCM network to another." << endl << "" << endl << "Example:" << endl << " zcm-bridge -A ipc -B udpm://239.255.76.67:7667?ttl=0" << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -A, --A-enpt=URL One end of the bridge. Ex: zcm-bridge -A ipc" << endl << " -B, --B-endpt=URL One end of the bridge. Ex: zcm-bridge -B udpm://239.255.76.67:7667?ttl=0" << endl << " -a, --A-channel=CHANNEL One channel to subscribe to on A and repeat to B." << endl << " This argument can be specified multiple times. If this option is not," << endl << " present then we subscribe to all messages on the A interface." << endl << " Ex: zcm-bridge -A ipc -a EXAMPLE -B udpm://239.255.76.67:7667?ttl=0" << endl << " -b, --B-channel=CHANNEL One channel to subscribe to on B and repeat to A." << endl << " This argument can be specified multiple times. If this option is not," << endl << " present then we subscribe to all messages on the B interface." << endl << " Ex: zcm-bridge -A ipc -B udpm://239.255.76.67:7667?ttl=0 -b EXAMPLE" << endl << "" << endl << endl; } int main(int argc, char *argv[]) { Bridge bridge{}; if (!bridge.init(argc, argv)) { usage(); return 1; } // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); bridge.run(); cerr << "Bridge exiting" << endl; return 0; } <commit_msg>added decimation and channel prefixing to zcm bridge<commit_after>#include <iostream> #include <string> #include <unistd.h> #include <vector> #include <atomic> #include <signal.h> #include <getopt.h> #include "zcm/zcm-cpp.hpp" using namespace std; static atomic_int done {0}; static void sighandler(int signal) { done++; if (done == 3) exit(1); } struct Args { vector<string> Achannels; vector<string> Bchannels; vector<int> Adec; vector<int> Bdec; string Aurl = ""; string Burl = ""; string Aprefix = ""; string Bprefix = ""; bool parse(int argc, char *argv[]) { // set some defaults const char *optstring = "hp:r:A:B:a:b:d:"; struct option long_opts[] = { { "help", no_argument, 0, 'h' }, { "prefix-a", required_argument, 0, 'p' }, { "prefix-b", required_argument, 0, 'r' }, { "A-endpt", required_argument, 0, 'A' }, { "B-endpt", required_argument, 0, 'B' }, { "A-channel", required_argument, 0, 'a' }, { "B-channel", required_argument, 0, 'b' }, { "decimation", required_argument, 0, 'd' }, { 0, 0, 0, 0 } }; int c; vector<int> *currDec = nullptr; while ((c = getopt_long (argc, argv, optstring, long_opts, 0)) >= 0) { switch (c) { case 'p': currDec = nullptr; Aprefix = optarg; break; case 'r': currDec = nullptr; Bprefix = optarg; break; case 'A': currDec = nullptr; Aurl = optarg; break; case 'B': currDec = nullptr; Burl = optarg; break; case 'a': Achannels.push_back(optarg); Adec.push_back(0); currDec = &Adec; break; case 'b': Bchannels.push_back(optarg); Bdec.push_back(0); currDec = &Bdec; break; case 'd': ZCM_ASSERT(currDec != nullptr && "Decimation must immediately follow a channel"); currDec->back() = atoi(optarg); currDec = nullptr; break; case 'h': default: return false; }; } if (Aurl == "") { cerr << "Please specify A endpt url with the -A option" << endl; return false; } if (Burl == "") { cerr << "Please specify B endpt url with the -B option" << endl; return false; } if (Aurl == Burl) { cerr << "A and B endpoint urls must be unique" << endl; return false; } return true; } }; struct Bridge { Args args; zcm::ZCM *zcmA = nullptr; zcm::ZCM *zcmB = nullptr; struct BridgeInfo { zcm::ZCM *zcmOut = nullptr; string prefix = ""; int decimation = 0; int nSkipped = 0; BridgeInfo(zcm::ZCM* zcmOut, const string &prefix, int dec) : zcmOut(zcmOut), prefix(prefix), decimation(dec), nSkipped(0) {} BridgeInfo() {} }; Bridge() {} ~Bridge() { if (zcmA) delete zcmA; if (zcmB) delete zcmB; } bool init(int argc, char *argv[]) { if (!args.parse(argc, argv)) return false; // A endpoint network zcmA = new zcm::ZCM(args.Aurl); if (!zcmA->good()) { cerr << "Couldn't initialize A endpoint ZCM network! " "Please check your A endpoint transport url." << endl << endl; delete zcmA; zcmA = nullptr; return false; } // B endpoint network zcmB = new zcm::ZCM(args.Burl); if (!zcmB->good()) { cerr << "Couldn't initialize B endpoint ZCM network! " "Please check your B endpoint transport url." << endl << endl; delete zcmB; zcmB = nullptr; return false; } return true; } static void handler(const zcm::ReceiveBuffer* rbuf, const string& channel, void* usr) { BridgeInfo* info = (BridgeInfo*)usr; if (info->nSkipped == info->decimation) { string newChannel = info->prefix + channel; info->zcmOut->publish(newChannel, rbuf->data, rbuf->data_size); info->nSkipped = 0; } else { info->nSkipped++; } } void run() { vector<BridgeInfo> infoA, infoB; infoA.reserve(args.Achannels.size()); infoB.reserve(args.Bchannels.size()); BridgeInfo defaultA(zcmB, args.Bprefix, 0), defaultB(zcmA, args.Aprefix, 0); if (args.Achannels.size() == 0) { zcmA->subscribe(".*", &handler, &defaultA); } else { for (size_t i = 0; i < args.Achannels.size(); i++) { infoA.emplace_back(zcmB, args.Bprefix, args.Adec.at(i)); zcmA->subscribe(args.Achannels.at(i), &handler, &infoA.back()); } } if (args.Bchannels.size() == 0) { zcmB->subscribe(".*", &handler, &defaultB); } else { for (size_t i = 0; i < args.Bchannels.size(); i++) { infoB.emplace_back(zcmA, args.Aprefix, args.Bdec.at(i)); zcmB->subscribe(args.Bchannels.at(i), &handler, &infoB.back()); } } ZCM_ASSERT(infoA.size() == args.Achannels.size() && infoA.size() == args.Adec.size() && infoB.size() == args.Bchannels.size() && infoB.size() == args.Bdec.size()); zcmA->start(); zcmB->start(); while (!done) usleep(1e6); zcmA->stop(); zcmB->stop(); zcmA->flush(); zcmB->flush(); } }; static void usage() { cerr << "usage: zcm-bridge [options]" << endl << "" << endl << " ZCM bridge utility. Bridges all data from one ZCM network to another." << endl << "" << endl << "Example:" << endl << " zcm-bridge -A ipc -B udpm://239.255.76.67:7667?ttl=0" << endl << "" << endl << "Options:" << endl << "" << endl << " -h, --help Shows this help text and exits" << endl << " -A, --A-enpt=URL One end of the bridge. Ex: zcm-bridge -A ipc" << endl << " -B, --B-endpt=URL One end of the bridge. Ex: zcm-bridge -B udpm://239.255.76.67:7667?ttl=0" << endl << " -p, --prefix-a Specify a prefix for all messages published on the A url" << endl << " -r, --prefix-b Specify a prefix for all messages published on the B url" << endl << " -a, --A-channel=CHANNEL One channel to subscribe to on A and repeat to B." << endl << " This argument can be specified multiple times. If this option is not," << endl << " present then we subscribe to all messages on the A interface." << endl << " Ex: zcm-bridge -A ipc -a EXAMPLE -B udpm://239.255.76.67:7667?ttl=0" << endl << " -b, --B-channel=CHANNEL One channel to subscribe to on B and repeat to A." << endl << " This argument can be specified multiple times. If this option is not," << endl << " present then we subscribe to all messages on the B interface." << endl << " Ex: zcm-bridge -A ipc -B udpm://239.255.76.67:7667?ttl=0 -b EXAMPLE" << endl << " -d, --decimation Decimation level for the preceeding A-channel or B-channel. " << endl << " Ex: zcm-bridge -A ipc -B udpm://239.255.76.67:7667?ttl=0 -b EXAMPLE -d 2" << endl << " This example would result in the message on EXAMPLE being rebroadcast on" << endl << " the A url every third message." << endl << "" << endl << endl; } int main(int argc, char *argv[]) { Bridge bridge{}; if (!bridge.init(argc, argv)) { usage(); return 1; } // Register signal handlers signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); bridge.run(); cerr << "Bridge exiting" << endl; return 0; } <|endoftext|>
<commit_before>#include "Common.hpp" #include "MsgDisplay.hpp" #include "TypeDb.hpp" #include "MsgInfo.hpp" #include "Debug.hpp" #define SELECT_TIMEOUT 20000 #define ESCAPE_KEY 0x1B #define DEL_KEY 0x7f static volatile bool quit = false; enum class DisplayMode { Overview, Decode, }; struct SpyInfo { SpyInfo(const char *path, bool debug) : typedb(path, debug) { } ~SpyInfo() { for (auto& it : minfomap) delete it.second; } MsgInfo *getCurrentMsginfo(const char **channel) { auto& ch = names[decode_index]; MsgInfo **m = lookup(minfomap, ch); assert(m); if (channel) *channel = ch.c_str(); return *m; } bool isValidChannelnum(size_t index) { return (0 <= index && index < names.size()); } void addMessage(const char *channel, const zcm_recv_buf_t *rbuf); void display(); void displayOverview(); void handleKeyboard(char ch); void handleKeyboardOverview(char ch); void handleKeyboardDecode(char ch); private: vector<string> names; unordered_map<string, MsgInfo*> minfomap; TypeDb typedb; mutex mut; DisplayMode mode = DisplayMode::Overview; bool is_selecting = false; int decode_index = 0; MsgInfo *decode_msg_info; const char *decode_msg_channel; }; void SpyInfo::addMessage(const char *channel, const zcm_recv_buf_t *rbuf) { unique_lock<mutex> lk(mut); MsgInfo *minfo = minfomap[channel]; if (minfo == NULL) { minfo = new MsgInfo(typedb, channel); names.push_back(channel); std::sort(begin(names), end(names)); minfomap[channel] = minfo; } minfo->addMessage(TimeUtil::utime(), rbuf); } void SpyInfo::display() { unique_lock<mutex> lk(mut); switch (mode) { case DisplayMode::Overview: { displayOverview(); } break; case DisplayMode::Decode: { decode_msg_info->display(); } break; default: DEBUG(1, "ERR: unknown mode\n"); } } void SpyInfo::displayOverview() { printf(" %-28s\t%12s\t%8s\n", "Channel", "Num Messages", "Hz (ave)"); printf(" ----------------------------------------------------------------\n"); DEBUG(5, "start-loop\n"); for (size_t i = 0; i < names.size(); i++) { auto& channel = names[i]; MsgInfo **minfo = lookup(minfomap, channel); assert(minfo != NULL); float hz = (*minfo)->getHertz(); printf(" %3zu) %-28s\t%9" PRIu64 "\t%7.2f\n", i, channel.c_str(), (*minfo)->getNumMsgs(), hz); } printf("\n"); if (is_selecting) { printf(" Decode channel: "); if (decode_index != -1) printf("%d", decode_index); fflush(stdout); } } void SpyInfo::handleKeyboardOverview(char ch) { if (ch == '-') { is_selecting = true; decode_index = -1; } else if ('0' <= ch && ch <= '9') { // shortcut for single digit channels if (!is_selecting) { decode_index = ch - '0'; if (isValidChannelnum(decode_index)) { decode_msg_info = getCurrentMsginfo(&decode_msg_channel); mode = DisplayMode::Decode; } } else { if (decode_index == -1) { decode_index = ch - '0'; } else if (decode_index < 10000) { decode_index *= 10; decode_index += (ch - '0'); } } } else if (ch == '\n') { if (is_selecting) { if (isValidChannelnum(decode_index)) { decode_msg_info = getCurrentMsginfo(&decode_msg_channel); mode = DisplayMode::Decode; } is_selecting = false; } } else if (ch == '\b' || ch == DEL_KEY) { if (is_selecting) { if (decode_index < 10) decode_index = -1; else decode_index /= 10; } } else { DEBUG(1, "INFO: unrecognized input: '%c' (0x%2x)\n", ch, ch); } } void SpyInfo::handleKeyboardDecode(char ch) { MsgInfo& minfo = *decode_msg_info; size_t depth = minfo.getViewDepth(); if (ch == ESCAPE_KEY) { if (depth > 0) { minfo.decViewDepth(); } else { mode = DisplayMode::Overview; } } else if ('0' <= ch && ch <= '9') { // if number is pressed, set and increase sub-msg decoding depth size_t viewid = (ch - '0'); if (depth < MSG_DISPLAY_RECUR_MAX) { minfo.incViewDepth(viewid); } else { DEBUG(1, "INFO: cannot recurse further: reached maximum depth of %d\n", MSG_DISPLAY_RECUR_MAX); } } else { DEBUG(1, "INFO: unrecognized input: '%c' (0x%2x)\n", ch, ch); } } void SpyInfo::handleKeyboard(char ch) { unique_lock<mutex> lk(mut); switch (mode) { case DisplayMode::Overview: handleKeyboardOverview(ch); break; case DisplayMode::Decode: handleKeyboardDecode(ch); break; default: DEBUG(1, "INFO: unrecognized keyboard mode: %d\n", (int)mode); } } void *keyboard_thread_func(void *arg) { SpyInfo *spy = (SpyInfo *)arg; struct termios old = {0}; if (tcgetattr(0, &old) < 0) perror("tcsetattr()"); struct termios newt = old; newt.c_lflag &= ~ICANON; newt.c_lflag &= ~ECHO; newt.c_cc[VMIN] = 1; newt.c_cc[VTIME] = 0; if (tcsetattr(0, TCSANOW, &newt) < 0) perror("tcsetattr ICANON"); char ch; while(!quit) { fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); struct timeval timeout = { 0, SELECT_TIMEOUT }; int status = select(1, &fds, 0, 0, &timeout); if(quit) break; if(status != 0 && FD_ISSET(0, &fds)) { if(read(0, &ch, 1) < 0) perror ("read()"); spy->handleKeyboard(ch); } else { DEBUG(4, "INFO: keyboard_thread_func select() timeout\n"); } } if (tcsetattr(0, TCSADRAIN, &old) < 0) perror ("tcsetattr ~ICANON"); return NULL; } ////////////////////////////////////////////////////////////////////// ////////////////////////// Helper Functions ////////////////////////// ////////////////////////////////////////////////////////////////////// void clearscreen() { // clear printf("\033[2J"); // move cursor to (0, 0) printf("\033[0;0H"); } ////////////////////////////////////////////////////////////////////// //////////////////////////// Print Thread //////////////////////////// ////////////////////////////////////////////////////////////////////// void printThreadFunc(SpyInfo *spy) { static constexpr float hz = 20.0; static constexpr u64 period = 1000000 / hz; DEBUG(1, "INFO: %s: Starting\n", "print_thread"); while (!quit) { usleep(period); clearscreen(); printf(" **************************************************************************** \n"); printf(" ******************************* ZCM-SPY-LITE ******************************* \n"); printf(" **************************************************************************** \n"); spy->display(); // flush the stdout buffer (required since we use full buffering) fflush(stdout); } DEBUG(1, "INFO: %s: Ending\n", "print_thread"); } ////////////////////////////////////////////////////////////////////// ///////////////////////////// LCM HANDLER //////////////////////////// ////////////////////////////////////////////////////////////////////// void handler_all_zcm (const zcm_recv_buf_t *rbuf, const char *channel, void *arg) { SpyInfo *spy = (SpyInfo *)arg; spy->addMessage(channel, rbuf); } ////////////////////////////////////////////////////////////////////// ////////////////////////////////// MAIN ////////////////////////////// ////////////////////////////////////////////////////////////////////// static void sighandler(int s) { switch(s) { case SIGQUIT: case SIGINT: case SIGTERM: DEBUG(1, "Caught signal...\n"); quit = true; break; default: DEBUG(1, "WRN: unrecognized signal fired\n"); break; } } int main(int argc, char *argv[]) { DEBUG_INIT(); bool debug = false; // XXX get opt if(argc > 1 && strcmp(argv[1], "--debug") == 0) debug = true; // get the zcmtypes.so from ZCM_SPY_LITE_PATH const char *spy_lite_path = getenv("ZCM_SPY_LITE_PATH"); if (debug) printf("zcm_spy_lite_path='%s'\n", spy_lite_path); if (spy_lite_path == NULL) { fprintf(stderr, "ERR: invalid $ZCM_SPY_LITE_PATH\n"); return 1; } SpyInfo spy {spy_lite_path, debug}; if (debug) exit(0); signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); // configure stdout buffering: use FULL buffering to avoid flickering setvbuf(stdout, NULL, _IOFBF, 2048); // start zcm zcm_t *zcm = zcm_create(NULL); if (!zcm) { DEBUG(1, "ERR: failed to create an zcm object!\n"); return 1; } zcm_subscribe(zcm, ".*", handler_all_zcm, &spy); zcm_start(zcm); thread printThread {printThreadFunc, &spy}; // use this thread as the keyboard thread keyboard_thread_func(&spy); // cleanup printThread.join(); zcm_stop(zcm); DEBUG(1, "Exiting...\n"); return 0; } <commit_msg>Now accepts multidigit field decoding via dash operator<commit_after>#include "Common.hpp" #include "MsgDisplay.hpp" #include "TypeDb.hpp" #include "MsgInfo.hpp" #include "Debug.hpp" #define SELECT_TIMEOUT 20000 #define ESCAPE_KEY 0x1B #define DEL_KEY 0x7f static volatile bool quit = false; enum class DisplayMode { Overview, Decode, }; struct SpyInfo { SpyInfo(const char *path, bool debug) : typedb(path, debug) { } ~SpyInfo() { for (auto& it : minfomap) delete it.second; } MsgInfo *getCurrentMsginfo(const char **channel) { auto& ch = names[decode_index]; MsgInfo **m = lookup(minfomap, ch); assert(m); if (channel) *channel = ch.c_str(); return *m; } bool isValidChannelnum(size_t index) { return (0 <= index && index < names.size()); } void addMessage(const char *channel, const zcm_recv_buf_t *rbuf); void display(); void displayOverview(); void handleKeyboard(char ch); void handleKeyboardOverview(char ch); void handleKeyboardDecode(char ch); private: vector<string> names; unordered_map<string, MsgInfo*> minfomap; TypeDb typedb; mutex mut; DisplayMode mode = DisplayMode::Overview; bool is_selecting = false; int decode_index = 0; MsgInfo *decode_msg_info; const char *decode_msg_channel; int view_id; }; void SpyInfo::addMessage(const char *channel, const zcm_recv_buf_t *rbuf) { unique_lock<mutex> lk(mut); MsgInfo *minfo = minfomap[channel]; if (minfo == NULL) { minfo = new MsgInfo(typedb, channel); names.push_back(channel); std::sort(begin(names), end(names)); minfomap[channel] = minfo; } minfo->addMessage(TimeUtil::utime(), rbuf); } void SpyInfo::display() { unique_lock<mutex> lk(mut); switch (mode) { case DisplayMode::Overview: { displayOverview(); } break; case DisplayMode::Decode: { decode_msg_info->display(); if (is_selecting) { printf(" Decode field: "); if (view_id != -1) printf("%d", view_id ); fflush(stdout); } } break; default: DEBUG(1, "ERR: unknown mode\n"); } } void SpyInfo::displayOverview() { printf(" %-28s\t%12s\t%8s\n", "Channel", "Num Messages", "Hz (ave)"); printf(" ----------------------------------------------------------------\n"); DEBUG(5, "start-loop\n"); for (size_t i = 0; i < names.size(); i++) { auto& channel = names[i]; MsgInfo **minfo = lookup(minfomap, channel); assert(minfo != NULL); float hz = (*minfo)->getHertz(); printf(" %3zu) %-28s\t%9" PRIu64 "\t%7.2f\n", i, channel.c_str(), (*minfo)->getNumMsgs(), hz); } printf("\n"); if (is_selecting) { printf(" Decode channel: "); if (decode_index != -1) printf("%d", decode_index); fflush(stdout); } } void SpyInfo::handleKeyboardOverview(char ch) { if (ch == '-') { is_selecting = true; decode_index = -1; } else if ('0' <= ch && ch <= '9') { // shortcut for single digit channels if (!is_selecting) { decode_index = ch - '0'; if (isValidChannelnum(decode_index)) { decode_msg_info = getCurrentMsginfo(&decode_msg_channel); mode = DisplayMode::Decode; } } else { if (decode_index == -1) { decode_index = ch - '0'; } else if (decode_index < 10000) { decode_index *= 10; decode_index += (ch - '0'); } } } else if (ch == '\n') { if (is_selecting) { if (isValidChannelnum(decode_index)) { decode_msg_info = getCurrentMsginfo(&decode_msg_channel); mode = DisplayMode::Decode; } is_selecting = false; } } else if (ch == '\b' || ch == DEL_KEY) { if (is_selecting) { if (decode_index < 10) decode_index = -1; else decode_index /= 10; } } else { DEBUG(1, "INFO: unrecognized input: '%c' (0x%2x)\n", ch, ch); } } void SpyInfo::handleKeyboardDecode(char ch) { MsgInfo& minfo = *decode_msg_info; size_t depth = minfo.getViewDepth(); if (ch == ESCAPE_KEY) { if (depth > 0) { minfo.decViewDepth(); } else { mode = DisplayMode::Overview; } is_selecting = false; } else if (ch == '-') { is_selecting = true; view_id = -1; } else if ('0' <= ch && ch <= '9') { // shortcut for single digit channels if (!is_selecting) { view_id = ch - '0'; // set and increase sub-msg decoding depth if (depth < MSG_DISPLAY_RECUR_MAX) { minfo.incViewDepth(view_id); } else { DEBUG(1, "INFO: cannot recurse further: reached maximum depth of %d\n", MSG_DISPLAY_RECUR_MAX); } } else { if (view_id == -1) { view_id = ch - '0'; } else if (view_id < 10000) { view_id *= 10; view_id += (ch - '0'); } } } else if (ch == '\n') { if (is_selecting) { // set and increase sub-msg decoding depth if (depth < MSG_DISPLAY_RECUR_MAX) { minfo.incViewDepth(view_id); } else { DEBUG(1, "INFO: cannot recurse further: reached maximum depth of %d\n", MSG_DISPLAY_RECUR_MAX); } is_selecting = false; } } else if (ch == '\b' || ch == DEL_KEY) { if (is_selecting) { if (view_id < 10) view_id = -1; else view_id /= 10; } } else { DEBUG(1, "INFO: unrecognized input: '%c' (0x%2x)\n", ch, ch); } } void SpyInfo::handleKeyboard(char ch) { unique_lock<mutex> lk(mut); switch (mode) { case DisplayMode::Overview: handleKeyboardOverview(ch); break; case DisplayMode::Decode: handleKeyboardDecode(ch); break; default: DEBUG(1, "INFO: unrecognized keyboard mode: %d\n", (int)mode); } } void *keyboard_thread_func(void *arg) { SpyInfo *spy = (SpyInfo *)arg; struct termios old = {0}; if (tcgetattr(0, &old) < 0) perror("tcsetattr()"); struct termios newt = old; newt.c_lflag &= ~ICANON; newt.c_lflag &= ~ECHO; newt.c_cc[VMIN] = 1; newt.c_cc[VTIME] = 0; if (tcsetattr(0, TCSANOW, &newt) < 0) perror("tcsetattr ICANON"); char ch; while(!quit) { fd_set fds; FD_ZERO(&fds); FD_SET(0, &fds); struct timeval timeout = { 0, SELECT_TIMEOUT }; int status = select(1, &fds, 0, 0, &timeout); if(quit) break; if(status != 0 && FD_ISSET(0, &fds)) { if(read(0, &ch, 1) < 0) perror ("read()"); spy->handleKeyboard(ch); } else { DEBUG(4, "INFO: keyboard_thread_func select() timeout\n"); } } if (tcsetattr(0, TCSADRAIN, &old) < 0) perror ("tcsetattr ~ICANON"); return NULL; } ////////////////////////////////////////////////////////////////////// ////////////////////////// Helper Functions ////////////////////////// ////////////////////////////////////////////////////////////////////// void clearscreen() { // clear printf("\033[2J"); // move cursor to (0, 0) printf("\033[0;0H"); } ////////////////////////////////////////////////////////////////////// //////////////////////////// Print Thread //////////////////////////// ////////////////////////////////////////////////////////////////////// void printThreadFunc(SpyInfo *spy) { static constexpr float hz = 20.0; static constexpr u64 period = 1000000 / hz; DEBUG(1, "INFO: %s: Starting\n", "print_thread"); while (!quit) { usleep(period); clearscreen(); printf(" **************************************************************************** \n"); printf(" ******************************* ZCM-SPY-LITE ******************************* \n"); printf(" **************************************************************************** \n"); spy->display(); // flush the stdout buffer (required since we use full buffering) fflush(stdout); } DEBUG(1, "INFO: %s: Ending\n", "print_thread"); } ////////////////////////////////////////////////////////////////////// ///////////////////////////// LCM HANDLER //////////////////////////// ////////////////////////////////////////////////////////////////////// void handler_all_zcm (const zcm_recv_buf_t *rbuf, const char *channel, void *arg) { SpyInfo *spy = (SpyInfo *)arg; spy->addMessage(channel, rbuf); } ////////////////////////////////////////////////////////////////////// ////////////////////////////////// MAIN ////////////////////////////// ////////////////////////////////////////////////////////////////////// static void sighandler(int s) { switch(s) { case SIGQUIT: case SIGINT: case SIGTERM: DEBUG(1, "Caught signal...\n"); quit = true; break; default: DEBUG(1, "WRN: unrecognized signal fired\n"); break; } } int main(int argc, char *argv[]) { DEBUG_INIT(); bool debug = false; // XXX get opt if(argc > 1 && strcmp(argv[1], "--debug") == 0) debug = true; // get the zcmtypes.so from ZCM_SPY_LITE_PATH const char *spy_lite_path = getenv("ZCM_SPY_LITE_PATH"); if (debug) printf("zcm_spy_lite_path='%s'\n", spy_lite_path); if (spy_lite_path == NULL) { fprintf(stderr, "ERR: invalid $ZCM_SPY_LITE_PATH\n"); return 1; } SpyInfo spy {spy_lite_path, debug}; if (debug) exit(0); signal(SIGINT, sighandler); signal(SIGQUIT, sighandler); signal(SIGTERM, sighandler); // configure stdout buffering: use FULL buffering to avoid flickering setvbuf(stdout, NULL, _IOFBF, 2048); // start zcm zcm_t *zcm = zcm_create(NULL); if (!zcm) { DEBUG(1, "ERR: failed to create an zcm object!\n"); return 1; } zcm_subscribe(zcm, ".*", handler_all_zcm, &spy); zcm_start(zcm); thread printThread {printThreadFunc, &spy}; // use this thread as the keyboard thread keyboard_thread_func(&spy); // cleanup printThread.join(); zcm_stop(zcm); DEBUG(1, "Exiting...\n"); return 0; } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //--- // Produces the data needed to calculate the quality assurance. // All data must be mergeable objects. // Authors: // // Luciano Diaz Gonzalez <luciano.diaz@nucleares.unam.mx> (ICN-UNAM) // Mario Rodriguez Cahuantzi <mrodrigu@mail.cern.ch> (FCFM-BUAP) // Arturo Fernandez Tellez <afernan@mail.cern.ch (FCFM-BUAP) // // Created: June 13th 2008 //--- // Last Update: Aug. 27th 2008 --> Implementation to declare QA expert histogram // --- ROOT system --- #include <TClonesArray.h> #include <TFile.h> #include <TH1F.h> #include <TDirectory.h> // --- Standard library --- // --- AliRoot header files --- #include "AliESDEvent.h" #include "AliLog.h" #include "AliACORDEdigit.h" #include "AliACORDEhit.h" #include "AliACORDEQADataMakerRec.h" #include "AliQAChecker.h" #include "AliACORDERawReader.h" #include "AliACORDERawStream.h" ClassImp(AliACORDEQADataMakerRec) //____________________________________________________________________________ AliACORDEQADataMakerRec::AliACORDEQADataMakerRec():AliQADataMakerRec(AliQA::GetDetName(AliQA::kACORDE), "ACORDE Quality Assurance Data Maker") { } //____________________________________________________________________________ AliACORDEQADataMakerRec::AliACORDEQADataMakerRec(const AliACORDEQADataMakerRec& qadm):AliQADataMakerRec() { SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); } //__________________________________________________________________ AliACORDEQADataMakerRec& AliACORDEQADataMakerRec::operator = (const AliACORDEQADataMakerRec& qadm ) { // Equal operator. this->~AliACORDEQADataMakerRec(); new(this) AliACORDEQADataMakerRec(qadm); return *this; } //____________________________________________________________________________ void AliACORDEQADataMakerRec::EndOfDetectorCycle(AliQA::TASKINDEX_t task, TObjArray * list) { //Detector specific actions at end of cycle // do the QA checking AliQAChecker::Instance()->Run(AliQA::kACORDE, task, list) ; } //____________________________________________________________________________ void AliACORDEQADataMakerRec::StartOfDetectorCycle() { //Detector specific actions at start of cycle } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitRaws() { // create Raw histograms in Raw subdir TH1D *fhACORDEBitPattern[4]; fhACORDEBitPattern[0] = new TH1D("ACORDERawDataSM","ACORDE-SingleMuon",60,1,60);//AcordeSingleMuon BitPattern fhACORDEBitPattern[1] = new TH1D("ACORDERawDataMM","ACORDE-MultiMuon",60,1,60);//AcordeMultiMuon BitPattern fhACORDEBitPattern[2] = new TH1D("ACORDERawDataSMM","ACORDE-SingleMuonMultiplicity",60,1,60);//AcordeSingleMuon Multiplicity fhACORDEBitPattern[3] = new TH1D("ACORDERawDataMMM","ACORDE-MultiMuonMultiplicity",60,1,60);//AcordeMultiMuon Multiplicity for(Int_t i=0;i<4;i++) { Add2RawsList(fhACORDEBitPattern[i],i,kFALSE); } } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitRecPoints() { // create cluster histograms in RecPoint subdir // Not needed for ACORDE by now !!! } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitESDs() { //create ESDs histograms in ESDs subdir TH1F * fhESDsSingle; TH1F * fhESDsMulti; TString name; name = "hESDsSingle"; fhESDsSingle = new TH1F(name.Data(),"hESDsSingle",60,0,60); Add2ESDsList(fhESDsSingle,0,kFALSE); name = "hESDsMulti"; fhESDsMulti = new TH1F(name.Data(),"hESDsMulti",60,0,60); Add2ESDsList(fhESDsMulti,1,kFALSE); } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeRaws(AliRawReader* rawReader) { //fills QA histos for RAW rawReader->Reset(); AliACORDERawStream rawStream(rawReader); size_t contSingle=0; size_t contMulti=0; UInt_t dy[4]; bool kroSingle[60],kroMulti[60]; UInt_t tmpDy; for(Int_t m=0;m<60;m++) {kroSingle[m]=0;kroMulti[m]=0;} if(rawStream.Next()) { rawReader->NextEvent(); rawStream.Reset(); dy[0]=rawStream.GetWord(0); dy[1]=rawStream.GetWord(1); dy[2]=rawStream.GetWord(2); dy[3]=rawStream.GetWord(3); tmpDy=dy[0]; for(Int_t r=0;r<30;++r) { kroSingle[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[1]; for(Int_t r=30;r<60;++r) { kroSingle[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[2]; for(Int_t r=0;r<30;++r) { kroMulti[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[3]; for(Int_t r=30;r<60;++r) { kroMulti[r] = tmpDy & 1; tmpDy>>=1; } contSingle=0; contMulti=0; for(Int_t r=0;r<60;++r) { if(kroSingle[r]==1) { GetRawsData(0)->Fill(r+1); contSingle=contSingle+1; } if(kroMulti[r]==1) { GetRawsData(1)->Fill(r+1); contMulti++; } }GetRawsData(2)->Fill(contSingle);GetRawsData(3)->Fill(contMulti); } } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeRecPoints(TTree * clustersTree) { //fills QA histos for clusters // Not needed for ACORDE by now !!! } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeESDs(AliESDEvent * esd) { //fills QA histos for ESD AliESDACORDE * fESDACORDE= esd->GetACORDEData(); Int_t *fACORDEMultiMuon =fESDACORDE->GetACORDEMultiMuon(); Int_t *fACORDESingleMuon=fESDACORDE->GetACORDESingleMuon(); for(int i=0;i<60;i++){ if(fACORDESingleMuon[i]==1) GetESDsData(0) -> Fill(i); if(fACORDEMultiMuon[i]==1) GetESDsData(1) -> Fill(i); } } <commit_msg>Crucial bug-fix. The raw-data events should be never skipped inside the QA data makers<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ //--- // Produces the data needed to calculate the quality assurance. // All data must be mergeable objects. // Authors: // // Luciano Diaz Gonzalez <luciano.diaz@nucleares.unam.mx> (ICN-UNAM) // Mario Rodriguez Cahuantzi <mrodrigu@mail.cern.ch> (FCFM-BUAP) // Arturo Fernandez Tellez <afernan@mail.cern.ch (FCFM-BUAP) // // Created: June 13th 2008 //--- // Last Update: Aug. 27th 2008 --> Implementation to declare QA expert histogram // --- ROOT system --- #include <TClonesArray.h> #include <TFile.h> #include <TH1F.h> #include <TDirectory.h> // --- Standard library --- // --- AliRoot header files --- #include "AliESDEvent.h" #include "AliLog.h" #include "AliACORDEdigit.h" #include "AliACORDEhit.h" #include "AliACORDEQADataMakerRec.h" #include "AliQAChecker.h" #include "AliACORDERawReader.h" #include "AliACORDERawStream.h" ClassImp(AliACORDEQADataMakerRec) //____________________________________________________________________________ AliACORDEQADataMakerRec::AliACORDEQADataMakerRec():AliQADataMakerRec(AliQA::GetDetName(AliQA::kACORDE), "ACORDE Quality Assurance Data Maker") { } //____________________________________________________________________________ AliACORDEQADataMakerRec::AliACORDEQADataMakerRec(const AliACORDEQADataMakerRec& qadm):AliQADataMakerRec() { SetName((const char*)qadm.GetName()) ; SetTitle((const char*)qadm.GetTitle()); } //__________________________________________________________________ AliACORDEQADataMakerRec& AliACORDEQADataMakerRec::operator = (const AliACORDEQADataMakerRec& qadm ) { // Equal operator. this->~AliACORDEQADataMakerRec(); new(this) AliACORDEQADataMakerRec(qadm); return *this; } //____________________________________________________________________________ void AliACORDEQADataMakerRec::EndOfDetectorCycle(AliQA::TASKINDEX_t task, TObjArray * list) { //Detector specific actions at end of cycle // do the QA checking AliQAChecker::Instance()->Run(AliQA::kACORDE, task, list) ; } //____________________________________________________________________________ void AliACORDEQADataMakerRec::StartOfDetectorCycle() { //Detector specific actions at start of cycle } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitRaws() { // create Raw histograms in Raw subdir TH1D *fhACORDEBitPattern[4]; fhACORDEBitPattern[0] = new TH1D("ACORDERawDataSM","ACORDE-SingleMuon",60,1,60);//AcordeSingleMuon BitPattern fhACORDEBitPattern[1] = new TH1D("ACORDERawDataMM","ACORDE-MultiMuon",60,1,60);//AcordeMultiMuon BitPattern fhACORDEBitPattern[2] = new TH1D("ACORDERawDataSMM","ACORDE-SingleMuonMultiplicity",60,1,60);//AcordeSingleMuon Multiplicity fhACORDEBitPattern[3] = new TH1D("ACORDERawDataMMM","ACORDE-MultiMuonMultiplicity",60,1,60);//AcordeMultiMuon Multiplicity for(Int_t i=0;i<4;i++) { Add2RawsList(fhACORDEBitPattern[i],i,kFALSE); } } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitRecPoints() { // create cluster histograms in RecPoint subdir // Not needed for ACORDE by now !!! } //____________________________________________________________________________ void AliACORDEQADataMakerRec::InitESDs() { //create ESDs histograms in ESDs subdir TH1F * fhESDsSingle; TH1F * fhESDsMulti; TString name; name = "hESDsSingle"; fhESDsSingle = new TH1F(name.Data(),"hESDsSingle",60,0,60); Add2ESDsList(fhESDsSingle,0,kFALSE); name = "hESDsMulti"; fhESDsMulti = new TH1F(name.Data(),"hESDsMulti",60,0,60); Add2ESDsList(fhESDsMulti,1,kFALSE); } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeRaws(AliRawReader* rawReader) { //fills QA histos for RAW rawReader->Reset(); AliACORDERawStream rawStream(rawReader); size_t contSingle=0; size_t contMulti=0; UInt_t dy[4]; bool kroSingle[60],kroMulti[60]; UInt_t tmpDy; for(Int_t m=0;m<60;m++) {kroSingle[m]=0;kroMulti[m]=0;} if(rawStream.Next()) { dy[0]=rawStream.GetWord(0); dy[1]=rawStream.GetWord(1); dy[2]=rawStream.GetWord(2); dy[3]=rawStream.GetWord(3); tmpDy=dy[0]; for(Int_t r=0;r<30;++r) { kroSingle[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[1]; for(Int_t r=30;r<60;++r) { kroSingle[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[2]; for(Int_t r=0;r<30;++r) { kroMulti[r] = tmpDy & 1; tmpDy>>=1; } tmpDy=dy[3]; for(Int_t r=30;r<60;++r) { kroMulti[r] = tmpDy & 1; tmpDy>>=1; } contSingle=0; contMulti=0; for(Int_t r=0;r<60;++r) { if(kroSingle[r]==1) { GetRawsData(0)->Fill(r+1); contSingle=contSingle+1; } if(kroMulti[r]==1) { GetRawsData(1)->Fill(r+1); contMulti++; } }GetRawsData(2)->Fill(contSingle);GetRawsData(3)->Fill(contMulti); } } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeRecPoints(TTree * clustersTree) { //fills QA histos for clusters // Not needed for ACORDE by now !!! } //____________________________________________________________________________ void AliACORDEQADataMakerRec::MakeESDs(AliESDEvent * esd) { //fills QA histos for ESD AliESDACORDE * fESDACORDE= esd->GetACORDEData(); Int_t *fACORDEMultiMuon =fESDACORDE->GetACORDEMultiMuon(); Int_t *fACORDESingleMuon=fESDACORDE->GetACORDESingleMuon(); for(int i=0;i<60;i++){ if(fACORDESingleMuon[i]==1) GetESDsData(0) -> Fill(i); if(fACORDEMultiMuon[i]==1) GetESDsData(1) -> Fill(i); } } <|endoftext|>
<commit_before>/* * Accounts model item, represents an account in the contactlist tree * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * 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 <TelepathyQt4/Account> #include <TelepathyQt4/ContactManager> #include "accounts-model-item.h" #include "accounts-model.h" #include "contact-model-item.h" struct AccountsModelItem::Private { Private(const Tp::AccountPtr &account) : mAccount(account) { } void setStatus(const QString &value); void setStatusMessage(const QString &value); Tp::AccountPtr mAccount; }; void AccountsModelItem::Private::setStatus(const QString &value) { Tp::Presence presence = mAccount->currentPresence().barePresence(); presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString()); mAccount->setRequestedPresence(presence); } void AccountsModelItem::Private::setStatusMessage(const QString &value) { Tp::Presence presence = mAccount->currentPresence().barePresence(); presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value); mAccount->setRequestedPresence(presence); } AccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account) : mPriv(new Private(account)) { if (!mPriv->mAccount->connection().isNull()) { QTimer::singleShot(0, this, SLOT(onNewConnection())); } connect(mPriv->mAccount.data(), SIGNAL(removed()), SLOT(onRemoved())); connect(mPriv->mAccount.data(), SIGNAL(serviceNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(profileChanged(Tp::ProfilePtr)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(iconNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(nicknameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(normalizedNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(validityChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(stateChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(connectsAutomaticallyPropertyChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(parametersChanged(QVariantMap)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(changingPresence(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(automaticPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(currentPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(requestedPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(onlinenessChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(avatarChanged(Tp::Avatar)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(onlinenessChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)), SLOT(onStatusChanged(Tp::ConnectionStatus))); connect(mPriv->mAccount.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onConnectionChanged(Tp::ConnectionPtr))); } AccountsModelItem::~AccountsModelItem() { delete mPriv; } QVariant AccountsModelItem::data(int role) const { switch (role) { case AccountsModel::ItemRole: return QVariant::fromValue((AccountsModelItem*)this); case AccountsModel::IdRole: return mPriv->mAccount->uniqueIdentifier(); case AccountsModel::AvatarRole: return QVariant(); //TODO: Return account icon case AccountsModel::ValidRole: return mPriv->mAccount->isValid(); case AccountsModel::EnabledRole: return mPriv->mAccount->isEnabled(); case AccountsModel::ConnectionManagerNameRole: return mPriv->mAccount->cmName(); case AccountsModel::ProtocolNameRole: return mPriv->mAccount->protocolName(); case AccountsModel::DisplayNameRole: case Qt::DisplayRole: return mPriv->mAccount->displayName(); case AccountsModel::IconRole: return mPriv->mAccount->iconName(); case AccountsModel::NicknameRole: return mPriv->mAccount->nickname(); case AccountsModel::ConnectsAutomaticallyRole: return mPriv->mAccount->connectsAutomatically(); case AccountsModel::ChangingPresenceRole: return mPriv->mAccount->isChangingPresence(); case AccountsModel::AutomaticPresenceRole: return mPriv->mAccount->automaticPresence().status(); case AccountsModel::AutomaticPresenceTypeRole: return mPriv->mAccount->automaticPresence().type(); case AccountsModel::AutomaticPresenceStatusMessageRole: return mPriv->mAccount->automaticPresence().statusMessage(); case AccountsModel::CurrentPresenceRole: return mPriv->mAccount->currentPresence().status(); case AccountsModel::CurrentPresenceTypeRole: return mPriv->mAccount->currentPresence().type(); case AccountsModel::CurrentPresenceStatusMessageRole: return mPriv->mAccount->currentPresence().statusMessage(); case AccountsModel::RequestedPresenceRole: return mPriv->mAccount->requestedPresence().status(); case AccountsModel::RequestedPresenceTypeRole: return mPriv->mAccount->requestedPresence().type(); case AccountsModel::RequestedPresenceStatusMessageRole: return mPriv->mAccount->requestedPresence().statusMessage(); case AccountsModel::ConnectionStatusRole: return mPriv->mAccount->connectionStatus(); case AccountsModel::ConnectionStatusReasonRole: return mPriv->mAccount->connectionStatusReason(); default: return QVariant(); } } bool AccountsModelItem::setData(int role, const QVariant &value) { switch (role) { case AccountsModel::EnabledRole: setEnabled(value.toBool()); return true; case AccountsModel::RequestedPresenceRole: mPriv->setStatus(value.toString()); return true; case AccountsModel::RequestedPresenceStatusMessageRole: mPriv->setStatusMessage(value.toString()); return true; case AccountsModel::NicknameRole: setNickname(value.toString()); return true; default: return false; } } Tp::AccountPtr AccountsModelItem::account() const { return mPriv->mAccount; } void AccountsModelItem::setEnabled(bool value) { mPriv->mAccount->setEnabled(value); } void AccountsModelItem::setNickname(const QString &value) { mPriv->mAccount->setNickname(value); } void AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage) { Tp::Presence presence; presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage); mPriv->mAccount->setAutomaticPresence(presence); } void AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage) { Tp::Presence presence; presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage); mPriv->mAccount->setRequestedPresence(presence); } void AccountsModelItem::onRemoved() { int index = parent()->indexOf(this); emit childrenRemoved(parent(), index, index); } void AccountsModelItem::onChanged() { emit changed(this); } void AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts, const Tp::Contacts &removedContacts) { foreach (const Tp::ContactPtr &contact, removedContacts) { for (int i = 0; i < size(); ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item->contact() == contact) { emit childrenRemoved(this, i, i); break; } } } // get the list of contact ids in the children QStringList idList; int numElems = size(); for (int i = 0; i < numElems; ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { idList.append(item->contact()->id()); } } QList<TreeNode *> newNodes; foreach (const Tp::ContactPtr &contact, addedContacts) { if (!idList.contains(contact->id())) { newNodes.append(new ContactModelItem(contact)); } } emit childrenAdded(this, newNodes); } void AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status) { onChanged(); emit connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status); } void AccountsModelItem::onNewConnection() { onConnectionChanged(mPriv->mAccount->connection()); } void AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection) { onChanged(); // if the connection is invalid or disconnected, clear the contacts list if (connection.isNull() || !connection->isValid() || connection->status() == Tp::ConnectionStatusDisconnected) { emit childrenRemoved(this, 0, size() - 1); return; } Tp::ContactManagerPtr manager = connection->contactManager(); connect(manager.data(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts, Tp::Channel::GroupMemberChangeDetails)), SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts))); connect(manager.data(), SIGNAL(stateChanged(Tp::ContactListState)), SLOT(onContactManagerStateChanged(Tp::ContactListState))); onContactManagerStateChanged(manager->state()); } void AccountsModelItem::onContactManagerStateChanged(Tp::ContactListState state) { if (state == Tp::ContactListStateSuccess) { clearContacts(); addKnownContacts(); } } void AccountsModelItem::clearContacts() { if (!mPriv->mAccount->connection().isNull() && mPriv->mAccount->connection()->isValid()) { Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager(); Tp::Contacts contacts = manager->allKnownContacts(); // remove the items no longer present for (int i = 0; i < size(); ++i) { bool exists = false; ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { Tp::ContactPtr itemContact = item->contact(); if (contacts.contains(itemContact)) { exists = true; } } if (!exists) { emit childrenRemoved(this, i, i); } } } } void AccountsModelItem::addKnownContacts() { // reload the known contacts if it has a connection QList<TreeNode *> newNodes; if (!mPriv->mAccount->connection().isNull() && mPriv->mAccount->connection()->isValid()) { Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager(); Tp::Contacts contacts = manager->allKnownContacts(); // get the list of contact ids in the children QStringList idList; int numElems = size(); for (int i = 0; i < numElems; ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { idList.append(item->contact()->id()); } } // only add the contact item if it is new foreach (const Tp::ContactPtr &contact, contacts) { if (!idList.contains(contact->id())) { newNodes.append(new ContactModelItem(contact)); } } } if (newNodes.count() > 0) { emit childrenAdded(this, newNodes); } } <commit_msg>Initial avatars support plus KConfig for storing the selected avatar. This will hold all other settings in the future.<commit_after>/* * Accounts model item, represents an account in the contactlist tree * This file is based on TelepathyQt4Yell Models * * Copyright (C) 2010 Collabora Ltd. <http://www.collabora.co.uk/> * Copyright (C) 2011 Martin Klapetek <martin dot klapetek at gmail dot com> * * 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 <TelepathyQt4/Account> #include <TelepathyQt4/ContactManager> #include "accounts-model-item.h" #include "accounts-model.h" #include "contact-model-item.h" struct AccountsModelItem::Private { Private(const Tp::AccountPtr &account) : mAccount(account) { } void setStatus(const QString &value); void setStatusMessage(const QString &value); Tp::AccountPtr mAccount; }; void AccountsModelItem::Private::setStatus(const QString &value) { Tp::Presence presence = mAccount->currentPresence().barePresence(); presence.setStatus(Tp::ConnectionPresenceTypeUnset, value, QString()); mAccount->setRequestedPresence(presence); } void AccountsModelItem::Private::setStatusMessage(const QString &value) { Tp::Presence presence = mAccount->currentPresence().barePresence(); presence.setStatus(Tp::ConnectionPresenceTypeUnset, QString(), value); mAccount->setRequestedPresence(presence); } AccountsModelItem::AccountsModelItem(const Tp::AccountPtr &account) : mPriv(new Private(account)) { if (!mPriv->mAccount->connection().isNull()) { QTimer::singleShot(0, this, SLOT(onNewConnection())); } connect(mPriv->mAccount.data(), SIGNAL(removed()), SLOT(onRemoved())); connect(mPriv->mAccount.data(), SIGNAL(serviceNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(profileChanged(Tp::ProfilePtr)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(iconNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(nicknameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(normalizedNameChanged(QString)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(validityChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(stateChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(capabilitiesChanged(Tp::ConnectionCapabilities)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(connectsAutomaticallyPropertyChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(parametersChanged(QVariantMap)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(changingPresence(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(automaticPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(currentPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(requestedPresenceChanged(Tp::Presence)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(onlinenessChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(avatarChanged(Tp::Avatar)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(onlinenessChanged(bool)), SLOT(onChanged())); connect(mPriv->mAccount.data(), SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)), SLOT(onStatusChanged(Tp::ConnectionStatus))); connect(mPriv->mAccount.data(), SIGNAL(connectionChanged(Tp::ConnectionPtr)), SLOT(onConnectionChanged(Tp::ConnectionPtr))); } AccountsModelItem::~AccountsModelItem() { delete mPriv; } QVariant AccountsModelItem::data(int role) const { switch (role) { case AccountsModel::ItemRole: return QVariant::fromValue((AccountsModelItem*)this); case AccountsModel::IdRole: return mPriv->mAccount->uniqueIdentifier(); case AccountsModel::AvatarRole: return QVariant::fromValue(mPriv->mAccount->avatar()); case AccountsModel::ValidRole: return mPriv->mAccount->isValid(); case AccountsModel::EnabledRole: return mPriv->mAccount->isEnabled(); case AccountsModel::ConnectionManagerNameRole: return mPriv->mAccount->cmName(); case AccountsModel::ProtocolNameRole: return mPriv->mAccount->protocolName(); case AccountsModel::DisplayNameRole: case Qt::DisplayRole: return mPriv->mAccount->displayName(); case AccountsModel::IconRole: return mPriv->mAccount->iconName(); case AccountsModel::NicknameRole: return mPriv->mAccount->nickname(); case AccountsModel::ConnectsAutomaticallyRole: return mPriv->mAccount->connectsAutomatically(); case AccountsModel::ChangingPresenceRole: return mPriv->mAccount->isChangingPresence(); case AccountsModel::AutomaticPresenceRole: return mPriv->mAccount->automaticPresence().status(); case AccountsModel::AutomaticPresenceTypeRole: return mPriv->mAccount->automaticPresence().type(); case AccountsModel::AutomaticPresenceStatusMessageRole: return mPriv->mAccount->automaticPresence().statusMessage(); case AccountsModel::CurrentPresenceRole: return mPriv->mAccount->currentPresence().status(); case AccountsModel::CurrentPresenceTypeRole: return mPriv->mAccount->currentPresence().type(); case AccountsModel::CurrentPresenceStatusMessageRole: return mPriv->mAccount->currentPresence().statusMessage(); case AccountsModel::RequestedPresenceRole: return mPriv->mAccount->requestedPresence().status(); case AccountsModel::RequestedPresenceTypeRole: return mPriv->mAccount->requestedPresence().type(); case AccountsModel::RequestedPresenceStatusMessageRole: return mPriv->mAccount->requestedPresence().statusMessage(); case AccountsModel::ConnectionStatusRole: return mPriv->mAccount->connectionStatus(); case AccountsModel::ConnectionStatusReasonRole: return mPriv->mAccount->connectionStatusReason(); default: return QVariant(); } } bool AccountsModelItem::setData(int role, const QVariant &value) { switch (role) { case AccountsModel::EnabledRole: setEnabled(value.toBool()); return true; case AccountsModel::RequestedPresenceRole: mPriv->setStatus(value.toString()); return true; case AccountsModel::RequestedPresenceStatusMessageRole: mPriv->setStatusMessage(value.toString()); return true; case AccountsModel::NicknameRole: setNickname(value.toString()); return true; case AccountsModel::AvatarRole: mPriv->mAccount->setAvatar(value.value<Tp::Avatar>()); return true; default: return false; } } Tp::AccountPtr AccountsModelItem::account() const { return mPriv->mAccount; } void AccountsModelItem::setEnabled(bool value) { mPriv->mAccount->setEnabled(value); } void AccountsModelItem::setNickname(const QString &value) { mPriv->mAccount->setNickname(value); } void AccountsModelItem::setAutomaticPresence(int type, const QString &status, const QString &statusMessage) { Tp::Presence presence; presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage); mPriv->mAccount->setAutomaticPresence(presence); } void AccountsModelItem::setRequestedPresence(int type, const QString &status, const QString &statusMessage) { Tp::Presence presence; presence.setStatus((Tp::ConnectionPresenceType) type, status, statusMessage); mPriv->mAccount->setRequestedPresence(presence); } void AccountsModelItem::onRemoved() { int index = parent()->indexOf(this); emit childrenRemoved(parent(), index, index); } void AccountsModelItem::onChanged() { emit changed(this); } void AccountsModelItem::onContactsChanged(const Tp::Contacts &addedContacts, const Tp::Contacts &removedContacts) { foreach (const Tp::ContactPtr &contact, removedContacts) { for (int i = 0; i < size(); ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item->contact() == contact) { emit childrenRemoved(this, i, i); break; } } } // get the list of contact ids in the children QStringList idList; int numElems = size(); for (int i = 0; i < numElems; ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { idList.append(item->contact()->id()); } } QList<TreeNode *> newNodes; foreach (const Tp::ContactPtr &contact, addedContacts) { if (!idList.contains(contact->id())) { newNodes.append(new ContactModelItem(contact)); } } emit childrenAdded(this, newNodes); } void AccountsModelItem::onStatusChanged(Tp::ConnectionStatus status) { onChanged(); emit connectionStatusChanged(mPriv->mAccount->uniqueIdentifier(), status); } void AccountsModelItem::onNewConnection() { onConnectionChanged(mPriv->mAccount->connection()); } void AccountsModelItem::onConnectionChanged(const Tp::ConnectionPtr &connection) { onChanged(); // if the connection is invalid or disconnected, clear the contacts list if (connection.isNull() || !connection->isValid() || connection->status() == Tp::ConnectionStatusDisconnected) { emit childrenRemoved(this, 0, size() - 1); return; } Tp::ContactManagerPtr manager = connection->contactManager(); connect(manager.data(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts, Tp::Channel::GroupMemberChangeDetails)), SLOT(onContactsChanged(Tp::Contacts,Tp::Contacts))); connect(manager.data(), SIGNAL(stateChanged(Tp::ContactListState)), SLOT(onContactManagerStateChanged(Tp::ContactListState))); onContactManagerStateChanged(manager->state()); } void AccountsModelItem::onContactManagerStateChanged(Tp::ContactListState state) { if (state == Tp::ContactListStateSuccess) { clearContacts(); addKnownContacts(); } } void AccountsModelItem::clearContacts() { if (!mPriv->mAccount->connection().isNull() && mPriv->mAccount->connection()->isValid()) { Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager(); Tp::Contacts contacts = manager->allKnownContacts(); // remove the items no longer present for (int i = 0; i < size(); ++i) { bool exists = false; ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { Tp::ContactPtr itemContact = item->contact(); if (contacts.contains(itemContact)) { exists = true; } } if (!exists) { emit childrenRemoved(this, i, i); } } } } void AccountsModelItem::addKnownContacts() { // reload the known contacts if it has a connection QList<TreeNode *> newNodes; if (!mPriv->mAccount->connection().isNull() && mPriv->mAccount->connection()->isValid()) { Tp::ContactManagerPtr manager = mPriv->mAccount->connection()->contactManager(); Tp::Contacts contacts = manager->allKnownContacts(); // get the list of contact ids in the children QStringList idList; int numElems = size(); for (int i = 0; i < numElems; ++i) { ContactModelItem *item = qobject_cast<ContactModelItem *>(childAt(i)); if (item) { idList.append(item->contact()->id()); } } // only add the contact item if it is new foreach (const Tp::ContactPtr &contact, contacts) { if (!idList.contains(contact->id())) { newNodes.append(new ContactModelItem(contact)); } } } if (newNodes.count() > 0) { emit childrenAdded(this, newNodes); } } <|endoftext|>
<commit_before>/*************************************************************************/ /* area_bullet.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "area_bullet.h" #include "bullet_physics_server.h" #include "bullet_types_converter.h" #include "bullet_utilities.h" #include "collision_object_bullet.h" #include "space_bullet.h" #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <btBulletCollisionCommon.h> /** @author AndreaCatania */ AreaBullet::AreaBullet() : RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) { btGhost = bulletnew(btGhostObject); reload_shapes(); setupBulletCollisionObject(btGhost); /// Collision objects with a callback still have collision response with dynamic rigid bodies. /// In order to use collision objects as trigger, you have to disable the collision response. set_collision_enabled(false); for (int i = 0; i < 5; ++i) { call_event_res_ptr[i] = &call_event_res[i]; } } AreaBullet::~AreaBullet() { // signal are handled by godot, so just clear without notify for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { overlappingObjects[i].object->on_exit_area(this); } } void AreaBullet::dispatch_callbacks() { if (!isScratched) { return; } isScratched = false; // Reverse order because I've to remove EXIT objects for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { OverlappingObjectData &otherObj = overlappingObjects.write[i]; switch (otherObj.state) { case OVERLAP_STATE_ENTER: otherObj.state = OVERLAP_STATE_INSIDE; call_event(otherObj.object, PhysicsServer3D::AREA_BODY_ADDED); otherObj.object->on_enter_area(this); break; case OVERLAP_STATE_EXIT: call_event(otherObj.object, PhysicsServer3D::AREA_BODY_REMOVED); otherObj.object->on_exit_area(this); overlappingObjects.remove(i); // Remove after callback break; case OVERLAP_STATE_DIRTY: case OVERLAP_STATE_INSIDE: break; } } } void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) { InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())]; Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id); if (!areaGodoObject) { event.event_callback_id = ObjectID(); return; } call_event_res[0] = p_status; call_event_res[1] = p_otherObject->get_self(); // Other body call_event_res[2] = p_otherObject->get_instance_id(); // instance ID call_event_res[3] = 0; // other_body_shape ID call_event_res[4] = 0; // self_shape ID Callable::CallError outResp; areaGodoObject->call(event.event_callback_method, (const Variant **)call_event_res_ptr, 5, outResp); } void AreaBullet::scratch() { if (isScratched) { return; } isScratched = true; } void AreaBullet::clear_overlaps(bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); } overlappingObjects[i].object->on_exit_area(this); } overlappingObjects.clear(); } void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { if (overlappingObjects[i].object == p_object) { if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); } overlappingObjects[i].object->on_exit_area(this); overlappingObjects.remove(i); break; } } } int AreaBullet::find_overlapping_object(CollisionObjectBullet *p_colObj) { const int size = overlappingObjects.size(); for (int i = 0; i < size; ++i) { if (overlappingObjects[i].object == p_colObj) { return i; } } return -1; } void AreaBullet::set_monitorable(bool p_monitorable) { monitorable = p_monitorable; } bool AreaBullet::is_monitoring() const { return get_godot_object_flags() & GOF_IS_MONITORING_AREA; } void AreaBullet::main_shape_changed() { CRASH_COND(!get_main_shape()); btGhost->setCollisionShape(get_main_shape()); } void AreaBullet::do_reload_body() { if (space) { space->remove_area(this); space->add_area(this); } } void AreaBullet::set_space(SpaceBullet *p_space) { // Clear the old space if there is one if (space) { overlappingObjects.clear(); isScratched = false; // Remove this object form the physics world space->unregister_collision_object(this); space->remove_area(this); } space = p_space; if (space) { space->register_collision_object(this); reload_body(); } } void AreaBullet::on_collision_filters_change() { if (space) { space->reload_collision_filters(this); } } void AreaBullet::add_overlap(CollisionObjectBullet *p_otherObject) { scratch(); overlappingObjects.push_back(OverlappingObjectData(p_otherObject, OVERLAP_STATE_ENTER)); p_otherObject->notify_new_overlap(this); } void AreaBullet::put_overlap_as_exit(int p_index) { scratch(); overlappingObjects.write[p_index].state = OVERLAP_STATE_EXIT; } void AreaBullet::put_overlap_as_inside(int p_index) { // This check is required to be sure this body was inside if (OVERLAP_STATE_DIRTY == overlappingObjects[p_index].state) { overlappingObjects.write[p_index].state = OVERLAP_STATE_INSIDE; } } void AreaBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) { switch (p_param) { case PhysicsServer3D::AREA_PARAM_GRAVITY: set_spOv_gravityMag(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: set_spOv_gravityVec(p_value); break; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: set_spOv_linearDump(p_value); break; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: set_spOv_angularDump(p_value); break; case PhysicsServer3D::AREA_PARAM_PRIORITY: set_spOv_priority(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: set_spOv_gravityPoint(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: set_spOv_gravityPointDistanceScale(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: set_spOv_gravityPointAttenuation(p_value); break; default: WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); } } Variant AreaBullet::get_param(PhysicsServer3D::AreaParameter p_param) const { switch (p_param) { case PhysicsServer3D::AREA_PARAM_GRAVITY: return spOv_gravityMag; case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: return spOv_gravityVec; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: return spOv_linearDump; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: return spOv_angularDump; case PhysicsServer3D::AREA_PARAM_PRIORITY: return spOv_priority; case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: return spOv_gravityPoint; case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return spOv_gravityPointDistanceScale; case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return spOv_gravityPointAttenuation; default: WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); return Variant(); } } void AreaBullet::set_event_callback(Type p_callbackObjectType, ObjectID p_id, const StringName &p_method) { InOutEventCallback &ev = eventsCallbacks[static_cast<int>(p_callbackObjectType)]; ev.event_callback_id = p_id; ev.event_callback_method = p_method; /// Set if monitoring if (eventsCallbacks[0].event_callback_id.is_valid() || eventsCallbacks[1].event_callback_id.is_valid()) { set_godot_object_flags(get_godot_object_flags() | GOF_IS_MONITORING_AREA); } else { set_godot_object_flags(get_godot_object_flags() & (~GOF_IS_MONITORING_AREA)); } } bool AreaBullet::has_event_callback(Type p_callbackObjectType) { return eventsCallbacks[static_cast<int>(p_callbackObjectType)].event_callback_id.is_valid(); } void AreaBullet::on_enter_area(AreaBullet *p_area) { } void AreaBullet::on_exit_area(AreaBullet *p_area) { CollisionObjectBullet::on_exit_area(p_area); } <commit_msg>Fix overlappingObjects vector crash<commit_after>/*************************************************************************/ /* area_bullet.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2020 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* 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 "area_bullet.h" #include "bullet_physics_server.h" #include "bullet_types_converter.h" #include "bullet_utilities.h" #include "collision_object_bullet.h" #include "space_bullet.h" #include <BulletCollision/CollisionDispatch/btGhostObject.h> #include <btBulletCollisionCommon.h> /** @author AndreaCatania */ AreaBullet::AreaBullet() : RigidCollisionObjectBullet(CollisionObjectBullet::TYPE_AREA) { btGhost = bulletnew(btGhostObject); reload_shapes(); setupBulletCollisionObject(btGhost); /// Collision objects with a callback still have collision response with dynamic rigid bodies. /// In order to use collision objects as trigger, you have to disable the collision response. set_collision_enabled(false); for (int i = 0; i < 5; ++i) { call_event_res_ptr[i] = &call_event_res[i]; } } AreaBullet::~AreaBullet() { // signal are handled by godot, so just clear without notify for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { overlappingObjects[i].object->on_exit_area(this); } } void AreaBullet::dispatch_callbacks() { if (!isScratched) { return; } isScratched = false; // Reverse order because I've to remove EXIT objects for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { OverlappingObjectData &otherObj = overlappingObjects.write[i]; switch (otherObj.state) { case OVERLAP_STATE_ENTER: otherObj.state = OVERLAP_STATE_INSIDE; call_event(otherObj.object, PhysicsServer3D::AREA_BODY_ADDED); otherObj.object->on_enter_area(this); break; case OVERLAP_STATE_EXIT: call_event(otherObj.object, PhysicsServer3D::AREA_BODY_REMOVED); otherObj.object->on_exit_area(this); overlappingObjects.remove(i); // Remove after callback break; case OVERLAP_STATE_DIRTY: case OVERLAP_STATE_INSIDE: break; } } } void AreaBullet::call_event(CollisionObjectBullet *p_otherObject, PhysicsServer3D::AreaBodyStatus p_status) { InOutEventCallback &event = eventsCallbacks[static_cast<int>(p_otherObject->getType())]; Object *areaGodoObject = ObjectDB::get_instance(event.event_callback_id); if (!areaGodoObject) { event.event_callback_id = ObjectID(); return; } call_event_res[0] = p_status; call_event_res[1] = p_otherObject->get_self(); // Other body call_event_res[2] = p_otherObject->get_instance_id(); // instance ID call_event_res[3] = 0; // other_body_shape ID call_event_res[4] = 0; // self_shape ID Callable::CallError outResp; areaGodoObject->call(event.event_callback_method, (const Variant **)call_event_res_ptr, 5, outResp); } void AreaBullet::scratch() { if (isScratched) { return; } isScratched = true; } void AreaBullet::clear_overlaps(bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); } overlappingObjects[i].object->on_exit_area(this); } overlappingObjects.clear(); } void AreaBullet::remove_overlap(CollisionObjectBullet *p_object, bool p_notify) { for (int i = overlappingObjects.size() - 1; 0 <= i; --i) { if (overlappingObjects[i].object == p_object) { if (p_notify) { call_event(overlappingObjects[i].object, PhysicsServer3D::AREA_BODY_REMOVED); } overlappingObjects[i].object->on_exit_area(this); overlappingObjects.remove(i); break; } } } int AreaBullet::find_overlapping_object(CollisionObjectBullet *p_colObj) { const int size = overlappingObjects.size(); for (int i = 0; i < size; ++i) { if (overlappingObjects[i].object == p_colObj) { return i; } } return -1; } void AreaBullet::set_monitorable(bool p_monitorable) { monitorable = p_monitorable; } bool AreaBullet::is_monitoring() const { return get_godot_object_flags() & GOF_IS_MONITORING_AREA; } void AreaBullet::main_shape_changed() { CRASH_COND(!get_main_shape()); btGhost->setCollisionShape(get_main_shape()); } void AreaBullet::do_reload_body() { if (space) { space->remove_area(this); space->add_area(this); } } void AreaBullet::set_space(SpaceBullet *p_space) { // Clear the old space if there is one if (space) { clear_overlaps(false); isScratched = false; // Remove this object form the physics world space->unregister_collision_object(this); space->remove_area(this); } space = p_space; if (space) { space->register_collision_object(this); reload_body(); } } void AreaBullet::on_collision_filters_change() { if (space) { space->reload_collision_filters(this); } } void AreaBullet::add_overlap(CollisionObjectBullet *p_otherObject) { scratch(); overlappingObjects.push_back(OverlappingObjectData(p_otherObject, OVERLAP_STATE_ENTER)); p_otherObject->notify_new_overlap(this); } void AreaBullet::put_overlap_as_exit(int p_index) { scratch(); overlappingObjects.write[p_index].state = OVERLAP_STATE_EXIT; } void AreaBullet::put_overlap_as_inside(int p_index) { // This check is required to be sure this body was inside if (OVERLAP_STATE_DIRTY == overlappingObjects[p_index].state) { overlappingObjects.write[p_index].state = OVERLAP_STATE_INSIDE; } } void AreaBullet::set_param(PhysicsServer3D::AreaParameter p_param, const Variant &p_value) { switch (p_param) { case PhysicsServer3D::AREA_PARAM_GRAVITY: set_spOv_gravityMag(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: set_spOv_gravityVec(p_value); break; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: set_spOv_linearDump(p_value); break; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: set_spOv_angularDump(p_value); break; case PhysicsServer3D::AREA_PARAM_PRIORITY: set_spOv_priority(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: set_spOv_gravityPoint(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: set_spOv_gravityPointDistanceScale(p_value); break; case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: set_spOv_gravityPointAttenuation(p_value); break; default: WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); } } Variant AreaBullet::get_param(PhysicsServer3D::AreaParameter p_param) const { switch (p_param) { case PhysicsServer3D::AREA_PARAM_GRAVITY: return spOv_gravityMag; case PhysicsServer3D::AREA_PARAM_GRAVITY_VECTOR: return spOv_gravityVec; case PhysicsServer3D::AREA_PARAM_LINEAR_DAMP: return spOv_linearDump; case PhysicsServer3D::AREA_PARAM_ANGULAR_DAMP: return spOv_angularDump; case PhysicsServer3D::AREA_PARAM_PRIORITY: return spOv_priority; case PhysicsServer3D::AREA_PARAM_GRAVITY_IS_POINT: return spOv_gravityPoint; case PhysicsServer3D::AREA_PARAM_GRAVITY_DISTANCE_SCALE: return spOv_gravityPointDistanceScale; case PhysicsServer3D::AREA_PARAM_GRAVITY_POINT_ATTENUATION: return spOv_gravityPointAttenuation; default: WARN_PRINT("Area doesn't support this parameter in the Bullet backend: " + itos(p_param)); return Variant(); } } void AreaBullet::set_event_callback(Type p_callbackObjectType, ObjectID p_id, const StringName &p_method) { InOutEventCallback &ev = eventsCallbacks[static_cast<int>(p_callbackObjectType)]; ev.event_callback_id = p_id; ev.event_callback_method = p_method; /// Set if monitoring if (eventsCallbacks[0].event_callback_id.is_valid() || eventsCallbacks[1].event_callback_id.is_valid()) { set_godot_object_flags(get_godot_object_flags() | GOF_IS_MONITORING_AREA); } else { set_godot_object_flags(get_godot_object_flags() & (~GOF_IS_MONITORING_AREA)); } } bool AreaBullet::has_event_callback(Type p_callbackObjectType) { return eventsCallbacks[static_cast<int>(p_callbackObjectType)].event_callback_id.is_valid(); } void AreaBullet::on_enter_area(AreaBullet *p_area) { } void AreaBullet::on_exit_area(AreaBullet *p_area) { CollisionObjectBullet::on_exit_area(p_area); } <|endoftext|>
<commit_before>#include <iostream> #include <fstream> #include <string> using namespace std; int main() { string line; ifstream myFile("Animals.txt"); if(myFile.is_open()) { while(getline(myFile, line)) { cout << line << "\n"; } myFile.close(); } else cout << "Unable to open file."; return 0; } <commit_msg>Delete exampleReadFiles.cpp<commit_after><|endoftext|>
<commit_before>// // Created by iskakoff on 19/07/16. // #include <iostream> #include <edlib/EDParams.h> #include "edlib/Hamiltonian.h" #include "edlib/SzSymmetry.h" #include "edlib/SOCRSStorage.h" #include "edlib/CRSStorage.h" #include "edlib/HubbardModel.h" #include "edlib/GreensFunction.h" #include "edlib/ChiLoc.h" #include "edlib/HDF5Utils.h" #include "edlib/SpinResolvedStorage.h" #include "edlib/StaticObervables.h" #include "edlib/MeshFactory.h" int main(int argc, const char ** argv) { #ifdef USE_MPI MPI_Init(&argc, (char ***) &argv); alps::mpi::communicator comm; #endif alps::params params(argc, argv); EDLib::define_parameters(params); if(params.help_requested(std::cout)) { exit(0); } alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE); #ifdef USE_MPI if(comm.rank()) ar.close(); #endif try { #ifdef USE_MPI EDLib::SRSHubbardHamiltonian ham(params, comm); #else EDLib::SRSHubbardHamiltonian ham(params); #endif ham.diag(); EDLib::hdf5::save_eigen_pairs(ham, ar, "results"); EDLib::gf::GreensFunction < EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC); greensFunction.compute(); greensFunction.save(ar, "results"); EDLib::gf::ChiLoc<EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC); susc.compute(); susc.save(ar, "results"); susc.compute<EDLib::gf::NOperator<double> >(); susc.save(ar, "results"); } catch (std::exception & e) { #ifdef USE_MPI if(comm.rank() == 0) std::cerr<<e.what(); #else std::cerr<<e.what(); #endif } #ifdef USE_MPI if(!comm.rank()) #endif ar.close(); #ifdef USE_MPI MPI_Finalize(); #endif return 0; } <commit_msg>time measurements. temporary<commit_after>// // Created by iskakoff on 19/07/16. // #include <iostream> #include <edlib/EDParams.h> #include "edlib/Hamiltonian.h" #include "edlib/SzSymmetry.h" #include "edlib/SOCRSStorage.h" #include "edlib/CRSStorage.h" #include "edlib/HubbardModel.h" #include "edlib/GreensFunction.h" #include "edlib/ChiLoc.h" #include "edlib/HDF5Utils.h" #include "edlib/SpinResolvedStorage.h" #include "edlib/StaticObervables.h" #include "edlib/MeshFactory.h" #include "edlib/ExecutionStatistic.h" int main(int argc, const char ** argv) { #ifdef USE_MPI MPI_Init(&argc, (char ***) &argv); alps::mpi::communicator comm; #endif alps::params params(argc, argv); EDLib::define_parameters(params); if(params.help_requested(std::cout)) { exit(0); } alps::hdf5::archive ar(params["OUTPUT_FILE"], alps::hdf5::archive::WRITE); #ifdef USE_MPI if(comm.rank()) ar.close(); #endif try { #ifdef USE_MPI EDLib::SRSHubbardHamiltonian ham(params, comm); #else EDLib::SRSHubbardHamiltonian ham(params); #endif EDLib::common::statistics.registerEvent("total"); ham.diag(); EDLib::common::statistics.updateEvent("total"); /*EDLib::hdf5::save_eigen_pairs(ham, ar, "results"); EDLib::gf::GreensFunction < EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> greensFunction(params, ham,alps::gf::statistics::statistics_type::FERMIONIC); greensFunction.compute(); greensFunction.save(ar, "results"); EDLib::gf::ChiLoc<EDLib::SRSHubbardHamiltonian, alps::gf::matsubara_positive_mesh, alps::gf::statistics::statistics_type> susc(params, ham, alps::gf::statistics::statistics_type::BOSONIC); susc.compute(); susc.save(ar, "results"); susc.compute<EDLib::gf::NOperator<double> >(); susc.save(ar, "results");*/ EDLib::common::statistics.print(); } catch (std::exception & e) { #ifdef USE_MPI if(comm.rank() == 0) std::cerr<<e.what(); #else std::cerr<<e.what(); #endif } #ifdef USE_MPI if(!comm.rank()) #endif ar.close(); #ifdef USE_MPI MPI_Finalize(); #endif return 0; } <|endoftext|>
<commit_before>#include <iostream.h> #include <iomanip.h> #include <SharedMem/MemPool.h> #include <SharedMem/SharedType.h> #include <Input/vjPosition/vjFlock.h> #include <Input/ibox/ibox.h> #include <Input/vjGlove/vjCyberGlove.h> int main() { MemPool* anSgiPool = new MemPoolSGI(1024*1024); C2Flock* flock = new(anSgiPool) C2Flock; IBox* anIbox = new(anSgiPool) IBox; CyberGlove* aGlove = new(anSgiPool) CyberGlove("/home/vr/CAVE/glove","/dev/ttyd45",38400); C2POS_DATA *data,*data2; C2IBOX_DATA *iboxData; char achar; cout << "U - Update\n" << "S - Start\n" << "X - Stop\n" << "Q - Quit\n" << "O - Output\n"; do { cin >> achar; cout << flush; switch(achar) { case 'u':case 'U': break; case 's':case 'S': flock->StartSampling(); anIbox->StartSampling(); aGlove->StartSampling(); break; case 'x':case 'X': flock->StopSampling(); anIbox->StopSampling(); aGlove->StopSampling(); break; case 'o':case 'O': for(int z = 0; z < 10; z++){ C2GLOVE_DATA *gdata; flock->UpdateData(); flock->GetData(data); flock->GetData(data2); anIbox->UpdateData(); anIbox->GetData(iboxData); // aGlove->UpdateData(); // aGlove->GetData(gdata); system("clear"); cout << "C2Flock------------------------------------------------------------" << endl << "Data: x:" << setw(10) << data->x << " Data2x:" << setw(10) << data2->x << endl << " y:" << setw(10) << data->y << " y:" << setw(10) << data2->y << endl << " z:" << setw(10) << data->z << " z:" << setw(10) << data2->z << endl << " azi:" << setw(10) << data->azi << " azi:" << setw(10) << data2->azi << endl << " elev:" << setw(10) << data->elev << " elev:" << setw(10) << data2->elev << endl << " roll:" << setw(10) <<data->roll << " roll:" << setw(10) <<data2->roll << endl << endl; cout << "Ibox---------------------------------------------------------------" << endl << " button1: " << iboxData->button[0] << endl << " button2: " << iboxData->button[1] << endl << " button3: " << iboxData->button[2] << endl << " button4: " << iboxData->button[3] << endl << endl; /* cout << "Glove--------------------------------------------------------------" << endl << " first finger: " << gdata->joints[0][0] << " " << gdata->joints[0][1] << " " << gdata->joints[0][2] << " " << gdata->joints[0][3] << endl << "second finger: " << gdata->joints[1][0] << " " << gdata->joints[1][1] << " " << gdata->joints[1][2] << " " << gdata->joints[1][3] << endl << " third finger: " << gdata->joints[2][0] << " " << gdata->joints[2][1] << " " << gdata->joints[2][2] << " " << gdata->joints[2][3] << endl << " fourth finger: " << gdata->joints[3][0] << " " << gdata->joints[3][1] << " " << gdata->joints[3][2] << " " << gdata->joints[3][3] << endl; */ sleep(2); } break; } cout << achar; } while ((achar != 'q') && (achar != 'Q')); flock->StopSampling(); anIbox->StopSampling(); aGlove->StopSampling(); delete flock; delete anIbox; delete aGlove; delete anSgiPool; return 0; } <commit_msg>Brought this file a little closer to compiling with the following changes:<commit_after>#include <iostream.h> #include <iomanip.h> #include <SharedMem/vjMemPool.h> //#include <SharedMem/SharedType.h> #include <Input/vjPosition/vjFlock.h> #include <Input/ibox/hci.h> #include <Input/ibox/ibox.h> #include <Input/vjInput/vjIbox.h> #include <Input/vjGlove/vjCyberGlove.h> int main() { vjMemPool* anSgiPool = new vjSharedPool(1024*1024); vjFlock* flock = new(anSgiPool) vjFlock; vjIBox* anIbox = new(anSgiPool) vjIBox; vjCyberGlove* aGlove = new(anSgiPool) vjCyberGlove("/home/vr/CAVE/glove","/dev/ttyd45",38400); vjPOS_DATA *data,*data2; vjIBOX_DATA *iboxData; char achar; cout << "U - Update\n" << "S - Start\n" << "X - Stop\n" << "Q - Quit\n" << "O - Output\n"; do { cin >> achar; cout << flush; switch(achar) { case 'u':case 'U': break; case 's':case 'S': flock->StartSampling(); anIbox->StartSampling(); aGlove->StartSampling(); break; case 'x':case 'X': flock->StopSampling(); anIbox->StopSampling(); aGlove->StopSampling(); break; case 'o':case 'O': for(int z = 0; z < 10; z++){ C2GLOVE_DATA *gdata; flock->UpdateData(); flock->GetData(data); flock->GetData(data2); anIbox->UpdateData(); anIbox->GetData(iboxData); // aGlove->UpdateData(); // aGlove->GetData(gdata); system("clear"); cout << "vjFlock------------------------------------------------------------" << endl << "Data: x:" << setw(10) << data->pos.vec[0] << " Data2x:" << setw(10) << data2->pos.vec[0] << endl << " y:" << setw(10) << data->pos.vec[1] << " y:" << setw(10) << data2->pos.vec[1] << endl << " z:" << setw(10) << data->pos.vec[2] << " z:" << setw(10) << data2->pos.vec[2] << endl << " azi:" << setw(10) << data->orient.vec[0] << " azi:" << setw(10) << data2->orient.vec[0] << endl << " elev:" << setw(10) << data->orient.vec[1] << " elev:" << setw(10) << data2->orient.vec[1] << endl << " roll:" << setw(10) <<data->orient.vec[2] << " roll:" << setw(10) <<data2->orient.vec[2] << endl << endl; cout << "Ibox---------------------------------------------------------------" << endl << " button1: " << iboxData->button[0] << endl << " button2: " << iboxData->button[1] << endl << " button3: " << iboxData->button[2] << endl << " button4: " << iboxData->button[3] << endl << endl; /* cout << "Glove--------------------------------------------------------------" << endl << " first finger: " << gdata->joints[0][0] << " " << gdata->joints[0][1] << " " << gdata->joints[0][2] << " " << gdata->joints[0][3] << endl << "second finger: " << gdata->joints[1][0] << " " << gdata->joints[1][1] << " " << gdata->joints[1][2] << " " << gdata->joints[1][3] << endl << " third finger: " << gdata->joints[2][0] << " " << gdata->joints[2][1] << " " << gdata->joints[2][2] << " " << gdata->joints[2][3] << endl << " fourth finger: " << gdata->joints[3][0] << " " << gdata->joints[3][1] << " " << gdata->joints[3][2] << " " << gdata->joints[3][3] << endl; */ sleep(2); } break; } cout << achar; } while ((achar != 'q') && (achar != 'Q')); flock->StopSampling(); anIbox->StopSampling(); aGlove->StopSampling(); delete flock; delete anIbox; delete aGlove; delete anSgiPool; return 0; } <|endoftext|>
<commit_before>// XYFunctionInterface.cpp // Authors: Peter Loan /* * Copyright (c) 2009, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //============================================================================= // INCLUDES //============================================================================= #include "XYFunctionInterface.h" namespace OpenSim { bool XYFunctionInterface::isXYFunction(Function* f) { Function* func = f; MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f); if (mf) func = mf->getFunction(); if (dynamic_cast<Constant*>(func) || dynamic_cast<StepFunction*>(func) || dynamic_cast<PiecewiseLinearFunction*>(func) || dynamic_cast<LinearFunction*>(func) || dynamic_cast<SimmSpline*>(func) || dynamic_cast<GCVSpline*>(func)|| dynamic_cast<PiecewiseConstantFunction*>(func)) return true; return false; } XYFunctionInterface::XYFunctionInterface(Function* f) : _functionType(typeUndefined), _constant(0), _stepFunction(0), _linearFunction(0), _natCubicSpline(0), _gcvSpline(0), _mStepFunction(0) { Function* func; MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f); if (mf) { func = mf->getFunction(); _scaleFactor = mf->getScale(); } else { func = f; _scaleFactor = 1.0; } _constant = dynamic_cast<Constant*>(func); if (_constant) { _functionType = typeConstant; return; } _stepFunction = dynamic_cast<StepFunction*>(func); if (_stepFunction) { _functionType = typeStepFunction; return; } _mStepFunction = dynamic_cast<PiecewiseConstantFunction*>(func); if (_mStepFunction) { _functionType = typePiecewiseConstantFunction; return; } _piecewiseLinearFunction = dynamic_cast<PiecewiseLinearFunction*>(func); if (_piecewiseLinearFunction) { _functionType = typePiecewiseLinearFunction; return; } _linearFunction = dynamic_cast<LinearFunction*>(func); if (_linearFunction) { _functionType = typeLinearFunction; return; } _natCubicSpline = dynamic_cast<SimmSpline*>(func); if (_natCubicSpline) { _functionType = typeNatCubicSpline; return; } _gcvSpline = dynamic_cast<GCVSpline*>(func); if (_gcvSpline) { _functionType = typeGCVSpline; return; } throw Exception("Object " + getName() + " of type " + getConcreteClassName() + " is not an XYFunction."); } int XYFunctionInterface::getNumberOfPoints() const { switch (_functionType) { case typeConstant: return 0; case typePiecewiseConstantFunction: return _mStepFunction->getNumberOfPoints(); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getNumberOfPoints(); case typeLinearFunction: return 2; case typeNatCubicSpline: return _natCubicSpline->getNumberOfPoints(); case typeGCVSpline: return _gcvSpline->getNumberOfPoints(); default: return 0; } } const double* XYFunctionInterface::getXValues() const { switch (_functionType) { case typeConstant: return NULL; case typeStepFunction: return NULL; case typePiecewiseConstantFunction: return _mStepFunction->getXValues(); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getXValues(); case typeLinearFunction: { double* xValues = new double[2]; xValues[0] = -1.0; xValues[1] = 1.0; return xValues; // possible memory leak } case typeNatCubicSpline: return _natCubicSpline->getXValues(); case typeGCVSpline: return _gcvSpline->getXValues(); default: return 0; } } const double* XYFunctionInterface::getYValues() const { const double* yValues = NULL; double* tmp = NULL; int numPoints = getNumberOfPoints(); switch (_functionType) { case typeConstant: return NULL; case typeStepFunction: return NULL;; break; case typePiecewiseConstantFunction: yValues = _mStepFunction->getYValues(); break; case typePiecewiseLinearFunction: yValues = _piecewiseLinearFunction->getYValues(); break; case typeLinearFunction: tmp = new double[2]; tmp[0] = _linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]; tmp[1] = _linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]; break; case typeNatCubicSpline: yValues = _natCubicSpline->getYValues(); break; case typeGCVSpline: yValues = _gcvSpline->getYValues(); break; default: return NULL; } double* scaledY = new double[numPoints]; memcpy(scaledY, yValues, numPoints*sizeof(double)); for (int i=0; i<numPoints; i++) scaledY[i] *= _scaleFactor; if (tmp) delete tmp; // possible memory leak return scaledY; } double XYFunctionInterface::getX(int aIndex) const { switch (_functionType) { case typeConstant: return 0; //_constant->getX(aIndex); case typeStepFunction: return 0; //_stepFunction->getX(aIndex); case typePiecewiseConstantFunction: return _mStepFunction->getX(aIndex); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getX(aIndex); case typeLinearFunction: if (aIndex == 0) return -1.0; else if (aIndex == 1) return 1.0; else return 0.0; case typeNatCubicSpline: return _natCubicSpline->getX(aIndex); case typeGCVSpline: return _gcvSpline->getX(aIndex); default: return 0.0; } } double XYFunctionInterface::getY(int aIndex) const { switch (_functionType) { case typeConstant: return _constant->getValue() * _scaleFactor; case typeStepFunction: return SimTK::NaN; case typePiecewiseConstantFunction: return _mStepFunction->getY(aIndex) * _scaleFactor; case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getY(aIndex) * _scaleFactor; case typeLinearFunction: if (aIndex == 0) return (_linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]) * _scaleFactor; else if (aIndex == 1) return (_linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]) * _scaleFactor; else return 0.0; case typeNatCubicSpline: return _natCubicSpline->getY(aIndex) * _scaleFactor; case typeGCVSpline: return _gcvSpline->getY(aIndex) * _scaleFactor; default: return 0.0; } } void XYFunctionInterface::setX(int aIndex, double aValue) { switch (_functionType) { case typeConstant: break; case typePiecewiseConstantFunction: _mStepFunction->setX(aIndex, aValue); break; case typePiecewiseLinearFunction: _piecewiseLinearFunction->setX(aIndex, aValue); break; case typeLinearFunction: break; case typeNatCubicSpline: _natCubicSpline->setX(aIndex, aValue); break; case typeGCVSpline: _gcvSpline->setX(aIndex, aValue); break; default: return; } } void XYFunctionInterface::setY(int aIndex, double aValue) { aValue /= _scaleFactor; switch (_functionType) { case typeConstant: break; case typePiecewiseConstantFunction: _mStepFunction->setY(aIndex, aValue); break; case typePiecewiseLinearFunction: _piecewiseLinearFunction->setY(aIndex, aValue); break; case typeLinearFunction: break; case typeNatCubicSpline: _natCubicSpline->setY(aIndex, aValue); break; case typeGCVSpline: _gcvSpline->setY(aIndex, aValue); break; default: return; } } bool XYFunctionInterface::deletePoint(int aIndex) { switch (_functionType) { case typeConstant: return true; case typeStepFunction: return false; case typePiecewiseConstantFunction: return _mStepFunction->deletePoint(aIndex); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->deletePoint(aIndex); case typeLinearFunction: return false; case typeNatCubicSpline: return _natCubicSpline->deletePoint(aIndex); case typeGCVSpline: return _gcvSpline->deletePoint(aIndex); default: return true; } } bool XYFunctionInterface::deletePoints(const Array<int>& indices) { switch (_functionType) { case typeConstant: return true; case typeStepFunction: return false; case typePiecewiseConstantFunction: return _mStepFunction->deletePoints(indices); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->deletePoints(indices); case typeLinearFunction: return false; case typeNatCubicSpline: return _natCubicSpline->deletePoints(indices); case typeGCVSpline: return _gcvSpline->deletePoints(indices); default: return true; } } int XYFunctionInterface::addPoint(double aX, double aY) { aY /= _scaleFactor; switch (_functionType) { case typeConstant: return 1; case typeStepFunction: return 0; case typePiecewiseConstantFunction: return _mStepFunction->addPoint(aX, aY); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->addPoint(aX, aY); case typeLinearFunction: return 0; case typeNatCubicSpline: return _natCubicSpline->addPoint(aX, aY); case typeGCVSpline: return _gcvSpline->addPoint(aX, aY); default: return 1; } } Array<XYPoint>* XYFunctionInterface::renderAsLineSegments(int aIndex) { if (_functionType == typeUndefined || _functionType == typeConstant || _functionType == typeLinearFunction || aIndex < 0 || aIndex >= getNumberOfPoints() - 1) return NULL; Array<XYPoint>* xyPts = new Array<XYPoint>(XYPoint()); const double* x = getXValues(); const double* y = getYValues(); if (_functionType == typeStepFunction) { xyPts->append(XYPoint(x[aIndex], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1])); } else if (_functionType == typePiecewiseLinearFunction) { xyPts->append(XYPoint(x[aIndex], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1])); } else if (_functionType == typeNatCubicSpline) { // X sometimes goes slightly beyond the range due to roundoff error, // so do the last point separately. int numSegs = 20; for (int i=0; i<numSegs-1; i++) { double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0); xyPts->append(XYPoint(xValue, _natCubicSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor)); } xyPts->append(XYPoint(x[aIndex + 1], _natCubicSpline->calcValue(SimTK::Vector(1,x[aIndex+1])) * _scaleFactor)); } else if (_functionType == typeGCVSpline) { // X sometimes goes slightly beyond the range due to roundoff error, // so do the last point separately. int numSegs = 20; for (int i=0; i<numSegs-1; i++) { double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0); xyPts->append(XYPoint(xValue, _gcvSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor)); } xyPts->append(XYPoint(x[aIndex + 1], _gcvSpline->calcValue(SimTK::Vector(1,x[aIndex + 1])) * _scaleFactor)); } return xyPts; } } // namespace <commit_msg>Change display of PiecewiseConstantFunction in Excitation Editor to reflect actual interpretation by CMC.<commit_after>// XYFunctionInterface.cpp // Authors: Peter Loan /* * Copyright (c) 2009, Stanford University. All rights reserved. * Use of the OpenSim software in source form is permitted provided that the following * conditions are met: * 1. The software is used only for non-commercial research and education. It may not * be used in relation to any commercial activity. * 2. The software is not distributed or redistributed. Software distribution is allowed * only through https://simtk.org/home/opensim. * 3. Use of the OpenSim software or derivatives must be acknowledged in all publications, * presentations, or documents describing work in which OpenSim or derivatives are used. * 4. Credits to developers may not be removed from executables * created from modifications of the source. * 5. Modifications of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * * 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; * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR BUSINESS INTERRUPTION) 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. */ //============================================================================= // INCLUDES //============================================================================= #include "XYFunctionInterface.h" namespace OpenSim { bool XYFunctionInterface::isXYFunction(Function* f) { Function* func = f; MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f); if (mf) func = mf->getFunction(); if (dynamic_cast<Constant*>(func) || dynamic_cast<StepFunction*>(func) || dynamic_cast<PiecewiseLinearFunction*>(func) || dynamic_cast<LinearFunction*>(func) || dynamic_cast<SimmSpline*>(func) || dynamic_cast<GCVSpline*>(func)|| dynamic_cast<PiecewiseConstantFunction*>(func)) return true; return false; } XYFunctionInterface::XYFunctionInterface(Function* f) : _functionType(typeUndefined), _constant(0), _stepFunction(0), _linearFunction(0), _natCubicSpline(0), _gcvSpline(0), _mStepFunction(0) { Function* func; MultiplierFunction* mf = dynamic_cast<MultiplierFunction*>(f); if (mf) { func = mf->getFunction(); _scaleFactor = mf->getScale(); } else { func = f; _scaleFactor = 1.0; } _constant = dynamic_cast<Constant*>(func); if (_constant) { _functionType = typeConstant; return; } _stepFunction = dynamic_cast<StepFunction*>(func); if (_stepFunction) { _functionType = typeStepFunction; return; } _mStepFunction = dynamic_cast<PiecewiseConstantFunction*>(func); if (_mStepFunction) { _functionType = typePiecewiseConstantFunction; return; } _piecewiseLinearFunction = dynamic_cast<PiecewiseLinearFunction*>(func); if (_piecewiseLinearFunction) { _functionType = typePiecewiseLinearFunction; return; } _linearFunction = dynamic_cast<LinearFunction*>(func); if (_linearFunction) { _functionType = typeLinearFunction; return; } _natCubicSpline = dynamic_cast<SimmSpline*>(func); if (_natCubicSpline) { _functionType = typeNatCubicSpline; return; } _gcvSpline = dynamic_cast<GCVSpline*>(func); if (_gcvSpline) { _functionType = typeGCVSpline; return; } throw Exception("Object " + getName() + " of type " + getConcreteClassName() + " is not an XYFunction."); } int XYFunctionInterface::getNumberOfPoints() const { switch (_functionType) { case typeConstant: return 0; case typePiecewiseConstantFunction: return _mStepFunction->getNumberOfPoints(); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getNumberOfPoints(); case typeLinearFunction: return 2; case typeNatCubicSpline: return _natCubicSpline->getNumberOfPoints(); case typeGCVSpline: return _gcvSpline->getNumberOfPoints(); default: return 0; } } const double* XYFunctionInterface::getXValues() const { switch (_functionType) { case typeConstant: return NULL; case typeStepFunction: return NULL; case typePiecewiseConstantFunction: return _mStepFunction->getXValues(); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getXValues(); case typeLinearFunction: { double* xValues = new double[2]; xValues[0] = -1.0; xValues[1] = 1.0; return xValues; // possible memory leak } case typeNatCubicSpline: return _natCubicSpline->getXValues(); case typeGCVSpline: return _gcvSpline->getXValues(); default: return 0; } } const double* XYFunctionInterface::getYValues() const { const double* yValues = NULL; double* tmp = NULL; int numPoints = getNumberOfPoints(); switch (_functionType) { case typeConstant: return NULL; case typeStepFunction: return NULL;; break; case typePiecewiseConstantFunction: yValues = _mStepFunction->getYValues(); break; case typePiecewiseLinearFunction: yValues = _piecewiseLinearFunction->getYValues(); break; case typeLinearFunction: tmp = new double[2]; tmp[0] = _linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]; tmp[1] = _linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]; break; case typeNatCubicSpline: yValues = _natCubicSpline->getYValues(); break; case typeGCVSpline: yValues = _gcvSpline->getYValues(); break; default: return NULL; } double* scaledY = new double[numPoints]; memcpy(scaledY, yValues, numPoints*sizeof(double)); for (int i=0; i<numPoints; i++) scaledY[i] *= _scaleFactor; if (tmp) delete tmp; // possible memory leak return scaledY; } double XYFunctionInterface::getX(int aIndex) const { switch (_functionType) { case typeConstant: return 0; //_constant->getX(aIndex); case typeStepFunction: return 0; //_stepFunction->getX(aIndex); case typePiecewiseConstantFunction: return _mStepFunction->getX(aIndex); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getX(aIndex); case typeLinearFunction: if (aIndex == 0) return -1.0; else if (aIndex == 1) return 1.0; else return 0.0; case typeNatCubicSpline: return _natCubicSpline->getX(aIndex); case typeGCVSpline: return _gcvSpline->getX(aIndex); default: return 0.0; } } double XYFunctionInterface::getY(int aIndex) const { switch (_functionType) { case typeConstant: return _constant->getValue() * _scaleFactor; case typeStepFunction: return SimTK::NaN; case typePiecewiseConstantFunction: return _mStepFunction->getY(aIndex) * _scaleFactor; case typePiecewiseLinearFunction: return _piecewiseLinearFunction->getY(aIndex) * _scaleFactor; case typeLinearFunction: if (aIndex == 0) return (_linearFunction->getCoefficients()[1] - _linearFunction->getCoefficients()[0]) * _scaleFactor; else if (aIndex == 1) return (_linearFunction->getCoefficients()[1] + _linearFunction->getCoefficients()[0]) * _scaleFactor; else return 0.0; case typeNatCubicSpline: return _natCubicSpline->getY(aIndex) * _scaleFactor; case typeGCVSpline: return _gcvSpline->getY(aIndex) * _scaleFactor; default: return 0.0; } } void XYFunctionInterface::setX(int aIndex, double aValue) { switch (_functionType) { case typeConstant: break; case typePiecewiseConstantFunction: _mStepFunction->setX(aIndex, aValue); break; case typePiecewiseLinearFunction: _piecewiseLinearFunction->setX(aIndex, aValue); break; case typeLinearFunction: break; case typeNatCubicSpline: _natCubicSpline->setX(aIndex, aValue); break; case typeGCVSpline: _gcvSpline->setX(aIndex, aValue); break; default: return; } } void XYFunctionInterface::setY(int aIndex, double aValue) { aValue /= _scaleFactor; switch (_functionType) { case typeConstant: break; case typePiecewiseConstantFunction: _mStepFunction->setY(aIndex, aValue); break; case typePiecewiseLinearFunction: _piecewiseLinearFunction->setY(aIndex, aValue); break; case typeLinearFunction: break; case typeNatCubicSpline: _natCubicSpline->setY(aIndex, aValue); break; case typeGCVSpline: _gcvSpline->setY(aIndex, aValue); break; default: return; } } bool XYFunctionInterface::deletePoint(int aIndex) { switch (_functionType) { case typeConstant: return true; case typeStepFunction: return false; case typePiecewiseConstantFunction: return _mStepFunction->deletePoint(aIndex); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->deletePoint(aIndex); case typeLinearFunction: return false; case typeNatCubicSpline: return _natCubicSpline->deletePoint(aIndex); case typeGCVSpline: return _gcvSpline->deletePoint(aIndex); default: return true; } } bool XYFunctionInterface::deletePoints(const Array<int>& indices) { switch (_functionType) { case typeConstant: return true; case typeStepFunction: return false; case typePiecewiseConstantFunction: return _mStepFunction->deletePoints(indices); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->deletePoints(indices); case typeLinearFunction: return false; case typeNatCubicSpline: return _natCubicSpline->deletePoints(indices); case typeGCVSpline: return _gcvSpline->deletePoints(indices); default: return true; } } int XYFunctionInterface::addPoint(double aX, double aY) { aY /= _scaleFactor; switch (_functionType) { case typeConstant: return 1; case typeStepFunction: return 0; case typePiecewiseConstantFunction: return _mStepFunction->addPoint(aX, aY); case typePiecewiseLinearFunction: return _piecewiseLinearFunction->addPoint(aX, aY); case typeLinearFunction: return 0; case typeNatCubicSpline: return _natCubicSpline->addPoint(aX, aY); case typeGCVSpline: return _gcvSpline->addPoint(aX, aY); default: return 1; } } Array<XYPoint>* XYFunctionInterface::renderAsLineSegments(int aIndex) { if (_functionType == typeUndefined || _functionType == typeConstant || _functionType == typeLinearFunction || aIndex < 0 || aIndex >= getNumberOfPoints() - 1) return NULL; Array<XYPoint>* xyPts = new Array<XYPoint>(XYPoint()); const double* x = getXValues(); const double* y = getYValues(); if (_functionType == typeStepFunction) { xyPts->append(XYPoint(x[aIndex], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1])); } else if (_functionType == typePiecewiseLinearFunction) { xyPts->append(XYPoint(x[aIndex], y[aIndex])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1])); } else if (_functionType == typeNatCubicSpline) { // X sometimes goes slightly beyond the range due to roundoff error, // so do the last point separately. int numSegs = 20; for (int i=0; i<numSegs-1; i++) { double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0); xyPts->append(XYPoint(xValue, _natCubicSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor)); } xyPts->append(XYPoint(x[aIndex + 1], _natCubicSpline->calcValue(SimTK::Vector(1,x[aIndex+1])) * _scaleFactor)); } else if (_functionType == typeGCVSpline) { // X sometimes goes slightly beyond the range due to roundoff error, // so do the last point separately. int numSegs = 20; for (int i=0; i<numSegs-1; i++) { double xValue = x[aIndex] + (double)i * (x[aIndex + 1] - x[aIndex]) / ((double)numSegs - 1.0); xyPts->append(XYPoint(xValue, _gcvSpline->calcValue(SimTK::Vector(1,xValue)) * _scaleFactor)); } xyPts->append(XYPoint(x[aIndex + 1], _gcvSpline->calcValue(SimTK::Vector(1,x[aIndex + 1])) * _scaleFactor)); } else if (_functionType == typePiecewiseConstantFunction) { xyPts->append(XYPoint(x[aIndex], y[aIndex])); xyPts->append(XYPoint(x[aIndex], y[aIndex+1])); xyPts->append(XYPoint(x[aIndex+1], y[aIndex+1])); } return xyPts; } } // namespace <|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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkBSplineDecompositionImageFilter_hxx #define itkBSplineDecompositionImageFilter_hxx #include "itkBSplineDecompositionImageFilter.h" #include "itkImageRegionConstIteratorWithIndex.h" #include "itkImageRegionIterator.h" #include "itkProgressReporter.h" #include "itkVector.h" namespace itk { template< typename TInputImage, typename TOutputImage > BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::BSplineDecompositionImageFilter() { this->SetSplineOrder( 3 ); for( unsigned int i = 0; i < m_Scratch.size(); ++i ) { m_Scratch[i] = 0; } m_DataLength.Fill( itk::NumericTraits< typename TInputImage::SizeType::SizeValueType >::ZeroValue() ); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::PrintSelf( std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scratch: " << std::endl; for( unsigned int i = 0; i < m_Scratch.size(); ++i ) { os << indent << "[" << i << "]: " << m_Scratch[i] << std::endl; } os << indent << "Data Length: " << m_DataLength << std::endl; os << indent << "Spline Order: " << m_SplineOrder << std::endl; os << indent << "SplinePoles: " << std::endl; for( unsigned int i = 0; i < m_SplinePoles.size(); ++i ) { os << indent << "[" << i << "]" << m_SplinePoles[i] << std::endl; } os << indent << "Number Of Poles: " << m_NumberOfPoles << std::endl; os << indent << "Tolerance: " << m_Tolerance << std::endl; os << indent << "Iterator Direction: " << m_IteratorDirection << std::endl; } template< typename TInputImage, typename TOutputImage > bool BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::DataToCoefficients1D() { // See Unser, 1993, Part II, Equation 2.5, // or Unser, 1999, Box 2. for an explanation. double c0 = 1.0; if ( m_DataLength[m_IteratorDirection] == 1 ) // Required by mirror boundaries { return false; } // Compute over all gain for ( int k = 0; k < m_NumberOfPoles; k++ ) { // Note for cubic splines lambda = 6 c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] ); } // Apply the gain for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ ) { m_Scratch[n] *= c0; } // Loop over all poles for ( int k = 0; k < m_NumberOfPoles; k++ ) { // Causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); // Causal recursion for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ ) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; } // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); // anticausal recursion for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- ) { m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] ); } } return true; } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetSplineOrder(unsigned int SplineOrder) { if ( SplineOrder == m_SplineOrder ) { return; } m_SplinePoles.clear(); m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetPoles() { // See Unser, 1997. Part II, Table I for Pole values. // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac // N. Bankman, 2000, pg. 416. switch ( m_SplineOrder ) { case 3: m_NumberOfPoles = 1; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt(3.0) - 2.0; break; case 0: m_NumberOfPoles = 0; break; case 1: m_NumberOfPoles = 0; break; case 2: m_NumberOfPoles = 1; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt(8.0) - 3.0; break; case 4: m_NumberOfPoles = 2; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0; m_SplinePoles.at( 1 ) = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0; break; case 5: m_NumberOfPoles = 2; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0) - 13.0 / 2.0; m_SplinePoles.at( 1 ) = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0) - 13.0 / 2.0; break; default: // SplineOrder not implemented yet. itkExceptionMacro(<< "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet."); break; } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetInitialCausalCoefficient(double z) { // See Unser, 1999, Box 2 for explanation CoeffType sum; double zn, z2n, iz; typename TInputImage::SizeValueType horizon; // Yhis initialization corresponds to mirror boundaries horizon = m_DataLength[m_IteratorDirection]; zn = z; if ( m_Tolerance > 0.0 ) { horizon = (typename TInputImage::SizeValueType) std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) ); } if ( horizon < m_DataLength[m_IteratorDirection] ) { // Accelerated loop sum = m_Scratch[0]; // verify this for ( unsigned int n = 1; n < horizon; n++ ) { sum += zn * m_Scratch[n]; zn *= z; } m_Scratch[0] = sum; } else { // Full loop iz = 1.0 / z; z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) ); sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; z2n *= z2n * iz; for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ ) { sum += ( zn + z2n ) * m_Scratch[n]; zn *= z; z2n *= iz; } m_Scratch[0] = sum / ( 1.0 - zn * zn ); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetInitialAntiCausalCoefficient(double z) { // This initialization corresponds to mirror boundaries. // See Unser, 1999, Box 2 for explanation. // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = ( z / ( z * z - 1.0 ) ) * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] ); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::DataToCoefficientsND() { OutputImagePointer output = this->GetOutput(); Size< ImageDimension > size = output->GetBufferedRegion().GetSize(); unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension; ProgressReporter progress(this, 0, count, 10); // Initialize coeffient array this->CopyImageToImage(); // Coefficients are initialized to the input data // Loop through each dimension for ( unsigned int n = 0; n < ImageDimension; n++ ) { m_IteratorDirection = n; // Initialize iterators OutputLinearIterator CIterator( output, output->GetBufferedRegion() ); CIterator.SetDirection(m_IteratorDirection); // For each data vector while ( !CIterator.IsAtEnd() ) { // Copy coefficients to scratch this->CopyCoefficientsToScratch(CIterator); // Perform 1D BSpline calculations this->DataToCoefficients1D(); // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); this->CopyScratchToCoefficients(CIterator); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); } } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyImageToImage() { using InputIterator = ImageRegionConstIteratorWithIndex< TInputImage >; using OutputIterator = ImageRegionIterator< TOutputImage >; using OutputPixelType = typename TOutputImage::PixelType; InputIterator inIt( this->GetInput(), this->GetInput()->GetBufferedRegion() ); OutputIterator outIt( this->GetOutput(), this->GetOutput()->GetBufferedRegion() ); inIt.GoToBegin(); outIt.GoToBegin(); while ( !outIt.IsAtEnd() ) { outIt.Set( static_cast< OutputPixelType >( inIt.Get() ) ); ++inIt; ++outIt; } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyScratchToCoefficients(OutputLinearIterator & Iter) { using OutputPixelType = typename TOutputImage::PixelType; typename TOutputImage::SizeValueType j = 0; while ( !Iter.IsAtEndOfLine() ) { Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) ); ++Iter; ++j; } } /** */ template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyCoefficientsToScratch(OutputLinearIterator & Iter) { typename TOutputImage::SizeValueType j = 0; while ( !Iter.IsAtEndOfLine() ) { m_Scratch[j] = static_cast< CoeffType >( Iter.Get() ); ++Iter; ++j; } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() { // This filter requires all of the input image to be in the buffer InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); if ( inputPtr ) { inputPtr->SetRequestedRegionToLargestPossibleRegion(); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::EnlargeOutputRequestedRegion(DataObject *output) { // This filter requires all of the input image to be in the buffer TOutputImage *imgData; imgData = dynamic_cast< TOutputImage * >( output ); if ( imgData ) { imgData->SetRequestedRegionToLargestPossibleRegion(); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::GenerateData() { // Allocate scratch memory InputImageConstPointer inputPtr = this->GetInput(); m_DataLength = inputPtr->GetBufferedRegion().GetSize(); typename TOutputImage::SizeValueType maxLength = 0; for ( unsigned int n = 0; n < ImageDimension; n++ ) { if ( m_DataLength[n] > maxLength ) { maxLength = m_DataLength[n]; } } m_Scratch.resize(maxLength); // Allocate memory for output image OutputImagePointer outputPtr = this->GetOutput(); outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); outputPtr->Allocate(); // Calculate actual output this->DataToCoefficientsND(); // Clean up m_Scratch.clear(); } } // namespace itk #endif <commit_msg>PERF: BSplineDecompositionImageFilter now calls ImageAlgorithm::Copy<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. * *=========================================================================*/ /*========================================================================= * * Portions of this file are subject to the VTK Toolkit Version 3 copyright. * * Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen * * For complete copyright, license and disclaimer of warranty information * please refer to the NOTICE file at the top of the ITK source tree. * *=========================================================================*/ #ifndef itkBSplineDecompositionImageFilter_hxx #define itkBSplineDecompositionImageFilter_hxx #include "itkBSplineDecompositionImageFilter.h" #include "itkImageAlgorithm.h" #include "itkProgressReporter.h" #include "itkVector.h" namespace itk { template< typename TInputImage, typename TOutputImage > BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::BSplineDecompositionImageFilter() { this->SetSplineOrder( 3 ); for( unsigned int i = 0; i < m_Scratch.size(); ++i ) { m_Scratch[i] = 0; } m_DataLength.Fill( itk::NumericTraits< typename TInputImage::SizeType::SizeValueType >::ZeroValue() ); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::PrintSelf( std::ostream & os, Indent indent) const { Superclass::PrintSelf(os, indent); os << indent << "Scratch: " << std::endl; for( unsigned int i = 0; i < m_Scratch.size(); ++i ) { os << indent << "[" << i << "]: " << m_Scratch[i] << std::endl; } os << indent << "Data Length: " << m_DataLength << std::endl; os << indent << "Spline Order: " << m_SplineOrder << std::endl; os << indent << "SplinePoles: " << std::endl; for( unsigned int i = 0; i < m_SplinePoles.size(); ++i ) { os << indent << "[" << i << "]" << m_SplinePoles[i] << std::endl; } os << indent << "Number Of Poles: " << m_NumberOfPoles << std::endl; os << indent << "Tolerance: " << m_Tolerance << std::endl; os << indent << "Iterator Direction: " << m_IteratorDirection << std::endl; } template< typename TInputImage, typename TOutputImage > bool BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::DataToCoefficients1D() { // See Unser, 1993, Part II, Equation 2.5, // or Unser, 1999, Box 2. for an explanation. double c0 = 1.0; if ( m_DataLength[m_IteratorDirection] == 1 ) // Required by mirror boundaries { return false; } // Compute over all gain for ( int k = 0; k < m_NumberOfPoles; k++ ) { // Note for cubic splines lambda = 6 c0 = c0 * ( 1.0 - m_SplinePoles[k] ) * ( 1.0 - 1.0 / m_SplinePoles[k] ); } // Apply the gain for ( unsigned int n = 0; n < m_DataLength[m_IteratorDirection]; n++ ) { m_Scratch[n] *= c0; } // Loop over all poles for ( int k = 0; k < m_NumberOfPoles; k++ ) { // Causal initialization this->SetInitialCausalCoefficient(m_SplinePoles[k]); // Causal recursion for ( unsigned int n = 1; n < m_DataLength[m_IteratorDirection]; n++ ) { m_Scratch[n] += m_SplinePoles[k] * m_Scratch[n - 1]; } // anticausal initialization this->SetInitialAntiCausalCoefficient(m_SplinePoles[k]); // anticausal recursion for ( int n = m_DataLength[m_IteratorDirection] - 2; 0 <= n; n-- ) { m_Scratch[n] = m_SplinePoles[k] * ( m_Scratch[n + 1] - m_Scratch[n] ); } } return true; } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetSplineOrder(unsigned int SplineOrder) { if ( SplineOrder == m_SplineOrder ) { return; } m_SplinePoles.clear(); m_SplineOrder = SplineOrder; this->SetPoles(); this->Modified(); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetPoles() { // See Unser, 1997. Part II, Table I for Pole values. // See also, Handbook of Medical Imaging, Processing and Analysis, Ed. Isaac // N. Bankman, 2000, pg. 416. switch ( m_SplineOrder ) { case 3: m_NumberOfPoles = 1; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt(3.0) - 2.0; break; case 0: m_NumberOfPoles = 0; break; case 1: m_NumberOfPoles = 0; break; case 2: m_NumberOfPoles = 1; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt(8.0) - 3.0; break; case 4: m_NumberOfPoles = 2; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt( 664.0 - std::sqrt(438976.0) ) + std::sqrt(304.0) - 19.0; m_SplinePoles.at( 1 ) = std::sqrt( 664.0 + std::sqrt(438976.0) ) - std::sqrt(304.0) - 19.0; break; case 5: m_NumberOfPoles = 2; m_SplinePoles.resize( m_NumberOfPoles ); m_SplinePoles.at( 0 ) = std::sqrt( 135.0 / 2.0 - std::sqrt(17745.0 / 4.0) ) + std::sqrt(105.0 / 4.0) - 13.0 / 2.0; m_SplinePoles.at( 1 ) = std::sqrt( 135.0 / 2.0 + std::sqrt(17745.0 / 4.0) ) - std::sqrt(105.0 / 4.0) - 13.0 / 2.0; break; default: // SplineOrder not implemented yet. itkExceptionMacro(<< "SplineOrder must be between 0 and 5. Requested spline order has not been implemented yet."); break; } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetInitialCausalCoefficient(double z) { // See Unser, 1999, Box 2 for explanation CoeffType sum; double zn, z2n, iz; typename TInputImage::SizeValueType horizon; // Yhis initialization corresponds to mirror boundaries horizon = m_DataLength[m_IteratorDirection]; zn = z; if ( m_Tolerance > 0.0 ) { horizon = (typename TInputImage::SizeValueType) std::ceil( std::log(m_Tolerance) / std::log( std::fabs(z) ) ); } if ( horizon < m_DataLength[m_IteratorDirection] ) { // Accelerated loop sum = m_Scratch[0]; // verify this for ( unsigned int n = 1; n < horizon; n++ ) { sum += zn * m_Scratch[n]; zn *= z; } m_Scratch[0] = sum; } else { // Full loop iz = 1.0 / z; z2n = std::pow( z, (double)( m_DataLength[m_IteratorDirection] - 1L ) ); sum = m_Scratch[0] + z2n * m_Scratch[m_DataLength[m_IteratorDirection] - 1L]; z2n *= z2n * iz; for ( unsigned int n = 1; n <= ( m_DataLength[m_IteratorDirection] - 2 ); n++ ) { sum += ( zn + z2n ) * m_Scratch[n]; zn *= z; z2n *= iz; } m_Scratch[0] = sum / ( 1.0 - zn * zn ); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::SetInitialAntiCausalCoefficient(double z) { // This initialization corresponds to mirror boundaries. // See Unser, 1999, Box 2 for explanation. // Also see erratum at http://bigwww.epfl.ch/publications/unser9902.html m_Scratch[m_DataLength[m_IteratorDirection] - 1] = ( z / ( z * z - 1.0 ) ) * ( z * m_Scratch[m_DataLength[m_IteratorDirection] - 2] + m_Scratch[m_DataLength[m_IteratorDirection] - 1] ); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::DataToCoefficientsND() { OutputImagePointer output = this->GetOutput(); Size< ImageDimension > size = output->GetBufferedRegion().GetSize(); unsigned int count = output->GetBufferedRegion().GetNumberOfPixels() / size[0] * ImageDimension; ProgressReporter progress(this, 0, count, 10); // Initialize coeffient array this->CopyImageToImage(); // Coefficients are initialized to the input data // Loop through each dimension for ( unsigned int n = 0; n < ImageDimension; n++ ) { m_IteratorDirection = n; // Initialize iterators OutputLinearIterator CIterator( output, output->GetBufferedRegion() ); CIterator.SetDirection(m_IteratorDirection); // For each data vector while ( !CIterator.IsAtEnd() ) { // Copy coefficients to scratch this->CopyCoefficientsToScratch(CIterator); // Perform 1D BSpline calculations this->DataToCoefficients1D(); // Copy scratch back to coefficients. // Brings us back to the end of the line we were working on. CIterator.GoToBeginOfLine(); this->CopyScratchToCoefficients(CIterator); // m_Scratch = m_Image; CIterator.NextLine(); progress.CompletedPixel(); } } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyImageToImage() { const TInputImage* const inputImage = this->GetInput(); TOutputImage* const outputImage = this->GetOutput(); ImageAlgorithm::Copy(inputImage, outputImage, inputImage->GetBufferedRegion(), outputImage->GetBufferedRegion()); } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyScratchToCoefficients(OutputLinearIterator & Iter) { using OutputPixelType = typename TOutputImage::PixelType; typename TOutputImage::SizeValueType j = 0; while ( !Iter.IsAtEndOfLine() ) { Iter.Set( static_cast< OutputPixelType >( m_Scratch[j] ) ); ++Iter; ++j; } } /** */ template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::CopyCoefficientsToScratch(OutputLinearIterator & Iter) { typename TOutputImage::SizeValueType j = 0; while ( !Iter.IsAtEndOfLine() ) { m_Scratch[j] = static_cast< CoeffType >( Iter.Get() ); ++Iter; ++j; } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::GenerateInputRequestedRegion() { // This filter requires all of the input image to be in the buffer InputImagePointer inputPtr = const_cast< TInputImage * >( this->GetInput() ); if ( inputPtr ) { inputPtr->SetRequestedRegionToLargestPossibleRegion(); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::EnlargeOutputRequestedRegion(DataObject *output) { // This filter requires all of the input image to be in the buffer TOutputImage *imgData; imgData = dynamic_cast< TOutputImage * >( output ); if ( imgData ) { imgData->SetRequestedRegionToLargestPossibleRegion(); } } template< typename TInputImage, typename TOutputImage > void BSplineDecompositionImageFilter< TInputImage, TOutputImage > ::GenerateData() { // Allocate scratch memory InputImageConstPointer inputPtr = this->GetInput(); m_DataLength = inputPtr->GetBufferedRegion().GetSize(); typename TOutputImage::SizeValueType maxLength = 0; for ( unsigned int n = 0; n < ImageDimension; n++ ) { if ( m_DataLength[n] > maxLength ) { maxLength = m_DataLength[n]; } } m_Scratch.resize(maxLength); // Allocate memory for output image OutputImagePointer outputPtr = this->GetOutput(); outputPtr->SetBufferedRegion( outputPtr->GetRequestedRegion() ); outputPtr->Allocate(); // Calculate actual output this->DataToCoefficientsND(); // Clean up m_Scratch.clear(); } } // namespace itk #endif <|endoftext|>
<commit_before>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with #include <chrono> #include <thread> Auctioneer::Auctioneer(void) { numBidders = 0; numTargets = 0; roundNumber = 0; numRecvdBids = 0; bids = nullptr; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p != NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numRecvdBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, numTargets); if (roundNumber <= numTargets) { dp.dprintf(LVL_MID_VERB, "numReceivedBids=%i\n", numRecvdBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numRecvdBids == numBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (size_t i = 0; i < numBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numRecvdBids = 0; } else { // Keep sending the round number in case they didn't get the message. doNotify(MVAR_BID_START, roundNumber); if (roundNumber == 1) doNotify(MVAR_BID_TARGETS, targets); } } else { // Exit pAuctioneer doNotify("EXITED_NORMALLY", "pAuctioneer"); RequestQuit(); } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // DebugOutput config int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (ret) { // NumBidders config std::string tmp; if (!m_MissionReader.GetConfigurationParam("NumBidders", tmp)) ret = MissingRequiredParam("NumBidders"); else { numBidders = boost::lexical_cast<size_t>(tmp); this->bids = new Bid[numBidders]; } if (ret) { // Targets config if (!m_MissionReader.GetConfigurationParam("Targets", targets)) ret = MissingRequiredParam("Targets"); else { numTargets = getStringPathSize(targets); numTargets += 1; // for the bidder's node doNotify(MVAR_BID_TARGETS, targets); } if (ret) RegisterVariables(); } } return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (size_t i = 0; i < numBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str()); m_Comms.Register(key, 0); } } <commit_msg>Auctioneer num targets adjustment no longer necessary<commit_after>/** * @author Mike Bogochow * @version 2.4.0, Dec 8, 2015 * * @file Auctioneer.cpp * * Auctioneer class implementation */ #include "Auctioneer.h" #include "../lib_auction/AuctionDefs.h" #include "../lib_auction/DebugPrinter.h" #include "MBUtils.h" #include <boost/algorithm/string/predicate.hpp> // starts_with #include <chrono> #include <thread> Auctioneer::Auctioneer(void) { numBidders = 0; numTargets = 0; roundNumber = 0; numRecvdBids = 0; bids = nullptr; } Auctioneer::~Auctioneer(void) { if (bids != nullptr) delete bids; } bool Auctioneer::OnNewMail(MOOSMSG_LIST &NewMail) { bool ret = AuctionMOOSApp::OnNewMail(NewMail); MOOSMSG_LIST::reverse_iterator p; for(p = NewMail.rbegin(); p != NewMail.rend(); p++) { CMOOSMsg &msg = *p; std::string key = msg.GetKey(); if (boost::starts_with(key, MVAR_BID_HEADER)) { int bidder = getBidder(key); bids[bidder] = bidFromString(msg.GetString()); numRecvdBids += 1; dp.dprintf(LVL_MIN_VERB, "Got %s mail: %s\n", key.c_str(), msg.GetString().c_str()); } } return ret; } bool Auctioneer::Iterate(void) { bool ret = AuctionMOOSApp::Iterate(); dp.dprintf(LVL_MAX_VERB, "roundNum <= numNodes (%lu <= %lu)?\n", roundNumber, numTargets); if (roundNumber <= numTargets) { dp.dprintf(LVL_MID_VERB, "numReceivedBids=%i\n", numRecvdBids); if (roundNumber == 0) doNotify(MVAR_BID_START, ++roundNumber); else if (numRecvdBids == numBidders) { // All bids received for round WinningBid winner = { 0, MAX_VERTEX, MAX_WEIGHT }; // Calculate winner for (size_t i = 0; i < numBidders; i++) { if (bids[i].second < winner.bid) { winner.winner = i; winner.target = bids[i].first; winner.bid = bids[i].second; } } // Send winner doNotify(MVAR_BID_WINNER, winningBidToString(winner)); doNotify(MVAR_BID_START, ++roundNumber); numRecvdBids = 0; } else { // Keep sending the round number in case they didn't get the message. doNotify(MVAR_BID_START, roundNumber); if (roundNumber == 1) doNotify(MVAR_BID_TARGETS, targets); } } else { // Exit pAuctioneer doNotify("EXITED_NORMALLY", "pAuctioneer"); RequestQuit(); } return ret; } bool Auctioneer::OnStartUp(void) { bool ret; // DebugOutput config int debugLevel; if (!m_MissionReader.GetConfigurationParam("DebugOutput", debugLevel)) debugLevel = LVL_OFF; dp.setLevel((DebugLevel)debugLevel); ret = AuctionMOOSApp::OnStartUp(); if (ret) { // NumBidders config std::string tmp; if (!m_MissionReader.GetConfigurationParam("NumBidders", tmp)) ret = MissingRequiredParam("NumBidders"); else { numBidders = boost::lexical_cast<size_t>(tmp); this->bids = new Bid[numBidders]; } if (ret) { // Targets config if (!m_MissionReader.GetConfigurationParam("Targets", targets)) ret = MissingRequiredParam("Targets"); else { numTargets = getStringPathSize(targets); doNotify(MVAR_BID_TARGETS, targets); } if (ret) RegisterVariables(); } } return ret; } bool Auctioneer::OnConnectToServer(void) { bool ret = AuctionMOOSApp::OnConnectToServer(); RegisterVariables(); return ret; } void Auctioneer::RegisterVariables(void) { for (size_t i = 0; i < numBidders; i++) { std::string key = getBidVar(i); dp.dprintf(LVL_MIN_VERB, "Registering %s\n", key.c_str()); m_Comms.Register(key, 0); } } <|endoftext|>
<commit_before><commit_msg>In KMFolderTree::contentsMouseReleaseEvent make sure all code paths call the base class method KFolderTree::contentsMouseReleaseEvent.<commit_after><|endoftext|>
<commit_before>#include <benchmark/benchmark.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wdouble-promotion" #include <flat_hash_map.hpp> #pragma GCC diagnostic pop #include <random> #include <sparsehash/dense_hash_map> #include <unordered_map> #include <utils/macros.h> #include <vector> namespace { template <typename HashTableT, typename PostInitF> HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor) { using T = typename HashTableT::key_type; std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); std::mt19937_64 generator; HashTableT hashTable; iPostInitFunctor(hashTable); while (hashTable.size() != iNumberElements) { hashTable.emplace(randomDistribution(generator), hashTable.size()); } return hashTable; } template <typename HashTableT, typename PostInitF> void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor) { HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor)); std::vector<typename HashTableT::key_type> dataToLookup; dataToLookup.reserve(hashTable.size()); for (const auto& element : hashTable) { dataToLookup.emplace_back(element.first); } std::mt19937_64 randomGenerator(235432876); std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator); std::size_t i = 0; for ([[maybe_unused]] auto handler : iState) { benchmark::DoNotOptimize(hashTable.find(dataToLookup[i])); if (unlikely(dataToLookup.size() == ++i)) { i = 0; } } } template <typename HashTableT> void HashTableLookup_RunBenchmark(benchmark::State& iState) { return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {}); } void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); }); } void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState); } void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState); } void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark) { for (double i = 10; i <= 120'000; i *= 12) // NOLINT { iBenchmark->Arg(i); } } } // All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor. // Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full. // The reason for this is that there are more hash collisions when the table is more full. // So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again. // Another thing that we notice is that all the graphs are essentially flat on the left half of the screen. // This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge. // You will only get the numbers on the left if the element you’re looking for is already in the cache. BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT <commit_msg>Update benchmark_lookup.cpp<commit_after>#include <benchmark/benchmark.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" #pragma GCC diagnostic ignored "-Wdouble-promotion" #include <flat_hash_map.hpp> #include <sparsehash/dense_hash_map> #pragma GCC diagnostic pop #include <random> #include <unordered_map> #include <utils/macros.h> #include <vector> namespace { template <typename HashTableT, typename PostInitF> HashTableT CreateHashTable(std::size_t iNumberElements, PostInitF&& iPostInitFunctor) { using T = typename HashTableT::key_type; std::uniform_int_distribution<T> randomDistribution(std::numeric_limits<T>::min(), std::numeric_limits<T>::max()); std::mt19937_64 generator; HashTableT hashTable; iPostInitFunctor(hashTable); while (hashTable.size() != iNumberElements) { hashTable.emplace(randomDistribution(generator), hashTable.size()); } return hashTable; } template <typename HashTableT, typename PostInitF> void HashTableLookup_RunBenchmark(benchmark::State& iState, PostInitF&& iPostInitFunctor) { HashTableT hashTable = CreateHashTable<HashTableT>(iState.range(0), std::forward<PostInitF>(iPostInitFunctor)); std::vector<typename HashTableT::key_type> dataToLookup; dataToLookup.reserve(hashTable.size()); for (const auto& element : hashTable) { dataToLookup.emplace_back(element.first); } std::mt19937_64 randomGenerator(235432876); std::shuffle(std::begin(dataToLookup), std::end(dataToLookup), randomGenerator); std::size_t i = 0; for ([[maybe_unused]] auto handler : iState) { benchmark::DoNotOptimize(hashTable.find(dataToLookup[i])); if (unlikely(dataToLookup.size() == ++i)) { i = 0; } } } template <typename HashTableT> void HashTableLookup_RunBenchmark(benchmark::State& iState) { return HashTableLookup_RunBenchmark<HashTableT>(iState, [](HashTableT& iHashTable) {}); } void HashTableLookup_DenseHashMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<google::dense_hash_map<std::int64_t, std::int64_t>>(iState, [](auto& iHashTable) { iHashTable.set_empty_key(-1); }); } void HashTableLookup_FlatHashMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<ska::flat_hash_map<std::int64_t, std::int64_t>>(iState); } void HashTableLookup_UnorderedMapBenchmark(benchmark::State& iState) { HashTableLookup_RunBenchmark<std::unordered_map<std::int64_t, std::int64_t>>(iState); } void HashTableLookup_Arguments(benchmark::internal::Benchmark* iBenchmark) { for (double i = 10; i <= 120'000; i *= 12) // NOLINT { iBenchmark->Arg(i); } } } // All of the graphs are spiky. This is because all hashtables have different performance depending on the current load factor. // Meaning depending on how full they are. When a table is 25% full lookups will be faster than when it’s 50% full. // The reason for this is that there are more hash collisions when the table is more full. // So you can see the cost go up until at some point the table decides that it’s too full and that it should reallocate, which makes lookups fast again. // Another thing that we notice is that all the graphs are essentially flat on the left half of the screen. // This is because the table fits entirely into the cache. Only when we get to the point where the data doesn’t fit into the L3 cache do we see the different graphs really diverge. // You will only get the numbers on the left if the element you’re looking for is already in the cache. BENCHMARK(HashTableLookup_DenseHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT BENCHMARK(HashTableLookup_FlatHashMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT BENCHMARK(HashTableLookup_UnorderedMapBenchmark)->Apply(HashTableLookup_Arguments); // NOLINT <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: urlkeys.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: vg $ $Date: 2007-04-11 20:20:56 $ * * 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 __URLKEYS_HXX #define __URLKEYS_HXX // Defines for common keys in URL files // ANSI version #define A_URLSECTION_SHORTCUT "InternetShortcut" #define A_URLKEY_URL "URL" #define A_URLKEY_TITLE "Title" #define A_URLKEY_TARGET "Target" #define A_URLKEY_FRAME "Frame" #define A_URLKEY_OPENAS "OpenAs" #define A_URLKEY_SOICON "SOIcon" #define A_URLKEY_WIN_ICONFILE "IconFile" #define A_URLKEY_WIN_ICONINDEX "IconIndex" #define A_URLKEY_WORKDIR "WorkingDirectory" #define A_URLKEY_ARGUMENTS "Arguments" #define A_URLKEY_INTERN_ORIGURL "[URL]" // Unicode version #define U_URLSECTION_SHORTCUT L"InternetShortcut" #define U_URLKEY_URL L"URL" #define U_URLKEY_TITLE L"Title" #define U_URLKEY_TARGET L"Target" #define U_URLKEY_FRAME L"Frame" #define U_URLKEY_OPENAS L"OpenAs" #define U_URLKEY_SOICON L"SOIcon" #define U_URLKEY_WIN_ICONFILE L"IconFile" #define U_URLKEY_WIN_ICONINDEX L"IconIndex" #define U_URLKEY_WORKDIR L"WorkingDirectory" #define U_URLKEY_ARGUMENTS L"Arguments" #define U_URLKEY_INTERN_ORIGURL L"[URL]" # define URLSECTION_SHORTCUT U_URLSECTION_SHORTCUT # define URLKEY_URL U_URLKEY_URL # define URLKEY_TITLE U_URLKEY_TITLE # define URLKEY_TARGET U_URLKEY_TARGET # define URLKEY_FRAME U_URLKEY_FRAME # define URLKEY_OPENAS U_URLKEY_OPENAS # define URLKEY_SOICON U_URLKEY_SOICON # define URLKEY_WIN_ICONFILE U_URLKEY_WIN_ICONFILE # define URLKEY_WIN_ICONINDEX U_URLKEY_WIN_ICONINDEX # define URLKEY_WORKDIR U_URLKEY_WORKDIR # define URLKEY_ARGUMENTS U_URLKEY_ARGUMENTS # define URLKEY_INTERN_ORIGURL U_URLKEY_INTERN_ORIGURL #endif // __URLKEYS_HXX <commit_msg>INTEGRATION: CWS changefileheader (1.2.120); FILE MERGED 2008/03/28 15:41:14 rt 1.2.120.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: urlkeys.hxx,v $ * $Revision: 1.3 $ * * 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 __URLKEYS_HXX #define __URLKEYS_HXX // Defines for common keys in URL files // ANSI version #define A_URLSECTION_SHORTCUT "InternetShortcut" #define A_URLKEY_URL "URL" #define A_URLKEY_TITLE "Title" #define A_URLKEY_TARGET "Target" #define A_URLKEY_FRAME "Frame" #define A_URLKEY_OPENAS "OpenAs" #define A_URLKEY_SOICON "SOIcon" #define A_URLKEY_WIN_ICONFILE "IconFile" #define A_URLKEY_WIN_ICONINDEX "IconIndex" #define A_URLKEY_WORKDIR "WorkingDirectory" #define A_URLKEY_ARGUMENTS "Arguments" #define A_URLKEY_INTERN_ORIGURL "[URL]" // Unicode version #define U_URLSECTION_SHORTCUT L"InternetShortcut" #define U_URLKEY_URL L"URL" #define U_URLKEY_TITLE L"Title" #define U_URLKEY_TARGET L"Target" #define U_URLKEY_FRAME L"Frame" #define U_URLKEY_OPENAS L"OpenAs" #define U_URLKEY_SOICON L"SOIcon" #define U_URLKEY_WIN_ICONFILE L"IconFile" #define U_URLKEY_WIN_ICONINDEX L"IconIndex" #define U_URLKEY_WORKDIR L"WorkingDirectory" #define U_URLKEY_ARGUMENTS L"Arguments" #define U_URLKEY_INTERN_ORIGURL L"[URL]" # define URLSECTION_SHORTCUT U_URLSECTION_SHORTCUT # define URLKEY_URL U_URLKEY_URL # define URLKEY_TITLE U_URLKEY_TITLE # define URLKEY_TARGET U_URLKEY_TARGET # define URLKEY_FRAME U_URLKEY_FRAME # define URLKEY_OPENAS U_URLKEY_OPENAS # define URLKEY_SOICON U_URLKEY_SOICON # define URLKEY_WIN_ICONFILE U_URLKEY_WIN_ICONFILE # define URLKEY_WIN_ICONINDEX U_URLKEY_WIN_ICONINDEX # define URLKEY_WORKDIR U_URLKEY_WORKDIR # define URLKEY_ARGUMENTS U_URLKEY_ARGUMENTS # define URLKEY_INTERN_ORIGURL U_URLKEY_INTERN_ORIGURL #endif // __URLKEYS_HXX <|endoftext|>
<commit_before><commit_msg>Add files via upload<commit_after><|endoftext|>
<commit_before><commit_msg>Minor bug fix<commit_after><|endoftext|>
<commit_before>#include <windows.h> #include <math.h> #include <string> #include <vector> #include <sstream> #include "../math/math.h" #include <objidl.h> #include <gdiplus.h> #pragma comment( lib, "gdiplus.lib" ) using namespace std; using namespace Gdiplus; // Gdiplus GdiplusStartupInput g_gdiplusStartupInput; ULONG_PTR g_gdiplusToken; Graphics *g_graphics; Font *g_font; Pen *g_pen; // ü. Brush *g_blackBrush; // 귯 ü. Brush *g_redBrush; // 귯 ü. Brush *g_brush; // 귯 ü. Bitmap *g_bg; Image *g_image; Image *g_carImage; HWND g_hWnd = NULL; int g_incT = 0; int frameT = 0; int frame = 0; wstring frameStr; int g_pathIdx = 0; vector<Vector3> g_Path; struct sCar { bool isStop; int curPathIdx; Vector3 pos; float speed; // ʴ ȼ ̵ӵ. }; sCar g_car; // ݹ ν Լ Ÿ LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); void InitGdiPlus(HWND hWnd); void ReleaseGdiPlus(); void DrawString( Graphics *graph, int x, int y, const wstring &str); void MainLoop(int elapseT); void MoveCar(int elapseT); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { wchar_t className[32] = L"Petrol Station"; wchar_t windowName[32] = L"Petrol Station"; // Ŭ // ̷ ڴ WNDCLASS WndClass; WndClass.cbClsExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.cbWndExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH); // WndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); // Ŀ WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION ); //ܸ WndClass.hInstance = hInstance; //α׷νϽڵ WndClass.lpfnWndProc = (WNDPROC)WndProc; // ν Լ WndClass.lpszMenuName = NULL; //޴̸ NULL WndClass.lpszClassName = className; // ۼϰ ִ Ŭ ̸ WndClass.style = CS_HREDRAW | CS_VREDRAW; // ׸ (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW ) // ۼ Ŭ RegisterClass( &WndClass ); // // ڵ g_hWnd ޴´. HWND hWnd = CreateWindow( className, //Ǵ Ŭ̸ windowName, // ŸƲٿ µǴ ̸ WS_OVERLAPPEDWINDOW, // Ÿ WS_OVERLAPPEDWINDOW 0, // ġ X 0, // ġ Y 800, // ũ ( ۾ ũⰡ ƴ ) 600, // ũ ( ۾ ũⰡ ƴ ) GetDesktopWindow(), //θ ڵ ( α׷ ֻ NULL Ǵ GetDesktopWindow() ) NULL, //޴ ID ( ڽ Ʈ ü ΰ Ʈ ID hInstance, // 찡 α׷ νϽ ڵ NULL //߰ NULL ( Ű ) ); g_hWnd = hWnd; //츦 Ȯ ۾ ũ RECT rcClient = { 0, 0, 800, 600}; AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE ); //rcClient ũ⸦ ۾ ũ⸦ rcClient ԵǾ ´. // ũ ġ ٲپش. SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER | SWP_NOMOVE ); // 츦 ȭ鿡 . ShowWindow( hWnd, nCmdShow ); InitGdiPlus(hWnd); //޽ ü MSG msg; ZeroMemory( &msg, sizeof(MSG) ); int oldT = GetTickCount(); while (msg.message != WM_QUIT) { //PeekMessage ޽ ť ޽  α׷ ߱ ʰ ȴ. //̶ ޽ť ޽ false ϵǰ ޽ true ̵ȴ. if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage( &msg ); // Ű ڸ Ͽ WM_CHAR ޽ ߻Ų. DispatchMessage( &msg ); //޾ƿ ޽ ν Լ Ų. } const int curT = GetTickCount(); const int elapseT = curT - oldT; if (elapseT > 15) { oldT = curT; MainLoop(elapseT); } } ReleaseGdiPlus(); return 0; } // // ν Լ ( ޽ ť ޾ƿ ޽ óѴ ) // LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { PAINTSTRUCT ps; HDC hdc; switch (msg) { case WM_PAINT: // ȭ ŵ ȣȴ. { hdc = BeginPaint(hWnd, &ps); Graphics *graph = Graphics::FromImage(g_bg); RECT cr; GetClientRect(hWnd, &cr); Rect wndSize(cr.left, cr.top, cr.right, cr.bottom); graph->DrawImage(g_image, wndSize); for (int i=0; i < (int)g_Path.size(); ++i) { graph->FillEllipse(g_redBrush, (int)g_Path[ i].x, (int)g_Path[ i].z, 5, 5); } const int W = 113; const int H = 58; Vector3 p1(-W/2, 0, -H/2); Vector3 p2(W/2, 0, -H/2); Vector3 p3(-W/2, 0, H/2); Matrix44 m; if ((g_car.curPathIdx >= 0) && (g_car.curPathIdx+1 < (int)g_Path.size())) { Vector3 dir = g_Path[ g_car.curPathIdx+1] - g_car.pos; dir.Normalize(); Quaternion q(Vector3(1,0,0), Vector3(dir.x, 0, -dir.z)); m = q.GetMatrix(); } Vector3 pp1 = (p1 * m) + g_car.pos; Vector3 pp2 = (p2 * m) + g_car.pos; Vector3 pp3 = (p3 * m) + g_car.pos; Point pp[3]; pp[0] = Point((int)pp1.x, (int)pp1.z); pp[1] = Point((int)pp2.x, (int)pp2.z); pp[2] = Point((int)pp3.x, (int)pp3.z); //graph->DrawImage(g_carImage, // Rect((int)g_car.pos.x-(113/2), // (int)g_car.pos.y-(58/2), 113, 58) ); graph->DrawImage(g_carImage, pp, 3, 0,0,W,H, UnitPixel); DrawString(graph, 50, 0, frameStr); g_graphics->DrawImage(g_bg, wndSize); EndPaint(hWnd, &ps); } break; case WM_LBUTTONDOWN: { Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam)); g_Path.push_back(pos); } break; case WM_LBUTTONUP: break; case WM_MOUSEMOVE: break; case WM_KEYDOWN: break; case WM_DESTROY: //찡 ıȴٸ.. PostQuitMessage(0); //α׷ û ( ޽ ȴ ) break; } return DefWindowProc( hWnd, msg, wParam, lParam ); // ⺻ ޼ ó Ѵ. } // Gdiplus ʱȭ. void InitGdiPlus(HWND hWnd) { //Start Gdiplus Gdiplus::GdiplusStartup(&g_gdiplusToken, &g_gdiplusStartupInput, NULL); g_graphics = new Graphics(hWnd); g_pen = new Pen(Color::Red); g_brush = new SolidBrush(Color::White); g_blackBrush = new SolidBrush(0xFF000000); g_redBrush = new SolidBrush(0xFFFF0000); g_font = new Font(L"Arial", 16); g_bg = new Bitmap(800,600); g_image = Image::FromFile(L"oilbank.png"); g_carImage = Image::FromFile(L"car.png"); g_car.isStop = false; g_car.curPathIdx = -1; g_car.pos = Vector3(0,0,0); g_car.speed = 40; } // Gdiplus . void ReleaseGdiPlus() { delete g_image; delete g_font; delete g_pen; delete g_brush; delete g_blackBrush; delete g_redBrush; delete g_graphics; delete g_bg; delete g_carImage; // Shutdown Gdiplus Gdiplus::GdiplusShutdown(g_gdiplusToken); } void DrawString( Graphics *graph, int x, int y, const wstring &str) { StringFormat format; format.SetAlignment(StringAlignmentCenter); graph->DrawString( str.c_str(), -1, g_font, PointF((REAL)x, (REAL)y), &format, g_blackBrush); } void MainLoop(int elapseT) { MoveCar(elapseT); ++frame; frameT += elapseT; if (frameT > 1000) { std::wstringstream ss; ss << frame; frameStr = ss.str(); frame = 0; frameT = 0; } ::InvalidateRect(g_hWnd, NULL, FALSE); } void MoveCar(int elapseT) { //if (g_car.isStop) // return; if (2 > (int)g_Path.size()) return; if ((g_car.curPathIdx+1) >= (int)g_Path.size()) return; if (g_car.curPathIdx == -1) { g_car.pos = g_Path[ 0]; g_car.curPathIdx = 0; } Vector3 dir = g_Path[ g_car.curPathIdx+1] - g_car.pos; const float len = dir.Length(); if (len < 1.9f) { // η ̵Ѵ. if ((g_car.curPathIdx + 1) < (int)g_Path.size()) { ++g_car.curPathIdx; } else { g_car.isStop = true; } } dir.Normalize(); g_car.pos += dir * g_car.speed * (elapseT * 0.001f); } <commit_msg>petrol<commit_after>#include <windows.h> #include <math.h> #include <string> #include <vector> #include <sstream> #include "../math/math.h" #include <objidl.h> #include <gdiplus.h> #pragma comment( lib, "gdiplus.lib" ) using namespace std; using namespace Gdiplus; // Gdiplus GdiplusStartupInput g_gdiplusStartupInput; ULONG_PTR g_gdiplusToken; Graphics *g_graphics; Font *g_font; Pen *g_pen; // ü. Brush *g_blackBrush; // 귯 ü. Brush *g_redBrush; // 귯 ü. Brush *g_blueBrush; // 귯 ü. Brush *g_brush; // 귯 ü. Bitmap *g_bg; Image *g_image; Image *g_carImage; HWND g_hWnd = NULL; int g_incT = 0; int frameT = 0; int frame = 0; wstring frameStr; struct sPath { int type; // 0:move, 1:stop Vector3 pos; }; vector<sPath> g_Path; struct sCar { bool isStop; int waitTime; int curPathIdx; Vector3 pos; float speed; // ʴ ȼ ̵ӵ. }; sCar g_car; // ݹ ν Լ Ÿ LRESULT CALLBACK WndProc( HWND hWnd, UINT iMessage, WPARAM wParam, LPARAM lParam ); void InitGdiPlus(HWND hWnd); void ReleaseGdiPlus(); void DrawString( Graphics *graph, int x, int y, const wstring &str); void MainLoop(int elapseT); void MoveCar(int elapseT); int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { wchar_t className[32] = L"Petrol Station"; wchar_t windowName[32] = L"Petrol Station"; // Ŭ // ̷ ڴ WNDCLASS WndClass; WndClass.cbClsExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.cbWndExtra = 0; //쿡 ϴ ޸𸮼( ׳ 0 ̴ Ű澲 ) WndClass.hbrBackground = (HBRUSH)GetStockObject(LTGRAY_BRUSH); // WndClass.hCursor = LoadCursor( NULL, IDC_ARROW ); // Ŀ WndClass.hIcon = LoadIcon( NULL, IDI_APPLICATION ); //ܸ WndClass.hInstance = hInstance; //α׷νϽڵ WndClass.lpfnWndProc = (WNDPROC)WndProc; // ν Լ WndClass.lpszMenuName = NULL; //޴̸ NULL WndClass.lpszClassName = className; // ۼϰ ִ Ŭ ̸ WndClass.style = CS_HREDRAW | CS_VREDRAW; // ׸ (  ɶ ȭ鰻 CS_HREDRAW | CS_VREDRAW ) // ۼ Ŭ RegisterClass( &WndClass ); // // ڵ g_hWnd ޴´. HWND hWnd = CreateWindow( className, //Ǵ Ŭ̸ windowName, // ŸƲٿ µǴ ̸ WS_OVERLAPPEDWINDOW, // Ÿ WS_OVERLAPPEDWINDOW 0, // ġ X 0, // ġ Y 800, // ũ ( ۾ ũⰡ ƴ ) 600, // ũ ( ۾ ũⰡ ƴ ) GetDesktopWindow(), //θ ڵ ( α׷ ֻ NULL Ǵ GetDesktopWindow() ) NULL, //޴ ID ( ڽ Ʈ ü ΰ Ʈ ID hInstance, // 찡 α׷ νϽ ڵ NULL //߰ NULL ( Ű ) ); g_hWnd = hWnd; //츦 Ȯ ۾ ũ RECT rcClient = { 0, 0, 800, 600}; AdjustWindowRect( &rcClient, WS_OVERLAPPEDWINDOW, FALSE ); //rcClient ũ⸦ ۾ ũ⸦ rcClient ԵǾ ´. // ũ ġ ٲپش. SetWindowPos( hWnd, NULL, 0, 0, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER | SWP_NOMOVE ); // 츦 ȭ鿡 . ShowWindow( hWnd, nCmdShow ); InitGdiPlus(hWnd); //޽ ü MSG msg; ZeroMemory( &msg, sizeof(MSG) ); int oldT = GetTickCount(); while (msg.message != WM_QUIT) { //PeekMessage ޽ ť ޽  α׷ ߱ ʰ ȴ. //̶ ޽ť ޽ false ϵǰ ޽ true ̵ȴ. if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage( &msg ); // Ű ڸ Ͽ WM_CHAR ޽ ߻Ų. DispatchMessage( &msg ); //޾ƿ ޽ ν Լ Ų. } const int curT = GetTickCount(); const int elapseT = curT - oldT; if (elapseT > 15) { oldT = curT; MainLoop(elapseT); } } ReleaseGdiPlus(); return 0; } // // ν Լ ( ޽ ť ޾ƿ ޽ óѴ ) // LRESULT CALLBACK WndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam ) { PAINTSTRUCT ps; HDC hdc; switch (msg) { case WM_PAINT: // ȭ ŵ ȣȴ. { hdc = BeginPaint(hWnd, &ps); Graphics *graph = Graphics::FromImage(g_bg); RECT cr; GetClientRect(hWnd, &cr); Rect wndSize(cr.left, cr.top, cr.right, cr.bottom); graph->DrawImage(g_image, wndSize); for (int i=0; i < (int)g_Path.size(); ++i) { graph->FillEllipse((g_Path[ i].type==0)? g_redBrush : g_blueBrush, (int)g_Path[ i].pos.x, (int)g_Path[ i].pos.z, 5, 5); } const int W = 113; const int H = 58; Vector3 p1(-W/2, 0, -H/2); Vector3 p2(W/2, 0, -H/2); Vector3 p3(-W/2, 0, H/2); Matrix44 m; if ((g_car.curPathIdx >= 0) && (g_car.curPathIdx+1 < (int)g_Path.size())) { Vector3 dir = g_Path[ g_car.curPathIdx+1].pos - g_car.pos; dir.Normalize(); Quaternion q(Vector3(1,0,0), Vector3(dir.x, 0, -dir.z)); m = q.GetMatrix(); } Vector3 pp1 = (p1 * m) + g_car.pos; Vector3 pp2 = (p2 * m) + g_car.pos; Vector3 pp3 = (p3 * m) + g_car.pos; Point pp[3]; pp[0] = Point((int)pp1.x, (int)pp1.z); pp[1] = Point((int)pp2.x, (int)pp2.z); pp[2] = Point((int)pp3.x, (int)pp3.z); graph->DrawImage(g_carImage, pp, 3, 0,0,W,H, UnitPixel); DrawString(graph, 50, 0, frameStr); g_graphics->DrawImage(g_bg, wndSize); EndPaint(hWnd, &ps); } break; case WM_LBUTTONDOWN: { Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam)); sPath path; path.pos = pos; path.type = 0; g_Path.push_back(path); } break; case WM_RBUTTONDOWN: { Vector3 pos(LOWORD(lParam), 0, HIWORD(lParam)); sPath path; path.pos = pos; path.type = 1; g_Path.push_back(path); } break; case WM_LBUTTONUP: break; case WM_MOUSEMOVE: break; case WM_KEYDOWN: break; case WM_DESTROY: //찡 ıȴٸ.. PostQuitMessage(0); //α׷ û ( ޽ ȴ ) break; } return DefWindowProc( hWnd, msg, wParam, lParam ); // ⺻ ޼ ó Ѵ. } // Gdiplus ʱȭ. void InitGdiPlus(HWND hWnd) { //Start Gdiplus Gdiplus::GdiplusStartup(&g_gdiplusToken, &g_gdiplusStartupInput, NULL); g_graphics = new Graphics(hWnd); g_pen = new Pen(Color::Red); g_brush = new SolidBrush(Color::White); g_blackBrush = new SolidBrush(0xFF000000); g_redBrush = new SolidBrush(0xFFFF0000); g_blueBrush = new SolidBrush(0xFF0000FF); g_font = new Font(L"Arial", 16); g_bg = new Bitmap(800,600); g_image = Image::FromFile(L"oilbank.png"); g_carImage = Image::FromFile(L"car.png"); g_car.isStop = false; g_car.waitTime = 0; g_car.curPathIdx = -1; g_car.pos = Vector3(0,0,0); g_car.speed = 40; } // Gdiplus . void ReleaseGdiPlus() { delete g_image; delete g_font; delete g_pen; delete g_brush; delete g_blackBrush; delete g_redBrush; delete g_blueBrush; delete g_graphics; delete g_bg; delete g_carImage; // Shutdown Gdiplus Gdiplus::GdiplusShutdown(g_gdiplusToken); } void DrawString( Graphics *graph, int x, int y, const wstring &str) { StringFormat format; format.SetAlignment(StringAlignmentCenter); graph->DrawString( str.c_str(), -1, g_font, PointF((REAL)x, (REAL)y), &format, g_blackBrush); } void MainLoop(int elapseT) { MoveCar(elapseT); ++frame; frameT += elapseT; if (frameT > 1000) { std::wstringstream ss; ss << frame; frameStr = ss.str(); frame = 0; frameT = 0; } ::InvalidateRect(g_hWnd, NULL, FALSE); } void MoveCar(int elapseT) { //if (g_car.isStop) // return; if (2 > (int)g_Path.size()) return; if ((g_car.curPathIdx+1) >= (int)g_Path.size()) return; if (g_car.curPathIdx == -1) { g_car.pos = g_Path[ 0].pos; g_car.curPathIdx = 0; } Vector3 dir = g_Path[ g_car.curPathIdx+1].pos - g_car.pos; const float len = dir.Length(); if (len < 1.9f) { // η ̵Ѵ. if ((g_car.curPathIdx + 1) < (int)g_Path.size()) { if (g_Path[ g_car.curPathIdx+1].type == 1) { // ð Ѵ. g_car.waitTime += elapseT; if (g_car.waitTime > 5000) { ++g_car.curPathIdx; g_car.waitTime =0; } } else { ++g_car.curPathIdx; } } else { g_car.isStop = true; } } dir.Normalize(); g_car.pos += dir * g_car.speed * (elapseT * 0.001f); } <|endoftext|>
<commit_before>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(weighted_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(value_list_t const& values, std::vector<pregen_node_t> const& value_nodes) { if(values.empty() && value_nodes.empty()) return generated_node_t(); uint32_t total = total_weight(values) + total_weight(value_nodes); int roll = random_int(total); for(size_t i = 0; i < values.size(); ++i) { if(roll <= values[i].weight) { generated_node_t node; node.generated_values = std::move(roll_value(values[i])); return node; } roll -= values[i].weight; } //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { generated_node_t node(value_nodes[i].name); node.add_child(generate_node(value_nodes[i])); return node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } generated_node_t roll_values(pregen_node_t const& node) { return roll_values(node.values, node.value_nodes); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } generated_node_t rolled = roll_values(pre_node); node.children.insert(node.children.end(), rolled.children.begin(), rolled.children.end()); node.generated_values = std::move(rolled.generated_values); return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return generate_node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return generated_node_t(); } if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return generated_node_t(); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 1; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } void print_node(pregen_node_t const& node, size_t level) { using namespace std; auto indent = indenation_string(level); cout << indent << node.name << "\n"; for(auto const& child : node.children) print_node(child, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.values) cout << indent << value << "\n"; for(auto const& vnode : node.value_nodes) print_node(vnode, level + 1); for(auto const& user_val : node.user_data) cout << indent << user_val << "\n"; } void print_node(generated_node_t const& node, size_t level) { using namespace std; auto indent = indenation_string(level); cout << indent << node.name << "\n"; for(auto const& child : node.children) print_node(child, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) { cout << indent << value << "\n"; } } }<commit_msg>many things<commit_after>#include "plant_generator.h" #include <algorithm> #include <chrono> #include <functional> #include <iostream> #include <numeric> #include <random> #include <type_traits> #include <asdf_multiplat/main/asdf_defs.h> #include "from_json.h" namespace plantgen { //std::vector<std::string> roll_multi_value(multi_value_t const& m); std::mt19937 mt_rand( std::chrono::high_resolution_clock::now().time_since_epoch().count() ); int random_int(uint32_t min, uint32_t max) { std::uniform_int_distribution<int> dis(min,max); return dis(mt_rand); } int random_int(uint32_t max) { return random_int(0, max); } template <typename L> uint32_t total_weight(L const& list) { uint32_t total = 0; for(auto const& v : list) total += v.weight; return total; } std::vector<std::string> roll_multi_value(multi_value_t const& m) { if(m.num_to_pick >= m.values.size()) return m.values; std::vector<size_t> inds(m.values.size()); std::iota(inds.begin(), inds.end(), size_t(0)); //0, 1, 2, 3, ..., size-1 std::shuffle(inds.begin(), inds.end(), std::mt19937{std::random_device{}()}); std::vector<std::string> output; output.reserve(m.num_to_pick); for(size_t i = 0; i < m.num_to_pick; ++i) output.push_back(m.values[inds[i]]); return output; } std::vector<std::string> roll_range_value(range_value_t const& r) { std::vector<std::string> output; output.reserve(r.size()); uint32_t counter = 0; for(size_t i = 0; i < r.size() - 1; ++i) { int roll = 0; if(counter < 100) roll = random_int(100 - counter); counter += roll; output.push_back(std::to_string(roll) + "% " + r[i]); } //push remaining output.push_back(std::to_string(100 - counter) + "% " + r.back()); return output; } /// Runtime version (compile-time visitor pattern doesn't compile in msvc) std::vector<std::string> roll_value(weighted_value_t const& variant_val) { std::vector<std::string> output; if(auto* s = std::get_if<std::string>(&variant_val)) { output.push_back(*s); } else if(auto* r = std::get_if<range_value_t>(&variant_val)) { auto rolled_range = roll_range_value(*r); output.insert(output.end(), rolled_range.begin(), rolled_range.end()); } else if(auto* m = std::get_if<multi_value_t>(&variant_val)) { auto rolled_multi = roll_multi_value(*m); output.insert(output.end(), rolled_multi.begin(), rolled_multi.end()); } else { EXPLODE("unexpected variant sub-type"); } return output; } generated_node_t roll_values(value_list_t const& values, std::vector<pregen_node_t> const& value_nodes) { if(values.empty() && value_nodes.empty()) return generated_node_t(); uint32_t total = total_weight(values) + total_weight(value_nodes); int roll = random_int(total); for(size_t i = 0; i < values.size(); ++i) { if(roll <= values[i].weight) { generated_node_t node; node.generated_values = std::move(roll_value(values[i])); return node; } roll -= values[i].weight; } //if no value from the value list has been hit yet, continue onward into value_nodes for(size_t i = 0; i < value_nodes.size(); ++i) { if(roll <= value_nodes[i].weight) { generated_node_t node(value_nodes[i].name); //node.add_child(generate_node(value_nodes[i])); auto gend_node = generate_node(value_nodes[i]); node.add_value_node(std::move(gend_node)); return node; } roll -= value_nodes[i].weight; } EXPLODE("Random roll was too large, ran out of values and value_nodes"); return generated_node_t("ERROR"); } generated_node_t roll_values(pregen_node_t const& node) { return roll_values(node.values, node.value_nodes); } pregen_node_t node_from_file(stdfs::path const& filepath) { using namespace std; auto ext = filepath.extension(); if(ext == ".json") { return node_from_json(filepath); } else if(ext == ".yaml" || ext == ".yml") { cout << "TODO: yaml support"; return pregen_node_t(); } //TODO: exception? if(stdfs::is_directory(filepath)) cout << filepath.string() << " is a directory, not a file"; else cout << "Filetype " << ext << " not recognized"; return pregen_node_t(); } generated_node_t generate_node(pregen_node_t const& pre_node) { generated_node_t node; node.name = pre_node.name; for(auto const& child : pre_node.children) { node.add_child(generate_node(child)); } if(pre_node.values.size() > 0 || pre_node.value_nodes.size() > 0) { generated_node_t rolled = roll_values(pre_node); node.merge_with(rolled); } auto search = pre_node.user_data.find("PrintString"); if(search != pre_node.user_data.end()) { node.print_string = std::get<std::string>(search->second); } return node; } generated_node_t generate_node_from_file(stdfs::path const& filepath) { auto node = node_from_file(filepath); return generate_node(node); } constexpr size_t indent_amt = 4; // constexpr char indent_char = ' '; // constexpr char indent_tree_marker = ':'; constexpr char const* indent_cstr = ": "; std::string indenation_string(size_t indent_level) { if(indent_level == 0) return ""; // std::string indent_str(indent_level * indent_amt, indent_char); // indent_str[indent_str.size()-indent_amt] = indent_tree_marker; std::string indent_str; for(size_t i = 0; i < indent_level; ++i) indent_str.insert(indent_str.end(), indent_cstr, indent_cstr + 4); return indent_str; } void print_node(pregen_node_t const& node, size_t level) { using namespace std; auto indent = indenation_string(level); cout << indent << node.name << "\n"; for(auto const& child : node.children) print_node(child, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.values) cout << indent << value << "\n"; for(auto const& vnode : node.value_nodes) print_node(vnode, level + 1); for(auto const& user_vals : node.user_data) cout << indent << user_vals.first << ": " << user_vals.second << "\n"; } void print_node(generated_node_t const& node, size_t level) { using namespace std; auto indent = indenation_string(level); cout << indent << node.name << "\n"; for(auto const& child : node.children) print_node(child, level + 1); indent.append(indenation_string(1)); for(auto const& value : node.generated_values) cout << indent << value << "\n"; for(auto const& vn : node.value_nodes) print_node(vn, level + 1); } }<|endoftext|>
<commit_before>// // WMSLayer.cpp // G3MiOSSDK // // Created by José Miguel S N on 18/07/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "WMSLayer.hpp" #include "Tile.hpp" #include "Petition.hpp" #include "IStringBuilder.hpp" #include "LayerTilesRenderParameters.hpp" #include "MercatorUtils.hpp" #include "LayerCondition.hpp" WMSLayer::WMSLayer(const std::string& mapLayer, const URL& mapServerURL, const WMSServerVersion mapServerVersion, const std::string& queryLayer, const URL& queryServerURL, const WMSServerVersion queryServerVersion, const Sector& sector, const std::string& format, const std::string& srs, const std::string& style, const bool isTransparent, LayerCondition* condition, const TimeInterval& timeToCache, bool readExpired, const LayerTilesRenderParameters* parameters): Layer(condition, mapLayer, timeToCache, readExpired, (parameters == NULL) ? LayerTilesRenderParameters::createDefaultWGS84(Sector::fullSphere()) : parameters), _mapLayer(mapLayer), _mapServerURL(mapServerURL), _mapServerVersion(mapServerVersion), _queryLayer(queryLayer), _queryServerURL(queryServerURL), _queryServerVersion(queryServerVersion), _sector(sector), _format(format), _srs(srs), _style(style), _isTransparent(isTransparent), _extraParameter("") { } WMSLayer::WMSLayer(const std::string& mapLayer, const URL& mapServerURL, const WMSServerVersion mapServerVersion, const Sector& sector, const std::string& format, const std::string& srs, const std::string& style, const bool isTransparent, LayerCondition* condition, const TimeInterval& timeToCache, bool readExpired, const LayerTilesRenderParameters* parameters): Layer(condition, mapLayer, timeToCache, readExpired, (parameters == NULL) ? LayerTilesRenderParameters::createDefaultWGS84(Sector::fullSphere()) : parameters), _mapLayer(mapLayer), _mapServerURL(mapServerURL), _mapServerVersion(mapServerVersion), _queryLayer(mapLayer), _queryServerURL(mapServerURL), _queryServerVersion(mapServerVersion), _sector(sector), _format(format), _srs(srs), _style(style), _isTransparent(isTransparent), _extraParameter("") { } double WMSLayer::toBBOXLongitude(const Angle& longitude) const { return (_parameters->_mercator) ? MercatorUtils::longitudeToMeters(longitude) : longitude._degrees; } double WMSLayer::toBBOXLatitude(const Angle& latitude) const { return (_parameters->_mercator) ? MercatorUtils::latitudeToMeters(latitude) : latitude._degrees; } std::vector<Petition*> WMSLayer::createTileMapPetitions(const G3MRenderContext* rc, const Tile* tile) const { std::vector<Petition*> petitions; const Sector tileSector = tile->_sector; if (!_sector.touchesWith(tileSector)) { return petitions; } const Sector sector = tileSector.intersection(_sector); if (sector._deltaLatitude.isZero() || sector._deltaLongitude.isZero() ) { return petitions; } //TODO: MUST SCALE WIDTH,HEIGHT const Vector2I tileTextureResolution = _parameters->_tileTextureResolution; //Server name std::string req = _mapServerURL.getPath(); if (req[req.size() - 1] != '?') { req += '?'; } // //If the server refer to itself as localhost... // const int localhostPos = req.find("localhost"); // if (localhostPos != -1) { // req = req.substr(localhostPos+9); // // const int slashPos = req.find("/", 8); // std::string newHost = req.substr(0, slashPos); // // req = newHost + req; // } req += "REQUEST=GetMap&SERVICE=WMS"; switch (_mapServerVersion) { case WMS_1_3_0: { req += "&VERSION=1.3.0"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); req += isb->getString(); delete isb; req += "&CRS=EPSG:4326"; break; } case WMS_1_1_0: default: { // default is 1.1.1 req += "&VERSION=1.1.1"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); req += isb->getString(); delete isb; break; } } req += "&LAYERS=" + _mapLayer; req += "&FORMAT=" + _format; if (_srs != "") { req += "&SRS=" + _srs; } else { req += "&SRS=EPSG:4326"; } //Style if (_style != "") { req += "&STYLES=" + _style; } else { req += "&STYLES="; } //ASKING TRANSPARENCY if (_isTransparent) { req += "&TRANSPARENT=TRUE"; } else { req += "&TRANSPARENT=FALSE"; } if (_extraParameter.compare("") != 0) { req += "&"; req += _extraParameter; } // printf("Request: %s\n", req.c_str()); Petition *petition = new Petition(sector, URL(req, false), getTimeToCache(), getReadExpired(), _isTransparent); petitions.push_back(petition); return petitions; } URL WMSLayer::getFeatureInfoURL(const Geodetic2D& position, const Sector& tileSector) const { if (!_sector.touchesWith(tileSector)) { return URL::nullURL(); } const Sector sector = tileSector.intersection(_sector); //Server name std::string req = _queryServerURL.getPath(); if (req[req.size()-1] != '?') { req += '?'; } //If the server refer to itself as localhost... int pos = req.find("localhost"); if (pos != -1) { req = req.substr(pos+9); int pos2 = req.find("/", 8); std::string newHost = req.substr(0, pos2); req = newHost + req; } req += "REQUEST=GetFeatureInfo&SERVICE=WMS"; //SRS if (_srs != "") { req += "&SRS=" + _srs; } else { req += "&SRS=EPSG:4326"; } switch (_queryServerVersion) { case WMS_1_3_0: { req += "&VERSION=1.3.0"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(_parameters->_tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(_parameters->_tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); req += isb->getString(); delete isb; req += "&CRS=EPSG:4326"; break; } case WMS_1_1_0: default: { // default is 1.1.1 req += "&VERSION=1.1.1"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(_parameters->_tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(_parameters->_tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); req += isb->getString(); delete isb; break; } } req += "&LAYERS=" + _queryLayer; req += "&QUERY_LAYERS=" + _queryLayer; req += "&INFO_FORMAT=text/plain"; const IMathUtils* mu = IMathUtils::instance(); double u; double v; if (_parameters->_mercator) { u = sector.getUCoordinate(position._longitude); v = MercatorUtils::getMercatorV(position._latitude); } else { const Vector2D uv = sector.getUVCoordinates(position); u = uv._x; v = uv._y; } //X and Y //const Vector2D uv = sector.getUVCoordinates(position); const long long x = mu->round( (u * _parameters->_tileTextureResolution._x) ); const long long y = mu->round( (v * _parameters->_tileTextureResolution._y) ); IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&X="); isb->addLong(x); isb->addString("&Y="); isb->addLong(y); req += isb->getString(); delete isb; return URL(req, false); } const std::string WMSLayer::description() const { return "[WMSLayer]"; } bool WMSLayer::rawIsEquals(const Layer* that) const { WMSLayer* t = (WMSLayer*) that; if (!(_mapServerURL.isEquals(t->_mapServerURL))) { return false; } if (!(_queryServerURL.isEquals(t->_queryServerURL))) { return false; } if (_mapLayer != t->_mapLayer) { return false; } if (_mapServerVersion != t->_mapServerVersion) { return false; } if (_queryLayer != t->_queryLayer) { return false; } if (_queryServerVersion != t->_queryServerVersion) { return false; } if (!(_sector.isEquals(t->_sector))) { return false; } if (_format != t->_format) { return false; } if (_queryServerVersion != t->_queryServerVersion) { return false; } if (_srs != t->_srs) { return false; } if (_style != t->_style) { return false; } if (_isTransparent != t->_isTransparent) { return false; } if (_extraParameter != t->_extraParameter) { return false; } return true; } WMSLayer* WMSLayer::copy() const { return new WMSLayer(_mapLayer, _mapServerURL, _mapServerVersion, _queryLayer, _queryServerURL, _queryServerVersion, _sector, _format, _srs, _style, _isTransparent, (_condition == NULL) ? NULL : _condition->copy(), TimeInterval::fromMilliseconds(_timeToCacheMS), _readExpired, (_parameters == NULL) ? NULL : _parameters->copy()); } <commit_msg>bug fixed in WMSLayer<commit_after>// // WMSLayer.cpp // G3MiOSSDK // // Created by José Miguel S N on 18/07/12. // Copyright (c) 2012 __MyCompanyName__. All rights reserved. // #include "WMSLayer.hpp" #include "Tile.hpp" #include "Petition.hpp" #include "IStringBuilder.hpp" #include "LayerTilesRenderParameters.hpp" #include "MercatorUtils.hpp" #include "LayerCondition.hpp" WMSLayer::WMSLayer(const std::string& mapLayer, const URL& mapServerURL, const WMSServerVersion mapServerVersion, const std::string& queryLayer, const URL& queryServerURL, const WMSServerVersion queryServerVersion, const Sector& sector, const std::string& format, const std::string& srs, const std::string& style, const bool isTransparent, LayerCondition* condition, const TimeInterval& timeToCache, bool readExpired, const LayerTilesRenderParameters* parameters): Layer(condition, mapLayer, timeToCache, readExpired, (parameters == NULL) ? LayerTilesRenderParameters::createDefaultWGS84(Sector::fullSphere()) : parameters), _mapLayer(mapLayer), _mapServerURL(mapServerURL), _mapServerVersion(mapServerVersion), _queryLayer(queryLayer), _queryServerURL(queryServerURL), _queryServerVersion(queryServerVersion), _sector(sector), _format(format), _srs(srs), _style(style), _isTransparent(isTransparent), _extraParameter("") { } WMSLayer::WMSLayer(const std::string& mapLayer, const URL& mapServerURL, const WMSServerVersion mapServerVersion, const Sector& sector, const std::string& format, const std::string& srs, const std::string& style, const bool isTransparent, LayerCondition* condition, const TimeInterval& timeToCache, bool readExpired, const LayerTilesRenderParameters* parameters): Layer(condition, mapLayer, timeToCache, readExpired, (parameters == NULL) ? LayerTilesRenderParameters::createDefaultWGS84(Sector::fullSphere()) : parameters), _mapLayer(mapLayer), _mapServerURL(mapServerURL), _mapServerVersion(mapServerVersion), _queryLayer(mapLayer), _queryServerURL(mapServerURL), _queryServerVersion(mapServerVersion), _sector(sector), _format(format), _srs(srs), _style(style), _isTransparent(isTransparent), _extraParameter("") { } double WMSLayer::toBBOXLongitude(const Angle& longitude) const { return (_parameters->_mercator) ? MercatorUtils::longitudeToMeters(longitude) : longitude._degrees; } double WMSLayer::toBBOXLatitude(const Angle& latitude) const { return (_parameters->_mercator) ? MercatorUtils::latitudeToMeters(latitude) : latitude._degrees; } std::vector<Petition*> WMSLayer::createTileMapPetitions(const G3MRenderContext* rc, const Tile* tile) const { std::vector<Petition*> petitions; const std::string path = _mapServerURL.getPath(); if (path.empty()) { return petitions; } const Sector tileSector = tile->_sector; if (!_sector.touchesWith(tileSector)) { return petitions; } const Sector sector = tileSector.intersection(_sector); if (sector._deltaLatitude.isZero() || sector._deltaLongitude.isZero() ) { return petitions; } //TODO: MUST SCALE WIDTH,HEIGHT const Vector2I tileTextureResolution = _parameters->_tileTextureResolution; //Server name std::string req = path; if (req[req.size() - 1] != '?') { req += '?'; } // //If the server refer to itself as localhost... // const int localhostPos = req.find("localhost"); // if (localhostPos != -1) { // req = req.substr(localhostPos+9); // // const int slashPos = req.find("/", 8); // std::string newHost = req.substr(0, slashPos); // // req = newHost + req; // } req += "REQUEST=GetMap&SERVICE=WMS"; switch (_mapServerVersion) { case WMS_1_3_0: { req += "&VERSION=1.3.0"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); req += isb->getString(); delete isb; req += "&CRS=EPSG:4326"; break; } case WMS_1_1_0: default: { // default is 1.1.1 req += "&VERSION=1.1.1"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); req += isb->getString(); delete isb; break; } } req += "&LAYERS=" + _mapLayer; req += "&FORMAT=" + _format; if (_srs != "") { req += "&SRS=" + _srs; } else { req += "&SRS=EPSG:4326"; } //Style if (_style != "") { req += "&STYLES=" + _style; } else { req += "&STYLES="; } //ASKING TRANSPARENCY if (_isTransparent) { req += "&TRANSPARENT=TRUE"; } else { req += "&TRANSPARENT=FALSE"; } if (_extraParameter.compare("") != 0) { req += "&"; req += _extraParameter; } // printf("Request: %s\n", req.c_str()); Petition *petition = new Petition(sector, URL(req, false), getTimeToCache(), getReadExpired(), _isTransparent); petitions.push_back(petition); return petitions; } URL WMSLayer::getFeatureInfoURL(const Geodetic2D& position, const Sector& tileSector) const { if (!_sector.touchesWith(tileSector)) { return URL::nullURL(); } const Sector sector = tileSector.intersection(_sector); //Server name std::string req = _queryServerURL.getPath(); if (req[req.size()-1] != '?') { req += '?'; } //If the server refer to itself as localhost... int pos = req.find("localhost"); if (pos != -1) { req = req.substr(pos+9); int pos2 = req.find("/", 8); std::string newHost = req.substr(0, pos2); req = newHost + req; } req += "REQUEST=GetFeatureInfo&SERVICE=WMS"; //SRS if (_srs != "") { req += "&SRS=" + _srs; } else { req += "&SRS=EPSG:4326"; } switch (_queryServerVersion) { case WMS_1_3_0: { req += "&VERSION=1.3.0"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(_parameters->_tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(_parameters->_tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); req += isb->getString(); delete isb; req += "&CRS=EPSG:4326"; break; } case WMS_1_1_0: default: { // default is 1.1.1 req += "&VERSION=1.1.1"; IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&WIDTH="); isb->addInt(_parameters->_tileTextureResolution._x); isb->addString("&HEIGHT="); isb->addInt(_parameters->_tileTextureResolution._y); isb->addString("&BBOX="); isb->addDouble( toBBOXLongitude( sector._lower._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._lower._latitude ) ); isb->addString(","); isb->addDouble( toBBOXLongitude( sector._upper._longitude ) ); isb->addString(","); isb->addDouble( toBBOXLatitude( sector._upper._latitude ) ); req += isb->getString(); delete isb; break; } } req += "&LAYERS=" + _queryLayer; req += "&QUERY_LAYERS=" + _queryLayer; req += "&INFO_FORMAT=text/plain"; const IMathUtils* mu = IMathUtils::instance(); double u; double v; if (_parameters->_mercator) { u = sector.getUCoordinate(position._longitude); v = MercatorUtils::getMercatorV(position._latitude); } else { const Vector2D uv = sector.getUVCoordinates(position); u = uv._x; v = uv._y; } //X and Y //const Vector2D uv = sector.getUVCoordinates(position); const long long x = mu->round( (u * _parameters->_tileTextureResolution._x) ); const long long y = mu->round( (v * _parameters->_tileTextureResolution._y) ); IStringBuilder* isb = IStringBuilder::newStringBuilder(); isb->addString("&X="); isb->addLong(x); isb->addString("&Y="); isb->addLong(y); req += isb->getString(); delete isb; return URL(req, false); } const std::string WMSLayer::description() const { return "[WMSLayer]"; } bool WMSLayer::rawIsEquals(const Layer* that) const { WMSLayer* t = (WMSLayer*) that; if (!(_mapServerURL.isEquals(t->_mapServerURL))) { return false; } if (!(_queryServerURL.isEquals(t->_queryServerURL))) { return false; } if (_mapLayer != t->_mapLayer) { return false; } if (_mapServerVersion != t->_mapServerVersion) { return false; } if (_queryLayer != t->_queryLayer) { return false; } if (_queryServerVersion != t->_queryServerVersion) { return false; } if (!(_sector.isEquals(t->_sector))) { return false; } if (_format != t->_format) { return false; } if (_queryServerVersion != t->_queryServerVersion) { return false; } if (_srs != t->_srs) { return false; } if (_style != t->_style) { return false; } if (_isTransparent != t->_isTransparent) { return false; } if (_extraParameter != t->_extraParameter) { return false; } return true; } WMSLayer* WMSLayer::copy() const { return new WMSLayer(_mapLayer, _mapServerURL, _mapServerVersion, _queryLayer, _queryServerURL, _queryServerVersion, _sector, _format, _srs, _style, _isTransparent, (_condition == NULL) ? NULL : _condition->copy(), TimeInterval::fromMilliseconds(_timeToCacheMS), _readExpired, (_parameters == NULL) ? NULL : _parameters->copy()); } <|endoftext|>
<commit_before>// Copyright (c) 2017, CNRS // Authors: Florent Lamiraux // // This file is part of hpp-pinocchio. // hpp-pinocchio 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 // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #ifndef HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH # define HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH # include <hpp/pinocchio/liegroup-space.hh> # include <hpp/pinocchio/deprecated.hh> namespace hpp { namespace pinocchio { /// \addtogroup liegroup /// \{ template <typename vector_type> class LiegroupElementBase { public: /// Constructor /// \param value vector representation, /// \param liegroupSpace space the element belongs to. template <typename Derived> LiegroupElementBase (const Eigen::EigenBase<Derived>& value, const LiegroupSpacePtr_t& liegroupSpace) : value_ (value.derived()), space_ (liegroupSpace) { check(); } /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. template <typename Derived> explicit LiegroupElementBase (const Eigen::EigenBase<Derived>& value) : value_ (value.derived()), space_ (LiegroupSpace::create (value.derived().size ())) {} /// get reference to vector of Lie groups const LiegroupSpacePtr_t& space () const { return space_; } /// Const vector representation const vector_type& vector () const { return value_; } /// Size of the vector representation size_type size () const { return value_.size (); } /// Check that size of vector fits size of space /// \note only in debug mode void check () const { assert (value_.size () == space_->nq ()); } protected: vector_type value_; LiegroupSpacePtr_t space_; }; typedef LiegroupElementBase<vectorIn_t> LiegroupConstElementRef; template <typename vector_type> class LiegroupNonconstElementBase : public LiegroupElementBase<vector_type> { public: typedef LiegroupElementBase<vector_type> Base; /// Constructor /// \param value vector representation, /// \param liegroupSpace space the element belongs to. LiegroupNonconstElementBase (const vector_type& value, const LiegroupSpacePtr_t& space) : Base (value, space) {} /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. LiegroupNonconstElementBase (const LiegroupSpacePtr_t& space) : Base (vector_t (space->nq ()), space) {} /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. explicit LiegroupNonconstElementBase (const vector_type& value) : Base (value) {} /// Copy constructor template <typename vector_type2> LiegroupNonconstElementBase (const LiegroupElementBase<vector_type2>& other) : Base (other.vector(), other.space()) {} /// Const vector representation const vector_type& vector () const { return Base::vector(); } /// Modifiable vector representation vector_type& vector () { return this->value_; } /// Set element to neutral element void setNeutral () { this->value_ = this->space_->neutral ().vector (); } /// Inplace integration of a velocity vector LiegroupNonconstElementBase& operator+= (vectorIn_t v); }; /// Element of a Lie group /// /// See class LiegroupSpace. typedef LiegroupNonconstElementBase< vector_t> LiegroupElement; typedef LiegroupNonconstElementBase<vectorOut_t> LiegroupElementRef; /// Integration of a velocity vector from a configuration /// /// \param e element of the Lie group, /// \param v element of the tangent space of the Lie group. /// \return the element of the Lie group resulting from the integration /// /// By extension of the vector space case, we represent the integration /// of a constant velocity during unit time by an addition template <typename vector_type> LiegroupElement operator+ (const LiegroupElementBase<vector_type>& e, vectorIn_t v); /// Difference between two configurations /// /// \param e1, e2 elements of the Lie group, /// \return the velocity that integrated from e2 yiels e1 /// /// By extension of the vector space case, we represent the integration /// of a constant velocity during unit time by an addition template <typename vector_type1, typename vector_type2> vector_t operator- (const LiegroupElementBase<vector_type1>& e1, const LiegroupElementBase<vector_type2>& e2); /// \} /// Compute the log as a tangent vector of a Lie group element template <typename vector_type> vector_t log (const LiegroupElementBase<vector_type>& lge); template <typename vector_type> inline std::ostream& operator<< (std::ostream& os, const LiegroupElementBase<vector_type>& e) { os << "Lie group element in " << *(e.space ()) << " represented by vector (" << e. vector ().transpose () << ")"; return os; } } // namespace pinocchio } // namespace hpp #endif // HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH <commit_msg>Add missing empty constructor in LiegroupNonconstElementBase<commit_after>// Copyright (c) 2017, CNRS // Authors: Florent Lamiraux // // This file is part of hpp-pinocchio. // hpp-pinocchio 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 // 3 of the License, or (at your option) any later version. // // hpp-pinocchio 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 Lesser Public License for more details. You should have // received a copy of the GNU Lesser General Public License along with // hpp-pinocchio. If not, see <http://www.gnu.org/licenses/>. #ifndef HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH # define HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH # include <hpp/pinocchio/liegroup-space.hh> # include <hpp/pinocchio/deprecated.hh> namespace hpp { namespace pinocchio { /// \addtogroup liegroup /// \{ template <typename vector_type> class LiegroupElementBase { public: /// Constructor /// \param value vector representation, /// \param liegroupSpace space the element belongs to. template <typename Derived> LiegroupElementBase (const Eigen::EigenBase<Derived>& value, const LiegroupSpacePtr_t& liegroupSpace) : value_ (value.derived()), space_ (liegroupSpace) { check(); } /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. template <typename Derived> explicit LiegroupElementBase (const Eigen::EigenBase<Derived>& value) : value_ (value.derived()), space_ (LiegroupSpace::create (value.derived().size ())) {} /// get reference to vector of Lie groups const LiegroupSpacePtr_t& space () const { return space_; } /// Const vector representation const vector_type& vector () const { return value_; } /// Size of the vector representation size_type size () const { return value_.size (); } /// Check that size of vector fits size of space /// \note only in debug mode void check () const { assert (value_.size () == space_->nq ()); } protected: vector_type value_; LiegroupSpacePtr_t space_; }; typedef LiegroupElementBase<vectorIn_t> LiegroupConstElementRef; template <typename vector_type> class LiegroupNonconstElementBase : public LiegroupElementBase<vector_type> { public: typedef LiegroupElementBase<vector_type> Base; /// Constructor /// \param value vector representation, /// \param liegroupSpace space the element belongs to. LiegroupNonconstElementBase (const vector_type& value, const LiegroupSpacePtr_t& space) : Base (value, space) {} /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. LiegroupNonconstElementBase (const LiegroupSpacePtr_t& space) : Base (vector_t (space->nq ()), space) {} /// Constructor /// \param value vector representation, /// /// By default the space containing the value is a vector space. explicit LiegroupNonconstElementBase (const vector_type& value) : Base (value) {} /// Copy constructor template <typename vector_type2> LiegroupNonconstElementBase (const LiegroupElementBase<vector_type2>& other) : Base (other.vector(), other.space()) {} /// Constructor of trivial element LiegroupNonconstElementBase () : Base (vector_t(), LiegroupSpace::empty ()) {} /// Const vector representation const vector_type& vector () const { return Base::vector(); } /// Modifiable vector representation vector_type& vector () { return this->value_; } /// Set element to neutral element void setNeutral () { this->value_ = this->space_->neutral ().vector (); } /// Inplace integration of a velocity vector LiegroupNonconstElementBase& operator+= (vectorIn_t v); }; /// Element of a Lie group /// /// See class LiegroupSpace. typedef LiegroupNonconstElementBase< vector_t> LiegroupElement; typedef LiegroupNonconstElementBase<vectorOut_t> LiegroupElementRef; /// Integration of a velocity vector from a configuration /// /// \param e element of the Lie group, /// \param v element of the tangent space of the Lie group. /// \return the element of the Lie group resulting from the integration /// /// By extension of the vector space case, we represent the integration /// of a constant velocity during unit time by an addition template <typename vector_type> LiegroupElement operator+ (const LiegroupElementBase<vector_type>& e, vectorIn_t v); /// Difference between two configurations /// /// \param e1, e2 elements of the Lie group, /// \return the velocity that integrated from e2 yiels e1 /// /// By extension of the vector space case, we represent the integration /// of a constant velocity during unit time by an addition template <typename vector_type1, typename vector_type2> vector_t operator- (const LiegroupElementBase<vector_type1>& e1, const LiegroupElementBase<vector_type2>& e2); /// \} /// Compute the log as a tangent vector of a Lie group element template <typename vector_type> vector_t log (const LiegroupElementBase<vector_type>& lge); template <typename vector_type> inline std::ostream& operator<< (std::ostream& os, const LiegroupElementBase<vector_type>& e) { os << "Lie group element in " << *(e.space ()) << " represented by vector (" << e. vector ().transpose () << ")"; return os; } } // namespace pinocchio } // namespace hpp #endif // HPP_PINOCCHIO_LIEGROUP_ELEMENT_HH <|endoftext|>
<commit_before>#include "ioutils.h" #include "stringutils.h" #include <iostream> #include <math/infnan.h> #include <fstream> #include <limits> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> //if c is preceded by a \, returns the translated ascii character int TranslateEscape(int c) { switch(c) { case 'a': return '\a'; case 'b': return '\b'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; default: return c; } } std::string TranslateEscapes(const std::string& str) { std::string res; for(size_t i=0;i+1<str.length();i++) { if(str[i]=='\\') { res += TranslateEscape(str[i+1]); i++; } else res += str[i]; } res += str[str.length()-1]; return res; } void EatWhitespace(std::istream& in) { while(in && isspace(in.peek())) in.get(); } bool InputToken(std::istream& in,const char* characterSet,std::string& str) { str.erase(); int c; while(in && (c=in.peek())!=EOF) { if(strchr(characterSet,c) != NULL) str += c; c=in.get(); } return !in.bad(); } bool InputQuotedString(std::istream& in, char* out, int n) { int c; int state=0; //0 = not yet read begin ", 1 is reading chars until end " int i=0; while((c=in.peek())!=EOF) { switch (state) { case 0: if(c=='\"') state = 1; else if(!isspace(c)) return false; break; case 1: if(c=='\"') { in.get(); out[i]='\0'; return true; } else if(c=='\\') { c=in.get(); c=in.peek(); out[i] = c; } else { if(i>=n) return false; out[i] = c; i++; } break; } c=in.get(); } return false; } bool InputQuotedString(std::istream& in, std::string& out) { int c; int state=0; out.erase(); while((c=in.peek())!=EOF) { switch (state) { case 0: if(c=='\"') state = 1; else if(!isspace(c)) return false; break; case 1: if(c=='\"') { in.get(); return true; } else if(c=='\\') { c=in.get(); c=in.peek(); out+= c; } else out+= c; break; } c = in.get(); } return false; } void OutputQuotedString(std::ostream& out, const char* str) { if(StringContainsQuote(str)) { //output quotes using \" out<<'\"'; const char* c=str; while(*c) { if(*c == '\"') out<<"\\\""; else out<<*c; } out<<'\"'; } else out<<'\"'<<str<<'\"'; } void OutputQuotedString(std::ostream& out, const std::string& str) { OutputQuotedString(out,str.c_str()); } bool StringContainsQuote(const char* str) { return strchr(str,'\"')!=NULL; } bool StringContainsQuote(const std::string& str) { return str.rfind('\"')!=str.npos; } bool StringRequiresQuoting(const char* str) { if(*str == 0) return true; while(str) { if(!isgraph(*str)) return true; if(*str == '\"') return true; str++; } return false; } bool StringRequiresQuoting(const std::string& str) { return StringRequiresQuoting(str.c_str()); } bool SafeInputString(std::istream& in, char* str,int n) { EatWhitespace(in); if(!in) return false; if(in.peek() == EOF) return false; if(in.peek() == '\"') return InputQuotedString(in,str,n); else { //read until new whitespace int i; for(i=0;i<n;i++) { str[i] = in.get(); if(isspace(str[i]) || in.eof()) { str[i] = 0; return true; } if(!in) return false; } //buffer overflowed return false; } } bool SafeInputString(std::istream& in, std::string& str) { //first eat up white space str.erase(); while(in && isspace(in.peek())) in.get(); if(!in) return false; if(in.peek() == EOF) return false; if(in.peek() == '\"') return InputQuotedString(in,str); else { //read until new whitespace in >> str; /* while(in) { char c = in.get(); if(isspace(c) || c==EOF) return true; str += c; } */ if(in.eof()) return true; if(!in) return false; return true; } } void SafeOutputString(std::ostream& out, const char* str) { if(StringRequiresQuoting(str)) OutputQuotedString(out,str); else out<<str; } void SafeOutputString(std::ostream& out, const std::string& str) { if(StringRequiresQuoting(str)) OutputQuotedString(out,str); else out<<str; } bool SafeInputFloat(std::istream& in, float& f) { EatWhitespace(in); int c=in.peek(); bool neg=false; if(c=='-') { in.get(); c=in.peek(); neg=true; } if(isdigit(c) || c=='.') { in>>f; } else if(tolower(c) == 'n' || tolower(c) == 'i') { std::string str; in>>str; Lowercase(str); if(str == "inf" || str == "infinity") f = Math::fInf; else if(str=="nan") f = std::numeric_limits<float>::quiet_NaN(); else return false; } else return false; if(neg) f = -f; return (bool)in; } bool SafeInputFloat(std::istream& in, double& f) { EatWhitespace(in); int c=in.peek(); bool neg=false; if(c=='-') { in.get(); c=in.peek(); neg=true; } #if _WIN32 if(isdigit(c) || c=='.') { in>>f; } #else if(std::isdigit(c) || c=='.') { in>>f; } #endif else if(tolower(c) == 'n' || tolower(c) == 'i') { std::string str; in>>str; Lowercase(str); if(str == "inf" || str == "infinity") f = Math::dInf; else if(str=="nan") f = std::numeric_limits<double>::quiet_NaN(); else return false; } else return false; if(neg) f = -f; return (bool)in; } bool SafeOutputFloat(std::ostream& out, float f) { out<<f; return true; } bool SafeOutputFloat(std::ostream& out, double f) { out<<f; return true; } bool GetFileContents(const char *filename,std::string& contents) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); contents.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return true; } return false; } <commit_msg>Fixed stupid error in outputting quoted strings<commit_after>#include "ioutils.h" #include "stringutils.h" #include <iostream> #include <math/infnan.h> #include <fstream> #include <limits> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> //if c is preceded by a \, returns the translated ascii character int TranslateEscape(int c) { switch(c) { case 'a': return '\a'; case 'b': return '\b'; case 'n': return '\n'; case 'r': return '\r'; case 't': return '\t'; case 'v': return '\v'; default: return c; } } std::string TranslateEscapes(const std::string& str) { std::string res; for(size_t i=0;i+1<str.length();i++) { if(str[i]=='\\') { res += TranslateEscape(str[i+1]); i++; } else res += str[i]; } res += str[str.length()-1]; return res; } void EatWhitespace(std::istream& in) { while(in && isspace(in.peek())) in.get(); } bool InputToken(std::istream& in,const char* characterSet,std::string& str) { str.erase(); int c; while(in && (c=in.peek())!=EOF) { if(strchr(characterSet,c) != NULL) str += c; c=in.get(); } return !in.bad(); } bool InputQuotedString(std::istream& in, char* out, int n) { int c; int state=0; //0 = not yet read begin ", 1 is reading chars until end " int i=0; while((c=in.peek())!=EOF) { switch (state) { case 0: if(c=='\"') state = 1; else if(!isspace(c)) return false; break; case 1: if(c=='\"') { in.get(); out[i]='\0'; return true; } else if(c=='\\') { c=in.get(); c=in.peek(); out[i] = c; } else { if(i>=n) return false; out[i] = c; i++; } break; } c=in.get(); } return false; } bool InputQuotedString(std::istream& in, std::string& out) { int c; int state=0; out.erase(); while((c=in.peek())!=EOF) { switch (state) { case 0: if(c=='\"') state = 1; else if(!isspace(c)) return false; break; case 1: if(c=='\"') { in.get(); return true; } else if(c=='\\') { c=in.get(); c=in.peek(); out+= c; } else out+= c; break; } c = in.get(); } return false; } void OutputQuotedString(std::ostream& out, const char* str) { if(StringContainsQuote(str)) { //output quotes using \" out<<'\"'; const char* c=str; while(*c) { if(*c == '\"') out<<"\\\""; else out<<*c; c++; } out<<'\"'; } else out<<'\"'<<str<<'\"'; } void OutputQuotedString(std::ostream& out, const std::string& str) { OutputQuotedString(out,str.c_str()); } bool StringContainsQuote(const char* str) { return strchr(str,'\"')!=NULL; } bool StringContainsQuote(const std::string& str) { return str.rfind('\"')!=str.npos; } bool StringRequiresQuoting(const char* str) { if(*str == 0) return true; while(str) { if(!isgraph(*str)) return true; if(*str == '\"') return true; str++; } return false; } bool StringRequiresQuoting(const std::string& str) { return StringRequiresQuoting(str.c_str()); } bool SafeInputString(std::istream& in, char* str,int n) { EatWhitespace(in); if(!in) return false; if(in.peek() == EOF) return false; if(in.peek() == '\"') return InputQuotedString(in,str,n); else { //read until new whitespace int i; for(i=0;i<n;i++) { str[i] = in.get(); if(isspace(str[i]) || in.eof()) { str[i] = 0; return true; } if(!in) return false; } //buffer overflowed return false; } } bool SafeInputString(std::istream& in, std::string& str) { //first eat up white space str.erase(); while(in && isspace(in.peek())) in.get(); if(!in) return false; if(in.peek() == EOF) return false; if(in.peek() == '\"') return InputQuotedString(in,str); else { //read until new whitespace in >> str; /* while(in) { char c = in.get(); if(isspace(c) || c==EOF) return true; str += c; } */ if(in.eof()) return true; if(!in) return false; return true; } } void SafeOutputString(std::ostream& out, const char* str) { if(StringRequiresQuoting(str)) OutputQuotedString(out,str); else out<<str; } void SafeOutputString(std::ostream& out, const std::string& str) { if(StringRequiresQuoting(str)) OutputQuotedString(out,str); else out<<str; } bool SafeInputFloat(std::istream& in, float& f) { EatWhitespace(in); int c=in.peek(); bool neg=false; if(c=='-') { in.get(); c=in.peek(); neg=true; } if(isdigit(c) || c=='.') { in>>f; } else if(tolower(c) == 'n' || tolower(c) == 'i') { std::string str; in>>str; Lowercase(str); if(str == "inf" || str == "infinity") f = Math::fInf; else if(str=="nan") f = std::numeric_limits<float>::quiet_NaN(); else return false; } else return false; if(neg) f = -f; return (bool)in; } bool SafeInputFloat(std::istream& in, double& f) { EatWhitespace(in); int c=in.peek(); bool neg=false; if(c=='-') { in.get(); c=in.peek(); neg=true; } #if _WIN32 if(isdigit(c) || c=='.') { in>>f; } #else if(std::isdigit(c) || c=='.') { in>>f; } #endif else if(tolower(c) == 'n' || tolower(c) == 'i') { std::string str; in>>str; Lowercase(str); if(str == "inf" || str == "infinity") f = Math::dInf; else if(str=="nan") f = std::numeric_limits<double>::quiet_NaN(); else return false; } else return false; if(neg) f = -f; return (bool)in; } bool SafeOutputFloat(std::ostream& out, float f) { out<<f; return true; } bool SafeOutputFloat(std::ostream& out, double f) { out<<f; return true; } bool GetFileContents(const char *filename,std::string& contents) { std::ifstream in(filename, std::ios::in | std::ios::binary); if (in) { in.seekg(0, std::ios::end); contents.resize(in.tellg()); in.seekg(0, std::ios::beg); in.read(&contents[0], contents.size()); in.close(); return true; } return false; } <|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-2013 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { } //--------------------------------------------------------------------- void CgPlugin::initialise() { // check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <commit_msg>[GL3+] Disable the Cg plugin during initialization. No more need to manually disable it in plugins.cfg.<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-2013 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 "OgreCgPlugin.h" #include "OgreRoot.h" #include "OgreHighLevelGpuProgramManager.h" #include "OgreCgFxScriptLoader.h" namespace Ogre { const String sPluginName = "Cg Program Manager"; //--------------------------------------------------------------------- CgPlugin::CgPlugin() :mCgProgramFactory(0) { } //--------------------------------------------------------------------- const String& CgPlugin::getName() const { return sPluginName; } //--------------------------------------------------------------------- void CgPlugin::install() { } //--------------------------------------------------------------------- void CgPlugin::initialise() { // Cg is also not supported on OpenGL 3+ if(Root::getSingletonPtr()->getRenderSystem()->getName().find("OpenGL 3+") == String::npos) { LogManager::getSingleton().logMessage("Disabling Cg Plugin for GL3+"); return; } // Check for gles2 by the glsles factory (this plugin is not supported on embedded systems for now) if (HighLevelGpuProgramManager::getSingleton().isLanguageSupported("glsles") == false) { // Create new factory mCgProgramFactory = OGRE_NEW CgProgramFactory(); // Register HighLevelGpuProgramManager::getSingleton().addFactory(mCgProgramFactory); OGRE_NEW CgFxScriptLoader(); } } //--------------------------------------------------------------------- void CgPlugin::shutdown() { // nothing to do } //--------------------------------------------------------------------- void CgPlugin::uninstall() { if (mCgProgramFactory) { OGRE_DELETE CgFxScriptLoader::getSingletonPtr(); // Remove from manager safely if (HighLevelGpuProgramManager::getSingletonPtr()) HighLevelGpuProgramManager::getSingleton().removeFactory(mCgProgramFactory); OGRE_DELETE mCgProgramFactory; mCgProgramFactory = 0; } } } <|endoftext|>
<commit_before>#pragma once /** * \file sal/span.hpp * * Temporary partial std::span implementation until it is provided by * clang++, g++ and MSVC. */ #include <sal/config.hpp> #include <iterator> #include <type_traits> __sal_begin template <typename T> class span_t { public: using element_type = T; using value_type = std::remove_cv_t<T>; using index_type = std::ptrdiff_t; using difference_type = std::ptrdiff_t; using pointer = T *; using reference = T &; using const_pointer = const T *; using const_reference = const T &; using iterator = pointer; using const_iterator = const_pointer; constexpr span_t () noexcept = default; constexpr span_t &operator= (const span_t &that) noexcept = default; constexpr span_t (pointer ptr, index_type count) noexcept : ptr_(ptr) , count_(count) { } constexpr span_t (pointer first, pointer last) noexcept : span_t(first, last - first) { } template <size_t N> constexpr span_t (element_type (&arr)[N]) noexcept : span_t(std::addressof(arr[0]), N) { } template <typename Container> constexpr span_t (Container &container) : span_t(std::data(container), std::size(container)) { } template <typename Container> constexpr span_t (const Container &container) : span_t(std::data(container), std::size(container)) { } constexpr bool empty () const noexcept { return size() == 0; } constexpr pointer data () const noexcept { return ptr_; } constexpr reference operator[] (index_type index) const { return ptr_[index]; } constexpr index_type size () const noexcept { return count_; } constexpr index_type size_bytes () const noexcept { return size() * sizeof(element_type); } constexpr iterator begin () const noexcept { return ptr_; } constexpr const_iterator cbegin () const noexcept { return ptr_; } constexpr iterator end () const noexcept { return ptr_ + count_; } constexpr const_iterator cend () const noexcept { return ptr_ + count_; } private: pointer ptr_{}; size_t count_{}; }; template <typename T> inline span_t<const std::byte> as_bytes (span_t<T> span) noexcept { return {reinterpret_cast<const std::byte *>(span.data()), span.size_bytes()}; } template <typename T, std::enable_if_t<std::is_const_v<T> == false, int> = 0> inline span_t<std::byte> as_writable_bytes (span_t<T> span) noexcept { return {reinterpret_cast<std::byte *>(span.data()), span.size_bytes()}; } __sal_end <commit_msg>Add doxygen docs for sal::span_t<commit_after>#pragma once /** * \file sal/span.hpp * * Temporary partial std::span implementation until it is provided by * clang++, g++ and MSVC. */ #include <sal/config.hpp> #include <iterator> #include <type_traits> __sal_begin /** * \see https://en.cppreference.com/w/cpp/container/span */ template <typename T> class span_t { public: /** * Span element type */ using element_type = T; /** * Span value type */ using value_type = std::remove_cv_t<T>; /** * Span index type */ using index_type = std::ptrdiff_t; /** * Difference type between two span's pointer's */ using difference_type = std::ptrdiff_t; /** * Span element pointer type */ using pointer = T *; /** * Span element reference type */ using reference = T &; /** * Span element const pointer type */ using const_pointer = const T *; /** * Span element const reference type */ using const_reference = const T &; /** * Span iterator type */ using iterator = pointer; /** * Span const iterator type */ using const_iterator = const_pointer; constexpr span_t () noexcept = default; /** * Assign \a that to \e this. */ constexpr span_t &operator= (const span_t &that) noexcept = default; /** * Construct span over range [\a ptr, \a ptr + \a count) */ constexpr span_t (pointer ptr, index_type count) noexcept : ptr_(ptr) , count_(count) { } /** * Construct span over range [\a first, \a last) */ constexpr span_t (pointer first, pointer last) noexcept : span_t(first, last - first) { } /** * Construct span over \a arr */ template <size_t N> constexpr span_t (element_type (&arr)[N]) noexcept : span_t(std::addressof(arr[0]), N) { } /** * Construct span over \a container */ template <typename Container> constexpr span_t (Container &container) : span_t(std::data(container), std::size(container)) { } /** * Construct const span over \a container */ template <typename Container> constexpr span_t (const Container &container) : span_t(std::data(container), std::size(container)) { } /** * Return true if size() == 0 */ constexpr bool empty () const noexcept { return size() == 0; } /** * Return pointer to beginning of span */ constexpr pointer data () const noexcept { return ptr_; } /** * Return span element on \a index */ constexpr reference operator[] (index_type index) const { return ptr_[index]; } /** * Return number of elements in span */ constexpr index_type size () const noexcept { return count_; } /** * Return size of span in bytes */ constexpr index_type size_bytes () const noexcept { return size() * sizeof(element_type); } /** * Return iterator to beginning of span */ constexpr iterator begin () const noexcept { return ptr_; } /** * Return const iterator to beginning of span */ constexpr const_iterator cbegin () const noexcept { return ptr_; } /** * Return iterator to past end of span */ constexpr iterator end () const noexcept { return ptr_ + count_; } /** * Return const iterator to past end of span */ constexpr const_iterator cend () const noexcept { return ptr_ + count_; } private: pointer ptr_{}; size_t count_{}; }; /** * Return new const span with std::byte value type over existing \a span */ template <typename T> inline span_t<const std::byte> as_bytes (span_t<T> span) noexcept { return {reinterpret_cast<const std::byte *>(span.data()), span.size_bytes()}; } /** * Return new span with std::byte value type over existing \a span */ template <typename T, std::enable_if_t<std::is_const_v<T> == false, int> = 0> inline span_t<std::byte> as_writable_bytes (span_t<T> span) noexcept { return {reinterpret_cast<std::byte *>(span.data()), span.size_bytes()}; } __sal_end <|endoftext|>
<commit_before>/* * Copyright (c) 2013, Red Hat. * Copyright (c) 2007-2009, Aconex. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) 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 General Public License * for more details. */ #include "openviewdialog.h" #include <QtGui/QCompleter> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include "main.h" #include "hostdialog.h" OpenViewDialog::OpenViewDialog(QWidget *parent) : QDialog(parent) { setupUi(this); my.dirModel = new QDirModel; my.dirModel->setIconProvider(fileIconProvider); dirListView->setModel(my.dirModel); my.completer = new QCompleter; my.completer->setModel(my.dirModel); fileNameLineEdit->setCompleter(my.completer); connect(dirListView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(dirListView_selectionChanged())); QDir dir; QChar sep(__pmPathSeparator()); QString sys = my.systemDir = pmGetConfig("PCP_VAR_DIR"); my.systemDir.append(sep); my.systemDir.append("config"); my.systemDir.append(sep); my.systemDir.append("kmchart"); if (dir.exists(my.systemDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.systemDir); my.systemDir = sys; my.systemDir.append(sep); my.systemDir.append("config"); my.systemDir.append(sep); my.systemDir.append("pmchart"); if (dir.exists(my.systemDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.systemDir); QString home = my.userDir = QDir::toNativeSeparators(QDir::homePath()); my.userDir.append(sep); my.userDir.append(".pcp"); my.userDir.append(sep); my.userDir.append("kmchart"); if (dir.exists(my.userDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.userDir); my.userDir = home; my.userDir.append(sep); my.userDir.append(".pcp"); my.userDir.append(sep); my.userDir.append("pmchart"); if (dir.exists(my.userDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.userDir); pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), home); } OpenViewDialog::~OpenViewDialog() { delete my.completer; delete my.dirModel; } void OpenViewDialog::reset() { if ((my.archiveSource = pmchart->isArchiveTab())) { sourceLabel->setText(tr("Archive:")); sourcePushButton->setIcon(QIcon(":/images/archive.png")); } else { sourceLabel->setText(tr("Host:")); sourcePushButton->setIcon(QIcon(":/images/computer.png")); } setupComboBoxes(my.archiveSource); setPath(my.systemDir); } void OpenViewDialog::setPathUi(const QString &path) { if (path.isEmpty()) return; int index = pathComboBox->findText(path); if (index == -1) { pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), path); index = pathComboBox->count() - 1; } pathComboBox->setCurrentIndex(index); dirListView->selectionModel()->clear(); userToolButton->setChecked(path == my.userDir); systemToolButton->setChecked(path == my.systemDir); fileNameLineEdit->setModified(false); fileNameLineEdit->clear(); } void OpenViewDialog::setPath(const QModelIndex &index) { console->post("OpenViewDialog::setPath QModelIndex path=%s", (const char *)my.dirModel->filePath(index).toAscii()); my.dirIndex = index; my.dirModel->refresh(index); dirListView->setRootIndex(index); setPathUi(my.dirModel->filePath(index)); } void OpenViewDialog::setPath(const QString &path) { console->post("OpenViewDialog::setPath QString path=%s", (const char *)path.toAscii()); my.dirIndex = my.dirModel->index(path); my.dirModel->refresh(my.dirIndex); dirListView->setRootIndex(my.dirIndex); setPathUi(path); } void OpenViewDialog::pathComboBox_currentIndexChanged(QString path) { console->post("OpenViewDialog::pathComboBox_currentIndexChanged"); setPath(path); } void OpenViewDialog::parentToolButton_clicked() { console->post("OpenViewDialog::parentToolButton_clicked"); setPath(my.dirModel->parent(my.dirIndex)); } void OpenViewDialog::userToolButton_clicked(bool enabled) { if (enabled) { QDir dir; if (!dir.exists(my.userDir)) dir.mkpath(my.userDir); setPath(my.userDir); } } void OpenViewDialog::systemToolButton_clicked(bool enabled) { if (enabled) setPath(my.systemDir); } void OpenViewDialog::dirListView_selectionChanged() { QItemSelectionModel *selections = dirListView->selectionModel(); QModelIndexList selectedIndexes = selections->selectedIndexes(); console->post("OpenViewDialog::dirListView_clicked"); my.completer->setCompletionPrefix(my.dirModel->filePath(my.dirIndex)); if (selectedIndexes.count() != 1) fileNameLineEdit->setText(""); else fileNameLineEdit->setText(my.dirModel->fileName(selectedIndexes.at(0))); } void OpenViewDialog::dirListView_activated(const QModelIndex &index) { QFileInfo fi = my.dirModel->fileInfo(index); console->post("OpenViewDialog::dirListView_activated"); if (fi.isDir()) setPath(index); else if (fi.isFile()) { QStringList files; files << fi.absoluteFilePath(); if (openViewFiles(files) == true) done(0); } } int OpenViewDialog::setupArchiveComboBoxes() { QIcon archiveIcon = fileIconProvider->icon(QedFileIconProvider::Archive); int index = 0; for (unsigned int i = 0; i < archiveGroup->numContexts(); i++) { QmcSource source = archiveGroup->context(i)->source(); sourceComboBox->insertItem(i, archiveIcon, source.source()); if (i == archiveGroup->contextIndex()) index = i; } return index; } int OpenViewDialog::setupLiveComboBoxes() { QIcon containerIcon = fileIconProvider->icon(QedFileIconProvider::Container); QIcon hostIcon = fileIconProvider->icon(QFileIconProvider::Computer); int index = 0; for (unsigned int i = 0; i < liveGroup->numContexts(); i++) { QmcSource source = liveGroup->context(i)->source(); QIcon icon = source.isContainer() ? containerIcon : hostIcon; sourceComboBox->insertItem(i, icon, source.hostLabel()); if (i == liveGroup->contextIndex()) index = i; } return index; } void OpenViewDialog::setupComboBoxes(bool arch) { // We block signals on the target combo boxes so that we don't // send spurious signals out about their lists being changed. // If we did that, we would keep changing the current context. sourceComboBox->blockSignals(true); sourceComboBox->clear(); int index = arch ? setupArchiveComboBoxes() : setupLiveComboBoxes(); sourceComboBox->setCurrentIndex(index); sourceComboBox->blockSignals(false); } void OpenViewDialog::archiveAdd() { QFileDialog *af = new QFileDialog(this); QStringList al; int sts; af->setFileMode(QFileDialog::ExistingFiles); af->setAcceptMode(QFileDialog::AcceptOpen); af->setWindowTitle(tr("Add Archive")); af->setIconProvider(fileIconProvider); af->setDirectory(QDir::toNativeSeparators(QDir::homePath())); if (af->exec() == QDialog::Accepted) al = af->selectedFiles(); for (QStringList::Iterator it = al.begin(); it != al.end(); ++it) { QString archive = *it; if ((sts = archiveGroup->use(PM_CONTEXT_ARCHIVE, archive)) < 0) { archive.prepend(tr("Cannot open PCP archive: ")); archive.append(tr("\n")); archive.append(tr(pmErrStr(sts))); QMessageBox::warning(this, pmProgname, archive, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); } else { setupComboBoxes(true); archiveGroup->updateBounds(); QmcSource source = archiveGroup->context()->source(); pmtime->addArchive(source.start(), source.end(), source.timezone(), source.host(), false); } } delete af; } void OpenViewDialog::hostAdd() { HostDialog *host = new HostDialog(this); if (host->exec() == QDialog::Accepted) { QString hostspec = host->getHostSpecification(); int sts, flags = host->getContextFlags(); if (hostspec == QString::null || hostspec.length() == 0) { hostspec.append(tr("Hostname not specified\n")); QMessageBox::warning(this, pmProgname, hostspec, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, Qt::NoButton, Qt::NoButton); } else if ((sts = liveGroup->use(PM_CONTEXT_HOST, hostspec, flags)) < 0) { hostspec.prepend(tr("Cannot connect to host: ")); hostspec.append(tr("\n")); hostspec.append(tr(pmErrStr(sts))); QMessageBox::warning(this, pmProgname, hostspec, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, Qt::NoButton, Qt::NoButton); } else { console->post(PmChart::DebugUi, "OpenViewDialog::newHost: %s (flags=0x%x)", (const char *)hostspec.toAscii(), flags); setupComboBoxes(false); } } delete host; } void OpenViewDialog::sourcePushButton_clicked() { if (my.archiveSource) archiveAdd(); else hostAdd(); } void OpenViewDialog::sourceComboBox_currentIndexChanged(int index) { console->post("OpenViewDialog::sourceComboBox_currentIndexChanged %d", index); if (my.archiveSource == false) liveGroup->use((unsigned int)index); else archiveGroup->use((unsigned int)index); } bool OpenViewDialog::useLiveContext(int index) { QmcSource source = liveGroup->context(index)->source(); char *sourceName = source.sourceAscii(); bool result = true; int sts; if ((sts = liveGroup->use(PM_CONTEXT_HOST, source.source())) < 0) { QString msg; msg.sprintf("Failed to connect to pmcd on \"%s\".\n%s.\n\n", sourceName, pmErrStr(sts)); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); result = false; } free(sourceName); return result; } bool OpenViewDialog::useArchiveContext(int index) { QmcSource source = archiveGroup->context(index)->source(); char *sourceName = source.sourceAscii(); bool result = true; int sts; if ((sts = archiveGroup->use(PM_CONTEXT_ARCHIVE, source.source())) < 0) { QString msg; msg.sprintf("Failed to open archive \"%s\".\n%s.\n\n", sourceName, pmErrStr(sts)); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); result = false; } free(sourceName); return result; } bool OpenViewDialog::useComboBoxContext(bool arch) { if (arch == false) return useLiveContext(sourceComboBox->currentIndex()); else return useArchiveContext(sourceComboBox->currentIndex()); } bool OpenViewDialog::openViewFiles(const QStringList &fl) { QString msg; bool result = true; if (pmchart->isArchiveTab() != my.archiveSource) { if (pmchart->isArchiveTab()) msg = tr("Cannot open Host View(s) in an Archive Tab\n"); else msg = tr("Cannot open Archive View(s) in a Host Tab\n"); QMessageBox::warning(this, pmProgname, msg, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); return false; } if (useComboBoxContext(my.archiveSource) == false) return false; QStringList files = fl; for (QStringList::Iterator it = files.begin(); it != files.end(); ++it) if (openView((const char *)(*it).toAscii()) == false) result = false; pmchart->enableUi(); return result; } void OpenViewDialog::openPushButton_clicked() { QStringList files; QString msg; if (fileNameLineEdit->isModified()) { QString filename = fileNameLineEdit->text().trimmed(); if (filename.isEmpty()) msg = tr("No View file(s) specified"); else { QFileInfo f(filename); if (f.isDir()) { setPath(filename); } else if (f.exists()) { files << filename; if (openViewFiles(files) == true) done(0); } else { msg = tr("No such View file exists:\n"); msg.append(filename); } } } else { QItemSelectionModel *selections = dirListView->selectionModel(); QModelIndexList selectedIndexes = selections->selectedIndexes(); if (selectedIndexes.count() == 0) msg = tr("No View file(s) selected"); else { for (int i = 0; i < selectedIndexes.count(); i++) { QString filename = my.dirModel->filePath(selectedIndexes.at(i)); QFileInfo f(filename); if (f.isDir()) continue; files << filename; } if (files.size() > 0) if (openViewFiles(files) == true) done(0); } } if (msg.isEmpty() == false) { QMessageBox::warning(this, pmProgname, msg, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); } } <commit_msg>pmchart: fix SIGSEGV from opening a view when no archive available<commit_after>/* * Copyright (c) 2013, Red Hat. * Copyright (c) 2007-2009, Aconex. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) 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 General Public License * for more details. */ #include "openviewdialog.h" #include <QtGui/QCompleter> #include <QtGui/QFileDialog> #include <QtGui/QMessageBox> #include "main.h" #include "hostdialog.h" OpenViewDialog::OpenViewDialog(QWidget *parent) : QDialog(parent) { setupUi(this); my.dirModel = new QDirModel; my.dirModel->setIconProvider(fileIconProvider); dirListView->setModel(my.dirModel); my.completer = new QCompleter; my.completer->setModel(my.dirModel); fileNameLineEdit->setCompleter(my.completer); connect(dirListView->selectionModel(), SIGNAL(selectionChanged(const QItemSelection&, const QItemSelection&)), this, SLOT(dirListView_selectionChanged())); QDir dir; QChar sep(__pmPathSeparator()); QString sys = my.systemDir = pmGetConfig("PCP_VAR_DIR"); my.systemDir.append(sep); my.systemDir.append("config"); my.systemDir.append(sep); my.systemDir.append("kmchart"); if (dir.exists(my.systemDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.systemDir); my.systemDir = sys; my.systemDir.append(sep); my.systemDir.append("config"); my.systemDir.append(sep); my.systemDir.append("pmchart"); if (dir.exists(my.systemDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.systemDir); QString home = my.userDir = QDir::toNativeSeparators(QDir::homePath()); my.userDir.append(sep); my.userDir.append(".pcp"); my.userDir.append(sep); my.userDir.append("kmchart"); if (dir.exists(my.userDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.userDir); my.userDir = home; my.userDir.append(sep); my.userDir.append(".pcp"); my.userDir.append(sep); my.userDir.append("pmchart"); if (dir.exists(my.userDir)) pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), my.userDir); pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), home); } OpenViewDialog::~OpenViewDialog() { delete my.completer; delete my.dirModel; } void OpenViewDialog::reset() { if ((my.archiveSource = pmchart->isArchiveTab())) { sourceLabel->setText(tr("Archive:")); sourcePushButton->setIcon(QIcon(":/images/archive.png")); } else { sourceLabel->setText(tr("Host:")); sourcePushButton->setIcon(QIcon(":/images/computer.png")); } setupComboBoxes(my.archiveSource); setPath(my.systemDir); } void OpenViewDialog::setPathUi(const QString &path) { if (path.isEmpty()) return; int index = pathComboBox->findText(path); if (index == -1) { pathComboBox->addItem(fileIconProvider->icon(QFileIconProvider::Folder), path); index = pathComboBox->count() - 1; } pathComboBox->setCurrentIndex(index); dirListView->selectionModel()->clear(); userToolButton->setChecked(path == my.userDir); systemToolButton->setChecked(path == my.systemDir); fileNameLineEdit->setModified(false); fileNameLineEdit->clear(); } void OpenViewDialog::setPath(const QModelIndex &index) { console->post("OpenViewDialog::setPath QModelIndex path=%s", (const char *)my.dirModel->filePath(index).toAscii()); my.dirIndex = index; my.dirModel->refresh(index); dirListView->setRootIndex(index); setPathUi(my.dirModel->filePath(index)); } void OpenViewDialog::setPath(const QString &path) { console->post("OpenViewDialog::setPath QString path=%s", (const char *)path.toAscii()); my.dirIndex = my.dirModel->index(path); my.dirModel->refresh(my.dirIndex); dirListView->setRootIndex(my.dirIndex); setPathUi(path); } void OpenViewDialog::pathComboBox_currentIndexChanged(QString path) { console->post("OpenViewDialog::pathComboBox_currentIndexChanged"); setPath(path); } void OpenViewDialog::parentToolButton_clicked() { console->post("OpenViewDialog::parentToolButton_clicked"); setPath(my.dirModel->parent(my.dirIndex)); } void OpenViewDialog::userToolButton_clicked(bool enabled) { if (enabled) { QDir dir; if (!dir.exists(my.userDir)) dir.mkpath(my.userDir); setPath(my.userDir); } } void OpenViewDialog::systemToolButton_clicked(bool enabled) { if (enabled) setPath(my.systemDir); } void OpenViewDialog::dirListView_selectionChanged() { QItemSelectionModel *selections = dirListView->selectionModel(); QModelIndexList selectedIndexes = selections->selectedIndexes(); console->post("OpenViewDialog::dirListView_clicked"); my.completer->setCompletionPrefix(my.dirModel->filePath(my.dirIndex)); if (selectedIndexes.count() != 1) fileNameLineEdit->setText(""); else fileNameLineEdit->setText(my.dirModel->fileName(selectedIndexes.at(0))); } void OpenViewDialog::dirListView_activated(const QModelIndex &index) { QFileInfo fi = my.dirModel->fileInfo(index); console->post("OpenViewDialog::dirListView_activated"); if (fi.isDir()) setPath(index); else if (fi.isFile()) { QStringList files; files << fi.absoluteFilePath(); if (openViewFiles(files) == true) done(0); } } int OpenViewDialog::setupArchiveComboBoxes() { QIcon archiveIcon = fileIconProvider->icon(QedFileIconProvider::Archive); int index = 0; for (unsigned int i = 0; i < archiveGroup->numContexts(); i++) { QmcSource source = archiveGroup->context(i)->source(); sourceComboBox->insertItem(i, archiveIcon, source.source()); if (i == archiveGroup->contextIndex()) index = i; } return index; } int OpenViewDialog::setupLiveComboBoxes() { QIcon containerIcon = fileIconProvider->icon(QedFileIconProvider::Container); QIcon hostIcon = fileIconProvider->icon(QFileIconProvider::Computer); int index = 0; for (unsigned int i = 0; i < liveGroup->numContexts(); i++) { QmcSource source = liveGroup->context(i)->source(); QIcon icon = source.isContainer() ? containerIcon : hostIcon; sourceComboBox->insertItem(i, icon, source.hostLabel()); if (i == liveGroup->contextIndex()) index = i; } return index; } void OpenViewDialog::setupComboBoxes(bool arch) { // We block signals on the target combo boxes so that we don't // send spurious signals out about their lists being changed. // If we did that, we would keep changing the current context. sourceComboBox->blockSignals(true); sourceComboBox->clear(); int index = arch ? setupArchiveComboBoxes() : setupLiveComboBoxes(); sourceComboBox->setCurrentIndex(index); sourceComboBox->blockSignals(false); } void OpenViewDialog::archiveAdd() { QFileDialog *af = new QFileDialog(this); QStringList al; int sts; af->setFileMode(QFileDialog::ExistingFiles); af->setAcceptMode(QFileDialog::AcceptOpen); af->setWindowTitle(tr("Add Archive")); af->setIconProvider(fileIconProvider); af->setDirectory(QDir::toNativeSeparators(QDir::homePath())); if (af->exec() == QDialog::Accepted) al = af->selectedFiles(); for (QStringList::Iterator it = al.begin(); it != al.end(); ++it) { QString archive = *it; if ((sts = archiveGroup->use(PM_CONTEXT_ARCHIVE, archive)) < 0) { archive.prepend(tr("Cannot open PCP archive: ")); archive.append(tr("\n")); archive.append(tr(pmErrStr(sts))); QMessageBox::warning(this, pmProgname, archive, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); } else { setupComboBoxes(true); archiveGroup->updateBounds(); QmcSource source = archiveGroup->context()->source(); pmtime->addArchive(source.start(), source.end(), source.timezone(), source.host(), false); } } delete af; } void OpenViewDialog::hostAdd() { HostDialog *host = new HostDialog(this); if (host->exec() == QDialog::Accepted) { QString hostspec = host->getHostSpecification(); int sts, flags = host->getContextFlags(); if (hostspec == QString::null || hostspec.length() == 0) { hostspec.append(tr("Hostname not specified\n")); QMessageBox::warning(this, pmProgname, hostspec, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, Qt::NoButton, Qt::NoButton); } else if ((sts = liveGroup->use(PM_CONTEXT_HOST, hostspec, flags)) < 0) { hostspec.prepend(tr("Cannot connect to host: ")); hostspec.append(tr("\n")); hostspec.append(tr(pmErrStr(sts))); QMessageBox::warning(this, pmProgname, hostspec, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, Qt::NoButton, Qt::NoButton); } else { console->post(PmChart::DebugUi, "OpenViewDialog::newHost: %s (flags=0x%x)", (const char *)hostspec.toAscii(), flags); setupComboBoxes(false); } } delete host; } void OpenViewDialog::sourcePushButton_clicked() { if (my.archiveSource) archiveAdd(); else hostAdd(); } void OpenViewDialog::sourceComboBox_currentIndexChanged(int index) { console->post("OpenViewDialog::sourceComboBox_currentIndexChanged %d", index); if (my.archiveSource == false) liveGroup->use((unsigned int)index); else archiveGroup->use((unsigned int)index); } bool OpenViewDialog::useLiveContext(int index) { if (liveGroup->numContexts() == 0) { QString msg("No host connections have been established yet\n"); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); return false; } Q_ASSERT(index <= liveGroup->numContexts()); QmcSource source = liveGroup->context(index)->source(); char *sourceName = source.sourceAscii(); bool result = true; int sts; if ((sts = liveGroup->use(PM_CONTEXT_HOST, source.source())) < 0) { QString msg; msg.sprintf("Failed to connect to pmcd on \"%s\".\n%s.\n\n", sourceName, pmErrStr(sts)); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); result = false; } free(sourceName); return result; } bool OpenViewDialog::useArchiveContext(int index) { if (archiveGroup->numContexts() == 0) { QString msg("No PCP archives have been opened yet\n"); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); return false; } Q_ASSERT(index <= archiveGroup->numContexts()); QmcSource source = archiveGroup->context(index)->source(); char *sourceName = source.sourceAscii(); bool result = true; int sts; if ((sts = archiveGroup->use(PM_CONTEXT_ARCHIVE, source.source())) < 0) { QString msg; msg.sprintf("Failed to open archive \"%s\".\n%s.\n\n", sourceName, pmErrStr(sts)); QMessageBox::warning(NULL, pmProgname, msg, QMessageBox::Ok | QMessageBox::Default | QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); result = false; } free(sourceName); return result; } bool OpenViewDialog::useComboBoxContext(bool arch) { if (arch == false) return useLiveContext(sourceComboBox->currentIndex()); else return useArchiveContext(sourceComboBox->currentIndex()); } bool OpenViewDialog::openViewFiles(const QStringList &fl) { QString msg; bool result = true; if (pmchart->isArchiveTab() != my.archiveSource) { if (pmchart->isArchiveTab()) msg = tr("Cannot open Host View(s) in an Archive Tab\n"); else msg = tr("Cannot open Archive View(s) in a Host Tab\n"); QMessageBox::warning(this, pmProgname, msg, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); return false; } if (useComboBoxContext(my.archiveSource) == false) return false; QStringList files = fl; for (QStringList::Iterator it = files.begin(); it != files.end(); ++it) if (openView((const char *)(*it).toAscii()) == false) result = false; pmchart->enableUi(); return result; } void OpenViewDialog::openPushButton_clicked() { QStringList files; QString msg; if (fileNameLineEdit->isModified()) { QString filename = fileNameLineEdit->text().trimmed(); if (filename.isEmpty()) msg = tr("No View file(s) specified"); else { QFileInfo f(filename); if (f.isDir()) { setPath(filename); } else if (f.exists()) { files << filename; if (openViewFiles(files) == true) done(0); } else { msg = tr("No such View file exists:\n"); msg.append(filename); } } } else { QItemSelectionModel *selections = dirListView->selectionModel(); QModelIndexList selectedIndexes = selections->selectedIndexes(); if (selectedIndexes.count() == 0) msg = tr("No View file(s) selected"); else { for (int i = 0; i < selectedIndexes.count(); i++) { QString filename = my.dirModel->filePath(selectedIndexes.at(i)); QFileInfo f(filename); if (f.isDir()) continue; files << filename; } if (files.size() > 0) if (openViewFiles(files) == true) done(0); } } if (msg.isEmpty() == false) { QMessageBox::warning(this, pmProgname, msg, QMessageBox::Ok|QMessageBox::Default|QMessageBox::Escape, QMessageBox::NoButton, QMessageBox::NoButton); } } <|endoftext|>
<commit_before>/**************************************************************************/ /** ** ChildRInterface.cpp: This is the C++ source file for ChildRInterface, which ** provides a generalized, OpenMI-style interface to the release ** version of the CHILD ** landscape evolution model. ** ** For information regarding this program, please contact Greg Tucker at: ** ** Cooperative Institute for Research in Environmental Sciences (CIRES) ** and Department of Geological Sciences ** University of Colorado ** 2200 Colorado Avenue, Campus Box 399 ** Boulder, CO 80309-0399 ** */ /**************************************************************************/ #include "childRInterface.h" Predicates predicate; /**************************************************************************/ /** ** Default constructor for childInterface ** ** Sets pointers to NULL and initialized flag to false. */ /**************************************************************************/ childRInterface:: childRInterface() { initialized = false; rand = NULL; mesh = NULL; output = NULL; storm = NULL; strmNet = NULL; erosion = NULL; uplift = NULL; time = NULL; stratGrid = NULL; loess = NULL; vegetation = NULL; } /**************************************************************************/ /** ** Initialize ** ** This method accesses the input file given on the command line (and ** passed via the parameters argc and argv), and creates the necessary ** objects. */ /**************************************************************************/ void childRInterface:: Initialize( int argc, char **argv ) { /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments tOption option( argc, argv ); // Say hello option.version(); // Open main input file tInputFile inputFile( option.inputFile ); // Create a random number generator for the simulation itself rand = new tRand( inputFile ); // Create and initialize objects: std::cout << "Creating mesh...\n"; mesh = new tMesh<tLNode>( inputFile, option.checkMeshConsistency ); std::cout << "Creating output files...\n"; output = new tLOutput<tLNode>( mesh, inputFile, rand ); storm = new tStorm( inputFile, rand ); std::cout << "Creating stream network...\n"; strmNet = new tStreamNet( *mesh, *storm, inputFile ); erosion = new tErosion( mesh, inputFile ); uplift = new tUplift( inputFile ); // Get various options optDetachLim = inputFile.ReadBool( "OPTDETACHLIM" ); optFloodplainDep = 0; // Floodplain module not linked into this release version optDiffuseDepo = inputFile.ReadBool( "OPTDIFFDEP" ); optLoessDep = inputFile.ReadBool( "OPTLOESSDEP" ); optStratGrid = inputFile.ReadBool( "OPTSTRATGRID" ,false); optNonlinearDiffusion = inputFile.ReadBool( "OPT_NONLINEAR_DIFFUSION", false ); optVegetation = inputFile.ReadBool( "OPTVEG" ); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( mesh, inputFile ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stratigraphy Grid object // and pass it to output if( optStratGrid ) { if (!optFloodplainDep) ReportFatalError("OPTFLOODPLAIN must be enabled."); stratGrid = new tStratGrid (inputFile, mesh); output->SetStratGrid( stratGrid, strmNet ); } std::cout << "Writing data for time zero...\n"; time = new tRunTimer( inputFile, !option.silent_mode ); output->WriteOutput( 0. ); initialized = true; std::cout << "Initialization done.\n"; } /**************************************************************************/ /** ** RunOneStorm ** ** This method executes the model for one storm, calling each of several ** subroutines in turn. It returns the updated simulation time. */ /**************************************************************************/ double childRInterface:: RunOneStorm() { /**************** Run 1 storm ****************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Do interstorm... ** Hillslope transport ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ if(0) //debug std::cout << " " << std::endl; time->ReportTimeStatus(); // Do storm... storm->GenerateStorm( time->getCurrentTime(), strmNet->getInfilt(), strmNet->getSoilStore() ); strmNet->UpdateNet( time->getCurrentTime(), *storm ); // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k0, time->getCurrentTime()); //Diffusion is now before fluvial erosion in case the tools //detachment laws are being used. if( optNonlinearDiffusion ) erosion->DiffuseNonlinear( storm->getStormDuration() + storm->interstormDur(), optDiffuseDepo ); else erosion->Diffuse( storm->getStormDuration() + storm->interstormDur(), optDiffuseDepo ); if( optDetachLim ) erosion->ErodeDetachLim( storm->getStormDuration(), strmNet, vegetation ); else{ erosion->DetachErode( storm->getStormDuration(), strmNet, time->getCurrentTime(), vegetation ); // To use tools rules, you must use DetachErode2 NMG 07/05 //erosion.DetachErode2( storm.getStormDuration(), &strmNet, // time.getCurrentTime(), vegetation ); } // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k1,time->getCurrentTime() ); #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( mesh, storm->interstormDur() ); else vegetation->UpdateVegetation( mesh, storm->getStormDuration(), storm->interstormDur() ); } #undef NEWVEG erosion->UpdateExposureTime( storm->getStormDuration() + storm->interstormDur() ); if( optLoessDep ) loess->DepositLoess( mesh, storm->getStormDuration()+storm->interstormDur(), time->getCurrentTime() ); if( time->getCurrentTime() < uplift->getDuration() ) uplift->DoUplift( mesh, storm->getStormDuration() + storm->interstormDur(), time->getCurrentTime() ); time->Advance( storm->getStormDuration() + storm->interstormDur() ); if( time->CheckOutputTime() ) output->WriteOutput( time->getCurrentTime() ); if( output->OptTSOutput() ) output->WriteTSOutput(); return( time->getCurrentTime() ); } /**************************************************************************/ /** ** Run ** ** This method runs CHILD for a duration specified on the command line or, ** if that duration is <=0, for the duration specified in the previously ** read input file. */ /**************************************************************************/ void childRInterface:: Run( double run_duration ) { if( initialized==false ) ReportFatalError( "childInterface must be initialized (with Initialize() method) before Run() method is called." ); if( run_duration>0.0 ) time->Start( time->getCurrentTime(), time->getCurrentTime()+run_duration ); while( !time->IsFinished() ) RunOneStorm(); } /**************************************************************************/ /** ** CleanUp ** ** This method deletes the various objects created. Note that this ** function is called by the destructor, so if a user function calls it ** explicitly, it will end up being called twice. */ /**************************************************************************/ void childRInterface:: CleanUp() { if( rand ) { delete rand; rand = NULL; } if( mesh ) { delete mesh; mesh = NULL; } if( output ) { delete output; output = NULL; } if( storm ) { delete storm; storm = NULL; } if( strmNet ) { delete strmNet; strmNet = NULL; } if( erosion ) { delete erosion; erosion = NULL; } if( uplift ) { delete uplift; uplift = NULL; } if( time ) { delete time; time = NULL; } if( optVegetation && vegetation ) { delete vegetation; vegetation = NULL; } if( optLoessDep && loess ) { delete loess; loess = NULL; } if( optStratGrid && stratGrid ) { delete stratGrid; stratGrid = NULL; } initialized = false; } childRInterface:: ~childRInterface() { CleanUp(); } /**************************************************************************/ /** ** childInterface::ExternalErosionAndDeposition ** ** This function allows a calling program to tell CHILD to perform a ** given depth of erosion and/or sedimentation at each node. ** ** Presently, it is set up without any grain-size information. A future ** version could also pass grain-size information. ** ** GT, June 09 */ /**************************************************************************/ void childRInterface::ExternalErosionAndDeposition( vector<double> dz ) { tMesh< tLNode >::nodeListIter_t mli( mesh->getNodeList() ); // gets nodes from the list tLNode * cn; for( cn=mli.FirstP(); mli.IsActive(); cn=mli.NextP() ) { int current_id = cn->getPermID(); cn->EroDep( dz[current_id] ); } } <commit_msg>added time->getCurrentTime() to Diffuse calls in childRInterface<commit_after>/**************************************************************************/ /** ** ChildRInterface.cpp: This is the C++ source file for ChildRInterface, which ** provides a generalized, OpenMI-style interface to the release ** version of the CHILD ** landscape evolution model. ** ** For information regarding this program, please contact Greg Tucker at: ** ** Cooperative Institute for Research in Environmental Sciences (CIRES) ** and Department of Geological Sciences ** University of Colorado ** 2200 Colorado Avenue, Campus Box 399 ** Boulder, CO 80309-0399 ** */ /**************************************************************************/ #include "childRInterface.h" Predicates predicate; /**************************************************************************/ /** ** Default constructor for childInterface ** ** Sets pointers to NULL and initialized flag to false. */ /**************************************************************************/ childRInterface:: childRInterface() { initialized = false; rand = NULL; mesh = NULL; output = NULL; storm = NULL; strmNet = NULL; erosion = NULL; uplift = NULL; time = NULL; stratGrid = NULL; loess = NULL; vegetation = NULL; } /**************************************************************************/ /** ** Initialize ** ** This method accesses the input file given on the command line (and ** passed via the parameters argc and argv), and creates the necessary ** objects. */ /**************************************************************************/ void childRInterface:: Initialize( int argc, char **argv ) { /****************** INITIALIZATION *************************************\ ** ALGORITHM ** Get command-line arguments (name of input file + any other opts) ** Set silent_mode flag ** Open main input file ** Create and initialize objects for... ** Mesh ** Output files ** Storm ** Stream network ** Erosion ** Uplift (or baselevel change) ** Run timer ** Write output for initial state ** Get options for erosion type, meandering, etc. \**********************************************************************/ // Check command-line arguments tOption option( argc, argv ); // Say hello option.version(); // Open main input file tInputFile inputFile( option.inputFile ); // Create a random number generator for the simulation itself rand = new tRand( inputFile ); // Create and initialize objects: std::cout << "Creating mesh...\n"; mesh = new tMesh<tLNode>( inputFile, option.checkMeshConsistency ); std::cout << "Creating output files...\n"; output = new tLOutput<tLNode>( mesh, inputFile, rand ); storm = new tStorm( inputFile, rand ); std::cout << "Creating stream network...\n"; strmNet = new tStreamNet( *mesh, *storm, inputFile ); erosion = new tErosion( mesh, inputFile ); uplift = new tUplift( inputFile ); // Get various options optDetachLim = inputFile.ReadBool( "OPTDETACHLIM" ); optFloodplainDep = 0; // Floodplain module not linked into this release version optDiffuseDepo = inputFile.ReadBool( "OPTDIFFDEP" ); optLoessDep = inputFile.ReadBool( "OPTLOESSDEP" ); optStratGrid = inputFile.ReadBool( "OPTSTRATGRID" ,false); optNonlinearDiffusion = inputFile.ReadBool( "OPT_NONLINEAR_DIFFUSION", false ); optVegetation = inputFile.ReadBool( "OPTVEG" ); // If applicable, create Vegetation object if( optVegetation ) vegetation = new tVegetation( mesh, inputFile ); // If applicable, create eolian deposition object if( optLoessDep ) loess = new tEolian( inputFile ); // If applicable, create Stratigraphy Grid object // and pass it to output if( optStratGrid ) { if (!optFloodplainDep) ReportFatalError("OPTFLOODPLAIN must be enabled."); stratGrid = new tStratGrid (inputFile, mesh); output->SetStratGrid( stratGrid, strmNet ); } std::cout << "Writing data for time zero...\n"; time = new tRunTimer( inputFile, !option.silent_mode ); output->WriteOutput( 0. ); initialized = true; std::cout << "Initialization done.\n"; } /**************************************************************************/ /** ** RunOneStorm ** ** This method executes the model for one storm, calling each of several ** subroutines in turn. It returns the updated simulation time. */ /**************************************************************************/ double childRInterface:: RunOneStorm() { /**************** Run 1 storm ****************************************\ ** ALGORITHM ** Generate storm ** Do storm... ** Update network (flow directions, drainage area, runoff) ** Water erosion/deposition (vertical) ** Do interstorm... ** Hillslope transport ** Exposure history ** Mesh densification (if applicable) ** Eolian (loess) deposition (if applicable) ** Uplift (or baselevel change) **********************************************************************/ if(0) //debug std::cout << " " << std::endl; time->ReportTimeStatus(); // Do storm... storm->GenerateStorm( time->getCurrentTime(), strmNet->getInfilt(), strmNet->getSoilStore() ); strmNet->UpdateNet( time->getCurrentTime(), *storm ); // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k0, time->getCurrentTime()); //Diffusion is now before fluvial erosion in case the tools //detachment laws are being used. if( optNonlinearDiffusion ) erosion->DiffuseNonlinear( storm->getStormDuration() + storm->interstormDur(), optDiffuseDepo, time->getCurrentTime() ); else erosion->Diffuse( storm->getStormDuration() + storm->interstormDur(), optDiffuseDepo, time->getCurrentTime() ); if( optDetachLim ) erosion->ErodeDetachLim( storm->getStormDuration(), strmNet, vegetation ); else{ erosion->DetachErode( storm->getStormDuration(), strmNet, time->getCurrentTime(), vegetation ); // To use tools rules, you must use DetachErode2 NMG 07/05 //erosion.DetachErode2( storm.getStormDuration(), &strmNet, // time.getCurrentTime(), vegetation ); } // Link tLNodes to StratNodes, adjust elevation StratNode to surrounding tLNodes if( optStratGrid ) stratGrid->UpdateStratGrid(tStratGrid::k1,time->getCurrentTime() ); #define NEWVEG 1 if( optVegetation ) { if( NEWVEG ) vegetation->GrowVegetation( mesh, storm->interstormDur() ); else vegetation->UpdateVegetation( mesh, storm->getStormDuration(), storm->interstormDur() ); } #undef NEWVEG erosion->UpdateExposureTime( storm->getStormDuration() + storm->interstormDur() ); if( optLoessDep ) loess->DepositLoess( mesh, storm->getStormDuration()+storm->interstormDur(), time->getCurrentTime() ); if( time->getCurrentTime() < uplift->getDuration() ) uplift->DoUplift( mesh, storm->getStormDuration() + storm->interstormDur(), time->getCurrentTime() ); time->Advance( storm->getStormDuration() + storm->interstormDur() ); if( time->CheckOutputTime() ) output->WriteOutput( time->getCurrentTime() ); if( output->OptTSOutput() ) output->WriteTSOutput(); return( time->getCurrentTime() ); } /**************************************************************************/ /** ** Run ** ** This method runs CHILD for a duration specified on the command line or, ** if that duration is <=0, for the duration specified in the previously ** read input file. */ /**************************************************************************/ void childRInterface:: Run( double run_duration ) { if( initialized==false ) ReportFatalError( "childInterface must be initialized (with Initialize() method) before Run() method is called." ); if( run_duration>0.0 ) time->Start( time->getCurrentTime(), time->getCurrentTime()+run_duration ); while( !time->IsFinished() ) RunOneStorm(); } /**************************************************************************/ /** ** CleanUp ** ** This method deletes the various objects created. Note that this ** function is called by the destructor, so if a user function calls it ** explicitly, it will end up being called twice. */ /**************************************************************************/ void childRInterface:: CleanUp() { if( rand ) { delete rand; rand = NULL; } if( mesh ) { delete mesh; mesh = NULL; } if( output ) { delete output; output = NULL; } if( storm ) { delete storm; storm = NULL; } if( strmNet ) { delete strmNet; strmNet = NULL; } if( erosion ) { delete erosion; erosion = NULL; } if( uplift ) { delete uplift; uplift = NULL; } if( time ) { delete time; time = NULL; } if( optVegetation && vegetation ) { delete vegetation; vegetation = NULL; } if( optLoessDep && loess ) { delete loess; loess = NULL; } if( optStratGrid && stratGrid ) { delete stratGrid; stratGrid = NULL; } initialized = false; } childRInterface:: ~childRInterface() { CleanUp(); } /**************************************************************************/ /** ** childInterface::ExternalErosionAndDeposition ** ** This function allows a calling program to tell CHILD to perform a ** given depth of erosion and/or sedimentation at each node. ** ** Presently, it is set up without any grain-size information. A future ** version could also pass grain-size information. ** ** GT, June 09 */ /**************************************************************************/ void childRInterface::ExternalErosionAndDeposition( vector<double> dz ) { tMesh< tLNode >::nodeListIter_t mli( mesh->getNodeList() ); // gets nodes from the list tLNode * cn; for( cn=mli.FirstP(); mli.IsActive(); cn=mli.NextP() ) { int current_id = cn->getPermID(); cn->EroDep( dz[current_id] ); } } <|endoftext|>
<commit_before>/** * @file mega/posix/drivenotifyposix.cpp * @brief Mega SDK various utilities and helper classes * * (c) 2013-2020 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #ifdef USE_DRIVE_NOTIFICATIONS #include "mega/drivenotify.h" #include <libudev.h> // Ubuntu: sudo apt-get install libudev-dev #include <mntent.h> #include <cstring> #include <chrono> namespace mega { // // DriveNotifyPosix ///////////////////////////////////////////// bool DriveNotifyPosix::startNotifier() { if (mEventSinkThread.joinable() || mStop.load()) return false; // init udev resource mUdev = udev_new(); if (!mUdev) return false; // is udevd daemon running? cacheMountedPartitions(); // init udev monitor mUdevMon = udev_monitor_new_from_netlink(mUdev, "udev"); if (!mUdevMon) { udev_unref(mUdev); mUdev = nullptr; return false; } // On unix systems you need to define your udev rules to allow notifications for // your device. // // i.e. on Ubuntu create file "99-z-mega.rules" either in // /etc/udev/rules.d/ OR // /usr/lib/udev/rules.d/ // and add line: // SUBSYSTEM=="block", ATTRS{idDevtype}=="partition", MODE="0666" udev_monitor_filter_add_match_subsystem_devtype(mUdevMon, "block", nullptr); udev_monitor_enable_receiving(mUdevMon); // start worker thread mEventSinkThread = std::thread(&DriveNotifyPosix::doInThread, this); return true; } void DriveNotifyPosix::stopNotifier() { // begin the stopping routine mStop.store(true); // stop the worker thread if (mEventSinkThread.joinable()) { mEventSinkThread.join(); } // release udev monitor if (mUdevMon) { udev_monitor_filter_remove(mUdevMon); udev_monitor_unref(mUdevMon); mUdevMon = nullptr; } // release udev resource if (mUdev) { udev_unref(mUdev); mUdev = nullptr; } // end the stopping routine mStop.store(false); // and allow reusing this instance } void DriveNotifyPosix::doInThread() { int fd = udev_monitor_get_fd(mUdevMon); while (!mStop.load()) { // use a blocking call, with a timeout, to check for device events fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); timeval tv; tv.tv_sec = 0; tv.tv_usec = 250 * 1000; // 250ms int ret = select(fd+1, &fds, nullptr, nullptr, &tv); if (ret <= 0 || !FD_ISSET(fd, &fds)) continue; // get any [dis]connected device udev_device* dev = udev_monitor_receive_device(mUdevMon); if (dev) { evaluateDevice(dev); udev_device_unref(dev); } } } void DriveNotifyPosix::evaluateDevice(udev_device* dev) // dev must Not be null { // filter "partition" events const char* devtype = udev_device_get_devtype(dev); // "partition" if(strcmp(devtype, "partition")) return; // filter "add"/"remove" actions const char* action = udev_device_get_action(dev); // "add" / "remove" bool added = !strcmp(action, "add"); bool removed = !added && !strcmp(action, "remove"); if (!(added || removed)) return; // ignore other possible actions // get device location const char* devNode = udev_device_get_devnode(dev); // "/dev/sda1" if (!devNode) return; // did something go wrong? const std::string& devNodeStr(devNode); // gather drive info DriveInfo drvInfo; drvInfo.connected = added; // get the mount point if (removed) { // get it from the cache, because it will have already been removed from // the relevant locations by the time getMountPoint() will attempt to read it drvInfo.mountPoint = mMounted[devNodeStr]; mMounted.erase(devNodeStr); // remove from cache } else // added { // reading it might happen before the relevant locations have been updated, // so allow retrying a few times, say at 100ms intervals for (int i = 0; i < 5; ++i) { drvInfo.mountPoint = getMountPoint(devNodeStr); if (!drvInfo.mountPoint.empty()) { mMounted[devNodeStr] = drvInfo.mountPoint; // cache it break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // send notification if (!drvInfo.mountPoint.empty()) { add(std::move(drvInfo)); } } std::string DriveNotifyPosix::getMountPoint(const std::string& device) { std::string mountPoint; // go to all mounts FILE* fsMounts = setmntent("/proc/mounts", "r"); if (!fsMounts) // this should never happen { // make another attempt fsMounts = setmntent("/etc/mtab", "r"); if (!fsMounts) return mountPoint; } // search mount point for the current device for (mntent* mnt = getmntent(fsMounts); mnt; mnt = getmntent(fsMounts)) { if (device == mnt->mnt_fsname) { mountPoint = mnt->mnt_dir; break; } } endmntent(fsMounts); // closes the file descriptor return mountPoint; } void DriveNotifyPosix::cacheMountedPartitions() { // enumerate all mounted partitions udev_enumerate* enumerate = udev_enumerate_new(mUdev); udev_enumerate_add_match_subsystem(enumerate, "block"); udev_enumerate_add_match_property(enumerate, "DEVTYPE", "partition"); udev_enumerate_scan_devices(enumerate); udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate); udev_list_entry *entry; udev_list_entry_foreach(entry, devices) // for loop { // get a partition const char* entryName = udev_list_entry_get_name(entry); udev_device* blockDev = udev_device_new_from_syspath(mUdev, entryName); if (!blockDev) continue; // filter only removable ones if (isRemovable(blockDev)) { // get partition node const char* devNode = udev_device_get_devnode(blockDev); // "/dev/sda1" // cache mount point std::string mountPoint = getMountPoint(devNode); if (!mountPoint.empty()) { mMounted[devNode] = mountPoint; } } udev_device_unref(blockDev); } udev_enumerate_unref(enumerate); } bool DriveNotifyPosix::isRemovable(udev_device* part) { udev_device* parent = udev_device_get_parent(part); // do not unref this one! if (!parent) return false; const char* removable = udev_device_get_sysattr_value(parent, "removable"); return removable && !strcmp(removable, "1"); } DriveNotifyPosix::~DriveNotifyPosix() { stop(); } } // namespace #endif // USE_DRIVE_NOTIFICATIONS <commit_msg>Restrict drive monitor filter even more<commit_after>/** * @file mega/posix/drivenotifyposix.cpp * @brief Mega SDK various utilities and helper classes * * (c) 2013-2020 by Mega Limited, Auckland, New Zealand * * This file is part of the MEGA SDK - Client Access Engine. * * Applications using the MEGA API must present a valid application key * and comply with the the rules set forth in the Terms of Service. * * The MEGA SDK 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. * * @copyright Simplified (2-clause) BSD License. * * You should have received a copy of the license along with this * program. */ #ifdef USE_DRIVE_NOTIFICATIONS #include "mega/drivenotify.h" #include <libudev.h> // Ubuntu: sudo apt-get install libudev-dev #include <mntent.h> #include <cstring> #include <chrono> namespace mega { // // DriveNotifyPosix ///////////////////////////////////////////// bool DriveNotifyPosix::startNotifier() { if (mEventSinkThread.joinable() || mStop.load()) return false; // init udev resource mUdev = udev_new(); if (!mUdev) return false; // is udevd daemon running? cacheMountedPartitions(); // init udev monitor mUdevMon = udev_monitor_new_from_netlink(mUdev, "udev"); if (!mUdevMon) { udev_unref(mUdev); mUdev = nullptr; return false; } // On unix systems you need to define your udev rules to allow notifications for // your device. // // i.e. on Ubuntu create file "100-megasync-udev.rules" either in // /etc/udev/rules.d/ OR // /usr/lib/udev/rules.d/ // and add line: // SUBSYSTEM=="block", ATTRS{idDevtype}=="partition" udev_monitor_filter_add_match_subsystem_devtype(mUdevMon, "block", "partition"); udev_monitor_enable_receiving(mUdevMon); // start worker thread mEventSinkThread = std::thread(&DriveNotifyPosix::doInThread, this); return true; } void DriveNotifyPosix::stopNotifier() { // begin the stopping routine mStop.store(true); // stop the worker thread if (mEventSinkThread.joinable()) { mEventSinkThread.join(); } // release udev monitor if (mUdevMon) { udev_monitor_filter_remove(mUdevMon); udev_monitor_unref(mUdevMon); mUdevMon = nullptr; } // release udev resource if (mUdev) { udev_unref(mUdev); mUdev = nullptr; } // end the stopping routine mStop.store(false); // and allow reusing this instance } void DriveNotifyPosix::doInThread() { int fd = udev_monitor_get_fd(mUdevMon); while (!mStop.load()) { // use a blocking call, with a timeout, to check for device events fd_set fds; FD_ZERO(&fds); FD_SET(fd, &fds); timeval tv; tv.tv_sec = 0; tv.tv_usec = 250 * 1000; // 250ms int ret = select(fd+1, &fds, nullptr, nullptr, &tv); if (ret <= 0 || !FD_ISSET(fd, &fds)) continue; // get any [dis]connected device udev_device* dev = udev_monitor_receive_device(mUdevMon); if (dev) { evaluateDevice(dev); udev_device_unref(dev); } } } void DriveNotifyPosix::evaluateDevice(udev_device* dev) // dev must Not be null { // filter "partition" events const char* devtype = udev_device_get_devtype(dev); // "partition" if(strcmp(devtype, "partition")) return; // filter "add"/"remove" actions const char* action = udev_device_get_action(dev); // "add" / "remove" bool added = !strcmp(action, "add"); bool removed = !added && !strcmp(action, "remove"); if (!(added || removed)) return; // ignore other possible actions // get device location const char* devNode = udev_device_get_devnode(dev); // "/dev/sda1" if (!devNode) return; // did something go wrong? const std::string& devNodeStr(devNode); // gather drive info DriveInfo drvInfo; drvInfo.connected = added; // get the mount point if (removed) { // get it from the cache, because it will have already been removed from // the relevant locations by the time getMountPoint() will attempt to read it drvInfo.mountPoint = mMounted[devNodeStr]; mMounted.erase(devNodeStr); // remove from cache } else // added { // reading it might happen before the relevant locations have been updated, // so allow retrying a few times, say at 100ms intervals for (int i = 0; i < 5; ++i) { drvInfo.mountPoint = getMountPoint(devNodeStr); if (!drvInfo.mountPoint.empty()) { mMounted[devNodeStr] = drvInfo.mountPoint; // cache it break; } std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } // send notification if (!drvInfo.mountPoint.empty()) { add(std::move(drvInfo)); } } std::string DriveNotifyPosix::getMountPoint(const std::string& device) { std::string mountPoint; // go to all mounts FILE* fsMounts = setmntent("/proc/mounts", "r"); if (!fsMounts) // this should never happen { // make another attempt fsMounts = setmntent("/etc/mtab", "r"); if (!fsMounts) return mountPoint; } // search mount point for the current device for (mntent* mnt = getmntent(fsMounts); mnt; mnt = getmntent(fsMounts)) { if (device == mnt->mnt_fsname) { mountPoint = mnt->mnt_dir; break; } } endmntent(fsMounts); // closes the file descriptor return mountPoint; } void DriveNotifyPosix::cacheMountedPartitions() { // enumerate all mounted partitions udev_enumerate* enumerate = udev_enumerate_new(mUdev); udev_enumerate_add_match_subsystem(enumerate, "block"); udev_enumerate_add_match_property(enumerate, "DEVTYPE", "partition"); udev_enumerate_scan_devices(enumerate); udev_list_entry *devices = udev_enumerate_get_list_entry(enumerate); udev_list_entry *entry; udev_list_entry_foreach(entry, devices) // for loop { // get a partition const char* entryName = udev_list_entry_get_name(entry); udev_device* blockDev = udev_device_new_from_syspath(mUdev, entryName); if (!blockDev) continue; // filter only removable ones if (isRemovable(blockDev)) { // get partition node const char* devNode = udev_device_get_devnode(blockDev); // "/dev/sda1" // cache mount point std::string mountPoint = getMountPoint(devNode); if (!mountPoint.empty()) { mMounted[devNode] = mountPoint; } } udev_device_unref(blockDev); } udev_enumerate_unref(enumerate); } bool DriveNotifyPosix::isRemovable(udev_device* part) { udev_device* parent = udev_device_get_parent(part); // do not unref this one! if (!parent) return false; const char* removable = udev_device_get_sysattr_value(parent, "removable"); return removable && !strcmp(removable, "1"); } DriveNotifyPosix::~DriveNotifyPosix() { stop(); } } // namespace #endif // USE_DRIVE_NOTIFICATIONS <|endoftext|>
<commit_before>#ifdef HAVE_CONFIG_H #include "sys_config.h" #endif #include "arch/MGSystem.h" #include "simreadline.h" #include "commands.h" #include "sim/config.h" #ifdef ENABLE_MONITOR # include "sim/monitor.h" #endif #include <sstream> #include <iostream> #include <limits> #ifdef USE_SDL #include <SDL.h> #endif using namespace Simulator; using namespace std; struct ProgramConfig { string m_programFile; string m_configFile; string m_symtableFile; bool m_enableMonitor; bool m_interactive; bool m_terminate; bool m_dumpconf; bool m_quiet; bool m_dumpvars; bool m_earlyquit; vector<pair<string,string> > m_overrides; vector<pair<RegAddr, RegValue> > m_regs; vector<pair<RegAddr, string> > m_loads; }; static void ParseArguments(int argc, const char ** argv, ProgramConfig& config) { config.m_configFile = MGSIM_CONFIG_PATH; config.m_enableMonitor = false; config.m_interactive = false; config.m_terminate = false; config.m_dumpconf = false; config.m_quiet = false; config.m_dumpvars = false; config.m_earlyquit = false; for (int i = 1; i < argc; ++i) { const string arg = argv[i]; if (arg[0] != '-') { if (config.m_programFile != "") cerr << "Warning: program already set (" << config.m_programFile << "), ignoring extra arg: " << arg << endl; else config.m_programFile = arg; } else if (arg == "-c" || arg == "--config") config.m_configFile = argv[++i]; else if (arg == "-i" || arg == "--interactive") config.m_interactive = true; else if (arg == "-t" || arg == "--terminate") config.m_terminate = true; else if (arg == "-q" || arg == "--quiet") config.m_quiet = true; else if (arg == "-s" || arg == "--symtable") config.m_symtableFile = argv[++i]; else if (arg == "--version") { PrintVersion(std::cout); exit(0); } else if (arg == "-h" || arg == "--help") { PrintUsage(std::cout, argv[0]); exit(0); } else if (arg == "-d" || arg == "--dumpconf") config.m_dumpconf = true; else if (arg == "-m" || arg == "--monitor") config.m_enableMonitor = true; else if (arg == "-D" || arg == "--dumpvars") config.m_dumpvars = true; else if (arg == "-n" || arg == "--do-nothing") config.m_earlyquit = true; else if (arg == "-o" || arg == "--override") { if (argv[++i] == NULL) { throw runtime_error("Error: expected configuration option"); } string arg = argv[i]; string::size_type eq = arg.find_first_of("="); if (eq == string::npos) { throw runtime_error("Error: malformed configuration override syntax"); } string name = arg.substr(0, eq); transform(name.begin(), name.end(), name.begin(), ::toupper); config.m_overrides.push_back(make_pair(name, arg.substr(eq + 1))); } else if (toupper(arg[1]) == 'L') { if (argv[++i] == NULL) { throw runtime_error("Error: expected filename"); } string filename(argv[i]); char* endptr; RegAddr addr; unsigned long index = strtoul(&arg[2], &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } addr = MAKE_REGADDR(RT_INTEGER, index); config.m_loads.push_back(make_pair(addr, filename)); } else if (toupper(arg[1]) == 'R' || toupper(arg[1]) == 'F') { if (argv[++i] == NULL) { throw runtime_error("Error: expected register value"); } stringstream value; value << argv[i]; RegAddr addr; RegValue val; char* endptr; unsigned long index = strtoul(&arg[2], &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } if (toupper(arg[1]) == 'R') { value >> *(signed Integer*)&val.m_integer; addr = MAKE_REGADDR(RT_INTEGER, index); } else { double f; value >> f; val.m_float.fromfloat(f); addr = MAKE_REGADDR(RT_FLOAT, index); } if (value.fail()) { throw runtime_error("Error: invalid value for register"); } val.m_state = RST_FULL; config.m_regs.push_back(make_pair(addr, val)); } } if (config.m_programFile.empty()) { throw runtime_error("Error: no program file specified"); } } #ifdef USE_SDL extern "C" #endif int main(int argc, char** argv) { srand(time(NULL)); try { // Parse command line arguments ProgramConfig config; ParseArguments(argc, (const char**)argv, config); if (config.m_interactive) { // Interactive mode PrintVersion(std::cout); } // Read configuration Config configfile(config.m_configFile, config.m_overrides); // Create the system MGSystem sys(configfile, config.m_programFile, config.m_symtableFile, config.m_regs, config.m_loads, !config.m_interactive, !config.m_earlyquit); #ifdef ENABLE_MONITOR string mo_mdfile = configfile.getValue<string>("MonitorMetadataFile", "mgtrace.md"); string mo_tfile = configfile.getValue<string>("MonitorTraceFile", "mgtrace.out"); Monitor mo(sys, config.m_enableMonitor, mo_mdfile, config.m_earlyquit ? "" : mo_tfile, !config.m_interactive); #endif if (config.m_dumpconf) { std::clog << "### simulator version: " PACKAGE_VERSION << std::endl; configfile.dumpConfiguration(std::clog, config.m_configFile); } if (config.m_dumpvars) { std::cout << "### begin monitor variables" << std::endl; ListSampleVariables(std::cout); std::cout << "### end monitor variables" << std::endl; } if (config.m_earlyquit) exit(0); bool interactive = config.m_interactive; if (!interactive) { // Non-interactive mode; run and dump cycle count try { #ifdef ENABLE_MONITOR mo.start(); #endif StepSystem(sys, INFINITE_CYCLES); #ifdef ENABLE_MONITOR mo.stop(); #endif if (!config.m_quiet) { clog << "### begin end-of-simulation statistics" << endl; sys.PrintAllStatistics(clog); clog << "### end end-of-simulation statistics" << endl; } } catch (const exception& e) { #ifdef ENABLE_MONITOR mo.stop(); #endif if (config.m_terminate) { // We do not want to go to interactive mode, // rethrow so it abort the program. throw; } PrintException(cerr, e); // When we get an exception in non-interactive mode, // jump into interactive mode interactive = true; } } if (interactive) { // Command loop cout << endl; CommandLineReader clr; cli_context ctx = { clr, sys #ifdef ENABLE_MONITOR , mo #endif }; while (HandleCommandLine(ctx) == false) /* just loop */; } } catch (const exception& e) { PrintException(cerr, e); return 1; } return 0; } <commit_msg>[mgsim-refactor] Allow to report the internal state of the simulation at the end of execution.<commit_after>#ifdef HAVE_CONFIG_H #include "sys_config.h" #endif #include "arch/MGSystem.h" #include "simreadline.h" #include "commands.h" #include "sim/config.h" #ifdef ENABLE_MONITOR # include "sim/monitor.h" #endif #include <sstream> #include <iostream> #include <limits> #ifdef USE_SDL #include <SDL.h> #endif using namespace Simulator; using namespace std; struct ProgramConfig { string m_programFile; string m_configFile; string m_symtableFile; bool m_enableMonitor; bool m_interactive; bool m_terminate; bool m_dumpconf; bool m_quiet; bool m_dumpvars; vector<string> m_printvars; bool m_earlyquit; vector<pair<string,string> > m_overrides; vector<pair<RegAddr, RegValue> > m_regs; vector<pair<RegAddr, string> > m_loads; }; static void ParseArguments(int argc, const char ** argv, ProgramConfig& config) { config.m_configFile = MGSIM_CONFIG_PATH; config.m_enableMonitor = false; config.m_interactive = false; config.m_terminate = false; config.m_dumpconf = false; config.m_quiet = false; config.m_dumpvars = false; config.m_earlyquit = false; for (int i = 1; i < argc; ++i) { const string arg = argv[i]; if (arg[0] != '-') { if (config.m_programFile != "") cerr << "Warning: program already set (" << config.m_programFile << "), ignoring extra arg: " << arg << endl; else config.m_programFile = arg; } else if (arg == "-c" || arg == "--config") config.m_configFile = argv[++i]; else if (arg == "-i" || arg == "--interactive") config.m_interactive = true; else if (arg == "-t" || arg == "--terminate") config.m_terminate = true; else if (arg == "-q" || arg == "--quiet") config.m_quiet = true; else if (arg == "-s" || arg == "--symtable") config.m_symtableFile = argv[++i]; else if (arg == "--version") { PrintVersion(std::cout); exit(0); } else if (arg == "-h" || arg == "--help") { PrintUsage(std::cout, argv[0]); exit(0); } else if (arg == "-d" || arg == "--dumpconf") config.m_dumpconf = true; else if (arg == "-m" || arg == "--monitor") config.m_enableMonitor = true; else if (arg == "-l" || arg == "--list-mvars") config.m_dumpvars = true; else if (arg == "-p" || arg == "--print-final-mvars") { if (argv[++i] == NULL) { throw runtime_error("Error: expected variable name"); } config.m_printvars.push_back(argv[i]); } else if (arg == "-n" || arg == "--do-nothing") config.m_earlyquit = true; else if (arg == "-o" || arg == "--override") { if (argv[++i] == NULL) { throw runtime_error("Error: expected configuration option"); } string arg = argv[i]; string::size_type eq = arg.find_first_of("="); if (eq == string::npos) { throw runtime_error("Error: malformed configuration override syntax"); } string name = arg.substr(0, eq); transform(name.begin(), name.end(), name.begin(), ::toupper); config.m_overrides.push_back(make_pair(name, arg.substr(eq + 1))); } else if (arg[1] == 'L') { if (argv[++i] == NULL) { throw runtime_error("Error: expected filename"); } string filename(argv[i]); char* endptr; RegAddr addr; unsigned long index = strtoul(&arg[2], &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } addr = MAKE_REGADDR(RT_INTEGER, index); config.m_loads.push_back(make_pair(addr, filename)); } else if (arg[1] == 'R' || arg[1] == 'F') { if (argv[++i] == NULL) { throw runtime_error("Error: expected register value"); } stringstream value; value << argv[i]; RegAddr addr; RegValue val; char* endptr; unsigned long index = strtoul(&arg[2], &endptr, 0); if (*endptr != '\0') { throw runtime_error("Error: invalid register specifier in option"); } if (arg[1] == 'R') { value >> *(signed Integer*)&val.m_integer; addr = MAKE_REGADDR(RT_INTEGER, index); } else { double f; value >> f; val.m_float.fromfloat(f); addr = MAKE_REGADDR(RT_FLOAT, index); } if (value.fail()) { throw runtime_error("Error: invalid value for register"); } val.m_state = RST_FULL; config.m_regs.push_back(make_pair(addr, val)); } } if (config.m_programFile.empty()) { throw runtime_error("Error: no program file specified"); } } void PrintFinalVariables(const ProgramConfig& cfg) { if (!cfg.m_printvars.empty()) { std::cout << "### begin end-of-simulation variables" << std::endl; for (size_t i = 0; i < cfg.m_printvars.size(); ++i) ReadSampleVariables(cout, cfg.m_printvars[i]); std::cout << "### end end-of-simulation variables" << std::endl; } } #ifdef USE_SDL extern "C" #endif int main(int argc, char** argv) { srand(time(NULL)); try { // Parse command line arguments ProgramConfig config; ParseArguments(argc, (const char**)argv, config); if (config.m_interactive) { // Interactive mode PrintVersion(std::cout); } // Read configuration Config configfile(config.m_configFile, config.m_overrides); // Create the system MGSystem sys(configfile, config.m_programFile, config.m_symtableFile, config.m_regs, config.m_loads, !config.m_interactive, !config.m_earlyquit); #ifdef ENABLE_MONITOR string mo_mdfile = configfile.getValue<string>("MonitorMetadataFile", "mgtrace.md"); string mo_tfile = configfile.getValue<string>("MonitorTraceFile", "mgtrace.out"); Monitor mo(sys, config.m_enableMonitor, mo_mdfile, config.m_earlyquit ? "" : mo_tfile, !config.m_interactive); #endif if (config.m_dumpconf) { std::clog << "### simulator version: " PACKAGE_VERSION << std::endl; configfile.dumpConfiguration(std::clog, config.m_configFile); } if (config.m_dumpvars) { std::cout << "### begin monitor variables" << std::endl; ListSampleVariables(std::cout); std::cout << "### end monitor variables" << std::endl; } if (config.m_earlyquit) exit(0); bool interactive = config.m_interactive; if (!interactive) { // Non-interactive mode; run and dump cycle count try { #ifdef ENABLE_MONITOR mo.start(); #endif StepSystem(sys, INFINITE_CYCLES); #ifdef ENABLE_MONITOR mo.stop(); #endif if (!config.m_quiet) { clog << "### begin end-of-simulation statistics" << endl; sys.PrintAllStatistics(clog); clog << "### end end-of-simulation statistics" << endl; } } catch (const exception& e) { #ifdef ENABLE_MONITOR mo.stop(); #endif if (config.m_terminate) { // We do not want to go to interactive mode, // rethrow so it abort the program. PrintFinalVariables(config); throw; } PrintException(cerr, e); // When we get an exception in non-interactive mode, // jump into interactive mode interactive = true; } } if (interactive) { // Command loop cout << endl; CommandLineReader clr; cli_context ctx = { clr, sys #ifdef ENABLE_MONITOR , mo #endif }; while (HandleCommandLine(ctx) == false) /* just loop */; } PrintFinalVariables(config); } catch (const exception& e) { PrintException(cerr, e); return 1; } return 0; } <|endoftext|>
<commit_before>#include <sstream> #include <iostream> #include <vector> #include <cassert> #include <cmath> #include <tr1/memory> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "hg_sampler.h" #include "sentence_metadata.h" #include "scorer.h" #include "verbose.h" #include "viterbi.h" #include "hg.h" #include "prob.h" #include "kbest.h" #include "ff_register.h" #include "decoder.h" #include "filelib.h" #include "fdict.h" #include "weights.h" #include "sparse_vector.h" #include "sampler.h" using namespace std; namespace po = boost::program_options; bool invert_score; std::tr1::shared_ptr<MT19937> rng; void RandomPermutation(int len, vector<int>* p_ids) { vector<int>& ids = *p_ids; ids.resize(len); for (int i = 0; i < len; ++i) ids[i] = i; for (int i = len; i > 0; --i) { int j = rng->next() * i; if (j == i) i--; swap(ids[i-1], ids[j]); } } bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("input_weights,w",po::value<string>(),"Input feature weights file") ("source,i",po::value<string>(),"Source file for development set") ("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data") ("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)") ("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)") ("max_step_size,C", po::value<double>()->default_value(0.01), "regularization strength (C)") ("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by") ("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to search for oracles") ("sample_forest,f", "Instead of a k-best list, sample k hypotheses from the decoder's forest") ("sample_forest_unit_weight_vector,x", "Before sampling (must use -f option), rescale the weight vector used so it has unit length; this may improve the quality of the samples") ("random_seed,S", po::value<uint32_t>(), "Random seed (if not specified, /dev/random will be used)") ("decoder_config,c",po::value<string>(),"Decoder configuration file"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) { cerr << dcmdline_options << endl; return false; } return true; } static const double kMINUS_EPSILON = -1e-6; struct HypothesisInfo { SparseVector<double> features; double mt_metric; }; struct GoodBadOracle { std::tr1::shared_ptr<HypothesisInfo> good; std::tr1::shared_ptr<HypothesisInfo> bad; }; struct TrainingObserver : public DecoderObserver { TrainingObserver(const int k, const DocScorer& d, bool sf, vector<GoodBadOracle>* o) : ds(d), oracles(*o), kbest_size(k), sample_forest(sf) {} const DocScorer& ds; vector<GoodBadOracle>& oracles; std::tr1::shared_ptr<HypothesisInfo> cur_best; const int kbest_size; const bool sample_forest; const HypothesisInfo& GetCurrentBestHypothesis() const { return *cur_best; } virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) { UpdateOracles(smeta.GetSentenceID(), *hg); } std::tr1::shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) { std::tr1::shared_ptr<HypothesisInfo> h(new HypothesisInfo); h->features = feats; h->mt_metric = score; return h; } void UpdateOracles(int sent_id, const Hypergraph& forest) { std::tr1::shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good; std::tr1::shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad; cur_bad.reset(); // TODO get rid of?? if (sample_forest) { vector<WordID> cur_prediction; ViterbiESentence(forest, &cur_prediction); float sentscore = ds[sent_id]->ScoreCandidate(cur_prediction)->ComputeScore(); cur_best = MakeHypothesisInfo(ViterbiFeatures(forest), sentscore); vector<HypergraphSampler::Hypothesis> samples; HypergraphSampler::sample_hypotheses(forest, kbest_size, &*rng, &samples); for (unsigned i = 0; i < samples.size(); ++i) { sentscore = ds[sent_id]->ScoreCandidate(samples[i].words)->ComputeScore(); if (invert_score) sentscore *= -1.0; if (!cur_good || sentscore > cur_good->mt_metric) cur_good = MakeHypothesisInfo(samples[i].fmap, sentscore); if (!cur_bad || sentscore < cur_bad->mt_metric) cur_bad = MakeHypothesisInfo(samples[i].fmap, sentscore); } } else { KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size); for (int i = 0; i < kbest_size; ++i) { const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d = kbest.LazyKthBest(forest.nodes_.size() - 1, i); if (!d) break; float sentscore = ds[sent_id]->ScoreCandidate(d->yield)->ComputeScore(); if (invert_score) sentscore *= -1.0; // cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl; if (i == 0) cur_best = MakeHypothesisInfo(d->feature_values, sentscore); if (!cur_good || sentscore > cur_good->mt_metric) cur_good = MakeHypothesisInfo(d->feature_values, sentscore); if (!cur_bad || sentscore < cur_bad->mt_metric) cur_bad = MakeHypothesisInfo(d->feature_values, sentscore); } //cerr << "GOOD: " << cur_good->mt_metric << endl; //cerr << " CUR: " << cur_best->mt_metric << endl; //cerr << " BAD: " << cur_bad->mt_metric << endl; } } }; void ReadTrainingCorpus(const string& fname, vector<string>* c) { ReadFile rf(fname); istream& in = *rf.stream(); string line; while(in) { getline(in, line); if (!in) break; c->push_back(line); } } bool ApproxEqual(double a, double b) { if (a == b) return true; return (fabs(a-b)/fabs(b)) < 0.000001; } int main(int argc, char** argv) { register_feature_functions(); SetSilent(true); // turn off verbose decoder output po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; if (conf.count("random_seed")) rng.reset(new MT19937(conf["random_seed"].as<uint32_t>())); else rng.reset(new MT19937); const bool sample_forest = conf.count("sample_forest") > 0; const bool sample_forest_unit_weight_vector = conf.count("sample_forest_unit_weight_vector") > 0; if (sample_forest_unit_weight_vector && !sample_forest) { cerr << "Cannot --sample_forest_unit_weight_vector without --sample_forest" << endl; return 1; } vector<string> corpus; ReadTrainingCorpus(conf["source"].as<string>(), &corpus); const string metric_name = conf["mt_metric"].as<string>(); ScoreType type = ScoreTypeFromString(metric_name); if (type == TER) { invert_score = true; } else { invert_score = false; } DocScorer ds(type, conf["reference"].as<vector<string> >(), ""); cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl; if (ds.size() != corpus.size()) { cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n"; return 1; } ReadFile ini_rf(conf["decoder_config"].as<string>()); Decoder decoder(ini_rf.stream()); // load initial weights vector<weight_t>& dense_weights = decoder.CurrentWeightVector(); SparseVector<weight_t> lambdas; Weights::InitFromFile(conf["input_weights"].as<string>(), &dense_weights); Weights::InitSparseVector(dense_weights, &lambdas); const double max_step_size = conf["max_step_size"].as<double>(); const double mt_metric_scale = conf["mt_metric_scale"].as<double>(); assert(corpus.size() > 0); vector<GoodBadOracle> oracles(corpus.size()); TrainingObserver observer(conf["k_best_size"].as<int>(), ds, sample_forest, &oracles); int cur_sent = 0; int lcount = 0; int normalizer = 0; double tot_loss = 0; int dots = 0; int cur_pass = 0; SparseVector<double> tot; tot += lambdas; // initial weights normalizer++; // count for initial weights int max_iteration = conf["passes"].as<int>() * corpus.size(); string msg = "# MIRA tuned weights"; string msga = "# MIRA tuned weights AVERAGED"; vector<int> order; RandomPermutation(corpus.size(), &order); while (lcount <= max_iteration) { lambdas.init_vector(&dense_weights); if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; } if (corpus.size() == cur_sent) { cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n"; Weights::ShowLargestFeatures(dense_weights); cur_sent = 0; tot_loss = 0; dots = 0; ostringstream os; os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz"; SparseVector<double> x = tot; x /= normalizer; ostringstream sa; sa << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << "-avg.gz"; x.init_vector(&dense_weights); Weights::WriteToFile(os.str(), dense_weights, true, &msg); ++cur_pass; RandomPermutation(corpus.size(), &order); } if (cur_sent == 0) { cerr << "PASS " << (lcount / corpus.size() + 1) << endl; } decoder.SetId(order[cur_sent]); double sc = 1.0; if (sample_forest_unit_weight_vector) { sc = lambdas.l2norm(); if (sc > 0) { for (unsigned i = 0; i < dense_weights.size(); ++i) dense_weights[i] /= sc; } } decoder.Decode(corpus[order[cur_sent]], &observer); // update oracles if (sc && sc != 1.0) { for (unsigned i = 0; i < dense_weights.size(); ++i) dense_weights[i] *= sc; } const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis(); const HypothesisInfo& cur_good = *oracles[order[cur_sent]].good; const HypothesisInfo& cur_bad = *oracles[order[cur_sent]].bad; tot_loss += cur_hyp.mt_metric; if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) { const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) + mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric); //cerr << "LOSS: " << loss << endl; if (loss > 0.0) { SparseVector<double> diff = cur_good.features; diff -= cur_bad.features; double step_size = loss / diff.l2norm_sq(); //cerr << loss << " " << step_size << " " << diff << endl; if (step_size > max_step_size) step_size = max_step_size; lambdas += (cur_good.features * step_size); lambdas -= (cur_bad.features * step_size); //cerr << "L: " << lambdas << endl; } } tot += lambdas; ++normalizer; ++lcount; ++cur_sent; } cerr << endl; Weights::WriteToFile("weights.mira-final.gz", dense_weights, true, &msg); tot /= normalizer; tot.init_vector(dense_weights); msg = "# MIRA tuned weights (averaged vector)"; Weights::WriteToFile("weights.mira-final-avg.gz", dense_weights, true, &msg); cerr << "Optimization complete.\nAVERAGED WEIGHTS: weights.mira-final-avg.gz\n"; return 0; } <commit_msg>switch to new score interface for mira<commit_after>#include <sstream> #include <iostream> #include <vector> #include <cassert> #include <cmath> #include <tr1/memory> #include <boost/program_options.hpp> #include <boost/program_options/variables_map.hpp> #include "stringlib.h" #include "hg_sampler.h" #include "sentence_metadata.h" #include "ns.h" #include "ns_docscorer.h" #include "verbose.h" #include "viterbi.h" #include "hg.h" #include "prob.h" #include "kbest.h" #include "ff_register.h" #include "decoder.h" #include "filelib.h" #include "fdict.h" #include "weights.h" #include "sparse_vector.h" #include "sampler.h" using namespace std; namespace po = boost::program_options; bool invert_score; std::tr1::shared_ptr<MT19937> rng; void RandomPermutation(int len, vector<int>* p_ids) { vector<int>& ids = *p_ids; ids.resize(len); for (int i = 0; i < len; ++i) ids[i] = i; for (int i = len; i > 0; --i) { int j = rng->next() * i; if (j == i) i--; swap(ids[i-1], ids[j]); } } bool InitCommandLine(int argc, char** argv, po::variables_map* conf) { po::options_description opts("Configuration options"); opts.add_options() ("input_weights,w",po::value<string>(),"Input feature weights file") ("source,i",po::value<string>(),"Source file for development set") ("passes,p", po::value<int>()->default_value(15), "Number of passes through the training data") ("reference,r",po::value<vector<string> >(), "[REQD] Reference translation(s) (tokenized text file)") ("mt_metric,m",po::value<string>()->default_value("ibm_bleu"), "Scoring metric (ibm_bleu, nist_bleu, koehn_bleu, ter, combi)") ("max_step_size,C", po::value<double>()->default_value(0.01), "regularization strength (C)") ("mt_metric_scale,s", po::value<double>()->default_value(1.0), "Amount to scale MT loss function by") ("k_best_size,k", po::value<int>()->default_value(250), "Size of hypothesis list to search for oracles") ("sample_forest,f", "Instead of a k-best list, sample k hypotheses from the decoder's forest") ("sample_forest_unit_weight_vector,x", "Before sampling (must use -f option), rescale the weight vector used so it has unit length; this may improve the quality of the samples") ("random_seed,S", po::value<uint32_t>(), "Random seed (if not specified, /dev/random will be used)") ("decoder_config,c",po::value<string>(),"Decoder configuration file"); po::options_description clo("Command line options"); clo.add_options() ("config", po::value<string>(), "Configuration file") ("help,h", "Print this help message and exit"); po::options_description dconfig_options, dcmdline_options; dconfig_options.add(opts); dcmdline_options.add(opts).add(clo); po::store(parse_command_line(argc, argv, dcmdline_options), *conf); if (conf->count("config")) { ifstream config((*conf)["config"].as<string>().c_str()); po::store(po::parse_config_file(config, dconfig_options), *conf); } po::notify(*conf); if (conf->count("help") || !conf->count("input_weights") || !conf->count("source") || !conf->count("decoder_config") || !conf->count("reference")) { cerr << dcmdline_options << endl; return false; } return true; } static const double kMINUS_EPSILON = -1e-6; struct HypothesisInfo { SparseVector<double> features; double mt_metric; }; struct GoodBadOracle { std::tr1::shared_ptr<HypothesisInfo> good; std::tr1::shared_ptr<HypothesisInfo> bad; }; struct TrainingObserver : public DecoderObserver { TrainingObserver(const int k, const DocumentScorer& d, const EvaluationMetric& m, bool sf, vector<GoodBadOracle>* o) : ds(d), metric(m), oracles(*o), kbest_size(k), sample_forest(sf) {} const DocumentScorer& ds; const EvaluationMetric& metric; vector<GoodBadOracle>& oracles; std::tr1::shared_ptr<HypothesisInfo> cur_best; const int kbest_size; const bool sample_forest; const HypothesisInfo& GetCurrentBestHypothesis() const { return *cur_best; } virtual void NotifyTranslationForest(const SentenceMetadata& smeta, Hypergraph* hg) { UpdateOracles(smeta.GetSentenceID(), *hg); } std::tr1::shared_ptr<HypothesisInfo> MakeHypothesisInfo(const SparseVector<double>& feats, const double score) { std::tr1::shared_ptr<HypothesisInfo> h(new HypothesisInfo); h->features = feats; h->mt_metric = score; return h; } void UpdateOracles(int sent_id, const Hypergraph& forest) { std::tr1::shared_ptr<HypothesisInfo>& cur_good = oracles[sent_id].good; std::tr1::shared_ptr<HypothesisInfo>& cur_bad = oracles[sent_id].bad; cur_bad.reset(); // TODO get rid of?? if (sample_forest) { vector<WordID> cur_prediction; ViterbiESentence(forest, &cur_prediction); SufficientStats sstats; ds[sent_id]->Evaluate(cur_prediction, &sstats); float sentscore = metric.ComputeScore(sstats); cur_best = MakeHypothesisInfo(ViterbiFeatures(forest), sentscore); vector<HypergraphSampler::Hypothesis> samples; HypergraphSampler::sample_hypotheses(forest, kbest_size, &*rng, &samples); for (unsigned i = 0; i < samples.size(); ++i) { ds[sent_id]->Evaluate(samples[i].words, &sstats); float sentscore = metric.ComputeScore(sstats); if (invert_score) sentscore *= -1.0; if (!cur_good || sentscore > cur_good->mt_metric) cur_good = MakeHypothesisInfo(samples[i].fmap, sentscore); if (!cur_bad || sentscore < cur_bad->mt_metric) cur_bad = MakeHypothesisInfo(samples[i].fmap, sentscore); } } else { KBest::KBestDerivations<vector<WordID>, ESentenceTraversal> kbest(forest, kbest_size); SufficientStats sstats; for (int i = 0; i < kbest_size; ++i) { const KBest::KBestDerivations<vector<WordID>, ESentenceTraversal>::Derivation* d = kbest.LazyKthBest(forest.nodes_.size() - 1, i); if (!d) break; ds[sent_id]->Evaluate(d->yield, &sstats); float sentscore = metric.ComputeScore(sstats); if (invert_score) sentscore *= -1.0; // cerr << TD::GetString(d->yield) << " ||| " << d->score << " ||| " << sentscore << endl; if (i == 0) cur_best = MakeHypothesisInfo(d->feature_values, sentscore); if (!cur_good || sentscore > cur_good->mt_metric) cur_good = MakeHypothesisInfo(d->feature_values, sentscore); if (!cur_bad || sentscore < cur_bad->mt_metric) cur_bad = MakeHypothesisInfo(d->feature_values, sentscore); } //cerr << "GOOD: " << cur_good->mt_metric << endl; //cerr << " CUR: " << cur_best->mt_metric << endl; //cerr << " BAD: " << cur_bad->mt_metric << endl; } } }; void ReadTrainingCorpus(const string& fname, vector<string>* c) { ReadFile rf(fname); istream& in = *rf.stream(); string line; while(in) { getline(in, line); if (!in) break; c->push_back(line); } } bool ApproxEqual(double a, double b) { if (a == b) return true; return (fabs(a-b)/fabs(b)) < 0.000001; } int main(int argc, char** argv) { register_feature_functions(); SetSilent(true); // turn off verbose decoder output po::variables_map conf; if (!InitCommandLine(argc, argv, &conf)) return 1; if (conf.count("random_seed")) rng.reset(new MT19937(conf["random_seed"].as<uint32_t>())); else rng.reset(new MT19937); const bool sample_forest = conf.count("sample_forest") > 0; const bool sample_forest_unit_weight_vector = conf.count("sample_forest_unit_weight_vector") > 0; if (sample_forest_unit_weight_vector && !sample_forest) { cerr << "Cannot --sample_forest_unit_weight_vector without --sample_forest" << endl; return 1; } vector<string> corpus; ReadTrainingCorpus(conf["source"].as<string>(), &corpus); string metric_name = UppercaseString(conf["evaluation_metric"].as<string>()); if (metric_name == "COMBI") { cerr << "WARNING: 'combi' metric is no longer supported, switching to 'COMB:TER=-0.5;IBM_BLEU=0.5'\n"; metric_name = "COMB:TER=-0.5;IBM_BLEU=0.5"; } else if (metric_name == "BLEU") { cerr << "WARNING: 'BLEU' is ambiguous, assuming 'IBM_BLEU'\n"; metric_name = "IBM_BLEU"; } EvaluationMetric* metric = EvaluationMetric::Instance(metric_name); DocumentScorer ds(metric, conf["reference"].as<vector<string> >()); cerr << "Loaded " << ds.size() << " references for scoring with " << metric_name << endl; invert_score = metric->IsErrorMetric(); if (ds.size() != corpus.size()) { cerr << "Mismatched number of references (" << ds.size() << ") and sources (" << corpus.size() << ")\n"; return 1; } ReadFile ini_rf(conf["decoder_config"].as<string>()); Decoder decoder(ini_rf.stream()); // load initial weights vector<weight_t>& dense_weights = decoder.CurrentWeightVector(); SparseVector<weight_t> lambdas; Weights::InitFromFile(conf["input_weights"].as<string>(), &dense_weights); Weights::InitSparseVector(dense_weights, &lambdas); const double max_step_size = conf["max_step_size"].as<double>(); const double mt_metric_scale = conf["mt_metric_scale"].as<double>(); assert(corpus.size() > 0); vector<GoodBadOracle> oracles(corpus.size()); TrainingObserver observer(conf["k_best_size"].as<int>(), ds, *metric, sample_forest, &oracles); int cur_sent = 0; int lcount = 0; int normalizer = 0; double tot_loss = 0; int dots = 0; int cur_pass = 0; SparseVector<double> tot; tot += lambdas; // initial weights normalizer++; // count for initial weights int max_iteration = conf["passes"].as<int>() * corpus.size(); string msg = "# MIRA tuned weights"; string msga = "# MIRA tuned weights AVERAGED"; vector<int> order; RandomPermutation(corpus.size(), &order); while (lcount <= max_iteration) { lambdas.init_vector(&dense_weights); if ((cur_sent * 40 / corpus.size()) > dots) { ++dots; cerr << '.'; } if (corpus.size() == cur_sent) { cerr << " [AVG METRIC LAST PASS=" << (tot_loss / corpus.size()) << "]\n"; Weights::ShowLargestFeatures(dense_weights); cur_sent = 0; tot_loss = 0; dots = 0; ostringstream os; os << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << ".gz"; SparseVector<double> x = tot; x /= normalizer; ostringstream sa; sa << "weights.mira-pass" << (cur_pass < 10 ? "0" : "") << cur_pass << "-avg.gz"; x.init_vector(&dense_weights); Weights::WriteToFile(os.str(), dense_weights, true, &msg); ++cur_pass; RandomPermutation(corpus.size(), &order); } if (cur_sent == 0) { cerr << "PASS " << (lcount / corpus.size() + 1) << endl; } decoder.SetId(order[cur_sent]); double sc = 1.0; if (sample_forest_unit_weight_vector) { sc = lambdas.l2norm(); if (sc > 0) { for (unsigned i = 0; i < dense_weights.size(); ++i) dense_weights[i] /= sc; } } decoder.Decode(corpus[order[cur_sent]], &observer); // update oracles if (sc && sc != 1.0) { for (unsigned i = 0; i < dense_weights.size(); ++i) dense_weights[i] *= sc; } const HypothesisInfo& cur_hyp = observer.GetCurrentBestHypothesis(); const HypothesisInfo& cur_good = *oracles[order[cur_sent]].good; const HypothesisInfo& cur_bad = *oracles[order[cur_sent]].bad; tot_loss += cur_hyp.mt_metric; if (!ApproxEqual(cur_hyp.mt_metric, cur_good.mt_metric)) { const double loss = cur_bad.features.dot(dense_weights) - cur_good.features.dot(dense_weights) + mt_metric_scale * (cur_good.mt_metric - cur_bad.mt_metric); //cerr << "LOSS: " << loss << endl; if (loss > 0.0) { SparseVector<double> diff = cur_good.features; diff -= cur_bad.features; double step_size = loss / diff.l2norm_sq(); //cerr << loss << " " << step_size << " " << diff << endl; if (step_size > max_step_size) step_size = max_step_size; lambdas += (cur_good.features * step_size); lambdas -= (cur_bad.features * step_size); //cerr << "L: " << lambdas << endl; } } tot += lambdas; ++normalizer; ++lcount; ++cur_sent; } cerr << endl; Weights::WriteToFile("weights.mira-final.gz", dense_weights, true, &msg); tot /= normalizer; tot.init_vector(dense_weights); msg = "# MIRA tuned weights (averaged vector)"; Weights::WriteToFile("weights.mira-final-avg.gz", dense_weights, true, &msg); cerr << "Optimization complete.\nAVERAGED WEIGHTS: weights.mira-final-avg.gz\n"; return 0; } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gsiconv.cxx,v $ * * $Revision: 1.4 $ * * last change: $Author: rt $ $Date: 2005-09-09 15:00:09 $ * * 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 <stdio.h> #include <tools/fsys.hxx> #include <tools/stream.hxx> // local includes #include "utf8conv.hxx" #define GSI_FILE_UNKNOWN 0x0000 #define GSI_FILE_OLDSTYLE 0x0001 #define GSI_FILE_L10NFRAMEWORK 0x0002 /*****************************************************************************/ USHORT GetGSIFileType( SvStream &rStream ) /*****************************************************************************/ { USHORT nFileType = GSI_FILE_UNKNOWN; ULONG nPos( rStream.Tell()); rStream.Seek( STREAM_SEEK_TO_BEGIN ); ByteString sLine; while( !rStream.IsEof() && !sLine.Len()) rStream.ReadLine( sLine ); if( sLine.Len()) { if( sLine.Search( "($$)" ) != STRING_NOTFOUND ) nFileType = GSI_FILE_OLDSTYLE; else nFileType = GSI_FILE_L10NFRAMEWORK; } rStream.Seek( nPos ); return nFileType; } /*****************************************************************************/ ByteString GetGSILineId( const ByteString &rLine, USHORT nFileType ) /*****************************************************************************/ { ByteString sId; switch ( nFileType ) { case GSI_FILE_OLDSTYLE: sId = rLine; sId.SearchAndReplaceAll( "($$)", "\t" ); sId = sId.GetToken( 0, '\t' ); break; case GSI_FILE_L10NFRAMEWORK: sId = rLine.GetToken( 0, '\t' ); sId += "\t"; sId += rLine.GetToken( 1, '\t' ); sId += "\t"; sId += rLine.GetToken( 4, '\t' ); sId += "\t"; sId += rLine.GetToken( 5, '\t' ); break; } return sId; } /*****************************************************************************/ ByteString GetGSILineLangId( const ByteString &rLine, USHORT nFileType ) /*****************************************************************************/ { ByteString sLangId; switch ( nFileType ) { case GSI_FILE_OLDSTYLE: sLangId = rLine; sLangId.SearchAndReplaceAll( "($$)", "\t" ); sLangId = sLangId.GetToken( 2, '\t' ); break; case GSI_FILE_L10NFRAMEWORK: sLangId = rLine.GetToken( 9, '\t' ); break; } return sLangId; } /*****************************************************************************/ void ConvertGSILine( BOOL bToUTF8, ByteString &rLine, rtl_TextEncoding nEncoding, USHORT nFileType ) /*****************************************************************************/ { switch ( nFileType ) { case GSI_FILE_OLDSTYLE: if ( bToUTF8 ) rLine = UTF8Converter::ConvertToUTF8( rLine, nEncoding ); else rLine = UTF8Converter::ConvertFromUTF8( rLine, nEncoding ); break; case GSI_FILE_L10NFRAMEWORK: { ByteString sConverted; for ( USHORT i = 0; i < rLine.GetTokenCount( '\t' ); i++ ) { ByteString sToken = rLine.GetToken( i, '\t' ); if (( i > 9 ) && ( i < 14 )) { if( bToUTF8 ) sToken = UTF8Converter::ConvertToUTF8( sToken, nEncoding ); else sToken = UTF8Converter::ConvertFromUTF8( sToken, nEncoding ); } if ( i ) sConverted += "\t"; sConverted += sToken; } rLine = sConverted; } break; } } /*****************************************************************************/ void Help() /*****************************************************************************/ { fprintf( stdout, "\n" ); fprintf( stdout, "gsiconv (c)1999 by StarOffice Entwicklungs GmbH\n" ); fprintf( stdout, "===============================================\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "gsiconv converts strings in GSI-Files (Gutschmitt Interface) from or to UTF-8\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Syntax: gsiconv (-t|-f langid charset)|(-p n) filename\n" ); fprintf( stdout, "Switches: -t => conversion from charset to UTF-8\n" ); fprintf( stdout, " -f => conversion from UTF-8 to charset\n" ); fprintf( stdout, " -p n => creates several files with ca. n lines\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Allowed charsets:\n" ); fprintf( stdout, " MS_932 => Japanese\n" ); fprintf( stdout, " MS_936 => Chinese Simplified\n" ); fprintf( stdout, " MS_949 => Korean\n" ); fprintf( stdout, " MS_950 => Chinese Traditional\n" ); fprintf( stdout, " MS_1250 => East Europe\n" ); fprintf( stdout, " MS_1251 => Cyrillic\n" ); fprintf( stdout, " MS_1252 => West Europe\n" ); fprintf( stdout, " MS_1253 => Greek\n" ); fprintf( stdout, " MS_1254 => Turkish\n" ); fprintf( stdout, " MS_1255 => Hebrew\n" ); fprintf( stdout, " MS_1256 => Arabic\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Allowed langids:\n" ); fprintf( stdout, " 1 => ENGLISH_US\n" ); fprintf( stdout, " 3 => PORTUGUESE \n" ); fprintf( stdout, " 4 => GERMAN_DE (new german style)\n" ); fprintf( stdout, " 7 => RUSSIAN\n" ); fprintf( stdout, " 30 => GREEK\n" ); fprintf( stdout, " 31 => DUTCH\n" ); fprintf( stdout, " 33 => FRENCH\n" ); fprintf( stdout, " 34 => SPANISH\n" ); fprintf( stdout, " 35 => FINNISH\n" ); fprintf( stdout, " 36 => HUNGARIAN\n" ); fprintf( stdout, " 39 => ITALIAN\n" ); fprintf( stdout, " 42 => CZECH\n" ); fprintf( stdout, " 44 => ENGLISH (UK)\n" ); fprintf( stdout, " 45 => DANISH\n" ); fprintf( stdout, " 46 => SWEDISH\n" ); fprintf( stdout, " 47 => NORWEGIAN\n" ); fprintf( stdout, " 49 => GERMAN (old german style)\n" ); fprintf( stdout, " 55 => PORTUGUESE_BRAZILIAN\n" ); fprintf( stdout, " 81 => JAPANESE\n" ); fprintf( stdout, " 82 => KOREAN\n" ); fprintf( stdout, " 86 => CHINESE_SIMPLIFIED\n" ); fprintf( stdout, " 88 => CHINESE_TRADITIONAL\n" ); fprintf( stdout, " 90 => TURKISH\n" ); fprintf( stdout, " 96 => ARABIC\n" ); fprintf( stdout, " 97 => HEBREW\n" ); fprintf( stdout, "\n" ); } /*****************************************************************************/ #if defined( UNX ) || defined( MAC ) int main( int argc, char *argv[] ) #else int _cdecl main( int argc, char *argv[] ) #endif /*****************************************************************************/ { if (( argc != 5 ) && ( argc != 4 )) { Help(); exit ( 0 ); } if ( argc == 4 ) { if ( ByteString( argv[ 1 ] ) == "-p" ) { DirEntry aSource = DirEntry( String( argv[ 3 ], RTL_TEXTENCODING_ASCII_US )); if ( !aSource.Exists()) { fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 2 ); } DirEntry aOutput( aSource ); String sBase = aOutput.GetBase(); String sExt = aOutput.GetExtension(); String sGSI( argv[ 3 ], RTL_TEXTENCODING_ASCII_US ); SvFileStream aGSI( sGSI, STREAM_STD_READ ); if ( !aGSI.IsOpen()) { fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 3 ); } USHORT nFileType( GetGSIFileType( aGSI )); ULONG nMaxLines = (ULONG) ByteString( argv[ 2 ] ).ToInt64(); if ( !nMaxLines ) { fprintf( stderr, "\nERROR: Linecount must be at least 1!\n\n" ); exit ( 3 ); } ByteString sGSILine; ByteString sOldId; ULONG nLine = 0; ULONG nOutputFile = 1; String sOutput( sBase ); sOutput += String( "_", RTL_TEXTENCODING_ASCII_US ); sOutput += String::CreateFromInt64( nOutputFile ); if ( sExt.Len()) { sOutput += String( ".", RTL_TEXTENCODING_ASCII_US ); sOutput += sExt; } nOutputFile ++; aOutput.SetName( sOutput ); SvFileStream aOutputStream( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); while ( !aGSI.IsEof()) { aGSI.ReadLine( sGSILine ); ByteString sId( GetGSILineId( sGSILine, nFileType )); nLine++; if (( nLine >= nMaxLines ) && ( sId != sOldId )) { aOutputStream.Close(); ByteString sText( aOutput.GetFull(), gsl_getSystemTextEncoding()); sText += " with "; sText += ByteString::CreateFromInt64( nLine ); sText += " lines written."; fprintf( stdout, "%s\n", sText.GetBuffer()); String sOutput( sBase ); sOutput += String( "_", RTL_TEXTENCODING_ASCII_US ); sOutput += String::CreateFromInt64( nOutputFile ); if ( sExt.Len()) { sOutput += String( ".", RTL_TEXTENCODING_ASCII_US ); sOutput += sExt; } nOutputFile ++; aOutput.SetName( sOutput ); aOutputStream.Open( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); nLine = 0; } aOutputStream.WriteLine( sGSILine ); sOldId = sId; } aGSI.Close(); aOutputStream.Close(); ByteString sText( aOutput.GetFull(), RTL_TEXTENCODING_ASCII_US ); sText += " with "; sText += ByteString::CreateFromInt64( nLine ); sText += " lines written."; } else { Help(); exit( 1 ); } } else { if ( ByteString( argv[ 1 ] ) == "-t" || ByteString( argv[ 1 ] ) == "-f" ) { rtl_TextEncoding nEncoding; ByteString sCurLangId( argv[ 2 ] ); ByteString sCharset( argv[ 3 ] ); sCharset.ToUpperAscii(); if ( sCharset == "MS_932" ) nEncoding = RTL_TEXTENCODING_MS_932; else if ( sCharset == "MS_936" ) nEncoding = RTL_TEXTENCODING_MS_936; else if ( sCharset == "MS_949" ) nEncoding = RTL_TEXTENCODING_MS_949; else if ( sCharset == "MS_950" ) nEncoding = RTL_TEXTENCODING_MS_950; else if ( sCharset == "MS_1250" ) nEncoding = RTL_TEXTENCODING_MS_1250; else if ( sCharset == "MS_1251" ) nEncoding = RTL_TEXTENCODING_MS_1251; else if ( sCharset == "MS_1252" ) nEncoding = RTL_TEXTENCODING_MS_1252; else if ( sCharset == "MS_1253" ) nEncoding = RTL_TEXTENCODING_MS_1253; else if ( sCharset == "MS_1254" ) nEncoding = RTL_TEXTENCODING_MS_1254; else if ( sCharset == "MS_1255" ) nEncoding = RTL_TEXTENCODING_MS_1255; else if ( sCharset == "MS_1256" ) nEncoding = RTL_TEXTENCODING_MS_1256; else if ( sCharset == "MS_1257" ) nEncoding = RTL_TEXTENCODING_MS_1257; else if ( sCharset == "UTF8" ) nEncoding = RTL_TEXTENCODING_UTF8; else { Help(); exit ( 1 ); } DirEntry aSource = DirEntry( String( argv[ 4 ], RTL_TEXTENCODING_ASCII_US )); if ( !aSource.Exists()) { fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 2 ); } String sGSI( argv[ 4 ], RTL_TEXTENCODING_ASCII_US ); SvFileStream aGSI( sGSI, STREAM_STD_READ ); if ( !aGSI.IsOpen()) { fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 3 ); } USHORT nFileType( GetGSIFileType( aGSI )); ByteString sGSILine; while ( !aGSI.IsEof()) { aGSI.ReadLine( sGSILine ); ByteString sLangId( GetGSILineLangId( sGSILine, nFileType )); if ( sLangId == sCurLangId ) ConvertGSILine(( ByteString( argv[ 1 ] ) == "-t" ), sGSILine, nEncoding, nFileType ); fprintf( stdout, "%s\n", sGSILine.GetBuffer()); } aGSI.Close(); } else { Help(); exit( 1 ); } } return 0; } <commit_msg>INTEGRATION: CWS warnings01 (1.4.16); FILE MERGED 2005/11/07 12:46:42 ihi 1.4.16.1: #i57362# Remove warnings<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gsiconv.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: hr $ $Date: 2006-06-19 17:22:22 $ * * 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 <stdio.h> #include <tools/fsys.hxx> #include <tools/stream.hxx> // local includes #include "utf8conv.hxx" #define GSI_FILE_UNKNOWN 0x0000 #define GSI_FILE_OLDSTYLE 0x0001 #define GSI_FILE_L10NFRAMEWORK 0x0002 /*****************************************************************************/ USHORT GetGSIFileType( SvStream &rStream ) /*****************************************************************************/ { USHORT nFileType = GSI_FILE_UNKNOWN; ULONG nPos( rStream.Tell()); rStream.Seek( STREAM_SEEK_TO_BEGIN ); ByteString sLine; while( !rStream.IsEof() && !sLine.Len()) rStream.ReadLine( sLine ); if( sLine.Len()) { if( sLine.Search( "($$)" ) != STRING_NOTFOUND ) nFileType = GSI_FILE_OLDSTYLE; else nFileType = GSI_FILE_L10NFRAMEWORK; } rStream.Seek( nPos ); return nFileType; } /*****************************************************************************/ ByteString GetGSILineId( const ByteString &rLine, USHORT nFileType ) /*****************************************************************************/ { ByteString sId; switch ( nFileType ) { case GSI_FILE_OLDSTYLE: sId = rLine; sId.SearchAndReplaceAll( "($$)", "\t" ); sId = sId.GetToken( 0, '\t' ); break; case GSI_FILE_L10NFRAMEWORK: sId = rLine.GetToken( 0, '\t' ); sId += "\t"; sId += rLine.GetToken( 1, '\t' ); sId += "\t"; sId += rLine.GetToken( 4, '\t' ); sId += "\t"; sId += rLine.GetToken( 5, '\t' ); break; } return sId; } /*****************************************************************************/ ByteString GetGSILineLangId( const ByteString &rLine, USHORT nFileType ) /*****************************************************************************/ { ByteString sLangId; switch ( nFileType ) { case GSI_FILE_OLDSTYLE: sLangId = rLine; sLangId.SearchAndReplaceAll( "($$)", "\t" ); sLangId = sLangId.GetToken( 2, '\t' ); break; case GSI_FILE_L10NFRAMEWORK: sLangId = rLine.GetToken( 9, '\t' ); break; } return sLangId; } /*****************************************************************************/ void ConvertGSILine( BOOL bToUTF8, ByteString &rLine, rtl_TextEncoding nEncoding, USHORT nFileType ) /*****************************************************************************/ { switch ( nFileType ) { case GSI_FILE_OLDSTYLE: if ( bToUTF8 ) rLine = UTF8Converter::ConvertToUTF8( rLine, nEncoding ); else rLine = UTF8Converter::ConvertFromUTF8( rLine, nEncoding ); break; case GSI_FILE_L10NFRAMEWORK: { ByteString sConverted; for ( USHORT i = 0; i < rLine.GetTokenCount( '\t' ); i++ ) { ByteString sToken = rLine.GetToken( i, '\t' ); if (( i > 9 ) && ( i < 14 )) { if( bToUTF8 ) sToken = UTF8Converter::ConvertToUTF8( sToken, nEncoding ); else sToken = UTF8Converter::ConvertFromUTF8( sToken, nEncoding ); } if ( i ) sConverted += "\t"; sConverted += sToken; } rLine = sConverted; } break; } } /*****************************************************************************/ void Help() /*****************************************************************************/ { fprintf( stdout, "\n" ); fprintf( stdout, "gsiconv (c)1999 by StarOffice Entwicklungs GmbH\n" ); fprintf( stdout, "===============================================\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "gsiconv converts strings in GSI-Files (Gutschmitt Interface) from or to UTF-8\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Syntax: gsiconv (-t|-f langid charset)|(-p n) filename\n" ); fprintf( stdout, "Switches: -t => conversion from charset to UTF-8\n" ); fprintf( stdout, " -f => conversion from UTF-8 to charset\n" ); fprintf( stdout, " -p n => creates several files with ca. n lines\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Allowed charsets:\n" ); fprintf( stdout, " MS_932 => Japanese\n" ); fprintf( stdout, " MS_936 => Chinese Simplified\n" ); fprintf( stdout, " MS_949 => Korean\n" ); fprintf( stdout, " MS_950 => Chinese Traditional\n" ); fprintf( stdout, " MS_1250 => East Europe\n" ); fprintf( stdout, " MS_1251 => Cyrillic\n" ); fprintf( stdout, " MS_1252 => West Europe\n" ); fprintf( stdout, " MS_1253 => Greek\n" ); fprintf( stdout, " MS_1254 => Turkish\n" ); fprintf( stdout, " MS_1255 => Hebrew\n" ); fprintf( stdout, " MS_1256 => Arabic\n" ); fprintf( stdout, "\n" ); fprintf( stdout, "Allowed langids:\n" ); fprintf( stdout, " 1 => ENGLISH_US\n" ); fprintf( stdout, " 3 => PORTUGUESE \n" ); fprintf( stdout, " 4 => GERMAN_DE (new german style)\n" ); fprintf( stdout, " 7 => RUSSIAN\n" ); fprintf( stdout, " 30 => GREEK\n" ); fprintf( stdout, " 31 => DUTCH\n" ); fprintf( stdout, " 33 => FRENCH\n" ); fprintf( stdout, " 34 => SPANISH\n" ); fprintf( stdout, " 35 => FINNISH\n" ); fprintf( stdout, " 36 => HUNGARIAN\n" ); fprintf( stdout, " 39 => ITALIAN\n" ); fprintf( stdout, " 42 => CZECH\n" ); fprintf( stdout, " 44 => ENGLISH (UK)\n" ); fprintf( stdout, " 45 => DANISH\n" ); fprintf( stdout, " 46 => SWEDISH\n" ); fprintf( stdout, " 47 => NORWEGIAN\n" ); fprintf( stdout, " 49 => GERMAN (old german style)\n" ); fprintf( stdout, " 55 => PORTUGUESE_BRAZILIAN\n" ); fprintf( stdout, " 81 => JAPANESE\n" ); fprintf( stdout, " 82 => KOREAN\n" ); fprintf( stdout, " 86 => CHINESE_SIMPLIFIED\n" ); fprintf( stdout, " 88 => CHINESE_TRADITIONAL\n" ); fprintf( stdout, " 90 => TURKISH\n" ); fprintf( stdout, " 96 => ARABIC\n" ); fprintf( stdout, " 97 => HEBREW\n" ); fprintf( stdout, "\n" ); } /*****************************************************************************/ #if defined( UNX ) || defined( MAC ) int main( int argc, char *argv[] ) #else int _cdecl main( int argc, char *argv[] ) #endif /*****************************************************************************/ { if (( argc != 5 ) && ( argc != 4 )) { Help(); exit ( 0 ); } if ( argc == 4 ) { if ( ByteString( argv[ 1 ] ) == "-p" ) { DirEntry aSource = DirEntry( String( argv[ 3 ], RTL_TEXTENCODING_ASCII_US )); if ( !aSource.Exists()) { fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 2 ); } DirEntry aOutput( aSource ); String sBase = aOutput.GetBase(); String sExt = aOutput.GetExtension(); String sGSI( argv[ 3 ], RTL_TEXTENCODING_ASCII_US ); SvFileStream aGSI( sGSI, STREAM_STD_READ ); if ( !aGSI.IsOpen()) { fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 3 ); } USHORT nFileType( GetGSIFileType( aGSI )); ULONG nMaxLines = (ULONG) ByteString( argv[ 2 ] ).ToInt64(); if ( !nMaxLines ) { fprintf( stderr, "\nERROR: Linecount must be at least 1!\n\n" ); exit ( 3 ); } ByteString sGSILine; ByteString sOldId; ULONG nLine = 0; ULONG nOutputFile = 1; String sOutput( sBase ); sOutput += String( "_", RTL_TEXTENCODING_ASCII_US ); sOutput += String::CreateFromInt64( nOutputFile ); if ( sExt.Len()) { sOutput += String( ".", RTL_TEXTENCODING_ASCII_US ); sOutput += sExt; } nOutputFile ++; aOutput.SetName( sOutput ); SvFileStream aOutputStream( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); while ( !aGSI.IsEof()) { aGSI.ReadLine( sGSILine ); ByteString sId( GetGSILineId( sGSILine, nFileType )); nLine++; if (( nLine >= nMaxLines ) && ( sId != sOldId )) { aOutputStream.Close(); ByteString sText( aOutput.GetFull(), gsl_getSystemTextEncoding()); sText += " with "; sText += ByteString::CreateFromInt64( nLine ); sText += " lines written."; fprintf( stdout, "%s\n", sText.GetBuffer()); String sOutput1( sBase ); sOutput1 += String( "_", RTL_TEXTENCODING_ASCII_US ); sOutput1 += String::CreateFromInt64( nOutputFile ); if ( sExt.Len()) { sOutput1 += String( ".", RTL_TEXTENCODING_ASCII_US ); sOutput1 += sExt; } nOutputFile ++; aOutput.SetName( sOutput1 ); aOutputStream.Open( aOutput.GetFull(), STREAM_STD_WRITE | STREAM_TRUNC ); nLine = 0; } aOutputStream.WriteLine( sGSILine ); sOldId = sId; } aGSI.Close(); aOutputStream.Close(); ByteString sText( aOutput.GetFull(), RTL_TEXTENCODING_ASCII_US ); sText += " with "; sText += ByteString::CreateFromInt64( nLine ); sText += " lines written."; } else { Help(); exit( 1 ); } } else { if ( ByteString( argv[ 1 ] ) == "-t" || ByteString( argv[ 1 ] ) == "-f" ) { rtl_TextEncoding nEncoding; ByteString sCurLangId( argv[ 2 ] ); ByteString sCharset( argv[ 3 ] ); sCharset.ToUpperAscii(); if ( sCharset == "MS_932" ) nEncoding = RTL_TEXTENCODING_MS_932; else if ( sCharset == "MS_936" ) nEncoding = RTL_TEXTENCODING_MS_936; else if ( sCharset == "MS_949" ) nEncoding = RTL_TEXTENCODING_MS_949; else if ( sCharset == "MS_950" ) nEncoding = RTL_TEXTENCODING_MS_950; else if ( sCharset == "MS_1250" ) nEncoding = RTL_TEXTENCODING_MS_1250; else if ( sCharset == "MS_1251" ) nEncoding = RTL_TEXTENCODING_MS_1251; else if ( sCharset == "MS_1252" ) nEncoding = RTL_TEXTENCODING_MS_1252; else if ( sCharset == "MS_1253" ) nEncoding = RTL_TEXTENCODING_MS_1253; else if ( sCharset == "MS_1254" ) nEncoding = RTL_TEXTENCODING_MS_1254; else if ( sCharset == "MS_1255" ) nEncoding = RTL_TEXTENCODING_MS_1255; else if ( sCharset == "MS_1256" ) nEncoding = RTL_TEXTENCODING_MS_1256; else if ( sCharset == "MS_1257" ) nEncoding = RTL_TEXTENCODING_MS_1257; else if ( sCharset == "UTF8" ) nEncoding = RTL_TEXTENCODING_UTF8; else { Help(); exit ( 1 ); } DirEntry aSource = DirEntry( String( argv[ 4 ], RTL_TEXTENCODING_ASCII_US )); if ( !aSource.Exists()) { fprintf( stderr, "\nERROR: GSI-File %s not found!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 2 ); } String sGSI( argv[ 4 ], RTL_TEXTENCODING_ASCII_US ); SvFileStream aGSI( sGSI, STREAM_STD_READ ); if ( !aGSI.IsOpen()) { fprintf( stderr, "\nERROR: Could not open GSI-File %s!\n\n", ByteString( argv[ 3 ] ).GetBuffer()); exit ( 3 ); } USHORT nFileType( GetGSIFileType( aGSI )); ByteString sGSILine; while ( !aGSI.IsEof()) { aGSI.ReadLine( sGSILine ); ByteString sLangId( GetGSILineLangId( sGSILine, nFileType )); if ( sLangId == sCurLangId ) ConvertGSILine(( ByteString( argv[ 1 ] ) == "-t" ), sGSILine, nEncoding, nFileType ); fprintf( stdout, "%s\n", sGSILine.GetBuffer()); } aGSI.Close(); } else { Help(); exit( 1 ); } } return 0; } <|endoftext|>
<commit_before>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef WIN32 #include "win32-dirent.h" #else #include <dirent.h> #endif /** WIN32 */ #include <time.h> #include "Preset.hpp" #include "Parser.hpp" #include "ParamUtils.hpp" #include "InitCondUtils.hpp" #include "fatal.h" #include <iostream> Preset::Preset(const std::string & filename, const PresetInputs & presetInputs, PresetOutputs & presetOutputs): builtinParams(presetInputs, presetOutputs), file_path(filename), m_presetOutputs(presetOutputs) { clearMeshChecks(); initialize(filename); } Preset::~Preset() { Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<InitCond> >(init_cond_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<InitCond> >(per_frame_init_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<PerPixelEqn> >(per_pixel_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<PerFrameEqn> >(per_frame_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<Param> >(user_param_tree); for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { delete(*pos); } for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { delete(*pos); } } /* Adds a per pixel equation according to its string name. This will be used only by the parser */ int Preset::add_per_pixel_eqn(char * name, GenExpr * gen_expr) { PerPixelEqn * per_pixel_eqn = NULL; int index; Param * param = NULL; assert(gen_expr); assert(name); if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: per pixel equation (name = \"%s\")\n", name); if (!strncmp(name, "dx", strlen("dx"))) this->m_presetOutputs.dx_is_mesh = true; else if (!strncmp(name, "dy", strlen("dy"))) this->m_presetOutputs.dy_is_mesh = true; else if (!strncmp(name, "cx", strlen("cx"))) this->m_presetOutputs.cx_is_mesh = true; else if (!strncmp(name, "cy", strlen("cy"))) this->m_presetOutputs.cy_is_mesh = true; else if (!strncmp(name, "zoom", strlen("zoom"))) this->m_presetOutputs.zoom_is_mesh = true; else if (!strncmp(name, "zoomexp", strlen("zoomexp"))) this->m_presetOutputs.zoomexp_is_mesh = true; else if (!strncmp(name, "rot", strlen("rot"))) this->m_presetOutputs.rot_is_mesh= true; else if (!strncmp(name, "sx", strlen("sx"))) this->m_presetOutputs.sx_is_mesh = true; else if (!strncmp(name, "sy", strlen("sy"))) this->m_presetOutputs.sy_is_mesh = true; /* Search for the parameter so we know what matrix the per pixel equation is referencing */ param = ParamUtils::find(name, &this->builtinParams, &this->user_param_tree); if ( !param ) { if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: failed to allocate a new parameter!\n"); return PROJECTM_FAILURE; } index = per_pixel_eqn_tree.size(); /* Create the per pixel equation given the index, parameter, and general expression */ if ((per_pixel_eqn = new PerPixelEqn(index, param, gen_expr)) == NULL) { if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: failed to create new per pixel equation!\n"); return PROJECTM_FAILURE; } /* Insert the per pixel equation into the preset per pixel database */ std::pair<std::map<int, PerPixelEqn*>::iterator, bool> inserteeOption = per_pixel_eqn_tree.insert (std::make_pair(per_pixel_eqn->index, per_pixel_eqn)); if (!inserteeOption.second) { printf("failed to add per pixel eqn!\n"); delete(per_pixel_eqn); return PROJECTM_FAILURE; } /* Done */ return PROJECTM_SUCCESS; } void Preset::evalCustomShapeInitConditions() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { assert(*pos); (*pos)->evalInitConds(); } } void Preset::evalCustomWaveInitConditions() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { assert(*pos); (*pos)->evalInitConds(); } } void Preset::evalCustomWavePerFrameEquations() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { std::map<std::string, InitCond*> & init_cond_tree = (*pos)->init_cond_tree; for (std::map<std::string, InitCond*>::iterator _pos = init_cond_tree.begin(); _pos != init_cond_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } std::map<int, PerFrameEqn*> & per_frame_eqn_tree = (*pos)->per_frame_eqn_tree; for (std::map<int, PerFrameEqn*>::iterator _pos = per_frame_eqn_tree.begin(); _pos != per_frame_eqn_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } } } void Preset::evalCustomShapePerFrameEquations() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { std::map<std::string, InitCond*> & init_cond_tree = (*pos)->init_cond_tree; for (std::map<std::string, InitCond*>::iterator _pos = init_cond_tree.begin(); _pos != init_cond_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } std::map<int, PerFrameEqn*> & per_frame_eqn_tree = (*pos)->per_frame_eqn_tree; for (std::map<int, PerFrameEqn*>::iterator _pos = per_frame_eqn_tree.begin(); _pos != per_frame_eqn_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } } } void Preset::evalPerFrameInitEquations() { for (std::map<std::string, InitCond*>::iterator pos = per_frame_init_eqn_tree.begin(); pos != per_frame_init_eqn_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } } void Preset::evalPerFrameEquations() { for (std::map<std::string, InitCond*>::iterator pos = init_cond_tree.begin(); pos != init_cond_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } for (std::map<int, PerFrameEqn*>::iterator pos = per_frame_eqn_tree.begin(); pos != per_frame_eqn_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } } void Preset::initialize(const std::string & pathname) { // Clear equation trees /// @slow unnecessary if we ensure this method is private init_cond_tree.clear(); user_param_tree.clear(); per_frame_eqn_tree.clear(); per_pixel_eqn_tree.clear(); per_frame_init_eqn_tree.clear(); /* Set initial index values */ this->per_pixel_eqn_string_index = 0; this->per_frame_eqn_string_index = 0; this->per_frame_init_eqn_string_index = 0; /* Clear string buffers */ /// @bug replace with ostringstream? memset(this->per_pixel_eqn_string_buffer, 0, STRING_BUFFER_SIZE); memset(this->per_frame_eqn_string_buffer, 0, STRING_BUFFER_SIZE); memset(this->per_frame_init_eqn_string_buffer, 0, STRING_BUFFER_SIZE); int retval; std::cerr << "[Preset] loading file \"" << pathname << "\"..." << std::endl; if ((retval = loadPresetFile(pathname)) < 0) { std::cerr << "[Preset] failed to load file \"" << pathname << "\"!" << std::endl; /// @bug how should we handle this problem? a well define exception? throw retval; } /* It's kind of ugly to reset these values here. Should definitely be placed in the parser somewhere */ this->per_frame_eqn_count = 0; this->per_frame_init_eqn_count = 0; this->loadBuiltinParamsUnspecInitConds(); this->loadCustomWaveUnspecInitConds(); this->loadCustomShapeUnspecInitConds(); } void Preset::loadBuiltinParamsUnspecInitConds() { InitCondUtils::LoadUnspecInitCond loadUnspecInitCond(this->init_cond_tree, this->per_frame_init_eqn_tree); this->builtinParams.traverse(loadUnspecInitCond); } void Preset::loadCustomWaveUnspecInitConds() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { assert(*pos); (*pos)->loadUnspecInitConds(); } } void Preset::loadCustomShapeUnspecInitConds() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { assert(*pos); (*pos)->loadUnspecInitConds(); } } void Preset::evaluateFrame() { /* Evaluate all equation objects in same order as the renderer */ evalPerFrameInitEquations(); evalPerFrameEquations(); evalPerPixelEqns(); evalCustomWaveInitConditions(); evalCustomShapeInitConditions(); evalCustomWavePerFrameEquations(); evalCustomShapePerFrameEquations(); // Setup pointers of the custom waves and shapes to the preset outputs instance /// @slow an extra O(N) per frame, could do this during eval m_presetOutputs.customWaves = PresetOutputs::cwave_container(customWaves); m_presetOutputs.customShapes = PresetOutputs::cshape_container(customShapes); } // Evaluates all per-pixel equations void Preset::evalPerPixelEqns() { /* Evaluate all per pixel equations in the tree datastructure */ for (std::map<int, PerPixelEqn*>::iterator pos = per_pixel_eqn_tree.begin(); pos != per_pixel_eqn_tree.end(); ++pos) pos->second->evaluate(); } /* loadPresetFile: private function that loads a specific preset denoted by the given pathname */ int Preset::loadPresetFile(std::string pathname) { FILE * fs; int retval; int lineno; line_mode_t line_mode; /* Open the file corresponding to pathname */ if ((fs = fopen(pathname.c_str(), "rb")) == 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: loading of file %s failed!\n", pathname); #endif return PROJECTM_ERROR; } #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: file stream \"%s\" opened successfully\n", pathname); #endif /* Parse any comments */ if (Parser::parse_top_comment(fs) < 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: no left bracket found...\n"); #endif fclose(fs); return PROJECTM_FAILURE; } /* Parse the preset name and a left bracket */ char tmp_name[MAX_TOKEN_SIZE]; if (Parser::parse_preset_name(fs, tmp_name) < 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: loading of preset name in file \"%s\" failed\n", pathname); #endif fclose(fs); return PROJECTM_ERROR; } name = std::string(tmp_name); #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: preset \"%s\" parsed\n", this->name); #endif /* Parse each line until end of file */ lineno = 0; #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: beginning line parsing...\n"); #endif while ((retval = Parser::parse_line(fs, this)) != EOF) { if (retval == PROJECTM_PARSE_ERROR) { line_mode = NORMAL_LINE_MODE; #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: parse error in file \"%s\": line %d\n", pathname,lineno); #endif } lineno++; } #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE("loadPresetFile: finished line parsing successfully\n"); #endif /* Now the preset has been loaded. Evaluation calls can be made at appropiate times in the frame loop */ fclose(fs); #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE("loadPresetFile: file \"%s\" closed, preset ready\n", pathname); #endif return PROJECTM_SUCCESS; } <commit_msg>clearing the preset outputs struct now in preset init<commit_after>/** * projectM -- Milkdrop-esque visualisation SDK * Copyright (C)2003-2004 projectM Team * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * See 'LICENSE.txt' included within this release * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #ifdef WIN32 #include "win32-dirent.h" #else #include <dirent.h> #endif /** WIN32 */ #include <time.h> #include "Preset.hpp" #include "Parser.hpp" #include "ParamUtils.hpp" #include "InitCondUtils.hpp" #include "fatal.h" #include <iostream> Preset::Preset(const std::string & filename, const PresetInputs & presetInputs, PresetOutputs & presetOutputs): builtinParams(presetInputs, presetOutputs), file_path(filename), m_presetOutputs(presetOutputs) { m_presetOutputs.customWaves.clear(); m_presetOutputs.customShapes.clear(); clearMeshChecks(); initialize(filename); } Preset::~Preset() { Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<InitCond> >(init_cond_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<InitCond> >(per_frame_init_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<PerPixelEqn> >(per_pixel_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<PerFrameEqn> >(per_frame_eqn_tree); Algorithms::traverse<Algorithms::TraverseFunctors::DeleteFunctor<Param> >(user_param_tree); for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { delete(*pos); } for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { delete(*pos); } } /* Adds a per pixel equation according to its string name. This will be used only by the parser */ int Preset::add_per_pixel_eqn(char * name, GenExpr * gen_expr) { PerPixelEqn * per_pixel_eqn = NULL; int index; Param * param = NULL; assert(gen_expr); assert(name); if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: per pixel equation (name = \"%s\")\n", name); if (!strncmp(name, "dx", strlen("dx"))) this->m_presetOutputs.dx_is_mesh = true; else if (!strncmp(name, "dy", strlen("dy"))) this->m_presetOutputs.dy_is_mesh = true; else if (!strncmp(name, "cx", strlen("cx"))) this->m_presetOutputs.cx_is_mesh = true; else if (!strncmp(name, "cy", strlen("cy"))) this->m_presetOutputs.cy_is_mesh = true; else if (!strncmp(name, "zoom", strlen("zoom"))) this->m_presetOutputs.zoom_is_mesh = true; else if (!strncmp(name, "zoomexp", strlen("zoomexp"))) this->m_presetOutputs.zoomexp_is_mesh = true; else if (!strncmp(name, "rot", strlen("rot"))) this->m_presetOutputs.rot_is_mesh= true; else if (!strncmp(name, "sx", strlen("sx"))) this->m_presetOutputs.sx_is_mesh = true; else if (!strncmp(name, "sy", strlen("sy"))) this->m_presetOutputs.sy_is_mesh = true; /* Search for the parameter so we know what matrix the per pixel equation is referencing */ param = ParamUtils::find(name, &this->builtinParams, &this->user_param_tree); if ( !param ) { if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: failed to allocate a new parameter!\n"); return PROJECTM_FAILURE; } index = per_pixel_eqn_tree.size(); /* Create the per pixel equation given the index, parameter, and general expression */ if ((per_pixel_eqn = new PerPixelEqn(index, param, gen_expr)) == NULL) { if (PER_PIXEL_EQN_DEBUG) printf("add_per_pixel_eqn: failed to create new per pixel equation!\n"); return PROJECTM_FAILURE; } /* Insert the per pixel equation into the preset per pixel database */ std::pair<std::map<int, PerPixelEqn*>::iterator, bool> inserteeOption = per_pixel_eqn_tree.insert (std::make_pair(per_pixel_eqn->index, per_pixel_eqn)); if (!inserteeOption.second) { printf("failed to add per pixel eqn!\n"); delete(per_pixel_eqn); return PROJECTM_FAILURE; } /* Done */ return PROJECTM_SUCCESS; } void Preset::evalCustomShapeInitConditions() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { assert(*pos); (*pos)->evalInitConds(); } } void Preset::evalCustomWaveInitConditions() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { assert(*pos); (*pos)->evalInitConds(); } } void Preset::evalCustomWavePerFrameEquations() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { std::map<std::string, InitCond*> & init_cond_tree = (*pos)->init_cond_tree; for (std::map<std::string, InitCond*>::iterator _pos = init_cond_tree.begin(); _pos != init_cond_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } std::map<int, PerFrameEqn*> & per_frame_eqn_tree = (*pos)->per_frame_eqn_tree; for (std::map<int, PerFrameEqn*>::iterator _pos = per_frame_eqn_tree.begin(); _pos != per_frame_eqn_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } } } void Preset::evalCustomShapePerFrameEquations() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { std::map<std::string, InitCond*> & init_cond_tree = (*pos)->init_cond_tree; for (std::map<std::string, InitCond*>::iterator _pos = init_cond_tree.begin(); _pos != init_cond_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } std::map<int, PerFrameEqn*> & per_frame_eqn_tree = (*pos)->per_frame_eqn_tree; for (std::map<int, PerFrameEqn*>::iterator _pos = per_frame_eqn_tree.begin(); _pos != per_frame_eqn_tree.end(); ++_pos) { assert(_pos->second); _pos->second->evaluate(); } } } void Preset::evalPerFrameInitEquations() { for (std::map<std::string, InitCond*>::iterator pos = per_frame_init_eqn_tree.begin(); pos != per_frame_init_eqn_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } } void Preset::evalPerFrameEquations() { for (std::map<std::string, InitCond*>::iterator pos = init_cond_tree.begin(); pos != init_cond_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } for (std::map<int, PerFrameEqn*>::iterator pos = per_frame_eqn_tree.begin(); pos != per_frame_eqn_tree.end(); ++pos) { assert(pos->second); pos->second->evaluate(); } } void Preset::initialize(const std::string & pathname) { // Clear equation trees /// @slow unnecessary if we ensure this method is private init_cond_tree.clear(); user_param_tree.clear(); per_frame_eqn_tree.clear(); per_pixel_eqn_tree.clear(); per_frame_init_eqn_tree.clear(); /* Set initial index values */ this->per_pixel_eqn_string_index = 0; this->per_frame_eqn_string_index = 0; this->per_frame_init_eqn_string_index = 0; /* Clear string buffers */ /// @bug replace with ostringstream? memset(this->per_pixel_eqn_string_buffer, 0, STRING_BUFFER_SIZE); memset(this->per_frame_eqn_string_buffer, 0, STRING_BUFFER_SIZE); memset(this->per_frame_init_eqn_string_buffer, 0, STRING_BUFFER_SIZE); int retval; std::cerr << "[Preset] loading file \"" << pathname << "\"..." << std::endl; if ((retval = loadPresetFile(pathname)) < 0) { std::cerr << "[Preset] failed to load file \"" << pathname << "\"!" << std::endl; /// @bug how should we handle this problem? a well define exception? throw retval; } /* It's kind of ugly to reset these values here. Should definitely be placed in the parser somewhere */ this->per_frame_eqn_count = 0; this->per_frame_init_eqn_count = 0; this->loadBuiltinParamsUnspecInitConds(); this->loadCustomWaveUnspecInitConds(); this->loadCustomShapeUnspecInitConds(); } void Preset::loadBuiltinParamsUnspecInitConds() { InitCondUtils::LoadUnspecInitCond loadUnspecInitCond(this->init_cond_tree, this->per_frame_init_eqn_tree); this->builtinParams.traverse(loadUnspecInitCond); } void Preset::loadCustomWaveUnspecInitConds() { for (PresetOutputs::cwave_container::iterator pos = customWaves.begin(); pos != customWaves.end(); ++pos) { assert(*pos); (*pos)->loadUnspecInitConds(); } } void Preset::loadCustomShapeUnspecInitConds() { for (PresetOutputs::cshape_container::iterator pos = customShapes.begin(); pos != customShapes.end(); ++pos) { assert(*pos); (*pos)->loadUnspecInitConds(); } } void Preset::evaluateFrame() { /* Evaluate all equation objects in same order as the renderer */ evalPerFrameInitEquations(); evalPerFrameEquations(); evalPerPixelEqns(); evalCustomWaveInitConditions(); evalCustomShapeInitConditions(); evalCustomWavePerFrameEquations(); evalCustomShapePerFrameEquations(); // Setup pointers of the custom waves and shapes to the preset outputs instance /// @slow an extra O(N) per frame, could do this during eval m_presetOutputs.customWaves = PresetOutputs::cwave_container(customWaves); m_presetOutputs.customShapes = PresetOutputs::cshape_container(customShapes); } // Evaluates all per-pixel equations void Preset::evalPerPixelEqns() { /* Evaluate all per pixel equations in the tree datastructure */ for (std::map<int, PerPixelEqn*>::iterator pos = per_pixel_eqn_tree.begin(); pos != per_pixel_eqn_tree.end(); ++pos) pos->second->evaluate(); } /* loadPresetFile: private function that loads a specific preset denoted by the given pathname */ int Preset::loadPresetFile(std::string pathname) { FILE * fs; int retval; int lineno; line_mode_t line_mode; /* Open the file corresponding to pathname */ if ((fs = fopen(pathname.c_str(), "rb")) == 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: loading of file %s failed!\n", pathname); #endif return PROJECTM_ERROR; } #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: file stream \"%s\" opened successfully\n", pathname); #endif /* Parse any comments */ if (Parser::parse_top_comment(fs) < 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: no left bracket found...\n"); #endif fclose(fs); return PROJECTM_FAILURE; } /* Parse the preset name and a left bracket */ char tmp_name[MAX_TOKEN_SIZE]; if (Parser::parse_preset_name(fs, tmp_name) < 0) { #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: loading of preset name in file \"%s\" failed\n", pathname); #endif fclose(fs); return PROJECTM_ERROR; } name = std::string(tmp_name); #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: preset \"%s\" parsed\n", this->name); #endif /* Parse each line until end of file */ lineno = 0; #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: beginning line parsing...\n"); #endif while ((retval = Parser::parse_line(fs, this)) != EOF) { if (retval == PROJECTM_PARSE_ERROR) { line_mode = NORMAL_LINE_MODE; #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE( "loadPresetFile: parse error in file \"%s\": line %d\n", pathname,lineno); #endif } lineno++; } #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE("loadPresetFile: finished line parsing successfully\n"); #endif /* Now the preset has been loaded. Evaluation calls can be made at appropiate times in the frame loop */ fclose(fs); #if defined(PRESET_DEBUG) && defined(DEBUG) DWRITE("loadPresetFile: file \"%s\" closed, preset ready\n", pathname); #endif return PROJECTM_SUCCESS; } <|endoftext|>
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2016 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #if defined(HAVE_CONFIG_H) #include "config/bitcoin-config.h" #endif #include "chainparams.h" #include "clientversion.h" #include "compat.h" #include "rpc/server.h" #include "init.h" #include "noui.h" #include "scheduler.h" #include "util.h" #include "httpserver.h" #include "httprpc.h" #include "utilstrencodings.h" #include <boost/algorithm/string/predicate.hpp> #include <boost/filesystem.hpp> #include <boost/thread.hpp> #include <stdio.h> /* Introduction text for doxygen: */ /*! \mainpage Developer documentation * * \section intro_sec Introduction * * This is the developer documentation of the reference client for an experimental new digital currency called Bitcoin (https://www.bitcoin.org/), * which enables instant payments to anyone, anywhere in the world. Bitcoin uses peer-to-peer technology to operate * with no central authority: managing transactions and issuing money are carried out collectively by the network. * * The software is a community-driven open source project, released under the MIT license. * * \section Navigation * Use the buttons <code>Namespaces</code>, <code>Classes</code> or <code>Files</code> at the top of the page to start navigating the code. */ void WaitForShutdown(boost::thread_group* threadGroup) { bool fShutdown = ShutdownRequested(); // Tell the main threads to shutdown. while (!fShutdown) { MilliSleep(200); fShutdown = ShutdownRequested(); } if (threadGroup) { Interrupt(*threadGroup); threadGroup->join_all(); } } ////////////////////////////////////////////////////////////////////////////// // // Start // bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; CScheduler scheduler; bool fRet = false; // // Parameters // // If Qt is used, parameters/bitcoin.conf are parsed in qt/bitcoin.cpp's main() ParseParameters(argc, argv); // Process help and version before taking care about datadir if (IsArgSet("-?") || IsArgSet("-h") || IsArgSet("-help") || IsArgSet("-version")) { std::string strUsage = strprintf(_("%s Daemon"), _(PACKAGE_NAME)) + " " + _("version") + " " + FormatFullVersion() + "\n"; if (IsArgSet("-version")) { strUsage += FormatParagraph(LicenseInfo()); } else { strUsage += "\n" + _("Usage:") + "\n" + " millcoind [options] " + strprintf(_("Start %s Daemon"), _(PACKAGE_NAME)) + "\n"; strUsage += "\n" + HelpMessage(HMM_BITCOIND); } fprintf(stdout, "%s", strUsage.c_str()); return true; } try { if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified data directory \"%s\" does not exist.\n", GetArg("-datadir", "").c_str()); return false; } try { ReadConfigFile(GetArg("-conf", BITCOIN_CONF_FILENAME)); } catch (const std::exception& e) { fprintf(stderr,"Error reading configuration file: %s\n", e.what()); return false; } // Check for -testnet or -regtest parameter (Params() calls are only valid after this clause) try { SelectParams(ChainNameFromCommandLine()); } catch (const std::exception& e) { fprintf(stderr, "Error: %s\n", e.what()); return false; } // Command-line RPC bool fCommandLine = false; for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "millcoin:")) fCommandLine = true; if (fCommandLine) { fprintf(stderr, "Error: There is no RPC client functionality in millcoind anymore. Use the millcoin-cli utility instead.\n"); exit(EXIT_FAILURE); } // -server defaults to true for bitcoind but not for the GUI so do this here SoftSetBoolArg("-server", true); // Set this early so that parameter interactions go to console InitLogging(); InitParameterInteraction(); if (!AppInitBasicSetup()) { // InitError will have been called with detailed error, which ends up on console exit(1); } if (!AppInitParameterInteraction()) { // InitError will have been called with detailed error, which ends up on console exit(1); } if (!AppInitSanityChecks()) { // InitError will have been called with detailed error, which ends up on console exit(1); } if (GetBoolArg("-daemon", false)) { #if HAVE_DECL_DAEMON fprintf(stdout, "Millcoin server starting\n"); // Daemonize if (daemon(1, 0)) { // don't chdir (1), do close FDs (0) fprintf(stderr, "Error: daemon() failed: %s\n", strerror(errno)); return false; } #else fprintf(stderr, "Error: -daemon is not supported on this operating system\n"); return false; #endif // HAVE_DECL_DAEMON } fRet = AppInitMain(threadGroup, scheduler); } catch (const std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { Interrupt(threadGroup); // threadGroup.join_all(); was left out intentionally here, because we didn't re-test all of // the startup-failure cases to make sure they don't result in a hang due to some // thread-blocking-waiting-for-another-thread-during-startup case } else { WaitForShutdown(&threadGroup); } Shutdown(); return fRet; } int main(int argc, char* argv[]) { SetupEnvironment(); // Connect bitcoind signal handlers noui_connect(); return (AppInit(argc, argv) ? EXIT_SUCCESS : EXIT_FAILURE); } <commit_msg>Delete bitcoind.cpp<commit_after><|endoftext|>
<commit_before>#include "../base/SRC_FIRST.hpp" #include "renderer.hpp" #include "utils.hpp" #include "framebuffer.hpp" #include "renderbuffer.hpp" #include "resource_manager.hpp" #include "internal/opengl.hpp" #include "../base/logging.hpp" namespace yg { namespace gl { const yg::Color Renderer::s_bgColor(192, 192, 192, 255); void Renderer::State::apply(BaseState const * prevBase) { State const * prevState = static_cast<State const *>(prevBase); if (m_frameBuffer) { bool shouldApply = false; if (m_frameBuffer == prevState->m_frameBuffer) { if (m_isDebugging) { std::ostringstream out; out << "equal frameBuffers, "; if (m_frameBuffer) out << m_frameBuffer->id() << ", " << prevState->m_frameBuffer->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } if (m_renderTarget != prevState->m_renderTarget) { if (m_isDebugging) { std::ostringstream out; out << "non-equal renderBuffers, "; if (prevState->m_renderTarget) out << prevState->m_renderTarget->id(); else out << "(null)"; out << " => "; if (m_renderTarget) out << m_renderTarget->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setRenderTarget(m_renderTarget); shouldApply = true; } else { if (m_isDebugging) { std::ostringstream out; out << "equal renderBuffers, "; if (m_renderTarget) out << m_renderTarget->id() << ", " << m_renderTarget->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } } if (m_depthBuffer != prevState->m_depthBuffer) { if (m_isDebugging) { std::ostringstream out; out << "non-equal depthBuffers, "; if (prevState->m_depthBuffer) out << prevState->m_depthBuffer->id(); else out << "(null)"; out << " => "; if (m_depthBuffer) out << m_depthBuffer->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setDepthBuffer(m_depthBuffer); shouldApply = true; } else { if (m_isDebugging) { std::ostringstream out; out << "equal depthBuffers, "; if (m_depthBuffer) out << m_depthBuffer->id() << ", " << m_depthBuffer->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } } } else { if (m_isDebugging) { ostringstream out; out << "non-equal frameBuffers, "; if (prevState->m_frameBuffer) out << prevState->m_frameBuffer->id() << ", "; else out << "(null)"; out << " => "; if (m_frameBuffer) out << m_frameBuffer->id() << ", "; else out << "(null)"; LOG(LINFO, (out.str().c_str())); out.str(""); out << "renderTarget="; if (m_renderTarget) out << m_renderTarget->id(); else out << "(null)"; out << ", depthBuffer="; if (m_depthBuffer) out << m_depthBuffer->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setRenderTarget(m_renderTarget); m_frameBuffer->setDepthBuffer(m_depthBuffer); shouldApply = true; } if (shouldApply) m_frameBuffer->makeCurrent(); } else CHECK(false, ()); } Renderer::Params::Params() : m_isDebugging(false), m_renderQueue(0) {} Renderer::Renderer(Params const & params) : m_isDebugging(params.m_isDebugging), m_isRendering(false) { m_frameBuffer = params.m_frameBuffer; m_resourceManager = params.m_resourceManager; if (m_frameBuffer) { m_renderTarget = m_frameBuffer->renderTarget(); m_depthBuffer = m_frameBuffer->depthBuffer(); } m_renderQueue = params.m_renderQueue; } Renderer::~Renderer() {} shared_ptr<ResourceManager> const & Renderer::resourceManager() const { return m_resourceManager; } void Renderer::beginFrame() { m_isRendering = true; if (m_renderQueue) return; if (m_frameBuffer) m_frameBuffer->makeCurrent(); } bool Renderer::isRendering() const { return m_isRendering; } void Renderer::endFrame() { m_isRendering = false; } shared_ptr<FrameBuffer> const & Renderer::frameBuffer() const { return m_frameBuffer; } shared_ptr<RenderTarget> const & Renderer::renderTarget() const { return m_renderTarget; } void Renderer::setRenderTarget(shared_ptr<RenderTarget> const & rt) { m_renderTarget = rt; if (!m_renderQueue) { m_frameBuffer->setRenderTarget(rt); m_frameBuffer->makeCurrent(); //< to attach renderTarget } } void Renderer::resetRenderTarget() { m_renderTarget.reset(); if (!m_renderQueue) m_frameBuffer->resetRenderTarget(); } shared_ptr<RenderBuffer> const & Renderer::depthBuffer() const { return m_depthBuffer; } void Renderer::setDepthBuffer(shared_ptr<RenderBuffer> const & rt) { m_depthBuffer = rt; if (!m_renderQueue) m_frameBuffer->setDepthBuffer(rt); } void Renderer::resetDepthBuffer() { m_depthBuffer.reset(); if (!m_renderQueue) m_frameBuffer->resetDepthBuffer(); } Renderer::ClearCommand::ClearCommand(yg::Color const & color, bool clearRT, float depth, bool clearDepth) : m_color(color), m_clearRT(clearRT), m_depth(depth), m_clearDepth(clearDepth) {} void Renderer::ClearCommand::perform() { if (isDebugging()) LOG(LINFO, ("performing clear command")); OGLCHECK(glClearColor(m_color.r / 255.0f, m_color.g / 255.0f, m_color.b / 255.0f, m_color.a / 255.0f)); #ifdef OMIM_GL_ES OGLCHECK(glClearDepthf(m_depth)); #else OGLCHECK(glClearDepth(m_depth)); #endif GLbitfield mask = 0; if (m_clearRT) mask |= GL_COLOR_BUFFER_BIT; if (m_clearDepth) mask |= GL_DEPTH_BUFFER_BIT; OGLCHECK(glDepthMask(GL_TRUE)); OGLCHECK(glClear(mask)); } void Renderer::clear(yg::Color const & c, bool clearRT, float depth, bool clearDepth) { shared_ptr<ClearCommand> command(new ClearCommand(c, clearRT, depth, clearDepth)); processCommand(command); } shared_ptr<BaseState> const Renderer::createState() const { return shared_ptr<BaseState>(new State()); } void Renderer::getState(BaseState * baseState) { State * state = static_cast<State *>(baseState); state->m_frameBuffer = m_frameBuffer; state->m_renderTarget = m_renderTarget; state->m_depthBuffer = m_depthBuffer; state->m_resourceManager = m_resourceManager; } void Renderer::FinishCommand::perform() { if (m_isDebugging) LOG(LINFO, ("performing FinishCommand command")); OGLCHECK(glFinish()); } void Renderer::finish() { shared_ptr<Command> command(new FinishCommand()); processCommand(command); } void Renderer::onSize(unsigned int width, unsigned int height) { if (width < 2) width = 2; if (height < 2) height = 2; m_width = width; m_height = height; if (m_frameBuffer) m_frameBuffer->onSize(width, height); } unsigned int Renderer::width() const { return m_width; } unsigned int Renderer::height() const { return m_height; } bool Renderer::isDebugging() const { return m_isDebugging; } void Renderer::processCommand(shared_ptr<Command> const & command, Packet::EType type) { // command->m_isDebugging = false; command->m_isDebugging = renderQueue(); if (renderQueue()) { shared_ptr<BaseState> state = createState(); getState(state.get()); m_renderQueue->processPacket(Packet(state, command, type)); } else command->perform(); } PacketsQueue * Renderer::renderQueue() { return m_renderQueue; } void Renderer::markFrameBoundary() { if (m_renderQueue) m_renderQueue->processPacket(Packet(Packet::ECheckPoint)); } } } <commit_msg>initializing width and height with invalid values.<commit_after>#include "../base/SRC_FIRST.hpp" #include "renderer.hpp" #include "utils.hpp" #include "framebuffer.hpp" #include "renderbuffer.hpp" #include "resource_manager.hpp" #include "internal/opengl.hpp" #include "../base/logging.hpp" namespace yg { namespace gl { const yg::Color Renderer::s_bgColor(192, 192, 192, 255); void Renderer::State::apply(BaseState const * prevBase) { State const * prevState = static_cast<State const *>(prevBase); if (m_frameBuffer) { bool shouldApply = false; if (m_frameBuffer == prevState->m_frameBuffer) { if (m_isDebugging) { std::ostringstream out; out << "equal frameBuffers, "; if (m_frameBuffer) out << m_frameBuffer->id() << ", " << prevState->m_frameBuffer->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } if (m_renderTarget != prevState->m_renderTarget) { if (m_isDebugging) { std::ostringstream out; out << "non-equal renderBuffers, "; if (prevState->m_renderTarget) out << prevState->m_renderTarget->id(); else out << "(null)"; out << " => "; if (m_renderTarget) out << m_renderTarget->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setRenderTarget(m_renderTarget); shouldApply = true; } else { if (m_isDebugging) { std::ostringstream out; out << "equal renderBuffers, "; if (m_renderTarget) out << m_renderTarget->id() << ", " << m_renderTarget->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } } if (m_depthBuffer != prevState->m_depthBuffer) { if (m_isDebugging) { std::ostringstream out; out << "non-equal depthBuffers, "; if (prevState->m_depthBuffer) out << prevState->m_depthBuffer->id(); else out << "(null)"; out << " => "; if (m_depthBuffer) out << m_depthBuffer->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setDepthBuffer(m_depthBuffer); shouldApply = true; } else { if (m_isDebugging) { std::ostringstream out; out << "equal depthBuffers, "; if (m_depthBuffer) out << m_depthBuffer->id() << ", " << m_depthBuffer->id(); else out << "(null), (null)"; LOG(LINFO, (out.str().c_str())); } } } else { if (m_isDebugging) { ostringstream out; out << "non-equal frameBuffers, "; if (prevState->m_frameBuffer) out << prevState->m_frameBuffer->id() << ", "; else out << "(null)"; out << " => "; if (m_frameBuffer) out << m_frameBuffer->id() << ", "; else out << "(null)"; LOG(LINFO, (out.str().c_str())); out.str(""); out << "renderTarget="; if (m_renderTarget) out << m_renderTarget->id(); else out << "(null)"; out << ", depthBuffer="; if (m_depthBuffer) out << m_depthBuffer->id(); else out << "(null)"; LOG(LINFO, (out.str().c_str())); } m_frameBuffer->setRenderTarget(m_renderTarget); m_frameBuffer->setDepthBuffer(m_depthBuffer); shouldApply = true; } if (shouldApply) m_frameBuffer->makeCurrent(); } else CHECK(false, ()); } Renderer::Params::Params() : m_isDebugging(false), m_renderQueue(0) {} Renderer::Renderer(Params const & params) : m_isDebugging(params.m_isDebugging), m_isRendering(false), m_width(0), m_height(0) { m_frameBuffer = params.m_frameBuffer; m_resourceManager = params.m_resourceManager; if (m_frameBuffer) { m_renderTarget = m_frameBuffer->renderTarget(); m_depthBuffer = m_frameBuffer->depthBuffer(); } m_renderQueue = params.m_renderQueue; } Renderer::~Renderer() {} shared_ptr<ResourceManager> const & Renderer::resourceManager() const { return m_resourceManager; } void Renderer::beginFrame() { m_isRendering = true; if (m_renderQueue) return; if (m_frameBuffer) m_frameBuffer->makeCurrent(); } bool Renderer::isRendering() const { return m_isRendering; } void Renderer::endFrame() { m_isRendering = false; } shared_ptr<FrameBuffer> const & Renderer::frameBuffer() const { return m_frameBuffer; } shared_ptr<RenderTarget> const & Renderer::renderTarget() const { return m_renderTarget; } void Renderer::setRenderTarget(shared_ptr<RenderTarget> const & rt) { m_renderTarget = rt; if (!m_renderQueue) { m_frameBuffer->setRenderTarget(rt); m_frameBuffer->makeCurrent(); //< to attach renderTarget } } void Renderer::resetRenderTarget() { m_renderTarget.reset(); if (!m_renderQueue) m_frameBuffer->resetRenderTarget(); } shared_ptr<RenderBuffer> const & Renderer::depthBuffer() const { return m_depthBuffer; } void Renderer::setDepthBuffer(shared_ptr<RenderBuffer> const & rt) { m_depthBuffer = rt; if (!m_renderQueue) m_frameBuffer->setDepthBuffer(rt); } void Renderer::resetDepthBuffer() { m_depthBuffer.reset(); if (!m_renderQueue) m_frameBuffer->resetDepthBuffer(); } Renderer::ClearCommand::ClearCommand(yg::Color const & color, bool clearRT, float depth, bool clearDepth) : m_color(color), m_clearRT(clearRT), m_depth(depth), m_clearDepth(clearDepth) {} void Renderer::ClearCommand::perform() { if (isDebugging()) LOG(LINFO, ("performing clear command")); OGLCHECK(glClearColor(m_color.r / 255.0f, m_color.g / 255.0f, m_color.b / 255.0f, m_color.a / 255.0f)); #ifdef OMIM_GL_ES OGLCHECK(glClearDepthf(m_depth)); #else OGLCHECK(glClearDepth(m_depth)); #endif GLbitfield mask = 0; if (m_clearRT) mask |= GL_COLOR_BUFFER_BIT; if (m_clearDepth) mask |= GL_DEPTH_BUFFER_BIT; OGLCHECK(glDepthMask(GL_TRUE)); OGLCHECK(glClear(mask)); } void Renderer::clear(yg::Color const & c, bool clearRT, float depth, bool clearDepth) { shared_ptr<ClearCommand> command(new ClearCommand(c, clearRT, depth, clearDepth)); processCommand(command); } shared_ptr<BaseState> const Renderer::createState() const { return shared_ptr<BaseState>(new State()); } void Renderer::getState(BaseState * baseState) { State * state = static_cast<State *>(baseState); state->m_frameBuffer = m_frameBuffer; state->m_renderTarget = m_renderTarget; state->m_depthBuffer = m_depthBuffer; state->m_resourceManager = m_resourceManager; } void Renderer::FinishCommand::perform() { if (m_isDebugging) LOG(LINFO, ("performing FinishCommand command")); OGLCHECK(glFinish()); } void Renderer::finish() { shared_ptr<Command> command(new FinishCommand()); processCommand(command); } void Renderer::onSize(unsigned int width, unsigned int height) { if (width < 2) width = 2; if (height < 2) height = 2; m_width = width; m_height = height; if (m_frameBuffer) m_frameBuffer->onSize(width, height); } unsigned int Renderer::width() const { return m_width; } unsigned int Renderer::height() const { return m_height; } bool Renderer::isDebugging() const { return m_isDebugging; } void Renderer::processCommand(shared_ptr<Command> const & command, Packet::EType type) { // command->m_isDebugging = false; command->m_isDebugging = renderQueue(); if (renderQueue()) { shared_ptr<BaseState> state = createState(); getState(state.get()); m_renderQueue->processPacket(Packet(state, command, type)); } else command->perform(); } PacketsQueue * Renderer::renderQueue() { return m_renderQueue; } void Renderer::markFrameBoundary() { if (m_renderQueue) m_renderQueue->processPacket(Packet(Packet::ECheckPoint)); } } } <|endoftext|>
<commit_before>/*-------------Lanczos.cpp----------------------------------------------------// * * Purpose: To diagonalize a random matrix using the Lanczos algorithm * * Notes: Compile with (for Arch systems): * g++ -I /usr/include/eigen3/ Lanczos.cpp * 0's along the prime diagonal. I don't know what this means. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <Eigen/Core> #include <Eigen/QR> #include <random> #include <vector> #include <math.h> using namespace Eigen; // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix); // Function for QR decomposition MatrixXd qrdecomp(MatrixXd &Tridiag); // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q); // Function to return sign of value (signum function) int sign(double value); // Function to check eigenvectors and values void eigentest(MatrixXd &d_matrix, MatrixXd &Q); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ int size = 200; MatrixXd d_matrix(size,size); // set up random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); for (size_t i = 0; i < d_matrix.rows(); ++i){ for (size_t j = 0; j <= i; ++j){ d_matrix(i,j) = dist(gen); d_matrix(j,i) = d_matrix(i,j); } } MatrixXd Tridiag = lanczos(d_matrix); std::cout << '\n' << "Tridiagonal matrix is: \n"; for (size_t i = 0; i < Tridiag.rows(); ++i){ for (size_t j = 0; j < Tridiag.cols(); ++j){ std::cout << Tridiag(i, j) << '\t'; } std::cout << '\n'; } std::cout << '\n'; MatrixXd Q = qrdecomp(Tridiag); MatrixXd Qtemp = Q; std::cout << Q << '\n'; std::cout << "Finding eigenvalues: " << '\n'; p_method(Tridiag, Q); Qtemp = Qtemp - Q; std::cout << "After the Power Method: " << Qtemp.squaredNorm() << '\n'; eigentest(Tridiag, Q); } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix){ // Creating random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); // Defining values double threshold = 0.01; int j = 0, j_tot = 5; int size = d_matrix.rows(); // Setting beta arbitrarily large for now double beta = 10; // generating the first rayleigh vector // alpha is actually just a double... sorry about that. MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1), alpha(1, 1); MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols()); // krylov is the krylovian subspace... Note, there might be a dynamic way to // do this. Something like: //std::vector <MatrixXd> krylov; MatrixXd krylov(d_matrix.rows(), j_tot); for (size_t i = 0; i < size; ++i){ rayleigh(i) = dist(gen); } //std::cout << rayleigh << '\n'; //while (beta > threshold){ for (size_t i = 0; i < j_tot; ++i){ beta = rayleigh.norm(); //std::cout << "beta is: \n" << beta << '\n'; q = rayleigh / beta; //std::cout << "q is: \n" << q << '\n'; alpha = q.transpose() * d_matrix * q; //std::cout << "alpha is \n" << alpha << '\n'; if (j == 0){ rayleigh = (d_matrix - alpha(0,0) * identity) * q; } else{ rayleigh = (d_matrix - alpha(0,0) * identity) * q - beta * krylov.col(j - 1); } //std::cout << "rayleigh is: \n" << rayleigh <<'\n'; //std::cout << "i is: " << i << '\n'; //krylov.push_back(q); krylov.col(j) = q; j = j+1; // std::cout << j << '\n'; } MatrixXd krylov_id = krylov.transpose() * krylov; std::cout << "The identity matrix from the krylov subspace is: \n" << krylov_id << '\n'; MatrixXd T(j_tot,j_tot); T = krylov.transpose() * d_matrix * krylov; return T; } // Function for QR decomposition // Because we only need Q for the power method, I will retun only Q MatrixXd qrdecomp(MatrixXd &Tridiag){ // Q is and orthonormal vector => Q'Q = 1 MatrixXd Q(Tridiag.rows(), Tridiag.cols()); MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols()); // R is the upper triangular matrix MatrixXd R = Tridiag; int row_num = Tridiag.rows(); int countx = 0, county = 0; // Scale R double sum = 0.0, sigma, tau, fak, max_val = 0; /* for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ if (R(i,j) > max_val){ max_val = R(i,j); } } } for (int i = 0; i < row_num; ++i){ for (int j = 0; j < row_num; ++j){ R(i,j) /= max_val; } } */ bool sing; // Defining vectors for algorithm MatrixXd diag(row_num,1); for (size_t i = 0; i < row_num; ++i){ // determining l_2 norm sum = 0.0; for (size_t j = i; j < row_num; ++j){ sum += R(j,i) * R(j,i); std::cout << R(j,i) << '\n'; } sum = sqrt(sum); std::cout << "sum is: " << sum << '\n'; if (sum == 0.0){ sing = true; diag(i) = 0.0; std::cout << "MATRIX IS SINGULAR!!!" << '\n'; } else{ if (R(i,i) >= 0){ diag(i) = -sum; } else{ diag(i) = sum; } fak = sqrt(sum * (sum + abs(R(i,i)))); R(i,i) = R(i,i) - diag(i); for (size_t j = i; j < row_num; ++j){ R(j,i) = R(j,i) / fak; } // Creating blocks to work with MatrixXd block1 = R.block(i, i+1, row_num-i, row_num -i-1); MatrixXd block2 = R.block(i, i, row_num-i,1); block1 = block1 - block2 * (block2.transpose() * block1); std::cout << R << '\n' << '\n' << block1 << '\n'; // setting values back to what they need to be countx = 0; for (int j = i+1; j < row_num; ++j){ for (int k = i; k < row_num; ++k){ R(k,j) = block1(k-i, j-i-1); } } } } MatrixXd z(row_num, 1); // Explicitly defining Q // Create column block for multiplication for (size_t i = 0; i < row_num; ++i){ MatrixXd Idblock = Id.block(0, i, row_num, 1); for (int j = row_num-1; j >= 0; --j){ z = Idblock; // Creating blocks for multiplication MatrixXd zblock = z.block(j, 0, row_num - j, 1); MatrixXd Rblock = R.block(j, j, row_num - j, 1); // Performing multiplication zblock = zblock - Rblock * (Rblock.transpose() * zblock); // Set xblock up for next iteration of k for (int k = j; k < row_num; ++k){ z(k) = zblock(k-j); } } Q.col(i) = z; //std::cout << Q << '\n'; } // Remove lower left from R for (int i = 0; i < row_num; ++i){ R(i,i) = diag(i); for (int j = 0; j < i; ++j){ R(i,j) = 0; } } //std::cout << "R is: " << '\n' << R << '\n'; MatrixXd temp = Q.transpose() * Q; /* std::cout << "Truncated Q^T * Q is:" << '\n'; for (int i = 0; i < temp.rows(); ++i){ for (int j = 0; j < temp.cols(); ++j){ if (temp(i,j) < 0.00000000001){ std::cout << 0 << '\t'; } else{ std::cout << temp(i,j) <<'\t'; } } std::cout << '\n'; } std::cout << '\n'; */ //std::cout << "Q^T * Q is: " << '\n' << Q * Q.transpose() << '\n' << '\n'; //std::cout << "QR - A is: " << '\n' << Q*R - Tridiag << '\n'; //std::cout << "Q^T * A - R: " << '\n' // << Q.transpose() * Tridiag - R << '\n' << '\n'; return Q.transpose(); } // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q){ // Find all eigenvectors MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols()); MatrixXd Z(Tridiag.rows(), Tridiag.cols()); MatrixXd Qtemp = Q; // Iteratively defines eigenvectors for (int i = 0; i < Tridiag.rows(); ++i){ Z = Tridiag * Q; Q = qrdecomp(Z); } Qtemp = Qtemp - Q; std::cout << "This should not be 0: " << Qtemp.squaredNorm() << '\n'; } // Function to return sign of value (signum function) int sign(double value){ if (value < 0.0){ return -1; } else if (value > 0){ return 1; } else { return 0; } } // Function to check eigenvectors and values void eigentest(MatrixXd &Tridiag, MatrixXd &Q){ // Calculating the Rayleigh quotient (v^t * A * v) / (v^t * v) // Note, that this should be a representation of eigenvalues std::vector<double> eigenvalues(Tridiag.rows()); MatrixXd eigenvector(Tridiag.rows(),1); double QQ, QAQ; for (size_t i = 0; i < Tridiag.rows(); ++i){ QQ = Q.col(i).transpose() * Q.col(i); QAQ = Q.col(i).transpose() * Tridiag * Q.col(i); eigenvalues[i] = QAQ / QQ; std::cout << "eigenvalue is: " << eigenvalues[i] << '\n'; eigenvector = ((Tridiag * Q.col(i)) / eigenvalues[i]) - Q.col(i); std::cout << eigenvector << '\n' << '\n'; std::cout << "This should be 0: " << '\t' << eigenvector.squaredNorm() << '\n'; } } <commit_msg>QR decomposition passing all tests Now to check diagonals<commit_after>/*-------------Lanczos.cpp----------------------------------------------------// * * Purpose: To diagonalize a random matrix using the Lanczos algorithm * * Notes: Compile with (for Arch systems): * g++ -I /usr/include/eigen3/ Lanczos.cpp * 0's along the prime diagonal. I don't know what this means. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <Eigen/Core> #include <Eigen/QR> #include <random> #include <vector> #include <math.h> using namespace Eigen; // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix); // Function for QR decomposition MatrixXd qrdecomp(MatrixXd &Tridiag); // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q); // Function to return sign of value (signum function) int sign(double value); // Function to check eigenvectors and values void eigentest(MatrixXd &d_matrix, MatrixXd &Q); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ /* int size = 200; MatrixXd d_matrix(size,size); // set up random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); for (size_t i = 0; i < d_matrix.rows(); ++i){ for (size_t j = 0; j <= i; ++j){ d_matrix(i,j) = dist(gen); d_matrix(j,i) = d_matrix(i,j); } } Tridiag = lanczos(d_matrix); std::cout << '\n' << "Tridiagonal matrix is: \n"; for (size_t i = 0; i < Tridiag.rows(); ++i){ for (size_t j = 0; j < Tridiag.cols(); ++j){ std::cout << Tridiag(i, j) << '\t'; } std::cout << '\n'; } std::cout << '\n'; */ MatrixXd Tridiag(4,4); Tridiag << 2, 1, 3, 5, -1, 0, 7, 1, 0,-1,-1,3, -3,7,4,3; MatrixXd Q = qrdecomp(Tridiag); /* MatrixXd Qtemp = Q; std::cout << Q << '\n'; std::cout << "Finding eigenvalues: " << '\n'; p_method(Tridiag, Q); Qtemp = Qtemp - Q; std::cout << "After the Power Method: " << Qtemp.squaredNorm() << '\n'; eigentest(Tridiag, Q); */ } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // Function for the lanczos algorithm, returns Tri-diagonal matrix MatrixXd lanczos(MatrixXd &d_matrix){ // Creating random device static std::random_device rd; int seed = rd(); static std::mt19937 gen(seed); std::uniform_real_distribution<double> dist(0,1); // Defining values double threshold = 0.01; int j = 0, j_tot = 5; int size = d_matrix.rows(); // Setting beta arbitrarily large for now double beta = 10; // generating the first rayleigh vector // alpha is actually just a double... sorry about that. MatrixXd rayleigh(d_matrix.rows(),1), q(d_matrix.rows(),1), alpha(1, 1); MatrixXd identity = MatrixXd::Identity(d_matrix.rows(), d_matrix.cols()); // krylov is the krylovian subspace... Note, there might be a dynamic way to // do this. Something like: //std::vector <MatrixXd> krylov; MatrixXd krylov(d_matrix.rows(), j_tot); for (size_t i = 0; i < size; ++i){ rayleigh(i) = dist(gen); } //std::cout << rayleigh << '\n'; //while (beta > threshold){ for (size_t i = 0; i < j_tot; ++i){ beta = rayleigh.norm(); //std::cout << "beta is: \n" << beta << '\n'; q = rayleigh / beta; //std::cout << "q is: \n" << q << '\n'; alpha = q.transpose() * d_matrix * q; //std::cout << "alpha is \n" << alpha << '\n'; if (j == 0){ rayleigh = (d_matrix - alpha(0,0) * identity) * q; } else{ rayleigh = (d_matrix - alpha(0,0) * identity) * q - beta * krylov.col(j - 1); } //std::cout << "rayleigh is: \n" << rayleigh <<'\n'; //std::cout << "i is: " << i << '\n'; //krylov.push_back(q); krylov.col(j) = q; j = j+1; // std::cout << j << '\n'; } MatrixXd krylov_id = krylov.transpose() * krylov; std::cout << "The identity matrix from the krylov subspace is: \n" << krylov_id << '\n'; MatrixXd T(j_tot,j_tot); T = krylov.transpose() * d_matrix * krylov; return T; } // Function for QR decomposition // Because we only need Q for the power method, I will retun only Q MatrixXd qrdecomp(MatrixXd &Tridiag){ // Q is and orthonormal vector => Q'Q = 1 MatrixXd Id = MatrixXd::Identity(Tridiag.rows(), Tridiag.cols()); MatrixXd Q = Id; MatrixXd P(Tridiag.rows(), Tridiag.cols()); // R is the upper triangular matrix MatrixXd R = Tridiag; int row_num = Tridiag.rows(); int countx = 0, county = 0; // Scale R double sum = 0.0, sigma, tau, fak, max_val = 0; bool sing; // Defining vectors for algorithm MatrixXd diag(row_num,1); std::cout << R << '\n'; for (int i = 0; i < row_num-1; ++i){ diag = MatrixXd::Zero(row_num, 1); sum = 0; for (size_t j = i; j < row_num; ++j){ sum += R(j,i) * R(j,i); std::cout << R(j,i) << '\n'; } sum = sqrt(sum); if (R(i,i) > 0){ sigma = -sum; } else{ sigma = sum; } std::cout << "sigma is: " << sigma << '\n'; sum = 0; //diag = R.block(i,i, row_num - i, 1); std::cout << "diag is: " << '\n'; for (int j = i; j < row_num; ++j){ //std::cout << i << '\t' << j << '\n'; if (j == i){ diag(j) = R(j,i) + sigma; } else{ diag(j) = R(j, i); } std::cout << diag(j) << '\n'; sum = sum + diag(j) * diag(j); } sum = sqrt(sum); std::cout << "sum is: " << sum << '\n'; if (sum > 0.000000000000001){ for (int j = i; j < row_num; ++j){ diag(j) = diag(j) / sum; } std::cout << "normalized diag is: " << '\n' << diag << '\n'; P = Id - (diag * diag.transpose()) * 2.0; R = P * R; Q = Q * P; } std::cout << "R is: " << R << '\n'; } std::cout << "R is: " << R << '\n'; std::cout << "Q is: " << Q << '\n'; std::cout << "QR is: " << '\n' << Q*R << '\n'; std::cout << "Q^T * Q is: " << '\n' << Q.transpose() * Q << '\n' << '\n'; std::cout << "QR - A is: " << '\n' << Q*R - Tridiag << '\n'; std::cout << "Q^T * A - R: " << '\n' << Q.transpose() * Tridiag - R << '\n' << '\n'; return Q.transpose(); } // Function to perform the Power Method void p_method(MatrixXd &Tridiag, MatrixXd &Q){ // Find all eigenvectors MatrixXd eigenvectors(Tridiag.rows(), Tridiag.cols()); MatrixXd Z(Tridiag.rows(), Tridiag.cols()); MatrixXd Qtemp = Q; // Iteratively defines eigenvectors for (int i = 0; i < Tridiag.rows(); ++i){ Z = Tridiag * Q; Q = qrdecomp(Z); } Qtemp = Qtemp - Q; std::cout << "This should not be 0: " << Qtemp.squaredNorm() << '\n'; } // Function to return sign of value (signum function) int sign(double value){ if (value < 0.0){ return -1; } else if (value > 0){ return 1; } else { return 0; } } // Function to check eigenvectors and values void eigentest(MatrixXd &Tridiag, MatrixXd &Q){ // Calculating the Rayleigh quotient (v^t * A * v) / (v^t * v) // Note, that this should be a representation of eigenvalues std::vector<double> eigenvalues(Tridiag.rows()); MatrixXd eigenvector(Tridiag.rows(),1); double QQ, QAQ; for (size_t i = 0; i < Tridiag.rows(); ++i){ QQ = Q.col(i).transpose() * Q.col(i); QAQ = Q.col(i).transpose() * Tridiag * Q.col(i); eigenvalues[i] = QAQ / QQ; std::cout << "eigenvalue is: " << eigenvalues[i] << '\n'; eigenvector = ((Tridiag * Q.col(i)) / eigenvalues[i]) - Q.col(i); std::cout << eigenvector << '\n' << '\n'; std::cout << "This should be 0: " << '\t' << eigenvector.squaredNorm() << '\n'; } } <|endoftext|>
<commit_before>//===- SILLowerAggregateInstrs.cpp - Aggregate insts to Scalar insts -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Simplify aggregate instructions into scalar instructions. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-lower-aggregate-instrs" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILModule.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; using namespace swift::Lowering; STATISTIC(NumExpand, "Number of instructions expanded"); //===----------------------------------------------------------------------===// // Higher Level Operation Expansion //===----------------------------------------------------------------------===// /// \brief Lower copy_addr into loads/stores/retain/release if we have a /// non-address only type. We do this here so we can process the resulting /// loads/stores. /// /// This peephole implements the following optimizations: /// /// copy_addr %0 to %1 : $*T /// -> /// %new = load %0 : $*T // Load the new value from the source /// %old = load %1 : $*T // Load the old value from the destination /// strong_retain %new : $T // Retain the new value /// strong_release %old : $T // Release the old /// store %new to %1 : $*T // Store the new value to the destination /// /// copy_addr [take] %0 to %1 : $*T /// -> /// %new = load %0 : $*T /// %old = load %1 : $*T /// // no retain of %new! /// strong_release %old : $T /// store %new to %1 : $*T /// /// copy_addr %0 to [initialization] %1 : $*T /// -> /// %new = load %0 : $*T /// strong_retain %new : $T /// // no load/release of %old! /// store %new to %1 : $*T /// /// copy_addr [take] %0 to [initialization] %1 : $*T /// -> /// %new = load %0 : $*T /// // no retain of %new! /// // no load/release of %old! /// store %new to %1 : $*T static bool expandCopyAddr(CopyAddrInst *CA) { SILModule &M = CA->getModule(); SILValue Source = CA->getSrc(); // If we have an address only type don't do anything. SILType SrcType = Source.getType(); if (SrcType.isAddressOnly(M)) return false; SILBuilder Builder(CA); // %new = load %0 : $*T LoadInst *New = Builder.createLoad(CA->getLoc(), Source); SILValue Destination = CA->getDest(); // If our object type is not trivial, we may need to release the old value and // retain the new one. // If we have a non-trivial type... if (!SrcType.isTrivial(M)) { // If we are not initializing: // %old = load %1 : $*T IsInitialization_t IsInit = CA->isInitializationOfDest(); LoadInst *Old = nullptr; if (IsInitialization_t::IsNotInitialization == IsInit) { Old = Builder.createLoad(CA->getLoc(), Destination); } // If we are not taking and have a reference type: // strong_retain %new : $*T // or if we have a non-trivial non-reference type. // copy_value %new : $*T IsTake_t IsTake = CA->isTakeOfSrc(); if (IsTake_t::IsNotTake == IsTake) { if (SrcType.hasReferenceSemantics()) Builder.createStrongRetain(CA->getLoc(), New); else Builder.createCopyValue(CA->getLoc(), New); } // If we are not initializing: // strong_release %old : $*T // *or* // destroy_value %new : $*T if (Old) { if (SrcType.hasReferenceSemantics()) Builder.createStrongRelease(CA->getLoc(), Old); else Builder.createDestroyValue(CA->getLoc(), Old); } } // Create the store. Builder.createStore(CA->getLoc(), New, Destination); ++NumExpand; return true; } static bool expandDestroyAddr(DestroyAddrInst *DA) { SILModule &Module = DA->getModule(); SILBuilder Builder(DA); // Strength reduce destroy_addr inst into release/store if // we have a non-address only type. SILValue Addr = DA->getOperand(); // If we have an address only type, do nothing. SILType Type = Addr.getType(); if (Type.isAddressOnly(Module)) return false; // If we have a non-trivial type... if (!Type.isTrivial(Module)) { // If we have a type with reference semantics, emit a load/strong release. LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr); if (Type.hasReferenceSemantics()) Builder.createStrongRelease(DA->getLoc(), LI); else Builder.createDestroyValue(DA->getLoc(), LI); } ++NumExpand; return true; } static bool expandDestroyValue(DestroyValueInst *DV) { SILModule &Module = DV->getModule(); SILBuilder Builder(DV); // Strength reduce destroy_addr inst into release/store if // we have a non-address only type. SILValue Value = DV->getOperand(); // If we have an address only type, do nothing. SILType Type = Value.getType(); assert(!Type.isAddressOnly(Module) && "destroy_value should never be called on a non-loadable type."); auto &TL = Module.getTypeLowering(Type); TL.emitLoweredDestroyValue(Builder, DV->getLoc(), Value, TypeLowering::LoweringStyle::DeepNoEnum); DEBUG(llvm::dbgs() << " Expanding Destroy Value: " << *DV); ++NumExpand; return true; } //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// static void processFunction(SILFunction &Fn) { for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) { auto II = BI->begin(), IE = BI->end(); while (II != IE) { SILInstruction *Inst = &*II; DEBUG(llvm::dbgs() << "Visiting: " << *Inst); if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) if (expandCopyAddr(CA)) { ++II; CA->eraseFromParent(); continue; } if (auto *DA = dyn_cast<DestroyAddrInst>(Inst)) if (expandDestroyAddr(DA)) { ++II; DA->eraseFromParent(); continue; } if (auto *DV = dyn_cast<DestroyValueInst>(Inst)) if (expandDestroyValue(DV)) { ++II; DV->eraseFromParent(); continue; } ++II; } } } void swift::performSILLowerAggregateInstrs(SILModule *M) { DEBUG(llvm::dbgs() << "*** SIL LowerAggregateInstrs ***\n"); // For each function Fn in M... for (auto &Fn : *M) { // If Fn has no basic blocks skip it. if (Fn.empty()) continue; DEBUG(llvm::dbgs() << "***** Visiting " << Fn.getName() << " *****\n"); // Otherwise perform LowerAggregateInstrs. processFunction(Fn); } } <commit_msg>[lower-aggregate-instrs] Change one usage of !isAddressOnly => isLoadable.<commit_after>//===- SILLowerAggregateInstrs.cpp - Aggregate insts to Scalar insts -----===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // Simplify aggregate instructions into scalar instructions. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "sil-lower-aggregate-instrs" #include "swift/SILPasses/Passes.h" #include "swift/SILPasses/Utils/Local.h" #include "swift/SIL/SILInstruction.h" #include "swift/SIL/SILVisitor.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILModule.h" #include "llvm/ADT/Statistic.h" #include "llvm/Support/Debug.h" using namespace swift; using namespace swift::Lowering; STATISTIC(NumExpand, "Number of instructions expanded"); //===----------------------------------------------------------------------===// // Higher Level Operation Expansion //===----------------------------------------------------------------------===// /// \brief Lower copy_addr into loads/stores/retain/release if we have a /// non-address only type. We do this here so we can process the resulting /// loads/stores. /// /// This peephole implements the following optimizations: /// /// copy_addr %0 to %1 : $*T /// -> /// %new = load %0 : $*T // Load the new value from the source /// %old = load %1 : $*T // Load the old value from the destination /// strong_retain %new : $T // Retain the new value /// strong_release %old : $T // Release the old /// store %new to %1 : $*T // Store the new value to the destination /// /// copy_addr [take] %0 to %1 : $*T /// -> /// %new = load %0 : $*T /// %old = load %1 : $*T /// // no retain of %new! /// strong_release %old : $T /// store %new to %1 : $*T /// /// copy_addr %0 to [initialization] %1 : $*T /// -> /// %new = load %0 : $*T /// strong_retain %new : $T /// // no load/release of %old! /// store %new to %1 : $*T /// /// copy_addr [take] %0 to [initialization] %1 : $*T /// -> /// %new = load %0 : $*T /// // no retain of %new! /// // no load/release of %old! /// store %new to %1 : $*T static bool expandCopyAddr(CopyAddrInst *CA) { SILModule &M = CA->getModule(); SILValue Source = CA->getSrc(); // If we have an address only type don't do anything. SILType SrcType = Source.getType(); if (SrcType.isAddressOnly(M)) return false; SILBuilder Builder(CA); // %new = load %0 : $*T LoadInst *New = Builder.createLoad(CA->getLoc(), Source); SILValue Destination = CA->getDest(); // If our object type is not trivial, we may need to release the old value and // retain the new one. // If we have a non-trivial type... if (!SrcType.isTrivial(M)) { // If we are not initializing: // %old = load %1 : $*T IsInitialization_t IsInit = CA->isInitializationOfDest(); LoadInst *Old = nullptr; if (IsInitialization_t::IsNotInitialization == IsInit) { Old = Builder.createLoad(CA->getLoc(), Destination); } // If we are not taking and have a reference type: // strong_retain %new : $*T // or if we have a non-trivial non-reference type. // copy_value %new : $*T IsTake_t IsTake = CA->isTakeOfSrc(); if (IsTake_t::IsNotTake == IsTake) { if (SrcType.hasReferenceSemantics()) Builder.createStrongRetain(CA->getLoc(), New); else Builder.createCopyValue(CA->getLoc(), New); } // If we are not initializing: // strong_release %old : $*T // *or* // destroy_value %new : $*T if (Old) { if (SrcType.hasReferenceSemantics()) Builder.createStrongRelease(CA->getLoc(), Old); else Builder.createDestroyValue(CA->getLoc(), Old); } } // Create the store. Builder.createStore(CA->getLoc(), New, Destination); ++NumExpand; return true; } static bool expandDestroyAddr(DestroyAddrInst *DA) { SILModule &Module = DA->getModule(); SILBuilder Builder(DA); // Strength reduce destroy_addr inst into release/store if // we have a non-address only type. SILValue Addr = DA->getOperand(); // If we have an address only type, do nothing. SILType Type = Addr.getType(); if (Type.isAddressOnly(Module)) return false; // If we have a non-trivial type... if (!Type.isTrivial(Module)) { // If we have a type with reference semantics, emit a load/strong release. LoadInst *LI = Builder.createLoad(DA->getLoc(), Addr); if (Type.hasReferenceSemantics()) Builder.createStrongRelease(DA->getLoc(), LI); else Builder.createDestroyValue(DA->getLoc(), LI); } ++NumExpand; return true; } static bool expandDestroyValue(DestroyValueInst *DV) { SILModule &Module = DV->getModule(); SILBuilder Builder(DV); // Strength reduce destroy_addr inst into release/store if // we have a non-address only type. SILValue Value = DV->getOperand(); // If we have an address only type, do nothing. SILType Type = Value.getType(); assert(Type.isLoadable(Module) && "destroy_value should never be called on a non-loadable type."); auto &TL = Module.getTypeLowering(Type); TL.emitLoweredDestroyValue(Builder, DV->getLoc(), Value, TypeLowering::LoweringStyle::DeepNoEnum); DEBUG(llvm::dbgs() << " Expanding Destroy Value: " << *DV); ++NumExpand; return true; } //===----------------------------------------------------------------------===// // Top Level Driver //===----------------------------------------------------------------------===// static void processFunction(SILFunction &Fn) { for (auto BI = Fn.begin(), BE = Fn.end(); BI != BE; ++BI) { auto II = BI->begin(), IE = BI->end(); while (II != IE) { SILInstruction *Inst = &*II; DEBUG(llvm::dbgs() << "Visiting: " << *Inst); if (auto *CA = dyn_cast<CopyAddrInst>(Inst)) if (expandCopyAddr(CA)) { ++II; CA->eraseFromParent(); continue; } if (auto *DA = dyn_cast<DestroyAddrInst>(Inst)) if (expandDestroyAddr(DA)) { ++II; DA->eraseFromParent(); continue; } if (auto *DV = dyn_cast<DestroyValueInst>(Inst)) if (expandDestroyValue(DV)) { ++II; DV->eraseFromParent(); continue; } ++II; } } } void swift::performSILLowerAggregateInstrs(SILModule *M) { DEBUG(llvm::dbgs() << "*** SIL LowerAggregateInstrs ***\n"); // For each function Fn in M... for (auto &Fn : *M) { // If Fn has no basic blocks skip it. if (Fn.empty()) continue; DEBUG(llvm::dbgs() << "***** Visiting " << Fn.getName() << " *****\n"); // Otherwise perform LowerAggregateInstrs. processFunction(Fn); } } <|endoftext|>
<commit_before>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR LITECOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Sakuracoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your sakuracoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <commit_msg>LITECOIN to SAKURACOIN<commit_after>// Copyright (c) 2011-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "askpassphrasedialog.h" #include "ui_askpassphrasedialog.h" #include "guiconstants.h" #include "walletmodel.h" #include <QMessageBox> #include <QPushButton> #include <QKeyEvent> AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) : QDialog(parent), ui(new Ui::AskPassphraseDialog), mode(mode), model(0), fCapsLock(false) { ui->setupUi(this); ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE); ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE); // Setup Caps Lock detection. ui->passEdit1->installEventFilter(this); ui->passEdit2->installEventFilter(this); ui->passEdit3->installEventFilter(this); switch(mode) { case Encrypt: // Ask passphrase x2 ui->passLabel1->hide(); ui->passEdit1->hide(); ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>10 or more random characters</b>, or <b>eight or more words</b>.")); setWindowTitle(tr("Encrypt wallet")); break; case Unlock: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Unlock wallet")); break; case Decrypt: // Ask passphrase ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet.")); ui->passLabel2->hide(); ui->passEdit2->hide(); ui->passLabel3->hide(); ui->passEdit3->hide(); setWindowTitle(tr("Decrypt wallet")); break; case ChangePass: // Ask old passphrase + new passphrase x2 setWindowTitle(tr("Change passphrase")); ui->warningLabel->setText(tr("Enter the old and new passphrase to the wallet.")); break; } textChanged(); connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged())); } AskPassphraseDialog::~AskPassphraseDialog() { // Attempt to overwrite text so that they do not linger around in memory ui->passEdit1->setText(QString(" ").repeated(ui->passEdit1->text().size())); ui->passEdit2->setText(QString(" ").repeated(ui->passEdit2->text().size())); ui->passEdit3->setText(QString(" ").repeated(ui->passEdit3->text().size())); delete ui; } void AskPassphraseDialog::setModel(WalletModel *model) { this->model = model; } void AskPassphraseDialog::accept() { SecureString oldpass, newpass1, newpass2; if(!model) return; oldpass.reserve(MAX_PASSPHRASE_SIZE); newpass1.reserve(MAX_PASSPHRASE_SIZE); newpass2.reserve(MAX_PASSPHRASE_SIZE); // TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string) // Alternately, find a way to make this input mlock()'d to begin with. oldpass.assign(ui->passEdit1->text().toStdString().c_str()); newpass1.assign(ui->passEdit2->text().toStdString().c_str()); newpass2.assign(ui->passEdit3->text().toStdString().c_str()); switch(mode) { case Encrypt: { if(newpass1.empty() || newpass2.empty()) { // Cannot encrypt with empty passphrase break; } QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"), tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR SAKURACOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"), QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Cancel); if(retval == QMessageBox::Yes) { if(newpass1 == newpass2) { if(model->setWalletEncrypted(true, newpass1)) { QMessageBox::warning(this, tr("Wallet encrypted"), "<qt>" + tr("Sakuracoin will close now to finish the encryption process. " "Remember that encrypting your wallet cannot fully protect " "your sakuracoins from being stolen by malware infecting your computer.") + "<br><br><b>" + tr("IMPORTANT: Any previous backups you have made of your wallet file " "should be replaced with the newly generated, encrypted wallet file. " "For security reasons, previous backups of the unencrypted wallet file " "will become useless as soon as you start using the new, encrypted wallet.") + "</b></qt>"); QApplication::quit(); } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted.")); } QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } } else { QDialog::reject(); // Cancelled } } break; case Unlock: if(!model->setWalletLocked(false, oldpass)) { QMessageBox::critical(this, tr("Wallet unlock failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case Decrypt: if(!model->setWalletEncrypted(false, oldpass)) { QMessageBox::critical(this, tr("Wallet decryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } else { QDialog::accept(); // Success } break; case ChangePass: if(newpass1 == newpass2) { if(model->changePassphrase(oldpass, newpass1)) { QMessageBox::information(this, tr("Wallet encrypted"), tr("Wallet passphrase was successfully changed.")); QDialog::accept(); // Success } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The passphrase entered for the wallet decryption was incorrect.")); } } else { QMessageBox::critical(this, tr("Wallet encryption failed"), tr("The supplied passphrases do not match.")); } break; } } void AskPassphraseDialog::textChanged() { // Validate input, set Ok button to enabled when acceptable bool acceptable = false; switch(mode) { case Encrypt: // New passphrase x2 acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; case Unlock: // Old passphrase x1 case Decrypt: acceptable = !ui->passEdit1->text().isEmpty(); break; case ChangePass: // Old passphrase x1, new passphrase x2 acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty(); break; } ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable); } bool AskPassphraseDialog::event(QEvent *event) { // Detect Caps Lock key press. if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); if (ke->key() == Qt::Key_CapsLock) { fCapsLock = !fCapsLock; } if (fCapsLock) { ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else { ui->capsLabel->clear(); } } return QWidget::event(event); } bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event) { /* Detect Caps Lock. * There is no good OS-independent way to check a key state in Qt, but we * can detect Caps Lock by checking for the following condition: * Shift key is down and the result is a lower case character, or * Shift key is not down and the result is an upper case character. */ if (event->type() == QEvent::KeyPress) { QKeyEvent *ke = static_cast<QKeyEvent *>(event); QString str = ke->text(); if (str.length() != 0) { const QChar *psz = str.unicode(); bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0; if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) { fCapsLock = true; ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!")); } else if (psz->isLetter()) { fCapsLock = false; ui->capsLabel->clear(); } } } return QDialog::eventFilter(object, event); } <|endoftext|>
<commit_before>#include <stdio.h> #include <time.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <errno.h> #include <string.h> #include "stdsneezy.h" #include "connect.h" #define WIZ_KEY_FILE "/mud/prod/lib/IPC_Wiznet" #define MAIN_PORT 7900 #define BUILD_PORT 8900 #define WIZNET_FORMAT "%s %s" #define MAX_STRING_LENGTH 4096 #define MAX_INPUT_LENGTH 1024 #define MAX_MSGBUF_LENGTH 2048 int my_ipc_id, other_ipc_id; key_t keyval; int qid=-2; struct mud_msgbuf { long mtype; char mtext[MAX_MSGBUF_LENGTH+1]; }; int openQueue() { int oldqid=qid; if (qid==-2) { extern int gamePort; if (gamePort==MAIN_PORT) { my_ipc_id = MAIN_PORT; other_ipc_id = BUILD_PORT; } else { my_ipc_id = BUILD_PORT; other_ipc_id = MAIN_PORT; } keyval = ftok(WIZ_KEY_FILE, 'm'); } if ((qid = msgget(keyval, IPC_CREAT|0660)) == -1) { vlogf(LOG_BUG, "Unable to msgget keyval %d.", keyval); return -1; } if (oldqid!=qid) { vlogf(LOG_BUG, "msgget successful, qid: %d, keyval: %d", qid, keyval); oldqid = qid; } return 1; } void closeQueue() { msgctl(qid, IPC_RMID, 0); vlogf(LOG_BUG, "closeQueue"); } void mudSendMessage(int mtype, int ctype, const char *arg) { struct mud_msgbuf qbuf; int ret; if (openQueue()<0) return; if (mtype<=0) { vlogf(LOG_BUG, "invalid mtype, must be > 0, setting to 1"); mtype = 1; } snprintf(qbuf.mtext, MAX_MSGBUF_LENGTH, "%d %s", ctype, arg); qbuf.mtype = mtype; if ((ret = msgsnd(qid, (struct msgbuf *)&qbuf, strlen(qbuf.mtext)+1, 0)) == -1) vlogf(LOG_BUG, "mudSendMessage: errno: %d ret: %d", errno, ret); } void TBeing::mudMessage(TBeing *ch, int channel, const char *arg) { char tbuf[MAX_MSGBUF_LENGTH+1]; snprintf(tbuf, MAX_MSGBUF_LENGTH, "%s: %s", ch->getName(), arg); mudSendMessage(other_ipc_id, channel, tbuf); } void recvTextHandler(const char *str) { Descriptor *d; char arg1[MAX_INPUT_LENGTH], arg2[MAX_INPUT_LENGTH], chname[MAX_INPUT_LENGTH]; char buf[MAX_STRING_LENGTH-1]; int channel=-1, level=-1; str = one_argument(str, arg1); str = one_argument(str, arg2); str = one_argument(str, chname); channel = atoi(arg1); level = atoi(arg2); snprintf(buf, MAX_STRING_LENGTH, WIZNET_FORMAT, chname, str); for (d = descriptor_list; d; d = d->next) { TBeing *och; och = d->original ? d->original : d->character; if (!och) continue; if (och->hasWizPower(POWER_WIZNET)) { if (!d->isEditing()) { och->sendTo(buf); } else { // do nothing } } } } void mudRecvMessage() { struct mud_msgbuf qbuf; int ret; if (openQueue() < 0) return; while ((ret = msgrcv(qid, (struct msgbuf *)&qbuf, MAX_MSGBUF_LENGTH, my_ipc_id, IPC_NOWAIT)) > 0) recvTextHandler(qbuf.mtext); if (ret==-1 && errno!=ENOMSG) vlogf(LOG_BUG, "mudRecvMessage: errno: %d ret: %d", errno, ret); } <commit_msg>fix bwiz<commit_after>#include <stdio.h> #include <time.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #include <errno.h> #include <string.h> #include "stdsneezy.h" #include "connect.h" #define WIZ_KEY_FILE "/mud/prod/lib/IPC_Wiznet" #define MAIN_PORT 7900 #define BUILD_PORT 8900 #define WIZNET_FORMAT "%s %s" #define MAX_STRING_LENGTH 4096 #define MAX_INPUT_LENGTH 1024 #define MAX_MSGBUF_LENGTH 2048 int my_ipc_id, other_ipc_id; key_t keyval; int qid=-2; struct mud_msgbuf { long mtype; char mtext[MAX_MSGBUF_LENGTH+1]; }; int openQueue() { int oldqid=qid; if (qid==-2) { extern int gamePort; if (gamePort==MAIN_PORT) { my_ipc_id = MAIN_PORT; other_ipc_id = BUILD_PORT; } else { my_ipc_id = BUILD_PORT; other_ipc_id = MAIN_PORT; } keyval = ftok(WIZ_KEY_FILE, 'm'); } if ((qid = msgget(keyval, IPC_CREAT|0660)) == -1) { vlogf(LOG_BUG, "Unable to msgget keyval %d.", keyval); return -1; } if (oldqid!=qid) { vlogf(LOG_BUG, "msgget successful, qid: %d, keyval: %d", qid, keyval); oldqid = qid; } return 1; } void closeQueue() { msgctl(qid, IPC_RMID, 0); vlogf(LOG_BUG, "closeQueue"); } void mudSendMessage(int mtype, int ctype, const char *arg) { struct mud_msgbuf qbuf; int ret; if (openQueue()<0) return; if (mtype<=0) { vlogf(LOG_BUG, "invalid mtype, must be > 0, setting to 1"); mtype = 1; } snprintf(qbuf.mtext, MAX_MSGBUF_LENGTH, "%d %s", ctype, arg); qbuf.mtype = mtype; if ((ret = msgsnd(qid, (struct msgbuf *)&qbuf, strlen(qbuf.mtext)+1, 0)) == -1) vlogf(LOG_BUG, "mudSendMessage: errno: %d ret: %d", errno, ret); } void TBeing::mudMessage(TBeing *ch, int channel, const char *arg) { char tbuf[MAX_MSGBUF_LENGTH+1]; snprintf(tbuf, MAX_MSGBUF_LENGTH, "%s: %s", ch->getName(), arg); mudSendMessage(other_ipc_id, channel, tbuf); } void recvTextHandler(const char *str) { Descriptor *d; char arg1[MAX_INPUT_LENGTH], arg2[MAX_INPUT_LENGTH], chname[MAX_INPUT_LENGTH]; char buf[MAX_STRING_LENGTH-1]; int channel=-1, level=-1; str = one_argument(str, arg1); str = one_argument(str, arg2); str = one_argument(str, chname); channel = atoi(arg1); level = atoi(arg2); snprintf(buf, MAX_STRING_LENGTH, WIZNET_FORMAT, chname, str); for (d = descriptor_list; d; d = d->next) { TBeing *och; och = d->original ? d->original : d->character; if (!och) continue; if (och->hasWizPower(POWER_WIZNET)) { if (och->desc->connected) { } else { och->sendTo(buf); // do nothing } } } } void mudRecvMessage() { struct mud_msgbuf qbuf; int ret; if (openQueue() < 0) return; while ((ret = msgrcv(qid, (struct msgbuf *)&qbuf, MAX_MSGBUF_LENGTH, my_ipc_id, IPC_NOWAIT)) > 0) recvTextHandler(qbuf.mtext); if (ret==-1 && errno!=ENOMSG) vlogf(LOG_BUG, "mudRecvMessage: errno: %d ret: %d", errno, ret); } <|endoftext|>
<commit_before>/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include <bitset> #include <ipmid/api.hpp> #include <string> namespace ipmi { // TODO: Has to be replaced with proper channel number assignment logic /** * @enum Channel Id */ enum class EChannelID : uint8_t { chanLan1 = 0x01 }; static constexpr uint8_t invalidUserId = 0xFF; static constexpr uint8_t reservedUserId = 0x0; static constexpr uint8_t ipmiMaxUserName = 16; static constexpr uint8_t ipmiMaxUsers = 15; static constexpr uint8_t ipmiMaxChannels = 16; static constexpr uint8_t maxIpmi20PasswordSize = 20; static constexpr uint8_t maxIpmi15PasswordSize = 16; static constexpr uint8_t payloadsPerByte = 8; /** @struct PrivAccess * * User privilege related access data as per IPMI specification.(refer spec * sec 22.26) */ struct PrivAccess { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t privilege : 4; uint8_t ipmiEnabled : 1; uint8_t linkAuthEnabled : 1; uint8_t accessCallback : 1; uint8_t reserved : 1; #endif #if BYTE_ORDER == BIG_ENDIAN uint8_t reserved : 1; uint8_t accessCallback : 1; uint8_t linkAuthEnabled : 1; uint8_t ipmiEnabled : 1; uint8_t privilege : 4; #endif } __attribute__((packed)); /** @struct UserPayloadAccess * * Structure to denote payload access restrictions applicable for a * given user and channel. (refer spec sec 24.6) */ struct PayloadAccess { std::bitset<payloadsPerByte> stdPayloadEnables1; std::bitset<payloadsPerByte> stdPayloadEnables2Reserved; std::bitset<payloadsPerByte> oemPayloadEnables1; std::bitset<payloadsPerByte> oemPayloadEnables2Reserved; }; /** @brief initializes user management * * @return ccSuccess for success, others for failure. */ Cc ipmiUserInit(); /** @brief The ipmi get user password layer call * * @param[in] userName - user name * * @return password or empty string */ std::string ipmiUserGetPassword(const std::string& userName); /** @brief The IPMI call to clear password entry associated with specified * username * * @param[in] userName - user name to be removed * * @return 0 on success, non-zero otherwise. */ Cc ipmiClearUserEntryPassword(const std::string& userName); /** @brief The IPMI call to reuse password entry for the renamed user * to another one * * @param[in] userName - user name which has to be renamed * @param[in] newUserName - new user name * * @return 0 on success, non-zero otherwise. */ Cc ipmiRenameUserEntryPassword(const std::string& userName, const std::string& newUserName); /** @brief determines valid userId * * @param[in] userId - user id * * @return true if valid, false otherwise */ bool ipmiUserIsValidUserId(const uint8_t userId); /** @brief determines valid privilege level * * @param[in] priv - privilege level * * @return true if valid, false otherwise */ bool ipmiUserIsValidPrivilege(const uint8_t priv); /** @brief get user id corresponding to the user name * * @param[in] userName - user name * * @return userid. Will return 0xff if no user id found */ uint8_t ipmiUserGetUserId(const std::string& userName); /** @brief set's user name * * @param[in] userId - user id * @param[in] userName - user name * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserName(const uint8_t userId, const std::string& userName); /** @brief set user password * * @param[in] userId - user id * @param[in] userPassword - New Password * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserPassword(const uint8_t userId, const char* userPassword); /** @brief set special user password (non-ipmi accounts) * * @param[in] userName - user name * @param[in] userPassword - New Password * * @return ccSuccess for success, others for failure. */ Cc ipmiSetSpecialUserPassword(const std::string& userName, const std::string& userPassword); /** @brief get user name * * @param[in] userId - user id * @param[out] userName - user name * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetUserName(const uint8_t userId, std::string& userName); /** @brief provides available fixed, max, and enabled user counts * * @param[out] maxChUsers - max channel users * @param[out] enabledUsers - enabled user count * @param[out] fixedUsers - fixed user count * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetAllCounts(uint8_t& maxChUsers, uint8_t& enabledUsers, uint8_t& fixedUsers); /** @brief function to update user enabled state * * @param[in] userId - user id *..@param[in] state - state of the user to be updated, true - user enabled. * * @return ccSuccess for success, others for failure. */ Cc ipmiUserUpdateEnabledState(const uint8_t userId, const bool& state); /** @brief determines whether user is enabled * * @param[in] userId - user id *..@param[out] state - state of the user * * @return ccSuccess for success, others for failure. */ Cc ipmiUserCheckEnabled(const uint8_t userId, bool& state); /** @brief provides user privilege access data * * @param[in] userId - user id * @param[in] chNum - channel number * @param[out] privAccess - privilege access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetPrivilegeAccess(const uint8_t userId, const uint8_t chNum, PrivAccess& privAccess); /** @brief sets user privilege access data * * @param[in] userId - user id * @param[in] chNum - channel number * @param[in] privAccess - privilege access data * @param[in] otherPrivUpdate - flags to indicate other fields update * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetPrivilegeAccess(const uint8_t userId, const uint8_t chNum, const PrivAccess& privAccess, const bool& otherPrivUpdate); /** @brief check for user pam authentication. This is to determine, whether user * is already locked out for failed login attempt * * @param[in] username - username * @param[in] password - password * * @return status */ bool ipmiUserPamAuthenticate(std::string_view userName, std::string_view userPassword); /** @brief sets user payload access data * * @param[in] chNum - channel number * @param[in] operation - ENABLE / DISABLE operation * @param[in] userId - user id * @param[in] payloadAccess - payload access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserPayloadAccess(const uint8_t chNum, const uint8_t operation, const uint8_t userId, const PayloadAccess& payloadAccess); /** @brief provides user payload access data * * @param[in] chNum - channel number * @param[in] userId - user id * @param[out] payloadAccess - payload access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetUserPayloadAccess(const uint8_t chNum, const uint8_t userId, PayloadAccess& payloadAccess); } // namespace ipmi <commit_msg>Fix for ipmiUserSetUserName<commit_after>/* // Copyright (c) 2018 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. */ #pragma once #include <bitset> #include <ipmid/api.hpp> #include <string> namespace ipmi { // TODO: Has to be replaced with proper channel number assignment logic /** * @enum Channel Id */ enum class EChannelID : uint8_t { chanLan1 = 0x01 }; static constexpr uint8_t invalidUserId = 0xFF; static constexpr uint8_t reservedUserId = 0x0; static constexpr uint8_t ipmiMaxUserName = 16; static constexpr uint8_t ipmiMaxUsers = 15; static constexpr uint8_t ipmiMaxChannels = 16; static constexpr uint8_t maxIpmi20PasswordSize = 20; static constexpr uint8_t maxIpmi15PasswordSize = 16; static constexpr uint8_t payloadsPerByte = 8; /** @struct PrivAccess * * User privilege related access data as per IPMI specification.(refer spec * sec 22.26) */ struct PrivAccess { #if BYTE_ORDER == LITTLE_ENDIAN uint8_t privilege : 4; uint8_t ipmiEnabled : 1; uint8_t linkAuthEnabled : 1; uint8_t accessCallback : 1; uint8_t reserved : 1; #endif #if BYTE_ORDER == BIG_ENDIAN uint8_t reserved : 1; uint8_t accessCallback : 1; uint8_t linkAuthEnabled : 1; uint8_t ipmiEnabled : 1; uint8_t privilege : 4; #endif } __attribute__((packed)); /** @struct UserPayloadAccess * * Structure to denote payload access restrictions applicable for a * given user and channel. (refer spec sec 24.6) */ struct PayloadAccess { std::bitset<payloadsPerByte> stdPayloadEnables1; std::bitset<payloadsPerByte> stdPayloadEnables2Reserved; std::bitset<payloadsPerByte> oemPayloadEnables1; std::bitset<payloadsPerByte> oemPayloadEnables2Reserved; }; /** @brief initializes user management * * @return ccSuccess for success, others for failure. */ Cc ipmiUserInit(); /** @brief The ipmi get user password layer call * * @param[in] userName - user name * * @return password or empty string */ std::string ipmiUserGetPassword(const std::string& userName); /** @brief The IPMI call to clear password entry associated with specified * username * * @param[in] userName - user name to be removed * * @return 0 on success, non-zero otherwise. */ Cc ipmiClearUserEntryPassword(const std::string& userName); /** @brief The IPMI call to reuse password entry for the renamed user * to another one * * @param[in] userName - user name which has to be renamed * @param[in] newUserName - new user name * * @return 0 on success, non-zero otherwise. */ Cc ipmiRenameUserEntryPassword(const std::string& userName, const std::string& newUserName); /** @brief determines valid userId * * @param[in] userId - user id * * @return true if valid, false otherwise */ bool ipmiUserIsValidUserId(const uint8_t userId); /** @brief determines valid privilege level * * @param[in] priv - privilege level * * @return true if valid, false otherwise */ bool ipmiUserIsValidPrivilege(const uint8_t priv); /** @brief get user id corresponding to the user name * * @param[in] userName - user name * * @return userid. Will return 0xff if no user id found */ uint8_t ipmiUserGetUserId(const std::string& userName); /** @brief set's user name * * @param[in] userId - user id * @param[in] userName - user name * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserName(const uint8_t userId, const char* userName); /** @brief set user password * * @param[in] userId - user id * @param[in] userPassword - New Password * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserPassword(const uint8_t userId, const char* userPassword); /** @brief set special user password (non-ipmi accounts) * * @param[in] userName - user name * @param[in] userPassword - New Password * * @return ccSuccess for success, others for failure. */ Cc ipmiSetSpecialUserPassword(const std::string& userName, const std::string& userPassword); /** @brief get user name * * @param[in] userId - user id * @param[out] userName - user name * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetUserName(const uint8_t userId, std::string& userName); /** @brief provides available fixed, max, and enabled user counts * * @param[out] maxChUsers - max channel users * @param[out] enabledUsers - enabled user count * @param[out] fixedUsers - fixed user count * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetAllCounts(uint8_t& maxChUsers, uint8_t& enabledUsers, uint8_t& fixedUsers); /** @brief function to update user enabled state * * @param[in] userId - user id *..@param[in] state - state of the user to be updated, true - user enabled. * * @return ccSuccess for success, others for failure. */ Cc ipmiUserUpdateEnabledState(const uint8_t userId, const bool& state); /** @brief determines whether user is enabled * * @param[in] userId - user id *..@param[out] state - state of the user * * @return ccSuccess for success, others for failure. */ Cc ipmiUserCheckEnabled(const uint8_t userId, bool& state); /** @brief provides user privilege access data * * @param[in] userId - user id * @param[in] chNum - channel number * @param[out] privAccess - privilege access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetPrivilegeAccess(const uint8_t userId, const uint8_t chNum, PrivAccess& privAccess); /** @brief sets user privilege access data * * @param[in] userId - user id * @param[in] chNum - channel number * @param[in] privAccess - privilege access data * @param[in] otherPrivUpdate - flags to indicate other fields update * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetPrivilegeAccess(const uint8_t userId, const uint8_t chNum, const PrivAccess& privAccess, const bool& otherPrivUpdate); /** @brief check for user pam authentication. This is to determine, whether user * is already locked out for failed login attempt * * @param[in] username - username * @param[in] password - password * * @return status */ bool ipmiUserPamAuthenticate(std::string_view userName, std::string_view userPassword); /** @brief sets user payload access data * * @param[in] chNum - channel number * @param[in] operation - ENABLE / DISABLE operation * @param[in] userId - user id * @param[in] payloadAccess - payload access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserSetUserPayloadAccess(const uint8_t chNum, const uint8_t operation, const uint8_t userId, const PayloadAccess& payloadAccess); /** @brief provides user payload access data * * @param[in] chNum - channel number * @param[in] userId - user id * @param[out] payloadAccess - payload access data * * @return ccSuccess for success, others for failure. */ Cc ipmiUserGetUserPayloadAccess(const uint8_t chNum, const uint8_t userId, PayloadAccess& payloadAccess); } // namespace ipmi <|endoftext|>
<commit_before>/* Copyright (C) LinBox * * Author: Zhendong Wan * * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ /*! @file tests/test-smith-form-iliopoulos.C * @ingroup tests * @brief no doc. * @test no doc. */ //#include "linbox/field/ntl.h" //#include "linbox/field/modular.h" #include "linbox/field/PID-integer.h" #include "linbox/field/PIR-ntl-ZZ_p.h" #include "linbox/field/PIR-modular-int32.h" //#include "linbox/integer.h" #include "linbox/randiter/random-prime.h" //#include "linbox/algorithms/last-invariant-factor.h" #include "linbox/algorithms/smith-form-iliopoulos.h" #include "linbox/matrix/matrix-domain.h" //#include "linbox/algorithms/rational-solver.h" //#include <time.h> #include "linbox/util/commentator.h" //#include "linbox/vector/stream.h" #include "test-common.h" #include "linbox/algorithms/matrix-hom.h" #include "linbox/solutions/det.h" #include <iostream> #ifndef __LINBOX_HAVE_NTL #error "you can't compile this test without NTL enabled. Please make sure you configured Linbox with --with-ntl=path/to/ntl" #endif using namespace LinBox; template <class Ring> bool testRead(const Ring& R, string file) { BlasMatrix<Ring> A(R); BlasMatrixDomain<Ring> BMD(R); std::ifstream data(file); A.read(data); size_t m = A.rowdim(); size_t n = A.coldim(); BlasMatrix<Ring> U(R, m, m), V(R, n, n), B(R, m, n); /* random unimodular BMD.randomNonsingular(U); BMD.randomNonsingular(V); */ for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < m; ++j) U.setEntry(i, j, R.zero); U.setEntry(i, i, R.one); } for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) V.setEntry(i, j, R.zero); V.setEntry(i, i, R.one); } BMD.copy(B, A); BMD.mulin_left(B,V); BMD.mulin_right(U,B); SmithFormIliopoulos::smithFormIn (B); return BMD.areEqual(A, B); } template <class Ring> bool testRandom(const Ring& R, size_t n) { bool pass = true; commentator().start ("Testing Iloipoulos elimination:", "testRandom"); using namespace std; ostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION); BlasMatrixDomain<Ring> BMD(R); BlasMatrix<Ring> D(R, n, n), L(R, n, n), U(R, n, n), A(R,n,n); // D is Smith Form const int m = 16; int p[m] = {1,1,1,1,1,1,2, 2, 2, 4, 3, 3, 3, 5, 7, 101}; typename Ring::Element x, y; R.assign(x, R.one); if (n > 0) D.setEntry(0,0,x); for(size_t i = 1; i < n; ++i){ R.init(y, p[rand()%m]); D.setEntry(i,i, R.mulin(x, y)); } if (n > 0) D.setEntry(n-1,n-1, R.zero); // L and U are random unit triangular. for (size_t i = 0; i < n; ++ i) { for (size_t j = 0; j < i; ++ j) { L.setEntry(i,j, R.init(x, rand() % 10)); U.setEntry(j,i, R.init(x, rand() % 10)); } L.setEntry(i,i, R.one); U.setEntry(i,i, R.one); } // A is ULDU BMD.mul(A, U, L); BMD.mulin_left(A, D); BMD.mulin_left(A, U); D.write( report << "Smith form matrix:\n " ) << endl; A.write( report << "input matrix:\n " ) << endl; // SmithFormIliopoulos::smithFormIn (A); // A.write( report << "smith of input matrix direct:\n " ) << endl; report << "Using PIRModular<int32_t>\n"; typename Ring::Element d; R.init(d,16*101);//16*101*5*7*9); for (int i = 0; i < n-1; ++i) R.mulin(d, D.getEntry(x, i, i)); R.write(report << "modulus: ", d) << endl; //det(d, D); //PIRModular<int32_t> Rd( (int32_t)(s % LINBOX_MAX_MODULUS)); PIRModular<int32_t> Rp( (int32_t)d); BlasMatrix<PIRModular<int32_t> > Ap(Rp, n, n), Dp(Rp, n, n); MatrixHom::map (Ap, A); SmithFormIliopoulos::smithFormIn (Ap); Ap.write( report << "Computed Smith form: \n") << endl; MatrixHom::map (Dp, D); BlasMatrixDomain<PIRModular<int32_t> > BMDp(Rp); pass = pass and BMDp.areEqual(Dp, Ap); commentator().stop (MSG_STATUS (pass), (const char *) 0, "testRandom"); return pass; } int main(int argc, char** argv) { using namespace LinBox; bool pass = true; static size_t n = 2; static Argument args[] = { { 'n', "-n N", "Set order of test matrices to N.", TYPE_INT, &n }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); commentator().start("Ilioloulos Smith Form test suite", "Ilioloulos"); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5); PID_integer R; // Ring of integers //NTL_ZZ R; if (!testRandom(R, n)) pass = false; // if (!testRead(R, "data/Ismith.mat")) pass = false; commentator().stop("Ilioloulos Smith Form test suite"); return pass ? 0 : -1; } // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <commit_msg>unsigned<commit_after>/* Copyright (C) LinBox * * Author: Zhendong Wan * * * ========LICENCE======== * This file is part of the library LinBox. * * LinBox 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 * ========LICENCE======== */ /*! @file tests/test-smith-form-iliopoulos.C * @ingroup tests * @brief no doc. * @test no doc. */ //#include "linbox/field/ntl.h" //#include "linbox/field/modular.h" #include "linbox/field/PID-integer.h" #include "linbox/field/PIR-ntl-ZZ_p.h" #include "linbox/field/PIR-modular-int32.h" //#include "linbox/integer.h" #include "linbox/randiter/random-prime.h" //#include "linbox/algorithms/last-invariant-factor.h" #include "linbox/algorithms/smith-form-iliopoulos.h" #include "linbox/matrix/matrix-domain.h" //#include "linbox/algorithms/rational-solver.h" //#include <time.h> #include "linbox/util/commentator.h" //#include "linbox/vector/stream.h" #include "test-common.h" #include "linbox/algorithms/matrix-hom.h" #include "linbox/solutions/det.h" #include <iostream> #ifndef __LINBOX_HAVE_NTL #error "you can't compile this test without NTL enabled. Please make sure you configured Linbox with --with-ntl=path/to/ntl" #endif using namespace LinBox; template <class Ring> bool testRead(const Ring& R, string file) { BlasMatrix<Ring> A(R); BlasMatrixDomain<Ring> BMD(R); std::ifstream data(file); A.read(data); size_t m = A.rowdim(); size_t n = A.coldim(); BlasMatrix<Ring> U(R, m, m), V(R, n, n), B(R, m, n); /* random unimodular BMD.randomNonsingular(U); BMD.randomNonsingular(V); */ for (size_t i = 0; i < m; ++i) { for (size_t j = 0; j < m; ++j) U.setEntry(i, j, R.zero); U.setEntry(i, i, R.one); } for (size_t i = 0; i < n; ++i) { for (size_t j = 0; j < n; ++j) V.setEntry(i, j, R.zero); V.setEntry(i, i, R.one); } BMD.copy(B, A); BMD.mulin_left(B,V); BMD.mulin_right(U,B); SmithFormIliopoulos::smithFormIn (B); return BMD.areEqual(A, B); } template <class Ring> bool testRandom(const Ring& R, size_t n) { bool pass = true; commentator().start ("Testing Iloipoulos elimination:", "testRandom"); using namespace std; ostream &report = commentator().report (Commentator::LEVEL_IMPORTANT, INTERNAL_DESCRIPTION); BlasMatrixDomain<Ring> BMD(R); BlasMatrix<Ring> D(R, n, n), L(R, n, n), U(R, n, n), A(R,n,n); // D is Smith Form const int m = 16; int p[m] = {1,1,1,1,1,1,2, 2, 2, 4, 3, 3, 3, 5, 7, 101}; typename Ring::Element x, y; R.assign(x, R.one); if (n > 0) D.setEntry(0,0,x); for(size_t i = 1; i < n; ++i){ R.init(y, p[rand()%m]); D.setEntry(i,i, R.mulin(x, y)); } if (n > 0) D.setEntry(n-1,n-1, R.zero); // L and U are random unit triangular. for (size_t i = 0; i < n; ++ i) { for (size_t j = 0; j < i; ++ j) { L.setEntry(i,j, R.init(x, rand() % 10)); U.setEntry(j,i, R.init(x, rand() % 10)); } L.setEntry(i,i, R.one); U.setEntry(i,i, R.one); } // A is ULDU BMD.mul(A, U, L); BMD.mulin_left(A, D); BMD.mulin_left(A, U); D.write( report << "Smith form matrix:\n " ) << endl; A.write( report << "input matrix:\n " ) << endl; // SmithFormIliopoulos::smithFormIn (A); // A.write( report << "smith of input matrix direct:\n " ) << endl; report << "Using PIRModular<int32_t>\n"; typename Ring::Element d; R.init(d,16*101);//16*101*5*7*9); for (size_t i = 0; i < n-1; ++i) R.mulin(d, D.getEntry(x, i, i)); R.write(report << "modulus: ", d) << endl; //det(d, D); //PIRModular<int32_t> Rd( (int32_t)(s % LINBOX_MAX_MODULUS)); PIRModular<int32_t> Rp( (int32_t)d); BlasMatrix<PIRModular<int32_t> > Ap(Rp, n, n), Dp(Rp, n, n); MatrixHom::map (Ap, A); SmithFormIliopoulos::smithFormIn (Ap); Ap.write( report << "Computed Smith form: \n") << endl; MatrixHom::map (Dp, D); BlasMatrixDomain<PIRModular<int32_t> > BMDp(Rp); pass = pass and BMDp.areEqual(Dp, Ap); commentator().stop (MSG_STATUS (pass), (const char *) 0, "testRandom"); return pass; } int main(int argc, char** argv) { using namespace LinBox; bool pass = true; static size_t n = 2; static Argument args[] = { { 'n', "-n N", "Set order of test matrices to N.", TYPE_INT, &n }, END_OF_ARGUMENTS }; parseArguments (argc, argv, args); commentator().start("Ilioloulos Smith Form test suite", "Ilioloulos"); commentator().getMessageClass (INTERNAL_DESCRIPTION).setMaxDepth (5); PID_integer R; // Ring of integers //NTL_ZZ R; if (!testRandom(R, n)) pass = false; // if (!testRead(R, "data/Ismith.mat")) pass = false; commentator().stop("Ilioloulos Smith Form test suite"); return pass ? 0 : -1; } // Local Variables: // mode: C++ // tab-width: 8 // indent-tabs-mode: nil // c-basic-offset: 8 // End: // vim:sts=8:sw=8:ts=8:noet:sr:cino=>s,f0,{0,g0,(0,\:0,t0,+0,=s <|endoftext|>
<commit_before>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2019 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * XDC commands * * This plugin operates on the existing design and modifies its structure * based on the content of the XDC (Xilinx Design Constraints) file. * Since the XDC file consists of Tcl commands it is read using Yosys's * Tcl interpreter and processed by the new XDC commands imported to the * Tcl interpreter. */ #include <cassert> #include "kernel/register.h" #include "kernel/rtlil.h" #include "kernel/log.h" #include "libs/json11/json11.hpp" #include "../bank_tiles.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN enum class SetPropertyOptions { INTERNAL_VREF }; const std::unordered_map<std::string, SetPropertyOptions> set_property_options_map = { {"INTERNAL_VREF", SetPropertyOptions::INTERNAL_VREF} }; void register_in_tcl_interpreter(const std::string& command) { Tcl_Interp* interp = yosys_get_tcl_interp(); std::string tcl_script = stringf("proc %s args { return [yosys %s {*}$args] }", command.c_str(), command.c_str()); Tcl_Eval(interp, tcl_script.c_str()); } struct GetPorts : public Pass { GetPorts() : Pass("get_ports", "Print matching ports") { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_ports <port_name> \n"); log("\n"); log("Get matching ports\n"); log("\n"); log("Print the output to stdout too. This is useful when all Yosys is executed\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { std::string text; for (auto& arg : args) { text += arg + ' '; } if (!text.empty()) { text.resize(text.size()-1); } log("%s\n", text.c_str()); } }; struct GetIOBanks : public Pass { GetIOBanks(std::function<const BankTilesMap&()> get_bank_tiles) : Pass("get_iobanks", "Set IO Bank number") , get_bank_tiles(get_bank_tiles) { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_iobanks <bank_number>\n"); log("\n"); log("Get IO Bank number\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("%s: Missing bank number.\n", pass_name.c_str()); } auto bank_tiles = get_bank_tiles(); if (bank_tiles.count(std::atoi(args[1].c_str())) == 0) { log_cmd_error("%s:Bank number %s is not present in the target device.\n", args[1].c_str(), pass_name.c_str()); } Tcl_Interp *interp = yosys_get_tcl_interp(); Tcl_SetResult(interp, const_cast<char*>(args[1].c_str()), NULL); log("%s\n", args[1].c_str()); } std::function<const BankTilesMap&()> get_bank_tiles; }; struct SetProperty : public Pass { SetProperty(std::function<const BankTilesMap&()> get_bank_tiles) : Pass("set_property", "Set a given property") , get_bank_tiles(get_bank_tiles) { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" set_property PROPERTY VALUE OBJECT\n"); log("\n"); log("Set the given property to the specified value on an object\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE { if (design->top_module() == nullptr) { log_cmd_error("No top module detected\n"); } std::string option(args[1]); if (set_property_options_map.count(option) == 0) { log_warning("set_property: %s option is currently not supported\n", option.c_str()); return; } switch (set_property_options_map.at(option)) { case SetPropertyOptions::INTERNAL_VREF: process_vref(std::vector<std::string>(args.begin() + 2, args.end()), design); break; default: assert(false); } } void process_vref(std::vector<std::string> args, RTLIL::Design* design) { if (args.size() < 2) { log_error("set_property INTERNAL_VREF: Incorrect number of arguments.\n"); } int iobank = std::atoi(args[1].c_str()); auto bank_tiles = get_bank_tiles(); if (bank_tiles.count(iobank) == 0) { log_cmd_error("set_property INTERNAL_VREF: Invalid IO bank.\n"); } int internal_vref = 1000 * std::atof(args[0].c_str()); if (internal_vref != 600 && internal_vref != 675 && internal_vref != 750 && internal_vref != 900) { log("set_property INTERNAL_VREF: Incorrect INTERNAL_VREF value\n"); return; } // Create a new BANK module if it hasn't been created so far RTLIL::Module* top_module = design->top_module(); if (!design->has(ID(BANK))) { std::string fasm_extra_modules_dir(proc_share_dirname() + "/plugins/fasm_extra_modules"); Pass::call(design, "read_verilog " + fasm_extra_modules_dir + "/BANK.v"); } // Set parameters on a new bank instance or update an existing one char bank_cell_name[16]; snprintf(bank_cell_name, 16, "\\bank_cell_%d", iobank); RTLIL::Cell* bank_cell = top_module->cell(RTLIL::IdString(bank_cell_name)); if (!bank_cell) { bank_cell = top_module->addCell(RTLIL::IdString(bank_cell_name), ID(BANK)); } bank_cell->setParam(ID(FASM_EXTRA), RTLIL::Const("INTERNAL_VREF")); bank_cell->setParam(ID(NUMBER), RTLIL::Const(iobank)); bank_cell->setParam(ID(INTERNAL_VREF), RTLIL::Const(internal_vref)); } std::function<const BankTilesMap&()> get_bank_tiles; }; struct ReadXdc : public Frontend { ReadXdc() : Frontend("xdc", "Read XDC file") , GetIOBanks(std::bind(&ReadXdc::get_bank_tiles, this)) , SetProperty(std::bind(&ReadXdc::get_bank_tiles, this)) {} void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" read_xdc -part_json <part_json_filename> <filename>\n"); log("\n"); log("Read XDC file.\n"); log("\n"); } void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("Missing script file.\n"); } Tcl_Interp *interp = yosys_get_tcl_interp(); size_t argidx = 1; if (args[argidx] == "-part_json" && argidx + 1 < args.size()) { bank_tiles = ::get_bank_tiles(args[++argidx]); argidx++; } extra_args(f, filename, args, argidx); std::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()}; log("%s\n", content.c_str()); if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) { log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp)); } } const BankTilesMap& get_bank_tiles() { return bank_tiles; } BankTilesMap bank_tiles; GetPorts GetPorts; GetIOBanks GetIOBanks; SetProperty SetProperty; } ReadXdc; struct GetBankTiles : public Pass { GetBankTiles() : Pass("get_bank_tiles", "Inspect IO Bank tiles") { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_bank_tiles <part_json_file>\n"); log("\n"); log("Inspect IO Bank tiles for the specified part based on the provided JSON file.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("Missing JSON file.\n"); } // Check if the part has the specified bank auto bank_tiles = get_bank_tiles(args[1]); if (bank_tiles.size()) { log("Available bank tiles:\n"); for (auto bank : bank_tiles) { log("Bank: %d, Tile: %s\n", bank.first, bank.second.c_str()); } log("\n"); } else { log("No bank tiles available.\n"); } } } GetBankTiles; PRIVATE_NAMESPACE_END <commit_msg>XDC: Clear bank_tiles if json_part not provided<commit_after>/* * yosys -- Yosys Open SYnthesis Suite * * Copyright (C) 2012 Clifford Wolf <clifford@clifford.at> * Copyright (C) 2019 The Symbiflow Authors * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. * * --- * * XDC commands * * This plugin operates on the existing design and modifies its structure * based on the content of the XDC (Xilinx Design Constraints) file. * Since the XDC file consists of Tcl commands it is read using Yosys's * Tcl interpreter and processed by the new XDC commands imported to the * Tcl interpreter. */ #include <cassert> #include "kernel/register.h" #include "kernel/rtlil.h" #include "kernel/log.h" #include "libs/json11/json11.hpp" #include "../bank_tiles.h" USING_YOSYS_NAMESPACE PRIVATE_NAMESPACE_BEGIN enum class SetPropertyOptions { INTERNAL_VREF }; const std::unordered_map<std::string, SetPropertyOptions> set_property_options_map = { {"INTERNAL_VREF", SetPropertyOptions::INTERNAL_VREF} }; void register_in_tcl_interpreter(const std::string& command) { Tcl_Interp* interp = yosys_get_tcl_interp(); std::string tcl_script = stringf("proc %s args { return [yosys %s {*}$args] }", command.c_str(), command.c_str()); Tcl_Eval(interp, tcl_script.c_str()); } struct GetPorts : public Pass { GetPorts() : Pass("get_ports", "Print matching ports") { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_ports <port_name> \n"); log("\n"); log("Get matching ports\n"); log("\n"); log("Print the output to stdout too. This is useful when all Yosys is executed\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { std::string text; for (auto& arg : args) { text += arg + ' '; } if (!text.empty()) { text.resize(text.size()-1); } log("%s\n", text.c_str()); } }; struct GetIOBanks : public Pass { GetIOBanks(std::function<const BankTilesMap&()> get_bank_tiles) : Pass("get_iobanks", "Set IO Bank number") , get_bank_tiles(get_bank_tiles) { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_iobanks <bank_number>\n"); log("\n"); log("Get IO Bank number\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("%s: Missing bank number.\n", pass_name.c_str()); } auto bank_tiles = get_bank_tiles(); if (bank_tiles.count(std::atoi(args[1].c_str())) == 0) { log_cmd_error("%s:Bank number %s is not present in the target device.\n", args[1].c_str(), pass_name.c_str()); } Tcl_Interp *interp = yosys_get_tcl_interp(); Tcl_SetResult(interp, const_cast<char*>(args[1].c_str()), NULL); log("%s\n", args[1].c_str()); } std::function<const BankTilesMap&()> get_bank_tiles; }; struct SetProperty : public Pass { SetProperty(std::function<const BankTilesMap&()> get_bank_tiles) : Pass("set_property", "Set a given property") , get_bank_tiles(get_bank_tiles) { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" set_property PROPERTY VALUE OBJECT\n"); log("\n"); log("Set the given property to the specified value on an object\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* design) YS_OVERRIDE { if (design->top_module() == nullptr) { log_cmd_error("No top module detected\n"); } std::string option(args[1]); if (set_property_options_map.count(option) == 0) { log_warning("set_property: %s option is currently not supported\n", option.c_str()); return; } switch (set_property_options_map.at(option)) { case SetPropertyOptions::INTERNAL_VREF: process_vref(std::vector<std::string>(args.begin() + 2, args.end()), design); break; default: assert(false); } } void process_vref(std::vector<std::string> args, RTLIL::Design* design) { if (args.size() < 2) { log_error("set_property INTERNAL_VREF: Incorrect number of arguments.\n"); } int iobank = std::atoi(args[1].c_str()); auto bank_tiles = get_bank_tiles(); if (bank_tiles.count(iobank) == 0) { log_cmd_error("set_property INTERNAL_VREF: Invalid IO bank.\n"); } int internal_vref = 1000 * std::atof(args[0].c_str()); if (internal_vref != 600 && internal_vref != 675 && internal_vref != 750 && internal_vref != 900) { log("set_property INTERNAL_VREF: Incorrect INTERNAL_VREF value\n"); return; } // Create a new BANK module if it hasn't been created so far RTLIL::Module* top_module = design->top_module(); if (!design->has(ID(BANK))) { std::string fasm_extra_modules_dir(proc_share_dirname() + "/plugins/fasm_extra_modules"); Pass::call(design, "read_verilog " + fasm_extra_modules_dir + "/BANK.v"); } // Set parameters on a new bank instance or update an existing one char bank_cell_name[16]; snprintf(bank_cell_name, 16, "\\bank_cell_%d", iobank); RTLIL::Cell* bank_cell = top_module->cell(RTLIL::IdString(bank_cell_name)); if (!bank_cell) { bank_cell = top_module->addCell(RTLIL::IdString(bank_cell_name), ID(BANK)); } bank_cell->setParam(ID(FASM_EXTRA), RTLIL::Const("INTERNAL_VREF")); bank_cell->setParam(ID(NUMBER), RTLIL::Const(iobank)); bank_cell->setParam(ID(INTERNAL_VREF), RTLIL::Const(internal_vref)); } std::function<const BankTilesMap&()> get_bank_tiles; }; struct ReadXdc : public Frontend { ReadXdc() : Frontend("xdc", "Read XDC file") , GetIOBanks(std::bind(&ReadXdc::get_bank_tiles, this)) , SetProperty(std::bind(&ReadXdc::get_bank_tiles, this)) {} void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" read_xdc -part_json <part_json_filename> <filename>\n"); log("\n"); log("Read XDC file.\n"); log("\n"); } void execute(std::istream *&f, std::string filename, std::vector<std::string> args, RTLIL::Design*) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("Missing script file.\n"); } Tcl_Interp *interp = yosys_get_tcl_interp(); size_t argidx = 1; bank_tiles.clear(); if (args[argidx] == "-part_json" && argidx + 1 < args.size()) { bank_tiles = ::get_bank_tiles(args[++argidx]); argidx++; } extra_args(f, filename, args, argidx); std::string content{std::istreambuf_iterator<char>(*f), std::istreambuf_iterator<char>()}; log("%s\n", content.c_str()); if (Tcl_EvalFile(interp, args[argidx].c_str()) != TCL_OK) { log_cmd_error("TCL interpreter returned an error: %s\n", Tcl_GetStringResult(interp)); } } const BankTilesMap& get_bank_tiles() { return bank_tiles; } BankTilesMap bank_tiles; GetPorts GetPorts; GetIOBanks GetIOBanks; SetProperty SetProperty; } ReadXdc; struct GetBankTiles : public Pass { GetBankTiles() : Pass("get_bank_tiles", "Inspect IO Bank tiles") { register_in_tcl_interpreter(pass_name); } void help() YS_OVERRIDE { // |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---| log("\n"); log(" get_bank_tiles <part_json_file>\n"); log("\n"); log("Inspect IO Bank tiles for the specified part based on the provided JSON file.\n"); log("\n"); } void execute(std::vector<std::string> args, RTLIL::Design* ) YS_OVERRIDE { if (args.size() < 2) { log_cmd_error("Missing JSON file.\n"); } // Check if the part has the specified bank auto bank_tiles = get_bank_tiles(args[1]); if (bank_tiles.size()) { log("Available bank tiles:\n"); for (auto bank : bank_tiles) { log("Bank: %d, Tile: %s\n", bank.first, bank.second.c_str()); } log("\n"); } else { log("No bank tiles available.\n"); } } } GetBankTiles; PRIVATE_NAMESPACE_END <|endoftext|>
<commit_before>/******************************************************************************* Module: FGGain.cpp Author: Date started: ------------- Copyright (C) 2000 ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- ******************************************************************************** COMMENTS, REFERENCES, and NOTES ******************************************************************************** ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGGain.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ // ***************************************************************************** // Function: Constructor // Purpose: Builds a Gain-type of FCS component. // Parameters: void // Comments: Types are PURE_GAIN, SCHEDULED_GAIN, and AEROSURFACE_SCALE FGGain::FGGain(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs), AC_cfg(AC_cfg) { string token; string strScheduledBy; lookup = NULL; Schedule.clear(); Gain = 1.000; Min = Max = 0; ScheduledBy = FG_NONE; Type = AC_cfg->GetValue("TYPE"); Name = AC_cfg->GetValue("NAME"); AC_cfg->GetNextConfigLine(); while ((token = AC_cfg->GetValue()) != "/COMPONENT") { *AC_cfg >> token; if (token == "ID") { *AC_cfg >> ID; cout << " ID: " << ID << endl; } else if (token == "INPUT") { token = AC_cfg->GetValue("INPUT"); cout << " INPUT: " << token << endl; if (token.find("FG_") != token.npos) { *AC_cfg >> token; InputIdx = fcs->GetState()->GetParameterIndex(token); InputType = itPilotAC; } else { *AC_cfg >> InputIdx; InputType = itFCS; } } else if (token == "GAIN") { *AC_cfg >> Gain; cout << " GAIN: " << Gain << endl; } else if (token == "MIN") { *AC_cfg >> Min; cout << " MIN: " << Min << endl; } else if (token == "MAX") { *AC_cfg >> Max; cout << " MAX: " << Max << endl; } else if (token == "SCHEDULED_BY") { *AC_cfg >> strScheduledBy; ScheduledBy = fcs->GetState()->GetParameterIndex(strScheduledBy); } else if (token == "OUTPUT") { IsOutput = true; *AC_cfg >> sOutputIdx; OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx); cout << " OUTPUT: " << sOutputIdx << endl; } else { AC_cfg->ResetLineIndexToZero(); lookup = new float[2]; *AC_cfg >> lookup[0] >> lookup[1]; Schedule.push_back(lookup); } } } // ***************************************************************************** // Function: Run // Purpose: // Parameters: void // Comments: bool FGGain::Run(void ) { float SchedGain = 1.0; FGFCSComponent::Run(); // call the base class for initialization of Input if (Type == "PURE_GAIN") { Output = Gain * Input; } else if (Type == "SCHEDULED_GAIN") { float LookupVal = fcs->GetState()->GetParameter(ScheduledBy); unsigned int last = Schedule.size()-1; float lowVal = Schedule[0][0], hiVal = Schedule[last][0]; float factor = 1.0; if (LookupVal <= lowVal) Output = Gain * Schedule[0][1]; else if (LookupVal >= hiVal) Output = Gain * Schedule[last][1]; else { for (unsigned int ctr = 1; ctr < last; ctr++) { if (LookupVal < Schedule[ctr][0]) { hiVal = Schedule[ctr][0]; lowVal = Schedule[ctr-1][0]; factor = (LookupVal - lowVal) / (hiVal - lowVal); SchedGain = Schedule[ctr-1][1] + factor*(Schedule[ctr][1] - Schedule[ctr-1][1]); Output = Gain * SchedGain * Input; break; } } } } else if (Type == "AEROSURFACE_SCALE") { if (Output >= 0.0) Output = Input * Max; else Output = Input * (-Min); Output *= Gain; } if (IsOutput) SetOutput(); return true; } <commit_msg>Adjustments to parameter retrieval in FGGain<commit_after>/******************************************************************************* Module: FGGain.cpp Author: Date started: ------------- Copyright (C) 2000 ------------- This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. Further information about the GNU General Public License can also be found on the world wide web at http://www.gnu.org. FUNCTIONAL DESCRIPTION -------------------------------------------------------------------------------- HISTORY -------------------------------------------------------------------------------- ******************************************************************************** COMMENTS, REFERENCES, and NOTES ******************************************************************************** ******************************************************************************** INCLUDES *******************************************************************************/ #include "FGGain.h" /******************************************************************************* ************************************ CODE ************************************** *******************************************************************************/ // ***************************************************************************** // Function: Constructor // Purpose: Builds a Gain-type of FCS component. // Parameters: void // Comments: Types are PURE_GAIN, SCHEDULED_GAIN, and AEROSURFACE_SCALE FGGain::FGGain(FGFCS* fcs, FGConfigFile* AC_cfg) : FGFCSComponent(fcs), AC_cfg(AC_cfg) { string token; string strScheduledBy; lookup = NULL; Schedule.clear(); Gain = 1.000; Min = Max = 0; ScheduledBy = FG_NONE; Type = AC_cfg->GetValue("TYPE"); Name = AC_cfg->GetValue("NAME"); AC_cfg->GetNextConfigLine(); while ((token = AC_cfg->GetValue()) != "/COMPONENT") { *AC_cfg >> token; if (token == "ID") { *AC_cfg >> ID; cout << " ID: " << ID << endl; } else if (token == "INPUT") { token = AC_cfg->GetValue("INPUT"); cout << " INPUT: " << token << endl; if (token.find("FG_") != token.npos) { *AC_cfg >> token; InputIdx = fcs->GetState()->GetParameterIndex(token); InputType = itPilotAC; } else { *AC_cfg >> InputIdx; InputType = itFCS; } } else if (token == "GAIN") { *AC_cfg >> Gain; cout << " GAIN: " << Gain << endl; } else if (token == "MIN") { *AC_cfg >> Min; cout << " MIN: " << Min << endl; } else if (token == "MAX") { *AC_cfg >> Max; cout << " MAX: " << Max << endl; } else if (token == "SCHEDULED_BY") { token = AC_cfg->GetValue("SCHEDULED_BY"); if (token.find("FG_") != token.npos) { *AC_cfg >> strScheduledBy; ScheduledBy = fcs->GetState()->GetParameterIndex(strScheduledBy); cout << " Scheduled by parameter: " << token << endl; } else { *AC_cfg >> ScheduledBy; cout << " Scheduled by FCS output: " << ScheduledBy << endl; } } else if (token == "OUTPUT") { IsOutput = true; *AC_cfg >> sOutputIdx; OutputIdx = fcs->GetState()->GetParameterIndex(sOutputIdx); cout << " OUTPUT: " << sOutputIdx << endl; } else { AC_cfg->ResetLineIndexToZero(); lookup = new float[2]; *AC_cfg >> lookup[0] >> lookup[1]; Schedule.push_back(lookup); } } } // ***************************************************************************** // Function: Run // Purpose: // Parameters: void // Comments: bool FGGain::Run(void ) { float SchedGain = 1.0; FGFCSComponent::Run(); // call the base class for initialization of Input if (Type == "PURE_GAIN") { Output = Gain * Input; } else if (Type == "SCHEDULED_GAIN") { float LookupVal = fcs->GetState()->GetParameter(ScheduledBy); unsigned int last = Schedule.size()-1; float lowVal = Schedule[0][0], hiVal = Schedule[last][0]; float factor = 1.0; if (LookupVal <= lowVal) Output = Gain * Schedule[0][1]; else if (LookupVal >= hiVal) Output = Gain * Schedule[last][1]; else { for (unsigned int ctr = 1; ctr < last; ctr++) { if (LookupVal < Schedule[ctr][0]) { hiVal = Schedule[ctr][0]; lowVal = Schedule[ctr-1][0]; factor = (LookupVal - lowVal) / (hiVal - lowVal); SchedGain = Schedule[ctr-1][1] + factor*(Schedule[ctr][1] - Schedule[ctr-1][1]); Output = Gain * SchedGain * Input; break; } } } } else if (Type == "AEROSURFACE_SCALE") { if (Output >= 0.0) Output = Input * Max; else Output = Input * (-Min); Output *= Gain; } if (IsOutput) SetOutput(); return true; } <|endoftext|>
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #define INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #include <basebmp/bitmapdevice.hxx> #include <basebmp/color.hxx> #include <vcl/sysdata.hxx> #include "salgdi.hxx" #include "sallayout.hxx" #ifdef IOS #include "quartz/salgdi.h" #include <premac.h> #include <Foundation/Foundation.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #endif class ServerFont; #ifdef IOS // To keep changes to the CoreText code shared with AOO to a minimum, // let's continue calling the SalGraphics subclass "AquaSalGraphics" even if it // is used by us also on iOS, where of course the term "Aqua" has no meaning at all. // (Note that even on OS X, using the term "Aqua" is a misunderstanding or obsolete.) #define SvpSalGraphics AquaSalGraphics #endif class SvpSalGraphics : public SalGraphics { #ifndef IOS basebmp::BitmapDeviceSharedPtr m_aDevice; basebmp::BitmapDeviceSharedPtr m_aOrigDevice; basebmp::BitmapDeviceSharedPtr m_aClipMap; bool m_bUseLineColor; basebmp::Color m_aLineColor; bool m_bUseFillColor; basebmp::Color m_aFillColor; basebmp::DrawMode m_aDrawMode; // These fields are used only when we use FreeType to draw into a // headless backend, i.e. not on iOS. basebmp::Color m_aTextColor; ServerFont* m_pServerFont[ MAX_FALLBACK ]; basebmp::Format m_eTextFmt; protected: basegfx::B2IVector GetSize() { return m_aOrigDevice->getSize(); } private: bool m_bClipSetup; struct ClipUndoHandle { SvpSalGraphics &m_rGfx; basebmp::BitmapDeviceSharedPtr m_aDevice; ClipUndoHandle( SvpSalGraphics *pGfx ) : m_rGfx( *pGfx ) {} ~ClipUndoHandle(); }; public: void setDevice( basebmp::BitmapDeviceSharedPtr& rDevice ); #else friend class CTLayout; CGLayerRef mxLayer; // mirror AquaSalVirtualDevice::mbForeignContext for SvpSalGraphics objects related to such bool mbForeignContext; CGContextRef mrContext; class XorEmulation* mpXorEmulation; int mnXorMode; // 0: off 1: on 2: invert only int mnWidth; int mnHeight; int mnBitmapDepth; // zero unless bitmap /// path representing current clip region CGMutablePathRef mxClipPath; /// Drawing colors /// pen color RGBA RGBAColor maLineColor; /// brush color RGBA RGBAColor maFillColor; // Device Font settings const CoreTextFontData* mpFontData; CoreTextStyle* mpTextStyle; RGBAColor maTextColor; /// allows text to be rendered without antialiasing bool mbNonAntialiasedText; /// is this a printer graphics bool mbPrinter; /// is this a virtual device graphics bool mbVirDev; #endif protected: Region m_aClipRegion; protected: virtual bool drawAlphaBitmap( const SalTwoRect&, const SalBitmap& rSourceBitmap, const SalBitmap& rAlphaBitmap ); virtual bool drawTransformedBitmap( const basegfx::B2DPoint& rNull, const basegfx::B2DPoint& rX, const basegfx::B2DPoint& rY, const SalBitmap& rSourceBitmap, const SalBitmap* pAlphaBitmap); virtual bool drawAlphaRect( long nX, long nY, long nWidth, long nHeight, sal_uInt8 nTransparency ); public: SvpSalGraphics(); virtual ~SvpSalGraphics(); virtual void GetResolution( sal_Int32& rDPIX, sal_Int32& rDPIY ); virtual sal_uInt16 GetBitCount() const; virtual long GetGraphicsWidth() const; virtual void ResetClipRegion(); virtual bool setClipRegion( const Region& ); virtual void SetLineColor(); virtual void SetLineColor( SalColor nSalColor ); virtual void SetFillColor(); virtual void SetFillColor( SalColor nSalColor ); virtual void SetXORMode( bool bSet, bool ); virtual void SetROPLineColor( SalROPColor nROPColor ); virtual void SetROPFillColor( SalROPColor nROPColor ); virtual void SetTextColor( SalColor nSalColor ); virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ); virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ); virtual const ImplFontCharMap* GetImplFontCharMap() const; virtual bool GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const; virtual void GetDevFontList( PhysicalFontCollection* ); virtual void ClearDevFontCache(); virtual bool AddTempDevFont( PhysicalFontCollection*, const OUString& rFileURL, const OUString& rFontName ); virtual bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIds, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ); virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ); virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ); virtual void FreeEmbedFontData( const void* pData, long nDataLen ); virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ); virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ); virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ); virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ); virtual void DrawServerFontLayout( const ServerFontLayout& ); virtual bool supportsOperation( OutDevSupportType ) const; virtual void drawPixel( long nX, long nY ); virtual void drawPixel( long nX, long nY, SalColor nSalColor ); virtual void drawLine( long nX1, long nY1, long nX2, long nY2 ); virtual void drawRect( long nX, long nY, long nWidth, long nHeight ); virtual bool drawPolyPolygon( const ::basegfx::B2DPolyPolygon&, double fTransparency ); virtual bool drawPolyLine( const ::basegfx::B2DPolygon&, double fTransparency, const ::basegfx::B2DVector& rLineWidths, basegfx::B2DLineJoin, com::sun::star::drawing::LineCap); virtual void drawPolyLine( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolygon( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolyPolygon( sal_uInt32 nPoly, const sal_uInt32* pPoints, PCONSTSALPOINT* pPtAry ); virtual bool drawPolyLineBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual bool drawPolygonBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual bool drawPolyPolygonBezier( sal_uInt32 nPoly, const sal_uInt32* pPoints, const SalPoint* const* pPtAry, const sal_uInt8* const* pFlgAry ); virtual void copyArea( long nDestX, long nDestY, long nSrcX, long nSrcY, long nSrcWidth, long nSrcHeight, sal_uInt16 nFlags ); virtual void copyBits( const SalTwoRect& rPosAry, SalGraphics* pSrcGraphics ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nTransparentColor ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, const SalBitmap& rTransparentBitmap ); virtual void drawMask( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nMaskColor ); virtual SalBitmap* getBitmap( long nX, long nY, long nWidth, long nHeight ); virtual SalColor getPixel( long nX, long nY ); virtual void invert( long nX, long nY, long nWidth, long nHeight, SalInvert nFlags ); virtual void invert( sal_uInt32 nPoints, const SalPoint* pPtAry, SalInvert nFlags ); virtual bool drawEPS( long nX, long nY, long nWidth, long nHeight, void* pPtr, sal_uLong nSize ); virtual SystemGraphicsData GetGraphicsData() const; virtual SystemFontData GetSysFontData( int nFallbacklevel ) const; #ifdef IOS void SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext, int = 0 ); bool CheckContext(); CGContextRef GetContext(); bool GetRawFontData( const PhysicalFontFace* pFontData, std::vector<unsigned char>& rBuffer, bool* pJustCFF ); void RefreshRect( const CGRect& ) { }; void RefreshRect(float lX, float lY, float lWidth, float lHeight); void SetState(); void UnsetState(); void InvalidateContext(); bool IsPenVisible() const { return maLineColor.IsVisible(); } bool IsBrushVisible() const { return maFillColor.IsVisible(); } void ImplDrawPixel( long nX, long nY, const RGBAColor& ); // helper to draw single pixels CGPoint* makeCGptArray(sal_uLong nPoints, const SalPoint* pPtAry); bool IsFlipped() const { return false; } void ApplyXorContext(); void Pattern50Fill(); #endif }; #endif // INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <commit_msg>Return two accidentally removed member functions<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ #ifndef INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #define INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX #include <basebmp/bitmapdevice.hxx> #include <basebmp/color.hxx> #include <vcl/sysdata.hxx> #include "salgdi.hxx" #include "sallayout.hxx" #ifdef IOS #include "quartz/salgdi.h" #include <premac.h> #include <Foundation/Foundation.h> #include <CoreGraphics/CoreGraphics.h> #include <postmac.h> #endif class ServerFont; #ifdef IOS // To keep changes to the CoreText code shared with AOO to a minimum, // let's continue calling the SalGraphics subclass "AquaSalGraphics" even if it // is used by us also on iOS, where of course the term "Aqua" has no meaning at all. // (Note that even on OS X, using the term "Aqua" is a misunderstanding or obsolete.) #define SvpSalGraphics AquaSalGraphics #endif class SvpSalGraphics : public SalGraphics { #ifndef IOS basebmp::BitmapDeviceSharedPtr m_aDevice; basebmp::BitmapDeviceSharedPtr m_aOrigDevice; basebmp::BitmapDeviceSharedPtr m_aClipMap; bool m_bUseLineColor; basebmp::Color m_aLineColor; bool m_bUseFillColor; basebmp::Color m_aFillColor; basebmp::DrawMode m_aDrawMode; // These fields are used only when we use FreeType to draw into a // headless backend, i.e. not on iOS. basebmp::Color m_aTextColor; ServerFont* m_pServerFont[ MAX_FALLBACK ]; basebmp::Format m_eTextFmt; protected: basegfx::B2IVector GetSize() { return m_aOrigDevice->getSize(); } private: bool m_bClipSetup; struct ClipUndoHandle { SvpSalGraphics &m_rGfx; basebmp::BitmapDeviceSharedPtr m_aDevice; ClipUndoHandle( SvpSalGraphics *pGfx ) : m_rGfx( *pGfx ) {} ~ClipUndoHandle(); }; bool isClippedSetup( const basegfx::B2IBox &aRange, ClipUndoHandle &rUndo ); void ensureClip(); public: void setDevice( basebmp::BitmapDeviceSharedPtr& rDevice ); #else friend class CTLayout; CGLayerRef mxLayer; // mirror AquaSalVirtualDevice::mbForeignContext for SvpSalGraphics objects related to such bool mbForeignContext; CGContextRef mrContext; class XorEmulation* mpXorEmulation; int mnXorMode; // 0: off 1: on 2: invert only int mnWidth; int mnHeight; int mnBitmapDepth; // zero unless bitmap /// path representing current clip region CGMutablePathRef mxClipPath; /// Drawing colors /// pen color RGBA RGBAColor maLineColor; /// brush color RGBA RGBAColor maFillColor; // Device Font settings const CoreTextFontData* mpFontData; CoreTextStyle* mpTextStyle; RGBAColor maTextColor; /// allows text to be rendered without antialiasing bool mbNonAntialiasedText; /// is this a printer graphics bool mbPrinter; /// is this a virtual device graphics bool mbVirDev; #endif protected: Region m_aClipRegion; protected: virtual bool drawAlphaBitmap( const SalTwoRect&, const SalBitmap& rSourceBitmap, const SalBitmap& rAlphaBitmap ); virtual bool drawTransformedBitmap( const basegfx::B2DPoint& rNull, const basegfx::B2DPoint& rX, const basegfx::B2DPoint& rY, const SalBitmap& rSourceBitmap, const SalBitmap* pAlphaBitmap); virtual bool drawAlphaRect( long nX, long nY, long nWidth, long nHeight, sal_uInt8 nTransparency ); public: SvpSalGraphics(); virtual ~SvpSalGraphics(); virtual void GetResolution( sal_Int32& rDPIX, sal_Int32& rDPIY ); virtual sal_uInt16 GetBitCount() const; virtual long GetGraphicsWidth() const; virtual void ResetClipRegion(); virtual bool setClipRegion( const Region& ); virtual void SetLineColor(); virtual void SetLineColor( SalColor nSalColor ); virtual void SetFillColor(); virtual void SetFillColor( SalColor nSalColor ); virtual void SetXORMode( bool bSet, bool ); virtual void SetROPLineColor( SalROPColor nROPColor ); virtual void SetROPFillColor( SalROPColor nROPColor ); virtual void SetTextColor( SalColor nSalColor ); virtual sal_uInt16 SetFont( FontSelectPattern*, int nFallbackLevel ); virtual void GetFontMetric( ImplFontMetricData*, int nFallbackLevel ); virtual const ImplFontCharMap* GetImplFontCharMap() const; virtual bool GetImplFontCapabilities(vcl::FontCapabilities &rFontCapabilities) const; virtual void GetDevFontList( PhysicalFontCollection* ); virtual void ClearDevFontCache(); virtual bool AddTempDevFont( PhysicalFontCollection*, const OUString& rFileURL, const OUString& rFontName ); virtual bool CreateFontSubset( const OUString& rToFile, const PhysicalFontFace*, sal_GlyphId* pGlyphIds, sal_uInt8* pEncoding, sal_Int32* pWidths, int nGlyphs, FontSubsetInfo& rInfo ); virtual const Ucs2SIntMap* GetFontEncodingVector( const PhysicalFontFace*, const Ucs2OStrMap** ppNonEncoded ); virtual const void* GetEmbedFontData( const PhysicalFontFace*, const sal_Ucs* pUnicodes, sal_Int32* pWidths, FontSubsetInfo& rInfo, long* pDataLen ); virtual void FreeEmbedFontData( const void* pData, long nDataLen ); virtual void GetGlyphWidths( const PhysicalFontFace*, bool bVertical, Int32Vector& rWidths, Ucs2UIntMap& rUnicodeEnc ); virtual bool GetGlyphBoundRect( sal_GlyphId nIndex, Rectangle& ); virtual bool GetGlyphOutline( sal_GlyphId nIndex, ::basegfx::B2DPolyPolygon& ); virtual SalLayout* GetTextLayout( ImplLayoutArgs&, int nFallbackLevel ); virtual void DrawServerFontLayout( const ServerFontLayout& ); virtual bool supportsOperation( OutDevSupportType ) const; virtual void drawPixel( long nX, long nY ); virtual void drawPixel( long nX, long nY, SalColor nSalColor ); virtual void drawLine( long nX1, long nY1, long nX2, long nY2 ); virtual void drawRect( long nX, long nY, long nWidth, long nHeight ); virtual bool drawPolyPolygon( const ::basegfx::B2DPolyPolygon&, double fTransparency ); virtual bool drawPolyLine( const ::basegfx::B2DPolygon&, double fTransparency, const ::basegfx::B2DVector& rLineWidths, basegfx::B2DLineJoin, com::sun::star::drawing::LineCap); virtual void drawPolyLine( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolygon( sal_uInt32 nPoints, const SalPoint* pPtAry ); virtual void drawPolyPolygon( sal_uInt32 nPoly, const sal_uInt32* pPoints, PCONSTSALPOINT* pPtAry ); virtual bool drawPolyLineBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual bool drawPolygonBezier( sal_uInt32 nPoints, const SalPoint* pPtAry, const sal_uInt8* pFlgAry ); virtual bool drawPolyPolygonBezier( sal_uInt32 nPoly, const sal_uInt32* pPoints, const SalPoint* const* pPtAry, const sal_uInt8* const* pFlgAry ); virtual void copyArea( long nDestX, long nDestY, long nSrcX, long nSrcY, long nSrcWidth, long nSrcHeight, sal_uInt16 nFlags ); virtual void copyBits( const SalTwoRect& rPosAry, SalGraphics* pSrcGraphics ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nTransparentColor ); virtual void drawBitmap( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, const SalBitmap& rTransparentBitmap ); virtual void drawMask( const SalTwoRect& rPosAry, const SalBitmap& rSalBitmap, SalColor nMaskColor ); virtual SalBitmap* getBitmap( long nX, long nY, long nWidth, long nHeight ); virtual SalColor getPixel( long nX, long nY ); virtual void invert( long nX, long nY, long nWidth, long nHeight, SalInvert nFlags ); virtual void invert( sal_uInt32 nPoints, const SalPoint* pPtAry, SalInvert nFlags ); virtual bool drawEPS( long nX, long nY, long nWidth, long nHeight, void* pPtr, sal_uLong nSize ); virtual SystemGraphicsData GetGraphicsData() const; virtual SystemFontData GetSysFontData( int nFallbacklevel ) const; #ifdef IOS void SetVirDevGraphics( CGLayerRef xLayer, CGContextRef xContext, int = 0 ); bool CheckContext(); CGContextRef GetContext(); bool GetRawFontData( const PhysicalFontFace* pFontData, std::vector<unsigned char>& rBuffer, bool* pJustCFF ); void RefreshRect( const CGRect& ) { }; void RefreshRect(float lX, float lY, float lWidth, float lHeight); void SetState(); void UnsetState(); void InvalidateContext(); bool IsPenVisible() const { return maLineColor.IsVisible(); } bool IsBrushVisible() const { return maFillColor.IsVisible(); } void ImplDrawPixel( long nX, long nY, const RGBAColor& ); // helper to draw single pixels CGPoint* makeCGptArray(sal_uLong nPoints, const SalPoint* pPtAry); bool IsFlipped() const { return false; } void ApplyXorContext(); void Pattern50Fill(); #endif }; #endif // INCLUDED_VCL_INC_HEADLESS_SVPGDI_HXX /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ <|endoftext|>
<commit_before> #include <stdlib.h> /* srand, rand */ #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <unsupported/Eigen/SparseExtra> #ifdef _OPENMP #include <omp.h> #else #include <tbb/tbb.h> #endif #include "bpmf.h" using namespace std; using namespace Eigen; const int num_feat = 32; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; typedef SparseMatrix<double> SparseMatrixD; SparseMatrixD M, Mt, P; typedef Matrix<double, num_feat, 1> VectorNd; typedef Matrix<double, num_feat, num_feat> MatrixNNd; typedef Matrix<double, num_feat, Dynamic> MatrixNXd; VectorNd mu_u; VectorNd mu_m; MatrixNNd Lambda_u; MatrixNNd Lambda_m; MatrixNXd sample_u; MatrixNXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixNNd WI_u; const int b0_u = 2; const int df_u = num_feat; VectorNd mu0_u; MatrixNNd WI_m; const int b0_m = 2; const int df_m = num_feat; VectorNd mu0_m; void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixNXd(num_feat,M.rows()); sample_m = MatrixNXd(num_feat,M.cols()); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const MatrixNXd &sample_m, const MatrixNXd &sample_u, double mean_rating) { unsigned n = P.nonZeros(); unsigned correct = 0; double diff = .0; for (int k=0; k<P.outerSize(); ++k) for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) { double prediction = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << it.value() << endl; correct += (it.value() < log10(200)) == (prediction < log10(200)); diff += abs(it.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } double randn(double) { static mt19937 rng; static normal_distribution<> nd; return nd(rng); } void sample_movie(MatrixNXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixNXd &samples, int alpha, const VectorNd &mu_u, const MatrixNNd &Lambda_u) { int i = 0; MatrixNNd MM; MM.setZero(); VectorNd rr; rr.setZero(); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; auto col = samples.col(it.row()); MM += col * col.transpose(); rr += col * ((it.value() - mean_rating) * alpha); } auto MMs = alpha * MM; MatrixNNd covar = (Lambda_u + MMs).inverse(); auto U = Lambda_u * mu_u; auto mu = covar * (rr + U); MatrixNNd chol = covar.llt().matrixL(); auto r = VectorXd::NullaryExpr(num_feat, ptr_fun(randn)); s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixNXd sample_u(M.rows()); MatrixNXd sample_m(M.cols()); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = tick(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); const int num_m = M.cols(); const int num_u = M.rows(); #ifdef _OPENMP #pragma omp parallel for for(int mm=0; mm<num_m; ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu=0; uu<num_u; ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } #else tbb::parallel_for(0, num_m, [](int mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); }); tbb::parallel_for(0, num_u, [](int uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); }); #endif auto eval = eval_probe_vec(sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = tick(); auto elapsed = end - start; double samples_per_sec = (i + 1) * (M.rows() + M.cols()) / elapsed; printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { assert(argv[1] && argv[2] && "filename missing"); Eigen::initParallel(); loadMarket(M, argv[1]); Mt = M.transpose(); loadMarket(P, argv[2]); assert(M.nonZeros() > P.nonZeros()); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <commit_msg>c++: fix missing include<commit_after> #include <stdlib.h> /* srand, rand */ #include <iostream> #include <fstream> #include <string> #include <algorithm> #include <random> #include <unsupported/Eigen/SparseExtra> #ifdef _OPENMP #include <omp.h> #else #include <tbb/tbb.h> #endif #include "bpmf.h" using namespace std; using namespace Eigen; const int num_feat = 32; const int alpha = 2; const int nsims = 20; const int burnin = 5; double mean_rating = .0; typedef SparseMatrix<double> SparseMatrixD; SparseMatrixD M, Mt, P; typedef Matrix<double, num_feat, 1> VectorNd; typedef Matrix<double, num_feat, num_feat> MatrixNNd; typedef Matrix<double, num_feat, Dynamic> MatrixNXd; VectorNd mu_u; VectorNd mu_m; MatrixNNd Lambda_u; MatrixNNd Lambda_m; MatrixNXd sample_u; MatrixNXd sample_m; // parameters of Inv-Whishart distribution (see paper for details) MatrixNNd WI_u; const int b0_u = 2; const int df_u = num_feat; VectorNd mu0_u; MatrixNNd WI_m; const int b0_m = 2; const int df_m = num_feat; VectorNd mu0_m; void init() { mean_rating = M.sum() / M.nonZeros(); Lambda_u.setIdentity(); Lambda_m.setIdentity(); sample_u = MatrixNXd(num_feat,M.rows()); sample_m = MatrixNXd(num_feat,M.cols()); sample_u.setZero(); sample_m.setZero(); // parameters of Inv-Whishart distribution (see paper for details) WI_u.setIdentity(); mu0_u.setZero(); WI_m.setIdentity(); mu0_m.setZero(); } pair<double,double> eval_probe_vec(const MatrixNXd &sample_m, const MatrixNXd &sample_u, double mean_rating) { unsigned n = P.nonZeros(); unsigned correct = 0; double diff = .0; for (int k=0; k<P.outerSize(); ++k) for (SparseMatrix<double>::InnerIterator it(P,k); it; ++it) { double prediction = sample_m.col(it.col()).dot(sample_u.col(it.row())) + mean_rating; //cout << "prediction: " << prediction - mean_rating << " + " << mean_rating << " = " << prediction << endl; //cout << "actual: " << it.value() << endl; correct += (it.value() < log10(200)) == (prediction < log10(200)); diff += abs(it.value() - prediction); } return std::make_pair((double)correct / n, diff / n); } double randn(double) { static mt19937 rng; static normal_distribution<> nd; return nd(rng); } void sample_movie(MatrixNXd &s, int mm, const SparseMatrixD &mat, double mean_rating, const MatrixNXd &samples, int alpha, const VectorNd &mu_u, const MatrixNNd &Lambda_u) { int i = 0; MatrixNNd MM; MM.setZero(); VectorNd rr; rr.setZero(); for (SparseMatrixD::InnerIterator it(mat,mm); it; ++it, ++i) { // cout << "M[" << it.row() << "," << it.col() << "] = " << it.value() << endl; auto col = samples.col(it.row()); MM += col * col.transpose(); rr += col * ((it.value() - mean_rating) * alpha); } auto MMs = alpha * MM; MatrixNNd covar = (Lambda_u + MMs).inverse(); auto U = Lambda_u * mu_u; auto mu = covar * (rr + U); MatrixNNd chol = covar.llt().matrixL(); auto r = VectorXd::NullaryExpr(num_feat, ptr_fun(randn)); s.col(mm) = chol * r + mu; #ifdef TEST_SAMPLE cout << "movie " << mm << ":" << result.cols() << " x" << result.rows() << endl; cout << "mean rating " << mean_rating << endl; cout << "E = [" << E << "]" << endl; cout << "rr = [" << rr << "]" << endl; cout << "MM = [" << MM << "]" << endl; cout << "Lambda_u = [" << Lambda_u << "]" << endl; cout << "covar = [" << covar << "]" << endl; cout << "mu = [" << mu << "]" << endl; cout << "chol = [" << chol << "]" << endl; cout << "rand = [" << r <<"]" << endl; cout << "result = [" << result << "]" << endl; #endif } #ifdef TEST_SAMPLE void test() { MatrixNXd sample_u(M.rows()); MatrixNXd sample_m(M.cols()); mu_m.setZero(); Lambda_m.setIdentity(); sample_u.setConstant(2.0); Lambda_m *= 0.5; sample_m.col(0) = sample_movie(0, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #else void run() { auto start = tick(); std::cout << "Sampling" << endl; for(int i=0; i<nsims; ++i) { // Sample from movie hyperparams tie(mu_m, Lambda_m) = CondNormalWishart(sample_m, mu0_m, b0_m, WI_m, df_m); // Sample from user hyperparams tie(mu_u, Lambda_u) = CondNormalWishart(sample_u, mu0_u, b0_u, WI_u, df_u); const int num_m = M.cols(); const int num_u = M.rows(); #ifdef _OPENMP #pragma omp parallel for for(int mm=0; mm<num_m; ++mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); } #pragma omp parallel for for(int uu=0; uu<num_u; ++uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); } #else tbb::parallel_for(0, num_m, [](int mm) { sample_movie(sample_m, mm, M, mean_rating, sample_u, alpha, mu_m, Lambda_m); }); tbb::parallel_for(0, num_u, [](int uu) { sample_movie(sample_u, uu, Mt, mean_rating, sample_m, alpha, mu_u, Lambda_u); }); #endif auto eval = eval_probe_vec(sample_m, sample_u, mean_rating); double norm_u = sample_u.norm(); double norm_m = sample_m.norm(); auto end = tick(); auto elapsed = end - start; double samples_per_sec = (i + 1) * (M.rows() + M.cols()) / elapsed; printf("Iteration %d:\t num_correct: %3.2f%%\tavg_diff: %3.2f\tFU(%6.2f)\tFM(%6.2f)\tSamples/sec: %6.2f\n", i, 100*eval.first, eval.second, norm_u, norm_m, samples_per_sec); } } #endif int main(int argc, char *argv[]) { assert(argv[1] && argv[2] && "filename missing"); Eigen::initParallel(); loadMarket(M, argv[1]); Mt = M.transpose(); loadMarket(P, argv[2]); assert(M.nonZeros() > P.nonZeros()); init(); #ifdef TEST_SAMPLE test(); #else run(); #endif return 0; } <|endoftext|>
<commit_before>#include <algorithm> #include "./types.h" #include "utils/logger.h" namespace { bool IsTypeInvalid(rpc::Enum<rpc::policy_table_interface_base::RequestType> request) { return !request.is_valid(); } } namespace rpc { namespace policy_table_interface_base { CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyTableValidation") void RemoveInvalidTypes(RequestTypes& types) { types.erase( std::remove_if(types.begin(), types.end(), &IsTypeInvalid), types.end()); } bool PolicyBase::Validate() const { return true; } bool ApplicationPoliciesSection::Validate() const { ApplicationPolicies::iterator it_default_policy = apps.find(kDefaultApp); ApplicationPolicies::iterator it_pre_data_policy = apps.find(kPreDataConsentApp); // Default and PreData policies are mandatory if (apps.end() == it_default_policy || apps.end() == it_pre_data_policy) { LOG4CXX_ERROR(logger_, "Default or preData policy is not present."); return false; } // Device policy is mandatory if (!device.is_initialized()) { LOG4CXX_ERROR(logger_, "Device policy is not present."); return false; } PolicyTableType pt_type = GetPolicyTableType(); if (PT_PRELOADED != pt_type && PT_UPDATE != pt_type) { return true; } if (!it_default_policy->second.RequestType.is_valid()) { LOG4CXX_WARN(logger_, "Default policy RequestTypes are not valid. Will be cleaned."); RemoveInvalidTypes(*it_default_policy->second.RequestType); // If preloaded does not have valid default types - validation fails // Otherwise default will be empty, i.e. all types allowed if (PT_PRELOADED == pt_type) { if (it_default_policy->second.RequestType->empty()) { LOG4CXX_ERROR( logger_, "Default policy RequestTypes empty after clean-up. Exiting."); return false; } } } ApplicationPolicies::iterator iter = apps.begin(); ApplicationPolicies::iterator end_iter = apps.end(); while(iter != end_iter) { ApplicationParams& app_params = (*iter).second; bool is_request_type_ommited = !app_params.RequestType.is_initialized(); bool is_request_type_valid = app_params.RequestType.is_valid(); bool is_request_type_empty = app_params.RequestType->empty(); if (PT_PRELOADED == pt_type) { if (!is_request_type_valid) { LOG4CXX_WARN( logger_, "App policy RequestTypes are not valid. Will be cleaned."); RemoveInvalidTypes(*app_params.RequestType); if (app_params.RequestType->empty()) { LOG4CXX_ERROR( logger_, "App policy RequestTypes empty after clean-up. Exiting."); return false; } } } else { if (is_request_type_ommited) { LOG4CXX_WARN(logger_, "App policy RequestTypes ommited." " Will be replaced with default."); app_params.RequestType = apps[kDefaultApp].RequestType; continue; } if (!is_request_type_valid) { LOG4CXX_WARN( logger_, "App policy RequestTypes are invalid. Will be cleaned."); RemoveInvalidTypes(*app_params.RequestType); if (app_params.RequestType->empty()) { LOG4CXX_WARN(logger_, "App policy RequestTypes empty after clean-up." " Will be replaced with default."); app_params.RequestType = apps[kDefaultApp].RequestType; continue; } } if (is_request_type_empty) { LOG4CXX_WARN(logger_, "App policy RequestTypes empty."); } } ++iter; } return true; } bool ApplicationParams::Validate() const { return true; } bool RpcParameters::Validate() const { return true; } bool Rpcs::Validate() const { return true; } bool ModuleConfig::Validate() const { if (PT_PRELOADED == GetPolicyTableType()) { if (vehicle_make.is_initialized()) { return false; } if (vehicle_year.is_initialized()) { return false; } if (vehicle_model.is_initialized()) { return false; } } return true; } bool MessageString::Validate() const { return true; } bool MessageLanguages::Validate() const { if (PT_SNAPSHOT == GetPolicyTableType()) { return false; } return true; } bool ConsumerFriendlyMessages::Validate() const { if (PT_SNAPSHOT == GetPolicyTableType()) { return false; } return true; } bool ModuleMeta::Validate() const { return true; } bool AppLevel::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { return false; } return true; } bool UsageAndErrorCounts::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { return false; } return true; } bool DeviceParams::Validate() const { return true; } bool PolicyTable::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { if (device_data.is_initialized()) { return false; } } return true; } bool Table::Validate() const { return true; } } // namespace policy_table_interface_base } // namespace rpc <commit_msg>Fixed RequestType validation.<commit_after>#include <algorithm> #include "./types.h" #include "utils/logger.h" namespace { bool IsTypeInvalid(rpc::Enum<rpc::policy_table_interface_base::RequestType> request) { return !request.is_valid(); } } namespace rpc { namespace policy_table_interface_base { CREATE_LOGGERPTR_GLOBAL(logger_, "PolicyTableValidation") void RemoveInvalidTypes(RequestTypes& types) { types.erase( std::remove_if(types.begin(), types.end(), &IsTypeInvalid), types.end()); } bool PolicyBase::Validate() const { return true; } bool ApplicationPoliciesSection::Validate() const { ApplicationPolicies::iterator it_default_policy = apps.find(kDefaultApp); ApplicationPolicies::iterator it_pre_data_policy = apps.find(kPreDataConsentApp); // Default and PreData policies are mandatory if (apps.end() == it_default_policy || apps.end() == it_pre_data_policy) { LOG4CXX_ERROR(logger_, "Default or preData policy is not present."); return false; } // Device policy is mandatory if (!device.is_initialized()) { LOG4CXX_ERROR(logger_, "Device policy is not present."); return false; } PolicyTableType pt_type = GetPolicyTableType(); if (PT_PRELOADED != pt_type && PT_UPDATE != pt_type) { return true; } if (!it_default_policy->second.RequestType.is_valid()) { LOG4CXX_WARN(logger_, "Default policy RequestTypes are not valid. Will be cleaned."); RemoveInvalidTypes(*it_default_policy->second.RequestType); // If preloaded does not have valid default types - validation fails // Otherwise default will be empty, i.e. all types allowed if (PT_PRELOADED == pt_type) { if (it_default_policy->second.RequestType->empty()) { LOG4CXX_ERROR( logger_, "Default policy RequestTypes empty after clean-up. Exiting."); return false; } } } ApplicationPolicies::iterator iter = apps.begin(); ApplicationPolicies::iterator end_iter = apps.end(); while(iter != end_iter) { ApplicationParams& app_params = (*iter).second; bool is_request_type_ommited = !app_params.RequestType.is_initialized(); bool is_request_type_valid = app_params.RequestType.is_valid(); bool is_request_type_empty = app_params.RequestType->empty(); if (PT_PRELOADED == pt_type) { if (!is_request_type_valid) { LOG4CXX_WARN( logger_, "App policy RequestTypes are not valid. Will be cleaned."); RemoveInvalidTypes(*app_params.RequestType); if (app_params.RequestType->empty()) { LOG4CXX_ERROR( logger_, "App policy RequestTypes empty after clean-up. Exiting."); return false; } } } else { if (is_request_type_ommited) { LOG4CXX_WARN(logger_, "App policy RequestTypes ommited." " Will be replaced with default."); app_params.RequestType = apps[kDefaultApp].RequestType; ++iter; continue; } if (!is_request_type_valid) { LOG4CXX_WARN( logger_, "App policy RequestTypes are invalid. Will be cleaned."); RemoveInvalidTypes(*app_params.RequestType); if (app_params.RequestType->empty()) { LOG4CXX_WARN(logger_, "App policy RequestTypes empty after clean-up." " Will be replaced with default."); app_params.RequestType = apps[kDefaultApp].RequestType; ++iter; continue; } } if (is_request_type_empty) { LOG4CXX_WARN(logger_, "App policy RequestTypes empty."); } } ++iter; } return true; } bool ApplicationParams::Validate() const { return true; } bool RpcParameters::Validate() const { return true; } bool Rpcs::Validate() const { return true; } bool ModuleConfig::Validate() const { if (PT_PRELOADED == GetPolicyTableType()) { if (vehicle_make.is_initialized()) { return false; } if (vehicle_year.is_initialized()) { return false; } if (vehicle_model.is_initialized()) { return false; } } return true; } bool MessageString::Validate() const { return true; } bool MessageLanguages::Validate() const { if (PT_SNAPSHOT == GetPolicyTableType()) { return false; } return true; } bool ConsumerFriendlyMessages::Validate() const { if (PT_SNAPSHOT == GetPolicyTableType()) { return false; } return true; } bool ModuleMeta::Validate() const { return true; } bool AppLevel::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { return false; } return true; } bool UsageAndErrorCounts::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { return false; } return true; } bool DeviceParams::Validate() const { return true; } bool PolicyTable::Validate() const { if (PT_PRELOADED == GetPolicyTableType() || PT_UPDATE == GetPolicyTableType()) { if (device_data.is_initialized()) { return false; } } return true; } bool Table::Validate() const { return true; } } // namespace policy_table_interface_base } // namespace rpc <|endoftext|>
<commit_before>#include <iostream> #include <vector> #include <list> #include <chrono> #include <sstream> #include <string.h> #ifndef _WIN32 #include <unistd.h> #include <sys/select.h> #include <sys/wait.h> #endif #include "plugin.h" #include "term_network.h" #include "term_data_handler.h" #include "term_context.h" #include "term_buffer.h" #include "term_window.h" #include "PortableThread.h" #include "term_data_handler_impl.h" #include "term_data_handler_impl_decl.h" #include "read_termdata.h" #include "string_utils.h" const char * kPathSeparator = #if defined _WIN32 || defined __CYGWIN__ "\\"; #else "/"; #endif static bool load_cap_str(const std::string & termcap_dir, const std::string & term_name, std::string & term_entry) { std::string file_path = termcap_dir; file_path.append(kPathSeparator).append(term_name).append(".dat"); return get_entry(file_path, term_name, term_entry); } void TermDataHandlerImpl::LoadNativeDataHandler() { std::string termcap_dir = GetPluginContext()->GetAppConfig()->GetEntry("/term/termcap_dir", "data"); std::string term_name = GetPluginContext()->GetAppConfig()->GetEntry("/term/term_name", "xterm-256color"); bool use_generic = GetPluginContext()->GetAppConfig()->GetEntryBool("/term/use_generic_cap", "true"); std::stringstream ss; std::string term_entry; if (use_generic) { if (load_cap_str(termcap_dir, "generic-cap", term_entry)) ss << term_entry; } if (!load_cap_str(termcap_dir, term_name, term_entry)) { if (load_cap_str(termcap_dir, "xterm-256color", term_entry)) { ss << term_entry; } } else { ss << term_entry; } m_Cap = parse_cap(ss.str()); m_State = m_Cap->control_data_start_state; m_ParseContext = std::make_shared<ControlDataParserContext>(); } void TermDataHandlerImpl::ProcessSingleCharNative(const char * ch) { if (!ch) { if (!m_State) return; HandleCap(false, 0); return; } auto next_state = m_State->handle(m_ParseContext, *ch); CapNameMapValue cap_tuple; if (!next_state || m_State->get_cap(m_ParseContext->params, cap_tuple)) { HandleCap(true, *ch); if (next_state) next_state->reset(); next_state = m_State->handle(m_ParseContext, *ch); if (next_state) { m_State = next_state; if (*ch == 0x1B) { m_ControlData.push_back('\\'); m_ControlData.push_back('E'); } else { m_ControlData.push_back(*ch); } } else { output_char(m_DataContext, *ch, false); } return; } m_State = next_state; if (*ch == 0x1B) { m_ControlData.push_back('\\'); m_ControlData.push_back('E'); } else { m_ControlData.push_back(*ch); } } void TermDataHandlerImpl::HandleCap(bool check_unknown, char c) { CapNameMapValue cap_tuple; (void)c; auto result = m_State->get_cap(m_ParseContext->params, cap_tuple); if (result) { bool inc_param = std::get<1>(cap_tuple); if (inc_param) { for(auto & p : m_ParseContext->params) { if (p.has_int_value && p.int_value > 0) p.int_value--; } } handle_cap(m_DataContext, std::get<0>(cap_tuple), m_ParseContext->params); if (m_CapStateStack.size() > 0) { std::tie(m_State, m_ParseContext->params, m_ControlData) = m_CapStateStack.front(); m_CapStateStack.pop_front(); } else { m_State = m_Cap->control_data_start_state; m_ParseContext->params.clear(); m_ControlData.clear(); } } else if (check_unknown && m_ControlData.size() > 0) { m_CapStateStack.push_front(std::make_tuple(m_State, m_ParseContext->params, m_ControlData)); m_State = m_Cap->control_data_start_state; m_ParseContext->params.clear(); m_ControlData.clear(); } } <commit_msg>ignore unkown cap<commit_after>#include <iostream> #include <vector> #include <list> #include <chrono> #include <sstream> #include <string.h> #ifndef _WIN32 #include <unistd.h> #include <sys/select.h> #include <sys/wait.h> #endif #include "plugin.h" #include "term_network.h" #include "term_data_handler.h" #include "term_context.h" #include "term_buffer.h" #include "term_window.h" #include "PortableThread.h" #include "term_data_handler_impl.h" #include "term_data_handler_impl_decl.h" #include "read_termdata.h" #include "string_utils.h" const char * kPathSeparator = #if defined _WIN32 || defined __CYGWIN__ "\\"; #else "/"; #endif static bool load_cap_str(const std::string & termcap_dir, const std::string & term_name, std::string & term_entry) { std::string file_path = termcap_dir; file_path.append(kPathSeparator).append(term_name).append(".dat"); return get_entry(file_path, term_name, term_entry); } void TermDataHandlerImpl::LoadNativeDataHandler() { std::string termcap_dir = GetPluginContext()->GetAppConfig()->GetEntry("/term/termcap_dir", "data"); std::string term_name = GetPluginContext()->GetAppConfig()->GetEntry("/term/term_name", "xterm-256color"); bool use_generic = GetPluginContext()->GetAppConfig()->GetEntryBool("/term/use_generic_cap", "true"); std::stringstream ss; std::string term_entry; if (use_generic) { if (load_cap_str(termcap_dir, "generic-cap", term_entry)) ss << term_entry; } if (!load_cap_str(termcap_dir, term_name, term_entry)) { if (load_cap_str(termcap_dir, "xterm-256color", term_entry)) { ss << term_entry; } } else { ss << term_entry; } m_Cap = parse_cap(ss.str()); m_State = m_Cap->control_data_start_state; m_ParseContext = std::make_shared<ControlDataParserContext>(); } void TermDataHandlerImpl::ProcessSingleCharNative(const char * ch) { if (!ch) { if (!m_State) return; HandleCap(false, 0); return; } bool state_checked = false; handle_state: auto next_state = m_State->handle(m_ParseContext, *ch); CapNameMapValue cap_tuple; if (!next_state || m_State->get_cap(m_ParseContext->params, cap_tuple)) { HandleCap(true, *ch); if (next_state) next_state->reset(); next_state = m_State->handle(m_ParseContext, *ch); if (next_state) { m_State = next_state; if (*ch == 0x1B) { m_ControlData.push_back('\\'); m_ControlData.push_back('E'); } else { m_ControlData.push_back(*ch); } } else { if (*ch == 0x1B) { assert(!state_checked); state_checked = true; std::cout << "unknown/not defined cap found:"; std::copy(m_ControlData.begin(), m_ControlData.end(), std::ostream_iterator<char>(std::cout, "")); std::cout << std::endl; m_State = m_Cap->control_data_start_state; m_ParseContext->params.clear(); m_ControlData.clear(); goto handle_state; } output_char(m_DataContext, *ch, false); } return; } m_State = next_state; if (*ch == 0x1B) { m_ControlData.push_back('\\'); m_ControlData.push_back('E'); } else { m_ControlData.push_back(*ch); } } void TermDataHandlerImpl::HandleCap(bool check_unknown, char c) { CapNameMapValue cap_tuple; (void)c; auto result = m_State->get_cap(m_ParseContext->params, cap_tuple); if (result) { bool inc_param = std::get<1>(cap_tuple); if (inc_param) { for(auto & p : m_ParseContext->params) { if (p.has_int_value && p.int_value > 0) p.int_value--; } } handle_cap(m_DataContext, std::get<0>(cap_tuple), m_ParseContext->params); if (m_CapStateStack.size() > 0) { std::tie(m_State, m_ParseContext->params, m_ControlData) = m_CapStateStack.front(); m_CapStateStack.pop_front(); } else { m_State = m_Cap->control_data_start_state; m_ParseContext->params.clear(); m_ControlData.clear(); } } else if (check_unknown && m_ControlData.size() > 0) { m_CapStateStack.push_front(std::make_tuple(m_State, m_ParseContext->params, m_ControlData)); m_State = m_Cap->control_data_start_state; m_ParseContext->params.clear(); m_ControlData.clear(); } } <|endoftext|>
<commit_before>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifdef LLVM_ON_WIN32 #include <Windows.h> #include <shlobj.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace { #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } #if defined(__APPLE__) || defined(__CYGWIN__) Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); Paths.push_back("/lib/x86_64-linux-gnu/"); Paths.push_back("/usr/local/lib64/"); Paths.push_back("/usr/lib64/"); Paths.push_back("/lib64/"); #else static bool initialized = false; static std::vector<std::string> SysPaths; if (!initialized) { // trick to get the system search path std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1"); FILE *pf = popen(cmd.c_str (), "r"); std::string result = ""; std::string sys_path = ""; char buffer[128]; while (!feof(pf)) { if (fgets(buffer, 128, pf) != NULL) result += buffer; } pclose(pf); std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)")); std::size_t to = result.find("(system search path)"); if (from != std::string::npos && to != std::string::npos) { from += 12; sys_path = result.substr(from, to-from); sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end()); sys_path += ':'; } static const char PathSeparator = ':'; const char* at = sys_path.c_str(); const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) SysPaths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } initialized = true; } for (std::vector<std::string>::const_iterator I = SysPaths.begin(), E = SysPaths.end(); I != E; ++I) Paths.push_back((*I).c_str()); #endif } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } static bool is_dll(const char *filename) { bool is_dll = false; HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hFileMapping == INVALID_HANDLE_VALUE) { CloseHandle(hFile); return false; } LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); if (lpFileBase == NULL) { CloseHandle(hFileMapping); CloseHandle(hFile); return false; } PIMAGE_DOS_HEADER pDOSHeader = static_cast<PIMAGE_DOS_HEADER>(lpFileBase); if (pDOSHeader->e_magic == IMAGE_DOS_SIGNATURE) { PIMAGE_NT_HEADERS pNTHeader = reinterpret_cast<PIMAGE_NT_HEADERS>((PBYTE)lpFileBase + pDOSHeader->e_lfanew); if ((pNTHeader->Signature == IMAGE_NT_SIGNATURE) && ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL))) is_dll = true; } UnmapViewOfFile(lpFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); return is_dll; } #else # error "Unsupported platform." #endif } namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts), m_Callbacks(0) { GetSystemLibraryPaths(m_SystemSearchPaths); m_SystemSearchPaths.push_back("."); } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) { using namespace llvm::sys::fs; file_magic Magic; std::error_code Error = identify_magic(LibName, Magic); bool onDisk = (Error != std::errc::no_such_file_or_directory); if (exists) *exists = onDisk; return onDisk && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub || Magic == file_magic::macho_universal_binary) #elif defined(LLVM_ON_UNIX) #ifdef __CYGWIN__ (Magic == file_magic::pecoff_executable) #else (Magic == file_magic::elf_shared_object) #endif #elif defined(LLVM_ON_WIN32) (Magic == file_magic::pecoff_executable || is_dll(LibName.str().c_str())) #else # error "Unsupported platform." #endif ; } std::string DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const { llvm::SmallVector<std::string, 128> Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end()); for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop llvm::sys::path::append(ThisPath, libStem); bool exists; if (isSharedLib(ThisPath.str(), &exists)) return ThisPath.str(); if (exists) return ""; } return ""; } std::string DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const { using namespace llvm::sys; std::string foundDyLib = lookupLibInPaths(libStem); if (foundDyLib.empty()) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(libStem); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; foundDyLib = lookupLibInPaths(filenameWithExt); #ifdef __APPLE__ if (foundDyLib.empty()) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; foundDyLib = lookupLibInPaths(filenameWithExt); } #endif } if (foundDyLib.empty()) return ""; // get canonical path name and check if already loaded #if defined(LLVM_ON_WIN32) llvm::SmallString<_MAX_PATH> FullPath(""); char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath(""); char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): " "error getting real (canonical) path of library " << foundDyLib << '\n'; return foundDyLib; } FullPath.set_size(strlen(res)); return FullPath.str(); } std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) { // Make the path canonical if the file exists. struct stat buffer; if (stat(path.data(), &buffer) != 0) return ""; #if defined(LLVM_ON_WIN32) char buf[_MAX_PATH]; char *res = _fullpath(buf, path.data(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(path.data(), buf); #endif if (res == 0) { assert(0 && "Cannot normalize!?"); return ""; } return res; } std::string DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const { llvm::SmallString<128> Absolute(libStem); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = libStem == Absolute; // If it is an absolute path, don't try iterate over the paths. if (isAbsolute) { if (isSharedLib(libStem)) return normalizePath(libStem); else return ""; } std::string foundName = lookupLibMaybeAddExt(libStem); if (foundName.empty() && !libStem.startswith("lib")) { // try with "lib" prefix: foundName = lookupLibMaybeAddExt("lib" + libStem.str()); } if (isSharedLib(foundName)) return normalizePath(foundName); return ""; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& libStem, bool permanent) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (canonicalLoadedLib.empty()) return kLoadLibNotFound; if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end()) return kLoadLibAlreadyLoaded; std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); errMsg = "LoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(), RTLD_LAZY|RTLD_GLOBAL); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg << '\n'; return kLoadLibLoadError; } else if (InterpreterCallbacks* C = getCallbacks()) C->LibraryLoaded(dyLibHandle, canonicalLoadedLib); std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, canonicalLoadedLib)); if (!insRes.second) return kLoadLibAlreadyLoaded; m_LoadedLibraries.insert(canonicalLoadedLib); return kLoadLibSuccess; } void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (!isLibraryLoaded(canonicalLoadedLib)) return; DyLibHandle dyLibHandle = 0; for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end(); I != E; ++I) { if (I->second == canonicalLoadedLib) dyLibHandle = I->first; } std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) FreeLibrary((HMODULE)dyLibHandle); errMsg = "UnoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else dlclose(const_cast<void*>(dyLibHandle)); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (InterpreterCallbacks* C = getCallbacks()) C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib); m_DyLibs.erase(dyLibHandle); m_LoadedLibraries.erase(canonicalLoadedLib); } bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const { std::string canonPath = normalizePath(fullPath); if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <commit_msg>Exit early once the dylib is found.<commit_after>//------------------------------------------------------------------------------ // CLING - the C++ LLVM-based InterpreterG :) // author: Vassil Vassilev <vasil.georgiev.vasilev@cern.ch> // // This file is dual-licensed: you can choose to license it under the University // of Illinois Open Source License or the GNU Lesser General Public License. See // LICENSE.TXT for details. //------------------------------------------------------------------------------ #include "cling/Interpreter/DynamicLibraryManager.h" #include "cling/Interpreter/InterpreterCallbacks.h" #include "cling/Interpreter/InvocationOptions.h" #include "llvm/Support/DynamicLibrary.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Path.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <iostream> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #ifdef LLVM_ON_WIN32 #include <Windows.h> #include <shlobj.h> #else #include <limits.h> /* PATH_MAX */ #include <dlfcn.h> #endif namespace { #if defined(LLVM_ON_UNIX) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char* env_var = getenv("LD_LIBRARY_PATH"); #if __APPLE__ if (!env_var) env_var = getenv("DYLD_LIBRARY_PATH"); if (!env_var) env_var = getenv("DYLD_FALLBACK_LIBRARY_PATH"); #endif if (env_var != 0) { static const char PathSeparator = ':'; const char* at = env_var; const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) Paths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } if (*at != 0) if (llvm::sys::fs::is_directory(llvm::StringRef(at))) Paths.push_back(at); } #if defined(__APPLE__) || defined(__CYGWIN__) Paths.push_back("/usr/local/lib/"); Paths.push_back("/usr/X11R6/lib/"); Paths.push_back("/usr/lib/"); Paths.push_back("/lib/"); Paths.push_back("/lib/x86_64-linux-gnu/"); Paths.push_back("/usr/local/lib64/"); Paths.push_back("/usr/lib64/"); Paths.push_back("/lib64/"); #else static bool initialized = false; static std::vector<std::string> SysPaths; if (!initialized) { // trick to get the system search path std::string cmd("LD_DEBUG=libs LD_PRELOAD=DOESNOTEXIST ls 2>&1"); FILE *pf = popen(cmd.c_str (), "r"); std::string result = ""; std::string sys_path = ""; char buffer[128]; while (!feof(pf)) { if (fgets(buffer, 128, pf) != NULL) result += buffer; } pclose(pf); std::size_t from = result.find("search path=", result.find("(LD_LIBRARY_PATH)")); std::size_t to = result.find("(system search path)"); if (from != std::string::npos && to != std::string::npos) { from += 12; sys_path = result.substr(from, to-from); sys_path.erase(std::remove_if(sys_path.begin(), sys_path.end(), isspace), sys_path.end()); sys_path += ':'; } static const char PathSeparator = ':'; const char* at = sys_path.c_str(); const char* delim = strchr(at, PathSeparator); while (delim != 0) { std::string tmp(at, size_t(delim-at)); if (llvm::sys::fs::is_directory(tmp.c_str())) SysPaths.push_back(tmp); at = delim + 1; delim = strchr(at, PathSeparator); } initialized = true; } for (std::vector<std::string>::const_iterator I = SysPaths.begin(), E = SysPaths.end(); I != E; ++I) Paths.push_back((*I).c_str()); #endif } #elif defined(LLVM_ON_WIN32) static void GetSystemLibraryPaths(llvm::SmallVectorImpl<std::string>& Paths) { char buff[MAX_PATH]; // Generic form of C:\Windows\System32 HRESULT res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_SYSTEM, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get system directory"); return; } Paths.push_back(buff); // Reset buff. buff[0] = 0; // Generic form of C:\Windows res = SHGetFolderPathA(NULL, CSIDL_FLAG_CREATE | CSIDL_WINDOWS, NULL, SHGFP_TYPE_CURRENT, buff); if (res != S_OK) { assert(0 && "Failed to get windows directory"); return; } Paths.push_back(buff); } static bool is_dll(const char *filename) { bool is_dll = false; HANDLE hFile = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); HANDLE hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hFileMapping == INVALID_HANDLE_VALUE) { CloseHandle(hFile); return false; } LPVOID lpFileBase = MapViewOfFile(hFileMapping, FILE_MAP_READ, 0, 0, 0); if (lpFileBase == NULL) { CloseHandle(hFileMapping); CloseHandle(hFile); return false; } PIMAGE_DOS_HEADER pDOSHeader = static_cast<PIMAGE_DOS_HEADER>(lpFileBase); if (pDOSHeader->e_magic == IMAGE_DOS_SIGNATURE) { PIMAGE_NT_HEADERS pNTHeader = reinterpret_cast<PIMAGE_NT_HEADERS>((PBYTE)lpFileBase + pDOSHeader->e_lfanew); if ((pNTHeader->Signature == IMAGE_NT_SIGNATURE) && ((pNTHeader->FileHeader.Characteristics & IMAGE_FILE_DLL))) is_dll = true; } UnmapViewOfFile(lpFileBase); CloseHandle(hFileMapping); CloseHandle(hFile); return is_dll; } #else # error "Unsupported platform." #endif } namespace cling { DynamicLibraryManager::DynamicLibraryManager(const InvocationOptions& Opts) : m_Opts(Opts), m_Callbacks(0) { GetSystemLibraryPaths(m_SystemSearchPaths); m_SystemSearchPaths.push_back("."); } DynamicLibraryManager::~DynamicLibraryManager() {} static bool isSharedLib(llvm::StringRef LibName, bool* exists = 0) { using namespace llvm::sys::fs; file_magic Magic; std::error_code Error = identify_magic(LibName, Magic); bool onDisk = (Error != std::errc::no_such_file_or_directory); if (exists) *exists = onDisk; return onDisk && #ifdef __APPLE__ (Magic == file_magic::macho_fixed_virtual_memory_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib || Magic == file_magic::macho_dynamically_linked_shared_lib_stub || Magic == file_magic::macho_universal_binary) #elif defined(LLVM_ON_UNIX) #ifdef __CYGWIN__ (Magic == file_magic::pecoff_executable) #else (Magic == file_magic::elf_shared_object) #endif #elif defined(LLVM_ON_WIN32) (Magic == file_magic::pecoff_executable || is_dll(LibName.str().c_str())) #else # error "Unsupported platform." #endif ; } std::string DynamicLibraryManager::lookupLibInPaths(llvm::StringRef libStem) const { llvm::SmallVector<std::string, 128> Paths(m_Opts.LibSearchPath.begin(), m_Opts.LibSearchPath.end()); Paths.append(m_SystemSearchPaths.begin(), m_SystemSearchPaths.end()); for (llvm::SmallVectorImpl<std::string>::const_iterator IPath = Paths.begin(), E = Paths.end();IPath != E; ++IPath) { llvm::SmallString<512> ThisPath(*IPath); // FIXME: move alloc outside loop llvm::sys::path::append(ThisPath, libStem); bool exists; if (isSharedLib(ThisPath.str(), &exists)) return ThisPath.str(); if (exists) return ""; } return ""; } std::string DynamicLibraryManager::lookupLibMaybeAddExt(llvm::StringRef libStem) const { using namespace llvm::sys; std::string foundDyLib = lookupLibInPaths(libStem); if (foundDyLib.empty()) { // Add DyLib extension: llvm::SmallString<512> filenameWithExt(libStem); #if defined(LLVM_ON_UNIX) #ifdef __APPLE__ llvm::SmallString<512>::iterator IStemEnd = filenameWithExt.end() - 1; #endif static const char* DyLibExt = ".so"; #elif defined(LLVM_ON_WIN32) static const char* DyLibExt = ".dll"; #else # error "Unsupported platform." #endif filenameWithExt += DyLibExt; foundDyLib = lookupLibInPaths(filenameWithExt); #ifdef __APPLE__ if (foundDyLib.empty()) { filenameWithExt.erase(IStemEnd + 1, filenameWithExt.end()); filenameWithExt += ".dylib"; foundDyLib = lookupLibInPaths(filenameWithExt); } #endif } if (foundDyLib.empty()) return ""; // get canonical path name and check if already loaded #if defined(LLVM_ON_WIN32) llvm::SmallString<_MAX_PATH> FullPath(""); char *res = _fullpath((char *)FullPath.data(), foundDyLib.c_str(), _MAX_PATH); #else llvm::SmallString<PATH_MAX+1> FullPath(""); char *res = realpath(foundDyLib.c_str(), (char *)FullPath.data()); #endif if (res == 0) { llvm::errs() << "cling::DynamicLibraryManager::lookupLibMaybeAddExt(): " "error getting real (canonical) path of library " << foundDyLib << '\n'; return foundDyLib; } FullPath.set_size(strlen(res)); return FullPath.str(); } std::string DynamicLibraryManager::normalizePath(llvm::StringRef path) { // Make the path canonical if the file exists. struct stat buffer; if (stat(path.data(), &buffer) != 0) return ""; #if defined(LLVM_ON_WIN32) char buf[_MAX_PATH]; char *res = _fullpath(buf, path.data(), _MAX_PATH); #else char buf[PATH_MAX+1]; char *res = realpath(path.data(), buf); #endif if (res == 0) { assert(0 && "Cannot normalize!?"); return ""; } return res; } std::string DynamicLibraryManager::lookupLibrary(llvm::StringRef libStem) const { llvm::SmallString<128> Absolute(libStem); llvm::sys::fs::make_absolute(Absolute); bool isAbsolute = libStem == Absolute; // If it is an absolute path, don't try iterate over the paths. if (isAbsolute) { if (isSharedLib(libStem)) return normalizePath(libStem); else return ""; } std::string foundName = lookupLibMaybeAddExt(libStem); if (foundName.empty() && !libStem.startswith("lib")) { // try with "lib" prefix: foundName = lookupLibMaybeAddExt("lib" + libStem.str()); } if (isSharedLib(foundName)) return normalizePath(foundName); return ""; } DynamicLibraryManager::LoadLibResult DynamicLibraryManager::loadLibrary(const std::string& libStem, bool permanent) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (canonicalLoadedLib.empty()) return kLoadLibNotFound; if (m_LoadedLibraries.find(canonicalLoadedLib) != m_LoadedLibraries.end()) return kLoadLibAlreadyLoaded; std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) HMODULE dyLibHandle = LoadLibraryEx(canonicalLoadedLib.c_str(), NULL, DONT_RESOLVE_DLL_REFERENCES); errMsg = "LoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else const void* dyLibHandle = dlopen(canonicalLoadedLib.c_str(), RTLD_LAZY|RTLD_GLOBAL); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (!dyLibHandle) { llvm::errs() << "cling::DynamicLibraryManager::loadLibrary(): " << errMsg << '\n'; return kLoadLibLoadError; } else if (InterpreterCallbacks* C = getCallbacks()) C->LibraryLoaded(dyLibHandle, canonicalLoadedLib); std::pair<DyLibs::iterator, bool> insRes = m_DyLibs.insert(std::pair<DyLibHandle, std::string>(dyLibHandle, canonicalLoadedLib)); if (!insRes.second) return kLoadLibAlreadyLoaded; m_LoadedLibraries.insert(canonicalLoadedLib); return kLoadLibSuccess; } void DynamicLibraryManager::unloadLibrary(llvm::StringRef libStem) { std::string canonicalLoadedLib = lookupLibrary(libStem); if (!isLibraryLoaded(canonicalLoadedLib)) return; DyLibHandle dyLibHandle = 0; for (DyLibs::const_iterator I = m_DyLibs.begin(), E = m_DyLibs.end(); I != E; ++I) { if (I->second == canonicalLoadedLib) { dyLibHandle = I->first; break; } } std::string errMsg; // TODO: !permanent case #if defined(LLVM_ON_WIN32) FreeLibrary((HMODULE)dyLibHandle); errMsg = "UnoadLibraryEx: GetLastError() returned "; errMsg += GetLastError(); #else dlclose(const_cast<void*>(dyLibHandle)); if (const char* DyLibError = dlerror()) { errMsg = DyLibError; } #endif if (InterpreterCallbacks* C = getCallbacks()) C->LibraryUnloaded(dyLibHandle, canonicalLoadedLib); m_DyLibs.erase(dyLibHandle); m_LoadedLibraries.erase(canonicalLoadedLib); } bool DynamicLibraryManager::isLibraryLoaded(llvm::StringRef fullPath) const { std::string canonPath = normalizePath(fullPath); if (m_LoadedLibraries.find(canonPath) != m_LoadedLibraries.end()) return true; return false; } void DynamicLibraryManager::ExposeHiddenSharedLibrarySymbols(void* handle) { llvm::sys::DynamicLibrary::addPermanentLibrary(const_cast<void*>(handle)); } } // end namespace cling <|endoftext|>
<commit_before>#ifndef COMPRESS__H__ #define COMPRESS__H__ #include "iterbase.hpp" #include <utility> #include <initializer_list> namespace iter { //Forward declarations of Compressed and compress template <typename Container, typename Selector> class Compressed; template <typename Container, typename Selector> Compressed<Container, Selector> compress(Container&&, Selector&&); template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>&&, Selector&&); template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&&, std::initializer_list<T>&&); template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&&, std::initializer_list<U>&&); template <typename Container, typename Selector> class Compressed { private: Container& container; Selector & selectors; // The only thing allowed to directly instantiate an Compressed is // the compress function friend Compressed compress<Container, Selector>( Container&&, Selector&&); template <typename T, typename Sel> friend Compressed<std::initializer_list<T>, Sel> compress( std::initializer_list<T>&&, Sel&&); template <typename Con, typename T> friend Compressed<Con, std::initializer_list<T>> compress( Con&&, std::initializer_list<T>&&); template <typename T, typename U> friend Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&&, std::initializer_list<U>&&); // Selector::Iterator type using selector_iter_type = decltype(std::begin(selectors)); // Value constructor for use only in the compress function Compressed(Container&& container, Selector&& selectors) : container{container}, selectors{selectors} { } Compressed() = delete; Compressed& operator=(const Compressed&) = delete; public: Compressed(const Compressed&) = default; class Iterator { private: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; selector_iter_type selector_iter; const selector_iter_type selector_end; void increment_iterators() { ++this->sub_iter; ++this->selector_iter; } void skip_failures() { while (this->sub_iter != this->sub_end && this->selector_iter != this->selector_end && !*this->selector_iter) { this->increment_iterators(); } } public: Iterator (iterator_type<Container> cont_iter, iterator_type<Container> cont_end, selector_iter_type sel_iter, selector_iter_type sel_end) : sub_iter{cont_iter}, sub_end{cont_end}, selector_iter{sel_iter}, selector_end{sel_end} { this->skip_failures(); } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator & operator++() { this->increment_iterators(); this->skip_failures(); return *this; } bool operator!=(const Iterator & other) const { return this->sub_iter != other.sub_iter && this->selector_iter != other.selector_iter; } }; Iterator begin() const { return {std::begin(this->container), std::end(this->container), std::begin(this->selectors), std::end(this->selectors)}; } Iterator end() const { return {std::end(this->container), std::end(this->container), std::end(this->selectors), std::end(this->selectors)}; } }; // Helper function to instantiate an Compressed template <typename Container, typename Selector> Compressed<Container, Selector> compress( Container&& container, Selector&& selectors) { return {std::forward<Container>(container), std::forward<Selector>(selectors)}; } template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>&& data, Selector&& selectors) { return {std::move(data), std::forward<Selector>(selectors)}; } template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&& container, std::initializer_list<T>&& selectors) { return {std::forward<Container>(container), std::move(selectors)}; } template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&& data, std::initializer_list<U>&& selectors) { return {std::move(data), std::move(selectors)}; } } #endif //ifndef COMPRESS__H__ <commit_msg>formats compress.hpp<commit_after>#ifndef COMPRESS__H__ #define COMPRESS__H__ #include "iterbase.hpp" #include <utility> #include <initializer_list> namespace iter { //Forward declarations of Compressed and compress template <typename Container, typename Selector> class Compressed; template <typename Container, typename Selector> Compressed<Container, Selector> compress(Container&&, Selector&&); template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>&&, Selector&&); template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&&, std::initializer_list<T>&&); template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&&, std::initializer_list<U>&&); template <typename Container, typename Selector> class Compressed { private: Container& container; Selector & selectors; // The only thing allowed to directly instantiate an Compressed is // the compress function friend Compressed compress<Container, Selector>( Container&&, Selector&&); template <typename T, typename Sel> friend Compressed<std::initializer_list<T>, Sel> compress( std::initializer_list<T>&&, Sel&&); template <typename Con, typename T> friend Compressed<Con, std::initializer_list<T>> compress( Con&&, std::initializer_list<T>&&); template <typename T, typename U> friend Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&&, std::initializer_list<U>&&); // Selector::Iterator type using selector_iter_type = decltype(std::begin(selectors)); // Value constructor for use only in the compress function Compressed(Container&& container, Selector&& selectors) : container{container}, selectors{selectors} { } Compressed() = delete; Compressed& operator=(const Compressed&) = delete; public: Compressed(const Compressed&) = default; class Iterator { private: iterator_type<Container> sub_iter; const iterator_type<Container> sub_end; selector_iter_type selector_iter; const selector_iter_type selector_end; void increment_iterators() { ++this->sub_iter; ++this->selector_iter; } void skip_failures() { while (this->sub_iter != this->sub_end && this->selector_iter != this->selector_end && !*this->selector_iter) { this->increment_iterators(); } } public: Iterator (iterator_type<Container> cont_iter, iterator_type<Container> cont_end, selector_iter_type sel_iter, selector_iter_type sel_end) : sub_iter{cont_iter}, sub_end{cont_end}, selector_iter{sel_iter}, selector_end{sel_end} { this->skip_failures(); } iterator_deref<Container> operator*() const { return *this->sub_iter; } Iterator& operator++() { this->increment_iterators(); this->skip_failures(); return *this; } bool operator!=(const Iterator& other) const { return this->sub_iter != other.sub_iter && this->selector_iter != other.selector_iter; } }; Iterator begin() const { return {std::begin(this->container), std::end(this->container), std::begin(this->selectors), std::end(this->selectors)}; } Iterator end() const { return {std::end(this->container), std::end(this->container), std::end(this->selectors), std::end(this->selectors)}; } }; // Helper function to instantiate an Compressed template <typename Container, typename Selector> Compressed<Container, Selector> compress( Container&& container, Selector&& selectors) { return {std::forward<Container>(container), std::forward<Selector>(selectors)}; } template <typename T, typename Selector> Compressed<std::initializer_list<T>, Selector> compress( std::initializer_list<T>&& data, Selector&& selectors) { return {std::move(data), std::forward<Selector>(selectors)}; } template <typename Container, typename T> Compressed<Container, std::initializer_list<T>> compress( Container&& container, std::initializer_list<T>&& selectors) { return {std::forward<Container>(container), std::move(selectors)}; } template <typename T, typename U> Compressed<std::initializer_list<T>, std::initializer_list<U>> compress( std::initializer_list<T>&& data, std::initializer_list<U>&& selectors) { return {std::move(data), std::move(selectors)}; } } #endif //ifndef COMPRESS__H__ <|endoftext|>
<commit_before>/*========================================================================= Library: CTK Copyright (c) Kitware 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.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. =========================================================================*/ // Qt includes #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QVariant> #include <QDate> #include <QStringList> #include <QSet> #include <QFile> #include <QDirIterator> #include <QFileInfo> #include <QDebug> #include <QPixmap> // ctkDICOM includes #include "ctkDICOMIndexer.h" #include "ctkDICOMIndexer_p.h" #include "ctkDICOMDatabase.h" // DCMTK includes #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdatset.h> #include <dcmtk/ofstd/ofcond.h> #include <dcmtk/ofstd/ofstring.h> #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */ #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */ #include <dcmtk/dcmimgle/dcmimage.h> /* for class DicomImage */ #include <dcmtk/dcmimage/diregist.h> /* include support for color images */ //------------------------------------------------------------------------------ // ctkDICOMIndexerPrivate methods //------------------------------------------------------------------------------ ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate(ctkDICOMIndexer& o) : q_ptr(&o), Canceled(false) { } //------------------------------------------------------------------------------ ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate() { } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // ctkDICOMIndexer methods //------------------------------------------------------------------------------ ctkDICOMIndexer::ctkDICOMIndexer(QObject *parent):d_ptr(new ctkDICOMIndexerPrivate(*this)) { Q_UNUSED(parent); } //------------------------------------------------------------------------------ ctkDICOMIndexer::~ctkDICOMIndexer() { } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addFile(ctkDICOMDatabase& database, const QString filePath, const QString & sourceDirectoryName, const QString& destinationDirectoryName) { qDebug() << "Currently processing " << filePath; if ( !destinationDirectoryName.isEmpty() ) { qDebug() << "Copying " << filePath << " into the destination directory: " << destinationDirectoryName; } emit indexingFilePath( filePath ); database.insert( filePath, !destinationDirectoryName.isEmpty(), true, true, sourceDirectoryName, destinationDirectoryName ); } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addDirectory(ctkDICOMDatabase& ctkDICOMDatabase, const QString& directoryName, const QString& destinationDirectoryName) { QStringList listOfFiles; QDir directory(directoryName); if(directory.exists("DICOMDIR")) { addDicomdir(ctkDICOMDatabase,directoryName,destinationDirectoryName); } else { QDirIterator it(directoryName,QDir::Files,QDirIterator::Subdirectories); qDebug() << "Iterating subdirs of \"" << directory << "\""; while(it.hasNext()) { QString currentPath( it.next() ); qDebug() << "Currently in subdir \"" << currentPath << "\""; listOfFiles << currentPath; } emit foundFilesToIndex(listOfFiles.count()); addListOfFiles( ctkDICOMDatabase, listOfFiles, directoryName, destinationDirectoryName ); } } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addListOfFiles(ctkDICOMDatabase& ctkDICOMDatabase, const QStringList& listOfFiles, const QString & sourceDirectoryName, const QString& destinationDirectoryName) { Q_D(ctkDICOMIndexer); d->Canceled = false; int CurrentFileIndex = 0; if ( !destinationDirectoryName.isEmpty() ) { qDebug() << "destinationDirectory is set to " << destinationDirectoryName; } foreach(QString filePath, listOfFiles) { int percent = ( 100 * CurrentFileIndex ) / listOfFiles.size(); emit this->progress(percent); this->addFile( ctkDICOMDatabase, filePath, sourceDirectoryName, destinationDirectoryName ); CurrentFileIndex++; if( d->Canceled ) { break; } } emit this->indexingComplete(); } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addDicomdir( ctkDICOMDatabase & ctkDICOMDatabase, const QString & directoryName, const QString & destinationDirectoryName ) { //Initialize dicomdir with directory path QString dcmFilePath = directoryName; dcmFilePath.append( "/DICOMDIR" ); DcmDicomDir * dicomDir = new DcmDicomDir( dcmFilePath.toStdString().c_str() ); //Values to store records data at the moment only uid needed OFString patientsName, studyInstanceUID, seriesInstanceUID, sopInstanceUID, referencedFileName ; //Variables for progress operations QString instanceFilePath; QStringList listOfInstances; DcmDirectoryRecord * rootRecord = &( dicomDir->getRootRecord() ); DcmDirectoryRecord * patientRecord = NULL; DcmDirectoryRecord * studyRecord = NULL; DcmDirectoryRecord * seriesRecord = NULL; DcmDirectoryRecord * fileRecord = NULL; /*Iterate over all records in dicomdir and setup path to the dataset of the filerecord then insert. the filerecord into the database. If any UID is missing the record and all of it's subelements won't be added to the database*/ bool success = true; if(rootRecord != NULL) { while ((patientRecord = rootRecord->nextSub(patientRecord)) != NULL) { logger.debug( "Reading new Patient:" ); if (patientRecord->findAndGetOFString(DCM_PatientName, patientsName).bad()) { logger.warn( "DICOMDIR file at "+directoryName+" is invalid: patient name not found. All records belonging to this patient will be ignored."); success = false; continue; } logger.debug( "Patient's Name: " + QString(patientsName.c_str()) ); while ((studyRecord = patientRecord->nextSub(studyRecord)) != NULL) { logger.debug( "Reading new Study:" ); if (studyRecord->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).bad()) { logger.warn( "DICOMDIR file at "+directoryName+" is invalid: study instance UID not found for patient "+ QString(patientsName.c_str())+". All records belonging to this study will be ignored."); success = false; continue; } logger.debug( "Study instance UID: " + QString(studyInstanceUID.c_str()) ); while ((seriesRecord = studyRecord->nextSub(seriesRecord)) != NULL) { logger.debug( "Reading new Series:" ); if (seriesRecord->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).bad()) { logger.warn( "DICOMDIR file at "+directoryName+" is invalid: series instance UID not found for patient "+ QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+". All records belonging to this series will be ignored."); success = false; continue; } logger.debug( "Series instance UID: " + QString(seriesInstanceUID.c_str()) ); while ((fileRecord = seriesRecord->nextSub(fileRecord)) != NULL) { if (fileRecord->findAndGetOFStringArray(DCM_ReferencedSOPInstanceUIDInFile, sopInstanceUID).bad() || fileRecord->findAndGetOFStringArray(DCM_ReferencedFileID,referencedFileName).bad()) { logger.warn( "DICOMDIR file at "+directoryName+" is invalid: referenced SOP instance UID or file name is invalid for patient " + QString(patientsName.c_str())+", study "+ QString(studyInstanceUID.c_str())+", series "+ QString(seriesInstanceUID.c_str())+ ". This file will be ignored."); success = false; continue; } //Get the filepath of the instance and insert it into a list instanceFilePath = directoryName; instanceFilePath.append( "/" ); instanceFilePath.append( QString( referencedFileName.c_str() ) ); instanceFilePath.replace( "\\", "/" ); listOfInstances << instanceFilePath; } } } } emit foundFilesToIndex( listOfInstances.count() ); addListOfFiles( ctkDICOMDatabase, listOfInstances, directoryName, destinationDirectoryName ); } return success; } //------------------------------------------------------------------------------ void ctkDICOMIndexer::refreshDatabase( ctkDICOMDatabase& dicomDatabase, const QString & directoryName ) { Q_UNUSED(dicomDatabase); Q_UNUSED(directoryName); /* * Probably this should go to the database class as well * Or we have to extend the interface to make possible what we do here * without using SQL directly /// get all filenames from the database QSqlQuery allFilesQuery(dicomDatabase.database()); QStringList databaseFileNames; QStringList filesToRemove; this->loggedExec(allFilesQuery, "SELECT Filename from Images;"); while (allFilesQuery.next()) { QString fileName = allFilesQuery.value(0).toString(); databaseFileNames.append(fileName); if (! QFile::exists(fileName) ) { filesToRemove.append(fileName); } } QSet<QString> filesytemFiles; QDirIterator dirIt(directoryName); while (dirIt.hasNext()) { filesytemFiles.insert(dirIt.next()); } // TODO: it looks like this function was never finished... // // I guess the next step is to remove all filesToRemove from the database // and also to add filesystemFiles into the database tables */ } //------------------------------------------------------------------------------ void ctkDICOMIndexer::waitForImportFinished() { // No-op - this had been used when the indexing was multi-threaded, // and has only been retained for API compatibility. } //---------------------------------------------------------------------------- void ctkDICOMIndexer::cancel() { Q_D(ctkDICOMIndexer); d->Canceled = true; } <commit_msg>COMP: Fix due to the issues caused by merging with main CTK repo<commit_after>/*========================================================================= Library: CTK Copyright (c) Kitware 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.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. =========================================================================*/ // Qt includes #include <QSqlQuery> #include <QSqlRecord> #include <QSqlError> #include <QVariant> #include <QDate> #include <QStringList> #include <QSet> #include <QFile> #include <QDirIterator> #include <QFileInfo> #include <QDebug> #include <QPixmap> // ctkDICOM includes #include "ctkDICOMIndexer.h" #include "ctkDICOMIndexer_p.h" #include "ctkDICOMDatabase.h" // DCMTK includes #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcfilefo.h> #include <dcmtk/dcmdata/dcdeftag.h> #include <dcmtk/dcmdata/dcdatset.h> #include <dcmtk/ofstd/ofcond.h> #include <dcmtk/ofstd/ofstring.h> #include <dcmtk/ofstd/ofstd.h> /* for class OFStandard */ #include <dcmtk/dcmdata/dcddirif.h> /* for class DicomDirInterface */ #include <dcmtk/dcmimgle/dcmimage.h> /* for class DicomImage */ #include <dcmtk/dcmimage/diregist.h> /* include support for color images */ //------------------------------------------------------------------------------ // ctkDICOMIndexerPrivate methods //------------------------------------------------------------------------------ ctkDICOMIndexerPrivate::ctkDICOMIndexerPrivate(ctkDICOMIndexer& o) : q_ptr(&o), Canceled(false) { } //------------------------------------------------------------------------------ ctkDICOMIndexerPrivate::~ctkDICOMIndexerPrivate() { } //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // ctkDICOMIndexer methods //------------------------------------------------------------------------------ ctkDICOMIndexer::ctkDICOMIndexer(QObject *parent):d_ptr(new ctkDICOMIndexerPrivate(*this)) { Q_UNUSED(parent); } //------------------------------------------------------------------------------ ctkDICOMIndexer::~ctkDICOMIndexer() { } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addFile(ctkDICOMDatabase& database, const QString filePath, const QString & sourceDirectoryName, const QString& destinationDirectoryName) { qDebug() << "Currently processing " << filePath; if ( !destinationDirectoryName.isEmpty() ) { qDebug() << "Copying " << filePath << " into the destination directory: " << destinationDirectoryName; } emit indexingFilePath( filePath ); database.insert( filePath, !destinationDirectoryName.isEmpty(), true, true, sourceDirectoryName, destinationDirectoryName ); } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addDirectory(ctkDICOMDatabase& ctkDICOMDatabase, const QString& directoryName, const QString& destinationDirectoryName) { QStringList listOfFiles; QDir directory(directoryName); if(directory.exists("DICOMDIR")) { addDicomdir(ctkDICOMDatabase,directoryName,destinationDirectoryName); } else { QDirIterator it(directoryName,QDir::Files,QDirIterator::Subdirectories); qDebug() << "Iterating subdirs of \"" << directory << "\""; while(it.hasNext()) { QString currentPath( it.next() ); qDebug() << "Currently in subdir \"" << currentPath << "\""; listOfFiles << currentPath; } emit foundFilesToIndex(listOfFiles.count()); addListOfFiles( ctkDICOMDatabase, listOfFiles, directoryName, destinationDirectoryName ); } } //------------------------------------------------------------------------------ void ctkDICOMIndexer::addListOfFiles(ctkDICOMDatabase& ctkDICOMDatabase, const QStringList& listOfFiles, const QString & sourceDirectoryName, const QString& destinationDirectoryName) { Q_D(ctkDICOMIndexer); d->Canceled = false; int CurrentFileIndex = 0; if ( !destinationDirectoryName.isEmpty() ) { qDebug() << "destinationDirectory is set to " << destinationDirectoryName; } foreach(QString filePath, listOfFiles) { int percent = ( 100 * CurrentFileIndex ) / listOfFiles.size(); emit this->progress(percent); this->addFile( ctkDICOMDatabase, filePath, sourceDirectoryName, destinationDirectoryName ); CurrentFileIndex++; if( d->Canceled ) { break; } } emit this->indexingComplete(); } //------------------------------------------------------------------------------ bool ctkDICOMIndexer::addDicomdir( ctkDICOMDatabase & ctkDICOMDatabase, const QString & directoryName, const QString & destinationDirectoryName ) { //Initialize dicomdir with directory path QString dcmFilePath = directoryName; dcmFilePath.append( "/DICOMDIR" ); DcmDicomDir * dicomDir = new DcmDicomDir( dcmFilePath.toStdString().c_str() ); //Values to store records data at the moment only uid needed OFString patientsName, studyInstanceUID, seriesInstanceUID, sopInstanceUID, referencedFileName ; //Variables for progress operations QString instanceFilePath; QStringList listOfInstances; DcmDirectoryRecord * rootRecord = &( dicomDir->getRootRecord() ); DcmDirectoryRecord * patientRecord = NULL; DcmDirectoryRecord * studyRecord = NULL; DcmDirectoryRecord * seriesRecord = NULL; DcmDirectoryRecord * fileRecord = NULL; /*Iterate over all records in dicomdir and setup path to the dataset of the filerecord then insert. the filerecord into the database. If any UID is missing the record and all of it's subelements won't be added to the database*/ bool success = true; if(rootRecord != NULL) { while ((patientRecord = rootRecord->nextSub(patientRecord)) != NULL) { qDebug() << "Reading new Patient:"; if (patientRecord->findAndGetOFString(DCM_PatientName, patientsName).bad()) { qDebug() << "DICOMDIR file at " << directoryName << " is invalid: patient name not found. All records belonging to this patient will be ignored."; success = false; continue; } qDebug() << "Patient's Name: " << QString( patientsName.c_str() ); while ((studyRecord = patientRecord->nextSub(studyRecord)) != NULL) { qDebug() << "Reading new Study:"; if (studyRecord->findAndGetOFString(DCM_StudyInstanceUID, studyInstanceUID).bad()) { qDebug() << "DICOMDIR file at " << directoryName << " is invalid: study instance UID not found for patient " << QString(patientsName.c_str()) << ". All records belonging to this study will be ignored."; success = false; continue; } qDebug() << "Study instance UID: " << QString(studyInstanceUID.c_str()); while ((seriesRecord = studyRecord->nextSub(seriesRecord)) != NULL) { qDebug() << "Reading new Series:"; if (seriesRecord->findAndGetOFString(DCM_SeriesInstanceUID, seriesInstanceUID).bad()) { qDebug() << "DICOMDIR file at " << directoryName << " is invalid: series instance UID not found for patient " << QString(patientsName.c_str()) << ", study " << QString(studyInstanceUID.c_str()) << ". All records belonging to this series will be ignored."; success = false; continue; } qDebug() << "Series instance UID: " << QString(seriesInstanceUID.c_str()); while ((fileRecord = seriesRecord->nextSub(fileRecord)) != NULL) { if (fileRecord->findAndGetOFStringArray(DCM_ReferencedSOPInstanceUIDInFile, sopInstanceUID).bad() || fileRecord->findAndGetOFStringArray(DCM_ReferencedFileID,referencedFileName).bad()) { qDebug() << "DICOMDIR file at " << directoryName << " is invalid: referenced SOP instance UID or file name is invalid for patient " << QString(patientsName.c_str()) << ", study " << QString(studyInstanceUID.c_str()) << ", series " << QString(seriesInstanceUID.c_str()) << ". This file will be ignored."; success = false; continue; } //Get the filepath of the instance and insert it into a list instanceFilePath = directoryName; instanceFilePath.append( "/" ); instanceFilePath.append( QString( referencedFileName.c_str() ) ); instanceFilePath.replace( "\\", "/" ); listOfInstances << instanceFilePath; } } } } emit foundFilesToIndex( listOfInstances.count() ); addListOfFiles( ctkDICOMDatabase, listOfInstances, directoryName, destinationDirectoryName ); } return success; } //------------------------------------------------------------------------------ void ctkDICOMIndexer::refreshDatabase( ctkDICOMDatabase& dicomDatabase, const QString & directoryName ) { Q_UNUSED(dicomDatabase); Q_UNUSED(directoryName); /* * Probably this should go to the database class as well * Or we have to extend the interface to make possible what we do here * without using SQL directly /// get all filenames from the database QSqlQuery allFilesQuery(dicomDatabase.database()); QStringList databaseFileNames; QStringList filesToRemove; this->loggedExec(allFilesQuery, "SELECT Filename from Images;"); while (allFilesQuery.next()) { QString fileName = allFilesQuery.value(0).toString(); databaseFileNames.append(fileName); if (! QFile::exists(fileName) ) { filesToRemove.append(fileName); } } QSet<QString> filesytemFiles; QDirIterator dirIt(directoryName); while (dirIt.hasNext()) { filesytemFiles.insert(dirIt.next()); } // TODO: it looks like this function was never finished... // // I guess the next step is to remove all filesToRemove from the database // and also to add filesystemFiles into the database tables */ } //------------------------------------------------------------------------------ void ctkDICOMIndexer::waitForImportFinished() { // No-op - this had been used when the indexing was multi-threaded, // and has only been retained for API compatibility. } //---------------------------------------------------------------------------- void ctkDICOMIndexer::cancel() { Q_D(ctkDICOMIndexer); d->Canceled = true; } <|endoftext|>
<commit_before>#include "MT_XDFDialogs.h" enum { ID_X_CHOICE = wxID_HIGHEST + 1, ID_Y_CHOICE, ID_TIMESTEP }; MT_LoadXDFDialog::MT_LoadXDFDialog(wxWindow* parent, MT_ExperimentDataFile* pXDF) : wxDialog(parent, wxID_ANY, wxT("XDF Settings"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE), m_pXDF(pXDF) { /* gather relevant information from XDF */ std::vector<std::string> datanames; std::vector<std::string> datafiles; m_pXDF->getFilesFromXML(&datanames, &datafiles); unsigned int x_guess = 0; unsigned int y_guess = 0; unsigned int frame_period_guess = 32; for(unsigned int i = 0; i < datanames.size(); i++) { wxString cname(datanames[i].c_str()); m_asXChoices.Add(cname); m_asYChoices.Add(cname); if(cname.Find(wxT("X")) != wxNOT_FOUND || cname.Find(wxT("x")) != wxNOT_FOUND) { x_guess = i; } if(cname.Find(wxT("Y")) != wxNOT_FOUND || cname.Find(wxT("y")) != wxNOT_FOUND) { y_guess = i; } } MT_XDFSettingsGroup* pDG = m_pXDF->getSettingsGroup(); m_pDG = pDG; if(pDG && (pDG->GetGroupName() == MT_XDFSettingsGroup::SettingsName)) { unsigned int i = pDG->GetIndexByName(MT_XDFSettingsGroup::XPlaybackName); if(i >= 0 && i < pDG->GetGroupSize()) { wxString X_Found(pDG->GetStringValue(i).c_str()); int j = m_asXChoices.Index(X_Found); if(j != wxNOT_FOUND) { x_guess = j; } } i = pDG->GetIndexByName(MT_XDFSettingsGroup::YPlaybackName); if(i >= 0 && i < pDG->GetGroupSize()) { wxString Y_Found(pDG->GetStringValue(i).c_str()); int j = m_asXChoices.Index(Y_Found); if(j != wxNOT_FOUND) { y_guess = j; } } i = pDG->GetIndexByName(MT_XDFSettingsGroup::PlaybackFramePeriodName); if(i >= 0 && i < pDG->GetGroupSize()) { int v = (int) pDG->GetNumericValue(i); if(v > 0) { frame_period_guess = v; } } } if(x_guess == y_guess) { y_guess = x_guess + 1; } /* GUI setup */ wxBoxSizer* vbox0 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* hbox0 = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* vbox1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* vbox2 = new wxBoxSizer(wxVERTICAL); vbox1->Add(new wxStaticText(this, wxID_ANY, wxT("X Data")), 0, wxLEFT | wxRIGHT, 10); m_pXChoice = new wxChoice(this, ID_X_CHOICE, wxDefaultPosition, wxSize(150, 20), m_asXChoices); vbox1->Add(m_pXChoice, 0, wxLEFT | wxRIGHT, 10); vbox2->Add(new wxStaticText(this, wxID_ANY, wxT("Y Data")), 0, wxLEFT | wxRIGHT, 10); m_pYChoice = new wxChoice(this, ID_Y_CHOICE, wxDefaultPosition, wxSize(150, 20), m_asYChoices); vbox2->Add(m_pYChoice, 0, wxLEFT | wxRIGHT, 10); hbox0->Add(vbox1); hbox0->Add(vbox2); vbox0->Add(hbox0, 0, wxTOP, 10); wxBoxSizer* hbox1 = new wxBoxSizer(wxHORIZONTAL); hbox1->Add(new wxStaticText(this, wxID_ANY, wxT("Time Step [msec]")), 0, wxLEFT | wxRIGHT, 10); wxString sDt; sDt.Printf("%d", frame_period_guess); m_pTimeStepCtrl = new wxTextCtrl(this, ID_TIMESTEP, sDt, wxDefaultPosition, wxSize(100, 20)); hbox1->Add(m_pTimeStepCtrl, 0, wxLEFT | wxRIGHT | wxALIGN_RIGHT, 10); vbox0->Add(hbox1, 0, wxLEFT | wxRIGHT | wxTOP | wxALIGN_RIGHT, 10); vbox0->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALL | wxALIGN_RIGHT, 10); SetSizerAndFit(vbox0); Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MT_LoadXDFDialog::onOKClicked)); Connect(ID_TIMESTEP, wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(MT_LoadXDFDialog::onTSChanged)); m_pXChoice->SetSelection(x_guess); m_pYChoice->SetSelection(y_guess); } void MT_LoadXDFDialog::onTSChanged(wxCommandEvent& event) { if(!(m_pTimeStepCtrl->IsModified())) { return; } MT_ValidateTextCtrlInteger(m_pTimeStepCtrl); } void MT_LoadXDFDialog::onOKClicked(wxCommandEvent& event) { std::string X_sel(m_pXChoice->GetStringSelection().mb_str()); std::string Y_sel(m_pYChoice->GetStringSelection().mb_str()); std::string FR(m_pTimeStepCtrl->GetValue().mb_str()); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::XPlaybackName, X_sel); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::YPlaybackName, Y_sel); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::PlaybackFramePeriodName, FR); if(IsModal()) { EndModal(wxID_OK); } else { Close(); } } void MT_LoadXDFDialog::getInfo(std::string* x_name, std::string* y_name, unsigned int* frame_period_msec) { *x_name = std::string(m_pXChoice->GetStringSelection().mb_str()); *y_name = std::string(m_pYChoice->GetStringSelection().mb_str()); *frame_period_msec = MT_ClampTextCtrlInt(m_pTimeStepCtrl, 0, MT_max_int); } <commit_msg>[MT_GUI, Unicode] Fixed problems with MT_LoadXDFDialog converting std::string to wxString.<commit_after>#include "MT_XDFDialogs.h" enum { ID_X_CHOICE = wxID_HIGHEST + 1, ID_Y_CHOICE, ID_TIMESTEP }; MT_LoadXDFDialog::MT_LoadXDFDialog(wxWindow* parent, MT_ExperimentDataFile* pXDF) : wxDialog(parent, wxID_ANY, wxT("XDF Settings"), wxDefaultPosition, wxDefaultSize, wxDEFAULT_DIALOG_STYLE), m_pXDF(pXDF) { /* gather relevant information from XDF */ std::vector<std::string> datanames; std::vector<std::string> datafiles; m_pXDF->getFilesFromXML(&datanames, &datafiles); unsigned int x_guess = 0; unsigned int y_guess = 0; unsigned int frame_period_guess = 32; for(unsigned int i = 0; i < datanames.size(); i++) { wxString cname(MT_StringToWxString(datanames[i].c_str())); m_asXChoices.Add(cname); m_asYChoices.Add(cname); if(cname.Find(wxT("X")) != wxNOT_FOUND || cname.Find(wxT("x")) != wxNOT_FOUND) { x_guess = i; } if(cname.Find(wxT("Y")) != wxNOT_FOUND || cname.Find(wxT("y")) != wxNOT_FOUND) { y_guess = i; } } MT_XDFSettingsGroup* pDG = m_pXDF->getSettingsGroup(); m_pDG = pDG; if(pDG && (pDG->GetGroupName() == MT_XDFSettingsGroup::SettingsName)) { unsigned int i = pDG->GetIndexByName(MT_XDFSettingsGroup::XPlaybackName); if(i >= 0 && i < pDG->GetGroupSize()) { wxString X_Found(MT_StringToWxString(pDG->GetStringValue(i).c_str())); int j = m_asXChoices.Index(X_Found); if(j != wxNOT_FOUND) { x_guess = j; } } i = pDG->GetIndexByName(MT_XDFSettingsGroup::YPlaybackName); if(i >= 0 && i < pDG->GetGroupSize()) { wxString Y_Found(MT_StringToWxString(pDG->GetStringValue(i).c_str())); int j = m_asXChoices.Index(Y_Found); if(j != wxNOT_FOUND) { y_guess = j; } } i = pDG->GetIndexByName(MT_XDFSettingsGroup::PlaybackFramePeriodName); if(i >= 0 && i < pDG->GetGroupSize()) { int v = (int) pDG->GetNumericValue(i); if(v > 0) { frame_period_guess = v; } } } if(x_guess == y_guess) { y_guess = x_guess + 1; } /* GUI setup */ wxBoxSizer* vbox0 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* hbox0 = new wxBoxSizer(wxHORIZONTAL); wxBoxSizer* vbox1 = new wxBoxSizer(wxVERTICAL); wxBoxSizer* vbox2 = new wxBoxSizer(wxVERTICAL); vbox1->Add(new wxStaticText(this, wxID_ANY, wxT("X Data")), 0, wxLEFT | wxRIGHT, 10); m_pXChoice = new wxChoice(this, ID_X_CHOICE, wxDefaultPosition, wxSize(150, 20), m_asXChoices); vbox1->Add(m_pXChoice, 0, wxLEFT | wxRIGHT, 10); vbox2->Add(new wxStaticText(this, wxID_ANY, wxT("Y Data")), 0, wxLEFT | wxRIGHT, 10); m_pYChoice = new wxChoice(this, ID_Y_CHOICE, wxDefaultPosition, wxSize(150, 20), m_asYChoices); vbox2->Add(m_pYChoice, 0, wxLEFT | wxRIGHT, 10); hbox0->Add(vbox1); hbox0->Add(vbox2); vbox0->Add(hbox0, 0, wxTOP, 10); wxBoxSizer* hbox1 = new wxBoxSizer(wxHORIZONTAL); hbox1->Add(new wxStaticText(this, wxID_ANY, wxT("Time Step [msec]")), 0, wxLEFT | wxRIGHT, 10); wxString sDt; sDt.Printf(wxT("%d"), frame_period_guess); m_pTimeStepCtrl = new wxTextCtrl(this, ID_TIMESTEP, sDt, wxDefaultPosition, wxSize(100, 20)); hbox1->Add(m_pTimeStepCtrl, 0, wxLEFT | wxRIGHT | wxALIGN_RIGHT, 10); vbox0->Add(hbox1, 0, wxLEFT | wxRIGHT | wxTOP | wxALIGN_RIGHT, 10); vbox0->Add(CreateButtonSizer(wxOK | wxCANCEL), 0, wxALL | wxALIGN_RIGHT, 10); SetSizerAndFit(vbox0); Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(MT_LoadXDFDialog::onOKClicked)); Connect(ID_TIMESTEP, wxEVT_COMMAND_TEXT_UPDATED, wxCommandEventHandler(MT_LoadXDFDialog::onTSChanged)); m_pXChoice->SetSelection(x_guess); m_pYChoice->SetSelection(y_guess); } void MT_LoadXDFDialog::onTSChanged(wxCommandEvent& event) { if(!(m_pTimeStepCtrl->IsModified())) { return; } MT_ValidateTextCtrlInteger(m_pTimeStepCtrl); } void MT_LoadXDFDialog::onOKClicked(wxCommandEvent& event) { std::string X_sel(m_pXChoice->GetStringSelection().mb_str()); std::string Y_sel(m_pYChoice->GetStringSelection().mb_str()); std::string FR(m_pTimeStepCtrl->GetValue().mb_str()); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::XPlaybackName, X_sel); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::YPlaybackName, Y_sel); m_pDG->SetStringValueByName(MT_XDFSettingsGroup::PlaybackFramePeriodName, FR); if(IsModal()) { EndModal(wxID_OK); } else { Close(); } } void MT_LoadXDFDialog::getInfo(std::string* x_name, std::string* y_name, unsigned int* frame_period_msec) { *x_name = std::string(m_pXChoice->GetStringSelection().mb_str()); *y_name = std::string(m_pYChoice->GetStringSelection().mb_str()); *frame_period_msec = MT_ClampTextCtrlInt(m_pTimeStepCtrl, 0, MT_max_int); } <|endoftext|>
<commit_before>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONTrackerPreprocessor.h" #include "AliMUONPedestalSubprocessor.h" #include "AliMUONHVSubprocessor.h" #include "AliMUONGMSSubprocessor.h" #include "AliLog.h" #include "AliShuttleInterface.h" #include "Riostream.h" #include "TObjArray.h" /// \class AliMUONTrackerPreprocessor /// /// Shuttle preprocessor for MUON tracker /// /// It's simply a manager class that deals with a list of sub-tasks /// (of type AliMUONVSubprocessor). /// /// \author Laurent Aphecetche /// \cond CLASSIMP ClassImp(AliMUONTrackerPreprocessor) /// \endcond //_____________________________________________________________________________ AliMUONTrackerPreprocessor::AliMUONTrackerPreprocessor(AliShuttleInterface* shuttle) : AliMUONPreprocessor("MCH",shuttle), fPedestalSubprocessor(new AliMUONPedestalSubprocessor(this)), fGMSSubprocessor(new AliMUONGMSSubprocessor(this)), fHVSubprocessor(new AliMUONHVSubprocessor(this)) { /// ctor. } //_____________________________________________________________________________ AliMUONTrackerPreprocessor::~AliMUONTrackerPreprocessor() { /// dtor delete fPedestalSubprocessor; delete fGMSSubprocessor; delete fHVSubprocessor; } //_____________________________________________________________________________ void AliMUONTrackerPreprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime) { ClearSubprocessors(); TString runType = GetRunType(); if ( runType == "PEDESTAL_RUN" ) // FIXME : check the name { Add(fPedestalSubprocessor); // to be called only for pedestal runs Log("INFO-Will run Pedestal subprocessor"); } else if ( runType == "ELECTRONICS_CALIBRATION_RUN" ) // FIXME : check the name { Log("WARNING-Subprocessor for gains not yet implemented"); //fSubprocessors->Add(new AliMUONGainSubprocessor(this)); // to be called only for gain runs } else if ( runType == "GMS" ) // FIXME : check the name { Add(fGMSSubprocessor); Log("INFO-Will run GMS subprocessor"); } else if ( runType == "PHYSICS" ) // FIXME : check the name { Add(fHVSubprocessor); // to be called only for physics runs Log("INFO-Will run HV subprocessor"); } else { Log(Form("ERROR-Unknown RunType=%",runType.Data())); } AliMUONPreprocessor::Initialize(run,startTime,endTime); } <commit_msg>Adding comment<commit_after>/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ // $Id$ #include "AliMUONTrackerPreprocessor.h" #include "AliMUONPedestalSubprocessor.h" #include "AliMUONHVSubprocessor.h" #include "AliMUONGMSSubprocessor.h" #include "AliLog.h" #include "AliShuttleInterface.h" #include "Riostream.h" #include "TObjArray.h" /// \class AliMUONTrackerPreprocessor /// /// Shuttle preprocessor for MUON tracker /// /// It's simply a manager class that deals with a list of sub-tasks /// (of type AliMUONVSubprocessor). /// /// \author Laurent Aphecetche /// \cond CLASSIMP ClassImp(AliMUONTrackerPreprocessor) /// \endcond //_____________________________________________________________________________ AliMUONTrackerPreprocessor::AliMUONTrackerPreprocessor(AliShuttleInterface* shuttle) : AliMUONPreprocessor("MCH",shuttle), fPedestalSubprocessor(new AliMUONPedestalSubprocessor(this)), fGMSSubprocessor(new AliMUONGMSSubprocessor(this)), fHVSubprocessor(new AliMUONHVSubprocessor(this)) { /// ctor. } //_____________________________________________________________________________ AliMUONTrackerPreprocessor::~AliMUONTrackerPreprocessor() { /// dtor delete fPedestalSubprocessor; delete fGMSSubprocessor; delete fHVSubprocessor; } //_____________________________________________________________________________ void AliMUONTrackerPreprocessor::Initialize(Int_t run, UInt_t startTime, UInt_t endTime) { /// Re-register the subprocessor(s) depnding on the actual runTYpe ClearSubprocessors(); TString runType = GetRunType(); if ( runType == "PEDESTAL_RUN" ) // FIXME : check the name { Add(fPedestalSubprocessor); // to be called only for pedestal runs Log("INFO-Will run Pedestal subprocessor"); } else if ( runType == "ELECTRONICS_CALIBRATION_RUN" ) // FIXME : check the name { Log("WARNING-Subprocessor for gains not yet implemented"); //fSubprocessors->Add(new AliMUONGainSubprocessor(this)); // to be called only for gain runs } else if ( runType == "GMS" ) // FIXME : check the name { Add(fGMSSubprocessor); Log("INFO-Will run GMS subprocessor"); } else if ( runType == "PHYSICS" ) // FIXME : check the name { Add(fHVSubprocessor); // to be called only for physics runs Log("INFO-Will run HV subprocessor"); } else { Log(Form("ERROR-Unknown RunType=%",runType.Data())); } AliMUONPreprocessor::Initialize(run,startTime,endTime); } <|endoftext|>
<commit_before>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "sfidl-generator.hh" #include "sfidl-options.hh" #include "sfidl-parser.hh" using namespace Sfidl; int main (int argc, char **argv) { Options options; Parser parser; if (!options.parse (&argc, &argv, parser)) { /* invalid options */ return 1; } if (options.doExit) { return 0; } if (options.doHelp) { options.printUsage (); return 0; } if (argc != 2) { options.printUsage (); return 1; } if (!options.codeGenerator) { options.printUsage(); return 1; } if (!parser.parse(argv[1])) { /* parse error */ return 1; } if (!options.codeGenerator->run ()) { delete options.codeGenerator; return 1; } delete options.codeGenerator; return 0; } #include "sfidl-generator.cc" #include "sfidl-namespace.cc" #include "sfidl-options.cc" #include "sfidl-parser.cc" #include "sfidl-factory.cc" #include "sfidl-typelist.cc" #include "sfidl-cbase.cc" #include "sfidl-clientc.cc" #include "sfidl-clientcxx.cc" #include "sfidl-corec.cc" #include "sfidl-corecxx.cc" #include "sfidl-cxxbase.cc" #include "sfidl-hostc.cc" #include "sfidl-utils.cc" /* vim:set ts=8 sts=2 sw=2: */ <commit_msg>SFI: sfidl.cc: main: abort if an assertion is triggered<commit_after>// Licensed GNU LGPL v2.1 or later: http://www.gnu.org/licenses/lgpl.html #include "sfidl-generator.hh" #include "sfidl-options.hh" #include "sfidl-parser.hh" using namespace Sfidl; int main (int argc, char **argv) { Bse::assertion_failed_hook ([&] () { Bse::breakpoint(); }); Options options; Parser parser; if (!options.parse (&argc, &argv, parser)) { /* invalid options */ return 1; } if (options.doExit) { return 0; } if (options.doHelp) { options.printUsage (); return 0; } if (argc != 2) { options.printUsage (); return 1; } if (!options.codeGenerator) { options.printUsage(); return 1; } if (!parser.parse(argv[1])) { /* parse error */ return 1; } if (!options.codeGenerator->run ()) { delete options.codeGenerator; return 1; } delete options.codeGenerator; return 0; } #include "sfidl-generator.cc" #include "sfidl-namespace.cc" #include "sfidl-options.cc" #include "sfidl-parser.cc" #include "sfidl-factory.cc" #include "sfidl-typelist.cc" #include "sfidl-cbase.cc" #include "sfidl-clientc.cc" #include "sfidl-clientcxx.cc" #include "sfidl-corec.cc" #include "sfidl-corecxx.cc" #include "sfidl-cxxbase.cc" #include "sfidl-hostc.cc" #include "sfidl-utils.cc" /* vim:set ts=8 sts=2 sw=2: */ <|endoftext|>
<commit_before>// MapView.cpp : Դϴ. // #include "stdafx.h" #include "MapTool.h" #include "MapView.h" #include "../../etc/Utility.h" #include "MainPanel.h" CMapView *g_mapView = NULL; vector<graphic::cCube*> g_cubes; using namespace graphic; const int WINSIZE_X = 1024; //ʱ ũ const int WINSIZE_Y = 768; //ʱ ũ // CMapView CMapView::CMapView() : m_dxInit(false) , m_RButtonDown(false) { g_mapView = this; } CMapView::~CMapView() { } BEGIN_MESSAGE_MAP(CMapView, CView) ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONUP() ON_WM_KEYDOWN() END_MESSAGE_MAP() // CMapView ׸Դϴ. void CMapView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: ⿡ ׸ ڵ带 ߰մϴ. } // CMapView Դϴ. #ifdef _DEBUG void CMapView::AssertValid() const { CView::AssertValid(); } #ifndef _WIN32_WCE void CMapView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif #endif //_DEBUG // CMapView ޽ óԴϴ. LPDIRECT3DDEVICE9 g_pDevice; LPDIRECT3DDEVICE9 graphic::GetDevice() { return g_pDevice; } bool CMapView::Init() { if (!graphic::InitDirectX(m_hWnd, WINSIZE_X, WINSIZE_Y, g_pDevice)) { return 0; } m_camPos = Vector3(100,100,-500); m_lookAtPos = Vector3(0,0,0); UpdateCamera(); m_matProj.SetProjection(D3DX_PI / 4.f, (float)WINSIZE_X / (float) WINSIZE_Y, 1.f, 10000.0f) ; graphic::GetDevice()->SetTransform(D3DTS_PROJECTION, (D3DXMATRIX*)&m_matProj) ; graphic::GetDevice()->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); graphic::GetDevice()->LightEnable ( 0, // Ȱȭ/ Ȱȭ Ϸ Ʈ true); // true = Ȱȭ false = Ȱȭ m_grid.Create(64,64,50.f); m_cube.SetCube(Vector3(-10,-10,-10), Vector3(10,10,10)); m_cube.SetColor( 0xFF0000FF ); m_dxInit = true; return true; } void CMapView::Render() { if (!m_dxInit) return; //ȭ û if (SUCCEEDED(g_pDevice->Clear( 0, //û D3DRECT 迭 ( ü Ŭ 0 ) NULL, //û D3DRECT 迭 ( ü Ŭ NULL ) D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, //ûҵ ÷ ( D3DCLEAR_TARGET ÷, D3DCLEAR_ZBUFFER ̹, D3DCLEAR_STENCIL ٽǹ D3DCOLOR_XRGB(150, 150, 150), //÷۸ ûϰ ä ( 0xAARRGGBB ) 1.0f, //̹۸ ûҰ ( 0 ~ 1 0 ī޶󿡼 ϰ 1 ī޶󿡼 ) 0 //ٽ ۸ äﰪ ))) { //ȭ ûҰ ̷ ٸ... g_pDevice->BeginScene(); //RenderFPS(timeDelta); GetDevice()->SetRenderState( D3DRS_LIGHTING, FALSE); Matrix44 matIdentity; GetDevice()->SetTransform( D3DTS_WORLD, (D3DMATRIX*)&matIdentity); m_grid.Render(); RenderAxis(); m_cube.Render(matIdentity); for (int i=0; i < (int)g_cubes.size(); ++i) g_cubes[ i]->Render(matIdentity); // g_pDevice->EndScene(); // ȭ g_pDevice->Present( NULL, NULL, NULL, NULL ); } } void CMapView::Update(float elapseT) { } void CMapView::OnMouseMove(UINT nFlags, CPoint point) { if (m_RButtonDown) { CPoint pos = point - m_curPos; m_curPos = point; { // rotate Y-Axis Quaternion q(Vector3(0,1,0), pos.x * 0.005f); Matrix44 m = q.GetMatrix(); m_camPos *= m; } { // rotate X-Axis Quaternion q(Vector3(1,0,0), pos.y * 0.005f); Matrix44 m = q.GetMatrix(); m_camPos *= m; } UpdateCamera(); } else { Vector3 orig, dir, pickPos; GetRay(point.x, point.y, orig, dir); if (m_grid.Pick(point.x, point.y, orig, dir, pickPos)) { Matrix44 mT; mT.SetTranslate(pickPos); m_cube.SetTransform(mT); } } CView::OnMouseMove(nFlags, point); } void CMapView::OnLButtonDown(UINT nFlags, CPoint point) { Vector3 orig, dir, pickPos; GetRay(point.x, point.y, orig, dir); if (m_grid.Pick(point.x, point.y, orig, dir, pickPos)) { graphic::cCube *newCube = new graphic::cCube(); newCube->SetCube(Vector3(-10,-10,-10), Vector3(10,10,10)); newCube->SetTransform( m_cube.GetTransform() ); newCube->SetColor(0xFF0000); g_cubes.push_back( newCube ); g_mainPanel->InsertCube( *newCube ); } CView::OnLButtonDown(nFlags, point); } void CMapView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: ⿡ ޽ ó ڵ带 ߰ /Ǵ ⺻ ȣմϴ. CView::OnLButtonUp(nFlags, point); } void CMapView::OnRButtonDown(UINT nFlags, CPoint point) { SetFocus(); SetCapture(); m_RButtonDown = true; m_curPos = point; CView::OnRButtonDown(nFlags, point); } void CMapView::OnRButtonUp(UINT nFlags, CPoint point) { ReleaseCapture(); m_RButtonDown = false; CView::OnRButtonUp(nFlags, point); } void CMapView::UpdateCamera() { Vector3 dir = m_lookAtPos - m_camPos; dir.Normalize(); m_matView.SetView(m_camPos, dir, Vector3(0,1,0)); graphic::GetDevice()->SetTransform(D3DTS_VIEW, (D3DXMATRIX*)&m_matView); } void CMapView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar == VK_TAB) { static bool flag = false; GetDevice()->SetRenderState(D3DRS_CULLMODE, flag); GetDevice()->SetRenderState(D3DRS_FILLMODE, flag? D3DFILL_SOLID : D3DFILL_WIREFRAME); flag = !flag; } CView::OnKeyDown(nChar, nRepCnt, nFlags); } void CMapView::GetRay(int sx, int sy, Vector3 &orig, Vector3 &dir) { const float x = ((sx * 2.0F / WINSIZE_X) - 1.0F ); const float y = -((sy * 2.0F / WINSIZE_Y) - 1.0F ); Vector3 v; v.x = x / m_matProj._11; v.y = y / m_matProj._22; v.z = 1.0F; Matrix44 m = m_matView.Inverse(); dir.x = v.x * m._11 + v.y * m._21 + v.z * m._31; dir.y = v.x * m._12 + v.y * m._22 + v.z * m._32; dir.z = v.x * m._13 + v.y * m._23 + v.z * m._33; dir.Normalize(); orig.x = m._41; orig.y = m._42; orig.z = m._43; } void CMapView::SelectCube( int index ) { for (int i=0; i < (int)g_cubes.size(); ++i) g_cubes[ i]->SetColor( 0xFF0000 ); g_cubes[ index]->SetColor( 0x00FF00 ); } <commit_msg>update maptool bug<commit_after>// MapView.cpp : Դϴ. // #include "stdafx.h" #include "MapTool.h" #include "MapView.h" #include "../../etc/Utility.h" #include "MainPanel.h" CMapView *g_mapView = NULL; vector<graphic::cCube*> g_cubes; using namespace graphic; const int WINSIZE_X = 1024; //ʱ ũ const int WINSIZE_Y = 768; //ʱ ũ // CMapView CMapView::CMapView() : m_dxInit(false) , m_RButtonDown(false) { g_mapView = this; } CMapView::~CMapView() { } BEGIN_MESSAGE_MAP(CMapView, CView) ON_WM_MOUSEMOVE() ON_WM_LBUTTONDOWN() ON_WM_LBUTTONUP() ON_WM_RBUTTONDOWN() ON_WM_RBUTTONUP() ON_WM_KEYDOWN() END_MESSAGE_MAP() // CMapView ׸Դϴ. void CMapView::OnDraw(CDC* pDC) { CDocument* pDoc = GetDocument(); // TODO: ⿡ ׸ ڵ带 ߰մϴ. } // CMapView Դϴ. #ifdef _DEBUG void CMapView::AssertValid() const { CView::AssertValid(); } #ifndef _WIN32_WCE void CMapView::Dump(CDumpContext& dc) const { CView::Dump(dc); } #endif #endif //_DEBUG // CMapView ޽ óԴϴ. LPDIRECT3DDEVICE9 g_pDevice; LPDIRECT3DDEVICE9 graphic::GetDevice() { return g_pDevice; } bool CMapView::Init() { if (!graphic::InitDirectX(m_hWnd, WINSIZE_X, WINSIZE_Y, g_pDevice)) { return 0; } m_camPos = Vector3(100,100,-500); m_lookAtPos = Vector3(0,0,0); UpdateCamera(); m_matProj.SetProjection(D3DX_PI / 4.f, (float)WINSIZE_X / (float) WINSIZE_Y, 1.f, 10000.0f) ; graphic::GetDevice()->SetTransform(D3DTS_PROJECTION, (D3DXMATRIX*)&m_matProj) ; graphic::GetDevice()->SetRenderState(D3DRS_NORMALIZENORMALS, TRUE); graphic::GetDevice()->LightEnable ( 0, // Ȱȭ/ Ȱȭ Ϸ Ʈ true); // true = Ȱȭ false = Ȱȭ m_grid.Create(64,64,50.f); m_cube.SetCube(Vector3(-10,-10,-10), Vector3(10,10,10)); m_cube.SetColor( 0xFF0000FF ); m_dxInit = true; return true; } void CMapView::Render() { if (!m_dxInit) return; //ȭ û if (SUCCEEDED(g_pDevice->Clear( 0, //û D3DRECT 迭 ( ü Ŭ 0 ) NULL, //û D3DRECT 迭 ( ü Ŭ NULL ) D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, //ûҵ ÷ ( D3DCLEAR_TARGET ÷, D3DCLEAR_ZBUFFER ̹, D3DCLEAR_STENCIL ٽǹ D3DCOLOR_XRGB(150, 150, 150), //÷۸ ûϰ ä ( 0xAARRGGBB ) 1.0f, //̹۸ ûҰ ( 0 ~ 1 0 ī޶󿡼 ϰ 1 ī޶󿡼 ) 0 //ٽ ۸ äﰪ ))) { //ȭ ûҰ ̷ ٸ... g_pDevice->BeginScene(); //RenderFPS(timeDelta); GetDevice()->SetRenderState( D3DRS_LIGHTING, FALSE); Matrix44 matIdentity; GetDevice()->SetTransform( D3DTS_WORLD, (D3DMATRIX*)&matIdentity); m_grid.Render(); RenderAxis(); m_cube.Render(matIdentity); for (int i=0; i < (int)g_cubes.size(); ++i) g_cubes[ i]->Render(matIdentity); // g_pDevice->EndScene(); // ȭ g_pDevice->Present( NULL, NULL, NULL, NULL ); } } void CMapView::Update(float elapseT) { } void CMapView::OnMouseMove(UINT nFlags, CPoint point) { if (m_RButtonDown) { CPoint pos = point - m_curPos; m_curPos = point; { // rotate Y-Axis Quaternion q(Vector3(0,1,0), pos.x * 0.005f); Matrix44 m = q.GetMatrix(); m_camPos *= m; } { // rotate X-Axis Quaternion q(Vector3(1,0,0), pos.y * 0.005f); Matrix44 m = q.GetMatrix(); m_camPos *= m; } UpdateCamera(); } else { Vector3 orig, dir, pickPos; GetRay(point.x, point.y, orig, dir); if (m_grid.Pick(point.x, point.y, orig, dir, pickPos)) { Matrix44 mT; mT.SetTranslate(pickPos); m_cube.SetTransform(mT); } } CView::OnMouseMove(nFlags, point); } void CMapView::OnLButtonDown(UINT nFlags, CPoint point) { Vector3 orig, dir, pickPos; GetRay(point.x, point.y, orig, dir); if (m_grid.Pick(point.x, point.y, orig, dir, pickPos)) { graphic::cCube *newCube = new graphic::cCube(); newCube->SetCube(Vector3(-10,-10,-10), Vector3(10,10,10)); newCube->SetTransform( m_cube.GetTransform() ); newCube->SetColor(0xFF0000); g_cubes.push_back( newCube ); g_mainPanel->InsertCube( *newCube ); } CView::OnLButtonDown(nFlags, point); } void CMapView::OnLButtonUp(UINT nFlags, CPoint point) { // TODO: ⿡ ޽ ó ڵ带 ߰ /Ǵ ⺻ ȣմϴ. CView::OnLButtonUp(nFlags, point); } void CMapView::OnRButtonDown(UINT nFlags, CPoint point) { SetFocus(); SetCapture(); m_RButtonDown = true; m_curPos = point; CView::OnRButtonDown(nFlags, point); } void CMapView::OnRButtonUp(UINT nFlags, CPoint point) { ReleaseCapture(); m_RButtonDown = false; CView::OnRButtonUp(nFlags, point); } void CMapView::UpdateCamera() { Vector3 dir = m_lookAtPos - m_camPos; dir.Normalize(); m_matView.SetView(m_camPos, dir, Vector3(0,1,0)); graphic::GetDevice()->SetTransform(D3DTS_VIEW, (D3DXMATRIX*)&m_matView); } void CMapView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags) { if (nChar == VK_TAB) { static bool flag = false; GetDevice()->SetRenderState(D3DRS_CULLMODE, flag); GetDevice()->SetRenderState(D3DRS_FILLMODE, flag? D3DFILL_SOLID : D3DFILL_WIREFRAME); flag = !flag; } CView::OnKeyDown(nChar, nRepCnt, nFlags); } void CMapView::GetRay(int sx, int sy, Vector3 &orig, Vector3 &dir) { const float x = ((sx * 2.0F / WINSIZE_X) - 1.0F ); const float y = -((sy * 2.0F / WINSIZE_Y) - 1.0F ); Vector3 v; v.x = x / m_matProj._11; v.y = y / m_matProj._22; v.z = 1.0F; Matrix44 m = m_matView.Inverse(); dir.x = v.x * m._11 + v.y * m._21 + v.z * m._31; dir.y = v.x * m._12 + v.y * m._22 + v.z * m._32; dir.z = v.x * m._13 + v.y * m._23 + v.z * m._33; dir.Normalize(); orig.x = m._41; orig.y = m._42; orig.z = m._43; } void CMapView::SelectCube( int index ) { if (index < 0) return; for (int i=0; i < (int)g_cubes.size(); ++i) g_cubes[ i]->SetColor( 0xFF0000 ); g_cubes[ index]->SetColor( 0x00FF00 ); } <|endoftext|>
<commit_before>#include <array> using box = std::array<int, 4>; auto prelude = x3::lit('[') ; auto box = x3::lit('[') > x3::int_ > ',' x3::int_ > ',' x3::int_ > ',' x3::int_ > ']'; auto innerboxlist = *(box > ',') > box; auto fullboxlist = x3::lit("array") > '(' > '[' > boxlist > ']' > ',' > "dtype" > '=' > "int64" > ')'; <commit_msg>A little bit more X3 stuff<commit_after>#include <array> #include <boost/spirit/home/x3.hpp> using namespace boost::spirit; using box = std::array<int, 4>; auto constexpr bracketize(auto what) { return '[' > what > ']'; } auto boxrule = bracketize(x3::int_ > ',' > x3::int_ > ',' > x3::int_ > ',' > x3::int_); auto innerboxlist = *(boxrule > ',') > boxrule; auto fullboxlist = x3::lit("array") > '(' > bracketize(innerboxlist ) > ',' > "dtype" > '=' > "int64" > ')'; auto boxes = bracketize(*(fullboxlist)); auto scorelist = x3::lit("array") > '(' > bracketize(*(x3::double_)) > ')'; auto scores = bracketize(*(scorelist)); int main() { scores.has_action; } <|endoftext|>
<commit_before>#pragma once #include <iostream> #include <sstream> #include <map> #include <set> #include <vector> #include <algorithm> #include <functional> #include <iterator> // forward for polyfill::make_ostream_joiner template <typename Stream, typename V1, typename V2> Stream& operator << (Stream& out, const std::pair<V1, V2>& aPair); #include "acmacs-base/iterator.hh" #include "acmacs-base/sfinae.hh" // ---------------------------------------------------------------------- // to work with std::copy, std::transform, operators << have to be declared in the namespace std template <typename Stream, typename V1, typename V2> inline Stream& operator << (Stream& out, const std::pair<V1, V2>& aPair) { return out << '(' << aPair.first << ", " << aPair.second << ')'; } namespace stream_internal { template <typename Stream, typename Iterator> inline Stream& write_to_stream(Stream& out, Iterator first, Iterator last, std::string prefix, std::string suffix, std::string separator) { out << prefix; std::copy(first, last, polyfill::make_ostream_joiner(out, separator)); return out << suffix; } template <typename Stream, typename Collection, typename = std::enable_if<ad_sfinae::is_std_container<Collection>::value>> inline Stream& write_to_stream(Stream& out, const Collection& aCollection, std::string prefix, std::string suffix, std::string separator) { return write_to_stream(out, std::begin(aCollection), std::end(aCollection), prefix, suffix, separator); } } // ---------------------------------------------------------------------- template <typename Stream, typename Value> inline Stream& operator << (Stream& out, const std::vector<Value>& aCollection) { return stream_internal::write_to_stream(out, aCollection, "[", "]", ", "); } // ---------------------------------------------------------------------- template <typename Stream, typename Value> inline Stream& operator << (Stream& out, const std::set<Value>& aCollection) { return stream_internal::write_to_stream(out, aCollection, "{", "}", ", "); } // ---------------------------------------------------------------------- template <typename Stream, typename Key, typename Value> inline Stream& operator << (Stream& out, const std::map<Key, Value>& aCollection) { out << '{'; std::transform(std::begin(aCollection), std::end(aCollection), polyfill::make_ostream_joiner(out, ", "), [](const auto& elt) { std::ostringstream os; os << '<' << elt.first << ">: <" << elt.second << '>'; return os.str(); }); return out << '}'; } // ---------------------------------------------------------------------- // template <typename Stream, typename Collection> class to_stream_t // { // public: // using value_type = typename Collection::value_type; // using const_iterator = typename Collection::const_iterator; // using transformer_t = typename std::function<std::string(value_type)>; // inline to_stream_t(const_iterator first, const_iterator last, transformer_t transformer) : mFirst(first), mLast(last), mTransformer(transformer) {} // inline friend Stream& operator << (Stream& out, const to_stream_t<Stream, Collection>& converter) // { // if ((converter.mLast - converter.mFirst) > 1) // std::transform(converter.mFirst, converter.mLast, std::ostream_iterator<std::string>(out, " "), converter.mTransformer); // else // out << converter.mTransformer(*converter.mFirst); // return out; // } // private: // const_iterator mFirst, mLast; // transformer_t mTransformer; // }; // class to_stream // template <typename Stream, typename Collection> inline auto to_stream(const Collection& c, typename to_stream_t<Stream, Collection>::transformer_t transformer) // { // return to_stream_t<Stream, Collection>(c.begin(), c.end(), transformer); // } // template <typename Stream, typename Collection> inline auto to_stream(const Collection& c) // { // return to_stream_t<Stream, Collection>(c.begin(), c.end(), std::to_string); // } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <commit_msg>bug fix<commit_after>#pragma once #include <iostream> #include <sstream> #include <map> #include <set> #include <vector> #include <algorithm> #include <functional> #include <iterator> // forward for polyfill::make_ostream_joiner template <typename Stream, typename V1, typename V2> Stream& operator << (Stream& out, const std::pair<V1, V2>& aPair); template <typename Stream, typename Value> Stream& operator << (Stream& out, const std::vector<Value>& aCollection); #include "acmacs-base/iterator.hh" #include "acmacs-base/sfinae.hh" // ---------------------------------------------------------------------- // to work with std::copy, std::transform, operators << have to be declared in the namespace std template <typename Stream, typename V1, typename V2> inline Stream& operator << (Stream& out, const std::pair<V1, V2>& aPair) { return out << '(' << aPair.first << ", " << aPair.second << ')'; } namespace stream_internal { template <typename Stream, typename Iterator> inline Stream& write_to_stream(Stream& out, Iterator first, Iterator last, std::string prefix, std::string suffix, std::string separator) { out << prefix; std::copy(first, last, polyfill::make_ostream_joiner(out, separator)); return out << suffix; } template <typename Stream, typename Collection, typename = std::enable_if<ad_sfinae::is_std_container<Collection>::value>> inline Stream& write_to_stream(Stream& out, const Collection& aCollection, std::string prefix, std::string suffix, std::string separator) { return write_to_stream(out, std::begin(aCollection), std::end(aCollection), prefix, suffix, separator); } } // ---------------------------------------------------------------------- template <typename Stream, typename Value> inline Stream& operator << (Stream& out, const std::vector<Value>& aCollection) { return stream_internal::write_to_stream(out, aCollection, "[", "]", ", "); } // ---------------------------------------------------------------------- template <typename Stream, typename Value> inline Stream& operator << (Stream& out, const std::set<Value>& aCollection) { return stream_internal::write_to_stream(out, aCollection, "{", "}", ", "); } // ---------------------------------------------------------------------- template <typename Stream, typename Key, typename Value> inline Stream& operator << (Stream& out, const std::map<Key, Value>& aCollection) { out << '{'; std::transform(std::begin(aCollection), std::end(aCollection), polyfill::make_ostream_joiner(out, ", "), [](const auto& elt) { std::ostringstream os; os << '<' << elt.first << ">: <" << elt.second << '>'; return os.str(); }); return out << '}'; } // ---------------------------------------------------------------------- // template <typename Stream, typename Collection> class to_stream_t // { // public: // using value_type = typename Collection::value_type; // using const_iterator = typename Collection::const_iterator; // using transformer_t = typename std::function<std::string(value_type)>; // inline to_stream_t(const_iterator first, const_iterator last, transformer_t transformer) : mFirst(first), mLast(last), mTransformer(transformer) {} // inline friend Stream& operator << (Stream& out, const to_stream_t<Stream, Collection>& converter) // { // if ((converter.mLast - converter.mFirst) > 1) // std::transform(converter.mFirst, converter.mLast, std::ostream_iterator<std::string>(out, " "), converter.mTransformer); // else // out << converter.mTransformer(*converter.mFirst); // return out; // } // private: // const_iterator mFirst, mLast; // transformer_t mTransformer; // }; // class to_stream // template <typename Stream, typename Collection> inline auto to_stream(const Collection& c, typename to_stream_t<Stream, Collection>::transformer_t transformer) // { // return to_stream_t<Stream, Collection>(c.begin(), c.end(), transformer); // } // template <typename Stream, typename Collection> inline auto to_stream(const Collection& c) // { // return to_stream_t<Stream, Collection>(c.begin(), c.end(), std::to_string); // } // ---------------------------------------------------------------------- /// Local Variables: /// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer)) /// End: <|endoftext|>
<commit_before>#ifndef __CCCALLCC_HPP__ #define __CCCALLCC_HPP__ #include <functional> #include <memory> #include <unistd.h> #ifdef __GNUC__ #define NORETURN __attribute__((noreturn)) #else #define NORETURN #endif template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) NORETURN { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) NORETURN { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; pid_t pid = fork(); if (pid) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < ssize_t(sizeof(T))) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> static inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCCALLCC_HPP__) <commit_msg>simplify<commit_after>#ifndef __CCCALLCC_HPP__ #define __CCCALLCC_HPP__ #include <functional> #include <memory> #include <unistd.h> #ifdef __GNUC__ #define NORETURN __attribute__((noreturn)) #else #define NORETURN #endif template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) NORETURN { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) NORETURN { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; if (fork()) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < ssize_t(sizeof(T))) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> static inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCCALLCC_HPP__) <|endoftext|>
<commit_before>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "vertex_index.h" #include "vector_vector.h" #include "fm_utils.h" #include "fg_utils.h" #include "crs_header.h" #include "local_vec_store.h" using namespace fm; void read_data(char *data, size_t size, size_t num, off_t off, FILE *stream) { int iret = fseek(stream, off, SEEK_SET); assert(iret == 0); size_t ret = fread(data, size, num, stream); assert(ret == num); } class adj2crs_apply_operate: public arr_apply_operate { public: adj2crs_apply_operate(): arr_apply_operate(0) { } virtual void run(const local_vec_store &in, local_vec_store &out) const; virtual const scalar_type &get_input_type() const { return get_scalar_type<char>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<crs_idx_t>(); } }; void adj2crs_apply_operate::run(const local_vec_store &in, local_vec_store &out) const { const fg::ext_mem_undirected_vertex *v = (const fg::ext_mem_undirected_vertex *) in.get_raw_arr(); size_t num_edges = v->get_num_edges(); out.resize(num_edges); for (size_t i = 0; i < num_edges; i++) out.set<crs_idx_t>(i, v->get_neighbor(i)); } void export_crs(vector_vector::ptr adjs, const std::string &output_file) { vector_vector::ptr col_idxs = vector_vector::cast( adjs->apply(adj2crs_apply_operate())); vector::ptr col_vec = col_idxs->cat(); std::vector<crs_idx_t> offs(adjs->get_num_vecs() + 1); for (size_t i = 0; i < adjs->get_num_vecs(); i++) { offs[i + 1] = offs[i] + col_idxs->get_length(i); } FILE *f = fopen(output_file.c_str(), "w"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", output_file.c_str(), strerror(errno)); exit(1); } // This is an adjacency matrix of a graph, so it has the same number of // rows and columns. crs_header header(adjs->get_num_vecs(), adjs->get_num_vecs(), col_vec->get_length()); size_t ret = fwrite(&header, sizeof(header), 1, f); if (ret == 0) { fprintf(stderr, "can't write header: %s\n", strerror(errno)); exit(1); } ret = fwrite(offs.data(), offs.size() * sizeof(offs[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't write the row pointers: %s\n", strerror(errno)); exit(1); } ret = fwrite(dynamic_cast<const detail::mem_vec_store &>(col_vec->get_data()).get_raw_arr(), col_vec->get_length() * col_vec->get_entry_size(), 1, f); if (ret == 0) { fprintf(stderr, "can't write col idx: %s\n", strerror(errno)); exit(1); } fclose(f); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "el2crs graph_file index_file crs_file\n"); return -1; } std::string graph_file = std::string(argv[1]); std::string index_file = std::string(argv[2]); std::string crs_file = std::string(argv[3]); fg::vertex_index::ptr vindex = fg::vertex_index::load(index_file); FILE *f = fopen(graph_file.c_str(), "r"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", graph_file.c_str(), strerror(errno)); return -1; } size_t out_size = get_out_size(vindex); off_t out_off = get_out_off(vindex); detail::raw_data_array out_data(out_size); read_data(out_data.get_raw(), out_size, 1, out_off, f); std::vector<off_t> out_offs(vindex->get_num_vertices() + 1); init_out_offs(vindex, out_offs); vector_vector::ptr out_adjs = vector_vector::create( out_data, out_offs, get_scalar_type<char>()); export_crs(out_adjs, crs_file); out_adjs = NULL; if (vindex->get_graph_header().is_directed_graph()) { std::string t_crs_file = std::string("t_") + crs_file; size_t in_size = get_in_size(vindex); off_t in_off = get_in_off(vindex); detail::raw_data_array in_data(in_size); read_data(in_data.get_raw(), in_size, 1, in_off, f); std::vector<off_t> in_offs(vindex->get_num_vertices() + 1); init_in_offs(vindex, in_offs); vector_vector::ptr in_adjs = vector_vector::create( in_data, in_offs, get_scalar_type<char>()); export_crs(in_adjs, t_crs_file); } fclose(f); } <commit_msg>[Matrix]: fix a bug in al2crs.<commit_after>/* * Copyright 2014 Open Connectome Project (http://openconnecto.me) * Written by Da Zheng (zhengda1936@gmail.com) * * This file is part of FlashMatrix. * * 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 "vertex_index.h" #include "vector_vector.h" #include "fm_utils.h" #include "fg_utils.h" #include "crs_header.h" #include "local_vec_store.h" using namespace fm; void read_data(char *data, size_t size, size_t num, off_t off, FILE *stream) { int iret = fseek(stream, off, SEEK_SET); assert(iret == 0); size_t ret = fread(data, size, num, stream); assert(ret == num); } class adj2crs_apply_operate: public arr_apply_operate { public: adj2crs_apply_operate(): arr_apply_operate(0) { } virtual void run(const local_vec_store &in, local_vec_store &out) const; virtual const scalar_type &get_input_type() const { return get_scalar_type<char>(); } virtual const scalar_type &get_output_type() const { return get_scalar_type<crs_idx_t>(); } }; void adj2crs_apply_operate::run(const local_vec_store &in, local_vec_store &out) const { const fg::ext_mem_undirected_vertex *v = (const fg::ext_mem_undirected_vertex *) in.get_raw_arr(); size_t num_edges = v->get_num_edges(); out.resize(num_edges); for (size_t i = 0; i < num_edges; i++) out.set<crs_idx_t>(i, v->get_neighbor(i)); } void export_crs(vector_vector::ptr adjs, const std::string &output_file) { vector_vector::ptr col_idxs = vector_vector::cast( adjs->apply(adj2crs_apply_operate())); vector::ptr col_vec = col_idxs->cat(); std::vector<crs_idx_t> offs(adjs->get_num_vecs() + 1); for (size_t i = 0; i < adjs->get_num_vecs(); i++) { offs[i + 1] = offs[i] + col_idxs->get_length(i); } FILE *f = fopen(output_file.c_str(), "w"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", output_file.c_str(), strerror(errno)); exit(1); } // This is an adjacency matrix of a graph, so it has the same number of // rows and columns. crs_header header(adjs->get_num_vecs(), adjs->get_num_vecs(), col_vec->get_length()); size_t ret = fwrite(&header, sizeof(header), 1, f); if (ret == 0) { fprintf(stderr, "can't write header: %s\n", strerror(errno)); exit(1); } ret = fwrite(offs.data(), offs.size() * sizeof(offs[0]), 1, f); if (ret == 0) { fprintf(stderr, "can't write the row pointers: %s\n", strerror(errno)); exit(1); } ret = fwrite(dynamic_cast<const detail::mem_vec_store &>(col_vec->get_data()).get_raw_arr(), col_vec->get_length() * col_vec->get_entry_size(), 1, f); if (ret == 0) { fprintf(stderr, "can't write col idx: %s\n", strerror(errno)); exit(1); } fclose(f); } int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "el2crs graph_file index_file crs_file\n"); return -1; } std::string graph_file = std::string(argv[1]); std::string index_file = std::string(argv[2]); std::string crs_file = std::string(argv[3]); fg::vertex_index::ptr vindex = fg::vertex_index::load(index_file); FILE *f = fopen(graph_file.c_str(), "r"); if (f == NULL) { fprintf(stderr, "can't open %s: %s\n", graph_file.c_str(), strerror(errno)); return -1; } size_t out_size = get_out_size(vindex); off_t out_off = get_out_off(vindex); detail::raw_data_array out_data(out_size); read_data(out_data.get_raw(), out_size, 1, out_off, f); std::vector<off_t> out_offs(vindex->get_num_vertices() + 1); init_out_offs(vindex, out_offs); for (size_t i = 0; i < out_offs.size(); i++) out_offs[i] -= out_off; vector_vector::ptr out_adjs = vector_vector::create( out_data, out_offs, get_scalar_type<char>()); export_crs(out_adjs, crs_file); out_adjs = NULL; if (vindex->get_graph_header().is_directed_graph()) { std::string t_crs_file = std::string("t_") + crs_file; size_t in_size = get_in_size(vindex); off_t in_off = get_in_off(vindex); detail::raw_data_array in_data(in_size); read_data(in_data.get_raw(), in_size, 1, in_off, f); std::vector<off_t> in_offs(vindex->get_num_vertices() + 1); init_in_offs(vindex, in_offs); for (size_t i = 0; i < in_offs.size(); i++) in_offs[i] -= in_off; vector_vector::ptr in_adjs = vector_vector::create( in_data, in_offs, get_scalar_type<char>()); export_crs(in_adjs, t_crs_file); } fclose(f); } <|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-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "Animation/OgreBone.h" #include "OgreNode.h" #include "OgreLogManager.h" #include "Math/Array/OgreBoneMemoryManager.h" #include "Math/Array/OgreKfTransform.h" #include "Math/Array/OgreBooleanMask.h" #ifndef NDEBUG #define CACHED_TRANSFORM_OUT_OF_DATE() this->setCachedTransformOutOfDate() #else #define CACHED_TRANSFORM_OUT_OF_DATE() ((void)0) #endif namespace Ogre { //----------------------------------------------------------------------- Bone::Bone() : IdObject( 0 ), mReverseBind( 0 ), mTransform( BoneTransform() ), #ifndef NDEBUG mCachedTransformOutOfDate( true ), mDebugParentNode( 0 ), mInitialized( false ), #endif mDepthLevel( 0 ), mParent( 0 ), mName( "@Dummy Bone" ), mBoneMemoryManager( 0 ), mGlobalIndex( -1 ), mParentIndex( -1 ) { } //----------------------------------------------------------------------- Bone::~Bone() { assert( !mInitialized && "Must call _deinitialize() before destructor!" ); } //----------------------------------------------------------------------- void Bone::_initialize( IdType id, BoneMemoryManager *boneMemoryManager, Bone *parent, ArrayMatrixAf4x3 const * RESTRICT_ALIAS reverseBind ) { assert( !mInitialized ); #ifndef NDEBUG mInitialized = true; #endif this->_setId( id ); mReverseBind = reverseBind; mParent = parent; mBoneMemoryManager = boneMemoryManager; if( mParent ) mDepthLevel = mParent->mDepthLevel + 1; //Will initialize mTransform mBoneMemoryManager->nodeCreated( mTransform, mDepthLevel ); mTransform.mOwner[mTransform.mIndex] = this; if( mParent ) { const BoneTransform parentTransform = mParent->mTransform; mTransform.mParentTransform[mTransform.mIndex] = &parentTransform.mDerivedTransform[parentTransform.mIndex]; mParent->mChildren.push_back( this ); this->mParentIndex = mParent->mChildren.size() - 1; } } //----------------------------------------------------------------------- void Bone::_deinitialize(void) { removeAllChildren(); if( mParent ) mParent->removeChild( this ); if( mBoneMemoryManager ) mBoneMemoryManager->nodeDestroyed( mTransform, mDepthLevel ); mReverseBind = 0; mBoneMemoryManager = 0; #ifndef NDEBUG mInitialized = false; #endif } //----------------------------------------------------------------------- void Bone::unsetParent(void) { if( mParent ) { mTransform.mParentTransform[mTransform.mIndex] = &SimpleMatrixAf4x3::IDENTITY; mParent = 0;//Needs to be set now, if nodeDetached triggers a cleanup, //_memoryRebased will be called on us //BoneMemoryManager will set mTransform.mParentTransform to a dummy //transform (as well as transfering the memory) mBoneMemoryManager->nodeDettached( mTransform, mDepthLevel ); if( mDepthLevel != 0 ) { mDepthLevel = 0; //Propagate the change to our children BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->parentDepthLevelChanged(); ++itor; } } } } //----------------------------------------------------------------------- void Bone::parentDepthLevelChanged(void) { mBoneMemoryManager->nodeMoved( mTransform, mDepthLevel, mParent->mDepthLevel + 1 ); mDepthLevel = mParent->mDepthLevel + 1; //Keep propagating changes to our children BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->parentDepthLevelChanged(); ++itor; } } //----------------------------------------------------------------------- void Bone::setCachedTransformOutOfDate(void) const { #ifndef NDEBUG mCachedTransformOutOfDate = true; BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->setCachedTransformOutOfDate(); ++itor; } #else OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Do not call setCachedTransformOutOfDate in Release builds.\n" "Use CACHED_TRANSFORM_OUT_OF_DATE macro instead!", "Bone::setCachedTransformOutOfDate" ); #endif } //----------------------------------------------------------------------- void Bone::resetParentTransformPtr(void) { if( mParent ) { const BoneTransform parentTransform = mParent->mTransform; mTransform.mParentTransform[mTransform.mIndex] = &parentTransform.mDerivedTransform[parentTransform.mIndex]; } _memoryRebased(); } //----------------------------------------------------------------------- void Bone::_memoryRebased(void) { BoneVec::iterator itor = mChildren.begin(); BoneVec::iterator end = mChildren.end(); while( itor != end ) { (*itor)->resetParentTransformPtr(); ++itor; } } //----------------------------------------------------------------------- void Bone::_setNodeParent( Node *nodeParent ) { if( mParent ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Only Root bones call this function.", "Bone::_addNodeParent" ); } #ifndef NDEBUG mDebugParentNode = nodeParent; #endif if( nodeParent ) { //This "Hack" just works. Don't ask. And it's fast! //(we're responsible for ensuring the memory layout matches) Transform parentTransf = nodeParent->_getTransform(); mTransform.mParentTransform[mTransform.mIndex] = reinterpret_cast<SimpleMatrixAf4x3*>( &parentTransf.mDerivedTransform[parentTransf.mIndex] ); } else { mTransform.mParentTransform[mTransform.mIndex] = &SimpleMatrixAf4x3::IDENTITY; } } //----------------------------------------------------------------------- void Bone::setInheritOrientation(bool inherit) { mTransform.mInheritOrientation[mTransform.mIndex] = inherit; CACHED_TRANSFORM_OUT_OF_DATE(); } //----------------------------------------------------------------------- bool Bone::getInheritOrientation(void) const { return mTransform.mInheritOrientation[mTransform.mIndex]; } //----------------------------------------------------------------------- void Bone::setInheritScale(bool inherit) { mTransform.mInheritScale[mTransform.mIndex] = inherit; CACHED_TRANSFORM_OUT_OF_DATE(); } //----------------------------------------------------------------------- bool Bone::getInheritScale(void) const { return mTransform.mInheritScale[mTransform.mIndex]; } //----------------------------------------------------------------------- const SimpleMatrixAf4x3& Bone::_getFullTransformUpdated(void) { _updateFromParent(); return mTransform.mDerivedTransform[mTransform.mIndex]; } //----------------------------------------------------------------------- void Bone::_updateFromParent(void) { if( mParent ) mParent->_updateFromParent(); updateFromParentImpl(); } //----------------------------------------------------------------------- void Bone::updateFromParentImpl(void) { //Retrieve from parents. Unfortunately we need to do SoA -> AoS -> SoA conversion ArrayMatrixAf4x3 parentMat; parentMat.loadFromAoS( mTransform.mParentTransform ); //ArrayMatrixAf4x3::retain is quite lengthy in instruction count, and the //general case is to inherit both attributes. This branch is justified. if( BooleanMask4::allBitsSet( mTransform.mInheritOrientation, mTransform.mInheritScale ) ) { ArrayMaskR inheritOrientation = BooleanMask4::getMask( mTransform.mInheritOrientation ); ArrayMaskR inheritScale = BooleanMask4::getMask( mTransform.mInheritScale ); parentMat.retain( inheritOrientation, inheritScale ); } //BIG TODO: When in local space, reverse bind can be applied before making the transforms. ArrayMatrixAf4x3 mat; mat.makeTransform( *mTransform.mPosition, *mTransform.mScale, *mTransform.mOrientation ); mat = ((*reverseBind) * mat) * parentMat; /* Calculating the bone matrices ----------------------------- Now that we have the derived scaling factors, orientations & positions matrices, we have to compute the Matrix4x3 to apply to the vertices of a mesh. Because any modification of a vertex has to be relative to the bone, we must first reverse transform by the Bone's original derived position/orientation/scale, then transform by the new derived position/orientation/scale. */ mat.storeToAoS( mTransform.mDerivedTransform ); #ifndef NDEBUG for( size_t j=0; j<ARRAY_PACKED_REALS; ++j ) { if( mTransform.mOwner[j] ) mTransform.mOwner[j]->mCachedTransformOutOfDate = false; } #endif } //----------------------------------------------------------------------- void Bone::updateAllTransforms( const size_t numNodes, BoneTransform t, ArrayMatrixAf4x3 const * RESTRICT_ALIAS _reverseBind, size_t numBinds ) { size_t currentBind = 0; numBinds = (numBinds + ARRAY_PACKED_REALS - 1) / ARRAY_PACKED_REALS; ArrayMatrixAf4x3 derivedTransform; for( size_t i=0; i<numNodes; i += ARRAY_PACKED_REALS ) { //Retrieve from parents. Unfortunately we need to do SoA -> AoS -> SoA conversion ArrayMatrixAf4x3 parentMat; parentMat.loadFromAoS( t.mParentTransform ); //ArrayMatrixAf4x3::retain is quite lengthy in instruction count, and the //general case is to inherit both attributes. This branch is justified. if( !BooleanMask4::allBitsSet( t.mInheritOrientation, t.mInheritScale ) ) { ArrayMaskR inheritOrientation = BooleanMask4::getMask( t.mInheritOrientation ); ArrayMaskR inheritScale = BooleanMask4::getMask( t.mInheritScale ); parentMat.retain( inheritOrientation, inheritScale ); } const ArrayMatrixAf4x3 * RESTRICT_ALIAS reverseBind = _reverseBind + currentBind; derivedTransform.makeTransform( *t.mPosition, *t.mScale, *t.mOrientation ); derivedTransform = ((*reverseBind) * derivedTransform) * parentMat; /* Calculating the bone matrices ----------------------------- Now that we have the derived scaling factors, orientations & positions matrices, we have to compute the Matrix4x3 to apply to the vertices of a mesh. Because any modification of a vertex has to be relative to the bone, we must first reverse transform by the Bone's original derived position/orientation/scale, then transform by the new derived position/orientation/scale. */ derivedTransform.storeToAoS( t.mDerivedTransform ); #ifndef NDEBUG for( size_t j=0; j<ARRAY_PACKED_REALS; ++j ) { if( t.mOwner[j] ) t.mOwner[j]->mCachedTransformOutOfDate = false; } #endif t.advancePack(); currentBind = ( currentBind + 1 ) % numBinds; } } //----------------------------------------------------------------------- void Bone::removeChild( Bone* child ) { assert( child->getParent() == this && "Node says it's not our child" ); assert( child->mParentIndex < mChildren.size() && "mParentIndex was out of date!!!" ); if( child->mParentIndex < mChildren.size() ) { BoneVec::iterator itor = mChildren.begin() + child->mParentIndex; assert( child == *itor && "mParentIndex was out of date!!!" ); if( child == *itor ) { itor = efficientVectorRemove( mChildren, itor ); child->unsetParent(); child->mParentIndex = -1; //The node that was at the end got swapped and has now a different index if( itor != mChildren.end() ) (*itor)->mParentIndex = itor - mChildren.begin(); } } } //----------------------------------------------------------------------- void Bone::removeAllChildren(void) { BoneVec::iterator itor = mChildren.begin(); BoneVec::iterator end = mChildren.end(); while( itor != end ) { (*itor)->unsetParent(); (*itor)->mParentIndex = -1; ++itor; } mChildren.clear(); } } #undef CACHED_TRANSFORM_OUT_OF_DATE <commit_msg>Fixed silly compile error<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-2013 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "Animation/OgreBone.h" #include "OgreNode.h" #include "OgreLogManager.h" #include "Math/Array/OgreBoneMemoryManager.h" #include "Math/Array/OgreKfTransform.h" #include "Math/Array/OgreBooleanMask.h" #ifndef NDEBUG #define CACHED_TRANSFORM_OUT_OF_DATE() this->setCachedTransformOutOfDate() #else #define CACHED_TRANSFORM_OUT_OF_DATE() ((void)0) #endif namespace Ogre { //----------------------------------------------------------------------- Bone::Bone() : IdObject( 0 ), mReverseBind( 0 ), mTransform( BoneTransform() ), #ifndef NDEBUG mCachedTransformOutOfDate( true ), mDebugParentNode( 0 ), mInitialized( false ), #endif mDepthLevel( 0 ), mParent( 0 ), mName( "@Dummy Bone" ), mBoneMemoryManager( 0 ), mGlobalIndex( -1 ), mParentIndex( -1 ) { } //----------------------------------------------------------------------- Bone::~Bone() { assert( !mInitialized && "Must call _deinitialize() before destructor!" ); } //----------------------------------------------------------------------- void Bone::_initialize( IdType id, BoneMemoryManager *boneMemoryManager, Bone *parent, ArrayMatrixAf4x3 const * RESTRICT_ALIAS reverseBind ) { assert( !mInitialized ); #ifndef NDEBUG mInitialized = true; #endif this->_setId( id ); mReverseBind = reverseBind; mParent = parent; mBoneMemoryManager = boneMemoryManager; if( mParent ) mDepthLevel = mParent->mDepthLevel + 1; //Will initialize mTransform mBoneMemoryManager->nodeCreated( mTransform, mDepthLevel ); mTransform.mOwner[mTransform.mIndex] = this; if( mParent ) { const BoneTransform parentTransform = mParent->mTransform; mTransform.mParentTransform[mTransform.mIndex] = &parentTransform.mDerivedTransform[parentTransform.mIndex]; mParent->mChildren.push_back( this ); this->mParentIndex = mParent->mChildren.size() - 1; } } //----------------------------------------------------------------------- void Bone::_deinitialize(void) { removeAllChildren(); if( mParent ) mParent->removeChild( this ); if( mBoneMemoryManager ) mBoneMemoryManager->nodeDestroyed( mTransform, mDepthLevel ); mReverseBind = 0; mBoneMemoryManager = 0; #ifndef NDEBUG mInitialized = false; #endif } //----------------------------------------------------------------------- void Bone::unsetParent(void) { if( mParent ) { mTransform.mParentTransform[mTransform.mIndex] = &SimpleMatrixAf4x3::IDENTITY; mParent = 0;//Needs to be set now, if nodeDetached triggers a cleanup, //_memoryRebased will be called on us //BoneMemoryManager will set mTransform.mParentTransform to a dummy //transform (as well as transfering the memory) mBoneMemoryManager->nodeDettached( mTransform, mDepthLevel ); if( mDepthLevel != 0 ) { mDepthLevel = 0; //Propagate the change to our children BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->parentDepthLevelChanged(); ++itor; } } } } //----------------------------------------------------------------------- void Bone::parentDepthLevelChanged(void) { mBoneMemoryManager->nodeMoved( mTransform, mDepthLevel, mParent->mDepthLevel + 1 ); mDepthLevel = mParent->mDepthLevel + 1; //Keep propagating changes to our children BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->parentDepthLevelChanged(); ++itor; } } //----------------------------------------------------------------------- void Bone::setCachedTransformOutOfDate(void) const { #ifndef NDEBUG mCachedTransformOutOfDate = true; BoneVec::const_iterator itor = mChildren.begin(); BoneVec::const_iterator end = mChildren.end(); while( itor != end ) { (*itor)->setCachedTransformOutOfDate(); ++itor; } #else OGRE_EXCEPT( Exception::ERR_INTERNAL_ERROR, "Do not call setCachedTransformOutOfDate in Release builds.\n" "Use CACHED_TRANSFORM_OUT_OF_DATE macro instead!", "Bone::setCachedTransformOutOfDate" ); #endif } //----------------------------------------------------------------------- void Bone::resetParentTransformPtr(void) { if( mParent ) { const BoneTransform parentTransform = mParent->mTransform; mTransform.mParentTransform[mTransform.mIndex] = &parentTransform.mDerivedTransform[parentTransform.mIndex]; } _memoryRebased(); } //----------------------------------------------------------------------- void Bone::_memoryRebased(void) { BoneVec::iterator itor = mChildren.begin(); BoneVec::iterator end = mChildren.end(); while( itor != end ) { (*itor)->resetParentTransformPtr(); ++itor; } } //----------------------------------------------------------------------- void Bone::_setNodeParent( Node *nodeParent ) { if( mParent ) { OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Only Root bones call this function.", "Bone::_addNodeParent" ); } #ifndef NDEBUG mDebugParentNode = nodeParent; #endif if( nodeParent ) { //This "Hack" just works. Don't ask. And it's fast! //(we're responsible for ensuring the memory layout matches) Transform parentTransf = nodeParent->_getTransform(); mTransform.mParentTransform[mTransform.mIndex] = reinterpret_cast<SimpleMatrixAf4x3*>( &parentTransf.mDerivedTransform[parentTransf.mIndex] ); } else { mTransform.mParentTransform[mTransform.mIndex] = &SimpleMatrixAf4x3::IDENTITY; } } //----------------------------------------------------------------------- void Bone::setInheritOrientation(bool inherit) { mTransform.mInheritOrientation[mTransform.mIndex] = inherit; CACHED_TRANSFORM_OUT_OF_DATE(); } //----------------------------------------------------------------------- bool Bone::getInheritOrientation(void) const { return mTransform.mInheritOrientation[mTransform.mIndex]; } //----------------------------------------------------------------------- void Bone::setInheritScale(bool inherit) { mTransform.mInheritScale[mTransform.mIndex] = inherit; CACHED_TRANSFORM_OUT_OF_DATE(); } //----------------------------------------------------------------------- bool Bone::getInheritScale(void) const { return mTransform.mInheritScale[mTransform.mIndex]; } //----------------------------------------------------------------------- const SimpleMatrixAf4x3& Bone::_getFullTransformUpdated(void) { _updateFromParent(); return mTransform.mDerivedTransform[mTransform.mIndex]; } //----------------------------------------------------------------------- void Bone::_updateFromParent(void) { if( mParent ) mParent->_updateFromParent(); updateFromParentImpl(); } //----------------------------------------------------------------------- void Bone::updateFromParentImpl(void) { //Retrieve from parents. Unfortunately we need to do SoA -> AoS -> SoA conversion ArrayMatrixAf4x3 parentMat; parentMat.loadFromAoS( mTransform.mParentTransform ); //ArrayMatrixAf4x3::retain is quite lengthy in instruction count, and the //general case is to inherit both attributes. This branch is justified. if( BooleanMask4::allBitsSet( mTransform.mInheritOrientation, mTransform.mInheritScale ) ) { ArrayMaskR inheritOrientation = BooleanMask4::getMask( mTransform.mInheritOrientation ); ArrayMaskR inheritScale = BooleanMask4::getMask( mTransform.mInheritScale ); parentMat.retain( inheritOrientation, inheritScale ); } //BIG TODO: When in local space, reverse bind can be applied before making the transforms. ArrayMatrixAf4x3 mat; mat.makeTransform( *mTransform.mPosition, *mTransform.mScale, *mTransform.mOrientation ); mat = ((*mReverseBind) * mat) * parentMat; /* Calculating the bone matrices ----------------------------- Now that we have the derived scaling factors, orientations & positions matrices, we have to compute the Matrix4x3 to apply to the vertices of a mesh. Because any modification of a vertex has to be relative to the bone, we must first reverse transform by the Bone's original derived position/orientation/scale, then transform by the new derived position/orientation/scale. */ mat.storeToAoS( mTransform.mDerivedTransform ); #ifndef NDEBUG for( size_t j=0; j<ARRAY_PACKED_REALS; ++j ) { if( mTransform.mOwner[j] ) mTransform.mOwner[j]->mCachedTransformOutOfDate = false; } #endif } //----------------------------------------------------------------------- void Bone::updateAllTransforms( const size_t numNodes, BoneTransform t, ArrayMatrixAf4x3 const * RESTRICT_ALIAS _reverseBind, size_t numBinds ) { size_t currentBind = 0; numBinds = (numBinds + ARRAY_PACKED_REALS - 1) / ARRAY_PACKED_REALS; ArrayMatrixAf4x3 derivedTransform; for( size_t i=0; i<numNodes; i += ARRAY_PACKED_REALS ) { //Retrieve from parents. Unfortunately we need to do SoA -> AoS -> SoA conversion ArrayMatrixAf4x3 parentMat; parentMat.loadFromAoS( t.mParentTransform ); //ArrayMatrixAf4x3::retain is quite lengthy in instruction count, and the //general case is to inherit both attributes. This branch is justified. if( !BooleanMask4::allBitsSet( t.mInheritOrientation, t.mInheritScale ) ) { ArrayMaskR inheritOrientation = BooleanMask4::getMask( t.mInheritOrientation ); ArrayMaskR inheritScale = BooleanMask4::getMask( t.mInheritScale ); parentMat.retain( inheritOrientation, inheritScale ); } const ArrayMatrixAf4x3 * RESTRICT_ALIAS reverseBind = _reverseBind + currentBind; derivedTransform.makeTransform( *t.mPosition, *t.mScale, *t.mOrientation ); derivedTransform = ((*reverseBind) * derivedTransform) * parentMat; /* Calculating the bone matrices ----------------------------- Now that we have the derived scaling factors, orientations & positions matrices, we have to compute the Matrix4x3 to apply to the vertices of a mesh. Because any modification of a vertex has to be relative to the bone, we must first reverse transform by the Bone's original derived position/orientation/scale, then transform by the new derived position/orientation/scale. */ derivedTransform.storeToAoS( t.mDerivedTransform ); #ifndef NDEBUG for( size_t j=0; j<ARRAY_PACKED_REALS; ++j ) { if( t.mOwner[j] ) t.mOwner[j]->mCachedTransformOutOfDate = false; } #endif t.advancePack(); currentBind = ( currentBind + 1 ) % numBinds; } } //----------------------------------------------------------------------- void Bone::removeChild( Bone* child ) { assert( child->getParent() == this && "Node says it's not our child" ); assert( child->mParentIndex < mChildren.size() && "mParentIndex was out of date!!!" ); if( child->mParentIndex < mChildren.size() ) { BoneVec::iterator itor = mChildren.begin() + child->mParentIndex; assert( child == *itor && "mParentIndex was out of date!!!" ); if( child == *itor ) { itor = efficientVectorRemove( mChildren, itor ); child->unsetParent(); child->mParentIndex = -1; //The node that was at the end got swapped and has now a different index if( itor != mChildren.end() ) (*itor)->mParentIndex = itor - mChildren.begin(); } } } //----------------------------------------------------------------------- void Bone::removeAllChildren(void) { BoneVec::iterator itor = mChildren.begin(); BoneVec::iterator end = mChildren.end(); while( itor != end ) { (*itor)->unsetParent(); (*itor)->mParentIndex = -1; ++itor; } mChildren.clear(); } } #undef CACHED_TRANSFORM_OUT_OF_DATE <|endoftext|>
<commit_before>#include "Camera.h" #include <GL\freeglut.h> #include <iostream> float Camera::fov = 45.0f; float Camera::aspect = 1.0f; float hAngle = 3.14f; float vAngle = 0.0f; float speed = 3.0f; float mouseSpeed = 0.05f; glm::vec3 position = glm::vec3(4, 3, 3); glm::vec3 direction, right, up; float deltaTime = 0.0f; double cursor_x, cursor_y; bool hRotationEnabled, vRotationEnabled; glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; glm::mat4 Camera::GetProjectionMatrix() { return ProjectionMatrix; } glm::mat4 Camera::GetViewMatrix() { return ViewMatrix; } void updateMouseLocation(int x, int y) { std::cout << "x=" << x << "y=" << y << std::endl; if (hRotationEnabled) hAngle += mouseSpeed * deltaTime * float(1024 / 2 - cursor_x); if (vRotationEnabled) vAngle += mouseSpeed * deltaTime * float(768 / 2 - cursor_y); } /* * Callback for glutMouseFunc() * https://www.opengl.org/documentation/specs/glut/spec3/node50.html */ void onMouseButton(int button, int state, int x, int y) { std::cout << "button: " << button << "\tstate: " << state << std::endl; hRotationEnabled = false; vRotationEnabled = false; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { hRotationEnabled = true; vRotationEnabled = true; } } void onKeyPressed(int key, int x, int y) { if (key == GLUT_KEY_UP) position += direction * speed; if (key == GLUT_KEY_DOWN) position -= direction * speed; if (key == GLUT_KEY_RIGHT) position += right * speed; if (key == GLUT_KEY_LEFT) position -= right * speed; } //TODO switch from hardcoding in 1024/768, aspect, etc void Camera::ComputeMatrices() { static int pTime = glutGet(GLUT_ELAPSED_TIME); // called once. Wrong! TODO: Fix int cTime = glutGet(GLUT_ELAPSED_TIME); deltaTime = float(cTime - pTime)/1000.0f; // time elapsed in seconds // listen for mouse input //TODO call outside of this class glutMotionFunc(updateMouseLocation); direction = glm::vec3( cos(vAngle) * sin(hAngle), sin(vAngle), cos(vAngle) * cos(hAngle)); right = glm::vec3( sin(hAngle - 3.14f/2.0f), 0, cos(hAngle - 3.14/2.0f)); up = glm::cross(right, direction); // listen for mouse events //TODO call outside of this class glutSpecialFunc(onKeyPressed); glutMouseFunc(onMouseButton); ProjectionMatrix = glm::perspective(glm::radians(fov), 4.0f / 3.0f, 0.1f, 100.0f); ViewMatrix = glm::lookAt( position, // camera position direction, // camera looks here up ); pTime = cTime; // update "previous" time } <commit_msg>Fix mouse movement<commit_after>#include "Camera.h" #include <GL\freeglut.h> #include <iostream> float Camera::fov = 45.0f; float Camera::aspect = 1.0f; float hAngle = 3.14f; float vAngle = 0.0f; float speed = 3.0f; float mouseSpeed = 0.5f; glm::vec3 position = glm::vec3(0, 0, 5); glm::vec3 direction, right, up; float deltaTime = 0.0f; double x_origin, y_origin; bool hRotationEnabled, vRotationEnabled; glm::mat4 ViewMatrix; glm::mat4 ProjectionMatrix; glm::mat4 Camera::GetProjectionMatrix() { return ProjectionMatrix; } glm::mat4 Camera::GetViewMatrix() { return ViewMatrix; } void updateMouseLocation(int x, int y) { double dx = x - x_origin; double dy = y - y_origin; std::cout << "deltaTime" << deltaTime << std::endl; if (hRotationEnabled) hAngle += mouseSpeed * deltaTime * float(dx); if (vRotationEnabled) vAngle += mouseSpeed * deltaTime * float(dy); x_origin = x; y_origin = y; } /* * Callback for glutMouseFunc() * https://www.opengl.org/documentation/specs/glut/spec3/node50.html */ void onMouseButton(int button, int state, int x, int y) { hRotationEnabled = false; vRotationEnabled = false; if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) { x_origin = x; y_origin = y; hRotationEnabled = true; vRotationEnabled = true; } else if (button == 3 && state == GLUT_DOWN) // Mouse wheel down { position += direction * speed; } else if (button == 4 && state == GLUT_DOWN) // Mouse wheel up { position -= direction * speed; } } void onKeyPressed(int key, int x, int y) { std::cout << "deltaTime" << deltaTime << std::endl; if (key == GLUT_KEY_UP) position += direction * speed; if (key == GLUT_KEY_DOWN) position -= direction * speed; if (key == GLUT_KEY_RIGHT) position += right * speed; if (key == GLUT_KEY_LEFT) position -= right * speed; } //TODO switch from hardcoding in 1024/768, aspect, etc void Camera::ComputeMatrices() { static int pTime = glutGet(GLUT_ELAPSED_TIME); // called once. Wrong! TODO: Fix int cTime = glutGet(GLUT_ELAPSED_TIME); deltaTime = float(cTime - pTime)/1000.0f; // time elapsed in seconds // listen for mouse input //TODO call outside of this class glutMotionFunc(updateMouseLocation); direction = glm::vec3( cos(vAngle) * sin(hAngle), sin(vAngle), cos(vAngle) * cos(hAngle)); right = glm::vec3( sin(hAngle - 3.14f/2.0f), 0, cos(hAngle - 3.14/2.0f)); up = cross(right, direction); // listen for mouse events //TODO call outside of this class glutSpecialFunc(onKeyPressed); glutMouseFunc(onMouseButton); ProjectionMatrix = glm::perspective(glm::radians(fov), 4.0f / 3.0f, 0.1f, 100.0f); ViewMatrix = lookAt( position, // camera position position + direction, // camera looks here up ); pTime = cTime; // update "previous" time } <|endoftext|>
<commit_before>// // sim_tools.cpp // // Program to read and process contents of a SIM file // // $Id: sim.cpp 1354 2010-11-11 16:20:09Z js10 $ // // // Author: Jennifer Liddle <js10@sanger.ac.uk, jennifer@jsquared.co.uk>, Iain Bancarz <ib5@sanger.ac.uk> // // Copyright (c) 2009 - 2013 Genome Research Ltd. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of Genome Research Ltd nor the names of the // contributors may be used to endorse or promote products derived from // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL GENOME RESEARCH LTD. 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. // // TODO Keep command line parsing in this file; move analysis logic into a separate class. Tidies up code and enables testing. #include <getopt.h> #include <iostream> #include <sstream> #include <vector> #include <map> #include <iomanip> #include <algorithm> #include "commands.h" #include "Sim.h" #include "Gtc.h" #include "QC.h" #include "Manifest.h" #include "json/json.h" using namespace std; static struct option long_options[] = { {"infile", 1, 0, 0}, {"outfile", 1, 0, 0}, {"man_file", 1, 0, 0}, {"man_dir", 1, 0, 0}, {"normalize", 0, 0, 0}, {"verbose", 0, 0, 0}, {"start", 1, 0, 0}, {"end", 1, 0, 0}, {"magnitude", 1, 0, 0}, {"xydiff", 1, 0, 0}, {0, 0, 0, 0} }; void showUsage(int argc, char *argv[]) { string command = ""; if (argc > 2) command = argv[2]; cout << endl; if (command == "create") { cout << "Usage: " << argv[0] << " create [options]" << endl << endl; cout << "Create a SIM file from a list of GTC files" << endl<< endl; cout << "Options: --infile <filename> File containing list of GTC files to process" << endl; cout << " --outfile <filename> Name of SIM file to create or '-' for STDOUT" << endl; cout << " --man_file <dirname> Directory to look for Manifest file in" << endl; cout << " --normalize Normalize the intensities (default is raw values)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "illuminus") { cout << "Usage: " << argv[0] << " illuminus [options]" << endl << endl; cout << "Create an Illuminus file from a SIM file" << endl<< endl; cout << "Options: --infile <filename> Name of SIM file to process or '-' for STDIN" << endl; cout << " --outfile <filename> Name of Illuminus file to create or '-' for STDOUT" << endl; cout << " --man_file <dirname> Directory to look for Manifest file in" << endl; cout << " --start <index> Which SNP to start processing at (default is to start at the beginning)" << endl; cout << " --end <index> Which SNP to end processing at (default is to continue until the end)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "genosnp") { cout << "Usage: " << argv[0] << " genosnp [options]" << endl << endl; cout << "Create a GenoSNP file from a SIM file" << endl<< endl; cout << "Options: --infile The name of the SIM file or '-' for STDIN" << endl; cout << " --outfile Name of GenoSNP file to create or '-' for STDOUT" << endl; cout << " --start <index> Which sample to start processing at (default is to start at the beginning)" << endl; cout << " --end <index> Which sample to end processing at (default is to continue until the end)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "view") { cout << "Usage: " << argv[0] << " view [options]" << endl << endl; cout << "Display some information from a SIM file" << endl<< endl; cout << "Options: --infile The name of the SIM file or '-' for STDIN" << endl; cout << " --verbose Display intensities as well as header information" << endl; exit(0); } if (command == "qc") { cout << "Usage: " << argv[0] << " qc [options]" << endl << endl; cout << "Compute genotyping QC metrics and write to text files" << endl<< endl; cout << "Options: --infile The name of the SIM file (cannot accept STDIN)" << endl; cout << " --magnitude Output file for sample magnitude (normalised by SNP); cannot use STDOUT" << endl; cout << " --xydiff Output file for XY intensity difference; cannot use STDOUT" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } cout << "Usage: " << argv[0] << " <command> [options]" << endl; cout << "Command: view Dump SIM file to screen" << endl; cout << " create Create a SIM file from GTC files" << endl; cout << " illuminus Produce Illuminus output" << endl; cout << " genosnp Produce GenoSNP output" << endl; cout << " qc Produce QC metrics" << endl; cout << " help Display this help. Use 'help <command>' for more help" << endl; exit(0); } int main(int argc, char *argv[]) { string infile = "-"; string outfile = "-"; string manfile = ""; string magnitude = ""; string xydiff = ""; bool verbose = false; bool normalize = false; int start_pos = 0; int end_pos = -1; int option_index = -1; int c; // placeholder -- create Commander object Commander *commander = new Commander(); // Get command if (argc < 2) showUsage(argc,argv); string command = argv[1]; if (command == "help") showUsage(argc, argv); // get options while ( (c=getopt_long(argc,argv,"h?",long_options,&option_index)) != -1) { if (c == '?') showUsage(argc,argv); // unknown option if (option_index > -1) { string option = long_options[option_index].name; if (option == "infile") infile = optarg; if (option == "outfile") outfile = optarg; if (option == "verbose") verbose = true; if (option == "man_file") manfile = optarg; if (option == "man_dir") manfile = optarg; if (option == "normalize") normalize = true; if (option == "start") start_pos = atoi(optarg); if (option == "end") end_pos = atoi(optarg); if (option == "magnitude") magnitude = optarg; if (option == "xydiff") xydiff = optarg; } } // Allow stdin and stdout as synonyms for "-" if (infile == "stdin") infile = "-"; if (outfile == "stdout") outfile = "-"; // Process the command try { if (command == "view") { commander->commandView(infile, verbose); } else if (command == "create") { commander->commandCreate(infile, outfile, normalize, manfile, verbose); } else if (command == "illuminus") { commander->commandIlluminus(infile, outfile, manfile, start_pos, end_pos, verbose); } else if (command == "genosnp") { commander->commandGenoSNP(infile, outfile, manfile, start_pos, end_pos, verbose); } else if (command == "qc") { commander->commandQC(infile, magnitude, xydiff, verbose); } else { cerr << "Unknown command '" << command << "'" << endl; showUsage(argc,argv); } } catch (const char *error_msg) { cerr << error_msg << endl << endl; exit(1); } catch (string error_msg) { cerr << error_msg << endl << endl; exit(1); } delete commander; return 0; } <commit_msg>Remove unnecessary import statements, move Commander initialization<commit_after>// // sim_tools.cpp // // Program to read and process contents of a SIM file // // $Id: sim.cpp 1354 2010-11-11 16:20:09Z js10 $ // // // Author: Jennifer Liddle <js10@sanger.ac.uk, jennifer@jsquared.co.uk>, Iain Bancarz <ib5@sanger.ac.uk> // // Copyright (c) 2009 - 2013 Genome Research Ltd. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of Genome Research Ltd nor the names of the // contributors may be used to endorse or promote products derived from // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR // IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. // IN NO EVENT SHALL GENOME RESEARCH LTD. 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. // // TODO Keep command line parsing in this file; move analysis logic into a separate class. Tidies up code and enables testing. #include <getopt.h> #include <iostream> #include "commands.h" using namespace std; static struct option long_options[] = { {"infile", 1, 0, 0}, {"outfile", 1, 0, 0}, {"man_file", 1, 0, 0}, {"man_dir", 1, 0, 0}, {"normalize", 0, 0, 0}, {"verbose", 0, 0, 0}, {"start", 1, 0, 0}, {"end", 1, 0, 0}, {"magnitude", 1, 0, 0}, {"xydiff", 1, 0, 0}, {0, 0, 0, 0} }; void showUsage(int argc, char *argv[]) { string command = ""; if (argc > 2) command = argv[2]; cout << endl; if (command == "create") { cout << "Usage: " << argv[0] << " create [options]" << endl << endl; cout << "Create a SIM file from a list of GTC files" << endl<< endl; cout << "Options: --infile <filename> File containing list of GTC files to process" << endl; cout << " --outfile <filename> Name of SIM file to create or '-' for STDOUT" << endl; cout << " --man_file <dirname> Directory to look for Manifest file in" << endl; cout << " --normalize Normalize the intensities (default is raw values)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "illuminus") { cout << "Usage: " << argv[0] << " illuminus [options]" << endl << endl; cout << "Create an Illuminus file from a SIM file" << endl<< endl; cout << "Options: --infile <filename> Name of SIM file to process or '-' for STDIN" << endl; cout << " --outfile <filename> Name of Illuminus file to create or '-' for STDOUT" << endl; cout << " --man_file <dirname> Directory to look for Manifest file in" << endl; cout << " --start <index> Which SNP to start processing at (default is to start at the beginning)" << endl; cout << " --end <index> Which SNP to end processing at (default is to continue until the end)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "genosnp") { cout << "Usage: " << argv[0] << " genosnp [options]" << endl << endl; cout << "Create a GenoSNP file from a SIM file" << endl<< endl; cout << "Options: --infile The name of the SIM file or '-' for STDIN" << endl; cout << " --outfile Name of GenoSNP file to create or '-' for STDOUT" << endl; cout << " --start <index> Which sample to start processing at (default is to start at the beginning)" << endl; cout << " --end <index> Which sample to end processing at (default is to continue until the end)" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } if (command == "view") { cout << "Usage: " << argv[0] << " view [options]" << endl << endl; cout << "Display some information from a SIM file" << endl<< endl; cout << "Options: --infile The name of the SIM file or '-' for STDIN" << endl; cout << " --verbose Display intensities as well as header information" << endl; exit(0); } if (command == "qc") { cout << "Usage: " << argv[0] << " qc [options]" << endl << endl; cout << "Compute genotyping QC metrics and write to text files" << endl<< endl; cout << "Options: --infile The name of the SIM file (cannot accept STDIN)" << endl; cout << " --magnitude Output file for sample magnitude (normalised by SNP); cannot use STDOUT" << endl; cout << " --xydiff Output file for XY intensity difference; cannot use STDOUT" << endl; cout << " --verbose Show progress messages to STDERR" << endl; exit(0); } cout << "Usage: " << argv[0] << " <command> [options]" << endl; cout << "Command: view Dump SIM file to screen" << endl; cout << " create Create a SIM file from GTC files" << endl; cout << " illuminus Produce Illuminus output" << endl; cout << " genosnp Produce GenoSNP output" << endl; cout << " qc Produce QC metrics" << endl; cout << " help Display this help. Use 'help <command>' for more help" << endl; exit(0); } int main(int argc, char *argv[]) { string infile = "-"; string outfile = "-"; string manfile = ""; string magnitude = ""; string xydiff = ""; bool verbose = false; bool normalize = false; int start_pos = 0; int end_pos = -1; int option_index = -1; int c; // Get command if (argc < 2) showUsage(argc,argv); string command = argv[1]; if (command == "help") showUsage(argc, argv); // get options while ( (c=getopt_long(argc,argv,"h?",long_options,&option_index)) != -1) { if (c == '?') showUsage(argc,argv); // unknown option if (option_index > -1) { string option = long_options[option_index].name; if (option == "infile") infile = optarg; if (option == "outfile") outfile = optarg; if (option == "verbose") verbose = true; if (option == "man_file") manfile = optarg; if (option == "man_dir") manfile = optarg; if (option == "normalize") normalize = true; if (option == "start") start_pos = atoi(optarg); if (option == "end") end_pos = atoi(optarg); if (option == "magnitude") magnitude = optarg; if (option == "xydiff") xydiff = optarg; } } // Allow stdin and stdout as synonyms for "-" if (infile == "stdin") infile = "-"; if (outfile == "stdout") outfile = "-"; Commander *commander = new Commander(); // Process the command try { if (command == "view") { commander->commandView(infile, verbose); } else if (command == "create") { commander->commandCreate(infile, outfile, normalize, manfile, verbose); } else if (command == "illuminus") { commander->commandIlluminus(infile, outfile, manfile, start_pos, end_pos, verbose); } else if (command == "genosnp") { commander->commandGenoSNP(infile, outfile, manfile, start_pos, end_pos, verbose); } else if (command == "qc") { commander->commandQC(infile, magnitude, xydiff, verbose); } else { cerr << "Unknown command '" << command << "'" << endl; showUsage(argc,argv); } } catch (const char *error_msg) { cerr << error_msg << endl << endl; exit(1); } catch (string error_msg) { cerr << error_msg << endl << endl; exit(1); } delete commander; return 0; } <|endoftext|>
<commit_before>//============================================================================= // ■ VMtest.cxx //----------------------------------------------------------------------------- // 虚拟机测试程序。 // 扩展名用了.cxx,意思是“×不要自动编译”。 //============================================================================= #include "ASM76.hpp" using namespace ASM76; Instruct mem_test_i[] = { {LCMM,0x4000000,0}, {DATI,0xABCD1234,1}, {DATB,'V',5}, {DATB,'M',6}, {DATB,'7',7}, {DATB,'6',8}, {SLLA,0x2000000,1}, {SLIA,0x2500000,2}, {SLBA,0x2700000,3}, {LDLA,0x2500000,51}, {LDIA,0x2500000,51}, {LDBA,0x2500000,61}, {HALT, 0, 0}, }; Program mem_test_p { .size = sizeof(mem_test_i), .instruct = mem_test_i }; Instruct basic_algebra_test_prgm[] = { {LCMM,0x100,0}, {DATI,0x1,1}, // $1 = $1 + $1 // 1, 2, 4, 8, 16, ... {ADDL,1,1}, {ADDL,1,1}, {ADDL,1,1}, {ADDL,1,1}, // Put the result else where {MVRL,1,31}, // Then divide 4 {DATI,0x4,11}, {DIVL,1,11}, {HALT, 0, 0}, }; Instruct flow_control_test_prgm[] = { {DATB,0x1,20}, {DATB,0xA,10}, {DATB,0x2,15}, {ADDL,15,15}, {ADDL,3,20}, {CMPI,3,10}, {PUSH,15,1}, {JILA, 3 * sizeof(Instruct),0}, {HALT, 0, 0}, }; const char* const asm_test = "# Comments.\n" "DATB 0x1 $20\n" "DATB 0xA $10\n" "DATB 0x2 $15\n" "[loop_start]\n" "ADDL $15 $15\n" "ADDL $3 $20\n" "CMPI $3 $10\n" "PUSH $15 1\n" "JILA [loop_start]\n" "HALT\n" "DD 0x7676 0xEFEF 0xABAB 0xCDCD 0x0000\n" "# EOF\n"; const char* const bios_test = "DATI 0x76 $0\n" "SLIA 0x100 $0\n" "INTX 0x1 0x100\n" "DATI 0xAB $0\n" "SLIA 0x100 $0\n" "INTX 0x1 0x100\n" "HALT\n" "# EOF\n"; static uint32_t test_bios_call(uint8_t* input) { printf("TEST BIOS CALL: %x\n", *((uint32_t*) input)); return 0x89ABCDEF; } Instruct speed_test_prgm[] = { {DATI,0x1,20}, {DATI,0x3000000,60}, {DATI,0x2,15}, {ADDL,3,20}, {CMPI,3,60}, {JILA, 3 * sizeof(Instruct),0}, {HALT, 0, 0}, }; const char* const tag_test = "JMPA [end]\n" "ADDI $50 $100\n" "MINI $25 $50\n" "[end]\n" "HALT\n" "# EOF\n"; #include <ratio> #include <chrono> using namespace std; int main() { printf("===== ASM 76 Test Program =====\n"); init(); #define VM_v(var) VM v({.size = sizeof(var), .instruct = var}) { printf("===== Memory =====\n"); VM v(mem_test_p); v.execute(true); v.dump_registers(); } { printf("===== Basic Algebra =====\n"); VM_v(basic_algebra_test_prgm); v.execute(true); v.dump_registers(); } { printf("===== Disassembler =====\n"); Disassembler d({sizeof(flow_control_test_prgm), flow_control_test_prgm}); char* s = d.disassemble(); puts(s); free(s); } { printf("===== Assembler =====\n"); Assembler a(asm_test); a.scan(); Program p = a.assemble(); // Test assembler DD function printf("Data DD: %04x%08x%08x\n", p.instruct[9].opcode, p.instruct[9].a, p.instruct[9].b); // Test disassembler Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); printf("===== Flow Control & Logistics =====\n"); VM v(p); v.execute(false); v.dump_registers(); free(p.instruct); } { printf("===== Assembler: Tag Test =====\n"); Assembler a(tag_test); a.scan(); Program p = a.assemble(); Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); } { printf("===== BIOS Test =====\n"); BIOS* b = new BIOS(5); b->function_table[1] = &test_bios_call; Assembler a(bios_test); a.scan(); Program p = a.assemble(); VM v(p); v.firmware = b; v.execute(true); v.dump_registers(); } { printf("===== Object Code =====\n"); ObjectCode::write_file("test.obj", mem_test_p); Program p = ObjectCode::read_file("test.obj"); Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); free(p.instruct); } { printf("===== Speed Test: 0x3000000 cycles =====\n"); VM_v(speed_test_prgm); // The type is chrono::time_point<chrono::high_resolution_clock> // and that is why people used auto. auto t1 = chrono::high_resolution_clock::now(); v.execute(false); auto t2 = chrono::high_resolution_clock::now(); chrono::duration<double, milli> delay = t2 - t1; printf("Elapsed time: %lfms\nMIPS: %lf\n", delay.count(), ((double) 0x3000000) * 3.0 / ((double) delay.count()) / 10000.0 ); } printf("===== TEST END =====\n"); return 0; } <commit_msg>Refine VMtest.cxx<commit_after>//============================================================================= // ■ VMtest.cxx //----------------------------------------------------------------------------- // 虚拟机测试程序。 // 扩展名用了.cxx,意思是“×不要自动编译”。 //============================================================================= #include <ratio> #include <chrono> using namespace std; #include "ASM76.hpp" using namespace ASM76; Instruct test_mem_i[] = { {LCMM, 0x4000000, 0}, {DATI, 0xABCD1234, 1}, {DATB, 'V', 5}, {DATB, 'M', 6}, {DATB, '7', 7}, {DATB, '6', 8}, {SLLA, 0x2000000, 1}, {SLIA, 0x2500000, 2}, {SLBA, 0x2700000, 3}, {LDLA, 0x2500000, 51}, {LDIA, 0x2500000, 51}, {LDBA, 0x2500000, 61}, {HALT, 0, 0}, }; Program test_mem_p { .size = sizeof(test_mem_i), .instruct = test_mem_i }; Instruct test_basic_algebra_i[] = { {LCMM, 0x100, 0}, {DATI, 0x1, 1}, // $1 = $1 + $1 // 1, 2, 4, 8, 16, ... {ADDL, 1, 1}, {ADDL, 1, 1}, {ADDL, 1, 1}, {ADDL, 1, 1}, // Put the result somewhere else {MVRL, 1, 31}, // Then divide it by 4 {DATI, 0x4, 11}, {DIVL, 1, 11}, {HALT, 0, 0}, }; Program test_basic_algebra_p { .size = sizeof(test_basic_algebra_i), .instruct = test_basic_algebra_i }; Instruct test_flow_control_i[] = { {DATB, 0x1, 20}, {DATB, 0xA, 10}, {DATB, 0x2, 15}, {ADDL, 15, 15}, {ADDL, 3, 20}, {CMPI, 3, 10}, {PUSH, 15, 1}, {JILA, 3 * sizeof(Instruct), 0}, {HALT, 0, 0}, }; Program test_flow_control_p { .size = sizeof(test_flow_control_i), .instruct = test_flow_control_i }; const char* const test_asm = "# Comments.\n" "DATB 0x1 $20\n" "DATB 0xA $10\n" "DATB 0x2 $15\n" "[loop_start]\n" "ADDL $15 $15\n" "ADDL $3 $20\n" "CMPI $3 $10\n" "PUSH $15 1\n" "JILA [loop_start]\n" "HALT\n" "DD 0x7676 0xEFEF 0xABAB 0xCDCD 0x0000\n" "# EOF\n"; const char* const test_bios = "DATI 0x76 $0\n" "SLIA 0x100 $0\n" "INTX 0x1 0x100\n" "DATI 0xAB $0\n" "SLIA 0x100 $0\n" "INTX 0x1 0x100\n" "HALT\n" "# EOF\n"; static uint32_t test_bios_call(uint8_t* input) { printf("TEST BIOS CALL: %x\n", *((uint32_t*) input)); return 0x89ABCDEF; } Instruct test_speed_i[] = { {DATI, 0x1, 20}, {DATI, 0x3000000, 60}, {DATI, 0x2, 15}, {ADDL, 3, 20}, {CMPI, 3, 60}, {JILA, 3 * sizeof(Instruct), 0}, {HALT, 0, 0}, }; Program test_speed_p { .size = sizeof(test_speed_i), .instruct = test_speed_i }; const char* const test_tag = "JMPA [end]\n" "ADDI $50 $100\n" "MINI $25 $50\n" "[end]\n" "HALT\n" "# EOF\n"; int main() { puts("+---------------------+"); puts("| ASM 76 Test Program |"); puts("+---------------------+"); init(); { puts("===== Memory ====="); VM v(test_mem_p); v.execute(true); v.dump_registers(); } { puts("===== Basic Algebra ====="); VM v(test_basic_algebra_p); v.execute(true); v.dump_registers(); } { puts("===== Disassembler ====="); Disassembler d(test_flow_control_p); char* s = d.disassemble(); puts(s); free(s); } { puts("===== Assembler ====="); Assembler a(test_asm); a.scan(); Program p = a.assemble(); // Test assembler DD function printf("Data DD: %04x%08x%08x\n", p.instruct[9].opcode, p.instruct[9].a, p.instruct[9].b); // Test disassembler Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); puts("===== Flow Control & Logistics ====="); VM v(p); v.execute(false); v.dump_registers(); free(p.instruct); } { puts("===== Assembler: Tag Test ====="); Assembler a(test_tag); a.scan(); Program p = a.assemble(); Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); } { puts("===== BIOS Test ====="); BIOS* b = new BIOS(5); b->function_table[1] = &test_bios_call; Assembler a(test_bios); a.scan(); Program p = a.assemble(); VM v(p); v.firmware = b; v.execute(true); v.dump_registers(); } { puts("===== Object Code ====="); ObjectCode::write_file("test.obj", test_mem_p); Program p = ObjectCode::read_file("test.obj"); Disassembler d(p); char* s = d.disassemble(); puts(s); free(s); free(p.instruct); } { puts("===== Speed Test: 0x3000000 cycles ====="); VM v(test_speed_p); // The type is chrono::time_point<chrono::high_resolution_clock> // and that is why people used auto. auto t1 = chrono::high_resolution_clock::now(); v.execute(false); auto t2 = chrono::high_resolution_clock::now(); chrono::duration<double, milli> delay = t2 - t1; printf("Elapsed time: %lfms\nMIPS: %lf\n", delay.count(), ((double) 0x3000000) * 3.0 / ((double) delay.count()) / 10000.0 ); } puts("\n===== TEST END ====="); return 0; } <|endoftext|>
<commit_before>#include "ApacheProcess.h" #include "ApacheRequest.h" namespace mod_node { static apr_queue_t *queue; static ev_async req_watcher; static Persistent<Object> Process; static Persistent<Function> ProcessFunc; static Persistent<String> onrequest_sym; static process_rec *process; static void node_hook_child_init(apr_pool_t *p, server_rec *s); void ApacheProcess::Initialize(Handle<Object> target) { using mod_node::process; using mod_node::queue; using mod_node::req_watcher; HandleScope scope; Local<FunctionTemplate> proc_function_template = FunctionTemplate::New(); proc_function_template->InstanceTemplate()->SetInternalFieldCount(1); proc_function_template->SetClassName(String::New("ApacheProcess")); NODE_SET_PROTOTYPE_METHOD(proc_function_template, "log", Log); target->Set(String::New("APLOG_EMERG"), v8::Integer::NewFromUnsigned(APLOG_EMERG)); target->Set(String::New("APLOG_ALERT"), v8::Integer::NewFromUnsigned(APLOG_ALERT)); target->Set(String::New("APLOG_CRIT"), v8::Integer::NewFromUnsigned(APLOG_CRIT)); target->Set(String::New("APLOG_ERR"), v8::Integer::NewFromUnsigned(APLOG_ERR)); target->Set(String::New("APLOG_WARNING"), v8::Integer::NewFromUnsigned(APLOG_WARNING)); target->Set(String::New("APLOG_INFO"), v8::Integer::NewFromUnsigned(APLOG_INFO)); target->Set(String::New("APLOG_NOTICE"), v8::Integer::NewFromUnsigned(APLOG_NOTICE)); target->Set(String::New("APLOG_DEBUG"), v8::Integer::NewFromUnsigned(APLOG_DEBUG)); onrequest_sym = NODE_PSYMBOL("onrequest"); ProcessFunc = Persistent<Function>::New(proc_function_template->GetFunction()); Process = Persistent<Object>::New(ProcessFunc->NewInstance()); apr_queue_create(&queue, 100, process->pool); // @todo handle error ev_async_init(EV_DEFAULT_UC_ &req_watcher, ApacheProcess::RequestCallback); ev_async_start(EV_DEFAULT_UC_ &req_watcher); ev_ref(EV_DEFAULT_UC); target->Set(String::New("ApacheProcess"), ProcessFunc); target->Set(String::New("process"), Process); } void ApacheProcess::register_hooks(apr_pool_t *p) { ap_hook_child_init (node_hook_child_init, NULL,NULL, APR_HOOK_MIDDLE); ap_hook_handler(ApacheProcess::handler, NULL, NULL, APR_HOOK_MIDDLE); }; int ApacheProcess::handler(request_rec *r) { // Runs in the Apache thread using mod_node::queue; using mod_node::req_watcher; apr_status_t rv; request_ext rex; rex.req = r; rex.cont_request = 0; int rc = OK; apr_thread_cond_create(&rex.cv, process->pool); apr_thread_mutex_create(&rex.mtx, APR_THREAD_MUTEX_DEFAULT, process->pool); apr_thread_mutex_lock(rex.mtx); apr_table_setn(r->notes, "mod_node", (char *)&rex); apr_queue_push(queue, &rex); // @todo Errors { ev_async_send(EV_DEFAULT_ &req_watcher); while(!rex.cont_request) { apr_thread_cond_wait(rex.cv, rex.mtx); } } apr_thread_mutex_unlock(rex.mtx); return rc; } void ApacheProcess::RequestCallback(EV_P_ ev_async *w, int revents) { // Executes in Node's thread using mod_node::queue; using mod_node::req_watcher; HandleScope scope; request_ext *rex; apr_queue_pop(queue, (void **)&rex); // @todo Errors Handle<Value> req = ApacheRequest::New(rex); Local<Value> callback_v = Process->Get(onrequest_sym); if(!callback_v->IsFunction()) return; TryCatch trycatch; trycatch.SetVerbose(true); trycatch.SetCaptureMessage(true); const int argc = 1; Handle<Value> args[argc] = { req }; Local<Function>::Cast(callback_v)->Call(Process, 1, args); if(trycatch.HasCaught()) { v8::String::Utf8Value str(trycatch.Message()->Get()); ap_log_perror(APLOG_MARK, APLOG_ERR, APR_SUCCESS, process->pool, "%s", *str); } }; Handle<Value> ApacheProcess::Log(const Arguments &args) { if (args.Length() < 2 || !args[1]->IsString() || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } String::Utf8Value val(args[1]->ToString()); ap_log_perror(APLOG_MARK, args[0]->ToInt32()->Value(), APR_SUCCESS, process->pool, "%s", *val); return Undefined(); }; static void node_hook_child_init(apr_pool_t *p, server_rec *s) { using mod_node::thread; using mod_node::process; ap_open_logs(p, p, p, s); mod_node::process = s->process; apr_thread_create(&mod_node::thread, NULL, start_node, (void *)s, s->process->pool); }; }; <commit_msg>Use trypop and a loop, so we can be more out of sync with Apache<commit_after>#include "ApacheProcess.h" #include "ApacheRequest.h" namespace mod_node { static apr_queue_t *queue; static ev_async req_watcher; static Persistent<Object> Process; static Persistent<Function> ProcessFunc; static Persistent<String> onrequest_sym; static process_rec *process; static void node_hook_child_init(apr_pool_t *p, server_rec *s); void ApacheProcess::Initialize(Handle<Object> target) { using mod_node::process; using mod_node::queue; using mod_node::req_watcher; HandleScope scope; Local<FunctionTemplate> proc_function_template = FunctionTemplate::New(); proc_function_template->InstanceTemplate()->SetInternalFieldCount(1); proc_function_template->SetClassName(String::New("ApacheProcess")); NODE_SET_PROTOTYPE_METHOD(proc_function_template, "log", Log); target->Set(String::New("APLOG_EMERG"), v8::Integer::NewFromUnsigned(APLOG_EMERG)); target->Set(String::New("APLOG_ALERT"), v8::Integer::NewFromUnsigned(APLOG_ALERT)); target->Set(String::New("APLOG_CRIT"), v8::Integer::NewFromUnsigned(APLOG_CRIT)); target->Set(String::New("APLOG_ERR"), v8::Integer::NewFromUnsigned(APLOG_ERR)); target->Set(String::New("APLOG_WARNING"), v8::Integer::NewFromUnsigned(APLOG_WARNING)); target->Set(String::New("APLOG_INFO"), v8::Integer::NewFromUnsigned(APLOG_INFO)); target->Set(String::New("APLOG_NOTICE"), v8::Integer::NewFromUnsigned(APLOG_NOTICE)); target->Set(String::New("APLOG_DEBUG"), v8::Integer::NewFromUnsigned(APLOG_DEBUG)); onrequest_sym = NODE_PSYMBOL("onrequest"); ProcessFunc = Persistent<Function>::New(proc_function_template->GetFunction()); Process = Persistent<Object>::New(ProcessFunc->NewInstance()); apr_queue_create(&queue, 100, process->pool); // @todo handle error ev_async_init(EV_DEFAULT_UC_ &req_watcher, ApacheProcess::RequestCallback); ev_async_start(EV_DEFAULT_UC_ &req_watcher); ev_ref(EV_DEFAULT_UC); target->Set(String::New("ApacheProcess"), ProcessFunc); target->Set(String::New("process"), Process); } void ApacheProcess::register_hooks(apr_pool_t *p) { ap_hook_child_init (node_hook_child_init, NULL,NULL, APR_HOOK_MIDDLE); ap_hook_handler(ApacheProcess::handler, NULL, NULL, APR_HOOK_MIDDLE); }; int ApacheProcess::handler(request_rec *r) { // Runs in the Apache thread using mod_node::queue; using mod_node::req_watcher; apr_status_t rv; request_ext rex; rex.req = r; rex.cont_request = 0; int rc = OK; apr_thread_cond_create(&rex.cv, process->pool); apr_thread_mutex_create(&rex.mtx, APR_THREAD_MUTEX_DEFAULT, process->pool); apr_thread_mutex_lock(rex.mtx); apr_table_setn(r->notes, "mod_node", (char *)&rex); apr_queue_push(queue, &rex); // @todo Errors { ev_async_send(EV_DEFAULT_ &req_watcher); while(!rex.cont_request) { apr_thread_cond_wait(rex.cv, rex.mtx); } } apr_thread_mutex_unlock(rex.mtx); return rc; } void ApacheProcess::RequestCallback(EV_P_ ev_async *w, int revents) { // Executes in Node's thread using mod_node::queue; using mod_node::req_watcher; HandleScope scope; request_ext *rex; while (apr_queue_trypop(queue, (void **)&rex) == APR_SUCCESS) { // @todo Errors Handle<Value> req = ApacheRequest::New(rex); Local<Value> callback_v = Process->Get(onrequest_sym); if(!callback_v->IsFunction()) return; TryCatch trycatch; trycatch.SetVerbose(true); trycatch.SetCaptureMessage(true); const int argc = 1; Handle<Value> args[argc] = { req }; Local<Function>::Cast(callback_v)->Call(Process, 1, args); if(trycatch.HasCaught()) { v8::String::Utf8Value str(trycatch.Message()->Get()); ap_log_perror(APLOG_MARK, APLOG_ERR, APR_SUCCESS, process->pool, "%s", *str); } } }; Handle<Value> ApacheProcess::Log(const Arguments &args) { if (args.Length() < 2 || !args[1]->IsString() || !args[0]->IsInt32()) { return THROW_BAD_ARGS; } String::Utf8Value val(args[1]->ToString()); ap_log_perror(APLOG_MARK, args[0]->ToInt32()->Value(), APR_SUCCESS, process->pool, "%s", *val); return Undefined(); }; static void node_hook_child_init(apr_pool_t *p, server_rec *s) { using mod_node::thread; using mod_node::process; ap_open_logs(p, p, p, s); mod_node::process = s->process; apr_thread_create(&mod_node::thread, NULL, start_node, (void *)s, s->process->pool); }; }; <|endoftext|>
<commit_before>/* * opencog/atoms/base/Atom.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * Welter Silva <welter@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/base/Atom.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/AtomTable.h> #include <opencog/attentionbank/AttentionBank.h> #include <opencog/attentionbank/ImportanceIndex.h> namespace opencog { #define _avmtx _mtx // ============================================================== AttentionValuePtr Atom::getAttentionValue() const { // OK. The atomic thread-safety of shared-pointers is subtle. See // http://www.boost.org/doc/libs/1_53_0/libs/smart_ptr/shared_ptr.htm#ThreadSafety // and http://cppwisdom.quora.com/shared_ptr-is-almost-thread-safe // What it boils down to here is that we must *always* make a copy // of _attentionValue before we use it, since it can go out of scope // because it can get set in another thread. Viz, using it to // dereference can return a raw pointer to an object that has been // deconstructed. Furthermore, we must make a copy while holding // the lock! Got that? std::lock_guard<std::mutex> lck(_mtx); AttentionValuePtr local(_attentionValue); return local; } // XXX TODO This is insane. All this needs to be moved to the attention bank. void Atom::setAttentionValue(AttentionValuePtr av) { // Must obtain a local copy of the AV, since there may be // parallel writers in other threads. AttentionValuePtr local(getAttentionValue()); if (av == local) return; if (*av == *local) return; // Need to lock, shared_ptr is NOT atomic! std::unique_lock<std::mutex> lck (_avmtx); local = _attentionValue; // Get it again, to avoid races. _attentionValue = av; lck.unlock(); // If the atom free-floating, we are done. if (NULL == _atomTable) return; // Get old and new bins. int oldBin = ImportanceIndex::importanceBin(local->getSTI()); int newBin = ImportanceIndex::importanceBin(av->getSTI()); // If the atom importance has changed its bin, // update the importance index. if (oldBin != newBin) { attentionbank(_atomTable->getAtomSpace()).updateImportanceIndex(getHandle(), oldBin); } // Notify any interested parties that the AV changed. AVCHSigl& avch = attentionbank(_atomTable->getAtomSpace()).getAVChangedSignal(); avch(getHandle(), local, av); } void Atom::chgVLTI(int unit) { AttentionValuePtr old_av = getAttentionValue(); AttentionValuePtr new_av = createAV( old_av->getSTI(), old_av->getLTI(), old_av->getVLTI() + unit); setAttentionValue(new_av); } // ============================================================== } // ~namespace opencog <commit_msg>Remove the AV from the atom.<commit_after>/* * opencog/atoms/base/Atom.cc * * Copyright (C) 2002-2007 Novamente LLC * All Rights Reserved * * Written by Thiago Maia <thiago@vettatech.com> * Andre Senna <senna@vettalabs.com> * Welter Silva <welter@vettalabs.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License v3 as * published by the Free Software Foundation and including the exceptions * at http://opencog.org/wiki/Licenses * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program; if not, write to: * Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <opencog/atoms/base/Atom.h> #include <opencog/atomspace/AtomSpace.h> #include <opencog/atomspace/AtomTable.h> #include <opencog/attentionbank/AttentionBank.h> #include <opencog/attentionbank/ImportanceIndex.h> namespace opencog { #define _avmtx _mtx // ============================================================== AttentionValuePtr Atom::getAttentionValue() const { if (NULL == _atomTable) return AttentionValue::DEFAULT_AV(); Atom* a = (Atom*) this; return attentionbank(_atomTable->getAtomSpace()).get_av(a->getHandle()); } // XXX TODO This is insane. All this needs to be moved to the attention bank. void Atom::setAttentionValue(AttentionValuePtr av) { // If the atom free-floating, we are done. if (NULL == _atomTable) return; AttentionValuePtr local(getAttentionValue()); attentionbank(_atomTable->getAtomSpace()).add_atom(getHandle(), av); // Get old and new bins. int oldBin = ImportanceIndex::importanceBin(local->getSTI()); int newBin = ImportanceIndex::importanceBin(av->getSTI()); // If the atom importance has changed its bin, // update the importance index. if (oldBin != newBin) { attentionbank(_atomTable->getAtomSpace()).updateImportanceIndex(getHandle(), oldBin); } // Notify any interested parties that the AV changed. AVCHSigl& avch = attentionbank(_atomTable->getAtomSpace()).getAVChangedSignal(); avch(getHandle(), local, av); } void Atom::chgVLTI(int unit) { AttentionValuePtr old_av = getAttentionValue(); AttentionValuePtr new_av = createAV( old_av->getSTI(), old_av->getLTI(), old_av->getVLTI() + unit); setAttentionValue(new_av); } // ============================================================== } // ~namespace opencog <|endoftext|>
<commit_before>#include "pch.h" #include "GameMenuLayer.h" #include "ResourceManager.h" #include "ButtonLayer.h" GameMenuLayer::GameMenuLayer() { } GameMenuLayer::~GameMenuLayer() { } bool GameMenuLayer::init() { if (!Layer::init()) { return false; } auto winSize = cocos2d::Director::getInstance()->getWinSize(); m_WinWidth = winSize.width; m_WinHeight = winSize.height; m_GameMenuBackGround = GET_RESOURCE_MANAGER()->createSprite(ST_GAMEMENU_BACKGROUND); m_GameMenuFrame = GET_RESOURCE_MANAGER()->createSprite(ST_GAMEMENU_FRAME); setUIProperties(m_GameMenuBackGround, cocos2d::Point(0.5, 0.5), cocos2d::Point(m_WinWidth / 2, m_WinHeight / 2), 0.75f, false, 50); setUIProperties(m_GameMenuFrame, cocos2d::Point(0.5, 0.5), cocos2d::Point(m_WinWidth / 2, m_WinHeight / 2), 0.75f, false, 51); m_Button1 = ButtonLayer::create(); m_Button2 = ButtonLayer::create(); m_Button1->setButtonProperties(BUTTON_GAMEMENU, cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY()), cocos2d::Point(m_GameMenuFrame->getContentSize().width / 2, m_GameMenuFrame->getContentSize().height / 2), "Resume"); m_Button2->setButtonProperties(BUTTON_GAMEMENU, cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY()), cocos2d::Point(m_GameMenuFrame->getContentSize().width / 2, m_GameMenuFrame->getContentSize().height / 2 - 55), "Save and Quit"); //temporary buttons m_Button1->setButtonFunc(std::bind(&GameMenuLayer::quitGame, this)); m_Button2->setButtonFunc(std::bind(&GameMenuLayer::quitGame, this)); //add Children m_GameMenuFrame->addChild(m_Button1); m_GameMenuFrame->addChild(m_Button2); this->addChild(m_GameMenuBackGround); this->addChild(m_GameMenuFrame); return true; } void GameMenuLayer::update(float dTime) { m_Button1->update(dTime); m_Button2->update(dTime); } void GameMenuLayer::resumeGame() { } void GameMenuLayer::quitGame() { exit(0); } void GameMenuLayer::showGameMenu() { m_GameMenuBackGround->setVisible(true); m_GameMenuFrame->setVisible(true); m_Button1->setButtonRect(cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY())); m_Button2->setButtonRect(cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY())); } void GameMenuLayer::hideGameMenu() { m_GameMenuBackGround->setVisible(false); m_GameMenuFrame->setVisible(false); m_Button1->setButtonRect(cocos2d::Point(m_WinWidth, m_WinHeight)); m_Button2->setButtonRect(cocos2d::Point(m_WinWidth, m_WinHeight)); } <commit_msg>game 중 클릭 종료 버그 수정<commit_after>#include "pch.h" #include "GameMenuLayer.h" #include "ResourceManager.h" #include "ButtonLayer.h" GameMenuLayer::GameMenuLayer() { } GameMenuLayer::~GameMenuLayer() { } bool GameMenuLayer::init() { if (!Layer::init()) { return false; } auto winSize = cocos2d::Director::getInstance()->getWinSize(); m_WinWidth = winSize.width; m_WinHeight = winSize.height; m_GameMenuBackGround = GET_RESOURCE_MANAGER()->createSprite(ST_GAMEMENU_BACKGROUND); m_GameMenuFrame = GET_RESOURCE_MANAGER()->createSprite(ST_GAMEMENU_FRAME); setUIProperties(m_GameMenuBackGround, cocos2d::Point(0.5, 0.5), cocos2d::Point(m_WinWidth / 2, m_WinHeight / 2), 0.75f, false, 50); setUIProperties(m_GameMenuFrame, cocos2d::Point(0.5, 0.5), cocos2d::Point(m_WinWidth / 2, m_WinHeight / 2), 0.75f, false, 51); m_Button1 = ButtonLayer::create(); m_Button2 = ButtonLayer::create(); m_Button1->setButtonProperties(BUTTON_GAMEMENU, cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY()), cocos2d::Point(m_GameMenuFrame->getContentSize().width / 2, m_GameMenuFrame->getContentSize().height / 2), "Resume"); m_Button2->setButtonProperties(BUTTON_GAMEMENU, cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY()), cocos2d::Point(m_GameMenuFrame->getContentSize().width / 2, m_GameMenuFrame->getContentSize().height / 2 - 55), "Save and Quit"); //temporary buttons m_Button1->setButtonFunc(std::bind(&GameMenuLayer::quitGame, this)); m_Button2->setButtonFunc(std::bind(&GameMenuLayer::quitGame, this)); hideGameMenu(); //add Children m_GameMenuFrame->addChild(m_Button1); m_GameMenuFrame->addChild(m_Button2); this->addChild(m_GameMenuBackGround); this->addChild(m_GameMenuFrame); return true; } void GameMenuLayer::update(float dTime) { m_Button1->update(dTime); m_Button2->update(dTime); } void GameMenuLayer::resumeGame() { } void GameMenuLayer::quitGame() { exit(0); } void GameMenuLayer::showGameMenu() { m_GameMenuBackGround->setVisible(true); m_GameMenuFrame->setVisible(true); m_Button1->setButtonRect(cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY())); m_Button2->setButtonRect(cocos2d::Point(m_GameMenuFrame->getBoundingBox().getMinX(), m_GameMenuFrame->getBoundingBox().getMinY())); } void GameMenuLayer::hideGameMenu() { m_GameMenuBackGround->setVisible(false); m_GameMenuFrame->setVisible(false); m_Button1->setButtonRect(cocos2d::Point(m_WinWidth, m_WinHeight)); m_Button2->setButtonRect(cocos2d::Point(m_WinWidth, m_WinHeight)); } <|endoftext|>
<commit_before>/* The MIT License (MIT) * * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică * * 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 "elf_file.hpp" #include "elf_header_container.hpp" #include "program_header_table_container.hpp" #include "section_header_table_container.hpp" #include "segment_contents_container.hpp" #include "section_contents_container.hpp" #include <utility> using namespace elf; ELFFile::ELFFile(const std::string &filename) : FileUnit(filename), formatName("ELF") { loadFile(filename); } const std::string &ELFFile::getFormatName() { return formatName; } ELFFile::~ELFFile() { delete file; } bool ELFFile::getOpenStatus() { return open; } bool ELFFile::save(std::string &filename) { return file->save(filename); } void ELFFile::modifyHex(size_t offset, std::string &newContent) {} ELFIO::elfio *ELFFile::getELFIO() { return file; } bool ELFFile::loadFile(const std::string &filename) { file = new ELFIO::elfio(); open = file->load(filename); if (open && file->get_type() != ET_EXEC) open = false; std::vector<Container *> &topLevelContainers = getTopLevelContainers(); topLevelContainers.clear(); if (open) { topLevelContainers.push_back(new ELFHeaderContainer(this, std::make_pair(0, file->get_header_size()))); topLevelContainers.push_back(new ProgramHeaderTableContainer(this, std::make_pair(10, 20))); topLevelContainers.push_back(new SectionHeaderTableContainer(this, std::make_pair(20, 30))); topLevelContainers.push_back(new SegmentContentsContainer(this)); topLevelContainers.push_back(new SectionContentsContainer(this)); } return open; } <commit_msg>Handle ELFIO crash for 64-bit executable with corrupted e_ehsize<commit_after>/* The MIT License (MIT) * * Copyright (c) 2016 Ștefan-Gabriel Mirea, Adrian Dobrică * * 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 "elf_file.hpp" #include "elf_header_container.hpp" #include "program_header_table_container.hpp" #include "section_header_table_container.hpp" #include "segment_contents_container.hpp" #include "section_contents_container.hpp" #include <utility> using namespace elf; ELFFile::ELFFile(const std::string &filename) : FileUnit(filename), formatName("ELF") { loadFile(filename); } const std::string &ELFFile::getFormatName() { return formatName; } ELFFile::~ELFFile() { delete file; } bool ELFFile::getOpenStatus() { return open; } bool ELFFile::save(std::string &filename) { return file->save(filename); } void ELFFile::modifyHex(size_t offset, std::string &newContent) {} ELFIO::elfio *ELFFile::getELFIO() { return file; } bool ELFFile::loadFile(const std::string &filename) { file = new ELFIO::elfio(); try { open = file->load(filename); } catch (std::exception &e) { #ifdef DEBUG std::cerr << "Caught " << e.what() << " in LEFIO::load.\n"; #endif open = false; } if (open && file->get_type() != ET_EXEC) open = false; std::vector<Container *> &topLevelContainers = getTopLevelContainers(); topLevelContainers.clear(); if (open) { topLevelContainers.push_back(new ELFHeaderContainer(this, std::make_pair(0, file->get_header_size()))); topLevelContainers.push_back(new ProgramHeaderTableContainer(this, std::make_pair(10, 20))); topLevelContainers.push_back(new SectionHeaderTableContainer(this, std::make_pair(20, 30))); topLevelContainers.push_back(new SegmentContentsContainer(this)); topLevelContainers.push_back(new SectionContentsContainer(this)); } return open; } <|endoftext|>
<commit_before>// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Engine.h" #include "CompileConfig.h" #ifdef OUZEL_PLATFORM_OSX #include "RendererOGL.h" #endif #ifdef OUZEL_PLATFORM_WINDOWS #include "RendererD3D11.h" #endif #include "Utils.h" #include "Renderer.h" #include "Scene.h" #include "SoundManager.h" #include "FileSystem.h" void OuzelInit(ouzel::Settings&); void OuzelBegin(ouzel::Engine*); void OuzelEnd(); namespace ouzel { Engine::Engine() { Settings settings; OuzelInit(settings); switch (settings.driver) { case Renderer::Driver::OPENGL: #ifdef OUZEL_PLATFORM_OSX _renderer = new RendererOGL(settings.size, settings.fullscreen, this); #endif break; case Renderer::Driver::DIRECT3D11: #ifdef OUZEL_PLATFORM_WINDOWS _renderer = new RendererD3D11(settings.size, settings.fullscreen, this); #endif break; default: _renderer = new Renderer(settings.size, settings.fullscreen, this); break; } _scene = new Scene(this); _scene->init(); _soundManager = new SoundManager(this); _fileSystem = new FileSystem(); _previousFrameTime = getCurrentMicroSeconds(); } Engine::~Engine() { OuzelEnd(); if (_renderer) _renderer->release(); if (_scene) _scene->release(); if (_fileSystem) _fileSystem->release(); } void Engine::begin() { OuzelBegin(this); } void Engine::run() { _renderer->begin(); _renderer->clear(); _scene->drawAll(); _renderer->flush(); for (EventHandler* eventHandler : _eventHandlers) { uint64_t currentTime = getCurrentMicroSeconds(); uint64_t delta = currentTime - _previousFrameTime; _previousFrameTime = currentTime; eventHandler->update(static_cast<float>(delta)); } } void Engine::addEventHandler(EventHandler* eventHandler) { std::vector<EventHandler*>::iterator i = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler); if (i == _eventHandlers.end()) { _eventHandlers.push_back(eventHandler); } } void Engine::removeEventHandler(EventHandler* eventHandler) { std::vector<EventHandler*>::iterator i = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler); if (i != _eventHandlers.end()) { _eventHandlers.erase(i); } } void Engine::handleEvent(const Event& event) { for (EventHandler* eventHandler : _eventHandlers) { if (!eventHandler->handleEvent(event)) { break; } } } } <commit_msg>Create a default Renderer if none is available<commit_after>// Copyright (C) 2015 Elviss Strazdins // This file is part of the Ouzel engine. #include "Engine.h" #include "CompileConfig.h" #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) #include "RendererOGL.h" #endif #ifdef OUZEL_PLATFORM_WINDOWS #include "RendererD3D11.h" #endif #include "Utils.h" #include "Renderer.h" #include "Scene.h" #include "SoundManager.h" #include "FileSystem.h" void OuzelInit(ouzel::Settings&); void OuzelBegin(ouzel::Engine*); void OuzelEnd(); namespace ouzel { Engine::Engine() { Settings settings; OuzelInit(settings); switch (settings.driver) { #if defined(OUZEL_PLATFORM_OSX) || defined(OUZEL_PLATFORM_IOS) case Renderer::Driver::OPENGL: _renderer = new RendererOGL(settings.size, settings.fullscreen, this); break; #endif #ifdef OUZEL_PLATFORM_WINDOWS case Renderer::Driver::DIRECT3D11: _renderer = new RendererD3D11(settings.size, settings.fullscreen, this); break; #endif default: _renderer = new Renderer(settings.size, settings.fullscreen, this); break; } _scene = new Scene(this); _scene->init(); _soundManager = new SoundManager(this); _fileSystem = new FileSystem(); _previousFrameTime = getCurrentMicroSeconds(); } Engine::~Engine() { OuzelEnd(); if (_renderer) _renderer->release(); if (_scene) _scene->release(); if (_fileSystem) _fileSystem->release(); } void Engine::begin() { OuzelBegin(this); } void Engine::run() { _renderer->begin(); _renderer->clear(); _scene->drawAll(); _renderer->flush(); for (EventHandler* eventHandler : _eventHandlers) { uint64_t currentTime = getCurrentMicroSeconds(); uint64_t delta = currentTime - _previousFrameTime; _previousFrameTime = currentTime; eventHandler->update(static_cast<float>(delta)); } } void Engine::addEventHandler(EventHandler* eventHandler) { std::vector<EventHandler*>::iterator i = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler); if (i == _eventHandlers.end()) { _eventHandlers.push_back(eventHandler); } } void Engine::removeEventHandler(EventHandler* eventHandler) { std::vector<EventHandler*>::iterator i = std::find(_eventHandlers.begin(), _eventHandlers.end(), eventHandler); if (i != _eventHandlers.end()) { _eventHandlers.erase(i); } } void Engine::handleEvent(const Event& event) { for (EventHandler* eventHandler : _eventHandlers) { if (!eventHandler->handleEvent(event)) { break; } } } } <|endoftext|>
<commit_before>// // CRTMachine.hpp // Clock Signal // // Created by Thomas Harte on 31/05/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #ifndef CRTMachine_hpp #define CRTMachine_hpp #include "../Outputs/ScanTarget.hpp" #include "../Outputs/Speaker/Speaker.hpp" #include "../ClockReceiver/ClockReceiver.hpp" #include "../ClockReceiver/TimeTypes.hpp" #include "ROMMachine.hpp" #include "../Configurable/StandardOptions.hpp" #include <cmath> // TODO: rename. namespace CRTMachine { /*! A CRTMachine::Machine is a mostly-abstract base class for machines that connect to a CRT, that optionally provide a speaker, and that nominate a clock rate and can announce to a delegate should that clock rate change. */ class Machine { public: /*! Causes the machine to set up its display and, if it has one, speaker. The @c scan_target will receive all video output; the caller guarantees that it is non-null. */ virtual void set_scan_target(Outputs::Display::ScanTarget *scan_target) = 0; /// @returns The speaker that receives this machine's output, or @c nullptr if this machine is mute. virtual Outputs::Speaker::Speaker *get_speaker() = 0; /// @returns The confidence that this machine is running content it understands. virtual float get_confidence() { return 0.5f; } virtual std::string debug_type() { return ""; } /// Runs the machine for @c duration seconds. virtual void run_for(Time::Seconds duration) { const double cycles = (duration * clock_rate_) + clock_conversion_error_; clock_conversion_error_ = std::fmod(cycles, 1.0); run_for(Cycles(static_cast<int>(cycles))); } protected: /// Runs the machine for @c cycles. virtual void run_for(const Cycles cycles) = 0; void set_clock_rate(double clock_rate) { clock_rate_ = clock_rate; } double get_clock_rate() { return clock_rate_; } /*! Maps from Configurable::Display to Outputs::Display::VideoSignal and calls @c set_display_type with the result. */ void set_video_signal_configurable(Configurable::Display type) { Outputs::Display::DisplayType display_type; switch(type) { default: case Configurable::Display::RGB: display_type = Outputs::Display::DisplayType::RGB; break; case Configurable::Display::SVideo: display_type = Outputs::Display::DisplayType::SVideo; break; case Configurable::Display::CompositeColour: display_type = Outputs::Display::DisplayType::CompositeColour; break; case Configurable::Display::CompositeMonochrome: display_type = Outputs::Display::DisplayType::CompositeMonochrome; break; } set_display_type(display_type); } /*! Forwards the video signal to the target returned by get_crt(). */ virtual void set_display_type(Outputs::Display::DisplayType display_type) {} private: double clock_rate_ = 1.0; double clock_conversion_error_ = 0.0; }; } #endif /* CRTMachine_hpp */ <commit_msg>Adds CRTMachine::run_until, which will run until a condition is true.<commit_after>// // CRTMachine.hpp // Clock Signal // // Created by Thomas Harte on 31/05/2016. // Copyright 2016 Thomas Harte. All rights reserved. // #ifndef CRTMachine_hpp #define CRTMachine_hpp #include "../Outputs/ScanTarget.hpp" #include "../Outputs/Speaker/Speaker.hpp" #include "../ClockReceiver/ClockReceiver.hpp" #include "../ClockReceiver/TimeTypes.hpp" #include "ROMMachine.hpp" #include "../Configurable/StandardOptions.hpp" #include <cmath> // TODO: rename. namespace CRTMachine { /*! A CRTMachine::Machine is a mostly-abstract base class for machines that connect to a CRT, that optionally provide a speaker, and that nominate a clock rate and can announce to a delegate should that clock rate change. */ class Machine { public: /*! Causes the machine to set up its display and, if it has one, speaker. The @c scan_target will receive all video output; the caller guarantees that it is non-null. */ virtual void set_scan_target(Outputs::Display::ScanTarget *scan_target) = 0; /// @returns The speaker that receives this machine's output, or @c nullptr if this machine is mute. virtual Outputs::Speaker::Speaker *get_speaker() = 0; /// @returns The confidence that this machine is running content it understands. virtual float get_confidence() { return 0.5f; } virtual std::string debug_type() { return ""; } /// Runs the machine for @c duration seconds. void run_for(Time::Seconds duration) { const double cycles = (duration * clock_rate_) + clock_conversion_error_; clock_conversion_error_ = std::fmod(cycles, 1.0); run_for(Cycles(static_cast<int>(cycles))); } /// Runs for the machine for at least @c duration seconds, and then until @c condition is true. void run_until(Time::Seconds minimum_duration, std::function<bool()> condition) { run_for(minimum_duration); while(!condition()) { run_for(0.002); } } protected: /// Runs the machine for @c cycles. virtual void run_for(const Cycles cycles) = 0; void set_clock_rate(double clock_rate) { clock_rate_ = clock_rate; } double get_clock_rate() { return clock_rate_; } /*! Maps from Configurable::Display to Outputs::Display::VideoSignal and calls @c set_display_type with the result. */ void set_video_signal_configurable(Configurable::Display type) { Outputs::Display::DisplayType display_type; switch(type) { default: case Configurable::Display::RGB: display_type = Outputs::Display::DisplayType::RGB; break; case Configurable::Display::SVideo: display_type = Outputs::Display::DisplayType::SVideo; break; case Configurable::Display::CompositeColour: display_type = Outputs::Display::DisplayType::CompositeColour; break; case Configurable::Display::CompositeMonochrome: display_type = Outputs::Display::DisplayType::CompositeMonochrome; break; } set_display_type(display_type); } /*! Forwards the video signal to the target returned by get_crt(). */ virtual void set_display_type(Outputs::Display::DisplayType display_type) {} private: double clock_rate_ = 1.0; double clock_conversion_error_ = 0.0; }; } #endif /* CRTMachine_hpp */ <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/external_cookie_handler.h" #include <set> #include <vector> #include "base/basictypes.h" #include "base/time.h" #include "googleurl/src/gurl.h" #include "net/base/cookie_options.h" #include "net/base/cookie_store.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test ExternalCookieHandlerTest; static const std::string cookie1 = "coookie1\n"; static const std::string cookie2 = "coookie2\n"; static const std::string cookie3 = "coookie3"; class MockCookieStore : public net::CookieStore { public: MockCookieStore() : expected_url_(ExternalCookieHandler::kGoogleAccountsUrl) { cookies_.insert(cookie1); cookies_.insert(cookie2); cookies_.insert(cookie3); } virtual ~MockCookieStore() {} virtual bool SetCookie(const GURL& url, const std::string& cookie_line) { EXPECT_TRUE(false); return true; } virtual bool SetCookieWithOptions(const GURL& url, const std::string& cookie_line, const net::CookieOptions& options) { EXPECT_FALSE(options.exclude_httponly()); EXPECT_EQ(expected_url_, url); std::set<std::string>::iterator it; it = cookies_.find(cookie_line); bool has_cookie = cookies_.end() != it; if (has_cookie) cookies_.erase(it); return has_cookie; } virtual bool SetCookieWithCreationTime(const GURL& url, const std::string& cookie_line, const base::Time& creation_time) { EXPECT_TRUE(false); return true; } virtual bool SetCookieWithCreationTimeWithOptions( const GURL& url, const std::string& cookie_line, const base::Time& creation_time, const net::CookieOptions& options) { EXPECT_TRUE(false); return true; } virtual void SetCookies(const GURL& url, const std::vector<std::string>& cookies) { EXPECT_TRUE(false); } virtual void SetCookiesWithOptions(const GURL& url, const std::vector<std::string>& cookies, const net::CookieOptions& options) { EXPECT_TRUE(false); } virtual std::string GetCookies(const GURL& url) { EXPECT_TRUE(false); return std::string(); } virtual std::string GetCookiesWithOptions(const GURL& url, const net::CookieOptions& options) { EXPECT_TRUE(false); return std::string(); } private: std::set<std::string> cookies_; const GURL expected_url_; DISALLOW_EVIL_CONSTRUCTORS(MockCookieStore); }; TEST_F(ExternalCookieHandlerTest, MockCookieStoreSanityTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; net::CookieOptions options; options.set_include_httponly(); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie1, options)); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie2, options)); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie3, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie1, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie2, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie3, options)); } class MockReader : public PipeReader { public: explicit MockReader(const std::vector<std::string>& cookies) : data_(cookies) { } std::string Read(const uint32 bytes_to_read) { std::string to_return; if (!data_.empty()) { to_return = data_.back(); data_.pop_back(); } return to_return; } private: std::vector<std::string> data_; }; TEST_F(ExternalCookieHandlerTest, SuccessfulReadTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; std::vector<std::string> cookies; cookies.push_back(cookie3); cookies.push_back(cookie2); cookies.push_back(cookie1); MockReader *reader = new MockReader(cookies); ExternalCookieHandler handler(reader); // takes ownership. EXPECT_TRUE(handler.HandleCookies(&cookie_store)); } TEST_F(ExternalCookieHandlerTest, SuccessfulSlowReadTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; std::vector<std::string> cookies; cookies.push_back(cookie3); cookies.push_back(cookie2.substr(2)); cookies.push_back(cookie2.substr(0, 2)); cookies.push_back(cookie1); MockReader *reader = new MockReader(cookies); ExternalCookieHandler handler(reader); // takes ownership. EXPECT_TRUE(handler.HandleCookies(&cookie_store)); } <commit_msg>Disabling failing ExternalCookieHandlerTest tests<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/chromeos/external_cookie_handler.h" #include <set> #include <vector> #include "base/basictypes.h" #include "base/time.h" #include "googleurl/src/gurl.h" #include "net/base/cookie_options.h" #include "net/base/cookie_store.h" #include "testing/gtest/include/gtest/gtest.h" typedef testing::Test ExternalCookieHandlerTest; static const std::string cookie1 = "coookie1\n"; static const std::string cookie2 = "coookie2\n"; static const std::string cookie3 = "coookie3"; class MockCookieStore : public net::CookieStore { public: MockCookieStore() : expected_url_(ExternalCookieHandler::kGoogleAccountsUrl) { cookies_.insert(cookie1); cookies_.insert(cookie2); cookies_.insert(cookie3); } virtual ~MockCookieStore() {} virtual bool SetCookie(const GURL& url, const std::string& cookie_line) { EXPECT_TRUE(false); return true; } virtual bool SetCookieWithOptions(const GURL& url, const std::string& cookie_line, const net::CookieOptions& options) { EXPECT_FALSE(options.exclude_httponly()); EXPECT_EQ(expected_url_, url); std::set<std::string>::iterator it; it = cookies_.find(cookie_line); bool has_cookie = cookies_.end() != it; if (has_cookie) cookies_.erase(it); return has_cookie; } virtual bool SetCookieWithCreationTime(const GURL& url, const std::string& cookie_line, const base::Time& creation_time) { EXPECT_TRUE(false); return true; } virtual bool SetCookieWithCreationTimeWithOptions( const GURL& url, const std::string& cookie_line, const base::Time& creation_time, const net::CookieOptions& options) { EXPECT_TRUE(false); return true; } virtual void SetCookies(const GURL& url, const std::vector<std::string>& cookies) { EXPECT_TRUE(false); } virtual void SetCookiesWithOptions(const GURL& url, const std::vector<std::string>& cookies, const net::CookieOptions& options) { EXPECT_TRUE(false); } virtual std::string GetCookies(const GURL& url) { EXPECT_TRUE(false); return std::string(); } virtual std::string GetCookiesWithOptions(const GURL& url, const net::CookieOptions& options) { EXPECT_TRUE(false); return std::string(); } private: std::set<std::string> cookies_; const GURL expected_url_; DISALLOW_EVIL_CONSTRUCTORS(MockCookieStore); }; TEST_F(ExternalCookieHandlerTest, DISABLED_MockCookieStoreSanityTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; net::CookieOptions options; options.set_include_httponly(); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie1, options)); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie2, options)); EXPECT_TRUE(cookie_store.SetCookieWithOptions(url, cookie3, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie1, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie2, options)); EXPECT_FALSE(cookie_store.SetCookieWithOptions(url, cookie3, options)); } class MockReader : public PipeReader { public: explicit MockReader(const std::vector<std::string>& cookies) : data_(cookies) { } std::string Read(const uint32 bytes_to_read) { std::string to_return; if (!data_.empty()) { to_return = data_.back(); data_.pop_back(); } return to_return; } private: std::vector<std::string> data_; }; TEST_F(ExternalCookieHandlerTest, DISABLED_SuccessfulReadTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; std::vector<std::string> cookies; cookies.push_back(cookie3); cookies.push_back(cookie2); cookies.push_back(cookie1); MockReader *reader = new MockReader(cookies); ExternalCookieHandler handler(reader); // takes ownership. EXPECT_TRUE(handler.HandleCookies(&cookie_store)); } TEST_F(ExternalCookieHandlerTest, DISABLED_SuccessfulSlowReadTest) { GURL url(ExternalCookieHandler::kGoogleAccountsUrl); MockCookieStore cookie_store; std::vector<std::string> cookies; cookies.push_back(cookie3); cookies.push_back(cookie2.substr(2)); cookies.push_back(cookie2.substr(0, 2)); cookies.push_back(cookie1); MockReader *reader = new MockReader(cookies); ExternalCookieHandler handler(reader); // takes ownership. EXPECT_TRUE(handler.HandleCookies(&cookie_store)); } <|endoftext|>
<commit_before>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "chrome/browser/media/webrtc_browsertest_base.h" #include "chrome/browser/media/webrtc_browsertest_common.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/test/browser_test_utils.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/perf/perf_test.h" #include "ui/gl/gl_switches.h" static const char kSimulcastTestPage[] = "/webrtc/webrtc-simulcast.html"; // Simulcast integration test. This test ensures 'a=x-google-flag:conference' // is working and that Chrome is capable of sending simulcast streams. class WebRtcSimulcastBrowserTest : public WebRtcTestBase { public: // TODO(phoglund): Make it possible to enable DetectErrorsInJavaScript() here. void SetUpCommandLine(base::CommandLine* command_line) override { // Just answer 'allow' to GetUserMedia invocations. command_line->AppendSwitch(switches::kUseFakeUIForMediaStream); // The video playback will not work without a GPU, so force its use here. command_line->AppendSwitch(switches::kUseGpuInTests); // Use fake devices in order to run on VMs. command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream); } }; // Fails/times out on Win only. http://crbug.com/452623 #if defined(OS_WIN) #define MAYBE_TestVgaReturnsTwoSimulcastStreams DISABLED_TestVgaReturnsTwoSimulcastStreams #else #define MAYBE_TestVgaReturnsTwoSimulcastStreams TestVgaReturnsTwoSimulcastStreams #endif IN_PROC_BROWSER_TEST_F(WebRtcSimulcastBrowserTest, MAYBE_TestVgaReturnsTwoSimulcastStreams) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kSimulcastTestPage)); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_EQ("OK", ExecuteJavascript("testVgaReturnsTwoSimulcastStreams()", tab_contents)); } <commit_msg>Disable WebRtcSimulcastBrowserTest.TestVgaReturnsTwoSimulcastStreams under MSan<commit_after>// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/command_line.h" #include "base/files/file_path.h" #include "base/path_service.h" #include "chrome/browser/media/webrtc_browsertest_base.h" #include "chrome/browser/media/webrtc_browsertest_common.h" #include "chrome/browser/ui/browser.h" #include "chrome/browser/ui/browser_tabstrip.h" #include "chrome/browser/ui/tabs/tab_strip_model.h" #include "chrome/common/chrome_switches.h" #include "chrome/test/base/in_process_browser_test.h" #include "chrome/test/base/ui_test_utils.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/render_process_host.h" #include "content/public/test/browser_test_utils.h" #include "media/base/media_switches.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/perf/perf_test.h" #include "ui/gl/gl_switches.h" static const char kSimulcastTestPage[] = "/webrtc/webrtc-simulcast.html"; // Simulcast integration test. This test ensures 'a=x-google-flag:conference' // is working and that Chrome is capable of sending simulcast streams. class WebRtcSimulcastBrowserTest : public WebRtcTestBase { public: // TODO(phoglund): Make it possible to enable DetectErrorsInJavaScript() here. void SetUpCommandLine(base::CommandLine* command_line) override { // Just answer 'allow' to GetUserMedia invocations. command_line->AppendSwitch(switches::kUseFakeUIForMediaStream); // The video playback will not work without a GPU, so force its use here. command_line->AppendSwitch(switches::kUseGpuInTests); // Use fake devices in order to run on VMs. command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream); } }; // Fails/times out on Win only. http://crbug.com/452623 // MSan reports errors. http://crbug.com/452892 #if defined(OS_WIN) || defined(MEMORY_SANITIZER) #define MAYBE_TestVgaReturnsTwoSimulcastStreams DISABLED_TestVgaReturnsTwoSimulcastStreams #else #define MAYBE_TestVgaReturnsTwoSimulcastStreams TestVgaReturnsTwoSimulcastStreams #endif IN_PROC_BROWSER_TEST_F(WebRtcSimulcastBrowserTest, MAYBE_TestVgaReturnsTwoSimulcastStreams) { ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady()); ui_test_utils::NavigateToURL( browser(), embedded_test_server()->GetURL(kSimulcastTestPage)); content::WebContents* tab_contents = browser()->tab_strip_model()->GetActiveWebContents(); ASSERT_EQ("OK", ExecuteJavascript("testVgaReturnsTwoSimulcastStreams()", tab_contents)); } <|endoftext|>
<commit_before>// // riscv-format.cc // #include <map> #include <vector> #include <string> #include "riscv-opcodes.h" #include "riscv-types.h" #include "riscv-imm.h" #include "riscv-regs.h" #include "riscv-decode.h" #include "riscv-regs.h" #include "riscv-csr.h" #include "riscv-processor.h" #include "riscv-compression.h" #include "riscv-util.h" #include "riscv-format.h" const rvf fmt_none[] = { rvf_z }; const rvf fmt_ipc[] = { rvf_ipc, rvf_z }; const rvf fmt_rs1_rs2[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf fmt_rd_imm[] = { rvf_rd, rvf_c, rvf_imm, rvf_z }; const rvf fmt_rd_ipc[] = { rvf_rd, rvf_c, rvf_ipc, rvf_z }; const rvf fmt_rd_rs1_rs2[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf fmt_frd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_z }; const rvf fmt_rd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_rs1, rvf_c, rvf_frs2, rvf_z }; const rvf fmt_frd_frs1_frs2_frs3[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_c, rvf_frs3, rvf_z }; const rvf fmt_frd_rs1[] = { rvf_frd, rvf_c, rvf_rs1, rvf_z }; const rvf fmt_frd_frs1[] = { rvf_frd, rvf_c, rvf_frs1, rvf_z }; const rvf fmt_rd_frs1[] = { rvf_rd, rvf_c, rvf_frs1, rvf_z }; const rvf fmt_rd_rs1_imm[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_imm, rvf_z }; const rvf fmt_rd_bimm_rs1[] = { rvf_rd, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_frd_bimm_rs1[] = { rvf_frd, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rd_csr_rs1[] = { rvf_rd, rvf_c, rvf_csr, rvf_c, rvf_rs1, rvf_z }; const rvf fmt_rd_csr_irs1[] = { rvf_rd, rvf_c, rvf_csr, rvf_c, rvf_irs1, rvf_z }; const rvf fmt_rs2_bimm_rs1[] = { rvf_rs2, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_frs2_bimm_rs1[] = { rvf_frs2, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rs1_rs2_ipc[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_ipc, rvf_z }; const rvf fmt_rd_rs2_b_rs1[] = { rvf_rd, rvf_c, rvf_rs2, rvf_c, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rd_b_rs1[] = { rvf_rd, rvf_c, rvf_b, rvf_rs1, rvf_d, rvf_z }; const riscv_inst_type_metadata riscv_inst_type_table[] = { { riscv_inst_type_unknown, fmt_none }, { riscv_inst_type_c_none, fmt_none }, { riscv_inst_type_cb, fmt_ipc }, { riscv_inst_type_ci, fmt_rd_imm }, { riscv_inst_type_ci_16sp, fmt_rd_rs1_imm }, { riscv_inst_type_ci_fldsp, fmt_frd_bimm_rs1 }, { riscv_inst_type_ci_flwsp, fmt_frd_bimm_rs1 }, { riscv_inst_type_ci_ldsp, fmt_rd_bimm_rs1 }, { riscv_inst_type_ci_li, fmt_rd_imm }, { riscv_inst_type_ci_lui, fmt_rd_imm }, { riscv_inst_type_ci_lwsp, fmt_rd_imm }, { riscv_inst_type_ciw_4spn, fmt_rd_rs1_imm }, { riscv_inst_type_cj, fmt_ipc }, { riscv_inst_type_cl_fld, fmt_frd_bimm_rs1 }, { riscv_inst_type_cl_flw, fmt_frd_bimm_rs1 }, { riscv_inst_type_cl_ld, fmt_rd_bimm_rs1 }, { riscv_inst_type_cl_lw, fmt_rd_bimm_rs1 }, { riscv_inst_type_cr, fmt_rs1_rs2 }, { riscv_inst_type_cr_jalr, fmt_rs1_rs2 }, { riscv_inst_type_cr_jr, fmt_rs1_rs2 }, { riscv_inst_type_cs, fmt_rs1_rs2 }, { riscv_inst_type_cs_fsd, fmt_frs2_bimm_rs1 }, { riscv_inst_type_cs_fsw, fmt_frs2_bimm_rs1 }, { riscv_inst_type_cs_sd, fmt_rs2_bimm_rs1 }, { riscv_inst_type_cs_sw, fmt_rs2_bimm_rs1 }, { riscv_inst_type_css_fswsp, fmt_frs2_bimm_rs1 }, { riscv_inst_type_css_fsdsp, fmt_frs2_bimm_rs1 }, { riscv_inst_type_css_swsp, fmt_rs2_bimm_rs1 }, { riscv_inst_type_css_sdsp, fmt_rs2_bimm_rs1 }, { riscv_inst_type_i, fmt_rd_rs1_imm }, { riscv_inst_type_i_csr, fmt_rd_csr_rs1 }, { riscv_inst_type_i_csri, fmt_rd_csr_irs1 }, { riscv_inst_type_i_l, fmt_rd_bimm_rs1 }, { riscv_inst_type_i_lf, fmt_frd_bimm_rs1 }, { riscv_inst_type_i_none, fmt_none }, { riscv_inst_type_i_sh5, fmt_rd_rs1_imm }, { riscv_inst_type_i_sh6, fmt_rd_rs1_imm }, { riscv_inst_type_r, fmt_rd_rs1_rs2 }, { riscv_inst_type_r_3f, fmt_frd_frs1_frs2 }, { riscv_inst_type_r_4f, fmt_frd_frs1_frs2_frs3 }, { riscv_inst_type_r_a, fmt_rd_rs2_b_rs1 }, { riscv_inst_type_r_ff, fmt_frd_frs1 }, { riscv_inst_type_r_fr, fmt_frd_rs1 }, { riscv_inst_type_r_l, fmt_rd_b_rs1 }, { riscv_inst_type_r_rf, fmt_rd_frs1 }, { riscv_inst_type_r_rff, fmt_rd_frs1_frs2 }, { riscv_inst_type_s, fmt_rs2_bimm_rs1 }, { riscv_inst_type_s_f, fmt_frs2_bimm_rs1 }, { riscv_inst_type_sb, fmt_rs1_rs2_ipc }, { riscv_inst_type_u, fmt_rd_imm }, { riscv_inst_type_uj, fmt_rd_ipc }, { riscv_inst_type_unknown, nullptr } }; /* Metadata Tables */ struct riscv_inst_type_map : std::map<riscv_inst_type,const riscv_inst_type_metadata*> { riscv_inst_type_map() { for (const auto *ent = riscv_inst_type_table; ent->fmt; ent++) (*this)[ent->type] = ent; } }; struct riscv_inst_comp_map : std::map<riscv_op,const riscv_inst_comp_metadata*> { riscv_inst_comp_map() { for (const auto *ent = riscv_comp_table; ent->cop; ent++) (*this)[ent->cop] = ent; } }; struct riscv_csr_map : std::map<riscv_hu,const riscv_csr_metadata*> { riscv_csr_map() { for (const auto *ent = riscv_csr_table; ent->csr_value; ent++) (*this)[ent->csr_value] = ent; } }; const riscv_inst_type_metadata* riscv_lookup_inst_metadata(riscv_inst_type type) { static riscv_inst_type_map type_map; return type_map[type]; } const riscv_inst_comp_metadata* riscv_lookup_comp_metadata(riscv_op op) { static riscv_inst_comp_map comp_map; return comp_map[op]; } const riscv_csr_metadata* riscv_lookup_csr_metadata(riscv_hu csr_value) { static riscv_csr_map csr_map; return csr_map[csr_value]; } void riscv_print_instruction(riscv_decode &dec, riscv_proc_state *proc, riscv_ptr pc, riscv_ptr pc_offset) { #if 1 const riscv_inst_comp_metadata *comp = riscv_lookup_comp_metadata((riscv_op)dec.op); if (comp) { dec.op = comp->op; dec.type = comp->type; } #endif const riscv_inst_type_metadata *inst_meta = riscv_lookup_inst_metadata((riscv_inst_type)dec.type); const rvf *fmt = inst_meta ? inst_meta->fmt : fmt_none; printf("%s", format_string("%016tx: \t", pc - pc_offset).c_str()); switch (dec.sz) { case 2: printf("%s", format_string("%04x\t\t", *(riscv_hu*)pc).c_str()); break; case 4: printf("%s", format_string("%08x\t", *(riscv_wu*)pc).c_str()); break; } printf("%s\t", riscv_instructions[dec.op].opcode); while (*fmt != rvf_z) { switch (*fmt) { case rvf_b: printf("("); break; case rvf_c: printf(","); break; case rvf_d: printf(")"); break; case rvf_rd: printf("%s", riscv_i_registers[dec.rd]); break; case rvf_rs1: printf("%s", riscv_i_registers[dec.rs1]); break; case rvf_rs2: printf("%s", riscv_i_registers[dec.rs2]); break; case rvf_frd: printf("%s", riscv_f_registers[dec.rd]); break; case rvf_frs1: printf("%s", riscv_f_registers[dec.rs1]); break; case rvf_frs2: printf("%s", riscv_f_registers[dec.rs2]); break; case rvf_frs3: printf("%s", riscv_f_registers[dec.rs3]); break; case rvf_irs1: printf("%s", format_string("%d", dec.rs1).c_str()); break; case rvf_imm: printf("%s", format_string("%lld", dec.imm, dec.imm).c_str()); break; case rvf_ipc: printf("%s", format_string("%lld \t# 0x%016tx", dec.imm, pc - pc_offset + dec.imm).c_str()); break; case rvf_csr: { const riscv_csr_metadata *csr = riscv_lookup_csr_metadata(dec.imm); printf("%s", (csr ? csr->csr_name : format_string("%llu", dec.imm)).c_str()); break; } case rvf_z: break; } fmt++; } printf("\n"); } <commit_msg>Remove ifdef around opcode decompression<commit_after>// // riscv-format.cc // #include <map> #include <vector> #include <string> #include "riscv-opcodes.h" #include "riscv-types.h" #include "riscv-imm.h" #include "riscv-regs.h" #include "riscv-decode.h" #include "riscv-regs.h" #include "riscv-csr.h" #include "riscv-processor.h" #include "riscv-compression.h" #include "riscv-util.h" #include "riscv-format.h" const rvf fmt_none[] = { rvf_z }; const rvf fmt_ipc[] = { rvf_ipc, rvf_z }; const rvf fmt_rs1_rs2[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf fmt_rd_imm[] = { rvf_rd, rvf_c, rvf_imm, rvf_z }; const rvf fmt_rd_ipc[] = { rvf_rd, rvf_c, rvf_ipc, rvf_z }; const rvf fmt_rd_rs1_rs2[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf fmt_frd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_z }; const rvf fmt_rd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_rs1, rvf_c, rvf_frs2, rvf_z }; const rvf fmt_frd_frs1_frs2_frs3[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_c, rvf_frs3, rvf_z }; const rvf fmt_frd_rs1[] = { rvf_frd, rvf_c, rvf_rs1, rvf_z }; const rvf fmt_frd_frs1[] = { rvf_frd, rvf_c, rvf_frs1, rvf_z }; const rvf fmt_rd_frs1[] = { rvf_rd, rvf_c, rvf_frs1, rvf_z }; const rvf fmt_rd_rs1_imm[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_imm, rvf_z }; const rvf fmt_rd_bimm_rs1[] = { rvf_rd, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_frd_bimm_rs1[] = { rvf_frd, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rd_csr_rs1[] = { rvf_rd, rvf_c, rvf_csr, rvf_c, rvf_rs1, rvf_z }; const rvf fmt_rd_csr_irs1[] = { rvf_rd, rvf_c, rvf_csr, rvf_c, rvf_irs1, rvf_z }; const rvf fmt_rs2_bimm_rs1[] = { rvf_rs2, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_frs2_bimm_rs1[] = { rvf_frs2, rvf_c, rvf_imm, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rs1_rs2_ipc[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_ipc, rvf_z }; const rvf fmt_rd_rs2_b_rs1[] = { rvf_rd, rvf_c, rvf_rs2, rvf_c, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf fmt_rd_b_rs1[] = { rvf_rd, rvf_c, rvf_b, rvf_rs1, rvf_d, rvf_z }; const riscv_inst_type_metadata riscv_inst_type_table[] = { { riscv_inst_type_unknown, fmt_none }, { riscv_inst_type_c_none, fmt_none }, { riscv_inst_type_cb, fmt_ipc }, { riscv_inst_type_ci, fmt_rd_imm }, { riscv_inst_type_ci_16sp, fmt_rd_rs1_imm }, { riscv_inst_type_ci_fldsp, fmt_frd_bimm_rs1 }, { riscv_inst_type_ci_flwsp, fmt_frd_bimm_rs1 }, { riscv_inst_type_ci_ldsp, fmt_rd_bimm_rs1 }, { riscv_inst_type_ci_li, fmt_rd_imm }, { riscv_inst_type_ci_lui, fmt_rd_imm }, { riscv_inst_type_ci_lwsp, fmt_rd_imm }, { riscv_inst_type_ciw_4spn, fmt_rd_rs1_imm }, { riscv_inst_type_cj, fmt_ipc }, { riscv_inst_type_cl_fld, fmt_frd_bimm_rs1 }, { riscv_inst_type_cl_flw, fmt_frd_bimm_rs1 }, { riscv_inst_type_cl_ld, fmt_rd_bimm_rs1 }, { riscv_inst_type_cl_lw, fmt_rd_bimm_rs1 }, { riscv_inst_type_cr, fmt_rs1_rs2 }, { riscv_inst_type_cr_jalr, fmt_rs1_rs2 }, { riscv_inst_type_cr_jr, fmt_rs1_rs2 }, { riscv_inst_type_cs, fmt_rs1_rs2 }, { riscv_inst_type_cs_fsd, fmt_frs2_bimm_rs1 }, { riscv_inst_type_cs_fsw, fmt_frs2_bimm_rs1 }, { riscv_inst_type_cs_sd, fmt_rs2_bimm_rs1 }, { riscv_inst_type_cs_sw, fmt_rs2_bimm_rs1 }, { riscv_inst_type_css_fswsp, fmt_frs2_bimm_rs1 }, { riscv_inst_type_css_fsdsp, fmt_frs2_bimm_rs1 }, { riscv_inst_type_css_swsp, fmt_rs2_bimm_rs1 }, { riscv_inst_type_css_sdsp, fmt_rs2_bimm_rs1 }, { riscv_inst_type_i, fmt_rd_rs1_imm }, { riscv_inst_type_i_csr, fmt_rd_csr_rs1 }, { riscv_inst_type_i_csri, fmt_rd_csr_irs1 }, { riscv_inst_type_i_l, fmt_rd_bimm_rs1 }, { riscv_inst_type_i_lf, fmt_frd_bimm_rs1 }, { riscv_inst_type_i_none, fmt_none }, { riscv_inst_type_i_sh5, fmt_rd_rs1_imm }, { riscv_inst_type_i_sh6, fmt_rd_rs1_imm }, { riscv_inst_type_r, fmt_rd_rs1_rs2 }, { riscv_inst_type_r_3f, fmt_frd_frs1_frs2 }, { riscv_inst_type_r_4f, fmt_frd_frs1_frs2_frs3 }, { riscv_inst_type_r_a, fmt_rd_rs2_b_rs1 }, { riscv_inst_type_r_ff, fmt_frd_frs1 }, { riscv_inst_type_r_fr, fmt_frd_rs1 }, { riscv_inst_type_r_l, fmt_rd_b_rs1 }, { riscv_inst_type_r_rf, fmt_rd_frs1 }, { riscv_inst_type_r_rff, fmt_rd_frs1_frs2 }, { riscv_inst_type_s, fmt_rs2_bimm_rs1 }, { riscv_inst_type_s_f, fmt_frs2_bimm_rs1 }, { riscv_inst_type_sb, fmt_rs1_rs2_ipc }, { riscv_inst_type_u, fmt_rd_imm }, { riscv_inst_type_uj, fmt_rd_ipc }, { riscv_inst_type_unknown, nullptr } }; /* Metadata Tables */ struct riscv_inst_type_map : std::map<riscv_inst_type,const riscv_inst_type_metadata*> { riscv_inst_type_map() { for (const auto *ent = riscv_inst_type_table; ent->fmt; ent++) (*this)[ent->type] = ent; } }; struct riscv_inst_comp_map : std::map<riscv_op,const riscv_inst_comp_metadata*> { riscv_inst_comp_map() { for (const auto *ent = riscv_comp_table; ent->cop; ent++) (*this)[ent->cop] = ent; } }; struct riscv_csr_map : std::map<riscv_hu,const riscv_csr_metadata*> { riscv_csr_map() { for (const auto *ent = riscv_csr_table; ent->csr_value; ent++) (*this)[ent->csr_value] = ent; } }; const riscv_inst_type_metadata* riscv_lookup_inst_metadata(riscv_inst_type type) { static riscv_inst_type_map type_map; return type_map[type]; } const riscv_inst_comp_metadata* riscv_lookup_comp_metadata(riscv_op op) { static riscv_inst_comp_map comp_map; return comp_map[op]; } const riscv_csr_metadata* riscv_lookup_csr_metadata(riscv_hu csr_value) { static riscv_csr_map csr_map; return csr_map[csr_value]; } void riscv_print_instruction(riscv_decode &dec, riscv_proc_state *proc, riscv_ptr pc, riscv_ptr pc_offset) { const riscv_inst_comp_metadata *comp = riscv_lookup_comp_metadata((riscv_op)dec.op); if (comp) { dec.op = comp->op; dec.type = comp->type; } const riscv_inst_type_metadata *inst_meta = riscv_lookup_inst_metadata((riscv_inst_type)dec.type); const rvf *fmt = inst_meta ? inst_meta->fmt : fmt_none; printf("%s", format_string("%016tx: \t", pc - pc_offset).c_str()); switch (dec.sz) { case 2: printf("%s", format_string("%04x\t\t", *(riscv_hu*)pc).c_str()); break; case 4: printf("%s", format_string("%08x\t", *(riscv_wu*)pc).c_str()); break; } printf("%s\t", riscv_instructions[dec.op].opcode); while (*fmt != rvf_z) { switch (*fmt) { case rvf_b: printf("("); break; case rvf_c: printf(","); break; case rvf_d: printf(")"); break; case rvf_rd: printf("%s", riscv_i_registers[dec.rd]); break; case rvf_rs1: printf("%s", riscv_i_registers[dec.rs1]); break; case rvf_rs2: printf("%s", riscv_i_registers[dec.rs2]); break; case rvf_frd: printf("%s", riscv_f_registers[dec.rd]); break; case rvf_frs1: printf("%s", riscv_f_registers[dec.rs1]); break; case rvf_frs2: printf("%s", riscv_f_registers[dec.rs2]); break; case rvf_frs3: printf("%s", riscv_f_registers[dec.rs3]); break; case rvf_irs1: printf("%s", format_string("%d", dec.rs1).c_str()); break; case rvf_imm: printf("%s", format_string("%lld", dec.imm, dec.imm).c_str()); break; case rvf_ipc: printf("%s", format_string("%lld \t# 0x%016tx", dec.imm, pc - pc_offset + dec.imm).c_str()); break; case rvf_csr: { const riscv_csr_metadata *csr = riscv_lookup_csr_metadata(dec.imm); printf("%s", (csr ? csr->csr_name : format_string("%llu", dec.imm)).c_str()); break; } case rvf_z: break; } fmt++; } printf("\n"); } <|endoftext|>
<commit_before>// // riscv-format.cc // #include <map> #include <vector> #include <string> #include "riscv-opcodes.h" #include "riscv-types.h" #include "riscv-imm.h" #include "riscv-decode.h" #include "riscv-regs.h" #include "riscv-csr.h" #include "riscv-processor.h" #include "riscv-compression.h" #include "riscv-util.h" #include "riscv-format.h" const rvf rvf_none[] = { rvf_z }; const rvf rvf_imm_pc[] = { rvf_ipc, rvf_z }; const rvf rvf_rs1_rs2[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf rvf_rs2_imm[] = { rvf_rs2, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_imm[] = { rvf_rd, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_imm_pc[] = { rvf_rd, rvf_c, rvf_ipc, rvf_z }; const rvf rvf_rd_rs1_rs2[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf rvf_frd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_z }; const rvf rvf_rd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_rs1, rvf_c, rvf_frs2, rvf_z }; const rvf rvf_frd_frs1_frs2_frs3[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_c, rvf_frs3, rvf_z }; const rvf rvf_frd_rs1[] = { rvf_frd, rvf_c, rvf_rs1, rvf_z }; const rvf rvf_frd_frs1[] = { rvf_frd, rvf_c, rvf_frs1, rvf_z }; const rvf rvf_rd_frs1[] = { rvf_rd, rvf_c, rvf_frs1, rvf_z }; const rvf rvf_rd_rs1_imm[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_bimm_rs1[] = { rvf_rd, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_frd_bimm_rs1[] = { rvf_frd, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_rd_csr_rs1[] = { rvf_rd, rvf_c, rvf_icsr, rvf_c, rvf_rs1, rvf_z }; const rvf rvf_rd_csr_srs1[] = { rvf_rd, rvf_c, rvf_icsr, rvf_c, rvf_srs1, rvf_z }; const rvf rvf_rs1_rs2_imm[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_i, rvf_z }; const rvf rvf_rs2_bimm_rs1[] = { rvf_rs2, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_frs2_bimm_rs1[] = { rvf_frs2, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_rs1_rs2_imm_pc[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_ipc, rvf_z }; const riscv_inst_type_metadata riscv_inst_type_table[] = { { riscv_inst_type_unknown, rvf_none }, { riscv_inst_type_cr, rvf_rs1_rs2 }, { riscv_inst_type_ci, rvf_rd_imm }, { riscv_inst_type_ci_lui, rvf_rd_imm }, { riscv_inst_type_ci_lwsp, rvf_rd_imm }, { riscv_inst_type_ci_ldsp, rvf_rd_imm }, { riscv_inst_type_ci_addi16sp, rvf_rd_imm }, { riscv_inst_type_css_swsp, rvf_rs2_imm }, { riscv_inst_type_css_sdsp, rvf_rs2_imm }, { riscv_inst_type_ciw_addi4spn, rvf_rd_imm }, { riscv_inst_type_cl_lw, rvf_rd_imm }, { riscv_inst_type_cl_ld, rvf_rd_imm }, { riscv_inst_type_cs_x, rvf_rs1_rs2 }, { riscv_inst_type_cs_sw, rvf_rs1_rs2_imm }, { riscv_inst_type_cs_sd, rvf_rs1_rs2_imm }, { riscv_inst_type_cb, rvf_imm_pc }, { riscv_inst_type_cj, rvf_imm_pc }, { riscv_inst_type_r, rvf_rd_rs1_rs2 }, { riscv_inst_type_r_ff, rvf_frd_frs1}, { riscv_inst_type_r_rf, rvf_rd_frs1}, { riscv_inst_type_r_fr, rvf_frd_rs1 }, { riscv_inst_type_r_fff, rvf_frd_frs1_frs2}, { riscv_inst_type_r_rff, rvf_rd_frs1_frs2}, { riscv_inst_type_r_ffff, rvf_frd_frs1_frs2_frs3}, { riscv_inst_type_i, rvf_rd_rs1_imm }, { riscv_inst_type_i_s, rvf_none }, { riscv_inst_type_i_l, rvf_rd_bimm_rs1 }, { riscv_inst_type_i_lf, rvf_frd_bimm_rs1 }, { riscv_inst_type_i_csr, rvf_rd_csr_rs1 }, { riscv_inst_type_i_csri, rvf_rd_csr_srs1 }, { riscv_inst_type_s, rvf_rs2_bimm_rs1 }, { riscv_inst_type_sf, rvf_frs2_bimm_rs1 }, { riscv_inst_type_sb, rvf_rs1_rs2_imm_pc }, { riscv_inst_type_u, rvf_rd_imm }, { riscv_inst_type_uj, rvf_rd_imm_pc }, { riscv_inst_type_unknown, nullptr } }; /* Metadata Tables */ const riscv_inst_type_metadata* riscv_lookup_inst_metadata(riscv_inst_type type) { static std::map<riscv_inst_type,const riscv_inst_type_metadata*> type_map; if (type_map.size() == 0) { const riscv_inst_type_metadata *ent = riscv_inst_type_table; while (ent->fmt) { type_map[ent->type] = ent; ent++; } } std::map<riscv_inst_type,const riscv_inst_type_metadata*>::iterator type_i = type_map.find(type); return (type_i != type_map.end()) ? type_i->second : nullptr; } const riscv_inst_comp_metadata* riscv_lookup_comp_metadata(riscv_op op) { static std::map<riscv_op,const riscv_inst_comp_metadata*> comp_map; if (comp_map.size() == 0) { const riscv_inst_comp_metadata *ent = riscv_comp_table; while (ent->cop) { comp_map[ent->cop] = ent; ent++; } } std::map<riscv_op,const riscv_inst_comp_metadata*>::iterator type_i = comp_map.find(op); return (type_i != comp_map.end()) ? type_i->second : nullptr; } const riscv_csr_metadata* riscv_lookup_csr_metadata(riscv_hu csr_value) { static std::map<riscv_hu,const riscv_csr_metadata*> csr_map; if (csr_map.size() == 0) { const riscv_csr_metadata *ent = riscv_csr_table; while (ent->csr_value) { csr_map[ent->csr_value] = ent; ent++; } } std::map<riscv_hu,const riscv_csr_metadata*>::iterator csr_i = csr_map.find(csr_value); return (csr_i != csr_map.end()) ? csr_i->second : nullptr; } void riscv_print_instruction(riscv_decode &dec, riscv_proc_state *proc, riscv_ptr pc, riscv_ptr pc_offset) { #if 1 const riscv_inst_comp_metadata *comp = riscv_lookup_comp_metadata((riscv_op)dec.op); if (comp) { dec.op = comp->op; dec.type = comp->type; } #endif const riscv_inst_type_metadata *inst_meta = riscv_lookup_inst_metadata((riscv_inst_type)dec.type); const rvf *fmt = inst_meta ? inst_meta->fmt : rvf_none; printf("%s", format_string("%016tx: \t", pc - pc_offset).c_str()); switch (dec.sz) { case 2: printf("%s", format_string("%04x\t\t", *(riscv_hu*)pc).c_str()); break; case 4: printf("%s", format_string("%08x\t", *(riscv_wu*)pc).c_str()); break; } printf("%s\t", riscv_instructions[dec.op]); while (*fmt != rvf_z) { switch (*fmt) { case rvf_b: printf("("); break; case rvf_c: printf(","); break; case rvf_d: printf(")"); break; case rvf_rd: printf("%s", riscv_i_registers[dec.rd]); break; case rvf_rs1: printf("%s", riscv_i_registers[dec.rs1]); break; case rvf_rs2: printf("%s", riscv_i_registers[dec.rs2]); break; case rvf_frd: printf("%s", riscv_f_registers[dec.rd]); break; case rvf_frs1: printf("%s", riscv_f_registers[dec.rs1]); break; case rvf_frs2: printf("%s", riscv_f_registers[dec.rs2]); break; case rvf_frs3: printf("%s", riscv_f_registers[dec.rs3]); break; case rvf_srs1: printf("%s", format_string("%d", dec.rs1).c_str()); break; case rvf_i: printf("%s", format_string("%lld", dec.imm, dec.imm).c_str()); break; case rvf_ipc: printf("%s", format_string("%lld \t# 0x%016tx", dec.imm, pc - pc_offset + dec.imm).c_str()); break; case rvf_icsr: { const riscv_csr_metadata *csr = riscv_lookup_csr_metadata(dec.imm); printf("%s", (csr ? csr->csr_name : format_string("%llu", dec.imm)).c_str()); break; } case rvf_z: break; } fmt++; } printf("\n"); } <commit_msg>Use thread safe static initializers for metadata tables<commit_after>// // riscv-format.cc // #include <map> #include <vector> #include <string> #include "riscv-opcodes.h" #include "riscv-types.h" #include "riscv-imm.h" #include "riscv-decode.h" #include "riscv-regs.h" #include "riscv-csr.h" #include "riscv-processor.h" #include "riscv-compression.h" #include "riscv-util.h" #include "riscv-format.h" const rvf rvf_none[] = { rvf_z }; const rvf rvf_imm_pc[] = { rvf_ipc, rvf_z }; const rvf rvf_rs1_rs2[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf rvf_rs2_imm[] = { rvf_rs2, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_imm[] = { rvf_rd, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_imm_pc[] = { rvf_rd, rvf_c, rvf_ipc, rvf_z }; const rvf rvf_rd_rs1_rs2[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_rs2, rvf_z }; const rvf rvf_frd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_z }; const rvf rvf_rd_frs1_frs2[] = { rvf_frd, rvf_c, rvf_rs1, rvf_c, rvf_frs2, rvf_z }; const rvf rvf_frd_frs1_frs2_frs3[] = { rvf_frd, rvf_c, rvf_frs1, rvf_c, rvf_frs2, rvf_c, rvf_frs3, rvf_z }; const rvf rvf_frd_rs1[] = { rvf_frd, rvf_c, rvf_rs1, rvf_z }; const rvf rvf_frd_frs1[] = { rvf_frd, rvf_c, rvf_frs1, rvf_z }; const rvf rvf_rd_frs1[] = { rvf_rd, rvf_c, rvf_frs1, rvf_z }; const rvf rvf_rd_rs1_imm[] = { rvf_rd, rvf_c, rvf_rs1, rvf_c, rvf_i, rvf_z }; const rvf rvf_rd_bimm_rs1[] = { rvf_rd, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_frd_bimm_rs1[] = { rvf_frd, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_rd_csr_rs1[] = { rvf_rd, rvf_c, rvf_icsr, rvf_c, rvf_rs1, rvf_z }; const rvf rvf_rd_csr_srs1[] = { rvf_rd, rvf_c, rvf_icsr, rvf_c, rvf_srs1, rvf_z }; const rvf rvf_rs1_rs2_imm[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_i, rvf_z }; const rvf rvf_rs2_bimm_rs1[] = { rvf_rs2, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_frs2_bimm_rs1[] = { rvf_frs2, rvf_c, rvf_i, rvf_b, rvf_rs1, rvf_d, rvf_z }; const rvf rvf_rs1_rs2_imm_pc[] = { rvf_rs1, rvf_c, rvf_rs2, rvf_c, rvf_ipc, rvf_z }; const riscv_inst_type_metadata riscv_inst_type_table[] = { { riscv_inst_type_unknown, rvf_none }, { riscv_inst_type_cr, rvf_rs1_rs2 }, { riscv_inst_type_ci, rvf_rd_imm }, { riscv_inst_type_ci_lui, rvf_rd_imm }, { riscv_inst_type_ci_lwsp, rvf_rd_imm }, { riscv_inst_type_ci_ldsp, rvf_rd_imm }, { riscv_inst_type_ci_addi16sp, rvf_rd_imm }, { riscv_inst_type_css_swsp, rvf_rs2_imm }, { riscv_inst_type_css_sdsp, rvf_rs2_imm }, { riscv_inst_type_ciw_addi4spn, rvf_rd_imm }, { riscv_inst_type_cl_lw, rvf_rd_imm }, { riscv_inst_type_cl_ld, rvf_rd_imm }, { riscv_inst_type_cs_x, rvf_rs1_rs2 }, { riscv_inst_type_cs_sw, rvf_rs1_rs2_imm }, { riscv_inst_type_cs_sd, rvf_rs1_rs2_imm }, { riscv_inst_type_cb, rvf_imm_pc }, { riscv_inst_type_cj, rvf_imm_pc }, { riscv_inst_type_r, rvf_rd_rs1_rs2 }, { riscv_inst_type_r_ff, rvf_frd_frs1}, { riscv_inst_type_r_rf, rvf_rd_frs1}, { riscv_inst_type_r_fr, rvf_frd_rs1 }, { riscv_inst_type_r_fff, rvf_frd_frs1_frs2}, { riscv_inst_type_r_rff, rvf_rd_frs1_frs2}, { riscv_inst_type_r_ffff, rvf_frd_frs1_frs2_frs3}, { riscv_inst_type_i, rvf_rd_rs1_imm }, { riscv_inst_type_i_s, rvf_none }, { riscv_inst_type_i_l, rvf_rd_bimm_rs1 }, { riscv_inst_type_i_lf, rvf_frd_bimm_rs1 }, { riscv_inst_type_i_csr, rvf_rd_csr_rs1 }, { riscv_inst_type_i_csri, rvf_rd_csr_srs1 }, { riscv_inst_type_s, rvf_rs2_bimm_rs1 }, { riscv_inst_type_sf, rvf_frs2_bimm_rs1 }, { riscv_inst_type_sb, rvf_rs1_rs2_imm_pc }, { riscv_inst_type_u, rvf_rd_imm }, { riscv_inst_type_uj, rvf_rd_imm_pc }, { riscv_inst_type_unknown, nullptr } }; /* Metadata Tables */ struct riscv_inst_type_map : std::map<riscv_inst_type,const riscv_inst_type_metadata*> { riscv_inst_type_map() { for (const auto *ent = riscv_inst_type_table; ent->fmt; ent++) (*this)[ent->type] = ent; } }; struct riscv_inst_comp_map : std::map<riscv_op,const riscv_inst_comp_metadata*> { riscv_inst_comp_map() { for (const auto *ent = riscv_comp_table; ent->cop; ent++) (*this)[ent->cop] = ent; } }; struct riscv_csr_map : std::map<riscv_hu,const riscv_csr_metadata*> { riscv_csr_map() { for (const auto *ent = riscv_csr_table; ent->csr_value; ent++) (*this)[ent->csr_value] = ent; } }; const riscv_inst_type_metadata* riscv_lookup_inst_metadata(riscv_inst_type type) { static riscv_inst_type_map type_map; return type_map[type]; } const riscv_inst_comp_metadata* riscv_lookup_comp_metadata(riscv_op op) { static riscv_inst_comp_map comp_map; return comp_map[op]; } const riscv_csr_metadata* riscv_lookup_csr_metadata(riscv_hu csr_value) { static riscv_csr_map csr_map; return csr_map[csr_value]; } void riscv_print_instruction(riscv_decode &dec, riscv_proc_state *proc, riscv_ptr pc, riscv_ptr pc_offset) { #if 1 const riscv_inst_comp_metadata *comp = riscv_lookup_comp_metadata((riscv_op)dec.op); if (comp) { dec.op = comp->op; dec.type = comp->type; } #endif const riscv_inst_type_metadata *inst_meta = riscv_lookup_inst_metadata((riscv_inst_type)dec.type); const rvf *fmt = inst_meta ? inst_meta->fmt : rvf_none; printf("%s", format_string("%016tx: \t", pc - pc_offset).c_str()); switch (dec.sz) { case 2: printf("%s", format_string("%04x\t\t", *(riscv_hu*)pc).c_str()); break; case 4: printf("%s", format_string("%08x\t", *(riscv_wu*)pc).c_str()); break; } printf("%s\t", riscv_instructions[dec.op]); while (*fmt != rvf_z) { switch (*fmt) { case rvf_b: printf("("); break; case rvf_c: printf(","); break; case rvf_d: printf(")"); break; case rvf_rd: printf("%s", riscv_i_registers[dec.rd]); break; case rvf_rs1: printf("%s", riscv_i_registers[dec.rs1]); break; case rvf_rs2: printf("%s", riscv_i_registers[dec.rs2]); break; case rvf_frd: printf("%s", riscv_f_registers[dec.rd]); break; case rvf_frs1: printf("%s", riscv_f_registers[dec.rs1]); break; case rvf_frs2: printf("%s", riscv_f_registers[dec.rs2]); break; case rvf_frs3: printf("%s", riscv_f_registers[dec.rs3]); break; case rvf_srs1: printf("%s", format_string("%d", dec.rs1).c_str()); break; case rvf_i: printf("%s", format_string("%lld", dec.imm, dec.imm).c_str()); break; case rvf_ipc: printf("%s", format_string("%lld \t# 0x%016tx", dec.imm, pc - pc_offset + dec.imm).c_str()); break; case rvf_icsr: { const riscv_csr_metadata *csr = riscv_lookup_csr_metadata(dec.imm); printf("%s", (csr ? csr->csr_name : format_string("%llu", dec.imm)).c_str()); break; } case rvf_z: break; } fmt++; } printf("\n"); } <|endoftext|>
<commit_before>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "modsecurity/rules.h" #include "modsecurity/rule_message.h" #include "modsecurity/modsecurity.h" #include "modsecurity/transaction.h" #include "src/utils/string.h" namespace modsecurity { std::string RuleMessage::_details(const RuleMessage *rm) { std::string msg; msg.append(" [file \"" + std::string(rm->m_ruleFile) + "\"]"); msg.append(" [line \"" + std::to_string(rm->m_ruleLine) + "\"]"); msg.append(" [id \"" + std::to_string(rm->m_ruleId) + "\"]"); msg.append(" [rev \"" + rm->m_rev + "\"]"); msg.append(" [msg \"" + rm->m_message + "\"]"); msg.append(" [data \"" + rm->m_data + "\"]"); msg.append(" [severity \"" + std::to_string(rm->m_severity) + "\"]"); msg.append(" [ver \"" + rm->m_ver + "\"]"); msg.append(" [maturity \"" + std::to_string(rm->m_maturity) + "\"]"); msg.append(" [accuracy \"" + std::to_string(rm->m_accuracy) + "\"]"); for (auto &a : rm->m_tags) { msg.append(" [tag \"" + a + "\"]"); } msg.append(" [hostname \"" + std::string(rm->m_serverIpAddress) \ + "\"]"); msg.append(" [uri \"" + rm->m_uriNoQueryStringDecoded + "\"]"); msg.append(" [unique_id \"" + rm->m_id + "\"]"); msg.append(" [ref \"" + rm->m_reference + "\"]"); return msg; } std::string RuleMessage::_errorLogTail(const RuleMessage *rm) { std::string msg; msg.append("[hostname \"" + std::string(rm->m_serverIpAddress) + "\"]"); msg.append(" [uri \"" + rm->m_uriNoQueryStringDecoded + "\"]"); msg.append(" [unique_id \"" + rm->m_id + "\"]"); return msg; } std::string RuleMessage::log(const RuleMessage *rm, int props, int code) { std::string msg(""); if (props & ClientLogMessageInfo) { msg.append("[client " + std::string(rm->m_clientIpAddress) + "] "); } if (rm->m_isDisruptive) { msg.append("ModSecurity: Access denied with code "); if (code == -1) { msg.append("%d"); } else { msg.append(std::to_string(code)); } msg.append(" (phase "); msg.append(std::to_string(rm->m_rule->m_phase - 1) + "). "); } else { msg.append("ModSecurity: Warning. "); } msg.append(rm->m_match); msg.append(_details(rm)); if (props & ErrorLogTailLogMessageInfo) { msg.append(" " + _errorLogTail(rm)); } return modsecurity::utils::string::toHexIfNeeded(msg); } } // namespace modsecurity <commit_msg>Limit log variables to 200 characters<commit_after>/* * ModSecurity, http://www.modsecurity.org/ * Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/) * * 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 * * If any of the files related to licensing are missing or if you have any * other questions related to licensing please contact Trustwave Holdings, Inc. * directly using the email address security@modsecurity.org. * */ #include "modsecurity/rules.h" #include "modsecurity/rule_message.h" #include "modsecurity/modsecurity.h" #include "modsecurity/transaction.h" #include "src/utils/string.h" namespace modsecurity { std::string RuleMessage::_details(const RuleMessage *rm) { std::string msg; msg.append(" [file \"" + std::string(rm->m_ruleFile) + "\"]"); msg.append(" [line \"" + std::to_string(rm->m_ruleLine) + "\"]"); msg.append(" [id \"" + std::to_string(rm->m_ruleId) + "\"]"); msg.append(" [rev \"" + rm->m_rev + "\"]"); msg.append(" [msg \"" + rm->m_message + "\"]"); msg.append(" [data \"" + utils::string::limitTo(200, rm->m_data) + "\"]"); msg.append(" [severity \"" + std::to_string(rm->m_severity) + "\"]"); msg.append(" [ver \"" + rm->m_ver + "\"]"); msg.append(" [maturity \"" + std::to_string(rm->m_maturity) + "\"]"); msg.append(" [accuracy \"" + std::to_string(rm->m_accuracy) + "\"]"); for (auto &a : rm->m_tags) { msg.append(" [tag \"" + a + "\"]"); } msg.append(" [hostname \"" + std::string(rm->m_serverIpAddress) \ + "\"]"); msg.append(" [uri \"" + utils::string::limitTo(200, rm->m_uriNoQueryStringDecoded) + "\"]"); msg.append(" [unique_id \"" + rm->m_id + "\"]"); msg.append(" [ref \"" + utils::string::limitTo(200, rm->m_reference) + "\"]"); return msg; } std::string RuleMessage::_errorLogTail(const RuleMessage *rm) { std::string msg; msg.append("[hostname \"" + std::string(rm->m_serverIpAddress) + "\"]"); msg.append(" [uri \"" + utils::string::limitTo(200, rm->m_uriNoQueryStringDecoded) + "\"]"); msg.append(" [unique_id \"" + rm->m_id + "\"]"); return msg; } std::string RuleMessage::log(const RuleMessage *rm, int props, int code) { std::string msg(""); if (props & ClientLogMessageInfo) { msg.append("[client " + std::string(rm->m_clientIpAddress) + "] "); } if (rm->m_isDisruptive) { msg.append("ModSecurity: Access denied with code "); if (code == -1) { msg.append("%d"); } else { msg.append(std::to_string(code)); } msg.append(" (phase "); msg.append(std::to_string(rm->m_rule->m_phase - 1) + "). "); } else { msg.append("ModSecurity: Warning. "); } msg.append(rm->m_match); msg.append(_details(rm)); if (props & ErrorLogTailLogMessageInfo) { msg.append(" " + _errorLogTail(rm)); } return modsecurity::utils::string::toHexIfNeeded(msg); } } // namespace modsecurity <|endoftext|>
<commit_before>#include "sift.hpp" #include "internal.hpp" #include <opencv2/imgproc/imgproc.hpp> #include <vector> #include <utility> #include <iterator> #include <algorithm> namespace sift { void buildGaussianPyramid(Mat& image, vector<vector<Mat>>& pyr, int nOctaves) { Mat image_ds = image.clone(); pyr.resize(nOctaves); for (int o = 0; o < nOctaves; o++) { auto sigma = GAUSSIAN_PYR_SIGMA0; for (auto s = 0; s < GAUSSIAN_PYR_OCTAVE_SIZE; s++) { Mat image_ds_blur(image_ds.rows, image_ds.cols, image_ds.type()); cv::GaussianBlur( image_ds, image_ds_blur, cv::Size(GAUSSIAN_PYR_KERNEL_SIZE, GAUSSIAN_PYR_KERNEL_SIZE), sigma); pyr[o].push_back(image_ds_blur); sigma *= GAUSSIAN_PYR_K; } image_ds = downSample(pyr[o][GAUSSIAN_PYR_OCTAVE_SIZE-3]); } } /** * @brief Builds a difference of gaussian for each octave * * @param gauss_pyr 2D vector representing pyramids of all octaves. * @remark order of dogs is identical to gauss_pyr * @return 2D vector of DoGs */ vector<vector<Mat>> buildDogPyr(vector<vector<Mat>> gauss_pyr) { vector<vector<Mat>> dogs(gauss_pyr.size()); auto dog_iterator = std::begin(dogs); for (const auto &octave : gauss_pyr) { auto start = std::begin(octave); auto end = --std::end(octave); std::transform(start, end, start + 1, std::back_inserter(*dog_iterator), [](const Mat & lower, const Mat &upper) { return upper - lower; } ); dog_iterator++; } return dogs; } /** * @brief Detects keypoints from DoG * @details Finds extremas in a 3x3x3 window * * @param dog_pyr DoGs for each octave * @param keypoints vector to be populated */ void getScaleSpaceExtrema(vector<vector<Mat>> &dog_pyr, vector<KeyPoint> &keypoints) { for (std::size_t octave = 0; octave < dog_pyr.size(); octave++) { auto &octave_dog = dog_pyr[octave]; auto octave_sigma = internal::compute_octave_sigma(octave); for (std::size_t image = 1; image < octave_dog.size() - 1; image++) { vector<internal::point> points = internal::find_local_extremas( octave_dog[image - 1], octave_dog[image], octave_dog[image + 1]); // Now we have x, y coordinates of extremas, we need to create keypoints /*********************************************************************************************** * References * *- http://answers.opencv.org/question/7337/keypoint-size/ * *- http://www.aishack.in/tutorials/sift-scale-invariant-feature-transform-keypoints/ * *- http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html * ***********************************************************************************************/ for (const auto &p : points) { // FIXME: need to compute response value // found abs(interpolated_DoG_val ue), what does that mean? // FIXME: Use subpixel values // Compute subpixel values // using taylor expansion keypoints.emplace_back(p.first, p.second, octave_sigma, -1, octave_dog[image].at<image_t>(p.first, p.second), octave); } } } } } <commit_msg>Document buildGaussianPyramid<commit_after>#include "sift.hpp" #include "internal.hpp" #include <opencv2/imgproc/imgproc.hpp> #include <vector> #include <utility> #include <iterator> #include <algorithm> namespace sift { /** * @brief Builds the gaussian pyramid * * @param image cv::Mat representing the input image * @param pyr reference to a 2D vector representing pyramids of all octaves. * @param nOctaves total number of octaves that should be built * @remark pyr[0] is octave 0, pyr[0][0] is the least blurred image of octave 0 * @return void */ void buildGaussianPyramid(Mat& image, vector<vector<Mat>>& pyr, int nOctaves) { Mat image_ds = image.clone(); pyr.resize(nOctaves); for (int o = 0; o < nOctaves; o++) { auto sigma = GAUSSIAN_PYR_SIGMA0; for (auto s = 0; s < GAUSSIAN_PYR_OCTAVE_SIZE; s++) { Mat image_ds_blur(image_ds.rows, image_ds.cols, image_ds.type()); cv::GaussianBlur( image_ds, image_ds_blur, cv::Size(GAUSSIAN_PYR_KERNEL_SIZE, GAUSSIAN_PYR_KERNEL_SIZE), sigma); pyr[o].push_back(image_ds_blur); sigma *= GAUSSIAN_PYR_K; } image_ds = downSample(pyr[o][GAUSSIAN_PYR_OCTAVE_SIZE-3]); } } /** * @brief Builds a difference of gaussian for each octave * * @param gauss_pyr 2D vector representing pyramids of all octaves. * @remark order of dogs is identical to gauss_pyr * @return 2D vector of DoGs */ vector<vector<Mat>> buildDogPyr(vector<vector<Mat>> gauss_pyr) { vector<vector<Mat>> dogs(gauss_pyr.size()); auto dog_iterator = std::begin(dogs); for (const auto &octave : gauss_pyr) { auto start = std::begin(octave); auto end = --std::end(octave); std::transform(start, end, start + 1, std::back_inserter(*dog_iterator), [](const Mat & lower, const Mat &upper) { return upper - lower; } ); dog_iterator++; } return dogs; } /** * @brief Detects keypoints from DoG * @details Finds extremas in a 3x3x3 window * * @param dog_pyr DoGs for each octave * @param keypoints vector to be populated */ void getScaleSpaceExtrema(vector<vector<Mat>> &dog_pyr, vector<KeyPoint> &keypoints) { for (std::size_t octave = 0; octave < dog_pyr.size(); octave++) { auto &octave_dog = dog_pyr[octave]; auto octave_sigma = internal::compute_octave_sigma(octave); for (std::size_t image = 1; image < octave_dog.size() - 1; image++) { vector<internal::point> points = internal::find_local_extremas( octave_dog[image - 1], octave_dog[image], octave_dog[image + 1]); // Now we have x, y coordinates of extremas, we need to create keypoints /*********************************************************************************************** * References * *- http://answers.opencv.org/question/7337/keypoint-size/ * *- http://www.aishack.in/tutorials/sift-scale-invariant-feature-transform-keypoints/ * *- http://docs.opencv.org/modules/features2d/doc/common_interfaces_of_feature_detectors.html * ***********************************************************************************************/ for (const auto &p : points) { // FIXME: need to compute response value // found abs(interpolated_DoG_val ue), what does that mean? // FIXME: Use subpixel values // Compute subpixel values // using taylor expansion keypoints.emplace_back(p.first, p.second, octave_sigma, -1, octave_dog[image].at<image_t>(p.first, p.second), octave); } } } } } <|endoftext|>
<commit_before>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "http.h" #include "manager.h" #include <assert.h> Http::Http(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_, int port_) : BaseTCP(manager_, loop_, port_, "Http", port_ == XAPIAND_HTTP_SERVERPORT ? 10 : 1, CONN_TCP_NODELAY | CONN_TCP_DEFER_ACCEPT) { local_node.http_port = port; L_OBJ(this, "CREATED CONFIGURATION FOR HTTP"); } Http::~Http() { L_OBJ(this, "DELETED CONFIGURATION FOR HTTP"); } std::string Http::getDescription() const noexcept { return "TCP:" + std::to_string(port) + " (" + description + ")"; } <commit_msg>HTTP protocol and version in description<commit_after>/* * Copyright (C) 2015 deipi.com LLC and contributors. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "http.h" #include "manager.h" #include <assert.h> Http::Http(const std::shared_ptr<XapiandManager>& manager_, ev::loop_ref *loop_, int port_) : BaseTCP(manager_, loop_, port_, "HTTP", port_ == XAPIAND_HTTP_SERVERPORT ? 10 : 1, CONN_TCP_NODELAY | CONN_TCP_DEFER_ACCEPT) { local_node.http_port = port; L_OBJ(this, "CREATED CONFIGURATION FOR HTTP"); } Http::~Http() { L_OBJ(this, "DELETED CONFIGURATION FOR HTTP"); } std::string Http::getDescription() const noexcept { return "TCP:" + std::to_string(port) + " (" + description + " v1.1)"; } <|endoftext|>
<commit_before>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include <iostream> #include <fstream> #include "LinuxUtils.h" #include "Utils.h" #include "PrintVar.h" #include "Capture.h" #include "Callstack.h" #include "SamplingProfiler.h" #include "EventBuffer.h" #include "Capture.h" #include "ScopeTimer.h" #include "OrbitProcess.h" #include "OrbitModule.h" #include "ConnectionManager.h" #include "TcpClient.h" #include "EventBuffer.h" #include "EventTracer.h" #if __linux__ #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <linux/types.h> #include <linux/perf_event.h> #include <asm/unistd.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <string.h> #include <iomanip> #include <signal.h> #include <sys/wait.h> #include <sstream> #include <string> #include <cstdlib> #include <memory> #include <cxxabi.h> #endif //----------------------------------------------------------------------------- LinuxPerf::LinuxPerf( uint32_t a_PID, uint32_t a_Freq ) : m_PID(a_PID) , m_Frequency(a_Freq) { m_OutputFile = "/tmp/perf.data"; m_ReportFile = Replace(m_OutputFile, ".data", ".txt"); } //----------------------------------------------------------------------------- void LinuxPerf::Start() { #if __linux__ m_IsRunning = true; std::string path = ws2s(Path::GetBasePath()); pid_t PID = fork(); if(PID == 0) { execl ( "/usr/bin/perf" , "/usr/bin/perf" , "record" , "-k", "monotonic" , "-F", Format("%u", m_Frequency).c_str() , "-p", Format("%u", m_PID).c_str() , "-g" , "-o", m_OutputFile.c_str(), (const char*)nullptr); exit(1); } else { m_ForkedPID = PID; PRINT_VAR(m_ForkedPID); } #endif } //----------------------------------------------------------------------------- void LinuxPerf::Stop() { #if __linux__ if( m_ForkedPID != 0 ) { kill(m_ForkedPID, 15); int status = 0; waitpid(m_ForkedPID, &status, 0); } m_IsRunning = false; //m_Thread = std::make_shared<std::thread>([this]{ std::string cmd = Format("perf script -i %s > %s", m_OutputFile.c_str(), m_ReportFile.c_str()); PRINT_VAR(cmd); LinuxUtils::ExecuteCommand(cmd.c_str()); if( ConnectionManager::Get().IsRemote() ) { std::ifstream t(m_ReportFile); std::stringstream buffer; buffer << t.rdbuf(); std::string perfData = buffer.str(); GTcpServer->Send(Msg_RemotePerf, (void*)perfData.data(), perfData.size()); } //else { LoadPerfData(m_ReportFile); } // }); // m_Thread->detach(); #endif } //----------------------------------------------------------------------------- bool ParseStackLine( const std::string& a_Line, uint64_t& o_Address, std::string& o_Name, std::string& o_Module ) { // Module std::size_t moduleBegin = a_Line.find_last_of("("); if( moduleBegin == std::string::npos ) return false; o_Module = Replace(a_Line.substr(moduleBegin+1), ")", ""); // Function name std::string line = LTrim(a_Line.substr(0, moduleBegin)); std::size_t nameBegin = line.find_first_of(" "); if( nameBegin == std::string::npos ) return false; o_Name = line.substr(nameBegin); // Address std::string address = line.substr(0, nameBegin); o_Address = std::stoull(address, nullptr, 16); return true; } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( const std::string& a_FileName ) { SCOPE_TIMER_LOG(L"LoadPerfData"); std::ifstream inFile(a_FileName); if( inFile.fail() ) { PRINT_VAR("Could not open input file"); PRINT_VAR(a_FileName); return; } LoadPerfData(inFile); inFile.close(); } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( std::istream& a_Stream ) { std::string header; uint32_t tid = 0; uint64_t time = 0; uint64_t numCallstacks = 0; CallStack CS; for (std::string line; std::getline(a_Stream, line); ) { bool isHeader = !line.empty() && !StartsWith(line, "\t"); bool isStackLine = !isHeader && !line.empty(); bool isEndBlock = !isStackLine && line.empty() && !header.empty(); if(isHeader) { header = line; auto tokens = Tokenize(line); time = tokens.size() > 2 ? GetMicros(tokens[2])*1000 : 0; tid = tokens.size() > 1 ? atoi(tokens[1].c_str()) : 0; } else if(isStackLine) { std::string module; std::string function; uint64_t address; if( !ParseStackLine( line, address, function, module ) ) { PRINT_VAR("ParseStackLine error"); PRINT_VAR(line); continue; } std::wstring moduleName = ToLower(Path::GetFileName(s2ws(module))); std::shared_ptr<Module> moduleFromName = Capture::GTargetProcess->GetModuleFromName( moduleName ); // Debug - Temporary if( Contains(function, "Renderer::render") ) { PRINT_VAR(function); PRINT_VAR(moduleName); PRINT_VAR(address); } if( moduleFromName ) { uint64_t new_address = moduleFromName->ValidateAddress(address); // Debug - Temporary if( Contains(function, "Renderer::render") ) { std::cout << std::hex << address << " -> " << std::hex << new_address << std::endl; } address = new_address; } else { // Debug - Temporary if( Contains(function, "Renderer::render") ) { PRINT_VAR("could not validate address"); PRINT_VAR(moduleName); } } CS.m_Data.push_back(address); if( Capture::GTargetProcess && !Capture::GTargetProcess->HasSymbol(address)) { auto symbol = std::make_shared<LinuxSymbol>(); symbol->m_Name = function; symbol->m_Module = module; Capture::GTargetProcess->AddSymbol( address, symbol ); } } else if(isEndBlock) { if( CS.m_Data.size() ) { CS.m_Depth = CS.m_Data.size(); CS.m_ThreadId = tid; Capture::GSamplingProfiler->AddCallStack( CS ); GEventTracer.GetEventBuffer().AddCallstackEvent( time, CS ); ++numCallstacks; } CS.m_Data.clear(); header = ""; time = 0; tid = 0; } } PRINT_VAR(numCallstacks); PRINT_FUNC; }<commit_msg>Fix build.<commit_after>//----------------------------------- // Copyright Pierric Gimmig 2013-2017 //----------------------------------- #include <iostream> #include <fstream> #include "LinuxUtils.h" #include "Utils.h" #include "PrintVar.h" #include "Capture.h" #include "Callstack.h" #include "SamplingProfiler.h" #include "EventBuffer.h" #include "Capture.h" #include "ScopeTimer.h" #include "OrbitProcess.h" #include "OrbitModule.h" #include "ConnectionManager.h" #include "TcpServer.h" #include "EventBuffer.h" #include "EventTracer.h" #if __linux__ #include <unistd.h> #include <sys/types.h> #include <sys/syscall.h> #include <linux/types.h> #include <linux/perf_event.h> #include <asm/unistd.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/stat.h> #include <string.h> #include <iomanip> #include <signal.h> #include <sys/wait.h> #include <sstream> #include <string> #include <cstdlib> #include <memory> #include <cxxabi.h> #endif //----------------------------------------------------------------------------- LinuxPerf::LinuxPerf( uint32_t a_PID, uint32_t a_Freq ) : m_PID(a_PID) , m_Frequency(a_Freq) { m_OutputFile = "/tmp/perf.data"; m_ReportFile = Replace(m_OutputFile, ".data", ".txt"); } //----------------------------------------------------------------------------- void LinuxPerf::Start() { #if __linux__ m_IsRunning = true; std::string path = ws2s(Path::GetBasePath()); pid_t PID = fork(); if(PID == 0) { execl ( "/usr/bin/perf" , "/usr/bin/perf" , "record" , "-k", "monotonic" , "-F", Format("%u", m_Frequency).c_str() , "-p", Format("%u", m_PID).c_str() , "-g" , "-o", m_OutputFile.c_str(), (const char*)nullptr); exit(1); } else { m_ForkedPID = PID; PRINT_VAR(m_ForkedPID); } #endif } //----------------------------------------------------------------------------- void LinuxPerf::Stop() { #if __linux__ if( m_ForkedPID != 0 ) { kill(m_ForkedPID, 15); int status = 0; waitpid(m_ForkedPID, &status, 0); } m_IsRunning = false; //m_Thread = std::make_shared<std::thread>([this]{ std::string cmd = Format("perf script -i %s > %s", m_OutputFile.c_str(), m_ReportFile.c_str()); PRINT_VAR(cmd); LinuxUtils::ExecuteCommand(cmd.c_str()); if( ConnectionManager::Get().IsRemote() ) { std::ifstream t(m_ReportFile); std::stringstream buffer; buffer << t.rdbuf(); std::string perfData = buffer.str(); GTcpServer->Send(Msg_RemotePerf, (void*)perfData.data(), perfData.size()); } //else { LoadPerfData(m_ReportFile); } // }); // m_Thread->detach(); #endif } //----------------------------------------------------------------------------- bool ParseStackLine( const std::string& a_Line, uint64_t& o_Address, std::string& o_Name, std::string& o_Module ) { // Module std::size_t moduleBegin = a_Line.find_last_of("("); if( moduleBegin == std::string::npos ) return false; o_Module = Replace(a_Line.substr(moduleBegin+1), ")", ""); // Function name std::string line = LTrim(a_Line.substr(0, moduleBegin)); std::size_t nameBegin = line.find_first_of(" "); if( nameBegin == std::string::npos ) return false; o_Name = line.substr(nameBegin); // Address std::string address = line.substr(0, nameBegin); o_Address = std::stoull(address, nullptr, 16); return true; } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( const std::string& a_FileName ) { SCOPE_TIMER_LOG(L"LoadPerfData"); std::ifstream inFile(a_FileName); if( inFile.fail() ) { PRINT_VAR("Could not open input file"); PRINT_VAR(a_FileName); return; } LoadPerfData(inFile); inFile.close(); } //----------------------------------------------------------------------------- void LinuxPerf::LoadPerfData( std::istream& a_Stream ) { std::string header; uint32_t tid = 0; uint64_t time = 0; uint64_t numCallstacks = 0; CallStack CS; for (std::string line; std::getline(a_Stream, line); ) { bool isHeader = !line.empty() && !StartsWith(line, "\t"); bool isStackLine = !isHeader && !line.empty(); bool isEndBlock = !isStackLine && line.empty() && !header.empty(); if(isHeader) { header = line; auto tokens = Tokenize(line); time = tokens.size() > 2 ? GetMicros(tokens[2])*1000 : 0; tid = tokens.size() > 1 ? atoi(tokens[1].c_str()) : 0; } else if(isStackLine) { std::string module; std::string function; uint64_t address; if( !ParseStackLine( line, address, function, module ) ) { PRINT_VAR("ParseStackLine error"); PRINT_VAR(line); continue; } std::wstring moduleName = ToLower(Path::GetFileName(s2ws(module))); std::shared_ptr<Module> moduleFromName = Capture::GTargetProcess->GetModuleFromName( moduleName ); // Debug - Temporary if( Contains(function, "Renderer::render") ) { PRINT_VAR(function); PRINT_VAR(moduleName); PRINT_VAR(address); } if( moduleFromName ) { uint64_t new_address = moduleFromName->ValidateAddress(address); // Debug - Temporary if( Contains(function, "Renderer::render") ) { std::cout << std::hex << address << " -> " << std::hex << new_address << std::endl; } address = new_address; } else { // Debug - Temporary if( Contains(function, "Renderer::render") ) { PRINT_VAR("could not validate address"); PRINT_VAR(moduleName); } } CS.m_Data.push_back(address); if( Capture::GTargetProcess && !Capture::GTargetProcess->HasSymbol(address)) { auto symbol = std::make_shared<LinuxSymbol>(); symbol->m_Name = function; symbol->m_Module = module; Capture::GTargetProcess->AddSymbol( address, symbol ); } } else if(isEndBlock) { if( CS.m_Data.size() ) { CS.m_Depth = CS.m_Data.size(); CS.m_ThreadId = tid; Capture::GSamplingProfiler->AddCallStack( CS ); GEventTracer.GetEventBuffer().AddCallstackEvent( time, CS ); ++numCallstacks; } CS.m_Data.clear(); header = ""; time = 0; tid = 0; } } PRINT_VAR(numCallstacks); PRINT_FUNC; }<|endoftext|>
<commit_before> #include "PN532_HSU.h" #include "PN532_debug.h" PN532_HSU::PN532_HSU(HardwareSerial &serial) { _serial = &serial; command = 0; } void PN532_HSU::begin() { _serial->begin(115200); } void PN532_HSU::wakeup() { _serial->write(0x55); _serial->write(0x55); _serial->write(0); _serial->write(0); _serial->write(0); /** dump serial buffer */ if(_serial->available()){ DMSG("Dump serial buffer: "); } while(_serial->available()){ uint8_t ret = _serial->read(); DMSG_HEX(ret); } } int8_t PN532_HSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) { /** dump serial buffer */ if(_serial->available()){ DMSG("Dump serial buffer: "); } while(_serial->available()){ uint8_t ret = _serial->read(); DMSG_HEX(ret); } command = header[0]; _serial->write(PN532_PREAMBLE); _serial->write(PN532_STARTCODE1); _serial->write(PN532_STARTCODE2); uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA _serial->write(length); _serial->write(~length + 1); // checksum of length _serial->write(PN532_HOSTTOPN532); uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA DMSG("\nWrite: "); _serial->write(header, hlen); for (uint8_t i = 0; i < hlen; i++) { sum += header[i]; DMSG_HEX(header[i]); } _serial->write(body, blen); for (uint8_t i = 0; i < blen; i++) { sum += body[i]; DMSG_HEX(body[i]); } uint8_t checksum = ~sum + 1; // checksum of TFI + DATA _serial->write(checksum); _serial->write(PN532_POSTAMBLE); return readAckFrame(); } int16_t PN532_HSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) { uint8_t tmp[3]; DMSG("\nRead: "); /** Frame Preamble and Start Code */ if(receive(tmp, 3, timeout)<=0){ return PN532_TIMEOUT; } if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){ DMSG("Preamble error"); return PN532_INVALID_FRAME; } /** receive length and check */ uint8_t length[2]; if(receive(length, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( 0 != (uint8_t)(length[0] + length[1]) ){ DMSG("Length error"); return PN532_INVALID_FRAME; } length[0] -= 2; if( length[0] > len){ return PN532_NO_SPACE; } /** receive command byte */ uint8_t cmd = command + 1; // response command if(receive(tmp, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){ DMSG("Command error"); return PN532_INVALID_FRAME; } if(receive(buf, length[0], timeout) != length[0]){ return PN532_TIMEOUT; } uint8_t sum = PN532_PN532TOHOST + cmd; for(uint8_t i=0; i<length[0]; i++){ sum += buf[i]; } /** checksum and postamble */ if(receive(tmp, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( 0 != (uint8_t)(sum + tmp[0]) || 0 != tmp[1] ){ DMSG("Checksum error"); return PN532_INVALID_FRAME; } return length[0]; } int8_t PN532_HSU::readAckFrame() { const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0}; uint8_t ackBuf[sizeof(PN532_ACK)]; DMSG("\nAck: "); if( receive(ackBuf, sizeof(PN532_ACK), PN532_ACK_WAIT_TIME) <= 0 ){ DMSG("Timeout\n"); return PN532_TIMEOUT; } if( memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)) ){ DMSG("Invalid\n"); return PN532_INVALID_ACK; } return 0; } /** @brief receive data . @param buf --> return value buffer. len --> length expect to receive. timeout --> time of reveiving @retval number of received bytes, 0 means no data received. */ int8_t PN532_HSU::receive(uint8_t *buf, int len, uint16_t timeout) { int read_bytes = 0; int ret; unsigned long start_millis; while (read_bytes < len) { start_millis = millis(); do { ret = _serial->read(); if (ret >= 0) { break; } } while((timeout == 0) || ((millis()- start_millis ) < timeout)); if (ret < 0) { if(read_bytes){ return read_bytes; }else{ return PN532_TIMEOUT; } } buf[read_bytes] = (uint8_t)ret; DMSG_HEX(ret); read_bytes++; } return read_bytes; } <commit_msg>maybe give some time for Android to response? this modification makes P2P working on Nexus 5 Android 5.1.<commit_after> #include "PN532_HSU.h" #include "PN532_debug.h" PN532_HSU::PN532_HSU(HardwareSerial &serial) { _serial = &serial; command = 0; } void PN532_HSU::begin() { _serial->begin(115200); } void PN532_HSU::wakeup() { _serial->write(0x55); _serial->write(0x55); _serial->write(0); _serial->write(0); _serial->write(0); /** dump serial buffer */ if(_serial->available()){ DMSG("Dump serial buffer: "); } while(_serial->available()){ uint8_t ret = _serial->read(); DMSG_HEX(ret); } } int8_t PN532_HSU::writeCommand(const uint8_t *header, uint8_t hlen, const uint8_t *body, uint8_t blen) { /** dump serial buffer */ if(_serial->available()){ DMSG("Dump serial buffer: "); } while(_serial->available()){ uint8_t ret = _serial->read(); DMSG_HEX(ret); } command = header[0]; _serial->write(PN532_PREAMBLE); _serial->write(PN532_STARTCODE1); _serial->write(PN532_STARTCODE2); uint8_t length = hlen + blen + 1; // length of data field: TFI + DATA _serial->write(length); _serial->write(~length + 1); // checksum of length _serial->write(PN532_HOSTTOPN532); uint8_t sum = PN532_HOSTTOPN532; // sum of TFI + DATA DMSG("\nWrite: "); _serial->write(header, hlen); for (uint8_t i = 0; i < hlen; i++) { sum += header[i]; DMSG_HEX(header[i]); } _serial->write(body, blen); for (uint8_t i = 0; i < blen; i++) { sum += body[i]; DMSG_HEX(body[i]); } uint8_t checksum = ~sum + 1; // checksum of TFI + DATA _serial->write(checksum); _serial->write(PN532_POSTAMBLE); return readAckFrame(); } int16_t PN532_HSU::readResponse(uint8_t buf[], uint8_t len, uint16_t timeout) { uint8_t tmp[3]; delay(100); DMSG("\nRead: "); /** Frame Preamble and Start Code */ if(receive(tmp, 3, timeout)<=0){ return PN532_TIMEOUT; } if(0 != tmp[0] || 0!= tmp[1] || 0xFF != tmp[2]){ DMSG("Preamble error"); return PN532_INVALID_FRAME; } /** receive length and check */ uint8_t length[2]; if(receive(length, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( 0 != (uint8_t)(length[0] + length[1]) ){ DMSG("Length error"); return PN532_INVALID_FRAME; } length[0] -= 2; if( length[0] > len){ return PN532_NO_SPACE; } /** receive command byte */ uint8_t cmd = command + 1; // response command if(receive(tmp, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( PN532_PN532TOHOST != tmp[0] || cmd != tmp[1]){ DMSG("Command error"); return PN532_INVALID_FRAME; } if(receive(buf, length[0], timeout) != length[0]){ return PN532_TIMEOUT; } uint8_t sum = PN532_PN532TOHOST + cmd; for(uint8_t i=0; i<length[0]; i++){ sum += buf[i]; } /** checksum and postamble */ if(receive(tmp, 2, timeout) <= 0){ return PN532_TIMEOUT; } if( 0 != (uint8_t)(sum + tmp[0]) || 0 != tmp[1] ){ DMSG("Checksum error"); return PN532_INVALID_FRAME; } return length[0]; } int8_t PN532_HSU::readAckFrame() { const uint8_t PN532_ACK[] = {0, 0, 0xFF, 0, 0xFF, 0}; uint8_t ackBuf[sizeof(PN532_ACK)]; delay(100); DMSG("\nAck: "); if( receive(ackBuf, sizeof(PN532_ACK), PN532_ACK_WAIT_TIME) <= 0 ){ DMSG("Timeout\n"); return PN532_TIMEOUT; } if( memcmp(ackBuf, PN532_ACK, sizeof(PN532_ACK)) ){ DMSG("Invalid\n"); return PN532_INVALID_ACK; } return 0; } /** @brief receive data . @param buf --> return value buffer. len --> length expect to receive. timeout --> time of reveiving @retval number of received bytes, 0 means no data received. */ int8_t PN532_HSU::receive(uint8_t *buf, int len, uint16_t timeout) { int read_bytes = 0; int ret; unsigned long start_millis; while (read_bytes < len) { start_millis = millis(); do { ret = _serial->read(); if (ret >= 0) { break; } delay(10); } while((timeout == 0) || ((millis()- start_millis ) < timeout)); if (ret < 0) { if(read_bytes){ return read_bytes; }else{ return PN532_TIMEOUT; } } buf[read_bytes] = (uint8_t)ret; DMSG_HEX(ret); read_bytes++; } return read_bytes; } <|endoftext|>
<commit_before>/* * SSL/TLS configuration. * * author: Max Kellermann <mk@cm4all.com> */ #include "ssl_factory.hxx" #include "ssl_config.hxx" #include "ssl_domain.hxx" #include "util/Error.hxx" #include <inline/compiler.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> struct ssl_cert_key { X509 *cert; EVP_PKEY *key; ssl_cert_key():cert(nullptr), key(nullptr) {} ssl_cert_key(X509 *_cert, EVP_PKEY *_key) :cert(_cert), key(_key) {} ssl_cert_key(ssl_cert_key &&other) :cert(other.cert), key(other.key) { other.cert = nullptr; other.key = nullptr; } ~ssl_cert_key() { if (cert != nullptr) X509_free(cert); if (key != nullptr) EVP_PKEY_free(key); } ssl_cert_key &operator=(ssl_cert_key &&other) { std::swap(cert, other.cert); std::swap(key, other.key); return *this; } bool Load(const ssl_cert_key_config &config, Error &error); }; struct ssl_factory { SSL_CTX *const ssl_ctx; std::vector<ssl_cert_key> cert_key; const bool server; ssl_factory(SSL_CTX *_ssl_ctx, bool _server) :ssl_ctx(_ssl_ctx), server(_server) {} ~ssl_factory() { SSL_CTX_free(ssl_ctx); } bool EnableSNI(Error &error); SSL *Make(); unsigned Flush(long tm); }; static int verify_callback(int ok, gcc_unused X509_STORE_CTX *ctx) { return ok; } static BIO * bio_open_file(const char *path, Error &error) { BIO *bio = BIO_new_file(path, "r"); if (bio == nullptr) error.Format(ssl_domain, "Failed to open file %s", path); return bio; } static EVP_PKEY * read_key_file(const char *path, Error &error) { BIO *bio = bio_open_file(path, error); if (bio == nullptr) return nullptr; EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr); BIO_free(bio); if (key == nullptr) error.Format(ssl_domain, "Failed to load key file %s", path); return key; } static X509 * read_cert_file(const char *path, Error &error) { BIO *bio = bio_open_file(path, error); if (bio == nullptr) return nullptr; X509 *cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); BIO_free(bio); if (cert == nullptr) error.Format(ssl_domain, "Failed to load certificate file %s", path); return cert; } /** * Are both public keys equal? */ gcc_pure static bool MatchModulus(EVP_PKEY *key1, EVP_PKEY *key2) { assert(key1 != nullptr); assert(key2 != nullptr); if (key1->type != key2->type) return false; switch (key1->type) { case EVP_PKEY_RSA: return BN_cmp(key1->pkey.rsa->n, key2->pkey.rsa->n) == 0; case EVP_PKEY_DSA: return BN_cmp(key1->pkey.dsa->pub_key, key2->pkey.dsa->pub_key) == 0; default: return false; } } /** * Does the certificate belong to the given key? */ gcc_pure static bool MatchModulus(X509 *cert, EVP_PKEY *key) { assert(cert != nullptr); assert(key != nullptr); EVP_PKEY *public_key = X509_get_pubkey(cert); if (public_key == nullptr) return false; const bool result = MatchModulus(public_key, key); EVP_PKEY_free(public_key); return result; } bool ssl_cert_key::Load(const ssl_cert_key_config &config, Error &error) { assert(key == nullptr); assert(cert == nullptr); key = read_key_file(config.key_file.c_str(), error); if (key == nullptr) return false; cert = read_cert_file(config.cert_file.c_str(), error); if (cert == nullptr) return false; if (!MatchModulus(cert, key)) { error.Format(ssl_domain, "Key '%s' does not match certificate '%s'", config.key_file.c_str(), config.cert_file.c_str()); return false; } return true; } static bool load_certs_keys(ssl_factory &factory, const ssl_config &config, Error &error) { factory.cert_key.reserve(config.cert_key.size()); for (const auto &c : config.cert_key) { ssl_cert_key ck; if (!ck.Load(c, error)) return false; factory.cert_key.emplace_back(std::move(ck)); } return true; } static bool apply_server_config(SSL_CTX *ssl_ctx, const ssl_config &config, Error &error) { assert(!config.cert_key.empty()); ERR_clear_error(); if (SSL_CTX_use_RSAPrivateKey_file(ssl_ctx, config.cert_key[0].key_file.c_str(), SSL_FILETYPE_PEM) != 1) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "Failed to load key file %s", config.cert_key[0].key_file.c_str()); return false; } if (SSL_CTX_use_certificate_chain_file(ssl_ctx, config.cert_key[0].cert_file.c_str()) != 1) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "Failed to load certificate file %s", config.cert_key[0].cert_file.c_str()); return false; } if (!config.ca_cert_file.empty()) { if (SSL_CTX_load_verify_locations(ssl_ctx, config.ca_cert_file.c_str(), nullptr) != 1) { error.Format(ssl_domain, "Failed to load CA certificate file %s", config.ca_cert_file.c_str()); return false; } /* send all certificates from this file to the client (list of acceptable CA certificates) */ STACK_OF(X509_NAME) *list = SSL_load_client_CA_file(config.ca_cert_file.c_str()); if (list == nullptr) { error.Format(ssl_domain, "Failed to load CA certificate list from file %s", config.ca_cert_file.c_str()); return false; } SSL_CTX_set_client_CA_list(ssl_ctx, list); } if (config.verify != ssl_verify::NO) { /* enable client certificates */ int mode = SSL_VERIFY_PEER; if (config.verify == ssl_verify::YES) mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; SSL_CTX_set_verify(ssl_ctx, mode, verify_callback); } return true; } static bool match_cn(X509_NAME *subject, const char *host_name, size_t hn_length) { char common_name[256]; if (X509_NAME_get_text_by_NID(subject, NID_commonName, common_name, sizeof(common_name)) < 0) return false; if (strcmp(host_name, common_name) == 0) return true; if (common_name[0] == '*' && common_name[1] == '.' && common_name[2] != 0) { const size_t cn_length = strlen(common_name); if (hn_length >= cn_length && /* match only one segment (no dots) */ memchr(host_name, '.', hn_length - cn_length + 1) == nullptr && memcmp(host_name + hn_length - cn_length + 1, common_name + 1, cn_length - 1) == 0) return true; } return false; } static bool use_cert_key(SSL *ssl, const ssl_cert_key &ck) { return SSL_use_certificate(ssl, ck.cert) == 1 && SSL_use_PrivateKey(ssl, ck.key) == 1; } static int ssl_servername_callback(SSL *ssl, gcc_unused int *al, const ssl_factory &factory) { const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (host_name == nullptr) return SSL_TLSEXT_ERR_OK; const size_t length = strlen(host_name); /* find the first certificate that matches */ for (const auto &ck : factory.cert_key) { X509_NAME *subject = X509_get_subject_name(ck.cert); if (subject != nullptr && match_cn(subject, host_name, length)) { /* found it - now use it */ use_cert_key(ssl, ck); break; } } return SSL_TLSEXT_ERR_OK; } inline bool ssl_factory::EnableSNI(Error &error) { if (!SSL_CTX_set_tlsext_servername_callback(ssl_ctx, ssl_servername_callback) || !SSL_CTX_set_tlsext_servername_arg(ssl_ctx, this)) { error.Format(ssl_domain, "SSL_CTX_set_tlsext_servername_callback() failed"); return false; } return true; } inline SSL * ssl_factory::Make() { SSL *ssl = SSL_new(ssl_ctx); if (ssl == nullptr) return nullptr; if (server) SSL_set_accept_state(ssl); else SSL_set_connect_state(ssl); return ssl; } inline unsigned ssl_factory::Flush(long tm) { unsigned before = SSL_CTX_sess_number(ssl_ctx); SSL_CTX_flush_sessions(ssl_ctx, tm); unsigned after = SSL_CTX_sess_number(ssl_ctx); return after < before ? before - after : 0; } /** * Enable Elliptic curve Diffie-Hellman (ECDH) for perfect forward * secrecy. By default, it OpenSSL disables it. */ static bool enable_ecdh(SSL_CTX *ssl_ctx, Error &error) { /* OpenSSL 1.0.2 will allow this instead: SSL_CTX_set_ecdh_auto(ssl_ctx, 1) */ EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (ecdh == nullptr) { error.Set(ssl_domain, "EC_KEY_new_by_curve_name() failed"); return nullptr; } bool success = SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh) == 1; EC_KEY_free(ecdh); if (!success) error.Set(ssl_domain, "SSL_CTX_set_tmp_ecdh() failed"); return success; } struct ssl_factory * ssl_factory_new(const ssl_config &config, bool server, Error &error) { assert(!config.cert_key.empty() || !server); ERR_clear_error(); /* don't be fooled - we want TLS, not SSL - but TLSv1_method() will only allow TLSv1.0 and will refuse TLSv1.1 and TLSv1.2; only SSLv23_method() supports all (future) TLS protocol versions, even if we don't want any SSL at all */ auto method = server ? SSLv23_server_method() : SSLv23_client_method(); SSL_CTX *ssl_ctx = SSL_CTX_new(method); if (ssl_ctx == nullptr) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "SSL_CTX_new() failed"); return nullptr; } long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER; #ifdef SSL_MODE_RELEASE_BUFFERS /* requires libssl 1.0.0 */ mode |= SSL_MODE_RELEASE_BUFFERS; #endif /* without this flag, OpenSSL attempts to verify the whole local certificate chain for each connection, which is a waste of CPU time */ mode |= SSL_MODE_NO_AUTO_CHAIN; SSL_CTX_set_mode(ssl_ctx, mode); if (server && !enable_ecdh(ssl_ctx, error)) { SSL_CTX_free(ssl_ctx); return nullptr; } /* disable protocols that are known to be insecure */ SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3); /* disable weak ciphers */ SSL_CTX_set_cipher_list(ssl_ctx, "DEFAULT:!EXPORT:!LOW"); ssl_factory *factory = new ssl_factory(ssl_ctx, server); if (server) { if (!apply_server_config(ssl_ctx, config, error) || !load_certs_keys(*factory, config, error)) { delete factory; return nullptr; } } else { assert(config.cert_key.empty()); assert(config.ca_cert_file.empty()); assert(config.verify == ssl_verify::NO); } if (factory->cert_key.size() > 1 && !factory->EnableSNI(error)) { delete factory; return nullptr; } return factory; } void ssl_factory_free(struct ssl_factory *factory) { delete factory; } SSL * ssl_factory_make(ssl_factory &factory) { return factory.Make(); } unsigned ssl_factory_flush(struct ssl_factory &factory, long tm) { return factory.Flush(tm); } <commit_msg>ssl_factory: move code to CreateBasicSslCtx()<commit_after>/* * SSL/TLS configuration. * * author: Max Kellermann <mk@cm4all.com> */ #include "ssl_factory.hxx" #include "ssl_config.hxx" #include "ssl_domain.hxx" #include "util/Error.hxx" #include <inline/compiler.h> #include <openssl/ssl.h> #include <openssl/err.h> #include <assert.h> struct ssl_cert_key { X509 *cert; EVP_PKEY *key; ssl_cert_key():cert(nullptr), key(nullptr) {} ssl_cert_key(X509 *_cert, EVP_PKEY *_key) :cert(_cert), key(_key) {} ssl_cert_key(ssl_cert_key &&other) :cert(other.cert), key(other.key) { other.cert = nullptr; other.key = nullptr; } ~ssl_cert_key() { if (cert != nullptr) X509_free(cert); if (key != nullptr) EVP_PKEY_free(key); } ssl_cert_key &operator=(ssl_cert_key &&other) { std::swap(cert, other.cert); std::swap(key, other.key); return *this; } bool Load(const ssl_cert_key_config &config, Error &error); }; struct ssl_factory { SSL_CTX *const ssl_ctx; std::vector<ssl_cert_key> cert_key; const bool server; ssl_factory(SSL_CTX *_ssl_ctx, bool _server) :ssl_ctx(_ssl_ctx), server(_server) {} ~ssl_factory() { SSL_CTX_free(ssl_ctx); } bool EnableSNI(Error &error); SSL *Make(); unsigned Flush(long tm); }; static int verify_callback(int ok, gcc_unused X509_STORE_CTX *ctx) { return ok; } static BIO * bio_open_file(const char *path, Error &error) { BIO *bio = BIO_new_file(path, "r"); if (bio == nullptr) error.Format(ssl_domain, "Failed to open file %s", path); return bio; } static EVP_PKEY * read_key_file(const char *path, Error &error) { BIO *bio = bio_open_file(path, error); if (bio == nullptr) return nullptr; EVP_PKEY *key = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr); BIO_free(bio); if (key == nullptr) error.Format(ssl_domain, "Failed to load key file %s", path); return key; } static X509 * read_cert_file(const char *path, Error &error) { BIO *bio = bio_open_file(path, error); if (bio == nullptr) return nullptr; X509 *cert = PEM_read_bio_X509(bio, nullptr, nullptr, nullptr); BIO_free(bio); if (cert == nullptr) error.Format(ssl_domain, "Failed to load certificate file %s", path); return cert; } /** * Are both public keys equal? */ gcc_pure static bool MatchModulus(EVP_PKEY *key1, EVP_PKEY *key2) { assert(key1 != nullptr); assert(key2 != nullptr); if (key1->type != key2->type) return false; switch (key1->type) { case EVP_PKEY_RSA: return BN_cmp(key1->pkey.rsa->n, key2->pkey.rsa->n) == 0; case EVP_PKEY_DSA: return BN_cmp(key1->pkey.dsa->pub_key, key2->pkey.dsa->pub_key) == 0; default: return false; } } /** * Does the certificate belong to the given key? */ gcc_pure static bool MatchModulus(X509 *cert, EVP_PKEY *key) { assert(cert != nullptr); assert(key != nullptr); EVP_PKEY *public_key = X509_get_pubkey(cert); if (public_key == nullptr) return false; const bool result = MatchModulus(public_key, key); EVP_PKEY_free(public_key); return result; } bool ssl_cert_key::Load(const ssl_cert_key_config &config, Error &error) { assert(key == nullptr); assert(cert == nullptr); key = read_key_file(config.key_file.c_str(), error); if (key == nullptr) return false; cert = read_cert_file(config.cert_file.c_str(), error); if (cert == nullptr) return false; if (!MatchModulus(cert, key)) { error.Format(ssl_domain, "Key '%s' does not match certificate '%s'", config.key_file.c_str(), config.cert_file.c_str()); return false; } return true; } static bool load_certs_keys(ssl_factory &factory, const ssl_config &config, Error &error) { factory.cert_key.reserve(config.cert_key.size()); for (const auto &c : config.cert_key) { ssl_cert_key ck; if (!ck.Load(c, error)) return false; factory.cert_key.emplace_back(std::move(ck)); } return true; } static bool apply_server_config(SSL_CTX *ssl_ctx, const ssl_config &config, Error &error) { assert(!config.cert_key.empty()); ERR_clear_error(); if (SSL_CTX_use_RSAPrivateKey_file(ssl_ctx, config.cert_key[0].key_file.c_str(), SSL_FILETYPE_PEM) != 1) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "Failed to load key file %s", config.cert_key[0].key_file.c_str()); return false; } if (SSL_CTX_use_certificate_chain_file(ssl_ctx, config.cert_key[0].cert_file.c_str()) != 1) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "Failed to load certificate file %s", config.cert_key[0].cert_file.c_str()); return false; } if (!config.ca_cert_file.empty()) { if (SSL_CTX_load_verify_locations(ssl_ctx, config.ca_cert_file.c_str(), nullptr) != 1) { error.Format(ssl_domain, "Failed to load CA certificate file %s", config.ca_cert_file.c_str()); return false; } /* send all certificates from this file to the client (list of acceptable CA certificates) */ STACK_OF(X509_NAME) *list = SSL_load_client_CA_file(config.ca_cert_file.c_str()); if (list == nullptr) { error.Format(ssl_domain, "Failed to load CA certificate list from file %s", config.ca_cert_file.c_str()); return false; } SSL_CTX_set_client_CA_list(ssl_ctx, list); } if (config.verify != ssl_verify::NO) { /* enable client certificates */ int mode = SSL_VERIFY_PEER; if (config.verify == ssl_verify::YES) mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; SSL_CTX_set_verify(ssl_ctx, mode, verify_callback); } return true; } static bool match_cn(X509_NAME *subject, const char *host_name, size_t hn_length) { char common_name[256]; if (X509_NAME_get_text_by_NID(subject, NID_commonName, common_name, sizeof(common_name)) < 0) return false; if (strcmp(host_name, common_name) == 0) return true; if (common_name[0] == '*' && common_name[1] == '.' && common_name[2] != 0) { const size_t cn_length = strlen(common_name); if (hn_length >= cn_length && /* match only one segment (no dots) */ memchr(host_name, '.', hn_length - cn_length + 1) == nullptr && memcmp(host_name + hn_length - cn_length + 1, common_name + 1, cn_length - 1) == 0) return true; } return false; } static bool use_cert_key(SSL *ssl, const ssl_cert_key &ck) { return SSL_use_certificate(ssl, ck.cert) == 1 && SSL_use_PrivateKey(ssl, ck.key) == 1; } static int ssl_servername_callback(SSL *ssl, gcc_unused int *al, const ssl_factory &factory) { const char *host_name = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); if (host_name == nullptr) return SSL_TLSEXT_ERR_OK; const size_t length = strlen(host_name); /* find the first certificate that matches */ for (const auto &ck : factory.cert_key) { X509_NAME *subject = X509_get_subject_name(ck.cert); if (subject != nullptr && match_cn(subject, host_name, length)) { /* found it - now use it */ use_cert_key(ssl, ck); break; } } return SSL_TLSEXT_ERR_OK; } inline bool ssl_factory::EnableSNI(Error &error) { if (!SSL_CTX_set_tlsext_servername_callback(ssl_ctx, ssl_servername_callback) || !SSL_CTX_set_tlsext_servername_arg(ssl_ctx, this)) { error.Format(ssl_domain, "SSL_CTX_set_tlsext_servername_callback() failed"); return false; } return true; } inline SSL * ssl_factory::Make() { SSL *ssl = SSL_new(ssl_ctx); if (ssl == nullptr) return nullptr; if (server) SSL_set_accept_state(ssl); else SSL_set_connect_state(ssl); return ssl; } inline unsigned ssl_factory::Flush(long tm) { unsigned before = SSL_CTX_sess_number(ssl_ctx); SSL_CTX_flush_sessions(ssl_ctx, tm); unsigned after = SSL_CTX_sess_number(ssl_ctx); return after < before ? before - after : 0; } /** * Enable Elliptic curve Diffie-Hellman (ECDH) for perfect forward * secrecy. By default, it OpenSSL disables it. */ static bool enable_ecdh(SSL_CTX *ssl_ctx, Error &error) { /* OpenSSL 1.0.2 will allow this instead: SSL_CTX_set_ecdh_auto(ssl_ctx, 1) */ EC_KEY *ecdh = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1); if (ecdh == nullptr) { error.Set(ssl_domain, "EC_KEY_new_by_curve_name() failed"); return nullptr; } bool success = SSL_CTX_set_tmp_ecdh(ssl_ctx, ecdh) == 1; EC_KEY_free(ecdh); if (!success) error.Set(ssl_domain, "SSL_CTX_set_tmp_ecdh() failed"); return success; } static bool SetupBasicSslCtx(SSL_CTX *ssl_ctx, bool server, Error &error) { long mode = SSL_MODE_ENABLE_PARTIAL_WRITE | SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER; #ifdef SSL_MODE_RELEASE_BUFFERS /* requires libssl 1.0.0 */ mode |= SSL_MODE_RELEASE_BUFFERS; #endif /* without this flag, OpenSSL attempts to verify the whole local certificate chain for each connection, which is a waste of CPU time */ mode |= SSL_MODE_NO_AUTO_CHAIN; SSL_CTX_set_mode(ssl_ctx, mode); if (server && !enable_ecdh(ssl_ctx, error)) return false; /* disable protocols that are known to be insecure */ SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3); /* disable weak ciphers */ SSL_CTX_set_cipher_list(ssl_ctx, "DEFAULT:!EXPORT:!LOW"); return true; } static SSL_CTX * CreateBasicSslCtx(bool server, Error &error) { ERR_clear_error(); /* don't be fooled - we want TLS, not SSL - but TLSv1_method() will only allow TLSv1.0 and will refuse TLSv1.1 and TLSv1.2; only SSLv23_method() supports all (future) TLS protocol versions, even if we don't want any SSL at all */ auto method = server ? SSLv23_server_method() : SSLv23_client_method(); SSL_CTX *ssl_ctx = SSL_CTX_new(method); if (ssl_ctx == nullptr) { ERR_print_errors_fp(stderr); error.Format(ssl_domain, "SSL_CTX_new() failed"); return nullptr; } if (!SetupBasicSslCtx(ssl_ctx, server, error)) { SSL_CTX_free(ssl_ctx); return nullptr; } return ssl_ctx; } struct ssl_factory * ssl_factory_new(const ssl_config &config, bool server, Error &error) { assert(!config.cert_key.empty() || !server); SSL_CTX *ssl_ctx = CreateBasicSslCtx(server, error); if (ssl_ctx == nullptr) return nullptr; ssl_factory *factory = new ssl_factory(ssl_ctx, server); if (server) { if (!apply_server_config(ssl_ctx, config, error) || !load_certs_keys(*factory, config, error)) { delete factory; return nullptr; } } else { assert(config.cert_key.empty()); assert(config.ca_cert_file.empty()); assert(config.verify == ssl_verify::NO); } if (factory->cert_key.size() > 1 && !factory->EnableSNI(error)) { delete factory; return nullptr; } return factory; } void ssl_factory_free(struct ssl_factory *factory) { delete factory; } SSL * ssl_factory_make(ssl_factory &factory) { return factory.Make(); } unsigned ssl_factory_flush(struct ssl_factory &factory, long tm) { return factory.Flush(tm); } <|endoftext|>
<commit_before>/* Project: TUC File: syntax_tree.cpp Author: Leonardo Banderali Created: September 6, 2015 Last Modified: November 4, 2015 Description: TUC is a simple, experimental compiler designed for learning and experimenting. It is not intended to have any useful purpose other than being a way to learn how compilers work. Copyright (C) 2015 Leonardo Banderali License: 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. */ // project headers #include "syntax_tree.hpp" #include "compiler_exceptions.hpp" // standard libraries #include <stdexcept> #include <sstream> #include <iostream> //~class implementations~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tuc::SyntaxNode::SyntaxNode(NodeType _type) : syntaxNodeType{_type} {} tuc::SyntaxNode::SyntaxNode(NodeType _type, const TextEntity& _textValue) : syntaxNodeType{_type}, textValue{_textValue} {} /* constructs a node from a syntax token */ tuc::SyntaxNode::SyntaxNode(const Token& _token) : textValue{_token.text()} { switch (_token.type()) { case TokenType::TYPE: syntaxNodeType = NodeType::TYPE; break; case TokenType::HASTYPE: syntaxNodeType = NodeType::HASTYPE; break; case TokenType::ASSIGN: syntaxNodeType = NodeType::ASSIGN; break; case TokeType::MAPTO: syntaxNodeType = NodeType::MAPTO; break; case TokenType::ADD: syntaxNodeType = NodeType::ADD; break; case TokenType::SUBTRACT: syntaxNodeType = NodeType::SUBTRACT; break; case TokenType::MULTIPLY: syntaxNodeType = NodeType::MULTIPLY; break; case TokenType::DIVIDE: syntaxNodeType = NodeType::DIVIDE; break; case TokenType::INTEGER: syntaxNodeType = NodeType::INTEGER; break; case TokenType::SEMICOL: syntaxNodeType = NodeType::SEMICOL; break; case TokenType::IDENTIFIER: syntaxNodeType = NodeType::IDENTIFIER; break; default: syntaxNodeType = NodeType::UNKNOWN; } } tuc::SyntaxNode* tuc::SyntaxNode::parent() noexcept { return parentNode; } /* returns child with index `i` */ tuc::SyntaxNode* tuc::SyntaxNode::child(int i) noexcept { return children[i].get(); } int tuc::SyntaxNode::child_count() const noexcept { return children.size(); } void tuc::SyntaxNode::append_child(NodeType _type, const TextEntity& _textValue) { children.push_back(std::make_unique<SyntaxNode>(_type, _textValue)); } void tuc::SyntaxNode::append_child(const Token& _token) { children.push_back(std::make_unique<SyntaxNode>(_token)); } /* appends an already existing (allocated) child; since this node must "own" the child, move semantics *must* be used to transfer ownership. */ void tuc::SyntaxNode::append_child(std::unique_ptr<SyntaxNode>&& c) noexcept { children.push_back(std::move(c)); } tuc::SyntaxNode::NodeType tuc::SyntaxNode::type() const noexcept { return syntaxNodeType; } bool tuc::SyntaxNode::is_operator() const noexcept { return syntaxNodeType == NodeType::ADD || syntaxNodeType == NodeType::SUBTRACT || syntaxNodeType == NodeType::MULTIPLY || syntaxNodeType == NodeType::DIVIDE; } std::string tuc::SyntaxNode::value() const noexcept { return textValue.text(); } int tuc::SyntaxNode::position() const noexcept { return textValue.position(); } tuc::TextEntity tuc::SyntaxNode::text() const noexcept { return textValue; } //~function implementations~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* generate a syntax tree from a list of tokens */ std::tuple<std::unique_ptr<tuc::SyntaxNode>, tuc::SymbolTable> tuc::gen_syntax_tree(const std::vector<tuc::Token>& tokenList) { auto treeRoot = std::make_unique<tuc::SyntaxNode>(tuc::SyntaxNode::NodeType::PROGRAM); auto symTable = SymbolTable{}; auto rpnExpr = std::vector<tuc::Token>{}; auto opStack = std::vector<tuc::Token>{}; /*########################################################################################################## ### To parse mathematical expressions, first use a variation of Dijkstra's shunting yard algorithm to ## ### transform the expression into Reverse Polish Notation (RPN). Once transformed, the expression can be ## ### read into the syntax tree. ## ##########################################################################################################*/ for (const auto token: tokenList) { if (token.is_operator() /*|| token.type() == tuc::TokenType::IDENTIFIER || token.type() == tuc::TokenType::HASTYPE*/) { while(!opStack.empty() && opStack.back().is_operator() && ( (token.fixity() == Associativity::LEFT && token.precedence() <= opStack.back().precedence()) || (token.fixity() == Associativity::RIGHT && token.precedence() < opStack.back().precedence()) )) { rpnExpr.push_back(opStack.back()); opStack.pop_back(); } opStack.push_back(token); } else if (token.type() == tuc::TokenType::IDENTIFIER) { auto symIterator = symTable.find(token.lexeme()); if (symIterator != symTable.end()) { // test if symbol is defined in the symbol table // treat symbol as an operator while(!opStack.empty() && opStack.back().is_operator() && ( (token.fixity() == Associativity::LEFT && token.precedence() <= opStack.back().precedence()) || (token.fixity() == Associativity::RIGHT && token.precedence() < opStack.back().precedence()) )) { rpnExpr.push_back(opStack.back()); opStack.pop_back(); } opStack.push_back(token); } else { throw CompilerException::UnknownSymbol{token.text()}; } } else if (token.type() == tuc::TokenType::INTEGER) { rpnExpr.push_back(token); } else if (token.type() == tuc::TokenType::LPAREN) { opStack.push_back(token); } else if (token.type() == tuc::TokenType::RPAREN) { auto t = opStack.back(); while(t.type() != tuc::TokenType::LPAREN) { rpnExpr.push_back(t); opStack.pop_back(); t = opStack.back(); } } else if (token.type() == tuc::TokenType::SEMICOL) { while (!opStack.empty()) { rpnExpr.push_back(opStack.back()); opStack.pop_back(); } auto nodeStack = std::vector<std::unique_ptr<tuc::SyntaxNode>>{}; for (auto t : rpnExpr) { auto node = std::make_unique<tuc::SyntaxNode>(t); if (node->is_operator()) { auto secondVal = std::move(nodeStack.back()); // using `std::move()` causes `.back()` to exist nodeStack.pop_back(); // also note that node come out in reverse order auto firstVal = std::move(nodeStack.back()); nodeStack.pop_back(); node->append_child(std::move(firstVal)); node->append_child(std::move(secondVal)); nodeStack.push_back(std::move(node)); } else if (t.type() == tuc::TokenType::INTEGER) { nodeStack.push_back(std::move(node)); } } treeRoot->append_child(std::move(nodeStack.back())); rpnExpr.clear(); } } return std::make_tuple(std::move(treeRoot), symTable); } <commit_msg>Remove transformation to RPN from praser.<commit_after>/* Project: TUC File: syntax_tree.cpp Author: Leonardo Banderali Created: September 6, 2015 Last Modified: November 4, 2015 Description: TUC is a simple, experimental compiler designed for learning and experimenting. It is not intended to have any useful purpose other than being a way to learn how compilers work. Copyright (C) 2015 Leonardo Banderali License: 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. */ // project headers #include "syntax_tree.hpp" #include "compiler_exceptions.hpp" // standard libraries #include <stdexcept> #include <sstream> #include <iostream> //~class implementations~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ tuc::SyntaxNode::SyntaxNode(NodeType _type) : syntaxNodeType{_type} {} tuc::SyntaxNode::SyntaxNode(NodeType _type, const TextEntity& _textValue) : syntaxNodeType{_type}, textValue{_textValue} {} /* constructs a node from a syntax token */ tuc::SyntaxNode::SyntaxNode(const Token& _token) : textValue{_token.text()} { switch (_token.type()) { case TokenType::TYPE: syntaxNodeType = NodeType::TYPE; break; case TokenType::HASTYPE: syntaxNodeType = NodeType::HASTYPE; break; case TokenType::ASSIGN: syntaxNodeType = NodeType::ASSIGN; break; case TokenType::MAPTO: syntaxNodeType = NodeType::MAPTO; break; case TokenType::ADD: syntaxNodeType = NodeType::ADD; break; case TokenType::SUBTRACT: syntaxNodeType = NodeType::SUBTRACT; break; case TokenType::MULTIPLY: syntaxNodeType = NodeType::MULTIPLY; break; case TokenType::DIVIDE: syntaxNodeType = NodeType::DIVIDE; break; case TokenType::INTEGER: syntaxNodeType = NodeType::INTEGER; break; case TokenType::SEMICOL: syntaxNodeType = NodeType::SEMICOL; break; case TokenType::IDENTIFIER: syntaxNodeType = NodeType::IDENTIFIER; break; default: syntaxNodeType = NodeType::UNKNOWN; } } tuc::SyntaxNode* tuc::SyntaxNode::parent() noexcept { return parentNode; } /* returns child with index `i` */ tuc::SyntaxNode* tuc::SyntaxNode::child(int i) noexcept { return children[i].get(); } int tuc::SyntaxNode::child_count() const noexcept { return children.size(); } void tuc::SyntaxNode::append_child(NodeType _type, const TextEntity& _textValue) { children.push_back(std::make_unique<SyntaxNode>(_type, _textValue)); } void tuc::SyntaxNode::append_child(const Token& _token) { children.push_back(std::make_unique<SyntaxNode>(_token)); } /* appends an already existing (allocated) child; since this node must "own" the child, move semantics *must* be used to transfer ownership. */ void tuc::SyntaxNode::append_child(std::unique_ptr<SyntaxNode>&& c) noexcept { children.push_back(std::move(c)); } tuc::SyntaxNode::NodeType tuc::SyntaxNode::type() const noexcept { return syntaxNodeType; } bool tuc::SyntaxNode::is_operator() const noexcept { return syntaxNodeType == NodeType::ADD || syntaxNodeType == NodeType::SUBTRACT || syntaxNodeType == NodeType::MULTIPLY || syntaxNodeType == NodeType::DIVIDE; } std::string tuc::SyntaxNode::value() const noexcept { return textValue.text(); } int tuc::SyntaxNode::position() const noexcept { return textValue.position(); } tuc::TextEntity tuc::SyntaxNode::text() const noexcept { return textValue; } //~function implementations~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ /* generate a syntax tree from a list of tokens */ std::tuple<std::unique_ptr<tuc::SyntaxNode>, tuc::SymbolTable> tuc::gen_syntax_tree(const std::vector<tuc::Token>& tokenList) { auto treeRoot = std::make_unique<tuc::SyntaxNode>(tuc::SyntaxNode::NodeType::PROGRAM); auto symTable = SymbolTable{}; auto nodeStack = std::vector<std::unique_ptr<tuc::SyntaxNode>>{}; auto opStack = std::vector<tuc::Token>{}; /*########################################################################################################## ### To parse expressions, use a variation of Dijkstra's shunting yard algorithm. Instead of generating a ## ### Reverse Polish Notation (RPN) expression, create syntax trees in equivalent to the expression and ## ### add it to the main syntax tree at the end. ## ##########################################################################################################*/ for (const auto token: tokenList) { if (token.is_operator() /*|| token.type() == tuc::TokenType::IDENTIFIER || token.type() == tuc::TokenType::HASTYPE*/) { while(!opStack.empty() && opStack.back().is_operator() && ( (token.fixity() == Associativity::LEFT && token.precedence() <= opStack.back().precedence()) || (token.fixity() == Associativity::RIGHT && token.precedence() < opStack.back().precedence()) )) { auto op = std::make_unique<tuc::SyntaxNode>(opStack.back()); auto n2 = std::move(nodeStack.back()); nodeStack.pop_back(); auto n1 = std::move(nodeStack.back()); nodeStack.pop_back(); op->append_child(std::move(n1)); op->append_child(std::move(n2)); opStack.pop_back(); nodeStack.push_back(std::move(op)); } opStack.push_back(token); } else if (token.type() == tuc::TokenType::IDENTIFIER) { auto symIterator = symTable.find(token.lexeme()); if (symIterator != symTable.end()) { // test if symbol is defined in the symbol table // treat symbol as an operator while(!opStack.empty() && opStack.back().is_operator() && ( (token.fixity() == Associativity::LEFT && token.precedence() <= opStack.back().precedence()) || (token.fixity() == Associativity::RIGHT && token.precedence() < opStack.back().precedence()) )) { auto op = std::make_unique<tuc::SyntaxNode>(opStack.back()); auto n2 = std::move(nodeStack.back()); nodeStack.pop_back(); auto n1 = std::move(nodeStack.back()); nodeStack.pop_back(); op->append_child(std::move(n1)); op->append_child(std::move(n2)); opStack.pop_back(); nodeStack.push_back(std::move(op)); } opStack.push_back(token); } else { throw CompilerException::UnknownSymbol{token.text()}; } } else if (token.type() == tuc::TokenType::INTEGER) { nodeStack.push_back(std::make_unique<tuc::SyntaxNode>(token)); } else if (token.type() == tuc::TokenType::LPAREN) { opStack.push_back(token); } else if (token.type() == tuc::TokenType::RPAREN) { auto t = opStack.back(); while(t.type() != tuc::TokenType::LPAREN) { auto op = std::make_unique<tuc::SyntaxNode>(opStack.back()); auto n2 = std::move(nodeStack.back()); nodeStack.pop_back(); auto n1 = std::move(nodeStack.back()); nodeStack.pop_back(); op->append_child(std::move(n1)); op->append_child(std::move(n2)); nodeStack.push_back(std::move(op)); opStack.pop_back(); t = opStack.back(); } opStack.pop_back(); } else if (token.type() == tuc::TokenType::SEMICOL) { while (!opStack.empty()) { auto op = std::make_unique<tuc::SyntaxNode>(opStack.back()); auto n2 = std::move(nodeStack.back()); nodeStack.pop_back(); auto n1 = std::move(nodeStack.back()); nodeStack.pop_back(); op->append_child(std::move(n1)); op->append_child(std::move(n2)); nodeStack.push_back(std::move(op)); opStack.pop_back(); } treeRoot->append_child(std::move(nodeStack.back())); nodeStack.clear(); } } return std::make_tuple(std::move(treeRoot), symTable); } <|endoftext|>