hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
517c6767801ca68a9e685f04ffa3c210d0904211
10,321
cpp
C++
vm/capi/string.cpp
bruce/rubinius
44d3bdd0d988a17de1fe446bd29d2e9dede65f45
[ "BSD-3-Clause" ]
1
2017-09-09T21:28:06.000Z
2017-09-09T21:28:06.000Z
vm/capi/string.cpp
bruce/rubinius
44d3bdd0d988a17de1fe446bd29d2e9dede65f45
[ "BSD-3-Clause" ]
null
null
null
vm/capi/string.cpp
bruce/rubinius
44d3bdd0d988a17de1fe446bd29d2e9dede65f45
[ "BSD-3-Clause" ]
null
null
null
#include "builtin/bytearray.hpp" #include "builtin/fixnum.hpp" #include "builtin/integer.hpp" #include "builtin/nativemethod.hpp" #include "builtin/object.hpp" #include "builtin/string.hpp" #include "capi/capi.hpp" #include "capi/ruby.h" #include <cstring> using namespace rubinius; using namespace rubinius::capi; namespace rubinius { namespace capi { String* capi_get_string(NativeMethodEnvironment* env, VALUE str_handle) { if(!env) env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(str_handle); String* string = c_as<String>(handle->object()); return string; } void repin_string(NativeMethodEnvironment* env, String* string, RString* str) { size_t size = string->size(); ByteArray* ba = string->data(); char* ptr = 0; if(ba->pinned_p()) { ptr = reinterpret_cast<char*>(ba->raw_bytes()); } else { ByteArray* new_ba = ByteArray::create_pinned(env->state(), size + 1); std::memcpy(new_ba->raw_bytes(), string->byte_address(), size); string->data(env->state(), new_ba); ptr = reinterpret_cast<char*>(new_ba->raw_bytes()); } ptr[size] = 0; str->dmwmb = str->ptr = ptr; str->aux.capa = str->len = size; } void capi_update_string(NativeMethodEnvironment* env, VALUE str_handle) { if(!env) env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(str_handle); RString* str = handle->as_rstring(env); String* string = c_as<String>(handle->object()); repin_string(env, string, str); } RString* Handle::as_rstring(NativeMethodEnvironment* env) { String* string = c_as<String>(object()); if(type_ != cRString) { string->unshare(env->state()); RString* str = new RString; str->aux.shared = Qfalse; type_ = cRString; as_.rstring = str; } // We always repin because the ByteArray could have changed between // the last time we used this handle and now. repin_string(env, string, as_.rstring); return as_.rstring; } } } extern "C" { struct RString* capi_rstring_struct(VALUE str_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(str_handle); RString* rstring = handle->as_rstring(env); return rstring; } VALUE rb_String(VALUE object_handle) { return rb_convert_type(object_handle, 0, "String", "to_s"); } void rb_str_modify(VALUE self_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* self = capi_get_string(env, self_handle); self->unshare(env->state()); } VALUE rb_str_freeze(VALUE str) { return rb_obj_freeze(str); } VALUE rb_str_append(VALUE self_handle, VALUE other_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* self = capi_get_string(env, self_handle); self->append(env->state(), capi_get_string(env, other_handle)); capi_update_string(env, self_handle); return self_handle; } VALUE rb_str_buf_new(long capacity) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* str = String::create(env->state(), Fixnum::from(capacity)); str->num_bytes(env->state(), Fixnum::from(0)); return env->get_handle(str); } VALUE rb_str_buf_append(VALUE self_handle, VALUE other_handle) { return rb_str_append(self_handle, other_handle); } VALUE rb_str_buf_cat(VALUE self_handle, const char* other, size_t size) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* string = capi_get_string(env, self_handle); string->append(env->state(), other, size); capi_update_string(env, self_handle); return self_handle; } VALUE rb_str_buf_cat2(VALUE self_handle, const char* other) { return rb_str_buf_cat(self_handle, other, std::strlen(other)); } VALUE rb_str_cat(VALUE self_handle, const char* other, size_t length) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* self = capi_get_string(env, self_handle); self->append(env->state(), other, length); capi_update_string(env, self_handle); return self_handle; } VALUE rb_str_cat2(VALUE self_handle, const char* other) { return rb_str_cat(self_handle, other, std::strlen(other)); } int rb_str_cmp(VALUE self_handle, VALUE other_handle) { return NUM2INT(rb_funcall(self_handle, rb_intern("<=>"), 1, other_handle)); } VALUE rb_str_concat(VALUE self_handle, VALUE other_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Object* other = env->get_object(other_handle); /* Could be a character code. Only up to 256 supported. */ if(Fixnum* character = try_as<Fixnum>(other)) { char byte = character->to_uint(); return rb_str_cat(self_handle, &byte, 1); } return rb_str_append(self_handle, other_handle); } VALUE rb_str_dup(VALUE self_handle) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* self = capi_get_string(env, self_handle); return env->get_handle(self->string_dup(env->state())); } VALUE rb_str_intern(VALUE self) { return rb_funcall(self, rb_intern("to_sym"), 0); } VALUE rb_str_new(const char* string, long length) { if(length < 0) rb_raise(rb_eArgError, "invalid string size"); NativeMethodEnvironment* env = NativeMethodEnvironment::get(); return env->get_handle(String::create(env->state(), string, length)); } VALUE rb_str_new2(const char* string) { if(string == NULL) { rb_raise(rb_eArgError, "NULL pointer given"); } return rb_str_new(string, std::strlen(string)); } VALUE rb_str_plus(VALUE self_handle, VALUE other_handle) { return rb_str_append(rb_str_dup(self_handle), other_handle); } VALUE rb_str_resize(VALUE self_handle, size_t len) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* string = capi_get_string(env, self_handle); size_t size = string->size(); if(size != len) { if(size < len) { ByteArray* ba = ByteArray::create_pinned(env->state(), len+1); std::memcpy(ba->raw_bytes(), string->byte_address(), size); string->data(env->state(), ba); } string->byte_address()[len] = 0; string->num_bytes(env->state(), Fixnum::from(len)); string->characters(env->state(), Fixnum::from(len)); string->hash_value(env->state(), reinterpret_cast<Integer*>(RBX_Qnil)); } capi_update_string(env, self_handle); return self_handle; } VALUE rb_str_split(VALUE self_handle, const char* separator) { return rb_funcall(self_handle, rb_intern("split"), 1, rb_str_new2(separator)); } VALUE rb_str_substr(VALUE self_handle, size_t starting_index, size_t length) { return rb_funcall(self_handle, rb_intern("slice"), 2, LONG2NUM(starting_index), LONG2NUM(length) ); } VALUE rb_str_times(VALUE self_handle, VALUE times) { return rb_funcall(self_handle, rb_intern("*"), 1, times); } VALUE rb_str2inum(VALUE self_handle, int base) { return rb_funcall(self_handle, rb_intern("to_i"), 1, INT2NUM(base)); } VALUE rb_str_to_str(VALUE object_handle) { return rb_convert_type(object_handle, 0, "String", "to_str"); } VALUE rb_string_value(VALUE* object_variable) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); if(!kind_of<String>(env->get_object(*object_variable))) { *object_variable = rb_str_to_str(*object_variable); } return *object_variable; } char* rb_string_value_ptr(VALUE* object_variable) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); VALUE str = rb_string_value(object_variable); String* string = c_as<String>(env->get_object(str)); return const_cast<char*>(string->c_str()); } char* rb_string_value_cstr(VALUE* object_variable) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); VALUE str = rb_string_value(object_variable); String* string = capi_get_string(env, str); if(string->size() != strlen(string->c_str())) { rb_raise(rb_eArgError, "string contains NULL byte"); } return const_cast<char*>(string->c_str()); } VALUE rb_tainted_str_new2(const char* string) { if(string == NULL) { rb_raise(rb_eArgError, "NULL pointer given"); } return rb_tainted_str_new(string, std::strlen(string)); } VALUE rb_tainted_str_new(const char* string, long size) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* str = String::create(env->state(), string, size); str->taint(env->state()); return env->get_handle(str); } char* rb_str2cstr(VALUE str_handle, long* len) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); StringValue(str_handle); String* string = capi_get_string(env, str_handle); char *ptr = RSTRING_PTR(str_handle); if(len) { *len = string->size(); } else if(RTEST(ruby_verbose) && string->size() != strlen(ptr)) { rb_warn("string contains \\0 character"); } return ptr; } char* rb_str_ptr(VALUE self) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); Handle* handle = Handle::from(self); RString* rstring = handle->as_rstring(env); return rstring->ptr; } void rb_str_flush(VALUE self) { // Using pinned ByteArray, we don't need this anymore. } void rb_str_update(VALUE self) { // Using pinned ByteArray, we don't need this anymore. } char* rb_str_ptr_readonly(VALUE self) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); RString* rstr = Handle::from(self)->as_rstring(env); return rstr->ptr; } size_t rb_str_len(VALUE self) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* string = capi_get_string(env, self); return string->size(); } void rb_str_set_len(VALUE self, size_t len) { NativeMethodEnvironment* env = NativeMethodEnvironment::get(); String* string = capi_get_string(env, self); if(string->size() > len) { string->byte_address()[len] = 0; string->num_bytes(env->state(), Fixnum::from(len)); } } }
28.829609
83
0.678035
[ "object" ]
517cbaefc4087b9eae310bf786c2e065467d5601
22,689
cpp
C++
src/avatar_locomanipulation/collision_environment/collision_environment.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
5
2020-01-06T11:43:18.000Z
2021-12-14T22:59:09.000Z
src/avatar_locomanipulation/collision_environment/collision_environment.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
null
null
null
src/avatar_locomanipulation/collision_environment/collision_environment.cpp
stevenjj/icra2020locomanipulation
414085b68cc1b3b24f7b920b543bba9d95350c16
[ "MIT" ]
2
2020-09-03T16:08:34.000Z
2022-02-17T11:13:49.000Z
#include <avatar_locomanipulation/collision_environment/collision_environment.h> CollisionEnvironment::CollisionEnvironment(std::shared_ptr<RobotModel> & val){ valkyrie = val; // Prepare valkyrie for appending to appended valkyrie->geomModel.addAllCollisionPairs(); pinocchio::srdf::removeCollisionPairs(valkyrie->model, valkyrie->geomModel, valkyrie->srdf_filename, false); valkyrie->enableUpdateGeomOnKinematicsUpdate(true); valkyrie->updateFullKinematics(valkyrie->q_current); std::cout << "Collision Environment Created" << std::endl; // Indicates if there is an object object_flag = false; // Potential scaling factor eta = 1.0; // Set the object q counter object_q_counter = 0; // Indicates that appended will append a valkyrie model first_time = true; // create an empty RobotModel apended appended = std::shared_ptr<RobotModel> (new RobotModel() ); // append empty appended with valkyrie append_models(); // Builds a map from collision names (i.e. body_0) to frame names (i.e body) map_collision_names_to_frame_names(); // Builds a map from collision body name (i.e. rightPalm_0) to list of valkyrie bodies from which we would want directed vectors generalize_build_self_directed_vectors(); // Builds a map from collision body name (i.e. rightPalm_0) to list of object bodies from which we would want directed vectors generalize_build_object_directed_vectors(); } CollisionEnvironment::~CollisionEnvironment(){ } void CollisionEnvironment::append_models(){ if(first_time){ std::shared_ptr<RobotModel> app(new RobotModel() ); // Append the object onto the robot, and fill appended RobotModel pinocchio::appendModel(appended->model, valkyrie->model, appended->geomModel, valkyrie->geomModel, appended->model.frames.size()-1, pinocchio::SE3::Identity(), app->model, app->geomModel); appended = app; // Like common intialization but for appended objects // Difference is the initialization of geomData appended->common_initialization(true); // Define the appended configuration vector appended->q_current = valkyrie->q_current; // Update the full kinematics appended->enableUpdateGeomOnKinematicsUpdate(true); appended->updateFullKinematics(appended->q_current); first_time = false; } else{ // temporarily holds the original appended->q_current Eigen::VectorXd temp; temp = appended->q_current; // create new temporary appended RobotModel for appendModel output std::shared_ptr<RobotModel> app(new RobotModel() ); // prepare the object for appending object->geomModel.addAllCollisionPairs(); // append the object into appended, such that its parent frame has the parent joint "universe" pinocchio::appendModel(appended->model, object->model, appended->geomModel, object->geomModel, 0, pinocchio::SE3::Identity(), app->model, app->geomModel); // now replace the appended with the appendModel output appended = app; // initialize this, since it does not yet have data, geomData // a correctly sized q_current, etc. appended->common_initialization(true); // Fill the objects config inside of the appended model for(int i=0; i<object->q_current.size(); ++i){ appended->q_current[i] = object->q_current[i]; } // Fill the remainder of the appended with the original q_current int k=0; for(int j=object->q_current.size(); j<appended->q_current.size(); ++j){ appended->q_current[j] = temp[k]; ++k; } // Now that appended->q_current is filled update full kinematics appended->enableUpdateGeomOnKinematicsUpdate(true); appended->updateFullKinematics(appended->q_current); std::cout << "Object appended to appended [RobotModel] in [CollisionEnvironment]" << std::endl; } first_time = false; } void CollisionEnvironment::find_near_points(std::string & interest_link, const std::vector<std::string> & list, std::map<std::string, Eigen::Vector3d> & from_near_points, std::map<std::string, Eigen::Vector3d> & to_near_points){ // first name in the vector is the link to which we want to get near_point pairs std::string to_link_name = interest_link; std::string from_link_name; from_near_points.clear(); to_near_points.clear(); for(int i=0; i<list.size(); ++i){ // iterating thru rest of list, we get pairs with each of the other links from_link_name = list[i]; // loop thru all of the collision pairs for(int j=0; j<appended->geomModel.collisionPairs.size(); ++j){ // grab this collision pair pinocchio::CollisionPair id2 = appended->geomModel.collisionPairs[j]; // check if pair.first and pair.second are our pair if((appended->geomModel.getGeometryName(id2.first) == to_link_name && appended->geomModel.getGeometryName(id2.second) == from_link_name)){ // if this is our pair, computeDistance appended->dresult = pinocchio::computeDistance(appended->geomModel, *(appended->geomData), appended->geomModel.findCollisionPair(id2)); // fill this map with nearest point on from object // (i.e nearest point on link list[i] to link list[0]) from_near_points[from_link_name] = appended->dresult.nearest_points[1]; // fill this map with nearest point on to object // (i.e nearest point on link list[0] to link list[i]) to_near_points[from_link_name] = appended->dresult.nearest_points[0]; } // First if closed // check if pair.second and pair.first are our pair // (note that we do not know a priori which is pair.first and pair.second respectively) else if((appended->geomModel.getGeometryName(id2.first) == from_link_name && appended->geomModel.getGeometryName(id2.second) == to_link_name)){ // if this is our pair, computeDistance appended->dresult = pinocchio::computeDistance(appended->geomModel, *(appended->geomData), appended->geomModel.findCollisionPair(id2)); // fill this map with nearest point on from object // (i.e nearest point on link list[i] to link list[0]) from_near_points[from_link_name] = appended->dresult.nearest_points[0]; // fill this map with nearest point on to object // (i.e nearest point on link list[0] to link list[i]) to_near_points[from_link_name] = appended->dresult.nearest_points[1]; } // else if closed } // Inner for closed (i.e for this pair we have found the collisionpair and filled our map) } // Outer for closed (i.e we have found nearest_point pairs for every link in our input list) } void CollisionEnvironment::build_self_directed_vectors(const std::string & frame_name, Eigen::VectorXd & q_update){ // for clarity on these maps, see control flow in find_self_near_points function std::map<std::string, Eigen::Vector3d> from_near_points, to_near_points; // initialize two iterators to be used in pushing to DirectedVectors struct std::map<std::string, Eigen::Vector3d>::iterator it; Eigen::Vector3d difference; std::string to_link = frame_name + "_0"; // Pinocchio Convention has _0 after collision links // std::cout << "ce1\n"; // std::cout << object_q_counter << std::endl; // std::cout << "appended->model.nq: " << appended->model.nq << std::endl; // Update the robot config for the given step of IK iteration int l=0; for(int j=object_q_counter; j<appended->q_current.size(); ++j){ appended->q_current[j] = q_update[l]; ++l; } // Update full kinematics appended->enableUpdateGeomOnKinematicsUpdate(true); appended->updateFullKinematics(appended->q_current); // fill our two maps find_near_points(to_link, link_to_collision_names.find(to_link)->second, from_near_points, to_near_points); for(it=from_near_points.begin(); it!=from_near_points.end(); ++it){ // If nearest_point[1] = nearest_point[0], then the two links are in collision // and we need a different way to get a dvector if((it->second - to_near_points[it->first]).norm() <= 1e-6){ std::cout << "Collision between " << it->first << " and " << to_link << std::endl; get_dvector_collision_links(it->first, to_link); } // The typical case when two links are not in collision else{ // get the difference between near_points difference = to_near_points[it->first] - it->second; // Fill the dvector and push back dvector.from = collision_to_frame.find(it->first)->second; dvector.to = collision_to_frame.find(to_link)->second; dvector.direction = difference.normalized(); dvector.magnitude = difference.norm(); dvector.using_worldFramePose = false; directed_vectors.push_back(dvector); } } } void CollisionEnvironment::build_point_list_directed_vectors(const std::vector<Eigen::Vector3d> & point_list_in, Eigen::VectorXd & q_update, std::string & frame){ // used to build directed vectors Eigen::Vector3d difference; // Used to hold the current 3d pos of points in and worlFramePose of robotlinks Eigen::Vector3d cur_pos_to, cur_pos_from; // For getting results from getFrameWorldPose Eigen::Quaternion<double> cur_ori; // For sending to getFrameWorldPose std::string frame_name = frame; // For naming the from vectors char myString[2]; directed_vectors.clear(); // Update the robot config for the given step of IK iteration for(int j=object_q_counter; j<appended->q_current.size(); ++j){ appended->q_current[j] = q_update[j]; } // Update full kinematics appended->enableUpdateGeomOnKinematicsUpdate(true); appended->updateFullKinematics(appended->q_current); // we will build the directed vectors from each of the points in the list for(int i=0; i<point_list_in.size(); ++i){ cur_pos_from = point_list_in[i]; sprintf(myString, "%d", i); appended->getFrameWorldPose(frame_name, cur_pos_to, cur_ori); difference = cur_pos_to - cur_pos_from; // Fill the dvector and push_back dvector.from = myString; dvector.to = frame_name; dvector.direction = difference.normalized(); dvector.magnitude = difference.norm(); dvector.using_worldFramePose = false; directed_vectors.push_back(dvector); } } void CollisionEnvironment::build_object_directed_vectors(std::string & frame_name, Eigen::VectorXd & q_update){ // for clarity on these maps, see control flow in find_self_near_points function std::map<std::string, Eigen::Vector3d> from_near_points, to_near_points; // initialize two iterators to be used in pushing to DirectedVectors struct std::map<std::string, Eigen::Vector3d>::iterator it; // used to build directed vectors Eigen::Vector3d difference; // Update the robot config for the given step of IK iteration int o=0; for(int j=object_q_counter; j<appended->q_current.size(); ++j){ appended->q_current[j] = q_update[o]; ++o; } // Update full kinematics appended->enableUpdateGeomOnKinematicsUpdate(true); appended->updateFullKinematics(appended->q_current); // we will build the directed vectors from each of the object links for(int i=0; i<object_links.size(); ++i){ // Notice we reverse to and from near_points, because unlike in the self directed vectors, // we want vectors away from the collision_names[0] find_near_points(object_links[i], link_to_object_collision_names[frame_name], to_near_points, from_near_points); for(it=from_near_points.begin(); it!=from_near_points.end(); ++it){ // If nearest_point[1] = nearest_point[0], then the two links are in collision // and we need a different way to get a dvector if( (it->second - to_near_points[it->first]).norm() <= 1e-6 ){ std::cout << "Collision between " << it->first << " and " << object_links[i] << std::endl; get_dvector_collision_links(object_links[i], it->first); } // end if // The typical case when two links are not in collision else{ difference = to_near_points[it->first] - it->second; // Fill the dvector and push back dvector.from = collision_to_frame[object_links[i]]; dvector.to = collision_to_frame.find(it->first)->second; dvector.direction = difference.normalized(); dvector.magnitude = difference.norm(); dvector.using_worldFramePose = false; directed_vectors.push_back(dvector); } // end else } // end inner for } // end outer for } double CollisionEnvironment::get_collision_potential(){ double Potential, temp; Potential = 0; closest = 0; double safety_dist; temp = directed_vectors[0].magnitude; // We want to find the index of the directed vector with lowest magnitude // Sort thru all of the directed vectors for(int j=1; j<directed_vectors.size(); ++j){ // If in collision, this is the pair we want if(directed_vectors[j].using_worldFramePose){ temp = directed_vectors[j].magnitude; closest = j; break; } // Else if the jth directed vector has magnitude less than temo else if(directed_vectors[j].magnitude < temp){ // The jth directed vector is the closest pair temp = directed_vectors[j].magnitude; closest = j; } } // Set the local safety distance accordingly and output if there is a collision if(directed_vectors[closest].using_worldFramePose){ safety_dist = safety_dist_collision; std::cout << "Collision between these links: (to, from) (" << directed_vectors[closest].to << ", " << directed_vectors[closest].from << ")" << std::endl; } else safety_dist = safety_dist_normal; // Get the potential using the proper safety_distance if(directed_vectors[closest].magnitude < safety_dist){ Potential = (1.0/2.0) * eta * std::pow(( (1/(directed_vectors[closest].magnitude)) - (1/(safety_dist)) ),2); } return Potential; } void CollisionEnvironment::add_new_object(std::shared_ptr<RobotModel> & obj, const Eigen::VectorXd & q_start, std::string & prefix){ // Initialize the RobotModel object = obj; // Set the q_current object->q_current = q_start; // Keep track of nq object_q_counter += q_start.size(); // --------- Fix allowing forwardKinematics on appended // Apply a prefix prefix_ = prefix + "/"; for (pinocchio::JointIndex i = 1; i < object->model.joints.size(); ++i) { object->model.names[i] = prefix_ + object->model.names[i]; } for (pinocchio::FrameIndex i = 0; i < object->model.frames.size(); ++i) { ::pinocchio::Frame& f = object->model.frames[i]; f.name = prefix_ + f.name; } //--------------------- // Update kinematics and geom placements object->enableUpdateGeomOnKinematicsUpdate(true); object->updateFullKinematics(object->q_current); // Tells append_models to add this to end of appended first_time = false; // Appends this to end of appended append_models(); // push back the list of object collision names get_object_links(); // Tells the collision to frame names to look through the object object_flag = true; // Adds this objects collision and frame names to collision_to_frame map_collision_names_to_frame_names(); std::cout << "[RobotModel] Environmental Object Created and appended in [CollisionEnvironment]" << std::endl; } void CollisionEnvironment::set_safety_distance_normal(double safety_dist_normal_in){ safety_dist_normal = safety_dist_normal_in; } void CollisionEnvironment::set_safety_distance_collision(double safety_dist_collision_in){ safety_dist_collision = safety_dist_collision_in; } void CollisionEnvironment::get_dvector_collision_links(const std::string & from_name, const std::string & to_name){ Eigen::Vector3d cur_pos_to, cur_pos_from, difference; Eigen::Quaternion<double> cur_ori; appended->getFrameWorldPose(collision_to_frame.find(to_name)->second, cur_pos_to, cur_ori); appended->getFrameWorldPose(collision_to_frame.find(from_name)->second, cur_pos_from, cur_ori); difference = cur_pos_to - cur_pos_from; dvector.from = collision_to_frame.find(from_name)->second; dvector.to = collision_to_frame.find(to_name)->second; dvector.direction = difference.normalized(); dvector.magnitude = 0.005; dvector.using_worldFramePose = true; directed_vectors.push_back(dvector); } std::vector<std::string> CollisionEnvironment::make_point_collision_list(){ std::vector<std::string> names; names.push_back("torso"); names.push_back("pelvis"); names.push_back("head"); names.push_back("rightPalm"); names.push_back("leftPalm"); names.push_back("rightKneePitch"); names.push_back("leftKneePitch"); names.push_back("rightElbowPitch"); names.push_back("leftElbowPitch"); names.push_back("rightForearmLink"); names.push_back("leftForearmLink"); names.push_back("rightHipUpperLink"); names.push_back("leftHipUpperLink"); return names; } void CollisionEnvironment::map_collision_names_to_frame_names(){ std::string tmp; // if we added an object to the collision environment if(object_flag){ // add the map from collision names to frame names for(int i=0; i<object->geomModel.geometryObjects.size(); ++i){ tmp = object->geomModel.getGeometryName(i); tmp.pop_back(); tmp.pop_back(); collision_to_frame[object->geomModel.getGeometryName(i)] = prefix_ + tmp; } } else{ collision_to_frame["leftElbowNearLink_0"] = "leftElbowPitch"; collision_to_frame["rightElbowNearLink_0"] = "rightElbowPitch"; collision_to_frame["leftKneeNearLink_0"] = "leftKneePitch"; collision_to_frame["rightKneeNearLink_0"] = "rightKneePitch"; collision_to_frame["pelvis_0"] = "pelvis"; collision_to_frame["torso_0"] = "torso"; collision_to_frame["torso_1"] = "torso"; collision_to_frame["torso_2"] = "torso"; collision_to_frame["torso_3"] = "torso"; collision_to_frame["torso_4"] = "torso"; collision_to_frame["rightPalm_0"] = "rightPalm"; collision_to_frame["leftPalm_0"] = "leftPalm"; collision_to_frame["head_0"] = "head"; collision_to_frame["rightHipUpperLink_0"] = "rightHipUpperLink"; collision_to_frame["leftHipUpperLink_0"] = "leftHipUpperLink"; collision_to_frame["rightForearmLink_0"] = "rightForearmLink"; collision_to_frame["leftForearmLink_0"] = "leftForearmLink"; collision_to_frame["rightShoulderRollLink_0"] = "rightShoulderRollLink"; collision_to_frame["leftShoulderRollLink_0"] = "leftShoulderRollLink"; collision_to_frame["rightHipPitchLink_0"] = "rightHipPitchLink"; collision_to_frame["leftHipPitchLink_0"] = "leftHipPitchLink"; collision_to_frame["rightKneePitchLink_0"] = "rightKneePitchLink"; collision_to_frame["leftKneePitchLink_0"] = "leftKneePitchLink"; } } void CollisionEnvironment::get_object_links(){ for(int i=0; i<object->geomModel.geometryObjects.size(); ++i){ object_links.push_back(appended->geomModel.getGeometryName(i)); } } void CollisionEnvironment::generalize_build_self_directed_vectors(){ link_to_collision_names["leftElbowNearLink_0"] = {"rightKneeNearLink_0", "leftKneeNearLink_0", "rightForearmLink_0","rightHipPitchLink_0", "rightHipUpperLink_0", "leftHipPitchLink_0", "leftHipUpperLink_0", "pelvis_0", "torso_0", "torso_1", "torso_2", "torso_3", "torso_4"}; link_to_collision_names["rightPalm_0"] = {"leftPalm_0", "leftElbowNearLink_0", "leftShoulderRollLink_0", "leftForearmLink_0", "rightKneeNearLink_0", "leftKneeNearLink_0", "rightHipPitchLink_0", "rightHipUpperLink_0", "leftHipPitchLink_0", "leftHipUpperLink_0", "rightKneePitchLink_0", "leftKneePitchLink_0", "head_0", "pelvis_0", "torso_0", "torso_1", "torso_2", "torso_3", "torso_4"}; link_to_collision_names["rightElbowNearLink_0"] = {"rightKneeNearLink_0", "leftKneeNearLink_0", "leftForearmLink_0", "rightHipPitchLink_0", "rightHipUpperLink_0", "leftHipPitchLink_0", "leftHipUpperLink_0", "pelvis_0", "torso_0", "torso_1", "torso_2", "torso_3", "torso_4"}; link_to_collision_names["leftKneeNearLink_0"] = {"rightKneeNearLink_0", "rightHipPitchLink_0", "rightHipUpperLink_0", "rightKneePitchLink_0"}; link_to_collision_names["rightKneeNearLink_0"] = {"leftKneeNearLink_0", "leftHipPitchLink_0", "leftHipUpperLink_0", "leftKneePitchLink_0"}; link_to_collision_names["head_0"] = {"torso_0", "torso_1", "torso_2", "torso_3", "torso_4"}; link_to_collision_names["leftPalm_0"] = {"rightPalm_0", "rightElbowNearLink_0", "rightShoulderRollLink_0", "rightForearmLink_0", "rightKneeNearLink_0", "leftKneeNearLink_0", "rightHipPitchLink_0", "rightHipUpperLink_0", "leftHipPitchLink_0", "leftHipUpperLink_0", "rightKneePitchLink_0", "leftKneePitchLink_0", "head_0", "pelvis_0", "torso_0"}; } void CollisionEnvironment::generalize_build_object_directed_vectors(){ link_to_object_collision_names["rightPalm"] = {"rightPalm_0"}; link_to_object_collision_names["leftPalm"] = {"leftPalm_0"}; link_to_object_collision_names["head"] = {"head_0"}; link_to_object_collision_names["rightKneePitch"] = {"rightKneeNearLink_0"}; link_to_object_collision_names["leftKneePitch"] = {"leftKneeNearLink_0"}; link_to_object_collision_names["rightElbowPitch"] = {"rightElbowNearLink_0", "rightForearmLink_0"}; link_to_object_collision_names["leftElbowPitch"] = {"leftElbowNearLink_0", "leftForearmLink_0"}; } // void CollisionEnvironment::compute_collision(Eigen::VectorXd & q, Eigen::VectorXd & obj_config){ // // Define the new appended model and fill it with the current configuration // std::shared_ptr<RobotModel> appended = append_models(); // // Build the appended_config for collision computation // Eigen::VectorXd appended_config(appended->model.nq); // appended_config << q, obj_config; // int j, k; // // Compute all collisions // pinocchio::computeCollisions(appended->model, *appended->data, appended->geomModel, *appended->geomData, appended_config); // // Loop thru results and print them // for(j=0; j< appended->geomModel.collisionPairs.size(); j++) // { // appended->result = (*appended->geomData).collisionResults[j]; // pinocchio::CollisionPair id2 = appended->geomModel.collisionPairs[j]; // appended->result.getContacts(appended->contacts); // if(appended->contacts.size() != 0) // { // for(k=0; k<appended->contacts.size(); k++) // { // std::cout << "Contact Found Between: " << appended->geomModel.getGeometryName(id2.first) << " and " << appended->geomModel.getGeometryName(id2.second) << std::endl; // std::cout << "position: " << appended->contacts[k].pos << std::endl; // std::cout << "-------------------" << std::endl; // } // } // } // }
40.954874
387
0.715281
[ "object", "vector", "model", "3d" ]
517cdb9d1cf1a66f05bce8a8cf1223ca9f018ef4
1,795
cpp
C++
modules/media/test/apps/test_box_art_loader.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
modules/media/test/apps/test_box_art_loader.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
1
2016-01-25T13:03:03.000Z
2016-01-25T13:03:03.000Z
modules/media/test/apps/test_box_art_loader.cpp
LCClyde/nyra
f8280db2633e888ab62e929a2c238a33755ff694
[ "MIT" ]
null
null
null
/* * Copyright (c) 2017 Clyde Stanfield * * 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 <nyra/test/Test.h> #include <nyra/media/BoxArtLoader.h> #include <nyra/core/Path.h> namespace nyra { namespace media { //===========================================================================// TEST(BoxArtLoader, Load) { std::vector<Game> games(2); games[0].boxArtFile = "game 2.png"; games[1].boxArtFile = "game 3.png"; BoxArtLoader loader(games, core::path::join( core::DATA_PATH, "/textures/mtest/")); EXPECT_EQ(nullptr, games[0].sprite.get()); EXPECT_EQ(nullptr, games[1].sprite.get()); loader(); EXPECT_NE(nullptr, games[0].sprite.get()); EXPECT_NE(nullptr, games[1].sprite.get()); } } } NYRA_TEST()
33.240741
79
0.689136
[ "vector" ]
3d629f2835f17c96084228b88217961331ad96b6
4,126
hpp
C++
ThirdParty-mod/java2cpp/org/apache/http/auth/AuthenticationException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/org/apache/http/auth/AuthenticationException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/org/apache/http/auth/AuthenticationException.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: org.apache.http.auth.AuthenticationException ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_DECL #define J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_DECL namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Throwable; } } } namespace j2cpp { namespace org { namespace apache { namespace http { class ProtocolException; } } } } #include <java/lang/String.hpp> #include <java/lang/Throwable.hpp> #include <org/apache/http/ProtocolException.hpp> namespace j2cpp { namespace org { namespace apache { namespace http { namespace auth { class AuthenticationException; class AuthenticationException : public object<AuthenticationException> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) explicit AuthenticationException(jobject jobj) : object<AuthenticationException>(jobj) { } operator local_ref<org::apache::http::ProtocolException>() const; AuthenticationException(); AuthenticationException(local_ref< java::lang::String > const&); AuthenticationException(local_ref< java::lang::String > const&, local_ref< java::lang::Throwable > const&); }; //class AuthenticationException } //namespace auth } //namespace http } //namespace apache } //namespace org } //namespace j2cpp #endif //J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_IMPL #define J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_IMPL namespace j2cpp { org::apache::http::auth::AuthenticationException::operator local_ref<org::apache::http::ProtocolException>() const { return local_ref<org::apache::http::ProtocolException>(get_jobject()); } org::apache::http::auth::AuthenticationException::AuthenticationException() : object<org::apache::http::auth::AuthenticationException>( call_new_object< org::apache::http::auth::AuthenticationException::J2CPP_CLASS_NAME, org::apache::http::auth::AuthenticationException::J2CPP_METHOD_NAME(0), org::apache::http::auth::AuthenticationException::J2CPP_METHOD_SIGNATURE(0) >() ) { } org::apache::http::auth::AuthenticationException::AuthenticationException(local_ref< java::lang::String > const &a0) : object<org::apache::http::auth::AuthenticationException>( call_new_object< org::apache::http::auth::AuthenticationException::J2CPP_CLASS_NAME, org::apache::http::auth::AuthenticationException::J2CPP_METHOD_NAME(1), org::apache::http::auth::AuthenticationException::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } org::apache::http::auth::AuthenticationException::AuthenticationException(local_ref< java::lang::String > const &a0, local_ref< java::lang::Throwable > const &a1) : object<org::apache::http::auth::AuthenticationException>( call_new_object< org::apache::http::auth::AuthenticationException::J2CPP_CLASS_NAME, org::apache::http::auth::AuthenticationException::J2CPP_METHOD_NAME(2), org::apache::http::auth::AuthenticationException::J2CPP_METHOD_SIGNATURE(2) >(a0, a1) ) { } J2CPP_DEFINE_CLASS(org::apache::http::auth::AuthenticationException,"org/apache/http/auth/AuthenticationException") J2CPP_DEFINE_METHOD(org::apache::http::auth::AuthenticationException,0,"<init>","()V") J2CPP_DEFINE_METHOD(org::apache::http::auth::AuthenticationException,1,"<init>","(Ljava/lang/String;)V") J2CPP_DEFINE_METHOD(org::apache::http::auth::AuthenticationException,2,"<init>","(Ljava/lang/String;Ljava/lang/Throwable;)V") } //namespace j2cpp #endif //J2CPP_ORG_APACHE_HTTP_AUTH_AUTHENTICATIONEXCEPTION_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
32.746032
163
0.729278
[ "object" ]
3d651c7f17a700ed05d995c2e4f57374c365c1ac
4,296
cpp
C++
Greedy/water_connection.cpp
krayong/DS---Algo
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
2
2021-01-30T08:50:12.000Z
2021-05-30T19:56:53.000Z
Greedy/water_connection.cpp
krayong/Data-Structures-and-Algorithms
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
null
null
null
Greedy/water_connection.cpp
krayong/Data-Structures-and-Algorithms
5105dab434fa59580b4068e64468a4a37245d763
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std; /************************************************************************************************************* * * Link : https://practice.geeksforgeeks.org/problems/water-connection-problem/1 * Description: Every house in the colony has at most one pipe going into it and at most one pipe going out of it. Tanks and taps are to be installed in a manner such that every house with one outgoing pipe but no incoming pipe gets a tank installed on its roof and every house with only an incoming pipe and no outgoing pipe gets a tap. Find the efficient way for the construction of the network of pipes. Input: The first line contains an integer T denoting the number of test cases. For each test case, the first line contains two integer n & p denoting the number of houses and number of pipes respectively. Next, p lines contain 3 integer inputs a, b & d, d denoting the diameter of the pipe from the house a to house b. Output: For each test case, the output is the number of pairs of tanks and taps installed i.e n followed by n lines that contain three integers: house number of tank, house number of tap and the minimum diameter of pipe between them. Constraints: 1<=T<=50 1<=n<=20 1<=p<=50 1<=a,b<=20 1<=d<=100 Example: Input: 1 9 6 7 4 98 5 9 72 4 6 10 2 8 22 9 7 17 3 1 66 Output: 3 2 8 22 3 1 66 5 6 10 Explanation: Connected components are 3->1, 5->9->7->4->6 and 2->8. Therefore, our answer is 3 followed by 2 8 22, 3 1 66, 5 6 10. * Resources: * https://www.geeksforgeeks.org/water-connection-problem/ * *************************************************************************************************************/ #define si(x) scanf("%d", &x) #define sll(x) scanf("%lld", &x) #define ss(s) getline(cin, s) #define pi(x) printf("%d\n", x) #define pll(x) printf("%lld\n", x) #define ps(s) cout << s << "\n" #define ll long long #define fo(i, k, n) for (ll i = k; i < n; i++) #define rof(i, k, n) for (ll i = k; i >= n; i--) #define deb(x) cout << #x << "=" << x << "\n" #define pb push_back #define mp make_pair #define fi first #define se second #define all(x) x.begin(), x.end() #define clr(x) memset(x, 0, sizeof(x)) #define set(x, i) memset(x, i, sizeof(x)) #define sortall(x) sort(all(x)) #define tr(a, it) for (auto it = a.begin(); it != a.end(); it++) #define present(c, x) (c.find(x) != c.end()) #define cpresent(c, x) (find(all(c), x) != c.end()) typedef pair<int, int> pii; typedef pair<ll, ll> pll; typedef vector<int> vi; typedef vector<ll> vl; typedef vector<string> vs; typedef vector<pii> vpii; typedef vector<pll> vpll; typedef vector<vi> vvi; typedef vector<vl> vvl; int dfs(int idx, int &min_diam, int forward[], int backward[], int diams[]) { if (forward[idx] == 0) // has no outgoing pipe so can give water to the idx return idx; if (diams[idx] < min_diam) min_diam = diams[idx]; return dfs(forward[idx], min_diam, forward, backward, diams); } int main() { ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0); srand(chrono::high_resolution_clock::now().time_since_epoch().count()); int t; si(t); while (t--) { int houses, pipes; si(houses), si(pipes); int forward[houses + 1] = {0}, backward[houses + 1] = {0}, diams[houses + 1] = {0}; fo(i, 0, pipes) { int start, end, diam; si(start), si(end), si(diam); forward[start] = end; backward[end] = start; diams[start] = diam; } vector<pair<int, pii>> result; fo(i, 1, houses + 1) { if (backward[i] == 0 && forward[i] != 0) // no incoming pipe but has outgoing pipe { int min_diam = INT_MAX; int end = dfs(i, min_diam, forward, backward, diams); result.pb(mp(i, mp(end, min_diam))); } } cout << result.size() << "\n"; for (auto ele : result) cout << ele.fi << " " << ele.se.fi << " " << ele.se.se << "\n"; } return 0; }
29.424658
110
0.554236
[ "vector" ]
3d792e4455baba486579381cc7bdcfdfc2e5d831
1,947
hpp
C++
easycl/easysdl.hpp
ichko/gpu_computing
14bb3f1d5963ba73f69179aad9a33221c74ac2db
[ "MIT" ]
null
null
null
easycl/easysdl.hpp
ichko/gpu_computing
14bb3f1d5963ba73f69179aad9a33221c74ac2db
[ "MIT" ]
null
null
null
easycl/easysdl.hpp
ichko/gpu_computing
14bb3f1d5963ba73f69179aad9a33221c74ac2db
[ "MIT" ]
1
2022-01-01T22:19:40.000Z
2022-01-01T22:19:40.000Z
#pragma once #include <time.h> #include <chrono> #include <ctime> #include <SDL.h> #include "canvas.hpp" struct EasySDL : public Canvas { SDL_Renderer *renderer; SDL_Window *window; SDL_Texture *texture; SDL_Event event; float timer; clock_t program_start; float delta_t; clock_t frame_start; int fps; EasySDL(size_t width, size_t height) { program_start = clock(); frame_start = clock(); delta_t = 0.0f; fps = 0; event = SDL_Event(); SDL_Init(SDL_INIT_VIDEO); Canvas::SetSize(width, height); SDL_CreateWindowAndRenderer(int(width), int(height), 0, &window, &renderer); texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_RGBA32, SDL_TEXTUREACCESS_STREAMING, int(width), int(height)); SDL_SetRenderDrawColor(renderer, 0, 0, 0, 0); } bool KeyDown(int key_type) { return event.type == SDL_KEYDOWN && event.key.keysym.sym == key_type; } EasySDL& Render() { SDL_UpdateTexture(texture, NULL, context.screen_buffer, int(context.width * sizeof(Uint32))); SDL_RenderCopy(renderer, texture, NULL, NULL); SDL_RenderPresent(renderer); return *this; } float GetTime() { return (clock() - program_start) / 1000.0f; } EasySDL& SetTitle(std::string title = "") { SDL_SetWindowTitle(window, title.c_str()); return *this; } EasySDL& Tick() { timer = GetTime(); delta_t = (clock() - frame_start) / 1000.0f; frame_start = clock(); fps = int(1000 / (delta_t * 1000)); SDL_PollEvent(&event); return *this; } void Destroy() { Cleanup(); SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_DestroyTexture(texture); SDL_Quit(); } ~EasySDL() { // Destroy(); } };
22.905882
124
0.586543
[ "render" ]
3d8a12adf2c8992c8959c1f119d2378414ee8c52
4,935
cpp
C++
common/src/pcharacter.cpp
ScenarioCPP/scenario
8559e6053e208dd7ddceb2b8374309314e19c946
[ "MIT" ]
null
null
null
common/src/pcharacter.cpp
ScenarioCPP/scenario
8559e6053e208dd7ddceb2b8374309314e19c946
[ "MIT" ]
null
null
null
common/src/pcharacter.cpp
ScenarioCPP/scenario
8559e6053e208dd7ddceb2b8374309314e19c946
[ "MIT" ]
null
null
null
#include <QtMath> #include <QDebug> #include "global_defines.h" #include "pcharacter.h" PCharacter::PCharacter(SpritePtr sprite, ColliderPtr collider, ControllerPtr controller, QObject *parent) : Actor(sprite,parent),m_collider(collider),m_controller(controller) { signal_on_rendor(sprite); sprite->set_type(PLAYER); } void PCharacter::act(qint64 t) { Q_UNUSED(t) /* Because animation is entirely dependent on the player's movement at this point, this is a separate just for the animation to be called after collision between the player and the world. This gives the most accurate animations for what the player is doing movement wise on the screen. */ if (m_controller->btn_left()->active()) { move_left(); } if (m_controller->btn_right()->active()) { move_right(); } if (m_controller->btn_up()->active()) { jump(); m_controller->btn_up()->active(false); } update_position(gravity(), friction()); collide_objects(); if (m_velocity_y < 0) { if (m_direction_x < 0) m_sprite->changeFrameSet("jump-left", "pause"); else m_sprite->changeFrameSet("jump-right", "pause"); } else if (m_direction_x < 0) { if (m_velocity_x < -0.1) m_sprite->changeFrameSet("move-left", "loop", 5); else m_sprite->changeFrameSet("idle-left", "pause"); } else if (m_direction_x > 0) { if (m_velocity_x > 0.1) m_sprite->changeFrameSet("move-right", "loop", 5); else m_sprite->changeFrameSet("idle-right", "pause"); } update_animation(); } void PCharacter::render(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) { //painter->drawPixmap(rect(),*(tilemap()),current_frame_rect()); default_render(painter,option,widget); } void PCharacter::collide_objects() { /* Let's collide with some tiles!!! The side values refer to the tile grid row and column spaces that the object is occupying on each of its sides. For instance bottom refers to the row in the collision map that the bottom of the object occupies. Right refers to the column in the collision map occupied by the right side of the object. Value refers to the value of a collision tile in the map under the specified row and column occupied by the object. */ double bottom, left, right, top, value; /* First we test the top left corner of the object. We get the row and column he occupies in the collision map, then we get the value from the collision map at that row and column. In this case the row is top and the column is left. Then we hand the information to the collider's collide function. */ auto conf = assets(); assert(conf != nullptr); auto collision_map = conf->collision_map(); int cell_size = conf->cell_size(); int columns = conf->columns(); top = floor(get_top() / cell_size); left = floor(get_left() / cell_size); if(top*columns+left>=0 && top*columns+left < collision_map.size()) { value = collision_map.at(static_cast<int>(top * columns + left)); m_collider->collide(value, this, static_cast<int>(left * cell_size), static_cast<int>(top * cell_size), cell_size); } /* We must redefine top since the last collision check because the object may have moved since the last collision check. Also, the reason we check the top corners first is because if the object is moved down while checking the top, he will be moved back up when checking the bottom, and it is better to look like he is standing on the ground than being pushed down through the ground by the ceiling. */ top = floor(get_top() / cell_size); right = floor(get_right() / cell_size); if(top*columns+right >=0 && top*columns+right < collision_map.size()) { value = collision_map.at(static_cast<int>(top * columns + right)); m_collider->collide(value, this, static_cast<int>(right * cell_size), static_cast<int>(top * cell_size), cell_size); } bottom = floor(get_bottom() / cell_size); left = floor(get_left() / cell_size); if(bottom * columns+left >= 0 && bottom*columns+left < collision_map.size()) { value = collision_map.at(static_cast<int>(bottom * columns + left)); m_collider->collide(value, this, static_cast<int>(left * cell_size), static_cast<int>(bottom * cell_size), cell_size); } bottom = floor(get_bottom() / cell_size); right = floor(get_right() / cell_size); if(bottom*columns+right >=0 && bottom*columns+right < collision_map.size()) { value = collision_map.at(static_cast<int>(bottom * columns + right)); m_collider->collide(value, this, static_cast<int>(right * cell_size), static_cast<int>(bottom * cell_size), cell_size); } } void PCharacter::on_key_down_up(QKeyEvent *e) { m_controller->key_down_up(e); }
39.798387
125
0.674164
[ "render", "object" ]
3d8b7e2f1003a524e7a1840834a414b1f4cdb955
3,161
cpp
C++
quantize__dither_quantize.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2015-12-09T20:37:49.000Z
2021-08-10T08:06:29.000Z
quantize__dither_quantize.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
13
2021-09-20T16:25:30.000Z
2022-03-17T04:59:40.000Z
quantize__dither_quantize.cpp
poikilos/golgotha
d3184dea6b061f853423e0666dba23218042e5ba
[ "CC0-1.0" ]
5
2016-01-04T22:54:22.000Z
2021-09-20T16:09:03.000Z
#include "pch.h" /********************************************************************** Golgotha Forever - A portable, free 3D strategy and FPS game. Copyright (C) 1999 Golgotha Forever Developers Sources contained in this distribution were derived from Crack Dot Com's public release of Golgotha which can be found here: http://www.crack.com All changes and new works are licensed under the GPL: 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 For the full license, see COPYING. ***********************************************************************/ #include "image/image.h" #include "error/error.h" #include "memory/malloc.h" #include "image/context.h" #include <memory.h> inline void argb_split(w32 c, int &a, int &r, int &g, int &b) { a=(c&0xff000000)>>24; r=(c&0xff0000)>>16; g=(c&0xff00)>>8; b=(c&0xff)>>0; } inline w32 pack_argb(int a, int r, int g, int b) { return (a<<24) | (r<<16) | (g<<8) | b; } void i4_dither_quantize(i4_image_class * source, i4_image_class * dest) { int w=source->width(), h=source->height(), x,y; I4_ASSERT(source && dest && w==dest->width() && h==dest->height(), "source size !=dest"); int size=(w+1)*(h+1)*4; w32 * er_im=(w32 *)I4_MALLOC(size,""); memset(er_im, 0, size); w32 * cur_er=er_im; i4_draw_context_class context(0,0, w-1, h-1); for (y=0; y<h; y++) { for (x=0; x<w; x++, cur_er++) { w32 c=source->get_pixel(x,y, context); int r,g,b,a, ea,er,eg,eb; argb_split(c, a,r,g,b); argb_split(*cur_er, ea, er, eg,eb); ea-=127; er-=127; eg-=127; eb-=127; a+=ea; if (a<0) { a=0; } if (a>255) { a=255; } r+=er; if (r<0) { r=0; } if (r>255) { r=255; } g+=eg; if (g<0) { g=0; } if (g>255) { g=255; } b+=eb; if (b<0) { b=0; } if (b>255) { b=255; } dest->put_pixel(x,y, pack_argb(a,r,g,b), context); w32 d=dest->get_pixel(x,y, context); // see what the differance is argb_split(d, ea, er, eg, eb); ea-=a; er-=r; eg-=g; eb-=b; cur_er[1]+=pack_argb( (ea/4)+127, (er/4)+127, (eg/4)+127, (eb/4)+127); cur_er[w+1]+=pack_argb( (ea/2)+127, (er/2)+127, (eg/2)+127, (eb/2)+127); cur_er[w+1+1]+=pack_argb( (ea/4)+127, (er/4)+127, (eg/4)+127, (eb/4)+127); } cur_er++; } i4_free(er_im); }
23.242647
91
0.551724
[ "3d" ]
3d91403a38a7a23ebd743b0a717f1decff4dc148
11,276
cpp
C++
lib/Runtime/Debug/DiagStackFrame.cpp
satheeshravi/ChakraCore
3bf47ff12bf80ab06fb7ea6925ec7579985ac1f5
[ "MIT" ]
1
2021-11-07T18:56:21.000Z
2021-11-07T18:56:21.000Z
lib/Runtime/Debug/DiagStackFrame.cpp
MaxMood96/ChakraCore
9d9fea268ce1ae6c00873fd966a6a2be048f3455
[ "MIT" ]
null
null
null
lib/Runtime/Debug/DiagStackFrame.cpp
MaxMood96/ChakraCore
9d9fea268ce1ae6c00873fd966a6a2be048f3455
[ "MIT" ]
1
2021-09-04T23:26:57.000Z
2021-09-04T23:26:57.000Z
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- #include "RuntimeDebugPch.h" #include "Language/JavascriptFunctionArgIndex.h" #include "Language/InterpreterStackFrame.h" namespace Js { DiagStackFrame::DiagStackFrame(int frameIndex) : frameIndex(frameIndex) { Assert(frameIndex >= 0); } // Returns whether or not this frame is on the top of the callstack. bool DiagStackFrame::IsTopFrame() { return this->frameIndex == 0 && GetScriptContext()->GetDebugContext()->GetProbeContainer()->IsPrimaryBrokenToDebuggerContext(); } ScriptFunction* DiagStackFrame::GetScriptFunction() { return ScriptFunction::FromVar(GetJavascriptFunction()); } FunctionBody* DiagStackFrame::GetFunction() { return GetJavascriptFunction()->GetFunctionBody(); } ScriptContext* DiagStackFrame::GetScriptContext() { return GetJavascriptFunction()->GetScriptContext(); } PCWSTR DiagStackFrame::GetDisplayName() { return GetFunction()->GetExternalDisplayName(); } bool DiagStackFrame::IsInterpreterFrame() { return false; } InterpreterStackFrame* DiagStackFrame::AsInterpreterFrame() { AssertMsg(FALSE, "AsInterpreterFrame called for non-interpreter frame."); return nullptr; } ArenaAllocator * DiagStackFrame::GetArena() { Assert(GetScriptContext() != NULL); return GetScriptContext()->GetThreadContext()->GetDebugManager()->GetDiagnosticArena()->Arena(); } FrameDisplay * DiagStackFrame::GetFrameDisplay() { FrameDisplay *display = NULL; Assert(this->GetFunction() != NULL); RegSlot frameDisplayReg = this->GetFunction()->GetFrameDisplayRegister(); if (frameDisplayReg != Js::Constants::NoRegister && frameDisplayReg != 0) { display = (FrameDisplay*)this->GetNonVarRegValue(frameDisplayReg); } else { display = this->GetScriptFunction()->GetEnvironment(); } return display; } Var DiagStackFrame::GetScopeObjectFromFrameDisplay(uint index) { FrameDisplay * display = GetFrameDisplay(); return (display != NULL && display->GetLength() > index) ? display->GetItem(index) : NULL; } Var DiagStackFrame::GetRootObject() { Assert(this->GetFunction()); return this->GetFunction()->LoadRootObject(); } Var DiagStackFrame::GetInnerScopeFromRegSlot(RegSlot location) { return GetNonVarRegValue(location); } DiagInterpreterStackFrame::DiagInterpreterStackFrame(InterpreterStackFrame* frame, int frameIndex) : DiagStackFrame(frameIndex), m_interpreterFrame(frame) { Assert(m_interpreterFrame != NULL); AssertMsg(m_interpreterFrame->GetScriptContext() && m_interpreterFrame->GetScriptContext()->IsScriptContextInDebugMode(), "This only supports interpreter stack frames running in debug mode."); } JavascriptFunction* DiagInterpreterStackFrame::GetJavascriptFunction() { return m_interpreterFrame->GetJavascriptFunction(); } ScriptContext* DiagInterpreterStackFrame::GetScriptContext() { return m_interpreterFrame->GetScriptContext(); } int DiagInterpreterStackFrame::GetByteCodeOffset() { return m_interpreterFrame->GetReader()->GetCurrentOffset(); } // Address on stack that belongs to current frame. // Currently we only use this to determine which of given frames is above/below another one. DWORD_PTR DiagInterpreterStackFrame::GetStackAddress() { return m_interpreterFrame->GetStackAddress(); } bool DiagInterpreterStackFrame::IsInterpreterFrame() { return true; } InterpreterStackFrame* DiagInterpreterStackFrame::AsInterpreterFrame() { return m_interpreterFrame; } Var DiagInterpreterStackFrame::GetRegValue(RegSlot slotId, bool allowTemp) { return m_interpreterFrame->GetReg(slotId); } Var DiagInterpreterStackFrame::GetNonVarRegValue(RegSlot slotId) { return m_interpreterFrame->GetNonVarReg(slotId); } void DiagInterpreterStackFrame::SetRegValue(RegSlot slotId, Var value) { m_interpreterFrame->SetReg(slotId, value); } Var DiagInterpreterStackFrame::GetArgumentsObject() { return m_interpreterFrame->GetArgumentsObject(); } Var DiagInterpreterStackFrame::CreateHeapArguments() { return m_interpreterFrame->CreateHeapArguments(GetScriptContext()); } FrameDisplay * DiagInterpreterStackFrame::GetFrameDisplay() { return m_interpreterFrame->GetFrameDisplayForNestedFunc(); } Var DiagInterpreterStackFrame::GetInnerScopeFromRegSlot(RegSlot location) { return m_interpreterFrame->InnerScopeFromRegSlot(location); } #if ENABLE_NATIVE_CODEGEN DiagNativeStackFrame::DiagNativeStackFrame( ScriptFunction* function, int byteCodeOffset, void* stackAddr, void *codeAddr, int frameIndex) : DiagStackFrame(frameIndex), m_function(function), m_byteCodeOffset(byteCodeOffset), m_stackAddr(stackAddr), m_localVarSlotsOffset(InvalidOffset), m_localVarChangedOffset(InvalidOffset) { Assert(m_stackAddr != NULL); AssertMsg(m_function && m_function->GetScriptContext() && m_function->GetScriptContext()->IsScriptContextInDebugMode(), "This only supports functions in debug mode."); FunctionEntryPointInfo * entryPointInfo = GetFunction()->GetEntryPointFromNativeAddress((DWORD_PTR)codeAddr); if (entryPointInfo) { m_localVarSlotsOffset = entryPointInfo->localVarSlotsOffset; m_localVarChangedOffset = entryPointInfo->localVarChangedOffset; } else { AssertMsg(FALSE, "Failed to get entry point for native address. Most likely the frame is old/gone."); } OUTPUT_TRACE(Js::DebuggerPhase, _u("DiagNativeStackFrame::DiagNativeStackFrame: e.p(addr %p)=%p varOff=%d changedOff=%d\n"), codeAddr, entryPointInfo, m_localVarSlotsOffset, m_localVarChangedOffset); } JavascriptFunction* DiagNativeStackFrame::GetJavascriptFunction() { return m_function; } ScriptContext* DiagNativeStackFrame::GetScriptContext() { return m_function->GetScriptContext(); } int DiagNativeStackFrame::GetByteCodeOffset() { return m_byteCodeOffset; } // Address on stack that belongs to current frame. // Currently we only use this to determine which of given frames is above/below another one. DWORD_PTR DiagNativeStackFrame::GetStackAddress() { return reinterpret_cast<DWORD_PTR>(m_stackAddr); } Var DiagNativeStackFrame::GetRegValue(RegSlot slotId, bool allowTemp) { Js::Var *varPtr = GetSlotOffsetLocation(slotId, allowTemp); return (varPtr != NULL) ? *varPtr : NULL; } Var * DiagNativeStackFrame::GetSlotOffsetLocation(RegSlot slotId, bool allowTemp) { Assert(GetFunction() != NULL); int32 slotOffset; if (GetFunction()->GetSlotOffset(slotId, &slotOffset, allowTemp)) { Assert(m_localVarSlotsOffset != InvalidOffset); slotOffset = m_localVarSlotsOffset + slotOffset; // We will have the var offset only (which is always the Var size. With TypeSpecialization, below will change to accommodate double offset. return (Js::Var *)(((char *)m_stackAddr) + slotOffset); } Assert(false); return NULL; } Var DiagNativeStackFrame::GetNonVarRegValue(RegSlot slotId) { return GetRegValue(slotId); } void DiagNativeStackFrame::SetRegValue(RegSlot slotId, Var value) { Js::Var *varPtr = GetSlotOffsetLocation(slotId); Assert(varPtr != NULL); // First assign the value *varPtr = value; Assert(m_localVarChangedOffset != InvalidOffset); // Now change the bit in the stack which tells that current stack values got changed. char *stackOffset = (((char *)m_stackAddr) + m_localVarChangedOffset); Assert(*stackOffset == 0 || *stackOffset == FunctionBody::LocalsChangeDirtyValue); *stackOffset = FunctionBody::LocalsChangeDirtyValue; } Var DiagNativeStackFrame::GetArgumentsObject() { return (Var)((void **)m_stackAddr)[JavascriptFunctionArgIndex_ArgumentsObject]; } Var DiagNativeStackFrame::CreateHeapArguments() { // We would be creating the arguments object if there is no default arguments object present. Assert(GetArgumentsObject() == NULL); CallInfo const * callInfo = (CallInfo const *)&(((void **)m_stackAddr)[JavascriptFunctionArgIndex_CallInfo]); // At the least we will have 'this' by default. Assert(callInfo->Count > 0); // Get the passed parameter's position (which is starting from 'this') Var * inParams = (Var *)&(((void **)m_stackAddr)[JavascriptFunctionArgIndex_This]); return JavascriptOperators::LoadHeapArguments( m_function, callInfo->Count - 1, &inParams[1], GetScriptContext()->GetLibrary()->GetNull(), (PropertyId*)GetScriptContext()->GetLibrary()->GetNull(), GetScriptContext(), /* formalsAreLetDecls */ false); } #endif DiagRuntimeStackFrame::DiagRuntimeStackFrame(JavascriptFunction* function, PCWSTR displayName, void* stackAddr, int frameIndex): DiagStackFrame(frameIndex), m_function(function), m_displayName(displayName), m_stackAddr(stackAddr) { } JavascriptFunction* DiagRuntimeStackFrame::GetJavascriptFunction() { return m_function; } PCWSTR DiagRuntimeStackFrame::GetDisplayName() { return m_displayName; } DWORD_PTR DiagRuntimeStackFrame::GetStackAddress() { return reinterpret_cast<DWORD_PTR>(m_stackAddr); } int DiagRuntimeStackFrame::GetByteCodeOffset() { return 0; } Var DiagRuntimeStackFrame::GetRegValue(RegSlot slotId, bool allowTemp) { return nullptr; } Var DiagRuntimeStackFrame::GetNonVarRegValue(RegSlot slotId) { return nullptr; } void DiagRuntimeStackFrame::SetRegValue(RegSlot slotId, Var value) { } Var DiagRuntimeStackFrame::GetArgumentsObject() { return nullptr; } Var DiagRuntimeStackFrame::CreateHeapArguments() { return nullptr; } } // namespace Js
31.76338
207
0.647659
[ "object" ]
3d91c38a7af73397e3f5a69b7fc3f25bb839f106
8,330
cc
C++
media/gpu/v4l2/v4l2_device_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/gpu/v4l2/v4l2_device_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/gpu/v4l2/v4l2_device_unittest.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2021-01-05T23:43:46.000Z
2021-01-07T23:36:34.000Z
// Copyright 2018 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 "media/gpu/v4l2/v4l2_device.h" #include <cstring> #include <sstream> #include <vector> #include "media/base/color_plane_layout.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/gfx/native_pixmap_handle.h" namespace { // Composes a v4l2_format of type V4L2_BUF_TYPE_VIDEO_OUTPUT. v4l2_format V4L2FormatVideoOutput(uint32_t width, uint32_t height, uint32_t pixelformat, uint32_t field, uint32_t bytesperline, uint32_t sizeimage) { v4l2_format format; memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT; struct v4l2_pix_format* pix = &format.fmt.pix; pix->width = width; pix->height = height; pix->pixelformat = pixelformat; pix->field = field; pix->bytesperline = bytesperline; pix->sizeimage = sizeimage; return format; } // Composes a v4l2_format of type V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE. // If anything goes wrong, it returns v4l2_format with // pix_mp.pixelformat = 0. v4l2_format V4L2FormatVideoOutputMplane(uint32_t width, uint32_t height, uint32_t pixelformat, uint32_t field, std::vector<uint32_t> bytesperlines, std::vector<uint32_t> sizeimages) { v4l2_format format; memset(&format, 0, sizeof(format)); format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE; struct v4l2_pix_format_mplane* pix_mp = &format.fmt.pix_mp; if (bytesperlines.size() != sizeimages.size() || bytesperlines.size() > static_cast<size_t>(VIDEO_MAX_PLANES)) { // Used to emit test error message. EXPECT_EQ(bytesperlines.size(), sizeimages.size()); EXPECT_LE(bytesperlines.size(), static_cast<size_t>(VIDEO_MAX_PLANES)); return format; } pix_mp->width = width; pix_mp->height = height; pix_mp->pixelformat = pixelformat; pix_mp->field = field; pix_mp->num_planes = bytesperlines.size(); for (size_t i = 0; i < pix_mp->num_planes; ++i) { pix_mp->plane_fmt[i].bytesperline = bytesperlines[i]; pix_mp->plane_fmt[i].sizeimage = sizeimages[i]; } return format; } } // namespace namespace media { // Test V4L2FormatToVideoFrameLayout with NV12 pixelformat, which has one buffer // and two color planes. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutNV12) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutputMplane( 300, 180, V4L2_PIX_FMT_NV12, V4L2_FIELD_ANY, {320}, {86400})); ASSERT_TRUE(layout.has_value()); EXPECT_EQ(PIXEL_FORMAT_NV12, layout->format()); EXPECT_EQ(gfx::Size(300, 180), layout->coded_size()); std::vector<ColorPlaneLayout> expected_planes( {{320, 0u, 86400u}, {320, 57600u, 28800u}}); EXPECT_EQ(expected_planes, layout->planes()); EXPECT_EQ(layout->is_multi_planar(), false); std::ostringstream ostream; ostream << *layout; const std::string kNoModifierStr = std::to_string(gfx::NativePixmapHandle::kNoModifier); EXPECT_EQ( ostream.str(), "VideoFrameLayout(format: PIXEL_FORMAT_NV12, coded_size: 300x180, " "planes (stride, offset, size): [(320, 0, 86400), (320, 57600, 28800)], " "is_multi_planar: 0, buffer_addr_align: 4096, modifier: " + kNoModifierStr + ")"); } // Test V4L2FormatToVideoFrameLayout with NV12M pixelformat, which has two // buffers and two color planes. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutNV12M) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout( V4L2FormatVideoOutputMplane(300, 180, V4L2_PIX_FMT_NV12, V4L2_FIELD_ANY, {320, 320}, {57600, 28800})); ASSERT_TRUE(layout.has_value()); EXPECT_EQ(PIXEL_FORMAT_NV12, layout->format()); EXPECT_EQ(gfx::Size(300, 180), layout->coded_size()); std::vector<ColorPlaneLayout> expected_planes( {{320, 0u, 57600u}, {320, 0u, 28800u}}); EXPECT_EQ(expected_planes, layout->planes()); EXPECT_EQ(layout->is_multi_planar(), true); std::ostringstream ostream; ostream << *layout; const std::string kNoModifierStr = std::to_string(gfx::NativePixmapHandle::kNoModifier); EXPECT_EQ( ostream.str(), "VideoFrameLayout(format: PIXEL_FORMAT_NV12, coded_size: 300x180, " "planes (stride, offset, size): [(320, 0, 57600), (320, 0, 28800)], " "is_multi_planar: 1, buffer_addr_align: 4096, modifier: " + kNoModifierStr + ")"); } // Test V4L2FormatToVideoFrameLayout with YUV420 pixelformat, which has one // buffer and three color planes. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutYUV420) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutputMplane( 300, 180, V4L2_PIX_FMT_YUV420, V4L2_FIELD_ANY, {320}, {86400})); ASSERT_TRUE(layout.has_value()); EXPECT_EQ(PIXEL_FORMAT_I420, layout->format()); EXPECT_EQ(gfx::Size(300, 180), layout->coded_size()); std::vector<ColorPlaneLayout> expected_planes( {{320, 0u, 86400}, {160, 57600u, 14400u}, {160, 72000u, 14400u}}); EXPECT_EQ(expected_planes, layout->planes()); std::ostringstream ostream; ostream << *layout; const std::string kNoModifierStr = std::to_string(gfx::NativePixmapHandle::kNoModifier); EXPECT_EQ(ostream.str(), "VideoFrameLayout(format: PIXEL_FORMAT_I420, coded_size: 300x180, " "planes (stride, offset, size): [(320, 0, 86400), (160, 57600, " "14400), (160, 72000, 14400)], " "is_multi_planar: 0, buffer_addr_align: 4096, modifier: " + kNoModifierStr + ")"); } // Test V4L2FormatToVideoFrameLayout with single planar v4l2_format. // Expect an invalid VideoFrameLayout. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutNoMultiPlanar) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutput( 300, 180, V4L2_PIX_FMT_NV12, V4L2_FIELD_ANY, 320, 86400)); EXPECT_FALSE(layout.has_value()); } // Test V4L2FormatToVideoFrameLayout with unsupported v4l2_format pixelformat, // e.g. V4L2_PIX_FMT_NV16. Expect an invalid VideoFrameLayout. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutUnsupportedPixelformat) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutputMplane( 300, 180, V4L2_PIX_FMT_NV16, V4L2_FIELD_ANY, {320}, {86400})); EXPECT_FALSE(layout.has_value()); } // Test V4L2FormatToVideoFrameLayout with unsupported pixelformat which's // #color planes > #buffers, e.g. V4L2_PIX_FMT_YUV422M. // Expect an invalid VideoFrameLayout. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutUnsupportedStrideCalculation) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutputMplane( 300, 180, V4L2_PIX_FMT_YUV422M, V4L2_FIELD_ANY, {320}, {86400})); EXPECT_FALSE(layout.has_value()); } // Test V4L2FormatToVideoFrameLayout with wrong stride value (expect even). // Expect an invalid VideoFrameLayout. TEST(V4L2DeviceTest, V4L2FormatToVideoFrameLayoutWrongStrideValue) { auto layout = V4L2Device::V4L2FormatToVideoFrameLayout(V4L2FormatVideoOutputMplane( 300, 180, V4L2_PIX_FMT_YUV420, V4L2_FIELD_ANY, {319}, {86400})); EXPECT_FALSE(layout.has_value()); } // Test GetNumPlanesOfV4L2PixFmt. TEST(V4L2DeviceTest, GetNumPlanesOfV4L2PixFmt) { EXPECT_EQ(1u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_NV12)); EXPECT_EQ(1u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_YUV420)); EXPECT_EQ(1u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_YVU420)); EXPECT_EQ(1u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_RGB32)); EXPECT_EQ(2u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_NV12M)); EXPECT_EQ(2u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_MT21C)); EXPECT_EQ(3u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_YUV420M)); EXPECT_EQ(3u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_YVU420M)); EXPECT_EQ(3u, V4L2Device::GetNumPlanesOfV4L2PixFmt(V4L2_PIX_FMT_YUV422M)); } } // namespace media
41.859296
80
0.708163
[ "vector" ]
3d987219d46b72d2e3f51a9e553927ece054b1e5
20,074
cpp
C++
src/lab_m1/tema1/tema1.cpp
whoisann/Shooter-Game
8691354e1d53a4ac9a1ed1149852e19633c600ae
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/lab_m1/tema1/tema1.cpp
whoisann/Shooter-Game
8691354e1d53a4ac9a1ed1149852e19633c600ae
[ "MIT", "BSD-3-Clause" ]
null
null
null
src/lab_m1/tema1/tema1.cpp
whoisann/Shooter-Game
8691354e1d53a4ac9a1ed1149852e19633c600ae
[ "MIT", "BSD-3-Clause" ]
null
null
null
#include "lab_m1/tema1/tema1.h" #include <vector> #include <iostream> #include "lab_m1/tema1/transform2D.h" #include "lab_m1/tema1/object2D.h" using namespace std; using namespace m1; /* * To find out more about `FrameStart`, `Update`, `FrameEnd` * and the order in which they are called, see `world.cpp`. */ Tema1::Tema1() { } Tema1::~Tema1() { } void Tema1::Init() { auto camera = GetSceneCamera(); //camera->SetOrthographic(0, (float)window->GetResolution().x, 0, (float)window->GetResolution().y, 0.01f, 400); camera->SetPosition(glm::vec3(0, 0, 50)); camera->SetRotation(glm::vec3(0, 0, 0)); camera->Update(); GetCameraInput()->SetActive(false); // Rotation variables angle = 0.f; // Initialize tx and ty (the translation steps) translateX = 0; translateY = 0; logicSpace.x = 0; // logic x logicSpace.y = 0; // logic y logicSpace.width = 12.8; // logic width logicSpace.height = 7.2; // logic height corner = glm::vec3(0, 0, 0); length = 0.5f; // initialize obstacles variables for (int i = 0; i < 3; i++) { obstacles[i].obstacleX = 3 * (i + 1); obstacles[i].obstacleY = 4 * i + 1; obstacles[i].obstacleLength = i + 2; } // collision with obstacles colObstacleDown = false; colObstacleUp = false; colObstacleLeft = false; colObstacleRight = false; isCollided = false; Mesh* mc = object2D::CreateChar("mc", corner, length, glm::vec3(0.75, 0.50, 1), true); AddMeshToList(mc); Mesh* map = object2D::CreateRectangle("map", corner, 30 * length, glm::vec3(0.25, 0, 0.50), true); AddMeshToList(map); Mesh* enemy = object2D::CreateEnemy("enemy", corner, length, glm::vec3(0.7, 0.9, 1), true); AddMeshToList(enemy); Mesh* proj = object2D::CreateProj("proj", corner, length / 3, glm::vec3(0, 0, 0), true); AddMeshToList(proj); Mesh* obstacle1 = object2D::CreateRectangle("obstacle1", corner, obstacles[0].obstacleLength * length, glm::vec3(1, 0.50, 0.67), true); AddMeshToList(obstacle1); Mesh* obstacle2 = object2D::CreateRectangle("obstacle2", corner, obstacles[1].obstacleLength * length, glm::vec3(1, 0.50, 0.67), true); AddMeshToList(obstacle2); Mesh* obstacle3 = object2D::CreateRectangle("obstacle3", corner, obstacles[2].obstacleLength * length, glm::vec3(1, 0.50, 0.67), true); AddMeshToList(obstacle3); Mesh* healthbar = object2D::CreateHealthbar("healthbar", corner, length, glm::vec3(1, 0.3, 0.42)); AddMeshToList(healthbar); Mesh* life = object2D::CreateSquare("life", corner, length, glm::vec3(1, 0.3, 0.42), true); AddMeshToList(life); Mesh* extralife = object2D::CreateSquare("extralife", corner, length, glm::vec3(1, 0.3, 0.42), true); AddMeshToList(extralife); } // 2D visualization matrix glm::mat3 Tema1::VisualizationTransf2D(const LogicSpace & logicSpace, const ViewportSpace & viewSpace) { float sx, sy, tx, ty; sx = viewSpace.width / logicSpace.width; sy = viewSpace.height / logicSpace.height; tx = viewSpace.x - sx * logicSpace.x; ty = viewSpace.y - sy * logicSpace.y; return glm::transpose(glm::mat3( sx, 0.0f, tx, 0.0f, sy, ty, 0.0f, 0.0f, 1.0f)); } // Uniform 2D visualization matrix (same scale factor on x and y axes) glm::mat3 Tema1::VisualizationTransf2DUnif(const LogicSpace & logicSpace, const ViewportSpace & viewSpace) { float sx, sy, tx, ty, smin; sx = viewSpace.width / logicSpace.width; sy = viewSpace.height / logicSpace.height; if (sx < sy) smin = sx; else smin = sy; tx = viewSpace.x - smin * logicSpace.x + (viewSpace.width - smin * logicSpace.width) / 2; ty = viewSpace.y - smin * logicSpace.y + (viewSpace.height - smin * logicSpace.height) / 2; return glm::transpose(glm::mat3( smin, 0.0f, tx, 0.0f, smin, ty, 0.0f, 0.0f, 1.0f)); } void Tema1::SetViewportArea(const ViewportSpace & viewSpace, glm::vec3 colorColor, bool clear) { glViewport(viewSpace.x, viewSpace.y, viewSpace.width, viewSpace.height); glEnable(GL_SCISSOR_TEST); glScissor(viewSpace.x, viewSpace.y, viewSpace.width, viewSpace.height); // Clears the color buffer (using the previously set color) and depth buffer glClearColor(colorColor.r, colorColor.g, colorColor.b, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_SCISSOR_TEST); GetSceneCamera()->SetOrthographic((float)viewSpace.x, (float)(viewSpace.x + viewSpace.width), (float)viewSpace.y, (float)(viewSpace.y + viewSpace.height), 0.1f, 400); GetSceneCamera()->Update(); } void Tema1::FrameStart() { // Clears the color buffer (using the previously set color) and depth buffer glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } void Tema1::GenerateEnemy() { // generate enemies with random positions and speeds enemies.push_back(enemy(rand() % 11 + 1, rand() % 6 + 1, rand() % 3 + 1, false)); } void Tema1::UpdateEnemy(float deltaTimeSeconds) { float speed = 0.8 * deltaTimeSeconds; // eliminate hit enemies for (int i = 0; i < enemies.size(); i++) { if (enemies[i].isHit == false) { modelMatrix = visMatrix * transform2D::Translate(enemies[i].enemyX, enemies[i].enemyY); RenderMesh2D(meshes["enemy"], shaders["VertexColor"], modelMatrix); } else { enemies.erase(enemies.begin() + i); } } // generate enemy every 3 seconds this_time = clock(); time_counter += (double)(this_time - last_time); last_time = this_time; if (time_counter > (double)(3 * CLOCKS_PER_SEC)) { time_counter -= (double)(3 * CLOCKS_PER_SEC); GenerateEnemy(); } // make enemy follow you for (int i = 0; i < enemies.size(); i++) { if (enemies[i].enemyX > translateX - length / 2 + logicSpace.width / 2) { (float)enemies[i].enemyX -= speed * enemies[i].enemySpeed; } if (enemies[i].enemyX + length / 2 < translateX + logicSpace.width / 2) { (float)enemies[i].enemyX += speed * enemies[i].enemySpeed; } if (enemies[i].enemyY + length < translateY + logicSpace.height / 2) { (float)enemies[i].enemyY += speed * enemies[i].enemySpeed; } if (enemies[i].enemyY > translateY + logicSpace.height / 2) { (float)enemies[i].enemyY -= speed * enemies[i].enemySpeed; } } // check collision enemy-player for (int i = 0; i < enemies.size(); i++) { if (CheckCollision(translateX + logicSpace.width/2, translateY + logicSpace.height / 2, length, length, enemies[i].enemyX, enemies[i].enemyY, length + 0.15, length + 0.15)) { enemies[i].isHit = true; lives--; } } } void Tema1::GenerateProj() { projs.push_back(proj(translateX, translateY, angle, false)); } void Tema1::UpdateProj(float deltaTimeSeconds) { // calculate projectile trajectory float startX = 0; float startY = 0; for (int i = 0; i < projs.size(); i++) { if (projMoving == false) { projs[i].projX = translateX; projs[i].projY = translateY; projs[i].projAngle = angle; } else { projs[i].projX += projSpeed * cos(projs[i].projAngle); projs[i].projY += projSpeed * sin(projs[i].projAngle); } } // check collision enemy-projectile for (int i = 0; i < enemies.size(); i++) { for (int j = 0; j < projs.size(); j++) { if (CheckCollision(projs[j].projX + logicSpace.width/2, projs[j].projY + logicSpace.height/2, length / 3, 2 * length / 3, enemies[i].enemyX, enemies[i].enemyY, length, length)) { enemies[i].isHit = true; projs[j].projHit = true; score++; cout << "Score: " << score << endl; } } } // check collision obstacle-projectile for (int j = 0; j < 3; j++) { for (int i = 0; i < projs.size(); i++) { if (CheckCollision(projs[i].projX + logicSpace.width / 2, projs[i].projY + logicSpace.height / 2, length / 3, 2 * length / 3, obstacles[j].obstacleX, obstacles[j].obstacleY, obstacles[j].obstacleLength * length, 2 * length * obstacles[j].obstacleLength)) { projs[i].projHit = true; } } } // check collision projectile map float mapW, mapH; mapW = 30 * length; mapH = 60 * length; for (int i = 0; i < projs.size(); i++) { if (projs[i].projX > corner.x + mapW / 2) { projs[i].projHit = true; } if (projs[i].projX < corner.x - mapW / 2) { projs[i].projHit = true; } if (projs[i].projY > corner.y + mapH / 2) { projs[i].projHit = true; } if (projs[i].projY < corner.y - mapH / 2) { projs[i].projHit = true; } } } bool Tema1::CheckCollision(float oneX, float oneY, float oneW, float oneH, float twoX, float twoY, float twoW, float twoH) { bool collisionX = oneX + oneW >= twoX && twoX + twoW >= oneX; bool collisionY = oneY + oneH >= twoY && twoY + twoH >= oneY; return collisionX && collisionY; } void Tema1::Update(float deltaTimeSeconds) { glm::ivec2 resolution = window->GetResolution(); //// Sets the screen area where to draw - the left half of the window viewSpace = ViewportSpace(0, 0, resolution.x, resolution.y); SetViewportArea(viewSpace, glm::vec3(0.2), true); // Compute uniform 2D visualization matrix visMatrix = glm::mat3(1); visMatrix *= VisualizationTransf2DUnif(logicSpace, viewSpace); UpdateEnemy(deltaTimeSeconds); UpdateProj(deltaTimeSeconds); DrawScene(visMatrix); // collision with map colUp = false; colDown = false; colLeft = false; colRight = false; float mapW, mapH; mapW = 30 * length; mapH = 60 * length; if (translateX > corner.x + mapW / 2 - length / 2) { colRight = true; } if (translateX < corner.x - mapW / 2 + length / 2) { colLeft = true; } if (translateY > corner.y + mapH / 2 - length / 2) { colUp = true; } if (translateY < corner.y - mapH / 2 + length / 2) { colDown = true; } if (CheckCollision(translateX + logicSpace.width / 2, translateY + logicSpace.height / 2, length, length, 3, 4, length + 0.15, length + 0.15) && lives < 3) { extralife = false; lives += 1; } // exit game if you die if (lives == 0) { exit(0); } } void Tema1::FrameEnd() { } void Tema1::DrawScene(glm::mat3 visMatrix) { modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2) * transform2D::Translate(length, length); RenderMesh2D(meshes["healthbar"], shaders["VertexColor"], modelMatrix); if (lives == 3) { modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2 + length) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2 + 2 * length) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); } if (lives == 2) { modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2 + length) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); } if (lives == 1) { modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width / 3, logicSpace.height / 2) * transform2D::Translate(length, length); RenderMesh2D(meshes["life"], shaders["VertexColor"], modelMatrix); } if (extralife == true) { modelMatrix = visMatrix * transform2D::Translate(3, 4); RenderMesh2D(meshes["extralife"], shaders["VertexColor"], modelMatrix); } modelMatrix = visMatrix * transform2D::Translate(translateX, translateY); modelMatrix *= transform2D::Translate(logicSpace.width/2, logicSpace.height/2) * transform2D::Translate(-length / 2, -length / 2) * transform2D::Translate(length / 2, length / 2) * transform2D::Rotate(angle) * transform2D::Translate(-length / 2, -length / 2); RenderMesh2D(meshes["mc"], shaders["VertexColor"], modelMatrix); for (int i = 0; i < projs.size(); i++) { if (projs[i].projHit == false) { modelMatrix = visMatrix * transform2D::Translate(projs[i].projX, projs[i].projY); modelMatrix *= transform2D::Translate(logicSpace.width / 2, logicSpace.height / 2) * transform2D::Translate(-length / 2, -length / 6) * transform2D::Translate(length / 2, length / 6) * transform2D::Rotate(projs[i].projAngle) * transform2D::Translate(-length / 2, -length / 6); RenderMesh2D(meshes["proj"], shaders["VertexColor"], modelMatrix); } else { projs.erase(projs.begin() + i); } } modelMatrix = visMatrix * transform2D::Translate(obstacles[0].obstacleX, obstacles[0].obstacleY); RenderMesh2D(meshes["obstacle1"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(obstacles[1].obstacleX, obstacles[1].obstacleY); RenderMesh2D(meshes["obstacle2"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(obstacles[2].obstacleX, obstacles[2].obstacleY); RenderMesh2D(meshes["obstacle3"], shaders["VertexColor"], modelMatrix); modelMatrix = visMatrix * transform2D::Translate(logicSpace.width / 2, logicSpace.height / 2) * transform2D::Translate(-30 * length / 2, -60 * length / 2); RenderMesh2D(meshes["map"], shaders["VertexColor"], modelMatrix); } void Tema1::OnInputUpdate(float deltaTime, int mods) { // Move the logic window with W, A, S, D (up, left, down, right) if (window->KeyHold(GLFW_KEY_W) && colUp == false && colObstacleDown == false) { logicSpace.y += deltaTime * 10; translateY += deltaTime * 10; colDown = false; for (int i = 0; i < 3; i++) { if (CheckCollision(obstacles[i].obstacleX, obstacles[i].obstacleY, obstacles[i].obstacleLength * length, 2 * obstacles[i].obstacleLength * length, translateX + logicSpace.width / 2, translateY + logicSpace.height / 2, length, length)) { colObstacleDown = true; colObstacleRight = false; colObstacleLeft = false; colObstacleUp = false; break; } else { colObstacleDown = false; colObstacleRight = false; colObstacleLeft = false; colObstacleUp = false; } } } if (window->KeyHold(GLFW_KEY_S) && colDown == false && colObstacleUp == false) { logicSpace.y -= deltaTime * 10; translateY -= deltaTime * 10; colUp = false; colObstacleDown = false; for (int i = 0; i < 3; i++) { if (CheckCollision(obstacles[i].obstacleX, obstacles[i].obstacleY, obstacles[i].obstacleLength * length, 2 * obstacles[i].obstacleLength * length, translateX + logicSpace.width / 2, translateY + logicSpace.height / 2, 2*length, 2*length)) { colObstacleUp = true; colObstacleRight = false; colObstacleLeft = false; break; } else { colObstacleDown = false; colObstacleRight = false; colObstacleLeft = false; colObstacleUp = false; } } } if (window->KeyHold(GLFW_KEY_D) && colRight == false && colObstacleLeft == false) { logicSpace.x += deltaTime * 10; translateX += deltaTime * 10; colLeft = false; colObstacleRight = false; for (int i = 0; i < 3; i++) { if (CheckCollision(obstacles[i].obstacleX, obstacles[i].obstacleY, obstacles[i].obstacleLength * length, 2 * obstacles[i].obstacleLength * length, translateX + logicSpace.width / 2, translateY + logicSpace.height / 2, length, length)) { colObstacleLeft = true; colObstacleUp = false; colObstacleDown = false; break; } else { colObstacleDown = false; colObstacleRight = false; colObstacleLeft = false; colObstacleUp = false; } } } if (window->KeyHold(GLFW_KEY_A) && colLeft == false && colObstacleRight == false) { logicSpace.x -= deltaTime * 10; translateX -= deltaTime * 10; colRight = false; colObstacleLeft = false; for (int i = 0; i < 3; i++) { if (CheckCollision(obstacles[i].obstacleX, obstacles[i].obstacleY, obstacles[i].obstacleLength * length, 2 * obstacles[i].obstacleLength * length, translateX + logicSpace.width / 2, translateY + logicSpace.height / 2, length, length)) { colObstacleRight = true; colObstacleUp = false; colObstacleDown = false; break; } else { colObstacleDown = false; colObstacleRight = false; colObstacleLeft = false; colObstacleUp = false; } } } if (window->MouseHold(GLFW_MOUSE_BUTTON_LEFT) == false) { projMoving = true; projSpeed = deltaTime * 12; } } void Tema1::OnKeyPress(int key, int mods) { } void Tema1::OnKeyRelease(int key, int mods) { // Add key release event } void Tema1::OnMouseMove(int mouseX, int mouseY, int deltaX, int deltaY) { // player rotation angle angle = atan2f((viewSpace.height - mouseY * viewSpace.height/window->GetResolution().y - viewSpace.height/2), (mouseX * viewSpace.width/window->GetResolution().x - viewSpace.width / 2)); } void Tema1::OnMouseBtnPress(int mouseX, int mouseY, int button, int mods) { // Add mouse button press event if (window->MouseHold(GLFW_MOUSE_BUTTON_LEFT) == true) { this_time = clock(); time_counter += (double)(this_time - last_time); last_time = this_time; if (time_counter > (double)(0.7 * CLOCKS_PER_SEC)) { time_counter -= (double)(0.7 * CLOCKS_PER_SEC); GenerateProj(); } } } void Tema1::OnMouseBtnRelease(int mouseX, int mouseY, int button, int mods) { // Add mouse button release event } void Tema1::OnMouseScroll(int mouseX, int mouseY, int offsetX, int offsetY) { }
33.966159
170
0.603168
[ "mesh", "vector" ]
3d994d511adb0123824ea8ccad33597ecb4a20f6
6,839
cpp
C++
v3d_main/v3d/mdichild.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
39
2015-05-10T23:23:03.000Z
2022-01-26T01:31:30.000Z
v3d_main/v3d/mdichild.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
13
2016-03-04T05:29:23.000Z
2021-02-07T01:11:10.000Z
v3d_main/v3d/mdichild.cpp
lens-biophotonics/v3d_external
44ff3b60a297a96eaa77ca092e0de9af5c990ed3
[ "MIT" ]
44
2015-11-11T07:30:59.000Z
2021-12-26T16:41:21.000Z
/* * Copyright (c)2006-2010 Hanchuan Peng (Janelia Farm, Howard Hughes Medical Institute). * All rights reserved. */ /************ ********* LICENSE NOTICE ************ This folder contains all source codes for the V3D project, which is subject to the following conditions if you want to use it. You will ***have to agree*** the following terms, *before* downloading/using/running/editing/changing any portion of codes in this package. 1. This package is free for non-profit research, but needs a special license for any commercial purpose. Please contact Hanchuan Peng for details. 2. You agree to appropriately cite this work in your related studies and publications. Peng, H., Ruan, Z., Long, F., Simpson, J.H., and Myers, E.W. (2010) “V3D enables real-time 3D visualization and quantitative analysis of large-scale biological image data sets,” Nature Biotechnology, Vol. 28, No. 4, pp. 348-353, DOI: 10.1038/nbt.1612. ( http://penglab.janelia.org/papersall/docpdf/2010_NBT_V3D.pdf ) Peng, H, Ruan, Z., Atasoy, D., and Sternson, S. (2010) “Automatic reconstruction of 3D neuron structures using a graph-augmented deformable model,” Bioinformatics, Vol. 26, pp. i38-i46, 2010. ( http://penglab.janelia.org/papersall/docpdf/2010_Bioinfo_GD_ISMB2010.pdf ) 3. This software is provided by the copyright holders (Hanchuan Peng), Howard Hughes Medical Institute, Janelia Farm Research Campus, and contributors "as is" and any express or implied warranties, including, but not limited to, any implied warranties of merchantability, non-infringement, or fitness for a particular purpose are disclaimed. In no event shall the copyright owner, Howard Hughes Medical Institute, Janelia Farm Research Campus, 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; reasonable royalties; 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. 4. Neither the name of the Howard Hughes Medical Institute, Janelia Farm Research Campus, nor Hanchuan Peng, may be used to endorse or promote products derived from this software without specific prior written permission. *************/ /**************************************************************************** ** ** Copyright (C) 2005-2005 Trolltech AS. All rights reserved. ** ** This file is part of the example classes of the Qt Toolkit. ** ** This file may be used under the terms of the GNU General Public ** License version 2.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of ** this file. Please review the following information to ensure GNU ** General Public Licensing requirements will be met: ** http://www.trolltech.com/products/qt/opensource.html ** ** If you are unsure which license is appropriate for your use, please ** review the following information: ** http://www.trolltech.com/products/qt/licensing.html or contact the ** sales department at sales@trolltech.com. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #ifdef USE_Qt5 #include <QtWidgets> #else #include <QtGui> #endif #include "mdichild.h" MdiChild::MdiChild() { setAttribute(Qt::WA_DeleteOnClose); isUntitled = true; connect(document(), SIGNAL(contentsChanged()), this, SLOT(documentWasModified())); } void MdiChild::newFile() { static int sequenceNumber = 1; isUntitled = true; curFile = tr("document%1.txt").arg(sequenceNumber++); setWindowTitle(curFile + "[*]"); } bool MdiChild::loadFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot read file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return false; } QTextStream in(&file); QApplication::setOverrideCursor(Qt::WaitCursor); setPlainText(in.readAll()); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; } bool MdiChild::save() { if (isUntitled) { return saveAs(); } else { return saveFile(curFile); } } bool MdiChild::saveAs() { QString fileName = QFileDialog::getSaveFileName(this, tr("Save As"), curFile); if (fileName.isEmpty()) return false; return saveFile(fileName); } bool MdiChild::saveFile(const QString &fileName) { QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { QMessageBox::warning(this, tr("MDI"), tr("Cannot write file %1:\n%2.") .arg(fileName) .arg(file.errorString())); return false; } QTextStream out(&file); QApplication::setOverrideCursor(Qt::WaitCursor); out << toPlainText(); QApplication::restoreOverrideCursor(); setCurrentFile(fileName); return true; } QString MdiChild::userFriendlyCurrentFile() { return strippedName(curFile); } void MdiChild::closeEvent(QCloseEvent *event) { if (maybeSave()) { event->accept(); } else { event->ignore(); } } void MdiChild::documentWasModified() { setWindowModified(document()->isModified()); } bool MdiChild::maybeSave() { if (document()->isModified()) { int ret = QMessageBox::warning(this, tr("MDI"), tr("'%1' has been modified.\n" "Do you want to save your changes?") .arg(userFriendlyCurrentFile()), QMessageBox::Yes | QMessageBox::Default, QMessageBox::No, QMessageBox::Cancel | QMessageBox::Escape); if (ret == QMessageBox::Yes) return save(); else if (ret == QMessageBox::Cancel) return false; } return true; } void MdiChild::setCurrentFile(const QString &fileName) { curFile = QFileInfo(fileName).canonicalFilePath(); isUntitled = false; document()->setModified(false); setWindowModified(false); setWindowTitle(userFriendlyCurrentFile() + "[*]"); } QString MdiChild::strippedName(const QString &fullFileName) { return QFileInfo(fullFileName).fileName(); }
36.185185
941
0.654189
[ "model", "3d" ]
3d9aa3865359367e73b0ac0a6b21c8ad51bc26d9
24,501
cxx
C++
com/ole32/com/moniker2/csessmon.cxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/com/moniker2/csessmon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/com/moniker2/csessmon.cxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+--------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1993 - 1993. // // File: csessmon.cxx // // Contents: // // Classes: // // Functions: // // History: 11-25-98 GilleG Created // // The purpose of a Session moniker is to active an object on a given // session id. // // // //---------------------------------------------------------------------------- #include <ole2int.h> #include <cbasemon.hxx> #include <csessmon.hxx> #include <immact.hxx> #include "mnk.h" #define SESSION_MONIKER_NAME L"Session:" #define SESSION_MONIKER_DELIMITER L"!" #define CONSOLE_SESSION_TOKEN L"Console" //+--------------------------------------------------------------------------- // // Function: FindSessionMoniker // // Synopsis: Interpreting a display name as a SessionID, derive a // moniker from it. // // Arguments: [pbc] - Bind context // [pszDisplayName] - Display name to parse // [pcchEaten] - Number of characters eaten // [ppmk] - Moniker of running object // // Returns: S_OK if successful // MK_E_UNAVAILABLE or the return value from ParseDisplayName. // // Algorithm: Parse the first part of the display name to see if it's a // session moniker and create a session moniker. // //---------------------------------------------------------------------------- STDAPI FindSessionMoniker( IBindCtx * pbc, LPCWSTR pszDisplayName, ULONG * pcchEaten, IMoniker **ppmk) { HRESULT hr = S_OK; WCHAR* pwch; ULONG ullength; ULONG ulchcount; ULONG ulSessionID = 0; BOOL bUseConsole = FALSE; mnkDebugOut((DEB_ITRACE, "FindSessionMoniker(%x,%ws,%x,%x)\n", pbc, pszDisplayName, pcchEaten, ppmk)); *ppmk = NULL; ulchcount = 0; ullength = sizeof (SESSION_MONIKER_NAME) / sizeof (WCHAR) - 1; // // We now support two different syntaxes: // // "Session:XX" -- where XX is a numeric session id // "Session:Console" -- this means direct the activation to the // currently active TS user session. // if(_wcsnicmp(pszDisplayName, SESSION_MONIKER_NAME, ullength ) == 0) { WCHAR* pwchTmp; pwch = (LPWSTR)pszDisplayName + ullength; ulchcount = ullength; ullength = sizeof (CONSOLE_SESSION_TOKEN) / sizeof (WCHAR) - 1; // First look for "Console" if (_wcsnicmp(pwch, CONSOLE_SESSION_TOKEN, ullength) == 0) { pwchTmp = pwch + ullength; if ((*pwchTmp == L'\0') || (*pwchTmp == L'!')) { ulchcount += ullength; if (*pwchTmp == L'!') { ulchcount++; } ulSessionID = 0; // doesn't matter, but init it anyway bUseConsole = TRUE; } else { hr = MK_E_UNAVAILABLE; ulchcount = 0; } } else { // else it must be the original syntax // // verify that we've got a correct session id // ulSessionID = wcstoul( pwch, &pwchTmp, 10 ); if ((*pwchTmp == L'\0') || (*pwchTmp == L'!')) { ulchcount += (ULONG)((ULONG_PTR)pwchTmp - (ULONG_PTR)pwch)/sizeof(WCHAR); if (*pwchTmp == L'!') { ulchcount++; } bUseConsole = FALSE; // user was specific } else { hr = MK_E_UNAVAILABLE; ulchcount = 0; } } } else { hr = MK_E_UNAVAILABLE; } if (hr == S_OK) { CSessionMoniker *pCSM = new CSessionMoniker( ulSessionID, bUseConsole ); if (pCSM) { *ppmk = pCSM; hr = S_OK; } else { hr = E_OUTOFMEMORY; ulchcount = 0; } } *pcchEaten = ulchcount; return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::QueryInterface // // Synopsis: Gets a pointer to the specified interface. The session // moniker supports the IMarshal, IMoniker, IPersistStream, // IPersist, IROTData, IClassActivator and IUnknown interfaces. // The session moniker also supports CLSID_SessionMoniker so that // the IsEqual method can directly access the data members. // // Arguments: [iid] -- the requested interface // [ppv] -- where to put the interface pointer // // Returns: S_OK // E_INVALIDARG // E_NOINTERFACE // // Notes: Bad parameters will raise an exception. The exception // handler catches exceptions and returns E_INVALIDARG. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::QueryInterface( REFIID riid, void **ppv) { HRESULT hr; __try { mnkDebugOut((DEB_ITRACE, "CSessionMoniker::QueryInterface(%x,%I,%x)\n", this, &riid, ppv)); //Parameter validation. *ppv = NULL; // assume success hr = S_OK; if (IsEqualIID(riid, IID_IClassActivator)) { AddRef(); *ppv = (IClassActivator *)this; } // not supported by the CBaseMoniker::QueryInterface else if (IsEqualIID(riid, IID_IPersist)) { AddRef(); *ppv = (IMoniker *) this; } else if (IsEqualIID(riid, CLSID_SessionMoniker)) { AddRef(); *ppv = (CSessionMoniker *) this; } else { hr = CBaseMoniker::QueryInterface(riid, ppv); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetClassID // // Synopsis: Gets the class ID of the object. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetClassID( CLSID *pClassID) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetClassID(%x,%x)\n", this, pClassID)); __try { *pClassID = CLSID_SessionMoniker; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::Load // // Synopsis: Loads a session moniker from a stream // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::Load( IStream *pStream) { HRESULT hr; ULONG cbRead; DWORD sessionid; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::Load(%x,%x)\n", this, pStream)); __try { hr = pStream->Read(&sessionid, sizeof(sessionid), &cbRead); if(SUCCEEDED(hr)) { if(sizeof(sessionid) == cbRead) { m_sessionid = sessionid; hr = S_OK; } else { hr = STG_E_READFAULT; } } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::Save // // Synopsis: Saves the session moniker to a stream // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::Save( IStream *pStream, BOOL fClearDirty) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::Save(%x,%x,%x)\n", this, pStream, fClearDirty)); __try { hr = pStream->Write(&m_sessionid, sizeof(m_sessionid), NULL); } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetSizeMax // // Synopsis: Get the maximum size required to serialize this moniker // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetSizeMax( ULARGE_INTEGER * pcbSize) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetSizeMax(%x,%x)\n", this, pcbSize)); __try { ULISet32(*pcbSize, sizeof(CLSID) + sizeof(m_sessionid)); hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::BindToObject // // Synopsis: Bind to the session specified by this moniker. // // Notes: // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::BindToObject ( IBindCtx *pbc, IMoniker *pmkToLeft, REFIID riid, void ** ppv) { HRESULT hr; __try { mnkDebugOut((DEB_ITRACE, "CSessionMoniker::BindToObject(%x,%x,%x,%I,%x)\n", this, pbc, pmkToLeft, &riid, ppv)); //Validate parameters *ppv = NULL; // // This is being called by the ClassMoniker. // The actual binding is done in GetClassObject // if (riid == IID_IClassActivator) { m_bindopts2.cbStruct = sizeof(BIND_OPTS2); hr = pbc->GetBindOptions(&m_bindopts2); if (SUCCEEDED(hr)) { m_bHaveBindOpts = TRUE; AddRef(); *ppv = (IClassActivator*)this; } } else { hr = E_NOINTERFACE; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::BindToStorage // // Synopsis: Bind to the storage for the session specified by the moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::BindToStorage( IBindCtx *pbc, IMoniker *pmkToLeft, REFIID riid, void ** ppv) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::BindToStorage(%x,%x,%x,%I,%x)\n", this, pbc, pmkToLeft, &riid, ppv)); hr = BindToObject(pbc, pmkToLeft, riid, ppv); return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::ComposeWith // // Synopsis: Compose this moniker with another moniker. // // Notes: // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::ComposeWith( IMoniker * pmkRight, BOOL fOnlyIfNotGeneric, IMoniker **ppmkComposite) { HRESULT hr; IMoniker *pmk; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::ComposeWith(%x,%x,%x,%x)\n", this, pmkRight, fOnlyIfNotGeneric, ppmkComposite)); __try { //Validate parameters. *ppmkComposite = NULL; //Check for an anti-moniker hr = pmkRight->QueryInterface(CLSID_AntiMoniker, (void **)&pmk); if(FAILED(hr)) { //pmkRight is not an anti-moniker. if (!fOnlyIfNotGeneric) { hr = CreateGenericComposite(this, pmkRight, ppmkComposite); } else { hr = MK_E_NEEDGENERIC; } } else { //pmkRight is an anti-moniker. pmk->Release(); hr = S_OK; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::IsEqual // // Synopsis: Compares with another moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::IsEqual( IMoniker *pmkOtherMoniker) { HRESULT hr; CSessionMoniker *pSessionMoniker; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::IsEqual(%x,pmkOther(%x))\n", this, pmkOtherMoniker)); __try { hr = pmkOtherMoniker->QueryInterface(CLSID_SessionMoniker, (void **) &pSessionMoniker); if(SUCCEEDED(hr)) { if( m_sessionid == pSessionMoniker->m_sessionid ) { hr = S_OK; } else { hr = S_FALSE; } pSessionMoniker->Release(); } else { hr = S_FALSE; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::Hash // // Synopsis: Computes a hash value // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::Hash( DWORD * pdwHash) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::Hash(%x,%x)\n", this, pdwHash)); __try { *pdwHash = m_sessionid; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetTimeOfLastChange // // Synopsis: Returns the time when the object identified by this moniker // was changed. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetTimeOfLastChange ( IBindCtx * pbc, IMoniker * pmkToLeft, FILETIME * pFileTime) { mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetTimeOfLastChange(%x,%x,%x,%x)\n", this, pbc, pmkToLeft, pFileTime)); return MK_E_UNAVAILABLE; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::Inverse // // Synopsis: Returns the inverse of this moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::Inverse( IMoniker ** ppmk) { mnkDebugOut((DEB_ITRACE, "CSessionMoniker::Inverse(%x,%x)\n", this, ppmk)); return CreateAntiMoniker(ppmk); } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::CommonPrefixWith // // Synopsis: Returns the common prefix shared by this moniker and the // other moniker. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::CommonPrefixWith( IMoniker * pmkOther, IMoniker ** ppmkPrefix) { HRESULT hr; CSessionMoniker *pSessionMoniker; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::CommonPrefixWith(%x,%x,%x)\n", this, pmkOther, ppmkPrefix)); __try { //Validate parameters. *ppmkPrefix = NULL; hr = pmkOther->QueryInterface(CLSID_SessionMoniker, (void **) &pSessionMoniker); if(SUCCEEDED(hr)) { if( m_sessionid == pSessionMoniker->m_sessionid ) { AddRef(); *ppmkPrefix = (IMoniker *) this; hr = MK_S_US; } else { hr = MK_E_NOPREFIX; } pSessionMoniker->Release(); } else { hr = MonikerCommonPrefixWith(this, pmkOther, ppmkPrefix); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetDisplayName // // Synopsis: Get the display name of this moniker. // // Notes: The name is returned in the format: // "Session:3" if the session id is 3. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetDisplayName( IBindCtx * pbc, IMoniker * pmkToLeft, LPWSTR * lplpszDisplayName) { HRESULT hr = E_FAIL; LPWSTR pszDisplayName; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetDisplayName(%x,%x,pmkLeft(%x),%x)\n", this, pbc, pmkToLeft, lplpszDisplayName)); __try { WCHAR szSessionID[20]; ULONG cName; //Validate parameters. *lplpszDisplayName = NULL; //Create a display name from the session ID. //Get the session ID string. wsprintfW( szSessionID, L"%d", m_sessionid ); cName = lstrlenW(SESSION_MONIKER_NAME) + lstrlenW(szSessionID) + lstrlenW(SESSION_MONIKER_DELIMITER) + 2; pszDisplayName = (LPWSTR) CoTaskMemAlloc(cName * sizeof(WCHAR)); if(pszDisplayName != NULL) { lstrcpyW(pszDisplayName, SESSION_MONIKER_NAME); lstrcatW(pszDisplayName, szSessionID); lstrcatW(pszDisplayName, SESSION_MONIKER_DELIMITER); *lplpszDisplayName = pszDisplayName; hr = S_OK; } else { hr = E_OUTOFMEMORY; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::ParseDisplayName // // Synopsis: Parses the display name. // // Algorithm: // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::ParseDisplayName ( IBindCtx * pbc, IMoniker * pmkToLeft, LPWSTR lpszDisplayName, ULONG * pchEaten, IMoniker ** ppmkOut) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::ParseDisplayName(%x,%x,pmkLeft(%x),lpszDisplayName(%ws),%x,%x)\n", this, pbc, pmkToLeft, lpszDisplayName, pchEaten, ppmkOut)); __try { //Validate parameters *ppmkOut = NULL; *pchEaten = 0; ULONG chEaten; IMoniker* pmkNext; // // Parse the remaining display name. // hr = MkParseDisplayName(pbc, lpszDisplayName, &chEaten, &pmkNext); if (SUCCEEDED(hr)) { *ppmkOut = pmkNext; *pchEaten = chEaten; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::IsSystemMoniker // // Synopsis: Determines if this is one of the system supplied monikers. // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::IsSystemMoniker( DWORD * pdwType) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::IsSystemMoniker(%x,%x)\n", this, pdwType)); __try { *pdwType = MKSYS_SESSIONMONIKER; hr = S_OK; } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetComparisonData // // Synopsis: Gets comparison data for registration in the ROT // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetComparisonData( byte * pbData, ULONG cbMax, DWORD *pcbData) { HRESULT hr; mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetComparisonData(%x,%x,%x,%x)\n", this, pbData, cbMax, pcbData)); __try { *pcbData = 0; if(cbMax >= sizeof(CLSID_SessionMoniker) + sizeof(m_sessionid)) { memcpy(pbData, &CLSID_SessionMoniker, sizeof(CLSID_SessionMoniker)); memcpy(pbData + sizeof(CLSID_SessionMoniker), &m_sessionid, sizeof(m_sessionid)); *pcbData = sizeof(CLSID_SessionMoniker) + sizeof(m_sessionid); hr = S_OK; } else { hr = E_OUTOFMEMORY; } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; } //+--------------------------------------------------------------------------- // // Method: CSessionMoniker::GetClassObject // // Synopsis: // //---------------------------------------------------------------------------- STDMETHODIMP CSessionMoniker::GetClassObject( REFCLSID pClassID, DWORD dwClsContext, LCID locale, REFIID riid, void** ppv) { HRESULT hr; __try { mnkDebugOut((DEB_ITRACE, "CSessionMoniker::GetClassObject(%x,%x,%x,%x,%I,%x)\n", this, pClassID, dwClsContext, &locale, &riid, ppv)); //Validate parameters *ppv = NULL; CComActivator *pComAct; ISpecialSystemProperties *pSSp; hr = CoCreateInstance( CLSID_ComActivator, NULL, CLSCTX_INPROC_SERVER, IID_IStandardActivator, (void **) &pComAct); if(SUCCEEDED(hr)) { hr = pComAct->QueryInterface( IID_ISpecialSystemProperties, (void**) &pSSp ); if(SUCCEEDED(hr)) { // Pass in TRUE here since we want session moniker-specified // id's to go off-machine: hr = pSSp->SetSessionId( m_sessionid, m_bUseConsoleSession, TRUE); if(SUCCEEDED(hr)) { hr = pComAct->StandardGetClassObject( pClassID, dwClsContext, m_bHaveBindOpts ? m_bindopts2.pServerInfo : NULL, riid, ppv ); } pSSp->Release(); } pComAct->Release(); } } __except(EXCEPTION_EXECUTE_HANDLER) { hr = E_INVALIDARG; } return hr; }
25.954449
108
0.440145
[ "object" ]
3d9e46c9e77019b7eb8569dec8ada51b6845d247
12,080
hpp
C++
src/include/structures/rank_pairing_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
2
2019-03-18T20:37:47.000Z
2019-03-19T04:51:47.000Z
src/include/structures/rank_pairing_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
1
2019-09-09T02:33:02.000Z
2019-09-09T02:33:02.000Z
src/include/structures/rank_pairing_heap.hpp
mr-c/structures
5a2279557ec0e9da9bcff37f68f8fb1cd89a9314
[ "Apache-2.0" ]
4
2018-02-15T19:17:15.000Z
2020-06-25T13:26:19.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. // rank_pairing_heap.hpp // // Contains an implementation of the rank-pairing heap described in Haeupler, et al. (2011). // #ifndef structures_rank_pairing_heap_hpp #define structures_rank_pairing_heap_hpp #include <unordered_set> #include <unordered_map> #include <vector> #include <cstdlib> #include <cstdint> namespace structures { using namespace std; /** * A priority queue data structure that allows amortized O(1) priority increases. * Each value is only allows to be popped one time. Values must also be hashable. */ template <typename T, typename PriorityType, typename Compare = less<PriorityType>> class RankPairingHeap { public: /// Construct an empty heap. RankPairingHeap(); /// Construct an empty heap using a non-default comparator. RankPairingHeap(const Compare& compare); /// Destructor. ~RankPairingHeap(); /// Return the highest priority item on the heap and its priority. inline const pair<T, PriorityType>& top() const; /// Add the value to the heap if it has not been added yet. If it has been added /// but has not been popped, set its priority to the maximum of the current priority /// and the given priority. If it has been popped already, do nothing. inline void push_or_reprioritize(const T& value, const PriorityType& priority); /// Remove the highest priority item from the heap. inline void pop(); /// Return true if there are no items in the heap, else false. inline bool empty() const; /// Return the number of items on the heap. inline size_t size() const; private: class Node; /// Add a half-tree to the primary tree through the tournament procedure. inline void place_half_tree(Node* node); /// Link two half-tree roots and update rank. inline void link(Node* winner, Node* loser); /// Give an item the maximum of the given priority and its current priority. inline void reprioritize(Node* node, const PriorityType& priority); /// Find the nodes in the heap by value unordered_map<T, Node*> current_nodes; /// Roots of the half trees Node* first_root = nullptr; unordered_set<Node*> other_roots; /// Tracker to enable size query size_t num_items = 0; /// Comparator we are using to select maximum Compare compare; }; /* * Represents a value in the heap and a node in the binary tree structure. */ template <typename T, typename PriorityType, typename Compare> class RankPairingHeap<T, PriorityType, Compare>::Node { public: Node(const T& value, const PriorityType& priority) : value(value, priority) {} ~Node() { delete left; delete right; } pair<T, PriorityType> value; uint64_t rank = 0; Node* parent = nullptr; Node* left = nullptr; Node* right = nullptr; }; template <typename T, typename PriorityType, typename Compare> RankPairingHeap<T, PriorityType, Compare>::RankPairingHeap() { // nothing to do } template <typename T, typename PriorityType, typename Compare> RankPairingHeap<T, PriorityType, Compare>::RankPairingHeap(const Compare& compare) : compare(compare) { // nothing to do } template <typename T, typename PriorityType, typename Compare> RankPairingHeap<T, PriorityType, Compare>::~RankPairingHeap() { // clean up the heap trees delete first_root; for (Node* half_tree_root : other_roots) { delete half_tree_root; } } template <typename T, typename PriorityType, typename Compare> void RankPairingHeap<T, PriorityType, Compare>::link(Node* winner, Node* loser) { // tied contests increase the winner's rank if (winner->rank == loser->rank) { winner->rank++; } // place winner's left subtree on loser's right subtree loser->right = winner->left; if (loser->right) { loser->right->parent = loser; } // winner's left subtree is now the loser winner->left = loser; loser->parent = winner; } template <typename T, typename PriorityType, typename Compare> void RankPairingHeap<T, PriorityType, Compare>::place_half_tree(Node* node) { if (first_root == nullptr) { // this is the first value first_root = node; } else if (compare(top().second, node->value.second)) { // this is the new maximum other_roots.insert(first_root); first_root = node; } else { // this is not the new maximum other_roots.insert(node); } } template <typename T, typename PriorityType, typename Compare> inline void RankPairingHeap<T, PriorityType, Compare>::push_or_reprioritize(const T& value, const PriorityType& priority) { // look for the value in the heap auto current_location = current_nodes.find(value); if (current_location != current_nodes.end()) { // we've seen this value before if (current_location->second) { // it hasn't been popped yet, give it the new priority reprioritize(current_location->second, priority); } } else { // we haven't seen this value before, make a new node Node* node = new Node(value, priority); // add it to the heap place_half_tree(node); // bookkeeping current_nodes[value] = node; num_items++; } } template <typename T, typename PriorityType, typename Compare> inline const pair<T, PriorityType>& RankPairingHeap<T, PriorityType, Compare>::top() const { return first_root->value; } template <typename T, typename PriorityType, typename Compare> inline void RankPairingHeap<T, PriorityType, Compare>::reprioritize(Node* node, const PriorityType& priority) { if (compare(node->value.second, priority)) { // we're giving it a higher priority than it currently has node->value.second = priority; if (!node->parent) { // this is the root of a half tree if (compare(top().second, priority)) { // this is now the highest priority root, so we need to move it to the front other_roots.insert(first_root); other_roots.erase(node); first_root = node; } } else { // remove this node from the tree and put its right subtree in its place Node* next_parent = node->parent; node->parent = nullptr; if (next_parent->left == node) { next_parent->left = node->right; } else { next_parent->right = node->right; } if (node->right) { node->right->parent = next_parent; } node->right = nullptr; place_half_tree(node); // restore the type-2 rank property above the node while (next_parent) { // make it a (1,1), (1, 2), or, (0, i) node if (next_parent->right && next_parent->left) { uint64_t next_rank = max(next_parent->left->rank, next_parent->right->rank); if (next_rank - min(next_parent->left->rank, next_parent->right->rank) <= 1) { next_rank++; } if (next_rank >= next_parent->rank) { break; } else { next_parent->rank = next_rank; } } else if (next_parent->right) { next_parent->rank = next_parent->right->rank + 1; } else if (next_parent->left) { next_parent->rank = next_parent->left->rank + 1; } else { next_parent->rank = 0; } next_parent = next_parent->parent; } } } } template <typename T, typename PriorityType, typename Compare> inline void RankPairingHeap<T, PriorityType, Compare>::pop() { // bookkeeping num_items--; // mark this value as popped current_nodes[top().first] = nullptr; // collect the other roots for later processing vector<Node*> new_roots; // disassemble the first tree and collect the right spine if (first_root->left) { // have to have one iteration outside the loop since we travel // left the first time Node* prev_spine_node = first_root->left; new_roots.push_back(prev_spine_node); prev_spine_node->parent = nullptr; while (prev_spine_node->right) { new_roots.push_back(prev_spine_node->right); prev_spine_node->right = nullptr; prev_spine_node = new_roots.back(); prev_spine_node->parent = nullptr; } } // collect the other current roots too for (Node* half_tree_root : other_roots) { new_roots.push_back(half_tree_root); } other_roots.clear(); // get rid of the first root first_root->left = nullptr; // so it won't delete the other nodes delete first_root; first_root = nullptr; // one-pass algorithm over the roots described in paper vector<Node*> buckets; for (Node* half_tree_root : new_roots) { // compact the ranks to make 1-nodes half_tree_root->rank = half_tree_root->left ? half_tree_root->left->rank + 1 : 0; // ensure that we have enough buckets while (buckets.size() <= half_tree_root->rank) { buckets.push_back(nullptr); } // what's in the bucket right now? uint64_t bucket_num = half_tree_root->rank; Node* other_root = buckets[bucket_num]; if (other_root) { // there's already a tree in this bucket if (compare(half_tree_root->value.second, other_root->value.second)) { // the current tree wins, link and place it link(other_root, half_tree_root); place_half_tree(other_root); } else { // the other tree wins, link and place it link(half_tree_root, other_root); place_half_tree(half_tree_root); } // empty the bucket buckets[bucket_num] = nullptr; } else { // the bucket is empty, fill it with the current half tree buckets[bucket_num] = half_tree_root; } } // get any half trees still in the buckets and add them to the main tree for (Node* half_tree_root : buckets) { if (half_tree_root) { place_half_tree(half_tree_root); } } } template <typename T, typename PriorityType, typename Compare> inline bool RankPairingHeap<T, PriorityType, Compare>::empty() const { return first_root == nullptr; } template <typename T, typename PriorityType, typename Compare> inline size_t RankPairingHeap<T, PriorityType, Compare>::size() const { return num_items; } } #endif /* structures_rank_pairing_heap_hpp */
32.737127
123
0.615149
[ "vector" ]
3d9f5e5ee56081639a99b3d69a6fc87157a84f56
2,096
cpp
C++
practice/almostArithmeticalProgression.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
practice/almostArithmeticalProgression.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
practice/almostArithmeticalProgression.cpp
xenowits/cp
963b3c7df65b5328d5ce5ef894a46691afefb98c
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define fori(i,a,b) for (int i = a; i <= b ; ++i) #define ford(i,a,b) for(int i = a;i >= b ; --i) #define mk make_pair #define mod 1000000007 #define pb push_back #define ll long long #define MAXN 100001 #define rnd mt19937_64 rng(chrono::high_resolution_clock::now().time_since_epoch().cnt()) #define pi pair<long long int,long long int> ll dp[4001][4001]; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); ll n; cin >> n; vector<ll> b(n); set<int> s; ll initial_max = INT_MIN; unordered_map<int,int> up; fori(i,0,n-1) { cin >> b[i]; up[b[i]] += 1; ll temps = up[b[i]]; initial_max = max(initial_max,temps); s.insert(b[i]); } if (n == 1) { cout << 1 << endl; return 0; } unordered_map<int,int> umap; //code for normalisation int cnt = 1; for(auto a : s) { umap[a] = cnt; cnt += 1; } vector<ll> a(n); fori(i,0,n-1) { a[i] = umap[b[i]]; //cout << a[i] << " " << b[i] << endl; } //vector normalised uptill now int new_int = s.size(); vector<int> last_index(new_int+1); fori(i,0,n-1) { int temp = a[i]; vector<bool> visited(n,false); visited[a[i]] = true; last_index[temp] = i; ford(j,i-1,0) { if (a[j] == temp) break; if (!visited[a[j]]) { dp[temp][a[j]] += 1; visited[a[j]] = true; } } } // for(int p : last_index) // cout << p << endl; ll row_maxu = INT_MIN,maxu_ele; ll final_ans = INT_MIN; fori(i,1,new_int) { fori(j,1,new_int) { //cout << dp[i][j] << " "; if (dp[i][j] > row_maxu) { row_maxu = dp[i][j]; maxu_ele = j; } } //row_maxu = row_maxu*2; fori(j,1,new_int) { if (dp[i][j] == row_maxu) { if (last_index[i] < n-1 && last_index[j] > last_index[i]) final_ans = max(final_ans,2*row_maxu+1); } } final_ans = max(final_ans,2*row_maxu); //cout << endl; } cout << max(final_ans,initial_max) << endl; return 0; }
20.349515
89
0.527195
[ "vector" ]
3da49bdd5516d94d75a6162cfab4415ba2dd3465
4,749
hpp
C++
Engine/Source/GEOGL/Layers/Layer.hpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Layers/Layer.hpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
Engine/Source/GEOGL/Layers/Layer.hpp
Matthew-Krueger/GEOGL
aae6adbd3d9cfadb4fe65b961d018636e42ddecc
[ "Zlib" ]
null
null
null
/******************************************************************************* * Copyright (c) 2020 Matthew Krueger * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgment in the product documentation would * * be appreciated but is not required. * * * * 2. Altered source versions must be plainly marked as such, and must not * * be misrepresented as being the original software. * * * * 3. This notice may not be removed or altered from any source * * distribution. * * * *******************************************************************************/ /******************************************************************************* * * * This code was based heavily off the Cherno game engine series * * * *******************************************************************************/ #ifndef GEOGL_LAYER_HPP #define GEOGL_LAYER_HPP #include "../IO/Events/Event.hpp" #include <GEOGL/Utils.hpp> namespace GEOGL { class GEOGL_API Layer{ public: explicit Layer(const std::string& name = "Layer"); virtual ~Layer(); /** * \brief Callback function called when the layer is attached to a LayerStack. */ virtual void onAttach(){} /** * \brief Callback function called when the layer is detached from a LayerStack. * \note This function is guaranteed to be called by any method of detachment. The LayerStack will call this * when the layer is detached. The LayerStack will also call this when the LayerStack is destructed if this * layer is a current member of the LayerStack. Furthermore, it is important to note that the LayerStack gains * ownership of the pointer to this layer while the LayerStack contains it. */ virtual void onDetach(){} /** * \brief Callback function called every frame for rendering the application. * * The LayerStack guarantees that onUpdate is called each frame in order of the LayerStack. */ virtual void onUpdate(TimeStep timeStep){} /** * \brief Callback function for ImGUI Render. Guaranteed to be called each frame. * * Uses the ImGui Immediate mode renderer to render ImGui graphics. This is called after all onUpdate functions * have been called. */ virtual void onImGuiRender(TimeStep timeStep){} /** * \brief Callback function for Events from the GEOGL Event System. * * \note This function is NOT guaranteed to be called when an event is dispatched. If an event is dispatched to * the Application, the event is propagated down the LayerStack. From here, if an event is marked as handled, * the loop is no longer continued to allow for blocking (i.e. clicking on a button shouldn't shoot a gun) * * @param event The event to be handled. */ virtual void onEvent(Event& event){} /** * \brief Gets the name of the current layer. Should not be used for release builds. * @return The name of the layer. */ inline const std::string& getName() const { return m_DebugName; } protected: std::string m_DebugName; }; } #endif //GEOGL_LAYER_HPP
48.958763
119
0.487471
[ "render" ]
3da6e7a8f76d0faa519269204b4968866ccbefad
7,344
cc
C++
shell/platform/linux/fl_mouse_cursor_plugin.cc
iMostfa/engine
09abc947e8d97a64edee790ccec6b4a9bc62485c
[ "BSD-3-Clause" ]
1
2021-10-10T12:37:49.000Z
2021-10-10T12:37:49.000Z
shell/platform/linux/fl_mouse_cursor_plugin.cc
iMostfa/engine
09abc947e8d97a64edee790ccec6b4a9bc62485c
[ "BSD-3-Clause" ]
null
null
null
shell/platform/linux/fl_mouse_cursor_plugin.cc
iMostfa/engine
09abc947e8d97a64edee790ccec6b4a9bc62485c
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2013 The Flutter 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 "flutter/shell/platform/linux/fl_mouse_cursor_plugin.h" #include <gtk/gtk.h> #include "flutter/shell/platform/linux/public/flutter_linux/fl_method_channel.h" #include "flutter/shell/platform/linux/public/flutter_linux/fl_standard_method_codec.h" static constexpr char kChannelName[] = "flutter/mousecursor"; static constexpr char kBadArgumentsError[] = "Bad Arguments"; static constexpr char kActivateSystemCursorMethod[] = "activateSystemCursor"; static constexpr char kKindKey[] = "kind"; static constexpr char kFallbackCursor[] = "default"; struct _FlMouseCursorPlugin { GObject parent_instance; FlMethodChannel* channel; FlView* view; GHashTable* system_cursor_table; }; G_DEFINE_TYPE(FlMouseCursorPlugin, fl_mouse_cursor_plugin, G_TYPE_OBJECT) // Insert a new entry into a hashtable from strings to strings. // // Returns whether the newly added value was already in the hash table or not. static bool define_system_cursor(GHashTable* table, const gchar* key, const gchar* value) { return g_hash_table_insert( table, reinterpret_cast<gpointer>(const_cast<gchar*>(key)), reinterpret_cast<gpointer>(const_cast<gchar*>(value))); } // Populate the hash table so that it maps from Flutter's cursor kinds to GTK's // cursor values. // // The table must have been created as a hashtable from strings to strings. static void populate_system_cursor_table(GHashTable* table) { // The following mapping must be kept in sync with Flutter framework's // mouse_cursor.dart. define_system_cursor(table, "alias", "alias"); define_system_cursor(table, "allScroll", "all-scroll"); define_system_cursor(table, "basic", "default"); define_system_cursor(table, "cell", "cell"); define_system_cursor(table, "click", "pointer"); define_system_cursor(table, "contextMenu", "context-menu"); define_system_cursor(table, "copy", "copy"); define_system_cursor(table, "forbidden", "not-allowed"); define_system_cursor(table, "grab", "grab"); define_system_cursor(table, "grabbing", "grabbing"); define_system_cursor(table, "help", "help"); define_system_cursor(table, "move", "move"); define_system_cursor(table, "none", "none"); define_system_cursor(table, "noDrop", "no-drop"); define_system_cursor(table, "precise", "crosshair"); define_system_cursor(table, "progress", "progress"); define_system_cursor(table, "text", "text"); define_system_cursor(table, "resizeColumn", "col-resize"); define_system_cursor(table, "resizeDown", "s-resize"); define_system_cursor(table, "resizeDownLeft", "sw-resize"); define_system_cursor(table, "resizeDownRight", "se-resize"); define_system_cursor(table, "resizeLeft", "w-resize"); define_system_cursor(table, "resizeLeftRight", "ew-resize"); define_system_cursor(table, "resizeRight", "e-resize"); define_system_cursor(table, "resizeRow", "row-resize"); define_system_cursor(table, "resizeUp", "n-resize"); define_system_cursor(table, "resizeUpDown", "ns-resize"); define_system_cursor(table, "resizeUpLeft", "nw-resize"); define_system_cursor(table, "resizeUpRight", "ne-resize"); define_system_cursor(table, "resizeUpLeftDownRight", "nwse-resize"); define_system_cursor(table, "resizeUpRightDownLeft", "nesw-resize"); define_system_cursor(table, "verticalText", "vertical-text"); define_system_cursor(table, "wait", "wait"); define_system_cursor(table, "zoomIn", "zoom-in"); define_system_cursor(table, "zoomOut", "zoom-out"); } // Sets the mouse cursor. FlMethodResponse* activate_system_cursor(FlMouseCursorPlugin* self, FlValue* args) { if (fl_value_get_type(args) != FL_VALUE_TYPE_MAP) { return FL_METHOD_RESPONSE(fl_method_error_response_new( kBadArgumentsError, "Argument map missing or malformed", nullptr)); } FlValue* kind_value = fl_value_lookup_string(args, kKindKey); const gchar* kind = nullptr; if (fl_value_get_type(kind_value) == FL_VALUE_TYPE_STRING) { kind = fl_value_get_string(kind_value); } if (self->system_cursor_table == nullptr) { self->system_cursor_table = g_hash_table_new(g_str_hash, g_str_equal); populate_system_cursor_table(self->system_cursor_table); } const gchar* cursor_name = reinterpret_cast<const gchar*>( g_hash_table_lookup(self->system_cursor_table, kind)); if (cursor_name == nullptr) { cursor_name = kFallbackCursor; } GdkWindow* window = gtk_widget_get_window(gtk_widget_get_toplevel(GTK_WIDGET(self->view))); g_autoptr(GdkCursor) cursor = gdk_cursor_new_from_name(gdk_window_get_display(window), cursor_name); gdk_window_set_cursor(window, cursor); return FL_METHOD_RESPONSE(fl_method_success_response_new(nullptr)); } // Called when a method call is received from Flutter. static void method_call_cb(FlMethodChannel* channel, FlMethodCall* method_call, gpointer user_data) { FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(user_data); const gchar* method = fl_method_call_get_name(method_call); FlValue* args = fl_method_call_get_args(method_call); g_autoptr(FlMethodResponse) response = nullptr; if (strcmp(method, kActivateSystemCursorMethod) == 0) { response = activate_system_cursor(self, args); } else { response = FL_METHOD_RESPONSE(fl_method_not_implemented_response_new()); } g_autoptr(GError) error = nullptr; if (!fl_method_call_respond(method_call, response, &error)) { g_warning("Failed to send method call response: %s", error->message); } } static void view_weak_notify_cb(gpointer user_data, GObject* object) { FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(object); self->view = nullptr; } static void fl_mouse_cursor_plugin_dispose(GObject* object) { FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN(object); g_clear_object(&self->channel); if (self->view != nullptr) { g_object_weak_unref(G_OBJECT(self->view), view_weak_notify_cb, self); self->view = nullptr; } g_clear_pointer(&self->system_cursor_table, g_hash_table_unref); G_OBJECT_CLASS(fl_mouse_cursor_plugin_parent_class)->dispose(object); } static void fl_mouse_cursor_plugin_class_init(FlMouseCursorPluginClass* klass) { G_OBJECT_CLASS(klass)->dispose = fl_mouse_cursor_plugin_dispose; } static void fl_mouse_cursor_plugin_init(FlMouseCursorPlugin* self) {} FlMouseCursorPlugin* fl_mouse_cursor_plugin_new(FlBinaryMessenger* messenger, FlView* view) { g_return_val_if_fail(FL_IS_BINARY_MESSENGER(messenger), nullptr); FlMouseCursorPlugin* self = FL_MOUSE_CURSOR_PLUGIN( g_object_new(fl_mouse_cursor_plugin_get_type(), nullptr)); g_autoptr(FlStandardMethodCodec) codec = fl_standard_method_codec_new(); self->channel = fl_method_channel_new(messenger, kChannelName, FL_METHOD_CODEC(codec)); fl_method_channel_set_method_call_handler(self->channel, method_call_cb, self, nullptr); self->view = view; g_object_weak_ref(G_OBJECT(view), view_weak_notify_cb, self); return self; }
39.913043
87
0.740468
[ "object" ]
3da7c7895fff0e0d94779f352705eaf7fa8c9fc3
10,871
cc
C++
xls/dslx/extract_conversion_order.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
xls/dslx/extract_conversion_order.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
xls/dslx/extract_conversion_order.cc
briansrls/xls
35fd94eff68611d510288938469ee620a38e1976
[ "Apache-2.0" ]
null
null
null
// Copyright 2021 The XLS Authors // // 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 "xls/dslx/extract_conversion_order.h" #include "xls/common/status/ret_check.h" #include "xls/dslx/dslx_builtins.h" namespace xls::dslx { static std::string CalleesToString(absl::Span<const Callee> callees) { return absl::StrCat("[", absl::StrJoin(callees, ", ", [](std::string* out, const Callee& callee) { absl::StrAppend(out, callee.ToString()); }), "]"); } static std::string ConversionRecordsToString( absl::Span<const ConversionRecord> records) { return absl::StrCat( "[", absl::StrJoin(records, ",\n ", [](std::string* out, const ConversionRecord& record) { absl::StrAppend(out, record.ToString()); }), "]"); } std::string Callee::ToString() const { return absl::StrFormat("Callee{m=%s, f=%s, bindings=%s}", m->name(), f->identifier(), sym_bindings.ToString()); } std::string ConversionRecord::ToString() const { return absl::StrFormat( "ConversionRecord{m=%s, f=%s, bindings=%s, callees=%s}", m->name(), f->identifier(), bindings.ToString(), CalleesToString(callees)); } class InvocationVisitor : public AstNodeVisitorWithDefault { public: InvocationVisitor(Module* module, TypeInfo* type_info, const SymbolicBindings& bindings) : module_(module), type_info_(type_info), bindings_(bindings) {} ~InvocationVisitor() override = default; absl::Status HandleInvocation(Invocation* node) { Module* this_m = nullptr; Function* f = nullptr; if (auto* colon_ref = dynamic_cast<ColonRef*>(node->callee())) { absl::optional<Import*> import = colon_ref->ResolveImportSubject(); XLS_RET_CHECK(import.has_value()); absl::optional<const ImportedInfo*> info = type_info_->GetImported(*import); XLS_RET_CHECK(info.has_value()); this_m = (*info)->module; f = this_m->GetFunction(colon_ref->attr()).value(); } else if (auto* name_ref = dynamic_cast<NameRef*>(node->callee())) { this_m = module_; // TODO(leary): 2020-01-16 change to detect builtinnamedef map, identifier // is fragile due to shadowing. std::string fn_identifier = name_ref->identifier(); if (fn_identifier == "map") { // We need to make sure we convert the mapped function! XLS_RET_CHECK_EQ(node->args().size(), 2); Expr* fn_node = node->args()[1]; XLS_VLOG(5) << "map() invoking: " << fn_node->ToString(); if (auto* mapped_colon_ref = dynamic_cast<ColonRef*>(fn_node)) { XLS_VLOG(5) << "map() invoking ColonRef"; fn_identifier = mapped_colon_ref->attr(); absl::optional<Import*> import = mapped_colon_ref->ResolveImportSubject(); XLS_RET_CHECK(import.has_value()); absl::optional<const ImportedInfo*> info = type_info_->GetImported(*import); XLS_RET_CHECK(info.has_value()); this_m = (*info)->module; } else { XLS_VLOG(5) << "map() invoking NameRef"; auto* mapped_name_ref = dynamic_cast<NameRef*>(fn_node); XLS_RET_CHECK(mapped_name_ref != nullptr); fn_identifier = mapped_name_ref->identifier(); } } absl::optional<Function*> maybe_f = this_m->GetFunction(fn_identifier); if (maybe_f.has_value()) { f = maybe_f.value(); } else { if (GetParametricBuiltins().contains(name_ref->identifier())) { return absl::OkStatus(); } return absl::InternalError("Could not resolve invoked function: " + fn_identifier); } } else { return absl::UnimplementedError( "Only calls to named functionsa re currently supported, got " "callee: " + node->callee()->ToString()); } absl::optional<TypeInfo*> invocation_type_info; XLS_VLOG(5) << "Getting callee bindings for invocation: " << node->ToString() << " @ " << node->span() << " caller bindings: " << bindings_.ToString(); absl::optional<const SymbolicBindings*> callee_bindings = type_info_->GetInvocationSymbolicBindings(node, bindings_); if (callee_bindings.has_value()) { XLS_RET_CHECK(*callee_bindings != nullptr); XLS_VLOG(5) << "Found callee bindings: " << **callee_bindings; invocation_type_info = type_info_->GetInstantiation(node, **callee_bindings); } // If we don't have any special type info to use for the invocation if (!invocation_type_info.has_value()) { invocation_type_info.emplace(type_info_); } callees_.push_back( Callee{f, this_m, invocation_type_info.value(), callee_bindings ? **callee_bindings : SymbolicBindings()}); return absl::OkStatus(); } std::vector<Callee>& callees() { return callees_; } private: Module* module_; TypeInfo* type_info_; const SymbolicBindings& bindings_; std::vector<Callee> callees_; }; // Traverses the definition of f to find callees. // // Args: // node: AST construct to inspect for calls. // m: Module that f resides in. // type_info: Node to type mapping that should be used with f. // imports: Mapping of modules imported by m. // bindings: Bindings used in instantiation of f. // // Returns: // Callee functions invoked by f, and the parametric bindings used in each of // those invocations. static absl::StatusOr<std::vector<Callee>> GetCallees( AstNode* node, Module* m, TypeInfo* type_info, const SymbolicBindings& bindings) { InvocationVisitor visitor(m, type_info, bindings); XLS_RETURN_IF_ERROR( WalkPostOrder(ToAstNode(node), &visitor, /*want_types=*/true)); return std::move(visitor.callees()); } static bool IsReady(absl::variant<Function*, TestFunction*> f, Module* m, const SymbolicBindings& bindings, const std::vector<ConversionRecord>* ready) { // Test functions are always the root and non-parametric, so they're always // ready. if (absl::holds_alternative<TestFunction*>(f)) { return true; } for (const ConversionRecord& cr : *ready) { if (cr.f == absl::get<Function*>(f) && cr.m == m && cr.bindings == bindings) { return true; } } return false; } // Forward decl. static absl::Status AddToReady(absl::variant<Function*, TestFunction*> f, Module* m, TypeInfo* type_info, const SymbolicBindings& bindings, std::vector<ConversionRecord>* ready); static absl::Status ProcessCallees(absl::Span<const Callee> orig_callees, std::vector<ConversionRecord>* ready) { // Knock out all callees that are already in the (ready) order. std::vector<Callee> non_ready; { for (const Callee& callee : orig_callees) { if (!IsReady(callee.f, callee.m, callee.sym_bindings, ready)) { non_ready.push_back(callee); } } } // For all the remaining callees (that were not ready), add them to the list // before us, since we depend upon them. for (const Callee& callee : non_ready) { XLS_RETURN_IF_ERROR( AddToReady(absl::variant<Function*, TestFunction*>(callee.f), callee.m, callee.type_info, callee.sym_bindings, ready)); } return absl::OkStatus(); } // Adds (f, bindings) to conversion order after deps have been added. static absl::Status AddToReady(absl::variant<Function*, TestFunction*> f, Module* m, TypeInfo* type_info, const SymbolicBindings& bindings, std::vector<ConversionRecord>* ready) { if (IsReady(f, m, bindings, ready)) { return absl::OkStatus(); } XLS_ASSIGN_OR_RETURN(const std::vector<Callee> orig_callees, GetCallees(ToAstNode(f), m, type_info, bindings)); XLS_VLOG(5) << "Original callees of " << absl::get<Function*>(f)->identifier() << ": " << CalleesToString(orig_callees); XLS_RETURN_IF_ERROR(ProcessCallees(orig_callees, ready)); XLS_RET_CHECK(!IsReady(f, m, bindings, ready)); // We don't convert the bodies of test constructs of IR. if (!absl::holds_alternative<TestFunction*>(f)) { auto* fn = absl::get<Function*>(f); XLS_VLOG(3) << "Adding to ready sequence: " << fn->identifier(); ready->push_back( ConversionRecord{fn, m, type_info, bindings, orig_callees}); } return absl::OkStatus(); } absl::StatusOr<std::vector<ConversionRecord>> GetOrder(Module* module, TypeInfo* type_info, bool traverse_tests) { std::vector<ConversionRecord> ready; for (ModuleMember member : module->top()) { if (absl::holds_alternative<QuickCheck*>(member)) { auto* quickcheck = absl::get<QuickCheck*>(member); Function* function = quickcheck->f(); XLS_RET_CHECK(!function->IsParametric()) << function->ToString(); XLS_RETURN_IF_ERROR( AddToReady(function, module, type_info, SymbolicBindings(), &ready)); } else if (absl::holds_alternative<Function*>(member)) { auto* function = absl::get<Function*>(member); if (function->IsParametric()) { continue; } XLS_RETURN_IF_ERROR( AddToReady(function, module, type_info, SymbolicBindings(), &ready)); } else if (absl::holds_alternative<ConstantDef*>(member)) { auto* constant_def = absl::get<ConstantDef*>(member); XLS_ASSIGN_OR_RETURN( const std::vector<Callee> callees, GetCallees(constant_def, module, type_info, SymbolicBindings())); XLS_RETURN_IF_ERROR(ProcessCallees(callees, &ready)); } } if (traverse_tests) { for (TestFunction* test : module->GetTests()) { XLS_RETURN_IF_ERROR( AddToReady(test, module, type_info, SymbolicBindings(), &ready)); } } XLS_VLOG(5) << "Ready list: " << ConversionRecordsToString(ready); return ready; } } // namespace xls::dslx
38.14386
80
0.62331
[ "vector" ]
3daa5e96e6d11c16502c73bd9cb3da73157e9ec3
2,200
cpp
C++
src/server/screensaver.cpp
pvanhoof/NymphCast
1b60ff19860e927809e91e129aa29e6ddeba17ca
[ "BSD-3-Clause" ]
1
2020-09-16T13:02:14.000Z
2020-09-16T13:02:14.000Z
src/server/screensaver.cpp
pvanhoof/NymphCast
1b60ff19860e927809e91e129aa29e6ddeba17ca
[ "BSD-3-Clause" ]
null
null
null
src/server/screensaver.cpp
pvanhoof/NymphCast
1b60ff19860e927809e91e129aa29e6ddeba17ca
[ "BSD-3-Clause" ]
null
null
null
#include "screensaver.h" #include <thread> // Static variables. std::atomic<bool> ScreenSaver::active = {false}; std::atomic<bool> ScreenSaver::firstRun = {true}; SDL_Window* ScreenSaver::window = 0; SDL_Renderer* ScreenSaver::renderer = 0; SDL_Texture* ScreenSaver::texture = 0; ChronoTrigger ScreenSaver::ct; std::vector<std::string> ScreenSaver::images = { "green.jpg", "forest_brook.jpg" }; int ScreenSaver::imageId = 0; void ScreenSaver::changeImage(int) { if (firstRun) { // Set up SDL. SDL_Init(SDL_INIT_VIDEO); IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG | IMG_INIT_TIF); // Create window. window = SDL_CreateWindow("SDL2 Displaying Image", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 1920, 1080, 0); // Create renderer. renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { fprintf(stderr, "Could not create renderer: %s\n", SDL_GetError()); return; } firstRun = false; } // Load current image. if (texture) { SDL_DestroyTexture(texture); texture = 0; } fprintf(stdout, "Changing image to %s\n", images[imageId].data()); texture = IMG_LoadTexture(renderer, images[imageId++].data()); if (!(imageId < images.size())) { imageId = 0; } //SDL_RenderClear(renderer); SDL_RenderCopy(renderer, texture, 0, 0); SDL_RenderPresent(renderer); // Keep the SDL event queue happy. SDL_Event event; SDL_PollEvent(&event); } void ScreenSaver::cleanUp() { // Clean up SDL. fprintf(stderr, "Destroying texture...\n"); SDL_DestroyTexture(texture); fprintf(stderr, "Destroying renderer...\n"); SDL_DestroyRenderer(renderer); fprintf(stderr, "Destroying window...\n"); SDL_DestroyWindow(window); fprintf(stderr, "Quitting...\n"); IMG_Quit(); /*SDL_Quit() */; } void ScreenSaver::start(uint32_t changeSecs) { if (active) { return; } // Cycle through the wallpapers until stopped. ct.setCallback(ScreenSaver::changeImage, 0); ct.setStopCallback(ScreenSaver::cleanUp); ct.start(changeSecs * 1000); // Convert to milliseconds. active = true; } void ScreenSaver::stop() { if (!active) { return; } fprintf(stderr, "Stopping timer...\n"); // Stop timer. ct.stop(); active = false; firstRun = true; }
22.680412
83
0.692727
[ "vector" ]
3dafe38c5412c5f7ebb6af64a1d12904b4777dad
691
cpp
C++
rali/source/node_nop.cpp
pruthvistony/MIVisionX
c3e2b360eb34ed7a75f3e08a4a7dfc256bfe801d
[ "MIT" ]
null
null
null
rali/source/node_nop.cpp
pruthvistony/MIVisionX
c3e2b360eb34ed7a75f3e08a4a7dfc256bfe801d
[ "MIT" ]
null
null
null
rali/source/node_nop.cpp
pruthvistony/MIVisionX
c3e2b360eb34ed7a75f3e08a4a7dfc256bfe801d
[ "MIT" ]
null
null
null
#include <vx_ext_rpp.h> #include "node_nop.h" #include "exception.h" NopNode::NopNode(const std::vector<Image*>& inputs, const std::vector<Image*>& outputs): Node(inputs, outputs) { } void NopNode::create(std::shared_ptr<Graph> graph) { if(_node) return; _graph = graph; if(_outputs.empty() || _inputs.empty()) THROW("Uninitialized input/output arguments") _node = vxExtrppNode_Nop(_graph->get(), _inputs[0]->handle(), _outputs[0]->handle()); vx_status status; if((status = vxGetStatus((vx_reference)_node)) != VX_SUCCESS) THROW("Adding the nop (vxNopNode) node failed: "+ TOSTR(status)) } void NopNode::update_parameters() { }
23.033333
89
0.66136
[ "vector" ]
3db49f743a6dd557dc3d04d824e51dc8c0c369f3
5,640
cpp
C++
src/lwvl/src/Shader.cpp
XakNitram/DVD
835045659be80a58de2a6669e0fe88c889d7eacd
[ "MIT" ]
null
null
null
src/lwvl/src/Shader.cpp
XakNitram/DVD
835045659be80a58de2a6669e0fe88c889d7eacd
[ "MIT" ]
null
null
null
src/lwvl/src/Shader.cpp
XakNitram/DVD
835045659be80a58de2a6669e0fe88c889d7eacd
[ "MIT" ]
null
null
null
#include "lwvl/lwvl.hpp" /* ****** Uniform ****** */ lwvl::Uniform::Uniform(int location) : m_location(location) {} void lwvl::Uniform::set(const int v0) { glUniform1i(m_location, v0); } void lwvl::Uniform::set(const float v0) { glUniform1f(m_location, v0); } void lwvl::Uniform::set(const unsigned int v0) { glUniform1ui(m_location, v0); } void lwvl::Uniform::set(const int v0, const int v1) { glUniform2i(m_location, v0, v1); } void lwvl::Uniform::set(const float v0, const float v1) { glUniform2f(m_location, v0, v1); } void lwvl::Uniform::set(const unsigned int v0, const unsigned int v1) { glUniform2ui(m_location, v0, v1); } void lwvl::Uniform::set(const int v0, const int v1, const int v2) { glUniform3i(m_location, v0, v1, v2); } void lwvl::Uniform::set(const float v0, const float v1, const float v2) { glUniform3f(m_location, v0, v1, v2); } void lwvl::Uniform::set(const unsigned int v0, const unsigned int v1, const unsigned int v2) { glUniform3ui( m_location, v0, v1, v2 ); } void lwvl::Uniform::set(const int v0, const int v1, const int v2, const int v3) { glUniform4i( m_location, v0, v1, v2, v3 ); } void lwvl::Uniform::set(const float v0, const float v1, const float v2, const float v3) { glUniform4f( m_location, v0, v1, v2, v3 ); } void lwvl::Uniform::set( const unsigned int v0, const unsigned int v1, const unsigned int v2, const unsigned int v3 ) { glUniform4ui(m_location, v0, v1, v2, v3); } void lwvl::Uniform::matrix4(const float *data) { glUniformMatrix4fv(m_location, 1, GL_FALSE, data); } void lwvl::Uniform::ortho(float top, float bottom, float right, float left, float far, float near) { float ortho[16] = { // top 3 rows 2.0f / (right - left), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (top - bottom), 0.0f, 0.0f, 0.0f, 0.0f, 2.0f / (far - near), 0.0f, // bottom row -(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1.0f }; glUniformMatrix4fv(m_location, 1, GL_FALSE, ortho); } void lwvl::Uniform::ortho2D(float top, float bottom, float right, float left) { float rlStein = 1.0f / (right - left); float tbStein = 1.0f / (top - bottom); float ortho[16] = { // top 3 rows 2.0f * rlStein, 0.0f, 0.0f, 0.0f, 0.0f, 2.0f * tbStein, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, -(right + left) * rlStein, -(top + bottom) * tbStein, 0.0f, 1.0f }; glUniformMatrix4fv(m_location, 1, GL_FALSE, ortho); } int lwvl::Uniform::location() const { return m_location; } /* ****** Shader ****** */ int lwvl::ShaderProgram::uniformLocation(const std::string &name) const { const int location = glGetUniformLocation(m_id, name.c_str()); if (location == -1) { std::stringstream msg; msg << "Uniform " << name << " not found."; throw std::exception(msg.str().c_str()); } else { return location; } } unsigned int lwvl::ShaderProgram::id() const { return m_id; } lwvl::Uniform lwvl::ShaderProgram::uniform(const std::string &name) { int location = uniformLocation(name); return Uniform(location); } void lwvl::ShaderProgram::link() { /* Links the program object. * https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glLinkProgram.xhtml * * If any shader objects of type GL_VERTEX_SHADER are attached to program, * they will be used to create an executable that will run on the programmable vertex processor. * * If any shader objects of type GL_GEOMETRY_SHADER are attached to program, * they will be used to create an executable that will run on the programmable geometry processor. * * If any shader objects of type GL_FRAGMENT_SHADER are attached to program, * they will be used to create an executable that will run on the programmable fragment processor. */ glLinkProgram(m_id); // assert(glGetProgramiv(m_offsite_id, GL_LINK_STATUS) == GL_TRUE); // assertion because the user can't change enough with shader files to break this. glValidateProgram(m_id); // assert(glGetProgramiv(m_offsite_id, GL_VALIDATION_STATUS) == GL_TRUE); /* Checks to see whether the executables contained in program can execute given the current OpenGL state. * https://www.khronos.org/registry/OpenGL-Refpages/gl4/html/glValidateProgram.xhtml * * The error GL_INVALID_OPERATION will be generated by any command that triggers the rendering of geometry if: * . Any two active samplers in the current program object are of different types, but refer to the same texture image unit * . The number of active samplers in the program exceeds the maximum number of texture image units allowed * * It may be difficult or cause a performance degradation for applications to catch these errors when rendering commands are issued. * Therefore, applications are advised to make calls to glValidateProgram to detect these issues during application development. */ } void lwvl::ShaderProgram::link(const VertexShader &vs, const FragmentShader &fs) { glAttachShader(m_id, vs.m_id); glAttachShader(m_id, fs.m_id); link(); glDetachShader(m_id, vs.m_id); glDetachShader(m_id, fs.m_id); } void lwvl::ShaderProgram::link(const std::string &vertexSource, const std::string &fragmentSource) { VertexShader vs(vertexSource); FragmentShader fs(fragmentSource); link(vs, fs); } void lwvl::ShaderProgram::bind() const { glUseProgram(m_id); } void lwvl::ShaderProgram::clear() { glUseProgram(0); }
34.601227
135
0.671099
[ "geometry", "object" ]
3dbea4486d7c57e373d257e0888741e5cf60b05c
306,150
cpp
C++
net/mmc/dhcp/scope.cpp
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
net/mmc/dhcp/scope.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
net/mmc/dhcp/scope.cpp
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/**********************************************************************/ /** Microsoft Windows/NT **/ /** Copyright(c) Microsoft Corporation, 1997 - 1999 **/ /**********************************************************************/ /* scope.cpp This file contains all of the implementation for the DHCP scope object and all objects that it may contain. They include: CDhcpScope CDhcpReservations CDhcpReservationClient CDhcpActiveLeases CDhcpAddressPool CDhcpScopeOptions FILE HISTORY: */ #include "stdafx.h" #include "server.h" // server object #include "scope.h" // scope object #include "scopepp.h" // scope property page #include "addbootp.h" // add BOOTP entry dialog #include "addexcl.h" // add exclusion range dialog #include "addres.h" // add reservation dialog #include "rclntpp.h" // reserved client property page #include "nodes.h" // all node (result pane) definitions #include "optcfg.h" // option configuration sheet #include "dlgrecon.h" // reconcile database dialog #include "scopstat.h" // scope statistics #include "addtoss.h" // add scope to superscope dialog WORD gwUnicodeHeader = 0xFEFF; // scope options result pane message stuff #define SCOPE_OPTIONS_MESSAGE_MAX_STRING 5 typedef enum _SCOPE_OPTIONS_MESSAGES { SCOPE_OPTIONS_MESSAGE_NO_OPTIONS, SCOPE_OPTIONS_MESSAGE_MAX }; UINT g_uScopeOptionsMessages[SCOPE_OPTIONS_MESSAGE_MAX][SCOPE_OPTIONS_MESSAGE_MAX_STRING] = { {IDS_SCOPE_OPTIONS_MESSAGE_TITLE, Icon_Information, IDS_SCOPE_OPTIONS_MESSAGE_BODY, 0, 0} }; // reservation options result pane message stuff #define RES_OPTIONS_MESSAGE_MAX_STRING 5 typedef enum _RES_OPTIONS_MESSAGES { RES_OPTIONS_MESSAGE_NO_OPTIONS, RES_OPTIONS_MESSAGE_MAX }; UINT g_uResOptionsMessages[RES_OPTIONS_MESSAGE_MAX][RES_OPTIONS_MESSAGE_MAX_STRING] = { {IDS_RES_OPTIONS_MESSAGE_TITLE, Icon_Information, IDS_RES_OPTIONS_MESSAGE_BODY, 0, 0} }; // reservations result pane message stuff #define RESERVATIONS_MESSAGE_MAX_STRING 5 typedef enum _RESERVATIONS_MESSAGES { RESERVATIONS_MESSAGE_NO_RES, RESERVATIONS_MESSAGE_MAX }; UINT g_uReservationsMessages[RESERVATIONS_MESSAGE_MAX][RESERVATIONS_MESSAGE_MAX_STRING] = { {IDS_RESERVATIONS_MESSAGE_TITLE, Icon_Information, IDS_RESERVATIONS_MESSAGE_BODY, 0, 0} }; /*--------------------------------------------------------------------------- Class CDhcpScope implementation ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScope::CDhcpScope Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpScope::CDhcpScope ( ITFSComponentData * pComponentData, DHCP_IP_ADDRESS dhcpScopeIp, DHCP_IP_MASK dhcpSubnetMask, LPCWSTR pName, LPCWSTR pComment, DHCP_SUBNET_STATE dhcpSubnetState ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // save off some parameters // m_dhcpIpAddress = dhcpScopeIp; m_dhcpSubnetMask = dhcpSubnetMask; m_strName = pName; m_strComment = pComment; m_dhcpSubnetState = dhcpSubnetState; m_bInSuperscope = FALSE; } /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpScope::CDhcpScope ( ITFSComponentData * pComponentData, LPDHCP_SUBNET_INFO pdhcpSubnetInfo ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // save off some parameters // m_dhcpIpAddress = pdhcpSubnetInfo->SubnetAddress; m_dhcpSubnetMask = pdhcpSubnetInfo->SubnetMask; m_strName = pdhcpSubnetInfo->SubnetName; m_strComment = pdhcpSubnetInfo->SubnetComment; m_dhcpSubnetState = pdhcpSubnetInfo->SubnetState; m_bInSuperscope = FALSE; } /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpScope::CDhcpScope ( ITFSComponentData * pComponentData, CSubnetInfo & subnetInfo ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // save off some parameters // m_dhcpIpAddress = subnetInfo.SubnetAddress; m_dhcpSubnetMask = subnetInfo.SubnetMask; m_strName = subnetInfo.SubnetName; m_strComment = subnetInfo.SubnetComment; m_dhcpSubnetState = subnetInfo.SubnetState; m_bInSuperscope = FALSE; } CDhcpScope::~CDhcpScope() { } /*!-------------------------------------------------------------------------- CDhcpScope::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; int nImage; // // Create the display name for this scope // CString strDisplay, strIpAddress; UtilCvtIpAddrToWstr (m_dhcpIpAddress, &strIpAddress); BuildDisplayName(&strDisplay, strIpAddress, m_strName); SetDisplayName(strDisplay); // // Figure out the correct icon // if ( !IsEnabled() ) { m_strState.LoadString(IDS_SCOPE_INACTIVE); } else { m_strState.LoadString(IDS_SCOPE_ACTIVE); } // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_SCOPE); SetColumnStringIDs(&aColumns[DHCPSNAP_SCOPE][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_SCOPE][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpScope::DestroyHandler We need to free up any resources we are holding Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScope::DestroyHandler(ITFSNode *pNode) { // cleanup the stats dialog WaitForStatisticsWindow(&m_dlgStats); return CMTDhcpHandler::DestroyHandler(pNode); } /*--------------------------------------------------------------------------- CDhcpScope::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); UtilCvtIpAddrToWstr (m_dhcpIpAddress, &strIpAddress); strId = GetServerObject()->GetName() + strIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpScope::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpScope::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { // TODO: these need to be updated with new busy state icons case loading: if (bOpenImage) nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_OPEN_BUSY : ICON_IDX_SCOPE_FOLDER_OPEN_BUSY; else nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_CLOSED_BUSY : ICON_IDX_SCOPE_FOLDER_CLOSED_BUSY; return nIndex; case notLoaded: case loaded: if (bOpenImage) nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_OPEN : ICON_IDX_SCOPE_INACTIVE_FOLDER_OPEN; else nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_CLOSED : ICON_IDX_SCOPE_INACTIVE_FOLDER_CLOSED; break; case unableToLoad: if (bOpenImage) nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_OPEN_LOST_CONNECTION : ICON_IDX_SCOPE_INACTIVE_FOLDER_OPEN_LOST_CONNECTION; else nIndex = (IsEnabled()) ? ICON_IDX_SCOPE_FOLDER_CLOSED_LOST_CONNECTION : ICON_IDX_SCOPE_INACTIVE_FOLDER_CLOSED_LOST_CONNECTION; return nIndex; default: ASSERT(FALSE); } // only calcualte alert/warnings if the scope is enabled. if (m_spServerNode && IsEnabled()) { CDhcpServer * pServer = GetServerObject(); LPDHCP_MIB_INFO pMibInfo = pServer->DuplicateMibInfo(); if (!pMibInfo) return nIndex; LPSCOPE_MIB_INFO pScopeMibInfo = pMibInfo->ScopeInfo; // walk the list of scopes and find our info for (UINT i = 0; i < pMibInfo->Scopes; i++) { // Find our scope stats if (pScopeMibInfo[i].Subnet == m_dhcpIpAddress) { int nPercentInUse; if ((pScopeMibInfo[i].NumAddressesInuse + pScopeMibInfo[i].NumAddressesFree) == 0) nPercentInUse = 0; else nPercentInUse = (pScopeMibInfo[i].NumAddressesInuse * 100) / (pScopeMibInfo[i].NumAddressesInuse + pScopeMibInfo[i].NumAddressesFree); // look to see if this scope meets the warning or red flag case if (pScopeMibInfo[i].NumAddressesFree == 0) { // red flag case, no addresses free, this is the highest // level of warning, so break out of the loop if we set this. if (bOpenImage) nIndex = ICON_IDX_SCOPE_FOLDER_OPEN_ALERT; else nIndex = ICON_IDX_SCOPE_FOLDER_CLOSED_ALERT; break; } else if (nPercentInUse >= SCOPE_WARNING_LEVEL) { // warning condition if Num Addresses in use is greater than // some pre-defined threshold. if (bOpenImage) nIndex = ICON_IDX_SCOPE_FOLDER_OPEN_WARNING; else nIndex = ICON_IDX_SCOPE_FOLDER_CLOSED_WARNING; } break; } } pServer->FreeDupMibInfo(pMibInfo); } return nIndex; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScope::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScope::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // Get the version of the server LONG fFlags = 0; LARGE_INTEGER liDhcpVersion; CDhcpServer * pServer = GetServerObject(); pServer->GetVersion(liDhcpVersion); HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { // // these menu items go in the new menu, // only visible from scope pane // if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { strMenuText.LoadString(IDS_SCOPE_SHOW_STATISTICS); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_SCOPE_SHOW_STATISTICS, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); // separator hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, 0, CCM_INSERTIONPOINTID_PRIMARY_TOP, MF_SEPARATOR); ASSERT( SUCCEEDED(hr) ); // reconcile is only supports for NT4 SP2 and greater. if (liDhcpVersion.QuadPart >= DHCP_SP2_VERSION) { strMenuText.LoadString(IDS_SCOPE_RECONCILE); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_SCOPE_RECONCILE, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } // Superscope support only on NT4 SP2 and greater if (liDhcpVersion.QuadPart >= DHCP_SP2_VERSION) { int nID = 0; if (IsInSuperscope()) { nID = IDS_SCOPE_REMOVE_SUPERSCOPE; } else { // check to see if there are superscopes to add to SPITFSNode spNode; pNode->GetParent(&spNode); pServer = GETHANDLER(CDhcpServer, spNode); if (pServer->HasSuperscopes(spNode)) nID = IDS_SCOPE_ADD_SUPERSCOPE; } // load the menu item if we need to if (nID) { strMenuText.LoadString(nID); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, nID, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } // separator hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, 0, CCM_INSERTIONPOINTID_PRIMARY_TOP, MF_SEPARATOR); ASSERT( SUCCEEDED(hr) ); // activate/deactivate if ( !IsEnabled() ) { strMenuText.LoadString(IDS_SCOPE_ACTIVATE); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_SCOPE_ACTIVATE, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } else { strMenuText.LoadString(IDS_SCOPE_DEACTIVATE); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_SCOPE_DEACTIVATE, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } } return hr; } /*--------------------------------------------------------------------------- CDhcpScope::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScope::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_ACTIVATE: case IDS_DEACTIVATE: case IDS_SCOPE_ACTIVATE: case IDS_SCOPE_DEACTIVATE: OnActivateScope(pNode); break; case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; case IDS_SCOPE_SHOW_STATISTICS: OnShowScopeStats(pNode); break; case IDS_SCOPE_RECONCILE: OnReconcileScope(pNode); break; case IDS_DELETE: OnDelete(pNode); break; case IDS_SCOPE_ADD_SUPERSCOPE: OnAddToSuperscope(pNode); break; case IDS_SCOPE_REMOVE_SUPERSCOPE: OnRemoveFromSuperscope(pNode); break; default: break; } return hr; } /*!-------------------------------------------------------------------------- CDhcpScope::OnDelete The base handler calls this when MMC sends a MMCN_DELETE for a scope pane item. We just call our delete command handler. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnDelete ( ITFSNode * pNode, LPARAM arg, LPARAM lParam ) { return OnDelete(pNode); } /*!-------------------------------------------------------------------------- CDhcpScope::HasPropertyPages Says whether or not this handler has property pages Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScope::HasPropertyPages ( ITFSNode * pNode, LPDATAOBJECT pDataObject, DATA_OBJECT_TYPES type, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; if (dwType & TFS_COMPDATA_CREATE) { // This is the case where we are asked to bring up property // pages when the user is adding a new snapin. These calls // are forwarded to the root node to handle. // Should never get here!! Assert(FALSE); hr = S_FALSE; } else { // we have property pages in the normal case hr = hrOK; } return hr; } /*--------------------------------------------------------------------------- CDhcpScope::CreatePropertyPages Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScope::CreatePropertyPages ( ITFSNode * pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; DWORD dwError; DWORD dwDynDnsFlags; SPIComponentData spComponentData; LARGE_INTEGER liVersion; CDhcpServer * pServer; CDhcpIpRange dhcpIpRange; // // Create the property page // m_spNodeMgr->GetComponentData(&spComponentData); CScopeProperties * pScopeProp = new CScopeProperties(pNode, spComponentData, m_spTFSCompData, NULL); // Get the Server version and set it in the property sheet pServer = GetServerObject(); pServer->GetVersion(liVersion); pScopeProp->SetVersion(liVersion); pScopeProp->SetSupportsDynBootp(pServer->FSupportsDynBootp()); // Set scope specific data in the prop sheet pScopeProp->m_pageGeneral.m_strName = m_strName; pScopeProp->m_pageGeneral.m_strComment = m_strComment; BEGIN_WAIT_CURSOR; dwError = GetIpRange(&dhcpIpRange); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } pScopeProp->m_pageGeneral.m_dwStartAddress = dhcpIpRange.QueryAddr(TRUE); pScopeProp->m_pageGeneral.m_dwEndAddress = dhcpIpRange.QueryAddr(FALSE); pScopeProp->m_pageGeneral.m_dwSubnetMask = m_dhcpSubnetMask; pScopeProp->m_pageGeneral.m_uImage = GetImageIndex(FALSE); pScopeProp->m_pageAdvanced.m_RangeType = dhcpIpRange.GetRangeType(); GetLeaseTime(&pScopeProp->m_pageGeneral.m_dwLeaseTime); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } if (pServer->FSupportsDynBootp()) { GetDynBootpLeaseTime(&pScopeProp->m_pageAdvanced.m_dwLeaseTime); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } } // set the DNS registration option dwError = GetDnsRegistration(&dwDynDnsFlags); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } END_WAIT_CURSOR; pScopeProp->SetDnsRegistration(dwDynDnsFlags, DhcpSubnetOptions); // // Object gets deleted when the page is destroyed // Assert(lpProvider != NULL); return pScopeProp->CreateModelessSheet(lpProvider, handle); } /*!-------------------------------------------------------------------------- CDhcpScope::GetString Returns string information for display in the result pane columns Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(LPCTSTR) CDhcpScope::GetString ( ITFSNode * pNode, int nCol ) { switch (nCol) { case 0: return GetDisplayName(); case 1: return m_strState; case 2: return m_strComment; } return NULL; } /*--------------------------------------------------------------------------- CDhcpScope::OnPropertyChange Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnPropertyChange ( ITFSNode * pNode, LPDATAOBJECT pDataobject, DWORD dwType, LPARAM arg, LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CScopeProperties * pScopeProp = reinterpret_cast<CScopeProperties *>(lParam); LONG_PTR changeMask = 0; // tell the property page to do whatever now that we are back on the // main thread pScopeProp->OnPropertyChange(TRUE, &changeMask); pScopeProp->AcknowledgeNotify(); if (changeMask) pNode->ChangeNode(changeMask); return hrOK; } /*!-------------------------------------------------------------------------- CDhcpScope::OnUpdateToolbarButtons We override this function to show/hide the correct activate/deactivate buttons Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnUpdateToolbarButtons ( ITFSNode * pNode, LPDHCPTOOLBARNOTIFY pToolbarNotify ) { HRESULT hr = hrOK; if (pToolbarNotify->bSelect) { UpdateToolbarStates(); } CMTDhcpHandler::OnUpdateToolbarButtons(pNode, pToolbarNotify); return hr; } /*!-------------------------------------------------------------------------- CDhcpScope::UpdateToolbarStates Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::UpdateToolbarStates() { if ( !IsEnabled() ) { g_SnapinButtonStates[DHCPSNAP_SCOPE][TOOLBAR_IDX_ACTIVATE] = ENABLED; g_SnapinButtonStates[DHCPSNAP_SCOPE][TOOLBAR_IDX_DEACTIVATE] = HIDDEN; } else { g_SnapinButtonStates[DHCPSNAP_SCOPE][TOOLBAR_IDX_ACTIVATE] = HIDDEN; g_SnapinButtonStates[DHCPSNAP_SCOPE][TOOLBAR_IDX_DEACTIVATE] = ENABLED; } } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScope:OnHaveData Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::OnHaveData ( ITFSNode * pParentNode, ITFSNode * pNewNode ) { if (pNewNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_ACTIVE_LEASES) { pParentNode->AddChild(pNewNode); m_spActiveLeases.Set(pNewNode); } else if (pNewNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_ADDRESS_POOL) { pParentNode->AddChild(pNewNode); m_spAddressPool.Set(pNewNode); } else if (pNewNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_RESERVATIONS) { pParentNode->AddChild(pNewNode); m_spReservations.Set(pNewNode); } else if (pNewNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_SCOPE_OPTIONS) { pParentNode->AddChild(pNewNode); m_spOptions.Set(pNewNode); } // now tell the view to update themselves ExpandNode(pParentNode, TRUE); } /*--------------------------------------------------------------------------- CDhcpScope::OnHaveData Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::OnHaveData ( ITFSNode * pParentNode, LPARAM Data, LPARAM Type ) { // This is how we get non-node data back from the background thread. switch (Type) { case DHCP_QDATA_SUBNET_INFO: { LONG_PTR changeMask = 0; LPDHCP_SUBNET_INFO pdhcpSubnetInfo = reinterpret_cast<LPDHCP_SUBNET_INFO>(Data); // update the scope name and state based on the info if (m_strName.CompareNoCase(pdhcpSubnetInfo->SubnetName) != 0) { CString strDisplay, strIpAddress; m_strName = pdhcpSubnetInfo->SubnetName; UtilCvtIpAddrToWstr (m_dhcpIpAddress, &strIpAddress); BuildDisplayName(&strDisplay, strIpAddress, m_strName); SetDisplayName(strDisplay); changeMask = SCOPE_PANE_CHANGE_ITEM; } if (m_dhcpSubnetState != pdhcpSubnetInfo->SubnetState) { DHCP_SUBNET_STATE dhcpOldState = m_dhcpSubnetState; m_dhcpSubnetState = pdhcpSubnetInfo->SubnetState; // Tell the scope to update it's state DWORD err = SetInfo(); if (err != 0) { ::DhcpMessageBox(err); m_dhcpSubnetState = dhcpOldState; } else { pParentNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pParentNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); // Update the toolbar button UpdateToolbarStates(); SendUpdateToolbar(pParentNode, TRUE); // need to notify the owning superscope to update it's state information // this is strictly for UI purposes only. if (IsInSuperscope()) { SPITFSNode spSuperscopeNode; pParentNode->GetParent(&spSuperscopeNode); CDhcpSuperscope * pSuperscope = GETHANDLER(CDhcpSuperscope, spSuperscopeNode); Assert(pSuperscope); pSuperscope->NotifyScopeStateChange(spSuperscopeNode, m_dhcpSubnetState); } changeMask = SCOPE_PANE_CHANGE_ITEM; } } if (pdhcpSubnetInfo) ::DhcpRpcFreeMemory(pdhcpSubnetInfo); if (changeMask) VERIFY(SUCCEEDED(pParentNode->ChangeNode(changeMask))); } break; case DHCP_QDATA_OPTION_VALUES: { COptionValueEnum * pOptionValueEnum = reinterpret_cast<COptionValueEnum *>(Data); SetOptionValueEnum(pOptionValueEnum); pOptionValueEnum->RemoveAll(); delete pOptionValueEnum; break; } default: break; } } /*--------------------------------------------------------------------------- CDhcpScope::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpScope::OnCreateQuery(ITFSNode * pNode) { CDhcpScopeQueryObj* pQuery = new CDhcpScopeQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(); pQuery->m_dhcpScopeAddress = GetAddress(); GetServerVersion(pQuery->m_liVersion); return pQuery; } /*--------------------------------------------------------------------------- CDhcpScope::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeQueryObj::Execute() { HRESULT hr = hrOK; DWORD dwReturn; LPDHCP_SUBNET_INFO pdhcpSubnetInfo = NULL; DHCP_OPTION_SCOPE_INFO dhcpOptionScopeInfo; COptionValueEnum * pOptionValueEnum = NULL; dwReturn = ::DhcpGetSubnetInfo(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, &pdhcpSubnetInfo); if (dwReturn == ERROR_SUCCESS && pdhcpSubnetInfo) { AddToQueue((LPARAM) pdhcpSubnetInfo, DHCP_QDATA_SUBNET_INFO); } else { Trace1("CDhcpScopeQueryObj::Execute - DhcpGetSubnetInfo failed! %d\n", dwReturn); PostError(dwReturn); return hrFalse; } // get the option info for this scope pOptionValueEnum = new COptionValueEnum(); dhcpOptionScopeInfo.ScopeType = DhcpSubnetOptions; dhcpOptionScopeInfo.ScopeInfo.SubnetScopeInfo = m_dhcpScopeAddress; pOptionValueEnum->Init(m_strServer, m_liVersion, dhcpOptionScopeInfo); dwReturn = pOptionValueEnum->Enum(); if (dwReturn != ERROR_SUCCESS) { Trace1("CDhcpScopeQueryObj::Execute - EnumOptions Failed! %d\n", dwReturn); m_dwErr = dwReturn; PostError(dwReturn); delete pOptionValueEnum; } else { pOptionValueEnum->SortById(); AddToQueue((LPARAM) pOptionValueEnum, DHCP_QDATA_OPTION_VALUES); } // now create the scope subcontainers CreateSubcontainers(); return hrFalse; } /*--------------------------------------------------------------------------- CDhcpScope::CreateSubcontainers() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeQueryObj::CreateSubcontainers() { HRESULT hr = hrOK; SPITFSNode spNode; // // create the address pool Handler // CDhcpAddressPool *pAddressPool = new CDhcpAddressPool(m_spTFSCompData); CreateContainerTFSNode(&spNode, &GUID_DhcpAddressPoolNodeType, pAddressPool, pAddressPool, m_spNodeMgr); // Tell the handler to initialize any specific data pAddressPool->InitializeNode((ITFSNode *) spNode); // Add the node as a child to this node AddToQueue(spNode); pAddressPool->Release(); spNode.Set(NULL); // // create the Active Leases Handler // CDhcpActiveLeases *pActiveLeases = new CDhcpActiveLeases(m_spTFSCompData); CreateContainerTFSNode(&spNode, &GUID_DhcpActiveLeasesNodeType, pActiveLeases, pActiveLeases, m_spNodeMgr); // Tell the handler to initialize any specific data pActiveLeases->InitializeNode((ITFSNode *) spNode); // Add the node as a child to this node AddToQueue(spNode); pActiveLeases->Release(); spNode.Set(NULL); // // create the reservations Handler // CDhcpReservations *pReservations = new CDhcpReservations(m_spTFSCompData); CreateContainerTFSNode(&spNode, &GUID_DhcpReservationsNodeType, pReservations, pReservations, m_spNodeMgr); // Tell the handler to initialize any specific data pReservations->InitializeNode((ITFSNode *) spNode); // Add the node as a child to this node AddToQueue(spNode); pReservations->Release(); spNode.Set(NULL); // // create the Scope Options Handler // CDhcpScopeOptions *pScopeOptions = new CDhcpScopeOptions(m_spTFSCompData); CreateContainerTFSNode(&spNode, &GUID_DhcpScopeOptionsNodeType, pScopeOptions, pScopeOptions, m_spNodeMgr); // Tell the handler to initialize any specific data pScopeOptions->InitializeNode((ITFSNode *) spNode); // Add the node as a child to this node AddToQueue(spNode); pScopeOptions->Release(); return hr; } /*--------------------------------------------------------------------------- Command handlers ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScope::OnActivateScope Message handler for the scope activate/deactivate menu Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::OnActivateScope ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); DWORD err = 0; int nOpenImage, nClosedImage; DHCP_SUBNET_STATE dhcpOldState = m_dhcpSubnetState; if ( IsEnabled() ) { // if they want to disable the scope, confirm if (AfxMessageBox(IDS_SCOPE_DISABLE_CONFIRM, MB_YESNO) != IDYES) { return err; } } SetState( IsEnabled()? DhcpSubnetDisabled : DhcpSubnetEnabled ); // Tell the scope to update it's state err = SetInfo(); if (err != 0) { ::DhcpMessageBox(err); m_dhcpSubnetState = dhcpOldState; } else { // update the icon and the status text if ( !IsEnabled() ) { nOpenImage = ICON_IDX_SCOPE_INACTIVE_FOLDER_OPEN; nClosedImage = ICON_IDX_SCOPE_INACTIVE_FOLDER_CLOSED; m_strState.LoadString(IDS_SCOPE_INACTIVE); } else { nOpenImage = GetImageIndex(TRUE); nClosedImage = GetImageIndex(FALSE); m_strState.LoadString(IDS_SCOPE_ACTIVE); } pNode->SetData(TFS_DATA_IMAGEINDEX, nClosedImage); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, nOpenImage); VERIFY(SUCCEEDED(pNode->ChangeNode(SCOPE_PANE_CHANGE_ITEM))); // Update the toolbar button UpdateToolbarStates(); SendUpdateToolbar(pNode, TRUE); // need to notify the owning superscope to update it's state information // this is strictly for UI purposes only. if (IsInSuperscope()) { SPITFSNode spSuperscopeNode; pNode->GetParent(&spSuperscopeNode); CDhcpSuperscope * pSuperscope = GETHANDLER(CDhcpSuperscope, spSuperscopeNode); Assert(pSuperscope); pSuperscope->NotifyScopeStateChange(spSuperscopeNode, m_dhcpSubnetState); } } TriggerStatsRefresh(); return err; } /*--------------------------------------------------------------------------- CDhcpScope::OnRefreshScope Refreshes all of the subnodes of the scope Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnRefreshScope ( ITFSNode * pNode, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = hrOK; CDhcpReservations * pReservations = GetReservationsObject(); CDhcpActiveLeases * pActiveLeases = GetActiveLeasesObject(); CDhcpAddressPool * pAddressPool = GetAddressPoolObject(); CDhcpScopeOptions * pScopeOptions = GetScopeOptionsObject(); Assert(pReservations); Assert(pActiveLeases); Assert(pAddressPool); Assert(pScopeOptions); if (pReservations) pReservations->OnRefresh(m_spReservations, pDataObject, dwType, 0, 0); if (pActiveLeases) pActiveLeases->OnRefresh(m_spActiveLeases, pDataObject, dwType, 0, 0); if (pAddressPool) pAddressPool->OnRefresh(m_spAddressPool, pDataObject, dwType, 0, 0); if (pScopeOptions) pScopeOptions->OnRefresh(m_spOptions, pDataObject, dwType, 0, 0); return hr; } /*--------------------------------------------------------------------------- CDhcpScope::OnReconcileScope Reconciles the active leases database for this scope Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnReconcileScope ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CReconcileDlg dlgRecon(pNode); dlgRecon.DoModal(); return hrOK; } /*--------------------------------------------------------------------------- CDhcpScope::OnShowScopeStats() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnShowScopeStats ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = S_OK; CString strScopeAddress; // Fill in some information in the stats object. // CreateNewStatisticsWindow handles the case if the window is // already visible. m_dlgStats.SetNode(pNode); m_dlgStats.SetServer(GetServerIpAddress()); m_dlgStats.SetScope(m_dhcpIpAddress); CreateNewStatisticsWindow(&m_dlgStats, ::FindMMCMainWindow(), IDD_STATS_NARROW); return hr; } /*--------------------------------------------------------------------------- CDhcpScope::OnDelete() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnDelete(ITFSNode * pNode) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = S_OK; SPITFSNode spServer; SPITFSNode spSuperscopeNode; int nVisible = 0, nTotal = 0; int nResponse; LONG err = 0 ; if (IsInSuperscope()) { pNode->GetParent(&spSuperscopeNode); spSuperscopeNode->GetChildCount(&nVisible, &nTotal); } if (nTotal == 1) { // warn the user that this is the last scope in the superscope // and the superscope will be removed. nResponse = AfxMessageBox(IDS_DELETE_LAST_SCOPE_FROM_SS, MB_YESNO); } else { nResponse = ::DhcpMessageBox( IsEnabled() ? IDS_MSG_DELETE_ACTIVE : IDS_MSG_DELETE_SCOPE, MB_YESNO | MB_DEFBUTTON2 | MB_ICONQUESTION); } if (nResponse == IDYES) { SPITFSNode spTemp; if (IsInSuperscope()) { // superscope spTemp.Set(spSuperscopeNode); } else { spTemp.Set(pNode); } spTemp->GetParent(&spServer); CDhcpServer * pServer = GETHANDLER(CDhcpServer, spServer); err = pServer->DeleteScope(pNode); if (err == ERROR_SUCCESS && nTotal == 1) { // gotta remove the superscope spServer->RemoveChild(spSuperscopeNode); } } // trigger the statistics to refresh only if we removed this scope if (spServer) { TriggerStatsRefresh(); } return hr; } /*--------------------------------------------------------------------------- CDhcpScope::OnAddToSuperscope() Adds this scope to a superscope Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnAddToSuperscope ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CString strTitle, strAddress; UtilCvtIpAddrToWstr(m_dhcpIpAddress, &strAddress); AfxFormatString1(strTitle, IDS_ADD_SCOPE_DLG_TITLE, strAddress); CAddScopeToSuperscope dlgAddScope(pNode, strTitle); dlgAddScope.DoModal(); return hrOK; } /*--------------------------------------------------------------------------- CDhcpScope::OnRemoveFromSuperscope() Removes this scope from a superscope Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::OnRemoveFromSuperscope ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); int nVisible, nTotal, nResponse; SPITFSNode spSuperscopeNode; pNode->GetParent(&spSuperscopeNode); spSuperscopeNode->GetChildCount(&nVisible, &nTotal); if (nTotal == 1) { // warn the user that this is the last scope in the superscope // and the superscope will be removed. nResponse = AfxMessageBox(IDS_REMOVE_LAST_SCOPE_FROM_SS, MB_YESNO); } else { nResponse = AfxMessageBox(IDS_REMOVE_SCOPE_FROM_SS, MB_YESNO); } if (nResponse == IDYES) { // set the superscope for this scope to be NULL // effectively removing it from the scope. DWORD dwError = SetSuperscope(NULL, TRUE); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } // now move the scope out of the supersope in the UI spSuperscopeNode->ExtractChild(pNode); // now put the scope node back in at the server level. SPITFSNode spServerNode; spSuperscopeNode->GetParent(&spServerNode); CDhcpServer * pServer = GETHANDLER(CDhcpServer, spServerNode); pServer->AddScopeSorted(spServerNode, pNode); SetInSuperscope(FALSE); if (nTotal == 1) { // now delete the superscope. spServerNode->RemoveChild(spSuperscopeNode); } } return hrOK; } /*--------------------------------------------------------------------------- CDhcpScope::UpdateStatistics Notification that stats are now available. Update stats for the node and give all subnodes a chance to update. Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::UpdateStatistics ( ITFSNode * pNode ) { HRESULT hr = hrOK; SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned; HWND hStatsWnd; BOOL bChangeIcon = FALSE; // Check to see if this node has a stats sheet up. hStatsWnd = m_dlgStats.GetSafeHwnd(); if (hStatsWnd != NULL) { PostMessage(hStatsWnd, WM_NEW_STATS_AVAILABLE, 0, 0); } if (!IsEnabled()) return hr; // check to see if the image index has changed and only // switch it if we have to--this avoids flickering. LONG_PTR nOldIndex = pNode->GetData(TFS_DATA_IMAGEINDEX); int nNewIndex = GetImageIndex(FALSE); if (nOldIndex != nNewIndex) { pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->ChangeNode(SCOPE_PANE_CHANGE_ITEM_ICON); } return hr; } /*--------------------------------------------------------------------------- Scope manipulation functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScope::SetState Sets the state for this scope - updates cached information and display string Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::SetState ( DHCP_SUBNET_STATE dhcpSubnetState ) { BOOL fSwitched = FALSE; if( m_dhcpSubnetState != DhcpSubnetEnabled && m_dhcpSubnetState != DhcpSubnetDisabled ) { fSwitched = TRUE; } if( fSwitched ) { if( dhcpSubnetState == DhcpSubnetEnabled ) { dhcpSubnetState = DhcpSubnetEnabledSwitched; } else { dhcpSubnetState = DhcpSubnetDisabledSwitched; } } m_dhcpSubnetState = dhcpSubnetState; // update the status text if ( !IsEnabled() ) { m_strState.LoadString(IDS_SCOPE_INACTIVE); } else { m_strState.LoadString(IDS_SCOPE_ACTIVE); } } /*--------------------------------------------------------------------------- CDhcpScope::CreateReservation Creates a reservation for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::CreateReservation ( const CDhcpClient * pClient ) { SPITFSNode spResClientNode, spActiveLeaseNode; DWORD err = 0; // // Tell the DHCP server to create this client // err = CreateClient(pClient); if (err != 0) return err; // // Now that we have this reservation on the server, create the UI object // in both the reservation folder and the ActiveLeases folder // // create the Reservation client folder // CDhcpReservations * pRes = GETHANDLER(CDhcpReservations, m_spReservations); CDhcpActiveLeases * pActLeases = GETHANDLER(CDhcpActiveLeases, m_spActiveLeases); // only add to the UI if the node is expanded. MMC will fail the call if // we try to add a child to a node that hasn't been expanded. If we don't add // it now, it will be enumerated when the user selects the node. if (pRes->m_bExpanded) { CDhcpReservationClient * pNewResClient = new CDhcpReservationClient(m_spTFSCompData, (CDhcpClient&) *pClient); CreateContainerTFSNode(&spResClientNode, &GUID_DhcpReservationClientNodeType, pNewResClient, pNewResClient, m_spNodeMgr); // Tell the handler to initialize any specific data pNewResClient->InitializeNode((ITFSNode *) spResClientNode); // Add the node as a child to this node CDhcpReservations * pReservations = GETHANDLER(CDhcpReservations, m_spReservations); pReservations->AddReservationSorted(m_spReservations, spResClientNode); pNewResClient->Release(); } // // Active Lease record // if (pActLeases->m_bExpanded) { CDhcpActiveLease * pNewLease = new CDhcpActiveLease(m_spTFSCompData, (CDhcpClient&) *pClient); CreateLeafTFSNode(&spActiveLeaseNode, &GUID_DhcpActiveLeaseNodeType, pNewLease, pNewLease, m_spNodeMgr); // Tell the handler to initialize any specific data pNewLease->InitializeNode((ITFSNode *) spActiveLeaseNode); // Add the node as a child to the Active Leases container m_spActiveLeases->AddChild(spActiveLeaseNode); pNewLease->Release(); } return err; } /*--------------------------------------------------------------------------- CDhcpScope::UpdateReservation Creates a reservation for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::UpdateReservation ( const CDhcpClient * pClient, COptionValueEnum * pOptionValueEnum ) { DWORD err = 0; const CByteArray & baHardwareAddress = pClient->QueryHardwareAddress(); SPITFSNode spResClientNode, spActiveLeaseNode; // // To update a reservation we need to remove the old one and update it // with the new information. This is mostly for the client type field. // err = DeleteReservation((CByteArray&) baHardwareAddress, pClient->QueryIpAddress()); // now add the updated one err = AddReservation(pClient); if (err != ERROR_SUCCESS) return err; // restore the options for this reserved client err = RestoreReservationOptions(pClient, pOptionValueEnum); if (err != ERROR_SUCCESS) return err; // Now update the client info record associated with this. err = SetClientInfo(pClient); return err; } /*--------------------------------------------------------------------------- CDhcpScope::RestoreReservationOptions Restores options when updating a reservation becuase the only way to update the reservation is to remove it and re-add it. Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RestoreReservationOptions ( const CDhcpClient * pClient, COptionValueEnum * pOptionValueEnum ) { DWORD dwErr = ERROR_SUCCESS; CDhcpOption * pCurOption; LARGE_INTEGER liVersion; GetServerVersion(liVersion); // start at the top of the list pOptionValueEnum->Reset(); // loop through all the options, re-adding them while (pCurOption = pOptionValueEnum->Next()) { CDhcpOptionValue optValue = pCurOption->QueryValue(); DHCP_OPTION_DATA * pOptData; dwErr = optValue.CreateOptionDataStruct(&pOptData); if (dwErr != ERROR_SUCCESS) break; if ( liVersion.QuadPart >= DHCP_NT5_VERSION ) { LPCTSTR pClassName = pCurOption->IsClassOption() ? pCurOption->GetClassName() : NULL; dwErr = ::DhcpSetOptionValueV5((LPTSTR) GetServerIpAddress(), pCurOption->IsVendor() ? DHCP_FLAGS_OPTION_IS_VENDOR : 0, pCurOption->QueryId(), (LPTSTR) pClassName, (LPTSTR) pCurOption->GetVendor(), &pOptionValueEnum->m_dhcpOptionScopeInfo, pOptData); } else { dwErr = ::DhcpSetOptionValue((LPTSTR) GetServerIpAddress(), pCurOption->QueryId(), &pOptionValueEnum->m_dhcpOptionScopeInfo, pOptData); } if (dwErr != ERROR_SUCCESS) break; } return dwErr; } /*--------------------------------------------------------------------------- CDhcpScope::AddReservation Deletes a reservation Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::AddReservation ( const CDhcpClient * pClient ) { DWORD err = 0 ; DHCP_SUBNET_ELEMENT_DATA_V4 dhcSubElData; DHCP_IP_RESERVATION_V4 dhcpIpReservation; DHCP_CLIENT_UID dhcpClientUID; const CByteArray& baHardwareAddress = pClient->QueryHardwareAddress(); dhcpClientUID.DataLength = (DWORD) baHardwareAddress.GetSize(); dhcpClientUID.Data = (BYTE *) baHardwareAddress.GetData(); dhcpIpReservation.ReservedIpAddress = pClient->QueryIpAddress(); dhcpIpReservation.ReservedForClient = &dhcpClientUID; dhcSubElData.ElementType = DhcpReservedIps; dhcSubElData.Element.ReservedIp = &dhcpIpReservation; dhcpIpReservation.bAllowedClientTypes = pClient->QueryClientType(); LARGE_INTEGER liVersion; GetServerVersion(liVersion); if (liVersion.QuadPart >= DHCP_SP2_VERSION) { err = AddElementV4( &dhcSubElData ); } else { err = AddElement( reinterpret_cast<DHCP_SUBNET_ELEMENT_DATA *>(&dhcSubElData) ); } return err; } /*--------------------------------------------------------------------------- CDhcpScope::DeleteReservation Deletes a reservation Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::DeleteReservation ( CByteArray& baHardwareAddress, DHCP_IP_ADDRESS dhcpReservedIpAddress ) { DHCP_SUBNET_ELEMENT_DATA dhcpSubnetElementData; DHCP_IP_RESERVATION dhcpIpReservation; DHCP_CLIENT_UID dhcpClientUID; dhcpClientUID.DataLength = (DWORD) baHardwareAddress.GetSize(); dhcpClientUID.Data = baHardwareAddress.GetData(); dhcpIpReservation.ReservedIpAddress = dhcpReservedIpAddress; dhcpIpReservation.ReservedForClient = &dhcpClientUID; dhcpSubnetElementData.ElementType = DhcpReservedIps; dhcpSubnetElementData.Element.ReservedIp = &dhcpIpReservation; return RemoveElement(&dhcpSubnetElementData, TRUE); } /*--------------------------------------------------------------------------- CDhcpScope::DeleteReservation Deletes a reservation Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::DeleteReservation ( DHCP_CLIENT_UID &dhcpClientUID, DHCP_IP_ADDRESS dhcpReservedIpAddress ) { DHCP_SUBNET_ELEMENT_DATA dhcpSubnetElementData; DHCP_IP_RESERVATION dhcpIpReservation; dhcpIpReservation.ReservedIpAddress = dhcpReservedIpAddress; dhcpIpReservation.ReservedForClient = &dhcpClientUID; dhcpSubnetElementData.ElementType = DhcpReservedIps; dhcpSubnetElementData.Element.ReservedIp = &dhcpIpReservation; return RemoveElement(&dhcpSubnetElementData, TRUE); } /*--------------------------------------------------------------------------- CDhcpScope::GetClientInfo Gets a clients detailed information Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetClientInfo ( DHCP_IP_ADDRESS dhcpClientIpAddress, LPDHCP_CLIENT_INFO *ppdhcpClientInfo ) { DHCP_SEARCH_INFO dhcpSearchInfo; dhcpSearchInfo.SearchType = DhcpClientIpAddress; dhcpSearchInfo.SearchInfo.ClientIpAddress = dhcpClientIpAddress; return ::DhcpGetClientInfo(GetServerIpAddress(), &dhcpSearchInfo, ppdhcpClientInfo); } /*--------------------------------------------------------------------------- CDhcpScope::CreateClient CreateClient() creates a reservation for a client. The act of adding a new reserved IP address causes the DHCP server to create a new client record; we then set the client info for this newly created client. Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::CreateClient ( const CDhcpClient * pClient ) { DWORD err = 0; do { err = AddReservation( pClient ); if (err != ERROR_SUCCESS) break; err = SetClientInfo( pClient ); } while (FALSE); return err; } /*--------------------------------------------------------------------------- CDhcpScope::SetClientInfo Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetClientInfo ( const CDhcpClient * pClient ) { DWORD err = 0 ; DHCP_CLIENT_INFO_V4 dhcpClientInfo; const CByteArray& baHardwareAddress = pClient->QueryHardwareAddress(); LARGE_INTEGER liVersion; GetServerVersion(liVersion); dhcpClientInfo.ClientIpAddress = pClient->QueryIpAddress(); dhcpClientInfo.SubnetMask = pClient->QuerySubnet(); dhcpClientInfo.ClientHardwareAddress.DataLength = (DWORD) baHardwareAddress.GetSize(); dhcpClientInfo.ClientHardwareAddress.Data = (BYTE *) baHardwareAddress.GetData(); dhcpClientInfo.ClientName = (LPTSTR) ((LPCTSTR) pClient->QueryName()); dhcpClientInfo.ClientComment = (LPTSTR) ((LPCTSTR) pClient->QueryComment()); dhcpClientInfo.ClientLeaseExpires = pClient->QueryExpiryDateTime(); dhcpClientInfo.OwnerHost.IpAddress = 0; dhcpClientInfo.OwnerHost.HostName = NULL; dhcpClientInfo.OwnerHost.NetBiosName = NULL; if (liVersion.QuadPart >= DHCP_SP2_VERSION) { dhcpClientInfo.bClientType = pClient->QueryClientType(); err = ::DhcpSetClientInfoV4(GetServerIpAddress(), &dhcpClientInfo); } else { err = ::DhcpSetClientInfo(GetServerIpAddress(), reinterpret_cast<LPDHCP_CLIENT_INFO>(&dhcpClientInfo)); } return err; } /*--------------------------------------------------------------------------- CDhcpScope::DeleteClient Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::DeleteClient ( DHCP_IP_ADDRESS dhcpClientIpAddress ) { DHCP_SEARCH_INFO dhcpClientInfo; dhcpClientInfo.SearchType = DhcpClientIpAddress; dhcpClientInfo.SearchInfo.ClientIpAddress = dhcpClientIpAddress; return ::DhcpDeleteClientInfo((LPWSTR) GetServerIpAddress(), &dhcpClientInfo); } /*--------------------------------------------------------------------------- CDhcpScope::SetInfo() Updates the scope's information Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetInfo() { DWORD err = 0 ; DHCP_SUBNET_INFO dhcpSubnetInfo; dhcpSubnetInfo.SubnetAddress = m_dhcpIpAddress; dhcpSubnetInfo.SubnetMask = m_dhcpSubnetMask; dhcpSubnetInfo.SubnetName = (LPTSTR) ((LPCTSTR) m_strName); dhcpSubnetInfo.SubnetComment = (LPTSTR) ((LPCTSTR) m_strComment); dhcpSubnetInfo.SubnetState = m_dhcpSubnetState; GetServerIpAddress(&dhcpSubnetInfo.PrimaryHost.IpAddress); // Review : ericdav - do we need to fill these in? dhcpSubnetInfo.PrimaryHost.NetBiosName = NULL; dhcpSubnetInfo.PrimaryHost.HostName = NULL; err = ::DhcpSetSubnetInfo(GetServerIpAddress(), m_dhcpIpAddress, &dhcpSubnetInfo); return err; } /*--------------------------------------------------------------------------- CDhcpScope::GetIpRange() returns the scope's allocation range. Connects to the server to get the information Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetIpRange ( CDhcpIpRange * pdhipr ) { BOOL bAlloced = FALSE; DWORD dwError = ERROR_SUCCESS; pdhipr->SetAddr(0, TRUE); pdhipr->SetAddr(0, FALSE); CDhcpAddressPool * pAddressPool = GetAddressPoolObject(); if (pAddressPool == NULL) { // the address pool folder isn't there yet... // Create a temporary one for now... pAddressPool = new CDhcpAddressPool(m_spTFSCompData); bAlloced = TRUE; } // Get a query object from the address pool handler CDhcpAddressPoolQueryObj * pQueryObject = reinterpret_cast<CDhcpAddressPoolQueryObj *>(pAddressPool->OnCreateQuery(m_spAddressPool)); // if we created an address pool handler, then free it up now if (bAlloced) { pQueryObject->m_strServer = GetServerIpAddress(); pQueryObject->m_dhcpScopeAddress = GetAddress(); pQueryObject->m_fSupportsDynBootp = GetServerObject()->FSupportsDynBootp(); pAddressPool->Release(); } // tell the query object to get the ip ranges pQueryObject->EnumerateIpRanges(); // check to see if there was any problems getting the information dwError = pQueryObject->m_dwError; if (dwError != ERROR_SUCCESS) { return dwError; } LPQUEUEDATA pQD; while (pQD = pQueryObject->RemoveFromQueue()) { Assert (pQD->Type == QDATA_PNODE); SPITFSNode p; p = reinterpret_cast<ITFSNode *>(pQD->Data); delete pQD; CDhcpAllocationRange * pAllocRange = GETHANDLER(CDhcpAllocationRange, p); *pdhipr = *pAllocRange; pdhipr->SetRangeType(pAllocRange->GetRangeType()); p.Release(); } pQueryObject->Release(); return dwError; } /*--------------------------------------------------------------------------- CDhcpScope::UpdateIpRange() This function updates the IP range on the server. We also need to remove any exclusion ranges that fall outside of the new allocation range. Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::UpdateIpRange ( DHCP_IP_RANGE * pdhipr ) { return SetIpRange(pdhipr, TRUE); } /*--------------------------------------------------------------------------- CDhcpScope::QueryIpRange() Returns the scope's allocation range (doesn't talk to the server directly, only returns internally cached information). Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::QueryIpRange ( DHCP_IP_RANGE * pdhipr ) { pdhipr->StartAddress = 0; pdhipr->EndAddress = 0; SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; m_spAddressPool->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { if (spCurrentNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_ALLOCATION_RANGE) { // found the address // CDhcpAllocationRange * pAllocRange = GETHANDLER(CDhcpAllocationRange, spCurrentNode); pdhipr->StartAddress = pAllocRange->QueryAddr(TRUE); pdhipr->EndAddress = pAllocRange->QueryAddr(FALSE); } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } } /*--------------------------------------------------------------------------- CDhcpScope::SetIpRange Set's the allocation range for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetIpRange ( DHCP_IP_RANGE * pdhcpIpRange, BOOL bUpdateOnServer ) { CDhcpIpRange dhcpIpRange = *pdhcpIpRange; return SetIpRange(dhcpIpRange, bUpdateOnServer); } /*--------------------------------------------------------------------------- CDhcpScope::SetIpRange Set's the allocation range for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetIpRange ( CDhcpIpRange & dhcpIpRange, BOOL bUpdateOnServer ) { DWORD err = 0; if (bUpdateOnServer) { DHCP_SUBNET_ELEMENT_DATA dhcSubElData; CDhcpIpRange dhipOldRange; DHCP_IP_RANGE dhcpTempIpRange; err = GetIpRange(&dhipOldRange); if (err != ERROR_SUCCESS) { return err; } dhcpTempIpRange.StartAddress = dhipOldRange.QueryAddr(TRUE); dhcpTempIpRange.EndAddress = dhipOldRange.QueryAddr(FALSE); dhcSubElData.ElementType = DhcpIpRanges; dhcSubElData.Element.IpRange = &dhcpTempIpRange; // // First update the information on the server // if (dhcpIpRange.GetRangeType() != 0) { // Dynamic BOOTP stuff... DHCP_SUBNET_ELEMENT_DATA_V5 dhcSubElDataV5; DHCP_BOOTP_IP_RANGE dhcpNewIpRange = {0}; dhcpNewIpRange.StartAddress = dhcpIpRange.QueryAddr(TRUE); dhcpNewIpRange.EndAddress = dhcpIpRange.QueryAddr(FALSE); dhcpNewIpRange.BootpAllocated = 0; // this field could be set to allow X number of dyn bootp clients from a scope. dhcpNewIpRange.MaxBootpAllowed = -1; dhcSubElDataV5.Element.IpRange = &dhcpNewIpRange; dhcSubElDataV5.ElementType = (DHCP_SUBNET_ELEMENT_TYPE) dhcpIpRange.GetRangeType(); err = AddElementV5(&dhcSubElDataV5); if (err != ERROR_SUCCESS) { DHCP_BOOTP_IP_RANGE dhcpOldIpRange = {0}; // something bad happened, try to put the old range back dhcpOldIpRange.StartAddress = dhipOldRange.QueryAddr(TRUE); dhcpOldIpRange.EndAddress = dhipOldRange.QueryAddr(FALSE); dhcSubElDataV5.Element.IpRange = &dhcpOldIpRange; dhcSubElDataV5.ElementType = (DHCP_SUBNET_ELEMENT_TYPE) dhipOldRange.GetRangeType(); if (AddElementV5(&dhcSubElDataV5) != ERROR_SUCCESS) { Trace0("SetIpRange - cannot return ip range back to old state!!"); } } } else { // Remove the old IP range; allow "not found" error in new scope. // (void)RemoveElement(&dhcSubElData); DHCP_IP_RANGE dhcpNewIpRange = {0}; dhcpNewIpRange.StartAddress = dhcpIpRange.QueryAddr(TRUE); dhcpNewIpRange.EndAddress = dhcpIpRange.QueryAddr(FALSE); dhcSubElData.Element.IpRange = &dhcpNewIpRange; err = AddElement( & dhcSubElData ); if (err != ERROR_SUCCESS) { // something bad happened, try to put the old range back dhcpTempIpRange.StartAddress = dhipOldRange.QueryAddr(TRUE); dhcpTempIpRange.EndAddress = dhipOldRange.QueryAddr(FALSE); dhcSubElData.Element.IpRange = &dhcpTempIpRange; if (AddElement(&dhcSubElData) != ERROR_SUCCESS) { Trace0("SetIpRange - cannot return ip range back to old state!!"); } } } } // // Find the address pool folder and update the UI object // SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; if (m_spAddressPool == NULL) return err; m_spAddressPool->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { if (spCurrentNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_ALLOCATION_RANGE) { // found the address // CDhcpAllocationRange * pAllocRange = GETHANDLER(CDhcpAllocationRange, spCurrentNode); // now set them // pAllocRange->SetAddr(dhcpIpRange.QueryAddr(TRUE), TRUE); pAllocRange->SetAddr(dhcpIpRange.QueryAddr(FALSE), FALSE); // tell the UI to update spCurrentNode->ChangeNode(RESULT_PANE_CHANGE_ITEM_DATA); } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } return err ; } /*--------------------------------------------------------------------------- CDhcpScope::IsOverlappingRange determines if the exclusion overlaps an existing range Author: EricDav ---------------------------------------------------------------------------*/ BOOL CDhcpScope::IsOverlappingRange ( CDhcpIpRange & dhcpIpRange ) { SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; BOOL bOverlap = FALSE; m_spActiveLeases->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { if (spCurrentNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_EXCLUSION_RANGE) { // found the address // CDhcpExclusionRange * pExclusion = GETHANDLER(CDhcpExclusionRange, spCurrentNode); if ( bOverlap = pExclusion->IsOverlap( dhcpIpRange ) ) { spCurrentNode.Release(); break; } } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } return bOverlap ; } /*--------------------------------------------------------------------------- CDhcpScope::IsValidExclusion determines if the exclusion is valid for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::IsValidExclusion ( CDhcpIpRange & dhcpExclusionRange ) { DWORD err = 0; CDhcpIpRange dhcpScopeRange; err = GetIpRange (&dhcpScopeRange); // // Get the data into a range object. // if ( IsOverlappingRange( dhcpExclusionRange ) ) { // // Walk the current list, determining if the new range is valid. // Then, if OK, verify that it's really a sub-range of the current range. // err = IDS_ERR_IP_RANGE_OVERLAP ; } else if ( ! dhcpExclusionRange.IsSubset( dhcpScopeRange ) ) { // // Guarantee that the new range is an (improper) subset of the scope's range // err = IDS_ERR_IP_RANGE_NOT_SUBSET ; } return err; } /*--------------------------------------------------------------------------- CDhcpScope::StoreExceptionList Adds a bunch of exclusions to the scope Author: EricDav ---------------------------------------------------------------------------*/ LONG CDhcpScope::StoreExceptionList ( CExclusionList * plistExclusions ) { DHCP_SUBNET_ELEMENT_DATA dhcElement ; DHCP_IP_RANGE dhipr ; CDhcpIpRange * pobIpRange ; DWORD err = 0, err1 = 0; POSITION pos; pos = plistExclusions->GetHeadPosition(); while ( pos ) { pobIpRange = plistExclusions->GetNext(pos); err1 = AddExclusion( *pobIpRange ) ; if ( err1 != 0 ) { err = err1; Trace1("CDhcpScope::StoreExceptionList error adding range %d\n", err); } } return err ; } /*--------------------------------------------------------------------------- CDhcpScope::AddExclusion Adds an individual exclusion to the server Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::AddExclusion ( CDhcpIpRange & dhcpIpRange, BOOL bAddToUI ) { DHCP_SUBNET_ELEMENT_DATA dhcElement ; DHCP_IP_RANGE dhipr ; DWORD err = 0; dhcElement.ElementType = DhcpExcludedIpRanges ; dhipr = dhcpIpRange ; dhcElement.Element.ExcludeIpRange = & dhipr ; Trace2("CDhcpScope::AddExclusion add excluded range %lx %lx\n", dhipr.StartAddress, dhipr.EndAddress ); err = AddElement( & dhcElement ) ; //if ( err != 0 && err != ERROR_DHCP_INVALID_RANGE) if ( err != 0 ) { Trace1("CDhcpScope::AddExclusion error removing range %d\n", err); } if (m_spAddressPool != NULL) { CDhcpAddressPool * pAddrPool = GETHANDLER(CDhcpAddressPool, m_spAddressPool); if (!err && bAddToUI && pAddrPool->m_bExpanded) { SPITFSNode spNewExclusion; CDhcpExclusionRange * pExclusion = new CDhcpExclusionRange(m_spTFSCompData, &((DHCP_IP_RANGE) dhcpIpRange)); CreateLeafTFSNode(&spNewExclusion, &GUID_DhcpExclusionNodeType, pExclusion, pExclusion, m_spNodeMgr); // Tell the handler to initialize any specific data pExclusion->InitializeNode((ITFSNode *) spNewExclusion); // Add the node as a child to this node m_spAddressPool->AddChild(spNewExclusion); pExclusion->Release(); } } TriggerStatsRefresh(); return err; } /*--------------------------------------------------------------------------- CDhcpScope::RemoveExclusion Removes and exclusion from the server Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RemoveExclusion ( CDhcpIpRange & dhcpIpRange ) { DHCP_SUBNET_ELEMENT_DATA dhcElement ; DHCP_IP_RANGE dhipr ; DWORD err = 0; dhcElement.ElementType = DhcpExcludedIpRanges ; dhipr = dhcpIpRange ; dhcElement.Element.ExcludeIpRange = & dhipr ; Trace2("CDhcpScope::RemoveExclusion remove excluded range %lx %lx\n", dhipr.StartAddress, dhipr.EndAddress); err = RemoveElement( & dhcElement ) ; //if ( err != 0 && err != ERROR_DHCP_INVALID_RANGE) if ( err != 0 ) { Trace1("CDhcpScope::RemoveExclusion error removing range %d\n", err); } return err; } /*--------------------------------------------------------------------------- CDhcpScope::GetLeaseTime Gets the least time for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetLeaseTime ( LPDWORD pdwLeaseTime ) { // // Check option 51 -- the lease duration // DWORD dwLeaseTime = 0; DHCP_OPTION_VALUE * poptValue = NULL; DWORD err = GetOptionValue(OPTION_LEASE_DURATION, DhcpSubnetOptions, &poptValue); if (err != ERROR_SUCCESS) { Trace0("CDhcpScope::GetLeaseTime - couldn't get lease duration -- \ this scope may have been created by a pre-release version of the admin tool\n"); // // The scope doesn't have a lease duration, maybe there's // a global option that can come to the rescue here... // if ((err = GetOptionValue(OPTION_LEASE_DURATION, DhcpGlobalOptions, &poptValue)) != ERROR_SUCCESS) { Trace0("CDhcpScope::GetLeaseTime - No global lease duration either -- \ assuming permanent lease duration\n"); dwLeaseTime = 0; } } if (err == ERROR_SUCCESS) { if (poptValue->Value.Elements != NULL) dwLeaseTime = poptValue->Value.Elements[0].Element.DWordOption; } if (poptValue) ::DhcpRpcFreeMemory(poptValue); *pdwLeaseTime = dwLeaseTime; return err; } /*--------------------------------------------------------------------------- CDhcpScope::SetLeaseTime Sets the least time for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetLeaseTime ( DWORD dwLeaseTime ) { DWORD err = 0; // // Set lease duration (option 51) // CDhcpOption dhcpOption (OPTION_LEASE_DURATION, DhcpDWordOption , _T(""), _T("")); dhcpOption.QueryValue().SetNumber(dwLeaseTime); err = SetOptionValue(&dhcpOption, DhcpSubnetOptions); return err; } /*--------------------------------------------------------------------------- CDhcpScope::GetDynBootpLeaseTime Gets the least time for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetDynBootpLeaseTime ( LPDWORD pdwLeaseTime ) { // // Check option 51 -- the lease duration // DWORD dwLeaseTime = 0; DHCP_OPTION_VALUE * poptValue = NULL; CString strName; GetDynBootpClassName(strName); DWORD err = GetOptionValue(OPTION_LEASE_DURATION, DhcpSubnetOptions, &poptValue, 0, strName, NULL); if (err != ERROR_SUCCESS) { Trace0("CDhcpScope::GetDynBootpLeaseTime - couldn't get lease duration -- \ this scope may have been created by a pre-release version of the admin tool\n"); // // The scope doesn't have a lease duration, maybe there's // a global option that can come to the rescue here... // if ((err = GetOptionValue(OPTION_LEASE_DURATION, DhcpGlobalOptions, &poptValue, 0, strName, NULL)) != ERROR_SUCCESS) { Trace0("CDhcpScope::GetDynBootpLeaseTime - No global lease duration either -- \ assuming permanent lease duration\n"); dwLeaseTime = 0; } } if (err == ERROR_SUCCESS) { if (poptValue->Value.Elements != NULL) dwLeaseTime = poptValue->Value.Elements[0].Element.DWordOption; } else { // none specified, using default dwLeaseTime = UtilConvertLeaseTime(DYN_BOOTP_DFAULT_LEASE_DAYS, DYN_BOOTP_DFAULT_LEASE_HOURS, DYN_BOOTP_DFAULT_LEASE_MINUTES); } if (poptValue) ::DhcpRpcFreeMemory(poptValue); *pdwLeaseTime = dwLeaseTime; return err; } /*--------------------------------------------------------------------------- CDhcpScope::SetDynBootpLeaseTime Sets the least time for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetDynBootpLeaseTime ( DWORD dwLeaseTime ) { DWORD err = 0; // // Set lease duration (option 51) // CDhcpOption dhcpOption (OPTION_LEASE_DURATION, DhcpDWordOption , _T(""), _T("")); dhcpOption.QueryValue().SetNumber(dwLeaseTime); CString strName; GetDynBootpClassName(strName); err = SetOptionValue(&dhcpOption, DhcpSubnetOptions, 0, strName, NULL); return err; } /*--------------------------------------------------------------------------- CDhcpScope::GetDynBootpClassName returns the user class name to be used to set the lease time Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::GetDynBootpClassName(CString & strName) { // use DHCP_BOOTP_CLASS_TXT as the class data to search for CClassInfoArray classInfoArray; GetServerObject()->GetClassInfoArray(classInfoArray); for (int i = 0; i < classInfoArray.GetSize(); i++) { // check to make sure same size if (classInfoArray[i].IsDynBootpClass()) { // found it! strName = classInfoArray[i].strName; break; } } } DWORD CDhcpScope::SetDynamicBootpInfo(UINT uRangeType, DWORD dwLeaseTime) { DWORD dwErr = 0; // set the range type CDhcpIpRange dhcpIpRange; GetIpRange(&dhcpIpRange); dhcpIpRange.SetRangeType(uRangeType); // this updates the type dwErr = SetIpRange(dhcpIpRange, TRUE); if (dwErr != ERROR_SUCCESS) return dwErr; // set the lease time dwErr = SetDynBootpLeaseTime(dwLeaseTime); return dwErr; } /*--------------------------------------------------------------------------- CDhcpScope::GetDnsRegistration Gets the DNS registration option value Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetDnsRegistration ( LPDWORD pDnsRegOption ) { // // Check option 81 -- the DNS registration option // DHCP_OPTION_VALUE * poptValue = NULL; DWORD err = GetOptionValue(OPTION_DNS_REGISTATION, DhcpSubnetOptions, &poptValue); // this is the default if (pDnsRegOption) *pDnsRegOption = DHCP_DYN_DNS_DEFAULT; if (err == ERROR_SUCCESS) { if ((poptValue->Value.Elements != NULL) && (pDnsRegOption)) { *pDnsRegOption = poptValue->Value.Elements[0].Element.DWordOption; } } else { Trace0("CDhcpScope::GetDnsRegistration - couldn't get DNS reg value, option may not be defined, Getting Server value.\n"); CDhcpServer * pServer = GETHANDLER(CDhcpServer, m_spServerNode); err = pServer->GetDnsRegistration(pDnsRegOption); } if (poptValue) ::DhcpRpcFreeMemory(poptValue); return err; } /*--------------------------------------------------------------------------- CDhcpScope::SetDnsRegistration Sets the DNS Registration option for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetDnsRegistration ( DWORD DnsRegOption ) { DWORD err = 0; // // Set DNS name registration (option 81) // CDhcpOption dhcpOption (OPTION_DNS_REGISTATION, DhcpDWordOption , _T(""), _T("")); dhcpOption.QueryValue().SetNumber(DnsRegOption); err = SetOptionValue(&dhcpOption, DhcpSubnetOptions); return err; } /*--------------------------------------------------------------------------- CDhcpScope::SetOptionValue Sets the least time for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetOptionValue ( CDhcpOption * pdhcType, DHCP_OPTION_SCOPE_TYPE dhcOptType, DHCP_IP_ADDRESS dhipaReservation, LPCTSTR pClassName, LPCTSTR pVendorName ) { DWORD err = 0; DHCP_OPTION_DATA * pdhcOptionData; DHCP_OPTION_SCOPE_INFO dhcScopeInfo; CDhcpOptionValue * pcOptionValue = NULL; ZeroMemory( & dhcScopeInfo, sizeof(dhcScopeInfo) ); CATCH_MEM_EXCEPTION { pcOptionValue = new CDhcpOptionValue( & pdhcType->QueryValue() ) ; //if ( (err = pcOptionValue->QueryError()) == 0 ) if ( pcOptionValue ) { dhcScopeInfo.ScopeType = dhcOptType ; // // Provide the sub-net address if this is a scope-level operation // if ( dhcOptType == DhcpSubnetOptions ) { dhcScopeInfo.ScopeInfo.SubnetScopeInfo = m_dhcpIpAddress; } else if ( dhcOptType == DhcpReservedOptions ) { dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpAddress = dhipaReservation; dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpSubnetAddress = m_dhcpIpAddress; } pcOptionValue->CreateOptionDataStruct(&pdhcOptionData, TRUE); if (pClassName || pVendorName) { err = (DWORD) ::DhcpSetOptionValueV5((LPTSTR) GetServerIpAddress(), 0, pdhcType->QueryId(), (LPTSTR) pClassName, (LPTSTR) pVendorName, &dhcScopeInfo, pdhcOptionData); } else { err = (DWORD) ::DhcpSetOptionValue(GetServerIpAddress(), pdhcType->QueryId(), &dhcScopeInfo, pdhcOptionData); } } } END_MEM_EXCEPTION(err) ; delete pcOptionValue ; return err ; } /*--------------------------------------------------------------------------- CDhcpScope::GetValue Gets an option value for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::GetOptionValue ( DHCP_OPTION_ID OptionID, DHCP_OPTION_SCOPE_TYPE dhcOptType, DHCP_OPTION_VALUE ** ppdhcOptionValue, DHCP_IP_ADDRESS dhipaReservation, LPCTSTR pClassName, LPCTSTR pVendorName ) { DWORD err = 0 ; DHCP_OPTION_SCOPE_INFO dhcScopeInfo ; ZeroMemory( &dhcScopeInfo, sizeof(dhcScopeInfo) ); CATCH_MEM_EXCEPTION { dhcScopeInfo.ScopeType = dhcOptType ; // // Provide the sub-net address if this is a scope-level operation // if ( dhcOptType == DhcpSubnetOptions ) { dhcScopeInfo.ScopeInfo.SubnetScopeInfo = m_dhcpIpAddress; } else if ( dhcOptType == DhcpReservedOptions ) { dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpAddress = dhipaReservation; dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpSubnetAddress = m_dhcpIpAddress; } if (pClassName || pVendorName) { err = (DWORD) ::DhcpGetOptionValueV5((LPTSTR) GetServerIpAddress(), 0, OptionID, (LPTSTR) pClassName, (LPTSTR) pVendorName, &dhcScopeInfo, ppdhcOptionValue ); } else { err = (DWORD) ::DhcpGetOptionValue(GetServerIpAddress(), OptionID, &dhcScopeInfo, ppdhcOptionValue ); } } END_MEM_EXCEPTION(err) ; return err ; } /*--------------------------------------------------------------------------- CDhcpScope::RemoveValue Removes an option Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RemoveOptionValue ( DHCP_OPTION_ID dhcOptId, DHCP_OPTION_SCOPE_TYPE dhcOptType, DHCP_IP_ADDRESS dhipaReservation ) { DHCP_OPTION_SCOPE_INFO dhcScopeInfo; ZeroMemory( &dhcScopeInfo, sizeof(dhcScopeInfo) ); dhcScopeInfo.ScopeType = dhcOptType; // // Provide the sub-net address if this is a scope-level operation // if ( dhcOptType == DhcpSubnetOptions ) { dhcScopeInfo.ScopeInfo.SubnetScopeInfo = m_dhcpIpAddress; } else if ( dhcOptType == DhcpReservedOptions ) { dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpAddress = dhipaReservation; dhcScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpSubnetAddress = m_dhcpIpAddress; } return (DWORD) ::DhcpRemoveOptionValue(GetServerIpAddress(), dhcOptId, &dhcScopeInfo); } /*--------------------------------------------------------------------------- CDhcpScope::AddElement Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::AddElement ( DHCP_SUBNET_ELEMENT_DATA * pdhcpSubnetElementData ) { return ::DhcpAddSubnetElement(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData); } /*--------------------------------------------------------------------------- CDhcpScope::RemoveElement Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RemoveElement ( DHCP_SUBNET_ELEMENT_DATA * pdhcpSubnetElementData, BOOL bForce ) { return ::DhcpRemoveSubnetElement(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData, bForce ? DhcpFullForce : DhcpNoForce); } /*--------------------------------------------------------------------------- CDhcpScope::AddElementV4 Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::AddElementV4 ( DHCP_SUBNET_ELEMENT_DATA_V4 * pdhcpSubnetElementData ) { return ::DhcpAddSubnetElementV4(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData); } /*--------------------------------------------------------------------------- CDhcpScope::RemoveElementV4 Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RemoveElementV4 ( DHCP_SUBNET_ELEMENT_DATA_V4 * pdhcpSubnetElementData, BOOL bForce ) { return ::DhcpRemoveSubnetElementV4(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData, bForce ? DhcpFullForce : DhcpNoForce); } /*--------------------------------------------------------------------------- CDhcpScope::AddElementV5 Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::AddElementV5 ( DHCP_SUBNET_ELEMENT_DATA_V5 * pdhcpSubnetElementData ) { return ::DhcpAddSubnetElementV5(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData); } /*--------------------------------------------------------------------------- CDhcpScope::RemoveElementV5 Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::RemoveElementV5 ( DHCP_SUBNET_ELEMENT_DATA_V5 * pdhcpSubnetElementData, BOOL bForce ) { return ::DhcpRemoveSubnetElementV5(GetServerIpAddress(), m_dhcpIpAddress, pdhcpSubnetElementData, bForce ? DhcpFullForce : DhcpNoForce); } /*--------------------------------------------------------------------------- CDhcpScope::GetServerIpAddress() Description Author: EricDav ---------------------------------------------------------------------------*/ LPCWSTR CDhcpScope::GetServerIpAddress() { CDhcpServer * pServer = GetServerObject(); return pServer->GetIpAddress(); } /*--------------------------------------------------------------------------- CDhcpScope::GetServerIpAddress Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::GetServerIpAddress(DHCP_IP_ADDRESS * pdhcpIpAddress) { CDhcpServer * pServer = GetServerObject(); pServer->GetIpAddress(pdhcpIpAddress); } /*--------------------------------------------------------------------------- CDhcpScope::GetServerVersion Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScope::GetServerVersion ( LARGE_INTEGER& liVersion ) { CDhcpServer * pServer = GetServerObject(); pServer->GetVersion(liVersion); } /*--------------------------------------------------------------------------- CDhcpScope::SetSuperscope Sets this scope as part of the given superscope name Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpScope::SetSuperscope ( LPCTSTR pSuperscopeName, BOOL bRemove ) { DWORD dwReturn = 0; dwReturn = ::DhcpSetSuperScopeV4(GetServerIpAddress(), GetAddress(), (LPWSTR) pSuperscopeName, bRemove); if (dwReturn != ERROR_SUCCESS) { Trace1("CDhcpScope::SetSuperscope - DhcpSetSuperScopeV4 failed!! %d\n", dwReturn); } return dwReturn; } /*--------------------------------------------------------------------------- Helper functions ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::BuildDisplayName ( CString * pstrDisplayName, LPCTSTR pIpAddress, LPCTSTR pName ) { if (pstrDisplayName) { CString strStandard, strIpAddress, strName; strIpAddress = pIpAddress; strName = pName; strStandard.LoadString(IDS_SCOPE_FOLDER); *pstrDisplayName = strStandard + L" [" + strIpAddress + L"] " + strName; } return hrOK; } HRESULT CDhcpScope::SetName ( LPCWSTR pName ) { if (pName != NULL) { m_strName = pName; } CString strIpAddress, strDisplayName; // // Create the display name for this scope // Convert DHCP_IP_ADDRES to a string and initialize this object // UtilCvtIpAddrToWstr (m_dhcpIpAddress, &strIpAddress); BuildDisplayName(&strDisplayName, strIpAddress, pName); SetDisplayName(strDisplayName); return hrOK; } /*--------------------------------------------------------------------------- CDhcpScope::GetAddressPoolObject() Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpAddressPool * CDhcpScope::GetAddressPoolObject() { if (m_spAddressPool) return GETHANDLER(CDhcpAddressPool, m_spAddressPool); else return NULL; } /*--------------------------------------------------------------------------- CDhcpScope::GetReservationsObject() Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpReservations * CDhcpScope::GetReservationsObject() { if ( m_spReservations ) return GETHANDLER(CDhcpReservations, m_spReservations); else return NULL; } /*--------------------------------------------------------------------------- CDhcpScope::GetReservationsObject() Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpActiveLeases * CDhcpScope::GetActiveLeasesObject() { if (m_spActiveLeases) return GETHANDLER(CDhcpActiveLeases, m_spActiveLeases); else return NULL; } /*--------------------------------------------------------------------------- CDhcpScope::GetScopeOptionsContainer() Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpScopeOptions * CDhcpScope::GetScopeOptionsObject() { if (m_spOptions) return GETHANDLER(CDhcpScopeOptions, m_spOptions); else return NULL; } /*--------------------------------------------------------------------------- CDhcpScope::TriggerStatsRefresh() Calls into the server object to update the stats Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScope::TriggerStatsRefresh() { GetServerObject()->TriggerStatsRefresh(m_spServerNode); return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservations Implementation ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservations::CDhcpReservations() Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpReservations::CDhcpReservations ( ITFSComponentData * pComponentData ) : CMTDhcpHandler(pComponentData) { } // // copy all the resrved ips to an array and qsort it // when matching an entry that is read from dhcp db // we can do a binary search on the qsorted array // a better algorithm for large n ( n number of active clients ) is to // go through the active clients once for each m ( reserved ip ) where m > // 100 but << n BOOL CDhcpReservationsQueryObj::AddReservedIPsToArray( ) { DHCP_RESUME_HANDLE dhcpResumeHandle = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0, dwTotalRead = 0; DWORD dwError = ERROR_MORE_DATA; DWORD dwResvThreshold = 100; m_resvMap.RemoveAll(); m_subnetElements = NULL; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElementsV4(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, DhcpReservedIps, &dhcpResumeHandle, -1, &m_subnetElements, &dwElementsRead, &dwElementsTotal); Trace3("BuildReservationList: Scope %lx Reservations read %d, total %d\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal ); // // If number of reservations is less than 100 handle it the old way // if ( dwElementsTotal <= dwResvThreshold ) { m_totalResvs = dwElementsTotal; return( FALSE ); } if (dwElementsRead && dwElementsTotal && m_subnetElements ) { // // Loop through the array that was returned // for (DWORD i = 0; i < m_subnetElements->NumElements; i++) { m_resvMap.SetAt( m_subnetElements->Elements[i].Element.ReservedIp->ReservedIpAddress, &m_subnetElements->Elements[ i ]); } dwTotalRead += dwElementsRead; if ( dwTotalRead <= dwElementsTotal ) { m_totalResvs = dwTotalRead; } else { m_totalResvs = dwElementsTotal; } } } // while return( TRUE ); } CDhcpReservations::~CDhcpReservations() { } /*!-------------------------------------------------------------------------- CDhcpReservations::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservations::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; // // Create the display name for this scope // CString strTemp; strTemp.LoadString(IDS_RESERVATIONS_FOLDER); SetDisplayName(strTemp); // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_RESERVATIONS); SetColumnStringIDs(&aColumns[DHCPSNAP_RESERVATIONS][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_RESERVATIONS][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpReservations::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservations::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); DHCP_IP_ADDRESS dhcpIpAddress = GetScopeObject(pNode)->GetAddress(); UtilCvtIpAddrToWstr (dhcpIpAddress, &strIpAddress); strId = GetServerName(pNode) + strIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservations::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpReservations::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { case notLoaded: case loaded: if (bOpenImage) nIndex = ICON_IDX_RESERVATIONS_FOLDER_OPEN; else nIndex = ICON_IDX_RESERVATIONS_FOLDER_CLOSED; break; case loading: if (bOpenImage) nIndex = ICON_IDX_RESERVATIONS_FOLDER_OPEN_BUSY; else nIndex = ICON_IDX_RESERVATIONS_FOLDER_CLOSED_BUSY; break; case unableToLoad: if (bOpenImage) nIndex = ICON_IDX_RESERVATIONS_FOLDER_OPEN_LOST_CONNECTION; else nIndex = ICON_IDX_RESERVATIONS_FOLDER_CLOSED_LOST_CONNECTION; break; default: ASSERT(FALSE); } return nIndex; } /*!-------------------------------------------------------------------------- CDhcpReservations::RemoveReservationFromUI Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpReservations::RemoveReservationFromUI ( ITFSNode * pReservationsNode, DHCP_IP_ADDRESS dhcpReservationIp ) { DWORD dwError = E_UNEXPECTED; CDhcpReservationClient * pReservationClient = NULL; SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; pReservationsNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { pReservationClient = GETHANDLER(CDhcpReservationClient, spCurrentNode); if (dhcpReservationIp == pReservationClient->GetIpAddress()) { // // Tell this reservation to delete itself // pReservationsNode->RemoveChild(spCurrentNode); spCurrentNode.Release(); dwError = ERROR_SUCCESS; break; } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } return dwError; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservations::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservations::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); LONG fFlags = 0; HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { // these menu items go in the new menu, // only visible from scope pane strMenuText.LoadString(IDS_CREATE_NEW_RESERVATION); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_CREATE_NEW_RESERVATION, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } return hr; } /*--------------------------------------------------------------------------- CDhcpReservations::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservations::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_CREATE_NEW_RESERVATION: OnCreateNewReservation(pNode); break; case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; default: break; } return hr; } /*--------------------------------------------------------------------------- CDhcpReservations::CompareItems Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CDhcpReservations::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { SPITFSNode spNode1, spNode2; m_spNodeMgr->FindNode(cookieA, &spNode1); m_spNodeMgr->FindNode(cookieB, &spNode2); int nCompare = 0; CDhcpReservationClient *pDhcpRC1 = GETHANDLER(CDhcpReservationClient, spNode1); CDhcpReservationClient *pDhcpRC2 = GETHANDLER(CDhcpReservationClient, spNode2); switch (nCol) { case 0: { // IP address compare // DHCP_IP_ADDRESS dhcpIp1 = pDhcpRC1->GetIpAddress(); DHCP_IP_ADDRESS dhcpIp2 = pDhcpRC2->GetIpAddress(); if (dhcpIp1 < dhcpIp2) nCompare = -1; else if (dhcpIp1 > dhcpIp2) nCompare = 1; // default is that they are equal } break; } return nCompare; } /*!-------------------------------------------------------------------------- CDhcpReservations::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservations::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { HRESULT hr = hrOK; // call the base class to see if it is handling this if (CMTDhcpHandler::OnGetResultViewType(pComponent, cookie, ppViewType, pViewOptions) != S_OK) { *pViewOptions = MMC_VIEW_OPTIONS_MULTISELECT; hr = S_FALSE; } return hr; } /*!-------------------------------------------------------------------------- CDhcpReservations::OnResultSelect Update the verbs and the result pane message Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservations::OnResultSelect(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPITFSNode spNode; CORg(CMTDhcpHandler::OnResultSelect(pComponent, pDataObject, cookie, arg, lParam)); CORg (pComponent->GetSelectedNode(&spNode)); if ( spNode != 0 ) { UpdateResultMessage(spNode); } Error: return hr; } /*!-------------------------------------------------------------------------- CDhcpReservations::UpdateResultMessage Figures out what message to put in the result pane, if any Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpReservations::UpdateResultMessage(ITFSNode * pNode) { HRESULT hr = hrOK; int nMessage = -1; // default int nVisible, nTotal; int i; CString strTitle, strBody, strTemp; if (!m_dwErr) { pNode->GetChildCount(&nVisible, &nTotal); // determine what message to display if ( (m_nState == notLoaded) || (m_nState == loading) ) { nMessage = -1; } else if (nTotal == 0) { nMessage = RESERVATIONS_MESSAGE_NO_RES; } // build the strings if (nMessage != -1) { // now build the text strings // first entry is the title strTitle.LoadString(g_uReservationsMessages[nMessage][0]); // second entry is the icon // third ... n entries are the body strings for (i = 2; g_uReservationsMessages[nMessage][i] != 0; i++) { strTemp.LoadString(g_uReservationsMessages[nMessage][i]); strBody += strTemp; } } } // show the message if (nMessage == -1) { ClearMessage(pNode); } else { ShowMessage(pNode, strTitle, strBody, (IconIdentifier) g_uReservationsMessages[nMessage][1]); } } /*--------------------------------------------------------------------------- Message handlers ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservations::OnCreateNewReservation Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpReservations::OnCreateNewReservation ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spScopeNode; pNode->GetParent(&spScopeNode); CDhcpScope * pScope = GETHANDLER(CDhcpScope, spScopeNode); LARGE_INTEGER liVersion; pScope->GetServerVersion(liVersion); CAddReservation dlgAddReservation(spScopeNode, liVersion); dlgAddReservation.DoModal(); GetScopeObject(pNode)->TriggerStatsRefresh(); UpdateResultMessage(pNode); return 0; } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservations::OnHaveData Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpReservations::OnHaveData ( ITFSNode * pParentNode, ITFSNode * pNewNode ) { AddReservationSorted(pParentNode, pNewNode); // update the view ExpandNode(pParentNode, TRUE); } /*--------------------------------------------------------------------------- CDhcpReservations::AddReservationSorted Adding reservation after sorting it by comparing against the resvname takes too much time. Adds a scope node to the UI sorted Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservations::AddReservationSorted ( ITFSNode * pReservationsNode, ITFSNode * pResClientNode ) { HRESULT hr = hrOK; SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; SPITFSNode spPrevNode; ULONG nNumReturned = 0; CDhcpReservationClient * pResClient; // get our target address pResClient = GETHANDLER(CDhcpReservationClient, pResClientNode); // get the enumerator for this node CORg(pReservationsNode->GetEnum(&spNodeEnum)); CORg(spNodeEnum->Next(1, &spCurrentNode, &nNumReturned)); while (nNumReturned) { pResClient = GETHANDLER(CDhcpReservationClient, spCurrentNode); // get the next node in the list spPrevNode.Set(spCurrentNode); spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } // Add the node in based on the PrevNode pointer if (spPrevNode) { if (m_bExpanded) { pResClientNode->SetData(TFS_DATA_RELATIVE_FLAGS, SDI_PREVIOUS); pResClientNode->SetData(TFS_DATA_RELATIVE_SCOPEID, spPrevNode->GetData(TFS_DATA_SCOPEID)); } CORg(pReservationsNode->InsertChild(spPrevNode, pResClientNode)); } else { // add to the head if (m_bExpanded) { pResClientNode->SetData(TFS_DATA_RELATIVE_FLAGS, SDI_FIRST); } CORg(pReservationsNode->AddChild(pResClientNode)); } Error: return hr; } /*--------------------------------------------------------------------------- CDhcpReservations::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpReservations::OnCreateQuery(ITFSNode * pNode) { CDhcpReservationsQueryObj* pQuery = new CDhcpReservationsQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(pNode); pQuery->m_dhcpScopeAddress = GetScopeObject(pNode)->GetAddress(); pQuery->m_dhcpResumeHandle = NULL; pQuery->m_dwPreferredMax = 2000; pQuery->m_resvMap.RemoveAll(); pQuery->m_totalResvs = 0; pQuery->m_subnetElements = NULL; GetScopeObject(pNode)->GetServerVersion(pQuery->m_liVersion); return pQuery; } /*--------------------------------------------------------------------------- CDhcpReservationsQueryObj::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationsQueryObj::Execute() { HRESULT hr = hrOK; if (m_liVersion.QuadPart >= DHCP_SP2_VERSION) { if ( AddReservedIPsToArray( ) ) { // // // this should handle the case where there are a large # of resvs. // // hr = EnumerateReservationsV4(); } else { // // a typical corporation doesnt have more than 100 resvs // handle it here // hr = EnumerateReservationsForLessResvsV4( ); } } else { hr = EnumerateReservations(); } return hr; } HRESULT CDhcpReservationsQueryObj::EnumerateReservationsForLessResvsV4( ) { DWORD dwError = ERROR_MORE_DATA; LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V4 pdhcpSubnetElementArray = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; HRESULT hr = hrOK; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElementsV4(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, DhcpReservedIps, &m_dhcpResumeHandle, m_dwPreferredMax, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace3("Scope %lx Reservations read %d, total %d\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal); if (dwElementsRead && dwElementsTotal && pdhcpSubnetElementArray) { // // Loop through the array that was returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { // // For each reservation, we need to get the client info // DWORD dwReturn; LPDHCP_CLIENT_INFO_V4 pClientInfo = NULL; DHCP_SEARCH_INFO dhcpSearchInfo; dhcpSearchInfo.SearchType = DhcpClientIpAddress; dhcpSearchInfo.SearchInfo.ClientIpAddress = pdhcpSubnetElementArray->Elements[i].Element.ReservedIp->ReservedIpAddress; dwReturn = ::DhcpGetClientInfoV4(m_strServer, &dhcpSearchInfo, &pClientInfo); if (dwReturn == ERROR_SUCCESS) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpReservationClient * pDhcpReservationClient; COM_PROTECT_TRY { pDhcpReservationClient = new CDhcpReservationClient(m_spTFSCompData, pClientInfo); // Tell the reservation what the client type is pDhcpReservationClient->SetClientType(pdhcpSubnetElementArray->Elements[i].Element.ReservedIp->bAllowedClientTypes); CreateContainerTFSNode(&spNode, &GUID_DhcpReservationClientNodeType, pDhcpReservationClient, pDhcpReservationClient, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpReservationClient->InitializeNode(spNode); AddToQueue(spNode); pDhcpReservationClient->Release(); } COM_PROTECT_CATCH ::DhcpRpcFreeMemory(pClientInfo); } else { // REVIEW: ericdav - do we need to post the error back here? Trace1("EnumReservationsV4 - GetClientInfoV4 failed! %d\n", dwReturn); } } ::DhcpRpcFreeMemory(pdhcpSubnetElementArray); pdhcpSubnetElementArray = NULL; dwElementsRead = 0; dwElementsTotal = 0; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateReservationsV4 error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } /*--------------------------------------------------------------------------- CDhcpReservationsQueryObj::EnumerateReservationsV4() Enumerates leases for NT4 SP2 and newer servers Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationsQueryObj::EnumerateReservationsV4() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_CLIENT_INFO_ARRAY_V5 pdhcpClientArrayV5 = NULL; LPDHCP_SUBNET_ELEMENT_DATA_V4 pSubnetData = NULL; DWORD dwClientsRead = 0, dwClientsTotal = 0; DWORD dwResvsHandled = 0; DWORD dwEnumedClients = 0; DWORD dwResvThreshold = 1000; DWORD i = 0; DWORD k = 0; DWORD *j = NULL; HRESULT hr = hrOK; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetClientsV5(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, &m_dhcpResumeHandle, -1, &pdhcpClientArrayV5, &dwClientsRead, &dwClientsTotal); if ( dwClientsRead && dwClientsTotal && pdhcpClientArrayV5 ) { // // we do a binary search for a reservation // that is present in the table. // for( i = 0; i < dwClientsRead; i ++ ) { // // do binary search against each client that was read to see // if it is a reservation. // k = pdhcpClientArrayV5 -> Clients[i] -> ClientIpAddress; if ( m_resvMap.Lookup( k, pSubnetData )) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpReservationClient * pDhcpReservationClient; COM_PROTECT_TRY { pDhcpReservationClient = new CDhcpReservationClient( m_spTFSCompData, reinterpret_cast<LPDHCP_CLIENT_INFO_V4>(pdhcpClientArrayV5 -> Clients[ i ] )); pDhcpReservationClient->SetClientType( pSubnetData->Element.ReservedIp->bAllowedClientTypes ); CreateContainerTFSNode(&spNode, &GUID_DhcpReservationClientNodeType, pDhcpReservationClient, pDhcpReservationClient, m_spNodeMgr); // // Tell the handler to initialize any specific data // pDhcpReservationClient->InitializeNode(spNode); AddToQueue(spNode); pDhcpReservationClient->Release(); } COM_PROTECT_CATCH } // end of if that adds a reservation } // end of for ::DhcpRpcFreeMemory(pdhcpClientArrayV5); pdhcpClientArrayV5 = NULL; dwEnumedClients += dwClientsRead; dwClientsRead = 0; dwClientsTotal = 0; } // end of main if that checks if read succeeded. // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateReservationsV4 error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } DhcpRpcFreeMemory( m_subnetElements ); m_subnetElements = NULL; m_totalResvs = 0; m_resvMap.RemoveAll(); return hrFalse; } /*--------------------------------------------------------------------------- CDhcpReservationsQueryObj::Execute() Enumerates reservations for pre NT4 SP2 servers Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationsQueryObj::EnumerateReservations() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_SUBNET_ELEMENT_INFO_ARRAY pdhcpSubnetElementArray = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElements(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, DhcpReservedIps, &m_dhcpResumeHandle, m_dwPreferredMax, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace3("Scope %lx Reservations read %d, total %d\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal); if (dwElementsRead && dwElementsTotal && pdhcpSubnetElementArray) { // // Loop through the array that was returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { // // For each reservation, we need to get the client info // DWORD dwReturn; LPDHCP_CLIENT_INFO pClientInfo = NULL; DHCP_SEARCH_INFO dhcpSearchInfo; dhcpSearchInfo.SearchType = DhcpClientIpAddress; dhcpSearchInfo.SearchInfo.ClientIpAddress = pdhcpSubnetElementArray->Elements[i].Element.ReservedIp->ReservedIpAddress; dwReturn = ::DhcpGetClientInfo(m_strServer, &dhcpSearchInfo, &pClientInfo); if (dwReturn == ERROR_SUCCESS) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpReservationClient * pDhcpReservationClient; pDhcpReservationClient = new CDhcpReservationClient(m_spTFSCompData, reinterpret_cast<LPDHCP_CLIENT_INFO>(pClientInfo)); CreateContainerTFSNode(&spNode, &GUID_DhcpReservationClientNodeType, pDhcpReservationClient, pDhcpReservationClient, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpReservationClient->InitializeNode(spNode); AddToQueue(spNode); pDhcpReservationClient->Release(); ::DhcpRpcFreeMemory(pClientInfo); } } ::DhcpRpcFreeMemory(pdhcpSubnetElementArray); pdhcpSubnetElementArray = NULL; dwElementsRead = 0; dwElementsTotal = 0; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateReservations error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } /*!-------------------------------------------------------------------------- CDhcpReservations::OnNotifyExiting CMTDhcpHandler overridden functionality allows us to know when the background thread is done Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservations::OnNotifyExiting ( LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode; spNode.Set(m_spNode); // save this off because OnNotifyExiting will release it HRESULT hr = CMTDhcpHandler::OnNotifyExiting(lParam); UpdateResultMessage(spNode); return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient implementation ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpReservationClient::CDhcpReservationClient ( ITFSComponentData * pComponentData, LPDHCP_CLIENT_INFO pDhcpClientInfo ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); InitializeData(pDhcpClientInfo); // // Intialize our client type // m_bClientType = CLIENT_TYPE_UNSPECIFIED; m_fResProp = TRUE; } CDhcpReservationClient::CDhcpReservationClient ( ITFSComponentData * pComponentData, LPDHCP_CLIENT_INFO_V4 pDhcpClientInfo ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); InitializeData(reinterpret_cast<LPDHCP_CLIENT_INFO>(pDhcpClientInfo)); // // Intialize our client type // m_bClientType = pDhcpClientInfo->bClientType; m_fResProp = TRUE; } CDhcpReservationClient::CDhcpReservationClient ( ITFSComponentData * pComponentData, CDhcpClient & dhcpClient ) : CMTDhcpHandler(pComponentData) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); m_dhcpClientIpAddress = dhcpClient.QueryIpAddress(); // // Copy data out if it's there // if (dhcpClient.QueryName().GetLength() > 0) { m_pstrClientName = new CString (dhcpClient.QueryName()); } else { m_pstrClientName = NULL; } if (dhcpClient.QueryComment().GetLength() > 0) { m_pstrClientComment = new CString(dhcpClient.QueryComment()); } else { m_pstrClientComment = NULL; } // // build the clients hardware address // if (dhcpClient.QueryHardwareAddress().GetSize() > 0) { m_baHardwareAddress.Copy(dhcpClient.QueryHardwareAddress()); } if ( (dhcpClient.QueryExpiryDateTime().dwLowDateTime == 0) && (dhcpClient.QueryExpiryDateTime().dwHighDateTime == 0) ) { // // This is an inactive reservation // m_strLeaseExpires.LoadString(IDS_DHCP_INFINITE_LEASE_INACTIVE); } else { m_strLeaseExpires.LoadString(IDS_DHCP_INFINITE_LEASE_ACTIVE); } // // Intialize our client type // m_bClientType = dhcpClient.QueryClientType(); m_fResProp = TRUE; } CDhcpReservationClient::~CDhcpReservationClient() { if (m_pstrClientName) { delete m_pstrClientName; } if (m_pstrClientComment) { delete m_pstrClientComment; } } void CDhcpReservationClient::InitializeData ( LPDHCP_CLIENT_INFO pDhcpClientInfo ) { Assert(pDhcpClientInfo); m_dhcpClientIpAddress = pDhcpClientInfo->ClientIpAddress; // // Copy data out if it's there // if (pDhcpClientInfo->ClientName) { m_pstrClientName = new CString (pDhcpClientInfo->ClientName); } else { m_pstrClientName = NULL; } if (pDhcpClientInfo->ClientComment) { m_pstrClientComment = new CString(pDhcpClientInfo->ClientComment); } else { m_pstrClientComment = NULL; } // build a copy of the hardware address if (pDhcpClientInfo->ClientHardwareAddress.DataLength) { for (DWORD i = 0; i < pDhcpClientInfo->ClientHardwareAddress.DataLength; i++) { m_baHardwareAddress.Add(pDhcpClientInfo->ClientHardwareAddress.Data[i]); } } if ( (pDhcpClientInfo->ClientLeaseExpires.dwLowDateTime == 0) && (pDhcpClientInfo->ClientLeaseExpires.dwHighDateTime == 0) ) { // // This is an inactive reservation // m_strLeaseExpires.LoadString(IDS_DHCP_INFINITE_LEASE_INACTIVE); } else { m_strLeaseExpires.LoadString(IDS_DHCP_INFINITE_LEASE_ACTIVE); } } /*!-------------------------------------------------------------------------- CDhcpReservationClient::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; CString strIpAddress, strDisplayName; // // Create the display name for this scope // Convert DHCP_IP_ADDRES to a string and initialize this object // UtilCvtIpAddrToWstr (m_dhcpClientIpAddress, &strIpAddress); BuildDisplayName(&strDisplayName, strIpAddress, *m_pstrClientName); SetDisplayName(strDisplayName); // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_RESERVATION_CLIENT); pNode->SetData(TFS_DATA_SCOPE_LEAF_NODE, TRUE); SetColumnStringIDs(&aColumns[DHCPSNAP_RESERVATION_CLIENT][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_RESERVATION_CLIENT][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strScopeIpAddress, strResIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); DHCP_IP_ADDRESS dhcpIpAddress = GetScopeObject(pNode, TRUE)->GetAddress(); UtilCvtIpAddrToWstr (dhcpIpAddress, &strScopeIpAddress); UtilCvtIpAddrToWstr (m_dhcpClientIpAddress, &strResIpAddress); strId = GetServerName(pNode, TRUE) + strScopeIpAddress + strResIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpReservationClient::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { case notLoaded: case loaded: if (bOpenImage) nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_OPEN; else nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_CLOSED; break; case loading: if (bOpenImage) nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_OPEN_BUSY; else nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_CLOSED_BUSY; break; case unableToLoad: if (bOpenImage) nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_OPEN_LOST_CONNECTION; else nIndex = ICON_IDX_CLIENT_OPTION_FOLDER_CLOSED_LOST_CONNECTION; break; default: ASSERT(FALSE); } return nIndex; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservationClient::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationClient::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); LONG fFlags = 0; HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { strMenuText.LoadString(IDS_CREATE_OPTION_RESERVATION); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_CREATE_OPTION_RESERVATION, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationClient::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; case IDS_DELETE: OnDelete(pNode); break; case IDS_CREATE_OPTION_RESERVATION: OnCreateNewOptions(pNode); break; default: break; } return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient::CompareItems Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CDhcpReservationClient::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { SPITFSNode spNode1, spNode2; m_spNodeMgr->FindNode(cookieA, &spNode1); m_spNodeMgr->FindNode(cookieB, &spNode2); int nCompare = 0; CDhcpOptionItem *pOpt1 = GETHANDLER(CDhcpOptionItem, spNode1); CDhcpOptionItem *pOpt2 = GETHANDLER(CDhcpOptionItem, spNode2); switch (nCol) { case 0: { // // Name compare - use the option # // LONG_PTR uImage1 = spNode1->GetData(TFS_DATA_IMAGEINDEX); LONG_PTR uImage2 = spNode2->GetData(TFS_DATA_IMAGEINDEX); nCompare = UtilGetOptionPriority((int) uImage1, (int) uImage2); if (nCompare == 0) { DHCP_OPTION_ID id1 = pOpt1->GetOptionId(); DHCP_OPTION_ID id2 = pOpt2->GetOptionId(); if (id1 < id2) nCompare = -1; else if (id1 > id2) nCompare = 1; } } break; case 1: { // compare the vendor strings CString str1, str2; str1 = pOpt1->GetVendorDisplay(); str2 = pOpt2->GetVendorDisplay(); nCompare = str1.CompareNoCase(str2); } break; case 2: { // compare the printable values CString str1, str2; str1 = pOpt1->GetString( pComponent, cookieA, nCol ); str2 = pOpt2->GetString( pComponent, cookieB, nCol ); nCompare = str1.CompareNoCase( str2 ); break; } case 3: { CString str1, str2; str1 = pOpt1->GetClassName(); str2 = pOpt2->GetClassName(); nCompare = str1.CompareNoCase(str2); } break; } return nCompare; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnResultSelect Update the verbs and the result pane message Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnResultSelect(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPITFSNode spNode; CORg(CMTDhcpHandler::OnResultSelect(pComponent, pDataObject, cookie, arg, lParam)); CORg (pComponent->GetSelectedNode(&spNode)); if ( spNode != 0 ) { UpdateResultMessage(spNode); } Error: return hr; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::UpdateResultMessage Figures out what message to put in the result pane, if any Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpReservationClient::UpdateResultMessage(ITFSNode * pNode) { HRESULT hr = hrOK; int nMessage = -1; // default int nVisible, nTotal; int i; CString strTitle, strBody, strTemp; if (!m_dwErr) { pNode->GetChildCount(&nVisible, &nTotal); // determine what message to display if ( (m_nState == notLoaded) || (m_nState == loading) ) { nMessage = -1; } else if (nTotal == 0) { nMessage = RES_OPTIONS_MESSAGE_NO_OPTIONS; } // build the strings if (nMessage != -1) { // now build the text strings // first entry is the title strTitle.LoadString(g_uResOptionsMessages[nMessage][0]); // second entry is the icon // third ... n entries are the body strings for (i = 2; g_uResOptionsMessages[nMessage][i] != 0; i++) { strTemp.LoadString(g_uResOptionsMessages[nMessage][i]); strBody += strTemp; } } } // show the message if (nMessage == -1) { ClearMessage(pNode); } else { ShowMessage(pNode, strTitle, strBody, (IconIdentifier) g_uResOptionsMessages[nMessage][1]); } } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnDelete The base handler calls this when MMC sends a MMCN_DELETE for a scope pane item. We just call our delete command handler. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnDelete ( ITFSNode * pNode, LPARAM arg, LPARAM lParam ) { return OnDelete(pNode); } /*--------------------------------------------------------------------------- Command handlers ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnCreateNewOptions ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CPropertyPageHolderBase * pPropSheet; CString strOptCfgTitle, strOptType; SPITFSNode spServerNode; SPIComponentData spComponentData; COptionsConfig * pOptCfg; DHCP_OPTION_SCOPE_INFO dhcpScopeInfo; HRESULT hr = hrOK; COM_PROTECT_TRY { CString strOptCfgTitle, strOptType; SPIComponentData spComponentData; BOOL fFound = FALSE; strOptType.LoadString(IDS_CONFIGURE_OPTIONS_CLIENT); AfxFormatString1(strOptCfgTitle, IDS_CONFIGURE_OPTIONS_TITLE, strOptType); // this gets kinda weird because we implemented the option config page // as a property page, so technically this node has two property pages. // // search the open prop pages to see if the option config is up // if it's up, set it active instead of creating a new one. for (int i = 0; i < HasPropSheetsOpen(); i++) { GetOpenPropSheet(i, &pPropSheet); HWND hwnd = pPropSheet->GetSheetWindow(); CString strTitle; ::GetWindowText(hwnd, strTitle.GetBuffer(256), 256); strTitle.ReleaseBuffer(); if (strTitle == strOptCfgTitle) { pPropSheet->SetActiveWindow(); fFound = TRUE; break; } } if (!fFound) { m_spNodeMgr->GetComponentData(&spComponentData); m_fResProp = FALSE; hr = DoPropertiesOurselvesSinceMMCSucks(pNode, spComponentData, strOptCfgTitle); m_fResProp = TRUE; } } COM_PROTECT_CATCH; return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient::OnDelete Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpReservationClient::OnDelete ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CString strMessage, strTemp; DWORD dwError = 0; CDhcpReservations *pResrv; pResrv = GETHANDLER( CDhcpReservations, pNode ); // Check for any open property sheets if ( pResrv->HasPropSheetsOpen()) { AfxMessageBox( IDS_MSG_CLOSE_PROPSHEET ); return ERROR_INVALID_PARAMETER; } UtilCvtIpAddrToWstr (m_dhcpClientIpAddress, &strTemp); AfxFormatString1(strMessage, IDS_DELETE_RESERVATION, (LPCTSTR) strTemp); if (AfxMessageBox(strMessage, MB_YESNO) == IDYES) { BEGIN_WAIT_CURSOR; dwError = GetScopeObject(pNode, TRUE)->DeleteReservation(m_baHardwareAddress, m_dhcpClientIpAddress); if (dwError != 0) { // // OOOpss. Something happened, reservation not // deleted, so don't remove from UI and put up a message box // ::DhcpMessageBox(dwError); } else { CDhcpScope * pScope = NULL; SPITFSNode spActiveLeasesNode; pScope = GetScopeObject(pNode, TRUE); pScope->GetActiveLeasesNode(&spActiveLeasesNode); pScope->GetActiveLeasesObject()->DeleteClient(spActiveLeasesNode, m_dhcpClientIpAddress); SPITFSNode spReservationsNode; pNode->GetParent(&spReservationsNode); spReservationsNode->RemoveChild(pNode); // update stats pScope->TriggerStatsRefresh(); } // else END_WAIT_CURSOR; } // if return dwError; } // CDhcpReservationClient::OnDelete() /*--------------------------------------------------------------------------- CDhcpReservationClient::OnResultPropertyChange Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnResultPropertyChange ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode; m_spNodeMgr->FindNode(cookie, &spNode); COptionsConfig * pOptCfg = reinterpret_cast<COptionsConfig *>(param); LPARAM changeMask = 0; // tell the property page to do whatever now that we are back on the // main thread pOptCfg->OnPropertyChange(TRUE, &changeMask); pOptCfg->AcknowledgeNotify(); if (changeMask) spNode->ChangeNode(changeMask); return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::CreatePropertyPages Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationClient::CreatePropertyPages ( ITFSNode * pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType ) { HRESULT hr = hrOK; if (m_fResProp) { hr = DoResPages(pNode, lpProvider, pDataObject, handle, dwType); } else { hr = DoOptCfgPages(pNode, lpProvider, pDataObject, handle, dwType); } return hr; } HRESULT CDhcpReservationClient::DoResPages ( ITFSNode * pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); // // Create the property page // SPIComponentData spComponentData; m_spNodeMgr->GetComponentData(&spComponentData); CReservedClientProperties * pResClientProp = new CReservedClientProperties(pNode, spComponentData, m_spTFSCompData, NULL); // Get the Server version and set it in the property sheet LARGE_INTEGER liVersion; CDhcpServer * pServer = GetScopeObject(pNode, TRUE)->GetServerObject(); pServer->GetVersion(liVersion); pResClientProp->SetVersion(liVersion); // fill in the data for the prop page pResClientProp->m_pageGeneral.m_dwClientAddress = m_dhcpClientIpAddress; if (m_pstrClientName) pResClientProp->m_pageGeneral.m_strName = *m_pstrClientName; if (m_pstrClientComment) pResClientProp->m_pageGeneral.m_strComment = *m_pstrClientComment; pResClientProp->SetClientType(m_bClientType); // fill in the UID string UtilCvtByteArrayToString(m_baHardwareAddress, pResClientProp->m_pageGeneral.m_strUID); // set the DNS registration option DWORD dwDynDnsFlags; DWORD dwError; BEGIN_WAIT_CURSOR; dwError = GetDnsRegistration(pNode, &dwDynDnsFlags); if (dwError != ERROR_SUCCESS) { ::DhcpMessageBox(dwError); return hrFalse; } END_WAIT_CURSOR; pResClientProp->SetDnsRegistration(dwDynDnsFlags, DhcpReservedOptions); // // Object gets deleted when the page is destroyed // Assert(lpProvider != NULL); return pResClientProp->CreateModelessSheet(lpProvider, handle); } HRESULT CDhcpReservationClient::DoOptCfgPages ( ITFSNode * pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); DWORD dwError; DWORD dwDynDnsFlags; HRESULT hr = hrOK; COptionsConfig * pOptCfg; CString strOptCfgTitle, strOptType; SPITFSNode spServerNode; SPIComponentData spComponentData; COptionValueEnum * pOptionValueEnum; // // Create the property page // COM_PROTECT_TRY { m_spNodeMgr->GetComponentData(&spComponentData); BEGIN_WAIT_CURSOR; strOptType.LoadString(IDS_CONFIGURE_OPTIONS_CLIENT); AfxFormatString1(strOptCfgTitle, IDS_CONFIGURE_OPTIONS_TITLE, strOptType); GetScopeObject(pNode, TRUE)->GetServerNode(&spServerNode); pOptCfg = new COptionsConfig(pNode, spServerNode, spComponentData, m_spTFSCompData, GetOptionValueEnum(), strOptCfgTitle); END_WAIT_CURSOR; // // Object gets deleted when the page is destroyed // Assert(lpProvider != NULL); hr = pOptCfg->CreateModelessSheet(lpProvider, handle); } COM_PROTECT_CATCH return hr; } /*--------------------------------------------------------------------------- CDhcpReservationClient::OnPropertyChange Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnPropertyChange ( ITFSNode * pNode, LPDATAOBJECT pDataobject, DWORD dwType, LPARAM arg, LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CPropertyPageHolderBase * pProp = reinterpret_cast<CPropertyPageHolderBase *>(lParam); LONG_PTR changeMask = 0; // tell the property page to do whatever now that we are back on the // main thread pProp->OnPropertyChange(TRUE, &changeMask); pProp->AcknowledgeNotify(); if (changeMask) pNode->ChangeNode(changeMask); return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::OnResultDelete This function is called when we are supposed to delete result pane items. We build a list of selected items and then delete them. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnResultDelete ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { HRESULT hr = hrOK; AFX_MANAGE_STATE(AfxGetStaticModuleState()); // translate the cookie into a node pointer SPITFSNode spResClient, spSelectedNode; DWORD dwError; m_spNodeMgr->FindNode(cookie, &spResClient); pComponent->GetSelectedNode(&spSelectedNode); Assert(spSelectedNode == spResClient); if (spSelectedNode != spResClient) return hr; // build the list of selected nodes CTFSNodeList listNodesToDelete; hr = BuildSelectedItemList(pComponent, &listNodesToDelete); // // Confirm with the user // CString strMessage, strTemp; int nNodes = (int) listNodesToDelete.GetCount(); if (nNodes > 1) { strTemp.Format(_T("%d"), nNodes); AfxFormatString1(strMessage, IDS_DELETE_ITEMS, (LPCTSTR) strTemp); } else { strMessage.LoadString(IDS_DELETE_ITEM); } if (AfxMessageBox(strMessage, MB_YESNO) == IDNO) { return NOERROR; } // check to make sure we are deleting just scope options POSITION pos = listNodesToDelete.GetHeadPosition(); while (pos) { ITFSNode * pNode = listNodesToDelete.GetNext(pos); if (pNode->GetData(TFS_DATA_IMAGEINDEX) != ICON_IDX_CLIENT_OPTION_LEAF) { // this option is not scope option. Put up a dialog telling the user what to do AfxMessageBox(IDS_CANNOT_DELETE_OPTION_RES); return NOERROR; } } CString strServer = GetServerIpAddress(spResClient, TRUE); DHCP_OPTION_SCOPE_INFO dhcpOptionScopeInfo; dhcpOptionScopeInfo.ScopeType = DhcpReservedOptions; dhcpOptionScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpAddress = m_dhcpClientIpAddress; CDhcpScope * pScope = GetScopeObject(spResClient, TRUE); dhcpOptionScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpSubnetAddress = pScope->GetAddress(); // // Loop through all items deleting // BEGIN_WAIT_CURSOR; while (listNodesToDelete.GetCount() > 0) { SPITFSNode spOptionNode; spOptionNode = listNodesToDelete.RemoveHead(); CDhcpOptionItem * pOptItem = GETHANDLER(CDhcpOptionItem, spOptionNode); // // Try to remove it from the server // if (pOptItem->IsVendorOption() || pOptItem->IsClassOption()) { LPCTSTR pClassName = pOptItem->GetClassName(); if (lstrlen(pClassName) == 0) pClassName = NULL; dwError = ::DhcpRemoveOptionValueV5((LPTSTR) ((LPCTSTR) strServer), pOptItem->IsVendorOption() ? DHCP_FLAGS_OPTION_IS_VENDOR : 0, pOptItem->GetOptionId(), (LPTSTR) pClassName, (LPTSTR) pOptItem->GetVendor(), &dhcpOptionScopeInfo); } else { dwError = ::DhcpRemoveOptionValue(strServer, pOptItem->GetOptionId(), &dhcpOptionScopeInfo); } if (dwError != 0) { ::DhcpMessageBox(dwError); RESTORE_WAIT_CURSOR; hr = E_FAIL; continue; } GetOptionValueEnum()->Remove(pOptItem->GetOptionId(), pOptItem->GetVendor(), pOptItem->GetClassName()); // // Remove from UI now // spResClient->RemoveChild(spOptionNode); spOptionNode.Release(); } END_WAIT_CURSOR; UpdateResultMessage(spResClient); return hr; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { HRESULT hr = hrOK; // call the base class to see if it is handling this if (CMTDhcpHandler::OnGetResultViewType(pComponent, cookie, ppViewType, pViewOptions) != S_OK) { *pViewOptions = MMC_VIEW_OPTIONS_MULTISELECT; hr = S_FALSE; } return hr; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnHaveData Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpReservationClient::OnHaveData ( ITFSNode * pParentNode, LPARAM Data, LPARAM Type ) { // This is how we get non-node data back from the background thread. switch (Type) { case DHCP_QDATA_OPTION_VALUES: { HRESULT hr = hrOK; SPIComponentData spCompData; SPIConsole spConsole; SPIDataObject spDataObject; IDataObject * pDataObject; COptionValueEnum * pOptionValueEnum = reinterpret_cast<COptionValueEnum *>(Data); SetOptionValueEnum(pOptionValueEnum); pOptionValueEnum->RemoveAll(); delete pOptionValueEnum; // now tell the view to update themselves m_spNodeMgr->GetComponentData(&spCompData); CORg ( spCompData->QueryDataObject((MMC_COOKIE) pParentNode, CCT_SCOPE, &pDataObject) ); spDataObject = pDataObject; CORg ( m_spNodeMgr->GetConsole(&spConsole) ); CORg ( spConsole->UpdateAllViews(pDataObject, (LPARAM) pParentNode, DHCPSNAP_UPDATE_OPTIONS) ); break; } } Error: return; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnNotifyExiting CMTDhcpHandler overridden functionality allows us to know when the background thread is done Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationClient::OnNotifyExiting ( LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode; spNode.Set(m_spNode); // save this off because OnNotifyExiting will release it HRESULT hr = CMTDhcpHandler::OnNotifyExiting(lParam); UpdateResultMessage(spNode); return hr; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::OnResultUpdateView Implementation of ITFSResultHandler::OnResultUpdateView Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::OnResultUpdateView ( ITFSComponent *pComponent, LPDATAOBJECT pDataObject, LPARAM data, LPARAM hint ) { HRESULT hr = hrOK; SPITFSNode spSelectedNode; pComponent->GetSelectedNode(&spSelectedNode); if (spSelectedNode == NULL) return S_OK; // no selection for our IComponentData if ( hint == DHCPSNAP_UPDATE_OPTIONS ) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); SPITFSNode spSelectedNode; pComponent->GetSelectedNode(&spSelectedNode); EnumerateResultPane(pComponent, (MMC_COOKIE) spSelectedNode.p, 0, 0); } else { // we don't handle this message, let the base class do it. return CMTDhcpHandler::OnResultUpdateView(pComponent, pDataObject, data, hint); } return hr; } /*!-------------------------------------------------------------------------- CDhcpReservationClient::EnumerateResultPane We override this function for the options nodes for one reason. Whenever an option class is deleted, then all options defined for that class will be removed as well. Since there are multiple places that these options may show up, it's easier to just not show any options that don't have a class defined for it. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::EnumerateResultPane ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CClassInfoArray ClassInfoArray; SPITFSNode spContainer, spServerNode; CDhcpServer * pServer; COptionValueEnum * aEnum[3]; int aImages[3] = {ICON_IDX_CLIENT_OPTION_LEAF, ICON_IDX_SCOPE_OPTION_LEAF, ICON_IDX_SERVER_OPTION_LEAF}; m_spNodeMgr->FindNode(cookie, &spContainer); spServerNode = GetServerNode(spContainer, TRUE); pServer = GETHANDLER(CDhcpServer, spServerNode); pServer->GetClassInfoArray(ClassInfoArray); aEnum[0] = GetOptionValueEnum(); aEnum[1] = GetScopeObject(spContainer, TRUE)->GetOptionValueEnum(); aEnum[2] = pServer->GetOptionValueEnum(); aEnum[0]->Reset(); aEnum[1]->Reset(); aEnum[2]->Reset(); return OnResultUpdateOptions(pComponent, spContainer, &ClassInfoArray, aEnum, aImages, 3); } /*--------------------------------------------------------------------------- Helper functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservationClient::GetDnsRegistration Gets the DNS registration option value Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpReservationClient::GetDnsRegistration ( ITFSNode * pNode, LPDWORD pDnsRegOption ) { // // Check option 81 -- the DNS registration option // CDhcpScope * pScope = GetScopeObject(pNode, TRUE); DHCP_OPTION_VALUE * poptValue = NULL; DWORD err = pScope->GetOptionValue(OPTION_DNS_REGISTATION, DhcpReservedOptions, &poptValue, m_dhcpClientIpAddress); // this is the default if (pDnsRegOption) *pDnsRegOption = DHCP_DYN_DNS_DEFAULT; if (err == ERROR_SUCCESS) { if ((poptValue->Value.Elements != NULL) && (pDnsRegOption)) { *pDnsRegOption = poptValue->Value.Elements[0].Element.DWordOption; } } else { Trace0("CDhcpReservationClient::GetDnsRegistration - couldn't get DNS reg value -- \ option may not be defined, Getting Scope value.\n"); err = pScope->GetDnsRegistration(pDnsRegOption); } if (poptValue) ::DhcpRpcFreeMemory(poptValue); return err; } /*--------------------------------------------------------------------------- CDhcpReservationClient::SetDnsRegistration Sets the DNS Registration option for this scope Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpReservationClient::SetDnsRegistration ( ITFSNode * pNode, DWORD DnsRegOption ) { CDhcpScope * pScope = GetScopeObject(pNode, TRUE); DWORD err = 0; // // Set DNS name registration (option 81) // CDhcpOption dhcpOption (OPTION_DNS_REGISTATION, DhcpDWordOption , _T(""), _T("")); dhcpOption.QueryValue().SetNumber(DnsRegOption); err = pScope->SetOptionValue(&dhcpOption, DhcpReservedOptions, m_dhcpClientIpAddress); return err; } /*--------------------------------------------------------------------------- CDhcpReservationClient::BuildDisplayName Builds the display name string Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::BuildDisplayName ( CString * pstrDisplayName, LPCTSTR pIpAddress, LPCTSTR pName ) { if (pstrDisplayName) { CString strTemp = pIpAddress; strTemp = L"[" + strTemp + L"]"; if (pName) { CString strName = pName; strTemp += L" " + strName; } *pstrDisplayName = strTemp; } return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::BuildDisplayName Updates the cached name for this reservation and updates the UI Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::SetName ( LPCTSTR pName ) { if (pName != NULL) { if (m_pstrClientName) { *m_pstrClientName = pName; } else { m_pstrClientName = new CString(pName); } } else { if (m_pstrClientName) { delete m_pstrClientName; m_pstrClientName = NULL; } } CString strIpAddress, strDisplayName; // // Create the display name for this scope // Convert DHCP_IP_ADDRES to a string and initialize this object // UtilCvtIpAddrToWstr (m_dhcpClientIpAddress, &strIpAddress); BuildDisplayName(&strDisplayName, strIpAddress, pName); SetDisplayName(strDisplayName); return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::BuildDisplayName Updates the cached comment for this reservation Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::SetComment ( LPCTSTR pComment ) { if (pComment != NULL) { if (m_pstrClientComment) { *m_pstrClientComment = pComment; } else { m_pstrClientComment = new CString(pComment); } } else { if (m_pstrClientComment) { delete m_pstrClientComment; m_pstrClientComment = NULL; } } return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::SetUID Updates the cached unique ID for this reservation Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpReservationClient::SetUID ( const CByteArray & baClientUID ) { m_baHardwareAddress.Copy(baClientUID); return hrOK; } /*--------------------------------------------------------------------------- CDhcpReservationClient::SetClientType Updates the cached client type for this record Author: EricDav ---------------------------------------------------------------------------*/ BYTE CDhcpReservationClient::SetClientType ( BYTE bClientType ) { BYTE bRet = m_bClientType; m_bClientType = bClientType; return bRet; } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpReservationClient::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpReservationClient::OnCreateQuery(ITFSNode * pNode) { CDhcpReservationClientQueryObj* pQuery = new CDhcpReservationClientQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(pNode, TRUE); pQuery->m_dhcpScopeAddress = GetScopeObject(pNode, TRUE)->GetAddress(); pQuery->m_dhcpClientIpAddress = m_dhcpClientIpAddress; GetScopeObject(pNode, TRUE)->GetServerVersion(pQuery->m_liDhcpVersion); GetScopeObject(pNode, TRUE)->GetDynBootpClassName(pQuery->m_strDynBootpClassName); pQuery->m_dhcpResumeHandle = NULL; pQuery->m_dwPreferredMax = 0xFFFFFFFF; return pQuery; } /*--------------------------------------------------------------------------- CDhcpReservationClientQueryObj::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpReservationClientQueryObj::Execute() { DWORD dwErr; COptionNodeEnum OptionNodeEnum(m_spTFSCompData, m_spNodeMgr); DHCP_OPTION_SCOPE_INFO dhcpOptionScopeInfo; COptionValueEnum * pOptionValueEnum = new COptionValueEnum; pOptionValueEnum->m_strDynBootpClassName = m_strDynBootpClassName; dhcpOptionScopeInfo.ScopeType = DhcpReservedOptions; dhcpOptionScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpAddress = m_dhcpClientIpAddress; dhcpOptionScopeInfo.ScopeInfo.ReservedScopeInfo.ReservedIpSubnetAddress = m_dhcpScopeAddress; pOptionValueEnum->Init(m_strServer, m_liDhcpVersion, dhcpOptionScopeInfo); dwErr = pOptionValueEnum->Enum(); // add all of the nodes if (dwErr != ERROR_SUCCESS) { Trace1("CDhcpReservationClientQueryObj::Execute - Enum Failed! %d\n", dwErr); m_dwErr = dwErr; PostError(dwErr); delete pOptionValueEnum; } else { pOptionValueEnum->SortById(); AddToQueue((LPARAM) pOptionValueEnum, DHCP_QDATA_OPTION_VALUES); } return hrFalse; } ///////////////////////////////////////////////////////////////////// // // CDhcpActiveLeases implementation // ///////////////////////////////////////////////////////////////////// /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpActiveLeases::CDhcpActiveLeases ( ITFSComponentData * pComponentData ) : CMTDhcpHandler(pComponentData) { } CDhcpActiveLeases::~CDhcpActiveLeases() { } /*!-------------------------------------------------------------------------- CDhcpActiveLeases::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeases::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; // // Create the display name for this scope // CString strTemp; strTemp.LoadString(IDS_ACTIVE_LEASES_FOLDER); SetDisplayName(strTemp); // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_ACTIVE_LEASES); pNode->SetData(TFS_DATA_SCOPE_LEAF_NODE, TRUE); SetColumnStringIDs(&aColumns[DHCPSNAP_ACTIVE_LEASES][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_ACTIVE_LEASES][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeases::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); DHCP_IP_ADDRESS dhcpIpAddress = GetScopeObject(pNode)->GetAddress(); UtilCvtIpAddrToWstr (dhcpIpAddress, &strIpAddress); strId = GetServerName(pNode) + strIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpActiveLeases::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { case notLoaded: case loaded: if (bOpenImage) nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_OPEN; else nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_CLOSED; break; case loading: if (bOpenImage) nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_OPEN_BUSY; else nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_CLOSED_BUSY; break; case unableToLoad: if (bOpenImage) nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_OPEN_LOST_CONNECTION; else nIndex = ICON_IDX_ACTIVE_LEASES_FOLDER_CLOSED_LOST_CONNECTION; break; default: ASSERT(FALSE); } return nIndex; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpActiveLeases::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); LONG fFlags = 0; HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { /* removed, using new MMC save list functionality strMenuText.LoadString(IDS_EXPORT_LEASE_INFO); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_EXPORT_LEASE_INFO, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); */ } } return hr; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpActiveLeases::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; case IDS_EXPORT_LEASE_INFO: OnExportLeases(pNode); break; default: break; } return hr; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnResultDelete This function is called when we are supposed to delete result pane items. We build a list of selected items and then delete them. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeases::OnResultDelete ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { HRESULT hr = hrOK; BOOL bIsRes, bIsActive, bBadAddress; AFX_MANAGE_STATE(AfxGetStaticModuleState()); // translate the cookie into a node pointer SPITFSNode spActiveLeases, spSelectedNode; m_spNodeMgr->FindNode(cookie, &spActiveLeases); pComponent->GetSelectedNode(&spSelectedNode); Assert(spSelectedNode == spActiveLeases); if (spSelectedNode != spActiveLeases) return hr; // build the list of selected nodes CTFSNodeList listNodesToDelete; hr = BuildSelectedItemList(pComponent, &listNodesToDelete); // // Confirm with the user // CString strMessage, strTemp; int nNodes = (int) listNodesToDelete.GetCount(); if (nNodes > 1) { strTemp.Format(_T("%d"), nNodes); AfxFormatString1(strMessage, IDS_DELETE_ITEMS, (LPCTSTR) strTemp); } else { strMessage.LoadString(IDS_DELETE_ITEM); } if (AfxMessageBox(strMessage, MB_YESNO) == IDNO) { return NOERROR; } // // Loop through all items deleting // BEGIN_WAIT_CURSOR; while (listNodesToDelete.GetCount() > 0) { SPITFSNode spActiveLeaseNode; spActiveLeaseNode = listNodesToDelete.RemoveHead(); CDhcpActiveLease * pActiveLease = GETHANDLER(CDhcpActiveLease, spActiveLeaseNode); // // delete the node, check to see if it is a reservation // bIsRes = pActiveLease->IsReservation(&bIsActive, &bBadAddress); if (bIsRes && !bBadAddress) { // // Delete the reservation // LPDHCP_CLIENT_INFO pdhcpClientInfo; DWORD dwError = GetScopeObject(spActiveLeases)->GetClientInfo(pActiveLease->GetIpAddress(), &pdhcpClientInfo); if (dwError == ERROR_SUCCESS) { dwError = GetScopeObject(spActiveLeases)->DeleteReservation(pdhcpClientInfo->ClientHardwareAddress, pdhcpClientInfo->ClientIpAddress); if (dwError == ERROR_SUCCESS) { // // Tell the reservations folder to remove this from it's list // SPITFSNode spReservationsNode; GetScopeObject(spActiveLeases)->GetReservationsNode(&spReservationsNode); GetScopeObject(spActiveLeases)->GetReservationsObject()-> RemoveReservationFromUI((ITFSNode *) spReservationsNode, pActiveLease->GetIpAddress()); spActiveLeases->RemoveChild(spActiveLeaseNode); } else { UtilCvtIpAddrToWstr(pActiveLease->GetIpAddress(), &strTemp); AfxFormatString1(strMessage, IDS_ERROR_DELETING_RECORD, (LPCTSTR) strTemp); if (::DhcpMessageBoxEx(dwError, strMessage, MB_OKCANCEL) == IDCANCEL) { break; } RESTORE_WAIT_CURSOR; Trace1("Delete reservation failed %lx\n", dwError); hr = E_FAIL; } ::DhcpRpcFreeMemory(pdhcpClientInfo); } else { UtilCvtIpAddrToWstr(pActiveLease->GetIpAddress(), &strTemp); AfxFormatString1(strMessage, IDS_ERROR_DELETING_RECORD, (LPCTSTR) strTemp); if (::DhcpMessageBoxEx(dwError, strMessage, MB_OKCANCEL) == IDCANCEL) { break; } RESTORE_WAIT_CURSOR; Trace1("GetClientInfo failed %lx\n", dwError); hr = E_FAIL; } } else { DWORD dwError = GetScopeObject(spActiveLeases)->DeleteClient(pActiveLease->GetIpAddress()); if (dwError == ERROR_SUCCESS) { // // Client gone, now remove from UI // spActiveLeases->RemoveChild(spActiveLeaseNode); // if we are deleting a lot of addresses, then we can hit the server hard.. // lets take a short time out to smooth out the process Sleep(5); } else { UtilCvtIpAddrToWstr(pActiveLease->GetIpAddress(), &strTemp); AfxFormatString1(strMessage, IDS_ERROR_DELETING_RECORD, (LPCTSTR) strTemp); if (::DhcpMessageBoxEx(dwError, strMessage, MB_OKCANCEL) == IDCANCEL) { break; } RESTORE_WAIT_CURSOR; Trace1("DhcpDeleteClientInfo failed %lx\n", dwError); hr = E_FAIL; } } spActiveLeaseNode.Release(); } // update stats GetScopeObject(spActiveLeases)->TriggerStatsRefresh(); END_WAIT_CURSOR; return hr; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::DeleteClient The reservations object will call this when a reservation is deleted. Since a reservation also has an active lease record, we have to delete it as well. Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpActiveLeases::DeleteClient ( ITFSNode * pActiveLeasesNode, DHCP_IP_ADDRESS dhcpIpAddress ) { DWORD dwError = E_UNEXPECTED; CDhcpActiveLease * pActiveLease = NULL; SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; pActiveLeasesNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { pActiveLease = GETHANDLER(CDhcpActiveLease, spCurrentNode); if (dhcpIpAddress == pActiveLease->GetIpAddress()) { // // Tell this reservation to delete itself // pActiveLeasesNode->RemoveChild(spCurrentNode); spCurrentNode.Release(); dwError = ERROR_SUCCESS; break; } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } return dwError; } /*!-------------------------------------------------------------------------- CDhcpActiveLeases::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeases::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { *pViewOptions = MMC_VIEW_OPTIONS_MULTISELECT; // we still want the default MMC result pane view, we just want // multiselect, so return S_FALSE return S_FALSE; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::CompareItems Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CDhcpActiveLeases::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { SPITFSNode spNode1, spNode2; m_spNodeMgr->FindNode(cookieA, &spNode1); m_spNodeMgr->FindNode(cookieB, &spNode2); int nCompare = 0; CDhcpActiveLease *pDhcpAL1 = GETHANDLER(CDhcpActiveLease, spNode1); CDhcpActiveLease *pDhcpAL2 = GETHANDLER(CDhcpActiveLease, spNode2); switch (nCol) { case 0: { // IP address compare // nCompare = CompareIpAddresses(pDhcpAL1, pDhcpAL2); } break; case 1: { // Client Name compare // CString strAL1 = pDhcpAL1->GetString(pComponent, cookieA, nCol); CString strAL2 = pDhcpAL2->GetString(pComponent, cookieA, nCol); nCompare = strAL1.CompareNoCase(strAL2); } break; case 2: { // Lease expiration compare // BOOL bIsActive1, bIsActive2; BOOL bIsBad1, bIsBad2; BOOL bIsRes1 = pDhcpAL1->IsReservation(&bIsActive1, &bIsBad1); BOOL bIsRes2 = pDhcpAL2->IsReservation(&bIsActive2, &bIsBad2); // // Check to see if these are reservations // if (bIsRes1 && bIsRes2) { // // Figure out if this is a bad address // They go first // if (bIsBad1 && bIsBad2) { // // Sort by IP Address // nCompare = CompareIpAddresses(pDhcpAL1, pDhcpAL2); } else if (bIsBad1) nCompare = -1; else if (bIsBad2) nCompare = 1; else if ((bIsActive1 && bIsActive2) || (!bIsActive1 && !bIsActive2)) { // // if both reservations are either active/inactive // sort by IP address // nCompare = CompareIpAddresses(pDhcpAL1, pDhcpAL2); } else if (bIsActive1) nCompare = -1; else nCompare = 1; } else if (bIsRes1) { nCompare = -1; } else if (bIsRes2) { nCompare = 1; } else { CTime timeAL1, timeAL2; pDhcpAL1->GetLeaseExpirationTime(timeAL1); pDhcpAL2->GetLeaseExpirationTime(timeAL2); if (timeAL1 < timeAL2) nCompare = -1; else if (timeAL1 > timeAL2) nCompare = 1; } // default is that they are equal } break; case 3: { // Client Type Compare CString strAL1 = pDhcpAL1->GetString(pComponent, cookieA, nCol); CString strAL2 = pDhcpAL2->GetString(pComponent, cookieA, nCol); nCompare = strAL1.Compare(strAL2); } break; case 4: { CString strUID1 = pDhcpAL1->GetUID(); nCompare = strUID1.CompareNoCase(pDhcpAL2->GetUID()); } break; case 5: { CString strComment1 = pDhcpAL1->GetComment(); nCompare = strComment1.CompareNoCase(pDhcpAL2->GetComment()); } break; } return nCompare; } /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpActiveLeases::CompareIpAddresses ( CDhcpActiveLease * pDhcpAL1, CDhcpActiveLease * pDhcpAL2 ) { int nCompare = 0; DHCP_IP_ADDRESS dhcpIp1 = pDhcpAL1->GetIpAddress(); DHCP_IP_ADDRESS dhcpIp2 = pDhcpAL2->GetIpAddress(); if (dhcpIp1 < dhcpIp2) nCompare = -1; else if (dhcpIp1 > dhcpIp2) nCompare = 1; return nCompare; } /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnExportLeases() - Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeases::OnExportLeases(ITFSNode * pNode) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; // Bring up the Save Dialog SPITFSNodeEnum spNodeEnum; SPITFSNode spCurrentNode; ULONG nNumReturned = 0; CString strType; CString strDefFileName; CString strFilter; CString strTitle; CString strFileName; strType.LoadString(IDS_FILE_EXTENSION); strDefFileName.LoadString(IDS_FILE_DEFNAME); strFilter.LoadString(IDS_STR_EXPORTFILE_FILTER); CFileDialog cFileDlg(FALSE, strType, strDefFileName, OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, strFilter);//_T("Comma Separated Files (*.csv)|*.csv||") ); strTitle.LoadString(IDS_EXPFILE_TITLE); cFileDlg.m_ofn.lpstrTitle = strTitle; // put up the file dialog if( cFileDlg.DoModal() != IDOK ) return hrFalse; strFileName = cFileDlg.GetPathName(); COM_PROTECT_TRY { CString strContent; CString strLine; CString strTemp; CString strDelim = _T(','); CString strNewLine = _T("\r\n"); int nCount = 0; // create a file named "WinsExp.txt" in the current directory CFile cFileExp(strFileName, CFile::modeCreate | CFile::modeRead | CFile::modeWrite); // this is a unicode file, write the unicde lead bytes (2) cFileExp.Write(&gwUnicodeHeader, sizeof(WORD)); // write the header for (int i = 0; i < MAX_COLUMNS; i++) { if (aColumns[DHCPSNAP_ACTIVE_LEASES][i]) { if (!strLine.IsEmpty()) strLine += strDelim; strTemp.LoadString(aColumns[DHCPSNAP_ACTIVE_LEASES][i]); strLine += strTemp; } } strLine += strNewLine; cFileExp.Write(strLine, strLine.GetLength()*sizeof(TCHAR)); cFileExp.SeekToEnd(); BEGIN_WAIT_CURSOR #ifdef DEBUG CTime timeStart, timeFinish; timeStart = CTime::GetCurrentTime(); #endif // enumerate all the leases and output pNode->GetEnum(&spNodeEnum); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); while (nNumReturned) { CDhcpActiveLease * pLease = GETHANDLER(CDhcpActiveLease, spCurrentNode); strLine.Empty(); // ipaddr, name, type, lease exp, UID, comment for (int j = 0; j < 6; j++) { if (!strLine.IsEmpty()) strLine += strDelim; strLine += pLease->GetString(NULL, NULL, j); } strLine += strNewLine; strContent += strLine; nCount++; //optimize // write to the file for every 1000 records converted if( nCount % 1000 == 0) { cFileExp.Write(strContent, strContent.GetLength() * (sizeof(TCHAR)) ); cFileExp.SeekToEnd(); // clear all the strings now strContent.Empty(); } spCurrentNode.Release(); spNodeEnum->Next(1, &spCurrentNode, &nNumReturned); } // write to the file cFileExp.Write(strContent, strContent.GetLength() * (sizeof(TCHAR)) ); cFileExp.Close(); #ifdef DEBUG timeFinish = CTime::GetCurrentTime(); CTimeSpan timeDelta = timeFinish - timeStart; Trace2("ActiveLeases - Export Entries: %d records written, total time %s\n", nCount, timeDelta.Format(_T("%H:%M:%S"))); #endif END_WAIT_CURSOR } COM_PROTECT_CATCH CString strDisp; AfxFormatString1(strDisp, IDS_EXPORT_SUCCESS, strFileName); AfxMessageBox(strDisp, MB_ICONINFORMATION ); return hr; } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpActiveLeases::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpActiveLeases::OnCreateQuery(ITFSNode * pNode) { CDhcpActiveLeasesQueryObj* pQuery = new CDhcpActiveLeasesQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(pNode); pQuery->m_dhcpScopeAddress = GetScopeObject(pNode)->GetAddress(); pQuery->m_dhcpResumeHandle = NULL; pQuery->m_dwPreferredMax = 2000; GetServerVersion(pNode, pQuery->m_liDhcpVersion); return pQuery; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpActiveLeasesQueryObj::Execute() { HRESULT hr; BuildReservationList(); if (m_liDhcpVersion.QuadPart >= DHCP_NT5_VERSION) { hr = EnumerateLeasesV5(); } else if (m_liDhcpVersion.QuadPart >= DHCP_SP2_VERSION) { hr = EnumerateLeasesV4(); } else { hr = EnumerateLeases(); } return hr; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::IsReservation() Description Author: EricDav ---------------------------------------------------------------------------*/ BOOL CDhcpActiveLeasesQueryObj::IsReservation(DWORD dwIp) { BOOL fIsRes = FALSE; for (int i = 0; i < m_ReservationArray.GetSize(); i++) { if (m_ReservationArray[i] == dwIp) { fIsRes = TRUE; break; } } return fIsRes; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::BuildReservationList() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeasesQueryObj::BuildReservationList() { LPDHCP_SUBNET_ELEMENT_INFO_ARRAY pdhcpSubnetElementArray = NULL; DHCP_RESUME_HANDLE dhcpResumeHandle = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; DWORD dwError = ERROR_MORE_DATA; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElements(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, DhcpReservedIps, &dhcpResumeHandle, -1, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace3("BuildReservationList: Scope %lx Reservations read %d, total %d\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal); if (dwElementsRead && dwElementsTotal && pdhcpSubnetElementArray) { // // Loop through the array that was returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { m_ReservationArray.Add(pdhcpSubnetElementArray->Elements[i].Element.ReservedIp->ReservedIpAddress); } } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: BuildReservationList error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::EnumerateLeasesV5() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeasesQueryObj::EnumerateLeasesV5() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_CLIENT_INFO_ARRAY_V5 pdhcpClientArrayV5 = NULL; DWORD dwClientsRead = 0, dwClientsTotal = 0; DWORD dwEnumedClients = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetClientsV5(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, &m_dhcpResumeHandle, m_dwPreferredMax, &pdhcpClientArrayV5, &dwClientsRead, &dwClientsTotal); if (dwClientsRead && dwClientsTotal && pdhcpClientArrayV5) { // // loop through all of the elements that were returned // for (DWORD i = 0; i < dwClientsRead; i++) { CDhcpActiveLease * pDhcpActiveLease; // // Create the result pane item for this element // SPITFSNode spNode; pDhcpActiveLease = new CDhcpActiveLease(m_spTFSCompData, pdhcpClientArrayV5->Clients[i]); // filter these types of records out if (pDhcpActiveLease->IsUnreg()) { delete pDhcpActiveLease; continue; } if (IsReservation(pdhcpClientArrayV5->Clients[i]->ClientIpAddress)) pDhcpActiveLease->SetReservation(TRUE); CreateLeafTFSNode(&spNode, &GUID_DhcpActiveLeaseNodeType, pDhcpActiveLease, pDhcpActiveLease, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpActiveLease->InitializeNode(spNode); AddToQueue(spNode); pDhcpActiveLease->Release(); } ::DhcpRpcFreeMemory(pdhcpClientArrayV5); dwEnumedClients += dwClientsRead; dwClientsRead = 0; dwClientsTotal = 0; pdhcpClientArrayV5 = NULL; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateLeasesV5 error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } Trace1("DHCP snapin: V5 Leases enumerated: %d\n", dwEnumedClients); return hrFalse; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::EnumerateLeasesV4() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeasesQueryObj::EnumerateLeasesV4() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_CLIENT_INFO_ARRAY_V4 pdhcpClientArrayV4 = NULL; DWORD dwClientsRead = 0, dwClientsTotal = 0; DWORD dwEnumedClients = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetClientsV4(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, &m_dhcpResumeHandle, m_dwPreferredMax, &pdhcpClientArrayV4, &dwClientsRead, &dwClientsTotal); if (dwClientsRead && dwClientsTotal && pdhcpClientArrayV4) { // // loop through all of the elements that were returned // //for (DWORD i = 0; i < pdhcpClientArrayV4->NumElements; i++) for (DWORD i = 0; i < dwClientsRead; i++) { CDhcpActiveLease * pDhcpActiveLease; // // Create the result pane item for this element // SPITFSNode spNode; pDhcpActiveLease = new CDhcpActiveLease(m_spTFSCompData, pdhcpClientArrayV4->Clients[i]); // filter these types of records out if (pDhcpActiveLease->IsGhost() || pDhcpActiveLease->IsUnreg() || pDhcpActiveLease->IsDoomed() ) { delete pDhcpActiveLease; continue; } if (IsReservation(pdhcpClientArrayV4->Clients[i]->ClientIpAddress)) pDhcpActiveLease->SetReservation(TRUE); CreateLeafTFSNode(&spNode, &GUID_DhcpActiveLeaseNodeType, pDhcpActiveLease, pDhcpActiveLease, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpActiveLease->InitializeNode(spNode); AddToQueue(spNode); pDhcpActiveLease->Release(); } ::DhcpRpcFreeMemory(pdhcpClientArrayV4); dwEnumedClients += dwClientsRead; dwClientsRead = 0; dwClientsTotal = 0; pdhcpClientArrayV4 = NULL; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateLeasesV4 error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } Trace1("DHCP snapin: V4 Leases enumerated: %d\n", dwEnumedClients); return hrFalse; } /*--------------------------------------------------------------------------- CDhcpActiveLeasesQueryObj::EnumerateLeases() Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpActiveLeasesQueryObj::EnumerateLeases() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_CLIENT_INFO_ARRAY pdhcpClientArray = NULL; DWORD dwClientsRead = 0, dwClientsTotal = 0; DWORD dwEnumedClients = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetClients(((LPWSTR) (LPCTSTR)m_strServer), m_dhcpScopeAddress, &m_dhcpResumeHandle, m_dwPreferredMax, &pdhcpClientArray, &dwClientsRead, &dwClientsTotal); if (dwClientsRead && dwClientsTotal && pdhcpClientArray) { // // loop through all of the elements that were returned // for (DWORD i = 0; i < pdhcpClientArray->NumElements; i++) { CDhcpActiveLease * pDhcpActiveLease; // // Create the result pane item for this element // SPITFSNode spNode; pDhcpActiveLease = new CDhcpActiveLease(m_spTFSCompData,pdhcpClientArray->Clients[i]); // filter these types of records out if (pDhcpActiveLease->IsGhost() || pDhcpActiveLease->IsUnreg() || pDhcpActiveLease->IsDoomed() ) { delete pDhcpActiveLease; continue; } if (IsReservation(pdhcpClientArray->Clients[i]->ClientIpAddress)) pDhcpActiveLease->SetReservation(TRUE); CreateLeafTFSNode(&spNode, &GUID_DhcpActiveLeaseNodeType, pDhcpActiveLease, pDhcpActiveLease, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpActiveLease->InitializeNode(spNode); AddToQueue(spNode); pDhcpActiveLease->Release(); } ::DhcpRpcFreeMemory(pdhcpClientArray); dwEnumedClients += dwClientsRead; dwClientsRead = 0; dwClientsTotal = 0; pdhcpClientArray = NULL; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateLeases error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } Trace1("DHCP snpain: Leases enumerated: %d\n", dwEnumedClients); return hrFalse; } /*--------------------------------------------------------------------------- Class CDhcpAddressPool implementation ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ CDhcpAddressPool::CDhcpAddressPool ( ITFSComponentData * pComponentData ) : CMTDhcpHandler(pComponentData) { } CDhcpAddressPool::~CDhcpAddressPool() { } /*!-------------------------------------------------------------------------- CDhcpAddressPool::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPool::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; // // Create the display name for this scope // CString strTemp; strTemp.LoadString(IDS_ADDRESS_POOL_FOLDER); SetDisplayName(strTemp); // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_ADDRESS_POOL); pNode->SetData(TFS_DATA_SCOPE_LEAF_NODE, TRUE); SetColumnStringIDs(&aColumns[DHCPSNAP_ADDRESS_POOL][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_ADDRESS_POOL][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpAddressPool::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPool::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); DHCP_IP_ADDRESS dhcpIpAddress = GetScopeObject(pNode)->GetAddress(); UtilCvtIpAddrToWstr (dhcpIpAddress, &strIpAddress); strId = GetServerName(pNode) + strIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpAddressPool::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpAddressPool::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { case notLoaded: case loaded: if (bOpenImage) nIndex = ICON_IDX_ADDR_POOL_FOLDER_OPEN; else nIndex = ICON_IDX_ADDR_POOL_FOLDER_CLOSED; break; case loading: if (bOpenImage) nIndex = ICON_IDX_ADDR_POOL_FOLDER_OPEN_BUSY; else nIndex = ICON_IDX_ADDR_POOL_FOLDER_CLOSED_BUSY; break; case unableToLoad: if (bOpenImage) nIndex = ICON_IDX_ADDR_POOL_FOLDER_OPEN_LOST_CONNECTION; else nIndex = ICON_IDX_ADDR_POOL_FOLDER_CLOSED_LOST_CONNECTION; break; default: ASSERT(FALSE); } return nIndex; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpAddressPool::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpAddressPool::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); LONG fFlags = 0; HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { // these menu items go in the new menu, // only visible from scope pane if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { strMenuText.LoadString(IDS_CREATE_NEW_EXCLUSION); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_CREATE_NEW_EXCLUSION, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } return hr; } /*--------------------------------------------------------------------------- CDhcpAddressPool::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpAddressPool::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_CREATE_NEW_EXCLUSION: OnCreateNewExclusion(pNode); break; case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; default: break; } return hr; } /*--------------------------------------------------------------------------- Message handlers ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpAddressPool::OnCreateNewExclusion Description Author: EricDav ---------------------------------------------------------------------------*/ DWORD CDhcpAddressPool::OnCreateNewExclusion ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spScopeNode; pNode->GetParent(&spScopeNode); CAddExclusion dlgAddExclusion(spScopeNode); dlgAddExclusion.DoModal(); return 0; } /*--------------------------------------------------------------------------- CDhcpAddressPool::OnResultDelete This function is called when we are supposed to delete result pane items. We build a list of selected items and then delete them. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPool::OnResultDelete ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { HRESULT hr = NOERROR; BOOL bIsRes, bIsActive, bBadAddress; AFX_MANAGE_STATE(AfxGetStaticModuleState()); // translate the cookie into a node pointer SPITFSNode spAddressPool, spSelectedNode; m_spNodeMgr->FindNode(cookie, &spAddressPool); pComponent->GetSelectedNode(&spSelectedNode); Assert(spSelectedNode == spAddressPool); if (spSelectedNode != spAddressPool) return hr; // build the list of selected nodes CTFSNodeList listNodesToDelete; hr = BuildSelectedItemList(pComponent, &listNodesToDelete); // // Confirm with the user // CString strMessage, strTemp; int nNodes = (int)listNodesToDelete.GetCount(); if (nNodes > 1) { strTemp.Format(_T("%d"), nNodes); AfxFormatString1(strMessage, IDS_DELETE_ITEMS, (LPCTSTR) strTemp); } else { strMessage.LoadString(IDS_DELETE_ITEM); } if (AfxMessageBox(strMessage, MB_YESNO) == IDNO) { return NOERROR; } // // Loop through all items deleting // BEGIN_WAIT_CURSOR; while (listNodesToDelete.GetCount() > 0) { SPITFSNode spExclusionRangeNode; spExclusionRangeNode = listNodesToDelete.RemoveHead(); CDhcpExclusionRange * pExclusion = GETHANDLER(CDhcpExclusionRange, spExclusionRangeNode); if (spExclusionRangeNode->GetData(TFS_DATA_TYPE) == DHCPSNAP_ALLOCATION_RANGE) { // // This is the allocation range, can't delete // AfxMessageBox(IDS_CANNOT_DELETE_ALLOCATION_RANGE); spExclusionRangeNode.Release(); continue; } // // Try to remove it from the server // CDhcpIpRange dhcpIpRange((DHCP_IP_RANGE) *pExclusion); DWORD dwError = GetScopeObject(spAddressPool)->RemoveExclusion(dhcpIpRange); if (dwError != 0) { ::DhcpMessageBox(dwError); RESTORE_WAIT_CURSOR; hr = E_FAIL; continue; } // // Remove from UI now // spAddressPool->RemoveChild(spExclusionRangeNode); spExclusionRangeNode.Release(); } // update stats GetScopeObject(spAddressPool)->TriggerStatsRefresh(); END_WAIT_CURSOR; return hr; } /*!-------------------------------------------------------------------------- CDhcpAddressPool::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPool::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { *pViewOptions = MMC_VIEW_OPTIONS_MULTISELECT; // we still want the default MMC result pane view, we just want // multiselect, so return S_FALSE return S_FALSE; } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpAddressPool::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpAddressPool::OnCreateQuery(ITFSNode * pNode) { CDhcpAddressPoolQueryObj* pQuery = new CDhcpAddressPoolQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(pNode); CDhcpScope * pScope = GetScopeObject(pNode); if (pScope) { pQuery->m_dhcpScopeAddress = pScope->GetAddress(); pQuery->m_fSupportsDynBootp = pScope->GetServerObject()->FSupportsDynBootp(); } pQuery->m_dhcpExclResumeHandle = NULL; pQuery->m_dwExclPreferredMax = 0xFFFFFFFF; pQuery->m_dhcpIpResumeHandle = NULL; pQuery->m_dwIpPreferredMax = 0xFFFFFFFF; return pQuery; } /*--------------------------------------------------------------------------- CDhcpAddressPoolQueryObj::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpAddressPoolQueryObj::Execute() { HRESULT hr1 = EnumerateIpRanges(); HRESULT hr2 = EnumerateExcludedIpRanges(); if (hr1 == hrOK || hr2 == hrOK) return hrOK; else return hrFalse; } /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPoolQueryObj::EnumerateExcludedIpRanges() { DWORD dwError = ERROR_MORE_DATA; DHCP_RESUME_HANDLE dhcpResumeHandle = 0; LPDHCP_SUBNET_ELEMENT_INFO_ARRAY pdhcpSubnetElementArray = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElements((LPWSTR) ((LPCTSTR) m_strServer), m_dhcpScopeAddress, DhcpExcludedIpRanges, &m_dhcpExclResumeHandle, m_dwExclPreferredMax, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace3("Scope %lx Excluded Ip Ranges read %d, total %d\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal); if (dwElementsRead && dwElementsTotal && pdhcpSubnetElementArray) { // // loop through all of the elements that were returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpExclusionRange * pDhcpExclusionRange = new CDhcpExclusionRange(m_spTFSCompData, pdhcpSubnetElementArray->Elements[i].Element.ExcludeIpRange); CreateLeafTFSNode(&spNode, &GUID_DhcpExclusionNodeType, pDhcpExclusionRange, pDhcpExclusionRange, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpExclusionRange->InitializeNode(spNode); AddToQueue(spNode); pDhcpExclusionRange->Release(); } // Free up the memory from the RPC call // ::DhcpRpcFreeMemory(pdhcpSubnetElementArray); } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateExcludedIpRanges error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } /*--------------------------------------------------------------------------- Function Name Here Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpAddressPoolQueryObj::EnumerateIpRanges() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_SUBNET_ELEMENT_INFO_ARRAY pdhcpSubnetElementArray = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; if (m_fSupportsDynBootp) { return EnumerateIpRangesV5(); } while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElements((LPWSTR) ((LPCTSTR) m_strServer), m_dhcpScopeAddress, DhcpIpRanges, &m_dhcpIpResumeHandle, m_dwIpPreferredMax, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace4("Scope %lx allocation ranges read %d, total %d, dwError = %lx\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal, dwError); if ((dwError == ERROR_MORE_DATA) || ( (dwElementsRead) && (dwError == ERROR_SUCCESS) )) { // // Loop through the array that was returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpAllocationRange * pDhcpAllocRange = new CDhcpAllocationRange(m_spTFSCompData, pdhcpSubnetElementArray->Elements[i].Element.IpRange); CreateLeafTFSNode(&spNode, &GUID_DhcpAllocationNodeType, pDhcpAllocRange, pDhcpAllocRange, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpAllocRange->InitializeNode(spNode); AddToQueue(spNode); pDhcpAllocRange->Release(); } ::DhcpRpcFreeMemory(pdhcpSubnetElementArray); } else if (dwError != ERROR_SUCCESS && dwError != ERROR_NO_MORE_ITEMS) { // set the error variable so that it can be looked at later m_dwError = dwError; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateAllocationRanges error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } HRESULT CDhcpAddressPoolQueryObj::EnumerateIpRangesV5() { DWORD dwError = ERROR_MORE_DATA; LPDHCP_SUBNET_ELEMENT_INFO_ARRAY_V5 pdhcpSubnetElementArray = NULL; DWORD dwElementsRead = 0, dwElementsTotal = 0; while (dwError == ERROR_MORE_DATA) { dwError = ::DhcpEnumSubnetElementsV5((LPWSTR) ((LPCTSTR) m_strServer), m_dhcpScopeAddress, DhcpIpRangesDhcpBootp, &m_dhcpIpResumeHandle, m_dwIpPreferredMax, &pdhcpSubnetElementArray, &dwElementsRead, &dwElementsTotal); Trace4("EnumerateIpRangesV5: Scope %lx allocation ranges read %d, total %d, dwError = %lx\n", m_dhcpScopeAddress, dwElementsRead, dwElementsTotal, dwError); if ((dwError == ERROR_MORE_DATA) || ( (dwElementsRead) && (dwError == ERROR_SUCCESS) )) { // // Loop through the array that was returned // for (DWORD i = 0; i < pdhcpSubnetElementArray->NumElements; i++) { // // Create the result pane item for this element // SPITFSNode spNode; CDhcpAllocationRange * pDhcpAllocRange = new CDhcpAllocationRange(m_spTFSCompData, pdhcpSubnetElementArray->Elements[i].Element.IpRange); pDhcpAllocRange->SetRangeType(pdhcpSubnetElementArray->Elements[i].ElementType); CreateLeafTFSNode(&spNode, &GUID_DhcpAllocationNodeType, pDhcpAllocRange, pDhcpAllocRange, m_spNodeMgr); // Tell the handler to initialize any specific data pDhcpAllocRange->InitializeNode(spNode); AddToQueue(spNode); pDhcpAllocRange->Release(); } ::DhcpRpcFreeMemory(pdhcpSubnetElementArray); } else if (dwError != ERROR_SUCCESS && dwError != ERROR_NO_MORE_ITEMS) { // set the error variable so that it can be looked at later m_dwError = dwError; } // Check the abort flag on the thread if (FCheckForAbort() == hrOK) break; // check to see if we have an error and post it to the main thread if we do.. if (dwError != ERROR_NO_MORE_ITEMS && dwError != ERROR_SUCCESS && dwError != ERROR_MORE_DATA) { Trace1("DHCP snapin: EnumerateAllocationRanges error: %d\n", dwError); m_dwErr = dwError; PostError(dwError); } } return hrFalse; } /*--------------------------------------------------------------------------- CDhcpAddressPool::CompareItems Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CDhcpAddressPool::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { SPITFSNode spNode1, spNode2; m_spNodeMgr->FindNode(cookieA, &spNode1); m_spNodeMgr->FindNode(cookieB, &spNode2); int nCompare = 0; CDhcpAllocationRange *pDhcpAR1 = GETHANDLER(CDhcpAllocationRange, spNode1); CDhcpAllocationRange *pDhcpAR2 = GETHANDLER(CDhcpAllocationRange, spNode2); switch (nCol) { case 0: { // Start IP address compare // DHCP_IP_ADDRESS dhcpIp1 = pDhcpAR1->QueryAddr(TRUE); DHCP_IP_ADDRESS dhcpIp2 = pDhcpAR2->QueryAddr(TRUE); if (dhcpIp1 < dhcpIp2) nCompare = -1; else if (dhcpIp1 > dhcpIp2) nCompare = 1; // default is that they are equal } break; case 1: { // End IP address compare // DHCP_IP_ADDRESS dhcpIp1 = pDhcpAR1->QueryAddr(FALSE); DHCP_IP_ADDRESS dhcpIp2 = pDhcpAR2->QueryAddr(FALSE); if (dhcpIp1 < dhcpIp2) nCompare = -1; else if (dhcpIp1 > dhcpIp2) nCompare = 1; // default is that they are equal } break; case 2: { // Description compare // CString strRange1 = pDhcpAR1->GetString(pComponent, cookieA, nCol); CString strRange2 = pDhcpAR2->GetString(pComponent, cookieA, nCol); // Compare should not be case sensitive // strRange1.MakeUpper(); strRange2.MakeUpper(); nCompare = strRange1.Compare(strRange2); } break; } return nCompare; } /*--------------------------------------------------------------------------- CDhcpScopeOptions Implementation ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScopeOptions Constructor and destructor Author: EricDav ---------------------------------------------------------------------------*/ CDhcpScopeOptions::CDhcpScopeOptions ( ITFSComponentData * pComponentData ) : CMTDhcpHandler(pComponentData) { } CDhcpScopeOptions::~CDhcpScopeOptions() { } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::InitializeNode Initializes node specific data Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::InitializeNode ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); HRESULT hr = hrOK; // // Create the display name for this scope // CString strTemp; strTemp.LoadString(IDS_SCOPE_OPTIONS_FOLDER); SetDisplayName(strTemp); // Make the node immediately visible pNode->SetVisibilityState(TFS_VIS_SHOW); pNode->SetData(TFS_DATA_IMAGEINDEX, GetImageIndex(FALSE)); pNode->SetData(TFS_DATA_OPENIMAGEINDEX, GetImageIndex(TRUE)); pNode->SetData(TFS_DATA_COOKIE, (LPARAM) pNode); pNode->SetData(TFS_DATA_USER, (LPARAM) this); pNode->SetData(TFS_DATA_TYPE, DHCPSNAP_SCOPE_OPTIONS); pNode->SetData(TFS_DATA_SCOPE_LEAF_NODE, TRUE); SetColumnStringIDs(&aColumns[DHCPSNAP_SCOPE_OPTIONS][0]); SetColumnWidths(&aColumnWidths[DHCPSNAP_SCOPE_OPTIONS][0]); return hr; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnCreateNodeId2 Returns a unique string for this node Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnCreateNodeId2(ITFSNode * pNode, CString & strId, DWORD * dwFlags) { const GUID * pGuid = pNode->GetNodeType(); CString strIpAddress, strGuid; StringFromGUID2(*pGuid, strGuid.GetBuffer(256), 256); strGuid.ReleaseBuffer(); DHCP_IP_ADDRESS dhcpIpAddress = GetScopeObject(pNode)->GetAddress(); UtilCvtIpAddrToWstr (dhcpIpAddress, &strIpAddress); strId = GetServerName(pNode) + strIpAddress + strGuid; return hrOK; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::GetImageIndex Description Author: EricDav ---------------------------------------------------------------------------*/ int CDhcpScopeOptions::GetImageIndex(BOOL bOpenImage) { int nIndex = -1; switch (m_nState) { case notLoaded: case loaded: if (bOpenImage) nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_OPEN; else nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_CLOSED; break; case loading: if (bOpenImage) nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_OPEN_BUSY; else nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_CLOSED_BUSY; break; case unableToLoad: if (bOpenImage) nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_OPEN_LOST_CONNECTION; else nIndex = ICON_IDX_SCOPE_OPTION_FOLDER_CLOSED_LOST_CONNECTION; break; default: ASSERT(FALSE); } return nIndex; } /*--------------------------------------------------------------------------- Overridden base handler functions ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnAddMenuItems Adds entries to the context sensitive menu Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptions::OnAddMenuItems ( ITFSNode * pNode, LPCONTEXTMENUCALLBACK pContextMenuCallback, LPDATAOBJECT lpDataObject, DATA_OBJECT_TYPES type, DWORD dwType, long * pInsertionAllowed ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); LONG fFlags = 0; HRESULT hr = S_OK; CString strMenuText; if ( (m_nState != loaded) ) { fFlags |= MF_GRAYED; } if (type == CCT_SCOPE) { if (*pInsertionAllowed & CCM_INSERTIONALLOWED_TOP) { // these menu items go in the new menu, // only visible from scope pane strMenuText.LoadString(IDS_CREATE_OPTION_SCOPE); hr = LoadAndAddMenuItem( pContextMenuCallback, strMenuText, IDS_CREATE_OPTION_SCOPE, CCM_INSERTIONPOINTID_PRIMARY_TOP, fFlags ); ASSERT( SUCCEEDED(hr) ); } } return hr; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnCommand Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptions::OnCommand ( ITFSNode * pNode, long nCommandId, DATA_OBJECT_TYPES type, LPDATAOBJECT pDataObject, DWORD dwType ) { HRESULT hr = S_OK; switch (nCommandId) { case IDS_CREATE_OPTION_SCOPE: OnCreateNewOptions(pNode); break; case IDS_REFRESH: OnRefresh(pNode, pDataObject, dwType, 0, 0); break; default: break; } return hr; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::HasPropertyPages Implementation of ITFSNodeHandler::HasPropertyPages NOTE: the root node handler has to over-ride this function to handle the snapin manager property page (wizard) case!!! Author: KennT ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptions::HasPropertyPages ( ITFSNode * pNode, LPDATAOBJECT pDataObject, DATA_OBJECT_TYPES type, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); HRESULT hr = hrOK; // we have property pages in the normal case, but don't put the // menu up if we are not loaded yet if ( m_nState != loaded ) { hr = hrFalse; } else { hr = hrOK; } return hr; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::CreatePropertyPages Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptions::CreatePropertyPages ( ITFSNode * pNode, LPPROPERTYSHEETCALLBACK lpProvider, LPDATAOBJECT pDataObject, LONG_PTR handle, DWORD dwType ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); DWORD dwError; DWORD dwDynDnsFlags; HRESULT hr = hrOK; COptionsConfig * pOptCfg; CString strOptCfgTitle, strOptType; SPITFSNode spServerNode; SPIComponentData spComponentData; COptionValueEnum * pOptionValueEnum; // // Create the property page // COM_PROTECT_TRY { m_spNodeMgr->GetComponentData(&spComponentData); BEGIN_WAIT_CURSOR; strOptType.LoadString(IDS_CONFIGURE_OPTIONS_SCOPE); AfxFormatString1(strOptCfgTitle, IDS_CONFIGURE_OPTIONS_TITLE, strOptType); GetScopeObject(pNode)->GetServerNode(&spServerNode); pOptionValueEnum = GetScopeObject(pNode)->GetOptionValueEnum(); pOptCfg = new COptionsConfig(pNode, spServerNode, spComponentData, m_spTFSCompData, pOptionValueEnum, strOptCfgTitle); END_WAIT_CURSOR; // // Object gets deleted when the page is destroyed // Assert(lpProvider != NULL); hr = pOptCfg->CreateModelessSheet(lpProvider, handle); } COM_PROTECT_CATCH return hr; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnPropertyChange Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnPropertyChange ( ITFSNode * pNode, LPDATAOBJECT pDataobject, DWORD dwType, LPARAM arg, LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); COptionsConfig * pOptCfg = reinterpret_cast<COptionsConfig *>(lParam); LPARAM changeMask = 0; // tell the property page to do whatever now that we are back on the // main thread pOptCfg->OnPropertyChange(TRUE, &changeMask); pOptCfg->AcknowledgeNotify(); if (changeMask) pNode->ChangeNode(changeMask); return hrOK; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnPropertyChange Description Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnResultPropertyChange ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode; m_spNodeMgr->FindNode(cookie, &spNode); COptionsConfig * pOptCfg = reinterpret_cast<COptionsConfig *>(param); LPARAM changeMask = 0; // tell the property page to do whatever now that we are back on the // main thread pOptCfg->OnPropertyChange(TRUE, &changeMask); pOptCfg->AcknowledgeNotify(); if (changeMask) spNode->ChangeNode(changeMask); return hrOK; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::CompareItems Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP_(int) CDhcpScopeOptions::CompareItems ( ITFSComponent * pComponent, MMC_COOKIE cookieA, MMC_COOKIE cookieB, int nCol ) { SPITFSNode spNode1, spNode2; m_spNodeMgr->FindNode(cookieA, &spNode1); m_spNodeMgr->FindNode(cookieB, &spNode2); int nCompare = 0; CDhcpOptionItem *pOpt1 = GETHANDLER(CDhcpOptionItem, spNode1); CDhcpOptionItem *pOpt2 = GETHANDLER(CDhcpOptionItem, spNode2); switch (nCol) { case 0: { // // Name compare - use the option # // LONG_PTR uImage1 = spNode1->GetData(TFS_DATA_IMAGEINDEX); LONG_PTR uImage2 = spNode2->GetData(TFS_DATA_IMAGEINDEX); nCompare = UtilGetOptionPriority((int) uImage1, (int) uImage2); if (nCompare == 0) { DHCP_OPTION_ID id1 = pOpt1->GetOptionId(); DHCP_OPTION_ID id2 = pOpt2->GetOptionId(); if (id1 < id2) nCompare = -1; else if (id1 > id2) nCompare = 1; } } break; case 1: { // compare the vendor strings CString str1, str2; str1 = pOpt1->GetVendorDisplay(); str2 = pOpt2->GetVendorDisplay(); nCompare = str1.CompareNoCase(str2); } break; case 2: { // compare the printable values CString str1, str2; str1 = pOpt1->GetString( pComponent, cookieA, nCol ); str2 = pOpt2->GetString( pComponent, cookieB, nCol ); nCompare = str1.CompareNoCase( str2 ); break; } case 3: { CString str1, str2; str1 = pOpt1->GetClassName(); str2 = pOpt2->GetClassName(); nCompare = str1.CompareNoCase(str2); } break; } return nCompare; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::OnResultSelect Update the verbs and the result pane message Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnResultSelect(ITFSComponent *pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam) { HRESULT hr = hrOK; SPITFSNode spNode; CORg(CMTDhcpHandler::OnResultSelect(pComponent, pDataObject, cookie, arg, lParam)); CORg (pComponent->GetSelectedNode(&spNode)); if ( spNode != 0 ) { UpdateResultMessage(spNode); } Error: return hr; } /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnResultDelete This function is called when we are supposed to delete result pane items. We build a list of selected items and then delete them. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnResultDelete ( ITFSComponent * pComponent, LPDATAOBJECT pDataObject, MMC_COOKIE cookie, LPARAM arg, LPARAM param ) { HRESULT hr = hrOK; AFX_MANAGE_STATE(AfxGetStaticModuleState()); // translate the cookie into a node pointer SPITFSNode spScopeOpt, spSelectedNode; m_spNodeMgr->FindNode(cookie, &spScopeOpt); pComponent->GetSelectedNode(&spSelectedNode); Assert(spSelectedNode == spScopeOpt); if (spSelectedNode != spScopeOpt) return hr; // build the list of selected nodes CTFSNodeList listNodesToDelete; hr = BuildSelectedItemList(pComponent, &listNodesToDelete); // // Confirm with the user // CString strMessage, strTemp; int nNodes = (int)listNodesToDelete.GetCount(); if (nNodes > 1) { strTemp.Format(_T("%d"), nNodes); AfxFormatString1(strMessage, IDS_DELETE_ITEMS, (LPCTSTR) strTemp); } else { strMessage.LoadString(IDS_DELETE_ITEM); } if (AfxMessageBox(strMessage, MB_YESNO) == IDNO) { return NOERROR; } // check to make sure we are deleting just scope options POSITION pos = listNodesToDelete.GetHeadPosition(); while (pos) { ITFSNode * pNode = listNodesToDelete.GetNext(pos); if (pNode->GetData(TFS_DATA_IMAGEINDEX) != ICON_IDX_SCOPE_OPTION_LEAF) { // this option is not scope option. Put up a dialog telling the user what to do AfxMessageBox(IDS_CANNOT_DELETE_OPTION_SCOPE); return NOERROR; } } CString strServer = GetServerIpAddress(spScopeOpt); DHCP_OPTION_SCOPE_INFO dhcpOptionScopeInfo; dhcpOptionScopeInfo.ScopeType = DhcpSubnetOptions; dhcpOptionScopeInfo.ScopeInfo.SubnetScopeInfo = GetScopeObject(spScopeOpt)->GetAddress(); // // Loop through all items deleting // BEGIN_WAIT_CURSOR; while (listNodesToDelete.GetCount() > 0) { SPITFSNode spOptionNode; spOptionNode = listNodesToDelete.RemoveHead(); CDhcpOptionItem * pOptItem = GETHANDLER(CDhcpOptionItem, spOptionNode); // // Try to remove it from the server // DWORD dwError; if (pOptItem->IsVendorOption() || pOptItem->IsClassOption()) { LPCTSTR pClassName = pOptItem->GetClassName(); if (lstrlen(pClassName) == 0) pClassName = NULL; dwError = ::DhcpRemoveOptionValueV5((LPTSTR) ((LPCTSTR) strServer), pOptItem->IsVendorOption() ? DHCP_FLAGS_OPTION_IS_VENDOR : 0, pOptItem->GetOptionId(), (LPTSTR) pClassName, (LPTSTR) pOptItem->GetVendor(), &dhcpOptionScopeInfo); } else { dwError = ::DhcpRemoveOptionValue(strServer, pOptItem->GetOptionId(), &dhcpOptionScopeInfo); } if (dwError != 0) { ::DhcpMessageBox(dwError); RESTORE_WAIT_CURSOR; hr = E_FAIL; continue; } // // remove from our internal list // GetScopeObject(spScopeOpt)->GetOptionValueEnum()->Remove(pOptItem->GetOptionId(), pOptItem->GetVendor(), pOptItem->GetClassName()); // // Remove from UI now // spScopeOpt->RemoveChild(spOptionNode); spOptionNode.Release(); } END_WAIT_CURSOR; UpdateResultMessage(spScopeOpt); return hr; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::OnHaveData Description Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScopeOptions::OnHaveData ( ITFSNode * pParentNode, LPARAM Data, LPARAM Type ) { // This is how we get non-node data back from the background thread. switch (Type) { case DHCP_QDATA_OPTION_VALUES: { HRESULT hr = hrOK; SPIComponentData spCompData; SPIConsole spConsole; SPIDataObject spDataObject; IDataObject * pDataObject; CDhcpScope * pScope = GetScopeObject(pParentNode); COptionValueEnum * pOptionValueEnum = reinterpret_cast<COptionValueEnum *>(Data); pScope->SetOptionValueEnum(pOptionValueEnum); pOptionValueEnum->RemoveAll(); delete pOptionValueEnum; // now tell the view to update themselves m_spNodeMgr->GetComponentData(&spCompData); CORg ( spCompData->QueryDataObject((MMC_COOKIE) pParentNode, CCT_SCOPE, &pDataObject) ); spDataObject = pDataObject; CORg ( m_spNodeMgr->GetConsole(&spConsole) ); CORg ( spConsole->UpdateAllViews(pDataObject, (LPARAM) pParentNode, DHCPSNAP_UPDATE_OPTIONS) ); break; } } Error: return; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::OnResultUpdateView Implementation of ITFSResultHandler::OnResultUpdateView Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnResultUpdateView ( ITFSComponent *pComponent, LPDATAOBJECT pDataObject, LPARAM data, LPARAM hint ) { HRESULT hr = hrOK; SPITFSNode spSelectedNode; pComponent->GetSelectedNode(&spSelectedNode); if (spSelectedNode == NULL) return S_OK; // no selection for our IComponentData if ( hint == DHCPSNAP_UPDATE_OPTIONS ) { SPINTERNAL spInternal = ExtractInternalFormat(pDataObject); ITFSNode * pNode = reinterpret_cast<ITFSNode *>(spInternal->m_cookie); SPITFSNode spSelectedNode; pComponent->GetSelectedNode(&spSelectedNode); EnumerateResultPane(pComponent, (MMC_COOKIE) spSelectedNode.p, 0, 0); } else { // we don't handle this message, let the base class do it. return CMTDhcpHandler::OnResultUpdateView(pComponent, pDataObject, data, hint); } return hr; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::OnGetResultViewType MMC calls this to get the result view information Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnGetResultViewType ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPOLESTR * ppViewType, long * pViewOptions ) { HRESULT hr = hrOK; // call the base class to see if it is handling this if (CMTDhcpHandler::OnGetResultViewType(pComponent, cookie, ppViewType, pViewOptions) != S_OK) { *pViewOptions = MMC_VIEW_OPTIONS_MULTISELECT; hr = S_FALSE; } return hr; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::UpdateResultMessage Figures out what message to put in the result pane, if any Author: EricDav ---------------------------------------------------------------------------*/ void CDhcpScopeOptions::UpdateResultMessage(ITFSNode * pNode) { HRESULT hr = hrOK; int nMessage = -1; // default int nVisible, nTotal; int i; CString strTitle, strBody, strTemp; if (!m_dwErr) { pNode->GetChildCount(&nVisible, &nTotal); // determine what message to display if ( (m_nState == notLoaded) || (m_nState == loading) ) { nMessage = -1; } else if (nTotal == 0) { nMessage = SCOPE_OPTIONS_MESSAGE_NO_OPTIONS; } // build the strings if (nMessage != -1) { // now build the text strings // first entry is the title strTitle.LoadString(g_uScopeOptionsMessages[nMessage][0]); // second entry is the icon // third ... n entries are the body strings for (i = 2; g_uScopeOptionsMessages[nMessage][i] != 0; i++) { strTemp.LoadString(g_uScopeOptionsMessages[nMessage][i]); strBody += strTemp; } } } // show the message if (nMessage == -1) { ClearMessage(pNode); } else { ShowMessage(pNode, strTitle, strBody, (IconIdentifier) g_uScopeOptionsMessages[nMessage][1]); } } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::EnumerateResultPane We override this function for the options nodes for one reason. Whenever an option class is deleted, then all options defined for that class will be removed as well. Since there are multiple places that these options may show up, it's easier to just not show any options that don't have a class defined for it. Author: EricDav ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::EnumerateResultPane ( ITFSComponent * pComponent, MMC_COOKIE cookie, LPARAM arg, LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState()); CClassInfoArray ClassInfoArray; SPITFSNode spContainer, spServerNode; CDhcpServer * pServer; COptionValueEnum * aEnum[2]; int aImages[2] = {ICON_IDX_SCOPE_OPTION_LEAF, ICON_IDX_SERVER_OPTION_LEAF}; m_spNodeMgr->FindNode(cookie, &spContainer); spServerNode = GetServerNode(spContainer); pServer = GETHANDLER(CDhcpServer, spServerNode); pServer->GetClassInfoArray(ClassInfoArray); aEnum[0] = GetScopeObject(spContainer)->GetOptionValueEnum(); aEnum[1] = pServer->GetOptionValueEnum(); aEnum[0]->Reset(); aEnum[1]->Reset(); return OnResultUpdateOptions(pComponent, spContainer, &ClassInfoArray, aEnum, aImages, 2); } /*--------------------------------------------------------------------------- Command handlers ---------------------------------------------------------------------------*/ HRESULT CDhcpScopeOptions::OnCreateNewOptions ( ITFSNode * pNode ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); CPropertyPageHolderBase * pPropSheet; HRESULT hr = hrOK; COM_PROTECT_TRY { if (HasPropSheetsOpen()) { GetOpenPropSheet(0, &pPropSheet); pPropSheet->SetActiveWindow(); } else { CString strOptCfgTitle, strOptType; SPIComponentData spComponentData; strOptType.LoadString(IDS_CONFIGURE_OPTIONS_SCOPE); AfxFormatString1(strOptCfgTitle, IDS_CONFIGURE_OPTIONS_TITLE, strOptType); m_spNodeMgr->GetComponentData(&spComponentData); hr = DoPropertiesOurselvesSinceMMCSucks(pNode, spComponentData, strOptCfgTitle); } } COM_PROTECT_CATCH return hr; } /*--------------------------------------------------------------------------- Background thread functionality ---------------------------------------------------------------------------*/ /*--------------------------------------------------------------------------- CDhcpScopeOptions::OnCreateQuery() Description Author: EricDav ---------------------------------------------------------------------------*/ ITFSQueryObject* CDhcpScopeOptions::OnCreateQuery(ITFSNode * pNode) { CDhcpScopeOptionsQueryObj* pQuery = new CDhcpScopeOptionsQueryObj(m_spTFSCompData, m_spNodeMgr); pQuery->m_strServer = GetServerIpAddress(pNode); pQuery->m_dhcpScopeAddress = GetScopeObject(pNode)->GetAddress(); pQuery->m_dhcpResumeHandle = NULL; pQuery->m_dwPreferredMax = 0xFFFFFFFF; GetScopeObject(pNode)->GetDynBootpClassName(pQuery->m_strDynBootpClassName); GetScopeObject(pNode)->GetServerVersion(pQuery->m_liDhcpVersion); return pQuery; } /*--------------------------------------------------------------------------- CDhcpScopeOptionsQueryObj::Execute() Description Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptionsQueryObj::Execute() { DWORD dwErr; DHCP_OPTION_SCOPE_INFO dhcpOptionScopeInfo; COptionValueEnum * pOptionValueEnum; pOptionValueEnum = new COptionValueEnum(); pOptionValueEnum->m_strDynBootpClassName = m_strDynBootpClassName; dhcpOptionScopeInfo.ScopeType = DhcpSubnetOptions; dhcpOptionScopeInfo.ScopeInfo.SubnetScopeInfo = m_dhcpScopeAddress; pOptionValueEnum->Init(m_strServer, m_liDhcpVersion, dhcpOptionScopeInfo); dwErr = pOptionValueEnum->Enum(); if (dwErr != ERROR_SUCCESS) { Trace1("CDhcpScopeOptionsQueryObj::Execute - Enum Failed! %d\n", dwErr); m_dwErr = dwErr; PostError(dwErr); delete pOptionValueEnum; } else { pOptionValueEnum->SortById(); AddToQueue((LPARAM) pOptionValueEnum, DHCP_QDATA_OPTION_VALUES); } return hrFalse; } /*!-------------------------------------------------------------------------- CDhcpScopeOptions::OnNotifyExiting CMTDhcpHandler overridden functionality allows us to know when the background thread is done Author: EricDav ---------------------------------------------------------------------------*/ STDMETHODIMP CDhcpScopeOptions::OnNotifyExiting ( LPARAM lParam ) { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); SPITFSNode spNode; spNode.Set(m_spNode); // save this off because OnNotifyExiting will release it HRESULT hr = CMTDhcpHandler::OnNotifyExiting(lParam); UpdateResultMessage(spNode); return hr; } // // // qsort comparison routine to compare the ip addresses. // // int __cdecl QCompare( const void *ip1, const void *ip2 ) { DWORD *lip1, *lip2; if ( ip1 && ip2 ) { lip1 = (DWORD *)ip1; lip2 = (DWORD *)ip2; if ( *lip1 < *lip2 ) { return -1; } else if ( *lip1 > *lip2 ) { return 1; } else { return 0; } } return 0; }
35.54098
165
0.439935
[ "object" ]
3dc7d1cfc20021fd8dff30478ebc174c1bd3ac75
4,529
cpp
C++
src/FusionEKF.cpp
edoardomazzella/CarND-Extended-Kalman-Filter-Project
f35be87c58cffcc1911568986f9bec6daece9e93
[ "MIT" ]
null
null
null
src/FusionEKF.cpp
edoardomazzella/CarND-Extended-Kalman-Filter-Project
f35be87c58cffcc1911568986f9bec6daece9e93
[ "MIT" ]
null
null
null
src/FusionEKF.cpp
edoardomazzella/CarND-Extended-Kalman-Filter-Project
f35be87c58cffcc1911568986f9bec6daece9e93
[ "MIT" ]
null
null
null
#include "FusionEKF.h" #include <iostream> #include "Eigen/Dense" #include "tools.h" using Eigen::MatrixXd; using Eigen::VectorXd; using std::cout; using std::endl; using std::vector; /** * Constructor. */ FusionEKF::FusionEKF() { // create a 4D state vector, we don't know yet the values of the x state VectorXd x = VectorXd(4); // state covariance matrix P MatrixXd P = MatrixXd(4, 4); P << 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1000, 0, 0, 0, 0, 1000; // the initial transition matrix F_ MatrixXd F = MatrixXd(4, 4); F << 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1; // linear measurement matrix MatrixXd H = MatrixXd(2, 4); H << 1, 0, 0, 0, 0, 1, 0, 0; VectorXd hx = VectorXd(3); // H Jacobian initialization MatrixXd Hj = MatrixXd(3, 4); // Process noise covariance matrix MatrixXd Q = MatrixXd(4, 4); // measurement covariance matrix - laser MatrixXd R_laser = MatrixXd(2, 2); R_laser << 0.0225, 0, 0, 0.0225; // measurement covariance matrix - radar MatrixXd R_radar = MatrixXd(3, 3); R_radar << 0.09, 0, 0, 0, 0.0009, 0, 0, 0, 0.09; ekf_.Init(std::move(x), std::move(P), std::move(F), std::move(H), std::move(hx), std::move(Hj), std::move(Q), std::move(R_laser), std::move(R_radar)); // set the acceleration noise components noise_ax_ = 9; noise_ay_ = 9; // set other private members is_initialized_ = false; previous_timestamp_ = 0; } /** * Destructor. */ FusionEKF::~FusionEKF() {} void FusionEKF::ProcessMeasurement(const MeasurementPackage &measurement_pack) { /** * Initialization */ if (!is_initialized_) { // first measurement cout << "EKF: " << endl; VectorXd x = VectorXd(4); // set the state with the initial location and zero velocity if (MeasurementPackage::RADAR == measurement_pack.sensor_type_) { cout << endl << "First iteration - Radar" << endl; // Convert radar from polar to cartesian coordinates // and initialize state. x = tools::Polar2Cartesian(measurement_pack.raw_measurements_); } else if (MeasurementPackage::LASER == measurement_pack.sensor_type_) { cout << endl << "First iteration - Laser" << endl; // Initialize state. x << measurement_pack.raw_measurements_[0], measurement_pack.raw_measurements_[1], 0, 0; } else { cout << endl << "Error: invalid sensor type." << endl; return; } ekf_.SetX(std::move(x)); // done initializing, no need to predict or update is_initialized_ = true; previous_timestamp_ = measurement_pack.timestamp_; cout << "x_ = " << ekf_.GetX() << endl; cout << "P_ = " << ekf_.GetP() << endl; } else { /** * Prediction */ // Update the state transition matrix F according to the new elapsed time. // Time is measured in seconds. double elapsed_time = ((double) measurement_pack.timestamp_ - previous_timestamp_) / 1000000.0; previous_timestamp_ = measurement_pack.timestamp_; cout << "Elapsed time: " << elapsed_time << endl; MatrixXd F = MatrixXd(4, 4); F << 1, 0, elapsed_time, 0, 0, 1, 0, elapsed_time, 0, 0, 1, 0, 0, 0, 0, 1; ekf_.SetF(std::move(F)); // Update the process noise covariance matrix. // Use noise_ax = 9 and noise_ay = 9 for your Q matrix. ekf_.SetQ(tools::CalculateProcessNoiseCovarianceMatrix(elapsed_time, noise_ax_, noise_ay_)); cout << endl << "Predict step." << endl; ekf_.Predict(); /** * Update */ if (MeasurementPackage::RADAR == measurement_pack.sensor_type_) { cout << endl << "Radar update step." << endl; VectorXd x_state = ekf_.GetX(); // Radar updates ekf_.Sethx(tools::NonLinearH(x_state)); ekf_.SetHj(tools::CalculateJacobian(x_state)); ekf_.UpdateEKF(measurement_pack.raw_measurements_); } else if (MeasurementPackage::LASER == measurement_pack.sensor_type_) { cout << endl << "Laser update step." << endl; // Laser updates ekf_.Update(measurement_pack.raw_measurements_); } else { cout << endl << "Error: invalid sensor type." << endl; return; } } }
27.615854
101
0.57739
[ "vector" ]
3dc8dcdf29aa4d2b34b913c6e3996a08ee3880a2
1,394
cpp
C++
src/GHUtils/GHControllerTransition.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/GHUtils/GHControllerTransition.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
src/GHUtils/GHControllerTransition.cpp
GoldenHammerSoftware/GH
757213f479c0fc80ed1a0f59972bf3e9d92b7526
[ "MIT" ]
null
null
null
// Copyright Golden Hammer Software #include "GHControllerTransition.h" #include "GHControllerMgr.h" #include "GHController.h" GHControllerTransition::GHControllerTransition(GHControllerMgr& controllerMgr, GHController* controller, float priority) : mControllerMgr(controllerMgr) , mPriority(priority) { mControllers.push_back(controller); } GHControllerTransition::GHControllerTransition(GHControllerMgr& controllerMgr, const std::vector<GHController*>& controllers, float priority) : mControllerMgr(controllerMgr) , mPriority(priority) { mControllers = controllers; } GHControllerTransition::~GHControllerTransition(void) { for (size_t i = 0; i < mControllers.size(); ++i) { // if we call remove here, then we might be calling deactivate twice. // should only call remove if we are active. //mControllerMgr.remove(mControllers[i]); delete mControllers[i]; } } void GHControllerTransition::activate(void) { for (size_t i = 0; i < mControllers.size(); ++i) { mControllerMgr.add(mControllers[i], mPriority); } } void GHControllerTransition::deactivate(void) { for (size_t i = 0; i < mControllers.size(); ++i) { mControllerMgr.remove(mControllers[i]); } }
27.88
104
0.642755
[ "vector" ]
3dd2c5583a7bcd11e88d293abf882060f6e0678c
11,352
hpp
C++
include/application.hpp
Arvkus/vk-visualiser
b641dfae56d3f871fb01868eccb1abb3a1fc34fc
[ "MIT" ]
null
null
null
include/application.hpp
Arvkus/vk-visualiser
b641dfae56d3f871fb01868eccb1abb3a1fc34fc
[ "MIT" ]
null
null
null
include/application.hpp
Arvkus/vk-visualiser
b641dfae56d3f871fb01868eccb1abb3a1fc34fc
[ "MIT" ]
null
null
null
#include "common.hpp" #include "instance.hpp" #include "memory.hpp" #include "pipeline.hpp" #include "swapchain.hpp" #include "descriptors.hpp" #include "model.hpp" #include "input.hpp" #include "camera.hpp" #include "loader.hpp" class Application{ public: void draw() { if(is_model_update()) return; // do not render while model is loading if(RECREATE_SWAPCHAIN) return; // do not render while swapchain is recreating std::optional<uint32_t> next_image = swapchain.accquire_next_image(); if(!next_image.has_value()) RECREATE_SWAPCHAIN = true; // recreate_swapchain(); update_uniform_buffer(next_image.value()); bool is_presented = swapchain.present_image(next_image.value()); if(!is_presented) RECREATE_SWAPCHAIN = true; // recreate_swapchain(); } void init_vulkan(GLFWwindow* window) { this->instance.init(window); this->descriptors.init(&this->instance); this->render_pass = create_render_pass(&this->instance); this->model_pipeline.init(&this->instance, &this->descriptors, &this->render_pass); this->model_pipeline.create_graphics_pipeline(); this->skybox_pipeline.init(&this->instance, &this->descriptors, &this->render_pass); this->skybox_pipeline.create_skybox_pipeline(); this->swapchain.init(&this->instance, &this->render_pass); Loader loader = Loader(); skybox = loader.load("models/cube.glb"); skybox.prepare_model(&this->instance, &this->descriptors); //model = loader.load("models/crate.glb"); model = loader.load("models/cube.glb"); //model = loader.load("models/tests/NormalTangentTest.glb"); model.prepare_model(&this->instance, &this->descriptors); camera.set_region(model.get_region()); create_enviroment_buffer(); this->descriptors.bind_enviroment_image(&this->enviroment_image); this->descriptors.create_descriptor_sets(); create_command_pool(); create_command_buffers(); this->swapchain.bind_command_buffers(this->command_buffers.data()); } void recreate_swapchain() { instance.update_surface_capabilities(); vkDeviceWaitIdle(instance.device); printf("---------------------\n"); // destroy outdated objects this->swapchain.destroy(); this->model_pipeline.destroy(); this->skybox_pipeline.destroy(); vkDestroyCommandPool(instance.device, command_pool, nullptr); // recreate objects this->model_pipeline.init(&this->instance, &this->descriptors, &this->render_pass); this->model_pipeline.create_graphics_pipeline(); this->skybox_pipeline.init(&this->instance, &this->descriptors, &this->render_pass); this->skybox_pipeline.create_skybox_pipeline(); this->swapchain.init(&this->instance, &this->render_pass); create_command_pool(); create_command_buffers(); this->swapchain.bind_command_buffers(this->command_buffers.data()); } void destroy() { vkDeviceWaitIdle(instance.device); this->swapchain.destroy(); this->descriptors.destroy(); this->skybox_pipeline.destroy(); this->model_pipeline.destroy(); enviroment_image.destroy(); skybox.destroy(); model.destroy(); vkDestroyRenderPass(instance.device, this->render_pass, nullptr); vkDestroyCommandPool(instance.device, command_pool, nullptr); this->instance.destroy(); } private: Instance instance; Pipeline model_pipeline; Pipeline skybox_pipeline; Descriptors descriptors; Swapchain swapchain; VkRenderPass render_pass; Model model; Model skybox; UniformPropertiesStruct properties = UniformPropertiesStruct(); Camera camera = Camera(); VkCommandPool command_pool; std::vector<VkCommandBuffer> command_buffers; Image enviroment_image; //--------------------------------------------------------------------------------- bool is_model_update() { if(Input::Keys::L == false) return false; pfd::open_file f = pfd::open_file("Choose files to read", FILE_PATH, { "Model Files (.glb .gltf)", "*.glb *.gltf"}, false); if(f.result().size() > 0){ vkDeviceWaitIdle(instance.device); msg::printl("File selected from dialog: ", f.result()[0]); vkDestroyCommandPool(instance.device, command_pool, nullptr); this->descriptors.destroy(); this->model.destroy(); //----------------------------------------- this->descriptors.init(&this->instance); this->descriptors.bind_enviroment_image(&this->enviroment_image); Loader loader = Loader(); model = loader.load(f.result()[0].c_str()); model.prepare_model(&this->instance, &this->descriptors); camera.set_region(model.get_region()); this->descriptors.create_descriptor_sets(); create_command_pool(); create_command_buffers(); }else{ msg::printl("No file selected from dialog"); } return false; } //--------------------------------------------------------------------------------- void update_uniform_buffer(uint32_t current_image) { camera.move(); Input::reset(); float width = instance.surface.capabilities.currentExtent.width; float height = instance.surface.capabilities.currentExtent.height; UniformCameraStruct ubo = {}; ubo.view = camera.cframe(); // glm::translate(glm::mat4(1.0), glm::vec3(0,0,-4)); ubo.proj = glm::perspective(glm::radians(45.0f), width / height, 0.05f, 500.0f); // ... descriptors.view_buffer.fill_memory(&ubo, sizeof(ubo)); } //--------------------------------------------------------------------------------- void create_command_pool() { VkCommandPoolCreateInfo ci = { VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO }; ci.flags = 0; ci.queueFamilyIndex = instance.queues.graphics_family_index; if(vkCreateCommandPool(instance.device, &ci, nullptr, &this->command_pool) != VK_SUCCESS){ throw std::runtime_error("failed to create command pool!"); }; } void create_command_buffers() { command_buffers.resize(instance.surface.image_count); VkCommandBufferAllocateInfo alloc_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO }; alloc_info.commandPool = this->command_pool; alloc_info.commandBufferCount = (uint32_t)command_buffers.size(); alloc_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; if(vkAllocateCommandBuffers(instance.device, &alloc_info, command_buffers.data()) != VK_SUCCESS){ throw std::runtime_error("failed to allocate command buffers!"); }; std::array<VkClearValue, 2> clear_values = {}; clear_values[0].color = {0.0, 0.0, 0.0, 1.0}; clear_values[1].depthStencil = {1.0, 0}; for(int i = 0; i < command_buffers.size(); i++) { // render pass info for recodring VkRenderPassBeginInfo render_pass_bi = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO }; render_pass_bi.renderPass = this->render_pass; render_pass_bi.framebuffer = this->swapchain.swapchain_framebuffers[i]; // framebuffer for each swap chain image that specifies it as color attachment. render_pass_bi.renderArea.offset = {0, 0}; // render area render_pass_bi.renderArea.extent = this->instance.surface.capabilities.currentExtent; render_pass_bi.clearValueCount = (uint32_t)clear_values.size(); render_pass_bi.pClearValues = clear_values.data(); VkDeviceSize offsets[1] = {0}; uint32_t min_align = 256; uint32_t dyn_align = sizeof(float); dyn_align = (dyn_align + min_align - 1) & ~(min_align - 1); VkCommandBufferBeginInfo begin_info = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO }; vkBeginCommandBuffer(command_buffers[i], &begin_info); // RECORD START vkCmdBeginRenderPass(command_buffers[i], &render_pass_bi, VK_SUBPASS_CONTENTS_INLINE); // VK_SUBPASS_CONTENTS_INLINE - render pass commands will be embedded in the primary command buffer itself, no secondary buffers. // VK_SUBPASS_CONTENTS_SECONDARY_COMMAND_BUFFERS - The render pass commands will be executed from secondary command buffers. //------------------------------------------ vkCmdBindPipeline(command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, this->skybox_pipeline.graphics_pipeline); skybox.draw(&command_buffers[i], &skybox_pipeline.pipeline_layout, &descriptors); //------------------------------------------ vkCmdBindPipeline(command_buffers[i], VK_PIPELINE_BIND_POINT_GRAPHICS, this->model_pipeline.graphics_pipeline); model.draw(&command_buffers[i], &model_pipeline.pipeline_layout, &descriptors); //------------------------------------------ vkCmdEndRenderPass(command_buffers[i]); // RECORD END if (vkEndCommandBuffer(command_buffers[i]) != VK_SUCCESS) { throw std::runtime_error("failed to record command buffer!"); } } printf("Recorded commands \n"); } void create_enviroment_buffer() { VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT; int width = 0, height = 0, channel = 0; float* pixels = stbi_loadf("textures/pond.hdr", &width, &height, &channel, STBI_rgb_alpha); if(!pixels) throw std::runtime_error("failed to load texture image!"); // for (int i = 0; i < width*height; i++) pixels[i] *=255; this->enviroment_image.init(&this->instance); this->enviroment_image.create_image(width, height, format, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); this->enviroment_image.fill_memory(width, height, 4*sizeof(float), pixels); this->enviroment_image.create_image_view(format, VK_IMAGE_ASPECT_COLOR_BIT); stbi_image_free(pixels); msg::printl("enviroment created"); } void create_tonemapped_enviroment_buffer() { VkFormat format = VK_FORMAT_R8G8B8A8_SRGB; int width = 0, height = 0, channel = 0; stbi_uc* pixels = stbi_load("textures/saturn_hdr.png", &width, &height, &channel, STBI_rgb_alpha); if(!pixels) throw std::runtime_error("failed to load texture image!"); this->enviroment_image.init(&this->instance); this->enviroment_image.create_image(width, height, format, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT); this->enviroment_image.fill_memory(width, height, 4, pixels); this->enviroment_image.create_image_view(format, VK_IMAGE_ASPECT_COLOR_BIT); stbi_image_free(pixels); msg::printl("enviroment created"); } };
37.714286
163
0.622357
[ "render", "vector", "model" ]
3dd401a9cbe4867d28368966270fb4f6beaf68c3
1,449
cpp
C++
Blue-Flame-Engine/Sandbox_Web/Sandbox/_2DScene.cpp
FantasyVII/Blue-Flame-Engine
b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96
[ "MIT" ]
2
2020-10-12T13:40:05.000Z
2021-09-17T08:37:03.000Z
Blue-Flame-Engine/Sandbox_Web/Sandbox/_2DScene.cpp
21423236/Blue-Flame-Engine
cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b
[ "MIT" ]
null
null
null
Blue-Flame-Engine/Sandbox_Web/Sandbox/_2DScene.cpp
21423236/Blue-Flame-Engine
cf26fbdb94d1338f04e57ba88f0bbfc8b77c969b
[ "MIT" ]
null
null
null
#include "_2DScene.h" namespace _2DScene { using namespace BF; using namespace BF::AI; using namespace BF::Application; using namespace BF::Graphics; using namespace BF::Graphics::API; using namespace BF::Graphics::Renderers; using namespace BF::Graphics::GUI; using namespace BF::Math; using namespace BF::System; _2DScene::_2DScene() { } _2DScene::~_2DScene() { } void _2DScene::Initialize() { } void _2DScene::Load() { } void _2DScene::FixedUpdate() { } void _2DScene::Update() { if(BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Left)) BF_LOG_INFO("LEFT PRESSED !!"); if (BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Right)) BF_LOG_INFO("Right PRESSED !!"); if (BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Middle)) BF_LOG_INFO("Middle PRESSED !!"); /*if (!BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Left)) BF_LOG_INFO("LEFT REleased !!"); if (!BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Right)) BF_LOG_INFO("Right REleased !!"); if (!BF::Input::Mouse::IsButtonPressed(BF::Input::Mouse::Button::Middle)) BF_LOG_INFO("Middle REleased !!");*/ //BF_LOG_INFO("MouseX: %f, MouseY: %f", BF::Input::Mouse::GetPosition().x, BF::Input::Mouse::GetPosition().y); } void _2DScene::Render() { BF::Engine::GetContext().Clear(Color(0.5, 0.0f, 0.0f, 1.0f)); BF::Engine::GetContext().SwapBuffers(); } }
21.954545
112
0.669427
[ "render" ]
3ddc384547a228def5938a03263c550d00e2a0ad
11,429
cpp
C++
mux/attrcache.cpp
lashtear/tinymux
f8bc593d77889e8ace0c8a5fd063816bdc65548b
[ "RSA-MD" ]
2
2016-03-26T17:48:50.000Z
2017-05-23T20:16:15.000Z
mux/attrcache.cpp
lashtear/tinymux
f8bc593d77889e8ace0c8a5fd063816bdc65548b
[ "RSA-MD" ]
9
2015-01-03T16:01:23.000Z
2017-05-23T21:51:25.000Z
mux/attrcache.cpp
lashtear/tinymux
f8bc593d77889e8ace0c8a5fd063816bdc65548b
[ "RSA-MD" ]
1
2016-09-18T16:15:28.000Z
2016-09-18T16:15:28.000Z
/*! \file attrcache.cpp * \brief Attribute caching module. * * $Id$ * * The functions here manage the upper-level attribute value cache for * disk-based mode. It's not used in memory-based builds. The lower-level * cache is managed in svdhash.cpp * * The upper-level cache is organized by a CHashTable and a linked list. The * former allows random access while the linked list helps find the * least-recently-used attribute. */ #include "copyright.h" #include "autoconf.h" #include "config.h" #include "externs.h" #if !defined(HAVE_MEMORY_BASED) static CHashFile hfAttributeFile; static bool cache_initted = false; static bool cache_redirected = false; #define N_TEMP_FILES 8 static FILE *TempFiles[N_TEMP_FILES]; CLinearTimeAbsolute cs_ltime; #pragma pack(1) typedef struct tagAttrRecord { Aname attrKey; UTF8 attrText[LBUF_SIZE]; } ATTR_RECORD, *PATTR_RECORD; #pragma pack() static ATTR_RECORD TempRecord; typedef struct tagCacheEntryHeader { struct tagCacheEntryHeader *pPrevEntry; struct tagCacheEntryHeader *pNextEntry; Aname attrKey; size_t nSize; } CENT_HDR, *PCENT_HDR; static PCENT_HDR pCacheHead = 0; static PCENT_HDR pCacheTail = 0; static size_t CacheSize = 0; int cache_init(const UTF8 *game_dir_file, const UTF8 *game_pag_file, int nCachePages) { if (cache_initted) { return HF_OPEN_STATUS_ERROR; } int cc = hfAttributeFile.Open(game_dir_file, game_pag_file, nCachePages); if (cc != HF_OPEN_STATUS_ERROR) { // Mark caching system live // cache_initted = true; cs_ltime.GetUTC(); } return cc; } void cache_redirect(void) { for (int i = 0; i < N_TEMP_FILES; i++) { UTF8 TempFileName[20]; mux_sprintf(TempFileName, sizeof(TempFileName), T("$convtemp.%d"), i); mux_assert(mux_fopen(&TempFiles[i], TempFileName, T("wb+"))); mux_assert(TempFiles[i]); setvbuf(TempFiles[i], NULL, _IOFBF, 16384); } cache_redirected = true; } void cache_pass2(void) { ATTR_RECORD Record; cache_redirected = false; mux_fprintf(stderr, T("2nd Pass:\n")); for (int i = 0; i < N_TEMP_FILES; i++) { mux_fprintf(stderr, T("File %d: "), i); long int li = fseek(TempFiles[i], 0, SEEK_SET); mux_assert(0L == li); int cnt = 1000; size_t nSize; for (;;) { size_t cc = fread(&nSize, 1, sizeof(nSize), TempFiles[i]); if (cc != sizeof(nSize)) { break; } cc = fread(&Record, 1, nSize, TempFiles[i]); mux_assert(cc == nSize); cache_put(&Record.attrKey, Record.attrText, nSize - sizeof(Aname)); if (cnt-- == 0) { fputc('.', stderr); fflush(stderr); cnt = 1000; } } fclose(TempFiles[i]); UTF8 TempFileName[20]; mux_sprintf(TempFileName, sizeof(TempFileName), T("$convtemp.%d"), i); RemoveFile(TempFileName); mux_fprintf(stderr, T(ENDLINE)); } } void cache_cleanup(void) { for (int i = 0; i < N_TEMP_FILES; i++) { fclose(TempFiles[i]); UTF8 TempFileName[20]; mux_sprintf(TempFileName, sizeof(TempFileName), T("$convtemp.%d"), i); RemoveFile(TempFileName); } } void cache_close(void) { hfAttributeFile.CloseAll(); cache_initted = false; } void cache_tick(void) { hfAttributeFile.Tick(); } static void REMOVE_ENTRY(PCENT_HDR pEntry) { // How is X positioned? // if (pEntry == pCacheHead) { if (pEntry == pCacheTail) { // HEAD --> X --> 0 // 0 <-- <-- TAIL // // ASSERT: pEntry->pNextEntry == 0; // ASSERT: pEntry->pPrevEntry == 0; // pCacheHead = pCacheTail = 0; } else { // HEAD --> X --> Y --> 0 // 0 <-- <-- <-- TAIL // // ASSERT: pEntry->pNextEntry != 0; // ASSERT: pEntry->pPrevEntry == 0; // pCacheHead = pEntry->pNextEntry; pCacheHead->pPrevEntry = 0; pEntry->pNextEntry = 0; } } else if (pEntry == pCacheTail) { // HEAD --> Y --> X --> 0 // 0 <-- <-- <-- TAIL // // ASSERT: pEntry->pNextEntry == 0; // ASSERT: pEntry->pPrevEntry != 0; // pCacheTail = pEntry->pPrevEntry; pCacheTail->pNextEntry = 0; pEntry->pPrevEntry = 0; } else { // HEAD --> Y --> X --> Z --> 0 // 0 <-- <-- <-- <-- TAIL // // ASSERT: pEntry->pNextEntry != 0; // ASSERT: pEntry->pNextEntry != 0; // pEntry->pNextEntry->pPrevEntry = pEntry->pPrevEntry; pEntry->pPrevEntry->pNextEntry = pEntry->pNextEntry; pEntry->pNextEntry = 0; pEntry->pPrevEntry = 0; } } static void ADD_ENTRY(PCENT_HDR pEntry) { if (pCacheHead) { pCacheHead->pPrevEntry = pEntry; } pEntry->pNextEntry = pCacheHead; pEntry->pPrevEntry = 0; pCacheHead = pEntry; if (!pCacheTail) { pCacheTail = pCacheHead; } } static void TrimCache(void) { // Check to see if the cache needs to be trimmed. // while (CacheSize > mudconf.max_cache_size) { // Blow something away. // PCENT_HDR pCacheEntry = pCacheTail; if (!pCacheEntry) { CacheSize = 0; break; } REMOVE_ENTRY(pCacheEntry); CacheSize -= pCacheEntry->nSize; hashdeleteLEN(&(pCacheEntry->attrKey), sizeof(Aname), &mudstate.acache_htab); MEMFREE(pCacheEntry); pCacheEntry = NULL; } } const UTF8 *cache_get(Aname *nam, size_t *pLen) { if ( nam == (Aname *) 0 || !cache_initted) { *pLen = 0; return NULL; } PCENT_HDR pCacheEntry = NULL; if (!mudstate.bStandAlone) { // Check the cache, first. // pCacheEntry = (PCENT_HDR)hashfindLEN(nam, sizeof(Aname), &mudstate.acache_htab); if (pCacheEntry) { // It was in the cache, so move this entry to the head of the queue. // and return a pointer to it. // REMOVE_ENTRY(pCacheEntry); ADD_ENTRY(pCacheEntry); if (sizeof(CENT_HDR) < pCacheEntry->nSize) { *pLen = pCacheEntry->nSize - sizeof(CENT_HDR); return (UTF8 *)(pCacheEntry+1); } else { *pLen = 0; return NULL; } } } UINT32 nHash = CRC32_ProcessInteger2(nam->object, nam->attrnum); UINT32 iDir = hfAttributeFile.FindFirstKey(nHash); while (iDir != HF_FIND_END) { HP_HEAPLENGTH nRecord; hfAttributeFile.Copy(iDir, &nRecord, &TempRecord); if ( TempRecord.attrKey.attrnum == nam->attrnum && TempRecord.attrKey.object == nam->object) { int nLength = nRecord - sizeof(Aname); *pLen = nLength; if (!mudstate.bStandAlone) { // Add this information to the cache. // pCacheEntry = (PCENT_HDR)MEMALLOC(sizeof(CENT_HDR)+nLength); if (pCacheEntry) { pCacheEntry->attrKey = *nam; pCacheEntry->nSize = nLength + sizeof(CENT_HDR); CacheSize += pCacheEntry->nSize; memcpy((char *)(pCacheEntry+1), TempRecord.attrText, nLength); ADD_ENTRY(pCacheEntry); hashaddLEN(nam, sizeof(Aname), pCacheEntry, &mudstate.acache_htab); TrimCache(); } } return TempRecord.attrText; } iDir = hfAttributeFile.FindNextKey(iDir, nHash); } // We didn't find that one. // if (!mudstate.bStandAlone) { // Add this information to the cache. // pCacheEntry = (PCENT_HDR)MEMALLOC(sizeof(CENT_HDR)); if (pCacheEntry) { pCacheEntry->attrKey = *nam; pCacheEntry->nSize = sizeof(CENT_HDR); CacheSize += pCacheEntry->nSize; ADD_ENTRY(pCacheEntry); hashaddLEN(nam, sizeof(Aname), pCacheEntry, &mudstate.acache_htab); TrimCache(); } } *pLen = 0; return NULL; } // cache_put no longer frees the pointer. // bool cache_put(Aname *nam, const UTF8 *value, size_t len) { if ( !value || !nam || !cache_initted || len == 0) { return false; } #if defined(HAVE_WORKING_FORK) if (mudstate.write_protect) { Log.tinyprintf(T("cache_put((%d,%d), \xE2\x80\x98%s\xE2\x80\x99, %u) while database is write-protected" ENDLINE), nam->object, nam->attrnum, value, len); return false; } #endif // HAVE_WORKING_FORK if (len > sizeof(TempRecord.attrText)) { len = sizeof(TempRecord.attrText); } // Removal from DB. // UINT32 nHash = CRC32_ProcessInteger2(nam->object, nam->attrnum); if (cache_redirected) { TempRecord.attrKey = *nam; memcpy(TempRecord.attrText, value, len); TempRecord.attrText[len-1] = '\0'; int iFile = (N_TEMP_FILES-1) & (nHash >> 29); size_t nSize = len+sizeof(Aname); fwrite(&nSize, 1, sizeof(nSize), TempFiles[iFile]); fwrite(&TempRecord, 1, nSize, TempFiles[iFile]); return true; } UINT32 iDir = hfAttributeFile.FindFirstKey(nHash); while (iDir != HF_FIND_END) { HP_HEAPLENGTH nRecord; hfAttributeFile.Copy(iDir, &nRecord, &TempRecord); if ( TempRecord.attrKey.attrnum == nam->attrnum && TempRecord.attrKey.object == nam->object) { hfAttributeFile.Remove(iDir); } iDir = hfAttributeFile.FindNextKey(iDir, nHash); } TempRecord.attrKey = *nam; memcpy(TempRecord.attrText, value, len); TempRecord.attrText[len-1] = '\0'; // Insertion into DB. // if (!hfAttributeFile.Insert((HP_HEAPLENGTH)(len+sizeof(Aname)), nHash, &TempRecord)) { Log.tinyprintf(T("cache_put((%d,%d), \xE2\x80\x98%s\xE2\x80\x99, %u) failed" ENDLINE), nam->object, nam->attrnum, value, len); } if (!mudstate.bStandAlone) { // Update cache. // PCENT_HDR pCacheEntry = (PCENT_HDR)hashfindLEN(nam, sizeof(Aname), &mudstate.acache_htab); if (pCacheEntry) { // It was in the cache, so delete it. // REMOVE_ENTRY(pCacheEntry); CacheSize -= pCacheEntry->nSize; hashdeleteLEN((char *)nam, sizeof(Aname), &mudstate.acache_htab); MEMFREE(pCacheEntry); pCacheEntry = NULL; } // Add information about the new entry back into the cache. // size_t nSizeOfEntry = sizeof(CENT_HDR) + len; pCacheEntry = (PCENT_HDR)MEMALLOC(nSizeOfEntry); if (pCacheEntry) { pCacheEntry->attrKey = *nam; pCacheEntry->nSize = nSizeOfEntry; CacheSize += pCacheEntry->nSize; memcpy((char *)(pCacheEntry+1), TempRecord.attrText, len); ADD_ENTRY(pCacheEntry); hashaddLEN(nam, sizeof(Aname), pCacheEntry, &mudstate.acache_htab); TrimCache(); } } return true; } bool cache_sync(void) { hfAttributeFile.Sync(); return true; } // Delete this attribute from the database. // void cache_del(Aname *nam) { if ( !nam || !cache_initted) { return; } #if defined(HAVE_WORKING_FORK) if (mudstate.write_protect) { Log.tinyprintf(T("cache_del((%d,%d)) while database is write-protected" ENDLINE), nam->object, nam->attrnum); return; } #endif // HAVE_WORKING_FORK UINT32 nHash = CRC32_ProcessInteger2(nam->object, nam->attrnum); UINT32 iDir = hfAttributeFile.FindFirstKey(nHash); while (iDir != HF_FIND_END) { HP_HEAPLENGTH nRecord; hfAttributeFile.Copy(iDir, &nRecord, &TempRecord); if ( TempRecord.attrKey.attrnum == nam->attrnum && TempRecord.attrKey.object == nam->object) { hfAttributeFile.Remove(iDir); } iDir = hfAttributeFile.FindNextKey(iDir, nHash); } if (!mudstate.bStandAlone) { // Update cache. // PCENT_HDR pCacheEntry = (PCENT_HDR)hashfindLEN(nam, sizeof(Aname), &mudstate.acache_htab); if (pCacheEntry) { // It was in the cache, so delete it. // REMOVE_ENTRY(pCacheEntry); CacheSize -= pCacheEntry->nSize;; hashdeleteLEN((char *)nam, sizeof(Aname), &mudstate.acache_htab); MEMFREE(pCacheEntry); pCacheEntry = NULL; } } } #endif // HAVE_MEMORY_BASED
22.72167
114
0.640738
[ "object" ]
3ddceb8347cafc10ae4b8c1e667d08c408998dbd
9,396
cpp
C++
mx_psfFit.cpp
scstein/FastPsfFitting
a8538a50ec93f5673722078ced5bedfd50b2a0e9
[ "BSD-3-Clause" ]
6
2018-06-16T18:37:47.000Z
2021-02-04T10:45:36.000Z
mx_psfFit.cpp
scstein/FastPsfFitting
a8538a50ec93f5673722078ced5bedfd50b2a0e9
[ "BSD-3-Clause" ]
null
null
null
mx_psfFit.cpp
scstein/FastPsfFitting
a8538a50ec93f5673722078ced5bedfd50b2a0e9
[ "BSD-3-Clause" ]
2
2018-04-13T01:06:24.000Z
2018-09-18T09:15:54.000Z
// Authors: Simon Christoph Stein and Jan Thiart // E-Mail: scstein@phys.uni-goettingen.de // Date: March 2016 // Optimization is done using the ceres-solver library. // http://ceres-solver.org, New BSD license. // Copyright 2015 Google Inc. All rights reserved. // % Copyright (c) 2016, Simon Christoph Stein // % All rights reserved. // % // % Redistribution and use in source and binary forms, with or without // % modification, are permitted provided that the following conditions are met: // % // % 1. Redistributions of source code must retain the above copyright notice, this // % list of conditions and the following disclaimer. // % 2. Redistributions in binary form must reproduce the above copyright notice, // % this list of conditions and the following disclaimer in the documentation // % and/or other materials provided with the distribution. // % // % THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // % ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // % WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // % DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR // % ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // % (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // % LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND // % ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // % (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // % SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // % // % The views and conclusions contained in the software and documentation are those // % of the authors and should not be interpreted as representing official policies, // % either expressed or implied, of the FreeBSD Project. // mex #include "mex.h" // stdlib #include <cmath> #include <math.h> // our headers #include "mexUtil.h" // -- Type definitions (must go before further inclusions!) -- typedef Array1D_t<double> Array1D; typedef Array2D_t<double> Array2D; typedef Array3D_t<double> Array3D; #include "mx_psfFit_OptimizerFunctions.h" using namespace std; // % Short usage: params = psfFit( img ); (fits an isotropic gaussian) // % Full usage: [ params, exitflag ] = psfFit( img, param_init, param_optimizeMask, useIntegratedGauss, useMLErefine) // % Fit a gaussian point spread function model to the given image. // % // % Coordinate convention: Integer coordinates are centered in pixels. I.e. // % the position xpos=3, ypos=5 is exactly the center of pixel img(5,3). Thus // % pixel center coordinates range from 1 to size(img,2) for x and 1 to // % size(img,1) for y coordinates. // % // % Use empty matrix [] for parameters you don't want to specify. // % // % Gaussian fitting covers three basic cases: // % - fitting isotropic gaussian (sigma_y and angle initial values not specified and they should not be optimized) // % - fitting anisotropic gaussian (angle initial value not specified and should not be optimized) // % - fitting anisotropic rotated gaussian // % // % The fitting case is selected based on the set of specified initial // % parameters together with the set of parameters that should be optimized. // % The angle input/output should be in degree. // % // % Input: // % img - NxM image to fit to. (internally converted to double) // % param_init - Initial values for parameters. You can specify up to [xpos;ypos;A;BG;sigma_x,sigma_y,angle]. // % If negative or no values are given, the fitter estimates a value for that parameter if neccessary, // % with the exception of the angle, which is estimated if angle==0 and if it should be optimized. // % If parameters are not optimized (see next entry) their values are kept constant during optimization. // % param_optimizeMask - Must be true(1)/false(0) for every parameter [xpos,ypos,A,BG,sigma_x,sigma_y,angle]. // % Parameters with value 'false' are not fitted. | default: [1,1,1,1,1,0,0] -> 'optimize x,y,A,BG,sigma' (isoptric gaussian) // % useIntegratedGauss - Wether to use pixel integrated gaussian or not // % not supported for non-isotropic arbitrarily roated gaussians | default: false // % useMLErefine - Use Poissonian noise based maximum likelihood estimation after // % least squares fit. Make sure to input image intensities in photons // % for this to make sense. | default: false // % // % Output // % params - Final parameters [xpos,ypos,A,BG,sigma_x,sigma_y,angle]. // % exitflag - Return state of optimizer. Positive = 'good'. Negative = 'bad'. // % 1 - CONVERGENCE // % -1 - NO_CONVERGENCE // % -2 - FAILURE // % // % Optimization is done using the ceres-solver library. // % http://ceres-solver.org, New BSD license. // % Copyright 2015 Google Inc. All rights reserved. // % // % Authors: Simon Christoph Stein and Jan Thiart // % Date: March 2016 // % E-Mail: scstein@phys.uni-goettingen.de // % void mexFunction(int nlhs, mxArray* plhs[], int nrhs, const mxArray* prhs[]) { // Replace the std stream with the 'matlab' stream to see cout outputs in the MATLAB console mexStream mout; std::streambuf *outbuf = std::cout.rdbuf(&mout); /// -- Input parsing -- /// /* Check for proper number of arguments. */ if(nrhs<1) mexErrMsgTxt("psfFit is hungry! Please feed me at least an image!"); if(mxGetClassID(prhs[0]) != mxDOUBLE_CLASS) mexErrMsgTxt("psfFit: input image datatype must be double!"); /* Map access to input data */ Array2D img( prhs[0] ); Array2D param_init( prhs[1] ); int nr_given_params = param_init.nElements; std::vector<bool> param_optimMask(7, 1); // default all 1's: optimize every parameter bool usePixelIntegratedGauss = false; bool useMLErefine = false; if(nrhs>2) { Array1D p_optimMask( prhs[2] ); if( !p_optimMask.isEmpty() ) { if(p_optimMask.nElements != 7) mexErrMsgTxt("Specify for every parameter if it should be optimized. [xpos,ypos,A,BG,sigma].\n Use false to not optimize a parameter."); else { bool* logical = mxGetLogicals(prhs[2]); for(int iParam=0; iParam<7; ++iParam) param_optimMask[iParam] = logical[iParam]; } } } if(nrhs>3) { Array1D usePixelIntegration( prhs[3] ); if( !usePixelIntegration.isEmpty() ) { usePixelIntegratedGauss = mxIsLogicalScalarTrue(prhs[3]); } } if(nrhs>4) { Array1D useMLE( prhs[4] ); if( !useMLE.isEmpty() ) { useMLErefine = mxIsLogicalScalarTrue(prhs[4]); } } /// -- Here goes the fitting! -- /// // Set intital conditions std::vector<double> p_init(7); p_init[0] = (nr_given_params >= 1) ? param_init[0]:-1; p_init[1] = (nr_given_params >= 2) ? param_init[1]:-1; p_init[2] = (nr_given_params >= 3) ? param_init[2]:-1; p_init[3] = (nr_given_params >= 4) ? param_init[3]:-1; p_init[4] = (nr_given_params >= 5) ? param_init[4]:-1; p_init[5] = (nr_given_params >= 6) ? param_init[5]:-1; // Angle is special as any value (-infty,infty) can make sense. // Also we convert it from degrees to radian here, which is the input needed by fitPSF. p_init[6] = (nr_given_params >= 7) ? param_init[6]*M_PI/180.:0; // Built coordinate system to use std::vector<int> xCoords(img.nCols); std::vector<int> yCoords(img.nRows); for(unsigned int iCol = 0; iCol<img.nCols; ++iCol) xCoords[iCol] = iCol+1; // We use Matlab coordinates for(unsigned int iRow = 0; iRow<img.nRows; ++iRow) yCoords[iRow] = iRow+1; // We use Matlab coordinates // Fit image, collect results std::vector<double> results = fitPSF(img, xCoords, yCoords, p_init, param_optimMask, usePixelIntegratedGauss, useMLErefine); /// -- Output to MATLAB -- // const int nDims = 1; // Number of dimensions for output mwSize dim_out0[nDims] = { 7 }; plhs[0] = mxCreateNumericArray( nDims, dim_out0 , mxDOUBLE_CLASS, mxREAL); // fitted parameter values Array1D fin_params ( plhs[0] ); // Map access to output fin_params[0] = results[0]; // x fin_params[1] = results[1]; // y fin_params[2] = results[2]; // A fin_params[3] = results[3]; // BG // results[4]; // q1 (related to sigma_x) // results[5]; // q2 (related to sigma_y) // results[6]; // q3 (related to angle) double sigma_x, sigma_y, angle; convert_Qs_To_SxSyAngle( results[4], results[5], results[6], sigma_x, sigma_y, angle); fin_params[4] = sigma_x; fin_params[5] = sigma_y; fin_params[6] = angle*180./M_PI; // back-convert from radian to degree; // exit state of optimizer mwSize dim_out1[1] = { 1 }; plhs[1] = mxCreateNumericArray( 1, dim_out1 , mxDOUBLE_CLASS, mxREAL); double& exitflag = *mxGetPr(plhs[1]); exitflag = results[7]; // exitflag // Restore the std stream buffer std::cout.rdbuf(outbuf); }
42.515837
149
0.656875
[ "vector", "model" ]
3ddd6fad2575d23c5bce5a8b18e65b46f02566fd
8,093
cpp
C++
src/MPC.cpp
zasimov/CarND-MPC-Project
81e214e71bed4ba679114394e2baa0064554ed9e
[ "MIT" ]
null
null
null
src/MPC.cpp
zasimov/CarND-MPC-Project
81e214e71bed4ba679114394e2baa0064554ed9e
[ "MIT" ]
null
null
null
src/MPC.cpp
zasimov/CarND-MPC-Project
81e214e71bed4ba679114394e2baa0064554ed9e
[ "MIT" ]
null
null
null
#include "MPC.h" #include <cppad/cppad.hpp> #include <cppad/ipopt/solve.hpp> #include "Eigen-3.3/Eigen/Core" #include "kinematic_model.h" #include "config.h" using CppAD::AD; /* * A number of variables */ const int kNumberOfVars = kStateDim * kN + kActuatorCount * (kN - 1); /* * A number of constraints. */ const int kNumberOfConstraints = kStateDim * kN; // helpers to work with vars enum { kRowX = 0, // a number of row for X kRowY = 1, // a number of row for Y kRowPsi = 2, // ... kRowV = 3, kRowCte = 4, kRowEpsi = 5, kRowDelta = 6, kRowA = 7 }; #define X_VAR(i) (0 + i) #define Y_VAR(i) (X_VAR(kN) + i) #define PSI_VAR(i) (Y_VAR(kN) + i) #define V_VAR(i) (PSI_VAR(kN) + i) #define CTE_VAR(i) (V_VAR(kN) + i) #define EPSI_VAR(i) (CTE_VAR(kN) + i) #define DELTA_VAR(i) (EPSI_VAR(kN) + i) #define A_VAR(i) (DELTA_VAR(kN - 1) + i) class FG_eval { public: // Fitted polynomial coefficients Eigen::VectorXd coeffs_; FG_eval(const Eigen::VectorXd &coeffs): coeffs_(coeffs) { // nothing to do } typedef CPPAD_TESTVECTOR(AD<double>) ADvector; inline AD<double> cost(const ADvector &vars) { AD<double> cost = 0; for (int i = 0; i < kN; ++i) { const auto cte = vars[CTE_VAR(i)]; const auto epsi = vars[EPSI_VAR(i)]; const auto v = vars[V_VAR(i)] - kMaxSpeed; cost += kWcte * cte * cte + kWepsi * epsi * epsi + kWv * v * v; } for (int i = 0; i < kN - 1; ++i) { const auto delta = vars[DELTA_VAR(i)]; const auto a = vars[A_VAR(i)]; cost += kWdelta * delta * delta + kWa * a * a; } for (int i = 0; i < kN - 2; ++i) { const auto ddelta = vars[DELTA_VAR(i + 1)] - vars[DELTA_VAR(i)]; const auto da = vars[A_VAR(i + 1)] - vars[A_VAR(i)]; cost += kWddelta * ddelta * ddelta + kWda * da * da; } return cost; } // `fg` a vector of the cost constraints, `vars` is a vector of variable values (state & actuators) void operator()(ADvector& fg, const ADvector& vars) { // The cost is stored is the first element of `fg`. // Any additions to the cost should be added to `fg[0]`. fg[0] = cost(vars); // Fill current state fg[1 + X_VAR(0)] = vars[X_VAR(0)]; fg[1 + Y_VAR(0)] = vars[Y_VAR(0)]; fg[1 + PSI_VAR(0)] = vars[PSI_VAR(0)]; fg[1 + V_VAR(0)] = vars[V_VAR(0)]; fg[1 + CTE_VAR(0)] = vars[CTE_VAR(0)]; fg[1 + EPSI_VAR(0)] = vars[EPSI_VAR(0)]; for (int t = 0; t < kN - 1; t++) { const auto x_t = vars[X_VAR(t)]; const auto y_t = vars[Y_VAR(t)]; const auto psi_t = vars[PSI_VAR(t)]; const auto v_t = vars[V_VAR(t)]; const auto cte_t = vars[CTE_VAR(t)]; const auto epsi_t = vars[EPSI_VAR(t)]; const auto delta = vars[DELTA_VAR(t)]; const auto a = vars[A_VAR(t)]; const auto x_t1 = vars[X_VAR(t + 1)]; const auto y_t1 = vars[Y_VAR(t + 1)]; const auto psi_t1 = vars[PSI_VAR(t + 1)]; const auto v_t1 = vars[V_VAR(t + 1)]; const auto cte_t1 = vars[CTE_VAR(t + 1)]; const auto epsi_t1 = vars[EPSI_VAR(t + 1)]; // calculate y desired and psi desired const auto y_des = poly3eval(coeffs_, x_t); const auto psi_des = CppAD::atan(dfpoly3(coeffs_, x_t)); const auto cte = y_des - y_t; const auto epsi = psi_t - psi_des; AD<double> e_x_t1, e_y_t1, e_psi_t1, e_v_t1, e_cte_t1, e_epsi_t1; calc_state_t_plus_1(x_t, y_t, psi_t, v_t, cte, epsi, delta, a, kDt, e_x_t1, e_y_t1, e_psi_t1, e_v_t1, e_cte_t1, e_epsi_t1); fg[1 + X_VAR(t + 1)] = (x_t1 - e_x_t1); fg[1 + Y_VAR(t + 1)] = (y_t1 - e_y_t1); fg[1 + PSI_VAR(t + 1)] = (psi_t1 - e_psi_t1); fg[1 + V_VAR(t + 1)] = (v_t1 - e_v_t1); fg[1 + CTE_VAR(t + 1)] = (cte_t1 - e_cte_t1); fg[1 + EPSI_VAR(t + 1)] = (epsi_t1 - e_epsi_t1); } } }; // // MPC class definition implementation. // MPC::MPC() : vars_(kNumberOfVars), vars_lowerbound_(kNumberOfVars), vars_upperbound_(kNumberOfVars), constraints_lowerbound_(kNumberOfConstraints), constraints_upperbound_(kNumberOfConstraints) { // Set lower and upper limits for variables. for (int i = 0; i < DELTA_VAR(0); i++) { vars_lowerbound_[i] = -1.0e10; vars_upperbound_[i] = 1.0e10; } // The upper and lower limits of delta are set to -25 and 25 // degrees (values in radians). // NOTE: Feel free to change this to something else. for (int i = DELTA_VAR(0); i < A_VAR(0); i++) { vars_lowerbound_[i] = kMinDelta; vars_upperbound_[i] = kMaxDelta; } // Acceleration/decceleration upper and lower limits. // NOTE: Feel free to change this to something else. for (int i = A_VAR(0); i < vars_.size(); i++) { vars_lowerbound_[i] = kMinThrottle; vars_upperbound_[i] = kMaxThrottle; } // Lower and upper limits for the constraints // Should be 0 besides initial state. for (int i = 0; i < constraints_lowerbound_.size(); i++) { constraints_lowerbound_[i] = 0; constraints_upperbound_[i] = 0; } } /* * state is the "current" state * coeffs is the coefficients of the fitting polynomial */ void MPC::Solve(const Eigen::VectorXd &state, const Eigen::VectorXd &coeffs) { bool ok = true; typedef CPPAD_TESTVECTOR(double) Dvector; const double x0 = state[kStateX]; const double y0 = state[kStateY]; const double psi0 = state[kStatePsi]; const double v0 = state[kStateV]; const double cte0 = state[kStateCte]; const double epsi0 = state[kStateEpsi]; // Initial value of the independent variables. // SHOULD BE 0 besides initial state. for (int i = 0; i < vars_.size(); i++) { vars_[i] = 0; } // Initial state vars_[X_VAR(0)] = x0; vars_[Y_VAR(0)] = y0; vars_[PSI_VAR(0)] = psi0; vars_[V_VAR(0)] = v0; vars_[CTE_VAR(0)] = cte0; vars_[EPSI_VAR(0)] = epsi0; constraints_lowerbound_[X_VAR(0)] = x0; constraints_lowerbound_[Y_VAR(0)] = y0; constraints_lowerbound_[PSI_VAR(0)] = psi0; constraints_lowerbound_[V_VAR(0)] = v0; constraints_lowerbound_[CTE_VAR(0)] = cte0; constraints_lowerbound_[EPSI_VAR(0)] = epsi0; constraints_upperbound_[X_VAR(0)] = x0; constraints_upperbound_[Y_VAR(0)] = y0; constraints_upperbound_[PSI_VAR(0)] = psi0; constraints_upperbound_[V_VAR(0)] = v0; constraints_upperbound_[CTE_VAR(0)] = cte0; constraints_upperbound_[EPSI_VAR(0)] = epsi0; // object that computes objective and constraints FG_eval fg_eval(coeffs); // // NOTE: You don't have to worry about these options // // options for IPOPT solver std::string options; // Uncomment this if you'd like more print information options += "Integer print_level 0\n"; // NOTE: Setting sparse to true allows the solver to take advantage // of sparse routines, this makes the computation MUCH FASTER. If you // can uncomment 1 of these and see if it makes a difference or not but // if you uncomment both the computation time should go up in orders of // magnitude. options += "Sparse true forward\n"; options += "Sparse true reverse\n"; // NOTE: Currently the solver has a maximum time limit of 0.5 seconds. // Change this as you see fit. options += "Numeric max_cpu_time " + kMaxCpuTime + "\n"; // place to return solution CppAD::ipopt::solve_result<Dvector> solution; // solve the problem CppAD::ipopt::solve<Dvector, FG_eval>( options, vars_, vars_lowerbound_, vars_upperbound_, constraints_lowerbound_, constraints_upperbound_, fg_eval, solution); // Check some of the solution values ok &= solution.status == CppAD::ipopt::solve_result<Dvector>::success; if (! ok) { std::cerr << "unable to find solution (terminated with code 42)" << std::endl; exit(42); } // Cost auto cost = solution.obj_value; std::cout << "Cost " << cost << std::endl; steering_angle_ = solution.x[DELTA_VAR(0)]; throttle_ = solution.x[A_VAR(0)]; xs_.clear(); ys_.clear(); for (int t = 0; t < kN - 1; t++) { xs_.push_back(solution.x[X_VAR(t + 1)]); ys_.push_back(solution.x[Y_VAR(t + 1)]); } }
29.753676
101
0.630792
[ "object", "vector" ]
3de20cb780b3aea90637816d4bcf859998fc265c
2,321
cpp
C++
Moss/src/Platform/OpenGL/OpenGLVertexArray.cpp
wzhhh123/Moss
9a45127ffab59d0079c9db09b8966fc092a77440
[ "Apache-2.0" ]
null
null
null
Moss/src/Platform/OpenGL/OpenGLVertexArray.cpp
wzhhh123/Moss
9a45127ffab59d0079c9db09b8966fc092a77440
[ "Apache-2.0" ]
null
null
null
Moss/src/Platform/OpenGL/OpenGLVertexArray.cpp
wzhhh123/Moss
9a45127ffab59d0079c9db09b8966fc092a77440
[ "Apache-2.0" ]
null
null
null
#include "mspch.h" #include "OpenGLVertexArray.h" #include <glad/glad.h> namespace Moss { static GLenum ShaderDataTypeToOpenGLBaseType(ShaderDataType type) { switch (type) { case Moss::ShaderDataType::Float: return GL_FLOAT; case Moss::ShaderDataType::Float2: return GL_FLOAT; case Moss::ShaderDataType::Float3: return GL_FLOAT; case Moss::ShaderDataType::Float4: return GL_FLOAT; case Moss::ShaderDataType::Mat3: return GL_FLOAT; case Moss::ShaderDataType::Mat4: return GL_FLOAT; case Moss::ShaderDataType::Int: return GL_INT; case Moss::ShaderDataType::Int2: return GL_INT; case Moss::ShaderDataType::Int3: return GL_INT; case Moss::ShaderDataType::Int4: return GL_INT; case Moss::ShaderDataType::Bool: return GL_BOOL; } MS_CORE_ASSERT(false, "Unknown ShaderDataType!"); return 0; } OpenGLVertexArray::~OpenGLVertexArray() { glDeleteVertexArrays(1, &m_RendererID); } OpenGLVertexArray::OpenGLVertexArray() { glCreateVertexArrays(1, &m_RendererID); } void OpenGLVertexArray::Bind() const { glBindVertexArray(m_RendererID); } void OpenGLVertexArray::Unbind() const { glBindVertexArray(0); } void OpenGLVertexArray::AddVertexBuffer(const Moss::Ref<VertexBuffer>& vertexBuffer) { MS_CORE_ASSERT(vertexBuffer->GetLayout().GetElements().size(), "Vertex Buffer has no layout!"); glBindVertexArray(m_RendererID); vertexBuffer->Bind(); auto layout = vertexBuffer->GetLayout(); int index = 0; for (auto& element : layout) { glEnableVertexAttribArray(index); glVertexAttribPointer( index, element.GetElementComponentCount(), ShaderDataTypeToOpenGLBaseType(element.Type), element.Normalized ? GL_TRUE : GL_FALSE, layout.GetStride(), (const void*)element.Offset); index++; } glBindVertexArray(0); m_VertexBuffers.push_back(vertexBuffer); } void OpenGLVertexArray::SetIndexBuffer(const Moss::Ref<IndexBuffer>& indexBuffer) { glBindVertexArray(m_RendererID); indexBuffer->Bind(); glBindVertexArray(0); m_IndexBuffers = indexBuffer; } const std::vector<Moss::Ref<Moss::VertexBuffer>>& OpenGLVertexArray::GetVertexBuffer() const { return m_VertexBuffers; } const Moss::Ref<Moss::IndexBuffer>& OpenGLVertexArray::GetIndexBuffer() const { return m_IndexBuffers; } }
26.078652
97
0.734166
[ "vector" ]
3de43ff69a7ef23bb22c916a6abc9c98760df7b5
578
hpp
C++
include/chopper/build/build_data.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
include/chopper/build/build_data.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
include/chopper/build/build_data.hpp
Felix-Droop/Chopper
5cc214103b2d088ae400bec0fde8973e03dd3095
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <chopper/build/batch.hpp> #include <chopper/build/region.hpp> #include <chopper/detail_parse_chopper_pack_line.hpp> struct build_data { size_t hibf_num_technical_bins{}; size_t num_libfs{}; std::string hibf_max_bin_id{}; size_t hibf_max_bin{}; chopper_pack_record * hibf_max_record{nullptr}; batch * hibf_max_batch_record{nullptr}; std::unordered_map<size_t, size_t> merged_max_bin_map{}; std::unordered_map<std::string, size_t> merged_bin_map{}; std::unordered_map<std::string, std::vector<region>> region_map{}; };
28.9
70
0.742215
[ "vector" ]
3de85a249327e2e1decbd88a6ece071320bf8b87
546
cpp
C++
Leetcode/code/260-single-number-iii.cpp
skyline417/Algorithm
2353a2b760ada35b2e22702b2283e8168e4e990c
[ "MIT" ]
null
null
null
Leetcode/code/260-single-number-iii.cpp
skyline417/Algorithm
2353a2b760ada35b2e22702b2283e8168e4e990c
[ "MIT" ]
null
null
null
Leetcode/code/260-single-number-iii.cpp
skyline417/Algorithm
2353a2b760ada35b2e22702b2283e8168e4e990c
[ "MIT" ]
null
null
null
/* 题意: 一个整数数组,其中两个元素只出现一次,其余所有元素均出现两次。找出只出现一次的那两个元素。 思路: 常数空间复杂度 先求异或和 找出a^b的值 然后找出(a^b)的任意一个为1的位 第k位为1 根据这一位 把数组分成两部分 a和b各属于一部分 每一部分 可以化简为这个问题:一个整数数组,其中某个元素只出现一次,其余所有元素均出现两次。找出只出现一次的那个元素。 */ class Solution { public: vector<int> singleNumber(vector<int>& nums) { int ab=0; for(auto e:nums) ab^=e; int k=0; while(!(ab>>k&1)) ++k; vector<int>ans(2); for(auto e:nums){ if(!(e>>k&1)) ans[0]^=e; else ans[1]^=e; } return ans; } };
21
63
0.549451
[ "vector" ]
3de8a66ae1ae199768dd601980e6cc5fdd556bf1
568
cpp
C++
Vector.cpp
NullC0d3r/R6S-Trainer-Featurs
847167fae9740bf455bf42d74293738d7c241414
[ "MIT" ]
null
null
null
Vector.cpp
NullC0d3r/R6S-Trainer-Featurs
847167fae9740bf455bf42d74293738d7c241414
[ "MIT" ]
null
null
null
Vector.cpp
NullC0d3r/R6S-Trainer-Featurs
847167fae9740bf455bf42d74293738d7c241414
[ "MIT" ]
null
null
null
#include "Vector.h" Vector3::Vector3() { } Vector3::Vector3(float x, float y, float z) : x(x), y(y), z(z) { } Vector3& Vector3::operator+=(const Vector3& vector) { x += vector.x; y += vector.y; z += vector.z; return *this; } Vector3& Vector3::operator-=(const Vector3& vector) { x -= vector.x; y -= vector.y; z -= vector.z; return *this; } Vector3& Vector3::operator*=(float number) { x *= number; y *= number; z *= number; return *this; } Vector3& Vector3::operator/=(float number) { x /= number; y /= number; z /= number; return *this; }
13.52381
53
0.602113
[ "vector" ]
3de98e065fc6335ecf3bfe25824d817de199575f
7,047
cc
C++
chrome/browser/ui/webui/history_clusters/history_clusters_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
chrome/browser/ui/webui/history_clusters/history_clusters_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
chrome/browser/ui/webui/history_clusters/history_clusters_handler_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2021 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/ui/webui/history_clusters/history_clusters_handler.h" #include <memory> #include <string> #include <vector> #include "base/test/bind.h" #include "base/time/time.h" #include "chrome/browser/search_engines/template_url_service_factory.h" #include "chrome/browser/ui/webui/history_clusters/history_clusters_handler.h" #include "chrome/test/base/testing_profile.h" #include "components/history/core/browser/history_types.h" #include "components/history/core/browser/url_row.h" #include "components/history_clusters/core/history_clusters_types.h" #include "content/public/test/browser_task_environment.h" #include "testing/gtest/include/gtest/gtest.h" #include "url/gurl.h" namespace history_clusters { namespace { history::ClusterVisit CreateVisit( std::string url, float score, std::vector<std::string> related_searches = {}) { history::ClusterVisit visit; visit.annotated_visit = { {GURL{url}, 0}, {}, {}, {}, 0, 0, history::VisitSource::SOURCE_BROWSED}; visit.annotated_visit.content_annotations.related_searches = related_searches; visit.score = score; visit.normalized_url = GURL{url}; return visit; } class HistoryClustersHandlerTest : public testing::Test { public: HistoryClustersHandlerTest() { TemplateURLServiceFactory::GetInstance()->SetTestingFactoryAndUse( &profile_, base::BindRepeating(&TemplateURLServiceFactory::BuildInstanceFor)); } // Everything must be called on Chrome_UIThread. content::BrowserTaskEnvironment task_environment_; TestingProfile profile_; }; TEST_F(HistoryClustersHandlerTest, QueryClustersResultToMojom_BelowTheFold) { QueryClustersResult result; // High scoring visits should always be above the fold. history::Cluster cluster1; cluster1.cluster_id = 4; cluster1.visits.push_back(CreateVisit("https://high-score-1", 1)); cluster1.visits.push_back(CreateVisit("https://high-score-2", .8)); cluster1.visits.push_back(CreateVisit("https://high-score-3", .5)); cluster1.visits.push_back(CreateVisit("https://high-score-4", .5)); cluster1.visits.push_back(CreateVisit("https://high-score-5", .5)); cluster1.keywords.push_back(u"keyword"); // Low scoring visits should be above the fold only if they're one of top 4. history::Cluster cluster2; cluster2.cluster_id = 6; cluster2.visits.push_back(CreateVisit("https://low-score-1", .4)); cluster2.visits.push_back(CreateVisit("https://low-score-2", .4)); cluster2.visits.push_back(CreateVisit("https://low-score-3", .4)); cluster2.visits.push_back(CreateVisit("https://low-score-4", .4)); cluster2.visits.push_back(CreateVisit("https://low-score-5", .4)); cluster2.keywords.push_back(u"keyword"); // 0 scoring visits should be above the fold only if they're 1st. history::Cluster cluster3; cluster3.cluster_id = 8; cluster3.visits.push_back(CreateVisit("https://zero-score-1", 0)); cluster3.visits.push_back(CreateVisit("https://zero-score-2", 0)); cluster3.keywords.push_back(u"keyword"); result.clusters.push_back(cluster1); result.clusters.push_back(cluster2); result.clusters.push_back(cluster3); result.continuation_end_time = base::Time::FromDoubleT(10); mojom::QueryResultPtr mojom_result = QueryClustersResultToMojom(&profile_, "query", false, result); EXPECT_EQ(mojom_result->query, "query"); EXPECT_EQ(mojom_result->is_continuation, false); EXPECT_EQ(mojom_result->continuation_end_time, base::Time::FromDoubleT(10)); ASSERT_EQ(mojom_result->clusters.size(), 3u); { EXPECT_EQ(mojom_result->clusters[0]->id, 4); EXPECT_EQ(mojom_result->clusters[0]->visit->below_the_fold, false); const auto& related_visits = mojom_result->clusters[0]->visit->related_visits; ASSERT_EQ(related_visits.size(), 4u); EXPECT_EQ(related_visits[0]->below_the_fold, false); EXPECT_EQ(related_visits[1]->below_the_fold, false); EXPECT_EQ(related_visits[2]->below_the_fold, false); EXPECT_EQ(related_visits[3]->below_the_fold, false); } { EXPECT_EQ(mojom_result->clusters[1]->id, 6); EXPECT_EQ(mojom_result->clusters[0]->visit->below_the_fold, false); const auto& related_visits = mojom_result->clusters[1]->visit->related_visits; ASSERT_EQ(related_visits.size(), 4u); EXPECT_EQ(related_visits[0]->below_the_fold, false); EXPECT_EQ(related_visits[1]->below_the_fold, false); EXPECT_EQ(related_visits[2]->below_the_fold, false); EXPECT_EQ(related_visits[3]->below_the_fold, true); } { EXPECT_EQ(mojom_result->clusters[2]->id, 8); ASSERT_EQ(mojom_result->clusters[2]->visit->related_visits.size(), 1u); EXPECT_EQ(mojom_result->clusters[2]->visit->below_the_fold, false); const auto& related_visits = mojom_result->clusters[02]->visit->related_visits; EXPECT_EQ(related_visits[0]->below_the_fold, true); } } TEST_F(HistoryClustersHandlerTest, QueryClustersResultToMojom_RelatedSearches) { QueryClustersResult result; history::Cluster cluster; cluster.cluster_id = 4; // Should include the top visit's related searches. cluster.visits.push_back( CreateVisit("https://high-score-1", 0, {"one", "two"})); // Should exclude duplicates (i.e. "one"). cluster.visits.push_back(CreateVisit( "https://high-score-2", 0, {"one", "three", "four", "five", "six"})); // Visits without related searches shouldn't interrupt the coalescing. cluster.visits.push_back(CreateVisit("https://high-score-3", 0)); // Should include all related searches of a visit even if doing so surpasses // the max related searches (8). cluster.visits.push_back( CreateVisit("https://high-score-4", 0, {"seven", "eight", "nine"})); // Should not include related searches of more visits once the max related // searches has been met. cluster.visits.push_back(CreateVisit("https://high-score-5", 0, {"ten"})); result.clusters.push_back(cluster); mojom::QueryResultPtr mojom_result = QueryClustersResultToMojom(&profile_, "query", false, result); ASSERT_EQ(mojom_result->clusters.size(), 1u); EXPECT_EQ(mojom_result->clusters[0]->id, 4); const auto& top_visit = mojom_result->clusters[0]->visit; ASSERT_EQ(top_visit->related_searches.size(), 9u); EXPECT_EQ(top_visit->related_searches[0]->query, "one"); EXPECT_EQ(top_visit->related_searches[1]->query, "two"); EXPECT_EQ(top_visit->related_searches[2]->query, "three"); EXPECT_EQ(top_visit->related_searches[3]->query, "four"); EXPECT_EQ(top_visit->related_searches[4]->query, "five"); EXPECT_EQ(top_visit->related_searches[5]->query, "six"); EXPECT_EQ(top_visit->related_searches[6]->query, "seven"); EXPECT_EQ(top_visit->related_searches[7]->query, "eight"); EXPECT_EQ(top_visit->related_searches[8]->query, "nine"); } // TODO(manukh) Add a test case for `VisitToMojom`. } // namespace } // namespace history_clusters
39.589888
80
0.734923
[ "vector" ]
3deae79f2bbf9725a82c66676c79b3bcf4f76899
13,188
cpp
C++
httpdns-20160201/src/httpdns_20160201.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-02-01T03:20:23.000Z
2022-01-28T02:13:49.000Z
httpdns-20160201/src/httpdns_20160201.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
4
2021-05-03T08:34:12.000Z
2022-01-28T02:13:33.000Z
httpdns-20160201/src/httpdns_20160201.cpp
aliyun/alibabacloud-cpp-sdk
0e7c0576abcd4ef1aef07d714b92654deb713c36
[ "Apache-2.0" ]
5
2021-04-02T02:59:04.000Z
2022-02-24T02:33:44.000Z
// This file is auto-generated, don't edit it. Thanks. #include <alibabacloud/httpdns_20160201.hpp> #include <alibabacloud/endpoint_util.hpp> #include <alibabacloud/open_api.hpp> #include <alibabacloud/open_api_util.hpp> #include <boost/any.hpp> #include <boost/throw_exception.hpp> #include <darabonba/core.hpp> #include <darabonba/util.hpp> #include <iostream> #include <map> #include <vector> using namespace std; using namespace Alibabacloud_Httpdns20160201; Alibabacloud_Httpdns20160201::Client::Client(const shared_ptr<Alibabacloud_OpenApi::Config>& config) : Alibabacloud_OpenApi::Client(config) { _endpointRule = make_shared<string>(""); checkConfig(config); _endpoint = make_shared<string>(getEndpoint(make_shared<string>("httpdns"), _regionId, _endpointRule, _network, _suffix, _endpointMap, _endpoint)); }; string Alibabacloud_Httpdns20160201::Client::getEndpoint(shared_ptr<string> productId, shared_ptr<string> regionId, shared_ptr<string> endpointRule, shared_ptr<string> network, shared_ptr<string> suffix, shared_ptr<map<string, string>> endpointMap, shared_ptr<string> endpoint) { if (!Darabonba_Util::Client::empty(endpoint)) { return *endpoint; } if (!Darabonba_Util::Client::isUnset<map<string, string>>(endpointMap) && !Darabonba_Util::Client::empty(make_shared<string>((*endpointMap)[regionId]))) { return (*endpointMap)[regionId]; } return Alibabacloud_EndpointUtil::Client::getEndpointRules(productId, regionId, endpointRule, network, suffix); } AddDomainResponse Alibabacloud_Httpdns20160201::Client::addDomainWithOptions(shared_ptr<AddDomainRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, string>("AccountId", *request->accountId)); query->insert(pair<string, string>("DomainName", *request->domainName)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("AddDomain"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return AddDomainResponse(callApi(params, req, runtime)); } AddDomainResponse Alibabacloud_Httpdns20160201::Client::addDomain(shared_ptr<AddDomainRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return addDomainWithOptions(request, runtime); } DeleteDomainResponse Alibabacloud_Httpdns20160201::Client::deleteDomainWithOptions(shared_ptr<DeleteDomainRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, string>("AccountId", *request->accountId)); query->insert(pair<string, string>("DomainName", *request->domainName)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("DeleteDomain"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return DeleteDomainResponse(callApi(params, req, runtime)); } DeleteDomainResponse Alibabacloud_Httpdns20160201::Client::deleteDomain(shared_ptr<DeleteDomainRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return deleteDomainWithOptions(request, runtime); } DescribeDomainsResponse Alibabacloud_Httpdns20160201::Client::describeDomainsWithOptions(shared_ptr<DescribeDomainsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, string>("AccountId", *request->accountId)); query->insert(pair<string, long>("PageNumber", *request->pageNumber)); query->insert(pair<string, long>("PageSize", *request->pageSize)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("DescribeDomains"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return DescribeDomainsResponse(callApi(params, req, runtime)); } DescribeDomainsResponse Alibabacloud_Httpdns20160201::Client::describeDomains(shared_ptr<DescribeDomainsRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return describeDomainsWithOptions(request, runtime); } GetAccountInfoResponse Alibabacloud_Httpdns20160201::Client::getAccountInfoWithOptions(shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("GetAccountInfo"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return GetAccountInfoResponse(callApi(params, req, runtime)); } GetAccountInfoResponse Alibabacloud_Httpdns20160201::Client::getAccountInfo() { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return getAccountInfoWithOptions(runtime); } GetResolveCountSummaryResponse Alibabacloud_Httpdns20160201::Client::getResolveCountSummaryWithOptions(shared_ptr<GetResolveCountSummaryRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, string>("Granularity", *request->granularity)); query->insert(pair<string, long>("TimeSpan", *request->timeSpan)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("GetResolveCountSummary"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return GetResolveCountSummaryResponse(callApi(params, req, runtime)); } GetResolveCountSummaryResponse Alibabacloud_Httpdns20160201::Client::getResolveCountSummary(shared_ptr<GetResolveCountSummaryRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return getResolveCountSummaryWithOptions(request, runtime); } GetResolveStatisticsResponse Alibabacloud_Httpdns20160201::Client::getResolveStatisticsWithOptions(shared_ptr<GetResolveStatisticsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, string>("DomainName", *request->domainName)); query->insert(pair<string, string>("Granularity", *request->granularity)); query->insert(pair<string, string>("ProtocolName", *request->protocolName)); query->insert(pair<string, long>("TimeSpan", *request->timeSpan)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("GetResolveStatistics"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return GetResolveStatisticsResponse(callApi(params, req, runtime)); } GetResolveStatisticsResponse Alibabacloud_Httpdns20160201::Client::getResolveStatistics(shared_ptr<GetResolveStatisticsRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return getResolveStatisticsWithOptions(request, runtime); } ListDomainsResponse Alibabacloud_Httpdns20160201::Client::listDomainsWithOptions(shared_ptr<ListDomainsRequest> request, shared_ptr<Darabonba_Util::RuntimeOptions> runtime) { Darabonba_Util::Client::validateModel(request); shared_ptr<map<string, boost::any>> query = make_shared<map<string, boost::any>>(map<string, boost::any>()); query->insert(pair<string, long>("PageNumber", *request->pageNumber)); query->insert(pair<string, long>("PageSize", *request->pageSize)); shared_ptr<Alibabacloud_OpenApi::OpenApiRequest> req = make_shared<Alibabacloud_OpenApi::OpenApiRequest>(map<string, boost::any>({ {"query", boost::any(Alibabacloud_OpenApiUtil::Client::query(query))}, {"body", boost::any(Darabonba_Util::Client::toMap(request))} })); shared_ptr<Alibabacloud_OpenApi::Params> params = make_shared<Alibabacloud_OpenApi::Params>(map<string, boost::any>({ {"action", boost::any(string("ListDomains"))}, {"version", boost::any(string("2016-02-01"))}, {"protocol", boost::any(string("HTTPS"))}, {"pathname", boost::any(string("/"))}, {"method", boost::any(string("POST"))}, {"authType", boost::any(string("AK"))}, {"style", boost::any(string("RPC"))}, {"reqBodyType", boost::any(string("json"))}, {"bodyType", boost::any(string("json"))} })); return ListDomainsResponse(callApi(params, req, runtime)); } ListDomainsResponse Alibabacloud_Httpdns20160201::Client::listDomains(shared_ptr<ListDomainsRequest> request) { shared_ptr<Darabonba_Util::RuntimeOptions> runtime = make_shared<Darabonba_Util::RuntimeOptions>(); return listDomainsWithOptions(request, runtime); }
56.600858
207
0.715954
[ "vector" ]
3deb5311a4a7bb4ff1c17c91a7e8eb419906ede0
5,092
cpp
C++
framework/core/buffer.cpp
TomasRejhons/siren
9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825
[ "MIT" ]
null
null
null
framework/core/buffer.cpp
TomasRejhons/siren
9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825
[ "MIT" ]
null
null
null
framework/core/buffer.cpp
TomasRejhons/siren
9ef3ace7174cbdb48b9e45a2db104f3f5c4b9825
[ "MIT" ]
1
2021-05-26T12:06:12.000Z
2021-05-26T12:06:12.000Z
/* * MIT License * * Copyright (c) 2021 silicon-village * * 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 "buffer.h" #include "device.h" namespace siren { namespace core { Buffer::Buffer(Device &device, VkDeviceSize size, VkBufferUsageFlags buffer_usage, VmaMemoryUsage memory_usage, VmaAllocationCreateFlags flags) : device{device}, size{size} { #ifdef VK_USE_PLATFORM_MACOS_MVK // Workaround for Mac (MoltenVK requires unmapping https://github.com/KhronosGroup/MoltenVK/issues/175) // Force cleares the flag VMA_ALLOCATION_CREATE_MAPPED_BIT flags &= ~VMA_ALLOCATION_CREATE_MAPPED_BIT; #endif persistent = (flags & VMA_ALLOCATION_CREATE_MAPPED_BIT) != 0; VkBufferCreateInfo buffer_info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; buffer_info.usage = buffer_usage; buffer_info.size = size; VmaAllocationCreateInfo memory_info{}; memory_info.flags = flags; memory_info.usage = memory_usage; VmaAllocationInfo allocation_info{}; auto result = vmaCreateBuffer(device.get_memory_allocator(), &buffer_info, &memory_info, &handle, &allocation, &allocation_info); if (result != VK_SUCCESS) { throw VulkanException{result, "Cannot create Buffer"}; } memory = allocation_info.deviceMemory; if (persistent) { mapped_data = static_cast<uint8_t *>(allocation_info.pMappedData); } } Buffer::Buffer(Buffer &&other) : device{other.device}, handle{other.handle}, allocation{other.allocation}, memory{other.memory}, size{other.size}, mapped_data{other.mapped_data}, mapped{other.mapped} { // Reset other handles to avoid releasing on destruction other.handle = VK_NULL_HANDLE; other.allocation = VK_NULL_HANDLE; other.memory = VK_NULL_HANDLE; other.mapped_data = nullptr; other.mapped = false; } Buffer::~Buffer() { if (handle != VK_NULL_HANDLE && allocation != VK_NULL_HANDLE) { unmap(); vmaDestroyBuffer(device.get_memory_allocator(), handle, allocation); } } const Device &Buffer::get_device() const { return device; } VkBuffer Buffer::get_handle() const { return handle; } const VkBuffer *Buffer::get() const { return &handle; } VmaAllocation Buffer::get_allocation() const { return allocation; } VkDeviceMemory Buffer::get_memory() const { return memory; } VkDeviceSize Buffer::get_size() const { return size; } uint8_t *Buffer::map() { if (!mapped && !mapped_data) { VK_CHECK(vmaMapMemory(device.get_memory_allocator(), allocation, reinterpret_cast<void **>(&mapped_data))); mapped = true; } return mapped_data; } void Buffer::unmap() { if (mapped) { vmaUnmapMemory(device.get_memory_allocator(), allocation); mapped_data = nullptr; mapped = false; } } void Buffer::flush() const { vmaFlushAllocation(device.get_memory_allocator(), allocation, 0, size); } void Buffer::update(const std::vector<uint8_t> &data, size_t offset) { update(data.data(), data.size(), offset); } uint64_t Buffer::get_device_address() { VkBufferDeviceAddressInfoKHR buffer_device_address_info{}; buffer_device_address_info.sType = VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO; buffer_device_address_info.buffer = handle; return vkGetBufferDeviceAddressKHR(device.get_handle(), &buffer_device_address_info); } void Buffer::update(void *data, size_t size, size_t offset) { update(reinterpret_cast<const uint8_t *>(data), size, offset); } void Buffer::update(const uint8_t *data, const size_t size, const size_t offset) { if (persistent) { std::copy(data, data + size, mapped_data + offset); flush(); } else { map(); std::copy(data, data + size, mapped_data + offset); flush(); unmap(); } } } // namespace core } // namespace siren
31.239264
111
0.686371
[ "vector" ]
3df39255e0400e7ba0ada0805f62336318d7baf8
2,211
cpp
C++
JobScheduler/JobDedup.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
1
2016-09-10T17:08:56.000Z
2016-09-10T17:08:56.000Z
JobScheduler/JobDedup.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
null
null
null
JobScheduler/JobDedup.cpp
mple/sigmod-programming-contest2013
900a969822f192793fa5f4152383cc9f5daafab4
[ "MIT" ]
null
null
null
/* * JobDedup.cpp * * Created on: Mar 29, 2013 * Author: johnchronis */ #include "JobDedup.h" extern mple::TokenManager * globalmanager; //extern mple::TokenManager * docmanager; extern mple::JobScheduler* js;; extern google::dense_hash_map<int, bool> wordbatch; extern std::vector<int>* wordbatchv; extern std::vector<DocID> globaldocs; extern int batchno; ; extern pthread_mutex_t mtx_empty_spot; extern pthread_cond_t cond_empty_spot; extern std::queue<int> empty_spot; extern vector<int> doctokens; ; extern char** matchdocjs_buff; namespace mple { JobDedup::~JobDedup() { // TODO Auto-generated destructor stub } int JobDedup::Run() { char *cur_doc_str = (char*) matchdocjs_buff[spot]; char *buff; google::dense_hash_map<const char *, bool, mur, eqstr> docdupli_; docdupli_.set_empty_key(""); int i = 0, wl; bool doc_end = false; if (cur_doc_str[0] == '\0') { doc_end = true; } //int kara=0; //int dkara = 0; //if(dn!=dkara){ // dkara=dn; // kara=0; //} while (!doc_end) { //every word in a doc wl = 0; while (cur_doc_str[i] != '\0' && cur_doc_str[i] == ' ') { ++i; } buff = &cur_doc_str[i]; while (cur_doc_str[i] != '\0' && cur_doc_str[i] != ' ') { ++i; ++wl; } if (wl == 0) { continue; } if (cur_doc_str[i] == '\0') doc_end = true; i++; mple::TokenId temp; mple::ErrorCode ecode = globalmanager->AddDocToken(buff, wl, dn+1,batchno, &temp); if (ecode != mple::TOKENEXISTSINBATCH) { if (false){//kara<5 && dn==0) { //kara++; //JobMatchPruneDedup *J = new mple::JobMatchPruneDedup( globalmanager->GetTokenInfo(temp),temp.length_); //js->Schedule(J); doctokens.push_back(temp.key()); // cout<<"ours ------ "<<((DocToken *) docmanager->GetTokenInfo(temp))->GetTokenstring()<<endl; } else { wordbatchv[wl - MIN_WORD_LENGTH].push_back(temp.key()); //cout<<"not ours ------ "<<((DocToken *) docmanager->GetTokenInfo(temp))->GetTokenstring()<<endl; } //wordbatch[temp.key()] = true; } } globaldocs.push_back(dn+1); pthread_mutex_lock(&mtx_empty_spot); empty_spot.push(spot); pthread_cond_signal(&cond_empty_spot); pthread_mutex_unlock(&mtx_empty_spot); } } /* namespace mple */
24.032609
108
0.647671
[ "vector" ]
ad014e04942b8be7e741078305a1f4941d7a9cbc
26,338
hpp
C++
include/sigcxx/sigcxx.hpp
jiangrunwu/singal-and-slot
76c274a6c6153a97bc26619094d08df13651460c
[ "MIT" ]
null
null
null
include/sigcxx/sigcxx.hpp
jiangrunwu/singal-and-slot
76c274a6c6153a97bc26619094d08df13651460c
[ "MIT" ]
null
null
null
include/sigcxx/sigcxx.hpp
jiangrunwu/singal-and-slot
76c274a6c6153a97bc26619094d08df13651460c
[ "MIT" ]
null
null
null
/* * The MIT License (MIT) * * Copyright (c) 2015 Freeman Zhang <zhanggyb@gmail.com> * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #ifndef SIGCXX_SIGCXX_HPP_ #define SIGCXX_SIGCXX_HPP_ #include <cstddef> #include "delegate.hpp" #ifdef DEBUG #include <cassert> #endif namespace sigcxx { // forward declaration class Trackable; template<typename ... ParamTypes> class Signal; class Slot; typedef Slot *SLOT; #ifndef __SLOT__ /** * @brief A helper macro to define a slot parameter with default nullptr */ #define __SLOT__ SLOT slot = nullptr #endif /// @cond IGNORE namespace details { struct Token; template<typename ... ParamTypes> class SignalToken; /** * @brief A simple structure works as a list node in @ref Trackable object */ struct Binding { Binding() : trackable_object(nullptr), previous(nullptr), next(nullptr), token(nullptr) { } ~Binding(); Trackable *trackable_object; Binding *previous; Binding *next; Token *token; }; /** * @brief A simple structure works as a list node in @ref Signal object signals */ struct Token { Token() : trackable_object(nullptr), previous(nullptr), next(nullptr), binding(nullptr), slot(nullptr) { } virtual ~Token(); Trackable *trackable_object; Token *previous; Token *next; Binding *binding; Slot *slot; }; template<typename ... ParamTypes> class CallableToken : public Token { CallableToken(const CallableToken &orig) = delete; CallableToken &operator=(const CallableToken &other) = delete; public: CallableToken() : Token() {} virtual ~CallableToken() {} virtual void Invoke(ParamTypes ... Args) { // Override this in sub class } }; template<typename ... ParamTypes> class DelegateToken : public CallableToken<ParamTypes...> { DelegateToken() = delete; DelegateToken(const DelegateToken &orig) = delete; DelegateToken &operator=(const DelegateToken &other) = delete; public: DelegateToken(const Delegate<void(ParamTypes...)> &d) : CallableToken<ParamTypes...>(), delegate_(d) { } virtual ~DelegateToken() {} virtual void Invoke(ParamTypes... Args) final { delegate_(Args...); } inline const Delegate<void(ParamTypes...)> &delegate() const { return delegate_; } private: Delegate<void(ParamTypes...)> delegate_; }; template<typename ... ParamTypes> class SignalToken : public CallableToken<ParamTypes...> { SignalToken() = delete; SignalToken(const SignalToken &orig) = delete; SignalToken &operator=(const SignalToken &other) = delete; public: SignalToken(Signal<ParamTypes...> &signal) : CallableToken<ParamTypes...>(), signal_(&signal) { } virtual ~SignalToken() {} virtual void Invoke(ParamTypes... Args) final { signal_->Emit(Args...); } const Signal<ParamTypes...> *signal() const { return signal_; } private: Signal<ParamTypes...> *signal_; }; }// namespace details /// @endcond /** * @brief Iterator and signature to a slot method * * A Slot object is created and destroyed when a signal is being emitting. * * It has two main purpose: * - Works as an iterator * - The last parameter in a slot method * * A Signal holds a list of token to support multicast, when it's being * emitting, it create a simple Slot object and use it as an iterate and call * each delegate (@ref Delegate) to the slot method or another signal. */ class Slot { friend struct details::Token; template<typename ... ParamTypes> friend class Signal; template<typename ... ParamTypes> friend class details::SignalToken; friend class Trackable; Slot() = delete; Slot(const Slot &orig) = delete; Slot &operator=(const Slot &other) = delete; public: /** * @brief Get the Signal object which is just calling this slot */ template<typename ... ParamTypes> Signal<ParamTypes...> *signal() const { return dynamic_cast<Signal<ParamTypes...> *>(token_->trackable_object); } /** * @brief The trackable object in which the slot method is being called * @return The trackable object receiving signal */ Trackable *binding_object() const { return token_->binding->trackable_object; } private: Slot(details::Token *token = nullptr) : token_(token), skip_(false) {} ~Slot() {} details::Token *token_; bool skip_; }; /** * @brief The basic class for an object which provides slot methods */ class Trackable { friend struct details::Binding; friend struct details::Token; template<typename ... ParamTypes> friend class Signal; public: Trackable() : first_binding_(nullptr), last_binding_(nullptr) { } virtual ~Trackable(); Trackable(const Trackable &orig) {} Trackable &operator=(const Trackable &orig) { return *this; } /** * @brief Count connections to the given slot method */ template<typename T, typename ... ParamTypes> std::size_t CountBindings(void (T::*method)(ParamTypes...)) const; /** * @brief Count all connections */ std::size_t CountBindings() const; protected: /** * @brief Break the connection to a signal by given slot * * This is the fastest way to disconnect from a signal via the slot parameter. */ void Unbind(SLOT slot); /** * @brief Break the all connections to this object */ void UnbindAll(); /** * @brief Break all connections to the given slot method of this object */ template<typename T, typename ... ParamTypes> void UnbindAll(void (T::*method)(ParamTypes...)); virtual void AuditDestroyingToken(details::Token *token) {} void PushBackBinding(details::Binding *binding); void PushFrontBinding(details::Binding *binding); void InsertBinding(int index, details::Binding *binding); static inline void link(details::Token *token, details::Binding *binding) { #ifdef DEBUG assert((nullptr == token->binding) && (nullptr == binding->token)); #endif token->binding = binding; binding->token = token; } static inline void push_front(Trackable *trackable, details::Binding *binding) { trackable->PushBackBinding(binding); } static inline void push_back(Trackable *trackable, details::Binding *binding) { trackable->PushBackBinding(binding); } static inline void insert(Trackable *trackable, details::Binding *binding, int index = 0) { trackable->InsertBinding(index, binding); } details::Binding *first_binding() const { return first_binding_; } details::Binding *last_binding() const { return last_binding_; } private: details::Binding *first_binding_; details::Binding *last_binding_; }; template<typename T, typename ... ParamTypes> void Trackable::UnbindAll(void (T::*method)(ParamTypes...)) { details::Binding *it = last_binding_; details::Binding *tmp = nullptr; details::DelegateToken<ParamTypes...> *delegate_token = nullptr; while (it) { tmp = it; it = it->previous; delegate_token = dynamic_cast<details::DelegateToken<ParamTypes...> *>(tmp->token); if (delegate_token && (delegate_token->delegate().template Equal<T>((T *) this, method))) { delete tmp; } } } template<typename T, typename ... ParamTypes> size_t Trackable::CountBindings(void (T::*method)(ParamTypes...)) const { std::size_t count = 0; details::DelegateToken<ParamTypes...> *delegate_token = nullptr; for (details::Binding *p = first_binding_; p; p = p->next) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes...> *>(p->token); if (delegate_token && (delegate_token->delegate().template Equal<T>((T *) this, method))) { count++; } } return count; } /** * @brief A template class which can emit signal(s) */ template<typename ... ParamTypes> class Signal : public Trackable { friend class Trackable; Signal(const Signal &orig) = delete; Signal &operator=(const Signal &orig) = delete; public: Signal() : Trackable(), first_token_(nullptr), last_token_(nullptr) { } virtual ~Signal() { DisconnectAll(); } /** * @brief Connect this signal to a slot method in a observer */ template<typename T> void Connect(T *obj, void (T::*method)(ParamTypes..., SLOT), int index = -1); void Connect(Signal<ParamTypes...> &other, int index = -1); /** * @brief Disconnect all delegates to a method */ template<typename T> void DisconnectAll(T *obj, void (T::*method)(ParamTypes..., SLOT)); /** * @brief Disconnect all signals */ void DisconnectAll(Signal<ParamTypes...> &other); /** * @brief Disconnect delegats to a method by given start position and counts * @tparam T * @param obj * @param method * @param start_pos * @param counts * @return A integer number of how many delegates are found and disconnected * * By the default parameters this disconnect the last delegate to a method. */ template<typename T> int Disconnect(T *obj, void (T::*method)(ParamTypes..., SLOT), int start_pos = -1, int counts = 1); /** * @brief Disconnect connections to a signal by given start position and counts * @param other * @param start_pos * @param counts * @return A integer number of how many signals are found and disconnected * * By the default parameters this disconnect the last signal. */ int Disconnect(Signal<ParamTypes...> &other, int start_pos = -1, int counts = 1); /** * @brief Disconnect any kind of connections from the start position * @param start_pos * @param counts How many connections to be break, if it's negative or a very big number, * this is the same as DisconnectAll() * @return */ int Disconnect(int start_pos = -1, int counts = 1); /** * @brief Disconnect all */ void DisconnectAll(); template<typename T> bool IsConnectedTo(T *obj, void (T::*method)(ParamTypes..., SLOT)) const; bool IsConnectedTo(const Signal<ParamTypes...> &other) const; bool IsConnectedTo(const Trackable *obj) const; template<typename T> std::size_t CountConnections(T *obj, void (T::*method)(ParamTypes..., SLOT)) const; std::size_t CountConnections(const Signal<ParamTypes...> &other) const; std::size_t CountConnections() const; void Emit(ParamTypes ... Args); inline void operator()(ParamTypes ... Args) { Emit(Args...); } protected: virtual void AuditDestroyingToken(details::Token *token) final; void PushBackToken(details::Token *token); void PushFrontToken(details::Token *token); void InsertToken(int index, details::Token *token); inline details::Token *first_token() const { return first_token_; } inline details::Token *last_token() const { return last_token_; } private: details::Token *first_token_; details::Token *last_token_; }; // Signal implementation: template<typename ... ParamTypes> template<typename T> void Signal<ParamTypes...>::Connect(T *obj, void (T::*method)(ParamTypes..., SLOT), int index) { details::Binding *downstream = new details::Binding; Delegate<void(ParamTypes..., SLOT)> d = Delegate<void(ParamTypes..., SLOT)>::template FromMethod<T>(obj, method); details::DelegateToken<ParamTypes..., SLOT> *token = new details::DelegateToken< ParamTypes..., SLOT>(d); link(token, downstream); InsertToken(index, token); push_back(obj, downstream); // always push back binding, don't care about the position in observer } template<typename ... ParamTypes> void Signal<ParamTypes...>::Connect(Signal<ParamTypes...> &other, int index) { details::SignalToken<ParamTypes...> *token = new details::SignalToken<ParamTypes...>( other); details::Binding *binding = new details::Binding; link(token, binding); InsertToken(index, token); push_back(&other, binding); // always push back binding, don't care about the position in observer } template<typename ... ParamTypes> template<typename T> void Signal<ParamTypes...>::DisconnectAll(T *obj, void (T::*method)(ParamTypes..., SLOT)) { details::DelegateToken<ParamTypes..., SLOT> *delegate_token = nullptr; details::Token *it = last_token_; details::Token *tmp = nullptr; while (it) { tmp = it; it = it->previous; if (tmp->binding->trackable_object == obj) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes..., SLOT> * > (tmp); if (delegate_token && (delegate_token->delegate().template Equal<T>(obj, method))) { delete tmp; } } } } template<typename ... ParamTypes> void Signal<ParamTypes...>::DisconnectAll(Signal<ParamTypes...> &other) { details::SignalToken<ParamTypes...> *signal_token = nullptr; details::Token *it = last_token_; details::Token *tmp = nullptr; while (it) { tmp = it; it = it->previous; if (tmp->binding->trackable_object == (&other)) { signal_token = dynamic_cast<details::SignalToken<ParamTypes...> * > (tmp); if (signal_token && (signal_token->signal() == (&other))) { delete tmp; } } } } template<typename ... ParamTypes> template<typename T> int Signal<ParamTypes...>::Disconnect(T *obj, void (T::*method)(ParamTypes..., SLOT), int start_pos, int counts) { details::DelegateToken<ParamTypes..., SLOT> *delegate_token = nullptr; details::Token *it = nullptr; details::Token *tmp = nullptr; int ret_count = 0; if (start_pos >= 0) { it = first_token_; while (it && (start_pos > 0)) { it = it->next; start_pos--; } while (it) { tmp = it; it = it->next; if (tmp->binding->trackable_object == obj) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes..., SLOT> * > (tmp); if (delegate_token && (delegate_token->delegate().template Equal<T>(obj, method))) { ret_count++; counts--; delete tmp; } } if (counts == 0) break; } } else { it = last_token_; while (it && (start_pos < -1)) { it = it->previous; start_pos++; } while (it) { tmp = it; it = it->previous; if (tmp->binding->trackable_object == obj) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes..., SLOT> * > (tmp); if (delegate_token && (delegate_token->delegate().template Equal<T>(obj, method))) { ret_count++; counts--; delete tmp; } } if (counts == 0) break; } } return ret_count; } template<typename ... ParamTypes> int Signal<ParamTypes...>::Disconnect(Signal<ParamTypes...> &other, int start_pos, int counts) { details::SignalToken<ParamTypes...> *signal_token = nullptr; details::Token *it = nullptr; details::Token *tmp = nullptr; int ret_count = 0; if (start_pos >= 0) { it = first_token_; while (it && (start_pos > 0)) { it = it->next; start_pos--; } while (it) { tmp = it; it = it->next; if (tmp->binding->trackable_object == (&other)) { signal_token = dynamic_cast<details::SignalToken<ParamTypes...> * > (tmp); if (signal_token && (signal_token->signal() == (&other))) { ret_count++; counts--; delete tmp; } } if (counts == 0) break; } } else { it = last_token_; while (it && (start_pos < -1)) { it = it->previous; start_pos++; } while (it) { tmp = it; it = it->previous; if (tmp->binding->trackable_object == (&other)) { signal_token = dynamic_cast<details::SignalToken<ParamTypes...> * > (tmp); if (signal_token && (signal_token->signal() == (&other))) { ret_count++; counts--; delete tmp; } } if (counts == 0) break; } } return ret_count; } template<typename ... ParamTypes> int Signal<ParamTypes...>::Disconnect(int start_pos, int counts) { details::Token *it = nullptr; details::Token *tmp = nullptr; int ret_count = 0; if (start_pos >= 0) { it = first_token_; while (it && (start_pos > 0)) { it = it->next; start_pos--; } while (it) { tmp = it; it = it->next; ret_count++; counts--; delete tmp; if (counts == 0) break; } } else { it = last_token_; while (it && (start_pos < -1)) { it = it->previous; start_pos++; } while (it) { tmp = it; it = it->previous; ret_count++; counts--; delete tmp; if (counts == 0) break; } } return ret_count; } template<typename ... ParamTypes> template<typename T> bool Signal<ParamTypes...>::IsConnectedTo(T *obj, void (T::*method)(ParamTypes..., SLOT)) const { details::DelegateToken<ParamTypes..., SLOT> *delegate_token = nullptr; for (details::Token *it = first_token_; it; it = it->next) { if (it->binding->trackable_object == obj) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes..., SLOT> *>(it); if (delegate_token && (delegate_token->delegate().template Equal<T>(obj, method))) { return true; } } } return false; } template<typename ... ParamTypes> bool Signal<ParamTypes...>::IsConnectedTo(const Signal<ParamTypes...> &other) const { details::SignalToken<ParamTypes...> *signal_token = nullptr; for (details::Token *it = first_token_; it; it = it->next) { if (it->binding->trackable_object == (&other)) { signal_token = dynamic_cast<details::SignalToken<ParamTypes...> * > (it); if (signal_token && (signal_token->signal() == (&other))) { return true; } } } return false; } template<typename ... ParamTypes> bool Signal<ParamTypes...>::IsConnectedTo(const Trackable *obj) const { details::Token *token = first_token(); details::Binding *binding = obj->first_binding(); while (token && binding) { if (token->binding->trackable_object == obj) return true; if (binding->token->trackable_object == this) return true; token = token->next; binding = binding->next; } return false; } template<typename ... ParamTypes> template<typename T> std::size_t Signal<ParamTypes...>::CountConnections(T *obj, void (T::*method)(ParamTypes..., SLOT)) const { std::size_t count = 0; details::DelegateToken<ParamTypes..., SLOT> *delegate_token = nullptr; for (details::Token *it = first_token_; it; it = it->next) { if (it->binding->trackable_object == obj) { delegate_token = dynamic_cast<details::DelegateToken<ParamTypes..., SLOT> *>(it); if (delegate_token && (delegate_token->delegate().template Equal<T>(obj, method))) { count++; } } } return count; } template<typename ... ParamTypes> std::size_t Signal<ParamTypes...>::CountConnections(const Signal<ParamTypes...> &other) const { std::size_t count = 0; details::SignalToken<ParamTypes...> *signal_token = nullptr; for (details::Token *it = first_token_; it; it = it->next) { if (it->binding->trackable_object == (&other)) { signal_token = dynamic_cast<details::SignalToken<ParamTypes...> * > (it); if (signal_token && (signal_token->signal() == (&other))) { count++; } } } return count; } template<typename ... ParamTypes> std::size_t Signal<ParamTypes...>::CountConnections() const { std::size_t count = 0; for (details::Token *it = first_token_; it; it = it->next) { count++; } return count; } template<typename ... ParamTypes> void Signal<ParamTypes...>::Emit(ParamTypes ... Args) { Slot slot(first_token()); while (slot.token_) { slot.token_->slot = &slot; static_cast<details::CallableToken<ParamTypes..., SLOT> * > (slot.token_)->Invoke(Args..., &slot); if (slot.skip_) { slot.skip_ = false; } else { slot.token_->slot = nullptr; slot.token_ = slot.token_->next; } } } template<typename ... ParamTypes> void Signal<ParamTypes...>::AuditDestroyingToken(details::Token *token) { if (token == first_token_) first_token_ = token->next; if (token == last_token_) last_token_ = token->previous; } template<typename ... ParamTypes> void Signal<ParamTypes...>::PushBackToken(details::Token *token) { #ifdef DEBUG assert(nullptr == token->trackable_object); #endif if (last_token_) { last_token_->next = token; token->previous = last_token_; } else { #ifdef DEBUG assert(nullptr == first_token_); #endif token->previous = nullptr; first_token_ = token; } last_token_ = token; token->next = nullptr; token->trackable_object = this; } template<typename ... ParamTypes> void Signal<ParamTypes...>::PushFrontToken(details::Token *token) { #ifdef DEBUG assert(nullptr == token->trackable_object); #endif if (first_token_) { first_token_->previous = token; token->next = first_token_; } else { #ifdef DEBUG assert(nullptr == last_token_); #endif token->next = nullptr; last_token_ = token; } first_token_ = token; token->previous = nullptr; token->trackable_object = this; } template<typename ... ParamTypes> void Signal<ParamTypes...>::InsertToken(int index, details::Token *token) { #ifdef DEBUG assert(nullptr == token->trackable_object); #endif if (nullptr == first_token_) { #ifdef DEBUG assert(nullptr == last_token_); #endif token->next = nullptr; last_token_ = token; first_token_ = token; token->previous = nullptr; } else { if (index >= 0) { details::Token *p = first_token_; #ifdef DEBUG assert(p != nullptr); #endif while (p && (index > 0)) { p = p->next; index--; } if (p) { // insert before p token->previous = p->previous; token->next = p; if (p->previous) p->previous->next = token; else first_token_ = token; p->previous = token; } else { // push back last_token_->next = token; token->previous = last_token_; last_token_ = token; token->next = nullptr; } } else { details::Token *p = last_token_; #ifdef DEBUG assert(p != nullptr); #endif while (p && (index < -1)) { p = p->previous; index++; } if (p) { // insert after p token->next = p->next; token->previous = p; if (p->next) p->next->previous = token; else last_token_ = token; p->next = token; } else { // push front first_token_->previous = token; token->next = first_token_; first_token_ = token; token->previous = nullptr; } } } token->trackable_object = this; } template<typename ... ParamTypes> void Signal<ParamTypes...>::DisconnectAll() { details::Token *it = first_token_; details::Token *tmp = nullptr; while (it) { tmp = it; it = it->next; delete tmp; } } /** * @brief A reference to a corresponding signal */ template<typename ... ParamTypes> class SignalRef { SignalRef() = delete; public: SignalRef(Signal<ParamTypes...> &signal) : signal_(&signal) { } SignalRef(const SignalRef &orig) : signal_(orig.signal_) { } ~SignalRef() {} SignalRef &operator=(const SignalRef &other) { signal_ = other.signal_; return *this; } template<typename T> void Connect(T *obj, void (T::*method)(ParamTypes..., SLOT), int index = -1) { signal_->Connect(obj, method, index); } void Connect(Signal<ParamTypes...> &signal, int index = -1) { signal_->Connect(signal, index); } template<typename T> void DisconnectAll(T *obj, void (T::*method)(ParamTypes..., SLOT)) { signal_->DisconnectAll(obj, method); } void DisconnectAll(Signal<ParamTypes...> &signal) { signal_->DisconnectAll(signal); } template<typename T> int Disconnect(T *obj, void (T::*method)(ParamTypes..., SLOT), int start_pos = -1, int counts = 1) { return signal_->Disconnect(obj, method, start_pos, counts); } int Disconnect(Signal<ParamTypes...> &signal, int start_pos = -1, int counts = 1) { return signal_->Disconnect(signal, start_pos, counts); } int Disconnect(int start_pos = -1, int counts = 1) { return signal_->Disconnect(start_pos, counts); } void DisconnectAll() { signal_->DisconnectAll(); } template<typename T> bool IsConnectedTo(T *obj, void (T::*method)(ParamTypes..., SLOT)) const { return signal_->IsConnectedTo(obj, method); } bool IsConnectedTo(const Signal<ParamTypes...> &signal) const { return signal_->IsConnectedTo(signal); } bool IsConnectedTo(const Trackable *obj) const { return signal_->IsConnectedTo(obj); } template<typename T> std::size_t CountConnections(T *obj, void (T::*method)(ParamTypes..., SLOT)) const { return signal_->CountConnections(obj, method); } std::size_t CountConnections(const Signal<ParamTypes...> &signal) const { return signal_->CountConnections(signal); } std::size_t CountConnections() const { return signal_->CountConnections(); } std::size_t CountBindings() const { return signal_->CountBindings(); } private: Signal<ParamTypes...> *signal_; }; } // namespace sigcxx #endif // SIGCXX_SIGCXX_HPP_
24.546132
114
0.643101
[ "object" ]
ad05201903100e960145f057f9dfdcb26036e758
39,504
cpp
C++
MoravaEngine/src/Renderer/RendererEditor.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
168
2020-07-18T04:20:27.000Z
2022-03-31T23:39:38.000Z
MoravaEngine/src/Renderer/RendererEditor.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
5
2020-11-23T12:33:06.000Z
2022-01-05T15:15:30.000Z
MoravaEngine/src/Renderer/RendererEditor.cpp
dtrajko/MoravaEngine
dab8a9e84bde6bdb5e979596c29cabccb566b9d4
[ "Apache-2.0" ]
8
2020-09-07T03:04:18.000Z
2022-03-25T13:47:16.000Z
#include "Renderer/RendererEditor.h" #include "Core/Application.h" #include "Core/Profiler.h" #include "Core/Timer.h" #include "Framebuffer/MoravaFramebuffer.h" #include "Mesh/GeometryFactory.h" #include "Scene/SceneEditor.h" #include "Platform/OpenGL/OpenGLMoravaShader.h" #include <stdexcept> RendererEditor::RendererEditor() { } RendererEditor::~RendererEditor() { } void RendererEditor::Init(Scene* scene) { m_IsViewportEnabled = ((SceneEditor*)scene)->m_IsViewportEnabled; SetUniforms(); SetShaders(); } void RendererEditor::SetUniforms() { } void RendererEditor::SetShaders() { Hazel::Ref<OpenGLMoravaShader> shaderEditor = MoravaShader::Create("Shaders/editor_object.vs", "Shaders/editor_object.fs"); RendererBasic::GetShaders().insert(std::make_pair("editor_object", shaderEditor)); Log::GetLogger()->info("RendererEditor: shaderEditor compiled [programID={0}]", shaderEditor->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderEditorPBR = MoravaShader::Create("Shaders/editor_object.vs", "Shaders/PBR/editor_object_pbr.fs"); RendererBasic::GetShaders().insert(std::make_pair("editor_object_pbr", shaderEditorPBR)); Log::GetLogger()->info("RendererEditor: shaderEditorPBR compiled [programID={0}]", shaderEditorPBR->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderSkinning = MoravaShader::Create("Shaders/OGLdev/skinning.vs", "Shaders/OGLdev/skinning.fs"); RendererBasic::GetShaders().insert(std::make_pair("skinning", shaderSkinning)); Log::GetLogger()->info("RendererEditor: shaderSkinning compiled [programID={0}]", shaderSkinning->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderHybridAnimPBR = MoravaShader::Create("Shaders/HybridAnimPBR.vs", "Shaders/HybridAnimPBR.fs"); RendererBasic::GetShaders().insert(std::make_pair("hybrid_anim_pbr", shaderHybridAnimPBR)); Log::GetLogger()->info("RendererEditor: shaderHybridAnimPBR compiled [programID={0}]", shaderHybridAnimPBR->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderShadowMap = MoravaShader::Create("Shaders/directional_shadow_map.vert", "Shaders/directional_shadow_map.frag"); RendererBasic::GetShaders().insert(std::make_pair("shadow_map", shaderShadowMap)); Log::GetLogger()->info("RendererEditor: shaderShadowMap compiled [programID={0}]", shaderShadowMap->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderOmniShadowMap = MoravaShader::Create("Shaders/omni_shadow_map.vert", "Shaders/omni_shadow_map.geom", "Shaders/omni_shadow_map.frag"); RendererBasic::GetShaders().insert(std::make_pair("omni_shadow_map", shaderOmniShadowMap)); Log::GetLogger()->info("RendererEditor: shaderOmniShadowMap compiled [programID={0}]", shaderOmniShadowMap->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderWater = MoravaShader::Create("Shaders/water.vert", "Shaders/water.frag"); RendererBasic::GetShaders().insert(std::make_pair("water", shaderWater)); Log::GetLogger()->info("RendererEditor: shaderWater compiled [programID={0}]", shaderWater->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderBackground = MoravaShader::Create("Shaders/LearnOpenGL/2.2.2.background.vs", "Shaders/LearnOpenGL/2.2.2.background.fs"); RendererBasic::GetShaders().insert(std::make_pair("background", shaderBackground)); Log::GetLogger()->info("RendererEditor: shaderBackground compiled [programID={0}]", shaderBackground->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderBasic = MoravaShader::Create("Shaders/basic.vs", "Shaders/basic.fs"); RendererBasic::GetShaders().insert(std::make_pair("basic", shaderBasic)); Log::GetLogger()->info("RendererEditor: shaderBasic compiled [programID={0}]", shaderBasic->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderGizmo = MoravaShader::Create("Shaders/gizmo.vs", "Shaders/gizmo.fs"); RendererBasic::GetShaders().insert(std::make_pair("gizmo", shaderGizmo)); Log::GetLogger()->info("RendererEditor: shaderGizmo compiled [programID={0}]", shaderGizmo->GetProgramID()); Hazel::Ref<OpenGLMoravaShader> shaderGlass = MoravaShader::Create("Shaders/glass.vs", "Shaders/glass.fs"); RendererBasic::GetShaders().insert(std::make_pair("glass", shaderGlass)); Log::GetLogger()->info("RendererEditor: shaderGlass compiled [programID={0}]", shaderGlass->GetProgramID()); shaderEditor->Bind(); shaderEditor->SetInt("albedoMap", 0); shaderEditor->SetInt("cubeMap", 1); shaderEditor->SetInt("shadowMap", 2); m_OmniShadowTxSlots.insert(std::make_pair("editor_object", 3)); // omniShadowMaps[i].shadowMap = 3 shaderEditorPBR->Bind(); shaderEditorPBR->SetInt("irradianceMap", 0); shaderEditorPBR->SetInt("prefilterMap", 1); shaderEditorPBR->SetInt("brdfLUT", 2); shaderEditorPBR->SetInt("albedoMap", 3); shaderEditorPBR->SetInt("normalMap", 4); shaderEditorPBR->SetInt("metallicMap", 5); shaderEditorPBR->SetInt("roughnessMap", 6); shaderEditorPBR->SetInt("aoMap", 7); shaderEditorPBR->SetInt("shadowMap", 8); m_OmniShadowTxSlots.insert(std::make_pair("editor_object_pbr", 9)); // omniShadowMaps[i].shadowMap = 9 shaderHybridAnimPBR->Bind(); shaderHybridAnimPBR->SetInt("u_AlbedoTexture", 1); shaderHybridAnimPBR->SetInt("u_NormalTexture", 2); shaderHybridAnimPBR->SetInt("u_MetalnessTexture", 3); shaderHybridAnimPBR->SetInt("u_RoughnessTexture", 4); shaderHybridAnimPBR->SetInt("u_EnvRadianceTex", 5); shaderHybridAnimPBR->SetInt("u_PrefilterMap", 6); shaderHybridAnimPBR->SetInt("u_BRDFLUT", 7); } void RendererEditor::RenderPassShadow(Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableShadows) return; if (!LightManager::directionalLight.GetEnabled()) return; if (LightManager::directionalLight.GetShadowMap() == nullptr) return; Hazel::Ref<OpenGLMoravaShader> shaderShadowMap = RendererBasic::GetShaders()["shadow_map"]; shaderShadowMap->Bind(); DirectionalLight* light = &LightManager::directionalLight; glViewport(0, 0, light->GetShadowMap()->GetShadowWidth(), light->GetShadowMap()->GetShadowHeight()); light->GetShadowMap()->BindForWriting(); // printf("RenderPassShadow write to FBO = %i Texture ID = %i\n", light->GetShadowMap()->GetFBO(), light->GetShadowMap()->GetTextureID()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); shaderShadowMap->SetMat4("u_DirLightTransform", light->CalculateLightTransform()); shaderShadowMap->SetBool("u_Animated", false); shaderShadowMap->Validate(); DisableCulling(); std::string passType = "shadow_dir"; scene->Render(mainWindow, projectionMatrix, passType, RendererBasic::GetShaders(), RendererBasic::GetUniforms()); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void RendererEditor::RenderPassOmniShadow(PointLight* light, Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableOmniShadows) return; Hazel::Ref<MoravaShader> shaderOmniShadow = RendererBasic::GetShaders()["omni_shadow_map"]; shaderOmniShadow->Bind(); glViewport(0, 0, light->GetShadowMap()->GetShadowWidth(), light->GetShadowMap()->GetShadowHeight()); light->GetShadowMap()->BindForWriting(); // printf("RenderPassOmniShadow write to FBO = %i Texture ID = %i\n", light->GetShadowMap()->GetFBO(), light->GetShadowMap()->GetTextureID()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glDisable(GL_BLEND); shaderOmniShadow->SetFloat3("lightPosition", light->GetPosition()); shaderOmniShadow->SetFloat("farPlane", light->GetFarPlane()); shaderOmniShadow->setLightMat4(light->CalculateLightTransform()); shaderOmniShadow->Validate(); EnableCulling(); std::string passType = "shadow_omni"; scene->Render(mainWindow, projectionMatrix, passType, RendererBasic::GetShaders(), RendererBasic::GetUniforms()); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void RendererEditor::RenderPassWaterReflection(Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableWaterEffects) return; glViewport(0, 0, scene->GetWaterManager()->GetFramebufferWidth(), scene->GetWaterManager()->GetFramebufferHeight()); scene->GetWaterManager()->GetReflectionFramebuffer()->Bind(); // Clear the window RendererBasic::Clear(); Hazel::Ref<OpenGLMoravaShader> shaderEditor = RendererBasic::GetShaders()["editor_object"]; shaderEditor->Bind(); shaderEditor->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditor->SetMat4("projection", projectionMatrix); shaderEditor->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditor->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditor->SetFloat4("clipPlane", glm::vec4(0.0f, 1.0f, 0.0f, -scene->GetWaterManager()->GetWaterHeight())); // reflection clip plane Hazel::Ref<MoravaShader> shaderEditorPBR = RendererBasic::GetShaders()["editor_object_pbr"]; shaderEditorPBR->Bind(); shaderEditorPBR->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditorPBR->SetMat4("projection", projectionMatrix); shaderEditorPBR->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditorPBR->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditorPBR->SetFloat4("clipPlane", glm::vec4(0.0f, 1.0f, 0.0f, -scene->GetWaterManager()->GetWaterHeight())); // reflection clip plane Hazel::Ref<MoravaShader> shaderSkinning = RendererBasic::GetShaders()["skinning"]; shaderSkinning->Bind(); shaderSkinning->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderSkinning->SetMat4("projection", projectionMatrix); shaderSkinning->SetFloat4("clipPlane", glm::vec4(0.0f, 1.0f, 0.0f, -scene->GetWaterManager()->GetWaterHeight())); // reflection clip plane Hazel::Ref<OpenGLMoravaShader> shaderHybridAnimPBR = RendererBasic::GetShaders()["hybrid_anim_pbr"]; shaderHybridAnimPBR->Bind(); shaderHybridAnimPBR->SetMat4("u_ViewProjectionMatrix", projectionMatrix * scene->GetCamera()->GetViewMatrix()); DisableCulling(); std::string passType = "water_reflect"; scene->Render(mainWindow, projectionMatrix, passType, RendererBasic::GetShaders(), RendererBasic::GetUniforms()); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void RendererEditor::RenderPassWaterRefraction(Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableWaterEffects) return; glViewport(0, 0, scene->GetWaterManager()->GetFramebufferWidth(), scene->GetWaterManager()->GetFramebufferHeight()); scene->GetWaterManager()->GetRefractionFramebuffer()->Bind(); scene->GetWaterManager()->GetRefractionFramebuffer()->GetColorAttachment()->Bind(scene->GetTextureSlots()["refraction"]); scene->GetWaterManager()->GetRefractionFramebuffer()->GetDepthAttachment()->Bind(scene->GetTextureSlots()["depth"]); // Clear the window RendererBasic::Clear(); Hazel::Ref<OpenGLMoravaShader> shaderEditor = RendererBasic::GetShaders()["editor_object"]; shaderEditor->Bind(); shaderEditor->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditor->SetMat4("projection", projectionMatrix); shaderEditor->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditor->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditor->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, scene->GetWaterManager()->GetWaterHeight())); // refraction clip plane Hazel::Ref<OpenGLMoravaShader> shaderEditorPBR = RendererBasic::GetShaders()["editor_object_pbr"]; shaderEditorPBR->Bind(); shaderEditorPBR->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditorPBR->SetMat4("projection", projectionMatrix); shaderEditorPBR->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditorPBR->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditorPBR->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, scene->GetWaterManager()->GetWaterHeight())); // refraction clip plane Hazel::Ref<OpenGLMoravaShader> shaderSkinning = RendererBasic::GetShaders()["skinning"]; shaderSkinning->Bind(); shaderSkinning->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderSkinning->SetMat4("projection", projectionMatrix); shaderSkinning->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, scene->GetWaterManager()->GetWaterHeight())); // refraction clip plane Hazel::Ref<OpenGLMoravaShader> shaderHybridAnimPBR = RendererBasic::GetShaders()["hybrid_anim_pbr"]; shaderHybridAnimPBR->Bind(); shaderHybridAnimPBR->SetMat4("u_ViewProjectionMatrix", projectionMatrix * scene->GetCamera()->GetViewMatrix()); DisableCulling(); std::string passType = "water_refract"; scene->Render(mainWindow, projectionMatrix, passType, RendererBasic::GetShaders(), RendererBasic::GetUniforms()); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void RendererEditor::RenderOmniShadows(Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableOmniShadows) return; for (size_t i = 0; i < LightManager::pointLightCount; i++) { if (LightManager::pointLights[i].GetEnabled()) { std::string profilerTitle = "RE::RenderPassOmniShadow[PL_" + std::to_string(i) + ']'; Profiler profiler(profilerTitle); RenderPassOmniShadow(&LightManager::pointLights[i], mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } } for (size_t i = 0; i < LightManager::spotLightCount; i++) { if (LightManager::spotLights[i].GetBasePL()->GetEnabled()) { std::string profilerTitle = "RE::RenderPassOmniShadow[SL_" + std::to_string(i) + ']'; Profiler profiler(profilerTitle); RenderPassOmniShadow((PointLight*)&LightManager::spotLights[i], mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } } } void RendererEditor::RenderWaterEffects(float deltaTime, Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { if (!scene->GetSettings().enableWaterEffects) return; if (!scene->IsWaterOnScene()) return; glEnable(GL_CLIP_DISTANCE0); float waterMoveFactor = scene->GetWaterManager()->GetWaterMoveFactor(); waterMoveFactor += WaterManager::m_WaveSpeed * deltaTime; if (waterMoveFactor >= 1.0f) waterMoveFactor = waterMoveFactor - 1.0f; scene->GetWaterManager()->SetWaterMoveFactor(waterMoveFactor); float distance = 2.0f * (scene->GetCamera()->GetPosition().y - scene->GetWaterManager()->GetWaterHeight()); scene->GetCamera()->SetPosition(glm::vec3(scene->GetCamera()->GetPosition().x, scene->GetCamera()->GetPosition().y - distance, scene->GetCamera()->GetPosition().z)); scene->GetCameraController()->InvertPitch(); { Profiler profiler("RE::RenderPassWaterReflection"); RenderPassWaterReflection(mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } scene->GetCamera()->SetPosition(glm::vec3(scene->GetCamera()->GetPosition().x, scene->GetCamera()->GetPosition().y + distance, scene->GetCamera()->GetPosition().z)); scene->GetCameraController()->InvertPitch(); { Profiler profiler("RE::RenderPassWaterRefraction"); RenderPassWaterRefraction(mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } glDisable(GL_CLIP_DISTANCE0); } void RendererEditor::RenderPassMain(Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { SceneEditor* sceneEditor = (SceneEditor*)scene; Hazel::Ref<MoravaFramebuffer> renderFramebuffer; if (m_IsViewportEnabled) { renderFramebuffer = sceneEditor->GetRenderFramebuffer(); renderFramebuffer->Bind(); renderFramebuffer->Clear(); // Clear the window } else { glViewport(0, 0, (GLsizei)mainWindow->GetWidth(), (GLsizei)mainWindow->GetHeight()); } // Clear the window RendererBasic::Clear(); // configure global opengl state glEnable(GL_DEPTH_TEST); // set depth function to less than AND equal for skybox depth trick. glDepthFunc(GL_LEQUAL); // enable seamless cubemap sampling for lower mip levels in the pre-filter map. glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // then before rendering, configure the viewport to the original framebuffer's screen dimensions if (!m_IsViewportEnabled) SetDefaultFramebuffer((unsigned int)mainWindow->GetWidth(), (unsigned int)mainWindow->GetHeight()); EnableTransparency(); EnableCulling(); if (scene->GetSettings().enableSkybox) { glm::mat4 modelMatrix = glm::mat4(1.0f); float angleRadians = glm::radians((GLfloat)glfwGetTime()); modelMatrix = glm::rotate(modelMatrix, angleRadians, glm::vec3(0.0f, 1.0f, 0.0f)); scene->GetSkybox()->Draw(modelMatrix, scene->GetCamera()->GetViewMatrix(), projectionMatrix); } scene->GetSettings().enableCulling ? EnableCulling() : DisableCulling(); std::string passType = "main"; scene->Render(mainWindow, projectionMatrix, passType, RendererBasic::GetShaders(), RendererBasic::GetUniforms()); if (m_IsViewportEnabled) { renderFramebuffer->Unbind(); } } void RendererEditor::RenderStageSetUniforms(Scene* scene, glm::mat4* projectionMatrix) { /**** Begin editor_object ****/ Hazel::Ref<OpenGLMoravaShader> shaderEditor = RendererBasic::GetShaders()["editor_object"]; shaderEditor->Bind(); shaderEditor->SetMat4("model", glm::mat4(1.0f)); shaderEditor->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditor->SetMat4("projection", *projectionMatrix); shaderEditor->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditor->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, -10000)); shaderEditor->SetInt("pointLightCount", LightManager::pointLightCount); shaderEditor->SetInt("spotLightCount", LightManager::spotLightCount); // Eye position / camera direction shaderEditor->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditor->SetFloat("waterLevel", scene->GetWaterManager()->GetWaterHeight()); shaderEditor->SetFloat4("waterColor", scene->GetWaterManager()->GetWaterColor()); // Directional Light shaderEditor->SetBool("directionalLight.base.enabled", LightManager::directionalLight.GetEnabled()); shaderEditor->SetFloat3("directionalLight.base.color", LightManager::directionalLight.GetColor()); shaderEditor->SetFloat("directionalLight.base.ambientIntensity", LightManager::directionalLight.GetAmbientIntensity()); shaderEditor->SetFloat("directionalLight.base.diffuseIntensity", LightManager::directionalLight.GetDiffuseIntensity()); shaderEditor->SetFloat3("directionalLight.direction", LightManager::directionalLight.GetDirection()); char locBuff[100] = { '\0' }; // Point Lights for (unsigned int i = 0; i < LightManager::pointLightCount; i++) { snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.enabled", i); // printf("PointLight[%d] enabled: %d\n", i, LightManager::pointLights[i].GetEnabled()); shaderEditor->SetBool(locBuff, LightManager::pointLights[i].GetEnabled()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.color", i); shaderEditor->SetFloat3(locBuff, LightManager::pointLights[i].GetColor()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.ambientIntensity", i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetAmbientIntensity()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].base.diffuseIntensity", i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetDiffuseIntensity()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].position", i); shaderEditor->SetFloat3(locBuff, LightManager::pointLights[i].GetPosition()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].constant", i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetConstant()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].linear", i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetLinear()); snprintf(locBuff, sizeof(locBuff), "pointLights[%d].exponent", i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetExponent()); // set uniforms for omni shadow maps // texture slot for 'omniShadowMaps[i].shadowMap' samplerCube in editor_object.fs is 3 int textureSlotOffset = 0; LightManager::pointLights[i].GetShadowMap()->ReadTexture(m_OmniShadowTxSlots["editor_object"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].shadowMap", textureSlotOffset + i); shaderEditor->SetInt(locBuff, m_OmniShadowTxSlots["editor_object"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].farPlane", textureSlotOffset + i); shaderEditor->SetFloat(locBuff, LightManager::pointLights[i].GetFarPlane()); } // Spot Lights for (unsigned int i = 0; i < LightManager::spotLightCount; i++) { snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.enabled", i); shaderEditor->SetBool(locBuff, LightManager::spotLights[i].GetBasePL()->GetEnabled()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.color", i); shaderEditor->SetFloat3(locBuff, LightManager::spotLights[i].GetBasePL()->GetColor()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.ambientIntensity", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetAmbientIntensity()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.base.diffuseIntensity", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetDiffuseIntensity()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.position", i); shaderEditor->SetFloat3(locBuff, LightManager::spotLights[i].GetBasePL()->GetPosition()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.constant", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetConstant()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.linear", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetLinear()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].base.exponent", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetExponent()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].direction", i); shaderEditor->SetFloat3(locBuff, LightManager::spotLights[i].GetDirection()); snprintf(locBuff, sizeof(locBuff), "spotLights[%d].edge", i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetEdge()); // set uniforms for omni shadow maps // texture slot for 'omniShadowMaps[i].shadowMap' samplerCube in editor_object.fs is 3 int textureSlotOffset = LightManager::pointLightCount; LightManager::spotLights[i].GetShadowMap()->ReadTexture(m_OmniShadowTxSlots["editor_object"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].shadowMap", textureSlotOffset + i); shaderEditor->SetInt(locBuff, m_OmniShadowTxSlots["editor_object"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].farPlane", textureSlotOffset + i); shaderEditor->SetFloat(locBuff, LightManager::spotLights[i].GetFarPlane()); } /**** End editor_object ****/ /**** Begin editor_object_pbr ****/ // Init shaderEditorPBR Hazel::Ref<OpenGLMoravaShader> shaderEditorPBR = RendererBasic::GetShaders()["editor_object_pbr"]; shaderEditorPBR->Bind(); // initialize static shader uniforms before rendering shaderEditorPBR->SetMat4("model", glm::mat4(1.0f)); shaderEditorPBR->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderEditorPBR->SetMat4("projection", *projectionMatrix); shaderEditorPBR->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderEditorPBR->SetMat4("dirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderEditorPBR->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, -10000)); shaderEditorPBR->SetFloat("waterLevel", scene->GetWaterManager()->GetWaterHeight()); shaderEditorPBR->SetFloat4("waterColor", scene->GetWaterManager()->GetWaterColor()); shaderEditorPBR->SetInt("pointSpotLightCount", LightManager::pointLightCount + LightManager::spotLightCount); // directional light shaderEditorPBR->SetBool("directionalLight.base.enabled", LightManager::directionalLight.GetEnabled()); shaderEditorPBR->SetFloat3("directionalLight.base.color", LightManager::directionalLight.GetColor()); shaderEditorPBR->SetFloat("directionalLight.base.ambientIntensity", LightManager::directionalLight.GetAmbientIntensity()); shaderEditorPBR->SetFloat("directionalLight.base.diffuseIntensity", LightManager::directionalLight.GetDiffuseIntensity()); shaderEditorPBR->SetFloat3("directionalLight.direction", LightManager::directionalLight.GetDirection()); // printf("Exponent = %.2ff Linear = %.2ff Constant = %.2ff\n", *m_PointLightExponent, *m_PointLightLinear, *m_PointLightConstant); // point lights unsigned int lightIndex = 0; for (unsigned int i = 0; i < LightManager::pointLightCount; ++i) { lightIndex = 0 + i; // offset for point lights snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.enabled", lightIndex); shaderEditorPBR->SetBool(locBuff, LightManager::pointLights[i].GetEnabled()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.color", lightIndex); shaderEditorPBR->SetFloat3(locBuff, LightManager::pointLights[i].GetColor()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.ambientIntensity", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetAmbientIntensity()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.diffuseIntensity", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetDiffuseIntensity()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].position", lightIndex); shaderEditorPBR->SetFloat3(locBuff, LightManager::pointLights[i].GetPosition()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].exponent", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetExponent()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].linear", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetLinear()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].constant", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetConstant()); // set uniforms for omni shadow maps // texture slot for 'omniShadowMaps[i].shadowMap' samplerCube in editor_object_pbr.fs is 9 int textureSlotOffset = 0; LightManager::pointLights[i].GetShadowMap()->ReadTexture(m_OmniShadowTxSlots["editor_object_pbr"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].shadowMap", textureSlotOffset + i); shaderEditorPBR->SetInt(locBuff, m_OmniShadowTxSlots["editor_object_pbr"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].farPlane", textureSlotOffset + i); shaderEditorPBR->SetFloat(locBuff, LightManager::pointLights[i].GetFarPlane()); } for (unsigned int i = 0; i < LightManager::spotLightCount; ++i) { lightIndex = LightManager::pointLightCount + i; // offset for spot lights snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.enabled", lightIndex); shaderEditorPBR->SetBool(locBuff, LightManager::spotLights[i].GetBasePL()->GetEnabled()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.color", lightIndex); shaderEditorPBR->SetFloat3(locBuff, LightManager::spotLights[i].GetBasePL()->GetColor()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.ambientIntensity", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetAmbientIntensity()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].base.diffuseIntensity", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetDiffuseIntensity()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].position", lightIndex); shaderEditorPBR->SetFloat3(locBuff, LightManager::spotLights[i].GetBasePL()->GetPosition()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].exponent", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetExponent()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].linear", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetLinear()); snprintf(locBuff, sizeof(locBuff), "pointSpotLights[%d].constant", lightIndex); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetBasePL()->GetConstant()); // set uniforms for omni shadow maps // texture slot for 'omniShadowMaps[i].shadowMap' samplerCube in editor_object_pbr.fs is 9 int textureSlotOffset = LightManager::pointLightCount; LightManager::spotLights[i].GetShadowMap()->ReadTexture(m_OmniShadowTxSlots["editor_object_pbr"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].shadowMap", textureSlotOffset + i); shaderEditorPBR->SetInt(locBuff, m_OmniShadowTxSlots["editor_object_pbr"] + textureSlotOffset + i); snprintf(locBuff, sizeof(locBuff), "omniShadowMaps[%d].farPlane", textureSlotOffset + i); shaderEditorPBR->SetFloat(locBuff, LightManager::spotLights[i].GetFarPlane()); } /**** End editor_object_pbr ****/ /**** Begin skinning ****/ Hazel::Ref<OpenGLMoravaShader> shaderSkinning = RendererBasic::GetShaders()["skinning"]; shaderSkinning->Bind(); shaderSkinning->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderSkinning->SetMat4("projection", *projectionMatrix); shaderSkinning->SetFloat4("clipPlane", glm::vec4(0.0f, -1.0f, 0.0f, -10000)); shaderSkinning->SetFloat3("gEyeWorldPos", scene->GetCamera()->GetPosition()); shaderSkinning->SetFloat("waterLevel", scene->GetWaterManager()->GetWaterHeight()); shaderSkinning->SetFloat4("waterColor", scene->GetWaterManager()->GetWaterColor()); // Directional Light shaderSkinning->SetFloat3("gDirectionalLight.Base.Color", LightManager::directionalLight.GetColor()); shaderSkinning->SetFloat("gDirectionalLight.Base.AmbientIntensity", LightManager::directionalLight.GetAmbientIntensity()); shaderSkinning->SetFloat("gDirectionalLight.Base.DiffuseIntensity", LightManager::directionalLight.GetDiffuseIntensity()); shaderSkinning->SetFloat3("gDirectionalLight.Direction", LightManager::directionalLight.GetDirection()); // TODO: point lights shaderSkinning->SetInt("gNumPointLights", 0); // TODO: spot lights shaderSkinning->SetInt("gNumSpotLights", 0); /**** End skinning ****/ /**** Begin Hybrid Anim PBR ****/ Hazel::Ref<OpenGLMoravaShader> shaderHybridAnimPBR = RendererBasic::GetShaders()["hybrid_anim_pbr"]; shaderHybridAnimPBR->Bind(); shaderHybridAnimPBR->SetMat4("u_ViewProjectionMatrix", *projectionMatrix * scene->GetCamera()->GetViewMatrix()); shaderHybridAnimPBR->SetFloat3("u_CameraPosition", scene->GetCamera()->GetPosition()); // point lights lightIndex = 0; for (unsigned int i = 0; i < LightManager::pointLightCount; ++i) { lightIndex = 0 + i; // offset for point lights std::string uniformName = std::string("lightPositions[") + std::to_string(lightIndex) + std::string("]"); shaderHybridAnimPBR->SetFloat3(uniformName, LightManager::pointLights[i].GetPosition()); uniformName = std::string("lightColors[") + std::to_string(lightIndex) + std::string("]"); shaderHybridAnimPBR->SetFloat3(uniformName, LightManager::pointLights[i].GetColor()); } for (unsigned int i = 0; i < LightManager::spotLightCount; ++i) { lightIndex = LightManager::pointLightCount + i; // offset for spot lights std::string uniformName = std::string("lightPositions[") + std::to_string(lightIndex) + std::string("]"); shaderHybridAnimPBR->SetFloat3(uniformName, LightManager::spotLights[i].GetBasePL()->GetPosition()); uniformName = std::string("lightColors[") + std::to_string(lightIndex) + std::string("]"); shaderHybridAnimPBR->SetFloat3(uniformName, LightManager::spotLights[i].GetBasePL()->GetColor()); } /**** End Hybrid Anim PBR ****/ /**** Begin shadow_map ****/ Hazel::Ref<OpenGLMoravaShader> shaderShadowMap = RendererBasic::GetShaders()["shadow_map"]; shaderShadowMap->Bind(); shaderShadowMap->SetMat4("u_DirLightTransform", LightManager::directionalLight.CalculateLightTransform()); shaderShadowMap->SetBool("u_Animated", false); /**** End shadow_map ****/ /**** Begin omni_shadow_map ****/ Hazel::Ref<OpenGLMoravaShader> shaderOmniShadowMap = RendererBasic::GetShaders()["omni_shadow_map"]; shaderOmniShadowMap->Bind(); shaderOmniShadowMap->SetFloat3("lightPosition", LightManager::directionalLight.GetPosition()); shaderOmniShadowMap->SetFloat("farPlane", scene->GetSettings().farPlane); /**** End omni_shadow_map ****/ /**** Begin shaderWater ****/ Hazel::Ref<OpenGLMoravaShader> shaderWater = RendererBasic::GetShaders()["water"]; shaderWater->Bind(); shaderWater->SetMat4("projection", *projectionMatrix); shaderWater->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderWater->SetFloat3("lightPosition", LightManager::directionalLight.GetPosition()); shaderWater->SetFloat3("cameraPosition", scene->GetCamera()->GetPosition()); shaderWater->SetFloat3("lightColor", LightManager::directionalLight.GetColor()); shaderWater->SetFloat("moveFactor", scene->GetWaterManager()->GetWaterMoveFactor()); shaderWater->SetFloat("nearPlane", scene->GetSettings().nearPlane); shaderWater->SetFloat("farPlane", scene->GetSettings().farPlane); shaderWater->SetFloat3("eyePosition", scene->GetCamera()->GetPosition()); shaderWater->SetFloat("waterLevel", scene->GetWaterManager()->GetWaterHeight()); shaderWater->SetFloat4("waterColor", scene->GetWaterManager()->GetWaterColor()); /**** End shaderWater ****/ /**** Begin Background shader ****/ Hazel::Ref<OpenGLMoravaShader> shaderBackground = RendererBasic::GetShaders()["background"]; shaderBackground->Bind(); shaderBackground->SetMat4("projection", *projectionMatrix); shaderBackground->SetMat4("view", scene->GetCamera()->GetViewMatrix()); /**** End Background shader ****/ /**** Begin of shaderBasic ****/ Hazel::Ref<OpenGLMoravaShader> shaderBasic = RendererBasic::GetShaders()["basic"]; shaderBasic->Bind(); shaderBasic->SetMat4("projection", *projectionMatrix); shaderBasic->SetMat4("view", scene->GetCamera()->GetViewMatrix()); /**** End of shaderBasic ****/ /**** Begin gizmo shader ****/ Hazel::Ref<OpenGLMoravaShader> shaderGizmo = RendererBasic::GetShaders()["gizmo"]; shaderGizmo->Bind(); // shaderGizmo->SetMat4("projection", *projectionMatrix); // experimental if (((SceneEditor*)scene)->m_GizmoOrthoProjection) { float aspectRatio = scene->GetCameraController()->GetAspectRatio(); float sizeCoef = 5.0f; glm::mat4 orthoMatrix = glm::ortho(-aspectRatio * sizeCoef, aspectRatio * sizeCoef, -1.0f * sizeCoef, 1.0f * sizeCoef, scene->GetSettings().nearPlane, scene->GetSettings().farPlane); shaderGizmo->SetMat4("projection", orthoMatrix); } else { shaderGizmo->SetMat4("projection", *projectionMatrix); } shaderGizmo->SetMat4("view", scene->GetCamera()->GetViewMatrix()); // Directional Light shaderGizmo->SetBool("directionalLight.base.enabled", LightManager::directionalLight.GetEnabled()); shaderGizmo->SetFloat3("directionalLight.base.color", LightManager::directionalLight.GetColor()); shaderGizmo->SetFloat("directionalLight.base.ambientIntensity", LightManager::directionalLight.GetAmbientIntensity()); shaderGizmo->SetFloat("directionalLight.base.diffuseIntensity", LightManager::directionalLight.GetDiffuseIntensity()); shaderGizmo->SetFloat3("directionalLight.direction", LightManager::directionalLight.GetDirection()); /**** End gizmo shader ****/ /**** Begin glass ****/ Hazel::Ref<OpenGLMoravaShader> shaderGlass = RendererBasic::GetShaders()["glass"]; shaderGlass->Bind(); shaderGlass->SetMat4("view", scene->GetCamera()->GetViewMatrix()); shaderGlass->SetMat4("projection", *projectionMatrix); shaderGlass->SetFloat3("cameraPosition", scene->GetCamera()->GetPosition()); /**** End glass ****/ } void RendererEditor::BeginFrame() { } void RendererEditor::WaitAndRender(float deltaTime, Window* mainWindow, Scene* scene, glm::mat4 projectionMatrix) { float aspectRatio = scene->GetCameraController()->GetAspectRatio(); projectionMatrix = glm::perspective(glm::radians(scene->GetFOV()), aspectRatio, scene->GetSettings().nearPlane, scene->GetSettings().farPlane); RendererBasic::SetProjectionMatrix(projectionMatrix); RenderStageSetUniforms(scene, &projectionMatrix); { Profiler profiler("RE::RenderPassShadow"); RenderPassShadow(mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } { Profiler profiler("RE::RenderOmniShadows"); RenderOmniShadows(mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } { Profiler profiler("RE::RenderWaterEffects"); RenderWaterEffects(deltaTime, mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } { Profiler profiler("RE::RenderPass"); RenderPassMain(mainWindow, scene, projectionMatrix); scene->GetProfilerResults()->insert(std::make_pair(profiler.GetName(), profiler.Stop())); } }
54.1893
174
0.71775
[ "mesh", "render", "model" ]
ad15656541ea17e85dab871b5a2bd819e49eeaca
5,980
cpp
C++
tests/14-variable-transformation.cpp
USCbiostats/binaryarrays
6bd956f1eddfe328841a2c96e99e40b194f75b26
[ "MIT" ]
null
null
null
tests/14-variable-transformation.cpp
USCbiostats/binaryarrays
6bd956f1eddfe328841a2c96e99e40b194f75b26
[ "MIT" ]
null
null
null
tests/14-variable-transformation.cpp
USCbiostats/binaryarrays
6bd956f1eddfe328841a2c96e99e40b194f75b26
[ "MIT" ]
null
null
null
#include "tests.hpp" BARRY_TEST_CASE("Transformation of models", "[transformation]") { // Reading large network /** set.seed(123) x <- ergmito::rbernoulli(4, .2) gender <- c(0,0,1,0) x <- network::network(x, vertex.attr = list(gender = gender)) ans <- ergm::ergm.allstats(x ~ edges + mutual + isolates + istar(2) + ostar(2) + ttriad + ctriad + density + idegree1.5 + odegree1.5 + nodematch("gender"),maxNumChangeStatVectors = 2^20, zeroobs = FALSE) ans <- cbind(ans$statmat, w = ans$weights) set.seed(9988) p0 <- runif(11) p1 <- runif(11) l0 <- log(exp(p0 %*% t(ans[, -ncol(ans)])) %*% cbind(ans[,ncol(ans)])) l1 <- log(exp(p1 %*% t(ans[, -ncol(ans)])) %*% cbind(ans[,ncol(ans)])) cat(sprintf("%.5f", p0), sep = ", ") cat(sprintf("%.5f", p1), sep = ", ") cat(sprintf("%.5f", c(l0, l1)), sep = ", ") cat(sprintf("%.5f", colMeans(ans[, -12])), sep = ", ") */ std::vector< double > p0 = {0.60959, 0.01940, 0.90534, 0.62935, 0.01958, 0.97016, 0.51485, 0.47980, 0.18479, 0.87739, 0.02286}; std::vector< double > p1 = {0.34609, 0.81370, 0.79881, 0.96398, 0.48765, 0.13675, 0.47716, 0.11797, 0.13809, 0.69155, 0.07703}; // Reverse version (for checking transformation) std::vector< double > p0_rev = p0; std::reverse(p0_rev.begin(), p0_rev.end()); std::vector< double > p1_rev = p1; std::reverse(p1_rev.begin(), p1_rev.end()); std::vector< double > logs_expected = {65.31523, 51.38268}; using namespace barry::counters::network; NetworkDense net(4, 4); net.set_data(new NetworkData({0,0,1,0}), true); NetSupport<NetworkDense> support(net); // Preparing model counter_edges<NetworkDense>(support.get_counters()); counter_mutual<NetworkDense>(support.get_counters()); counter_isolates<NetworkDense>(support.get_counters()); counter_istar2<NetworkDense>(support.get_counters()); counter_ostar2<NetworkDense>(support.get_counters()); counter_ttriads<NetworkDense>(support.get_counters()); counter_ctriads<NetworkDense>(support.get_counters()); counter_density<NetworkDense>(support.get_counters()); counter_idegree15<NetworkDense>(support.get_counters()); counter_odegree15<NetworkDense>(support.get_counters()); counter_nodematch<NetworkDense>(support.get_counters(),0u); rules_zerodiag<NetworkDense>(support.get_rules()); // Getting the full support support.calc(); // Checking change statistics // - Triangle: 0-1-2-0 // - Isolates: 3 // - Extra dyad: 0-2 // 0 1 1 0 // 0 0 1 0 // 1 0 0 0 // 0 0 0 0 net.clear(); net(0, 1) = 1; net(0, 2) = 1; net(1, 2) = 1; net(2, 0) = 1; // Preparing the model ----------------------------------------------------- NetModel<NetworkDense> model2; model2.set_counters(support.get_counters()); model2.set_rules(support.get_rules()); model2.add_array(net); // This transformation reverses the order of the terms std::function<std::vector<double>(double *,unsigned int)> tfun = [] (double * dat, unsigned int k) { std::vector< double > v(k); for (auto i = 0u; i < k; ++i) v[k - i - 1] = (*(dat + i)); return v; }; // Same variables std::vector< std::string > newnames = { "New nodematch", "New odegree15", "New idegree15", "New density", "New ctriads", "New ttriads", "New ostar2", "New istar2", "New isolates", "New mutual", "New edges" }; model2.print(); auto loglik0 = model2.likelihood_total(p0, true); auto loglik1 = model2.likelihood_total(p1, true); model2.set_transform_model(tfun, newnames); auto loglik0_rev = model2.likelihood_total(p0_rev, true); auto loglik1_rev = model2.likelihood_total(p1_rev, true); model2.print(); #ifdef CATCH_CONFIG_MAIN REQUIRE(loglik0 == Approx(loglik0_rev).epsilon(0.00001)); REQUIRE(loglik1 == Approx(loglik1_rev).epsilon(0.00001)); #endif // Preparing the model Setting zeros and other mults ----------------------- NetModel<NetworkDense> model3; model3.set_counters(support.get_counters()); model3.set_rules(support.get_rules()); model3.add_array(net); // This transformation reverses the order of the terms std::function<std::vector<double>(double *,unsigned int)> tfun2 = [] (double * dat, unsigned int k) { // Removing the edge variable auto k_new = k - 1; std::vector< double > v(k_new); for (auto i = 0u; i < k_new; ++i) v[k_new - i - 1u] = (*(dat + i + 1u)); // Rescaling mutual v[9u] /= 1.25; return v; }; // Same variables std::vector< std::string > newnames2 = { "New nodematch", "New odegree15", "New idegree15", "New density", "New ctriads", "New ttriads", "New ostar2", "New istar2", "New isolates", "New mutual" }; model3.print(); // Updating the likelihoods to reveal the changes // - edges: 0 // - mutuals: /1.25 p0[0u] *= 0.0; p0[1u] /= 1.25; p1[0u] *= 0.0; p1[1u] /= 1.25; p0_rev.pop_back(); p1_rev.pop_back(); auto loglik0b = model3.likelihood_total(p0, true); auto loglik1b = model3.likelihood_total(p1, true); auto target = *model3.get_stats_target(); model3.set_transform_model(tfun2, newnames2); auto loglik0b_rev = model3.likelihood_total(p0_rev, true); auto loglik1b_rev = model3.likelihood_total(p1_rev, true); auto targetb = *model3.get_stats_target(); model3.print(); #ifdef CATCH_CONFIG_MAIN REQUIRE(loglik0b == Approx(loglik0b_rev).epsilon(0.00001)); REQUIRE(loglik1b == Approx(loglik1b_rev).epsilon(0.00001)); #endif }
29.60396
131
0.590635
[ "vector", "model" ]
ad1e7cf96e0a0b25fbd451cdd259774cebeeb024
17,351
cpp
C++
wpiutil/src/main/native/cpp/MemoryBuffer.cpp
carelesshippo/allwpilib
ab7ac4fbb97308473b4d6fc7f12b6e1a672f1471
[ "BSD-3-Clause" ]
null
null
null
wpiutil/src/main/native/cpp/MemoryBuffer.cpp
carelesshippo/allwpilib
ab7ac4fbb97308473b4d6fc7f12b6e1a672f1471
[ "BSD-3-Clause" ]
null
null
null
wpiutil/src/main/native/cpp/MemoryBuffer.cpp
carelesshippo/allwpilib
ab7ac4fbb97308473b4d6fc7f12b6e1a672f1471
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) FIRST and other WPILib contributors. // Open Source Software; you can modify and/or share it under the terms of // the WPILib BSD license file in the root directory of this project. //===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the MemoryBuffer interface. // //===----------------------------------------------------------------------===// #include "wpi/MemoryBuffer.h" #ifdef _MSC_VER // no matching operator delete #pragma warning(disable : 4291) #endif #ifdef _WIN32 #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <windows.h> // NOLINT(build/include_order) #endif #include <sys/stat.h> #include <sys/types.h> #ifdef _MSC_VER #include <io.h> #else #include <unistd.h> #endif #include <cassert> #include <cerrno> #include <cstring> #include <new> #include <system_error> #include "wpi/Errc.h" #include "wpi/Errno.h" #include "wpi/MappedFileRegion.h" #include "wpi/SmallVector.h" #include "wpi/SmallVectorMemoryBuffer.h" #include "wpi/fs.h" #ifdef _WIN32 #include "wpi/WindowsError.h" #endif using namespace wpi; //===----------------------------------------------------------------------===// // MemoryBuffer implementation itself. //===----------------------------------------------------------------------===// MemoryBuffer::~MemoryBuffer() {} /// init - Initialize this MemoryBuffer as a reference to externally allocated /// memory. void MemoryBuffer::Init(const uint8_t* bufStart, const uint8_t* bufEnd) { m_bufferStart = bufStart; m_bufferEnd = bufEnd; } //===----------------------------------------------------------------------===// // MemoryBufferMem implementation. //===----------------------------------------------------------------------===// /// CopyStringRef - Copies contents of a StringRef into a block of memory and /// null-terminates it. static void CopyStringView(uint8_t* memory, std::string_view data) { if (!data.empty()) { std::memcpy(memory, data.data(), data.size()); } memory[data.size()] = 0; // Null terminate string. } namespace { struct NamedBufferAlloc { std::string_view name; explicit NamedBufferAlloc(std::string_view name) : name(name) {} }; } // namespace void* operator new(size_t N, NamedBufferAlloc alloc) { uint8_t* mem = static_cast<uint8_t*>(operator new(N + alloc.name.size() + 1)); CopyStringView(mem + N, alloc.name); return mem; } namespace { /// MemoryBufferMem - Named MemoryBuffer pointing to a block of memory. template <typename MB> class MemoryBufferMem : public MB { public: explicit MemoryBufferMem(span<const uint8_t> inputData) { MemoryBuffer::Init(inputData.begin(), inputData.end()); } /// Disable sized deallocation for MemoryBufferMem, because it has /// tail-allocated data. void operator delete(void* p) { ::operator delete(p); } // NOLINT std::string_view GetBufferIdentifier() const override { // The name is stored after the class itself. return std::string_view(reinterpret_cast<const char*>(this + 1)); } MemoryBuffer::BufferKind GetBufferKind() const override { return MemoryBuffer::MemoryBuffer_Malloc; } }; } // namespace template <typename MB> static std::unique_ptr<MB> GetFileAux(std::string_view filename, std::error_code& ec, int64_t fileSize, uint64_t mapSize, uint64_t offset); std::unique_ptr<MemoryBuffer> MemoryBuffer::GetMemBuffer( span<const uint8_t> inputData, std::string_view bufferName) { auto* ret = new (NamedBufferAlloc(bufferName)) MemoryBufferMem<MemoryBuffer>(inputData); return std::unique_ptr<MemoryBuffer>(ret); } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetMemBuffer(MemoryBufferRef ref) { return std::unique_ptr<MemoryBuffer>( GetMemBuffer(ref.GetBuffer(), ref.GetBufferIdentifier())); } static std::unique_ptr<WritableMemoryBuffer> GetMemBufferCopyImpl( span<const uint8_t> inputData, std::string_view bufferName, std::error_code& ec) { auto buf = WritableMemoryBuffer::GetNewUninitMemBuffer(inputData.size(), bufferName); if (!buf) { ec = make_error_code(errc::not_enough_memory); return nullptr; } std::memcpy(buf->begin(), inputData.data(), inputData.size()); return buf; } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetMemBufferCopy( span<const uint8_t> inputData, std::string_view bufferName) { std::error_code ec; return GetMemBufferCopyImpl(inputData, bufferName, ec); } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetFileSlice( std::string_view filePath, std::error_code& ec, uint64_t mapSize, uint64_t offset) { return GetFileAux<MemoryBuffer>(filePath, ec, -1, mapSize, offset); } //===----------------------------------------------------------------------===// // MemoryBuffer::getFile implementation. //===----------------------------------------------------------------------===// namespace { template <typename MB> constexpr auto kMapMode = MappedFileRegion::kReadOnly; template <> constexpr auto kMapMode<MemoryBuffer> = MappedFileRegion::kReadOnly; template <> constexpr auto kMapMode<WritableMemoryBuffer> = MappedFileRegion::kPriv; template <> constexpr auto kMapMode<WriteThroughMemoryBuffer> = MappedFileRegion::kReadWrite; /// Memory maps a file descriptor using MappedFileRegion. /// /// This handles converting the offset into a legal offset on the platform. template <typename MB> class MemoryBufferMMapFile : public MB { MappedFileRegion m_mfr; static uint64_t getLegalMapOffset(uint64_t offset) { return offset & ~(MappedFileRegion::GetAlignment() - 1); } static uint64_t getLegalMapSize(uint64_t len, uint64_t offset) { return len + (offset - getLegalMapOffset(offset)); } const uint8_t* getStart(uint64_t len, uint64_t offset) { return m_mfr.const_data() + (offset - getLegalMapOffset(offset)); } public: MemoryBufferMMapFile(fs::file_t f, uint64_t len, uint64_t offset, std::error_code& ec) : m_mfr(f, getLegalMapSize(len, offset), getLegalMapOffset(offset), kMapMode<MB>, ec) { if (!ec) { const uint8_t* Start = getStart(len, offset); MemoryBuffer::Init(Start, Start + len); } } /// Disable sized deallocation for MemoryBufferMMapFile, because it has /// tail-allocated data. void operator delete(void* p) { ::operator delete(p); } // NOLINT std::string_view GetBufferIdentifier() const override { // The name is stored after the class itself. return std::string_view(reinterpret_cast<const char*>(this + 1)); } MemoryBuffer::BufferKind GetBufferKind() const override { return MemoryBuffer::MemoryBuffer_MMap; } }; } // namespace static std::unique_ptr<WritableMemoryBuffer> GetMemoryBufferForStream( fs::file_t f, std::string_view bufferName, std::error_code& ec) { constexpr size_t ChunkSize = 4096 * 4; SmallVector<uint8_t, ChunkSize> buffer; #ifdef _WIN32 DWORD readBytes; #else ssize_t readBytes; #endif // Read into Buffer until we hit EOF. do { buffer.reserve(buffer.size() + ChunkSize); #ifdef _WIN32 if (!ReadFile(f, buffer.end(), ChunkSize, &readBytes, nullptr)) { ec = mapWindowsError(GetLastError()); return nullptr; } #else readBytes = sys::RetryAfterSignal(-1, ::read, f, buffer.end(), ChunkSize); if (readBytes == -1) { ec = std::error_code(errno, std::generic_category()); return nullptr; } #endif buffer.set_size(buffer.size() + readBytes); } while (readBytes != 0); return GetMemBufferCopyImpl(buffer, bufferName, ec); } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetFile(std::string_view filename, std::error_code& ec, int64_t fileSize) { return GetFileAux<MemoryBuffer>(filename, ec, fileSize, fileSize, 0); } template <typename MB> static std::unique_ptr<MB> GetOpenFileImpl(fs::file_t f, std::string_view filename, std::error_code& ec, uint64_t fileSize, uint64_t mapSize, int64_t offset); template <typename MB> static std::unique_ptr<MB> GetFileAux(std::string_view filename, std::error_code& ec, int64_t fileSize, uint64_t mapSize, uint64_t offset) { fs::file_t F = fs::OpenFileForRead(filename, ec, fs::OF_None); if (ec) { return nullptr; } auto Ret = GetOpenFileImpl<MB>(F, filename, ec, fileSize, mapSize, offset); fs::CloseFile(F); return Ret; } std::unique_ptr<WritableMemoryBuffer> WritableMemoryBuffer::GetFile( std::string_view filename, std::error_code& ec, int64_t fileSize) { return GetFileAux<WritableMemoryBuffer>(filename, ec, fileSize, fileSize, 0); } std::unique_ptr<WritableMemoryBuffer> WritableMemoryBuffer::GetFileSlice( std::string_view filename, std::error_code& ec, uint64_t mapSize, uint64_t offset) { return GetFileAux<WritableMemoryBuffer>(filename, ec, -1, mapSize, offset); } std::unique_ptr<WritableMemoryBuffer> WritableMemoryBuffer::GetNewUninitMemBuffer(size_t size, std::string_view bufferName) { using MemBuffer = MemoryBufferMem<WritableMemoryBuffer>; // Allocate space for the MemoryBuffer, the data and the name. It is important // that MemoryBuffer and data are aligned so PointerIntPair works with them. // TODO: Is 16-byte alignment enough? We copy small object files with large // alignment expectations into this buffer. size_t alignedStringLen = alignTo(sizeof(MemBuffer) + bufferName.size() + 1, 16); size_t realLen = alignedStringLen + size + 1; uint8_t* mem = static_cast<uint8_t*>(operator new(realLen, std::nothrow)); if (!mem) { return nullptr; } // The name is stored after the class itself. CopyStringView(mem + sizeof(MemBuffer), bufferName); // The buffer begins after the name and must be aligned. uint8_t* buf = mem + alignedStringLen; buf[size] = 0; // Null terminate buffer. auto* ret = new (mem) MemBuffer({buf, size}); return std::unique_ptr<WritableMemoryBuffer>(ret); } std::unique_ptr<WritableMemoryBuffer> WritableMemoryBuffer::GetNewMemBuffer( size_t size, std::string_view bufferName) { auto sb = WritableMemoryBuffer::GetNewUninitMemBuffer(size, bufferName); if (!sb) { return nullptr; } std::memset(sb->begin(), 0, size); return sb; } static std::unique_ptr<WriteThroughMemoryBuffer> GetReadWriteFile( std::string_view filename, std::error_code& ec, uint64_t fileSize, uint64_t mapSize, uint64_t offset) { fs::file_t f = fs::OpenFileForReadWrite(filename, ec, fs::CD_OpenExisting, fs::OF_None); if (ec) { return nullptr; } // Default is to map the full file. if (mapSize == uint64_t(-1)) { // If we don't know the file size, use fstat to find out. fstat on an open // file descriptor is cheaper than stat on a random path. if (fileSize == uint64_t(-1)) { #ifdef _WIN32 // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't mmap it, so error out. if (GetFileType(f) != FILE_TYPE_DISK) { ec = std::error_code(errno, std::generic_category()); return nullptr; } LARGE_INTEGER fileSizeWin; if (!GetFileSizeEx(f, &fileSizeWin)) { ec = wpi::mapWindowsError(GetLastError()); return nullptr; } fileSize = fileSizeWin.QuadPart; #else struct stat status; if (fstat(f, &status) < 0) { ec = std::error_code(errno, std::generic_category()); return nullptr; } // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't mmap it, so error out. if (status.st_mode != S_IFREG && status.st_mode != S_IFBLK) { ec = make_error_code(errc::invalid_argument); return nullptr; } fileSize = status.st_size; #endif } mapSize = fileSize; } std::unique_ptr<WriteThroughMemoryBuffer> result(new (NamedBufferAlloc( filename)) MemoryBufferMMapFile<WriteThroughMemoryBuffer>(f, mapSize, offset, ec)); if (ec) { return nullptr; } return result; } std::unique_ptr<WriteThroughMemoryBuffer> WriteThroughMemoryBuffer::GetFile( std::string_view filename, std::error_code& ec, int64_t fileSize) { return GetReadWriteFile(filename, ec, fileSize, fileSize, 0); } /// Map a subrange of the specified file as a WritableMemoryBuffer. std::unique_ptr<WriteThroughMemoryBuffer> WriteThroughMemoryBuffer::GetFileSlice(std::string_view filename, std::error_code& ec, uint64_t mapSize, uint64_t offset) { return GetReadWriteFile(filename, ec, -1, mapSize, offset); } template <typename MB> static std::unique_ptr<MB> GetOpenFileImpl(fs::file_t f, std::string_view filename, std::error_code& ec, uint64_t fileSize, uint64_t mapSize, int64_t offset) { // Default is to map the full file. if (mapSize == uint64_t(-1)) { // If we don't know the file size, use fstat to find out. fstat on an open // file descriptor is cheaper than stat on a random path. if (fileSize == uint64_t(-1)) { #ifdef _WIN32 // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't trust the size. Create the memory // buffer by copying off the stream. LARGE_INTEGER fileSizeWin; if (GetFileType(f) != FILE_TYPE_DISK || !GetFileSizeEx(f, &fileSizeWin)) { return GetMemoryBufferForStream(f, filename, ec); } fileSize = fileSizeWin.QuadPart; #else struct stat status; if (fstat(f, &status) < 0) { ec = std::error_code(errno, std::generic_category()); return nullptr; } // If this not a file or a block device (e.g. it's a named pipe // or character device), we can't trust the size. Create the memory // buffer by copying off the stream. if (status.st_mode != S_IFREG && status.st_mode != S_IFBLK) { return GetMemoryBufferForStream(f, filename, ec); } fileSize = status.st_size; #endif } mapSize = fileSize; } // Don't use mmap for small files if (mapSize >= 4 * 4096) { std::unique_ptr<MB> result(new (NamedBufferAlloc( filename)) MemoryBufferMMapFile<MB>(f, mapSize, offset, ec)); if (!ec) { return result; } } auto buf = WritableMemoryBuffer::GetNewUninitMemBuffer(mapSize, filename); if (!buf) { // Failed to create a buffer. The only way it can fail is if // new(std::nothrow) returns 0. ec = make_error_code(errc::not_enough_memory); return nullptr; } uint8_t* bufPtr = buf.get()->begin(); size_t bytesLeft = mapSize; while (bytesLeft) { #ifdef _WIN32 LARGE_INTEGER offsetWin; offsetWin.QuadPart = offset; DWORD numRead; if (!SetFilePointerEx(f, offsetWin, nullptr, FILE_BEGIN) || !ReadFile(f, bufPtr, bytesLeft, &numRead, nullptr)) { ec = mapWindowsError(GetLastError()); return nullptr; } // TODO #else ssize_t numRead = sys::RetryAfterSignal(-1, ::pread, f, bufPtr, bytesLeft, mapSize - bytesLeft + offset); if (numRead == -1) { // Error while reading. ec = std::error_code(errno, std::generic_category()); return nullptr; } #endif if (numRead == 0) { std::memset(bufPtr, 0, bytesLeft); // zero-initialize rest of the buffer. break; } bytesLeft -= numRead; bufPtr += numRead; } return buf; } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetOpenFile( fs::file_t f, std::string_view filename, std::error_code& ec, uint64_t fileSize) { return GetOpenFileImpl<MemoryBuffer>(f, filename, ec, fileSize, fileSize, 0); } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetOpenFileSlice( fs::file_t f, std::string_view filename, std::error_code& ec, uint64_t mapSize, int64_t offset) { assert(mapSize != uint64_t(-1)); return GetOpenFileImpl<MemoryBuffer>(f, filename, ec, -1, mapSize, offset); } std::unique_ptr<MemoryBuffer> MemoryBuffer::GetFileAsStream( std::string_view filename, std::error_code& ec) { fs::file_t f = fs::OpenFileForRead(filename, ec, fs::OF_None); if (ec) { return nullptr; } std::unique_ptr<MemoryBuffer> ret = GetMemoryBufferForStream(f, filename, ec); fs::CloseFile(f); return ret; } MemoryBufferRef MemoryBuffer::GetMemBufferRef() const { return MemoryBufferRef(GetBuffer(), GetBufferIdentifier()); } SmallVectorMemoryBuffer::~SmallVectorMemoryBuffer() {}
33.175908
80
0.642557
[ "object" ]
ad1f2fcc4441f138726f67d6f0e8e049302e5962
8,731
cc
C++
content/browser/geolocation/geolocation_dispatcher_host.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2020-01-25T10:18:18.000Z
2021-01-23T15:29:56.000Z
content/browser/geolocation/geolocation_dispatcher_host.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/browser/geolocation/geolocation_dispatcher_host.cc
justremotephone/android_external_chromium_org
246856e61da7acf5494076c74198f2aea894a721
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2020-11-04T07:24:13.000Z
2020-11-04T07:24:13.000Z
// Copyright (c) 2012 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 "content/browser/geolocation/geolocation_dispatcher_host.h" #include <utility> #include "base/bind.h" #include "base/metrics/histogram.h" #include "content/browser/frame_host/render_frame_host_impl.h" #include "content/browser/renderer_host/render_message_filter.h" #include "content/browser/renderer_host/render_process_host_impl.h" #include "content/browser/renderer_host/render_view_host_impl.h" #include "content/browser/web_contents/web_contents_impl.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/content_browser_client.h" #include "content/public/common/geoposition.h" #include "content/common/geolocation_messages.h" namespace content { namespace { // Geoposition error codes for reporting in UMA. enum GeopositionErrorCode { // NOTE: Do not renumber these as that would confuse interpretation of // previously logged data. When making changes, also update the enum list // in tools/metrics/histograms/histograms.xml to keep it in sync. // There was no error. GEOPOSITION_ERROR_CODE_NONE = 0, // User denied use of geolocation. GEOPOSITION_ERROR_CODE_PERMISSION_DENIED = 1, // Geoposition could not be determined. GEOPOSITION_ERROR_CODE_POSITION_UNAVAILABLE = 2, // Timeout. GEOPOSITION_ERROR_CODE_TIMEOUT = 3, // NOTE: Add entries only immediately above this line. GEOPOSITION_ERROR_CODE_COUNT = 4 }; void RecordGeopositionErrorCode(Geoposition::ErrorCode error_code) { GeopositionErrorCode code = GEOPOSITION_ERROR_CODE_NONE; switch (error_code) { case Geoposition::ERROR_CODE_NONE: code = GEOPOSITION_ERROR_CODE_NONE; break; case Geoposition::ERROR_CODE_PERMISSION_DENIED: code = GEOPOSITION_ERROR_CODE_PERMISSION_DENIED; break; case Geoposition::ERROR_CODE_POSITION_UNAVAILABLE: code = GEOPOSITION_ERROR_CODE_POSITION_UNAVAILABLE; break; case Geoposition::ERROR_CODE_TIMEOUT: code = GEOPOSITION_ERROR_CODE_TIMEOUT; break; } UMA_HISTOGRAM_ENUMERATION("Geolocation.LocationUpdate.ErrorCode", code, GEOPOSITION_ERROR_CODE_COUNT); } } // namespace GeolocationDispatcherHost::PendingPermission::PendingPermission( int render_frame_id, int render_process_id, int bridge_id) : render_frame_id(render_frame_id), render_process_id(render_process_id), bridge_id(bridge_id) { } GeolocationDispatcherHost::PendingPermission::~PendingPermission() { } GeolocationDispatcherHost::GeolocationDispatcherHost( WebContents* web_contents) : WebContentsObserver(web_contents), paused_(false), weak_factory_(this) { // This is initialized by WebContentsImpl. Do not add any non-trivial // initialization here, defer to OnStartUpdating which is triggered whenever // a javascript geolocation object is actually initialized. } GeolocationDispatcherHost::~GeolocationDispatcherHost() { } void GeolocationDispatcherHost::RenderFrameDeleted( RenderFrameHost* render_frame_host) { OnStopUpdating(render_frame_host); } void GeolocationDispatcherHost::RenderViewHostChanged( RenderViewHost* old_host, RenderViewHost* new_host) { updating_frames_.clear(); paused_ = false; geolocation_subscription_.reset(); } bool GeolocationDispatcherHost::OnMessageReceived( const IPC::Message& msg, RenderFrameHost* render_frame_host) { bool handled = true; IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(GeolocationDispatcherHost, msg, render_frame_host) IPC_MESSAGE_HANDLER(GeolocationHostMsg_RequestPermission, OnRequestPermission) IPC_MESSAGE_HANDLER(GeolocationHostMsg_CancelPermissionRequest, OnCancelPermissionRequest) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StartUpdating, OnStartUpdating) IPC_MESSAGE_HANDLER(GeolocationHostMsg_StopUpdating, OnStopUpdating) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void GeolocationDispatcherHost::OnLocationUpdate( const Geoposition& geoposition) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); RecordGeopositionErrorCode(geoposition.error_code); if (paused_) return; for (std::map<RenderFrameHost*, bool>::iterator i = updating_frames_.begin(); i != updating_frames_.end(); ++i) { i->first->Send(new GeolocationMsg_PositionUpdated( i->first->GetRoutingID(), geoposition)); } } void GeolocationDispatcherHost::OnRequestPermission( RenderFrameHost* render_frame_host, int bridge_id, const GURL& requesting_frame, bool user_gesture) { int render_process_id = render_frame_host->GetProcess()->GetID(); int render_frame_id = render_frame_host->GetRoutingID(); PendingPermission pending_permission( render_frame_id, render_process_id, bridge_id); pending_permissions_.push_back(pending_permission); GetContentClient()->browser()->RequestGeolocationPermission( web_contents(), bridge_id, requesting_frame, user_gesture, base::Bind(&GeolocationDispatcherHost::SendGeolocationPermissionResponse, weak_factory_.GetWeakPtr(), render_process_id, render_frame_id, bridge_id), &pending_permissions_.back().cancel); } void GeolocationDispatcherHost::OnCancelPermissionRequest( RenderFrameHost* render_frame_host, int bridge_id, const GURL& requesting_frame) { int render_process_id = render_frame_host->GetProcess()->GetID(); int render_frame_id = render_frame_host->GetRoutingID(); for (size_t i = 0; i < pending_permissions_.size(); ++i) { if (pending_permissions_[i].render_process_id == render_process_id && pending_permissions_[i].render_frame_id == render_frame_id && pending_permissions_[i].bridge_id == bridge_id) { if (!pending_permissions_[i].cancel.is_null()) pending_permissions_[i].cancel.Run(); pending_permissions_.erase(pending_permissions_.begin() + i); return; } } } void GeolocationDispatcherHost::OnStartUpdating( RenderFrameHost* render_frame_host, const GURL& requesting_frame, bool enable_high_accuracy) { // StartUpdating() can be invoked as a result of high-accuracy mode // being enabled / disabled. No need to record the dispatcher again. UMA_HISTOGRAM_BOOLEAN( "Geolocation.GeolocationDispatcherHostImpl.EnableHighAccuracy", enable_high_accuracy); updating_frames_[render_frame_host] = enable_high_accuracy; RefreshGeolocationOptions(); } void GeolocationDispatcherHost::OnStopUpdating( RenderFrameHost* render_frame_host) { updating_frames_.erase(render_frame_host); RefreshGeolocationOptions(); } void GeolocationDispatcherHost::PauseOrResume(bool should_pause) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); paused_ = should_pause; RefreshGeolocationOptions(); } void GeolocationDispatcherHost::RefreshGeolocationOptions() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (updating_frames_.empty() || paused_) { geolocation_subscription_.reset(); return; } bool high_accuracy = false; for (std::map<RenderFrameHost*, bool>::iterator i = updating_frames_.begin(); i != updating_frames_.end(); ++i) { if (i->second) { high_accuracy = true; break; } } geolocation_subscription_ = GeolocationProvider::GetInstance()-> AddLocationUpdateCallback( base::Bind(&GeolocationDispatcherHost::OnLocationUpdate, base::Unretained(this)), high_accuracy); } void GeolocationDispatcherHost::SendGeolocationPermissionResponse( int render_process_id, int render_frame_id, int bridge_id, bool allowed) { for (size_t i = 0; i < pending_permissions_.size(); ++i) { if (pending_permissions_[i].render_process_id == render_process_id && pending_permissions_[i].render_frame_id == render_frame_id && pending_permissions_[i].bridge_id == bridge_id) { RenderFrameHost* render_frame_host = RenderFrameHost::FromID(render_process_id, render_frame_id); if (render_frame_host) { render_frame_host->Send(new GeolocationMsg_PermissionSet( render_frame_id, bridge_id, allowed)); } if (allowed) { GeolocationProviderImpl::GetInstance()-> UserDidOptIntoLocationServices(); } pending_permissions_.erase(pending_permissions_.begin() + i); return; } } NOTREACHED(); } } // namespace content
33.841085
79
0.741725
[ "object" ]
ad28cc316c623da2b7bf832ed60caee4581b40a3
1,899
cpp
C++
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Contracts/RestrictedNodeContract.cpp
cypherdotXd/o3de
bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676
[ "Apache-2.0", "MIT" ]
11
2021-07-08T09:58:26.000Z
2022-03-17T17:59:26.000Z
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Contracts/RestrictedNodeContract.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
29
2021-07-06T19:33:52.000Z
2022-03-22T10:27:49.000Z
Gems/ScriptCanvas/Code/Include/ScriptCanvas/Core/Contracts/RestrictedNodeContract.cpp
RoddieKieley/o3de
e804fd2a4241b039a42d9fa54eaae17dc94a7a92
[ "Apache-2.0", "MIT" ]
4
2021-07-06T19:24:43.000Z
2022-03-31T12:42:27.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include "RestrictedNodeContract.h" #include <ScriptCanvas/Core/ContractBus.h> #include <ScriptCanvas/Core/GraphBus.h> #include <ScriptCanvas/Core/NodeBus.h> #include <ScriptCanvas/Core/Endpoint.h> #include <ScriptCanvas/Core/Slot.h> #include <ScriptCanvas/Core/Node.h> #include <ScriptCanvas/Core/Graph.h> namespace ScriptCanvas { RestrictedNodeContract::RestrictedNodeContract(AZ::EntityId nodeId) : m_nodeId{ nodeId } {} void RestrictedNodeContract::Reflect(AZ::ReflectContext* reflection) { if (auto serializeContext = azrtti_cast<AZ::SerializeContext*>(reflection); serializeContext != nullptr) { serializeContext->Class<RestrictedNodeContract, Contract>() ->Version(0) ->Field("m_nodeId", &RestrictedNodeContract::m_nodeId) ; } } void RestrictedNodeContract::SetNodeId(AZ::EntityId nodeId) { m_nodeId = nodeId; } AZ::Outcome<void, AZStd::string> RestrictedNodeContract::OnEvaluate(const Slot& sourceSlot, const Slot& targetSlot) const { // Validate that the Node which contains the target slot matches the stored nodeId in order validate // the restricted node contract AZ::Outcome<void, AZStd::string> outcome(AZStd::string::format("Connection cannot be created between source slot" R"( "%s" and target slot "%s". Connections to source slot can be only be made from a node with node ID)" R"([%s])", sourceSlot.GetName().c_str(), targetSlot.GetName().c_str(), m_nodeId.ToString().c_str())); return targetSlot.GetNodeId() == m_nodeId ? AZ::Success() : outcome; } }
37.98
125
0.682464
[ "3d" ]
ad2bf48e97cb9040f59c249ebd5fc43f753c13ea
2,937
cpp
C++
codeforces/C - Spy Syndrome 2/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/C - Spy Syndrome 2/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/C - Spy Syndrome 2/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: May/04/2018 19:11 * solution_verdict: Accepted language: GNU C++11 * run_time: 202 ms memory_used: 51900 KB * problem: https://codeforces.com/contest/633/problem/C ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; const int N=1e4+1; int length,n,sz,last,occur[N+N],q,f; string s,sss[10*N]; map<string,int>mp; vector<int>v_len[N+N],tre[N+N],pos[N],yes; struct automata { int len,link,id,clone,next[26]; }st[N+N]; void insrt(int c,int idx) { int now=++sz; st[now].len=st[last].len+1; st[now].id=idx; occur[now]=1; int p,q,cl; for(p=last;p!=-1&&!st[p].next[c];p=st[p].link) st[p].next[c]=now; if(p==-1) st[now].link=0; else { q=st[p].next[c]; if(st[p].len+1==st[q].len) st[now].link=q; else { cl=++sz; st[cl].len=st[p].len+1; st[cl].link=st[q].link; st[cl].id=st[q].id; st[cl].clone=1; memcpy(st[cl].next,st[q].next,sizeof(st[cl].next)); for( ;p!=-1&&st[p].next[c]==q;p=st[p].link) st[p].next[c]=cl; st[q].link=st[now].link=cl; } } last=now; } void count_occurrence(void) { for(int i=1;i<=sz;i++) v_len[st[i].len].push_back(i); for(int i=length;i>=1;i--) { for(int j=0;j<v_len[i].size();j++) { int tmp=v_len[i][j]; occur[st[tmp].link]+=occur[tmp]; } } } void make_suffixtree(void) { for(int i=1;i<=sz;i++) tre[st[i].link].push_back(i); } void find_path(int now,int id,int ssz) { pos[st[now].id-ssz+1].push_back(id); for(auto x:tre[now]) find_path(x,id,ssz); } void position_of_occurrence(string s,int id) { int now=0; for(auto x:s) { int c=x-'a'; if(!st[now].next[c])return ; now=st[now].next[c]; } find_path(now,id,s.size()); } void print_path(int now) { if(now>n) { f=1; return ; } for(auto x:pos[now]) { print_path(now+sss[x].size()); if(f==1) { yes.push_back(x); return ; } } } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin>>n; cin>>s; length=s.size(); st[0].link=-1; for(int i=0;i<length;i++)insrt(s[i]-'a',i+1); count_occurrence(); make_suffixtree(); cin>>q; for(int ii=1;ii<=q;ii++) { cin>>s; sss[ii]=s; reverse(s.begin(),s.end()); for(int i=0;i<s.size();i++) { if(s[i]>='A'&&s[i]<='Z') s[i]=s[i]-'A'+'a'; } if(mp[s])continue; mp[s]=1; position_of_occurrence(s,ii); } print_path(1); for(int i=yes.size()-1;i>=0;i--) cout<<sss[yes[i]]<<" "; cout<<endl; return 0; }
22.082707
111
0.477698
[ "vector" ]
ad2c378889cd0e9f81f6198620220caf3efa47e8
3,082
cpp
C++
Filter_PD/PD/Safe_PD/v_Header.cpp
TomerEven/Pocket_Dictionary
29f906855f5e52eec61d00cb6e8fa0fb5e90a8e4
[ "Apache-2.0" ]
2
2019-12-10T03:41:02.000Z
2021-11-14T12:30:36.000Z
Filter_PD/PD/Safe_PD/v_Header.cpp
TomerEven/Pocket_Dictionary
29f906855f5e52eec61d00cb6e8fa0fb5e90a8e4
[ "Apache-2.0" ]
null
null
null
Filter_PD/PD/Safe_PD/v_Header.cpp
TomerEven/Pocket_Dictionary
29f906855f5e52eec61d00cb6e8fa0fb5e90a8e4
[ "Apache-2.0" ]
2
2019-12-10T03:41:07.000Z
2020-06-02T16:57:31.000Z
// // Created by tomer on 10/29/19. // #include "v_Header.h" v_Header::v_Header(size_t m, size_t f, size_t l) : header(m, f, l), const_header() { size_t number_of_bits = ((m + f) << 1ULL) + 1; if (HEADER_BLOCK_SIZE != (8 * sizeof(HEADER_BLOCK_TYPE))) { assert(false); } this->vec.resize(number_of_bits); } bool v_Header::lookup(uint_fast16_t quotient, size_t *start_index, size_t *end_index) { validate_get_interval(quotient); header.get_quotient_start_and_end_index(quotient, start_index, end_index); return *start_index != *end_index; } void v_Header::insert(uint_fast16_t quotient, size_t *start_index, size_t *end_index) { validate_get_interval(quotient); vector_insert(quotient); header.insert(quotient, start_index, end_index); const_header.insert(quotient, start_index, end_index); validate_get_interval(quotient); } void v_Header::remove(uint_fast16_t quotient, size_t *start_index, size_t *end_index) { validate_get_interval(quotient); vector_remove(quotient); header.remove(quotient, start_index, end_index); const_header.remove(quotient, start_index, end_index); validate_get_interval(quotient); } void v_Header::vector_get_interval(size_t quotient, size_t *start_index, size_t *end_index) { size_t zero_counter = -1, continue_from_index = 0; for (size_t i = 0; i < vec.size(); ++i) { if (zero_counter == quotient - 1) { *start_index = i; continue_from_index = i; break; } if (vec[i] == 0) zero_counter++; } for (size_t i = continue_from_index; i < vec.size(); ++i) { if (vec[i] == 0) { *end_index = i; return; } } assert(false); } void v_Header::vector_insert(size_t quotient) { size_t a = -1, b = -1; this->vector_get_interval(quotient, &a, &b); vec.insert(vec.begin() + a, true); vec.pop_back(); } void v_Header::vector_remove(uint_fast16_t quotient) { size_t a = -1, b = -1; this->vector_get_interval(quotient, &a, &b); assert(a < b); vec.erase(vec.begin() + a); vec.push_back(false); } void v_Header::validate_get_interval(size_t quotient) { size_t s1 = -1, e1 = -1, s2 = -2, e2 = -2, s3 = -3, e3 = -3; vector_get_interval(quotient, &s1, &e1); get_interval_attempt(header.get_h(), header.get_size(), quotient, &s2, &e2); const_header.get_interval(quotient, &s3, &e3); bool cond = (s1 == s2 and s1 == s3) && (e1 == e2 and e1 == e3); if (not cond) { cout << s1 << ", " << e1 << endl; cout << s2 << ", " << e2 << endl; cout << s3 << ", " << e3 << endl; cout << "header as word is: "; header.print_as_word(); cout << "vector as word is: "; print_bit_vector_as_words(&vec); cout << "const_header is: "; const_header.print(); } assert(s3 == s1 and s2 == s1); assert(e3 == e1 and e2 == e1); } void v_Header::print() { header.print(); const_header.print(); print_bit_vector_as_words(&vec); }
30.215686
93
0.615185
[ "vector" ]
ad32e6b6bb6772831dcfff1062479a091bd83862
14,465
cpp
C++
lexical.cpp
Drivit/Mini-C
65cc78676055e25dfbdf0c706006615e23d9b79a
[ "MIT" ]
1
2022-03-01T09:31:00.000Z
2022-03-01T09:31:00.000Z
lexical.cpp
Drivit/Mini-C
65cc78676055e25dfbdf0c706006615e23d9b79a
[ "MIT" ]
null
null
null
lexical.cpp
Drivit/Mini-C
65cc78676055e25dfbdf0c706006615e23d9b79a
[ "MIT" ]
null
null
null
#include "lexical.h" enum { Q0, Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q17, Q18, Q19, Q20, Q21, Q22, Q23, Q24, Q25 }; int transitions[27][21] = { { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q1, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q18, Q17, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q19, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q20, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q21, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q22, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, {Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q17, Q0, Q17, Q17, Q17}, {Q18, Q18, Q18, Q18, Q23, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18, Q18}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q0, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q0, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q0, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q0, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q24, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0}, { Q1, Q2, Q3, Q4, Q5, Q6, Q7, Q8, Q9, Q10, Q11, Q12, Q13, Q14, Q15, Q16, Q0, Q0, Q0, Q25, Q0} }; int outputs[27][21] = { {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 19}, {-1, -1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, { 1, -1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}, { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3}, { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4}, { 5, 5, 5, 5, -1, -1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5}, { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6}, { 7, 7, 7, 7, 7, 7, 7, 7, 7, -1, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7}, { 8, 8, 8, 8, 8, 8, 8, 8, 8, -1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8}, { 9, 9, 9, 9, 9, 9, 9, 9, 9, -1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9}, {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11}, {12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12}, {13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13}, {14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14}, {15, 15, 15, 15, 15, 15, 15, 15, 15, -1, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 21, -1, -1, -1}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 18, 22}, {23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 23, 19, 23}, {24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 20, 24}, {25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25}, {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}, {19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19} }; void Lexic::loadReservedWords() { reserved_.push_back("auto"); reserved_.push_back("double"); reserved_.push_back("const"); reserved_.push_back("float"); reserved_.push_back("int"); reserved_.push_back("short"); reserved_.push_back("struct"); reserved_.push_back("unsigned"); reserved_.push_back("break"); reserved_.push_back("continue"); reserved_.push_back("else"); reserved_.push_back("for"); reserved_.push_back("long"); reserved_.push_back("signed"); reserved_.push_back("switch"); reserved_.push_back("void"); reserved_.push_back("case"); reserved_.push_back("default"); reserved_.push_back("enum"); reserved_.push_back("goto"); reserved_.push_back("register"); reserved_.push_back("sizeof"); reserved_.push_back("typedef"); reserved_.push_back("volatile"); reserved_.push_back("char"); reserved_.push_back("do"); reserved_.push_back("extern"); reserved_.push_back("if"); reserved_.push_back("return"); reserved_.push_back("static"); reserved_.push_back("union"); reserved_.push_back("while"); } Lexic::Lexic(std::string file) { loadReservedWords(); std::fstream inFile(file.c_str(), std::ios::in); int outType = -1, type = -1, state = -1; std::string buffer = ""; char caracter = 0; state = Q0; if(inFile.is_open()) { while(!inFile.eof()) { inFile.read(&caracter, sizeof(caracter)); buffer += caracter; if(inFile.eof()) { buffer.erase(buffer.size() - 1); break; } } } else std::cerr << "Error al abrir el archivo" << std::endl; inFile.close(); Token temp; for (unsigned int i = 0; i <= buffer.size(); ++i) { type = returnType(buffer[i]); if(type != -1) { outType = outputs[state][type]; state = transitions[state][type]; if(outType != -1) { temp.setType(outType); if(temp.getType() != 20 && temp.getType() != 21) tokensList_.push_back(temp); temp.setType(-1); temp.setContent(""); } if(buffer[i] != ' ' && buffer[i] != '\t' && buffer[i] != '\n') temp.addContent(buffer[i]); } else { std::cerr << "ERROR. Existe un token no valido." << std::endl << std:: endl; exit(0); } } setReservedType(); createSymbolsTable(); } int Lexic::returnType(char caracter) { int type = -1; // type = -1: Error -> Error // type = 0: A - Z, a - z -> E1 // type = 1: 0 - 9 -> E2 // type = 2: + -> E3 // type = 3: - -> E4 // type = 4: * -> E5 // type = 5: / -> E6 // type = 6: % -> E7 // type = 7: < -> E8 // type = 8: > -> E9 // type = 9: = -> E10 // type = 10: ( -> E11 // type = 11: ) -> E12 // type = 12: { -> E13 // type = 13: } -> E14 // type = 14: , -> E15 // type = 15: ! -> E16 // type = 16: \s -> E17 // type = 17: \n -> E18 // type = 18: \t -> E19 // type = 19: ; -> E20 if((caracter >= 'a' && caracter <= 'z') || (caracter >= 'A' && caracter <= 'Z') || caracter == '_') type = 0; else if(caracter >= '0' && caracter <= '9') type = 1; else if(caracter == '+') type = 2; else if(caracter == '-') type = 3; else if(caracter == '*') type = 4; else if(caracter == '/') type = 5; else if(caracter == '%') type = 6; else if(caracter == '<') type = 7; else if(caracter == '>') type = 8; else if(caracter == '=') type = 9; else if(caracter == '(') type = 10; else if(caracter == ')') type = 11; else if(caracter == '{') type = 12; else if(caracter == '}') type = 13; else if(caracter == ',') type = 14; else if(caracter == '!') type = 15; else if(caracter == ' ') type = 16; else if(caracter == '\n') type = 17; else if(caracter == '\t') type = 18; else if(caracter == ';') type = 19; else if(caracter == '\0') type = 20; return type; } std::string Lexic::getTypeName(int type) { std::string name = ""; if(type == -1) name = "ERROR"; else if(type == 0) name = "IDENTIFIER"; else if(type == 1) name = "CONSTANT"; else if(type == 2) name = "PLUS_OPERATOR"; else if(type == 3) name = "MINUS_OPERATOR"; else if(type == 4) name = "MULTTIPLICATION_OPERATOR"; else if(type == 5) name = "DIVISION_OPERATOR"; else if(type == 6) name = "MOD_OPERATOR"; else if(type == 7) name = "LESS_THAN_OPERATOR"; else if(type == 8) name = "GREATER_THAN_OPERATOR"; else if(type == 9) name = "ASSIGMENT_OPERATOR"; else if(type == 10) name = "PARENTH_OPEN"; else if(type == 11) name = "PARENTH_CLOSE"; else if(type == 12) name = "KEY_OPEN"; else if(type == 13) name = "KEY_CLOSE"; else if(type == 14) name = "COMA"; else if(type == 15) name = "NEGATION"; else if(type == 16) name = "SPACE"; else if(type == 17) name = "NEW_LINE"; else if(type == 18) name = "TAB"; else if(type == 19) name = "SEMICOLON"; else if(type == 20) name = "BLOCK_COMMENT"; else if(type == 21) name = "COMMENT"; else if(type == 22) name = "LESS_THAN_OR_EQUAL_OPERATOR"; else if(type == 23) name = "GREATER_THAN_OR_EQUAL_OPERATOR"; else if(type == 24) name = "EQUAL_OPERATOR"; else if(type == 25) name = "NOT_EQUAL_OPERATOR"; else if(type == 26) name = "RESERVED_WORD"; return name; } void Lexic::setReservedType() { std::fstream outFile("salida.txt", std::ios::out); if(outFile.is_open()) { for(unsigned int i = 0; i < tokensList_.size(); i++) { outFile << tokensList_[i].getType() << std::endl; if(tokensList_[i].getType() == 0) { for(unsigned int x = 0; x < reserved_.size(); x++) { if(reserved_[x] == tokensList_[i].getContent()) tokensList_[i].setType(26); } } } } outFile.close(); } void Lexic::createSymbolsTable() { for (unsigned int i = 0; i < tokensList_.size(); i++) { if(tokensList_[i].getType() == 0) { if(symbolsList_.size() != 0) { bool exist = false; for (unsigned int j = 0; j < symbolsList_.size(); j++) { if(symbolsList_[j] == tokensList_[i].getContent()) exist = true; } if(!exist) symbolsList_.push_back(tokensList_[i].getContent()); } else symbolsList_.push_back(tokensList_[i].getContent()); } } } void Lexic::showSymbols() { if(!symbolsList_.empty()) { std::cout << "\n\nTabla de simbolos" << std::endl << std::endl; for(unsigned int i = 0; i < symbolsList_.size(); i++) if(i != symbolsList_.size() - 1) std::cout << symbolsList_[i] << std::endl; else std::cout << symbolsList_[i] << std::endl << std::endl; } else std::cerr << "No hay simbolos" << std::endl; } void Lexic::showTokens() { for(unsigned int i = 0; i < tokensList_.size(); i++) if(i != tokensList_.size() - 1) std::cout << i << ": " << getTypeName(tokensList_[i].getType()) << " -> " << tokensList_[i].getContent() << std::endl; else std::cout << i << ": " << getTypeName(tokensList_[i].getType()) << " -> " << tokensList_[i].getContent() << std::endl << std::endl; } std::vector<Token> Lexic::getTokensList() { return tokensList_; } std::vector<std::string> Lexic::getSymbolsList() { return symbolsList_; }
35.982587
144
0.435188
[ "vector" ]
ad334d3b69ee684111956153d31211f707e83ce5
15,096
cc
C++
instrumentation/cmplog-instructions-pass.cc
StarGazerM/AFLplusplus
15340b85e88c72176ef303950376234abca7ee6b
[ "Apache-2.0" ]
27
2022-03-01T01:09:03.000Z
2022-03-21T13:09:56.000Z
instrumentation/cmplog-instructions-pass.cc
StarGazerM/AFLplusplus
15340b85e88c72176ef303950376234abca7ee6b
[ "Apache-2.0" ]
1
2021-07-23T21:34:32.000Z
2021-07-23T21:34:32.000Z
instrumentation/cmplog-instructions-pass.cc
StarGazerM/AFLplusplus
15340b85e88c72176ef303950376234abca7ee6b
[ "Apache-2.0" ]
1
2022-03-01T23:56:34.000Z
2022-03-01T23:56:34.000Z
/* american fuzzy lop++ - LLVM CmpLog instrumentation -------------------------------------------------- Written by Andrea Fioraldi <andreafioraldi@gmail.com> Copyright 2015, 2016 Google Inc. All rights reserved. Copyright 2019-2020 AFLplusplus Project. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <iostream> #include <list> #include <string> #include <fstream> #include <sys/time.h> #include "llvm/Config/llvm-config.h" #include "llvm/ADT/Statistic.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/LegacyPassManager.h" #include "llvm/IR/Module.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include "llvm/Transforms/IPO/PassManagerBuilder.h" #include "llvm/Transforms/Utils/BasicBlockUtils.h" #include "llvm/Pass.h" #include "llvm/Analysis/ValueTracking.h" #if LLVM_VERSION_MAJOR > 3 || \ (LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR > 4) #include "llvm/IR/Verifier.h" #include "llvm/IR/DebugInfo.h" #else #include "llvm/Analysis/Verifier.h" #include "llvm/DebugInfo.h" #define nullptr 0 #endif #include <set> #include "afl-llvm-common.h" using namespace llvm; namespace { class CmpLogInstructions : public ModulePass { public: static char ID; CmpLogInstructions() : ModulePass(ID) { initInstrumentList(); } bool runOnModule(Module &M) override; #if LLVM_VERSION_MAJOR < 4 const char *getPassName() const override { #else StringRef getPassName() const override { #endif return "cmplog instructions"; } private: bool hookInstrs(Module &M); }; } // namespace char CmpLogInstructions::ID = 0; template <class Iterator> Iterator Unique(Iterator first, Iterator last) { while (first != last) { Iterator next(first); last = std::remove(++next, last, *first); first = next; } return last; } bool CmpLogInstructions::hookInstrs(Module &M) { std::vector<Instruction *> icomps; std::vector<SwitchInst *> switches; LLVMContext & C = M.getContext(); Type * VoidTy = Type::getVoidTy(C); IntegerType *Int8Ty = IntegerType::getInt8Ty(C); IntegerType *Int16Ty = IntegerType::getInt16Ty(C); IntegerType *Int32Ty = IntegerType::getInt32Ty(C); IntegerType *Int64Ty = IntegerType::getInt64Ty(C); IntegerType *Int128Ty = IntegerType::getInt128Ty(C); #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c1 = M.getOrInsertFunction("__cmplog_ins_hook1", VoidTy, Int8Ty, Int8Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookIns1 = cast<Function>(c1); #else FunctionCallee cmplogHookIns1 = c1; #endif #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c2 = M.getOrInsertFunction("__cmplog_ins_hook2", VoidTy, Int16Ty, Int16Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookIns2 = cast<Function>(c2); #else FunctionCallee cmplogHookIns2 = c2; #endif #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c4 = M.getOrInsertFunction("__cmplog_ins_hook4", VoidTy, Int32Ty, Int32Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookIns4 = cast<Function>(c4); #else FunctionCallee cmplogHookIns4 = c4; #endif #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c8 = M.getOrInsertFunction("__cmplog_ins_hook8", VoidTy, Int64Ty, Int64Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookIns8 = cast<Function>(c8); #else FunctionCallee cmplogHookIns8 = c8; #endif #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif c16 = M.getOrInsertFunction("__cmplog_ins_hook16", VoidTy, Int128Ty, Int128Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookIns16 = cast<Function>(c16); #else FunctionCallee cmplogHookIns16 = c16; #endif #if LLVM_VERSION_MAJOR < 9 Constant * #else FunctionCallee #endif cN = M.getOrInsertFunction("__cmplog_ins_hookN", VoidTy, Int128Ty, Int128Ty, Int8Ty, Int8Ty #if LLVM_VERSION_MAJOR < 5 , NULL #endif ); #if LLVM_VERSION_MAJOR < 9 Function *cmplogHookInsN = cast<Function>(cN); #else FunctionCallee cmplogHookInsN = cN; #endif /* iterate over all functions, bbs and instruction and add suitable calls */ for (auto &F : M) { if (!isInInstrumentList(&F)) continue; for (auto &BB : F) { for (auto &IN : BB) { CmpInst *selectcmpInst = nullptr; if ((selectcmpInst = dyn_cast<CmpInst>(&IN))) { icomps.push_back(selectcmpInst); } SwitchInst *switchInst = nullptr; if ((switchInst = dyn_cast<SwitchInst>(BB.getTerminator()))) { if (switchInst->getNumCases() > 1) { switches.push_back(switchInst); } } } } } // unique the collected switches switches.erase(Unique(switches.begin(), switches.end()), switches.end()); // Instrument switch values for cmplog if (switches.size()) { if (!be_quiet) errs() << "Hooking " << switches.size() << " switch instructions\n"; for (auto &SI : switches) { Value * Val = SI->getCondition(); unsigned int max_size = Val->getType()->getIntegerBitWidth(), cast_size; unsigned char do_cast = 0; if (!SI->getNumCases() || max_size < 16) { // if (!be_quiet) errs() << "skip trivial switch..\n"; continue; } if (max_size % 8) { max_size = (((max_size / 8) + 1) * 8); do_cast = 1; } IRBuilder<> IRB(SI->getParent()); IRB.SetInsertPoint(SI); if (max_size > 128) { if (!be_quiet) { fprintf(stderr, "Cannot handle this switch bit size: %u (truncating)\n", max_size); } max_size = 128; do_cast = 1; } // do we need to cast? switch (max_size) { case 8: case 16: case 32: case 64: case 128: cast_size = max_size; break; default: cast_size = 128; do_cast = 1; } Value *CompareTo = Val; if (do_cast) { CompareTo = IRB.CreateIntCast(CompareTo, IntegerType::get(C, cast_size), false); } for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i) { #if LLVM_VERSION_MAJOR < 5 ConstantInt *cint = i.getCaseValue(); #else ConstantInt *cint = i->getCaseValue(); #endif if (cint) { std::vector<Value *> args; args.push_back(CompareTo); Value *new_param = cint; if (do_cast) { new_param = IRB.CreateIntCast(cint, IntegerType::get(C, cast_size), false); } if (new_param) { args.push_back(new_param); ConstantInt *attribute = ConstantInt::get(Int8Ty, 1); args.push_back(attribute); if (cast_size != max_size) { ConstantInt *bitsize = ConstantInt::get(Int8Ty, (max_size / 8) - 1); args.push_back(bitsize); } switch (cast_size) { case 8: IRB.CreateCall(cmplogHookIns1, args); break; case 16: IRB.CreateCall(cmplogHookIns2, args); break; case 32: IRB.CreateCall(cmplogHookIns4, args); break; case 64: IRB.CreateCall(cmplogHookIns8, args); break; case 128: #ifdef WORD_SIZE_64 if (max_size == 128) { IRB.CreateCall(cmplogHookIns16, args); } else { IRB.CreateCall(cmplogHookInsN, args); } #endif break; default: break; } } } } } } if (icomps.size()) { // if (!be_quiet) errs() << "Hooking " << icomps.size() << // " cmp instructions\n"; for (auto &selectcmpInst : icomps) { IRBuilder<> IRB(selectcmpInst->getParent()); IRB.SetInsertPoint(selectcmpInst); Value *op0 = selectcmpInst->getOperand(0); Value *op1 = selectcmpInst->getOperand(1); IntegerType * intTyOp0 = NULL; IntegerType * intTyOp1 = NULL; unsigned max_size = 0, cast_size = 0; unsigned char attr = 0; std::vector<Value *> args; CmpInst *cmpInst = dyn_cast<CmpInst>(selectcmpInst); if (!cmpInst) { continue; } switch (cmpInst->getPredicate()) { case CmpInst::ICMP_NE: case CmpInst::FCMP_UNE: case CmpInst::FCMP_ONE: break; case CmpInst::ICMP_EQ: case CmpInst::FCMP_UEQ: case CmpInst::FCMP_OEQ: attr += 1; break; case CmpInst::ICMP_UGT: case CmpInst::ICMP_SGT: case CmpInst::FCMP_OGT: case CmpInst::FCMP_UGT: attr += 2; break; case CmpInst::ICMP_UGE: case CmpInst::ICMP_SGE: case CmpInst::FCMP_OGE: case CmpInst::FCMP_UGE: attr += 3; break; case CmpInst::ICMP_ULT: case CmpInst::ICMP_SLT: case CmpInst::FCMP_OLT: case CmpInst::FCMP_ULT: attr += 4; break; case CmpInst::ICMP_ULE: case CmpInst::ICMP_SLE: case CmpInst::FCMP_OLE: case CmpInst::FCMP_ULE: attr += 5; break; default: break; } if (selectcmpInst->getOpcode() == Instruction::FCmp) { auto ty0 = op0->getType(); if (ty0->isHalfTy() #if LLVM_VERSION_MAJOR >= 11 || ty0->isBFloatTy() #endif ) max_size = 16; else if (ty0->isFloatTy()) max_size = 32; else if (ty0->isDoubleTy()) max_size = 64; else if (ty0->isX86_FP80Ty()) max_size = 80; else if (ty0->isFP128Ty() || ty0->isPPC_FP128Ty()) max_size = 128; attr += 8; } else { intTyOp0 = dyn_cast<IntegerType>(op0->getType()); intTyOp1 = dyn_cast<IntegerType>(op1->getType()); if (intTyOp0 && intTyOp1) { max_size = intTyOp0->getBitWidth() > intTyOp1->getBitWidth() ? intTyOp0->getBitWidth() : intTyOp1->getBitWidth(); } } if (!max_size || max_size < 16) { continue; } if (max_size % 8) { max_size = (((max_size / 8) + 1) * 8); } if (max_size > 128) { if (!be_quiet) { fprintf(stderr, "Cannot handle this compare bit size: %u (truncating)\n", max_size); } max_size = 128; } // do we need to cast? switch (max_size) { case 8: case 16: case 32: case 64: case 128: cast_size = max_size; break; default: cast_size = 128; } // errs() << "[CMPLOG] cmp " << *cmpInst << "(in function " << // cmpInst->getFunction()->getName() << ")\n"; // first bitcast to integer type of the same bitsize as the original // type (this is a nop, if already integer) Value *op0_i = IRB.CreateBitCast( op0, IntegerType::get(C, op0->getType()->getPrimitiveSizeInBits())); // then create a int cast, which does zext, trunc or bitcast. In our case // usually zext to the next larger supported type (this is a nop if // already the right type) Value *V0 = IRB.CreateIntCast(op0_i, IntegerType::get(C, cast_size), false); args.push_back(V0); Value *op1_i = IRB.CreateBitCast( op1, IntegerType::get(C, op1->getType()->getPrimitiveSizeInBits())); Value *V1 = IRB.CreateIntCast(op1_i, IntegerType::get(C, cast_size), false); args.push_back(V1); // errs() << "[CMPLOG] casted parameters:\n0: " << *V0 << "\n1: " << *V1 // << "\n"; ConstantInt *attribute = ConstantInt::get(Int8Ty, attr); args.push_back(attribute); if (cast_size != max_size) { ConstantInt *bitsize = ConstantInt::get(Int8Ty, (max_size / 8) - 1); args.push_back(bitsize); } // fprintf(stderr, "_ExtInt(%u) castTo %u with attr %u didcast %u\n", // max_size, cast_size, attr); switch (cast_size) { case 8: IRB.CreateCall(cmplogHookIns1, args); break; case 16: IRB.CreateCall(cmplogHookIns2, args); break; case 32: IRB.CreateCall(cmplogHookIns4, args); break; case 64: IRB.CreateCall(cmplogHookIns8, args); break; case 128: if (max_size == 128) { IRB.CreateCall(cmplogHookIns16, args); } else { IRB.CreateCall(cmplogHookInsN, args); } break; } } } if (switches.size() || icomps.size()) return true; else return false; } bool CmpLogInstructions::runOnModule(Module &M) { if (getenv("AFL_QUIET") == NULL) printf("Running cmplog-instructions-pass by andreafioraldi@gmail.com\n"); else be_quiet = 1; hookInstrs(M); verifyModule(M); return true; } static void registerCmpLogInstructionsPass(const PassManagerBuilder &, legacy::PassManagerBase &PM) { auto p = new CmpLogInstructions(); PM.add(p); } static RegisterStandardPasses RegisterCmpLogInstructionsPass( PassManagerBuilder::EP_OptimizerLast, registerCmpLogInstructionsPass); static RegisterStandardPasses RegisterCmpLogInstructionsPass0( PassManagerBuilder::EP_EnabledOnOptLevel0, registerCmpLogInstructionsPass); #if LLVM_VERSION_MAJOR >= 11 static RegisterStandardPasses RegisterCmpLogInstructionsPassLTO( PassManagerBuilder::EP_FullLinkTimeOptimizationLast, registerCmpLogInstructionsPass); #endif
23.440994
80
0.563792
[ "vector" ]
ad35e2a8f70a2caf2df40e335284514658be1b25
1,070
cpp
C++
Online-Judge-Solution/Light OJ Solutions/1307 (Counting Triangles).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/Light OJ Solutions/1307 (Counting Triangles).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
Online-Judge-Solution/Light OJ Solutions/1307 (Counting Triangles).cpp
arifparvez14/Basic-and-competetive-programming
4cb9ee7fbed3c70307d0f63499fcede86ed3c732
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #define fileread freopen("in.txt","r",stdin) #define filewrite freopen("out.txt","w",stdout) #define ll long long int #define FOR(i,n) for(int i=0;i<n;i++) #define FOR(i,m) for(int i=0;i<m;i++) #define vll vector<ll> #define mp make_pair #define msll map<string, ll> #define pb push_back using namespace std; ll n; vll v; int main() { fileread; ll t, ans,lo,hi,c; vll :: iterator it1,it2; cin>>t; for(ll cs = 1; cs <= t; cs++){ cin>>n; c = 0; for(ll i =0; i < n; i++){ ll x; cin>>x; v.pb(x); } sort(v.begin(),v.end()); for(ll i = 0; i<n; i++) { for(ll j = i+1; j<n; j++) { lo = abs(v[j]-v[i])+1; hi = v[i] + v[j] -1; it1 = lower_bound(v.begin()+j+1,v.end(),lo); it2 = upper_bound(v.begin()+j+1,v.end(),hi); c = c + it2-it1; } } printf("Case %lld: %lld\n",cs,c); v.clear(); } return 0; }
23.26087
60
0.446729
[ "vector" ]
ad378882b9c42091a1207662a5c405d0f6f00d70
1,933
hpp
C++
ppcnn/ppcnn_server/ppcnn_server_result.hpp
mt-st1/PP-CNN2
a35caf4aa3081342b48556305f2b0574a3d68800
[ "Apache-2.0" ]
19
2020-09-28T20:53:20.000Z
2022-03-14T06:22:26.000Z
ppcnn/ppcnn_server/ppcnn_server_result.hpp
mt-st1/PP-CNN2
a35caf4aa3081342b48556305f2b0574a3d68800
[ "Apache-2.0" ]
null
null
null
ppcnn/ppcnn_server/ppcnn_server_result.hpp
mt-st1/PP-CNN2
a35caf4aa3081342b48556305f2b0574a3d68800
[ "Apache-2.0" ]
8
2020-09-28T20:53:26.000Z
2022-02-15T13:52:41.000Z
/* * Copyright 2020 Yamana Laboratory, Waseda University * Supported by JST CREST Grant Number JPMJCR1503, Japan. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE‐2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PPCNN_SERVER_RESULT_HPP #define PPCNN_SERVER_RESULT_HPP #include <chrono> #include <cstdbool> #include <cstdint> #include <vector> #include <ppcnn_share/ppcnn_concurrent_mapqueue.hpp> #include <seal/seal.h> namespace ppcnn_server { /** * @brief This class is used to hold the result data. */ struct Result { Result() = default; /** * Constructor * @param[in] key_id key ID * @param[in] query_id query ID * @param[in] status calcuration status * @param[in] ctxts cipher texts */ Result(const int32_t key_id, const int32_t query_id, const bool status, const std::vector<seal::Ciphertext>& ctxts); virtual ~Result() = default; double elapsed_time() const; int32_t key_id_; int32_t query_id_; bool status_; std::vector<seal::Ciphertext> ctxts_; std::chrono::system_clock::time_point created_time_; }; /** * @brief This class is used to hold the queue of results. */ struct ResultQueue : public ppcnn_share::ConcurrentMapQueue<int32_t, Result> { using super = ppcnn_share::ConcurrentMapQueue<int32_t, Result>; ResultQueue() = default; virtual ~ResultQueue() = default; }; } /* namespace ppcnn_server */ #endif /* PPCNN_SERVER_RESULT_HPP */
26.121622
76
0.70926
[ "vector" ]
ad38cf93ff28d47863ab580a6be876df26d65e1a
1,116
cpp
C++
src/lib/calibration/calibration.cpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
src/lib/calibration/calibration.cpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
src/lib/calibration/calibration.cpp
idangerichter/CryptoWorkshop
c8d5e202fe3d02c85e58c8c01978db013a81eccd
[ "WTFPL" ]
null
null
null
#include "calibration.hpp" #include "gap_score_provider.hpp" #include "simple_score_provider.hpp" #include <algorithm> #include <functional> #include <iostream> constexpr double THRESHOLD_FLUSHED_MULTIPLIER = 0.9; namespace Calibration { std::unique_ptr<ScoreProvider> Calibrate(std::vector<Measurement>& measurements_after_flush, AttackType type) { std::function<bool(int, int)> comparator = std::greater<>(); if (type != AttackType::FlushReload) { comparator = std::less<>(); } auto index = static_cast<size_t>(measurements_after_flush.size() * THRESHOLD_FLUSHED_MULTIPLIER); std::nth_element(measurements_after_flush.begin(), measurements_after_flush.begin() + index, measurements_after_flush.end(), [comparator](Measurement& lhs, Measurement& rhs) -> bool { return comparator(lhs.time, rhs.time); }); auto threshold = measurements_after_flush[index].time; return std::make_unique<SimpleScoreProvider>(type, threshold); } } // namespace Calibration
31.885714
99
0.669355
[ "vector" ]
ad3df6e567211ca85022dbad5491b484d0e0d19f
1,440
cpp
C++
Gems/PhysX/Code/NumericalMethods/Source/Optimization/Utilities.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T12:39:24.000Z
2021-07-20T12:39:24.000Z
Gems/PhysX/Code/NumericalMethods/Source/Optimization/Utilities.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/PhysX/Code/NumericalMethods/Source/Optimization/Utilities.cpp
aaarsene/o3de
37e3b0226958974defd14dd6d808e8557dcd7345
[ "Apache-2.0", "MIT" ]
1
2021-07-20T11:07:25.000Z
2021-07-20T11:07:25.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <NumericalMethods_precompiled.h> #include <NumericalMethods/Optimization.h> #include <Optimization/Constants.h> #include <Optimization/Utilities.h> namespace NumericalMethods::Optimization { double FunctionValue(const Function& function, const VectorVariable& point) { return function.Execute(point.GetValues()).GetValue(); } double DirectionalDerivative(const Function& function, const VectorVariable& point, const VectorVariable& direction) { return Gradient(function, point).Dot(direction); } VectorVariable Gradient(const Function& function, const VectorVariable& point) { const AZ::u32 dimension = point.GetDimension(); VectorVariable gradient(dimension); VectorVariable direction(dimension); for (AZ::u32 i = 0; i < dimension; i++) { direction[i] = 1.0; double f_plus = FunctionValue(function, point + epsilon * direction); double f_minus = FunctionValue(function, point - epsilon * direction); gradient[i] = (f_plus - f_minus) / (2.0 * epsilon); direction[i] = 0.0; } return gradient; } } // namespace NumericalMethods::Optimization
35.121951
158
0.677778
[ "3d" ]
ad4323144beb38cda821e1b30d866d953262cfef
965
cpp
C++
41-50/47. Permutations II.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
41-50/47. Permutations II.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
41-50/47. Permutations II.cpp
zzuliLL/Leetcode-
a14fe1188da008a39d7aaf4e142ee582493b7c60
[ "MIT" ]
null
null
null
//STL class Solution { public: vector<vector<int>> permuteUnique(vector<int>& nums) { vector<vector<int>> ans; sort(nums.begin(), nums.end()); do { ans.push_back(nums); }while(next_permutation(nums.begin(), nums.end())); return ans; } }; //手敲的dfs class Solution { public: void dfs(vector<int> &nums, int cur, int n) { if(cur == n) { if(st.find(nums) != st.end()) return ; ans.push_back(nums); st.insert(nums); return ; } for(int i = cur; i <= n; i++) { swap(nums[i], nums[cur]); dfs(nums, cur+1, n); swap(nums[i], nums[cur]); } } vector<vector<int>> ans; set<vector<int>> st; vector<vector<int>> permuteUnique(vector<int>& nums) { sort(nums.begin(), nums.end()); dfs(nums, 0, nums.size()-1); return ans; } };
22.44186
59
0.475648
[ "vector" ]
ad43ab7753a2b609fb5833a0cf951f263a4da629
3,245
cpp
C++
Core/Core/Caching/Backends/RedisBackend.cpp
d0si/vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
2
2019-12-27T22:06:25.000Z
2020-01-13T18:43:29.000Z
Core/Core/Caching/Backends/RedisBackend.cpp
D0si/Vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
25
2020-01-29T23:04:23.000Z
2020-04-17T06:40:11.000Z
Core/Core/Caching/Backends/RedisBackend.cpp
D0si/Vortex
a97031227d4e867986918d39eeb2d184147cf118
[ "MIT" ]
1
2022-03-09T09:14:47.000Z
2022-03-09T09:14:47.000Z
#include <Core/Caching/Backends/RedisBackend.h> namespace Vortex::Core::Caching::Backends { RedisBackend::RedisBackend() {} RedisBackend::RedisBackend(const Maze::Element& redis_config) { set_config(redis_config); } RedisBackend::~RedisBackend() { #ifdef HAS_FEATURE_CPPREDIS if (_client.is_connected()) { _client.sync_commit(); _client.disconnect(); } #endif } void RedisBackend::connect() { #ifdef HAS_FEATURE_CPPREDIS if (_enabled) { std::string address = "127.0.0.1"; int port = 6379; if (_redis_config.is_string("address")) { address = _redis_config["address"].get_string(); } if (_redis_config.is_int("port")) { port = _redis_config["port"].get_int(); } _client.connect(address, port); } #endif } void RedisBackend::set_config(const Maze::Element& redis_config) { _redis_config = redis_config; if (_redis_config.is_bool("enabled")) { _enabled = _redis_config["enabled"].get_bool(); } } const bool RedisBackend::is_enabled() const { return _enabled; } const std::string RedisBackend::get(const std::string& key) { #ifdef HAS_FEATURE_CPPREDIS if (_enabled && _client.is_connected()) { std::future<cpp_redis::reply> reply = _client.get(key); _client.sync_commit(); reply.wait(); return reply.get().as_string(); } else { return ""; } #else return ""; #endif } void RedisBackend::set(const std::string& key, const std::string& value, int expire_seconds) { #ifdef HAS_FEATURE_CPPREDIS if (_enabled && _client.is_connected()) { _client.set(key, value); _client.sync_commit(); if (expire_seconds > 0) { set_expiry(key, expire_seconds); } } #endif } bool RedisBackend::exists(const std::string& key) { #ifdef HAS_FEATURE_CPPREDIS if (_enabled && _client.is_connected()) { std::vector<std::string> keys; keys.push_back(key); std::future<cpp_redis::reply> reply = _client.exists(keys); _client.sync_commit(); reply.wait(); return reply.get().as_integer() == 1; } else { return false; } #else return false; #endif } void RedisBackend::remove(const std::string& key) { #ifdef HAS_FEATURE_CPPREDIS if (_enabled && _client.is_connected()) { std::vector<std::string> keys; keys.push_back(key); _client.del(keys); _client.sync_commit(); } #endif } void RedisBackend::set_expiry(const std::string& key, int seconds) { #ifdef HAS_FEATURE_CPPREDIS if (_enabled && _client.is_connected()) { _client.expire(key, seconds); _client.sync_commit(); } #endif } CacheBackendInterface* get_redis_backend() { static RedisBackend instance; return &instance; } } // namespace Vortex::Core::Cache::Backends
25.155039
98
0.56641
[ "vector" ]
ad45b7fe5ec3a80e0dac806d6d5686973c1b090d
2,480
cpp
C++
src/Compress.cpp
W-46ec/Huffman-Compression
1c3e81d85f989784cdb840d9624a0ad021ed86cd
[ "MIT" ]
1
2020-08-31T12:30:56.000Z
2020-08-31T12:30:56.000Z
src/Compress.cpp
W-46ec/Huffman-Compression
1c3e81d85f989784cdb840d9624a0ad021ed86cd
[ "MIT" ]
null
null
null
src/Compress.cpp
W-46ec/Huffman-Compression
1c3e81d85f989784cdb840d9624a0ad021ed86cd
[ "MIT" ]
null
null
null
/* * Compress.cpp * * Description: Implementation of compression function. * * * */ #include <iostream> #include "InBitStream.h" #include "OutBitStream.h" #include "FrequencyCounter.h" #include "PriorityQueue.h" #include "HuffmanTree.h" #include "HeaderFormat.h" using namespace std; // Desc: Write the required information to the header of // the compressed file. // Implemented in "FileHeaderHandler.cpp". int writeFileHeader(OutBitStream &, FrequencyCounter &); // Desc: Compression function. // Post: Return 0 if success. Otherwise, return -1. int compress(const char *src, const char *dst) { cout << "Compressing ..." << endl; InBitStream in; // Create an InBitStream object and open the source file. OutBitStream out; // Create an OutBitStream object. FrequencyCounter counter; // Frequency counter object PriorityQueue pq; // Priority Queue // Prepare the source file. bool isSuccessful = in.openFile(src); if (isSuccessful == false) { cout << "Error: Cannot open file \"" << src << "\"." << endl; return -1; } counter.createTable(in); cout << src << " -> " << in.getFileSize() << " bytes" << endl; counter.createPriorityQueue(pq); // Create Priority Queue. HuffmanTree huffTree(pq); // Create Huffman Tree. // huffTree.display(); // Test in.openFile(src); // Prepare the source file. // Create destination file. isSuccessful = out.openFile(dst); if (isSuccessful == false) { cout << "Error: Cannot create destination file \"" << dst << "\"." << endl; return -1; } // Write file header. unsigned totalHeaderSize = writeFileHeader(out, counter); // Load the data onto output buffer. // And write the compressed data to destination file. unsigned *codeTable = huffTree.getCodeTable(); unsigned *codeLengthTable = huffTree.getCodeLengthTable(); while (in.loadNextByte() == true) { out.loadNextByte(in.getCharacter(), codeTable, codeLengthTable); } out.sendEOF(); // Write the remaining bits (if any) to file. unsigned fileBodySize = out.getTotalNumOfBytes(); // Write the original file size to file. out.writeValueAt( totalHeaderSize - ORIGINAL_SIZE, in.getFileSize(), ORIGINAL_SIZE ); out.closeFile(); // Close file. cout << dst << " -> " << totalHeaderSize + fileBodySize << " bytes" << endl; if ((totalHeaderSize + fileBodySize) > in.getFileSize()) cout << "*** Size of compressed file > size of source file ***" << endl; return 0; } // compress // End of Compress.cpp
27.252747
77
0.685887
[ "object" ]
ad4a0261a281d32f47779411ab7278f2c8506df3
53
hpp
C++
src/boost_geometry_util_transform_variant.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_geometry_util_transform_variant.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_geometry_util_transform_variant.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/geometry/util/transform_variant.hpp>
26.5
52
0.830189
[ "geometry" ]
ad4f3727d9be633ec21bd6a252c378c81f01776e
17,771
cxx
C++
private/inet/xml/xml/islands/peer.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
11
2017-09-02T11:27:08.000Z
2022-01-02T15:25:24.000Z
private/inet/xml/xml/islands/peer.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
null
null
null
private/inet/xml/xml/islands/peer.cxx
King0987654/windows2000
01f9c2e62c4289194e33244aade34b7d19e7c9b8
[ "MIT" ]
14
2019-01-16T01:01:23.000Z
2022-02-20T15:54:27.000Z
/* * @(#)Peer.cxx 1.0 2/27/98 * * Copyright (c) 1997 - 1999 Microsoft Corporation. All rights reserved. * * implementation of xtag peer for XML data islands * */ #include "core.hxx" #pragma hdrstop #include "peer.hxx" #include "xmldom.hxx" #include "core/com/bstr.hxx" #include "islandshared.hxx" // BUGBUG remove when not needed #if DBG == 1 #include "core/io/stringbufferoutputstream.hxx" #endif //379E501F-B231-11d1-ADC1-00805FC752D8 extern "C" const CLSID CLSID_XMLIslandPeer = {0x379e501f,0xb231,0x11d1,{0xad,0xc1,0x00,0x80,0x5f,0xc7,0x52,0xd8}}; CXMLIslandPeer::EVENTINFO CXMLIslandPeer::s_eventinfoTable[] = { { L"ondataavailable", PEEREVENT_ONDATAAVAILABLE } }; CXMLIslandPeer::CXMLIslandPeer(DSODocument* pDoc) { _pPropChange = NULL; _pDocWrapper = new DOMDocumentWrapper(pDoc); _pDocWrapper->Release(); // smartpointer. _dwAdviseCookie = 0; _pDocEvents = NULL; _pEBOM = NULL; _pCPNodeList = NULL; _pDSO = NULL; } CXMLIslandPeer::~CXMLIslandPeer() { // Unadvise on the ConnectionPoint HookUpToConnection(FALSE); // Let go of the event helper if (_pDocEvents) _pDocEvents->Release(); // Detach from the event which notifies us of the src attribute changing if (_pPropChange) { AttachEventHelper(_HTMLElement, _pPropChange, L"onpropertychange", FALSE); _pPropChange->Release(); } _PeerSite = null; _pDocWrapper = null; if (_pEBOM) _pEBOM->Release(); ReleaseCPNODEList(_pCPNodeList); } /////////////////////////////////////////////////////////////////////////////// // CXMLIslandPeer::QueryInterface - over-ride QI // HRESULT STDMETHODCALLTYPE CXMLIslandPeer::QueryInterface(REFIID riid, LPVOID *ppvObject) { HRESULT hr = S_OK; STACK_ENTRY_IUNKNOWN(this); if (ppvObject == NULL) { hr = E_INVALIDARG; goto Cleanup; } *ppvObject = NULL; TRY { hr = super::QueryInterface(riid,ppvObject); if (hr != E_NOINTERFACE) goto Cleanup; if (IsEqualIID(riid, IID_IDispatch) || IsEqualIID(riid, IID_IDispatchEx)) { *ppvObject = static_cast<IDispatchEx *>(this); AddRef(); } else if (IsEqualIID(riid, IID_IConnectionPointContainer)) { // BUGBUG - is this all still needed now that CXMLIslandPeer // is it's own controlling IUnknown ? CXMLConnectionPtContainer *pCPC = new_ne CXMLConnectionPtContainer( IID_IPropertyNotifySink, static_cast<IElementBehavior *>(this), // set this object as the pUnkOuter &_pCPNodeList, getWrapped()->getSpinLockCPC()); if (NULL != pCPC) { *ppvObject = (LPVOID) pCPC; hr = S_OK; } else { hr = E_OUTOFMEMORY; } } else if (IsEqualIID(riid, IID_DataSource)) { if (!_pDSO) { _pDSO = new XMLDSO; // is created with refcount = 0 if (!_pDSO) { hr = E_OUTOFMEMORY; goto Cleanup; } _pDSO->GetAttributesFromElement(_HTMLElement); if (_PeerSite) { _pDSO->setSite(_PeerSite); _pDSO->setInterfaceSafetyOptions(IID_IUnknown, INTERFACESAFE_FOR_UNTRUSTED_DATA, INTERFACESAFE_FOR_UNTRUSTED_DATA); } _pDSO->AddDocument(getWrapped()); } Assert(!!_pDSO); hr = _pDSO->QueryInterface(riid, ppvObject); } else { hr = _pDocWrapper->QueryInterface(riid, ppvObject); } } CATCH { hr = ERESULT; } ENDTRY Cleanup: return hr; } HRESULT STDMETHODCALLTYPE CXMLIslandPeer::GetDispID( /* [in] */ BSTR bstrName, /* [in] */ DWORD grfdex, /* [out] */ DISPID __RPC_FAR *pid) { HRESULT hr; // bug 64435 - if this is a XML island peer document, then we need to return // DISP_E_UNKNOWNNAME if bstrName = "readyState" so that the peer readystate // is returned by Trident as a string instead of as a numeric value so that // out peer is consistent with all the other HTML elements. static const WCHAR* pszReadyState = L"readyState"; if (::StrCmpW(bstrName,pszReadyState) == 0) { return DISP_E_UNKNOWNNAME; } hr = getDispatch()->GetDispID(bstrName, grfdex, pid); return hr; } /////////////////////////////////////////////////////////////////////////////// // CXMLIslandPeer::Init // method of IElementBehavior interface // STDMETHODIMP CXMLIslandPeer::Init( IElementBehaviorSite *pPeerSite) { STACK_ENTRY_IUNKNOWN(this); HRESULT hr = S_OK; TRY { _PeerSite = pPeerSite; // _reference::operator= if (SUCCEEDED(hr = _PeerSite->GetElement(&_HTMLElement))) { // Set the security information. (setSite now works correctly in this case) getWrapped()->setSite(_PeerSite); getWrapped()->setInterfaceSafetyOptions(IID_IUnknown, INTERFACESAFE_FOR_UNTRUSTED_DATA, INTERFACESAFE_FOR_UNTRUSTED_DATA); hr = RegisterBehaviourEvents(); } else { goto Exit; } if (SUCCEEDED(hr)) { hr = HookUpToConnection(TRUE); } } CATCH { // BUGBUG something besides E_FAIL? hr = E_FAIL; } ENDTRY Exit: return hr; } /////////////////////////////////////////////////////////////////////////////// // CXMLIslandPeer::Notify // method of IElementBehavior interface // STDMETHODIMP CXMLIslandPeer::Notify( LONG event, VARIANT * pVar) { HRESULT hr = S_OK; Assert(_PeerSite != null); Assert(_HTMLElement != null); switch (event) { // BEHAVIOREVENT_CONTENTREADY is sent immediately after the peer's end tag is parsed // and at any subsequent time that the content of the tag is modified case BEHAVIOREVENT_CONTENTREADY: { hr = InitXMLIslandPeer(); break; } // BEHAVIOREVENT_DOCUMENTREADY is sent when the entire document has been parsed // BUGBUG do we need to handle this event or not? case BEHAVIOREVENT_DOCUMENTREADY: { break; } } return hr; } /////////////////////////////////////////////////////////////////////////////// // CXMLIslandPeer::GetParsedText // HRESULT CXMLIslandPeer::GetParsedText(BSTR *pbstrParsedText) { const static GUID SID_SElementBehaviorMisc = {0x3050f632,0x98b5,0x11cf, {0xbb,0x82,0x00,0xaa,0x00,0xbd,0xce,0x0b}}; const static GUID CGID_ElementBehaviorMisc = {0x3050f633,0x98b5,0x11cf, {0xbb,0x82,0x00,0xaa,0x00,0xbd,0xce,0x0b}}; const static int CMDID_ELEMENTBEHAVIORMISC_PARSEDTEXT = 1; HRESULT hr; IServiceProvider *pIServiceProvider = NULL; IOleCommandTarget *pIOleCommandTarget = NULL; VARIANT varParsedText; VariantInit(&varParsedText); Assert (pbstrParsedText); hr = _PeerSite->QueryInterface(IID_IServiceProvider, (void**)&pIServiceProvider); if (FAILED(hr)) goto Exit; hr = pIServiceProvider->QueryService(SID_SElementBehaviorMisc, IID_IOleCommandTarget, (void**)&pIOleCommandTarget); if (FAILED(hr)) goto Exit; hr = pIOleCommandTarget->Exec( &CGID_ElementBehaviorMisc, CMDID_ELEMENTBEHAVIORMISC_PARSEDTEXT, 0, NULL, &varParsedText); if (hr) goto Exit; if (V_VT(&varParsedText) != VT_BSTR) { VariantClear(&varParsedText); hr = E_UNEXPECTED; goto Exit; } *pbstrParsedText = V_BSTR(&varParsedText); Exit: release(&pIServiceProvider); release(&pIOleCommandTarget); // do not do VariantClear(&varParsedText) since we are returning the BSTR return hr; } /////////////////////////////////////////////////////////////////////////////// // CXMLIslandPeer::InitXMLIslandPeer // // initializes CXMLIslandPeer object // HRESULT CXMLIslandPeer::InitXMLIslandPeer() { HRESULT hr; STACK_ENTRY_IUNKNOWN(this); BSTR bstrXML = null; VARIANT vtSrcAttr; IStream *pIStream = NULL; BSTR bstrSRC = ::SysAllocString(L"SRC"); VARIANT varExpandoValue; VARIANT_BOOL result; TRY { // First attach our expando to the tag // This is the VARIANT we are going to attach varExpandoValue.pdispVal = static_cast<IDispatchEx *>(_pDocWrapper); varExpandoValue.vt = VT_DISPATCH; hr = SetExpandoProperty( _HTMLElement, String::newString("XMLDocument"), &varExpandoValue); Assert(SUCCEEDED(hr) && "Failed to add expando property !"); // VariantClear(&varExpandoValue); -- not needed since we didn't do an addref. if (NULL == bstrSRC && SUCCEEDED(hr)) { hr = E_OUTOFMEMORY; } // Get Trident to tell us when the SRC attribute changes if (SUCCEEDED(hr)) hr = RegisterForElementEvents(_HTMLElement, &_pPropChange, (CElementEventSink *)this); if (FAILED(hr)) { goto Exit; } VariantInit(&vtSrcAttr); hr = _HTMLElement->getAttribute(bstrSRC, 0, &vtSrcAttr); ::SysFreeString(bstrSRC); // If we don't have a SRC attribute, we need to get what's between the tags if (FAILED(hr) || (vtSrcAttr.vt != VT_BSTR) || (V_BSTR(&vtSrcAttr) == NULL)) { // BUGBUG - this get_innerHTML call can be removed when // MSHTML fixes their side. hr = _HTMLElement->get_innerHTML(&bstrXML); if (NULL == bstrXML || 0 == *bstrXML) { // try the new method hr = GetParsedText(&bstrXML); } if (NULL == bstrXML) hr = E_FAIL; if (FAILED(hr)) goto Exit; } // We had better have either a SRC attribute or some XML Assert (bstrXML != NULL || V_BSTR(&vtSrcAttr) != NULL && "Must have either a SRC attribute or some XML"); // Do we have a SRC attribute ? if (V_VT(&vtSrcAttr) == VT_BSTR && V_BSTR(&vtSrcAttr) != NULL) { // This relative URL will be resolved using the baseURL we provided on the // document in Init. // Have to call the wrapper instead of the document directly // because it's the wrapper that handles dom locks hr = _pDocWrapper->load(vtSrcAttr, &result); } else if (bstrXML != NULL) { // Have to call the wrapper instead of the document directly // because it's the wrapper that handles dom locks hr = _pDocWrapper->loadXML(bstrXML, &result); } #ifdef LETSLEAVETHISOUT #if DBG == 1 // debug code to enable looking at parsed doc tree in debugger StringBuffer * buf = StringBuffer::newStringBuffer(4096); Stream * pStreamOut = StringStream::newStringStream(buf); pStreamOut->getIStream(&pIStream); OutputHelper * pOutputHelper = getWrapped()->createOutput(pIStream); getWrapped()->save(pOutputHelper); String * pStringOut = buf->toString(); // BUGBUG add debug code to dump document //FileOutputStream* out = FileOutputStream::newFileOutputStream(String::newString(_T("dumpTree.xml"))); //dumpTree(getWrapped(), PrintStream::newPrintStream(out, true), String::emptyString()); #endif #endif // LETSLEAVETHISOUT } CATCH { // BUGBUG something besides E_FAIL? hr = E_FAIL; goto Exit; } ENDTRY Exit: VariantClear(&vtSrcAttr); ::SysFreeString(bstrXML); release(&pIStream); return hr; } HRESULT CXMLIslandPeer::HookUpToConnection(BOOL fAdvise) { HRESULT hr; IConnectionPointContainer *pCPC; IConnectionPoint *pCP; if (SUCCEEDED(hr = getWrapped()->QueryInterface(IID_IConnectionPointContainer, (LPVOID *)&pCPC))) { hr = pCPC->FindConnectionPoint(DIID_XMLDOMDocumentEvents, &pCP); pCPC->Release(); // Don't need you any more if (SUCCEEDED(hr)) { if (fAdvise) { if (!_pDocEvents) { _pDocEvents = new_ne CDocEventReceiver((CDocEventSink *)this); Assert(_pDocEvents && "Unable to create doc event handler"); if (!_pDocEvents) return E_OUTOFMEMORY; } hr = pCP->Advise((IUnknown *)_pDocEvents, &_dwAdviseCookie); } else { Assert(_dwAdviseCookie && "Unadvising on a bad cookie"); hr = pCP->Unadvise(_dwAdviseCookie); #if DBG == 1 _dwAdviseCookie = 0; #endif } pCP->Release(); } } return hr; } HRESULT CXMLIslandPeer::RegisterBehaviourEvents() { UINT i; HRESULT hr; EVENTINFO *pEventWalker; Assert (_PeerSite && "We don't have a Peer site to register events against!"); Assert (sizeof(s_eventinfoTable) / sizeof(EVENTINFO) == PEEREVENT_NUMEVENTS && "PEEREVENT_NUMEVENTS is out of sync"); if (SUCCEEDED(hr = _PeerSite->QueryInterface(IID_IElementBehaviorSiteOM, (LPVOID *)&_pEBOM))) { for (i = 0; i < PEEREVENT_NUMEVENTS && SUCCEEDED(hr); i++) { pEventWalker = &s_eventinfoTable[i]; BSTR bstrEventname = SysAllocString(pEventWalker->rgwchEventName); if (NULL != bstrEventname) { hr = _pEBOM->RegisterEvent( bstrEventname, 0, &_rglEventCookies[pEventWalker->lCookieNumber]); SysFreeString(bstrEventname); } else { hr = E_OUTOFMEMORY; } Assert (SUCCEEDED(hr) && "Unexpected problem while registering events"); } } Assert (_pEBOM && "Couldn't get an ElementBehaviourOM pointer - no events for you my lad !"); return hr; } HRESULT CXMLIslandPeer::onReadyStateChange() { // BUGBUG - commenting out this line fixes bug 66769, but this means the // loop is not safe to changes in the list that may happen during OnChanged. // We should eventually copy the ppnsConnector references into a local // array while inside BusyLock then release the BusyLock and zip through the // array and call OnChanged. // BusyLock bl(getWrapped()->getSpinLockCPC()); // bug 66769 PCPNODE pNode = _pCPNodeList; HRESULT hr = S_OK; while (pNode && SUCCEEDED(hr)) { Assert (pNode->cpt != CP_Invalid && "Invalid ConnectionPoint node"); // We only fire through IPropertyNotifySink // If we couldn't get IPropertyNotifySink, it's useless to us anyway if (CP_PropertyNotifySink == pNode->cpt) { hr = pNode->ppnsConnector->OnChanged(DISPID_READYSTATE); } pNode = pNode->pNext; } return hr; } HRESULT CXMLIslandPeer::onDataAvailable() { Assert (_pEBOM && "We don't have an EBOM pointer !"); if (!_pEBOM) return S_OK; return _pEBOM->FireEvent(_rglEventCookies[PEEREVENT_ONDATAAVAILABLE], NULL); } HRESULT CXMLIslandPeer::onSrcChange() { STACK_ENTRY_IUNKNOWN(this); VARIANT varAttrib; VARIANT varAttribBstr; BSTR bstrSrc; HRESULT hr; VariantInit(&varAttrib); VariantInit(&varAttribBstr); hr = GetExpandoProperty( _HTMLElement, String::newString("src"), &varAttrib); if (SUCCEEDED(hr)) { if (varAttrib.vt != VT_BSTR) { if (SUCCEEDED(hr = VariantChangeTypeEx(&varAttribBstr, &varAttrib, GetThreadLocale(), 0, VT_BSTR))) { bstrSrc = varAttribBstr.bstrVal; } else { bstrSrc = NULL; } } else { bstrSrc = varAttrib.bstrVal; } } TRY { if (SUCCEEDED(hr)) { // Let's re-use all the great IXMLDOMDocument wrapper stuff so we // get the right locking behavior. VARIANT_BOOL result; VARIANT vURL; vURL.vt = VT_BSTR; V_BSTR(&vURL) = bstrSrc; hr = _pDocWrapper->load(vURL, &result); } } CATCH { hr = ERESULT; } ENDTRY VariantClear(&varAttrib); if (varAttribBstr.vt != VT_EMPTY) VariantClear(&varAttribBstr); return hr; } /// End of file /////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
28.342903
136
0.551179
[ "object" ]
ad52238e3d18d89917735ff700c5f69a7a7fdf8e
6,336
cpp
C++
generated-tests/memory.cpp
ArisenIO/arisen-wasm-spec-tests
8264191d950776d6f4f79cb0736a07386f2278e1
[ "MIT" ]
null
null
null
generated-tests/memory.cpp
ArisenIO/arisen-wasm-spec-tests
8264191d950776d6f4f79cb0736a07386f2278e1
[ "MIT" ]
null
null
null
generated-tests/memory.cpp
ArisenIO/arisen-wasm-spec-tests
8264191d950776d6f4f79cb0736a07386f2278e1
[ "MIT" ]
null
null
null
#include <wasm_spec_tests.hpp> const string wasm_str_memory_0 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.0.wasm"; std::vector<uint8_t> wasm_memory_0= read_wasm(wasm_str_memory_0.c_str()); BOOST_DATA_TEST_CASE(memory_0_module, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_0); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_1 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.1.wasm"; std::vector<uint8_t> wasm_memory_1= read_wasm(wasm_str_memory_1.c_str()); BOOST_DATA_TEST_CASE(memory_1_module, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_1); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_2 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.2.wasm"; std::vector<uint8_t> wasm_memory_2= read_wasm(wasm_str_memory_2.c_str()); BOOST_DATA_TEST_CASE(memory_2_module, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_2); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_25 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.25.wasm"; std::vector<uint8_t> wasm_memory_25= read_wasm(wasm_str_memory_25.c_str()); BOOST_DATA_TEST_CASE(memory_25_pass, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_25); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_3 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.3.wasm"; std::vector<uint8_t> wasm_memory_3= read_wasm(wasm_str_memory_3.c_str()); BOOST_DATA_TEST_CASE(memory_3_module, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_3); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_6 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.6.wasm"; std::vector<uint8_t> wasm_memory_6= read_wasm(wasm_str_memory_6.c_str()); BOOST_DATA_TEST_CASE(memory_6_check_throw, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_6); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; BOOST_CHECK_THROW(push_action(tester, std::move(test), N(wasmtest).to_uint64_t()), wasm_execution_error); tester.produce_block(); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_7 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.7.wasm"; std::vector<uint8_t> wasm_memory_7= read_wasm(wasm_str_memory_7.c_str()); BOOST_DATA_TEST_CASE(memory_7_check_throw, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_7); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; BOOST_CHECK_THROW(push_action(tester, std::move(test), N(wasmtest).to_uint64_t()), wasm_execution_error); tester.produce_block(); } FC_LOG_AND_RETHROW() } const string wasm_str_memory_8 = base_dir + "/arisen-wasm-spec-tests/generated-tests/wasms/memory.8.wasm"; std::vector<uint8_t> wasm_memory_8= read_wasm(wasm_str_memory_8.c_str()); BOOST_DATA_TEST_CASE(memory_8_pass, boost::unit_test::data::xrange(0,1), index) { try { TESTER tester; tester.produce_block(); tester.create_account( N(wasmtest) ); tester.produce_block(); tester.set_code(N(wasmtest), wasm_memory_8); tester.produce_block(); action test; test.account = N(wasmtest); test.name = account_name((uint64_t)index); test.authorization = {{N(wasmtest), config::active_name}}; push_action(tester, std::move(test), N(wasmtest).to_uint64_t()); tester.produce_block(); BOOST_REQUIRE_EQUAL( tester.validate(), true ); } FC_LOG_AND_RETHROW() }
37.491124
108
0.733112
[ "vector" ]
ad54d79f360b3a2bd287bdc216eee54e27cebfca
1,385
cpp
C++
tools/LiveCollab/LiveManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
30
2021-01-25T22:25:05.000Z
2022-01-22T13:18:19.000Z
tools/LiveCollab/LiveManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
9
2021-07-03T11:41:47.000Z
2022-03-30T15:14:46.000Z
tools/LiveCollab/LiveManager.cpp
matcool/BetterEdit
aaf3f37b4c0d7b6d8298cd099d8bd2d9699cb68f
[ "MIT" ]
3
2021-07-01T20:52:24.000Z
2022-01-13T16:16:58.000Z
#include "LiveManager.hpp" using namespace gd; using namespace gdmake; using namespace gdmake::extra; using namespace cocos2d; using namespace cocos2d::extension; LiveManager* g_manager; bool LiveManager::init() { return true; } LiveManager* LiveManager::sharedState() { return g_manager; } bool LiveManager::goLive(const char* serverURL, const char* roomName, const char* roomPassword) { this->getRequest(serverURL, { }, &LiveManager::onResponse); return true; } void LiveManager::onResponse(CCHttpClient*, CCHttpResponse* res) { std::cout << res->getResponseCode() << "\n"; std::cout << std::string(res->getResponseData()->begin(), res->getResponseData()->end()) << "\n"; std::cout << res->getErrorBuffer() << "\n"; } void LiveManager::getRequest( const char* url, std::vector<std::string> const& headers, void(LiveManager::* cb)(CCHttpClient*, CCHttpResponse*) ) { auto req = new CCHttpRequest(); req->setUrl(url); req->setRequestType(CCHttpRequest::kHttpGet); req->setHeaders(headers); req->setResponseCallback(this, (SEL_HttpResponse)cb); CCHttpClient::getInstance()->send(req); } bool LiveManager::initGlobal() { g_manager = new LiveManager(); if (g_manager && g_manager->init()) { g_manager->retain(); return true; } CC_SAFE_DELETE(g_manager); return false; }
24.298246
101
0.67509
[ "vector" ]
ad566e078f4a5ef6c8ce4d3d43798bddc32a996f
58,153
cpp
C++
PlatformRig/DebuggingDisplays/BufferUploadDisplay.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
PlatformRig/DebuggingDisplays/BufferUploadDisplay.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
PlatformRig/DebuggingDisplays/BufferUploadDisplay.cpp
alexgithubber/XLE-Another-Fork
cdd8682367d9e9fdbdda9f79d72bb5b1499cec46
[ "MIT" ]
null
null
null
// Copyright 2015 XLGAMES Inc. // // Distributed under the MIT License (See // accompanying file "LICENSE" or the website // http://www.opensource.org/licenses/mit-license.php) #include "BufferUploadDisplay.h" #include "../../RenderCore/Techniques/ResourceBox.h" #include "../../RenderOverlays/OverlayUtils.h" #include "../../RenderOverlays/Font.h" #include "../../Utility/MemoryUtils.h" #include "../../Utility/PtrUtils.h" #include "../../Utility/StringFormat.h" #include "../../Utility/StringUtils.h" #include "../../Utility/IteratorUtils.h" #include "../../Utility/TimeUtils.h" #include <assert.h> #pragma warning(disable:4127) // warning C4127: conditional expression is constant namespace PlatformRig { namespace Overlays { static void DrawButton(IOverlayContext* context, const char name[], const Rect&buttonRect, Interactables&interactables, InterfaceState& interfaceState) { InteractableId id = InteractableId_Make(name); DrawButtonBasic(context, buttonRect, name, FormatButton(interfaceState, id)); interactables.Register(Interactables::Widget(buttonRect, id)); } BufferUploadDisplay::GPUMetrics::GPUMetrics() { _slidingAverageCostMS = 0.f; _slidingAverageBytesPerSecond = 0; } BufferUploadDisplay::FrameRecord::FrameRecord() { _frameId = 0x0; _gpuCost = 0.f; _commandListStart = _commandListEnd = ~unsigned(0x0); } BufferUploadDisplay::BufferUploadDisplay(BufferUploads::IManager* manager) : _manager(manager) { _graphMinValueHistory = _graphMaxValueHistory = 0.f; XlZeroMemory(_accumulatedCreateCount); XlZeroMemory(_accumulatedCreateBytes); XlZeroMemory(_accumulatedUploadCount); XlZeroMemory(_accumulatedUploadBytes); _graphsMode = 0; _mostRecentGPUFrequency = 0; _lastUploadBeginTime = 0; _mostRecentGPUCost = 0.f; _mostRecentGPUFrameId = 0; _lockedFrameId = ~unsigned(0x0); auto timerFrequency = GetPerformanceCounterFrequency(); _reciprocalTimerFrequency = 1./double(timerFrequency); assert(s_gpuListenerDisplay==0); s_gpuListenerDisplay = this; } BufferUploadDisplay::~BufferUploadDisplay() { assert(s_gpuListenerDisplay==this); s_gpuListenerDisplay = NULL; } static const char* AsString(BufferUploads::UploadDataType::Enum value) { using namespace BufferUploads::UploadDataType; switch (value) { case Texture: return "Texture"; case Vertex: return "Vertex"; case Index: return "Index"; default: return "<<unknown>>"; } }; static const char* TypeString(const BufferUploads::BufferDesc& desc) { using namespace BufferUploads; if (desc._type == BufferDesc::Type::Texture) { const TextureDesc& tDesc = desc._textureDesc; switch (tDesc._dimensionality) { case TextureDesc::Dimensionality::T1D: return "Tex1D"; case TextureDesc::Dimensionality::T2D: return "Tex2D"; case TextureDesc::Dimensionality::T3D: return "Tex3D"; case TextureDesc::Dimensionality::CubeMap: return "TexCube"; } } else if (desc._type == BufferDesc::Type::LinearBuffer) { if (desc._bindFlags & BindFlag::VertexBuffer) return "VB"; else if (desc._bindFlags & BindFlag::IndexBuffer) return "IB"; } return "Unknown"; } static std::string BuildDescription(const BufferUploads::BufferDesc& desc) { using namespace BufferUploads; char buffer[2048]; if (desc._type == BufferDesc::Type::Texture) { const TextureDesc& tDesc = desc._textureDesc; xl_snprintf(buffer, dimof(buffer), "(%4ix%4i) mips:(%i), array:(%i)", tDesc._width, tDesc._height, tDesc._mipCount, tDesc._arrayCount); } else if (desc._type == BufferDesc::Type::LinearBuffer) { xl_snprintf(buffer, dimof(buffer), "%6.2fkb", desc._linearBufferDesc._sizeInBytes/1024.f); } else { buffer[0] = '\0'; } return std::string(buffer); } static unsigned& GetFrameID() { static unsigned s_frameId = 0; return s_frameId; } namespace GraphTabs { enum Enum { Uploads, CreatesMB, CreatesCount, DeviceCreatesCount, Latency, PendingBuffers, CommandListCount, GPUCost, GPUBytesPerSecond, AveGPUCost, ThreadActivity, BatchedCopy, FramePriorityStall, Statistics, RecentRetirements }; static const char* Names[] = { "Uploads (MB)", "Creates (MB)", "Creates (count)", "Device creates (count)", "Latency (ms)", "Pending Buffers (MB)", "Command List Count", "GPU Cost", "GPU bytes/second", "Ave GPU cost", "Thread Activity", "Batched copy", "Frame Priority Stalls", "Statistics", "Recent Retirements" }; std::pair<const char*, std::vector<Enum>> Groups[] = { std::pair<const char*, std::vector<Enum>>("Uploads", { Uploads }), std::pair<const char*, std::vector<Enum>>("Creations", { CreatesMB, CreatesCount, DeviceCreatesCount }), std::pair<const char*, std::vector<Enum>>("GPU", { GPUCost, GPUBytesPerSecond, AveGPUCost }), std::pair<const char*, std::vector<Enum>>("Threading", { Latency, PendingBuffers, CommandListCount, ThreadActivity, BatchedCopy, FramePriorityStall }), std::pair<const char*, std::vector<Enum>>("Extra", { Statistics, RecentRetirements }), }; } static const unsigned s_MaxGraphSegments = 256; class FontBox { public: class Desc {}; intrusive_ptr<RenderOverlays::Font> _font; intrusive_ptr<RenderOverlays::Font> _smallFont; FontBox(const Desc&) : _font(RenderOverlays::GetX2Font("OrbitronBlack", 18)) , _smallFont(RenderOverlays::GetX2Font("Vera", 16)) {} }; static void DrawTopLeftRight(IOverlayContext* context, const Rect& rect, const ColorB& col) { Float3 coords[] = { AsPixelCoords(rect._topLeft), AsPixelCoords(Coord2(rect._topLeft[0], rect._bottomRight[1])), AsPixelCoords(rect._topLeft), AsPixelCoords(Coord2(rect._bottomRight[0], rect._topLeft[1])), AsPixelCoords(Coord2(rect._bottomRight[0], rect._topLeft[1])), AsPixelCoords(rect._bottomRight) }; ColorB cols[] = { col, col, col, col, col, col }; context->DrawLines(ProjectionMode::P2D, coords, dimof(coords), cols); } static void DrawBottomLeftRight(IOverlayContext* context, const Rect& rect, const ColorB& col) { Float3 coords[] = { AsPixelCoords(rect._topLeft), AsPixelCoords(Coord2(rect._topLeft[0], rect._bottomRight[1])), AsPixelCoords(Coord2(rect._topLeft[0], rect._bottomRight[1])), AsPixelCoords(rect._bottomRight), AsPixelCoords(Coord2(rect._bottomRight[0], rect._topLeft[1])), AsPixelCoords(rect._bottomRight) }; ColorB cols[] = { col, col, col, col, col, col }; context->DrawLines(ProjectionMode::P2D, coords, dimof(coords), cols); } void BufferUploadDisplay::DrawMenuBar(IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState) { static const ColorB edge(60, 60, 60, 0xcf); static const ColorB middle(32, 32, 32, 0xcf); static const ColorB mouseOver(20, 20, 20, 0xff); static const ColorB text(220, 220, 220, 0xff); static const ColorB smallText(170, 170, 170, 0xff); auto fullSize = layout.GetMaximumSize(); // bkgrnd DrawRectangle( context, Rect(fullSize._topLeft, Coord2(fullSize._bottomRight[0], fullSize._topLeft[1]+layout._paddingInternalBorder)), edge); DrawRectangle( context, Rect(Coord2(fullSize._topLeft[0], fullSize._bottomRight[1]-layout._paddingInternalBorder), fullSize._bottomRight), edge); DrawRectangle( context, Rect(Coord2(fullSize._topLeft[0], fullSize._topLeft[1]+layout._paddingInternalBorder), Coord2(fullSize._bottomRight[0], fullSize._bottomRight[1]-layout._paddingInternalBorder)), middle); layout.AllocateFullHeight(75); const std::vector<GraphTabs::Enum>* dropDown = nullptr; Rect dropDownRect; static const unsigned dropDownInternalBorder = 10; for (const auto& g:GraphTabs::Groups) { auto rect = layout.AllocateFullHeight(150); auto hash = Hash64(g.first); if (interfaceState.HasMouseOver(hash)) { DrawRectangle(context, rect, mouseOver); DrawTopLeftRight(context, rect, ColorB::White); dropDown = &g.second; unsigned count = (unsigned)g.second.size(); Coord2 dropDownSize( 300, count * 20 + (count-1) * layout._paddingBetweenAllocations + 2 * dropDownInternalBorder); dropDownRect._topLeft = Coord2(rect._topLeft[0], rect._bottomRight[1]); dropDownRect._bottomRight = dropDownRect._topLeft + dropDownSize; interactables.Register(Interactables::Widget(dropDownRect, hash)); } TextStyle style( *RenderCore::Techniques::FindCachedBox2<FontBox>()._font, DrawTextOptions(false, true)); context->DrawText( AsPixelCoords(rect), &style, text, TextAlignment::Center, g.first, nullptr); interactables.Register(Interactables::Widget(rect, hash)); } if (dropDown) { DrawRectangle(context, dropDownRect, mouseOver); DrawBottomLeftRight(context, dropDownRect, ColorB::White); Layout dd(dropDownRect); dd._paddingInternalBorder = dropDownInternalBorder; for (unsigned c=0; c<dropDown->size(); ++c) { auto rect = dd.AllocateFullWidth(20); auto col = smallText; const auto* name = GraphTabs::Names[unsigned(dropDown->begin()[c])]; auto hash = Hash64(name); if (interfaceState.HasMouseOver(hash)) col = ColorB::White; TextStyle style( *RenderCore::Techniques::FindCachedBox2<FontBox>()._smallFont, DrawTextOptions(false, true)); context->DrawText( AsPixelCoords(rect), &style, col, TextAlignment::Left, name, nullptr); if ((c+1) != dropDown->size()) context->DrawLine(ProjectionMode::P2D, AsPixelCoords(Coord2(rect._topLeft[0], rect._bottomRight[1])), col, AsPixelCoords(rect._bottomRight), col); interactables.Register(Interactables::Widget(rect, hash)); } } } size_t BufferUploadDisplay::FillValuesBuffer(unsigned graphType, unsigned uploadType, float valuesBuffer[], size_t valuesMaxCount) { using namespace BufferUploads; size_t valuesCount = 0; for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) { if (valuesCount>=valuesMaxCount) { break; } ++valuesCount; using namespace GraphTabs; float& value = valuesBuffer[valuesMaxCount-valuesCount]; value = 0.f; // Calculate the requested value ... if (graphType == Latency) { // latency (ms) TimeMarker transactionLatencySum = 0; unsigned transactionLatencyCount = 0; for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; for (unsigned i2=0; i2<commandList.RetirementCount(); ++i2) { const AssemblyLineRetirement& retirement = commandList.Retirement(i2); transactionLatencySum += retirement._retirementTime - retirement._requestTime; ++transactionLatencyCount; } } float averageTransactionLatency = transactionLatencyCount?float(double(transactionLatencySum/TimeMarker(transactionLatencyCount)) * _reciprocalTimerFrequency):0.f; value = averageTransactionLatency; } else if (graphType == PendingBuffers) { // pending buffers if (i->_commandListStart!=i->_commandListEnd) { value = _recentHistory[i->_commandListEnd-1]._assemblyLineMetrics._queuedBytes[uploadType] / (1024.f*1024.f); } } else if (graphType >= Uploads && graphType <= FramePriorityStall) { for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; if (_graphsMode == Uploads) { // bytes uploaded value += (commandList._bytesUploaded[uploadType] + commandList._bytesUploadedDuringCreation[uploadType]) / (1024.f*1024.f); } else if (_graphsMode == CreatesMB) { // creations (bytes) value += commandList._bytesCreated[uploadType] / (1024.f*1024.f); } else if (_graphsMode == CreatesCount) { // creations (count) value += commandList._countCreations[uploadType]; } else if (_graphsMode == DeviceCreatesCount) { value += commandList._countDeviceCreations[uploadType]; } else if (_graphsMode == FramePriorityStall) { value += float(commandList._framePriorityStallTime * _reciprocalTimerFrequency * 1000.f); } } } else if (_graphsMode == CommandListCount) { value = float(i->_commandListEnd-i->_commandListStart); } else if (_graphsMode == GPUCost) { value = i->_gpuCost; } else if (_graphsMode == GPUBytesPerSecond) { value = i->_gpuMetrics._slidingAverageBytesPerSecond / (1024.f * 1024.f); } else if (_graphsMode == AveGPUCost) { value = i->_gpuMetrics._slidingAverageCostMS; } else if (_graphsMode == ThreadActivity) { TimeMarker processingTimeSum = 0, waitTimeSum = 0; for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; processingTimeSum += commandList._processingEnd - commandList._processingStart; waitTimeSum += commandList._waitTime; } value = (float(processingTimeSum))?(100.f * (1.0f-(waitTimeSum/float(processingTimeSum)))):0.f; } else if (_graphsMode == BatchedCopy) { value = 0; for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; value += commandList._batchedCopyBytes; } } } return valuesCount; } void BufferUploadDisplay::DrawDisplay(IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState) { using namespace BufferUploads; static ColorB graphBk(180,200,255,128); static ColorB graphOutline(255,255,255,128); float valuesBuffer[s_MaxGraphSegments]; XlZeroMemory(valuesBuffer); unsigned graphCount = (_graphsMode<=GraphTabs::PendingBuffers)?UploadDataType::Max:1; for (unsigned c=0; c<graphCount; ++c) { Layout section = layout.AllocateFullWidthFraction(1.f/float(graphCount)); Rect labelRect = section.AllocateFullHeightFraction( .25f ); Rect historyRect = section.AllocateFullHeightFraction( .75f ); // DrawRectangleOutline(context, section._maximumSize); DrawRoundedRectangle(context, section._maximumSize, ColorB(180,200,255,128), ColorB(255,255,255,128)); size_t valuesCount = FillValuesBuffer(_graphsMode, c, valuesBuffer, dimof(valuesBuffer)); if (graphCount == UploadDataType::Max) { context->DrawText( AsPixelCoords(labelRect), nullptr, ColorB(0xffffffffu), TextAlignment::Left, StringMeld<256>() << GraphTabs::Names[_graphsMode] << " (" << AsString(UploadDataType::Enum(c)) << ")", nullptr); } else { context->DrawText( AsPixelCoords(labelRect), nullptr, ColorB(0xffffffffu), TextAlignment::Left, GraphTabs::Names[_graphsMode], nullptr); } if (valuesCount > 0) { float mostRecentValue = valuesBuffer[dimof(valuesBuffer) - valuesCount]; context->DrawText(AsPixelCoords(historyRect), nullptr, ColorB(0xffffffffu), TextAlignment::Top, XlDynFormatString("%6.3f", mostRecentValue).c_str(), nullptr); } DrawHistoryGraph( context, historyRect, &valuesBuffer[dimof(valuesBuffer)-valuesCount], (unsigned)valuesCount, (unsigned)dimof(valuesBuffer), _graphMinValueHistory, _graphMaxValueHistory); ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // extra graph functionality.... if (_graphsMode == GraphTabs::GPUCost) { // GPU cost graph should also have the total bytes uploaded draw in size_t valuesCount = 0; for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) { if (valuesCount>=dimof(valuesBuffer)) { break; } ++valuesCount; valuesBuffer[dimof(valuesBuffer)-valuesCount] = 0; for (unsigned cl=i->_commandListStart; cl<i->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; for (unsigned c2=0; c2<UploadDataType::Max; ++c2) { valuesBuffer[dimof(valuesBuffer)-valuesCount] += (commandList._bytesUploaded[c2] + commandList._bytesUploadedDuringCreation[c2]) / (1024.f*1024.f); } } } DrawHistoryGraph_ExtraLine( context, historyRect, &valuesBuffer[dimof(valuesBuffer)-valuesCount], (unsigned)valuesCount, (unsigned)dimof(valuesBuffer), _graphMinValueHistory, _graphMaxValueHistory); } { const InteractableId framePicker = InteractableId_Make("FramePicker"); size_t newValuesCount = 0; for (std::deque<FrameRecord>::const_reverse_iterator i =_frames.rbegin(); i!=_frames.rend(); ++i) { if (newValuesCount>=dimof(valuesBuffer)) { break; } int graphPartIndex = int(dimof(valuesBuffer)-newValuesCount-1); Rect graphPart( Coord2(LinearInterpolate(historyRect._topLeft[0], historyRect._bottomRight[0], (graphPartIndex)/float(dimof(valuesBuffer))), historyRect._topLeft[1]), Coord2(LinearInterpolate(historyRect._topLeft[0], historyRect._bottomRight[0], (graphPartIndex+1)/float(dimof(valuesBuffer))), historyRect._bottomRight[1])); InteractableId id = framePicker + newValuesCount; if (interfaceState.HasMouseOver(id)) { DrawRectangle(context, graphPart, ColorB(0x3f7f7f7fu)); } else if (i->_frameId == _lockedFrameId) { DrawRectangle(context, graphPart, ColorB(0x3f7f3f7fu)); } interactables.Register(Interactables::Widget(graphPart, id)); ++newValuesCount; } } } } void BufferUploadDisplay::DrawStatistics( IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState, const BufferUploads::CommandListMetrics& mostRecentResults) { using namespace BufferUploads; GPUMetrics gpuMetrics = CalculateGPUMetrics(); ////// TimeMarker transactionLatencySum = 0, commandListLatencySum = 0; unsigned transactionLatencyCount = 0, commandListLatencyCount = 0; for (auto i =_recentHistory.rbegin();i!=_recentHistory.rend(); ++i) { for (unsigned i2=0; i2<i->RetirementCount(); ++i2) { const AssemblyLineRetirement& retire = i->Retirement(i2); transactionLatencySum += retire._retirementTime - retire._requestTime; ++transactionLatencyCount; } commandListLatencySum += i->_commitTime - i->_resolveTime; ++commandListLatencyCount; } TimeMarker processingTimeSum = 0, waitTimeSum = 0; unsigned wakeCountSum = 0; size_t validFrameIndex = _frames.size()-1; for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i, --validFrameIndex) { if (i->_gpuCost != 0.f && i->_commandListStart != i->_commandListEnd) { break; } } if (validFrameIndex < _frames.size()) { for (unsigned cl=_frames[validFrameIndex]._commandListStart; cl<_frames[validFrameIndex]._commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; processingTimeSum += commandList._processingEnd - commandList._processingStart; waitTimeSum += commandList._waitTime; wakeCountSum += commandList._wakeCount; } } float averageTransactionLatency = transactionLatencyCount?float(double(transactionLatencySum/TimeMarker(transactionLatencyCount)) * _reciprocalTimerFrequency):0.f; float averageCommandListLatency = commandListLatencyCount?float(double(commandListLatencySum/TimeMarker(commandListLatencyCount)) * _reciprocalTimerFrequency):0.f; const auto lineHeight = 20u; const ColorB headerColor = ColorB::Blue; std::pair<std::string, unsigned> headers0[] = { std::make_pair("Name", 300), std::make_pair("Value", 3000) }; std::pair<std::string, unsigned> headers1[] = { std::make_pair("Name", 300), std::make_pair("Tex", 150), std::make_pair("VB", 150), std::make_pair("IB", 300) }; DrawTableHeaders(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), headerColor, &interactables); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Ave latency"), std::make_pair("Value", XlDynFormatString("%6.2f ms", averageTransactionLatency * 1000.f)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Command list latency"), std::make_pair("Value", XlDynFormatString("%6.2f ms", averageCommandListLatency * 1000.f)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "GPU theoretical MB/second"), std::make_pair("Value", XlDynFormatString("%6.2f MB/s", gpuMetrics._slidingAverageBytesPerSecond/float(1024.f*1024.f))) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "GPU ave cost"), std::make_pair("Value", XlDynFormatString("%6.2f ms", gpuMetrics._slidingAverageCostMS)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Thread activity"), std::make_pair("Value", XlDynFormatString("%6.3f%% (%i)", (float(processingTimeSum))?(100.f * (1.0f-(waitTimeSum/float(processingTimeSum)))):0.f, wakeCountSum)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Pending creates (peak)"), std::make_pair("Value", XlDynFormatString("%i (%i)", mostRecentResults._assemblyLineMetrics._queuedCreates, mostRecentResults._assemblyLineMetrics._queuedPeakCreates)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Pending uploads (peak)"), std::make_pair("Value", XlDynFormatString("%i (%i)", mostRecentResults._assemblyLineMetrics._queuedUploads, mostRecentResults._assemblyLineMetrics._queuedPeakUploads)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Pending staging creates (peak)"), std::make_pair("Value", XlDynFormatString("%i (%i)", mostRecentResults._assemblyLineMetrics._queuedStagingCreates, mostRecentResults._assemblyLineMetrics._queuedPeakStagingCreates)) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers0), { std::make_pair("Name", "Transaction count"), std::make_pair("Value", XlDynFormatString("%i/%i/%i", mostRecentResults._assemblyLineMetrics._transactionCount, mostRecentResults._assemblyLineMetrics._temporaryTransactionsAllocated, mostRecentResults._assemblyLineMetrics._longTermTransactionsAllocated)) }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// DrawTableHeaders(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), headerColor, &interactables); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), { std::make_pair("Name", "Recent creates"), std::make_pair("Tex", XlDynFormatString("%i", mostRecentResults._countCreations[UploadDataType::Texture])), std::make_pair("VB", XlDynFormatString("%i", mostRecentResults._countCreations[UploadDataType::Vertex])), std::make_pair("IB", XlDynFormatString("%i", mostRecentResults._countCreations[UploadDataType::Index])) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), { std::make_pair("Name", "Acc creates"), std::make_pair("Tex", XlDynFormatString("%i", _accumulatedCreateCount[UploadDataType::Texture])), std::make_pair("VB", XlDynFormatString("%i", _accumulatedCreateCount[UploadDataType::Vertex])), std::make_pair("IB", XlDynFormatString("%i", _accumulatedCreateCount[UploadDataType::Index])) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), { std::make_pair("Name", "Acc creates (MB)"), std::make_pair("Tex", XlDynFormatString("%8.3f MB", _accumulatedCreateBytes[UploadDataType::Texture] / (1024.f*1024.f))), std::make_pair("VB", XlDynFormatString("%8.3f MB", _accumulatedCreateBytes[UploadDataType::Vertex] / (1024.f*1024.f))), std::make_pair("IB", XlDynFormatString("%8.3f MB", _accumulatedCreateBytes[UploadDataType::Index] / (1024.f*1024.f))) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), { std::make_pair("Name", "Acc uploads"), std::make_pair("Tex", XlDynFormatString("%i", _accumulatedUploadCount[UploadDataType::Texture])), std::make_pair("VB", XlDynFormatString("%i", _accumulatedUploadCount[UploadDataType::Vertex])), std::make_pair("IB", XlDynFormatString("%i", _accumulatedUploadCount[UploadDataType::Index])) }); DrawTableEntry(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers1), { std::make_pair("Name", "Acc uploads (MB)"), std::make_pair("Tex", XlDynFormatString("%8.3f MB", _accumulatedUploadBytes[UploadDataType::Texture] / (1024.f*1024.f))), std::make_pair("VB", XlDynFormatString("%8.3f MB", _accumulatedUploadBytes[UploadDataType::Vertex] / (1024.f*1024.f))), std::make_pair("IB", XlDynFormatString("%8.3f MB", _accumulatedUploadBytes[UploadDataType::Index] / (1024.f*1024.f))) }); } void BufferUploadDisplay::DrawRecentRetirements( IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState) { const auto lineHeight = 20u; const ColorB headerColor = ColorB::Blue; std::pair<std::string, unsigned> headers[] = { std::make_pair("Name", 500), std::make_pair("Latency (ms)", 160), std::make_pair("Type", 80), std::make_pair("Description", 3000) }; DrawTableHeaders(context, layout.AllocateFullWidth(lineHeight), MakeIteratorRange(headers), headerColor, &interactables); unsigned frameCounter = 0; for (auto i=_frames.rbegin(); i!=_frames.rend(); ++i, ++frameCounter) { if (_lockedFrameId != ~unsigned(0x0) && i->_frameId != _lockedFrameId) { continue; } for (int cl=int(i->_commandListEnd)-1; cl>=int(i->_commandListStart); --cl) { const auto& commandList = _recentHistory[cl]; for (unsigned i2=0; i2<commandList.RetirementCount(); ++i2) { Rect rect = layout.AllocateFullWidth(lineHeight); if (!(IsGood(rect) && rect._bottomRight[1] < layout._maximumSize._bottomRight[1] && rect._topLeft[1] >= layout._maximumSize._topLeft[1])) break; const auto& retire = commandList.Retirement(i2); DrawTableEntry(context, rect, MakeIteratorRange(headers), { std::make_pair("Name", retire._desc._name), std::make_pair("Latency (ms)", XlDynFormatString("%6.2f", float(double(retire._retirementTime-retire._requestTime)*_reciprocalTimerFrequency*1000.))), std::make_pair("Type", TypeString(retire._desc)), std::make_pair("Description", BuildDescription(retire._desc)) }); } } } } void BufferUploadDisplay::Render(IOverlayContext* context, Layout& layout, Interactables& interactables, InterfaceState& interfaceState) { using namespace BufferUploads; CommandListMetrics mostRecentResults; unsigned commandListCount = 0; // Keep popping metrics from the upload manager until we stop getting valid ones BufferUploads::IManager* manager = _manager; if (manager) { for (;;) { CommandListMetrics metrics = manager->PopMetrics(); if (!metrics._commitTime) { break; } mostRecentResults = metrics; _recentHistory.push_back(metrics); AddCommandListToFrame(metrics._frameId, unsigned(_recentHistory.size()-1)); for (unsigned c=0; c<BufferUploads::UploadDataType::Max; ++c) { _accumulatedCreateCount[c] += metrics._countCreations[c]; _accumulatedCreateBytes[c] += metrics._bytesCreated[c]; _accumulatedUploadCount[c] += metrics._countUploaded[c]; _accumulatedUploadBytes[c] += metrics._bytesUploaded[c] + metrics._bytesUploadedDuringCreation[c]; } ++commandListCount; } } if (!mostRecentResults._commitTime && _recentHistory.size()) { mostRecentResults = _recentHistory[_recentHistory.size()-1]; } { ScopedLock(_gpuEventsBufferLock); ProcessGPUEvents_MT(AsPointer(_gpuEventsBuffer.begin()), AsPointer(_gpuEventsBuffer.end())); _gpuEventsBuffer.erase(_gpuEventsBuffer.begin(), _gpuEventsBuffer.end()); } // Present these frame by frame results visually. // But also show information about the recent history (retired textures, etc) layout.AllocateFullWidthFraction(0.01f); Layout menuBar = layout.AllocateFullWidthFraction(.125f); Layout displayArea = layout.AllocateFullWidthFraction(1.f); if (_graphsMode == GraphTabs::Statistics) { DrawStatistics(context, displayArea, interactables, interfaceState, mostRecentResults); } else if (_graphsMode == GraphTabs::RecentRetirements) { DrawRecentRetirements(context, displayArea, interactables, interfaceState); } else { DrawDisplay(context, displayArea, interactables, interfaceState); } DrawMenuBar(context, menuBar, interactables, interfaceState); } bool BufferUploadDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input) { if (interfaceState.TopMostId()) { if (input.IsRelease_LButton()) { InteractableId topMostWidget = interfaceState.TopMostId(); for (unsigned c=0; c<dimof(GraphTabs::Names); ++c) { if (topMostWidget == InteractableId_Make(GraphTabs::Names[c])) { _graphsMode = c; _graphMinValueHistory = _graphMaxValueHistory = 0.f; return true; } } const InteractableId framePicker = InteractableId_Make("FramePicker"); if (topMostWidget >= framePicker && topMostWidget < (framePicker+s_MaxGraphSegments)) { unsigned graphIndex = unsigned(topMostWidget - framePicker); _lockedFrameId = _frames[std::max(0,signed(_frames.size())-signed(graphIndex)-1)]._frameId; return true; } return false; } } return false; } void BufferUploadDisplay::AddCommandListToFrame(unsigned frameId, unsigned commandListIndex) { for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i) { if (i->_frameId == frameId) { if (i->_commandListStart == ~unsigned(0x0)) { i->_commandListStart = commandListIndex; i->_commandListEnd = commandListIndex+1; } else { assert(commandListIndex == i->_commandListEnd || commandListIndex == (i->_commandListEnd-1)); i->_commandListEnd = std::max(i->_commandListEnd, commandListIndex+1); } i->_gpuMetrics = CalculateGPUMetrics(); return; } else if (i->_frameId < frameId) { // We went too far and didn't find this frame... We'll have to insert it in as a new frame. FrameRecord newFrame; newFrame._frameId = frameId; newFrame._commandListStart = commandListIndex; newFrame._commandListEnd = commandListIndex+1; std::deque<FrameRecord>::iterator newItem = _frames.insert(i.base(),newFrame); newItem->_gpuMetrics = CalculateGPUMetrics(); return; } } FrameRecord newFrame; newFrame._frameId = frameId; newFrame._commandListStart = commandListIndex; newFrame._commandListEnd = commandListIndex+1; _frames.push_back(newFrame); _frames[_frames.size()-1]._gpuMetrics = CalculateGPUMetrics(); } void BufferUploadDisplay::AddGPUToCostToFrame(unsigned frameId, float gpuCost) { for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i) { if (i->_frameId == frameId) { i->_gpuCost += gpuCost; i->_gpuMetrics = CalculateGPUMetrics(); return; } else if (i->_frameId < frameId) { // we went too far and didn't find this frame... We'll have to insert it in as a new frame. FrameRecord newFrame; newFrame._frameId = frameId; newFrame._gpuCost = gpuCost; std::deque<FrameRecord>::iterator newItem = _frames.insert(i.base(),newFrame); newItem->_gpuMetrics = CalculateGPUMetrics(); return; } } FrameRecord newFrame; newFrame._frameId = frameId; newFrame._gpuCost = gpuCost; _frames.push_back(newFrame); _frames[_frames.size()-1]._gpuMetrics = CalculateGPUMetrics(); } BufferUploadDisplay::GPUMetrics BufferUploadDisplay::CalculateGPUMetrics() { ////// // calculate the GPU upload speed... How much GPU time should we expect to consume per mb uploaded, // based on a sliding average BufferUploadDisplay::GPUMetrics result; result._slidingAverageBytesPerSecond = 0; result._slidingAverageCostMS = 0.f; unsigned framesCountWithValidGPUCost = (unsigned)_frames.size(); for (std::deque<FrameRecord>::reverse_iterator i=_frames.rbegin(); i!=_frames.rend(); ++i, --framesCountWithValidGPUCost) { if (i->_gpuCost != 0.f && i->_commandListStart != i->_commandListEnd) { break; } } const unsigned samples = std::min(unsigned(framesCountWithValidGPUCost), 256u); std::deque<FrameRecord>::const_iterator gI = _frames.begin() + (_frames.size()-samples); float totalGPUCost = 0.f; unsigned totalBytesUploaded = 0; for (unsigned c=0; c<samples; ++c, ++gI) { float gpuCost = gI->_gpuCost; unsigned bytesUploaded = 0; for (unsigned cl=gI->_commandListStart; cl<gI->_commandListEnd; ++cl) { BufferUploads::CommandListMetrics& commandList = _recentHistory[cl]; for (unsigned c2=0; c2<BufferUploads::UploadDataType::Max; ++c2) { bytesUploaded += commandList._bytesUploaded[c2] + commandList._bytesUploadedDuringCreation[c2]; } } totalGPUCost += gpuCost; totalBytesUploaded += bytesUploaded; } if (totalGPUCost) { result._slidingAverageBytesPerSecond = unsigned(totalBytesUploaded / (totalGPUCost/1000.f)); } if (samples) { result._slidingAverageCostMS = totalGPUCost / float(samples); } return result; } void BufferUploadDisplay::ProcessGPUEvents(const void* eventsBufferStart, const void* eventsBufferEnd) { ScopedLock(_gpuEventsBufferLock); size_t oldSize = _gpuEventsBuffer.size(); size_t eventsBufferSize = ptrdiff_t(eventsBufferEnd) - ptrdiff_t(eventsBufferStart); _gpuEventsBuffer.resize(_gpuEventsBuffer.size() + eventsBufferSize); memcpy(&_gpuEventsBuffer[oldSize], eventsBufferStart, eventsBufferSize); } void BufferUploadDisplay::ProcessGPUEvents_MT(const void* eventsBufferStart, const void* eventsBufferEnd) { const void * evnt = eventsBufferStart; while (evnt < eventsBufferEnd) { uint32 eventType = (uint32)*((const size_t*)evnt); evnt = PtrAdd(evnt, sizeof(size_t)); if (eventType == ~uint32(0x0)) { size_t frameId = *((const size_t*)evnt); evnt = PtrAdd(evnt, sizeof(size_t)); GPUTime frequency = *((const uint64*)evnt); evnt = PtrAdd(evnt, sizeof(uint64)); _mostRecentGPUFrequency = frequency; _mostRecentGPUFrameId = (unsigned)frameId; } else { const char* eventName = *((const char**)evnt); evnt = PtrAdd(evnt, sizeof(const char*)); assert((size_t(evnt)%sizeof(uint64))==0); uint64 timeValue = *((const uint64*)evnt); evnt = PtrAdd(evnt, sizeof(uint64)); if (eventName && !XlCompareStringI(eventName, "GPU_UPLOAD")) { if (eventType == 0) { _lastUploadBeginTime = timeValue; } else { if (_lastUploadBeginTime) { _mostRecentGPUCost = float(double(timeValue - _lastUploadBeginTime) / double(_mostRecentGPUFrequency) * 1000.); // write this result into the GPU time for any frames that need it... AddGPUToCostToFrame(_mostRecentGPUFrameId, _mostRecentGPUCost); } } } } } } BufferUploadDisplay* BufferUploadDisplay::s_gpuListenerDisplay = 0; void BufferUploadDisplay::GPUEventListener(const void* eventsBufferStart, const void* eventsBufferEnd) { if (s_gpuListenerDisplay) { s_gpuListenerDisplay->ProcessGPUEvents(eventsBufferStart, eventsBufferEnd); } } //////////////////////////////////////////////////////////////////// ResourcePoolDisplay::ResourcePoolDisplay(BufferUploads::IManager* manager) { _manager = manager; _filter = 0; _detailsIndex = 0; _graphMin = _graphMax = 0.f; } ResourcePoolDisplay::~ResourcePoolDisplay() { } namespace ResourcePoolDisplayTabs { static const char* Names[] = { "Index Buffers", "Vertex Buffers", "Staging Textures" }; } bool ResourcePoolDisplay::Filter(const BufferUploads::BufferDesc& desc) { if (_filter == 0 && (desc._bindFlags&BufferUploads::BindFlag::IndexBuffer)) return true; if (_filter == 1 && (desc._bindFlags&BufferUploads::BindFlag::VertexBuffer)) return true; if (_filter == 2 && (desc._type == BufferUploads::BufferDesc::Type::Texture)) return true; return false; } static const InteractableId ResourcePoolDisplayGraph = InteractableId_Make("ResourcePoolDisplayGraph"); void ResourcePoolDisplay::Render(IOverlayContext* context, Layout& layout, Interactables&interactables, InterfaceState& interfaceState) { using namespace BufferUploads; IManager* manager = _manager; if (manager) { PoolSystemMetrics metrics = manager->CalculatePoolMetrics(); ///////////////////////////////////////////////////////////////////////////// const std::vector<PoolMetrics>& metricsVector = (_filter==2)?metrics._stagingPools:metrics._resourcePools; unsigned maxSize = 0, count = 0; for (std::vector<PoolMetrics>::const_iterator i=metricsVector.begin();i!=metricsVector.end(); ++i) { if (Filter(i->_desc)) { maxSize = std::max(maxSize, i->_peakSize); ++count; } } ///////////////////////////////////////////////////////////////////////////// layout.AllocateFullWidth(128); // leave some space at the top Layout buttonsLayout(layout.AllocateFullWidth(32)); for (unsigned c=0; c<dimof(ResourcePoolDisplayTabs::Names); ++c) { DrawButton(context, ResourcePoolDisplayTabs::Names[c], buttonsLayout.AllocateFullHeightFraction(1.f/float(dimof(ResourcePoolDisplayTabs::Names))), interactables, interfaceState); } if (count) { ///////////////////////////////////////////////////////////////////////////// Rect barChartRect = layout.AllocateFullWidth(400); Layout barsLayout(barChartRect); barsLayout._paddingBetweenAllocations = 4; const unsigned barWidth = (barChartRect.Width() - (count-1) * barsLayout._paddingBetweenAllocations - 2*barsLayout._paddingInternalBorder) / count; static ColorB rectColor(96, 192, 170, 128); static ColorB peakMarkerColor(192, 64, 64, 128); static ColorB textColour(192, 192, 192, 128); ///////////////////////////////////////////////////////////////////////////// unsigned c=0; const PoolMetrics* detailsMetrics = NULL; for (std::vector<PoolMetrics>::const_iterator i=metricsVector.begin(); i!=metricsVector.end(); ++i) { if (Filter(i->_desc)) { float A = i->_currentSize / float(maxSize); float B = i->_peakSize / float(maxSize); Rect fullRect = barsLayout.AllocateFullHeight(barWidth); Rect colouredRect(Coord2(fullRect._topLeft[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-A)), fullRect._bottomRight); DrawRectangle(context, colouredRect, rectColor); DrawRectangle(context, Rect( Coord2(fullRect._topLeft[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-B)), Coord2(fullRect._bottomRight[0], LinearInterpolate(fullRect._topLeft[1], fullRect._bottomRight[1], 1.f-B)+2)), peakMarkerColor); Rect textRect(colouredRect._topLeft, Coord2(colouredRect._bottomRight[0], colouredRect._topLeft[1]+10)); if (i->_peakSize) { const BufferDesc& desc = i->_desc; if (desc._type == BufferDesc::Type::LinearBuffer) { if (desc._bindFlags & BindFlag::IndexBuffer) { DrawFormatText(context, textRect, nullptr, textColour, "IB %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f); } else if (desc._bindFlags & BindFlag::VertexBuffer) { DrawFormatText(context, textRect, nullptr, textColour, "VB %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f); } else { DrawFormatText(context, textRect, nullptr, textColour, "B %6.2fk", desc._linearBufferDesc._sizeInBytes / 1024.f); } } else if (desc._type == BufferDesc::Type::Texture) { DrawFormatText(context, textRect, nullptr, textColour, "Tex %ix%i", desc._textureDesc._width, desc._textureDesc._height); } textRect._topLeft[1] += 16; textRect._bottomRight[1] += 16; if (i->_currentSize) { DrawFormatText(context, textRect, nullptr, textColour, "%i (%6.3fMB)", i->_currentSize, (i->_currentSize * manager->ByteCount(i->_desc)) / (1024.f*1024.f)); } } InteractableId id = ResourcePoolDisplayGraph+c; if (_detailsIndex==c) { detailsMetrics = &(*i); } interactables.Register(Interactables::Widget(fullRect, id)); ++c; } } if (detailsMetrics) { _detailsHistory.push_back(*detailsMetrics); Rect textRect = layout.AllocateFullWidth(32); DrawFormatText(context, textRect, nullptr, textColour, "Real size: %6.2fMB, Created size: %6.2fMB, Padding overhead: %6.2fMB, Count: %i", detailsMetrics->_totalRealSize/(1024.f*1024.f), detailsMetrics->_totalCreateSize/(1024.f*1024.f), (detailsMetrics->_totalCreateSize-detailsMetrics->_totalRealSize)/(1024.f*1024.f), detailsMetrics->_totalCreateCount); Rect historyRect = layout.AllocateFullWidth(200); float historyValues[256]; unsigned historyCount = 0; for (std::vector<PoolMetrics>::const_reverse_iterator i=_detailsHistory.rbegin(); i!=_detailsHistory.rend() && historyCount < dimof(historyValues); ++i, ++historyCount) { historyValues[historyCount] = float(i->_recentReleaseCount); } DrawHistoryGraph(context, historyRect, historyValues, historyCount, dimof(historyValues), _graphMin, _graphMax); } } } } bool ResourcePoolDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input) { if (interfaceState.TopMostId()) { if (input.IsRelease_LButton()) { InteractableId topMostWidget = interfaceState.TopMostId(); if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[0])) { _filter = 0; return true; } else if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[1])) { _filter = 1; return true; } else if (topMostWidget == InteractableId_Make(ResourcePoolDisplayTabs::Names[2])) { _filter = 2; return true; } else if (topMostWidget >= ResourcePoolDisplayGraph && topMostWidget < ResourcePoolDisplayGraph+100) { _detailsIndex = unsigned(topMostWidget-ResourcePoolDisplayGraph); _detailsHistory.clear(); return true; } } } return false; } //////////////////////////////////////////////////////////////////// static const unsigned FramesOfWarmth = 60; void BatchingDisplay::Render(IOverlayContext* context, Layout& layout, Interactables&interactables, InterfaceState& interfaceState) { using namespace BufferUploads; IManager* manager = _manager; if (manager) { PoolSystemMetrics poolMetrics = manager->CalculatePoolMetrics(); const BatchingSystemMetrics& metrics = poolMetrics._batchingSystemMetrics; layout.AllocateFullWidth(32); // leave some space at the top static ColorB textColour(192, 192, 192, 128); static ColorB unallocatedLineColour(192, 192, 192, 128); unsigned allocatedSpace = 0, unallocatedSpace = 0; unsigned largestFreeBlock = 0; unsigned largestHeapSize = 0; unsigned totalBlockCount = 0; for (std::vector<BatchedHeapMetrics>::const_iterator i=metrics._heaps.begin(); i!=metrics._heaps.end(); ++i) { allocatedSpace += i->_allocatedSpace; unallocatedSpace += i->_unallocatedSpace; largestFreeBlock = std::max(largestFreeBlock, i->_largestFreeBlock); largestHeapSize = std::max(largestHeapSize, i->_heapSize); totalBlockCount += i->_referencedCountedBlockCount; } { DrawFormatText(context, layout.AllocateFullWidth(16), nullptr, textColour, "Heap count: %i / Total allocated: %7.3fMb / Total unallocated: %7.3fMb", metrics._heaps.size(), allocatedSpace/(1024.f*1024.f), unallocatedSpace/(1024.f*1024.f)); DrawFormatText(context, layout.AllocateFullWidth(16), nullptr, textColour, "Largest free block: %7.3fKb / Average unallocated: %7.3fKb", largestFreeBlock/1024.f, unallocatedSpace/(float(metrics._heaps.size())*1024.f)); DrawFormatText(context, layout.AllocateFullWidth(16), nullptr, textColour, "Block count: %i / Ave block size: %7.3fKb", totalBlockCount, allocatedSpace/float(totalBlockCount*1024.f)); } unsigned currentFrameId = GetFrameID(); { const unsigned lineHeight = 4; Rect outsideRect = layout.AllocateFullWidth(DebuggingDisplay::Coord(metrics._heaps.size()*lineHeight + layout._paddingInternalBorder*2)); Rect heapAllocationDisplay = Layout(outsideRect).AllocateFullWidthFraction(100.f); DrawRectangleOutline(context, outsideRect); std::vector<Float3> lines; std::vector<ColorB> lineColors; lines.reserve(metrics._heaps.size()*lineHeight*2*10); lineColors.reserve(metrics._heaps.size()*lineHeight*10); float X = heapAllocationDisplay.Width() / float(largestHeapSize); unsigned y = heapAllocationDisplay._topLeft[1]; for (std::vector<BatchedHeapMetrics>::const_iterator i=metrics._heaps.begin(); i!=metrics._heaps.end(); ++i) { unsigned heapIndex = (unsigned)std::distance(metrics._heaps.begin(), i); unsigned lastStart = 0; const bool drawAllocated = true; for (std::vector<unsigned>::const_iterator i2=i->_markers.begin(); (i2+1)<i->_markers.end(); i2+=2) { unsigned start, end; if (drawAllocated) { start = lastStart; end = *i2; } else { start = *i2; end = *(i2+1); } if (start != end) { float warmth = CalculateWarmth(heapIndex, start, end, drawAllocated); ColorB col = ColorB::FromNormalized(warmth, 0.f, 1.0f-warmth); for (unsigned c=0; c<lineHeight; ++c) { const Coord x = Coord(start*X + heapAllocationDisplay._topLeft[0]); lines.push_back(AsPixelCoords(Coord2(x, y+c))); lines.push_back(AsPixelCoords(Coord2(std::max(x+1, Coord(end*X + heapAllocationDisplay._topLeft[0])), y+c))); lineColors.push_back(col); lineColors.push_back(col); } } lastStart = *(i2+1); } y += lineHeight; } if (!lines.empty()) { context->DrawLines(ProjectionMode::P2D, AsPointer(lines.begin()), (uint32)lines.size(), AsPointer(lineColors.begin())); } } _lastFrameMetrics = metrics; // extinquish cooling spans for (std::vector<WarmSpan>::iterator i=_warmSpans.begin(); i!=_warmSpans.end();) { if (i->_frameStart <= (currentFrameId-FramesOfWarmth)) { i = _warmSpans.erase(i); } else { ++i; } } } } float BatchingDisplay::CalculateWarmth(unsigned heapIndex, unsigned begin, unsigned end, bool allocatedMode) { const unsigned currentFrameId = GetFrameID(); for (std::vector<WarmSpan>::const_iterator i=_warmSpans.begin(); i!=_warmSpans.end(); ++i) { if (i->_heapIndex == heapIndex && i->_begin == begin && i->_end == end) { return 1.f-std::min((currentFrameId-i->_frameStart)/float(FramesOfWarmth), 1.f); } } const bool thereLastFrame = FindSpan(heapIndex, begin, end, allocatedMode); if (!thereLastFrame) { WarmSpan warmSpan; warmSpan._heapIndex = heapIndex; warmSpan._begin = begin; warmSpan._end = end; warmSpan._frameStart = currentFrameId; _warmSpans.push_back(warmSpan); return 1.f; } return 0.f; } bool BatchingDisplay::FindSpan(unsigned heapIndex, unsigned begin, unsigned end, bool allocatedMode) { if (heapIndex >= _lastFrameMetrics._heaps.size()) { return false; } unsigned lastStart = 0; for (std::vector<unsigned>::const_iterator i2=_lastFrameMetrics._heaps[heapIndex]._markers.begin(); (i2+1)<_lastFrameMetrics._heaps[heapIndex]._markers.end(); i2+=2) { unsigned spanBegin, spanEnd; if (allocatedMode) { spanBegin = lastStart; spanEnd = *i2; } else { spanBegin = *i2; spanEnd = *(i2+1); } if (begin == spanBegin && end == spanEnd) { return true; } lastStart = *(i2+1); } return false; } bool BatchingDisplay::ProcessInput(InterfaceState& interfaceState, const InputSnapshot& input) { return false; } BatchingDisplay::BatchingDisplay(BufferUploads::IManager* manager) : _manager(manager) { } BatchingDisplay::~BatchingDisplay() { } }}
51.145998
293
0.587983
[ "render", "vector" ]
ad5b38c6937f8364a53cbfd66d05baaddb431d3a
2,608
cpp
C++
multiview/multiview_cpp/src/perceive/geometry/line-2d.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
5
2021-09-03T23:12:08.000Z
2022-03-04T21:43:32.000Z
multiview/multiview_cpp/src/perceive/geometry/line-2d.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
3
2021-09-08T02:57:46.000Z
2022-02-26T05:33:02.000Z
multiview/multiview_cpp/src/perceive/geometry/line-2d.cpp
prcvlabs/multiview
1a03e14855292967ffb0c0ec7fff855c5abbc9d2
[ "Apache-2.0" ]
2
2021-09-26T03:14:40.000Z
2022-01-26T06:42:52.000Z
#include "line-2d.hpp" #include "perceive/utils/eigen-helpers.hpp" #include "stdinc.hpp" namespace perceive { template<typename T> Vector3r fit_2d_line_T(const T* Xs, unsigned N, unsigned stride) { Vector3r line; MatrixXr A(N, 3); for(unsigned i = 0; i < N; ++i) { for(unsigned j = 0; j < 3; ++j) A(i, j) = (*Xs)(int(j)); Xs += stride; } MatrixXr At = A.transpose(); Matrix3r AtA = At * A; svd_thin(AtA, line); line /= sqrt(line(0) * line(0) + line(1) * line(1)); return line; } // Vector3d fit_2d_line(const Vector3d * Xs, unsigned N, unsigned stride) // { // auto X = fit_2d_line_T<Vector3d>(Xs, N, stride); // Vector3d Z; // Z(0) = X(0); // Z(1) = X(1); // Z(2) = X(2); // return Z; // } Vector3r fit_2d_line(const Vector3r* Xs, unsigned N, unsigned stride) { return fit_2d_line_T<Vector3r>(Xs, N, stride); } Vector3 fit_2d_line(const Vector3* Xs, unsigned N, unsigned stride) { auto L = fit_2d_line_T<Vector3>(Xs, N, stride); return to_vec3(L); } Vector3 fit_line(const vector<Vector2>& Xs, const vector<unsigned>& inds) { struct TLParams { MatrixXr M1; MatrixXr M2; MatrixXr MtM; VectorXr thin; }; static thread_local TLParams tl; // Choose the matrix int sz = int(inds.size()); MatrixXr& M = (tl.M1.rows() == sz || tl.M1.rows() == 0) ? tl.M1 : tl.M2; MatrixXr& MtM = tl.MtM; // Fix dimensions if(M.rows() != int(inds.size()) || M.cols() != 3) M = MatrixXr::Zero(long(inds.size()), 3); if(MtM.rows() != 3) tl.MtM = MatrixXr::Zero(3, 3); if(tl.thin.rows() != 3) tl.thin = VectorXr::Zero(3); // Get the line centre Vector2 C(0.0, 0.0); for(const auto ind : inds) C += Xs[ind]; C /= real(inds.size()); // Fill 'M' for(unsigned row = 0; row < inds.size(); ++row) { const auto& X = Xs[inds[row]] - C; M(row, 0) = X.x; M(row, 1) = X.y; M(row, 2) = 1.0; } // Calculate 'MtM' auto calc_dot = [](const MatrixXr& M, unsigned i, unsigned j) { double val = 0.0; unsigned sz = unsigned(M.cols()); for(unsigned k = 0; k < sz; ++k) val += M(i, k) * M(k, j); return val; }; for(unsigned i = 0; i < 3; ++i) for(unsigned j = 0; j < 3; ++j) MtM(i, j) = calc_dot(M, i, j); // Get the line equation auto err = svd_thin(MtM, tl.thin); auto line = Vector3(tl.thin(0), tl.thin(1), tl.thin(2)); auto scale = sqrt(square(line.x) + square(line.y)); line /= scale; line.z = -(C.x * line.x + C.y * line.y); return line; } } // namespace perceive
25.821782
77
0.559816
[ "vector" ]
ad5be264c43ab996c869da43c215f5bb97fc421a
22,541
cpp
C++
z2clib/Scanner.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
z2clib/Scanner.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
z2clib/Scanner.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
#include "Scanner.h" char tab1[24] = { '+', '-', '*', '/', '=', ';', '(', ')', '.', '<', '>', '&', ',', '%', '|', '^', ':', '!', '[', ']', '@', '~', '?', '#' }; char tab2[9] = { '<', '>', '=', '!', '<', '>', ':', '+', '-' }; char tab3[9] = { '<', '>', '=', '=', '=', '=', ':', '+', '-' }; void Scanner::Scan(bool cond) { while (!parser.IsEof()) { if (parser.Id("using")) ScanUsing(); else if (parser.Id("namespace")) ScanNamespace(); else if (parser.Id("alias")) ScanAlias(); else if (parser.Id("static")) { parser.ExpectId("class"); ScanClass(true); } else if (parser.Id("class")) ScanClass(); else if (parser.Id("enum")) ScanEnum(); else if (cond && parser.EatIf()) ScanIf(); else if (!cond && (parser.IsElse() || parser.IsEndIf())) return; else if (parser.Char('#')) { Point p = parser.GetPoint(); parser.ExpectId("pragma"); parser.ExpectId("nl"); parser.SkipNewLines(false); source.SkipNewLines = false; } else { Point p = parser.GetPoint(); parser.Error(p, "syntax error: " + parser.Identify() + " found"); } } parser.SkipNewLines(true); for (int i = 0; i < source.References.GetCount(); i++) { if (source.References[i].Find(".") == -1) { source.References[i] = nameSpace + source.References[i]; } } } void Scanner::ScanIf() { String id1 = parser.ExpectId(); parser.Expect('.'); String id2 = parser.ExpectId(); parser.Expect('='); parser.Expect('='); String id3 = parser.ReadString(); if (id3 == "WIN32") { if (win) { Scan(false); if (parser.EatElse()) { parser.SkipBlock(); parser.EatEndIf(); } else { parser.EatEndIf(); } } else { parser.SkipBlock(); if (parser.EatElse()) { Scan(false); parser.EatEndIf(); } else { parser.EatEndIf(); } } } else { } } void Scanner::ScanIf(ZClass& cls) { String id1 = parser.ExpectId(); parser.Expect('.'); String id2 = parser.ExpectId(); parser.Expect('='); parser.Expect('='); String id3 = parser.ReadString(); if (id3 == "WIN32") { if (win) { ClassLoop(cls, false); if (parser.EatElse()) { parser.SkipBlock(); parser.EatEndIf(); } else { parser.EatEndIf(); } } else { parser.SkipBlock(); if (parser.EatElse()) { ClassLoop(cls, false); parser.EatEndIf(); } else { parser.EatEndIf(); } } } else { } } void Scanner::ScanAlias() { Point location = parser.GetPoint(); String name = parser.ExpectId(); String nspace = nameSpace; String fullName = nspace; fullName << name; int index = source.Aliases.Find(fullName); if (index != -1) { ZClassAlias& alias = source.Aliases[index]; parser.Dup(location, alias.Location, fullName); return; } source.ClassNameList.FindAdd(fullName); ZClassAlias& alias = source.Aliases.Add(fullName); alias.Name = name; alias.Namespace = nspace; alias.Location = location; alias.Source = &source; parser.Expect('='); alias.Context = parser.GetPos(); ScanType(); parser.ExpectEndStat(); } void Scanner::ScanUsing() { Point p = parser.GetPoint(); String path = parser.ExpectId(); String last = ""; while (parser.Char('.')) { if (last.GetLength() != 0) path << '.' << last; last = parser.ExpectId(); } if (last.GetLength()) { path << '.'; path << last; } parser.ExpectEndStat(); source.References.Add(path); source.ReferencePos.Add(p); } void Scanner::ScanNamespace() { String path = parser.ExpectId(); String total = path; total << "."; while (parser.Char('.')) { path = parser.ExpectId(); total << path << "."; } parser.ExpectEndStat(); nameSpace = total; } void Scanner::ScanClass(bool foreceStatic) { Point pos = parser.GetPoint(); String name = parser.ExpectId(); String tname; bool tplate = false; if (parser.Char('<')) { tname = parser.ExpectId(); parser.Expect(':'); parser.ExpectId("Class"); parser.Expect('>'); tplate = true; } ZClass& cls = source.AddClass(name, nameSpace, pos); cls.Scan.IsTemplate = tplate; cls.Scan.TName = tname; cls.MContName = cls.Scan.Name; pos = parser.GetPoint(); if (parser.Char(':')) { cls.Super.Point = pos; cls.Super.Name = parser.ExpectId(); if (cls.Super.Name == name) parser.Error(pos, "class can't inherit from itself"); cls.Super.IsEvaluated = false; if (parser.Char('<')) { cls.Super.TName = parser.ExpectId(); parser.Expect('>'); } } else cls.Super.IsEvaluated = true; cls.Source = &source; String fullName = cls.Scan.Namespace; fullName << cls.Scan.Name; source.References.Add(fullName); source.ReferencePos.Add(cls.Position); source.ClassNameList.FindAdd(fullName); insertAccess = Entity::atPublic; parser.Expect('{'); parser.EatNewlines(); ClassLoop(cls, true, foreceStatic); while (true) { if (parser.Id("private")) { insertAccess = Entity::atPrivate; parser.Expect('{'); parser.EatNewlines(); ClassLoop(cls, true, foreceStatic); } else if (parser.Id("protected")) { insertAccess = Entity::atProtected; parser.Expect('{'); parser.EatNewlines(); ClassLoop(cls, true, foreceStatic); } else break; } for (int i = 0; i < cls.Props.GetCount(); i++) { Def& def = cls.Props[i]; for (int j = 0; j < def.Overloads.GetCount(); j++) { Overload& ol = def.Overloads[j]; if (ol.IsGetter == false && ol.Params.GetCount()) for (int k = 0; k < ol.Params.GetCount(); k++) { for (int m = 0; m < cls.Vars.GetCount(); m++) if (cls.Vars[m].Name == ol.Params[k].Name) parser.Dup(ol.Params[k].Location, cls.Vars[m].Location, cls.Vars[m].Name); } } } } void Scanner::ScanEnum() { Point pos = parser.GetPoint(); String name = parser.ExpectId(); ZClass& cls = source.AddClass(name, nameSpace, pos); cls.MContName = cls.Scan.Name; cls.BackendName = cls.Scan.Name; cls.CoreSimple = true; pos = parser.GetPoint(); cls.Source = &source; String fullName = cls.Scan.Namespace; fullName << cls.Scan.Name; source.References.Add(fullName); source.ReferencePos.Add(cls.Position); source.ClassNameList.FindAdd(fullName); insertAccess = Entity::atPublic; cls.Scan.IsEnum = true; parser.Expect('{'); while (!parser.IsChar('}')) { Point p = parser.GetPoint(); int n = 0; while (parser.IsZId()) { Point pnt = parser.GetPoint(); String name = parser.ExpectId(); cls.TestDup(name, pnt, parser, false); Constant& cst = cls.AddConst(name); cst.Location = pnt; cst.Skip = parser.GetPos(); cst.Access = insertAccess; cst.IsEvaluated = true; cst.IVal = n++; if (parser.Char(',')) { } else if (parser.IsChar('}')) { } else parser.Error(pnt, "syntax error: " + parser.Identify() + " found"); } } parser.Expect('}'); while (true) { if (parser.Id("private")) { insertAccess = Entity::atPrivate; EnumLoop(cls); } else if (parser.Id("protected")) { insertAccess = Entity::atProtected; EnumLoop(cls); } else if (parser.Id("public")) { insertAccess = Entity::atPublic; EnumLoop(cls); } else break; } } void Scanner::InterpretTrait(const String& trait) { if (trait == "bindc") bindName = trait; else if (trait == "intrinsic") isIntrinsic = true; else if (trait == "dllimport") isDllImport = true; else if (trait == "stdcall") isStdCall = true; else if (trait == "cdecl") isCDecl = true; else if (trait == "nodoc") isNoDoc = true; else if (trait == "force") isForce = true; } void Scanner::TraitLoop() { bindName = ""; isIntrinsic = false; isDllImport = false; isStdCall = false; isCDecl = false; isNoDoc = false; isForce = false; if (parser.Char2('@', '[')) { String trait = parser.ExpectId(); InterpretTrait(trait); while (!parser.IsChar(']')) { parser.Expect(','); trait = parser.ExpectId(); InterpretTrait(trait); } parser.Expect(']'); } } void Scanner::ClassLoop(ZClass& cls, bool cond, bool foreceStatic) { while (!parser.IsChar('}')) { Point p = parser.GetPoint(); TraitLoop(); if (parser.Id("def")) ScanDef(cls, false, foreceStatic); else if (parser.Id("func")) ScanDef(cls, false, foreceStatic, 0, true); else if (parser.Id("this")) ScanDef(cls, true, foreceStatic); else if (parser.Id("const")) ScanConst(cls); else if (parser.Id("val")) ScanVar(cls); else if (parser.Id("property")) ScanProperty(cls); else if (parser.Id("static")) { if (parser.IsId("const")) parser.Error(p, "constants are already static"); else if (parser.Id("def")) ScanDef(cls, false, true); else if (parser.Id("func")) ScanDef(cls, false, true, 0, true); else if (parser.IsId("this")) parser.Error(p, "current version of the compiler does not support static constructors"); else if (parser.Id("val")) ScanVar(cls, true); else if (parser.Id("property")) ScanProperty(cls, true); else if (parser.Id("virtual") || parser.Id("override")) parser.Error(p, "virtual methods can't be static"); } else if (parser.Id("virtual")) { parser.ExpectId("def"); cls.Scan.HasVirtuals = true; ScanDef(cls, false, false, 1); } else if (parser.Id("override")) { if (cls.Super.Name.GetLength() == 0) parser.Error(p, "class '\f" + cls.Scan.Name + "\f' does not use inheritence, there is nothing to override"); parser.ExpectId("def"); cls.Scan.HasVirtuals = true; ScanDef(cls, false, false, 2); } else if (cond && parser.EatIf()) ScanIf(cls); else if (!cond && (parser.IsElse() || parser.IsEndIf())) return; else if (parser.Char('#')) { if (parser.Id("region")) parser.ExpectId(); else if (!parser.Id("endregion")) { Point p2 = parser.GetPoint(); parser.Error(p2, "syntax error: # followed by invalid directive"); } } else if (parser.Char('~')) { parser.ExpectId("this"); parser.Expect('('); if (cls.Dest) parser.Dup(p, cls.Dest->Location, cls.Scan.Name + "::~"); cls.Dest = new Def(); cls.Dest->Name = "~this"; cls.Dest->Class = &cls; Overload& over = cls.Dest->Add("~this", "~" + cls.BackendName, insertAccess, false); over.Skip = parser.GetPos(); over.CPosPar = parser.GetPos(); over.Location = parser.GetPoint(); over.IsDeclared = true; over.IsDest = true; parser.Expect(')'); parser.Expect('{'); over.Skip = parser.GetPos(); ScanBlock(); } else parser.Error(p, "syntax error: constant, variable, method, constructor or property definiton expected, " + parser.Identify() + " found"); } parser.Expect('}'); parser.EatNewlines(); } void Scanner::EnumLoop(ZClass& cls) { parser.Expect('{'); parser.EatNewlines(); while (!parser.IsChar('}')) { Point p = parser.GetPoint(); if (parser.Id("def")) ScanDef(cls, false); else if (parser.Id("func")) ScanDef(cls, false, false, 0, true); else if (parser.Id("this")) ScanDef(cls, true); else if (parser.Id("property")) ScanProperty(cls); else if (parser.Id("static")) { if (parser.IsId("const")) parser.Error(p, "constants are already static"); else if (parser.Id("def")) ScanDef(cls, false, true); else if (parser.IsId("this")) parser.Error(p, "current version of the compiler does not support static constructors"); else if (parser.Id("val")) ScanVar(cls, true); else if (parser.IsId("property")) ScanProperty(cls, true); } else if (parser.Char('#')) { if (parser.Id("region")) parser.ExpectId(); else if (!parser.Id("endregion")) parser.Error(p, "syntax error: # followed by invalid directive"); } else parser.Error(p, "syntax error: constant, variable, method, constructor or property definiton expected, " + parser.Identify() + " found"); } parser.Expect('}'); parser.EatNewlines(); } void Scanner::ScanConst(ZClass& cls) { Point pnt = parser.GetPoint(); String name = parser.ExpectId(); cls.TestDup(name, pnt, parser, false); Constant& cst = cls.AddConst(name); cst.Location = pnt; cst.Skip = parser.GetPos(); cst.Access = insertAccess; if (parser.Char(':')) ScanType(); if (parser.Char('=')) while (!parser.IsChar(';')) ScanToken(); parser.ExpectEndStat(); } void Scanner::ScanVar(ZClass& cls, bool stat) { Point pnt = parser.GetPoint(); String name = parser.ExpectId(); cls.TestDup(name, pnt, parser, true); Variable& var = cls.AddVar(name); var.Location = pnt; var.Skip = parser.GetPos(); var.Access = insertAccess; var.IsStatic = stat; if (parser.Char(':')) ScanType(); if (parser.Char('=')) while (!parser.IsChar(';')) ScanToken(); parser.ExpectEndStat(); } void Scanner::ScanProperty(ZClass& cls, bool stat) { Point pnt = parser.GetPoint(); String name, bname; if (parser.Char('@')) { String s = parser.ExpectId(); if (s != "index") parser.Error(pnt, "invalid operator for overloading"); name = "@" + s; bname = "_" + s; } else { name = parser.ExpectId(); bname = name; } cls.TestDup(name, pnt, parser, true); Def& prop = cls.Props.Add(name); prop.Name = name; prop.BackendName = bname; prop.Class = &cls; if (prop.Pos.GetCount() == 0) prop.Pos.Add(parser.GetPos()); prop.IsStatic = stat; prop.Location = pnt; if (parser.Char('=')) { parser.ExpectId(); parser.ExpectEndStat(); return; } parser.Expect(':'); if (parser.Id("const")) parser.ExpectId("ref"); ScanType(); int get = 0, set = 0; while (true) { TraitLoop(); if (parser.Id("get")) { Overload& over = prop.Add(name, insertAccess, stat); over.Location = pnt; over.Skip = parser.GetPos(); over.CPosPar = parser.GetPos(); over.IsProp = true; over.IsGetter = true; over.BackendName = bname; prop.HasPGetter = &over; over.IsIntrinsic = isIntrinsic; if (parser.Id("const")) over.IsConst = true; if (parser.Char('[')) { Variable& p = over.Params.Add(); p.Name = parser.ExpectId(); parser.Expect(':'); p.Skip = parser.GetPos(); ScanType(); parser.Expect(']'); over.IsIndex = true; } Point bp = parser.GetPoint(); if (isIntrinsic) parser.ExpectEndStat(); else if (parser.Char('=')) { ScanDefAlias(over); over.BindPoint = bp; parser.ExpectEndStat(); } else { parser.Expect('{'); over.Skip = parser.GetPos(); ScanBlock(); } get++; } else if (parser.Id("set")) { parser.Expect('('); Point p2 = parser.GetPoint(); String param = parser.ExpectId(); parser.Expect(')'); Overload& over = prop.Add(name, insertAccess, stat); over.BackendName = bname; over.Location = pnt; over.Skip = parser.GetPos(); over.CPosPar = parser.GetPos(); over.IsProp = true; over.IsGetter = false; prop.HasPSetter = &over; over.IsIntrinsic = isIntrinsic; if (parser.Char('[')) { Variable& p = over.Params.Add(); p.Name = parser.ExpectId(); parser.Expect(':'); p.Skip = parser.GetPos(); ScanType(); parser.Expect(']'); over.IsIndex = true; } Variable& p = over.Params.Add(); p.Name = param; p.Location = p2; while (true) { if (parser.IsId("native")) { parser.ReadId(); } else if (parser.Id("const")) parser.Error(pnt, "setters can't be const"); else if (parser.IsChar('{')) break; else parser.Error(pnt, "syntax error: " + parser.Identify() + " found"); } parser.Expect('{'); over.Skip = parser.GetPos(); ScanBlock(); set++; } else if (parser.Char('{')) { Overload& over = prop.Add(name, insertAccess, stat); over.Location = pnt; over.Skip = parser.GetPos(); over.CPosPar = parser.GetPos(); over.IsProp = true; over.IsGetter = true; over.BackendName = bname; prop.HasPGetter = &over; over.Skip = parser.GetPos(); ScanBlock(); get++; } else { if (get == 0 && set == 0) parser.Error(pnt, "property '" + name + "' needs to have at least a setter or a getter"); if (get > 1) parser.Error(pnt, "property '" + name + "' can't have more than one getter"); if (set > 1) parser.Error(pnt, "property '" + name + "' can't have more than one setter"); break; } } } void Scanner::ScanDefAlias(Overload& over) { String alias = parser.ExpectId(); if (alias == "null") { over.IsDeleted = true; return; } String lastAlias; while (parser.Char('.')) { if (over.AliasClass.GetCount()) over.AliasClass << "."; over.AliasClass << lastAlias; lastAlias = alias; alias = parser.ExpectId(); } if (over.AliasClass.GetCount()) over.AliasClass << "."; over.AliasClass << lastAlias; if (over.AliasClass.GetCount() == 0) over.AliasClass = over.Parent->Class->Scan.Name; over.AliasName = alias; over.IsAlias = true; } Def& Scanner::ScanDef(ZClass& cls, bool cons, bool stat, int virt, bool cst) { Point p = parser.GetPoint(); String name; String bname; int cval = 0; if (!cons) { if (parser.Char('@')) { String s = parser.ExpectId(); if (s == "size") parser.Error(p, "'@size' can't be overlaoded"); name = "@" + s; bname = "_" + s; } else { name = parser.ExpectId(); bname = name; } if (name == "this") parser.Error(p, "identifier expected, 'this' found. Are you trying to define a constructor?"); } else { if (parser.IsZId()) { name = parser.ReadId(); if (name == cls.Scan.Name) parser.Error(p, "named constructor must not have the same name as the parent class"); cval = 2; bname = name; } else if (parser.Char('@')) { name = parser.ReadId(); cval = 2; bname = "_" + name; name = "@" + name; } else { name = "this"; if (cls.CoreSimple) bname << "_" << name; else bname = name; cval = 1; } } bool tplt = false; Vector<String> tname; if (parser.Char('<')) { while (true) { tname.Add(parser.ExpectId()); tplt = true; parser.Expect(':'); parser.ExpectId("Class"); if (parser.Char('>')) break; parser.Expect(','); } } parser.Expect('('); Def& def = cls.FindDef(parser, name, p, cons); def.Name = name; def.BackendName = bname; def.IsStatic = stat; def.Class = &cls; def.Location = p; def.Template = tplt; def.DTName = clone(tname); def.Access = insertAccess; CParser::Pos backPos = parser.GetPos(); if (def.Pos.GetCount() == 0 || def.Template) def.Pos.Add(backPos); if (cval == 1 && parser.IsChar(')')) cls.Scan.HasDefaultCons = true; int pc = 0; Vector<String> params; while (!parser.IsChar(')')) { if (parser.IsId("val")) parser.ReadId(); else if (cst == false && parser.IsId("const")) parser.ReadId(); else if (parser.IsId("ref")) { parser.ReadId(); parser.Id("const"); } else if (parser.IsId("move")) parser.ReadId(); params << parser.ExpectId(); parser.Expect(':'); ScanType(); if (parser.Char(',')) { if (parser.IsChar(')')) parser.Error(parser.GetPoint(), "identifier expected, " + parser.Identify() + " found"); } pc++; } if (def.Template) def.PC.Add(pc); parser.Expect(')'); bool hasRet = false; if (parser.Char(':')) { hasRet = true; if (parser.IsId("ref")) parser.ReadId(); ScanType(); } Overload* ol = nullptr; if (!tplt) { Overload& over = def.Add(name, bname, insertAccess, stat); over.Location = p; over.Skip = backPos; over.CPosPar = backPos; over.IsCons = cval; over.IsVirtual = virt; over.IsConst = cst; over.ParamPreview = pick(params); over.IsVoidReturn = !hasRet; over.IsStatic = def.IsStatic; if (cons) over.BackendSuffix = "_"; ol = &over; if (bindName.GetCount()) ol->BindName = ol->Name; ol->IsIntrinsic = isIntrinsic; ol->IsDllImport = isDllImport; ol->IsStdCall = isStdCall; ol->IsCDecl = isCDecl; ol->IsNoDoc = isNoDoc; } else { def.CPosPar = backPos; } Point bp = parser.GetPoint(); if (parser.Char('=')) { TraitLoop(); ScanDefAlias(*ol); if (ol->IsDeleted == false) { ol->BindForce = true; ol->BindPoint = bp; } } if (ol) { if (ol->IsAlias || ol->IsIntrinsic || ol->IsDllImport || ol->BindName.GetCount() || ol->IsDeleted) { ol->Skip = parser.GetPos(); parser.ExpectEndStat(); return def; } } parser.Expect('{'); parser.EatNewlines(); if (def.BodyPos.GetCount() == 0 || def.Template) def.BodyPos.Add(parser.GetPos()); if (ol) ol->Skip = parser.GetPos(); ScanBlock(); return def; } void Scanner::ScanBlock() { bool b = parser.SkipNewLines(); parser.SkipNewLines(true); while (!parser.IsChar('}')) { if (parser.Char('{')) { parser.EatNewlines(); ScanBlock(); } else ScanToken(); } parser.SkipNewLines(b); parser.Expect('}'); parser.EatNewlines(); } void Scanner::ScanType() { if (parser.Id("val")) { } else if (parser.Id("ref")) { parser.Id("const"); } parser.ExpectId(); while (parser.Char('.')) parser.ExpectId(); if (parser.Char('<')) { String ss = parser.ExpectId(); if (ss == "const") parser.ExpectId(); if (parser.Char(',')) ScanToken(); parser.Expect('>'); } } void Scanner::ScanToken() { if (parser.IsInt()) { int64 oInt; double oDub; int base; parser.ReadInt64(oInt, oDub, base); } else if (parser.IsString()) parser.ReadString(); else if (parser.IsId()) parser.ReadId(); else if (parser.IsCharConst()) parser.ReadChar(); else { for (int i = 0; i < 9; i++) if (parser.Char2(tab2[i], tab3[i])) return; for (int i = 0; i < 24; i++) if (parser.Char(tab1[i])) return; if (parser.Char('{') || parser.Char('}')) return; Point p = parser.GetPoint(); parser.Error(p, "syntax error: " + parser.Identify() + " found"); } }
23.286157
141
0.578058
[ "vector" ]
ad63b63f4918465918e2b69175a3e0b6cff5c186
3,180
cpp
C++
src/core/lib/lattice/elemparams.cpp
jacobmas/PALISADE
4cd6a0e1efa58379797c15fa2fcfdca3a2d49d8d
[ "BSD-2-Clause" ]
6
2019-03-19T04:12:00.000Z
2022-01-27T11:23:01.000Z
src/core/lib/lattice/elemparams.cpp
jacobmas/PALISADE
4cd6a0e1efa58379797c15fa2fcfdca3a2d49d8d
[ "BSD-2-Clause" ]
null
null
null
src/core/lib/lattice/elemparams.cpp
jacobmas/PALISADE
4cd6a0e1efa58379797c15fa2fcfdca3a2d49d8d
[ "BSD-2-Clause" ]
3
2019-04-30T07:07:50.000Z
2022-01-27T06:59:53.000Z
/* * @file elemparams.cpp - element parameters for palisade * @author TPOC: palisade@njit.edu * * @copyright Copyright (c) 2017, New Jersey Institute of Technology (NJIT) * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * */ #include "elemparams.h" namespace lbcrypto { /** * Stores this object's attribute name value pairs to a map for serializing this object to a JSON file. * * @param serObj stores this object's serialized attribute name value pairs. * @return map updated with the attribute name value pairs required to serialize this object. */ template<typename IntType> bool ElemParams<IntType>::Serialize(Serialized* serObj) const { if( !serObj->IsObject() ){ serObj->SetObject(); } SerialItem ser(rapidjson::kObjectType); ser.AddMember("Modulus", this->GetModulus().ToString(), serObj->GetAllocator()); ser.AddMember("Order", std::to_string(this->GetCyclotomicOrder()), serObj->GetAllocator()); serObj->AddMember("ElemParams", ser, serObj->GetAllocator()); return true; } /** * Sets this object's attribute name value pairs to deserialize this object from a JSON file. * * @param serObj stores this object's serialized attribute name value pairs. */ template<typename IntType> bool ElemParams<IntType>::Deserialize(const Serialized& serObj) { Serialized::ConstMemberIterator mIter = serObj.FindMember("ElemParams"); if( mIter == serObj.MemberEnd() ) { return false; } SerialItem::ConstMemberIterator oIt; if( (oIt = mIter->value.FindMember("Modulus")) == mIter->value.MemberEnd() ) return false; IntType modulus(oIt->value.GetString()); if( (oIt = mIter->value.FindMember("Order")) == mIter->value.MemberEnd() ) return false; usint order = atoi(oIt->value.GetString()); cyclotomicOrder = order; ringDimension = GetTotient(order); isPowerOfTwo = cyclotomicOrder/2 == ringDimension; ciphertextModulus = modulus; return true; } } // namespace lbcrypto ends
36.551724
102
0.75283
[ "object" ]
ad63ddcc9ca1877ce1f8f65b343f4d863ab4406b
295
cpp
C++
holder for older programs/C++/vector01.cpp
GabrielSorensen/CSIS3150
da1c851ff1c537be0bb84c054f69f5a304edc7c7
[ "MIT" ]
null
null
null
holder for older programs/C++/vector01.cpp
GabrielSorensen/CSIS3150
da1c851ff1c537be0bb84c054f69f5a304edc7c7
[ "MIT" ]
null
null
null
holder for older programs/C++/vector01.cpp
GabrielSorensen/CSIS3150
da1c851ff1c537be0bb84c054f69f5a304edc7c7
[ "MIT" ]
null
null
null
//operator overloading // ratio ver. 2 #include <iostream> #include <vector> using namespace std; int main () { vector<int> squares; for (int i=0; i <= 100; i++) { squares.push_back(i*i); } for (int i=0; i< squares.size(); i++) { cout << squares[i] << endl; } }
14.75
41
0.555932
[ "vector" ]
ad63ffcb5151ba84b03e079305090b013983168a
12,865
c++
C++
src/lua/helpers.c++
therealaquarius/vega
7caf97e911ca8df48ff450620c73829b9b76f0d9
[ "MIT" ]
null
null
null
src/lua/helpers.c++
therealaquarius/vega
7caf97e911ca8df48ff450620c73829b9b76f0d9
[ "MIT" ]
null
null
null
src/lua/helpers.c++
therealaquarius/vega
7caf97e911ca8df48ff450620c73829b9b76f0d9
[ "MIT" ]
null
null
null
#include "helpers.h" #include "types.h" #include "main.h" namespace lua { namespace h { void Data::operator()( lua_CFunction gc, void* data ) { Lua::dec(); Table table( m_lua ); Arguments upvalues; upvalues.add( data ); table.set( "__gc", gc, upvalues ); m_lua.setmetatable( Lua::index() ); } Table::Table( Stack& stack, int index ) : Lua( stack.lua( ) ) { init( false, 0, index, &stack ); } bool Table::is( ) const { return lua_istable( m_lua, m_index ); } Table::Strings Table::values( ) { Strings result; if ( !is( ) ) { return result; } get( ); lua_pushnil( m_lua ); unsigned index = Lua::index(); index--; while ( lua_next( m_lua, index ) != 0 ) { std::string key = m_lua.tostring( -2 ); std::string value = m_lua.tostring( -1 ); if ( value.length() ) { result[ key ] = value; } m_lua.pop( 1 ); } return result; } void Table::init( bool pop, unsigned int ref, int index, Stack* stack ) { m_stack = stack; Lua::setPop( pop ); m_create = !Lua::getPop(); Lua::setIndex( index ); m_counter = 1; m_ref = ref; m_loaded = !global( ); } void Table::create( ) { if ( global( ) ) { get( ); return; } if ( m_create ) { m_lua.table(); m_create = false; } } void Table::get( ) { if ( m_stack || m_loaded ) { return; } if ( !global( ) ) { return; } m_loaded = true; if ( m_ref ) { m_lua.pushReference( m_ref ); } else { m_lua.global( m_name ); if ( m_lua.type( -1 ) == Nil ) { m_lua.pop( 1 ); m_lua.table(); m_lua.setglobal( m_name ); m_lua.global( m_name ); } } } void Table::field( const std::string& name ) { field( name, [](){}, false ); } template< class Field > void Table::field( const std::string& name, Field field, bool pop ) { get(); assert( is() ); if ( !is() ) { return; } m_lua.getfield( Lua::index(), name ); field(); if ( pop ) { m_lua.pop( 1 ); } } template < class Set > void Table::setfield( const std::string name, Set set ) { create( ); set( ); m_lua.setfield( name, -2 ); } bool Table::boolean( const std::string& name ) { bool result = false; field( name, [ & ](){ result = m_lua.toboolean( -1 ); } ); return result; } std::string Table::string( const std::string& name ) { std::string result; field( name, [ & ](){ result = m_lua.tostring( -1, true ); } ); return result; } void* Table::data( const std::string& name ) { void* result = NULL; field( name, [ & ](){ result = m_lua.touserdata( -1 ); } ); return result; } void Table::insert( const std::string& value, int index ) { create( ); bool inc = false; if ( !index ) { index = m_counter; inc = true; } m_lua.push( ( int ) index ); m_lua.push( value ); m_lua.settable( -3 ); if ( inc ) { m_counter++; } } void Table::setReference( const std::string& name, unsigned int ref ) { setfield( name, [ & ]( ) { m_lua.pushReference( ref ); } ); } void Table::set( const std::string& name, Table& table ) { table.get( ); setfield( name, [ & ]( ) { m_lua.insert( -2 ); } ); table.setPop( false ); } void Table::set( const std::string& name, lua_CFunction value, const Arguments& upvalues ) { setfield( name, [ & ]( ) { m_lua.push( value, upvalues.push( m_lua ) ); } ); } void Table::set( const std::string& name, void* value ) { setfield( name, [ & ]( ) { m_lua.push( value ); } ); } void Table::set( const std::string& name, const std::string& value ) { setfield( name, [ & ]( ) { m_lua.push( value.c_str(), value.length() ); } ); } void Table::set( const std::string& name, unsigned int value ) { setfield( name, [ & ]( ) { m_lua.push( ( int ) value ); } ); } void Table::setmetatable( Table& table ) { table.get(); if ( m_create ) { create( ); m_lua.insert( -2 ); } m_lua.setmetatable( -- m_index ); } Stack::Stack( Runner& runner ) : Lua( runner ), m_runner( &runner ), m_count( 0 ) { init( 0 ); } void Stack::init( unsigned int top ) { Lua::setCount( top ? top : m_lua.top( ) ); Lua::setIndex( -Lua::count() ); Lua::setPop( count() > 0 ); } long Stack::number( ) { unsigned int result = 0; get( [ & ]( ){ result = m_lua.tonumber( index() ); } ); return result; } int Stack::integer( ) { int result = 0; get( [ & ]( ){ result = m_lua.tointeger( index() ); } ); return result; } void* Stack::pointer( ) { void* result = NULL; get( [ & ]( ){ result = m_lua.touserdata( index() ); } ); return result; } template < class Get > void Stack::get( Get get ) { if ( !index() ) { return; } get(); inc(); } Table Stack::table( ) { Table table( *this, m_index ); inc( ); return table; } tau::Pill Stack::data( ) { tau::Pill result; get( [ & ]( ){ result = m_lua.topill( index() ); } ); return result; } std::string Stack::string( ) { std::string result; get( [ & ]( ){ result = m_lua.tostring( index(), true ); } ); return result; } types::Value* Stack::value( ) { types::Value* value = types::Value::load( m_lua, index( ), false ); inc( ); return value; } unsigned int Stack::reference( ) { unsigned int result = m_lua.reference( index() ); inc(); return result; } bool Stack::boolean( ) { bool result = false; get( [ & ]( ){ result = m_lua.toboolean( index() ); } ); return result; } void Stack::push( Table& table ) { table.get(); pushvalue( [](){} ); } void Stack::push( const char* data, unsigned int length ) { pushvalue( [ & ]( ) { m_lua.push( data, length ); } ); } void Stack::push( void* data ) { pushvalue( [ & ]( ) { m_lua.push( data ); } ); } void Stack::push( long number ) { pushvalue( [ & ]( ) { m_lua.push( number ); } ); } void Stack::push( int number ) { pushvalue( [ & ]( ) { m_lua.push( number ); } ); } void Stack::push( bool value ) { pushvalue( [ & ]( ) { m_lua.push( value ); } ); } void Stack::push( Object& object ) { pushvalue( [ & ]( ) { object.push( runner() ); } ); } void Stack::pushReference( unsigned int reference ) { pushvalue( [ & ]( ) { m_lua.pushReference( reference ); } ); } template < class Push > void Stack::pushvalue( Push push ) { pop( ); push( ); m_count++; } void Stack::push( const types::Value& value ) { pushvalue( [ & ]( ) { value.push( m_lua ); } ); } Type Stack::type( ) const { unsigned int type = 0; if ( index() ) { type = m_lua.type( index() ); } return ( Type) type; } void Arguments::add( const tau::Pill& pill ) { Argument arg( Pill ); arg.pill = &pill; m_list.emplace_back( arg ); } void Arguments::add( unsigned int number ) { Argument arg( Number ); arg.number = number; m_list.emplace_back( arg ); } void Arguments::addReference( unsigned int ref ) { Argument arg( Reference ); arg.number = ref; m_list.emplace_back( arg ); } void Arguments::add( void* pointer ) { Argument arg( Pointer ); arg.pointer = pointer; m_list.emplace_back( arg ); } void Arguments::add( Object& object ) { Argument arg( Obj ); arg.object = &object; m_list.emplace_back( arg ); } void Arguments::add( const types::Value& value ) { Argument arg( Value ); arg.value = &value; m_list.emplace_back( arg ); } unsigned int Arguments::push( const State& lua ) const { for ( auto i = m_list.begin( ); i != m_list.end( ); i++ ) { auto argument = *i; switch ( argument.type ) { case Pointer: lua.push( argument.pointer ); break; case Pill: lua.push( argument.pill->data( ), argument.pill->length( ) ); break; case Number: lua.push( argument.number ); break; case Nil: lua.push( NULL ); break; case Reference: lua.pushReference( argument.number ); break; case Obj: { auto object = argument.object; object->push( runner() ); } break; case Value: argument.value->push( lua ); break; } } return m_list.size( ); } unsigned int Arguments::push( Runner& runner, Arguments* arguments ) { if ( arguments ) { arguments->setRunner( runner ); } return arguments ? arguments->push( runner ) : 0; } } }
24.932171
99
0.363311
[ "object" ]
ad6bae8dff395383328590a0416a8d505b1aeb0a
5,814
cpp
C++
common/WhirlyGlobeLib/src/FontTextureManager.cpp
zzjiong/WhirlyGlobe
f309004b9066f3466c4593d359234869c9e8f0a7
[ "Apache-2.0" ]
null
null
null
common/WhirlyGlobeLib/src/FontTextureManager.cpp
zzjiong/WhirlyGlobe
f309004b9066f3466c4593d359234869c9e8f0a7
[ "Apache-2.0" ]
2
2021-01-04T01:27:26.000Z
2021-01-08T01:30:41.000Z
common/WhirlyGlobeLib/src/FontTextureManager.cpp
zzjiong/WhirlyGlobe
f309004b9066f3466c4593d359234869c9e8f0a7
[ "Apache-2.0" ]
null
null
null
/* * FontTextureManager.mm * WhirlyGlobeLib * * Created by Steve Gifford on 4/15/13. * Copyright 2011-2019 mousebird consulting * * 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. * */ #import "FontTextureManager.h" #import "WhirlyVector.h" using namespace Eigen; using namespace WhirlyKit; namespace WhirlyKit { FontManager::FontManager() : refCount(0),color(255,255,255,255),outlineColor(0,0,0,0),backColor(0,0,0,0),outlineSize(0.0) { } FontManager::~FontManager() { for (std::set<GlyphInfo *,GlyphInfoSorter>::iterator it = glyphs.begin(); it != glyphs.end(); ++it) { delete *it; } glyphs.clear(); } // Comparison operator // Subclass fills this in bool FontManager::operator < (const FontManager &that) const { return false; } // Look for an existing glyph and return it if it's there FontManager::GlyphInfo *FontManager::findGlyph(WKGlyph glyph) { GlyphInfo dummyGlyph(glyph); GlyphInfoSet::iterator it = glyphs.find(&dummyGlyph); if (it != glyphs.end()) { return *it; } return NULL; } // Add the given glyph info FontManager::GlyphInfo *FontManager::addGlyph(WKGlyph glyph,SubTexture subTex,const Point2f &size,const Point2f &offset,const Point2f &textureOffset) { GlyphInfo *info = new GlyphInfo(glyph); info->size = size; info->offset = offset; info->textureOffset = textureOffset; info->subTex = subTex; glyphs.insert(info); return info; } // Remove references to the given glyphs. void FontManager::addGlyphRefs(const GlyphSet &usedGlyphs) { refCount++; for (GlyphSet::iterator it = usedGlyphs.begin(); it != usedGlyphs.end(); ++it) { WKGlyph theGlyph = *it; GlyphInfo dummy(theGlyph); GlyphInfoSet::iterator git = glyphs.find(&dummy); if (git != glyphs.end()) { GlyphInfo *glyphInfo = *git; glyphInfo->refCount++; } } } // Returns a list of texture references to remove void FontManager::removeGlyphRefs(const GlyphSet &usedGlyphs,std::vector<SubTexture> &toRemove) { refCount--; for (GlyphSet::iterator it = usedGlyphs.begin(); it != usedGlyphs.end(); ++it) { WKGlyph theGlyph = *it; GlyphInfo dummy(theGlyph); GlyphInfoSet::iterator git = glyphs.find(&dummy); if (git != glyphs.end()) { GlyphInfo *glyphInfo = *git; glyphInfo->refCount--; if (glyphInfo->refCount <= 0) { toRemove.push_back(glyphInfo->subTex); glyphs.erase(git); delete glyphInfo; } } } } FontTextureManager::FontTextureManager(SceneRenderer *sceneRender,Scene *scene) : sceneRender(sceneRender), scene(scene), texAtlas(NULL) { } FontTextureManager::~FontTextureManager() { std::lock_guard<std::mutex> guardLock(lock); if (texAtlas) delete texAtlas; texAtlas = NULL; for (DrawStringRepSet::iterator it = drawStringReps.begin(); it != drawStringReps.end(); ++it) delete *it; drawStringReps.clear(); fontManagers.clear(); } void FontTextureManager::init() { if (!texAtlas) { // Let's do the biggest possible texture with small cells 32 bits deep // Note: Porting. We've turned main thread merge on here, which shouldn't be needed. // If we leave it off, we get corruption of the dynamic textures texAtlas = new DynamicTextureAtlas("Font Texture Atlas",2048,16,TexTypeUnsignedByte,1,true); } } void FontTextureManager::clear(ChangeSet &changes) { std::lock_guard<std::mutex> guardLock(lock); if (texAtlas) { texAtlas->teardown(changes); delete texAtlas; texAtlas = NULL; } for (DrawStringRepSet::iterator it = drawStringReps.begin(); it != drawStringReps.end(); ++it) delete *it; fontManagers.clear(); } void FontTextureManager::removeString(SimpleIdentity drawStringId,ChangeSet &changes,TimeInterval when) { std::lock_guard<std::mutex> guardLock(lock); DrawStringRep dummyRep(drawStringId); DrawStringRepSet::iterator it = drawStringReps.find(&dummyRep); if (it == drawStringReps.end()) { return; } DrawStringRep *theRep = *it; drawStringReps.erase(theRep); // Work through the fonts we're using for (SimpleIDGlyphMap::iterator fit = theRep->fontGlyphs.begin(); fit != theRep->fontGlyphs.end(); ++fit) { auto fmIt = fontManagers.find(fit->first); if (fmIt != fontManagers.end()) { // Decrement the glyph references FontManagerRef fm = fmIt->second; std::vector<SubTexture> texRemove; fm->removeGlyphRefs(fit->second,texRemove); // And possibly remove some sub textures if (!texRemove.empty()) for (unsigned int ii=0;ii<texRemove.size();ii++) texAtlas->removeTexture(texRemove[ii], changes, when); // Also see if we're done with the font if (fm->refCount <= 0) { fontManagers.erase(fmIt); } } } delete theRep; } }
27.685714
149
0.626075
[ "vector" ]
ad73006ef13c4a9204a399c3991aecb05416c50a
4,394
cpp
C++
ImageCompressor.cpp
nimble0/rsic
e94f2e226fa68e7495c7423f1845b01edff6b2fe
[ "Apache-2.0" ]
null
null
null
ImageCompressor.cpp
nimble0/rsic
e94f2e226fa68e7495c7423f1845b01edff6b2fe
[ "Apache-2.0" ]
null
null
null
ImageCompressor.cpp
nimble0/rsic
e94f2e226fa68e7495c7423f1845b01edff6b2fe
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2016 Erik Crevel * * 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 "ImageCompressor.hpp" #include <utility> #include <cmath> #include "ImageSegmentCompressor.hpp" #include <iostream> void ImageCompressor::compressLayer( std::ostream& _output, std::pair<std::size_t, std::size_t> _increment, std::pair<std::size_t, std::size_t> _startOffset, int _layerSize, const std::vector<std::pair<int, int>>& _vars) const { this->processLayer( _startOffset, _layerSize, [&](std::pair<std::size_t, std::size_t> _start, std::pair<std::size_t, std::size_t> _end) { ImageSegmentCompressor layerCompressor( this->image, _start, _end, _increment, _vars); std::streampos preProcessStreamPos = _output.tellp(); layerCompressor.compress(_output); std::cout<<"layer size="<<(_output.tellp()-preProcessStreamPos)<<std::endl; } ); } void ImageCompressor::decompressLayer( std::istream& _input, std::pair<std::size_t, std::size_t> _increment, std::pair<std::size_t, std::size_t> _startOffset, int _layerSize, const std::vector<std::pair<int, int>>& _vars) const { this->processLayer( _startOffset, _layerSize, [&](std::pair<std::size_t, std::size_t> _start, std::pair<std::size_t, std::size_t> _end) { ImageSegmentCompressor layerCompressor( this->image, _start, _end, _increment, _vars); std::streampos preProcessStreamPos = _input.tellg(); layerCompressor.decompress(_input); std::cout<<"layer size="<<(_input.tellg()-preProcessStreamPos)<<std::endl; } ); } void ImageCompressor::compress(std::ostream& _output) const { std::size_t width = this->image.width(); std::size_t height = this->image.height(); _output.write(reinterpret_cast<char*>(&width), sizeof(width)); _output.write(reinterpret_cast<char*>(&height), sizeof(height)); int skipLayers = 3; int divisionSize = 64; int layers = std::ceil(std::log2(std::max(this->image.width()-1, this->image.height()-1))); int scale = 1 << (layers - skipLayers); for(std::size_t y = 0; y < this->image.height(); y += scale) for(std::size_t x = 0; x < this->image.width(); x += scale) { unsigned char rawColour = this->image.get(x,y).r(); _output.write(reinterpret_cast<char*>(&rawColour), sizeof(rawColour)); } for(int layer = layers - skipLayers; layer > 0; --layer) { int scale = 1 << layer; int halfScale = scale >> 1; int layerSize = divisionSize*scale; this->compressLayer( _output, {scale, scale}, {halfScale, 0}, layerSize, scaleVars(aVars, halfScale)); this->compressLayer( _output, {halfScale, scale}, {0, halfScale}, layerSize, scaleVars(bVars, halfScale)); } } void ImageCompressor::decompress(std::istream& _input) { std::size_t width = this->image.width(); std::size_t height = this->image.height(); _input.read(reinterpret_cast<char*>(&width), sizeof(width)); _input.read(reinterpret_cast<char*>(&height), sizeof(height)); this->image.resize(width, height); int skipLayers = 3; int divisionSize = 64; int layers = std::ceil(std::log2(std::max(this->image.width()-1, this->image.height()-1))); int scale = 1 << (layers - skipLayers); for(std::size_t y = 0; y < this->image.height(); y += scale) for(std::size_t x = 0; x < this->image.width(); x += scale) { unsigned char rawColour; _input.read(reinterpret_cast<char*>(&rawColour), sizeof(rawColour)); this->image.set(x, y, RgbColour(rawColour, 0, 0)); } for(int layer = layers - skipLayers; layer > 0; --layer) { int scale = 1 << layer; int halfScale = scale >> 1; int layerSize = divisionSize*scale; this->decompressLayer( _input, {scale, scale}, {halfScale, 0}, layerSize, scaleVars(aVars, halfScale)); this->decompressLayer( _input, {halfScale, scale}, {0, halfScale}, layerSize, scaleVars(bVars, halfScale)); } }
26.154762
92
0.679563
[ "vector" ]
ad753c24f954626de52b49fafb591698c3b2e0af
13,065
cxx
C++
Studio/src/Groom/ShapeWorksGroom.cxx
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Studio/src/Groom/ShapeWorksGroom.cxx
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
Studio/src/Groom/ShapeWorksGroom.cxx
amylenz/ShapeWorks
78c2ee067a23e31f5b83d0121e60addb1b0bf462
[ "MIT" ]
null
null
null
#include <ShapeWorksGroom.h> #include <tinyxml.h> #include <sstream> #include <iostream> #include <vector> #include <map> #include <stdexcept> #include "vnl/vnl_vector.h" #include "bounding_box.h" #include "itkConnectedComponentImageFilter.h" #include "itkImageRegionIterator.h" #include "itkImageRegionIteratorWithIndex.h" #include "itkConnectedComponentImageFilter.h" #include "itkNearestNeighborInterpolateImageFunction.h" #include "itkResampleImageFilter.h" #include "itkExtractImageFilter.h" #include "itkConstantPadImageFilter.h" #include "itkAntiAliasBinaryImageFilter.h" #include "itkReinitializeLevelSetImageFilter.h" #include "itkDiscreteGaussianImageFilter.h" #include "itkNrrdImageIOFactory.h" #include "itkMetaImageIOFactory.h" #include "itkCastImageFilter.h" #include "itkRelabelComponentImageFilter.h" #include "itkThresholdImageFilter.h" #include "itkBinaryFillholeImageFilter.h" #include "itkApproximateSignedDistanceMapImageFilter.h" ShapeWorksGroom::ShapeWorksGroom( std::vector<ImageType::Pointer> inputs, double background, double foreground, double blurSigma, size_t padding, size_t iterations, bool verbose) : images_(inputs), background_(background), blurSigma_(blurSigma), foreground_(foreground), padding_(padding), iterations_(iterations), verbose_(verbose) { this->paddingInit_ = false; this->upper_ = { 0,0,0 }; this->lower_ = { 0,0,0 }; } void ShapeWorksGroom::queueTool(std::string tool) { this->runTools_.insert(std::make_pair(tool, true)); } void ShapeWorksGroom::run() { this->seed_.Fill(0); size_t ran = 0; if (this->runTools_.count("center")) { this->center(); } if (this->runTools_.count("isolate")) { this->isolate(); } if (this->runTools_.count("hole_fill")) { this->hole_fill(); } if (this->runTools_.count("auto_pad")) { this->auto_pad(); } if (this->runTools_.count("antialias")) { this->antialias(); } if (this->runTools_.count("fastmarching")) { this->fastmarching(); } if (this->runTools_.count("blur")) { this->blur(); } } std::map<std::string, bool> ShapeWorksGroom::tools() { return this->runTools_; } double ShapeWorksGroom::foreground() { return this->foreground_; } std::vector<ImageType::Pointer> ShapeWorksGroom::getImages() { return this->images_; } void ShapeWorksGroom::isolate(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: isolate on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start; i < end; i++) { auto img = this->images_[i]; typedef itk::Image<unsigned char, 3> IsolateType; typedef itk::CastImageFilter< ImageType, IsolateType > ToIntType; ToIntType::Pointer filter = ToIntType::New(); filter->SetInput(img); filter->Update(); // Find the connected components in this image. itk::ConnectedComponentImageFilter<IsolateType, IsolateType>::Pointer ccfilter = itk::ConnectedComponentImageFilter<IsolateType, IsolateType>::New(); ccfilter->SetInput(filter->GetOutput()); ccfilter->FullyConnectedOn(); ccfilter->Update(); typedef itk::RelabelComponentImageFilter< IsolateType, IsolateType > RelabelType; RelabelType::Pointer relabel = RelabelType::New(); relabel->SetInput(ccfilter->GetOutput()); relabel->SortByObjectSizeOn(); relabel->Update(); typedef itk::ThresholdImageFilter< IsolateType > ThreshType; ThreshType::Pointer thresh = ThreshType::New(); thresh->SetInput(relabel->GetOutput()); thresh->SetOutsideValue(0); thresh->ThresholdBelow(0); thresh->ThresholdAbove(1.001); thresh->Update(); typedef itk::CastImageFilter< IsolateType, ImageType > FilterType; FilterType::Pointer filter2 = FilterType::New(); filter2->SetInput(thresh->GetOutput()); filter2->Update(); this->images_[i] = filter2->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: isolate" << std::endl; } } void ShapeWorksGroom::hole_fill(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: antialias on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start; i < end; i++) { auto img = this->images_[i]; typedef itk::BinaryFillholeImageFilter< ImageType > HoleType; HoleType::Pointer hfilter = HoleType::New(); hfilter->SetInput(img); hfilter->SetForegroundValue(itk::NumericTraits< PixelType >::min()); hfilter->Update(); this->images_[i] = hfilter->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: hole_fill" << std::endl; } } void ShapeWorksGroom::center(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: center on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start; i < end; i++) { auto img = this->images_[i]; ImageType::PointType origin = img->GetOrigin(); // Copy the original image and find the center of mass. ImageType::Pointer simg = ImageType::New(); simg->CopyInformation(img); simg->SetRegions(img->GetLargestPossibleRegion()); simg->Allocate(); itk::ImageRegionIteratorWithIndex<ImageType> oit(img, img->GetLargestPossibleRegion()); itk::ImageRegionIteratorWithIndex<ImageType> sit(simg, img->GetLargestPossibleRegion()); sit.GoToBegin(); oit.GoToBegin(); itk::Array<double> params(3); params.Fill(0.0); double count = 0.0; itk::Point<double, 3> point; for (; !oit.IsAtEnd(); ++oit, ++sit) { if (oit.Get() != this->background_) { sit.Set(oit.Get()); // Get the physical index from the image index. img->TransformIndexToPhysicalPoint(oit.GetIndex(), point); for (unsigned int i = 0; i < 3; i++) { params[i] += point[i]; } count += 1.0; } else { sit.Set(this->background_); } } // Compute center of mass. for (unsigned int i = 0; i < 3; i++) { params[i] = params[i] / count; } double new_origin[3]; new_origin[0] = -(img->GetLargestPossibleRegion().GetSize()[0] / 2.0) * img->GetSpacing()[0]; new_origin[1] = -(img->GetLargestPossibleRegion().GetSize()[1] / 2.0) * img->GetSpacing()[1]; new_origin[2] = -(img->GetLargestPossibleRegion().GetSize()[2] / 2.0) * img->GetSpacing()[2]; img->SetOrigin(new_origin); if (this->verbose_) { std::cerr << "new origin = " << img->GetOrigin() << "\n"; } // Zero out the original image. for (oit.GoToBegin(); !oit.IsAtEnd(); ++oit){ oit.Set(this->background_); } // Translate the segmentation back into the original image. itk::TranslationTransform<double, 3>::Pointer trans = itk::TranslationTransform<double, 3>::New(); trans->SetParameters(params); itk::NearestNeighborInterpolateImageFunction<ImageType, double>::Pointer interp = itk::NearestNeighborInterpolateImageFunction<ImageType, double>::New(); itk::ResampleImageFilter<ImageType, ImageType>::Pointer resampler = itk::ResampleImageFilter<ImageType, ImageType>::New(); resampler->SetOutputParametersFromImage(img); resampler->SetTransform(trans); resampler->SetInterpolator(interp); resampler->SetInput(simg); resampler->Update(); oit.GoToBegin(); itk::ImageRegionIterator<ImageType> it(resampler->GetOutput(), img->GetLargestPossibleRegion()); for (; !it.IsAtEnd(); ++it, ++oit) { oit.Set(it.Get()); } this->images_[i] = resampler->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: center" << std::endl; } } void ShapeWorksGroom::auto_pad(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: auto_pad on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } bool first = true; auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); if (!this->paddingInit_) { for (size_t i = 0; i < this->images_.size(); i++) { auto img = this->images_[i]; if (first == true) { first = false; this->lower_ = img->GetLargestPossibleRegion().GetIndex(); this->upper_ = lower_ + img->GetLargestPossibleRegion().GetSize(); } else { // Keep the largest bounding box. ImageType::RegionType::IndexType lowerTmp = img->GetLargestPossibleRegion().GetIndex(); ImageType::RegionType::IndexType upperTmp = lowerTmp + img->GetLargestPossibleRegion().GetSize(); for (unsigned int i = 0; i < 3; i++) { if (lowerTmp[i] < this->lower_[i]) { this->lower_[i] = lowerTmp[i]; } if (upperTmp[i] > this->upper_[i]){ this->upper_[i] = upperTmp[i]; } } } } this->paddingInit_ = true; } if (this->verbose_) { std::cout << "Lower bound = " << this->lower_[0] << " " << this->lower_[1] << " " << this->lower_[2] << std::endl; std::cout << "Upper bound = " << this->upper_[0] << " " << this->upper_[1] << " " << this->upper_[2] << std::endl; } // Make sure the origin is at the center of the image. double orig[3]; for (unsigned int i = 0; i < 3; i++) { orig[i] = -static_cast<double>(this->upper_[i] - this->lower_[i]) / 2.0; } for (size_t i = start; i < end; i++) { auto img = this->images_[i]; itk::ConstantPadImageFilter<ImageType, ImageType>::Pointer padder = itk::ConstantPadImageFilter<ImageType, ImageType>::New(); padder->SetConstant(0); padder->SetInput(img); // set the desired padding auto pd = static_cast<unsigned long>((this->padding_ + 1) / 2); itk::Size<3> hipad; hipad[0] = pd; hipad[1] = pd; hipad[2] = pd; unsigned long lowpad[3] = { pd, pd, pd }; padder->SetPadUpperBound(hipad); padder->SetPadLowerBound(hipad); padder->UpdateLargestPossibleRegion(); if (this->verbose_) { std::cout << "input region = " << img->GetBufferedRegion().GetSize() << std::endl; std::cout << "lowpad: " << lowpad[0] << " " << lowpad[1] << " " << lowpad[2] << std::endl; std::cout << "hipad: " << hipad[0] << " " << hipad[1] << " " << hipad[2] << std::endl; } this->images_[i] = padder->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: auto_pad" << std::endl; } } void ShapeWorksGroom::antialias(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: antialias on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start; i < end; i++) { auto img = this->images_[i]; itk::AntiAliasBinaryImageFilter<ImageType, ImageType>::Pointer anti = itk::AntiAliasBinaryImageFilter<ImageType, ImageType>::New(); anti->SetInput(img); anti->SetNumberOfIterations(this->iterations_); anti->SetMaximumRMSError(0.024); anti->Update(); this->images_[i] = anti->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: antialias" << std::endl; } } void ShapeWorksGroom::fastmarching(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: fastmarching on " << (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start; i < end; i++) { auto img = this->images_[i]; itk::ApproximateSignedDistanceMapImageFilter<ImageType, ImageType>::Pointer P = itk::ApproximateSignedDistanceMapImageFilter<ImageType, ImageType>::New(); P->SetInput(img); P->SetInsideValue(0); P->SetOutsideValue(1); P->Update(); this->images_[i] = P->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: fastmarching" << std::endl; } } void ShapeWorksGroom::blur(int which) { if (this->verbose_) { std::cout << "*** RUNNING TOOL: blur on "<< (which == -1 ? "all" : std::to_string(which)) << std::endl; } auto start = (which == -1 ? 0 : which); auto end = (which == -1 ? this->images_.size() : which + 1); for (size_t i = start ; i < end; i++) { auto img = this->images_[i]; itk::DiscreteGaussianImageFilter<ImageType, ImageType>::Pointer blur = itk::DiscreteGaussianImageFilter<ImageType, ImageType>::New(); blur->SetInput(img); blur->SetVariance(this->blurSigma_ * this->blurSigma_); blur->Update(); this->images_[i] = blur->GetOutput(); } if (this->verbose_) { std::cout << "*** FINISHED RUNNING TOOL: blur" << std::endl; } }
34.472296
100
0.627248
[ "vector" ]
ad7d879ffe1d6d27200f68fb281c4f100eba3243
1,690
cpp
C++
libraries/ADXL335/ADXL335.cpp
whileman133/balloon_sat
2ab016cc65d469230859014ab486567383269378
[ "MIT" ]
null
null
null
libraries/ADXL335/ADXL335.cpp
whileman133/balloon_sat
2ab016cc65d469230859014ab486567383269378
[ "MIT" ]
null
null
null
libraries/ADXL335/ADXL335.cpp
whileman133/balloon_sat
2ab016cc65d469230859014ab486567383269378
[ "MIT" ]
null
null
null
#include "Arduino.h" #include "ADXL335.h" ADXL335::ADXL335( float aref, int x_pin, int y_pin, int z_pin, MUX* mux, int muxPin ) { _aref = aref; _x_pin = x_pin; _y_pin = y_pin; _z_pin = z_pin; _mux = mux; _muxPin = muxPin; } void ADXL335::begin(void) { if( _mux ) { pinMode( _muxPin, INPUT); } // end if else { pinMode( _x_pin, INPUT ); pinMode( _y_pin, INPUT ); pinMode( _z_pin, INPUT ); } // end else } float ADXL335::voltageX(void) { float value = 0; // If a MUX object was passed in, select the supplied muxPin // before sampling the ADC value. if( _mux ) { (*_mux).select( (char)_x_pin ); value = analogRead( _muxPin ); } // end if else { value = analogRead( _x_pin ); } // end else return ((float)value * _aref) / 1023.0; } float ADXL335::voltageY(void) { float value; // If a MUX object was passed in, select the supplied muxPin // before sampling the ADC value. if( _mux ) { (*_mux).select( (char)_y_pin ); value = analogRead( _muxPin ); } // end if else { value = analogRead( _y_pin ); } // end else return ((float)value * _aref) / 1023.0; } float ADXL335::voltageZ(void) { float value; // If a MUX object was passed in, select the supplied muxPin // before sampling the ADC value. if( _mux ) { (*_mux).select( (char)_z_pin ); value = analogRead( _muxPin ); } // end if else { value = analogRead( _z_pin ); } // end else return ((float)value * _aref) / 1023.0; } float ADXL335::accelerationX(void) { return (voltageX() - 1.64)/0.3; } float ADXL335::accelerationY(void) { return (voltageY() - 1.64)/0.3; } float ADXL335::accelerationZ(void) { return (voltageZ() - 1.64)/0.3; }
14.824561
85
0.628402
[ "object" ]
ad821eb42f78f3fe871bbc8e116be2b8278e647f
4,364
cpp
C++
em andamento/fluxos/sources/flowsalg.cpp
kleberkruger/trabalhos-de-grafos
f55294909df093511f2b54c0929703c27c074636
[ "MIT" ]
null
null
null
em andamento/fluxos/sources/flowsalg.cpp
kleberkruger/trabalhos-de-grafos
f55294909df093511f2b54c0929703c27c074636
[ "MIT" ]
null
null
null
em andamento/fluxos/sources/flowsalg.cpp
kleberkruger/trabalhos-de-grafos
f55294909df093511f2b54c0929703c27c074636
[ "MIT" ]
null
null
null
// // Created by Kleber Kruger on 2019-06-04. // #include "flowsalg.h" enum Color { WHITE, GRAY, BLACK }; struct SearchVertex { int vertex; Edge *parent; Color color; explicit SearchVertex(int vertex) : vertex(vertex), parent(nullptr), color(WHITE) {} }; bool BFS(const Graph &graph, int s, int t, std::pair<int, std::vector<Edge *>> &path) { std::vector<SearchVertex> vertices; vertices.reserve(graph.vertices.size()); for (auto &v : graph.vertices) { vertices.emplace_back(v.id); } vertices[s].color = GRAY; path.first = std::numeric_limits<int>::max(); path.second.clear(); if (s == t) return true; std::deque<SearchVertex *> q; q.push_back(&vertices[s]); while (!q.empty()) { auto &u = q.front(); q.pop_front(); for (auto &e : graph.getAdjacencyList(u->vertex)) { if (e->capacity > 0) { auto &v = vertices[e->end]; if (v.color == WHITE) { v.color = GRAY; v.parent = e; q.push_back(&v); if (v.vertex == t) { // std::cout << "encontrei o " << v.vertex << std::endl; path.first = e->capacity; path.second.emplace_back(e); auto aux = e; while (aux->start != s) { // std::cout << aux->start << " " << aux->end << std::endl; aux = vertices[aux->start].parent; path.second.emplace_back(aux); if (aux->capacity < path.first) path.first = aux->capacity; } return true; } } } } u->color = BLACK; } return false; } bool DFSVisit(const Graph &graph, std::vector<SearchVertex> &vertices, int s, int t, std::pair<int, std::vector<Edge *>> &path) { auto &u = vertices[s]; u.color = GRAY; if (u.vertex == t) { u.color = BLACK; return true; } for (auto &e : graph.getAdjacencyList(u.vertex)) { if (e->capacity > 0) { auto &v = vertices[e->end]; if (v.color == WHITE) { if (DFSVisit(graph, vertices, v.vertex, t, path)) { if (e->capacity < path.first) path.first = e->capacity; path.second.push_back(e); return true; } } } } u.color = BLACK; return false; } bool DFS(const Graph &graph, int s, int t, std::pair<int, std::vector<Edge *>> &path) { std::vector<SearchVertex> vertices; vertices.reserve(graph.vertices.size()); for (auto &u : graph.vertices) { vertices.emplace_back(u.id); } path.first = std::numeric_limits<int>::max(); path.second.clear(); return DFSVisit(graph, vertices, s, t, path); } void compadreWashington(const InputInfo &in, OutputInfo &out, bool (*search)(const Graph &, int, int, std::pair<int, std::vector<Edge *>> &)) { std::pair<int, std::vector<Edge *>> path; out.total = 0; Graph residual = in.graph; for (auto &e : residual.edges) { residual.insertEdge(e.end, e.start, 0); } auto &matrix = in.graph.getMinAdjacencyMatrix(); auto &matrixR = residual.getMinAdjacencyMatrix(); while (search(residual, in.source, in.target, path)) { // for (auto p : path.second) std::cout << "(" << p->start << "," << p->end << ") "; // std::cout << path.first << std::endl; out.total += path.first; for (auto &e : path.second) { if (matrix[e->start][e->end] != nullptr) { matrix[e->start][e->end]->flow += path.first; } else { matrix[e->end][e->start]->flow -= path.first; } matrixR[e->start][e->end]->capacity -= path.first; matrixR[e->end][e->start]->capacity += path.first; } } std::cout << "Max Flow: " << out.total << std::endl; } void fordFulkerson(const InputInfo &in, OutputInfo &out) { compadreWashington(in, out, DFS); } void edmondsKarp(const InputInfo &in, OutputInfo &out) { compadreWashington(in, out, BFS); }
29.093333
105
0.501833
[ "vector" ]
ad88c91f699e30b524b8dcd130ec6e336e58f830
12,662
cpp
C++
eospac-wrapper/eospac_wrapper.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
3
2021-04-14T15:08:37.000Z
2021-06-28T16:32:19.000Z
eospac-wrapper/eospac_wrapper.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
70
2021-04-15T23:08:34.000Z
2022-03-31T17:43:18.000Z
eospac-wrapper/eospac_wrapper.cpp
lanl/singularity-eos
c35669b93a492903ad4ce7a15211bd42b7c88d37
[ "BSD-3-Clause" ]
2
2021-05-21T16:59:30.000Z
2021-08-17T20:52:38.000Z
//====================================================================== // sesame2spiner tool for converting eospac to spiner // Author: Jonah Miller (jonahm@lanl.gov) // © 2021. Triad National Security, LLC. All rights reserved. This // program was produced under U.S. Government contract 89233218CNA000001 // for Los Alamos National Laboratory (LANL), which is operated by Triad // National Security, LLC for the U.S. Department of Energy/National // Nuclear Security Administration. All rights in the program are // reserved by Triad National Security, LLC, and the U.S. Department of // Energy/National Nuclear Security Administration. The Government is // granted for itself and others acting on its behalf a nonexclusive, // paid-up, irrevocable worldwide license in this material to reproduce, // prepare derivative works, distribute copies to the public, perform // publicly and display publicly, and to permit others to do so. //====================================================================== #include <array> #include <iostream> #include <regex> #include <string> #include <vector> #include "eospac_wrapper.hpp" #include <eos_Interface.h> namespace EospacWrapper { void eosGetMetadata(int matid, SesameMetadata &metadata, Verbosity eospacWarn) { constexpr int NT = 2; EOS_INTEGER tableHandle[NT]; EOS_INTEGER tableType[NT] = {EOS_Info, EOS_Ut_DT}; EOS_INTEGER commentsHandle[1]; EOS_INTEGER commentsType[1] = {EOS_Comment}; constexpr int numInfoTables = 2; constexpr int NI[] = {5, 11}; std::array<std::vector<EOS_INTEGER>, numInfoTables> infoItems = { std::vector<EOS_INTEGER>{EOS_Exchange_Coeff, EOS_Mean_Atomic_Mass, EOS_Mean_Atomic_Num, EOS_Modulus, EOS_Normal_Density}, std::vector<EOS_INTEGER>{EOS_Rmin, EOS_Rmax, EOS_Tmin, EOS_Tmax, EOS_Fmin, EOS_Fmax, EOS_NR, EOS_NT, EOS_X_Convert_Factor, EOS_Y_Convert_Factor, EOS_F_Convert_Factor}}; std::vector<EOS_REAL> infoVals[numInfoTables]; for (int i = 0; i < numInfoTables; i++) { infoVals[i].resize(NI[i]); for (int j = 0; j < NI[i]; j++) { infoVals[i][j] = 0; } } eosSafeLoad(NT, matid, tableType, tableHandle, {"EOS_Info", "EOS_Ut_DT"}, eospacWarn); for (int i = 0; i < numInfoTables; i++) { eosSafeTableInfo(&(tableHandle[i]), NI[i], infoItems[i].data(), infoVals[i].data(), eospacWarn); } metadata.matid = matid; metadata.exchangeCoefficient = infoVals[0][0]; metadata.meanAtomicMass = infoVals[0][1]; metadata.meanAtomicNumber = infoVals[0][2]; metadata.solidBulkModulus = bulkModulusFromSesame(infoVals[0][3]); metadata.normalDensity = densityFromSesame(infoVals[0][4]); metadata.rhoMin = densityFromSesame(infoVals[1][0]); metadata.rhoMax = densityFromSesame(infoVals[1][1]); metadata.TMin = temperatureFromSesame(infoVals[1][2]); metadata.TMax = temperatureFromSesame(infoVals[1][3]); metadata.sieMin = sieFromSesame(infoVals[1][4]); metadata.sieMax = sieFromSesame(infoVals[1][5]); metadata.numRho = static_cast<int>(infoVals[1][6]); metadata.numT = static_cast<int>(infoVals[1][7]); metadata.rhoConversionFactor = infoVals[1][8]; metadata.TConversionFactor = infoVals[1][9]; metadata.sieConversionFactor = infoVals[1][10]; eosSafeDestroy(NT, tableHandle, eospacWarn); EOS_INTEGER errorCode = eosSafeLoad(1, matid, commentsType, commentsHandle, {"EOS_Comments"}, eospacWarn); EOS_INTEGER eospacComments = commentsHandle[0]; if (errorCode == EOS_OK) { std::vector<EOS_CHAR> comments; EOS_REAL commentLen; EOS_INTEGER commentItem = EOS_Cmnt_Len; eosSafeTableInfo(commentsHandle, 1, &commentItem, &commentLen, eospacWarn); comments.resize(static_cast<int>(commentLen)); metadata.comments.resize(comments.size()); eosSafeTableCmnts(&eospacComments, comments.data(), eospacWarn); for (size_t i = 0; i < comments.size(); i++) { metadata.comments[i] = comments[i]; } metadata.name = getName(metadata.comments); eosSafeDestroy(1, commentsHandle, eospacWarn); } else { std::string matid_str = std::to_string(matid); if (eospacWarn != Verbosity::Quiet) { std::cerr << "eos_GetMetadata: failed to get comments table. " << "Using default comments and name fields." << std::endl; } metadata.name = "No name for matid " + matid_str; metadata.comments = "Comment unavailable for matid " + matid_str; } } EOS_INTEGER eosSafeLoad(int ntables, int matid, EOS_INTEGER tableType[], EOS_INTEGER tableHandle[], Verbosity eospacWarn, bool invert_at_setup) { std::vector<std::string> empty; return eosSafeLoad(ntables, matid, tableType, tableHandle, empty, eospacWarn, invert_at_setup); } EOS_INTEGER eosSafeLoad(int ntables, int matid, EOS_INTEGER tableType[], EOS_INTEGER tableHandle[], const std::vector<std::string> &table_names, Verbosity eospacWarn, bool invert_at_setup) { EOS_INTEGER NTABLES[] = {ntables}; std::vector<EOS_INTEGER> MATID(ntables, matid); EOS_INTEGER errorCode = EOS_OK; EOS_INTEGER tableHandleErrorCode = EOS_OK; EOS_CHAR errorMessage[EOS_MaxErrMsgLen]; eos_CreateTables(NTABLES, tableType, MATID.data(), tableHandle, &errorCode); if (invert_at_setup) { EOS_INTEGER options[] = {EOS_INVERT_AT_SETUP, EOS_INSERT_DATA}; EOS_REAL values[] = {1., 4.}; for (int i = 0; i < ntables; i++) { if (tableType[i] == EOS_T_DUt) { eos_SetOption(&(tableHandle[i]), &(options[0]), &(values[0]), &errorCode); eos_SetOption(&(tableHandle[i]), &(options[1]), &(values[1]), &errorCode); } } } #ifdef SINGULARITY_EOSPAC_SKIP_EXTRAP for (int i = 0; i < ntables; i++) { eos_SetOption(&(tableHandle[i]), &EOS_SKIP_EXTRAP_CHECK, NULL, &errorCode); } #endif // SINGULARITY_EOSPAC_SKIP_EXTRAP eos_LoadTables(&ntables, tableHandle, &errorCode); if (errorCode != EOS_OK && eospacWarn != Verbosity::Quiet) { for (int i = 0; i < ntables; i++) { eos_GetErrorCode(&tableHandle[i], &tableHandleErrorCode); eos_GetErrorMessage(&tableHandleErrorCode, errorMessage); std::cerr << "eos_CreateTables ERROR " << tableHandleErrorCode; if (table_names.size() > 0) { std::cerr << " for table names\n\t{"; for (auto &name : table_names) { std::cerr << name << ", "; } std::cerr << "}"; } std::cerr << ":\n\t" << errorMessage << std::endl; } } return errorCode; } bool eosSafeInterpolate(EOS_INTEGER *table, EOS_INTEGER nxypairs, EOS_REAL xVals[], EOS_REAL yVals[], EOS_REAL var[], EOS_REAL dx[], EOS_REAL dy[], const char tablename[], Verbosity eospacWarn) { EOS_INTEGER errorCode = EOS_OK; EOS_CHAR errorMessage[EOS_MaxErrMsgLen]; eos_Interpolate(table, &nxypairs, xVals, yVals, var, dx, dy, &errorCode); #ifndef SINGULARITY_EOSPAC_SKIP_EXTRAP if (errorCode != EOS_OK && eospacWarn == Verbosity::Debug) { eos_GetErrorMessage(&errorCode, errorMessage); std::cerr << "Table " << tablename << ":" << std::endl; std::cerr << "eos_Interpolate ERROR " << errorCode << ": " << errorMessage << std::endl; std::vector<EOS_INTEGER> xyBounds(nxypairs); eos_CheckExtrap(table, &nxypairs, xVals, yVals, xyBounds.data(), &errorCode); for (size_t i = 0; i < xyBounds.size(); i++) { std::string status = eosErrorString(xyBounds[i]); std::cerr << "var " << i << ": " << status << std::endl; std::cerr << "x = " << xVals[i] << std::endl; std::cerr << "y = " << yVals[i] << std::endl; } } #endif // SINGULARITY_EOSPAC_SKIP_EXTRAP return (errorCode == EOS_OK); // 1 for no erros. 0 for errors. } void eosSafeTableInfo(EOS_INTEGER *table, EOS_INTEGER numInfoItems, EOS_INTEGER infoItems[], EOS_REAL infoVals[], Verbosity eospacWarn) { EOS_INTEGER errorCode = EOS_OK; // EOS_CHAR errorMessage[EOS_MaxErrMsgLen]; EOS_INTEGER NITEMS[] = {numInfoItems}; eos_GetTableInfo(table, NITEMS, infoItems, infoVals, &errorCode); eosCheckError(errorCode, "eos_GetTableInfo", eospacWarn); } void eosSafeTableCmnts(EOS_INTEGER *table, EOS_CHAR *comments, Verbosity eospacWarn) { EOS_INTEGER errorCode = EOS_OK; eos_GetTableCmnts(table, comments, &errorCode); eosCheckError(errorCode, "eos_GetTableCmnts", eospacWarn); } void eosCheckError(EOS_INTEGER errorCode, const std::string &name, Verbosity eospacWarn) { EOS_CHAR errorMessage[EOS_MaxErrMsgLen]; if (errorCode != EOS_OK && eospacWarn != Verbosity::Quiet) { eos_GetErrorMessage(&errorCode, errorMessage); std::cerr << name << " ERROR " << errorCode << ":\n\t" << errorMessage << std::endl; } } std::string eosErrorString(EOS_INTEGER errorCode) { // Algorithmicallly generated by parsing the EOSPAC docs // I'm sorry. It's gross. ~JMM switch (errorCode) { case EOS_OK: return "EOS_OK"; case EOS_BAD_DATA_TYPE: return "EOS_BAD_DATA_TYPE"; case EOS_BAD_DERIVATIVE_FLAG: return "EOS_BAD_DERIVATIVE_FLAG"; case EOS_BAD_INTERPOLATION_FLAG: return "EOS_BAD_INTERPOLATION_FLAG"; case EOS_BAD_MATERIAL_ID: return "EOS_BAD_MATERIAL_ID"; case EOS_CANT_INVERT_DATA: return "EOS_CANT_INVERT_DATA"; case EOS_CANT_MAKE_MONOTONIC: return "EOS_CANT_MAKE_MONOTONIC"; case EOS_CONVERGENCE_FAILED: return "EOS_CONVERGENCE_FAILED"; case EOS_DATA_TYPE_NOT_FOUND: return "EOS_DATA_TYPE_NOT_FOUND"; case EOS_DATA_TYPE_NO_MATCH: return "EOS_DATA_TYPE_NO_MATCH"; case EOS_FAILED: return "EOS_FAILED"; case EOS_INTEGRATION_FAILED: return "EOS_INTEGRATION_FAILED"; case EOS_INTERP_EXTRAPOLATED: return "EOS_INTERP_EXTRAPOLATED"; case EOS_INTERP_EXTRAP_PBAL: return "EOS_INTERP_EXTRAP_PBAL"; case EOS_INTERP_EXTRAP_TBAL: return "EOS_INTERP_EXTRAP_TBAL"; case EOS_INVALID_CONC_SUM: return "EOS_INVALID_CONC_SUM"; case EOS_INVALID_DATA_TYPE: return "EOS_INVALID_DATA_TYPE"; case EOS_INVALID_INFO_FLAG: return "EOS_INVALID_INFO_FLAG"; case EOS_INVALID_OPTION_FLAG: return "EOS_INVALID_OPTION_FLAG"; case EOS_INVALID_SUBTABLE_INDEX: return "EOS_INVALID_SUBTABLE_INDEX"; case EOS_INVALID_TABLE_HANDLE: return "EOS_INVALID_TABLE_HANDLE"; case EOS_MATERIAL_NOT_FOUND: return "EOS_MATERIAL_NOT_FOUND"; case EOS_MEM_ALLOCATION_FAILED: return "EOS_MEM_ALLOCATION_FAILED"; case EOS_NOT_ALLOCATED: return "EOS_NOT_ALLOCATED"; case EOS_NOT_INITIALIZED: return "EOS_NOT_INITIALIZED"; case EOS_NO_COMMENTS: return "EOS_NO_COMMENTS"; case EOS_NO_DATA_TABLE: return "EOS_NO_DATA_TABLE"; case EOS_NO_SESAME_FILES: return "EOS_NO_SESAME_FILES"; case EOS_OPEN_SESAME_FILE_FAILED: return "EOS_OPEN_SESAME_FILE_FAILED"; case EOS_READ_DATA_FAILED: return "EOS_READ_DATA_FAILED"; case EOS_READ_FILE_VERSION_FAILED: return "EOS_READ_FILE_VERSION_FAILED"; case EOS_READ_MASTER_DIR_FAILED: return "EOS_READ_MASTER_DIR_FAILED"; case EOS_READ_MATERIAL_DIR_FAILED: return "EOS_READ_MATERIAL_DIR_FAILED"; case EOS_READ_TOTAL_MATERIALS_FAILED: return "EOS_READ_TOTAL_MATERIALS_FAILED"; case EOS_SPLIT_FAILED: return "EOS_SPLIT_FAILED"; case EOS_xHi_yHi: return "EOS_xHi_yHi"; case EOS_xHi_yOk: return "EOS_xHI_yOk"; case EOS_xHi_yLo: return "EOS_xHi_yLo"; case EOS_xOk_yLo: return "EOS_xOk_yLo"; case EOS_xLo_yLo: return "EOS_xLo_yLo"; case EOS_xLo_yOk: return "EOS_xLo_yOk"; case EOS_xLo_yHi: return "EOS_xLo_yHi"; case EOS_xOk_yHi: return "EOS_xOk_yHi"; case EOS_WARNING: return "EOS_WARNING"; case EOS_UNDEFINED: return "EOS_UNDEFINED"; default: return "UNKNOWN ERROR: " + std::to_string(errorCode); } } void eosSafeDestroy(int ntables, EOS_INTEGER tableHandles[], Verbosity eospacWarn) { EOS_INTEGER errorCode = EOS_OK; // EOS_CHAR errorMessage[EOS_MaxErrMsgLen]; EOS_INTEGER NTABLES[] = {ntables}; eos_DestroyTables(NTABLES, tableHandles, &errorCode); eosCheckError(errorCode, "eos_DestroyTables", eospacWarn); } std::string getName(std::string comment) { // required because lookbehinds not supported // constexpr int startPos=15; std::regex r("101: material. (.*)(?=\\s+\\(z)"); std::smatch match; if (std::regex_search(comment, match, r)) { return std::string(match[0]).substr(15); } std::string badstring("-1"); return badstring; } } // namespace EospacWrapper
37.797015
90
0.688991
[ "vector" ]
ad894c9b01ac85413461303fab82ba167021b423
9,036
cpp
C++
Gem/Code/Source/SceneReloadSoakTestComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
15
2021-07-07T02:16:06.000Z
2022-03-22T07:39:06.000Z
Gem/Code/Source/SceneReloadSoakTestComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
66
2021-07-07T00:01:05.000Z
2022-03-28T06:37:41.000Z
Gem/Code/Source/SceneReloadSoakTestComponent.cpp
Bindless-Chicken/o3de-atom-sampleviewer
13b11996079675445ce4e321f53c3ac79e01702d
[ "Apache-2.0", "MIT" ]
13
2021-07-06T18:21:33.000Z
2022-01-04T18:29:18.000Z
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <SceneReloadSoakTestComponent.h> #include <SampleComponentManager.h> #include <SampleComponentConfig.h> #include <Atom/RPI.Reflect/Model/ModelAsset.h> #include <Atom/RPI.Reflect/Material/MaterialAsset.h> #include <Atom/Component/DebugCamera/NoClipControllerBus.h> #include <AzCore/Component/Entity.h> #include <RHI/BasicRHIComponent.h> #include <SceneReloadSoakTestComponent_Traits_Platform.h> namespace AtomSampleViewer { using namespace AZ; using namespace RPI; void SceneReloadSoakTestComponent::Reflect(ReflectContext* context) { if (SerializeContext* serializeContext = azrtti_cast<SerializeContext*>(context)) { serializeContext->Class<SceneReloadSoakTestComponent, EntityLatticeTestComponent>() ->Version(0) ; } } void SceneReloadSoakTestComponent::Activate() { m_timeSettings.clear(); m_timeSettings.push_back(TimeSetting{2.0f, 1}); m_timeSettings.push_back(TimeSetting{0.2f, 50}); m_timeSettings.push_back(TimeSetting{0.5f, 10}); m_timeSettings.push_back(TimeSetting{1.0f, 5}); m_countdown = 0; m_totalTime = 0; m_currentSettingIndex = 0; m_currentCount = 0; m_totalResetCount = 0; SetLatticeDimensions(ATOMSAMPLEVIEWER_TRAIT_SCENE_RELOAD_SOAK_TEST_COMPONENT_LATTICE_SIZE, ATOMSAMPLEVIEWER_TRAIT_SCENE_RELOAD_SOAK_TEST_COMPONENT_LATTICE_SIZE, ATOMSAMPLEVIEWER_TRAIT_SCENE_RELOAD_SOAK_TEST_COMPONENT_LATTICE_SIZE); Base::Activate(); TickBus::Handler::BusConnect(); ExampleComponentRequestBus::Handler::BusConnect(GetEntityId()); } void SceneReloadSoakTestComponent::Deactivate() { ExampleComponentRequestBus::Handler::BusDisconnect(); TickBus::Handler::BusDisconnect(); Base::Deactivate(); } void SceneReloadSoakTestComponent::ResetCamera() { Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &Debug::NoClipControllerRequestBus::Events::SetHeading, DegToRad(-25)); Debug::NoClipControllerRequestBus::Event(GetCameraEntityId(), &Debug::NoClipControllerRequestBus::Events::SetPitch, DegToRad(25)); } void SceneReloadSoakTestComponent::PrepareCreateLatticeInstances(uint32_t instanceCount) { m_materialIsUnique.reserve(instanceCount); m_meshHandles.reserve(instanceCount); const char* materialPath = DefaultPbrMaterialPath; const char* modelPath = "objects/shaderball_simple.azmodel"; Data::AssetCatalogRequestBus::BroadcastResult( m_materialAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, materialPath, azrtti_typeid<MaterialAsset>(), false); Data::AssetCatalogRequestBus::BroadcastResult( m_modelAssetId, &Data::AssetCatalogRequestBus::Events::GetAssetIdByPath, modelPath, azrtti_typeid<ModelAsset>(), false); AZ_Assert(m_materialAssetId.IsValid(), "Failed to get material asset id: %s", materialPath); AZ_Assert(m_modelAssetId.IsValid(), "Failed to get model asset id: %s", modelPath); } void SceneReloadSoakTestComponent::CreateLatticeInstance(const Transform& transform) { Render::MaterialAssignmentMap materials; Render::MaterialAssignment& defaultMaterial = materials[Render::DefaultMaterialAssignmentId]; defaultMaterial.m_materialAsset = Data::AssetManager::Instance().GetAsset<MaterialAsset>(m_materialAssetId, AZ::Data::AssetLoadBehavior::PreLoad); defaultMaterial.m_materialAsset.BlockUntilLoadComplete(); // We have a mixture of both unique and shared instance to give more variety and therefore more opportunity for things to break. bool materialIsUnique = (m_materialIsUnique.size() % 2) == 0; defaultMaterial.m_materialInstance = materialIsUnique ? Material::Create(defaultMaterial.m_materialAsset) : Material::FindOrCreate(defaultMaterial.m_materialAsset); m_materialIsUnique.push_back(materialIsUnique); Data::Asset<ModelAsset> modelAsset; modelAsset.Create(m_modelAssetId); auto meshHandle = GetMeshFeatureProcessor()->AcquireMesh(Render::MeshHandleDescriptor{ modelAsset }, materials); GetMeshFeatureProcessor()->SetTransform(meshHandle, transform); m_meshHandles.push_back(AZStd::move(meshHandle)); } void SceneReloadSoakTestComponent::DestroyLatticeInstances() { m_materialIsUnique.clear(); for (auto& meshHandle : m_meshHandles) { GetMeshFeatureProcessor()->ReleaseMesh(meshHandle); } m_meshHandles.clear(); } void SceneReloadSoakTestComponent::OnTick(float deltaTime, [[maybe_unused]] ScriptTimePoint scriptTime) { // There are some crashes that specifically occurred when unloading a scene while compiling material changes { // Create a new SimpleLcgRandom every time TickMaterialUpdate is called to keep a consistent seed and consistent color selection. SimpleLcgRandom random; bool updatedSharedMaterialInstance = false; size_t entityIndex = 0; MaterialPropertyIndex colorPropertyIndex; for (auto& meshHandle : m_meshHandles) { const Render::MaterialAssignmentMap& materials = GetMeshFeatureProcessor()->GetMaterialAssignmentMap(meshHandle); const auto defaultMaterialItr = materials.find(Render::DefaultMaterialAssignmentId); const auto& defaultMaterial = defaultMaterialItr != materials.end() ? defaultMaterialItr->second : Render::MaterialAssignment(); Data::Instance<Material> material = defaultMaterial.m_materialInstance; if (material == nullptr) { continue; } static const float speed = 4.0f; const float t = static_cast<float>(sin(m_totalTime * speed) * 0.5f + 0.5f); static const Color colorOptions[] = { Color(1.0f, 0.0f, 0.0f, 1.0f), Color(0.0f, 1.0f, 0.0f, 1.0f), Color(0.0f, 0.0f, 1.0f, 1.0f), Color(1.0f, 1.0f, 0.0f, 1.0f), Color(0.0f, 1.0f, 1.0f, 1.0f), Color(1.0f, 0.0f, 1.0f, 1.0f), }; const int colorIndexA = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions); int colorIndexB = colorIndexA; while (colorIndexA == colorIndexB) { colorIndexB = random.GetRandom() % AZ_ARRAY_SIZE(colorOptions); } const Color color = colorOptions[colorIndexA] * t + colorOptions[colorIndexB] * (1.0f - t); if (m_materialIsUnique[entityIndex] || !updatedSharedMaterialInstance) { if (colorPropertyIndex.IsNull()) { colorPropertyIndex = material->FindPropertyIndex(Name("baseColor.color")); } if (colorPropertyIndex.IsValid()) { material->SetPropertyValue(colorPropertyIndex, color); if (!m_materialIsUnique[entityIndex]) { updatedSharedMaterialInstance = true; } } else { AZ_Error("", false, "Could not find the color property index"); } material->Compile(); } entityIndex++; } } m_countdown -= deltaTime; m_totalTime += deltaTime; // Rebuild the scene every time the countdown expires. // We might also need to move to the next TimeSetting with a new countdown time. if (m_countdown < 0) { TimeSetting currentSetting = m_timeSettings[m_currentSettingIndex % m_timeSettings.size()]; m_countdown = currentSetting.resetDelay; // The TimeSetting struct tells us how many times we should use it, before moving to the next TimeSetting struct m_currentCount++; if (m_currentCount >= currentSetting.count) { m_currentCount = 0; m_currentSettingIndex++; } m_totalResetCount++; AZ_TracePrintf("", "SceneReloadSoakTest RESET # %d @ time %f. Next reset in %f s\n", m_totalResetCount, m_totalTime, m_countdown); RebuildLattice(); } } } // namespace AtomSampleViewer
40.520179
239
0.634683
[ "render", "model", "transform", "3d" ]
ad8b0978e92d8ab654be41a2cba2f0e2d014b54f
538
cpp
C++
lesson15_NumberSolitaire.cpp
Nadesri/my-codility-solutions
76a724c262f5be7abf58bfad2e80874e1dedbf52
[ "MIT" ]
null
null
null
lesson15_NumberSolitaire.cpp
Nadesri/my-codility-solutions
76a724c262f5be7abf58bfad2e80874e1dedbf52
[ "MIT" ]
null
null
null
lesson15_NumberSolitaire.cpp
Nadesri/my-codility-solutions
76a724c262f5be7abf58bfad2e80874e1dedbf52
[ "MIT" ]
null
null
null
#include <algorithm> int calcMaxScoreAtI(vector<int> &aMaxSoFar, int currSquare, int i); int solution(vector<int> &A) { int n = A.size(); vector<int> aScoreAt(n); for (int i=0; i < n; i++) { aScoreAt[i] = calcMaxScoreAtI(aScoreAt, A[i], i); } return aScoreAt[n-1]; } int calcMaxScoreAtI(vector<int> &aMaxSoFar, int currSquare, int i) { int a = max(i-6, 0); int m = aMaxSoFar[a]+currSquare; for (int ind=a+1; ind<i; ind++) { m = max(m, currSquare + aMaxSoFar[ind]); } return m; }
24.454545
68
0.591078
[ "vector" ]
ad8f2682593a2dbc9ccb934e28db9affcabe82cc
1,691
cpp
C++
src/visualizer/Display-definitions.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
1,024
2019-09-20T22:55:09.000Z
2022-03-30T13:00:14.000Z
src/visualizer/Display-definitions.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
154
2019-09-23T13:10:33.000Z
2022-03-07T02:36:52.000Z
src/visualizer/Display-definitions.cpp
lefthandwriter/Kimera-VIO
641576fd86bdecbd663b4db3cb068f49502f3a2c
[ "BSD-2-Clause" ]
314
2019-09-20T23:49:05.000Z
2022-03-30T06:21:38.000Z
/* ---------------------------------------------------------------------------- * Copyright 2017, Massachusetts Institute of Technology, * Cambridge, MA 02139 * All Rights Reserved * Authors: Luca Carlone, et al. (see THANKS for the full author list) * See LICENSE for the license information * -------------------------------------------------------------------------- */ /** * @file Display-definitions.cpp * @brief Definitions for display module * @author Antoni Rosinol */ #include "kimera-vio/visualizer/Display-definitions.h" #include <opencv2/opencv.hpp> #include <gflags/gflags.h> #include <glog/logging.h> DEFINE_int32(mesh_shading, 0, "Mesh shading:\n 0: Flat, 1: Gouraud, 2: Phong"); DEFINE_int32(mesh_representation, 1, "Mesh representation:\n 0: Points, 1: Surface, 2: Wireframe"); DEFINE_bool(set_mesh_ambient, false, "Whether to use ambient light for the " "mesh."); DEFINE_bool(set_mesh_lighting, true, "Whether to use lighting for the mesh."); namespace VIO { // Contains internal data for Visualizer3D window. WindowData::WindowData() : window_(cv::viz::Viz3d("3D Visualizer")), mesh_representation_(FLAGS_mesh_representation), mesh_shading_(FLAGS_mesh_shading), mesh_ambient_(FLAGS_set_mesh_ambient), mesh_lighting_(FLAGS_set_mesh_lighting) {} WindowData::~WindowData() { // OpenCV 3d Viz has an issue that I can't resolve, it throws a segfault // at the end of the program. Probably because of memory not released. // See issues in opencv git: // https://github.com/opencv/opencv/issues/11219 and many more... window_.close(); } } // namespace VIO
33.156863
80
0.637493
[ "mesh", "3d" ]
ad91906d14f82f4f56cbfdedaf3773173e28d1cc
12,866
cpp
C++
OgreMain/src/OgreDecal.cpp
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
1
2021-05-12T18:01:21.000Z
2021-05-12T18:01:21.000Z
OgreMain/src/OgreDecal.cpp
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
1
2020-07-25T19:20:07.000Z
2020-07-25T19:20:07.000Z
OgreMain/src/OgreDecal.cpp
Stazer/ogre-next
4d3aa2aedf4575ac8a9e32a4e2af859562752d51
[ "MIT" ]
1
2021-09-28T18:44:28.000Z
2021-09-28T18:44:28.000Z
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2018 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 "OgreDecal.h" #include "OgreForwardPlusBase.h" #include "OgreSceneManager.h" #include "OgreRoot.h" #include "OgreHlms.h" #include "OgreHlmsManager.h" namespace Ogre { Decal::Decal( IdType id, ObjectMemoryManager *objectMemoryManager, SceneManager *manager ) : MovableObject( id, objectMemoryManager, manager, ForwardPlusBase::MinDecalRq ), mDiffuseTexture( 0 ), mNormalTexture( 0 ), mEmissiveTexture( 0 ), mDiffuseIdx( 0 ), mNormalMapIdx( 0 ), mEmissiveIdx( 0 ), mIgnoreDiffuseAlpha( 0 ), mMetalness( 1.0f ), mRoughness( 1.0f ) { //NOTE: For performance reasons, ForwardClustered::collectLightForSlice ignores //mLocalAabb & mWorldAabb and assumes its local AABB is this aabb we set as //default. To change its shape, use node scaling Aabb aabb( Vector3::ZERO, Vector3::UNIT_SCALE * 0.5f ); mObjectData.mLocalAabb->setFromAabb( aabb, mObjectData.mIndex ); mObjectData.mWorldAabb->setFromAabb( aabb, mObjectData.mIndex ); const float radius = aabb.getRadius(); mObjectData.mLocalRadius[mObjectData.mIndex] = radius; mObjectData.mWorldRadius[mObjectData.mIndex] = radius; //Disable shadow casting by default. Otherwise it's a waste or resources setCastShadows( false ); } //----------------------------------------------------------------------------------- Decal::~Decal() { if( mDiffuseTexture && mDiffuseTexture->hasAutomaticBatching() ) { mDiffuseTexture->removeListener( this ); mDiffuseTexture = 0; } if( mNormalTexture && mNormalTexture->hasAutomaticBatching() ) { mNormalTexture->removeListener( this ); mNormalTexture= 0; } if( mEmissiveTexture && mEmissiveTexture->hasAutomaticBatching() ) { mEmissiveTexture->removeListener( this ); mEmissiveTexture= 0; } } //----------------------------------------------------------------------------------- void Decal::setDiffuseTexture( TextureGpu *diffuseTex ) { if( mDiffuseTexture && mDiffuseTexture->hasAutomaticBatching() ) mDiffuseTexture->removeListener( this ); if( diffuseTex ) { OGRE_ASSERT_LOW( diffuseTex->hasAutomaticBatching() && "If the texture does is not AutomaticBatching, the use Raw calls!" ); OGRE_ASSERT_LOW( diffuseTex->getTextureType() == TextureTypes::Type2D ); diffuseTex->addListener( this ); diffuseTex->scheduleTransitionTo( GpuResidency::Resident ); mDiffuseTexture = diffuseTex; mDiffuseIdx = static_cast<uint16>( diffuseTex->getInternalSliceStart() ); } else { mDiffuseTexture = 0; mDiffuseIdx = 0; } } //----------------------------------------------------------------------------------- TextureGpu* Decal::getDiffuseTexture(void) const { return mDiffuseTexture; } //----------------------------------------------------------------------------------- void Decal::setNormalTexture( TextureGpu *normalTex ) { if( mNormalTexture && mNormalTexture->hasAutomaticBatching() ) mNormalTexture->removeListener( this ); if( normalTex ) { OGRE_ASSERT_LOW( normalTex->hasAutomaticBatching() && "If the texture does is not AutomaticBatching, the use Raw calls!" ); OGRE_ASSERT_LOW( normalTex->getTextureType() == TextureTypes::Type2D ); normalTex->addListener( this ); normalTex->scheduleTransitionTo( GpuResidency::Resident ); mNormalTexture = normalTex; mNormalMapIdx = static_cast<uint16>( normalTex->getInternalSliceStart() ); } else { mNormalTexture = 0; mNormalMapIdx = 0; } } //----------------------------------------------------------------------------------- TextureGpu* Decal::getNormalTexture(void) const { return mNormalTexture; } //----------------------------------------------------------------------------------- void Decal::setEmissiveTexture( TextureGpu *emissiveTex ) { if( mEmissiveTexture && mEmissiveTexture->hasAutomaticBatching() ) mEmissiveTexture->removeListener( this ); if( emissiveTex ) { OGRE_ASSERT_LOW( emissiveTex->hasAutomaticBatching() && "If the texture does is not AutomaticBatching, the use Raw calls!" ); OGRE_ASSERT_LOW( emissiveTex->getTextureType() == TextureTypes::Type2D ); emissiveTex->addListener( this ); emissiveTex->scheduleTransitionTo( GpuResidency::Resident ); mEmissiveTexture = emissiveTex; mEmissiveIdx = static_cast<uint16>( emissiveTex->getInternalSliceStart() ); } else { mEmissiveTexture = 0; mEmissiveIdx = 0; } } //----------------------------------------------------------------------------------- void Decal::setDiffuseTextureRaw( TextureGpu *diffuseTex, uint32 sliceIdx ) { if( mDiffuseTexture && mDiffuseTexture->hasAutomaticBatching() ) mDiffuseTexture->removeListener( this ); OGRE_ASSERT_LOW( (!diffuseTex || !diffuseTex->hasAutomaticBatching()) && "Only use Raw call if texture is not AutomaticBatching!" ); OGRE_ASSERT_LOW( diffuseTex->getTextureType() == TextureTypes::Type2DArray ); mDiffuseTexture = diffuseTex; mDiffuseIdx = sliceIdx; } //----------------------------------------------------------------------------------- void Decal::setNormalTextureRaw( TextureGpu *normalTex, uint32 sliceIdx ) { if( mNormalTexture && mNormalTexture->hasAutomaticBatching() ) mNormalTexture->removeListener( this ); OGRE_ASSERT_LOW( (!normalTex || !normalTex->hasAutomaticBatching()) && "Only use Raw call if texture is not AutomaticBatching!" ); OGRE_ASSERT_LOW( normalTex->getTextureType() == TextureTypes::Type2DArray ); mNormalTexture = normalTex; mNormalMapIdx = sliceIdx; } //----------------------------------------------------------------------------------- void Decal::setEmissiveTextureRaw( TextureGpu *emissiveTex, uint32 sliceIdx ) { if( mEmissiveTexture && mEmissiveTexture->hasAutomaticBatching() ) mEmissiveTexture->removeListener( this ); OGRE_ASSERT_LOW( (!emissiveTex || !emissiveTex->hasAutomaticBatching()) && "Only use Raw call if texture is not AutomaticBatching!" ); OGRE_ASSERT_LOW( emissiveTex->getTextureType() == TextureTypes::Type2DArray ); mEmissiveTexture = emissiveTex; mEmissiveIdx = sliceIdx; } //----------------------------------------------------------------------------------- TextureGpu* Decal::getEmissiveTexture(void) const { return mEmissiveTexture; } //----------------------------------------------------------------------------------- void Decal::setIgnoreAlphaDiffuse( bool bIgnore ) { mIgnoreDiffuseAlpha = bIgnore ? 1u : 0u; } //----------------------------------------------------------------------------------- bool Decal::getIgnoreAlphaDiffuse(void) const { return mIgnoreDiffuseAlpha != 0u; } //----------------------------------------------------------------------------------- void Decal::setRoughness( float roughness ) { mRoughness = std::max( roughness, 0.02f ); } //----------------------------------------------------------------------------------- void Decal::setMetalness( float value ) { mMetalness = value; } //----------------------------------------------------------------------------------- void Decal::setRectSize( Vector2 planeDimensions, Real depth ) { if( mParentNode ) mParentNode->setScale( planeDimensions.x, depth, planeDimensions.y ); } //----------------------------------------------------------------------------------- const String& Decal::getMovableType(void) const { return DecalFactory::FACTORY_TYPE_NAME; } //----------------------------------------------------------------------------------- void Decal::setRenderQueueGroup(uint8 queueID) { assert( queueID >= ForwardPlusBase::MinDecalRq && queueID <= ForwardPlusBase::MaxDecalRq && "RenderQueue IDs > 128 are reserved for other Forward+ objects" ); MovableObject::setRenderQueueGroup( queueID ); } //----------------------------------------------------------------------------------- void Decal::notifyTextureChanged( TextureGpu *texture, TextureGpuListener::Reason reason, void *extraData ) { if( reason == TextureGpuListener::PoolTextureSlotChanged ) { if( texture == mDiffuseTexture ) mDiffuseIdx = static_cast<uint16>( mDiffuseTexture->getInternalSliceStart() ); if( texture == mNormalTexture ) mNormalMapIdx = static_cast<uint16>( mNormalTexture->getInternalSliceStart() ); if( texture == mEmissiveTexture ) mEmissiveIdx = static_cast<uint16>( mEmissiveTexture->getInternalSliceStart() ); } else if( reason == TextureGpuListener::Deleted ) { if( texture == mDiffuseTexture ) { mDiffuseIdx = 0; mDiffuseTexture->removeListener( this ); mDiffuseTexture = 0; } if( texture == mNormalTexture ) { mNormalMapIdx = 0; mNormalTexture->removeListener( this ); mNormalTexture = 0; } if( texture == mEmissiveTexture ) { mEmissiveIdx = 0; mEmissiveTexture->removeListener( this ); mEmissiveTexture = 0; } } } //----------------------------------------------------------------------- //----------------------------------------------------------------------- //----------------------------------------------------------------------- String DecalFactory::FACTORY_TYPE_NAME = "Decal"; //----------------------------------------------------------------------- const String& DecalFactory::getType(void) const { return FACTORY_TYPE_NAME; } //----------------------------------------------------------------------- MovableObject* DecalFactory::createInstanceImpl( IdType id, ObjectMemoryManager *objectMemoryManager, SceneManager *manager, const NameValuePairList* params ) { Decal* decal = OGRE_NEW Decal( id, objectMemoryManager, manager ); return decal; } //----------------------------------------------------------------------- void DecalFactory::destroyInstance( MovableObject* obj) { OGRE_DELETE obj; } }
43.466216
99
0.515933
[ "object", "shape" ]
74f12824ee823bf9e497d323f31b0077a83fca45
28,270
cc
C++
old-software/kpixSw/sidApi/online/SidLink.cc
slaclab/kpix
abf5b87f9a5d25e4810fc5be523bdcc76c5cba91
[ "BSD-3-Clause-LBNL" ]
null
null
null
old-software/kpixSw/sidApi/online/SidLink.cc
slaclab/kpix
abf5b87f9a5d25e4810fc5be523bdcc76c5cba91
[ "BSD-3-Clause-LBNL" ]
3
2021-04-06T08:33:01.000Z
2021-04-30T16:16:33.000Z
old-software/kpixSw/sidApi/online/SidLink.cc
slaclab/kpix
abf5b87f9a5d25e4810fc5be523bdcc76c5cba91
[ "BSD-3-Clause-LBNL" ]
1
2020-12-12T22:58:44.000Z
2020-12-12T22:58:44.000Z
//----------------------------------------------------------------------------- // File : SidLink.cc // Author : Ryan Herbst <rherbst@slac.stanford.edu> // Created : 10/26/2006 // Project : SID Electronics API //----------------------------------------------------------------------------- // Description : // Class to handle IO operations to and from the SID electronics device. // This module supports both direct USB drivers and VCP drivers. // Link to the KPIX low level simulation is also supported. // stty notes: // Noticed freeze up in some cases. It seemed the flag ignbrk was set on the // interface and was causing problems. running stty --file=/dev/ttyUSB0 -ignbrk // seemed to fix the problem. // known working stty settings: // stty --file=/dev/ttyUSB0 raw //----------------------------------------------------------------------------- // Copyright (c) 2009 by SLAC. All rights reserved. // Proprietary and confidential to SLAC. //----------------------------------------------------------------------------- // Modification history : // 10/26/2006: created // 11/09/2006: Added 0x before every hex value printed. // 11/10/2006: Added support for link to KPIX simulation. // 04/27/2007: Modified for new communication protocol and add of fpga registers // 04/30/2007: Modified to throw strings instead of const char * // 07/31/2007: Fixed bug which was keeping direct mode USB device 0 from working // 08/03/2007: Removed reset and purge from direct link open, added direct // mode access to flush, added read/write timeout to direct mode // 01/10/2007: Added IOCTL call to set proper parameters to usb VCP interface. // 03/09/2009: Added echo read for simulation mode. // 06/18/2009: Changed read and write functions to save CPU cycles. // 06/22/2009: Added namespaces. // 06/23/2009: Removed namespaces. // 10/14/2010: Added UDP support. //----------------------------------------------------------------------------- #include <iostream> #include <iomanip> #include <sstream> #include <string> #include <fcntl.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <lockdev.h> #include <sys/ioctl.h> #include <termio.h> #include <sys/types.h> #include <sys/socket.h> #include <netdb.h> #include "../ftdi/ftd2xx.h" #include "SidLink.h" using namespace std; // Internal queue functions bool SidLink::qpush ( unsigned short value, unsigned int type, bool sof, bool eof ) { unsigned int next; unsigned int word; word = value; word += (type << 16) & 0x30000; if ( sof ) word += 0x40000; if ( eof ) word += 0x80000; next = (qwrite + 1) % qsize; if ( next != qread ) { qdata[qwrite] = word; qwrite = next; return true; } else return false; } bool SidLink::qpop ( unsigned short *value, unsigned int *type, bool *sof, bool *eof ) { unsigned int next; unsigned int word; if ( qread == qwrite ) return false; next = (qread + 1) % qsize; word = qdata[qread]; qread = next; *value = word & 0xFFFF; *type = (word >> 16) & 0x3; *sof = (word & 0x40000) != 0; *eof = (word & 0x80000) != 0; return true; } bool SidLink::qready () { return(qread != qwrite); } void SidLink::qinit () { qread = 0; qwrite = 0; } // Serial class constructor. This constructore // does nothing but create the base object. Serial // link must be opened. SidLink::SidLink () { // Init device value serDevice = ""; serFd = -1; serFdRd = -1; usbDevice = -1; usbHandle = NULL; enDebug = false; timeoutEn = true; maxRxSize = 0; udpHost = ""; udpPort = 0; udpFd = -1; udpAddr = malloc(sizeof(struct sockaddr_in)); qinit(); } // Deconstructor SidLink::~SidLink ( ) { if ( serFd >= 0 || usbDevice >= 0 || udpFd >= 0 ) linkClose(); free(udpAddr); } // Open link to SID devices, VCP driver version // Pass path to serial device for VCP driver // Throws exception on device open failure void SidLink::linkOpen ( string device ) { stringstream error; struct termio svbuf; // Make sure no links are open if ( serFd >= 0 || usbDevice >= 0 || udpFd >= 0 ) throw string("SidLink::linkOpen -> SID Link Already Open"); if ( enDebug ) cout << "SidLink::linkOpen -> Attempting to open VCP USB device " << device << "\n"; // Attempt to open serial port if ((serFd=open(device.c_str(), O_RDWR|O_NOCTTY|O_NONBLOCK)) < 0) { error << "SidLink::linkOpen -> Error opening VCP USB device " << device; throw error.str(); } // Setup serial port ioctl(serFd,TCGETA,&svbuf); svbuf.c_iflag = 0; svbuf.c_oflag = 0; svbuf.c_lflag = 0; svbuf.c_cflag = B38400 | CS8 | CLOCAL | CREAD; ioctl(serFd,TCSETA,&svbuf); // Debug cout << "SidLink::linkOpen -> Opened VCP USB device " << device << ".\n"; // Set device variable serDevice = device; maxRxSize = 0; } // Open link to SID devices, UDP Version // Pass hostname and port of UDP host // Throws exception on device open failure void SidLink::linkOpen ( string host, int port ) { struct addrinfo* aiList=0; struct addrinfo aiHints; const sockaddr_in* addr; int error; unsigned int size; // Make sure no links are open if ( serFd >= 0 || usbDevice >= 0 || udpFd >= 0 ) throw string("SidLink::linkOpen -> SID Link Already Open"); if ( enDebug ) cout << "SidLink::linkOpen -> Attempting to open UDP device " << host << ":" << port << "\n"; // Create socket udpFd = socket(AF_INET,SOCK_DGRAM,0); if ( udpFd == -1 ) throw string("SidLink::linkOpen -> Could Not Create Socket"); // Lookup host address aiHints.ai_flags = AI_CANONNAME; aiHints.ai_family = AF_INET; aiHints.ai_socktype = SOCK_DGRAM; aiHints.ai_protocol = IPPROTO_UDP; error = ::getaddrinfo(host.c_str(), 0, &aiHints, &aiList); if (error || !aiList) throw string("SidLink::linkOpen -> Error Getting Resolving Hostname"); addr = (const sockaddr_in*)(aiList->ai_addr); // Setup Remote Address memset(udpAddr,0,sizeof(struct sockaddr_in)); ((sockaddr_in *)udpAddr)->sin_family=AF_INET; ((sockaddr_in *)udpAddr)->sin_addr.s_addr=addr->sin_addr.s_addr; ((sockaddr_in *)udpAddr)->sin_port=htons(port); // Set receive size size = 2000000; setsockopt(udpFd, SOL_SOCKET, SO_RCVBUF, (char*)&size, sizeof(size)); // Debug cout << "SidLink::linkOpen -> Opened UDP device " << host << ":" << port << ". Fd=" << udpFd << "\n"; // Set device variable udpHost = host; udpPort = port; maxRxSize = 0; } // Open link to KPIX, direct driver version // Pass device ID for direct drivers // Throws exception on device open failure void SidLink::linkOpen ( int device ) { // Status variable FT_STATUS ftStatus; stringstream error; FT_HANDLE tmpHandle; // Make sure no links are open if ( serFd >= 0 || usbDevice >= 0 || udpFd >= 0 ) throw string("SidLink::linkOpen -> KPIX Link Already Open"); if ( enDebug ) cout << "SidLink::linkOpen -> Attempting to open direct USB device " << device << "\n"; // Attempt to open the USB interface if((ftStatus = FT_Open(device, &tmpHandle)) != FT_OK) { error << "SidLink::linkOpen -> Error opening direct USB device " << device << ", status=" << ftStatus; usbDevice = -1; throw error.str(); } usbHandle = (void *)tmpHandle; cout << "SidLink::linkOpen -> Opened direct USB device " << device << "\n"; // Copy variables usbDevice = device; maxRxSize = 0; } // Open link to SID Devices, Simulation Version // Pass path to named pipes (read & write directions) for simulation // Throws exception on device open failure void SidLink::linkOpen ( string rdPipe, string wrPipe ) { stringstream error; // Make sure no links are open if ( serFd >= 0 || usbDevice >= 0 || udpFd >= 0 ) throw string("SidLink::linkOpen -> SID Link Already Open"); if ( enDebug ) cout << "SidLink::linkOpen -> Attempting to open simulation write link " << wrPipe << "\n"; // Attempt to open named pipe if ((serFd=open(wrPipe.c_str(), O_WRONLY )) < 0) { error << "SidLink::linkOpen -> Error opening simulation write link" << wrPipe; throw error.str(); } // Debug if ( enDebug ) cout << "SidLink::linkOpen -> Opened simulation write link " << wrPipe << ".\n"; // Set pipe variable serDevice = wrPipe; if ( enDebug ) cout << "SidLink::linkOpen -> Attempting to open simulation read link " << rdPipe << "\n"; // Attempt to open named pipe if ((serFdRd=open(rdPipe.c_str(), O_RDONLY)) < 0) { error << "SidLink::linkOpen -> Error opening simulation read link" << rdPipe; throw error.str(); } // Debug if ( enDebug ) cout << "SidLink::linkOpen -> Opened simulation read link " << rdPipe << ".\n"; // Disable timeout timeoutEn = false; maxRxSize = 0; } // Flush any pending data from the link. // Returns number of bytes flushed int SidLink::linkFlush ( ) { FT_STATUS ftStatus; int count = 0; unsigned long rcount = 0; int total = 0; int fdes; unsigned char buffer[1000]; stringstream error; unsigned int udpAddrLength; struct timeval timeout; fd_set fds; int ret; if ( enDebug ) cout << "SidLink::linkFlush -> Flushing Link.\n"; // Determine link for read, sim uses a seperate file descriptor if ( serFdRd > 0 ) fdes = serFdRd; else fdes = serFd; // Read until we get 0 data returned do { rcount = 0; usleep(100); // Serial device is open if ( fdes >= 0 ) { // Flush any residual data count = read(fdes,buffer,1000); if ( count > 0 ) { rcount = count; total += count; } } // UDP device is open if ( udpFd >= 0 ) { do { timeout.tv_sec=0; timeout.tv_usec=1; FD_ZERO(&fds); FD_SET(udpFd,&fds); // Is data waiting? ret = select(udpFd+1,&fds,NULL,NULL,&timeout); if ( ret < 0 || FD_ISSET(udpFd,&fds) == 0 ) ret = 0; else { udpAddrLength = sizeof(struct sockaddr_in); ret = recvfrom(udpFd,buffer,1000,0,(struct sockaddr *)udpAddr,&udpAddrLength); } if ( ret > 0 ) { rcount = ret; total += ret; } } while ( ret > 0 ); qinit(); } // USB device is open if ( usbDevice >= 0 ) { if ((ftStatus = FT_Purge((FT_HANDLE)usbHandle,FT_PURGE_RX | FT_PURGE_TX)) != FT_OK ) { error << "SidLink::linkFlush -> Error purging device"; error << usbDevice << ", status=" << ftStatus; throw error.str(); } } } while (rcount > 0); maxRxSize = 0; // Debug cout << "SidLink::linkFlush -> Flushed " << dec << total << " bytes\n"; return(total); } // Reset the device void SidLink::linkReset ( ) { FT_STATUS ftStatus; stringstream error; // USB device is open if ( usbDevice >= 0 ) { if ((ftStatus = FT_ResetDevice((FT_HANDLE)usbHandle)) != FT_OK ) { error << "SidLink::linkFlush -> Error resetting device"; error << usbDevice << ", status=" << ftStatus; throw error.str(); } } } // Method to close the link // Throws exception on device close failure void SidLink::linkClose () { FT_STATUS ftStatus; stringstream error; // Check if no links are open if ( serFd < 0 && usbDevice < 0 && udpFd < 0 ) return; if ( enDebug ) cout << "SidLink::linkClose -> Attempting to close USB device\n"; // Serial device is open if ( serFd >= 0 ) { // Attempt to unlock device if ( dev_unlock(serDevice.c_str(),0) != 0 ) { error << "SidLink::linkOpen -> Error unlocking VCP USB device " << serDevice << "."; throw error.str(); } // Attempt to close if ( close(serFd) != 0 ) { error << "sidLink::linkClose -> Could not close VCP USB device " << serDevice; serFd = -1; serDevice = ""; throw error.str(); } serFd = -1; serDevice = ""; } // UDP Device is open if ( udpFd >= 0 ) { if ( close(udpFd) != 0 ) { udpFd = -1; throw("sidLink::linkClose -> Could not close UDP device "); } udpFd = -1; } // Special simulation read fdes is open if ( serFdRd >= 0 ) { // Attempt to close if ( close(serFdRd) != 0 ) { error << "sidLink::linkClose -> Could not close simulation RD device "; throw error.str(); serFd = -1; serDevice = ""; } serFdRd = -1; } // USB device is open if ( usbDevice >= 0 ) { // Attempt to close the USB interface if((ftStatus = FT_Close((FT_HANDLE)usbHandle)) != FT_OK) { usbDevice = -1; usbHandle = NULL; error << "SidLink::linkClose -> Could not close direct USB device " << usbDevice << ", status=" << ftStatus; throw error.str(); } usbDevice = -1; usbHandle = NULL; } } // Method to write a word array to a KPIX device, raw interface // Pass word (16-bit) array and length // Return number of words written int SidLink::linkRawWrite (unsigned short *data, short int size, unsigned char type, bool sof){ unsigned char *byteData; unsigned int i,y; FT_STATUS ftStatus; stringstream error; int ret; unsigned long wtotal; unsigned long newSize; // Check if no links are open if ( serFd < 0 && usbDevice < 0 && udpFd < 0 ) throw string("SidLink::linkRawWrite -> KPIX Link Not Open"); // Calc size newSize = size * 3; // First create byte array to contain converted data byteData = (unsigned char *) malloc(newSize); if (byteData == NULL ) throw(string("SidLink::linkRawWrite -> Malloc Error")); // Debug if enabled if ( enDebug ) { cout << "SidLink::linkRawWrite -> Writing data to USB:"; cout << " Sof=" << sof << ", Type=" << (int)type << ":"; for (i=0; i< (unsigned short int) size; i++) cout << " 0x" << setw(4) << setfill('0') << hex << (int)data[i]; cout << "\n"; } // UDP Data // UDP device is open if ( udpFd >= 0 ) { byteData[0] = (sof << 7) & 0x80; byteData[0] += (type << 4) & 0x30; byteData[0] += (size >> 8) & 0xF; byteData[1] = (size+1) & 0xFF; if ( enDebug ) { cout << "Data: 0x" << hex << setw(2) << setfill('0') << (uint)byteData[0]; cout << " 0x" << hex << setw(2) << setfill('0') << (uint)byteData[1]; } y = 2; for (i=0; i < (unsigned short int)size; i++) { byteData[y] = (data[i] >> 8) & 0xFF; if ( enDebug ) cout << " 0x" << hex << setw(2) << setfill('0') << (uint)byteData[y]; y++; byteData[y] = data[i] & 0xFF; if ( enDebug ) cout << " 0x" << hex << setw(2) << setfill('0') << (uint)byteData[y]; y++; } if ( enDebug ) cout << endl; ret = sendto(udpFd,byteData,y,0,(struct sockaddr *)(udpAddr),sizeof(struct sockaddr_in)); if ( ret > 0 ) wtotal = ret; } else { // Convert each word into a three byte string y=0; for (i=0; i < (unsigned short int)size; i++) { // Byte 0 byteData[y] = 0x80; if ( sof && i == 0 ) byteData[y] |= 0x40; byteData[y] |= ((type << 4) & 0x30); byteData[y] |= (data[i] & 0x0F); y++; // Byte 1 byteData[y] = 0x00; byteData[y] |= ((data[i] >> 4 ) & 0x3F); y++; // Byte 2 byteData[y] = 0x40; byteData[y] |= ((data[i] >> 10 ) & 0x3F); y++; } // Debug if enabled if ( enDebug ) { cout << "SidLink::linkRawWrite -> Writing data to USB:"; for (i=0; i< newSize; i++) cout << " 0x" << setw(2) << setfill('0') << hex << (int)byteData[i]; cout << "\n"; } // Serial device is open if ( serFd >= 0 ) { ret = write(serFd, byteData, newSize); if ( ret > 0 ) wtotal = ret; } // USB device is open if ( usbDevice >= 0 ) { // Attempt to write to direct usb device if((ftStatus = FT_Write((FT_HANDLE)usbHandle, byteData, newSize, &wtotal)) != FT_OK) { error << "SidLink::linkRawWrite -> Error writing to direct USB device " << usbDevice << ", status=" << ftStatus; free(byteData); throw error.str(); } } // Check size //if ( wtotal != newSize ) throw string("SidLink::linkRawWrite -> Write Size Error"); } free(byteData); if ( enDebug ) cout << "SidLink::linkRawWrite -> Write Done!\n"; return(size); } // Method to read a word array from a KPIX device, raw interface // Pass word (16-bit) array and length // Return number of words read int SidLink::linkRawRead ( unsigned short *data, short int size, unsigned char type, bool sof, int *eof ){ // Check if no links are open if ( serFd < 0 && usbDevice < 0 && udpFd < 0 ) throw string("SidLink::linkRawRead -> KPIX Link Not Open"); // UDP device is open if ( udpFd >= 0 ) return(linkRawReadUdp(data, size, type, sof, eof)); else { *eof = -1; return(linkRawReadUsb(data, size, type, sof)); } } // Method to read a word array from a KPIX device using UDP interface // Pass word (16-bit) array and length // Return number of words read int SidLink::linkRawReadUdp ( unsigned short *data, short int size, unsigned char type, bool sof, int *eof ){ unsigned long rcount; unsigned long toCount; int ret; stringstream error; unsigned int udpAddrLength; struct timeval timeout; fd_set fds; unsigned char qbuffer[8192]; bool rSof; bool rEof; unsigned int rType; unsigned short value; unsigned int x; unsigned int lcount; unsigned int udpx; unsigned int udpcnt; // Debug if ( enDebug ) cout << "SidLink::linkRawReadUdp -> Reading!\n"; rcount = 0; toCount = 0; do { // First read any data waiting in UDP queue timeout.tv_sec=0; timeout.tv_usec=1; FD_ZERO(&fds); FD_SET(udpFd,&fds); // Is data waiting? if ( ! qready() ) { ret = select(udpFd+1,&fds,NULL,NULL,&timeout); if ( ret > 0 && FD_ISSET(udpFd,&fds) ) { udpAddrLength = sizeof(struct sockaddr_in); ret = recvfrom(udpFd,&qbuffer,8192,0,(struct sockaddr *)udpAddr,&udpAddrLength); if ( ret > 0 ) { udpx = 0; while ( udpx < (uint)ret ) { rSof = (qbuffer[udpx] >> 7) & 0x1; rEof = (qbuffer[udpx] >> 6) & 0x1; rType = (qbuffer[udpx] >> 4) & 0x3; udpcnt = (qbuffer[udpx] << 8) & 0xF00; udpx++; udpcnt += (qbuffer[udpx] ) & 0xFF; udpcnt -= 1; udpx++; if ( udpcnt > 4001 ) break; for ( x=0; x < udpcnt; x++ ) { value = (qbuffer[udpx] << 8) & 0xFF00; udpx++; value += (qbuffer[udpx] & 0xFF); udpx++; qpush(value,rType,(rSof&&x==0),(rEof && x == (udpcnt-1))); } if ( enDebug ) { cout << "SidLink::linkRawReadUdp -> Read " << dec << x << " words from UDP. "; cout << "Type=" << dec << rType << ", SOF=" << dec << rSof << ", EOF=" << dec << rEof; cout << ", Ret=" << dec << ret << endl; } } } } } // Next pass queue data to user lcount = 0; while ( rcount < (uint)size && qready() ) { qpop(&value,&rType,&rSof,&rEof); *eof = rEof; data[rcount] = value; if ( rType != type ) { cout << "Expected Word Type : " << hex << (int)type << ", Got : " << (int)rType << endl; throw(string("SidLink::linkRawReadUdp -> Word Type Mimsatch")); } if ( rcount == 0 && sof != rSof ) { throw(string("SidLink::linkRawReadUdp -> SOF Mimsatch")); } toCount = 0; lcount++; rcount++; } if ( enDebug && lcount > 0 ) cout << "SidLink::linkRawReadUdp -> Read " << dec << lcount << " words from buffer\n"; if ( timeoutEn && lcount == 0 ) { toCount++; if ( toCount >= Timeout ) { error << "SidLink::linkRawReadUdp -> Read Timeout. Read "; error << dec << rcount << " Bytes. Max Buffer=" << dec << maxRxSize; error << ", Flush=" << dec << linkFlush(); error << ", Size=" << dec << size; if ( enDebug ) cout << error.str() << endl; throw error.str(); } usleep(1000); } } while ( rcount < (uint)size ); // Debug if enabled if ( enDebug ) { cout << "SidLink::linkRawReadUdp -> Read data from UDP:"; cout << " Sof=" << sof << ", Eof=" << dec << *eof << ", Type=" << (int)type << ", Size=" << size << endl; cout << "Data:"; for ( x=0; x < rcount && x < 10; x++ ) cout << " 0x" << hex << setfill('0') << setw(4) << data[x]; cout << endl; } return(rcount); } // Method to read a word array from a KPIX device using USB interface // Pass word (16-bit) array and length // Return number of words read int SidLink::linkRawReadUsb ( unsigned short *data, short int size, unsigned char type, bool sof ){ unsigned char *byteData; unsigned long newSize; unsigned long rcount; unsigned long rxBytes; unsigned long txBytes; unsigned long eventWord; int ret; FT_STATUS ftStatus; stringstream error; unsigned int i; unsigned long rtotal; unsigned int toCount; int fdes; unsigned int wordCnt; // First create byte array to contain byte newSize = size * 3; byteData = (unsigned char *) malloc(newSize); if (byteData == NULL ) throw(string("SidLink::linkRawRead -> Malloc Error")); // Determine link for read, sim uses a seperate file descriptor if ( serFdRd > 0 ) fdes = serFdRd; else fdes = serFd; // Debug if ( enDebug ) cout << "SidLink::linkRawRead -> Reading!\n"; // Read until we get amount of data we want rtotal = 0; toCount = 0; while ( rtotal < newSize ) { // Serial device is open if ( fdes >= 0 ) { // Attempt to read from device ret = read(fdes, &(byteData[rtotal]), (newSize-rtotal)); // Read returns -1 if no data is waiting if ( ret != -1 ) rcount = ret; else rcount = 0; } // USB device is open rxBytes = 0; if ( usbDevice >= 0 ) { // How many bytes are ready if ((ftStatus = FT_GetStatus((FT_HANDLE)usbHandle,&rxBytes,&txBytes,&eventWord)) != FT_OK ) { error << "SidLink::linkRawRead -> Error getting status from direct USB device "; error << usbDevice << ", status=" << ftStatus; free(byteData); throw error.str(); } // Data is ready if ( rxBytes >= newSize ) { if ( rxBytes > maxRxSize ) maxRxSize = rxBytes; // Read from usb device if((ftStatus = FT_Read((FT_HANDLE)usbHandle, byteData, newSize, &rcount)) != FT_OK) { error << "SidLink::linkRawRead -> Error reading from direct USB device "; error << usbDevice << ", status=" << ftStatus; free(byteData); throw error.str(); } } else rcount = 0; } // Update total if ( rcount != 0 ) { rtotal += rcount; toCount = 0; } // Check for timeout else if ( timeoutEn ) { toCount++; if ( toCount >= Timeout ) { free(byteData); // Flush the link ret = linkFlush(); error << "SidLink::linkRawRead -> Read Timeout. Read "; error << dec << rtotal << " Bytes. Max Buffer=" << dec << maxRxSize; error << ", Flush=" << dec << ret; error << ", Size=" << dec << size; error << ", RxBytes=" << dec << rxBytes; throw error.str(); } usleep(1000); } // Wait longer for simulation, 10mS else usleep(10000); } // Debug if enabled if ( enDebug ) { cout << "SidLink::linkRawRead -> Read data from USB:"; for (i=0; i< rtotal; i++) cout << " 0x" << setw(2) << setfill('0') << hex << (int)byteData[i]; cout << "\n"; } // Process each byte of read data wordCnt = 0; for (i=0; i < rtotal; i+=3) { // Check aligment if ( (byteData[i] & 0x80) == 0 || (byteData[i+1] & 0xC0) != 0 || (byteData[i+2] & 0xC0) != 0x40 ) { free(byteData); linkFlush(); throw(string("SidLink::linkRawRead -> Alignment Error")); } // Check word type if ( ((byteData[i] >> 4) & 0x03) != type ) { free(byteData); linkFlush(); throw(string("SidLink::linkRawRead -> Word Type Mimsatch")); } // Check SOF if ( i == 0 && (sof != ((byteData[i] & 0x40) != 0)) ) { free(byteData); linkFlush(); throw(string("SidLink::linkRawRead -> SOF Mimsatch")); } // Extract Data data[wordCnt] = byteData[i] & 0x0F; data[wordCnt] |= (byteData[i+1] << 4) & 0x03F0; data[wordCnt] |= (byteData[i+2] << 10) & 0xFC00; wordCnt++; } // Debug if enabled if ( enDebug ) { cout << "SidLink::linkRawRead -> Read data from USB:"; cout << " Sof=" << sof << ", Type=" << (int)type << ", Size=" << size << ":"; for (i=0; i< (unsigned int)size; i++) cout << " 0x" << setw(4) << setfill('0') << hex << (int)data[i]; cout << "\n"; } free(byteData); return(wordCnt); } // Method to write a word array to a KPIX device // Pass word (16-bit) array and length // Return number of words written int SidLink::linkKpixWrite ( unsigned short int *data, short int size) { // Sim Mode, all bytes are echoed if ( serFdRd > 0 ) { int eof; linkRawWrite (data, size, 0, true); return(linkRawRead (data, size, 0, true, &eof)); } // Normal Mode else return(linkRawWrite (data, size, 0, true)); } // Method to read a word array from a KPIX device // Pass word (16-bit) array and length // Return number of words read int SidLink::linkKpixRead ( unsigned short int *data, short int size ) { int eof; return(linkRawRead (data, size, 0, true, &eof)); } // Method to read a word array from a KPIX device, sample data // Pass word (16-bit) array, length and first read flag // Return number of words read int SidLink::linkDataRead ( unsigned short int *data, short int size, bool first, int *last ) { return(linkRawRead (data, size, 1, first, last)); } // Method to write a word array to the FPGA device // Pass word (16-bit) array and length // Return number of words written int SidLink::linkFpgaWrite ( unsigned short int *data, short int size) { // Sim Mode, all bytes are echoed if ( serFdRd > 0 ) { int eof; linkRawWrite (data, size, 2, true); return(linkRawRead (data, size, 2, true, &eof)); } // Normal Mode else return(linkRawWrite (data, size, 2, true)); } // Method to read a word array from the FPGA device // Pass word (16-bit) array and length // Return number of words read int SidLink::linkFpgaRead ( unsigned short int *data, short int size ) { int eof; return(linkRawRead (data, size, 2, true, &eof)); } // Turn on or off debugging for the class void SidLink::linkDebug ( bool debug ) { enDebug = debug; }
30.332618
121
0.547612
[ "object" ]
74fd3d87784a02af76034c44c8e83436d78c8318
5,595
cpp
C++
CodeSignal/Company Challenges/SpaceX/cpuEmulator.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
CodeSignal/Company Challenges/SpaceX/cpuEmulator.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
CodeSignal/Company Challenges/SpaceX/cpuEmulator.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*SpaceX is testing flight software subroutines (i.e., programs that consist of sequences of instructions) for a custom rocket CPU. To ensure that the software runs correctly before it's loaded into the rocket, you need to create a CPU simulator. The CPU has 43 32-bit unsigned integer registers, which are named R00..R42. At the start of the program, all the registers contain 0. The CPU supports the following instructions: MOV Rxx,Ryy - copies the value from register Rxx to register Ryy; MOV d,Rxx - copies the numeric constant d (specified as a decimal) to register Rxx; ADD Rxx,Ryy - calculates (Rxx + Ryy) MOD 232 and stores the result in Rxx; DEC Rxx - decrements Rxx by one. Decrementing 0 causes an overflow and results in 232-1; INC Rxx - increments Rxx by one. Incrementing 232-1 causes an overflow and results in 0; INV Rxx - performs a bitwise inversion of register Rxx; JMP d - unconditionally jumps to instruction number d (1-based). d is guaranteed to be a valid instruction number; JZ d - jumps to instruction d (1-based) only if R00 contains 0; NOP - does nothing. After the last instruction has been executed, the contents of R42 are considered to be the result of the subroutine. Write a software emulator for this CPU that executes the subroutines and returns the resulting value from R42. All the commands in the subroutine are guaranteed to be syntactically correct and have valid register numbers, numeric constants, and jump addresses. The maximum program length is 1024 instructions. The maximum total number of instructions that will be executed until the value is returned is 5 · 104. (Keep in mind that the same instruction will be counted as many times as it will be executed.) Example For subroutine = [ "MOV 5,R00", "MOV 10,R01", "JZ 7", "ADD R02,R01", "DEC R00", "JMP 3", "MOV R02,R42" ] the output should be cpuEmulator(subroutine) = "50". Here is the information about the CPU state after certain steps: Step Last executed command Non-zero registers Comment 1 1. MOV 5,R00 R00 = 5 Put 5 into R00 2 2. MOV 10,R01 R00 = 5, R01 = 10 Put 10 into R01 3 3. JZ 7 R00 = 5, R01 = 10 Move to the next instruction because R00 ≠ 0 4 4. ADD R02,R01 R00 = 5, R01 = 10, R02 = 10 R02 += R01 5 5. DEC R00 R00 = 4, R01 = 10, R02 = 10 R00 -= 1 6 6. JMP 3 R00 = 4, R01 = 10, R02 = 10 Jump to instruction number 3, i.e. JZ 7 7 3. JZ 7 R00 = 4, R01 = 10, RO2 = 10 Move to the next instruction because R00 ≠ 0 Information about 11 steps is skipped 19 3. JZ 7 R00 = 1, R01 = 10, RO2 = 40 Move to the next instruction because R00 ≠ 0 20 4. ADD R02,R01 R00 = 1, R01 = 10, R02 = 50 R02 += R01 21 5. DEC R00 R00 = 0, R01 = 10, R02 = 50 R00 -= 1 22 6. JMP 3 R00 = 0, R01 = 10, R02 = 50 Jump to instruction number 3, i.e. JZ 7 23 3. JZ 7 R00 = 0, R01 = 10, R02 = 50 Jump to instruction number 7 because R00 = 0 24 7. MOV R02,R42 R00 = 0, R01 = 10, R02 = 50, R42 = 50 R42 += R02 The subroutine is exited Input/Output [execution time limit] 0.5 seconds (cpp) [input] array.string subroutine Guaranteed constraints: 1 ≤ subroutine.length ≤ 1024. [output] string Return the resulting 32-bit unsigned integer, converted into a string. */ auto split_string(const string& input, const char delimiter) { stringstream ss {input.data()}; vector<string> result; // result.reserve(count(begin(input), end(input), delimiter)); for (string buffer; getline(ss, buffer, delimiter);) {result.push_back(move(buffer));} return result; } string cpuEmulator(vector<string> subroutine) { vector<unsigned> REG (43, 0); for (int i=0; i<subroutine.size(); ++i) { auto inst = subroutine[i]; auto s = split_string(inst, ' '); if (s[0] == "NOP") {continue;} else if (s[0] == "JMP") { i = stol(s[1]) - 2; } else if (s[0] == "JZ") { if (REG[0] == 0) { i = stol(s[1]) - 2; } } else if (s[0] == "INV") { int num = stoul(string(begin(s[1])+1, end(s[1]))); REG[num] = ~ REG[num]; } else if (s[0] == "INC") { int num = stoul(string(begin(s[1])+1, end(s[1]))); if (REG[num] == 4294967295) { REG[num] = 0; } else { ++REG[num]; } } else if (s[0] == "DEC") { int num = stoul(string(begin(s[1])+1, end(s[1]))); if (REG[num] == 0) { REG[num] = 4294967295; } else { --REG[num]; } } else if (s[0] == "ADD") { auto c = split_string(s[1], ','); auto n1 = stoul(string(begin(c[0])+1, end(c[0]))); auto n2 = stoul(string(begin(c[1])+1, end(c[1]))); REG[n1] = ((REG[n1] % 4294967296) + (REG[n2] % 4294967296)) % 4294967296; } else if (s[0] == "MOV") { auto c = split_string(s[1], ','); if (c[0][0] == 'R') { auto n1 = stoul(string(begin(c[0])+1, end(c[0]))); auto n2 = stoul(string(begin(c[1])+1, end(c[1]))); REG[n2] = REG[n1]; } else { auto n1 = stoul(c[0]); auto n2 = stoul(string(begin(c[1])+1, end(c[1]))); REG[n2] = n1; } } } return to_string(REG[42]); }
33.704819
396
0.575514
[ "vector" ]
2d01bac511df0197991659e1a068e45ca97e0378
4,760
hpp
C++
include/Core/Castor3D/Material/Material.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
245
2015-10-29T14:31:45.000Z
2022-03-31T13:04:45.000Z
include/Core/Castor3D/Material/Material.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
64
2016-03-11T19:45:05.000Z
2022-03-31T23:58:33.000Z
include/Core/Castor3D/Material/Material.hpp
Mu-L/Castor3D
7b9c6e7be6f7373ad60c0811d136c0004e50e76b
[ "MIT" ]
11
2018-05-24T09:07:43.000Z
2022-03-21T21:05:20.000Z
/* See LICENSE file in root folder */ #ifndef ___C3D_Material_H___ #define ___C3D_Material_H___ #include "MaterialModule.hpp" #include "Castor3D/Material/Pass/PassModule.hpp" #include "Castor3D/Render/RenderModule.hpp" #include <CastorUtils/Data/TextWriter.hpp> namespace castor3d { class Material : public castor::Named , public castor::OwnedBy< Engine > { public: /** *\~english *\brief Constructor. *\param[in] name The material name. *\param[in] engine The core engine. *\param[in] type The material type. *\~french *\brief Constructeur. *\param[in] name Le nom du matériau. *\param[in] engine Le moteur. *\param[in] type Le type de matériau. */ C3D_API Material( castor::String const & name , Engine & engine , PassTypeID type ); /** *\~english *\brief Destructor. *\~french *\brief Destructeur. */ C3D_API virtual ~Material(); C3D_API void initialise(); C3D_API void cleanup(); /** *\~english *\brief Creates a pass. *\return The created pass. *\~french *\brief Crée une passe. *\return La passe créée. */ C3D_API PassSPtr createPass(); /** *\~english *\brief Removes an external pass to rhe material. *\param[in] pass The pass. *\~french *\brief Supprime une passe externe. *\param[in] pass La passe. */ C3D_API void removePass( PassSPtr pass ); /** *\~english *\brief Retrieves a pass and returns it. *\param[in] index The index of the wanted pass. *\return The retrieved pass or nullptr if not found. *\~french *\brief Récupère une passe. *\param[in] index L'index de la passe voulue. *\return La passe récupére ou nullptr si non trouvés. */ C3D_API PassSPtr getPass( uint32_t index )const; /** *\~english *\brief Destroys the pass at the given index. *\param[in] index The pass index. *\~french *\brief Destroys the pass at the given index. *\param[in] index L'index de la passe. */ C3D_API void destroyPass( uint32_t index ); /** *\~english *\return \p true if all passes needs alpha blending. *\~french *\return \p true si toutes les passes ont besoin d'alpha blending. */ C3D_API bool hasAlphaBlending()const; /** *\~english *\return \p true if at least one pass needs a reflection map. *\~french *\return \p true si au moins une passe a besoin d'une reflection map. */ C3D_API bool hasEnvironmentMapping()const; /** *\~english *\return Tells if the material has subsurface scattering. *\~french *\return Dit si le matériau a du subsurface scattering. */ C3D_API bool hasSubsurfaceScattering()const; /** *\~english *\return Tells if the material is textured. *\param[in] mask A texture mask to filter out textures. *\~french *\return Dit si le matériau a des textures. *\param[in] mask Un masque de textures pour les filtrer. */ C3D_API bool isTextured( TextureFlags mask = TextureFlag::eAll )const; /** *\~english *\return The passes count. *\~french *\return Le nombre de passes. */ uint32_t getPassCount()const { return uint32_t( m_passes.size() ); } /** *\~english *\return The constant iterator on the beginning of the passes array. *\~french *\return L'itérateur constant sur le début du tableau de passes. */ PassPtrArrayConstIt begin()const { return m_passes.begin(); } /** *\~english *\return The iterator on the beginning of the passes array. *\~french *\return L'itérateur sur le début du tableau de passes. */ PassPtrArrayIt begin() { return m_passes.begin(); } /** *\~english *\return The constant iterator on the end of the passes array. *\~french *\return L'itérateur constant sur la fin du tableau de passes. */ PassPtrArrayConstIt end()const { return m_passes.end(); } /** *\~english *\return The iterator on the end of the passes array. *\~french *\return L'itérateur sur la fin du tableau de passes. */ PassPtrArrayIt end() { return m_passes.end(); } /** *\~english *\return The material type. *\~french *\return Le type de matériau. */ PassTypeID getType()const { return m_type; } private: void onPassChanged( Pass const & pass ); public: //!\~english The signal raised when the material has changed. //!\~french Le signal levé lorsque le matériau a changé. OnMaterialChanged onChanged; //!\~english The default material name. //!\~french Le nom du matériau par défaut. static const castor::String DefaultMaterialName; private: PassPtrArray m_passes; PassTypeID m_type{ 0u }; std::map< PassSPtr, OnPassChangedConnection > m_passListeners; }; } #endif
24.791667
72
0.659244
[ "render" ]
2d01dd2d349991240a196ec88a421f6bb1768fa3
46,099
hpp
C++
include/linAlg.hpp
motchy869/motchyMathLib
356676beef321902440ddf53b262dee57d335f44
[ "MIT" ]
null
null
null
include/linAlg.hpp
motchy869/motchyMathLib
356676beef321902440ddf53b262dee57d335f44
[ "MIT" ]
null
null
null
include/linAlg.hpp
motchy869/motchyMathLib
356676beef321902440ddf53b262dee57d335f44
[ "MIT" ]
null
null
null
/** * @author motchy (motchy869[at]gmail.com) * @brief Linear Algebra library */ #pragma once #include <cassert> #include <cmath> #include <complex> #include <cstddef> #include <cstring> #include <iostream> #include <numeric> #include "common.hpp" #include "analysis.hpp" namespace MathLib { namespace LinAlg { namespace Debug { /* For only debug use. Not intended to be used in field environment. */ /** * @brief Prints real matrix "A" in standard output. * * @tparam T the number type of the elements of "A" * @param[in] m the number of the rows in "A" * @param[in] n the number of the columns in "A" * @param[in] A the matrix "A" * @param[in] format format string which is applied to each element in "A" */ template <typename T> void printRealMat(size_t m, size_t n, const T *A, const char *format) { assert(m*n >= 1); const T *ptr_A = A; for (size_t i=0; i<m; ++i) { for (size_t j=0; j<n; ++j) { printf(format, *ptr_A); if (j < n-1) { printf(", "); } ++ptr_A; } puts(""); } } /** * @brief Prints real vector in standard output. * * @tparam T the number type of the elements of the input vector * @param[in] m the length of the input vector * @param[in] vec the input vector * @param[in] format format string which is applied to each element in the input vector */ template <typename T> void printRealVec(size_t m, const T *vec, const char *format) { assert(m >= 1); printRealMat(1, m, vec, format); } /** * @brief Prints complex matrix "A" in standard output. * * @tparam T the number type of the real and imaginary part of the elements of "A" * @param[in] m the number of the rows in "A" * @param[in] n the number of the columns in "A" * @param[in] A the matrix "A" * @param[in] format format string which is applied to each element in "A" */ template <typename T> void printComplexMat(size_t m, size_t n, const std::complex<T> *A, const char *format) { assert(m*n >= 1); const std::complex<T> *ptr_A = A; for (size_t i=0; i<m; ++i) { for (size_t j=0; j<n; ++j) { printf(format, (*ptr_A).real(), (*ptr_A).imag()); if (j < n-1) { printf(", "); } ++ptr_A; } puts(""); } } /** * @brief Prints complex vector in standard output. * * @tparam T the number type of the real and imaginary part of the elements of the input vector * @param[in] m the length of the input vector * @param[in] vec the input vector * @param[in] format format string which is applied to each element in the input vector */ template <typename T> void printComplexVec(size_t m, const std::complex<T> *vec, const char *format) { assert(m >= 1); printComplexMat(1, m, vec, format); } } /** * @brief Checks whether given two matrices "A" and "B" are equal or not. * @details "A" and "B" are considered to be equal if and only if the absolute value of all the element of "A-B" is strictly less than a given number, epsilon. * * @tparam T1 the number type of the elements of A and B * @tparam T2 the number type of the elements of epsilon * @param[in] m the number of the rows in the input matrices * @param[in] n the number of the columns in the input matrices * @param[in] A the matrix A * @param[in] B the matrix B * @param[in] epsilon the threshold epsilon * @retval true A and B are equal. * @retval false A and B are not equal. */ template <typename T1, typename T2> #if MATH_LIB_INLINE_AGGRESSIVELY inline static bool __attribute__((always_inline)) #else bool #endif isEqualMat(const size_t m, const size_t n, const T1 *const A, const T1 *const B, const T2 epsilon) { const size_t L = m*n; for (size_t i=0; i<L; ++i) { if (std::abs(A[i] - B[i]) > epsilon) {return false;} } return true; } /** * @brief Checks whether given two vectors "a" and "b" are equal or not. * @details "a" and "b" are considered to be equal if and only if the absolute value of all the element of "a-b" is strictly less than a given number, epsilon. * * @tparam T1 the number type of the elements of "a" and "b" * @tparam T2 the number type of the elements of epsilon * @param[in] m the length of the input vectors * @param[in] a the vector "a" * @param[in] b the vector "b" * @param[in] epsilon the threshold epsilon * @retval true "a" and "b" are equal. * @retval false "a" and "b" are not equal. */ template <typename T1, typename T2> inline static bool __attribute__((always_inline)) isEqualVec(const size_t m, const T1 *const a, const T1 *const b, const T2 epsilon) { return isEqualMat(1, m, a, b, epsilon); } /** * @brief Construct complex matrix "A" from real part "A_real" and imaginary part "A_imag". * * @tparam T the number type of "A_real" and "A_imag" * @param[in] m the number of the rows in the input matrices * @param[in] n the number of the columns in the input matrices * @param[in] A_real the real part of "A" * @param[in] A_imag the imaginary part of "A" * @param[out] A output buffer for "A" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif complexMat(const size_t m, const size_t n, const T *const A_real, const T *const A_imag, std::complex<T> *const A) { const size_t L = m*n; for (size_t i=0; i<L; ++i) { A[i].real(A_real[i]); A[i].imag(A_imag[i]); } } /** * @brief Construct complex vector "x" from real part "x_real" and imaginary part "x_imag". * * @tparam T the number type of "x_real" and "x_imag" * @param[in] m the length of the vector "x" * @param[in] x_real the real part of "x" * @param[in] x_imag the imaginary part of "x" * @param[out] x output buffer for "x" */ template <typename T> inline static void __attribute__((always_inline)) complexVec(const size_t m, const T *const x_real, const T *const x_imag, std::complex<T> *const x) { complexMat(m, 1, x_real, x_imag, x); } /** * @brief Set a given vector "d" to the diagonal entries of a given square matrix "A". * The length of "d" must be equal to the number of the rows of "A". * * @tparam T the number type of the elements of "d, A". * @param[in] m the number of the rows in the matrices "A" * @param[in] d "d" * @param[out] A "A" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif setDiag(const size_t m, const T *const d, T *const A) { for (size_t r=0; r<m; ++r) {A[r*m+r] = d[r];} } /** * @brief Fill lower triangle part of a given matrix "A" with a given value "x". * The diagonal boundary is controlled by a parameter "d", defaults to 0. * "d=0" corresponds to the main diagonal line. * "d=k (k>0)" corresponds "k"-th upper subdiagonal line, and "d=-k (k>0)" corresponds to "k"-th lower subdiagonal line. */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif fillLowTri(const int m, T *const A, const T x, const int d=0) { for (int r=0; r<m; ++r) { const int c_end_temp = r+d; const int c_end = (c_end_temp < m ? c_end_temp : m-1); T *const A_row_ptr = &A[r*m]; for (int c=0; c<=c_end; ++c) {A_row_ptr[c] = x;} } } /** * @brief Add a given vector "d" to the diagonal entries of a given square matrix "A". * * @tparam T the number type of the elements of "d, A". * @param[in] m the number of the rows in the matrices "A" * @param[in] d "d" * @param[out] A "A" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif addDiag(const size_t m, const T *const d, T *const A) { for (size_t r=0; r<m; ++r) {A[r*m+r] += d[r];} } /** * @brief Drop contiguous rows and columns from a given "m"-by-"n" matrix "A" and store the result to "B". * The "r1, r1+1, ..., r2"-th rows and "c1, c1+1, ..., c2"-th columns are dropped, where "0<=r1<=r2<=m-1, 0<=c1<=c2<=n-1". * Parameter check for "r1, r2, c1, c2" is performed ONLY under bug hunting mode. * * @tparam T the number type of the elements of "A". * @param[in] m the number of the rows in the matrices "A" * @param[in] n the number of the columns in the matrices "A" * @param[in] r1 "r1" * @param[in] r2 "r2" * @param[in] c1 "c1" * @param[in] c2 "c2" * @param[in] A "A" * @param[out] B the output buffer, "B" */ template <typename T> void dropSubMat(const size_t m, const size_t n, const size_t r1, const size_t r2, const size_t c1, const size_t c2, const T *const A, T *const B) { #if MATH_LIB_ENABLE_CANARY_MODE if (!(0 <= r1 && r1 <= r2 && r2 < m && 0 <= c1 && c1 <= c2 && c2 < n)) { std::cerr << "BUG, FILE: " << __FILE__ << ", LINE: " << __LINE__ << std::endl; exit(EXIT_FAILURE); } #endif const T *A_ptr = A; T *B_ptr = B; const size_t rowGap = r2-r1+1, colGap = c2-c1+1; for (size_t r=0; r<r1; ++r) { for (size_t c=0; c<c1; ++c) {*B_ptr++ = *A_ptr++;} // upper left part A_ptr += colGap; for (size_t c=c2+1; c<n; ++c) {*B_ptr++ = *A_ptr++;} // upper right part } A_ptr += rowGap*n; for (size_t r=r2+1; r<m; ++r) { for (size_t c=0; c<c1; ++c) {*B_ptr++ = *A_ptr++;} // lower left part A_ptr += colGap; for (size_t c=c2+1; c<n; ++c) {*B_ptr++ = *A_ptr++;} // lower right part } } /** * @brief Calculates transpose of a matrix "A" as "B". * * @tparam T the number type of the elements of input matrix * @param[in] m the number of the rows in the input matrix "A" * @param[in] n the number of the columns in the input matrix "A" * @param[in] A the input matrix * @param[out] B the output matrix */ template <typename T> void transposeMat(size_t m, size_t n, const T *A, T *B) { for (size_t r=0; r<m; ++r) { const T *ptr_A = &A[r*n]; T *ptr_B = B + r; for (size_t c=0; c<n; ++c) { ptr_B[c*m] = ptr_A[c]; } } } /** * @brief Calculate the conjugate of a matrix "A", and store the result to "A". * * @tparam T the number type of real and imaginary part of the elements of the matrix "A" * @param[in] m the number of the rows in the matrix "A" * @param[in] n the number of the columns in the matrix "A" * @param[inout] A the matrix "A" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif conjugateMat(const size_t m, const size_t n, std::complex<T> *A) { const size_t L = m*n; for (size_t i=0; i<L; ++i) {A[i] = std::conj(A[i]);} } /** * @brief Calculate the conjugate of a matrix "A" as "B". * * @tparam T the number type of real and imaginary part of the elements of the matrices "A" and "B"'. * @param[in] m the number of the rows in the matrices "A" and "B" * @param[in] n the number of the columns in the matrices "A" and "B" * @param[in] A the matrix "A" * @param[out] B the matrix "B" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif conjugateMat(const size_t m, const size_t n, const std::complex<T> *const A, std::complex<T> *const B) { const size_t L = m*n; for (size_t i=0; i<L; ++i) {B[i] = std::conj(A[i]);} } /** * @brief Calculate the conjugate of a vector "x", and store the result to "x". * * @tparam T the number type of real and imaginary part of the elements of the vector "x" * @param[in] m the length of the vector "x" * @param[inout] x the vector "x" */ template <typename T> inline static void __attribute__((always_inline)) conjugateVec(const size_t m, std::complex<T> *x) { conjugateMat(m, 1, x); } /** * @brief Calculate the conjugate of a vector "x" as "y". * * @tparam T the number type of real and imaginary part of the elements of the vectors "x" and "y". * @param[in] m the length of the vector "x" * @param[in] x the vector "x" * @param[out] y the vector "y" */ template <typename T> inline static void __attribute__((always_inline)) conjugateVec(const size_t m, const std::complex<T> *const x, std::complex<T> *const y) { conjugateMat(m, 1, x, y); } /** * @brief Calculate the sum of given two matrices "A" and "B". The result is stored in "A". * * @tparam T the number type of the elements of the matrices "A" and "B" * @param[in] m the number of the rows in the matrices "A" and "B" * @param[in] n the number of the columns in the matrices "A" and "B" * @param[inout] A the matrix "A" * @param[in] B the matrix "B" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif addMat(const size_t m, const size_t n, T *const A, const T *const B) { const size_t L = m*n; for (size_t i=0; i<L; ++i) {A[i] += B[i];} } /** * @brief Calculate the sum of given two vector "x" and "y". The result is stored in "x". * * @tparam T the number type of the elements of the vectors "x" and "y" * @param[in] m the length of the vector "x" and "y" * @param[inout] x the vector "x" * @param[in] y the vector "y" */ template <typename T> inline static void __attribute__((always_inline)) addVec(const size_t m, T *const x, const T *const y) { addMat(m, 1, x, y); } /** * @brief Calculate the sum of given two square matrices "A" and "B". The result is stored in "A". * * @tparam T the number type of the elements of the matrices "A" and "B" * @param[in] m the number of the rows in the matrices "A" and "B" * @param[inout] A the matrix "A" * @param[in] B the matrix "B" * @param[in] LUA An option for calculation, defaults to 'A'. This option is useful when the input matrices are Hermitian and only diagonal and lower/upper parts are important. * - 'L' only diagonal and lower elements are updated * - 'U' only diagonal and upper elements are updated * - 'A' all elements are updated * - other do nothing */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) // Internal conditional branch will be optimized out when `LUA` is compile-time constant. #else void #endif addSqMat(const size_t m, T *const A, const T *const B, const char LUA='A') { if (LUA == 'A') { const size_t L = m*m; for (size_t i=0; i<L; ++i) {A[i] += B[i];} } else if (LUA == 'L') { for (size_t r=0; r<m; ++r) { size_t index = r*m; for (size_t c=0; c<=r; ++c, ++index) {A[index] += B[index];} } } else if (LUA == 'U') { for (size_t r=0; r<m; ++r) { size_t index = r*m+r; for (size_t c=r; c<m; ++c, ++index) {A[index] += B[index];} } } } /** * @brief Overwrite a given matrix "A" by its scaled version "cA" where "c" is a scalar. * * @tparam Tc the number type of "c" * @tparam TA the number type of the entries of "A" * @param[in] m the number of the rows in the input matrix "A" * @param[in] n the number of the columns in the input matrix "A" * @param[in] c the scalar "c" * @param[in] A the matrix "A" */ template <typename Tc, typename TA> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif scaleMat(const size_t m, const size_t n, const Tc c, TA *const A) { const size_t L = m*n; for (size_t i=0; i<L; ++i) {A[i] = Analysis::prod(c, A[i]);} } /** * @brief Calculates a scaled matrix "cA" as "B" where "A" is a matrix and "c" is a scalar. * * @tparam T the number type of "c" and the elements of "A" * @param[in] m the number of the rows in the input matrix "A" * @param[in] n the number of the columns in the input matrix "A" * @param[in] c the scalar "c" * @param[in] A the matrix "A" * @param[out] B the matrix "B" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) #else void #endif scaleMat(const size_t m, const size_t n, const T c, const T *const A, T *const B) { const size_t L = m*n; for (size_t i=0; i<L; ++i) {B[i] = Analysis::prod(c, A[i]);} } /** * @brief Overwrite a given square matrix "A" by its scaled version "cA" where "c" is a scalar. * * @tparam Tc the number type of "c" * @tparam TA the number type of the entries of "A" * @param[in] m the number of the rows in the input matrix "A" * @param[in] c the scalar "c" * @param[in] A the matrix "A" * @param[in] LUA An option for calculation, defaults to 'A'. This option is useful when the input matrices are Hermitian and only diagonal and lower/upper parts are important. * - 'L' only diagonal and lower elements are updated * - 'U' only diagonal and upper elements are updated * - 'A' all elements are updated * - other do nothing */ template <typename Tc, typename TA> #if MATH_LIB_INLINE_AGGRESSIVELY inline static void __attribute__((always_inline)) // Internal conditional branch will be optimized out when `LUA` is compile-time constant. #else void #endif scaleSqMat(const size_t m, const Tc c, TA *const A, const char LUA='A') { if (LUA == 'A') { const size_t L = m*m; for (size_t i=0; i<L; ++i) {A[i] = Analysis::prod(c, A[i]);} } else if (LUA == 'L') { for (size_t row=0; row<m; ++row) { size_t index = row*m; for (size_t col=0; col<=row; ++col, ++index) {A[index] = Analysis::prod(c, A[index]);} } } else if (LUA == 'U') { for (size_t row=0; row<m; ++row) { size_t index = row*m+row; for (size_t col=row; col<m; ++col, ++index) {A[index] = Analysis::prod(c, A[index]);} } } } /** * @brief Multiply each row of a given "m x n" matrix "A", and store result to "B" * Multiply c[i] to the i-th row of "A" where "c" is a vector with length "m". * * @tparam Tc the number type of the elements of "c" * @tparam TA the number type of the elements of "A" * @tparam TB the number type of the elements of "B" * @param[in] m the number of the rows in the matrix "A" * @param[in] n the number of the columns in the matrix "A" * @param[in] c the vector "m" * @param[in] A the matrix "A" * @param[out] B the output matrix "B" */ template <typename Tc, typename TA, typename TB> void scaleMatEachRow(const size_t m, const size_t n, const Tc *const c, const TA *const A, TB *const B) { for (size_t i=0; i<m; ++i) { const TA *const ptr_A = &A[i*n]; TB *const ptr_B = &B[i*n]; const Tc ci = c[i]; for (size_t j=0; j<n; ++j) { ptr_B[j] = Analysis::prod(ci, ptr_A[j]); } } } /** * @brief Calculates a scaled vector "ca" as "b" where "a" is a vector and "c" is a scalar. * * @tparam T the number type of "c" and the elements of "a" * @param[in] m the length of the vector "a" * @param[in] c the scalar "c" * @param[in] a the vector "a" * @param[out] b the vector "b" */ template <typename T> inline static void __attribute__((always_inline)) scaleVec(const size_t m, const T c, const T *const a, T *const b) { scaleMat(1, m, c, a, b); } /** * @brief Calculate a self outer product of a given real vector "x". * * @tparam T the number type of the entries of "x" * @param[in] M the length of "x" * @param[in] x "x" * @param[out] X the output buffer * @param[in] LUA An option for calculation, defaults to 'A'. Due to the symmetry of "X", there is 3 way to calculate "X": * - 'L' only diagonal and lower elements are calculated * - 'U' only diagonal and upper elements are calculated * - 'A' all elements are calculated * - other do nothing */ template <typename T> void vecSelfOuterProd(const int M, const T *const __restrict__ x, T *const __restrict__ X, const char LUA='A') { static_assert(std::is_floating_point<T>::value, "T must be floating point number type."); #define MEM_OFFSET(row,col) ((row)*M+col) for (int m=0; m<M; ++m) {X[m*(M+1)] = Analysis::sqAbs(x[m]);} // Calculate diagonal part. /* Calculate lower part. */ if (LUA == 'L' || LUA == 'A') { for (int r=1; r<M; ++r) { T *const X_ptr = &X[MEM_OFFSET(r,0)]; for (int c=0; c<r; ++c) { X_ptr[c] = x[r]*x[c]; } } } /* Calculate upper part. */ if (LUA == 'U') { for (int r=0; r<M-1; ++r) { T *const X_ptr = &X[MEM_OFFSET(r,0)]; for (int c=r+1; c<M; ++c) { X_ptr[c] = x[r]*x[c]; } } } else if (LUA == 'A') { // The lower part is already calculated. for (int r=0; r<M-1; ++r) { T *const X_ptr = &X[MEM_OFFSET(r,0)]; const T *const X_T_ptr = &X[MEM_OFFSET(0,r)]; for (int c=r+1; c<M; ++c) { X_ptr[c] = X_T_ptr[c*M]; } } } #undef MEM_OFFSET } /** * @brief Calculate a self outer product of a given complex vector "x". * * @tparam T the number type of the entries of "x" * @param[in] M the length of "x" * @param[in] x "x" * @param[out] X the output buffer * @param[inout] workspace a buffer to temporarily store conj(x). * @param[in] LUA An option for calculation, defaults to 'A'. Due to the Hermitian symmetry of "X", there is 3 way to calculate "X": * - 'L' only diagonal and lower elements are calculated * - 'U' only diagonal and upper elements are calculated * - 'A' all elements are calculated * - other do nothing */ template <typename T> void vecSelfOuterProd(const int M, const std::complex<T> *const __restrict__ x, std::complex<T> *const __restrict__ X, std::complex<T> *const workspace, const char LUA='A') { #define MEM_OFFSET(row,col) ((row)*M+col) for (int m=0; m<M; ++m) {X[m*(M+1)] = Analysis::sqAbs(x[m]);} // Calculate diagonal part. /* Pre-calculate conj(x) */ std::complex<T> *const conj_x = workspace; for (int i=0; i<M; ++i) {conj_x[i] = Analysis::conj(x[i]);} /* Calculate lower part. */ if (LUA == 'L' || LUA == 'A') { for (int r=1; r<M; ++r) { std::complex<T> *const X_ptr = &X[MEM_OFFSET(r,0)]; for (int c=0; c<r; ++c) { X_ptr[c] = Analysis::prod(x[r], conj_x[c]); } } } /* Calculate upper part. */ if (LUA == 'U') { for (int r=0; r<M-1; ++r) { std::complex<T> *const X_ptr = &X[MEM_OFFSET(r,0)]; for (int c=r+1; c<M; ++c) { X_ptr[c] = Analysis::prod(x[r], conj_x[c]); } } } else if (LUA == 'A') { // The lower part is already calculated. for (int r=0; r<M-1; ++r) { std::complex<T> *const X_ptr = &X[MEM_OFFSET(r,0)]; const std::complex<T> *const X_T_ptr = &X[MEM_OFFSET(0,r)]; for (int c=r+1; c<M; ++c) { X_ptr[c] = Analysis::conj(X_T_ptr[c*M]); } } } #undef MEM_OFFSET } /** * @brief Calculates matrix multiplication "AB" as "C" where "A", "B", "C" are compatible matrices. * * @tparam T the number type of the elements of the matrices * @param[in] l the number of the rows in the matrix "A" * @param[in] m the number of columns in the matrix "A" (= the number of the rows in the matrix "B") * @param[in] n the number of columns columns in the matrix "B" * @param[in] A the matrix A * @param[in] B the matrix B * @param[out] C the matrix C */ template <typename T> void mulMat(const size_t l, const size_t m, const size_t n, const T *const A, const T *const B, T *const C) { constexpr T ZERO = static_cast<T>(0); T *ptr_C = C; for (size_t r=0; r<l; ++r) { for (size_t c=0; c<n; ++c) { T sum(ZERO); const T *const ptr_A = A + r*m, *const ptr_B = B + c; for (size_t i=0; i<m; ++i) {Analysis::addProd(ptr_A[i], ptr_B[i*n], sum);} *ptr_C = sum; ++ptr_C; } } } /** * @brief Calculate the inner product of given 2 vectors "x" and "y". * * @tparam T the number type of the elements of "x" and "y" * @param[in] N the length of vector "x" and "y" * @param[in] x the vector "x" * @param[in] y the vector "y" * @return the inner product of "x" and "y" */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static T __attribute__((always_inline)) #else T #endif innerProd(const size_t N, const T * const x, const T *const y) { constexpr T ZERO = static_cast<T>(0); T sum(ZERO); for (size_t n=0; n<N; ++n) {Analysis::addProd(x[n], y[n], sum);} return sum; } /** * @brief Calculates Hermitian inner product of given 2 complex vectors "x", "y". * Hermitian inner product of "x" and "y" is defined as "<x^*, y>"", where "^*" represents conjugate and "<,>" represents inner product. * * @tparam T the number type of the real and imaginary parts of complex number * @param[in] N vector length * @param[in] vec1 1st input vector, "x" * @param[in] vec2 2nd input vector, "y" * @param[in] stride1 The sampling interval for input vector "x". "x" is represented as "x = [vec1[0], vec1[stride1], ..., vec1[(N-1)*stride2]]". * @param[in] stride2 same as above for "y". * @return the Hermitian inner product of 2 input vectors */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static std::complex<T> __attribute__((always_inline)) #else std::complex<T> #endif hermitianInnerProduct(const size_t N, const std::complex<T> *const vec1, const std::complex<T> *const vec2, const size_t stride1, const size_t stride2) { std::complex<T> sum(0, 0); for (size_t n=0, n1=0, n2=0; n<N; ++n, n1+=stride1, n2+=stride2) { Analysis::addConjProd(vec1[n1], vec2[n2], sum); // faster than "sum += std::conj(vec1[n1])*vec2[n2]" } return sum; } /** * @brief Calculates Hermitian inner product of given 2 complex vectors "x", "y". * Hermitian inner product of "x" and "y" is defined as "<x^*, y>", where "^*" represents conjugate and "<,>" represents inner product. * * @tparam T the number type of complex number's real and imaginary part * @param[in] N vector length * @param[in] vec1 1st input vector, "x" * @param[in] vec2 2nd input vector, "y" * @param[in] stride The sampling interval for input vector "x". "x" is represented as "x = [vec1[0], vec1[stride], ..., vec1[(N-1)*stride]]". The same applies to "y" too. * @return the Hermitian inner product of 2 input vectors */ template <typename T> #if MATH_LIB_INLINE_AGGRESSIVELY inline static std::complex<T> __attribute__((always_inline)) #else std::complex<T> #endif hermitianInnerProduct(const size_t N, const std::complex<T> *const vec1, const std::complex<T> *const vec2, const size_t stride=1) { return hermitianInnerProduct(N, vec1, vec2, stride, stride); } /** * @brief Calculates L-2 norm of a given complex vector "x". * * @tparam T the number type of complex number's real and imaginary part * @param[in] N vector length * @param[in] vec input vector * @param[in] stride The sampling interval for input vectors. "x" is represented as "x = [vec1[0], vec1[stride], ..., vec1[(N-1)*stride]]". * @return the L-2 norm of input vector */ template <typename T> inline static T __attribute__((always_inline)) l2Norm(const size_t N, const std::complex<T> *const vec, const size_t stride=1) { return std::sqrt(hermitianInnerProduct(N, vec, vec, stride).real()); } /** * @brief Calculates the LDL decomposition of a given Hermitian-and-invertible matrix "A". * Find a lower-triangle matrix "L" and a diagonal matrix D such that "A = LDL^*". * The diagonal entries of "L" are all 1, and the diagonal entries of "D" are all real numbers. * * @tparam T the number type of complex number's real and imaginary part * @param[in] m the number of the rows and columns in the matrix "A" * @param[in] A the matrix "A". Only diagonal and lower parts are needed, and upper part is not accessed. * @param[out] d the diagonal elements of D * @param[out] L The matrix "L". The upper part is NOT modified by this function. * @param[inout] workspace The pointer to a continuous memory space whose size is "(m-1)*sizeof(std::complex<T>)" bytes. This space is used during calculation. * @param[in] epsilon The threshold used for zero-division detection. Zero-division is detected when the absolute value of a divider is smaller than "epsilon". * @retval false A zero-division is detected and calculation is aborted. Maybe "A" is non-invertible. * @retval true The calculation is successfully done. */ template <typename T> bool ldlDecomp(const int m, const std::complex<T> *const A, T *const d, std::complex<T> *const L, std::complex<T> *const workspace, const T epsilon=1e-12) { #define MEM_OFFSET(row, col) ((row)*m+col) static_assert(std::is_floating_point<T>::value, "T must be floating point number type."); constexpr std::complex<T> ONE = 1; const std::complex<T> *A_diag_ptr = A; for (int i=0; i<m; ++i) { T di = A_diag_ptr->real(); A_diag_ptr += m+1; // d[i] <- Re(A[i,i]) std::complex<T> *const __restrict__ dL_ptr = workspace; { std::complex<T> *const L_row_ptr = &L[MEM_OFFSET(i,0)]; for (int j=0; j<i; ++j) { const std::complex<T> &L_ij = L_row_ptr[j]; Analysis::subtractProd(d[j], Analysis::sqAbs(L_ij), di); // d[i] <- d[i] - d[j]*|L[i,j]|^2 dL_ptr[j] = Analysis::prod(d[j], std::conj(L_ij)); // Construct "d[j]*conj(L[i,j]) (j=0,1, ..., i-1)" } } d[i] = di; if (std::abs(di) < epsilon) { return false; } const T inv_di = 1/d[i]; L[MEM_OFFSET(i,i)] = ONE; const std::complex<T> *A_col_ptr = &A[MEM_OFFSET(i+1,i)]; std::complex<T> *L_col_ptr = &L[MEM_OFFSET(i+1,i)]; for (int k=i+1; k<m; ++k) { std::complex<T> L_ki = *A_col_ptr; A_col_ptr += m; // L[k,i] <- A[k,i] std::complex<T> *const L_row_ptr = &L[MEM_OFFSET(k,0)]; for (int j=0; j<i; ++j) { // L[k,i] <- L[k,i] - L[k,j]d[j]*conj(L[i,j]) Analysis::subtractProd(L_row_ptr[j], dL_ptr[j], L_ki); // faster than "L_ki -= L_row_ptr[j]*dL_ptr[j]" } *L_col_ptr = inv_di*L_ki; L_col_ptr += m; // L[k,i] <- L[k,i]/d[i] } } return true; #undef MEM_OFFSET } /** * @brief Calculates the LDL decomposition of a given Hermitian-and-invertible matrix "A". * Find a lower-triangle matrix "L" and a diagonal matrix D such that "A = LDL^*". * The diagonal entries of "L" are all 1, and the diagonal entries of "D" are all real numbers. * * @tparam T the number type of matrix "A" * @param[in] m the number of the rows and columns in the matrix "A" * @param[in] A the matrix "A". Only diagonal and lower parts are needed, and upper part is not accessed. * @param[out] d the diagonal elements of D * @param[out] L The matrix "L". The upper part is NOT modified by this function. * @param[inout] workspace The pointer to a continuous memory space whose size is "(m-1)*sizeof(T)" bytes. This space is used during calculation. * @param[in] epsilon The threshold used for zero-division detection. Zero-division is detected when the absolute value of a divider is smaller than "epsilon". * @retval false A zero-division is detected and calculation is aborted. Maybe "A" is non-invertible. * @retval true The calculation is successfully done. */ template <typename T> bool ldlDecomp(const int m, const T *const A, T *const d, T *const L, T *const workspace, const T epsilon=1e-12) { #define MEM_OFFSET(row, col) ((row)*m+col) static_assert(std::is_floating_point<T>::value, "T must be floating point number type."); const T *A_diag_ptr = A; for (int i=0; i<m; ++i) { T di = *A_diag_ptr; A_diag_ptr += m+1; // d[i] <- A[i,i] T *const dL_ptr = workspace; { T *const L_row_ptr = &L[MEM_OFFSET(i,0)]; for (int j=0; j<i; ++j) { const T &L_ij = L_row_ptr[j]; di -= d[j]*MathLib::Analysis::sqAbs(L_ij); // d[i] <- d[i] - d[j]*|L[i,j]|^2 dL_ptr[j] = d[j]*L_ij; // Construct "d[j]*conj(L[i,j]) (j=0,1, ..., i-1)" } } d[i] = di; if (std::abs(di) < epsilon) { return false; } const T inv_di = 1/d[i]; L[MEM_OFFSET(i,i)] = 1; const T *A_col_ptr = &A[MEM_OFFSET(i+1,i)]; T *L_col_ptr = &L[MEM_OFFSET(i+1,i)]; for (int k=i+1; k<m; ++k) { T L_ki = *A_col_ptr; A_col_ptr += m; // L[k,i] <- A[k,i] T *const L_row_ptr = &L[MEM_OFFSET(k,0)]; for (int j=0; j<i; ++j) {L_ki -= L_row_ptr[j]*dL_ptr[j];} // L[k,i] <- L[k,i] - L[k,j]d[j]*L[i,j] *L_col_ptr = inv_di*L_ki; L_col_ptr += m; // L[k,i] <- L[k,i]/d[i] } } return true; #undef MEM_OFFSET } /** * @brief Solves linear equation "Ax = b" by Gaussian elimination, where "A" is a square invertible matrix of size "m", and "b" is a vector of length "m". * The matrix "A" must be invertible, otherwise the behavior is undefined. * When "A" is known to be Hermitian, use `solveLinEqHermitian` function rather than this function, to achieve higher performance. * * @tparam T the number type of the elements of the matrix "A", vector "b" and "x" * @param[in] m the number of the rows and columns in the matrix "A" * @param[in] A the matrix "A" * @param[in] b the vector "b" * @param[out] x the vector "x" * @param[out] workspace The pointer to a continuous memory space whose size is "m*(m+1)*sizeof(T) + m*sizeof(size_t)" bytes. This space is used for the extended-matrix "[A, b]" and the row exchanging table. */ template <typename T> void solveLinearEquation(const size_t m, const T *const A, const T *const b, T *const x, char *workspace) { #define MEM_OFFSET_E(row, col) ((row)*(m+1)+col) constexpr T ZERO = 0.0; constexpr T ONE = 1.0; /* Creates an extended matrix "E". */ T *E = reinterpret_cast<T *>(workspace); workspace += m*(m+1)*sizeof(T); { const T *ptr_A = A, *ptr_b = b; T *ptr_E = E; for (size_t r=0; r<m; ++r) { std::memcpy(ptr_E, ptr_A, m*sizeof(T)); ptr_E += m; ptr_A += m; *ptr_E = *ptr_b; ++ptr_E; ++ptr_b; } } /* Initializes pivoting table. */ size_t *rowExchgTable = reinterpret_cast<size_t *>(workspace); std::iota(&rowExchgTable[0], &rowExchgTable[m], 0); for (size_t r=0; r<m; ++r) { /* Pivoting. Finds a row index r2 that |E[r2,r]| is largest in the set {|E[r,r]|, |E[r,r+1]|, ..., |E[r,m-1]|}. */ { size_t r2 = r; auto maxAbsVal = std::abs(E[MEM_OFFSET_E(rowExchgTable[r], r)]); for (size_t r3=r+1; r3<m; ++r3) { const auto currentAbsVal = std::abs(E[MEM_OFFSET_E(rowExchgTable[r3], r)]); if (currentAbsVal > maxAbsVal) { r2 = r3; maxAbsVal = currentAbsVal; } } std::swap(rowExchgTable[r], rowExchgTable[r2]); } /* Normalizes current row. */ { T *const ptr_E = E + MEM_OFFSET_E(rowExchgTable[r], 0); const T inv_E_rr = ONE/ptr_E[r]; ptr_E[r] = ONE; for (size_t c=r+1; c<m+1; ++c) {ptr_E[c] *= inv_E_rr;} } /* Reduces the rows over/under current row. */ { for (size_t r2=0; r2<m; ++r2) { if (r2 == r) { continue; } T *const ptr2_E = E + MEM_OFFSET_E(rowExchgTable[r2], 0); const T minus_E_r2r = -ptr2_E[r]; ptr2_E[r] = ZERO; const T *const ptr1_E = E + MEM_OFFSET_E(rowExchgTable[r], 0); for (size_t c=r+1; c<m+1; ++c) { Analysis::addProd(minus_E_r2r, ptr1_E[c], ptr2_E[c]); } } } } for (size_t r=0; r<m; ++r) {x[r] = E[MEM_OFFSET_E(rowExchgTable[r], m)];} // Stores the result. #undef MEM_OFFSET_E } /** * @brief Solve linear equation "Ax = b" using LDL decomposition, where "A" is a Hermitian and invertible matrix of size "m", and "b" is a vector of length "m". * The matrix "A" MUST be invertible. * * @tparam T the number type of the elements of the matrix "A", vector "b" and "x" * @param[in] m the number of the rows and columns in the matrix "A" * @param[in] A the matrix "A" * @param[in] b the vector "b" * @param[out] x the vector "x" * @param[out] workspace The pointer to a continuous memory space. Its size is calculated as follows:@n * - when A's type is floating-point T: (m*m+2*m-1)*sizeof(T) * - when A's type is std::complex<T>: m*sizeof(T) + (m*m+m-1)*sizeof(std::complex<T>) * @retval false A zero-division is detected and calculation is aborted. Maybe "A" is non-invertible. * @retval true The calculation is successfully done. */ template <typename T> bool solveLinEqHermitian(const int m, const T *const A, const T *const b, T *const x, char *workspace) { #define MEM_OFFSET(row, col) ((row)*m+col) if (m <= 0) { return true; } /* LDL decomposition */ typedef decltype(std::real(*A)) T_real; // floating-point type "A" is ok T_real *const d = reinterpret_cast<T_real *>(workspace); workspace += m*sizeof(T_real); T *const L = reinterpret_cast<T *>(workspace); workspace += m*m*sizeof(T); const bool noZeroDiv = ldlDecomp(m, A, d, L, reinterpret_cast<T *>(workspace)); if (!noZeroDiv) { return false; } /* forward substitution (Ly == b) */ T *const y = x; // Use "x" as a temporary buffer. for (int i=0; i<m; ++i) { T yi = b[i]; T *const L_ptr = &L[MEM_OFFSET(i,0)]; for (int j=0; j<i; ++j) { Analysis::subtractProd(L_ptr[j], y[j], yi); // higher performance than "yi -= L_ptr[j]*y[j]" for complex numbers } y[i] = yi; } /* backward substitution (DL^*x == y) */ for (int i=m-1; i>=0; --i) { T xi = y[i]/d[i]; for (int j=i+1; j<m; ++j) { Analysis::subtractProd(Analysis::conj(L[MEM_OFFSET(j,i)]), x[j], xi); // higher performance than "xi -= MathLib::Analysis::conj(L[MEM_OFFSET(j,i)])*x[j];" for complex numbers } x[i] = xi; } return true; #undef MEM_OFFSET } } }
46.099
215
0.508015
[ "vector" ]
2d02eec6c1fa1455c5323333f2ec7939f706d9ce
6,520
hpp
C++
navigation/teb_local_planner/include/teb_local_planner/homotopy_class_planner.hpp
mrsd16teamd/loco_car
36e4ed685f9463ad689ca72eec80e0f05f1ad66c
[ "MIT" ]
48
2016-11-10T06:00:27.000Z
2022-03-01T12:57:23.000Z
navigation/teb_local_planner/include/teb_local_planner/homotopy_class_planner.hpp
mrsd16teamd/loco_car
36e4ed685f9463ad689ca72eec80e0f05f1ad66c
[ "MIT" ]
6
2017-04-03T05:39:06.000Z
2017-07-27T02:35:44.000Z
navigation/teb_local_planner/include/teb_local_planner/homotopy_class_planner.hpp
mrsd16teamd/loco_car
36e4ed685f9463ad689ca72eec80e0f05f1ad66c
[ "MIT" ]
20
2017-02-28T13:24:31.000Z
2021-12-06T12:36:46.000Z
/********************************************************************* * * Software License Agreement (BSD License) * * Copyright (c) 2016, * TU Dortmund - Institute of Control Theory and Systems Engineering. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the institute nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Author: Christoph Rösmann *********************************************************************/ #include <teb_local_planner/homotopy_class_planner.h> namespace teb_local_planner { template<typename BidirIter, typename Fun> std::complex<long double> HomotopyClassPlanner::calculateHSignature(BidirIter path_start, BidirIter path_end, Fun fun_cplx_point, const ObstContainer* obstacles, double prescaler) { if (obstacles->empty()) return std::complex<double>(0,0); ROS_ASSERT_MSG(prescaler>0.1 && prescaler<=1, "Only a prescaler on the interval (0.1,1] ist allowed."); // guess values for f0 // paper proposes a+b=N-1 && |a-b|<=1, 1...N obstacles int m = obstacles->size()-1; int a = (int) std::ceil(double(m)/2.0); int b = m-a; std::advance(path_end, -1); // reduce path_end by 1 (since we check line segments between those path points typedef std::complex<long double> cplx; // guess map size (only a really really coarse guess is required // use distance from start to goal as distance to each direction // TODO: one could move the map determination outside this function, since it remains constant for the whole planning interval cplx start = fun_cplx_point(*path_start); cplx end = fun_cplx_point(*path_end); // path_end points to the last point now after calling std::advance before cplx delta = end-start; cplx normal(-delta.imag(), delta.real()); cplx map_bottom_left; cplx map_top_right; if (std::abs(delta) < 3.0) { // set minimum bound on distance (we do not want to have numerical instabilities) and 3.0 performs fine... map_bottom_left = start + cplx(0, -3); map_top_right = start + cplx(3, 3); } else { map_bottom_left = start - normal; map_top_right = start + delta + normal; } cplx H = 0; std::vector<double> imag_proposals(5); // iterate path while(path_start != path_end) { cplx z1 = fun_cplx_point(*path_start); cplx z2 = fun_cplx_point(*boost::next(path_start)); for (unsigned int l=0; l<obstacles->size(); ++l) // iterate all obstacles { cplx obst_l = obstacles->at(l)->getCentroidCplx(); //cplx f0 = (long double) prescaler * std::pow(obst_l-map_bottom_left,a) * std::pow(obst_l-map_top_right,b); cplx f0 = (long double) prescaler * (long double)a*(obst_l-map_bottom_left) * (long double)b*(obst_l-map_top_right); // denum contains product with all obstacles exepct j==l cplx Al = f0; for (unsigned int j=0; j<obstacles->size(); ++j) { if (j==l) continue; cplx obst_j = obstacles->at(j)->getCentroidCplx(); cplx diff = obst_l - obst_j; //if (diff.real()!=0 || diff.imag()!=0) if (std::abs(diff)<0.05) // skip really close obstacles Al /= diff; else continue; } // compute log value double diff2 = std::abs(z2-obst_l); double diff1 = std::abs(z1-obst_l); if (diff2 == 0 || diff1 == 0) continue; double log_real = std::log(diff2)-std::log(diff1); // complex ln has more than one solution -> choose minimum abs angle -> paper double arg_diff = std::arg(z2-obst_l)-std::arg(z1-obst_l); imag_proposals.at(0) = arg_diff; imag_proposals.at(1) = arg_diff+2*M_PI; imag_proposals.at(2) = arg_diff-2*M_PI; imag_proposals.at(3) = arg_diff+4*M_PI; imag_proposals.at(4) = arg_diff-4*M_PI; double log_imag = *std::min_element(imag_proposals.begin(),imag_proposals.end(),smaller_than_abs); cplx log_value(log_real,log_imag); //cplx log_value = std::log(z2-obst_l)-std::log(z1-obst_l); // the principal solution doesn't seem to work H += Al*log_value; } ++path_start; } return H; } template<typename BidirIter, typename Fun> void HomotopyClassPlanner::addAndInitNewTeb(BidirIter path_start, BidirIter path_end, Fun fun_position, double start_orientation, double goal_orientation, boost::optional<const Eigen::Vector2d&> start_velocity) { tebs_.push_back( TebOptimalPlannerPtr( new TebOptimalPlanner(*cfg_, obstacles_, robot_model_) ) ); tebs_.back()->teb().initTEBtoGoal(path_start, path_end, fun_position, cfg_->robot.max_vel_x, cfg_->robot.max_vel_theta, cfg_->robot.acc_lim_x, cfg_->robot.acc_lim_theta, start_orientation, goal_orientation, cfg_->trajectory.min_samples); if (start_velocity) tebs_.back()->setVelocityStart(*start_velocity); } } // namespace teb_local_planner
43.466667
179
0.655215
[ "vector" ]
2d06ffa7dff0754d04c25d27a0e4e38615152ca4
552,328
cpp
C++
centrosome/_filter.cpp
cclauss/centrosome
70373585d6d742c3f8f7ea844b5159861665c87d
[ "BSD-3-Clause" ]
null
null
null
centrosome/_filter.cpp
cclauss/centrosome
70373585d6d742c3f8f7ea844b5159861665c87d
[ "BSD-3-Clause" ]
null
null
null
centrosome/_filter.cpp
cclauss/centrosome
70373585d6d742c3f8f7ea844b5159861665c87d
[ "BSD-3-Clause" ]
null
null
null
/* Generated by Cython 0.27.3 */ #define PY_SSIZE_T_CLEAN #include "Python.h" #ifndef Py_PYTHON_H #error Python headers needed to compile C extensions, please install development version of Python. #elif PY_VERSION_HEX < 0x02060000 || (0x03000000 <= PY_VERSION_HEX && PY_VERSION_HEX < 0x03030000) #error Cython requires Python 2.6+ or Python 3.3+. #else #define CYTHON_ABI "0_27_3" #define CYTHON_FUTURE_DIVISION 0 #include <stddef.h> #ifndef offsetof #define offsetof(type, member) ( (size_t) & ((type*)0) -> member ) #endif #if !defined(WIN32) && !defined(MS_WINDOWS) #ifndef __stdcall #define __stdcall #endif #ifndef __cdecl #define __cdecl #endif #ifndef __fastcall #define __fastcall #endif #endif #ifndef DL_IMPORT #define DL_IMPORT(t) t #endif #ifndef DL_EXPORT #define DL_EXPORT(t) t #endif #define __PYX_COMMA , #ifndef HAVE_LONG_LONG #if PY_VERSION_HEX >= 0x02070000 #define HAVE_LONG_LONG #endif #endif #ifndef PY_LONG_LONG #define PY_LONG_LONG LONG_LONG #endif #ifndef Py_HUGE_VAL #define Py_HUGE_VAL HUGE_VAL #endif #ifdef PYPY_VERSION #define CYTHON_COMPILING_IN_PYPY 1 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 0 #undef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 0 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #if PY_VERSION_HEX < 0x03050000 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #undef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #undef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 1 #undef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 0 #undef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 0 #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #elif defined(PYSTON_VERSION) #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 1 #define CYTHON_COMPILING_IN_CPYTHON 0 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #undef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 0 #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #undef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 0 #undef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 0 #undef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT 0 #undef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE 0 #else #define CYTHON_COMPILING_IN_PYPY 0 #define CYTHON_COMPILING_IN_PYSTON 0 #define CYTHON_COMPILING_IN_CPYTHON 1 #ifndef CYTHON_USE_TYPE_SLOTS #define CYTHON_USE_TYPE_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYTYPE_LOOKUP #define CYTHON_USE_PYTYPE_LOOKUP 0 #elif !defined(CYTHON_USE_PYTYPE_LOOKUP) #define CYTHON_USE_PYTYPE_LOOKUP 1 #endif #if PY_MAJOR_VERSION < 3 #undef CYTHON_USE_ASYNC_SLOTS #define CYTHON_USE_ASYNC_SLOTS 0 #elif !defined(CYTHON_USE_ASYNC_SLOTS) #define CYTHON_USE_ASYNC_SLOTS 1 #endif #if PY_VERSION_HEX < 0x02070000 #undef CYTHON_USE_PYLONG_INTERNALS #define CYTHON_USE_PYLONG_INTERNALS 0 #elif !defined(CYTHON_USE_PYLONG_INTERNALS) #define CYTHON_USE_PYLONG_INTERNALS 1 #endif #ifndef CYTHON_USE_PYLIST_INTERNALS #define CYTHON_USE_PYLIST_INTERNALS 1 #endif #ifndef CYTHON_USE_UNICODE_INTERNALS #define CYTHON_USE_UNICODE_INTERNALS 1 #endif #if PY_VERSION_HEX < 0x030300F0 #undef CYTHON_USE_UNICODE_WRITER #define CYTHON_USE_UNICODE_WRITER 0 #elif !defined(CYTHON_USE_UNICODE_WRITER) #define CYTHON_USE_UNICODE_WRITER 1 #endif #ifndef CYTHON_AVOID_BORROWED_REFS #define CYTHON_AVOID_BORROWED_REFS 0 #endif #ifndef CYTHON_ASSUME_SAFE_MACROS #define CYTHON_ASSUME_SAFE_MACROS 1 #endif #ifndef CYTHON_UNPACK_METHODS #define CYTHON_UNPACK_METHODS 1 #endif #ifndef CYTHON_FAST_THREAD_STATE #define CYTHON_FAST_THREAD_STATE 1 #endif #ifndef CYTHON_FAST_PYCALL #define CYTHON_FAST_PYCALL 1 #endif #ifndef CYTHON_PEP489_MULTI_PHASE_INIT #define CYTHON_PEP489_MULTI_PHASE_INIT (0 && PY_VERSION_HEX >= 0x03050000) #endif #ifndef CYTHON_USE_TP_FINALIZE #define CYTHON_USE_TP_FINALIZE (PY_VERSION_HEX >= 0x030400a1) #endif #endif #if !defined(CYTHON_FAST_PYCCALL) #define CYTHON_FAST_PYCCALL (CYTHON_FAST_PYCALL && PY_VERSION_HEX >= 0x030600B1) #endif #if CYTHON_USE_PYLONG_INTERNALS #include "longintrepr.h" #undef SHIFT #undef BASE #undef MASK #endif #if CYTHON_COMPILING_IN_PYPY && PY_VERSION_HEX < 0x02070600 && !defined(Py_OptimizeFlag) #define Py_OptimizeFlag 0 #endif #define __PYX_BUILD_PY_SSIZE_T "n" #define CYTHON_FORMAT_SSIZE_T "z" #if PY_MAJOR_VERSION < 3 #define __Pyx_BUILTIN_MODULE_NAME "__builtin__" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyClass_Type #else #define __Pyx_BUILTIN_MODULE_NAME "builtins" #define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)\ PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) #define __Pyx_DefaultClassType PyType_Type #endif #ifndef Py_TPFLAGS_CHECKTYPES #define Py_TPFLAGS_CHECKTYPES 0 #endif #ifndef Py_TPFLAGS_HAVE_INDEX #define Py_TPFLAGS_HAVE_INDEX 0 #endif #ifndef Py_TPFLAGS_HAVE_NEWBUFFER #define Py_TPFLAGS_HAVE_NEWBUFFER 0 #endif #ifndef Py_TPFLAGS_HAVE_FINALIZE #define Py_TPFLAGS_HAVE_FINALIZE 0 #endif #if PY_VERSION_HEX < 0x030700A0 || !defined(METH_FASTCALL) #ifndef METH_FASTCALL #define METH_FASTCALL 0x80 #endif typedef PyObject *(*__Pyx_PyCFunctionFast) (PyObject *self, PyObject **args, Py_ssize_t nargs); typedef PyObject *(*__Pyx_PyCFunctionFastWithKeywords) (PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *kwnames); #else #define __Pyx_PyCFunctionFast _PyCFunctionFast #define __Pyx_PyCFunctionFastWithKeywords _PyCFunctionFastWithKeywords #endif #if CYTHON_FAST_PYCCALL #define __Pyx_PyFastCFunction_Check(func)\ ((PyCFunction_Check(func) && (METH_FASTCALL == (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS))))) #else #define __Pyx_PyFastCFunction_Check(func) 0 #endif #if !CYTHON_FAST_THREAD_STATE || PY_VERSION_HEX < 0x02070000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #elif PY_VERSION_HEX >= 0x03060000 #define __Pyx_PyThreadState_Current _PyThreadState_UncheckedGet() #elif PY_VERSION_HEX >= 0x03000000 #define __Pyx_PyThreadState_Current PyThreadState_GET() #else #define __Pyx_PyThreadState_Current _PyThreadState_Current #endif #if CYTHON_COMPILING_IN_CPYTHON || defined(_PyDict_NewPresized) #define __Pyx_PyDict_NewPresized(n) ((n <= 8) ? PyDict_New() : _PyDict_NewPresized(n)) #else #define __Pyx_PyDict_NewPresized(n) PyDict_New() #endif #if PY_MAJOR_VERSION >= 3 || CYTHON_FUTURE_DIVISION #define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y) #else #define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y) #define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y) #endif #if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND) #define CYTHON_PEP393_ENABLED 1 #define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ?\ 0 : _PyUnicode_Ready((PyObject *)(op))) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) PyUnicode_MAX_CHAR_VALUE(u) #define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u) #define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u) #define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) PyUnicode_WRITE(k, d, i, ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != (likely(PyUnicode_IS_READY(u)) ? PyUnicode_GET_LENGTH(u) : PyUnicode_GET_SIZE(u))) #else #define CYTHON_PEP393_ENABLED 0 #define PyUnicode_1BYTE_KIND 1 #define PyUnicode_2BYTE_KIND 2 #define PyUnicode_4BYTE_KIND 4 #define __Pyx_PyUnicode_READY(op) (0) #define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u) #define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i])) #define __Pyx_PyUnicode_MAX_CHAR_VALUE(u) ((sizeof(Py_UNICODE) == 2) ? 65535 : 1114111) #define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE)) #define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u)) #define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i])) #define __Pyx_PyUnicode_WRITE(k, d, i, ch) (((void)(k)), ((Py_UNICODE*)d)[i] = ch) #define __Pyx_PyUnicode_IS_TRUE(u) (0 != PyUnicode_GET_SIZE(u)) #endif #if CYTHON_COMPILING_IN_PYPY #define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b) #else #define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b) #define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ?\ PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b)) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyUnicode_Contains) #define PyUnicode_Contains(u, s) PySequence_Contains(u, s) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyByteArray_Check) #define PyByteArray_Check(obj) PyObject_TypeCheck(obj, &PyByteArray_Type) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Format) #define PyObject_Format(obj, fmt) PyObject_CallMethod(obj, "__format__", "O", fmt) #endif #if CYTHON_COMPILING_IN_PYPY && !defined(PyObject_Malloc) #define PyObject_Malloc(s) PyMem_Malloc(s) #define PyObject_Free(p) PyMem_Free(p) #define PyObject_Realloc(p) PyMem_Realloc(p) #endif #if CYTHON_COMPILING_IN_PYSTON #define __Pyx_PyCode_HasFreeVars(co) PyCode_HasFreeVars(co) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) PyFrame_SetLineNumber(frame, lineno) #else #define __Pyx_PyCode_HasFreeVars(co) (PyCode_GetNumFree(co) > 0) #define __Pyx_PyFrame_SetLineNumber(frame, lineno) (frame)->f_lineno = (lineno) #endif #define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b)) #define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b) #else #define __Pyx_PyString_Format(a, b) PyString_Format(a, b) #endif #if PY_MAJOR_VERSION < 3 && !defined(PyObject_ASCII) #define PyObject_ASCII(o) PyObject_Repr(o) #endif #if PY_MAJOR_VERSION >= 3 #define PyBaseString_Type PyUnicode_Type #define PyStringObject PyUnicodeObject #define PyString_Type PyUnicode_Type #define PyString_Check PyUnicode_Check #define PyString_CheckExact PyUnicode_CheckExact #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj) #define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj) #else #define __Pyx_PyBaseString_Check(obj) (PyString_Check(obj) || PyUnicode_Check(obj)) #define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj)) #endif #ifndef PySet_CheckExact #define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type) #endif #define __Pyx_PyException_Check(obj) __Pyx_TypeCheck(obj, PyExc_Exception) #if PY_MAJOR_VERSION >= 3 #define PyIntObject PyLongObject #define PyInt_Type PyLong_Type #define PyInt_Check(op) PyLong_Check(op) #define PyInt_CheckExact(op) PyLong_CheckExact(op) #define PyInt_FromString PyLong_FromString #define PyInt_FromUnicode PyLong_FromUnicode #define PyInt_FromLong PyLong_FromLong #define PyInt_FromSize_t PyLong_FromSize_t #define PyInt_FromSsize_t PyLong_FromSsize_t #define PyInt_AsLong PyLong_AsLong #define PyInt_AS_LONG PyLong_AS_LONG #define PyInt_AsSsize_t PyLong_AsSsize_t #define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask #define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask #define PyNumber_Int PyNumber_Long #endif #if PY_MAJOR_VERSION >= 3 #define PyBoolObject PyLongObject #endif #if PY_MAJOR_VERSION >= 3 && CYTHON_COMPILING_IN_PYPY #ifndef PyUnicode_InternFromString #define PyUnicode_InternFromString(s) PyUnicode_FromString(s) #endif #endif #if PY_VERSION_HEX < 0x030200A4 typedef long Py_hash_t; #define __Pyx_PyInt_FromHash_t PyInt_FromLong #define __Pyx_PyInt_AsHash_t PyInt_AsLong #else #define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t #define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t #endif #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func)) #else #define __Pyx_PyMethod_New(func, self, klass) PyMethod_New(func, self, klass) #endif #ifndef __has_attribute #define __has_attribute(x) 0 #endif #ifndef __has_cpp_attribute #define __has_cpp_attribute(x) 0 #endif #if CYTHON_USE_ASYNC_SLOTS #if PY_VERSION_HEX >= 0x030500B1 #define __Pyx_PyAsyncMethodsStruct PyAsyncMethods #define __Pyx_PyType_AsAsync(obj) (Py_TYPE(obj)->tp_as_async) #else #define __Pyx_PyType_AsAsync(obj) ((__Pyx_PyAsyncMethodsStruct*) (Py_TYPE(obj)->tp_reserved)) #endif #else #define __Pyx_PyType_AsAsync(obj) NULL #endif #ifndef __Pyx_PyAsyncMethodsStruct typedef struct { unaryfunc am_await; unaryfunc am_aiter; unaryfunc am_anext; } __Pyx_PyAsyncMethodsStruct; #endif #ifndef CYTHON_RESTRICT #if defined(__GNUC__) #define CYTHON_RESTRICT __restrict__ #elif defined(_MSC_VER) && _MSC_VER >= 1400 #define CYTHON_RESTRICT __restrict #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define CYTHON_RESTRICT restrict #else #define CYTHON_RESTRICT #endif #endif #ifndef CYTHON_UNUSED # if defined(__GNUC__) # if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif # elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER)) # define CYTHON_UNUSED __attribute__ ((__unused__)) # else # define CYTHON_UNUSED # endif #endif #ifndef CYTHON_MAYBE_UNUSED_VAR # if defined(__cplusplus) template<class T> void CYTHON_MAYBE_UNUSED_VAR( const T& ) { } # else # define CYTHON_MAYBE_UNUSED_VAR(x) (void)(x) # endif #endif #ifndef CYTHON_NCP_UNUSED # if CYTHON_COMPILING_IN_CPYTHON # define CYTHON_NCP_UNUSED # else # define CYTHON_NCP_UNUSED CYTHON_UNUSED # endif #endif #define __Pyx_void_to_None(void_result) ((void)(void_result), Py_INCREF(Py_None), Py_None) #ifdef _MSC_VER #ifndef _MSC_STDINT_H_ #if _MSC_VER < 1300 typedef unsigned char uint8_t; typedef unsigned int uint32_t; #else typedef unsigned __int8 uint8_t; typedef unsigned __int32 uint32_t; #endif #endif #else #include <stdint.h> #endif #ifndef CYTHON_FALLTHROUGH #if defined(__cplusplus) && __cplusplus >= 201103L #if __has_cpp_attribute(fallthrough) #define CYTHON_FALLTHROUGH [[fallthrough]] #elif __has_cpp_attribute(clang::fallthrough) #define CYTHON_FALLTHROUGH [[clang::fallthrough]] #elif __has_cpp_attribute(gnu::fallthrough) #define CYTHON_FALLTHROUGH [[gnu::fallthrough]] #endif #endif #ifndef CYTHON_FALLTHROUGH #if __has_attribute(fallthrough) #define CYTHON_FALLTHROUGH __attribute__((fallthrough)) #else #define CYTHON_FALLTHROUGH #endif #endif #if defined(__clang__ ) && defined(__apple_build_version__) #if __apple_build_version__ < 7000000 #undef CYTHON_FALLTHROUGH #define CYTHON_FALLTHROUGH #endif #endif #endif #ifndef __cplusplus #error "Cython files generated with the C++ option must be compiled with a C++ compiler." #endif #ifndef CYTHON_INLINE #if defined(__clang__) #define CYTHON_INLINE __inline__ __attribute__ ((__unused__)) #else #define CYTHON_INLINE inline #endif #endif template<typename T> void __Pyx_call_destructor(T& x) { x.~T(); } template<typename T> class __Pyx_FakeReference { public: __Pyx_FakeReference() : ptr(NULL) { } __Pyx_FakeReference(const T& ref) : ptr(const_cast<T*>(&ref)) { } T *operator->() { return ptr; } T *operator&() { return ptr; } operator T&() { return *ptr; } template<typename U> bool operator ==(U other) { return *ptr == other; } template<typename U> bool operator !=(U other) { return *ptr != other; } private: T *ptr; }; #if defined(WIN32) || defined(MS_WINDOWS) #define _USE_MATH_DEFINES #endif #include <math.h> #ifdef NAN #define __PYX_NAN() ((float) NAN) #else static CYTHON_INLINE float __PYX_NAN() { float value; memset(&value, 0xFF, sizeof(value)); return value; } #endif #if defined(__CYGWIN__) && defined(_LDBL_EQ_DBL) #define __Pyx_truncl trunc #else #define __Pyx_truncl truncl #endif #define __PYX_ERR(f_index, lineno, Ln_error) \ { \ __pyx_filename = __pyx_f[f_index]; __pyx_lineno = lineno; __pyx_clineno = __LINE__; goto Ln_error; \ } #ifndef __PYX_EXTERN_C #ifdef __cplusplus #define __PYX_EXTERN_C extern "C" #else #define __PYX_EXTERN_C extern #endif #endif #define __PYX_HAVE__centrosome___filter #define __PYX_HAVE_API__centrosome___filter #include <string.h> #include <stdio.h> #include "numpy/arrayobject.h" #include "numpy/ufuncobject.h" #include "stdlib.h" #include "string.h" #ifdef _OPENMP #include <omp.h> #endif /* _OPENMP */ #if defined(PYREX_WITHOUT_ASSERTIONS) && !defined(CYTHON_WITHOUT_ASSERTIONS) #define CYTHON_WITHOUT_ASSERTIONS #endif typedef struct {PyObject **p; const char *s; const Py_ssize_t n; const char* encoding; const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; #define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0 #define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0 #define __PYX_DEFAULT_STRING_ENCODING "" #define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString #define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #define __Pyx_uchar_cast(c) ((unsigned char)c) #define __Pyx_long_cast(x) ((long)x) #define __Pyx_fits_Py_ssize_t(v, type, is_signed) (\ (sizeof(type) < sizeof(Py_ssize_t)) ||\ (sizeof(type) > sizeof(Py_ssize_t) &&\ likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX) &&\ (!is_signed || likely(v > (type)PY_SSIZE_T_MIN ||\ v == (type)PY_SSIZE_T_MIN))) ||\ (sizeof(type) == sizeof(Py_ssize_t) &&\ (is_signed || likely(v < (type)PY_SSIZE_T_MAX ||\ v == (type)PY_SSIZE_T_MAX))) ) #if defined (__cplusplus) && __cplusplus >= 201103L #include <cstdlib> #define __Pyx_sst_abs(value) std::abs(value) #elif SIZEOF_INT >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) abs(value) #elif SIZEOF_LONG >= SIZEOF_SIZE_T #define __Pyx_sst_abs(value) labs(value) #elif defined (_MSC_VER) #define __Pyx_sst_abs(value) ((Py_ssize_t)_abs64(value)) #elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L #define __Pyx_sst_abs(value) llabs(value) #elif defined (__GNUC__) #define __Pyx_sst_abs(value) __builtin_llabs(value) #else #define __Pyx_sst_abs(value) ((value<0) ? -value : value) #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject*); static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length); #define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s)) #define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l) #define __Pyx_PyBytes_FromString PyBytes_FromString #define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char*); #if PY_MAJOR_VERSION < 3 #define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize #else #define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString #define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize #endif #define __Pyx_PyBytes_AsWritableString(s) ((char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableSString(s) ((signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsWritableUString(s) ((unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsString(s) ((const char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsSString(s) ((const signed char*) PyBytes_AS_STRING(s)) #define __Pyx_PyBytes_AsUString(s) ((const unsigned char*) PyBytes_AS_STRING(s)) #define __Pyx_PyObject_AsWritableString(s) ((char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableSString(s) ((signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsWritableUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsSString(s) ((const signed char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_AsUString(s) ((const unsigned char*) __Pyx_PyObject_AsString(s)) #define __Pyx_PyObject_FromCString(s) __Pyx_PyObject_FromString((const char*)s) #define __Pyx_PyBytes_FromCString(s) __Pyx_PyBytes_FromString((const char*)s) #define __Pyx_PyByteArray_FromCString(s) __Pyx_PyByteArray_FromString((const char*)s) #define __Pyx_PyStr_FromCString(s) __Pyx_PyStr_FromString((const char*)s) #define __Pyx_PyUnicode_FromCString(s) __Pyx_PyUnicode_FromString((const char*)s) static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u) { const Py_UNICODE *u_end = u; while (*u_end++) ; return (size_t)(u_end - u - 1); } #define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u)) #define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode #define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode #define __Pyx_NewRef(obj) (Py_INCREF(obj), obj) #define __Pyx_Owned_Py_None(b) __Pyx_NewRef(Py_None) #define __Pyx_PyBool_FromLong(b) ((b) ? __Pyx_NewRef(Py_True) : __Pyx_NewRef(Py_False)) static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*); static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x); #define __Pyx_PySequence_Tuple(obj)\ (likely(PyTuple_CheckExact(obj)) ? __Pyx_NewRef(obj) : PySequence_Tuple(obj)) static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*); static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t); #if CYTHON_ASSUME_SAFE_MACROS #define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x)) #else #define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x) #endif #define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x)) #if PY_MAJOR_VERSION >= 3 #define __Pyx_PyNumber_Int(x) (PyLong_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Long(x)) #else #define __Pyx_PyNumber_Int(x) (PyInt_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Int(x)) #endif #define __Pyx_PyNumber_Float(x) (PyFloat_CheckExact(x) ? __Pyx_NewRef(x) : PyNumber_Float(x)) #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII static int __Pyx_sys_getdefaultencoding_not_ascii; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; PyObject* ascii_chars_u = NULL; PyObject* ascii_chars_b = NULL; const char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; if (strcmp(default_encoding_c, "ascii") == 0) { __Pyx_sys_getdefaultencoding_not_ascii = 0; } else { char ascii_chars[128]; int c; for (c = 0; c < 128; c++) { ascii_chars[c] = c; } __Pyx_sys_getdefaultencoding_not_ascii = 1; ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL); if (!ascii_chars_u) goto bad; ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL); if (!ascii_chars_b || !PyBytes_Check(ascii_chars_b) || memcmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) { PyErr_Format( PyExc_ValueError, "This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.", default_encoding_c); goto bad; } Py_DECREF(ascii_chars_u); Py_DECREF(ascii_chars_b); } Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); Py_XDECREF(ascii_chars_u); Py_XDECREF(ascii_chars_b); return -1; } #endif #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3 #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL) #else #define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL) #if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT static char* __PYX_DEFAULT_STRING_ENCODING; static int __Pyx_init_sys_getdefaultencoding_params(void) { PyObject* sys; PyObject* default_encoding = NULL; char* default_encoding_c; sys = PyImport_ImportModule("sys"); if (!sys) goto bad; default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL); Py_DECREF(sys); if (!default_encoding) goto bad; default_encoding_c = PyBytes_AsString(default_encoding); if (!default_encoding_c) goto bad; __PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c)); if (!__PYX_DEFAULT_STRING_ENCODING) goto bad; strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c); Py_DECREF(default_encoding); return 0; bad: Py_XDECREF(default_encoding); return -1; } #endif #endif /* Test for GCC > 2.95 */ #if defined(__GNUC__) && (__GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))) #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #else /* !__GNUC__ or GCC < 2.95 */ #define likely(x) (x) #define unlikely(x) (x) #endif /* __GNUC__ */ static CYTHON_INLINE void __Pyx_pretend_to_initialize(void* ptr) { (void)ptr; } static PyObject *__pyx_m = NULL; static PyObject *__pyx_d; static PyObject *__pyx_b; static PyObject *__pyx_cython_runtime; static PyObject *__pyx_empty_tuple; static PyObject *__pyx_empty_bytes; static PyObject *__pyx_empty_unicode; static int __pyx_lineno; static int __pyx_clineno = 0; static const char * __pyx_cfilenm= __FILE__; static const char *__pyx_filename; /* Header.proto */ #if !defined(CYTHON_CCOMPLEX) #if defined(__cplusplus) #define CYTHON_CCOMPLEX 1 #elif defined(_Complex_I) #define CYTHON_CCOMPLEX 1 #else #define CYTHON_CCOMPLEX 0 #endif #endif #if CYTHON_CCOMPLEX #ifdef __cplusplus #include <complex> #else #include <complex.h> #endif #endif #if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__) #undef _Complex_I #define _Complex_I 1.0fj #endif static const char *__pyx_f[] = { "centrosome/_filter.pyx", "__init__.pxd", "type.pxd", }; /* BufferFormatStructs.proto */ #define IS_UNSIGNED(type) (((type) -1) > 0) struct __Pyx_StructField_; #define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0) typedef struct { const char* name; struct __Pyx_StructField_* fields; size_t size; size_t arraysize[8]; int ndim; char typegroup; char is_unsigned; int flags; } __Pyx_TypeInfo; typedef struct __Pyx_StructField_ { __Pyx_TypeInfo* type; const char* name; size_t offset; } __Pyx_StructField; typedef struct { __Pyx_StructField* field; size_t parent_offset; } __Pyx_BufFmt_StackElem; typedef struct { __Pyx_StructField root; __Pyx_BufFmt_StackElem* head; size_t fmt_offset; size_t new_count, enc_count; size_t struct_alignment; int is_complex; char enc_type; char new_packmode; char enc_packmode; char is_valid_array; } __Pyx_BufFmt_Context; /* NoFastGil.proto */ #define __Pyx_PyGILState_Ensure PyGILState_Ensure #define __Pyx_PyGILState_Release PyGILState_Release #define __Pyx_FastGIL_Remember() #define __Pyx_FastGIL_Forget() #define __Pyx_FastGilFuncInit() /* ForceInitThreads.proto */ #ifndef __PYX_FORCE_INIT_THREADS #define __PYX_FORCE_INIT_THREADS 0 #endif /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":743 * # in Cython to enable them only on the right systems. * * ctypedef npy_int8 int8_t # <<<<<<<<<<<<<< * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t */ typedef npy_int8 __pyx_t_5numpy_int8_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":744 * * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t # <<<<<<<<<<<<<< * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t */ typedef npy_int16 __pyx_t_5numpy_int16_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":745 * ctypedef npy_int8 int8_t * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t # <<<<<<<<<<<<<< * ctypedef npy_int64 int64_t * #ctypedef npy_int96 int96_t */ typedef npy_int32 __pyx_t_5numpy_int32_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":746 * ctypedef npy_int16 int16_t * ctypedef npy_int32 int32_t * ctypedef npy_int64 int64_t # <<<<<<<<<<<<<< * #ctypedef npy_int96 int96_t * #ctypedef npy_int128 int128_t */ typedef npy_int64 __pyx_t_5numpy_int64_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":750 * #ctypedef npy_int128 int128_t * * ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<< * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t */ typedef npy_uint8 __pyx_t_5numpy_uint8_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":751 * * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<< * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t */ typedef npy_uint16 __pyx_t_5numpy_uint16_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":752 * ctypedef npy_uint8 uint8_t * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<< * ctypedef npy_uint64 uint64_t * #ctypedef npy_uint96 uint96_t */ typedef npy_uint32 __pyx_t_5numpy_uint32_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":753 * ctypedef npy_uint16 uint16_t * ctypedef npy_uint32 uint32_t * ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<< * #ctypedef npy_uint96 uint96_t * #ctypedef npy_uint128 uint128_t */ typedef npy_uint64 __pyx_t_5numpy_uint64_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":757 * #ctypedef npy_uint128 uint128_t * * ctypedef npy_float32 float32_t # <<<<<<<<<<<<<< * ctypedef npy_float64 float64_t * #ctypedef npy_float80 float80_t */ typedef npy_float32 __pyx_t_5numpy_float32_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":758 * * ctypedef npy_float32 float32_t * ctypedef npy_float64 float64_t # <<<<<<<<<<<<<< * #ctypedef npy_float80 float80_t * #ctypedef npy_float128 float128_t */ typedef npy_float64 __pyx_t_5numpy_float64_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":767 * # The int types are mapped a bit surprising -- * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t # <<<<<<<<<<<<<< * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t */ typedef npy_long __pyx_t_5numpy_int_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":768 * # numpy.int corresponds to 'l' and numpy.long to 'q' * ctypedef npy_long int_t * ctypedef npy_longlong long_t # <<<<<<<<<<<<<< * ctypedef npy_longlong longlong_t * */ typedef npy_longlong __pyx_t_5numpy_long_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":769 * ctypedef npy_long int_t * ctypedef npy_longlong long_t * ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<< * * ctypedef npy_ulong uint_t */ typedef npy_longlong __pyx_t_5numpy_longlong_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":771 * ctypedef npy_longlong longlong_t * * ctypedef npy_ulong uint_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t */ typedef npy_ulong __pyx_t_5numpy_uint_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":772 * * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<< * ctypedef npy_ulonglong ulonglong_t * */ typedef npy_ulonglong __pyx_t_5numpy_ulong_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":773 * ctypedef npy_ulong uint_t * ctypedef npy_ulonglong ulong_t * ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<< * * ctypedef npy_intp intp_t */ typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":775 * ctypedef npy_ulonglong ulonglong_t * * ctypedef npy_intp intp_t # <<<<<<<<<<<<<< * ctypedef npy_uintp uintp_t * */ typedef npy_intp __pyx_t_5numpy_intp_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":776 * * ctypedef npy_intp intp_t * ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<< * * ctypedef npy_double float_t */ typedef npy_uintp __pyx_t_5numpy_uintp_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":778 * ctypedef npy_uintp uintp_t * * ctypedef npy_double float_t # <<<<<<<<<<<<<< * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t */ typedef npy_double __pyx_t_5numpy_float_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":779 * * ctypedef npy_double float_t * ctypedef npy_double double_t # <<<<<<<<<<<<<< * ctypedef npy_longdouble longdouble_t * */ typedef npy_double __pyx_t_5numpy_double_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":780 * ctypedef npy_double float_t * ctypedef npy_double double_t * ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cfloat cfloat_t */ typedef npy_longdouble __pyx_t_5numpy_longdouble_t; /* "centrosome/_filter.pyx":45 * DTYPE_UINT32 = np.uint32 * DTYPE_BOOL = np.bool * ctypedef np.uint16_t pixel_count_t # <<<<<<<<<<<<<< * * ########### */ typedef __pyx_t_5numpy_uint16_t __pyx_t_10centrosome_7_filter_pixel_count_t; /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< float > __pyx_t_float_complex; #else typedef float _Complex __pyx_t_float_complex; #endif #else typedef struct { float real, imag; } __pyx_t_float_complex; #endif static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float); /* Declarations.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus typedef ::std::complex< double > __pyx_t_double_complex; #else typedef double _Complex __pyx_t_double_complex; #endif #else typedef struct { double real, imag; } __pyx_t_double_complex; #endif static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double); /*--- Type declarations ---*/ /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":782 * ctypedef npy_longdouble longdouble_t * * ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<< * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t */ typedef npy_cfloat __pyx_t_5numpy_cfloat_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":783 * * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<< * ctypedef npy_clongdouble clongdouble_t * */ typedef npy_cdouble __pyx_t_5numpy_cdouble_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":784 * ctypedef npy_cfloat cfloat_t * ctypedef npy_cdouble cdouble_t * ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<< * * ctypedef npy_cdouble complex_t */ typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":786 * ctypedef npy_clongdouble clongdouble_t * * ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew1(a): */ typedef npy_cdouble __pyx_t_5numpy_complex_t; struct __pyx_t_10centrosome_7_filter_HistogramPiece; struct __pyx_t_10centrosome_7_filter_Histogram; struct __pyx_t_10centrosome_7_filter_PixelCount; struct __pyx_t_10centrosome_7_filter_SCoord; struct __pyx_t_10centrosome_7_filter_Histograms; /* "centrosome/_filter.pyx":59 * ########### * * cdef struct HistogramPiece: # <<<<<<<<<<<<<< * np.uint16_t coarse[16] * np.uint16_t fine[256] */ struct __pyx_t_10centrosome_7_filter_HistogramPiece { __pyx_t_5numpy_uint16_t coarse[16]; __pyx_t_5numpy_uint16_t fine[0x100]; }; /* "centrosome/_filter.pyx":63 * np.uint16_t fine[256] * * cdef struct Histogram: # <<<<<<<<<<<<<< * HistogramPiece top_left # top-left corner * HistogramPiece top_right # top-right corner */ struct __pyx_t_10centrosome_7_filter_Histogram { struct __pyx_t_10centrosome_7_filter_HistogramPiece top_left; struct __pyx_t_10centrosome_7_filter_HistogramPiece top_right; struct __pyx_t_10centrosome_7_filter_HistogramPiece edge; struct __pyx_t_10centrosome_7_filter_HistogramPiece bottom_left; struct __pyx_t_10centrosome_7_filter_HistogramPiece bottom_right; }; /* "centrosome/_filter.pyx":74 * # because of the mask * # * cdef struct PixelCount: # <<<<<<<<<<<<<< * pixel_count_t top_left * pixel_count_t top_right */ struct __pyx_t_10centrosome_7_filter_PixelCount { __pyx_t_10centrosome_7_filter_pixel_count_t top_left; __pyx_t_10centrosome_7_filter_pixel_count_t top_right; __pyx_t_10centrosome_7_filter_pixel_count_t edge; __pyx_t_10centrosome_7_filter_pixel_count_t bottom_left; __pyx_t_10centrosome_7_filter_pixel_count_t bottom_right; }; /* "centrosome/_filter.pyx":85 * # relative offsets from the octagon center * # * cdef struct SCoord: # <<<<<<<<<<<<<< * np.int32_t stride # add the stride to the memory location * np.int32_t x */ struct __pyx_t_10centrosome_7_filter_SCoord { __pyx_t_5numpy_int32_t stride; __pyx_t_5numpy_int32_t x; __pyx_t_5numpy_int32_t y; }; /* "centrosome/_filter.pyx":90 * np.int32_t y * * cdef struct Histograms: # <<<<<<<<<<<<<< * void *memory # pointer to the allocated memory * Histogram *histogram # pointer to the histogram memory */ struct __pyx_t_10centrosome_7_filter_Histograms { void *memory; struct __pyx_t_10centrosome_7_filter_Histogram *histogram; struct __pyx_t_10centrosome_7_filter_PixelCount *pixel_count; __pyx_t_5numpy_uint8_t *data; __pyx_t_5numpy_uint8_t *mask; __pyx_t_5numpy_uint8_t *output; __pyx_t_5numpy_int32_t column_count; __pyx_t_5numpy_int32_t stripe_length; __pyx_t_5numpy_int32_t row_count; __pyx_t_5numpy_int32_t current_column; __pyx_t_5numpy_int32_t current_row; __pyx_t_5numpy_int32_t current_stride; __pyx_t_5numpy_int32_t radius; __pyx_t_5numpy_int32_t a_2; struct __pyx_t_10centrosome_7_filter_SCoord last_top_left; struct __pyx_t_10centrosome_7_filter_SCoord top_left; struct __pyx_t_10centrosome_7_filter_SCoord last_top_right; struct __pyx_t_10centrosome_7_filter_SCoord top_right; struct __pyx_t_10centrosome_7_filter_SCoord last_leading_edge; struct __pyx_t_10centrosome_7_filter_SCoord leading_edge; struct __pyx_t_10centrosome_7_filter_SCoord last_bottom_right; struct __pyx_t_10centrosome_7_filter_SCoord bottom_right; struct __pyx_t_10centrosome_7_filter_SCoord last_bottom_left; struct __pyx_t_10centrosome_7_filter_SCoord bottom_left; __pyx_t_5numpy_int32_t row_stride; __pyx_t_5numpy_int32_t col_stride; struct __pyx_t_10centrosome_7_filter_HistogramPiece accumulator; __pyx_t_5numpy_uint32_t accumulator_count; __pyx_t_5numpy_int32_t percent; __pyx_t_5numpy_int32_t last_update_column[16]; }; /* --- Runtime support code (head) --- */ /* Refnanny.proto */ #ifndef CYTHON_REFNANNY #define CYTHON_REFNANNY 0 #endif #if CYTHON_REFNANNY typedef struct { void (*INCREF)(void*, PyObject*, int); void (*DECREF)(void*, PyObject*, int); void (*GOTREF)(void*, PyObject*, int); void (*GIVEREF)(void*, PyObject*, int); void* (*SetupContext)(const char*, int, const char*); void (*FinishContext)(void**); } __Pyx_RefNannyAPIStruct; static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL; static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); #define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL; #ifdef WITH_THREAD #define __Pyx_RefNannySetupContext(name, acquire_gil)\ if (acquire_gil) {\ PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ PyGILState_Release(__pyx_gilstate_save);\ } else {\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__);\ } #else #define __Pyx_RefNannySetupContext(name, acquire_gil)\ __pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__) #endif #define __Pyx_RefNannyFinishContext()\ __Pyx_RefNanny->FinishContext(&__pyx_refnanny) #define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__) #define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0) #define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0) #define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0) #define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0) #else #define __Pyx_RefNannyDeclarations #define __Pyx_RefNannySetupContext(name, acquire_gil) #define __Pyx_RefNannyFinishContext() #define __Pyx_INCREF(r) Py_INCREF(r) #define __Pyx_DECREF(r) Py_DECREF(r) #define __Pyx_GOTREF(r) #define __Pyx_GIVEREF(r) #define __Pyx_XINCREF(r) Py_XINCREF(r) #define __Pyx_XDECREF(r) Py_XDECREF(r) #define __Pyx_XGOTREF(r) #define __Pyx_XGIVEREF(r) #endif #define __Pyx_XDECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_XDECREF(tmp);\ } while (0) #define __Pyx_DECREF_SET(r, v) do {\ PyObject *tmp = (PyObject *) r;\ r = v; __Pyx_DECREF(tmp);\ } while (0) #define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0) #define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0) /* PyObjectGetAttrStr.proto */ #if CYTHON_USE_TYPE_SLOTS static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) { PyTypeObject* tp = Py_TYPE(obj); if (likely(tp->tp_getattro)) return tp->tp_getattro(obj, attr_name); #if PY_MAJOR_VERSION < 3 if (likely(tp->tp_getattr)) return tp->tp_getattr(obj, PyString_AS_STRING(attr_name)); #endif return PyObject_GetAttr(obj, attr_name); } #else #define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n) #endif /* GetBuiltinName.proto */ static PyObject *__Pyx_GetBuiltinName(PyObject *name); /* None.proto */ static CYTHON_INLINE long __Pyx_div_long(long, long); /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_EqObjC(op1, op2, intval, inplace)\ PyObject_RichCompare(op1, op2, Py_EQ) #endif /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_AddObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceAdd(op1, op2) : PyNumber_Add(op1, op2)) #endif /* PyIntBinop.proto */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_SubtractObjC(PyObject *op1, PyObject *op2, long intval, int inplace); #else #define __Pyx_PyInt_SubtractObjC(op1, op2, intval, inplace)\ (inplace ? PyNumber_InPlaceSubtract(op1, op2) : PyNumber_Subtract(op1, op2)) #endif /* PyThreadStateGet.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyThreadState_declare PyThreadState *__pyx_tstate; #define __Pyx_PyThreadState_assign __pyx_tstate = __Pyx_PyThreadState_Current; #define __Pyx_PyErr_Occurred() __pyx_tstate->curexc_type #else #define __Pyx_PyThreadState_declare #define __Pyx_PyThreadState_assign #define __Pyx_PyErr_Occurred() PyErr_Occurred() #endif /* PyErrFetchRestore.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_Clear() __Pyx_ErrRestore(NULL, NULL, NULL) #define __Pyx_ErrRestoreWithState(type, value, tb) __Pyx_ErrRestoreInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) __Pyx_ErrFetchInState(PyThreadState_GET(), type, value, tb) #define __Pyx_ErrRestore(type, value, tb) __Pyx_ErrRestoreInState(__pyx_tstate, type, value, tb) #define __Pyx_ErrFetch(type, value, tb) __Pyx_ErrFetchInState(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_PyErr_SetNone(exc) (Py_INCREF(exc), __Pyx_ErrRestore((exc), NULL, NULL)) #else #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #endif #else #define __Pyx_PyErr_Clear() PyErr_Clear() #define __Pyx_PyErr_SetNone(exc) PyErr_SetNone(exc) #define __Pyx_ErrRestoreWithState(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchWithState(type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestoreInState(tstate, type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetchInState(tstate, type, value, tb) PyErr_Fetch(type, value, tb) #define __Pyx_ErrRestore(type, value, tb) PyErr_Restore(type, value, tb) #define __Pyx_ErrFetch(type, value, tb) PyErr_Fetch(type, value, tb) #endif /* WriteUnraisableException.proto */ static void __Pyx_WriteUnraisable(const char *name, int clineno, int lineno, const char *filename, int full_traceback, int nogil); /* None.proto */ static CYTHON_INLINE long __Pyx_mod_long(long, long); /* RaiseArgTupleInvalid.proto */ static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /* RaiseDoubleKeywords.proto */ static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /* ParseKeywords.proto */ static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[],\ PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args,\ const char* function_name); /* ArgTypeTest.proto */ #define __Pyx_ArgTypeTest(obj, type, none_allowed, name, exact)\ ((likely((Py_TYPE(obj) == type) | (none_allowed && (obj == Py_None)))) ? 1 :\ __Pyx__ArgTypeTest(obj, type, name, exact)) static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact); /* IsLittleEndian.proto */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void); /* BufferFormatCheck.proto */ static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts); static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type); /* BufferGetAndValidate.proto */ #define __Pyx_GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)\ ((obj == Py_None || obj == NULL) ?\ (__Pyx_ZeroBuffer(buf), 0) :\ __Pyx__GetBufferAndValidate(buf, obj, dtype, flags, nd, cast, stack)) static int __Pyx__GetBufferAndValidate(Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack); static void __Pyx_ZeroBuffer(Py_buffer* buf); static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info); static Py_ssize_t __Pyx_minusones[] = { -1, -1, -1, -1, -1, -1, -1, -1 }; static Py_ssize_t __Pyx_zeros[] = { 0, 0, 0, 0, 0, 0, 0, 0 }; /* PyObjectCall.proto */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); #else #define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw) #endif /* RaiseException.proto */ static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /* GetModuleGlobalName.proto */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /* PyFunctionFastCall.proto */ #if CYTHON_FAST_PYCALL #define __Pyx_PyFunction_FastCall(func, args, nargs)\ __Pyx_PyFunction_FastCallDict((func), (args), (nargs), NULL) #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs); #else #define __Pyx_PyFunction_FastCallDict(func, args, nargs, kwargs) _PyFunction_FastCallDict(func, args, nargs, kwargs) #endif #endif /* PyCFunctionFastCall.proto */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject *__Pyx_PyCFunction_FastCall(PyObject *func, PyObject **args, Py_ssize_t nargs); #else #define __Pyx_PyCFunction_FastCall(func, args, nargs) (assert(0), NULL) #endif /* ExtTypeTest.proto */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /* BufferFallbackError.proto */ static void __Pyx_RaiseBufferFallbackError(void); /* None.proto */ static CYTHON_INLINE npy_intp __Pyx_div_npy_intp(npy_intp, npy_intp); /* UnaryNegOverflows.proto */ #define UNARY_NEG_WOULD_OVERFLOW(x)\ (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x))) /* DictGetItem.proto */ #if PY_MAJOR_VERSION >= 3 && !CYTHON_COMPILING_IN_PYPY static PyObject *__Pyx_PyDict_GetItem(PyObject *d, PyObject* key) { PyObject *value; value = PyDict_GetItemWithError(d, key); if (unlikely(!value)) { if (!PyErr_Occurred()) { PyObject* args = PyTuple_Pack(1, key); if (likely(args)) PyErr_SetObject(PyExc_KeyError, args); Py_XDECREF(args); } return NULL; } Py_INCREF(value); return value; } #else #define __Pyx_PyDict_GetItem(d, key) PyObject_GetItem(d, key) #endif /* RaiseTooManyValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected); /* RaiseNeedMoreValuesToUnpack.proto */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index); /* RaiseNoneIterError.proto */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void); /* SaveResetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_ExceptionSave(type, value, tb) __Pyx__ExceptionSave(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #define __Pyx_ExceptionReset(type, value, tb) __Pyx__ExceptionReset(__pyx_tstate, type, value, tb) static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb); #else #define __Pyx_ExceptionSave(type, value, tb) PyErr_GetExcInfo(type, value, tb) #define __Pyx_ExceptionReset(type, value, tb) PyErr_SetExcInfo(type, value, tb) #endif /* PyErrExceptionMatches.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_PyErr_ExceptionMatches(err) __Pyx_PyErr_ExceptionMatchesInState(__pyx_tstate, err) static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err); #else #define __Pyx_PyErr_ExceptionMatches(err) PyErr_ExceptionMatches(err) #endif /* GetException.proto */ #if CYTHON_FAST_THREAD_STATE #define __Pyx_GetException(type, value, tb) __Pyx__GetException(__pyx_tstate, type, value, tb) static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb); #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); #endif /* Import.proto */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /* CLineInTraceback.proto */ #ifdef CYTHON_CLINE_IN_TRACEBACK #define __Pyx_CLineForTraceback(tstate, c_line) (((CYTHON_CLINE_IN_TRACEBACK)) ? c_line : 0) #else static int __Pyx_CLineForTraceback(PyThreadState *tstate, int c_line); #endif /* CodeObjectCache.proto */ typedef struct { PyCodeObject* code_object; int code_line; } __Pyx_CodeObjectCacheEntry; struct __Pyx_CodeObjectCache { int count; int max_count; __Pyx_CodeObjectCacheEntry* entries; }; static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL}; static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line); static PyCodeObject *__pyx_find_code_object(int code_line); static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object); /* AddTraceback.proto */ static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename); /* BufferStructDeclare.proto */ typedef struct { Py_ssize_t shape, strides, suboffsets; } __Pyx_Buf_DimInfo; typedef struct { size_t refcount; Py_buffer pybuffer; } __Pyx_Buffer; typedef struct { __Pyx_Buffer *rcbuffer; char *data; __Pyx_Buf_DimInfo diminfo[8]; } __Pyx_LocalBuf_ND; #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags); static void __Pyx_ReleaseBuffer(Py_buffer *view); #else #define __Pyx_GetBuffer PyObject_GetBuffer #define __Pyx_ReleaseBuffer PyBuffer_Release #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_uint8(npy_uint8 value); /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value); /* RealImag.proto */ #if CYTHON_CCOMPLEX #ifdef __cplusplus #define __Pyx_CREAL(z) ((z).real()) #define __Pyx_CIMAG(z) ((z).imag()) #else #define __Pyx_CREAL(z) (__real__(z)) #define __Pyx_CIMAG(z) (__imag__(z)) #endif #else #define __Pyx_CREAL(z) ((z).real) #define __Pyx_CIMAG(z) ((z).imag) #endif #if defined(__cplusplus) && CYTHON_CCOMPLEX\ && (defined(_WIN32) || defined(__clang__) || (defined(__GNUC__) && (__GNUC__ >= 5 || __GNUC__ == 4 && __GNUC_MINOR__ >= 4 )) || __cplusplus >= 201103) #define __Pyx_SET_CREAL(z,x) ((z).real(x)) #define __Pyx_SET_CIMAG(z,y) ((z).imag(y)) #else #define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x) #define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y) #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_float(a, b) ((a)==(b)) #define __Pyx_c_sum_float(a, b) ((a)+(b)) #define __Pyx_c_diff_float(a, b) ((a)-(b)) #define __Pyx_c_prod_float(a, b) ((a)*(b)) #define __Pyx_c_quot_float(a, b) ((a)/(b)) #define __Pyx_c_neg_float(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_float(z) ((z)==(float)0) #define __Pyx_c_conj_float(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_float(z) (::std::abs(z)) #define __Pyx_c_pow_float(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_float(z) ((z)==0) #define __Pyx_c_conj_float(z) (conjf(z)) #if 1 #define __Pyx_c_abs_float(z) (cabsf(z)) #define __Pyx_c_pow_float(a, b) (cpowf(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex, __pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex); static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex); #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex); static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex, __pyx_t_float_complex); #endif #endif /* Arithmetic.proto */ #if CYTHON_CCOMPLEX #define __Pyx_c_eq_double(a, b) ((a)==(b)) #define __Pyx_c_sum_double(a, b) ((a)+(b)) #define __Pyx_c_diff_double(a, b) ((a)-(b)) #define __Pyx_c_prod_double(a, b) ((a)*(b)) #define __Pyx_c_quot_double(a, b) ((a)/(b)) #define __Pyx_c_neg_double(a) (-(a)) #ifdef __cplusplus #define __Pyx_c_is_zero_double(z) ((z)==(double)0) #define __Pyx_c_conj_double(z) (::std::conj(z)) #if 1 #define __Pyx_c_abs_double(z) (::std::abs(z)) #define __Pyx_c_pow_double(a, b) (::std::pow(a, b)) #endif #else #define __Pyx_c_is_zero_double(z) ((z)==0) #define __Pyx_c_conj_double(z) (conj(z)) #if 1 #define __Pyx_c_abs_double(z) (cabs(z)) #define __Pyx_c_pow_double(a, b) (cpow(a, b)) #endif #endif #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex, __pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex); static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex); #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex); static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex, __pyx_t_double_complex); #endif #endif /* CIntToPy.proto */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value); /* CIntFromPy.proto */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *); /* CIntFromPy.proto */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *); /* FastTypeChecks.proto */ #if CYTHON_COMPILING_IN_CPYTHON #define __Pyx_TypeCheck(obj, type) __Pyx_IsSubtype(Py_TYPE(obj), (PyTypeObject *)type) static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject *type); static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *type1, PyObject *type2); #else #define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type) #define __Pyx_PyErr_GivenExceptionMatches(err, type) PyErr_GivenExceptionMatches(err, type) #define __Pyx_PyErr_GivenExceptionMatches2(err, type1, type2) (PyErr_GivenExceptionMatches(err, type1) || PyErr_GivenExceptionMatches(err, type2)) #endif /* CheckBinaryVersion.proto */ static int __Pyx_check_binary_version(void); /* PyIdentifierFromString.proto */ #if !defined(__Pyx_PyIdentifier_FromString) #if PY_MAJOR_VERSION < 3 #define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s) #else #define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s) #endif #endif /* ModuleImport.proto */ static PyObject *__Pyx_ImportModule(const char *name); /* TypeImport.proto */ static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /* InitStrings.proto */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /* Module declarations from 'cpython.buffer' */ /* Module declarations from 'libc.string' */ /* Module declarations from 'libc.stdio' */ /* Module declarations from '__builtin__' */ /* Module declarations from 'cpython.type' */ static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0; /* Module declarations from 'cpython' */ /* Module declarations from 'cpython.object' */ /* Module declarations from 'cpython.ref' */ /* Module declarations from 'cpython.mem' */ /* Module declarations from 'numpy' */ /* Module declarations from 'numpy' */ static PyTypeObject *__pyx_ptype_5numpy_dtype = 0; static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0; static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0; static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0; static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0; static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/ /* Module declarations from 'cython' */ /* Module declarations from 'centrosome._filter' */ static PyTypeObject *__pyx_ptype_10centrosome_7_filter_ndarray = 0; static struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_f_10centrosome_7_filter_allocate_histograms(__pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_uint8_t *, __pyx_t_5numpy_uint8_t *, __pyx_t_5numpy_uint8_t *); /*proto*/ static void __pyx_f_10centrosome_7_filter_free_histograms(struct __pyx_t_10centrosome_7_filter_Histograms *); /*proto*/ static void __pyx_f_10centrosome_7_filter_set_stride(struct __pyx_t_10centrosome_7_filter_Histograms *, struct __pyx_t_10centrosome_7_filter_SCoord *); /*proto*/ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_tl_br_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_tr_bl_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_leading_edge_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_trailing_edge_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_add16(__pyx_t_5numpy_uint16_t *, __pyx_t_5numpy_uint16_t *); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_sub16(__pyx_t_5numpy_uint16_t *, __pyx_t_5numpy_uint16_t *); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate_coarse_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_deaccumulate_coarse_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate_fine_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_uint32_t); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_deaccumulate_fine_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_uint32_t); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate(struct __pyx_t_10centrosome_7_filter_Histograms *); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_fine(struct __pyx_t_10centrosome_7_filter_Histograms *, int); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *, struct __pyx_t_10centrosome_7_filter_HistogramPiece *, __pyx_t_10centrosome_7_filter_pixel_count_t *, struct __pyx_t_10centrosome_7_filter_SCoord *, struct __pyx_t_10centrosome_7_filter_SCoord *); /*proto*/ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_current_location(struct __pyx_t_10centrosome_7_filter_Histograms *); /*proto*/ static CYTHON_INLINE __pyx_t_5numpy_uint8_t __pyx_f_10centrosome_7_filter_find_median(struct __pyx_t_10centrosome_7_filter_Histograms *); /*proto*/ static int __pyx_f_10centrosome_7_filter_c_median_filter(__pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_int32_t, __pyx_t_5numpy_uint8_t *, __pyx_t_5numpy_uint8_t *, __pyx_t_5numpy_uint8_t *); /*proto*/ static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t = { "uint8_t", NULL, sizeof(__pyx_t_5numpy_uint8_t), { 0 }, 0, IS_UNSIGNED(__pyx_t_5numpy_uint8_t) ? 'U' : 'I', IS_UNSIGNED(__pyx_t_5numpy_uint8_t), 0 }; static __Pyx_TypeInfo __Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t = { "float64_t", NULL, sizeof(__pyx_t_5numpy_float64_t), { 0 }, 0, 'R', 0, 0 }; #define __Pyx_MODULE_NAME "centrosome._filter" extern int __pyx_module_is_main_centrosome___filter; int __pyx_module_is_main_centrosome___filter = 0; /* Implementation of 'centrosome._filter' */ static PyObject *__pyx_builtin_range; static PyObject *__pyx_builtin_ValueError; static PyObject *__pyx_builtin_MemoryError; static PyObject *__pyx_builtin_RuntimeError; static PyObject *__pyx_builtin_ImportError; static const char __pyx_k_a[] = "a"; static const char __pyx_k_b[] = "b"; static const char __pyx_k_c[] = "c"; static const char __pyx_k_i[] = "i"; static const char __pyx_k_j[] = "j"; static const char __pyx_k_k[] = "k"; static const char __pyx_k_p[] = "p"; static const char __pyx_k_x[] = "x"; static const char __pyx_k_ik[] = "ik"; static const char __pyx_k_jk[] = "jk"; static const char __pyx_k_np[] = "np"; static const char __pyx_k_pa[] = "pa"; static const char __pyx_k_pb[] = "pb"; static const char __pyx_k_pc[] = "pc"; static const char __pyx_k_ptr[] = "ptr"; static const char __pyx_k_bool[] = "bool"; static const char __pyx_k_data[] = "data"; static const char __pyx_k_imax[] = "imax"; static const char __pyx_k_jmax[] = "jmax"; static const char __pyx_k_kmax[] = "kmax"; static const char __pyx_k_main[] = "__main__"; static const char __pyx_k_mask[] = "mask"; static const char __pyx_k_test[] = "__test__"; static const char __pyx_k_dtype[] = "dtype"; static const char __pyx_k_numpy[] = "numpy"; static const char __pyx_k_pmask[] = "pmask"; static const char __pyx_k_range[] = "range"; static const char __pyx_k_uint8[] = "uint8"; static const char __pyx_k_zeros[] = "zeros"; static const char __pyx_k_import[] = "__import__"; static const char __pyx_k_kernel[] = "kernel"; static const char __pyx_k_output[] = "output"; static const char __pyx_k_pimage[] = "pimage"; static const char __pyx_k_radius[] = "radius"; static const char __pyx_k_uint32[] = "uint32"; static const char __pyx_k_istride[] = "istride"; static const char __pyx_k_kstride[] = "kstride"; static const char __pyx_k_mstride[] = "mstride"; static const char __pyx_k_percent[] = "percent"; static const char __pyx_k_pkernel[] = "pkernel"; static const char __pyx_k_poutput[] = "poutput"; static const char __pyx_k_big_mask[] = "big_mask"; static const char __pyx_k_estimate[] = "estimate"; static const char __pyx_k_DTYPE_BOOL[] = "DTYPE_BOOL"; static const char __pyx_k_ValueError[] = "ValueError"; static const char __pyx_k_ImportError[] = "ImportError"; static const char __pyx_k_MemoryError[] = "MemoryError"; static const char __pyx_k_accumulator[] = "accumulator"; static const char __pyx_k_mask_offset[] = "mask_offset"; static const char __pyx_k_mask_stride[] = "mask_stride"; static const char __pyx_k_DTYPE_UINT32[] = "DTYPE_UINT32"; static const char __pyx_k_RuntimeError[] = "RuntimeError"; static const char __pyx_k_image_stride[] = "image_stride"; static const char __pyx_k_kernel_width[] = "kernel_width"; static const char __pyx_k_pixel_stride[] = "pixel_stride"; static const char __pyx_k_plane_number[] = "plane_number"; static const char __pyx_k_raster_count[] = "raster_count"; static const char __pyx_k_kernel_stride[] = "kernel_stride"; static const char __pyx_k_median_filter[] = "median_filter"; static const char __pyx_k_paeth_decoder[] = "paeth_decoder"; static const char __pyx_k_raster_number[] = "raster_number"; static const char __pyx_k_raster_stride[] = "raster_stride"; static const char __pyx_k_kernel_half_width[] = "kernel_half_width"; static const char __pyx_k_centrosome__filter[] = "centrosome._filter"; static const char __pyx_k_cline_in_traceback[] = "cline_in_traceback"; static const char __pyx_k_masked_convolution[] = "masked_convolution"; static const char __pyx_k_Kernel_must_be_square[] = "Kernel must be square"; static const char __pyx_k_centrosome__filter_pyx[] = "centrosome/_filter.pyx"; static const char __pyx_k_Kernel_shape_must_be_odd[] = "Kernel shape must be odd"; static const char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous"; static const char __pyx_k_Median_filter_percent_d_is_less[] = "Median filter percent = %d is less than zero"; static const char __pyx_k_numpy_core_multiarray_failed_to[] = "numpy.core.multiarray failed to import"; static const char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)"; static const char __pyx_k_Data_shape_d_d_is_not_mask_shape[] = "Data shape (%d,%d) is not mask shape (%d,%d)"; static const char __pyx_k_Data_shape_d_d_is_not_output_sha[] = "Data shape (%d,%d) is not output shape (%d,%d)"; static const char __pyx_k_Failed_to_allocate_scratchpad_me[] = "Failed to allocate scratchpad memory"; static const char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd"; static const char __pyx_k_Median_filter_percent_d_is_great[] = "Median filter percent = %d is greater than 100"; static const char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported"; static const char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous"; static const char __pyx_k_numpy_core_umath_failed_to_impor[] = "numpy.core.umath failed to import"; static const char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short."; static PyObject *__pyx_n_s_DTYPE_BOOL; static PyObject *__pyx_n_s_DTYPE_UINT32; static PyObject *__pyx_kp_s_Data_shape_d_d_is_not_mask_shape; static PyObject *__pyx_kp_s_Data_shape_d_d_is_not_output_sha; static PyObject *__pyx_kp_s_Failed_to_allocate_scratchpad_me; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor; static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2; static PyObject *__pyx_n_s_ImportError; static PyObject *__pyx_kp_s_Kernel_must_be_square; static PyObject *__pyx_kp_s_Kernel_shape_must_be_odd; static PyObject *__pyx_kp_s_Median_filter_percent_d_is_great; static PyObject *__pyx_kp_s_Median_filter_percent_d_is_less; static PyObject *__pyx_n_s_MemoryError; static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor; static PyObject *__pyx_n_s_RuntimeError; static PyObject *__pyx_n_s_ValueError; static PyObject *__pyx_n_s_a; static PyObject *__pyx_n_s_accumulator; static PyObject *__pyx_n_s_b; static PyObject *__pyx_n_s_big_mask; static PyObject *__pyx_n_s_bool; static PyObject *__pyx_n_s_c; static PyObject *__pyx_n_s_centrosome__filter; static PyObject *__pyx_kp_s_centrosome__filter_pyx; static PyObject *__pyx_n_s_cline_in_traceback; static PyObject *__pyx_n_s_data; static PyObject *__pyx_n_s_dtype; static PyObject *__pyx_n_s_estimate; static PyObject *__pyx_n_s_i; static PyObject *__pyx_n_s_ik; static PyObject *__pyx_n_s_image_stride; static PyObject *__pyx_n_s_imax; static PyObject *__pyx_n_s_import; static PyObject *__pyx_n_s_istride; static PyObject *__pyx_n_s_j; static PyObject *__pyx_n_s_jk; static PyObject *__pyx_n_s_jmax; static PyObject *__pyx_n_s_k; static PyObject *__pyx_n_s_kernel; static PyObject *__pyx_n_s_kernel_half_width; static PyObject *__pyx_n_s_kernel_stride; static PyObject *__pyx_n_s_kernel_width; static PyObject *__pyx_n_s_kmax; static PyObject *__pyx_n_s_kstride; static PyObject *__pyx_n_s_main; static PyObject *__pyx_n_s_mask; static PyObject *__pyx_n_s_mask_offset; static PyObject *__pyx_n_s_mask_stride; static PyObject *__pyx_n_s_masked_convolution; static PyObject *__pyx_n_s_median_filter; static PyObject *__pyx_n_s_mstride; static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous; static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou; static PyObject *__pyx_n_s_np; static PyObject *__pyx_n_s_numpy; static PyObject *__pyx_kp_s_numpy_core_multiarray_failed_to; static PyObject *__pyx_kp_s_numpy_core_umath_failed_to_impor; static PyObject *__pyx_n_s_output; static PyObject *__pyx_n_s_p; static PyObject *__pyx_n_s_pa; static PyObject *__pyx_n_s_paeth_decoder; static PyObject *__pyx_n_s_pb; static PyObject *__pyx_n_s_pc; static PyObject *__pyx_n_s_percent; static PyObject *__pyx_n_s_pimage; static PyObject *__pyx_n_s_pixel_stride; static PyObject *__pyx_n_s_pkernel; static PyObject *__pyx_n_s_plane_number; static PyObject *__pyx_n_s_pmask; static PyObject *__pyx_n_s_poutput; static PyObject *__pyx_n_s_ptr; static PyObject *__pyx_n_s_radius; static PyObject *__pyx_n_s_range; static PyObject *__pyx_n_s_raster_count; static PyObject *__pyx_n_s_raster_number; static PyObject *__pyx_n_s_raster_stride; static PyObject *__pyx_n_s_test; static PyObject *__pyx_n_s_uint32; static PyObject *__pyx_n_s_uint8; static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd; static PyObject *__pyx_n_s_x; static PyObject *__pyx_n_s_zeros; static PyObject *__pyx_pf_10centrosome_7_filter_median_filter(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_mask, PyArrayObject *__pyx_v_output, int __pyx_v_radius, __pyx_t_5numpy_int32_t __pyx_v_percent); /* proto */ static PyObject *__pyx_pf_10centrosome_7_filter_2masked_convolution(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_mask, PyArrayObject *__pyx_v_kernel); /* proto */ static PyObject *__pyx_pf_10centrosome_7_filter_4paeth_decoder(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_x, __pyx_t_5numpy_int32_t __pyx_v_raster_count); /* proto */ static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */ static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */ static PyObject *__pyx_int_0; static PyObject *__pyx_int_1; static PyObject *__pyx_tuple_; static PyObject *__pyx_tuple__2; static PyObject *__pyx_tuple__3; static PyObject *__pyx_tuple__4; static PyObject *__pyx_tuple__5; static PyObject *__pyx_tuple__6; static PyObject *__pyx_tuple__7; static PyObject *__pyx_tuple__8; static PyObject *__pyx_tuple__9; static PyObject *__pyx_tuple__10; static PyObject *__pyx_tuple__11; static PyObject *__pyx_tuple__13; static PyObject *__pyx_tuple__15; static PyObject *__pyx_codeobj__12; static PyObject *__pyx_codeobj__14; static PyObject *__pyx_codeobj__16; /* "centrosome/_filter.pyx":166 * # * ############################################################################ * cdef Histograms *allocate_histograms(np.int32_t rows, # <<<<<<<<<<<<<< * np.int32_t columns, * np.int32_t row_stride, */ static struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_f_10centrosome_7_filter_allocate_histograms(__pyx_t_5numpy_int32_t __pyx_v_rows, __pyx_t_5numpy_int32_t __pyx_v_columns, __pyx_t_5numpy_int32_t __pyx_v_row_stride, __pyx_t_5numpy_int32_t __pyx_v_col_stride, __pyx_t_5numpy_int32_t __pyx_v_radius, __pyx_t_5numpy_int32_t __pyx_v_percent, __pyx_t_5numpy_uint8_t *__pyx_v_data, __pyx_t_5numpy_uint8_t *__pyx_v_mask, __pyx_t_5numpy_uint8_t *__pyx_v_output) { unsigned int __pyx_v_adjusted_stripe_length; unsigned int __pyx_v_memory_size; void *__pyx_v_ptr; struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph; size_t __pyx_v_roundoff; int __pyx_v_a; PyObject *__pyx_v_a_2 = NULL; struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; __pyx_t_5numpy_int32_t __pyx_t_3; PyObject *__pyx_t_4 = NULL; __Pyx_RefNannySetupContext("allocate_histograms", 0); /* "centrosome/_filter.pyx":176 * np.uint8_t * output): * cdef: * unsigned int adjusted_stripe_length = columns + 2*radius + 1 # <<<<<<<<<<<<<< * unsigned int memory_size * void *ptr */ __pyx_v_adjusted_stripe_length = ((__pyx_v_columns + (2 * __pyx_v_radius)) + 1); /* "centrosome/_filter.pyx":186 * memory_size = (adjusted_stripe_length * * (sizeof(Histogram) + sizeof(PixelCount))+ * sizeof(Histograms)+32) # <<<<<<<<<<<<<< * ptr = malloc(memory_size) * memset(ptr, 0, memory_size) */ __pyx_v_memory_size = (((__pyx_v_adjusted_stripe_length * ((sizeof(struct __pyx_t_10centrosome_7_filter_Histogram)) + (sizeof(struct __pyx_t_10centrosome_7_filter_PixelCount)))) + (sizeof(struct __pyx_t_10centrosome_7_filter_Histograms))) + 32); /* "centrosome/_filter.pyx":187 * (sizeof(Histogram) + sizeof(PixelCount))+ * sizeof(Histograms)+32) * ptr = malloc(memory_size) # <<<<<<<<<<<<<< * memset(ptr, 0, memory_size) * ph = <Histograms *>ptr */ __pyx_v_ptr = malloc(__pyx_v_memory_size); /* "centrosome/_filter.pyx":188 * sizeof(Histograms)+32) * ptr = malloc(memory_size) * memset(ptr, 0, memory_size) # <<<<<<<<<<<<<< * ph = <Histograms *>ptr * if not ptr: */ memset(__pyx_v_ptr, 0, __pyx_v_memory_size); /* "centrosome/_filter.pyx":189 * ptr = malloc(memory_size) * memset(ptr, 0, memory_size) * ph = <Histograms *>ptr # <<<<<<<<<<<<<< * if not ptr: * return ph */ __pyx_v_ph = ((struct __pyx_t_10centrosome_7_filter_Histograms *)__pyx_v_ptr); /* "centrosome/_filter.pyx":190 * memset(ptr, 0, memory_size) * ph = <Histograms *>ptr * if not ptr: # <<<<<<<<<<<<<< * return ph * ph.memory = ptr */ __pyx_t_1 = ((!(__pyx_v_ptr != 0)) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":191 * ph = <Histograms *>ptr * if not ptr: * return ph # <<<<<<<<<<<<<< * ph.memory = ptr * ptr = <void *>(ph+1) */ __pyx_r = __pyx_v_ph; goto __pyx_L0; /* "centrosome/_filter.pyx":190 * memset(ptr, 0, memory_size) * ph = <Histograms *>ptr * if not ptr: # <<<<<<<<<<<<<< * return ph * ph.memory = ptr */ } /* "centrosome/_filter.pyx":192 * if not ptr: * return ph * ph.memory = ptr # <<<<<<<<<<<<<< * ptr = <void *>(ph+1) * ph.pixel_count = <PixelCount *>ptr */ __pyx_v_ph->memory = __pyx_v_ptr; /* "centrosome/_filter.pyx":193 * return ph * ph.memory = ptr * ptr = <void *>(ph+1) # <<<<<<<<<<<<<< * ph.pixel_count = <PixelCount *>ptr * ptr = <void *>(ph.pixel_count + adjusted_stripe_length) */ __pyx_v_ptr = ((void *)(__pyx_v_ph + 1)); /* "centrosome/_filter.pyx":194 * ph.memory = ptr * ptr = <void *>(ph+1) * ph.pixel_count = <PixelCount *>ptr # <<<<<<<<<<<<<< * ptr = <void *>(ph.pixel_count + adjusted_stripe_length) * # */ __pyx_v_ph->pixel_count = ((struct __pyx_t_10centrosome_7_filter_PixelCount *)__pyx_v_ptr); /* "centrosome/_filter.pyx":195 * ptr = <void *>(ph+1) * ph.pixel_count = <PixelCount *>ptr * ptr = <void *>(ph.pixel_count + adjusted_stripe_length) # <<<<<<<<<<<<<< * # * # Align histogram memory to a 32-byte boundary */ __pyx_v_ptr = ((void *)(__pyx_v_ph->pixel_count + __pyx_v_adjusted_stripe_length)); /* "centrosome/_filter.pyx":199 * # Align histogram memory to a 32-byte boundary * # * roundoff = <size_t>ptr # <<<<<<<<<<<<<< * roundoff += 31 * roundoff -= roundoff % 32 */ __pyx_v_roundoff = ((size_t)__pyx_v_ptr); /* "centrosome/_filter.pyx":200 * # * roundoff = <size_t>ptr * roundoff += 31 # <<<<<<<<<<<<<< * roundoff -= roundoff % 32 * ptr = <void *>roundoff */ __pyx_v_roundoff = (__pyx_v_roundoff + 31); /* "centrosome/_filter.pyx":201 * roundoff = <size_t>ptr * roundoff += 31 * roundoff -= roundoff % 32 # <<<<<<<<<<<<<< * ptr = <void *>roundoff * ph.histogram = <Histogram *>ptr */ __pyx_v_roundoff = (__pyx_v_roundoff - (__pyx_v_roundoff % 32)); /* "centrosome/_filter.pyx":202 * roundoff += 31 * roundoff -= roundoff % 32 * ptr = <void *>roundoff # <<<<<<<<<<<<<< * ph.histogram = <Histogram *>ptr * # */ __pyx_v_ptr = ((void *)__pyx_v_roundoff); /* "centrosome/_filter.pyx":203 * roundoff -= roundoff % 32 * ptr = <void *>roundoff * ph.histogram = <Histogram *>ptr # <<<<<<<<<<<<<< * # * # Fill in the statistical things we keep around */ __pyx_v_ph->histogram = ((struct __pyx_t_10centrosome_7_filter_Histogram *)__pyx_v_ptr); /* "centrosome/_filter.pyx":207 * # Fill in the statistical things we keep around * # * ph.column_count = columns # <<<<<<<<<<<<<< * ph.row_count = rows * ph.current_column = -radius */ __pyx_v_ph->column_count = __pyx_v_columns; /* "centrosome/_filter.pyx":208 * # * ph.column_count = columns * ph.row_count = rows # <<<<<<<<<<<<<< * ph.current_column = -radius * ph.stripe_length = adjusted_stripe_length */ __pyx_v_ph->row_count = __pyx_v_rows; /* "centrosome/_filter.pyx":209 * ph.column_count = columns * ph.row_count = rows * ph.current_column = -radius # <<<<<<<<<<<<<< * ph.stripe_length = adjusted_stripe_length * ph.current_row = 0 */ __pyx_v_ph->current_column = (-__pyx_v_radius); /* "centrosome/_filter.pyx":210 * ph.row_count = rows * ph.current_column = -radius * ph.stripe_length = adjusted_stripe_length # <<<<<<<<<<<<<< * ph.current_row = 0 * ph.radius = radius */ __pyx_v_ph->stripe_length = __pyx_v_adjusted_stripe_length; /* "centrosome/_filter.pyx":211 * ph.current_column = -radius * ph.stripe_length = adjusted_stripe_length * ph.current_row = 0 # <<<<<<<<<<<<<< * ph.radius = radius * ph.percent = percent */ __pyx_v_ph->current_row = 0; /* "centrosome/_filter.pyx":212 * ph.stripe_length = adjusted_stripe_length * ph.current_row = 0 * ph.radius = radius # <<<<<<<<<<<<<< * ph.percent = percent * ph.row_stride = row_stride */ __pyx_v_ph->radius = __pyx_v_radius; /* "centrosome/_filter.pyx":213 * ph.current_row = 0 * ph.radius = radius * ph.percent = percent # <<<<<<<<<<<<<< * ph.row_stride = row_stride * ph.col_stride = col_stride */ __pyx_v_ph->percent = __pyx_v_percent; /* "centrosome/_filter.pyx":214 * ph.radius = radius * ph.percent = percent * ph.row_stride = row_stride # <<<<<<<<<<<<<< * ph.col_stride = col_stride * ph.data = data */ __pyx_v_ph->row_stride = __pyx_v_row_stride; /* "centrosome/_filter.pyx":215 * ph.percent = percent * ph.row_stride = row_stride * ph.col_stride = col_stride # <<<<<<<<<<<<<< * ph.data = data * ph.mask = mask */ __pyx_v_ph->col_stride = __pyx_v_col_stride; /* "centrosome/_filter.pyx":216 * ph.row_stride = row_stride * ph.col_stride = col_stride * ph.data = data # <<<<<<<<<<<<<< * ph.mask = mask * ph.output = output */ __pyx_v_ph->data = __pyx_v_data; /* "centrosome/_filter.pyx":217 * ph.col_stride = col_stride * ph.data = data * ph.mask = mask # <<<<<<<<<<<<<< * ph.output = output * # */ __pyx_v_ph->mask = __pyx_v_mask; /* "centrosome/_filter.pyx":218 * ph.data = data * ph.mask = mask * ph.output = output # <<<<<<<<<<<<<< * # * # Compute the coordinates of the significant points */ __pyx_v_ph->output = __pyx_v_output; /* "centrosome/_filter.pyx":232 * # corners * # * a = <int>(<np.float64_t>radius * 2.0 / 2.414213) # <<<<<<<<<<<<<< * a_2 = a / 2 * if a_2 == 0: */ __pyx_v_a = ((int)((((__pyx_t_5numpy_float64_t)__pyx_v_radius) * 2.0) / 2.414213)); /* "centrosome/_filter.pyx":233 * # * a = <int>(<np.float64_t>radius * 2.0 / 2.414213) * a_2 = a / 2 # <<<<<<<<<<<<<< * if a_2 == 0: * a_2 = 1 */ __pyx_t_2 = __Pyx_PyInt_From_long(__Pyx_div_long(__pyx_v_a, 2)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 233, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_v_a_2 = __pyx_t_2; __pyx_t_2 = 0; /* "centrosome/_filter.pyx":234 * a = <int>(<np.float64_t>radius * 2.0 / 2.414213) * a_2 = a / 2 * if a_2 == 0: # <<<<<<<<<<<<<< * a_2 = 1 * ph.a_2 = a_2 */ __pyx_t_2 = __Pyx_PyInt_EqObjC(__pyx_v_a_2, __pyx_int_0, 0, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 234, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_2); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 234, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (__pyx_t_1) { /* "centrosome/_filter.pyx":235 * a_2 = a / 2 * if a_2 == 0: * a_2 = 1 # <<<<<<<<<<<<<< * ph.a_2 = a_2 * if radius <= a_2: */ __Pyx_INCREF(__pyx_int_1); __Pyx_DECREF_SET(__pyx_v_a_2, __pyx_int_1); /* "centrosome/_filter.pyx":234 * a = <int>(<np.float64_t>radius * 2.0 / 2.414213) * a_2 = a / 2 * if a_2 == 0: # <<<<<<<<<<<<<< * a_2 = 1 * ph.a_2 = a_2 */ } /* "centrosome/_filter.pyx":236 * if a_2 == 0: * a_2 = 1 * ph.a_2 = a_2 # <<<<<<<<<<<<<< * if radius <= a_2: * radius = a_2+1 */ __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_v_a_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 236, __pyx_L1_error) __pyx_v_ph->a_2 = __pyx_t_3; /* "centrosome/_filter.pyx":237 * a_2 = 1 * ph.a_2 = a_2 * if radius <= a_2: # <<<<<<<<<<<<<< * radius = a_2+1 * ph.radius = radius */ __pyx_t_2 = __Pyx_PyInt_From_npy_int32(__pyx_v_radius); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 237, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = PyObject_RichCompare(__pyx_t_2, __pyx_v_a_2, Py_LE); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 237, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_1 < 0)) __PYX_ERR(0, 237, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_1) { /* "centrosome/_filter.pyx":238 * ph.a_2 = a_2 * if radius <= a_2: * radius = a_2+1 # <<<<<<<<<<<<<< * ph.radius = radius * */ __pyx_t_4 = __Pyx_PyInt_AddObjC(__pyx_v_a_2, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_4); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 238, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_radius = __pyx_t_3; /* "centrosome/_filter.pyx":239 * if radius <= a_2: * radius = a_2+1 * ph.radius = radius # <<<<<<<<<<<<<< * * ph.last_top_left.x = -a_2 */ __pyx_v_ph->radius = __pyx_v_radius; /* "centrosome/_filter.pyx":237 * a_2 = 1 * ph.a_2 = a_2 * if radius <= a_2: # <<<<<<<<<<<<<< * radius = a_2+1 * ph.radius = radius */ } /* "centrosome/_filter.pyx":241 * ph.radius = radius * * ph.last_top_left.x = -a_2 # <<<<<<<<<<<<<< * ph.last_top_left.y = -radius - 1 * */ __pyx_t_4 = PyNumber_Negative(__pyx_v_a_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 241, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_4); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 241, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_ph->last_top_left.x = __pyx_t_3; /* "centrosome/_filter.pyx":242 * * ph.last_top_left.x = -a_2 * ph.last_top_left.y = -radius - 1 # <<<<<<<<<<<<<< * * ph.top_left.x = -radius */ __pyx_v_ph->last_top_left.y = ((-__pyx_v_radius) - 1); /* "centrosome/_filter.pyx":244 * ph.last_top_left.y = -radius - 1 * * ph.top_left.x = -radius # <<<<<<<<<<<<<< * ph.top_left.y = -a_2 - 1 * */ __pyx_v_ph->top_left.x = (-__pyx_v_radius); /* "centrosome/_filter.pyx":245 * * ph.top_left.x = -radius * ph.top_left.y = -a_2 - 1 # <<<<<<<<<<<<<< * * ph.last_top_right.x = a_2 - 1 */ __pyx_t_4 = PyNumber_Negative(__pyx_v_a_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 245, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_2 = __Pyx_PyInt_SubtractObjC(__pyx_t_4, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 245, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 245, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_ph->top_left.y = __pyx_t_3; /* "centrosome/_filter.pyx":247 * ph.top_left.y = -a_2 - 1 * * ph.last_top_right.x = a_2 - 1 # <<<<<<<<<<<<<< * ph.last_top_right.y = -radius - 1 * */ __pyx_t_2 = __Pyx_PyInt_SubtractObjC(__pyx_v_a_2, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 247, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 247, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_ph->last_top_right.x = __pyx_t_3; /* "centrosome/_filter.pyx":248 * * ph.last_top_right.x = a_2 - 1 * ph.last_top_right.y = -radius - 1 # <<<<<<<<<<<<<< * * ph.top_right.x = radius - 1 */ __pyx_v_ph->last_top_right.y = ((-__pyx_v_radius) - 1); /* "centrosome/_filter.pyx":250 * ph.last_top_right.y = -radius - 1 * * ph.top_right.x = radius - 1 # <<<<<<<<<<<<<< * ph.top_right.y = -a_2 - 1 * */ __pyx_v_ph->top_right.x = (__pyx_v_radius - 1); /* "centrosome/_filter.pyx":251 * * ph.top_right.x = radius - 1 * ph.top_right.y = -a_2 - 1 # <<<<<<<<<<<<<< * * ph.last_leading_edge.x = radius */ __pyx_t_2 = PyNumber_Negative(__pyx_v_a_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_SubtractObjC(__pyx_t_2, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_4); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 251, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_ph->top_right.y = __pyx_t_3; /* "centrosome/_filter.pyx":253 * ph.top_right.y = -a_2 - 1 * * ph.last_leading_edge.x = radius # <<<<<<<<<<<<<< * ph.last_leading_edge.y = -a_2 - 1 * */ __pyx_v_ph->last_leading_edge.x = __pyx_v_radius; /* "centrosome/_filter.pyx":254 * * ph.last_leading_edge.x = radius * ph.last_leading_edge.y = -a_2 - 1 # <<<<<<<<<<<<<< * * ph.leading_edge.x = radius */ __pyx_t_4 = PyNumber_Negative(__pyx_v_a_2); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_2 = __Pyx_PyInt_SubtractObjC(__pyx_t_4, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 254, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 254, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_v_ph->last_leading_edge.y = __pyx_t_3; /* "centrosome/_filter.pyx":256 * ph.last_leading_edge.y = -a_2 - 1 * * ph.leading_edge.x = radius # <<<<<<<<<<<<<< * ph.leading_edge.y = a_2 * */ __pyx_v_ph->leading_edge.x = __pyx_v_radius; /* "centrosome/_filter.pyx":257 * * ph.leading_edge.x = radius * ph.leading_edge.y = a_2 # <<<<<<<<<<<<<< * * ph.last_bottom_right.x = radius */ __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_v_a_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 257, __pyx_L1_error) __pyx_v_ph->leading_edge.y = __pyx_t_3; /* "centrosome/_filter.pyx":259 * ph.leading_edge.y = a_2 * * ph.last_bottom_right.x = radius # <<<<<<<<<<<<<< * ph.last_bottom_right.y = a_2 * */ __pyx_v_ph->last_bottom_right.x = __pyx_v_radius; /* "centrosome/_filter.pyx":260 * * ph.last_bottom_right.x = radius * ph.last_bottom_right.y = a_2 # <<<<<<<<<<<<<< * * ph.bottom_right.x = a_2 */ __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_v_a_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 260, __pyx_L1_error) __pyx_v_ph->last_bottom_right.y = __pyx_t_3; /* "centrosome/_filter.pyx":262 * ph.last_bottom_right.y = a_2 * * ph.bottom_right.x = a_2 # <<<<<<<<<<<<<< * ph.bottom_right.y = radius * */ __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_v_a_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 262, __pyx_L1_error) __pyx_v_ph->bottom_right.x = __pyx_t_3; /* "centrosome/_filter.pyx":263 * * ph.bottom_right.x = a_2 * ph.bottom_right.y = radius # <<<<<<<<<<<<<< * * ph.last_bottom_left.x = -radius-1 */ __pyx_v_ph->bottom_right.y = __pyx_v_radius; /* "centrosome/_filter.pyx":265 * ph.bottom_right.y = radius * * ph.last_bottom_left.x = -radius-1 # <<<<<<<<<<<<<< * ph.last_bottom_left.y = a_2 * */ __pyx_v_ph->last_bottom_left.x = ((-__pyx_v_radius) - 1); /* "centrosome/_filter.pyx":266 * * ph.last_bottom_left.x = -radius-1 * ph.last_bottom_left.y = a_2 # <<<<<<<<<<<<<< * * ph.bottom_left.x = -a_2-1 */ __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_v_a_2); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 266, __pyx_L1_error) __pyx_v_ph->last_bottom_left.y = __pyx_t_3; /* "centrosome/_filter.pyx":268 * ph.last_bottom_left.y = a_2 * * ph.bottom_left.x = -a_2-1 # <<<<<<<<<<<<<< * ph.bottom_left.y = radius * */ __pyx_t_2 = PyNumber_Negative(__pyx_v_a_2); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 268, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_SubtractObjC(__pyx_t_2, __pyx_int_1, 1, 0); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 268, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_3 = __Pyx_PyInt_As_npy_int32(__pyx_t_4); if (unlikely((__pyx_t_3 == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 268, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_v_ph->bottom_left.x = __pyx_t_3; /* "centrosome/_filter.pyx":269 * * ph.bottom_left.x = -a_2-1 * ph.bottom_left.y = radius # <<<<<<<<<<<<<< * * # */ __pyx_v_ph->bottom_left.y = __pyx_v_radius; /* "centrosome/_filter.pyx":274 * # Set the stride of each SCoord based on its x and y * # * set_stride(ph, &ph.last_top_left) # <<<<<<<<<<<<<< * set_stride(ph, &ph.top_left) * set_stride(ph, &ph.last_top_right) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->last_top_left)); /* "centrosome/_filter.pyx":275 * # * set_stride(ph, &ph.last_top_left) * set_stride(ph, &ph.top_left) # <<<<<<<<<<<<<< * set_stride(ph, &ph.last_top_right) * set_stride(ph, &ph.top_right) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->top_left)); /* "centrosome/_filter.pyx":276 * set_stride(ph, &ph.last_top_left) * set_stride(ph, &ph.top_left) * set_stride(ph, &ph.last_top_right) # <<<<<<<<<<<<<< * set_stride(ph, &ph.top_right) * set_stride(ph, &ph.last_leading_edge) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->last_top_right)); /* "centrosome/_filter.pyx":277 * set_stride(ph, &ph.top_left) * set_stride(ph, &ph.last_top_right) * set_stride(ph, &ph.top_right) # <<<<<<<<<<<<<< * set_stride(ph, &ph.last_leading_edge) * set_stride(ph, &ph.leading_edge) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->top_right)); /* "centrosome/_filter.pyx":278 * set_stride(ph, &ph.last_top_right) * set_stride(ph, &ph.top_right) * set_stride(ph, &ph.last_leading_edge) # <<<<<<<<<<<<<< * set_stride(ph, &ph.leading_edge) * set_stride(ph, &ph.last_bottom_left) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->last_leading_edge)); /* "centrosome/_filter.pyx":279 * set_stride(ph, &ph.top_right) * set_stride(ph, &ph.last_leading_edge) * set_stride(ph, &ph.leading_edge) # <<<<<<<<<<<<<< * set_stride(ph, &ph.last_bottom_left) * set_stride(ph, &ph.bottom_left) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->leading_edge)); /* "centrosome/_filter.pyx":280 * set_stride(ph, &ph.last_leading_edge) * set_stride(ph, &ph.leading_edge) * set_stride(ph, &ph.last_bottom_left) # <<<<<<<<<<<<<< * set_stride(ph, &ph.bottom_left) * set_stride(ph, &ph.last_bottom_right) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->last_bottom_left)); /* "centrosome/_filter.pyx":281 * set_stride(ph, &ph.leading_edge) * set_stride(ph, &ph.last_bottom_left) * set_stride(ph, &ph.bottom_left) # <<<<<<<<<<<<<< * set_stride(ph, &ph.last_bottom_right) * set_stride(ph, &ph.bottom_right) */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->bottom_left)); /* "centrosome/_filter.pyx":282 * set_stride(ph, &ph.last_bottom_left) * set_stride(ph, &ph.bottom_left) * set_stride(ph, &ph.last_bottom_right) # <<<<<<<<<<<<<< * set_stride(ph, &ph.bottom_right) * */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->last_bottom_right)); /* "centrosome/_filter.pyx":283 * set_stride(ph, &ph.bottom_left) * set_stride(ph, &ph.last_bottom_right) * set_stride(ph, &ph.bottom_right) # <<<<<<<<<<<<<< * * return ph */ __pyx_f_10centrosome_7_filter_set_stride(__pyx_v_ph, (&__pyx_v_ph->bottom_right)); /* "centrosome/_filter.pyx":285 * set_stride(ph, &ph.bottom_right) * * return ph # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_r = __pyx_v_ph; goto __pyx_L0; /* "centrosome/_filter.pyx":166 * # * ############################################################################ * cdef Histograms *allocate_histograms(np.int32_t rows, # <<<<<<<<<<<<<< * np.int32_t columns, * np.int32_t row_stride, */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_4); __Pyx_WriteUnraisable("centrosome._filter.allocate_histograms", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_XDECREF(__pyx_v_a_2); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":292 * # * ############################################################################ * cdef void free_histograms(Histograms *ph): # <<<<<<<<<<<<<< * free(ph.memory) * */ static void __pyx_f_10centrosome_7_filter_free_histograms(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("free_histograms", 0); /* "centrosome/_filter.pyx":293 * ############################################################################ * cdef void free_histograms(Histograms *ph): * free(ph.memory) # <<<<<<<<<<<<<< * * ############################################################################ */ free(__pyx_v_ph->memory); /* "centrosome/_filter.pyx":292 * # * ############################################################################ * cdef void free_histograms(Histograms *ph): # <<<<<<<<<<<<<< * free(ph.memory) * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":301 * ############################################################################ * * cdef void set_stride(Histograms *ph, SCoord *psc): # <<<<<<<<<<<<<< * psc.stride = psc.x * ph.col_stride + psc.y * ph.row_stride * */ static void __pyx_f_10centrosome_7_filter_set_stride(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, struct __pyx_t_10centrosome_7_filter_SCoord *__pyx_v_psc) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("set_stride", 0); /* "centrosome/_filter.pyx":302 * * cdef void set_stride(Histograms *ph, SCoord *psc): * psc.stride = psc.x * ph.col_stride + psc.y * ph.row_stride # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_v_psc->stride = ((__pyx_v_psc->x * __pyx_v_ph->col_stride) + (__pyx_v_psc->y * __pyx_v_ph->row_stride)); /* "centrosome/_filter.pyx":301 * ############################################################################ * * cdef void set_stride(Histograms *ph, SCoord *psc): # <<<<<<<<<<<<<< * psc.stride = psc.x * ph.col_stride + psc.y * ph.row_stride * */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":326 * # * ############################################################################ * cdef inline np.int32_t tl_br_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius + ph.current_row)%ph.stripe_length * */ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_tl_br_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations long __pyx_t_1; __Pyx_RefNannySetupContext("tl_br_colidx", 0); /* "centrosome/_filter.pyx":327 * ############################################################################ * cdef inline np.int32_t tl_br_colidx(Histograms *ph, np.int32_t colidx): * return (colidx + 3*ph.radius + ph.current_row)%ph.stripe_length # <<<<<<<<<<<<<< * * cdef inline np.int32_t tr_bl_colidx(Histograms *ph, np.int32_t colidx): */ __pyx_t_1 = ((__pyx_v_colidx + (3 * __pyx_v_ph->radius)) + __pyx_v_ph->current_row); if (unlikely(__pyx_v_ph->stripe_length == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 327, __pyx_L1_error) } __pyx_r = __Pyx_mod_long(__pyx_t_1, __pyx_v_ph->stripe_length); goto __pyx_L0; /* "centrosome/_filter.pyx":326 * # * ############################################################################ * cdef inline np.int32_t tl_br_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius + ph.current_row)%ph.stripe_length * */ /* function exit code */ __pyx_L1_error:; __Pyx_WriteUnraisable("centrosome._filter.tl_br_colidx", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":329 * return (colidx + 3*ph.radius + ph.current_row)%ph.stripe_length * * cdef inline np.int32_t tr_bl_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius + ph.row_count-ph.current_row) % ph.stripe_length * */ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_tr_bl_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations long __pyx_t_1; __Pyx_RefNannySetupContext("tr_bl_colidx", 0); /* "centrosome/_filter.pyx":330 * * cdef inline np.int32_t tr_bl_colidx(Histograms *ph, np.int32_t colidx): * return (colidx + 3*ph.radius + ph.row_count-ph.current_row) % ph.stripe_length # <<<<<<<<<<<<<< * * cdef inline np.int32_t leading_edge_colidx(Histograms *ph, np.int32_t colidx): */ __pyx_t_1 = (((__pyx_v_colidx + (3 * __pyx_v_ph->radius)) + __pyx_v_ph->row_count) - __pyx_v_ph->current_row); if (unlikely(__pyx_v_ph->stripe_length == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 330, __pyx_L1_error) } __pyx_r = __Pyx_mod_long(__pyx_t_1, __pyx_v_ph->stripe_length); goto __pyx_L0; /* "centrosome/_filter.pyx":329 * return (colidx + 3*ph.radius + ph.current_row)%ph.stripe_length * * cdef inline np.int32_t tr_bl_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius + ph.row_count-ph.current_row) % ph.stripe_length * */ /* function exit code */ __pyx_L1_error:; __Pyx_WriteUnraisable("centrosome._filter.tr_bl_colidx", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":332 * return (colidx + 3*ph.radius + ph.row_count-ph.current_row) % ph.stripe_length * * cdef inline np.int32_t leading_edge_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 5*ph.radius) % ph.stripe_length * */ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_leading_edge_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations long __pyx_t_1; __Pyx_RefNannySetupContext("leading_edge_colidx", 0); /* "centrosome/_filter.pyx":333 * * cdef inline np.int32_t leading_edge_colidx(Histograms *ph, np.int32_t colidx): * return (colidx + 5*ph.radius) % ph.stripe_length # <<<<<<<<<<<<<< * * cdef inline np.int32_t trailing_edge_colidx(Histograms *ph, np.int32_t colidx): */ __pyx_t_1 = (__pyx_v_colidx + (5 * __pyx_v_ph->radius)); if (unlikely(__pyx_v_ph->stripe_length == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 333, __pyx_L1_error) } __pyx_r = __Pyx_mod_long(__pyx_t_1, __pyx_v_ph->stripe_length); goto __pyx_L0; /* "centrosome/_filter.pyx":332 * return (colidx + 3*ph.radius + ph.row_count-ph.current_row) % ph.stripe_length * * cdef inline np.int32_t leading_edge_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 5*ph.radius) % ph.stripe_length * */ /* function exit code */ __pyx_L1_error:; __Pyx_WriteUnraisable("centrosome._filter.leading_edge_colidx", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":335 * return (colidx + 5*ph.radius) % ph.stripe_length * * cdef inline np.int32_t trailing_edge_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius - 1) % ph.stripe_length * # */ static CYTHON_INLINE __pyx_t_5numpy_int32_t __pyx_f_10centrosome_7_filter_trailing_edge_colidx(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { __pyx_t_5numpy_int32_t __pyx_r; __Pyx_RefNannyDeclarations long __pyx_t_1; __Pyx_RefNannySetupContext("trailing_edge_colidx", 0); /* "centrosome/_filter.pyx":336 * * cdef inline np.int32_t trailing_edge_colidx(Histograms *ph, np.int32_t colidx): * return (colidx + 3*ph.radius - 1) % ph.stripe_length # <<<<<<<<<<<<<< * # * # add16 - add 16 consecutive integers */ __pyx_t_1 = ((__pyx_v_colidx + (3 * __pyx_v_ph->radius)) - 1); if (unlikely(__pyx_v_ph->stripe_length == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 336, __pyx_L1_error) } __pyx_r = __Pyx_mod_long(__pyx_t_1, __pyx_v_ph->stripe_length); goto __pyx_L0; /* "centrosome/_filter.pyx":335 * return (colidx + 5*ph.radius) % ph.stripe_length * * cdef inline np.int32_t trailing_edge_colidx(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * return (colidx + 3*ph.radius - 1) % ph.stripe_length * # */ /* function exit code */ __pyx_L1_error:; __Pyx_WriteUnraisable("centrosome._filter.trailing_edge_colidx", __pyx_clineno, __pyx_lineno, __pyx_filename, 1, 0); __pyx_r = 0; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":344 * # TO_DO - optimize using SIMD instructions * # * cdef inline void add16(np.uint16_t *dest, np.uint16_t *src): # <<<<<<<<<<<<<< * cdef int i * for i in range(16): */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_add16(__pyx_t_5numpy_uint16_t *__pyx_v_dest, __pyx_t_5numpy_uint16_t *__pyx_v_src) { int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("add16", 0); /* "centrosome/_filter.pyx":346 * cdef inline void add16(np.uint16_t *dest, np.uint16_t *src): * cdef int i * for i in range(16): # <<<<<<<<<<<<<< * dest[i] += src[i] * */ for (__pyx_t_1 = 0; __pyx_t_1 < 16; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "centrosome/_filter.pyx":347 * cdef int i * for i in range(16): * dest[i] += src[i] # <<<<<<<<<<<<<< * * cdef inline void sub16(np.uint16_t *dest, np.uint16_t *src): */ __pyx_t_2 = __pyx_v_i; (__pyx_v_dest[__pyx_t_2]) = ((__pyx_v_dest[__pyx_t_2]) + (__pyx_v_src[__pyx_v_i])); } /* "centrosome/_filter.pyx":344 * # TO_DO - optimize using SIMD instructions * # * cdef inline void add16(np.uint16_t *dest, np.uint16_t *src): # <<<<<<<<<<<<<< * cdef int i * for i in range(16): */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":349 * dest[i] += src[i] * * cdef inline void sub16(np.uint16_t *dest, np.uint16_t *src): # <<<<<<<<<<<<<< * cdef int i * for i in range(16): */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_sub16(__pyx_t_5numpy_uint16_t *__pyx_v_dest, __pyx_t_5numpy_uint16_t *__pyx_v_src) { int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("sub16", 0); /* "centrosome/_filter.pyx":351 * cdef inline void sub16(np.uint16_t *dest, np.uint16_t *src): * cdef int i * for i in range(16): # <<<<<<<<<<<<<< * dest[i] -= src[i] * */ for (__pyx_t_1 = 0; __pyx_t_1 < 16; __pyx_t_1+=1) { __pyx_v_i = __pyx_t_1; /* "centrosome/_filter.pyx":352 * cdef int i * for i in range(16): * dest[i] -= src[i] # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_t_2 = __pyx_v_i; (__pyx_v_dest[__pyx_t_2]) = ((__pyx_v_dest[__pyx_t_2]) - (__pyx_v_src[__pyx_v_i])); } /* "centrosome/_filter.pyx":349 * dest[i] += src[i] * * cdef inline void sub16(np.uint16_t *dest, np.uint16_t *src): # <<<<<<<<<<<<<< * cdef int i * for i in range(16): */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":363 * # * ############################################################################ * cdef inline void accumulate_coarse_histogram(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * cdef: * int offset */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate_coarse_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { int __pyx_v_offset; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("accumulate_coarse_histogram", 0); /* "centrosome/_filter.pyx":367 * int offset * * offset = tr_bl_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].top_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":368 * * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].top_right > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].top_right */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).top_right > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":369 * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].top_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count += ph.pixel_count[offset].top_right * offset = leading_edge_colidx(ph, colidx) */ __pyx_f_10centrosome_7_filter_add16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).top_right.coarse); /* "centrosome/_filter.pyx":370 * if ph.pixel_count[offset].top_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].top_right # <<<<<<<<<<<<<< * offset = leading_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count + (__pyx_v_ph->pixel_count[__pyx_v_offset]).top_right); /* "centrosome/_filter.pyx":368 * * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].top_right > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].top_right */ } /* "centrosome/_filter.pyx":371 * add16(ph.accumulator.coarse, ph.histogram[offset].top_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].top_right * offset = leading_edge_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].edge > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_leading_edge_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":372 * ph.accumulator_count += ph.pixel_count[offset].top_right * offset = leading_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count += ph.pixel_count[offset].edge */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).edge > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":373 * offset = leading_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count += ph.pixel_count[offset].edge * offset = tl_br_colidx(ph, colidx) */ __pyx_f_10centrosome_7_filter_add16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).edge.coarse); /* "centrosome/_filter.pyx":374 * if ph.pixel_count[offset].edge > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count += ph.pixel_count[offset].edge # <<<<<<<<<<<<<< * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_right > 0: */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count + (__pyx_v_ph->pixel_count[__pyx_v_offset]).edge); /* "centrosome/_filter.pyx":372 * ph.accumulator_count += ph.pixel_count[offset].top_right * offset = leading_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count += ph.pixel_count[offset].edge */ } /* "centrosome/_filter.pyx":375 * add16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count += ph.pixel_count[offset].edge * offset = tl_br_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].bottom_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].bottom_right.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":376 * ph.accumulator_count += ph.pixel_count[offset].edge * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_right > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].bottom_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].bottom_right */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).bottom_right > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":377 * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].bottom_right.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count += ph.pixel_count[offset].bottom_right * */ __pyx_f_10centrosome_7_filter_add16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).bottom_right.coarse); /* "centrosome/_filter.pyx":378 * if ph.pixel_count[offset].bottom_right > 0: * add16(ph.accumulator.coarse, ph.histogram[offset].bottom_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].bottom_right # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count + (__pyx_v_ph->pixel_count[__pyx_v_offset]).bottom_right); /* "centrosome/_filter.pyx":376 * ph.accumulator_count += ph.pixel_count[offset].edge * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_right > 0: # <<<<<<<<<<<<<< * add16(ph.accumulator.coarse, ph.histogram[offset].bottom_right.coarse) * ph.accumulator_count += ph.pixel_count[offset].bottom_right */ } /* "centrosome/_filter.pyx":363 * # * ############################################################################ * cdef inline void accumulate_coarse_histogram(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * cdef: * int offset */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":386 * # * ############################################################################ * cdef inline void deaccumulate_coarse_histogram(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * cdef: * int offset */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_deaccumulate_coarse_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx) { int __pyx_v_offset; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("deaccumulate_coarse_histogram", 0); /* "centrosome/_filter.pyx":392 * # The trailing diagonals don't appear until here * # * if colidx <= ph.a_2: # <<<<<<<<<<<<<< * return * offset = tl_br_colidx(ph, colidx) */ __pyx_t_1 = ((__pyx_v_colidx <= __pyx_v_ph->a_2) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":393 * # * if colidx <= ph.a_2: * return # <<<<<<<<<<<<<< * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].top_left > 0: */ goto __pyx_L0; /* "centrosome/_filter.pyx":392 * # The trailing diagonals don't appear until here * # * if colidx <= ph.a_2: # <<<<<<<<<<<<<< * return * offset = tl_br_colidx(ph, colidx) */ } /* "centrosome/_filter.pyx":394 * if colidx <= ph.a_2: * return * offset = tl_br_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].top_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].top_left.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":395 * return * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].top_left > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].top_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].top_left */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).top_left > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":396 * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].top_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].top_left.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count -= ph.pixel_count[offset].top_left * # */ __pyx_f_10centrosome_7_filter_sub16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).top_left.coarse); /* "centrosome/_filter.pyx":397 * if ph.pixel_count[offset].top_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].top_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].top_left # <<<<<<<<<<<<<< * # * # The trailing edge doesn't appear from the border until here */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count - (__pyx_v_ph->pixel_count[__pyx_v_offset]).top_left); /* "centrosome/_filter.pyx":395 * return * offset = tl_br_colidx(ph, colidx) * if ph.pixel_count[offset].top_left > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].top_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].top_left */ } /* "centrosome/_filter.pyx":401 * # The trailing edge doesn't appear from the border until here * # * if colidx > ph.radius: # <<<<<<<<<<<<<< * offset = trailing_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: */ __pyx_t_1 = ((__pyx_v_colidx > __pyx_v_ph->radius) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":402 * # * if colidx > ph.radius: * offset = trailing_edge_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].edge > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_trailing_edge_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":403 * if colidx > ph.radius: * offset = trailing_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count -= ph.pixel_count[offset].edge */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).edge > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":404 * offset = trailing_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count -= ph.pixel_count[offset].edge * offset = tr_bl_colidx(ph, colidx) */ __pyx_f_10centrosome_7_filter_sub16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).edge.coarse); /* "centrosome/_filter.pyx":405 * if ph.pixel_count[offset].edge > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count -= ph.pixel_count[offset].edge # <<<<<<<<<<<<<< * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_left > 0: */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count - (__pyx_v_ph->pixel_count[__pyx_v_offset]).edge); /* "centrosome/_filter.pyx":403 * if colidx > ph.radius: * offset = trailing_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count -= ph.pixel_count[offset].edge */ } /* "centrosome/_filter.pyx":401 * # The trailing edge doesn't appear from the border until here * # * if colidx > ph.radius: # <<<<<<<<<<<<<< * offset = trailing_edge_colidx(ph, colidx) * if ph.pixel_count[offset].edge > 0: */ } /* "centrosome/_filter.pyx":406 * sub16(ph.accumulator.coarse, ph.histogram[offset].edge.coarse) * ph.accumulator_count -= ph.pixel_count[offset].edge * offset = tr_bl_colidx(ph, colidx) # <<<<<<<<<<<<<< * if ph.pixel_count[offset].bottom_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].bottom_left.coarse) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":407 * ph.accumulator_count -= ph.pixel_count[offset].edge * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_left > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].bottom_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].bottom_left */ __pyx_t_1 = (((__pyx_v_ph->pixel_count[__pyx_v_offset]).bottom_left > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":408 * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].bottom_left.coarse) # <<<<<<<<<<<<<< * ph.accumulator_count -= ph.pixel_count[offset].bottom_left * */ __pyx_f_10centrosome_7_filter_sub16(__pyx_v_ph->accumulator.coarse, (__pyx_v_ph->histogram[__pyx_v_offset]).bottom_left.coarse); /* "centrosome/_filter.pyx":409 * if ph.pixel_count[offset].bottom_left > 0: * sub16(ph.accumulator.coarse, ph.histogram[offset].bottom_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].bottom_left # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_v_ph->accumulator_count = (__pyx_v_ph->accumulator_count - (__pyx_v_ph->pixel_count[__pyx_v_offset]).bottom_left); /* "centrosome/_filter.pyx":407 * ph.accumulator_count -= ph.pixel_count[offset].edge * offset = tr_bl_colidx(ph, colidx) * if ph.pixel_count[offset].bottom_left > 0: # <<<<<<<<<<<<<< * sub16(ph.accumulator.coarse, ph.histogram[offset].bottom_left.coarse) * ph.accumulator_count -= ph.pixel_count[offset].bottom_left */ } /* "centrosome/_filter.pyx":386 * # * ############################################################################ * cdef inline void deaccumulate_coarse_histogram(Histograms *ph, np.int32_t colidx): # <<<<<<<<<<<<<< * cdef: * int offset */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":416 * # * ############################################################################ * cdef inline void accumulate_fine_histogram(Histograms *ph, # <<<<<<<<<<<<<< * np.int32_t colidx, * np.uint32_t fineidx): */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate_fine_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx, __pyx_t_5numpy_uint32_t __pyx_v_fineidx) { int __pyx_v_fineoffset; int __pyx_v_offset; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("accumulate_fine_histogram", 0); /* "centrosome/_filter.pyx":420 * np.uint32_t fineidx): * cdef: * int fineoffset = fineidx * 16 # <<<<<<<<<<<<<< * int offset * */ __pyx_v_fineoffset = (__pyx_v_fineidx * 16); /* "centrosome/_filter.pyx":423 * int offset * * offset = tr_bl_colidx(ph, colidx) # <<<<<<<<<<<<<< * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_right.fine+fineoffset) * offset = leading_edge_colidx(ph, colidx) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":424 * * offset = tr_bl_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_right.fine+fineoffset) # <<<<<<<<<<<<<< * offset = leading_edge_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) */ __pyx_f_10centrosome_7_filter_add16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).top_right.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":425 * offset = tr_bl_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_right.fine+fineoffset) * offset = leading_edge_colidx(ph, colidx) # <<<<<<<<<<<<<< * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tl_br_colidx(ph, colidx) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_leading_edge_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":426 * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_right.fine+fineoffset) * offset = leading_edge_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) # <<<<<<<<<<<<<< * offset = tl_br_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_right.fine+fineoffset) */ __pyx_f_10centrosome_7_filter_add16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).edge.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":427 * offset = leading_edge_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tl_br_colidx(ph, colidx) # <<<<<<<<<<<<<< * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_right.fine+fineoffset) * */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":428 * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tl_br_colidx(ph, colidx) * add16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_right.fine+fineoffset) # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_f_10centrosome_7_filter_add16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).bottom_right.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":416 * # * ############################################################################ * cdef inline void accumulate_fine_histogram(Histograms *ph, # <<<<<<<<<<<<<< * np.int32_t colidx, * np.uint32_t fineidx): */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":435 * # * ############################################################################ * cdef inline void deaccumulate_fine_histogram(Histograms *ph, # <<<<<<<<<<<<<< * np.int32_t colidx, * np.uint32_t fineidx): */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_deaccumulate_fine_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, __pyx_t_5numpy_int32_t __pyx_v_colidx, __pyx_t_5numpy_uint32_t __pyx_v_fineidx) { int __pyx_v_fineoffset; int __pyx_v_offset; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("deaccumulate_fine_histogram", 0); /* "centrosome/_filter.pyx":439 * np.uint32_t fineidx): * cdef: * int fineoffset = fineidx * 16 # <<<<<<<<<<<<<< * int offset * */ __pyx_v_fineoffset = (__pyx_v_fineidx * 16); /* "centrosome/_filter.pyx":445 * # The trailing diagonals don't appear until here * # * if colidx < ph.a_2: # <<<<<<<<<<<<<< * return * offset = tl_br_colidx(ph, colidx) */ __pyx_t_1 = ((__pyx_v_colidx < __pyx_v_ph->a_2) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":446 * # * if colidx < ph.a_2: * return # <<<<<<<<<<<<<< * offset = tl_br_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) */ goto __pyx_L0; /* "centrosome/_filter.pyx":445 * # The trailing diagonals don't appear until here * # * if colidx < ph.a_2: # <<<<<<<<<<<<<< * return * offset = tl_br_colidx(ph, colidx) */ } /* "centrosome/_filter.pyx":447 * if colidx < ph.a_2: * return * offset = tl_br_colidx(ph, colidx) # <<<<<<<<<<<<<< * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) * if colidx >= ph.radius: */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":448 * return * offset = tl_br_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) # <<<<<<<<<<<<<< * if colidx >= ph.radius: * offset = trailing_edge_colidx(ph, colidx) */ __pyx_f_10centrosome_7_filter_sub16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).top_left.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":449 * offset = tl_br_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) * if colidx >= ph.radius: # <<<<<<<<<<<<<< * offset = trailing_edge_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) */ __pyx_t_1 = ((__pyx_v_colidx >= __pyx_v_ph->radius) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":450 * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) * if colidx >= ph.radius: * offset = trailing_edge_colidx(ph, colidx) # <<<<<<<<<<<<<< * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tr_bl_colidx(ph, colidx) */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_trailing_edge_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":451 * if colidx >= ph.radius: * offset = trailing_edge_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) # <<<<<<<<<<<<<< * offset = tr_bl_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_left.fine+fineoffset) */ __pyx_f_10centrosome_7_filter_sub16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).edge.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":449 * offset = tl_br_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].top_left.fine+fineoffset) * if colidx >= ph.radius: # <<<<<<<<<<<<<< * offset = trailing_edge_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) */ } /* "centrosome/_filter.pyx":452 * offset = trailing_edge_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tr_bl_colidx(ph, colidx) # <<<<<<<<<<<<<< * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_left.fine+fineoffset) * */ __pyx_v_offset = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_colidx); /* "centrosome/_filter.pyx":453 * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].edge.fine+fineoffset) * offset = tr_bl_colidx(ph, colidx) * sub16(ph.accumulator.fine+fineoffset, ph.histogram[offset].bottom_left.fine+fineoffset) # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_f_10centrosome_7_filter_sub16((__pyx_v_ph->accumulator.fine + __pyx_v_fineoffset), ((__pyx_v_ph->histogram[__pyx_v_offset]).bottom_left.fine + __pyx_v_fineoffset)); /* "centrosome/_filter.pyx":435 * # * ############################################################################ * cdef inline void deaccumulate_fine_histogram(Histograms *ph, # <<<<<<<<<<<<<< * np.int32_t colidx, * np.uint32_t fineidx): */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":461 * ############################################################################ * * cdef inline void accumulate(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * int i */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_accumulate(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("accumulate", 0); /* "centrosome/_filter.pyx":466 * int j * np.int32_t accumulator * accumulate_coarse_histogram(ph, ph.current_column) # <<<<<<<<<<<<<< * deaccumulate_coarse_histogram(ph, ph.current_column) * */ __pyx_f_10centrosome_7_filter_accumulate_coarse_histogram(__pyx_v_ph, __pyx_v_ph->current_column); /* "centrosome/_filter.pyx":467 * np.int32_t accumulator * accumulate_coarse_histogram(ph, ph.current_column) * deaccumulate_coarse_histogram(ph, ph.current_column) # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_f_10centrosome_7_filter_deaccumulate_coarse_histogram(__pyx_v_ph, __pyx_v_ph->current_column); /* "centrosome/_filter.pyx":461 * ############################################################################ * * cdef inline void accumulate(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * int i */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":489 * ############################################################################ * * cdef inline void update_fine(Histograms *ph, int fineidx): # <<<<<<<<<<<<<< * cdef: * int first_update_column = ph.last_update_column[fineidx]+1 */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_fine(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, int __pyx_v_fineidx) { int __pyx_v_first_update_column; int __pyx_v_update_limit; int __pyx_v_i; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __pyx_t_5numpy_int32_t __pyx_t_3; __Pyx_RefNannySetupContext("update_fine", 0); /* "centrosome/_filter.pyx":491 * cdef inline void update_fine(Histograms *ph, int fineidx): * cdef: * int first_update_column = ph.last_update_column[fineidx]+1 # <<<<<<<<<<<<<< * int update_limit = ph.current_column+1 * int i */ __pyx_v_first_update_column = ((__pyx_v_ph->last_update_column[__pyx_v_fineidx]) + 1); /* "centrosome/_filter.pyx":492 * cdef: * int first_update_column = ph.last_update_column[fineidx]+1 * int update_limit = ph.current_column+1 # <<<<<<<<<<<<<< * int i * */ __pyx_v_update_limit = (__pyx_v_ph->current_column + 1); /* "centrosome/_filter.pyx":495 * int i * * for i in range(first_update_column, update_limit): # <<<<<<<<<<<<<< * accumulate_fine_histogram(ph, i, fineidx) * deaccumulate_fine_histogram(ph, i, fineidx) */ __pyx_t_1 = __pyx_v_update_limit; for (__pyx_t_2 = __pyx_v_first_update_column; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "centrosome/_filter.pyx":496 * * for i in range(first_update_column, update_limit): * accumulate_fine_histogram(ph, i, fineidx) # <<<<<<<<<<<<<< * deaccumulate_fine_histogram(ph, i, fineidx) * ph.last_update_column[fineidx] = ph.current_column */ __pyx_f_10centrosome_7_filter_accumulate_fine_histogram(__pyx_v_ph, __pyx_v_i, __pyx_v_fineidx); /* "centrosome/_filter.pyx":497 * for i in range(first_update_column, update_limit): * accumulate_fine_histogram(ph, i, fineidx) * deaccumulate_fine_histogram(ph, i, fineidx) # <<<<<<<<<<<<<< * ph.last_update_column[fineidx] = ph.current_column * */ __pyx_f_10centrosome_7_filter_deaccumulate_fine_histogram(__pyx_v_ph, __pyx_v_i, __pyx_v_fineidx); } /* "centrosome/_filter.pyx":498 * accumulate_fine_histogram(ph, i, fineidx) * deaccumulate_fine_histogram(ph, i, fineidx) * ph.last_update_column[fineidx] = ph.current_column # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_t_3 = __pyx_v_ph->current_column; (__pyx_v_ph->last_update_column[__pyx_v_fineidx]) = __pyx_t_3; /* "centrosome/_filter.pyx":489 * ############################################################################ * * cdef inline void update_fine(Histograms *ph, int fineidx): # <<<<<<<<<<<<<< * cdef: * int first_update_column = ph.last_update_column[fineidx]+1 */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":512 * # * ############################################################################ * cdef inline void update_histogram(Histograms *ph, # <<<<<<<<<<<<<< * HistogramPiece *hist_piece, * pixel_count_t *pixel_count, */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_histogram(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph, struct __pyx_t_10centrosome_7_filter_HistogramPiece *__pyx_v_hist_piece, __pyx_t_10centrosome_7_filter_pixel_count_t *__pyx_v_pixel_count, struct __pyx_t_10centrosome_7_filter_SCoord *__pyx_v_last_coord, struct __pyx_t_10centrosome_7_filter_SCoord *__pyx_v_coord) { __pyx_t_5numpy_int32_t __pyx_v_current_column; __pyx_t_5numpy_int32_t __pyx_v_current_row; __pyx_t_5numpy_int32_t __pyx_v_current_stride; __pyx_t_5numpy_int32_t __pyx_v_column_count; __pyx_t_5numpy_int32_t __pyx_v_row_count; __pyx_t_5numpy_uint8_t __pyx_v_value; __pyx_t_5numpy_int32_t __pyx_v_stride; __pyx_t_5numpy_int32_t __pyx_v_x; __pyx_t_5numpy_int32_t __pyx_v_y; __Pyx_RefNannyDeclarations __pyx_t_5numpy_int32_t __pyx_t_1; int __pyx_t_2; int __pyx_t_3; long __pyx_t_4; __pyx_t_5numpy_uint8_t __pyx_t_5; __Pyx_RefNannySetupContext("update_histogram", 0); /* "centrosome/_filter.pyx":518 * SCoord *coord): * cdef: * np.int32_t current_column = ph.current_column # <<<<<<<<<<<<<< * np.int32_t current_row = ph.current_row * np.int32_t current_stride = ph.current_stride */ __pyx_t_1 = __pyx_v_ph->current_column; __pyx_v_current_column = __pyx_t_1; /* "centrosome/_filter.pyx":519 * cdef: * np.int32_t current_column = ph.current_column * np.int32_t current_row = ph.current_row # <<<<<<<<<<<<<< * np.int32_t current_stride = ph.current_stride * np.int32_t column_count = ph.column_count */ __pyx_t_1 = __pyx_v_ph->current_row; __pyx_v_current_row = __pyx_t_1; /* "centrosome/_filter.pyx":520 * np.int32_t current_column = ph.current_column * np.int32_t current_row = ph.current_row * np.int32_t current_stride = ph.current_stride # <<<<<<<<<<<<<< * np.int32_t column_count = ph.column_count * np.int32_t row_count = ph.row_count */ __pyx_t_1 = __pyx_v_ph->current_stride; __pyx_v_current_stride = __pyx_t_1; /* "centrosome/_filter.pyx":521 * np.int32_t current_row = ph.current_row * np.int32_t current_stride = ph.current_stride * np.int32_t column_count = ph.column_count # <<<<<<<<<<<<<< * np.int32_t row_count = ph.row_count * np.uint8_t value */ __pyx_t_1 = __pyx_v_ph->column_count; __pyx_v_column_count = __pyx_t_1; /* "centrosome/_filter.pyx":522 * np.int32_t current_stride = ph.current_stride * np.int32_t column_count = ph.column_count * np.int32_t row_count = ph.row_count # <<<<<<<<<<<<<< * np.uint8_t value * np.int32_t stride */ __pyx_t_1 = __pyx_v_ph->row_count; __pyx_v_row_count = __pyx_t_1; /* "centrosome/_filter.pyx":528 * np.int32_t y * * x = last_coord.x + current_column # <<<<<<<<<<<<<< * y = last_coord.y + current_row * stride = current_stride+last_coord.stride */ __pyx_v_x = (__pyx_v_last_coord->x + __pyx_v_current_column); /* "centrosome/_filter.pyx":529 * * x = last_coord.x + current_column * y = last_coord.y + current_row # <<<<<<<<<<<<<< * stride = current_stride+last_coord.stride * */ __pyx_v_y = (__pyx_v_last_coord->y + __pyx_v_current_row); /* "centrosome/_filter.pyx":530 * x = last_coord.x + current_column * y = last_coord.y + current_row * stride = current_stride+last_coord.stride # <<<<<<<<<<<<<< * * if (x >= 0 and x < column_count and */ __pyx_v_stride = (__pyx_v_current_stride + __pyx_v_last_coord->stride); /* "centrosome/_filter.pyx":532 * stride = current_stride+last_coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ __pyx_t_3 = ((__pyx_v_x >= 0) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = ((__pyx_v_x < __pyx_v_column_count) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } /* "centrosome/_filter.pyx":533 * * if (x >= 0 and x < column_count and * y >= 0 and y < row_count and # <<<<<<<<<<<<<< * ph.mask[stride]): * value = ph.data[stride] */ __pyx_t_3 = ((__pyx_v_y >= 0) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } __pyx_t_3 = ((__pyx_v_y < __pyx_v_row_count) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L4_bool_binop_done; } /* "centrosome/_filter.pyx":534 * if (x >= 0 and x < column_count and * y >= 0 and y < row_count and * ph.mask[stride]): # <<<<<<<<<<<<<< * value = ph.data[stride] * pixel_count[0] -= 1 */ __pyx_t_3 = ((__pyx_v_ph->mask[__pyx_v_stride]) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L4_bool_binop_done:; /* "centrosome/_filter.pyx":532 * stride = current_stride+last_coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ if (__pyx_t_2) { /* "centrosome/_filter.pyx":535 * y >= 0 and y < row_count and * ph.mask[stride]): * value = ph.data[stride] # <<<<<<<<<<<<<< * pixel_count[0] -= 1 * hist_piece.fine[value] -= 1 */ __pyx_v_value = (__pyx_v_ph->data[__pyx_v_stride]); /* "centrosome/_filter.pyx":536 * ph.mask[stride]): * value = ph.data[stride] * pixel_count[0] -= 1 # <<<<<<<<<<<<<< * hist_piece.fine[value] -= 1 * hist_piece.coarse[value / 16] -= 1 */ __pyx_t_4 = 0; (__pyx_v_pixel_count[__pyx_t_4]) = ((__pyx_v_pixel_count[__pyx_t_4]) - 1); /* "centrosome/_filter.pyx":537 * value = ph.data[stride] * pixel_count[0] -= 1 * hist_piece.fine[value] -= 1 # <<<<<<<<<<<<<< * hist_piece.coarse[value / 16] -= 1 * */ __pyx_t_5 = __pyx_v_value; (__pyx_v_hist_piece->fine[__pyx_t_5]) = ((__pyx_v_hist_piece->fine[__pyx_t_5]) - 1); /* "centrosome/_filter.pyx":538 * pixel_count[0] -= 1 * hist_piece.fine[value] -= 1 * hist_piece.coarse[value / 16] -= 1 # <<<<<<<<<<<<<< * * x = coord.x + current_column */ __pyx_t_4 = __Pyx_div_long(__pyx_v_value, 16); (__pyx_v_hist_piece->coarse[__pyx_t_4]) = ((__pyx_v_hist_piece->coarse[__pyx_t_4]) - 1); /* "centrosome/_filter.pyx":532 * stride = current_stride+last_coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ } /* "centrosome/_filter.pyx":540 * hist_piece.coarse[value / 16] -= 1 * * x = coord.x + current_column # <<<<<<<<<<<<<< * y = coord.y + current_row * stride = current_stride + coord.stride */ __pyx_v_x = (__pyx_v_coord->x + __pyx_v_current_column); /* "centrosome/_filter.pyx":541 * * x = coord.x + current_column * y = coord.y + current_row # <<<<<<<<<<<<<< * stride = current_stride + coord.stride * */ __pyx_v_y = (__pyx_v_coord->y + __pyx_v_current_row); /* "centrosome/_filter.pyx":542 * x = coord.x + current_column * y = coord.y + current_row * stride = current_stride + coord.stride # <<<<<<<<<<<<<< * * if (x >= 0 and x < column_count and */ __pyx_v_stride = (__pyx_v_current_stride + __pyx_v_coord->stride); /* "centrosome/_filter.pyx":544 * stride = current_stride + coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ __pyx_t_3 = ((__pyx_v_x >= 0) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L10_bool_binop_done; } __pyx_t_3 = ((__pyx_v_x < __pyx_v_column_count) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L10_bool_binop_done; } /* "centrosome/_filter.pyx":545 * * if (x >= 0 and x < column_count and * y >= 0 and y < row_count and # <<<<<<<<<<<<<< * ph.mask[stride]): * value = ph.data[stride] */ __pyx_t_3 = ((__pyx_v_y >= 0) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L10_bool_binop_done; } __pyx_t_3 = ((__pyx_v_y < __pyx_v_row_count) != 0); if (__pyx_t_3) { } else { __pyx_t_2 = __pyx_t_3; goto __pyx_L10_bool_binop_done; } /* "centrosome/_filter.pyx":546 * if (x >= 0 and x < column_count and * y >= 0 and y < row_count and * ph.mask[stride]): # <<<<<<<<<<<<<< * value = ph.data[stride] * pixel_count[0] += 1 */ __pyx_t_3 = ((__pyx_v_ph->mask[__pyx_v_stride]) != 0); __pyx_t_2 = __pyx_t_3; __pyx_L10_bool_binop_done:; /* "centrosome/_filter.pyx":544 * stride = current_stride + coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ if (__pyx_t_2) { /* "centrosome/_filter.pyx":547 * y >= 0 and y < row_count and * ph.mask[stride]): * value = ph.data[stride] # <<<<<<<<<<<<<< * pixel_count[0] += 1 * hist_piece.fine[value] += 1 */ __pyx_v_value = (__pyx_v_ph->data[__pyx_v_stride]); /* "centrosome/_filter.pyx":548 * ph.mask[stride]): * value = ph.data[stride] * pixel_count[0] += 1 # <<<<<<<<<<<<<< * hist_piece.fine[value] += 1 * hist_piece.coarse[value / 16] += 1 */ __pyx_t_4 = 0; (__pyx_v_pixel_count[__pyx_t_4]) = ((__pyx_v_pixel_count[__pyx_t_4]) + 1); /* "centrosome/_filter.pyx":549 * value = ph.data[stride] * pixel_count[0] += 1 * hist_piece.fine[value] += 1 # <<<<<<<<<<<<<< * hist_piece.coarse[value / 16] += 1 * */ __pyx_t_5 = __pyx_v_value; (__pyx_v_hist_piece->fine[__pyx_t_5]) = ((__pyx_v_hist_piece->fine[__pyx_t_5]) + 1); /* "centrosome/_filter.pyx":550 * pixel_count[0] += 1 * hist_piece.fine[value] += 1 * hist_piece.coarse[value / 16] += 1 # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_t_4 = __Pyx_div_long(__pyx_v_value, 16); (__pyx_v_hist_piece->coarse[__pyx_t_4]) = ((__pyx_v_hist_piece->coarse[__pyx_t_4]) + 1); /* "centrosome/_filter.pyx":544 * stride = current_stride + coord.stride * * if (x >= 0 and x < column_count and # <<<<<<<<<<<<<< * y >= 0 and y < row_count and * ph.mask[stride]): */ } /* "centrosome/_filter.pyx":512 * # * ############################################################################ * cdef inline void update_histogram(Histograms *ph, # <<<<<<<<<<<<<< * HistogramPiece *hist_piece, * pixel_count_t *pixel_count, */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":557 * # * ############################################################################ * cdef inline void update_current_location(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * np.int32_t current_column = ph.current_column */ static CYTHON_INLINE void __pyx_f_10centrosome_7_filter_update_current_location(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph) { __pyx_t_5numpy_int32_t __pyx_v_current_column; CYTHON_UNUSED __pyx_t_5numpy_int32_t __pyx_v_radius; __pyx_t_5numpy_int32_t __pyx_v_top_left_off; __pyx_t_5numpy_int32_t __pyx_v_top_right_off; __pyx_t_5numpy_int32_t __pyx_v_bottom_left_off; __pyx_t_5numpy_int32_t __pyx_v_bottom_right_off; __pyx_t_5numpy_int32_t __pyx_v_leading_edge_off; __Pyx_RefNannyDeclarations __pyx_t_5numpy_int32_t __pyx_t_1; __Pyx_RefNannySetupContext("update_current_location", 0); /* "centrosome/_filter.pyx":559 * cdef inline void update_current_location(Histograms *ph): * cdef: * np.int32_t current_column = ph.current_column # <<<<<<<<<<<<<< * np.int32_t radius = ph.radius * np.int32_t top_left_off = tl_br_colidx(ph, current_column) */ __pyx_t_1 = __pyx_v_ph->current_column; __pyx_v_current_column = __pyx_t_1; /* "centrosome/_filter.pyx":560 * cdef: * np.int32_t current_column = ph.current_column * np.int32_t radius = ph.radius # <<<<<<<<<<<<<< * np.int32_t top_left_off = tl_br_colidx(ph, current_column) * np.int32_t top_right_off = tr_bl_colidx(ph, current_column) */ __pyx_t_1 = __pyx_v_ph->radius; __pyx_v_radius = __pyx_t_1; /* "centrosome/_filter.pyx":561 * np.int32_t current_column = ph.current_column * np.int32_t radius = ph.radius * np.int32_t top_left_off = tl_br_colidx(ph, current_column) # <<<<<<<<<<<<<< * np.int32_t top_right_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_left_off = tr_bl_colidx(ph, current_column) */ __pyx_v_top_left_off = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_current_column); /* "centrosome/_filter.pyx":562 * np.int32_t radius = ph.radius * np.int32_t top_left_off = tl_br_colidx(ph, current_column) * np.int32_t top_right_off = tr_bl_colidx(ph, current_column) # <<<<<<<<<<<<<< * np.int32_t bottom_left_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_right_off = tl_br_colidx(ph, current_column) */ __pyx_v_top_right_off = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_current_column); /* "centrosome/_filter.pyx":563 * np.int32_t top_left_off = tl_br_colidx(ph, current_column) * np.int32_t top_right_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_left_off = tr_bl_colidx(ph, current_column) # <<<<<<<<<<<<<< * np.int32_t bottom_right_off = tl_br_colidx(ph, current_column) * np.int32_t leading_edge_off = leading_edge_colidx(ph, current_column) */ __pyx_v_bottom_left_off = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, __pyx_v_current_column); /* "centrosome/_filter.pyx":564 * np.int32_t top_right_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_left_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_right_off = tl_br_colidx(ph, current_column) # <<<<<<<<<<<<<< * np.int32_t leading_edge_off = leading_edge_colidx(ph, current_column) * np.int32_t *coarse_histogram */ __pyx_v_bottom_right_off = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, __pyx_v_current_column); /* "centrosome/_filter.pyx":565 * np.int32_t bottom_left_off = tr_bl_colidx(ph, current_column) * np.int32_t bottom_right_off = tl_br_colidx(ph, current_column) * np.int32_t leading_edge_off = leading_edge_colidx(ph, current_column) # <<<<<<<<<<<<<< * np.int32_t *coarse_histogram * np.int32_t *fine_histogram */ __pyx_v_leading_edge_off = __pyx_f_10centrosome_7_filter_leading_edge_colidx(__pyx_v_ph, __pyx_v_current_column); /* "centrosome/_filter.pyx":575 * np.int32_t stride * * update_histogram(ph, &ph.histogram[top_left_off].top_left, # <<<<<<<<<<<<<< * &ph.pixel_count[top_left_off].top_left, * &ph.last_top_left, */ __pyx_f_10centrosome_7_filter_update_histogram(__pyx_v_ph, (&(__pyx_v_ph->histogram[__pyx_v_top_left_off]).top_left), (&(__pyx_v_ph->pixel_count[__pyx_v_top_left_off]).top_left), (&__pyx_v_ph->last_top_left), (&__pyx_v_ph->top_left)); /* "centrosome/_filter.pyx":580 * &ph.top_left) * * update_histogram(ph, &ph.histogram[top_right_off].top_right, # <<<<<<<<<<<<<< * &ph.pixel_count[top_right_off].top_right, * &ph.last_top_right, */ __pyx_f_10centrosome_7_filter_update_histogram(__pyx_v_ph, (&(__pyx_v_ph->histogram[__pyx_v_top_right_off]).top_right), (&(__pyx_v_ph->pixel_count[__pyx_v_top_right_off]).top_right), (&__pyx_v_ph->last_top_right), (&__pyx_v_ph->top_right)); /* "centrosome/_filter.pyx":585 * &ph.top_right) * * update_histogram(ph, &ph.histogram[bottom_left_off].bottom_left, # <<<<<<<<<<<<<< * &ph.pixel_count[bottom_left_off].bottom_left, * &ph.last_bottom_left, */ __pyx_f_10centrosome_7_filter_update_histogram(__pyx_v_ph, (&(__pyx_v_ph->histogram[__pyx_v_bottom_left_off]).bottom_left), (&(__pyx_v_ph->pixel_count[__pyx_v_bottom_left_off]).bottom_left), (&__pyx_v_ph->last_bottom_left), (&__pyx_v_ph->bottom_left)); /* "centrosome/_filter.pyx":590 * &ph.bottom_left) * * update_histogram(ph, &ph.histogram[bottom_right_off].bottom_right, # <<<<<<<<<<<<<< * &ph.pixel_count[bottom_right_off].bottom_right, * &ph.last_bottom_right, */ __pyx_f_10centrosome_7_filter_update_histogram(__pyx_v_ph, (&(__pyx_v_ph->histogram[__pyx_v_bottom_right_off]).bottom_right), (&(__pyx_v_ph->pixel_count[__pyx_v_bottom_right_off]).bottom_right), (&__pyx_v_ph->last_bottom_right), (&__pyx_v_ph->bottom_right)); /* "centrosome/_filter.pyx":595 * &ph.bottom_right) * * update_histogram(ph, &ph.histogram[leading_edge_off].edge, # <<<<<<<<<<<<<< * &ph.pixel_count[leading_edge_off].edge, * &ph.last_leading_edge, */ __pyx_f_10centrosome_7_filter_update_histogram(__pyx_v_ph, (&(__pyx_v_ph->histogram[__pyx_v_leading_edge_off]).edge), (&(__pyx_v_ph->pixel_count[__pyx_v_leading_edge_off]).edge), (&__pyx_v_ph->last_leading_edge), (&__pyx_v_ph->leading_edge)); /* "centrosome/_filter.pyx":557 * # * ############################################################################ * cdef inline void update_current_location(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * np.int32_t current_column = ph.current_column */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "centrosome/_filter.pyx":606 * ############################################################################ * * cdef inline np.uint8_t find_median(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * np.uint32_t pixels_below # of pixels below the median */ static CYTHON_INLINE __pyx_t_5numpy_uint8_t __pyx_f_10centrosome_7_filter_find_median(struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph) { __pyx_t_5numpy_uint32_t __pyx_v_pixels_below; int __pyx_v_i; int __pyx_v_j; __pyx_t_5numpy_uint32_t __pyx_v_accumulator; __pyx_t_5numpy_uint8_t __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; long __pyx_t_3; __Pyx_RefNannySetupContext("find_median", 0); /* "centrosome/_filter.pyx":614 * np.uint32_t accumulator * * if ph.accumulator_count == 0: # <<<<<<<<<<<<<< * return 0 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff */ __pyx_t_1 = ((__pyx_v_ph->accumulator_count == 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":615 * * if ph.accumulator_count == 0: * return 0 # <<<<<<<<<<<<<< * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff * if pixels_below > 0: */ __pyx_r = 0; goto __pyx_L0; /* "centrosome/_filter.pyx":614 * np.uint32_t accumulator * * if ph.accumulator_count == 0: # <<<<<<<<<<<<<< * return 0 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff */ } /* "centrosome/_filter.pyx":616 * if ph.accumulator_count == 0: * return 0 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff # <<<<<<<<<<<<<< * if pixels_below > 0: * pixels_below -= 1 */ __pyx_v_pixels_below = __Pyx_div_long(((__pyx_v_ph->accumulator_count * __pyx_v_ph->percent) + 50), 0x64); /* "centrosome/_filter.pyx":617 * return 0 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff * if pixels_below > 0: # <<<<<<<<<<<<<< * pixels_below -= 1 * accumulator = 0 */ __pyx_t_1 = ((__pyx_v_pixels_below > 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":618 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff * if pixels_below > 0: * pixels_below -= 1 # <<<<<<<<<<<<<< * accumulator = 0 * for i in range(16): */ __pyx_v_pixels_below = (__pyx_v_pixels_below - 1); /* "centrosome/_filter.pyx":617 * return 0 * pixels_below = (ph.accumulator_count * ph.percent + 50) / 100 # +50 for roundoff * if pixels_below > 0: # <<<<<<<<<<<<<< * pixels_below -= 1 * accumulator = 0 */ } /* "centrosome/_filter.pyx":619 * if pixels_below > 0: * pixels_below -= 1 * accumulator = 0 # <<<<<<<<<<<<<< * for i in range(16): * accumulator += ph.accumulator.coarse[i] */ __pyx_v_accumulator = 0; /* "centrosome/_filter.pyx":620 * pixels_below -= 1 * accumulator = 0 * for i in range(16): # <<<<<<<<<<<<<< * accumulator += ph.accumulator.coarse[i] * if accumulator > pixels_below: */ for (__pyx_t_2 = 0; __pyx_t_2 < 16; __pyx_t_2+=1) { __pyx_v_i = __pyx_t_2; /* "centrosome/_filter.pyx":621 * accumulator = 0 * for i in range(16): * accumulator += ph.accumulator.coarse[i] # <<<<<<<<<<<<<< * if accumulator > pixels_below: * break */ __pyx_v_accumulator = (__pyx_v_accumulator + (__pyx_v_ph->accumulator.coarse[__pyx_v_i])); /* "centrosome/_filter.pyx":622 * for i in range(16): * accumulator += ph.accumulator.coarse[i] * if accumulator > pixels_below: # <<<<<<<<<<<<<< * break * accumulator -= ph.accumulator.coarse[i] */ __pyx_t_1 = ((__pyx_v_accumulator > __pyx_v_pixels_below) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":623 * accumulator += ph.accumulator.coarse[i] * if accumulator > pixels_below: * break # <<<<<<<<<<<<<< * accumulator -= ph.accumulator.coarse[i] * update_fine(ph, i) */ goto __pyx_L6_break; /* "centrosome/_filter.pyx":622 * for i in range(16): * accumulator += ph.accumulator.coarse[i] * if accumulator > pixels_below: # <<<<<<<<<<<<<< * break * accumulator -= ph.accumulator.coarse[i] */ } } __pyx_L6_break:; /* "centrosome/_filter.pyx":624 * if accumulator > pixels_below: * break * accumulator -= ph.accumulator.coarse[i] # <<<<<<<<<<<<<< * update_fine(ph, i) * for j in range(i*16,(i+1)*16): */ __pyx_v_accumulator = (__pyx_v_accumulator - (__pyx_v_ph->accumulator.coarse[__pyx_v_i])); /* "centrosome/_filter.pyx":625 * break * accumulator -= ph.accumulator.coarse[i] * update_fine(ph, i) # <<<<<<<<<<<<<< * for j in range(i*16,(i+1)*16): * accumulator += ph.accumulator.fine[j] */ __pyx_f_10centrosome_7_filter_update_fine(__pyx_v_ph, __pyx_v_i); /* "centrosome/_filter.pyx":626 * accumulator -= ph.accumulator.coarse[i] * update_fine(ph, i) * for j in range(i*16,(i+1)*16): # <<<<<<<<<<<<<< * accumulator += ph.accumulator.fine[j] * if accumulator > pixels_below: */ __pyx_t_3 = ((__pyx_v_i + 1) * 16); for (__pyx_t_2 = (__pyx_v_i * 16); __pyx_t_2 < __pyx_t_3; __pyx_t_2+=1) { __pyx_v_j = __pyx_t_2; /* "centrosome/_filter.pyx":627 * update_fine(ph, i) * for j in range(i*16,(i+1)*16): * accumulator += ph.accumulator.fine[j] # <<<<<<<<<<<<<< * if accumulator > pixels_below: * return <np.uint8_t> j */ __pyx_v_accumulator = (__pyx_v_accumulator + (__pyx_v_ph->accumulator.fine[__pyx_v_j])); /* "centrosome/_filter.pyx":628 * for j in range(i*16,(i+1)*16): * accumulator += ph.accumulator.fine[j] * if accumulator > pixels_below: # <<<<<<<<<<<<<< * return <np.uint8_t> j * return 0 */ __pyx_t_1 = ((__pyx_v_accumulator > __pyx_v_pixels_below) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":629 * accumulator += ph.accumulator.fine[j] * if accumulator > pixels_below: * return <np.uint8_t> j # <<<<<<<<<<<<<< * return 0 * */ __pyx_r = ((__pyx_t_5numpy_uint8_t)__pyx_v_j); goto __pyx_L0; /* "centrosome/_filter.pyx":628 * for j in range(i*16,(i+1)*16): * accumulator += ph.accumulator.fine[j] * if accumulator > pixels_below: # <<<<<<<<<<<<<< * return <np.uint8_t> j * return 0 */ } } /* "centrosome/_filter.pyx":630 * if accumulator > pixels_below: * return <np.uint8_t> j * return 0 # <<<<<<<<<<<<<< * * ############################################################################ */ __pyx_r = 0; goto __pyx_L0; /* "centrosome/_filter.pyx":606 * ############################################################################ * * cdef inline np.uint8_t find_median(Histograms *ph): # <<<<<<<<<<<<<< * cdef: * np.uint32_t pixels_below # of pixels below the median */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":647 * # * ############################################################################ * cdef int c_median_filter(np.int32_t rows, # <<<<<<<<<<<<<< * np.int32_t columns, * np.int32_t row_stride, */ static int __pyx_f_10centrosome_7_filter_c_median_filter(__pyx_t_5numpy_int32_t __pyx_v_rows, __pyx_t_5numpy_int32_t __pyx_v_columns, __pyx_t_5numpy_int32_t __pyx_v_row_stride, __pyx_t_5numpy_int32_t __pyx_v_col_stride, __pyx_t_5numpy_int32_t __pyx_v_radius, __pyx_t_5numpy_int32_t __pyx_v_percent, __pyx_t_5numpy_uint8_t *__pyx_v_data, __pyx_t_5numpy_uint8_t *__pyx_v_mask, __pyx_t_5numpy_uint8_t *__pyx_v_output) { struct __pyx_t_10centrosome_7_filter_Histograms *__pyx_v_ph; int __pyx_v_row; int __pyx_v_col; int __pyx_v_i; __pyx_t_5numpy_int32_t __pyx_v_tl_br_off; __pyx_t_5numpy_int32_t __pyx_v_tr_bl_off; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; __pyx_t_5numpy_int32_t __pyx_t_2; int __pyx_t_3; int __pyx_t_4; long __pyx_t_5; __pyx_t_5numpy_int32_t __pyx_t_6; __Pyx_RefNannySetupContext("c_median_filter", 0); /* "centrosome/_filter.pyx":667 * np.int32_t bottom_right_off * * ph = allocate_histograms(rows, columns, row_stride, col_stride, # <<<<<<<<<<<<<< * radius, percent, data, mask, output) * if not ph: */ __pyx_v_ph = __pyx_f_10centrosome_7_filter_allocate_histograms(__pyx_v_rows, __pyx_v_columns, __pyx_v_row_stride, __pyx_v_col_stride, __pyx_v_radius, __pyx_v_percent, __pyx_v_data, __pyx_v_mask, __pyx_v_output); /* "centrosome/_filter.pyx":669 * ph = allocate_histograms(rows, columns, row_stride, col_stride, * radius, percent, data, mask, output) * if not ph: # <<<<<<<<<<<<<< * return 1 * */ __pyx_t_1 = ((!(__pyx_v_ph != 0)) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":670 * radius, percent, data, mask, output) * if not ph: * return 1 # <<<<<<<<<<<<<< * * for row in range(-radius, rows): */ __pyx_r = 1; goto __pyx_L0; /* "centrosome/_filter.pyx":669 * ph = allocate_histograms(rows, columns, row_stride, col_stride, * radius, percent, data, mask, output) * if not ph: # <<<<<<<<<<<<<< * return 1 * */ } /* "centrosome/_filter.pyx":672 * return 1 * * for row in range(-radius, rows): # <<<<<<<<<<<<<< * # * # Initialize the starting diagonal histograms to zero. The leading */ __pyx_t_2 = __pyx_v_rows; for (__pyx_t_3 = (-__pyx_v_radius); __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) { __pyx_v_row = __pyx_t_3; /* "centrosome/_filter.pyx":681 * # start of each row * # * tl_br_off = tl_br_colidx(ph, -radius) # <<<<<<<<<<<<<< * tr_bl_off = tr_bl_colidx(ph, columns+radius-1) * */ __pyx_v_tl_br_off = __pyx_f_10centrosome_7_filter_tl_br_colidx(__pyx_v_ph, (-__pyx_v_radius)); /* "centrosome/_filter.pyx":682 * # * tl_br_off = tl_br_colidx(ph, -radius) * tr_bl_off = tr_bl_colidx(ph, columns+radius-1) # <<<<<<<<<<<<<< * * memset(&ph.histogram[tl_br_off].top_left, 0, sizeof(HistogramPiece)) */ __pyx_v_tr_bl_off = __pyx_f_10centrosome_7_filter_tr_bl_colidx(__pyx_v_ph, ((__pyx_v_columns + __pyx_v_radius) - 1)); /* "centrosome/_filter.pyx":684 * tr_bl_off = tr_bl_colidx(ph, columns+radius-1) * * memset(&ph.histogram[tl_br_off].top_left, 0, sizeof(HistogramPiece)) # <<<<<<<<<<<<<< * memset(&ph.histogram[tl_br_off].bottom_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].top_right, 0, sizeof(HistogramPiece)) */ memset((&(__pyx_v_ph->histogram[__pyx_v_tl_br_off]).top_left), 0, (sizeof(struct __pyx_t_10centrosome_7_filter_HistogramPiece))); /* "centrosome/_filter.pyx":685 * * memset(&ph.histogram[tl_br_off].top_left, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tl_br_off].bottom_right, 0, sizeof(HistogramPiece)) # <<<<<<<<<<<<<< * memset(&ph.histogram[tr_bl_off].top_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].bottom_left, 0, sizeof(HistogramPiece)) */ memset((&(__pyx_v_ph->histogram[__pyx_v_tl_br_off]).bottom_right), 0, (sizeof(struct __pyx_t_10centrosome_7_filter_HistogramPiece))); /* "centrosome/_filter.pyx":686 * memset(&ph.histogram[tl_br_off].top_left, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tl_br_off].bottom_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].top_right, 0, sizeof(HistogramPiece)) # <<<<<<<<<<<<<< * memset(&ph.histogram[tr_bl_off].bottom_left, 0, sizeof(HistogramPiece)) * ph.pixel_count[tl_br_off].top_left = 0 */ memset((&(__pyx_v_ph->histogram[__pyx_v_tr_bl_off]).top_right), 0, (sizeof(struct __pyx_t_10centrosome_7_filter_HistogramPiece))); /* "centrosome/_filter.pyx":687 * memset(&ph.histogram[tl_br_off].bottom_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].top_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].bottom_left, 0, sizeof(HistogramPiece)) # <<<<<<<<<<<<<< * ph.pixel_count[tl_br_off].top_left = 0 * ph.pixel_count[tl_br_off].bottom_right = 0 */ memset((&(__pyx_v_ph->histogram[__pyx_v_tr_bl_off]).bottom_left), 0, (sizeof(struct __pyx_t_10centrosome_7_filter_HistogramPiece))); /* "centrosome/_filter.pyx":688 * memset(&ph.histogram[tr_bl_off].top_right, 0, sizeof(HistogramPiece)) * memset(&ph.histogram[tr_bl_off].bottom_left, 0, sizeof(HistogramPiece)) * ph.pixel_count[tl_br_off].top_left = 0 # <<<<<<<<<<<<<< * ph.pixel_count[tl_br_off].bottom_right = 0 * ph.pixel_count[tr_bl_off].top_right = 0 */ (__pyx_v_ph->pixel_count[__pyx_v_tl_br_off]).top_left = 0; /* "centrosome/_filter.pyx":689 * memset(&ph.histogram[tr_bl_off].bottom_left, 0, sizeof(HistogramPiece)) * ph.pixel_count[tl_br_off].top_left = 0 * ph.pixel_count[tl_br_off].bottom_right = 0 # <<<<<<<<<<<<<< * ph.pixel_count[tr_bl_off].top_right = 0 * ph.pixel_count[tr_bl_off].bottom_left = 0 */ (__pyx_v_ph->pixel_count[__pyx_v_tl_br_off]).bottom_right = 0; /* "centrosome/_filter.pyx":690 * ph.pixel_count[tl_br_off].top_left = 0 * ph.pixel_count[tl_br_off].bottom_right = 0 * ph.pixel_count[tr_bl_off].top_right = 0 # <<<<<<<<<<<<<< * ph.pixel_count[tr_bl_off].bottom_left = 0 * # */ (__pyx_v_ph->pixel_count[__pyx_v_tr_bl_off]).top_right = 0; /* "centrosome/_filter.pyx":691 * ph.pixel_count[tl_br_off].bottom_right = 0 * ph.pixel_count[tr_bl_off].top_right = 0 * ph.pixel_count[tr_bl_off].bottom_left = 0 # <<<<<<<<<<<<<< * # * # Initialize the accumulator (octagon histogram) to zero */ (__pyx_v_ph->pixel_count[__pyx_v_tr_bl_off]).bottom_left = 0; /* "centrosome/_filter.pyx":695 * # Initialize the accumulator (octagon histogram) to zero * # * memset(&ph.accumulator, 0, sizeof(ph.accumulator)) # <<<<<<<<<<<<<< * ph.accumulator_count = 0 * for i in range(16): */ memset((&__pyx_v_ph->accumulator), 0, (sizeof(__pyx_v_ph->accumulator))); /* "centrosome/_filter.pyx":696 * # * memset(&ph.accumulator, 0, sizeof(ph.accumulator)) * ph.accumulator_count = 0 # <<<<<<<<<<<<<< * for i in range(16): * ph.last_update_column[i] = -radius-1 */ __pyx_v_ph->accumulator_count = 0; /* "centrosome/_filter.pyx":697 * memset(&ph.accumulator, 0, sizeof(ph.accumulator)) * ph.accumulator_count = 0 * for i in range(16): # <<<<<<<<<<<<<< * ph.last_update_column[i] = -radius-1 * # */ for (__pyx_t_4 = 0; __pyx_t_4 < 16; __pyx_t_4+=1) { __pyx_v_i = __pyx_t_4; /* "centrosome/_filter.pyx":698 * ph.accumulator_count = 0 * for i in range(16): * ph.last_update_column[i] = -radius-1 # <<<<<<<<<<<<<< * # * # Initialize the current stride to the beginning of the row */ (__pyx_v_ph->last_update_column[__pyx_v_i]) = ((-__pyx_v_radius) - 1); } /* "centrosome/_filter.pyx":702 * # Initialize the current stride to the beginning of the row * # * ph.current_row = row # <<<<<<<<<<<<<< * # * # Update locations and coarse accumulator for the octagon */ __pyx_v_ph->current_row = __pyx_v_row; /* "centrosome/_filter.pyx":707 * # for points before 0 * # * for col in range(-radius, 0 if row >=0 else columns+radius): # <<<<<<<<<<<<<< * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride */ if (((__pyx_v_row >= 0) != 0)) { __pyx_t_5 = 0; } else { __pyx_t_5 = (__pyx_v_columns + __pyx_v_radius); } for (__pyx_t_4 = (-__pyx_v_radius); __pyx_t_4 < __pyx_t_5; __pyx_t_4+=1) { __pyx_v_col = __pyx_t_4; /* "centrosome/_filter.pyx":708 * # * for col in range(-radius, 0 if row >=0 else columns+radius): * ph.current_column = col # <<<<<<<<<<<<<< * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) */ __pyx_v_ph->current_column = __pyx_v_col; /* "centrosome/_filter.pyx":709 * for col in range(-radius, 0 if row >=0 else columns+radius): * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride # <<<<<<<<<<<<<< * update_current_location(ph) * accumulate(ph) */ __pyx_v_ph->current_stride = ((__pyx_v_row * __pyx_v_row_stride) + (__pyx_v_col * __pyx_v_col_stride)); /* "centrosome/_filter.pyx":710 * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) # <<<<<<<<<<<<<< * accumulate(ph) * # */ __pyx_f_10centrosome_7_filter_update_current_location(__pyx_v_ph); /* "centrosome/_filter.pyx":711 * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) * accumulate(ph) # <<<<<<<<<<<<<< * # * # Update locations and coarse accumulator and compute */ __pyx_f_10centrosome_7_filter_accumulate(__pyx_v_ph); } /* "centrosome/_filter.pyx":716 * # the median for points between 0 and "columns" * # * if row >= 0: # <<<<<<<<<<<<<< * for col in range(0, columns): * ph.current_column = col */ __pyx_t_1 = ((__pyx_v_row >= 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":717 * # * if row >= 0: * for col in range(0, columns): # <<<<<<<<<<<<<< * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride */ __pyx_t_6 = __pyx_v_columns; for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_6; __pyx_t_4+=1) { __pyx_v_col = __pyx_t_4; /* "centrosome/_filter.pyx":718 * if row >= 0: * for col in range(0, columns): * ph.current_column = col # <<<<<<<<<<<<<< * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) */ __pyx_v_ph->current_column = __pyx_v_col; /* "centrosome/_filter.pyx":719 * for col in range(0, columns): * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride # <<<<<<<<<<<<<< * update_current_location(ph) * accumulate(ph) */ __pyx_v_ph->current_stride = ((__pyx_v_row * __pyx_v_row_stride) + (__pyx_v_col * __pyx_v_col_stride)); /* "centrosome/_filter.pyx":720 * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) # <<<<<<<<<<<<<< * accumulate(ph) * ph.output[ph.current_stride] = find_median(ph) */ __pyx_f_10centrosome_7_filter_update_current_location(__pyx_v_ph); /* "centrosome/_filter.pyx":721 * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) * accumulate(ph) # <<<<<<<<<<<<<< * ph.output[ph.current_stride] = find_median(ph) * for col in range(columns, columns+radius): */ __pyx_f_10centrosome_7_filter_accumulate(__pyx_v_ph); /* "centrosome/_filter.pyx":722 * update_current_location(ph) * accumulate(ph) * ph.output[ph.current_stride] = find_median(ph) # <<<<<<<<<<<<<< * for col in range(columns, columns+radius): * ph.current_column = col */ (__pyx_v_ph->output[__pyx_v_ph->current_stride]) = __pyx_f_10centrosome_7_filter_find_median(__pyx_v_ph); } /* "centrosome/_filter.pyx":723 * accumulate(ph) * ph.output[ph.current_stride] = find_median(ph) * for col in range(columns, columns+radius): # <<<<<<<<<<<<<< * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride */ __pyx_t_6 = (__pyx_v_columns + __pyx_v_radius); for (__pyx_t_4 = __pyx_v_columns; __pyx_t_4 < __pyx_t_6; __pyx_t_4+=1) { __pyx_v_col = __pyx_t_4; /* "centrosome/_filter.pyx":724 * ph.output[ph.current_stride] = find_median(ph) * for col in range(columns, columns+radius): * ph.current_column = col # <<<<<<<<<<<<<< * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) */ __pyx_v_ph->current_column = __pyx_v_col; /* "centrosome/_filter.pyx":725 * for col in range(columns, columns+radius): * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride # <<<<<<<<<<<<<< * update_current_location(ph) * */ __pyx_v_ph->current_stride = ((__pyx_v_row * __pyx_v_row_stride) + (__pyx_v_col * __pyx_v_col_stride)); /* "centrosome/_filter.pyx":726 * ph.current_column = col * ph.current_stride = row * row_stride + col * col_stride * update_current_location(ph) # <<<<<<<<<<<<<< * * */ __pyx_f_10centrosome_7_filter_update_current_location(__pyx_v_ph); } /* "centrosome/_filter.pyx":716 * # the median for points between 0 and "columns" * # * if row >= 0: # <<<<<<<<<<<<<< * for col in range(0, columns): * ph.current_column = col */ } } /* "centrosome/_filter.pyx":729 * * * free_histograms(ph) # <<<<<<<<<<<<<< * return 0 * */ __pyx_f_10centrosome_7_filter_free_histograms(__pyx_v_ph); /* "centrosome/_filter.pyx":730 * * free_histograms(ph) * return 0 # <<<<<<<<<<<<<< * * def median_filter(np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] data, */ __pyx_r = 0; goto __pyx_L0; /* "centrosome/_filter.pyx":647 * # * ############################################################################ * cdef int c_median_filter(np.int32_t rows, # <<<<<<<<<<<<<< * np.int32_t columns, * np.int32_t row_stride, */ /* function exit code */ __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":732 * return 0 * * def median_filter(np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] output, */ /* Python wrapper */ static PyObject *__pyx_pw_10centrosome_7_filter_1median_filter(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10centrosome_7_filter_median_filter[] = "Median filter with octagon shape and masking\n\n data - a 2d array containing the image data\n mask - a 2d array of 1=significant pixel, 0=masked\n similarly shaped to \"data\"\n output - a 2d array that will hold the output of this operation\n similarly shaped to \"data\"\n radius - the radius of the inscribed circle to the octagon\n percent - sort the unmasked pixels within the octagon into\n an array (conceptually) and take the value indexed\n by the size of that array times the percent divided by 100.\n 50 gives the median\n "; static PyMethodDef __pyx_mdef_10centrosome_7_filter_1median_filter = {"median_filter", (PyCFunction)__pyx_pw_10centrosome_7_filter_1median_filter, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10centrosome_7_filter_median_filter}; static PyObject *__pyx_pw_10centrosome_7_filter_1median_filter(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_data = 0; PyArrayObject *__pyx_v_mask = 0; PyArrayObject *__pyx_v_output = 0; int __pyx_v_radius; __pyx_t_5numpy_int32_t __pyx_v_percent; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("median_filter (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_data,&__pyx_n_s_mask,&__pyx_n_s_output,&__pyx_n_s_radius,&__pyx_n_s_percent,0}; PyObject* values[5] = {0,0,0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4); CYTHON_FALLTHROUGH; case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3); CYTHON_FALLTHROUGH; case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("median_filter", 1, 5, 5, 1); __PYX_ERR(0, 732, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_output)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("median_filter", 1, 5, 5, 2); __PYX_ERR(0, 732, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 3: if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_radius)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("median_filter", 1, 5, 5, 3); __PYX_ERR(0, 732, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 4: if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_percent)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("median_filter", 1, 5, 5, 4); __PYX_ERR(0, 732, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "median_filter") < 0)) __PYX_ERR(0, 732, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 5) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); values[3] = PyTuple_GET_ITEM(__pyx_args, 3); values[4] = PyTuple_GET_ITEM(__pyx_args, 4); } __pyx_v_data = ((PyArrayObject *)values[0]); __pyx_v_mask = ((PyArrayObject *)values[1]); __pyx_v_output = ((PyArrayObject *)values[2]); __pyx_v_radius = __Pyx_PyInt_As_int(values[3]); if (unlikely((__pyx_v_radius == (int)-1) && PyErr_Occurred())) __PYX_ERR(0, 735, __pyx_L3_error) __pyx_v_percent = __Pyx_PyInt_As_npy_int32(values[4]); if (unlikely((__pyx_v_percent == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 736, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("median_filter", 1, 5, 5, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 732, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("centrosome._filter.median_filter", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), __pyx_ptype_5numpy_ndarray, 1, "data", 0))) __PYX_ERR(0, 732, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), __pyx_ptype_5numpy_ndarray, 1, "mask", 0))) __PYX_ERR(0, 733, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_output), __pyx_ptype_5numpy_ndarray, 1, "output", 0))) __PYX_ERR(0, 734, __pyx_L1_error) __pyx_r = __pyx_pf_10centrosome_7_filter_median_filter(__pyx_self, __pyx_v_data, __pyx_v_mask, __pyx_v_output, __pyx_v_radius, __pyx_v_percent); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10centrosome_7_filter_median_filter(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_mask, PyArrayObject *__pyx_v_output, int __pyx_v_radius, __pyx_t_5numpy_int32_t __pyx_v_percent) { __Pyx_LocalBuf_ND __pyx_pybuffernd_data; __Pyx_Buffer __pyx_pybuffer_data; __Pyx_LocalBuf_ND __pyx_pybuffernd_mask; __Pyx_Buffer __pyx_pybuffer_mask; __Pyx_LocalBuf_ND __pyx_pybuffernd_output; __Pyx_Buffer __pyx_pybuffer_output; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; __Pyx_RefNannySetupContext("median_filter", 0); __pyx_pybuffer_data.pybuffer.buf = NULL; __pyx_pybuffer_data.refcount = 0; __pyx_pybuffernd_data.data = NULL; __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; __pyx_pybuffer_mask.pybuffer.buf = NULL; __pyx_pybuffer_mask.refcount = 0; __pyx_pybuffernd_mask.data = NULL; __pyx_pybuffernd_mask.rcbuffer = &__pyx_pybuffer_mask; __pyx_pybuffer_output.pybuffer.buf = NULL; __pyx_pybuffer_output.refcount = 0; __pyx_pybuffernd_output.data = NULL; __pyx_pybuffernd_output.rcbuffer = &__pyx_pybuffer_output; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 732, __pyx_L1_error) } __pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_data.diminfo[1].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_data.diminfo[1].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mask.rcbuffer->pybuffer, (PyObject*)__pyx_v_mask, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 732, __pyx_L1_error) } __pyx_pybuffernd_mask.diminfo[0].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mask.diminfo[0].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_mask.diminfo[1].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_mask.diminfo[1].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_output.rcbuffer->pybuffer, (PyObject*)__pyx_v_output, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 732, __pyx_L1_error) } __pyx_pybuffernd_output.diminfo[0].strides = __pyx_pybuffernd_output.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_output.diminfo[0].shape = __pyx_pybuffernd_output.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_output.diminfo[1].strides = __pyx_pybuffernd_output.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_output.diminfo[1].shape = __pyx_pybuffernd_output.rcbuffer->pybuffer.shape[1]; /* "centrosome/_filter.pyx":750 * 50 gives the median * """ * if percent < 0: # <<<<<<<<<<<<<< * raise ValueError('Median filter percent = %d is less than zero'%percent) * if percent > 100: */ __pyx_t_1 = ((__pyx_v_percent < 0) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":751 * """ * if percent < 0: * raise ValueError('Median filter percent = %d is less than zero'%percent) # <<<<<<<<<<<<<< * if percent > 100: * raise ValueError('Median filter percent = %d is greater than 100'%percent) */ __pyx_t_2 = __Pyx_PyInt_From_npy_int32(__pyx_v_percent); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 751, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Median_filter_percent_d_is_less, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 751, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 751, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 751, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(0, 751, __pyx_L1_error) /* "centrosome/_filter.pyx":750 * 50 gives the median * """ * if percent < 0: # <<<<<<<<<<<<<< * raise ValueError('Median filter percent = %d is less than zero'%percent) * if percent > 100: */ } /* "centrosome/_filter.pyx":752 * if percent < 0: * raise ValueError('Median filter percent = %d is less than zero'%percent) * if percent > 100: # <<<<<<<<<<<<<< * raise ValueError('Median filter percent = %d is greater than 100'%percent) * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: */ __pyx_t_1 = ((__pyx_v_percent > 0x64) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":753 * raise ValueError('Median filter percent = %d is less than zero'%percent) * if percent > 100: * raise ValueError('Median filter percent = %d is greater than 100'%percent) # <<<<<<<<<<<<<< * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% */ __pyx_t_3 = __Pyx_PyInt_From_npy_int32(__pyx_v_percent); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 753, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyString_Format(__pyx_kp_s_Median_filter_percent_d_is_great, __pyx_t_3); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 753, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 753, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 753, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_2, 0, 0, 0); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __PYX_ERR(0, 753, __pyx_L1_error) /* "centrosome/_filter.pyx":752 * if percent < 0: * raise ValueError('Median filter percent = %d is less than zero'%percent) * if percent > 100: # <<<<<<<<<<<<<< * raise ValueError('Median filter percent = %d is greater than 100'%percent) * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: */ } /* "centrosome/_filter.pyx":754 * if percent > 100: * raise ValueError('Median filter percent = %d is greater than 100'%percent) * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: # <<<<<<<<<<<<<< * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% * (data.shape[0],data.shape[1], */ __pyx_t_4 = (((__pyx_v_data->dimensions[0]) != (__pyx_v_mask->dimensions[0])) != 0); if (!__pyx_t_4) { } else { __pyx_t_1 = __pyx_t_4; goto __pyx_L6_bool_binop_done; } __pyx_t_4 = (((__pyx_v_data->dimensions[1]) != (__pyx_v_mask->dimensions[1])) != 0); __pyx_t_1 = __pyx_t_4; __pyx_L6_bool_binop_done:; if (__pyx_t_1) { /* "centrosome/_filter.pyx":756 * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% * (data.shape[0],data.shape[1], # <<<<<<<<<<<<<< * mask.shape[0], mask.shape[1])) * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: */ __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[0])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 756, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[1])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 756, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "centrosome/_filter.pyx":757 * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% * (data.shape[0],data.shape[1], * mask.shape[0], mask.shape[1])) # <<<<<<<<<<<<<< * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% */ __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_mask->dimensions[0])); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 757, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_mask->dimensions[1])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 757, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); /* "centrosome/_filter.pyx":756 * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% * (data.shape[0],data.shape[1], # <<<<<<<<<<<<<< * mask.shape[0], mask.shape[1])) * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: */ __pyx_t_7 = PyTuple_New(4); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 756, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_7, 1, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 3, __pyx_t_6); __pyx_t_2 = 0; __pyx_t_3 = 0; __pyx_t_5 = 0; __pyx_t_6 = 0; /* "centrosome/_filter.pyx":755 * raise ValueError('Median filter percent = %d is greater than 100'%percent) * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% # <<<<<<<<<<<<<< * (data.shape[0],data.shape[1], * mask.shape[0], mask.shape[1])) */ __pyx_t_6 = __Pyx_PyString_Format(__pyx_kp_s_Data_shape_d_d_is_not_mask_shape, __pyx_t_7); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 755, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 755, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 755, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(0, 755, __pyx_L1_error) /* "centrosome/_filter.pyx":754 * if percent > 100: * raise ValueError('Median filter percent = %d is greater than 100'%percent) * if data.shape[0] != mask.shape[0] or data.shape[1] != mask.shape[1]: # <<<<<<<<<<<<<< * raise ValueError('Data shape (%d,%d) is not mask shape (%d,%d)'% * (data.shape[0],data.shape[1], */ } /* "centrosome/_filter.pyx":758 * (data.shape[0],data.shape[1], * mask.shape[0], mask.shape[1])) * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: # <<<<<<<<<<<<<< * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% * (data.shape[0],data.shape[1], */ __pyx_t_4 = (((__pyx_v_data->dimensions[0]) != (__pyx_v_output->dimensions[0])) != 0); if (!__pyx_t_4) { } else { __pyx_t_1 = __pyx_t_4; goto __pyx_L9_bool_binop_done; } __pyx_t_4 = (((__pyx_v_data->dimensions[1]) != (__pyx_v_output->dimensions[1])) != 0); __pyx_t_1 = __pyx_t_4; __pyx_L9_bool_binop_done:; if (__pyx_t_1) { /* "centrosome/_filter.pyx":760 * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% * (data.shape[0],data.shape[1], # <<<<<<<<<<<<<< * output.shape[0], output.shape[1])) * if c_median_filter(data.shape[0], data.shape[1], */ __pyx_t_6 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[0])); if (unlikely(!__pyx_t_6)) __PYX_ERR(0, 760, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[1])); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 760, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); /* "centrosome/_filter.pyx":761 * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% * (data.shape[0],data.shape[1], * output.shape[0], output.shape[1])) # <<<<<<<<<<<<<< * if c_median_filter(data.shape[0], data.shape[1], * data.strides[0], data.strides[1], */ __pyx_t_5 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_output->dimensions[0])); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 761, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_output->dimensions[1])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 761, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); /* "centrosome/_filter.pyx":760 * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% * (data.shape[0],data.shape[1], # <<<<<<<<<<<<<< * output.shape[0], output.shape[1])) * if c_median_filter(data.shape[0], data.shape[1], */ __pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 760, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_6); __Pyx_GIVEREF(__pyx_t_7); PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_7); __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3); __pyx_t_6 = 0; __pyx_t_7 = 0; __pyx_t_5 = 0; __pyx_t_3 = 0; /* "centrosome/_filter.pyx":759 * mask.shape[0], mask.shape[1])) * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% # <<<<<<<<<<<<<< * (data.shape[0],data.shape[1], * output.shape[0], output.shape[1])) */ __pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Data_shape_d_d_is_not_output_sha, __pyx_t_2); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 759, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 759, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 759, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(0, 759, __pyx_L1_error) /* "centrosome/_filter.pyx":758 * (data.shape[0],data.shape[1], * mask.shape[0], mask.shape[1])) * if data.shape[0] != output.shape[0] or data.shape[1] != output.shape[1]: # <<<<<<<<<<<<<< * raise ValueError('Data shape (%d,%d) is not output shape (%d,%d)'% * (data.shape[0],data.shape[1], */ } /* "centrosome/_filter.pyx":762 * (data.shape[0],data.shape[1], * output.shape[0], output.shape[1])) * if c_median_filter(data.shape[0], data.shape[1], # <<<<<<<<<<<<<< * data.strides[0], data.strides[1], * radius, percent, */ __pyx_t_1 = (__pyx_f_10centrosome_7_filter_c_median_filter((__pyx_v_data->dimensions[0]), (__pyx_v_data->dimensions[1]), (__pyx_v_data->strides[0]), (__pyx_v_data->strides[1]), __pyx_v_radius, __pyx_v_percent, ((__pyx_t_5numpy_uint8_t *)__pyx_v_data->data), ((__pyx_t_5numpy_uint8_t *)__pyx_v_mask->data), ((__pyx_t_5numpy_uint8_t *)__pyx_v_output->data)) != 0); if (__pyx_t_1) { /* "centrosome/_filter.pyx":768 * <np.uint8_t *>mask.data, * <np.uint8_t *>output.data): * raise MemoryError('Failed to allocate scratchpad memory') # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple_, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 768, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(0, 768, __pyx_L1_error) /* "centrosome/_filter.pyx":762 * (data.shape[0],data.shape[1], * output.shape[0], output.shape[1])) * if c_median_filter(data.shape[0], data.shape[1], # <<<<<<<<<<<<<< * data.strides[0], data.strides[1], * radius, percent, */ } /* "centrosome/_filter.pyx":732 * return 0 * * def median_filter(np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] output, */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_output.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("centrosome._filter.median_filter", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_output.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":771 * * @cython.boundscheck(False) * def masked_convolution(np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] kernel): */ /* Python wrapper */ static PyObject *__pyx_pw_10centrosome_7_filter_3masked_convolution(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10centrosome_7_filter_2masked_convolution[] = "Convolution respecting a mask\n\n data - a 2d array containing the image data\n mask - a mask of relevant points.\n kernel - a square convolution kernel of odd dimension\n "; static PyMethodDef __pyx_mdef_10centrosome_7_filter_3masked_convolution = {"masked_convolution", (PyCFunction)__pyx_pw_10centrosome_7_filter_3masked_convolution, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10centrosome_7_filter_2masked_convolution}; static PyObject *__pyx_pw_10centrosome_7_filter_3masked_convolution(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_data = 0; PyArrayObject *__pyx_v_mask = 0; PyArrayObject *__pyx_v_kernel = 0; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("masked_convolution (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_data,&__pyx_n_s_mask,&__pyx_n_s_kernel,0}; PyObject* values[3] = {0,0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2); CYTHON_FALLTHROUGH; case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_data)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mask)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("masked_convolution", 1, 3, 3, 1); __PYX_ERR(0, 771, __pyx_L3_error) } CYTHON_FALLTHROUGH; case 2: if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kernel)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("masked_convolution", 1, 3, 3, 2); __PYX_ERR(0, 771, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "masked_convolution") < 0)) __PYX_ERR(0, 771, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 3) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); values[2] = PyTuple_GET_ITEM(__pyx_args, 2); } __pyx_v_data = ((PyArrayObject *)values[0]); __pyx_v_mask = ((PyArrayObject *)values[1]); __pyx_v_kernel = ((PyArrayObject *)values[2]); } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("masked_convolution", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 771, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("centrosome._filter.masked_convolution", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_data), __pyx_ptype_5numpy_ndarray, 1, "data", 0))) __PYX_ERR(0, 771, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_mask), __pyx_ptype_5numpy_ndarray, 1, "mask", 0))) __PYX_ERR(0, 772, __pyx_L1_error) if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_kernel), __pyx_ptype_5numpy_ndarray, 1, "kernel", 0))) __PYX_ERR(0, 773, __pyx_L1_error) __pyx_r = __pyx_pf_10centrosome_7_filter_2masked_convolution(__pyx_self, __pyx_v_data, __pyx_v_mask, __pyx_v_kernel); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10centrosome_7_filter_2masked_convolution(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_data, PyArrayObject *__pyx_v_mask, PyArrayObject *__pyx_v_kernel) { __pyx_t_5numpy_float64_t *__pyx_v_pkernel; __pyx_t_5numpy_float64_t *__pyx_v_pimage; __pyx_t_5numpy_uint8_t *__pyx_v_pmask; __pyx_t_5numpy_float64_t *__pyx_v_poutput; int __pyx_v_kernel_width; int __pyx_v_kernel_half_width; int __pyx_v_i; int __pyx_v_j; int __pyx_v_ik; int __pyx_v_jk; int __pyx_v_istride; int __pyx_v_mstride; int __pyx_v_kstride; __pyx_t_5numpy_float64_t __pyx_v_accumulator; PyArrayObject *__pyx_v_big_mask = 0; PyArrayObject *__pyx_v_output = 0; __Pyx_LocalBuf_ND __pyx_pybuffernd_big_mask; __Pyx_Buffer __pyx_pybuffer_big_mask; __Pyx_LocalBuf_ND __pyx_pybuffernd_data; __Pyx_Buffer __pyx_pybuffer_data; __Pyx_LocalBuf_ND __pyx_pybuffernd_kernel; __Pyx_Buffer __pyx_pybuffer_kernel; __Pyx_LocalBuf_ND __pyx_pybuffernd_mask; __Pyx_Buffer __pyx_pybuffer_mask; __Pyx_LocalBuf_ND __pyx_pybuffernd_output; __Pyx_Buffer __pyx_pybuffer_output; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; PyObject *__pyx_t_5 = NULL; int __pyx_t_6; PyObject *__pyx_t_7 = NULL; PyArrayObject *__pyx_t_8 = NULL; PyObject *__pyx_t_9 = NULL; PyObject *__pyx_t_10 = NULL; PyObject *__pyx_t_11 = NULL; PyArrayObject *__pyx_t_12 = NULL; npy_intp __pyx_t_13; npy_intp __pyx_t_14; int __pyx_t_15; int __pyx_t_16; long __pyx_t_17; int __pyx_t_18; long __pyx_t_19; int __pyx_t_20; __Pyx_RefNannySetupContext("masked_convolution", 0); __pyx_pybuffer_big_mask.pybuffer.buf = NULL; __pyx_pybuffer_big_mask.refcount = 0; __pyx_pybuffernd_big_mask.data = NULL; __pyx_pybuffernd_big_mask.rcbuffer = &__pyx_pybuffer_big_mask; __pyx_pybuffer_output.pybuffer.buf = NULL; __pyx_pybuffer_output.refcount = 0; __pyx_pybuffernd_output.data = NULL; __pyx_pybuffernd_output.rcbuffer = &__pyx_pybuffer_output; __pyx_pybuffer_data.pybuffer.buf = NULL; __pyx_pybuffer_data.refcount = 0; __pyx_pybuffernd_data.data = NULL; __pyx_pybuffernd_data.rcbuffer = &__pyx_pybuffer_data; __pyx_pybuffer_mask.pybuffer.buf = NULL; __pyx_pybuffer_mask.refcount = 0; __pyx_pybuffernd_mask.data = NULL; __pyx_pybuffernd_mask.rcbuffer = &__pyx_pybuffer_mask; __pyx_pybuffer_kernel.pybuffer.buf = NULL; __pyx_pybuffer_kernel.refcount = 0; __pyx_pybuffernd_kernel.data = NULL; __pyx_pybuffernd_kernel.rcbuffer = &__pyx_pybuffer_kernel; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_data.rcbuffer->pybuffer, (PyObject*)__pyx_v_data, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 771, __pyx_L1_error) } __pyx_pybuffernd_data.diminfo[0].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_data.diminfo[0].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_data.diminfo[1].strides = __pyx_pybuffernd_data.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_data.diminfo[1].shape = __pyx_pybuffernd_data.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_mask.rcbuffer->pybuffer, (PyObject*)__pyx_v_mask, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 771, __pyx_L1_error) } __pyx_pybuffernd_mask.diminfo[0].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_mask.diminfo[0].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_mask.diminfo[1].strides = __pyx_pybuffernd_mask.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_mask.diminfo[1].shape = __pyx_pybuffernd_mask.rcbuffer->pybuffer.shape[1]; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_kernel.rcbuffer->pybuffer, (PyObject*)__pyx_v_kernel, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) __PYX_ERR(0, 771, __pyx_L1_error) } __pyx_pybuffernd_kernel.diminfo[0].strides = __pyx_pybuffernd_kernel.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_kernel.diminfo[0].shape = __pyx_pybuffernd_kernel.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_kernel.diminfo[1].strides = __pyx_pybuffernd_kernel.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_kernel.diminfo[1].shape = __pyx_pybuffernd_kernel.rcbuffer->pybuffer.shape[1]; /* "centrosome/_filter.pyx":797 * np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] output * * assert kernel.shape[0] % 2 == 1, "Kernel shape must be odd" # <<<<<<<<<<<<<< * assert kernel.shape[0]==kernel.shape[1], "Kernel must be square" * assert mask.shape[0]==data.shape[0] */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!((__Pyx_mod_long((__pyx_v_kernel->dimensions[0]), 2) == 1) != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_Kernel_shape_must_be_odd); __PYX_ERR(0, 797, __pyx_L1_error) } } #endif /* "centrosome/_filter.pyx":798 * * assert kernel.shape[0] % 2 == 1, "Kernel shape must be odd" * assert kernel.shape[0]==kernel.shape[1], "Kernel must be square" # <<<<<<<<<<<<<< * assert mask.shape[0]==data.shape[0] * assert mask.shape[1]==data.shape[1] */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!(((__pyx_v_kernel->dimensions[0]) == (__pyx_v_kernel->dimensions[1])) != 0))) { PyErr_SetObject(PyExc_AssertionError, __pyx_kp_s_Kernel_must_be_square); __PYX_ERR(0, 798, __pyx_L1_error) } } #endif /* "centrosome/_filter.pyx":799 * assert kernel.shape[0] % 2 == 1, "Kernel shape must be odd" * assert kernel.shape[0]==kernel.shape[1], "Kernel must be square" * assert mask.shape[0]==data.shape[0] # <<<<<<<<<<<<<< * assert mask.shape[1]==data.shape[1] * kernel_width = kernel.shape[0] */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!(((__pyx_v_mask->dimensions[0]) == (__pyx_v_data->dimensions[0])) != 0))) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 799, __pyx_L1_error) } } #endif /* "centrosome/_filter.pyx":800 * assert kernel.shape[0]==kernel.shape[1], "Kernel must be square" * assert mask.shape[0]==data.shape[0] * assert mask.shape[1]==data.shape[1] # <<<<<<<<<<<<<< * kernel_width = kernel.shape[0] * kernel_half_width = kernel_width / 2 */ #ifndef CYTHON_WITHOUT_ASSERTIONS if (unlikely(!Py_OptimizeFlag)) { if (unlikely(!(((__pyx_v_mask->dimensions[1]) == (__pyx_v_data->dimensions[1])) != 0))) { PyErr_SetNone(PyExc_AssertionError); __PYX_ERR(0, 800, __pyx_L1_error) } } #endif /* "centrosome/_filter.pyx":801 * assert mask.shape[0]==data.shape[0] * assert mask.shape[1]==data.shape[1] * kernel_width = kernel.shape[0] # <<<<<<<<<<<<<< * kernel_half_width = kernel_width / 2 * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) */ __pyx_v_kernel_width = (__pyx_v_kernel->dimensions[0]); /* "centrosome/_filter.pyx":802 * assert mask.shape[1]==data.shape[1] * kernel_width = kernel.shape[0] * kernel_half_width = kernel_width / 2 # <<<<<<<<<<<<<< * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) */ __pyx_v_kernel_half_width = __Pyx_div_long(__pyx_v_kernel_width, 2); /* "centrosome/_filter.pyx":803 * kernel_width = kernel.shape[0] * kernel_half_width = kernel_width / 2 * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) # <<<<<<<<<<<<<< * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) * big_mask[kernel_half_width:kernel_half_width+data.shape[0], */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_zeros); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t(((__pyx_v_data->dimensions[0]) + __pyx_v_kernel_width)); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_4 = __Pyx_PyInt_From_Py_intptr_t(((__pyx_v_data->dimensions[1]) + __pyx_v_kernel_width)); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_2); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_4); __pyx_t_2 = 0; __pyx_t_4 = 0; __pyx_t_4 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_4, __pyx_n_s_uint8); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_4 = NULL; __pyx_t_6 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_3))) { __pyx_t_4 = PyMethod_GET_SELF(__pyx_t_3); if (likely(__pyx_t_4)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_3, function); __pyx_t_6 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_t_5, __pyx_t_2}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_3)) { PyObject *__pyx_temp[3] = {__pyx_t_4, __pyx_t_5, __pyx_t_2}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_3, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_7 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); if (__pyx_t_4) { __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_4); __pyx_t_4 = NULL; } __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_7, 0+__pyx_t_6, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_7, 1+__pyx_t_6, __pyx_t_2); __pyx_t_5 = 0; __pyx_t_2 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_3, __pyx_t_7, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 803, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; } __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 803, __pyx_L1_error) __pyx_t_8 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_big_mask.rcbuffer->pybuffer); __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_big_mask.rcbuffer->pybuffer, (PyObject*)__pyx_t_8, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); if (unlikely(__pyx_t_6 < 0)) { PyErr_Fetch(&__pyx_t_9, &__pyx_t_10, &__pyx_t_11); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_big_mask.rcbuffer->pybuffer, (PyObject*)__pyx_v_big_mask, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_9); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_11); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_9, __pyx_t_10, __pyx_t_11); } __pyx_t_9 = __pyx_t_10 = __pyx_t_11 = 0; } __pyx_pybuffernd_big_mask.diminfo[0].strides = __pyx_pybuffernd_big_mask.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_big_mask.diminfo[0].shape = __pyx_pybuffernd_big_mask.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_big_mask.diminfo[1].strides = __pyx_pybuffernd_big_mask.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_big_mask.diminfo[1].shape = __pyx_pybuffernd_big_mask.rcbuffer->pybuffer.shape[1]; if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 803, __pyx_L1_error) } __pyx_t_8 = 0; __pyx_v_big_mask = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":804 * kernel_half_width = kernel_width / 2 * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) # <<<<<<<<<<<<<< * big_mask[kernel_half_width:kernel_half_width+data.shape[0], * kernel_half_width:kernel_half_width+data.shape[1]] = mask */ __pyx_t_3 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_7 = __Pyx_PyObject_GetAttrStr(__pyx_t_3, __pyx_n_s_zeros); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_2 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_data->dimensions[1])); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_5 = PyTuple_New(2); if (unlikely(!__pyx_t_5)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_3); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2); __pyx_t_3 = 0; __pyx_t_2 = 0; __pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_data), __pyx_n_s_dtype); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_3 = NULL; __pyx_t_6 = 0; if (CYTHON_UNPACK_METHODS && unlikely(PyMethod_Check(__pyx_t_7))) { __pyx_t_3 = PyMethod_GET_SELF(__pyx_t_7); if (likely(__pyx_t_3)) { PyObject* function = PyMethod_GET_FUNCTION(__pyx_t_7); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(function); __Pyx_DECREF_SET(__pyx_t_7, function); __pyx_t_6 = 1; } } #if CYTHON_FAST_PYCALL if (PyFunction_Check(__pyx_t_7)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_5, __pyx_t_2}; __pyx_t_1 = __Pyx_PyFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif #if CYTHON_FAST_PYCCALL if (__Pyx_PyFastCFunction_Check(__pyx_t_7)) { PyObject *__pyx_temp[3] = {__pyx_t_3, __pyx_t_5, __pyx_t_2}; __pyx_t_1 = __Pyx_PyCFunction_FastCall(__pyx_t_7, __pyx_temp+1-__pyx_t_6, 2+__pyx_t_6); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0; __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; } else #endif { __pyx_t_4 = PyTuple_New(2+__pyx_t_6); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); if (__pyx_t_3) { __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = NULL; } __Pyx_GIVEREF(__pyx_t_5); PyTuple_SET_ITEM(__pyx_t_4, 0+__pyx_t_6, __pyx_t_5); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_4, 1+__pyx_t_6, __pyx_t_2); __pyx_t_5 = 0; __pyx_t_2 = 0; __pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_7, __pyx_t_4, NULL); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 804, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; } __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_ptype_5numpy_ndarray))))) __PYX_ERR(0, 804, __pyx_L1_error) __pyx_t_12 = ((PyArrayObject *)__pyx_t_1); { __Pyx_BufFmt_StackElem __pyx_stack[1]; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_output.rcbuffer->pybuffer); __pyx_t_6 = __Pyx_GetBufferAndValidate(&__pyx_pybuffernd_output.rcbuffer->pybuffer, (PyObject*)__pyx_t_12, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack); if (unlikely(__pyx_t_6 < 0)) { PyErr_Fetch(&__pyx_t_11, &__pyx_t_10, &__pyx_t_9); if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_output.rcbuffer->pybuffer, (PyObject*)__pyx_v_output, &__Pyx_TypeInfo_nn___pyx_t_5numpy_float64_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 2, 0, __pyx_stack) == -1)) { Py_XDECREF(__pyx_t_11); Py_XDECREF(__pyx_t_10); Py_XDECREF(__pyx_t_9); __Pyx_RaiseBufferFallbackError(); } else { PyErr_Restore(__pyx_t_11, __pyx_t_10, __pyx_t_9); } __pyx_t_11 = __pyx_t_10 = __pyx_t_9 = 0; } __pyx_pybuffernd_output.diminfo[0].strides = __pyx_pybuffernd_output.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_output.diminfo[0].shape = __pyx_pybuffernd_output.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_output.diminfo[1].strides = __pyx_pybuffernd_output.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_output.diminfo[1].shape = __pyx_pybuffernd_output.rcbuffer->pybuffer.shape[1]; if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(0, 804, __pyx_L1_error) } __pyx_t_12 = 0; __pyx_v_output = ((PyArrayObject *)__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":805 * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) * big_mask[kernel_half_width:kernel_half_width+data.shape[0], # <<<<<<<<<<<<<< * kernel_half_width:kernel_half_width+data.shape[1]] = mask * # */ __pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_kernel_half_width); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_7 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_kernel_half_width + (__pyx_v_data->dimensions[0]))); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_4 = PySlice_New(__pyx_t_1, __pyx_t_7, Py_None); if (unlikely(!__pyx_t_4)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; /* "centrosome/_filter.pyx":806 * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) * big_mask[kernel_half_width:kernel_half_width+data.shape[0], * kernel_half_width:kernel_half_width+data.shape[1]] = mask # <<<<<<<<<<<<<< * # * # stride in number of elements across the i direction */ __pyx_t_7 = __Pyx_PyInt_From_int(__pyx_v_kernel_half_width); if (unlikely(!__pyx_t_7)) __PYX_ERR(0, 806, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_7); __pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t((__pyx_v_kernel_half_width + (__pyx_v_data->dimensions[1]))); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 806, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); /* "centrosome/_filter.pyx":805 * big_mask = np.zeros((data.shape[0]+kernel_width, data.shape[1]+kernel_width), np.uint8) * output = np.zeros((data.shape[0],data.shape[1]), data.dtype) * big_mask[kernel_half_width:kernel_half_width+data.shape[0], # <<<<<<<<<<<<<< * kernel_half_width:kernel_half_width+data.shape[1]] = mask * # */ __pyx_t_2 = PySlice_New(__pyx_t_7, __pyx_t_1, Py_None); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0; __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; __pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_GIVEREF(__pyx_t_4); PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_4); __Pyx_GIVEREF(__pyx_t_2); PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_t_2); __pyx_t_4 = 0; __pyx_t_2 = 0; if (unlikely(PyObject_SetItem(((PyObject *)__pyx_v_big_mask), __pyx_t_1, ((PyObject *)__pyx_v_mask)) < 0)) __PYX_ERR(0, 805, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":810 * # stride in number of elements across the i direction * # * istride = data.strides[0] / PyArray_ITEMSIZE(data) # <<<<<<<<<<<<<< * mstride = big_mask.strides[0] / PyArray_ITEMSIZE(big_mask) * kstride = kernel.strides[0] / PyArray_ITEMSIZE(kernel) */ __pyx_t_6 = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_data)); if (unlikely(__pyx_t_6 == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 810, __pyx_L1_error) } else if (sizeof(npy_intp) == sizeof(long) && (!(((int)-1) > 0)) && unlikely(__pyx_t_6 == (int)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW((__pyx_v_data->strides[0])))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(0, 810, __pyx_L1_error) } __pyx_v_istride = __Pyx_div_npy_intp((__pyx_v_data->strides[0]), __pyx_t_6); /* "centrosome/_filter.pyx":811 * # * istride = data.strides[0] / PyArray_ITEMSIZE(data) * mstride = big_mask.strides[0] / PyArray_ITEMSIZE(big_mask) # <<<<<<<<<<<<<< * kstride = kernel.strides[0] / PyArray_ITEMSIZE(kernel) * # */ __pyx_t_6 = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_big_mask)); if (unlikely(__pyx_t_6 == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 811, __pyx_L1_error) } else if (sizeof(npy_intp) == sizeof(long) && (!(((int)-1) > 0)) && unlikely(__pyx_t_6 == (int)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW((__pyx_v_big_mask->strides[0])))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(0, 811, __pyx_L1_error) } __pyx_v_mstride = __Pyx_div_npy_intp((__pyx_v_big_mask->strides[0]), __pyx_t_6); /* "centrosome/_filter.pyx":812 * istride = data.strides[0] / PyArray_ITEMSIZE(data) * mstride = big_mask.strides[0] / PyArray_ITEMSIZE(big_mask) * kstride = kernel.strides[0] / PyArray_ITEMSIZE(kernel) # <<<<<<<<<<<<<< * # * # pointers to data. pmask is offset to point at the 0,0 element */ __pyx_t_6 = PyArray_ITEMSIZE(((PyArrayObject *)__pyx_v_kernel)); if (unlikely(__pyx_t_6 == 0)) { PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero"); __PYX_ERR(0, 812, __pyx_L1_error) } else if (sizeof(npy_intp) == sizeof(long) && (!(((int)-1) > 0)) && unlikely(__pyx_t_6 == (int)-1) && unlikely(UNARY_NEG_WOULD_OVERFLOW((__pyx_v_kernel->strides[0])))) { PyErr_SetString(PyExc_OverflowError, "value too large to perform division"); __PYX_ERR(0, 812, __pyx_L1_error) } __pyx_v_kstride = __Pyx_div_npy_intp((__pyx_v_kernel->strides[0]), __pyx_t_6); /* "centrosome/_filter.pyx":817 * # pkernel is offset to point at the middle of the kernel * # * pmask = <np.uint8_t *>(big_mask.data + kernel_half_width * # <<<<<<<<<<<<<< * (big_mask.strides[0] + big_mask.strides[1])) * pimage = <np.float64_t *>(data.data) */ __pyx_v_pmask = ((__pyx_t_5numpy_uint8_t *)(__pyx_v_big_mask->data + (__pyx_v_kernel_half_width * ((__pyx_v_big_mask->strides[0]) + (__pyx_v_big_mask->strides[1]))))); /* "centrosome/_filter.pyx":819 * pmask = <np.uint8_t *>(big_mask.data + kernel_half_width * * (big_mask.strides[0] + big_mask.strides[1])) * pimage = <np.float64_t *>(data.data) # <<<<<<<<<<<<<< * pkernel = <np.float64_t *>(kernel.data)+(kstride+1) * kernel_half_width * poutput = <np.float64_t *>(output.data) */ __pyx_v_pimage = ((__pyx_t_5numpy_float64_t *)__pyx_v_data->data); /* "centrosome/_filter.pyx":820 * (big_mask.strides[0] + big_mask.strides[1])) * pimage = <np.float64_t *>(data.data) * pkernel = <np.float64_t *>(kernel.data)+(kstride+1) * kernel_half_width # <<<<<<<<<<<<<< * poutput = <np.float64_t *>(output.data) * for i in range(data.shape[0]): */ __pyx_v_pkernel = (((__pyx_t_5numpy_float64_t *)__pyx_v_kernel->data) + ((__pyx_v_kstride + 1) * __pyx_v_kernel_half_width)); /* "centrosome/_filter.pyx":821 * pimage = <np.float64_t *>(data.data) * pkernel = <np.float64_t *>(kernel.data)+(kstride+1) * kernel_half_width * poutput = <np.float64_t *>(output.data) # <<<<<<<<<<<<<< * for i in range(data.shape[0]): * for j in range(data.shape[1]): */ __pyx_v_poutput = ((__pyx_t_5numpy_float64_t *)__pyx_v_output->data); /* "centrosome/_filter.pyx":822 * pkernel = <np.float64_t *>(kernel.data)+(kstride+1) * kernel_half_width * poutput = <np.float64_t *>(output.data) * for i in range(data.shape[0]): # <<<<<<<<<<<<<< * for j in range(data.shape[1]): * if pmask[i*mstride+j] == 0: */ __pyx_t_13 = (__pyx_v_data->dimensions[0]); for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_13; __pyx_t_6+=1) { __pyx_v_i = __pyx_t_6; /* "centrosome/_filter.pyx":823 * poutput = <np.float64_t *>(output.data) * for i in range(data.shape[0]): * for j in range(data.shape[1]): # <<<<<<<<<<<<<< * if pmask[i*mstride+j] == 0: * continue */ __pyx_t_14 = (__pyx_v_data->dimensions[1]); for (__pyx_t_15 = 0; __pyx_t_15 < __pyx_t_14; __pyx_t_15+=1) { __pyx_v_j = __pyx_t_15; /* "centrosome/_filter.pyx":824 * for i in range(data.shape[0]): * for j in range(data.shape[1]): * if pmask[i*mstride+j] == 0: # <<<<<<<<<<<<<< * continue * accumulator = 0 */ __pyx_t_16 = (((__pyx_v_pmask[((__pyx_v_i * __pyx_v_mstride) + __pyx_v_j)]) == 0) != 0); if (__pyx_t_16) { /* "centrosome/_filter.pyx":825 * for j in range(data.shape[1]): * if pmask[i*mstride+j] == 0: * continue # <<<<<<<<<<<<<< * accumulator = 0 * for ik in range(-kernel_half_width,kernel_half_width+1): */ goto __pyx_L5_continue; /* "centrosome/_filter.pyx":824 * for i in range(data.shape[0]): * for j in range(data.shape[1]): * if pmask[i*mstride+j] == 0: # <<<<<<<<<<<<<< * continue * accumulator = 0 */ } /* "centrosome/_filter.pyx":826 * if pmask[i*mstride+j] == 0: * continue * accumulator = 0 # <<<<<<<<<<<<<< * for ik in range(-kernel_half_width,kernel_half_width+1): * for jk in range(-kernel_half_width,kernel_half_width+1): */ __pyx_v_accumulator = 0.0; /* "centrosome/_filter.pyx":827 * continue * accumulator = 0 * for ik in range(-kernel_half_width,kernel_half_width+1): # <<<<<<<<<<<<<< * for jk in range(-kernel_half_width,kernel_half_width+1): * if pmask[(i+ik)*mstride+j+jk] != 0: */ __pyx_t_17 = (__pyx_v_kernel_half_width + 1); for (__pyx_t_18 = (-__pyx_v_kernel_half_width); __pyx_t_18 < __pyx_t_17; __pyx_t_18+=1) { __pyx_v_ik = __pyx_t_18; /* "centrosome/_filter.pyx":828 * accumulator = 0 * for ik in range(-kernel_half_width,kernel_half_width+1): * for jk in range(-kernel_half_width,kernel_half_width+1): # <<<<<<<<<<<<<< * if pmask[(i+ik)*mstride+j+jk] != 0: * accumulator += (pkernel[ik*kstride+jk] * */ __pyx_t_19 = (__pyx_v_kernel_half_width + 1); for (__pyx_t_20 = (-__pyx_v_kernel_half_width); __pyx_t_20 < __pyx_t_19; __pyx_t_20+=1) { __pyx_v_jk = __pyx_t_20; /* "centrosome/_filter.pyx":829 * for ik in range(-kernel_half_width,kernel_half_width+1): * for jk in range(-kernel_half_width,kernel_half_width+1): * if pmask[(i+ik)*mstride+j+jk] != 0: # <<<<<<<<<<<<<< * accumulator += (pkernel[ik*kstride+jk] * * pimage[(i+ik)*istride+j+jk]) */ __pyx_t_16 = (((__pyx_v_pmask[((((__pyx_v_i + __pyx_v_ik) * __pyx_v_mstride) + __pyx_v_j) + __pyx_v_jk)]) != 0) != 0); if (__pyx_t_16) { /* "centrosome/_filter.pyx":830 * for jk in range(-kernel_half_width,kernel_half_width+1): * if pmask[(i+ik)*mstride+j+jk] != 0: * accumulator += (pkernel[ik*kstride+jk] * # <<<<<<<<<<<<<< * pimage[(i+ik)*istride+j+jk]) * poutput[i*istride+j] = accumulator */ __pyx_v_accumulator = (__pyx_v_accumulator + ((__pyx_v_pkernel[((__pyx_v_ik * __pyx_v_kstride) + __pyx_v_jk)]) * (__pyx_v_pimage[((((__pyx_v_i + __pyx_v_ik) * __pyx_v_istride) + __pyx_v_j) + __pyx_v_jk)]))); /* "centrosome/_filter.pyx":829 * for ik in range(-kernel_half_width,kernel_half_width+1): * for jk in range(-kernel_half_width,kernel_half_width+1): * if pmask[(i+ik)*mstride+j+jk] != 0: # <<<<<<<<<<<<<< * accumulator += (pkernel[ik*kstride+jk] * * pimage[(i+ik)*istride+j+jk]) */ } } } /* "centrosome/_filter.pyx":832 * accumulator += (pkernel[ik*kstride+jk] * * pimage[(i+ik)*istride+j+jk]) * poutput[i*istride+j] = accumulator # <<<<<<<<<<<<<< * return output * */ (__pyx_v_poutput[((__pyx_v_i * __pyx_v_istride) + __pyx_v_j)]) = __pyx_v_accumulator; __pyx_L5_continue:; } } /* "centrosome/_filter.pyx":833 * pimage[(i+ik)*istride+j+jk]) * poutput[i*istride+j] = accumulator * return output # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_output)); __pyx_r = ((PyObject *)__pyx_v_output); goto __pyx_L0; /* "centrosome/_filter.pyx":771 * * @cython.boundscheck(False) * def masked_convolution(np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] kernel): */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_7); { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_big_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_kernel.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_output.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("centrosome._filter.masked_convolution", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_big_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_data.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_kernel.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_mask.rcbuffer->pybuffer); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_output.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_big_mask); __Pyx_XDECREF((PyObject *)__pyx_v_output); __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "centrosome/_filter.pyx":837 * @cython.boundscheck(False) * @cython.cdivision(True) * def paeth_decoder( # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=3, negative_indices=False, mode='c'] x, * np.int32_t raster_count): */ /* Python wrapper */ static PyObject *__pyx_pw_10centrosome_7_filter_5paeth_decoder(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/ static char __pyx_doc_10centrosome_7_filter_4paeth_decoder[] = "Paeth decoder - reverse Paeth filter\n \n x: matrix of bytes. The first dimension indexes rasters. The second\n dimension indexes pixel positions (stride = 24 for interleaved color,\n = 8 for monochrome). The third dimension indexes the bytes within\n the pixel. If your image consists of multiple planes, you should\n combine the planar dimensions on input by changing the image shape.\n \n raster_count: # of rasters in a plane\n \n Given a 2-dimensional array of unsigned bytes, the Paeth filter\n looks at 4 elements\n \n C B\n A x\n \n p = A+B-C\n estimate = A if abs(p-A) <= abs(p-B) and similarly for C\n = B if abs(p-B) <= abs(p-C)\n = C otherwise\n x += estimate if reverse\n \n Citation: http://www.w3.org/TR/PNG-Filters.html\n "; static PyMethodDef __pyx_mdef_10centrosome_7_filter_5paeth_decoder = {"paeth_decoder", (PyCFunction)__pyx_pw_10centrosome_7_filter_5paeth_decoder, METH_VARARGS|METH_KEYWORDS, __pyx_doc_10centrosome_7_filter_4paeth_decoder}; static PyObject *__pyx_pw_10centrosome_7_filter_5paeth_decoder(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) { PyArrayObject *__pyx_v_x = 0; __pyx_t_5numpy_int32_t __pyx_v_raster_count; PyObject *__pyx_r = 0; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("paeth_decoder (wrapper)", 0); { static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_x,&__pyx_n_s_raster_count,0}; PyObject* values[2] = {0,0}; if (unlikely(__pyx_kwds)) { Py_ssize_t kw_args; const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args); switch (pos_args) { case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1); CYTHON_FALLTHROUGH; case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0); CYTHON_FALLTHROUGH; case 0: break; default: goto __pyx_L5_argtuple_error; } kw_args = PyDict_Size(__pyx_kwds); switch (pos_args) { case 0: if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_x)) != 0)) kw_args--; else goto __pyx_L5_argtuple_error; CYTHON_FALLTHROUGH; case 1: if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_raster_count)) != 0)) kw_args--; else { __Pyx_RaiseArgtupleInvalid("paeth_decoder", 1, 2, 2, 1); __PYX_ERR(0, 837, __pyx_L3_error) } } if (unlikely(kw_args > 0)) { if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "paeth_decoder") < 0)) __PYX_ERR(0, 837, __pyx_L3_error) } } else if (PyTuple_GET_SIZE(__pyx_args) != 2) { goto __pyx_L5_argtuple_error; } else { values[0] = PyTuple_GET_ITEM(__pyx_args, 0); values[1] = PyTuple_GET_ITEM(__pyx_args, 1); } __pyx_v_x = ((PyArrayObject *)values[0]); __pyx_v_raster_count = __Pyx_PyInt_As_npy_int32(values[1]); if (unlikely((__pyx_v_raster_count == ((npy_int32)-1)) && PyErr_Occurred())) __PYX_ERR(0, 839, __pyx_L3_error) } goto __pyx_L4_argument_unpacking_done; __pyx_L5_argtuple_error:; __Pyx_RaiseArgtupleInvalid("paeth_decoder", 1, 2, 2, PyTuple_GET_SIZE(__pyx_args)); __PYX_ERR(0, 837, __pyx_L3_error) __pyx_L3_error:; __Pyx_AddTraceback("centrosome._filter.paeth_decoder", __pyx_clineno, __pyx_lineno, __pyx_filename); __Pyx_RefNannyFinishContext(); return NULL; __pyx_L4_argument_unpacking_done:; if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_x), __pyx_ptype_5numpy_ndarray, 1, "x", 0))) __PYX_ERR(0, 838, __pyx_L1_error) __pyx_r = __pyx_pf_10centrosome_7_filter_4paeth_decoder(__pyx_self, __pyx_v_x, __pyx_v_raster_count); /* function exit code */ goto __pyx_L0; __pyx_L1_error:; __pyx_r = NULL; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyObject *__pyx_pf_10centrosome_7_filter_4paeth_decoder(CYTHON_UNUSED PyObject *__pyx_self, PyArrayObject *__pyx_v_x, __pyx_t_5numpy_int32_t __pyx_v_raster_count) { __pyx_t_5numpy_int32_t __pyx_v_raster_stride; __pyx_t_5numpy_int32_t __pyx_v_pixel_stride; unsigned char *__pyx_v_ptr; __pyx_t_5numpy_int32_t __pyx_v_a; __pyx_t_5numpy_int32_t __pyx_v_b; __pyx_t_5numpy_int32_t __pyx_v_c; __pyx_t_5numpy_int32_t __pyx_v_p; __pyx_t_5numpy_int32_t __pyx_v_pa; __pyx_t_5numpy_int32_t __pyx_v_pb; __pyx_t_5numpy_int32_t __pyx_v_pc; __pyx_t_5numpy_int32_t __pyx_v_estimate; __pyx_t_5numpy_int32_t __pyx_v_i; __pyx_t_5numpy_int32_t __pyx_v_j; CYTHON_UNUSED __pyx_t_5numpy_int32_t __pyx_v_k; __pyx_t_5numpy_int32_t __pyx_v_imax; __pyx_t_5numpy_int32_t __pyx_v_jmax; __pyx_t_5numpy_int32_t __pyx_v_kmax; __pyx_t_5numpy_int32_t __pyx_v_raster_number; __Pyx_LocalBuf_ND __pyx_pybuffernd_x; __Pyx_Buffer __pyx_pybuffer_x; PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations __pyx_t_5numpy_int32_t __pyx_t_1; __pyx_t_5numpy_int32_t __pyx_t_2; __pyx_t_5numpy_int32_t __pyx_t_3; int __pyx_t_4; __pyx_t_5numpy_int32_t __pyx_t_5; int __pyx_t_6; long __pyx_t_7; __Pyx_RefNannySetupContext("paeth_decoder", 0); __pyx_pybuffer_x.pybuffer.buf = NULL; __pyx_pybuffer_x.refcount = 0; __pyx_pybuffernd_x.data = NULL; __pyx_pybuffernd_x.rcbuffer = &__pyx_pybuffer_x; { __Pyx_BufFmt_StackElem __pyx_stack[1]; if (unlikely(__Pyx_GetBufferAndValidate(&__pyx_pybuffernd_x.rcbuffer->pybuffer, (PyObject*)__pyx_v_x, &__Pyx_TypeInfo_nn___pyx_t_5numpy_uint8_t, PyBUF_FORMAT| PyBUF_C_CONTIGUOUS, 3, 0, __pyx_stack) == -1)) __PYX_ERR(0, 837, __pyx_L1_error) } __pyx_pybuffernd_x.diminfo[0].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[0]; __pyx_pybuffernd_x.diminfo[0].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[0]; __pyx_pybuffernd_x.diminfo[1].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[1]; __pyx_pybuffernd_x.diminfo[1].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[1]; __pyx_pybuffernd_x.diminfo[2].strides = __pyx_pybuffernd_x.rcbuffer->pybuffer.strides[2]; __pyx_pybuffernd_x.diminfo[2].shape = __pyx_pybuffernd_x.rcbuffer->pybuffer.shape[2]; /* "centrosome/_filter.pyx":865 * ''' * cdef: * np.int32_t raster_stride = x.strides[0] # <<<<<<<<<<<<<< * np.int32_t pixel_stride = x.strides[1] * unsigned char *ptr = <unsigned char *>x.data */ __pyx_v_raster_stride = (__pyx_v_x->strides[0]); /* "centrosome/_filter.pyx":866 * cdef: * np.int32_t raster_stride = x.strides[0] * np.int32_t pixel_stride = x.strides[1] # <<<<<<<<<<<<<< * unsigned char *ptr = <unsigned char *>x.data * np.int32_t a,b,c,p,pa,pb,pc,estimate */ __pyx_v_pixel_stride = (__pyx_v_x->strides[1]); /* "centrosome/_filter.pyx":867 * np.int32_t raster_stride = x.strides[0] * np.int32_t pixel_stride = x.strides[1] * unsigned char *ptr = <unsigned char *>x.data # <<<<<<<<<<<<<< * np.int32_t a,b,c,p,pa,pb,pc,estimate * np.int32_t i,j,k */ __pyx_v_ptr = ((unsigned char *)__pyx_v_x->data); /* "centrosome/_filter.pyx":870 * np.int32_t a,b,c,p,pa,pb,pc,estimate * np.int32_t i,j,k * np.int32_t imax = x.shape[0] # <<<<<<<<<<<<<< * np.int32_t jmax = x.shape[1] * np.int32_t kmax = x.shape[2] */ __pyx_v_imax = (__pyx_v_x->dimensions[0]); /* "centrosome/_filter.pyx":871 * np.int32_t i,j,k * np.int32_t imax = x.shape[0] * np.int32_t jmax = x.shape[1] # <<<<<<<<<<<<<< * np.int32_t kmax = x.shape[2] * np.int32_t raster_number */ __pyx_v_jmax = (__pyx_v_x->dimensions[1]); /* "centrosome/_filter.pyx":872 * np.int32_t imax = x.shape[0] * np.int32_t jmax = x.shape[1] * np.int32_t kmax = x.shape[2] # <<<<<<<<<<<<<< * np.int32_t raster_number * np.int32_t plane_number */ __pyx_v_kmax = (__pyx_v_x->dimensions[2]); /* "centrosome/_filter.pyx":876 * np.int32_t plane_number * * with nogil: # <<<<<<<<<<<<<< * for i from 0<=i<imax: * raster_number = i % raster_count */ { #ifdef WITH_THREAD PyThreadState *_save; Py_UNBLOCK_THREADS __Pyx_FastGIL_Remember(); #endif /*try:*/ { /* "centrosome/_filter.pyx":877 * * with nogil: * for i from 0<=i<imax: # <<<<<<<<<<<<<< * raster_number = i % raster_count * for j from 0<=j<jmax: */ __pyx_t_1 = __pyx_v_imax; for (__pyx_v_i = 0; __pyx_v_i < __pyx_t_1; __pyx_v_i++) { /* "centrosome/_filter.pyx":878 * with nogil: * for i from 0<=i<imax: * raster_number = i % raster_count # <<<<<<<<<<<<<< * for j from 0<=j<jmax: * for k from 0<=k<kmax: */ __pyx_v_raster_number = (__pyx_v_i % __pyx_v_raster_count); /* "centrosome/_filter.pyx":879 * for i from 0<=i<imax: * raster_number = i % raster_count * for j from 0<=j<jmax: # <<<<<<<<<<<<<< * for k from 0<=k<kmax: * if raster_number == 0: */ __pyx_t_2 = __pyx_v_jmax; for (__pyx_v_j = 0; __pyx_v_j < __pyx_t_2; __pyx_v_j++) { /* "centrosome/_filter.pyx":880 * raster_number = i % raster_count * for j from 0<=j<jmax: * for k from 0<=k<kmax: # <<<<<<<<<<<<<< * if raster_number == 0: * b = c = 0 */ __pyx_t_3 = __pyx_v_kmax; for (__pyx_v_k = 0; __pyx_v_k < __pyx_t_3; __pyx_v_k++) { /* "centrosome/_filter.pyx":881 * for j from 0<=j<jmax: * for k from 0<=k<kmax: * if raster_number == 0: # <<<<<<<<<<<<<< * b = c = 0 * if j==0: */ __pyx_t_4 = ((__pyx_v_raster_number == 0) != 0); if (__pyx_t_4) { /* "centrosome/_filter.pyx":882 * for k from 0<=k<kmax: * if raster_number == 0: * b = c = 0 # <<<<<<<<<<<<<< * if j==0: * a = 0 */ __pyx_v_b = 0; __pyx_v_c = 0; /* "centrosome/_filter.pyx":883 * if raster_number == 0: * b = c = 0 * if j==0: # <<<<<<<<<<<<<< * a = 0 * else: */ __pyx_t_4 = ((__pyx_v_j == 0) != 0); if (__pyx_t_4) { /* "centrosome/_filter.pyx":884 * b = c = 0 * if j==0: * a = 0 # <<<<<<<<<<<<<< * else: * a = ptr[-pixel_stride] */ __pyx_v_a = 0; /* "centrosome/_filter.pyx":883 * if raster_number == 0: * b = c = 0 * if j==0: # <<<<<<<<<<<<<< * a = 0 * else: */ goto __pyx_L13; } /* "centrosome/_filter.pyx":886 * a = 0 * else: * a = ptr[-pixel_stride] # <<<<<<<<<<<<<< * else: * b = ptr[-raster_stride] */ /*else*/ { __pyx_v_a = (__pyx_v_ptr[(-__pyx_v_pixel_stride)]); } __pyx_L13:; /* "centrosome/_filter.pyx":881 * for j from 0<=j<jmax: * for k from 0<=k<kmax: * if raster_number == 0: # <<<<<<<<<<<<<< * b = c = 0 * if j==0: */ goto __pyx_L12; } /* "centrosome/_filter.pyx":888 * a = ptr[-pixel_stride] * else: * b = ptr[-raster_stride] # <<<<<<<<<<<<<< * if j==0: * a = c = 0 */ /*else*/ { __pyx_v_b = (__pyx_v_ptr[(-__pyx_v_raster_stride)]); /* "centrosome/_filter.pyx":889 * else: * b = ptr[-raster_stride] * if j==0: # <<<<<<<<<<<<<< * a = c = 0 * else: */ __pyx_t_4 = ((__pyx_v_j == 0) != 0); if (__pyx_t_4) { /* "centrosome/_filter.pyx":890 * b = ptr[-raster_stride] * if j==0: * a = c = 0 # <<<<<<<<<<<<<< * else: * a = ptr[-pixel_stride] */ __pyx_v_a = 0; __pyx_v_c = 0; /* "centrosome/_filter.pyx":889 * else: * b = ptr[-raster_stride] * if j==0: # <<<<<<<<<<<<<< * a = c = 0 * else: */ goto __pyx_L14; } /* "centrosome/_filter.pyx":892 * a = c = 0 * else: * a = ptr[-pixel_stride] # <<<<<<<<<<<<<< * c = ptr[-raster_stride-pixel_stride] * p = a + b - c */ /*else*/ { __pyx_v_a = (__pyx_v_ptr[(-__pyx_v_pixel_stride)]); /* "centrosome/_filter.pyx":893 * else: * a = ptr[-pixel_stride] * c = ptr[-raster_stride-pixel_stride] # <<<<<<<<<<<<<< * p = a + b - c * pa = (a-p) if (a>p) else (p-a) */ __pyx_v_c = (__pyx_v_ptr[((-__pyx_v_raster_stride) - __pyx_v_pixel_stride)]); } __pyx_L14:; } __pyx_L12:; /* "centrosome/_filter.pyx":894 * a = ptr[-pixel_stride] * c = ptr[-raster_stride-pixel_stride] * p = a + b - c # <<<<<<<<<<<<<< * pa = (a-p) if (a>p) else (p-a) * pb = (b-p) if (b>p) else (p-b) */ __pyx_v_p = ((__pyx_v_a + __pyx_v_b) - __pyx_v_c); /* "centrosome/_filter.pyx":895 * c = ptr[-raster_stride-pixel_stride] * p = a + b - c * pa = (a-p) if (a>p) else (p-a) # <<<<<<<<<<<<<< * pb = (b-p) if (b>p) else (p-b) * pc = (c-p) if (c>p) else (p-c) */ if (((__pyx_v_a > __pyx_v_p) != 0)) { __pyx_t_5 = (__pyx_v_a - __pyx_v_p); } else { __pyx_t_5 = (__pyx_v_p - __pyx_v_a); } __pyx_v_pa = __pyx_t_5; /* "centrosome/_filter.pyx":896 * p = a + b - c * pa = (a-p) if (a>p) else (p-a) * pb = (b-p) if (b>p) else (p-b) # <<<<<<<<<<<<<< * pc = (c-p) if (c>p) else (p-c) * if (pa <= pb) and (pa <= pc): */ if (((__pyx_v_b > __pyx_v_p) != 0)) { __pyx_t_5 = (__pyx_v_b - __pyx_v_p); } else { __pyx_t_5 = (__pyx_v_p - __pyx_v_b); } __pyx_v_pb = __pyx_t_5; /* "centrosome/_filter.pyx":897 * pa = (a-p) if (a>p) else (p-a) * pb = (b-p) if (b>p) else (p-b) * pc = (c-p) if (c>p) else (p-c) # <<<<<<<<<<<<<< * if (pa <= pb) and (pa <= pc): * estimate = a */ if (((__pyx_v_c > __pyx_v_p) != 0)) { __pyx_t_5 = (__pyx_v_c - __pyx_v_p); } else { __pyx_t_5 = (__pyx_v_p - __pyx_v_c); } __pyx_v_pc = __pyx_t_5; /* "centrosome/_filter.pyx":898 * pb = (b-p) if (b>p) else (p-b) * pc = (c-p) if (c>p) else (p-c) * if (pa <= pb) and (pa <= pc): # <<<<<<<<<<<<<< * estimate = a * elif (pb <= pc): */ __pyx_t_6 = ((__pyx_v_pa <= __pyx_v_pb) != 0); if (__pyx_t_6) { } else { __pyx_t_4 = __pyx_t_6; goto __pyx_L16_bool_binop_done; } __pyx_t_6 = ((__pyx_v_pa <= __pyx_v_pc) != 0); __pyx_t_4 = __pyx_t_6; __pyx_L16_bool_binop_done:; if (__pyx_t_4) { /* "centrosome/_filter.pyx":899 * pc = (c-p) if (c>p) else (p-c) * if (pa <= pb) and (pa <= pc): * estimate = a # <<<<<<<<<<<<<< * elif (pb <= pc): * estimate = b */ __pyx_v_estimate = __pyx_v_a; /* "centrosome/_filter.pyx":898 * pb = (b-p) if (b>p) else (p-b) * pc = (c-p) if (c>p) else (p-c) * if (pa <= pb) and (pa <= pc): # <<<<<<<<<<<<<< * estimate = a * elif (pb <= pc): */ goto __pyx_L15; } /* "centrosome/_filter.pyx":900 * if (pa <= pb) and (pa <= pc): * estimate = a * elif (pb <= pc): # <<<<<<<<<<<<<< * estimate = b * else: */ __pyx_t_4 = ((__pyx_v_pb <= __pyx_v_pc) != 0); if (__pyx_t_4) { /* "centrosome/_filter.pyx":901 * estimate = a * elif (pb <= pc): * estimate = b # <<<<<<<<<<<<<< * else: * estimate = c */ __pyx_v_estimate = __pyx_v_b; /* "centrosome/_filter.pyx":900 * if (pa <= pb) and (pa <= pc): * estimate = a * elif (pb <= pc): # <<<<<<<<<<<<<< * estimate = b * else: */ goto __pyx_L15; } /* "centrosome/_filter.pyx":903 * estimate = b * else: * estimate = c # <<<<<<<<<<<<<< * ptr[0] += estimate * ptr += 1 */ /*else*/ { __pyx_v_estimate = __pyx_v_c; } __pyx_L15:; /* "centrosome/_filter.pyx":904 * else: * estimate = c * ptr[0] += estimate # <<<<<<<<<<<<<< * ptr += 1 */ __pyx_t_7 = 0; (__pyx_v_ptr[__pyx_t_7]) = ((__pyx_v_ptr[__pyx_t_7]) + __pyx_v_estimate); /* "centrosome/_filter.pyx":905 * estimate = c * ptr[0] += estimate * ptr += 1 # <<<<<<<<<<<<<< */ __pyx_v_ptr = (__pyx_v_ptr + 1); } } } } /* "centrosome/_filter.pyx":876 * np.int32_t plane_number * * with nogil: # <<<<<<<<<<<<<< * for i from 0<=i<imax: * raster_number = i % raster_count */ /*finally:*/ { /*normal exit:*/{ #ifdef WITH_THREAD __Pyx_FastGIL_Forget(); Py_BLOCK_THREADS #endif goto __pyx_L5; } __pyx_L5:; } } /* "centrosome/_filter.pyx":837 * @cython.boundscheck(False) * @cython.cdivision(True) * def paeth_decoder( # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=3, negative_indices=False, mode='c'] x, * np.int32_t raster_count): */ /* function exit code */ __pyx_r = Py_None; __Pyx_INCREF(Py_None); goto __pyx_L0; __pyx_L1_error:; { PyObject *__pyx_type, *__pyx_value, *__pyx_tb; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&__pyx_type, &__pyx_value, &__pyx_tb); __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __Pyx_ErrRestore(__pyx_type, __pyx_value, __pyx_tb);} __Pyx_AddTraceback("centrosome._filter.paeth_decoder", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; goto __pyx_L2; __pyx_L0:; __Pyx_SafeReleaseBuffer(&__pyx_pybuffernd_x.rcbuffer->pybuffer); __pyx_L2:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* Python wrapper */ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/ static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_r; __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0); __pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags)); /* function exit code */ __Pyx_RefNannyFinishContext(); return __pyx_r; } static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) { int __pyx_v_copy_shape; int __pyx_v_i; int __pyx_v_ndim; int __pyx_v_endian_detector; int __pyx_v_little_endian; int __pyx_v_t; char *__pyx_v_f; PyArray_Descr *__pyx_v_descr = 0; int __pyx_v_offset; int __pyx_v_hasfields; int __pyx_r; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; int __pyx_t_5; PyObject *__pyx_t_6 = NULL; char *__pyx_t_7; __Pyx_RefNannySetupContext("__getbuffer__", 0); if (__pyx_v_info != NULL) { __pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None); __Pyx_GIVEREF(__pyx_v_info->obj); } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":220 * # of flags * * if info == NULL: return # <<<<<<<<<<<<<< * * cdef int copy_shape, i, ndim */ __pyx_t_1 = ((__pyx_v_info == NULL) != 0); if (__pyx_t_1) { __pyx_r = 0; goto __pyx_L0; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":223 * * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * */ __pyx_v_endian_detector = 1; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":224 * cdef int copy_shape, i, ndim * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * * ndim = PyArray_NDIM(self) */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":226 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * * ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<< * * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_v_ndim = PyArray_NDIM(__pyx_v_self); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":229 * * if sizeof(npy_intp) != sizeof(Py_ssize_t): * copy_shape = 1 # <<<<<<<<<<<<<< * else: * copy_shape = 0 */ __pyx_v_copy_shape = 1; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":228 * ndim = PyArray_NDIM(self) * * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * copy_shape = 1 * else: */ goto __pyx_L4; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":231 * copy_shape = 1 * else: * copy_shape = 0 # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) */ /*else*/ { __pyx_v_copy_shape = 0; } __pyx_L4:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L6_bool_binop_done; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":234 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not C contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L6_bool_binop_done:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__2, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 235, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 235, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":233 * copy_shape = 0 * * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ __pyx_t_2 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L9_bool_binop_done; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":238 * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<< * raise ValueError(u"ndarray is not Fortran contiguous") * */ __pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L9_bool_binop_done:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 239, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 239, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":237 * raise ValueError(u"ndarray is not C contiguous") * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<< * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":241 * raise ValueError(u"ndarray is not Fortran contiguous") * * info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<< * info.ndim = ndim * if copy_shape: */ __pyx_v_info->buf = PyArray_DATA(__pyx_v_self); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":242 * * info.buf = PyArray_DATA(self) * info.ndim = ndim # <<<<<<<<<<<<<< * if copy_shape: * # Allocate new buffer for strides and shape info. */ __pyx_v_info->ndim = __pyx_v_ndim; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ __pyx_t_1 = (__pyx_v_copy_shape != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":246 * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) # <<<<<<<<<<<<<< * info.shape = info.strides + ndim * for i in range(ndim): */ __pyx_v_info->strides = ((Py_ssize_t *)PyObject_Malloc((((sizeof(Py_ssize_t)) * 2) * ((size_t)__pyx_v_ndim)))); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":247 * # This is allocated as one block, strides first. * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) * info.shape = info.strides + ndim # <<<<<<<<<<<<<< * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] */ __pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":248 * info.strides = <Py_ssize_t*>PyObject_Malloc(sizeof(Py_ssize_t) * 2 * <size_t>ndim) * info.shape = info.strides + ndim * for i in range(ndim): # <<<<<<<<<<<<<< * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] */ __pyx_t_4 = __pyx_v_ndim; for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_4; __pyx_t_5+=1) { __pyx_v_i = __pyx_t_5; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":249 * info.shape = info.strides + ndim * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<< * info.shape[i] = PyArray_DIMS(self)[i] * else: */ (__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":250 * for i in range(ndim): * info.strides[i] = PyArray_STRIDES(self)[i] * info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<< * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) */ (__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]); } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":243 * info.buf = PyArray_DATA(self) * info.ndim = ndim * if copy_shape: # <<<<<<<<<<<<<< * # Allocate new buffer for strides and shape info. * # This is allocated as one block, strides first. */ goto __pyx_L11; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":252 * info.shape[i] = PyArray_DIMS(self)[i] * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<< * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL */ /*else*/ { __pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self)); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":253 * else: * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<< * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) */ __pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self)); } __pyx_L11:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":254 * info.strides = <Py_ssize_t*>PyArray_STRIDES(self) * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL # <<<<<<<<<<<<<< * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) */ __pyx_v_info->suboffsets = NULL; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":255 * info.shape = <Py_ssize_t*>PyArray_DIMS(self) * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<< * info.readonly = not PyArray_ISWRITEABLE(self) * */ __pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":256 * info.suboffsets = NULL * info.itemsize = PyArray_ITEMSIZE(self) * info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<< * * cdef int t */ __pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0)); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":259 * * cdef int t * cdef char* f = NULL # <<<<<<<<<<<<<< * cdef dtype descr = self.descr * cdef int offset */ __pyx_v_f = NULL; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":260 * cdef int t * cdef char* f = NULL * cdef dtype descr = self.descr # <<<<<<<<<<<<<< * cdef int offset * */ __pyx_t_3 = ((PyObject *)__pyx_v_self->descr); __Pyx_INCREF(__pyx_t_3); __pyx_v_descr = ((PyArray_Descr *)__pyx_t_3); __pyx_t_3 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":263 * cdef int offset * * cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<< * * if not hasfields and not copy_shape: */ __pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ __pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L15_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_copy_shape != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L15_bool_binop_done:; if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":267 * if not hasfields and not copy_shape: * # do not call releasebuffer * info.obj = None # <<<<<<<<<<<<<< * else: * # need to call releasebuffer */ __Pyx_INCREF(Py_None); __Pyx_GIVEREF(Py_None); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = Py_None; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":265 * cdef bint hasfields = PyDataType_HASFIELDS(descr) * * if not hasfields and not copy_shape: # <<<<<<<<<<<<<< * # do not call releasebuffer * info.obj = None */ goto __pyx_L14; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":270 * else: * # need to call releasebuffer * info.obj = self # <<<<<<<<<<<<<< * * if not hasfields: */ /*else*/ { __Pyx_INCREF(((PyObject *)__pyx_v_self)); __Pyx_GIVEREF(((PyObject *)__pyx_v_self)); __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = ((PyObject *)__pyx_v_self); } __pyx_L14:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ __pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":273 * * if not hasfields: * t = descr.type_num # <<<<<<<<<<<<<< * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): */ __pyx_t_4 = __pyx_v_descr->type_num; __pyx_v_t = __pyx_t_4; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '>') != 0); if (!__pyx_t_2) { goto __pyx_L20_next_or; } else { } __pyx_t_2 = (__pyx_v_little_endian != 0); if (!__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_L20_next_or:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":275 * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" */ __pyx_t_2 = ((__pyx_v_descr->byteorder == '<') != 0); if (__pyx_t_2) { } else { __pyx_t_1 = __pyx_t_2; goto __pyx_L19_bool_binop_done; } __pyx_t_2 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_1 = __pyx_t_2; __pyx_L19_bool_binop_done:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 276, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 276, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":274 * if not hasfields: * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":277 * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" */ switch (__pyx_v_t) { case NPY_BYTE: __pyx_v_f = ((char *)"b"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":278 * raise ValueError(u"Non-native byte order not supported") * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" */ case NPY_UBYTE: __pyx_v_f = ((char *)"B"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":279 * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" */ case NPY_SHORT: __pyx_v_f = ((char *)"h"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":280 * elif t == NPY_UBYTE: f = "B" * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" */ case NPY_USHORT: __pyx_v_f = ((char *)"H"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":281 * elif t == NPY_SHORT: f = "h" * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" */ case NPY_INT: __pyx_v_f = ((char *)"i"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":282 * elif t == NPY_USHORT: f = "H" * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" */ case NPY_UINT: __pyx_v_f = ((char *)"I"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":283 * elif t == NPY_INT: f = "i" * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" */ case NPY_LONG: __pyx_v_f = ((char *)"l"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":284 * elif t == NPY_UINT: f = "I" * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" */ case NPY_ULONG: __pyx_v_f = ((char *)"L"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":285 * elif t == NPY_LONG: f = "l" * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" */ case NPY_LONGLONG: __pyx_v_f = ((char *)"q"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":286 * elif t == NPY_ULONG: f = "L" * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" */ case NPY_ULONGLONG: __pyx_v_f = ((char *)"Q"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":287 * elif t == NPY_LONGLONG: f = "q" * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" */ case NPY_FLOAT: __pyx_v_f = ((char *)"f"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":288 * elif t == NPY_ULONGLONG: f = "Q" * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" */ case NPY_DOUBLE: __pyx_v_f = ((char *)"d"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":289 * elif t == NPY_FLOAT: f = "f" * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" */ case NPY_LONGDOUBLE: __pyx_v_f = ((char *)"g"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":290 * elif t == NPY_DOUBLE: f = "d" * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" */ case NPY_CFLOAT: __pyx_v_f = ((char *)"Zf"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":291 * elif t == NPY_LONGDOUBLE: f = "g" * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" */ case NPY_CDOUBLE: __pyx_v_f = ((char *)"Zd"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":292 * elif t == NPY_CFLOAT: f = "Zf" * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f = "O" * else: */ case NPY_CLONGDOUBLE: __pyx_v_f = ((char *)"Zg"); break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":293 * elif t == NPY_CDOUBLE: f = "Zd" * elif t == NPY_CLONGDOUBLE: f = "Zg" * elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ case NPY_OBJECT: __pyx_v_f = ((char *)"O"); break; default: /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":295 * elif t == NPY_OBJECT: f = "O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * info.format = f * return */ __pyx_t_3 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 295, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_6 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_3); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 295, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 295, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_GIVEREF(__pyx_t_6); PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_6); __pyx_t_6 = 0; __pyx_t_6 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_6)) __PYX_ERR(1, 295, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_6); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __Pyx_Raise(__pyx_t_6, 0, 0, 0); __Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0; __PYX_ERR(1, 295, __pyx_L1_error) break; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":296 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f # <<<<<<<<<<<<<< * return * else: */ __pyx_v_info->format = __pyx_v_f; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":297 * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * info.format = f * return # <<<<<<<<<<<<<< * else: * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) */ __pyx_r = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":272 * info.obj = self * * if not hasfields: # <<<<<<<<<<<<<< * t = descr.type_num * if ((descr.byteorder == c'>' and little_endian) or */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":299 * return * else: * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) # <<<<<<<<<<<<<< * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 */ /*else*/ { __pyx_v_info->format = ((char *)PyObject_Malloc(0xFF)); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":300 * else: * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<< * offset = 0 * f = _util_dtypestring(descr, info.format + 1, */ (__pyx_v_info->format[0]) = '^'; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":301 * info.format = <char*>PyObject_Malloc(_buffer_format_string_len) * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 # <<<<<<<<<<<<<< * f = _util_dtypestring(descr, info.format + 1, * info.format + _buffer_format_string_len, */ __pyx_v_offset = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":302 * info.format[0] = c'^' # Native data types, manual alignment * offset = 0 * f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<< * info.format + _buffer_format_string_len, * &offset) */ __pyx_t_7 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 0xFF), (&__pyx_v_offset)); if (unlikely(__pyx_t_7 == ((char *)NULL))) __PYX_ERR(1, 302, __pyx_L1_error) __pyx_v_f = __pyx_t_7; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":305 * info.format + _buffer_format_string_len, * &offset) * f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<< * * def __releasebuffer__(ndarray self, Py_buffer* info): */ (__pyx_v_f[0]) = '\x00'; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":214 * # experimental exception made for __getbuffer__ and __releasebuffer__ * # -- the details of this may change. * def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<< * # This implementation of getbuffer is geared towards Cython * # requirements, and does not yet fullfill the PEP. */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_6); __Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) { __Pyx_GOTREF(__pyx_v_info->obj); __Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL; } goto __pyx_L2; __pyx_L0:; if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) { __Pyx_GOTREF(Py_None); __Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL; } __pyx_L2:; __Pyx_XDECREF((PyObject *)__pyx_v_descr); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":307 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) */ /* Python wrapper */ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/ static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0); __pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info)); /* function exit code */ __Pyx_RefNannyFinishContext(); } static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) { __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("__releasebuffer__", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":308 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ __pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":309 * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) # <<<<<<<<<<<<<< * if sizeof(npy_intp) != sizeof(Py_ssize_t): * PyObject_Free(info.strides) */ PyObject_Free(__pyx_v_info->format); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":308 * * def __releasebuffer__(ndarray self, Py_buffer* info): * if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<< * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":310 * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * PyObject_Free(info.strides) * # info.shape was stored after info.strides in the same block */ __pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":311 * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): * PyObject_Free(info.strides) # <<<<<<<<<<<<<< * # info.shape was stored after info.strides in the same block * */ PyObject_Free(__pyx_v_info->strides); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":310 * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) * if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<< * PyObject_Free(info.strides) * # info.shape was stored after info.strides in the same block */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":307 * f[0] = c'\0' # Terminate format string * * def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<< * if PyArray_HASFIELDS(self): * PyObject_Free(info.format) */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":788 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":789 * * cdef inline object PyArray_MultiIterNew1(a): * return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew2(a, b): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 789, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":788 * ctypedef npy_cdouble complex_t * * cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(1, <void*>a) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":792 * * cdef inline object PyArray_MultiIterNew2(a, b): * return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew3(a, b, c): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 792, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":791 * return PyArray_MultiIterNew(1, <void*>a) * * cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":795 * * cdef inline object PyArray_MultiIterNew3(a, b, c): * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 795, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":794 * return PyArray_MultiIterNew(2, <void*>a, <void*>b) * * cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":798 * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<< * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 798, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":797 * return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) * * cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":800 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; __Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":801 * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<< * * cdef inline tuple PyDataType_SHAPE(dtype d): */ __Pyx_XDECREF(__pyx_r); __pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) __PYX_ERR(1, 801, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_r = __pyx_t_1; __pyx_t_1 = 0; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":800 * return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) * * cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<< * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = 0; __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyDataType_SHAPE(PyArray_Descr *__pyx_v_d) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("PyDataType_SHAPE", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ __pyx_t_1 = (PyDataType_HASSUBARRAY(__pyx_v_d) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":805 * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape # <<<<<<<<<<<<<< * else: * return () */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject*)__pyx_v_d->subarray->shape)); __pyx_r = ((PyObject*)__pyx_v_d->subarray->shape); goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":804 * * cdef inline tuple PyDataType_SHAPE(dtype d): * if PyDataType_HASSUBARRAY(d): # <<<<<<<<<<<<<< * return <tuple>d.subarray.shape * else: */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":807 * return <tuple>d.subarray.shape * else: * return () # <<<<<<<<<<<<<< * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(__pyx_empty_tuple); __pyx_r = __pyx_empty_tuple; goto __pyx_L0; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":803 * return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) * * cdef inline tuple PyDataType_SHAPE(dtype d): # <<<<<<<<<<<<<< * if PyDataType_HASSUBARRAY(d): * return <tuple>d.subarray.shape */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":809 * return () * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) { PyArray_Descr *__pyx_v_child = 0; int __pyx_v_endian_detector; int __pyx_v_little_endian; PyObject *__pyx_v_fields = 0; PyObject *__pyx_v_childname = NULL; PyObject *__pyx_v_new_offset = NULL; PyObject *__pyx_v_t = NULL; char *__pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; Py_ssize_t __pyx_t_2; PyObject *__pyx_t_3 = NULL; PyObject *__pyx_t_4 = NULL; int __pyx_t_5; int __pyx_t_6; int __pyx_t_7; long __pyx_t_8; char *__pyx_t_9; __Pyx_RefNannySetupContext("_util_dtypestring", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":814 * * cdef dtype child * cdef int endian_detector = 1 # <<<<<<<<<<<<<< * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) * cdef tuple fields */ __pyx_v_endian_detector = 1; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":815 * cdef dtype child * cdef int endian_detector = 1 * cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<< * cdef tuple fields * */ __pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ if (unlikely(__pyx_v_descr->names == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); __PYX_ERR(1, 818, __pyx_L1_error) } __pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0; for (;;) { if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break; #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) __PYX_ERR(1, 818, __pyx_L1_error) #else __pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 818, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); #endif __Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3); __pyx_t_3 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":819 * * for childname in descr.names: * fields = descr.fields[childname] # <<<<<<<<<<<<<< * child, new_offset = fields * */ if (unlikely(__pyx_v_descr->fields == Py_None)) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not subscriptable"); __PYX_ERR(1, 819, __pyx_L1_error) } __pyx_t_3 = __Pyx_PyDict_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 819, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) __PYX_ERR(1, 819, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3)); __pyx_t_3 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":820 * for childname in descr.names: * fields = descr.fields[childname] * child, new_offset = fields # <<<<<<<<<<<<<< * * if (end - f) - <int>(new_offset - offset[0]) < 15: */ if (likely(__pyx_v_fields != Py_None)) { PyObject* sequence = __pyx_v_fields; #if !CYTHON_COMPILING_IN_PYPY Py_ssize_t size = Py_SIZE(sequence); #else Py_ssize_t size = PySequence_Size(sequence); #endif if (unlikely(size != 2)) { if (size > 2) __Pyx_RaiseTooManyValuesError(2); else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size); __PYX_ERR(1, 820, __pyx_L1_error) } #if CYTHON_ASSUME_SAFE_MACROS && !CYTHON_AVOID_BORROWED_REFS __pyx_t_3 = PyTuple_GET_ITEM(sequence, 0); __pyx_t_4 = PyTuple_GET_ITEM(sequence, 1); __Pyx_INCREF(__pyx_t_3); __Pyx_INCREF(__pyx_t_4); #else __pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 820, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 820, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); #endif } else { __Pyx_RaiseNoneNotIterableError(); __PYX_ERR(1, 820, __pyx_L1_error) } if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) __PYX_ERR(1, 820, __pyx_L1_error) __Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3)); __pyx_t_3 = 0; __Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ __pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 822, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 822, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) __PYX_ERR(1, 822, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0); if (__pyx_t_6) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 823, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":822 * child, new_offset = fields * * if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ __pyx_t_7 = ((__pyx_v_child->byteorder == '>') != 0); if (!__pyx_t_7) { goto __pyx_L8_next_or; } else { } __pyx_t_7 = (__pyx_v_little_endian != 0); if (!__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_L8_next_or:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":826 * * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<< * raise ValueError(u"Non-native byte order not supported") * # One could encode it in the format string and have Cython */ __pyx_t_7 = ((__pyx_v_child->byteorder == '<') != 0); if (__pyx_t_7) { } else { __pyx_t_6 = __pyx_t_7; goto __pyx_L7_bool_binop_done; } __pyx_t_7 = ((!(__pyx_v_little_endian != 0)) != 0); __pyx_t_6 = __pyx_t_7; __pyx_L7_bool_binop_done:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ if (__pyx_t_6) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 827, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":825 * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") * * if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<< * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":837 * * # Output padding bytes * while offset[0] < new_offset: # <<<<<<<<<<<<<< * f[0] = 120 # "x"; pad byte * f += 1 */ while (1) { __pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (!__pyx_t_6) break; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":838 * # Output padding bytes * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<< * f += 1 * offset[0] += 1 */ (__pyx_v_f[0]) = 0x78; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":839 * while offset[0] < new_offset: * f[0] = 120 # "x"; pad byte * f += 1 # <<<<<<<<<<<<<< * offset[0] += 1 * */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":840 * f[0] = 120 # "x"; pad byte * f += 1 * offset[0] += 1 # <<<<<<<<<<<<<< * * offset[0] += child.itemsize */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + 1); } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":842 * offset[0] += 1 * * offset[0] += child.itemsize # <<<<<<<<<<<<<< * * if not PyDataType_HASFIELDS(child): */ __pyx_t_8 = 0; (__pyx_v_offset[__pyx_t_8]) = ((__pyx_v_offset[__pyx_t_8]) + __pyx_v_child->elsize); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ __pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0); if (__pyx_t_6) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":845 * * if not PyDataType_HASFIELDS(child): * t = child.type_num # <<<<<<<<<<<<<< * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") */ __pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 845, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4); __pyx_t_4 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":846 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ __pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0); if (__pyx_t_6) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 847, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_Raise(__pyx_t_4, 0, 0, 0); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __PYX_ERR(1, 847, __pyx_L1_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":846 * if not PyDataType_HASFIELDS(child): * t = child.type_num * if end - f < 5: # <<<<<<<<<<<<<< * raise RuntimeError(u"Format string allocated too short.") * */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":850 * * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<< * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_BYTE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 850, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 850, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 850, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 98; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":851 * # Until ticket #99 is fixed, use integers to avoid warnings * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<< * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UBYTE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 851, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 851, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 851, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 66; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":852 * if t == NPY_BYTE: f[0] = 98 #"b" * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<< * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_SHORT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 852, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 852, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 852, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x68; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":853 * elif t == NPY_UBYTE: f[0] = 66 #"B" * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<< * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_USHORT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 853, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 853, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 853, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 72; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":854 * elif t == NPY_SHORT: f[0] = 104 #"h" * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<< * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_INT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 854, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 854, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 854, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x69; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":855 * elif t == NPY_USHORT: f[0] = 72 #"H" * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<< * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_UINT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 855, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 855, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 855, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 73; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":856 * elif t == NPY_INT: f[0] = 105 #"i" * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<< * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 856, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 856, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 856, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x6C; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":857 * elif t == NPY_UINT: f[0] = 73 #"I" * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<< * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 857, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 857, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 857, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 76; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":858 * elif t == NPY_LONG: f[0] = 108 #"l" * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<< * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 858, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 858, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 858, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x71; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":859 * elif t == NPY_ULONG: f[0] = 76 #"L" * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<< * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 859, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 859, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 859, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 81; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":860 * elif t == NPY_LONGLONG: f[0] = 113 #"q" * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<< * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_FLOAT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 860, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 860, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 860, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x66; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":861 * elif t == NPY_ULONGLONG: f[0] = 81 #"Q" * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<< * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 861, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 861, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 861, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x64; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":862 * elif t == NPY_FLOAT: f[0] = 102 #"f" * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<< * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 862, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 862, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 862, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 0x67; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":863 * elif t == NPY_DOUBLE: f[0] = 100 #"d" * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<< * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 863, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 863, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 863, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x66; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":864 * elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<< * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 864, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 864, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 864, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x64; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":865 * elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<< * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: */ __pyx_t_3 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 865, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 865, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 865, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 90; (__pyx_v_f[1]) = 0x67; __pyx_v_f = (__pyx_v_f + 1); goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":866 * elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd * elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg * elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<< * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) */ __pyx_t_4 = __Pyx_PyInt_From_enum__NPY_TYPES(NPY_OBJECT); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 866, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 866, __pyx_L1_error) __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) __PYX_ERR(1, 866, __pyx_L1_error) __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; if (__pyx_t_6) { (__pyx_v_f[0]) = 79; goto __pyx_L15; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":868 * elif t == NPY_OBJECT: f[0] = 79 #"O" * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<< * f += 1 * else: */ /*else*/ { __pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 868, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) __PYX_ERR(1, 868, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_4); __Pyx_GIVEREF(__pyx_t_3); PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3); __pyx_t_3 = 0; __pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) __PYX_ERR(1, 868, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_3); __Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0; __Pyx_Raise(__pyx_t_3, 0, 0, 0); __Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0; __PYX_ERR(1, 868, __pyx_L1_error) } __pyx_L15:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":869 * else: * raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) * f += 1 # <<<<<<<<<<<<<< * else: * # Cython ignores struct boundary information ("T{...}"), */ __pyx_v_f = (__pyx_v_f + 1); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":844 * offset[0] += child.itemsize * * if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<< * t = child.type_num * if end - f < 5: */ goto __pyx_L13; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":873 * # Cython ignores struct boundary information ("T{...}"), * # so don't output it * f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<< * return f * */ /*else*/ { __pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_9 == ((char *)NULL))) __PYX_ERR(1, 873, __pyx_L1_error) __pyx_v_f = __pyx_t_9; } __pyx_L13:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":818 * cdef tuple fields * * for childname in descr.names: # <<<<<<<<<<<<<< * fields = descr.fields[childname] * child, new_offset = fields */ } __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":874 * # so don't output it * f = _util_dtypestring(child, f, end, offset) * return f # <<<<<<<<<<<<<< * * */ __pyx_r = __pyx_v_f; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":809 * return () * * cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<< * # Recursive utility function used in __getbuffer__ to get format * # string. The new location in the format string is returned. */ /* function exit code */ __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_3); __Pyx_XDECREF(__pyx_t_4); __Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = NULL; __pyx_L0:; __Pyx_XDECREF((PyObject *)__pyx_v_child); __Pyx_XDECREF(__pyx_v_fields); __Pyx_XDECREF(__pyx_v_childname); __Pyx_XDECREF(__pyx_v_new_offset); __Pyx_XDECREF(__pyx_v_t); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":990 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) { PyObject *__pyx_v_baseptr; __Pyx_RefNannyDeclarations int __pyx_t_1; int __pyx_t_2; __Pyx_RefNannySetupContext("set_array_base", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":992 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ __pyx_t_1 = (__pyx_v_base == Py_None); __pyx_t_2 = (__pyx_t_1 != 0); if (__pyx_t_2) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":993 * cdef PyObject* baseptr * if base is None: * baseptr = NULL # <<<<<<<<<<<<<< * else: * Py_INCREF(base) # important to do this before decref below! */ __pyx_v_baseptr = NULL; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":992 * cdef inline void set_array_base(ndarray arr, object base): * cdef PyObject* baseptr * if base is None: # <<<<<<<<<<<<<< * baseptr = NULL * else: */ goto __pyx_L3; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":995 * baseptr = NULL * else: * Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<< * baseptr = <PyObject*>base * Py_XDECREF(arr.base) */ /*else*/ { Py_INCREF(__pyx_v_base); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":996 * else: * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base # <<<<<<<<<<<<<< * Py_XDECREF(arr.base) * arr.base = baseptr */ __pyx_v_baseptr = ((PyObject *)__pyx_v_base); } __pyx_L3:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":997 * Py_INCREF(base) # important to do this before decref below! * baseptr = <PyObject*>base * Py_XDECREF(arr.base) # <<<<<<<<<<<<<< * arr.base = baseptr * */ Py_XDECREF(__pyx_v_arr->base); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":998 * baseptr = <PyObject*>base * Py_XDECREF(arr.base) * arr.base = baseptr # <<<<<<<<<<<<<< * * cdef inline object get_array_base(ndarray arr): */ __pyx_v_arr->base = __pyx_v_baseptr; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":990 * * * cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<< * cdef PyObject* baseptr * if base is None: */ /* function exit code */ __Pyx_RefNannyFinishContext(); } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1000 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) { PyObject *__pyx_r = NULL; __Pyx_RefNannyDeclarations int __pyx_t_1; __Pyx_RefNannySetupContext("get_array_base", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ __pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0); if (__pyx_t_1) { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1002 * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: * return None # <<<<<<<<<<<<<< * else: * return <object>arr.base */ __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(Py_None); __pyx_r = Py_None; goto __pyx_L0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1001 * * cdef inline object get_array_base(ndarray arr): * if arr.base is NULL: # <<<<<<<<<<<<<< * return None * else: */ } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1004 * return None * else: * return <object>arr.base # <<<<<<<<<<<<<< * * */ /*else*/ { __Pyx_XDECREF(__pyx_r); __Pyx_INCREF(((PyObject *)__pyx_v_arr->base)); __pyx_r = ((PyObject *)__pyx_v_arr->base); goto __pyx_L0; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1000 * arr.base = baseptr * * cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<< * if arr.base is NULL: * return None */ /* function exit code */ __pyx_L0:; __Pyx_XGIVEREF(__pyx_r); __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1009 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ static CYTHON_INLINE int __pyx_f_5numpy_import_array(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_array", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1010 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1011 * cdef inline int import_array() except -1: * try: * _import_array() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.multiarray failed to import") */ __pyx_t_4 = _import_array(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1011, __pyx_L3_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1010 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1012 * try: * _import_array() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.multiarray failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1012, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1013 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__8, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1013, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1013, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1010 * # Cython code. * cdef inline int import_array() except -1: * try: # <<<<<<<<<<<<<< * _import_array() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1009 * # Versions of the import_* functions which are more suitable for * # Cython code. * cdef inline int import_array() except -1: # <<<<<<<<<<<<<< * try: * _import_array() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_array", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1015 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_umath(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_umath", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1016 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1017 * cdef inline int import_umath() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1017, __pyx_L3_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1016 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1018 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") * */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1018, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1019 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1019, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1019, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1016 * * cdef inline int import_umath() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1015 * raise ImportError("numpy.core.multiarray failed to import") * * cdef inline int import_umath() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_umath", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1021 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ static CYTHON_INLINE int __pyx_f_5numpy_import_ufunc(void) { int __pyx_r; __Pyx_RefNannyDeclarations PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; PyObject *__pyx_t_3 = NULL; int __pyx_t_4; PyObject *__pyx_t_5 = NULL; PyObject *__pyx_t_6 = NULL; PyObject *__pyx_t_7 = NULL; PyObject *__pyx_t_8 = NULL; __Pyx_RefNannySetupContext("import_ufunc", 0); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1022 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ { __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ExceptionSave(&__pyx_t_1, &__pyx_t_2, &__pyx_t_3); __Pyx_XGOTREF(__pyx_t_1); __Pyx_XGOTREF(__pyx_t_2); __Pyx_XGOTREF(__pyx_t_3); /*try:*/ { /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1023 * cdef inline int import_ufunc() except -1: * try: * _import_umath() # <<<<<<<<<<<<<< * except Exception: * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = _import_umath(); if (unlikely(__pyx_t_4 == ((int)-1))) __PYX_ERR(1, 1023, __pyx_L3_error) /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1022 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ } __Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0; __Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0; __Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0; goto __pyx_L8_try_end; __pyx_L3_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1024 * try: * _import_umath() * except Exception: # <<<<<<<<<<<<<< * raise ImportError("numpy.core.umath failed to import") */ __pyx_t_4 = __Pyx_PyErr_ExceptionMatches(((PyObject *)(&((PyTypeObject*)PyExc_Exception)[0]))); if (__pyx_t_4) { __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) __PYX_ERR(1, 1024, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_5); __Pyx_GOTREF(__pyx_t_6); __Pyx_GOTREF(__pyx_t_7); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1025 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ImportError, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_8)) __PYX_ERR(1, 1025, __pyx_L5_except_error) __Pyx_GOTREF(__pyx_t_8); __Pyx_Raise(__pyx_t_8, 0, 0, 0); __Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0; __PYX_ERR(1, 1025, __pyx_L5_except_error) } goto __pyx_L5_except_error; __pyx_L5_except_error:; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1022 * * cdef inline int import_ufunc() except -1: * try: # <<<<<<<<<<<<<< * _import_umath() * except Exception: */ __Pyx_XGIVEREF(__pyx_t_1); __Pyx_XGIVEREF(__pyx_t_2); __Pyx_XGIVEREF(__pyx_t_3); __Pyx_ExceptionReset(__pyx_t_1, __pyx_t_2, __pyx_t_3); goto __pyx_L1_error; __pyx_L8_try_end:; } /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1021 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /* function exit code */ __pyx_r = 0; goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_5); __Pyx_XDECREF(__pyx_t_6); __Pyx_XDECREF(__pyx_t_7); __Pyx_XDECREF(__pyx_t_8); __Pyx_AddTraceback("numpy.import_ufunc", __pyx_clineno, __pyx_lineno, __pyx_filename); __pyx_r = -1; __pyx_L0:; __Pyx_RefNannyFinishContext(); return __pyx_r; } static PyMethodDef __pyx_methods[] = { {0, 0, 0, 0} }; #if PY_MAJOR_VERSION >= 3 #if CYTHON_PEP489_MULTI_PHASE_INIT static PyObject* __pyx_pymod_create(PyObject *spec, PyModuleDef *def); /*proto*/ static int __pyx_pymod_exec__filter(PyObject* module); /*proto*/ static PyModuleDef_Slot __pyx_moduledef_slots[] = { {Py_mod_create, (void*)__pyx_pymod_create}, {Py_mod_exec, (void*)__pyx_pymod_exec__filter}, {0, NULL} }; #endif static struct PyModuleDef __pyx_moduledef = { PyModuleDef_HEAD_INIT, "_filter", 0, /* m_doc */ #if CYTHON_PEP489_MULTI_PHASE_INIT 0, /* m_size */ #else -1, /* m_size */ #endif __pyx_methods /* m_methods */, #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_moduledef_slots, /* m_slots */ #else NULL, /* m_reload */ #endif NULL, /* m_traverse */ NULL, /* m_clear */ NULL /* m_free */ }; #endif static __Pyx_StringTabEntry __pyx_string_tab[] = { {&__pyx_n_s_DTYPE_BOOL, __pyx_k_DTYPE_BOOL, sizeof(__pyx_k_DTYPE_BOOL), 0, 0, 1, 1}, {&__pyx_n_s_DTYPE_UINT32, __pyx_k_DTYPE_UINT32, sizeof(__pyx_k_DTYPE_UINT32), 0, 0, 1, 1}, {&__pyx_kp_s_Data_shape_d_d_is_not_mask_shape, __pyx_k_Data_shape_d_d_is_not_mask_shape, sizeof(__pyx_k_Data_shape_d_d_is_not_mask_shape), 0, 0, 1, 0}, {&__pyx_kp_s_Data_shape_d_d_is_not_output_sha, __pyx_k_Data_shape_d_d_is_not_output_sha, sizeof(__pyx_k_Data_shape_d_d_is_not_output_sha), 0, 0, 1, 0}, {&__pyx_kp_s_Failed_to_allocate_scratchpad_me, __pyx_k_Failed_to_allocate_scratchpad_me, sizeof(__pyx_k_Failed_to_allocate_scratchpad_me), 0, 0, 1, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0}, {&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0}, {&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1}, {&__pyx_kp_s_Kernel_must_be_square, __pyx_k_Kernel_must_be_square, sizeof(__pyx_k_Kernel_must_be_square), 0, 0, 1, 0}, {&__pyx_kp_s_Kernel_shape_must_be_odd, __pyx_k_Kernel_shape_must_be_odd, sizeof(__pyx_k_Kernel_shape_must_be_odd), 0, 0, 1, 0}, {&__pyx_kp_s_Median_filter_percent_d_is_great, __pyx_k_Median_filter_percent_d_is_great, sizeof(__pyx_k_Median_filter_percent_d_is_great), 0, 0, 1, 0}, {&__pyx_kp_s_Median_filter_percent_d_is_less, __pyx_k_Median_filter_percent_d_is_less, sizeof(__pyx_k_Median_filter_percent_d_is_less), 0, 0, 1, 0}, {&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1}, {&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0}, {&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1}, {&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1}, {&__pyx_n_s_a, __pyx_k_a, sizeof(__pyx_k_a), 0, 0, 1, 1}, {&__pyx_n_s_accumulator, __pyx_k_accumulator, sizeof(__pyx_k_accumulator), 0, 0, 1, 1}, {&__pyx_n_s_b, __pyx_k_b, sizeof(__pyx_k_b), 0, 0, 1, 1}, {&__pyx_n_s_big_mask, __pyx_k_big_mask, sizeof(__pyx_k_big_mask), 0, 0, 1, 1}, {&__pyx_n_s_bool, __pyx_k_bool, sizeof(__pyx_k_bool), 0, 0, 1, 1}, {&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1}, {&__pyx_n_s_centrosome__filter, __pyx_k_centrosome__filter, sizeof(__pyx_k_centrosome__filter), 0, 0, 1, 1}, {&__pyx_kp_s_centrosome__filter_pyx, __pyx_k_centrosome__filter_pyx, sizeof(__pyx_k_centrosome__filter_pyx), 0, 0, 1, 0}, {&__pyx_n_s_cline_in_traceback, __pyx_k_cline_in_traceback, sizeof(__pyx_k_cline_in_traceback), 0, 0, 1, 1}, {&__pyx_n_s_data, __pyx_k_data, sizeof(__pyx_k_data), 0, 0, 1, 1}, {&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1}, {&__pyx_n_s_estimate, __pyx_k_estimate, sizeof(__pyx_k_estimate), 0, 0, 1, 1}, {&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1}, {&__pyx_n_s_ik, __pyx_k_ik, sizeof(__pyx_k_ik), 0, 0, 1, 1}, {&__pyx_n_s_image_stride, __pyx_k_image_stride, sizeof(__pyx_k_image_stride), 0, 0, 1, 1}, {&__pyx_n_s_imax, __pyx_k_imax, sizeof(__pyx_k_imax), 0, 0, 1, 1}, {&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1}, {&__pyx_n_s_istride, __pyx_k_istride, sizeof(__pyx_k_istride), 0, 0, 1, 1}, {&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1}, {&__pyx_n_s_jk, __pyx_k_jk, sizeof(__pyx_k_jk), 0, 0, 1, 1}, {&__pyx_n_s_jmax, __pyx_k_jmax, sizeof(__pyx_k_jmax), 0, 0, 1, 1}, {&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1}, {&__pyx_n_s_kernel, __pyx_k_kernel, sizeof(__pyx_k_kernel), 0, 0, 1, 1}, {&__pyx_n_s_kernel_half_width, __pyx_k_kernel_half_width, sizeof(__pyx_k_kernel_half_width), 0, 0, 1, 1}, {&__pyx_n_s_kernel_stride, __pyx_k_kernel_stride, sizeof(__pyx_k_kernel_stride), 0, 0, 1, 1}, {&__pyx_n_s_kernel_width, __pyx_k_kernel_width, sizeof(__pyx_k_kernel_width), 0, 0, 1, 1}, {&__pyx_n_s_kmax, __pyx_k_kmax, sizeof(__pyx_k_kmax), 0, 0, 1, 1}, {&__pyx_n_s_kstride, __pyx_k_kstride, sizeof(__pyx_k_kstride), 0, 0, 1, 1}, {&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1}, {&__pyx_n_s_mask, __pyx_k_mask, sizeof(__pyx_k_mask), 0, 0, 1, 1}, {&__pyx_n_s_mask_offset, __pyx_k_mask_offset, sizeof(__pyx_k_mask_offset), 0, 0, 1, 1}, {&__pyx_n_s_mask_stride, __pyx_k_mask_stride, sizeof(__pyx_k_mask_stride), 0, 0, 1, 1}, {&__pyx_n_s_masked_convolution, __pyx_k_masked_convolution, sizeof(__pyx_k_masked_convolution), 0, 0, 1, 1}, {&__pyx_n_s_median_filter, __pyx_k_median_filter, sizeof(__pyx_k_median_filter), 0, 0, 1, 1}, {&__pyx_n_s_mstride, __pyx_k_mstride, sizeof(__pyx_k_mstride), 0, 0, 1, 1}, {&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0}, {&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0}, {&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1}, {&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1}, {&__pyx_kp_s_numpy_core_multiarray_failed_to, __pyx_k_numpy_core_multiarray_failed_to, sizeof(__pyx_k_numpy_core_multiarray_failed_to), 0, 0, 1, 0}, {&__pyx_kp_s_numpy_core_umath_failed_to_impor, __pyx_k_numpy_core_umath_failed_to_impor, sizeof(__pyx_k_numpy_core_umath_failed_to_impor), 0, 0, 1, 0}, {&__pyx_n_s_output, __pyx_k_output, sizeof(__pyx_k_output), 0, 0, 1, 1}, {&__pyx_n_s_p, __pyx_k_p, sizeof(__pyx_k_p), 0, 0, 1, 1}, {&__pyx_n_s_pa, __pyx_k_pa, sizeof(__pyx_k_pa), 0, 0, 1, 1}, {&__pyx_n_s_paeth_decoder, __pyx_k_paeth_decoder, sizeof(__pyx_k_paeth_decoder), 0, 0, 1, 1}, {&__pyx_n_s_pb, __pyx_k_pb, sizeof(__pyx_k_pb), 0, 0, 1, 1}, {&__pyx_n_s_pc, __pyx_k_pc, sizeof(__pyx_k_pc), 0, 0, 1, 1}, {&__pyx_n_s_percent, __pyx_k_percent, sizeof(__pyx_k_percent), 0, 0, 1, 1}, {&__pyx_n_s_pimage, __pyx_k_pimage, sizeof(__pyx_k_pimage), 0, 0, 1, 1}, {&__pyx_n_s_pixel_stride, __pyx_k_pixel_stride, sizeof(__pyx_k_pixel_stride), 0, 0, 1, 1}, {&__pyx_n_s_pkernel, __pyx_k_pkernel, sizeof(__pyx_k_pkernel), 0, 0, 1, 1}, {&__pyx_n_s_plane_number, __pyx_k_plane_number, sizeof(__pyx_k_plane_number), 0, 0, 1, 1}, {&__pyx_n_s_pmask, __pyx_k_pmask, sizeof(__pyx_k_pmask), 0, 0, 1, 1}, {&__pyx_n_s_poutput, __pyx_k_poutput, sizeof(__pyx_k_poutput), 0, 0, 1, 1}, {&__pyx_n_s_ptr, __pyx_k_ptr, sizeof(__pyx_k_ptr), 0, 0, 1, 1}, {&__pyx_n_s_radius, __pyx_k_radius, sizeof(__pyx_k_radius), 0, 0, 1, 1}, {&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1}, {&__pyx_n_s_raster_count, __pyx_k_raster_count, sizeof(__pyx_k_raster_count), 0, 0, 1, 1}, {&__pyx_n_s_raster_number, __pyx_k_raster_number, sizeof(__pyx_k_raster_number), 0, 0, 1, 1}, {&__pyx_n_s_raster_stride, __pyx_k_raster_stride, sizeof(__pyx_k_raster_stride), 0, 0, 1, 1}, {&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1}, {&__pyx_n_s_uint32, __pyx_k_uint32, sizeof(__pyx_k_uint32), 0, 0, 1, 1}, {&__pyx_n_s_uint8, __pyx_k_uint8, sizeof(__pyx_k_uint8), 0, 0, 1, 1}, {&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0}, {&__pyx_n_s_x, __pyx_k_x, sizeof(__pyx_k_x), 0, 0, 1, 1}, {&__pyx_n_s_zeros, __pyx_k_zeros, sizeof(__pyx_k_zeros), 0, 0, 1, 1}, {0, 0, 0, 0, 0, 0, 0} }; static int __Pyx_InitCachedBuiltins(void) { __pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) __PYX_ERR(0, 346, __pyx_L1_error) __pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) __PYX_ERR(0, 751, __pyx_L1_error) __pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) __PYX_ERR(0, 768, __pyx_L1_error) __pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) __PYX_ERR(1, 823, __pyx_L1_error) __pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) __PYX_ERR(1, 1013, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } static int __Pyx_InitCachedConstants(void) { __Pyx_RefNannyDeclarations __Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0); /* "centrosome/_filter.pyx":768 * <np.uint8_t *>mask.data, * <np.uint8_t *>output.data): * raise MemoryError('Failed to allocate scratchpad memory') # <<<<<<<<<<<<<< * * @cython.boundscheck(False) */ __pyx_tuple_ = PyTuple_Pack(1, __pyx_kp_s_Failed_to_allocate_scratchpad_me); if (unlikely(!__pyx_tuple_)) __PYX_ERR(0, 768, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple_); __Pyx_GIVEREF(__pyx_tuple_); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":235 * if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): * raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<< * * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) */ __pyx_tuple__2 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__2)) __PYX_ERR(1, 235, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__2); __Pyx_GIVEREF(__pyx_tuple__2); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":239 * if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) * and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): * raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<< * * info.buf = PyArray_DATA(self) */ __pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__3)) __PYX_ERR(1, 239, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__3); __Pyx_GIVEREF(__pyx_tuple__3); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":276 * if ((descr.byteorder == c'>' and little_endian) or * (descr.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * if t == NPY_BYTE: f = "b" * elif t == NPY_UBYTE: f = "B" */ __pyx_tuple__4 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__4)) __PYX_ERR(1, 276, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__4); __Pyx_GIVEREF(__pyx_tuple__4); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":823 * * if (end - f) - <int>(new_offset - offset[0]) < 15: * raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<< * * if ((child.byteorder == c'>' and little_endian) or */ __pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__5)) __PYX_ERR(1, 823, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__5); __Pyx_GIVEREF(__pyx_tuple__5); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":827 * if ((child.byteorder == c'>' and little_endian) or * (child.byteorder == c'<' and not little_endian)): * raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<< * # One could encode it in the format string and have Cython * # complain instead, BUT: < and > in format strings also imply */ __pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__6)) __PYX_ERR(1, 827, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__6); __Pyx_GIVEREF(__pyx_tuple__6); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":847 * t = child.type_num * if end - f < 5: * raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<< * * # Until ticket #99 is fixed, use integers to avoid warnings */ __pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__7)) __PYX_ERR(1, 847, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__7); __Pyx_GIVEREF(__pyx_tuple__7); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1013 * _import_array() * except Exception: * raise ImportError("numpy.core.multiarray failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_umath() except -1: */ __pyx_tuple__8 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_multiarray_failed_to); if (unlikely(!__pyx_tuple__8)) __PYX_ERR(1, 1013, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__8); __Pyx_GIVEREF(__pyx_tuple__8); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1019 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< * * cdef inline int import_ufunc() except -1: */ __pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__9)) __PYX_ERR(1, 1019, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__9); __Pyx_GIVEREF(__pyx_tuple__9); /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1025 * _import_umath() * except Exception: * raise ImportError("numpy.core.umath failed to import") # <<<<<<<<<<<<<< */ __pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s_numpy_core_umath_failed_to_impor); if (unlikely(!__pyx_tuple__10)) __PYX_ERR(1, 1025, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__10); __Pyx_GIVEREF(__pyx_tuple__10); /* "centrosome/_filter.pyx":732 * return 0 * * def median_filter(np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] output, */ __pyx_tuple__11 = PyTuple_Pack(5, __pyx_n_s_data, __pyx_n_s_mask, __pyx_n_s_output, __pyx_n_s_radius, __pyx_n_s_percent); if (unlikely(!__pyx_tuple__11)) __PYX_ERR(0, 732, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__11); __Pyx_GIVEREF(__pyx_tuple__11); __pyx_codeobj__12 = (PyObject*)__Pyx_PyCode_New(5, 0, 5, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__11, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_centrosome__filter_pyx, __pyx_n_s_median_filter, 732, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__12)) __PYX_ERR(0, 732, __pyx_L1_error) /* "centrosome/_filter.pyx":771 * * @cython.boundscheck(False) * def masked_convolution(np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] kernel): */ __pyx_tuple__13 = PyTuple_Pack(23, __pyx_n_s_data, __pyx_n_s_mask, __pyx_n_s_kernel, __pyx_n_s_pkernel, __pyx_n_s_pimage, __pyx_n_s_pmask, __pyx_n_s_poutput, __pyx_n_s_kernel_stride, __pyx_n_s_image_stride, __pyx_n_s_mask_stride, __pyx_n_s_mask_offset, __pyx_n_s_kernel_width, __pyx_n_s_kernel_half_width, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_ik, __pyx_n_s_jk, __pyx_n_s_istride, __pyx_n_s_mstride, __pyx_n_s_kstride, __pyx_n_s_accumulator, __pyx_n_s_big_mask, __pyx_n_s_output); if (unlikely(!__pyx_tuple__13)) __PYX_ERR(0, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__13); __Pyx_GIVEREF(__pyx_tuple__13); __pyx_codeobj__14 = (PyObject*)__Pyx_PyCode_New(3, 0, 23, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__13, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_centrosome__filter_pyx, __pyx_n_s_masked_convolution, 771, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__14)) __PYX_ERR(0, 771, __pyx_L1_error) /* "centrosome/_filter.pyx":837 * @cython.boundscheck(False) * @cython.cdivision(True) * def paeth_decoder( # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=3, negative_indices=False, mode='c'] x, * np.int32_t raster_count): */ __pyx_tuple__15 = PyTuple_Pack(21, __pyx_n_s_x, __pyx_n_s_raster_count, __pyx_n_s_raster_stride, __pyx_n_s_pixel_stride, __pyx_n_s_ptr, __pyx_n_s_a, __pyx_n_s_b, __pyx_n_s_c, __pyx_n_s_p, __pyx_n_s_pa, __pyx_n_s_pb, __pyx_n_s_pc, __pyx_n_s_estimate, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_imax, __pyx_n_s_jmax, __pyx_n_s_kmax, __pyx_n_s_raster_number, __pyx_n_s_plane_number); if (unlikely(!__pyx_tuple__15)) __PYX_ERR(0, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_tuple__15); __Pyx_GIVEREF(__pyx_tuple__15); __pyx_codeobj__16 = (PyObject*)__Pyx_PyCode_New(2, 0, 21, 0, CO_OPTIMIZED|CO_NEWLOCALS, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__15, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_centrosome__filter_pyx, __pyx_n_s_paeth_decoder, 837, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__16)) __PYX_ERR(0, 837, __pyx_L1_error) __Pyx_RefNannyFinishContext(); return 0; __pyx_L1_error:; __Pyx_RefNannyFinishContext(); return -1; } static int __Pyx_InitGlobals(void) { if (__Pyx_InitStrings(__pyx_string_tab) < 0) __PYX_ERR(0, 1, __pyx_L1_error); __pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) __PYX_ERR(0, 1, __pyx_L1_error) return 0; __pyx_L1_error:; return -1; } #if PY_MAJOR_VERSION < 3 PyMODINIT_FUNC init_filter(void); /*proto*/ PyMODINIT_FUNC init_filter(void) #else PyMODINIT_FUNC PyInit__filter(void); /*proto*/ PyMODINIT_FUNC PyInit__filter(void) #if CYTHON_PEP489_MULTI_PHASE_INIT { return PyModuleDef_Init(&__pyx_moduledef); } static int __Pyx_copy_spec_to_module(PyObject *spec, PyObject *moddict, const char* from_name, const char* to_name) { PyObject *value = PyObject_GetAttrString(spec, from_name); int result = 0; if (likely(value)) { result = PyDict_SetItemString(moddict, to_name, value); Py_DECREF(value); } else if (PyErr_ExceptionMatches(PyExc_AttributeError)) { PyErr_Clear(); } else { result = -1; } return result; } static PyObject* __pyx_pymod_create(PyObject *spec, CYTHON_UNUSED PyModuleDef *def) { PyObject *module = NULL, *moddict, *modname; if (__pyx_m) return __Pyx_NewRef(__pyx_m); modname = PyObject_GetAttrString(spec, "name"); if (unlikely(!modname)) goto bad; module = PyModule_NewObject(modname); Py_DECREF(modname); if (unlikely(!module)) goto bad; moddict = PyModule_GetDict(module); if (unlikely(!moddict)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "loader", "__loader__") < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "origin", "__file__") < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "parent", "__package__") < 0)) goto bad; if (unlikely(__Pyx_copy_spec_to_module(spec, moddict, "submodule_search_locations", "__path__") < 0)) goto bad; return module; bad: Py_XDECREF(module); return NULL; } static int __pyx_pymod_exec__filter(PyObject *__pyx_pyinit_module) #endif #endif { PyObject *__pyx_t_1 = NULL; PyObject *__pyx_t_2 = NULL; __Pyx_RefNannyDeclarations #if CYTHON_PEP489_MULTI_PHASE_INIT if (__pyx_m && __pyx_m == __pyx_pyinit_module) return 0; #endif #if CYTHON_REFNANNY __Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny"); if (!__Pyx_RefNanny) { PyErr_Clear(); __Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny"); if (!__Pyx_RefNanny) Py_FatalError("failed to import 'refnanny' module"); } #endif __Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit__filter(void)", 0); if (__Pyx_check_binary_version() < 0) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_empty_unicode = PyUnicode_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_unicode)) __PYX_ERR(0, 1, __pyx_L1_error) #ifdef __Pyx_CyFunction_USED if (__pyx_CyFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_FusedFunction_USED if (__pyx_FusedFunction_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Coroutine_USED if (__pyx_Coroutine_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_Generator_USED if (__pyx_Generator_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_AsyncGen_USED if (__pyx_AsyncGen_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif #ifdef __Pyx_StopAsyncIteration_USED if (__pyx_StopAsyncIteration_init() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /*--- Library function declarations ---*/ /*--- Threads initialization code ---*/ #if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS #ifdef WITH_THREAD /* Python build with threading support? */ PyEval_InitThreads(); #endif #endif /*--- Module creation code ---*/ #if CYTHON_PEP489_MULTI_PHASE_INIT __pyx_m = __pyx_pyinit_module; Py_INCREF(__pyx_m); #else #if PY_MAJOR_VERSION < 3 __pyx_m = Py_InitModule4("_filter", __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m); #else __pyx_m = PyModule_Create(&__pyx_moduledef); #endif if (unlikely(!__pyx_m)) __PYX_ERR(0, 1, __pyx_L1_error) #endif __pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) __PYX_ERR(0, 1, __pyx_L1_error) Py_INCREF(__pyx_d); __pyx_b = PyImport_AddModule(__Pyx_BUILTIN_MODULE_NAME); if (unlikely(!__pyx_b)) __PYX_ERR(0, 1, __pyx_L1_error) __pyx_cython_runtime = PyImport_AddModule((char *) "cython_runtime"); if (unlikely(!__pyx_cython_runtime)) __PYX_ERR(0, 1, __pyx_L1_error) #if CYTHON_COMPILING_IN_PYPY Py_INCREF(__pyx_b); #endif if (PyObject_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) __PYX_ERR(0, 1, __pyx_L1_error); /*--- Initialize various global constants etc. ---*/ if (__Pyx_InitGlobals() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT) if (__Pyx_init_sys_getdefaultencoding_params() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif if (__pyx_module_is_main_centrosome___filter) { if (PyObject_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) __PYX_ERR(0, 1, __pyx_L1_error) } #if PY_MAJOR_VERSION >= 3 { PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) __PYX_ERR(0, 1, __pyx_L1_error) if (!PyDict_GetItemString(modules, "centrosome._filter")) { if (unlikely(PyDict_SetItemString(modules, "centrosome._filter", __pyx_m) < 0)) __PYX_ERR(0, 1, __pyx_L1_error) } } #endif /*--- Builtin init code ---*/ if (__Pyx_InitCachedBuiltins() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Constants init code ---*/ if (__Pyx_InitCachedConstants() < 0) __PYX_ERR(0, 1, __pyx_L1_error) /*--- Global init code ---*/ /*--- Variable export code ---*/ /*--- Function export code ---*/ /*--- Type init code ---*/ __pyx_ptype_10centrosome_7_filter_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_10centrosome_7_filter_ndarray)) __PYX_ERR(0, 9, __pyx_L1_error) /*--- Type import code ---*/ __pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type", #if CYTHON_COMPILING_IN_PYPY sizeof(PyTypeObject), #else sizeof(PyHeapTypeObject), #endif 0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) __PYX_ERR(2, 9, __pyx_L1_error) __pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) __PYX_ERR(1, 163, __pyx_L1_error) __pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) __PYX_ERR(1, 185, __pyx_L1_error) __pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) __PYX_ERR(1, 189, __pyx_L1_error) __pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) __PYX_ERR(1, 198, __pyx_L1_error) __pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) __PYX_ERR(1, 885, __pyx_L1_error) /*--- Variable import code ---*/ /*--- Function import code ---*/ /*--- Execution code ---*/ #if defined(__Pyx_Generator_USED) || defined(__Pyx_Coroutine_USED) if (__Pyx_patch_abc() < 0) __PYX_ERR(0, 1, __pyx_L1_error) #endif /* "centrosome/_filter.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ __pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":23 * void *memset(void *, int, int) * * import_array() # <<<<<<<<<<<<<< * * ############################################################################## */ import_array(); /* "centrosome/_filter.pyx":43 * ############################################################################## * * DTYPE_UINT32 = np.uint32 # <<<<<<<<<<<<<< * DTYPE_BOOL = np.bool * ctypedef np.uint16_t pixel_count_t */ __pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 43, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_uint32); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 43, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE_UINT32, __pyx_t_2) < 0) __PYX_ERR(0, 43, __pyx_L1_error) __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; /* "centrosome/_filter.pyx":44 * * DTYPE_UINT32 = np.uint32 * DTYPE_BOOL = np.bool # <<<<<<<<<<<<<< * ctypedef np.uint16_t pixel_count_t * */ __pyx_t_2 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_2)) __PYX_ERR(0, 44, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_2); __pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_bool); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 44, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); __Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0; if (PyDict_SetItem(__pyx_d, __pyx_n_s_DTYPE_BOOL, __pyx_t_1) < 0) __PYX_ERR(0, 44, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":732 * return 0 * * def median_filter(np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] output, */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_10centrosome_7_filter_1median_filter, NULL, __pyx_n_s_centrosome__filter); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 732, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_median_filter, __pyx_t_1) < 0) __PYX_ERR(0, 732, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":771 * * @cython.boundscheck(False) * def masked_convolution(np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] data, # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=2, negative_indices=False, mode='c'] mask, * np.ndarray[dtype=np.float64_t, ndim=2, negative_indices=False, mode='c'] kernel): */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_10centrosome_7_filter_3masked_convolution, NULL, __pyx_n_s_centrosome__filter); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 771, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_masked_convolution, __pyx_t_1) < 0) __PYX_ERR(0, 771, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":837 * @cython.boundscheck(False) * @cython.cdivision(True) * def paeth_decoder( # <<<<<<<<<<<<<< * np.ndarray[dtype=np.uint8_t, ndim=3, negative_indices=False, mode='c'] x, * np.int32_t raster_count): */ __pyx_t_1 = PyCFunction_NewEx(&__pyx_mdef_10centrosome_7_filter_5paeth_decoder, NULL, __pyx_n_s_centrosome__filter); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 837, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_paeth_decoder, __pyx_t_1) < 0) __PYX_ERR(0, 837, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "centrosome/_filter.pyx":1 * import numpy as np # <<<<<<<<<<<<<< * cimport numpy as np * cimport cython */ __pyx_t_1 = __Pyx_PyDict_NewPresized(0); if (unlikely(!__pyx_t_1)) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_GOTREF(__pyx_t_1); if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_1) < 0) __PYX_ERR(0, 1, __pyx_L1_error) __Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0; /* "../../../../../usr/local/lib/python2.7/site-packages/Cython/Includes/numpy/__init__.pxd":1021 * raise ImportError("numpy.core.umath failed to import") * * cdef inline int import_ufunc() except -1: # <<<<<<<<<<<<<< * try: * _import_umath() */ /*--- Wrapped vars code ---*/ goto __pyx_L0; __pyx_L1_error:; __Pyx_XDECREF(__pyx_t_1); __Pyx_XDECREF(__pyx_t_2); if (__pyx_m) { if (__pyx_d) { __Pyx_AddTraceback("init centrosome._filter", 0, __pyx_lineno, __pyx_filename); } Py_DECREF(__pyx_m); __pyx_m = 0; } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ImportError, "init centrosome._filter"); } __pyx_L0:; __Pyx_RefNannyFinishContext(); #if CYTHON_PEP489_MULTI_PHASE_INIT return (__pyx_m != NULL) ? 0 : -1; #elif PY_MAJOR_VERSION >= 3 return __pyx_m; #else return; #endif } /* --- Runtime support code --- */ /* Refnanny */ #if CYTHON_REFNANNY static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) { PyObject *m = NULL, *p = NULL; void *r = NULL; m = PyImport_ImportModule((char *)modname); if (!m) goto end; p = PyObject_GetAttrString(m, (char *)"RefNannyAPI"); if (!p) goto end; r = PyLong_AsVoidPtr(p); end: Py_XDECREF(p); Py_XDECREF(m); return (__Pyx_RefNannyAPIStruct *)r; } #endif /* GetBuiltinName */ static PyObject *__Pyx_GetBuiltinName(PyObject *name) { PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name); if (unlikely(!result)) { PyErr_Format(PyExc_NameError, #if PY_MAJOR_VERSION >= 3 "name '%U' is not defined", name); #else "name '%.200s' is not defined", PyString_AS_STRING(name)); #endif } return result; } /* None */ static CYTHON_INLINE long __Pyx_div_long(long a, long b) { long q = a / b; long r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_EqObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { if (op1 == op2) { Py_RETURN_TRUE; } #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long a = PyInt_AS_LONG(op1); if (a == b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a; const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; } #if PyLong_SHIFT < 30 && PyLong_SHIFT != 15 default: return PyLong_Type.tp_richcompare(op1, op2, Py_EQ); #else default: Py_RETURN_FALSE; #endif } } if (a == b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); if ((double)a == (double)b) { Py_RETURN_TRUE; } else { Py_RETURN_FALSE; } } return PyObject_RichCompare(op1, op2, Py_EQ); } #endif /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_AddObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a + b); if (likely((x^a) >= 0 || (x^b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_add(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } default: return PyLong_Type.tp_as_number->nb_add(op1, op2); } } x = a + b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla + llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("add", return NULL) result = ((double)a) + (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceAdd : PyNumber_Add)(op1, op2); } #endif /* PyIntBinop */ #if !CYTHON_COMPILING_IN_PYPY static PyObject* __Pyx_PyInt_SubtractObjC(PyObject *op1, PyObject *op2, CYTHON_UNUSED long intval, CYTHON_UNUSED int inplace) { #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(op1))) { const long b = intval; long x; long a = PyInt_AS_LONG(op1); x = (long)((unsigned long)a - b); if (likely((x^a) >= 0 || (x^~b) >= 0)) return PyInt_FromLong(x); return PyLong_Type.tp_as_number->nb_subtract(op1, op2); } #endif #if CYTHON_USE_PYLONG_INTERNALS if (likely(PyLong_CheckExact(op1))) { const long b = intval; long a, x; #ifdef HAVE_LONG_LONG const PY_LONG_LONG llb = intval; PY_LONG_LONG lla, llx; #endif const digit* digits = ((PyLongObject*)op1)->ob_digit; const Py_ssize_t size = Py_SIZE(op1); if (likely(__Pyx_sst_abs(size) <= 1)) { a = likely(size) ? digits[0] : 0; if (size == -1) a = -a; } else { switch (size) { case -2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 2: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { a = (long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 2 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case -3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 3: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { a = (long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 3 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case -4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = -(PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } case 4: if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { a = (long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0])); break; #ifdef HAVE_LONG_LONG } else if (8 * sizeof(PY_LONG_LONG) - 1 > 4 * PyLong_SHIFT) { lla = (PY_LONG_LONG) (((((((((unsigned PY_LONG_LONG)digits[3]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[2]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[1]) << PyLong_SHIFT) | (unsigned PY_LONG_LONG)digits[0])); goto long_long; #endif } default: return PyLong_Type.tp_as_number->nb_subtract(op1, op2); } } x = a - b; return PyLong_FromLong(x); #ifdef HAVE_LONG_LONG long_long: llx = lla - llb; return PyLong_FromLongLong(llx); #endif } #endif if (PyFloat_CheckExact(op1)) { const long b = intval; double a = PyFloat_AS_DOUBLE(op1); double result; PyFPE_START_PROTECT("subtract", return NULL) result = ((double)a) - (double)b; PyFPE_END_PROTECT(result) return PyFloat_FromDouble(result); } return (inplace ? PyNumber_InPlaceSubtract : PyNumber_Subtract)(op1, op2); } #endif /* PyErrFetchRestore */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx_ErrRestoreInState(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; tmp_type = tstate->curexc_type; tmp_value = tstate->curexc_value; tmp_tb = tstate->curexc_traceback; tstate->curexc_type = type; tstate->curexc_value = value; tstate->curexc_traceback = tb; Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } static CYTHON_INLINE void __Pyx_ErrFetchInState(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { *type = tstate->curexc_type; *value = tstate->curexc_value; *tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; } #endif /* WriteUnraisableException */ static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno, CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename, int full_traceback, CYTHON_UNUSED int nogil) { PyObject *old_exc, *old_val, *old_tb; PyObject *ctx; __Pyx_PyThreadState_declare #ifdef WITH_THREAD PyGILState_STATE state; if (nogil) state = PyGILState_Ensure(); #ifdef _MSC_VER else state = (PyGILState_STATE)-1; #endif #endif __Pyx_PyThreadState_assign __Pyx_ErrFetch(&old_exc, &old_val, &old_tb); if (full_traceback) { Py_XINCREF(old_exc); Py_XINCREF(old_val); Py_XINCREF(old_tb); __Pyx_ErrRestore(old_exc, old_val, old_tb); PyErr_PrintEx(1); } #if PY_MAJOR_VERSION < 3 ctx = PyString_FromString(name); #else ctx = PyUnicode_FromString(name); #endif __Pyx_ErrRestore(old_exc, old_val, old_tb); if (!ctx) { PyErr_WriteUnraisable(Py_None); } else { PyErr_WriteUnraisable(ctx); Py_DECREF(ctx); } #ifdef WITH_THREAD if (nogil) PyGILState_Release(state); #endif } /* None */ static CYTHON_INLINE long __Pyx_mod_long(long a, long b) { long r = a % b; r += ((r != 0) & ((r ^ b) < 0)) * b; return r; } /* RaiseArgTupleInvalid */ static void __Pyx_RaiseArgtupleInvalid( const char* func_name, int exact, Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found) { Py_ssize_t num_expected; const char *more_or_less; if (num_found < num_min) { num_expected = num_min; more_or_less = "at least"; } else { num_expected = num_max; more_or_less = "at most"; } if (exact) { more_or_less = "exactly"; } PyErr_Format(PyExc_TypeError, "%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)", func_name, more_or_less, num_expected, (num_expected == 1) ? "" : "s", num_found); } /* RaiseDoubleKeywords */ static void __Pyx_RaiseDoubleKeywordsError( const char* func_name, PyObject* kw_name) { PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION >= 3 "%s() got multiple values for keyword argument '%U'", func_name, kw_name); #else "%s() got multiple values for keyword argument '%s'", func_name, PyString_AsString(kw_name)); #endif } /* ParseKeywords */ static int __Pyx_ParseOptionalKeywords( PyObject *kwds, PyObject **argnames[], PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, const char* function_name) { PyObject *key = 0, *value = 0; Py_ssize_t pos = 0; PyObject*** name; PyObject*** first_kw_arg = argnames + num_pos_args; while (PyDict_Next(kwds, &pos, &key, &value)) { name = first_kw_arg; while (*name && (**name != key)) name++; if (*name) { values[name-argnames] = value; continue; } name = first_kw_arg; #if PY_MAJOR_VERSION < 3 if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) { while (*name) { if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key)) && _PyString_Eq(**name, key)) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { if ((**argname == key) || ( (CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key)) && _PyString_Eq(**argname, key))) { goto arg_passed_twice; } argname++; } } } else #endif if (likely(PyUnicode_Check(key))) { while (*name) { int cmp = (**name == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**name, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) { values[name-argnames] = value; break; } name++; } if (*name) continue; else { PyObject*** argname = argnames; while (argname != first_kw_arg) { int cmp = (**argname == key) ? 0 : #if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3 (PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 : #endif PyUnicode_Compare(**argname, key); if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad; if (cmp == 0) goto arg_passed_twice; argname++; } } } else goto invalid_keyword_type; if (kwds2) { if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad; } else { goto invalid_keyword; } } return 0; arg_passed_twice: __Pyx_RaiseDoubleKeywordsError(function_name, key); goto bad; invalid_keyword_type: PyErr_Format(PyExc_TypeError, "%.200s() keywords must be strings", function_name); goto bad; invalid_keyword: PyErr_Format(PyExc_TypeError, #if PY_MAJOR_VERSION < 3 "%.200s() got an unexpected keyword argument '%.200s'", function_name, PyString_AsString(key)); #else "%s() got an unexpected keyword argument '%U'", function_name, key); #endif bad: return -1; } /* ArgTypeTest */ static int __Pyx__ArgTypeTest(PyObject *obj, PyTypeObject *type, const char *name, int exact) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } else if (exact) { #if PY_MAJOR_VERSION == 2 if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1; #endif } else { if (likely(__Pyx_TypeCheck(obj, type))) return 1; } PyErr_Format(PyExc_TypeError, "Argument '%.200s' has incorrect type (expected %.200s, got %.200s)", name, type->tp_name, Py_TYPE(obj)->tp_name); return 0; } /* IsLittleEndian */ static CYTHON_INLINE int __Pyx_Is_Little_Endian(void) { union { uint32_t u32; uint8_t u8[4]; } S; S.u32 = 0x01020304; return S.u8[0] == 4; } /* BufferFormatCheck */ static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx, __Pyx_BufFmt_StackElem* stack, __Pyx_TypeInfo* type) { stack[0].field = &ctx->root; stack[0].parent_offset = 0; ctx->root.type = type; ctx->root.name = "buffer dtype"; ctx->root.offset = 0; ctx->head = stack; ctx->head->field = &ctx->root; ctx->fmt_offset = 0; ctx->head->parent_offset = 0; ctx->new_packmode = '@'; ctx->enc_packmode = '@'; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->is_complex = 0; ctx->is_valid_array = 0; ctx->struct_alignment = 0; while (type->typegroup == 'S') { ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = 0; type = type->fields->type; } } static int __Pyx_BufFmt_ParseNumber(const char** ts) { int count; const char* t = *ts; if (*t < '0' || *t > '9') { return -1; } else { count = *t++ - '0'; while (*t >= '0' && *t < '9') { count *= 10; count += *t++ - '0'; } } *ts = t; return count; } static int __Pyx_BufFmt_ExpectNumber(const char **ts) { int number = __Pyx_BufFmt_ParseNumber(ts); if (number == -1) PyErr_Format(PyExc_ValueError,\ "Does not understand character buffer dtype format string ('%c')", **ts); return number; } static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) { PyErr_Format(PyExc_ValueError, "Unexpected format string character: '%c'", ch); } static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) { switch (ch) { case 'c': return "'char'"; case 'b': return "'signed char'"; case 'B': return "'unsigned char'"; case 'h': return "'short'"; case 'H': return "'unsigned short'"; case 'i': return "'int'"; case 'I': return "'unsigned int'"; case 'l': return "'long'"; case 'L': return "'unsigned long'"; case 'q': return "'long long'"; case 'Q': return "'unsigned long long'"; case 'f': return (is_complex ? "'complex float'" : "'float'"); case 'd': return (is_complex ? "'complex double'" : "'double'"); case 'g': return (is_complex ? "'complex long double'" : "'long double'"); case 'T': return "a struct"; case 'O': return "Python object"; case 'P': return "a pointer"; case 's': case 'p': return "a string"; case 0: return "end"; default: return "unparseable format string"; } } static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return 2; case 'i': case 'I': case 'l': case 'L': return 4; case 'q': case 'Q': return 8; case 'f': return (is_complex ? 8 : 4); case 'd': return (is_complex ? 16 : 8); case 'g': { PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g').."); return 0; } case 'O': case 'P': return sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) { switch (ch) { case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(short); case 'i': case 'I': return sizeof(int); case 'l': case 'L': return sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(float) * (is_complex ? 2 : 1); case 'd': return sizeof(double) * (is_complex ? 2 : 1); case 'g': return sizeof(long double) * (is_complex ? 2 : 1); case 'O': case 'P': return sizeof(void*); default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } typedef struct { char c; short x; } __Pyx_st_short; typedef struct { char c; int x; } __Pyx_st_int; typedef struct { char c; long x; } __Pyx_st_long; typedef struct { char c; float x; } __Pyx_st_float; typedef struct { char c; double x; } __Pyx_st_double; typedef struct { char c; long double x; } __Pyx_st_longdouble; typedef struct { char c; void *x; } __Pyx_st_void_p; #ifdef HAVE_LONG_LONG typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_st_float) - sizeof(float); case 'd': return sizeof(__Pyx_st_double) - sizeof(double); case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } /* These are for computing the padding at the end of the struct to align on the first member of the struct. This will probably the same as above, but we don't have any guarantees. */ typedef struct { short x; char c; } __Pyx_pad_short; typedef struct { int x; char c; } __Pyx_pad_int; typedef struct { long x; char c; } __Pyx_pad_long; typedef struct { float x; char c; } __Pyx_pad_float; typedef struct { double x; char c; } __Pyx_pad_double; typedef struct { long double x; char c; } __Pyx_pad_longdouble; typedef struct { void *x; char c; } __Pyx_pad_void_p; #ifdef HAVE_LONG_LONG typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong; #endif static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) { switch (ch) { case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1; case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short); case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int); case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long); #ifdef HAVE_LONG_LONG case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG); #endif case 'f': return sizeof(__Pyx_pad_float) - sizeof(float); case 'd': return sizeof(__Pyx_pad_double) - sizeof(double); case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double); case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*); default: __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) { switch (ch) { case 'c': return 'H'; case 'b': case 'h': case 'i': case 'l': case 'q': case 's': case 'p': return 'I'; case 'B': case 'H': case 'I': case 'L': case 'Q': return 'U'; case 'f': case 'd': case 'g': return (is_complex ? 'C' : 'R'); case 'O': return 'O'; case 'P': return 'P'; default: { __Pyx_BufFmt_RaiseUnexpectedChar(ch); return 0; } } } static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) { if (ctx->head == NULL || ctx->head->field == &ctx->root) { const char* expected; const char* quote; if (ctx->head == NULL) { expected = "end"; quote = ""; } else { expected = ctx->head->field->type->name; quote = "'"; } PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected %s%s%s but got %s", quote, expected, quote, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex)); } else { __Pyx_StructField* field = ctx->head->field; __Pyx_StructField* parent = (ctx->head - 1)->field; PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'", field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex), parent->type->name, field->name); } } static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) { char group; size_t size, offset, arraysize = 1; if (ctx->enc_type == 0) return 0; if (ctx->head->field->type->arraysize[0]) { int i, ndim = 0; if (ctx->enc_type == 's' || ctx->enc_type == 'p') { ctx->is_valid_array = ctx->head->field->type->ndim == 1; ndim = 1; if (ctx->enc_count != ctx->head->field->type->arraysize[0]) { PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %zu", ctx->head->field->type->arraysize[0], ctx->enc_count); return -1; } } if (!ctx->is_valid_array) { PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d", ctx->head->field->type->ndim, ndim); return -1; } for (i = 0; i < ctx->head->field->type->ndim; i++) { arraysize *= ctx->head->field->type->arraysize[i]; } ctx->is_valid_array = 0; ctx->enc_count = 1; } group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex); do { __Pyx_StructField* field = ctx->head->field; __Pyx_TypeInfo* type = field->type; if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') { size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex); } else { size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex); } if (ctx->enc_packmode == '@') { size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex); size_t align_mod_offset; if (align_at == 0) return -1; align_mod_offset = ctx->fmt_offset % align_at; if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset; if (ctx->struct_alignment == 0) ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type, ctx->is_complex); } if (type->size != size || type->typegroup != group) { if (type->typegroup == 'C' && type->fields != NULL) { size_t parent_offset = ctx->head->parent_offset + field->offset; ++ctx->head; ctx->head->field = type->fields; ctx->head->parent_offset = parent_offset; continue; } if ((type->typegroup == 'H' || group == 'H') && type->size == size) { } else { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } } offset = ctx->head->parent_offset + field->offset; if (ctx->fmt_offset != offset) { PyErr_Format(PyExc_ValueError, "Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected", (Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset); return -1; } ctx->fmt_offset += size; if (arraysize) ctx->fmt_offset += (arraysize - 1) * size; --ctx->enc_count; while (1) { if (field == &ctx->root) { ctx->head = NULL; if (ctx->enc_count != 0) { __Pyx_BufFmt_RaiseExpected(ctx); return -1; } break; } ctx->head->field = ++field; if (field->type == NULL) { --ctx->head; field = ctx->head->field; continue; } else if (field->type->typegroup == 'S') { size_t parent_offset = ctx->head->parent_offset + field->offset; if (field->type->fields->type == NULL) continue; field = field->type->fields; ++ctx->head; ctx->head->field = field; ctx->head->parent_offset = parent_offset; break; } else { break; } } } while (ctx->enc_count); ctx->enc_type = 0; ctx->is_complex = 0; return 0; } static PyObject * __pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp) { const char *ts = *tsp; int i = 0, number; int ndim = ctx->head->field->type->ndim; ; ++ts; if (ctx->new_count != 1) { PyErr_SetString(PyExc_ValueError, "Cannot handle repeated arrays in format string"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; while (*ts && *ts != ')') { switch (*ts) { case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue; default: break; } number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i]) return PyErr_Format(PyExc_ValueError, "Expected a dimension of size %zu, got %d", ctx->head->field->type->arraysize[i], number); if (*ts != ',' && *ts != ')') return PyErr_Format(PyExc_ValueError, "Expected a comma in format string, got '%c'", *ts); if (*ts == ',') ts++; i++; } if (i != ndim) return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d", ctx->head->field->type->ndim, i); if (!*ts) { PyErr_SetString(PyExc_ValueError, "Unexpected end of format string, expected ')'"); return NULL; } ctx->is_valid_array = 1; ctx->new_count = 1; *tsp = ++ts; return Py_None; } static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) { int got_Z = 0; while (1) { switch(*ts) { case 0: if (ctx->enc_type != 0 && ctx->head == NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; if (ctx->head != NULL) { __Pyx_BufFmt_RaiseExpected(ctx); return NULL; } return ts; case ' ': case '\r': case '\n': ++ts; break; case '<': if (!__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '>': case '!': if (__Pyx_Is_Little_Endian()) { PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler"); return NULL; } ctx->new_packmode = '='; ++ts; break; case '=': case '@': case '^': ctx->new_packmode = *ts++; break; case 'T': { const char* ts_after_sub; size_t i, struct_count = ctx->new_count; size_t struct_alignment = ctx->struct_alignment; ctx->new_count = 1; ++ts; if (*ts != '{') { PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'"); return NULL; } if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; ctx->enc_count = 0; ctx->struct_alignment = 0; ++ts; ts_after_sub = ts; for (i = 0; i != struct_count; ++i) { ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts); if (!ts_after_sub) return NULL; } ts = ts_after_sub; if (struct_alignment) ctx->struct_alignment = struct_alignment; } break; case '}': { size_t alignment = ctx->struct_alignment; ++ts; if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_type = 0; if (alignment && ctx->fmt_offset % alignment) { ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment); } } return ts; case 'x': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->fmt_offset += ctx->new_count; ctx->new_count = 1; ctx->enc_count = 0; ctx->enc_type = 0; ctx->enc_packmode = ctx->new_packmode; ++ts; break; case 'Z': got_Z = 1; ++ts; if (*ts != 'f' && *ts != 'd' && *ts != 'g') { __Pyx_BufFmt_RaiseUnexpectedChar('Z'); return NULL; } case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I': case 'l': case 'L': case 'q': case 'Q': case 'f': case 'd': case 'g': case 'O': case 'p': if (ctx->enc_type == *ts && got_Z == ctx->is_complex && ctx->enc_packmode == ctx->new_packmode) { ctx->enc_count += ctx->new_count; ctx->new_count = 1; got_Z = 0; ++ts; break; } case 's': if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL; ctx->enc_count = ctx->new_count; ctx->enc_packmode = ctx->new_packmode; ctx->enc_type = *ts; ctx->is_complex = got_Z; ++ts; ctx->new_count = 1; got_Z = 0; break; case ':': ++ts; while(*ts != ':') ++ts; ++ts; break; case '(': if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL; break; default: { int number = __Pyx_BufFmt_ExpectNumber(&ts); if (number == -1) return NULL; ctx->new_count = (size_t)number; } } } } /* BufferGetAndValidate */ static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) { if (unlikely(info->buf == NULL)) return; if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL; __Pyx_ReleaseBuffer(info); } static void __Pyx_ZeroBuffer(Py_buffer* buf) { buf->buf = NULL; buf->obj = NULL; buf->strides = __Pyx_zeros; buf->shape = __Pyx_zeros; buf->suboffsets = __Pyx_minusones; } static int __Pyx__GetBufferAndValidate( Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack) { buf->buf = NULL; if (unlikely(__Pyx_GetBuffer(obj, buf, flags) == -1)) { __Pyx_ZeroBuffer(buf); return -1; } if (unlikely(buf->ndim != nd)) { PyErr_Format(PyExc_ValueError, "Buffer has wrong number of dimensions (expected %d, got %d)", nd, buf->ndim); goto fail; } if (!cast) { __Pyx_BufFmt_Context ctx; __Pyx_BufFmt_Init(&ctx, stack, dtype); if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail; } if (unlikely((unsigned)buf->itemsize != dtype->size)) { PyErr_Format(PyExc_ValueError, "Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)", buf->itemsize, (buf->itemsize > 1) ? "s" : "", dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : ""); goto fail; } if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones; return 0; fail:; __Pyx_SafeReleaseBuffer(buf); return -1; } /* PyObjectCall */ #if CYTHON_COMPILING_IN_CPYTHON static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) { PyObject *result; ternaryfunc call = func->ob_type->tp_call; if (unlikely(!call)) return PyObject_Call(func, arg, kw); if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object"))) return NULL; result = (*call)(func, arg, kw); Py_LeaveRecursiveCall(); if (unlikely(!result) && unlikely(!PyErr_Occurred())) { PyErr_SetString( PyExc_SystemError, "NULL result without error in PyObject_Call"); } return result; } #endif /* RaiseException */ #if PY_MAJOR_VERSION < 3 static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, CYTHON_UNUSED PyObject *cause) { __Pyx_PyThreadState_declare Py_XINCREF(type); if (!value || value == Py_None) value = NULL; else Py_INCREF(value); if (!tb || tb == Py_None) tb = NULL; else { Py_INCREF(tb); if (!PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto raise_error; } } if (PyType_Check(type)) { #if CYTHON_COMPILING_IN_PYPY if (!value) { Py_INCREF(Py_None); value = Py_None; } #endif PyErr_NormalizeException(&type, &value, &tb); } else { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto raise_error; } value = type; type = (PyObject*) Py_TYPE(type); Py_INCREF(type); if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto raise_error; } } __Pyx_PyThreadState_assign __Pyx_ErrRestore(type, value, tb); return; raise_error: Py_XDECREF(value); Py_XDECREF(type); Py_XDECREF(tb); return; } #else static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) { PyObject* owned_instance = NULL; if (tb == Py_None) { tb = 0; } else if (tb && !PyTraceBack_Check(tb)) { PyErr_SetString(PyExc_TypeError, "raise: arg 3 must be a traceback or None"); goto bad; } if (value == Py_None) value = 0; if (PyExceptionInstance_Check(type)) { if (value) { PyErr_SetString(PyExc_TypeError, "instance exception may not have a separate value"); goto bad; } value = type; type = (PyObject*) Py_TYPE(value); } else if (PyExceptionClass_Check(type)) { PyObject *instance_class = NULL; if (value && PyExceptionInstance_Check(value)) { instance_class = (PyObject*) Py_TYPE(value); if (instance_class != type) { int is_subclass = PyObject_IsSubclass(instance_class, type); if (!is_subclass) { instance_class = NULL; } else if (unlikely(is_subclass == -1)) { goto bad; } else { type = instance_class; } } } if (!instance_class) { PyObject *args; if (!value) args = PyTuple_New(0); else if (PyTuple_Check(value)) { Py_INCREF(value); args = value; } else args = PyTuple_Pack(1, value); if (!args) goto bad; owned_instance = PyObject_Call(type, args, NULL); Py_DECREF(args); if (!owned_instance) goto bad; value = owned_instance; if (!PyExceptionInstance_Check(value)) { PyErr_Format(PyExc_TypeError, "calling %R should have returned an instance of " "BaseException, not %R", type, Py_TYPE(value)); goto bad; } } } else { PyErr_SetString(PyExc_TypeError, "raise: exception class must be a subclass of BaseException"); goto bad; } if (cause) { PyObject *fixed_cause; if (cause == Py_None) { fixed_cause = NULL; } else if (PyExceptionClass_Check(cause)) { fixed_cause = PyObject_CallObject(cause, NULL); if (fixed_cause == NULL) goto bad; } else if (PyExceptionInstance_Check(cause)) { fixed_cause = cause; Py_INCREF(fixed_cause); } else { PyErr_SetString(PyExc_TypeError, "exception causes must derive from " "BaseException"); goto bad; } PyException_SetCause(value, fixed_cause); } PyErr_SetObject(type, value); if (tb) { #if CYTHON_COMPILING_IN_PYPY PyObject *tmp_type, *tmp_value, *tmp_tb; PyErr_Fetch(&tmp_type, &tmp_value, &tmp_tb); Py_INCREF(tb); PyErr_Restore(tmp_type, tmp_value, tb); Py_XDECREF(tmp_tb); #else PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject* tmp_tb = tstate->curexc_traceback; if (tb != tmp_tb) { Py_INCREF(tb); tstate->curexc_traceback = tb; Py_XDECREF(tmp_tb); } #endif } bad: Py_XDECREF(owned_instance); return; } #endif /* GetModuleGlobalName */ static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) { PyObject *result; #if !CYTHON_AVOID_BORROWED_REFS result = PyDict_GetItem(__pyx_d, name); if (likely(result)) { Py_INCREF(result); } else { #else result = PyObject_GetItem(__pyx_d, name); if (!result) { PyErr_Clear(); #endif result = __Pyx_GetBuiltinName(name); } return result; } /* PyFunctionFastCall */ #if CYTHON_FAST_PYCALL #include "frameobject.h" static PyObject* __Pyx_PyFunction_FastCallNoKw(PyCodeObject *co, PyObject **args, Py_ssize_t na, PyObject *globals) { PyFrameObject *f; PyThreadState *tstate = __Pyx_PyThreadState_Current; PyObject **fastlocals; Py_ssize_t i; PyObject *result; assert(globals != NULL); /* XXX Perhaps we should create a specialized PyFrame_New() that doesn't take locals, but does take builtins without sanity checking them. */ assert(tstate != NULL); f = PyFrame_New(tstate, co, globals, NULL); if (f == NULL) { return NULL; } fastlocals = f->f_localsplus; for (i = 0; i < na; i++) { Py_INCREF(*args); fastlocals[i] = *args++; } result = PyEval_EvalFrameEx(f,0); ++tstate->recursion_depth; Py_DECREF(f); --tstate->recursion_depth; return result; } #if 1 || PY_VERSION_HEX < 0x030600B1 static PyObject *__Pyx_PyFunction_FastCallDict(PyObject *func, PyObject **args, int nargs, PyObject *kwargs) { PyCodeObject *co = (PyCodeObject *)PyFunction_GET_CODE(func); PyObject *globals = PyFunction_GET_GLOBALS(func); PyObject *argdefs = PyFunction_GET_DEFAULTS(func); PyObject *closure; #if PY_MAJOR_VERSION >= 3 PyObject *kwdefs; #endif PyObject *kwtuple, **k; PyObject **d; Py_ssize_t nd; Py_ssize_t nk; PyObject *result; assert(kwargs == NULL || PyDict_Check(kwargs)); nk = kwargs ? PyDict_Size(kwargs) : 0; if (Py_EnterRecursiveCall((char*)" while calling a Python object")) { return NULL; } if ( #if PY_MAJOR_VERSION >= 3 co->co_kwonlyargcount == 0 && #endif likely(kwargs == NULL || nk == 0) && co->co_flags == (CO_OPTIMIZED | CO_NEWLOCALS | CO_NOFREE)) { if (argdefs == NULL && co->co_argcount == nargs) { result = __Pyx_PyFunction_FastCallNoKw(co, args, nargs, globals); goto done; } else if (nargs == 0 && argdefs != NULL && co->co_argcount == Py_SIZE(argdefs)) { /* function called with no arguments, but all parameters have a default value: use default values as arguments .*/ args = &PyTuple_GET_ITEM(argdefs, 0); result =__Pyx_PyFunction_FastCallNoKw(co, args, Py_SIZE(argdefs), globals); goto done; } } if (kwargs != NULL) { Py_ssize_t pos, i; kwtuple = PyTuple_New(2 * nk); if (kwtuple == NULL) { result = NULL; goto done; } k = &PyTuple_GET_ITEM(kwtuple, 0); pos = i = 0; while (PyDict_Next(kwargs, &pos, &k[i], &k[i+1])) { Py_INCREF(k[i]); Py_INCREF(k[i+1]); i += 2; } nk = i / 2; } else { kwtuple = NULL; k = NULL; } closure = PyFunction_GET_CLOSURE(func); #if PY_MAJOR_VERSION >= 3 kwdefs = PyFunction_GET_KW_DEFAULTS(func); #endif if (argdefs != NULL) { d = &PyTuple_GET_ITEM(argdefs, 0); nd = Py_SIZE(argdefs); } else { d = NULL; nd = 0; } #if PY_MAJOR_VERSION >= 3 result = PyEval_EvalCodeEx((PyObject*)co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, kwdefs, closure); #else result = PyEval_EvalCodeEx(co, globals, (PyObject *)NULL, args, nargs, k, (int)nk, d, (int)nd, closure); #endif Py_XDECREF(kwtuple); done: Py_LeaveRecursiveCall(); return result; } #endif #endif /* PyCFunctionFastCall */ #if CYTHON_FAST_PYCCALL static CYTHON_INLINE PyObject * __Pyx_PyCFunction_FastCall(PyObject *func_obj, PyObject **args, Py_ssize_t nargs) { PyCFunctionObject *func = (PyCFunctionObject*)func_obj; PyCFunction meth = PyCFunction_GET_FUNCTION(func); PyObject *self = PyCFunction_GET_SELF(func); int flags = PyCFunction_GET_FLAGS(func); assert(PyCFunction_Check(func)); assert(METH_FASTCALL == (flags & ~(METH_CLASS | METH_STATIC | METH_COEXIST | METH_KEYWORDS))); assert(nargs >= 0); assert(nargs == 0 || args != NULL); /* _PyCFunction_FastCallDict() must not be called with an exception set, because it may clear it (directly or indirectly) and so the caller loses its exception */ assert(!PyErr_Occurred()); if ((PY_VERSION_HEX < 0x030700A0) || unlikely(flags & METH_KEYWORDS)) { return (*((__Pyx_PyCFunctionFastWithKeywords)meth)) (self, args, nargs, NULL); } else { return (*((__Pyx_PyCFunctionFast)meth)) (self, args, nargs); } } #endif /* ExtTypeTest */ static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) { if (unlikely(!type)) { PyErr_SetString(PyExc_SystemError, "Missing type object"); return 0; } if (likely(__Pyx_TypeCheck(obj, type))) return 1; PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s", Py_TYPE(obj)->tp_name, type->tp_name); return 0; } /* BufferFallbackError */ static void __Pyx_RaiseBufferFallbackError(void) { PyErr_SetString(PyExc_ValueError, "Buffer acquisition failed on assignment; and then reacquiring the old buffer failed too!"); } /* None */ static CYTHON_INLINE npy_intp __Pyx_div_npy_intp(npy_intp a, npy_intp b) { npy_intp q = a / b; npy_intp r = a - q*b; q -= ((r != 0) & ((r ^ b) < 0)); return q; } /* RaiseTooManyValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) { PyErr_Format(PyExc_ValueError, "too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected); } /* RaiseNeedMoreValuesToUnpack */ static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) { PyErr_Format(PyExc_ValueError, "need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack", index, (index == 1) ? "" : "s"); } /* RaiseNoneIterError */ static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) { PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable"); } /* SaveResetException */ #if CYTHON_FAST_THREAD_STATE static CYTHON_INLINE void __Pyx__ExceptionSave(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #if PY_VERSION_HEX >= 0x030700A2 *type = tstate->exc_state.exc_type; *value = tstate->exc_state.exc_value; *tb = tstate->exc_state.exc_traceback; #else *type = tstate->exc_type; *value = tstate->exc_value; *tb = tstate->exc_traceback; #endif Py_XINCREF(*type); Py_XINCREF(*value); Py_XINCREF(*tb); } static CYTHON_INLINE void __Pyx__ExceptionReset(PyThreadState *tstate, PyObject *type, PyObject *value, PyObject *tb) { PyObject *tmp_type, *tmp_value, *tmp_tb; #if PY_VERSION_HEX >= 0x030700A2 tmp_type = tstate->exc_state.exc_type; tmp_value = tstate->exc_state.exc_value; tmp_tb = tstate->exc_state.exc_traceback; tstate->exc_state.exc_type = type; tstate->exc_state.exc_value = value; tstate->exc_state.exc_traceback = tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = type; tstate->exc_value = value; tstate->exc_traceback = tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); } #endif /* PyErrExceptionMatches */ #if CYTHON_FAST_THREAD_STATE static int __Pyx_PyErr_ExceptionMatchesTuple(PyObject *exc_type, PyObject *tuple) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(tuple); #if PY_MAJOR_VERSION >= 3 for (i=0; i<n; i++) { if (exc_type == PyTuple_GET_ITEM(tuple, i)) return 1; } #endif for (i=0; i<n; i++) { if (__Pyx_PyErr_GivenExceptionMatches(exc_type, PyTuple_GET_ITEM(tuple, i))) return 1; } return 0; } static CYTHON_INLINE int __Pyx_PyErr_ExceptionMatchesInState(PyThreadState* tstate, PyObject* err) { PyObject *exc_type = tstate->curexc_type; if (exc_type == err) return 1; if (unlikely(!exc_type)) return 0; if (unlikely(PyTuple_Check(err))) return __Pyx_PyErr_ExceptionMatchesTuple(exc_type, err); return __Pyx_PyErr_GivenExceptionMatches(exc_type, err); } #endif /* GetException */ #if CYTHON_FAST_THREAD_STATE static int __Pyx__GetException(PyThreadState *tstate, PyObject **type, PyObject **value, PyObject **tb) { #else static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) { #endif PyObject *local_type, *local_value, *local_tb; #if CYTHON_FAST_THREAD_STATE PyObject *tmp_type, *tmp_value, *tmp_tb; local_type = tstate->curexc_type; local_value = tstate->curexc_value; local_tb = tstate->curexc_traceback; tstate->curexc_type = 0; tstate->curexc_value = 0; tstate->curexc_traceback = 0; #else PyErr_Fetch(&local_type, &local_value, &local_tb); #endif PyErr_NormalizeException(&local_type, &local_value, &local_tb); #if CYTHON_FAST_THREAD_STATE if (unlikely(tstate->curexc_type)) #else if (unlikely(PyErr_Occurred())) #endif goto bad; #if PY_MAJOR_VERSION >= 3 if (local_tb) { if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0)) goto bad; } #endif Py_XINCREF(local_tb); Py_XINCREF(local_type); Py_XINCREF(local_value); *type = local_type; *value = local_value; *tb = local_tb; #if CYTHON_FAST_THREAD_STATE #if PY_VERSION_HEX >= 0x030700A2 tmp_type = tstate->exc_state.exc_type; tmp_value = tstate->exc_state.exc_value; tmp_tb = tstate->exc_state.exc_traceback; tstate->exc_state.exc_type = local_type; tstate->exc_state.exc_value = local_value; tstate->exc_state.exc_traceback = local_tb; #else tmp_type = tstate->exc_type; tmp_value = tstate->exc_value; tmp_tb = tstate->exc_traceback; tstate->exc_type = local_type; tstate->exc_value = local_value; tstate->exc_traceback = local_tb; #endif Py_XDECREF(tmp_type); Py_XDECREF(tmp_value); Py_XDECREF(tmp_tb); #else PyErr_SetExcInfo(local_type, local_value, local_tb); #endif return 0; bad: *type = 0; *value = 0; *tb = 0; Py_XDECREF(local_type); Py_XDECREF(local_value); Py_XDECREF(local_tb); return -1; } /* Import */ static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) { PyObject *empty_list = 0; PyObject *module = 0; PyObject *global_dict = 0; PyObject *empty_dict = 0; PyObject *list; #if PY_MAJOR_VERSION < 3 PyObject *py_import; py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import); if (!py_import) goto bad; #endif if (from_list) list = from_list; else { empty_list = PyList_New(0); if (!empty_list) goto bad; list = empty_list; } global_dict = PyModule_GetDict(__pyx_m); if (!global_dict) goto bad; empty_dict = PyDict_New(); if (!empty_dict) goto bad; { #if PY_MAJOR_VERSION >= 3 if (level == -1) { if (strchr(__Pyx_MODULE_NAME, '.')) { module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, 1); if (!module) { if (!PyErr_ExceptionMatches(PyExc_ImportError)) goto bad; PyErr_Clear(); } } level = 0; } #endif if (!module) { #if PY_MAJOR_VERSION < 3 PyObject *py_level = PyInt_FromLong(level); if (!py_level) goto bad; module = PyObject_CallFunctionObjArgs(py_import, name, global_dict, empty_dict, list, py_level, NULL); Py_DECREF(py_level); #else module = PyImport_ImportModuleLevelObject( name, global_dict, empty_dict, list, level); #endif } } bad: #if PY_MAJOR_VERSION < 3 Py_XDECREF(py_import); #endif Py_XDECREF(empty_list); Py_XDECREF(empty_dict); return module; } /* CLineInTraceback */ #ifndef CYTHON_CLINE_IN_TRACEBACK static int __Pyx_CLineForTraceback(CYTHON_UNUSED PyThreadState *tstate, int c_line) { PyObject *use_cline; PyObject *ptype, *pvalue, *ptraceback; #if CYTHON_COMPILING_IN_CPYTHON PyObject **cython_runtime_dict; #endif __Pyx_ErrFetchInState(tstate, &ptype, &pvalue, &ptraceback); #if CYTHON_COMPILING_IN_CPYTHON cython_runtime_dict = _PyObject_GetDictPtr(__pyx_cython_runtime); if (likely(cython_runtime_dict)) { use_cline = PyDict_GetItem(*cython_runtime_dict, __pyx_n_s_cline_in_traceback); } else #endif { PyObject *use_cline_obj = __Pyx_PyObject_GetAttrStr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback); if (use_cline_obj) { use_cline = PyObject_Not(use_cline_obj) ? Py_False : Py_True; Py_DECREF(use_cline_obj); } else { PyErr_Clear(); use_cline = NULL; } } if (!use_cline) { c_line = 0; PyObject_SetAttr(__pyx_cython_runtime, __pyx_n_s_cline_in_traceback, Py_False); } else if (PyObject_Not(use_cline) != 0) { c_line = 0; } __Pyx_ErrRestoreInState(tstate, ptype, pvalue, ptraceback); return c_line; } #endif /* CodeObjectCache */ static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) { int start = 0, mid = 0, end = count - 1; if (end >= 0 && code_line > entries[end].code_line) { return count; } while (start < end) { mid = start + (end - start) / 2; if (code_line < entries[mid].code_line) { end = mid; } else if (code_line > entries[mid].code_line) { start = mid + 1; } else { return mid; } } if (code_line <= entries[mid].code_line) { return mid; } else { return mid + 1; } } static PyCodeObject *__pyx_find_code_object(int code_line) { PyCodeObject* code_object; int pos; if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) { return NULL; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) { return NULL; } code_object = __pyx_code_cache.entries[pos].code_object; Py_INCREF(code_object); return code_object; } static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) { int pos, i; __Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries; if (unlikely(!code_line)) { return; } if (unlikely(!entries)) { entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry)); if (likely(entries)) { __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = 64; __pyx_code_cache.count = 1; entries[0].code_line = code_line; entries[0].code_object = code_object; Py_INCREF(code_object); } return; } pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line); if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) { PyCodeObject* tmp = entries[pos].code_object; entries[pos].code_object = code_object; Py_DECREF(tmp); return; } if (__pyx_code_cache.count == __pyx_code_cache.max_count) { int new_max = __pyx_code_cache.max_count + 64; entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc( __pyx_code_cache.entries, (size_t)new_max*sizeof(__Pyx_CodeObjectCacheEntry)); if (unlikely(!entries)) { return; } __pyx_code_cache.entries = entries; __pyx_code_cache.max_count = new_max; } for (i=__pyx_code_cache.count; i>pos; i--) { entries[i] = entries[i-1]; } entries[pos].code_line = code_line; entries[pos].code_object = code_object; __pyx_code_cache.count++; Py_INCREF(code_object); } /* AddTraceback */ #include "compile.h" #include "frameobject.h" #include "traceback.h" static PyCodeObject* __Pyx_CreateCodeObjectForTraceback( const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyObject *py_srcfile = 0; PyObject *py_funcname = 0; #if PY_MAJOR_VERSION < 3 py_srcfile = PyString_FromString(filename); #else py_srcfile = PyUnicode_FromString(filename); #endif if (!py_srcfile) goto bad; if (c_line) { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #else py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line); #endif } else { #if PY_MAJOR_VERSION < 3 py_funcname = PyString_FromString(funcname); #else py_funcname = PyUnicode_FromString(funcname); #endif } if (!py_funcname) goto bad; py_code = __Pyx_PyCode_New( 0, 0, 0, 0, 0, __pyx_empty_bytes, /*PyObject *code,*/ __pyx_empty_tuple, /*PyObject *consts,*/ __pyx_empty_tuple, /*PyObject *names,*/ __pyx_empty_tuple, /*PyObject *varnames,*/ __pyx_empty_tuple, /*PyObject *freevars,*/ __pyx_empty_tuple, /*PyObject *cellvars,*/ py_srcfile, /*PyObject *filename,*/ py_funcname, /*PyObject *name,*/ py_line, __pyx_empty_bytes /*PyObject *lnotab*/ ); Py_DECREF(py_srcfile); Py_DECREF(py_funcname); return py_code; bad: Py_XDECREF(py_srcfile); Py_XDECREF(py_funcname); return NULL; } static void __Pyx_AddTraceback(const char *funcname, int c_line, int py_line, const char *filename) { PyCodeObject *py_code = 0; PyFrameObject *py_frame = 0; PyThreadState *tstate = __Pyx_PyThreadState_Current; if (c_line) { c_line = __Pyx_CLineForTraceback(tstate, c_line); } py_code = __pyx_find_code_object(c_line ? -c_line : py_line); if (!py_code) { py_code = __Pyx_CreateCodeObjectForTraceback( funcname, c_line, py_line, filename); if (!py_code) goto bad; __pyx_insert_code_object(c_line ? -c_line : py_line, py_code); } py_frame = PyFrame_New( tstate, /*PyThreadState *tstate,*/ py_code, /*PyCodeObject *code,*/ __pyx_d, /*PyObject *globals,*/ 0 /*PyObject *locals*/ ); if (!py_frame) goto bad; __Pyx_PyFrame_SetLineNumber(py_frame, py_line); PyTraceBack_Here(py_frame); bad: Py_XDECREF(py_code); Py_XDECREF(py_frame); } #if PY_MAJOR_VERSION < 3 static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) { if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags); if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags); PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name); return -1; } static void __Pyx_ReleaseBuffer(Py_buffer *view) { PyObject *obj = view->obj; if (!obj) return; if (PyObject_CheckBuffer(obj)) { PyBuffer_Release(view); return; } if ((0)) {} else if (__Pyx_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); view->obj = NULL; Py_DECREF(obj); } #endif /* CIntFromPyVerify */ #define __PYX_VERIFY_RETURN_INT(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 0) #define __PYX_VERIFY_RETURN_INT_EXC(target_type, func_type, func_value)\ __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, 1) #define __PYX__VERIFY_RETURN_INT(target_type, func_type, func_value, exc)\ {\ func_type value = func_value;\ if (sizeof(target_type) < sizeof(func_type)) {\ if (unlikely(value != (func_type) (target_type) value)) {\ func_type zero = 0;\ if (exc && unlikely(value == (func_type)-1 && PyErr_Occurred()))\ return (target_type) -1;\ if (is_unsigned && unlikely(value < zero))\ goto raise_neg_overflow;\ else\ goto raise_overflow;\ }\ }\ return (target_type) value;\ } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(long) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(long) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(long) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(long), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_int32(npy_int32 value) { const npy_int32 neg_one = (npy_int32) -1, const_zero = (npy_int32) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(npy_int32) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(npy_int32) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(npy_int32) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(npy_int32) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(npy_int32) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(npy_int32), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(int) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(int) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(int) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(int), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_npy_uint8(npy_uint8 value) { const npy_uint8 neg_one = (npy_uint8) -1, const_zero = (npy_uint8) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(npy_uint8) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(npy_uint8) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(npy_uint8) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(npy_uint8) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(npy_uint8) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(npy_uint8), little, !is_unsigned); } } /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) { const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = (Py_intptr_t) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(Py_intptr_t) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(Py_intptr_t) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(Py_intptr_t) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(Py_intptr_t) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t), little, !is_unsigned); } } /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return ::std::complex< float >(x, y); } #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { return x + y*(__pyx_t_float_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) { __pyx_t_float_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sum_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_diff_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prod_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabsf(b.real) >= fabsf(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { float r = b.imag / b.real; float s = 1.0 / (b.real + b.imag * r); return __pyx_t_float_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { float r = b.real / b.imag; float s = 1.0 / (b.imag + b.real * r); return __pyx_t_float_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quot_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { if (b.imag == 0) { return __pyx_t_float_complex_from_parts(a.real / b.real, a.imag / b.real); } else { float denom = b.real * b.real + b.imag * b.imag; return __pyx_t_float_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_neg_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_float(__pyx_t_float_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conj_float(__pyx_t_float_complex a) { __pyx_t_float_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE float __Pyx_c_abs_float(__pyx_t_float_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrtf(z.real*z.real + z.imag*z.imag); #else return hypotf(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_pow_float(__pyx_t_float_complex a, __pyx_t_float_complex b) { __pyx_t_float_complex z; float r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { float denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(a, a); case 3: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, a); case 4: z = __Pyx_c_prod_float(a, a); return __Pyx_c_prod_float(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = powf(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2f(0, -1); } } else { r = __Pyx_c_abs_float(a); theta = atan2f(a.imag, a.real); } lnr = logf(r); z_r = expf(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cosf(z_theta); z.imag = z_r * sinf(z_theta); return z; } #endif #endif /* Declarations */ #if CYTHON_CCOMPLEX #ifdef __cplusplus static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return ::std::complex< double >(x, y); } #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { return x + y*(__pyx_t_double_complex)_Complex_I; } #endif #else static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) { __pyx_t_double_complex z; z.real = x; z.imag = y; return z; } #endif /* Arithmetic */ #if CYTHON_CCOMPLEX #else static CYTHON_INLINE int __Pyx_c_eq_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { return (a.real == b.real) && (a.imag == b.imag); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real + b.real; z.imag = a.imag + b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real - b.real; z.imag = a.imag - b.imag; return z; } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; z.real = a.real * b.real - a.imag * b.imag; z.imag = a.real * b.imag + a.imag * b.real; return z; } #if 1 static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else if (fabs(b.real) >= fabs(b.imag)) { if (b.real == 0 && b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.imag); } else { double r = b.imag / b.real; double s = 1.0 / (b.real + b.imag * r); return __pyx_t_double_complex_from_parts( (a.real + a.imag * r) * s, (a.imag - a.real * r) * s); } } else { double r = b.real / b.imag; double s = 1.0 / (b.imag + b.real * r); return __pyx_t_double_complex_from_parts( (a.real * r + a.imag) * s, (a.imag * r - a.real) * s); } } #else static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { if (b.imag == 0) { return __pyx_t_double_complex_from_parts(a.real / b.real, a.imag / b.real); } else { double denom = b.real * b.real + b.imag * b.imag; return __pyx_t_double_complex_from_parts( (a.real * b.real + a.imag * b.imag) / denom, (a.imag * b.real - a.real * b.imag) / denom); } } #endif static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = -a.real; z.imag = -a.imag; return z; } static CYTHON_INLINE int __Pyx_c_is_zero_double(__pyx_t_double_complex a) { return (a.real == 0) && (a.imag == 0); } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj_double(__pyx_t_double_complex a) { __pyx_t_double_complex z; z.real = a.real; z.imag = -a.imag; return z; } #if 1 static CYTHON_INLINE double __Pyx_c_abs_double(__pyx_t_double_complex z) { #if !defined(HAVE_HYPOT) || defined(_MSC_VER) return sqrt(z.real*z.real + z.imag*z.imag); #else return hypot(z.real, z.imag); #endif } static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow_double(__pyx_t_double_complex a, __pyx_t_double_complex b) { __pyx_t_double_complex z; double r, lnr, theta, z_r, z_theta; if (b.imag == 0 && b.real == (int)b.real) { if (b.real < 0) { double denom = a.real * a.real + a.imag * a.imag; a.real = a.real / denom; a.imag = -a.imag / denom; b.real = -b.real; } switch ((int)b.real) { case 0: z.real = 1; z.imag = 0; return z; case 1: return a; case 2: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(a, a); case 3: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, a); case 4: z = __Pyx_c_prod_double(a, a); return __Pyx_c_prod_double(z, z); } } if (a.imag == 0) { if (a.real == 0) { return a; } else if (b.imag == 0) { z.real = pow(a.real, b.real); z.imag = 0; return z; } else if (a.real > 0) { r = a.real; theta = 0; } else { r = -a.real; theta = atan2(0, -1); } } else { r = __Pyx_c_abs_double(a); theta = atan2(a.imag, a.real); } lnr = log(r); z_r = exp(lnr * b.real - theta * b.imag); z_theta = theta * b.real + lnr * b.imag; z.real = z_r * cos(z_theta); z.imag = z_r * sin(z_theta); return z; } #endif #endif /* CIntToPy */ static CYTHON_INLINE PyObject* __Pyx_PyInt_From_enum__NPY_TYPES(enum NPY_TYPES value) { const enum NPY_TYPES neg_one = (enum NPY_TYPES) -1, const_zero = (enum NPY_TYPES) 0; const int is_unsigned = neg_one > const_zero; if (is_unsigned) { if (sizeof(enum NPY_TYPES) < sizeof(long)) { return PyInt_FromLong((long) value); } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned long)) { return PyLong_FromUnsignedLong((unsigned long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(unsigned PY_LONG_LONG)) { return PyLong_FromUnsignedLongLong((unsigned PY_LONG_LONG) value); #endif } } else { if (sizeof(enum NPY_TYPES) <= sizeof(long)) { return PyInt_FromLong((long) value); #ifdef HAVE_LONG_LONG } else if (sizeof(enum NPY_TYPES) <= sizeof(PY_LONG_LONG)) { return PyLong_FromLongLong((PY_LONG_LONG) value); #endif } } { int one = 1; int little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&value; return _PyLong_FromByteArray(bytes, sizeof(enum NPY_TYPES), little, !is_unsigned); } } /* CIntFromPy */ static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) { const int neg_one = (int) -1, const_zero = (int) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(int) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (int) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case 1: __PYX_VERIFY_RETURN_INT(int, digit, digits[0]) case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 2 * PyLong_SHIFT) { return (int) (((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 3 * PyLong_SHIFT) { return (int) (((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) >= 4 * PyLong_SHIFT) { return (int) (((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (int) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(int) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (int) 0; case -1: __PYX_VERIFY_RETURN_INT(int, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(int, digit, +digits[0]) case -2: if (8 * sizeof(int) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) (((int)-1)*(((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 2: if (8 * sizeof(int) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { return (int) ((((((int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -3: if (8 * sizeof(int) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 3: if (8 * sizeof(int) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { return (int) ((((((((int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case -4: if (8 * sizeof(int) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) (((int)-1)*(((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; case 4: if (8 * sizeof(int) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(int, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(int) - 1 > 4 * PyLong_SHIFT) { return (int) ((((((((((int)digits[3]) << PyLong_SHIFT) | (int)digits[2]) << PyLong_SHIFT) | (int)digits[1]) << PyLong_SHIFT) | (int)digits[0]))); } } break; } #endif if (sizeof(int) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(int, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(int) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(int, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else int val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (int) -1; } } else { int val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (int) -1; val = __Pyx_PyInt_As_int(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to int"); return (int) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to int"); return (int) -1; } /* CIntFromPy */ static CYTHON_INLINE npy_int32 __Pyx_PyInt_As_npy_int32(PyObject *x) { const npy_int32 neg_one = (npy_int32) -1, const_zero = (npy_int32) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(npy_int32) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(npy_int32, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (npy_int32) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (npy_int32) 0; case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, digits[0]) case 2: if (8 * sizeof(npy_int32) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) >= 2 * PyLong_SHIFT) { return (npy_int32) (((((npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0])); } } break; case 3: if (8 * sizeof(npy_int32) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) >= 3 * PyLong_SHIFT) { return (npy_int32) (((((((npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0])); } } break; case 4: if (8 * sizeof(npy_int32) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) >= 4 * PyLong_SHIFT) { return (npy_int32) (((((((((npy_int32)digits[3]) << PyLong_SHIFT) | (npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (npy_int32) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(npy_int32) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(npy_int32, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(npy_int32) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(npy_int32, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (npy_int32) 0; case -1: __PYX_VERIFY_RETURN_INT(npy_int32, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(npy_int32, digit, +digits[0]) case -2: if (8 * sizeof(npy_int32) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 2 * PyLong_SHIFT) { return (npy_int32) (((npy_int32)-1)*(((((npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; case 2: if (8 * sizeof(npy_int32) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 2 * PyLong_SHIFT) { return (npy_int32) ((((((npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; case -3: if (8 * sizeof(npy_int32) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 3 * PyLong_SHIFT) { return (npy_int32) (((npy_int32)-1)*(((((((npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; case 3: if (8 * sizeof(npy_int32) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 3 * PyLong_SHIFT) { return (npy_int32) ((((((((npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; case -4: if (8 * sizeof(npy_int32) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 4 * PyLong_SHIFT) { return (npy_int32) (((npy_int32)-1)*(((((((((npy_int32)digits[3]) << PyLong_SHIFT) | (npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; case 4: if (8 * sizeof(npy_int32) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(npy_int32, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(npy_int32) - 1 > 4 * PyLong_SHIFT) { return (npy_int32) ((((((((((npy_int32)digits[3]) << PyLong_SHIFT) | (npy_int32)digits[2]) << PyLong_SHIFT) | (npy_int32)digits[1]) << PyLong_SHIFT) | (npy_int32)digits[0]))); } } break; } #endif if (sizeof(npy_int32) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(npy_int32, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(npy_int32) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(npy_int32, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else npy_int32 val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (npy_int32) -1; } } else { npy_int32 val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (npy_int32) -1; val = __Pyx_PyInt_As_npy_int32(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to npy_int32"); return (npy_int32) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to npy_int32"); return (npy_int32) -1; } /* CIntFromPy */ static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) { const long neg_one = (long) -1, const_zero = (long) 0; const int is_unsigned = neg_one > const_zero; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x))) { if (sizeof(long) < sizeof(long)) { __PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG(x)) } else { long val = PyInt_AS_LONG(x); if (is_unsigned && unlikely(val < 0)) { goto raise_neg_overflow; } return (long) val; } } else #endif if (likely(PyLong_Check(x))) { if (is_unsigned) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case 1: __PYX_VERIFY_RETURN_INT(long, digit, digits[0]) case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 2 * PyLong_SHIFT) { return (long) (((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 3 * PyLong_SHIFT) { return (long) (((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) >= 4 * PyLong_SHIFT) { return (long) (((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0])); } } break; } #endif #if CYTHON_COMPILING_IN_CPYTHON if (unlikely(Py_SIZE(x) < 0)) { goto raise_neg_overflow; } #else { int result = PyObject_RichCompareBool(x, Py_False, Py_LT); if (unlikely(result < 0)) return (long) -1; if (unlikely(result == 1)) goto raise_neg_overflow; } #endif if (sizeof(long) <= sizeof(unsigned long)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned long, PyLong_AsUnsignedLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(unsigned PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, unsigned PY_LONG_LONG, PyLong_AsUnsignedLongLong(x)) #endif } } else { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)x)->ob_digit; switch (Py_SIZE(x)) { case 0: return (long) 0; case -1: __PYX_VERIFY_RETURN_INT(long, sdigit, (sdigit) (-(sdigit)digits[0])) case 1: __PYX_VERIFY_RETURN_INT(long, digit, +digits[0]) case -2: if (8 * sizeof(long) - 1 > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) (((long)-1)*(((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 2: if (8 * sizeof(long) > 1 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 2 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { return (long) ((((((long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -3: if (8 * sizeof(long) - 1 > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 3: if (8 * sizeof(long) > 2 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 3 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { return (long) ((((((((long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case -4: if (8 * sizeof(long) - 1 > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, long, -(long) (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) (((long)-1)*(((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; case 4: if (8 * sizeof(long) > 3 * PyLong_SHIFT) { if (8 * sizeof(unsigned long) > 4 * PyLong_SHIFT) { __PYX_VERIFY_RETURN_INT(long, unsigned long, (((((((((unsigned long)digits[3]) << PyLong_SHIFT) | (unsigned long)digits[2]) << PyLong_SHIFT) | (unsigned long)digits[1]) << PyLong_SHIFT) | (unsigned long)digits[0]))) } else if (8 * sizeof(long) - 1 > 4 * PyLong_SHIFT) { return (long) ((((((((((long)digits[3]) << PyLong_SHIFT) | (long)digits[2]) << PyLong_SHIFT) | (long)digits[1]) << PyLong_SHIFT) | (long)digits[0]))); } } break; } #endif if (sizeof(long) <= sizeof(long)) { __PYX_VERIFY_RETURN_INT_EXC(long, long, PyLong_AsLong(x)) #ifdef HAVE_LONG_LONG } else if (sizeof(long) <= sizeof(PY_LONG_LONG)) { __PYX_VERIFY_RETURN_INT_EXC(long, PY_LONG_LONG, PyLong_AsLongLong(x)) #endif } } { #if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray) PyErr_SetString(PyExc_RuntimeError, "_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers"); #else long val; PyObject *v = __Pyx_PyNumber_IntOrLong(x); #if PY_MAJOR_VERSION < 3 if (likely(v) && !PyLong_Check(v)) { PyObject *tmp = v; v = PyNumber_Long(tmp); Py_DECREF(tmp); } #endif if (likely(v)) { int one = 1; int is_little = (int)*(unsigned char *)&one; unsigned char *bytes = (unsigned char *)&val; int ret = _PyLong_AsByteArray((PyLongObject *)v, bytes, sizeof(val), is_little, !is_unsigned); Py_DECREF(v); if (likely(!ret)) return val; } #endif return (long) -1; } } else { long val; PyObject *tmp = __Pyx_PyNumber_IntOrLong(x); if (!tmp) return (long) -1; val = __Pyx_PyInt_As_long(tmp); Py_DECREF(tmp); return val; } raise_overflow: PyErr_SetString(PyExc_OverflowError, "value too large to convert to long"); return (long) -1; raise_neg_overflow: PyErr_SetString(PyExc_OverflowError, "can't convert negative value to long"); return (long) -1; } /* FastTypeChecks */ #if CYTHON_COMPILING_IN_CPYTHON static int __Pyx_InBases(PyTypeObject *a, PyTypeObject *b) { while (a) { a = a->tp_base; if (a == b) return 1; } return b == &PyBaseObject_Type; } static CYTHON_INLINE int __Pyx_IsSubtype(PyTypeObject *a, PyTypeObject *b) { PyObject *mro; if (a == b) return 1; mro = a->tp_mro; if (likely(mro)) { Py_ssize_t i, n; n = PyTuple_GET_SIZE(mro); for (i = 0; i < n; i++) { if (PyTuple_GET_ITEM(mro, i) == (PyObject *)b) return 1; } return 0; } return __Pyx_InBases(a, b); } #if PY_MAJOR_VERSION == 2 static int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject* exc_type2) { PyObject *exception, *value, *tb; int res; __Pyx_PyThreadState_declare __Pyx_PyThreadState_assign __Pyx_ErrFetch(&exception, &value, &tb); res = exc_type1 ? PyObject_IsSubclass(err, exc_type1) : 0; if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } if (!res) { res = PyObject_IsSubclass(err, exc_type2); if (unlikely(res == -1)) { PyErr_WriteUnraisable(err); res = 0; } } __Pyx_ErrRestore(exception, value, tb); return res; } #else static CYTHON_INLINE int __Pyx_inner_PyErr_GivenExceptionMatches2(PyObject *err, PyObject* exc_type1, PyObject *exc_type2) { int res = exc_type1 ? __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type1) : 0; if (!res) { res = __Pyx_IsSubtype((PyTypeObject*)err, (PyTypeObject*)exc_type2); } return res; } #endif static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches(PyObject *err, PyObject* exc_type) { if (likely(err == exc_type)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, NULL, exc_type); } return PyErr_GivenExceptionMatches(err, exc_type); } static CYTHON_INLINE int __Pyx_PyErr_GivenExceptionMatches2(PyObject *err, PyObject *exc_type1, PyObject *exc_type2) { if (likely(err == exc_type1 || err == exc_type2)) return 1; if (likely(PyExceptionClass_Check(err))) { return __Pyx_inner_PyErr_GivenExceptionMatches2(err, exc_type1, exc_type2); } return (PyErr_GivenExceptionMatches(err, exc_type1) || PyErr_GivenExceptionMatches(err, exc_type2)); } #endif /* CheckBinaryVersion */ static int __Pyx_check_binary_version(void) { char ctversion[4], rtversion[4]; PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion()); if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) { char message[200]; PyOS_snprintf(message, sizeof(message), "compiletime version %s of module '%.100s' " "does not match runtime version %s", ctversion, __Pyx_MODULE_NAME, rtversion); return PyErr_WarnEx(NULL, message, 1); } return 0; } /* ModuleImport */ #ifndef __PYX_HAVE_RT_ImportModule #define __PYX_HAVE_RT_ImportModule static PyObject *__Pyx_ImportModule(const char *name) { PyObject *py_name = 0; PyObject *py_module = 0; py_name = __Pyx_PyIdentifier_FromString(name); if (!py_name) goto bad; py_module = PyImport_Import(py_name); Py_DECREF(py_name); return py_module; bad: Py_XDECREF(py_name); return 0; } #endif /* TypeImport */ #ifndef __PYX_HAVE_RT_ImportType #define __PYX_HAVE_RT_ImportType static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict) { PyObject *py_module = 0; PyObject *result = 0; PyObject *py_name = 0; char warning[200]; Py_ssize_t basicsize; #ifdef Py_LIMITED_API PyObject *py_basicsize; #endif py_module = __Pyx_ImportModule(module_name); if (!py_module) goto bad; py_name = __Pyx_PyIdentifier_FromString(class_name); if (!py_name) goto bad; result = PyObject_GetAttr(py_module, py_name); Py_DECREF(py_name); py_name = 0; Py_DECREF(py_module); py_module = 0; if (!result) goto bad; if (!PyType_Check(result)) { PyErr_Format(PyExc_TypeError, "%.200s.%.200s is not a type object", module_name, class_name); goto bad; } #ifndef Py_LIMITED_API basicsize = ((PyTypeObject *)result)->tp_basicsize; #else py_basicsize = PyObject_GetAttrString(result, "__basicsize__"); if (!py_basicsize) goto bad; basicsize = PyLong_AsSsize_t(py_basicsize); Py_DECREF(py_basicsize); py_basicsize = 0; if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred()) goto bad; #endif if (!strict && (size_t)basicsize > size) { PyOS_snprintf(warning, sizeof(warning), "%s.%s size changed, may indicate binary incompatibility. Expected %zd, got %zd", module_name, class_name, basicsize, size); if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad; } else if ((size_t)basicsize != size) { PyErr_Format(PyExc_ValueError, "%.200s.%.200s has the wrong size, try recompiling. Expected %zd, got %zd", module_name, class_name, basicsize, size); goto bad; } return (PyTypeObject *)result; bad: Py_XDECREF(py_module); Py_XDECREF(result); return NULL; } #endif /* InitStrings */ static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) { while (t->p) { #if PY_MAJOR_VERSION < 3 if (t->is_unicode) { *t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL); } else if (t->intern) { *t->p = PyString_InternFromString(t->s); } else { *t->p = PyString_FromStringAndSize(t->s, t->n - 1); } #else if (t->is_unicode | t->is_str) { if (t->intern) { *t->p = PyUnicode_InternFromString(t->s); } else if (t->encoding) { *t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL); } else { *t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1); } } else { *t->p = PyBytes_FromStringAndSize(t->s, t->n - 1); } #endif if (!*t->p) return -1; if (PyObject_Hash(*t->p) == -1) PyErr_Clear(); ++t; } return 0; } static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(const char* c_str) { return __Pyx_PyUnicode_FromStringAndSize(c_str, (Py_ssize_t)strlen(c_str)); } static CYTHON_INLINE const char* __Pyx_PyObject_AsString(PyObject* o) { Py_ssize_t ignore; return __Pyx_PyObject_AsStringAndSize(o, &ignore); } #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT #if !CYTHON_PEP393_ENABLED static const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { char* defenc_c; PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL); if (!defenc) return NULL; defenc_c = PyBytes_AS_STRING(defenc); #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII { char* end = defenc_c + PyBytes_GET_SIZE(defenc); char* c; for (c = defenc_c; c < end; c++) { if ((unsigned char) (*c) >= 128) { PyUnicode_AsASCIIString(o); return NULL; } } } #endif *length = PyBytes_GET_SIZE(defenc); return defenc_c; } #else static CYTHON_INLINE const char* __Pyx_PyUnicode_AsStringAndSize(PyObject* o, Py_ssize_t *length) { if (unlikely(__Pyx_PyUnicode_READY(o) == -1)) return NULL; #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII if (likely(PyUnicode_IS_ASCII(o))) { *length = PyUnicode_GET_LENGTH(o); return PyUnicode_AsUTF8(o); } else { PyUnicode_AsASCIIString(o); return NULL; } #else return PyUnicode_AsUTF8AndSize(o, length); #endif } #endif #endif static CYTHON_INLINE const char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) { #if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT if ( #if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII __Pyx_sys_getdefaultencoding_not_ascii && #endif PyUnicode_Check(o)) { return __Pyx_PyUnicode_AsStringAndSize(o, length); } else #endif #if (!CYTHON_COMPILING_IN_PYPY) || (defined(PyByteArray_AS_STRING) && defined(PyByteArray_GET_SIZE)) if (PyByteArray_Check(o)) { *length = PyByteArray_GET_SIZE(o); return PyByteArray_AS_STRING(o); } else #endif { char* result; int r = PyBytes_AsStringAndSize(o, &result, length); if (unlikely(r < 0)) { return NULL; } else { return result; } } } static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) { int is_true = x == Py_True; if (is_true | (x == Py_False) | (x == Py_None)) return is_true; else return PyObject_IsTrue(x); } static PyObject* __Pyx_PyNumber_IntOrLongWrongResultType(PyObject* result, const char* type_name) { #if PY_MAJOR_VERSION >= 3 if (PyLong_Check(result)) { if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1, "__int__ returned non-int (type %.200s). " "The ability to return an instance of a strict subclass of int " "is deprecated, and may be removed in a future version of Python.", Py_TYPE(result)->tp_name)) { Py_DECREF(result); return NULL; } return result; } #endif PyErr_Format(PyExc_TypeError, "__%.4s__ returned non-%.4s (type %.200s)", type_name, type_name, Py_TYPE(result)->tp_name); Py_DECREF(result); return NULL; } static CYTHON_INLINE PyObject* __Pyx_PyNumber_IntOrLong(PyObject* x) { #if CYTHON_USE_TYPE_SLOTS PyNumberMethods *m; #endif const char *name = NULL; PyObject *res = NULL; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_Check(x) || PyLong_Check(x))) #else if (likely(PyLong_Check(x))) #endif return __Pyx_NewRef(x); #if CYTHON_USE_TYPE_SLOTS m = Py_TYPE(x)->tp_as_number; #if PY_MAJOR_VERSION < 3 if (m && m->nb_int) { name = "int"; res = m->nb_int(x); } else if (m && m->nb_long) { name = "long"; res = m->nb_long(x); } #else if (likely(m && m->nb_int)) { name = "int"; res = m->nb_int(x); } #endif #else if (!PyBytes_CheckExact(x) && !PyUnicode_CheckExact(x)) { res = PyNumber_Int(x); } #endif if (likely(res)) { #if PY_MAJOR_VERSION < 3 if (unlikely(!PyInt_Check(res) && !PyLong_Check(res))) { #else if (unlikely(!PyLong_CheckExact(res))) { #endif return __Pyx_PyNumber_IntOrLongWrongResultType(res, name); } } else if (!PyErr_Occurred()) { PyErr_SetString(PyExc_TypeError, "an integer is required"); } return res; } static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) { Py_ssize_t ival; PyObject *x; #if PY_MAJOR_VERSION < 3 if (likely(PyInt_CheckExact(b))) { if (sizeof(Py_ssize_t) >= sizeof(long)) return PyInt_AS_LONG(b); else return PyInt_AsSsize_t(x); } #endif if (likely(PyLong_CheckExact(b))) { #if CYTHON_USE_PYLONG_INTERNALS const digit* digits = ((PyLongObject*)b)->ob_digit; const Py_ssize_t size = Py_SIZE(b); if (likely(__Pyx_sst_abs(size) <= 1)) { ival = likely(size) ? digits[0] : 0; if (size == -1) ival = -ival; return ival; } else { switch (size) { case 2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return (Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -2: if (8 * sizeof(Py_ssize_t) > 2 * PyLong_SHIFT) { return -(Py_ssize_t) (((((size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return (Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -3: if (8 * sizeof(Py_ssize_t) > 3 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case 4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return (Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; case -4: if (8 * sizeof(Py_ssize_t) > 4 * PyLong_SHIFT) { return -(Py_ssize_t) (((((((((size_t)digits[3]) << PyLong_SHIFT) | (size_t)digits[2]) << PyLong_SHIFT) | (size_t)digits[1]) << PyLong_SHIFT) | (size_t)digits[0])); } break; } } #endif return PyLong_AsSsize_t(b); } x = PyNumber_Index(b); if (!x) return -1; ival = PyInt_AsSsize_t(x); Py_DECREF(x); return ival; } static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) { return PyInt_FromSize_t(ival); } #endif /* Py_PYTHON_H */
41.345011
906
0.615162
[ "object", "shape" ]
2d0a1868525cf17c6d90f3a04617c6c22e182a58
11,633
cpp
C++
src/engine.cpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
7
2019-05-18T06:59:03.000Z
2020-08-01T01:50:55.000Z
src/engine.cpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
null
null
null
src/engine.cpp
davemoore22/libtcod-painters-algorithm
b67118b5d93150b80a1dcdf247f3433f648415f1
[ "MIT" ]
null
null
null
// Copyright 2019 Dave Moore // // 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<iostream> #include "libtcod.hpp" #include "actor.hpp" #include "map.hpp" #include "engine.hpp" Engine::Engine() : fovRadius(10), computeFov(true) { TCODConsole::setCustomFont("terminal.png", TCOD_FONT_LAYOUT_ASCII_INROW | TCOD_FONT_TYPE_GREYSCALE); TCODConsole::initRoot(150, 81,"libtcod First Person demo", false); player = new Actor(40,25,'@',TCODColor::white, true); actors.push(player); map = new Map(80,45); setup_render(); facing = 1; TCODSystem::setFps(30); } void Engine::render() { TCODConsole::root->clear(); // draw the map render_3d(); map->render(); // draw the actors for (Actor **iterator=actors.begin(); iterator != actors.end(); iterator++) { Actor *actor=*iterator; if ( map->isInFov(actor->x,actor->y) ) { actor->render(); } } std::string str; if (facing == 1) { str = "Facing: North"; } else if (facing == 2) { str = "Facing: South"; } else if (facing == 3) { str = "Facing: West"; } else if (facing == 4) { str = "Facing: East"; } TCODConsole::root->setDefaultBackground(TCODColor::black); TCODConsole::root->setDefaultForeground(TCODColor::white); TCODConsole::root->print(2, 70, str); TCODConsole::root->setDefaultForeground(TCODColor::yellow); TCODConsole::root->print(2, 75, "Libtcod First Person Copyright (C) 2019 Dave Moore"); TCODConsole::root->setDefaultForeground(TCODColor::orange); TCODConsole::root->print(2, 77, "davemoore22@gmail.com"); TCODConsole::root->setDefaultForeground(TCODColor::red); TCODConsole::root->print(2, 79, "Code released under MIT License"); TCODConsole::root->setDefaultForeground(TCODColor::silver); TCODConsole::root->print(70, 75, "Artwork by Clint Bellanger"); TCODConsole::root->setDefaultForeground(TCODColor::cyan); TCODConsole::root->print(70, 77, "http://heroinedusk.com and http://clintbellanger.net"); TCODConsole::root->print(70, 78, "https://opengameart.org/content/first-person-dungeon-crawl-art-pack"); TCODConsole::root->setDefaultForeground(TCODColor::silver); std::string version = "Powered by Libtcod " + std::to_string(TCOD_MAJOR_VERSION) + "." + std::to_string(TCOD_MINOR_VERSION) + "." + std::to_string(TCOD_PATCHLEVEL); TCODConsole::root->print(70, 70, version); } void Engine:: setup_render() { OffScreenConsole = new TCODConsole(160, 120); DungeonWalls = new TCODConsole(640, 240); DungeonFloor = new TCODConsole(640, 240); DungeonCeiling = new TCODConsole(640, 240); TCODImage* WallsImage = new TCODImage("dungeon_wall.png"); TCODImage* FloorsImage = new TCODImage("dungeon_floor.png"); TCODImage* CeilingImage = new TCODImage("dungeon_ceiling.png"); WallsImage->blitRect(DungeonWalls, 0, 0); FloorsImage->blitRect(DungeonFloor, 0, 0); CeilingImage->blitRect(DungeonCeiling, 0, 0); DungeonWalls->setKeyColor(TCODColor::black); DungeonFloor->setKeyColor(TCODColor::black); DungeonCeiling->setKeyColor(TCODColor::black); OffScreenConsole->setKeyColor(TCODColor::black); width[0] = 80; height[0] = 120; src_x[0] = 0; src_y[0] = 0; dest_x[0] = 0; dest_y[0] = 0; width[1] = 80; height[1] = 120; src_x[1] = 80; src_y[1] = 0; dest_x[1] = 80; dest_y[1] = 0; width[2] = 80; height[2] = 120; src_x[2] = 160; src_y[2] = 0; dest_x[2] = 0; dest_y[2] = 0; width[3] = 80; height[3] = 120; src_x[3] = 240; src_y[3] = 0; dest_x[3] = 80; dest_y[3] = 0; width[4] = 160; height[4] = 120; src_x[4] = 320; src_y[4] = 0; dest_x[4] = 0; dest_y[4] = 0; width[5] = 80; height[5] = 120; src_x[5] = 480; src_y[5] = 0; dest_x[5] = 0; dest_y[5] = 0; width[6] = 80; height[6] = 120; src_x[6] = 560; src_y[6] = 0; dest_x[6] = 80; dest_y[6] = 0; width[7] = 80; height[7] = 120; src_x[7] = 0; src_y[7] = 120; dest_x[7] = 0; dest_y[7] = 0; width[8] = 80; height[8] = 120; src_x[8] = 80; src_y[8] = 120; dest_x[8] = 80; dest_y[8] = 0; width[9] = 160; height[9] = 120; src_x[9] = 160; src_y[9] = 120; dest_x[9] = 0; dest_y[9] = 0; width[10] = 80; height[10] = 120; src_x[10] = 320; src_y[10] = 120; dest_x[10] = 0; dest_y[10] = 0; width[11] = 80; height[11] = 120; src_x[11] = 400; src_y[11] = 120; dest_x[11] = 80; dest_y[11] = 0; width[12] = 160; height[12] = 120; src_x[12] = 480; src_y[12] = 120; dest_x[12] = 0; dest_y[12] = 0; } Engine::~Engine() { actors.clearAndDelete(); delete map; } void Engine::update() { TCOD_key_t key; TCODSystem::checkForEvent(TCOD_EVENT_KEY_PRESS,&key,NULL); switch(key.vk) { // FORWARD case TCODK_UP: // North if (facing == 1) { if (!map->isWall(player->x, player->y - 1)) { player->y--; computeFov=true; } } // South else if (facing == 2) { if (!map->isWall(player->x, player->y + 1)) { player->y++; computeFov=true; } // West } else if (facing == 3) { if (!map->isWall(player->x - 1, player->y)) { player->x--; computeFov=true; } // East } else if (facing == 4) { if (!map->isWall(player->x + 1, player->y)) { player->x++; computeFov=true; } } break; // BACKWARDS case TCODK_DOWN: // North if (facing == 1) { if (!map->isWall(player->x, player->y + 1)) { player->y++; computeFov=true; } } // South else if (facing == 2) { if (!map->isWall(player->x, player->y - 1)) { player->y--; computeFov=true; } // West } else if (facing == 3) { if (!map->isWall(player->x + 1, player->y)) { player->x++; computeFov=true; } // East } else if (facing == 4) { if (!map->isWall(player->x - 1, player->y)) { player->x--; computeFov=true; } } break; case TCODK_LEFT : if (facing == 1) { facing = 3; } else if (facing == 2) { facing = 4; } else if (facing == 3) { facing = 2; } else if (facing == 4) { facing = 1; } break; case TCODK_RIGHT: if (facing == 1) { facing = 4; } else if (facing == 2) { facing = 3; } else if (facing == 3) { facing = 1; } else if (facing == 4) { facing = 2; } break; default: break; } if ( computeFov ) { map->computeFov(); computeFov=false; } } void Engine::render_3d() { OffScreenConsole->clear(); if (facing == 1) { // back row render_tile(player->x - 2, player->y - 2, 0); render_tile(player->x + 2, player->y - 2, 1); render_tile(player->x - 1, player->y - 2, 2); render_tile(player->x + 1, player->y - 2, 3); render_tile(player->x, player->y - 2, 4); // middle row render_tile(player->x - 2, player->y - 1, 5); render_tile(player->x + 2, player->y - 1 ,6); render_tile(player->x - 1, player->y - 1, 7); render_tile(player->x + 1, player->y - 1, 8); render_tile(player->x, player->y - 1, 9); // front row render_tile(player->x - 1, player->y, 10); render_tile(player->x + 1, player->y, 11); render_tile(player->x, player->y, 12); } else if (facing == 2) { // back row render_tile(player->x + 2, player->y + 2, 0); render_tile(player->x - 2, player->y + 2, 1); render_tile(player->x + 1, player->y + 2, 2); render_tile(player->x - 1, player->y + 2, 3); render_tile(player->x, player->y + 2, 4); // middle row render_tile(player->x + 2, player->y + 1, 5); render_tile(player->x - 2, player->y + 1, 6); render_tile(player->x + 1, player->y + 1, 7); render_tile(player->x - 1, player->y + 1, 8); render_tile(player->x, player->y + 1, 9); // front row render_tile(player->x + 1, player->y, 10); render_tile(player->x - 1, player->y, 11); render_tile(player->x, player->y, 12); } else if (facing == 3) { // back row render_tile(player->x - 2, player->y + 2, 0); render_tile(player->x - 2, player->y - 2, 1); render_tile(player->x - 2, player->y + 1, 2); render_tile(player->x - 2, player->y - 1, 3); render_tile(player->x - 2, player->y, 4); // middle row render_tile(player->x - 1, player->y + 2, 5); render_tile(player->x - 1, player->y - 2, 6); render_tile(player->x - 1, player->y + 1, 7); render_tile(player->x - 1, player->y - 1, 8); render_tile(player->x - 1, player->y, 9); // front row render_tile(player->x, player->y + 1, 10); render_tile(player->x, player->y - 1, 11); render_tile(player->x, player->y, 12); } else if (facing == 4) { // back row render_tile(player->x + 2, player->y - 2, 0); render_tile(player->x + 2, player->y + 2, 1); render_tile(player->x + 2, player->y - 1, 2); render_tile(player->x + 2, player->y + 1, 3); render_tile(player->x + 2, player->y, 4); // middle row render_tile(player->x + 1, player->y - 2, 5); render_tile(player->x + 1, player->y + 2, 6); render_tile(player->x + 1, player->y - 1, 7); render_tile(player->x + 1, player->y + 1, 8); render_tile(player->x + 1, player->y, 9); // front row render_tile(player->x, player->y - 1, 10); render_tile(player->x, player->y + 1, 11); render_tile(player->x, player->y, 12); } TCODImage *image_to_render = new TCODImage(OffScreenConsole); image_to_render->scale(160, 120); image_to_render->blit2x(TCODConsole::root, 1, 1); } void Engine::render_tile(int pos_x, int pos_y, int position) { // If inbounds if ((pos_x > 0) && (pos_y > 0) && (pos_x <= 80) && (pos_y <= 45)) { // If we have a wall if (map->isWall(pos_x, pos_y)) { // Use the offsets to copy part of the background image TCODConsole::blit(DungeonWalls, src_x[position], src_y[position], width[position], height[position], OffScreenConsole, dest_x[position], dest_y[position]); } else { TCODConsole::blit(DungeonFloor, src_x[position], src_y[position], width[position], height[position], OffScreenConsole, dest_x[position], dest_y[position]); TCODConsole::blit(DungeonCeiling, src_x[position], src_y[position], width[position], height[position], OffScreenConsole, dest_x[position], dest_y[position]); } } else { TCODConsole::blit(DungeonWalls, src_x[position], src_y[position], width[position], height[position], OffScreenConsole, dest_x[position], dest_y[position]); } }
27.830144
120
0.601736
[ "render" ]
2d164219c2a5b74131f7b1c7b4af2d1a619e6acb
18,271
cpp
C++
homer.cpp
gleybersonandrade/JCTaxi
db28f0801d423e89f1465ff4b15852dbdbae4364
[ "MIT" ]
null
null
null
homer.cpp
gleybersonandrade/JCTaxi
db28f0801d423e89f1465ff4b15852dbdbae4364
[ "MIT" ]
null
null
null
homer.cpp
gleybersonandrade/JCTaxi
db28f0801d423e89f1465ff4b15852dbdbae4364
[ "MIT" ]
null
null
null
/* CHARACTER */ static GLuint Torso= 1; static GLuint UppLeftArm= 2; static GLuint LwrLeftArm= 3; static GLuint UppRightArm= 4; static GLuint LwrRightArm= 5; static GLuint UppRightLeg= 6; static GLuint LwrRightLeg= 7; static GLuint UppLeftLeg= 6; static GLuint LwrLeftLeg= 7; static GLuint HomerHead= 8; GLint toggle = 0; /* Variables */ static GLfloat spin = 0.0; static GLfloat ZRotate = 0.0; static GLfloat XRotate = 0.0; static GLfloat HeadTurn = 0.0; static GLfloat HeadNod = 0.0; static GLfloat BodyTurn = 0.0; static GLfloat MoveX= 0.0; static GLfloat MoveY= 0.0; static GLfloat MoveZ= 0.0; static GLfloat UpperRightLegAngleX= 0.0; static GLfloat LowerRightLegAngleX= 0.0; static GLfloat UpperLeftLegAngleX= 0.0; static GLfloat LowerLeftLegAngleX= 0.0; static GLfloat UpperLeftLegAngleZ= 0.0; static GLfloat UpperRightLegAngleZ= 0.0; static GLfloat UpperRightArmAngleX= 0.0; static GLfloat LowerRightArmAngleY= 0.0; static GLfloat LowerRightArmAngleX= 0.0; static GLfloat UpperLeftArmAngleX= 0.0; static GLfloat LowerLeftArmAngleX= 0.0; static GLfloat UpperRightArmAngleZ= 0.0; static GLfloat UpperLeftArmAngleZ= 0.0; /* --OBJECT AND MATERIAL PROPERTIES----------------------------------*/ GLfloat no_mat[] = {0.0f, 0.0f, 0.0f, 1.0f}; int leftLegFlag = 0; int rightLegFlag = 0; int phase = 1; float animationPeriod = 1; void myDrawTorso(void) { GLUquadricObj *qobj; GLfloat diffW[] = {1.0, 0.6, 0.0, 0.0}; qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); glRotated(-90.0,1.0,0.0,0.0); glScaled(1.2, 1.0, 1.0); gluSphere(qobj,2.5,30,30); glTranslated(0.0,0.0,-3.9); gluCylinder(qobj,2.5,2.5,3.9,30,30); glTranslated(0.0,0.0,3.5); gluCylinder(qobj,2.4,0.5,3.0,30,30); glTranslated(0.0,0.0,-4.0); gluCylinder(qobj,2.6,2.5,0.6,30,30); } void myDrawHomerHead(void) { GLUquadricObj *qobj; GLfloat diffB[] = {1.0, 1.0, 1.0, 1.0}; /*cor cabelo */ GLfloat diffW[] = {0.6, 0.0, 0.0, 0.0}; /*Cor dos olhos */ GLfloat diffBR[] = {0.5, 0.3, 0.04, 0.0}; /* cor boca */ qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); glRotated(-90.0,1.0,0.0,0.0); glPushMatrix(); glPushMatrix(); glTranslated(0.0,0.0,-2.5); glScaled(1.0, 1.15, 1.5); gluSphere(qobj,1.30,30,30); glTranslated(0.0,0.0,-3.4); gluCylinder(qobj,1.30,1.30,3.5,30,30); glPopMatrix(); glColor3f(0.088,0.224,0.909803922); glPushMatrix(); glTranslated(0.0,0.0,-1.3); glScaled(1.0, 1.0, 1.0); gluSphere(qobj,2.30,30,30); glTranslated(0.0,0.0,-2.5); gluCylinder(qobj,2.30,2.30,2.4,30,30); glPopMatrix(); glColor3f(1,1,1); /*LEFT EYE*/ glPushMatrix(); glTranslated(0.595,-1.0,-2.3); gluSphere(qobj,0.6,30,30); glPopMatrix(); /*RIGHT EYE*/ glPushMatrix(); glTranslated(-0.595,-1.0,-2.3); gluSphere(qobj,0.6,30,30); glPopMatrix(); /*LEFT PUPIL*/ glPushMatrix(); glTranslated(0.595,-1.50,-2.2); gluSphere(qobj,0.175,30,30); glPopMatrix(); /*RIGHT PUPIL*/ glPushMatrix(); glTranslated(-0.595,-1.50,-2.2); gluSphere(qobj,0.175,30,30); glPopMatrix(); /*MOUTH PART*/ glPushMatrix(); glTranslated(0.0,-1.0,-3.3); glutSolidCone(1.2,1.2,22,22); glRotated(180.0,1.0,0.0,0.0); glutSolidCone(1.2,1.2,22,22); glPopMatrix(); /*THE NOSE*/ glTranslated(0.0,0.0,-2.5); glRotated(90.0,1.0,0.0,0.0); gluCylinder(qobj,0.25,0.25,2.2,30,30); glTranslated(0.0,0.0,2.2); gluSphere(qobj,0.25,30,30); /*THE EARS*/ glPushMatrix(); glTranslated(-1.3,0.0,-2.4); gluSphere(qobj,0.25,30,30); glPopMatrix(); glPushMatrix(); glTranslated(1.3,0.0,-2.4); gluSphere(qobj,0.25,30,30); glPopMatrix(); /*THE HAIR*/ glPushMatrix(); glRotated(70.0,1.0,0.0,0.0); glRotated(20.0,0.0,0.0,1.0); glTranslated(0.6,-1.8,0.0); glTranslated(0.0,0.0,-1.9); gluCylinder(qobj,0.06,0.06,0.8,30,30); gluSphere(qobj,0.06,30,30); glTranslated(0.0,0.0,0); glRotated(-321.0,1.0,0.0,0.0); gluCylinder(qobj,0.06,0.06,0.8,30,30); glPopMatrix(); glPushMatrix(); glRotated(70.0,1.0,0.0,0.0); glRotated(20.0,0.0,0.0,1.0); glRotated(8.0,0.0,1.0,0.0); glTranslated(0.8,-2.3,-0.1); glTranslated(0.0,0.0,-1.9); gluCylinder(qobj,0.06,0.06,0.8,30,30); gluSphere(qobj,0.06,30,30); glRotated(-321.0,1.0,0.0,0.0); glRotated(-18.0,0.0,1.0,0.0); gluCylinder(qobj,0.06,0.06,0.8,30,30); glPopMatrix(); /*THE RIGHT SIDE*/ glPushMatrix(); glRotated(70.0,1.0,0.0,0.0); glRotated(20.0,0.0,0.0,1.0); glTranslated(-2.0,-1.8,0.0); glTranslated(0.0,0.0,-1.9); gluCylinder(qobj,0.06,0.06,0.8,30,30); gluSphere(qobj,0.06,30,30); glTranslated(0.0,0.0,0); glRotated(-321.0,1.0,0.0,0.0); gluCylinder(qobj,0.06,0.06,0.8,30,30); glPopMatrix(); glPushMatrix(); glRotated(70.0,1.0,0.0,0.0); glRotated(20.0,0.0,0.0,1.0); glRotated(4.0,0.0,1.0,0.0); glTranslated(-1.7,-1.3,0.0); glTranslated(0.0,0.0,-1.9); gluCylinder(qobj,0.06,0.06,0.8,30,30); gluSphere(qobj,0.06,30,30); glRotated(-321.0,1.0,0.0,0.0); glRotated(-18.0,0.0,1.0,0.0); gluCylinder(qobj,0.06,0.06,0.8,30,30); glPopMatrix(); /*TOP OF HIS HEAD... 3 HAIRS :-P */ glPushMatrix(); glTranslated(-0.5,2.0,-2.0); glRotated(75.0,0.0,1.0,0.0); gluCylinder(qobj,0.04,0.04,0.8,30,30); gluSphere(qobj,0.04,30,30); glRotated(110.0,1.0,0.0,0.0); gluCylinder(qobj,0.04,0.04,0.4,30,30); gluSphere(qobj,0.04,30,30); glPopMatrix(); glPushMatrix(); glTranslated(0.655,1.95,-1.755); glRotated(90.0,0.0,1.0,0.0); glPushMatrix(); glRotated(45.0,1.0,0.0,0.0); gluCylinder(qobj,0.04,0.04,0.2,30,30); gluSphere(qobj,0.04,30,30); glPopMatrix(); glRotated(190.0,1.0,0.0,0.0); gluCylinder(qobj,0.04,0.04,0.4,30,30); gluSphere(qobj,0.04,30,30); glPopMatrix(); glPushMatrix(); glTranslated(-0.5,1.905,-2.35); glRotated(95.0,0.0,1.0,0.0); gluCylinder(qobj,0.04,0.04,1.3,30,30); gluSphere(qobj,0.04,30,30); glRotated(129.0,1.0,0.0,0.0); gluCylinder(qobj,0.04,0.04,0.4,30,30); gluSphere(qobj,0.04,30,30); glPopMatrix(); glPushMatrix(); glTranslated(-0.5,1.905,-2.05); glRotated(95.0,0.0,1.0,0.0); gluCylinder(qobj,0.04,0.04,1.3,30,30); gluSphere(qobj,0.04,30,30); glRotated(129.0,1.0,0.0,0.0); gluCylinder(qobj,0.04,0.04,0.4,30,30); gluSphere(qobj,0.04,30,30); glPopMatrix(); glPopMatrix(); } void myDrawUppLeftArm(void) { GLUquadricObj *qobj; /* Set the material properties. */ /* Set up and draw the quadric. */ qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); /* rotate by -90 degrees about the x-axis so the quadric is aligned along the y-axis */ glRotated(90.0,1.0,0.0,0.0); /* Draw the Shoulder .. part of shirt*/ gluSphere(qobj,0.8,30,30); /* Draw Sleeve of Shirt Upper Arm - should be white, as it is his shirt */ glRotated(30.0,0.0,1.0,0.0); gluCylinder(qobj,0.8,0.8,2.0,22,22); /*This draws part of his shirt sleeve..white */ glTranslated(0.0,0.0,1.55); gluCylinder(qobj,0.8,0.8,1.4,22,22); /*This sraws part of his upper arm.. should be Yellow.. */ glTranslated(0.0,0.0,1.4); gluCylinder(qobj,0.8,0.8,1.4,22,22); /*elbow Joint */ glTranslated(0.0,0.0,1.3); gluSphere(qobj,0.7,30,30); } void myDrawLwrLeftArm(void) { GLUquadricObj *qobj; /* Set the material properties. */ /* Set up and draw the quadric. */ qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); glColor3f(1,0.117647059,0.211764706); gluCylinder(qobj,0.8,0.8,1.9,22,22); glColor3f(1,1,1); glColor3f(1,1,1); /*Draw the hands... with 4 fingers*/ glPushMatrix(); glTranslated(0.0,0.0,2.2); glScaled(0.8, 2.0, 1.0); gluSphere(qobj,0.5,30,30); /*Finger 1*/ glPushMatrix(); glTranslated(0.0,0.0,0.0); gluCylinder(qobj,0.2,0.2,1.2,22,22); glTranslated(0.0,0.0,1.2); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 2*/ glPushMatrix(); glRotated(22.0,1.0,0.0,0.0); glTranslated(0.0,0.0,0.4); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 3*/ glPushMatrix(); glRotated(35.0,1.0,0.0,0.0); glTranslated(0.0,-0.2,0.0); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 4*/ glPushMatrix(); glRotated(-30.0,1.1,0.0,0.0); glTranslated(0.0,0.0,0.1); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); glPopMatrix(); } void myDrawUppRightArm(void) { GLUquadricObj *qobj; /* Set the material properties. */ GLfloat diffW[] = {1.0, 1.0, 1.0, 1.0}; /*cor da manga camisa */ /* Set up and draw the quadric. */ qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); /* rotate by -90 degrees about the x-axis so the quadric is aligned along the y-axis */ glRotated(90.0,1.0,0.0,0.0); /* Draw the Shoulder .. part of shirt*/ gluSphere(qobj,0.8,30,30); /* Draw Sleeve of Shirt Upper Arm - should be white, as it is his shirt*/ glRotated(-30.0,0.0,1.0,0.0); /* Draw Sleeve of Shirt Upper Arm - should be white, as it is his shirt*/ gluCylinder(qobj,0.8,0.8,2.0,22,22); /*This draws part of his shirt sleeve..white */ glTranslated(0.0,0.0,1.55); gluCylinder(qobj,0.8,0.8,1.4,22,22); /*This sraws part of his upper arm.. should be Yellow.. */ glTranslated(0.0,0.0,1.4); gluCylinder(qobj,0.8,0.8,1.4,22,22); /*elbow Joint */ glTranslated(0.0,0.0,1.3); gluSphere(qobj,0.7,30,30); } void myDrawLwrRightArm(void) { GLUquadricObj *qobj; /* Set the material properties. */ glColor3f(1,0.117647059,0.211764706); qobj = gluNewQuadric(); /* Set up and draw the quadric. */ qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); gluCylinder(qobj,0.8,0.8,1.9,22,22); /*Draw the hands... with 4 fingers*/ glColor3f(1,1,1); glPushMatrix(); glTranslated(0.0,0.0,2.2); glScaled(1.0, 2.0, 1.0); gluSphere(qobj,0.5,30,30); /*Finger 1*/ glPushMatrix(); glTranslated(0.0,0.0,0.0); gluCylinder(qobj,0.2,0.2,1.2,22,22); glTranslated(0.0,0.0,1.2); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 2*/ glPushMatrix(); glRotated(22.0,1.0,0.0,0.0); glTranslated(0.0,0.0,0.4); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 3*/ glPushMatrix(); glRotated(35.0,1.0,0.0,0.0); glTranslated(0.0,-0.2,0.0); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); /*Finger 4*/ glPushMatrix(); glRotated(-30.0,1.1,0.0,0.0); glTranslated(0.0,0.0,0.1); gluCylinder(qobj,0.2,0.2,0.8,22,22); glTranslated(0.0,0.0,0.8); gluSphere(qobj,0.2,30,30); glPopMatrix(); glPopMatrix(); } void myDrawUppRightLeg(void) { GLUquadricObj *qobj; qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); gluSphere(qobj,1.45,30,30); glRotated(-90.0,1.0,0.0,0.0); glTranslated(0.0,0.0,-3.3); gluCylinder(qobj,1.30,1.45,3.5,30,30); } void myDrawLwrRightLeg(void) { GLUquadricObj *qobj; qobj = gluNewQuadric(); gluSphere(qobj,1.30,30,30); glTranslated(0.0,0.0,-3.2); gluCylinder(qobj,1.00,1.30,3.2,30,30); gluSphere(qobj,1.0,30,30); glTranslated(0.0,-0.5,-0.5); glRotated(90.0,1.0,0.0,0.0); glScaled(2.6, 1, 4.5); gluSphere(qobj,0.45,30,30); } void myDrawUppLeftLeg(void) { GLUquadricObj *qobj; glColor3f(0,0,0.090196078); qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); gluSphere(qobj,1.45,30,30); glRotated(-90.0,1.0,0.0,0.0); glTranslated(0.0,0.0,-3.3); gluCylinder(qobj,1.30,1.45,3.5,30,30); glColor3f(1,1,1); } void myDrawLwrLeftLeg(void) { GLUquadricObj *qobj; glColor3f(0,0,0.090196078); qobj = gluNewQuadric(); gluQuadricDrawStyle(qobj,GLU_FILL); gluQuadricNormals(qobj,GLU_SMOOTH); gluSphere(qobj,1.30,30,30); glTranslated(0.0,0.0,-3.2); gluCylinder(qobj,1.00,1.30,3.2,30,30); glColor3f(1,1,1); gluSphere(qobj,1.0,30,30); glTranslated(0.0,-0.5,-0.5); glRotated(90.0,1.0,0.0,0.0); glScaled(2.6, 1, 4.5); gluSphere(qobj,0.45,30,30); } void setLighting(void) { GLfloat ambient[] = {1.0, 1.0, 1.0, 1.0}; GLfloat diffuse0[] = {1.0, 1.0, 1.0, 1.0}; GLfloat position0[] = {0.0, 50.0, 60.0, 0.0}; /* Behind and up. */ GLfloat lmodel_ambient[] = {0.0, 0.0, 0.0, 1.0}; /* Set the background ambient lighting. */ GLfloat lmodel_twoside[] = {GL_TRUE}; /* Compute lighting for both inside and outside faces. */ glLightModelfv(GL_LIGHT_MODEL_AMBIENT, lmodel_ambient); glLightModelfv(GL_LIGHT_MODEL_TWO_SIDE, lmodel_twoside); /* Set the light properties */ glLightfv(GL_LIGHT0, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuse0); glLightfv(GL_LIGHT0, GL_POSITION, position0); glEnable(GL_LIGHTING); glEnable(GL_LIGHT0); } void initHomer(void) { glClearColor(0.0,0.0,0.0,0.0); glFrontFace(GL_CCW); /* Front faces defined using a clockwise rotation. */ glDepthFunc(GL_LEQUAL); /* Plot pixel */ glEnable(GL_DEPTH_TEST); /* Use a depth (z) buffer to draw only visible objects. */ glEnable(GL_CULL_FACE); /* Use back face culling to improve speed. */ glCullFace(GL_BACK); /* Cull only back faces. */ /* Which shade model to use: GL_FLAT / GL_SMOOTH. */ glShadeModel(GL_SMOOTH); glPushMatrix(); //setLighting(); /* Generate the display lists to store the robot: */ glNewList(Torso,GL_COMPILE); glColor3f(1,0.117647059,0.211764706); myDrawTorso(); glColor3f(1,1,1); glEndList(); glNewList(UppLeftArm,GL_COMPILE); glColor3f(1,0.117647059,0.211764706); myDrawUppLeftArm(); glColor3f(1,1,1); glEndList(); glNewList(LwrLeftArm,GL_COMPILE); myDrawLwrLeftArm(); glEndList(); glNewList(UppRightArm,GL_COMPILE); glColor3f(1,0.117647059,0.211764706); myDrawUppRightArm(); glColor3f(1,1,0.211764706); glEndList(); glNewList(LwrRightArm,GL_COMPILE); myDrawLwrRightArm(); glEndList(); glNewList(UppRightLeg,GL_COMPILE); myDrawUppRightLeg(); glEndList(); glNewList(LwrRightLeg,GL_COMPILE); myDrawLwrRightLeg(); glEndList(); glNewList(UppLeftLeg,GL_COMPILE); myDrawUppLeftLeg(); glEndList(); glNewList(LwrLeftLeg,GL_COMPILE); myDrawLwrLeftLeg(); glEndList(); glNewList(HomerHead,GL_COMPILE); myDrawHomerHead(); glEndList(); glPopMatrix(); } void displayHomer(void) { glPushMatrix(); glTranslated(0.0,0.0,0.0); glRotated(spin, 0,1,0); /* The Following is Scenery Object hierachy -- Will contain the walls, Lamps, TV etc */ glPushMatrix(); glTranslated (MoveX,MoveY,MoveZ); glRotated(XRotate,1,0,0); glRotated(ZRotate,0,0,1); glRotated(BodyTurn,0,1,0); glPushMatrix(); /*Torso*/ glTranslated(0.0,0.0,0.0); glCallList(Torso); glPopMatrix(); /*HOMER HEAD*/ glPushMatrix(); glTranslated(0.0,6.5,0.0); glRotatef(HeadNod, 1, 0, 0); glRotatef(HeadTurn, 0, 1, 0); glCallList(HomerHead); glPopMatrix(); /*RIGHT ARM*/ glPushMatrix(); glTranslated(-2.0,1.5,0.0); glRotatef(UpperRightArmAngleX, 1, 0, 0); glRotatef(UpperRightArmAngleZ, 0, 0, 1); glCallList(UppRightArm); glPushMatrix(); glRotatef(LowerRightArmAngleX, 1, 0, 0); glRotatef(LowerRightArmAngleY, 0, 1, 0); glCallList(LwrRightArm); glPopMatrix(); glPopMatrix(); /*LEFT ARM*/ glPushMatrix(); glTranslated(2.0,1.5,0.0); glRotatef(UpperLeftArmAngleX, 1, 0, 0); glRotatef(UpperLeftArmAngleZ, 0, 0, 1); glCallList(UppLeftArm); glPushMatrix(); glRotatef(LowerLeftArmAngleX, 1, 0, 0); glCallList(LwrLeftArm); glPopMatrix(); glPopMatrix(); glPushMatrix(); glPopMatrix(); /*RIGHT LEG*/ glPushMatrix(); glTranslated(-1.3,-3.85,0.0); glRotatef(UpperRightLegAngleX, 1, 0, 0); glRotatef(UpperRightLegAngleZ, 0, 0, 1); glCallList(UppRightLeg); glPushMatrix(); glRotatef(LowerRightLegAngleX, 1, 0, 0); glCallList(LwrRightLeg); glPopMatrix(); glPopMatrix(); /*LEFT LEG*/ glPushMatrix(); glTranslated(1.3,-3.85,0.0); glRotatef(UpperLeftLegAngleX , 1, 0, 0); glRotatef(UpperLeftLegAngleZ, 0, 0, 1); glCallList(UppLeftLeg); glPushMatrix(); glRotatef(LowerLeftLegAngleX , 1, 0, 0); glCallList(LwrLeftLeg); glPopMatrix(); glPopMatrix(); glPopMatrix(); glPopMatrix(); } void animateLeftLeg(void) { if (LowerLeftLegAngleX > 85.0) { leftLegFlag = 1; } else if (LowerLeftLegAngleX < 0) { leftLegFlag = 0; phase = 2; } if (leftLegFlag == 0) { HeadTurn+=2.0; LowerLeftLegAngleX += 10; LowerRightArmAngleX -= 20; } else { HeadTurn-=2.0; LowerLeftLegAngleX -= 10; LowerRightArmAngleX += 20; } glutPostRedisplay(); } void animateRightLeg(void) { if (LowerRightLegAngleX > 85.0) { rightLegFlag = 1; } else if (LowerRightLegAngleX < 0) { rightLegFlag = 0; phase = 1; } if (rightLegFlag == 0) { HeadTurn+=2.0; LowerRightLegAngleX += 10; LowerLeftArmAngleX -= 20; } else { HeadTurn-=2.0; LowerRightLegAngleX -= 10; LowerLeftArmAngleX += 20; } glutPostRedisplay(); } void animate(int value) { if (phase == 1) { animateLeftLeg(); } else { animateRightLeg(); } glutTimerFunc(animationPeriod, animate, 1); glutPostRedisplay(); } void myReshape(int width, int height) { glViewport(0, 0, (GLsizei) width, (GLsizei) height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum (-1.0, 1.0, -1.0, 1.0, 1.0, 200.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } /*int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800,800); glutInitWindowPosition(100,150); glutCreateWindow("Homer Simpson in 3D"); glutDisplayFunc(displayHomer); glutReshapeFunc(myReshape); glutTimerFunc(5, animate, 1); myInit(); glutMainLoop(); return 0; }*/
25.13205
97
0.652291
[ "object", "model", "3d" ]
2d19f14274a86ef678101a71836a98a2f54bc5d5
3,023
cpp
C++
src/tasker.cpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
src/tasker.cpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
src/tasker.cpp
pirobtumen/Remember
5d218d9c0e353ff1df7695486c794288f1ba0a96
[ "MIT" ]
null
null
null
// ----------------------------------------------------------------------------- // // MIT License // // Copyright (c) 2016 Alberto Sola // // 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 "tasker.hpp" // ----------------------------------------------------------------------------- Tasker::Tasker(){ task_db.set_name("task.txt"); task_db.read(); } // ----------------------------------------------------------------------------- void Tasker::add_task(Task & task){ task_db.add_task(task); } // ----------------------------------------------------------------------------- const Task & Tasker::get_task(unsigned int id) const{ return task_db.get_task(id); } // ----------------------------------------------------------------------------- void Tasker::get_task_list(std::vector<Task> & tasks, std::string tag){ if(tag.empty()) task_db.get_task_list(tasks); else task_db.get_task_list(tasks,tag); } // ----------------------------------------------------------------------------- void Tasker::delete_task(unsigned int id){ // TODO: return value task_db.delete_task(id); } // ----------------------------------------------------------------------------- void Tasker::update_task(const Task & task){ task_db.update_task(task); } // ----------------------------------------------------------------------------- void Tasker::save() const{ task_db.save(); } // ----------------------------------------------------------------------------- bool Tasker::finish_task(unsigned int id){ return task_db.finish_task(id); } // ----------------------------------------------------------------------------- bool Tasker::finish_task(unsigned int id, bool status){ return task_db.finish_task(id,status); } // -----------------------------------------------------------------------------
31.821053
81
0.47701
[ "vector" ]
2d1a8ee7804875df92f90850588e2d7668faa53e
1,957
cpp
C++
src/water/anim/AnimatorGerstner.cpp
WannaBeFaster/water
bcda6c5cfd17ad3fef7b0fdce03353827c6e7ee4
[ "MIT" ]
5
2019-09-18T18:59:30.000Z
2019-09-23T14:25:15.000Z
src/water/anim/AnimatorGerstner.cpp
WannaBeFaster/water
bcda6c5cfd17ad3fef7b0fdce03353827c6e7ee4
[ "MIT" ]
null
null
null
src/water/anim/AnimatorGerstner.cpp
WannaBeFaster/water
bcda6c5cfd17ad3fef7b0fdce03353827c6e7ee4
[ "MIT" ]
null
null
null
#include "../../headers.h" #include "../scene/Patch.h" #include "AnimatorGerstner.h" //------------------------------------------------------------------------------------------------- void AnimatorGerstner::addWave(const WaveSettings& wave) { waves_.push_back(wave); } //------------------------------------------------------------------------------------------------- void AnimatorGerstner::init() { // copy initial vertex positions auto& vertices = patch_->getVertices(); x0_.reserve(vertices.size()); x0_.clear(); for(auto& v: vertices) x0_.push_back(v.pos); // prepare wave settings for (auto& wave: waves_) { // find k vector length from the wave length glm::vec2 k = glm::normalize(wave.k); k *= 2*glm::pi<float>()/wave.L; wave.k = k; // unit wavevector wave.k1 = glm::normalize(k); } } //------------------------------------------------------------------------------------------------- void AnimatorGerstner::update(double t) { // for all waves // X = X0 − (K/k)A*sin(K*X0 − wt) // y = A*cos(K*X0 − wt) // iterate both vertex arrays: inital and target auto it = patch_->getVertices().begin(); for(auto& x0: x0_) { double dx = 0.0f; double dy = 0.0f; double dz = 0.0f; for(auto& wave: waves_) { const glm::vec2& k = wave.k; const glm::vec2& k1 = wave.k1; // w*w = gk (for deep ocean) double w = sqrt(9.81*glm::length(k)); double A = wave.A; double arg = k.x*x0.x/2 + k.y*x0.z/2 - w*t; // double val = A*sin(arg); dx += k1.x*val; dz += k1.y*val; // wave height dy += A*cos(arg); } it->pos.x = x0.x - dx; it->pos.z = x0.z - dz; it->pos.y = x0.y + dy; it++; } generateNormals(); }
24.4625
99
0.422075
[ "vector" ]
2d23bc6d78e023653a27e8164492c3bf91ea7d21
1,755
cpp
C++
lib/projectfs/projectstructure.cpp
NablaVM/libnabla
01fcc87c7b487be13d63bffeec2e4355cbfe69a2
[ "MIT" ]
null
null
null
lib/projectfs/projectstructure.cpp
NablaVM/libnabla
01fcc87c7b487be13d63bffeec2e4355cbfe69a2
[ "MIT" ]
null
null
null
lib/projectfs/projectstructure.cpp
NablaVM/libnabla
01fcc87c7b487be13d63bffeec2e4355cbfe69a2
[ "MIT" ]
null
null
null
#include "projectstructure.hpp" namespace NABLA { // --------------------------------------------------------------- // // --------------------------------------------------------------- ProjectStructure::ProjectStructure() { clear(); } // --------------------------------------------------------------- // // --------------------------------------------------------------- ProjectStructure::~ProjectStructure() { clear(); } // --------------------------------------------------------------- // // --------------------------------------------------------------- std::string ProjectStructure::get_author() const { return author; } // --------------------------------------------------------------- // // --------------------------------------------------------------- std::string ProjectStructure::get_description() const { return description; } // --------------------------------------------------------------- // // --------------------------------------------------------------- ProjectType ProjectStructure::get_projectType() const { return projectType; } // --------------------------------------------------------------- // // --------------------------------------------------------------- std::string ProjectStructure::get_entryFile() const { return entryFile; } // --------------------------------------------------------------- // // --------------------------------------------------------------- std::vector<std::string> ProjectStructure::get_module_list() const { return module_list; } }
26.19403
71
0.239886
[ "vector" ]
2d2a694ab3f40b23223331ff2b7bb5345b72c022
2,759
cpp
C++
src/applib/AppCfgData.cpp
jxmot/esp8266-dht-udp
ea35ccf622b98c50b648a0ad5513dd6c99b0b41f
[ "MIT" ]
1
2018-06-15T08:56:51.000Z
2018-06-15T08:56:51.000Z
src/applib/AppCfgData.cpp
jxmot/esp8266-dht-udp
ea35ccf622b98c50b648a0ad5513dd6c99b0b41f
[ "MIT" ]
15
2018-01-28T03:05:08.000Z
2020-11-21T16:00:41.000Z
src/applib/AppCfgData.cpp
jxmot/esp8266-dht-udp
ea35ccf622b98c50b648a0ad5513dd6c99b0b41f
[ "MIT" ]
null
null
null
/* ************************************************************************ */ /* AppCfgData.cpp - Intended to provide application configuration data, this could be things such as - 1) Application name 2) Feature control flags. A "debug mute" is implemented here. 3) Text message (be careful to not use too much memory!) content. (c) 2017 Jim Motyl - https://github.com/jxmot/esp8266-dht-udp */ #include "AppCfgData.h" #include <ArduinoJson.h> ////////////////////////////////////////////////////////////////////////////// /* Constructor */ AppCfgData::AppCfgData(const char *cfgfile): ConfigData(cfgfile) { debugmute = false; appname = ""; } ////////////////////////////////////////////////////////////////////////////// /* Parse the JSON data that is specific to this configuration object. */ void AppCfgData::parseJSON(std::unique_ptr<char[]>& buf) { // This will always print, we can't use the debug mute flag // because it hasn't been read & parsed yet. Serial.println(); Serial.println("AppCfgData parsing JSON - "); Serial.println(buf.get()); // For getting the size correct, use the following to calculate // how much is requried for a given bit of JSON data - // // https://arduinojson.org/assistant/ const size_t bufferSize = JSON_OBJECT_SIZE(6) + 145; StaticJsonBuffer<bufferSize> jsonBuffer; JsonObject& json = jsonBuffer.parseObject(buf.get()); /* This is one of the places where you would customize this class to be used with your application specific configuration data. Another place is in AppCfgData.h */ debugmute = json["debugmute"]; appname = String((const char *)json["appname"]); wificonfig = String((const char *)json["wificonfig"]); clientconfig = String((const char *)json["clientconfig"]); mcastconfig = String((const char *)json["mcastconfig"]); sensorconfig = String((const char *)json["sensorconfig"]); } ////////////////////////////////////////////////////////////////////////////// /* This is one of the places where you would customize this class to be used with your application specific configuration data. Another place is in AppCfgData.h */ String AppCfgData::getAppName() { return appname; } bool AppCfgData::getDebugMute() { return debugmute; } bool AppCfgData::setDebugMute(bool _debugmute) { debugmute = _debugmute; return debugmute; } String AppCfgData::getWifiConfig() { return wificonfig; } String AppCfgData::getClientConfig() { return clientconfig; } String AppCfgData::getMcastConfig() { return mcastconfig; } String AppCfgData::getSensorConfig() { return sensorconfig; }
26.27619
78
0.601305
[ "object" ]
2d2a7a293b724f4a8f9e39128a1cd5d27379530c
2,620
cpp
C++
api_test/main.cpp
jasoncoposky/scratch
9ae7f73bfdfc787a44be2e963ad6889a0aac6f25
[ "BSD-3-Clause" ]
null
null
null
api_test/main.cpp
jasoncoposky/scratch
9ae7f73bfdfc787a44be2e963ad6889a0aac6f25
[ "BSD-3-Clause" ]
2
2017-02-21T18:11:43.000Z
2020-10-05T20:10:02.000Z
api_test/main.cpp
jasoncoposky/scratch
9ae7f73bfdfc787a44be2e963ad6889a0aac6f25
[ "BSD-3-Clause" ]
1
2020-02-16T11:24:12.000Z
2020-02-16T11:24:12.000Z
// =-=-=-=-=-=-=- // STL Includes #include <iostream> #include <string> #include <functional> // =-=-=-=-=-=-=- // dlopen, etc #include <dlfcn.h> #include "operation_manager.hpp" #include "keyValPair.hpp" void init_rule_engine( const std::string& _rule_file, bp::object& _rule_context ) { try { Py_Initialize(); } catch( bp::error_already_set const& ) { PyErr_Print(); return; } namespace bfs = boost::filesystem; bfs::path workingDir = bfs::absolute("./").normalize(); char path[] = { "path" }; PyObject* sysPath = PySys_GetObject( path ); PyList_Insert( sysPath, 0, PyString_FromString(workingDir.string().c_str())); _rule_context = bp::import( _rule_file.c_str() ); } // init_rule_engine // =-=-=-=-=-=-=- // symbol to be read from loaded library std::string SYM_IN_EXEC( "i am a symbol in the main executable." ); // =-=-=-=-=-=-=- // main int main( int _argc, char* _argv[] ) { bp::object rule_context; init_rule_engine( "test_avro", rule_context ); // =-=-=-=-=-=-=- // load the dynamic library void* handle = dlopen( "./dynamic_loader_example.so", RTLD_LAZY ); if( !handle ) { std::cout << "failed to load ./dynamic_loader_example.so[" << dlerror() << "]" << std::endl; return -1; } // =-=-=-=-=-=-=- // fcn ptr typdef typedef void (*factory_t)( operation_manager& ); // =-=-=-=-=-=-=- // read a fcn ptr symbol from the library factory_t fac_ptr = reinterpret_cast< factory_t >( dlsym( handle, "factory_function" ) ); if( !fac_ptr ) { std::cout << "failed to load the library_function [" << dlerror() << "]" << std::endl; return -1; } { // scope block to release the references to the library functions // before the shared object is closed operation_manager op_mgr; fac_ptr( op_mgr ); keyValPair_t kvp; memset(&kvp,0,sizeof(kvp)); addKeyVal( &kvp, "KEY_1", "VAL_1" ); addKeyVal( &kvp, "KEY_2", "VAL_2" ); addKeyVal( &kvp, "KEY_3", "VAL_3" ); addKeyVal( &kvp, "KEY_4", "VAL_4" ); op_mgr.call<int,keyValPair_t,keyValPair_t,keyValPair_t>( rule_context, "serialize_function", std::move(kvp), std::move(kvp), std::move(kvp) ); op_mgr.call<double>( rule_context, "library_function3"); op_mgr.call( rule_context, "library_function"); } // =-=-=-=-=-=-=- // close the library dlclose( handle ); return 0; } // main
25.436893
100
0.560687
[ "object" ]
2d2b5abd37edbf7472155a21d884710b2e1e0145
4,563
cpp
C++
test/common/graph_test.cpp
ScottLiao920/noisepage
4ffb238529645efcaae99255f84d002f8d7fdf7d
[ "MIT" ]
971
2020-09-13T10:24:02.000Z
2022-03-31T07:02:51.000Z
test/common/graph_test.cpp
ScottLiao920/noisepage
4ffb238529645efcaae99255f84d002f8d7fdf7d
[ "MIT" ]
1,019
2018-07-20T23:11:10.000Z
2020-09-10T06:41:42.000Z
test/common/graph_test.cpp
ScottLiao920/noisepage
4ffb238529645efcaae99255f84d002f8d7fdf7d
[ "MIT" ]
318
2018-07-23T16:48:16.000Z
2020-09-07T09:46:31.000Z
#include "common/graph.h" #include "test_util/test_harness.h" namespace noisepage { using common::Graph; class GraphTest : public TerrierTest {}; // ---------------------------------------------------------------------------- // Test Utilities // ---------------------------------------------------------------------------- /** * Determine if two vertex sets are equal. * @param a Input vertex set * @param b Input vertex set * @return `true` if the vertex sets are equal, `false` otherwise */ static bool VertexSetsEqual(const std::vector<std::size_t> &a, const std::vector<std::size_t> &b) { std::vector<std::size_t> local_a{a.cbegin(), a.cend()}; std::vector<std::size_t> local_b{b.cbegin(), b.cend()}; std::sort(local_a.begin(), local_a.end()); std::sort(local_b.begin(), local_b.end()); return (local_a.size() == local_b.size()) && std::equal(local_a.cbegin(), local_a.cend(), local_a.cbegin()); } /** * Determine if two edge sets are equal. * @param a Input edge set * @param b Input edge set * @return `true` if the edge sets are equal, `false` otherwise */ static bool EdgeSetsEqual(const std::vector<std::pair<std::size_t, std::size_t>> &a, const std::vector<std::pair<std::size_t, std::size_t>> &b) { std::vector<std::pair<std::size_t, std::size_t>> local_a{a.cbegin(), a.cend()}; std::vector<std::pair<std::size_t, std::size_t>> local_b{b.cbegin(), b.cend()}; std::sort(local_a.begin(), local_a.end()); std::sort(local_b.begin(), local_b.end()); return (local_a.size() == local_b.size()) && std::equal(local_a.cbegin(), local_a.cend(), local_b.cbegin()); } // ---------------------------------------------------------------------------- // Graph Construction // ---------------------------------------------------------------------------- TEST_F(GraphTest, Construction0) { Graph g{}; std::vector<std::size_t> expected_vertex_set{}; std::vector<std::pair<std::size_t, std::size_t>> expected_edge_set{}; EXPECT_EQ(g.Order(), 0UL); EXPECT_EQ(g.Size(), 0UL); EXPECT_TRUE(VertexSetsEqual(g.VertexSet(), expected_vertex_set)); EXPECT_TRUE(EdgeSetsEqual(g.EdgeSet(), expected_edge_set)); } TEST_F(GraphTest, Construction1) { Graph g{}; g.AddEdge(0, 1); std::vector<std::size_t> expected_vertex_set{0, 1}; std::vector<std::pair<std::size_t, std::size_t>> expected_edge_set{{0, 1}}; EXPECT_EQ(g.Order(), 2UL); EXPECT_EQ(g.Size(), 1UL); EXPECT_TRUE(VertexSetsEqual(g.VertexSet(), expected_vertex_set)); EXPECT_TRUE(EdgeSetsEqual(g.EdgeSet(), expected_edge_set)); } TEST_F(GraphTest, Construction2) { Graph g{}; g.AddEdge(0, 1); g.AddEdge(1, 0); g.AddVertex(2); std::vector<std::size_t> expected_vertex_set{0, 1, 2}; std::vector<std::pair<std::size_t, std::size_t>> expected_edge_set{{0, 1}, {1, 0}}; EXPECT_EQ(g.Order(), 3UL); EXPECT_EQ(g.Size(), 2UL); EXPECT_TRUE(VertexSetsEqual(g.VertexSet(), expected_vertex_set)); EXPECT_TRUE(EdgeSetsEqual(g.EdgeSet(), expected_edge_set)); } TEST_F(GraphTest, Construction3) { const auto a = Graph::FromEdgeSet({{0, 1}, {1, 2}}); Graph b{}; b.AddEdge(0, 1); b.AddEdge(1, 2); EXPECT_EQ(a.Order(), 3UL); EXPECT_EQ(a.Size(), 2UL); EXPECT_EQ(b.Order(), 3UL); EXPECT_EQ(b.Size(), 2UL); EXPECT_EQ(a, b); } TEST_F(GraphTest, Construction4) { const auto g = Graph::FromEdgeSet({{0, 1}, {1, 2}}); std::vector<std::size_t> expected_vertex_set{0, 1, 2}; std::vector<std::pair<std::size_t, std::size_t>> expected_edge_set{{0, 1}, {1, 2}}; EXPECT_EQ(g.Order(), 3UL); EXPECT_EQ(g.Size(), 2UL); EXPECT_TRUE(VertexSetsEqual(g.VertexSet(), expected_vertex_set)); EXPECT_TRUE(EdgeSetsEqual(g.EdgeSet(), expected_edge_set)); } // ---------------------------------------------------------------------------- // Graph Eqaulity // ---------------------------------------------------------------------------- TEST_F(GraphTest, Equality0) { Graph a{}; Graph b{}; EXPECT_EQ(a, b); } TEST_F(GraphTest, Equality1) { Graph a{}; a.AddEdge(0, 1); a.AddEdge(1, 2); Graph b{}; b.AddEdge(0, 1); b.AddEdge(1, 2); EXPECT_EQ(a, b); } TEST_F(GraphTest, Equality2) { // Distinct edge sets Graph a{}; a.AddEdge(0, 1); a.AddEdge(1, 2); Graph b{}; b.AddEdge(0, 1); b.AddEdge(1, 2); b.AddEdge(0, 2); EXPECT_NE(a, b); } TEST_F(GraphTest, Equality3) { // Distinct vertex sets Graph a{}; a.AddEdge(0, 1); a.AddEdge(1, 2); Graph b{}; b.AddEdge(0, 1); b.AddEdge(1, 2); b.AddVertex(3); EXPECT_NE(a, b); } } // namespace noisepage
26.074286
110
0.586675
[ "vector" ]
2d353cff83d31fca80770dbd98b3910b3e05afb4
5,131
cpp
C++
ref/src/Chapter07/smart sweepers - v1.1/CMinesweeper.cpp
kugao222/geneticAlgorithmInLua
9bfd2a443f9492759027791a2b2b41b9467241b2
[ "MIT" ]
null
null
null
ref/src/Chapter07/smart sweepers - v1.1/CMinesweeper.cpp
kugao222/geneticAlgorithmInLua
9bfd2a443f9492759027791a2b2b41b9467241b2
[ "MIT" ]
null
null
null
ref/src/Chapter07/smart sweepers - v1.1/CMinesweeper.cpp
kugao222/geneticAlgorithmInLua
9bfd2a443f9492759027791a2b2b41b9467241b2
[ "MIT" ]
null
null
null
#include "CMinesweeper.h" //-----------------------------------constructor------------------------- // //----------------------------------------------------------------------- CMinesweeper::CMinesweeper(): m_dRotation(RandFloat()*CParams::dTwoPi), m_lTrack(0.16), m_rTrack(0.16), m_dFitness(CParams::dStartEnergy), m_dScale(CParams::iSweeperScale), m_iClosestMine(0) { //create a random start position m_vPosition = SVector2D((RandFloat() * CParams::WindowWidth), (RandFloat() * CParams::WindowHeight)); } //-------------------------------------------Reset()-------------------- // // Resets the sweepers position, energy level and rotation // //---------------------------------------------------------------------- void CMinesweeper::Reset() { //reset the sweepers positions m_vPosition = SVector2D((RandFloat() * CParams::WindowWidth), (RandFloat() * CParams::WindowHeight)); //and the energy level m_dFitness = CParams::dStartEnergy; //and the rotation m_dRotation = RandFloat()*CParams::dTwoPi; return; } //---------------------WorldTransform-------------------------------- // // sets up a translation matrix for the sweeper according to its // scale, rotation and position. Returns the transformed vertices. //------------------------------------------------------------------- void CMinesweeper::WorldTransform(vector<SPoint> &sweeper) { //create the world transformation matrix C2DMatrix matTransform; //scale matTransform.Scale(m_dScale, m_dScale); //rotate matTransform.Rotate(m_dRotation); //and translate matTransform.Translate(m_vPosition.x, m_vPosition.y); //now transform the ships vertices matTransform.TransformSPoints(sweeper); } //-------------------------------Update()-------------------------------- // // First we take sensor readings and feed these into the sweepers brain. // // The inputs are: // // a signed angle to the closest mine // // We receive two outputs from the brain.. lTrack & rTrack. // So given a force for each track we calculate the resultant rotation // and acceleration and apply to current velocity vector. // //----------------------------------------------------------------------- bool CMinesweeper::Update(vector<SVector2D> &mines) { //this will store all the inputs for the NN vector<double> inputs; //get vector to closest mine SVector2D vClosestMine = GetClosestMine(mines); //normalise it Vec2DNormalize(vClosestMine); //calculate dot product of the look at vector and Closest mine //vector. This will give us the angle we need turn to face //the closest mine double dot = Vec2DDot(m_vLookAt, vClosestMine); //calculate sign int sign = Vec2DSign(m_vLookAt, vClosestMine); inputs.push_back(dot*sign); //update the brain and get feedback vector<double> output = m_ItsBrain.Update(inputs); //make sure there were no errors in calculating the //output if (output.size() < CParams::iNumOutputs) { return false; } //assign the outputs to the sweepers left & right tracks m_lTrack = output[0]; m_rTrack = output[1]; //calculate steering forces double RotForce = m_lTrack - m_rTrack; //clamp rotation Clamp(RotForce, -CParams::dMaxTurnRate, CParams::dMaxTurnRate); m_dRotation += RotForce; m_dSpeed = (m_lTrack + m_rTrack); //update Look At m_vLookAt.x = -sin(m_dRotation); m_vLookAt.y = cos(m_dRotation); //update position m_vPosition += (m_vLookAt * m_dSpeed); //wrap around window limits if (m_vPosition.x > CParams::WindowWidth) m_vPosition.x = 0; if (m_vPosition.x < 0) m_vPosition.x = CParams::WindowWidth; if (m_vPosition.y > CParams::WindowHeight) m_vPosition.y = 0; if (m_vPosition.y < 0) m_vPosition.y = CParams::WindowHeight; return true; } //----------------------GetClosestObject()--------------------------------- // // returns the vector from the sweeper to the closest mine // //----------------------------------------------------------------------- SVector2D CMinesweeper::GetClosestMine(vector<SVector2D> &mines) { double closest_so_far = 99999; SVector2D vClosestObject(0, 0); //cycle through mines to find closest for (int i=0; i<mines.size(); i++) { double len_to_object = Vec2DLength(mines[i] - m_vPosition); if (len_to_object < closest_so_far) { closest_so_far = len_to_object; vClosestObject = m_vPosition - mines[i]; m_iClosestMine = i; } } return vClosestObject; } //----------------------------- CheckForMine ----------------------------- // // this function checks for collision with its closest mine (calculated // earlier and stored in m_iClosestMine) //----------------------------------------------------------------------- int CMinesweeper::CheckForMine(vector<SVector2D> &mines, double size) { SVector2D DistToObject = m_vPosition - mines[m_iClosestMine]; if (Vec2DLength(DistToObject) < (size + 5)) { return m_iClosestMine; } return -1; }
27.586022
75
0.581953
[ "vector", "transform" ]
2d38b0856cbaef90a1ca4b3aed8503e945fe8c33
7,585
inl
C++
Common/DyMath/Include/Math/Type/Inline/DVector4/Simd/DVector4TF32.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
4
2019-03-17T19:46:54.000Z
2019-12-09T20:11:01.000Z
Common/DyMath/Include/Math/Type/Inline/DVector4/Simd/DVector4TF32.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
11
2019-06-09T13:53:27.000Z
2020-02-09T09:47:28.000Z
Common/DyMath/Include/Math/Type/Inline/DVector4/Simd/DVector4TF32.inl
liliilli/DianYing
6e19f67e5d932e346a0ce63a648bed1a04ef618e
[ "MIT" ]
1
2019-06-04T15:20:18.000Z
2019-06-04T15:20:18.000Z
#pragma once /// /// MIT License /// Copyright (c) 2018-2019 Jongmin Yun /// /// 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. /// #ifdef MATH_ENABLE_SIMD #include <emmintrin.h> #include <smmintrin.h> namespace dy::math { template <> struct MATH_NODISCARD DVector4<TF32, void> final { using TValueType = TF32; union { __m128 __mVal; struct { TValueType X, Y, Z, W; }; }; DVector4() = default; DVector4(TValueType x, TValueType y, TValueType z, TValueType w) noexcept; DVector4(TValueType value) noexcept; DVector4(const DVector2<TValueType>& value, TValueType z = TValueType{}, TValueType w = TValueType{}) noexcept; DVector4(const DVector3<TValueType>& value, TValueType w = TValueType{}) noexcept; DVector4(__m128 __iSimd) noexcept; template <typename TAnotherType> explicit operator DVector4<TAnotherType>() const noexcept; /// @brief Narrow conversion. explicit operator DVector2<TValueType>() const noexcept; /// @brief Narrow conversion. explicit operator DVector3<TValueType>() const noexcept; /// @brief Get values with index. index must be 0, 1 or 2. TValueType& operator[](TIndex index); /// @brief Get values with index. index must be 0, 1 or 2. const TValueType& operator[](TIndex index) const; /// @brief Return data chunk pointer of DVector4. TValueType* Data() noexcept; /// @brief Return data chunk pointer of DVector2. const TValueType* Data() const noexcept; /// @brief Return squared length of this vector. TReal GetSquareLength() const noexcept; /// @brief Returns the length of this vector. TReal GetLength() const noexcept; /// @brief Return the length of this vector as homogeneous coordinate position. TReal GetHomogeneousLength() const noexcept; /// @brief Return new DVector4 instance of normalized input vector. DVector4<TReal> Normalize() const noexcept; /// @brief Check value has NaN. bool HasNaN() const noexcept; /// @brief Check value has Infinity. bool HasInfinity() const noexcept; /// @brief Check values are normal value, neither NaN nor Inf. bool HasOnlyNormal() const noexcept; DVector4& operator+=(const DVector4& value) noexcept; DVector4& operator-=(const DVector4& value) noexcept; DVector4& operator*=(TValueType value) noexcept; DVector4& operator*=(const DVector4& value) noexcept; DVector4& operator/=(TValueType value) noexcept; DVector4& operator/=(const DVector4& value) noexcept; }; template <typename TAnotherType> DVector4<TF32, void>::operator DVector4<TAnotherType>() const noexcept { using AnotherType = typename DVector4< TAnotherType, std::enable_if_t<kIsIntegerType<TAnotherType> || kIsRealType<TAnotherType>>>::TValueType; return DVector4<TAnotherType> { Cast<AnotherType>(this->X), Cast<AnotherType>(this->Y), Cast<AnotherType>(this->Z), Cast<AnotherType>(this->W) }; } inline DVector4<TF32, void> // NOLINT ::DVector4(TValueType x, TValueType y, TValueType z, TValueType w) noexcept : __mVal{_mm_set_ps(w, z, y, x)} // NOLINT { } inline DVector4<TF32, void> // NOLINT ::DVector4(TValueType value) noexcept : __mVal{_mm_set_ps1(value)} { } inline DVector4<TF32, void> // NOLINT ::DVector4(const DVector2<TValueType>& value, TValueType z, TValueType w) noexcept : __mVal{_mm_set_ps(w, z, value.Y, value.X)} { } inline DVector4<float, void> // NOLINT ::DVector4(const DVector3<TValueType>& value, TValueType w) noexcept : __mVal{_mm_set_ps(w, value.Z, value.Y, value.X)} { } inline DVector4<TF32, void> // NOLINT ::DVector4(__m128 __iSimd) noexcept : __mVal{__iSimd} { } inline DVector4<TF32>::TValueType& DVector4<TF32, void>::operator[](TIndex index) // NOLINT { switch (index) { case 0: return this->X; case 1: return this->Y; case 2: return this->Z; case 3: return this->W; default: M_ASSERT_OR_THROW(false, "index must be 0, 1, 2 and 3."); } } inline const DVector4<TF32>::TValueType& DVector4<TF32, void>::operator[](TIndex index) const // NOLINT { switch (index) { case 0: return this->X; case 1: return this->Y; case 2: return this->Z; case 3: return this->W; default: M_ASSERT_OR_THROW(false, "index must be 0, 1, 2 and 3."); } } inline DVector4<TF32>::TValueType* DVector4<TF32, void>::Data() noexcept { return &this->X; } inline const DVector4<TF32>::TValueType* DVector4<TF32, void>::Data() const noexcept { return &this->X; } inline TReal DVector4<TF32, void>::GetSquareLength() const noexcept { // Do dot product. (SSE4.1) const auto result = _mm_dp_ps(this->__mVal, this->__mVal, 0xFF); // Store float into values. (SSE) TF32 value[4]; _mm_store_ps(value, result); return value[3]; } inline TReal DVector4<TF32, void>::GetLength() const noexcept { return std::sqrt(this->GetSquareLength()); } inline TReal DVector4<TF32, void>::GetHomogeneousLength() const noexcept { TF32 vectorValues[4]; _mm_store_ps(vectorValues, this->__mVal); // Do dot product. (SSE4.1) const auto rejectedWSimd = _mm_set_ps(0, vectorValues[2], vectorValues[1], vectorValues[0]); const auto result = _mm_sqrt_ps(_mm_dp_ps(rejectedWSimd, rejectedWSimd, 0xFF)); #ifndef MATH_USE_REAL_AS_DOUBLE // Store float into values. (SSE) TF32 value[4]; _mm_store_ps(value, result); return value[3]; #else // Store double into values. (SSE) TF64 value[4]; _mm_store_pd(value, _mm_cvtps_pd(result)); return value[3]; #endif } inline DVector4<TReal> DVector4<TF32, void>::Normalize() const noexcept { #ifndef MATH_USE_REAL_AS_DOUBLE // Do dot product. (SSE4.1) and sqrt (SSE2) to get length. const auto result = _mm_sqrt_ps(_mm_dp_ps(this->__mVal, this->__mVal, 0xFF)); return DVector4<TReal>{_mm_div_ps(this->__mVal, result)}; #else // Do dot product. (SSE4.1) and sqrt (SSE2) to get length. const auto result = _mm_sqrt_pd(_mm_dp_pd(this->__mVal, this->__mVal, 0xFF)); return DVector4<TReal>{_mm_div_pd(simd, result)}; #endif } inline DVector4<TF32>& DVector4<TF32, void>::operator+=(const DVector4& value) noexcept { this->__mVal = _mm_add_ps(this->__mVal, value.__mVal); return *this; } inline DVector4<TF32>& DVector4<TF32, void>::operator-=(const DVector4& value) noexcept { this->__mVal = _mm_sub_ps(this->__mVal, value.__mVal); return *this; } inline DVector4<TF32>& DVector4<TF32, void>::operator*=(TValueType value) noexcept { this->__mVal = _mm_mul_ps(this->__mVal, _mm_set_ps1(value)); return *this; } inline DVector4<TF32>& DVector4<float, void>::operator*=(const DVector4& value) noexcept { this->__mVal = _mm_mul_ps(this->__mVal, value.__mVal); return *this; } inline DVector4<TF32>& DVector4<TF32, void>::operator/=(TValueType value) noexcept { this->__mVal = _mm_div_ps(this->__mVal, _mm_set_ps1(value)); return *this; } inline DVector4<TF32>& DVector4<TF32, void>::operator/=(const DVector4& value) noexcept { this->__mVal = _mm_div_ps(this->__mVal, value.__mVal); return *this; } } /// ::dy::math namespace #include "DVector4TF32Common.inl" #endif /// MATH_ENABLE_SIMD
29.628906
113
0.703626
[ "vector" ]
2d396a5644e120d93057121de5a60662b4642778
4,018
cpp
C++
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/Utilities.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
34
2015-02-04T18:03:14.000Z
2020-11-10T06:45:28.000Z
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/Utilities.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
5
2015-06-30T21:17:00.000Z
2016-06-14T22:31:51.000Z
src/C/Security-57031.40.6/Security/libsecurity_transform/lib/Utilities.cpp
GaloisInc/hacrypto
5c99d7ac73360e9b05452ac9380c1c7dc6784849
[ "BSD-3-Clause" ]
15
2015-10-29T14:21:58.000Z
2022-01-19T07:33:14.000Z
/* * Copyright (c) 2011,2014 Apple Inc. All Rights Reserved. * * @APPLE_LICENSE_HEADER_START@ * * This file contains Original Code and/or Modifications of Original Code * as defined in and that are subject to the Apple Public Source License * Version 2.0 (the 'License'). You may not use this file except in * compliance with the License. Please obtain a copy of the License at * http://www.opensource.apple.com/apsl/ and read it before using this * file. * * The Original Code and all software distributed under the License are * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES, * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT. * Please see the License for the specific language governing rights and * limitations under the License. * * @APPLE_LICENSE_HEADER_END@ */ #include "Utilities.h" #include "SecTransform.h" #include <sys/sysctl.h> #include <syslog.h> #include <dispatch/dispatch.h> void MyDispatchAsync(dispatch_queue_t queue, void(^block)(void)) { fprintf(stderr, "Running job on queue %p\n", queue); dispatch_async(queue, block); } dispatch_queue_t MyDispatchQueueCreate(const char* name, dispatch_queue_attr_t attr) { dispatch_queue_t result = dispatch_queue_create(name, attr); // fprintf(stderr, "Created queue %s as %p\n", name, result); return result; } static CFErrorRef CreateErrorRefCore(CFStringRef domain, int errorCode, const char* format, va_list ap) { CFStringRef fmt = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8); CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, fmt, ap); va_end(ap); CFRelease(fmt); CFStringRef keys[] = {kCFErrorDescriptionKey}; CFStringRef values[] = {str}; CFErrorRef result = CFErrorCreateWithUserInfoKeysAndValues(NULL, domain, errorCode, (const void**) keys, (const void**) values, 1); CFRelease(str); return result; } CFErrorRef CreateGenericErrorRef(CFStringRef domain, int errorCode, const char* format, ...) { va_list ap; va_start(ap, format); return CreateErrorRefCore(domain, errorCode, format, ap); } CFErrorRef CreateSecTransformErrorRef(int errorCode, const char* format, ...) { // create a CFError in the SecTransform error domain. You can add an explanation, which is cool. va_list ap; va_start(ap, format); return CreateErrorRefCore(kSecTransformErrorDomain, errorCode, format, ap); } CFErrorRef CreateSecTransformErrorRefWithCFType(int errorCode, CFTypeRef message) { CFStringRef keys[] = {kCFErrorLocalizedDescriptionKey}; CFTypeRef values[] = {message}; return CFErrorCreateWithUserInfoKeysAndValues(NULL, kSecTransformErrorDomain, errorCode, (const void**) keys, (const void**) values, 1); } CFTypeRef gAnnotatedRef = NULL; CFTypeRef DebugRetain(const void* owner, CFTypeRef type) { CFTypeRef result = CFRetain(type); if (type == gAnnotatedRef) { fprintf(stderr, "Object %p was retained by object %p, count = %ld\n", type, owner, CFGetRetainCount(type)); } return result; } void DebugRelease(const void* owner, CFTypeRef type) { if (type == gAnnotatedRef) { fprintf(stderr, "Object %p was released by object %p, count = %ld\n", type, owner, CFGetRetainCount(type) - 1); } CFRelease(type); } // Cribbed from _dispatch_bug and altered a bit void transforms_bug(size_t line, long val) { static dispatch_once_t pred; static char os_build[16]; static void *last_seen; void *ra = __builtin_return_address(0); dispatch_once(&pred, ^{ #ifdef __APPLE__ int mib[] = { CTL_KERN, KERN_OSVERSION }; size_t bufsz = sizeof(os_build); sysctl(mib, 2, os_build, &bufsz, NULL, 0); #else os_build[0] = '\0'; #endif }); if (last_seen != ra) { last_seen = ra; syslog(LOG_NOTICE, "BUG in SecTransforms: %s - %p - %lu - %lu", os_build, last_seen, (unsigned long)line, val); } }
28.7
137
0.729467
[ "object" ]
2d3b043c4484aafa6e98e47f97157340be8f8f13
637
hpp
C++
audio/Device.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
audio/Device.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
audio/Device.hpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#ifndef ___INANITY_AUDIO_DEVICE_HPP___ #define ___INANITY_AUDIO_DEVICE_HPP___ #include "audio.hpp" #include "../math/basic.hpp" BEGIN_INANITY_AUDIO class Source; class Sound; /// Abstract sound device class. class Device : public Object { public: virtual ptr<Sound> CreateBufferedSound(ptr<Source> source) = 0; virtual ptr<Sound> CreateStreamedSound(ptr<Source> source) = 0; virtual void SetListenerPosition(const Math::vec3& position) = 0; virtual void SetListenerOrientation(const Math::vec3& forward, const Math::vec3& up) = 0; virtual void SetListenerVelocity(const Math::vec3& velocity) = 0; }; END_INANITY_AUDIO #endif
23.592593
90
0.77551
[ "object" ]
2d3c19b66bfd0cdf3a7343326812766fc6a0f966
5,011
cc
C++
lib/tests/unit/external_module_test.cc
geoffnichols/pxp-agent
a852f9f4705f7027b96f7ea7d46675c9827a3536
[ "Apache-2.0" ]
null
null
null
lib/tests/unit/external_module_test.cc
geoffnichols/pxp-agent
a852f9f4705f7027b96f7ea7d46675c9827a3536
[ "Apache-2.0" ]
null
null
null
lib/tests/unit/external_module_test.cc
geoffnichols/pxp-agent
a852f9f4705f7027b96f7ea7d46675c9827a3536
[ "Apache-2.0" ]
null
null
null
#include "root_path.hpp" #include "content_format.hpp" #include <pxp-agent/external_module.hpp> #include <cpp-pcp-client/protocol/chunks.hpp> // ParsedChunks #include <leatherman/json_container/json_container.hpp> #include <boost/filesystem/operations.hpp> #include <catch.hpp> #include <string> #include <vector> #include <unistd.h> #ifdef _WIN32 #define EXTENSION ".bat" #else #define EXTENSION "" #endif namespace PXPAgent { namespace lth_jc = leatherman::json_container; static const std::string REVERSE_TXT { (DATA_FORMAT % "\"0987\"" % "\"reverse\"" % "\"string\"" % "{\"argument\" : \"maradona\"}").str() }; static const std::vector<lth_jc::JsonContainer> NO_DEBUG {}; static const PCPClient::ParsedChunks CONTENT { lth_jc::JsonContainer(ENVELOPE_TXT), // envelope lth_jc::JsonContainer(REVERSE_TXT), // data NO_DEBUG, // debug 0 }; // num invalid debug chunks TEST_CASE("ExternalModule::ExternalModule", "[modules]") { SECTION("can successfully instantiate from a valid external module") { REQUIRE_NOTHROW(ExternalModule(PXP_AGENT_ROOT_PATH "/lib/tests/resources/modules/reverse_valid" EXTENSION)); } SECTION("all actions are successfully loaded from a valid external module") { ExternalModule mod { PXP_AGENT_ROOT_PATH "/lib/tests/resources/modules/failures_test" EXTENSION }; REQUIRE(mod.actions.size() == 2); } SECTION("throw a Module::LoadingError in case the module has an invalid " "metadata schema") { REQUIRE_THROWS_AS( ExternalModule(PXP_AGENT_ROOT_PATH "/lib/tests/resources/broken_modules/reverse_broken" EXTENSION), Module::LoadingError); } } TEST_CASE("ExternalModule::hasAction", "[modules]") { ExternalModule mod { PXP_AGENT_ROOT_PATH "/lib/tests/resources/modules/reverse_valid" EXTENSION }; SECTION("correctly reports false") { REQUIRE(!mod.hasAction("foo")); } SECTION("correctly reports true") { REQUIRE(mod.hasAction("string")); } } TEST_CASE("ExternalModule::callAction - blocking", "[modules]") { SECTION("the shipped 'reverse' module works correctly") { ExternalModule reverse_module { PXP_AGENT_ROOT_PATH "/lib/tests/resources//modules/reverse_valid" EXTENSION }; SECTION("correctly call the reverse module") { ActionRequest request { RequestType::Blocking, CONTENT }; auto outcome = reverse_module.executeAction(request); REQUIRE(outcome.std_out.find("anodaram") != std::string::npos); } } SECTION("it should handle module failures") { ExternalModule test_reverse_module { PXP_AGENT_ROOT_PATH "/lib/tests/resources/modules/failures_test" EXTENSION }; SECTION("throw a Module::ProcessingError if the module returns an " "invalid result") { std::string failure_txt { (DATA_FORMAT % "\"1234987\"" % "\"failures_test\"" % "\"get_an_invalid_result\"" % "\"maradona\"").str() }; PCPClient::ParsedChunks failure_content { lth_jc::JsonContainer(ENVELOPE_TXT), lth_jc::JsonContainer(failure_txt), NO_DEBUG, 0 }; ActionRequest request { RequestType::Blocking, failure_content }; REQUIRE_THROWS_AS(test_reverse_module.executeAction(request), Module::ProcessingError); } SECTION("throw a Module::ProcessingError if a blocking action throws " "an exception") { std::string failure_txt { (DATA_FORMAT % "\"43217890\"" % "\"failures_test\"" % "\"broken_action\"" % "\"maradona\"").str() }; PCPClient::ParsedChunks failure_content { lth_jc::JsonContainer(ENVELOPE_TXT), lth_jc::JsonContainer(failure_txt), NO_DEBUG, 0 }; ActionRequest request { RequestType::Blocking, failure_content }; REQUIRE_THROWS_AS(test_reverse_module.executeAction(request), Module::ProcessingError); } } } } // namespace PXPAgent
36.845588
89
0.538216
[ "vector" ]
2d3da782b7b43bda066c5fb56e6db2ee1e2841b6
18,041
cpp
C++
src/GLHelpers.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
15
2015-10-18T15:11:34.000Z
2021-06-15T02:22:13.000Z
src/GLHelpers.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
13
2015-04-24T20:37:44.000Z
2020-01-27T15:26:42.000Z
src/GLHelpers.cpp
bpwiselybabu/SceneGraph
1ae7142615bb2c15883ed928a5ed69b0cd281665
[ "Apache-2.0" ]
9
2015-08-21T18:52:27.000Z
2020-04-08T15:15:38.000Z
/* * \file GLHelpers.cpp * * $Id$ */ #include <SceneGraph/GLHelpers.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <vector> #undef Success #include <Eigen/Core> #include <Eigen/LU> namespace SceneGraph { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// If a GL error has occured, this function outputs "msg" and the // programme exits. To avoid exiting @see WarnForGLErrors. void _CheckForGLErrors( const char *sFile, const int nLine ) { GLenum glError = glGetError(); if( glError != GL_NO_ERROR ) { fprintf( stderr, "ERROR: %s -- %s line %d\n", (char*)gluErrorString(glError), sFile, nLine ); //FIXME: On my box, glError is not totally free of error. // there's probably something wrong with one of the glEnable(...) in GLWindow.cpp // so I temporarily comment out the exit() call here. // exit( -1 ); } } ////////////////////////////////////////////////////////////////////////////// // Extract current camera pose from opengl in the Robotics Coordinate frame convention Eigen::Matrix4d GLGetCameraPose() { Eigen::Matrix<double,4,4,Eigen::ColMajor> M; // for opengl glGetDoublev( GL_MODELVIEW_MATRIX, M.data() ); Eigen::Matrix3d gl2v; gl2v << 0,0,-1, 1,0,0, 0,-1,0; // Eigen::Vector3d xyz = -M.block<3,3>(0,0).transpose()*M.block<3,1>(0,3); // Vector3d pqr = R2Cart( gl2v*M.block<3,3>(0,0) ); Eigen::Matrix4d T; T.block<3,3>(0,0) = gl2v*M.block<3,3>(0,0); T.block<3,1>(0,3) = -M.block<3,3>(0,0).transpose()*M.block<3,1>(0,3); T.block<1,4>(3,0) << 0, 0, 0, 1; return T; } /////////////////////////////////////////////////////////////////////////////// /// Convert opengl projection matrix into computer vision K matrix Eigen::Matrix3d GLGetProjectionMatrix() { Eigen::Matrix<double,4,4,Eigen::ColMajor> P; // for opengl glGetDoublev( GL_PROJECTION_MATRIX, P.data() ); GLint vViewport[4]; glGetIntegerv( GL_VIEWPORT, vViewport ); // fovy = 2*atan( h/2/f ); // f = tan(fovy/2)/(h/2) Eigen::Matrix3d K; K(0,0) = P(0,0); // P00 = 1/tan(fov/2) ==> fx = P00 K(0,1) = 0.0; // sx K(0,2) = vViewport[2]/2.0; // cx K(1,0) = 0.0; K(1,1) = P(1,1); // fy K(1,2) = vViewport[3]/2.0; // cy K(2,0) = 0.0; K(2,1) = 0.0; K(2,2) = 1.0; // cout << P(0,0) * vViewport[2]/(double)vViewport[3] << endl; // cout << "K:\n" << K << endl << endl; return K; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// If a GL error has occured, this function outputs "msg" and automatically sets // the gl error state back to normal. void WarnForGLErrors( const char * msg ) { GLenum glError = (GLenum)glGetError(); if( glError != GL_NO_ERROR ) { if( msg ) { fprintf( stderr, "WARNING: %s\n", msg ); } fprintf( stderr, "ERROR: %s\n", (char *) gluErrorString(glError) ); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// Given a particular OpenGL Format, return the appropriate number of image channels. unsigned int NumChannels( unsigned int nFormat ) { switch( nFormat ){ case GL_LUMINANCE: case GL_RED: case GL_BLUE: case GL_GREEN: case GL_ALPHA: return 1; case GL_RGB: return 3; case GL_RGBA: return 4; default: fprintf( stderr, "NumChannels() - unknown format\n" ); return 0; } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// Given an OpenGL Type, return the associated number of bits used. unsigned int BitsPerChannel( unsigned int nType ) { switch( nType ){ case GL_UNSIGNED_BYTE: case GL_BYTE: return 8; case GL_2_BYTES: case GL_SHORT: case GL_UNSIGNED_SHORT: return 16; case GL_4_BYTES: case GL_FLOAT: case GL_UNSIGNED_INT: case GL_INT: return 32; case GL_DOUBLE: return 64; case GL_3_BYTES: return 24; default: fprintf( stderr, "\nBitsPerChannel() - unknown image Type"); return 0; } return 0; } //////////////////////////////////////////////////////////////////////////////////////////////////// // Change to orthographic projection (for image drawing, etc) void PushOrtho( const unsigned int nWidth, const unsigned int nHeight ) { // load ortho to the size of the window glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glOrtho(0, nWidth, nHeight, 0, -1, 1); // left, right, top, bottom, near, far glMatrixMode( GL_MODELVIEW ); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// Set projection matrix void PopOrtho() { glBindTexture( GL_TEXTURE_RECTANGLE_ARB, 0 ); glMatrixMode(GL_PROJECTION); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// Set projection matrix void OrthoQuad( const int nTexWidth, //< Input: const int nTexHeight, //< Input: const int nTop, //< Input: const int nLeft, //< Input: const int nBottom, //< Input: const int nRight //< Input: ) { /* glBegin( GL_QUADS ); glTexCoord2f( 0.0, 0.0 ); glVertex3f( nLeft, nBottom, 1 ); glTexCoord2f( 0.0, nTexHeight ); glVertex3f( nLeft, nTop, 1 ); glTexCoord2f( nTexWidth, nTexHeight ); glVertex3f( nRight, nTop, 1 ); glTexCoord2f( nTexWidth, 0.0 ); glVertex3f( nRight, nBottom, 1 ); glEnd(); */ glNormal3f( -1,0,0 ); glBegin( GL_QUADS ); glTexCoord2f( 0.0, 0.0 ); glVertex3f( nLeft, nBottom, 0 ); glTexCoord2f( nTexWidth, 0.0 ); glVertex3f( nRight, nBottom, 0 ); glTexCoord2f( nTexWidth, nTexHeight ); glVertex3f( nRight, nTop, 0 ); glTexCoord2f( 0.0, nTexHeight ); glVertex3f( nLeft, nTop, 0 ); glEnd(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void DrawBorderAsWindowPercentage( const float fTop, const float fLeft, const float fBottom, const float fRight ) { GLint vViewport[4]; glGetIntegerv( GL_VIEWPORT, vViewport ); PushOrtho( vViewport[2], vViewport[3] ); glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glBegin( GL_QUADS ); glVertex3f( fLeft*vViewport[2], fBottom*vViewport[3], 0 ); glVertex3f( fRight*vViewport[2], fBottom*vViewport[3], 0 ); glVertex3f( fRight*vViewport[2], fTop*vViewport[3], 0 ); glVertex3f( fLeft*vViewport[2], fTop*vViewport[3], 0 ); glEnd(); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); PopOrtho(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void DrawTextureAsWindowPercentage( const unsigned int nTexId, //< Input: const unsigned int nTexWidth, //< Input: const unsigned int nTexHeight,//< Input: const float fTop, const float fLeft, const float fBottom, const float fRight ) { glDisable( GL_LIGHTING ); glColor4f( 1,1,1,1 ); // only scoop up texture colors GLint vViewport[4]; glGetIntegerv( GL_VIEWPORT, vViewport ); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture( GL_TEXTURE_RECTANGLE_ARB, nTexId ); PushOrtho( vViewport[2], vViewport[3] ); OrthoQuad( nTexWidth, nTexHeight, fTop*vViewport[3], fLeft*vViewport[2], fBottom*vViewport[3], fRight*vViewport[2] ); PopOrtho(); } //////////////////////////////////////////////////////////////////////////////////////////////////// void DrawTexture( const unsigned int nTexId, //< Input: const unsigned int nTexWidth, //< Input: const unsigned int nTexHeight,//< Input: const unsigned int nTop, //< Input: const unsigned int nLeft, //< Input: const unsigned int nBottom, //< Input: const unsigned int nRight //< Input: ) { // NB DECAL ignores lighting // glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); glDisable( GL_LIGHTING ); glColor4f( 1,1,1,1 ); // only scoop up texture colors GLint vViewport[4]; glGetIntegerv( GL_VIEWPORT, vViewport ); glEnable(GL_TEXTURE_RECTANGLE_ARB); glBindTexture( GL_TEXTURE_RECTANGLE_ARB, nTexId ); PushOrtho( vViewport[2], vViewport[3] ); OrthoQuad( nTexWidth, nTexHeight, nTop, nLeft, nBottom, nRight ); PopOrtho(); } ////////////////////////////////////////////////////////////////////////////// // read from opengl buffer into our own vector void ReadPixels( std::vector<unsigned char>& vPixels, int nWidth, int nHeight, bool bFlip /// default to true ) { int nFormat = GL_RGBA; int nType = GL_UNSIGNED_BYTE; unsigned int nBpp = GLBytesPerPixel( nFormat, nType ); if( vPixels.size() < nWidth*nBpp*nHeight ){ vPixels.resize( nWidth*nBpp*nHeight ); } char* pPixelData = (char*)&vPixels[0]; glReadPixels( 0, 0, nWidth, nHeight, nFormat, nType, pPixelData ); if( bFlip ){ int inc = nBpp*nWidth; char* pSwap = (char*)malloc( inc ); char* pTopDown = pPixelData; char* pBottomUp = &pPixelData[ nWidth*nBpp*nHeight ]; for( ; pTopDown < pBottomUp; pTopDown += inc, pBottomUp -= inc ){ memcpy( pSwap, pTopDown, inc ); memcpy( pTopDown, pBottomUp, inc ); memcpy( pBottomUp, pSwap, inc ); } free( pSwap ); } } ////////////////////////////////////////////////////////////////////////////// // read from opengl buffer into our own vector void ReadDepthPixels( std::vector<float>& vPixels, int nWidth, int nHeight, bool bFlip // defaults to true ) { int nFormat = GL_RGBA; int nType = GL_UNSIGNED_BYTE; unsigned int nBpp = GLBytesPerPixel( nFormat, nType ); if( vPixels.size() < nWidth*nBpp*nHeight ){ vPixels.resize( nWidth*nBpp*nHeight ); } char* pPixelData = (char*)&vPixels[0]; glReadPixels( 0, 0, nWidth, nHeight, nFormat, nType, pPixelData ); if( bFlip ){ int inc = nBpp*nWidth; char* pSwap = (char*)malloc( inc ); char* pTopDown = pPixelData; char* pBottomUp = &pPixelData[ nWidth*nBpp*nHeight ]; for( ; pTopDown < pBottomUp; pTopDown += inc, pBottomUp -= inc ){ memcpy( pSwap, pTopDown, inc ); memcpy( pTopDown, pBottomUp, inc ); memcpy( pBottomUp, pSwap, inc ); } free( pSwap ); } } ////////////////////////////////////////////////////////////////////////////// void CheckFBOStatus() { //Does the GPU support current FBO configuration? GLenum status; status = glCheckFramebufferStatusEXT( GL_FRAMEBUFFER_EXT ); switch(status) { case GL_FRAMEBUFFER_COMPLETE_EXT: // std::cerr << "The framebuffer is complete and valid for rendering.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT: std::cerr << "One or more attachment points are not framebuffer attachment complete.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT: std::cerr << "There are no attachments.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT: std::cerr << "Attachments are of different size. All attachments must have the same width and height.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT: std::cerr << "The color attachments have different format. All color attachments must have the same format.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT: std::cerr << "An attachment point referenced by glDrawBuffers() doesn’t have an attachment.\n"; break; case GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT: std::cerr << "The attachment point referenced by glReadBuffers() doesn’t have an attachment.\n"; break; case GL_FRAMEBUFFER_UNSUPPORTED_EXT: std::cerr << "This particular FBO configuration is not supported by the implementation.\n"; break; } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// set perspective view. same as gluperspective(). void Perspective( double fovy, double aspect, double zNear, double zFar) { double xmin, xmax, ymin, ymax; ymax = zNear * tan(fovy * M_PI / 360.0); ymin = -ymax; xmin = ymin * aspect; xmax = ymax * aspect; glFrustum(xmin, xmax, ymin, ymax, zNear, zFar); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// Reshape viewport whenever window changes size. void ReshapeViewport( int w, int h ) { // Viewport glViewport(0, 0, w, h ); // Projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); GLfloat ratio = float(w) / float(h); Perspective( 60.0, 1.0*ratio, 1.0, 1000.0 ); // Model view glMatrixMode(GL_MODELVIEW); glLoadIdentity(); } //////////////////////////////////////////////////////////////////////////////////////////////////// // local little helper Eigen::Vector4d Vec4( double a, double b, double c, double d ) { Eigen::Vector4d tmp; tmp << a, b, c, d; return tmp; } //////////////////////////////////////////////////////////////////////////////////////////////////// void DrawCamera( int nTexWidth, int nTexHeight, int nTexId, const Eigen::Matrix4d& dModelViewMatrix, const Eigen::Matrix4d& dProjectionMatrix ) { // OK Eigen::Matrix4d M = dProjectionMatrix.inverse(); Eigen::Matrix4d T = dModelViewMatrix.inverse(); Eigen::Vector4d lbn = T*M*Vec4( -1,-1,-1, 1 ); lbn/=lbn[3]; Eigen::Vector4d rbn = T*M*Vec4( 1,-1,-1, 1 ); rbn/=rbn[3]; Eigen::Vector4d ltn = T*M*Vec4( -1, 1,-1, 1 ); ltn/=ltn[3]; Eigen::Vector4d rtn = T*M*Vec4( 1, 1,-1, 1 ); rtn/=rtn[3]; Eigen::Vector4d lbf = T*M*Vec4( -1,-1, 1, 1 ); lbf/=lbf[3]; Eigen::Vector4d rbf = T*M*Vec4( 1,-1, 1, 1 ); rbf/=rbf[3]; Eigen::Vector4d ltf = T*M*Vec4( -1, 1, 1, 1 ); ltf/=ltf[3]; Eigen::Vector4d rtf = T*M*Vec4( 1, 1, 1, 1 ); rtf/=rtf[3]; // glColor4f( 1,1,1,1 ); /// Draw texture glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_DECAL ); glEnable( GL_TEXTURE_RECTANGLE_ARB ); glBindTexture( GL_TEXTURE_RECTANGLE_ARB, nTexId ); glEnable( GL_DEPTH_TEST ); glDisable( GL_LIGHTING ); glDisable( GL_LIGHT0 ); glDisable( GL_CULL_FACE ); glBegin( GL_QUADS ); glNormal3f( -1,0,0 ); glTexCoord2f( 0.0, 0.0 ); glVertex3dv( lbn.data() ); glTexCoord2f( nTexWidth, 0.0 ); glVertex3dv( rbn.data() ); glTexCoord2f( nTexWidth, nTexHeight ); glVertex3dv( rtn.data() ); glTexCoord2f( 0.0, nTexHeight ); glVertex3dv( ltn.data() ); glEnd(); glBindTexture( GL_TEXTURE_RECTANGLE_ARB, 0 ); glDisable(GL_TEXTURE_RECTANGLE_ARB); glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE ); // glDisable( GL_DEPTH_TEST ); glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA ); glEnable( GL_BLEND ); glColor4f( 1, 1, 1, 0.5 ); // draw frustrum glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); glBegin( GL_QUADS ); // near glVertex3dv( lbn.data() ); glVertex3dv( rbn.data() ); glVertex3dv( rtn.data() ); glVertex3dv( ltn.data() ); // far glVertex3dv( rbf.data() ); glVertex3dv( lbf.data() ); glVertex3dv( ltf.data() ); glVertex3dv( rtf.data() ); // left glVertex3dv( lbf.data() ); glVertex3dv( lbn.data() ); glVertex3dv( ltn.data() ); glVertex3dv( ltf.data() ); // right glVertex3dv( rbn.data() ); glVertex3dv( rbf.data() ); glVertex3dv( rtf.data() ); glVertex3dv( rtn.data() ); // top glVertex3dv( ltn.data() ); glVertex3dv( rtn.data() ); glVertex3dv( rtf.data() ); glVertex3dv( ltf.data() ); // bottom glVertex3dv( lbn.data() ); glVertex3dv( rbn.data() ); glVertex3dv( rbf.data() ); glVertex3dv( lbf.data() ); glEnd(); glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); // glEnable( GL_LIGHTING ); // lEnable( GL_LIGHT0 ); glColor4f( 1,1,1,0.1 ); glBegin( GL_QUADS ); // near glVertex3dv( lbn.data() ); glVertex3dv( rbn.data() ); glVertex3dv( rtn.data() ); glVertex3dv( ltn.data() ); // far glVertex3dv( rbf.data() ); glVertex3dv( lbf.data() ); glVertex3dv( ltf.data() ); glVertex3dv( rtf.data() ); // left glVertex3dv( lbf.data() ); glVertex3dv( lbn.data() ); glVertex3dv( ltn.data() ); glVertex3dv( ltf.data() ); // right glVertex3dv( rbn.data() ); glVertex3dv( rbf.data() ); glVertex3dv( rtf.data() ); glVertex3dv( rtn.data() ); // top glVertex3dv( ltn.data() ); glVertex3dv( rtn.data() ); glVertex3dv( rtf.data() ); glVertex3dv( ltf.data() ); // bottom glVertex3dv( lbn.data() ); glVertex3dv( rbn.data() ); glVertex3dv( rbf.data() ); glVertex3dv( lbf.data() ); glEnd(); glDisable( GL_BLEND ); glEnable( GL_DEPTH_TEST ); glEnable( GL_CULL_FACE ); } } // SceneGraph
31.051635
123
0.536722
[ "vector", "model" ]
2d3eeb83b881b7e804ac64e520a9eed61685d98d
3,661
hpp
C++
test/hipcub/test_hipcub_device_radix_sort.hpp
nunnikri/hipCUB
6e9bc3cfb36493719c89051d1053edceb1d2374e
[ "BSD-3-Clause" ]
null
null
null
test/hipcub/test_hipcub_device_radix_sort.hpp
nunnikri/hipCUB
6e9bc3cfb36493719c89051d1053edceb1d2374e
[ "BSD-3-Clause" ]
null
null
null
test/hipcub/test_hipcub_device_radix_sort.hpp
nunnikri/hipCUB
6e9bc3cfb36493719c89051d1053edceb1d2374e
[ "BSD-3-Clause" ]
null
null
null
// MIT License // // Copyright (c) 2017-2022 Advanced Micro Devices, Inc. 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. #ifndef HIPCUB_TEST_HIPCUB_DEVICE_RADIX_SORT_HPP_ #define HIPCUB_TEST_HIPCUB_DEVICE_RADIX_SORT_HPP_ #include "common_test_header.hpp" // hipcub API #include "hipcub/device/device_radix_sort.hpp" #include "test_utils_sort_comparator.hpp" template< class Key, class Value, bool Descending = false, unsigned int StartBit = 0, unsigned int EndBit = sizeof(Key) * 8, bool CheckLargeSizes = false > struct params { using key_type = Key; using value_type = Value; static constexpr bool descending = Descending; static constexpr unsigned int start_bit = StartBit; static constexpr unsigned int end_bit = EndBit; static constexpr bool check_large_sizes = CheckLargeSizes; }; template<class Params> class HipcubDeviceRadixSort : public ::testing::Test { public: using params = Params; }; typedef ::testing::Types< params<signed char, double, true>, params<int, short>, params<short, int, true>, params<long long, char>, params<double, unsigned int>, params<double, int, true>, params<float, int>, params<test_utils::half, int>, params<test_utils::half, int, true>, params<test_utils::bfloat16, int>, params<test_utils::bfloat16, int, true>, params<int, test_utils::custom_test_type<float>>, // start_bit and end_bit params<unsigned char, int, true, 0, 7>, params<unsigned short, int, true, 4, 10>, params<unsigned int, short, false, 3, 22>, params<unsigned int, double, true, 4, 21>, params<unsigned int, short, true, 0, 15>, params<unsigned long long, char, false, 8, 20>, params<unsigned short, double, false, 8, 11>, // some params used by PyTorch's Randperm() params<int64_t, int64_t, false, 0, 34>, params<int64_t, float, true, 0, 34>, params<int64_t, test_utils::half, true, 0, 34>, params<int64_t, int64_t, false, 0, 34, true>, // large sizes to check correctness of more than 1 block per batch params<float, char, true, 0, 32, true> > Params; TYPED_TEST_SUITE(HipcubDeviceRadixSort, Params); inline std::vector<unsigned int> get_sizes() { std::vector<unsigned int> sizes = { 1, 10, 53, 211, 1024, 2345, 4096, 34567, (1 << 16) - 1220, (1 << 23) - 76543 }; const std::vector<unsigned int> random_sizes = test_utils::get_random_data<unsigned int>(10, 1, 100000, rand()); sizes.insert(sizes.end(), random_sizes.begin(), random_sizes.end()); return sizes; } #endif // HIPCUB_TEST_HIPCUB_DEVICE_RADIX_SORT_HPP_
36.61
119
0.716471
[ "vector" ]
2d430f3d0524bf586a289c7cdc9ba44e11bb1731
14,320
cpp
C++
Plugins/OpenVR/OpenVRDevice.cpp
GlynnJKW/Stratum
ddc55796f3207fe3df23c455c6304cb72aebcb02
[ "MIT" ]
null
null
null
Plugins/OpenVR/OpenVRDevice.cpp
GlynnJKW/Stratum
ddc55796f3207fe3df23c455c6304cb72aebcb02
[ "MIT" ]
null
null
null
Plugins/OpenVR/OpenVRDevice.cpp
GlynnJKW/Stratum
ddc55796f3207fe3df23c455c6304cb72aebcb02
[ "MIT" ]
null
null
null
#include "OpenVRDevice.hpp" #pragma region Conversion code // Converts to float4x4 format and flips from right-handed to left-handed float4x4 OpenVRDevice::ConvertMat34(vr::HmdMatrix34_t mat34) { return float4x4( mat34.m[0][0], mat34.m[0][1], mat34.m[0][2], mat34.m[0][3], mat34.m[1][0], mat34.m[1][1], mat34.m[1][2], mat34.m[1][3], mat34.m[2][0], mat34.m[2][1], mat34.m[2][2], mat34.m[2][3], 0.f, 0.f, 0.f, 1.f ); } float4x4 OpenVRDevice::ConvertMat44(vr::HmdMatrix44_t mat44) { return float4x4( mat44.m[0][0], mat44.m[0][1], mat44.m[0][2], mat44.m[0][3], mat44.m[1][0], mat44.m[1][1], mat44.m[1][2], mat44.m[1][3], mat44.m[2][0], mat44.m[2][1], mat44.m[2][2], mat44.m[2][3], mat44.m[3][0], mat44.m[3][1], mat44.m[3][2], mat44.m[3][3] ); } float4x4 OpenVRDevice::RHtoLH(float4x4 RH) { return float4x4( RH[0][0], RH[1][0], -RH[2][0], RH[3][0], RH[0][1], RH[1][1], -RH[2][1], RH[3][1], -RH[0][2], -RH[1][2], RH[2][2], -RH[3][2], RH[0][3], RH[1][3], -RH[2][3], RH[3][3] ); } OpenVRDevice::OpenVRDevice(float near, float far) : mNearClip(near), mFarClip(far), mSystem(nullptr), mPosition(float3()), mRotation(quaternion()) { Init(); } OpenVRDevice::~OpenVRDevice() { vr::VR_Shutdown(); } void OpenVRDevice::Init() { vr::EVRInitError eError = vr::VRInitError_None; mSystem = vr::VR_Init(&eError, vr::VRApplication_Scene); if (eError != vr::VRInitError_None) { mSystem = nullptr; fprintf_color(COLOR_RED, stderr, "Error: Unable to initialize the OpenVR library.\nReason: %s\n", vr::VR_GetVRInitErrorAsEnglishDescription(eError)); throw "OPENVR_FAILURE"; return; } if (!vr::VRCompositor()) { mSystem = nullptr; vr::VR_Shutdown(); fprintf_color(COLOR_RED, stderr, "Error: Compositor initialization failed"); throw "OPENVR_FAILURE"; return; } mRenderModels = (vr::IVRRenderModels*)vr::VR_GetGenericInterface(vr::IVRRenderModels_Version, &eError); if (mRenderModels == nullptr) { mSystem = nullptr; vr::VR_Shutdown(); fprintf_color(COLOR_RED, stderr, "Error: Unable to get render model interface!\nReason: %s", vr::VR_GetVRInitErrorAsEnglishDescription(eError)); throw "OPENVR_FAILURE"; return; } //InitializeActions(); std::string driverName = GetDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_TrackingSystemName_String); std::string deviceSerialNumber = GetDeviceProperty(vr::k_unTrackedDeviceIndex_Hmd, vr::Prop_SerialNumber_String); fprintf_color(COLOR_GREEN, stdout, "OpenVR HMD Driver Initialized\Driver name: %s\nDriver serial#: %s\n", driverName, deviceSerialNumber); } // Adapted from https://github.com/Omnifinity/OpenVR-Tracking-Example void OpenVRDevice::InitializeActions() { // Prepare manifest file const char* manifestPath = "C:/Users/pt/Documents/Visual Studio 2013/Projects/HTC Lighthouse Tracking Example/Release/win32/vive_debugger_actions.json"; vr::EVRInputError inputError = vr::VRInput()->SetActionManifestPath(manifestPath); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to set manifest path: %d\n", inputError); throw "OPENVR_FAILURE"; } // Handles for the new IVRInput inputError = vr::VRInput()->GetActionSetHandle(actionSetPath, &mActionSet); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action set handle: %d\n", inputError); } // handle for left controller pose inputError = vr::VRInput()->GetActionHandle(actionHandLeftPath, &mActionHandLeft); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action handle: %d\n", inputError); } // handle for right controller pose inputError = vr::VRInput()->GetActionHandle(actionHandRightPath, &mActionHandRight); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action handle: %d\n", inputError); } // handle for analog trackpad action inputError = vr::VRInput()->GetActionHandle(actionDemoAnalogInputPath, &mActionAnalogInput); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action handle: %d\n", inputError); } // handle for a touch action inputError = vr::VRInput()->GetActionHandle(actionDemoTouchPath, &mActionTouch); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action handle: %d\n", inputError); } // handle for a click action inputError = vr::VRInput()->GetActionHandle(actionDemoClickPath, &mActionClick); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get action handle: %d\n", inputError); } // handle for controller pose source - not used atm inputError = vr::VRInput()->GetInputSourceHandle(inputHandLeftPath, &mInputHandLeftPath); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get input handle: %d\n", inputError); } inputError = vr::VRInput()->GetInputSourceHandle(inputHandRightPath, &mInputHandRightPath); if (inputError != vr::VRInputError_None) { printf_color(COLOR_RED, "Error: Unable to get input handle: %d\n", inputError); } } std::string OpenVRDevice::GetDeviceProperty(vr::TrackedDeviceIndex_t unDevice, vr::TrackedDeviceProperty prop, vr::TrackedPropertyError* peError) { uint32_t bufferLen = mSystem->GetStringTrackedDeviceProperty(unDevice, prop, NULL, 0, peError); if (bufferLen == 0) { return ""; } char* buffer = new char[bufferLen]; bufferLen = mSystem->GetStringTrackedDeviceProperty(unDevice, prop, buffer, bufferLen, peError); std::string result = buffer; delete[] buffer; return result; } void OpenVRDevice::Shutdown() { } void OpenVRDevice::Update() { /* vr::VRActiveActionSet_t actionSet = { 0 }; actionSet.ulActionSet = m_actionsetDemo; vr::VRInput()->UpdateActionState(&actionSet, sizeof(actionSet), 1); for (EHand eHand = Left; eHand <= Right; ((int&)eHand)++) { vr::InputPoseActionData_t poseData; if (vr::VRInput()->GetPoseActionDataForNextFrame(m_rHand[eHand].m_actionPose, vr::TrackingUniverseStanding, &poseData, sizeof(poseData), vr::k_ulInvalidInputValueHandle) != vr::VRInputError_None || !poseData.bActive || !poseData.pose.bPoseIsValid) { m_rHand[eHand].m_bShowController = false; } else { m_rHand[eHand].m_rmat4Pose = ConvertSteamVRMatrixToMatrix4(poseData.pose.mDeviceToAbsoluteTracking); vr::InputOriginInfo_t originInfo; if (vr::VRInput()->GetOriginTrackedDeviceInfo(poseData.activeOrigin, &originInfo, sizeof(originInfo)) == vr::VRInputError_None && originInfo.trackedDeviceIndex != vr::k_unTrackedDeviceIndexInvalid) { std::string sRenderModelName = GetTrackedDeviceString(originInfo.trackedDeviceIndex, vr::Prop_RenderModelName_String); if (sRenderModelName != m_rHand[eHand].m_sRenderModelName) { m_rHand[eHand].m_pRenderModel = FindOrLoadRenderModel(sRenderModelName.c_str()); m_rHand[eHand].m_sRenderModelName = sRenderModelName; } } } } */ vr::VRCompositor()->WaitGetPoses(mTrackedDevicePoses, vr::k_unMaxTrackedDeviceCount, NULL, 0); if (mTrackedDevicePoses[vr::k_unTrackedDeviceIndex_Hmd].bPoseIsValid) { mHeadMatrix = ConvertMat34(mTrackedDevicePoses[vr::k_unTrackedDeviceIndex_Hmd].mDeviceToAbsoluteTracking); //mHeadMatrix = RHtoLH(mHeadMatrix); mHeadMatrix.Decompose(&mPosition, &mRotation, nullptr); //mPosition.z = -mPosition.z; //mRotation.x = -mRotation.x; //mRotation.y = -mRotation.y; //printf_color(COLOR_MAGENTA, "Head position: %f, %f, %f\nHead rotation: %f, %f, %f, %f\n\n", mPosition.x, mPosition.y, mPosition.z, mRotation.x, mRotation.y, mRotation.z, mRotation.w); } } void OpenVRDevice::ProcessEvent(vr::VREvent_t event) { } void OpenVRDevice::UpdateTracking() { vr::EVRInputError inputError; vr::VRActiveActionSet_t actionSet = { 0 }; actionSet.ulActionSet = mActionSet; vr::VRInput()->UpdateActionState(&actionSet, sizeof(actionSet), 1); /* vr::InputAnalogActionData_t analogData; inputError = vr::VRInput()->GetAnalogActionData(mActionAnalogInput, &analogData, sizeof(analogData), vr::k_ulInvalidInputValueHandle); if (inputError == vr::VRInputError_None && analogData.bActive) { float m_vAnalogValue0 = analogData.x; float m_vAnalogValue1 = analogData.y; // check from which device the action came vr::InputOriginInfo_t originInfo; if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(analogData.activeOrigin, &originInfo, sizeof(originInfo))) { if (originInfo.devicePath == mInputHandLeftPath) { } else if (originInfo.devicePath == mInputHandRightPath) { } } } // Get digital data of a "Touch Action" vr::InputDigitalActionData_t digitalDataTouch; inputError = vr::VRInput()->GetDigitalActionData(mActionTouch, &digitalDataTouch, sizeof(digitalDataTouch), vr::k_ulInvalidInputValueHandle); if (inputError == vr::VRInputError_None) { bool val = digitalDataTouch.bState; // check from which device the action came vr::InputOriginInfo_t originInfo; if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(digitalDataTouch.activeOrigin, &originInfo, sizeof(originInfo))) { if (originInfo.devicePath == mInputHandLeftPath) { } else if (originInfo.devicePath == mInputHandRightPath) { } } } // Get digital data of a "Click Action" vr::InputDigitalActionData_t digitalDataClick; inputError = vr::VRInput()->GetDigitalActionData(mActionClick, &digitalDataClick, sizeof(digitalDataClick), vr::k_ulInvalidInputValueHandle); if (inputError == vr::VRInputError_None && digitalDataClick.bActive) { bool val = digitalDataClick.bState; // check from which device the action came vr::InputOriginInfo_t originInfo; if (vr::VRInputError_None == vr::VRInput()->GetOriginTrackedDeviceInfo(digitalDataClick.activeOrigin, &originInfo, sizeof(originInfo))) { if (originInfo.devicePath == mInputHandLeftPath) { } else if (originInfo.devicePath == mInputHandRightPath) { } } } */ // get pose data for each controller vr::InputPoseActionData_t poseData; inputError = vr::VRInput()->GetPoseActionDataForNextFrame(mActionHandLeft, vr::TrackingUniverseStanding, &poseData, sizeof(poseData), vr::k_ulInvalidInputValueHandle); if (inputError == vr::VRInputError_None && poseData.bActive && poseData.pose.bPoseIsValid && poseData.pose.bDeviceIsConnected) { float4x4 pose = ConvertMat34(poseData.pose.mDeviceToAbsoluteTracking); pose.Decompose(&mControllers[0].position, &mControllers[0].rotation, nullptr); } } void OpenVRDevice::CalculateEyeAdjustment() { vr::HmdMatrix34_t mat; mat = mSystem->GetEyeToHeadTransform(vr::Eye_Left); mLeftEyeTransform = (ConvertMat34(mat)); mat = mSystem->GetEyeToHeadTransform(vr::Eye_Right); mRightEyeTransform = (ConvertMat34(mat)); } void OpenVRDevice::CalculateProjectionMatrices() { vr::HmdMatrix44_t mat; float l, r, t, b; mSystem->GetProjectionRaw(vr::Eye_Left, &l, &r, &t, &b); l *= mNearClip; r *= mNearClip; t *= mNearClip; b *= mNearClip; //mLeftProjection = float4x4::Perspective(l, r, t, b, mNearClip, mFarClip); //Need to invert near/far. dont ask me why this works mLeftProjection = ConvertMat44(mSystem->GetProjectionMatrix(vr::Eye_Right, -mNearClip, -mFarClip)); mLeftProjection[1][1] = -mLeftProjection[1][1]; mLeftProjection[2][2] = -mLeftProjection[2][2]; mLeftProjection[3][2] = -mLeftProjection[3][2]; mLeftProjection[2][3] = -mLeftProjection[2][3]; mSystem->GetProjectionRaw(vr::Eye_Right, &l, &r, &t, &b); l *= mNearClip; r *= mNearClip; t *= mNearClip; b *= mNearClip; //mRightProjection = float4x4::Perspective(l, r, t, b, mNearClip, mFarClip); mRightProjection = ConvertMat44(mSystem->GetProjectionMatrix(vr::Eye_Right, -mNearClip, -mFarClip)); mRightProjection[1][1] = -mRightProjection[1][1]; mRightProjection[2][2] = -mRightProjection[2][2]; mRightProjection[3][2] = -mRightProjection[3][2]; mRightProjection[2][3] = -mRightProjection[2][3]; } //Extension getters taken from https://github.com/ValveSoftware/openvr/blob/master/samples/hellovr_vulkan/hellovr_vulkan_main.cpp #pragma region Extensions bool OpenVRDevice::GetVulkanInstanceExtensionsRequired(std::vector< std::string >& outInstanceExtensionList) { if (!vr::VRCompositor()) { return false; } outInstanceExtensionList.clear(); uint32_t nBufferSize = vr::VRCompositor()->GetVulkanInstanceExtensionsRequired(nullptr, 0); if (nBufferSize > 0) { // Allocate memory for the space separated list and query for it char* pExtensionStr = new char[nBufferSize]; pExtensionStr[0] = 0; vr::VRCompositor()->GetVulkanInstanceExtensionsRequired(pExtensionStr, nBufferSize); // Break up the space separated list into entries on the CUtlStringList std::string curExtStr; uint32_t nIndex = 0; while (pExtensionStr[nIndex] != 0 && (nIndex < nBufferSize)) { if (pExtensionStr[nIndex] == ' ') { outInstanceExtensionList.push_back(curExtStr); curExtStr.clear(); } else { curExtStr += pExtensionStr[nIndex]; } nIndex++; } if (curExtStr.size() > 0) { outInstanceExtensionList.push_back(curExtStr); } delete[] pExtensionStr; } return true; } bool OpenVRDevice::GetVulkanDeviceExtensionsRequired(VkPhysicalDevice pPhysicalDevice, std::vector< std::string >& outDeviceExtensionList) { if (!vr::VRCompositor()) { return false; } outDeviceExtensionList.clear(); uint32_t nBufferSize = vr::VRCompositor()->GetVulkanDeviceExtensionsRequired((VkPhysicalDevice_T*)pPhysicalDevice, nullptr, 0); if (nBufferSize > 0) { // Allocate memory for the space separated list and query for it char* pExtensionStr = new char[nBufferSize]; pExtensionStr[0] = 0; vr::VRCompositor()->GetVulkanDeviceExtensionsRequired((VkPhysicalDevice_T*)pPhysicalDevice, pExtensionStr, nBufferSize); // Break up the space separated list into entries on the CUtlStringList std::string curExtStr; uint32_t nIndex = 0; while (pExtensionStr[nIndex] != 0 && (nIndex < nBufferSize)) { if (pExtensionStr[nIndex] == ' ') { outDeviceExtensionList.push_back(curExtStr); curExtStr.clear(); } else { curExtStr += pExtensionStr[nIndex]; } nIndex++; } if (curExtStr.size() > 0) { outDeviceExtensionList.push_back(curExtStr); } delete[] pExtensionStr; } return true; } #pragma endregion
33.933649
196
0.729469
[ "render", "vector", "model" ]
2d44c3275dd490d4218f2a0329c950f50353f7e8
924
cpp
C++
Unterricht/W8/QuickHerzig.cpp
streusselhirni/hfict-aad
a9ddbf306ba36bb9299021f102281cd1e2824f45
[ "MIT" ]
null
null
null
Unterricht/W8/QuickHerzig.cpp
streusselhirni/hfict-aad
a9ddbf306ba36bb9299021f102281cd1e2824f45
[ "MIT" ]
null
null
null
Unterricht/W8/QuickHerzig.cpp
streusselhirni/hfict-aad
a9ddbf306ba36bb9299021f102281cd1e2824f45
[ "MIT" ]
null
null
null
// // Created by Nicolas Haenni on 20.10.18. // #include "QuickHerzig.h" void QuickHerzig::sort(std::vector<int> &v) { // abort if (v.size() <= 1) return; //int pivot = v.at(v.size()-1); int pivotpos = rand() % v.size(); int tmp = v.at(pivotpos); v[pivotpos] = v.at(v.size() - 1); v[v.size() - 1] = tmp; int pivot = v.at(v.size() - 1); // divide & conquer std::vector<int> left; std::vector<int> right; for (int i = 0; i < v.size() - 1; i++) { if (v.at(i) < pivot) { left.push_back(v.at(i)); } else { right.push_back(v.at(i)); } } sort(left); sort(right); // merge for (int i = 0; i < left.size(); i++) { v[i] = left.at(i); } v[left.size()] = pivot; for (int i = 0; i < right.size(); i++) { v[left.size() + i + 1] = right.at(i); } }
22.536585
52
0.445887
[ "vector" ]
2d48787bd6ab476cdf3e534e0872743276675f3f
19,639
cpp
C++
zide/zide.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
zide/zide.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
zide/zide.cpp
MasterZean/z2c-compiler-cpp
20ceae268b2197439a4d0ff68e317d6d443c7840
[ "Apache-2.0" ]
null
null
null
#include "zide.h" #include <z2clib/Source.h> #include <z2clib/Scanner.h> #include <z2clibex/Compiler.h> #include <z2clibex/ExprParser.h> ZPackage pak; //#include <Theme/Theme.h> void OutlineThread(Zide* zide, const String& data, uint64 hash) { try { ZSource* source = new ZSource(); source->Package = &pak; pak.Path = zide->lastPackage; source->Data = data; source->AddStdClassRefs(); bool win = false; #ifdef PLATFORM_WIN32 win = true; #endif Scanner scanner(*source, win); scanner.Scan(); PostCallback(callback2(zide, &Zide::NavigationDone, source, hash)); } catch (...) { } } void CreateZSyntax(One<EditorSyntax>& e, int kind) { CSyntax& s = e.Create<CSyntax>(); s.SetHighlight(kind); } Zide::Zide() { toolbar_in_row = false; optimize = 0; libMode = false; running = false; CtrlLayout(*this, "ZIDE"); Sizeable().Zoomable().Icon(ZImg::icon()); int r = HorzLayoutZoom(100); int l = HorzLayoutZoom(250); mnuMain.Transparent(); if (toolbar_in_row) { tlbMain.SetFrame(NullFrame()); int tcy = tlbMain.GetStdHeight() + 1; bararea.Add(mnuMain.LeftPos(0, l).VCenterPos(mnuMain.GetStdHeight())); bararea.Add(tlbMain.HSizePos(l, r).VCenterPos(tcy)); bararea.Add(lblLine.RightPos(4, r).VSizePos(2, 3)); lblLine.AddFrame(ThinInsetFrame()); bararea.Height(max(mnuMain.GetStdHeight(), tcy)); AddFrame(bararea); tlbMain.Transparent(); AddFrame(TopSeparatorFrame()); } else { bararea.Add(mnuMain.LeftPos(0, l).VCenterPos(mnuMain.GetStdHeight())); bararea.Add(lblLine.RightPos(4, r).VSizePos(2, 3)); lblLine.AddFrame(ThinInsetFrame()); bararea.Height(mnuMain.GetStdHeight()); AddFrame(bararea); AddFrame(TopSeparatorFrame()); AddFrame(tlbMain); tlbMain.NoTransparent(); } mnuMain.Set(THISBACK(DoMainMenu)); tlbMain.Set(THISBACK(MainToolbar)); Add(splMain); splMain.Horz(asbAss, canvas); splMain.SetPos(1750); canvas.Add(tabs); tabs.SizePos(); console.Height(150); CtrlLayout(explore); explore.lstItems.SetDisplay(Single<ItemDisplay>()); explore.lstItems.RenderMultiRoot(); explore.lstItems.NoRoot(); explore.lstItems.WhenAction = THISBACK(OnExplorerClick); explore.lstItems.Set(0, "aa", RawToValue(ZItem())); explore.lstItems.NoWantFocus(); explore.lstItems.WhenBar = THISBACK(OnExplorerMenu); canvas.AddFrame(splBottom.Bottom(console, 150)); canvas.AddFrame(splOutput.Right(tabs2, 400)); tabs.AddFrame(splExplore.Left(explore, 200)); splOutput.Hide(); explore.AddFrame(LeftSeparatorFrame()); splBottom.Hide(); console.WhenLeft = THISBACK(OnOutputSel); asbAss.WhenSelectSource = THISBACK(OnSelectSource); asbAss.WhenFileRemoved = THISBACK(OnFileRemoved); asbAss.WhenFileSaved = THISBACK(OnFileSaved); asbAss.WhenRenameFiles = THISBACK(OnRenameFiles); WhenClose = THISBACK(OnClose); tabs.WhenEditorCursor = THISBACK(OnEditCursor); tabs.WhenEditorChange = THISBACK(OnEditChange); tabs.WhenTabChange = THISBACK(OnTabChange); tabs.WhenAnnotation = THISBACK(OnAnnotation); tabs.WhenPopup = THISBACK(OnAcDot); lblLine.SetAlign(ALIGN_CENTER); edtDummy.Enable(false); tabs.tabFiles.Hide(); editThread = true; pauseExplorer = false; colors.Add(HighlightSetup::INK_NORMAL); colors.Add(HighlightSetup::PAPER_NORMAL); colors.Add(11); colors.Add(12); colors.Add(13); colors.Add(9); colors.Add(25); colors.Add(20); colors.Add(22); colors.Add(23); colors.Add(24); colors.Add(21); colors.Add(10); colors.Add(2); colors.Add(3); colors.Add(6); colors.Add(7); colors.Add(8); colors.Add(15); colors.Add(16); colors.Add(17); colors.Add(18); colors.Add(19); colors.Add(28); colors.Add(29); colors.Add(30); colors.Add(31); lstBldConf.Add("Default"); lstBldConf.Tip("Select build configuration"); lstBldConf.SetIndex(0); lstBldConf.NoDropFocus(); lstBldConf.NoWantFocus(); mbtBldMode.NoWantFocus(); mbtBldMode.Tip("Build mode"); mbtBldMode.AddButton().Tip("Build method").Left() <<= THISBACK(DropMethodList); mbtBldMode.AddButton().Tip("Build type") <<= THISBACK(DropTypeList); mbtBldMode.AddButton().Tip("Build architecture") <<= THISBACK(DropArchList); mbtEntryPoint.NoWantFocus(); mbtEntryPoint.Tip("Current entry point"); mbtEntryPoint.Set("* File in editor"); mbtEntryPoint.AddButton().Tip("Set entry point").SetImage(ZImg::dots) <<= Callback()/*THISBACK(DropTypeList)*/; popMethodList.Normal(); popMethodList.WhenSelect = THISBACK(OnSelectMethod); String curDir = GetFileDirectory(GetExeFilePath()); //NativePath(GetCurrentDirectory() + "\\"); LoadFromXMLFile(methods, curDir + "buildMethods.xml"); if (methods.GetCount() == 0) { methods.Clear(); Cout() << "No cached build method found! Trying to auto-detect...\n"; BuildMethod::Get(methods); if (methods.GetCount() == 0) { PromptOK("Could not find any build methods. Building is dissabled!"); canBuild = false; } StoreAsXMLFile(methods, "methods", curDir + "buildMethods.xml"); } Index<String> met; for (int i = 0; i < methods.GetCount(); i++) met.FindAdd(methods[i].Name); for (int i = 0; i < met.GetCount(); i++) popMethodList.Add(met[i]); popTypeList.Normal(); popTypeList.WhenSelect = THISBACK(OnSelectMethod); popTypeList.Add("Debug"); popTypeList.Add("Speed"); popTypeList.Add("Size"); popTypeList.SetCursor(1); popArchList.Normal(); popArchList.WhenSelect = THISBACK(OnSelectMethod); annotation_popup.Background(White); annotation_popup.SetFrame(BlackFrame()); annotation_popup.Margins(Zx(6)); annotation_popup.NoSb(); docPath = GetFileDirectory(GetExeFilePath()); docPath << "docs\\pak\\"; docPath = NativePath(docPath); RealizePath(docPath); } void Zide::OnAcDot() { int i = tabs.tabFiles.GetCursor(); if (i == -1) return; String file = tabs.tabFiles[i].key.ToString(); SmartEditor& editor = GetEditor(); if (!editor.IsEnabled()) return; ExprParser::Initialize(); Assembly ass; Compiler comp(ass); AST ast(ass); CppNodeWalker cpp(ass, NilStream()); comp.BringUp(ast, NilStream(), cpp); try { comp.Cache = &asbAss.Cache; for (int i = 0; i < packages.GetCount(); i++) comp.AddPackage(packages[i], false); ZSource* src = comp.FindSource(file); if (src == nullptr) return; comp.UpdateSource(*src, editor.Get()); comp.LookUp.Clear(); comp.Populate(true); comp.CompileClass(); comp.CompileCompiler(); comp.CompileString(); comp.CompileIntrinsic(); Point p = editor.Anchor; if (p.x > 0) { p.x++; p.y++; Swap(p.x, p.y); comp.DoAC(*src, p); } } catch (ZSyntaxError& exc) { /*StringStream ss; exc.PrettyPrint(comp.context, ss); splBottom.Show(); console.Set(ss.GetResult()); console.ScrollEnd(); console.ScrollLineUp();*/ } editor.words.Clear(); for (int i = 0; i < comp.AutoComplete.GetCount(); i++) editor.words.Add(comp.AutoComplete[i]); } void Zide::DropMethodList() { popMethodList.PopUp(&mbtBldMode); } void Zide::DropTypeList() { popTypeList.PopUp(&mbtBldMode); } void Zide::DropArchList() { popArchList.PopUp(&mbtBldMode); } void Zide::OnSelectMethod() { String s; if (popMethodList.GetCursor() == -1) for (int i = 0; i < popMethodList.GetCount(); i++) if (popMethodList.Get(i, 0) == method) { popMethodList.SetCursor(i); break; } if (popMethodList.GetCursor() == -1 && popMethodList.GetCount()) popMethodList.SetCursor(0); if (popMethodList.GetCursor() != -1) { method = popMethodList.Get(popMethodList.GetCursor(), 0); s << method; } Index<String> archs; int index = -1; bool x86 = false, x64 = false; for (int i = 0; i < methods.GetCount(); i++) { if (methods[i].Name == method) { archs.FindAdd(methods[i].Arch); index = i; } } String oldArch; if (popArchList.GetCursor() != -1) oldArch = popArchList.Get(popArchList.GetCursor(), 0); if (oldArch.GetCount() == 0) oldArch = arch; popArchList.Clear(); if (index!= -1) { for (int i = 0; i < archs.GetCount(); i++) { popArchList.Add(archs[i]); if (oldArch.GetCount() && oldArch == archs[i]) popArchList.SetCursor(popArchList.GetCount() - 1); } } if (popArchList.GetCursor() == -1 && popArchList.GetCount()) popArchList.SetCursor(0); if (popArchList.GetCursor() != -1) { if (!s.IsEmpty()) s << " "; arch = popArchList.Get(popArchList.GetCursor(), 0); s << arch; } else arch = ""; int c = popTypeList.GetCursor(); if (c != -1) { if (!s.IsEmpty()) s << " "; s << popTypeList.Get(c, 0); if (c == 0) OnToolO0(); else if (c == 2) OnToolO1(); else if (c == 1) OnToolO2(); } mbtBldMode.Set(s); } void Zide::ReadHlStyles(ArrayCtrl& hlstyle) { CodeEditor& editor = GetEditor(); hlstyle.Clear(); for(int i = 0; i < colors.GetCount(); i++) { const HlStyle& s = editor.GetHlStyle(colors[i]); hlstyle.Add(editor.GetHlName(colors[i]), s.color, s.bold, s.italic, s.underline); } } void Zide::OnClose() { while (Thread::GetCount()) { Sleep(10); } if (tabs.PromptSaves()) Close(); } void Zide::OnFileRemoved(const String& file) { tabs.RemoveFile(file); mnuMain.Set(THISBACK(DoMainMenu)); } void Zide::OnExplorerClick() { if (pauseExplorer) return; int i = explore.lstItems.GetCursor(); if (i == -1) return; CodeEditor& editor = GetEditor(); Point p = ValueTo<ZItem>(explore.lstItems.GetValue(i)).Pos; editThread = false; editor.SetCursor(editor.GetGPos(p.x - 1, p.y - 1)); editor.SetFocus(); editThread = true; } void Zide::OnExplorerMenu(Bar& bar) { int i = explore.lstItems.GetCursor(); if (i == -1) return; ZItem zi = ValueTo<ZItem>(explore.lstItems.GetValue(i)); if (zi.Kind == 1 || zi.Kind == 2) bar.Add("Generate documentation template", THISBACK(OnGenerateDocTemp)); } void Zide::OnFileSaved(const String& file) { int i = tabs.tabFiles.FindKey(file); if (i != -1) tabs.Save(i); } bool Zide::OnRenameFiles(const Vector<String>& files, const String& oldPath, const String& newPath) { for (int i = 0; i < files.GetCount(); i++) { int j = tabs.tabFiles.FindKey(files[i].ToWString()); if (j != -1) { if (tabs.IsChanged(j)) { tabs.Save(j); } } } if (FileMove(oldPath, newPath)) for (int i = 0; i < files.GetCount(); i++) { int j = tabs.tabFiles.FindKey(files[i].ToWString()); if (j != -1) { ASSERT(files[i].StartsWith(oldPath)); String np = newPath + files[i].Mid(oldPath.GetLength()); WString w1 = tabs.tabFiles.GetKey(j); WString w2 = np.ToWString(); int k = tabs.files.Find(w1); ASSERT(k != -1); OpenFileInfo* info = tabs.files.Detach(k); tabs.files.Add(w2); tabs.files.Set(tabs.files.GetCount() - 1, info); DUMP(w1); DUMP(w2); tabs.tabFiles.RenameFile(w1, w2, ZImg::zsrc); } } return true; } SmartEditor& Zide::GetEditor() { int i = tabs.tabFiles.GetCursor(); if (i == -1) return edtDummy; WString file = tabs.tabFiles[i].key; int j = tabs.files.Find(file); if (j == -1) return edtDummy; return tabs.files[j].editor; } OpenFileInfo* Zide::GetInfo() { int i = tabs.tabFiles.GetCursor(); if (i == -1) return nullptr; WString file = tabs.tabFiles[i].key; int j = tabs.files.Find(file); if (j == -1) return nullptr; return &tabs.files[j]; } String Zide::Build(const String& file, bool scu, bool& res, Point p) { String cmd = zcPath; if (cmd.GetCount() == 0) cmd = BuildMethod::Exe("z2c"); cmd << " -"; if (scu) cmd << "scu "; else cmd << "c++ "; cmd << "-file " << file << " "; cmd << "-pak " << lastPackage << " "; if (optimize == 2) cmd << " -O2"; else if (optimize == 1) cmd << " -O1"; else if (optimize == 0) cmd << " -Od"; if (libMode) cmd << " -lib"; if (popMethodList.GetCursor() != -1) cmd << " -bm " << popMethodList.Get(popMethodList.GetCursor(), 0); cmd << " -arch " << arch; if (p.x > 0) cmd << " -acp " << p.x << " " << p.y; DUMP(cmd); String t, tt; LocalProcess lp(cmd); while (lp.Read(t)) { if (t.GetCount()) tt << t; } res = BuildMethod::IsSuccessCode(lp.GetExitCode()); if (res == false && tt.GetCount() == 0) { DUMP(tt); cmd = GetFileDirectory(GetExeFilePath()) + BuildMethod::Exe("z2c"); if (!FileExists(cmd)) tt = "Could not find: " + cmd; } return tt; } void Zide::AddOutputLine(const String& str) { console << str; console.ScrollEnd(); } bool Zide::IsVerbose() const { return console.verbosebuild; } void Zide::PutConsole(const char *s) { console << s << "\n"; } void Zide::PutVerbose(const char *s) { if(console.verbosebuild) { PutConsole(s); console.Sync(); } } void Zide::OutPutEnd() { console.ScrollLineUp(); console.ScrollLineUp(); Title("ZIDE - Execution done in " + sw.ToString() + " sec."); running = false; } void Zide::OnEditChange() { DUMP("Change"); OpenFileInfo* info = GetInfo(); if (!info) return; SmartEditor& editor = info->editor; if (!editor.IsEnabled()) return; info->Hash++; if (editThread) Thread().Run(callback3(OutlineThread, this, editor.Get(), info->Hash)); } void Zide::OnEditCursor() { OpenFileInfo* info = GetInfo(); if (!info) return; CodeEditor& editor = info->editor; if (!editor.IsEnabled()) return; Point p = editor.GetColumnLine(editor.GetCursor()); lblLine.SetText(String().Cat() << "Ln " << (p.y + 1) << ", Cl " << (p.x + 1)); } void Zide::NavigationDone(ZSource* source, uint64 hash) { OpenFileInfo* info = GetInfo(); if (!info) return; if (info->Hash == hash) LoadNavigation(*source); delete source; } void Zide::OnTabChange() { int i = tabs.GetCursor(); if (i == -1) return; openFile = tabs.tabFiles[i].key; i = asbAss.treModules.Find(tabs.tabFiles[i].key); if (i != -1) { asbAss.treModules.SetCursor(i); } tabs.tabFiles.Show(tabs.tabFiles.GetCount()); splExplore.Show(tabs.tabFiles.GetCount()); } void Zide::OnOutputSel() { if (console.GetSelection().GetLength() != 0) return; Point p = console.GetColumnLine(console.GetCursor()); for (int i = 0; i < 5; i++) { if (p.y >= 0 && GetLineOfError(p.y)) return; p.y--; } } bool Zide::GetLineOfError(int ln) { String line = console.GetUtf8Line(ln); //#ifdef PLATFORM_WIN32 int s = line.Find("("); int e = line.Find(")"); //#endif /*#ifdef PLATFORM_POSIX int s = line.Find(":"); int e = line.Find(": error: "); #endif*/ if (s > -1 && s < e) { String file = line.Left(s); if (FileExists(file)) { tabs.Open(file); String rest = line.Mid(s + 1, e - s - 1); Vector<String> v = Split(rest, ","); if (v.GetCount() == 2) { int x = StrInt(TrimBoth(v[0])) - 1; int y = StrInt(TrimBoth(v[1])) - 1; CodeEditor& editor = GetEditor(); if (!editor.IsEnabled()) return false; editor.SetCursor(editor.GetGPos(x, y)); editor.SetFocus(); return true; } else if (v.GetCount() == 1) { int x = StrInt(TrimBoth(v[0])) - 1; CodeEditor& editor = GetEditor(); if (!editor.IsEnabled()) return false; editor.SetCursor(editor.GetGPos(x, 1)); editor.SetFocus(); return true; } return false; } } return false; } void Zide::OnGoTo() { CodeEditor& editor = GetEditor(); if (!editor.IsEnabled()) return; static int line = 1; if (EditNumber(line, "Go to line numer", "Line:")) { editor.GotoLine(line - 1); editor.SetFocus(); } } void Zide::OnSelectSource() { openFile = asbAss.GetItem(); DUMP(openFile); tabs.Open(openFile); mnuMain.Set(THISBACK(DoMainMenu)); } void Zide::Load(Vector<String>& list, int id) { for (int i = 0; i < asbAss.treModules.GetChildCount(id); i++) { int ch = asbAss.treModules.GetChild(id, i); if (asbAss.treModules.IsOpen(ch)) { String s = asbAss.treModules.GetNode(ch).key; list.Add(s); } Load(list, ch); } } void Zide::Serialize(Stream& s) { int version = 1; s / version; if (s.IsLoading()) { bool b; int w = 0; int h = 0; s % b % w % h; if (b) Maximize(b); else HCenterPos(w, 0).VCenterPos(h, 0); int split; s % split; splMain.SetPos(split); s % split; splExplore.SetSize(split); s % split; splBottom.SetSize(split); } else { bool b = IsMaximized(); int w = GetSize().cx; int h = GetSize().cy; s % b % w % h; int split = splMain.GetPos(); s % split; split = splExplore.GetSize(); s % split; split = splBottom.GetSize(); s % split; } s % openFile; s % lastPackage % openNodes % optimize % libMode % openDialogPreselect % recent; s % settings % method % arch % oShowPakPaths; } void Zide::LoadModule(const String& mod, int color) { asbAss.AddModule(NativePath(mod), color); } void Zide::SetupLast() { for (int i = 0; i < openNodes.GetCount(); i++) { int n = asbAss.treModules.Find(openNodes[i]); if (n != -1) asbAss.treModules.Open(n); } int n = asbAss.treModules.Find(openFile); if (n != -1) asbAss.treModules.SetCursor(n); tabs.tabFiles.Show(tabs.tabFiles.GetCount()); splExplore.Show(tabs.tabFiles.GetCount()); tabs.SetSettings(settings); tabs.tabFiles.SetAlign(settings.TabPos); tabs.tabFiles.Crosses(settings.TabClose >= 0, settings.TabClose); tlbMain.Set(THISBACK(MainToolbar)); mnuMain.Set(THISBACK(DoMainMenu)); int ii = popMethodList.Find(method); if (ii != -1) { popMethodList.SetCursor(ii); OnSelectMethod(); } asbAss.SetShowPaths(oShowPakPaths); } void Zide::LoadPackage(const String& package) { if (package.GetCount() == 0) return; #ifdef PLATFORM_WIN32 String platform = "WIN32"; String platformLib = "microsoft.windows"; #endif #ifdef PLATFORM_POSIX String platform = "POSIX"; String platformLib = "ieee.posix"; #endif lastPackage = package; asbAss.ClearModules(); packages << lastPackage; LoadModule(lastPackage, 0); String s = GetFileDirectory(GetExeFilePath()); String pak = NativePath(s + "source/stdlib/sys.core"); if (DirectoryExists(pak)) { packages << pak; LoadModule(pak, 1); } pak = NativePath(s + "source/stdlib/bind.c"); if (DirectoryExists(pak)) { packages << pak; LoadModule(pak, 1); } pak = NativePath(s + "source/stdlib/" + platformLib); if (DirectoryExists(pak)) { packages << pak; LoadModule(pak, 2); } openNodes.Add(lastPackage); SetupLast(); int i = recent.Find(lastPackage); if (i == -1) recent.Insert(0, lastPackage); else { recent.Remove(i); recent.Insert(0, lastPackage); } } GUI_APP_MAIN { SetLanguage(LNG_ENGLISH); SetDefaultCharset(CHARSET_UTF8); /*SColorPaper_Write(Color(51, 51, 51)); SColorFace_Write(Color(33, 37, 43)); SColorText_Write(Color(255, 251, 247)); SColorMenu_Write(Color(40, 44, 52)); SColorLabel_Write(Color(207, 210, 216)); SColorLtFace_Write(Color(51, 51, 51)); SColorInfo_Write(Color(255, 251, 247)); SColorInfoText_Write(Color(255, 251, 247)); SColorShadow_Write(Color(24, 26, 31)); SColorLight_Write(Color(157, 165, 179));*/ /*Theme theme; theme.Load("c:\\Dev\\upp\\bazaar\\Themes\\Skulpture.zip"); theme.Apply();*/ EditorSyntax::Register("z2", callback1(CreateZSyntax, CSyntax::HIGHLIGHT_Z2), "*.z2", "Z2 Source Files"); Ctrl::SetAppName("ZIDE"); Zide zide; String zz; String curDir = GetFileDirectory(GetExeFilePath()); FindFile ff(curDir + "/" + BuildMethod::Exe("z2c")); if (ff.IsExecutable()) zide.zcPath = ff.GetPath(); if (!LoadFromFile(zide)) { String s = curDir + "source/ut/org.z2legacy.ut"; s = NativePath(s); if (DirectoryExists(s)) { zide.lastPackage = s; zide.openNodes.Add(s); zide.recent.Add(s); zz = s + "/Hello.z2"; zide.openFile = NativePath(zz); } } zide.tabs.SetSettings(zide.settings); zide.OnSelectMethod(); zide.LoadPackage(zide.lastPackage); zide.Run(); StoreToFile(zide); }
22.165914
112
0.652528
[ "vector" ]
2d4b6216dbf6fc0fb55a5ecd292cb0d296d21f97
3,986
cpp
C++
Warcraft II/Warcraft II/GryphonAviary.cpp
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
9
2019-07-02T06:24:03.000Z
2022-03-18T20:07:02.000Z
Warcraft II/Warcraft II/GryphonAviary.cpp
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
109
2018-02-21T23:40:29.000Z
2020-04-25T18:26:41.000Z
Warcraft II/Warcraft II/GryphonAviary.cpp
DevCrumbs/Warcraft-II
fd4fab4c629783d6acc18c34bdaac15fcfb54dd1
[ "MIT" ]
6
2018-06-27T07:30:10.000Z
2020-03-09T19:18:41.000Z
#include "Defs.h" #include "p2Log.h" #include "GryphonAviary.h" #include "j1Player.h" #include "j1Scene.h" #include "j1Pathfinding.h" #include "j1Map.h" #include "j1Movement.h" #include "j1Collision.h" #include "j1Particles.h" #include "j1FadeToBlack.h" GryphonAviary::GryphonAviary(fPoint pos, iPoint size, int currLife, uint maxLife, const GryphonAviaryInfo& gryphonAviaryInfo, j1Module* listener) :StaticEntity(pos, size, currLife, maxLife, listener), gryphonAviaryInfo(gryphonAviaryInfo) { *(ENTITY_CATEGORY*)&entityType = EntityCategory_STATIC_ENTITY; *(StaticEntityCategory*)&staticEntityCategory = StaticEntityCategory_HumanBuilding; *(ENTITY_TYPE*)&staticEntityType = EntityType_GRYPHON_AVIARY; *(EntitySide*)&entitySide = EntitySide_Player; *(StaticEntitySize*)&buildingSize = StaticEntitySize_Medium; // Update the walkability map (invalidate the tiles of the building placed) vector<iPoint> walkability; iPoint buildingTile = App->map->WorldToMap(pos.x, pos.y); walkability.push_back({ buildingTile.x, buildingTile.y }); App->scene->data[App->scene->w * buildingTile.y + buildingTile.x] = 0u; walkability.push_back({ buildingTile.x, buildingTile.y }); App->scene->data[App->scene->w * buildingTile.y + (buildingTile.x + 1)] = 0u; walkability.push_back({ buildingTile.x + 1, buildingTile.y }); App->scene->data[App->scene->w * (buildingTile.y + 1) + buildingTile.x] = 0u; walkability.push_back({ buildingTile.x, buildingTile.y + 1 }); App->scene->data[App->scene->w * (buildingTile.y + 1) + (buildingTile.x + 1)] = 0u; walkability.push_back({ buildingTile.x + 1, buildingTile.y + 1 }); App->scene->data[App->scene->w * (buildingTile.y) + (buildingTile.x + 2)] = 0u; walkability.push_back({ buildingTile.x + 2, buildingTile.y }); App->scene->data[App->scene->w * (buildingTile.y + 2) + buildingTile.x] = 0u; walkability.push_back({ buildingTile.x, buildingTile.y + 2 }); App->scene->data[App->scene->w * (buildingTile.y + 2) + (buildingTile.x + 1)] = 0u; walkability.push_back({ buildingTile.x + 1, buildingTile.y + 2 }); App->scene->data[App->scene->w * (buildingTile.y + 2) + (buildingTile.x + 2)] = 0u; walkability.push_back({ buildingTile.x + 2, buildingTile.y + 2 }); App->scene->data[App->scene->w * (buildingTile.y + 1) + (buildingTile.x + 2)] = 0u; walkability.push_back({ buildingTile.x + 2, buildingTile.y + 1 }); App->movement->UpdateUnitsWalkability(walkability); // ----- texArea = &gryphonAviaryInfo.constructionPlanks1; buildingState = BuildingState_Building; // Collision CreateEntityCollider(EntitySide_Player, true); entityCollider->isTrigger = true; } GryphonAviary::~GryphonAviary() { if (peasants != nullptr) { peasants->isRemove = true; peasants = nullptr; } } void GryphonAviary::Move(float dt) { if (!isCheckedBuildingState && !App->fade->IsFading()) { CheckBuildingState(); isCheckedBuildingState = true; if (!isBuilt) { //Construction peasants App->audio->PlayFx(App->audio->GetFX().buildingConstruction, 0); //Construction sound peasants = App->particles->AddParticle(App->particles->peasantMediumBuild, { (int)pos.x - 30,(int)pos.y - 30 }); } else if(isBuilt) texArea = &gryphonAviaryInfo.completeTexArea; } if (listener != nullptr) HandleInput(EntityEvent); if (!isBuilt) { constructionTimer += dt; UpdateAnimations(dt); } if (constructionTimer >= constructionTime && !isBuilt) { isBuilt = true; if (peasants != nullptr) { peasants->isRemove = true; peasants = nullptr; } } } // Animations void GryphonAviary::LoadAnimationsSpeed() { } void GryphonAviary::UpdateAnimations(float dt) { if (constructionTimer >= (constructionTime / 3)) texArea = &gryphonAviaryInfo.constructionPlanks2; if (constructionTimer >= (constructionTime / 3 * 2)) texArea = &gryphonAviaryInfo.inProgressTexArea; if (constructionTimer >= constructionTime || isBuilt) { texArea = &gryphonAviaryInfo.completeTexArea; buildingState = BuildingState_Normal; } }
34.362069
237
0.718264
[ "vector" ]
2d5182494ffd1dedf54432f3bc41a94abe90a77b
1,797
cpp
C++
emerald/sph2d_box/tests/test_parallel_scan.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
3
2020-08-16T17:56:25.000Z
2021-02-25T21:55:39.000Z
emerald/sph2d_box/tests/test_parallel_scan.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
emerald/sph2d_box/tests/test_parallel_scan.cpp
blackencino/emerald
3c4823dbdeff7c63007ff359d262608227f5433f
[ "Apache-2.0" ]
null
null
null
#pragma warning(push) #pragma warning(disable : 4244) #include <tbb/blocked_range.h> #include <tbb/parallel_scan.h> #pragma warning(pop) #include <gtest/gtest.h> #include <cstdint> #include <numeric> #include <vector> namespace emerald::sph2d_box { uint64_t do_parallel_scan(size_t const size, uint64_t* const result, uint32_t const* const input) { return tbb::parallel_scan( tbb::blocked_range<size_t>{size_t{0}, size}, 0, [result, input](tbb::blocked_range<size_t> const& range, uint64_t const sum, bool const is_final_scan) { uint64_t temp = sum; for (auto i = range.begin(); i != range.end(); ++i) { temp += input[i]; if (is_final_scan) { result[i] = temp; } } return temp; }, [](uint64_t const left, uint64_t const right) { return left + right; }); } TEST(Sph2d_box_test, test_parallel_scan) { std::vector<uint32_t> values; std::vector<uint64_t> expected_results; std::vector<uint64_t> results; size_t const count = 54201; values.resize(count); expected_results.resize(count); results.resize(count); std::iota(values.begin(), values.end(), 1); EXPECT_EQ(1, values.front()); EXPECT_EQ(count, values.back()); size_t const expected_sum = (count * (1 + count)) / 2; size_t sum = 0; for (size_t i = 0; i < count; ++i) { sum += values[i]; expected_results[i] = sum; } EXPECT_EQ(expected_sum, sum); auto const parallel_sum = do_parallel_scan(count, results.data(), values.data()); EXPECT_EQ(expected_sum, parallel_sum); EXPECT_EQ(expected_results, results); } } // namespace emerald::sph2d_box
27.646154
78
0.605454
[ "vector" ]