bool PlayerEntity::findFirstCollision (const Array<Tri>& triArray, const Vector3& velocity, float& stepTime, Vector3& collisionNormal, Point3& collisionPoint) const { bool collision = false; const Sphere& startSphere = collisionProxy(); for (int t = 0; t < triArray.size(); ++t) { const Tri& tri = triArray[t]; const CPUVertexArray& cpuVertexArray = ((PhysicsScene*)m_scene)->getCPUVertexArrayOfCollisionTree(); Triangle triangle(tri.position(cpuVertexArray,0),tri.position(cpuVertexArray,1), tri.position(cpuVertexArray,2)); Vector3 C; const float d = CollisionDetection::collisionTimeForMovingSphereFixedTriangle (startSphere, velocity, triangle, C); if (d < stepTime) { // Found a new collision sooner than the previous one. const Vector3& centerAtCollisionTime = startSphere.center + velocity * d; const Vector3& delta = centerAtCollisionTime - C; // Distance from sphere to collision point; if this is less than the sphere radius, // the collision was interpenetarat const float r = delta.length(); const Vector3& n = delta / r; static const float epsilon = 0.000001f; const bool interpenetration = (r < startSphere.radius - epsilon); const bool rightDirection = (dot(n, velocity) < -epsilon); if (interpenetration || rightDirection) { // Normal to the sphere at the collision point collisionNormal = n; collisionPoint = C; stepTime = d; collision = true; } } } # ifdef SHOW_COLLISIONS if (collision) { if (collisionNormal.y < 0.99f) { //runSimulation = false; const float duration = 1.0f; debugDraw(new SphereShape(Sphere(collisionPoint, 0.1f)), duration, Color3::red(), Color4::clear()); debugDraw(new ArrowShape(collisionPoint, collisionNormal), duration, Color3::red(), Color4::clear()); } } # endif return collision; }
void kinactorApp::draw() { setFullScreen(); switch (currentFormat) { case kinactor: kinactorDraw(); break; case debug: debugDraw(); break; case cloud: ofPushMatrix(); ofTranslate(420, 320); // we need a proper camera class drawPointCloud(); ofPopMatrix(); default: break; } // show interface? bShowInterface == true ? showInterface() : hideInterface(); }
void GLWidget::drawMesh() { CudaLinearBvh * bvh = m_mesh->bvh(); Aabb ab = bvh->bound(); if(ab.low.x < -1e8 || ab.low.x > 1e8) std::cout<<" invalid big box "<<aabb_str(ab); #ifdef BVHSOLVER_DBG_DRAW unsigned numInternal = bvh->numInternalNodes(); debugDraw(*m_rootNodeInd, numInternal); #else GeoDrawer * dr = getDrawer(); BoundingBox bb; bb.setMin(ab.low.x, ab.low.y, ab.low.z); bb.setMax(ab.high.x, ab.high.y, ab.high.z); dr->boundingBox(bb); #endif #ifdef BVHSOLVER_DRAW_MESH glColor3f(0.f, 0.3f, 0.5f); //internalTimer()->stop(); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(3, GL_FLOAT, 0, (GLfloat*)m_mesh->vertices()); glDrawElements(GL_TRIANGLES, m_mesh->numTriangleFaceVertices(), GL_UNSIGNED_INT, m_mesh->triangleIndices()); glDisableClientState(GL_VERTEX_ARRAY); #endif }
void PhysicsWorld::update(float delta) { if (_delayDirty) { // the updateJoints must run before the updateBodies. updateJoints(); updateBodies(); _delayDirty = !(_delayAddBodies.size() == 0 && _delayRemoveBodies.size() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } for (auto& body : _bodies) { body->update(delta); } _updateTime += delta; if (++_updateRateCount >= _updateRate) { _info->step(_updateTime * _speed); _updateRateCount = 0; _updateTime = 0.0f; } if (_debugDrawMask != DEBUGDRAW_NONE) { debugDraw(); } }
//-------------------------------------------------------------- void ofApp::draw(){ debugDraw(); ofPushMatrix(); ofTranslate(ofGetWidth() * 0.5, ofGetHeight() * 0.5); //mesh.drawFaces(); // Draw rectangles on each vertex position // with a radius based on the z-position for(int i=0; i<mesh.getNumVertices(); i++){ ofVec3f vertex = mesh.getVertex(i); ofColor color = mesh.getColor(i); i%9 == 0 ? ofFill() : ofNoFill(); ofSetColor(color); ofSetCircleResolution( i%2 == 0 ? 4 : 3 ); ofPushMatrix(); ofTranslate(vertex); ofRotateZ(ofGetFrameNum() * i * 0.25); ofDrawCircle(0, 0, vertex.z * 0.1); ofPopMatrix(); } ofPopMatrix(); }
void PointSolver2::solve (cv::Mat &inputImage, Point3 &startPos, Quaternion &startOrientation) { assert (inputImage.type() == CV_8UC1); position0 = startPos; orientation0 = startOrientation; image = inputImage; prepareImage (); #define ITERATION 5 for (int np=0; np<ITERATION; np++) { currentViewMatrix = createViewMatrix (position0, orientation0); projectLines (); findNearestLinePerPoint (); prepareMatrices (); solveForCorrection (); } // currentViewMatrix = createViewMatrix (position0, orientation0); debugDraw ("/tmp/draw.png", &position0, &orientation0); return; }
void DynamicLight::draw(cocos2d::Renderer *renderer, const cocos2d::Mat4 &transform, bool transformUpdated) { if (!bakedMapIsValid) { bakedMapIsValid = true; updateUniforms(); updateShadowMap(renderer, transform, transformUpdated); finalShadowMap->getSprite()->setColor({color.r, color.g, color.b}); finalShadowMap->getSprite()->setGLProgram(shadowRenderShader); finalShadowMap->getSprite()->setAnchorPoint({0, 0}); finalShadowMap->getSprite()->setPosition({0, 0}); finalShadowMap->setScaleY(-1); bakedShadowMap->beginWithClear(0.0, 0.0, 0.0, 0.0); finalShadowMap->setAnchorPoint({0.5, 0.5}); finalShadowMap->setPosition({0, 0}); finalShadowMap->visit(renderer, transform, transformUpdated); bakedShadowMap->end(); bakedShadowMap->setPosition({0, 0}); if (additive) { bakedShadowMap->getSprite()->setBlendFunc({GL_SRC_ALPHA, GL_ONE}); } } bakedShadowMap->visit(renderer, transform, transformUpdated); if (debugDrawEnabled) { debugDraw(renderer, transform, transformUpdated); } }
void PlayerEntity::getConservativeCollisionTris(Array<Tri>& triArray, const Vector3& velocity, float deltaTime) const { Sphere nearby = collisionProxy(); nearby.radius += velocity.length() * deltaTime; ((PhysicsScene*)m_scene)->staticIntersectSphere(nearby, triArray); # ifdef SHOW_COLLISIONS //debugDraw(new SphereShape(nearby), 0, Color4::clear(), Color3::black()); debugDraw(new MeshShape(triArray), 0, Color3::cyan(), Color3::blue()); # endif }
void PhysicsWorld::update(float delta, bool userCall/* = false*/) { if (delta < FLT_EPSILON) { return; } if(_updateBodyTransform || !_delayAddBodies.empty()) { _scene->updatePhysicsBodyTransform(_scene->getNodeToParentTransform(), 0, 1.0f, 1.0f); updateBodies(); _updateBodyTransform = false; } else if (!_delayRemoveBodies.empty()) { updateBodies(); } if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty()) { updateJoints(); } if (userCall) { cpSpaceStep(_cpSpace, delta); for (auto& body : _bodies) { body->update(delta); } } else { _updateTime += delta; if (++_updateRateCount >= _updateRate) { const float dt = _updateTime * _speed / _substeps; for (int i = 0; i < _substeps; ++i) { cpSpaceStep(_cpSpace, dt); for (auto& body : _bodies) { body->update(dt); } } _updateRateCount = 0; _updateTime = 0.0f; } } if (_debugDrawMask != DEBUGDRAW_NONE) { debugDraw(); } }
Sprite::Sprite(void) : _batchNode(nullptr) , _shouldBeHidden(false) , _texture(nullptr) , _spriteFrame(nullptr) , _insideBounds(true) { #if CC_SPRITE_DEBUG_DRAW debugDraw(true); #endif //CC_SPRITE_DEBUG_DRAW }
void Box2DDebugDraw::paint(QPainter *p) { if (!mWorld) return; // Darken the view to make the debug draw stand out more p->fillRect(0, 0, width(), height(), QColor(0, 0, 0, 128)); DebugDraw debugDraw(p, mWorld); debugDraw.draw(); }
//-------------------------------------------------------------- void ofApp::draw(){ debugDraw(); ofPushMatrix(); ofTranslate(360, 50); fbo.draw(0, 0, 768, 240); ofPopMatrix(); }
//-------------------------------------------------------------- void ofApp::draw(){ debugDraw(); ofPushMatrix(); ofTranslate(ofGetWidth()*0.6, ofGetHeight()*0.5); flock.draw(); ofPopMatrix(); }
//-------------------------------------------------------------- void ofApp::draw(){ debugDraw(); ofPushMatrix(); ofTranslate(360, 310); difference.draw(0, 0, 320, 240); ofPopMatrix(); }
void Box2DDebugDraw::paint(QPainter *p, const QStyleOptionGraphicsItem *, QWidget *) { if (!mWorld) return; // Darken the view to make the debug draw stand out more p->fillRect(0, 0, width(), height(), QColor(0, 0, 0, 128)); DebugDraw debugDraw(p, mWorld); debugDraw.draw(); }
void PhysicsWorld::update(float delta, bool userCall/* = false*/) { if(!_delayAddBodies.empty()) { updateBodies(); } else if (!_delayRemoveBodies.empty()) { updateBodies(); } auto sceneToWorldTransform = _scene->getNodeToParentTransform(); beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f); if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty()) { updateJoints(); } if (delta < FLT_EPSILON) { return; } if (userCall) { cpSpaceStep(_cpSpace, delta); } else { _updateTime += delta; if (++_updateRateCount >= _updateRate) { const float dt = _updateTime * _speed / _substeps; for (int i = 0; i < _substeps; ++i) { cpSpaceStep(_cpSpace, dt); } _updateRateCount = 0; _updateTime = 0.0f; } } if (_debugDrawMask != DEBUGDRAW_NONE) { debugDraw(); } // Update physics position, should loop as the same sequence as node tree. // PhysicsWorld::afterSimulation() will depend on the sequence. afterSimulation(_scene, sceneToWorldTransform, 0.f); }
void PhysicsWorld::update(float delta) { cpSpaceStep(_info->space, delta); if (_drawNode) { _drawNode->removeFromParent(); _drawNode = nullptr; } if (_debugDraw) { debugDraw(); } }
//-------------------------------------------------------------- void ofApp::draw(){ debugDraw(); ofPushMatrix(); ofTranslate(ofGetWidth() * 0.6, ofGetHeight() * 0.5); ofRotateY(ofGetFrameNum() * 0.3); //ofRotateZ(ofGetFrameNum() * 0.3); ofEnableDepthTest(); if(wireframe) mesh.drawWireframe(); else mesh.drawFaces(); ofDisableDepthTest(); ofPopMatrix(); }
void NavigationGraph::calcGraph(OgreBulletDynamics::DynamicsWorld* world) { for (int z = 0; z < gridDepth; z++) { for (int x = 0; x < gridWidth; x++) { Vector3 pos((float) (x * NavigationNode::NODE_SIZE), 5.0f, (float) (z * NavigationNode::NODE_SIZE)); pos += origin; if(!checkSpaceForNode(world, pos)) { continue; } NavigationNode* node = new NavigationNode(Vector3((float) x, 0.0f, (float) z), pos); NavigationNode* leftNode = getNode(x-1, z); NavigationNode* topNode = getNode(x, z-1); if (leftNode != NULL) { Vector3 distance = node->center - leftNode->center; float cost = distance.length(); node->connections.push_back(new Connection(node, leftNode, cost)); leftNode->connections.push_back(new Connection(leftNode, node, cost)); } if (topNode != NULL) { Vector3 distance = node->center - topNode->center; float cost = distance.length(); node->connections.push_back(new Connection(node, topNode, cost)); topNode->connections.push_back(new Connection(topNode, node, cost)); } grid[x + z * gridWidth] = node; } } debugDraw(); }
void PhysicsWorld::update(float delta) { if (_delayDirty) { // the updateJoints must run before the updateBodies. updateJoints(); updateBodies(); _delayDirty = !(_delayAddBodies->count() == 0 && _delayRemoveBodies->count() == 0 && _delayAddJoints.size() == 0 && _delayRemoveJoints.size() == 0); } for (auto body : *_bodies) { body->update(delta); } cpSpaceStep(_info->getSpace(), delta); if (_debugDrawMask != DEBUGDRAW_NONE) { debugDraw(); } }
void PlayerEntity::slideMove(GameTime timeLeft) { static const float epsilon = 0.0001f; // Use constant velocity gravity (!) alwaysAssertM(((PhysicsScene*)m_scene)->gravity().x == 0.0f && ((PhysicsScene*)m_scene)->gravity().z == 0.0f, "We assume gravity points along the y axis to simplify implementation"); m_desiredOSVelocity.y = max( ((PhysicsScene*)m_scene)->gravity().y, m_desiredOSVelocity.y + ((PhysicsScene*)m_scene)->gravity().y); // Initial velocity Vector3 velocity = frame().vectorToWorldSpace(m_desiredOSVelocity) + ((PhysicsScene*)m_scene)->gravity(); Array<Tri> triArray; getConservativeCollisionTris(triArray, velocity, (float)timeLeft); // Trivial implementation that ignores collisions: # if 0 m_frame.translation += velocity * timeLeft; return; # endif // Keep simulating until we run out of time or velocity, at which point // no further movement is possible. # ifdef TRACE_COLLISIONS debugPrintf("================================\n"); debugPrintf("Initial velocity = %s; position = %s\n", velocity.toString().c_str(), m_frame.translation.toString().c_str()); # endif int iterations = 0; while ((timeLeft > epsilon) && (velocity.length() > epsilon)) { float stepTime = float(timeLeft); Vector3 collisionNormal; Point3 collisionPoint; const bool collided = findFirstCollision(triArray, velocity, stepTime, collisionNormal, collisionPoint); # ifdef TRACE_COLLISIONS debugPrintf(" stepTime = %f\n", stepTime); # endif // Advance to just before the collision stepTime = max(0.0f, stepTime - epsilon * 0.5f); m_frame.translation += velocity * stepTime; // Early out of loop when debugging //if (! runSimulation) { return; } if (collided) { # ifdef TRACE_COLLISIONS debugPrintf(" Collision C=%s, n=%s; position after=%s)\n", collisionPoint.toString().c_str(), collisionNormal.toString().c_str(), m_frame.translation.toString().c_str()); # endif if (collisionProxy().contains(collisionPoint)) { // Interpenetration. This is bad because the // rest of the code assumes no interpenetration and // uses that to rise up steps. Place the sphere // adjacent to the triangle and eliminate all velocity // towards the triangle. m_frame.translation = collisionPoint + collisionNormal * (m_collisionProxySphere.radius + epsilon * 2.0f); # ifdef TRACE_COLLISIONS debugPrintf(" Interpenetration detected. Position after = %s\n", m_frame.translation.toString().c_str()); # endif } // Constrain the velocity by subtracting the component // into the collision normal const Vector3& vPerp = collisionNormal * collisionNormal.dot(velocity); const Vector3& vPar = velocity - vPerp; # ifdef SHOW_COLLISIONS if (collisionNormal.y < 0.95f) { float duration = 1.0f; debugDraw(new ArrowShape(collisionPoint, velocity), duration, Color3::green()); debugDraw(new ArrowShape(collisionPoint, vPerp), duration, Color3::yellow()); debugDraw(new ArrowShape(collisionPoint, vPar), duration, Color3::blue()); if (duration == finf()) { // Pause so we can see the result runSimulation = false; } } # endif velocity = vPar; # ifdef TRACE_COLLISIONS debugPrintf(" velocity after collision = %s\n", velocity.toString().c_str()); # endif } # ifdef TRACE_COLLISIONS debugPrintf(" --------------\n"); # endif ++iterations; timeLeft -= stepTime; } //screenPrintf("%d collision iterations", iterations); }
void ARHelper::draw() { ofSetColor(0xffffff); glViewport(0, 0, ofGetWidth(), ofGetHeight() ); //else if(mode == FIT)convert.draw(0, 0,ofGetWidth(),ofGetHeight()); //this is where we use the calculated matrix from ARToolkitPlus to put //in our graphics at the location and orientation of the marker. //- the matrix has the 0,0 point as the center of the marker. glMatrixMode( GL_PROJECTION ); glLoadMatrixf(tracker->getProjectionMatrix()); float m[ 16 ]; #ifdef SINGE_MARKER if (markerId !=-1) { for (int i=0; i<16; i++) m[i] = tracker->getModelViewMatrix()[i]; if (modelHandler!=NULL && int(conf*100.0f)>tol)modelHandler->updateModelMatrix(markerId , m,(float*) tracker->getProjectionMatrix()); } #else int numDetected = tracker->getNumDetectedMarkers(); for (int i=0; i<numDetected; i++) { ARToolKitPlus::ARMarkerInfo marker = tracker->getDetectedMarker(i); float m34[ 3 ][ 4 ]; float c[ 2 ] = { 0.0f, 0.0f }; float w = 40.0f; tracker->rppGetTransMat( &marker, c, w, m34 ); float m[ 16 ]; //this is some crazy matrix transformative stuff. I think initially it came out of one of the arToolkit functions.... but i got it from here: http://chihara.naist.jp/people/STAFF/imura/computer/OpenGL/artp/disp_content for ( int i = 0; i < 3; i++ ) { for ( int j = 0; j < 4; j++ ) { m[ j * 4 + i ] = m34[ i ][ j ]; } } for ( int j = 0; j < 3; j++ ) { m[ j * 4 + 3 ] = 0.0f; } m[ 3 * 4 + 3 ] = 1.0f; if (modelHandler!=NULL )modelHandler->updateModelMatrix(marker.id , m,(float*) tracker->getProjectionMatrix()); //if (modelHandler!=NULL)modelHandler->updateModelMatrix(marker.id , m); debugDraw(marker.id,m); } #endif //#ifdef SINGE_MARKER glEnable(GL_DEPTH_TEST); if (modelHandler!=NULL)modelHandler->draw(); north.draw(-256,-256); glDisable(GL_DEPTH_TEST); glDisable(GL_DEPTH_TEST); debugDraw(markerId,m); glEnable(GL_DEPTH_TEST); GLdouble model_view[16]; GLdouble projection[16]; GLint viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); for (int i=0; i<16; i++) { model_view[i] = tracker->getModelViewMatrix()[i]; projection[i] = tracker->getProjectionMatrix()[i]; } if (modelHandler!=NULL) for (int i = 0 ; i<modelHandler->getModel().size() ; i++) { modelHandler->getModel()[i]->findScreenCoord(projection,viewport); } GLdouble ret_x, ret_y, ret_z; gluProject(0,0,0, model_view, projection, viewport, &ret_x, &ret_y, &ret_z); float x = ret_x; float y = ofGetHeight()-ret_y; markerV.set(x,y); ofSetupScreen(); if (bDebug) { ofNoFill(); ofSetColor(255,255,255,125); ofRect(-50+x,-50+y,100,100); ofRect(0,(ofGetHeight()/2)-IMAGE_AREA,ofGetWidth(),IMAGE_AREA*2); } { glDisable(GL_DEPTH_TEST); if (modelHandler!=NULL)modelHandler->draw2D(); glEnable(GL_DEPTH_TEST); } }
void testApp::draw() { //===================== // 入力画像抽出処理開始 //===================== if (bProcessGetDraw) { bool bError = false; mTmpWindow.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); //表示中の画面を取得 //---------- // 描画がある場合は波形変換を開始 //---------- if (mPts.size()) { //---------- // 図形の格子範囲を取得 //---------- ofRectangle scaleRect; float minX = ofGetWidth(); float minY = ofGetHeight(); float maxX = 0; float maxY = 0; for (int i=0; i < mPts.size(); i++) { if (mPts[i].x < minX) minX = mPts[i].x; if (mPts[i].y < minY) minY = mPts[i].y; if (mPts[i].x > maxX) maxX = mPts[i].x; if (mPts[i].y > maxY) maxY = mPts[i].y; } //正確に取得できたかチェック if (minX > maxX || minY > maxY) { cout << "[ERROR] 描画領域の取得に失敗しました" << endl; bError = true; goto _FAILD_GET_DRAWING; } scaleRect.set(minX, minY, maxX-minX, maxY-minY); mPtsRect = scaleRect; //---------- // 格子範囲を正規化 //---------- scaleRect.setPosition((ofGetWidth()/2)-(scaleRect.width/2), (ofGetHeight()/2)-(scaleRect.height/2)); float tScale = 1.0f; if (scaleRect.width < scaleRect.height) { tScale = (float)ofGetHeight() / scaleRect.height; } else { tScale = (float)ofGetHeight() / scaleRect.width; } scaleRect.scaleFromCenter(tScale); scaleRect.setPosition(0, 0); //---------- // 正規化した格子範囲に合わせて図形の大きさを変更した座標配列を取得 //---------- vector<ofPoint> tPts; for (int i=0; i < mPts.size(); i++) { float tX = ofMap(mPts[i].x, minX, maxX, scaleRect.x, scaleRect.width); float tY = ofMap(mPts[i].y, minY, maxY, scaleRect.y, scaleRect.height); ofPoint tPoint = ofPoint(tX, tY); tPts.push_back(tPoint); } if (bCircleMode) { //---------- // 円モードの場合は円を描画 //---------- if( mPts.size() > 0 ) { float size = ofDist(mPts[0].x, mPts[0].y, mPts[mPts.size()-1].x, mPts[mPts.size()-1].y); mVecOut.circle(mPts[0].x, mPts[0].y, size); } } else { //---------- // 描いた図形をfillして描画 //---------- int numPts = tPts.size(); int rescaleRes = 2; mVecOut.fill(); mVecOut.beginShape(); for(int i = 0; i < numPts; i++){ if(i == 0 || i == numPts -1){ mVecOut.curveVertex(tPts[i].x, tPts[i].y); } if(i % rescaleRes == 0) mVecOut.curveVertex(tPts[i].x, tPts[i].y); } mVecOut.endShape(); } //スクリーンショット mGrabImage.grabScreen(0, 0, ofGetWidth(), ofGetHeight()); mTmpWindow.draw(0, 0); //元の画面を描画 bProcessGetDraw = false; //---------- // フーリエ記述子の計算 - 波形変換 - OSC送信 //---------- calcFourier(); //---------- // Figureクラスのインスタンスを生成して輪郭座標点を渡す //---------- Figure tmpF; //図形IDを設定 if (mFMode==STATIC) { //STATICモードの場合はOSCで送られてくるシーケンサーの現在の数値をIDとする tmpF.setID(mSeqCurrentNum); } else if (mFMode==FLORTING) { tmpF.setID(0); } else if (mFMode==AROUND) { tmpF.setID(mFigures[2].size()); } //円モードの場合は計算に使用した輪郭点を描画点として置き換える if (bCircleMode) { vector<ofPoint> edgePts; for (int i=0; i < mResizedPts.size(); i++) { edgePts.push_back(mResizedPts[i]); } tmpF.setPts(edgePts); tmpF.setEdgePts(edgePts); } else { //計算に使用した輪郭点座標を元の大きさにスケーリングして取得 vector<ofPoint> edgePts; for (int i=0; i < mEdgeBits.size(); i++) { ofPoint tmpPoint; tmpPoint.set(ofMap(mResizedPts[i].x, scaleRect.x, scaleRect.width, minX, maxX), ofMap(mResizedPts[i].y, scaleRect.y, scaleRect.height, minY, maxY)); edgePts.push_back(tmpPoint); } tmpF.setEdgePts(edgePts); tmpF.setPts(mPts); } //モードをセットしてモードごとの配列に格納 //MEMO:現状、図形モードは配列の要素数とインスタンス毎のモード設定の2つで管理しているので、どっちかにしたい tmpF.setMode(mFMode); switch (mFMode) { case STATIC: mFigures[0].push_back(tmpF); break; case FLORTING: mFigures[1].push_back(tmpF); break; case AROUND: mFigures[2].push_back(tmpF); break; } //---------- // OSCでもろもろ送信 // 1.モードID 2.図形ID 3.全ビット 4.重心座標 //---------- sendModeId((int)mFMode); switch (mFMode) { case STATIC: sendBits(0, tmpF.getID()); sendPos(0, tmpF.getID(), tmpF.getCentPos()); break; case FLORTING: sendBits(1, mFigures[1].size()%2); sendPos(1, mFigures[1].size()%2, tmpF.getCentPos()); break; case AROUND: sendBits(2, mFigures[2].size()-1); break; } mPts.clear(); } _FAILD_GET_DRAWING: if (bError) { cout << "[ERROR] 画像の取得に失敗しました" << endl; } //==================== // 入力画像抽出処理終了 //==================== } else { //---------- // ルーラー //---------- ofPushStyle(); ofSetColor(40); for (int i=0; i < ofGetWidth(); i += 10){ if (i%100 == 0) { ofSetLineWidth(2); ofLine(i, 0, i, ofGetHeight()); } else { ofSetLineWidth(1); ofLine(i, 0, i, ofGetHeight()); } } for (int i=0; i < ofGetHeight(); i += 10){ if (i%100 == 0) { ofSetLineWidth(2); ofLine(0, i, ofGetWidth(), i); } else { ofSetLineWidth(1); ofLine(0, i, ofGetWidth(), i); } } //描画中 if (bDrawing) { ofSetLineWidth(1); ofSetColor(255); for (int i=0; i < ofGetWidth(); i += 10){ if (i%100 == 0) ofLine(i, 0, i, 15); else ofLine(i, 0, i, 10); } for (int i=0; i < ofGetHeight(); i += 10){ if (i%100 == 0) ofLine(0, i, 15, i); else ofLine(0, i, 10, i); } ofSetColor(120, 150, 120); ofLine(mouseX, 0, mouseX, ofGetHeight()); ofLine(0, mouseY, ofGetWidth(), mouseY); ofSetColor(220); ofDrawBitmapString(ofToString(mouseX, 2), mouseX+10, 25); ofDrawBitmapString(ofToString(mouseY, 2), 15, mouseY+10); } ofPopStyle(); //---------- // 形態を描画 //---------- for (int i=0; i < mFigures.size(); i++) { for (int j=0; j < mFigures[i].size(); j++) { mFigures[i][j].draw(); if (bDebugMode) { mFigures[i][j].debugDraw(); } } } if (bCircleMode) { //---------- // 円モードの場合は円を描画 //---------- if( mPts.size() > 0 ) { float size = ofDist(mPts[0].x, mPts[0].y, mPts[mPts.size()-1].x, mPts[mPts.size()-1].y); mVecOut.circle(mPts[0].x, mPts[0].y, size); } } else { //---------- // 自由線画像を描画 //---------- if( mPts.size() > 0 ) { int numPts = mPts.size(); int rescaleRes = 2; mVecOut.noFill(); mVecOut.beginShape(); for(int i = 0; i < numPts; i++){ if(i == 0 || i == numPts -1){ mVecOut.curveVertex(mPts[i].x, mPts[i].y); } if(i % rescaleRes == 0) mVecOut.curveVertex(mPts[i].x, mPts[i].y); } mVecOut.endShape(); //もし開始点に近い場合はマークを表示 if (ofDist(mPts[0].x, mPts[0].y, mouseX, mouseY) < 20 && mPts.size() > 10) { ofPushStyle(); ofSetColor(255, 0, 0); ofNoFill(); ofSetLineWidth(2); ofCircle(mPts[0], 20); ofPopStyle(); } } } } if (bDebugMode) { debugDraw(); } }
int Saloon::start() { if(_window != nullptr) { // Create an OpenGL context associated with the window. SDL_GLContext glContext = SDL_GL_CreateContext(_window); // Init and check for GL Errors. glInit(_displayWidth, _displayHeight); GLenum error = glGetError(); if( error != GL_NO_ERROR ) { logSDLError(std::cout, "GL INIT"); return 1; } LTimer fpsTimer; fpsTimer.start(); Uint32 frames = 0, FPS = 0; //Our event structure SDL_Event e; bool quit = false; int curTime, prevTime = SDL_GetTicks(); BMFont debugFont("Fonts/system16.fnt"); onCreate(); while (!quit){ while (SDL_PollEvent(&e)){ if (e.type == SDL_QUIT) quit = true; //Use number input to select which clip should be drawn if (e.type == SDL_KEYDOWN){ switch (e.key.keysym.sym){ case SDLK_ESCAPE: quit = true; break; case SDLK_TAB: if(_debugEnabled) { setVSyncEnabled(false); } break; default: break; } } else if(e.type == SDL_KEYUP) { switch (e.key.keysym.sym){ case SDLK_TAB: if(_debugEnabled) { setVSyncEnabled(true); } break; default: break; } } } if(_debugEnabled) { debugStart(); curTime = SDL_GetTicks(); deltaTime = (curTime - prevTime) / 1000.0f; prevTime = curTime; if(fpsTimer.getTicks() >= 1000) { FPS = frames; frames = 0; fpsTimer.reset(); } frames++; debugWatch("FPS", FPS); } onUpdate(); glClear(GL_COLOR_BUFFER_BIT); //Reset modelview matrix glMatrixMode( GL_MODELVIEW ); glLoadIdentity(); glPushMatrix(); glTranslatef(_halfDisplayWidth, _halfDisplayHeight, 0.0f); glPushMatrix(); // Camera transformations glScalef(_camZoom, _camZoom, 1.0f); glRotatef(_camAng, 0, 0, 1); glTranslatef(-_camX, _camY, 0); onRender(); glPopMatrix(); glPopMatrix(); glColor4(_debugColor); debugDraw(debugFont); SDL_GL_SwapWindow(_window); } onDestroy(); glDestroy(); // Once finished with OpenGL functions, the SDL_GLContext can be deleted. SDL_GL_DeleteContext(glContext); SDL_DestroyWindow(_window); TTF_Quit(); IMG_Quit(); SDL_Quit(); return 0; } else { logSDLError(std::cout, "Saloon::start"); return 1; } }
//-------------------------------------------------------------- void testApp::draw(){ //ofBackground( 255, 255, 255 ); //Set white background float time = ofGetElapsedTimef(); //1. Drawing to buffer fboTrails.begin(); //Draw semi-transparent white rectangle //to slightly clearing a buffer (depends on history value) ofEnableAlphaBlending(); //Enable transparency float alpha = (1-history) * 255; ofSetColor( 0, 0, 0, alpha ); ofFill(); ofClear(255, 255, 255, 0); //ofRect( 0, 0, ofGetWidth(), ofGetHeight() ); ofDisableAlphaBlending(); //Disable transparency //Draw the particles ofFill(); for (int i=0; i<p.size(); i++) { p[i].draw(); } fboTrails.end(); //Draw Background buffer fbo1.begin(); //ofBackgroundGradient( ofColor( 255 ), ofColor( 128 ) ); ofSetColor( 255, 255, 255 ); image.draw( 0, 0); fbo1.end(); //Draw Foreground greyscale buffer fbo2.begin(); //ofBackground( 0, 0, 0 ); imageGrey.draw(0,0); //ofBackground(255); //float ang = time * 30; ofPushMatrix(); //ofTranslate( 300, 384 ); //ofRotate( ang ); ofFill(); //ofSetColor( 255, 255, 255 ); ofSetColor(255); //ofTriangle( -200, -114, 200, -114, 0, 230 ); for(int i = 0; i<touches.size(); i++) { ofCircle(touches.at(i), TOUCH_RAD); } ofPopMatrix(); fbo2.end(); //Drawing to screen through the shader ofEnableAlphaBlending(); //NOTE: It is important to enable alpha blending for correct shader's working, //because shader performs masking by setting alpha-value of output color shader.begin(); shader.setUniform1f( "time", time ); //Pass float parameter "time" to shader //Pass mask to shader (fbo2) shader.setUniformTexture( "texture1", fbo2.getTextureReference(), 1 ); //Last parameter 1 is OpenGL texture identifier //Draw fbo image //ofSetColor( 255, 255, 255 ); fbo1.draw( 0, 0 ); shader.end(); //2. Draw buffer on the screen //ofSetColor( 255, 255, 255 ); fboTrails.draw( 0, 0 ); //GUI if ( debug ) { //Draw text debugDraw(); } }
int main() { sf::Font font; sf::Text overlayText; const std::string fontFile = "am.ttf"; if (font.loadFromFile(fontFile)) { overlayText.setFont(font); } else { std::cerr << "Could not find " << fontFile << "\n"; return 1; } overlayText.setCharacterSize(10); overlayText.setString("Hold left mouse button to modify\nRight mouse button to add objects"); sf::VideoMode videoMode{ static_cast<unsigned int>(screenWidth), static_cast<unsigned int>(screenHeight) }; sf::ContextSettings settings; settings.antialiasingLevel = 8; sf::RenderWindow window(videoMode, "Box2D modifiable geometry", sf::Style::Default, settings); std::unique_ptr<b2World> physicsWorld{ new b2World{ b2Vec2{ 0.0f, 18.0f } } }; physicsWorld->SetAutoClearForces(false); physicsWorld->SetContactListener(nullptr); DebugDraw debugDraw(&window, physicsWorld.get()); addStaticShapes(*physicsWorld); sf::Clock clock; bool simplifyGeometry = true; while (window.isOpen()) { float elapsed = clock.restart().asSeconds(); sf::Event event; auto mousePos = sf::Mouse::getPosition(window); auto worldPos = window.mapPixelToCoords(mousePos); const float removalRadius = 25.f; b2Vec2 position = { worldPos.x, worldPos.y }; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } if (event.type == sf::Event::MouseButtonPressed && event.mouseButton.button == sf::Mouse::Button::Right) { ShapeFactory factory{ constants::RENDER_SCALE }; auto ballShape = factory.circle(position, removalRadius / 2.f); b2BodyDef ballDef; b2Body* ballBody = physicsWorld->CreateBody(&ballDef); auto ballFixture = ballBody->CreateFixture(ballShape.get(), 0.0f); ballBody->SetType(b2BodyType::b2_dynamicBody); auto filter = ballFixture->GetFilterData(); filter.categoryBits = Shape::normal; filter.maskBits = Shape::normal | Shape::destructible; ballFixture->SetFilterData(filter); } if (event.type == sf::Event::KeyReleased && event.key.code == sf::Keyboard::S) { simplifyGeometry = !simplifyGeometry; } } window.clear(); step(*physicsWorld, elapsed); b2Vec2 scaledPos = position; scaledPos *= (1.f / constants::RENDER_SCALE); float scaledRadius = removalRadius / constants::RENDER_SCALE; if (sf::Mouse::isButtonPressed(sf::Mouse::Button::Left)) { processRemoval(scaledPos, scaledRadius, *physicsWorld, simplifyGeometry); drawMouseIndicator(worldPos, removalRadius, window); } physicsWorld->DrawDebugData(); window.draw(overlayText); window.display(); } return 0; }
int main(int argc, char** argv) { sf::RenderWindow* RenderWin = new sf::RenderWindow(sf::VideoMode(WIDTH, HEIGHT, 32), "lol test"); RenderWin->UseVerticalSync(true); // Collision configuration contains default setup for memory, collision setup. Advanced users can create their own configuration. boost::shared_ptr<btDefaultCollisionConfiguration> collisionConfiguration(new btDefaultCollisionConfiguration()); // Use the default collision dispatcher. For parallel processing you can use a diffent dispatcher (see Extras/BulletMultiThreaded). boost::shared_ptr<btCollisionDispatcher> dispatcher(new btCollisionDispatcher(collisionConfiguration.get())); // btDbvtBroadphase is a good general purpose broadphase. You can also try out btAxis3Sweep. boost::shared_ptr<btBroadphaseInterface> broadphase(new btDbvtBroadphase()); // The default constraint solver. For parallel processing you can use a different solver (see Extras/BulletMultiThreaded). boost::shared_ptr<btVoronoiSimplexSolver> simplex(new btVoronoiSimplexSolver()); boost::shared_ptr<btMinkowskiPenetrationDepthSolver> pd_solver(new btMinkowskiPenetrationDepthSolver()); boost::shared_ptr<btSequentialImpulseConstraintSolver> solver(new btSequentialImpulseConstraintSolver()); boost::shared_ptr<btDiscreteDynamicsWorld> dynamicsWorld(new btDiscreteDynamicsWorld(dispatcher.get(), broadphase.get(), solver.get(), collisionConfiguration.get())); boost::shared_ptr<btConvex2dConvex2dAlgorithm::CreateFunc> convex_algo_2d(new btConvex2dConvex2dAlgorithm::CreateFunc(simplex.get(),pd_solver.get())); dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get()); dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,CONVEX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get()); dispatcher->registerCollisionCreateFunc(CONVEX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE, convex_algo_2d.get()); dispatcher->registerCollisionCreateFunc(BOX_2D_SHAPE_PROXYTYPE,BOX_2D_SHAPE_PROXYTYPE, new btBox2dBox2dCollisionAlgorithm::CreateFunc()); // Set gravity to 9.8m/s² along y-axis. dynamicsWorld->setGravity(btVector3(0, 1, 0)); // Get us some debug output. Without this, we'd see nothing at all. boost::shared_ptr<DebugDraw> debugDraw(new DebugDraw(RenderWin)); debugDraw->setDebugMode(btIDebugDraw::DBG_DrawWireframe); dynamicsWorld->setDebugDrawer(debugDraw.get()); // Keep track of the shapes, we release memory at exit. // Make sure to re-use collision shapes among rigid bodies whenever possible! btAlignedObjectArray<btCollisionShape*> collisionShapes; // Create a ground body. btScalar thickness(0.2); boost::shared_ptr<btCollisionShape> groundShape(new btBoxShape(btVector3(btScalar(WIDTH / 2 * METERS_PER_PIXEL), thickness, btScalar(10)))); collisionShapes.push_back(groundShape.get()); btTransform groundTransform(btQuaternion(0, 0, 0, 1), btVector3(WIDTH / 2 * METERS_PER_PIXEL, HEIGHT * METERS_PER_PIXEL, 0)); // Using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects. boost::shared_ptr<btDefaultMotionState> groundMotionState(new btDefaultMotionState(groundTransform)); btRigidBody::btRigidBodyConstructionInfo ground_rbInfo(0, groundMotionState.get(), groundShape.get(), btVector3(0, 0, 0)); boost::shared_ptr<btRigidBody> ground_body(new btRigidBody(ground_rbInfo)); ground_body->setLinearFactor(btVector3(1,1,0)); ground_body->setAngularFactor(btVector3(0,0,1)); // Add the body to the dynamics world. dynamicsWorld->addRigidBody(ground_body.get()); // Create left wall. btTransform leftWallTransform(btQuaternion(0, 0, 1, 1), btVector3(0, HEIGHT / 2 * METERS_PER_PIXEL, 0)); boost::shared_ptr<btDefaultMotionState> leftWallMotionState(new btDefaultMotionState(leftWallTransform)); btRigidBody::btRigidBodyConstructionInfo leftWall_rbInfo(0, leftWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0)); boost::shared_ptr<btRigidBody> leftwall_body(new btRigidBody(leftWall_rbInfo)); leftwall_body->setLinearFactor(btVector3(1,1,0)); leftwall_body->setAngularFactor(btVector3(0,0,1)); // Add the body to the dynamics world. dynamicsWorld->addRigidBody(leftwall_body.get()); // Create right wall. btTransform rightWallTransform(btQuaternion(0, 0, 1, 1), btVector3(WIDTH * METERS_PER_PIXEL, HEIGHT / 2 * METERS_PER_PIXEL, 0)); boost::shared_ptr<btDefaultMotionState> rightWallMotionState(new btDefaultMotionState(rightWallTransform)); btRigidBody::btRigidBodyConstructionInfo rightWall_rbInfo(0, rightWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0)); boost::shared_ptr<btRigidBody> rightwall_body(new btRigidBody(rightWall_rbInfo)); rightwall_body->setLinearFactor(btVector3(1,1,0)); rightwall_body->setAngularFactor(btVector3(0,0,1)); // Add the body to the dynamics world. dynamicsWorld->addRigidBody(rightwall_body.get()); // Create ceiling btTransform topWallTransform(btQuaternion(0, 0, 0, 1), btVector3(WIDTH / 2 * METERS_PER_PIXEL, 0, 0)); boost::shared_ptr<btDefaultMotionState> topWallMotionState(new btDefaultMotionState(topWallTransform)); btRigidBody::btRigidBodyConstructionInfo topWall_rbInfo(0, topWallMotionState.get(), groundShape.get(), btVector3(0, 0, 0)); boost::shared_ptr<btRigidBody> topwall_body(new btRigidBody(topWall_rbInfo)); topwall_body->setLinearFactor(btVector3(1,1,0)); topwall_body->setAngularFactor(btVector3(0,0,1)); // Add the body to the dynamics world. dynamicsWorld->addRigidBody(topwall_body.get()); // Create dynamic rigid body. //btCollisionShape* colShape = new btBoxShape(btVector3(1,1,1)); boost::shared_ptr<btCollisionShape> colShape(new btSphereShape(btScalar(0.6))); collisionShapes.push_back(colShape.get()); /// Create Dynamic Objects btTransform startTransform; startTransform.setIdentity(); btScalar mass(1.f); //rigidbody is dynamic if and only if mass is non zero, otherwise static bool isDynamic = (mass != 0.f); btVector3 localInertia(0, 0, 0); if (isDynamic) colShape->calculateLocalInertia(mass,localInertia); startTransform.setOrigin(btVector3(2, 5, 0)); //using motionstate is recommended, it provides interpolation capabilities, and only synchronizes 'active' objects boost::shared_ptr<btDefaultMotionState> myMotionState(new btDefaultMotionState(startTransform)); btRigidBody::btRigidBodyConstructionInfo rbInfo(mass,myMotionState.get(),colShape.get(),localInertia); boost::shared_ptr<btRigidBody> body(new btRigidBody(rbInfo)); body->setLinearFactor(btVector3(1,1,0)); body->setAngularFactor(btVector3(0,0,1)); dynamicsWorld->addRigidBody(body.get()); // Create lulz boost::ptr_list<btRigidBody> body_list; boost::ptr_list<btDefaultMotionState> motionstate_list; boost::ptr_list<btCollisionShape> colshape_list; for (int i=0;i <= 10; ++i) { if (i < 5) colshape_list.push_back(new btSphereShape(btScalar(sf::Randomizer::Random(0.1f, 0.8f)))); else colshape_list.push_back(new btBoxShape(btVector3(sf::Randomizer::Random(0.1f,0.8f), sf::Randomizer::Random(0.1f,0.8f), 10))); if (isDynamic) colshape_list.back().calculateLocalInertia(mass,localInertia); collisionShapes.push_back(&(colshape_list.back())); startTransform.setIdentity(); startTransform.setOrigin(btVector3(i,i,0)); motionstate_list.push_back(new btDefaultMotionState(startTransform)); btRigidBody* lol = new btRigidBody(btRigidBody::btRigidBodyConstructionInfo(mass,&(motionstate_list.back()),&(colshape_list.back()),localInertia)); lol->setLinearFactor(btVector3(1,1,0)); lol->setAngularFactor(btVector3(0,0,1)); body_list.push_back(lol); } BOOST_FOREACH (btRigidBody& body, body_list) { dynamicsWorld->addRigidBody(&body); }
void PhysicsWorld::update(float delta, bool userCall/* = false*/) { if(!_delayAddBodies.empty()) { updateBodies(); } else if (!_delayRemoveBodies.empty()) { updateBodies(); } auto sceneToWorldTransform = _scene->getNodeToParentTransform(); beforeSimulation(_scene, sceneToWorldTransform, 1.f, 1.f, 0.f); if (!_delayAddJoints.empty() || !_delayRemoveJoints.empty()) { updateJoints(); } if (delta < FLT_EPSILON) { return; } if (userCall) { #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 cpSpaceStep(_cpSpace, delta); #else cpHastySpaceStep(_cpSpace, delta); #endif } else { _updateTime += delta; if(_fixedRate) { const float step = 1.0f / _fixedRate; const float dt = step * _speed; while(_updateTime>step) { _updateTime-=step; #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 cpSpaceStep(_cpSpace, dt); #else cpHastySpaceStep(_cpSpace, dt); #endif } } else { if (++_updateRateCount >= _updateRate) { const float dt = _updateTime * _speed / _substeps; for (int i = 0; i < _substeps; ++i) { #if CC_TARGET_PLATFORM == CC_PLATFORM_WINRT || CC_TARGET_PLATFORM == CC_PLATFORM_WIN32 cpSpaceStep(_cpSpace, dt); #else cpHastySpaceStep(_cpSpace, dt); #endif for (auto& body : _bodies) { body->update(dt); } } _updateRateCount = 0; _updateTime = 0.0f; } } } if (_debugDrawMask != DEBUGDRAW_NONE) { debugDraw(); } // Update physics position, should loop as the same sequence as node tree. // PhysicsWorld::afterSimulation() will depend on the sequence. afterSimulation(_scene, sceneToWorldTransform, 0.f); }