int Client::recommendedYieldMicros(){ int num = 0; { scoped_lock bl(clientsMutex); num = clients.size(); } if ( --num <= 0 ) // -- is for myself return 0; if ( num > 50 ) num = 50; num *= 100; return num; }
CollidablePolygon& SpinePoint::polygon() const { if (!_poly_is_dirty) return _polygon; if (is_empty() || !_previous) _polygon.set_start(_bottomLeft); else { Vector2 bl(_bottomLeft), br(_bottomRight); _polygon.set_start(bl); _polygon.add(br); _polygon.add(br.towards(_previous->base(),0.5)); ASSERT(!_polygon.collides_with(_previous->polygon())); } _poly_is_dirty = false; return _polygon; }
void dh_secret::create_symmetric_key(const util::bytes& pv) { u::mutex_scoped_lock bl(BOTAN_MUTEX); u::mutex_scoped_lock l(_mutex); INVARIANT(_pkey); b::PK_Key_Agreement k{*_pkey, KEY_AGREEMENT_ALGO}; _skey = std::make_shared<b::SymmetricKey>( k.derive_key( DH_KEY_SIZE, reinterpret_cast<const unsigned char*>(pv.data()), pv.size(), CONVERSATION_PARAM)); _other_pub_value = pv; ENSURE(_skey); }
void inProgCmd( Message &m, DbResponse &dbresponse ) { BSONObjBuilder b; if (!cc().getAuthorizationManager()->checkAuthorization( AuthorizationManager::SERVER_RESOURCE_NAME, ActionType::inprog)) { b.append("err", "unauthorized"); } else { DbMessage d(m); QueryMessage q(d); bool all = q.query["$all"].trueValue(); bool allMatching = q.query["$allMatching"].trueValue(); vector<BSONObj> vals; BSONObjBuilder qb; for (BSONObjIterator it(q.query); it.more(); ) { BSONElement e = it.next(); StringData fn(e.fieldName()); if (fn != "$all" && fn != "$allMatching") { qb.append(e); } } { Client& me = cc(); scoped_lock bl(Client::clientsMutex); scoped_ptr<Matcher> m(new Matcher(qb.done())); for( set<Client*>::iterator i = Client::clients.begin(); i != Client::clients.end(); i++ ) { Client *c = *i; verify( c ); CurOp* co = c->curop(); if ( c == &me && !co ) { continue; } verify( co ); if( all || allMatching || co->displayInCurop() ) { BSONObj info = co->info(); if ( all || m->matches( info )) { vals.push_back( info ); } } } } b.append("inprog", vals); } replyToQuery(0, m, dbresponse, b.obj()); }
// If we already have a stored, can we reuse it instead of also storing b? static bool equivalent(const SkBitmap& a, const SkBitmap& b) { if (a.info() != b.info() || a.pixelRefOrigin() != b.pixelRefOrigin()) { // Requiring a.info() == b.info() may be overkill in some cases (alphatype mismatch), // but it sure makes things easier to reason about below. return false; } if (a.pixelRef() == b.pixelRef()) { return true; // Same shape and same pixels -> same bitmap. } // From here down we're going to have to look at the bitmap data, so we require pixelRefs(). if (!a.pixelRef() || !b.pixelRef()) { return false; } // If the bitmaps have encoded data, check first before locking pixels so they don't decode. SkAutoTUnref<SkData> encA(a.pixelRef()->refEncodedData()), encB(b.pixelRef()->refEncodedData()); if (encA && encB) { return encA->equals(encB); } else if (encA || encB) { return false; // One has encoded data but the other does not. } // As a last resort, we have to look at the pixels. This will read back textures. SkAutoLockPixels al(a), bl(b); const char* ap = (const char*)a.getPixels(); const char* bp = (const char*)b.getPixels(); if (ap && bp) { // We check row by row; row bytes might differ. SkASSERT(a.info() == b.info()); // We checked this above. SkASSERT(a.info().bytesPerPixel() > 0); // If we have pixelRefs, this better be true. const SkImageInfo info = a.info(); const size_t bytesToCompare = info.width() * info.bytesPerPixel(); for (int row = 0; row < info.height(); row++) { if (0 != memcmp(ap, bp, bytesToCompare)) { return false; } ap += a.rowBytes(); bp += b.rowBytes(); } return true; } return false; // Couldn't get pixels for both bitmaps. }
int Client::getActiveClientCount( int& writers, int& readers ) { writers = 0; readers = 0; scoped_lock bl(clientsMutex); for ( set<Client*>::iterator i=clients.begin(); i!=clients.end(); ++i ) { Client* c = *i; if ( ! c->curop()->active() ) continue; if ( c->lockState().hasAnyWriteLock() ) writers++; if ( c->lockState().hasAnyReadLock() ) readers++; } return writers + readers; }
Client::Client(const string& desc, AbstractMessagingPort *p) : ClientBasic(p), _shutdown(false), _desc(desc), _god(0), _lastOp(0) { _hasWrittenSinceCheckpoint = false; _connectionId = p ? p->connectionId() : 0; _curOp = new CurOp( this ); #ifndef _WIN32 stringstream temp; temp << hex << showbase << pthread_self(); _threadId = temp.str(); #endif scoped_lock bl(clientsMutex); clients.insert(this); }
void sstSequence::DrawStar( vsDisplayList *list, int id ) { if ( m_targetActive[id] ) { vsVector2D pos = m_currentTransform.ApplyTo( m_segment[id].m_position ); vsVector2D tl( -5.0f, -5.0f ); vsVector2D tr( 5.0f, -5.0f ); vsVector2D bl( -5.0f, 5.0f ); vsVector2D br( 5.0f, 5.0f ); list->MoveTo( pos + tl ); list->LineTo( pos + br ); list->MoveTo( pos + tr ); list->LineTo( pos + bl ); } }
bool Client::shutdown() { #if defined(_DEBUG) && !defined(MONGO_OPTIMIZED_BUILD) && !XSAN_ENABLED { if( sizeof(void*) == 8 ) { StackChecker::check( desc() ); } } #endif _shutdown = true; if ( inShutdown() ) return false; { scoped_lock bl(clientsMutex); clients.erase(this); } return false; }
bool Client::shutdown() { #if defined(_DEBUG) { if( sizeof(void*) == 8 ) { StackChecker::check( desc() ); } } #endif _shutdown = true; if ( inShutdown() ) return false; { scoped_lock bl(clientsMutex); clients.erase(this); } return false; }
Shape::Shape(GLenum mode, const std::vector<glm::vec2>& vertices) : _mode(mode), _type(Type::VEC2), _scale(1.0f, 1.0f), _rotation(0), _need_update(false), _segments_need_update(true) { _vertices.reserve(2 * vertices.size()); glm::vec2 bl(std::numeric_limits<float>::max(), std::numeric_limits<float>::max());; glm::vec2 tr(std::numeric_limits<float>::min(), std::numeric_limits<float>::min()); for (const auto& v : vertices) { _vertices.push_back(v.x); _vertices.push_back(v.y); bl.x = std::min(bl.x, v.x); tr.x = std::max(tr.x, v.x); bl.y = std::min(bl.y, v.y); tr.y = std::max(tr.y, v.y); } _aabb.first = bl; _aabb.second = tr; init_vao(); }
void doUnlockedStuff(stringstream& ss) { /* this is in the header already ss << "port: " << port << '\n'; */ ss << mongodVersion() << "\n"; ss << "git hash: " << gitVersion() << "\n"; ss << "sys info: " << sysInfo() << "\n"; ss << "\n"; ss << "dbwritelocked: " << dbMutex.info().isLocked() << " (initial)\n"; ss << "uptime: " << time(0)-started << " seconds\n"; if ( replAllDead ) ss << "<b>replication replAllDead=" << replAllDead << "</b>\n"; ss << "\nassertions:\n"; for ( int i = 0; i < 4; i++ ) { if ( lastAssert[i].isSet() ) { ss << "<b>"; if ( i == 3 ) ss << "usererr"; else ss << i; ss << "</b>" << ' ' << lastAssert[i].toString(); } } ss << "\nreplInfo: " << replInfo << "\n\n"; ss << "Clients:\n"; ss << "<table border=1><tr align='left'><th>Thread</th><th>Current op</th>\n"; { boostlock bl(Client::clientsMutex); for( set<Client*>::iterator i = Client::clients.begin(); i != Client::clients.end(); i++ ) { Client *c = *i; CurOp& co = *(c->curop()); ss << "<tr><td>" << c->desc() << "</td><td"; BSONObj info = co.infoNoauth(); /* if( info.getIntField("inLock") > 0 ) ss << "style='color:red'"; else if( info.getIntField("inLock") < 0 ) ss << "style='color:green'"; */ ss << ">" << info << "</td></tr>\n"; } } ss << "</table>\n"; }
const CtrlrMidiMessageEx CtrlrSysexProcessor::sysexMessageFromString (const String &formula, const int value, const int channel) { MidiMessage m; MemoryBlock bl(0,true); StringArray tokens; tokens.addTokens (formula, " ;:", "\""); for (int i=0; i<tokens.size(); i++) { const int d = jmin<int> (tokens[i].getHexValue32(),255); bl.append (&d, 1); } Array <CtrlrSysexToken> tokenArray = sysExToTokenArray(formula); CtrlrMidiMessageEx mex; mex.m = MidiMessage (bl.getData(), bl.getSize()); mex.setTokenArray(tokenArray); return (mex); }
void inProgCmd( Message &m, DbResponse &dbresponse ) { BSONObjBuilder b; if( ! cc().isAdmin() ) { b.append("err", "unauthorized"); } else { DbMessage d(m); QueryMessage q(d); bool all = q.query["$all"].trueValue(); vector<BSONObj> vals; { Client& me = cc(); scoped_lock bl(Client::clientsMutex); auto_ptr<Matcher> m(new Matcher(q.query)); for( set<Client*>::iterator i = Client::clients.begin(); i != Client::clients.end(); i++ ) { Client *c = *i; assert( c ); CurOp* co = c->curop(); if ( c == &me && !co ) { continue; } assert( co ); if( all || co->active() ) { BSONObj info = co->infoNoauth(); if ( all || m->matches( info )) { vals.push_back( info ); } } } } b.append("inprog", vals); unsigned x = lockedForWriting; if( x ) { b.append("fsyncLock", x); b.append("info", "use db.fsyncUnlock() to terminate the fsync write/snapshot lock"); } } replyToQuery(0, m, dbresponse, b.obj()); }
void inProgCmd( Message &m, DbResponse &dbresponse ) { BSONObjBuilder b; if (!cc().getAuthorizationManager()->checkAuthorization( AuthorizationManager::SERVER_RESOURCE_NAME, ActionType::inprog)) { b.append("err", "unauthorized"); } else { DbMessage d(m); QueryMessage q(d); bool all = q.query["$all"].trueValue(); vector<BSONObj> vals; { Client& me = cc(); scoped_lock bl(Client::clientsMutex); scoped_ptr<Matcher> m(new Matcher(q.query)); for( set<Client*>::iterator i = Client::clients.begin(); i != Client::clients.end(); i++ ) { Client *c = *i; verify( c ); CurOp* co = c->curop(); if ( c == &me && !co ) { continue; } verify( co ); if( all || co->displayInCurop() ) { BSONObj info = co->info(); if ( all || m->matches( info )) { vals.push_back( info ); } } } } b.append("inprog", vals); if( lockedForWriting() ) { b.append("fsyncLock", true); b.append("info", "use db.fsyncUnlock() to terminate the fsync write/snapshot lock"); } } replyToQuery(0, m, dbresponse, b.obj()); }
void LibHandMetadata::log_metric_bb() const { // draw the metric bb Mat metric_viz = imageeq("",Z.clone(),false,false); Point bl(handBB.tl().x,handBB.br().y); Point tr(handBB.br().x,handBB.tl().y); cv::line(metric_viz,handBB.tl(),bl,toScalar(RED)); cv::line(metric_viz,handBB.br(),bl,toScalar(GREEN)); // compute edge lengths using law of cosines double z = medianApx(Z,handBB,.5); double t1 = camera.distance_angular(handBB.tl(),bl); double d1 = camera.distance_geodesic(handBB.tl(),z,bl,z); double t2 = camera.distance_angular(handBB.br(),bl); double d2 = camera.distance_geodesic(handBB.br(),z,bl,z); Mat text = vertCat(image_text(safe_printf("% cm % rad",d1,t1),RED), image_text(safe_printf("% cm % rad",d2,t2),GREEN)); text = vertCat(text,image_text(safe_printf("% cm",z))); log_im("MetricBBSides",vertCat(metric_viz,text)); }
BoxList& BoxList::intersect (const BoxList& b) { BL_ASSERT(ixType() == b.ixType()); BoxList bl(b.ixType()); for (iterator lhs = begin(); lhs != end(); ++lhs) { for (const_iterator rhs = b.begin(), End = b.end(); rhs != End; ++rhs) { const Box& bx = *lhs & *rhs; if (bx.ok()) bl.push_back(bx); } } *this = bl; return *this; }
void Camera::drawPhysics(unsigned int flags) const { glPushMatrix(); glMultMatrixf(transformation); if(flags & SimRobotCore2::Renderer::showSensors) { Vector3<> ml(1.f, -tan(angleX * 0.5f), 0); Vector3<> mt(1.f, 0, tan(angleY * 0.5f)); Vector3<> tl(1.f, ml.y, mt.z); Vector3<> tr(1.f, -ml.y, mt.z); Vector3<> bl(1.f, ml.y, -mt.z); Vector3<> br(1.f, -ml.y, -mt.z); glBegin(GL_LINE_LOOP); glColor3f(0, 0, 0.5f); glNormal3f (0, 0, 1.f); glVertex3f(tl.x, tl.y, tl.z); glVertex3f(tr.x, tr.y, tr.z); glVertex3f(br.x, br.y, br.z); glVertex3f(bl.x, bl.y, bl.z); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(tl.x, tl.y, tl.z); glVertex3f(0.f, 0.f, 0.f); glVertex3f(tr.x, tr.y, tr.z); glEnd(); glBegin(GL_LINE_STRIP); glVertex3f(bl.x, bl.y, bl.z); glVertex3f(0.f, 0.f, 0.f); glVertex3f(br.x, br.y, br.z); glEnd(); } PhysicalObject::drawPhysics(flags); glPopMatrix(); }
void Adina::DebugRenderer::drawBox(const glm::vec4& destRect, const ColorRGBA8& color, float angle) { int i = m_verts.size(); m_verts.resize(m_verts.size() + 4); glm::vec2 halfDims(destRect.z / 2.0f, destRect.w / 2.0f); // Get points centered at origin glm::vec2 tl(-halfDims.x, halfDims.y); glm::vec2 bl(-halfDims.x, -halfDims.y); glm::vec2 br(halfDims.x, -halfDims.y); glm::vec2 tr(halfDims.x, halfDims.y); glm::vec2 positionOffset(destRect.x, destRect.y); // Rotate the points m_verts[i].position = rotatePoint(tl, angle) + halfDims + positionOffset; m_verts[i + 1].position = rotatePoint(bl, angle) + halfDims + positionOffset; m_verts[i + 2].position = rotatePoint(br, angle) + halfDims + positionOffset; m_verts[i + 3].position = rotatePoint(tr, angle) + halfDims + positionOffset; for (int j = i; j < i + 4; j++) { m_verts[j].color = color; } m_indices.reserve(m_indices.size() + 8); m_indices.push_back(i); m_indices.push_back(i + 1); m_indices.push_back(i + 1); m_indices.push_back(i + 2); m_indices.push_back(i + 2); m_indices.push_back(i + 3); m_indices.push_back(i + 3); m_indices.push_back(i); }
int Client::recommendedYieldMicros( int * writers , int * readers, bool needExact ) { int num = 0; int w = 0; int r = 0; { scoped_lock bl(clientsMutex); for ( set<Client*>::iterator i=clients.begin(); i!=clients.end(); ++i ) { Client* c = *i; if ( c->lockState().hasLockPending() ) { num++; if ( c->lockState().hasAnyWriteLock() ) w++; else r++; } if (num > 100 && !needExact) break; } } if ( writers ) *writers = w; if ( readers ) *readers = r; int time = r * 10; // we have to be nice to readers since they don't have priority time += w; // writers are greedy, so we can be mean tot hem time = min( time , 1000000 ); // if there has been a kill request for this op - we should yield to allow the op to stop // This function returns empty string if we aren't interrupted if ( *killCurrentOp.checkForInterruptNoAssert() ) { return 100; } return time; }
void antPlane::generateVertices() { float sx = m_width / m_nColumns; float sz = m_depth / m_nRows; m_vertices = ( GLfloat * ) malloc( N_VERTEX_ATTRIBS * m_nVertices * sizeof( GLfloat ) ); for ( int i = 0; i < m_nRows; i++ ) { for ( int j = 0; j < m_nColumns; j++ ) { antVec3 bl( j * sx - m_width / 2.f, 0.f, i * sz - m_depth / 2.f ); // bottom left antVec3 tl( j * sx - m_width / 2.f, 0.f, ( i + 1 ) * sz - m_depth / 2.f ); // top left antVec3 tr( ( j + 1 ) * sx - m_width / 2.f, 0.f, ( i + 1 ) * sz - m_depth / 2.f ); // top right antVec3 br( ( j + 1 ) * sx - m_width / 2.f, 0.f, i * sz - m_depth / 2.f ); // bottom right int v = (i * m_nColumns + j) * 6 * N_VERTEX_ATTRIBS; for ( int n = 0; n < N_VERTEX_ATTRIBS; n++ ) { m_vertices[ v + n ] = bl.v[n]; m_vertices[ v + (1 * N_VERTEX_ATTRIBS) + n ] = tl.v[n]; m_vertices[ v + (2 * N_VERTEX_ATTRIBS) + n ] = tr.v[n]; m_vertices[ v + (3 * N_VERTEX_ATTRIBS) + n ] = tr.v[n]; m_vertices[ v + (4 * N_VERTEX_ATTRIBS) + n ] = br.v[n]; m_vertices[ v + (5 * N_VERTEX_ATTRIBS) + n ] = bl.v[n]; } } } m_hasVertices = true; bindVao(0); bindVbo(0); setData( m_nVertices * N_VERTEX_ATTRIBS * sizeof(GLfloat), m_vertices ); attrib( ATTR_POSITION_LOC, N_VERTEX_ATTRIBS ); enableVertices(); }
vector<Point> CharacterAnalysis::getCharArea(LineSegment topLine, LineSegment bottomLine) { const int MAX = 100000; const int MIN= -1; int leftX = MAX; int rightX = MIN; for (unsigned int i = 0; i < bestContours.size(); i++) { if (bestContours.goodIndices[i] == false) continue; for (unsigned int z = 0; z < bestContours.contours[i].size(); z++) { if (bestContours.contours[i][z].x < leftX) leftX = bestContours.contours[i][z].x; if (bestContours.contours[i][z].x > rightX) rightX = bestContours.contours[i][z].x; } } vector<Point> charArea; if (leftX != MAX && rightX != MIN) { Point tl(leftX, topLine.getPointAt(leftX)); Point tr(rightX, topLine.getPointAt(rightX)); Point br(rightX, bottomLine.getPointAt(rightX)); Point bl(leftX, bottomLine.getPointAt(leftX)); charArea.push_back(tl); charArea.push_back(tr); charArea.push_back(br); charArea.push_back(bl); } return charArea; }
GRect GetTransformedBoundingBox(const GRect &r) { // Top Left GVec3f tl(r.fLeft, r.fTop, 1.0f); // Top right GVec3f tr(r.fRight, r.fTop, 1.0f); // Bottom left GVec3f bl(r.fLeft, r.fBottom, 1.0f); // Bottom right GVec3f br(r.fRight, r.fBottom, 1.0f); tl = m_CTM * tl; tr = m_CTM * tr; bl = m_CTM * bl; br = m_CTM * br; GRect ret = GRect::MakeXYWH(tl.X(), tl.Y(), 0, 0); AddPoint(ret, tr); AddPoint(ret, bl); AddPoint(ret, br); return ret; }
void Rect::calcVecCoords() { Vector3 tl(-w / 2.0f, -h / 2.0f, 0.0f); Vector3 tr( w / 2.0f, -h / 2.0f, 0.0f); Vector3 bl(-w / 2.0f, h / 2.0f, 0.0f); Vector3 br( w / 2.0f, h / 2.0f, 0.0f); float radians = toRadians(degrees); vecCoords[0].x = center.x + tl.x * cos(radians) - tl.y * sin(radians); vecCoords[0].y = center.y + tl.x * sin(radians) + tl.y * cos(radians); vecCoords[0].z = center.z; vecCoords[1].x = center.x + tr.x * cos(radians) - tr.y * sin(radians); vecCoords[1].y = center.y + tr.x * sin(radians) + tr.y * cos(radians); vecCoords[1].z = center.z; vecCoords[2].x = center.x + bl.x * cos(radians) - bl.y * sin(radians); vecCoords[2].y = center.y + bl.x * sin(radians) + bl.y * cos(radians); vecCoords[2].z = center.z; vecCoords[3].x = center.x + br.x * cos(radians) - br.y * sin(radians); vecCoords[3].y = center.y + br.x * sin(radians) + br.y * cos(radians); vecCoords[3].z = center.z; }
void inProgCmd( Message &m, DbResponse &dbresponse ) { BSONObjBuilder b; AuthenticationInfo *ai = cc().ai; if( !ai->isAuthorized("admin") ) { BSONObjBuilder b; b.append("err", "unauthorized"); } else { vector<BSONObj> vals; { boostlock bl(Client::clientsMutex); for( set<Client*>::iterator i = Client::clients.begin(); i != Client::clients.end(); i++ ) { Client *c = *i; CurOp& co = *(c->curop()); if( co.active ) vals.push_back( co.infoNoauth() ); } } b.append("inprog", vals); } replyToQuery(0, m, dbresponse, b.obj()); }
int main(int argc, char *argv[]) { QApplication a(argc, argv); QLabel ww; ww.setPixmap(QPixmap("qt-logo.png")); //qDebug("wid=%d", (int)ww.winId()); QVBoxLayout vl; ww.setLayout(&vl); QAeroWidget aero_widget; //w.setWindowFlags(Qt::Window | Qt::WindowStaysOnTopHint); aero_widget.setEffect(QAeroWidget::Aero); aero_widget.setEffectOpacity(0.1); QLabel text(&aero_widget); text.setText("<font color=#ff0000 size=22>Aero Widget</font>"); QAeroWidget blur_widget; blur_widget.setEffect(QAeroWidget::Blur); blur_widget.setEffectOpacity(0.1); QLabel bl(&blur_widget); bl.setText("<font color=#ff00ff size=22>Blur Widget</font>"); QAeroWidget st_widget; st_widget.setEffect(QAeroWidget::SemiTransparent); st_widget.setEffectOpacity(0.1); QLabel stl(&st_widget); stl.setText("<font color=#ffff00 size=22>SemiTransparent Widget</font>"); QLabel normal_text; normal_text.setText("<font color=#0000ff size=22>Normal Widget</font>"); vl.addWidget(&aero_widget); vl.addWidget(&blur_widget); vl.addWidget(&st_widget); vl.addWidget(&normal_text); ww.show(); QAeroWidget aero_window; aero_window.setEffect(QAeroWidget::Aero); //aero_window.setEffectOpacity(0.618); //aero_window.setWindowFlags(Qt::FramelessWindowHint); QLabel text_aw(&aero_window); text_aw.setText("<font color=#ff0000 size=22>Aero Window</font>"); aero_window.show(); aero_window.resize(text_aw.size()); QAeroWidget blur_window; blur_window.setEffect(QAeroWidget::Blur); QLabel text_awbb(&blur_window); text_awbb.setText("<font color=#ff0000 size=22>Blur Window</font>"); blur_window.show(); blur_window.resize(text_awbb.size()); QAeroWidget semitransparent_window; semitransparent_window.setEffect(QAeroWidget::SemiTransparent); semitransparent_window.setEffectOpacity(0.618); QLabel text_semitransparent_window(&semitransparent_window); text_semitransparent_window.setText("<font color=#ff0000 size=22>SemiTransparent Window</font>"); semitransparent_window.show(); semitransparent_window.resize(text_semitransparent_window.size()); return a.exec(); }
GameObject* Terrain::CreateGameObject(const char* diffuseTxt_filename, const char* normalTxt_filename, const char* heightTxt_filemane) { std::vector<float2> texture_coordinate = calculateTextureCoordiate(); std::vector<float2> boundsY = CalcAllPatchBoundsY(); const int iNumVertices = m_initInfo.HeightmapWidth / 8 * (m_initInfo.HeightmapHeight) / 8 * 4; const int iNumIndices = iNumVertices; VertexTerrain* vertices = new VertexTerrain[iNumVertices]; unsigned int* indices = new unsigned int[iNumIndices]; // Translate the terrain, so that the mid-point of terrain is at (0, 0, 0) Matrix4 translate; translate.CreateTranslation(Vector3(-GetWidth() / 2.0f, 0.0f, -GetDepth() / 2.0f)); // Initialize the index to the vertex buffer. int indexCounter = 0; // Load the vertex and index array with the terrain data. for (int j = 0; j < m_initInfo.HeightmapHeight - 8; j += 8) { for (int i = 0; i < m_initInfo.HeightmapWidth - 8; i += 8) { const int index_bl = m_initInfo.HeightmapWidth * j + i; const int index_br = m_initInfo.HeightmapWidth * j + (i + 8); const int index_ul = m_initInfo.HeightmapWidth * (j + 8) + i; const int index_ur = m_initInfo.HeightmapWidth * (j + 8) + (i + 8); const float2 bl_uv( texture_coordinate[index_bl].x, texture_coordinate[index_bl].y ); const float2 br_uv( (texture_coordinate[index_br].x == 0.0f ? 1.0f : texture_coordinate[index_br].x), texture_coordinate[index_br].y ); const float2 ul_uv( texture_coordinate[index_ul].x, (texture_coordinate[index_ul].y == 1.0f ? 0.0f : texture_coordinate[index_ul].y) ); const float2 ur_uv( (texture_coordinate[index_ur].x == 0.0f ? 1.0f : texture_coordinate[index_ur].x), (texture_coordinate[index_ur].y == 1.0f ? 0.0f : texture_coordinate[index_ur].y) ); Vector3 bl(i * m_initInfo.CellSpacing, m_HeightMap[index_bl] * m_initInfo.CellSpacing, j* m_initInfo.CellSpacing); Vector3 br((i + 8)* m_initInfo.CellSpacing, m_HeightMap[index_br] * m_initInfo.CellSpacing, j* m_initInfo.CellSpacing); Vector3 ul(i* m_initInfo.CellSpacing, m_HeightMap[index_ul] * m_initInfo.CellSpacing, (j + 8)* m_initInfo.CellSpacing); Vector3 ur((i + 8)* m_initInfo.CellSpacing, m_HeightMap[index_ur] * m_initInfo.CellSpacing, (j + 8)* m_initInfo.CellSpacing); const int patch_id = j + (i / m_initInfo.CellsPerPatch); // bottom left { vertices[indexCounter].m_pos = bl; vertices[indexCounter].m_UV[0] = bl_uv.x; vertices[indexCounter].m_UV[1] = bl_uv.y; vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x; vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y; indices[indexCounter] = indexCounter; indexCounter++; } // bottom right { vertices[indexCounter].m_pos = br; vertices[indexCounter].m_UV[0] = br_uv.x; vertices[indexCounter].m_UV[1] = br_uv.y; vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x; vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y; indices[indexCounter] = indexCounter; indexCounter++; } // upper left { vertices[indexCounter].m_pos = ul; vertices[indexCounter].m_UV[0] = ul_uv.x; vertices[indexCounter].m_UV[1] = ul_uv.y; vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x; vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y; indices[indexCounter] = indexCounter; indexCounter++; } // upper right { vertices[indexCounter].m_pos = ur; vertices[indexCounter].m_UV[0] = ur_uv.x; vertices[indexCounter].m_UV[1] = ur_uv.y; vertices[indexCounter].m_boundsY[0] = boundsY[patch_id].x; vertices[indexCounter].m_boundsY[1] = boundsY[patch_id].y; indices[indexCounter] = indexCounter; indexCounter++; } } } std::string diffuseTxt_filepath = std::string("../Assets/") + diffuseTxt_filename; std::string normalTxt_filepath = std::string("../Assets/") + normalTxt_filename; std::string heightTxt_filepath = std::string("../Assets/") + heightTxt_filemane; MeshData* meshData = new MeshData(vertices, iNumVertices, indices, iNumIndices, sizeof(VertexTerrain)); meshData->SetBoundingBox(AABB(Vector3(0, 0, 0), Vector3(m_initInfo.HeightmapHeight, 0, m_initInfo.HeightmapWidth))); Handle hMeshComp(sizeof(MeshComponent)); new (hMeshComp) MeshComponent(meshData); SceneGraph::GetInstance()->AddComponent((MeshComponent*) hMeshComp.Raw()); RenderPass* renderPass = new RenderPass; renderPass->SetVertexShader("../DEngine/Shaders/VS_terrain.hlsl"); renderPass->SetHullShader("../DEngine/Shaders/HS_terrain.hlsl"); renderPass->SetDomainShader("../DEngine/Shaders/DS_terrain.hlsl"); renderPass->SetPixelShader("../DEngine/Shaders/PS_terrain.hlsl"); Handle hTexture1(sizeof(Texture)); new (hTexture1) Texture(Texture::SHADER_RESOURCES, 1, diffuseTxt_filepath.c_str()); Handle hTexture2(sizeof(Texture)); new (hTexture2) Texture(Texture::SHADER_RESOURCES, 1, normalTxt_filepath.c_str()); Handle hTexture3(sizeof(Texture)); new (hTexture3) Texture(Texture::SHADER_RESOURCES, 1, heightTxt_filepath.c_str()); renderPass->AddTexture(hTexture1); renderPass->AddTexture(hTexture2); renderPass->AddTexture(hTexture3); renderPass->SetTopology(D3D_PRIMITIVE_TOPOLOGY_4_CONTROL_POINT_PATCHLIST); renderPass->SetBlendState(State::NULL_STATE); renderPass->SetRenderTargets(D3D11Renderer::GetInstance()->m_pRTVArray, 2); renderPass->SetDepthStencilView(D3D11Renderer::GetInstance()->m_depth->GetDSV()); renderPass->SetDepthStencilState(State::DEFAULT_DEPTH_STENCIL_DSS); renderPass->SetRasterizerState(State::CULL_BACK_RS); ((MeshComponent*) hMeshComp.Raw())->m_pMeshData->m_Material.AddPassToTechnique(renderPass); GameObject* terrain = new GameObject; terrain->AddComponent((Component*) hMeshComp.Raw()); delete[] vertices; delete[] indices; return terrain; }
//-------------------------------------------------------------- void testApp::setup(){ ofSetFrameRate(60); ofSetVerticalSync(true); // just used to draw the wireframe squareMesh.tl = ofVec2f(0, 0); squareMesh.tr = ofVec2f(400, 0); squareMesh.bl = ofVec2f(0, 400); squareMesh.br = ofVec2f(400, 400); ofVec2f squareBounds( 400, 400 ); squareWorld.setupSquare( squareBounds ); squareWorld.setOption( ofxLabFlexParticleSystem::HORIZONTAL_WRAP, true ); ofVec2f tl(0, 0); ofVec2f bl(50, 400); ofVec2f tr(500, 0); ofVec2f br(400, 400); quadWorld.setupQuad( tl, bl, tr, br ); // print callbacks squareWorld.setWallCallback( tr1::bind(&testApp::wallCallbackSquare, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::TOP_WALL, false ); // don't override squareWorld.setWallCallback( tr1::bind(&testApp::wallCallbackSquare, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::BOTTOM_WALL, false ); // don't override squareWorld.setWallCallback( tr1::bind(&testApp::wallCallbackSquare, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::LEFT_WALL, false ); // don't override squareWorld.setWallCallback( tr1::bind(&testApp::wallCallbackSquare, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::RIGHT_WALL, false ); // don't override quadWorld.setWallCallback( tr1::bind(&testApp::wallCallbackQuad, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::TOP_WALL, false ); // don't override quadWorld.setWallCallback( tr1::bind(&testApp::wallCallbackQuad, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::BOTTOM_WALL, false ); // don't override quadWorld.setWallCallback( tr1::bind(&testApp::wallCallbackQuad, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::LEFT_WALL, false ); // don't override quadWorld.setWallCallback( tr1::bind(&testApp::wallCallbackQuad, this, tr1::placeholders::_1), ofxLabFlexParticleSystem::RIGHT_WALL, false ); // don't override ofVec3f pos(200, 200); ofVec3f velocity( ofRandom(-5, 5), ofRandom(-5, 5), 0 ); ofVec3f rotation( 0, 0, 0 ); ofVec3f rotationVelocity( 0, 0, 0 ); float radius = 10; float damping = 1.0f; ofxLabFlexParticleOptions pOpts( pos, velocity, rotation, rotationVelocity, radius, damping); // make two particles particles.push_back( ofxLabFlexParticle( pOpts ) ); particles.push_back( ofxLabFlexParticle( pOpts ) ); // add particles to diff systems squareWorld.addParticle( &particles[0] ); quadWorld.addParticle( &particles[1] ); ofSetWindowShape(1200, 600); }
void erase(MessagingPort* p) { stdx::lock_guard<stdx::mutex> bl(m); ports.erase(p); }
void GridCollector::stepFinished( const GridCollector::GridType& grid, const GridCollector::RegionType& validRegion, const GridCollector::CoordType& globalDimensions, unsigned step, LibGeoDecomp::WriterEvent event, std::size_t rank, bool lastCall) { { Mutex::scoped_lock l(mutex); if(!collectorServerId) { std::string name(VANDOUKEN_GRIDCOLLECTOR_NAME); name += "/"; name += boost::lexical_cast<std::string>(rank); collectorServerId = hpx::components::new_<GridCollectorServer>(hpx::find_here(), this).get(); hpx::agas::register_name_sync(name, collectorServerId); std::cout << "registered: " << name << "\n"; } } if(step == 0) timer.restart(); if(lastCall && step % 10 == 0 && rank == 0) { std::cout << "Simulation at step " << step << " (FPS: " << step/timer.elapsed() << ")" << "\n"; } Mutex::scoped_lock l(mutex); if(!ids.empty()) { Mutex::scoped_lock bl(bufferMutex); BufferMap::iterator it = buffers.find(step); if(it == buffers.end()) { it = buffers.insert( it , std::make_pair( step , RegionBuffer( boost::make_shared<Particles>() , validRegion ) ) ); it->second.buffer->reserve(globalDimensions.prod()); } else { it->second.region += validRegion; } for (RegionType::StreakIterator i = validRegion.beginStreak(); i != validRegion.endStreak(); ++i) { GridType::ConstIterator src = grid.at(i->origin); //it->second->resize(i->length()); for(int j = 0; j < i->length(); ++j) { ParticleConverter()(*src, globalDimensions, *it->second.buffer); ++src; } } /* std::cout << it->second->size() << "\n"; if(lastCall) std::cout << "\n"; */ } }