void disturbMidpoint(ofVec3f & midPoint, ofVec3f const & bottomLeft, ofVec3f const & topLeft, ofVec3f const & topRight, ofVec3f const & bottomRight) { //if (std::rand() % 2 == 0) { // return; //} midPoint[2] += (topLeft.distance(bottomRight) + topRight.distance(bottomLeft)) * randomValue(); if (midPoint[2] < minHeight) { minHeight = midPoint[2]; } if (midPoint[2] > maxHeight) { maxHeight = midPoint[2]; } }
// needs improvement. right now it just looks for the biggest cross product void approximatePlane(const vector<ofVec3f>& points, int iterations, ofVec3f& center, ofVec3f& normal) { int n = points.size(); for(int i = 0; i < n; i++) { center += points[i]; } center /= n; float maxLength = 0; for(int i = 0; i < n; i++) { ofVec3f side1 = points[i] - center; for(int j = i + 1; j < n; j++) { ofVec3f side2 = points[j] - center; ofVec3f curNormal = side1.getCrossed(side2); if(curNormal.z < 0) { curNormal *= -1; } float length = curNormal.length(); if(length > maxLength) { normal = curNormal; maxLength = length; } } } normal.normalize(); }
void ball::update(ofVec3f hand, ofVec3f prev_hand, ofVec3f handVel){ //Trigger the average tracking //80 is the threshold! if (handVel.length() > 80 && hand.z < prev_hand.z && movementCount == 0) { currentFood = floor((ofRandom(7))); isTracking = true; cout << "threw!" << endl; } //else if (handVel.length() < 10) { else if (movementCount > 60) { //Throws! //isTracking = false; //vel /= movementCount; movementCount = 0; pos = ofVec3f (2000, 2000, 0); vel.set (0, 0, 0); } //Tracks if(isTracking){ pos = hand; vel = (handVel/3); //movementCount ++; movementCount = 1; isTracking = false; }else if (movementCount > 0){ pos += vel; //movementCount = 1; movementCount++; } }
ofVec3f findNormal(ofVec3f a, ofVec3f b, ofVec3f ref) { a = a - ref; b = b - ref; ofVec3f v = a.cross(b); v.normalize(); return v; }
ofVec3f GrainViewTransform(ofVec3f InPutPoint, ofVec3f Eye, ofVec3f Target, ofVec3f UpVec){ // Transform the cordinates of a point InPutPoint. For a camera placed at Eye and looking at target with Up vector UpVec ofMatrix4x4 ViewMat; ofVec3f zaxis(Target - Eye); zaxis.normalize(); ofVec3f xaxis = UpVec.getCrossed(zaxis); xaxis.normalize(); ofVec3f yaxis = zaxis.getCrossed(xaxis); // translate vect InPutPoint -= Eye; // project on each axis ofVec3f Outpos; Outpos.x = -xaxis.dot(InPutPoint); Outpos.y = -yaxis.dot(InPutPoint); Outpos.z = zaxis.dot(InPutPoint); return Outpos; }
void AbstractPhysicsBehavior::drawForceArrow(ofVec3f position, ofVec3f force) { ofDrawArrow(position, position + force * 20.0f, ofClamp(force.length() * 2.0f, 0, 6.0f)); }
// Make a rotation Quat which will rotate vec1 to vec2 // Generally take adot product to get the angle between these // and then use a cross product to get the rotation axis // Watch out for the two special cases of when the vectors // are co-incident or opposite in direction. void ofQuaternion::makeRotate_original( const ofVec3f& from, const ofVec3f& to ) { const float epsilon = 0.0000001f; float length1 = from.length(); float length2 = to.length(); // dot product vec1*vec2 float cosangle = from.dot(to) / (length1 * length2); if ( fabs(cosangle - 1) < epsilon ) { //osg::notify(osg::INFO)<<"*** Quat::makeRotate(from,to) with near co-linear vectors, epsilon= "<<fabs(cosangle-1)<<std::endl; // cosangle is close to 1, so the vectors are close to being coincident // Need to generate an angle of zero with any vector we like // We'll choose (1,0,0) makeRotate( 0.0, 0.0, 0.0, 1.0 ); } else if ( fabs(cosangle + 1.0) < epsilon ) { // vectors are close to being opposite, so will need to find a // vector orthongonal to from to rotate about. ofVec3f tmp; if (fabs(from.x) < fabs(from.y)) if (fabs(from.x) < fabs(from.z)) tmp.set(1.0, 0.0, 0.0); // use x axis. else tmp.set(0.0, 0.0, 1.0); else if (fabs(from.y) < fabs(from.z)) tmp.set(0.0, 1.0, 0.0); else tmp.set(0.0, 0.0, 1.0); ofVec3f fromd(from.x, from.y, from.z); // find orthogonal axis. ofVec3f axis(fromd.getCrossed(tmp)); axis.normalize(); _v[0] = axis[0]; // sin of half angle of PI is 1.0. _v[1] = axis[1]; // sin of half angle of PI is 1.0. _v[2] = axis[2]; // sin of half angle of PI is 1.0. _v[3] = 0; // cos of half angle of PI is zero. } else { // This is the usual situation - take a cross-product of vec1 and vec2 // and that is the axis around which to rotate. ofVec3f axis(from.getCrossed(to)); float angle = acos( cosangle ); makeRotate( angle, axis ); } }
//-------------------------------------------------------------- ofVec3f ofApp::moveback(ofVec3f fltPos, ofVec3f aggPos,float aggRadius, float fltRadius){ float disAct = fltPos.distance(aggPos); float disShould = aggRadius + fltRadius; ofVec3f tpmoveBack = fltPos - aggPos; tpmoveBack.normalize(); tpmoveBack = tpmoveBack * (disShould - disAct); fltPos = fltPos + tpmoveBack; return fltPos; }
ofVec3f ofCairoRenderer::transform(ofVec3f vec){ if(!b3D) return vec; vec = modelView.preMult(vec); vec = projection.preMult(vec); //vec.set(vec.x/vec.z*viewportRect.width*0.5-ofGetWidth()*0.5-viewportRect.x,vec.y/vec.z*viewportRect.height*0.5-ofGetHeight()*0.5-viewportRect.y); vec.set(vec.x/vec.z*ofGetWidth()*0.5,vec.y/vec.z*ofGetHeight()*0.5); return vec; }
//---------- ofVec2f MovingHead::getPanTiltForTargetInObjectSpace(const ofVec3f & objectSpacePoint, float tiltOffset) { auto pan = atan2(objectSpacePoint.z, objectSpacePoint.x) * RAD_TO_DEG - 90.0f; if (pan < -180.0f) { pan += 360.0f; } auto tilt = acos(-objectSpacePoint.y / objectSpacePoint.length()) * RAD_TO_DEG; // will always produce positive tilt return ofVec2f(pan, tilt + tiltOffset); }
//-------------------------------------------------------------- void testApp::update(){ ofVec3f diff ; //Difference between particle and mouse float dist ; //distance from particle to mouse ( as the crow flies ) float ratio ; //Ratio of how strong the effect is = 1 + (-dist/maxDistance) ; const ofVec3f mousePosition = ofVec3f( mouseX , mouseY , 0 ) ; //Allocate and retrieve mouse values once. const ofVec3f origin = ofVec3f(0,0,0); //Create an iterator to cycle through the vector std::vector<Particle>::iterator p ; for ( p = particles.begin() ; p != particles.end() ; p++ ) { ratio = 1.0f ; p->velocity *= friction ; //reset acceleration every frame p->acceleration = ofVec3f() ; diff = mousePosition - p->position ; dist = mousePosition.distance( p->position ) ; //If within the zone of interaction if ( dist * .5 < forceRadius ) { ratio = -1 + dist / forceRadius ; //Repulsion if ( cursorMode == 0 ) p->acceleration -= ( diff * ratio) ; //Attraction else p->acceleration += ( diff * ratio ) ; } if ( springEnabled ) { //Move back to the original position p->acceleration += springFactor * (p->spawnPoint - p->position ); } p->velocity += p->acceleration * ratio ; p->position += p->velocity ; } if ( ofGetFrameNum() % 300 == 0 ) { curImageIndex++ ; setupParticles() ; } }
//---------------------------------------- void ofxViewportCam::frameBoundingBox(const ofVec3f &minCorner, const ofVec3f &maxCorner) { ofVec3f center((minCorner + maxCorner) * 0.5f); setTargetPosition(center); this->distance = minCorner.distance(maxCorner); setPosition(target.getGlobalPosition()); dolly(this->distance); }
void CorrelateXYZtoXY::push(ofVec3f &xyz, ofVec2f &xy) { if (xyz.length() < 0.1) return; ++nPoints; this->xyz.push_back(toCv(xyz)); this->xy.push_back(toCv(xy)); xyzPreview.addVertex(xyz); }
//-------------------------------------------------------------- void rotateToNormal(ofVec3f normal) { normal.normalize(); float rotationAmount; ofVec3f rotationAngle; ofQuaternion rotation; ofVec3f axis(0, 0, 1); rotation.makeRotate(axis, normal); rotation.getRotate(rotationAmount, rotationAngle); ofRotateDeg(rotationAmount, rotationAngle.x, rotationAngle.y, rotationAngle.z); }
//---------------------------------------- void ofNode::lookAt(const ofVec3f& lookAtPosition, ofVec3f upVector) { if(parent) upVector = upVector * ofMatrix4x4::getInverseOf(parent->getGlobalTransformMatrix()); ofVec3f zaxis = (getGlobalPosition() - lookAtPosition).normalized(); ofVec3f xaxis = upVector.getCrossed(zaxis).normalized(); ofVec3f yaxis = zaxis.getCrossed(xaxis); ofMatrix4x4 m; m._mat[0].set(xaxis.x, xaxis.y, xaxis.z, 0); m._mat[1].set(yaxis.x, yaxis.y, yaxis.z, 0); m._mat[2].set(zaxis.x, zaxis.y, zaxis.z, 0); setGlobalOrientation(m.getRotate()); }
void Graphics2552::rotateToNormal(ofVec3f normal) { normal.normalize(); float rotationAmount; ofVec3f rotationAngle; ofQuaternion rotation; ofVec3f axis(0, 0, 1); rotation.makeRotate(axis, normal); rotation.getRotate(rotationAmount, rotationAngle); logVerbose("ofRotate " + ofToString(rotationAmount)); ofRotate(rotationAmount, rotationAngle.x, rotationAngle.y, rotationAngle.z); }
ofVec3f RotateAux(ofVec3f input, float latitud, float azimuth, ofVec3f pivot){ ofVec3f theOut = input.getRotated(azimuth, ofVec3f(1, 0, 0)); theOut = theOut.getRotated(latitud, ofVec3f(0, 1, 0)); theOut += pivot; return theOut; }
//--------------------- AccumulateForce ---------------------------------- // // This function calculates how much of its max steering force the // vehicle has left to apply and then applies that amount of the // force to add. //------------------------------------------------------------------------ bool SteeringBehaviors::AccumulateForce(ofVec3f &RunningTot, ofVec3f ForceToAdd) { float MagnitudeSoFar = RunningTot.length(); double MagnitudeRemaining = m_Vehicle->MaxForce() - MagnitudeSoFar; if (MagnitudeRemaining <= 0.0) return false; float MagnitudeToAdd = ForceToAdd.length(); //if the magnitude of the sum of ForceToAdd and the running total //does not exceed the maximum force available to this vehicle, just //add together. Otherwise add as much of the ForceToAdd vector is //possible without going over the max. if (MagnitudeToAdd < MagnitudeRemaining) { RunningTot += ForceToAdd; } else { RunningTot += (ForceToAdd.getNormalized() * MagnitudeRemaining); } return true; }
//-------------------------------------------------- void ofPolyline::calcData(int index, ofVec3f &tangent, float &angle, ofVec3f &rotation, ofVec3f &normal) const { int i1 = getWrappedIndex(index - 1); int i2 = getWrappedIndex(index); int i3 = getWrappedIndex(index + 1); ofPoint p1(points[i1]); ofPoint p2(points[i2]); ofPoint p3(points[i3]); ofVec3f v1(p1 - p2); // vector to previous point ofVec3f v2(p3 - p2); // vector to next point v1.normalize(); v2.normalize(); tangent = (v2 - v1); tangent.normalize(); rotation = v1.getCrossed(v2); angle = 180 - ofRadToDeg(acos(ofClamp(v1.x * v2.x + v1.y * v2.y + v1.z * v2.z, -1, 1))); normal = rightVector.getCrossed(tangent); normal.normalize(); }
void ofxARToolkitPlus::getTranslationAndOrientation(int markerIndex, ofVec3f &translation, ofMatrix4x4 &orientation) { ARToolKitPlus::ARMarkerInfo marker = tracker->getDetectedMarker(markerIndex); getTransMat( &marker, c, m34 ); // Translation translation.set(m34[0][3], m34[1][3], m34[2][3]); // Orientation orientation.set(m34[0][0], m34[0][1], m34[0][2], 0, m34[1][0], m34[1][1], m34[1][2], 0, m34[2][0], m34[2][1], m34[2][2], 0, 0, 0, 0, 1); }
Boid::Boid(ofVec3f pos, ofVec3f vel, radomeModel* pMod) { position = pos; velocity = vel; velocity = vel.normalize(); acceleration = ofVec3f(0,0,0); neighborPosition = ofVec3f(0,0,0); numNeighbors = 0; decay = 0.99; crowdFactor = 1.0; speedRange = ofVec2f(ofRandom(1.0, 1.5), ofRandom(2.5, 4.0)); speedRangeSquared = ofVec2f(speedRange[0] * speedRange[0], speedRange[1] * speedRange[1]); pModel = pMod; }
//-------------------------------------------------------------- ofVec3f tal2mni(ofVec3f inpoints){ ofVec3f out; ofVec3f upT(0.99, 0.97, 0.92); ofVec3f downT(0.99, 0.97, 0.84); out = inpoints.rotateRad(0.05, ofVec3f(1,0,0)); if (inpoints.z > 0){ out = out / upT; }else{ out = out / downT; } return out; }
void Creature::slerp(const ofVec3f& target, const ofVec3f& upVector) { ofVec3f zaxis = (getPosition() - target).normalized(); ofVec3f xaxis = upVector.getCrossed(zaxis).normalized(); ofVec3f yaxis = zaxis.getCrossed(xaxis); ofMatrix4x4 m; m._mat[0].set(xaxis.x, xaxis.y, xaxis.z, 0); m._mat[1].set(yaxis.x, yaxis.y, yaxis.z, 0); m._mat[2].set(zaxis.x, zaxis.y, zaxis.z, 0); ofQuaternion targetQuat = m.getRotate(); ofQuaternion currentQuat = getOrientationQuat(); currentQuat.slerp(0.1, currentQuat, targetQuat); setOrientation(currentQuat); }
// if axis1 and axis2 are not orthogonal, only axis1 will be preserved ofQuaternion makeRotate(const ofVec3f& axis1, const ofVec3f& axis2) { ofVec3f avg = (axis1 + axis2) / 2; ofVec3f z = axis1.getCrossed(axis2); ofVec3f x = axis1; ofVec3f y = z.getCrossed(x); ofMatrix4x4 mat; vector<ofVec3f> axes; axes.push_back(x.normalize()); axes.push_back(y.normalize()); axes.push_back(z.normalize()); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { mat(i, j) = axes[i][j]; } } return mat.getRotate(); }
vector<ofVec3f>::const_iterator findCloser(const ofVec3f& v, const vector<ofVec3f>& vertexs) { float dist = numeric_limits<float>::max(); vector<ofVec3f>::const_iterator idx = vertexs.begin(); float curDist; for(vector<ofVec3f>::const_iterator iter = vertexs.begin(); iter != vertexs.end(); ++iter) { curDist = v.squareDistance(*iter); if(curDist < dist) { dist = curDist; idx = iter; } } return idx; }
// Renders a vector object 'v' as an arrow and a location 'x,y' void FlowField2D::drawVector(ofVec3f v, float x, float y, float scale) { ofPushMatrix(); float arrowsize = 4; // Translate to location to render vector ofTranslate(x, y); ofSetColor(100); // Call vector heading function to get direction (note that pointing up is a heading of 0) and rotate float rotate = atan2(v.y, v.x); ofRotate(ofRadToDeg(rotate), 0, 0, 1); // Calculate length of vector & scale it to be bigger or smaller if necessary float len = v.length() * scale; // Draw three lines to make an arrow (draw pointing up since we've rotate to the proper direction) ofLine(0, 0, len, 0); ofLine(len, 0, len - arrowsize, +arrowsize / 2); ofLine(len, 0, len - arrowsize, -arrowsize / 2); ofPopMatrix(); }
void ofxARToolkitPlus::getMultiMarkerTranslationAndOrientation(ofVec3f &translation, ofMatrix4x4 &orientation) { const ARToolKitPlus::ARMultiMarkerInfoT *multiMarkerConst = tracker->getMultiMarkerConfig(); if(multiMarkerConst != NULL) { // Create a copy of the ARMultiMarkerInfoT struct ARToolKitPlus::ARMultiMarkerInfoT mm; size_t mmSize = sizeof(ARToolKitPlus::ARMultiMarkerInfoT); memcpy(&mm, multiMarkerConst, mmSize); // Copy and pass in the markers int numberOfMarkers = tracker->getNumDetectedMarkers(); #ifdef TARGET_WIN32 ARToolKitPlus::ARMarkerInfo *marker = new ARToolKitPlus::ARMarkerInfo[numberOfMarkers]; #else ARToolKitPlus::ARMarkerInfo marker[numberOfMarkers]; #endif for (int i=0; i<numberOfMarkers; i++) { marker[i] = tracker->getDetectedMarker(i); } float result = tracker->rppMultiGetTransMat(marker, numberOfMarkers, &mm); // Check for error - yes this does occur if(result < 0 || result >= INT_MAX) { tracker->arMultiGetTransMat(marker, numberOfMarkers, &mm); ofLog(OF_LOG_VERBOSE, "RPP failed on multimarker"); } // Translation translation.set(mm.trans[0][3], mm.trans[1][3], mm.trans[2][3]); // Orientation orientation.set(mm.trans[0][0], mm.trans[0][1], mm.trans[0][2], 0, mm.trans[1][0], mm.trans[1][1], mm.trans[1][2], 0, mm.trans[2][0], mm.trans[2][1], mm.trans[2][2], 0, 0, 0, 0, 1); #ifdef TARGET_WIN32 free(marker); #endif } else { ofLog(OF_LOG_VERBOSE, "MultiMarkerConfig file NULL"); } }
//-------------------------------------------------------------- void DeviceNode::createChain(ofVec3f ptAttach, ofVec3f dir) { if (mp_device) { // Physics setup physics.clear(); physics.setGravity(ofVec3f(0, -0.00075, 0)); // Normalize dir.normalize(); ofVec3f posLed = ptAttach; msa::physics::Particle3D* prev=0; for (int i=0; i<mp_device->getNbLEDs(); i++ ) { // Create particles msa::physics::Particle3D *p = physics.makeParticle(posLed,0.0025f); // Attach first one if (i==0) p->makeFixed(); // Spring if (prev){ msa::physics::Spring3D* sp = physics.makeSpring(prev, p, 1.0f, mp_device->getDistLEDs()); sp->setForceCap(1.0f); } prev = p; posLed += mp_device->getDistLEDs() * dir; //printf("mp_device->getDistLEDs()=%.3f\n", mp_device->getDistLEDs()); } if (prev) prev->makeFixed(); } }
//-------------------------------------------------------------- void testApp::setup(){ g_Rotation = ofQuaternion(0.0f, 0.0f, 0.0f, 1.0f); g_RotateStart = ofQuaternion(0.0f, 0.0f, 0.0f, 1.0f); g_LightDirection.set(-0.57735f, -0.57735f, -0.57735f); // Create some 3D objects (stored in display lists) glNewList(SHAPE_TEAPOT, GL_COMPILE); glutSolidTeapot(1.0); glEndList(); glNewList(SHAPE_TORUS, GL_COMPILE); glutSolidTorus(0.3, 1.0, 16, 32); glEndList(); glNewList(SHAPE_CONE, GL_COMPILE); glutSolidCone(1.0, 1.5, 64, 4); glEndList(); float axis[] = { 0.7f, 0.7f, 0.0f }; // initial model rotation float angle = 0.8f; // Init rotation SetQuaternionFromAxisAngle(axis, angle, g_Rotation); SetQuaternionFromAxisAngle(axis, angle, g_RotateStart); //TWEAK BAR bar.init("TweakBar", 200, 400, 200, 200, 200, 100); bar.enable(); bar.addParam("Zoom", &g_Zoom, " min=0.01 max=500.0 step=1.0 keyIncr=z keyDecr=Z help='Scale the object (1=original size).' ", false); bar.addParam("ObjRotation", &g_Rotation, " label='Object rotation' open help='Change the object orientation.' ", false); bar.addParam("Multiplier", &g_LightMultiplier, " label='Light booster' min=0.1 max=4 step=0.02 keyIncr='+' keyDecr='-' help='Increase/decrease the light power.' ", false); bar.addParam("LightDir", &g_LightDirection, " label='Light direction' open help='Change the light direction.' ", false); bar.addSeparator("separator"); bar.addParam("Ambient", g_MatAmbient, " group='Material' ", false, TW_TYPE_COLOR3F); bar.addParam("Diffuse", g_MatDiffuse, " group='Material' ", false, TW_TYPE_COLOR3F); }
ofVec3f Player::moveToNextVert(ofVec3f gPoint, float dist){ ofVec3f ng = gPoint.normalize(); float dotX = ng.dot(ofVec3f(1.0, 0.0, 0.0)); float dotY = ng.dot(ofVec3f(0.0, 1.0, 0.0)); playerMoved = true; turn.clear(); if(dotX > 0.0 && dotY > 0.0) { // 1st quadrant ofLog() << "1st quadrant"; zRotDeg = 45.0; gameObject.setOrientation(ofVec3f(0.0, 0.0, 45.0)); } else if(dotX < 0.0 && dotY > 0.0) { // 2nd quadrant ofLog() << "2nd quadrant"; zRotDeg = 45.0+90.0; gameObject.setOrientation(ofVec3f(0.0, 0.0, 45.0+90.0)); } else if(dotX < 0.0 && dotY < 0.0) { // 3rd quadrant ofLog() << "3rd quadrant"; zRotDeg = 180.0 + 45.0; gameObject.setOrientation(ofVec3f(0.0, 0.0, 180.0 + 45.0)); } else if(dotX > 0.0 && dotY < 0.0) { // 4th quadrant ofLog() << "4th quadrant"; zRotDeg = 270.0 + 45.0; gameObject.setOrientation(ofVec3f(0.0, 0.0, 270.0 + 45.0)); } ofVec3f to = gameObject.getGlobalPosition() + (gameObject.getXAxis() * dist); ofLog() << "to: " << to; if(grid->checkMoveToPoint(gameObject.getGlobalPosition(), to)) { ofLog() << "direction open"; slide.addKeyFrame(Playlist::Action::tween(0.0f, 400.0f, &gPosX, to.x, Playlist::TweenType::TWEEN_QUART , TweenTransition::TWEEN_EASE_IN_OUT)); slide.addToKeyFrame(Playlist::Action::tween(0.0f, 400.0f, &gPosY, to.y, Playlist::TweenType::TWEEN_QUART , TweenTransition::TWEEN_EASE_IN_OUT)); return to; } else { to = gameObject.getGlobalPosition() + (gameObject.getXAxis() * (dist/2.0f)); ofLog() << "direction blocked"; slide.addKeyFrame(Playlist::Action::tween(0.0f, 200.0f, &gPosX, to.x, Playlist::TweenType::TWEEN_QUART, TweenTransition::TWEEN_EASE_IN_OUT)); slide.addToKeyFrame(Playlist::Action::tween(0.0f, 200.0f, &gPosY, to.y, Playlist::TweenType::TWEEN_QUART, TweenTransition::TWEEN_EASE_IN_OUT)); slide.addToKeyFrame(Playlist::Action::tween(200.0f, 200.0f, &gPosX, gameObject.getGlobalPosition().x, Playlist::TweenType::TWEEN_QUART, TweenTransition::TWEEN_EASE_IN_OUT)); slide.addToKeyFrame(Playlist::Action::tween(200.0f, 200.0f, &gPosY, gameObject.getGlobalPosition().y, Playlist::TweenType::TWEEN_QUART, TweenTransition::TWEEN_EASE_IN_OUT)); return gameObject.getGlobalPosition(); } // player anim call }