void linkInterp(Regs *regs, Elf64_Dyn *dynamic, ProcMem *pm) { uint64_t entry = regs->rip; if (AddSegment(pm, LIBC_TEXTPAGE, libcTextFrames, PROT_READ | PROT_EXEC) != 0) { kprintf_debug("could not load text pages\n"); regs->rip = 0; return; }; FrameList *fl = palloc(libcDataPages); uint64_t index = (LIBC_BASE + libcDataOffset) / 0x1000; if (AddSegment(pm, index, fl, PROT_READ | PROT_WRITE) != 0) { kprintf_debug("could not load data pages\n"); regs->rip = 0; return; }; SetProcessMemory(pm); memcpy((void*)(LIBC_BASE + libcDataOffset), libcDataSection, libcDataSize); regs->rip = libcInterpMain; regs->rsp = libcInterpStack; regs->rdi = (uint64_t) dynamic; regs->rsi = (uint64_t) libcSymbolTable; regs->rdx = libcSymbolCount; regs->rcx = libcNextLoadAddr; regs->r8 = (uint64_t) libcStringTable; regs->r9 = entry; };
SEGMENTH CombinePolygonPieces(SEGMENTH *A1, SEGMENTH *B1, Boolean keepAinB, Boolean keepAnotinB, Boolean keepBinA, Boolean keepBnotinA) { long i, j, err, numSegsA, numSegsB, numSegsC = 0; WorldPoint m; SEGMENTH C = 0, A2 = 0, B2 = 0, *A = 0, *B = 0; err = 0; numSegsA = _GetHandleSize((Handle)*A1) / sizeof(Segment); numSegsB = _GetHandleSize((Handle)*B1) / sizeof(Segment); A2 = (SEGMENTH)_NewHandle(numSegsA * sizeof(Segment)); if (_MemError()) { TechError("CombinePolygonPieces()", "_NewHandle()", 0); goto done; } for (i = 0 ; i < numSegsA ; i++) INDEXH(A2, i) = INDEXH(*A1, i); A = &A2; B2 = (SEGMENTH)_NewHandle(numSegsB * sizeof(Segment)); if (_MemError()) { TechError("CombinePolygonPieces()", "_NewHandle()", 0); goto done; } for (i = 0 ; i < numSegsB ; i++) INDEXH(B2, i) = INDEXH(*B1, i); B = &B2; for (i = 0 ; i < numSegsA ; i++) for (j = 0 ; j < numSegsB ; j++) if (SegmentTouchesSegment(INDEXH(*A, i), INDEXH(*B, j)) && !SameSegmentEndPoints(INDEXH(*A, i), INDEXH(*B, j))) { m = PointOfIntersection(INDEXH(*A, i), INDEXH(*B, j)); if (err = InsertSegment(A, &numSegsA, i, m)) goto done; if (err = InsertSegment(B, &numSegsB, j, m)) goto done; } C = (SEGMENTH)_NewHandle(0); if (_MemError()) { TechError("CombinePolygonPieces()", "_NewHandle()", 0); goto done; } for (i = 0 ; i < numSegsA ; i++) { m = Midpoint(INDEXH(*A, i)); if ((keepAinB && PointInPolygon(m, *B, numSegsB, TRUE)) || (keepAnotinB && !PointInPolygon(m, *B, numSegsB, TRUE))) if (err = AddSegment(&C, &numSegsC, INDEXH(*A, i))) goto done; } for (j = 0 ; j < numSegsB ; j++) { m = Midpoint(INDEXH(*B, j)); if ((keepBinA && PointInPolygon(m, *A, numSegsA, TRUE)) || (keepBnotinA && !PointInPolygon(m, *A, numSegsA, TRUE))) if (err = AddSegment(&C, &numSegsC, INDEXH(*B, j))) goto done; } SortSegments(C, numSegsC); done: if (A2) DisposeHandle((Handle)A2); if (B2) DisposeHandle((Handle)B2); if (err && C) DisposeHandle((Handle)C); return err ? 0 : C; }
const Error *Path::AddLine( uunit length ) { // Length must be a positive value. CML_ASSERT( length >= 0 ); // Calculate the ending position based on the // current position and direction of travel Point<PATH_MAX_DIMENSIONS> p; p.setDim( GetDim() ); p = posEnd; p[0] += cos(dirEnd) * length; if( GetDim() > 1 ) p[1] += sin(dirEnd) * length; // add the line segment to my path LineSeg *seg = new LineSeg( posEnd, dirEnd, length ); if( !seg ) return &PathError::Alloc; const Error *err = AddSegment( seg ); if( err ) return err; // Update my ending position & direction posEnd = p; return 0; }
void VisibilityTester::AddSegment (KDTree* tree, const csVector3& start, const csVector3& end) { csVector3 dir = end-start; float d = dir.Norm (); AddSegment (tree, start, dir / d, d); }
void PTrackManager::GenerateAdaptiveSegment(float skillLevel) { PSeg* curSeg = nullptr; if (previousSegType != TR_STR) // If the previous segment was a corner, ensure another corner is not generated curSeg = &segFactory->CreateRandomStr(track->state.curSegIndex); else { /* If skillLevel is -1, generate random segment */ if (skillLevel == -1.f) curSeg = &segFactory->CreateRandomSeg(track->state.curSegIndex); else // otherwise, take into account skill level { // Ensure corner is a different direction to the last PCornerType cType = PCornerType::CTLeft; if (previousCornerType == PCornerType::CTLeft) cType = PCornerType::CTRight; if (skillLevel != 0) { // Most difficult: smaller radius, larger arc. PSegmentRanges ranges = segFactory->ranges; // Seed random number generator by the current time std::default_random_engine engine(std::chrono::system_clock::now().time_since_epoch().count()); std::normal_distribution<tdble> distribution(skillLevel, NORMAL_DSTRIBUTION); // Produce a variant of the skill level using normal distribution, follow by clamping the value tdble variant = distribution(engine); if (variant > 1) variant = 1; else if (variant < 0) variant = 0; // Ensure that weighting is never 0.0f, if skill level estimate is 1 use 0.1f, as this is the lowest possible weighting tdble radius = lerp(ranges.Radius().Min(), ranges.Radius().Max(), variant < 1.0f ? 1.0f - variant : 0.1f); // Generate arc weighted with skill level, based upon corner type tdble arc = 0.f; if (cType == PCornerType::CTRight) arc = lerp(ranges.RightArc().Min(), ranges.RightArc().Max(), variant); else arc = lerp(ranges.LeftArc().Min(), ranges.LeftArc().Max(), variant); // Create the segment with the segment factory curSeg = &segFactory->CreateSegCnr(track->state.curSegIndex, cType, radius, arc); } else curSeg = &segFactory->CreateRandomStr(track->state.curSegIndex); previousCornerType = cType; } } // Add segment AddSegment(*curSeg); previousSegType = curSeg->type; }
//---------------------------------------------------------------------- // special handling for 16-bit PICs // for CODE segments use addresses as-is // for DATA segments, start from dataseg base static bool handle_area(ea_t start, ea_t end, const char *name, const char *aclass) { if ( ptype != PIC16 ) return false; if ( strcmp(aclass, "CODE") == 0 ) { AddSegment(start, end-start, 0, name, SEG_CODE); } else if ( strcmp(aclass, "DATA") == 0 ) { if ( dataseg == BADADDR ) dataseg = freechunk(0, 0x1000, -0xF); uchar type = stristr(name, "FSR") != NULL ? SEG_IMEM : SEG_DATA; AddSegment(dataseg + start, end-start, dataseg, name, type); } else { return false; } return true; }
void Snake::Restart() { segments.clear(); for(unsigned i = 0; i < START_LENGTH; i++) { AddSegment(START_X - i, START_Y); } direction = GO_RIGHT; time = 0; timeout = 6; dead = false; }
void AddDirections( VECTOR2D aP, int aMask, int aColor ) { BOX2I b( aP - VECTOR2I( 10000, 10000 ), VECTOR2I( 20000, 20000 ) ); AddBox( b, aColor ); for( int i = 0; i < 8; i++ ) { if( ( 1 << i ) & aMask ) { VECTOR2I v = DIRECTION_45( ( DIRECTION_45::Directions ) i ).ToVector() * 100000; AddSegment( SEG( aP, aP + v ), aColor ); } } }
void TimingData::Copy( const TimingData& cpy ) { /* de-allocate any old pointers we had */ Clear(); m_fBeat0OffsetInSeconds = cpy.m_fBeat0OffsetInSeconds; m_sFile = cpy.m_sFile; FOREACH_TimingSegmentType( tst ) { const vector<TimingSegment*> &vpSegs = cpy.m_avpTimingSegments[tst]; for( unsigned i = 0; i < vpSegs.size(); ++i ) AddSegment( vpSegs[i] ); } }
void virtual_segment_c::AddSegments( const std::vector<matroska_segment_c *> &segments) { // fill our current virtual segment with all hard linked segments size_t i_preloaded; do { i_preloaded = 0; for ( size_t i=0; i < segments.size(); i++ ) { i_preloaded += AddSegment( segments[i] ); } } while ( i_preloaded ); // worst case: will stop when all segments are found as linked Sort(); PreloadLinked( ); PrepareChapters( ); }
const Error *Path::AddArc( PointN ¢er, double angle ) { // Can't add an arc to a one dimensional path CML_ASSERT( GetDim() > 1 ); // Make sure the center position has the right number of dimensions CML_ASSERT( GetDim() == center.getDim() ); // Adjust the center to find a position relative to // the starting position. center -= posStart; // Find the starting angle on the arc double deltaX = center[0] - posEnd[0]; double deltaY = center[1] - posEnd[1]; double startAng = PI + atan2( deltaY, deltaX ); // See if there will be an abrupt change in direction when we start // this path. If so, then I'll need to come to a halt first. double deltaDir; if( angle < 0 ) deltaDir = startAng - dirEnd + PI_by_2; else deltaDir = startAng - dirEnd - PI_by_2; if( fabs(deltaDir) > MAX_ANGLE_ERROR ) Pause(0); double radius = center.distance( posEnd ); ArcSeg *seg = new ArcSeg( center, radius, startAng, angle ); if( !seg ) return &PathError::Alloc; const Error *err = AddSegment( seg ); if( err ) return err; // Update the ending position and direction double ang = startAng - angle; posEnd[0] = center[0] + cos(ang) * radius; posEnd[1] = center[1] + sin(ang) * radius; if( angle < 0 ) dirEnd = ang + PI_by_2; else dirEnd = ang - PI_by_2; return 0; }
const Error *Path::AddArc( double radius, double angle ) { // radius must be a positive value. CML_ASSERT( radius >= 0 ); // Can't add an arc to a one dimensional path CML_ASSERT( GetDim() > 1 ); // Find the center. This will be a point on the line that passes // through the current end position and is orthogonal to the current // direction of motion. Point<PATH_MAX_DIMENSIONS> center; center.setDim( GetDim() ); center = posEnd; double startAng; // Positive angles are clockwise rotation if( angle < 0 ) { center[0] -= radius * sin(dirEnd); center[1] += radius * cos(dirEnd); startAng = dirEnd - PI_by_2; } else { center[0] += radius * sin(dirEnd); center[1] -= radius * cos(dirEnd); startAng = dirEnd + PI_by_2; } ArcSeg *seg = new ArcSeg( center, radius, startAng, angle ); if( !seg ) return &PathError::Alloc; const Error *err = AddSegment( seg ); if( err ) return err; // Update the ending position and direction double ang = startAng - angle; posEnd[0] = center[0] + cos(ang) * radius; posEnd[1] = center[1] + sin(ang) * radius; dirEnd -= angle; return 0; }
const Error *Path::AddLine( PointN &p ) { // Make sure the passed point is of the correct dimension CML_ASSERT( p.getDim() == GetDim() ); if( p.getDim() != GetDim() ) return &PathError::BadPoint; // Adjust the passed point to find a position relative to // the starting position. p -= posStart; // Find the direction of travel between the current position // and the passed point. double dx = p[0] - posEnd[0]; double dy = 0.0; if( GetDim() > 1 ) dy = p[1] - posEnd[1]; double dirMove = atan2( dy, dx ); // If the move direction isn't in line with my current direction, // then I'll have to come to a halt before adding the line segment. // Otherwise, I would have an infinite acceleration during the // direction change. if( fabs(dirMove - dirEnd) > MAX_ANGLE_ERROR ) Pause(0); double len = posEnd.distance( p ); // Now, add the line segment to my path LineSeg *seg = new LineSeg( posEnd, dirMove, len ); if( !seg ) return &PathError::Alloc; const Error *err = AddSegment( seg ); if( err ) return err; // Update my ending position & direction posEnd = p; dirEnd = dirMove; return 0; }
// Set start and finish positions. void COGEmitterScrollingRay::SetStartFinishPositions (const OGVec3& _vStartPos, const OGVec3& _vFinishPos) { if (m_bPosReady) return; m_bPosReady = true; m_vStartPos = _vStartPos; m_vFinishPos = _vFinishPos; m_Direction = (m_vFinishPos - m_vStartPos); m_fRayLength = m_Direction.length(); m_Direction.normalize(); float fPos = 0.0f; bool bDone = false; while (!bDone) { bDone = AddSegment(fPos, 1.0f); fPos += m_fSegment; } }
static void spawnProc(void *stack) { kprintf("%$\x02" "Done%#\n"); initInterp(); kprintf("Allocating memory for bootstrap... "); FrameList *fl = palloc(2); AddSegment(getCurrentThread()->pm, 1, fl, PROT_READ | PROT_WRITE | PROT_EXEC); pdownref(fl); SetProcessMemory(getCurrentThread()->pm); kprintf("%$\x02" "Done%#\n"); kprintf("Setting up the terminal... "); setupTerminal(getCurrentThread()->ftab); kprintf("%$\x02" "Done%#\n"); kprintf("Loading /initrd/usbs... "); int err; File *file = vfsOpen("/initrd/usbs", VFS_CHECK_ACCESS, &err); if (file == NULL) { kprintf("%$\x04" "Failed%#\n"); panic("failed to open /initrd/usbs"); }; ssize_t count = vfsRead(file, (void*) 0x1000, 0x1000); if (count < 1) { kprintf("%$\x04" "Failed%#\n"); panic("read() /initrd/usbs: %d\n", count); }; vfsClose(file); kprintf("%$\x02" "%d bytes%#\n", count); kprintf("Control will be transferred to usbs now.\n"); _jmp_usbs(stack); };
void PTrackManager::Update(bool adaptive, float skillLevel) { // Prevent cars driving off the back of the track CorrectCars(); if (trackType == PTrackType::PROCEDURAL) { // If the current leading car is a given distance from the end, generate a new segment if (LeadingCar()->pub.trkPos.seg->id + MAX_SEGS_FROM_END >= track->GetEnd()->id) // If a new segment needs to be generated { if (!adaptive) // Generate random segment if not adaptive AddSegment(segFactory->CreateRandomSeg(track->state.curSegIndex)); else // Otherwise, generate segment taking into account skill level GenerateAdaptiveSegment(skillLevel); // Update graphical description if (raceManager->raceEngineInfo.displayMode == RM_DISP_MODE_NORMAL) UpdateGraphics(); // Check if a finish line needs to be added CheckForFinishLine(); } } }
void CcdrawDoc::EnforcePSLG(double tol) { /* need to enforce: 1) no duplicate point; 2) no intersections between line segments, lines and arcs, or arcs; 3) no duplicate block labels; 4) no overlapping lines or arcs. can do this by cleaning out the various lists, and rebuilding them using the ``add'' functions that ensure that things come out right. */ CArray< CNode, CNode&> newnodelist; CArray< CSegment, CSegment&> newlinelist; CArray< CArcSegment, CArcSegment&> newarclist; CArray< CBlockLabel, CBlockLabel&> newblocklist; int i; CComplex p0,p1; double d; newnodelist.RemoveAll(); newlinelist.RemoveAll(); newarclist.RemoveAll(); newblocklist.RemoveAll(); for(i=0;i<nodelist.GetSize();i++) newnodelist.Add(nodelist[i]); for(i=0;i<linelist.GetSize();i++) newlinelist.Add(linelist[i]); for(i=0;i<arclist.GetSize();i++) newarclist.Add(arclist[i]); for(i=0;i<blocklist.GetSize();i++) newblocklist.Add(blocklist[i]); nodelist.RemoveAll(); linelist.RemoveAll(); arclist.RemoveAll(); blocklist.RemoveAll(); // find out what tolerance is so that there are not nodes right on // top of each other; if(tol==0){ if (newnodelist.GetSize()<2) d=1.e-08; else{ p0=newnodelist[0].CC(); p1=p0; for(i=1;i<newnodelist.GetSize();i++) { if(newnodelist[i].x<p0.re) p0.re=newnodelist[i].x; if(newnodelist[i].x>p1.re) p1.re=newnodelist[i].x; if(newnodelist[i].y<p0.im) p0.im=newnodelist[i].y; if(newnodelist[i].y>p1.im) p1.im=newnodelist[i].y; } d=abs(p1-p0)*CLOSE_ENOUGH; } } else d=tol; // put in all of the nodes; for(i=0;i<newnodelist.GetSize();i++) AddNode(newnodelist[i],d); // put in all of the lines; for(i=0;i<newlinelist.GetSize();i++) { p0.Set(newnodelist[newlinelist[i].n0].x,newnodelist[newlinelist[i].n0].y); p1.Set(newnodelist[newlinelist[i].n1].x,newnodelist[newlinelist[i].n1].y); AddSegment(p0,p1,newlinelist[i]); } // put in all of the arcs; for(i=0;i<newarclist.GetSize();i++) { p0.Set(newnodelist[newarclist[i].n0].x,newnodelist[newarclist[i].n0].y); p1.Set(newnodelist[newarclist[i].n1].x,newnodelist[newarclist[i].n1].y); AddArcSegment(p0,p1,newarclist[i]); } // put in all of the block labels; for(i=0;i<newblocklist.GetSize();i++) AddBlockLabel(newblocklist[i],d); UnselectAll(); return; }
/*----------------------------------------------------------------------* | make a triangulization of a polygon (private) mwgee 10/05| *----------------------------------------------------------------------*/ bool MOERTEL::Overlap::Triangulation() { // we have a polygon that is in clockwise order at this moment // if more than 3 points, find a center point int np = SizePointPolygon(); if (np<3) { std::cout << "***ERR*** MOERTEL::Overlap::Triangulization:\n" << "***ERR*** # point in polygon < 3 ... very strange!!!\n" << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n"; exit(EXIT_FAILURE); } if (np>3) // we have to add a center point { double xi[2]; std::vector<Teuchos::RCP<MOERTEL::Point> > points; PointView(points); #if 1 // compute center point xi as centroid Centroid(xi,points,np); //std::cout << "Centroid xi : " << xi[0] << " / " << xi[1] << endl; fflush(stdout); #endif #if 0 // compute center point as nodal avergage xi[0] = xi[1] = 0.0; for (int i=0; i<np; ++i) { const double* pxi = points[i]->Xi(); xi[0] += pxi[0]; xi[1] += pxi[1]; } xi[0] /= np; xi[1] /= np; //std::cout << "Nodal xi : " << xi[0] << " / " << xi[1] << endl << endl; fflush(stdout); #endif // create a point -1 as center point and add it to the polygon AddPointtoPolygon(-1,xi); points.clear(); } // if (np>3) np = SizePointPolygon(); std::vector<Teuchos::RCP<MOERTEL::Point> > points; PointView(points); // create a MOERTEL::Node for every point int dof[3]; dof[0] = dof[1] = dof[2] = -1; // find real world coords for all points // find real world normal for all points // note that the polygon is in slave segment parameter space and is // completely contained in the slave segment. we can therefore use // slave segment values to interpolate polgon point values for (int i=0; i<np; ++i) { double x[3]; x[0] = x[1] = x[2] = 0.0; double n[3]; n[0] = n[1] = n[2] = 0.0; double val[20]; sseg_.EvaluateFunction(0,points[i]->Xi(),val,sseg_.Nnode(),NULL); MOERTEL::Node** snodes = sseg_.Nodes(); for (int j=0; j<sseg_.Nnode(); ++j) for (int k=0; k<3; ++k) { x[k] += val[j]*snodes[j]->X()[k]; n[k] += val[j]*snodes[j]->N()[k]; } const double length = MOERTEL::length(n,3); for (int j=0; j<3; ++j) n[j] /= length; // create a node with this coords and normal; MOERTEL::Node* node = new MOERTEL::Node(points[i]->Id(),x,3,dof,false,OutLevel()); node->SetN(n); // set node in point points[i]->SetNode(node); #if 0 std::cout << *points[i]; #endif } // find projection values for all points in polygon on mseg { double mxi[2]; double gap; MOERTEL::Projector projector(inter_.IsOneDimensional(),OutLevel()); for (int i=0; i<np; ++i) { Teuchos::RCP<MOERTEL::Node> node = points[i]->Node(); projector.ProjectNodetoSegment_NodalNormal(*node,mseg_,mxi,gap); // create a projected node and set it in node MOERTEL::ProjectedNode* pnode = new MOERTEL::ProjectedNode(*node,mxi,&mseg_); node->SetProjectedNode(pnode); node->SetGap(gap); #if 0 std::cout << "-------------------------------------------------------\n"; if (mseg_.Nnode()==3) { if (mxi[0]<=1. && mxi[1]<=abs(1.-mxi[0]) && mxi[0]>=0. && mxi[1]>=0.) std::cout << "OVERLAP: point " << points[i]->Id() << " is in mseg, mxi " << mxi[0] << " / " << mxi[1] << endl; else std::cout << "OVERLAP: point " << points[i]->Id() << " is NOT in mseg, mxi " << mxi[0] << " / " << mxi[1] << endl; } else if (mseg_.Nnode()==4) { if (mxi[0]<=1.001 && mxi[0]>=-1.001 && mxi[1]<=1.001 && mxi[1]>=-1.001) std::cout << "OVERLAP: point " << points[i]->Id() << " is in mseg, mxi " << mxi[0] << " / " << mxi[1] << endl; else std::cout << "OVERLAP: point " << points[i]->Id() << " is NOT in mseg, mxi " << mxi[0] << " / " << mxi[1] << endl; } else { std::cout << "***ERR*** MOERTEL::Overlap::Triangulization:\n" << "***ERR*** # nodes " << mseg_.Nnode() << " of master segment is unknown\n" << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n"; exit(EXIT_FAILURE); } std::cout << "-------------------------------------------------------\n"; #endif } } // if we plan to interpolate function values at the gaussian points we need the // function values at the points if (exactvalues_==false) { // every point has 3 values of the 3 shape functions of the elements: // max 4 values from function 0 from sseg // max 4 values from function 1 from sseg // max 4 values from function 0 from mseg for (int i=0; i<np; ++i) { double val[20]; int nmval = mseg_.Nnode(); int nsval = sseg_.Nnode(); // evaluate function 0 from sseg sseg_.EvaluateFunction(0,points[i]->Xi(),val,nsval,NULL); points[i]->StoreFunctionValues(0,val,nsval); // evaluate function 1 from sseg sseg_.EvaluateFunction(1,points[i]->Xi(),val,nsval,NULL); points[i]->StoreFunctionValues(1,val,nsval); // evaluate function 0 from mseg mseg_.EvaluateFunction(0,points[i]->Node()->GetProjectedNode()->Xi(),val,nmval,NULL); points[i]->StoreFunctionValues(2,val,nmval); } } // create the triangle elements from polygon with centerpoint // In case of np==3, there is no centerpoint if (np>3) { // the polygon is in clockwise order, center point is points[0] and has // id = -1 if (points[0]->Id() != -1) { std::cout << "***ERR*** MOERTEL::Overlap::Triangulization:\n" << "***ERR*** points[0]->Id() is not -1\n" << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n"; exit(EXIT_FAILURE); } int nodeid[3]; MOERTEL::Segment_BiLinearTri* tmp; MOERTEL::Function_LinearTri* func = new Function_LinearTri(OutLevel()); for (int i=2; i<np; ++i) { // there are np-1 triangles // triangle ids go from 0 to np-2 // a triangle is defined by nodes 0, i, i-1 // *this class takes ownership of triangle nodeid[0] = points[0]->Id(); nodeid[1] = points[i]->Id(); nodeid[2] = points[i-1]->Id(); tmp = new MOERTEL::Segment_BiLinearTri(i-2,3,nodeid,OutLevel()); // set a linear shape function to this triangle tmp->SetFunction(0,func); // add triangle to the *this class AddSegment(tmp->Id(),tmp); } // add the last triangle defined by nodes 0, 1, np-1 separately // *this class takes ownership of triangle nodeid[0] = points[0]->Id(); nodeid[1] = points[1]->Id(); nodeid[2] = points[np-1]->Id(); tmp = new MOERTEL::Segment_BiLinearTri(np-2,3,nodeid,OutLevel()); // set a linear shape function to this triangle tmp->SetFunction(0,func); // add triangle to the *this class AddSegment(tmp->Id(),tmp); if (func) delete func; func = NULL; } else if (np==3) // single triangle without centerpoint { int nodeid[3]; MOERTEL::Segment_BiLinearTri* tmp; MOERTEL::Function_LinearTri* func = new Function_LinearTri(OutLevel()); nodeid[0] = points[0]->Id(); nodeid[1] = points[2]->Id(); nodeid[2] = points[1]->Id(); // *this class takes ownership of triangle tmp = new MOERTEL::Segment_BiLinearTri(0,3,nodeid,OutLevel()); // set a linear shape function to this triangle tmp->SetFunction(0,func); // add triangle the *this class AddSegment(tmp->Id(),tmp); if (func) delete func; func = NULL; } else { std::cout << "***ERR*** MOERTEL::Overlap::Triangulization:\n" << "***ERR*** # point in polygon < 3 ... very strange!!!\n" << "***ERR*** file/line: " << __FILE__ << "/" << __LINE__ << "\n"; exit(EXIT_FAILURE); } // create ptr topology between triangle and nodes in points std::vector<MOERTEL::Node*> nodes(np); for (int i=0; i<np; ++i) nodes[i] = points[i]->Node().get(); // loop segments and set ptr to nodes in them std::map<int,Teuchos::RCP<MOERTEL::Segment> >::iterator curr; for (curr=s_.begin(); curr != s_.end(); ++curr) curr->second->GetPtrstoNodes(nodes); nodes.clear(); points.clear(); return true; }
int Slice::GenerateSegments(B9ModelInstance* inputInstance) { unsigned int t; int v1; int v2; int cmpcount = 0;//0 or 1 来指示你所寻找的点; QVector3D* thisvert = NULL;//局部指针进行快速访问顶点 QVector3D* thatvert = NULL; std::vector<Triangle3D*>* rangedTriangles; double xdisp; double ydisp; double zdisp; double planefraction; int intersections = 0; //Triangle Splitting here: //Get the right container of triangles and use that as the list //(we used to use the triList which was O(n^2)) rangedTriangles = inputInstance->GetTrianglesAroundZ(realAltitude); for(t = 0; t < rangedTriangles->size(); t++)//for each triangle in the model { //we want to create a temporary pointer to the currenct triangle Triangle3D* pTransTri = rangedTriangles->at(t); //test if the triangle intersects the XY plane of this slice! if(!pTransTri->IntersectsXYPlane(realAltitude)) { continue; } intersections++; cmpcount = 0; //create 1 new segment object for the end result Segment* seg1 = new Segment; QVector2D points[2]; for(v1=0;v1<3;v1++)//for 1 or 2 triangle verts ABOVE the plane: { thisvert = &pTransTri->vertex[v1]; if(thisvert->z() <= realAltitude)//we only want to compare FROM above the plane by convention (yes this means flush triangles below the plane) { continue; } for(v2=0; v2<3; v2++)//to every other triangle vert { if(v2 == v1) {continue;} thatvert = &pTransTri->vertex[v2]; //are both points on the same side of plane? //if so we dont want to compare if((thatvert->z() > realAltitude)) { continue; } cmpcount++; //common //displacments (final - initial) xdisp = thatvert->x() - thisvert->x(); ydisp = thatvert->y() - thisvert->y(); zdisp = thatvert->z() - thisvert->z(); planefraction = (thisvert->z() - realAltitude)/fabs(zdisp);//0-1 fraction of where the plane is in relation to the z distance between the 2 verts. //(0 would be the plane is at the hieght of thisvert) points[cmpcount-1].setX(thisvert->x() + xdisp*planefraction); points[cmpcount-1].setY(thisvert->y() + ydisp*planefraction); } } //initiallize the segment. seg1->normal.setX(pTransTri->normal.x()); seg1->normal.setY(pTransTri->normal.y()); seg1->p1.setX(points[0].x()); seg1->p1.setY(points[0].y()); seg1->p2.setX(points[1].x()); seg1->p2.setY(points[1].y()); seg1->normal.normalize(); seg1->CorrectPointOrder();//to match the normal convention! AddSegment(seg1); } return segmentList.size(); }
//---------------------------------------------------------------------- static ea_t AdditionalSegment(size_t size, ea_t offset, const char *name) { ea_t start = freechunk(0, size, -0xF); return AddSegment(start, size, start - offset, name, SEG_IMEM) - offset; }
//------------------------------------------------------------------------------------- CPattern::CPattern(LPCWSTR szPattern, CPort* pPort, BOOL bUserCommand) { HANDLE hHeap = GetProcessHeap(); m_szBuffer = (LPWSTR)HeapAlloc(hHeap, 0, MAXCOMMAND * sizeof(WCHAR)); m_szSearchBuffer = (LPWSTR)HeapAlloc(hHeap, 0, MAXCOMMAND * sizeof(WCHAR)); //initialization m_pPort = pPort; m_pFirstSegment = m_pLastSegment = NULL; m_szBuffer[0] = L'\0'; m_szSearchBuffer[0] = L'\0'; wcscpy_s(m_szPattern, LENGTHOF(m_szPattern), szPattern); //buffers for search fields WCHAR szBuf[3][MAX_PATH]; WCHAR* pBuf[3] = { szBuf[0], szBuf[1], szBuf[2] }; int nPipes = 0; //parse pattern string while (*szPattern) { switch (*szPattern) { case L'%': if (bUserCommand || nPipes == 0) { int nWidth = 0; UINT nStart = 1; //outside of a search field, all is treated as usually LPCWSTR pTemp = szPattern; szPattern++; if (*szPattern == L'%') { //check buffer overflow if ((pBuf[0] - szBuf[0]) < (LENGTHOF(szBuf[0]) - 1)) *pBuf[0]++ = *szPattern++; else szPattern++; } else { //unary minus int nSign = 1; if (*szPattern == L'-') { nSign = -1; szPattern++; } //width max 2 digits int digits = 0; while (*szPattern >= L'0' && *szPattern <= L'9') { if (digits < 2) nWidth = nWidth * 10 + (*szPattern - L'0'); szPattern++; digits++; } //apply sign nWidth *= nSign; //dot eventually followed by starting value if (*szPattern == L'.') { nStart = 0; szPattern++; static UINT max[] = { 9, 99, 999, 9999, 99999, 999999, 9999999, 99999999, 999999999 }; BOOL bOverflow = FALSE; int index = (nWidth < -9 || nWidth > 9) ? 8 : (nWidth == 0) ? 3 : (nWidth < 0) ? 1 - nWidth : nWidth - 1; while (*szPattern >= L'0' && *szPattern <= L'9') { WCHAR c = *szPattern++; if (bOverflow) continue; nStart = nStart * 10 + (c - L'0'); if (nStart > max[index]) { nStart = 1; bOverflow = TRUE; } } } //read segment type and create appropriate object CPatternSegment* pNewSeg = NULL; switch (*szPattern) { case L'i': if (!bUserCommand) pNewSeg = new CAutoIncrementSegment(nWidth, nStart); else while (pTemp <= szPattern) { //check buffer overflow if ((pBuf[0] - szBuf[0]) < (LENGTHOF(szBuf[0]) - 1)) *pBuf[0]++ = *pTemp++; else pTemp++; } break; case L'f': if (bUserCommand) pNewSeg = new CFileNameSegment(nWidth, m_pPort); else while (pTemp <= szPattern) { //check buffer overflow if ((pBuf[0] - szBuf[0]) < (LENGTHOF(szBuf[0]) - 1)) *pBuf[0]++ = *pTemp++; else pTemp++; } break; case L'p': if (bUserCommand) pNewSeg = new CPathSegment(nWidth, m_pPort); else while (pTemp <= szPattern) { //check buffer overflow if ((pBuf[0] - szBuf[0]) < (LENGTHOF(szBuf[0]) - 1)) *pBuf[0]++ = *pTemp++; else pTemp++; } break; case L'y': pNewSeg = new CShortYearSegment(nWidth); break; case L'Y': pNewSeg = new CLongYearSegment(nWidth); break; case L'm': pNewSeg = new CMonthSegment(nWidth); break; case L'M': pNewSeg = new CMonthNameSegment(nWidth); break; case L'd': pNewSeg = new CDaySegment(nWidth); break; case L'D': pNewSeg = new CDayNameSegment(nWidth); break; case L'h': pNewSeg = new CHour12Segment(nWidth); break; case L'H': pNewSeg = new CHour24Segment(nWidth); break; case L'n': pNewSeg = new CMinuteSegment(nWidth); break; case L's': pNewSeg = new CSecondSegment(nWidth); break; case L't': pNewSeg = new CJobTitleSegment(nWidth, m_pPort); break; case L'j': pNewSeg = new CJobIdSegment(nWidth, m_pPort); break; case L'u': pNewSeg = new CUserNameSegment(nWidth, m_pPort); break; case L'c': pNewSeg = new CComputerNameSegment(nWidth, m_pPort); break; case L'r': pNewSeg = new CPrinterNameSegment(nWidth, m_pPort); break; default: //not a valid field, get here from where we started parsing //and put aside for a static field while (pTemp <= szPattern) { //check buffer overflow if ((pBuf[0] - szBuf[0]) < (LENGTHOF(szBuf[0]) - 1)) *pBuf[0]++ = *pTemp++; else pTemp++; } break; } if (pNewSeg) { //add previously accumulated static segment if (pBuf[0] > szBuf[0]) { *pBuf[0] = L'\0'; AddSegment(new CStaticSegment(szBuf[0])); pBuf[0] = szBuf[0]; } //then add the dynamic segment just created AddSegment(pNewSeg); } szPattern++; } } else { //we populate the nPipes-th buffer inside the search field //all characters are treated literally here if ((pBuf[nPipes] - szBuf[nPipes]) < (LENGTHOF(szBuf[nPipes]) - 1)) *pBuf[nPipes]++ = *szPattern++; else szPattern++; } break; case L'|': if (bUserCommand) { if ((pBuf[nPipes] - szBuf[nPipes]) < (LENGTHOF(szBuf[nPipes]) - 1)) *pBuf[nPipes]++ = *szPattern++; else szPattern++; } else { //we are entering or leaving a search field if (nPipes == 0 && pBuf[0] > szBuf[0]) { *pBuf[0] = L'\0'; AddSegment(new CStaticSegment(szBuf[0])); pBuf[0] = szBuf[0]; } nPipes++; nPipes %= 3; if (nPipes == 0 && pBuf[1] > szBuf[1]) { *pBuf[1] = L'\0'; *pBuf[2] = L'\0'; AddSegment(new CSearchSegment(szBuf[1], szBuf[2])); pBuf[1] = szBuf[1]; pBuf[2] = szBuf[2]; } szPattern++; } break; default: if ((pBuf[nPipes] - szBuf[nPipes]) < (LENGTHOF(szBuf[nPipes]) - 1)) *pBuf[nPipes]++ = *szPattern++; else szPattern++; break; } } //we reached the end of the pattern - did we collect a last static field? if (nPipes == 0 && pBuf[0] > szBuf[0]) { *pBuf[0] = L'\0'; AddSegment(new CStaticSegment(szBuf[0])); } }
int elfExec(Regs *regs, const char *path, const char *pars, size_t parsz) { //getCurrentThread()->therrno = ENOEXEC; vfsLockCreation(); struct stat st; int error = vfsStat(path, &st); if (error != 0) { vfsUnlockCreation(); return sysOpenErrno(error); }; if (!vfsCanCurrentThread(&st, 1)) { vfsUnlockCreation(); getCurrentThread()->therrno = EPERM; return -1; }; File *fp = vfsOpen(path, VFS_CHECK_ACCESS, &error); if (fp == NULL) { vfsUnlockCreation(); return sysOpenErrno(error); }; vfsUnlockCreation(); if (fp->seek == NULL) { vfsClose(fp); getCurrentThread()->therrno = EIO; return -1; }; if (fp->dup == NULL) { vfsClose(fp); getCurrentThread()->therrno = EIO; return -1; }; Elf64_Ehdr elfHeader; if (vfsRead(fp, &elfHeader, sizeof(Elf64_Ehdr)) < sizeof(Elf64_Ehdr)) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (memcmp(elfHeader.e_ident, "\x7f" "ELF", 4) != 0) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (elfHeader.e_ident[EI_CLASS] != ELFCLASS64) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (elfHeader.e_ident[EI_DATA] != ELFDATA2LSB) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (elfHeader.e_ident[EI_VERSION] != 1) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (elfHeader.e_type != ET_EXEC) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (elfHeader.e_phentsize < sizeof(Elf64_Phdr)) { vfsClose(fp); getCurrentThread()->therrno = ENOEXEC; return -1; }; ProgramSegment *segments = (ProgramSegment*) kmalloc(sizeof(ProgramSegment)*(elfHeader.e_phnum)); memset(segments, 0, sizeof(ProgramSegment) * elfHeader.e_phnum); int interpNeeded = 0; Elf64_Dyn *dynamic; unsigned int i; for (i=0; i<elfHeader.e_phnum; i++) { fp->seek(fp, elfHeader.e_phoff + i * elfHeader.e_phentsize, SEEK_SET); Elf64_Phdr proghead; if (vfsRead(fp, &proghead, sizeof(Elf64_Phdr)) < sizeof(Elf64_Phdr)) { kfree(segments); getCurrentThread()->therrno = ENOEXEC; return -1; }; if (proghead.p_type == PT_PHDR) { continue; } else if (proghead.p_type == PT_NULL) { continue; } else if (proghead.p_type == PT_LOAD) { if (proghead.p_vaddr < 0x1000) { vfsClose(fp); kfree(segments); getCurrentThread()->therrno = ENOEXEC; return -1; }; if ((proghead.p_vaddr+proghead.p_memsz) > 0x8000000000) { vfsClose(fp); kfree(segments); return -1; }; uint64_t start = proghead.p_vaddr; segments[i].index = (start)/0x1000; uint64_t end = proghead.p_vaddr + proghead.p_memsz; uint64_t size = end - start; uint64_t numPages = ((start + size) / 0x1000) - segments[i].index + 1; //if (size % 0x1000) numPages++; segments[i].count = (int) numPages; segments[i].fileOffset = proghead.p_offset; segments[i].memorySize = proghead.p_memsz; segments[i].fileSize = proghead.p_filesz; segments[i].loadAddr = proghead.p_vaddr; segments[i].flags = 0; if (proghead.p_flags & PF_R) { segments[i].flags |= PROT_READ; }; if (proghead.p_flags & PF_W) { segments[i].flags |= PROT_WRITE; }; if (proghead.p_flags & PF_X) { segments[i].flags |= PROT_EXEC; }; } else if (proghead.p_type == PT_INTERP) { interpNeeded = 1; } else if (proghead.p_type == PT_DYNAMIC) { dynamic = (Elf64_Dyn*) proghead.p_vaddr; } else { kfree(segments); getCurrentThread()->therrno = ENOEXEC; return -1; }; }; // set the signal handler to default. getCurrentThread()->rootSigHandler = 0; // thread name strcpy(getCurrentThread()->name, path); // set the execPars Thread *thread = getCurrentThread(); if (thread->execPars != NULL) kfree(thread->execPars); thread->execPars = (char*) kmalloc(parsz); thread->szExecPars = parsz; memcpy(thread->execPars, pars, parsz); // create a new address space ProcMem *pm = CreateProcessMemory(); // switch the address space, so that AddSegment() can optimize mapping lockSched(); ProcMem *oldPM = thread->pm; thread->pm = pm; unlockSched(); SetProcessMemory(pm); DownrefProcessMemory(oldPM); // pass 1: allocate the frames and map them for (i=0; i<(elfHeader.e_phnum); i++) { if (segments[i].count > 0) { FrameList *fl = palloc_later(segments[i].count, segments[i].fileOffset, segments[i].fileSize); if (AddSegment(pm, segments[i].index, fl, segments[i].flags) != 0) { getCurrentThread()->therrno = ENOEXEC; pdownref(fl); DownrefProcessMemory(pm); break; }; pdownref(fl); }; }; // change the fpexec if (thread->fpexec != NULL) { if (thread->fpexec->close != NULL) thread->fpexec->close(thread->fpexec); kfree(thread->fpexec); }; thread->fpexec = fp; // make sure we jump to the entry upon return regs->rip = elfHeader.e_entry; // the errnoptr is now invalid thread->errnoptr = NULL; // close all files marked with O_CLOEXEC (on glidx a.k.a. FD_CLOEXEC) spinlockAcquire(&getCurrentThread()->ftab->spinlock); for (i=0; i<MAX_OPEN_FILES; i++) { File *fp = getCurrentThread()->ftab->entries[i]; if (fp != NULL) { if (fp->oflag & O_CLOEXEC) { getCurrentThread()->ftab->entries[i] = NULL; vfsClose(fp); }; }; }; spinlockRelease(&getCurrentThread()->ftab->spinlock); // suid/sgid stuff if (st.st_mode & VFS_MODE_SETUID) { thread->euid = st.st_uid; //thread->ruid = st.st_uid; //thread->suid = st.st_uid; thread->flags |= THREAD_REBEL; }; if (st.st_mode & VFS_MODE_SETGID) { thread->egid = st.st_gid; //thread->rgid = st.st_gid; //thread->sgid = st.st_gid; thread->flags |= THREAD_REBEL; }; if (interpNeeded) { linkInterp(regs, dynamic, pm); }; return 0; };
int YARPObjectContainer::Find (YARPImageOf<YarpPixelBGR>& scan, YARPImageOf<YarpPixelBGR>& out, int& bestaction) { if (!m_active) { printf ("YARPObjectContainer: need to update stats first\n"); bestaction = -1; out.PeerCopy(scan); m_last_known_object = -1; m_orientation = 0; m_displacement = 0; return -1; } YarpPixelBGR red; red.r = 255; red.g = red.b = 0; double x, y, quality; double max_quality = 0; int max_obj = -1; double max_x = 0, max_y = 0; const int NOBJ = m_canonical_stats->m_goodneurons; for (int obj = 0; obj < NOBJ; obj++) { m_locator[obj].BackProject (scan, m_backp[obj]); double ex, ey; m_locator[obj].GetExtent (ex, ey); ex *= SCALE; ey *= SCALE; if (m_locator[obj].Find (ex, ey, x, y, quality) >= 0) { double mean = 0, stddev = 0; const double THR = 2.0; m_locator[obj].GetExpectancy (mean, stddev); bool thr_cond = (fabs(quality - mean) < stddev * THR) ? true : false; printf ("object: %d location: %lf %lf q: %lf\n", obj, x, y, quality); if (quality > max_quality && thr_cond) { max_quality = quality; max_obj = obj; max_x = x; max_y = y; } } } m_last_known_object = max_obj; if (max_obj == -1) { printf ("I (COG) don't know about this object, if there's one at all!\n"); bestaction = -1; out.PeerCopy(scan); m_orientation = 0; m_displacement = 0; return -1; } // if max_quality is not good enough then skip the following search. // if pointiness is not good enough then skip the following search. printf ("object is %d, improving position\n", max_obj); double ex, ey; m_locator[max_obj].GetExtent (ex, ey); ex *= SCALE; ey *= SCALE; // try to improve the position estimation. double betterx = 0, bettery = 0; m_locator[max_obj].ImprovedSearch (scan, ex, ey, max_x, max_y, betterx, bettery); printf ("object is %d, looking for orientation\n", max_obj); double angle = -1; double angle2 = -1; double ave = 0; double std = 0; m_locator[max_obj].GetNumberOfPoints (ave, std); // need to add a threshold on pointiness! YARPSearchRotation sr (50, 0.0); sr.Search (int(m_canonical_stats->m_neuron_numbers(max_obj+1)), *m_canonical, scan, betterx, bettery, ave, std, angle, angle2); // store for future use. m_orientation = angle; m_displacement = 0; printf ("orientation: %lf\n", angle * radToDeg); int x1 = betterx + cos(angle) * 40; int y1 = bettery + sin(angle) * 40; int x2 = betterx - cos(angle) * 40; int y2 = bettery - sin(angle) * 40; AddSegment (m_backp[max_obj], red, x1, y1, x2, y2); AddRectangle (m_backp[max_obj], red, int(betterx+.5), int(bettery+.5), int (ex/2+.5), int (ey/2+.5)); AddCircleOutline (m_backp[max_obj], red, int(max_x+.5), int(max_y+.5), 10); AddCircle (m_backp[max_obj], red, int(betterx+.5), int(bettery+.5), 5); // return processed image. out.PeerCopy (m_backp[max_obj]); // angle is the current orientation. // search for the best affordance. const double affordance = m_canonical_stats->GetPrincipalAffordance (max_obj); double o1 = angle+affordance; double o2 = angle-affordance; printf ("---- object: %d, affordance: %lf, test1: %lf, test2: %lf\n", max_obj, affordance*radToDeg, o1*radToDeg, o2*radToDeg); if (o1 > pi/2) o1 -= pi; else if (o1 < -pi/2) o1 += pi; if (o2 > pi/2) o2 -= pi; else if (o2 < -pi/2) o2 += pi; double score1 = 0; double score2 = 0; int bestaction1 = m_canonical_stats->GetBestActionGeneric (o1, score1); int bestaction2 = m_canonical_stats->GetBestActionGeneric (o2, score2); printf ("---- score(s) %lf %lf\n", score1, score2); if (score1 < score2) bestaction = bestaction1; else bestaction = bestaction2; printf ("the best action for this object in this position is %d\n", bestaction); return 0; }
BOOL CcdrawDoc::AddSegment(CComplex p0, CComplex p1, CSegment &segm, double tol) { int i,j,k,n0,n1; double xi,yi,t; CComplex p[2]; CArray< CComplex, CComplex&> newnodes; newnodes.RemoveAll(); n0=ClosestNode(p0.re,p0.im); n1=ClosestNode(p1.re,p1.im); // don't add if line is degenerate if (n0==n1) return FALSE; // don't add if the line is already in the list; for(i=0;i<linelist.GetSize();i++){ if ((linelist[i].n0==n0) && (linelist[i].n1==n1)) return FALSE; if ((linelist[i].n0==n1) && (linelist[i].n1==n0)) return FALSE; } segm.IsSelected=FALSE; segm.n0=n0; segm.n1=n1; // check to see if there are intersections with segments for(i=0;i<linelist.GetSize();i++) if(GetIntersection(n0,n1,i,&xi,&yi)==TRUE) newnodes.Add(CComplex(xi,yi)); // check to see if there are intersections with arcs for(i=0;i<arclist.GetSize();i++){ j=GetLineArcIntersection(segm,arclist[i],p); if (j>0) for(k=0;k<j;k++) newnodes.Add(p[k]); } // add nodes at intersections if(tol==0) { if (nodelist.GetSize()<2) t=1.e-08; else{ CComplex p0,p1; p0=nodelist[0].CC(); p1=p0; for(i=1;i<nodelist.GetSize();i++) { if(nodelist[i].x<p0.re) p0.re=nodelist[i].x; if(nodelist[i].x>p1.re) p1.re=nodelist[i].x; if(nodelist[i].y<p0.im) p0.im=nodelist[i].y; if(nodelist[i].y>p1.im) p1.im=nodelist[i].y; } t=abs(p1-p0)*CLOSE_ENOUGH; } } else t=tol; for(i=0;i<newnodes.GetSize();i++) AddNode(newnodes[i].re,newnodes[i].im,t); // Add proposed line segment linelist.Add(segm); // check to see if proposed line passes through other points; // if so, delete line and create lines that link intermediate points; // does this by recursive use of AddSegment; double d,dmin; UnselectAll(); if (tol==0) dmin=abs(nodelist[n1].CC()-nodelist[n0].CC())*1.e-05; else dmin=tol; k=(int) linelist.GetSize()-1; for(i=0;i<nodelist.GetSize();i++) { if( (i!=n0) && (i!=n1) ) { d=ShortestDistance(nodelist[i].x,nodelist[i].y,k); // catch a special case... if (abs(nodelist[i].CC()-nodelist[n0].CC())<dmin) d=2.*dmin; if (abs(nodelist[i].CC()-nodelist[n1].CC())<dmin) d=2.*dmin; if (d<dmin){ linelist[k].ToggleSelect(); DeleteSelectedSegments(); AddSegment(n0,i,&segm,dmin); AddSegment(i,n1,&segm,dmin); i=(int) nodelist.GetSize(); } } } return TRUE; }
void CcdrawDoc::FancyEnforcePSLG(double tol) { /* need to enforce: 1) no duplicate point; 2) no intersections between line segments, lines and arcs, or arcs; 3) no duplicate block labels; 4) no overlapping lines or arcs. can do this by cleaning out the various lists, and rebuilding them using the ``add'' functions that ensure that things come out right. */ CArray< CNode, CNode&> newnodelist; CArray< CSegment, CSegment&> newlinelist; CArray< CArcSegment, CArcSegment&> newarclist; CArray< CBlockLabel, CBlockLabel&> newblocklist; int i,k; CComplex p0,p1; double d; bLinehook=ImportDXF; // kludge to stop the program from giving a crash if // the user tries to exit during a dxf import. CcdrawView *pView; POSITION pos; pos=GetFirstViewPosition(); pView=(CcdrawView *)GetNextView(pos); FirstDraw=TRUE; // pView->lua_zoomnatural(); dxf_line_hook(); pView->EditAction=4; newnodelist.RemoveAll(); newlinelist.RemoveAll(); newarclist.RemoveAll(); newblocklist.RemoveAll(); for(i=0;i<nodelist.GetSize();i++) newnodelist.Add(nodelist[i]); for(i=0;i<linelist.GetSize();i++) newlinelist.Add(linelist[i]); for(i=0;i<arclist.GetSize();i++) newarclist.Add(arclist[i]); for(i=0;i<blocklist.GetSize();i++) newblocklist.Add(blocklist[i]); nodelist.RemoveAll(); linelist.RemoveAll(); arclist.RemoveAll(); blocklist.RemoveAll(); pView->InvalidateRect(NULL); dxf_line_hook(); // find out what tolerance is so that there are not nodes right on // top of each other; if(tol==0){ if (newnodelist.GetSize()<2) d=1.e-08; else{ p0=newnodelist[0].CC(); p1=p0; for(i=1;i<newnodelist.GetSize();i++) { if(newnodelist[i].x<p0.re) p0.re=newnodelist[i].x; if(newnodelist[i].x>p1.re) p1.re=newnodelist[i].x; if(newnodelist[i].y<p0.im) p0.im=newnodelist[i].y; if(newnodelist[i].y>p1.im) p1.im=newnodelist[i].y; } d=abs(p1-p0)*CLOSE_ENOUGH; } } else d=tol; // put in all of the lines; for(i=0;i<newlinelist.GetSize();i++) { // Add in endpoints of the proposed line; AddNode(newnodelist[newlinelist[i].n0],d); AddNode(newnodelist[newlinelist[i].n1],d); // Add in the proposed line itself; p0=newnodelist[newlinelist[i].n0].CC(); p1=newnodelist[newlinelist[i].n1].CC(); if(AddSegment(p0,p1,newlinelist[i],d)==TRUE) { pView->DrawPSLG(); if(dxf_line_hook()){ bLinehook=FALSE; return; } } } // put in all of the arcs; for(i=0;i<newarclist.GetSize();i++) { // Add in endpoints of the proposed line; AddNode(newnodelist[newarclist[i].n0],d); AddNode(newnodelist[newarclist[i].n1],d); // Add in the proposed arc inself; p0=newnodelist[newarclist[i].n0].CC(); p1=newnodelist[newarclist[i].n1].CC(); if(AddArcSegment(p0,p1,newarclist[i],d)==TRUE) { pView->DrawPSLG(); if(dxf_line_hook()){ bLinehook=FALSE; return; } } } UnselectAll(); // do one last check to eliminate shallow arcs that // link up the same two points as a line segment; for(i=0;i<arclist.GetSize();i++) { if (arclist[i].ArcLength<=22.5) { for(k=0;k<linelist.GetSize();k++) { if ((arclist[i].n0==linelist[k].n0) && (arclist[i].n1==linelist[k].n1)) arclist[i].IsSelected=TRUE; if ((arclist[i].n1==linelist[k].n0) && (arclist[i].n0==linelist[k].n1)) arclist[i].IsSelected=TRUE; if (arclist[i].IsSelected) k=(int) linelist.GetSize(); } } } DeleteSelectedArcSegments(); // put in all of the block labels; for(i=0;i<newblocklist.GetSize();i++) AddBlockLabel(newblocklist[i],d); if(SelectOrphans()) { CString msg; msg ="There are lines or arcs with \"Orphaned\" end points.\n"; msg+="The lines or arcs could be glitches in the DXF import\n"; msg+="import, so they should be examined manually.\n"; msg+="These points and lines will be shown as selected.\n"; msg+="To redisplay the orphaned points and lines, select\n"; msg+="View|Show Orphans off of the main menu."; MsgBox(msg); } bLinehook=FALSE; return; }
// // only find object and orientation. // int YARPObjectContainer::FindSimple (YARPImageOf<YarpPixelBGR>& scan, YARPImageOf<YarpPixelBGR>& out) { if (!m_active) { printf ("YARPObjectContainer: need to update stats first\n"); out.PeerCopy(scan); m_last_known_object = -1; m_orientation = 0; m_displacement = 0; return -1; } YarpPixelBGR red; red.r = 255; red.g = red.b = 0; double x, y, quality; double max_quality = 0; int max_obj = -1; double max_x = 0, max_y = 0; const int NOBJ = m_canonical_stats->m_goodneurons; for (int obj = 0; obj < NOBJ; obj++) { m_locator[obj].BackProject (scan, m_backp[obj]); double ex, ey; m_locator[obj].GetExtent (ex, ey); ex *= SCALE; ey *= SCALE; if (m_locator[obj].Find (ex, ey, x, y, quality) >= 0) { double mean = 0, stddev = 0; const double THR = 2.0; m_locator[obj].GetExpectancy (mean, stddev); bool thr_cond = (fabs(quality - mean) < stddev * THR) ? true : false; #ifdef _DEBUG printf ("object: %d location: %lf %lf q: %lf\n", obj, x, y, quality); #endif if (quality > max_quality && thr_cond) { max_quality = quality; max_obj = obj; max_x = x; max_y = y; } } } m_last_known_object = max_obj; if (max_obj == -1) { printf ("I (COG) don't know about this object, if there's one at all!\n"); out.PeerCopy(scan); m_orientation = 0; m_displacement = 0; return -1; } // if max_quality is not good enough then skip the following search. // if pointiness is not good enough then skip the following search. #ifdef _DEBUG printf ("object is %d, improving position\n", max_obj); #endif double ex, ey; m_locator[max_obj].GetExtent (ex, ey); ex *= SCALE; ey *= SCALE; // try to improve the position estimation. double betterx = 0, bettery = 0; m_locator[max_obj].ImprovedSearch (scan, ex, ey, max_x, max_y, betterx, bettery); #ifdef _DEBUG printf ("object is %d, looking for orientation\n", max_obj); #endif double angle = -1; double angle2 = -1; double ave = 0; double std = 0; m_locator[max_obj].GetNumberOfPoints (ave, std); // need to add a threshold on pointiness! YARPSearchRotation sr (50, 0.0); sr.Search (int(m_canonical_stats->m_neuron_numbers(max_obj+1)), *m_canonical, scan, betterx, bettery, ave, std, angle, angle2); // store for future use. m_orientation = angle; m_displacement = 0; #ifdef _DEBUG printf ("orientation: %lf\n", angle * radToDeg); #endif int x1 = betterx + cos(angle) * 40; int y1 = bettery + sin(angle) * 40; int x2 = betterx - cos(angle) * 40; int y2 = bettery - sin(angle) * 40; AddSegment (m_backp[max_obj], red, x1, y1, x2, y2); AddRectangle (m_backp[max_obj], red, int(betterx+.5), int(bettery+.5), int (ex/2+.5), int (ey/2+.5)); AddCircleOutline (m_backp[max_obj], red, int(max_x+.5), int(max_y+.5), 10); AddCircle (m_backp[max_obj], red, int(betterx+.5), int(bettery+.5), 5); // return processed image. out.PeerCopy (m_backp[max_obj]); return 0; }
// Update. void COGEmitterScrollingRay::Update (unsigned long _ElapsedTime) { if (m_Status == OG_EFFECTSTATUS_INACTIVE || !m_bPosReady) return; bool bAdd = false; float fNewSegScale = 0.0f; std::list<ParticleFormat>::iterator iter = m_BBList.begin(); while (iter != m_BBList.end()) { ParticleFormat& seg = (*iter); if (seg.pos == 0.0f && seg.scale < 1.0f) { float fAdd = m_fSpeed / m_fSegment; if (seg.scale + fAdd > 1.0f) { float fMove = seg.scale + fAdd - 1.0f; bAdd = true; fNewSegScale = fMove; if (ScrollSegment(seg, fMove)) { GetEffectsManager()->ReleaseParticle(seg.verts); iter = m_BBList.erase(iter); continue; } } else { seg.scale += fAdd; seg.start -= fAdd; } } else { if (seg.pos == 0.0f && m_fSpeed > 0.0f) { bAdd = true; fNewSegScale = (m_fSpeed / m_fSegment); } if (ScrollSegment(seg, m_fSpeed)) { GetEffectsManager()->ReleaseParticle(seg.verts); iter = m_BBList.erase(iter); continue; } } UpdateSegment(seg); ++iter; } if (bAdd) { AddSegment(0.0f, fNewSegScale); } }
const Error *Path::Pause( double sec ) { DelaySeg *seg = new DelaySeg( posEnd, sec ); if( !seg ) return &PathError::Alloc; return AddSegment( seg ); }
void Mesh::Refine() { // reduce 2nd order size_t nb_vertices = ComputeNVertices(); points.resize(nb_vertices); IndexPair_map<PointIndex> between(nb_vertices + 5); size_t oldns = segments.size(); for (size_t si = 0; si < oldns; si++) { const Segment& seg = segments[si]; const MeshPoint& p1 = points[seg[0]]; const MeshPoint& p2 = points[seg[1]]; IndexPair i2(seg[0], seg[1]); i2.Sort(); PointIndex pi_new; if (between.count(i2) == 1) { pi_new = between[i2]; } else { Point2d pnew; pnew.X() = 0.5 * (p1.X() + p2.X()); pnew.Y() = 0.5 * (p1.Y() + p2.Y()); pi_new = AddPoint(pnew); between[i2] = pi_new; } Segment ns1 = seg; Segment ns2 = seg; ns1[1] = pi_new; ns2[0] = pi_new; segments[si] = ns1; AddSegment(ns2); } // refine surface elements size_t oldnf = elements.size(); for (size_t sei = 0; sei < oldnf; sei++) { int j, k; const Element2d& el = elements[sei]; PointIndex pnums[6]; static int betw[3][3] = {{1, 2, 3}, {0, 2, 4}, {0, 1, 5}}; for (j = 0; j < 3; j++) { pnums[j] = el.PointID(j); } for (j = 0; j < 3; j++) { PointIndex pi1 = pnums[betw[j][0]]; PointIndex pi2 = pnums[betw[j][1]]; IndexPair i2(pi1, pi2); i2.Sort(); if (between.count(i2) == 0) { const MeshPoint& p1 = points[pi1]; const MeshPoint& p2 = points[pi2]; Point2d pnew; pnew.X() = 0.5 * (p1.X() + p2.X()); pnew.Y() = 0.5 * (p1.Y() + p2.Y()); between[i2] = AddPoint(pnew); } pnums[3 + j] = between[i2]; } static int reftab[4][3] = {{0, 5, 4}, {1, 3, 5}, {2, 4, 3}, {5, 3, 4}}; DomainIndex ind = el.FaceID(); for (j = 0; j < 4; j++) { Element2d new_element; for (k = 0; k < 3; k++) { new_element.PointID(k) = pnums[reftab[j][k]]; } new_element.SetFaceID(ind); if (j == 0) { elements[sei] = new_element; } else { AddElement(new_element); } } } ComputeNVertices(); RebuildSurfaceElementLists(); }
static PVIEWERLINE SegmentText(PVIEWERPARAMS pViewerParams, char *pchText, BOOL bHighlight) { PVIEWERLINE pFirstSeg=NULL, pCurrentSeg=NULL; VIEWERLINE LineSeg; char *pchTemp = pchText; ULONG ulLen=0; BOOL bTest=TRUE; ULONG ulType=0; if (!pchText) return NULL; LineSeg.pchLine = pchText; LineSeg.ulLineLen = 0; while (*pchTemp) { if (bTest) { ulType = GetLineType(pViewerParams, pchTemp); bTest = FALSE; } switch(*pchTemp) { case '_': case '*': case '/': if (bHighlight) { ulLen = QuerySegment(pchText, pchTemp); if (ulLen) { /* Altes Segment */ if (LineSeg.ulLineLen) { LineSeg.ulFlags = ulType; pCurrentSeg = AddSegment(pCurrentSeg, &LineSeg); if (!pFirstSeg) pFirstSeg = pCurrentSeg; } /* neues Segment */ LineSeg.ulFlags = ulType; LineSeg.ulLineLen = ulLen; LineSeg.pchLine = pchTemp+1; switch(*pchTemp) { case '_': LineSeg.ulFlags |= LINESEG_UNDER; break; case '/': LineSeg.ulFlags |= LINESEG_ITALIC; break; default: LineSeg.ulFlags |= LINESEG_BOLD; break; } pCurrentSeg = AddSegment(pCurrentSeg, &LineSeg); if (!pFirstSeg) pFirstSeg = pCurrentSeg; /* naechstes Segment */ pchTemp += 1+ulLen; LineSeg.pchLine = pchTemp+1; LineSeg.ulLineLen = 0; LineSeg.ulFlags = ulType; } else LineSeg.ulLineLen++; } else LineSeg.ulLineLen++; break; case '\n': LineSeg.ulFlags = LINESEG_NEWLINE | ulType; pCurrentSeg = AddSegment(pCurrentSeg, &LineSeg); if (!pFirstSeg) pFirstSeg = pCurrentSeg; LineSeg.pchLine = pchTemp+1; LineSeg.ulLineLen = 0; bTest=TRUE; break; default: LineSeg.ulLineLen++; break; } pchTemp++; } if (LineSeg.ulLineLen) { /* letztes Segment noch hinzuf�gen */ LineSeg.ulFlags = LINESEG_NEWLINE | ulType; pCurrentSeg = AddSegment(pCurrentSeg, &LineSeg); if (!pFirstSeg) pFirstSeg = pCurrentSeg; } if (pCurrentSeg) /* sicherstellen, da� letztes Segment das Zeilenende-Flag hat. Kann vor- kommen, wenn letztes Segment ein fettes oder unterstrichenes Segment war */ pCurrentSeg->ulFlags |= LINESEG_NEWLINE; return pFirstSeg; }