当前位置: 首页>>代码示例>>C++>>正文


C++ Ray类代码示例

本文整理汇总了C++中Ray的典型用法代码示例。如果您正苦于以下问题:C++ Ray类的具体用法?C++ Ray怎么用?C++ Ray使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Ray类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: Intersects

        GeometryRayTestResult Intersects(const AxisAlignedBox& Box, const Ray& Cast)
        {
            // Code in this function is based on the equivalent in Ogre
            Vector3 CastDir = Cast.GetNormal();
            Vector3 AbsoluteDir = CastDir;
            AbsoluteDir.X = MathTools::Abs( AbsoluteDir.X );
            AbsoluteDir.Y = MathTools::Abs( AbsoluteDir.Y );
            AbsoluteDir.Z = MathTools::Abs( AbsoluteDir.Z );

            // A small fixed sized constant time sorting algorithm for sorting the length of each axis.
            Whole MaxAxis = 0, MidAxis = 1, MinAxis = 2;
            if( AbsoluteDir[0] < AbsoluteDir[2] ) {
                MaxAxis = 2;
                MinAxis = 1;
            }else if( AbsoluteDir[1] < AbsoluteDir[MinAxis] ) {
                MidAxis = MinAxis;
                MinAxis = 1;
            }else if( AbsoluteDir[1] > AbsoluteDir[MaxAxis] ) {
                MidAxis = MaxAxis;
                MaxAxis = 1;
            }

            if(IsInside(Box,Cast.Origin))
            {
                Vector3 Intersects;
                Intersects[MinAxis] = 0;
                Intersects[MidAxis] = 0;
                Intersects[MaxAxis] = 1;
                /*Plane Side(Intersects,)
                if(CastDir[MaxAxis]>0)
                {

                }else{

                }
                return GeometryRayTestResult(true,Ray(,Vector3));*/
            }

            SegmentPosPair Distances(0,std::numeric_limits<Real>::infinity());

            ::CalculateAxis(MaxAxis,Cast,Box,Distances);
            if( AbsoluteDir[MidAxis] < std::numeric_limits<Real>::epsilon() ) {
                if( Cast.GetOrigin()[MidAxis] < Box.MinExt[MidAxis] || Cast.GetOrigin()[MidAxis] > Box.MaxExt[MidAxis] ||
                    Cast.GetOrigin()[MinAxis] < Box.MinExt[MinAxis] || Cast.GetOrigin()[MinAxis] > Box.MaxExt[MinAxis] )
                {
                    return GeometryRayTestResult(false,Ray());
                }
            }else{
                ::CalculateAxis(MidAxis,Cast,Box,Distances);
                if( AbsoluteDir[MinAxis] < std::numeric_limits<Real>::epsilon() ) {
                    if( Cast.GetOrigin()[MinAxis] < Box.MinExt[MinAxis] || Cast.GetOrigin()[MinAxis] > Box.MaxExt[MinAxis] ) {
                        return GeometryRayTestResult(false,Ray());
                    }
                }else{
                    ::CalculateAxis(MinAxis,Cast,Box,Distances);
                }
            }

            Ray Ret( Cast.GetOrigin() + (CastDir * Distances.first), Cast.GetOrigin() + (CastDir * Distances.second) );
            return GeometryRayTestResult(true,Ret);
        }
开发者ID:,项目名称:,代码行数:61,代码来源:

示例2: parseRay

bool parseRay(Ray &ray, TiXmlElement* config)
{
  ray.clear();
  ray.type = VisualSensor::RAY;

  TiXmlElement *horizontal = config->FirstChildElement("horizontal");
  if (horizontal)
  {
    const char* samples_char = horizontal->Attribute("samples");
    if (samples_char)
    {
      try
      {
        ray.horizontal_samples = boost::lexical_cast<unsigned int>(samples_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray horizontal samples [%s] is not a valid float: %s", samples_char, e.what());
        return false;
      }
    }

    const char* resolution_char = horizontal->Attribute("resolution");
    if (resolution_char)
    {
      try
      {
        ray.horizontal_resolution = boost::lexical_cast<double>(resolution_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray horizontal resolution [%s] is not a valid float: %s", resolution_char, e.what());
        return false;
      }
    }   
    
    const char* min_angle_char = horizontal->Attribute("min_angle");
    if (min_angle_char)
    {
      try
      {
        ray.horizontal_min_angle = boost::lexical_cast<double>(min_angle_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray horizontal min_angle [%s] is not a valid float: %s", min_angle_char, e.what());
        return false;
      }
    }

    const char* max_angle_char = horizontal->Attribute("max_angle");
    if (max_angle_char)
    {
      try
      {
        ray.horizontal_max_angle = boost::lexical_cast<double>(max_angle_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray horizontal max_angle [%s] is not a valid float: %s", max_angle_char, e.what());
        return false;
      }
    }
  }
  
  TiXmlElement *vertical = config->FirstChildElement("vertical");
  if (vertical)
  {
    const char* samples_char = vertical->Attribute("samples");
    if (samples_char)
    {
      try
      {
        ray.vertical_samples = boost::lexical_cast<unsigned int>(samples_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray vertical samples [%s] is not a valid float: %s", samples_char, e.what());
        return false;
      }
    }

    const char* resolution_char = vertical->Attribute("resolution");
    if (resolution_char)
    {
      try
      {
        ray.vertical_resolution = boost::lexical_cast<double>(resolution_char);
      }
      catch (boost::bad_lexical_cast &e)
      {
        logError("Ray vertical resolution [%s] is not a valid float: %s", resolution_char, e.what());
        return false;
      }
    }   
    
    const char* min_angle_char = vertical->Attribute("min_angle");
    if (min_angle_char)
    {
      try
//.........这里部分代码省略.........
开发者ID:TRECVT,项目名称:urdfdom,代码行数:101,代码来源:urdf_sensor.cpp

示例3: worldToObjectSpace

    bool Sphere::hit(const Ray &ws_ray, float &thit,
                      std::shared_ptr<DifferentialGeometry> &dg) const {
      float phi;
      Point phit;

      //UNCOMMENT FOR BROKEN BB
      if(!mImpl->bb.hit(ws_ray))
        return false;

      // Transform the ray into object space
      Transform transform = worldToObjectSpace();
      Ray os_ray = transform(ws_ray);



      // Do ray-sphere intersection in object space
      // Compute quadratic sphere coefficients

      float A = os_ray.dir().x() * os_ray.dir().x() +
                os_ray.dir().y() * os_ray.dir().y() +
                os_ray.dir().z() * os_ray.dir().z();
      float B = 2.0 * (os_ray.dir().x() * os_ray.origin().x() +
                     os_ray.dir().y() * os_ray.origin().y() +
                     os_ray.dir().z() * os_ray.origin().z());
      float C = os_ray.origin().x() * os_ray.origin().x() +
                os_ray.origin().y() * os_ray.origin().y() +
                os_ray.origin().z() * os_ray.origin().z() -
                mImpl->radius * mImpl->radius;


      // Solve quadratic equation for t values
      float t0, t1;
      if (!mImpl->Quadratic(A,B,C, &t0, &t1)) return false;
      // compute intersection distance along ray
      if (t0 > os_ray.maxt() || t1 < os_ray.mint())
        return false;

      thit = t0;
      if (t0 < os_ray.mint()) {
        thit = t1;
        if (thit > os_ray.maxt()) return false;
      }


      // Compute sphere hit position and phi
      phit = os_ray(thit);

      if (phit.x() == 0.f && phit.y() == 0.f) phit.x(1e-5f * mImpl->radius);

      phi = atan2f(phit.y(), phit.x());

      if (phi < 0.) phi += 2.f*M_PI;

      // Test against clipping parameters
      if ((mImpl->zmin > -mImpl->radius && phit.z() < mImpl->zmin) ||
        (mImpl->zmax < mImpl->radius && phit.z() > mImpl->zmax) ||
         phi > mImpl->phiMax) {
           if (thit == t1) return false;
           thit = t1;

           if ((mImpl->zmin > -mImpl->radius && phit.z() < mImpl->zmin) ||
             (mImpl->zmax < mImpl->radius && phit.z() > mImpl->zmax) ||
             phi > mImpl->phiMax)
             return false;
         }

         // find parametric representation of sphere
         float u = phi/mImpl->phiMax;

         float theta = acosf(Clamp(phit.z()/mImpl->radius, -1.f, 1.f));

         float v = (theta - mImpl->thetaMin) / (mImpl->thetaMax - mImpl->thetaMin);
         float zradius = sqrtf(phit.x() * phit.x() + phit.y() * phit.y());
         float invzradius = 1.f / zradius;
         float cosphi = phit.x() * invzradius;
         float sinphi = phit.y() * invzradius;
         Vector dpdu(-mImpl->phiMax * phit.y(), mImpl->phiMax * phit.x(), 0);
         Vector dpdv = (mImpl->thetaMax - mImpl->thetaMin) *
                Vector(phit.z() * cosphi, phit.z() * sinphi,
                      -mImpl->radius * sinf(theta));

        Vector d2Pduu = -mImpl->phiMax * mImpl->phiMax * Vector(phit.x(), phit.y(), 0.0f);
        Vector d2Pduv = (mImpl->thetaMax - mImpl->thetaMin) * phit.z() * mImpl->phiMax * Vector(-sinphi, cosphi, 0.0f);
        Vector d2Pdvv = -(mImpl->thetaMax - mImpl->thetaMin) * (mImpl->thetaMax - mImpl->thetaMin) * Vector(phit.x(), phit.y(), phit.z());

        float E = dpdu.dot(dpdu);
        float F = dpdu.dot(dpdv);
        float G = dpdv.dot(dpdv);
        Vector N = dpdu.cross(dpdv).normalized();
        float e = N.dot(d2Pduu);
        float f = N.dot(d2Pduv);
        float g = N.dot(d2Pdvv);

        float invEGF2 = 1.f/(E * G - F * F);
        Normal dndu = Normal((f * F - e * G) * invEGF2 * dpdu +
                            (e * F - f * E) * invEGF2 * dpdv);
        Normal dndv = Normal((g * F - f * G) * invEGF2 * dpdu +
                            (f*F - g * E) * invEGF2 * dpdv);


//.........这里部分代码省略.........
开发者ID:ahoover64,项目名称:raytracer,代码行数:101,代码来源:Sphere.cpp

示例4: _findNodes

    void DefaultZone::_findNodes( const Ray &t, 
							      PCZSceneNodeList &list, 
                                  PortalList &visitedPortals,
						 	      bool includeVisitors,
							      bool recurseThruPortals,
							      PCZSceneNode *exclude )
    {
		// if this zone has an enclosure, check against the enclosure AABB first
		if (mEnclosureNode)
		{
			std::pair<bool, Real> nsect = t.intersects(mEnclosureNode->_getWorldAABB());
			if (!nsect.first)
			{
				// AABB of zone does not intersect t, just return.
				return;
			}
		}

		// check nodes at home in this zone
	    PCZSceneNodeList::iterator it = mHomeNodeList.begin();
	    while ( it != mHomeNodeList.end() )
	    {
			PCZSceneNode * pczsn = *it;
			if ( pczsn != exclude )
			{
				// make sure node is not already in the list (might have been added in another
				// zone it was visiting)
				PCZSceneNodeList::iterator it2 = list.find(pczsn);
				if (it2 == list.end())
				{
					std::pair<bool, Real> nsect = t.intersects( pczsn -> _getWorldAABB() );
					if ( nsect.first )
					{
						list.insert( pczsn );
					}
				}
			}
		    ++it;
	    }

		if (includeVisitors)
		{
			// check visitor nodes
			PCZSceneNodeList::iterator iter = mVisitorNodeList.begin();
			while ( iter != mVisitorNodeList.end() )
			{
				PCZSceneNode * pczsn = *iter;
				if ( pczsn != exclude )
				{
					// make sure node is not already in the list (might have been added in another
					// zone it was visiting)
					PCZSceneNodeList::iterator it2 = list.find(pczsn);
					if (it2 == list.end())
					{
						std::pair<bool, Real> nsect = t.intersects( pczsn -> _getWorldAABB() );
						if ( nsect.first )
						{
							list.insert( pczsn );
						}
					}
				}
				++iter;
			}
		}

		// if asked to, recurse through portals
		if (recurseThruPortals)
		{
			PortalList::iterator pit = mPortals.begin();
			while ( pit != mPortals.end() )
			{
				Portal * portal = *pit;
				// check portal versus bounding box
				if (portal->intersects(t))
				{
					// make sure portal hasn't already been recursed through
					PortalList::iterator pit2 = std::find(visitedPortals.begin(), visitedPortals.end(), portal);
					if (pit2 == visitedPortals.end())
					{
						// save portal to the visitedPortals list
						visitedPortals.push_front(portal);
						// recurse into the connected zone 
						portal->getTargetZone()->_findNodes(t, 
															list, 
															visitedPortals,
															includeVisitors, 
															recurseThruPortals, 
															exclude);
					}
				}
				pit++;
			}
		}

	}
开发者ID:JoeyZh,项目名称:ogre-android,代码行数:95,代码来源:OgreDefaultZone.cpp

示例5: getCameraToViewportRay

	//---------------------------------------------------------------------()
	void Camera::getCameraToViewportBoxVolume(Real screenLeft, 
		Real screenTop, Real screenRight, Real screenBottom, 
		PlaneBoundedVolume* outVolume, bool includeFarPlane)
	{
		outVolume->planes.clear();

		if (mProjType == PT_PERSPECTIVE)
		{

			// Use the corner rays to generate planes
			Ray ul = getCameraToViewportRay(screenLeft, screenTop);
			Ray ur = getCameraToViewportRay(screenRight, screenTop);
			Ray bl = getCameraToViewportRay(screenLeft, screenBottom);
			Ray br = getCameraToViewportRay(screenRight, screenBottom);


			Vector3 normal;
			// top plane
			normal = ul.getDirection().crossProduct(ur.getDirection());
			normal.normalise();
			outVolume->planes.push_back(
				Plane(normal, getDerivedPosition()));

			// right plane
			normal = ur.getDirection().crossProduct(br.getDirection());
			normal.normalise();
			outVolume->planes.push_back(
				Plane(normal, getDerivedPosition()));

			// bottom plane
			normal = br.getDirection().crossProduct(bl.getDirection());
			normal.normalise();
			outVolume->planes.push_back(
				Plane(normal, getDerivedPosition()));

			// left plane
			normal = bl.getDirection().crossProduct(ul.getDirection());
			normal.normalise();
			outVolume->planes.push_back(
				Plane(normal, getDerivedPosition()));

		}
		else
		{
			// ortho planes are parallel to frustum planes

			Ray ul = getCameraToViewportRay(screenLeft, screenTop);
			Ray br = getCameraToViewportRay(screenRight, screenBottom);

			updateFrustumPlanes();
			outVolume->planes.push_back(
				Plane(mFrustumPlanes[FRUSTUM_PLANE_TOP].normal, ul.getOrigin()));
			outVolume->planes.push_back(
				Plane(mFrustumPlanes[FRUSTUM_PLANE_RIGHT].normal, br.getOrigin()));
			outVolume->planes.push_back(
				Plane(mFrustumPlanes[FRUSTUM_PLANE_BOTTOM].normal, br.getOrigin()));
			outVolume->planes.push_back(
				Plane(mFrustumPlanes[FRUSTUM_PLANE_LEFT].normal, ul.getOrigin()));
			

		}

		// near & far plane applicable to both projection types
		outVolume->planes.push_back(getFrustumPlane(FRUSTUM_PLANE_NEAR));
		if (includeFarPlane)
			outVolume->planes.push_back(getFrustumPlane(FRUSTUM_PLANE_FAR));
	}
开发者ID:milram,项目名称:ogre-1.7.4-osx,代码行数:68,代码来源:OgreCamera.cpp

示例6: pow

  Vec3f PhongShader::shade(Ray& ray)
  {
    if (!scene) return Vec3f();

    vector<Light*>::iterator lightIt;
    Vec3f color;
    Point3f iPoint = ray.getIntersectionPoint();
    Vec3f N = ray.normal.normalized();

    for (lightIt = scene->lights.begin(); lightIt != scene->lights.end(); ++lightIt)
    {
      Light* light = *lightIt;
      if (!light) { color += Vec3f(0.5,0.5,0.5); continue; }

      float invlightDist = 1.0f / (light->pos() - iPoint).length();
      invlightDist *= invlightDist * light->intensity();

      Vec3f L = ( light->pos()- iPoint).normalized();
      color += ambient % light->ambient() * invlightDist;

      float angle = N * L;

      if (angle > 0.0f)
      {	
        Vec3f diff = light->diffuse() % diffuse * angle * invlightDist;
        Vec3f E = ray.org.vec3f().normalized();
        L = -L;
        float dotLN = N * L;
        Vec3f R = L - (2.0 * dotLN * N);

        float spec = pow(max( R * E , 0.0f ), shininess );
        diff += light->specular() % specular * spec * invlightDist;

        if (light->shadows() > 0.0f)
        {
          Point3f rndPos(light->pos().x-(RND-0.5)*light->radius(),
              light->pos().y-(RND-0.5)*light->radius(),
              light->pos().z-(RND-0.5)*light->radius());

          Ray shadowRay(rndPos,iPoint-rndPos);
          shadowRay.tmin = 0.01;
          shadowRay.tmax = 0.99;

          if (scene->traceShadowRay(shadowRay,(SceneObject*)ray.obj))
            diff *=  (1.0 - light->shadows()*(1.0-refract)*(1.0-reflect));
        }	

        color += diff;
      }
    }

    ray.color = color;

    if (ray.bounce < scene->maxBounce)
    {
      if (reflect > 0.0f)
      {
        Ray rayRefl = ray.reflect();
        color += color*(1.0f - reflect) + scene->traceRay(rayRefl,(SceneObject*)ray.obj) * reflect;
      }
      if (refract > 0.0f)
      {
        Ray rayRefr = ray.refract(IOR);
        color += color*(1.0f - refract) + scene->traceRay(rayRefr,(SceneObject*)ray.obj) * refract;
      }
    }

    return color;	
  }
开发者ID:patgithub,项目名称:Tomo,代码行数:69,代码来源:shader.cpp

示例7: P

	std::pair<bool, float> Capsule::intersects(const Ray& ray) const
	{
		const Vector3& org = ray.getOrigin();
		const Vector3& dir = ray.getDirection();

		Vector3 segDir = mSegment.getEnd() - mSegment.getStart();
		float segExtent = segDir.normalize() * 0.5f;
		Vector3 segCenter = mSegment.getStart() + segDir * segExtent;

		Vector3 basis[3];
		basis[0] = segDir;
		basis[0].orthogonalComplement(basis[1], basis[2]);

		float rSqr = mRadius * mRadius;

		Vector3 diff = org - segCenter;
		Vector3 P(basis[1].dot(diff), basis[2].dot(diff), basis[0].dot(diff));

		// Get the z-value, in capsule coordinates, of the incoming line's
		// unit-length direction.
		float dz = basis[0].dot(dir);
		if (std::abs(dz) == 1.0f)
		{
			// The line is parallel to the capsule axis.  Determine whether the
			// line intersects the capsule hemispheres.
			float radialSqrDist = rSqr - P[0] * P[0] - P[1] * P[1];
			if (radialSqrDist < 0.0f)
			{
				// The line is outside the cylinder of the capsule, so there is no
				// intersection.
				return std::make_pair(false, 0.0f);
			}

			// The line intersects the hemispherical caps.
			float zOffset = std::sqrt(radialSqrDist) + segExtent;
			if (dz > 0.0f)
				return std::make_pair(true, -P[2] - zOffset);
			else
				return std::make_pair(true, P[2] - zOffset);
		}

		// Convert the incoming line unit-length direction to capsule coordinates.
		Vector3 D(basis[1].dot(dir), basis[2].dot(dir), dz);

		// Test intersection of line with infinite cylinder 
		float a0 = P[0] * P[0] + P[1] * P[1] - rSqr;
		float a1 = P[0] * D[0] + P[1] * D[1];
		float a2 = D[0] * D[0] + D[1] * D[1];
		float discr = a1*a1 - a0*a2;

		if (discr < 0.0f)
		{
			// The line does not intersect the infinite cylinder.
			return std::make_pair(false, 0.0f);
		}

		float root, inv, tValue, zValue;
		float nearestT = std::numeric_limits<float>::max();
		bool foundOneIntersection = false;

		if (discr > 0.0f)
		{
			// The line intersects the infinite cylinder in two places.
			root = std::sqrt(discr);
			inv = 1.0f / a2;

			tValue = (-a1 - root)*inv;
			zValue = P[2] + tValue*D[2];
			if (std::abs(zValue) <= segExtent)
			{
				nearestT = tValue;
				foundOneIntersection = true;
			}

			tValue = (-a1 + root)*inv;
			zValue = P[2] + tValue*D[2];
			if (std::abs(zValue) <= segExtent)
			{
				if (foundOneIntersection)
					return std::make_pair(true, nearestT);
				else
				{
					nearestT = tValue;
					foundOneIntersection = true;
				}
			}
		}
		else
		{
			// The line is tangent to the infinite cylinder but intersects the
			// cylinder in a single point.
			tValue = -a1 / a2;
			zValue = P[2] + tValue*D[2];
			if (std::abs(zValue) <= segExtent)
				return std::make_pair(true, tValue);
		}

		// Test intersection with bottom hemisphere.
		float PZpE = P[2] + segExtent;
		a1 += PZpE*D[2];
//.........这里部分代码省略.........
开发者ID:AlfHub,项目名称:BansheeEngine,代码行数:101,代码来源:BsCapsule.cpp

示例8: init


//.........这里部分代码省略.........
		SSx[0] = -1.0/3.0;
		SSx[1] = 0.0;
		SSx[2] = 1.0/3.0;
		SSx[3] = -1.0/3.0;
		SSx[4] = 0.0;
		SSx[5] = 1.0/3.0;
		SSx[6] = -1.0/3.0;
		SSx[7] = 0.0;
		SSx[8] = 1.0/3.0;


		float SSy [9];

		SSy[0] = 1.0/3.0;
		SSy[1] = 1.0/3.0;
		SSy[2] = 1.0/3.0;
		SSy[3] = 0.0;
		SSy[4] = 0.0;
		SSy[5] = 0.0;
		SSy[6] = -1.0/3.0;
		SSy[7] = -1.0/3.0;
		SSy[8] = -1.0/3.0;
		
		srand((unsigned)time(NULL));
		float shadow = 1.0;

		for (int x=0; x<renderWidth; x++) 
		{	
			for (int y=0; y<renderHeight; y++) 
			{
				shadow = 1.0;
				renderColor = glm::vec3(0);


				
				for (int i=0; i<rays; i++) 
				{
					SSx[i] += 0.01*((((float)rand() / (float)RAND_MAX)/3.75) -1.0/7.5);
					SSy[i] += 0.01*((((float)rand() / (float)RAND_MAX)/3.75) -1.0/7.5);
				}
				
				for (int c=0; c<rays; c++) 
				{
					pixelColor = glm::vec3(0);
					glm::vec3 rayDirection = glm::vec3((x+SSx[c]-renderWidth/2.0)/yFov,(y+SSy[c]-renderHeight/2.0)/yFov,pixelPlane) - camera.position;

					rayDirection = glm::normalize(rayDirection);


					bool insideObject = false;
					bool hitWall = false;
					int rayDepth = 1;
					float t = 999999.0;
					float tMin = 999999.0;
					int objectID = -1;
					float lastRefIndex = 1.3333;
					int maxDepth = 12;


					Ray ray = Ray();
					ray.createRay(camera.position,rayDirection,1.0f,100.0f,maxDepth, false);
					ray.trace(obj,maxDepth);
					renderColor += ray.color;
					
				}
				

				renderColor.r = glm::min(renderColor.r/raysPerPixel,1.0f);
				renderColor.g = glm::min(renderColor.g/raysPerPixel,1.0f);
				renderColor.b = glm::min(renderColor.b/raysPerPixel,1.0f);

				pixels[3*(y*renderWidth+x)] = 255*renderColor.r;
				pixels[3*(y*renderWidth+x)+1] = 255*renderColor.g;
				pixels[3*(y*renderWidth+x)+2] = 255*renderColor.b;

				
			}
			std::cout << "progress: " << x << " / " << renderWidth << " done" << std::endl;
		}


		float ms = (glutGet(GLUT_ELAPSED_TIME) - seconds);

		std::cout << "RenderTime: " << ms << " milliseconds" << std::endl;
		//  (0,480)----------------- (640,480)
		//         |               |
		//         |   The Screen  |
		//         |               |
		//         |               |
		//    (0,0)----------------- (640,0)


	printf("OpenGL Version:%s\n",glGetString(GL_VERSION));
	printf("GLSL Version  :%s\n\n",glGetString(GL_SHADING_LANGUAGE_VERSION));

		glGenTextures( 1, &imageTexture );
	glBindTexture( GL_TEXTURE_2D, imageTexture);

		
}
开发者ID:RasmusKarlsson,项目名称:Raytracer,代码行数:101,代码来源:main.cpp

示例9: trace

Color trace(const Scene& scene, Ray ray, int depth)
{
    const Color background(0,0,0);
    const int maxDepth = 3;
    if (depth >= maxDepth)
        return background;

    Color color(0,0,0);
    double distance = 0;
    const Primitive* prim = NULL;
    int intersectionType = 0;

    findNearsetIntersection(scene, ray, &prim, &distance, &intersectionType);

    if (prim != NULL)
    {
        if (prim->IsIlluminative())
        {
            return prim->GetMaterial().GetColor();
        }

        const Vector3 intersectionPoint = ray.GetPoint(distance);
        const Vector3 n = prim->GetNormal(intersectionPoint);

        if (prim->GetMaterial().GetDiffuse() > 0)
        {
            for (Scene::ConstIterator it = scene.Begin(); it != scene.End(); it++)
            {
                const double intensive = getIntensity((*it), intersectionPoint, n, scene);

                if (intensive != .0)
                {
                    Vector3 x = (prim->GetMaterial().GetColor());
                    Vector3 y = ((*it)->GetMaterial().GetColor());

                    color = color + (intensive * prim->GetMaterial().GetDiffuse()) * x * y;
                }
            }
        }

        //refraction
        {
            const Vector3 x = ray.GetDirection();
            const Vector3 y = intersectionType * (-n);

            double n;
            if (intersectionType == IntersectOutside)
                n = 1.0 / prim->GetMaterial().GetRefractionRate();
            else
                n = prim->GetMaterial().GetRefractionRate();

            const double sin_1 = sqrt(1 - Dot(x,y));
            const double sin_2 = n * sin_1;

            if (sin_2 < 1)
            {
                const double cos_2 = sqrt(1 - sin_2);
                Vector3 xPerpendicular = x - Dot(x,y)*y;
                Vector3 z = cos_2 * y + sin_2 * xPerpendicular;
                z.Normalize();

                if (prim->GetMaterial().GetRefraction() > 0)
                {
                    if (intersectionType == IntersectInside)
                    {
                        color = color +
                            prim->GetMaterial().GetRefraction() *
                            exp(-prim->GetMaterial().GetAbsorptionRate()*distance) *
                            trace(scene, Ray(intersectionPoint, z), depth + 1);
                    }
                    else
                        color = color +
                            prim->GetMaterial().GetRefraction() * trace(scene, Ray(intersectionPoint, z), depth + 1);
                }
            }
        }

        //reflection
        if (prim->GetMaterial().GetReflection() > 0)
        {
            const Vector3 a = ray.GetDirection();
            Vector3 newA = a - 2 * (Dot(a,n)) * n;
            color = color + prim->GetMaterial().GetReflection() * trace(scene, Ray(intersectionPoint, newA), depth + 1);
        }
    }
    return color;
}
开发者ID:trams,项目名称:YetAnotherRayTracer,代码行数:87,代码来源:engine.cpp

示例10: switch

bool BoundingBox::intersects(const Ray& ray) const {
	if (mNull)
		return false;

	switch (ray.getClassification())
	{
	case Ray::MMM:
		// side(R,HD) < 0 or side(R,FB) > 0 or side(R,EF) > 0 or side(R,DC) < 0 or side(R,CB) < 0 or side(R,HE) > 0 to miss

		if ((ray.x() < mXMin) || (ray.y() < mYMin) || (ray.z() < mZMin) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMax < 0) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMax < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMin < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMax > 0))
			return false;

		return true;

	case Ray::MMP:
		// side(R,HD) < 0 or side(R,FB) > 0 or side(R,HG) > 0 or side(R,AB) < 0 or side(R,DA) < 0 or side(R,GF) > 0 to miss

		if ((ray.x() < mXMin) || (ray.y() < mYMin) || (ray.z() > mZMax) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMax < 0) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMin < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMin < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMax > 0))
			return false;

		return true;

	case Ray::MPM:
		// side(R,EA) < 0 or side(R,GC) > 0 or side(R,EF) > 0 or side(R,DC) < 0 or side(R,GF) < 0 or side(R,DA) > 0 to miss

		if ((ray.x() < mXMin) || (ray.y() > mYMax) || (ray.z() < mZMin) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMin < 0) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMax < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMax < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMin > 0))
			return false;

		return true;

	case Ray::MPP:
		// side(R,EA) < 0 or side(R,GC) > 0 or side(R,HG) > 0 or side(R,AB) < 0 or side(R,HE) < 0 or side(R,CB) > 0 to miss

		if ((ray.x() < mXMin) || (ray.y() > mYMax) || (ray.z() > mZMax) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMin < 0) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMin < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMax < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMin > 0))
			return false;

		return true;

	case Ray::PMM:
		// side(R,GC) < 0 or side(R,EA) > 0 or side(R,AB) > 0 or side(R,HG) < 0 or side(R,CB) < 0 or side(R,HE) > 0 to miss

		if ((ray.x() > mXMax) || (ray.y() < mYMin) || (ray.z() < mZMin) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMax < 0) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMax < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMin < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMax > 0))
			return false;

		return true;

	case Ray::PMP:
		// side(R,GC) < 0 or side(R,EA) > 0 or side(R,DC) > 0 or side(R,EF) < 0 or side(R,DA) < 0 or side(R,GF) > 0 to miss

		if ((ray.x() > mXMax) || (ray.y() < mYMin) || (ray.z() > mZMax) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMax < 0) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMin < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMin < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMax > 0))
			return false;

		return true;

	case Ray::PPM:
		// side(R,FB) < 0 or side(R,HD) > 0 or side(R,AB) > 0 or side(R,HG) < 0 or side(R,GF) < 0 or side(R,DA) > 0 to miss

		if ((ray.x() > mXMax) || (ray.y() > mYMax) || (ray.z() < mZMin) ||
			(ray.R0() + ray.i() * mYMax - ray.j() * mXMin < 0) ||
			(ray.R0() + ray.i() * mYMin - ray.j() * mXMax > 0) ||
			(ray.R1() + ray.i() * mZMin - ray.k() * mXMin > 0) ||
			(ray.R1() + ray.i() * mZMax - ray.k() * mXMax < 0) ||
			(ray.R3() - ray.k() * mYMax + ray.j() * mZMax < 0) ||
			(ray.R3() - ray.k() * mYMin + ray.j() * mZMin > 0))
//.........这里部分代码省略.........
开发者ID:davidbrazdil,项目名称:ray-tracing,代码行数:101,代码来源:BoundingBox.cpp

示例11: acos

/*
 * Calculates the output ray \a outputRay for the \a incident ray for the intersection parameters \a dg.
 *
 * Returns FALSE if there is not output ray.
 */
bool MaterialAngleDependentSpecular::OutputRay( const Ray& incident, DifferentialGeometry* dg, RandomDeviate& rand, Ray* outputRay  ) const
{
    double reflectivity = 0.0;

    NormalVector dgNormal;
    if( dg->shapeFrontSide )
    {
        if( !reflectivityFront.getValue() )	return ( false );
        dgNormal = dg->normal;

        // Product
        double incidenceAngle  = acos( DotProduct( -incident.direction(), dgNormal ) );
        reflectivity = OutputPropertyValue( m_frontReflectivityIncidenceAngle,  m_frontReflectivityValue, incidenceAngle );
    }
    else
    {
        if( !reflectivityBack.getValue() )	return ( false );

        dgNormal = - dg->normal;
        double incidenceAngle  = acos( DotProduct( -incident.direction(), dgNormal) );
        reflectivity = OutputPropertyValue( m_backReflectivityIncidenceAngle,  m_backReflectivityValue, incidenceAngle );

    }

    double randomNumber = rand.RandomDouble();
    if ( randomNumber >= reflectivity  ) return ( false );

    //Compute reflected ray (local coordinates )
    //Ray* reflected = new Ray();
    //reflected.origin = dg->point;
    outputRay->origin = dg->point;

    NormalVector normalVector;
    double sSlope = sigmaSlope.getValue() / 1000;
    if( sSlope > 0.0 )
    {
        NormalVector errorNormal;
        if ( distribution.getValue() == 0 )
        {
            double phi = gc::TwoPi * rand.RandomDouble();
            double theta = sSlope * rand.RandomDouble();

            errorNormal.x = sin( theta ) * sin( phi ) ;
            errorNormal.y = cos( theta );
            errorNormal.z = sin( theta ) * cos( phi );
        }
        else if (distribution.getValue() == 1 )
        {
            errorNormal.x = sSlope * tgf::AlternateBoxMuller( rand );
            errorNormal.y = 1.0;
            errorNormal.z = sSlope * tgf::AlternateBoxMuller( rand );
        }
        Vector3D r = dgNormal;
        Vector3D s = Normalize( dg->dpdu );
        Vector3D t = Normalize( dg->dpdv );

        Transform trasform( s.x, s.y, s.z, 0.0,
                            r.x, r.y, r.z, 0.0,
                            t.x, t.y, t.z, 0.0,
                            0.0, 0.0, 0.0, 1.0);

        NormalVector normalDirection = trasform.GetInverse()( errorNormal );
        normalVector = Normalize( normalDirection );
    }
    else
    {
        normalVector = dgNormal;
    }

    double cosTheta = DotProduct( normalVector, incident.direction() );
    outputRay->setDirection( Normalize( incident.direction() - 2.0 * normalVector * cosTheta ) );
    return ( true );

}
开发者ID:mblancomuriel,项目名称:tonatiuh,代码行数:79,代码来源:MaterialAngleDependentSpecular.cpp

示例12: make_pair

pair<int, float> Grid::trace(const Ray &ray, float tmin, float tmax, int ignored_id, int flags) const {
	float3 p1 = ray.at(tmin), p2 = ray.at(tmax);
	int2 pos = worldToGrid((int2)p1.xz()), end = worldToGrid((int2)p2.xz());
	
	//TODO: verify for rays going out of grid space
	if(!isInsideGrid(pos) || !isInsideGrid(end))
		return make_pair(-1, constant::inf);

	// Algorithm idea from: RTCD by Christer Ericson
	int dx = end.x > pos.x? 1 : end.x < pos.x? -1 : 0;
	int dz = end.y > pos.y? 1 : end.y < pos.y? -1 : 0;

	float cell_size = (float)node_size;
	float inv_cell_size = 1.0f / cell_size;
	float lenx = fabs(p2.x - p1.x);
	float lenz = fabs(p2.z - p1.z);

	float minx = float(node_size) * floorf(p1.x * inv_cell_size), maxx = minx + cell_size;
	float minz = float(node_size) * floorf(p1.z * inv_cell_size), maxz = minz + cell_size;
	float tx = (p1.x > p2.x? p1.x - minx : maxx - p1.x) / lenx;
	float tz = (p1.z > p2.z? p1.z - minz : maxz - p1.z) / lenz;

	float deltax = cell_size / lenx;
	float deltaz = cell_size / lenz;

	int out = -1;
	float out_dist = tmax + constant::epsilon;

	while(true) {
		int node_id = nodeAt(pos);
		const Node &node = m_nodes[node_id];

		if(flagTest(node.obj_flags, flags) && intersection(ray, node.bbox) < out_dist) {
			const Object *objects[node.size];
			int count = extractObjects(node_id, objects, ignored_id, flags);

			for(int n = 0; n < count; n++) {
				float dist = intersection(ray, objects[n]->bbox);
				if(dist < out_dist) {
					out_dist = dist;
					out = objects[n] - &m_objects[0];
				}
			}	
			
			if(node.is_dirty)
				updateNode(node_id);
		}

		if(tx <= tz || dz == 0) {
			if(pos.x == end.x)
				break;
			tx += deltax;
			pos.x += dx;
		}
		else {
			if(pos.y == end.y)
				break;
			tz += deltaz;
			pos.y += dz;
		}
		float ray_pos = tmin + max((tx - deltax) * lenx, (tz - deltaz) * lenz);
		if(ray_pos >= out_dist)
			break;
	}

	return make_pair(out, out_dist);
}
开发者ID:ChunHungLiu,项目名称:FreeFT,代码行数:67,代码来源:grid_intersect.cpp

示例13: Intersects

bool AABB::Intersects( const Ray& r ) const
{
	return r.Intersects( *this );
}
开发者ID:MinorKeyGames,项目名称:Eldritch,代码行数:4,代码来源:aabb.cpp

示例14: Vector4

void StaticModelGroup::ProcessRayQuery(const RayOctreeQuery& query, PODVector<RayQueryResult>& results)
{
    // If no bones or no bone-level testing, use the Drawable test
    RayQueryLevel level = query.level_;
    if (level < RAY_AABB)
    {
        Drawable::ProcessRayQuery(query, results);
        return;
    }

    // Check ray hit distance to AABB before proceeding with more accurate tests
    // GetWorldBoundingBox() updates the world transforms
    if (query.ray_.HitDistance(GetWorldBoundingBox()) >= query.maxDistance_)
        return;
    
    for (unsigned i = 0; i < numWorldTransforms_; ++i)
    {
        // Initial test using AABB
        float distance = query.ray_.HitDistance(boundingBox_.Transformed(worldTransforms_[i]));
        Vector3 normal = -query.ray_.direction_;
        
        // Then proceed to OBB and triangle-level tests if necessary
        if (level >= RAY_OBB && distance < query.maxDistance_)
        {
            Matrix3x4 inverse = worldTransforms_[i].Inverse();
            Ray localRay = query.ray_.Transformed(inverse);
            distance = localRay.HitDistance(boundingBox_);
            
            if (level == RAY_TRIANGLE && distance < query.maxDistance_)
            {
                distance = M_INFINITY;
                
                for (unsigned j = 0; j < batches_.Size(); ++j)
                {
                    Geometry* geometry = batches_[j].geometry_;
                    if (geometry)
                    {
                        Vector3 geometryNormal;
                        float geometryDistance = geometry->GetHitDistance(localRay, &geometryNormal);
                        if (geometryDistance < query.maxDistance_ && geometryDistance < distance)
                        {
                            distance = geometryDistance;
                            normal = (worldTransforms_[i] * Vector4(geometryNormal, 0.0f)).Normalized();
                        }
                    }
                }
            }
        }
        
        if (distance < query.maxDistance_)
        {
            RayQueryResult result;
            result.position_ = query.ray_.origin_ + distance * query.ray_.direction_;
            result.normal_ = normal;
            result.distance_ = distance;
            result.drawable_ = this;
            result.node_ = node_;
            result.subObject_ = i;
            results.Push(result);
        }
    }
}
开发者ID:Boshin,项目名称:Urho3D,代码行数:62,代码来源:StaticModelGroup.cpp

示例15: transformRayWorldToModel

Ray Renderable::transformRayWorldToModel(const Ray &ray) const
{
  return ray.transformed(mTransformInv);
}
开发者ID:HerrR,项目名称:Datorgrafik-Visualisering,代码行数:4,代码来源:Renderable.cpp


注:本文中的Ray类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。