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


C++ ray函数代码示例

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


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

示例1: TEST_F

TEST_F(CubeMeshTests, IntersectionTest) {
  IObject3D *object = Cube;

  Ray ray(glm::dvec3(3.0, 2.0, -1.0), Z_NORM_VEC);
  IntersectionResult res = object->Intersect(ray);
  ASSERT_TRUE(res);
  ASSERT_DOUBLE_EQ(1.0, res.GetDistance());
  ASSERT_VEC_NEAR(-Z_NORM_VEC, (res.GetNormalRay().GetDirection()), EPS_WEAK);

  // Test ray falling on edge of triangle.
  ray.SetOrigin(glm::dvec3(3.0, 3.0, -1.0));
  res = object->Intersect(ray);
  ASSERT_TRUE(res);
  ASSERT_DOUBLE_EQ(1.0, res.GetDistance());
  ASSERT_VEC_NEAR(-Z_NORM_VEC, (res.GetNormalRay().GetDirection()), EPS_WEAK);

  // Test ray falling on vertex.
  ray.SetOrigin(glm::dvec3(10.0, 5.0, 0.0));
  ray.SetDirection(-X_NORM_VEC);
  res = object->Intersect(ray);
  ASSERT_TRUE(res);
  ASSERT_DOUBLE_EQ(5.0, res.GetDistance());
  ASSERT_VEC_NEAR(X_NORM_VEC, (res.GetNormalRay().GetDirection()), EPS_WEAK);
}
开发者ID:DennZo1993,项目名称:RayTracer,代码行数:24,代码来源:MeshTests.cpp

示例2: MANGOS_ASSERT

 bool StaticMapTree::getObjectHitPos(const Vector3& pPos1, const Vector3& pPos2, Vector3& pResultHitPos, float pModifyDist) const
 {
     float maxDist = (pPos2 - pPos1).magnitude();
     // valid map coords should *never ever* produce float overflow, but this would produce NaNs too:
     MANGOS_ASSERT(maxDist < std::numeric_limits<float>::max());
     // prevent NaN values which can cause BIH intersection to enter infinite loop
     if (maxDist < 1e-10f)
     {
         pResultHitPos = pPos2;
         return false;
     }
     Vector3 dir = (pPos2 - pPos1) / maxDist;            // direction with length of 1
     G3D::Ray ray(pPos1, dir);
     float dist = maxDist;
     if (getIntersectionTime(ray, dist, false))
     {
         pResultHitPos = pPos1 + dir * dist;
         if (pModifyDist < 0)
         {
             if ((pResultHitPos - pPos1).magnitude() > -pModifyDist)
             {
                 pResultHitPos = pResultHitPos + dir * pModifyDist;
             }
             else
             {
                 pResultHitPos = pPos1;
             }
         }
         else
         {
             pResultHitPos = pResultHitPos + dir * pModifyDist;
         }
     }
     pResultHitPos = pPos2;
     return false;
 }
开发者ID:billy1arm,项目名称:serverZero,代码行数:36,代码来源:MapTree.cpp

示例3: ray

bool CGraphicView::GetXYPointForDXFTextExport( const CPoint& screenPt, CPoint3D& worldPt )
{
	//get a ray that goes through screenPt from the front of the view frustum to the back of it
	CPoint3D nearPt, farPt;
	if( !Get3DPointFromScreen( screenPt, nearPt, 0.f ) )
		return false;
	if( !Get3DPointFromScreen( screenPt, farPt, 1.f ) )
		return false;
	CLine3D ray( nearPt, farPt );

	//now find out where in 3D space the ray passes through the z=0 plane
	CVector3D xyNormal( 0., 0., 1. );
	CPoint3D ptOnXYPlane( 0., 0., 0. );
	CPlane3D xyPlane( xyNormal, ptOnXYPlane );
	double denom = xyNormal.dot( CVector3D( farPt, nearPt ) );
	if( zero( denom ) ) return false;
	double num = xyNormal.dot( CVector3D( ptOnXYPlane, nearPt  ) );
	double s = num/denom;
	worldPt = ray.offset( s );
	
	if( true/*is world point valid*/ )
		return true;
	else return false;
}
开发者ID:JeffLutzenberger,项目名称:fea-graphics-engine-example,代码行数:24,代码来源:GraphicsSelection.cpp

示例4: ray

void gkCameraNode::calculateNewPosition(const gkVector3& currentPosition, gkScalar rayLength, gkScalar tick)
{
	gkVector3 oDir = gkVector3::NEGATIVE_UNIT_Z * rayLength;

	gkVector3 tmpPosition = m_center - m_target->getOrientation() * oDir;

	bool newPosSet = false;

	if (GET_SOCKET_VALUE(AVOID_BLOCKING))
	{
		gkVector3 direction = tmpPosition - m_center;

		Ogre::Ray ray(m_center, direction);

		gkSweptTest::AVOID_LIST avoidList;
		avoidList.push_back(m_centerObj->getPhysicsController()->getCollisionObject());

		gkSweptTest sweptTest(avoidList);

		gkScalar blokingRadius = GET_SOCKET_VALUE(BLOCKING_RADIUS);

		if (sweptTest.collides(ray, blokingRadius))
		{
			gkVector3 displacement = (sweptTest.getHitPoint() - currentPosition) * 0.9f;

			m_target->setPosition(currentPosition + (displacement + sweptTest.getSliding()) * tick);

			newPosSet = true;
		}
	}

	if (!newPosSet)
	{
		m_target->setPosition(tmpPosition);
	}
}
开发者ID:Ali-il,项目名称:gamekit,代码行数:36,代码来源:gkCameraNode.cpp

示例5: genRay

/** genRay **/
vector_t genRay(scene_t *scene, int column, int row) {
   vector_t direction;                       // Directior vector
   entity_t    *ent;
   window_t *window;

   assert(scene->magic == SCENE_T);
   ent = scene->window;
   window = ent->entDerived;
   assert(window->magic == WINDOW_T);

   /* Computer the pixel's real scene coordinates */
   direction.x = ((double)(column)/
      (double)(scene->picture->columns-1))*window->windowWidth;
   direction.x -= window->windowWidth/2.0;
   direction.y = ((double)(row)/
      (double)(scene->picture->rows-1))*window->windowHeight;
   direction.y -= window->windowHeight/2.0;
   direction.z = 0;

   /* And now construct a unit vector from the view point to the pixel */
   direction = ray(window->viewPoint, direction);
   direction = unitize(direction);
   return(direction);
} /* End genRay */
开发者ID:zero-clouds-,项目名称:RayTracer,代码行数:25,代码来源:raytrace.c

示例6: TEST_F

  TEST_F(Ray3fTest, MethodIntersectPlane)
  {
    // Intersect.
    Ray3 ray(Vec3f(0, 0, 0), Vec3f(0, 0, 1));
    Plane plane(Vec3f(0, 0, 10), Vec3f(0, 0, -1));
    Vec3f intersection;
    bool intersect = ray.intersect(plane, intersection);
    float result[3];
    result[0] = 0;
    result[1] = 0;
    result[2] = 10;
    ASSERT_TRUE(intersect);
    cmpVec3f(result, intersection);

    // Ray pointing away.
    ray = Ray3(Vec3f(0, 0, 0), Vec3f(0, 0, -1));
    plane = Plane(Vec3f(0, 0, 10), Vec3f(0, 0, -1));
    intersect = ray.intersect(plane, intersection);
    ASSERT_TRUE(!intersect);

    // Normal same direction as ray.
    ray = Ray3(Vec3f(0, 0, 0), Vec3f(0, 0, 1));
    plane = Plane(Vec3f(0, 0, 10), Vec3f(0, 0, 1));
    intersect = ray.intersect(plane, intersection);
    result[0] = 0;
    result[1] = 0;
    result[2] = 10;
    ASSERT_TRUE(intersect);
    cmpVec3f(result, intersection);

    // Parallel.
    ray = Ray3(Vec3f(0, 0, 0), Vec3f(0, 0, 1));
    plane = Plane(Vec3f(0, 0, 10), Vec3f(0, 1, 0));
    intersect = ray.intersect(plane, intersection);
    ASSERT_TRUE(!intersect);
  }
开发者ID:knuke,项目名称:GMath,代码行数:36,代码来源:Ray3fTest.cpp

示例7: ray

bool BaseTank::isCollision(const Ogre::Vector3& position, const Ogre::Vector3& direction, Ogre::Real RaySize)
{
	//根据初始位置和方向创建一条射线;
	Ogre::Ray ray(position, direction);
	m_pRaySceneQuery->setRay(ray);
	//获取射线查询结果;
	Ogre::RaySceneQueryResult	&result = m_pRaySceneQuery->execute();
	Ogre::RaySceneQueryResult::iterator ite;
	//遍历查询结果,对每个结果做相应的操作;
	for( ite = result.begin(); ite!=result.end(); ite++)
	{
		//如果在指定距离的射线范围内查找到实体,则返回true;
		Ogre::String p=m_pBodyEntity->getName();
		if (ite->movable->getName().compare(m_pBodyEntity->getName()) != 0
			&& ite->distance < RaySize)
		{
			if (ite->movable->getName() != "PlayingCamera")
			{
					return true;
			}
		}
	}
	return false;
}
开发者ID:coneo,项目名称:TankWar,代码行数:24,代码来源:BaseTank.cpp

示例8: origin

void Engine::Calculate()
{
    const int max = Width * Height;
    const double cellWidth = 0.005;
    const double cellHeight = 0.005;
    const Vector3 origin(0.0,0.0,-5.0);

    for (int i = 0; i < Width; i++)
    {
        for (int j = 0; j < Height; j++)
        {
            Vector3 a;
            a.x = 1.0 * cellWidth * (i - Width/2);
            a.y = -1.0 * cellHeight * (j - Height/2);
            a.z = 0.0;

            a = a - origin;
            a.Normalize();

            Ray ray(origin, a);
            m_image[i][j] = trace(m_scene, ray, 0);
            m_progress++;

            int part = (m_progress*100/max);
            if (part*max == (m_progress*100))
            {
                if ((part/5)*5 == part)
                {
                    std::ostringstream caption;
                    caption << part << "%";
                    m_screen.SetCaption(caption.str());
                }
            }
        }
    }
}
开发者ID:trams,项目名称:YetAnotherRayTracer,代码行数:36,代码来源:engine.cpp

示例9: NumPoints

Point Polygon::FarthestPointAtAngle(real angle) const
{
    // TODO(mraggi): Replace with Binary search implementation
    int n = NumPoints();

    for (int i = 0; i < n; ++i)
    {
        Point p1 = m_vPoints[i];
        Point p2 = m_vPoints[(i + 1)%n];
        real a1 = p1.Angle();
        real a2 = p2.Angle();

        if (isAngleBetweenAngles(angle, a1, a2))
        {
            Point hola;
            Ray ray(Ray(Point(0, 0), angle));
            ray.Intersects(Segment(p1, p2), hola);
            return hola + Position();
        }
    }
    if (NumPoints() > 2)
        std::cerr << "ERROR IN Polygon::FarthestPointAtAngle" << std::endl;
    return {0, 0};
}
开发者ID:mraggi,项目名称:Graph,代码行数:24,代码来源:Polygon.cpp

示例10: lensQuery

 void PathTracingRenderer::Job::kernel(uint32_t threadID) {
     ArenaAllocator &mem = mems[threadID];
     IndependentLightPathSampler &pathSampler = *pathSamplers[threadID];
     for (int ly = 0; ly < numPixelY; ++ly) {
         for (int lx = 0; lx < numPixelX; ++lx) {
             float time = pathSampler.getTimeSample(timeStart, timeEnd);
             PixelPosition p = pathSampler.getPixelPositionSample(basePixelX + lx, basePixelY + ly);
             
             float selectWLPDF;
             WavelengthSamples wls = WavelengthSamples::createWithEqualOffsets(pathSampler.getWavelengthSample(), pathSampler.getWLSelectionSample(), &selectWLPDF);
             
             LensPosQuery lensQuery(time, wls);
             LensPosQueryResult lensResult;
             SampledSpectrum We0 = camera->sample(lensQuery, pathSampler.getLensPosSample(), &lensResult);
             
             IDFSample WeSample(p.x / imageWidth, p.y / imageHeight);
             IDFQueryResult WeResult;
             IDF* idf = camera->createIDF(lensResult.surfPt, wls, mem);
             SampledSpectrum We1 = idf->sample(WeSample, &WeResult);
             
             Ray ray(lensResult.surfPt.p, lensResult.surfPt.shadingFrame.fromLocal(WeResult.dirLocal), time);
             SampledSpectrum C = contribution(*scene, wls, ray, pathSampler, mem);
             SLRAssert(C.hasNaN() == false && C.hasInf() == false && C.hasMinus() == false,
                       "Unexpected value detected: %s\n"
                       "pix: (%f, %f)", C.toString().c_str(), px, py);
             
             SampledSpectrum weight = (We0 * We1) * (absDot(ray.dir, lensResult.surfPt.gNormal) / (lensResult.areaPDF * WeResult.dirPDF * selectWLPDF));
             SLRAssert(weight.hasNaN() == false && weight.hasInf() == false && weight.hasMinus() == false,
                       "Unexpected value detected: %s\n"
                       "pix: (%f, %f)", weight.toString().c_str(), px, py);
             sensor->add(p.x, p.y, wls, weight * C);
             
             mem.reset();
         }
     }
 }
开发者ID:shocker-0x15,项目名称:SLR,代码行数:36,代码来源:PathTracingRenderer.cpp

示例11: out

const std::shared_ptr<std::vector<ray>> mesh_light::shed(unsigned long samples) const {
	random_sampler s;
	std::vector<float> face_selector = *s.get_1d_samples(0.0f, 1.0f, samples);
	std::vector<vec2> c = *s.get_2d_samples(0, 1, 0, 1, samples);
	std::shared_ptr<std::vector<ray>> out(new std::vector<ray>());
	for (unsigned long i = 0; i < c.size(); i++) {
		for (unsigned long f = 0; f < cr_areas.size(); f++) {
			if (face_selector.at(i) < cr_areas[f]) {
				std::shared_ptr<triangle> face = faces->at(f);
				std::shared_ptr<vec2> lcoord(new vec2(c[i][0] + c[i][1] > 1 ? 1 - c[i][1] : c[i][0],
													  c[i][0] + c[i][1] > 1 ? 1 - c[i][0] : c[i][1]));
				std::shared_ptr<position> lpos = std::make_shared<position>(object_to_world(
						*face->get_barycentric_position(1 - (*lcoord)[0] - (*lcoord)[1], (*lcoord)[0], (*lcoord)[1]) +
						offset));
				std::array<position, 3> & v = *face->get_vertices();
				normal n = normalise(cross(object_to_world(v[1]-v[0]), object_to_world(v[2]-v[0])));
				if (dot(n, object_to_world(*face->get_avg_normal())) < 0)
					n = -n;
				out->push_back(ray(*lpos, s.get_solid_angle_samples(n, static_cast<float>(M_PI / 2), 1)->at(0)));
			}
		}
	}
	return out;
}
开发者ID:Chais,项目名称:RayTracer,代码行数:24,代码来源:mesh_light.cpp

示例12: movemask

void kdtreebenthin::draw<1>(scene& scene, ray4* r, hit4* hit4)
{

        unsigned int signx = movemask(r->D().x());
        unsigned int signy = movemask(r->D().y());
        unsigned int signz = movemask(r->D().z());

        //If the traversal direction is not same for all rays we 
        //  do a single ray traversal
        if (((signx - 1) < 14)       // sign of x is 0xF or 0
            || ((signy - 1) < 14)    // sign of y is 0xF or 0
            || ((signz - 1) < 14)) { // sign of z is 0xF or 0
                hit hit[4];
                for (int i = 0; i < 4; ++i) {
                        vec3f d(r->D().x()[i], r->D().y()[i], r->D().z()[i]);
                        ray ray(r->O(), d);
                        hit[i].prim = -1;
                        draw(scene, ray, hit[i]);
                }
                hit4->prim = ssei(hit[0].prim, hit[1].prim, hit[2].prim, hit[3].prim);
                hit4->u    = ssef(hit[0].u, hit[1].u, hit[2].u, hit[3].u);
                hit4->v    = ssef(hit[0].v, hit[1].v, hit[2].v, hit[3].v);
                return;
        }

        ssef tnear, tfar;
        _boundingBox.clip(*r, tnear, tfar);
        if (movemask(tnear >= tfar) == 0xF)
                return;

        const unsigned int dir[3][2] = {
                { signx & 1 , 1 - (signx & 1) },
                { signy & 1 , 1 - (signy & 1) },
                { signz & 1 , 1 - (signz & 1) } };

        ssef far[MAX_STACK_SIZE];
        ssef near[MAX_STACK_SIZE];
        int  nodes[MAX_STACK_SIZE];

        //push dummyNode onto stack which will cause us to exit
        nodes[0] = 0;
        far[0]  = BPRAY_INF;

        uint32_t stackptr = 1;
        kdnode* currNode = _nodes + 1;

        int activemask = 0xF;
#if MAILBOX
        static uint64_t rayid = 0;
        __sync_add_and_fetch(&rayid, 1);
#endif
        while (true) {
                if (!currNode->isLeaf()) {
                        const int axis  = currNode->getAxis();
                        const int front = currNode->getLeft() + dir[axis][0];
                        const int back  = currNode->getLeft() + dir[axis][1];
                        const ssef dist = currNode->getSplit() - r->O()[axis];
                        const ssef t    = dist * r->rcpD()[axis];

                        currNode   = _nodes + back;
                        if (!(movemask(tnear <= t) & activemask)) continue;

                        currNode   = _nodes + front;
                        if (!(movemask(tfar >= t) & activemask))  continue;

                        nodes[stackptr] = back;
                        near[stackptr]  = max(tnear, t);
                        far[stackptr]   = tfar;
                        tfar            = min(tfar, t);
                        activemask     &= movemask(tnear <= tfar);
                        ++stackptr;
                } else {
                        int primidx   = currNode->getPrimitiveOffset();
                        int primcount = currNode->getNumPrims();

                        for (int i = 0; i != primcount; ++i) {
                                int t = _prims[primidx + i];

                                //prefetch
                                int t2 = _prims[primidx + i + 1];
                                _mm_prefetch((char*)&scene._accels[t2], _MM_HINT_T0);
#if MAILBOX
                                //mailboxing
                                if (mbox.find(scene, rayid, t)) continue;
#endif
                                scene.intersect(t, *r, *hit4);
#if MAILBOX
                                mbox.add(scene, rayid, t);
#endif
                        }

                        if (movemask(tfar < r->tfar) == 0) return;
                        
                        --stackptr;
                        currNode   = nodes[stackptr] + _nodes;
                        tfar       = far[stackptr];
                        tnear      = near[stackptr];
                        activemask = movemask(tnear <= tfar);
                }
        }
//.........这里部分代码省略.........
开发者ID:samanpa,项目名称:raytracer,代码行数:101,代码来源:kdtreetraversalbenthin.cpp

示例13: dgAssert

dgInt32 dgCollisionConvexPolygon::CalculateContactToConvexHullContinue (dgCollisionParamProxy& proxy, const dgVector& polyInstanceScale, const dgVector& polyInstanceInvScale)
{
    dgAssert (proxy.m_referenceCollision->IsType (dgCollision::dgCollisionConvexShape_RTTI));
    dgAssert (proxy.m_floatingCollision->IsType (dgCollision::dgCollisionConvexPolygon_RTTI));

    const dgCollisionInstance* const hull = proxy.m_referenceCollision;

    dgAssert (this == proxy.m_floatingCollision->GetChildShape());
    dgAssert (m_count);
    dgAssert (m_count < dgInt32 (sizeof (m_localPoly) / sizeof (m_localPoly[0])));

    const dgBody* const floatingBody = proxy.m_floatingBody;
    const dgBody* const referenceBody = proxy.m_referenceBody;

    dgContact* const contactJoint = proxy.m_contactJoint;
    contactJoint->m_closestDistance = dgFloat32 (1.0e10f);

    m_normal = m_normal.CompProduct4(polyInstanceInvScale);
    dgAssert (m_normal.m_w == dgFloat32 (0.0f));
    m_normal = m_normal.CompProduct4(m_normal.DotProduct4(m_normal).InvSqrt());
    const dgVector savedFaceNormal (m_normal);

    for (dgInt32 i = 0; i < m_count; i ++) {
        m_localPoly[i] = polyInstanceScale.CompProduct4(dgVector (&m_vertex[m_vertexIndex[i] * m_stride]));
        dgAssert (m_localPoly[i].m_w == dgFloat32 (0.0f));
    }

    dgVector hullOrigin (proxy.m_matrix.UntransformVector(dgVector (dgFloat32 (0.0f))));
    hullOrigin = (hullOrigin - m_normal.CompProduct4(m_normal.DotProduct4(hullOrigin - m_localPoly[0]))) | dgVector::m_wOne;

    dgMatrix polygonMatrix;
    polygonMatrix[0] = m_localPoly[1] - m_localPoly[0];
    polygonMatrix[0] = polygonMatrix[0].CompProduct4 (polygonMatrix[0].InvMagSqrt());
    polygonMatrix[1] = m_normal;
    polygonMatrix[2] = polygonMatrix[0] * m_normal;
    polygonMatrix[3] = hullOrigin;
    dgAssert (polygonMatrix.TestOrthogonal());

    dgMatrix savedProxyMatrix (proxy.m_matrix);
    proxy.m_matrix = polygonMatrix * proxy.m_matrix;

    dgVector floatingVeloc (floatingBody->m_veloc);
    dgVector referenceVeloc (referenceBody->m_veloc);
    const dgMatrix& hullMatrix = hull->GetGlobalMatrix();
    dgVector hullRelativeVeloc (hullMatrix.UnrotateVector(referenceVeloc - floatingVeloc));
    dgVector polyRelativeVeloc (proxy.m_matrix.UnrotateVector (hullRelativeVeloc));

    dgVector polyBoxP0 (dgFloat32 ( 1.0e15f));
    dgVector polyBoxP1 (dgFloat32 (-1.0e15f));
    m_normal = polygonMatrix.UnrotateVector(m_normal);

    if (m_normal.DotProduct4(polyRelativeVeloc).m_x >= 0.0f) {
        proxy.m_matrix = savedProxyMatrix;
        return 0;
    }
    for (dgInt32 i = 0; i < m_count; i ++) {
        m_localPoly[i] = polygonMatrix.UntransformVector(m_localPoly[i]);
        dgAssert (m_localPoly[i].m_w == dgFloat32 (0.0f));
        polyBoxP0 = polyBoxP0.GetMin (m_localPoly[i]);
        polyBoxP1 = polyBoxP1.GetMax (m_localPoly[i]);
    }
    dgInt32 count = 0;


    dgVector hullBoxP0;
    dgVector hullBoxP1;
    hull->CalcAABB (proxy.m_matrix.Inverse(), hullBoxP0, hullBoxP1);
    dgVector minBox (polyBoxP0 - hullBoxP1);
    dgVector maxBox (polyBoxP1 - hullBoxP0);
    dgFastRayTest ray (dgVector (dgFloat32 (0.0f)), polyRelativeVeloc);
    dgFloat32 distance = ray.BoxIntersect(minBox, maxBox);

    if (distance < dgFloat32 (1.0f)) {

        dgVector boxSize ((hullBoxP1 - hullBoxP0).Scale4 (dgFloat32 (0.5f)));
//		dgVector boxOrigin ((hullBoxP1 + hullBoxP0).Scale4 (dgFloat32 (0.5f)));
//		boxOrigin += polyRelativeVeloc.Scale4 (distance);

        dgVector normalInHull (proxy.m_matrix.RotateVector (m_normal.Scale4 (dgFloat32 (-1.0f))));
        dgVector pointInHull (hull->SupportVertex (normalInHull, NULL));
        dgVector pointInPlane (proxy.m_matrix.UntransformVector (pointInHull));
        dgFloat32 distToPlane = (m_localPoly[0] - pointInPlane) % m_normal;
        dgFloat32 timeToPlane = distToPlane / (polyRelativeVeloc % m_normal);
        dgVector boxOrigin (pointInPlane + polyRelativeVeloc.Scale4(timeToPlane));

        bool inside = true;
        dgInt32 i0 = m_count - 1;
        for (dgInt32 i = 0; i < m_count; i ++) {
            dgVector e (m_localPoly[i] - m_localPoly[i0]);
            dgVector n (m_normal * e);
            dgPlane plane (n, - (m_localPoly[i0] % n));

            dgVector supportDist (plane.Abs().DotProduct4 (boxSize));
            dgFloat32 centerDist = plane.Evalue(boxOrigin);

            if ((centerDist + supportDist.m_x) < dgFloat32 (0.0f)) {
                proxy.m_matrix = savedProxyMatrix;
                return 0;
            }

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

示例14: dgAssert

dgInt32 dgCollisionConvexPolygon::CalculateContactToConvexHullContinue(const dgWorld* const world, const dgCollisionInstance* const parentMesh, dgCollisionParamProxy& proxy)
{
	dgAssert(proxy.m_instance0->IsType(dgCollision::dgCollisionConvexShape_RTTI));
	dgAssert(proxy.m_instance1->IsType(dgCollision::dgCollisionConvexPolygon_RTTI));

	dgAssert(this == proxy.m_instance1->GetChildShape());
	dgAssert(m_count);
	dgAssert(m_count < dgInt32(sizeof (m_localPoly) / sizeof (m_localPoly[0])));

	const dgBody* const body0 = proxy.m_body0;
	const dgBody* const body1 = proxy.m_body1;

	dgAssert (proxy.m_instance1->GetGlobalMatrix().TestIdentity());

	dgVector relativeVelocity (body0->m_veloc - body1->m_veloc);
	if (m_normal.DotProduct4(relativeVelocity).GetScalar() >= 0.0f) {
		return 0;
	}
	dgFloat32 den = dgFloat32 (1.0f) / (relativeVelocity % m_normal);
	if (den > dgFloat32 (1.0e-5f)) {
		// this can actually happens
		dgAssert(0);
		return 0;
	}

	dgContact* const contactJoint = proxy.m_contactJoint;
	contactJoint->m_closestDistance = dgFloat32(1.0e10f);

	dgMatrix polygonMatrix;
	dgVector right (m_localPoly[1] - m_localPoly[0]);
	polygonMatrix[0] = right.CompProduct4(right.InvMagSqrt());
	polygonMatrix[1] = m_normal;
	polygonMatrix[2] = polygonMatrix[0] * m_normal;
	polygonMatrix[3] = dgVector::m_wOne;
	dgAssert (polygonMatrix.TestOrthogonal());

	dgVector polyBoxP0(dgFloat32(1.0e15f));
	dgVector polyBoxP1(dgFloat32(-1.0e15f));
	for (dgInt32 i = 0; i < m_count; i++) {
		dgVector point (polygonMatrix.UnrotateVector(m_localPoly[i]));
		polyBoxP0 = polyBoxP0.GetMin(point);
		polyBoxP1 = polyBoxP1.GetMax(point);
	}

	dgVector hullBoxP0;
	dgVector hullBoxP1;
	dgMatrix hullMatrix (polygonMatrix * proxy.m_instance0->m_globalMatrix);
	proxy.m_instance0->CalcAABB(hullMatrix, hullBoxP0, hullBoxP1);
	dgVector minBox(polyBoxP0 - hullBoxP1);
	dgVector maxBox(polyBoxP1 - hullBoxP0);
	dgVector veloc (polygonMatrix.UnrotateVector (relativeVelocity));
	dgFastRayTest ray(dgVector(dgFloat32(0.0f)), veloc);
 	dgFloat32 distance = ray.BoxIntersect(minBox, maxBox);

	dgInt32 count = 0;
	if (distance < dgFloat32(1.0f)) {
		bool inside = false;

		dgVector boxSize((hullBoxP1 - hullBoxP0).CompProduct4(dgVector::m_half));
		dgVector sphereMag2 (boxSize.DotProduct4(boxSize));
		boxSize = sphereMag2.Sqrt();

		dgVector pointInPlane (polygonMatrix.RotateVector(hullBoxP1 + hullBoxP0).CompProduct4(dgVector::m_half));
		dgFloat32 distToPlane = (m_localPoly[0] - pointInPlane) % m_normal;

		dgFloat32 timeToPlane0 = (distToPlane + boxSize.GetScalar()) * den;
		dgFloat32 timeToPlane1 = (distToPlane - boxSize.GetScalar()) * den;

		dgVector boxOrigin0 (pointInPlane + relativeVelocity.Scale4(timeToPlane0));
		dgVector boxOrigin1 (pointInPlane + relativeVelocity.Scale4(timeToPlane1));
		dgVector boxOrigin ((boxOrigin0 + boxOrigin1).CompProduct4(dgVector::m_half)); 
		dgVector boxProjectSize (((boxOrigin0 - boxOrigin1).CompProduct4(dgVector::m_half))); 
		sphereMag2 = boxProjectSize.DotProduct4(boxProjectSize);
		boxSize = sphereMag2.Sqrt();

		dgAssert (boxOrigin.m_w == 0.0f);
		boxOrigin = boxOrigin | dgVector::m_wOne;
		
		if (!proxy.m_intersectionTestOnly) {
			inside = true;
			dgInt32 i0 = m_count - 1;

			for (dgInt32 i = 0; i < m_count; i++) {
				dgVector e(m_localPoly[i] - m_localPoly[i0]);
				dgVector n(m_normal * e & dgVector::m_triplexMask);
				dgFloat32 param = dgSqrt (sphereMag2.GetScalar() / (n.DotProduct4(n)).GetScalar());
				dgPlane plane(n, -(m_localPoly[i0] % n));

				dgVector p0 (boxOrigin + n.Scale4 (param));
				dgVector p1 (boxOrigin - n.Scale4 (param));

				dgFloat32 size0 = (plane.DotProduct4 (p0)).GetScalar();
				dgFloat32 size1 = (plane.DotProduct4 (p1)).GetScalar();

				if ((size0 < 0.0f) && (size1 < 0.0f)) {
					return 0;
				}

				if ((size0 * size1) < 0.0f) {
					inside = false;
//.........这里部分代码省略.........
开发者ID:Kaoswerk,项目名称:newton-dynamics,代码行数:101,代码来源:dgCollisionConvexPolygon.cpp

示例15: newray

vec3f RayTracer::traceRay( Scene *scene, const ray& r, 
	const vec3f& thresh, int depth, isect& i, vector<const SceneObject*>& stack )
{
	if( depth>=0
		&& thresh[0] > threshold - RAY_EPSILON && thresh[1] > threshold - RAY_EPSILON && thresh[2] > threshold - RAY_EPSILON
		&& scene->intersect( r, i ) ) {
		// YOUR CODE HERE

		// An intersection occured!  We've got work to do.  For now,
		// this code gets the material for the surface that was intersected,
		// and asks that material to provide a color for the ray.  

		// This is a great place to insert code for recursive ray tracing.
		// Instead of just returning the result of shade(), add some
		// more steps: add in the contributions from reflected and refracted
		// rays.
		
		const Material& m = i.getMaterial();
		vec3f color = m.shade(scene, r, i);
		//calculate the reflected ray
		vec3f d = r.getDirection();
		vec3f position = r.at(i.t);
		vec3f direction = d - 2 * i.N * d.dot(i.N);
		ray newray(position, direction);
		if(!m.kr.iszero()) {
			vec3f reflect = m.kr.multiply(traceRay(scene, newray, thresh.multiply(m.kr), depth-1, stack).clamp());
			color += reflect;
		}

		//calculate the refracted ray
		double ref_ratio;
		double sin_ang = d.cross(i.N).length();
		vec3f N = i.N;
		//Decide going in or out
		const SceneObject *mi = NULL, *mt = NULL;
		int stack_idx = -1;
		vector<const SceneObject*>::reverse_iterator itr;
		//1 use the normal to decide whether to go in or out
		//0: travel through, 1: in, 2: out
		char travel = 0;
		if(i.N.dot(d) <= -RAY_EPSILON) {
			//from outer surface in
			//test whether the object has two face
			ray test_ray(r.at(i.t) + d * 2 * RAY_EPSILON, -d);
			isect test_i;
			if(i.obj->intersect(r, test_i) && test_i.N.dot(N) > -RAY_EPSILON) {
				//has interior
				travel = 1;
			}
		}
		else {
			travel = 2;
		}

		if(travel == 1) {
			if(!stack.empty()) {
				mi = stack.back();
			}
			mt = i.obj;
			stack.push_back(mt);
		}
		else if(travel == 2) {
			//if it is in our stack, then we must pop it
			for(itr = stack.rbegin(); itr != stack.rend(); ++itr) {
				if(*itr == i.obj) {
					mi = *itr;
					vector<const SceneObject*>::iterator ii = itr.base() - 1;
					stack_idx = ii - stack.begin();
					stack.erase(ii);
					break;
				}
			}
			if(!stack.empty()) {
				mt = stack.back();
			}
		}

		if(N.dot(d) >= RAY_EPSILON) {
			N = -N;
		}
		
		ref_ratio = (mi?(mi->getMaterial().index):1.0) / (mt?(mt->getMaterial().index):1.0);

		if(!m.kt.iszero() && (ref_ratio < 1.0 + RAY_EPSILON || sin_ang < 1.0 / ref_ratio + RAY_EPSILON)) {
			//No total internal reflection
			//We do refraction now
			double c = N.dot(-d);
			direction = (ref_ratio * c - sqrt(1 - ref_ratio * ref_ratio * (1 - c * c))) * N + ref_ratio * d;
			newray = ray(position, direction);
			vec3f refraction = m.kt.multiply(traceRay(scene, newray, thresh.multiply(m.kt), depth-1, stack).clamp());
			color += refraction;
		}

		if(travel == 1) {
			stack.pop_back();
		}
		else if(travel == 2) {
			if(mi) {
				stack.insert(stack.begin() + stack_idx, mi);
			}
//.........这里部分代码省略.........
开发者ID:caomw,项目名称:RayTracer,代码行数:101,代码来源:RayTracer.cpp


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