/// Changes a btManifoldPoint collision normal to the normal from the mesh. void btAdjustInternalEdgeContacts(btManifoldPoint& cp, const btCollisionObjectWrapper* colObj0Wrap,const btCollisionObjectWrapper* colObj1Wrap, int partId0, int index0, int normalAdjustFlags) { //btAssert(colObj0->getCollisionShape()->getShapeType() == TRIANGLE_SHAPE_PROXYTYPE); if (colObj0Wrap->getCollisionShape()->getShapeType() != TRIANGLE_SHAPE_PROXYTYPE) return; btBvhTriangleMeshShape* trimesh = 0; if( colObj0Wrap->getCollisionObject()->getCollisionShape()->getShapeType() == SCALED_TRIANGLE_MESH_SHAPE_PROXYTYPE ) trimesh = ((btScaledBvhTriangleMeshShape*)colObj0Wrap->getCollisionObject()->getCollisionShape())->getChildShape(); else trimesh = (btBvhTriangleMeshShape*)colObj0Wrap->getCollisionObject()->getCollisionShape(); btTriangleInfoMap* triangleInfoMapPtr = (btTriangleInfoMap*) trimesh->getTriangleInfoMap(); if (!triangleInfoMapPtr) return; int hash = btGetHash(partId0,index0); btTriangleInfo* info = triangleInfoMapPtr->find(hash); if (!info) return; btScalar frontFacing = (normalAdjustFlags & BT_TRIANGLE_CONVEX_BACKFACE_MODE)==0? 1.f : -1.f; const btTriangleShape* tri_shape = static_cast<const btTriangleShape*>(colObj0Wrap->getCollisionShape()); btVector3 v0,v1,v2; tri_shape->getVertex(0,v0); tri_shape->getVertex(1,v1); tri_shape->getVertex(2,v2); //btVector3 center = (v0+v1+v2)*btScalar(1./3.); btVector3 red(1,0,0), green(0,1,0),blue(0,0,1),white(1,1,1),black(0,0,0); btVector3 tri_normal; tri_shape->calcNormal(tri_normal); //btScalar dot = tri_normal.dot(cp.m_normalWorldOnB); btVector3 nearest; btNearestPointInLineSegment(cp.m_localPointB,v0,v1,nearest); btVector3 contact = cp.m_localPointB; #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW const btTransform& tr = colObj0->getWorldTransform(); btDebugDrawLine(tr*nearest,tr*cp.m_localPointB,red); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW bool isNearEdge = false; int numConcaveEdgeHits = 0; int numConvexEdgeHits = 0; btVector3 localContactNormalOnB = colObj0Wrap->getWorldTransform().getBasis().transpose() * cp.m_normalWorldOnB; localContactNormalOnB.normalize();//is this necessary? // Get closest edge int bestedge=-1; btScalar disttobestedge=BT_LARGE_FLOAT; // // Edge 0 -> 1 if (btFabs(info->m_edgeV0V1Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { btVector3 nearest; btNearestPointInLineSegment( cp.m_localPointB, v0, v1, nearest ); btScalar len=(contact-nearest).length(); // if( len < disttobestedge ) { bestedge=0; disttobestedge=len; } } // Edge 1 -> 2 if (btFabs(info->m_edgeV1V2Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { btVector3 nearest; btNearestPointInLineSegment( cp.m_localPointB, v1, v2, nearest ); btScalar len=(contact-nearest).length(); // if( len < disttobestedge ) { bestedge=1; disttobestedge=len; } } // Edge 2 -> 0 if (btFabs(info->m_edgeV2V0Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { btVector3 nearest; btNearestPointInLineSegment( cp.m_localPointB, v2, v0, nearest ); btScalar len=(contact-nearest).length(); // if( len < disttobestedge ) { bestedge=2; disttobestedge=len; } } #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 upfix=tri_normal * btVector3(0.1f,0.1f,0.1f); btDebugDrawLine(tr * v0 + upfix, tr * v1 + upfix, red ); #endif if (btFabs(info->m_edgeV0V1Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*contact,tr*(contact+cp.m_normalWorldOnB*10),black); #endif btScalar len = (contact-nearest).length(); if(len<triangleInfoMapPtr->m_edgeDistanceThreshold) if( bestedge==0 ) { btVector3 edge(v0-v1); isNearEdge = true; if (info->m_edgeV0V1Angle==btScalar(0)) { numConcaveEdgeHits++; } else { bool isEdgeConvex = (info->m_flags & TRI_INFO_V0V1_CONVEX); btScalar swapFactor = isEdgeConvex ? btScalar(1) : btScalar(-1); #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*(nearest+swapFactor*tri_normal*10),white); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 nA = swapFactor * tri_normal; btQuaternion orn(edge,info->m_edgeV0V1Angle); btVector3 computedNormalB = quatRotate(orn,tri_normal); if (info->m_flags & TRI_INFO_V0V1_SWAP_NORMALB) computedNormalB*=-1; btVector3 nB = swapFactor*computedNormalB; btScalar NdotA = localContactNormalOnB.dot(nA); btScalar NdotB = localContactNormalOnB.dot(nB); bool backFacingNormal = (NdotA< triangleInfoMapPtr->m_convexEpsilon) && (NdotB<triangleInfoMapPtr->m_convexEpsilon); #ifdef DEBUG_INTERNAL_EDGE { btDebugDrawLine(cp.getPositionWorldOnB(),cp.getPositionWorldOnB()+tr.getBasis()*(nB*20),red); } #endif //DEBUG_INTERNAL_EDGE if (backFacingNormal) { numConcaveEdgeHits++; } else { numConvexEdgeHits++; btVector3 clampedLocalNormal; bool isClamped = btClampNormal(edge,swapFactor*tri_normal,localContactNormalOnB, info->m_edgeV0V1Angle,clampedLocalNormal); if (isClamped) { if (((normalAdjustFlags & BT_TRIANGLE_CONVEX_DOUBLE_SIDED)!=0) || (clampedLocalNormal.dot(frontFacing*tri_normal)>0)) { btVector3 newNormal = colObj0Wrap->getWorldTransform().getBasis() * clampedLocalNormal; // cp.m_distance1 = cp.m_distance1 * newNormal.dot(cp.m_normalWorldOnB); cp.m_normalWorldOnB = newNormal; // Reproject collision point along normal. (what about cp.m_distance1?) cp.m_positionWorldOnB = cp.m_positionWorldOnA - cp.m_normalWorldOnB * cp.m_distance1; cp.m_localPointB = colObj0Wrap->getWorldTransform().invXform(cp.m_positionWorldOnB); } } } } } } btNearestPointInLineSegment(contact,v1,v2,nearest); #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*cp.m_localPointB,green); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr * v1 + upfix, tr * v2 + upfix , green ); #endif if (btFabs(info->m_edgeV1V2Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*contact,tr*(contact+cp.m_normalWorldOnB*10),black); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btScalar len = (contact-nearest).length(); if(len<triangleInfoMapPtr->m_edgeDistanceThreshold) if( bestedge==1 ) { isNearEdge = true; #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*(nearest+tri_normal*10),white); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 edge(v1-v2); isNearEdge = true; if (info->m_edgeV1V2Angle == btScalar(0)) { numConcaveEdgeHits++; } else { bool isEdgeConvex = (info->m_flags & TRI_INFO_V1V2_CONVEX)!=0; btScalar swapFactor = isEdgeConvex ? btScalar(1) : btScalar(-1); #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*(nearest+swapFactor*tri_normal*10),white); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 nA = swapFactor * tri_normal; btQuaternion orn(edge,info->m_edgeV1V2Angle); btVector3 computedNormalB = quatRotate(orn,tri_normal); if (info->m_flags & TRI_INFO_V1V2_SWAP_NORMALB) computedNormalB*=-1; btVector3 nB = swapFactor*computedNormalB; #ifdef DEBUG_INTERNAL_EDGE { btDebugDrawLine(cp.getPositionWorldOnB(),cp.getPositionWorldOnB()+tr.getBasis()*(nB*20),red); } #endif //DEBUG_INTERNAL_EDGE btScalar NdotA = localContactNormalOnB.dot(nA); btScalar NdotB = localContactNormalOnB.dot(nB); bool backFacingNormal = (NdotA< triangleInfoMapPtr->m_convexEpsilon) && (NdotB<triangleInfoMapPtr->m_convexEpsilon); if (backFacingNormal) { numConcaveEdgeHits++; } else { numConvexEdgeHits++; btVector3 localContactNormalOnB = colObj0Wrap->getWorldTransform().getBasis().transpose() * cp.m_normalWorldOnB; btVector3 clampedLocalNormal; bool isClamped = btClampNormal(edge,swapFactor*tri_normal,localContactNormalOnB, info->m_edgeV1V2Angle,clampedLocalNormal); if (isClamped) { if (((normalAdjustFlags & BT_TRIANGLE_CONVEX_DOUBLE_SIDED)!=0) || (clampedLocalNormal.dot(frontFacing*tri_normal)>0)) { btVector3 newNormal = colObj0Wrap->getWorldTransform().getBasis() * clampedLocalNormal; // cp.m_distance1 = cp.m_distance1 * newNormal.dot(cp.m_normalWorldOnB); cp.m_normalWorldOnB = newNormal; // Reproject collision point along normal. cp.m_positionWorldOnB = cp.m_positionWorldOnA - cp.m_normalWorldOnB * cp.m_distance1; cp.m_localPointB = colObj0Wrap->getWorldTransform().invXform(cp.m_positionWorldOnB); } } } } } } btNearestPointInLineSegment(contact,v2,v0,nearest); #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*cp.m_localPointB,blue); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr * v2 + upfix, tr * v0 + upfix , blue ); #endif if (btFabs(info->m_edgeV2V0Angle)< triangleInfoMapPtr->m_maxEdgeAngleThreshold) { #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*contact,tr*(contact+cp.m_normalWorldOnB*10),black); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btScalar len = (contact-nearest).length(); if(len<triangleInfoMapPtr->m_edgeDistanceThreshold) if( bestedge==2 ) { isNearEdge = true; #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*(nearest+tri_normal*10),white); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 edge(v2-v0); if (info->m_edgeV2V0Angle==btScalar(0)) { numConcaveEdgeHits++; } else { bool isEdgeConvex = (info->m_flags & TRI_INFO_V2V0_CONVEX)!=0; btScalar swapFactor = isEdgeConvex ? btScalar(1) : btScalar(-1); #ifdef BT_INTERNAL_EDGE_DEBUG_DRAW btDebugDrawLine(tr*nearest,tr*(nearest+swapFactor*tri_normal*10),white); #endif //BT_INTERNAL_EDGE_DEBUG_DRAW btVector3 nA = swapFactor * tri_normal; btQuaternion orn(edge,info->m_edgeV2V0Angle); btVector3 computedNormalB = quatRotate(orn,tri_normal); if (info->m_flags & TRI_INFO_V2V0_SWAP_NORMALB) computedNormalB*=-1; btVector3 nB = swapFactor*computedNormalB; #ifdef DEBUG_INTERNAL_EDGE { btDebugDrawLine(cp.getPositionWorldOnB(),cp.getPositionWorldOnB()+tr.getBasis()*(nB*20),red); } #endif //DEBUG_INTERNAL_EDGE btScalar NdotA = localContactNormalOnB.dot(nA); btScalar NdotB = localContactNormalOnB.dot(nB); bool backFacingNormal = (NdotA< triangleInfoMapPtr->m_convexEpsilon) && (NdotB<triangleInfoMapPtr->m_convexEpsilon); if (backFacingNormal) { numConcaveEdgeHits++; } else { numConvexEdgeHits++; // printf("hitting convex edge\n"); btVector3 localContactNormalOnB = colObj0Wrap->getWorldTransform().getBasis().transpose() * cp.m_normalWorldOnB; btVector3 clampedLocalNormal; bool isClamped = btClampNormal(edge,swapFactor*tri_normal,localContactNormalOnB,info->m_edgeV2V0Angle,clampedLocalNormal); if (isClamped) { if (((normalAdjustFlags & BT_TRIANGLE_CONVEX_DOUBLE_SIDED)!=0) || (clampedLocalNormal.dot(frontFacing*tri_normal)>0)) { btVector3 newNormal = colObj0Wrap->getWorldTransform().getBasis() * clampedLocalNormal; // cp.m_distance1 = cp.m_distance1 * newNormal.dot(cp.m_normalWorldOnB); cp.m_normalWorldOnB = newNormal; // Reproject collision point along normal. cp.m_positionWorldOnB = cp.m_positionWorldOnA - cp.m_normalWorldOnB * cp.m_distance1; cp.m_localPointB = colObj0Wrap->getWorldTransform().invXform(cp.m_positionWorldOnB); } } } } } } #ifdef DEBUG_INTERNAL_EDGE { btVector3 color(0,1,1); btDebugDrawLine(cp.getPositionWorldOnB(),cp.getPositionWorldOnB()+cp.m_normalWorldOnB*10,color); } #endif //DEBUG_INTERNAL_EDGE if (isNearEdge) { if (numConcaveEdgeHits>0) { if ((normalAdjustFlags & BT_TRIANGLE_CONCAVE_DOUBLE_SIDED)!=0) { //fix tri_normal so it pointing the same direction as the current local contact normal if (tri_normal.dot(localContactNormalOnB) < 0) { tri_normal *= -1; } cp.m_normalWorldOnB = colObj0Wrap->getWorldTransform().getBasis()*tri_normal; } else { btVector3 newNormal = tri_normal *frontFacing; //if the tri_normal is pointing opposite direction as the current local contact normal, skip it btScalar d = newNormal.dot(localContactNormalOnB) ; if (d< 0) { return; } //modify the normal to be the triangle normal (or backfacing normal) cp.m_normalWorldOnB = colObj0Wrap->getWorldTransform().getBasis() *newNormal; } // Reproject collision point along normal. cp.m_positionWorldOnB = cp.m_positionWorldOnA - cp.m_normalWorldOnB * cp.m_distance1; cp.m_localPointB = colObj0Wrap->getWorldTransform().invXform(cp.m_positionWorldOnB); } } }
bool Foam::triSurfaceMesh::isSurfaceClosed() const { // Construct pointFaces. Let's hope surface has compact point // numbering ... labelListList pointFaces; invertManyToMany(points().size(), *this, pointFaces); // Loop over all faces surrounding point. Count edges emanating from point. // Every edge should be used by two faces exactly. // To prevent doing work twice per edge only look at edges to higher // point EdgeMap<label> facesPerEdge(100); forAll(pointFaces, pointI) { const labelList& pFaces = pointFaces[pointI]; facesPerEdge.clear(); forAll(pFaces, i) { const triSurface::FaceType& f = triSurface::operator[](pFaces[i]); label fp = findIndex(f, pointI); // Something weird: if I expand the code of addFaceToEdge in both // below instances it gives a segmentation violation on some // surfaces. Compiler (4.3.2) problem? // Forward edge label nextPointI = f[f.fcIndex(fp)]; if (nextPointI > pointI) { bool okFace = addFaceToEdge ( edge(pointI, nextPointI), facesPerEdge ); if (!okFace) { return false; } } // Reverse edge label prevPointI = f[f.rcIndex(fp)]; if (prevPointI > pointI) { bool okFace = addFaceToEdge ( edge(pointI, prevPointI), facesPerEdge ); if (!okFace) { return false; } } } // Check for any edges used only once. forAllConstIter(EdgeMap<label>, facesPerEdge, iter) { if (iter() != 2) { return false; } } } return true; }
void Deck::checkEdgeState( bool force ) { int shapeMask = 0; switch (edge()) { case TopEdge: { if (_position == 0.0) { shapeMask = BottomRight; _adjacentEdge = LeftEdge; } else if (_position == 1.0) { shapeMask = BottomLeft; _adjacentEdge = RightEdge; } else { shapeMask = BottomLeft | BottomRight; _adjacentEdge = None; } break; } case RightEdge: { if (_position == 0.0) { shapeMask = BottomLeft; _adjacentEdge = TopEdge; } else if (_position == 1.0) { shapeMask = TopLeft; _adjacentEdge = BottomEdge; } else { shapeMask = BottomLeft | TopLeft; _adjacentEdge = None; } break; } case BottomEdge: { if (_position == 0.0) { shapeMask = TopLeft; _adjacentEdge = RightEdge; } else if (_position == 1.0) { shapeMask = TopRight; _adjacentEdge = LeftEdge; } else { shapeMask = TopLeft | TopRight; _adjacentEdge = None; } break; } case LeftEdge: { if (_position == 0.0) { shapeMask = TopRight; _adjacentEdge = BottomEdge; } else if (_position == 1.0) { shapeMask = BottomRight; _adjacentEdge = TopEdge; } else { shapeMask = TopRight | BottomRight; _adjacentEdge = None; } break; } default: break; } if (shapeMask != _shapeMask || force) { _shapeMask = shapeMask; applyShapeMask(); } }
// induce tail if necessary Agedge_t *edge(char *tname, Agnode_t *h) { return edge(node(agraphof(h), tname), h); }
// induce tail/head if necessary Agedge_t *edge(Agraph_t *g, char *tname, char *hname) { return edge(node(g, tname), node(g, hname)); }
/* * Decode an operator/operand type command. * Eventually we switch to an operator subroutine in ex_vops.c. * The work here is setting up a function variable to point * to the routine we want, and manipulation of the variables * wcursor and wdot, which mark the other end of the affected * area. If wdot is zero, then the current line is the other end, * and if wcursor is zero, then the first non-blank location of the * other line is implied. */ void operate(int c, int cnt) { register int i; void (*moveop)(), (*deleteop)(); void (*opf)(); bool subop = 0; char *oglobp, *ocurs; register line *addr; line *odot; static char lastFKND, lastFCHR; char d; moveop = vmove, deleteop = vdelete; wcursor = cursor; wdot = NOLINE; notecnt = 0; dir = 1; switch (c) { /* * d delete operator. */ case 'd': moveop = vdelete; deleteop = beep; break; /* * s substitute characters, like c\040, i.e. change space. */ case 's': ungetkey(' '); subop++; /* fall into ... */ /* * c Change operator. */ case 'c': if ((c == 'c' && workcmd[0] == 'C') || workcmd[0] == 'S') subop++; moveop = vchange; deleteop = beep; break; /* * ! Filter through a UNIX command. */ case '!': moveop = vfilter; deleteop = beep; break; /* * y Yank operator. Place specified text so that it * can be put back with p/P. Also yanks to named buffers. */ case 'y': moveop = vyankit; deleteop = beep; break; /* * = Reformat operator (for LISP). */ #ifdef LISPCODE case '=': forbid(!value(LISP)); /* fall into ... */ #endif /* * > Right shift operator. * < Left shift operator. */ case '<': case '>': moveop = vshftop; deleteop = beep; break; /* * r Replace character under cursor with single following * character. */ case 'r': vmacchng(1); vrep(cnt); return; default: goto nocount; } vmacchng(1); /* * Had an operator, so accept another count. * Multiply counts together. */ if (isdigit(peekkey()) && peekkey() != '0') { cnt *= vgetcnt(); Xcnt = cnt; forbid (cnt <= 0); } /* * Get next character, mapping it and saving as * part of command for repeat. */ c = map(getesc(),arrows); if (c == 0) return; if (!subop) *lastcp++ = c; nocount: opf = moveop; switch (c) { /* * b Back up a word. * B Back up a word, liberal definition. */ case 'b': case 'B': dir = -1; /* fall into ... */ /* * w Forward a word. * W Forward a word, liberal definition. */ case 'W': case 'w': wdkind = c & ' '; forbid(lfind(2, cnt, opf, 0) < 0); vmoving = 0; break; /* * E to end of following blank/nonblank word */ case 'E': wdkind = 0; goto ein; /* * e To end of following word. */ case 'e': wdkind = 1; ein: forbid(lfind(3, cnt - 1, opf, 0) < 0); vmoving = 0; break; /* * ( Back an s-expression. */ case '(': dir = -1; /* fall into... */ /* * ) Forward an s-expression. */ case ')': forbid(lfind(0, cnt, opf, (line *) 0) < 0); markDOT(); break; /* * { Back an s-expression, but don't stop on atoms. * In text mode, a paragraph. For C, a balanced set * of {}'s. */ case '{': dir = -1; /* fall into... */ /* * } Forward an s-expression, but don't stop on atoms. * In text mode, back paragraph. For C, back a balanced * set of {}'s. */ case '}': forbid(lfind(1, cnt, opf, (line *) 0) < 0); markDOT(); break; /* * % To matching () or {}. If not at ( or { scan for * first such after cursor on this line. */ case '%': vsave(); i = lmatchp((line *) 0); #ifdef TRACE if (trace) fprintf(trace, "after lmatchp in %, dot=%d, wdot=%d, dol=%d\n", lineno(dot), lineno(wdot), lineno(dol)); #endif getDOT(); forbid(!i); if (opf != vmove) if (dir > 0) wcursor++; else cursor++; else markDOT(); vmoving = 0; break; /* * [ Back to beginning of defun, i.e. an ( in column 1. * For text, back to a section macro. * For C, back to a { in column 1 (~~ beg of function.) */ case '[': dir = -1; /* fall into ... */ /* * ] Forward to next defun, i.e. a ( in column 1. * For text, forward section. * For C, forward to a } in column 1 (if delete or such) * or if a move to a { in column 1. */ case ']': if (!vglobp) forbid(getkey() != c); forbid (Xhadcnt); vsave(); i = lbrack(c, opf); getDOT(); forbid(!i); markDOT(); if (ex_ospeed > B300) hold |= HOLDWIG; break; /* * , Invert last find with f F t or T, like inverse * of ;. */ case ',': forbid (lastFKND == 0); c = isupper((int)lastFKND) ? tolower((int)lastFKND) : toupper((int)lastFKND); i = lastFCHR; if (vglobp == 0) vglobp = ""; subop++; goto nocount; /* * 0 To beginning of real line. */ case '0': wcursor = linebuf; vmoving = 0; break; /* * ; Repeat last find with f F t or T. */ case ';': forbid (lastFKND == 0); c = lastFKND; i = lastFCHR; subop++; goto nocount; /* * F Find single character before cursor in current line. * T Like F, but stops before character. */ case 'F': /* inverted find */ case 'T': dir = -1; /* fall into ... */ /* * f Find single character following cursor in current line. * t Like f, but stope before character. */ case 'f': /* find */ case 't': if (!subop) { i = getesc(); if (i == 0) return; *lastcp++ = i; } if (vglobp == 0) /* TODO: Initialized? (ck) */ lastFKND = c, lastFCHR = i; for (; cnt > 0; cnt--) forbid (find(i) == 0); vmoving = 0; switch (c) { case 'T': wcursor++; break; case 't': wcursor--; case 'f': fixup: if (moveop != vmove) wcursor++; break; } break; /* * | Find specified print column in current line. */ case '|': if (Pline == numbline) cnt += 8; vmovcol = cnt; vmoving = 1; wcursor = vfindcol(cnt); break; /* * ^ To beginning of non-white space on line. */ case '^': wcursor = vskipwh(linebuf); vmoving = 0; break; /* * $ To end of line. */ case '$': if (opf == vmove) { vmoving = 1; vmovcol = 20000; } else vmoving = 0; if (cnt > 1) { if (opf == vmove) { wcursor = 0; cnt--; } else wcursor = linebuf; /* This is wrong at EOF */ wdot = dot + cnt; break; } if (linebuf[0]) { wcursor = strend(linebuf) - 1; goto fixup; } wcursor = linebuf; break; /* * h Back a character. * ^H Back a character. */ case 'h': case CTRL('h'): dir = -1; /* fall into ... */ /* * space Forward a character. */ case 'l': case ' ': forbid (margin() || (opf == vmove && edge())); while (cnt > 0 && !margin()) wcursor += dir, cnt--; if ((margin() && opf == vmove) || wcursor < linebuf) wcursor -= dir; vmoving = 0; break; /* * D Delete to end of line, short for d$. */ case 'D': cnt = INF; goto deleteit; /* * X Delete character before cursor. */ case 'X': dir = -1; /* fall into ... */ deleteit: /* * x Delete character at cursor, leaving cursor where it is. */ case 'x': if (margin()) goto errlab; vmacchng(1); while (cnt > 0 && !margin()) wcursor += dir, cnt--; opf = deleteop; vmoving = 0; break; default: /* * Stuttered operators are equivalent to the operator on * a line, thus turn dd into d_. */ if (opf == vmove || c != workcmd[0]) { errlab: beep(); vmacp = 0; return; } /* fall into ... */ /* * _ Target for a line or group of lines. * Stuttering is more convenient; this is mostly * for aesthetics. */ case '_': wdot = dot + cnt - 1; vmoving = 0; wcursor = 0; break; /* * H To first, home line on screen. * Count is for count'th line rather than first. */ case 'H': wdot = (dot - vcline) + cnt - 1; if (opf == vmove) markit(wdot); vmoving = 0; wcursor = 0; break; /* * - Backwards lines, to first non-white character. */ case '-': wdot = dot - cnt; vmoving = 0; wcursor = 0; break; /* * ^P To previous line same column. Ridiculous on the * console of the VAX since it puts console in LSI mode. */ case 'k': case CTRL('p'): wdot = dot - cnt; if (vmoving == 0) vmoving = 1, vmovcol = column(cursor); wcursor = 0; break; /* * L To last line on screen, or count'th line from the * bottom. */ case 'L': wdot = dot + vcnt - vcline - cnt; if (opf == vmove) markit(wdot); vmoving = 0; wcursor = 0; break; /* * M To the middle of the screen. */ case 'M': wdot = dot + ((vcnt + 1) / 2) - vcline - 1; if (opf == vmove) markit(wdot); vmoving = 0; wcursor = 0; break; /* * + Forward line, to first non-white. * * CR Convenient synonym for +. */ case '+': case CR: wdot = dot + cnt; vmoving = 0; wcursor = 0; break; /* * ^N To next line, same column if possible. * * LF Linefeed is a convenient synonym for ^N. */ case CTRL('n'): case 'j': case NL: wdot = dot + cnt; if (vmoving == 0) vmoving = 1, vmovcol = column(cursor); wcursor = 0; break; /* * n Search to next match of current pattern. */ case 'n': vglobp = vscandir; c = *vglobp++; goto nocount; /* * N Like n but in reverse direction. */ case 'N': vglobp = vscandir[0] == '/' ? "?" : "/"; c = *vglobp++; goto nocount; /* * ' Return to line specified by following mark, * first white position on line. * * ` Return to marked line at remembered column. */ case '\'': case '`': d = c; c = getesc(); if (c == 0) return; c = markreg(c); forbid (c == 0); wdot = getmark(c); forbid (wdot == NOLINE); forbid (Xhadcnt); vmoving = 0; wcursor = d == '`' ? ncols[c - 'a'] : 0; if (opf == vmove && (wdot != dot || (d == '`' && wcursor != cursor))) markDOT(); if (wcursor) { vsave(); ex_getline(*wdot); if (wcursor > strend(linebuf)) wcursor = 0; getDOT(); } if (ex_ospeed > B300) hold |= HOLDWIG; break; /* * G Goto count'th line, or last line if no count * given. */ case 'G': if (!Xhadcnt) cnt = lineDOL(); wdot = zero + cnt; forbid (wdot < one || wdot > dol); if (opf == vmove) markit(wdot); vmoving = 0; wcursor = 0; break; /* * / Scan forward for following re. * ? Scan backward for following re. */ case '/': case '?': forbid (Xhadcnt); vsave(); ocurs = cursor; odot = dot; wcursor = 0; if (readecho(c)) return; if (!vglobp) vscandir[0] = genbuf[0]; oglobp = globp; CP(vutmp, genbuf); globp = vutmp; d = peekc; fromsemi: ungetchar(0); fixech(); CATCH #ifndef CBREAK /* * Lose typeahead (ick). */ vcook(); #endif addr = address(cursor); #ifndef CBREAK vraw(); #endif ONERR #ifndef CBREAK vraw(); #endif slerr: globp = oglobp; dot = odot; cursor = ocurs; ungetchar(d); splitw = 0; vclean(); vjumpto(dot, ocurs, 0); return; ENDCATCH if (globp == 0) globp = ""; else if (peekc) --globp; if (*globp == ';') { /* /foo/;/bar/ */ globp++; dot = addr; cursor = loc1; goto fromsemi; } dot = odot; ungetchar(d); c = 0; if (*globp == 'z') globp++, c = '\n'; if (any(*globp, "^+-.")) c = *globp++; i = 0; while (isdigit((int)*globp)) i = i * 10 + *globp++ - '0'; if (any(*globp, "^+-.")) c = *globp++; if (*globp) { /* random junk after the pattern */ beep(); goto slerr; } globp = oglobp; splitw = 0; vmoving = 0; wcursor = loc1; if (i != 0) vsetsiz(i); if (opf == vmove) { if (state == ONEOPEN || state == HARDOPEN) outline = destline = WBOT; if (addr != dot || loc1 != cursor) markDOT(); if (loc1 > linebuf && *loc1 == 0) loc1--; if (c) vjumpto(addr, loc1, c); else { vmoving = 0; if (loc1) { vmoving++; vmovcol = column(loc1); } getDOT(); if (state == CRTOPEN && addr != dot) vup1(); vupdown(addr - dot, NOSTR); } return; } lastcp[-1] = 'n'; getDOT(); wdot = addr; break; } /* * Apply. */ if (vreg && wdot == 0) wdot = dot; (*opf)(c); wdot = NOLINE; }
void Graph<T1,T2>::add_edge(T1 source, T1 target, T2 weight) { Edge<T1,T2> edge(source,target,weight); adjacencyList_[source].push_back(edge); }
void init_game (void) { int count,tmprnd,special_rand; game_over = FALSE; game_blackhole = FALSE; game_bigspace = FALSE; end_count = 150; nbr_asteroids = 0; randomize(); input_enabled = TRUE; randomize(); special_rand = random(20); add_list(ship,&start); if (game_shieldduration > 3) add_list(init_objekt(OT_SHIPSHIELD,ship->current.x,ship->current.y,ship->angle,0,DT_POLY,game_shieldduration, CLR_WHITE,shielddata,4),effekts); // insert sats if (special_rand == 0) // sattelite madness { tmprnd = 10; insert_message (1600,0,"sattelite madness"); } else { tmprnd = game_level-5+random(7); // number of sats if (tmprnd > 4) tmprnd = 4; } if (tmprnd > 0) for (count = 0; count < tmprnd; count++) { add_list(init_objekt(OT_SAT,random(2000),random(1200)-600,random(360),3,DT_POLY,0,CLR_CYAN,satdata,8),enemies); nbr_asteroids++; } if (special_rand == 2) { insert_message (1600,0,"Go Polygunzz"); for (count = 0; count < 4; count++) add_list(init_objekt(OT_ENEMY1,edge(),random(2000),0,3,DT_POLY,0,CLR_BLUE,enemy1data,5),enemies); for (count = 0; count < 4; count++) add_list(init_objekt(OT_ENEMY2,random(2000),edge(),0,4,DT_POLY,0,CLR_CYAN,enemy2data,7),enemies); nbr_asteroids+=8; } if (special_rand == 3) { insert_message (1600,0,"Asteroid factory"); for (count=0; count < 4; count++) add_list(init_objekt(OT_MYSTSHIP,edge(),random(2000),random(360),random(8)+2,DT_POLY,0,CLR_BROWN,mysterydata,8),enemies); nbr_asteroids+=4; } if (special_rand > 4 || special_rand == 1 || special_rand == 4) // no special level except black hole zone { // inserts level+1 number of asteroids in llist for (count = 0; count < game_level+1; count++) { randomize_asteroids (asteroiddata , 10, 100); add_list(init_objekt(OT_BIGASTER,random(1200)-600,random(1200)-600,random(360),random(8)+2,DT_POLY,0,CLR_GREEN,asteroiddata,10),asteroids); nbr_asteroids++; } } if (special_rand == 1) { game_blackhole = TRUE; insert_message (1600,0,"black hole zone"); } if (special_rand == 4) { game_bigspace = TRUE; insert_message (1600,0,"wow bigspace"); } // insert start message insert_message (800,0, "level %02d",game_level); }
void game (HDC hdc) { int zoom, count; POINTL at; if (game_duration != 0) // zooming intro of the game { zoom = game_duration / 2; if (zoom == 0) zoom = 1; process_list_zoom(hdc,zoom); game_duration--; } else { process_list(hdc); if (random(2500) == 0 && !game_over && nbr_asteroids>5) // yep the mystery ship arrives { add_list(init_objekt(OT_MYSTSHIP,edge(),edge(),random(360),random(8)+4,DT_POLY,0,CLR_BROWN,mysterydata,8),enemies); nbr_asteroids++; } if (random(1000) < game_level && !game_over && nbr_asteroids > 5) // enemy1 has arrived { add_list(init_objekt(OT_ENEMY1,random(2000),edge(),0,4,DT_POLY,0,CLR_BLUE,enemy1data,5),enemies); nbr_asteroids++; } if (random(1500) == 0 && !game_over && nbr_asteroids > 5) // enemy2 has arrived { add_list(init_objekt(OT_ENEMY2,edge(),random(2000),0,4,DT_POLY,0,CLR_CYAN,enemy2data,7),enemies); nbr_asteroids++; } if (game_shieldduration > 0) game_shieldduration--; if (game_shieldduration < 0) game_shieldduration = 0; if (game_over) { input_enabled = FALSE; // game over... the end if (end_count == 150) { insert_message (1200,0, "game over"); insert_message (800,0, "score %05d",game_score); WinPostMsg(hwndClient,DM_CHECKSCORE,(MPARAM)game_score,(MPARAM)0); // check for hiscore } if (end_count == 0) { //terminate all free_all(); game_status = GAME_INTRO; game_duration = 200; WinInvalidateRect(hwndClient, NULL, TRUE); return; } end_count--; } if (nbr_asteroids == 0) // end of game { // do some end stuff if (input_enabled) { for (count = 0; count < 10; count++) { at.x = random(2000); at.y = random(2000); insert_explosion(at,10); } insert_message (1200,0, "level %02d clear", game_level); insert_message (800,0, "score %05d",game_score); } input_enabled = FALSE; if ((llist_items == 1) || (llist_items == 2 && game_shieldduration != 0)) // real end of game { delete_list(ship,&start); if (llist_items != 0) free_all(); // frees the shield ship->current.x = 1000; ship->current.y = 1000; ship->thrust_speed = 0; game_level++; init_game(); game_duration = 25; WinInvalidateRect(hwndClient, NULL, TRUE); } } } }
/** * Добавляет узел в граф и строит связааные с ним зависимости(дуги) * Исходим из предположения, что в акутальных данных содержаться * детерминированныее данные, в том числе и скаляры-массивы. */ void Graph::addNode(const Node &_arg_) { //cout<<"node added"<<endl; stringSet local; // local edge vars stringSet other; // other vars to arg Node arg = _arg_; // will be changed arg.setActual(createActual(arg. getIn()), createActual(arg. getOut())); // check for return in statement bool containReturn = false; /* { cout<<"Node #"<<arg. getNumber()<<" statement: "; arg.getAction().print(cout, ""); cout<<"Node #"<<arg. getNumber()<<" (in):"<<arg.getActualIn()<<endl; cout<<"Node #"<<arg. getNumber()<<" (out):"<<arg.getActualOut()<<endl; } */ if (checkStatement(arg.getAction(), false, false) == -2) containReturn = true; /* * Если в предложении есть возврат, то это зависимость по управлению * и необходимо, что бы все действия были завершены до действия возврата * это позволит сохранить семантику исполнения программы. */ nodes_num++; // first phase stringSet foreverOut = arg. getActualOut(); // arg's out stringSet readOut = arg. getActualOut(); // current read for consistency stringSet readIn = arg. getActualIn(); // current read for in TNodeSet::iterator beg = nodes. begin(); TNodeSet::iterator end = nodes. end(); unsigned long layer = init_layer - 1; bool findDep = false; while (beg != end) { Node cur = (*--end); // forward dep if (isForwardDepend(readIn, cur. getActualOut())) { findDep = true; // form local createForwardTransition(cur. getActualOut(), readIn, local, other); //cout<<"Forward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<":"<<local<<endl; // cur. actual(), readIn() - in // local, other, actual - out readIn = other; other. clear(); // для использования в ЛЮБОЙ следующий раз } else { // backward dep if (isBackwardDepend(foreverOut, cur. getActualIn())) { //cout<<"Backward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<endl; findDep = true; } } // out dep if (isOutwardDepend(foreverOut, cur. getActualOut())) { findDep = true; if (arg.getNumber() == 3) { //cout<<"Extended info"<<endl; //cout<<"Forever out : "<<foreverOut<<endl; //cout<<"cur out Node #"<<cur. getNumber()<<": "<<cur.getActualOut()<<endl; //cout<<"readOut: "<<readOut<<endl; //cout<<"Local: "<<local<<endl; //cout<<"Node #"<<arg. getNumber()<<" (in):"<<arg.getActualIn()<<endl; //cout<<"Node #"<<arg. getNumber()<<" (out):"<<arg.getActualOut()<<endl; } createOutwardTransition(cur. getActualOut(), readOut, local, other); //cout<<"Outward :"<<cur. getNumber()<<"->"<<arg. getNumber()<<":"<<local<<endl; // cur. actual(), arg. getIn() - in // local, other, actual - inout readOut = other; other. clear(); } if (findDep) { // create edge Edge edge(arg. getNumber(), cur. getNumber(), packArrays(local)); //edge. print(cout); // cout if (!local. empty()) ; //cout<<"Transit :"<<local<<endl; addEdge(edge); local. clear(); arg.addIn(edge. getNumber()); (*end). addOut(edge. getNumber()); if (cur. getLayer() > layer) layer = cur. getLayer(); findDep = false; } else { if (containReturn) { // create empty edge Edge edge(arg. getNumber(), cur. getNumber(), stringSet()); addEdge(edge); arg.addIn(edge. getNumber()); (*end). addOut(edge. getNumber()); if (cur. getLayer() > layer) layer = cur. getLayer(); } // else - do nothing } } // insert node arg. setLayer(layer + 1); nodes. push_back(arg); }
PixelRegion PixelRegion::localCut(Side side, int p) { if (p < 1) { return PixelRegion({ 0, 0 }, { 0, 0 }); } else return globalCut(side, edge(side) - edgeDirectionSign(side) * p); }
std::pair<typename DIRECTED_GRAPH::edge_descriptor, bool> edge(typename DIRECTED_GRAPH::vertex_descriptor u, typename DIRECTED_GRAPH::vertex_descriptor v, DIRECTED_GRAPH const& g) { return edge(u, v, g.impl()); }
void HistogramStatistics::computeInteractor() { GlQuantitativeAxis *histoXAxis = histoView->getDetailedHistogram()->getXAxis(); GlQuantitativeAxis *histoYAxis = histoView->getDetailedHistogram()->getYAxis(); if (histoYAxis == nullptr) { return; } Graph *graph = histoView->graph(); string selectedProperty(histoView->getDetailedHistogram()->getPropertyName()); double sampleStep = histoStatsConfigWidget->getSampleStep(); graphPropertyValueSet.clear(); densityEstimationCurvePoints.clear(); propertyMean = 0; propertyStandardDeviation = 0; cleanupAxis(); string propertyType(graph->getProperty(selectedProperty)->getTypename()); double min, max; if (propertyType == "double") { if (histoView->getDataLocation() == NODE) { min = graph->getProperty<DoubleProperty>(selectedProperty)->getNodeMin(); max = graph->getProperty<DoubleProperty>(selectedProperty)->getNodeMax(); } else { min = graph->getProperty<DoubleProperty>(selectedProperty)->getEdgeMin(); max = graph->getProperty<DoubleProperty>(selectedProperty)->getEdgeMax(); } } else { if (histoView->getDataLocation() == NODE) { min = graph->getProperty<IntegerProperty>(selectedProperty)->getNodeMin(); max = graph->getProperty<IntegerProperty>(selectedProperty)->getNodeMax(); } else { min = graph->getProperty<IntegerProperty>(selectedProperty)->getEdgeMin(); max = graph->getProperty<IntegerProperty>(selectedProperty)->getEdgeMax(); } } unsigned int nbElements = 0; if (histoView->getDataLocation() == NODE) { nbElements = graph->numberOfNodes(); for (auto n : graph->nodes()) { double nodeVal; if (propertyType == "double") { nodeVal = graph->getProperty<DoubleProperty>(selectedProperty)->getNodeValue(n); } else { nodeVal = graph->getProperty<IntegerProperty>(selectedProperty)->getNodeValue(n); } graphPropertyValueSet[n.id] = nodeVal; propertyMean += nodeVal; } } else { nbElements = graph->numberOfEdges(); for (auto e : graph->edges()) { double edgeVal; if (propertyType == "double") { edgeVal = graph->getProperty<DoubleProperty>(selectedProperty)->getEdgeValue(e); } else { edgeVal = graph->getProperty<IntegerProperty>(selectedProperty)->getEdgeValue(e); } graphPropertyValueSet[e.id] = edgeVal; propertyMean += edgeVal; } } propertyMean /= (nbElements); for (auto it = graphPropertyValueSet.begin(); it != graphPropertyValueSet.end(); ++it) { propertyStandardDeviation += square(it->second - propertyMean); } propertyStandardDeviation = sqrt(propertyStandardDeviation / (nbElements - 1)); histoStatsConfigWidget->setMinMaxMeanAndSd(min, max, propertyMean, propertyStandardDeviation); if (histoStatsConfigWidget->densityEstimation()) { double bandwidth = histoStatsConfigWidget->getBandwidth(); vector<double> estimatedDensity; float maxDensityValue = 0.; KernelFunction *kf = kernelFunctionsMap[histoStatsConfigWidget->getKernelFunctionName()]; for (double val = min; val <= max; val += sampleStep) { float fx = 0; for (auto it = graphPropertyValueSet.begin(); it != graphPropertyValueSet.end(); ++it) { fx += float((*kf)((val - (it->second)) / (bandwidth / 2.))); } fx *= (1.f / float(graphPropertyValueSet.size() * (bandwidth / 2.))); estimatedDensity.push_back(fx); if (fx > maxDensityValue) { maxDensityValue = fx; } } double val; unsigned int i; for (val = min, i = 0; val <= max; val += sampleStep, ++i) { float x = histoXAxis->getAxisPointCoordForValue(val).getX(); float y = histoYAxis ->getAxisPointCoordForValue( (estimatedDensity[i] * (histoView->getDetailedHistogram()->getMaxBinSize())) / maxDensityValue) .getY(); densityEstimationCurvePoints.push_back(Coord(x, y, 0)); } densityAxis = new GlQuantitativeAxis( "density", Coord(histoXAxis->getAxisBaseCoord().getX() + histoXAxis->getAxisLength(), 0, 0), histoYAxis->getAxisLength(), GlAxis::VERTICAL_AXIS, Color(255, 0, 0), true); densityAxis->setAxisParameters(0.0, double(maxDensityValue), 15, GlAxis::RIGHT_OR_ABOVE, true); densityAxis->updateAxis(); densityAxis->addCaption(GlAxis::LEFT, densityAxis->getSpaceBetweenAxisGrads(), false); } if (histoStatsConfigWidget->displayMeanAndStandardDeviation()) { float axisExtension = 2 * histoXAxis->getAxisGradsWidth(); float y = histoXAxis->getAxisBaseCoord().getY() - axisExtension; float axisLength = histoYAxis->getAxisLength() + axisExtension; float captionHeight = histoXAxis->getAxisGradsWidth(); float x = histoXAxis->getAxisPointCoordForValue(propertyMean).getX(); meanAxis = new GlAxis("m", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); meanAxis->addCaption(GlAxis::LEFT, captionHeight, false); x = histoXAxis->getAxisPointCoordForValue(propertyMean + propertyStandardDeviation).getX(); standardDeviationPosAxis = new GlAxis("+sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviationPosAxis->addCaption(GlAxis::LEFT, captionHeight, false); x = histoXAxis->getAxisPointCoordForValue(propertyMean - propertyStandardDeviation).getX(); standardDeviationNegAxis = new GlAxis("-sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviationNegAxis->addCaption(GlAxis::LEFT, captionHeight, false); if (propertyMean - 2 * propertyStandardDeviation > min) { x = histoXAxis->getAxisPointCoordForValue(propertyMean + 2 * propertyStandardDeviation) .getX(); standardDeviation2PosAxis = new GlAxis("+2sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviation2PosAxis->addCaption(GlAxis::LEFT, captionHeight, false); x = histoXAxis->getAxisPointCoordForValue(propertyMean - 2 * propertyStandardDeviation) .getX(); standardDeviation2NegAxis = new GlAxis("-2sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviation2NegAxis->addCaption(GlAxis::LEFT, captionHeight, false); } else { standardDeviation2NegAxis = nullptr; standardDeviation2PosAxis = nullptr; } if (propertyMean - 3 * propertyStandardDeviation > min) { x = histoXAxis->getAxisPointCoordForValue(propertyMean + 3 * propertyStandardDeviation) .getX(); standardDeviation3PosAxis = new GlAxis("+3sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviation3PosAxis->addCaption(GlAxis::LEFT, captionHeight, false); x = histoXAxis->getAxisPointCoordForValue(propertyMean - 3 * propertyStandardDeviation) .getX(); standardDeviation3NegAxis = new GlAxis("-3sd", Coord(x, y, 0), axisLength, GlAxis::VERTICAL_AXIS, Color(255, 0, 0)); standardDeviation3NegAxis->addCaption(GlAxis::LEFT, captionHeight, false); } else { standardDeviation3NegAxis = nullptr; standardDeviation3PosAxis = nullptr; } if (histoStatsConfigWidget->nodesSelection()) { Observable::holdObservers(); BooleanProperty *viewSelection = graph->getProperty<BooleanProperty>("viewSelection"); viewSelection->setAllNodeValue(false); viewSelection->setAllEdgeValue(false); double lowerBound = histoStatsConfigWidget->getSelectionLowerBound(); double upperBound = histoStatsConfigWidget->getSelectionUpperBound(); map<unsigned int, double>::iterator pos = find_if( graphPropertyValueSet.begin(), graphPropertyValueSet.end(), compose_fn(logical_and<bool>(), map_value_greater_equal<unsigned int, double>(lowerBound), map_value_less_equal<unsigned int, double>(upperBound))); while (pos != graphPropertyValueSet.end()) { if (histoView->getDataLocation() == EDGE) { viewSelection->setNodeValue(node(pos->first), true); } else { viewSelection->setEdgeValue(edge(pos->first), true); } pos = find_if(++pos, graphPropertyValueSet.end(), compose_fn(logical_and<bool>(), map_value_greater_equal<unsigned int, double>(lowerBound), map_value_less_equal<unsigned int, double>(upperBound))); } Observable::unholdObservers(); } } }
void VARIABLE_IS_NOT_USED remove_edge(int i) { remove_edgev(edge(i)); }
virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex) { //skip self-collisions if ((m_partIdA == partId) && (m_triangleIndexA == triangleIndex)) return; //skip duplicates (disabled for now) //if ((m_partIdA <= partId) && (m_triangleIndexA <= triangleIndex)) // return; //search for shared vertices and edges int numshared = 0; int sharedVertsA[3]={-1,-1,-1}; int sharedVertsB[3]={-1,-1,-1}; ///skip degenerate triangles btScalar crossBSqr = ((triangle[1]-triangle[0]).cross(triangle[2]-triangle[0])).length2(); if (crossBSqr < m_triangleInfoMap->m_equalVertexThreshold) return; btScalar crossASqr = ((m_triangleVerticesA[1]-m_triangleVerticesA[0]).cross(m_triangleVerticesA[2]-m_triangleVerticesA[0])).length2(); ///skip degenerate triangles if (crossASqr< m_triangleInfoMap->m_equalVertexThreshold) return; #if 0 printf("triangle A[0] = (%f,%f,%f)\ntriangle A[1] = (%f,%f,%f)\ntriangle A[2] = (%f,%f,%f)\n", m_triangleVerticesA[0].getX(),m_triangleVerticesA[0].getY(),m_triangleVerticesA[0].getZ(), m_triangleVerticesA[1].getX(),m_triangleVerticesA[1].getY(),m_triangleVerticesA[1].getZ(), m_triangleVerticesA[2].getX(),m_triangleVerticesA[2].getY(),m_triangleVerticesA[2].getZ()); printf("partId=%d, triangleIndex=%d\n",partId,triangleIndex); printf("triangle B[0] = (%f,%f,%f)\ntriangle B[1] = (%f,%f,%f)\ntriangle B[2] = (%f,%f,%f)\n", triangle[0].getX(),triangle[0].getY(),triangle[0].getZ(), triangle[1].getX(),triangle[1].getY(),triangle[1].getZ(), triangle[2].getX(),triangle[2].getY(),triangle[2].getZ()); #endif for (int i=0;i<3;i++) { for (int j=0;j<3;j++) { if ( (m_triangleVerticesA[i]-triangle[j]).length2() < m_triangleInfoMap->m_equalVertexThreshold) { sharedVertsA[numshared] = i; sharedVertsB[numshared] = j; numshared++; ///degenerate case if(numshared >= 3) return; } } ///degenerate case if(numshared >= 3) return; } switch (numshared) { case 0: { break; } case 1: { //shared vertex break; } case 2: { //shared edge //we need to make sure the edge is in the order V2V0 and not V0V2 so that the signs are correct if (sharedVertsA[0] == 0 && sharedVertsA[1] == 2) { sharedVertsA[0] = 2; sharedVertsA[1] = 0; int tmp = sharedVertsB[1]; sharedVertsB[1] = sharedVertsB[0]; sharedVertsB[0] = tmp; } int hash = btGetHash(m_partIdA,m_triangleIndexA); btTriangleInfo* info = m_triangleInfoMap->find(hash); if (!info) { btTriangleInfo tmp; m_triangleInfoMap->insert(hash,tmp); info = m_triangleInfoMap->find(hash); } int sumvertsA = sharedVertsA[0]+sharedVertsA[1]; int otherIndexA = 3-sumvertsA; btVector3 edge(m_triangleVerticesA[sharedVertsA[1]]-m_triangleVerticesA[sharedVertsA[0]]); btTriangleShape tA(m_triangleVerticesA[0],m_triangleVerticesA[1],m_triangleVerticesA[2]); int otherIndexB = 3-(sharedVertsB[0]+sharedVertsB[1]); btTriangleShape tB(triangle[sharedVertsB[1]],triangle[sharedVertsB[0]],triangle[otherIndexB]); //btTriangleShape tB(triangle[0],triangle[1],triangle[2]); btVector3 normalA; btVector3 normalB; tA.calcNormal(normalA); tB.calcNormal(normalB); edge.normalize(); btVector3 edgeCrossA = edge.cross(normalA).normalize(); { btVector3 tmp = m_triangleVerticesA[otherIndexA]-m_triangleVerticesA[sharedVertsA[0]]; if (edgeCrossA.dot(tmp) < 0) { edgeCrossA*=-1; } } btVector3 edgeCrossB = edge.cross(normalB).normalize(); { btVector3 tmp = triangle[otherIndexB]-triangle[sharedVertsB[0]]; if (edgeCrossB.dot(tmp) < 0) { edgeCrossB*=-1; } } btScalar angle2 = 0; btScalar ang4 = 0.f; btVector3 calculatedEdge = edgeCrossA.cross(edgeCrossB); btScalar len2 = calculatedEdge.length2(); btScalar correctedAngle(0); btVector3 calculatedNormalB = normalA; bool isConvex = false; if (len2<m_triangleInfoMap->m_planarEpsilon) { angle2 = 0.f; ang4 = 0.f; } else { calculatedEdge.normalize(); btVector3 calculatedNormalA = calculatedEdge.cross(edgeCrossA); calculatedNormalA.normalize(); angle2 = btGetAngle(calculatedNormalA,edgeCrossA,edgeCrossB); ang4 = SIMD_PI-angle2; btScalar dotA = normalA.dot(edgeCrossB); ///@todo: check if we need some epsilon, due to floating point imprecision isConvex = (dotA<0.); correctedAngle = isConvex ? ang4 : -ang4; btQuaternion orn2(calculatedEdge,-correctedAngle); calculatedNormalB = btMatrix3x3(orn2)*normalA; } //alternatively use //btVector3 calculatedNormalB2 = quatRotate(orn,normalA); switch (sumvertsA) { case 1: { btVector3 edge = m_triangleVerticesA[0]-m_triangleVerticesA[1]; btQuaternion orn(edge,-correctedAngle); btVector3 computedNormalB = quatRotate(orn,normalA); btScalar bla = computedNormalB.dot(normalB); if (bla<0) { computedNormalB*=-1; info->m_flags |= TRI_INFO_V0V1_SWAP_NORMALB; } #ifdef DEBUG_INTERNAL_EDGE if ((computedNormalB-normalB).length()>0.0001) { printf("warning: normals not identical\n"); } #endif//DEBUG_INTERNAL_EDGE info->m_edgeV0V1Angle = -correctedAngle; if (isConvex) info->m_flags |= TRI_INFO_V0V1_CONVEX; break; } case 2: { btVector3 edge = m_triangleVerticesA[2]-m_triangleVerticesA[0]; btQuaternion orn(edge,-correctedAngle); btVector3 computedNormalB = quatRotate(orn,normalA); if (computedNormalB.dot(normalB)<0) { computedNormalB*=-1; info->m_flags |= TRI_INFO_V2V0_SWAP_NORMALB; } #ifdef DEBUG_INTERNAL_EDGE if ((computedNormalB-normalB).length()>0.0001) { printf("warning: normals not identical\n"); } #endif //DEBUG_INTERNAL_EDGE info->m_edgeV2V0Angle = -correctedAngle; if (isConvex) info->m_flags |= TRI_INFO_V2V0_CONVEX; break; } case 3: { btVector3 edge = m_triangleVerticesA[1]-m_triangleVerticesA[2]; btQuaternion orn(edge,-correctedAngle); btVector3 computedNormalB = quatRotate(orn,normalA); if (computedNormalB.dot(normalB)<0) { info->m_flags |= TRI_INFO_V1V2_SWAP_NORMALB; computedNormalB*=-1; } #ifdef DEBUG_INTERNAL_EDGE if ((computedNormalB-normalB).length()>0.0001) { printf("warning: normals not identical\n"); } #endif //DEBUG_INTERNAL_EDGE info->m_edgeV1V2Angle = -correctedAngle; if (isConvex) info->m_flags |= TRI_INFO_V1V2_CONVEX; break; } } break; } default: { // printf("warning: duplicate triangle\n"); } } }
pair<NFAEdge, bool> NFABuilderImpl::addEdge(NFAVertex u, NFAVertex v) { // assert that the edge doesn't already exist assert(edge(u, v, *graph).second == false); return add_edge(u, v, *graph); }
void Tri2dFCBlockSolver::gradient(const int& nqp, const double* p, double* px) { for (int n=0; n<nNode*nqp*2; n++) px[n] = 0.; if (order == 2){ //Green-Gauss gradients int n1,n2,k1,k2,k1x,k1y,k2x,k2y,m=0; double Ax,Ay,a,third=1./3.; for (int n=0; n<nEdge; n++){ //interior edges n1 = edge(n,0); n2 = edge(n,1); Ax = area(n,0); Ay = area(n,1); k1 = n1*nqp; k2 = n2*nqp; k1x = n1*nqp*2; k1y = k1x+nqp; k2x = n2*nqp*2; k2y = k2x+nqp; for (int k=0; k<nqp; k++){ a = p[k1+k]+p[k2+k]; px[k1x+k] += Ax*a; px[k1y+k] += Ay*a; px[k2x+k] -= Ax*a; px[k2y+k] -= Ay*a; }} for (int n=nEdge-nEdgeBd; n<nEdge; n++){ //boundary edges n1 = edge(n,0); n2 = edge(n,1); Ax = areaBd(m ,0); Ay = areaBd(m++,1); k1 = n1*nqp; k2 = n2*nqp; k1x = n1*nqp*2; k1y = k1x+nqp; k2x = n2*nqp*2; k2y = k2x+nqp; for (int k=0; k<nqp; k++){ a =(5.*p[k1+k]+p[k2+k])*third; px[k1x+k] += Ax*a; px[k1y+k] += Ay*a; a =(p[k1+k]+5.*p[k2+k])*third; px[k2x+k] += Ax*a; px[k2y+k] += Ay*a; }} for (int n=0; n<nNode; n++){ //normalize gradients a = .5/v(n); k1 = n*nqp*2; for (int k=0; k<nqp*2; k++) px[k1+k] *= a; }} else if (order == 3){ //FEM gradients int k1x,k1y,k2,k3; double dx,dy; for (int n=0; n<nNode; n++){ k1x = n*nqp*2; k1y = k1x+nqp; for(int i=psp2(n); i<psp2(n+1); i++){ k2 = psp1(i)*nqp; dx = gx(i,0); dy = gx(i,1); for (int k=0; k<nqp; k++){ k3 = k2+k; px[k1x+k] += p[k3]*dx; px[k1y+k] += p[k3]*dy; }}}} }
bool NFABuilderImpl::hasEdge(Position startPos, Position endPos) const { return edge(getVertex(startPos), getVertex(endPos), *graph).second; }
explicit graph(double timeout_sec) : rpc_server(timeout_sec) { Impl* impl = static_cast<Impl*>(this); rpc_server::add<std::string(std::string)>("get_config", jubatus::util::lang::bind( &Impl::get_config, impl, jubatus::util::lang::_1)); rpc_server::add<std::string(std::string)>("create_node", jubatus::util::lang::bind( &Impl::create_node, impl, jubatus::util::lang::_1)); rpc_server::add<bool(std::string, std::string)>("remove_node", jubatus::util::lang::bind(&Impl::remove_node, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, std::string, std::map<std::string, std::string>)>("update_node", jubatus::util::lang::bind(&Impl::update_node, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3)); rpc_server::add<uint64_t(std::string, std::string, edge)>("create_edge", jubatus::util::lang::bind(&Impl::create_edge, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3)); rpc_server::add<bool(std::string, std::string, uint64_t, edge)>( "update_edge", jubatus::util::lang::bind(&Impl::update_edge, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3, jubatus::util::lang::_4)); rpc_server::add<bool(std::string, std::string, uint64_t)>("remove_edge", jubatus::util::lang::bind(&Impl::remove_edge, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3)); rpc_server::add<double(std::string, std::string, int32_t, jubatus::core::graph::preset_query)>("get_centrality", jubatus::util::lang::bind( &Impl::get_centrality, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3, jubatus::util::lang::_4)); rpc_server::add<bool(std::string, jubatus::core::graph::preset_query)>( "add_centrality_query", jubatus::util::lang::bind(&Impl::add_centrality_query, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, jubatus::core::graph::preset_query)>( "add_shortest_path_query", jubatus::util::lang::bind( &Impl::add_shortest_path_query, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, jubatus::core::graph::preset_query)>( "remove_centrality_query", jubatus::util::lang::bind( &Impl::remove_centrality_query, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, jubatus::core::graph::preset_query)>( "remove_shortest_path_query", jubatus::util::lang::bind( &Impl::remove_shortest_path_query, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<std::vector<std::string>(std::string, shortest_path_query)>( "get_shortest_path", jubatus::util::lang::bind(&Impl::get_shortest_path, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string)>("update_index", jubatus::util::lang::bind( &Impl::update_index, impl, jubatus::util::lang::_1)); rpc_server::add<bool(std::string)>("clear", jubatus::util::lang::bind(&Impl::clear, impl, jubatus::util::lang::_1)); rpc_server::add<jubatus::core::graph::node_info(std::string, std::string)>( "get_node", jubatus::util::lang::bind(&Impl::get_node, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<edge(std::string, std::string, uint64_t)>("get_edge", jubatus::util::lang::bind(&Impl::get_edge, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3)); rpc_server::add<bool(std::string, std::string)>("save", jubatus::util::lang::bind( &Impl::save, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, std::string)>("load", jubatus::util::lang::bind( &Impl::load, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<std::map<std::string, std::map<std::string, std::string> >( std::string)>("get_status", jubatus::util::lang::bind(&Impl::get_status, impl, jubatus::util::lang::_1)); rpc_server::add<bool(std::string, std::string)>("create_node_here", jubatus::util::lang::bind(&Impl::create_node_here, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, std::string)>("remove_global_node", jubatus::util::lang::bind(&Impl::remove_global_node, impl, jubatus::util::lang::_1, jubatus::util::lang::_2)); rpc_server::add<bool(std::string, uint64_t, edge)>("create_edge_here", jubatus::util::lang::bind(&Impl::create_edge_here, impl, jubatus::util::lang::_1, jubatus::util::lang::_2, jubatus::util::lang::_3)); }
void add_edge(int u, int v, int uv, int vu = 0) { e.push_back(edge(v, uv, head[u])); head[u] = ecnt++; e.push_back(edge(u, vu, head[v])); head[v] = ecnt++; }
int main() { //assert(freopen("input.txt", "r", stdin)); //assert(freopen("output.txt", "w", stdout)); //std::ios::sync_with_stdio(0); //std::cin.tie(0); int n, m; scanf("%d %d", &n, &m); for (int i = 1; i <= m; ++i) { int u, v, d; scanf("%d %d %d", &u, &v, &d); ed[u].push_back(edge(v, d)); ed[v].push_back(edge(u, d)); } std::priority_queue<edge> q; memset(dist, -1, sizeof(dist)); dist[1] = 0; q.push(edge(1, 0)); while (!q.empty()) { int u = q.top().to; int d = q.top().dist; q.pop(); if (dist[u] != d) continue; for (int i = 0; i < int(ed[u].size()); ++i) { int v = ed[u][i].to; int t = ed[u][i].dist + d; if (dist[v] == -1 || dist[v] > t) { dist[v] = t; q.push(edge(v, t)); } } } std::queue<int> que; que.push(n); while (!que.empty()) { int u = que.front(); que.pop(); for (int i = 0; i < int(ed[u].size()); ++i) { int v = ed[u][i].to; int d = ed[u][i].dist; if (dist[v] + d == dist[u]) { ev[u].push_back(v); ev[v].push_back(u); if (!vis[v]) { vis[v] = 1; que.push(v); } } } } // for (int i = 1; i <= n; ++i) { // fprintf(stderr, "i = %d : ", i); // for (int j = 0; j < int(ev[i].size()); ++j) { // fprintf(stderr, "%d ", ev[i][j]); // } // putchar('\n'); // } dfs(n, 0); for (int i = 2; i < n; ++i) { // fprintf(stderr, "i = %d tin = %d low = %d\n", i, tin[i], low[i]); if (tin[i] == 0) { ans.push_back(i); } else if (er[i].empty()) { ans.push_back(i); } else { int flag = 0; for (int j = 0; j < int(er[i].size()) && !flag; ++j) { int v = er[i][j]; flag = low[v] >= tin[i]; } if (flag == 0) { ans.push_back(i); } } } printf("%d\n", int(ans.size())); for (int i = 0; i < int(ans.size()); ++i) { printf("%d\n", ans[i]); } }
Error MeshDataTool::create_from_surface(const Ref<Mesh>& p_mesh,int p_surface) { ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_mesh.is_null(),ERR_INVALID_PARAMETER); ERR_FAIL_COND_V(p_mesh->surface_get_primitive_type(p_surface)!=Mesh::PRIMITIVE_TRIANGLES,ERR_INVALID_PARAMETER); Array arrays = p_mesh->surface_get_arrays(p_surface); ERR_FAIL_COND_V( arrays.empty(), ERR_INVALID_PARAMETER ); DVector<Vector3> varray = arrays[Mesh::ARRAY_VERTEX]; int vcount = varray.size(); ERR_FAIL_COND_V( vcount == 0, ERR_INVALID_PARAMETER); clear(); format = p_mesh->surface_get_format(p_surface); material=p_mesh->surface_get_material(p_surface); DVector<Vector3>::Read vr = varray.read(); DVector<Vector3>::Read nr; if (arrays[Mesh::ARRAY_NORMAL].get_type()!=Variant::NIL) nr = arrays[Mesh::ARRAY_NORMAL].operator DVector<Vector3>().read(); DVector<real_t>::Read ta; if (arrays[Mesh::ARRAY_TANGENT].get_type()!=Variant::NIL) ta = arrays[Mesh::ARRAY_TANGENT].operator DVector<real_t>().read(); DVector<Vector2>::Read uv; if (arrays[Mesh::ARRAY_TEX_UV].get_type()!=Variant::NIL) uv = arrays[Mesh::ARRAY_TEX_UV].operator DVector<Vector2>().read(); DVector<Vector2>::Read uv2; if (arrays[Mesh::ARRAY_TEX_UV2].get_type()!=Variant::NIL) uv2 = arrays[Mesh::ARRAY_TEX_UV2].operator DVector<Vector2>().read(); DVector<Color>::Read col; if (arrays[Mesh::ARRAY_COLOR].get_type()!=Variant::NIL) col = arrays[Mesh::ARRAY_COLOR].operator DVector<Color>().read(); DVector<real_t>::Read bo; if (arrays[Mesh::ARRAY_BONES].get_type()!=Variant::NIL) bo = arrays[Mesh::ARRAY_BONES].operator DVector<real_t>().read(); DVector<real_t>::Read we; if (arrays[Mesh::ARRAY_WEIGHTS].get_type()!=Variant::NIL) we = arrays[Mesh::ARRAY_WEIGHTS].operator DVector<real_t>().read(); vertices.resize(vcount); for(int i=0;i<vcount;i++) { Vertex v; v.vertex=vr[i]; if (nr.ptr()) v.normal=nr[i]; if (ta.ptr()) v.tangent=Plane(ta[i*4+0],ta[i*4+1],ta[i*4+2],ta[i*4+3]); if (uv.ptr()) v.uv=uv[i]; if (uv2.ptr()) v.uv2=uv2[i]; if (col.ptr()) v.color=col[i]; if (we.ptr()) { v.weights.push_back(we[i*4+0]); v.weights.push_back(we[i*4+1]); v.weights.push_back(we[i*4+2]); v.weights.push_back(we[i*4+3]); } if (bo.ptr()) { v.bones.push_back(bo[i*4+0]); v.bones.push_back(bo[i*4+1]); v.bones.push_back(bo[i*4+2]); v.bones.push_back(bo[i*4+3]); } vertices[i]=v; } DVector<int> indices; if (arrays[Mesh::ARRAY_INDEX].get_type()!=Variant::NIL) { indices = arrays[Mesh::ARRAY_INDEX]; } else { //make code simpler indices.resize(vcount); DVector<int>::Write iw=indices.write(); for(int i=0;i<vcount;i++) iw[i]=i; } int icount=indices.size(); DVector<int>::Read r = indices.read(); Map<Point2i,int> edge_indices; for(int i=0;i<icount;i+=3) { Vertex*v[3]={ &vertices[r[i+0]], &vertices[r[i+1]], &vertices[r[i+2]] }; int fidx=faces.size(); Face face; for(int j=0;j<3;j++) { face.v[j]=r[i+j]; Point2i edge(r[i+j],r[i+(j+1)%3]); if (edge.x > edge.y) { SWAP(edge.x,edge.y); } if (edge_indices.has(edge)) { face.edges[j]=edge_indices[edge]; } else { face.edges[j]=edge_indices.size(); edge_indices[edge]=face.edges[j]; Edge e; e.vertex[0]=edge.x; e.vertex[1]=edge.y; edges.push_back(e); } edges[face.edges[j]].faces.push_back(fidx); v[j]->faces.push_back(fidx); v[j]->edges.push_back(face.edges[j]); } faces.push_back(face); } return OK; }
// induce head if necessary Agedge_t *edge(Agnode_t *t, char *hname) { return edge(t, node(agraphof(t), hname)); }
static void ExtrudeFaces (void* userData, int vertexCount, const dFloat* faceVertec, int id) { dFloat OFFSET = 0.1f; dFloat face[32][10]; NewtonMesh* mesh = (NewtonMesh*) userData; // calculate the face normal dVector normal (0.0f); dVector p0 (faceVertec[0 * 3 + 0], faceVertec[0 * 3 + 1], faceVertec[0 * 3 + 2]); dVector p1 (faceVertec[1 * 3 + 0], faceVertec[1 * 3 + 1], faceVertec[1 * 3 + 2]); dVector e0 (p1 - p0); for (int i = 2; i < vertexCount; i ++) { dVector p2 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]); dVector e1 (p2 - p0); normal += e0 * e1; e0 = e1; } normal = normal.Scale (1.0f / dSqrt (normal % normal)); dVector displacemnet (normal.Scale (OFFSET)); // add the face displace by some offset for (int i = 0; i < vertexCount; i ++) { dVector p1 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]); p1 += displacemnet; face[i][0] = p1.m_x; face[i][1] = p1.m_y; face[i][2] = p1.m_z; face[i][3] = normal.m_x; face[i][4] = normal.m_y; face[i][5] = normal.m_z; face[i][6] = 0.0f; face[i][7] = 0.0f; face[i][8] = 0.0f; face[i][9] = 0.0f; } // add the face NewtonMeshAddFace (mesh, vertexCount, &face[0][0], 10 * sizeof (dFloat), id); // now add on face walk the perimeter and add a rivet face dVector q0 (faceVertec[(vertexCount - 1) * 3 + 0], faceVertec[(vertexCount - 1) * 3 + 1], faceVertec[(vertexCount - 1) * 3 + 2]); q0 += displacemnet; for (int i = 0; i < vertexCount; i ++) { dVector q1 (faceVertec[i * 3 + 0], faceVertec[i * 3 + 1], faceVertec[i * 3 + 2]); q1 += displacemnet; // calculate the river normal dVector edge (q1 - q0); dVector n (edge * normal); n = n.Scale (1.0f / sqrtf (n % n)); // build a quad to serve a the face between the two parellel faces face[0][0] = q0.m_x; face[0][1] = q0.m_y; face[0][2] = q0.m_z; face[0][3] = n.m_x; face[0][4] = n.m_y; face[0][5] = n.m_z; face[0][6] = 0.0f; face[0][7] = 0.0f; face[0][8] = 0.0f; face[0][9] = 0.0f; face[1][0] = q1.m_x; face[1][1] = q1.m_y; face[1][2] = q1.m_z; face[1][3] = n.m_x; face[1][4] = n.m_y; face[1][5] = n.m_z; face[1][6] = 0.0f; face[1][7] = 0.0f; face[1][8] = 0.0f; face[1][9] = 0.0f; face[2][0] = q1.m_x - displacemnet.m_x; face[2][1] = q1.m_y - displacemnet.m_y; face[2][2] = q1.m_z - displacemnet.m_z; face[2][3] = n.m_x; face[2][4] = n.m_y; face[2][5] = n.m_z; face[2][6] = 0.0f; face[2][7] = 0.0f; face[2][8] = 0.0f; face[2][9] = 0.0f; face[3][0] = q0.m_x - displacemnet.m_x; face[3][1] = q0.m_y - displacemnet.m_y; face[3][2] = q0.m_z - displacemnet.m_z; face[3][3] = n.m_x; face[3][4] = n.m_y; face[3][5] = n.m_z; face[3][6] = 0.0f; face[3][7] = 0.0f; face[3][8] = 0.0f; face[3][9] = 0.0f; // save the first point for the next rivet q0 = q1; // add this face to the mesh NewtonMeshAddFace (mesh, 4, &face[0][0], 10 * sizeof (dFloat), id); } }
int testSQLiteDatabaseConnection() { SQLiteDatabaseConnection connection; QFile file("sqlitetest.db"); std::cerr << "Removing database test file \"sqlitetest.db\"..." << std::endl; if (file.exists()) file.remove(); std::cerr << "Opening \"sqlitetest.db\"..." << std::endl; connection.open("sqlitetest.db"); CHECK(connection.isDBOpen()); std::cerr << "Closing database..." << std::endl; connection.close(); CHECK(!connection.isDBOpen()); std::cerr << "Reopening \"sqlitetest.db\"..." << std::endl; connection.open("sqlitetest.db"); CHECK(connection.isDBOpen()); RoutingNode node(25, 51.0, 7.0); std::cerr << "Save Node..." << std::endl; CHECK(connection.saveNode(node)); node = RoutingNode(26, 51.5, 7.5); CHECK(connection.saveNode(node)); CHECK(*connection.getNodeByID(26) == node); CHECK(*connection.getNodeByID(RoutingNode::convertIDToLongFormat(26)) == node); RoutingEdge edge(45, 25, 26); std::cerr << "Save Edge..." << std::endl; edge.setCycleBarrier(true); edge.setCyclewayType(5); CHECK(connection.saveEdge(edge, "Teststraße")); CHECK_EQ_TYPE(connection.getStreetName(edge), "Teststraße", QString); edge = RoutingEdge(46, 26, 25); CHECK(connection.saveEdge(edge)); GPSPosition min(50.0, 6.0); GPSPosition max(52.0, 8.0); QVector<boost::shared_ptr<RoutingNode> > list = connection.getNodes(min, max); CHECK(!list.isEmpty()); CHECK(list.size() == 2); std::cerr << "Node 0 from DB: " << *(list[0]) << std::endl; std::cerr << "Node 1 from DB: " << *(list[1]) << std::endl; CHECK((*list[0] == node) || (*list[1] == node)); boost::minstd_rand generator(42u); boost::uniform_real<> uni_dist(50, 52); boost::variate_generator<boost::minstd_rand&, boost::uniform_real<> > uni(generator, uni_dist); std::cerr << "Inserting 10000 Nodes within one transaction..." << std::endl; bool successInsertManyNodes = true; CHECK(connection.beginTransaction()); for (int i=0; i<10000; i++) { node = RoutingNode(i + 100, uni(), uni() - (51.0 - 7.0)); successInsertManyNodes = successInsertManyNodes && connection.saveNode(node); } CHECK(successInsertManyNodes); CHECK(connection.endTransaction()); std::cerr << "Hier erwartet: Resultcode 19 (-> Constraint failed)" << std::endl; CHECK(!connection.saveNode(node)); boost::shared_ptr<RoutingEdge> dbEdge(connection.getEdgeByEdgeID(46)); CHECK_EQ(edge, *dbEdge); QVector<boost::shared_ptr<RoutingEdge> > edgeList; edgeList = connection.getEdgesByStartNodeID(26); CHECK_EQ(edge, *edgeList[0]); edgeList = connection.getEdgesByStartNodeID(26); CHECK_EQ(edge, *edgeList[0]); edgeList = connection.getEdgesByEndNodeID(25); CHECK_EQ(edge, *edgeList[0]); edgeList = connection.getEdgesByEndNodeID(25); CHECK_EQ(edge, *edgeList[0]); std::cerr << "Inserting 10000 Edges within one transaction..." << std::endl; bool successInsertManyEdges = true; CHECK(connection.beginTransaction()); for (int i=0; i<10000; i++) { edge = RoutingEdge(i + 100, i+99, i+100); successInsertManyEdges = successInsertManyEdges && connection.saveEdge(edge); } CHECK(successInsertManyEdges); CHECK(connection.endTransaction()); std::cerr << "Hier erwartet: Resultcode 19 (-> Constraint failed)" << std::endl; CHECK(!connection.saveEdge(edge)); edgeList = connection.getEdgesByStartNodeID(99); CHECK(!edgeList.isEmpty()); edgeList = connection.getEdgesByStartNodeID(100); CHECK(!edgeList.isEmpty()); CHECK(connection.beginTransaction()); CHECK(connection.deleteEdge(99, 100)); CHECK(connection.deleteEdge(100, 101)); CHECK(connection.endTransaction()); edgeList = connection.getEdgesByStartNodeID(99); CHECK(edgeList.isEmpty()); edgeList = connection.getEdgesByStartNodeID(100); CHECK(edgeList.isEmpty()); return EXIT_SUCCESS; }
Foam::scalar Foam::wallBoundedParticle::trackFaceTri ( const vector& endPosition, label& minEdgeI ) { // Track p from position to endPosition const triFace tri(currentTetIndices().faceTriIs(mesh_)); vector n = tri.normal(mesh_.points()); n /= mag(n)+VSMALL; // Check which edge intersects the trajectory. // Project trajectory onto triangle minEdgeI = -1; scalar minS = 1; // end position edge currentE(-1, -1); if (meshEdgeStart_ != -1 || diagEdge_ != -1) { currentE = currentEdge(); } // Determine path along line position+s*d to see where intersections // are. forAll(tri, i) { label j = tri.fcIndex(i); const point& pt0 = mesh_.points()[tri[i]]; const point& pt1 = mesh_.points()[tri[j]]; if (edge(tri[i], tri[j]) == currentE) { // Do not check particle is on continue; } // Outwards pointing normal vector edgeNormal = (pt1-pt0)^n; edgeNormal /= mag(edgeNormal)+VSMALL; // Determine whether position and end point on either side of edge. scalar sEnd = (endPosition-pt0)&edgeNormal; if (sEnd >= 0) { // endPos is outside triangle. position() should always be // inside. scalar sStart = (position()-pt0)&edgeNormal; if (mag(sEnd-sStart) > VSMALL) { scalar s = sStart/(sStart-sEnd); if (s >= 0 && s < minS) { minS = s; minEdgeI = i; } } } }
/** * Scan the CFG for finding exit and builds virtual edges with entry and exit. * For memory-place and time purposes, this method is only called when the CFG * is used (call to an accessors method). */ void CFG::scan(void) { // Prepare data typedef HashTable<BasicBlock *, BasicBlock *> map_t; map_t map; VectorQueue<BasicBlock *> todo; todo.put(ent); // Find all BB _bbs.add(&_entry); while(todo) { BasicBlock *bb = todo.get(); ASSERT(bb); // second case : calling jump to a function if(map.exists(bb) || (bb != ent && ENTRY(bb))) continue; // build the virtual BB BasicBlock *vbb = new VirtualBasicBlock(bb); _bbs.add(vbb); map.put(bb, vbb); ASSERTP(map.exists(bb), "not for " << bb->address()); // resolve targets for(BasicBlock::OutIterator edge(bb); edge; edge++) { ASSERT(edge->target()); if(edge->kind() != Edge::CALL) todo.put(edge->target()); } } // Relink the BB BasicBlock *vent = map.get(ent, 0); ASSERT(vent); new Edge(&_entry, vent, Edge::VIRTUAL); for(bbs_t::Iterator vbb(_bbs); vbb; vbb++) { if(vbb->isEnd()) continue; BasicBlock *bb = ((VirtualBasicBlock *)*vbb)->bb(); if(bb->isReturn()) new Edge(vbb, &_exit, Edge::VIRTUAL); for(BasicBlock::OutIterator edge(bb); edge; edge++) { // A call if(edge->kind() == Edge::CALL) { Edge *vedge = new Edge(vbb, edge->target(), Edge::CALL); vedge->toCall(); } // Pending edge else if(!edge->target()) { new Edge(vbb, 0, edge->kind()); } // Possibly a not explicit call else { ASSERT(edge->target()); BasicBlock *vtarget = map.get(edge->target(), 0); if(vtarget) new Edge(vbb, vtarget, edge->kind()); else { // calling jump to a function Edge *nedge = new Edge(vbb, edge->target(), Edge::CALL); vbb->flags |= BasicBlock::FLAG_Call; new Edge(vbb, &_exit, Edge::VIRTUAL); } } } } _bbs.add(&_exit); // Number the BB for(int i = 0; i < _bbs.length(); i++) { INDEX(_bbs[i]) = i; _bbs[i]->_cfg = this; } flags |= FLAG_Scanned; }
/** * @function InsertEdge */ int HP2D::InsertEdge( Vertice *_v1, Vertice *_v2 ) { int n = mE.size(); Edge edge( _v1, _v2 ); mE.push_back(edge); return n; }