text
string
size
int64
token_count
int64
#include "trajectory_generator.h" #include "Eigen/Dense" #include "utils.h" using Eigen::Matrix3d; using Eigen::Vector3d; PathPlanning::TrajectoryGenerator::TrajectoryGenerator(const Map &map, double step_dt, double max_speed, double max_acc) : map(map), step_dt(step_dt), max_speed(max_speed), max_acc(max_acc) {} PathPlanning::FTrajectory PathPlanning::TrajectoryGenerator::Generate(const Frenet &start, const Frenet &target, size_t length) const { const double t = length * this->step_dt; // Computes the trajectory coefficients const Coeff s_p_coeff = this->MinimizeJerk(start.s, target.s, t); const Coeff s_v_coeff = this->Differentiate(s_p_coeff); const Coeff s_a_coeff = this->Differentiate(s_v_coeff); const Coeff d_p_coeff = this->MinimizeJerk(start.d, target.d, t); const Coeff d_v_coeff = this->Differentiate(d_p_coeff); const Coeff d_a_coeff = this->Differentiate(d_v_coeff); PathPlanning::FTrajectory trajectory; trajectory.reserve(length); Frenet prev_state = start; for (size_t i = 1; i <= length; ++i) { const double t = i * this->step_dt; const double max_s_delta = prev_state.s.v * this->step_dt + 0.5 * prev_state.s.a * this->step_dt * this->step_dt; // Reduces longitudinal values to meet speed and acceleration constraints const double s_p = std::min(this->Eval(t, s_p_coeff), prev_state.s.p + max_s_delta); const double s_v = std::min(this->Eval(t, s_v_coeff), this->max_speed); const double s_a = std::max(std::min(this->Eval(t, s_a_coeff), this->max_acc), -this->max_acc); const double d_p = this->Eval(t, d_p_coeff); const double d_v = this->Eval(t, d_v_coeff); const double d_a = this->Eval(t, d_a_coeff); const State s{Map::Mod(s_p), s_v, s_a}; const State d{d_p, d_v, d_a}; trajectory.emplace_back(s, d); prev_state = {s, d}; } return trajectory; } PathPlanning::FTrajectory PathPlanning::TrajectoryGenerator::Predict(const Frenet &start, const StatePredictionFunction &prediction, size_t length) const { FTrajectory trajectory; trajectory.reserve(length); for (size_t i = 1; i <= length; ++i) { const double t = i * step_dt; trajectory.emplace_back(prediction(t)); } return trajectory; } PathPlanning::CTrajectory PathPlanning::TrajectoryGenerator::FrenetToCartesian(const FTrajectory &trajectory) const { std::vector<double> next_x_vals; std::vector<double> next_y_vals; for (auto &step : trajectory) { auto coord = this->map.FrenetToCartesian(step.s.p, step.d.p); next_x_vals.emplace_back(coord.first); next_y_vals.emplace_back(coord.second); } return CTrajectory({next_x_vals, next_y_vals}); } size_t PathPlanning::TrajectoryGenerator::TrajectoryLength(double t) const { return t / this->step_dt; } PathPlanning::Coeff PathPlanning::TrajectoryGenerator::Differentiate(const Coeff &coefficients) const { Coeff result(coefficients.size() - 1); for (size_t i = 1; i < coefficients.size(); ++i) { result[i - 1] = i * coefficients[i]; } return result; } double PathPlanning::TrajectoryGenerator::Eval(double x, const Coeff &coefficients) const { double y = 0; for (size_t i = 0; i < coefficients.size(); ++i) { y += coefficients[i] * std::pow(x, i); } return y; } PathPlanning::Coeff PathPlanning::TrajectoryGenerator::MinimizeJerk(const State &start, const State &target, double t) const { const double t_2 = t * t; const double t_3 = t * t_2; const double t_4 = t * t_3; const double t_5 = t * t_4; Matrix3d t_matrix; t_matrix << t_3, t_4, t_5, 3 * t_2, 4 * t_3, 5 * t_4, 6 * t, 12 * t_2, 20 * t_3; Vector3d s_vector; s_vector << target.p - (start.p + start.v * t + 0.5 * start.a * t_2), target.v - (start.v + start.a * t), target.a - start.a; Vector3d a_vector = t_matrix.inverse() * s_vector; return {start.p, start.v, 0.5 * start.a, a_vector(0), a_vector(1), a_vector(2)}; }
4,363
1,622
#include "cachebase.h" #include "db/connpool.h" #include "db/statement.h" #include "db/connection.h" int CacheBase::GetNagtiveCount() { return 100; } void CacheBase::Nagtive(IStatement *stmt) { m_nagtive_lock.Lock(); if( (int)m_nagtive_list.size() <= (GetNagtiveCount() / 2) ) { NagtiveHelper(stmt); } m_nagtive_lock.Unlock(); } void CacheBase::Unnagtive(IStatement *stmt) { m_nagtive_lock.Lock(); for(NagtiveList::const_iterator iter = m_nagtive_list.begin() ; iter != m_nagtive_list.end() ; ++iter) { m_dbcommand->Remove(stmt, *iter, false); } m_nagtive_list.clear(); m_nagtive_lock.Unlock(); } long long CacheBase::GetNagtive() { m_nagtive_lock.Lock(); bool ret = true; if(m_nagtive_list.empty()) { IConnection *conn = ConnPool::Instance()->GetConn(); if (conn == 0) { return 0; } IStatement *stmt_tmp = conn->createStatement(); conn->begin(false); ret = NagtiveHelper(stmt_tmp); conn->commit(); delete stmt_tmp; ConnPool::Instance()->PutConn(conn); } long long nagtive_id = 0; if (ret) { nagtive_id = *m_nagtive_list.begin(); m_nagtive_list.pop_front(); } m_nagtive_lock.Unlock(); return nagtive_id; } bool CacheBase::NagtiveHelper(IStatement *stmt) { DataAdapter t = m_table->GetPrototype(); t.Malloc(); for (int i = 0; i < (int)t.m_data_area.size(); ++i) { if (m_table->m_mata_data[i].type == DATYPE_STRING) { t.m_data_area[i].length = t.m_data_area[i].length > 1 ? 1 : t.m_data_area[i].length; } } bool ret = true; while((int)m_nagtive_list.size() < GetNagtiveCount()) { if (m_dbcommand->Save(stmt, &t, false) != DBCommand::RESULT_SUC) { ret = false; break; } m_nagtive_list.push_back(t.m_data_area[m_table->m_key_id_index].vint64); } t.Free(); return ret; } void CacheBase::Flush(IStatement *stmt) { MEM_NODE_MAP flushMap; { m_lock.Lock(); if(m_flush_map.size() == 0) { m_lock.Unlock(); return; } m_flush_map.swap(flushMap); m_lock.Unlock(); } for(MEM_NODE_MAP::iterator iter = flushMap.begin(); iter != flushMap.end(); ++iter) { switch(iter->second->GetUpdateMode()) { case ECachedUpdateModelUpdate: { m_dbcommand->Update(stmt, *iter->second->GetNode(), false); } break; case ECachedUpdateModelDelete: { DataAdapter *node = iter->second->GetNode(); m_dbcommand->Remove(stmt, node->m_data_area[m_table->m_key_id_index].vint64, false); } break; } iter->second->GetNode()->Free(); delete iter->second; } } void CacheBase::Commit(ITransaction* transation) { m_lock.Lock(); TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation); if(m_transaction_nodes.end() == iter) { m_lock.Unlock(); return; } for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1) { MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first); if(iter1->second->GetUpdateMode() & ECachedUpdateModelDelete) { iter1->second->SetUpdateMode(ECachedUpdateModelDelete); } else if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd) { iter1->second->SetUpdateMode(ECachedUpdateModelUpdate); } else if(iter1->second->GetUpdateMode() & ECachedUpdateModelUpdate) { iter1->second->SetUpdateMode(ECachedUpdateModelUpdate); } if(iter2 == m_flush_map.end()) { m_flush_map[iter1->first] = iter1->second; } else { iter2->second->GetNode()->Free(); delete iter2->second; iter2->second = iter1->second; } } m_transaction_nodes.erase(iter); m_lock.Unlock(); } void CacheBase::Rollback(ITransaction* transation) { m_lock.Lock(); TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation); if(m_transaction_nodes.end() == iter) { m_lock.Unlock(); return; } for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1) { if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd) { iter1->second->SetUpdateMode(ECachedUpdateModelDelete); MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first); if(iter2 == m_flush_map.end()) { m_flush_map[iter1->first] = iter1->second; } else { iter2->second->GetNode()->Free(); delete iter2->second; iter2->second = iter1->second; } } else { iter1->second->GetNode()->Free(); delete iter1->second; } } m_transaction_nodes.erase(iter); m_lock.Unlock(); }
4,378
1,943
/* FILE: rectangularmesh.cc -*-Mode: c++-*- * * Rectangular mesh, derived from Oxs_Mesh class. * */ #include "nb.h" #include "vf.h" #include "atlas.h" #include "meshvalue.h" #include "oxsexcept.h" #include "rectangularmesh.h" #include "director.h" #include "nb.h" #include "energy.h" // Needed to make MSVC++ 5 happy #include "util.h" // Oxs_Ext registration support OXS_EXT_REGISTER(Oxs_RectangularMesh); OXS_EXT_REGISTER(Oxs_PeriodicRectangularMesh); /* End includes */ //////////////////////////////////////////////////////////////////////// /// Support for max angle routines. See NOTES VI, 6-Sep-2012, p 71-73. class OxsRectangularMeshAngle { // This (internal) class is used to store a representation of the // angle between two vectors. It is designed so that setting and // order comparisons are quick; the radian angle (between 0 and pi) // can be extracted via the GetAngle() call, but GetAngle() is slow // and so shouldn't be called more often than necessary. public: void Set(const ThreeVector& a, const ThreeVector& b) { OC_REAL8m dot = a*b; ThreeVector cross = a^b; sdotsq = dot * fabs(dot); crosssq = cross.MagSq(); } void SetAngle(OC_REAL8m angle) { // Note: SetAngle(ang) == SetAngle(|ang|) OC_REAL8m dot = cos(angle); OC_REAL8m cross = sin(angle); sdotsq = dot*fabs(dot); crosssq = cross*cross; } OC_REAL8m GetAngle() { // Returns angle in radians, 0<= ang <= pi if(sdotsq < 0.0) { return Oc_Atan2(sqrt(crosssq),-1*sqrt(-1*sdotsq)); } return Oc_Atan2(sqrt(crosssq),sqrt(sdotsq)); } friend OC_BOOL operator<(const OxsRectangularMeshAngle&, const OxsRectangularMeshAngle&); friend OC_BOOL operator>(const OxsRectangularMeshAngle&, const OxsRectangularMeshAngle&); friend OC_BOOL operator==(const OxsRectangularMeshAngle&, const OxsRectangularMeshAngle&); friend OC_BOOL operator!=(const OxsRectangularMeshAngle&, const OxsRectangularMeshAngle&); // Constructors: OxsRectangularMeshAngle(const ThreeVector& a, const ThreeVector& b) { Set(a,b); } OxsRectangularMeshAngle(OC_REAL8m angle) { SetAngle(angle); } // Note: Use default destructor and assignment operator. private: // For vectors a, b: OC_REAL8m crosssq; // |axb|^2 (non-negative) OC_REAL8m sdotsq; // (a*b).|a*b| (signed) }; OC_BOOL operator>(const OxsRectangularMeshAngle& a, const OxsRectangularMeshAngle& b){ return (a.crosssq * b.sdotsq > a.sdotsq * b.crosssq); } OC_BOOL operator<(const OxsRectangularMeshAngle& a, const OxsRectangularMeshAngle& b){ return (a.crosssq * b.sdotsq < a.sdotsq * b.crosssq); } OC_BOOL operator==(const OxsRectangularMeshAngle& a, const OxsRectangularMeshAngle& b) { return (a.crosssq * b.sdotsq == a.sdotsq * b.crosssq); } OC_BOOL operator!=(const OxsRectangularMeshAngle& a, const OxsRectangularMeshAngle& b) { return !(a == b); } ///////////////////////////////////////////////////////////////////// // Oxs_CommonRectangularMesh void Oxs_CommonRectangularMesh::InitScaling(const Oxs_Box& box) { // Constructor helper function. Assumes cellsize is already set. if(cellsize.x<=0.0 || cellsize.y<=0.0 || cellsize.z<=0.0) { String msg = String("Invalid MIF input block detected for object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } cellvolume=cellsize.x*cellsize.y*cellsize.z; OC_REAL8m xrange = box.GetMaxX() - box.GetMinX(); OC_REAL8m yrange = box.GetMaxY() - box.GetMinY(); OC_REAL8m zrange = box.GetMaxZ() - box.GetMinZ(); if(xrange<=0. || yrange<=0. || zrange<=0.) { String msg = String("Invalid atlas range detected for object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } base = ThreeVector(box.GetMinX()+cellsize.x/2., box.GetMinY()+cellsize.y/2., box.GetMinZ()+cellsize.z/2.); xdim = static_cast<OC_INDEX>(OC_ROUND(xrange/cellsize.x)); ydim = static_cast<OC_INDEX>(OC_ROUND(yrange/cellsize.y)); zdim = static_cast<OC_INDEX>(OC_ROUND(zrange/cellsize.z)); if(xdim<1 || ydim<1 || zdim<1) { String msg = String("Invalid MIF input block detected for object ") + String(InstanceName()) + String("; minimum range smaller than cell dimension."); throw Oxs_ExtError(msg.c_str()); } // Overflow test; restrict to signed value range OC_INDEX testval = OC_INDEX((OC_UINDEX(1)<<(sizeof(OC_INDEX)*8-1))-1); /// Maximum allowed value; Assumes 2's complement arithmetic testval /= xdim; testval /= ydim; testval /= zdim; if(testval<1) { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"Requested mesh size (%ld x %ld x %ld)" " has too many elements",(long)xdim, (long)ydim,(long)zdim); throw Oxs_ExtError(this,buf); } xydim = xdim*ydim; elementcount = xydim*zdim; if( fabs(xdim*cellsize.x - xrange) > 0.01*cellsize.x || fabs(ydim*cellsize.y - yrange) > 0.01*cellsize.y || fabs(zdim*cellsize.z - zrange) > 0.01*cellsize.z ) { String msg = String("Invalid MIF input block detected for object ") + String(InstanceName()) + String(": range is not an integral multiple of cellsize."); throw Oxs_ExtError(msg.c_str()); } } // Main constructor, for use by Specify command in MIF input file Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh (const char* name, // Child instance id Oxs_Director* newdtr, // App director const char* argstr) // MIF input block parameters : Oxs_Mesh(name,newdtr,argstr) { // Process arguments cellsize = GetThreeVectorInitValue("cellsize"); Oxs_OwnedPointer<Oxs_Atlas> atlas; OXS_GET_INIT_EXT_OBJECT("atlas",Oxs_Atlas,atlas); Oxs_Box box; atlas->GetWorldExtents(box); InitScaling(box); } // Secondary constructor; provides a function-level API // for use by other Oxs_Ext objects. Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh (const char* name, // Child instance id Oxs_Director* newdtr, // App director const char* argstr, // MIF input block parameters const ThreeVector& in_cellsize, const Oxs_Box& range_box) : Oxs_Mesh(name,newdtr,argstr) { cellsize = in_cellsize; InitScaling(range_box); } ///////////////////////////////////////////////////////////////////// // Constructor for internal use by MakeRefinedMesh member function. Oxs_CommonRectangularMesh::Oxs_CommonRectangularMesh (const char* name, // Child instance id Oxs_Director* newdtr, // App director const ThreeVector& in_base, const ThreeVector& in_cellsize, OC_INDEX in_xdim,OC_INDEX in_ydim,OC_INDEX in_zdim) : Oxs_Mesh(name,newdtr), base(in_base),cellsize(in_cellsize), xdim(in_xdim),ydim(in_ydim),zdim(in_zdim) { if(cellsize.x<=0.0 || cellsize.y<=0.0 || cellsize.z<=0.0) { String msg = String("Invalid cellsize data in constructor of" " refined rectangular mesh object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } cellvolume=cellsize.x*cellsize.y*cellsize.z; if(xdim<1 || ydim<1 || zdim<1) { String msg = String("Invalid x/y/zdim data in constructor of" " refined rectangular mesh object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } // Overflow test; restrict to signed value range OC_INDEX testval = OC_INDEX((OC_UINDEX(1)<<(sizeof(OC_INDEX)*8-1))-1); /// Maximum allowed value; Assumes 2's complement arithmetic testval /= xdim; testval /= ydim; testval /= zdim; if(testval<1) { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"Requested refined mesh size" " (%lu x %lu x %lu)" " has too many elements",(unsigned long)xdim, (unsigned long)ydim,(unsigned long)zdim); throw Oxs_ExtError(this,buf); } xydim = xdim*ydim; elementcount = xydim*zdim; } void Oxs_CommonRectangularMesh::GetBoundingBox(Oxs_Box& bbox) const { bbox.Set(base.x-cellsize.x/2., base.x-cellsize.x/2.+xdim*cellsize.x, base.y-cellsize.y/2., base.y-cellsize.y/2.+ydim*cellsize.y, base.z-cellsize.z/2., base.z-cellsize.z/2.+zdim*cellsize.z); } void Oxs_CommonRectangularMesh::Center(OC_INDEX index,ThreeVector &location) const { #ifndef NDEBUG if(index>elementcount) { String msg = String("Index out of range " "(Oxs_CommonRectangularMesh::Location(OC_INDEX) const)"); throw Oxs_ExtError(msg.c_str()); } #endif OC_INDEX iz = index/(xdim*ydim); index -= iz*xdim*ydim; OC_INDEX iy = index/xdim; index -= iy*xdim; OC_INDEX ix = index; location.Set(base.x+ix*cellsize.x, base.y+iy*cellsize.y, base.z+iz*cellsize.z); return; } OC_INDEX Oxs_CommonRectangularMesh::FindNearestIndex(const ThreeVector& location) const { // Note: This code assumes cellsize.{x,y,z} are all > 0. ThreeVector pt = location - base; OC_INDEX ix=0; if(pt.x>0) { ix = static_cast<OC_INDEX>(OC_ROUND(pt.x / cellsize.x)); if(ix>=xdim) ix = xdim-1; } OC_INDEX iy=0; if(pt.y>0) { iy = static_cast<OC_INDEX>(OC_ROUND(pt.y / cellsize.y)); if(iy>=ydim) iy = ydim-1; } OC_INDEX iz=0; if(pt.z>0) { iz = static_cast<OC_INDEX>(OC_ROUND(pt.z / cellsize.z)); if(iz>=zdim) iz = zdim-1; } return Index(ix,iy,iz); } OC_BOOL Oxs_CommonRectangularMesh::GetNeighborPoint (const ThreeVector& pt, OC_INDEX ngbr_index, ThreeVector& ngbr_pt) const { // Fills ngbr_pt with location of neighbor element indexed // by "ngbr_index", relative to pt. Returns 1 if // ngbr_pt < number of neighbors (currently 6); otherwise // 0 is returned, in which case ngbr_pt is unchanged. // NB: ngbr_index is 0-based. if(ngbr_index>5) return 0; int sign = 1 - 2*(ngbr_index%2); // 0,2,4 => +1, 1,3,5 => -1 ngbr_pt = pt; switch(ngbr_index/2) { case 0: ngbr_pt.x += sign*cellsize.x; break; case 1: ngbr_pt.y += sign*cellsize.y; break; default: ngbr_pt.z += sign*cellsize.z; break; } return 1; } OC_INDEX Oxs_CommonRectangularMesh::BoundaryList (const Oxs_Atlas& atlas, const String& region_name, const Oxs_ScalarField& bdry_surface, OC_REAL8m bdry_value, const String& bdry_side, vector<OC_INDEX> &BoundaryIndexList) const { // Boundary extraction. Returns list (technically, an STL vector) of // indices for those elements inside base_region that have a neighbor // (in the 6 nearest ngbr sense) such that the first element lies on // one side (the "inside") of the surface specified by the // Oxs_ScalarField bdry_surface + bdry_value, and the neighbor lies on // the other (the "outside"). If the bdry_side argument is "<" or // "<=", then the "inside" of the surface is the set of those points x // for which bdry_surface.Value(x) < or <= (resp.) bdry_value. The // bdry_side arguments ">" and ">=" are treated analogously. For // backwards compatibility, "-" and "+" are accepted as synonyms for // <= and >=, respectively. // Return value is the number of entries in the export list. // NB: The tested neighbors may lie outside the mesh proper, allowing // elements on the edge of the mesh to be specified. BoundaryIndexList.clear(); Oxs_Box world_box,work_box; GetBoundingBox(world_box); const OC_INDEX region_id = atlas.GetRegionId(region_name); if(region_id<0) { String msg=String("Region name ") + region_name + String(" not recognized by atlas ") + String(atlas.InstanceName()) + String(" (Oxs_CommonRectangularMesh::BoundaryList() in object") + String(InstanceName()) + String(")."); msg += String(" Known regions:"); vector<String> regions; atlas.GetRegionList(regions); for(unsigned int j=0;j<regions.size();++j) { msg += String("\n "); msg += regions[j]; } throw Oxs_ExtError(msg); } atlas.GetRegionExtents(region_id,work_box); work_box.Intersect(world_box); // work_box contains extents of /// base_region contained inside mesh OC_INDEX ixstart = OC_INDEX(ceil((work_box.GetMinX()-base.x)/cellsize.x)); OC_INDEX iystart = OC_INDEX(ceil((work_box.GetMinY()-base.y)/cellsize.y)); OC_INDEX izstart = OC_INDEX(ceil((work_box.GetMinZ()-base.z)/cellsize.z)); OC_INDEX ixstop = OC_INDEX(floor((work_box.GetMaxX()-base.x)/cellsize.x))+1; OC_INDEX iystop = OC_INDEX(floor((work_box.GetMaxY()-base.y)/cellsize.y))+1; OC_INDEX izstop = OC_INDEX(floor((work_box.GetMaxZ()-base.z)/cellsize.z))+1; // Check sign enum BdrySide { INVALID, LT, LE, GE, GT }; BdrySide side_check = INVALID; if(bdry_side.compare("<")==0) side_check = LT; else if(bdry_side.compare("<=")==0) side_check = LE; else if(bdry_side.compare(">=")==0) side_check = GE; else if(bdry_side.compare(">")==0) side_check = GT; else if(bdry_side.compare("+")==0) side_check = GE; else if(bdry_side.compare("-")==0) side_check = LE; else { String msg=String("Invalid boundary side representation: ") + bdry_side + String(" Should be one of <, <=, >=, or >.") + String(" (Oxs_CommonRectangularMesh::BoundaryList() in object") + String(InstanceName()) + String(")"); throw Oxs_ExtError(msg.c_str()); } const int check_sign = (side_check == LT || side_check == LE ? -1 : 1); const int equal_check = (side_check == LE || side_check == GE ? 1 : 0); OC_INDEX ixsize = ixstop-ixstart; for(OC_INDEX iz=izstart;iz<izstop;iz++) { for(OC_INDEX iy=iystart;iy<iystop;iy++) { OC_INDEX row_index = Index(ixstart,iy,iz); ThreeVector pt; Center(row_index,pt); for(OC_INDEX i=0; i<ixsize; ++i,pt.x+=cellsize.x) { if(check_sign*(bdry_surface.Value(pt)-bdry_value)<0 || (!equal_check && bdry_surface.Value(pt) == bdry_value)) { continue; // basept on wrong side of boundary } if(atlas.GetRegionId(pt) != region_id) { continue; // Point not in specified region } OC_INDEX ngbr_index=0; ThreeVector ngbr_pt; while(GetNeighborPoint(pt,ngbr_index++,ngbr_pt)) { if(check_sign*(bdry_surface.Value(ngbr_pt)-bdry_value)<0 || (!equal_check && bdry_surface.Value(ngbr_pt) == bdry_value)) { // Neighbor on "other" side of boundary BoundaryIndexList.push_back(row_index+i); break; // Don't include pt more than once } } } } } return static_cast<OC_INDEX>(BoundaryIndexList.size()); } // File (channel) output for ThreeVectors. Throws an exception on error. void Oxs_CommonRectangularMesh::WriteOvf (Tcl_Channel channel, // Output channel OC_BOOL headers, // If false, then output only raw data const char* title, // Long filename or title const char* desc, // Description to embed in output file const char* valueunit, // Field units, such as "A/m". const char* meshtype, // Either "rectangular" or "irregular" const char* datatype, // Either "binary" or "text" const char* precision, // For binary, "4" or "8"; /// for text, a printf-style format const Oxs_MeshValue<ThreeVector>* vec, // Vector array const Oxs_MeshValue<OC_REAL8m>* scale // Optional scaling for vec /// Set scale to NULL to use vec values directly. ) const { // Use default file writer for irregular mesh. if(strcmp("irregular",meshtype)==0) { ThreeVector stephints(cellsize.x,cellsize.y,cellsize.z); WriteOvfIrregular(channel,headers,title,desc,valueunit, datatype,precision, vec,scale,&stephints); return; } if(strcmp("rectangular",meshtype)!=0) { String msg=String("Unrecognized mesh type request: ") + String(meshtype) + String("(Oxs_CommonRectangularMesh::WriteOvf() in object") + String(InstanceName()) + String(")"); OXS_EXTTHROW(Oxs_BadParameter,msg.c_str(),-1); } // Rectangular Mesh //////////////////////////// // Check import validity enum DataType { BINARY, TEXT }; DataType dt = BINARY; if(strcmp("text",datatype)==0) { dt = TEXT; } else if(strcmp("binary",datatype)!=0){ String errmsg = String("Bad datatype: \"") + String(datatype) + String("\" Should be either \"binary\" or \"text\""); OXS_EXTTHROW(Oxs_BadParameter,errmsg.c_str(),-1); } int datawidth = 0; String dataformat; if(dt == BINARY) { datawidth = atoi(precision); if(datawidth != 4 && datawidth != 8) { String errmsg = String("Bad precision: ") + String(precision) + String(" Should be either 4 or 8."); OXS_EXTTHROW(Oxs_BadParameter,errmsg.c_str(),-1); } } else { if(precision==NULL || precision[0]=='\0') precision="%# .17g"; // Default format String temp = String(precision) + String(" "); dataformat = temp + temp + String(precision) + String("\n"); } if(!vec->CheckMesh(this)) { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"Size mismatch; input data length=%u," " which is different than mesh size=%u", vec->Size(),Size()); OXS_EXTTHROW(Oxs_BadParameter,buf,-1); } if(scale!=NULL && !scale->CheckMesh(this)) { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"Size mismatch; input scale data length=%u," " which is different than mesh size=%u", scale->Size(),Size()); OXS_EXTTHROW(Oxs_BadParameter,buf,-1); } if(headers) { try { // Write header Nb_FprintfChannel(channel,NULL,1024,"# OOMMF: rectangular mesh v1.0\n"); Nb_FprintfChannel(channel,NULL,1024,"# Segment count: 1\n"); Nb_FprintfChannel(channel,NULL,1024,"# Begin: Segment\n"); Nb_FprintfChannel(channel,NULL,1024,"# Begin: Header\n"); if(title==NULL || title[0]=='\0') Nb_FprintfChannel(channel,NULL,1024,"# Title: unknown\n"); else Nb_FprintfChannel(channel,NULL,1024,"# Title: %s\n",title); if(desc!=NULL && desc[0]!='\0') { // Print out description, breaking at newlines as necessary. // Note: This block is optional const char *cptr1,*cptr2; cptr1=desc; while((cptr2=strchr(cptr1,'\n'))!=NULL) { Nb_FprintfChannel(channel,NULL,1024,"# Desc: %.*s\n", (int)(cptr2-cptr1),cptr1); cptr1=cptr2+1; } if(*cptr1!='\0') Nb_FprintfChannel(channel,NULL,1024,"# Desc: %s\n",cptr1); } Nb_FprintfChannel(channel,NULL,1024,"# meshtype: rectangular\n"); Nb_FprintfChannel(channel,NULL,1024,"# meshunit: m\n"); Nb_FprintfChannel(channel,NULL,1024,"# xbase: %.17g\n" "# ybase: %.17g\n# zbase: %.17g\n", static_cast<double>(base.x), static_cast<double>(base.y), static_cast<double>(base.z)); Nb_FprintfChannel(channel,NULL,1024,"# xstepsize: %.17g\n" "# ystepsize: %.17g\n# zstepsize: %.17g\n", static_cast<double>(cellsize.x), static_cast<double>(cellsize.y), static_cast<double>(cellsize.z)); Nb_FprintfChannel(channel,NULL,1024,"# xnodes: %d\n" "# ynodes: %d\n# znodes: %d\n", xdim,ydim,zdim); Oxs_Box bbox; GetBoundingBox(bbox); Nb_FprintfChannel(channel,NULL,1024, "# xmin: %.17g\n# ymin: %.17g\n# zmin: %.17g\n" "# xmax: %.17g\n# ymax: %.17g\n# zmax: %.17g\n", static_cast<double>(bbox.GetMinX()), static_cast<double>(bbox.GetMinY()), static_cast<double>(bbox.GetMinZ()), static_cast<double>(bbox.GetMaxX()), static_cast<double>(bbox.GetMaxY()), static_cast<double>(bbox.GetMaxZ())); Nb_FprintfChannel(channel,NULL,1024,"# valueunit: %s\n",valueunit); Nb_FprintfChannel(channel,NULL,1024,"# valuemultiplier: 1\n"); // As of 6/2001, mmDisp supports display of out-of-plane rotations; // Representing the boundary under these conditions is awkward with // a single polygon. So don't write the boundary line, and rely // on defaults based on the data range and step size. OC_REAL8m minmag=0,maxmag=0; if(Size()>0) { minmag=DBL_MAX; for(OC_INDEX i=0;i<Size();i++) { OC_REAL8m val=(*vec)[i].MagSq(); if(scale!=NULL) { OC_REAL8m tempscale=(*scale)[i]; val*=tempscale*tempscale; } if(val<minmag && val>0) minmag=val; // minmag is smallest non-zero if(val>maxmag) maxmag=val; /// magnitude. } if(minmag>maxmag) minmag=maxmag; maxmag=sqrt(maxmag); minmag=sqrt(minmag); minmag*=0.9999; // Underestimate lower bound by 0.01% to protect /// against rounding errors. } Nb_FprintfChannel(channel,NULL,1024, "# ValueRangeMinMag: %.17g\n", static_cast<double>(minmag)); Nb_FprintfChannel(channel,NULL,1024, "# ValueRangeMaxMag: %.17g\n", static_cast<double>(maxmag)); Nb_FprintfChannel(channel,NULL,1024,"# End: Header\n"); } catch(...) { OXS_EXTTHROW(Oxs_DeviceFull, "Error writing OVF file header;" " disk full or buffer overflow?",-1); } } // Write data block try { if(dt == BINARY) { if(datawidth==4) { OC_REAL4 buf[3]; if(headers) { Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Binary 4\n"); buf[0]=1234567.; // 4-Byte checkvalue if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,1)) { throw Oxs_CommonRectangularMesh_WBError(); } } OC_INDEX size=Size(); for(OC_INDEX i=0 ; i<size ; ++i) { const ThreeVector& v = (*vec)[i]; if(scale==NULL) { buf[0] = static_cast<OC_REAL4>(v.x); buf[1] = static_cast<OC_REAL4>(v.y); buf[2] = static_cast<OC_REAL4>(v.z); } else { OC_REAL8m tempscale=(*scale)[i]; buf[0] = static_cast<OC_REAL4>(tempscale*v.x); buf[1] = static_cast<OC_REAL4>(tempscale*v.y); buf[2] = static_cast<OC_REAL4>(tempscale*v.z); } // Vf_OvfFileFormatSpecs::WriteBinary performs // byte-swapping as needed. if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,3)) { throw Oxs_CommonRectangularMesh_WBError(); } } if(headers) { Nb_FprintfChannel(channel,NULL,1024,"\n# End: Data Binary 4\n"); } } else { // datawidth==8 OC_REAL8 buf[3]; if(headers) { Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Binary 8\n"); buf[0]=123456789012345.; // 8-Byte checkvalue if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,1)) { throw Oxs_CommonRectangularMesh_WBError(); } } OC_INDEX size=Size(); for(OC_INDEX i=0 ; i<size ; ++i) { const ThreeVector& v = (*vec)[i]; if(scale==NULL) { buf[0] = static_cast<OC_REAL8>(v.x); buf[1] = static_cast<OC_REAL8>(v.y); buf[2] = static_cast<OC_REAL8>(v.z); } else { OC_REAL8m tempscale=(*scale)[i]; buf[0] = static_cast<OC_REAL8>(tempscale*v.x); buf[1] = static_cast<OC_REAL8>(tempscale*v.y); buf[2] = static_cast<OC_REAL8>(tempscale*v.z); } // Vf_OvfFileFormatSpecs::WriteBinary performs // byte-swapping as needed. if(Vf_OvfFileFormatSpecs::WriteBinary(channel,buf,3)) { throw Oxs_CommonRectangularMesh_WBError(); } } if(headers) { Nb_FprintfChannel(channel,NULL,1024,"\n# End: Data Binary 8\n"); } } } else { if(headers) { Nb_FprintfChannel(channel,NULL,1024,"# Begin: Data Text\n"); } OC_INDEX size=Size(); for(OC_INDEX i=0 ; i<size ; ++i) { const ThreeVector& v = (*vec)[i]; if(scale==NULL) { Nb_FprintfChannel(channel,NULL,1024,dataformat.c_str(), static_cast<double>(v.x), static_cast<double>(v.y), static_cast<double>(v.z)); } else { OC_REAL8m tempscale=(*scale)[i]; Nb_FprintfChannel(channel,NULL,1024,dataformat.c_str(), static_cast<double>(tempscale*v.x), static_cast<double>(tempscale*v.y), static_cast<double>(tempscale*v.z)); } } if(headers) { Nb_FprintfChannel(channel,NULL,1024,"# End: Data Text\n"); } } if(headers) { Nb_FprintfChannel(channel,NULL,1024,"# End: Segment\n"); } } catch(Oxs_CommonRectangularMesh_WBError&) { OXS_EXTTHROW(Oxs_DeviceFull, "Error writing OVF file binary data block;" " disk full?",-1); } catch(...) { OXS_EXTTHROW(Oxs_DeviceFull, "Error writing OVF file data block;" " disk full or buffer overflow?",-1); } } //////////////////////////////////////////////////////////////////// // Geometry string from common rectangular mesh interface. String Oxs_CommonRectangularMesh::GetGeometryString() const { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"%ld x %ld x %ld = %ld cells", (long)xdim,(long)ydim,(long)zdim,(long)Size()); return String(buf); } ///////////////////////////////////////////////////////////////// // Vf_Ovf20_MeshNodes interface function DumpGeometry. void Oxs_CommonRectangularMesh::DumpGeometry (Vf_Ovf20FileHeader& header, Vf_Ovf20_MeshType type) const { if(type == vf_ovf20mesh_irregular) { DumpIrregGeometry(header); header.xstepsize.Set(cellsize.x); header.ystepsize.Set(cellsize.y); header.zstepsize.Set(cellsize.z); if(!header.IsValidGeom()) { String msg=String("Invalid header (irregular mesh type) in" " Oxs_CommonRectangularMesh::DumpGeometry()" " in object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } return; } if(type != vf_ovf20mesh_rectangular) { String msg=String("Unrecognized mesh type request in" " Oxs_CommonRectangularMesh::DumpGeometry()" " in object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } header.meshtype.Set(vf_ovf20mesh_rectangular); header.meshunit.Set(String("m")); Oxs_Box bbox; GetBoundingBox(bbox); header.xmin.Set(bbox.GetMinX()); header.ymin.Set(bbox.GetMinY()); header.zmin.Set(bbox.GetMinZ()); header.xmax.Set(bbox.GetMaxX()); header.ymax.Set(bbox.GetMaxY()); header.zmax.Set(bbox.GetMaxZ()); header.xbase.Set(base.x); header.ybase.Set(base.y); header.zbase.Set(base.z); header.xnodes.Set(xdim); header.ynodes.Set(ydim); header.znodes.Set(zdim); header.xstepsize.Set(cellsize.x); header.ystepsize.Set(cellsize.y); header.zstepsize.Set(cellsize.z); if(!header.IsValidGeom()) { String msg=String("Invalid header (rectangular mesh type) in" " Oxs_CommonRectangularMesh::DumpGeometry()" " in object ") + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } } ////////////////////////////////////////////////////////////////////// // Conversion routines from Vf_Mesh to Oxs_MeshValue<ThreeVector>. // IsCompatible returns true iff vfmesh is a Vf_GridVec3f with // dimensions identical to those of *this. // NB: IsCompatible only compares the mesh dimensions, not the // underlying physical scale, or the cell aspect ratios. Do // we want to include such a check?, or is it more flexible // to leave it out? // FillMeshValueExact copies the vector field held in vfmesh to the // export Oxs_MeshValue<ThreeVector> vec. This routine throws // an exception on error, the primary cause of which is that // vfmesh is not compatible with *this. In other words, if you // don't want to catch the exception, call IsCompatible first. // The "Exact" in the name refers to the requirement that the // dimensions on vfmesh exactly match those of *this. OC_BOOL Oxs_CommonRectangularMesh::IsCompatible(const Vf_Mesh* vfmesh) const { const Vf_GridVec3f* gridmesh = dynamic_cast<const Vf_GridVec3f*>(vfmesh); if(gridmesh==NULL) return 0; OC_INDEX isize,jsize,ksize; gridmesh->GetDimens(isize,jsize,ksize); if(xdim != isize || ydim != jsize || zdim != ksize ) { return 0; } return 1; } void Oxs_CommonRectangularMesh::FillMeshValueExact (const Vf_Mesh* vfmesh, Oxs_MeshValue<ThreeVector>& vec) const { const Vf_GridVec3f* gridmesh = dynamic_cast<const Vf_GridVec3f*>(vfmesh); if(gridmesh==NULL || !IsCompatible(vfmesh)) { throw Oxs_ExtError(this, "Incompatible Vf_Mesh import to" " FillMeshValue(const Vf_Mesh*," " Oxs_MeshValue<ThreeVector>&)"); } vec.AdjustSize(this); // Both Oxs_CommonRectangularMesh and Vf_GridVec3f access with the // x-dimension index changing fastest, z-dimension index changing // slowest. OC_INDEX i,j,k; OC_REAL8m scale = gridmesh->GetValueMultiplier(); if(scale==1.0) { // Common case? for(k=0;k<zdim;++k) for(j=0;j<ydim;++j) for(i=0;i<xdim;++i) { const Nb_Vec3<OC_REAL8>& nbvec = gridmesh->GridVec(i,j,k); vec[Index(i,j,k)].Set(nbvec.x,nbvec.y,nbvec.z); } } else { for(k=0;k<zdim;++k) for(j=0;j<ydim;++j) for(i=0;i<xdim;++i) { const Nb_Vec3<OC_REAL8>& nbvec = gridmesh->GridVec(i,j,k); vec[Index(i,j,k)].Set(scale*nbvec.x, scale*nbvec.y, scale*nbvec.z); } } } ////////////////////////////////////////////////////////////////////// // Volume summing routines. This have advantage over the generic // in that for Oxs_CommonRectangularMesh all cells have same volume. OC_REAL8m Oxs_CommonRectangularMesh::VolumeSum (const Oxs_MeshValue<OC_REAL8m>& scalar) const { if(!scalar.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible scalar array import to" " VolumeSum(const Oxs_MeshValue<OC_REAL8m>&)"); } const OC_INDEX size=Size(); OC_REAL8m sum=0.0; for(OC_INDEX i=0;i<size;i++) sum += scalar[i]; sum *= cellvolume; return sum; } ThreeVector Oxs_CommonRectangularMesh::VolumeSum (const Oxs_MeshValue<ThreeVector>& vec) const { if(!vec.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " VolumeSum(const Oxs_MeshValue<ThreeVector>&)"); } const OC_INDEX size=Size(); ThreeVector sum(0.,0.,0.); for(OC_INDEX i=0;i<size;i++) sum += vec[i] ; sum *= cellvolume; return sum; } ThreeVector Oxs_CommonRectangularMesh::VolumeSum (const Oxs_MeshValue<ThreeVector>& vec, const Oxs_MeshValue<OC_REAL8m>& scale ) const { if(!vec.CheckMesh(this) || !scale.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " VolumeSum(const Oxs_MeshValue<ThreeVector>&," " const Oxs_MeshValue<OC_REAL8m>& scale)"); } const OC_INDEX size=Size(); ThreeVector sum(0.,0.,0.); for(OC_INDEX i=0;i<size;i++) { sum += scale[i] * vec[i]; } sum *= cellvolume; return sum; } OC_REAL8m Oxs_CommonRectangularMesh::VolumeSumXp (const Oxs_MeshValue<OC_REAL8m>& scalar) const { if(!scalar.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible scalar array import to" " VolumeSumXp(const Oxs_MeshValue<OC_REAL8m>&)"); } Nb_Xpfloat sum=0.; const OC_INDEX size=Size(); for(OC_INDEX i=0;i<size;i++) sum += scalar[i]; sum *= cellvolume; return sum.GetValue(); } ThreeVector Oxs_CommonRectangularMesh::VolumeSumXp (const Oxs_MeshValue<ThreeVector>& vec) const { if(!vec.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " VolumeSumXp(const Oxs_MeshValue<ThreeVector>&)"); } Nb_Xpfloat sum_x=0.,sum_y=0.,sum_z=0.; const OC_INDEX size=Size(); for(OC_INDEX i=0;i<size;i++) { sum_x += vec[i].x; sum_y += vec[i].y; sum_z += vec[i].z; } sum_x *= cellvolume; sum_y *= cellvolume; sum_z *= cellvolume; return ThreeVector(sum_x.GetValue(),sum_y.GetValue(),sum_z.GetValue()); } ThreeVector Oxs_CommonRectangularMesh::VolumeSumXp (const Oxs_MeshValue<ThreeVector>& vec, const Oxs_MeshValue<OC_REAL8m>& scale ) const { if(!vec.CheckMesh(this) || !scale.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " VolumeSumXp(const Oxs_MeshValue<ThreeVector>&," " const Oxs_MeshValue<OC_REAL8m>& scale)"); } Nb_Xpfloat sum_x=0.,sum_y=0.,sum_z=0.; const OC_INDEX size=Size(); for(OC_INDEX i=0;i<size;i++) { OC_REAL8m wgt = scale[i]; sum_x += wgt*vec[i].x; sum_y += wgt*vec[i].y; sum_z += wgt*vec[i].z; } sum_x *= cellvolume; sum_y *= cellvolume; sum_z *= cellvolume; return ThreeVector(sum_x.GetValue(),sum_y.GetValue(),sum_z.GetValue()); } ///////////////////////////////////////////////////////////////////// // Oxs_RectangularMesh (non-periodic) // Main constructor, for use by Specify command in MIF input file Oxs_RectangularMesh::Oxs_RectangularMesh (const char* name, // Child instance id Oxs_Director* newdtr, // App director const char* argstr) // MIF input block parameters : Oxs_CommonRectangularMesh(name,newdtr,argstr) { VerifyAllInitArgsUsed(); } void Oxs_RectangularMesh::MakeRefinedMesh (const char* name, OC_INDEX refine_x,OC_INDEX refine_y,OC_INDEX refine_z, Oxs_OwnedPointer<Oxs_RectangularMesh>& out_mesh) const { if(refine_x<1 || refine_y<1 || refine_z<1) { char buf[1024]; Oc_Snprintf(buf,sizeof(buf),"Invalid refinment request:" " (%lu x %lu x %lu)" " All refinement values must be >=1;" " Error in MakeRefinedMesh function in" " rectangular mesh object ", (unsigned long)refine_x, (unsigned long)refine_y, (unsigned long)refine_z); String msg = String(buf) + String(InstanceName()); throw Oxs_ExtError(msg.c_str()); } ThreeVector new_cellsize = GetCellsize(); new_cellsize.x /= static_cast<OC_REAL8m>(refine_x); new_cellsize.y /= static_cast<OC_REAL8m>(refine_y); new_cellsize.z /= static_cast<OC_REAL8m>(refine_z); ThreeVector new_base = GetBase(); new_base.Accum(-0.5,GetCellsize()); new_base.Accum( 0.5,new_cellsize); Oxs_RectangularMesh *refined_mesh = new Oxs_RectangularMesh(name,director,new_base,new_cellsize, refine_x*DimX(), refine_y*DimY(), refine_z*DimZ()); out_mesh.SetAsOwner(refined_mesh); } // Max angle routine. This routine returns the maximum angle // between neighboring vectors across the mesh, for all // those vectors for which the corresponding entry in zero_check // is non-zero. OC_REAL8m Oxs_RectangularMesh::MaxNeighborAngle (const Oxs_MeshValue<ThreeVector>& vec, const Oxs_MeshValue<OC_REAL8m>& zero_check, OC_INDEX node_start,OC_INDEX node_stop) const { if(!vec.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " MaxNeighborAngle(const Oxs_MeshValue<ThreeVector>&," " const Oxs_MeshValue<OC_REAL8m>& scale)"); } if(Size()<2) return 0.0; OxsRectangularMeshAngle maxangX(0.0); // 0.0 is min possible angle OxsRectangularMeshAngle maxangY(0.0); OxsRectangularMeshAngle maxangZ(0.0); const OC_INDEX dimx = DimX(); // For convenience const OC_INDEX dimy = DimY(); // For convenience const OC_INDEX dimz = DimZ(); // For convenience const OC_INDEX dimxy = dimx*dimy; OC_INDEX ix,iy,iz; GetCoords(node_start,ix,iy,iz); for(OC_INDEX index=node_start;index<node_stop;++index) { if(zero_check[index]!=0.0) { if(ix+1<dimx && zero_check[index+1]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+1]); if(test>maxangX) maxangX = test; } if(iy+1<dimy && zero_check[index+dimx]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+dimx]); if(test>maxangY) maxangY = test; } if(iz+1<dimz && zero_check[index+dimxy]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+dimxy]); if(test>maxangZ) maxangZ = test; } } if(++ix >= dimx) { ix=0; if(++iy >= dimy) { iy=0; ++iz; } } } if(maxangY > maxangX) maxangX = maxangY; if(maxangZ > maxangX) maxangX = maxangZ; return maxangX.GetAngle(); } ///////////////////////////////////////////////////////////////////// // Oxs_PeriodicRectangularMesh // Main constructor, for use by Specify command in MIF input file Oxs_PeriodicRectangularMesh::Oxs_PeriodicRectangularMesh (const char* name, // Child instance id Oxs_Director* newdtr, // App director const char* argstr) // MIF input block parameters : Oxs_CommonRectangularMesh(name,newdtr,argstr), xperiodic(0),yperiodic(0),zperiodic(0) { // Periodic boundary selection. String periodic = GetStringInitValue("periodic"); int badbits=0; for(size_t i=0;i<periodic.size();++i) { switch(tolower(periodic[i])) { case 'x': xperiodic=1; break; case 'y': yperiodic=1; break; case 'z': zperiodic=1; break; default: ++badbits; break; } } if(badbits>0) { String msg=String("Invalid periodic request string: ") + periodic + String("\n Should be a non-empty subset of \"xyz\"."); throw Oxs_ExtError(this,msg.c_str()); } if(xperiodic+yperiodic+zperiodic==0) { String msg=String("Invalid periodic request string ---" " no periodic directions requested. " " For non-periodic systems use" " Oxs_RectangularMesh."); throw Oxs_ExtError(this,msg.c_str()); } VerifyAllInitArgsUsed(); } // Max angle routine. This routine returns the maximum angle // between neighboring vectors across the mesh, for all // those vectors for which the corresponding entry in zero_check // is non-zero. OC_REAL8m Oxs_PeriodicRectangularMesh::MaxNeighborAngle (const Oxs_MeshValue<ThreeVector>& vec, const Oxs_MeshValue<OC_REAL8m>& zero_check, OC_INDEX node_start,OC_INDEX node_stop) const { if(!vec.CheckMesh(this)) { throw Oxs_ExtError(this, "Incompatible import array to" " MaxNeighborAngle(const Oxs_MeshValue<ThreeVector>&," " const Oxs_MeshValue<OC_REAL8m>& scale)"); } if(Size()<2) return 0.0; OxsRectangularMeshAngle maxangX(0.0); // 0.0 is min possible angle OxsRectangularMeshAngle maxangY(0.0); OxsRectangularMeshAngle maxangZ(0.0); const OC_INDEX dimx = DimX(); // For convenience const OC_INDEX dimy = DimY(); // For convenience const OC_INDEX dimz = DimZ(); // For convenience const OC_INDEX dimxy = dimx*dimy; const OC_INDEX zwrap = (dimz-1)*dimxy; OC_INDEX ix,iy,iz; GetCoords(node_start,ix,iy,iz); for(OC_INDEX index=node_start;index<node_stop;++index) { if(zero_check[index]!=0.0) { if(ix+1<dimx) { if(zero_check[index+1]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+1]); if(test>maxangX) maxangX = test; } } else if(xperiodic && zero_check[index+1-dimx]!=0) { OxsRectangularMeshAngle test(vec[index],vec[index+1-dimx]); if(test>maxangX) maxangX = test; } if(iy+1<dimy) { if(zero_check[index+dimx]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+dimx]); if(test>maxangY) maxangY = test; } } else if(yperiodic && zero_check[index+dimx-dimxy]!=0) { OxsRectangularMeshAngle test(vec[index],vec[index+dimx-dimxy]); if(test>maxangY) maxangY = test; } if(iz+1<dimz) { if(zero_check[index+dimxy]!=0.0) { OxsRectangularMeshAngle test(vec[index],vec[index+dimxy]); if(test>maxangZ) maxangZ = test; } } else if(zperiodic && zero_check[index-zwrap]!=0) { OxsRectangularMeshAngle test(vec[index],vec[index-zwrap]); if(test>maxangZ) maxangZ = test; } } if(++ix >= dimx) { ix=0; if(++iy >= dimy) { iy=0; ++iz; } } } if(maxangY > maxangX) maxangX = maxangY; if(maxangZ > maxangX) maxangX = maxangZ; return maxangX.GetAngle(); }
41,186
14,958
#include "Arduino.h" #include "ClassName.h" // class constructor ClassName::ClassName(int pin) { //pinMode(pin, OUTPUT); _pin = pin; } void ClassName::dot() { //digitalWrite(_pin, HIGH); delay(10); //digitalWrite(_pin, LOW); //delay(250); } void ClassName::dash() { //digitalWrite(_pin, HIGH); delay(10); //digitalWrite(_pin, LOW); //delay(250); }
373
160
/* * Copyright (c) 2012-2013, Olivier Tilmans * * 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 "mealcalendar.h" #include <QPainter> #include <QRect> MealCalendar::MealCalendar(QWidget *parent) : QCalendarWidget(parent) { } void MealCalendar::setCurrentMonthHighlights(const QHash<int,int>& highlights) { this->highlights = QHash<int,int>(highlights); update(); } void MealCalendar::setHighlightsForDay(int day, int highlights) { this->highlights[day] = highlights; updateCell(QDate(QCalendarWidget::yearShown(), QCalendarWidget::monthShown(), day)); } void MealCalendar::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const { QCalendarWidget::paintCell(painter, rect, date); if (highlights.value(date.day()) > 0 && date.month() == QCalendarWidget::selectedDate().month()) { painter->save(); // Set background color to green because there are meal(s) that day QFontMetrics fm = painter->fontMetrics(); int w = fm.width(QString::number(highlights.value(date.day()))); int h = fm.height(); int max = qMax(w, h) + 3; QRect r = QRect(rect.x(), rect.y(), max, max); painter->setBrush(QBrush(Qt::darkCyan, Qt::SolidPattern)); painter->setPen(Qt::NoPen); painter->drawEllipse(r); painter->setBrush(Qt::NoBrush); painter->setPen(Qt::lightGray); painter->drawRect(QRect(rect.x(), rect.y(), rect.width()-1, rect.height()-1)); painter->restore(); painter->drawText(QRect(r.x(), r.y() + max/2 - h/2, max, max), QString::number(highlights.value(date.day())), QTextOption(Qt::AlignCenter)); } }
2,760
913
#include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <string.h> #include "contig_reader.h" #include "sigma.h" ContigReader::~ContigReader() {} AllReader::AllReader(){} long int AllReader::read(const char* contigs_file, ContigMap* contigs) { int length = 0; long int assembly_size = 0; std::string id; std::ifstream contigs_fp(contigs_file); if (contigs_fp.is_open()) { while(true){ std::string line; if(!std::getline(contigs_fp, line)){ if (length !=0 && length >= Sigma::contig_len_thr){ contigs -> insert(std::make_pair(id, new Contig(id, length))); // std::cerr << length << "\n"; // std::cerr << id <<"\n"; } assembly_size += length; break; } if(line[0] != '>'){ length += (int) line.size(); } else{ assembly_size += length; if (length != 0 && length >= Sigma::contig_len_thr){ contigs -> insert(std::make_pair(id, new Contig(id, length))); // std::cerr << id << "\n"; // std::cerr << length << "\n"; } id = line.substr(1, line.find(' ') - 1); length = 0; } } contigs_fp.close(); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void AllReader::get_assembly_size(const char* contigs_file){ int length = 0; long int assembly_size = 0; long int assembly_nb_contig = 0; std::ifstream contigs_fp(contigs_file); if (contigs_fp.is_open()) { std::string line; while(true){ std::string line; if(!std::getline(contigs_fp, line)){ assembly_size+= length; break; } if(line[0] != '>'){ length += (int) line.size(); } else{ assembly_size += length; assembly_nb_contig++; length = 0; } } contigs_fp.close(); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; } SOAPdenovoReader::SOAPdenovoReader() {} long int SOAPdenovoReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n if (fscanf(contigs_fp, ">%s %*s %d %*s\n", id, &length) == 2) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void SOAPdenovoReader::get_assembly_size(const char* contigs_file) { int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n if (fscanf(contigs_fp, ">%*s %*s %d %*s\n", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; } RAYReader::RAYReader() {} long int RAYReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] [LENGTH] nucleotides\n if (fscanf(contigs_fp, ">%s %d %*s\n", id, &length) == 2) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void RAYReader::get_assembly_size(const char* contigs_file) { int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] [LENGTH] nucleotides\n if (fscanf(contigs_fp, ">%*s %d %*s\n", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; } VelvetReader::VelvetReader() {} long int VelvetReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void VelvetReader::get_assembly_size(const char* contigs_file) { char id[256]; int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; }
10,592
3,648
/** * @file tuple_tail_type.hpp * * @brief tuple_tail_type の定義 * * @author myoukaku */ #ifndef BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP #define BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP #include <bksge/fnd/tuple/fwd/tuple_tail_type_fwd.hpp> namespace bksge { /** * @brief 先頭要素を除いたTupleを返す */ template <typename Tuple> struct tuple_tail_type; } // namespace bksge #include <bksge/fnd/tuple/inl/tuple_tail_type_inl.hpp> #endif // BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP
496
263
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1996 - 1999 // // File: cjetblue.hxx // // Contents: Microsoft Internet Security Common // // History: 23-Oct-1997 pberkman created // //-------------------------------------------------------------------------- #ifndef CJETBLUE_HXX #define CJETBLUE_HXX #include "jet.h" typedef JET_ERR (JET_API *td_JetInit)(JET_INSTANCE *pinstance); typedef JET_ERR (JET_API *td_JetTerm)(JET_INSTANCE instance); typedef JET_ERR (JET_API *td_JetSetSystemParameter)(JET_INSTANCE *pinstance, JET_SESID sesid, unsigned long paramid, unsigned long lParam, const char *sz); typedef JET_ERR (JET_API *td_JetBeginSession)( JET_INSTANCE instance, JET_SESID *psesid, const char *szUserName, const char *szPassword); typedef JET_ERR (JET_API *td_JetCreateDatabase)(JET_SESID sesid, const char *szFilename, const char *szConnect, JET_DBID *pdbid, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetAttachDatabase)(JET_SESID sesid, const char *szFilename, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetDetachDatabase)(JET_SESID sesid, const char *szFilename); typedef JET_ERR (JET_API *td_JetCreateTable)(JET_SESID sesid, JET_DBID dbid, const char *szTableName, unsigned long lPages, unsigned long lDensity, JET_TABLEID *ptableid); typedef JET_ERR (JET_API *td_JetCreateTableColumnIndex)(JET_SESID sesid, JET_DBID dbid, JET_TABLECREATE *ptablecreate); typedef JET_ERR (JET_API *td_JetCloseDatabase)(JET_SESID sesid, JET_DBID dbid, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetCloseTable)(JET_SESID sesid, JET_TABLEID tableid); typedef JET_ERR (JET_API *td_JetOpenDatabase)(JET_SESID sesid, const char *szFilename, const char *szConnect, JET_DBID *pdbid, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetOpenTable)(JET_SESID sesid, JET_DBID dbid, const char *szTableName, const void *pvParameters, unsigned long cbParameters, JET_GRBIT grbit, JET_TABLEID *ptableid); typedef JET_ERR (JET_API *td_JetBeginTransaction)(JET_SESID sesid); typedef JET_ERR (JET_API *td_JetCommitTransaction)(JET_SESID sesid, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetRetrieveColumns)(JET_SESID sesid, JET_TABLEID tableid, JET_RETRIEVECOLUMN *pretrievecolumn, unsigned long cretrievecolumn); typedef JET_ERR (JET_API *td_JetSetColumns)(JET_SESID sesid, JET_TABLEID tableid, JET_SETCOLUMN *psetcolumn, unsigned long csetcolumn); typedef JET_ERR (JET_API *td_JetPrepareUpdate)(JET_SESID sesid, JET_TABLEID tableid, unsigned long prep); typedef JET_ERR (JET_API *td_JetSetCurrentIndex2)(JET_SESID sesid, JET_TABLEID tableid, const char *szIndexName, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetMove)(JET_SESID sesid, JET_TABLEID tableid, long cRow, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetMakeKey)(JET_SESID sesid, JET_TABLEID tableid, const void *pvData, unsigned long cbData, JET_GRBIT grbit); typedef JET_ERR (JET_API *td_JetSeek)(JET_SESID sesid, JET_TABLEID tableid, JET_GRBIT grbit); class cJetBlue_ { public: cJetBlue_(void); virtual ~cJetBlue_(void); protected: JET_ERR JetInit(JET_INSTANCE *pinstance); JET_ERR JetTerm(JET_INSTANCE instance); JET_ERR JetSetSystemParameter(JET_INSTANCE *pinstance, JET_SESID sesid, unsigned long paramid, unsigned long lParam, const char *sz); JET_ERR JetBeginSession(JET_INSTANCE instance, JET_SESID *psesid, const char *szUserName, const char *szPassword); JET_ERR JetCreateDatabase(JET_SESID sesid, const char *szFilename, const char *szConnect, JET_DBID *pdbid, JET_GRBIT grbit); JET_ERR JetAttachDatabase(JET_SESID sesid, const char *szFilename, JET_GRBIT grbit); JET_ERR JetDetachDatabase(JET_SESID sesid, const char *szFilename); JET_ERR JetCreateTable(JET_SESID sesid, JET_DBID dbid, const char *szTableName, unsigned long lPages, unsigned long lDensity, JET_TABLEID *ptableid); JET_ERR JetCreateTableColumnIndex(JET_SESID sesid, JET_DBID dbid, JET_TABLECREATE *ptablecreate); JET_ERR JetCloseDatabase(JET_SESID sesid, JET_DBID dbid, JET_GRBIT grbit); JET_ERR JetCloseTable(JET_SESID sesid, JET_TABLEID tableid); JET_ERR JetOpenDatabase(JET_SESID sesid, const char *szFilename, const char *szConnect, JET_DBID *pdbid, JET_GRBIT grbit); JET_ERR JetOpenTable(JET_SESID sesid, JET_DBID dbid, const char *szTableName, const void *pvParameters, unsigned long cbParameters, JET_GRBIT grbit, JET_TABLEID *ptableid); JET_ERR JetBeginTransaction(JET_SESID sesid); JET_ERR JetCommitTransaction(JET_SESID sesid, JET_GRBIT grbit); JET_ERR JetRetrieveColumns(JET_SESID sesid, JET_TABLEID tableid, JET_RETRIEVECOLUMN *pretrievecolumn, unsigned long cretrievecolumn); JET_ERR JetSetColumns(JET_SESID sesid, JET_TABLEID tableid, JET_SETCOLUMN *psetcolumn, unsigned long csetcolumn); JET_ERR JetPrepareUpdate(JET_SESID sesid, JET_TABLEID tableid, unsigned long prep); JET_ERR JetSetCurrentIndex2(JET_SESID sesid, JET_TABLEID tableid, const char *szIndexName, JET_GRBIT grbit); JET_ERR JetMove(JET_SESID sesid, JET_TABLEID tableid, long cRow, JET_GRBIT grbit); JET_ERR JetMakeKey(JET_SESID sesid, JET_TABLEID tableid, const void *pvData, unsigned long cbData, JET_GRBIT grbit); JET_ERR JetSeek(JET_SESID sesid, JET_TABLEID tableid, JET_GRBIT grbit); private: HINSTANCE hJet; td_JetInit fp_JetInit; td_JetTerm fp_JetTerm; td_JetSetSystemParameter fp_JetSetSystemParameter; td_JetBeginSession fp_JetBeginSession; td_JetCreateDatabase fp_JetCreateDatabase; td_JetAttachDatabase fp_JetAttachDatabase; td_JetDetachDatabase fp_JetDetachDatabase; td_JetCreateTable fp_JetCreateTable; td_JetCreateTableColumnIndex fp_JetCreateTableColumnIndex; td_JetCloseDatabase fp_JetCloseDatabase; td_JetCloseTable fp_JetCloseTable; td_JetOpenDatabase fp_JetOpenDatabase; td_JetOpenTable fp_JetOpenTable; td_JetBeginTransaction fp_JetBeginTransaction; td_JetCommitTransaction fp_JetCommitTransaction; td_JetRetrieveColumns fp_JetRetrieveColumns; td_JetSetColumns fp_JetSetColumns; td_JetPrepareUpdate fp_JetPrepareUpdate; td_JetSetCurrentIndex2 fp_JetSetCurrentIndex2; td_JetMove fp_JetMove; td_JetMakeKey fp_JetMakeKey; td_JetSeek fp_JetSeek; BOOL CheckOrLoadFunc(void **fp, char *pszfunc); }; #endif // CJETBLUE_HXX
8,934
2,803
//--------------------------------------------------------------------------- /* MIT LICENSE Copyright (c) 2021 Pawel Kuklik 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. */ //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma hdrstop #include "Path.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //------------------------------------------------------------------------- int Path_Class::save_object_to_stream(ofstream* File) { int Items_Number,Size; int version = 1; File->write((char*)&version, sizeof (int)); File->write((char*)&Type, sizeof (int)); File->write((char*)&x1, sizeof (double)); File->write((char*)&y1, sizeof (double)); File->write((char*)&z1, sizeof (double)); File->write((char*)&x2, sizeof (double)); File->write((char*)&y2, sizeof (double)); File->write((char*)&z2, sizeof (double)); File->write((char*)&Distance, sizeof (double)); File->write((char*)&LAT_Difference, sizeof (double)); return 1; } //------------------------------------------------------------------------- int Path_Class::load_object_from_stream(ifstream* File) { int Items_Number; int version; File->read((char*)&version, sizeof (int)); if( version == 1 ) { File->read((char*)&Type, sizeof (int)); File->read((char*)&x1, sizeof (double)); File->read((char*)&y1, sizeof (double)); File->read((char*)&z1, sizeof (double)); File->read((char*)&x2, sizeof (double)); File->read((char*)&y2, sizeof (double)); File->read((char*)&z2, sizeof (double)); File->read((char*)&Distance, sizeof (double)); File->read((char*)&LAT_Difference, sizeof (double)); } return 1; } //---------------------------------------------------------------------------
2,829
877
#include<iostream> #include<cstdio> using namespace std; int main() { int a,b; cin>>a>>b; cout<<a<<"+"<<b<<"="<<a+b<<endl; cout<<a<<"*"<<b<<"="<<a*b<<endl; cout<<a<<"/"<<b<<"="<<a/b<<endl; cout<<a<<"%"<<b<<"="<<a%b<<endl; return 0; }
271
128
/* * ostream_log_strategy.tcc * * Author: Ming Tsang * Copyright (c) 2014 Ming Tsang * Refer to LICENSE for details */ #pragma once #include <ostream> #include "libutils/io/ostream_log_strategy.h" namespace utils { namespace io { template<typename CharT_> OstreamLogStrategy<CharT_>::OstreamLogStrategy( std::basic_ostream<CharT_> *stream, const bool is_owner) : m_stream(stream), m_is_owner(is_owner) {} template<typename CharT_> OstreamLogStrategy<CharT_>::~OstreamLogStrategy() { if (m_is_owner) { delete m_stream; } } } }
552
226
// mglnrel.cpp: 实现直线位置关系函数 // Copyright (c) 2004-2012, Zhang Yungui // License: LGPL, https://github.com/rhcad/touchvg #include "mglnrel.h" // 判断点pt是否在有向直线a->b的左边 (开区间) GEOMAPI bool mgIsLeft(const Point2d& a, const Point2d& b, const Point2d& pt) { return (b-a).crossProduct(pt-a) > 0.f; } // 判断点pt是否在有向直线a->b的左边 GEOMAPI bool mgIsLeft2( const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol) { float dist = (b-a).distanceToVector(pt-a); return dist > tol.equalPoint(); } // 判断点pt是否在有向直线a->b的左边或线上 (闭区间) GEOMAPI bool mgIsLeftOn(const Point2d& a, const Point2d& b, const Point2d& pt) { return (b-a).crossProduct(pt-a) >= 0.f; } // 判断点pt是否在有向直线a->b的左边或线上 GEOMAPI bool mgIsLeftOn2( const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol) { float dist = (b-a).distanceToVector(pt-a); return dist > -tol.equalPoint(); } // 判断点pt是否在直线a->b的线上 GEOMAPI bool mgIsColinear(const Point2d& a, const Point2d& b, const Point2d& pt) { return mgIsZero((b-a).crossProduct(pt-a)); } // 判断点pt是否在直线a->b的线上 GEOMAPI bool mgIsColinear2( const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol) { float dist = (b-a).crossProduct(pt-a); return fabsf(dist) < tol.equalPoint(); } // 判断两个线段ab和cd是否相交于线段内部 GEOMAPI bool mgIsIntersectProp( const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d) { // Eliminate improper cases if (mgIsColinear(a,b,c) || mgIsColinear(a,b,d) || mgIsColinear(c,d,a) || mgIsColinear(c,d,b)) return false; return (mgIsLeft(a,b,c) ^ mgIsLeft(a,b,d)) && (mgIsLeft(c,d,a) ^ mgIsLeft(c,d,b)); } // 判断点pt是否在线段ab上(闭区间) GEOMAPI bool mgIsBetweenLine(const Point2d& a, const Point2d& b, const Point2d& pt) { if (!mgIsColinear(a, b, pt)) return false; // If ab not vertical, check betweenness on x; else on y. if (a.x != b.x) return (a.x <= pt.x && pt.x <= b.x) || (a.x >= pt.x && pt.x >= b.x); else return (a.y <= pt.y && pt.y <= b.y) || (a.y >= pt.y && pt.y >= b.y); } // 判断点pt是否在线段ab上 GEOMAPI bool mgIsBetweenLine2( const Point2d& a, const Point2d& b, const Point2d& pt, const Tol& tol) { if (!mgIsColinear2(a, b, pt, tol)) return false; // If ab not vertical, check betweenness on x; else on y. if (a.x != b.x) { return ((a.x <= pt.x + tol.equalPoint()) && (pt.x <= b.x + tol.equalPoint())) || ((a.x >= pt.x - tol.equalPoint()) && (pt.x >= b.x - tol.equalPoint())); } else { return ((a.y <= pt.y + tol.equalPoint()) && (pt.y <= b.y + tol.equalPoint())) || ((a.y >= pt.y - tol.equalPoint()) && (pt.y >= b.y - tol.equalPoint())); } } // 已知点pt在直线ab上, 判断点pt是否在线段ab上(闭区间) GEOMAPI bool mgIsBetweenLine3( const Point2d& a, const Point2d& b, const Point2d& pt, Point2d* nearpt) { bool ret; if (a.x != b.x) { ret = (a.x <= pt.x && pt.x <= b.x) || (a.x >= pt.x && pt.x >= b.x); if (nearpt != NULL) *nearpt = fabsf(pt.x - a.x) < fabsf(pt.x - b.x) ? a : b; } else { ret = (a.y <= pt.y && pt.y <= b.y) || (a.y >= pt.y && pt.y >= b.y); if (nearpt != NULL) *nearpt = fabsf(pt.y - a.y) < fabsf(pt.y - b.y) ? a : b; } return ret; } // 判断两个线段ab和cd是否相交(交点在线段闭区间内) GEOMAPI bool mgIsIntersect( const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d) { if (mgIsIntersectProp(a, b, c, d)) return true; else if (mgIsBetweenLine(a, b, c) || mgIsBetweenLine(a, b, d) || mgIsBetweenLine(c, d, a) || mgIsBetweenLine(c, d, b)) return true; else return false; } // 计算点pt到无穷直线ab的距离 GEOMAPI float mgPtToBeeline(const Point2d& a, const Point2d& b, const Point2d& pt) { float dist = (b-a).crossProduct(pt-a); return dist; } // 计算点pt到无穷直线ab的距离 GEOMAPI float mgPtToBeeline2( const Point2d& a, const Point2d& b, const Point2d& pt, Point2d& ptPerp) { // 两点重合 if (a == b) { ptPerp = a; return a.distanceTo(pt); } // 竖直线 else if (mgEquals(a.x, b.x)) { ptPerp.set(a.x, pt.y); return fabsf(a.x - pt.x); } // 水平线 else if (mgEquals(a.y, b.y)) { ptPerp.set(pt.x, a.y); return fabsf(a.y - pt.y); } else { float t1 = ( b.y - a.y ) / ( b.x - a.x ); float t2 = -1.f / t1; ptPerp.x = ( pt.y - a.y + a.x * t1 - pt.x * t2 ) / ( t1 - t2 ); ptPerp.y = a.y + (ptPerp.x - a.x) * t1; return pt.distanceTo(ptPerp); } } // 计算点pt到线段ab的最近距离 GEOMAPI float mgPtToLine( const Point2d& a, const Point2d& b, const Point2d& pt, Point2d& nearpt) { Point2d ptTemp; float dist = mgPtToBeeline2(a, b, pt, nearpt); if (!mgIsBetweenLine3(a, b, nearpt, &ptTemp)) { nearpt = ptTemp; dist = pt.distanceTo(nearpt); } return dist; } // 求两条直线(ax+by+c=0)的交点 GEOMAPI bool mgCrossLineAbc( float a1, float b1, float c1, float a2, float b2, float c2, Point2d& ptCross, const Tol& tolVec) { float sinnum, cosnum; sinnum = a1*b2 - a2*b1; if (mgIsZero(sinnum)) return false; cosnum = a1*a2 + b1*b2; if (!mgIsZero(cosnum) && fabsf(sinnum / cosnum) < tolVec.equalVector()) return false; ptCross.x = (b1*c2 - b2*c1) / sinnum; ptCross.y = (a2*c1 - a1*c2) / sinnum; return true; } // 求两条无穷直线的交点 GEOMAPI bool mgCross2Beeline( const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d, Point2d& ptCross, float* pu, float* pv, const Tol& tolVec) { float u, v, denom, cosnum; denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x); if (mgIsZero(denom)) // 平行或重合 return false; cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y); if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector()) return false; u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom; v = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom; if (pu != NULL) *pu = u; if (pv != NULL) *pv = v; ptCross.x = (1 - u) * a.x + u * b.x; ptCross.y = (1 - u) * a.y + u * b.y; return true; } // 求两条线段的交点 // 输入: (a.x,a.y),(b.x,b.y) 第一条线段上的两个点 // (c.x,c.y),(d.x,d.y) 第二条线段上的两个点 // 输出: (px, py) 交点坐标 // 返回: 有无交点 GEOMAPI bool mgCross2Line( const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d, Point2d& ptCross, const Tol& tolVec) { float u, v, denom, cosnum; if (mgMin(a.x,b.x) - mgMax(c.x,d.x) > _MGZERO || mgMin(c.x,d.x) - mgMax(a.x,b.x) > _MGZERO || mgMin(a.y,b.y) - mgMax(c.y,d.y) > _MGZERO || mgMin(c.y,d.y) - mgMax(a.y,b.y) > _MGZERO) return false; denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x); if (mgIsZero(denom)) return false; cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y); if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector()) return false; u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom; if (u < _MGZERO || u > 1.f - _MGZERO) return false; v = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom; if (v < _MGZERO || v > 1.f - _MGZERO) return false; ptCross.x = (1 - u) * a.x + u * b.x; ptCross.y = (1 - u) * a.y + u * b.y; return true; } // 求线段和直线的交点 GEOMAPI bool mgCrossLineBeeline( const Point2d& a, const Point2d& b, const Point2d& c, const Point2d& d, Point2d& ptCross, float* pv, const Tol& tolVec) { float u, denom, cosnum; denom = (c.x-d.x)*(b.y-a.y)-(c.y-d.y)*(b.x-a.x); if (mgIsZero(denom)) return false; cosnum = (b.x-a.x)*(d.x - c.x) + (b.y-a.y)*(d.y-c.y); if (!mgIsZero(cosnum) && fabsf(denom / cosnum) < tolVec.equalVector()) return false; u = ((c.x-a.x)*(d.y-c.y)-(c.y-a.y)*(d.x-c.x)) / denom; if (u < _MGZERO || u > 1.f - _MGZERO) return false; if (pv != NULL) *pv = ((c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x)) / denom; ptCross.x = (1 - u) * a.x + u * b.x; ptCross.y = (1 - u) * a.y + u * b.y; return true; } // 线段端点的区域编码: // 1001 | 1000 | 1010 // 0001 | 0000 | 0010 // 0101 | 0100 | 0110 static inline unsigned ClipCode(Point2d& pt, const Box2d& box) { unsigned code = 0; if (pt.y > box.ymax) code |= 0x1000; else if (pt.y < box.ymin) code |= 0x0100; if (pt.x < box.xmin) code |= 0x0001; else if (pt.x > box.xmax) code |= 0x0010; return code; } // 功能: 用矩形剪裁线段 // 参数: [in, out] pt1 线段起点坐标 // [in, out] pt2 线段终点坐标 // [in] box 剪裁矩形 // 返回: 剪裁后是否有处于剪裁矩形内的线段部分 GEOMAPI bool mgClipLine(Point2d& pt1, Point2d& pt2, const Box2d& _box) { Box2d box (_box); box.normalize(); unsigned code1, code2; code1 = ClipCode(pt1, box); code2 = ClipCode(pt2, box); for ( ; ; ) { if (!(code1 | code2)) // 完全在矩形内 return true; if (code1 & code2) // 完全在矩形外 return false; float x = 0.f, y = 0.f; unsigned code; if (code1) // 起点不在矩形内 code = code1; else // 终点不在矩形内 code = code2; if (code & 0x1000) // 上 { x = pt1.x + (pt2.x - pt1.x) * (box.ymax - pt1.y) / (pt2.y - pt1.y); y = box.ymax; } else if (code & 0x0100) // 下 { x = pt1.x + (pt2.x - pt1.x) * (box.ymin - pt1.y) / (pt2.y - pt1.y); y = box.ymin; } else if (code & 0x0001) // 左 { y = pt1.y + (pt2.y - pt1.y) * (box.xmin - pt1.x) / (pt2.x - pt1.x); x = box.xmin; } else if (code & 0x0010) // 右 { y = pt1.y + (pt2.y - pt1.y) * (box.xmax - pt1.x) / (pt2.x - pt1.x); x = box.xmax; } if (code == code1) { pt1.x = x; pt1.y = y; code1 = ClipCode(pt1, box); } else { pt2.x = x; pt2.y = y; code2 = ClipCode(pt2, box); } } } static bool PtInArea_Edge(int &odd, const Point2d& pt, const Point2d& p1, const Point2d& p2, const Point2d& p0) { // 如果从X方向上P不在边[P1,P2)上,则没有交点. 竖直边也没有 if (!((p2.x > p1.x) && (pt.x >= p1.x) && (pt.x < p2.x)) && !((p1.x > p2.x) && (pt.x <= p1.x) && (pt.x > p2.x)) ) { return false; } // 求从Y负无穷大向上到P的射线和该边的交点(pt.x, yy) float yy = p1.y + (pt.x - p1.x) * (p2.y - p1.y) / (p2.x - p1.x); if (pt.y > yy) // 相交 { if (mgEquals(pt.x, p1.x)) // 交点是顶点, 则比较P[i+1]和P[i-1]是否在pt.x同侧 { if (((p0.x > pt.x) && (p2.x > pt.x)) || ((p0.x < pt.x) && (p2.x < pt.x)) ) // 同侧 { return false; } } odd = 1 - odd; // 增加一个交点, 奇偶切换 } return true; } // 功能: 判断一点是否在一多边形范围内 GEOMAPI MgPtInAreaRet mgPtInArea( const Point2d& pt, int count, const Point2d* vertexs, int& order, const Tol& tol) { int i; int odd = 1; // 1: 交点数为偶数, 0: 交点数为奇数 order = -1; for (i = 0; i < count; i++) { // P与某顶点重合. 返回 kMgPtAtVertex, order = 顶点号 [0, count-1] if (pt.isEqualTo(vertexs[i], tol)) { order = i; return kMgPtAtVertex; } } for (i = 0; i < count; i++) { const Point2d& p1 = vertexs[i]; const Point2d& p2 = (i+1 < count) ? vertexs[i+1] : vertexs[0]; // P在某条边上. 返回 kMgPtOnEdge, order = 边号 [0, count-1] if (mgIsBetweenLine2(p1, p2, pt, tol)) { order = i; return kMgPtOnEdge; } if (!PtInArea_Edge(odd, pt, p1, p2, i > 0 ? vertexs[i-1] : vertexs[count-1])) continue; } // 如果射线和多边形的交点数为偶数, 则 p==1, P在区外, 返回 kMgPtOutArea // 为奇数则p==0, P在区内, 返回 kMgPtInArea return 0 == odd ? kMgPtInArea : kMgPtOutArea; } // 判断多边形是否为凸多边形 GEOMAPI bool mgIsConvex(int count, const Point2d* vs, bool* pACW) { if (count < 3 || vs == NULL) return true; bool z0 = (vs[count-1].x - vs[count-2].x) * (vs[1].y - vs[0].y) > (vs[count-1].y - vs[count-2].y) * (vs[1].x - vs[0].x); for (int i = 0; i < count; i++) { if (z0 != ((vs[i].x - vs[i-1].x) * (vs[i+1].y - vs[i].y) > (vs[i].y - vs[i-1].y) * (vs[i+1].x - vs[i].x))) return false; } if (pACW != NULL) *pACW = z0; return true; }
12,755
6,372
/* Copyright (c) 2012 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "TestUtil.h" #include "Histogram.h" namespace RAMCloud { /** * Unit tests for Histogram. */ class HistogramTest : public ::testing::Test { public: HistogramTest() {} DISALLOW_COPY_AND_ASSIGN(HistogramTest); }; TEST_F(HistogramTest, constructor_regular) { Histogram h(5000, 10); EXPECT_EQ(5000UL, h.numBuckets); EXPECT_EQ(10UL, h.bucketWidth); for (uint32_t i = 0; i < h.numBuckets; i++) EXPECT_EQ(0UL, h.buckets[i]); EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum)); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(~0UL, h.min); EXPECT_EQ(0UL, h.max); } TEST_F(HistogramTest, constructor_deserializer) { Histogram h1(100, 1); h1.storeSample(8); h1.storeSample(23482); h1.storeSample(27); ProtoBuf::Histogram protoBuf; h1.serialize(protoBuf); Histogram h2(protoBuf); EXPECT_EQ(h1.numBuckets, h2.numBuckets); EXPECT_EQ(h1.bucketWidth, h2.bucketWidth); EXPECT_EQ(downCast<uint64_t>(h1.sampleSum), downCast<uint64_t>(h2.sampleSum)); EXPECT_EQ(h1.outliers, h2.outliers); EXPECT_EQ(h1.max, h2.max); EXPECT_EQ(h1.min, h2.min); EXPECT_EQ(h1.buckets.size(), h2.buckets.size()); for (uint32_t i = 0; i < h1.buckets.size(); i++) EXPECT_EQ(h1.buckets[i], h2.buckets[i]); } TEST_F(HistogramTest, storeSample) { Histogram h(5000, 10); h.storeSample(3); EXPECT_EQ(3UL, h.min); EXPECT_EQ(3UL, h.max); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(1UL, h.buckets[0]); EXPECT_EQ(0UL, h.buckets[1]); EXPECT_EQ(0UL, h.buckets[2]); h.storeSample(3); h.storeSample(h.numBuckets * h.bucketWidth + 40); h.storeSample(12); h.storeSample(78); EXPECT_EQ(3UL, h.min); EXPECT_EQ(h.numBuckets * h.bucketWidth + 40, h.max); EXPECT_EQ(1UL, h.outliers); EXPECT_EQ(2UL, h.buckets[0]); EXPECT_EQ(1UL, h.buckets[1]); EXPECT_EQ(0UL, h.buckets[2]); EXPECT_EQ(3UL + 3 + 12 + 78 + h.numBuckets * h.bucketWidth + 40, downCast<uint64_t>(h.sampleSum)); } TEST_F(HistogramTest, reset) { Histogram h(100, 1); h.storeSample(23); h.storeSample(23492834); h.reset(); EXPECT_EQ(100UL, h.numBuckets); EXPECT_EQ(1UL, h.bucketWidth); for (uint32_t i = 0; i < h.numBuckets; i++) EXPECT_EQ(0UL, h.buckets[i]); EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum)); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(~0UL, h.min); EXPECT_EQ(0UL, h.max); } TEST_F(HistogramTest, toString) { Histogram h(100, 1); EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n" "# 0 samples, 0 outliers, min = 18446744073709551615, max = 0\n" "# median = 0, average = 0\n", h.toString()); h.storeSample(23); h.storeSample(28343); h.storeSample(99); EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n" "# 3 samples, 1 outliers, min = 23, max = 28343\n" "# median = 99, average = 9488\n" " 23 1 33.333 33.333\n" " 99 1 33.333 66.667\n", h.toString()); Histogram h2(5, 1); h2.storeSample(3); EXPECT_EQ("# Histogram: buckets = 5, bucket width = 1\n" "# 1 samples, 0 outliers, min = 3, max = 3\n" "# median = 3, average = 3\n" " 0 0 0.000 0.000\n" " 1 0 0.000 0.000\n" " 2 0 0.000 0.000\n" " 3 1 100.000 100.000\n" " 4 0 0.000 100.000\n", h2.toString(0)); } TEST_F(HistogramTest, getOutliers) { Histogram h(1, 1); EXPECT_EQ(0UL, h.getOutliers()); h.storeSample(0); h.storeSample(1); h.storeSample(2); EXPECT_EQ(2UL, h.getOutliers()); uint64_t highestOutlier; h.getOutliers(&highestOutlier); EXPECT_EQ(2UL, highestOutlier); } TEST_F(HistogramTest, getTotalSamples) { Histogram h(1, 1); EXPECT_EQ(0UL, h.getTotalSamples()); h.storeSample(0); h.storeSample(1); h.storeSample(2); EXPECT_EQ(3UL, h.getTotalSamples()); } TEST_F(HistogramTest, getAverage) { // small sum Histogram h(1, 1); EXPECT_EQ(0UL, h.getAverage()); h.storeSample(1); EXPECT_EQ(1UL, h.getAverage()); h.storeSample(20); EXPECT_EQ(10UL, h.getAverage()); // sum that doesn't fit in 64-bits h.storeSample(0xffffffffffffffffUL); h.storeSample(0x0fffffffffffffffUL); EXPECT_EQ(0x4400000000000004UL, h.getAverage()); } TEST_F(HistogramTest, getMedian) { // totalSamples == 0 Histogram noSamples(1, 1); EXPECT_EQ(0UL, noSamples.getMedian()); // numBuckets == 0 Histogram noBuckets(0, 1); noBuckets.storeSample(5); EXPECT_EQ(-1UL, noBuckets.getMedian()); // median falls within outliers Histogram h(2, 1); h.storeSample(10); EXPECT_EQ(-1UL, h.getMedian()); // median falls within buckets h.storeSample(1); h.storeSample(1); EXPECT_EQ(1UL, h.getMedian()); // test a slightly less trivial case Histogram h2(11, 1); for (int i = 0; i <= 10; i++) h2.storeSample(i); EXPECT_EQ(5UL, h2.getMedian()); } TEST_F(HistogramTest, serialize) { // Covered by 'constructor_deserializer'. } } // namespace RAMCloud
6,140
2,673
#include <string> namespace lib { std::string greet() { return "hello, world"; } int square(int number) { return number * number; } }
144
46
// Fill out your copyright notice in the Description page of Project Settings. #include "MyTank.h" // Sets default values AMyTank::AMyTank() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AMyTank::BeginPlay() { Super::BeginPlay(); UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 1); audioComponent = FindComponentByClass<UAudioComponent>(); extraName = GetWorld()->WorldType == EWorldType::PIE ? "UEDPIE_0_" : ""; if (GetWorld()->GetMapName() == extraName + "Level_1") { totalTargets = targetsLV1; timeRemaining = timeLV1; } else { totalTargets = targetsLV2; timeRemaining = timeLV2; } armor = maxArmor; fireTimer = fireDelay; bossBarFill = 1; armorBarFill = 1; isCountingDown = false; } // Called every frame void AMyTank::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!currentVelocity.IsZero()) { FVector newLocation = GetActorLocation() + (currentVelocity * DeltaTime); SetActorLocation(newLocation); } if (destroyedTargets == totalTargets) Win(); if (GetWorld()->GetMapName() != extraName + "Level_1" || GetWorld()->GetMapName() != extraName + "Level_2") timeRemaining -= DeltaTime; armorBarFill = armor / maxArmor; fireTimer += DeltaTime; powerUpTimer -= DeltaTime; remainingTargets = totalTargets - destroyedTargets; if (powerUpTimer <= 0) { unlimitedFireRate = false; shotgunMode = false; } if (armor <= 0 || timeRemaining <= 0) Lose(); if (timeRemaining <= 5 && !isCountingDown){ audioComponent->Stop(); audioComponent->Sound = countdown; audioComponent->Play(); isCountingDown = true; } } // Called to bind functionality to input void AMyTank::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("Move X", this, &AMyTank::MoveX); PlayerInputComponent->BindAxis("Move Y", this, &AMyTank::MoveY); PlayerInputComponent->BindAxis("Rotate X", this, &AMyTank::RotateX); PlayerInputComponent->BindAxis("Rotate Y", this, &AMyTank::RotateY); PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &AMyTank::Shoot); PlayerInputComponent->BindAction("Continue", IE_Pressed, this, &AMyTank::Continue); } void AMyTank::MoveX(float val) { if (won) return; isMovingX = val != 0; if (isMovingY) val *= 0.5f; currentVelocity.X = val * 100 * speed; } void AMyTank::MoveY(float val) { if (won) return; isMovingY = val != 0; if (isMovingX) val *= 0.5f; currentVelocity.Y = -val * 100 * speed; } void AMyTank::RotateX(float val) { if (won) return; FRotator rot = upperBody->RelativeRotation; rot.Yaw += rotationSpeed * val; upperBody->SetRelativeRotation(rot); } void AMyTank::RotateY(float val) { if (won) return; FRotator rot = rotor->RelativeRotation; rot.Roll -= rotationSpeed * val * 0.5f; if (rot.Roll > 15) rot.Roll = 15; else if (rot.Roll < -20) rot.Roll = -20; rotor->SetRelativeRotation(rot); } void AMyTank::Shoot() { if (won) return; if (fireTimer >= fireDelay || unlimitedFireRate) { if (shotgunMode) { for (int i = 0; i <= shotgunPellets; i++) { FRotator rot = PH->GetComponentRotation(); rot.Yaw += FMath::FRandRange(-shotgunSpread, shotgunSpread); rot.Roll += FMath::FRandRange(-shotgunSpread, shotgunSpread); GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), rot, FActorSpawnParameters()); } } else GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), PH->GetComponentRotation(), FActorSpawnParameters()); fireTimer = 0; } } void AMyTank::UnlimitedFireRate() { unlimitedFireRate = true; shotgunMode = false; powerUpTimer = powerUpTime; } void AMyTank::ShotgunMode() { unlimitedFireRate = false; shotgunMode = true; powerUpTimer = powerUpTime; } void AMyTank::Win() { UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 0.0001f); won = true; audioComponent->Stop(); audioComponent->Sound = complete; audioComponent->Play(); if (GetWorld()->GetMapName() == extraName + "Level_3") UGameplayStatics::OpenLevel(GetWorld(), "Complete"); } void AMyTank::Lose() { if (GetWorld()->GetMapName() == extraName + "Level_1") UGameplayStatics::OpenLevel(GetWorld(), "Lose_1"); else if (GetWorld()->GetMapName() == extraName + "Level_2") UGameplayStatics::OpenLevel(GetWorld(), "Lose_2"); else if (GetWorld()->GetMapName() == extraName + "Level_3") UGameplayStatics::OpenLevel(GetWorld(), "Lose_3"); } void AMyTank::Continue() { if (!won) return; if (GetWorld()->GetMapName() == extraName + "Level_1") UGameplayStatics::OpenLevel(GetWorld(), "Victory_1"); else UGameplayStatics::OpenLevel(GetWorld(), "Victory_2"); } void AMyTank::SetGamePaused(bool isPaused) { APlayerController* const MyPlayer = Cast<APlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld())); if (MyPlayer != NULL) MyPlayer->SetPause(isPaused); }
5,030
1,948
#ifndef STAN_MATH_PRIM_MAT_FUN_MINUS_HPP #define STAN_MATH_PRIM_MAT_FUN_MINUS_HPP namespace stan { namespace math { /** * Returns the negation of the specified scalar or matrix. * * @tparam T Type of subtrahend. * @param x Subtrahend. * @return Negation of subtrahend. */ template <typename T> inline T minus(const T& x) { return -x; } } // namespace math } // namespace stan #endif
417
164
//+------------------------------------------------------------------------- // // Microsoft OLE // Copyright (C) Microsoft Corporation, 1994 - 1995. // // File: automate.hxx // // Contents: Marina automation helper class // Marina aware applications use this class to aid in the // automation process // // Classes: CMAutomate // // Functions: // // History: 09-26-95 alexe Cleaned up / added more marina funcs // 1-25-95 kennethm Created // //-------------------------------------------------------------------------- #ifndef __AUTOMATE_HXX__ #define __AUTOMATE_HXX__ #include <copydata.hxx> // // number of marina API functions in the CMAutomate class // #define MAX_NUM_FUNCS 16 // // Function names: always unicode // // These are the known functions. TestDlls and application can always // cook up their own private function names, although this isn't // recommended. // #define FUNCNAME_CLOSEAPPLICATION L"MarinaCloseApplication" #define FUNCNAME_CREATEDOCUMENT L"MarinaCreateDocument" #define FUNCNAME_OPENDOCUMENT L"MarinaOpenDocument" #define FUNCNAME_CLOSEALLDOCUMENTS L"MarinaCloseAllDocuments" #define FUNCNAME_GETDOCUMENTCOUNT L"MarinaApiGetDocCount" #define FUNCNAME_GETAPPHWND L"MarinaGetAppHwnd" #define FUNCNAME_SAVEDOCUMENT L"MarinaSaveDocument" #define FUNCNAME_CLOSEDOCUMENT L"MarinaCloseDocument" #define FUNCNAME_COPYDOCUMENT L"MarinaCopyDocument" #define FUNCNAME_INSERTOBJECT L"MarinaInsertObject" #define FUNCNAME_GETOBJECT L"MarinaGetObject" #define FUNCNAME_GETOBJECTCOUNT L"MarinaApiGetObjCount" #define FUNCNAME_COPYOBJECT L"MarinaCopyObject" #define FUNCNAME_ACTIVATEOBJECT L"MarinaActivateObject" #define FUNCNAME_GETAPPPROCESSID L"MarinaGetAppProcessId" #define INVALID_MARINA_HANDLE (DWORD)-1 //+------------------------------------------------------------------------- // // Class: CMAutomate // // Purpose: Automation helper class for marina aware applications // // Interface: // // Public Functions: // // CMAutomate // ~CMAutomate // CMAutomate(ptr) // FindMarinaHandle // WriteMarinaHandle // MarinaRegisterFile // SetJumpTable // DispatchCopyData // InMarina // MarinaParseCommandLine // // MarinaApiCloseApp // MarinaApiCreateDoc // MarinaApiOpenDoc // MarinaApiCloseAllDocs // MarinaApiGetDocCount // MarinaApiGetAppHwnd // // MarinaApiSaveDoc // MarinaApiCloseDoc // MarinaApiCopyDoc // MarinaApiInsertObject // MarinaApiGetObject // MarinaApiGetObjCount // // MarinaApiCopyObject // MarinaApiActivateObject // // MarinaApiGetAppProcessId // // Private functions: // // SetClassFunctionTable // DispatchCDExecFunction // // History: 2-01-95 kennethm Created // 7-25-95 kennethm Merged function table class // (MarinaApiXXXX functions) // 9-26-95 alexe Cleaned up/ added more 'Marina' functions // Removed some obsolete accessor functions // // Notes: // //-------------------------------------------------------------------------- class CMAutomate { public: // // Default constructor and destructor // CMAutomate(); ~CMAutomate(); // // Special case initialization constructor // CMAutomate(struct tagMarinaFunctionTableElement *pJumpTable); // // On the server side, pull out the marina handle from ole storage // Called during object initialization. // HRESULT FindMarinaHandle(LPSTORAGE pStg, HWND hWndObj); // // On the container side, called to place the marina handle into // storage so FindMarinaHandle can get to it // HRESULT WriteMarinaHandle(LPSTORAGE pStg); // // Register a file name with marina // HRESULT MarinaRegisterFile(LPCWSTR pszFileName, HWND hWnd); // // Set the jump table used by Dispatch functions // VOID SetJumpTable(struct tagMarinaFunctionTableElement *pJumpTable); // // Called when a WM_COPYDATA message is received // LRESULT DispatchCopyData(HWND hwnd, LPARAM lParam); // // Called when a WM_PRIVATECOPYDATA message is received // LRESULT DispatchPrivateCopyData(HWND hwnd, LPARAM lParam); // // When an application starts up, checks to see if marina started // the application. Used by all applications // BOOL InMarina() const; // // When an application starts up, calls parsecommandline to see // if the application was started by marina // HRESULT MarinaParseCommandLine(HWND hWnd); // // Application level marina API functions // virtual HRESULT MarinaApiCloseApp( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiCreateDoc( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiOpenDoc( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiCloseAllDocs( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiGetDocCount( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiGetAppHwnd( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); // // Document level marina API functions // virtual HRESULT MarinaApiSaveDoc( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiCloseDoc( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiCopyDoc( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiInsertObject( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiGetObject( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiGetObjCount( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); // // Object level marina API functions // virtual HRESULT MarinaApiCopyObject( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); virtual HRESULT MarinaApiActivateObject( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); // // Other marina API functions // virtual HRESULT MarinaApiGetAppProcessId( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); private: struct tagMarinaFunctionTableElement *m_MarinaDispatchTable; // // The marina handle that is being used for the current call // DWORD m_dwMarinaHandle; static BOOL m_fRunByMarina; // // The window that was registered for this particular instance of // CMAutomate // DWORD m_dwRegisteredhWnd; // // Our own internal Marina API function table. This list contains // pointers to all of the virtual MarinaApiXXXXX functions listed // above after the call to SetClassFunctionTable. This is done in // the constructor // struct tagMarinaClassTableElement *m_MarinaAPIFuncTable; HRESULT SetClassFunctionTable(); // // Performs the actual call to the user api when a marina message // is received. // HRESULT DispatchCDExecFunction( HWND hwnd, PCDEXECINFO pCDExecInfo, PCOPYDATASTRUCT pOutParameter); }; // // Each function in the jump table follows this prototype // typedef HRESULT (WINAPI *COPYDATA_FUNCTION)( HWND hWnd, LPVOID pInParameter, PCOPYDATASTRUCT pOutParameter); // // This is one element in the jump table used by the CMAutomate class // The list is terminated by a null entry at the end // typedef struct tagMarinaFunctionTableElement { COPYDATA_FUNCTION pfnFunction; LPWSTR lpszFunctionName; } MARINAFUNCTIONTABLEELEMENT; // // This is one element in the internal class API function table // The list is terminated by a null entry at the end // typedef struct tagMarinaClassTableElement { HRESULT (CMAutomate::*pfnFunction)( HWND hwnd, PVOID pvParam, PCOPYDATASTRUCT pOutParameter); LPWSTR lpszFunctionName; } MARINACLASSTABLEELEMENT; // // An itty bitty class to perform the global rpc binding. // // Note, the Mac doesn't support real RPC yet (04-Nov-96) // #ifndef _MAC class CMarinaAutomateRPCBinding { public: CMarinaAutomateRPCBinding(); ~CMarinaAutomateRPCBinding(); }; #endif // !_MAC #endif // __AUTOMATE_HXX__
10,049
3,224
// 擬似微分器クラス // 2011/02/10 Yuki YOKOKURA // // 擬似微分器 G(s)=(s*gpd)/(s+gpd) (双一次変換) // // Copyright (C) 2011 Yuki YOKOKURA // This program is free software; // you can redistribute it and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 of the License, or 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 <http://www.gnu.org/licenses/>. // Besides, you can negotiate about other options of licenses instead of GPL. // If you would like to get other licenses, please contact us<yuki@katsura.sd.keio.ac.jp>. #include "Differentiator.hh" using namespace ARCS; Differentiator::Differentiator(double Bandwidth, double SmplTime) // コンストラクタ Bandwidth;[rad/s] 帯域,SmplTime;[s] 制御周期 : Ts(SmplTime), // [s] 制御周期の格納 gpd(Bandwidth), // [rad/s] 擬似微分の帯域の格納 uZ1(0), yZ1(0) { } Differentiator::~Differentiator(){ // デストラクタ } double Differentiator::GetSignal(double u){ // 出力信号の取得 u;入力信号 double y; y = ( 2.0*gpd*(u-uZ1) + (2.0-Ts*gpd)*yZ1 )/(2.0+Ts*gpd); uZ1=u; yZ1=y; return y; } void Differentiator::SetBandwidth(double Bandwidth){ // 擬似微分の帯域の再設定 Bandwidth;[rad/s] 帯域 gpd=Bandwidth; } void Differentiator::SetSmplTime(double SmplTime){ // 制御周期の再設定 SmplTime;[s] 制御周期 Ts=SmplTime; // [s] 制御周期の再設定 } void Differentiator::ClearStateVars(void){ // すべての状態変数のリセット uZ1=0; // 状態変数1のゼロクリア yZ1=0; // 状態変数2のゼロクリア }
1,617
807
// $Id: Buffering_Constraint_Policy.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/Messaging/Buffering_Constraint_Policy.h" #if (TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1) #include "tao/Messaging/TAO_ExtA.h" #include "tao/SystemException.h" #include "ace/CORBA_macros.h" #if ! defined (__ACE_INLINE__) #include "tao/Messaging/Buffering_Constraint_Policy.inl" #endif /* __ACE_INLINE__ */ TAO_BEGIN_VERSIONED_NAMESPACE_DECL TAO_Buffering_Constraint_Policy::TAO_Buffering_Constraint_Policy (const TAO::BufferingConstraint &buffering_constraint) : ::CORBA::Object () , ::CORBA::Policy () , TAO::BufferingConstraintPolicy () , ::CORBA::LocalObject () , buffering_constraint_ (buffering_constraint) { } TAO_Buffering_Constraint_Policy::TAO_Buffering_Constraint_Policy (const TAO_Buffering_Constraint_Policy &rhs) : ::CORBA::Object () , ::CORBA::Policy () , TAO::BufferingConstraintPolicy () , ::CORBA::LocalObject () , buffering_constraint_ (rhs.buffering_constraint_) { } CORBA::PolicyType TAO_Buffering_Constraint_Policy::policy_type (void) { return TAO::BUFFERING_CONSTRAINT_POLICY_TYPE; } CORBA::Policy_ptr TAO_Buffering_Constraint_Policy::create (const CORBA::Any& val) { const TAO::BufferingConstraint *buffering_constraint = 0; if ((val >>= buffering_constraint) == 0) throw ::CORBA::PolicyError (CORBA::BAD_POLICY_VALUE); TAO_Buffering_Constraint_Policy *servant = 0; ACE_NEW_THROW_EX (servant, TAO_Buffering_Constraint_Policy (*buffering_constraint), CORBA::NO_MEMORY ()); return servant; } TAO_Buffering_Constraint_Policy * TAO_Buffering_Constraint_Policy::clone (void) const { TAO_Buffering_Constraint_Policy *copy = 0; ACE_NEW_RETURN (copy, TAO_Buffering_Constraint_Policy (*this), 0); return copy; } TAO::BufferingConstraint TAO_Buffering_Constraint_Policy::buffering_constraint (void) { return this->buffering_constraint_; } CORBA::Policy_ptr TAO_Buffering_Constraint_Policy::copy (void) { TAO_Buffering_Constraint_Policy* servant = 0; ACE_NEW_THROW_EX (servant, TAO_Buffering_Constraint_Policy (*this), CORBA::NO_MEMORY ()); return servant; } void TAO_Buffering_Constraint_Policy::destroy (void) { } TAO_Cached_Policy_Type TAO_Buffering_Constraint_Policy::_tao_cached_type (void) const { return TAO_CACHED_POLICY_BUFFERING_CONSTRAINT; } TAO_END_VERSIONED_NAMESPACE_DECL #endif /* TAO_HAS_BUFFERING_CONSTRAINT_POLICY == 1 */
2,528
979
#include <hilti/hilti-intern.h> #include "../stmt-builder.h" using namespace hilti; using namespace codegen; static void _freeFields(CodeGen* cg, shared_ptr<Type> rtype, llvm::Value* fields, const Location& l) { auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList(); auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size()); fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr(atype)); for ( int i = 0; i < ftypes.size(); i++ ) { auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i)); cg->llvmFree(cg->builder()->CreateLoad(addr), "classifier-free-one-field", l); } cg->llvmFree(fields, "classifier-free-fields", l); } static llvm::Value* _matchAllField(CodeGen* cg) { return cg->llvmClassifierField(cg->llvmConstNull(cg->llvmTypePtr()), cg->llvmConstInt(0, 64)); } static llvm::Value* _llvmFields(CodeGen* cg, shared_ptr<Type> rtype, shared_ptr<Type> stype, llvm::Value* val, const Location& l) { auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList(); auto stypes = ast::type::checkedTrait<type::trait::TypeList>(stype)->typeList(); auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size()); auto fields = cg->llvmMalloc(atype, "hlt.classifier", l); // Convert the fields into the internal hlt_classifier_field representation. auto ft = ftypes.begin(); auto st = stypes.begin(); for ( int i = 0; i < ftypes.size(); i++ ) { auto field = cg->llvmStructGet(stype, val, i, [&](CodeGen* cg) -> llvm::Value* { return _matchAllField(cg); }, [&](CodeGen* cg, llvm::Value* v) -> llvm::Value* { return cg->llvmClassifierField(*ft, *st, v, l); }, l); auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i)); cg->llvmCreateStore(field, addr); ++ft; ++st; } fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr()); return fields; } void StatementBuilder::visit(statement::instruction::classifier::New* i) { auto ctype = ast::rtti::tryCast<type::Classifier>(typedType(i->op1())); auto op1 = builder::integer::create( ast::type::checkedTrait<type::trait::TypeList>(ctype->ruleType())->typeList().size()); auto op2 = builder::type::create(ctype->ruleType()); auto op3 = builder::type::create(ctype->valueType()); CodeGen::expr_list args = {op1, op2, op3}; auto result = cg()->llvmCall("hlt::classifier_new", args); cg()->llvmStore(i, result); } void StatementBuilder::visit(statement::instruction::classifier::Add* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); // op2 can be a tuple (ref<struct>, prio) or a just a rule ref<struct> // // TODO: The separations for the cases below isn't fool-proof but should // be good enough for now. auto ttype = ast::rtti::tryCast<type::Tuple>(i->op2()->type()); if ( ttype ) { auto op2 = cg()->llvmValue(i->op2()); auto rule = cg()->llvmExtractValue(op2, 0); auto reftype = ast::rtti::tryCast<type::Reference>(ttype->typeList().front()); if ( reftype ) { auto stype = reftype->argType(); auto prio = cg()->builder()->CreateZExt(cg()->llvmExtractValue(op2, 1), cg()->llvmTypeInt(64)); auto fields = _llvmFields(cg(), rtype, stype, rule, i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields), builder::codegen::create(builder::integer::type(64), prio), i->op3()}; cg()->llvmCall("hlt::classifier_add", args); return; } } auto rval = i->op2()->coerceTo(builder::reference::type(rtype)); auto rule = cg()->llvmValue(rval); auto reftype = ast::rtti::checkedCast<type::Reference>(rval->type()); auto stype = reftype->argType(); auto fields = _llvmFields(cg(), rtype, stype, rule, i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields), i->op3()}; cg()->llvmCall("hlt::classifier_add_no_prio", args); } void StatementBuilder::visit(statement::instruction::classifier::Compile* i) { CodeGen::expr_list args = {i->op1()}; cg()->llvmCall("hlt::classifier_compile", args); } void StatementBuilder::visit(statement::instruction::classifier::Get* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); auto vtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->valueType(); auto op2 = i->op2()->coerceTo(builder::reference::type(rtype)); auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)}; auto voidp = cg()->llvmCall("hlt::classifier_get", args, false, true, [&](CodeGen* cg) { _freeFields(cg, rtype, fields, i->location()); }); auto casted = builder()->CreateBitCast(voidp, cg()->llvmTypePtr(cg()->llvmType(vtype))); auto result = builder()->CreateLoad(casted); cg()->llvmStore(i, result); } void StatementBuilder::visit(statement::instruction::classifier::Matches* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); auto op2 = i->op2()->coerceTo(builder::reference::type(rtype)); auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)}; auto result = cg()->llvmCall("hlt::classifier_matches", args, false, false); _freeFields(cg(), rtype, fields, i->location()); cg()->llvmCheckException(); cg()->llvmStore(i, result); }
6,179
2,133
#include "zce_predefine.h" #include "zce_time_value.h" #include "zce_os_adapt_file.h" #include "zce_os_adapt_flock.h" #include "zce_os_adapt_process.h" #include "zce_os_adapt_socket.h" #include "zce_os_adapt_time.h" #include "zce_os_adapt_dirent.h" #include "zce_log_logging.h" #include "zce_server_base.h" /********************************************************************************* class ZCE_Server_Base *********************************************************************************/ ZCE_Server_Base *ZCE_Server_Base::base_instance_ = NULL; // 构造函数,私有,使用单子类的实例, ZCE_Server_Base::ZCE_Server_Base(): pid_handle_(ZCE_INVALID_HANDLE), self_pid_(0), app_run_(true), app_reload_(false), check_leak_times_(0), mem_checkpoint_size_(0), cur_mem_usesize_(0), process_cpu_ratio_(0), system_cpu_ratio_(0), mem_use_ratio_(0) { memset(&last_process_perf_, 0, sizeof(last_process_perf_)); memset(&now_process_perf_, 0, sizeof(now_process_perf_)); memset(&last_system_perf_, 0, sizeof(last_system_perf_)); memset(&now_system_perf_, 0, sizeof(now_system_perf_)); } ZCE_Server_Base::~ZCE_Server_Base() { // 关闭文件 if (pid_handle_ != ZCE_INVALID_HANDLE) { zce::flock_unlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN); zce::flock_destroy(&pidfile_lock_); zce::close(pid_handle_); } } // 初始化 int ZCE_Server_Base::socket_init() { int ret = 0; ret = zce::socket_init(); if (ret != 0) { return ret; } return 0; } //打印输出PID File int ZCE_Server_Base::out_pid_file(const char *pragramname) { int ret = 0; std::string pidfile_name = pragramname; pidfile_name += ".pid"; self_pid_ = zce::getpid(); //检查PID文件是否存在,, bool must_create_new = false; ret = zce::access(pidfile_name.c_str(), F_OK); if ( 0 != ret) { must_create_new = true; } // 设置文件读取参数,表示其他用户可以读取,open函数会自动帮忙调整参数的。 int fileperms = 0644; pid_handle_ = zce::open(pidfile_name.c_str(), O_RDWR | O_CREAT, static_cast<mode_t>(fileperms)); if (pid_handle_ == ZCE_INVALID_HANDLE) { ZCE_LOG(RS_ERROR, "Open pid file [%s]fail.", pidfile_name.c_str()); return -1; } //如果PID文件不存在,调整文件长度,(说明见下) //这个地方没有原子保护,有一定风险,但…… if (true == must_create_new) { //我是用WINDOWS下的记录锁是模拟和Linux类似,但Windows的文件锁其实没有对将长度参数设置0, //锁定整个文件的功能,所以要先把文件长度调整 zce::ftruncate(pid_handle_, PID_FILE_LEN); } zce::flock_init(&pidfile_lock_, pid_handle_); char tmpbuff[PID_FILE_LEN + 1]; snprintf(tmpbuff, PID_FILE_LEN + 1, "%*.u", (int)PID_FILE_LEN * (-1), self_pid_); // 尝试锁定全部文件,如果锁定不成功,表示有人正在用这个文件 ret = zce::flock_trywrlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN); if (ret != 0) { ZCE_LOG(RS_ERROR, "Trylock pid file [%s]fail. Last error =%d", pidfile_name.c_str(), zce::last_error()); return ret; } //写入文件内容, 截断文件为BUFFER_LEN, zce::ftruncate(pid_handle_, PID_FILE_LEN); zce::lseek(pid_handle_, 0, SEEK_SET); zce::write(pid_handle_, tmpbuff, PID_FILE_LEN); return 0; } // 监测这个进程的系统状况,每N分钟运行一次就OK了 // 看门狗得到进程的状态 int ZCE_Server_Base::watch_dog_status(bool first_record) { int ret = 0; // 如果不是第一次记录,保存上一次记录的结果 if (!first_record) { last_process_perf_ = now_process_perf_; last_system_perf_ = now_system_perf_; } ret = zce::get_self_perf(&now_process_perf_); if (0 != ret) { return ret; } ret = zce::get_system_perf(&now_system_perf_); if (0 != ret) { return ret; } cur_mem_usesize_ = now_process_perf_.vm_size_; // 记录第一次的内存数据 if (first_record) { mem_checkpoint_size_ = now_process_perf_.vm_size_; return 0; } // 处理内存变化的情况 size_t vary_mem_size = 0; if (now_process_perf_.vm_size_ >= mem_checkpoint_size_) { vary_mem_size = now_process_perf_.vm_size_ - mem_checkpoint_size_; } // 内存居然缩小了…… else { mem_checkpoint_size_ = now_process_perf_.vm_size_; } // 这个告警如何向监控汇报要考虑一下 if (vary_mem_size >= MEMORY_LEAK_THRESHOLD) { ++check_leak_times_; ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] Monitor could memory leak," "mem_checkpoint_size_ =[%u],run_mem_size_=[%u].", self_pid_, mem_checkpoint_size_, now_process_perf_.vm_size_); // 如果已经监测了若干次内存泄漏,则不再记录告警 if (check_leak_times_ > MAX_RECORD_MEMLEAK_NUMBER) { mem_checkpoint_size_ = now_process_perf_.vm_size_; check_leak_times_ = 0; } } // 其实到这个地方了,你可以干的事情很多, // 甚至计算某一段时间内程序的CPU占用率过高(TNNND,后来我真做了) timeval last_to_now = zce::timeval_sub(now_system_perf_.up_time_, last_system_perf_.up_time_); // 得到进程的CPU利用率 timeval proc_utime = zce::timeval_sub(now_process_perf_.run_utime_, last_process_perf_.run_utime_); timeval proc_stime = zce::timeval_sub(now_process_perf_.run_stime_, last_process_perf_.run_stime_); timeval proc_cpu_time = zce::timeval_add(proc_utime, proc_stime); // 如果间隔时间不为0 if (zce::total_milliseconds(last_to_now) > 0) { process_cpu_ratio_ = static_cast<uint32_t>(zce::total_milliseconds(proc_cpu_time) * 1000 / zce::total_milliseconds(last_to_now)); } else { process_cpu_ratio_ = 0; } ZCE_LOG(RS_INFO, "[zcelib] [WATCHDOG][PID:%u] cpu ratio[%u] " "totoal process user/sys[%lld/%lld] milliseconds " "leave last point all/usr/sys[%lld/%lld/%lld] milliseconds " "memory use//add [%ld/%ld].", self_pid_, process_cpu_ratio_, zce::total_milliseconds(now_process_perf_.run_utime_), zce::total_milliseconds(now_process_perf_.run_stime_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(proc_utime), zce::total_milliseconds(proc_stime), cur_mem_usesize_, vary_mem_size); // 计算系统的CPU时间,非IDLE以外的时间都是消耗时间 timeval sys_idletime = zce::timeval_sub(now_system_perf_.idle_time_, last_system_perf_.idle_time_); timeval sys_cputime = zce::timeval_sub(last_to_now, sys_idletime); // 如果间隔时间不为0 if (zce::total_milliseconds(last_to_now) > 0) { system_cpu_ratio_ = static_cast<uint32_t>(zce::total_milliseconds(sys_cputime) * 1000 / zce::total_milliseconds(last_to_now)); } else { ZCE_LOG(RS_ERROR, "system_uptime = %llu, process_start_time = %llu", zce::total_milliseconds(now_system_perf_.up_time_), zce::total_milliseconds(now_process_perf_.start_time_)); system_cpu_ratio_ = 0; } // 系统或进程CPU使用超过阈值时记条账单 if (process_cpu_ratio_ >= PROCESS_CPU_RATIO_THRESHOLD || system_cpu_ratio_ >= SYSTEM_CPU_RATIO_THRESHOLD) { ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] point[%u] vm_size[%u] " "process cpu ratio [%f] threshold [%f], system cpu ratio[%f] threshold[%f] " "totoal process user/sys[%lld/%lld] milliseconds " "leave last point all/usr/sys[%lld/%lld/%lld] milliseconds.", self_pid_, mem_checkpoint_size_, now_process_perf_.vm_size_, double(process_cpu_ratio_) / 10, double(PROCESS_CPU_RATIO_THRESHOLD) / 10, double(system_cpu_ratio_) / 10, double(SYSTEM_CPU_RATIO_THRESHOLD) / 10, zce::total_milliseconds(now_process_perf_.run_utime_), zce::total_milliseconds(now_process_perf_.run_stime_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(proc_utime), zce::total_milliseconds(proc_stime)); } // 内存使用情况的监控 can_use_size_ = now_system_perf_.freeram_size_ + now_system_perf_.cachedram_size_ + now_system_perf_.bufferram_size_; if (now_system_perf_.totalram_size_ > 0) { mem_use_ratio_ = static_cast<uint32_t>((now_system_perf_.totalram_size_ - can_use_size_) * 1000 / now_system_perf_.totalram_size_); } else { mem_use_ratio_ = 0; } ZCE_LOG(RS_INFO, "[zcelib] [WATCHDOG][SYSTEM] cpu radio [%u] " "totoal usr/nice/sys/idle/iowait/hardirq/softirq " "[%lld/%lld/%lld/%lld/%lld/%lld/%lld] milliseconds" "leave last point all/use/idle[%lld/%lld/%lld] milliseconds " "mem ratio[%u] [totoal/can use/free/buffer/cache] " "[%lld/%lld/%lld/%lld/%lld] bytes", system_cpu_ratio_, zce::total_milliseconds(now_system_perf_.user_time_), zce::total_milliseconds(now_system_perf_.nice_time_), zce::total_milliseconds(now_system_perf_.system_time_), zce::total_milliseconds(now_system_perf_.idle_time_), zce::total_milliseconds(now_system_perf_.iowait_time_), zce::total_milliseconds(now_system_perf_.hardirq_time_), zce::total_milliseconds(now_system_perf_.softirq_time_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(sys_cputime), zce::total_milliseconds(sys_idletime), mem_use_ratio_, now_system_perf_.totalram_size_, can_use_size_, now_system_perf_.freeram_size_, now_system_perf_.bufferram_size_, now_system_perf_.cachedram_size_); return 0; } int ZCE_Server_Base::process_signal(void) { //忽视部分信号,这样简单 zce::signal(SIGHUP, SIG_IGN); zce::signal(SIGPIPE, SIG_IGN); zce::signal(SIGCHLD, SIG_IGN); #ifdef ZCE_OS_WINDOWS //Windows下设置退出处理函数,可以用Ctrl + C 退出 SetConsoleCtrlHandler((PHANDLER_ROUTINE)exit_signal, TRUE); #else //这个几个信号被认可为退出信号 zce::signal(SIGINT, exit_signal); zce::signal(SIGQUIT, exit_signal); zce::signal(SIGTERM, exit_signal); //重新加载部分配置,用了SIGUSR1 kill -10 zce::signal(SIGUSR1, reload_cfg_signal); #endif //SIGUSR1,SIGUSR2你可以用来干点自己的活, return 0; } int ZCE_Server_Base::daemon_init() { //Daemon 精灵进程,但是我不清理目录路径, #if defined (ZCE_OS_LINUX) pid_t pid = zce::fork(); if (pid < 0) { return -1; } else if (pid > 0) { ::exit(0); } #endif zce::setsid(); zce::umask(0); #if defined (ZCE_OS_WINDOWS) //设置Console的标题信息 std::string out_str = get_app_basename(); out_str += " "; out_str += app_author_; ::SetConsoleTitle(out_str.c_str()); #endif return 0; } //通过启动参数0,得到app_base_name_,app_run_name_ int ZCE_Server_Base::create_app_name(const char *argv_0) { app_run_name_ = argv_0; // 取得base name char str_base_name[PATH_MAX + 1]; str_base_name[PATH_MAX] = '\0'; zce::basename(argv_0, str_base_name, PATH_MAX); #if defined ZCE_OS_WINDOWS //Windows下要去掉,EXE后缀 const size_t WIN_EXE_SUFFIX_LEN = 4; size_t name_len = strlen(str_base_name); if (name_len <= WIN_EXE_SUFFIX_LEN) { ZCE_LOG(RS_ERROR, "[framework] Exe file name is not expect?Path name[%s].", argv_0); return -1; } //如果有后缀才取消,没有就放鸭子 if (strcasecmp(str_base_name + name_len - WIN_EXE_SUFFIX_LEN, ".EXE") == 0) { str_base_name[name_len - WIN_EXE_SUFFIX_LEN] = '\0'; } #endif //如果是调试版本,去掉后缀符号_d #if defined (DEBUG) || defined (_DEBUG) //如果是调试版本,去掉后缀符号_d const size_t DEBUG_SUFFIX_LEN = 2; size_t debug_name_len = strlen(str_base_name); if (debug_name_len <= DEBUG_SUFFIX_LEN) { ZCE_LOG(RS_ERROR, "[framework] Exe file name is not debug _d suffix?str_base_name[%s].", str_base_name); return -1; } if (0 == strcasecmp(str_base_name + debug_name_len - DEBUG_SUFFIX_LEN, "_D")) { str_base_name[debug_name_len - DEBUG_SUFFIX_LEN] = '\0'; } #endif app_base_name_ = str_base_name; return 0; } //windows下设置服务信息 void ZCE_Server_Base::set_service_info(const char *svc_name, const char *svc_desc) { if (svc_name != NULL) { service_name_ = svc_name; } if (svc_desc != NULL) { service_desc_ = svc_desc; } } //得到运行信息,可能包括路径信息 const char *ZCE_Server_Base::get_app_runname() { return app_run_name_.c_str(); } //得到程序进程名称,,去掉了路径,WINDOWS下去掉了后缀 const char *ZCE_Server_Base::get_app_basename() { return app_base_name_.c_str(); } //设置进程是否运行的标志 void ZCE_Server_Base::set_run_sign(bool app_run) { app_run_ = app_run; } //设置reload标志 void ZCE_Server_Base::set_reload_sign(bool app_reload) { app_reload_ = app_reload; } //信号处理代码, #ifdef ZCE_OS_WINDOWS BOOL ZCE_Server_Base::exit_signal(DWORD) { base_instance_->set_run_sign(false); return TRUE; } #else void ZCE_Server_Base::exit_signal(int) { base_instance_->set_run_sign(false); return; } // USER1信号处理函数 void ZCE_Server_Base::reload_cfg_signal(int) { // 信号处理函数中不能有IO等不可重入的操作,否则容易死锁 base_instance_->set_reload_sign(true); return; } #endif #if defined ZCE_OS_WINDOWS //运行服务 int ZCE_Server_Base::win_services_run() { char service_name[PATH_MAX + 1]; service_name[PATH_MAX] = '\0'; strncpy(service_name, app_base_name_.c_str(), PATH_MAX); SERVICE_TABLE_ENTRY st[] = { { service_name, (LPSERVICE_MAIN_FUNCTION)win_service_main }, { NULL, NULL } }; BOOL b_ret = ::StartServiceCtrlDispatcher(st); if (b_ret) { //LogEvent(_T("Register Service Main Function Success!")); } else { UINT error_info = ::GetLastError(); ZCE_UNUSED_ARG(error_info); //LogEvent(_T("Register Service Main Function Error!")); } return 0; } //安装服务 int ZCE_Server_Base::win_services_install() { if (win_services_isinstalled()) { printf("install service fail. service %s already exist", app_base_name_.c_str()); return 0; } //打开服务控制管理器 SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm == NULL) { //::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK); printf("can't open service manager.\n"); return FALSE; } // Get the executable file path char file_path[MAX_PATH + 1]; file_path[MAX_PATH] = '\0'; ::GetModuleFileName(NULL, file_path, MAX_PATH); //创建服务 SC_HANDLE handle_services = ::CreateService( handle_scm, app_base_name_.c_str(), service_name_.c_str(), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, file_path, NULL, NULL, "", NULL, NULL); if (handle_services == NULL) { printf("install service %s fail. err=%d\n", app_base_name_.c_str(), GetLastError()); ::CloseServiceHandle(handle_scm); //MessageBox(NULL, _T("Couldn't create service"), app_base_name_.c_str(), MB_OK); return -1; } // 修改描述 SC_LOCK lock = LockServiceDatabase(handle_scm); if (lock != NULL) { SERVICE_DESCRIPTION desc; desc.lpDescription = (LPSTR)service_desc_.c_str(); ChangeServiceConfig2(handle_services, SERVICE_CONFIG_DESCRIPTION, &desc); UnlockServiceDatabase(handle_scm); } ::CloseServiceHandle(handle_services); ::CloseServiceHandle(handle_scm); printf("install service %s succ.\n", app_base_name_.c_str()); return 0; } //卸载服务 int ZCE_Server_Base::win_services_uninstall() { if (!win_services_isinstalled()) { printf("uninstall fail. service %s is not exist.\n", app_base_name_.c_str()); return 0; } SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm == NULL) { //::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK); printf("uninstall fail. can't open service manager"); return FALSE; } SC_HANDLE handle_services = ::OpenService(handle_scm, app_base_name_.c_str(), SERVICE_STOP | DELETE); if (handle_services == NULL) { ::CloseServiceHandle(handle_scm); //::MessageBox(NULL, _T("Couldn't open service"), app_base_name_.c_str(), MB_OK); printf("can't open service %s\n", app_base_name_.c_str()); return -1; } SERVICE_STATUS status; ::ControlService(handle_services, SERVICE_CONTROL_STOP, &status); //删除服务 BOOL bDelete = ::DeleteService(handle_services); ::CloseServiceHandle(handle_services); ::CloseServiceHandle(handle_scm); if (bDelete) { printf("uninstall service %s succ.\n", app_base_name_.c_str()); return 0; } printf("uninstall service %s fail.\n", app_base_name_.c_str()); //LogEvent(_T("Service could not be deleted")); return -1; } //检查服务是否安装 bool ZCE_Server_Base::win_services_isinstalled() { bool b_result = false; //打开服务控制管理器 SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm != NULL) { //打开服务 SC_HANDLE handle_service = ::OpenService(handle_scm, app_base_name_.c_str(), SERVICE_QUERY_CONFIG); if (handle_service != NULL) { b_result = true; ::CloseServiceHandle(handle_service); } ::CloseServiceHandle(handle_scm); } return b_result; } //服务运行函数 void WINAPI ZCE_Server_Base::win_service_main() { //WIN服务用的状态 static SERVICE_STATUS_HANDLE handle_service_status = NULL; SERVICE_STATUS status; status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwCurrentState = SERVICE_STOPPED; status.dwControlsAccepted = SERVICE_ACCEPT_STOP; status.dwWin32ExitCode = 0; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 0; status.dwWaitHint = 0; // Register the control request handler status.dwCurrentState = SERVICE_START_PENDING; status.dwControlsAccepted = SERVICE_ACCEPT_STOP; //注册服务控制 handle_service_status = ::RegisterServiceCtrlHandler(base_instance_->get_app_basename(), win_services_ctrl); if (handle_service_status == NULL) { //LogEvent(_T("Handler not installed")); return; } SetServiceStatus(handle_service_status, &status); status.dwWin32ExitCode = S_OK; status.dwCheckPoint = 0; status.dwWaitHint = 0; status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(handle_service_status, &status); //base_instance_->do_run(); status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(handle_service_status, &status); //LogEvent(_T("Service stopped")); } //服务控制台所需要的控制函数 void WINAPI ZCE_Server_Base::win_services_ctrl(DWORD op_code) { switch (op_code) { case SERVICE_CONTROL_STOP: // base_instance_->app_run_ = false; break; case SERVICE_CONTROL_PAUSE: break; case SERVICE_CONTROL_CONTINUE: break; case SERVICE_CONTROL_INTERROGATE: break; case SERVICE_CONTROL_SHUTDOWN: break; default: //LogEvent(_T("Bad service request")); break; } } #endif //#if defined ZCE_OS_WINDOWS
20,287
8,127
// 编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数。 // void函数以下面的格式显示这两个值。 // Enter the number of hours: 9 // Enter the number of minutes: 28 // Time: 9:28 #include <iostream> using namespace std; void show_time(int hour, int minutes); int main() { int hour, minutes; cout << "Enter the number of hours: "; cin >> hour; cout << "Enter the number of minutes: "; cin >> minutes; show_time(hour, minutes); return 0; } void show_time(int hour, int minutes) { cout << "Time: " << hour << ":" << minutes << endl; }
544
224
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <niftkLogHelper.h> #include <niftkConversionUtils.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkNifTKImageIOFactory.h> #include <itkShrinkImageFilter.h> #include <itkCommandLineHelper.h> /*! * \file niftkShrinkImage.cxx * \page niftkShrinkImage * \section niftkShrinkImageSummary Runs the ITK ShrinkImageFilter. */ void Usage(char *exec) { niftk::LogHelper::PrintCommandLineHeader(std::cout); std::cout << " " << std::endl; std::cout << " Runs the ITK ShrinkImageFilter on a 2D or 3D image." << std::endl; std::cout << " " << std::endl; std::cout << " " << exec << " -i inputFileName -o outputFileName [options]" << std::endl; std::cout << " " << std::endl; std::cout << "*** [mandatory] ***" << std::endl << std::endl; std::cout << " -i <filename> Input image " << std::endl; std::cout << " -o <filename> Output image" << std::endl << std::endl; std::cout << "*** [options] ***" << std::endl << std::endl; std::cout << " -f <int> [2] Shrink factor" << std::endl; } struct arguments { std::string inputImage; std::string outputImage; int factor; }; template <int Dimension, class PixelType> int DoMain(arguments args) { typedef typename itk::Image< PixelType, Dimension > InputImageType; typedef typename itk::ImageFileReader< InputImageType > InputImageReaderType; typedef typename itk::ImageFileWriter< InputImageType > OutputImageWriterType; typedef typename itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkFilterType; typename InputImageReaderType::Pointer imageReader = InputImageReaderType::New(); imageReader->SetFileName(args.inputImage); typename ShrinkFilterType::Pointer filter = ShrinkFilterType::New(); filter->SetInput(imageReader->GetOutput()); for (unsigned int i = 0; i < Dimension; i++) { filter->SetShrinkFactor(i, args.factor); } typename OutputImageWriterType::Pointer imageWriter = OutputImageWriterType::New(); imageWriter->SetFileName(args.outputImage); imageWriter->SetInput(filter->GetOutput()); try { imageWriter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Failed: " << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * \brief Takes image and shrinks it by a factor in each dimension. */ int main(int argc, char** argv) { itk::NifTKImageIOFactory::Initialize(); // To pass around command line args struct arguments args; // Define defaults args.factor = 2; // Parse command line args for(int i=1; i < argc; i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){ Usage(argv[0]); return -1; } else if(strcmp(argv[i], "-i") == 0){ args.inputImage=argv[++i]; std::cout << "Set -i=" << args.inputImage << std::endl; } else if(strcmp(argv[i], "-o") == 0){ args.outputImage=argv[++i]; std::cout << "Set -o=" << args.outputImage << std::endl; } else if(strcmp(argv[i], "-f") == 0){ args.factor=atoi(argv[++i]); std::cout << "Set -f=" << niftk::ConvertToString(args.factor) << std::endl; } else { std::cerr << argv[0] << ":\tParameter " << argv[i] << " unknown." << std::endl; return -1; } } // Validate command line args if (args.inputImage.length() == 0 || args.outputImage.length() == 0) { Usage(argv[0]); return EXIT_FAILURE; } int dims = itk::PeekAtImageDimension(args.inputImage); if (dims != 2 && dims != 3) { std::cout << "Unsuported image dimension" << std::endl; return EXIT_FAILURE; } int result; switch (itk::PeekAtComponentType(args.inputImage)) { case itk::ImageIOBase::UCHAR: if (dims == 2) { result = DoMain<2, unsigned char>(args); } else { result = DoMain<3, unsigned char>(args); } break; case itk::ImageIOBase::CHAR: if (dims == 2) { result = DoMain<2, char>(args); } else { result = DoMain<3, char>(args); } break; case itk::ImageIOBase::USHORT: if (dims == 2) { result = DoMain<2, unsigned short>(args); } else { result = DoMain<3, unsigned short>(args); } break; case itk::ImageIOBase::SHORT: if (dims == 2) { result = DoMain<2, short>(args); } else { result = DoMain<3, short>(args); } break; case itk::ImageIOBase::UINT: if (dims == 2) { result = DoMain<2, unsigned int>(args); } else { result = DoMain<3, unsigned int>(args); } break; case itk::ImageIOBase::INT: if (dims == 2) { result = DoMain<2, int>(args); } else { result = DoMain<3, int>(args); } break; case itk::ImageIOBase::ULONG: if (dims == 2) { result = DoMain<2, unsigned long>(args); } else { result = DoMain<3, unsigned long>(args); } break; case itk::ImageIOBase::LONG: if (dims == 2) { result = DoMain<2, long>(args); } else { result = DoMain<3, long>(args); } break; case itk::ImageIOBase::FLOAT: if (dims == 2) { result = DoMain<2, float>(args); } else { result = DoMain<3, float>(args); } break; case itk::ImageIOBase::DOUBLE: if (dims == 2) { result = DoMain<2, double>(args); } else { result = DoMain<3, double>(args); } break; default: std::cerr << "non standard pixel format" << std::endl; return EXIT_FAILURE; } return result; }
6,569
2,233
#ifndef IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_ #define IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_ #include "idocp/contact_complementarity/contact_complementarity_component_base.hpp" #include "idocp/constraints/pdipm_func.hpp" #include <cmath> #include <exception> #include <assert.h> namespace idocp { template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ContactComplementarityComponentBase(const double barrier, const double fraction_to_boundary_rate) : barrier_(barrier), fraction_to_boundary_rate_(fraction_to_boundary_rate) { try { if (barrier <= 0) { throw std::out_of_range( "invalid argment: barrirer must be positive"); } if (fraction_to_boundary_rate <= 0) { throw std::out_of_range( "invalid argment: fraction_to_boundary_rate must be positive"); } if (fraction_to_boundary_rate >= 1) { throw std::out_of_range( "invalid argment: fraction_to_boundary_rate must be less than 1"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } } template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ContactComplementarityComponentBase() : barrier_(0), fraction_to_boundary_rate_(0) { } template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ~ContactComplementarityComponentBase() { } template <typename Derived> inline bool ContactComplementarityComponentBase<Derived>::isFeasible( Robot& robot, ConstraintComponentData& data, const SplitSolution& s) const { return static_cast<const Derived*>(this)->isFeasible_impl(robot, data, s); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::setSlackAndDual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { static_cast<const Derived*>(this)->setSlackAndDual_impl(robot, data, dtau, s); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::augmentDualResidual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTResidual& kkt_residual) { static_cast<Derived*>(this)->augmentDualResidual_impl(robot, data, dtau, s, kkt_residual); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::condenseSlackAndDual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTMatrix& kkt_matrix, KKTResidual& kkt_residual) { static_cast<const Derived*>(this)->condenseSlackAndDual_impl(robot, data, dtau, s, kkt_matrix, kkt_residual); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: computeSlackAndDualDirection(Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, const SplitDirection& d) const { static_cast<const Derived*>(this)->computeSlackAndDualDirection_impl( robot, data, dtau, s, d); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::residualL1Nrom( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { return static_cast<const Derived*>(this)->residualL1Nrom_impl( robot, data, dtau, s); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::squaredKKTErrorNorm( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { return static_cast<const Derived*>(this)->squaredKKTErrorNorm_impl( robot, data, dtau, s); } template <typename Derived> inline int ContactComplementarityComponentBase<Derived>::dimc() const { return static_cast<const Derived*>(this)->dimc_impl(); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::maxSlackStepSize( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->maxSlackStepSize_impl( data, is_contact_active); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::maxDualStepSize( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->maxDualStepSize_impl( data, is_contact_active); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::updateSlack( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { assert(step_size > 0); static_cast<const Derived*>(this)->updateSlack_impl(data, is_contact_active, step_size); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::updateDual( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { assert(step_size > 0); static_cast<const Derived*>(this)->updateDual_impl(data, is_contact_active, step_size); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->costSlackBarrier_impl( data, is_contact_active); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { return static_cast<const Derived*>(this)->costSlackBarrier_impl( data, is_contact_active, step_size); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::setBarrier( const double barrier) { assert(barrier > 0); barrier_ = barrier; } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: setFractionToBoundaryRate(const double fraction_to_boundary_rate) { assert(fraction_to_boundary_rate > 0); fraction_to_boundary_rate_ = fraction_to_boundary_rate; } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: setSlackAndDualPositive(Eigen::VectorXd& slack, Eigen::VectorXd& dual) const { pdipmfunc::SetSlackAndDualPositive(barrier_, slack, dual); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const double slack) const { return - barrier_ * std::log(slack); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const double slack, const double dslack, const double step_size) const { return - barrier_ * std::log(slack + step_size * dslack); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::computeDuality( const double slack, const double dual) const { return pdipmfunc::ComputeDuality(barrier_, slack, dual); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::computeDualDirection( const double slack, const double dual, const double dslack, const double duality) const { return pdipmfunc::ComputeDualDirection(slack, dual, dslack, duality); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::fractionToBoundary( const double vec, const double dvec) const { return pdipmfunc::FractionToBoundary(fraction_to_boundary_rate_, vec, dvec); } } // namespace idocp #endif // IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_
8,071
2,516
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // // © 2020 Shockazoid, Inc. All Rights Reserved. // #ifndef __h3o_ClassSymbol__ #define __h3o_ClassSymbol__ #include <vector> #include "TypeSpec.hpp" #include "PackageSymbol.hpp" namespace hydro { class ClassSymbol : public Symbol { private: PackageSymbol *_package; std::vector<TypeSpec *> _types; public: ClassSymbol(Modifier *modifier, Name *name, Scope *ownScope, PackageSymbol *package) : Symbol{modifier, name, ownScope, package}, _types{}, _package{package} {} virtual ~ClassSymbol() {} void append(TypeSpec *type) { _types.push_back(type); } const std::vector<TypeSpec *> &types() const { return _types; } PackageSymbol *package() const { return _package; } std::string fullName() const { return _package ? _package->name()->value() + "::" + name()->value() : name()->value(); } }; } // namespace hydro #endif /* __h3o_ClassSymbol__ */
1,248
409
// Copyright 2018 Chia Network Inc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <pybind11/pybind11.h> #include <pybind11/stl.h> #include <pybind11/operators.h> #include "../src/privatekey.hpp" #include "../src/bls.hpp" namespace py = pybind11; using namespace bls; PYBIND11_MODULE(blspy, m) { py::class_<bn_t*>(m, "bn_ptr"); py::class_<AggregationInfo>(m, "AggregationInfo") .def("from_msg_hash", [](const PublicKey &pk, const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return AggregationInfo::FromMsgHash(pk, input); }) .def("from_msg", [](const PublicKey &pk, const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return AggregationInfo::FromMsg(pk, input, len(b)); }) .def("merge_infos", &AggregationInfo::MergeInfos) .def("get_pubkeys", &AggregationInfo::GetPubKeys) .def("get_msg_hashes", [](const AggregationInfo &self) { std::vector<uint8_t*> msgHashes = self.GetMessageHashes(); std::vector<py::bytes> ret; for (const uint8_t* msgHash : msgHashes) { ret.push_back(py::bytes(reinterpret_cast<const char*>(msgHash), BLS::MESSAGE_HASH_LEN)); } return ret; }) .def(py::self == py::self) .def(py::self != py::self) .def(py::self < py::self) .def("__repr__", [](const AggregationInfo &a) { std::stringstream s; s << a; return "<AggregationInfo " + s.str() + ">"; }); py::class_<PrivateKey>(m, "PrivateKey") .def_property_readonly_static("PRIVATE_KEY_SIZE", [](py::object self) { return PrivateKey::PRIVATE_KEY_SIZE; }) .def("from_seed", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return PrivateKey::FromSeed(input, len(b)); }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return PrivateKey::FromBytes(input); }) .def("serialize", [](const PrivateKey &k) { uint8_t* output = Util::SecAlloc<uint8_t>(PrivateKey::PRIVATE_KEY_SIZE); k.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), PrivateKey::PRIVATE_KEY_SIZE); Util::SecFree(output); return ret; }) .def("get_public_key", [](const PrivateKey &k) { return k.GetPublicKey(); }) .def("aggregate", &PrivateKey::Aggregate) .def("sign", [](const PrivateKey &k, const py::bytes &msg) { uint8_t* input = reinterpret_cast<uint8_t*>(&std::string(msg)[0]); return k.Sign(input, len(msg)); }) .def("sign_prehashed", [](const PrivateKey &k, const py::bytes &msg) { uint8_t* input = reinterpret_cast<uint8_t*>(&std::string(msg)[0]); return k.SignPrehashed(input); }) .def(py::self == py::self) .def(py::self != py::self) .def("__repr__", [](const PrivateKey &k) { uint8_t* output = Util::SecAlloc<uint8_t>(PrivateKey::PRIVATE_KEY_SIZE); k.Serialize(output); std::string ret = "<PrivateKey " + Util::HexStr(output, PrivateKey::PRIVATE_KEY_SIZE) + ">"; Util::SecFree(output); return ret; }); py::class_<PublicKey>(m, "PublicKey") .def_property_readonly_static("PUBLIC_KEY_SIZE", [](py::object self) { return PublicKey::PUBLIC_KEY_SIZE; }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return PublicKey::FromBytes(input); }) .def("aggregate", &PublicKey::Aggregate) .def("get_fingerprint", &PublicKey::GetFingerprint) .def("serialize", [](const PublicKey &pk) { uint8_t* output = new uint8_t[PublicKey::PUBLIC_KEY_SIZE]; pk.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), PublicKey::PUBLIC_KEY_SIZE); delete[] output; return ret; }) .def(py::self == py::self) .def(py::self != py::self) .def("__repr__", [](const PublicKey &pk) { std::stringstream s; s << pk; return "<PublicKey " + s.str() + ">"; }); py::class_<Signature>(m, "Signature") .def_property_readonly_static("SIGNATURE_SIZE", [](py::object self) { return Signature::SIGNATURE_SIZE; }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return Signature::FromBytes(input); }) .def("serialize", [](const Signature &sig) { uint8_t* output = new uint8_t[Signature::SIGNATURE_SIZE]; sig.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), Signature::SIGNATURE_SIZE); delete[] output; return ret; }) .def("verify", &Signature::Verify) .def("aggregate", &Signature::AggregateSigs) .def("divide_by", &Signature::DivideBy) .def("set_aggregation_info", &Signature::SetAggregationInfo) .def("get_aggregation_info", [](const Signature &sig) { return *sig.GetAggregationInfo(); }) .def(py::self == py::self) .def(py::self != py::self) .def("__repr__", [](const Signature &sig) { std::stringstream s; s << sig; return "<Signature " + s.str() + ">"; }); py::class_<ChainCode>(m, "ChainCode") .def_property_readonly_static("CHAIN_CODE_KEY_SIZE", [](py::object self) { return ChainCode::CHAIN_CODE_SIZE; }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return ChainCode::FromBytes(input); }) .def("serialize", [](const ChainCode &cc) { uint8_t* output = new uint8_t[ChainCode::CHAIN_CODE_SIZE]; cc.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), ChainCode::CHAIN_CODE_SIZE); delete[] output; return ret; }) .def("__repr__", [](const ChainCode &cc) { uint8_t* output = new uint8_t[ChainCode::CHAIN_CODE_SIZE]; cc.Serialize(output); std::string ret = "<ChainCode " + Util::HexStr(output, ChainCode::CHAIN_CODE_SIZE) + ">"; Util::SecFree(output); return ret; }); py::class_<ExtendedPublicKey>(m, "ExtendedPublicKey") .def_property_readonly_static("EXTENDED_PUBLIC_KEY_SIZE", [](py::object self) { return ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE; }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return ExtendedPublicKey::FromBytes(input); }) .def("public_child", &ExtendedPublicKey::PublicChild) .def("get_version", &ExtendedPublicKey::GetVersion) .def("get_depth", &ExtendedPublicKey::GetDepth) .def("get_parent_fingerprint", &ExtendedPublicKey::GetParentFingerprint) .def("get_child_number", &ExtendedPublicKey::GetChildNumber) .def("get_chain_code", &ExtendedPublicKey::GetChainCode) .def("get_public_key", &ExtendedPublicKey::GetPublicKey) .def(py::self == py::self) .def(py::self != py::self) .def("serialize", [](const ExtendedPublicKey &pk) { uint8_t* output = new uint8_t[ ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE]; pk.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE); delete[] output; return ret; }) .def("__repr__", [](const ExtendedPublicKey &pk) { uint8_t* output = new uint8_t[ ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE]; pk.Serialize(output); std::string ret = "<ExtendedPublicKey " + Util::HexStr(output, ExtendedPublicKey::EXTENDED_PUBLIC_KEY_SIZE) + ">"; Util::SecFree(output); return ret; }); py::class_<ExtendedPrivateKey>(m, "ExtendedPrivateKey") .def_property_readonly_static("EXTENDED_PRIVATE_KEY_SIZE", [](py::object self) { return ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE; }) .def("from_seed", [](const py::bytes &seed) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(seed)[0]); return ExtendedPrivateKey::FromSeed(input, len(seed)); }) .def("from_bytes", [](const py::bytes &b) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(b)[0]); return ExtendedPrivateKey::FromBytes(input); }) .def("private_child", &ExtendedPrivateKey::PrivateChild) .def("public_child", &ExtendedPrivateKey::PublicChild) .def("get_version", &ExtendedPrivateKey::GetVersion) .def("get_depth", &ExtendedPrivateKey::GetDepth) .def("get_parent_fingerprint", &ExtendedPrivateKey::GetParentFingerprint) .def("get_child_number", &ExtendedPrivateKey::GetChildNumber) .def("get_chain_code", &ExtendedPrivateKey::GetChainCode) .def("get_private_key", &ExtendedPrivateKey::GetPrivateKey) .def("get_public_key", &ExtendedPrivateKey::GetPublicKey) .def("get_extended_public_key", &ExtendedPrivateKey::GetExtendedPublicKey) .def(py::self == py::self) .def(py::self != py::self) .def("serialize", [](const ExtendedPrivateKey &k) { uint8_t* output = Util::SecAlloc<uint8_t>( ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE); k.Serialize(output); py::bytes ret = py::bytes(reinterpret_cast<char*>(output), ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE); Util::SecFree(output); return ret; }) .def("__repr__", [](const ExtendedPrivateKey &k) { uint8_t* output = Util::SecAlloc<uint8_t>( ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE); k.Serialize(output); std::string ret = "<ExtendedPrivateKey " + Util::HexStr(output, ExtendedPrivateKey::EXTENDED_PRIVATE_KEY_SIZE) + ">"; Util::SecFree(output); return ret; }); py::class_<BLS>(m, "BLS") .def_property_readonly_static("MESSAGE_HASH_LEN", [](py::object self) { return BLS::MESSAGE_HASH_LEN; }); py::class_<Util>(m, "Util") .def("hash256", [](const py::bytes &message) { const uint8_t* input = reinterpret_cast<const uint8_t*>(&std::string(message)[0]); uint8_t output[BLS::MESSAGE_HASH_LEN]; Util::Hash256(output, input, len(message)); return py::bytes(reinterpret_cast<char*>(output), BLS::MESSAGE_HASH_LEN); }); #ifdef VERSION_INFO m.attr("__version__") = VERSION_INFO; #else m.attr("__version__") = "dev"; #endif }
12,194
3,989
#include <bits/stdc++.h> using namespace std; int main() { set<int> S; S.insert(1); // O(logN) S.insert(3); S.insert(-8); S.insert(0); S.insert(10); S.erase(3); // O(logN) /* set maintains ascending order */ // for int x in S for (int x : S) { cout << x << " "; } cout << endl; auto it = S.find(8); if (it == S.end()) { cout << "element not found" << endl; } else { cout << "element found" << endl; cout << *it << endl; } auto it2 = S.lower_bound(1); //first iterator >= //1 auto it3 = S.upper_bound(1); //first iterator > //3 cout << *it2 << " " << *it3 << endl; auto it4 = S.upper_bound(10); //S.end() //4 if (it4 == S.end()) { cout << "element not found" << endl; } }
829
328
#pragma once #include <string> #include <libadb/libadb.hpp> #include <cstdint> namespace adb::api { enum class GuildFeature : uint64_t { UNKNOWN, /// guild has access to set an animated guild banner image ANIMATED_BANNER, /// guild has access to set an animated guild icon ANIMATED_ICON, /// guild has access to set a guild banner image BANNER, /// guild has access to use commerce features (i.e. create store channels) COMMERCE, /// guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates COMMUNITY, /// guild is able to be discovered in the directory DISCOVERABLE, /// guild is able to be featured in the directory FEATURABLE, /// guild has access to set an invite splash background INVITE_SPLASH, /// guild has enabled Membership Screening MEMBER_VERIFICATION_GATE_ENABLED, /// guild has enabled monetization MONETIZATION_ENABLED, /// guild has increased custom sticker slots MORE_STICKERS, /// guild has access to create news channels NEWS, /// guild is partnered PARTNERED, /// guild can be previewed before joining via Membership Screening or the directory PREVIEW_ENABLED, /// guild has access to create private threads PRIVATE_THREADS, /// guild is able to set role icons ROLE_ICONS, /// guild has access to the seven day archive time for threads SEVEN_DAY_THREAD_ARCHIVE, /// guild has access to the three day archive time for threads THREE_DAY_THREAD_ARCHIVE, /// guild has enabled ticketed events TICKETED_EVENTS_ENABLED, /// guild has access to set a vanity URL VANITY_URL, /// guild is verified VERIFIED, /// guild has access to set 384kbps bitrate in voice (previously VIP voice servers) VIP_REGIONS, /// guild has enabled the welcome screen WELCOME_SCREEN_ENABLED }; LIBADB_API std::string to_string(GuildFeature e); LIBADB_API void from_string(const std::string &str, GuildFeature &feature); }
2,268
672
#include "TwitterGraph.hpp" #include <vector> #include <iterator> #include <algorithm> int TwitterGraph::weakComponents() { int maxComponent = 0; for (unsigned int i = 0; i < nodes.size(); i++) { if (nodes[i].componentID == NO_COMPONENT) { const int currentComponent = maxComponent++; bfs(i, [currentComponent, this] (int i) -> bool { if (nodes[i].componentID == NO_COMPONENT) { nodes[i].componentID = currentComponent; return true; } else if (nodes[i].componentID != currentComponent) { recolor(nodes[i].componentID, currentComponent); return false; } return false; }); } } // Count the occurrernces for the different components. vector<int> componentCounts(nodes.size(), 0); for (const auto& node : nodes) { componentCounts[node.componentID]++; } // Save the largest component ID and return the size. const auto it = max_element(componentCounts.begin(), componentCounts.end()); giantComponentID = distance(componentCounts.begin(), it); return giantComponentID; } void TwitterGraph::recolor(int original, int to) { for (auto& node : nodes) { if (node.componentID == original) { node.componentID = to; } } }
1,187
430
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved. #include "PropertyEditorPrivatePCH.h" #include "PropertyNode.h" #include "ItemPropertyNode.h" #include "CategoryPropertyNode.h" #include "ObjectPropertyNode.h" FItemPropertyNode::FItemPropertyNode(void) : FPropertyNode() { } FItemPropertyNode::~FItemPropertyNode(void) { } /** * Calculates the memory address for the data associated with this item's property. This is typically the value of a UProperty or a UObject address. * * @param StartAddress the location to use as the starting point for the calculation; typically the address of the object that contains this property. * * @return a pointer to a UProperty value or UObject. (For dynamic arrays, you'd cast this value to an FArray*) */ uint8* FItemPropertyNode::GetValueBaseAddress( uint8* StartAddress ) { UProperty* MyProperty = GetProperty(); if( MyProperty ) { UArrayProperty* OuterArrayProp = Cast<UArrayProperty>(MyProperty->GetOuter()); if ( OuterArrayProp != NULL ) { FScriptArrayHelper ArrayHelper(OuterArrayProp,ParentNode->GetValueBaseAddress(StartAddress)); if ( ParentNode->GetValueBaseAddress(StartAddress) != NULL && ArrayIndex < ArrayHelper.Num() ) { return ArrayHelper.GetRawPtr() + ArrayOffset; } return NULL; } else { uint8* ValueAddress = ParentNode->GetValueAddress(StartAddress); if (ValueAddress != NULL && ParentNode->GetProperty() != MyProperty) { // if this is not a fixed size array (in which the parent property and this property are the same), we need to offset from the property (otherwise, the parent already did that for us) ValueAddress = Property->ContainerPtrToValuePtr<uint8>(ValueAddress); } if ( ValueAddress != NULL ) { ValueAddress += ArrayOffset; } return ValueAddress; } } return NULL; } /** * Calculates the memory address for the data associated with this item's value. For most properties, identical to GetValueBaseAddress. For items corresponding * to dynamic array elements, the pointer returned will be the location for that element's data. * * @param StartAddress the location to use as the starting point for the calculation; typically the address of the object that contains this property. * * @return a pointer to a UProperty value or UObject. (For dynamic arrays, you'd cast this value to whatever type is the Inner for the dynamic array) */ uint8* FItemPropertyNode::GetValueAddress( uint8* StartAddress ) { uint8* Result = GetValueBaseAddress(StartAddress); UProperty* MyProperty = GetProperty(); UArrayProperty* ArrayProperty; if( Result != NULL && (ArrayProperty=Cast<UArrayProperty>(MyProperty))!=NULL ) { FScriptArrayHelper ArrayHelper(ArrayProperty,Result); Result = ArrayHelper.GetRawPtr(); } return Result; } /** * Overridden function for special setup */ void FItemPropertyNode::InitExpansionFlags (void) { UProperty* MyProperty = GetProperty(); FReadAddressList Addresses; if( Cast<UStructProperty>(MyProperty) || ( Cast<UArrayProperty>(MyProperty) && GetReadAddress(false,Addresses) ) || HasNodeFlags(EPropertyNodeFlags::EditInline) || ( Property->ArrayDim > 1 && ArrayIndex == -1 ) ) { SetNodeFlags(EPropertyNodeFlags::CanBeExpanded, true); } } /** * Overridden function for Creating Child Nodes */ void FItemPropertyNode::InitChildNodes() { //NOTE - this is only turned off as to not invalidate child object nodes. UProperty* Property = GetProperty(); UStructProperty* StructProperty = Cast<UStructProperty>(Property); UArrayProperty* ArrayProperty = Cast<UArrayProperty>(Property); UObjectPropertyBase* ObjectProperty = Cast<UObjectPropertyBase>(Property); const bool bShouldShowHiddenProperties = !!HasNodeFlags(EPropertyNodeFlags::ShouldShowHiddenProperties); const bool bShouldShowDisableEditOnInstance = !!HasNodeFlags(EPropertyNodeFlags::ShouldShowDisableEditOnInstance); if( Property->ArrayDim > 1 && ArrayIndex == -1 ) { // Do not add array children which are defined by an enum but the enum at the array index is hidden // This only applies to static arrays static const FName NAME_ArraySizeEnum("ArraySizeEnum"); UEnum* ArraySizeEnum = NULL; if (Property->HasMetaData(NAME_ArraySizeEnum)) { ArraySizeEnum = FindObject<UEnum>(NULL, *Property->GetMetaData(NAME_ArraySizeEnum)); } // Expand array. for( int32 ArrayIndex = 0 ; ArrayIndex < Property->ArrayDim ; ArrayIndex++ ) { bool bShouldBeHidden = false; if( ArraySizeEnum ) { // The enum at this array index is hidden bShouldBeHidden = ArraySizeEnum->HasMetaData(TEXT("Hidden"), ArrayIndex ); } if( !bShouldBeHidden ) { TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode); FPropertyNodeInitParams InitParams; InitParams.ParentNode = SharedThis(this); InitParams.Property = Property; InitParams.ArrayOffset = ArrayIndex*Property->ElementSize; InitParams.ArrayIndex = ArrayIndex; InitParams.bAllowChildren = true; InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties; InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance; NewItemNode->InitNode( InitParams ); AddChildNode(NewItemNode); } } } else if( ArrayProperty ) { void* Array = NULL; FReadAddressList Addresses; if ( GetReadAddress(!!HasNodeFlags(EPropertyNodeFlags::SingleSelectOnly), Addresses ) ) { Array = Addresses.GetAddress(0); } if( Array ) { for( int32 ArrayIndex = 0 ; ArrayIndex < FScriptArrayHelper::Num(Array) ; ArrayIndex++ ) { TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode ); FPropertyNodeInitParams InitParams; InitParams.ParentNode = SharedThis(this); InitParams.Property = ArrayProperty->Inner; InitParams.ArrayOffset = ArrayIndex*ArrayProperty->Inner->ElementSize; InitParams.ArrayIndex = ArrayIndex; InitParams.bAllowChildren = true; InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties; InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance; NewItemNode->InitNode( InitParams ); AddChildNode(NewItemNode); } } } else if( StructProperty ) { // Expand struct. for( TFieldIterator<UProperty> It(StructProperty->Struct); It; ++It ) { UProperty* StructMember = *It; const bool bShowIfEditableProperty = StructMember->HasAnyPropertyFlags(CPF_Edit); const bool bShowIfDisableEditOnInstance = !StructMember->HasAnyPropertyFlags(CPF_DisableEditOnInstance) || bShouldShowDisableEditOnInstance; if (bShouldShowHiddenProperties || (bShowIfEditableProperty && bShowIfDisableEditOnInstance)) { TSharedPtr<FItemPropertyNode> NewItemNode( new FItemPropertyNode );//;//CreatePropertyItem(StructMember,INDEX_NONE,this); FPropertyNodeInitParams InitParams; InitParams.ParentNode = SharedThis(this); InitParams.Property = StructMember; InitParams.ArrayOffset = 0; InitParams.ArrayIndex = INDEX_NONE; InitParams.bAllowChildren = true; InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties; InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance; NewItemNode->InitNode( InitParams ); AddChildNode(NewItemNode); if ( FPropertySettings::Get().ExpandDistributions() == false) { // auto-expand distribution structs if ( Cast<UObjectProperty>(StructMember) || Cast<UWeakObjectProperty>(StructMember) || Cast<ULazyObjectProperty>(StructMember) || Cast<UAssetObjectProperty>(StructMember) ) { const FName StructName = StructProperty->Struct->GetFName(); if (StructName == NAME_RawDistributionFloat || StructName == NAME_RawDistributionVector) { NewItemNode->SetNodeFlags(EPropertyNodeFlags::Expanded, true); } } } } } } else if( ObjectProperty || Property->IsA(UInterfaceProperty::StaticClass())) { uint8* ReadValue = NULL; FReadAddressList ReadAddresses; if( GetReadAddress(!!HasNodeFlags(EPropertyNodeFlags::SingleSelectOnly), ReadAddresses, false ) ) { // We've got some addresses, and we know they're all NULL or non-NULL. // Have a peek at the first one, and only build an objects node if we've got addresses. if( UObject* Obj = (ReadAddresses.Num() > 0) ? ObjectProperty->GetObjectPropertyValue(ReadAddresses.GetAddress(0)) : nullptr ) { //verify it's not above in the hierarchy somewhere FObjectPropertyNode* ParentObjectNode = FindObjectItemParent(); while (ParentObjectNode) { for ( TPropObjectIterator Itor( ParentObjectNode->ObjectIterator() ) ; Itor ; ++Itor ) { if (*Itor == Obj) { SetNodeFlags(EPropertyNodeFlags::NoChildrenDueToCircularReference, true); //stop the circular loop!!! return; } } FPropertyNode* UpwardTravesalNode = ParentObjectNode->GetParentNode(); ParentObjectNode = (UpwardTravesalNode==NULL) ? NULL : UpwardTravesalNode->FindObjectItemParent(); } TSharedPtr<FObjectPropertyNode> NewObjectNode( new FObjectPropertyNode ); for ( int32 AddressIndex = 0 ; AddressIndex < ReadAddresses.Num() ; ++AddressIndex ) { NewObjectNode->AddObject( ObjectProperty->GetObjectPropertyValue(ReadAddresses.GetAddress(AddressIndex) ) ); } FPropertyNodeInitParams InitParams; InitParams.ParentNode = SharedThis(this); InitParams.Property = Property; InitParams.ArrayOffset = 0; InitParams.ArrayIndex = INDEX_NONE; InitParams.bAllowChildren = true; InitParams.bForceHiddenPropertyVisibility = bShouldShowHiddenProperties; InitParams.bCreateDisableEditOnInstanceNodes = bShouldShowDisableEditOnInstance; NewObjectNode->InitNode( InitParams ); AddChildNode(NewObjectNode); } } } } void FItemPropertyNode::SetDisplayNameOverride( const FText& InDisplayNameOverride ) { DisplayNameOverride = InDisplayNameOverride; } FText FItemPropertyNode::GetDisplayName() const { FText FinalDisplayName; if( !DisplayNameOverride.IsEmpty() ) { FinalDisplayName = DisplayNameOverride; } else { const UProperty* PropertyPtr = GetProperty(); if( GetArrayIndex()==-1 && PropertyPtr != NULL ) { // This item is not a member of an array, get a traditional display name if ( FPropertySettings::Get().ShowFriendlyPropertyNames() ) { //We are in "readable display name mode"../ Make a nice name FinalDisplayName = PropertyPtr->GetDisplayNameText(); if ( FinalDisplayName.IsEmpty() ) { FString PropertyDisplayName; bool bIsBoolProperty = Cast<const UBoolProperty>(PropertyPtr) != NULL; const UStructProperty* ParentStructProperty = Cast<const UStructProperty>(ParentNode->GetProperty()); if( ParentStructProperty && ParentStructProperty->Struct->GetFName() == NAME_Rotator ) { if( Property->GetFName() == "Roll" ) { PropertyDisplayName = TEXT("X"); } else if( Property->GetFName() == "Pitch" ) { PropertyDisplayName = TEXT("Y"); } else if( Property->GetFName() == "Yaw" ) { PropertyDisplayName = TEXT("Z"); } else { check(0); } } else { PropertyDisplayName = Property->GetName(); } if( GetDefault<UEditorStyleSettings>()->bShowFriendlyNames ) { PropertyDisplayName = FName::NameToDisplayString( PropertyDisplayName, bIsBoolProperty ); } FinalDisplayName = FText::FromString( PropertyDisplayName ); } } else { FinalDisplayName = FText::FromString( PropertyPtr->GetName() ); } } else { // Get the ArraySizeEnum class from meta data. static const FName NAME_ArraySizeEnum("ArraySizeEnum"); UEnum* ArraySizeEnum = NULL; if (PropertyPtr && PropertyPtr->HasMetaData(NAME_ArraySizeEnum)) { ArraySizeEnum = FindObject<UEnum>(NULL, *Property->GetMetaData(NAME_ArraySizeEnum)); } // This item is a member of an array, its display name is its index if ( PropertyPtr == NULL || ArraySizeEnum == NULL ) { FinalDisplayName = FText::AsNumber( GetArrayIndex() ); } else { FString TempDisplayName = ArraySizeEnum->GetEnumName(GetArrayIndex()); //fixup the display name if we have displayname metadata AdjustEnumPropDisplayName(ArraySizeEnum, TempDisplayName); FinalDisplayName = FText::FromString(TempDisplayName); // todo: should this be using ArraySizeEnum->GetEnumText? } } } return FinalDisplayName; } void FItemPropertyNode::SetToolTipOverride( const FText& InToolTipOverride ) { ToolTipOverride = InToolTipOverride; } FText FItemPropertyNode::GetToolTipText() const { if(!ToolTipOverride.IsEmpty()) { return ToolTipOverride; } return PropertyEditorHelpers::GetToolTipText(GetProperty()); }
12,805
4,426
// 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 "ash/services/ime/public/cpp/rulebased/def/ml_phone.h" #include "base/cxx17_backports.h" namespace ml_phone { const char* kId = "ml_phone"; bool kIs102 = false; const char* kTransforms[] = { u8"\\\\([a-zA-Z0-9@$])", u8"\\1", u8"([a-zA-Z])\u001d([a-zA-Z0-9`~!@#$%^&*()_=+:;\"',<.>?/|\\-])", u8"\\1\\2", u8"\\\\(ch)", u8"\\1", u8"([a-zA-Z])\u001d(ch)", u8"\\1\\2", u8"(M|\u001d?_M|\u0d02\u001d?m)", u8"\u0d2e\u0d4d\u0d2e\u0d4d", u8"([\u0d03-\u0d0a\u0d0c-\u0d4c\u0d4e-\u0d79])\u001d?R", u8"\\1\u0d7c", u8"([\u0d02-\u0d4c\u0d4e-\u0d79])\u001d?~", u8"\\1\u0d4d", u8"([\u0d02-\u0d4c\u0d4e-\u0d7f])\u0d7b\u001d?j", u8"\\1\u0d1e\u0d4d\u0d1e\u0d4d", u8"([\u0d15-\u0d3a])\u001d?a", u8"\\1\u0d3e", u8"([\u0d15-\u0d3a])\u001d?i", u8"\\1\u0d48", u8"([\u0d15-\u0d3a])\u001d?u", u8"\\1\u0d57", u8"([\u0d66-\u0d6f])\u001d?0", u8"\\1\u0d66", u8"([\u0d66-\u0d6f])\u001d?1", u8"\\1\u0d67", u8"([\u0d66-\u0d6f])\u001d?2", u8"\\1\u0d68", u8"([\u0d66-\u0d6f])\u001d?3", u8"\\1\u0d69", u8"([\u0d66-\u0d6f])\u001d?4", u8"\\1\u0d6a", u8"([\u0d66-\u0d6f])\u001d?5", u8"\\1\u0d6b", u8"([\u0d66-\u0d6f])\u001d?6", u8"\\1\u0d6c", u8"([\u0d66-\u0d6f])\u001d?7", u8"\\1\u0d6d", u8"([\u0d66-\u0d6f])\u001d?8", u8"\\1\u0d6e", u8"([\u0d66-\u0d6f])\u001d?9", u8"\\1\u0d6f", u8"([wv]|\u001d?_[wv])", u8"\u0d35\u0d4d", u8"(\u001d?R|\u0d0b\u001d?)A", u8"\u0d31\u0d3e", u8"(\u001d?R|\u0d0b\u001d?)E", u8"\u0d31\u0d47", u8"(\u001d?R|\u0d0b\u001d?)I", u8"\u0d31\u0d40", u8"(\u001d?R|\u0d0b\u001d?)U", u8"\u0d31\u0d42", u8"(\u001d?R|\u0d0b\u001d?)a", u8"\u0d31", u8"(\u001d?R|\u0d0b\u001d?)e", u8"\u0d31\u0d46", u8"(\u001d?R|\u0d0b\u001d?)i", u8"\u0d31\u0d3f", u8"(\u001d?R|\u0d0b\u001d?)u", u8"\u0d31\u0d41", u8"(\u001d?_)?B", u8"\u0d2c\u0d4d\u0d2c\u0d4d", u8"(\u001d?_)?D", u8"\u0d21\u0d4d", u8"(\u001d?_)?G", u8"\u0d17\u0d4d\u0d17\u0d4d", u8"(\u001d?_)?J", u8"\u0d1c\u0d4d\u0d1c\u0d4d", u8"(\u001d?_)?K", u8"\u0d15\u0d4d\u0d15\u0d4d", u8"(\u001d?_)?P", u8"\u0d2a\u0d4d\u0d2a\u0d4d", u8"(\u001d?_)?Y", u8"\u0d2f\u0d4d\u0d2f\u0d4d", u8"(\u001d?_)?Z", u8"\u0d34\u0d4d", u8"(\u001d?_)?T", u8"\u0d1f\u0d4d", u8"(\u001d?_)?[Sz]", u8"\u0d36\u0d4d", u8"(\u001d?_)?[VW]", u8"\u0d35\u0d4d\u0d35\u0d4d", u8"(\u001d?_)?[Cc]", u8"\u0d1a\u0d4d", u8"(\u001d?_)?[Xx]", u8"\u0d15\u0d4d\u0d38\u0d4d", u8"(\u001d?_)?b", u8"\u0d2c\u0d4d", u8"(\u001d?_)?d", u8"\u0d26\u0d4d", u8"(\u001d?_)?g", u8"\u0d17\u0d4d", u8"(\u001d?_)?h", u8"\u0d39\u0d4d", u8"(\u001d?_)?j", u8"\u0d1c\u0d4d", u8"(\u001d?_)?p", u8"\u0d2a\u0d4d", u8"(\u001d?_)?s", u8"\u0d38\u0d4d", u8"(\u001d?_)?y", u8"\u0d2f\u0d4d", u8"(\u0d05\u001d?a|_?A)", u8"\u0d06", u8"(\u0d07\u001d?i|\u0d0e\u001d?a|_?I|[\u0d0e\u0d07]\u001d?e)", u8"\u0d08", u8"(\u0d09\u001d?u|\u0d12\u001d?o|_?U)", u8"\u0d0a", u8"(\u0d0b\u001d?|\u001d?R)O", u8"\u0d31\u0d4b", u8"(\u0d0b\u001d?|\u001d?R)o", u8"\u0d31\u0d4a", u8"(\u0d0b\u001d?|\u001d?R)~", u8"\u0d31\u0d4d", u8"(\u0d15\u0d4d\u001d?h|\u001d?_[qQ]|[qQ])", u8"\u0d16\u0d4d", u8"(\u0d15\u0d4d|\u0d7f)\u001d?\\^", u8"\u0d15\u0d4d\u200d", u8"(\u0d1f\u0d4d\u001d?t|\u0d31\u0d4d\u0d31\u0d4d\u001d?[tT])", u8"\u0d1f\u0d4d\u0d1f\u0d4d", u8"(\u0d28\u0d4d\u001d?T|\u0d7a\u001d?[Tt])", u8"\u0d23\u0d4d\u0d1f\u0d4d", u8"(\u0d23\u0d4d\u001d?t|\u0d7b\u001d?T)", u8"\u0d23\u0d4d\u0d1f\u0d4d", u8"(\u0d23\u0d4d|\u0d7a)\u001d?\\^", u8"\u0d23\u0d4d\u200d", u8"(\u0d28\u0d4d\u001d?ch?|\u0d7b\u001d?ch?)", u8"\u0d1e\u0d4d\u0d1a\u0d4d", u8"(\u0d28\u0d4d|\u0d7b)\u001d?k", u8"\u0d19\u0d4d\u0d15\u0d4d", u8"(\u0d2a\u0d4d\u001d?h|\u001d?_[Ff]|[Ff])", u8"\u0d2b\u0d4d", u8"(\u0d30\u0d4d|\u0d7c)\u001d?\\^", u8"\u0d30\u0d4d\u200d", u8"(\u0d30\u0d4d|\u0d7c)\u001d?r", u8"\u0d31\u0d4d", u8"(\u0d4b\u0d3e*)\u001d?O", u8"\\1\u0d3e", u8"(\u0d4d\u001d?I|\u0d46\u001d?[ea]|\u0d3f\u001d?[ie])", u8"\u0d40", u8"(\u0d4d\u001d?U|\u0d41\u001d?u|\u0d4a\u001d?o)", u8"\u0d42", u8"(\u0d4d\u0d05|\u0d46)\u001d?i", u8"\u0d48", u8"(\u0d4d\u0d05|\u0d4a)\u001d?u", u8"\u0d57", u8"(\u0d7b|\u0d28\u0d4d)\u001d?\\^", u8"\u0d28\u0d4d\u200d", u8"(\u0d7b|\u0d28\u0d4d)\u001d?t", u8"\u0d28\u0d4d\u0d31\u0d4d", u8"(\u0d7d\u001d?L|\u0d7e\u001d?[lL])", u8"\u0d33\u0d4d\u0d33\u0d4d", u8"(\u0d7d|\u0d32\u0d4d)\u001d?\\^", u8"\u0d32\u0d4d\u200d", u8"(\u0d7e|\u0d33\u0d4d)\u001d?\\^", u8"\u0d33\u0d4d\u200d", u8"(k|\u001d?_[kc])", u8"\u0d15\u0d4d", u8"(\u0d7c\u001d?~|\u001d?_r)", u8"\u0d30\u0d4d", u8"(\u0d7e\u001d?~|\u001d?_L)", u8"\u0d33\u0d4d", u8"(\u0d7d\u001d?~|\u001d?_l)", u8"\u0d32\u0d4d", u8"(\u0d7a\u001d?~|\u001d?_N)", u8"\u0d23\u0d4d", u8"(\u0d7b\u001d?~|\u001d?_n)", u8"\u0d28\u0d4d", u8"(\u0d02\u001d?~|\u001d?_m)", u8"\u0d2e\u0d4d", u8"0#", u8"\u0d66", u8"1#", u8"\u0d67", u8"1/2#", u8"\u0d74", u8"1/4#", u8"\u0d73", u8"10#", u8"\u0d70", u8"100#", u8"\u0d71", u8"1000#", u8"\u0d72", u8"2#", u8"\u0d68", u8"3#", u8"\u0d69", u8"3/4#", u8"\u0d75", u8"4#", u8"\u0d6a", u8"5#", u8"\u0d6b", u8"6#", u8"\u0d6c", u8"7#", u8"\u0d6d", u8"8#", u8"\u0d6e", u8"9#", u8"\u0d6f", u8"@", u8"\u0d4d", u8"@a", u8"\u0d4d\u0d05", u8"@aL", u8"\u0d7e", u8"@aN", u8"\u0d7a", u8"@aa", u8"\u0d3e", u8"@ai", u8"\u0d48", u8"@al", u8"\u0d7d", u8"@am", u8"\u0d02", u8"@an", u8"\u0d7b", u8"@ar", u8"\u0d7c", u8"@au", u8"\u0d57", u8"C", u8"\u0d1a\u0d4d\u0d1a\u0d4d", u8"H", u8"\u0d03", u8"[\u0d05\u0d0e]\u001d?i", u8"\u0d10", u8"[\u0d05\u0d12]\u001d?u", u8"\u0d14", u8"\\$", u8"\u20b9", u8"\u001d?_X", u8"\u0d15\u0d4d\u0d37\u0d4d", u8"\u0d02\u001d?A", u8"\u0d2e\u0d3e", u8"\u0d02\u001d?E", u8"\u0d2e\u0d47", u8"\u0d02\u001d?I", u8"\u0d2e\u0d40", u8"\u0d02\u001d?O", u8"\u0d2e\u0d4b", u8"\u0d02\u001d?U", u8"\u0d2e\u0d42", u8"\u0d02\u001d?[Ll]", u8"\u0d2e\u0d4d\u0d32\u0d4d", u8"\u0d02\u001d?a", u8"\u0d2e", u8"\u0d02\u001d?e", u8"\u0d2e\u0d46", u8"\u0d02\u001d?i", u8"\u0d2e\u0d3f", u8"\u0d02\u001d?n", u8"\u0d2e\u0d4d\u0d28\u0d4d", u8"\u0d02\u001d?o", u8"\u0d2e\u0d4a", u8"\u0d02\u001d?p", u8"\u0d2e\u0d4d\u0d2a\u0d4d", u8"\u0d02\u001d?r", u8"\u0d2e\u0d4d\u0d30\u0d4d", u8"\u0d02\u001d?R", u8"\u0d2e\u0d43", u8"\u0d02\u001d?u", u8"\u0d2e\u0d41", u8"\u0d02\u001d?y", u8"\u0d2e\u0d4d\u0d2f\u0d4d", u8"\u0d05\u001d?#", u8"\u0d3d", u8"\u0d06\u001d?[Aa]", u8"\u0d06\u0d3e", u8"\u0d08\u001d?#", u8"\u0d5f", u8"\u0d08\u001d?[eiI]", u8"\u0d08\u0d57", u8"\u0d0a\u001d?[uoU]", u8"\u0d0a\u0d57", u8"\u0d0b\u0d0b\u001d?#", u8"\u0d60", u8"\u0d0c\u001d?L", u8"\u0d61", u8"\u0d13\u001d?O", u8"\u0d13\u0d3e", u8"\u0d14\u001d?u", u8"\u0d14\u0d57", u8"\u0d15\u0d4d\u001d?#", u8"\u0d7f", u8"\u0d17\u0d4d\u001d?h", u8"\u0d18\u0d4d", u8"\u0d1a\u0d4d\u001d?h", u8"\u0d1b\u0d4d", u8"\u0d1c\u0d4d\u001d?h", u8"\u0d1d\u0d4d", u8"\u0d1e\u0d4d\u0d1e\u0d4d\u001d?ch", u8"\u0d1e\u0d4d\u0d1a\u0d4d", u8"\u0d1e\u0d4d\u0d1e\u0d4d\u001d?j", u8"\u0d1e\u0d4d\u0d1c\u0d4d", u8"\u0d1e\u0d4d\u0d1e\u0d4d\u0d28\u0d4d\u001d?j", u8"\u0d1e\u0d4d\u0d1e\u0d4d", u8"\u0d1e\u0d4d\u0d1e\u0d4d\u0d7b\u001d?j", u8"\u0d1e\u0d4d\u0d1e\u0d4d", u8"\u0d1e\u0d4d\u0d28\u0d4d\u001d?j", u8"\u0d1e\u0d4d\u0d1e\u0d4d", u8"\u0d1f\u0d4d\u001d?h", u8"\u0d20\u0d4d", u8"\u0d1f\u0d4d\u0d1f\u0d4d\u001d?h", u8"\u0d24\u0d4d\u0d24\u0d4d", u8"\u0d21\u0d4d\u001d?h", u8"\u0d22\u0d4d", u8"\u0d23\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d7a\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d23\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d7a\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d23\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d7a\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d23\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d7a\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d23\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d7a\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d23\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d7a\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d23\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d7a\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d23\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d7a\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d23\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d7a\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d23\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d7a\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d24\u0d4d\u001d?h", u8"\u0d25\u0d4d", u8"\u0d24\u0d4d\u0d24\u0d4d\u001d?h", u8"\u0d24\u0d4d\u0d25\u0d4d", u8"\u0d26\u0d4d\u001d?h", u8"\u0d27\u0d4d", u8"\u0d28\u0d41\u001d?#", u8"\u0d79", u8"\u0d28\u0d4d\u001d?#", u8"\u0d29\u0d4d", u8"\u0d28\u001d?#", u8"\u0d29", u8"\u0d28\u0d4d\u001d?g", u8"\u0d19\u0d4d", u8"\u0d7b\u001d?j", u8"\u0d1e\u0d4d", u8"\u0d28\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d7b\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d28\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d7b\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d28\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d7b\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d28\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d7b\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d28\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d7b\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d28\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d7b\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d28\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d7b\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d28\u0d4d\u0d30\u0d4d\u001d?r", u8"\u0d7b\u0d31\u0d4d", u8"\u0d28\u0d4d\u0d31\u0d4d\u001d?h", u8"\u0d28\u0d4d\u0d24\u0d4d", u8"\u0d28\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d7b\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d28\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d7b\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d28\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d7b\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d2c\u0d4d\u001d?h", u8"\u0d2d\u0d4d", u8"\u0d2e\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d02\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d2e\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d02\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d2e\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d02\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d2e\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d02\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d2e\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d02\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d2e\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d02\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d2e\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d02\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d2e\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d02\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d2e\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d02\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d2e\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d02\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d30\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d7c\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d30\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d7c\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d30\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d7c\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d30\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d7c\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d30\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d7c\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d30\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d7c\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d30\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d7c\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d30\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d7c\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d30\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d7c\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d30\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d7c\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d31\u0d4d\u0d31\u0d4d\u001d?#", u8"\u0d3a\u0d4d", u8"\u0d31\u0d4d\u0d31\u001d?#", u8"\u0d3a", u8"\u0d31\u0d4d\u0d31\u0d4d\u001d?h", u8"\u0d24\u0d4d", u8"\u0d32\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d7d\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d32\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d7d\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d32\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d7d\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d32\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d7d\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d32\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d7d\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d32\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d7d\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d32\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d7d\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d32\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d7d\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d32\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d7d\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d32\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d7d\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d33\u0d4d\u001d?#", u8"\u0d0c", u8"\u0d33\u0d4d\u001d?L", u8"\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d33\u0d4d\u0d1f\u0d4d\u001d?T", u8"\u0d7e\u0d1f\u0d4d\u0d1f\u0d4d", u8"\u0d33\u0d4d\u0d21\u0d4d\u001d?D", u8"\u0d7e\u0d21\u0d4d\u0d21\u0d4d", u8"\u0d33\u0d4d\u0d26\u0d4d\u001d?d", u8"\u0d7e\u0d26\u0d4d\u0d26\u0d4d", u8"\u0d33\u0d4d\u0d28\u0d4d\u001d?n", u8"\u0d7e\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d33\u0d4d\u0d2a\u0d4d\u001d?p", u8"\u0d7e\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d33\u0d4d\u0d2e\u0d4d\u001d?m", u8"\u0d7e\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d33\u0d4d\u0d2f\u0d4d\u001d?y", u8"\u0d7e\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d33\u0d4d\u0d32\u0d4d\u001d?l", u8"\u0d7e\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d33\u0d4d\u0d33\u0d4d\u001d?L", u8"\u0d7e\u0d33\u0d4d\u0d33\u0d4d", u8"\u0d33\u0d4d\u0d33\u0d4d\u001d?#", u8"\u0d61", u8"\u0d33\u0d4d\u0d35\u0d4d\u001d?v", u8"\u0d7e\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d36\u0d4d\u001d?h", u8"\u0d34\u0d4d", u8"\u0d38\u0d02\u001d?r", u8"\u0d38\u0d02\u0d7c", u8"\u0d38\u0d02\u001d?y", u8"\u0d38\u0d02\u0d2f\u0d4d", u8"\u0d38\u0d4d\u001d?h", u8"\u0d37\u0d4d", u8"\u0d3e\u001d?[Aa]", u8"\u0d3e\u0d3e", u8"\u0d40\u001d?[eiI]", u8"\u0d40\u0d40", u8"\u0d42\u001d?[uoU]", u8"\u0d42\u0d42", u8"\u0d43\u001d?R", u8"\u0d43\u0d7c", u8"\u0d43\u0d7c\u001d?#", u8"\u0d44", u8"\u0d4c\u001d?u", u8"\u0d4c\u0d57", u8"\u0d4d(\u001d?A|\u0d05\u001d?a)", u8"\u0d3e", u8"\u0d4d[\u0d33\u0d32]\u0d4d\u001d?#", u8"\u0d62", u8"\u0d4d[\u0d33\u0d32]\u0d4d[\u0d33\u0d32]\u0d4d\u001d?#", u8"\u0d63", u8"\u0d4d\u001d?E", u8"\u0d47", u8"\u0d4d\u001d?L", u8"\u0d4d\u0d32\u0d4d", u8"\u0d4d\u001d?O", u8"\u0d4b", u8"\u0d4d\u001d?R", u8"\u0d43", u8"\u0d4d\u001d?RA", u8"\u0d4d\u0d30\u0d3e", u8"\u0d4d\u001d?RE", u8"\u0d4d\u0d30\u0d47", u8"\u0d4d\u001d?RI", u8"\u0d4d\u0d30\u0d40", u8"\u0d4d\u001d?RO", u8"\u0d4d\u0d30\u0d4b", u8"\u0d4d\u001d?RU", u8"\u0d4d\u0d30\u0d42", u8"\u0d4d\u001d?Ra", u8"\u0d4d\u0d30", u8"\u0d4d\u001d?Re", u8"\u0d4d\u0d30\u0d46", u8"\u0d4d\u001d?Ri", u8"\u0d4d\u0d30\u0d3f", u8"\u0d4d\u001d?Ro", u8"\u0d4d\u0d30\u0d4a", u8"\u0d4d\u001d?Ru", u8"\u0d4d\u0d30\u0d41", u8"\u0d4d\u001d?R~", u8"\u0d4d\u0d30\u0d4d", u8"\u0d4d\u001d?_B", u8"\u0d4d\u200c\u0d2c\u0d4d\u0d2c\u0d4d", u8"\u0d4d\u001d?_C", u8"\u0d4d\u200c\u0d1a\u0d4d", u8"\u0d4d\u001d?_G", u8"\u0d4d\u200c\u0d17\u0d4d\u0d17\u0d4d", u8"\u0d4d\u001d?_J", u8"\u0d4d\u200c\u0d1c\u0d4d\u0d1c\u0d4d", u8"\u0d4d\u001d?_K", u8"\u0d4d\u200c\u0d15\u0d4d\u0d15\u0d4d", u8"\u0d4d\u001d?_N", u8"\u0d4d\u200c\u0d23\u0d4d", u8"\u0d4d\u001d?_Z", u8"\u0d4d\u200c\u0d36\u0d4d\u0d36\u0d4d", u8"\u0d4d\u001d?_b", u8"\u0d4d\u200c\u0d2c\u0d4d", u8"\u0d4d\u001d?_g", u8"\u0d4d\u200c\u0d17\u0d4d", u8"\u0d4d\u001d?_j", u8"\u0d4d\u200c\u0d1c\u0d4d", u8"\u0d4d\u001d?_n", u8"\u0d4d\u200c\u0d28\u0d4d", u8"\u0d4d\u001d?_r", u8"\u0d4d\u200c\u0d30\u0d4d", u8"\u0d4d\u001d?_s", u8"\u0d4d\u200c\u0d38\u0d4d", u8"\u0d4d\u001d?_T", u8"\u0d4d\u200c\u0d1f\u0d4d", u8"\u0d4d\u001d?_t", u8"\u0d4d\u200c\u0d31\u0d4d\u0d31\u0d4d", u8"\u0d4d\u001d?_D", u8"\u0d4d\u200c\u0d21\u0d4d", u8"\u0d4d\u001d?_L", u8"\u0d4d\u200c\u0d33\u0d4d", u8"\u0d4d\u001d?_M", u8"\u0d4d\u200c\u0d2e\u0d4d\u0d2e\u0d4d", u8"\u0d4d\u001d?_P", u8"\u0d4d\u200c\u0d2a\u0d4d\u0d2a\u0d4d", u8"\u0d4d\u001d?_X", u8"\u0d4d\u200c\u0d15\u0d4d\u0d37\u0d4d", u8"\u0d4d\u001d?_Y", u8"\u0d4d\u200c\u0d2f\u0d4d\u0d2f\u0d4d", u8"\u0d4d\u001d?_d", u8"\u0d4d\u200c\u0d26\u0d4d", u8"\u0d4d\u001d?_h", u8"\u0d4d\u200c\u0d39\u0d4d", u8"\u0d4d\u001d?_l", u8"\u0d4d\u200c\u0d32\u0d4d", u8"\u0d4d\u001d?_m", u8"\u0d4d\u200c\u0d2e\u0d4d", u8"\u0d4d\u001d?_p", u8"\u0d4d\u200c\u0d2a\u0d4d", u8"\u0d4d\u001d?_x", u8"\u0d4d\u200c\u0d15\u0d4d\u0d38\u0d4d", u8"\u0d4d\u001d?_y", u8"\u0d4d\u200c\u0d2f\u0d4d", u8"\u0d4d\u001d?_[kc]", u8"\u0d4d\u200c\u0d15\u0d4d", u8"\u0d4d\u001d?_[qQ]", u8"\u0d4d\u200c\u0d16\u0d4d", u8"\u0d4d\u001d?_[fF]", u8"\u0d4d\u200c\u0d2b\u0d4d", u8"\u0d4d\u001d?_[VW]", u8"\u0d4d\u200c\u0d35\u0d4d\u0d35\u0d4d", u8"\u0d4d\u001d?_[vw]", u8"\u0d4d\u200c\u0d35\u0d4d", u8"\u0d4d\u001d?_[zS]", u8"\u0d4d\u200c\u0d36\u0d4d", u8"\u0d33\u0d4d\u001d?_", u8"\u0d7e", u8"\u0d23\u0d4d\u001d?_", u8"\u0d7a", u8"\u0d32\u0d4d\u001d?_", u8"\u0d7d", u8"\u0d2e\u0d4d\u001d?_", u8"\u0d02", u8"\u0d28\u0d4d\u001d?_", u8"\u0d7b", u8"\u0d30\u0d4d\u001d?_", u8"\u0d7c", u8"\u0d4d\u001d?a", u8"", u8"\u0d4d\u001d?e", u8"\u0d46", u8"\u0d4d\u001d?i", u8"\u0d3f", u8"\u0d4d\u001d?o", u8"\u0d4a", u8"\u0d4d\u001d?u", u8"\u0d41", u8"\u0d4d\u001d?~", u8"\u0d4d", u8"\u0d4d\u001d?~A", u8"\u0d4d\u0d06", u8"\u0d4d\u001d?~E", u8"\u0d4d\u0d0f", u8"\u0d4d\u001d?~I", u8"\u0d4d\u0d08", u8"\u0d4d\u001d?~O", u8"\u0d4d\u0d13", u8"\u0d4d\u001d?~R", u8"\u0d4d\u0d0b", u8"\u0d4d\u001d?~U", u8"\u0d4d\u0d0a", u8"\u0d4d\u001d?~a", u8"\u0d4d\u0d05", u8"\u0d4d\u001d?~e", u8"\u0d4d\u0d0e", u8"\u0d4d\u001d?~i", u8"\u0d4d\u0d07", u8"\u0d4d\u001d?~o", u8"\u0d4d\u0d12", u8"\u0d4d\u001d?~u", u8"\u0d4d\u0d09", u8"\u0d57\u001d?#", u8"\u0d4c", u8"\u0d57\u001d?[uieIuUou]", u8"\u0d57\u0d57", u8"\u0d7a\u001d?A", u8"\u0d23\u0d3e", u8"\u0d7a\u001d?D", u8"\u0d23\u0d4d\u0d21\u0d4d", u8"\u0d7a\u001d?E", u8"\u0d23\u0d47", u8"\u0d7a\u001d?I", u8"\u0d23\u0d40", u8"\u0d7a\u001d?N", u8"\u0d23\u0d4d\u0d23\u0d4d", u8"\u0d7a\u001d?O", u8"\u0d23\u0d4b", u8"\u0d7a\u001d?U", u8"\u0d23\u0d42", u8"\u0d7a\u001d?a", u8"\u0d23", u8"\u0d7a\u001d?e", u8"\u0d23\u0d46", u8"\u0d7a\u001d?i", u8"\u0d23\u0d3f", u8"\u0d7a\u001d?m", u8"\u0d23\u0d4d\u0d2e\u0d4d", u8"\u0d7a\u001d?o", u8"\u0d23\u0d4a", u8"\u0d7a\u001d?R", u8"\u0d23\u0d43", u8"\u0d7a\u001d?u", u8"\u0d23\u0d41", u8"\u0d7a\u001d?v", u8"\u0d23\u0d4d\u0d35\u0d4d", u8"\u0d7a\u001d?y", u8"\u0d23\u0d4d\u0d2f\u0d4d", u8"\u0d7b\u001d?A", u8"\u0d28\u0d3e", u8"\u0d7b\u001d?E", u8"\u0d28\u0d47", u8"\u0d7b\u001d?I", u8"\u0d28\u0d40", u8"\u0d7b\u001d?O", u8"\u0d28\u0d4b", u8"\u0d7b\u001d?U", u8"\u0d28\u0d42", u8"\u0d7b\u001d?a", u8"\u0d28", u8"\u0d7b\u001d?d", u8"\u0d28\u0d4d\u0d26\u0d4d", u8"\u0d7b\u001d?e", u8"\u0d28\u0d46", u8"\u0d7b\u001d?g", u8"\u0d19\u0d4d", u8"\u0d7b\u001d?i", u8"\u0d28\u0d3f", u8"\u0d7b\u001d?m", u8"\u0d28\u0d4d\u0d2e\u0d4d", u8"\u0d7b\u001d?n", u8"\u0d28\u0d4d\u0d28\u0d4d", u8"\u0d7b\u001d?o", u8"\u0d28\u0d4a", u8"\u0d7b\u001d?r", u8"\u0d28\u0d4d\u0d30\u0d4d", u8"\u0d7b\u001d?R", u8"\u0d28\u0d43", u8"\u0d7b\u001d?u", u8"\u0d28\u0d41", u8"\u0d7b\u001d?v", u8"\u0d28\u0d4d\u0d35\u0d4d", u8"\u0d7b\u001d?y", u8"\u0d28\u0d4d\u0d2f\u0d4d", u8"\u0d7c\u001d?#", u8"\u0d4e", u8"\u0d7c\u001d?A", u8"\u0d30\u0d3e", u8"\u0d7c\u001d?E", u8"\u0d30\u0d47", u8"\u0d7c\u001d?I", u8"\u0d30\u0d40", u8"\u0d7c\u001d?O", u8"\u0d30\u0d4b", u8"\u0d7c\u001d?U", u8"\u0d30\u0d42", u8"\u0d7c\u001d?a", u8"\u0d30", u8"\u0d7c\u001d?e", u8"\u0d30\u0d46", u8"\u0d7c\u001d?i", u8"\u0d30\u0d3f", u8"\u0d7c\u001d?o", u8"\u0d30\u0d4a", u8"\u0d7c\u001d?R", u8"\u0d30\u0d43", u8"\u0d7c\u001d?u", u8"\u0d30\u0d41", u8"\u0d7c\u001d?y", u8"\u0d30\u0d4d\u0d2f\u0d4d", u8"\u0d7d\u001d?A", u8"\u0d32\u0d3e", u8"\u0d7d\u001d?E", u8"\u0d32\u0d47", u8"\u0d7d\u001d?I", u8"\u0d32\u0d40", u8"\u0d7d\u001d?O", u8"\u0d32\u0d4b", u8"\u0d7d\u001d?U", u8"\u0d32\u0d42", u8"\u0d7d\u001d?[lL]", u8"\u0d32\u0d4d\u0d32\u0d4d", u8"\u0d7d\u001d?a", u8"\u0d32", u8"\u0d7d\u001d?e", u8"\u0d32\u0d46", u8"\u0d7d\u001d?i", u8"\u0d32\u0d3f", u8"\u0d7d\u001d?m", u8"\u0d32\u0d4d\u0d2e\u0d4d", u8"\u0d7d\u001d?o", u8"\u0d32\u0d4a", u8"\u0d7d\u001d?p", u8"\u0d32\u0d4d\u0d2a\u0d4d", u8"\u0d7d\u001d?R", u8"\u0d32\u0d43", u8"\u0d7d\u001d?u", u8"\u0d32\u0d41", u8"\u0d7d\u001d?v", u8"\u0d32\u0d4d\u0d35\u0d4d", u8"\u0d7d\u001d?y", u8"\u0d32\u0d4d\u0d2f\u0d4d", u8"\u0d7e\u001d?A", u8"\u0d33\u0d3e", u8"\u0d7e\u001d?E", u8"\u0d33\u0d47", u8"\u0d7e\u001d?I", u8"\u0d33\u0d40", u8"\u0d7e\u001d?O", u8"\u0d33\u0d4b", u8"\u0d7e\u001d?U", u8"\u0d33\u0d42", u8"\u0d7e\u001d?a", u8"\u0d33", u8"\u0d7e\u001d?e", u8"\u0d33\u0d46", u8"\u0d7e\u001d?i", u8"\u0d33\u0d3f", u8"\u0d7e\u001d?o", u8"\u0d33\u0d4a", u8"\u0d7e\u001d?R", u8"\u0d33\u0d43", u8"\u0d7e\u001d?u", u8"\u0d33\u0d41", u8"\u0d7e\u001d?y", u8"\u0d33\u0d4d\u0d2f\u0d4d", u8"_?E", u8"\u0d0f", u8"_?O", u8"\u0d13", u8"_?R", u8"\u0d0b", u8"_?a", u8"\u0d05", u8"_?e", u8"\u0d0e", u8"_?i", u8"\u0d07", u8"_?o", u8"\u0d12", u8"_?u", u8"\u0d09", u8"cch", u8"\u0d1a\u0d4d\u0d1a\u0d4d", u8"cchh", u8"\u0d1a\u0d4d\u0d1b\u0d4d", u8"ch", u8"\u0d1a\u0d4d", u8"t", u8"\u0d31\u0d4d\u0d31\u0d4d", u8"L", u8"\u0d7e", u8"N", u8"\u0d7a", u8"l", u8"\u0d7d", u8"m", u8"\u0d02", u8"n", u8"\u0d7b", u8"r", u8"\u0d7c"}; const unsigned int kTransformsLen = base::size(kTransforms); const char* kHistoryPrune = "a|@|@a|c|R|_|~"; } // namespace ml_phone
23,362
18,763
#pragma once #include "Arduino.h" #include <Homie.h> // #include "homieSyslog.h" // #include "datatypes.h" #include "homie_property.hpp" #include "homie_node.hpp" #include "homie_device.hpp" bool globalInputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value); void onHomieEvent(const HomieEvent& event); void homieParameterSet(const __FlashStringHelper *nodeId, const __FlashStringHelper *parameterId, bool state);
465
155
#include<stdio.h> int main(){ char name[20]; printf("Enter your name:-"); scanf("%[^\n]s", name); printf("Hello Mr. %s",name); return 0; }
150
69
#include "ulp_assembler.h" #include "ulp_constants.h" #define WORDS_TO_ADDR(instr) (instr) * sizeof(ULPInstruction) std::array<const char*, 7> ULPAssembler::ALUSEL = { "add", "sub", "and", "or", "move", "lsh", "rsh" }; bool ULPAssembler::decode(const RDBufferView* view, ULPInstruction* ulpinstr) { if(!ulpinstr || (view->size < sizeof(ULPInstruction))) return false; ulpinstr->data = RD_FromLittleEndian32(*reinterpret_cast<u32*>(view->data)); return true; } void ULPAssembler::renderInstruction(RDContext*, const RDRendererParams* rp) { ULPInstruction ulpinstr; if(!ULPAssembler::decode(&rp->view, &ulpinstr)) return; switch(ulpinstr.unk.opcode) { case ULP_OP_ALU: ULPAssembler::renderAlu(&ulpinstr, rp); break; case ULP_OP_STORE: ULPAssembler::renderStore(&ulpinstr, rp); break; case ULP_OP_LOAD: ULPAssembler::renderLoad(&ulpinstr, rp); break; case ULP_OP_JUMP: ULPAssembler::renderJmp(&ulpinstr, rp); break; case ULP_OP_HALT: RDRenderer_Mnemonic(rp->renderer, "halt", Theme_Ret); break; case ULP_OP_WAKESLEEP: ULPAssembler::renderWakeSleep(&ulpinstr, rp); break; case ULP_OP_WAIT: ULPAssembler::renderWait(&ulpinstr, rp); break; case ULP_OP_TSENS: ULPAssembler::renderTSens(&ulpinstr, rp); break; case ULP_OP_ADC: ULPAssembler::renderAdc(&ulpinstr, rp); break; case ULP_OP_I2C: ULPAssembler::renderI2C(&ulpinstr, rp); break; case ULP_OP_REGRD: ULPAssembler::renderRegRD(&ulpinstr, rp); break; case ULP_OP_REGWR: ULPAssembler::renderRegWR(&ulpinstr, rp); break; default: RDRenderer_Unknown(rp->renderer); break; } } void ULPAssembler::emulate(RDContext*, RDEmulateResult* result) { ULPInstruction ulpinstr; if(!ULPAssembler::decode(RDEmulateResult_GetView(result), &ulpinstr)) return; RDEmulateResult_SetSize(result, sizeof(ULPInstruction)); switch(ulpinstr.unk.opcode) { case ULP_OP_JUMP: ULPAssembler::emulateJmp(&ulpinstr, result); break; case ULP_OP_HALT: RDEmulateResult_AddReturn(result); break; default: break; } } std::string ULPAssembler::regName(u8 reg) { return "r" + std::to_string(reg); } void ULPAssembler::emulateJmp(const ULPInstruction* ulpinstr, RDEmulateResult* result) { rd_address address = RDEmulateResult_GetAddress(result); switch(ulpinstr->unk.choice) { case 0: { if(!ulpinstr->jump.sel) { if(ulpinstr->jump.type) RDEmulateResult_AddBranchTrue(result, ulpinstr->jump.addr); else RDEmulateResult_AddBranch(result, WORDS_TO_ADDR(ulpinstr->jump.addr)); } else RDEmulateResult_AddBranchIndirect(result); if(ulpinstr->jump.type) RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction)); break; } case 1: case 2: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F); int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1; RDEmulateResult_AddBranchTrue(result, address + sign * relative); RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction)); break; } default: break; } } void ULPAssembler::renderAlu(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { switch(ulpinstr->unk.choice) { case 0: ULPAssembler::renderAluReg(ulpinstr, rp); break; case 1: ULPAssembler::renderAluImm(ulpinstr, rp); break; case 2: ULPAssembler::renderAluStage(ulpinstr, rp); break; default: break; } } void ULPAssembler::renderAluReg(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->alureg.sel], Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc1).c_str()); if(ulpinstr->alureg.sel == ALU_SEL_MOVE) return; RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc2).c_str()); } void ULPAssembler::renderAluImm(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->aluimm.sel], Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rdst).c_str()); if(ulpinstr->aluimm.sel != ALU_SEL_MOVE) { RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rsrc1).c_str()); } RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->aluimm.imm); } void ULPAssembler::renderAluStage(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { static std::array<const char*, 3> STAgeSEL = { "stage_inc", "stage_dec", "stage_rst" }; RDRenderer_MnemonicWord(rp->renderer, STAgeSEL[ulpinstr->alustage.sel], Theme_Default); if(ulpinstr->alustage.sel == 2) return; RDRenderer_Unsigned(rp->renderer, ulpinstr->alustage.imm); } void ULPAssembler::renderJmp(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { switch(ulpinstr->unk.choice) { case 0: { RDRenderer_MnemonicWord(rp->renderer, "jump", ulpinstr->jump.type ? Theme_JumpCond : Theme_Jump); if(ulpinstr->jump.sel) RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->jump.rdest).c_str()); else RDRenderer_Reference(rp->renderer, WORDS_TO_ADDR(ulpinstr->jump.addr)); if(ulpinstr->jump.type) { RDRenderer_Text(rp->renderer, ", "); if(ulpinstr->jump.type == 1) RDRenderer_Text(rp->renderer, "eq"); else if(ulpinstr->jump.type == 2) RDRenderer_Text(rp->renderer, "ov"); } break; } case 1: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F); int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1; RDRenderer_MnemonicWord(rp->renderer, "jumpr", Theme_JumpCond); RDRenderer_Reference(rp->renderer, rp->address + sign * relative); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Text(rp->renderer, ulpinstr->jumpr.cond ? "ge" : "lt"); break; } case 2: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumps.step & 0x7F); int sign = ulpinstr->jumps.step & 0x80 ? -1 : +1; RDRenderer_MnemonicWord(rp->renderer, "jumps", Theme_JumpCond); RDRenderer_Unsigned(rp->renderer, rp->address + (sign * relative)); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres); RDRenderer_Text(rp->renderer, ", "); if(ulpinstr->jumps.cond == 0) RDRenderer_Text(rp->renderer, "lt"); else if(ulpinstr->jumps.cond == 1) RDRenderer_Text(rp->renderer, "gt"); else RDRenderer_Text(rp->renderer, "eq"); break; } default: break; } } void ULPAssembler::renderWakeSleep(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->wakesleep.wakeorsleep) { RDRenderer_MnemonicWord(rp->renderer, "sleep", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->wakesleep.reg); } else RDRenderer_Mnemonic(rp->renderer, "wake", Theme_Default); } void ULPAssembler::renderWait(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->wait.cycles) { RDRenderer_MnemonicWord(rp->renderer, "wait", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->wait.cycles); } else RDRenderer_Mnemonic(rp->renderer, "nop", Theme_Nop); } void ULPAssembler::renderTSens(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "tsens", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->tsens.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->tsens.delay); } void ULPAssembler::renderAdc(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "adc", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->adc.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sel); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sarmux); } void ULPAssembler::renderI2C(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->i2c.rw) { RDRenderer_MnemonicWord(rp->renderer, "i2c_wr", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.data); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel); } else { RDRenderer_MnemonicWord(rp->renderer, "i2c_rd", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel); } } void ULPAssembler::renderRegRD(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE; unsigned int base; if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE; else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE; else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE; else base = DR_REG_RTCCNTL_BASE; unsigned int offset = address - base; RDRenderer_MnemonicWord(rp->renderer, "reg_rd", Theme_Default); if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str()); else RDRenderer_Unsigned(rp->renderer, base); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low); } void ULPAssembler::renderRegWR(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE; unsigned int base; if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE; else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE; else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE; else base = DR_REG_RTCCNTL_BASE; unsigned int offset = address - base; RDRenderer_MnemonicWord(rp->renderer, "reg_wr", Theme_Default); if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str()); else RDRenderer_Unsigned(rp->renderer, base); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.data); } void ULPAssembler::renderStore(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "st", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset); } void ULPAssembler::renderLoad(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "ld", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset); }
12,917
5,063
/* * Copyright (c) 2015 - 2021, Intel Corporation * * 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 Intel Corporation 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 LOG OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef CIRCULARBUFFER_HPP_INCLUDE #define CIRCULARBUFFER_HPP_INCLUDE #include <stdlib.h> #include <vector> #include "Exception.hpp" namespace geopm { /// @brief Templated container for a circular buffer implementation. /// The CircularBuffer container implements a fixed size buffer. Once /// at capacity, any new insertions cause the oldest entry to be dropped. template <class type> class CircularBuffer { public: CircularBuffer(); /// @brief Constructor for the CircularBuffer template. /// /// Creates an empty circular buffer with a set capacity. /// /// @param [in] size Requested capacity for the buffer. CircularBuffer(unsigned int size); /// @brief CircularBuffer destructor, virtual virtual ~CircularBuffer(); /// @brief Re-size the circular buffer. /// /// Resets the capacity of the circular buffer without /// modifying its current contents. /// /// @param [in] size Requested capacity for the buffer. void set_capacity(const unsigned int size); /// @brief Clears all entries from the buffer. void clear(void); /// @brief Size of the buffer contents. /// /// Returns the number of items in the buffer. This /// value will be less than or equal to the current /// capacity of the buffer. // /// @return Size of the buffer contents. int size(void) const; /// @brief Capacity of the buffer. /// /// Returns the current size of the circular buffer at /// the time of the call. /// /// @return Capacity of the buffer. int capacity(void) const; /// @brief Insert a value into the buffer. /// /// If the buffer is not full, the new value is simply /// added to the buffer. It the buffer is at capacity, /// The head of the buffer is dropped and moved to the /// next oldest entry and the new value is then inserted /// at the end of the buffer. /// /// @param [in] value The value to be inserted. void insert(const type value); /// @brief Returns a constant reference to the value from the buffer. /// /// Accesses the contents of the circular buffer /// at a particular index. Valid indices range /// from 0 to [size-1]. Where size is the number /// of valid entries in the buffer. An attempt to /// retrieve a value for an out of bound index /// will throw a geopm::Exception with an /// error_value() of GEOPM_ERROR_INVALID. /// /// @param [in] index Buffer index to retrieve. /// /// @return Value from the specified buffer index. const type& value(const unsigned int index) const; /// @brief Create a vector from the circular buffer contents. /// /// @return Vector containing the circular buffer contents. std::vector<type> make_vector(void) const; /// @brief Create a vector slice from the circular buffer contents. /// /// @param [in] start Start index (inclusive). /// @param [in] end End index (exclusive). /// @return Vector containing the circular buffer contents at [start, end). std::vector<type> make_vector(const unsigned int start, const unsigned int end) const; private: /// @brief Vector holding the buffer data. std::vector<type> m_buffer; /// @brief Index of the current head of the buffer. unsigned long m_head; /// @brief The number of valid entries in the buffer. unsigned long m_count; /// @brief Current capacity of the buffer. size_t m_max_size; }; template <class type> CircularBuffer<type>::CircularBuffer() : CircularBuffer(0) { } template <class type> CircularBuffer<type>::CircularBuffer(unsigned int size) : m_buffer(size) , m_head(0) , m_count(0) , m_max_size(size) { } template <class type> CircularBuffer<type>::~CircularBuffer() { } template <class type> int CircularBuffer<type>::size() const { return m_count; } template <class type> int CircularBuffer<type>::capacity() const { return m_max_size; } template <class type> void CircularBuffer<type>::clear() { m_head = 0; m_count = 0; } template <class type> void CircularBuffer<type>::set_capacity(const unsigned int size) { if (size < m_count && m_max_size > 0) { int size_diff = m_count - size; std::vector<type> temp; //Copy newest data into temporary vector for (unsigned int i = m_head + size_diff; i != ((m_head + m_count) % m_max_size); i = ((i + 1) % m_max_size)) { temp.push_back(m_buffer[i]); } //now re-size and swap out with tmp vector data m_buffer.resize(size); m_buffer.swap(temp); m_count = size; } else { m_buffer.resize(size); } m_head = 0; m_max_size = size; } template <class type> void CircularBuffer<type>::insert(const type value) { if (m_max_size < 1) { throw Exception("CircularBuffer::insert(): Cannot insert into a buffer of 0 size", GEOPM_ERROR_RUNTIME, __FILE__, __LINE__); } if (m_count < m_max_size) { m_buffer[m_count] = value; m_count++; } else { m_buffer[m_head] = value; m_head = ((m_head + 1) % m_max_size); } } template <class type> const type& CircularBuffer<type>::value(const unsigned int index) const { if (index >= m_count) { throw Exception("CircularBuffer::value(): index is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } return m_buffer[(m_head + index) % m_max_size]; } template <class type> std::vector<type> CircularBuffer<type>::make_vector(void) const { std::vector<type> result(size()); if (m_head == 0) { std::copy(m_buffer.begin(), m_buffer.begin() + m_count, result.begin()); } else { std::copy(m_buffer.begin() + m_head, m_buffer.end(), result.begin()); std::copy(m_buffer.begin(), m_buffer.begin() + m_head, result.end() - m_head); } return result; } template <class type> std::vector<type> CircularBuffer<type>::make_vector(const unsigned int idx_start, const unsigned int idx_end) const { if (idx_start >= (unsigned int)size()) { throw Exception("CircularBuffer::make_vector(): start is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } if (idx_end > (unsigned int)size()) { throw Exception("CircularBuffer::make_vector(): end is out of bounds", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } if (idx_end <= idx_start) { throw Exception("CircularBuffer::make_vector(): end index is smaller than start index", GEOPM_ERROR_INVALID, __FILE__, __LINE__); } int slice_length = idx_end - idx_start; std::vector<type> result(slice_length); unsigned int start=(m_head + idx_start) % capacity(); unsigned int end=(((m_head + idx_end) - 1) % capacity()) + 1; if(end > start) { std::copy(m_buffer.begin() + start, m_buffer.begin() + end, result.begin()); } else { std::copy(m_buffer.begin() + start, m_buffer.end(), result.begin()); std::copy(m_buffer.begin(), m_buffer.begin() + end, result.begin() + capacity() - start); } return result; } } #endif
9,839
2,808
#include "NormalInput.h" #include <time.h> NormalInput::NormalInput() { } float NormalInput::realTime(clock_t clockDiff) { return ((float) clockDiff) / CLOCKS_PER_SEC; } QChar NormalInput::resolve(int index, QString charField) { clock_t nowTime = clock(); clock_t diff = nowTime - _lastTime; _lastTime = nowTime; if (index == _lastButton && realTime(diff) < QUICK_PRESS_INTEVAL) { /* Quick press, change last character */ _lastResult = CHANGE_LAST; if (_lastPosition >= charField.length()) { _lastPosition = 0; } return charField[_lastPosition++]; } _lastResult = APPEND_NEW; _lastButton = index; _lastPosition = 0; return charField[_lastPosition++]; }
717
270
/**************************************************************************** ** ** Copyright (C) 2016 The Qt Company Ltd. ** Contact: https://www.qt.io/licensing/ ** ** This file is part of the QtNetwork module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and The Qt Company. For licensing terms ** and conditions see https://www.qt.io/terms-conditions. For further ** information use the contact form at https://www.qt.io/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 3 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL3 included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 3 requirements ** will be met: https://www.gnu.org/licenses/lgpl-3.0.html. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 2.0 or (at your option) the GNU General ** Public license version 3 or any later version approved by the KDE Free ** Qt Foundation. The licenses are as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3 ** included in the packaging of this file. Please review the following ** information to ensure the GNU General Public License requirements will ** be met: https://www.gnu.org/licenses/gpl-2.0.html and ** https://www.gnu.org/licenses/gpl-3.0.html. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qlocalsocket.h" #include "qlocalsocket_p.h" #include "qnet_unix_p.h" #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <qdir.h> #include <qdebug.h> #include <qelapsedtimer.h> #ifdef Q_OS_VXWORKS # include <selectLib.h> #endif #define QT_CONNECT_TIMEOUT 30000 QT_BEGIN_NAMESPACE QLocalSocketPrivate::QLocalSocketPrivate() : QIODevicePrivate(), delayConnect(0), connectTimer(0), connectingSocket(-1), connectingOpenMode(0), state(QLocalSocket::UnconnectedState) { } void QLocalSocketPrivate::init() { Q_Q(QLocalSocket); // QIODevice signals q->connect(&unixSocket, SIGNAL(aboutToClose()), q, SIGNAL(aboutToClose())); q->connect(&unixSocket, SIGNAL(bytesWritten(qint64)), q, SIGNAL(bytesWritten(qint64))); q->connect(&unixSocket, SIGNAL(readyRead()), q, SIGNAL(readyRead())); // QAbstractSocket signals q->connect(&unixSocket, SIGNAL(connected()), q, SIGNAL(connected())); q->connect(&unixSocket, SIGNAL(disconnected()), q, SIGNAL(disconnected())); q->connect(&unixSocket, SIGNAL(stateChanged(QAbstractSocket::SocketState)), q, SLOT(_q_stateChanged(QAbstractSocket::SocketState))); q->connect(&unixSocket, SIGNAL(error(QAbstractSocket::SocketError)), q, SLOT(_q_error(QAbstractSocket::SocketError))); q->connect(&unixSocket, SIGNAL(readChannelFinished()), q, SIGNAL(readChannelFinished())); unixSocket.setParent(q); } void QLocalSocketPrivate::_q_error(QAbstractSocket::SocketError socketError) { Q_Q(QLocalSocket); QString function = QLatin1String("QLocalSocket"); QLocalSocket::LocalSocketError error = (QLocalSocket::LocalSocketError)socketError; QString errorString = generateErrorString(error, function); q->setErrorString(errorString); emit q->error(error); } void QLocalSocketPrivate::_q_stateChanged(QAbstractSocket::SocketState newState) { Q_Q(QLocalSocket); QLocalSocket::LocalSocketState currentState = state; switch(newState) { case QAbstractSocket::UnconnectedState: state = QLocalSocket::UnconnectedState; serverName.clear(); fullServerName.clear(); break; case QAbstractSocket::ConnectingState: state = QLocalSocket::ConnectingState; break; case QAbstractSocket::ConnectedState: state = QLocalSocket::ConnectedState; break; case QAbstractSocket::ClosingState: state = QLocalSocket::ClosingState; break; default: #if defined QLOCALSOCKET_DEBUG qWarning() << "QLocalSocket::Unhandled socket state change:" << newState; #endif return; } if (currentState != state) emit q->stateChanged(state); } QString QLocalSocketPrivate::generateErrorString(QLocalSocket::LocalSocketError error, const QString &function) const { QString errorString; switch (error) { case QLocalSocket::ConnectionRefusedError: errorString = QLocalSocket::tr("%1: Connection refused").arg(function); break; case QLocalSocket::PeerClosedError: errorString = QLocalSocket::tr("%1: Remote closed").arg(function); break; case QLocalSocket::ServerNotFoundError: errorString = QLocalSocket::tr("%1: Invalid name").arg(function); break; case QLocalSocket::SocketAccessError: errorString = QLocalSocket::tr("%1: Socket access error").arg(function); break; case QLocalSocket::SocketResourceError: errorString = QLocalSocket::tr("%1: Socket resource error").arg(function); break; case QLocalSocket::SocketTimeoutError: errorString = QLocalSocket::tr("%1: Socket operation timed out").arg(function); break; case QLocalSocket::DatagramTooLargeError: errorString = QLocalSocket::tr("%1: Datagram too large").arg(function); break; case QLocalSocket::ConnectionError: errorString = QLocalSocket::tr("%1: Connection error").arg(function); break; case QLocalSocket::UnsupportedSocketOperationError: errorString = QLocalSocket::tr("%1: The socket operation is not supported").arg(function); break; case QLocalSocket::OperationError: errorString = QLocalSocket::tr("%1: Operation not permitted when socket is in this state").arg(function); break; case QLocalSocket::UnknownSocketError: default: errorString = QLocalSocket::tr("%1: Unknown error %2").arg(function).arg(errno); } return errorString; } void QLocalSocketPrivate::errorOccurred(QLocalSocket::LocalSocketError error, const QString &function) { Q_Q(QLocalSocket); switch (error) { case QLocalSocket::ConnectionRefusedError: unixSocket.setSocketError(QAbstractSocket::ConnectionRefusedError); break; case QLocalSocket::PeerClosedError: unixSocket.setSocketError(QAbstractSocket::RemoteHostClosedError); break; case QLocalSocket::ServerNotFoundError: unixSocket.setSocketError(QAbstractSocket::HostNotFoundError); break; case QLocalSocket::SocketAccessError: unixSocket.setSocketError(QAbstractSocket::SocketAccessError); break; case QLocalSocket::SocketResourceError: unixSocket.setSocketError(QAbstractSocket::SocketResourceError); break; case QLocalSocket::SocketTimeoutError: unixSocket.setSocketError(QAbstractSocket::SocketTimeoutError); break; case QLocalSocket::DatagramTooLargeError: unixSocket.setSocketError(QAbstractSocket::DatagramTooLargeError); break; case QLocalSocket::ConnectionError: unixSocket.setSocketError(QAbstractSocket::NetworkError); break; case QLocalSocket::UnsupportedSocketOperationError: unixSocket.setSocketError(QAbstractSocket::UnsupportedSocketOperationError); break; case QLocalSocket::UnknownSocketError: default: unixSocket.setSocketError(QAbstractSocket::UnknownSocketError); } QString errorString = generateErrorString(error, function); q->setErrorString(errorString); emit q->error(error); // errors cause a disconnect unixSocket.setSocketState(QAbstractSocket::UnconnectedState); bool stateChanged = (state != QLocalSocket::UnconnectedState); state = QLocalSocket::UnconnectedState; q->close(); if (stateChanged) q->emit stateChanged(state); } void QLocalSocket::connectToServer(OpenMode openMode) { Q_D(QLocalSocket); if (state() == ConnectedState || state() == ConnectingState) { QString errorString = d->generateErrorString(QLocalSocket::OperationError, QLatin1String("QLocalSocket::connectToserver")); setErrorString(errorString); emit error(QLocalSocket::OperationError); return; } d->errorString.clear(); d->unixSocket.setSocketState(QAbstractSocket::ConnectingState); d->state = ConnectingState; emit stateChanged(d->state); if (d->serverName.isEmpty()) { d->errorOccurred(ServerNotFoundError, QLatin1String("QLocalSocket::connectToServer")); return; } // create the socket if (-1 == (d->connectingSocket = qt_safe_socket(PF_UNIX, SOCK_STREAM, 0, O_NONBLOCK))) { d->errorOccurred(UnsupportedSocketOperationError, QLatin1String("QLocalSocket::connectToServer")); return; } // _q_connectToSocket does the actual connecting d->connectingName = d->serverName; d->connectingOpenMode = openMode; d->_q_connectToSocket(); return; } /*! \internal Tries to connect connectingName and connectingOpenMode \sa connectToServer(), waitForConnected() */ void QLocalSocketPrivate::_q_connectToSocket() { Q_Q(QLocalSocket); QString connectingPathName; // determine the full server path if (connectingName.startsWith(QLatin1Char('/'))) { connectingPathName = connectingName; } else { connectingPathName = QDir::tempPath(); connectingPathName += QLatin1Char('/') + connectingName; } const QByteArray encodedConnectingPathName = QFile::encodeName(connectingPathName); struct sockaddr_un name; name.sun_family = PF_UNIX; if (sizeof(name.sun_path) < (uint)encodedConnectingPathName.size() + 1) { QString function = QLatin1String("QLocalSocket::connectToServer"); errorOccurred(QLocalSocket::ServerNotFoundError, function); return; } ::memcpy(name.sun_path, encodedConnectingPathName.constData(), encodedConnectingPathName.size() + 1); if (-1 == qt_safe_connect(connectingSocket, (struct sockaddr *)&name, sizeof(name))) { QString function = QLatin1String("QLocalSocket::connectToServer"); switch (errno) { case EINVAL: case ECONNREFUSED: errorOccurred(QLocalSocket::ConnectionRefusedError, function); break; case ENOENT: errorOccurred(QLocalSocket::ServerNotFoundError, function); break; case EACCES: case EPERM: errorOccurred(QLocalSocket::SocketAccessError, function); break; case ETIMEDOUT: errorOccurred(QLocalSocket::SocketTimeoutError, function); break; case EAGAIN: // Try again later, all of the sockets listening are full if (!delayConnect) { delayConnect = new QSocketNotifier(connectingSocket, QSocketNotifier::Write, q); q->connect(delayConnect, SIGNAL(activated(int)), q, SLOT(_q_connectToSocket())); } if (!connectTimer) { connectTimer = new QTimer(q); q->connect(connectTimer, SIGNAL(timeout()), q, SLOT(_q_abortConnectionAttempt()), Qt::DirectConnection); connectTimer->start(QT_CONNECT_TIMEOUT); } delayConnect->setEnabled(true); break; default: errorOccurred(QLocalSocket::UnknownSocketError, function); } return; } // connected! cancelDelayedConnect(); serverName = connectingName; fullServerName = connectingPathName; if (unixSocket.setSocketDescriptor(connectingSocket, QAbstractSocket::ConnectedState, connectingOpenMode)) { q->QIODevice::open(connectingOpenMode | QIODevice::Unbuffered); q->emit connected(); } else { QString function = QLatin1String("QLocalSocket::connectToServer"); errorOccurred(QLocalSocket::UnknownSocketError, function); } connectingSocket = -1; connectingName.clear(); connectingOpenMode = 0; } bool QLocalSocket::setSocketDescriptor(qintptr socketDescriptor, LocalSocketState socketState, OpenMode openMode) { Q_D(QLocalSocket); QAbstractSocket::SocketState newSocketState = QAbstractSocket::UnconnectedState; switch (socketState) { case ConnectingState: newSocketState = QAbstractSocket::ConnectingState; break; case ConnectedState: newSocketState = QAbstractSocket::ConnectedState; break; case ClosingState: newSocketState = QAbstractSocket::ClosingState; break; case UnconnectedState: newSocketState = QAbstractSocket::UnconnectedState; break; } QIODevice::open(openMode); d->state = socketState; return d->unixSocket.setSocketDescriptor(socketDescriptor, newSocketState, openMode); } void QLocalSocketPrivate::_q_abortConnectionAttempt() { Q_Q(QLocalSocket); q->close(); } void QLocalSocketPrivate::cancelDelayedConnect() { if (delayConnect) { delayConnect->setEnabled(false); delete delayConnect; delayConnect = 0; connectTimer->stop(); delete connectTimer; connectTimer = 0; } } qintptr QLocalSocket::socketDescriptor() const { Q_D(const QLocalSocket); return d->unixSocket.socketDescriptor(); } qint64 QLocalSocket::readData(char *data, qint64 c) { Q_D(QLocalSocket); return d->unixSocket.read(data, c); } qint64 QLocalSocket::writeData(const char *data, qint64 c) { Q_D(QLocalSocket); return d->unixSocket.writeData(data, c); } void QLocalSocket::abort() { Q_D(QLocalSocket); d->unixSocket.abort(); } qint64 QLocalSocket::bytesAvailable() const { Q_D(const QLocalSocket); return QIODevice::bytesAvailable() + d->unixSocket.bytesAvailable(); } qint64 QLocalSocket::bytesToWrite() const { Q_D(const QLocalSocket); return d->unixSocket.bytesToWrite(); } bool QLocalSocket::canReadLine() const { Q_D(const QLocalSocket); return QIODevice::canReadLine() || d->unixSocket.canReadLine(); } void QLocalSocket::close() { Q_D(QLocalSocket); d->unixSocket.close(); d->cancelDelayedConnect(); if (d->connectingSocket != -1) ::close(d->connectingSocket); d->connectingSocket = -1; d->connectingName.clear(); d->connectingOpenMode = 0; d->serverName.clear(); d->fullServerName.clear(); QIODevice::close(); } bool QLocalSocket::waitForBytesWritten(int msecs) { Q_D(QLocalSocket); return d->unixSocket.waitForBytesWritten(msecs); } bool QLocalSocket::flush() { Q_D(QLocalSocket); return d->unixSocket.flush(); } void QLocalSocket::disconnectFromServer() { Q_D(QLocalSocket); d->unixSocket.disconnectFromHost(); } QLocalSocket::LocalSocketError QLocalSocket::error() const { Q_D(const QLocalSocket); switch (d->unixSocket.error()) { case QAbstractSocket::ConnectionRefusedError: return QLocalSocket::ConnectionRefusedError; case QAbstractSocket::RemoteHostClosedError: return QLocalSocket::PeerClosedError; case QAbstractSocket::HostNotFoundError: return QLocalSocket::ServerNotFoundError; case QAbstractSocket::SocketAccessError: return QLocalSocket::SocketAccessError; case QAbstractSocket::SocketResourceError: return QLocalSocket::SocketResourceError; case QAbstractSocket::SocketTimeoutError: return QLocalSocket::SocketTimeoutError; case QAbstractSocket::DatagramTooLargeError: return QLocalSocket::DatagramTooLargeError; case QAbstractSocket::NetworkError: return QLocalSocket::ConnectionError; case QAbstractSocket::UnsupportedSocketOperationError: return QLocalSocket::UnsupportedSocketOperationError; case QAbstractSocket::UnknownSocketError: return QLocalSocket::UnknownSocketError; default: #if defined QLOCALSOCKET_DEBUG qWarning() << "QLocalSocket error not handled:" << d->unixSocket.error(); #endif break; } return UnknownSocketError; } bool QLocalSocket::isValid() const { Q_D(const QLocalSocket); return d->unixSocket.isValid(); } qint64 QLocalSocket::readBufferSize() const { Q_D(const QLocalSocket); return d->unixSocket.readBufferSize(); } void QLocalSocket::setReadBufferSize(qint64 size) { Q_D(QLocalSocket); d->unixSocket.setReadBufferSize(size); } bool QLocalSocket::waitForConnected(int msec) { Q_D(QLocalSocket); if (state() != ConnectingState) return (state() == ConnectedState); QElapsedTimer timer; timer.start(); pollfd pfd = qt_make_pollfd(d->connectingSocket, POLLIN); do { const int timeout = (msec > 0) ? qMax(msec - timer.elapsed(), Q_INT64_C(0)) : msec; const int result = qt_poll_msecs(&pfd, 1, timeout); if (result == -1) d->errorOccurred(QLocalSocket::UnknownSocketError, QLatin1String("QLocalSocket::waitForConnected")); else if (result > 0) d->_q_connectToSocket(); } while (state() == ConnectingState && !timer.hasExpired(msec)); return (state() == ConnectedState); } bool QLocalSocket::waitForDisconnected(int msecs) { Q_D(QLocalSocket); if (state() == UnconnectedState) { qWarning("QLocalSocket::waitForDisconnected() is not allowed in UnconnectedState"); return false; } return (d->unixSocket.waitForDisconnected(msecs)); } bool QLocalSocket::waitForReadyRead(int msecs) { Q_D(QLocalSocket); if (state() == QLocalSocket::UnconnectedState) return false; return (d->unixSocket.waitForReadyRead(msecs)); } QT_END_NAMESPACE
18,441
5,408
#include "logger.h" #include <boost/log/attributes/attribute_value_set.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/expressions.hpp> #include <boost/shared_ptr.hpp> void init_logger(const std::string& prefixFile, boost::log::trivial::severity_level severity) { auto format = "[%TimeStamp%] [%ThreadID%] [%Severity%] [%ProcessID%] [%LineID%] %Message%"; namespace keywords = boost::log::keywords; namespace expr = boost::log::expressions; boost::log::add_console_log( std::clog, keywords::format = ( expr::stream //<< std::hex //To print the LineID in Hexadecimal format // << std::setw(8) << std::setfill('0') << expr::attr< unsigned int >("LineID") // << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f") << "<" << boost::log::trivial::severity << ">" << expr::smessage ) ); boost::log::add_file_log ( keywords::file_name = prefixFile, /*< file name pattern >*/ keywords::rotation_size = 10 * 1024, /*< rotate files every 1 KiB >*/ /*< log record format >*/ keywords::format = ( expr::stream //<< std::hex //To print the LineID in Hexadecimal format // << std::setw(8) << std::setfill('0') << expr::attr< unsigned int >("LineID") << "\t" // << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f") << "\t: <" << boost::log::trivial::severity << "> \t" << expr::smessage ) ); // boost::log::core::get()->set_filter // ( // boost::log::trivial::severity >= severity // ); }
1,915
642
#define DEBUG 1 /** * File : A.cpp * Author : Kazune Takahashi * Created : 2020/1/25 11:32:12 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } class Sieve { static constexpr ll MAX_SIZE{10000010LL}; ll N; vector<ll> f; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{} { f[0] = f[1] = -1; for (auto i = 2; i < N; i++) { if (f[i]) { continue; } prime_nums.push_back(i); f[i] = i; for (auto j = 2 * i; j < N; j += i) { if (!f[j]) { f[j] = i; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return f[x]; } for (auto e : prime_nums) { if (x % e == 0) { return false; } } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { if (x < 2) { return {}; } vector<ll> res; auto it{prime_nums.begin()}; if (x < N) { while (x != 1) { res.push_back(f[x]); x /= f[x]; } } else { while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } } return res; } vector<tuple<ll, ll>> factor(ll x) const { if (x < 2) { return {}; } auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; // ----- main() ----- using ld = long double; using point = complex<ld>; constexpr ld PI{3.14159265358979323846}; class Solve { ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc; int alpha; Sieve sieve; ld Ta = 0; ld Tb; point Oa{0, 900}, Ob{900, 0}, Oc{900, 900}, Oe{90, 50}; point Aa{1, 0}, Ab{0, 1}, Ac{-1, 0}; ld S{500}, A{3000}, D{60}; public: Solve(ld La, ld Lb, ld Lc, ld Na, ld Nb, ld Nc, ld Ne, ld Ma, ld Mb, ld Mc, ld Tc) : La{La}, Lb{Lb}, Lc{Lc}, Na{Na}, Nb{Nb}, Nc{Nc}, Ne{Ne}, Ma{Ma}, Mb{Mb}, Mc{Mc}, Tc{Tc} {} void flush() { for (auto i = 0; i < 20; ++i) { ld now{0}; ld W{Ma}; if (now + Ma * Na > 100) { W = 500; } flush_A(W); now += Na * W; W = Mb; if (now + Mb * Nb > 100) { W = 500; } flush_B(W); now += Nb * W; W = Mc; if (now + Mc * Nc > 100) { W = 500; } flush_C(W); now += Nc * W; flush_E(now / Ne); } } private: void update_Tb() { if (alpha == 0) { Tb = 0; } else { ll p{sieve.primes()[alpha + 1]}; ll r{p % 180}; Tb = (r <= 90 ? r : 180 - r); } } point arg(ld theta) { return theta / 180 * PI * point(0, 1); } point Pa() { return exp(-arg(Ta)) * La + Oa; } point Pb() { return exp(arg(Tb)) * Lb + Ob; } point Pc() { return exp(arg(Tc)) * Lc + Oc; } void flush_simple(ld X, ld Sx, ld Ax, ld Dx, ld Y, ld Sy, ld Ay, ld Dy, ld Ta, ld Wa, ld Wb, ld Wc, ld We) { cout << fixed << setprecision(0) << X << ", " << Sx << ", " << Ax << ", " << Dx << ", " << Y << ", " << Sy << ", " << Ay << ", " << Dy << ", " << Ta << ", " << Wa << ", " << Wb << ", " << Wc << ", " << We << endl; } void flush_A(ld W) { flush_simple(Pa().real(), S, A, D, Pa().imag(), S, A, D, Ta, W, 0, 0, 0); alpha += W; } void flush_B(ld W) { flush_simple(Pb().real(), S, A, D, Pb().imag(), S, A, D, Ta, 0, W, 0, 0); } void flush_C(ld W) { flush_simple(Pc().real(), S, A, D, Pc().imag(), S, A, D, Ta, 0, 0, W, 0); } void flush_E(ld W) { flush_simple(Oe.real(), S, A, D, Oe.imag(), S, A, D, Ta, 0, 0, 0, W); } }; int main() { ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc; cin >> La >> Lb >> Lc >> Na >> Nb >> Nc >> Ne >> Ma >> Mb >> Mc >> Tc; Solve solve(La, Lb, Lc, Na / 1000, Nb / 1000, Nc / 1000, Ne / 1000, Ma, Mb, Mc, Tc); solve.flush(); }
9,016
4,059
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "GameFramework/Info.h" #include "UObject/ConstructorHelpers.h" #include "Components/BillboardComponent.h" #include "Engine/Texture2D.h" AInfo::AInfo(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { #if WITH_EDITORONLY_DATA SpriteComponent = CreateEditorOnlyDefaultSubobject<UBillboardComponent>(TEXT("Sprite")); RootComponent = SpriteComponent; if (!IsRunningCommandlet() && (SpriteComponent != nullptr)) { // Structure to hold one-time initialization struct FConstructorStatics { ConstructorHelpers::FObjectFinderOptional<UTexture2D> SpriteTexture; FName ID_Info; FText NAME_Info; FConstructorStatics() : SpriteTexture(TEXT("/Engine/EditorResources/S_Actor")) , ID_Info(TEXT("Info")) , NAME_Info(NSLOCTEXT("SpriteCategory", "Info", "Info")) { } }; static FConstructorStatics ConstructorStatics; SpriteComponent->Sprite = ConstructorStatics.SpriteTexture.Get(); SpriteComponent->SpriteInfo.Category = ConstructorStatics.ID_Info; SpriteComponent->SpriteInfo.DisplayName = ConstructorStatics.NAME_Info; SpriteComponent->bIsScreenSizeScaled = true; } #endif // WITH_EDITORONLY_DATA PrimaryActorTick.bCanEverTick = false; bAllowTickBeforeBeginPlay = true; bReplicates = false; NetUpdateFrequency = 10.0f; bHidden = true; bReplicateMovement = false; bCanBeDamaged = false; } #if WITH_EDITORONLY_DATA /** Returns SpriteComponent subobject **/ UBillboardComponent* AInfo::GetSpriteComponent() const { return SpriteComponent; } #endif
1,590
576
// GLFW mojo runtime. // // Copyright 2011 Mark Sibly, all rights reserved. // No warranty implied; use at your own risk. //***** gxtkGraphics.h ***** class gxtkSurface; class gxtkGraphics : public Object{ public: enum{ MAX_VERTS=1024, MAX_QUADS=(MAX_VERTS/4) }; int width; int height; int colorARGB; float r,g,b,alpha; float ix,iy,jx,jy,tx,ty; bool tformed; float vertices[MAX_VERTS*5]; unsigned short quadIndices[MAX_QUADS*6]; int primType; int vertCount; gxtkSurface *primSurf; gxtkGraphics(); void Flush(); float *Begin( int type,int count,gxtkSurface *surf ); //***** GXTK API ***** virtual int Width(); virtual int Height(); virtual int BeginRender(); virtual void EndRender(); virtual void DiscardGraphics(); virtual gxtkSurface *LoadSurface( String path ); virtual gxtkSurface *CreateSurface( int width,int height ); virtual bool LoadSurface__UNSAFE__( gxtkSurface *surface,String path ); virtual int Cls( float r,float g,float b ); virtual int SetAlpha( float alpha ); virtual int SetColor( float r,float g,float b ); virtual int SetBlend( int blend ); virtual int SetScissor( int x,int y,int w,int h ); virtual int SetMatrix( float ix,float iy,float jx,float jy,float tx,float ty ); virtual int DrawPoint( float x,float y ); virtual int DrawRect( float x,float y,float w,float h ); virtual int DrawLine( float x1,float y1,float x2,float y2 ); virtual int DrawOval( float x1,float y1,float x2,float y2 ); virtual int DrawPoly( Array<Float> verts ); virtual int DrawPoly2( Array<Float> verts,gxtkSurface *surface,int srcx,int srcy ); virtual int DrawSurface( gxtkSurface *surface,float x,float y ); virtual int DrawSurface2( gxtkSurface *surface,float x,float y,int srcx,int srcy,int srcw,int srch ); virtual int ReadPixels( Array<int> pixels,int x,int y,int width,int height,int offset,int pitch ); virtual int WritePixels2( gxtkSurface *surface,Array<int> pixels,int x,int y,int width,int height,int offset,int pitch ); }; class gxtkSurface : public Object{ public: unsigned char *data; int width; int height; int depth; int format; int seq; GLuint texture; float uscale; float vscale; gxtkSurface(); void SetData( unsigned char *data,int width,int height,int depth ); void SetSubData( int x,int y,int w,int h,unsigned *src,int pitch ); void Bind(); ~gxtkSurface(); //***** GXTK API ***** virtual int Discard(); virtual int Width(); virtual int Height(); virtual int Loaded(); virtual void OnUnsafeLoadComplete(); }; //***** gxtkGraphics.cpp ***** #ifndef GL_BGRA #define GL_BGRA 0x80e1 #endif #ifndef GL_CLAMP_TO_EDGE #define GL_CLAMP_TO_EDGE 0x812f #endif #ifndef GL_GENERATE_MIPMAP #define GL_GENERATE_MIPMAP 0x8191 #endif static int Pow2Size( int n ){ int i=1; while( i<n ) i+=i; return i; } gxtkGraphics::gxtkGraphics(){ width=height=0; vertCount=0; #ifdef _glfw3_h_ GLFWwindow *window=BBGlfwGame::GlfwGame()->GetGLFWwindow(); if( window ) glfwGetWindowSize( BBGlfwGame::GlfwGame()->GetGLFWwindow(),&width,&height ); #else glfwGetWindowSize( &width,&height ); #endif if( CFG_OPENGL_GLES20_ENABLED ) return; for( int i=0;i<MAX_QUADS;++i ){ quadIndices[i*6 ]=(short)(i*4); quadIndices[i*6+1]=(short)(i*4+1); quadIndices[i*6+2]=(short)(i*4+2); quadIndices[i*6+3]=(short)(i*4); quadIndices[i*6+4]=(short)(i*4+2); quadIndices[i*6+5]=(short)(i*4+3); } } void gxtkGraphics::Flush(){ if( !vertCount ) return; if( primSurf ){ glEnable( GL_TEXTURE_2D ); primSurf->Bind(); } switch( primType ){ case 1: glDrawArrays( GL_POINTS,0,vertCount ); break; case 2: glDrawArrays( GL_LINES,0,vertCount ); break; case 3: glDrawArrays( GL_TRIANGLES,0,vertCount ); break; case 4: glDrawElements( GL_TRIANGLES,vertCount/4*6,GL_UNSIGNED_SHORT,quadIndices ); break; default: for( int j=0;j<vertCount;j+=primType ){ glDrawArrays( GL_TRIANGLE_FAN,j,primType ); } break; } if( primSurf ){ glDisable( GL_TEXTURE_2D ); } vertCount=0; } float *gxtkGraphics::Begin( int type,int count,gxtkSurface *surf ){ if( primType!=type || primSurf!=surf || vertCount+count>MAX_VERTS ){ Flush(); primType=type; primSurf=surf; } float *vp=vertices+vertCount*5; vertCount+=count; return vp; } //***** GXTK API ***** int gxtkGraphics::Width(){ return width; } int gxtkGraphics::Height(){ return height; } int gxtkGraphics::BeginRender(){ width=height=0; #ifdef _glfw3_h_ glfwGetWindowSize( BBGlfwGame::GlfwGame()->GetGLFWwindow(),&width,&height ); #else glfwGetWindowSize( &width,&height ); #endif #if CFG_OPENGL_GLES20_ENABLED return 0; #else glViewport( 0,0,width,height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity(); glOrtho( 0,width,height,0,-1,1 ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glEnableClientState( GL_VERTEX_ARRAY ); glVertexPointer( 2,GL_FLOAT,20,&vertices[0] ); glEnableClientState( GL_TEXTURE_COORD_ARRAY ); glTexCoordPointer( 2,GL_FLOAT,20,&vertices[2] ); glEnableClientState( GL_COLOR_ARRAY ); glColorPointer( 4,GL_UNSIGNED_BYTE,20,&vertices[4] ); glEnable( GL_BLEND ); glBlendFunc( GL_ONE,GL_ONE_MINUS_SRC_ALPHA ); glDisable( GL_TEXTURE_2D ); vertCount=0; return 1; #endif } void gxtkGraphics::EndRender(){ if( !CFG_OPENGL_GLES20_ENABLED ) Flush(); } void gxtkGraphics::DiscardGraphics(){ } int gxtkGraphics::Cls( float r,float g,float b ){ vertCount=0; glClearColor( r/255.0f,g/255.0f,b/255.0f,1 ); glClear( GL_COLOR_BUFFER_BIT ); return 0; } int gxtkGraphics::SetAlpha( float alpha ){ this->alpha=alpha; int a=int(alpha*255); colorARGB=(a<<24) | (int(b*alpha)<<16) | (int(g*alpha)<<8) | int(r*alpha); return 0; } int gxtkGraphics::SetColor( float r,float g,float b ){ this->r=r; this->g=g; this->b=b; int a=int(alpha*255); colorARGB=(a<<24) | (int(b*alpha)<<16) | (int(g*alpha)<<8) | int(r*alpha); return 0; } int gxtkGraphics::SetBlend( int blend ){ Flush(); switch( blend ){ case 1: glBlendFunc( GL_ONE,GL_ONE ); break; default: glBlendFunc( GL_ONE,GL_ONE_MINUS_SRC_ALPHA ); } return 0; } int gxtkGraphics::SetScissor( int x,int y,int w,int h ){ Flush(); if( x!=0 || y!=0 || w!=Width() || h!=Height() ){ glEnable( GL_SCISSOR_TEST ); y=Height()-y-h; glScissor( x,y,w,h ); }else{ glDisable( GL_SCISSOR_TEST ); } return 0; } int gxtkGraphics::SetMatrix( float ix,float iy,float jx,float jy,float tx,float ty ){ tformed=(ix!=1 || iy!=0 || jx!=0 || jy!=1 || tx!=0 || ty!=0); this->ix=ix;this->iy=iy;this->jx=jx;this->jy=jy;this->tx=tx;this->ty=ty; return 0; } int gxtkGraphics::DrawPoint( float x,float y ){ if( tformed ){ float px=x; x=px * ix + y * jx + tx; y=px * iy + y * jy + ty; } float *vp=Begin( 1,1,0 ); vp[0]=x+.5f;vp[1]=y+.5f;(int&)vp[4]=colorARGB; return 0; } int gxtkGraphics::DrawLine( float x0,float y0,float x1,float y1 ){ if( tformed ){ float tx0=x0,tx1=x1; x0=tx0 * ix + y0 * jx + tx;y0=tx0 * iy + y0 * jy + ty; x1=tx1 * ix + y1 * jx + tx;y1=tx1 * iy + y1 * jy + ty; } float *vp=Begin( 2,2,0 ); vp[0]=x0+.5f;vp[1]=y0+.5f;(int&)vp[4]=colorARGB; vp[5]=x1+.5f;vp[6]=y1+.5f;(int&)vp[9]=colorARGB; return 0; } int gxtkGraphics::DrawRect( float x,float y,float w,float h ){ float x0=x,x1=x+w,x2=x+w,x3=x; float y0=y,y1=y,y2=y+h,y3=y+h; if( tformed ){ float tx0=x0,tx1=x1,tx2=x2,tx3=x3; x0=tx0 * ix + y0 * jx + tx;y0=tx0 * iy + y0 * jy + ty; x1=tx1 * ix + y1 * jx + tx;y1=tx1 * iy + y1 * jy + ty; x2=tx2 * ix + y2 * jx + tx;y2=tx2 * iy + y2 * jy + ty; x3=tx3 * ix + y3 * jx + tx;y3=tx3 * iy + y3 * jy + ty; } float *vp=Begin( 4,4,0 ); vp[0 ]=x0;vp[1 ]=y0;(int&)vp[4 ]=colorARGB; vp[5 ]=x1;vp[6 ]=y1;(int&)vp[9 ]=colorARGB; vp[10]=x2;vp[11]=y2;(int&)vp[14]=colorARGB; vp[15]=x3;vp[16]=y3;(int&)vp[19]=colorARGB; return 0; } int gxtkGraphics::DrawOval( float x,float y,float w,float h ){ float xr=w/2.0f; float yr=h/2.0f; int n; if( tformed ){ float dx_x=xr * ix; float dx_y=xr * iy; float dx=sqrtf( dx_x*dx_x+dx_y*dx_y ); float dy_x=yr * jx; float dy_y=yr * jy; float dy=sqrtf( dy_x*dy_x+dy_y*dy_y ); n=(int)( dx+dy ); }else{ n=(int)( fabs( xr )+fabs( yr ) ); } if( n<12 ){ n=12; }else if( n>MAX_VERTS ){ n=MAX_VERTS; }else{ n&=~3; } float x0=x+xr,y0=y+yr; float *vp=Begin( n,n,0 ); for( int i=0;i<n;++i ){ float th=i * 6.28318531f / n; float px=x0+cosf( th ) * xr; float py=y0-sinf( th ) * yr; if( tformed ){ float ppx=px; px=ppx * ix + py * jx + tx; py=ppx * iy + py * jy + ty; } vp[0]=px;vp[1]=py;(int&)vp[4]=colorARGB; vp+=5; } return 0; } int gxtkGraphics::DrawPoly( Array<Float> verts ){ int n=verts.Length()/2; if( n<1 || n>MAX_VERTS ) return 0; float *vp=Begin( n,n,0 ); for( int i=0;i<n;++i ){ int j=i*2; if( tformed ){ vp[0]=verts[j] * ix + verts[j+1] * jx + tx; vp[1]=verts[j] * iy + verts[j+1] * jy + ty; }else{ vp[0]=verts[j]; vp[1]=verts[j+1]; } (int&)vp[4]=colorARGB; vp+=5; } return 0; } int gxtkGraphics::DrawPoly2( Array<Float> verts,gxtkSurface *surface,int srcx,int srcy ){ int n=verts.Length()/4; if( n<1 || n>MAX_VERTS ) return 0; float *vp=Begin( n,n,surface ); for( int i=0;i<n;++i ){ int j=i*4; if( tformed ){ vp[0]=verts[j] * ix + verts[j+1] * jx + tx; vp[1]=verts[j] * iy + verts[j+1] * jy + ty; }else{ vp[0]=verts[j]; vp[1]=verts[j+1]; } vp[2]=(srcx+verts[j+2])*surface->uscale; vp[3]=(srcy+verts[j+3])*surface->vscale; (int&)vp[4]=colorARGB; vp+=5; } return 0; } int gxtkGraphics::DrawSurface( gxtkSurface *surf,float x,float y ){ float w=surf->Width(); float h=surf->Height(); float x0=x,x1=x+w,x2=x+w,x3=x; float y0=y,y1=y,y2=y+h,y3=y+h; float u0=0,u1=w*surf->uscale; float v0=0,v1=h*surf->vscale; if( tformed ){ float tx0=x0,tx1=x1,tx2=x2,tx3=x3; x0=tx0 * ix + y0 * jx + tx;y0=tx0 * iy + y0 * jy + ty; x1=tx1 * ix + y1 * jx + tx;y1=tx1 * iy + y1 * jy + ty; x2=tx2 * ix + y2 * jx + tx;y2=tx2 * iy + y2 * jy + ty; x3=tx3 * ix + y3 * jx + tx;y3=tx3 * iy + y3 * jy + ty; } float *vp=Begin( 4,4,surf ); vp[0 ]=x0;vp[1 ]=y0;vp[2 ]=u0;vp[3 ]=v0;(int&)vp[4 ]=colorARGB; vp[5 ]=x1;vp[6 ]=y1;vp[7 ]=u1;vp[8 ]=v0;(int&)vp[9 ]=colorARGB; vp[10]=x2;vp[11]=y2;vp[12]=u1;vp[13]=v1;(int&)vp[14]=colorARGB; vp[15]=x3;vp[16]=y3;vp[17]=u0;vp[18]=v1;(int&)vp[19]=colorARGB; return 0; } int gxtkGraphics::DrawSurface2( gxtkSurface *surf,float x,float y,int srcx,int srcy,int srcw,int srch ){ float w=srcw; float h=srch; float x0=x,x1=x+w,x2=x+w,x3=x; float y0=y,y1=y,y2=y+h,y3=y+h; float u0=srcx*surf->uscale,u1=(srcx+srcw)*surf->uscale; float v0=srcy*surf->vscale,v1=(srcy+srch)*surf->vscale; if( tformed ){ float tx0=x0,tx1=x1,tx2=x2,tx3=x3; x0=tx0 * ix + y0 * jx + tx;y0=tx0 * iy + y0 * jy + ty; x1=tx1 * ix + y1 * jx + tx;y1=tx1 * iy + y1 * jy + ty; x2=tx2 * ix + y2 * jx + tx;y2=tx2 * iy + y2 * jy + ty; x3=tx3 * ix + y3 * jx + tx;y3=tx3 * iy + y3 * jy + ty; } float *vp=Begin( 4,4,surf ); vp[0 ]=x0;vp[1 ]=y0;vp[2 ]=u0;vp[3 ]=v0;(int&)vp[4 ]=colorARGB; vp[5 ]=x1;vp[6 ]=y1;vp[7 ]=u1;vp[8 ]=v0;(int&)vp[9 ]=colorARGB; vp[10]=x2;vp[11]=y2;vp[12]=u1;vp[13]=v1;(int&)vp[14]=colorARGB; vp[15]=x3;vp[16]=y3;vp[17]=u0;vp[18]=v1;(int&)vp[19]=colorARGB; return 0; } int gxtkGraphics::ReadPixels( Array<int> pixels,int x,int y,int width,int height,int offset,int pitch ){ Flush(); unsigned *p=(unsigned*)malloc(width*height*4); glReadPixels( x,this->height-y-height,width,height,GL_BGRA,GL_UNSIGNED_BYTE,p ); for( int py=0;py<height;++py ){ memcpy( &pixels[offset+py*pitch],&p[(height-py-1)*width],width*4 ); } free( p ); return 0; } int gxtkGraphics::WritePixels2( gxtkSurface *surface,Array<int> pixels,int x,int y,int width,int height,int offset,int pitch ){ surface->SetSubData( x,y,width,height,(unsigned*)&pixels[offset],pitch ); return 0; } //***** gxtkSurface ***** gxtkSurface::gxtkSurface():data(0),width(0),height(0),depth(0),format(0),seq(-1),texture(0),uscale(0),vscale(0){ } gxtkSurface::~gxtkSurface(){ Discard(); } int gxtkSurface::Discard(){ if( seq==glfwGraphicsSeq ){ glDeleteTextures( 1,&texture ); seq=-1; } if( data ){ free( data ); data=0; } return 0; } int gxtkSurface::Width(){ return width; } int gxtkSurface::Height(){ return height; } int gxtkSurface::Loaded(){ return 1; } //Careful! Can't call any GL here as it may be executing off-thread. // void gxtkSurface::SetData( unsigned char *data,int width,int height,int depth ){ this->data=data; this->width=width; this->height=height; this->depth=depth; unsigned char *p=data; int n=width*height; switch( depth ){ case 1: #if _WIN32 format=GL_LUMINANCE; #elif __APPLE__ format=GL_RED; #elif __linux format=GL_LUMINANCE; #endif break; case 2: #if _WIN32 format=GL_LUMINANCE_ALPHA; #elif __APPLE__ format=GL_RG; #elif __linux format=GL_LUMINANCE_ALPHA; #endif if( data ){ while( n-- ){ //premultiply alpha p[0]=p[0]*p[1]/255; p+=2; } } break; case 3: format=GL_RGB; break; case 4: format=GL_RGBA; if( data ){ while( n-- ){ //premultiply alpha p[0]=p[0]*p[3]/255; p[1]=p[1]*p[3]/255; p[2]=p[2]*p[3]/255; p+=4; } } break; } } void gxtkSurface::SetSubData( int x,int y,int w,int h,unsigned *src,int pitch ){ if( format!=GL_RGBA ) return; if( !data ) data=(unsigned char*)malloc( width*height*4 ); unsigned *dst=(unsigned*)data+y*width+x; for( int py=0;py<h;++py ){ unsigned *d=dst+py*width; unsigned *s=src+py*pitch; for( int px=0;px<w;++px ){ unsigned p=*s++; unsigned a=p>>24; *d++=(a<<24) | ((p>>0&0xff)*a/255<<16) | ((p>>8&0xff)*a/255<<8) | ((p>>16&0xff)*a/255); } } if( seq==glfwGraphicsSeq ){ glBindTexture( GL_TEXTURE_2D,texture ); glPixelStorei( GL_UNPACK_ALIGNMENT,1 ); if( width==pitch ){ glTexSubImage2D( GL_TEXTURE_2D,0,x,y,w,h,format,GL_UNSIGNED_BYTE,dst ); }else{ for( int py=0;py<h;++py ){ glTexSubImage2D( GL_TEXTURE_2D,0,x,y+py,w,1,format,GL_UNSIGNED_BYTE,dst+py*width ); } } } } void gxtkSurface::Bind(){ if( !glfwGraphicsSeq ) return; if( seq==glfwGraphicsSeq ){ glBindTexture( GL_TEXTURE_2D,texture ); return; } seq=glfwGraphicsSeq; glGenTextures( 1,&texture ); glBindTexture( GL_TEXTURE_2D,texture ); if( CFG_MOJO_IMAGE_FILTERING_ENABLED ){ glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR ); }else{ glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_NEAREST ); glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_NEAREST ); } glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_WRAP_S,GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D,GL_TEXTURE_WRAP_T,GL_CLAMP_TO_EDGE ); int texwidth=width; int texheight=height; glTexImage2D( GL_TEXTURE_2D,0,format,texwidth,texheight,0,format,GL_UNSIGNED_BYTE,0 ); if( glGetError()!=GL_NO_ERROR ){ texwidth=Pow2Size( width ); texheight=Pow2Size( height ); glTexImage2D( GL_TEXTURE_2D,0,format,texwidth,texheight,0,format,GL_UNSIGNED_BYTE,0 ); } uscale=1.0/texwidth; vscale=1.0/texheight; if( data ){ glPixelStorei( GL_UNPACK_ALIGNMENT,1 ); glTexSubImage2D( GL_TEXTURE_2D,0,0,0,width,height,format,GL_UNSIGNED_BYTE,data ); } } void gxtkSurface::OnUnsafeLoadComplete(){ Bind(); } bool gxtkGraphics::LoadSurface__UNSAFE__( gxtkSurface *surface,String path ){ int width,height,depth; unsigned char *data=BBGlfwGame::GlfwGame()->LoadImageData( path,&width,&height,&depth ); if( !data ) return false; surface->SetData( data,width,height,depth ); return true; } gxtkSurface *gxtkGraphics::LoadSurface( String path ){ gxtkSurface *surf=new gxtkSurface(); if( !LoadSurface__UNSAFE__( surf,path ) ) return 0; surf->Bind(); return surf; } gxtkSurface *gxtkGraphics::CreateSurface( int width,int height ){ gxtkSurface *surf=new gxtkSurface(); surf->SetData( 0,width,height,4 ); surf->Bind(); return surf; } //***** gxtkAudio.h ***** class gxtkSample; class gxtkChannel{ public: ALuint source; gxtkSample *sample; int flags; int state; int AL_Source(); }; class gxtkAudio : public Object{ public: static gxtkAudio *audio; ALCdevice *alcDevice; ALCcontext *alcContext; gxtkChannel channels[33]; gxtkAudio(); virtual void mark(); //***** GXTK API ***** virtual int Suspend(); virtual int Resume(); virtual gxtkSample *LoadSample( String path ); virtual bool LoadSample__UNSAFE__( gxtkSample *sample,String path ); virtual int PlaySample( gxtkSample *sample,int channel,int flags ); virtual int StopChannel( int channel ); virtual int PauseChannel( int channel ); virtual int ResumeChannel( int channel ); virtual int ChannelState( int channel ); virtual int SetVolume( int channel,float volume ); virtual int SetPan( int channel,float pan ); virtual int SetRate( int channel,float rate ); virtual int PlayMusic( String path,int flags ); virtual int StopMusic(); virtual int PauseMusic(); virtual int ResumeMusic(); virtual int MusicState(); virtual int SetMusicVolume( float volume ); }; class gxtkSample : public Object{ public: ALuint al_buffer; gxtkSample(); gxtkSample( ALuint buf ); ~gxtkSample(); void SetBuffer( ALuint buf ); //***** GXTK API ***** virtual int Discard(); }; //***** gxtkAudio.cpp ***** gxtkAudio *gxtkAudio::audio; static std::vector<ALuint> discarded; static void FlushDiscarded(){ if( !discarded.size() ) return; for( int i=0;i<33;++i ){ gxtkChannel *chan=&gxtkAudio::audio->channels[i]; if( chan->state ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state==AL_STOPPED ) alSourcei( chan->source,AL_BUFFER,0 ); } } std::vector<ALuint> out; for( int i=0;i<discarded.size();++i ){ ALuint buf=discarded[i]; alDeleteBuffers( 1,&buf ); ALenum err=alGetError(); if( err==AL_NO_ERROR ){ // printf( "alDeleteBuffers OK!\n" );fflush( stdout ); }else{ // printf( "alDeleteBuffers failed...\n" );fflush( stdout ); out.push_back( buf ); } } discarded=out; } int gxtkChannel::AL_Source(){ if( source ) return source; alGetError(); alGenSources( 1,&source ); if( alGetError()==AL_NO_ERROR ) return source; //couldn't create source...steal a free source...? // source=0; for( int i=0;i<32;++i ){ gxtkChannel *chan=&gxtkAudio::audio->channels[i]; if( !chan->source || gxtkAudio::audio->ChannelState( i ) ) continue; // puts( "Stealing source!" ); source=chan->source; chan->source=0; break; } return source; } gxtkAudio::gxtkAudio(){ audio=this; alcDevice=alcOpenDevice( 0 ); if( !alcDevice ){ alcDevice=alcOpenDevice( "Generic Hardware" ); if( !alcDevice ) alcDevice=alcOpenDevice( "Generic Software" ); } // bbPrint( "opening openal device" ); if( alcDevice ){ if( (alcContext=alcCreateContext( alcDevice,0 )) ){ if( (alcMakeContextCurrent( alcContext )) ){ //alc all go! }else{ bbPrint( "OpenAl error: alcMakeContextCurrent failed" ); } }else{ bbPrint( "OpenAl error: alcCreateContext failed" ); } }else{ bbPrint( "OpenAl error: alcOpenDevice failed" ); } alDistanceModel( AL_NONE ); memset( channels,0,sizeof(channels) ); channels[32].AL_Source(); } void gxtkAudio::mark(){ for( int i=0;i<33;++i ){ gxtkChannel *chan=&channels[i]; if( chan->state!=0 ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state!=AL_STOPPED ) gc_mark( chan->sample ); } } } int gxtkAudio::Suspend(){ for( int i=0;i<33;++i ){ gxtkChannel *chan=&channels[i]; if( chan->state==1 ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state==AL_PLAYING ) alSourcePause( chan->source ); } } return 0; } int gxtkAudio::Resume(){ for( int i=0;i<33;++i ){ gxtkChannel *chan=&channels[i]; if( chan->state==1 ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state==AL_PAUSED ) alSourcePlay( chan->source ); } } return 0; } bool gxtkAudio::LoadSample__UNSAFE__( gxtkSample *sample,String path ){ int length=0; int channels=0; int format=0; int hertz=0; unsigned char *data=BBGlfwGame::GlfwGame()->LoadAudioData( path,&length,&channels,&format,&hertz ); if( !data ) return false; int al_format=0; if( format==1 && channels==1 ){ al_format=AL_FORMAT_MONO8; }else if( format==1 && channels==2 ){ al_format=AL_FORMAT_STEREO8; }else if( format==2 && channels==1 ){ al_format=AL_FORMAT_MONO16; }else if( format==2 && channels==2 ){ al_format=AL_FORMAT_STEREO16; } int size=length*channels*format; ALuint al_buffer; alGenBuffers( 1,&al_buffer ); alBufferData( al_buffer,al_format,data,size,hertz ); free( data ); sample->SetBuffer( al_buffer ); return true; } gxtkSample *gxtkAudio::LoadSample( String path ){ FlushDiscarded(); gxtkSample *sample=new gxtkSample(); if( !LoadSample__UNSAFE__( sample,path ) ) return 0; return sample; } int gxtkAudio::PlaySample( gxtkSample *sample,int channel,int flags ){ FlushDiscarded(); gxtkChannel *chan=&channels[channel]; if( !chan->AL_Source() ) return -1; alSourceStop( chan->source ); alSourcei( chan->source,AL_BUFFER,sample->al_buffer ); alSourcei( chan->source,AL_LOOPING,flags ? 1 : 0 ); alSourcePlay( chan->source ); gc_assign( chan->sample,sample ); chan->flags=flags; chan->state=1; return 0; } int gxtkAudio::StopChannel( int channel ){ gxtkChannel *chan=&channels[channel]; if( chan->state!=0 ){ alSourceStop( chan->source ); chan->state=0; } return 0; } int gxtkAudio::PauseChannel( int channel ){ gxtkChannel *chan=&channels[channel]; if( chan->state==1 ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state==AL_STOPPED ){ chan->state=0; }else{ alSourcePause( chan->source ); chan->state=2; } } return 0; } int gxtkAudio::ResumeChannel( int channel ){ gxtkChannel *chan=&channels[channel]; if( chan->state==2 ){ alSourcePlay( chan->source ); chan->state=1; } return 0; } int gxtkAudio::ChannelState( int channel ){ gxtkChannel *chan=&channels[channel]; if( chan->state==1 ){ int state=0; alGetSourcei( chan->source,AL_SOURCE_STATE,&state ); if( state==AL_STOPPED ) chan->state=0; } return chan->state; } int gxtkAudio::SetVolume( int channel,float volume ){ gxtkChannel *chan=&channels[channel]; alSourcef( chan->AL_Source(),AL_GAIN,volume ); return 0; } int gxtkAudio::SetPan( int channel,float pan ){ gxtkChannel *chan=&channels[channel]; float x=sinf( pan ),y=0,z=-cosf( pan ); alSource3f( chan->AL_Source(),AL_POSITION,x,y,z ); return 0; } int gxtkAudio::SetRate( int channel,float rate ){ gxtkChannel *chan=&channels[channel]; alSourcef( chan->AL_Source(),AL_PITCH,rate ); return 0; } int gxtkAudio::PlayMusic( String path,int flags ){ StopMusic(); gxtkSample *music=LoadSample( path ); if( !music ) return -1; PlaySample( music,32,flags ); return 0; } int gxtkAudio::StopMusic(){ StopChannel( 32 ); return 0; } int gxtkAudio::PauseMusic(){ PauseChannel( 32 ); return 0; } int gxtkAudio::ResumeMusic(){ ResumeChannel( 32 ); return 0; } int gxtkAudio::MusicState(){ return ChannelState( 32 ); } int gxtkAudio::SetMusicVolume( float volume ){ SetVolume( 32,volume ); return 0; } gxtkSample::gxtkSample(): al_buffer(0){ } gxtkSample::gxtkSample( ALuint buf ): al_buffer(buf){ } gxtkSample::~gxtkSample(){ Discard(); } void gxtkSample::SetBuffer( ALuint buf ){ al_buffer=buf; } int gxtkSample::Discard(){ if( al_buffer ){ discarded.push_back( al_buffer ); al_buffer=0; } return 0; }
23,654
11,438
#ifndef RENDER #define RENDER #include <SFML/Graphics.hpp> #include <vector> class Render { public: Render(); virtual ~Render(); void Background(); void Tile(unsigned int x,unsigned int y,unsigned int id); void Hud(); void Player(); private: sf::Texture Tile1; sf::Texture Tile2; sf::Texture Tile3; sf::Texture background; sf::Sprite backgroundSprite; sf::Texture Sprite1; sf::Texture Sprite2; sf::Sprite playerSprite; sf::RenderTexture hud; sf::Sprite hudSprite; std::vector<std::vector<sf::Sprite*> > SpriteArea; }; #endif // RENDER
569
217
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: RootMotion.BipedReferences #include "RootMotion/BipedReferences.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: RootMotion namespace RootMotion { // Size: 0x2 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: RootMotion.BipedReferences/RootMotion.AutoDetectParams // [TokenAttribute] Offset: FFFFFFFF struct BipedReferences::AutoDetectParams/*, public System::ValueType*/ { public: // public System.Boolean legsParentInSpine // Size: 0x1 // Offset: 0x0 bool legsParentInSpine; // Field size check static_assert(sizeof(bool) == 0x1); // public System.Boolean includeEyes // Size: 0x1 // Offset: 0x1 bool includeEyes; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: AutoDetectParams constexpr AutoDetectParams(bool legsParentInSpine_ = {}, bool includeEyes_ = {}) noexcept : legsParentInSpine{legsParentInSpine_}, includeEyes{includeEyes_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Get instance field reference: public System.Boolean legsParentInSpine bool& dyn_legsParentInSpine(); // Get instance field reference: public System.Boolean includeEyes bool& dyn_includeEyes(); // static public RootMotion.BipedReferences/RootMotion.AutoDetectParams get_Default() // Offset: 0x1D2FDEC static RootMotion::BipedReferences::AutoDetectParams get_Default(); // public System.Void .ctor(System.Boolean legsParentInSpine, System.Boolean includeEyes) // Offset: 0x1D2FDD8 // template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> // ABORTED: conflicts with another method. AutoDetectParams(bool legsParentInSpine, bool includeEyes) }; // RootMotion.BipedReferences/RootMotion.AutoDetectParams #pragma pack(pop) static check_size<sizeof(BipedReferences::AutoDetectParams), 1 + sizeof(bool)> __RootMotion_BipedReferences_AutoDetectParamsSizeCheck; static_assert(sizeof(BipedReferences::AutoDetectParams) == 0x2); } DEFINE_IL2CPP_ARG_TYPE(RootMotion::BipedReferences::AutoDetectParams, "RootMotion", "BipedReferences/AutoDetectParams"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::get_Default // Il2CppName: get_Default template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<RootMotion::BipedReferences::AutoDetectParams (*)()>(&RootMotion::BipedReferences::AutoDetectParams::get_Default)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::BipedReferences::AutoDetectParams), "get_Default", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::AutoDetectParams // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
3,913
1,287
// chess.cpp // @author octopoulo <polluxyz@gmail.com> // @version 2021-05-21 // - wasm implementation, 2x faster than fast chess.js // - FRC support // - emcc --bind -o ../js/chess-wasm.js chess.cpp -s WASM=1 -Wall -s MODULARIZE=1 -O3 --closure 1 #include <emscripten/bind.h> #include <emscripten/val.h> #include <algorithm> #include <iostream> #include <map> #include <regex> #include <set> #include <stdio.h> using namespace emscripten; // specific #define DELETE(x) {if (x) delete x; x = nullptr;} #define DELETE_ARRAY(x) {if (x) delete [] x; x = nullptr;} constexpr int Max(int a, int b) {return (a >= b)? a: b;} constexpr int Min(int a, int b) {return (a <= b)? a: b;} constexpr uint8_t Max(uint8_t a, uint8_t b) {return (a >= b)? a: b;} constexpr uint8_t Min(uint8_t a, uint8_t b) {return (a <= b)? a: b;} // types typedef uint64_t Bitboard; typedef uint64_t Hash; typedef uint32_t Move; typedef uint8_t Piece; typedef uint8_t Square; // defines constexpr Piece BISHOP = 3; constexpr uint8_t BITS_CASTLE = 1; constexpr uint8_t BITS_EN_PASSANT = 2; constexpr uint8_t BLACK = 1; constexpr uint8_t BOUND_EXACT = 0; constexpr uint8_t BOUND_LOWER = 1; constexpr uint8_t BOUND_UPPER = 2; constexpr uint8_t COLOR(Piece piece) {return piece >> 3;} constexpr char COLOR_TEXT(uint8_t color) {return (color == 0)? 'w': 'b';} constexpr Piece COLORIZE(uint8_t color, Piece type) {return type + (color << 3);} #define DEFAULT_POSITION "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" constexpr Square EMPTY = 255; constexpr Square Filer(Square square) {return square & 15;} constexpr Piece KING = 6; constexpr Piece KNIGHT = 2; constexpr uint8_t MAX_DEPTH = 64; constexpr Piece MoveCapture(Move move) {return (move >> 10) & 7;}; constexpr uint8_t MoveFlag(Move move) {return (move >> 13) & 3;}; constexpr Square MoveFrom(Move move) {return (move >> 15) & 127;}; constexpr uint8_t MoveOrder(Move move) {return (move & 1023);}; constexpr Piece MovePromote(Move move) {return (move >> 22) & 7;}; constexpr Square MoveTo(Move move) {return (move >> 25) & 127;}; constexpr Piece NONE = 0; constexpr Piece PAWN = 1; #define PIECE_LOWER " pnbrqk pnbrqk" #define PIECE_NAMES " PNBRQK pnbrqk" #define PIECE_UPPER " PNBRQK PNBRQK" constexpr Piece QUEEN = 5; constexpr Square Rank(Square square) {return square >> 4;} constexpr Square RELATIVE_RANK(int color, int square) {return color? 7 - (square >> 4): (square >> 4);} constexpr Piece ROOK = 4; constexpr int SCORE_INFINITY = 31001; constexpr int SCORE_MATE = 31000; constexpr int SCORE_MATING = 30001; constexpr int SCORE_NONE = 31002; constexpr Square SQUARE_A8 = 0; constexpr Square SQUARE_H1 = 119; constexpr int TT_SIZE = 65536; constexpr Piece TYPE(Piece piece) {return piece & 7;} constexpr uint8_t WHITE = 0; // tables int MOBILITY_LIMITS[] = { 0, 8, // P 32, // N 24, // B 24, // R 24, // Q 1, // K 0, 0, 8, // p 32, // n 24, // b 24, // r 24, // q 1, // k 0, }, MOBILITY_SCORES[] = { 0, 2, // P 4, // N 3, // B 3, // R 2, // Q 1, // K 0, 0, 2, // p 4, // n 3, // b 3, // r 2, // q 1, // k 0, }, PAWN_OFFSETS[2][3] = { {-17, -16, -15}, {17, 16, 15}, }, // attacks + defenses // those values could be optimized automatically PIECE_ATTACKS[16][16] = { // P N B R Q K . . p n b r q k . {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 7, 15, 10, 2, 1, 0, 0, 0, 1, 1, 1, 1, 1, 5, 0}, // P {0, 5, 9, 9, 8, 8, 0, 0, 0, 5, 2, 9, 5, 5, 5, 0}, // N {0, 5, 9, 9, 8, 8, 0, 0, 0, 5, 9, 2, 5, 5, 5, 0}, // B {0, 10, 4, 4, 18, 14, 0, 0, 0, 5, 5, 5, 2, 5, 5, 0}, // R {0, 5, 5, 5, 14, 1, 0, 0, 0, 5, 5, 5, 5, 2, 5, 0}, // Q {0, 5, 9, 9, 9, 9, 0, 0, 0, 10, 5, 5, 5, 0, 0, 0}, // K {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 1, 5, 0, 0, 7, 15, 10, 2, 1, 0, 0}, // p {0, 5, 2, 9, 5, 5, 5, 0, 0, 5, 9, 9, 8, 8, 0, 0}, // n {0, 5, 9, 2, 5, 5, 5, 0, 0, 5, 9, 9, 8, 8, 0, 0}, // b {0, 5, 5, 5, 2, 5, 5, 0, 0, 5, 10, 4, 18, 14, 0, 0}, // r {0, 5, 5, 5, 5, 2, 5, 0, 0, 5, 5, 5, 14, 1, 0, 0}, // q {0, 10, 5, 5, 5, 0, 0, 0, 0, 5, 9, 9, 9, 9, 9, 0}, // k {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, }, // move ordering PIECE_CAPTURES[] = { 0, 80, // P 200, // N 200, // B 360, // R 720, // Q 640, // K 0, 0, 80, // p 200, // n 200, // b 360, // r 720, // q 640, // k 0, }, // for move generation PIECE_OFFSETS[7][8] = { { 0, 0, 0, 0, 0, 0, 0, 0}, { 0, 0, 0, 0, 0, 0, 0, 0}, {-18, -33, -31, -14, 18, 33, 31, 14}, {-17, -15, 17, 15, 0, 0, 0, 0}, {-16, 1, 16, -1, 0, 0, 0, 0}, {-17, -16, -15, 1, 17, 16, 15, -1}, {-17, -16, -15, 1, 17, 16, 15, -1}, }, // move ordering PIECE_ORDERS[] = { 0, 4, // P 1, // N 1, // B 2, // R 3, // Q 5, // K 0, 0, 4, // p 1, // n 1, // b 2, // r 3, // q 5, // k 0, }, // material eval PIECE_SCORES[] = { 0, 161, // P 720, // N 752, // B 1200, // R 2496, // Q 4992, // K 0, 0, 161, // p 720, // n 752, // b 1200, // r 2496, // q 4992, // k 0, }, PROMOTE_SCORES[] = { 0, 0, // P 600, // N 590, // B 1040, // R 2340, // Q 0, // K 0, 0, 0, // p 600, // n 590, // b 1040, // r 2340, // q 0, // k 0, }; // extras std::map<std::string, int> EVAL_MODES = { {"att", 1 + 2 + 4}, {"hce", 1 + 2}, {"mat", 1}, {"mob", 2}, {"nn", 1 + 2 + 4 + 8 + 16 + 32}, {"nul", 0}, {"paw", 1 + 2 + 4 + 8}, {"kin", 1 + 2 + 4 + 16}, }; // piece names for print std::map<char, Piece> PIECES = { {'P', 1}, {'N', 2}, {'B', 3}, {'R', 4}, {'Q', 5}, {'K', 6}, {'p', 9}, {'n', 10}, {'b', 11}, {'r', 12}, {'q', 13}, {'k', 14}, }; std::map<std::string, int> SEARCH_MODES = { {"ab", 2}, {"mm", 1}, {"rnd", 0}, }; // piece-square for move ordering int PIECE_SQUARES[2][8][128] = { // white { {0}, // pawn { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 50, 50, 50, 50, 50, 50, 50, 50, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 25, 25, 25, 25, 25, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 12, 12, 12, 12, 12, 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 15, 20, 20, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 20, 10, 15, 15, 0, 20, 10, 0, 0, 0, 0, 0, 0, 0, 0, 25, 25, 25, 0, 0, 25, 25, 25, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // knight { 0, 20, 25, 25, 25, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 40, 60, 60, 40, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 35, 45, 45, 35, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 32, 40, 40, 32, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 30, 30, 30, 30, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 40, 30, 30, 40, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 20, 25, 28, 28, 28, 25, 25, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // bishop { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // rook { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // queen { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }, // king { 20, 30, 0, 0, 0, 0, 30, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 20, 30, 0, 0, 0, 0, 30, 20, 0, 0, 0, 0, 0, 0, 0, 0, }, {0}, }, // black { {0}, {0}, {0}, {0}, {0}, {0}, {0}, {0}, }, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// struct MoveText { Piece capture; std::string fen; uint8_t flag; Square from; std::string m; int ply; Piece promote; std::string pv; int score; Square to; MoveText() {} MoveText(Piece capture, uint8_t flag, Square from, Piece promote, int score, Square to): capture(capture), flag(flag), from(from), promote(promote), score(score), to(to) { ply = -2; } MoveText(const Move move) { capture = MoveCapture(move); flag = MoveFlag(move); from = MoveFrom(move); ply = -2; promote = MovePromote(move); score = 0; to = MoveTo(move); } }; struct PV { int length; Move moves[MAX_DEPTH]; PV() { length = 0; } }; struct State { Hash hash; // 64 bit Square castling[4]; // 32 Square ep_square; // 8 uint8_t half_moves; // 8 Move move; // 32 }; struct Table { Hash hash; // 64 bit int16_t score; // 16 uint8_t bound; // 8 uint8_t depth; // 8 Move move; // 32 }; // null object MoveText NULL_OBJ = { 0, 0, 0, 0, 0, 0, }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /** * 64bit pseudo random generator * https://en.wikipedia.org/wiki/Xorshift * + WeissNNUE */ Hash xorshift64() { static Hash seed = 1070372ull; seed ^= seed >> 12; seed ^= seed << 25; seed ^= seed >> 27; return seed * 2685821657736338717ull; } /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // chess class class Chess { private: // PRIVATE ////////// uint8_t attacks[16]; int avg_depth; Piece board[128]; Hash board_hash; Square castling[4]; int debug; uint8_t defenses[16]; Square ep_square; int eval_mode; // 0:null, &1:mat, &2:hc2, &4:qui, &8:nn std::string fen; int fen_ply; std::vector<Move> first_moves; // top level moves std::vector<MoveText> first_objs; bool frc; uint8_t half_moves; int hash_mode; bool is_search; Square kings[4]; int materials[2]; int max_depth; int max_extend; int max_nodes; int max_quiesce; int max_time; uint8_t mobilities[16]; int move_id; int move_number; int nodes; int order_mode; Square pawns[8]; Square pieces[2][16]; int ply; State ply_states[128]; int positions[2]; int pv_mode; std::vector<std::string> prev_pv; bool scan_all; int search_mode; // 1:minimax, 2:alpha-beta int sel_depth; Table table[TT_SIZE]; // 16 bytes: hash=8, score=2, bound=1, depth=1, move=4 std::string trace; int tt_adds; int tt_hits; int turn; Hash zobrist[15][128]; bool zobrist_ready; Hash zobrist_side; /** * Add a single move */ void addMove(std::vector<Move> &moves, Piece piece, Square from, Square to, uint8_t flag, Piece promote, Piece value) { int capture = (flag & BITS_EN_PASSANT)? PAWN: (flag & BITS_CASTLE? NONE: TYPE(value)); auto score = (capture | promote)? Max(PIECE_CAPTURES[capture], PIECE_CAPTURES[promote]) - (PIECE_CAPTURES[piece] >> 3) + 50: 0; auto squares = PIECE_SQUARES[COLOR(piece)][TYPE(piece)]; moves.push_back( 100 + squares[to] - squares[from] + (flag & BITS_CASTLE) * 30 + score + (capture << 10) + (flag << 13) + ((from & 127) << 15) + (promote << 22) + ((to & 127) << 25) ); if (!promote) { // TODO: // empty => give bonus for controlling the square, especially if near the other king (or in the center) mobilities[piece] ++; } } /** * Add a pawn move + promote moves */ void addPawnMove(std::vector<Move> &moves, Piece piece, Square from, Square to, uint8_t flag, Piece value, bool only_capture) { auto rank = Rank(to); if (rank == 0 || rank == 7) { if (only_capture) addMove(moves, piece, from, to, flag, QUEEN, value); else for (auto promote = QUEEN; promote >= KNIGHT; promote --) addMove(moves, piece, from, to, flag, promote, value); mobilities[piece] ++; } else addMove(moves, piece, from, to, flag, 0, value); } /** * Add a ply state */ void addState(Move move) { auto &state = ply_states[ply & 127]; state.hash = board_hash; memcpy(state.castling, castling, sizeof(castling)); state.ep_square = ep_square; state.half_moves = half_moves; state.move = move; } /** * Add a top level move */ void addTopMove(Move move, int score, PV *pv) { auto uci = ucifyMove(move), pv_string = uci; if (pv) for (auto i = 0; i < pv->length; i ++) { pv_string += " "; pv_string += ucifyMove(pv->moves[i]); } auto obj = unpackMove(move); obj.m = uci; obj.pv = pv_string; obj.score = score; first_objs.emplace_back(obj); if (debug & 2) std::cout << score << ":" << pv_string << "\n"; } /** * Alpha beta tree search * http://web.archive.org/web/20040427015506/http://brucemo.com/compchess/programming/pvs.htm */ int alphaBeta(int alpha, int beta, int depth, int max_depth, PV *pv) { // extend depth if in check if (max_depth < max_extend && kingAttacked(turn)) max_depth ++; // transposition bool hit = false, is_pv = (alpha != beta - 1); auto entry = findEntry(board_hash, hit); auto idepth = max_depth - depth; if (depth > 0 && hit && entry->depth >= idepth) { nodes ++; tt_hits ++; if (entry->bound & BOUND_EXACT) return entry->score; if ((entry->bound & BOUND_UPPER) && entry->score <= alpha) return alpha; if ((entry->bound & BOUND_LOWER) && entry->score >= beta) return beta; } if (idepth <= 0) { pv->length = 0; int score; if (!max_quiesce) { nodes ++; score = evaluate(); } else score = quiesce(alpha, beta, max_quiesce); updateEntry(entry, board_hash, score, BOUND_EXACT, idepth, 0); move_id ++; return score; } auto alpha0 = alpha, best = -SCORE_INFINITY; Move best_move = 0; PV line; auto moves = createMoves(false); auto num_valid = 0; // top level if (depth == 0) moves = first_moves; else { nodes ++; if (ply >= avg_depth) avg_depth = ply + 1; } // check all moves for (auto &move : moves) { if (!makeMove(move)) continue; num_valid ++; int score; // pv search if (alpha > alpha0 && pv_mode) { score = -alphaBeta(-alpha - 1, -alpha, depth + 1, max_depth, &line); if (score > alpha && score < beta) score = -alphaBeta(-beta, -alpha, depth + 1, max_depth, &line); } else score = -alphaBeta(-beta, -alpha, depth + 1, max_depth, &line); undoMove(); // top level if (depth == 0 && scan_all) { addTopMove(move, score, &line); if (score > best) best = score; continue; } // bound check if (!hash_mode && score >= beta) return beta; if (score > best) { best = score; best_move = move; // update pv if ((score > alpha && is_pv) || (!ply && num_valid == 0)) { pv->length = line.length + 1; pv->moves[0] = move; memcpy(pv->moves + 1, line.moves, line.length * sizeof(Move)); } if (score > alpha) { alpha = score; if (depth == 0) addTopMove(move, score, &line); if (hash_mode && score >= beta) break; } } // checkmate found if (ply > 3 && score >= SCORE_MATING) break; } // mate + stalemate if (!num_valid) return kingAttacked(turn)? -SCORE_MATE + ply: 0; auto bound = (best >= beta)? BOUND_LOWER: ((alpha != alpha0)? BOUND_EXACT: BOUND_UPPER); updateEntry(entry, board_hash, best, bound, idepth, best_move); return best; } /** * Move ordering for alpha-beta * - captures * - castle * - nb/r/q/r/p */ static bool compareMoves(const Move a, const Move b) { return (b & 1023) < (a & 1023); } /** * Uniquely identify ambiguous moves */ std::string disambiguate(Move move, std::vector<Move> &moves) { auto ambiguities = 0; auto from = MoveFrom(move), to = MoveTo(move); auto same_file = 0, same_rank = 0; auto type = board[from]; for (auto &move2 : moves) { auto ambig_from = MoveFrom(move2), ambig_to = MoveTo(move2); // if a move of the same piece type ends on the same to square, // we'll need to add a disambiguator to the algebraic notation if (type == board[ambig_from] && from != ambig_from && to == ambig_to) { ambiguities ++; if (Rank(from) == Rank(ambig_from)) same_rank ++; if (Filer(from) == Filer(ambig_from)) same_file ++; } } if (!ambiguities) return ""; auto an = squareToAn(from, false); if (same_rank > 0 && same_file > 0) return an; else return an.substr((same_file > 0)? 1: 0, 1); } /** * Find an entry in the transposition table */ Table *findEntry(Hash hash, bool &hit) { if (!hash_mode) return nullptr; auto entry = &table[hash % TT_SIZE]; hit = (entry->hash == hash); return entry; } /** * Initialise piece squares */ void initSquares() { for (auto piece = PAWN; piece <= KING; piece ++) { auto bsquares = PIECE_SQUARES[1][piece], wsquares = PIECE_SQUARES[0][piece]; for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) bsquares[((7 - Rank(i)) << 4) + Filer(i)] = wsquares[i]; } } /** * Mini max tree search */ int miniMax(int depth, int max_depth, PV *pv) { // transposition bool hit = false; auto entry = findEntry(board_hash, hit); auto idepth = max_depth - depth; if (depth > 0 && hit && entry->depth >= idepth) { nodes ++; tt_hits ++; return entry->score; } if (depth >= max_depth) { nodes ++; pv->length = 0; return evaluate(); } auto best = -SCORE_INFINITY, best_move = 0; PV line; auto moves = createMoves(false); auto num_valid = 0; // top level if (depth == 0) moves = first_moves; else { nodes ++; if (ply >= avg_depth) avg_depth = ply + 1; } // check all moves for (auto &move : moves) { if (!makeMove(move)) continue; num_valid ++; int score = -miniMax(depth + 1, max_depth, &line); undoMove(); // top level if (depth == 0) addTopMove(move, score, &line); if (score > best) { best = score; best_move = move; // update pv pv->length = line.length + 1; pv->moves[0] = move; memcpy(pv->moves + 1, line.moves, line.length * sizeof(Move)); } // checkmate found if (ply > 3 && score >= SCORE_MATING) break; } // mate + stalemate if (!num_valid) best = kingAttacked(turn)? -SCORE_MATE + ply: 0; updateEntry(entry, board_hash, best, BOUND_EXACT, idepth, best_move); return best; } /** * Get the move list */ std::string moveList() { std::string text; for (auto i = 0 ; i <= ply; i ++) { auto state = ply_states[i & 127]; if (text.size()) text += " "; text += ucifyMove(state.move); } return text; } /** * Null search, used by perft */ void nullSearch(int depth) { if (depth <= 0) { nodes ++; return; } auto moves = createMoves(false); for (auto &move : moves) { if (!makeMove(move)) continue; nullSearch(depth - 1); undoMove(); } } /** * Quiescence search * https://www.chessprogramming.org/Quiescence_Search */ int quiesce(int alpha, int beta, int depth_left) { auto delta = PIECE_SCORES[QUEEN]; nodes ++; auto score = evaluate(); if (depth_left <= 0) return score; if (score >= beta) return beta; if (score + delta < alpha) return alpha; if (score > alpha) alpha = score; auto best = score, futility = best + PIECE_SCORES[PAWN]; if (ply >= sel_depth) sel_depth = ply + 1; auto moves = createMoves(true); for (auto &move : moves) { if (futility + PIECE_SCORES[MoveCapture(move)] <= alpha && (TYPE(board[MoveFrom(move)]) != PAWN || RELATIVE_RANK(turn, MoveTo(move)) <= 5)) continue; if (!makeMove(move)) continue; auto score = -quiesce(-beta, -alpha, depth_left - 1); undoMove(); if (score > best) { best = score; if (score > alpha) { alpha = score; if (score >= beta) break; } } } return best; } /** * Update an entry */ void updateEntry(Table *entry, Hash hash, int score, uint8_t bound, uint8_t depth, Move move) { if (!hash_mode) return; if (hash == entry->hash && depth < entry->depth && bound != BOUND_EXACT) return; entry->hash = hash; entry->score = score; entry->bound = bound; entry->depth = depth; entry->move = move; tt_adds ++; } public: // PUBLIC ///////// Chess() { configure(false, "", 4); clear(); load(DEFAULT_POSITION, false); initSquares(); } ~Chess() { } /** * Convert AN to square * - 'a' = 97 * - '8' = 56 * @param an c2 * @return 98 */ Square anToSquare(std::string an) { if (an.size() < 2) return EMPTY; Square file = an[0] - 'a', rank = '8' - an[1]; return file + (rank << 4); } /** * Check if a square is attacked by a color * @param color attacking color * @param square . * @returns true if the square is attacked */ bool attacked(int color, Square square) { // knight auto target = COLORIZE(color, KNIGHT); for (auto &offset : PIECE_OFFSETS[KNIGHT]) { auto pos = square + offset; if (pos & 0x88) continue; if (board[pos] == target) return true; } // bishop + pawn + rook + queen auto offsets = PIECE_OFFSETS[QUEEN]; for (auto j = 0; j < 8; j ++) { auto offset = offsets[j]; auto pos = square; auto target = BISHOP + (j & 1); for (auto k = 0; ; k ++) { pos += offset; if (pos & 0x88) break; auto value = board[pos]; if (!value) continue; if (COLOR(value) != color) break; auto piece_type = TYPE(value); if (piece_type == QUEEN || piece_type == target) return true; if (k == 0) { if (piece_type == KING) return true; if (target == BISHOP && piece_type == PAWN) { if (color == ((j < 4)? BLACK: WHITE)) return true; } } break; } } return false; } /** * Remove decorators from the SAN * @param san Bxe6+!! * @return clean san Bxe6 */ std::string cleanSan(std::string san) { int i = san.size() - 1; for (; i >= 0 && strchr("+#?!", san[i]); i --) san.erase(i, 1); for (; i >= 0; i --) if (san[i] == '=') { san.erase(i, 1); break; } return san; } /** * Clear the board */ void clear() { memset(attacks, 0, sizeof(attacks)); avg_depth = 0; memset(board, 0, sizeof(board)); board_hash = 0; memset(castling, EMPTY, sizeof(castling)); memset(defenses, 0, sizeof(defenses)); ep_square = EMPTY; fen = ""; fen_ply = -1; half_moves = 0; is_search = false; memset(kings, EMPTY, sizeof(kings)); memset(materials, 0, sizeof(materials)); memset(mobilities, 0, sizeof(mobilities)); move_id = 0; move_number = 1; nodes = 0; memset(pawns, EMPTY, sizeof(pawns)); memset(pieces, 0, sizeof(pieces)); memset(positions, 0, sizeof(positions)); ply = 0; memset(ply_states, 0, sizeof(ply_states)); sel_depth = 0; turn = WHITE; } /** * Configure parameters * @param frc_ * @param options * @param depth this overrides max_depth if > 0 */ void configure(bool frc_, std::string options, int depth) { debug = 0; eval_mode = 1; frc = frc_; hash_mode = 0; max_depth = 4; max_extend = 0; max_nodes = 1e9; max_quiesce = 0; max_time = 0; order_mode = 1; pv_mode = 1; search_mode = 0; // parse the line std::regex re("\\s+"); std::sregex_token_iterator it(options.begin(), options.end(), re, -1); std::sregex_token_iterator reg_end; for (; it != reg_end; it ++) { auto option = it->str(); if (option.size() < 3 || option.at(1) != '=') continue; auto left = option.at(0); auto right = option.substr(2); auto value = std::atoi(right.c_str()); switch (left) { case 'd': max_depth = value; break; case 'D': debug = value; break; case 'e': { auto eit = EVAL_MODES.find(right); if (eit != EVAL_MODES.end()) eval_mode = eit->second; } break; case 'h': hash_mode = value; break; case 'n': max_nodes = value; break; case 'o': order_mode = value; break; case 'p': pv_mode = value; break; case 'q': max_quiesce = value; break; case 's': { auto sit = SEARCH_MODES.find(right); if (sit != SEARCH_MODES.end()) search_mode = sit->second; } break; case 't': max_time = value; break; case 'x': max_extend = value; break; } } if (depth > 0) max_depth = depth; max_extend = Max(max_extend, max_depth); } /** * Create the FEN * @return fen */ std::string createFen() { auto empty = 0; fen = ""; for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) { auto piece = board[i]; if (!piece) empty ++; else { if (empty > 0) { fen += ('0' + empty); empty = 0; } fen += PIECE_NAMES[piece]; } // off board if ((i + 1) & 0x88) { if (empty > 0) fen += ('0' + empty); if (i != SQUARE_H1) fen += '/'; empty = 0; i += 8; } } std::string castle; if (frc) { for (auto &square : castling) if (square != EMPTY) { auto file = Filer(square), rank = Rank(square); if (rank > 0) castle += (file + 'A'); else castle += (file + 'a'); } } else { if (castling[0] != EMPTY) castle += 'K'; if (castling[1] != EMPTY) castle += 'Q'; if (castling[2] != EMPTY) castle += 'k'; if (castling[3] != EMPTY) castle += 'q'; } // empty castling flag? if (castle.empty()) castle = "-"; std::string epflags = (ep_square == EMPTY)? "-": squareToAn(ep_square, false); fen = fen + " " + COLOR_TEXT(turn) + " " + castle + " " + epflags + " " + std::to_string(half_moves) + " " + std::to_string(move_number); return fen; } /** * Create a Fischer Random 960 FEN * http://www.russellcottrell.com/Chess/Chess960.htm * @param index between 0 and 959 */ std::string createFen960(int index) { if (index < 0 || index >= 960) return ""; int i, n1, n2, q; std::string line = " "; line[(index & 3) * 2 + 1] = 'B'; index /= 4; line[(index & 3) * 2] = 'B'; index /= 4; q = index % 6; index /= 6; for (n1 = 0; n1 < 4; n1 ++) { n2 = index + ((3 - n1) * (4 - n1)) / 2 - 5; if (n1 < n2 && n2 > 0 && n2 < 5) break; } // queen for (i = 0; i < 8; i ++) if (line[i] == ' ') { if (!q) { line[i] = 'Q'; break; } q --; } // knights for (i = 0; i < 8; i ++) if (line[i] == ' ') { if (!n1 || !n2) line[i] = 'N'; n1 --; n2 --; } // rook - king - rook std::string castle, castle2; i = 7; for (auto type : "RKR") for (; i >= 0; i --) { if (line[i] == ' ') { line[i] = type; if (type == 'R') { castle += 'A' + i; castle2 += 'a' + i; } break; } } std::string result; for (auto letter : line) result += letter + 'a' - 'A'; result = result + "/pppppppp/8/8/8/8/PPPPPPPP/" + line + " w " + castle + castle2 + " - 0 1"; return result; } /** * Create the moves * @param only_capture * @return moves */ std::vector<Move> createMoves(bool only_capture) { std::vector<Move> moves; auto second_rank = 6 - turn * 5, us = turn, us8 = us << 3, them = us ^ 1; for (auto i = us8; i < us8 + 8; i ++) { attacks[i] = 0; defenses[i] = 0; mobilities[i] = 0; } // 1) collect all moves for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) { // off board if (i & 0x88) { i += 7; continue; } auto piece = board[i]; if (!piece || COLOR(piece) != us) continue; auto piece_type = TYPE(piece); // pawn if (piece_type == PAWN) { auto offsets = PAWN_OFFSETS[us], piece_attacks = PIECE_ATTACKS[piece]; // single square, non-capturing auto square = i + offsets[1]; if (!only_capture) { if (!board[square]) { addPawnMove(moves, piece, i, square, 0, 0, only_capture); // double square square += offsets[1]; if (second_rank == Rank(i) && !board[square]) addMove(moves, piece, i, square, 0, 0, 0); } } // else if (Rank(square) % 7 == 0) // addMove(moves, piece, i, square, 0, QUEEN, 0); // pawn captures for (auto j : {0, 2}) { auto square = i + offsets[j]; if (square & 0x88) continue; auto value = board[square]; if (value) { if (COLOR(value) == them) { addPawnMove(moves, piece, i, square, 0, value, only_capture); attacks[piece] += piece_attacks[value]; } else defenses[piece] += piece_attacks[value]; } // en passant else if (square == ep_square) addPawnMove(moves, piece, i, square, BITS_EN_PASSANT, value, false); } } // other pieces // TODO: separate by piece_type? else { auto offsets = PIECE_OFFSETS[piece_type], piece_attacks = PIECE_ATTACKS[piece]; for (auto j = 0; j < 8; j ++) { auto offset = offsets[j]; auto square = i; if (!offset) break; while (true) { square += offset; if (square & 0x88) break; auto value = board[square]; if (!value) { if (!only_capture) addMove(moves, piece, i, square, 0, 0, 0); } else { if (COLOR(value) == us) defenses[piece] += piece_attacks[value]; else { addMove(moves, piece, i, square, 0, 0, value); attacks[piece] += piece_attacks[value]; } break; } // break if knight or king if (piece_type == KING || piece_type == KNIGHT) break; } } } } // 2) castling if (!only_capture) { Square king = kings[us], pos0 = Rank(king) << 4; // q=0: king side, q=1: queen side for (auto q = 0; q < 2; q ++) { auto rook = castling[(us << 1) + q]; if (rook == EMPTY) continue; auto error = false; Square king_to = pos0 + 6 - (q << 2), rook_to = king_to - 1 + (q << 1), max_king = Max(king, king_to), min_king = Min(king, king_to), max_path = Max(max_king, Max(rook, rook_to)), min_path = Min(min_king, Min(rook, rook_to)); // check that all squares are empty along the path for (auto j = min_path; j <= max_path; j ++) if (j != king && j != rook && board[j]) { error = true; break; } if (error) continue; // check that the king is not attacked for (auto j = min_king; j <= max_king; j ++) if (attacked(them, j)) { error = true; break; } // add castle, always in FRC format if (!error) addMove(moves, COLORIZE(us, KING), king, rook, BITS_CASTLE, 0, 0); } } // move ordering for alpha-beta if (order_mode && is_search) orderMoves(moves); return moves; } /** * Decorate the SAN with + or # */ std::string decorateSan(std::string san) { char last = san[san.size() - 1]; if (last != '+' && last != '#' && kingAttacked(turn)) { auto moves = legalMoves(); san += moves.size()? '+': '#'; } return san; } /** * Evaluate the current position * - eval_mode: 0:nul, 1:mat, 2:hc2, 4:att, 8:paw, 16:kin, 32:nn * - 8/5q2/8/3K4/8/8/8/7k w - - 0 1 KQ vs K * - 8/5r2/8/3K4/8/8/8/7k w - - 0 1 KR vs K * - 8/5n2/8/3K4/8/8/b7/7k w - - 0 1 KNB vs K */ int evaluate() { // 1) draw if (half_moves >= 100) return 0; int mat0 = materials[WHITE], mat1 = materials[BLACK], num_pawn0 = mat0 & 15, num_pawn1 = mat1 & 15, low0 = (!num_pawn0 && mat0 < 6000), low1 = (!num_pawn1 && mat1 < 6000), score = 0; if (low0) { if (low1) return 0; mat0 -= 300; if (num_pawn1) mat1 += 600; } else if (low1) { mat1 -= 300; if (num_pawn0) mat0 += 600; } // 2) material if (eval_mode & 1) { score += mat0 - mat1; // KRR vs KR => KR should not exchange the rook float ratio = mat0 * 1.0f / (mat0 + mat1) - 0.5f; score += int(ratio * 2048 + 0.5f); } // 3) mobility if (eval_mode & 2) { auto factor = (eval_mode & 16)? 1: 2; if (mat0 <= 5000) { auto king = kings[WHITE], king2 = kings[BLACK]; score -= (std::abs(Filer(king) * 2 - 7) + std::abs(Rank(king) * 2 - 7)) * 25; score += (std::abs(Filer(king) - Filer(king2)) + std::abs(Rank(king) - Rank(king2))) * 40; score += mobilities[6] * 15; } else for (auto i = 1; i < 7; i ++) score += Min(mobilities[i] * MOBILITY_SCORES[i], MOBILITY_LIMITS[i]) * factor; if (mat1 <= 5000) { auto king = kings[BLACK], king2 = kings[WHITE]; score += (std::abs(Filer(king) * 2 - 7) + std::abs(Rank(king) * 2 - 7)) * 25; score -= (std::abs(Filer(king) - Filer(king2)) + std::abs(Rank(king) - Rank(king2))) * 40; score -= mobilities[14] * 15; } else for (auto i = 9; i < 15; i ++) score -= Min(mobilities[i] * MOBILITY_SCORES[i], MOBILITY_LIMITS[i]) * factor; } // 4) attacks + defenses if (eval_mode & 4) { for (auto i = 1; i < 7; i ++) score += attacks[i] + defenses[i]; for (auto i = 9; i < 15; i ++) score -= attacks[i] + defenses[i]; } // 5) pawns if (eval_mode & 8) { for (auto square = SQUARE_A8; square <= SQUARE_H1; square ++) { if (square & 0x88) { square += 7; continue; } auto piece = board[square]; if (piece == PAWN) { if (board[square + 1] == PAWN) score += 15; } else if (piece == PAWN + 8) { if (board[square + 1] == PAWN + 8) score -= 15; } } } // 6) king // if (eval_mode & 16) { // } return score * (1 - (turn << 1)); } /** * Evaluate every piece position, done when starting a search */ void evaluatePositions() { memset(attacks, 0, sizeof(attacks)); memset(defenses, 0, sizeof(defenses)); memset(materials, 0, sizeof(materials)); memset(mobilities, 0, sizeof(mobilities)); memset(positions, 0, sizeof(positions)); for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) { if (i & 0x88) { i += 7; continue; } auto piece = board[i]; if (!piece) continue; auto color = COLOR(piece); materials[color] += PIECE_SCORES[piece]; positions[color] += PIECE_SQUARES[color][TYPE(piece)][i]; } } /** * Hash the current board */ void hashBoard() { if (!zobrist_ready) initZobrist(); // 1) board board_hash = 0; for (auto square = SQUARE_A8; square <= SQUARE_H1; square ++) { if (square & 0x88) { square += 7; continue; } auto piece = board[square]; if (piece) board_hash ^= zobrist[piece][square]; } // 2) en passant hashEnPassant(); // 3) castle for (auto id = 0; id < 4; id ++) if (castling[id] != EMPTY) board_hash ^= zobrist[0][id]; // 4) side if (turn) board_hash ^= zobrist_side; } /** * Hash a castle square * @param id 2 * color + 0/1 => 0, 1, 2, 3 */ void hashCastle(int id) { if (castling[id] != EMPTY) { castling[id] = EMPTY; board_hash ^= zobrist[0][id]; } } /** * Hash the en-passant square */ void hashEnPassant() { if (ep_square != EMPTY) board_hash ^= zobrist[0][ep_square]; } /** * Modify the board hash * https://en.wikipedia.org/wiki/Zobrist_hashing * @param {number} square * @param {number} piece */ inline void hashSquare(Square square, Piece piece) { board_hash ^= zobrist[piece][square]; } /** * Initialise the zobrist table * - 0 is used for en passant + castling */ void initZobrist() { auto collision = 0; xorshift64(); zobrist_side = xorshift64(); std::set<Hash> seens; for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) { if (i & 0x88) { i += 7; continue; } for (auto j = 0; j <= 14; j ++) { if (j && !PIECE_ORDERS[j]) continue; auto x = xorshift64(); if (seens.find(x) != seens.end()) { collision ++; break; } zobrist[j][i] = x; seens.insert(x); } } if (collision) std::cout << "init_zobrist:" << collision << "collisions\n"; zobrist_ready = true; } /** * Check if the king is attacked * @param color 0, 1 + special cases: 2, 3 * @return true if king is attacked */ bool kingAttacked(int color) { if (color > 1) color = (color == 2)? turn: turn ^ 1; return attacked(color ^ 1, kings[color]); } /** * Get a list of all legal moves */ std::vector<Move> legalMoves() { auto moves = createMoves(false); std::vector<Move> legals; for (auto &move : moves) { if (!makeMove(move)) continue; undoMove(); legals.push_back(std::move(move)); } return legals; } /** * Load a FEN * @param fen valid or invalid FEN * @param hash must_hash the board? * @return empty on error, and the FEN may be corrected */ std::string load(std::string fen_, bool must_hash) { if (fen_.empty()) return ""; clear(); fen = fen_; int half = 0, move = 0, step = 0, step2 = 0, step3 = 0, square = 0; std::string castle, ep; for (auto i = 0; i < fen.size(); i ++) { auto value = fen[i]; if (value == ' ') { step ++; if (step == 2) step2 = i; else if (step == 3) step3 = i; continue; } switch (step) { // pieces case 0: if (value == '/') square += 8; else if (value >= '1' && value <= '9') square += value - '0'; else { put(PIECES[value], square); square ++; } break; // turn case 1: turn = (value == 'w')? 0: 1; break; // castle case 2: castle += value; break; // en passant case 3: ep += value; break; // 50 moves rule case 4: half = (half * 10) + value - '0'; break; // move # case 5: move = (move * 10) + value - '0'; break; } } ep_square = (ep == "-")? EMPTY: anToSquare(ep); half_moves = half; move_number = Max(move, 1); fen_ply = (move_number << 1) - 3 + turn; ply = 0; auto start = (!turn && !half_moves && move_number == 1 && castle.size() == 4); if (start) frc = (fen_.substr(0, 8) != "rnbqkbnr"); // can detect FRC if castle is not empty if (castle != "-") { auto error = false; for (auto letter : castle) { auto lower = (letter < 'a')? letter + 'a' - 'A': letter, final = (lower == 'k')? 'h': (lower == 'q')? 'a': lower, color = (letter == lower)? 1: 0, square = final - 'a' + ((color? 0: 7) << 4), index = color * 2 + ((square < kings[color])? 1: 0); castling[index] = square; if (start && TYPE(board[square]) != ROOK) error = true; if (final == lower) frc = true; else if (frc && start) error = true; } // fix corrupted FEN (only for the initial board) if (error) { castle = ""; for (auto color = 0; color < 2; color ++) { char file_letter = color? 'a': 'A'; auto king = kings[color]; for (int i = king + 1; Filer(i) <= 7; i ++) if (TYPE(board[i]) == ROOK) { castling[color * 2] = i; castle += file_letter + Filer(i); break; } for (int i = king - 1; Filer(i) >= 0; i --) if (TYPE(board[i]) == ROOK) { castling[color * 2 + 1] = i; castle += file_letter + Filer(i); break; } } fen = fen.substr(0, step2) + " " + castle + fen.substr(step3); frc = true; } } if (must_hash) hashBoard(); else board_hash = 0; return fen; } /** * Make a raw move, no verification is being performed * @returns false if the move is not legal */ bool makeMove(Move move) { // null move auto move_from = MoveFrom(move), move_to = MoveTo(move); if (move_from == move_to) { // addState(move); // ply ++; // turn ^= 1; return false; } auto us = turn, them = us ^ 1; auto capture = MoveCapture(move); auto flag = MoveFlag(move); uint8_t is_castle = (flag & BITS_CASTLE), passant = (flag & BITS_EN_PASSANT)? move_to + 16 - (turn << 5): EMPTY; auto piece_from = board[move_from], piece_to = board[move_to], piece_type = TYPE(piece_from); auto promote = MovePromote(move); auto squares = PIECE_SQUARES[us]; if (promote) promote = COLORIZE(us, promote); // 1) check if move is legal // castle is always legal because the checks were made in makeMove if (!is_castle) { // quick makeMove if (piece_type == KING) kings[us] = move_to; board[move_from] = 0; board[move_to] = promote? promote: piece_from; if (passant) board[passant] = 0; if (kingAttacked(us)) { // quick undoMove if (piece_type == KING) kings[us] = move_from; board[move_from] = piece_from; board[move_to] = piece_to; if (passant) board[passant] = COLORIZE(them, PAWN); return false; } } // 2) move is legal => do all other stuff addState(move); half_moves ++; hashEnPassant(); ep_square = EMPTY; // castle? if (is_castle) { auto q = (move_to < move_from)? 1: 0; auto king = kings[us]; auto king_piece = COLORIZE(us, KING); auto king_to = (Rank(king) << 4) + 6 - (q << 2); auto rook = castling[(us << 1) + q]; auto rook_piece = COLORIZE(us, ROOK); auto rook_to = king_to - 1 + (q << 1); hashSquare(king, king_piece); hashSquare(rook, rook_piece); hashSquare(king_to, king_piece); hashSquare(rook_to, rook_piece); board[king] = 0; board[rook] = 0; board[king_to] = king_piece; board[rook_to] = rook_piece; kings[us] = king_to; hashCastle(us << 1); hashCastle((us << 1) + 1); // score positions[us] += squares[KING][king_to] - squares[KING][king] + squares[ROOK][rook_to] - squares[ROOK][rook] + 30; } else { hashSquare(move_from, piece_from); hashSquare(move_to, piece_to); hashSquare(move_to, promote? promote: piece_from); // remove castling if we capture a rook if (capture) { materials[them] -= PIECE_SCORES[capture]; if (capture == ROOK) { if (move_to == castling[them << 1]) hashCastle(them << 1); else if (move_to == castling[(them << 1) + 1]) hashCastle((them << 1) + 1); } half_moves = 0; } // remove castling if we move a king/rook if (piece_type == KING) { hashCastle(us << 1); hashCastle((us << 1) + 1); } else if (piece_type == ROOK) { if (move_from == castling[us << 1]) hashCastle(us << 1); else if (move_from == castling[(us << 1) + 1]) hashCastle((us << 1) + 1); } // pawn + update 50MR else if (piece_type == PAWN) { if (passant != EMPTY) hashEnPassant(); else if (promote) materials[us] += PROMOTE_SCORES[promote]; // pawn moves 2 squares else if (std::abs(Rank(move_to) - Rank(move_from)) == 2) ep_square = move_to + 16 - (turn << 5); half_moves = 0; } // score auto psquares = squares[piece_type]; positions[us] += psquares[piece_to] - psquares[piece_from]; } ply ++; if (turn == BLACK) move_number ++; turn ^= 1; board_hash ^= zobrist_side; return true; } /** * Try an object move * @param move {from: 23, to: 7, promote: 5} * @param decorate add + # decorators */ MoveText moveObject(MoveText &obj, bool decorate) { auto flag = 0; Move move = 0; auto move_from = obj.from, move_to = obj.to; auto moves = legalMoves(); std::string san; // castle if (move_from == kings[turn]) { auto piece = board[move_to]; // regular notation => change .to to rook position if (!piece) { if (std::abs(Filer(move_from) - Filer(move_to)) == 2) { if (move_to > move_from) move_to ++; else move_to -= 2; } } // frc notation else if (piece == COLORIZE(turn, ROOK)) flag = BITS_CASTLE; } // find an existing match + add the SAN if (flag) { for (auto &move2 : moves) if ((MoveFlag(move2) & flag) && move_to == MoveTo(move2)) { move = move2; san = moveToSan(move, moves); break; } } else for (auto &move2 : moves) { if (move_from != MoveFrom(move2) || move_to != MoveTo(move2)) continue; auto promote = MovePromote(move2); if (promote && obj.promote != promote) continue; move = move2; san = moveToSan(move, moves); break; } // no suitable move? if (move && makeMove(move)) { obj = unpackMove(move); obj.m = decorate? decorateSan(san): san; obj.ply = fen_ply + ply; } return obj; } /** * Try a SAN move * @param text Nxb7, a8=Q * @param decorate add + # decorators * @param sloppy allow sloppy parser */ MoveText moveSan(std::string text, bool decorate, bool sloppy) { auto moves = legalMoves(); auto obj = sanToObject(text, moves, sloppy); if (obj.from != obj.to) { makeMove(packObject(obj)); if (decorate) obj.m = decorateSan(obj.m); } return obj; } /** * Convert a move to SAN * r1bqkbnr/ppp2ppp/2n5/1B1pP3/4P3/8/PPPP2PP/RNBQK1NR b KQkq - 2 4 * 4. ... Nge7 is overly disambiguated because the knight on c6 is pinned * 4. ... Ne7 is technically the valid SAN * @param move * @param moves */ std::string moveToSan(Move move, std::vector<Move> &moves) { auto move_flag = MoveFlag(move), move_from = MoveFrom(move), move_to = MoveTo(move); if (move_flag & BITS_CASTLE) return (move_to > move_from)? "O-O": "O-O-O"; std::string disambiguator = disambiguate(move, moves); auto move_type = TYPE(board[move_from]); std::string output; if (move_type != PAWN) output += PIECE_UPPER[move_type] + disambiguator; if (MoveCapture(move) || (move_flag & BITS_EN_PASSANT)) { if (move_type == PAWN) output += squareToAn(move_from, false)[0]; output += 'x'; } output += squareToAn(move_to, false); auto promote = MovePromote(move); if (promote) { output += '='; output += PIECE_UPPER[promote]; } return output; } /** * Try an UCI move * @param text c2c4, a7a8a * @param decorate add + # decorators */ MoveText moveUci(std::string text, bool decorate) { MoveText obj; obj.from = anToSquare(text.substr(0, 2)); obj.promote = text[4]? TYPE(PIECES[text[4]]): 0; obj.to = anToSquare(text.substr(2, 2)); return moveObject(obj, decorate); } /** * Parse a list of SAN moves + create FEN for each move * @param text c2c4 a7a8a ... * @param sloppy allow sloppy parser */ std::vector<MoveText> multiSan(std::string multi, bool sloppy, bool create_fen) { std::vector<MoveText> result; int prev = 0, size = multi.size(); for (int i = 0; i <= size; i ++) { if (i < size && multi[i] != ' ') continue; if (multi[prev] >= 'A') { auto text = multi.substr(prev, i - prev); auto moves = legalMoves(); auto obj = sanToObject(text, moves, sloppy); if (obj.from == obj.to) break; makeMove(packObject(obj)); obj.fen = create_fen? createFen(): ""; obj.ply = fen_ply + ply; obj.score = 0; result.emplace_back(obj); } prev = i + 1; } return result; } /** * Parse a list of UCI moves + create SAN + FEN for each move * @param text c2c4 a7a8a ... */ std::vector<MoveText> multiUci(std::string multi) { std::vector<MoveText> result; int prev = 0, size = multi.size(); for (int i = 0; i <= size; i ++) { if (i < size && multi[i] != ' ') continue; if (multi[prev] >= 'A') { auto text = multi.substr(prev, i - prev); auto obj = moveUci(text, true); if (obj.from == obj.to || !obj.m.size()) break; obj.fen = createFen(); obj.ply = fen_ply + ply; obj.score = 0; result.emplace_back(obj); } prev = i + 1; } return result; } /** * Move ordering for alpha-beta * - captures * - castle * - nb/r/q/r/p */ void orderMoves(std::vector<Move> &moves) { // use previous PV to reorder the first move if (!move_id && (order_mode & 2) && prev_pv.size() > ply) { auto first = prev_pv[ply]; auto from = anToSquare(first.substr(0, 2)), to = anToSquare(first.substr(2, 2)); auto promote = first[4]? TYPE(PIECES[first[4]]): 0; auto id = 0; for (auto &move : moves) { if (MoveFrom(move) == from && MoveTo(move) == to && MovePromote(move) == promote) moves[id] += 1023 - (move & 1023); id ++; } } std::stable_sort(moves.begin(), moves.end(), compareMoves); } /** * Pack a move object to a number * - 0-9 : order * - 10-12 : capture * - 13-14 : flag * - 15-21 : from * - 22-24 : promote * - 25-31 : to */ Move packObject(MoveText &obj) { return 0 + (obj.capture << 10) + (obj.flag << 13) + ((obj.from & 127) << 15) + (obj.promote << 22) + ((obj.to & 127) << 25); } /** * Get params */ std::vector<int> params() { std::vector<int> result = { max_depth, // 0 eval_mode, // 1 max_nodes, // 2 search_mode, // 3 max_time, // 4 max_quiesce, // 5 }; return result; } /** * Perform perft and divide * @param {string} fen * @param {number} depth * @returns {string} */ std::string perft(std::string fen, int depth) { if (fen.size()) load(fen, false); auto moves = legalMoves(); std::vector<std::string> lines; lines.push_back(std::to_string(1) + "=" +std::to_string(moves.size())); for (auto &move : moves) { makeMove(move); auto prev = nodes; nullSearch(depth - 1); auto delta = nodes - prev; lines.push_back(ucifyMove(move) + ":" + std::to_string(delta)); prev = nodes; undoMove(); } if (depth > 1) lines.push_back(std::to_string(depth) + "=" + std::to_string(nodes)); std::sort(lines.begin(), lines.end()); std::string result; for (auto &line : lines) { if (result.size()) result += " "; result += line; } return result; } /** * Process the move + pv strings * @param move_string list of numbers * @param pv_string previous pv * @param scan_all_ */ void prepareSearch(std::string move_string, std::string pv_string, bool scan_all_) { std::regex re("\\s+"); std::sregex_token_iterator reg_end; first_moves.clear(); if (move_string.size()) { std::sregex_token_iterator it(move_string.begin(), move_string.end(), re, -1); for (; it != reg_end; it ++) { auto move = static_cast<uint32_t>(std::stoul(it->str())); first_moves.push_back(move); } } prev_pv.clear(); if (pv_string.size()) { std::sregex_token_iterator it2(pv_string.begin(), pv_string.end(), re, -1); for (; it2 != reg_end; it2 ++) prev_pv.push_back(it2->str()); } avg_depth = 1; first_objs.clear(); is_search = true; move_id = 0; nodes = 0; scan_all = scan_all_; sel_depth = 0; tt_adds = 0; tt_hits = 0; } /** * Print the board */ std::string print(bool console) { std::string text; for (auto i = SQUARE_A8; i <= SQUARE_H1; i ++) { // off board if (i & 0x88) { i += 7; text += '\n'; continue; } text += PIECE_NAMES[board[i]]; } if (console) std::cout << text; return text; } /** * Put a piece on a square */ void put(Piece piece, Square square) { board[square] = piece; if (TYPE(piece) == KING) kings[COLOR(piece)] = square; else materials[COLOR(piece)] += PIECE_SCORES[piece]; } /** * Reset the board to the default position */ void reset() { frc = false; load(DEFAULT_POSITION, false); } /** * Convert a move from Standard Algebraic Notation (SAN) to 0x88 coordinates * @param san Nf3, Nf3+?! * @param moves list of moves to match the san against * @param sloppy allow sloppy parser */ MoveText sanToObject(std::string san, std::vector<Move> &moves, bool sloppy) { // 1) try exact matching auto clean = cleanSan(san); for (auto &move : moves) if (clean == cleanSan(moveToSan(move, moves))) { auto obj = unpackMove(move); obj.m = san; obj.ply = fen_ply + ply + 1; return obj; } // 2) try sloppy matching if (!sloppy) return NULL_OBJ; auto from_file = EMPTY, from_rank = EMPTY; Piece promote = 0; auto to = EMPTY; Piece type = 0; auto i = clean.size() - 1; if (i < 2) return NULL_OBJ; // analyse backwards if (strchr("bnrqBNRQ", clean[i])) { promote = TYPE(PIECES[clean[i]]); i --; } // to if (clean[i] < '1' || clean[i] > '8') return NULL_OBJ; i --; if (clean[i] < 'a' || clean[i] > 'j') return NULL_OBJ; to = clean[i] - 'a' + (('8' - clean[i + 1]) << 4); i --; // if (i >= 0 && clean[i] == 'x') i --; // from if (i >= 0 && clean[i] >= '1' && clean[i] <= '8') { from_rank = '8' - clean[i]; i --; } if (i >= 0 && clean[i] >= 'a' && clean[i] <= 'j') { from_file = clean[i] - 'a'; i --; } // type type = TYPE(PIECES[clean[i]]); for (auto &move : moves) { auto move_from = MoveFrom(move), move_to = MoveTo(move); if (to == move_to && (!type || type == TYPE(board[move_from])) && (from_file == EMPTY || from_file == Filer(move_from)) && (from_rank == EMPTY || from_rank == Rank(move_from)) && (!promote || promote == MovePromote(move))) { auto obj = unpackMove(move); obj.m = moveToSan(move, moves); obj.ply = fen_ply + ply + 1; return obj; } } return NULL_OBJ; } /** * Main tree search * https://www.chessprogramming.org/Principal_Variation_Search * @param move_string list of numbers * @param pv_string previous pv * @param scan_all_ * @return updated moves */ std::vector<MoveText> search(std::string move_string, std::string pv_string, bool scan_all_) { // 1) prepare search prepareSearch(move_string, pv_string, scan_all_); hashBoard(); evaluatePositions(); // 3) search PV pv; if (search_mode == 1) miniMax(0, max_depth, &pv); else alphaBeta(-SCORE_INFINITY, SCORE_INFINITY, 0, max_depth, &pv); // 4) add unseen moves with a None score if (!scan_all) { std::map<std::string, int> seens; for (auto &obj : first_objs) seens[obj.m] = 1; for (auto &move : first_moves) { auto uci = ucifyMove(move); if (seens.find(uci) != seens.end()) addTopMove(move, -SCORE_NONE, nullptr); } } is_search = false; return first_objs; } /** * Convert a square number to an algebraic notation * - 'a' = 97 * - '8' = 56 * @param square 112 * @param check check the boundaries * @return a1 */ std::string squareToAn(Square square, bool check) { auto file = Filer(square), rank = Rank(square); if (check && (file < 0 || file > 7 || rank < 0 || rank > 7)) return ""; std::string text; text += ('a' + file); text += ('8' - rank); return text; } /** * Get the UCI of a move number */ std::string ucifyMove(Move move) { auto promote = MovePromote(move); auto uci = squareToAn(MoveFrom(move), false) + squareToAn(MoveTo(move), false); if (promote) uci += PIECE_LOWER[promote]; return uci; } /** * Get the UCI of a move * @param {MoveText} obj * @returns {string} */ std::string ucifyObject(MoveText &obj) { auto uci = squareToAn(obj.from, false) + squareToAn(obj.to, false); if (obj.promote) uci += PIECE_LOWER[obj.promote]; return uci; } /** * Undo a move */ bool undoMove() { if (ply <= 0) return false; ply --; auto &state = ply_states[ply & 127]; board_hash = state.hash; memcpy(castling, state.castling, sizeof(castling)); ep_square = state.ep_square; half_moves = state.half_moves; auto move = state.move; turn ^= 1; if (turn == BLACK) move_number --; auto move_capture = MoveCapture(move); auto move_flag = MoveFlag(move); auto move_from = MoveFrom(move), move_to = MoveTo(move); auto promote = MovePromote(move); auto squares = PIECE_SQUARES[turn]; auto us = turn, them = turn ^ 1; if (move_from == move_to) { // null move return true; } // undo castle if (move_flag & BITS_CASTLE) { auto q = (move_to < move_from)? 1: 0; auto king = move_from; auto king_piece = COLORIZE(us, KING); auto king_to = (Rank(king) << 4) + 6 - (q << 2); auto rook_piece = COLORIZE(us, ROOK); auto rook_to = king_to - 1 + (q << 1); board[king_to] = 0; board[rook_to] = 0; board[king] = king_piece; board[move_to] = rook_piece; kings[us] = king; // score positions[us] += squares[KING][king] - squares[KING][king_to] + squares[ROOK][move_to] - squares[ROOK][rook_to] - 30; } else { auto piece = board[move_to]; if (promote) { piece = COLORIZE(us, PAWN); materials[us] -= PROMOTE_SCORES[promote]; } board[move_to] = 0; board[move_from] = piece; auto piece_type = TYPE(piece); if (piece_type == KING) kings[us] = move_from; if (move_flag & BITS_EN_PASSANT) { auto capture = COLORIZE(them, PAWN); Square target = move_to + 16 - (us << 5); board[target] = capture; materials[them] += PIECE_SCORES[PAWN]; } else if (move_capture) { auto capture = COLORIZE(them, move_capture); board[move_to] = capture; materials[them] += PIECE_SCORES[move_capture]; } // score auto psquares = squares[piece_type]; positions[turn] += psquares[move_from] - psquares[move_to]; } return true; } /** * Unpack a move to an object * - 0-9 : order * - 10-12 : capture * - 13-14 : flag * - 15-21 : from * - 22-24 : promote * - 25-31 : to */ MoveText unpackMove(Move move) { return { MoveCapture(move), MoveFlag(move), MoveFrom(move), MovePromote(move), static_cast<int>(move & 1023), MoveTo(move), }; } // EMSCRIPTEN INTERFACES //////////////////////// val em_attacks() { return val(typed_memory_view(16, attacks)); } int em_avgDepth() { return max_depth; } val em_board() { return val(typed_memory_view(128, board)); } int32_t em_boardHash() { return (int32_t)board_hash; } val em_castling() { return val(typed_memory_view(4, castling)); } bool em_checked(int color) { return kingAttacked(color); } val em_defenses() { return val(typed_memory_view(16, defenses)); } std::string em_fen() { return fen; } bool em_frc() { return frc; } std::vector<int> em_hashStats() { return {tt_adds, tt_hits}; } int em_material(int color) { return materials[color]; } val em_mobilities() { return val(typed_memory_view(16, mobilities)); } int em_nodes() { return nodes; } Piece em_piece(std::string text) { if (text.size() != 1) return 0; auto it = PIECES.find(text.at(0)); return (it != PIECES.end())? it->second: 0; } int em_selDepth() { return Max(avg_depth, sel_depth); } std::string em_trace() { return trace; } int em_turn() { return turn; } std::string em_version() { return "20201102"; } }; // BINDING CODE /////////////// EMSCRIPTEN_BINDINGS(chess) { // MOVE BINDINGS value_object<MoveText>("MoveText") .field("capture", &MoveText::capture) .field("flag", &MoveText::flag) .field("from", &MoveText::from) .field("promote", &MoveText::promote) .field("to", &MoveText::to) // .field("fen", &MoveText::fen) .field("m", &MoveText::m) .field("ply", &MoveText::ply) .field("pv", &MoveText::pv) .field("score", &MoveText::score) ; // CHESS BINDINGS class_<Chess>("Chess") .constructor() // .function("anToSquare", &Chess::anToSquare) .function("attacked", &Chess::attacked) .function("attacks", &Chess::em_attacks) .function("avgDepth", &Chess::em_avgDepth) .function("board", &Chess::em_board) .function("boardHash", &Chess::em_boardHash) .function("castling", &Chess::em_castling) .function("checked", &Chess::em_checked) .function("cleanSan", &Chess::cleanSan) .function("clear", &Chess::clear) .function("configure", &Chess::configure) .function("currentFen", &Chess::em_fen) .function("decorateSan", &Chess::decorateSan) .function("defenses", &Chess::em_defenses) .function("evaluate", &Chess::evaluate) .function("fen", &Chess::createFen) .function("fen960", &Chess::createFen960) .function("frc", &Chess::em_frc) .function("hashBoard", &Chess::hashBoard) .function("hashStats", &Chess::em_hashStats) .function("load", &Chess::load) .function("makeMove", &Chess::makeMove) .function("material", &Chess::em_material) .function("mobilities", &Chess::em_mobilities) .function("moveObject", &Chess::moveObject) .function("moves", &Chess::legalMoves) .function("moveSan", &Chess::moveSan) .function("moveToSan", &Chess::moveToSan) .function("moveUci", &Chess::moveUci) .function("multiSan", &Chess::multiSan) .function("multiUci", &Chess::multiUci) .function("nodes", &Chess::em_nodes) .function("order", &Chess::orderMoves) .function("packObject", &Chess::packObject) .function("params", &Chess::params) .function("perft", &Chess::perft) .function("piece", &Chess::em_piece) .function("prepare", &Chess::prepareSearch) .function("print", &Chess::print) .function("put", &Chess::put) .function("reset", &Chess::reset) .function("sanToObject", &Chess::sanToObject) .function("search", &Chess::search) .function("selDepth", &Chess::em_selDepth) .function("squareToAn", &Chess::squareToAn) .function("trace", &Chess::em_trace) .function("turn", &Chess::em_turn) .function("ucifyMove", &Chess::ucifyMove) .function("ucifyObject", &Chess::ucifyObject) .function("undo", &Chess::undoMove) .function("unpackMove", &Chess::unpackMove) .function("version", &Chess::em_version) ; register_vector<int>("vector<int>"); register_vector<Move>("vector<Move>"); register_vector<MoveText>("vector<MoveText>"); }
81,360
28,512
#include "../graphics.h" #include "rect.h" #include <iostream> using namespace std; /********************* Dimensions Struct ********************/ dimensions::dimensions() : width(0), height(0) {} dimensions::dimensions(double w, double h) : width(w), height(h) {} ostream& operator << (ostream& outs, const dimensions &d) { outs << "[" << d.width << ", " << d.height << "]"; return outs; } Rect::Rect() : Shape(), size({0, 0}) {} Rect::Rect(dimensions size) : Shape() { setSize(size); } Rect::Rect(color fill) : Shape(fill), size({0, 0}) {} Rect::Rect(point2D center) : Shape(center), size({0, 0}) {} Rect::Rect(color fill, point2D center) : Shape(fill, center), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha) : Shape(red, green, blue, alpha), size({0, 0}) {} Rect::Rect(double x, double y) : Shape(x, y), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha, double x, double y) : Shape(red, green, blue, alpha, x, y), size({0, 0}) {} Rect::Rect(color fill, double x, double y) : Shape(fill, x, y), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha, point2D center) : Shape(red, green, blue, alpha, center), size({0, 0}) {} Rect::Rect(color fill, dimensions size) : Shape(fill) { setSize(size); } Rect::Rect(point2D center, dimensions size) : Shape(center) { setSize(size); } Rect::Rect(color fill, point2D center, dimensions size) : Shape(fill, center) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, dimensions size) : Shape(red, green, blue, alpha) { setSize(size); } Rect::Rect(double x, double y, dimensions size) : Shape(x, y) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, double x, double y, dimensions size) : Shape(red, green, blue, alpha, x, y) { setSize(size); } Rect::Rect(color fill, double x, double y, dimensions size) : Shape(fill, x, y) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, point2D center, dimensions size) : Shape(red, green, blue, alpha, center) { setSize(size); } dimensions Rect::getSize() const { return size; } double Rect::getWidth() const { return size.width; } double Rect::getHeight() const { return size.height; } double Rect::getLeftX() const { return center.x - (size.width / 2.0); } double Rect::getRightX() const { return center.x + (size.width / 2.0); } double Rect::getTopY() const { return center.y - (size.height / 2.0); } double Rect::getBottomY() const { return center.y + (size.height / 2.0); } void Rect::setSize(dimensions size) { if (size.width >= 0 && size.height >= 0) { this->size = size; } } void Rect::setSize(double width, double height) { setSize({width, height}); } void Rect::setWidth(double width) { setSize({width, size.height}); } void Rect::setHeight(double height) { setSize({size.width, height}); } void Rect::changeSize(double deltaWidth, double deltaHeight) { setSize({size.width + deltaWidth, size.height + deltaHeight}); } void Rect::changeWidth(double delta) { setSize({size.width + delta, size.height}); } void Rect::changeHeight(double delta) { setSize({size.width, size.height + delta}); } // TODO: Implement this method bool Rect::isOverlapping(const Rect &r) const { // There are only two cases when rectangles are *not* overlapping: // 1. when one is to the left of the other // 2. when one is above the other if ( (r.getLeftX() > getLeftX() && r.getRightX() < getRightX()) && (r.getBottomY() < getBottomY() && r.getTopY() > getTopY())) { return true; } // if (r.getLeftX() > getLeftX() && r.getRightX() < getRightX() && r.getTopY() > getTopY()) { // return true; // } return false; } // TODO: Implement this method void Rect::draw() const { // Don't forget to set the color to the fill field glBegin(GL_QUADS); glColor3f( fill.red, fill.green, fill.blue); glVertex2i(getLeftX(), getBottomY()); glVertex2i(getRightX(), getBottomY()); glVertex2i(getRightX(), getTopY()); glVertex2i(getLeftX(), getTopY()); glEnd(); }
4,224
1,470
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ /* ---------------------------------------------------------------------- Contributing author: W. Michael Brown (Intel) ------------------------------------------------------------------------- */ #include "pair_gayberne_intel.h" #include "math_extra_intel.h" #ifdef _LMP_INTEL_OFFLOAD #pragma offload_attribute(push,target(mic)) #endif #include <cmath> #ifdef _LMP_INTEL_OFFLOAD #pragma offload_attribute(pop) #endif #include "atom.h" #include "comm.h" #include "atom_vec_ellipsoid.h" #include "force.h" #include "memory.h" #include "modify.h" #include "neighbor.h" #include "neigh_list.h" #include "neigh_request.h" #include "suffix.h" using namespace LAMMPS_NS; #define FC_PACKED1_T typename ForceConst<flt_t>::fc_packed1 #define FC_PACKED2_T typename ForceConst<flt_t>::fc_packed2 #define FC_PACKED3_T typename ForceConst<flt_t>::fc_packed3 /* ---------------------------------------------------------------------- */ PairGayBerneIntel::PairGayBerneIntel(LAMMPS *lmp) : PairGayBerne(lmp) { suffix_flag |= Suffix::INTEL; respa_enable = 0; } /* ---------------------------------------------------------------------- */ void PairGayBerneIntel::compute(int eflag, int vflag) { if (fix->precision()==FixIntel::PREC_MODE_MIXED) compute<float,double>(eflag, vflag, fix->get_mixed_buffers(), force_const_single); else if (fix->precision()==FixIntel::PREC_MODE_DOUBLE) compute<double,double>(eflag, vflag, fix->get_double_buffers(), force_const_double); else compute<float,float>(eflag, vflag, fix->get_single_buffers(), force_const_single); fix->balance_stamp(); vflag_fdotr = 0; } template <class flt_t, class acc_t> void PairGayBerneIntel::compute(int eflag, int vflag, IntelBuffers<flt_t,acc_t> *buffers, const ForceConst<flt_t> &fc) { if (eflag || vflag) { ev_setup(eflag, vflag); } else evflag = vflag_fdotr = 0; const int inum = list->inum; const int nall = atom->nlocal + atom->nghost; const int nthreads = comm->nthreads; const int host_start = fix->host_start_pair(); const int offload_end = fix->offload_end_pair(); const int ago = neighbor->ago; if (fix->separate_buffers() == 0) { fix->start_watch(TIME_PACK); const AtomVecEllipsoid::Bonus * const bonus = avec->bonus; const int * const ellipsoid = atom->ellipsoid; QUAT_T * _noalias const quat = buffers->get_quat(); #if defined(_OPENMP) #pragma omp parallel default(none) shared(eflag,vflag,buffers,fc) #endif { int ifrom, ito, tid; IP_PRE_omp_range_id_align(ifrom, ito, tid, nall, nthreads, sizeof(ATOM_T)); if (ago != 0) buffers->thr_pack(ifrom,ito,ago); for (int i = ifrom; i < ito; i++) { int qi = ellipsoid[i]; if (qi > -1) { quat[i].w = bonus[qi].quat[0]; quat[i].i = bonus[qi].quat[1]; quat[i].j = bonus[qi].quat[2]; quat[i].k = bonus[qi].quat[3]; } } } quat[nall].w = (flt_t)1.0; quat[nall].i = (flt_t)0.0; quat[nall].j = (flt_t)0.0; quat[nall].k = (flt_t)0.0; fix->stop_watch(TIME_PACK); } if (evflag || vflag_fdotr) { int ovflag = 0; if (vflag_fdotr) ovflag = 2; else if (vflag) ovflag = 1; if (eflag) { if (force->newton_pair) { eval<1,1,1>(1, ovflag, buffers, fc, 0, offload_end); eval<1,1,1>(0, ovflag, buffers, fc, host_start, inum); } else { eval<1,1,0>(1, ovflag, buffers, fc, 0, offload_end); eval<1,1,0>(0, ovflag, buffers, fc, host_start, inum); } } else { if (force->newton_pair) { eval<1,0,1>(1, ovflag, buffers, fc, 0, offload_end); eval<1,0,1>(0, ovflag, buffers, fc, host_start, inum); } else { eval<1,0,0>(1, ovflag, buffers, fc, 0, offload_end); eval<1,0,0>(0, ovflag, buffers, fc, host_start, inum); } } } else { if (force->newton_pair) { eval<0,0,1>(1, 0, buffers, fc, 0, offload_end); eval<0,0,1>(0, 0, buffers, fc, host_start, inum); } else { eval<0,0,0>(1, 0, buffers, fc, 0, offload_end); eval<0,0,0>(0, 0, buffers, fc, host_start, inum); } } } template <int EVFLAG, int EFLAG, int NEWTON_PAIR, class flt_t, class acc_t> void PairGayBerneIntel::eval(const int offload, const int vflag, IntelBuffers<flt_t,acc_t> *buffers, const ForceConst<flt_t> &fc, const int astart, const int aend) { const int inum = aend - astart; if (inum == 0) return; int nlocal, nall, minlocal; fix->get_buffern(offload, nlocal, nall, minlocal); const int ago = neighbor->ago; ATOM_T * _noalias const x = buffers->get_x(offload); QUAT_T * _noalias const quat = buffers->get_quat(offload); const AtomVecEllipsoid::Bonus *bonus = avec->bonus; const int *ellipsoid = atom->ellipsoid; #ifdef _LMP_INTEL_OFFLOAD if (fix->separate_buffers()) { fix->start_watch(TIME_PACK); if (offload) { #pragma omp parallel default(none) \ shared(buffers,nlocal,nall,bonus,ellipsoid) { int ifrom, ito, tid; int nthreads = comm->nthreads; IP_PRE_omp_range_id_align(ifrom, ito, tid, nlocal, nthreads, sizeof(ATOM_T)); if (ago != 0) buffers->thr_pack_cop(ifrom, ito, 0); for (int i = ifrom; i < ito; i++) { int qi = ellipsoid[i]; if (qi > -1) { quat[i].w = bonus[qi].quat[0]; quat[i].i = bonus[qi].quat[1]; quat[i].j = bonus[qi].quat[2]; quat[i].k = bonus[qi].quat[3]; } } int nghost = nall - nlocal; if (nghost) { IP_PRE_omp_range_align(ifrom, ito, tid, nall - nlocal, nthreads, sizeof(ATOM_T)); int offset = 0; ifrom += nlocal; ito += nlocal; if (ago != 0) { offset = fix->offload_min_ghost() - nlocal; buffers->thr_pack_cop(ifrom, ito, offset, ago == 1); } for (int i = ifrom; i < ito; i++) { int qi = ellipsoid[i + offset]; if (qi > -1) { quat[i].w = bonus[qi].quat[0]; quat[i].i = bonus[qi].quat[1]; quat[i].j = bonus[qi].quat[2]; quat[i].k = bonus[qi].quat[3]; } } } } } else { if (ago != 0) buffers->thr_pack_host(fix->host_min_local(), nlocal, 0); for (int i = fix->host_min_local(); i < nlocal; i++) { int qi = ellipsoid[i]; if (qi > -1) { quat[i].w = bonus[qi].quat[0]; quat[i].i = bonus[qi].quat[1]; quat[i].j = bonus[qi].quat[2]; quat[i].k = bonus[qi].quat[3]; } } int offset = fix->host_min_ghost() - nlocal; if (ago != 0) buffers->thr_pack_host(nlocal, nall, offset); for (int i = nlocal; i < nall; i++) { int qi = ellipsoid[i + offset]; if (qi > -1) { quat[i].w = bonus[qi].quat[0]; quat[i].i = bonus[qi].quat[1]; quat[i].j = bonus[qi].quat[2]; quat[i].k = bonus[qi].quat[3]; } } } fix->stop_watch(TIME_PACK); } #endif // const int * _noalias const ilist = list->ilist; const int * _noalias const numneigh = list->numneigh; const int * _noalias const cnumneigh = buffers->cnumneigh(list); const int * _noalias const firstneigh = buffers->firstneigh(list); const flt_t * _noalias const special_lj = fc.special_lj; const FC_PACKED1_T * _noalias const ijc = fc.ijc[0]; const FC_PACKED2_T * _noalias const lj34 = fc.lj34[0]; const FC_PACKED3_T * _noalias const ic = fc.ic; const flt_t mu = fc.mu; const flt_t gamma = fc.gamma; const flt_t upsilon = fc.upsilon; flt_t * const rsq_formi = fc.rsq_form[0]; flt_t * const delx_formi = fc.delx_form[0]; flt_t * const dely_formi = fc.dely_form[0]; flt_t * const delz_formi = fc.delz_form[0]; int * const jtype_formi = fc.jtype_form[0]; int * const jlist_formi = fc.jlist_form[0]; const int ntypes = atom->ntypes + 1; const int eatom = this->eflag_atom; // Determine how much data to transfer int x_size, q_size, f_stride, ev_size, separate_flag; IP_PRE_get_transfern(ago, NEWTON_PAIR, EVFLAG, EFLAG, vflag, buffers, offload, fix, separate_flag, x_size, q_size, ev_size, f_stride); int tc; FORCE_T * _noalias f_start; acc_t * _noalias ev_global; IP_PRE_get_buffers(offload, buffers, fix, tc, f_start, ev_global); const int max_nbors = _max_nbors; const int nthreads = tc; int pad = 1; if (offload) { if (INTEL_MIC_NBOR_PAD > 1) pad = INTEL_MIC_NBOR_PAD * sizeof(float) / sizeof(flt_t); } else { if (INTEL_NBOR_PAD > 1) pad = INTEL_NBOR_PAD * sizeof(float) / sizeof(flt_t); } const int pad_width = pad; #ifdef _LMP_INTEL_OFFLOAD int *overflow = fix->get_off_overflow_flag(); double *timer_compute = fix->off_watch_pair(); if (offload) fix->start_watch(TIME_OFFLOAD_LATENCY); #pragma offload target(mic:_cop) if(offload) \ in(special_lj:length(0) alloc_if(0) free_if(0)) \ in(ijc,lj34,ic:length(0) alloc_if(0) free_if(0)) \ in(rsq_formi, delx_formi, dely_formi: length(0) alloc_if(0) free_if(0)) \ in(delz_formi, jtype_formi, jlist_formi: length(0) alloc_if(0) free_if(0))\ in(firstneigh:length(0) alloc_if(0) free_if(0)) \ in(cnumneigh:length(0) alloc_if(0) free_if(0)) \ in(numneigh:length(0) alloc_if(0) free_if(0)) \ in(x:length(x_size) alloc_if(0) free_if(0)) \ in(quat:length(nall+1) alloc_if(0) free_if(0)) \ in(overflow:length(0) alloc_if(0) free_if(0)) \ in(nthreads,inum,nall,ntypes,vflag,eatom,minlocal,separate_flag) \ in(astart,nlocal,f_stride,max_nbors,mu,gamma,upsilon,offload,pad_width) \ out(f_start:length(f_stride) alloc_if(0) free_if(0)) \ out(ev_global:length(ev_size) alloc_if(0) free_if(0)) \ out(timer_compute:length(1) alloc_if(0) free_if(0)) \ signal(f_start) #endif { #if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD) *timer_compute=MIC_Wtime(); #endif #ifdef _LMP_INTEL_OFFLOAD if (separate_flag) { if (separate_flag < 3) { int all_local = nlocal; int ghost_min = overflow[LMP_GHOST_MIN]; nlocal = overflow[LMP_LOCAL_MAX] + 1; int nghost = overflow[LMP_GHOST_MAX] + 1 - ghost_min; if (nghost < 0) nghost = 0; nall = nlocal + nghost; separate_flag--; int flength; if (NEWTON_PAIR) flength = nall; else flength = nlocal; IP_PRE_get_stride(f_stride, flength, sizeof(FORCE_T), separate_flag); if (nghost) { if (nlocal < all_local || ghost_min > all_local) { memmove(x + nlocal, x + ghost_min, (nall - nlocal) * sizeof(ATOM_T)); memmove(quat + nlocal, quat + ghost_min, (nall - nlocal) * sizeof(QUAT_T)); } } } x[nall].x = (flt_t)INTEL_BIGP; x[nall].y = (flt_t)INTEL_BIGP; x[nall].z = (flt_t)INTEL_BIGP; quat[nall].w = (flt_t)1.0; quat[nall].i = (flt_t)0.0; quat[nall].j = (flt_t)0.0; quat[nall].k = (flt_t)0.0; } #endif acc_t oevdwl, ov0, ov1, ov2, ov3, ov4, ov5; if (EVFLAG) { oevdwl = (acc_t)0.0; if (vflag) ov0 = ov1 = ov2 = ov3 = ov4 = ov5 = (acc_t)0.0; } // loop over neighbors of my atoms #if defined(_OPENMP) #pragma omp parallel default(none) \ shared(f_start,f_stride,nlocal,nall,minlocal) \ reduction(+:oevdwl,ov0,ov1,ov2,ov3,ov4,ov5) #endif { int iifrom, iito, tid; IP_PRE_omp_range_id(iifrom, iito, tid, inum, nthreads); iifrom += astart; iito += astart; FORCE_T * _noalias const f = f_start - minlocal * 2 + (tid * f_stride); memset(f + minlocal * 2, 0, f_stride * sizeof(FORCE_T)); flt_t * _noalias const rsq_form = rsq_formi + tid * max_nbors; flt_t * _noalias const delx_form = delx_formi + tid * max_nbors; flt_t * _noalias const dely_form = dely_formi + tid * max_nbors; flt_t * _noalias const delz_form = delz_formi + tid * max_nbors; int * _noalias const jtype_form = jtype_formi + tid * max_nbors; int * _noalias const jlist_form = jlist_formi + tid * max_nbors; int ierror = 0; for (int i = iifrom; i < iito; ++i) { // const int i = ilist[ii]; const int itype = x[i].w; const int ptr_off = itype * ntypes; const FC_PACKED1_T * _noalias const ijci = ijc + ptr_off; const FC_PACKED2_T * _noalias const lj34i = lj34 + ptr_off; const int * _noalias const jlist = firstneigh + cnumneigh[i]; const int jnum = numneigh[i]; const flt_t xtmp = x[i].x; const flt_t ytmp = x[i].y; const flt_t ztmp = x[i].z; flt_t a1_0, a1_1, a1_2, a1_3, a1_4, a1_5, a1_6, a1_7, a1_8; flt_t b1_0, b1_1, b1_2, b1_3, b1_4, b1_5, b1_6, b1_7, b1_8; flt_t g1_0, g1_1, g1_2, g1_3, g1_4, g1_5, g1_6, g1_7, g1_8; if (ijci[itype].form == ELLIPSE_ELLIPSE) { flt_t temp_0,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6,temp_7,temp_8; ME_quat_to_mat_trans(quat[i],a1); ME_diag_times3(ic[itype].well,a1,temp); ME_transpose_times3(a1,temp,b1); ME_diag_times3(ic[itype].shape2,a1,temp); ME_transpose_times3(a1,temp,g1); } acc_t fxtmp, fytmp, fztmp, fwtmp, t1tmp, t2tmp, t3tmp; acc_t sevdwl, sv0, sv1, sv2, sv3, sv4, sv5; fxtmp = fytmp = fztmp = t1tmp = t2tmp = t3tmp = (acc_t)0.0; if (EVFLAG) { if (EFLAG) fwtmp = sevdwl = (acc_t)0.0; if (vflag==1) sv0 = sv1 = sv2 = sv3 = sv4 = sv5 = (acc_t)0.0; } bool multiple_forms = false; int packed_j = 0; for (int jj = 0; jj < jnum; jj++) { int jm = jlist[jj]; int j = jm & NEIGHMASK; const int jtype = x[j].w; if (ijci[jtype].form == ELLIPSE_ELLIPSE) { flt_t delx = x[j].x-xtmp; flt_t dely = x[j].y-ytmp; flt_t delz = x[j].z-ztmp; flt_t rsq = delx * delx + dely * dely + delz * delz; if (rsq < ijci[jtype].cutsq) { rsq_form[packed_j] = rsq; delx_form[packed_j] = delx; dely_form[packed_j] = dely; delz_form[packed_j] = delz; jtype_form[packed_j] = jtype; jlist_form[packed_j] = jm; packed_j++; } } else multiple_forms = true; } const int edge = (packed_j % pad_width); if (edge) { const int packed_end = packed_j + (pad_width - edge); #if defined(LMP_SIMD_COMPILER) #pragma loop_count min=1, max=15, avg=8 #endif for ( ; packed_j < packed_end; packed_j++) jlist_form[packed_j] = nall; } // ------------------------------------------------------------- #ifdef INTEL_V512 __assume(packed_j % INTEL_VECTOR_WIDTH == 0); __assume(packed_j % 8 == 0); __assume(packed_j % INTEL_MIC_VECTOR_WIDTH == 0); #endif #if defined(LMP_SIMD_COMPILER) #pragma vector aligned #pragma simd reduction(+:fxtmp,fytmp,fztmp,fwtmp,t1tmp,t2tmp,t3tmp, \ sevdwl,sv0,sv1,sv2,sv3,sv4,sv5) #endif for (int jj = 0; jj < packed_j; jj++) { flt_t a2_0, a2_1, a2_2, a2_3, a2_4, a2_5, a2_6, a2_7, a2_8; flt_t b2_0, b2_1, b2_2, b2_3, b2_4, b2_5, b2_6, b2_7, b2_8; flt_t g2_0, g2_1, g2_2, g2_3, g2_4, g2_5, g2_6, g2_7, g2_8; flt_t temp_0,temp_1,temp_2,temp_3,temp_4,temp_5,temp_6,temp_7,temp_8; flt_t fforce_0, fforce_1, fforce_2, ttor_0, ttor_1, ttor_2; flt_t rtor_0, rtor_1, rtor_2; const int sbindex = jlist_form[jj] >> SBBITS & 3; const int j = jlist_form[jj] & NEIGHMASK; flt_t factor_lj = special_lj[sbindex]; const int jtype = jtype_form[jj]; const flt_t sigma = ijci[jtype].sigma; const flt_t epsilon = ijci[jtype].epsilon; const flt_t shape2_0 = ic[jtype].shape2[0]; const flt_t shape2_1 = ic[jtype].shape2[1]; const flt_t shape2_2 = ic[jtype].shape2[2]; flt_t one_eng, evdwl; ME_quat_to_mat_trans(quat[j], a2); ME_diag_times3(ic[jtype].well, a2, temp); ME_transpose_times3(a2, temp, b2); ME_diag_times3a(shape2, a2, temp); ME_transpose_times3(a2, temp, g2); flt_t tempv_0, tempv_1, tempv_2, tempv2_0, tempv2_1, tempv2_2; flt_t temp1, temp2, temp3; flt_t r12hat_0, r12hat_1, r12hat_2; ME_normalize3(delx_form[jj], dely_form[jj], delz_form[jj], r12hat); flt_t r = sqrt(rsq_form[jj]); // compute distance of closest approach flt_t g12_0, g12_1, g12_2, g12_3, g12_4, g12_5, g12_6, g12_7, g12_8; ME_plus3(g1, g2, g12); flt_t kappa_0, kappa_1, kappa_2; ME_mldivide3(g12, delx_form[jj], dely_form[jj], delz_form[jj], kappa, ierror); // tempv = G12^-1*r12hat flt_t inv_r = (flt_t)1.0 / r; tempv_0 = kappa_0 * inv_r; tempv_1 = kappa_1 * inv_r; tempv_2 = kappa_2 * inv_r; flt_t sigma12 = ME_dot3(r12hat, tempv); sigma12 = std::pow((flt_t)0.5 * sigma12,(flt_t) - 0.5); flt_t h12 = r - sigma12; // energy // compute u_r flt_t varrho = sigma / (h12 + gamma * sigma); flt_t varrho6 = std::pow(varrho, (flt_t)6.0); flt_t varrho12 = varrho6 * varrho6; flt_t u_r = (flt_t)4.0 * epsilon * (varrho12 - varrho6); // compute eta_12 flt_t eta = (flt_t)2.0 * ijci[jtype].lshape; flt_t det_g12 = ME_det3(g12); eta = std::pow(eta / det_g12, upsilon); // compute chi_12 flt_t b12_0, b12_1, b12_2, b12_3, b12_4, b12_5, b12_6, b12_7, b12_8; flt_t iota_0, iota_1, iota_2; ME_plus3(b1, b2, b12); ME_mldivide3(b12, delx_form[jj], dely_form[jj], delz_form[jj], iota, ierror); // tempv = G12^-1*r12hat tempv_0 = iota_0 * inv_r; tempv_1 = iota_1 * inv_r; tempv_2 = iota_2 * inv_r; flt_t chi = ME_dot3(r12hat, tempv); chi = std::pow(chi * (flt_t)2.0, mu); // force // compute dUr/dr temp1 = ((flt_t)2.0 * varrho12 * varrho - varrho6 * varrho) / sigma; temp1 = temp1 * (flt_t)24.0 * epsilon; flt_t u_slj = temp1 * std::pow(sigma12, (flt_t)3.0) * (flt_t)0.5; flt_t dUr_0, dUr_1, dUr_2; temp2 = ME_dot3(kappa, r12hat); flt_t uslj_rsq = u_slj / rsq_form[jj]; dUr_0 = temp1 * r12hat_0 + uslj_rsq * (kappa_0 - temp2 * r12hat_0); dUr_1 = temp1 * r12hat_1 + uslj_rsq * (kappa_1 - temp2 * r12hat_1); dUr_2 = temp1 * r12hat_2 + uslj_rsq * (kappa_2 - temp2 * r12hat_2); // compute dChi_12/dr flt_t dchi_0, dchi_1, dchi_2; temp1 = ME_dot3(iota, r12hat); temp2 = (flt_t)-4.0 / rsq_form[jj] * mu * std::pow(chi, (mu - (flt_t)1.0) / mu); dchi_0 = temp2 * (iota_0 - temp1 * r12hat_0); dchi_1 = temp2 * (iota_1 - temp1 * r12hat_1); dchi_2 = temp2 * (iota_2 - temp1 * r12hat_2); temp1 = -eta * u_r; temp2 = eta * chi; fforce_0 = temp1 * dchi_0 - temp2 * dUr_0; fforce_1 = temp1 * dchi_1 - temp2 * dUr_1; fforce_2 = temp1 * dchi_2 - temp2 * dUr_2; // torque for particle 1 and 2 // compute dUr tempv_0 = -uslj_rsq * kappa_0; tempv_1 = -uslj_rsq * kappa_1; tempv_2 = -uslj_rsq * kappa_2; ME_vecmat(kappa, g1, tempv2); ME_cross3(tempv, tempv2, dUr); flt_t dUr2_0, dUr2_1, dUr2_2; if (NEWTON_PAIR || j < nlocal) { ME_vecmat(kappa, g2, tempv2); ME_cross3(tempv, tempv2, dUr2); } // compute d_chi ME_vecmat(iota, b1, tempv); ME_cross3(tempv, iota, dchi); temp1 = (flt_t)-4.0 / rsq_form[jj]; dchi_0 *= temp1; dchi_1 *= temp1; dchi_2 *= temp1; flt_t dchi2_0, dchi2_1, dchi2_2; if (NEWTON_PAIR || j < nlocal) { ME_vecmat(iota, b2, tempv); ME_cross3(tempv, iota, dchi2); dchi2_0 *= temp1; dchi2_1 *= temp1; dchi2_2 *= temp1; } // compute d_eta flt_t deta_0, deta_1, deta_2; deta_0 = deta_1 = deta_2 = (flt_t)0.0; ME_compute_eta_torque(g12, a1, shape2, temp); temp1 = -eta * upsilon; tempv_0 = temp1 * temp_0; tempv_1 = temp1 * temp_1; tempv_2 = temp1 * temp_2; ME_mv0_cross3(a1, tempv, tempv2); deta_0 += tempv2_0; deta_1 += tempv2_1; deta_2 += tempv2_2; tempv_0 = temp1 * temp_3; tempv_1 = temp1 * temp_4; tempv_2 = temp1 * temp_5; ME_mv1_cross3(a1, tempv, tempv2); deta_0 += tempv2_0; deta_1 += tempv2_1; deta_2 += tempv2_2; tempv_0 = temp1 * temp_6; tempv_1 = temp1 * temp_7; tempv_2 = temp1 * temp_8; ME_mv2_cross3(a1, tempv, tempv2); deta_0 += tempv2_0; deta_1 += tempv2_1; deta_2 += tempv2_2; // compute d_eta for particle 2 flt_t deta2_0, deta2_1, deta2_2; if (NEWTON_PAIR || j < nlocal) { deta2_0 = deta2_1 = deta2_2 = (flt_t)0.0; ME_compute_eta_torque(g12, a2, shape2, temp); tempv_0 = temp1 * temp_0; tempv_1 = temp1 * temp_1; tempv_2 = temp1 * temp_2; ME_mv0_cross3(a2, tempv, tempv2); deta2_0 += tempv2_0; deta2_1 += tempv2_1; deta2_2 += tempv2_2; tempv_0 = temp1 * temp_3; tempv_1 = temp1 * temp_4; tempv_2 = temp1 * temp_5; ME_mv1_cross3(a2, tempv, tempv2); deta2_0 += tempv2_0; deta2_1 += tempv2_1; deta2_2 += tempv2_2; tempv_0 = temp1 * temp_6; tempv_1 = temp1 * temp_7; tempv_2 = temp1 * temp_8; ME_mv2_cross3(a2, tempv, tempv2); deta2_0 += tempv2_0; deta2_1 += tempv2_1; deta2_2 += tempv2_2; } // torque temp1 = u_r * eta; temp2 = u_r * chi; temp3 = chi * eta; ttor_0 = (temp1 * dchi_0 + temp2 * deta_0 + temp3 * dUr_0) * (flt_t)-1.0; ttor_1 = (temp1 * dchi_1 + temp2 * deta_1 + temp3 * dUr_1) * (flt_t)-1.0; ttor_2 = (temp1 * dchi_2 + temp2 * deta_2 + temp3 * dUr_2) * (flt_t)-1.0; if (NEWTON_PAIR || j < nlocal) { rtor_0 = (temp1 * dchi2_0 + temp2 * deta2_0 + temp3 * dUr2_0) * (flt_t)-1.0; rtor_1 = (temp1 * dchi2_1 + temp2 * deta2_1 + temp3 * dUr2_1) * (flt_t)-1.0; rtor_2 = (temp1 * dchi2_2 + temp2 * deta2_2 + temp3 * dUr2_2) * (flt_t)-1.0; } one_eng = temp1 * chi; #ifndef INTEL_VMASK if (jlist_form[jj] == nall) { one_eng = (flt_t)0.0; fforce_0 = 0.0; fforce_1 = 0.0; fforce_2 = 0.0; ttor_0 = 0.0; ttor_1 = 0.0; ttor_2 = 0.0; rtor_0 = 0.0; rtor_1 = 0.0; rtor_2 = 0.0; } #endif fforce_0 *= factor_lj; fforce_1 *= factor_lj; fforce_2 *= factor_lj; ttor_0 *= factor_lj; ttor_1 *= factor_lj; ttor_2 *= factor_lj; #ifdef INTEL_VMASK if (jlist_form[jj] < nall) { #endif fxtmp += fforce_0; fytmp += fforce_1; fztmp += fforce_2; t1tmp += ttor_0; t2tmp += ttor_1; t3tmp += ttor_2; if (NEWTON_PAIR || j < nlocal) { rtor_0 *= factor_lj; rtor_1 *= factor_lj; rtor_2 *= factor_lj; int jp = j * 2; f[jp].x -= fforce_0; f[jp].y -= fforce_1; f[jp].z -= fforce_2; jp++; f[jp].x += rtor_0; f[jp].y += rtor_1; f[jp].z += rtor_2; } if (EVFLAG) { flt_t ev_pre = (flt_t)0.0; if (NEWTON_PAIR || i < nlocal) ev_pre += (flt_t)0.5; if (NEWTON_PAIR || j < nlocal) ev_pre += (flt_t)0.5; if (EFLAG) { evdwl = factor_lj * one_eng; sevdwl += ev_pre * evdwl; if (eatom) { if (NEWTON_PAIR || i < nlocal) fwtmp += (flt_t)0.5 * evdwl; if (NEWTON_PAIR || j < nlocal) f[j*2].w += (flt_t)0.5 * evdwl; } } if (vflag == 1) { ev_pre *= (flt_t)-1.0; sv0 += ev_pre * delx_form[jj] * fforce_0; sv1 += ev_pre * dely_form[jj] * fforce_1; sv2 += ev_pre * delz_form[jj] * fforce_2; sv3 += ev_pre * delx_form[jj] * fforce_1; sv4 += ev_pre * delx_form[jj] * fforce_2; sv5 += ev_pre * dely_form[jj] * fforce_2; } } // EVFLAG #ifdef INTEL_VMASK } #endif } // for jj // ------------------------------------------------------------- if (multiple_forms) ierror = 2; int ip = i * 2; f[ip].x += fxtmp; f[ip].y += fytmp; f[ip].z += fztmp; ip++; f[ip].x += t1tmp; f[ip].y += t2tmp; f[ip].z += t3tmp; if (EVFLAG) { if (EFLAG) { if (eatom) f[i * 2].w += fwtmp; oevdwl += sevdwl; } if (vflag == 1) { ov0 += sv0; ov1 += sv1; ov2 += sv2; ov3 += sv3; ov4 += sv4; ov5 += sv5; } } } // for i int o_range; if (NEWTON_PAIR) o_range = nall; else o_range = nlocal; if (offload == 0) o_range -= minlocal; IP_PRE_omp_range_align(iifrom, iito, tid, o_range, nthreads, sizeof(FORCE_T)); const int two_iito = iito * 2; acc_t *facc = &(f_start[0].x); const int sto = two_iito * 4; const int fst4 = f_stride * 4; #if defined(_OPENMP) #pragma omp barrier #endif int t_off = f_stride; if (EFLAG && eatom) { for (int t = 1; t < nthreads; t++) { #if defined(LMP_SIMD_COMPILER) #pragma vector nontemporal #pragma novector #endif for (int n = iifrom * 2; n < two_iito; n++) { f_start[n].x += f_start[n + t_off].x; f_start[n].y += f_start[n + t_off].y; f_start[n].z += f_start[n + t_off].z; f_start[n].w += f_start[n + t_off].w; } t_off += f_stride; } } else { for (int t = 1; t < nthreads; t++) { #if defined(LMP_SIMD_COMPILER) #pragma vector nontemporal #pragma novector #endif for (int n = iifrom * 2; n < two_iito; n++) { f_start[n].x += f_start[n + t_off].x; f_start[n].y += f_start[n + t_off].y; f_start[n].z += f_start[n + t_off].z; } t_off += f_stride; } } if (EVFLAG) { if (vflag==2) { const ATOM_T * _noalias const xo = x + minlocal; #if defined(LMP_SIMD_COMPILER) #pragma vector nontemporal #pragma novector #endif for (int n = iifrom; n < iito; n++) { const int nt2 = n * 2; ov0 += f_start[nt2].x * xo[n].x; ov1 += f_start[nt2].y * xo[n].y; ov2 += f_start[nt2].z * xo[n].z; ov3 += f_start[nt2].y * xo[n].x; ov4 += f_start[nt2].z * xo[n].x; ov5 += f_start[nt2].z * xo[n].y; } } } if (ierror) f_start[1].w = ierror; } // omp if (EVFLAG) { if (EFLAG) { ev_global[0] = oevdwl; ev_global[1] = (acc_t)0.0; } if (vflag) { ev_global[2] = ov0; ev_global[3] = ov1; ev_global[4] = ov2; ev_global[5] = ov3; ev_global[6] = ov4; ev_global[7] = ov5; } } #if defined(__MIC__) && defined(_LMP_INTEL_OFFLOAD) *timer_compute = MIC_Wtime() - *timer_compute; #endif } // offload if (offload) fix->stop_watch(TIME_OFFLOAD_LATENCY); else fix->stop_watch(TIME_HOST_PAIR); if (EVFLAG) fix->add_result_array(f_start, ev_global, offload, eatom, 0, 2); else fix->add_result_array(f_start, 0, offload, 0, 0, 2); } /* ---------------------------------------------------------------------- */ void PairGayBerneIntel::init_style() { PairGayBerne::init_style(); neighbor->requests[neighbor->nrequest-1]->intel = 1; int ifix = modify->find_fix("package_intel"); if (ifix < 0) error->all(FLERR, "The 'package intel' command is required for /intel styles"); fix = static_cast<FixIntel *>(modify->fix[ifix]); fix->pair_init_check(); #ifdef _LMP_INTEL_OFFLOAD if (force->newton_pair) fix->set_offload_noghost(1); _cop = fix->coprocessor_number(); #endif if (fix->precision() == FixIntel::PREC_MODE_MIXED) pack_force_const(force_const_single, fix->get_mixed_buffers()); else if (fix->precision() == FixIntel::PREC_MODE_DOUBLE) pack_force_const(force_const_double, fix->get_double_buffers()); else pack_force_const(force_const_single, fix->get_single_buffers()); } /* ---------------------------------------------------------------------- */ template <class flt_t, class acc_t> void PairGayBerneIntel::pack_force_const(ForceConst<flt_t> &fc, IntelBuffers<flt_t,acc_t> *buffers) { int tp1 = atom->ntypes + 1; _max_nbors = buffers->get_max_nbors(); int mthreads = comm->nthreads; if (mthreads < buffers->get_off_threads()) mthreads = buffers->get_off_threads(); fc.set_ntypes(tp1, _max_nbors, mthreads, memory, _cop); buffers->set_ntypes(tp1); flt_t **cutneighsq = buffers->get_cutneighsq(); // Repeat cutsq calculation because done after call to init_style double cut, cutneigh; for (int i = 1; i <= atom->ntypes; i++) { for (int j = i; j <= atom->ntypes; j++) { if (setflag[i][j] != 0 || (setflag[i][i] != 0 && setflag[j][j] != 0)) { cut = init_one(i,j); cutneigh = cut + neighbor->skin; cutsq[i][j] = cutsq[j][i] = cut*cut; cutneighsq[i][j] = cutneighsq[j][i] = cutneigh * cutneigh; } } } for (int i = 0; i < 4; i++) { fc.special_lj[i] = force->special_lj[i]; fc.special_lj[0] = 1.0; } fc.gamma = gamma; fc.upsilon = upsilon; fc.mu = mu; for (int i = 0; i < tp1; i++) { for (int j = 0; j < tp1; j++) { fc.ijc[i][j].lj1 = lj1[i][j]; fc.ijc[i][j].lj2 = lj2[i][j]; fc.ijc[i][j].cutsq = cutsq[i][j]; fc.ijc[i][j].offset = offset[i][j]; fc.ijc[i][j].sigma = sigma[i][j]; fc.ijc[i][j].epsilon = epsilon[i][j]; fc.ijc[i][j].form = form[i][j]; fc.ijc[i][j].lshape = lshape[i] * lshape[j]; fc.lj34[i][j].lj3 = lj3[i][j]; fc.lj34[i][j].lj4 = lj4[i][j]; } for (int j = 0; j < 4; j++) { fc.ic[i].shape2[j] = shape2[i][j]; fc.ic[i].well[j] = well[i][j]; } } #ifdef _LMP_INTEL_OFFLOAD if (_cop < 0) return; flt_t * special_lj = fc.special_lj; FC_PACKED1_T *oijc = fc.ijc[0]; FC_PACKED2_T *olj34 = fc.lj34[0]; FC_PACKED3_T *oic = fc.ic; flt_t * ocutneighsq = cutneighsq[0]; int tp1sq = tp1 * tp1; if (oijc != NULL && oic != NULL) { #pragma offload_transfer target(mic:_cop) \ in(special_lj: length(4) alloc_if(0) free_if(0)) \ in(oijc,olj34: length(tp1sq) alloc_if(0) free_if(0)) \ in(oic: length(tp1) alloc_if(0) free_if(0)) \ in(ocutneighsq: length(tp1sq)) } #endif } /* ---------------------------------------------------------------------- */ template <class flt_t> void PairGayBerneIntel::ForceConst<flt_t>::set_ntypes(const int ntypes, const int one_length, const int nthreads, Memory *memory, const int cop) { if (ntypes != _ntypes) { if (_ntypes > 0) { fc_packed3 *oic = ic; #ifdef _LMP_INTEL_OFFLOAD flt_t * ospecial_lj = special_lj; fc_packed1 *oijc = ijc[0]; fc_packed2 *olj34 = lj34[0]; flt_t * orsq_form = rsq_form[0]; flt_t * odelx_form = delx_form[0]; flt_t * odely_form = dely_form[0]; flt_t * odelz_form = delz_form[0]; int * ojtype_form = jtype_form[0]; int * ojlist_form = jlist_form[0]; if (ospecial_lj != NULL && oijc != NULL && olj34 != NULL && orsq_form != NULL && odelx_form != NULL && odely_form != NULL && odelz_form != NULL && ojtype_form != NULL && ojlist_form != NULL && _cop >= 0) { #pragma offload_transfer target(mic:_cop) \ nocopy(ospecial_lj, oijc, olj34, oic: alloc_if(0) free_if(1)) \ nocopy(orsq_form, odelx_form, odely_form: alloc_if(0) free_if(1)) \ nocopy(odelz_form, ojtype_form, ojlist_form: alloc_if(0) free_if(1)) } #endif _memory->destroy(oic); _memory->destroy(ijc); _memory->destroy(lj34); _memory->destroy(rsq_form); _memory->destroy(delx_form); _memory->destroy(dely_form); _memory->destroy(delz_form); _memory->destroy(jtype_form); _memory->destroy(jlist_form); } if (ntypes > 0) { _cop = cop; memory->create(ijc, ntypes, ntypes, "fc.ijc"); memory->create(lj34, ntypes, ntypes, "fc.lj34"); memory->create(ic, ntypes, "fc.ic"); memory->create(rsq_form, nthreads, one_length, "rsq_form"); memory->create(delx_form, nthreads, one_length, "delx_form"); memory->create(dely_form, nthreads, one_length, "dely_form"); memory->create(delz_form, nthreads, one_length, "delz_form"); memory->create(jtype_form, nthreads, one_length, "jtype_form"); memory->create(jlist_form, nthreads, one_length, "jlist_form"); for (int zn = 0; zn < nthreads; zn++) for (int zo = 0; zo < one_length; zo++) { rsq_form[zn][zo] = 10.0; delx_form[zn][zo] = 10.0; dely_form[zn][zo] = 10.0; delz_form[zn][zo] = 10.0; jtype_form[zn][zo] = 1; jlist_form[zn][zo] = 0; } #ifdef _LMP_INTEL_OFFLOAD flt_t * ospecial_lj = special_lj; fc_packed1 *oijc = ijc[0]; fc_packed2 *olj34 = lj34[0]; fc_packed3 *oic = ic; flt_t * orsq_form = rsq_form[0]; flt_t * odelx_form = delx_form[0]; flt_t * odely_form = dely_form[0]; flt_t * odelz_form = delz_form[0]; int * ojtype_form = jtype_form[0]; int * ojlist_form = jlist_form[0]; int off_onel = one_length * nthreads; int tp1sq = ntypes*ntypes; if (ospecial_lj != NULL && oijc != NULL && olj34 != NULL && oic != NULL && orsq_form != NULL && odelx_form != NULL && odely_form != NULL && odelz_form != NULL && ojtype_form !=NULL && ojlist_form !=NULL && cop >= 0) { #pragma offload_transfer target(mic:cop) \ nocopy(ospecial_lj: length(4) alloc_if(1) free_if(0)) \ nocopy(oijc,olj34: length(tp1sq) alloc_if(1) free_if(0)) \ nocopy(oic: length(ntypes) alloc_if(1) free_if(0)) \ in(orsq_form: length(off_onel) alloc_if(1) free_if(0)) \ in(odelx_form: length(off_onel) alloc_if(1) free_if(0)) \ in(odely_form: length(off_onel) alloc_if(1) free_if(0)) \ in(odelz_form: length(off_onel) alloc_if(1) free_if(0)) \ in(ojtype_form: length(off_onel) alloc_if(1) free_if(0)) \ in(ojlist_form: length(off_onel) alloc_if(1) free_if(0)) } #endif } } _ntypes = ntypes; _memory = memory; }
35,873
15,738
#include <cinttypes> #include <cstring> #include <cstdio> #include <iostream> #include "mem/Pem.hpp" #include "med/MedCommon.hpp" #include "med/MedException.hpp" #include "med/ScanParser.hpp" #include "med/MedTypes.hpp" #include "med/MemOperator.hpp" Pem::Pem(size_t size, MemIO* memio) : Mem(size) { this->memio = memio; scanType = ScanType::Unknown; } Pem::Pem(Address addr, size_t size, MemIO* memio) : Mem(size) { this->memio = memio; setAddress(addr); scanType = ScanType::Unknown; } Pem::~Pem() {} string Pem::bytesToString(Byte* buf, const string& scanType) { if (scanType == SCAN_TYPE_CUSTOM) { return memToString(buf, SCAN_TYPE_INT_8); } return memToString(buf, scanType); } string Pem::getValue(const string& scanType) { MemPtr pem = memio->read(address, size); if (!pem) { return "(invalid)"; } Byte* buf = pem->getData(); return Pem::bytesToString(buf, scanType); } string Pem::getValue() { string scanType = getScanType(); return getValue(scanType); } BytePtr Pem::getValuePtr(int n) { int size = n > 0 ? n : this->size; BytePtr buf(new Byte[size]); MemPtr pem = memio->read(address, size); if (!pem) { return NULL; } memcpy(buf.get(), pem->getData(), size); return buf; } string Pem::getScanType() { return scanTypeToString(scanType); } SizedBytes Pem::stringToBytes(const string& value, const string& scanType) { // If scanType is string, it will just copy all if (scanType == SCAN_TYPE_STRING) { int size = MAX_STRING_SIZE; Byte* buf = new Byte[size]; sprintf((char*)buf, "%s", value.c_str()); int length = strlen((char*)buf); BytePtr data(new Byte[length]); memcpy(data.get(), buf, length); delete[] buf; return SizedBytes(data, length); } else { // Allows parse comma vector<string> tokens = ScanParser::getValues(value); int size = scanTypeToSize(stringToScanType(scanType)); BytePtr data(new Byte[size * tokens.size()]); Byte* pointer = data.get(); for (size_t i = 0; i < tokens.size(); i++) { stringToMemory(tokens[i], stringToScanType(scanType), pointer); pointer += size; } return SizedBytes(data, size * tokens.size()); } } void Pem::setValue(const string& value, const string& scanType) { SizedBytes buffer = Pem::stringToBytes(value, scanType); Byte* bytes = buffer.getBytes(); int size = buffer.getSize(); MemPtr mem(new Mem(size)); mem->setAddress(address); memcpy(mem->getData(), bytes, size); memio->write(address, mem, size); } void Pem::setScanType(const string& scanType) { this->scanType = stringToScanType(scanType); size_t newSize; Byte* newData; Byte* temp; if (this->scanType == ScanType::String) { newSize = MAX_STRING_SIZE; newData = new Byte[newSize]; } else { newSize = scanTypeToSize(this->scanType); newData = new Byte[newSize]; } temp = data; data = newData; size = newSize; delete[] temp; } MemIO* Pem::getMemIO() { return memio; } void Pem::rememberValue(const string& value, const string& scanType) { rememberedValue = Pem::stringToBytes(value, scanType); } void Pem::rememberValue(Byte* value, size_t size) { rememberedValue = SizedBytes(value, size); } string Pem::recallValue(const string& scanType) { if (rememberedValue.isEmpty()) { return ""; } return Pem::bytesToString(rememberedValue.getBytes(), scanType); } Byte* Pem::recallValuePtr() { return rememberedValue.getBytes(); } PemPtr Pem::convertToPemPtr(MemPtr mem, MemIO* memio) { return PemPtr(new Pem(mem->getAddress(), mem->getSize(), memio)); }
3,597
1,302
#include <bits/stdc++.h> using namespace std; class XOR_GAUSSIAN { // XOR Gaussian Elimination public: static const int MAXN = 32767, MAXM = 64; char mtx[MAXN][MAXM+1], varX[MAXN]; int compute(int n, int m) { int row = 0, col = 0, arb = 0; int equ = n, var = m; while (row < equ && col < var) { int c = row; for (int i = row; i < equ; i++) if (mtx[i][col]) c = i; for (int i = 0; i <= var; i++) swap(mtx[c][i], mtx[row][i]); if (mtx[row][col] == 0) { col++, arb++; continue; } for (int i = 0; i < equ; i++) { if (i == row || mtx[i][col] == 0) continue; for (int j = var; j >= 0; j--) mtx[i][j] ^= mtx[row][j]; } row++, col++; } return row; memset(varX, 0, sizeof(varX)); for (int i = 0, j; i < equ; i++) { if (mtx[i][var] == 0) continue; for (j = 0; j < var && mtx[i][j] == 0; j++); varX[j] = mtx[i][var]; } } } gauss; int main() { int n, m, x; while (scanf("%d %d", &n, &m) == 2) { for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { scanf("%d", &x); gauss.mtx[i][j] = x&1; } } int rank = gauss.compute(n, m); if (rank < m) puts("S"); else { if (n > rank) puts("N"); // for zeroes else puts("S"); } } return 0; } /* 4 3 0 0 1 0 0 1 0 0 1 0 1 0 2 3 1 2 3 5 6 7 3 3 3 2 1 6 5 4 4 4 4 4 3 9 4 7 4 4 4 2 7 2 2 2 1 4 2 0 0 0 1 1 0 1 1 */
1,488
818
#include "Turtle.h" #define LLOG(x) // RLOG(x) #define LDUMP(x) // RDUMP(x) #define LTIMING(x) namespace Upp { static bool sQuit; // Ctrl::IsEndSession() would be much better to use had it been implemented. static BiVector<String> sEventQueue; Point ReadPoint(CParser& p) { Point pt; pt.x = p.ReadInt(); pt.y = p.ReadInt(); return pt; } bool TurtleServer::ProcessEvent(bool *quit) { if(!IsWaitingEvent()) return false; while(sEventQueue.GetCount() >= 2 && *sEventQueue[0] == 'M' && *sEventQueue[1] == 'M') sEventQueue.DropHead(); // MouseMove compression String event = sEventQueue[0]; sEventQueue.DropHead(); LLOG("Processing event " << event); CParser p(event); try { if(p.Id("i")) { ResetImageCache(); } else if(p.Id("R")) { Resize(p); } else if(p.Id("M")) { MouseMove(p); } else if(p.Id("W")) { MouseWheel(p); } else if(p.Id("I")) { mousein = true; } else if(p.Id("O")) { mousebuttons = 0; mousein = false; } else if(p.Id("D")) { MouseButton(Ctrl::DOWN, p); } else if(p.Id("U")) { MouseButton(Ctrl::UP, p); } else if(p.Id("K")) { KeyDown(event, p); } else if(p.Id("k")) { KeyUp(event, p); } else if(p.Id("C")) { KeyPress(event, p); } } catch(const CParser::Error&) { LLOG("ProcessEvent() -> Parser error"); } return true; } void TurtleServer::WaitEvent(int ms) { websocket.Do(); SocketWaitEvent we; websocket.AddTo(we); we.Wait(ms); } bool TurtleServer::IsWaitingEvent() { websocket.Do(); String s = websocket.Receive(); if(websocket.IsClosed()) { Ctrl::EndSession(); sQuit = true; // Ugly.. return false; } if(s.GetCount() == 0) return sEventQueue.GetCount(); LLOG("Received data " << s); StringStream ss(s); while(!ss.IsEof()) { String s = ss.GetLine(); CParser p(s); try { if(p.Id("S")) { uint32 l = p.ReadNumber(); uint32 h = p.ReadNumber(); recieved_update_serial = MAKEQWORD(l, h); stat_client_ms = p.ReadNumber(); } else sEventQueue.AddTail(s); } catch(const CParser::Error&) { LLOG("IsWaitingEvent() -> Parser error."); } } if(recieved_update_serial == serial_0) { serial_0 = 0; stat_roundtrip_ms = msecs() - serial_time0; serial_time0 = Null; } if(websocket.IsError()) LLOG("ERROR: " << websocket.GetErrorDesc()); return sEventQueue.GetCount(); } void TurtleServer::SyncClient() { while(recieved_update_serial < update_serial && !sQuit) { Ctrl::GuiSleep(10); IsWaitingEvent(); } } void TurtleServer::MouseButton(dword event, CParser& p) { auto MaxDistance = [](Point a, Point b) -> int { return IsNull(a) ? INT_MAX : max(abs(a.x - b.x), abs(a.y - b.y)); }; static int64 sMouseDownTime; static Point sMouseDownPos; int bt = p.ReadInt(); Point pt = ReadPoint(p); int64 tm = p.ReadInt64(); dword down = (dword) event == Ctrl::DOWN; dword bt2 = decode(bt, 0, (1 << 0), 2, (1 << 1), (1 << 2)); mousebuttons = (mousebuttons & ~bt2) | ((dword)-(int32)down & bt2); // Toggles button flags. if(event == Ctrl::DOWN) { if(MaxDistance(sMouseDownPos, pt) < GUI_DragDistance() && tm - sMouseDownTime < 800) { event = Ctrl::DOUBLE; sMouseDownTime = 0; } else { sMouseDownPos = pt; sMouseDownTime = tm; } } ReadModifierKeys(p); Ctrl::DoMouseFB(decode(bt, 0, Ctrl::LEFT, 2, Ctrl::RIGHT, Ctrl::MIDDLE) | event, pt, 0); } void TurtleServer::MouseWheel(CParser& p) { double w = p.ReadDouble(); Point pt = ReadPoint(p); ReadModifierKeys(p); Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, pt, w < 0 ? 120 : -120); } void TurtleServer::MouseMove(CParser& p) { Point pt = ReadPoint(p); ReadModifierKeys(p); Ctrl::DoMouseFB(Ctrl::MOUSEMOVE, pt, 0); } void TurtleServer::KeyDown(const String& event, CParser& p) { int count = 1; int code = p.ReadInt(); int which = p.ReadInt(); for(;;) { if(sEventQueue.GetCount() && sEventQueue[0] == event) { // Chrome autorepeat sEventQueue.DropHead(); count++; } else if(sEventQueue.GetCount() >= 2 && *sEventQueue[0] == 'C' && sEventQueue[1] == event) { // Firefox autorepeat String h = sEventQueue[0]; sEventQueue.DropHead(); sEventQueue.DropHead(); sEventQueue.AddHead(h); count++; } else break; } ReadModifierKeys(p); Ctrl::DoKeyFB(TranslateWebKeyToK(which), count); } void TurtleServer::KeyUp(const String& event, CParser& p) { int code = p.ReadInt(); int which = p.ReadInt(); ReadModifierKeys(p); Ctrl::DoKeyFB(TranslateWebKeyToK(which) | K_KEYUP, 1); } void TurtleServer::KeyPress(const String& event, CParser& p) { int code = p.ReadInt(); int which = p.ReadInt(); ReadModifierKeys(p); while(sEventQueue.GetCount() && sEventQueue[0] == event) // 'K_'s are not there anymore sEventQueue.DropHead(); if(which && !GetAlt() && !GetCtrl() && findarg(which, 0x09, 0x0D, 0x20) < 0) Ctrl::DoKeyFB(which, 1); } void TurtleServer::Resize(CParser& p) { desktopsize = ReadPoint(p); SetCanvasSize(desktopsize); Ctrl::SetDesktopSize(desktopsize); } void TurtleServer::SetMouseCursor(const Image& image) { int64 q = image.GetAuxData(); if(q) { Put8(STD_CURSORIMAGE); Put8(clamp((int)q, 1, 16)); } else { Point pt = image.GetHotSpot(); String h; h << "url('data:image/png;base64," << Base64Encode(PNGEncoder().SaveString(image)) << "') " << pt.x << ' ' << pt.y << ", default"; Put8(SETCURSORIMAGE); Put16(0); // TODO: Cursor cache Put(h); Put8(MOUSECURSOR); Put16(0); // TODO: Cursor cache } } }
5,538
2,564
namespace phoenix { struct pPopupMenu : public pObject { PopupMenu& popupMenu; void append(Action& action); void remove(Action& action); void setVisible(); pPopupMenu(PopupMenu& popupMenu) : pObject(popupMenu), popupMenu(popupMenu) {} void constructor(); void destructor(); }; }
297
100
// simple dp #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define fi first #define se second #define pb push_back #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", 1.0*clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector<string> vs; const int INF = 1e9; const int MAXN = 500 + 9; const int MOD = 1e9 + 7; bool used[MAXN]; int n, m; ll dp[MAXN][MAXN]; void precalc() { for(int i = 1; i < MAXN; i++) { dp[i][0] = dp[0][i] = 1; } for(int i = 1; i < MAXN; i++) { for(int j = 1; j < MAXN; j++) { dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD; } } } void solve() { cin >> n >> m; cout << dp[n][m] << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else //freopen("xxx.in", "r", stdin); //freopen("xxx.out", "w", stdout); #endif precalc(); int t; cin >> t; while(t--) { solve(); } return 0; }
1,270
589
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/sparse_fill_empty_rows_op.h" #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRows<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, const Tensor& default_value_t, const Tensor& indices_t, const Tensor& values_t, const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done) { (void)done; // Unused (only used in GPU implementation) const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<Tindex>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<Tindex>(); const Tindex N = indices_t.shape().dim_size(0); const Tindex dense_rows = dense_shape(0); bool* empty_row_indicator = nullptr; if (context->output_required(kEmptyRowIndicatorOutput)) { Tensor* empty_row_indicator_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); empty_row_indicator = empty_row_indicator_t->vec<bool>().data(); } Tindex* reverse_index_map = nullptr; if (context->output_required(kReverseIndexMapOutput)) { Tensor* reverse_index_map_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output( kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); reverse_index_map = reverse_index_map_t->vec<Tindex>().data(); } int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { if (N != 0) { return errors::InvalidArgument( "Received SparseTensor with dense_shape[0] = 0 but " "indices.shape[0] = ", N); } Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return Status::OK(); } bool rows_are_ordered = true; Tindex last_indices_row = 0; std::vector<Tindex> csr_offset(dense_rows, 0); for (int i = 0; i < N; ++i) { const Tindex row = indices(i, 0); if (row < 0 || row >= dense_rows) { return errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows); } ++csr_offset[row]; rows_are_ordered = rows_are_ordered & (row >= last_indices_row); last_indices_row = row; } bool all_rows_full = true; for (int row = 0; row < dense_rows; ++row) { // csr_offset here describes the number of elements in this dense row bool row_empty = (csr_offset[row] == 0); if (empty_row_indicator) { empty_row_indicator[row] = row_empty; } all_rows_full = all_rows_full & !row_empty; // In filled version, each row has at least one element. csr_offset[row] = std::max(csr_offset[row], Tindex{1}); // Update csr_offset to represent the number of elements up to and // including dense_row + 1: // csr_offset(0) == #{elements of row 0} // csr_offset(1) == #{elements of row 1} + #{elements of row 0} // .. // csr_offset(i) == starting index for elements in row i + 1. if (row > 0) { csr_offset[row] += csr_offset[row - 1]; } } if (all_rows_full && rows_are_ordered) { context->set_output(kOutputIndicesOutput, indices_t); context->set_output(kOutputValuesOutput, values_t); if (reverse_index_map) { for (Tindex i = 0; i < N; ++i) { reverse_index_map[i] = i; } } } else { Tensor* output_indices_t; const Tindex N_full = csr_offset[dense_rows - 1]; TensorShape output_indices_shape({N_full, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<Tindex>(); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); std::vector<Tindex> filled_count(dense_rows, 0); // Fill in values for rows that are not missing for (Tindex i = 0; i < N; ++i) { const Tindex row = indices(i, 0); Tindex& offset = filled_count[row]; const Tindex output_i = ((row == 0) ? 0 : csr_offset[row - 1]) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. if (reverse_index_map) { reverse_index_map[i] = output_i; } } // Fill in values for rows that are missing for (Tindex row = 0; row < dense_rows; ++row) { const Tindex row_count = filled_count[row]; if (row_count == 0) { // We haven't filled this row const Tindex starting_index = (row == 0) ? 0 : csr_offset[row - 1]; // Remaining index values were set to zero already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; for (Tindex col = 1; col < rank; ++col) { output_indices(starting_index, col) = 0; } output_values(starting_index) = default_value; } } } return Status::OK(); } }; } // namespace functor namespace { template <typename Device, typename T, typename Tindex> void SparseFillEmptyRowsOpImpl(OpKernelContext* context, AsyncOpKernel::DoneCallback done = nullptr) { // Note that setting this empty lambda as the default parameter value directly // can cause strange compiler/linker errors, so we do it like this instead. if (!done) { done = [] {}; } const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString()), done); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString()), done); // TODO(ebrevdo): add shape checks between values, indices, // Also add check that dense rank > 0. OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0, errors::InvalidArgument("Dense shape cannot be empty."), done); using FunctorType = functor::SparseFillEmptyRows<Device, T, Tindex>; OP_REQUIRES_OK_ASYNC(context, FunctorType()(context, default_value_t, indices_t, values_t, dense_shape_t, done), done); } } // namespace template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { SparseFillEmptyRowsOpImpl<Device, T, Tindex>(context); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_##D) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_ALL_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // The GPU implementation is async because it requires waiting for a // host->device memcpy before the output is allocated (similar to // SegmentSumGPUOp). template <typename T, typename Tindex> class SparseFillEmptyRowsGPUOp : public AsyncOpKernel { public: explicit SparseFillEmptyRowsGPUOp(OpKernelConstruction* context) : AsyncOpKernel(context) {} void ComputeAsync(OpKernelContext* context, DoneCallback done) override { SparseFillEmptyRowsOpImpl<GPUDevice, T, Tindex>(context, done); } }; #define REGISTER_KERNELS(T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_GPU) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGPUOp<T, Tindex>) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRows<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, const Tensor& default_value_t, \ const Tensor& indices_t, const Tensor& values_t, \ const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done); \ extern template struct SparseFillEmptyRows<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_POD_TYPES(DECLARE_GPU_SPEC_INT64) #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_KERNELS_TINDEX(T) REGISTER_KERNELS(T, int64) TF_CALL_POD_TYPES(REGISTER_KERNELS_TINDEX) #undef REGISTER_KERNELS_TINDEX #undef REGISTER_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRowsGrad<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, typename TTypes<Tindex>::ConstVec reverse_index_map, typename TTypes<T>::ConstVec grad_values, typename TTypes<T>::Vec d_values, typename TTypes<T>::Scalar d_default_value) { const CPUDevice& device = context->eigen_device<CPUDevice>(); const Tindex N = reverse_index_map.dimension(0); const Tindex N_full = grad_values.dimension(0); T& d_default_value_scalar = d_default_value(); d_default_value_scalar = T(); Tensor visited_t; TF_RETURN_IF_ERROR( context->allocate_temp(DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(device) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. int64 reverse_index = reverse_index_map(i); if (reverse_index < 0 || reverse_index >= N_full) { return errors::InvalidArgument( "Elements in reverse index must be in [0, ", N_full, ") but got ", reverse_index); } d_values(i) = grad_values(reverse_index); visited(reverse_index) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value_scalar += grad_values(j); } } return Status::OK(); } }; } // namespace functor template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()), errors::InvalidArgument("grad_values must be a vector, saw: ", grad_values_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<Tindex>(); const auto grad_values = grad_values_t->vec<T>(); const Tindex N = reverse_index_map_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); auto d_default_value = d_default_value_t->scalar<T>(); OP_REQUIRES_OK(context, functor::SparseFillEmptyRowsGrad<Device, T, Tindex>()( context, reverse_index_map, grad_values, d_values, d_default_value)); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_##D) \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGradOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, \ typename TTypes<Tindex>::ConstVec reverse_index_map, \ typename TTypes<T>::ConstVec grad_values, \ typename TTypes<T>::Vec d_values, \ typename TTypes<T>::Scalar d_default_value); \ extern template struct SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_REAL_NUMBER_TYPES(DECLARE_GPU_SPEC_INT64); #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_GPU_KERNELS(T) REGISTER_KERNELS(GPU, T, int64) TF_CALL_REAL_NUMBER_TYPES(REGISTER_GPU_KERNELS); #undef REGISTER_GPU_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #undef REGISTER_KERNELS } // namespace tensorflow
17,878
5,805
#ifndef STLPLUS_PRINT_BASIC #define STLPLUS_PRINT_BASIC //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // Utilities for converting printing basic C types //////////////////////////////////////////////////////////////////////////////// #include "print_bool.hpp" #include "print_cstring.hpp" #include "print_float.hpp" #include "print_int.hpp" #include "print_pointer.hpp" #endif
611
181
#pragma once #include <string> #include <ulocal/http_header_table.hpp> #include <ulocal/http_request.hpp> #include <ulocal/string_stream.hpp> #include <ulocal/url_args.hpp> namespace ulocal { namespace detail { enum class RequestState { Start, StatusLineMethod, StatusLineResource, StatusLineHttpVersion, HeaderName, HeaderValue, Content }; } // namespace detail class HttpRequestParser { public: HttpRequestParser() : _state(detail::RequestState::Start) {} HttpRequestParser(const HttpRequestParser&) = delete; HttpRequestParser(HttpRequestParser&&) noexcept = default; HttpRequestParser& operator=(const HttpRequestParser&) = delete; HttpRequestParser& operator=(HttpRequestParser&&) noexcept = default; std::optional<HttpRequest> parse(StringStream& stream) { bool continue_parsing = true; while (continue_parsing) { switch (_state) { case detail::RequestState::Start: { _method.clear(); _resource.clear(); _http_version.clear(); _header_name.clear(); _header_value.clear(); _headers.clear(); _content.clear(); _content_length = 0; _state = detail::RequestState::StatusLineMethod; break; } case detail::RequestState::StatusLineMethod: { auto [str, found_space] = stream.read_until(' '); _method += str; if (found_space) { _state = detail::RequestState::StatusLineResource; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineResource: { auto [str, found_space] = stream.read_until(' '); _resource += str; if (found_space) { _state = detail::RequestState::StatusLineHttpVersion; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineHttpVersion: { auto [str, found_newline] = stream.read_until("\r\n"); _http_version += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); } else continue_parsing = false; break; } case detail::RequestState::HeaderName: { if (stream.as_string_view(2) == "\r\n") { stream.skip(2); _state = detail::RequestState::Content; auto content_length_header = _headers.get_header("content-length"); if (content_length_header) _content_length = content_length_header->get_value_as<std::uint64_t>(); } else if (stream.as_string_view(1) == "\r") { continue_parsing = false; } else { auto [str, found_colon] = stream.read_until(':'); _header_name += str; if (found_colon) { _state = detail::RequestState::HeaderValue; stream.skip(1); } else continue_parsing = false; } break; } case detail::RequestState::HeaderValue: { auto [str, found_newline] = stream.read_until("\r\n"); _header_value += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); _headers.add_header(std::move(_header_name), lstrip(_header_value)); _header_name.clear(); _header_value.clear(); } else continue_parsing = false; break; } case detail::RequestState::Content: { auto str = stream.read(_content_length - _content.length()); _content += str; if (_content.length() == _content_length) { _state = detail::RequestState::Start; return HttpRequest{ std::move(_method), std::move(_resource), std::move(_headers), std::move(_content) }; } else continue_parsing = false; break; } } } stream.realign(); return std::nullopt; } private: detail::RequestState _state; std::string _method, _resource, _http_version, _header_name, _header_value, _content; HttpHeaderTable _headers; std::uint64_t _content_length; }; } // namespace ulocal
4,015
1,771
#include "unpack.hpp" #include <memory> #include <iomanip> #include <archive.h> #include <archive_entry.h> #include <cpprest/http_client.h> #include <cpprest/rawptrstream.h> #include <boost/filesystem.hpp> #include "types.hpp" #include "exception.hpp" #include "text.hpp" const uint64_t CHUNK_SIZE = 65536; class Context { public: Context (uint16_t port, const std::string & id); web::http::http_response & getResponse (); int64_t readChunk (const void ** buffer); int64_t seek (int64_t offset, int whence); void reset (); private: web::uri base; web::uri path; web::http::http_response response; int64_t offset; int64_t length; std::array<uint8_t, CHUNK_SIZE> chunk; }; using ContextHandle = std::shared_ptr<Context>; ArchiveHandle createArchiveReader (ContextHandle context); ArchiveHandle createDiskWriter (); std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName); void extractArchive (ArchiveHandle reader, ArchiveHandle writer); web::uri makeBase (uint16_t port); web::uri makePath (const std::string & id); int openCallback (struct archive * handle, void * context); int closeCallback (struct archive * handle, void * context); la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer); la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence); void unpackTo (uint16_t port, const std::string & id, const std::string & localPath) { ContextHandle context = std::make_shared<Context>(port, id); Text text; auto reader = createArchiveReader(context); auto writer = createDiskWriter(); for (;;) { struct archive_entry * entry = nullptr; int rv = archive_read_next_header(reader.get(), &entry); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_next_header"); } // skip folders auto fileType = archive_entry_filetype(entry); if (fileType & AE_IFDIR) { continue; } const char * entryName = archive_entry_pathname(entry); if (!entryName) { throw EntryError("archive_entry_pathname", "nullptr"); } auto entryPath = resolvePath(text, localPath, id, entryName); rv = archive_entry_update_pathname_utf8(entry, entryPath.c_str()); if (!rv) { throw EntryError("archive_entry_update_pathname_utf8", entryPath); } rv = archive_write_header(writer.get(), entry); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_header"); } extractArchive(reader, writer); rv = archive_write_finish_entry(writer.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_finish_entry"); } } } ArchiveHandle createArchiveReader (ContextHandle context) { int rv = 0; ArchiveHandle handle( archive_read_new(), [](ArchiveHandle::element_type * p) -> void { archive_read_free(p); }); rv = archive_read_support_filter_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_filter_all"); } rv = archive_read_support_format_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_format_all"); } rv = archive_read_set_open_callback(handle.get(), openCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_open_callback"); } rv = archive_read_set_close_callback(handle.get(), closeCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_close_callback"); } rv = archive_read_set_read_callback(handle.get(), readCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_read_callback"); } rv = archive_read_set_seek_callback(handle.get(), seekCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_seek_callback"); } rv = archive_read_set_callback_data(handle.get(), context.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_callback_data"); } rv = archive_read_open1(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_open1"); } return handle; } ArchiveHandle createDiskWriter () { ArchiveHandle handle( archive_write_disk_new(), [](ArchiveHandle::element_type * p) -> void { archive_write_free(p); }); return handle; } void extractArchive (ArchiveHandle reader, ArchiveHandle writer) { for (;;) { int rv = 0; const void * chunk = nullptr; size_t length = 0; la_int64_t offset = 0; rv = archive_read_data_block(reader.get(), &chunk, &length, &offset); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_data_block"); } rv = archive_write_data_block(writer.get(), chunk, length, offset); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_data_block"); } } } int openCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } int closeCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer) { auto ctx = static_cast<Context *>(context); try { return ctx->readChunk(buffer); } catch (std::exception & e) { fprintf(stderr, "readCallback %s\n", e.what()); return ARCHIVE_FATAL; } } la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence) { auto ctx = static_cast<Context *>(context); auto rv = ctx->seek(offset, whence); if (rv < 0) { return ARCHIVE_FATAL; } return rv; } web::uri makeBase (uint16_t port) { web::uri_builder builder; builder.set_scheme("http"); builder.set_host("localhost"); builder.set_port(port); return builder.to_uri(); } web::uri makePath (const std::string & id) { std::ostringstream sout; sout << "/api/v1/nodes/" << id << "/stream"; web::uri_builder builder; builder.set_path(sout.str()); return builder.to_uri(); } std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName) { auto newEntryName = text.toUtf8(entryName); boost::filesystem::path path = localPath; path /= id; path /= newEntryName; return path.string(); } Context::Context (uint16_t port, const std::string & id) : base(makeBase(port)) , path(makePath(id)) , response() , offset(0) , length(-1) , chunk() {} web::http::http_response & Context::getResponse () { auto status = this->response.status_code(); if (status == web::http::status_codes::OK || status == web::http::status_codes::PartialContent) { return this->response; } web::http::http_request request; request.set_method(web::http::methods::GET); request.set_request_uri(this->path); if (this->length >= 0) { std::ostringstream sout; sout << "bytes=" << this->offset << "-" << (this->length - 1); request.headers().add("Range", sout.str()); } web::http::client::http_client_config cfg; cfg.set_timeout(std::chrono::minutes(1)); web::http::client::http_client client(this->base, cfg); this->response = client.request(request).get(); status = this->response.status_code(); if (status == web::http::status_codes::OK) { this->length = this->response.headers().content_length(); } else if (status != web::http::status_codes::PartialContent) { throw HttpError(status, this->response.reason_phrase()); } return this->response; } int64_t Context::readChunk (const void ** buffer) { using Buffer = Concurrency::streams::rawptr_buffer<uint8_t>; auto & response = this->getResponse(); Buffer glue(&this->chunk[0], CHUNK_SIZE); auto length = response.body().read(glue, CHUNK_SIZE).get(); *buffer = &this->chunk[0]; this->offset += length; return length; } int64_t Context::seek (int64_t offset, int whence) { this->response = web::http::http_response(); switch (whence) { case SEEK_SET: this->offset = offset; break; case SEEK_CUR: this->offset += offset; break; case SEEK_END: if (this->length < 0) { return -1; } this->offset = this->length + offset; break; default: return -1; } return this->offset; } void Context::reset () { this->response = web::http::http_response(); this->offset = 0; this->length = -1; }
9,379
3,026
/* * Copyright (C) 2008, 2009 Apple Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 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 APPLE INC. ``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 APPLE INC. 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 "config.h" #include "ApplicationCacheHost.h" #if ENABLE(OFFLINE_WEB_APPLICATIONS) #include "ApplicationCache.h" #include "ApplicationCacheGroup.h" #include "ApplicationCacheResource.h" #include "DocumentLoader.h" #include "DOMApplicationCache.h" #include "Frame.h" #include "FrameLoader.h" #include "FrameLoaderClient.h" #include "MainResourceLoader.h" #include "ProgressEvent.h" #include "ResourceLoader.h" #include "ResourceRequest.h" #include "Settings.h" namespace WebCore { ApplicationCacheHost::ApplicationCacheHost(DocumentLoader* documentLoader) : m_domApplicationCache(0) , m_documentLoader(documentLoader) , m_defersEvents(true) , m_candidateApplicationCacheGroup(0) { ASSERT(m_documentLoader); } ApplicationCacheHost::~ApplicationCacheHost() { ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup); if (m_applicationCache) m_applicationCache->group()->disassociateDocumentLoader(m_documentLoader); else if (m_candidateApplicationCacheGroup) m_candidateApplicationCacheGroup->disassociateDocumentLoader(m_documentLoader); } void ApplicationCacheHost::selectCacheWithoutManifest() { ApplicationCacheGroup::selectCacheWithoutManifestURL(m_documentLoader->frame()); } void ApplicationCacheHost::selectCacheWithManifest(const KURL& manifestURL) { ApplicationCacheGroup::selectCache(m_documentLoader->frame(), manifestURL); } void ApplicationCacheHost::maybeLoadMainResource(ResourceRequest& request, SubstituteData& substituteData) { // Check if this request should be loaded from the application cache if (!substituteData.isValid() && isApplicationCacheEnabled()) { ASSERT(!m_mainResourceApplicationCache); m_mainResourceApplicationCache = ApplicationCacheGroup::cacheForMainRequest(request, m_documentLoader); if (m_mainResourceApplicationCache) { // Get the resource from the application cache. By definition, cacheForMainRequest() returns a cache that contains the resource. ApplicationCacheResource* resource = m_mainResourceApplicationCache->resourceForRequest(request); substituteData = SubstituteData(resource->data(), resource->response().mimeType(), resource->response().textEncodingName(), KURL()); } } } void ApplicationCacheHost::maybeLoadMainResourceForRedirect(ResourceRequest& request, SubstituteData& substituteData) { ASSERT(status() == UNCACHED); maybeLoadMainResource(request, substituteData); } bool ApplicationCacheHost::maybeLoadFallbackForMainResponse(const ResourceRequest& request, const ResourceResponse& r) { if (r.httpStatusCode() / 100 == 4 || r.httpStatusCode() / 100 == 5) { ASSERT(!m_mainResourceApplicationCache); if (isApplicationCacheEnabled()) { m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, documentLoader()); if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get())) return true; } } return false; } bool ApplicationCacheHost::maybeLoadFallbackForMainError(const ResourceRequest& request, const ResourceError& error) { if (!error.isCancellation()) { ASSERT(!m_mainResourceApplicationCache); if (isApplicationCacheEnabled()) { m_mainResourceApplicationCache = ApplicationCacheGroup::fallbackCacheForMainRequest(request, m_documentLoader); if (scheduleLoadFallbackResourceFromApplicationCache(documentLoader()->mainResourceLoader(), m_mainResourceApplicationCache.get())) return true; } } return false; } void ApplicationCacheHost::mainResourceDataReceived(const char*, int, long long, bool) { // This method is here to facilitate alternate implemetations of this interface by the host browser. } void ApplicationCacheHost::failedLoadingMainResource() { ApplicationCacheGroup* group = m_candidateApplicationCacheGroup; if (!group && m_applicationCache) { if (mainResourceApplicationCache()) { // Even when the main resource is being loaded from an application cache, loading can fail if aborted. return; } group = m_applicationCache->group(); } if (group) group->failedLoadingMainResource(m_documentLoader); } void ApplicationCacheHost::finishedLoadingMainResource() { ApplicationCacheGroup* group = candidateApplicationCacheGroup(); if (!group && applicationCache() && !mainResourceApplicationCache()) group = applicationCache()->group(); if (group) group->finishedLoadingMainResource(m_documentLoader); } bool ApplicationCacheHost::maybeLoadResource(ResourceLoader* loader, ResourceRequest& request, const KURL& originalURL) { if (!isApplicationCacheEnabled()) return false; if (request.url() != originalURL) return false; ApplicationCacheResource* resource; if (!shouldLoadResourceFromApplicationCache(request, resource)) return false; m_documentLoader->m_pendingSubstituteResources.set(loader, resource); m_documentLoader->deliverSubstituteResourcesAfterDelay(); return true; } bool ApplicationCacheHost::maybeLoadFallbackForRedirect(ResourceLoader* resourceLoader, ResourceRequest& request, const ResourceResponse& redirectResponse) { if (!redirectResponse.isNull() && !protocolHostAndPortAreEqual(request.url(), redirectResponse.url())) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadFallbackForResponse(ResourceLoader* resourceLoader, const ResourceResponse& response) { if (response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadFallbackForError(ResourceLoader* resourceLoader, const ResourceError& error) { if (!error.isCancellation()) if (scheduleLoadFallbackResourceFromApplicationCache(resourceLoader)) return true; return false; } bool ApplicationCacheHost::maybeLoadSynchronously(ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data) { ApplicationCacheResource* resource; if (shouldLoadResourceFromApplicationCache(request, resource)) { if (resource) { response = resource->response(); data.append(resource->data()->data(), resource->data()->size()); } else { error = documentLoader()->frameLoader()->client()->cannotShowURLError(request); } return true; } return false; } void ApplicationCacheHost::maybeLoadFallbackSynchronously(const ResourceRequest& request, ResourceError& error, ResourceResponse& response, Vector<char>& data) { // If normal loading results in a redirect to a resource with another origin (indicative of a captive portal), or a 4xx or 5xx status code or equivalent, // or if there were network errors (but not if the user canceled the download), then instead get, from the cache, the resource of the fallback entry // corresponding to the matched namespace. if ((!error.isNull() && !error.isCancellation()) || response.httpStatusCode() / 100 == 4 || response.httpStatusCode() / 100 == 5 || !protocolHostAndPortAreEqual(request.url(), response.url())) { ApplicationCacheResource* resource; if (getApplicationCacheFallbackResource(request, resource)) { response = resource->response(); data.clear(); data.append(resource->data()->data(), resource->data()->size()); } } } bool ApplicationCacheHost::canCacheInPageCache() const { return !applicationCache() && !candidateApplicationCacheGroup(); } void ApplicationCacheHost::setDOMApplicationCache(DOMApplicationCache* domApplicationCache) { ASSERT(!m_domApplicationCache || !domApplicationCache); m_domApplicationCache = domApplicationCache; } void ApplicationCacheHost::notifyDOMApplicationCache(EventID id, int total, int done) { if (m_defersEvents) { // Event dispatching is deferred until document.onload has fired. m_deferredEvents.append(DeferredEvent(id, total, done)); return; } dispatchDOMEvent(id, total, done); } void ApplicationCacheHost::stopLoadingInFrame(Frame* frame) { ASSERT(!m_applicationCache || !m_candidateApplicationCacheGroup || m_applicationCache->group() == m_candidateApplicationCacheGroup); if (m_candidateApplicationCacheGroup) m_candidateApplicationCacheGroup->stopLoadingInFrame(frame); else if (m_applicationCache) m_applicationCache->group()->stopLoadingInFrame(frame); } void ApplicationCacheHost::stopDeferringEvents() { RefPtr<DocumentLoader> protect(documentLoader()); for (unsigned i = 0; i < m_deferredEvents.size(); ++i) { const DeferredEvent& deferred = m_deferredEvents[i]; dispatchDOMEvent(deferred.eventID, deferred.progressTotal, deferred.progressDone); } m_deferredEvents.clear(); m_defersEvents = false; } #if ENABLE(INSPECTOR) void ApplicationCacheHost::fillResourceList(ResourceInfoList* resources) { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return; ApplicationCache::ResourceMap::const_iterator end = cache->end(); for (ApplicationCache::ResourceMap::const_iterator it = cache->begin(); it != end; ++it) { RefPtr<ApplicationCacheResource> resource = it->second; unsigned type = resource->type(); bool isMaster = type & ApplicationCacheResource::Master; bool isManifest = type & ApplicationCacheResource::Manifest; bool isExplicit = type & ApplicationCacheResource::Explicit; bool isForeign = type & ApplicationCacheResource::Foreign; bool isFallback = type & ApplicationCacheResource::Fallback; resources->append(ResourceInfo(resource->url(), isMaster, isManifest, isFallback, isForeign, isExplicit, resource->estimatedSizeInStorage())); } } ApplicationCacheHost::CacheInfo ApplicationCacheHost::applicationCacheInfo() { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return CacheInfo(KURL(), 0, 0, 0); // FIXME: Add "Creation Time" and "Update Time" to Application Caches. return CacheInfo(cache->manifestResource()->url(), 0, 0, cache->estimatedSizeInStorage()); } #endif void ApplicationCacheHost::dispatchDOMEvent(EventID id, int total, int done) { if (m_domApplicationCache) { const AtomicString& eventType = DOMApplicationCache::toEventType(id); ExceptionCode ec = 0; RefPtr<Event> event; if (id == PROGRESS_EVENT) event = ProgressEvent::create(eventType, true, done, total); else event = Event::create(eventType, false, false); m_domApplicationCache->dispatchEvent(event, ec); ASSERT(!ec); } } void ApplicationCacheHost::setCandidateApplicationCacheGroup(ApplicationCacheGroup* group) { ASSERT(!m_applicationCache); m_candidateApplicationCacheGroup = group; } void ApplicationCacheHost::setApplicationCache(PassRefPtr<ApplicationCache> applicationCache) { if (m_candidateApplicationCacheGroup) { ASSERT(!m_applicationCache); m_candidateApplicationCacheGroup = 0; } m_applicationCache = applicationCache; } bool ApplicationCacheHost::shouldLoadResourceFromApplicationCache(const ResourceRequest& request, ApplicationCacheResource*& resource) { ApplicationCache* cache = applicationCache(); if (!cache || !cache->isComplete()) return false; // If the resource is not to be fetched using the HTTP GET mechanism or equivalent, or if its URL has a different // <scheme> component than the application cache's manifest, then fetch the resource normally. // +{ ASD-NET-JC-JLO_JB.1257-01 if (!cache->manifestResource() || (!ApplicationCache::requestIsHTTPOrHTTPSGet(request) || !equalIgnoringCase(request.url().protocol(), cache->manifestResource()->url().protocol()))) // if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request) || !equalIgnoringCase(request.url().protocol(), cache->manifestResource()->url().protocol())) // ASD-NET-JC-JLO_JB.1257-01 }+ return false; // If the resource's URL is an master entry, the manifest, an explicit entry, or a fallback entry // in the application cache, then get the resource from the cache (instead of fetching it). resource = cache->resourceForURL(request.url()); // Resources that match fallback namespaces or online whitelist entries are fetched from the network, // unless they are also cached. if (!resource && (cache->allowsAllNetworkRequests() || cache->urlMatchesFallbackNamespace(request.url()) || cache->isURLInOnlineWhitelist(request.url()))) return false; // Resources that are not present in the manifest will always fail to load (at least, after the // cache has been primed the first time), making the testing of offline applications simpler. return true; } bool ApplicationCacheHost::getApplicationCacheFallbackResource(const ResourceRequest& request, ApplicationCacheResource*& resource, ApplicationCache* cache) { if (!cache) { cache = applicationCache(); if (!cache) return false; } if (!cache->isComplete()) return false; // If the resource is not a HTTP/HTTPS GET, then abort if (!ApplicationCache::requestIsHTTPOrHTTPSGet(request)) return false; KURL fallbackURL; if (cache->isURLInOnlineWhitelist(request.url())) return false; if (!cache->urlMatchesFallbackNamespace(request.url(), &fallbackURL)) return false; resource = cache->resourceForURL(fallbackURL); ASSERT(resource); return true; } bool ApplicationCacheHost::scheduleLoadFallbackResourceFromApplicationCache(ResourceLoader* loader, ApplicationCache* cache) { if (!isApplicationCacheEnabled()) return false; ApplicationCacheResource* resource; if (!getApplicationCacheFallbackResource(loader->request(), resource, cache)) return false; m_documentLoader->m_pendingSubstituteResources.set(loader, resource); m_documentLoader->deliverSubstituteResourcesAfterDelay(); loader->handle()->cancel(); return true; } ApplicationCacheHost::Status ApplicationCacheHost::status() const { ApplicationCache* cache = applicationCache(); if (!cache) return UNCACHED; switch (cache->group()->updateStatus()) { case ApplicationCacheGroup::Checking: return CHECKING; case ApplicationCacheGroup::Downloading: return DOWNLOADING; case ApplicationCacheGroup::Idle: { if (cache->group()->isObsolete()) return OBSOLETE; if (cache != cache->group()->newestCache()) return UPDATEREADY; return IDLE; } } ASSERT_NOT_REACHED(); return UNCACHED; } bool ApplicationCacheHost::update() { ApplicationCache* cache = applicationCache(); if (!cache) return false; cache->group()->update(m_documentLoader->frame(), ApplicationCacheUpdateWithoutBrowsingContext); return true; } bool ApplicationCacheHost::swapCache() { ApplicationCache* cache = applicationCache(); if (!cache) return false; // If the group of application caches to which cache belongs has the lifecycle status obsolete, unassociate document from cache. if (cache->group()->isObsolete()) { cache->group()->disassociateDocumentLoader(m_documentLoader); return true; } // If there is no newer cache, raise an INVALID_STATE_ERR exception. ApplicationCache* newestCache = cache->group()->newestCache(); if (cache == newestCache) return false; ASSERT(cache->group() == newestCache->group()); setApplicationCache(newestCache); return true; } bool ApplicationCacheHost::isApplicationCacheEnabled() { return m_documentLoader->frame()->settings() && m_documentLoader->frame()->settings()->offlineWebApplicationCacheEnabled(); } } // namespace WebCore #endif // ENABLE(OFFLINE_WEB_APPLICATIONS)
18,025
4,922
/*************************************************/ /* Bacteria - The interesting bacteria simulator */ /* (c) Kristian K. Skordal 2009 - 2012 */ /*************************************************/ #include "config_parser.h" using namespace std; config_parser::config_parser(const string & filename) : filename(filename) { assert(!filename.empty()); } bool config_parser::parse() { ifstream config_file(filename.c_str(), ios::in); string input_line; int line_number = 0; if(!config_file.good()) { cerr << "ERROR: Could not open configuration file: " << filename << endl; return false; } while(config_file.good() && !config_file.eof()) { size_t equal_sign_index; string attribute_name; string attribute_value; getline(config_file, input_line); ++line_number; // Check for empty lines or comments: if(input_line.length() == 0 || input_line.at(0) == '\n' || input_line.at(0) == '\r' || input_line.at(0) == '#') continue; equal_sign_index = input_line.find_first_of('='); if(equal_sign_index == string::npos) { cerr << "ERROR: Missing assignment on line " << input_line << endl; return false; } size_t name_start = input_line.find_first_not_of(" \t"); if(name_start == string::npos && input_line[name_start] == '=') { cerr << "ERROR: Missing attribute name on line " << input_line << endl; return false; } size_t name_end = input_line.find_first_of(" =\t", name_start); if(name_end == string::npos) { cerr << "ERROR: End of attribute name not found on line " << input_line << endl; return false; } attribute_name = input_line.substr(name_start, name_end); size_t value_start = input_line.find_first_not_of(" \t", equal_sign_index + 1); if(value_start == string::npos) { cerr << "ERROR: No value found for attribute " << attribute_name << " on line " << input_line << endl; return false; } size_t value_end = input_line.find_first_of("\n\r\t ", value_start); attribute_value = input_line.substr(value_start, value_end); // Check the name and type of the parsed attribute and value: config_type_t type = config_db::get_type(attribute_name); if(type == TYPE_INVALID) { cerr << "ERROR: Unrecognized attribute name: " << attribute_name << " on line " << input_line << endl; return false; } istringstream value_extractor(attribute_value); switch(type) { case TYPE_INTEGER: int intval; value_extractor >> intval; config_db::get().set_value(attribute_name, intval); break; case TYPE_FLOAT: float floatval; value_extractor >> floatval; config_db::get().set_value(attribute_name, floatval); break; case TYPE_BOOLEAN: transform(attribute_value.begin(), attribute_value.end(), attribute_value.begin(), ptr_fun<int, int>(tolower)); if(attribute_value == "true") config_db::get().set_value(attribute_name, true); else if(attribute_value == "false") config_db::get().set_value(attribute_name, false); else { cerr << "ERROR: Unrecognized boolean value for attribute " << attribute_name << " on line " << input_line << endl; return false; } break; case TYPE_STRING: config_db::get().set_value(attribute_name, attribute_value.c_str()); break; } } config_file.close(); return true; }
3,329
1,295
#ifndef INCLUDE_LOAD_FONT_MODULE_HPP #define INCLUDE_LOAD_FONT_MODULE_HPP #include <vector> #include <cstdint> namespace al_stb { // Wrapper for all the data needed for font rendering struct FontData { struct BakedChar { unsigned short x0, y0, x1, y1; float xoff, yoff, xadvance; }; // to be casted to stbtt_bakedchar in the implementation // user will not need to use this struct float pixelHeight = -1; int width = -1, height = -1; // of bitmap pixel data std::vector<uint8_t> bitmap; // 1 channel bitmap data std::vector<BakedChar> charData; }; // info about a chracter, calculated from font data struct CharData { float x0, y0, x1, y1; // packing rect corners, x towards right, y towards down float s0, t0, s1, t1; // texcoords float xAdvance; // how much to go horizontally after this character }; // pixelHeight is max height of each character in font texture // value larger than 128 might result not all fonts fitting in the texture FontData loadFont(const char* filename, float pixelHeight, int bitmapSize); // caching the results of this function might give better performance // x0, y0, x1, y1, and xAdvance of returned CharData are in fontData.pixelHeight scale CharData getCharData(FontData* fontData, int charIndex); } #endif
1,314
420
// Copyright 2017 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 "ui/gfx/mojom/ca_layer_params_mojom_traits.h" #include "build/build_config.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ui/gfx/geometry/mojom/geometry_mojom_traits.h" namespace mojo { gfx::mojom::CALayerContentPtr StructTraits<gfx::mojom::CALayerParamsDataView, gfx::CALayerParams>::content( const gfx::CALayerParams& ca_layer_params) { #if defined(OS_MAC) if (ca_layer_params.io_surface_mach_port) { DCHECK(!ca_layer_params.ca_context_id); return gfx::mojom::CALayerContent::NewIoSurfaceMachPort( mojo::PlatformHandle(base::mac::RetainMachSendRight( ca_layer_params.io_surface_mach_port.get()))); } #endif return gfx::mojom::CALayerContent::NewCaContextId( ca_layer_params.ca_context_id); } bool StructTraits<gfx::mojom::CALayerParamsDataView, gfx::CALayerParams>::Read( gfx::mojom::CALayerParamsDataView data, gfx::CALayerParams* out) { out->is_empty = data.is_empty(); gfx::mojom::CALayerContentDataView content_data; data.GetContentDataView(&content_data); switch (content_data.tag()) { case gfx::mojom::CALayerContentDataView::Tag::CA_CONTEXT_ID: out->ca_context_id = content_data.ca_context_id(); break; case gfx::mojom::CALayerContentDataView::Tag::IO_SURFACE_MACH_PORT: #if defined(OS_MAC) mojo::PlatformHandle platform_handle = content_data.TakeIoSurfaceMachPort(); if (!platform_handle.is_mach_send()) return false; out->io_surface_mach_port.reset(platform_handle.ReleaseMachSendRight()); break; #else return false; #endif } if (!data.ReadPixelSize(&out->pixel_size)) return false; out->scale_factor = data.scale_factor(); return true; } } // namespace mojo
1,912
714
/* ____ _ __ ____ __ ____ / __/___(_) / ___ ____/ __ \__ _____ ___ / /_ / _/__ ____ _\ \/ __/ / _ \/ -_) __/ /_/ / // / -_|_-</ __/ _/ // _ \/ __/ /___/\__/_/_.__/\__/_/ \___\_\_,_/\__/___/\__/ /___/_//_/\__(_) Copyright 2012 SciberQuest Inc. */ /*===================== Program: Visualization Toolkit Module: $RCSfile: vtkSQSeedPointLatice.cxx,v $ Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =====================*/ #include "vtkSQSeedPointLatice.h" #include "vtkObjectFactory.h" #include "vtkStreamingDemandDrivenPipeline.h" #include "vtkMultiProcessController.h" #include "vtkInformation.h" #include "vtkInformationVector.h" #include "vtkCellArray.h" #include "vtkFloatArray.h" #include "vtkIdTypeArray.h" #include "vtkPoints.h" #include "vtkPolyData.h" #include "vtkType.h" #include "Tuple.hxx" #include "vtkPVInformationKeys.h" // #define SQTK_DEBUG //***************************************************************************** static inline void indexToIJK(int idx, int nx, int nxy, int &i, int &j, int &k) { // convert a flat array index into a i,j,k three space tuple. k=idx/nxy; j=(idx-k*nxy)/nx; i=idx-k*nxy-j*nx; } //***************************************************************************** template <typename T> static void linspace(T lo, T hi, int n, T *data) { if (n==1) { data[0]=(hi+lo)/((T)2); return; } T delta=(hi-lo)/((T)(n-1)); for (int i=0; i<n; ++i) { data[i]=lo+((T)i)*delta; } } //***************************************************************************** template <typename T> static void logspace(T lo, T hi, int n, T p, T *data) { int mid=n/2; int nlo=mid; int nhi=n-mid; T s=hi-lo; T rhi=((T)pow(((T)10),p)); linspace<T>(((T)1),((T)0.99)*rhi,nlo,data); linspace<T>(1.0,rhi,nhi,data+nlo); int i=0; for (; i<nlo; ++i) { data[i]=lo+s*(((T)0.5)*((T)log10(data[i]))/p); } for (; i<n; ++i) { data[i]=lo+s*(((T)1)-((T)log10(data[i]))/(((T)2)*p)); } } //---------------------------------------------------------------------------- vtkStandardNewMacro(vtkSQSeedPointLatice); //---------------------------------------------------------------------------- vtkSQSeedPointLatice::vtkSQSeedPointLatice() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::vtkSQSeedPointLatice" << std::endl; #endif this->NX[0]=this->NX[1]=this->NX[2]=4; this->Bounds[0]=this->Bounds[2]=this->Bounds[4]=0.0; this->Bounds[1]=this->Bounds[3]=this->Bounds[5]=1.0; this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } //---------------------------------------------------------------------------- vtkSQSeedPointLatice::~vtkSQSeedPointLatice() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::~vtkSQSeedPointLatice" << std::endl; #endif } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetTransformPower(double itp, double jtp, double ktp) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetTransformPower" << std::endl; #endif double tp[3]={itp,jtp,ktp}; this->SetTransformPower(tp); } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetTransformPower(double *tp) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetTransformPower" << std::endl; #endif if (tp[0]<0.0) vtkErrorMacro("Negative transform power i unsupported."); if (tp[1]<0.0) vtkErrorMacro("Negative transform power j unsupported."); if (tp[2]<0.0) vtkErrorMacro("Negative transform power k unsupported."); this->Power[0]=tp[0]; this->Power[1]=tp[1]; this->Power[2]=tp[2]; this->Transform[0]=(tp[0]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Transform[1]=(tp[1]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Transform[2]=(tp[2]<0.25?TRANSFORM_NONE:TRANSFORM_LOG); this->Modified(); } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetIBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetIBounds" << std::endl; #endif this->Bounds[0]=lo; this->Bounds[1]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetIBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetIBounds" << std::endl; #endif return this->Bounds; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetJBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetJBounds" << std::endl; #endif this->Bounds[2]=lo; this->Bounds[3]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetJBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetJBounds" << std::endl; #endif return this->Bounds+2; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::SetKBounds(double lo, double hi) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::SetKBounds" << std::endl; #endif this->Bounds[4]=lo; this->Bounds[5]=hi; this->Modified(); } //---------------------------------------------------------------------------- double *vtkSQSeedPointLatice::GetKBounds() { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::GetKBounds" << std::endl; #endif return this->Bounds+4; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::FillInputPortInformation( int /*port*/, vtkInformation *info) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::FillInputPortInformation" << std::endl; #endif // The input is optional,if present it will be used // for bounds. info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(),"vtkDataSet"); info->Set(vtkAlgorithm::INPUT_IS_OPTIONAL(),1); return 1; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::RequestInformation( vtkInformation * /*req*/, vtkInformationVector ** /*inInfos*/, vtkInformationVector *outInfos) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::RequestInformation" << std::endl; #endif // tell the excutive that we are handling our own paralelization. vtkInformation *outInfo=outInfos->GetInformationObject(0); outInfo->Set(CAN_HANDLE_PIECE_REQUEST(), 1); // TODO extract bounds and set if the input data set is present. return 1; } //---------------------------------------------------------------------------- int vtkSQSeedPointLatice::RequestData( vtkInformation * /*req*/, vtkInformationVector **inInfos, vtkInformationVector *outInfos) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::RequestData" << std::endl; #endif vtkInformation *outInfo=outInfos->GetInformationObject(0); vtkPolyData *output = dynamic_cast<vtkPolyData*>(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (output==NULL) { vtkErrorMacro("Empty output."); return 1; } // paralelize by piece information. int pieceNo = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_PIECE_NUMBER()); int nPieces = outInfo->Get(vtkStreamingDemandDrivenPipeline::UPDATE_NUMBER_OF_PIECES()); // sanity - the requst cannot be fullfilled if (pieceNo>=nPieces) { output->Initialize(); return 1; } // domain decomposition int nPoints=this->NX[0]*this->NX[1]*this->NX[2]; int pieceSize=nPoints/nPieces; int nLarge=nPoints%nPieces; int nLocal=pieceSize+(pieceNo<nLarge?1:0); int startId=pieceSize*pieceNo+(pieceNo<nLarge?pieceNo:nLarge); int endId=startId+nLocal; // If the input is present then use it for bounds // otherwise we assume the user has previously set // desired bounds. vtkInformation *inInfo=0; if (inInfos[0]->GetNumberOfInformationObjects()) { inInfo=inInfos[0]->GetInformationObject(0); vtkDataSet *input = dynamic_cast<vtkDataSet*>(inInfo->Get(vtkDataObject::DATA_OBJECT())); if (input) { if (!inInfo->Has(vtkPVInformationKeys::WHOLE_BOUNDING_BOX())) { vtkErrorMacro("Input must have WHOLE_BOUNDING_BOX set."); return 1; } double bounds[6]; inInfo->Get(vtkPVInformationKeys::WHOLE_BOUNDING_BOX(),bounds); double dX[3]; dX[0]=(this->Bounds[1]-this->Bounds[0])/((double)this->NX[0]); dX[1]=(this->Bounds[3]-this->Bounds[2])/((double)this->NX[1]); dX[2]=(this->Bounds[5]-this->Bounds[4])/((double)this->NX[2]); bounds[0]+=dX[0]/2.0; bounds[1]-=dX[0]/2.0; bounds[2]+=dX[1]/2.0; bounds[3]-=dX[1]/2.0; bounds[4]+=dX[2]/2.0; bounds[5]-=dX[2]/2.0; this->SetBounds(bounds); } } // generate the i,j,k coordinate axes // note these are not decompoesed, TODO decomposition. float *axes[3]={NULL}; for (int q=0; q<3; ++q) { axes[q]=new float [this->NX[q]]; switch (this->Transform[q]) { case TRANSFORM_NONE: linspace<float>( ((float)this->Bounds[2*q]), ((float)this->Bounds[2*q+1]), this->NX[q], axes[q]); break; case TRANSFORM_LOG: logspace<float>( ((float)this->Bounds[2*q]), ((float)this->Bounds[2*q+1]), this->NX[q], ((float)this->Power[q]), axes[q]); break; default: vtkErrorMacro("Unsupported transform."); return 1; } } // Configure the output vtkFloatArray *X=vtkFloatArray::New(); X->SetNumberOfComponents(3); X->SetNumberOfTuples(nLocal); float *pX=X->GetPointer(0); vtkPoints *pts=vtkPoints::New(); pts->SetData(X); X->Delete(); output->SetPoints(pts); pts->Delete(); vtkIdTypeArray *ia=vtkIdTypeArray::New(); ia->SetNumberOfComponents(1); ia->SetNumberOfTuples(2*nLocal); vtkIdType *pIa=ia->GetPointer(0); vtkCellArray *verts=vtkCellArray::New(); verts->SetCells(nLocal,ia); ia->Delete(); output->SetVerts(verts); verts->Delete(); int nx=this->NX[0]; int nxy=this->NX[0]*this->NX[1]; double prog=0.0; double progUnit=1.0/nLocal; double progRepUnit=0.1; double progRepLevel=0.1; // generate the point set for (int idx=startId,pid=0; idx<endId; ++idx,++pid,prog+=progUnit) { // update PV progress if (prog>=progRepLevel) { this->UpdateProgress(prog); progRepLevel+=progRepUnit; } int i,j,k; indexToIJK(idx,nx,nxy,i,j,k); // new latice point pX[0]=(axes[0])[i]; pX[1]=(axes[1])[j]; pX[2]=(axes[2])[k]; pX+=3; // insert the cell pIa[0]=1; pIa[1]=pid; pIa+=2; } delete [] axes[0]; delete [] axes[1]; delete [] axes[2]; #ifdef SQTK_DEBUG int rank=vtkMultiProcessController::GetGlobalController()->GetLocalProcessId(); std::cerr << "pieceNo = " << pieceNo << std::endl << "nPieces = " << nPieces << std::endl << "rank = " << rank << std::endl << "nLocal = " << nLocal << std::endl << "startId = " << startId << std::endl << "endId = " << endId << std::endl << "NX=" << Tuple<int>(this->NX,3) << std::endl << "Bounds=" << Tuple<double>(this->Bounds,6) << std::endl; #endif return 1; } //---------------------------------------------------------------------------- void vtkSQSeedPointLatice::PrintSelf(ostream& os, vtkIndent indent) { #ifdef SQTK_DEBUG std::cerr << "=====vtkSQSeedPointLatice::PrintSelf" << std::endl; #endif this->Superclass::PrintSelf(os,indent); os << indent << "NumberOfPoints: " << this->NumberOfPoints << "\n"; }
12,257
4,642
#ifndef DOXYGENSCRAPER_HPP #define DOXYGENSCRAPER_HPP #include "ApplicationPrinter.hpp" #include <sapi/var.hpp> class DoxygenScraperKey { public: DoxygenScraperKey(const String &key, const String &kind, bool is_array) { m_key = key; m_kind = kind; m_is_array = is_array; } const String &key() const { return m_key; } const String &kind() const { return m_kind; } bool is_array() const { return m_is_array; } private: String m_key; String m_kind; bool m_is_array = false; }; class DoxygenScraperObject { public: DoxygenScraperObject(const String &name) { m_name = name; } bool operator==(const DoxygenScraperObject &a) const { return m_name == a.m_name; } void add_key(const String &key, const String &kind, bool is_array = false) { for (size_t i = 0; i < m_keys.count(); i++) { if (m_keys.at(i).key() == key) { // key already exists return; } } m_keys.push_back(DoxygenScraperKey(key, kind, is_array)); } const String &name() const { return m_name; } String constructors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " {\n"; result += " JsonArray json_array = object.at(\"" + key.key() + "\").to_array();\n"; result += " for(u32 i=0; i < json_array.count(); i++){\n"; result += " m_" + translate_name(output_key) + ".push_back(" + key.kind() + "(json_array.at(i).to_object()));\n"; result += " }\n"; result += " }\n"; } else if (key.kind() == "String") { result += " m_" + translate_name(output_key) + " = object.at(\"" + key.key() + "\").to_string();\n"; } else { result += " m_" + translate_name(output_key) + " = " + key.kind() + "(object.at(\"" + key.key() + "\").to_object());\n"; } } return result; } String accessors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); result += " const " + key.kind() + "& " + translate_name(output_key) + "() const { return m_" + translate_name(output_key) + "; }\n"; } return result; } String members() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " Vector<" + key.kind() + "> m_" + translate_name(output_key) + ";\n"; } else { result += " " + key.kind() + " m_" + translate_name(output_key) + ";\n"; } } return result; } static String translate_name(const String &name, bool is_class = false); const Vector<DoxygenScraperKey> &keys() const { return m_keys; } private: String to_output_key(const String &key) const { String result = key; result.replace(String::ToErase("@"), String::ToInsert("a_")); result.replace(String::ToErase("#"), String::ToInsert("h_")); result.replace(String::ToErase(":"), String::ToInsert("_")); return result; } String m_name; Vector<DoxygenScraperKey> m_keys; }; class DoxygenScraper : public ApplicationPrinter { public: DoxygenScraper(); void generate_code(const String &file); private: int generate_code_object( const String &object_key, const JsonObject &object, int depth); Vector<DoxygenScraperObject> m_objects; }; #endif // DOXYGENSCRAPER_HPP
3,568
1,247
/* Copyright (c) 2018 Anakin Authors, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "include/saber_pooling_with_index.h" namespace anakin { namespace saber { template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::init( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& param, Context<AMD>& ctx) { this->_ctx = &ctx; return create(inputs, outputs, param, ctx); } template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::create( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& power_param, Context<AMD>& ctx) { const int count = outputs[0]->size(); Shape out_stride = outputs[0]->get_stride(); Shape in_stride = inputs[0]->get_stride(); int in_n_index = inputs[0]->num_index(); int in_c_index = inputs[0]->channel_index(); int in_h_index = inputs[0]->height_index(); int in_w_index = inputs[0]->width_index(); int out_n_index = outputs[0]->num_index(); int out_c_index = outputs[0]->channel_index(); int out_h_index = outputs[0]->height_index(); int out_w_index = outputs[0]->width_index(); _in_n_stride = in_stride[in_n_index]; _in_c_stride = in_stride[in_c_index]; _in_h_stride = in_stride[in_h_index]; _in_w_stride = in_stride[in_w_index]; _out_n_stride = out_stride[out_n_index]; _out_c_stride = out_stride[out_c_index]; _out_h_stride = out_stride[out_h_index]; _out_w_stride = out_stride[out_w_index]; KernelInfo kernelInfo; kernelInfo.kernel_file = "Pooling_with_index.cl"; kernelInfo.kernel_name = "Pooling_with_index"; kernelInfo.wk_dim = 1; kernelInfo.l_wk = {AMD_NUM_THREADS}; kernelInfo.g_wk = { (count + kernelInfo.l_wk[0] - 1) / kernelInfo.l_wk[0]* kernelInfo.l_wk[0], 1, 1 }; AMDKernelPtr kptr = CreateKernel(inputs[0]->device_id(), &kernelInfo); if (!kptr.get()->isInit()) { LOG(ERROR) << "Failed to load program"; return SaberInvalidValue; } _kernel_poo1ing_with_index = kptr; LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE CREATE KERNEL"; return SaberSuccess; } template <DataType OpDtype> SaberStatus SaberPoolingWithIndex<AMD, OpDtype>::dispatch( const std::vector<Tensor<AMD>*>& inputs, std::vector<Tensor<AMD>*>& outputs, PoolingParam<AMD>& param) { bool err; AMD_API::stream_t cm = this->_ctx->get_compute_stream(); amd_kernel_list list; // To set the argument cl_mem memObjects[3]; cl_mem in_data = (cl_mem)inputs[0]->data(); cl_mem out_data = (cl_mem)outputs[0]->mutable_data(); cl_mem out_index = (cl_mem)outputs[1]->mutable_data(); // To set the argument int count = outputs[0]->valid_size(); int out_n = outputs[0]->num(); int out_c = outputs[0]->channel(); int out_h = outputs[0]->height(); int out_w = outputs[0]->width(); int in_h = inputs[0]->height(); int in_w = inputs[0]->width(); AMDKernel* kernel = _kernel_poo1ing_with_index.get(); kernel->SetKernelArgs( out_data, out_index, in_data, _in_n_stride, _in_c_stride, _in_h_stride, _in_w_stride, in_h, in_w, _out_n_stride, _out_c_stride, _out_h_stride, _out_w_stride, out_h, out_w, out_n, out_c, param.pad_h, param.pad_w, param.stride_h, param.stride_w, param.window_h, param.window_w, count); list.push_back(_kernel_poo1ing_with_index); err = LaunchKernel(cm, list); if (!err) { LOG(ERROR) << "Fialed to set execution."; return SaberInvalidValue; } list.clear(); LOG_IF_S(INFO, ENABLE_AMD_DEBUG_LOG) << "COMPLETE EXECUTION"; return SaberSuccess; } } // namespace saber } // namespace anakin
4,553
1,694
/* The MIT License (MIT) Copyright (c) 2011 - 2013, Philipp Heise and Sebastian Klose 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 <cvt/vision/slam/stereo/ORBTracking.h> namespace cvt { ORBTracking::ORBTracking() : _maxDescDistance( 80 ), _windowRadius( 100 ), _orbOctaves( 3 ), _orbScaleFactor( 0.5f ), _orbCornerThreshold( 15 ), _orbMaxFeatures( 2000 ), _orbNonMaxSuppression( true ) { } ORBTracking::~ORBTracking() { } void ORBTracking::trackFeatures( PointSet2d& trackedPositions, std::vector<size_t>& trackedFeatureIds, const std::vector<Vector2f>& predictedPositions, const std::vector<size_t>& predictedIds, const Image& img ) { // create the ORB //_orb0.update( img ); // we want to find the best matching orb feature from current, that lies // within a certain distance from the "predicted" position std::vector<size_t>::const_iterator currentId = predictedIds.begin(); std::vector<size_t>::const_iterator tEnd = predictedIds.end(); std::vector<Vector2f>::const_iterator pred = predictedPositions.begin(); // keep track of already assigned indices to avoid double associations _orb0MatchedIds.clear(); while( currentId != tEnd ){ FeatureMatch m; const ORBFeature & desc = _descriptors.descriptor( *currentId ); m.feature0 = &desc; int matchedIdx = matchInWindow( m, *pred, _orb0, _orb0MatchedIds ); if( matchedIdx != -1 ){ _orb0MatchedIds.insert( ( size_t )matchedIdx ); trackedPositions.add( Vector2d( m.feature1->pt.x, m.feature1->pt.y ) ); trackedFeatureIds.push_back( *currentId ); } ++currentId; ++pred; } } void ORBTracking::addFeatureToDatabase( const Vector2f & f, size_t id ) { // this is odd, we need to search the closest feature in orb0 size_t closestIdx = 0; float distsqr = Math::MAXF; for( size_t i = 0; i < _orb0.size(); ++i ){ float currd = ( _orb0[ i ].pt - f ).lengthSqr(); if( currd < distsqr ){ closestIdx = i; distsqr = currd; } } _descriptors.addDescriptor( _orb0[ closestIdx ], id ); } int ORBTracking::matchInWindow( FeatureMatch& match, const Vector2f & p, const ORB & orb, const std::set<size_t> & used ) const { const ORBFeature * f = (ORBFeature*)match.feature0; match.feature1 = 0; match.distance = _maxDescDistance; size_t currDist; const std::set<size_t>::const_iterator usedEnd = used.end(); size_t matchedId = 0; for( size_t i = 0; i < orb.size(); i++ ){ if( used.find( i ) == usedEnd ){ if( ( p - orb[ i ].pt ).length() < _windowRadius ){ // try to match currDist = f->distance( orb[ i ] ); if( currDist < match.distance ){ match.feature1 = &orb[ i ]; match.distance = currDist; matchedId = i; } } } } // to ensure unique matches if( match.distance < _maxDescDistance ){ return matchedId; } return -1; } void ORBTracking::clear() { _descriptors.clear(); _orb0MatchedIds.clear(); } }
4,573
1,455
#include <fstream> #include <sstream> #include <gtest/gtest.h> #include <test/utility.hpp> using cmdstan::test::get_path_separator; using cmdstan::test::run_command; using cmdstan::test::run_command_output; TEST(CommandDiagnose, corr_gauss) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "corr_gauss_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/corr_gauss.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, eight_schools) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "eight_schools_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/eight_schools.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, mix) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "mix_output.*"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/mix.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); }
2,304
843
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2009 StatPro Italia srl Copyright (C) 2009 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. 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 license for more details. */ /*! \file defaultevent.hpp \brief Classes for default-event description. */ #ifndef quantlib_default_event_hpp #define quantlib_default_event_hpp #include <ql/event.hpp> #include <ql/currency.hpp> #include <ql/math/comparison.hpp> #include <ql/experimental/credit/defaulttype.hpp> #include <ql/experimental/credit/defaultprobabilitykey.hpp> #include <map> namespace QuantLib { /** @class DefaultEvent @brief Credit event on a bond of a certain seniority(ies)/currency Represents a credit event affecting all bonds with a given \ seniority and currency. It assumes that all such bonds suffer \ the event simultaneously. Some events affect all seniorities and this has to be encoded through a different set of events of the same event type. The event is an actual realization, not a contractual reference, as such it contains only an atomic type. */ class DefaultEvent : public Event { public: class DefaultSettlement : public Event { public: friend class DefaultEvent; protected: /*! Default settlement events encode the settlement date and the recovery rates for the affected seniorities. Specific events might require different sets of recoveries to be present. The way these objects are constructed is a prerogative of the particular event class. */ DefaultSettlement(const Date& date, const std::map<Seniority, Real>& recoveryRates); /*! When NoSeniority is passed all seniorities are assumed to have settled to the recovery passed. */ DefaultSettlement(const Date& date = Date(), Seniority seniority = NoSeniority, Real recoveryRate = 0.4); public: Date date() const override; /*! Returns the recovery rate of a default event which has already settled. */ Real recoveryRate(Seniority sen) const; void accept(AcyclicVisitor&) override; private: Date settlementDate_; //! Realized recovery rates std::map<Seniority, Real> recoveryRates_; }; private: // for some reason, gcc chokes on the default parameter below // unless we use the typedef typedef std::map<Seniority, Real> rate_map; public: /*! Credit event with optional settlement information. Represents a credit event that has taken place. Realized events are of an atomic type. If the settlement information is given seniorities present are the seniorities/bonds affected by the event. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), const std::map<Seniority, Real>& recoveryRates = rate_map()); /*! Use NoSeniority to settle to all seniorities with that recovery. In that case the event is assumed to have affected all seniorities. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), Real recoveryRate = 0.4); Date date() const override; bool isRestructuring() const { return eventType_.isRestructuring(); } bool isDefault() const { return !isRestructuring();} bool hasSettled() const { return defSettlement_.date() != Null<Date>(); } const DefaultSettlement& settlement() const { return defSettlement_; } const DefaultType& defaultType() const { return eventType_; } //! returns the currency of the bond this event refers to. const Currency& currency() const { return bondsCurrency_; } //! returns the seniority of the bond that triggered the event. Seniority eventSeniority() const { return bondsSeniority_; } /*! returns a value if the event lead to a settlement for the requested seniority. Specializations on the default atomics and recoveries could change the default policy. */ virtual Real recoveryRate(Seniority seniority) const { if(hasSettled()) { return defSettlement_.recoveryRate(seniority); } return Null<Real>(); } /*! matches the event if this event would trigger a contract related to the requested event type. Notice the contractual event types are not neccesarily atomic. Notice it does not check seniority or currency only event type. typically used from Issuer */ virtual bool matchesEventType( const ext::shared_ptr<DefaultType>& contractEvType) const { // remember we are made of an atomic type. // behaviour by default... return contractEvType->containsRestructuringType( eventType_.restructuringType()) && contractEvType->containsDefaultType( eventType_.defaultType()); } /*! Returns true if this event would trigger a contract with the arguments characteristics. */ virtual bool matchesDefaultKey(const DefaultProbKey& contractKey) const; void accept(AcyclicVisitor&) override; protected: Currency bondsCurrency_; Date defaultDate_; DefaultType eventType_; Seniority bondsSeniority_; DefaultSettlement defSettlement_; }; /*! Two credit events are the same independently of their settlement member data. This has the side effect of overwritting different settlements from the same credit event when, say, inserting in a map. But on the other hand one given event can only have one settlement. This means we can not have two restructuring events on a bond on the same date. */ bool operator==(const DefaultEvent& lhs, const DefaultEvent& rhs); inline bool operator!=(const DefaultEvent& lhs, const DefaultEvent& rhs) { return !(lhs == rhs); } template<> struct earlier_than<DefaultEvent> { bool operator()(const DefaultEvent& e1, const DefaultEvent& e2) const { return e1.date() < e2.date(); } }; // ------------------------------------------------------------------------ class FailureToPayEvent : public DefaultEvent { public: FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, Real recoveryRates); Real amountDefaulted() const {return defaultedAmount_;} bool matchesEventType(const ext::shared_ptr<DefaultType>& contractEvType) const override; private: Real defaultedAmount_; }; // ------------------------------------------------------------------------ class BankruptcyEvent : public DefaultEvent { public: BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, // means same for all Real recoveryRates); //! This is a stronger than all event and will trigger all of them. bool matchesEventType(const ext::shared_ptr<DefaultType>&) const override { return true; } }; } #endif
9,908
2,379
#include <stdexcept> #include <string> #include <sstream> #ifndef ARC_EXCEPTIONS_HPP #define ARC_EXCEPTIONS_HPP #define throw_arc_exception(type, ...) arc_exceptions::ArcException<type>(__FILE__, __LINE__, __VA_ARGS__) namespace arc_exceptions { template <typename ExceptionType> inline void ArcException(const char* file, const std::size_t line, const std::string& message) { std::ostringstream stream; stream << message << ": " << file << ": " << line; throw ExceptionType(stream.str()); } } #endif // ARC_EXCEPTIONS_HPP
564
192
#include "runtime/allocators/FreeListAllocator.h" #include <fmt/format.h> #include <cassert> #include <unistd.h> using namespace Shiny; using namespace Shiny::FreeListImpl; //------------------------------------------------------------------------------ FreeListAllocator::~FreeListAllocator() { reset(); } //------------------------------------------------------------------------------ void* FreeListAllocator::allocate(size_t requestedSizeInBytes) { // Support zero sized byte allocations by rounding up to one. auto sizeInBytes = (requestedSizeInBytes > 0 ? requestedSizeInBytes : 1); // Ensure the requested allocation size is rounded up to the nearest aligned // size. auto alignedSizeInBytes = align(sizeInBytes); // Search for an available free block to reuse before allocating a new block. auto block = findFreeBlock(alignedSizeInBytes); if (block == nullptr) { // No free block found - allocate a new block for this request. block = allocateBlock(alignedSizeInBytes); byteCount_ += requestedSizeInBytes; // Track the original requested byte count. // Set the start of the heap to this block if the heap hasn't been // initialized (ie this is the first allocation). if (heapRoot_ == nullptr) { heapRoot_ = block; } // Append the block to the back of the heap so it can be tracked. if (heapBack_ != nullptr) { heapBack_->next = block; } heapBack_ = block; } // Mark block as being used before returning the payload poriton back to the // caller. block->isUsed = true; return reinterpret_cast<void*>(block->data); } //------------------------------------------------------------------------------ Block* FreeListAllocator::allocateBlock(size_t sizeInBytes) { assert(sizeInBytes > 0); // Get a pointer to the current heap break (end of the heap). This will be the // beginning position of our newly allocated block. auto block = reinterpret_cast<Block*>(sbrk(0)); // Bump the heap break by the number of bytes required for this allocation, // and check for a failed allocation after doing this. auto actualSizeInBytes = getAllocationSizeInBytes(sizeInBytes); if (sbrk(actualSizeInBytes) == reinterpret_cast<void*>(-1)) { throw OutOfMemoryException( fmt::format( "Allocation {} bytes failed because out of memory", sizeInBytes), EXCEPTION_CALLSITE_ARGS); } // Initialize header. block->sizeInBytes = sizeInBytes; block->isUsed = true; block->next = nullptr; // Update statistics before returning the block. blockCount_++; actualByteCount_ += actualSizeInBytes; return block; } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFreeBlock(size_t sizeInBytes) { return findFirstFreeFitBlock(sizeInBytes); } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFirstFreeFitBlock(size_t sizeInBytes) { // Search begins where the last block was allocated, or at the start of the // heap if this is the first find. if (findStart_ == nullptr) { findStart_ = heapRoot_; } // Look for the first block that can fit the request. // O(n) linear search. auto block = findStart_; while (block != nullptr) { // Check if this block is free and of the right size to be re-used. if (!block->isUsed && block->sizeInBytes >= sizeInBytes) { findStart_ = block; return block; } // Break out once we reach the block where the start began. if (block->next == findStart_ || (block->next == nullptr && findStart_ == heapRoot_)) { break; } // Move to the next block, or go back to the start if we've reached the end // of the heap. if (block->next == nullptr) { block = heapRoot_; } else { block = block->next; } } // Failed to find a block. return nullptr; } //------------------------------------------------------------------------------ void FreeListAllocator::destroy(void* userPointer) { // Nothing needs to be done when destroying a null pointer. if (userPointer == nullptr) { return; } freeBlock(getHeader(userPointer)); } //------------------------------------------------------------------------------ void FreeListAllocator::reset() { // Nothing to do if already reset. if (heapRoot_ == nullptr) { return; } // Check if blocks should be freed before reset. if (freeBeforeReset_) { freeHeap(); } // Reset the program data segment pointer back to where it was prior to any // allocation by this allocator. // TODO: Switch to mmap to enable multiple concurrent heaps. brk(heapRoot_); heapRoot_ = nullptr; heapBack_ = nullptr; findStart_ = nullptr; blockCount_ = 0; byteCount_ = 0; actualByteCount_ = 0; } //------------------------------------------------------------------------------ void FreeListAllocator::freeHeap() { auto block = heapRoot_; while (block != nullptr) { auto nextBlock = block->next; if (block->isUsed) { freeBlock(block); } block = nextBlock; } // TODO: Return the used space back to the operating system. // (probably once we switch to mmap). } //------------------------------------------------------------------------------ void FreeListAllocator::freeBlock(Block* block) { assert(block != nullptr); // Don't let a block be freed more than once. if (!block->isUsed) { throw DoubleFreeException( reinterpret_cast<void*>(block->data), EXCEPTION_CALLSITE_ARGS); } // Mark as free to let allocator reuse the block. block->isUsed = false; // Clear memory contents if requested. if (clearAfterFree_) { memset(reinterpret_cast<void*>(block->data), 0xC0FEFE, block->sizeInBytes); } } //------------------------------------------------------------------------------ const Block* FreeListAllocator::getHeader(void* userPointer) const { return reinterpret_cast<const Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ Block* FreeListAllocator::getHeader(void* userPointer) { return reinterpret_cast<Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ size_t FreeListAllocator::getAllocationSizeInBytes(size_t userSizeInBytes) { // Since the block structure includes the first word of user data (C++ // doesn't allow zero sized arrays), we subtract it from the size request. return userSizeInBytes + sizeof(Block) - sizeof(std::declval<Block>().data); }
6,798
1,943
// // Copyright 2014 Dropbox, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #pragma once #include <cassert> #include <exception> #include <memory> #include <mutex> #include <string> #include <unordered_map> #include <jni.h> // work-around for missing noexcept and constexpr support in MSVC prior to 2015 #if (defined _MSC_VER) && (_MSC_VER < 1900) # define noexcept _NOEXCEPT # define constexpr #endif /* * Djinni support library */ // jni.h should really put extern "C" in JNIEXPORT, but it doesn't. :( #define CJNIEXPORT extern "C" JNIEXPORT namespace djinni { /* * Global initialization and shutdown. Call these from JNI_OnLoad and JNI_OnUnload. */ void jniInit(JavaVM * jvm); void jniShutdown(); /* * Get the JNIEnv for the invoking thread. Should only be called on Java-created threads. */ JNIEnv * jniGetThreadEnv(); /* * Exception to indicate that a Java exception is pending in the JVM. */ class jni_exception_pending : public std::exception {}; /* * Throw jni_exception_pending if any Java exception is pending in the JVM. */ void jniExceptionCheck(JNIEnv * env); /* * Set an AssertionError in env with message message, and then throw jni_exception_pending. */ #ifdef _MSC_VER __declspec(noreturn) #else __attribute__((noreturn)) #endif void jniThrowAssertionError(JNIEnv * env, const char * file, int line, const char * check); #define DJINNI_ASSERT(check, env) \ do { \ djinni::jniExceptionCheck(env); \ const bool check__res = bool(check); \ djinni::jniExceptionCheck(env); \ if (!check__res) { \ djinni::jniThrowAssertionError(env, __FILE__, __LINE__, #check); \ } \ } while(false) /* * Global and local reference guard objects. * * A GlobalRef<T> is constructed with a local reference; the constructor upgrades the local * reference to a global reference, and the destructor deletes the local ref. * * A LocalRef<T> should be constructed with a new local reference. The local reference will * be deleted when the LocalRef is deleted. */ struct GlobalRefDeleter { void operator() (jobject globalRef) noexcept; }; template <typename PointerType> class GlobalRef : public std::unique_ptr<typename std::remove_pointer<PointerType>::type, GlobalRefDeleter> { public: GlobalRef() {} GlobalRef(GlobalRef && obj) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::GlobalRefDeleter>( std::move(obj) ) {} GlobalRef(JNIEnv * env, PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::GlobalRefDeleter>( static_cast<PointerType>(env->NewGlobalRef(localRef)), ::djinni::GlobalRefDeleter{} ) {} }; struct LocalRefDeleter { void operator() (jobject localRef) noexcept; }; template <typename PointerType> class LocalRef : public std::unique_ptr<typename std::remove_pointer<PointerType>::type, LocalRefDeleter> { public: LocalRef() {} LocalRef(JNIEnv * /*env*/, PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, ::djinni::LocalRefDeleter>( localRef) {} explicit LocalRef(PointerType localRef) : std::unique_ptr<typename std::remove_pointer<PointerType>::type, LocalRefDeleter>( localRef) {} }; /* * Helper for JniClassInitializer. Copied from Oxygen. */ template <class Key, class T> class static_registration { public: using registration_map = std::unordered_map<Key, T *>; static registration_map get_all() { const std::lock_guard<std::mutex> lock(get_mutex()); return get_map(); } static_registration(const Key & key, T * obj) : m_key(key) { const std::lock_guard<std::mutex> lock(get_mutex()); get_map().emplace(key, obj); } ~static_registration() { const std::lock_guard<std::mutex> lock(get_mutex()); get_map().erase(m_key); } private: const Key m_key; static registration_map & get_map() { static registration_map m; return m; } static std::mutex & get_mutex() { static std::mutex mtx; return mtx; } }; /* * Helper for JniClass. (This can't be a subclass because it needs to not be templatized.) */ class JniClassInitializer { private: using Registration = static_registration<void *, const JniClassInitializer>; const std::function<void()> init; const Registration reg; JniClassInitializer(const std::function<void()> & init) : init(init), reg(this, this) {} template <class C> friend class JniClass; friend void jniInit(JavaVM *); }; /* * Each instantiation of this template produces a singleton object of type C which * will be initialized by djinni::jniInit(). For example: * * struct JavaFooInfo { * jmethodID foo; * JavaFooInfo() // initialize clazz and foo from jniGetThreadEnv * } * * To use this in a JNI function or callback, invoke: * * CallVoidMethod(object, JniClass<JavaFooInfo>::get().foo, ...); * * This uses C++'s template instantiation behavior to guarantee that any T for which * JniClass<T>::get() is *used* anywhere in the program will be *initialized* by init_all(). * Therefore, it's always safe to compile in wrappers for all known Java types - the library * will only depend on the presence of those actually needed. */ template <class C> class JniClass { public: static const C & get() { (void)s_initializer; // ensure that initializer is actually instantiated assert(s_singleton); return *s_singleton; } private: static const JniClassInitializer s_initializer; static std::unique_ptr<C> s_singleton; static void allocate() { // We can't use make_unique here, because C will have a private constructor and // list JniClass as a friend; so we have to allocate it by hand. s_singleton = std::unique_ptr<C>(new C()); } }; template <class C> const JniClassInitializer JniClass<C>::s_initializer ( allocate ); template <class C> std::unique_ptr<C> JniClass<C>::s_singleton; /* * Exception-checking helpers. These will throw if an exception is pending. */ GlobalRef<jclass> jniFindClass(const char * name); jmethodID jniGetStaticMethodID(jclass clazz, const char * name, const char * sig); jmethodID jniGetMethodID(jclass clazz, const char * name, const char * sig); jfieldID jniGetFieldID(jclass clazz, const char * name, const char * sig); /* * Helper for maintaining shared_ptrs to wrapped Java objects. * * This is used for automatically wrapping a Java object that exposes some interface * with a C++ object that calls back into the JVM, such as a listener. Calling * JavaProxyCache<T>::get(jobj, ...) the first time will construct a T and return a * shared_ptr to it, and also save a weak_ptr to the new object internally. The constructed * T contains a strong GlobalRef to jobj. As long as something in C++ maintains a strong * reference to the wrapper, future calls to get(jobj) will return the *same* wrapper object. * * Java | C++ * | ________________________ ___________ * _____________ | | | | | * | | | | JniImplFooListener | <=========== | Foo | * | FooListener | <============ | : public FooListener, | shared_ptr |___________| * |_____________| GlobalRef | JavaProxyCacheEntry | * | |________________________| * | ^ ______________________ * | \ | | * | - - - - - - | JavaProxyCache | * | weak_ptr | <JniImplFooListener> | * | |______________________| * * As long as the C++ FooListener has references, the Java FooListener is kept alive. * * We use a custom unordered_map with Java objects (jobject) as keys, and JNI object * identity and hashing functions. This means that as long as a key is in the map, * we must have some other GlobalRef keeping it alive. To ensure safety, the Entry * destructor removes *itself* from the map - destruction order guarantees that this * will happen before the contained global reference becomes invalid (by destruction of * the GlobalRefGuard). */ /* * Look up an entry in the global JNI wrapper cache. If none is found, create one with factory, * save it, and return it. * * The contract of `factory` is: The parameter to factory is a local ref. The factory returns * a shared_ptr to the object (JniImplFooListener, in the diagram above), as well as the * jobject *global* ref contained inside. */ std::shared_ptr<void> javaProxyCacheLookup(jobject obj, std::pair<std::shared_ptr<void>, jobject>(*factory)(jobject)); class JavaProxyCacheEntry { public: jobject getGlobalRef() { return m_globalRef.get(); } protected: JavaProxyCacheEntry(jobject localRef, JNIEnv * env); // env used only for construction JavaProxyCacheEntry(jobject localRef); virtual ~JavaProxyCacheEntry() noexcept; JavaProxyCacheEntry(const JavaProxyCacheEntry & other) = delete; JavaProxyCacheEntry & operator=(const JavaProxyCacheEntry & other) = delete; private: const GlobalRef<jobject> m_globalRef; }; template <class T> class JavaProxyCache { public: using Entry = JavaProxyCacheEntry; static std::pair<std::shared_ptr<void>, jobject> factory(jobject obj) { std::shared_ptr<T> ret = std::make_shared<T>(obj); return { ret, ret->getGlobalRef() }; } /* * Check whether a wrapped T exists for obj. If one is found, return it; if not, * construct a new one with obj, save it, and return it. */ static std::shared_ptr<T> get(jobject obj) { static_assert(std::is_base_of<JavaProxyCacheEntry, T>::value, "JavaProxyCache can only be used with T if T derives from Entry<T>"); return std::static_pointer_cast<T>(javaProxyCacheLookup(obj, &factory)); } }; /* * Cache for CppProxy objects. This is the inverse of the JavaProxyCache mechanism above, * ensuring that each time we pass an interface from Java to C++, we get the *same* CppProxy * object on the Java side: * * Java | C++ * | * ______________ | ________________ ___________ * | | | | | | | * | Foo.CppProxy | ------------> | CppProxyHandle | =============> | Foo | * |______________| (jlong) | <Foo> | (shared_ptr) |___________| * ^ | |________________| * \ | * _________ | __________________ * | | | | | * | WeakRef | <------------------------- | jniCppProxyCache | * |_________| (GlobalRef) |__________________| * | * * We don't use JNI WeakGlobalRef objects, because they last longer than is safe - a * WeakGlobalRef can still be upgraded to a strong reference even during finalization, which * leads to use-after-free. Java WeakRefs provide the right lifetime guarantee. */ /* * Information needed to use a CppProxy class. * * In an ideal world, this object would be properly always-valid RAII, and we'd use an * optional<CppProxyClassInfo> where needed. Unfortunately we don't want to depend on optional * here, so this object has an invalid state and default constructor. */ struct CppProxyClassInfo { const GlobalRef<jclass> clazz; const jmethodID constructor; const jfieldID idField; CppProxyClassInfo(const char * className); CppProxyClassInfo(); ~CppProxyClassInfo(); // Validity check explicit operator bool() const { return bool(clazz); } }; /* * Proxy cache implementation. These functions are used by CppProxyHandle::~CppProxyHandle() * and JniInterface::_toJava, respectively. They're declared in a separate class to avoid * having to templatize them. This way, all the map lookup code is only generated once, * rather than once for each T, saving substantially on binary size. (We do something simiar * in the other direction too; see javaProxyCacheLookup() above.) * * The data used by this class is declared only in djinni_support.cpp, since it's global and * opaque to all other code. */ class JniCppProxyCache { private: template <class T> friend class CppProxyHandle; static void erase(void * key); template <class I, class Self> friend class JniInterface; static jobject get(const std::shared_ptr<void> & cppObj, JNIEnv * jniEnv, const CppProxyClassInfo & proxyClass, jobject (*factory)(const std::shared_ptr<void> &, JNIEnv *, const CppProxyClassInfo &)); /* This "class" is basically a namespace, to make clear that get() and erase() should only * be used by the helper infrastructure below. */ JniCppProxyCache() = delete; }; template <class T> class CppProxyHandle { public: CppProxyHandle(std::shared_ptr<T> obj) : m_obj(move(obj)) {} ~CppProxyHandle() { JniCppProxyCache::erase(m_obj.get()); } static const std::shared_ptr<T> & get(jlong handle) { return reinterpret_cast<const CppProxyHandle<T> *>(handle)->m_obj; } private: const std::shared_ptr<T> m_obj; }; /* * Base class for Java <-> C++ interface adapters. * * I is the C++ base class (interface) being adapted; Self is the interface adapter class * derived from JniInterface (using CRTP). For example: * * class NativeToken final : djinni::JniInterface<Token, NativeToken> { ... } */ template <class I, class Self> class JniInterface { public: /* * Given a C++ object, find or create a Java version. The cases here are: * 1. Null * 2. The provided C++ object is actually a JavaProxy (C++-side proxy for Java impl) * 3. The provided C++ object has an existing CppProxy (Java-side proxy for C++ impl) * 4. The provided C++ object needs a new CppProxy allocated */ jobject _toJava(JNIEnv* jniEnv, const std::shared_ptr<I> & c) const { // Case 1 - null if (!c) { return nullptr; } // Case 2 - already a JavaProxy. Only possible if Self::JavaProxy exists. if (jobject impl = _unwrapJavaProxy<Self>(&c)) { return jniEnv->NewLocalRef(impl); } // Cases 3 and 4. assert(m_cppProxyClass); return JniCppProxyCache::get(c, jniEnv, m_cppProxyClass, &newCppProxy); } /* * Given a Java object, find or create a C++ version. The cases here are: * 1. Null * 2. The provided Java object is actually a CppProxy (Java-side proxy for a C++ impl) * 3. The provided Java object has an existing JavaProxy (C++-side proxy for a Java impl) * 4. The provided Java object needs a new JavaProxy allocated */ std::shared_ptr<I> _fromJava(JNIEnv* jniEnv, jobject j) const { // Case 1 - null if (!j) { return nullptr; } // Case 2 - already a Java proxy; we just need to pull the C++ impl out. (This case // is only possible if we were constructed with a cppProxyClassName parameter.) if (m_cppProxyClass && jniEnv->IsSameObject(jniEnv->GetObjectClass(j), m_cppProxyClass.clazz.get())) { jlong handle = jniEnv->GetLongField(j, m_cppProxyClass.idField); jniExceptionCheck(jniEnv); return CppProxyHandle<I>::get(handle); } // Cases 3 and 4 - see _getJavaProxy helper below. JavaProxyCache is responsible for // distinguishing between the two cases. Only possible if Self::JavaProxy exists. return _getJavaProxy<Self>(j); } // Constructor for interfaces for which a Java-side CppProxy class exists JniInterface(const char * cppProxyClassName) : m_cppProxyClass(cppProxyClassName) {} // Constructor for interfaces without a Java proxy class JniInterface() : m_cppProxyClass{} {} private: /* * Helpers for _toJava above. The possibility that an object is already a C++-side proxy * only exists if the code generator emitted one (if Self::JavaProxy exists). */ template <typename S, typename = typename S::JavaProxy> jobject _unwrapJavaProxy(const std::shared_ptr<I> * c) const { if (auto proxy = dynamic_cast<typename S::JavaProxy *>(c->get())) { return proxy->getGlobalRef(); } else { return nullptr; } } template <typename S> jobject _unwrapJavaProxy(...) const { return nullptr; } /* * Helper for _toJava above: given a C++ object, allocate a CppProxy on the Java side for * it. This is actually called by jniCppProxyCacheGet, which holds a lock on the global * C++-to-Java proxy map object. */ static jobject newCppProxy(const std::shared_ptr<void> & cppObj, JNIEnv * jniEnv, const CppProxyClassInfo & proxyClass) { std::unique_ptr<CppProxyHandle<I>> to_encapsulate( new CppProxyHandle<I>(std::static_pointer_cast<I>(cppObj))); jlong handle = static_cast<jlong>(reinterpret_cast<uintptr_t>(to_encapsulate.get())); jobject cppProxy = jniEnv->NewObject(proxyClass.clazz.get(), proxyClass.constructor, handle); jniExceptionCheck(jniEnv); to_encapsulate.release(); return cppProxy; } /* * Helpers for _fromJava above. We can only produce a C++-side proxy if the code generator * emitted one (if Self::JavaProxy exists). */ template <typename S, typename = typename S::JavaProxy> std::shared_ptr<I> _getJavaProxy(jobject j) const { return JavaProxyCache<typename S::JavaProxy>::get(j); } template <typename S> std::shared_ptr<I> _getJavaProxy(...) const { assert(false); return nullptr; } const CppProxyClassInfo m_cppProxyClass; }; /* * Guard object which automatically begins and ends a JNI local frame when * it is created and destroyed, using PushLocalFrame and PopLocalFrame. * * Local frame creation can fail. The throwOnError parameter specifies how * errors are reported: * - true (default): throws on failure * - false: queues a JNI exception on failure; the user must call checkSuccess() * * The JNIEnv given at construction is expected to still be valid at * destruction, so this class isn't suitable for use across threads. * It is intended for use on the stack. * * All JNI local references created within the defined scope will be * released at the end of the scope. This class doesn't support * the jobject return value supported by PopLocalFrame(), because * the destructor cannot return the new reference value for the parent * frame. */ class JniLocalScope { public: /* * Create the guard object and begin the local frame. * * @param p_env the JNIEnv for the current thread. * @param capacity the initial number of local references to * allocate. */ JniLocalScope(JNIEnv* p_env, jint capacity, bool throwOnError = true); bool checkSuccess() const { return m_success; } ~JniLocalScope(); private: JniLocalScope(const JniLocalScope& other); JniLocalScope& operator=(const JniLocalScope& other); static bool _pushLocalFrame(JNIEnv* const env, jint capacity); static void _popLocalFrame(JNIEnv* const env, jobject returnRef); JNIEnv* const m_env; const bool m_success; }; jstring jniStringFromUTF8(JNIEnv * env, const std::string & str); std::string jniUTF8FromString(JNIEnv * env, const jstring jstr); class JniEnum { public: /* * Given a Java object, find its numeric value. This returns a jint, which the caller can * static_cast<> into the necessary C++ enum type. */ jint ordinal(JNIEnv * env, jobject obj) const; /* * Create a Java value of the wrapped class with the given value. */ LocalRef<jobject> create(JNIEnv * env, jint value) const; protected: JniEnum(const std::string & name); private: const GlobalRef<jclass> m_clazz; const jmethodID m_staticmethValues; const jmethodID m_methOrdinal; }; #define DJINNI_FUNCTION_PROLOGUE0(env_) #define DJINNI_FUNCTION_PROLOGUE1(env_, arg1_) // Helper for JNI_TRANSLATE_EXCEPTIONS_RETURN. Do not call directly. void jniSetPendingFromCurrent(JNIEnv * env, const char * ctx) noexcept; /* Catch C++ exceptions and translate them to Java exceptions. * * All functions called by Java must be fully wrapped by an outer try...catch block like so: * * try { * ... * } JNI_TRANSLATE_EXCEPTIONS_RETURN(env, 0) * ... or JNI_TRANSLATE_EXCEPTIONS_RETURN(env, ) for functions returning void * * The second parameter is a default return value to be used if an exception is caught and * converted. (For JNI outer-layer calls, this result will always be ignored by JNI, so * it can safely be 0 for any function with a non-void return value.) */ #define JNI_TRANSLATE_EXCEPTIONS_RETURN(env, ret) \ catch (const std::exception &) { \ ::djinni::jniSetPendingFromCurrent(env, __func__); \ return ret; \ } } // namespace djinni
22,473
6,527
#ifndef LT_MATH_HPP #define LT_MATH_HPP #include <stdio.h> #include <cmath> #include <iostream> #include <iomanip> #include <cstring> #include <type_traits> #include <limits> #include "lt_core.hpp" #include "math.h" #ifndef LT_PI #define LT_PI 3.14159265358979323846 #endif struct Point3f { f32 x, y, z; explicit Point3f(f32 x, f32 y, f32 z) : x(x), y(y), z(z) {} }; struct Size2f { f32 width, height; explicit Size2f(f32 width, f32 height) : width(width), height(height) {} }; template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, T epsilon = std::numeric_limits<T>::epsilon()) { // http://realtimecollisiondetection.net/blog/?p=89 bool almost = std::abs(x - y) <= epsilon * std::max(std::max(static_cast<T>(1), std::abs(x)), std::abs(y)); return almost; } ///////////////////////////////////////////////////////// // // Vector2 // // Definition of a vector structure. // template<typename T> union Vec2 { T val[2]; struct { T x, y; }; Vec2(): x(0), y(0) {} explicit Vec2(T k): x(k), y(k) {} explicit Vec2(T x, T y): x(x), y(y) {} inline Vec2<T> operator-(Vec2<T> rhs) const {return Vec2<T>(x - rhs.x, y - rhs.y);} }; template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f32 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f64 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator+(const Vec2<T> &a, const Vec2<T> &b) { return Vec2<T>(a.x + b.x, a.y + b.y); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec2<T> &v) { os << "(" << v.x << ", " << v.y << ")"; return os; } ///////////////////////////////////////////////////////// // // Vector3 // // Definition of a vector structure. // template<typename T> union Vec4; template<typename T> struct Vec3 { union { T val[3]; struct { T x, y, z; }; struct { T r, g, b; }; struct { T i, j, k; }; struct { Vec2<T> xy; f32 _ignored_z; }; struct { f32 _ignored_x; Vec2<T> yz; }; }; Vec3() noexcept : x(0), y(0), z(0) {} explicit Vec3(T val) noexcept : x(val), y(val), z(val) {} explicit Vec3(T x, T y, T z) noexcept : x(x), y(y), z(z) {} explicit Vec3(Vec4<T> v) noexcept : x(v.x), y(v.y), z(v.z) {} explicit Vec3(Vec2<T> v, T z) noexcept : x(v.x), y(v.y), z(z) {} inline Vec3<T> operator-(const Vec3<T>& rhs) const { return Vec3<T>(x-rhs.x, y-rhs.y, z-rhs.z); } inline Vec3<T> operator-() const { return Vec3<T>(-x, -y, -z); } inline Vec3<T> operator+(const Vec3<T>& rhs) const { return Vec3<T>(x+rhs.x, y+rhs.y, z+rhs.z); } inline Vec2<T> xz() const { return Vec2<T>(x, z); } inline void operator-=(const Vec3<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; } inline void operator+=(const Vec3<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; } }; template<typename T> inline bool operator==(const Vec3<T> &a, const Vec3<T> &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } template<> inline bool operator==<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<> inline bool operator==<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<typename T> inline bool operator!=(const Vec3<T> &a, const Vec3<T> &b) { return a.x != b.x && a.y != b.y && a.z != b.z; } template<> inline bool operator!=<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<> inline bool operator!=<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec3<T> &v) { os << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return os; } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f32 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f32 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f64 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f64 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } ///////////////////////////////////////////////////////// // // Vector4 // // Definition of a vector structure. // template<typename T> union Vec4 { T val[4]; struct { T x, y, z, w; }; struct { T r, g, b, a; }; Vec4(): x(0), y(0), z(0), w(0) {} explicit Vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {} explicit Vec4(const Vec3<T>& v, T w): x(v.x), y(v.y), z(v.z), w(w) {} }; namespace lt { template<typename T> inline T norm(const Vec4<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); } template<typename T> inline T norm(const Vec3<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } template<typename T> inline T norm(const Vec2<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y); } template<typename T> inline Vec2<T> normalize(const Vec2<T>& v) { return Vec2<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v)); } template<typename T> inline Vec3<T> normalize(const Vec3<T>& v) { const f32 EPSILON = 0.0001f; f32 length = lt::norm(v); if (length <= EPSILON) return v; return Vec3<T>(v.x/length, v.y/length, v.z/length); } template<typename T> inline Vec4<T> normalize(const Vec4<T>& v) { return Vec4<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v), v.w /lt::norm(v)); } template<typename T> inline T radians(T angle) { return angle * (static_cast<T>(M_PI) / static_cast<T>(180)); } template<typename T> inline T degrees(T angle) { return angle * (static_cast<T>(180) / static_cast<T>(M_PI)); } template<typename T> inline T dot(const Vec2<T>& a, const Vec2<T>& b) { return (a.x * b.x) + (a.y * b.y); } template<typename T> inline T dot(const Vec3<T>& lhs, const Vec3<T>& rhs) { return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z); } template<typename T> inline Vec2<T> projection(const Vec2<T>& p, const Vec2<T>& plane) { f32 alpha = lt::dot(p, plane) / lt::dot(plane, plane); return alpha * plane; } template<typename T> inline Vec3<T> cross(const Vec3<T>& a, const Vec3<T>& b) { return Vec3<T>((a.y * b.z) - (a.z * b.y), (a.z * b.x) - (a.x * b.z), (a.x * b.y) - (a.y * b.x)); } } ///////////////////////////////////////////////////////// // // Matrix // // Column major // union Mat4f { Mat4f(); explicit Mat4f(f32 diag); explicit Mat4f(f32 m00, f32 m01, f32 m02, f32 m03, f32 m10, f32 m11, f32 m12, f32 m13, f32 m20, f32 m21, f32 m22, f32 m23, f32 m30, f32 m31, f32 m32, f32 m33); inline f32 operator()(isize row, isize col) const { return m_col[col].val[row]; } inline f32& operator()(isize row, isize col) { return m_col[col].val[row]; } inline Vec4<f32> col(isize col) { return m_col[col]; } inline f32 *data() const { return (f32*)&m_col[0].val[0]; } Mat4f operator*(const Mat4f& rhs); private: Vec4<f32> m_col[4]; }; inline std::ostream &operator<<(std::ostream& os, const Mat4f &mat) { for (i32 row = 0; row < 4; row++) { os << "| "; for (i32 col = 0; col < 4; col++) { os << std::setw(9) << std::setprecision(3) << mat(row, col) << " "; } os << "|\n"; } return os; } inline Mat4f operator*(const Mat4f &lhs, const Mat4f &rhs) { Mat4f ret(1.0); // First row ret(0,0) = lhs(0,0)*rhs(0,0) + lhs(0,1)*rhs(1,0) + lhs(0,2)*rhs(2,0) + lhs(0,3)*rhs(3,0); ret(0,1) = lhs(0,0)*rhs(0,1) + lhs(0,1)*rhs(1,1) + lhs(0,2)*rhs(2,1) + lhs(0,3)*rhs(3,1); ret(0,2) = lhs(0,0)*rhs(0,2) + lhs(0,1)*rhs(1,2) + lhs(0,2)*rhs(2,2) + lhs(0,3)*rhs(3,2); ret(0,3) = lhs(0,0)*rhs(0,3) + lhs(0,1)*rhs(1,3) + lhs(0,2)*rhs(2,3) + lhs(0,3)*rhs(3,3); // Second row ret(1,0) = lhs(1,0)*rhs(0,0) + lhs(1,1)*rhs(1,0) + lhs(1,2)*rhs(2,0) + lhs(1,3)*rhs(3,0); ret(1,1) = lhs(1,0)*rhs(0,1) + lhs(1,1)*rhs(1,1) + lhs(1,2)*rhs(2,1) + lhs(1,3)*rhs(3,1); ret(1,2) = lhs(1,0)*rhs(0,2) + lhs(1,1)*rhs(1,2) + lhs(1,2)*rhs(2,2) + lhs(1,3)*rhs(3,2); ret(1,3) = lhs(1,0)*rhs(0,3) + lhs(1,1)*rhs(1,3) + lhs(1,2)*rhs(2,3) + lhs(1,3)*rhs(3,3); // Third row ret(2,0) = lhs(2,0)*rhs(0,0) + lhs(2,1)*rhs(1,0) + lhs(2,2)*rhs(2,0) + lhs(2,3)*rhs(3,0); ret(2,1) = lhs(2,0)*rhs(0,1) + lhs(2,1)*rhs(1,1) + lhs(2,2)*rhs(2,1) + lhs(2,3)*rhs(3,1); ret(2,2) = lhs(2,0)*rhs(0,2) + lhs(2,1)*rhs(1,2) + lhs(2,2)*rhs(2,2) + lhs(2,3)*rhs(3,2); ret(2,3) = lhs(2,0)*rhs(0,3) + lhs(2,1)*rhs(1,3) + lhs(2,2)*rhs(2,3) + lhs(2,3)*rhs(3,3); // Fourth row ret(3,0) = lhs(3,0)*rhs(0,0) + lhs(3,1)*rhs(1,0) + lhs(3,2)*rhs(2,0) + lhs(3,3)*rhs(3,0); ret(3,1) = lhs(3,0)*rhs(0,1) + lhs(3,1)*rhs(1,1) + lhs(3,2)*rhs(2,1) + lhs(3,3)*rhs(3,1); ret(3,2) = lhs(3,0)*rhs(0,2) + lhs(3,1)*rhs(1,2) + lhs(3,2)*rhs(2,2) + lhs(3,3)*rhs(3,2); ret(3,3) = lhs(3,0)*rhs(0,3) + lhs(3,1)*rhs(1,3) + lhs(3,2)*rhs(2,3) + lhs(3,3)*rhs(3,3); return ret; } namespace lt { Mat4f perspective(f32 fovy, f32 aspect_ratio, f32 znear, f32 zfar); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top, f32 near, f32 far); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top); Mat4f look_at(const Vec3<f32> eye, const Vec3<f32> center, const Vec3<f32> up); Mat4f translation(const Mat4f &in_mat, Vec3<f32> amount); Mat4f scale(const Mat4f &in_mat, Vec3<f32> scale); inline Mat4f rotation_x(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(1, 0, 0, 0, 0, cos(rad), -sin(rad), 0, 0, sin(rad), cos(rad), 0, 0, 0, 0, 1); } inline Mat4f rotation_y(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(cos(rad), 0, sin(rad), 0, 0, 1, 0, 0, -sin(rad), 0, cos(rad), 0, 0, 0, 0, 1); } } ///////////////////////////////////////////////////////// // // Quaternion // // Definition of a quaternion structure. // // Some properties (not necessarily complete): // - Not comutative (q1q2 != q2q1) // - Associative ((q1q2)q3 == q1(q2q3)) // - The quaternion (1, 0, 0, 0) maps to the identity matrix. // template<typename T> union Quat { T val[4]; struct { T s; Vec3<T> v; }; explicit Quat(T s, T i, T j, T k) : val{s, i, j, k} {} explicit Quat(T s, const Vec3<T>& v) : s(s), v(v) {} Quat() : s(0), v(Vec3<T>(0, 0, 0)) {} static inline Quat<T> identity() { return Quat<T>(1, 0, 0, 0); } static inline Quat<T> rotation(T angle, const Vec3<T>& axis) { Vec3<T> sin_axis = axis * std::sin(angle/static_cast<T>(2)); return Quat<T>(std::cos(angle/static_cast<T>(2)), sin_axis); } Mat4f to_mat4() const { return Mat4f(s, -v.i, -v.j, -v.k, v.i, s, -v.k, v.j, v.j, v.k, s, -v.i, v.k, -v.j, v.i, s); } inline Quat<T> operator+(const Quat<T>& rhs) const { return Quat<T>(s+rhs.s, v.i+rhs.v.i, v.j+rhs.v.j, v.k+rhs.v.k); } inline Quat<T> operator/(T k) const { return Quat<T>(val[0]/k, val[1]/k, val[2]/k, val[3]/k); } }; template<typename T> inline Quat<T> operator*(const Quat<T> &q, T k) { return Quat<T>(q.s*k, q.v*k); } template<typename T> inline Quat<T> operator*(T k, const Quat<T> &q) { return Quat<T>(q.s*k, q.v*k); } template<typename T> static inline Quat<T> operator*(const Quat<T>& lhs, const Quat<T>& rhs) { return Quat<T>((lhs.s*rhs.s) - lt::dot(lhs.v, rhs.v), rhs.s*lhs.v + lhs.s*rhs.v + lt::cross(lhs.v, rhs.v)); } template<typename T> inline std::ostream & operator<<(std::ostream &os, const Quat<T> &q) { os << "(" << std::setprecision(3) << q.val[0] << ", "; os << q.val[1] << ", " << q.val[2] << ", " << q.val[3] << ")"; return os; } template<typename T> inline bool operator==(const Quat<T> &a, const Quat<T> &b) { return (a.val[0] == b.val[0]) && (a.val[1] == b.val[1]) && (a.val[2] == b.val[2]) && (a.val[3] == b.val[3]); } template<> inline bool operator==<f32>(const Quat<f32> &a, const Quat<f32> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } template<> inline bool operator==<f64>(const Quat<f64> &a, const Quat<f64> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } namespace lt { template<typename T> inline T norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return std::sqrt(v); } template<typename T> inline T sqr_norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return v; } template<typename T> inline Quat<T> normalize(const Quat<T> &q) { return Quat<T>(q.s/lt::norm(q), q.v.i/lt::norm(q), q.v.j/lt::norm(q), q.v.k/lt::norm(q)); } template<typename T> inline Quat<T> conjugate(const Quat<T> &q) { return Quat<T>(q.s, -q.v); } template<typename T> inline Quat<T> inverse(const Quat<T> &q) { Quat<T> inv = lt::conjugate(q) / lt::sqr_norm(q); LT_Assert(q*inv == Quat<T>::identity()); return inv; } template<typename T> inline Quat<T> rotate(const Quat<T> &q, T angle, const Quat<T> &axis) { const Quat<T> rotor = Quat<T>::rotation(angle, axis.v); return rotor * q * lt::inverse(rotor); } template<typename T> T dot(const Quat<T> &a, const Quat<T> &b) { return a.val[0]*b.val[0] + a.val[1]*b.val[1] + a.val[2]*b.val[2] + a.val[3]*b.val[3]; } template<typename T> Quat<T> slerp(const Quat<T> &start_q, const Quat<T> &end_q, T t) { LT_Assert(t >= 0); LT_Assert(t <= 1); const T EPSILON = static_cast<T>(0.0001); // FIXME: Find a more specific epsilon value here. T start_dot_end = lt::dot(start_q, end_q); if (start_dot_end < 1-EPSILON) { T angle = std::acos(start_dot_end); LT_Assert(angle != static_cast<T>(0)); return (std::sin((static_cast<T>(1) - t) * angle) * start_q + std::sin(t * angle) * end_q) / std::sin(angle); } else { return start_q; } } } typedef Vec2<i32> Vec2i; typedef Vec2<f32> Vec2f; typedef Vec3<i32> Vec3i; typedef Vec3<f32> Vec3f; typedef Vec4<i32> Vec4i; typedef Vec4<f32> Vec4f; typedef Quat<f32> Quatf; typedef Quat<f64> Quatd; #endif // LT_MATH_HPP
15,364
7,369
#include <iostream> using namespace std; #define LINHAS 2 #define COLUNAS 50 void calculeAreas(double triangulos[LINHAS][COLUNAS], double areas[]) { for (int i = 0; i < COLUNAS; i++) { areas[i] = (triangulos[0][i] * triangulos[1][i]) / 2; cout << "A área do " << i + 1 << "º triângulo é " << areas[i] << endl; } } void imprimaMatriz(double matriz[LINHAS][COLUNAS]) { int j = 0; cout << "[" << endl; for (int i = 0; i < LINHAS; i++) { j = 0; cout << "[" << matriz[i][j] << ", "; for (j = 1; j < COLUNAS - 1; j++) { cout << matriz[i][j] << ", "; } cout << matriz[i][j] << "]," << endl; } cout << "]" << endl; } int main() { double matriz[LINHAS][COLUNAS] = { {12, 5, 6, 7, 6, 9, 8, 3, 6, 10, 2, 7, 6, 9, 2, 5, 9, 5, 9, 5, 9, 6, 3, 10, 7, 10, 4, 5, 1, 9, 6, 6, 5, 1, 4, 10, 9, 1, 2, 7, 3, 6, 3, 8, 6, 4, 5, 5, 10, 3}, {23, 8, 10, 5, 8, 7, 4, 3, 1, 4, 3, 8, 2, 7, 1, 5, 6, 1, 8, 10, 7, 10, 7, 9, 9, 2, 5, 3, 8, 4, 7, 8, 2, 9, 2, 1, 5, 5, 3, 7, 1, 5, 4, 4, 3, 4, 10, 10, 7, 7}}; double areas[COLUNAS] = {}; imprimaMatriz(matriz); calculeAreas(matriz, areas); return 0; }
1,190
675
#pragma once #include <string_view> #include <opencv2/opencv.hpp> #include "GeneratorStage.hpp" #include "FilterStage.hpp" #include "ContourDetectionStage.hpp" class ContourPlotStage : public FilterStage { public: ContourPlotStage(GeneratorStage &input, ContourDetectionStage &contour); void Execute(); std::string_view GetStageName() const { return "ContourPlotStage"; }; cv::Mat GetOutputImage() { return output; }; private: cv::Mat output; ContourDetectionStage contour; cv::RNG rng; };
520
169
#include <stack.hpp> #include "iostream" #include "stack2.hpp" class CustomClass { private: int f; double ft; public: CustomClass() { f = -1; ft = -1; } CustomClass(int fi) { f = fi; ft = 0; } CustomClass(int fi, double fth) { f = fi; ft = fth; } bool operator!() const { if (f != -1) { return false; } if (ft != -1) { return false; } return true; }; CustomClass& operator=(CustomClass* right) noexcept { f = right->f; ft = right->ft; return *this; } CustomClass& operator=(const CustomClass& right) = default; void print() const { std::cout << f << " " << ft << std::endl; } std::string getStr() const { std::string a = std::to_string(f) + " " + std::to_string(ft); return a; } }; int main() { // Stack<int> stack; // const int& left = 50; // stack.push(10); // std::cout << stack.head() << std::endl; // // stack.push(20); // std::cout << stack.head() << std::endl; // stack.push(30); // std::cout << stack.head() << std::endl; // stack.push(40); // std::cout << stack.head() << std::endl; // stack.push(left); // std::cout << stack.head() << std::endl; // stack.pop(); // std::cout << stack.head() << std::endl; // stack.pop(); // std::cout << stack.head() << std::endl; // stack.pop(); // std::cout << stack.head() << std::endl; // std::cout << "Stack " << stack.head() << std::endl; // Stack<int> stack1; // stack1.push(333); // std::cout << "Stack1 " << stack1.head() << std::endl; // // Оператор перемещения. // stack1 = Stack<int>(444); // std::cout << "Stack " << stack.head() << std::endl; // std::cout << "Stack1 " << stack1.head() << std::endl; // Stack2<CustomClass> stack2(CustomClass{11 }); // stack2.head().print(); // stack2.push_emplace(22, 22.0); // stack2.head().print(); // stack2.push_emplace(33, 33.0); // stack2.head().print(); // stack2.push_emplace(44, 44.0); // stack2.head().print(); // stack2.push_emplace(55); // stack2.head().print(); // stack2 = Stack2<CustomClass>(123); // stack2.push_emplace(2223, 2223.0); // stack2.push_emplace(3354, 3354.0); // stack2.head().print(); // std::string a = stack2.head().getStr(); // std::cout << a << std::endl; }
2,308
946
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/macie2/model/IpAddressDetails.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Macie2 { namespace Model { IpAddressDetails::IpAddressDetails() : m_ipAddressV4HasBeenSet(false), m_ipCityHasBeenSet(false), m_ipCountryHasBeenSet(false), m_ipGeoLocationHasBeenSet(false), m_ipOwnerHasBeenSet(false) { } IpAddressDetails::IpAddressDetails(JsonView jsonValue) : m_ipAddressV4HasBeenSet(false), m_ipCityHasBeenSet(false), m_ipCountryHasBeenSet(false), m_ipGeoLocationHasBeenSet(false), m_ipOwnerHasBeenSet(false) { *this = jsonValue; } IpAddressDetails& IpAddressDetails::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("ipAddressV4")) { m_ipAddressV4 = jsonValue.GetString("ipAddressV4"); m_ipAddressV4HasBeenSet = true; } if(jsonValue.ValueExists("ipCity")) { m_ipCity = jsonValue.GetObject("ipCity"); m_ipCityHasBeenSet = true; } if(jsonValue.ValueExists("ipCountry")) { m_ipCountry = jsonValue.GetObject("ipCountry"); m_ipCountryHasBeenSet = true; } if(jsonValue.ValueExists("ipGeoLocation")) { m_ipGeoLocation = jsonValue.GetObject("ipGeoLocation"); m_ipGeoLocationHasBeenSet = true; } if(jsonValue.ValueExists("ipOwner")) { m_ipOwner = jsonValue.GetObject("ipOwner"); m_ipOwnerHasBeenSet = true; } return *this; } JsonValue IpAddressDetails::Jsonize() const { JsonValue payload; if(m_ipAddressV4HasBeenSet) { payload.WithString("ipAddressV4", m_ipAddressV4); } if(m_ipCityHasBeenSet) { payload.WithObject("ipCity", m_ipCity.Jsonize()); } if(m_ipCountryHasBeenSet) { payload.WithObject("ipCountry", m_ipCountry.Jsonize()); } if(m_ipGeoLocationHasBeenSet) { payload.WithObject("ipGeoLocation", m_ipGeoLocation.Jsonize()); } if(m_ipOwnerHasBeenSet) { payload.WithObject("ipOwner", m_ipOwner.Jsonize()); } return payload; } } // namespace Model } // namespace Macie2 } // namespace Aws
2,228
863
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * LICENSE@@@ */ #include "Common.h" #include "CardWindowManager.h" #include <QGesture> #include "ApplicationDescription.h" #include "AnimationSettings.h" #include "CardWindow.h" #include "HostBase.h" #include "Logging.h" #include "Settings.h" #include "SoundPlayerPool.h" #include "SystemService.h" #include "SystemUiController.h" #include "Time.h" #include "Window.h" #include "WindowServer.h" #include "Utils.h" #include "CardWindowManagerStates.h" #include "CardGroup.h" #include "FlickGesture.h" #include "GhostCard.h" #include "IMEController.h" #include <QTapGesture> #include <QTapAndHoldGesture> #include <QPropertyAnimation> static int kGapBetweenGroups = 0; static qreal kActiveScale = 0.659; static qreal kNonActiveScale = 0.61; static const qreal kWindowOriginRatio = 0.40; static int kWindowOrigin = 0; static int kWindowOriginMax = 0; static const qreal kMinimumWindowScale = 0.26; static int kMinimumHeight = 0; static const int kFlickToCloseWindowVelocityThreshold = -1100; static const int kFlickToCloseWindowDistanceThreshold = -50; static const int kFlickToCloseWindowMinimumVelocity = -500; static const int kModalWindowAnimationTimeout = 45; static const int s_marginSlice = 5; int kAngryCardThreshold = 0; // ------------------------------------------------------------------------------------------------------------- CardWindowManager::CardWindowManager(int maxWidth, int maxHeight) : WindowManagerBase(maxWidth, maxHeight) , m_activeGroup(0) , m_draggedWin(0) , m_penDown(false) , m_cardToRestoreToMaximized(0) , m_lowResMode(false) , m_movement(MovementUnlocked) , m_trackWithinGroup(true) , m_seenFlickOrTap(false) , m_activeGroupPivot(0) , m_reorderZone(ReorderZone_Center) , m_stateMachine(0) , m_minimizeState(0) , m_maximizeState(0) , m_preparingState(0) , m_loadingState(0) , m_focusState(0) , m_reorderState(0) , m_curState(0) , m_addingModalWindow(false) , m_initModalMaximizing(false) , m_parentOfModalCard(0) , m_modalDismissInProgress(false) , m_modalDimissed(false) , m_dismissModalImmediately(-1) , m_animateWindowForModalDismisal(true) , m_modalWindowState(NoModalWindow) , m_playedAngryCardStretchSound(false) , m_animationsActive(false) { setObjectName("CardWindowManager"); SystemUiController* sysui = SystemUiController::instance(); connect(sysui, SIGNAL(signalPositiveSpaceAboutToChange(const QRect&, bool, bool)), SLOT(slotPositiveSpaceAboutToChange(const QRect&, bool, bool))); connect(sysui, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)), SLOT(slotPositiveSpaceChangeFinished(const QRect&))); connect(sysui, SIGNAL(signalPositiveSpaceChanged(const QRect&)), SLOT(slotPositiveSpaceChanged(const QRect&))); connect(sysui, SIGNAL(signalLauncherVisible(bool, bool)), SLOT(slotLauncherVisible(bool, bool))); connect(sysui, SIGNAL(signalLauncherShown(bool)), SLOT(slotLauncherShown(bool))); connect(sysui, SIGNAL(signalMaximizeActiveCardWindow()), SLOT(slotMaximizeActiveCardWindow())); connect(sysui, SIGNAL(signalMinimizeActiveCardWindow()), SLOT(slotMinimizeActiveCardWindow())); connect(sysui, SIGNAL(signalChangeCardWindow(bool)), SLOT(slotChangeCardWindow(bool))); connect(sysui, SIGNAL(signalFocusMaximizedCardWindow(bool)), SLOT(slotFocusMaximizedCardWindow(bool))); connect(SystemService::instance(), SIGNAL(signalTouchToShareAppUrlTransfered(const std::string&)), SLOT(slotTouchToShareAppUrlTransfered(const std::string&))); connect(SystemService::instance(), SIGNAL(signalDismissModalDialog()), SLOT(slotDismissActiveModalWindow())); connect(SystemService::instance(), SIGNAL(signalStopModalDismissTimer()), SLOT(slotDismissModalTimerStopped())); connect(&m_anims, SIGNAL(finished()), SLOT(slotAnimationsFinished())); grabGesture(Qt::TapGesture); grabGesture(Qt::TapAndHoldGesture); grabGesture((Qt::GestureType) SysMgrGestureFlick); } CardWindowManager::~CardWindowManager() { // doesn't reach here } void CardWindowManager::init() { kGapBetweenGroups = Settings::LunaSettings()->gapBetweenCardGroups; if (g_file_test(Settings::LunaSettings()->firstCardLaunch.c_str(), G_FILE_TEST_EXISTS)){ m_dismissedFirstCard=true; } else{ m_dismissedFirstCard=false; } // register CardWindow::Position types for use as Q_PROPERTY's qRegisterMetaType<CardWindow::Position>("CardWindow::Position"); qRegisterAnimationInterpolator<CardWindow::Position>(positionInterpolator); // needed in order for CardWindow pointers to be used with queued signal and slot // connections, i.e. QStateMachine signal transitions qRegisterMetaType<CardWindow*>("CardWindow*"); m_stateMachine = new QStateMachine(this); // setup our states m_minimizeState = new MinimizeState(this); m_maximizeState = new MaximizeState(this); m_preparingState = new PreparingState(this); m_loadingState = new LoadingState(this); m_focusState = new FocusState(this); m_reorderState = new ReorderState(this); m_stateMachine->addState(m_minimizeState); m_stateMachine->addState(m_maximizeState); m_stateMachine->addState(m_preparingState); m_stateMachine->addState(m_loadingState); m_stateMachine->addState(m_focusState); m_stateMachine->addState(m_reorderState); // connect allowed state transitions m_minimizeState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_minimizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_minimizeState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_minimizeState->addTransition(this, SIGNAL(signalEnterReorder(QPoint, int)), m_reorderState); m_maximizeState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_maximizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_maximizeState->addTransition(new MaximizeToFocusTransition(this, m_focusState)); m_focusState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_focusState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_focusState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_focusState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_preparingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_preparingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalLoadingActiveWindow()), m_loadingState); m_loadingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_loadingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_loadingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_reorderState->addTransition(this, SIGNAL(signalExitReorder(bool)), m_minimizeState); // start off minimized m_stateMachine->setInitialState(m_minimizeState); m_stateMachine->start(); updateAngryCardThreshold(); } bool CardWindowManager::handleNavigationEvent(QKeyEvent* keyEvent, bool& propogate) { propogate = false; return m_curState->handleKeyNavigation(keyEvent); } bool CardWindowManager::okToResize() { if(m_anims.state() != QAbstractAnimation::Stopped) return false; return true; } void CardWindowManager::updateAngryCardThreshold() { kAngryCardThreshold = ((boundingRect().height() / 2) * 0.30); } void CardWindowManager::resize(int width, int height) { // accept requests for resizing to the current dimensions, in case we are doing a force resize due to // previous cancelation of Card Window flip operations. WindowManagerBase::resize(width, height); m_normalScreenBounds = QRect(0, Settings::LunaSettings()->positiveSpaceTopPadding, SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight() - Settings::LunaSettings()->positiveSpaceTopPadding); kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = SystemUiController::instance()->positiveSpaceBounds(); kWindowOrigin = boundingRect().y() + ((m_normalScreenBounds.y() + 48) + (int) ((m_normalScreenBounds.height() - 48) * kWindowOriginRatio)); updateAngryCardThreshold(); if(m_groups.size() > 0) { int index = m_groups.indexOf(m_activeGroup); // first resize the active group m_groups[index]->resize(width, height, m_normalScreenBounds); m_groups[index]->setY(kWindowOrigin); // resize the group to the left of the active group if(index > 0) { m_groups[index-1]->resize(width, height, m_normalScreenBounds); m_groups[index-1]->setY(kWindowOrigin); } // resize the group to the right of the active group if(index < m_groups.size()-1) { m_groups[index+1]->resize(width, height, m_normalScreenBounds); m_groups[index+1]->setY(kWindowOrigin); } // now resize the other groups, if there are any if(index-1 > 0) { // left side for(int x = index-2; x >= 0; x--) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } if(index+1 < m_groups.size()-1) { // right side for(int x = index+2; x < m_groups.size(); x++) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } } m_curState->relayout(m_boundingRect, false); } void CardWindowManager::removeAnimationForWindow(CardWindow* win, bool includeDeletedAnimations) { if ((m_curState != m_maximizeState) && m_penDown && !includeDeletedAnimations) win->allowUpdates(false); else win->allowUpdates(true); if (m_cardAnimMap.contains(win)) { QPropertyAnimation* a = m_cardAnimMap.value(win); m_anims.removeAnimation(a); m_cardAnimMap.remove(win); delete a; } if (includeDeletedAnimations) { QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.find(win); if (it != m_deletedAnimMap.end()) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (a) { m_deletedAnimMap.erase(it); delete a; } } } } bool CardWindowManager::windowHasAnimation(CardWindow* win) const { return m_cardAnimMap.contains(win) || m_deletedAnimMap.contains(win); } void CardWindowManager::setAnimationForWindow(CardWindow* win, QPropertyAnimation* anim) { removeAnimationForWindow(win); m_cardAnimMap.insert(win, anim); m_anims.addAnimation(anim); } void CardWindowManager::setAnimationForGroup(CardGroup* group, QPropertyAnimation* anim) { removeAnimationForGroup(group); m_groupAnimMap.insert(group, anim); m_anims.addAnimation(anim); } void CardWindowManager::removeAnimationForGroup(CardGroup* group) { if (m_groupAnimMap.contains(group)) { QPropertyAnimation* a = m_groupAnimMap.value(group); m_anims.removeAnimation(a); m_groupAnimMap.remove(group); delete a; } } bool CardWindowManager::groupHasAnimation(CardGroup* group) const { return m_groupAnimMap.contains(group); } void CardWindowManager::startAnimations() { m_animationsActive = true; updateAllowWindowUpdates(); m_anims.start(); } void CardWindowManager::clearAnimations() { m_anims.stop(); m_anims.clear(); m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::resetMouseTrackState() { m_draggedWin = 0; m_penDown = false; updateAllowWindowUpdates(); m_trackWithinGroup = true; m_seenFlickOrTap = false; m_playedAngryCardStretchSound = false; m_movement = MovementUnlocked; } int CardWindowManager::proceedToAddModalWindow(CardWindow* win) { Window* maxCardWindow = SystemUiController::instance()->maximizedCardWindow(); CardWindow* activeWin = activeWindow(); // Check if we have an active card if(!maxCardWindow || !activeWin) return SystemUiController::NoMaximizedCard; // Check if the active window is the same as the maximized window if(activeWin != maxCardWindow) return SystemUiController::ParentDifferent; // Get the id of the currently active window ApplicationDescription* desc = activeWin->appDescription(); if(desc) { std::string id = desc->id(); if(id.length() > 0) { // Compare with what the card thinks it's caller is if((0 == win->launchingAppId().compare(id) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } else { // If it's a PDK app and we have no appDescription, comparing to appId if(activeWin->isHost()) { if((0 == win->launchingAppId().compare(activeWin->appId()) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } return SystemUiController::LaunchUnknown; } void CardWindowManager::prepareAddWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; if ((card->hostWindowData() != 0) && !card->isHost() && (card->type() != Window::Type_ModalChildWindowCard) && (card->getCardFixedOrientation() == Event::Orientation_Invalid)) { // safeguard code in case the data card was launched right before we changed orientation, resulting // in possibly a landscape card in portrait mode or vice versa bool isCardLandscape = card->hostWindowData()->width() >= card->hostWindowData()->height(); bool isUiLandscape = SystemUiController::instance()->currentUiWidth() >= SystemUiController::instance()->currentUiHeight(); if(isCardLandscape != isUiLandscape) { // we need to resize this card card->flipEventSync(); } } // Proxy cards don't have to wait if (!card->isHost()) { // delay adding a new card if (card->delayPrepare()) { return; } } // If we have a modal card and we cannot add it for whatever reason, just return if(Window::Type_ModalChildWindowCard == win->type() && (SystemUiController::NoErr != (m_dismissModalImmediately = proceedToAddModalWindow(card)))) { m_modalWindowState = ModalWindowAddInitCheckFail; notifySysControllerOfModalStatus(m_dismissModalImmediately, false, ModalLaunch, win); return; } Q_EMIT signalExitReorder(); card->enableShadow(); // Do this ONLY if we are not adding a MODAL window if(Window::Type_ModalChildWindowCard != card->type()) { // If the currently active card is a modal card, make sure we dismiss it as we are going to get a new active card - don't restore the state as the new card will be the active card if(activeWindow() && Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedParentSwitched; notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } card->setParentItem(this); } else { m_parentOfModalCard = activeWindow(); // Set the desired fields for the modal card. card->setModalParent(m_parentOfModalCard); // Set the desired fields for the parent of the modal card. m_parentOfModalCard->setCardIsModalParent(true); m_parentOfModalCard->setModalChild(card); m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedNotAcceptingInput); // Let the modal window compute it's initial position card->computeModalWindowPlacementInf(-1); // Set the fact that we are adding a modal window m_addingModalWindow = true; } disableCardRestoreToMaximized(); Q_EMIT signalPreparingWindow(card); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::prepareAddWindowSibling(CardWindow* win) { if (m_activeGroup && !win->launchInNewGroup()) { CardWindow* activeWin = m_activeGroup->activeCard(); if(Window::Type_ModalChildWindowCard != win->type()) { if ((activeWin->focused() && (win->launchingProcessId() == activeWin->processId() || (win->launchingAppId() == activeWin->appId())))) { // add to active group m_activeGroup->addToFront(win); setActiveGroup(m_activeGroup); m_cardToRestoreToMaximized = activeWin; } else { // spawn new group to the right of active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.insert(m_groups.indexOf(m_activeGroup)+1, newGroup); setActiveGroup(newGroup); } queueFocusAction(activeWin, false); setActiveCardOffScreen(); slideAllGroups(false); startAnimations(); } else { queueFocusAction(activeWin, false); } } else { CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.append(newGroup); setActiveGroup(newGroup); setActiveCardOffScreen(); } SystemUiController::instance()->setCardWindowAboutToMaximize(); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::addWindowTimedOut(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); // Host windows shouldn't fire this handler anyways if (card->isHost()) return; if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalExitReorder(); m_curState->windowTimedOut(card); SystemUiController::instance()->cardWindowTimeout(); } void CardWindowManager::addWindowTimedOutNormal(CardWindow* win) { m_penDown = false; updateAllowWindowUpdates(); Q_ASSERT(m_activeGroup && m_activeGroup->activeCard() == win); if(Window::Type_ModalChildWindowCard != win->type()) { setActiveCardOffScreen(false); slideAllGroups(); } if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalLoadingActiveWindow(); } void CardWindowManager::addWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); card->setAddedToWindowManager(); // process addWindow once preparing has finished if (!card->isHost() && !card->prepareAddedToWindowManager()) return; Q_EMIT signalExitReorder(); m_curState->windowAdded(card); } void CardWindowManager::removeWindow(Window* win) { if(!win) return; CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; Q_EMIT signalExitReorder(); // Either there are no modal window(s) OR we are not deleting the modal parent - default to the plain vanilla delete. if((win->type() != Window::Type_ModalChildWindowCard && false == m_addingModalWindow) || (win->type() != Window::Type_ModalChildWindowCard && false == card->isCardModalParent())) { removeWindowNoModality(card); } else removeWindowWithModality(card); } void CardWindowManager::removeWindowNoModality(CardWindow* win) { if(!win) return; QPropertyAnimation* anim = NULL; if(false == performCommonWindowRemovalTasks(win, true)) return; // slide card off the top of the screen CardWindow::Position pos = win->position(); QRectF r = pos.toTransform().mapRect(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); anim = new QPropertyAnimation(win, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); m_curState->windowRemoved(win); } void CardWindowManager::removeWindowWithModality(CardWindow* win) { CardWindow* card = NULL, *activeCard = NULL; QPropertyAnimation* anim = NULL; bool restore = false; if(!win) return; activeCard = activeWindow(); if(!activeCard) return; card = win; restore = (activeCard == card && Window::Type_ModalChildWindowCard == card->type()) ? true:false; // If the modal card was deleted because it's parent was deleted externally, don't run any of these, simply remove the modal and return if(Window::Type_ModalChildWindowCard == card->type() && m_modalWindowState == ModalParentDimissedWaitForChildDismissal && NULL == m_parentOfModalCard) { handleModalRemovalForDeletedParent(card); m_modalWindowState = NoModalWindow; return; } /* This function is called externally by some component when it wants the CardWindow to go away. Also when ::closeWindow's call to win->close will result in a call to this function. For the modal windows, we have 2 cases to consider. 1) ::removeWindow is called on a modal window by an external component. 2) ::removeWindow is called on a modal window by as a result of a call to ::closeWindow. We also need to consider the case if the modal was even added. */ // This is not a part of a call to closeWindow and came by externally. This means there is NO need to call close on the window again. if(false == m_modalDismissInProgress) { SystemUiController::ModalWinDismissErrorReason dismiss = SystemUiController::DismissUnknown; // We are removing a modal card externally if(Window::Type_ModalChildWindowCard == card->type()) { m_modalWindowState = ModalWindowDismissedExternally; } // check if w is a modal parent else if(true == card->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; dismiss = SystemUiController::ParentCardDismissed; } notifySysControllerOfModalStatus(dismiss, restore, ModalDismissNoAnimate); } else { m_modalDismissInProgress = false; } // Signal that we no longer have an active modal window - Either the modal is getting dismissed/parent is getting dismissed/modal add failed as the parent was different etc if(true == restore || m_modalWindowState == ModalParentDismissed || m_modalWindowState == ModalWindowAddInitCheckFail || m_modalWindowState == ModalWindowDismissedParentSwitched) SystemUiController::instance()->notifyModalWindowDeactivated(); // Reset in different ways (if true == restore => modal card was added successfully and is the card being deleted. if(true == restore) resetModalFlags(); // If we are deleting the modal card because of a failure during initialization, just reset the flags here. else if(m_modalWindowState == ModalWindowAddInitCheckFail) resetModalFlags(true); else if(m_modalWindowState == ModalParentDismissed) { // modal parent is deleted - Do the following to make things smoother. // 1 - Make the modal card invisible. // 2 - Set that the parent no longer has a modal child. (Don't reset the state) activeCard->setVisible(false); if(m_parentOfModalCard) { m_parentOfModalCard->setCardIsModalParent(false); m_parentOfModalCard->setModalChild(NULL); m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } else if(m_modalWindowState == ModalWindowDismissedParentSwitched) { resetModalFlags(true); } if(false == performCommonWindowRemovalTasks(card, (m_modalWindowState == ModalParentDismissed)?true:false)) return; if(Window::Type_ModalChildWindowCard != card->type()) { // slide card off the top of the screen CardWindow::Position pos = card->position(); QRectF r = pos.toTransform().mapRect(card->boundingRect()); qreal offTop = boundingRect().y() - (card->y() + (r.height()/2)); anim = new QPropertyAnimation(card, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); } else if(true == m_animateWindowForModalDismisal){ anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(card, anim); if(true == m_animateWindowForModalDismisal) anim->start(); m_curState->windowRemoved(card); // Finally if we are deleting a modal parent, clean reset the state if(m_modalWindowState == ModalParentDismissed) { resetModalFlags(true); m_modalWindowState = ModalParentDimissedWaitForChildDismissal; } } void CardWindowManager::handleModalRemovalForDeletedParent(CardWindow* card) { if(NULL == card || Window::Type_ModalChildWindowCard != card->type()) return; // ignore the return value. performCommonWindowRemovalTasks(card, false); } bool CardWindowManager::performCommonWindowRemovalTasks(CardWindow* card, bool checkCardGroup) { if(!card) return false; removePendingActionWindow(card); // Mark window as removed. Its safe to delete this now card->setRemoved(); // Is it already on the deleted animation list? if (m_deletedAnimMap.contains(card)) { // if it is animating, let it finish which will delete it QPropertyAnimation* a = m_deletedAnimMap.value(card); if (a && a->state() != QAbstractAnimation::Running) { // nuke the animation removeAnimationForWindow(card, true); delete card; } return false; } if(true == checkCardGroup) Q_ASSERT(card->cardGroup() != 0); removeAnimationForWindow(card); return true; } void CardWindowManager::initiateRemovalOfActiveModalWindow() { // Ensure that the last window we added was a modal window if(true == m_addingModalWindow) { CardWindow* activeWin = activeWindow(); // ERROR. DONT KNOW WHICH CARD WILL BE THE NEW ACTIVE CARD if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); return; } // Techinically this should never happen, but just in case. if(!m_parentOfModalCard) m_parentOfModalCard = static_cast<CardWindow*>(activeWin->parentItem()); if(!m_parentOfModalCard) { g_warning("Unable to get parent of active modal window %s", __PRETTY_FUNCTION__); return; } // Start an animation for the opacity of the currently active modal window QPropertyAnimation* winAnim = new QPropertyAnimation(activeWin, "opacity"); winAnim->setEndValue(0.0); winAnim->setDuration(kModalWindowAnimationTimeout); // connect to the slot that gets called when this animation gets done. connect(winAnim, SIGNAL(finished()), SLOT(slotOpacityAnimationFinished())); // start the animation winAnim->start(QAbstractAnimation::DeleteWhenStopped); } } void CardWindowManager::resetModalFlags(bool forceReset) { m_addingModalWindow = false; m_initModalMaximizing = false; m_modalDismissInProgress = false; m_modalDimissed = false; m_dismissModalImmediately = -1; if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } if(true == forceReset) m_parentOfModalCard = NULL; } void CardWindowManager::performPostModalWindowRemovedActions(Window* win, bool restore) { CardWindow* activeWin = (NULL != win)? (static_cast<CardWindow*>(win)) : activeWindow(); if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); // Set the parent to the first card of the active card group. if(m_activeGroup) m_activeGroup->makeBackCardActive(); return; } // call close ONLY if the modal was deleted internally if(ModalWindowDismissedExternally != m_modalWindowState || NoModalWindow != m_modalWindowState) { closeWindow(activeWin); } // Make the parent card as the active card. Notify SysUiController of this fact as well. No animations are needed as the parent is already the active card in full screen if(true == restore && NULL != m_parentOfModalCard) { m_modalDimissed = true; // Just set this flag so that the parent doesn't forward events to the modal card anymore m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); // Set the new maximized/active cards. SystemUiController::instance()->setMaximizedCardWindow(m_parentOfModalCard); SystemUiController::instance()->setActiveCardWindow(m_parentOfModalCard); // PDK apps need both Focus and Maximized events to be sent to them to direct render. The call above will give focus, disable DR here and resetModalFlags will re-enable DR on the parent if(m_parentOfModalCard->isHost()) { SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, m_parentOfModalCard, false); } // If we are restoring the parent state coz of active card being switched, don't start an animation, but do all the actions in sequence if(ModalWindowDismissedParentSwitched != m_modalWindowState) { // Queue up the fact that we need to give focus back to the parent queueFocusAction(m_parentOfModalCard, true); // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus back to the parent. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); m_anims.start(); } else { // we have a modal card as the active card and a new card is being added to the system. Perform all the actions here. if (m_activeGroup) { m_activeGroup->raiseCards(); } m_parentOfModalCard->aboutToFocusEvent(true); m_parentOfModalCard->queueFocusAction(true); m_parentOfModalCard->performPendingFocusAction(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; } } else { if(!((ModalWindowAddInitCheckFail == m_modalWindowState) || (ModalParentDismissed == m_modalWindowState) || (ModalWindowDismissedParentSwitched == m_modalWindowState))) { resetModalFlags(); } } // Finally - if the modal was dismissed externally then make it invisible here so that it doesn't linger around. ResetModal() will clear out the flags on the parent if((ModalWindowDismissedExternally == m_modalWindowState || ModalWindowDismissedParentSwitched == m_modalWindowState) && (activeWin->type() == Window::Type_ModalChildWindowCard)) activeWin->setVisible(false); } void CardWindowManager::slotOpacityAnimationFinished() { performPostModalWindowRemovedActions(NULL, true); } void CardWindowManager::removeCardFromGroup(CardWindow* win, bool adjustLayout) { if(Window::Type_ModalChildWindowCard == win->type()) return; CardGroup* group = win->cardGroup(); luna_assert(group != 0); group->removeFromGroup(win); if (group->empty()) { // clean up this group m_groups.remove(m_groups.indexOf(group)); removeAnimationForGroup(group); delete group; } // make sure we aren't holding a reference to a soon to be deleted card if (m_draggedWin == win) { // clear any dragging state resetMouseTrackState(); } // If we are removing a modal dialog , we don't need these. if(adjustLayout) { // select a new active group setActiveGroup(groupClosestToCenterHorizontally()); // make sure everything is positioned properly slideAllGroups(); } } void CardWindowManager::removeCardFromGroupMaximized(CardWindow* win) { IMEController::instance()->removeClient(win); if(Window::Type_ModalChildWindowCard == win->type()) return; // Switch out only if we are the active window if (activeWindow() == win) { Q_EMIT signalMinimizeActiveWindow(); removeCardFromGroup(win); return; }else if(NULL != m_parentOfModalCard && m_parentOfModalCard == win && true == m_parentOfModalCard->isCardModalParent()) { removeCardFromGroup(win); return; } removeCardFromGroup(win, false); } void CardWindowManager::layoutGroups(qreal xDiff) { if (!m_activeGroup || m_groups.empty()) return; int activeGroupPosition = m_groups.indexOf(m_activeGroup); removeAnimationForGroup(m_activeGroup); m_activeGroup->setX(m_activeGroup->x() + xDiff); int centerX = -m_activeGroup->left() - kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition-1; i>=0; i--) { centerX += -m_groups[i]->right(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::maximizeActiveWindow(bool animate) { if (!m_activeGroup) return; Q_EMIT signalExitReorder(); QRect r; // If the currently active card window is a modal window, don't do any of these operations except If we are doing this as a part of rotation if(activeWindow()->type() != Window::Type_ModalChildWindowCard || (activeWindow()->type() == Window::Type_ModalChildWindowCard && true == SystemUiController::instance()->isUiRotating())) { m_activeGroup->raiseCards(); setActiveGroup(m_activeGroup); if(animate) slideAllGroups(false); else layoutAllGroups(false); if(activeWindow()->type() != Window::Type_ModalChildWindowCard) r = normalOrScreenBounds(m_activeGroup->activeCard()); else if(NULL != m_parentOfModalCard) r = normalOrScreenBounds(m_parentOfModalCard); if(animate) { QList<QPropertyAnimation*> maxAnims = m_activeGroup->maximizeActiveCard(r.y()/2); Q_FOREACH(QPropertyAnimation* anim, maxAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } startAnimations(); } else { m_activeGroup->maximizeActiveCardNoAnimation(r.y()/2); } } else { // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus to the active card. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); if(false == m_initModalMaximizing) { // Notify SystemUiController that the modal window was added successfully. if(true == m_addingModalWindow) { // Notify SysUiController that we have setup a modal notifySysControllerOfModalStatus(SystemUiController::NoErr, false, ModalLaunch, activeWindow()); } m_initModalMaximizing = true; } // start the animations startAnimations(); } Q_EMIT signalMaximizeActiveWindow(); } void CardWindowManager::slotMaximizeActiveCardWindow() { if(false == m_addingModalWindow) maximizeActiveWindow(); } void CardWindowManager::minimizeActiveWindow(bool animate) { disableCardRestoreToMaximized(); Q_EMIT signalExitReorder(); if (m_activeGroup) m_activeGroup->raiseCards(); // always allow transitions to minimized mode if(false == m_addingModalWindow) { Q_EMIT signalMinimizeActiveWindow(); if(animate) slideAllGroups(); else layoutAllGroups(); } else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::UiMinimized, true, ModalDismissAnimate); } } void CardWindowManager::markFirstCardDone() { g_message("[%s]: DEBUG: staring markFirstCardDone.", __PRETTY_FUNCTION__); m_dismissedFirstCard=true; // For first-use mode, touch a marker file on the filesystem //if (Settings::LunaSettings()->uiType == Settings::UI_MINIMAL) { g_mkdir_with_parents(Settings::LunaSettings()->lunaPrefsPath.c_str(), 0755); FILE* f = fopen(Settings::LunaSettings()->firstCardLaunch.c_str(), "w"); fclose(f); //} } void CardWindowManager::firstCardAlert() { if(!m_dismissedFirstCard){ Q_EMIT signalFirstCardRun(); markFirstCardDone(); } } void CardWindowManager::handleKeyNavigationMinimized(QKeyEvent* keyEvent) { if (!m_activeGroup || keyEvent->type() != QEvent::KeyPress) return; switch (keyEvent->key()) { case Qt::Key_Left: switchToPrevApp(); break; case Qt::Key_Right: switchToNextApp(); break; case Qt::Key_Return: if (!keyEvent->isAutoRepeat()) maximizeActiveWindow(); break; case Qt::Key_Backspace: if ((keyEvent->modifiers() & Qt::ControlModifier) && !keyEvent->isAutoRepeat()) closeWindow(activeWindow()); break; default: break; } } void CardWindowManager::slotMinimizeActiveCardWindow() { if(false == m_addingModalWindow) minimizeActiveWindow(); else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::HomeButtonPressed, true, ModalDismissAnimate); } } void CardWindowManager::setActiveCardOffScreen(bool fullsize) { CardWindow* activeCard = activeWindow(); if (!activeCard) return; // safety precaution removeAnimationForWindow(activeCard); CardWindow::Position pos; qreal yOffset = boundingRect().bottom() - activeCard->y(); pos.trans.setZ(fullsize ? 1.0 : kActiveScale); pos.trans.setY(yOffset - activeCard->boundingRect().y() * pos.trans.z()); activeCard->setPosition(pos); } void CardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event) { // We may get a second pen down. Just ignore it. if (m_penDown) return; resetMouseTrackState(); if (m_groups.empty() || !m_activeGroup) return; m_penDown = true; updateAllowWindowUpdates(); m_curState->mousePressEvent(event); } void CardWindowManager::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { mousePressEvent(event); } void CardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (!m_penDown || m_seenFlickOrTap) return; m_curState->mouseMoveEvent(event); } void CardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if (m_penDown) m_curState->mouseReleaseEvent(event); resetMouseTrackState(); } bool CardWindowManager::playAngryCardSounds() const { return WindowServer::instance()->getUiOrientation() == OrientationEvent::Orientation_Down; } bool CardWindowManager::sceneEvent(QEvent* event) { if (event->type() == QEvent::GestureOverride && m_curState != m_maximizeState) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { event->accept(); return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { event->accept(); return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { event->accept(); return true; } } else if (event->type() == QEvent::Gesture) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { QTapGesture* tap = static_cast<QTapGesture*>(g); if (tap->state() == Qt::GestureFinished) { tapGestureEvent(tap); } return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { QTapAndHoldGesture* hold = static_cast<QTapAndHoldGesture*>(g); if (hold->state() == Qt::GestureFinished) { tapAndHoldGestureEvent(hold); } return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { FlickGesture* flick = static_cast<FlickGesture*>(g); if (flick->state() == Qt::GestureFinished) { flickGestureEvent(ge); } return true; } } return QGraphicsObject::sceneEvent(event); } void CardWindowManager::tapGestureEvent(QTapGesture* event) { if (!m_penDown) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapGestureEvent(event); } void CardWindowManager::tapAndHoldGestureEvent(QTapAndHoldGesture* event) { if (!m_penDown) return; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapAndHoldGestureEvent(event); } void CardWindowManager::handleTapAndHoldGestureMinimized(QTapAndHoldGesture* event) { QPoint pt = mapFromScene(event->position()).toPoint(); if (m_activeGroup->setActiveCard(event->position())) { // start reordering the active card Q_EMIT signalEnterReorder(pt, s_marginSlice); } else if (pt.x() < 0) { switchToPrevGroup(); } else { switchToNextGroup(); } } void CardWindowManager::flickGestureEvent(QGestureEvent* event) { g_message("%s", __PRETTY_FUNCTION__); if (!m_penDown || m_seenFlickOrTap) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->flickGestureEvent(event); } void CardWindowManager::handleFlickGestureMinimized(QGestureEvent* event) { QGesture* g = event->gesture((Qt::GestureType) SysMgrGestureFlick); if (!g) return; FlickGesture* flick = static_cast<FlickGesture*>(g); if (m_movement == MovementVLocked) { if (!m_draggedWin) { slideAllGroups(); return; } QPointF start = mapFromScene(event->mapToGraphicsScene(flick->hotSpot())); QPointF end = mapFromScene(event->mapToGraphicsScene(flick->endPos())); int distanceY = end.y() - start.y(); static const int flickDistanceVelocityMultiplied = kFlickToCloseWindowVelocityThreshold * kFlickToCloseWindowDistanceThreshold; QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if (distanceY < kFlickToCloseWindowDistanceThreshold && flick->velocity().y() < kFlickToCloseWindowMinimumVelocity && flick->velocity().y() < (flickDistanceVelocityMultiplied / distanceY)) { closeWindow(m_draggedWin); } else if (pr.center().y() > boundingRect().bottom()) { closeWindow(m_draggedWin, true); } else if (pr.center().y() < boundingRect().top()) { closeWindow(m_draggedWin); } else { slideAllGroups(); } } else if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { // adjust the fanning position within the group based on the users flick velocity m_activeGroup->flick(flick->velocity().x()); setActiveGroup(m_activeGroup); slideAllGroups(); } else { // advance to the next/previous group if we are Outer Locked or were still unbiased horizontally if (flick->velocity().x() > 0) switchToPrevGroup(); else switchToNextGroup(); } } } void CardWindowManager::handleMousePressMinimized(QGraphicsSceneMouseEvent* event) { // try to capture the card the user first touched if (m_activeGroup && m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); } void CardWindowManager::handleMouseMoveMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.isEmpty() || !m_activeGroup) return; QPoint delta = (event->pos() - event->buttonDownPos(Qt::LeftButton)).toPoint(); QPoint diff; // distance move between last and current mouse position // lock movement to an axis if (m_movement == MovementUnlocked) { if ((delta.x() * delta.x() + delta.y() * delta.y()) < Settings::LunaSettings()->tapRadiusSquared) return; if (abs(delta.x()) > 0.866 * abs(delta.y())) { m_movement = MovementHLocked; m_activeGroupPivot = m_activeGroup->x(); } else { m_movement = MovementVLocked; } diff = delta; } else { diff = (event->pos() - event->lastPos()).toPoint(); } if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { m_trackWithinGroup = !m_activeGroup->atEdge(diff.x()); if (m_trackWithinGroup) { // shift cards within the active group m_activeGroup->adjustHorizontally(diff.x()); slideAllGroups(); } else { m_activeGroupPivot = m_activeGroup->x(); } } if (!m_trackWithinGroup) { m_activeGroupPivot += diff.x(); slideAllGroupsTo(m_activeGroupPivot); } } else if (m_movement == MovementVLocked) { if (!m_draggedWin) { if (m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); if (!m_draggedWin) return; } // ignore pen movements outside the vertical pillar around the active window QPointF mappedPos = m_draggedWin->mapFromParent(event->pos()); if (mappedPos.x() < m_draggedWin->boundingRect().x() || mappedPos.x() >= m_draggedWin->boundingRect().right()) { return; } if (delta.y() == 0) return; if (!m_playedAngryCardStretchSound && (delta.y() > kAngryCardThreshold) && playAngryCardSounds()) { SoundPlayerPool::instance()->playFeedback("carddrag"); m_playedAngryCardStretchSound = true; } removeAnimationForWindow(m_draggedWin); // cards are always offset from the parents origin CardWindow::Position pos = m_draggedWin->position(); pos.trans.setY(delta.y()); m_draggedWin->setPosition(pos); } } void CardWindowManager::handleMouseMoveReorder(QGraphicsSceneMouseEvent* event) { CardWindow* activeWin = activeWindow(); if (!activeWin) return; // track the active window under the users finger QPoint delta = (event->pos() - event->lastPos()).toPoint(); CardWindow::Position pos; pos.trans = QVector3D(activeWin->position().trans.x() + delta.x(), activeWin->position().trans.y() + delta.y(), kActiveScale); activeWin->setPosition(pos); // should we switch zones? ReorderZone newZone = getReorderZone(event->pos().toPoint()); if (newZone == m_reorderZone && newZone == ReorderZone_Center) { moveReorderSlotCenter(event->pos()); } else if (newZone != m_reorderZone) { if (newZone == ReorderZone_Right) { m_reorderZone = newZone; moveReorderSlotRight(); } else if (newZone == ReorderZone_Left) { m_reorderZone = newZone; moveReorderSlotLeft(); } else { m_reorderZone = newZone; } } } CardWindowManager::ReorderZone CardWindowManager::getReorderZone(QPoint pt) { qreal section = boundingRect().width() / s_marginSlice; if (pt.x() < boundingRect().left() + section) { return ReorderZone_Left; } else if (pt.x() > boundingRect().right() - section) { return ReorderZone_Right; } return ReorderZone_Center; } void CardWindowManager::enterReorder(QPoint pt) { CardWindow* activeWin = activeWindow(); luna_assert(activeWin != 0); activeWin->setOpacity(0.8); activeWin->disableShadow(); activeWin->setAttachedToGroup(false); // get our initial zone m_reorderZone = getReorderZone(pt); } void CardWindowManager::cycleReorderSlot() { if (m_reorderZone == ReorderZone_Right) moveReorderSlotRight(); else if (m_reorderZone == ReorderZone_Left) moveReorderSlotLeft(); } void CardWindowManager::moveReorderSlotCenter(QPointF pt) { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; // NOTE: it is assumed that the active card has already // been repositioned when making this check if (m_activeGroup->moveActiveCard()) { m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } setActiveGroup(m_activeGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotRight() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the top card in the group? if (m_activeGroup->moveActiveCard(1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.last() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group. m_groups.remove(activeIndex); delete m_activeGroup; newActiveGroup = m_groups[activeIndex]; } else { // this was an existing group. // insert a new group to the right of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex+1, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToBack(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotLeft() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the bottom card in the group? if (m_activeGroup->moveActiveCard(-1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.first() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group m_groups.remove(activeIndex); delete m_activeGroup; // the previous group is the new active group newActiveGroup = m_groups[qMax(0, activeIndex-1)]; } else { // this was an existing group. // insert a new group to the left of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToFront(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::arrangeWindowsAfterReorderChange(int duration, QEasingCurve::Type curve) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardShuffleReorderCurve)); anim->setDuration(AS(cardShuffleReorderDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(duration, curve, false); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::handleMouseReleaseMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.empty() || m_seenFlickOrTap) return; if (m_movement == MovementVLocked) { // Did we go too close to the top? if (m_draggedWin) { QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if ((!event->canceled()) && (pr.center().y() > boundingRect().bottom())) { closeWindow(m_draggedWin, true); } else if ((!event->canceled()) && (pr.center().y() < boundingRect().top())) { closeWindow(m_draggedWin); } else { // else just restore all windows back to original position slideAllGroups(); } } } else if (m_movement == MovementHLocked) { if(!event->canceled()) setActiveGroup(groupClosestToCenterHorizontally()); slideAllGroups(); } } void CardWindowManager::handleMouseReleaseReorder(QGraphicsSceneMouseEvent* event) { Q_UNUSED(event) Q_EMIT signalExitReorder(false); CardWindow* activeWin = activeWindow(); if (!activeWin) return; // TODO: fix the y for the draggedWin activeWin->setOpacity(1.0); activeWin->enableShadow(); activeWin->setAttachedToGroup(true); slideAllGroups(); } void CardWindowManager::handleTapGestureMinimized(QTapGesture* event) { if (!m_activeGroup) return; //Things that must be done here: //--Perform a hit test to determine if the current active group was hit if (m_activeGroup->testHit(event->position())) { //--If it was, then we need to see if the card hit was in a reasonable // range of the active card. If it was then maximize it. If it was not // slide the card fan over to make it more visible. if (m_activeGroup->shouldMaximizeOrScroll(event->position())) { m_activeGroup->setActiveCard(event->position()); m_activeGroup->moveToActiveCard(); maximizeActiveWindow(); } else { slideAllGroups(); } } else { // first test to see if the tap is not above/below the active group QPointF pt = mapFromScene(event->position()); if (!m_activeGroup->withinColumn(pt)) { if (pt.x() < 0) { // tapped to the left of the active group switchToPrevGroup(); } else { // tapped to the right of the active group switchToNextGroup(); } } else { // poke the groups to make sure they animate to their final positions slideAllGroups(); } } } CardGroup* CardWindowManager::groupClosestToCenterHorizontally() const { if (m_groups.empty()) return 0; qreal deltaX = FLT_MAX; qreal curDeltaX = 0; CardGroup* grp = 0; Q_FOREACH(CardGroup* cg, m_groups) { curDeltaX = qAbs(cg->pos().x()); if (curDeltaX < deltaX) { grp = cg; deltaX = curDeltaX; } } return grp; } void CardWindowManager::setActiveGroup(CardGroup* group) { m_activeGroup = group; SystemUiController::instance()->setActiveCardWindow(m_activeGroup ? m_activeGroup->activeCard() : 0); } void CardWindowManager::switchToNextApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makeNextCardActive()) { // couldn't move, switch to the next group int index = m_groups.indexOf(m_activeGroup); if (index < m_groups.size() - 1) { m_activeGroup = m_groups[index + 1]; m_activeGroup->makeBackCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToPrevApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makePreviousCardActive()) { // couldn't move, switch to the previous group int index = m_groups.indexOf(m_activeGroup); if (index > 0) { m_activeGroup = m_groups[index - 1]; m_activeGroup->makeFrontCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToNextGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.last()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex++; activeGroupIndex = qMin(activeGroupIndex, m_groups.size() - 1); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToPrevGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.first()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex--; activeGroupIndex = qMax(activeGroupIndex, 0); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToNextAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); if(!oldActiveCard) return; // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makeNextCardActive()) { if (m_activeGroup == m_groups.last()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() - 40); oldActiveCard->setPosition(pos); } else { // switch to the bottom card of the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index+1]); m_activeGroup->makeBackCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::switchToPrevAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makePreviousCardActive()) { if (m_activeGroup == m_groups.first()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() + 40); oldActiveCard->setPosition(pos); } else { // shift to the bottom card in the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index-1]); m_activeGroup->makeFrontCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { // current maximized card QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::slideAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(200, QEasingCurve::OutCubic, includeActiveCard); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } if (includeActiveCard) startAnimations(); } void CardWindowManager::slideAllGroupsTo(int xOffset) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(xOffset); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), xOffset); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups + xOffset; for (int i=activeGrpIndex-1; i>=0;i--) { centerX += -m_groups[i]->right(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + xOffset; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::layoutAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); m_activeGroup->layoutCards(true, includeActiveCard); int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { m_groups[i]->layoutCards(false, false); centerX += -m_groups[i]->right(); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { m_groups[i]->layoutCards(false, false); centerX += m_groups[i]->left(); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::slideToActiveCard() { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::focusWindow(Window* win) { Q_EMIT signalExitReorder(); disableCardRestoreToMaximized(); // make sure this are window has already been group'd CardWindow* card = static_cast<CardWindow*>(win); if (!m_groups.contains(card->cardGroup()) || !m_activeGroup) return; // If the active card is a modal window and we are focusing another window, we need to dismiss the modal first. if(Window::Type_ModalChildWindowCard == activeWindow()->type() && card != activeWindow()) { // Cehck if we are trying to focus the parent m_modalWindowState = ModalWindowDismissedParentSwitched; if(m_parentOfModalCard != card) { // Some other card is being focussed so no need to restore the state of the parent notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; m_modalDimissed = true; } } else { // Someone tried to give focus to the parent. notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); return; } } Q_EMIT signalFocusWindow(card); } void CardWindowManager::slotPositiveSpaceAboutToChange(const QRect& r, bool fullScreenMode, bool screenResizing) { Q_EMIT signalExitReorder(); m_targetPositiveSpace = r; if (m_curState) m_curState->positiveSpaceAboutToChange(r, fullScreenMode); } void CardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r) { Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChangeFinished(r); } void CardWindowManager::slotPositiveSpaceChanged(const QRect& r) { static bool initialBounds = true; static qreal kActiveWindowScale = Settings::LunaSettings()->activeCardWindowRatio; static qreal kNonActiveWindowScale = Settings::LunaSettings()->nonActiveCardWindowRatio; if (initialBounds) { initialBounds = false; m_normalScreenBounds = r; kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = r; // TODO: this is a temporary solution to fake the existence of the search pill // which happens to be 48 pixels tall kActiveScale = ((qreal) (r.height() - 48) * kActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kActiveScale = qMax(kMinimumWindowScale, kActiveScale); kNonActiveScale = ((qreal) (r.height() - 48) * kNonActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kNonActiveScale = qMax(kMinimumWindowScale, kNonActiveScale); // allow groups to shift up to a maximum so the tops of cards don't go off the screen kWindowOriginMax = (boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio))) - Settings::LunaSettings()->positiveSpaceTopPadding - Settings::LunaSettings()->positiveSpaceBottomPadding; kWindowOrigin = boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio)); } QRect rect = r; if (rect.height() < kMinimumHeight) { rect.setHeight(kMinimumHeight); } Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChanged(rect); } void CardWindowManager::disableCardRestoreToMaximized() { m_cardToRestoreToMaximized = 0; } void CardWindowManager::restoreCardToMaximized() { if (!m_cardToRestoreToMaximized || !m_activeGroup) return; if (m_activeGroup->setActiveCard(m_cardToRestoreToMaximized)) maximizeActiveWindow(); disableCardRestoreToMaximized(); } QRect CardWindowManager::normalOrScreenBounds(CardWindow* win) const { if (win && win->fullScreen() && win->type() != Window::Type_ModalChildWindowCard) { return QRect(m_targetPositiveSpace.x(), m_targetPositiveSpace.y(), SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight()); } return m_normalScreenBounds; } void CardWindowManager::cancelReorder(bool dueToPenCancel) { handleMouseReleaseReorder(NULL); } void CardWindowManager::closeWindow(CardWindow* win, bool angryCard) { if(!win) return; QPropertyAnimation* anim = NULL; /*// The only case we need to worry about here is if a modal parent called closeWindow() on itself. Then we need to close the child first and then continue if(true == win->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; notifySysControllerOfModalStatus(SystemUiController::ParentCardDismissed, false, ModalDismissNoAnimate); win->setCardIsModalParent(false); win->setModalChild(NULL); win->setModalAcceptInputState(CardWindow::NoModalWindow); }*/ if (angryCard) win->setDisableKeepAlive(); win->close(); // remove the window from the current animation list removeAnimationForWindow(win, true); if(Window::Type_ModalChildWindowCard != win->type()) { CardWindow::Position pos = win->position(); QRectF r = win->mapRectToParent(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); pos.trans.setY(offTop); anim = new QPropertyAnimation(win, "position"); QVariant end; end.setValue(pos); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setDuration(AS(cardDeleteDuration)); anim->setEndValue(end); } else { anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); // Modal cards are not a part of any card group. if(Window::Type_ModalChildWindowCard != win->type()) { removeCardFromGroup(win); } if (angryCard && playAngryCardSounds()) SoundPlayerPool::instance()->playFeedback("birdappclose"); else if (!Settings::LunaSettings()->lunaSystemSoundAppClose.empty()) SoundPlayerPool::instance()->playFeedback(Settings::LunaSettings()->lunaSystemSoundAppClose); } void CardWindowManager::queueFocusAction(CardWindow* win, bool focused) { if (win->removed()) return; win->aboutToFocusEvent(focused); win->queueFocusAction(focused); if (!m_pendingActionWinSet.contains(win)) m_pendingActionWinSet.insert(win); } void CardWindowManager::performPendingFocusActions() { Q_FOREACH(CardWindow* card, m_pendingActionWinSet) { card->performPendingFocusAction(); } m_pendingActionWinSet.clear(); } void CardWindowManager::queueTouchToShareAction(CardWindow* win) { if (win->removed()) return; if (!m_pendingTouchToShareWinSet.contains(win)) m_pendingTouchToShareWinSet.insert(win); } void CardWindowManager::performPendingTouchToShareActions() { Q_FOREACH(CardWindow* card, m_pendingTouchToShareWinSet) { GhostCard* ghost = card->createGhost(); if (ghost) { // place the ghost on top of the card we're sharing ghost->setParentItem(card->parentItem()); ghost->stackBefore(card); card->stackBefore(ghost); // anchor the ghost within it's parent's group CardGroup* group = card->cardGroup(); ghost->setPos((group ? group->pos() : QPointF(0,0))); ghost->setOpacity(0.5); QPropertyAnimation* anim = new QPropertyAnimation(ghost, "position"); anim->setDuration(AS(cardGhostDuration)); anim->setEasingCurve(AS_CURVE(cardGhostCurve)); // animate the ghost off the top of the screen CardWindow::Position pos; QRectF r = ghost->mapRectToParent(ghost->boundingRect()); qreal offTop = boundingRect().y() - (ghost->y() + (r.height()/2)); pos.trans.setY(offTop); pos.trans.setZ(Settings::LunaSettings()->ghostCardFinalRatio); QVariant end; end.setValue(pos); anim->setEndValue(end); connect(anim, SIGNAL(finished()), SLOT(slotTouchToShareAnimationFinished())); anim->start(); } } m_pendingTouchToShareWinSet.clear(); } void CardWindowManager::removePendingActionWindow(CardWindow* win) { QSet<CardWindow*>::iterator it = m_pendingActionWinSet.find(win); if (it != m_pendingActionWinSet.end()) m_pendingActionWinSet.erase(it); it = m_pendingTouchToShareWinSet.find(win); if (it != m_pendingTouchToShareWinSet.end()) m_pendingTouchToShareWinSet.erase(it); } CardWindow* CardWindowManager::activeWindow() const { CardWindow* activeCard = NULL; CardWindow* w = NULL; if((NULL == m_activeGroup) || (NULL == (activeCard = m_activeGroup->activeCard()))) { return NULL; } else { w = activeCard->getModalChild(); return( NULL != w)? w: activeCard; } } CardGroup* CardWindowManager::activeGroup() const { return m_activeGroup; } void CardWindowManager::slotAnimationsFinished() { if(false == m_addingModalWindow) { if (m_anims.animationCount() == 0) { return; } } m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_anims.clear(); // make sure the active group stays at the top of the stacking order if (m_activeGroup) { m_activeGroup->raiseCards(); } performPendingFocusActions(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::slotDeletedAnimationFinished() { QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); // find the card whose animation finished and delete it if webkit already told us we can QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.begin(); for (; it != m_deletedAnimMap.end(); ++it) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (anim == a) { CardWindow* w = static_cast<CardWindow*>(it.key()); if (w->removed()) { m_deletedAnimMap.erase(it); delete w; delete a; } else { // since we don't adjust these when ui orientation changes, make sure they remain // invisible until the reaper comes to collect them w->setVisible(false); } break; } } } void CardWindowManager::slotTouchToShareAnimationFinished() { g_debug("%s: deleting TapToShare Ghost", __PRETTY_FUNCTION__); QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); GhostCard* target = static_cast<GhostCard*>(anim->targetObject()); delete anim; if (target) { delete target; } } void CardWindowManager::slotLauncherVisible(bool val, bool fullyVisible) { if (fullyVisible && !m_lowResMode) { m_lowResMode = true; Q_FOREACH(CardGroup* group, m_groups) { group->disableShadows(); } } else if (!fullyVisible && m_lowResMode) { m_lowResMode = false; Q_FOREACH(CardGroup* group, m_groups) { group->enableShadows(); } } } void CardWindowManager::slotLauncherShown(bool val) { if (!val) return; if (m_curState && m_curState->supportLauncherOverlay()) return; minimizeActiveWindow(); } void CardWindowManager::slotChangeCardWindow(bool next) { if (m_curState) m_curState->changeCardWindow(next); } void CardWindowManager::slotFocusMaximizedCardWindow(bool focus) { if (m_curState) m_curState->focusMaximizedCardWindow(focus); } void CardWindowManager::slotTouchToShareAppUrlTransfered(const std::string& appId) { if (m_curState) m_curState->processTouchToShareTransfer(appId); } void CardWindowManager::slotDismissActiveModalWindow() { if(Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::ServiceDismissedModalCard, true, ModalDismissAnimate); } else { resetModalFlags(); } } void CardWindowManager::slotDismissModalTimerStopped() { CardWindow* activeWin = activeWindow(); if(activeWin && (Window::Type_ModalChildWindowCard == activeWin->type()) && m_parentOfModalCard) { m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedAcceptingInput); } } void CardWindowManager::setInModeAnimation(bool animating) { if (animating) { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_SourceOver); } } else { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_Source); } } } void CardWindowManager::notifySysControllerOfModalStatus(int reason, bool restore, NotifySystemUiControllerAction type, Window* win) { if(type == Invalid) return; if(type == ModalLaunch) { // Notify SystemUiController of the result of the modal launch SystemUiController::instance()->setModalWindowLaunchErrReason((SystemUiController::ModalWinLaunchErrorReason)(reason)); // Signal that we no longer have an active modal window only if the reason is NoErr, else remove the window if(SystemUiController::NoErr == ((SystemUiController::ModalWinLaunchErrorReason)(reason))) { SystemUiController::instance()->notifyModalWindowActivated(m_parentOfModalCard); } else { // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; performPostModalWindowRemovedActions(win, restore); } return; } // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; // Notify SystemUiController of the reason why the modal was dismissed SystemUiController::instance()->setModalWindowDismissErrReason((SystemUiController::ModalWinDismissErrorReason)(reason)); if(type == ModalDismissAnimate) { // We need to animate the removal of the modal. So call this function, which will call performPostModalWindowRemovedActions(restore) with the correct params initiateRemovalOfActiveModalWindow(); } else { // directly get rid of the modal card performPostModalWindowRemovedActions(NULL, restore); } } void CardWindowManager::updateAllowWindowUpdates() { bool allow = true; if (m_animationsActive) allow = false; else if ((m_curState != m_maximizeState) && m_penDown) allow = false; Q_FOREACH(CardGroup* cg, m_groups) { Q_FOREACH(CardWindow* w, cg->cards()) w->allowUpdates(allow); } }
86,107
30,098
#include "TarsServantName.h" #include "TarsTest/TestcaseServer/RPCTest.h" #include "gtest/gtest.h" #include "servant/AdminF.h" #include "servant/Application.h" #include <cassert> #include <iostream> #include "util/tc_pack.h" using namespace std; using namespace tars; using namespace TarsTest; TEST(TarsUtilTestcase, UT_TC_Pack) { bool b = true; char c = 'a'; short si = 3; int ii = 4; char cn[] = "abc"; string sn = "def"; TC_PackIn pi; pi << b << c << si << ii << cn << sn; string s = pi.topacket(); TC_PackOut po(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; po >> si; assert(si == 3); cout << "short OK" << endl; po >> ii; assert(ii == 4); cout << "int OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> sn; assert(sn == "def"); cout << "string OK" << endl; { pi.clear(); pi << b << c; pi.insert(1) << cn; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; } { pi.clear(); pi << b << c; pi.replace(1) << 'b'; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'b'); cout << "char OK" << endl; } }
1,560
658
#include<bits/stdc++.h> #include<iostream> using namespace std; #define mod 10000000007 #define all(x) (x).begin(), (x).end() typedef long long ll; void subMain(){ ll r, c; cin >> r; cin >> c; ll ans = 0; ll z = max(r, c); ll z2 = (z - 1) * (z - 1); if (z % 2 == 0) { if (z == c) { ans = z2 + r; } else { ans = z2 + 2 * z - c; } } else { if (r == z) { ans = z2 + c; } else { ans = z2 + 2 * z - r; } } cout << ans << endl; } int32_t main(){ ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); ll t; cin >> t; while(t-- > 0){ subMain(); } //subMain(); return 0; }
648
370
#include<iostream> #include<cmath> #define pi 3.14 using namespace std; class Shape { protected: float area; //派生类可以访问protected,外部访问不了;派生类共有 public: Shape(); //构造函数 float Area(); //同名隐藏;输出area ~Shape(); //析构函数 }; class Rectangle : public Shape { private: float length, width; //长宽 public: Rectangle(float length, float width); //构造 float Area(); //计算area,并输出 ~Rectangle(); //析构 }; class Round : public Shape { private: float radius; //半径 public: Round(float radius); //构造 float Area(); //计算area,并输出 ~Round(); //析构 }; class Square : public Rectangle { private: float l; //边长 public: Square(float l); //构造 float Area(); //计算area,并输出 ~Square(); //析构 }; Shape::Shape(){ cout << "construct Shape\n"; area=0; } float Shape::Area(){ cout << "Shape Area:" << area << endl; return area; } Shape::~Shape(){ cout << "deleting Shape\n"; area=0; } Round::Round(float radius){ cout << "construct Round\n"; this->radius=radius; } float Round::Area(){ area=pi*radius*radius; cout << "Round Area:" << area << endl; return area; } Round::~Round(){ cout << "deleting Round\n"; } Rectangle::Rectangle(float length, float width){ cout << "construct Rectangle\n"; this->length=length, this->width=width; } float Rectangle::Area(){ area=length*width; cout << "Rectangle Area:" << area << endl; return area; } Rectangle::~Rectangle(){ cout << "deleting Rectangle\n"; } Square::Square(float l):Rectangle(l ,l){ //派生类的构造函数;同时赋值给基类Rectangle cout << "construct Square\n"; this->l = l; } float Square::Area(){ area=l*l; cout << "Square Area:"<< area << endl; return area; } Square::~Square(){ cout << "deleting Square\n"; } int main(){ float l; cout << "input square length:\n"; cin >> l; Square square(l); cout << endl; square.Area(); //同名隐藏规则 square.Rectangle::Area(); //限定类名 square.Shape::Area(); float r; cout << "\ninput Round radius:\n"; cin >> r; Round round(r); cout << endl; round.Area(); //同名隐藏规则 round.Shape::Area(); //限定类名 float length, width; cout << "input Rectangle (length, width):\n"; cin >> length >> width; Rectangle rectanle(length, width); cout << endl; rectanle.Area(); //同名隐藏规则 rectanle.Shape::Area(); //限定类名 cout << endl; return 0; }
2,253
1,013
#include "CSceneIterator.h" #include "CScene.h" CSceneIterator::CSceneIterator(CScene *pScene, FNodeFlags AllowedNodeTypes /*= eAllNodeTypes*/, bool AllowHiddenNodes /*= false*/) : mpScene(pScene) , mAllowHiddenNodes(AllowHiddenNodes) , mNodeFlags(AllowedNodeTypes) , mpCurNode(nullptr) { mMapIterator = mpScene->mNodes.begin(); while (mMapIterator != mpScene->mNodes.end()) { if (mMapIterator->first & AllowedNodeTypes) break; mMapIterator++; } if (mMapIterator != mpScene->mNodes.end()) { mVectorIterator = (mMapIterator->second).begin(); Next(); // Find first node } } // ************ PROTECTED ************ void CSceneIterator::InternalFindNext() { // This function does most of the heavy lifting. We continue from where we left off last time this function was called. while (mMapIterator != mpScene->mNodes.end()) { // Iterate over each node in the vector. std::vector<CSceneNode*>& rVector = mMapIterator->second; bool FoundNext = false; while (mVectorIterator != rVector.end()) { CSceneNode *pNode = *mVectorIterator; // Check node visibility if (mAllowHiddenNodes || pNode->IsVisible()) { mpCurNode = pNode; FoundNext = true; } mVectorIterator++; if (FoundNext) return; } // We've reached the end of this node vector, so advance the map iterator while (true) { mMapIterator++; if (mMapIterator == mpScene->mNodes.end()) { break; } if (mNodeFlags & mMapIterator->first) { mVectorIterator = mMapIterator->second.begin(); break; } } } // If we're down here, then it seems we're done iterating the scene. mpCurNode = nullptr; }
1,984
562
// Copyright 2016 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 "components/offline_pages/background/pick_request_task.h" #include <memory> #include <set> #include "base/bind.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "components/offline_pages/background/device_conditions.h" #include "components/offline_pages/background/offliner_policy.h" #include "components/offline_pages/background/request_coordinator.h" #include "components/offline_pages/background/request_coordinator_event_logger.h" #include "components/offline_pages/background/request_notifier.h" #include "components/offline_pages/background/request_queue_in_memory_store.h" #include "components/offline_pages/background/request_queue_store.h" #include "components/offline_pages/background/save_page_request.h" #include "testing/gtest/include/gtest/gtest.h" namespace offline_pages { namespace { // Data for request 1. const int64_t kRequestId1 = 17; const GURL kUrl1("https://google.com"); const ClientId kClientId1("bookmark", "1234"); // Data for request 2. const int64_t kRequestId2 = 42; const GURL kUrl2("http://nytimes.com"); const ClientId kClientId2("bookmark", "5678"); const bool kUserRequested = true; const int kAttemptCount = 1; const int kMaxStartedTries = 5; const int kMaxCompletedTries = 1; // Constants for policy values - These settings represent the default values. const bool kPreferUntried = false; const bool kPreferEarlier = true; const bool kPreferRetryCount = true; const int kBackgroundProcessingTimeBudgetSeconds = 170; // Default request const SavePageRequest kEmptyRequest(0UL, GURL(""), ClientId("", ""), base::Time(), true); } // namespace // Helper class needed by the PickRequestTask class RequestNotifierStub : public RequestNotifier { public: RequestNotifierStub() : last_expired_request_(kEmptyRequest), total_expired_requests_(0) {} void NotifyAdded(const SavePageRequest& request) override {} void NotifyChanged(const SavePageRequest& request) override {} void NotifyCompleted(const SavePageRequest& request, BackgroundSavePageResult status) override { last_expired_request_ = request; last_request_expiration_status_ = status; total_expired_requests_++; } const SavePageRequest& last_expired_request() { return last_expired_request_; } RequestCoordinator::BackgroundSavePageResult last_request_expiration_status() { return last_request_expiration_status_; } int32_t total_expired_requests() { return total_expired_requests_; } private: BackgroundSavePageResult last_request_expiration_status_; SavePageRequest last_expired_request_; int32_t total_expired_requests_; }; class PickRequestTaskTest : public testing::Test { public: PickRequestTaskTest(); ~PickRequestTaskTest() override; void SetUp() override; void PumpLoop(); void AddRequestDone(ItemActionStatus status); void RequestPicked(const SavePageRequest& request); void RequestNotPicked(const bool non_user_requested_tasks_remaining); void RequestCountCallback(size_t total_count, size_t available_count); void QueueRequests(const SavePageRequest& request1, const SavePageRequest& request2); // Reset the factory and the task using the current policy. void MakeFactoryAndTask(); RequestNotifierStub* GetNotifier() { return notifier_.get(); } PickRequestTask* task() { return task_.get(); } void TaskCompletionCallback(Task* completed_task); protected: std::unique_ptr<RequestQueueStore> store_; std::unique_ptr<RequestNotifierStub> notifier_; std::unique_ptr<SavePageRequest> last_picked_; std::unique_ptr<OfflinerPolicy> policy_; RequestCoordinatorEventLogger event_logger_; std::set<int64_t> disabled_requests_; std::unique_ptr<PickRequestTaskFactory> factory_; std::unique_ptr<PickRequestTask> task_; bool request_queue_not_picked_called_; size_t total_request_count_; size_t available_request_count_; bool task_complete_called_; private: scoped_refptr<base::TestSimpleTaskRunner> task_runner_; base::ThreadTaskRunnerHandle task_runner_handle_; }; PickRequestTaskTest::PickRequestTaskTest() : task_runner_(new base::TestSimpleTaskRunner), task_runner_handle_(task_runner_) {} PickRequestTaskTest::~PickRequestTaskTest() {} void PickRequestTaskTest::SetUp() { DeviceConditions conditions; store_.reset(new RequestQueueInMemoryStore()); policy_.reset(new OfflinerPolicy()); notifier_.reset(new RequestNotifierStub()); MakeFactoryAndTask(); request_queue_not_picked_called_ = false; total_request_count_ = 9999; available_request_count_ = 9999; task_complete_called_ = false; last_picked_.reset(); } void PickRequestTaskTest::PumpLoop() { task_runner_->RunUntilIdle(); } void PickRequestTaskTest::TaskCompletionCallback(Task* completed_task) { task_complete_called_ = true; } void PickRequestTaskTest::AddRequestDone(ItemActionStatus status) {} void PickRequestTaskTest::RequestPicked(const SavePageRequest& request) { last_picked_.reset(new SavePageRequest(request)); } void PickRequestTaskTest::RequestNotPicked( const bool non_user_requested_tasks_remaining) { request_queue_not_picked_called_ = true; } void PickRequestTaskTest::RequestCountCallback(size_t total_count, size_t available_count) { total_request_count_ = total_count; available_request_count_ = available_count; } // Test helper to queue the two given requests. void PickRequestTaskTest::QueueRequests(const SavePageRequest& request1, const SavePageRequest& request2) { DeviceConditions conditions; std::set<int64_t> disabled_requests; // Add test requests on the Queue. store_->AddRequest(request1, base::Bind(&PickRequestTaskTest::AddRequestDone, base::Unretained(this))); store_->AddRequest(request2, base::Bind(&PickRequestTaskTest::AddRequestDone, base::Unretained(this))); // Pump the loop to give the async queue the opportunity to do the adds. PumpLoop(); } void PickRequestTaskTest::MakeFactoryAndTask() { factory_.reset(new PickRequestTaskFactory(policy_.get(), notifier_.get(), &event_logger_)); DeviceConditions conditions; task_ = factory_->CreatePickerTask( store_.get(), base::Bind(&PickRequestTaskTest::RequestPicked, base::Unretained(this)), base::Bind(&PickRequestTaskTest::RequestNotPicked, base::Unretained(this)), base::Bind(&PickRequestTaskTest::RequestCountCallback, base::Unretained(this)), conditions, disabled_requests_); task_->SetTaskCompletionCallbackForTesting( task_runner_.get(), base::Bind(&PickRequestTaskTest::TaskCompletionCallback, base::Unretained(this))); } TEST_F(PickRequestTaskTest, PickFromEmptyQueue) { task()->Run(); PumpLoop(); // Pump the loop again to give the async queue the opportunity to return // results from the Get operation, and for the picker to call the "QueueEmpty" // callback. PumpLoop(); EXPECT_TRUE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 0, total_request_count_); EXPECT_EQ((size_t) 0, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithHigherRetryCount) { // Set up policy to prefer higher retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 2, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithSameRetryCountButEarlier) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseEarlierRequest) { // We need a custom policy object prefering recency to retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseSameTimeRequestWithHigherRetryCount) { // We need a custom policy object preferring recency to retry count. policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestWithLowerRetryCount) { // We need a custom policy object preferring lower retry count. policy_.reset(new OfflinerPolicy( !kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseLaterRequest) { // We need a custom policy preferring recency over retry, and later requests. policy_.reset(new OfflinerPolicy( kPreferUntried, !kPreferEarlier, !kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries, kBackgroundProcessingTimeBudgetSeconds)); MakeFactoryAndTask(); base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(10); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseNonExpiredRequest) { base::Time creation_time = base::Time::Now(); base::Time expired_time = creation_time - base::TimeDelta::FromSeconds( policy_->GetRequestExpirationTimeInSeconds() + 60); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, expired_time, kUserRequested); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ(kRequestId2, GetNotifier()->last_expired_request().request_id()); EXPECT_EQ(RequestNotifier::BackgroundSavePageResult::EXPIRED, GetNotifier()->last_request_expiration_status()); EXPECT_EQ(1, GetNotifier()->total_expired_requests()); EXPECT_EQ((size_t) 1, total_request_count_); EXPECT_EQ((size_t) 1, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatHasNotExceededStartLimit) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(1); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); // With default policy settings, we should choose the earlier request. // However, we will make the earlier reqeust exceed the limit. request1.set_started_attempt_count(policy_->GetMaxStartedTries()); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); // TODO(dougarnett): Counts should be 1 here once requests exceeding start // count get cleaned up from the queue. EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 2, available_request_count_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatHasNotExceededCompletionLimit) { base::Time creation_time1 = base::Time::Now() - base::TimeDelta::FromSeconds(1); base::Time creation_time2 = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time1, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time2, kUserRequested); // With default policy settings, we should choose the earlier request. // However, we will make the earlier reqeust exceed the limit. request1.set_completed_attempt_count(policy_->GetMaxCompletedTries()); QueueRequests(request1, request2); task()->Run(); PumpLoop(); EXPECT_EQ(kRequestId2, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_TRUE(task_complete_called_); } TEST_F(PickRequestTaskTest, ChooseRequestThatIsNotDisabled) { policy_.reset(new OfflinerPolicy( kPreferUntried, kPreferEarlier, kPreferRetryCount, kMaxStartedTries, kMaxCompletedTries + 1, kBackgroundProcessingTimeBudgetSeconds)); // put request 2 on disabled list, ensure request1 picked instead, // even though policy would prefer 2. disabled_requests_.insert(kRequestId2); MakeFactoryAndTask(); base::Time creation_time = base::Time::Now(); SavePageRequest request1(kRequestId1, kUrl1, kClientId1, creation_time, kUserRequested); SavePageRequest request2(kRequestId2, kUrl2, kClientId2, creation_time, kUserRequested); request2.set_completed_attempt_count(kAttemptCount); // Add test requests on the Queue. QueueRequests(request1, request2); task()->Run(); PumpLoop(); // Pump the loop again to give the async queue the opportunity to return // results from the Get operation, and for the picker to call the "picked" // callback. PumpLoop(); EXPECT_EQ(kRequestId1, last_picked_->request_id()); EXPECT_FALSE(request_queue_not_picked_called_); EXPECT_EQ((size_t) 2, total_request_count_); EXPECT_EQ((size_t) 1, available_request_count_); EXPECT_TRUE(task_complete_called_); } } // namespace offline_pages
17,397
5,600
// Copyright 2013 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/sync_file_system/drive_backend/metadata_db_migration_util.h" #include <memory> #include "base/files/file_path.h" #include "base/strings/string_util.h" #include "chrome/browser/sync_file_system/drive_backend/drive_backend_util.h" #include "storage/common/file_system/file_system_types.h" #include "storage/common/file_system/file_system_util.h" #include "third_party/leveldatabase/src/include/leveldb/db.h" #include "third_party/leveldatabase/src/include/leveldb/write_batch.h" #include "url/gurl.h" namespace sync_file_system { namespace drive_backend { SyncStatusCode MigrateDatabaseFromV4ToV3(leveldb::DB* db) { // Rollback from version 4 to version 3. // Please see metadata_database_index.cc for version 3 format, and // metadata_database_index_on_disk.cc for version 4 format. const char kDatabaseVersionKey[] = "VERSION"; const char kServiceMetadataKey[] = "SERVICE"; const char kFileMetadataKeyPrefix[] = "FILE: "; const char kFileTrackerKeyPrefix[] = "TRACKER: "; // Key prefixes used in version 4. const char kAppRootIDByAppIDKeyPrefix[] = "APP_ROOT: "; const char kActiveTrackerIDByFileIDKeyPrefix[] = "ACTIVE_FILE: "; const char kTrackerIDByFileIDKeyPrefix[] = "TRACKER_FILE: "; const char kMultiTrackerByFileIDKeyPrefix[] = "MULTI_FILE: "; const char kActiveTrackerIDByParentAndTitleKeyPrefix[] = "ACTIVE_PATH: "; const char kTrackerIDByParentAndTitleKeyPrefix[] = "TRACKER_PATH: "; const char kMultiBackingParentAndTitleKeyPrefix[] = "MULTI_PATH: "; const char kDirtyIDKeyPrefix[] = "DIRTY: "; const char kDemotedDirtyIDKeyPrefix[] = "DEMOTED_DIRTY: "; leveldb::WriteBatch write_batch; write_batch.Put(kDatabaseVersionKey, "3"); std::unique_ptr<leveldb::Iterator> itr( db->NewIterator(leveldb::ReadOptions())); for (itr->SeekToFirst(); itr->Valid(); itr->Next()) { std::string key = itr->key().ToString(); // Do nothing for valid entries in both versions. if (base::StartsWith(key, kServiceMetadataKey, base::CompareCase::SENSITIVE) || base::StartsWith(key, kFileMetadataKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kFileTrackerKeyPrefix, base::CompareCase::SENSITIVE)) { continue; } // Drop entries used in version 4 only. if (base::StartsWith(key, kAppRootIDByAppIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kActiveTrackerIDByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kTrackerIDByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kMultiTrackerByFileIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kActiveTrackerIDByParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kTrackerIDByParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kMultiBackingParentAndTitleKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kDirtyIDKeyPrefix, base::CompareCase::SENSITIVE) || base::StartsWith(key, kDemotedDirtyIDKeyPrefix, base::CompareCase::SENSITIVE)) { write_batch.Delete(key); continue; } DVLOG(3) << "Unknown key: " << key << " was found."; } return LevelDBStatusToSyncStatusCode( db->Write(leveldb::WriteOptions(), &write_batch)); } } // namespace drive_backend } // namespace sync_file_system
3,882
1,256
// Copyright 2021 The IREE Authors // // Licensed under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtDialect.h" #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.h" #include "llvm/ADT/SmallVector.h" #include "llvm/Support/SourceMgr.h" #include "mlir/IR/Attributes.h" #include "mlir/IR/DialectImplementation.h" #include "mlir/IR/OpDefinition.h" #include "mlir/IR/OpImplementation.h" #include "mlir/Parser.h" #include "mlir/Transforms/InliningUtils.h" namespace mlir { namespace iree_compiler { namespace linalg_ext { LinalgExtDialect::LinalgExtDialect(MLIRContext *context) : Dialect(getDialectNamespace(), context, TypeID::get<LinalgExtDialect>()) { // TODO(hanchung): Add interface to the dialect. // addInterfaces<IREEInlinerInterface>(); #define GET_OP_LIST addOperations< #include "iree/compiler/Dialect/LinalgExt/IR/LinalgExtOps.cpp.inc" >(); } } // namespace linalg_ext } // namespace iree_compiler } // namespace mlir
1,132
438
/******************************************************************************* * Copyright 2021 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #include "oneapi/dal/algo/kmeans/test/fixture.hpp" namespace oneapi::dal::kmeans::test { template <typename TestType> class kmeans_batch_test : public kmeans_test<TestType, kmeans_batch_test<TestType>> {}; /* TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans degenerated test", "[kmeans][batch]", kmeans_types) { // number of observations is equal to number of centroids (obvious clustering) SKIP_IF(this->not_float64_friendly()); using Float = std::tuple_element_t<0, TestType>; Float data[] = { 0.0, 5.0, 0.0, 0.0, 0.0, 1.0, 1.0, 4.0, 0.0, 0.0, 1.0, 0.0, 0.0, 5.0, 1.0 }; const auto x = homogen_table::wrap(data, 3, 5); Float responses[] = { 0, 1, 2 }; const auto y = homogen_table::wrap(responses, 3, 1); this->exact_checks(x, x, x, y, 3, 2, 0.0, 0.0, false); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans relocation test", "[kmeans][batch]", kmeans_types) { // relocation of empty cluster to the best candidate SKIP_IF(this->not_float64_friendly()); using Float = std::tuple_element_t<0, TestType>; Float data[] = { 0, 0, 0.5, 0, 0.5, 1, 1, 1 }; const auto x = homogen_table::wrap(data, 4, 2); Float initial_centroids[] = { 0.5, 0.5, 3, 3 }; const auto c_init = homogen_table::wrap(initial_centroids, 2, 2); Float final_centroids[] = { 0.25, 0, 0.75, 1 }; const auto c_final = homogen_table::wrap(final_centroids, 2, 2); std::int64_t responses[] = { 0, 0, 1, 1 }; const auto y = homogen_table::wrap(responses, 4, 1); Float expected_obj_function = 0.25; std::int64_t expected_n_iters = 4; this->exact_checks_with_reordering(x, c_init, c_final, y, 2, expected_n_iters + 1, 0.0, expected_obj_function, false); } */ TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans empty clusters test", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_empty_clusters(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans smoke train/infer test", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_on_smoke_data(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans train/infer on gold data", "[kmeans][batch]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->check_on_gold_data(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans block test", "[kmeans][batch][nightly][block]", kmeans_types) { // This test is not stable on CPU // TODO: Remove the following `SKIP_IF` once stability problem is resolved SKIP_IF(this->get_policy().is_cpu()); SKIP_IF(this->not_float64_friendly()); this->check_on_large_data_with_one_cluster(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "kmeans partial centroids stress test", "[kmeans][batch][nightly][stress]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); this->partial_centroids_stress_test(); } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "higgs: samples=1M, iters=3", "[kmeans][batch][external-dataset][higgs]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 3; const std::string higgs_path = "workloads/higgs/dataset/higgs_1m_test.csv"; SECTION("clusters=10") { this->test_on_dataset(higgs_path, 10, iters, 3.1997724684, 14717484.0); } SECTION("clusters=100") { this->test_on_dataset(higgs_path, 100, iters, 2.7450205195, 10704352.0); } SECTION("cluster=250") { this->test_on_dataset(higgs_path, 250, iters, 2.5923397174, 9335216.0); } } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "susy: samples=0.5M, iters=10", "[kmeans][nightly][batch][external-dataset][susy]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 10; const std::string susy_path = "workloads/susy/dataset/susy_test.csv"; SECTION("clusters=10") { this->test_on_dataset(susy_path, 10, iters, 1.7730860782, 3183696.0); } SECTION("clusters=100") { this->test_on_dataset(susy_path, 100, iters, 1.9384844916, 1757022.625); } SECTION("cluster=250") { this->test_on_dataset(susy_path, 250, iters, 1.8950113604, 1400958.5); } } TEMPLATE_LIST_TEST_M(kmeans_batch_test, "epsilon: samples=80K, iters=2", "[kmeans][nightly][batch][external-dataset][epsilon]", kmeans_types) { SKIP_IF(this->not_float64_friendly()); const std::int64_t iters = 2; const std::string epsilon_path = "workloads/epsilon/dataset/epsilon_80k_train.csv"; SECTION("clusters=512") { this->test_on_dataset(epsilon_path, 512, iters, 6.9367580565, 50128.640625, 1.0e-3); } SECTION("clusters=1024") { this->test_on_dataset(epsilon_path, 1024, iters, 5.59003873, 49518.75, 1.0e-3); } SECTION("cluster=2048") { this->test_on_dataset(epsilon_path, 2048, iters, 4.3202752143, 48437.6015625, 1.0e-3); } } } // namespace oneapi::dal::kmeans::test
6,516
2,542
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "pg/AsyncConnection.hxx" #include "event/FineTimerEvent.hxx" #include "io/Logger.hxx" #include <unordered_set> #include <unordered_map> #include <set> #include <string> #include <mutex> struct CertDatabaseConfig; class CertNameCacheHandler { public: virtual void OnCertModified(const std::string &name, bool deleted) noexcept = 0; }; /** * A frontend for #CertDatabase which establishes a cache of all host * names and keeps it up to date. * * All modifications run asynchronously in the main thread, and * std::unordered_set queries may be executed from any thread * (protected by the mutex). */ class CertNameCache final : Pg::AsyncConnectionHandler, Pg::AsyncResultHandler { const LLogger logger; CertNameCacheHandler &handler; Pg::AsyncConnection conn; FineTimerEvent update_timer; mutable std::mutex mutex; /** * A list of host names found in the database. */ std::unordered_set<std::string> names; /** * A list of alt_names found in the database. Each alt_name maps * to a list of common_name values it appears in. */ std::unordered_map<std::string, std::set<std::string>> alt_names; /** * The latest timestamp seen in a record. This is used for * incremental updates. */ std::string latest = "1971-01-01"; unsigned n_added, n_updated, n_deleted; /** * This flag is set to true as soon as the cached name list has * become complete for the first time. With an incomplete cache, * Lookup() will always return true, because we don't know yet if * the desired name is just not yet loaded. */ bool complete = false; public: CertNameCache(EventLoop &event_loop, const CertDatabaseConfig &config, CertNameCacheHandler &_handler) noexcept; auto &GetEventLoop() const noexcept { return update_timer.GetEventLoop(); } void Connect() noexcept { conn.Connect(); } void Disconnect() noexcept { conn.Disconnect(); update_timer.Cancel(); } /** * Check if the given name exists in the database. */ bool Lookup(const char *host) const noexcept; private: void OnUpdateTimer() noexcept; void ScheduleUpdate() noexcept; void UnscheduleUpdate() noexcept { update_timer.Cancel(); } void AddAltName(const std::string &common_name, std::string &&alt_name) noexcept; void RemoveAltName(const std::string &common_name, const std::string &alt_name) noexcept; /* virtual methods from Pg::AsyncConnectionHandler */ void OnConnect() override; void OnDisconnect() noexcept override; void OnNotify(const char *name) override; void OnError(std::exception_ptr e) noexcept override; /* virtual methods from Pg::AsyncResultHandler */ void OnResult(Pg::Result &&result) override; void OnResultEnd() override; void OnResultError() noexcept override; };
4,206
1,413
// Fill out your copyright notice in the Description page of Project Settings. #include "HeroCharacter.h" #include "GameFramework/Character.h" #include "Components/InputComponent.h" #include "Components/SceneComponent.h" #include "UObject/ConstructorHelpers.h" AHeroCharacter::AHeroCharacter() { // Set this character to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; //Camera setting selfie_stick = CreateDefaultSubobject<USpringArmComponent>(TEXT("SelfieStick")); selfie_stick->SetupAttachment(RootComponent); selfie_stick->TargetArmLength = 100; selfie_stick->SetRelativeRotation(FRotator(-90, 0, 0)); selfie_stick->bDoCollisionTest = false; selfie_stick->bInheritPitch = false; selfie_stick->bInheritRoll = false; selfie_stick->bInheritYaw = false; hero_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("HeroCamera")); hero_camera->SetupAttachment(selfie_stick); hero_camera->SetRelativeRotation(FRotator(90, 0, 0)); hero_camera->bUsePawnControlRotation = true; /*static ConstructorHelpers::FObjectFinder<UClass>FoundWeapon(TEXT("BlueprintGeneratedClass'/Game/Weapons/MyBaseWeapon.MyBaseWeapon_C'")); if (FoundWeapon.Succeeded()) { weapon_class = FoundWeapon.Object; }*/ /*static ConstructorHelpers::FObjectFinder<UClass>AnimClass(TEXT("AnimBlueprintGeneratedClass'/Game/MyAnim/HeroAnimBP.HeroAnimBP_C'")); if (AnimClass.Succeeded()) { anim_instance_class = AnimClass.Object; }*/ this->Tags.Add(FName("Player")); } void AHeroCharacter::BeginPlay() { Super::BeginPlay(); if (weapon_class) { FActorSpawnParameters SpawnInfo; auto transform = GetTransform(); transform.SetLocation(FVector(30, 0, -30)); SpawnInfo.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AlwaysSpawn; weapon = GetWorld()->SpawnActor<ABaseWeapon>(weapon_class, transform, SpawnInfo); weapon->weapon_mesh->AttachToComponent(hero_camera, FAttachmentTransformRules::KeepRelativeTransform); weapon->AttachToComponent(hero_camera, FAttachmentTransformRules::KeepRelativeTransform); } } void AHeroCharacter::move_up(float val) { AddMovementInput(GetActorForwardVector(), val); } void AHeroCharacter::move_right(float val) { AddMovementInput(GetActorRightVector(), val); } void AHeroCharacter::look_up(float val) { AddControllerPitchInput(val); } void AHeroCharacter::turn(float val) { AddControllerYawInput(val); } void AHeroCharacter::attack() { if (weapon) { weapon->fire(); } } void AHeroCharacter::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AHeroCharacter::SetupPlayerInputComponent(UInputComponent *PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("MoveUp", this, &AHeroCharacter::move_up); PlayerInputComponent->BindAxis("MoveRight", this, &AHeroCharacter::move_right); PlayerInputComponent->BindAxis("LookUp", this, &AHeroCharacter::look_up); PlayerInputComponent->BindAxis("Turn", this, &AHeroCharacter::turn); PlayerInputComponent->BindAction("Fire", IE_Pressed, this, &AHeroCharacter::attack); }
3,139
1,128
/*************************************************************************** * * $Id: StMcSvtLadderHitCollection.cc,v 2.5 2005/01/27 23:40:48 calderon Exp $ * * Author: Manuel Calderon de la Barca Sanchez, Oct 1999 *************************************************************************** * * Description: Monte Carlo Svt Ladder Hit Collection class * *************************************************************************** * * $Log: StMcSvtLadderHitCollection.cc,v $ * Revision 2.5 2005/01/27 23:40:48 calderon * Adding persistency to StMcEvent as a step for Virtual MonteCarlo. * * Revision 2.4 2000/04/19 14:34:48 calderon * More corrections for the SSD, thanks Helen * * Revision 2.3 2000/03/06 18:05:22 calderon * 1) Modified SVT Hits storage scheme from layer-ladder-wafer to * barrel-ladder-wafer. * 2) Added Rich Hit class and collection, and links to them in other * classes. * * Revision 2.2 1999/12/14 07:04:49 calderon * Numbering scheme as per SVT request. * * Revision 2.1 1999/11/19 19:06:33 calderon * Recommit after redoing the files. * * Revision 2.0 1999/11/17 02:01:00 calderon * Completely revised for new StEvent * * **************************************************************************/ #include "StMcSvtLadderHitCollection.hh" static const char rcsid[] = "$Id: StMcSvtLadderHitCollection.cc,v 2.5 2005/01/27 23:40:48 calderon Exp $"; ClassImp(StMcSvtLadderHitCollection); StMcSvtLadderHitCollection::StMcSvtLadderHitCollection() { mBarrelNumber = -1; } StMcSvtLadderHitCollection::~StMcSvtLadderHitCollection() { /* noop */ } void StMcSvtLadderHitCollection::setBarrelNumber(int i) { if (mBarrelNumber == -1) mBarrelNumber = i; } unsigned int StMcSvtLadderHitCollection::numberOfWafers() const { switch (mBarrelNumber) { case 0: return 4; break; case 1: return 6; break; case 2: return 7; break; case 3: // SSD return 16; break; default: return 0; } } unsigned long StMcSvtLadderHitCollection::numberOfHits() const { unsigned long sum = 0; for (unsigned int j=0; j<numberOfWafers(); j++) { sum += mWafers[j].hits().size(); } return sum; } StMcSvtWaferHitCollection* StMcSvtLadderHitCollection::wafer(unsigned int i) { if (i < numberOfWafers()) return &(mWafers[i]); else return 0; } const StMcSvtWaferHitCollection* StMcSvtLadderHitCollection::wafer(unsigned int i) const { if (i < numberOfWafers()) return &(mWafers[i]); else return 0; }
2,603
1,014
#include "raytracer.hpp" #include "ray.hpp" #include "scene.hpp" #include "primitive/iprimitive.hpp" namespace Rendering { RayTracer::RayTracer(unsigned long pixelWidth, unsigned long pixelHeight, double width, double height, double depth) : m_pixel_width(pixelWidth) , m_pixel_height(pixelHeight) , width(width) , height(height) , depth(depth) { origin.fill(0.); direction.fill(0.); direction(2) = 1; updateParameters(); } RayTracer::~RayTracer() = default; Image RayTracer::draw() const { Image res{Eigen::Index(m_pixel_height), Eigen::Index(m_pixel_width)}; for(std::size_t j = 0; j < m_pixel_height; ++j) { for(std::size_t i = 0; i < m_pixel_width; ++i) { res(j, i) = computeColor(generateRay(i, j)); } } return res; } void RayTracer::setViewer(double width, double height, const Math::Vector3d& origin, const Math::Vector3d& direction) { this->width = width; this->height = height; this->origin = origin; this->direction = direction; updateParameters(); } void RayTracer::setResolution(unsigned long pixelWidth, unsigned long pixelHeight) { m_pixel_width = pixelWidth; m_pixel_height = pixelHeight; updateParameters(); } void RayTracer::setScene(Scene* scene) { m_scene = scene; } Ray RayTracer::generateRay(const std::size_t x, const std::size_t y) const { Math::Vector3d dir = Math::createPoint(precompWidth * (x - m_pixel_width / 2.), precompHeight * (y - m_pixel_height / 2.), depth); return Ray(origin, Math::normalize(dir)); } Color RayTracer::computeColor(const Ray& ray) const { Color color; color.fill(0.); double distance; const auto index = m_scene->getFirstCollision(ray, distance); if(index) { Math::Vector3d normal; auto& primitive = m_scene->getPrimitive(*index); primitive.computeColorNormal(ray, distance, color, normal); } return color; } void RayTracer::updateParameters() { precompWidth = width / m_pixel_width; precompHeight = height / m_pixel_height; } } // Rendering
2,117
749
/** * Copyright - See the COPYRIGHT that is included with this distribution. * pvxs is distributed subject to a Software License Agreement found * in file LICENSE that is included with this distribution. */ #include "pvxs/version.h" #if !defined(GCC_VERSION) || GCC_VERSION>VERSION_INT(4,9,0,0) # include <regex> #else // GCC 4.8 provides the regex header and symbols, but with a no-op implementation // so fill in the gap with POSIX regex # include <sys/types.h> # include <regex.h> # define USE_POSIX_REGEX #endif #include <epicsUnitTest.h> #include "pvxs/unittest.h" #include "utilpvt.h" #include "udp_collector.h" namespace pvxs { void testSetup() { #ifdef _WIN32 // One of the SEM_* options, either SEM_FAILCRITICALERRORS or SEM_NOGPFAULTERRORBOX, // depending on who you ask, acts to disable Windows Error Reporting entirely. // This also prevents the AeDebug facility from triggering. UINT prev = SetErrorMode(0); if(prev) testDiag("SetErrorMode() disables 0x%x\n", (unsigned)prev); #endif } void cleanup_for_valgrind() { for(auto& pair : instanceSnapshot()) { // This will mess up test counts, but is the only way // 'prove' will print the result in CI runs. if(pair.second!=0) testFail("Instance leak %s : %zu", pair.first.c_str(), pair.second); } #if LIBEVENT_VERSION_NUMBER >= 0x02010000 libevent_global_shutdown(); #endif impl::logger_shutdown(); impl::UDPManager::cleanup(); IfaceMap::cleanup(); } testCase::testCase() :result(Diag) {} testCase::testCase(bool result) :result(result ? Pass : Fail) {} testCase::testCase(testCase&& o) noexcept :result(o.result) #if !GCC_VERSION || GCC_VERSION>=VERSION_INT(4,10,0,0) ,msg(std::move(o.msg)) #else // gcc 4.8 (at least) doesn't provide a move ctor yet ,msg(o.msg.str()) #endif { o.result = Nothing; } testCase& testCase::operator=(testCase&& o) noexcept { if(this!=&o) { result = o.result; o.result = Nothing; #if !GCC_VERSION || GCC_VERSION>=VERSION_INT(4,10,0,0) msg = std::move(o.msg); #else msg.seekp(0); msg.str(o.msg.str()); #endif } return *this; } testCase::~testCase() { if(result==Nothing) return; std::istringstream strm(msg.str()); for(std::string line; std::getline(strm, line);) { if(result==Diag) { testDiag("%s", line.c_str()); } else { testOk(result==Pass, "%s", line.c_str()); result=Diag; } } } testCase& testCase::setPassMatch(const std::string& expr, const std::string& inp) { #ifdef USE_POSIX_REGEX regex_t ex{}; if(auto err = regcomp(&ex, expr.c_str(), REG_EXTENDED|REG_NOSUB)) { auto len = regerror(err, &ex, nullptr, 0u); std::vector<char> msg(len+1); (void)regerror(err, &ex, msg.data(), len); msg[len] = '\0'; // paranoia setPass(false); (*this)<<" expression error: "<<msg.data()<<" :"; } else { setPass(regexec(&ex, inp.c_str(), 0, nullptr, 0)!=REG_NOMATCH); regfree(&ex); } #else std::regex ex; try { ex.assign(expr, std::regex_constants::extended); setPass(std::regex_match(inp, ex)); }catch(std::regex_error& e) { setPass(false); (*this)<<" expression error: "<<e.what()<<" :"; } #endif return *this; } namespace detail { size_t findNextLine(const std::string& s, size_t pos=0u) { size_t next = s.find_first_of('\n', pos); if(next!=std::string::npos) next++; return next; } testCase _testStrTest(unsigned op, const char *sLHS, const char* rlhs, const char *sRHS, const char* rrhs) { bool eq; if(rlhs==rrhs) // same string. handles NULL==NULL eq = true; else if(!rlhs ^ !rrhs) // one NULL eq = false; else eq = strcmp(rlhs, rrhs)==0; testCase ret(eq==op); ret<<sLHS<<(op ? " == " : " != ")<<sRHS<<"\n"; std::string lhs(rlhs ? rlhs : "<null>"); std::string rhs(rrhs ? rrhs : "<null>"); size_t posL=0u, posR=0u; while(posL<lhs.size() && posR<rhs.size()) { size_t eolL = findNextLine(lhs, posL); size_t eolR = findNextLine(rhs, posR); auto L = lhs.substr(posL, eolL-posL); auto R = rhs.substr(posR, eolR-posR); if(L==R) { ret<<" \""<<escape(L)<<"\"\n"; } else { ret<<"+ \""<<escape(R)<<"\"\n"; ret<<"- \""<<escape(L)<<"\"\n"; } posL = eolL; posR = eolR; } while(posR<rhs.size()) { size_t eol = findNextLine(rhs, posR); auto line = rhs.substr(posR, eol-posR); ret<<"+ \""<<escape(line)<<"\"\n"; posR = eol; } while(posL<lhs.size()) { size_t eol = findNextLine(lhs, posL); auto line = lhs.substr(posL, eol-posL); ret<<"- \""<<escape(line)<<"\"\n"; posL = eol; } return ret; } testCase _testStrMatch(const char *spat, const std::string& pat, const char *sstr, const std::string& str) { testCase ret; ret.setPassMatch(pat, str); ret<<spat<<" (\""<<pat<<"\") match "<<str<<" (\""<<escape(str)<<"\")"; return ret; } } // namespace detail } // namespace pvxs
5,268
2,022
#include <agz/editor/material/material_thumbnail.h> #include <agz/tracer/core/intersection.h> #include <agz/tracer/core/bsdf.h> #include <agz/tracer/core/light.h> #include <agz/tracer/core/sampler.h> #include <agz/tracer/create/envir_light.h> #include <agz/tracer/create/texture2d.h> #include <agz/tracer/utility/sphere_aux.h> #include <agz-utils/image.h> AGZ_EDITOR_BEGIN namespace { class MaterialThumbnailEnvLight { RC<const tracer::EnvirLight> env_light_; public: MaterialThumbnailEnvLight() { const unsigned char data[] = { #include "./material_thumbnail_env.txt" }; auto tex_data = img::load_rgb_from_hdr_memory(data, sizeof(data)); auto img_data = newRC<Image2D<math::color3f>>(std::move(tex_data)); auto tex = tracer::create_hdr_texture({}, img_data, "linear"); env_light_ = create_ibl_light(tex); } const tracer::EnvirLight *operator->() const { return env_light_.get(); } }; Spectrum illum( const Vec3 &wo, const Vec3 &nor, const tracer::BSDF *bsdf, const MaterialThumbnailEnvLight &light, tracer::Sampler &sampler) { Spectrum bsdf_illum, light_illum; const auto bsdf_sample = bsdf->sample_all( wo, tracer::TransMode::Radiance, sampler.sample3()); if(!bsdf_sample.f.is_black()) { const real cos_v = std::abs(cos(bsdf_sample.dir, nor)); const Spectrum env = light->radiance({}, bsdf_sample.dir); if(bsdf->is_delta()) bsdf_illum = bsdf_sample.f * cos_v * env / bsdf_sample.pdf; else { const real env_pdf = light->pdf({}, bsdf_sample.dir); bsdf_illum = bsdf_sample.f * cos_v * env / (bsdf_sample.pdf + env_pdf); } } const auto light_sample = light->sample({}, sampler.sample5()); if(!light_sample.radiance.is_black()) { const Vec3 wi = light_sample.ref_to_light(); const Spectrum f = bsdf->eval_all(wi, wo, tracer::TransMode::Radiance); const real cos_v = std::abs(cos(wi, nor)); const real bsdf_pdf = bsdf->pdf_all(wi, wo); light_illum = light_sample.radiance * f * cos_v / (light_sample.pdf + bsdf_pdf); } return bsdf_illum + light_illum; } } // IMPROVE: bssrdf is not handled void MaterialThumbnailProvider::run_one_iter(int spp) { static const MaterialThumbnailEnvLight env; tracer::Arena arena; real init_xf, zf, df; if(width_ < height_) { df = real(6) / width_; init_xf = -3 + df / 2; zf = real(height_) / width_ * 3 - df / 2; } else { df = real(6) / height_; zf = 3 - df / 2; init_xf = -real(width_) / height_ * 3 + df / 2; } for(int y = 0; y < height_; ++y) { real xf = init_xf; if(exit_) return; for(int x = 0; x < width_; ++x) { for(int s = 0; s < spp; ++s) { const real pxf = xf + (sampler_->sample1().u - 1) * df; const real pzf = zf + (sampler_->sample1().u - 1) * df; if(pxf * pxf + pzf * pzf < 4) { const real pyf = -std::sqrt(4 - pxf * pxf - pzf * pzf); tracer::FCoord coord; Vec2 uv; tracer::sphere::local_geometry_uv_and_coord( { pxf, pyf, pzf }, &uv, &coord, 2); tracer::SurfacePoint spt; spt.pos = { pxf, pyf, pzf }; spt.uv = uv; spt.geometry_coord = coord; spt.user_coord = coord; tracer::EntityIntersection inct; (tracer::SurfacePoint &)inct = spt; inct.entity = nullptr; inct.material = mat_.get(); inct.medium_in = nullptr; inct.medium_out = nullptr; inct.wr = { 0, 0, 1 }; inct.t = 1; auto shd = mat_->shade(inct, arena); Spectrum color; for(int j = 0; j < 4; ++j) { color += illum( { 0, -1, 0 }, spt.geometry_coord.z, shd.bsdf, env, *sampler_); } accum_color_(y, x) += real(0.25) * color; } else accum_color_(y, x) += Spectrum(real(0.2)); } xf += df; } zf -= df; } ++finished_iters_; finished_spp_ += spp; } QPixmap MaterialThumbnailProvider::compute_pixmap() { assert(finished_iters_ > 0); const real ratio = real(1) / finished_spp_; QImage img(width_, height_, QImage::Format_RGB888); for(int y = 0; y < height_; ++y) { for(int x = 0; x < width_; ++x) { const Spectrum color = accum_color_(y, x).map([=](real c) { return std::pow(c * ratio, 1 / real(2.2)); }).saturate(); img.setPixelColor(x, y, QColor::fromRgbF(color.r, color.g, color.b)); } } QPixmap ret; ret.convertFromImage(img); return ret; } MaterialThumbnailProvider::MaterialThumbnailProvider( int width, int height, RC<const tracer::Material> mat, int iter_spp, int iter_count) : width_(width), height_(height), mat_(std::move(mat)), exit_(false) { iter_spp_ = iter_spp; iter_count_ = iter_count; finished_iters_ = 0; finished_spp_ = 0; } MaterialThumbnailProvider::~MaterialThumbnailProvider() { assert(!exit_); exit_ = true; if(render_thread_.joinable()) render_thread_.join(); } QPixmap MaterialThumbnailProvider::start() { assert(!exit_); accum_color_.initialize(height_, width_, Spectrum()); sampler_ = newRC<tracer::NativeSampler>(42, false); run_one_iter(1); auto ret = compute_pixmap(); render_thread_ = std::thread([=] { for(;;) { if(exit_) return; if(finished_iters_ >= iter_count_) return; run_one_iter(iter_spp_); if(exit_) return; emit update_thumbnail(compute_pixmap()); } }); return ret; } AGZ_EDITOR_END
6,612
2,254
#ifndef TH_GENERIC_FILE #define TH_GENERIC_FILE "TH/generic/THTensorLapack.cpp" #else /* Check if self is transpose of a contiguous matrix */ static int THTensor_(isTransposedContiguous)(THTensor *self) { return self->stride(0) == 1 && self->stride(1) == self->size(0); } /* Check if self contains any inf or NaN values */ static int THTensor_(isFinite)(THTensor *self) { std::atomic<int> finite{1}; TH_TENSOR_APPLY(scalar_t, self, if (finite && !std::isfinite(*self_data)) { finite = 0; TH_TENSOR_APPLY_hasFinished = 1; break; }); return finite; } /* If a matrix is a regular contiguous matrix, make sure it is transposed because this is what we return from Lapack calls. */ static void THTensor_(checkTransposed)(THTensor *self) { if(THTensor_(isContiguous)(self)) THTensor_(transpose)(self, NULL, 0, 1); return; } /* newContiguous followed by transpose Similar to (newContiguous), but checks if the transpose of the matrix is contiguous and also limited to 2D matrices. */ static THTensor *THTensor_(newTransposedContiguous)(THTensor *self) { THTensor *tensor; if(THTensor_(isTransposedContiguous)(self)) { THTensor_(retain)(self); tensor = self; } else { tensor = THTensor_(newContiguous)(self); THTensor_(transpose)(tensor, NULL, 0, 1); } return tensor; } /* Given the result tensor and src tensor, decide if the lapack call should use the provided result tensor or should allocate a new space to put the result in. The returned tensor have to be freed by the calling function. nrows is required, because some lapack calls, require output space smaller than input space, like underdetermined gels. */ static THTensor *THTensor_(checkLapackClone)(THTensor *result, THTensor *src, int nrows) { /* check if user wants to reuse src and if it is correct shape/size */ if (src == result && THTensor_(isTransposedContiguous)(src) && src->size(1) == nrows) THTensor_(retain)(result); else if(src == result || result == NULL) /* in this case, user wants reuse of src, but its structure is not OK */ result = THTensor_(new)(); else THTensor_(retain)(result); return result; } /* Same as cloneColumnMajor, but accepts nrows argument, because some lapack calls require the resulting tensor to be larger than src. */ static THTensor *THTensor_(cloneColumnMajorNrows)(THTensor *self, THTensor *src, int nrows) { THTensor *result; THTensor *view; if (src == NULL) src = self; result = THTensor_(checkLapackClone)(self, src, nrows); if (src == result) return result; THTensor_(resize2d)(result, src->size(1), nrows); THTensor_(checkTransposed)(result); if (src->size(0) == nrows) { at::Tensor result_wrap = THTensor_wrap(result); at::Tensor src_wrap = THTensor_wrap(src); at::native::copy_(result_wrap, src_wrap); } else { view = THTensor_(newNarrow)(result, 0, 0, src->size(0)); at::Tensor view_wrap = THTensor_wrap(view); at::Tensor src_wrap = THTensor_wrap(src); at::native::copy_(view_wrap, src_wrap); c10::raw::intrusive_ptr::decref(view); } return result; } /* Create a clone of src in self column major order for use with Lapack. If src == self, a new tensor is allocated, in any case, the return tensor should be freed by calling function. */ static THTensor *THTensor_(cloneColumnMajor)(THTensor *self, THTensor *src) { return THTensor_(cloneColumnMajorNrows)(self, src, src->size(0)); } void THTensor_(gels)(THTensor *rb_, THTensor *ra_, THTensor *b, THTensor *a) { int free_b = 0; // Note that a = NULL is interpreted as a = ra_, and b = NULL as b = rb_. if (a == NULL) a = ra_; if (b == NULL) b = rb_; THArgCheck(a->dim() == 2, 2, "A should have 2 dimensions, but has %d", a->dim()); THArgCheck(!a->is_empty(), 2, "A should not be empty"); THArgCheck(b->dim() == 1 || b->dim() == 2, 1, "B should have 1 or 2 " "dimensions, but has %d", b->dim()); THArgCheck(!b->is_empty(), 1, "B should not be empty"); TORCH_CHECK(a->size(0) == b->size(0), "Expected A and b to have same size " "at dim 0, but A has ", a->size(0), " rows and B has ", b->size(0), " rows"); if (b->dim() == 1) { b = THTensor_wrap(b).unsqueeze(1).unsafeReleaseTensorImpl(); free_b = 1; } int m, n, nrhs, lda, ldb, info, lwork; THTensor *work = NULL; scalar_t wkopt = 0; THTensor *ra__ = NULL; // working version of A matrix to be passed into lapack GELS THTensor *rb__ = NULL; // working version of B matrix to be passed into lapack GELS ra__ = THTensor_(cloneColumnMajor)(ra_, a); m = ra__->size(0); n = ra__->size(1); lda = m; ldb = (m > n) ? m : n; rb__ = THTensor_(cloneColumnMajorNrows)(rb_, b, ldb); nrhs = rb__->size(1); info = 0; /* get optimal workspace size */ THLapack_(gels)('N', m, n, nrhs, ra__->data<scalar_t>(), lda, rb__->data<scalar_t>(), ldb, &wkopt, -1, &info); lwork = (int)wkopt; work = THTensor_(newWithSize1d)(lwork); THLapack_(gels)('N', m, n, nrhs, ra__->data<scalar_t>(), lda, rb__->data<scalar_t>(), ldb, work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup("Lapack Error in %s : The %d-th diagonal element of the triangular factor of A is zero", THCleanup(c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(rb__); c10::raw::intrusive_ptr::decref(work); if (free_b) c10::raw::intrusive_ptr::decref(b);), "gels", info,""); /* * In the m < n case, if the input b is used as the result (so b == _rb), * then rb_ was originally m by nrhs but now should be n by nrhs. * This is larger than before, so we need to expose the new rows by resizing. */ if (m < n && b == rb_) { THTensor_(resize2d)(rb_, n, nrhs); } THTensor_(freeCopyTo)(ra__, ra_); THTensor_(freeCopyTo)(rb__, rb_); c10::raw::intrusive_ptr::decref(work); if (free_b) c10::raw::intrusive_ptr::decref(b); } /* The geqrf function does the main work of QR-decomposing a matrix. However, rather than producing a Q matrix directly, it produces a sequence of elementary reflectors which may later be composed to construct Q - for example with the orgqr function, below. Args: * `ra_` - Result matrix which will contain: i) The elements of R, on and above the diagonal. ii) Directions of the reflectors implicitly defining Q. * `rtau_` - Result tensor which will contain the magnitudes of the reflectors implicitly defining Q. * `a` - Input matrix, to decompose. If NULL, `ra_` is used as input. For further details, please see the LAPACK documentation. */ void THTensor_(geqrf)(THTensor *ra_, THTensor *rtau_, THTensor *a) { if (a == NULL) ra_ = a; THArgCheck(a->dim() == 2, 1, "A should be 2 dimensional"); THArgCheck(!a->is_empty(), 1, "A should not be empty"); THTensor *ra__ = NULL; /* Prepare the input for LAPACK, making a copy if necessary. */ ra__ = THTensor_(cloneColumnMajor)(ra_, a); int m = ra__->size(0); int n = ra__->size(1); int k = (m < n ? m : n); int lda = m; THTensor_(resize1d)(rtau_, k); /* Dry-run to query the suggested size of the workspace. */ int info = 0; scalar_t wkopt = 0; THLapack_(geqrf)(m, n, ra__->data<scalar_t>(), lda, rtau_->data<scalar_t>(), &wkopt, -1, &info); /* Allocate the workspace and call LAPACK to do the real work. */ int lwork = (int)wkopt; THTensor *work = THTensor_(newWithSize1d)(lwork); THLapack_(geqrf)(m, n, ra__->data<scalar_t>(), lda, rtau_->data<scalar_t>(), work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup("Lapack Error %s : unknown Lapack error. info = %i", THCleanup( c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(work);), "geqrf", info,""); THTensor_(freeCopyTo)(ra__, ra_); c10::raw::intrusive_ptr::decref(work); } /* The ormqr function multiplies Q with another matrix from a sequence of elementary reflectors, such as is produced by the geqrf function. Args: * `ra_` - result Tensor, which will contain the matrix Q' c. * `a` - input Tensor, which should be a matrix with the directions of the elementary reflectors below the diagonal. If NULL, `ra_` is used as input. * `tau` - input Tensor, containing the magnitudes of the elementary reflectors. * `c` - input Tensor, containing the matrix to be multiplied. * `left` - bool, determining whether c is left- or right-multiplied with Q. * `transpose` - bool, determining whether to transpose Q before multiplying. For further details, please see the LAPACK documentation. */ void THTensor_(ormqr)(THTensor *ra_, THTensor *a, THTensor *tau, THTensor *c, bool left, bool transpose) { char side = left ? 'L' : 'R'; char trans = transpose ? 'T' : 'N'; if (a == NULL) a = ra_; THArgCheck(THTensor_nDimensionLegacyAll(a) == 2, 1, "A should be 2 dimensional"); THTensor *ra__ = NULL; ra__ = THTensor_(cloneColumnMajor)(ra_, c); int m = c->size(0); int n = c->size(1); int k = THTensor_sizeLegacyNoScalars(tau, 0); int lda; if (side == 'L') { lda = m; } else { lda = n; } int ldc = m; /* Dry-run to query the suggested size of the workspace. */ int info = 0; scalar_t wkopt = 0; THLapack_(ormqr)(side, trans, m, n, k, a->data<scalar_t>(), lda, tau->data<scalar_t>(), ra__->data<scalar_t>(), ldc, &wkopt, -1, &info); /* Allocate the workspace and call LAPACK to do the real work. */ int lwork = (int)wkopt; THTensor *work = THTensor_(newWithSize1d)(lwork); THLapack_(ormqr)(side, trans, m, n, k, a->data<scalar_t>(), lda, tau->data<scalar_t>(), ra__->data<scalar_t>(), ldc, work->data<scalar_t>(), lwork, &info); THLapackCheckWithCleanup(" Lapack Error %s : unknown Lapack error. info = %i", THCleanup( c10::raw::intrusive_ptr::decref(ra__); c10::raw::intrusive_ptr::decref(work);), "ormqr", info,""); THTensor_(freeCopyTo)(ra__, ra_); c10::raw::intrusive_ptr::decref(work); } #endif
10,680
3,873
// Copy-protected formats that require special support // // Contains detection and generation for each track format. // Output will be in bitstream or flux format (or both), // depending on the format requirements. #include "SAMdisk.h" #include "IBMPC.h" #include "BitstreamTrackBuilder.h" #include "FluxTrackBuilder.h" //////////////////////////////////////////////////////////////////////////////// bool IsEmptyTrack(const Track& track) { return track.size() == 0; } TrackData GenerateEmptyTrack(const CylHead& cylhead, const Track& track) { assert(IsEmptyTrack(track)); (void)track; // Generate a DD track full of gap filler. It shouldn't really matter // which datarate and encoding as long as there are no sync marks. BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addBlock(0x4e, 6250); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // KBI-19 protection (19 valid sectors on CPC+PC, plus 1 error sector on PC) bool IsKBI19Track(const Track& track) { static const uint8_t ids[]{ 0,1,4,7,10,13,16,2,5,8,11,14,17,3,6,9,12,15,18,19 }; // CPC version has 19 sectors, PC version has 20 (with bad sector 19). if (track.size() != arraysize(ids) && track.size() != arraysize(ids) - 1) return false; int idx = 0; for (auto& s : track.sectors()) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.sector != ids[idx++] || s.size() != 512 || (!s.has_good_data() && s.header.sector != 19)) return false; } if (opt.debug) util::cout << "detected KBI-19 track\n"; return true; } TrackData GenerateKBI19Track(const CylHead& cylhead, const Track& track) { assert(IsKBI19Track(track)); static const Data gap2_sig{ 0x20,0x4B,0x42,0x49,0x20 }; // " KBI " BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); // Track start with slightly shorter gap4a. bitbuf.addGap(64); bitbuf.addIAM(); bitbuf.addGap(50); int sector_index = 0; for (auto& s : track) { bitbuf.addSectorHeader(s.header); if (s.header.sector == 0) { bitbuf.addGap(17); bitbuf.addBlock(gap2_sig); } else { bitbuf.addGap(8); bitbuf.addBlock(gap2_sig); bitbuf.addGap(9); } bitbuf.addAM(s.dam); auto data = s.data_copy(); // Short or full sector data? if (sector_index++ % 3) { data.resize(61); bitbuf.addBlock(data); } else { if (s.header.sector == 0) { data.resize(s.size()); bitbuf.addBlock(data); bitbuf.addCrc(3 + 1 + 512); } else { auto crc_block_size = 3 + 1 + s.size(); bitbuf.addBlock({ data.begin() + 0, data.begin() + 0x10e }); bitbuf.addCrc(crc_block_size); bitbuf.addBlock({ data.begin() + 0x110, data.begin() + 0x187 }); bitbuf.addCrc(crc_block_size); bitbuf.addBlock({ data.begin() + 0x189, data.begin() + s.size() }); bitbuf.addCrc(crc_block_size); bitbuf.addGap(80); } } } // Pad up to normal track size. bitbuf.addGap(90); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Sega System 24 track? (currently just 0x2f00 variant) bool IsSystem24Track(const Track& track) { static const uint8_t sizes[] = { 4,4,4,4,4,3,1 }; auto i = 0; if (track.size() != arraysize(sizes)) return false; for (auto& s : track) { if (s.datarate != DataRate::_500K || s.encoding != Encoding::MFM || s.header.size != sizes[i++] || !s.has_data()) return false; } if (opt.debug) util::cout << "detected System-24 track\n"; return true; } TrackData GenerateSystem24Track(const CylHead& cylhead, const Track& track) { assert(IsSystem24Track(track)); BitstreamTrackBuilder bitbuf(DataRate::_500K, Encoding::MFM); for (auto& s : track) { auto gap3{ (s.header.sector < 6) ? 52 : 41 }; bitbuf.addSector(s, gap3); } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Speedlock weak sector for Spectrum +3? bool IsSpectrumSpeedlockTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector0 = track[0]; auto& sector1 = track[1]; if (sector0.encoding != Encoding::MFM || sector1.encoding != Encoding::MFM || sector0.datarate != DataRate::_250K || sector1.datarate != DataRate::_250K || sector0.size() != 512 || sector1.size() != 512 || sector0.data_size() < 512 || sector1.data_size() < 512 || !sector1.has_baddatacrc()) // weak sector return false; auto& data0 = sector0.data_copy(); auto& data1 = sector1.data_copy(); // Check for signature in the 2 known positions if (memcmp(data0.data() + 304, "SPEEDLOCK", 9) && memcmp(data0.data() + 176, "SPEEDLOCK", 9)) return false; // If there's no common block at the start, assume fully random // Buggy Boy has only 255, so don't check the full first half! if (memcmp(data1.data(), data1.data() + 1, (sector1.size() / 2) - 1)) { // -512 weak_offset = 0; weak_size = 512; } else { // =256 -33 +47 -176 weak_offset = 336; weak_size = 32; } if (opt.debug) util::cout << "detected Spectrum Speedlock track\n"; return true; } TrackData GenerateSpectrumSpeedlockTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsSpectrumSpeedlockTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[1] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[5]) { auto& sector1{ track[1] }; auto data1{ sector1.data_copy() }; std::fill(data1.begin() + weak_offset, data1.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector1.header, data1, 0x2e, sector1.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Speedlock weak sector for Amstrad CPC? bool IsCpcSpeedlockTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector0 = track[0]; auto& sector7 = track[7]; if (sector0.encoding != Encoding::MFM || sector7.encoding != Encoding::MFM || sector0.datarate != DataRate::_250K || sector7.datarate != DataRate::_250K || sector0.size() != 512 || sector7.size() != 512 || sector0.data_size() < 512 || sector7.data_size() < 512 || !sector7.has_baddatacrc()) // weak sector return false; auto& data0 = sector0.data_copy(); auto& data7 = sector7.data_copy(); // Check for signature in the boot sector if (memcmp(data0.data() + 257, "SPEEDLOCK", 9) && memcmp(data0.data() + 129, "SPEEDLOCK", 9)) { // If that's missing, look for a code signature if (memcmp(data0.data() + 208, "\x4a\x00\x09\x46\x00\x00\x00\x42\x02\x47\x2a\xff", 12) || CRC16(data0.data() + 49, 220 - 49) != 0x62c2) return false; } // If there's no common block at the start, assume fully random // Buggy Boy has only 255, so don't check the full first half! if (memcmp(data7.data(), data7.data() + 1, (sector7.size() / 2) - 1)) { // -512 weak_offset = 0; weak_size = 512; } else if (data0[129] == 'S') { // =256 -256 weak_offset = 256; weak_size = 256; } else { // =256 -33 +47 -176 weak_offset = 336; weak_size = 32; } if (opt.debug) util::cout << "detected CPC Speedlock track\n"; return true; } TrackData GenerateCpcSpeedlockTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsCpcSpeedlockTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[7] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[1]) { auto& sector7{ track[7] }; auto data7{ sector7.data_copy() }; std::fill(data7.begin() + weak_offset, data7.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector7.header, data7, 0x2e, sector7.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Rainbow Arts weak sector for CPC? bool IsRainbowArtsTrack(const Track& track, int& weak_offset, int& weak_size) { if (track.size() != 9) return false; auto& sector1 = track[1]; auto& sector3 = track[3]; if (sector1.encoding != Encoding::MFM || sector3.encoding != Encoding::MFM || sector1.datarate != DataRate::_250K || sector3.datarate != DataRate::_250K || sector1.size() != 512 || sector3.size() != 512 || sector1.data_size() < 512 || sector3.data_size() < 512 || sector1.header.sector != 198 || !sector1.has_baddatacrc()) // weak sector 198 return false; auto& data3 = sector3.data_copy(); // Check for code signature at the start of the 4th sector if (memcmp(data3.data(), "\x2a\x6d\xa7\x01\x30\x01\xaf\xed\x42\x4d\x44\x21\x70\x01", 14)) return false; // The first 100 bytes are constant weak_offset = 100; // =100 -258 +151 -3 weak_size = 256; if (opt.debug) util::cout << "detected Rainbow Arts weak sector track\n"; return true; } TrackData GenerateRainbowArtsTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsRainbowArtsTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak{ &sector == &track[1] }; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 0x2e, sector.dam, is_weak); // Add duplicate weak sector half way around track. if (&sector == &track[5]) { // Add a duplicate of the weak sector, with different data from the weak position auto& sector1{ track[1] }; auto data1{ sector1.data_copy() }; std::fill(data1.begin() + weak_offset, data1.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sector1.header, data1, 0x2e, sector1.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // KBI-10 weak sector for CPC? bool IsKBIWeakSectorTrack(const Track& track, int& weak_offset, int& weak_size) { auto sectors = track.size(); // Most titles use the 10-sector version, but some have 3x2K sectors. int size_code; if (sectors == 3) size_code = 4; else if (sectors == 10) size_code = 2; else return false; // Weak sector is always last on track and 256 bytes auto& sectorW = track[sectors - 1]; if (sectorW.encoding != Encoding::MFM || sectorW.datarate != DataRate::_250K || sectorW.header.size != 1 || sectorW.data_size() < 256 || !sectorW.has_baddatacrc()) { return false; } // The remaining sector must be the correct type and size code. for (int i = 0; i < sectors - 1; ++i) { auto& sector = track[i]; if (sector.encoding != Encoding::MFM || sector.datarate != DataRate::_250K || sector.header.size != size_code || sector.data_size() < Sector::SizeCodeToLength(size_code)) { return false; } } auto& dataW = sectorW.data_copy(); // The first character of the weak sector is 'K', and the next two are alphabetic. if (dataW[0] != 'K' || !std::isalpha(static_cast<uint8_t>(dataW[1])) || !std::isalpha(static_cast<uint8_t>(dataW[2]))) { return false; } // =4 -4 =124 -4 =120 weak_offset = 4; weak_size = 4; if (opt.debug) util::cout << "detected KBI weak sector track\n"; return true; } TrackData GenerateKBIWeakSectorTrack(const CylHead& cylhead, const Track& track, int weak_offset, int weak_size) { #ifdef _DEBUG int temp_offset, temp_size; assert(IsKBIWeakSectorTrack(track, temp_offset, temp_size)); assert(weak_offset == temp_offset && weak_size == temp_size); #endif FluxTrackBuilder fluxbuf(cylhead, DataRate::_250K, Encoding::MFM); fluxbuf.addTrackStart(); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); auto sectors = track.size(); for (auto& sector : track) { auto& data_copy = sector.data_copy(); auto is_weak = sector.header.size == 1; if (!is_weak) fluxbuf.addSector(sector.header, data_copy, 0x54, sector.dam); else { fluxbuf.addSectorUpToData(sector.header, sector.dam); fluxbuf.addBlock(Data(data_copy.begin(), data_copy.begin() + weak_offset)); fluxbuf.addWeakBlock(weak_size); fluxbuf.addBlock(Data( data_copy.begin() + weak_offset + weak_size, data_copy.begin() + sector.size())); } bitbuf.addSector(sector.header, data_copy, 1, sector.dam, is_weak); // Insert the duplicate sector earlier on the track. if (&sector == &track[((sectors - 1) / 2) - 1]) { auto& sectorW = track[sectors - 1]; auto dataW{ sectorW.data_copy() }; std::fill(dataW.begin() + weak_offset, dataW.begin() + weak_offset + weak_size, uint8_t(0xee)); bitbuf.addSector(sectorW.header, dataW, 1, sectorW.dam, true); } } TrackData trackdata(cylhead); trackdata.add(std::move(bitbuf.buffer())); //trackdata.add(FluxData({ fluxbuf.buffer() })); return trackdata; } //////////////////////////////////////////////////////////////////////////////// // Logo Professor track? bool IsLogoProfTrack(const Track& track) { // Accept track with or without placeholder sector if (track.size() != 10 && track.size() != 11) return false; // First non-placeholder sector id. int id = 2; for (auto& s : track) { // Check for placeholder sector, present in old EDSK images. if (track.size() == 11 && s.header.sector == 1) { // It must have a bad ID header CRC. if (s.has_badidcrc()) continue; else return false; } // Ensure each sector is double-density MFM, 512-bytes, with good data if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.sector != id++ || s.size() != 512 || !s.has_good_data()) return false; } // If there's no placeholder, the first sector must begin late if (track.size() == 10) { // Determine an offset considered late auto min_offset = Sector::SizeCodeToLength(1) + GetSectorOverhead(Encoding::MFM); // Reject if first sector doesn't start late on the track if (track[0].offset < (min_offset * 16)) return false; } if (opt.debug) util::cout << "detected Logo Professor track\n"; return true; } TrackData GenerateLogoProfTrack(const CylHead& cylhead, const Track& track) { assert(IsLogoProfTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); bitbuf.addGap(600); for (auto& sector : track) { if (sector.header.sector != 1) bitbuf.addSector(sector, 0x20); } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // OperaSoft track with 32K sector bool IsOperaSoftTrack(const Track& track) { uint32_t sector_mask = 0; int i = 0; if (track.size() != 9) return false; for (auto& s : track) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM) return false; static const uint8_t sizes[] = { 1,1,1,1,1,1,1,1,8 }; if (s.header.size != sizes[i++]) return false; sector_mask |= (1 << s.header.sector); } // Sectors must be numbered 0 to 8 if (sector_mask != ((1 << 9) - 1)) return false; if (opt.debug) util::cout << "detected OperaSoft track with 32K sector\n"; return true; } TrackData GenerateOperaSoftTrack(const CylHead& cylhead, const Track& track) { assert(IsOperaSoftTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); for (auto& sector : track) { if (sector.header.sector != 8) bitbuf.addSector(sector, 0xf0); else { auto& sector7 = track[7]; auto& sector8 = track[8]; bitbuf.addSectorUpToData(sector8.header, sector8.dam); bitbuf.addBlock(Data(256, 0x55)); bitbuf.addCrc(4 + 256); bitbuf.addBlock(Data(0x512 - 256 - 2, 0x4e)); bitbuf.addBlock(sector7.data_copy()); } } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // 8K sector track? bool Is8KSectorTrack(const Track& track) { // There must only be 1 sector. if (track.size() != 1) return false; auto& sector{ track[0] }; if (sector.datarate != DataRate::_250K || sector.encoding != Encoding::MFM || sector.size() != 8192 || !sector.has_data()) return false; if (opt.debug) util::cout << "detected 8K sector track\n"; return true; } TrackData Generate8KSectorTrack(const CylHead& cylhead, const Track& track) { assert(Is8KSectorTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addGap(16); // gap 4a bitbuf.addIAM(); bitbuf.addGap(16); // gap 1 auto& sector{ track[0] }; bitbuf.addSectorUpToData(sector.header, sector.dam); // Maximum size of long-track version used by Coin-Op Hits static constexpr auto max_size{ 0x18a3 }; auto data = sector.data_copy(); if (data.size() > max_size) data.resize(max_size); bitbuf.addBlock(data); bitbuf.addGap(max_size - data.size()); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// // Titus Prehistorik protection, which may be followed by unused KBI-19 sectors. // The KBI format isn't tested, so this seems to be a disk mastering error. bool IsPrehistorikTrack(const Track& track) { bool found_12{ false }; for (auto& s : track.sectors()) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.header.size != (s.has_baddatacrc() ? 5 : 2)) return false; // The 4K sector 12 contains the protection signature. if (s.header.sector == 12 && s.header.size == 5) { found_12 = true; auto& data12 = s.data_copy(); if (memcmp(data12.data() + 0x1b, "Titus", 5)) return false; } } if (!found_12) return false; if (opt.debug) util::cout << "detected Prehistorik track\n"; return true; } TrackData GeneratePrehistorikTrack(const CylHead& cylhead, const Track& track) { assert(IsPrehistorikTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(); auto gap3 = (track.size() == 11) ? 106 : 30; for (auto& sector : track) { if (sector.header.sector != 12) bitbuf.addSector(sector, gap3); else { bitbuf.addSector(sector.header, sector.data_copy(), gap3, sector.dam, true); break; } } return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// bool Is11SectorTrack(const Track& track) { if (track.size() != 11) return false; for (auto& s : track) { if (s.datarate != DataRate::_250K || s.encoding != Encoding::MFM || s.size() != 512 || !s.has_good_data()) { return false; } } if (opt.debug) util::cout << "detected 11-sector tight track\n"; return true; } TrackData Generate11SectorTrack(const CylHead& cylhead, const Track& track) { assert(Is11SectorTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addTrackStart(true); for (auto& sector : track) bitbuf.addSector(sector, 1); return TrackData(cylhead, std::move(bitbuf.buffer())); } //////////////////////////////////////////////////////////////////////////////// #if 0 /* We don't currently use these functions, as patching the protection code gives a simpler and more reliable writing solution. The protection reads 8K from cyl 38 sector 1 and takes a byte at offset 0x1f9f. It then reads cyl 39 sector 195 and reads a byte at offset 0x1ff. If the two bytes don't match the protection fails and the computer is reset. The byte sampled from sector 1 is part of 2K of E5 filler bytes, so the byte read from the second track revolution will be one of the 16 possible MFM data or clock patterns: E5 CB 97 2F 5E BC 79 F2 10 20 40 80 01 02 04 08. To write the protection we must read the byte from sector 1 and ensure the correct byte is written to the end of sector 195. If the track splice sync isn't reliable for sector 1 it may need to be formatted multiple times. */ // Reussir protection with leading 8K sector. bool IsReussirProtectedTrack(const Track& track) { if (track.size() != 2) return false; auto& sector1 = track[0]; auto& sector2 = track[1]; if (sector1.header.sector != 1 || sector1.datarate != DataRate::_250K || sector1.encoding != Encoding::MFM || sector1.size() != 8192 || !sector1.has_data() || !sector1.has_baddatacrc()) return false; if (sector2.header.sector != 2 || sector2.datarate != DataRate::_250K || sector2.encoding != Encoding::MFM || sector2.size() != 512 || !sector2.has_data() || !sector2.has_baddatacrc()) return false; if (opt.debug) util::cout << "detected Reussir protected track\n"; return true; } // This format isn't difficult to create, but we need to ensure it's close to // the correct length so the sampling point is comfortably within sector 1. TrackData GenerateReussirProtectedTrack(const CylHead& cylhead, const Track& track) { assert(IsReussirProtectedTrack(track)); BitstreamTrackBuilder bitbuf(DataRate::_250K, Encoding::MFM); bitbuf.addGap(80); // gap 4a bitbuf.addIAM(); bitbuf.addGap(50); // gap 1 auto& sector1 = track[0]; bitbuf.addSectorUpToData(sector1.header, sector1.dam); bitbuf.addBlockUpdateCrc(0x4e, 2048); bitbuf.addCrcBytes(); bitbuf.addGap(82); auto& sector2 = track[1]; bitbuf.addSectorUpToData(sector2.header, sector2.dam); bitbuf.addBlockUpdateCrc(0x4e, 2048); bitbuf.addCrcBytes(); bitbuf.addGap(1802); return TrackData(cylhead, std::move(bitbuf.buffer())); } #endif ////////////////////////////////////////////////////////////////////////////////
27,140
9,409
#include "CubeNodeG2.h" /** * Create a CubeNode from a Cube * @param cube base cube */ CubeNodeG2::CubeNodeG2 (const Cube& cube) : CubeNode(cube) { } bool CubeNodeG2::isGoal() { typedef Cube::FACE FACE; // IDEA: replace this->getColor with this->cube[idx]; in all CubeNode files // Corners, left and right facets. FACE LUB = this->getColor(FACE::L, 0, 0); FACE LUF = this->getColor(FACE::L, 0, 2); FACE LDB = this->getColor(FACE::L, 2, 0); FACE LDF = this->getColor(FACE::L, 2, 2); FACE RUB = this->getColor(FACE::R, 0, 2); FACE RUF = this->getColor(FACE::R, 0, 0); FACE RDB = this->getColor(FACE::R, 2, 2); FACE RDF = this->getColor(FACE::R, 2, 0); // Edges in the M slice (between R and L). FACE UF = this->getColor(FACE::U, 2, 1); FACE FU = this->getColor(FACE::F, 0, 1); FACE UB = this->getColor(FACE::U, 0, 1); FACE BU = this->getColor(FACE::B, 0, 1); FACE DF = this->getColor(FACE::D, 0, 1); FACE FD = this->getColor(FACE::F, 2, 1); FACE DB = this->getColor(FACE::D, 2, 1); FACE BD = this->getColor(FACE::B, 2, 1); return // All left/right corner facets either blue or green. (LUB == FACE::R || LUB == FACE::L) && (LUF == FACE::R || LUF == FACE::L) && (LDB == FACE::R || LDB == FACE::L) && (LDF == FACE::R || LDF == FACE::L) && (RUB == FACE::R || RUB == FACE::L) && (RUF == FACE::R || RUF == FACE::L) && (RDB == FACE::R || RDB == FACE::L) && (RDF == FACE::R || RDF == FACE::L) && // UF, UB, DF, DB in the M slice. Note that the edges // are already oriented. (UF == FACE::F || UF == FACE::B) && (FU == FACE::U || FU == FACE::D) && (UB == FACE::F || UB == FACE::B) && (BU == FACE::U || BU == FACE::D) && (DF == FACE::F || DF == FACE::B) && (FD == FACE::U || FD == FACE::D) && (DB == FACE::F || DB == FACE::B) && (BD == FACE::U || BD == FACE::D); }
1,918
910
int pnpoly(int nvert, double *vertx, double *verty, double testx, double testy){ // Source: https://wrf.ecse.rpi.edu//Research/Short_Notes/pnpoly.html // modified here for double precision // Copyright (c) 1970-2003, Wm. Randolph Franklin // // 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: // // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimers. // 2. Redistributions in binary form must reproduce the above copyright notice // in the documentation and/or other materials provided with the distribution. // 3. The name of W. Randolph Franklin may not be used to endorse or promote // products derived from this Software without specific prior written permission. // // // 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. int i, j, c = 0; for (i = 0, j = nvert-1; i < nvert; j = i++) { if ( ((verty[i]>testy) != (verty[j]>testy)) && (testx < (vertx[j]-vertx[i]) * (testy-verty[i]) / (verty[j]-verty[i]) + vertx[i]) ) c = !c; } return c; }
2,026
683
#include "stdafx.h" #include "PlayerMovingStopState.h" PlayerMovingStopState::PlayerMovingStopState(Player* player, Animation* animation) { m_player = player; m_animation = animation; } PlayerMovingStopState::~PlayerMovingStopState() { } void PlayerMovingStopState::Update(float deltaTime) { m_animation->setPositionX(m_player->getPosition().x); m_animation->setPositionY(m_player->getPosition().y); m_animation->Update(deltaTime); } void PlayerMovingStopState::Draw() { m_animation->Draw(); } PlayerStates PlayerMovingStopState::GetState() { return PlayerStates::MovingStop; } void PlayerMovingStopState::PreCollision(GameObject * entity, float deltaTime) { } void PlayerMovingStopState::OnCollision(GameObject* entity, float deltaTime) { }
758
259
#include "LuaWrapper.hpp" namespace LuaSTGPlus::LuaWrapper { std::string_view const ParticleSystemWrapper::ClassID("lstg.ParticleSystemInstance"); ParticleSystemWrapper::UserData* ParticleSystemWrapper::Cast(lua_State* L, int idx) { return (UserData*)luaL_checkudata(L, idx, ClassID.data()); } ParticleSystemWrapper::UserData* ParticleSystemWrapper::Create(lua_State* L) { UserData* self = (UserData*)lua_newuserdata(L, sizeof(UserData)); // udata self->res = nullptr; self->ptr = nullptr; luaL_getmetatable(L, ClassID.data()); // udata mt lua_setmetatable(L, -2); // udata return self; } void ParticleSystemWrapper::Register(lua_State* L) { struct Wrapper { static int SetInactive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetInactive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetActive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetActive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetAliveCount(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { size_t const alive = self->ptr->GetAliveCount(); lua_pushinteger(L, (lua_Integer)alive); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = (float)luaL_checknumber(L, 2); self->ptr->SetEmission(emi); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = self->ptr->GetEmission(); lua_pushnumber(L, emi); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int Update(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const x = (float)luaL_checknumber(L, 2); float const y = (float)luaL_checknumber(L, 3); float const rot = (float)luaL_checknumber(L, 4); float const delta = (float)luaL_optnumber(L, 5, 1.0 / 60.0); self->ptr->SetRotation((float)rot); if (self->ptr->IsActived()) // 兼容性处理 { self->ptr->SetInactive(); self->ptr->SetCenter(fcyVec2(x, y)); self->ptr->SetActive(); } else { self->ptr->SetCenter(fcyVec2(x, y)); } self->ptr->Update(delta); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int Render(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const scale = (float)luaL_checknumber(L, 2); LAPP.Render(self->ptr, scale, scale); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int __tostring(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { lua_pushfstring(L, "lstg.ParticleSystemInstance(\"%s\")", self->res->GetResName().c_str()); } else { lua_pushstring(L, "lstg.ParticleSystemInstance"); } return 1; } static int __gc(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { if (self->ptr) { self->res->FreeInstance(self->ptr); } self->res->Release(); } self->res = nullptr; self->ptr = nullptr; return 0; } static int ParticleSystemInstance(lua_State* L) { char const* ps_name = luaL_checkstring(L, 1); auto p_res = LRES.FindParticle(ps_name); if (!p_res) return luaL_error(L, "particle system '%s' not found.", ps_name); try { auto* p_obj = p_res->AllocInstance(); auto* p_lud = Create(L); p_lud->res = *p_res; p_lud->res->AddRef(); p_lud->ptr = p_obj; } catch (const std::bad_alloc&) { return luaL_error(L, "create particle system instance of '%s' failed, memory allocation failed.", ps_name); } return 1; } }; luaL_Reg const lib[] = { { "SetInactive", &Wrapper::SetInactive }, { "SetActive", &Wrapper::SetActive }, { "GetAliveCount", &Wrapper::GetAliveCount }, { "SetEmission", &Wrapper::SetEmission }, { "GetEmission", &Wrapper::GetEmission }, { "Update", &Wrapper::Update }, { "Render", &Wrapper::Render }, { NULL, NULL } }; luaL_Reg const mt[] = { { "__tostring", &Wrapper::__tostring }, { "__gc", &Wrapper::__gc }, { NULL, NULL }, }; luaL_Reg const ins[] = { { "ParticleSystemInstance", Wrapper::ParticleSystemInstance }, { NULL, NULL } }; luaL_register(L, "lstg", ins); // ??? lstg RegisterClassIntoTable(L, ".ParticleSystemInstance", lib, ClassID.data(), mt); lua_pop(L, 1); } }
5,596
2,631
// CS32 lab06 // Completed by: Kevin Lu and Kevin Lai #include <iostream> #include <string> #include <fstream> #include <vector> #include <memory> #include "demogData.h" #include "psData.h" #include "parse.h" #include "dataAQ.h" using namespace std; int main() { /*//Deboog output ofstream myfile; myfile.open("output.txt");*/ dataAQ theAnswers; //read in a csv file and create a vector of objects representing each counties data std::vector<shared_ptr<regionData>> theDemogData = read_csv( "county_demographics.csv", DEMOG); std::vector<shared_ptr<regionData>> thePoliceData = read_csv( "police_shootings_cleaned.csv", POLICE); /*//Deboog print for (auto obj : theDemogData) { myfile << *dynamic_pointer_cast<demogData>(obj) << std::endl; } for (auto obj : thePoliceData) { myfile << *dynamic_pointer_cast<psData>(obj) << std::endl; } */ std::vector<shared_ptr<demogData>> castedDemogData; std::vector<shared_ptr<psData>> castedPoliceData; for (auto entry : theDemogData) { castedDemogData.push_back(static_pointer_cast<demogData>(entry)); } for (auto entry : thePoliceData) { castedPoliceData.push_back(static_pointer_cast<psData>(entry)); } theAnswers.createComboDemogData(castedDemogData); theAnswers.createComboPoliceData(castedPoliceData); //cout << theAnswers << endl; theAnswers.comboReport(92); //myfile.close(); /* cout << "*** the state that needs the most pre-schools**" << endl; string needPK = theAnswers.youngestPop(); cout << *(theAnswers.getStateData(needPK)) << endl; cout << "*** the state that needs the most high schools**" << endl; string needHS = theAnswers.teenPop(); cout << *(theAnswers.getStateData(needHS)) << endl; cout << "*** the state that needs the most vaccines**" << endl; string needV = theAnswers.wisePop(); cout << *(theAnswers.getStateData(needV)) << endl; cout << "*** the state that needs the most help with education**" << endl; string noHS = theAnswers.underServeHS(); cout << *(theAnswers.getStateData(noHS)) << endl; cout << "*** the state with most college grads**" << endl; string grads = theAnswers.collegeGrads(); cout << *(theAnswers.getStateData(grads)) << endl; cout << "*** the state with most population below the poverty line**" << endl; string belowPov = theAnswers.belowPoverty(); cout << *(theAnswers.getStateData(belowPov)) << endl; */ return 0; }
2,560
888
// DFS binary_searching // https://open.kattis.com/problems/muddyhike #include <bits/stdc++.h> #define For(i, n) for (int i = 0; i < n; ++i) #define Forcase int __t = 0; cin >> __t; while (__t--) #define pb push_back #define ll long long #define ull unsigned long long #define ar array using namespace std; const int MOD = 1e9;//1e9 + 7; const ll INF = 1e18; int n, m; int tb[1010][1010]; bool vst[1010][1010]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; void dfs(int x, int y, int d) { vst[x][y] = 1; For (i, 4) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (tb[nx][ny] <= d && !vst[nx][ny]) { dfs(nx, ny, d); } } } bool ok(int d) { For (i, n) For (j, m) vst[i][j] = 0; For (i, n) if (tb[i][0] <= d) dfs(i, 0, d); For (i, n) if (vst[i][m - 1]) return 1; return 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; For (i, n) For (j, m) cin >> tb[i][j]; int l = 0, r = 1000000; while (l < r) { int mid = (l + r) / 2; if (ok(mid)) { r = mid; } else { l = mid + 1; } } cout << l << '\n'; return 0; }
1,264
611
// Copyright 2020 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 "components/services/storage/service_worker/service_worker_resource_ops.h" #include "base/numerics/checked_math.h" #include "base/pickle.h" #include "components/services/storage/public/cpp/big_io_buffer.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/data_pipe.h" #include "net/http/http_response_info.h" #include "services/network/public/cpp/net_adapters.h" #include "services/network/public/mojom/url_response_head.mojom.h" #include "third_party/blink/public/common/blob/blob_utils.h" namespace storage { namespace { // Disk cache entry data indices. // // This enum pertains to data persisted on disk. Do not remove or reuse values. enum { kResponseInfoIndex = 0, kResponseContentIndex = 1, kResponseMetadataIndex = 2, }; // Convert an HttpResponseInfo retrieved from disk_cache to URLResponseHead. network::mojom::URLResponseHeadPtr ConvertHttpResponseInfo( const net::HttpResponseInfo& http_info, int64_t response_data_size) { auto response_head = network::mojom::URLResponseHead::New(); response_head->request_time = http_info.request_time; response_head->response_time = http_info.response_time; response_head->headers = http_info.headers; response_head->headers->GetMimeType(&response_head->mime_type); response_head->headers->GetCharset(&response_head->charset); response_head->content_length = response_data_size; response_head->was_fetched_via_spdy = http_info.was_fetched_via_spdy; response_head->was_alpn_negotiated = http_info.was_alpn_negotiated; response_head->connection_info = http_info.connection_info; response_head->alpn_negotiated_protocol = http_info.alpn_negotiated_protocol; response_head->remote_endpoint = http_info.remote_endpoint; response_head->cert_status = http_info.ssl_info.cert_status; // See ConvertToPickle(), where an invalid ssl_info is put into storage in // case of |response_head->ssl_info| being nullptr. Here we restore // |response_head->ssl_info| to nullptr if we got the invalid ssl_info from // storage. if (http_info.ssl_info.is_valid()) response_head->ssl_info = http_info.ssl_info; return response_head; } // Convert a URLResponseHead to base::Pickle. Used to persist the response to // disk. std::unique_ptr<base::Pickle> ConvertToPickle( network::mojom::URLResponseHeadPtr response_head) { net::HttpResponseInfo response_info; response_info.headers = response_head->headers; if (response_head->ssl_info.has_value()) { response_info.ssl_info = *response_head->ssl_info; DCHECK(response_info.ssl_info.is_valid()); } response_info.was_fetched_via_spdy = response_head->was_fetched_via_spdy; response_info.was_alpn_negotiated = response_head->was_alpn_negotiated; response_info.alpn_negotiated_protocol = response_head->alpn_negotiated_protocol; response_info.connection_info = response_head->connection_info; response_info.remote_endpoint = response_head->remote_endpoint; response_info.response_time = response_head->response_time; const bool kSkipTransientHeaders = true; const bool kTruncated = false; auto pickle = std::make_unique<base::Pickle>(); response_info.Persist(pickle.get(), kSkipTransientHeaders, kTruncated); return pickle; } // An IOBuffer that wraps a pickle's data. Used to write URLResponseHead. class WrappedPickleIOBuffer : public net::WrappedIOBuffer { public: explicit WrappedPickleIOBuffer(std::unique_ptr<const base::Pickle> pickle) : net::WrappedIOBuffer(reinterpret_cast<const char*>(pickle->data())), pickle_(std::move(pickle)) { DCHECK(pickle_->data()); } size_t size() const { return pickle_->size(); } private: ~WrappedPickleIOBuffer() override = default; const std::unique_ptr<const base::Pickle> pickle_; }; } // namespace DiskEntryCreator::DiskEntryCreator( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache) : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); DCHECK(disk_cache_); } DiskEntryCreator::~DiskEntryCreator() = default; void DiskEntryCreator::EnsureEntryIsCreated(base::OnceClosure callback) { DCHECK(creation_phase_ == CreationPhase::kNoAttempt || creation_phase_ == CreationPhase::kDone); DCHECK(!ensure_entry_is_created_callback_); ensure_entry_is_created_callback_ = std::move(callback); if (entry_) { RunEnsureEntryIsCreatedCallback(); return; } if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } creation_phase_ = CreationPhase::kInitialAttempt; disk_cache_->CreateEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidCreateEntryForFirstAttempt, weak_factory_.GetWeakPtr())); } void DiskEntryCreator::DidCreateEntryForFirstAttempt( int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { DCHECK_EQ(creation_phase_, CreationPhase::kInitialAttempt); DCHECK(!entry_); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } if (rv != net::OK) { // The first attempt to create an entry is failed. Try to overwrite the // existing entry. creation_phase_ = CreationPhase::kDoomExisting; disk_cache_->DoomEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidDoomExistingEntry, weak_factory_.GetWeakPtr())); return; } DCHECK(entry); entry_ = std::move(entry); RunEnsureEntryIsCreatedCallback(); } void DiskEntryCreator::DidDoomExistingEntry(int rv) { DCHECK_EQ(creation_phase_, CreationPhase::kDoomExisting); DCHECK(!entry_); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } creation_phase_ = CreationPhase::kSecondAttempt; disk_cache_->CreateEntry( resource_id_, base::BindOnce(&DiskEntryCreator::DidCreateEntryForSecondAttempt, weak_factory_.GetWeakPtr())); } void DiskEntryCreator::DidCreateEntryForSecondAttempt( int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { DCHECK_EQ(creation_phase_, CreationPhase::kSecondAttempt); if (!disk_cache_) { entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } if (rv != net::OK) { // The second attempt is also failed. Give up creating an entry. entry_.reset(); RunEnsureEntryIsCreatedCallback(); return; } DCHECK(!entry_); DCHECK(entry); entry_ = std::move(entry); RunEnsureEntryIsCreatedCallback(); } void DiskEntryCreator::RunEnsureEntryIsCreatedCallback() { creation_phase_ = CreationPhase::kDone; std::move(ensure_entry_is_created_callback_).Run(); } DiskEntryOpener::DiskEntryOpener( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache) : resource_id_(resource_id), disk_cache_(std::move(disk_cache)) { DCHECK_NE(resource_id_, blink::mojom::kInvalidServiceWorkerResourceId); DCHECK(disk_cache_); } DiskEntryOpener::~DiskEntryOpener() = default; void DiskEntryOpener::EnsureEntryIsOpen(base::OnceClosure callback) { if (entry_) { std::move(callback).Run(); return; } if (!disk_cache_) { std::move(callback).Run(); return; } disk_cache_->OpenEntry( resource_id_, base::BindOnce(&DiskEntryOpener::DidOpenEntry, weak_factory_.GetWeakPtr(), std::move(callback))); } void DiskEntryOpener::DidOpenEntry( base::OnceClosure callback, int rv, std::unique_ptr<ServiceWorkerDiskCacheEntry> entry) { if (!entry_ && rv == net::OK) { DCHECK(entry); entry_ = std::move(entry); } std::move(callback).Run(); } class ServiceWorkerResourceReaderImpl::DataReader { public: DataReader( base::WeakPtr<ServiceWorkerResourceReaderImpl> owner, size_t total_bytes_to_read, mojo::PendingRemote<mojom::ServiceWorkerDataPipeStateNotifier> notifier, mojo::ScopedDataPipeProducerHandle producer_handle) : owner_(std::move(owner)), total_bytes_to_read_(total_bytes_to_read), notifier_(std::move(notifier)), producer_handle_(std::move(producer_handle)), watcher_(FROM_HERE, mojo::SimpleWatcher::ArmingPolicy::MANUAL, base::SequencedTaskRunnerHandle::Get()) { DCHECK(owner_); DCHECK(notifier_); } ~DataReader() = default; DataReader(const DataReader&) = delete; DataReader operator=(const DataReader&) = delete; void Start() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kInitialized); state_ = State::kStarted; #endif owner_->entry_opener_.EnsureEntryIsOpen(base::BindOnce( &DataReader::ContinueReadData, weak_factory_.GetWeakPtr())); } private: void ContinueReadData() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kStarted); state_ = State::kCacheEntryOpened; #endif if (!owner_) { Complete(net::ERR_ABORTED); return; } if (!owner_->entry_opener_.entry()) { Complete(net::ERR_CACHE_MISS); return; } watcher_.Watch(producer_handle_.get(), MOJO_HANDLE_SIGNAL_WRITABLE, base::BindRepeating(&DataReader::OnWritable, weak_factory_.GetWeakPtr())); watcher_.ArmOrNotify(); } void OnWritable(MojoResult) { #if DCHECK_IS_ON() DCHECK(state_ == State::kCacheEntryOpened || state_ == State::kDataRead); state_ = State::kProducerWritable; #endif DCHECK(producer_handle_.is_valid()); DCHECK(!pending_buffer_); if (!owner_ || !owner_->entry_opener_.entry()) { Complete(net::ERR_ABORTED); return; } uint32_t num_bytes = 0; MojoResult rv = network::NetToMojoPendingBuffer::BeginWrite( &producer_handle_, &pending_buffer_, &num_bytes); switch (rv) { case MOJO_RESULT_INVALID_ARGUMENT: case MOJO_RESULT_BUSY: NOTREACHED(); return; case MOJO_RESULT_FAILED_PRECONDITION: Complete(net::ERR_ABORTED); return; case MOJO_RESULT_SHOULD_WAIT: watcher_.ArmOrNotify(); return; case MOJO_RESULT_OK: // |producer__handle_| must have been taken by |pending_buffer_|. DCHECK(pending_buffer_); DCHECK(!producer_handle_.is_valid()); break; } num_bytes = std::min(num_bytes, blink::BlobUtils::GetDataPipeChunkSize()); scoped_refptr<network::NetToMojoIOBuffer> buffer = base::MakeRefCounted<network::NetToMojoIOBuffer>(pending_buffer_.get()); net::IOBuffer* raw_buffer = buffer.get(); int read_bytes = owner_->entry_opener_.entry()->Read( kResponseContentIndex, current_bytes_read_, raw_buffer, num_bytes, base::BindOnce(&DataReader::DidReadData, weak_factory_.GetWeakPtr(), buffer)); if (read_bytes != net::ERR_IO_PENDING) { DidReadData(std::move(buffer), read_bytes); } } void DidReadData(scoped_refptr<network::NetToMojoIOBuffer> buffer, int read_bytes) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kProducerWritable); state_ = State::kDataRead; #endif if (read_bytes < 0) { Complete(read_bytes); return; } producer_handle_ = pending_buffer_->Complete(read_bytes); DCHECK(producer_handle_.is_valid()); pending_buffer_.reset(); current_bytes_read_ += read_bytes; if (read_bytes == 0 || current_bytes_read_ == total_bytes_to_read_) { // All data has been read. Complete(current_bytes_read_); return; } watcher_.ArmOrNotify(); } void Complete(int status) { #if DCHECK_IS_ON() DCHECK_NE(state_, State::kComplete); state_ = State::kComplete; #endif watcher_.Cancel(); producer_handle_.reset(); if (notifier_.is_connected()) { notifier_->OnComplete(status); } if (owner_) { owner_->DidReadDataComplete(); } } base::WeakPtr<ServiceWorkerResourceReaderImpl> owner_; const size_t total_bytes_to_read_; size_t current_bytes_read_ = 0; mojo::Remote<mojom::ServiceWorkerDataPipeStateNotifier> notifier_; mojo::ScopedDataPipeProducerHandle producer_handle_; mojo::SimpleWatcher watcher_; scoped_refptr<network::NetToMojoPendingBuffer> pending_buffer_; #if DCHECK_IS_ON() enum class State { kInitialized, kStarted, kCacheEntryOpened, kProducerWritable, kDataRead, kComplete, }; State state_ = State::kInitialized; #endif // DCHECK_IS_ON() base::WeakPtrFactory<DataReader> weak_factory_{this}; }; ServiceWorkerResourceReaderImpl::ServiceWorkerResourceReaderImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceReader> receiver, base::OnceClosure disconnect_handler) : entry_opener_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceReaderImpl::~ServiceWorkerResourceReaderImpl() = default; void ServiceWorkerResourceReaderImpl::ReadResponseHead( ReadResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kReadResponseHeadStarted; #endif DCHECK(!read_response_head_callback_) << __func__ << " already called"; DCHECK(!response_head_) << " another ReadResponseHead() in progress"; DCHECK(!metadata_buffer_); DCHECK(!data_reader_); read_response_head_callback_ = std::move(callback); entry_opener_.EnsureEntryIsOpen( base::BindOnce(&ServiceWorkerResourceReaderImpl::ContinueReadResponseHead, weak_factory_.GetWeakPtr())); } void ServiceWorkerResourceReaderImpl::ReadData( int64_t size, mojo::PendingRemote<mojom::ServiceWorkerDataPipeStateNotifier> notifier, ReadDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kReadDataStarted; #endif DCHECK(!read_response_head_callback_) << "ReadResponseHead() being operating"; DCHECK(!response_head_); DCHECK(!metadata_buffer_); DCHECK(!data_reader_); MojoCreateDataPipeOptions options; options.struct_size = sizeof(MojoCreateDataPipeOptions); options.flags = MOJO_CREATE_DATA_PIPE_FLAG_NONE; options.element_num_bytes = 1; options.capacity_num_bytes = blink::BlobUtils::GetDataPipeCapacity(size); mojo::ScopedDataPipeConsumerHandle consumer_handle; mojo::ScopedDataPipeProducerHandle producer_handle; MojoResult rv = mojo::CreateDataPipe(&options, producer_handle, consumer_handle); if (rv != MOJO_RESULT_OK) { std::move(callback).Run(mojo::ScopedDataPipeConsumerHandle()); return; } data_reader_ = std::make_unique<DataReader>(weak_factory_.GetWeakPtr(), size, std::move(notifier), std::move(producer_handle)); data_reader_->Start(); std::move(callback).Run(std::move(consumer_handle)); } void ServiceWorkerResourceReaderImpl::ContinueReadResponseHead() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kReadResponseHeadStarted); state_ = State::kCacheEntryOpened; #endif DCHECK(read_response_head_callback_); if (!entry_opener_.entry()) { FailReadResponseHead(net::ERR_CACHE_MISS); return; } int64_t size = entry_opener_.entry()->GetSize(kResponseInfoIndex); if (size <= 0) { FailReadResponseHead(net::ERR_CACHE_MISS); return; } auto buffer = base::MakeRefCounted<net::IOBuffer>(base::checked_cast<size_t>(size)); int rv = entry_opener_.entry()->Read( kResponseInfoIndex, /*offset=*/0, buffer.get(), size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadHttpResponseInfo, weak_factory_.GetWeakPtr(), buffer)); if (rv != net::ERR_IO_PENDING) { DidReadHttpResponseInfo(std::move(buffer), rv); } } void ServiceWorkerResourceReaderImpl::DidReadHttpResponseInfo( scoped_refptr<net::IOBuffer> buffer, int status) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kCacheEntryOpened); state_ = State::kResponseInfoRead; #endif DCHECK(read_response_head_callback_); DCHECK(entry_opener_.entry()); if (status < 0) { FailReadResponseHead(status); return; } // Deserialize the http info structure, ensuring we got headers. base::Pickle pickle(buffer->data(), status); auto http_info = std::make_unique<net::HttpResponseInfo>(); bool response_truncated = false; if (!http_info->InitFromPickle(pickle, &response_truncated) || !http_info->headers.get()) { FailReadResponseHead(net::ERR_FAILED); return; } DCHECK(!response_truncated); int64_t response_data_size = entry_opener_.entry()->GetSize(kResponseContentIndex); response_head_ = ConvertHttpResponseInfo(*http_info, response_data_size); int64_t metadata_size = entry_opener_.entry()->GetSize(kResponseMetadataIndex); DCHECK_GE(metadata_size, 0); if (metadata_size <= 0) { CompleteReadResponseHead(status); return; } // Read metadata. metadata_buffer_ = base::MakeRefCounted<BigIOBuffer>( mojo_base::BigBuffer(base::checked_cast<size_t>(metadata_size))); int rv = entry_opener_.entry()->Read( kResponseMetadataIndex, /*offset=*/0, metadata_buffer_.get(), metadata_size, base::BindOnce(&ServiceWorkerResourceReaderImpl::DidReadMetadata, weak_factory_.GetWeakPtr())); if (rv != net::ERR_IO_PENDING) { DidReadMetadata(rv); } } void ServiceWorkerResourceReaderImpl::DidReadMetadata(int status) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kResponseInfoRead); state_ = State::kMetadataRead; #endif DCHECK(read_response_head_callback_); DCHECK(metadata_buffer_); if (status < 0) { FailReadResponseHead(status); return; } CompleteReadResponseHead(status); } void ServiceWorkerResourceReaderImpl::FailReadResponseHead(int status) { DCHECK_NE(net::OK, status); response_head_ = nullptr; metadata_buffer_ = nullptr; CompleteReadResponseHead(status); } void ServiceWorkerResourceReaderImpl::CompleteReadResponseHead(int status) { #if DCHECK_IS_ON() DCHECK_NE(state_, State::kIdle); state_ = State::kIdle; #endif DCHECK(read_response_head_callback_); absl::optional<mojo_base::BigBuffer> metadata = metadata_buffer_ ? absl::optional<mojo_base::BigBuffer>(metadata_buffer_->TakeBuffer()) : absl::nullopt; metadata_buffer_ = nullptr; std::move(read_response_head_callback_) .Run(status, std::move(response_head_), std::move(metadata)); } void ServiceWorkerResourceReaderImpl::DidReadDataComplete() { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kReadDataStarted); state_ = State::kIdle; #endif DCHECK(data_reader_); data_reader_.reset(); } ServiceWorkerResourceWriterImpl::ServiceWorkerResourceWriterImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceWriter> receiver, base::OnceClosure disconnect_handler) : entry_creator_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceWriterImpl::~ServiceWorkerResourceWriterImpl() = default; void ServiceWorkerResourceWriterImpl::WriteResponseHead( network::mojom::URLResponseHeadPtr response_head, WriteResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteResponseHeadStarted; #endif entry_creator_.EnsureEntryIsCreated( base::BindOnce(&ServiceWorkerResourceWriterImpl::WriteResponseHeadToEntry, weak_factory_.GetWeakPtr(), std::move(response_head), std::move(callback))); } void ServiceWorkerResourceWriterImpl::WriteData(mojo_base::BigBuffer data, WriteDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteDataStarted; #endif entry_creator_.EnsureEntryIsCreated(base::BindOnce( &ServiceWorkerResourceWriterImpl::WriteDataToEntry, weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); } void ServiceWorkerResourceWriterImpl::WriteResponseHeadToEntry( network::mojom::URLResponseHeadPtr response_head, WriteResponseHeadCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteResponseHeadStarted); state_ = State::kWriteResponseHeadHasEntry; #endif if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_callback_); write_callback_ = std::move(callback); std::unique_ptr<const base::Pickle> pickle = ConvertToPickle(std::move(response_head)); auto buffer = base::MakeRefCounted<WrappedPickleIOBuffer>(std::move(pickle)); size_t write_amount = buffer->size(); int rv = entry_creator_.entry()->Write( kResponseInfoIndex, /*offset=*/0, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteResponseHead, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteResponseHead(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceWriterImpl::DidWriteResponseHead( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteResponseHeadHasEntry); state_ = State::kIdle; #endif DCHECK(write_callback_); DCHECK(rv < 0 || base::checked_cast<size_t>(rv) == write_amount); std::move(write_callback_).Run(rv); } void ServiceWorkerResourceWriterImpl::WriteDataToEntry( mojo_base::BigBuffer data, WriteDataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteDataStarted); state_ = State::kWriteDataHasEntry; #endif if (!entry_creator_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_callback_); write_callback_ = std::move(callback); size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); int rv = entry_creator_.entry()->Write( kResponseContentIndex, write_position_, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceWriterImpl::DidWriteData, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteData(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceWriterImpl::DidWriteData( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteDataHasEntry); state_ = State::kIdle; #endif DCHECK(write_callback_); if (rv >= 0) { DCHECK(base::checked_cast<size_t>(rv) == write_amount); write_position_ += write_amount; } std::move(write_callback_).Run(rv); } ServiceWorkerResourceMetadataWriterImpl:: ServiceWorkerResourceMetadataWriterImpl( int64_t resource_id, base::WeakPtr<ServiceWorkerDiskCache> disk_cache, mojo::PendingReceiver<mojom::ServiceWorkerResourceMetadataWriter> receiver, base::OnceClosure disconnect_handler) : entry_opener_(resource_id, std::move(disk_cache)), receiver_(this, std::move(receiver)) { receiver_.set_disconnect_handler(std::move(disconnect_handler)); } ServiceWorkerResourceMetadataWriterImpl:: ~ServiceWorkerResourceMetadataWriterImpl() = default; void ServiceWorkerResourceMetadataWriterImpl::WriteMetadata( mojo_base::BigBuffer data, WriteMetadataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kIdle); state_ = State::kWriteMetadataStarted; #endif entry_opener_.EnsureEntryIsOpen(base::BindOnce( &ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata, weak_factory_.GetWeakPtr(), std::move(data), std::move(callback))); } void ServiceWorkerResourceMetadataWriterImpl::ContinueWriteMetadata( mojo_base::BigBuffer data, WriteMetadataCallback callback) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteMetadataStarted); state_ = State::kWriteMetadataHasEntry; #endif if (!entry_opener_.entry()) { std::move(callback).Run(net::ERR_FAILED); return; } DCHECK(!write_metadata_callback_); write_metadata_callback_ = std::move(callback); size_t write_amount = data.size(); auto buffer = base::MakeRefCounted<BigIOBuffer>(std::move(data)); int rv = entry_opener_.entry()->Write( kResponseMetadataIndex, /*offset=*/0, buffer.get(), write_amount, base::BindOnce(&ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata, weak_factory_.GetWeakPtr(), buffer, write_amount)); if (rv != net::ERR_IO_PENDING) { DidWriteMetadata(std::move(buffer), write_amount, rv); } } void ServiceWorkerResourceMetadataWriterImpl::DidWriteMetadata( scoped_refptr<net::IOBuffer> buffer, size_t write_amount, int rv) { #if DCHECK_IS_ON() DCHECK_EQ(state_, State::kWriteMetadataHasEntry); state_ = State::kIdle; #endif DCHECK(rv < 0 || base::checked_cast<size_t>(rv) == write_amount); DCHECK(write_metadata_callback_); std::move(write_metadata_callback_).Run(rv); } } // namespace storage
25,489
8,549
/* * Copyright (c) 2017 ARM Limited. * * SPDX-License-Identifier: MIT * * 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 "arm_compute/core/NEON/kernels/NEDepthConcatenateKernel.h" #include "arm_compute/core/Error.h" #include "arm_compute/core/Helpers.h" #include "arm_compute/core/IAccessWindow.h" #include "arm_compute/core/ITensor.h" #include "arm_compute/core/TensorInfo.h" #include "arm_compute/core/Utils.h" #include "arm_compute/core/Validate.h" #include "arm_compute/core/Window.h" #include <arm_neon.h> using namespace arm_compute; NEDepthConcatenateKernel::NEDepthConcatenateKernel() : _input(nullptr), _output(nullptr), _top_bottom(0), _left_right(0), _depth_offset(0) { } BorderSize NEDepthConcatenateKernel::border_size() const { return BorderSize(_top_bottom, _left_right); } void NEDepthConcatenateKernel::configure(const ITensor *input, unsigned int depth_offset, ITensor *output) { ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::F32); ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(output, 1, DataType::F32); ARM_COMPUTE_ERROR_ON(input->info()->dimension(2) + depth_offset > output->info()->dimension(2)); ARM_COMPUTE_ERROR_ON(input->info()->dimension(0) > output->info()->dimension(0)); ARM_COMPUTE_ERROR_ON(input->info()->dimension(1) > output->info()->dimension(1)); ARM_COMPUTE_ERROR_ON_MISMATCHING_SHAPES(3, input, output); // The gaps between the two lowest dimensions of input and output need to be divisible by 2 // Otherwise it is not clear how the padding should be added onto the input tensor ARM_COMPUTE_ERROR_ON((output->info()->dimension(0) - input->info()->dimension(0)) % 2); ARM_COMPUTE_ERROR_ON((output->info()->dimension(1) - input->info()->dimension(1)) % 2); _input = input; _output = output; _depth_offset = depth_offset; _left_right = (output->info()->dimension(0) - input->info()->dimension(0)) / 2; _top_bottom = (output->info()->dimension(1) - input->info()->dimension(1)) / 2; const unsigned int num_elems_processed_per_iteration = 4; const unsigned int num_elems_read_per_iteration = 4; const unsigned int num_rows_read_per_iteration = 1; // The window needs to be based on input as we copy all the depths of input Window win = calculate_max_enlarged_window(*input->info(), Steps(num_elems_processed_per_iteration), border_size()); AccessWindowRectangle input_access(input->info(), -_left_right, -_top_bottom, num_elems_read_per_iteration, num_rows_read_per_iteration); AccessWindowHorizontal output_access(output->info(), 0, num_elems_processed_per_iteration); update_window_and_padding(win, input_access, output_access); output_access.set_valid_region(win, ValidRegion(Coordinates(0, 0), output->info()->tensor_shape())); INEKernel::configure(win); } void NEDepthConcatenateKernel::run(const Window &window) { ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this); ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window); // Offset output const unsigned int offset_to_first_elements_in_bytes = _output->info()->offset_first_element_in_bytes() + _left_right * _output->info()->strides_in_bytes()[0] + _top_bottom * _output->info()->strides_in_bytes()[1] + _depth_offset * _output->info()->strides_in_bytes()[2]; uint8_t *output_ptr = _output->buffer() + offset_to_first_elements_in_bytes; Iterator input(_input, window); Iterator output(_output, window); execute_window_loop(window, [&](const Coordinates & id) { const auto in_ptr = reinterpret_cast<const float *>(input.ptr()); const auto out_ptr = reinterpret_cast<float *>(output_ptr + output.offset()); vst1q_f32(out_ptr, vld1q_f32(in_ptr)); }, input, output); }
4,940
1,703
/* Copyright (C) 2021 hidenorly 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 __ANDROID_HAL_STREAM_OUT_HPP__ #define __ANDROID_HAL_STREAM_OUT_HPP__ #include "AndroidHalStream.hpp" #include <fmq/MessageQueue.h> #include <vector> #include <system/audio.h> #include <stdint.h> #include "Strategy.hpp" #include "Pipe.hpp" #include "Source.hpp" #include "Sink.hpp" #include "PlaybackRateFilter.hpp" #include "DualMonoFilter.hpp" #include <fmq/EventFlag.h> #include "deleters.hpp" class IStreamOut : public IStream { public: class IStreamOutCallback { public: virtual void onWriteReady(void); virtual void onDrainReady(void); virtual void onError(void); }; class IStreamOutEventCallback { public: virtual void onCodecFormatChanged(std::vector<uint8_t> audioMetadata); }; enum WriteCommand { WRITE, GET_PRESENTATION_POSITION, GET_LATENCY }; struct WriteStatus { HalResult retval; WriteCommand replyTo; union Reply { uint64_t written; PresentationPosition presentationPosition; uint32_t latencyMs; } reply; WriteStatus():retval(HalResult::OK), replyTo(WriteCommand::WRITE), reply{0}{}; }; typedef android::hardware::MessageQueue<IStreamOut::WriteCommand, android::hardware::kSynchronizedReadWrite> CommandMQ; typedef android::hardware::MessageQueue<IStreamOut::WriteStatus, android::hardware::kSynchronizedReadWrite> StatusMQ; typedef android::hardware::MessageQueue<uint8_t, android::hardware::kSynchronizedReadWrite> DataMQ; class WritePipeInfo { public: std::shared_ptr<CommandMQ> commandMQ; std::shared_ptr<DataMQ> dataMQ; std::shared_ptr<StatusMQ> statusMQ; //ThreadInfo threadInfo; WritePipeInfo( std::shared_ptr<CommandMQ> commandMQ = std::make_shared<CommandMQ>(1), std::shared_ptr<DataMQ> dataMQ = std::make_shared<DataMQ>(1), std::shared_ptr<StatusMQ> statusMQ = std::make_shared<StatusMQ>(4096, true)) : commandMQ(commandMQ), dataMQ(dataMQ), statusMQ(statusMQ){}; virtual ~WritePipeInfo(){}; }; class AndroidAudioSource : public ISource { protected: std::shared_ptr<DataMQ> mDataMQ; std::shared_ptr<StatusMQ> mStatusMQ; std::unique_ptr<::android::hardware::EventFlag, deleters::forEventFlag> mEfGroup; long mLastWritePts; public: AndroidAudioSource(std::shared_ptr<DataMQ> dataMQ = nullptr, std::shared_ptr<StatusMQ> statusMQ = nullptr) : mDataMQ(dataMQ), mStatusMQ(statusMQ), mLastWritePts(0){ android::hardware::EventFlag* rawEfGroup = nullptr; android::hardware::EventFlag::createEventFlag( mDataMQ->getEventFlagWord(), &rawEfGroup ); mEfGroup.reset( rawEfGroup ); }; virtual ~AndroidAudioSource(){ mDataMQ.reset(); mStatusMQ.reset(); }; virtual bool isAvailableFormat(AudioFormat format){ return true; }; virtual void notifyDoRead(void); virtual void notifyNextCommand(void); virtual void resetWritePts(void){ mLastWritePts = 0; }; long getWritePresentationTimeUsec(void){ return mLastWritePts; }; protected: virtual void readPrimitive(IAudioBuffer& buf); virtual long getDeltaPtsUsecByBytes(int64_t bytes); }; protected: std::weak_ptr<IStreamOutCallback> mCallback; std::weak_ptr<IStreamOutEventCallback> mEventCallback; std::shared_ptr<WritePipeInfo> mWritePipeInfo; std::shared_ptr<AndroidAudioSource> mSource; std::shared_ptr<ISink> mSink; AudioOutputFlags mOutputFlags; SourceMetadata mSourceMetadata; float mAudioDescMixLevlDb; PlaybackRate mPlaybackRate; std::shared_ptr<PlaybackRateFilter> mPlaybackRateFilter; DualMonoMode mDualMonoMode; std::shared_ptr<DualMonoFilter> mDualMonoFilter; int32_t mPresentationId; int32_t mProgramId; long mLastPts; long mLastWritePtsBase; protected: virtual void process(void); public: IStreamOut(AudioIoHandle ioHandle = 0, DeviceAddress device=DeviceAddress(), AudioConfig config={0}, AudioOutputFlags flags=AUDIO_OUTPUT_FLAG_NONE, SourceMetadata sourceMetadata=SourceMetadata(), std::shared_ptr<StreamSessionHandler> pSessionHandler = nullptr, std::shared_ptr<ISink> pSink = nullptr); virtual ~IStreamOut(){}; virtual std::shared_ptr<WritePipeInfo> prepareForWriting(uint32_t frameSize, uint32_t framesCount); // capability check virtual bool supportsPause(void); virtual bool supportsResume(void); virtual bool supportsDrain(void); // operation virtual HalResult pause(void); virtual HalResult resume(void); virtual HalResult drain(AudioDrain type); virtual HalResult flush(void); // callback virtual HalResult setCallback(std::weak_ptr<IStreamOutCallback> callback); virtual HalResult clearCallback(void); virtual HalResult setEventCallback(std::weak_ptr<IStreamOutEventCallback> callback); // get status virtual int64_t getNextWriteTimestampUsec(); virtual uint32_t getLatencyMsec(void); virtual uint32_t getRenderPositionDspFrames(void); virtual PresentationPosition getPresentationPosition(void); virtual HalResult setVolume(float left, float right); virtual PlaybackRate getPlaybackRateParameters(void); virtual HalResult setPlaybackRateParameters(PlaybackRate playbackRate); virtual DualMonoMode getDualMonoMode(void); virtual HalResult setDualMonoMode(DualMonoMode mode); virtual HalResult selectPresentation(int32_t presentationId, int32_t programId); virtual float getAudioDescriptionMixLevelDb(void); virtual HalResult setAudioDescriptionMixLevel(float leveldB); virtual void updateSourceMetadata(SourceMetadata sourceMetadata); virtual std::vector<DeviceAddress> getDevices(void); virtual HalResult setDevices(std::vector<DeviceAddress> devices); virtual HalResult streamClose(void); }; class StreamOutContext : public StrategyContext { public: AudioIoHandle ioHandle; DeviceAddress device; AudioConfig config; AudioOutputFlags flags; SourceMetadata sourceMetadata; public: StreamOutContext(AudioIoHandle ioHandle, DeviceAddress device, AudioConfig config, AudioOutputFlags flags, SourceMetadata sourceMetadata):ioHandle(ioHandle), device(device), config(config), flags(flags), sourceMetadata(sourceMetadata){}; virtual ~StreamOutContext(){}; }; #endif /* __ANDROID_HAL_STREAM_OUT_HPP__ */
6,780
2,160
#include <mtt/editorLib/EditorApplication.h> #include <MainWindow.h> int main(int argc, char* argv[]) { VkPhysicalDeviceFeatures features{}; features.samplerAnisotropy = VK_TRUE; features.geometryShader = VK_TRUE; mtt::EditorApplication application( argc, argv, "Mtt particles editor", { 0, 0, 0 }, features); MainWindow mainWindow; mainWindow.show(); return application.exec(); }
552
158