Leg(std::shared_ptr<geogo::Mesh> _geometry, const glm::vec3& foot_pos) : geometry(_geometry), default_foot_pos_local(foot_pos), default_hip_pos_local(0.1f * foot_pos) { foot_vertex = geometry->create_vertex(); hip_vertex = geometry->create_vertex(); geometry->create_edge(hip_vertex, foot_vertex); }
// ----------------------------------------------------------------------------- // ----------------------------------------------------------------------------- void ChTrackShoeBandBushing::Connect(std::shared_ptr<ChTrackShoe> next) { // Bushings are inherited from ChLoad, so they require a 'load container' auto loadcontainer = std::make_shared<ChLoadContainer>(); m_shoe->GetSystem()->Add(loadcontainer); // Stiffness and Damping matrix values ChMatrixNM<double, 6, 6> K_matrix; ChMatrixNM<double, 6, 6> R_matrix; K_matrix(0, 0) = m_Klin; K_matrix(1, 1) = m_Klin; K_matrix(2, 2) = m_Klin; K_matrix(3, 3) = m_Krot_other; K_matrix(4, 4) = m_Krot_dof; K_matrix(5, 5) = m_Krot_other; R_matrix(0, 0) = m_Dlin; R_matrix(1, 1) = m_Dlin; R_matrix(2, 2) = m_Dlin; R_matrix(3, 3) = m_Drot_other; R_matrix(4, 4) = m_Drot_dof; R_matrix(5, 5) = m_Drot_other; int index = 0; // Connect tread body to the first web segment. { ChVector<> loc = m_shoe->TransformPointLocalToParent(ChVector<>(GetToothBaseLength() / 2, 0, 0)); ChQuaternion<>& rot = m_shoe->GetRot(); auto loadbushing = std::make_shared<ChLoadBodyBodyBushingGeneric>( m_shoe, // body A m_web_segments[0], // body B ChFrame<>(loc, rot), // initial frame of bushing in abs space K_matrix, // the 6x6 (translation+rotation) K matrix in local frame R_matrix // the 6x6 (translation+rotation) R matrix in local frame ); loadbushing->SetNameString(m_name + "_bushing_" + std::to_string(index++)); loadbushing->SetApplicationFrameA(ChFrame<>(ChVector<>(GetToothBaseLength() / 2, 0, 0))); loadbushing->SetApplicationFrameB(ChFrame<>(ChVector<>(-m_seg_length / 2, 0, 0))); loadcontainer->Add(loadbushing); m_web_bushings.push_back(loadbushing); } // Connect the web segments to each other. for (size_t is = 0; is < GetNumWebSegments() - 1; is++) { ChVector<> loc = m_web_segments[is]->TransformPointLocalToParent(ChVector<>(m_seg_length / 2, 0, 0)); ChQuaternion<>& rot = m_web_segments[is]->GetRot(); auto loadbushing = std::make_shared<ChLoadBodyBodyBushingGeneric>( m_web_segments[is], // body A m_web_segments[is + 1], // body B ChFrame<>(loc, rot), // initial frame of bushing in abs space K_matrix, // the 6x6 (translation+rotation) K matrix in local frame R_matrix // the 6x6 (translation+rotation) R matrix in local frame ); loadbushing->SetNameString(m_name + "_bushing_" + std::to_string(index++)); loadbushing->SetApplicationFrameA(ChFrame<>(ChVector<>(m_seg_length / 2, 0, 0))); loadbushing->SetApplicationFrameB(ChFrame<>(ChVector<>(-m_seg_length / 2, 0, 0))); loadcontainer->Add(loadbushing); m_web_bushings.push_back(loadbushing); } { // Connect the last web segment to the tread body from the next track shoe. int is = GetNumWebSegments() - 1; ChVector<> loc = m_web_segments[is]->TransformPointLocalToParent(ChVector<>(m_seg_length / 2, 0, 0)); ChQuaternion<>& rot = m_web_segments[is]->GetRot(); auto loadbushing = std::make_shared<ChLoadBodyBodyBushingGeneric>( m_web_segments[is], // body A next->GetShoeBody(), // body B ChFrame<>(loc, rot), // initial frame of bushing in abs space K_matrix, // the 6x6 (translation+rotation) K matrix in local frame R_matrix // the 6x6 (translation+rotation) R matrix in local frame ); loadbushing->SetNameString(m_name + "_bushing_" + std::to_string(index++)); loadbushing->SetApplicationFrameA(ChFrame<>(ChVector<>(m_seg_length / 2, 0, 0))); loadbushing->SetApplicationFrameB(ChFrame<>(ChVector<>(-GetToothBaseLength() / 2, 0, 0))); loadcontainer->Add(loadbushing); m_web_bushings.push_back(loadbushing); } }
shared_ptr<SwitchState> ThriftConfigApplier::run() { auto newState = orig_->clone(); bool changed = false; processVlanPorts(); { auto newPorts = updatePorts(); if (newPorts) { newState->resetPorts(std::move(newPorts)); changed = true; } } { auto newIntfs = updateInterfaces(); if (newIntfs) { newState->resetIntfs(std::move(newIntfs)); changed = true; } } // Note: updateInterfaces() must be called before updateVlans(), // as updateInterfaces() populates the vlanInterfaces_ data structure. { auto newVlans = updateVlans(); if (newVlans) { newState->resetVlans(std::move(newVlans)); changed = true; } } // Note: updateInterfaces() must be called before updateRouteTables(), // as updateInterfaces() populates the intfRouteTables_ data structure. { auto newTables = updateRouteTables(); if (newTables) { newState->resetRouteTables(std::move(newTables)); changed = true; } } // Make sure all interfaces refer to valid VLANs. auto newVlans = newState->getVlans(); for (const auto& vlanInfo : vlanInterfaces_) { if (newVlans->getVlanIf(vlanInfo.first) == nullptr) { throw FbossError("Interface ", *(vlanInfo.second.interfaces.begin()), " refers to non-existent VLAN ", vlanInfo.first); } } VlanID dfltVlan(cfg_->defaultVlan); if (orig_->getDefaultVlan() != dfltVlan) { if (newVlans->getVlanIf(dfltVlan) == nullptr) { throw FbossError("Default VLAN ", dfltVlan, " does not exist"); } newState->setDefaultVlan(dfltVlan); changed = true; } std::chrono::seconds arpAgerInterval(cfg_->arpAgerInterval); if (orig_->getArpAgerInterval() != arpAgerInterval) { newState->setArpAgerInterval(arpAgerInterval); changed = true; } if (!changed) { return nullptr; } return newState; }
// This callback is called when the scroll wheel is used void wheelCB(GLFWwindow* window, double xOffset, double yOffset) { gCamera->mouseWheelScrolled(int(yOffset)); }
// Publish Various Representations of the Depth Image: void Pass::sendSweepDepthImage(){ bool write_raw = false; bool publish_raw = true; bool publish_range_image = false; // a. Write raw depths to file if (write_raw){ cout << "Writing Raw Range Image Points to /tmp\n"; std::ofstream ofs("/tmp/sweep_depths.txt"); for (int i = 0; i < camera_params_.height; ++i) { for (int j = 0; j < camera_params_.width; ++j) { ofs << depth_buf_[i*camera_params_.width + j] << " "; } ofs << std::endl; } ofs.close(); } // b. Reproject the depth image into xyz, colourize, apply a mask and publish if (publish_raw){ cout << "Publishing Raw Range Image Points\n"; pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud4 (new pcl::PointCloud<pcl::PointXYZRGB> ()); int decimate=4; uint8_t* mask_buf = NULL; if (mask_init_){ mask_buf = imgutils_->unzipImage( &last_mask_ ); } for (int v = 0; v < camera_params_.height ; v=v+decimate) { // rows t2b //height for (int u = 0; u < camera_params_.width; u=u+decimate) { // cols l2r pcl::PointXYZRGB pt; int pixel = v*camera_params_.width +u; pt.z = 1/ depth_buf_[pixel]; /// inversion currently required due to Matt's interperation of depth as 1/depth ;) pt.x = ( pt.z * (u - camera_params_.cx ))/ camera_params_.fx ; pt.y = ( pt.z * (v - camera_params_.cy ))/ camera_params_.fy ; if (img_.pixelformat == bot_core::image_t::PIXEL_FORMAT_RGB){ pt.r = (float) img_.data[pixel*3]; pt.g = (float) img_.data[pixel*3+1]; pt.b = (float) img_.data[pixel*3+2]; }else if (img_.pixelformat == bot_core::image_t::PIXEL_FORMAT_GRAY){ pt.r = (float) img_.data[pixel]; pt.g = (float) img_.data[pixel]; pt.b = (float) img_.data[pixel]; } if (mask_init_){ // if we have a mask color the points by it if (mask_buf[pixel] > 0){ // if the mask is not 0 (black), apply it as red pt.r = 255; pt.g = 0; pt.b = 0; } } cloud4->points.push_back(pt); } } cloud4->width = cloud4->points.size(); cloud4->height =1; Isometry3dTime camera_pose_T = Isometry3dTime(current_utime_, camera_pose_); pc_vis_->pose_to_lcm_from_list(91004, camera_pose_T); pc_vis_->ptcld_to_lcm_from_list(91005, *cloud4, current_utime_, current_utime_); // pc_vis_->pointcloud2_to_lcm(*cloud4,"RANGE_IMAGE_POINTS",current_utime_); } if (publish_range_image){ std::cout << "Publishing Range image to LIDARSWEEP\n"; // c. publish in Depth Image mode: int n_bytes=2; // 2 bytes per value // different from before in driver int isize = n_bytes*camera_params_.width * camera_params_.height; disparity_.utime =img_.utime; disparity_.width = camera_params_.width; disparity_.height = camera_params_.height; disparity_.pixelformat =bot_core::image_t::PIXEL_FORMAT_GRAY; //PIXEL_FORMAT_GRAY; disparity_.nmetadata =0; disparity_.row_stride=n_bytes* camera_params_.width ; disparity_.size =isize; disparity_.data.resize(isize); for (size_t i=0; i < camera_params_.width * camera_params_.height; i++){ // convert to MM - the same as kinect mm openni format disparity_data_[i] = (uint16_t) 1000* 1/(depth_buf_[i]); // need 1/depth for now until Matt fixes this } memcpy(&disparity_.data[0], disparity_data_, isize); bot_core::images_t images; images.utime = img_.utime; images.n_images =2; images.image_types.push_back( 0 ); // multisense::images_t::LEFT ); for some reason enums won't work images.image_types.push_back( 4 ); // multisense::images_t::DEPTH_MM ); images.images.push_back( img_ ); images.images.push_back(disparity_); lcm_->publish("LIDARSWEEP", &images); } }
void WorldLogic::setForce(std::shared_ptr<Box> &box, std::shared_ptr<Paddle> &paddle) { if (!paddle) { std::uniform_real_distribution<scalar_type> x_dist(-20.f, 20.f), y_dist(-5.f, 25.f); box->externalForce() = vec3_type(x_dist(rng), y_dist(rng), 0.f); return; } // I like how this function completely disregards the size of the box in // regard to how box and paddle overlap vec3_type pll = paddle->position() - paddle->size() / 2.f; // lower left vec3_type pur = paddle->position() + paddle->size() / 2.f; // upper right pll.y() = -HUGE_VALF; pur.y() = HUGE_VALF; vec3_type force; if (in_bounding_box(box->position(), pll, pur)) { force = vec3_type(0.f, 1.f, 0.f); } else if (box->position().y() - box->size() / 2.f > paddle->position().y()) { // "oberhalb", not "oberhalb oder auf gleicher Höhe" vec3_type min_vector(HUGE_VALF, HUGE_VALF, HUGE_VALF); // Only consider vertices, no edges (the tasks requires this) // (2edgy4u) for (int xm: {-1, 1}) { for (int ym: {-1, 1}) { vec3_type paddle_vertex = paddle->position() + vec3_type(xm * paddle->size().x(), ym * paddle->size().y(), 0.f); vec3_type vector = box->position() - paddle_vertex; if (vector.length() < min_vector.length()) { min_vector = vector; } } } min_vector.normalize(); // If a box is bigger than the paddle, it might happen that the box is // off-center, but its closest edge ie on the other side of the paddle // center than most of the box; this will lead to the box being pushed in // the wrong direction. Fix this here. if (((box->position().x() > paddle->position().x()) && (min_vector.x() < 0.f)) || ((box->position().x() < paddle->position().x()) && (min_vector.x() > 0.f))) { min_vector.x() = 0.f; } force = off_force_mult * powf(vec3_type(0.f, 1.f, 0.f).dot(min_vector), off_force_exp) * min_vector; } box->externalForce() = paddle->relativeFanPower() * force * 10.f * box->size() * box->size(); }
// This callback is called when moving the mouse while a button is pressed void motionCB(GLFWwindow* window,double x, double y) { gCamera->mouseMoved(int(x),int(y)); }
static void ddRenderOBBs(const mat4& projview) { const ShaderInfo* shader = g_dbgdrawShader.get(); GLint posLoc = shader->m_attrs[GEOM_Pos]; GLint colorLoc = shader->m_attrs[GEOM_Color]; GLint mvpLoc = shader->m_uniforms[BIND_Mvp]; glUniformMatrix4fv(mvpLoc, 1, 0, projview.m); static const float s_coords[][3] = { { -1.f, -1.f, -1.f }, { 1.f, -1.f, -1.f }, { 1.f, 1.f, -1.f }, { -1.f, 1.f, -1.f }, { -1.f, -1.f, 1.f }, { 1.f, -1.f, 1.f }, { 1.f, 1.f, 1.f }, { -1.f, 1.f, 1.f }, }; const ddOBB* cur = g_lists.m_obbs; if(cur) { glBegin(GL_LINES); while(cur) { OBB obb = OBBTransform(cur->m_xfm, cur->m_obb); glVertexAttrib3fv(colorLoc, &cur->m_color.r); vec3 pt[8]; for(int i = 0; i < 8; ++i) { pt[i] = obb.m_center + obb.m_b[0] * s_coords[i][0] + obb.m_b[1] * s_coords[i][1] + obb.m_b[2] * s_coords[i][2]; } // Bottom half glVertexAttrib3fv(posLoc, &pt[0].x); glVertexAttrib3fv(posLoc, &pt[1].x); glVertexAttrib3fv(posLoc, &pt[1].x); glVertexAttrib3fv(posLoc, &pt[2].x); glVertexAttrib3fv(posLoc, &pt[2].x); glVertexAttrib3fv(posLoc, &pt[3].x); glVertexAttrib3fv(posLoc, &pt[3].x); glVertexAttrib3fv(posLoc, &pt[0].x); // Top half glVertexAttrib3fv(posLoc, &pt[4].x); glVertexAttrib3fv(posLoc, &pt[5].x); glVertexAttrib3fv(posLoc, &pt[5].x); glVertexAttrib3fv(posLoc, &pt[6].x); glVertexAttrib3fv(posLoc, &pt[6].x); glVertexAttrib3fv(posLoc, &pt[7].x); glVertexAttrib3fv(posLoc, &pt[7].x); glVertexAttrib3fv(posLoc, &pt[4].x); // Connecting lines glVertexAttrib3fv(posLoc, &pt[0].x); glVertexAttrib3fv(posLoc, &pt[4].x); glVertexAttrib3fv(posLoc, &pt[1].x); glVertexAttrib3fv(posLoc, &pt[5].x); glVertexAttrib3fv(posLoc, &pt[2].x); glVertexAttrib3fv(posLoc, &pt[6].x); glVertexAttrib3fv(posLoc, &pt[3].x); glVertexAttrib3fv(posLoc, &pt[7].x); cur = cur->m_next; } glEnd(); } }
static void ddDrawPlane(const Plane& plane, const AABB& bounds, const Color& color) { vec3 points[6]; struct edge_t { int start; int end; }; static const edge_t edges[12] = { // bottom {0, 1}, {1, 3}, {3, 2}, {2, 0}, // top {4, 5}, {5, 7}, {7, 6}, {6, 4}, // top to bottom sides {0, 4}, {1, 5}, {2, 6}, {3, 7}, }; // clip plane to bounds and render a quad vec3 corners[8]; const vec3 *minmax[2] = { &bounds.m_min, &bounds.m_max }; for(int j = 0; j < 8; ++j) { int iz = j & 1; int ix = (j >> 1) & 1; int iy = (j >> 2) & 1; corners[j].Set(minmax[ix]->x, minmax[iy]->y, minmax[iz]->z); } int numPoints = 0; // add corners as points if they are close to the plane for(int j = 0; j < 8; ++j) { float planeDist = PlaneDist(plane, corners[j]); if(fabs(planeDist) < EPSILON) points[numPoints++] = corners[j]; } // add edge intersections for(int j = 0; j < 12; ++j) { vec3 a = corners[edges[j].start], b = corners[edges[j].end], ab = b - a; // intersect edge with plane float t = (-plane.m_d - Dot(plane.m_n, a)) / Dot(plane.m_n, ab); if(t >= 0.f && t <= 1.f) { vec3 pt = a + t * ab, ptA = a - pt, ptB = b - pt; float distSqA = LengthSq(ptA); float distSqB = LengthSq(ptB); if(distSqA > EPSILON_SQ && distSqB > EPSILON_SQ) { points[numPoints++] = pt; if(numPoints == 6) break; } } } if(numPoints < 3) return; // Sort results const float inv_num = 1.f / numPoints; vec3 center = {0,0,0}; for(int j = 0; j < numPoints; ++j) center += inv_num * points[j]; vec3 sideVec = Normalize(points[0] - center); vec3 upVec = Normalize(Cross(plane.m_n, sideVec)); for(int j = 1; j < numPoints; ++j) { vec3 toPointJ = points[j] - center; float angleJ = AngleWrap(atan2(Dot(upVec, toPointJ), Dot(sideVec, toPointJ))); for(int k = j+1; k < numPoints; ++k) { vec3 toPointK = points[k] - center; float angleK = AngleWrap(atan2(Dot(upVec, toPointK), Dot(sideVec, toPointK))); if(angleK < angleJ) { angleJ = angleK; std::swap(points[j], points[k]); } } } // Draw outline const ShaderInfo* shader = g_dbgdrawShader.get(); GLint posLoc = shader->m_attrs[GEOM_Pos]; GLint colorLoc = shader->m_attrs[GEOM_Color]; glVertexAttrib3fv(colorLoc, &color.r); glLineWidth(2.f); glBegin(GL_LINES); for(int j = 0; j < numPoints; ++j) { int next = (j + 1) % numPoints; glVertexAttrib3fv(posLoc, &points[j].x); glVertexAttrib3fv(posLoc, &points[next].x); } glEnd(); glLineWidth(1.f); // Draw triangles glVertexAttrib3fv(colorLoc, &color.r); glBegin(GL_TRIANGLE_FAN); glVertexAttrib3fv(posLoc, ¢er.x); for(int j = 0; j < numPoints; ++j) glVertexAttrib3fv(posLoc, &points[j].x); glVertexAttrib3fv(posLoc, &points[0].x); glEnd(); glBegin(GL_TRIANGLE_FAN); glVertexAttrib3fv(posLoc, ¢er.x); for(int j = numPoints-1; j >= 0; --j) glVertexAttrib3fv(posLoc, &points[j].x); glVertexAttrib3fv(posLoc, &points[numPoints-1].x); glEnd(); }
void OsmAnd::EmbeddedFontFinder_initialize() { s_embeddedFontFinderDefaultInstance.reset(new EmbeddedFontFinder()); }
static void ddRenderAABBs(const mat4& projview) { const ShaderInfo* shader = g_dbgdrawShader.get(); GLint posLoc = shader->m_attrs[GEOM_Pos]; GLint colorLoc = shader->m_attrs[GEOM_Color]; GLint mvpLoc = shader->m_uniforms[BIND_Mvp]; glUniformMatrix4fv(mvpLoc, 1, 0, projview.m); const ddAABB* cur = g_lists.m_aabbs; if(cur) { glBegin(GL_LINES); while(cur) { glVertexAttrib3fv(colorLoc, &cur->m_color.r); const AABB* aabb = &cur->m_aabb; // Bottom half glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_min.z); // Top half glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_min.z); // Connecting lines glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_min.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_max.x, aabb->m_max.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_min.y, aabb->m_max.z); glVertexAttrib3f(posLoc, aabb->m_min.x, aabb->m_max.y, aabb->m_max.z); cur = cur->m_next; } glEnd(); } }
void OsmAnd::EmbeddedFontFinder_release() { s_embeddedFontFinderDefaultInstance.reset(); }
void Flow::calculateConstraints(const std::shared_ptr<AnimSkeleton>& skeleton, AnimPoseVec& relativePoses, AnimPoseVec& absolutePoses) { cleanUp(); if (!skeleton) { return; } auto flowPrefix = FLOW_JOINT_PREFIX.toUpper(); auto simPrefix = SIM_JOINT_PREFIX.toUpper(); std::vector<int> handsIndices; _groupSettings.clear(); for (int i = 0; i < skeleton->getNumJoints(); i++) { auto name = skeleton->getJointName(i); if (std::find(HAND_COLLISION_JOINTS.begin(), HAND_COLLISION_JOINTS.end(), name) != HAND_COLLISION_JOINTS.end()) { handsIndices.push_back(i); } auto parentIndex = skeleton->getParentIndex(i); if (parentIndex == -1) { continue; } auto jointChildren = skeleton->getChildrenOfJoint(i); // auto childIndex = jointChildren.size() > 0 ? jointChildren[0] : -1; auto group = QStringRef(&name, 0, 3).toString().toUpper(); auto split = name.split("_"); bool isSimJoint = (group == simPrefix); bool isFlowJoint = split.size() > 2 && split[0].toUpper() == flowPrefix; if (isFlowJoint || isSimJoint) { group = ""; if (isSimJoint) { for (int j = 1; j < name.size() - 1; j++) { bool toFloatSuccess; QStringRef(&name, (int)(name.size() - j), 1).toString().toFloat(&toFloatSuccess); if (!toFloatSuccess && (name.size() - j) > (int)simPrefix.size()) { group = QStringRef(&name, (int)simPrefix.size(), (int)(name.size() - j + 1) - (int)simPrefix.size()).toString(); break; } } if (group.isEmpty()) { group = QStringRef(&name, (int)simPrefix.size(), name.size() - (int)simPrefix.size()).toString(); } qCDebug(animation) << "Sim joint added to flow: " << name; } else { group = split[1]; } if (!group.isEmpty()) { _flowJointKeywords.push_back(group); FlowPhysicsSettings jointSettings; if (PRESET_FLOW_DATA.find(group) != PRESET_FLOW_DATA.end()) { jointSettings = PRESET_FLOW_DATA.at(group); } else { jointSettings = DEFAULT_JOINT_SETTINGS; } if (_flowJointData.find(i) == _flowJointData.end()) { auto flowJoint = FlowJoint(i, parentIndex, -1, name, group, jointSettings); _flowJointData.insert(std::pair<int, FlowJoint>(i, flowJoint)); } updateGroupSettings(group, jointSettings); } } else { if (PRESET_COLLISION_DATA.find(name) != PRESET_COLLISION_DATA.end()) { _collisionSystem.addCollisionSphere(i, PRESET_COLLISION_DATA.at(name)); } } } for (auto &jointData : _flowJointData) { int jointIndex = jointData.first; glm::vec3 jointPosition, parentPosition, jointTranslation; glm::quat jointRotation; getJointPositionInWorldFrame(absolutePoses, jointIndex, jointPosition, _entityPosition, _entityRotation); getJointTranslation(relativePoses, jointIndex, jointTranslation); getJointRotation(relativePoses, jointIndex, jointRotation); getJointPositionInWorldFrame(absolutePoses, jointData.second.getParentIndex(), parentPosition, _entityPosition, _entityRotation); jointData.second.setInitialData(jointPosition, jointTranslation, jointRotation, parentPosition); } std::vector<int> roots; for (auto &joint :_flowJointData) { if (_flowJointData.find(joint.second.getParentIndex()) == _flowJointData.end()) { joint.second.setAnchored(true); roots.push_back(joint.first); } else { _flowJointData[joint.second.getParentIndex()].setChildIndex(joint.first); } } int extraIndex = -1; for (size_t i = 0; i < roots.size(); i++) { FlowThread thread = FlowThread(roots[i], &_flowJointData); // add threads with at least 2 joints if (thread._joints.size() > 0) { if (thread._joints.size() == 1) { int jointIndex = roots[i]; auto &joint = _flowJointData[jointIndex]; auto &jointPosition = joint.getUpdatedPosition(); auto newSettings = joint.getSettings(); extraIndex = extraIndex > -1 ? extraIndex + 1 : skeleton->getNumJoints(); joint.setChildIndex(extraIndex); auto newJoint = FlowJoint(extraIndex, jointIndex, -1, joint.getName(), joint.getGroup(), newSettings); newJoint.toHelperJoint(jointPosition, HELPER_JOINT_LENGTH); glm::vec3 translation = glm::vec3(0.0f, HELPER_JOINT_LENGTH, 0.0f); newJoint.setInitialData(jointPosition + translation, 100.0f * translation , Quaternions::IDENTITY, jointPosition); _flowJointData.insert(std::pair<int, FlowJoint>(extraIndex, newJoint)); FlowThread newThread = FlowThread(jointIndex, &_flowJointData); if (newThread._joints.size() > 1) { _jointThreads.push_back(newThread); } } else { _jointThreads.push_back(thread); } } } if (_jointThreads.size() == 0) { onCleanup(); } if (handsIndices.size() > 0) { FlowCollisionSettings handSettings; handSettings._radius = HAND_COLLISION_RADIUS; for (size_t i = 0; i < handsIndices.size(); i++) { _collisionSystem.addCollisionSphere(handsIndices[i], handSettings, glm::vec3(), true, true); } } _initialized = _jointThreads.size() > 0; }
// ----------------------------------------------------------------- // // @details This is the entry point for the Win32 application. // // ----------------------------------------------------------------- int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nShowCmd) { // // Create a console window for debugging and other output AllocConsole(); HANDLE hout = GetStdHandle(STD_OUTPUT_HANDLE); int hcrt = _open_osfhandle((long) hout, _O_TEXT); FILE* fout = _fdopen(hcrt, "w"); setvbuf(fout, NULL, _IONBF, 1); *stdout = *fout; HANDLE hin = GetStdHandle(STD_INPUT_HANDLE); hcrt = _open_osfhandle((long) hin, _O_TEXT); FILE* fin = _fdopen(hcrt, "r"); setvbuf(fin, NULL, _IONBF, 128); *stdin = *fin; // // Define a window class WNDCLASS wcl; wcl.hInstance = hInstance; wcl.lpszClassName = L"FaultTolerant"; wcl.lpfnWndProc = WinMessageHandler; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcl.hIcon = LoadIcon(NULL, IDI_WINLOGO); wcl.hCursor = LoadCursor(NULL, IDC_ARROW); wcl.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wcl.lpszMenuName=NULL; // // Register with Windows if (!RegisterClass(&wcl)) { return 0; } DWORD dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // // Create the window HWND hwnd = CreateWindowEx( dwExStyle, L"FaultTolerant", L"FaultTolerantPriority - Demo", dwStyle, CW_USEDEFAULT,CW_USEDEFAULT, 500, 500, NULL, NULL, hInstance, NULL); SetFocus(hwnd); // // Obtain the client size of the window RECT rcClient; GetClientRect(hwnd, &rcClient); // // Initialize the application code g_app = std::make_shared<FaultTolerantApp>(hwnd, static_cast<uint16_t>(rcClient.right), static_cast<uint16_t>(rcClient.bottom)); g_app->initialize(); // // Display the window ShowWindow(hwnd, nShowCmd); // // Enter the Windows message loop MSG winMessage; while (GetMessage(&winMessage,NULL,0,0)) { TranslateMessage(&winMessage); DispatchMessage(&winMessage); g_app->pulse(); } g_app->terminate(); // // Disable a compiler warning complaining about WPARAM to int conversion. #pragma warning(push) #pragma warning(disable : 4244) return winMessage.wParam; #pragma warning(pop) }
std::unique_ptr<RenderQueue> BREW::CreateFrameDrawable( std::shared_ptr<const Frame> frame ) const { auto padding = GetProperty<float>( "Padding", frame ); auto border_color = GetProperty<sf::Color>( "BorderColor", frame ); auto color = GetProperty<sf::Color>( "Color", frame ); auto border_width = GetProperty<float>( "BorderWidth", frame ); const auto& font_name = GetProperty<std::string>( "FontName", frame ); auto font_size = GetProperty<unsigned int>( "FontSize", frame ); const auto& font = GetResourceManager().GetFont( font_name ); auto label_padding = GetProperty<float>( "LabelPadding", frame ); auto line_height = GetFontLineHeight( *font, font_size ); std::unique_ptr<RenderQueue> queue( new RenderQueue ); // Right queue->Add( Renderer::Get().CreateLine( sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, line_height / 2.f + border_width / 2.f ), sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, frame->GetAllocation().height - border_width ), border_color, border_width ) ); // Bottom queue->Add( Renderer::Get().CreateLine( sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, frame->GetAllocation().height - border_width ), sf::Vector2f( border_width / 2.f, frame->GetAllocation().height - border_width ), border_color, border_width ) ); // Left queue->Add( Renderer::Get().CreateLine( sf::Vector2f( border_width / 2.f, frame->GetAllocation().height - border_width ), sf::Vector2f( border_width / 2.f, line_height / 2.f + border_width / 2.f ), border_color, border_width ) ); auto label_start_x = 0.f; auto label_end_x = 0.f; auto alignment = frame->GetAlignment().x; if( frame->GetLabel().getSize() > 0 ) { auto metrics = GetTextStringMetrics( frame->GetLabel(), *font, font_size ); metrics.x += 2.f * label_padding; label_start_x = padding + ( alignment * ( frame->GetAllocation().width - 2.f * padding - metrics.x ) ); label_end_x = label_start_x + metrics.x; sf::Text text( frame->GetLabel(), *font, font_size ); text.setPosition( label_start_x + label_padding, border_width / 2.f ); text.setFillColor( color ); queue->Add( Renderer::Get().CreateText( text ) ); } // Top Left queue->Add( Renderer::Get().CreateLine( sf::Vector2f( border_width / 2.f, line_height / 2.f + border_width / 2.f ), sf::Vector2f( label_start_x - .5f * border_width, line_height / 2.f + border_width / 2.f ), border_color, border_width ) ); // Top Right queue->Add( Renderer::Get().CreateLine( sf::Vector2f( label_end_x + .5f * border_width, line_height / 2.f + border_width / 2.f ), sf::Vector2f( frame->GetAllocation().width - border_width / 2.f, line_height / 2.f + border_width / 2.f ), border_color, border_width ) ); return queue; }
void mcts_two_players<Game>::think(const std::shared_ptr<Game>& game) { using namespace std; const chrono::steady_clock::time_point start = chrono::steady_clock::now(); chrono::steady_clock::time_point now; mt19937& generator = mcts<Game>::generators[util::omp_util::get_thread_num()]; auto state = game->get_state(); vector<node*> visited(200); vector<uint16_t> moves(200); unsigned int nb_iter = 0; do { int size = 1; node* current = this->root; visited[0] = current; while (!game->end_of_game() && !current->is_leaf() && !current->is_proven()) { current = select(game, generator, current); visited[size++] = current; } int game_value = 0; if (current->is_proven()) { if (current->is_won()) game_value = 1; else { game_value = -1; } } else if (game->end_of_game()) { int v = game->value_for_current_player(); if (v > 0) { game_value = 1; if (new_version_) current->set_won(); } else if (v < 0) { game_value = -1; if (new_version_) { current->set_lost(); if (size > 1) visited[size - 2]->set_won(); } } } else { uint8_t player = game->current_player(); expand(game, current); game->playout(generator); int v = game->value(player); if (v > 0) game_value = 1; else if (v < 0) game_value = -1; } for (int i = size - 1; i >= 0; --i) { visited[i]->update(game_value); game_value = -game_value; } game->set_state(state); ++nb_iter; if ((nb_iter & 0x3F) == 0) now = chrono::steady_clock::now(); } while ((nb_iter & 0x3F) != 0 || now < start + this->milliseconds); }
void MakeBid( std::shared_ptr<Packet_ServerBeginRound> roundInfo, // Information about this particular round const std::shared_ptr<Packet_ServerRequestBid> request, // The specific request we received double period, // How long this bidding period will last double skewEstimate, // An estimate of the time difference between us and the server (positive -> we are ahead) std::vector<uint32_t> &solution, // Our vector of indices describing the solution uint32_t *pProof // Will contain the "proof", which is just the value ) { double tSafetyMargin = 0.5; // accounts for uncertainty in network conditions /* This is when the server has said all bids must be produced by, plus the adjustment for clock skew, and the safety margin */ double tFinish = request->timeStampReceiveBids * 1e-9 + skewEstimate - tSafetyMargin; Log(Log_Verbose, "MakeBid - start, total period=%lg.", period); /* We will use this to track the best solution we have created so far. */ roundInfo->maxIndices = 4; std::vector<uint32_t> bestSolution(roundInfo->maxIndices); std::vector<uint32_t> gpuBestSolution(roundInfo->maxIndices); bigint_t bestProof, gpuBestProof; wide_ones(BIGINT_WORDS, bestProof.limbs); // Incorporate the existing block chain data - in a real system this is the // list of transactions we are signing. This is the FNV hash: // http://en.wikipedia.org/wiki/Fowler%E2%80%93Noll%E2%80%93Vo_hash_function hash::fnv<64> hasher; uint64_t chainHash = hasher((const char *)&roundInfo->chainData[0], roundInfo->chainData.size()); bigint_t x; wide_x_init(&x.limbs[0], uint32_t(0), roundInfo->roundId, roundInfo->roundSalt, chainHash); std::vector<uint32_t> indices(roundInfo->maxIndices); //Define TBB arrays uint32_t *parallel_Indices = (uint32_t *)malloc(sizeof(uint32_t) * TBB_PARALLEL_COUNT); uint32_t *parallel_BestSolutions = (uint32_t *)malloc(sizeof(uint32_t) * TBB_PARALLEL_COUNT * roundInfo->maxIndices); uint32_t *parallel_Proofs = (uint32_t *)malloc(sizeof(uint32_t) * 8 * TBB_PARALLEL_COUNT); uint32_t *parallel_BestProofs = (uint32_t *)malloc(sizeof(uint32_t) * 8 * TBB_PARALLEL_COUNT); //Define GPU arrays uint32_t *d_ParallelBestSolutions; checkCudaErrors(cudaMalloc((void **)&d_ParallelBestSolutions, sizeof(uint32_t) * CUDA_DIM * CUDA_DIM * roundInfo->maxIndices)); checkCudaErrors(cudaMemcpy(d_hashConstant, &roundInfo->c[0], sizeof(uint32_t) * 4, cudaMemcpyHostToDevice)); unsigned gpuTrials = 0; unsigned cpuTrials = 0; unsigned maxNum = uint32_t(0xFFFFFFFF); auto runGPU = [ = , &gpuTrials] { cudaInit(CUDA_DIM, d_ParallelBestProofs); do { cudaIteration(d_ParallelIndices, d_ParallelProofs, d_ParallelBestProofs, d_ParallelBestSolutions, x, d_hashConstant, roundInfo->hashSteps, CUDA_DIM, gpuTrials, CUDA_TRIALS, roundInfo->maxIndices); gpuTrials += CUDA_TRIALS; } while ((tFinish - now() * 1e-9) > 0); }; std::thread runGPUThread(runGPU); auto tbbInitial = [ = ](unsigned i) { bigint_t ones; wide_ones(8, ones.limbs); wide_copy(8, ¶llel_BestProofs[i * 8], ones.limbs); }; tbb::parallel_for<unsigned>(0, TBB_PARALLEL_COUNT, tbbInitial); do { auto tbbIteration = [ = ](unsigned i) { uint32_t index = maxNum - (TBB_PARALLEL_COUNT<<2) - cpuTrials + (i<<1); bigint_t proof = tbbHash(roundInfo.get(), index, x); wide_copy(8, ¶llel_Proofs[i * 8], proof.limbs); parallel_Indices[i] = index; }; tbb::parallel_for<unsigned>(0, TBB_PARALLEL_COUNT, tbbIteration); auto tbbCrossHash = [ = ](unsigned i) { for (unsigned xorStride = 1; xorStride < TBB_PARALLEL_COUNT >> 2; xorStride++) { if (i + (roundInfo->maxIndices * xorStride) < TBB_PARALLEL_COUNT) { bigint_t candidateBestProof; wide_copy(8, candidateBestProof.limbs, ¶llel_Proofs[i * 8]); for (unsigned indexNum = 1; indexNum < roundInfo->maxIndices; indexNum++) { wide_xor(8, candidateBestProof.limbs, candidateBestProof.limbs, ¶llel_Proofs[(i + (indexNum * xorStride)) * 8]); } if (wide_compare(8, candidateBestProof.limbs, ¶llel_BestProofs[i * 8]) < 0) { wide_copy(8, ¶llel_BestProofs[i * 8], candidateBestProof.limbs); for (unsigned ID = 0; ID < roundInfo->maxIndices; ID++) { parallel_BestSolutions[(i * roundInfo->maxIndices) + ID] = parallel_Indices[i + (ID * xorStride)]; } } } } }; tbb::parallel_for<unsigned>(0, TBB_PARALLEL_COUNT, tbbCrossHash); cpuTrials += TBB_PARALLEL_COUNT; } while ((tFinish - now() * 1e-9) > 0); runGPUThread.join(); auto reduceGPU = [ = , &gpuBestSolution, &gpuBestProof] { cudaParallelReduce(CUDA_DIM, roundInfo->maxIndices, d_ParallelBestProofs, d_ParallelBestSolutions, &gpuBestSolution[0], gpuBestProof.limbs); }; std::thread reduceThread(reduceGPU); //TBB for (int toDo = TBB_PARALLEL_COUNT / 2; toDo >= 1; toDo >>= 1) { auto tbbReduce = [ = ](unsigned i) { if (wide_compare(BIGINT_WORDS, ¶llel_BestProofs[(i + toDo) * 8], ¶llel_BestProofs[i * 8]) < 0) { wide_copy(8, ¶llel_BestProofs[i * 8], ¶llel_BestProofs[(i + toDo) * 8]); wide_copy(roundInfo->maxIndices, ¶llel_BestSolutions[i * roundInfo->maxIndices], ¶llel_BestSolutions[(i + toDo) * roundInfo->maxIndices]); } }; tbb::parallel_for<unsigned>(0, toDo, tbbReduce); } wide_copy(BIGINT_WORDS, bestProof.limbs, ¶llel_BestProofs[0]); wide_copy(roundInfo->maxIndices, &bestSolution[0], ¶llel_BestSolutions[0]); reduceThread.join(); if (wide_compare(BIGINT_WORDS, gpuBestProof.limbs, bestProof.limbs) < 0) { Log(Log_Verbose, "Accepting GPU Solution"); wide_copy(8, bestProof.limbs, gpuBestProof.limbs); wide_copy(roundInfo->maxIndices, &bestSolution[0], &gpuBestSolution[0]); } solution = bestSolution; wide_copy(BIGINT_WORDS, pProof, bestProof.limbs); free(parallel_Indices); free(parallel_BestSolutions); free(parallel_Proofs); free(parallel_BestProofs); checkCudaErrors(cudaFree(d_ParallelBestSolutions)); Log(Log_Verbose, "MakeBid - finish. Total trials %d, cpu: %d, gpu %d", cpuTrials + gpuTrials, cpuTrials, gpuTrials); }
void CameraControl::applyInteraction(glm::mat4 & camera) { #ifdef HAVE_SIXENSE static bool hydraInitialized = false; if (!hydraInitialized) { int init = sixenseInit(); sixenseSetActiveBase(0); sixenseUtils::getTheControllerManager()->setGameType(sixenseUtils::ControllerManager::ONE_PLAYER_TWO_CONTROLLER); sixenseUtils::getTheControllerManager()->registerSetupCallback(controller_manager_setup_callback); hydraInitialized = true; } if (hydraEnabled) { sixenseSetActiveBase(0); static sixenseAllControllerData acd; sixenseGetAllNewestData(&acd); sixenseUtils::getTheControllerManager()->update(&acd); int i = sixenseUtils::getTheControllerManager()->getIndex( sixenseUtils::IControllerManager::P1L); const sixenseControllerData & left = acd.controllers[i]; i = sixenseUtils::getTheControllerManager()->getIndex( sixenseUtils::IControllerManager::P1R); const sixenseControllerData & right = acd.controllers[i]; translateCamera(camera, glm::vec3(left.joystick_x, right.joystick_y, -left.joystick_y) / 100.0f); rotateCamera(camera, glm::angleAxis(-right.joystick_x /100.0f, glm::vec3(0, 1, 0))); } #endif #ifdef HAVE_SPNAV static int spnav = -2; static spnav_event event; if (-2 == spnav) { spnav = spnav_open(); } if (spnav >= 0) { int eventType; while (0 != (eventType = spnav_poll_event(&event))) { SAY("event type %d", eventType); if (SPNAV_EVENT_MOTION == eventType) { spnav_event_motion & m = event.motion; glm::vec3 spaceTranslation = getTranslation(m); translateCamera(camera, spaceTranslation); // camera = glm::rotate(camera, (float)m.rx / 200.0f, GlUtils::X_AXIS); // We take the world Y axis and put it into the camera reference frame glm::vec3 yawAxis = glm::inverse(glm::quat(camera)) * GlUtils::Y_AXIS; camera = glm::rotate(camera, (float)m.ry / 200.0f, yawAxis); // if (abs(m.ry) >= 3 || abs(m.rx) >= 3) { // if (m.rx > m.ry) { // } else { // camera = glm::rotate(camera, (float)m.ry / 200.0f, GlUtils::Y_AXIS); // } // // } // camera = glm::rotate(camera, (float)m.rx / 500.0f, GlUtils::X_AXIS); // glm::quat currentRotation(camera); // glm::quat inverse = glm::inverse(currentRotation); // camera = glm::mat4_cast(inverse) * camera; // rot = glm::quat(euler); // camera = glm::mat4_cast(rot) * camera; // camera = glm::mat4_cast(spaceRotation * currentRotation) * camera; // rotateCamera(camera, glm::quat(rotation)); } } } // int spnav_sensitivity(double sens); #endif if (glfwJoystickPresent(0)) { static const char * joyName = glfwGetJoystickName(0); static bool x52present = std::string(joyName).find("X52") != std::string::npos; static std::shared_ptr<GlfwJoystick> joystick( x52present ? (GlfwJoystick*)new SaitekX52Pro::Controller(0) : (GlfwJoystick*)new Xbox::Controller(0) ); joystick->read(); glm::vec3 translation; glm::quat rotation; float scale = 500.0f; if (x52present) { using namespace SaitekX52Pro::Axis; // 0 - 9 float scaleMod = joystick->getCalibratedAxisValue(SaitekX52Pro::Axis::THROTTLE_SLIDER); scaleMod *= 0.5f; scaleMod += 0.5f; scaleMod *= 9.0f; scaleMod += 1.0f; scale /= scaleMod; translation = joystick->getCalibratedVector( STICK_POV_X, STICK_POV_Y, THROTTLE_MAIN); glm::vec3 euler = joystick->getCalibratedVector( STICK_Y, STICK_Z, STICK_X); rotation = glm::quat(euler / 20.0f); } else { using namespace Xbox::Axis; translation.z = joystick->getCalibratedAxisValue(LEFT_Y) * 20.0f; translation.x = joystick->getCalibratedAxisValue(LEFT_X) * 20.0f; rotation.y = joystick->getCalibratedAxisValue(RIGHT_X) / 100.0f; rotation.x = joystick->getCalibratedAxisValue(RIGHT_Y) / 200.0f; rotation.z = joystick->getCalibratedAxisValue(TRIGGER) / 400.0f; } if (glm::length(translation) > 0.01f) { translateCamera(camera, translation / scale); } rotateCamera(camera, rotation); recompose(camera); } static uint32_t lastKeyboardUpdateTick = 0; uint32_t now = Platform::elapsedMillis(); if (0 != lastKeyboardUpdateTick) { float dt = (now - lastKeyboardUpdateTick) / 1000.0f; if (keyboardRotate.x || keyboardRotate.y || keyboardRotate.z) { const glm::quat delta = glm::quat(glm::vec3(keyboardRotate) * dt); rotateCamera(camera, delta); } if (keyboardTranslate.x || keyboardTranslate.y || keyboardTranslate.z) { const glm::vec3 delta = glm::vec3(keyboardTranslate) * dt; translateCamera(camera, delta); } } lastKeyboardUpdateTick = now; }
// This callback is called upon resizing the OpenGL window, // e.g. when maximizing the window void resizeCB(GLFWwindow* window, int width, int height) { gCamera->resize(width,height); }
void print_myobject3_2(std::shared_ptr<MyObject3> obj) { py::print(obj->toString()); }
// This callback is called when a mouse button is pressed or released void mouseCB(GLFWwindow* window, int button, int state, int mods) { gCamera->mouseButtonPressed(button,state); }
void print_myobject3_3(const std::shared_ptr<MyObject3> &obj) { py::print(obj->toString()); }
void Enemy::render(std::shared_ptr<sf::RenderTarget> screen) { screen->draw(sprite); }
bool OsmAnd::MapPrimitivesMetricsLayerProvider_P::obtainData( const IMapDataProvider::Request& request_, std::shared_ptr<IMapDataProvider::Data>& outData, std::shared_ptr<Metric>* const pOutMetric) { const auto& request = MapDataProviderHelpers::castRequest<MapPrimitivesMetricsLayerProvider::Request>(request_); if (pOutMetric) pOutMetric->reset(); MapPrimitivesProvider_Metrics::Metric_obtainData obtainDataMetric; // Obtain offline map primitives tile std::shared_ptr<MapPrimitivesProvider::Data> primitivesTile; owner->primitivesProvider->obtainTiledPrimitives(request, primitivesTile, &obtainDataMetric); if (!primitivesTile) { outData.reset(); return true; } // Prepare drawing canvas const std::shared_ptr<SkBitmap> bitmap(new SkBitmap()); if (!bitmap->tryAllocPixels(SkImageInfo::MakeN32Premul(owner->tileSize, owner->tileSize))) { LogPrintf(LogSeverityLevel::Error, "Failed to allocate buffer for rasterization surface %dx%d", owner->tileSize, owner->tileSize); return false; } SkBitmapDevice target(*bitmap); SkCanvas canvas(&target); canvas.clear(SK_ColorDKGRAY); QString text; text += QString(QLatin1String("TILE %1x%2@%3\n")) .arg(request.tileId.x) .arg(request.tileId.y) .arg(request.zoom); QString obtainBinaryMapObjectsElapsedTime(QLatin1String("?")); if (const auto obtainBinaryMapObjectsMetric = obtainDataMetric.findSubmetricOfType<ObfMapObjectsProvider_Metrics::Metric_obtainData>(true)) { obtainBinaryMapObjectsElapsedTime = QString::number(obtainBinaryMapObjectsMetric->elapsedTime, 'f', 2); } QString primitiviseElapsedTime(QLatin1String("?")); if (const auto primitiviseMetric = obtainDataMetric.findSubmetricOfType<MapPrimitiviser_Metrics::Metric_primitiviseWithSurface>(true)) { text += QString(QLatin1String("order %1/-%2 %3s ~%4us/e\n")) .arg(primitiviseMetric->orderEvaluations) .arg(primitiviseMetric->orderRejects) .arg(QString::number(primitiviseMetric->elapsedTimeForOrderEvaluation, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForOrderEvaluation * 1000000.0f / primitiviseMetric->orderEvaluations)); text += QString(QLatin1String("polyg %1/-%2(-%3) %4s ~%5us/e\n")) .arg(primitiviseMetric->polygonEvaluations) .arg(primitiviseMetric->polygonRejects) .arg(primitiviseMetric->polygonsRejectedByArea) .arg(QString::number(primitiviseMetric->elapsedTimeForPolygonEvaluation, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPolygonEvaluation * 1000000.0f / primitiviseMetric->polygonEvaluations)); text += QString(QLatin1String("%1s ~%2us/p\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForPolygonProcessing, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPolygonProcessing * 1000000.0f / primitiviseMetric->polygonPrimitives)); text += QString(QLatin1String("polyl %1/-%2(-%3) %4s ~%5us/e\n")) .arg(primitiviseMetric->polylineEvaluations) .arg(primitiviseMetric->polylineRejects) .arg(primitiviseMetric->polylineRejectedByDensity) .arg(QString::number(primitiviseMetric->elapsedTimeForPolylineEvaluation, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPolylineEvaluation * 1000000.0f / primitiviseMetric->polylineEvaluations)); text += QString(QLatin1String("%1s ~%2us/p\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForPolylineProcessing, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPolylineProcessing * 1000000.0f / primitiviseMetric->polylinePrimitives)); text += QString(QLatin1String("point %1/-%2 %3s ~%4us/e\n")) .arg(primitiviseMetric->pointEvaluations) .arg(primitiviseMetric->pointRejects) .arg(QString::number(primitiviseMetric->elapsedTimeForPointEvaluation, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPointEvaluation * 1000000.0f / primitiviseMetric->pointEvaluations)); text += QString(QLatin1String("%1s ~%2us/p\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForPointProcessing, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForPointProcessing * 1000000.0f / primitiviseMetric->pointPrimitives)); const auto deltaGroups = primitiviseMetric->elapsedTimeForObtainingPrimitivesGroups - primitiviseMetric->elapsedTimeForOrderEvaluation - primitiviseMetric->elapsedTimeForOrderProcessing - primitiviseMetric->elapsedTimeForPolygonEvaluation - primitiviseMetric->elapsedTimeForPolygonProcessing - primitiviseMetric->elapsedTimeForPolylineEvaluation - primitiviseMetric->elapsedTimeForPolylineProcessing - primitiviseMetric->elapsedTimeForPointEvaluation - primitiviseMetric->elapsedTimeForPointProcessing; text += QString(QLatin1String("grp %1s (-^=%2s)\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForObtainingPrimitivesGroups, 'f', 2)) .arg(QString::number(deltaGroups, 'f', 2)); text += QString(QLatin1String("prim %1s+s%2s+?=%3s\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForObtainingPrimitivesGroups, 'f', 2)) .arg(QString::number(primitiviseMetric->elapsedTimeForFutureSharedPrimitivesGroups, 'f', 2)) .arg(QString::number(primitiviseMetric->elapsedTimeForPrimitives, 'f', 2)); text += QString(QLatin1String("d/b/c %1s/%2s/%3s\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForObtainingPrimitivesFromDetailedmap, 'f', 2)) .arg(QString::number(primitiviseMetric->elapsedTimeForObtainingPrimitivesFromBasemap, 'f', 2)) .arg(QString::number(primitiviseMetric->elapsedTimeForObtainingPrimitivesFromCoastlines, 'f', 2)); text += QString(QLatin1String("txt %1(-%2) %3s ~%4us/e ~%5us/p\n")) .arg(primitiviseMetric->obtainedTextSymbols) .arg(primitiviseMetric->rejectedTextSymbols) .arg(QString::number(primitiviseMetric->elapsedTimeForTextSymbolsEvaluation + primitiviseMetric->elapsedTimeForTextSymbolsProcessing, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForTextSymbolsEvaluation * 1000000.0f / primitiviseMetric->textSymbolsEvaluations)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForTextSymbolsProcessing * 1000000.0f / (primitiviseMetric->obtainedTextSymbols + primitiviseMetric->rejectedTextSymbols))); text += QString(QLatin1String("icn %1(-%2) %3s ~%4us/p\n")) .arg(primitiviseMetric->obtainedIconSymbols) .arg(primitiviseMetric->rejectedIconSymbols) .arg(QString::number(primitiviseMetric->elapsedTimeForIconSymbolsProcessing, 'f', 2)) .arg(static_cast<int>(primitiviseMetric->elapsedTimeForIconSymbolsProcessing * 1000000.0f / (primitiviseMetric->obtainedIconSymbols + primitiviseMetric->rejectedIconSymbols))); const auto deltaSymbols = primitiviseMetric->elapsedTimeForSymbolsGroupsProcessing - primitiviseMetric->elapsedTimeForTextSymbolsEvaluation - primitiviseMetric->elapsedTimeForTextSymbolsProcessing - primitiviseMetric->elapsedTimeForIconSymbolsProcessing; text += QString(QLatin1String("sym %1s(-^=%2s) %3->%4\n")) .arg(QString::number(primitiviseMetric->elapsedTimeForSymbolsGroupsProcessing, 'f', 2)) .arg(QString::number(deltaSymbols, 'f', 2)) .arg(primitiviseMetric->symbolsGroupsProcessed) .arg(primitiviseMetric->obtainedTextSymbols + primitiviseMetric->obtainedIconSymbols); primitiviseElapsedTime = QString::number(primitiviseMetric->elapsedTime, 'f', 2); } text += QString(QLatin1String("total r%1+p%2+?=%3s\n")) .arg(obtainBinaryMapObjectsElapsedTime) .arg(primitiviseElapsedTime) .arg(QString::number(obtainDataMetric.elapsedTime, 'f', 2)); text = text.trimmed(); const auto fontSize = 14.0f * owner->densityFactor; SkPaint textPaint; textPaint.setAntiAlias(true); textPaint.setTextEncoding(SkPaint::kUTF16_TextEncoding); textPaint.setTextSize(fontSize); textPaint.setColor(SK_ColorGREEN); auto topOffset = fontSize; const auto lines = text.split(QLatin1Char('\n'), QString::SkipEmptyParts); for (const auto& line : lines) { canvas.drawText( line.constData(), line.length()*sizeof(QChar), 5, topOffset, textPaint); topOffset += 1.15f * fontSize; } outData.reset(new MapPrimitivesMetricsLayerProvider::Data( request.tileId, request.zoom, AlphaChannelPresence::NotPresent, owner->densityFactor, bitmap, primitivesTile, new RetainableCacheMetadata(primitivesTile->retainableCacheMetadata))); return true; }
/** * Set the rulebook and reset the rules to their defaults. * @param rulebook The rulebook (may be @c nullptr). */ void Rules::SetRulebook(std::shared_ptr<const Rulebook> rulebook) { rules = rulebook ? rulebook->CreateDefaultRules() : luabind::object(); this->rulebook = std::move(rulebook); }
/** * \brief Manually sets extended shape * * \param shape source of new extended shape * \param extension new extended shape */ void set_extended_shape(std::shared_ptr< ShapeEnum<D,MultiIndex> > shape, std::shared_ptr< ShapeEnum<D,MultiIndex> > extension) { cached_extended_shape_source_ = shape.get(); cached_extended_shape_ = extension; }
touchmind::VISITOR_RESULT operator()(std::shared_ptr<touchmind::model::node::NodeModel> node) { node->SetId(node->GenerateId()); return touchmind::VISITOR_RESULT_CONTINUE; }
void WalletApi::TestSendMoney(int64_t transferAmount, uint64_t fee, uint64_t mixIn, const std::string& extra) { prepareBobWallet(); prepareCarolWallet(); alice->initAndGenerate("pass"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(GetOneBlockReward(*alice)); //unblock Alice's money generator.generateEmptyBlocks(10); uint64_t expectedBalance = TEST_BLOCK_REWARD; alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); EXPECT_EQ(alice->pendingBalance(), expectedBalance); EXPECT_EQ(alice->actualBalance(), expectedBalance); bob->initAndGenerate("pass2"); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); ASSERT_NO_FATAL_FAILURE(TransferMoney(*alice, *bob, transferAmount, fee, 0, "")); generator.generateEmptyBlocks(10); alice->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(aliceWalletObserver.get())); bob->startRefresh(); ASSERT_NO_FATAL_FAILURE(WaitWalletSync(bobWalletObserver.get())); EXPECT_EQ(bob->pendingBalance(), transferAmount); EXPECT_EQ(bob->actualBalance(), transferAmount); EXPECT_EQ(alice->pendingBalance(), expectedBalance - transferAmount - fee); EXPECT_EQ(alice->actualBalance(), expectedBalance - transferAmount - fee); alice->shutdown(); bob->shutdown(); }
inline void keepAspectRatio(const bool keep) { img->keepAspectRatio(keep); }
void JPEGParser::parse(const std::string& filename, const std::string& resolvedFilename, std::shared_ptr<Options> options, const std::vector<unsigned char>& data, std::shared_ptr<AssetLibrary> assetLibrary) { int width; int height; int comps; // Loads a JPEG image from a memory buffer. // req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA). // On return, width/height will be set to the image's dimensions, and actual_comps will be set // to either 1 (grayscale) or 3 (RGB). auto bmpData = jpgd::decompress_jpeg_image_from_memory( (const unsigned char*)&data[0], data.size(), &width, &height, &comps, 3 ); if (bmpData == nullptr) { error()->execute(shared_from_this(), Error("ParserError", "failed to decode JPEG file " + filename)); return; } auto format = render::TextureFormat::RGBA; if (comps == 3 || comps == 1) format = render::TextureFormat::RGB; render::AbstractTexture::Ptr texture = nullptr; if (options->isCubeTexture()) { MipMapChainParser parser; auto cubeTexture = parser.parseCubeTexture( options->context(), width, height, bmpData, options->parseMipMaps(), options->parseMipMaps() || options->generateMipmaps(), options->resizeSmoothly(), format, filename ); cubeTexture = std::static_pointer_cast<render::CubeTexture>(options->textureFunction()(filename, cubeTexture)); assetLibrary->cubeTexture(filename, cubeTexture); texture = cubeTexture; } else if (options->isRectangleTexture()) { throw; // FIXME: handle rectangle textures } else { MipMapChainParser parser; auto texture2d = parser.parseTexture( options->context(), width, height, bmpData, options->parseMipMaps(), options->parseMipMaps() || options->generateMipmaps(), options->resizeSmoothly(), format, filename ); texture2d = std::static_pointer_cast<render::Texture>(options->textureFunction()(filename, texture2d)); texture = texture2d; assetLibrary->texture(filename, texture2d); } if (options->disposeTextureAfterLoading()) texture->disposeData(); free(bmpData); if (options->disposeTextureAfterLoading()) texture->disposeData(); complete()->execute(shared_from_this()); }