void ShapeDetection::draw( bool useBalance, bool showNegativeSpace ) { gl::setMatricesWindow( Vec2i(getWindowWidth(), getWindowHeight()) ); // draw points for( int i=0; i<mTrackedShapes.size(); i++){ if( mTrackedShapes[i].mOffBalance && useBalance ){ glBegin( GL_POLYGON ); } else if (showNegativeSpace) { glLineWidth(2.0f); glBegin( GL_LINE_LOOP ); } else{ glLineWidth(1.0f); glBegin(GL_LINE_LOOP); } glLineWidth(1.0f); glBegin(GL_LINE_LOOP); for( int j=0; j<mTrackedShapes[i].hull.size(); j++ ){ if (showNegativeSpace) { gl::color( Color( 0.0f, 0.0f, 0.0f ) ); } else { gl::color(Color( 0.5f, 0.5f, 0.5f) ); } Vec2f v = fromOcv( mTrackedShapes[i].hull[j] ); // offset the points to align with the camera used for the mesh float newX = lmap(v.x, 0.0f, 320.0f, 0.0f, float(getWindowWidth())); float newY = lmap(v.y, 0.0f, 240.0f, 0.0f, float(getWindowHeight())); Vec2f pos = Vec2f( newX, newY); gl::vertex( pos ); } glEnd(); // glLineWidth(10.0f); // gl::enableAlphaBlending(); //// glEnable(GL_BLEND); // gl::color(0.0f, 0.75f, 1.0f); // glBegin( GL_LINE_STRIP ); // int counter = 50; // for( Vec3f v: mTrackedShapes[i].mTrailPoint.mTrail ) { //// gl::color( ColorA( 0.0f, 0.75f, 1.0f, (1.0 - counter*2/100)) ); //// glColor4f(0.0f, 0.75f, 1.0f, (1.0 - counter*2/100)); // float newX = lmap(v.x, 0.0f, 320.0f, 0.0f, float(getWindowWidth())); // float newY = lmap(v.y, 0.0f, 240.0f, 0.0f, float(getWindowHeight())); // gl::vertex( newX, newY ); // counter--; // } // glEnd(); //// glDisable(GL_BLEND); // gl::disableAlphaBlending(); } }
void AGWorm::draw(){ //noFill(); gl::color(1.f, 1.f, 1.f); gl::lineWidth(1.f); gl::begin(GL_LINE); for(int i = 0; i < springs.size(); i++){ Spring s = springs.at(i); gl::vertex(s.a); // app::console() << "s.a["<<i<<"]: " << s.a << endl; gl::vertex(s.b); // app::console() << "s.b["<<i<<"]: " << s.b << endl; } gl::end(); gl::pushMatrices(); int i = 0; // noStroke(); // sphereDetail(3); // fill(255); float baseFreq = frameCount * freq1; for (int j = 0; j < nodes.size(); j++){ Node n = nodes.at(j); //app::console() << "n[" << j << "]: " << n << endl; float d = lmap( sin(baseFreq - i*freq2), -1.f, 1.f, radius, radius * 2); gl::pushMatrices(); gl::translate(n); gl::drawSphere(Vec3f::zero(), d); gl::popMatrices(); i++; } frameCount++; }
ServoWave::ServoWave(int _numServos, float _angle, float _period, int _wavelength, int _ampMax, int _indexSpacing){ numServos = _numServos;//servos of the whole unit angle = _angle;//height of wave period = _period; //in milliseconds wavelength = _wavelength;//how many servos long the wave will be ampMax=_ampMax; indexSpacing=_indexSpacing; float a=0; numServos = _numServos; currentServo = 0;//set currentServo to 0 long previousMillis = 0; long lastUpdatedAt = millis(); TOTAL_INDICES=360;//total num of index pioints, until the amplitude is back at zero TOTAL_NODES=10; //initialize servoPosition array for(int i=0;i<numServos;i++){ servoPositions[i] = 90; // starting position for all servos. could be passed as an argument } for (int i = 0; i < TOTAL_INDICES; i++) { // wave[i] = (sin(a) + 1.0) * ampMax;//ampMax defines the amount it strays from the 0 position wave[i] = lmap(sin(a),-1.0,1.0,0.0,angle);//180.0); a+=period;// Serial.println(wave[i]); } for (int i = 0; i < TOTAL_NODES; i++) { index[i] = i*indexSpacing;//i*wavelength; } }
/** See tree_builder::open_node(). */ static bool open_node( const FlexLexer * lexer, const std::string & classname, const std::string & nodename ) { IFNOLEXER(false); return lmap()[lexer].builder->open_node( classname, nodename ); }
void PuzzleApp::update() { if (_hands[LEFT]->state != Hand::NORMAL && _hands[RIGHT]->state != Hand::NORMAL) { Vec2f diff = _hands[RIGHT]->pos - _hands[LEFT]->pos; Vec2f polar = toPolar(diff); console()<<polar.x<<" "<<polar.y<<endl; float theta = polar.y;//[0, PI_two) clockwise float sign = 0.0f; if (theta > Pi) theta -= Pi; if (theta < Pi_half) { sign = theta*0.5f; } else if (theta > Pi_half) { theta = Pi - theta; sign = -theta*0.5f; } _rotate = sign; float loBound = 150; float hiBound = getWindowWidth(); _scale = lmap(polar.x, loBound, hiBound, minScale, maxScale); _scale = constrain(_scale, minScale, maxScale); } StateMachine::update(); }
/** See tree_builder::add_property(). */ static bool add_property( const FlexLexer * lexer, const std::string & key, const std::string & val ) { IFNOLEXER(false); return lmap()[lexer].builder->add_property( key, val ); }
void Particle::update(const float &fps, const ci::Vec2i &mouseLoc, const ci::Perlin &perlin,const bool &mouseDir, const bool &mouse, const float &noiseScale,const float &noiseStrength) { float nz = cinder::app::getElapsedSeconds() ; // angle = perlin.(/noiseScale,p.y/noiseScale) * noiseStrength; float noise = perlin.fBm(mLoc.x/noiseScale,mLoc.y/noiseScale)*noiseStrength; //mAcc = perlin.dfBm(mLoc); mAcc = Vec2f(cos(noise), sin(noise)); if(mLoc.x < 100 || mLoc.x > ci::app::getWindowWidth()-100 || mLoc.y < 100 || mLoc.y > ci::app::getWindowHeight()-100) { mDir = ci::app::getWindowCenter() - mLoc; mDir.normalized(); mAcc += mDir*0.003; } if(mouse){ if(mouseDir == true){ mDir = (mouseLoc * 1.01) - mLoc; mDir.normalized(); mAcc += mDir *0.05; } else { if(mouseLoc.distance(mLoc) < 80) { mDir = mLoc - (mouseLoc); //mDir = (mouseLoc * 1.01) - mLoc; mDir.normalized(); //mDir *= -1; mAcc += mDir*2 ; } } } //Add Perlin to Acc mAcc.normalize(); //mAcc += mNoiseVec; mVel += mAcc; if(mVel.length() > 4){ mVel.normalize(); mVel *= 4; } mLoc += mVel; mLifeTime--; mSize = lmap(mLifeTime, 0.0f, 300.0f, 1.0f, 5.0f); //mAcc *=0; }
void StandardShader::compute() { // turn off all lights memset(lightmap,0,sizeof(TCODColor)*map->getWidth()*map->getHeight()); for ( Light *l=lights.begin(); l != lights.end(); l++) { // compute the potential visible set for this light int minx=l->x-l->radius; int miny=l->y-l->radius; int maxx=l->x+l->radius; int maxy=l->y+l->radius; minx=MAX(0,minx); miny=MAX(0,miny); maxx=MIN(maxx,map->getWidth()-1); maxy=MIN(maxy,map->getHeight()-1); float offset = 1.0f/(1.0f+(float)(l->radius*l->radius)/20); float factor = 1.0f/(1.0f-offset); // compute the light's fov TCODMap lmap(maxx-minx+1,maxy-miny+1); for (int x=minx; x <= maxx; x++) { for (int y=miny; y <= maxy; y++) { lmap.setProperties(x-minx,y-miny,map->isWalkable(x,y),map->isTransparent(x,y)); } } lmap.computeFov(l->x-minx,l->y-miny,l->radius); // compute the light's contribution //double invSquaredRadius=1.0 / (l->radius*l->radius); for (int x=minx; x <= maxx; x++) { for (int y=miny; y <= maxy; y++) { if ( lmap.isInFov(x-minx,y-miny)) { int squaredDist = (l->x-x)*(l->x-x)+(l->y-y)*(l->y-y); // basic //double coef = 1.0-squaredDist*invSquaredRadius; // invsqr1 //double coef=(1.0f/(1.0f+(float)(squaredDist))); // invsqr2 double coef=(1.0f/(1.0f+(float)(squaredDist)/20)- offset)*factor; TCODColor *col=&lightmap[x+y*map->getWidth()]; *col = *col + l->col * coef; } } } } }
int main(int argc, char **argv) { //LET THE MEMORY LEAKING BEGIN!!! iter(map(range(0, 10), dbl,NULL), printint, NULL); iter(filter(range(0, 10), odd, NULL), printint, NULL); //Darker magic? Not really... closure *addtwo = bind(NULL, add, liftint(2)); closure *addten = bind(NULL, add, liftint(10)); printf("%d\n", *(int *)call(addtwo, liftint(3))); printf("%d\n", *(int *)call(addten, liftint(3))); //all together now, with pseudo types everywhere woopie!!! list *vars = liftlist(range(0, 10), sizeof(int)); list *res = lmap(vars, addtwo); iter(res, printint, NULL); exit(0); }
void PretzelColorPicker::mouseDragged(const ci::vec2 &pos){ if( bDragging ){ vec2 localPos = pos - mOffset; vec2 n; n.x = ci::math<float>::clamp( (localPos.x - mColorSwatchRect.x1) / mColorSwatchRect.getWidth(), 0.0, 1.0); n.y = ci::math<float>::clamp( (localPos.y - mColorSwatchRect.y1) / mColorSwatchRect.getHeight(), 0.0, 1.0); mCrosshairPos = n; updateColor(); }else if( bDraggingHue ){ vec2 localPos = pos - mOffset; mHueNorm = lmap( localPos.y, mHueStripRect.y1, mHueStripRect.y2, 0.0f, 1.0f); mHueNorm = ci::math<float>::clamp(mHueNorm); ColorA cc = mHueSurf.getPixel( vec2(1, mHueNorm * mHueSurf.getHeight()) ); mHueCol = cc; redrawBox(); } }
vector< Shape > ShapeDetection::getEvaluationSet( ContourVector rawContours, int minimalArea, int maxArea ) { vector< Shape > vec; for ( vector< cv::Point > &c : rawContours ) { // create a matrix for the contour cv::Mat matrix = cv::Mat(c); // extract data from contour cv::Scalar center = mean(matrix); // cout << "center " << center << endl; double area = cv::contourArea(matrix); // reject it if too small if ( area < minimalArea ) { continue; } // reject it if too big if ( area > maxArea ) { continue; } // store data Shape shape; shape.area = area; shape.centroid = cv::Point( center.val[0], center.val[1] ); // get depth value from center point float centerDepth = (float)mInput.at<short>( shape.centroid.y, shape.centroid.x ); // map 10000 to 0 1 shape.depth = lmap( centerDepth, (float)mNearLimit, (float)mFarLimit, 0.0f, 1.0f ); // store points around shape shape.hull = c; shape.matchFound = false; vec.push_back(shape); } return vec; }
/** Gets the current builder object for this context, which must have been previously set up via a call to bind(lexer,builder). Ownership of the returned pointer does not change by calling this function. */ static tree_builder * builder( const FlexLexer * lexer ) { return lmap()[lexer].builder; }
void llsdutil_object::test<9>() { set_test_name("llsd_matches"); // for this test, construct a map of all possible LLSD types LLSD map; map.insert("empty", LLSD()); map.insert("Boolean", LLSD::Boolean()); map.insert("Integer", LLSD::Integer(0)); map.insert("Real", LLSD::Real(0.0)); map.insert("String", LLSD::String("bah")); map.insert("NumString", LLSD::String("1")); map.insert("UUID", LLSD::UUID()); map.insert("Date", LLSD::Date()); map.insert("URI", LLSD::URI()); map.insert("Binary", LLSD::Binary()); map.insert("Map", LLSD().with("foo", LLSD())); // Only an empty array can be constructed on the fly LLSD array; array.append(LLSD()); map.insert("Array", array); // These iterators are declared outside our various for loops to avoid // fatal MSVC warning: "I used to be broken, but I'm all better now!" LLSD::map_const_iterator mi, mend(map.endMap()); /*-------------------------- llsd_matches --------------------------*/ // empty prototype matches anything for (mi = map.beginMap(); mi != mend; ++mi) { ensure_equals(std::string("empty matches ") + mi->first, llsd_matches(LLSD(), mi->second), ""); } LLSD proto_array, data_array; for (int i = 0; i < 3; ++i) { proto_array.append(LLSD()); data_array.append(LLSD()); } // prototype array matches only array for (mi = map.beginMap(); mi != mend; ++mi) { ensure(std::string("array doesn't match ") + mi->first, ! llsd_matches(proto_array, mi->second).empty()); } // data array must be at least as long as prototype array proto_array.append(LLSD()); ensure_equals("data array too short", llsd_matches(proto_array, data_array), "Array size 4 required instead of Array size 3"); data_array.append(LLSD()); ensure_equals("data array just right", llsd_matches(proto_array, data_array), ""); data_array.append(LLSD()); ensure_equals("data array longer", llsd_matches(proto_array, data_array), ""); // array element matching data_array[0] = LLSD::String(); ensure_equals("undefined prototype array entry", llsd_matches(proto_array, data_array), ""); proto_array[0] = LLSD::Binary(); ensure_equals("scalar prototype array entry", llsd_matches(proto_array, data_array), "[0]: Binary required instead of String"); data_array[0] = LLSD::Binary(); ensure_equals("matching prototype array entry", llsd_matches(proto_array, data_array), ""); // build a coupla maps LLSD proto_map, data_map; data_map["got"] = LLSD(); data_map["found"] = LLSD(); for (LLSD::map_const_iterator dmi(data_map.beginMap()), dmend(data_map.endMap()); dmi != dmend; ++dmi) { proto_map[dmi->first] = dmi->second; } proto_map["foo"] = LLSD(); proto_map["bar"] = LLSD(); // prototype map matches only map for (mi = map.beginMap(); mi != mend; ++mi) { ensure(std::string("map doesn't match ") + mi->first, ! llsd_matches(proto_map, mi->second).empty()); } // data map must contain all keys in prototype map std::string error(llsd_matches(proto_map, data_map)); ensure_contains("missing keys", error, "missing keys"); ensure_contains("missing foo", error, "foo"); ensure_contains("missing bar", error, "bar"); ensure_does_not_contain("found found", error, "found"); ensure_does_not_contain("got got", error, "got"); data_map["bar"] = LLSD(); error = llsd_matches(proto_map, data_map); ensure_contains("missing foo", error, "foo"); ensure_does_not_contain("got bar", error, "bar"); data_map["foo"] = LLSD(); ensure_equals("data map just right", llsd_matches(proto_map, data_map), ""); data_map["extra"] = LLSD(); ensure_equals("data map with extra", llsd_matches(proto_map, data_map), ""); // map element matching data_map["foo"] = LLSD::String(); ensure_equals("undefined prototype map entry", llsd_matches(proto_map, data_map), ""); proto_map["foo"] = LLSD::Binary(); ensure_equals("scalar prototype map entry", llsd_matches(proto_map, data_map), "['foo']: Binary required instead of String"); data_map["foo"] = LLSD::Binary(); ensure_equals("matching prototype map entry", llsd_matches(proto_map, data_map), ""); // String { static const char* matches[] = { "String", "NumString", "Boolean", "Integer", "Real", "UUID", "Date", "URI" }; test_matches("String", map, boost::begin(matches), boost::end(matches)); } // Boolean, Integer, Real static const char* numerics[] = { "Boolean", "Integer", "Real" }; for (const char **ni = boost::begin(numerics), **nend = boost::end(numerics); ni != nend; ++ni) { static const char* matches[] = { "Boolean", "Integer", "Real", "String", "NumString" }; test_matches(*ni, map, boost::begin(matches), boost::end(matches)); } // UUID { static const char* matches[] = { "UUID", "String", "NumString" }; test_matches("UUID", map, boost::begin(matches), boost::end(matches)); } // Date { static const char* matches[] = { "Date", "String", "NumString" }; test_matches("Date", map, boost::begin(matches), boost::end(matches)); } // URI { static const char* matches[] = { "URI", "String", "NumString" }; test_matches("URI", map, boost::begin(matches), boost::end(matches)); } // Binary { static const char* matches[] = { "Binary" }; test_matches("Binary", map, boost::begin(matches), boost::end(matches)); } /*-------------------------- llsd_equals ---------------------------*/ // Cross-product of each LLSD type with every other for (LLSD::map_const_iterator lmi(map.beginMap()), lmend(map.endMap()); lmi != lmend; ++lmi) { for (LLSD::map_const_iterator rmi(map.beginMap()), rmend(map.endMap()); rmi != rmend; ++rmi) { // Name this test based on the map keys naming the types of // interest, e.g "String::Integer". // We expect the values (xmi->second) to be equal if and only // if the type names (xmi->first) are equal. ensure(STRINGIZE(lmi->first << "::" << rmi->first), bool(lmi->first == rmi->first) == bool(llsd_equals(lmi->second, rmi->second))); } } // Array cases LLSD rarray; rarray.append(1.0); rarray.append(2); rarray.append("3"); LLSD larray(rarray); ensure("llsd_equals(equal arrays)", llsd_equals(larray, rarray)); rarray[2] = "4"; ensure("llsd_equals(different [2])", ! llsd_equals(larray, rarray)); rarray = larray; rarray.append(LLSD::Date()); ensure("llsd_equals(longer right array)", ! llsd_equals(larray, rarray)); rarray = larray; rarray.erase(2); ensure("llsd_equals(shorter right array)", ! llsd_equals(larray, rarray)); // Map cases LLSD rmap; rmap["San Francisco"] = 65; rmap["Phoenix"] = 92; rmap["Boston"] = 77; LLSD lmap(rmap); ensure("llsd_equals(equal maps)", llsd_equals(lmap, rmap)); rmap["Boston"] = 80; ensure("llsd_equals(different [\"Boston\"])", ! llsd_equals(lmap, rmap)); rmap = lmap; rmap["Atlanta"] = 95; ensure("llsd_equals(superset right map)", ! llsd_equals(lmap, rmap)); rmap = lmap; lmap["Seattle"] = 72; ensure("llsd_equals(superset left map)", ! llsd_equals(lmap, rmap)); }
void Trilinos_Util_GenerateVbrProblem(int nx, int ny, int npoints, int * xoff, int * yoff, int nsizes, int * sizes, int nrhs, const Epetra_Comm &comm, Epetra_BlockMap *& map, Epetra_VbrMatrix *& A, Epetra_MultiVector *& x, Epetra_MultiVector *& b, Epetra_MultiVector *&xexact) { int i, j; // Number of global equations is nx*ny. These will be distributed in a linear fashion int numGlobalEquations = nx*ny; Epetra_Map ptMap(numGlobalEquations, 0, comm); // Create map with equal distribution of equations. int numMyElements = ptMap.NumMyElements(); Epetra_IntVector elementSizes(ptMap); // This vector will have the list of element sizes for (i=0; i<numMyElements; i++) elementSizes[i] = sizes[ptMap.GID64(i)%nsizes]; // cycle through sizes array map = new Epetra_BlockMap(-1, numMyElements, ptMap.MyGlobalElements(), elementSizes.Values(), ptMap.IndexBase(), ptMap.Comm()); A = new Epetra_VbrMatrix(Copy, *map, 0); // Construct matrix int * indices = new int[npoints]; // double * values = new double[npoints]; // double dnpoints = (double) npoints; // This section of code creates a vector of random values that will be used to create // light-weight dense matrices to pass into the VbrMatrix construction process. int maxElementSize = 0; for (i=0; i< nsizes; i++) maxElementSize = EPETRA_MAX(maxElementSize, sizes[i]); Epetra_LocalMap lmap(maxElementSize*maxElementSize, ptMap.IndexBase(), ptMap.Comm()); Epetra_Vector randvec(lmap); randvec.Random(); randvec.Scale(-1.0); // Make value negative for (i=0; i<numMyElements; i++) { int rowID = map->GID(i); int numIndices = 0; int rowDim = sizes[rowID%nsizes]; for (j=0; j<npoints; j++) { int colID = rowID + xoff[j] + nx*yoff[j]; // Compute column ID based on stencil offsets if (colID>-1 && colID<numGlobalEquations) indices[numIndices++] = colID; } A->BeginInsertGlobalValues(rowID, numIndices, indices); for (j=0; j < numIndices; j++) { int colDim = sizes[indices[j]%nsizes]; A->SubmitBlockEntry(&(randvec[0]), rowDim, rowDim, colDim); } A->EndSubmitEntries(); } delete [] indices; A->FillComplete(); // Compute the InvRowSums of the matrix rows Epetra_Vector invRowSums(A->RowMap()); Epetra_Vector rowSums(A->RowMap()); A->InvRowSums(invRowSums); rowSums.Reciprocal(invRowSums); // Jam the row sum values into the diagonal of the Vbr matrix (to make it diag dominant) int numBlockDiagonalEntries; int * rowColDims; int * diagoffsets = map->FirstPointInElementList(); A->BeginExtractBlockDiagonalView(numBlockDiagonalEntries, rowColDims); for (i=0; i< numBlockDiagonalEntries; i++) { double * diagVals; int diagLDA; A->ExtractBlockDiagonalEntryView(diagVals, diagLDA); int rowDim = map->ElementSize(i); for (j=0; j<rowDim; j++) diagVals[j+j*diagLDA] = rowSums[diagoffsets[i]+j]; } if (nrhs<=1) { x = new Epetra_Vector(*map); b = new Epetra_Vector(*map); xexact = new Epetra_Vector(*map); } else { x = new Epetra_MultiVector(*map, nrhs); b = new Epetra_MultiVector(*map, nrhs); xexact = new Epetra_MultiVector(*map, nrhs); } xexact->Random(); // Fill xexact with random values A->Multiply(false, *xexact, *b); return; }
static Tree prepareRules(Tree rules) { return lmap(prepareRule, rules); }
/** * Prepare a "pattern" by replacing variables x by special * pattern variables ?x. * * P[x] -> ?x * P[x(e)] -> x(P[e]) * P[e(f)] -> P[e](P[f]) * P[e:f] -> P[e]:P[f] * etc. */ static Tree preparePattern(Tree box) { // cerr << "preparePattern(" << boxpp(box) << ")" << endl; int id; double r; prim0 p0; prim1 p1; prim2 p2; prim3 p3; prim4 p4; prim5 p5; Tree t1, t2, t3, ff, label, cur, min, max, step, type, name, file, arg, body, fun, args, ldef, slot, ident, rules; xtended* xt = (xtended*)getUserData(box); // primitive elements if(xt) return box; else if(isBoxIdent(box)) return boxPatternVar(box); else if(isBoxAppl(box, fun, args)) { if(isBoxIdent(fun)) return boxAppl(fun, lmap(preparePattern, args)); else return boxAppl(preparePattern(fun), lmap(preparePattern, args)); } else if(isBoxAbstr(box, arg, body)) return box; else if(isBoxInt(box)) return box; else if(isBoxReal(box, &r)) return box; else if(isBoxWaveform(box)) return box; else if(isBoxCut(box)) return box; else if(isBoxWire(box)) return box; else if(isBoxPrim0(box, &p0)) return box; else if(isBoxPrim1(box, &p1)) return box; else if(isBoxPrim2(box, &p2)) return box; else if(isBoxPrim3(box, &p3)) return box; else if(isBoxPrim4(box, &p4)) return box; else if(isBoxPrim5(box, &p5)) return box; else if(isBoxWithLocalDef(box, body, ldef)) return boxWithLocalDef(preparePattern(body), ldef); // foreign elements else if(isBoxFFun(box, ff)) return box; else if(isBoxFConst(box, type, name, file)) return box; else if(isBoxFVar(box, type, name, file)) return box; // block diagram binary operator else if(isBoxSeq(box, t1, t2)) return boxSeq(preparePattern(t1), preparePattern(t2)); else if(isBoxSplit(box, t1, t2)) return boxSplit(preparePattern(t1), preparePattern(t2)); else if(isBoxMerge(box, t1, t2)) return boxMerge(preparePattern(t1), preparePattern(t2)); else if(isBoxPar(box, t1, t2)) return boxPar(preparePattern(t1), preparePattern(t2)); else if(isBoxRec(box, t1, t2)) return boxRec(preparePattern(t1), preparePattern(t2)); // iterative block diagram construction else if(isBoxIPar(box, t1, t2, t3)) return boxIPar(t1, t2, preparePattern(t3)); else if(isBoxISeq(box, t1, t2, t3)) return boxISeq(t1, t2, preparePattern(t3)); else if(isBoxISum(box, t1, t2, t3)) return boxISum(t1, t2, preparePattern(t3)); else if(isBoxIProd(box, t1, t2, t3)) return boxIProd(t1, t2, preparePattern(t3)); // static information else if(isBoxInputs(box, t1)) return boxInputs(preparePattern(t1)); else if(isBoxOutputs(box, t1)) return boxOutputs(preparePattern(t1)); // user interface else if(isBoxButton(box, label)) return box; else if(isBoxCheckbox(box, label)) return box; else if(isBoxVSlider(box, label, cur, min, max, step)) return box; else if(isBoxHSlider(box, label, cur, min, max, step)) return box; else if(isBoxVGroup(box, label, t1)) return boxVGroup(label, preparePattern(t1)); else if(isBoxHGroup(box, label, t1)) return boxHGroup(label, preparePattern(t1)); else if(isBoxTGroup(box, label, t1)) return boxTGroup(label, preparePattern(t1)); else if(isBoxHBargraph(box, label, min, max)) return box; else if(isBoxVBargraph(box, label, min, max)) return box; else if(isBoxNumEntry(box, label, cur, min, max, step)) return box; else if(isNil(box)) return box; else if(isList(box)) return lmap(preparePattern, box); else if(isBoxEnvironment(box)) return box; /* not expected else if (isClosure(box, abstr, genv, vis, lenv)) { fout << "closure[" << boxpp(abstr) << ", genv = " << envpp(genv) << ", lenv = " << envpp(lenv) << "]"; } */ else if(isBoxComponent(box, label)) return box; else if(isBoxAccess(box, t1, t2)) return box; /* not expected else if (isImportFile(box, label)) { fout << "import(" << tree2str(label) << ')'; } */ else if(isBoxSlot(box, &id)) return box; else if(isBoxSymbolic(box, slot, body)) return box; // Pattern Matching Extensions else if(isBoxCase(box, rules)) return box; else if(isBoxPatternVar(box, ident)) return box; // None of the previous tests succeded, then it is not a valid box else { cerr << "Error in preparePattern() : " << *box << " is not a valid box" << endl; exit(1); } return box; }
/** Returns the lexer_metadata for the given lexer, creating one if needed. It is assumed that the lexer has been bound via a call to bind(). */ static lexer_metadata & metadata( const FlexLexer * lexer ) { return lmap()[lexer]; }
static Tree prepareRule(Tree rule) { return cons(lmap(preparePattern, hd(rule)), tl(rule)); }
/** See tree_builder::node_depth(). */ static size_t node_depth( const FlexLexer * lexer ) { IFNOLEXER(0); return lmap()[lexer].builder->node_depth(); }
/** See tree_builder::change_node_class(). */ static bool change_node_class( const FlexLexer * lexer, const std::string & newclassname ) { IFNOLEXER(false); return lmap()[lexer].builder->change_node_class( newclassname ); }
void GenerateVbrProblem(int numNodesX, int numNodesY, int numProcsX, int numProcsY, int numPoints, int * xoff, int * yoff, int nsizes, int * sizes, int nrhs, const Epetra_Comm &comm, bool verbose, bool summary, Epetra_BlockMap *& map, Epetra_VbrMatrix *& A, Epetra_MultiVector *& b, Epetra_MultiVector *& bt, Epetra_MultiVector *&xexact, bool StaticProfile, bool MakeLocalOnly) { int i; // Determine my global IDs long long * myGlobalElements; GenerateMyGlobalElements(numNodesX, numNodesY, numProcsX, numProcsY, comm.MyPID(), myGlobalElements); int numMyElements = numNodesX*numNodesY; Epetra_Map ptMap((long long)-1, numMyElements, myGlobalElements, 0, comm); // Create map with 2D block partitioning. delete [] myGlobalElements; Epetra_IntVector elementSizes(ptMap); // This vector will have the list of element sizes for (i=0; i<numMyElements; i++) elementSizes[i] = sizes[ptMap.GID64(i)%nsizes]; // cycle through sizes array map = new Epetra_BlockMap((long long)-1, numMyElements, ptMap.MyGlobalElements64(), elementSizes.Values(), ptMap.IndexBase64(), ptMap.Comm()); int profile = 0; if (StaticProfile) profile = numPoints; // FIXME: Won't compile until Epetra_VbrMatrix is modified. #if 0 int j; long long numGlobalEquations = ptMap.NumGlobalElements64(); if (MakeLocalOnly) A = new Epetra_VbrMatrix(Copy, *map, *map, profile); // Construct matrix rowmap=colmap else A = new Epetra_VbrMatrix(Copy, *map, profile); // Construct matrix long long * indices = new long long[numPoints]; // This section of code creates a vector of random values that will be used to create // light-weight dense matrices to pass into the VbrMatrix construction process. int maxElementSize = 0; for (i=0; i< nsizes; i++) maxElementSize = EPETRA_MAX(maxElementSize, sizes[i]); Epetra_LocalMap lmap((long long)maxElementSize*maxElementSize, ptMap.IndexBase(), ptMap.Comm()); Epetra_Vector randvec(lmap); randvec.Random(); randvec.Scale(-1.0); // Make value negative int nx = numNodesX*numProcsX; for (i=0; i<numMyElements; i++) { long long rowID = map->GID64(i); int numIndices = 0; int rowDim = sizes[rowID%nsizes]; for (j=0; j<numPoints; j++) { long long colID = rowID + xoff[j] + nx*yoff[j]; // Compute column ID based on stencil offsets if (colID>-1 && colID<numGlobalEquations) indices[numIndices++] = colID; } A->BeginInsertGlobalValues(rowID, numIndices, indices); for (j=0; j < numIndices; j++) { int colDim = sizes[indices[j]%nsizes]; A->SubmitBlockEntry(&(randvec[0]), rowDim, rowDim, colDim); } A->EndSubmitEntries(); } delete [] indices; A->FillComplete(); // Compute the InvRowSums of the matrix rows Epetra_Vector invRowSums(A->RowMap()); Epetra_Vector rowSums(A->RowMap()); A->InvRowSums(invRowSums); rowSums.Reciprocal(invRowSums); // Jam the row sum values into the diagonal of the Vbr matrix (to make it diag dominant) int numBlockDiagonalEntries; int * rowColDims; int * diagoffsets = map->FirstPointInElementList(); A->BeginExtractBlockDiagonalView(numBlockDiagonalEntries, rowColDims); for (i=0; i< numBlockDiagonalEntries; i++) { double * diagVals; int diagLDA; A->ExtractBlockDiagonalEntryView(diagVals, diagLDA); int rowDim = map->ElementSize(i); for (j=0; j<rowDim; j++) diagVals[j+j*diagLDA] = rowSums[diagoffsets[i]+j]; } if (nrhs<=1) { b = new Epetra_Vector(*map); bt = new Epetra_Vector(*map); xexact = new Epetra_Vector(*map); } else { b = new Epetra_MultiVector(*map, nrhs); bt = new Epetra_MultiVector(*map, nrhs); xexact = new Epetra_MultiVector(*map, nrhs); } xexact->Random(); // Fill xexact with random values A->Multiply(false, *xexact, *b); A->Multiply(true, *xexact, *bt); #endif // EPETRA_NO_32BIT_GLOBAL_INDICES return; }
/** See tree_builder::clode_node(). */ static bool close_node( const FlexLexer * lexer ) { IFNOLEXER(false); return lmap()[lexer].builder->close_node(); }
/** Sets the current builder object for this context. Pointer ownership does not change by calling this function. This must be carefully marshalled: it must always be set immediately before the matching lexer is used, and unbind(lexer) should be called immediately afterwards to free up the internal marshaling data. Failing to call unbind will mean a resource leak (albeit a small one). Preconditions: - lexer and builder must be valid pointers and must out-live the expected lifetime of this context object, which internally associates these two objects. */ static void bind( const FlexLexer * lexer, tree_builder * builder ) { lmap()[lexer].builder = builder; }
void ShapeDetection::onDepth( openni::VideoFrameRef frame, const OpenNI::DeviceOptions& deviceOptions ) { // convert frame from the camera to an OpenCV matrix mInput = toOcv( OpenNI::toChannel16u(frame) ); cv::Mat thresh; cv::Mat eightBit; cv::Mat withoutBlack; // remove black pixels from frame which get detected as noise withoutBlack = removeBlack( mInput, mNearLimit, mFarLimit ); // convert matrix from 16 bit to 8 bit with some color compensation withoutBlack.convertTo( eightBit, CV_8UC3, 0.1/1.0 ); // invert the image cv::bitwise_not( eightBit, eightBit ); mContours.clear(); mApproxContours.clear(); // using a threshold to reduce noise cv::threshold( eightBit, thresh, mThresh, mMaxVal, CV_8U ); // draw lines around shapes cv::findContours( thresh, mContours, mHierarchy, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE ); vector<cv::Point> approx; // approx number of points per contour for ( int i = 0; i < mContours.size(); i++ ) { cv::approxPolyDP(mContours[i], approx, 1, true ); mApproxContours.push_back( approx ); } mShapes.clear(); // get data that we can later compare mShapes = getEvaluationSet( mApproxContours, 75, 100000 ); // find the nearest match for each shape for ( int i = 0; i < mTrackedShapes.size(); i++ ) { Shape* nearestShape = findNearestMatch( mTrackedShapes[i], mShapes, 5000 ); // a tracked shape was found, update that tracked shape with the new shape if ( nearestShape != NULL ) { nearestShape->matchFound = true; mTrackedShapes[i].centroid = nearestShape->centroid; // get depth value from center point float centerDepth = (float)mInput.at<short>( mTrackedShapes[i].centroid.y, mTrackedShapes[i].centroid.x ); // map 10 10000 to 0 1 mTrackedShapes[i].depth = lmap( centerDepth, (float)mNearLimit, (float)mFarLimit, 0.0f, 1.0f ); mTrackedShapes[i].lastFrameSeen = ci::app::getElapsedFrames(); mTrackedShapes[i].hull.clear(); mTrackedShapes[i].hull = nearestShape->hull; mTrackedShapes[i].motion = nearestShape->motion; Vec3f centerVec = Vec3f( mTrackedShapes[i].centroid.x, mTrackedShapes[i].centroid.y, 0.0f ); mTrackedShapes[i].mTrailPoint.arrive(centerVec); mTrackedShapes[i].mTrailPoint.updateTrail(); } } // if shape->matchFound is false, add it as a new shape for ( int i = 0; i < mShapes.size(); i++ ) { if( mShapes[i].matchFound == false ){ // assign an unique ID mShapes[i].ID = shapeUID; mShapes[i].lastFrameSeen = ci::app::getElapsedFrames(); // starting point of the trail mShapes[i].mTrailPoint.mLocation = Vec3f( mShapes[i].centroid.x, mShapes[i].centroid.y, 0.0f ); // add this new shape to tracked shapes mTrackedShapes.push_back( mShapes[i] ); shapeUID++; } } // if we didn't find a match for x frames, delete the tracked shape for ( vector<Shape>::iterator it = mTrackedShapes.begin(); it != mTrackedShapes.end(); ) { if ( ci::app::getElapsedFrames() - it->lastFrameSeen > 20 ) { // remove the tracked shape it = mTrackedShapes.erase(it); } else { ++it; } } mSurfaceDepth = Surface8u( fromOcv( mInput ) ); mSurfaceSubtract = Surface8u( fromOcv(eightBit) ); }
/** Frees up the internal resources used by the marshaling process for the given lexer. */ static void unbind( const FlexLexer * lexer ) { lmap().erase( lexer ); }