示例#1
0
bool Commands::prmSetPatch(int argc, char** argv) {
    const Line* cur_state = CommandLine::getState();

    // if state is blank we have nothing selected
    // print error message and skip
    if (cur_state) {
        if (cur_state->toCommandID() == Commands::primitive_get_cmd_id) {
            int patch_x = atoi(argv[1]);
            int patch_y = atoi(argv[2]);
            float patch_x_f = atof(argv[1]);
            float patch_y_f = atof(argv[2]);
            if (patch_x_f > 0.0 && patch_y_f > 0.0 &&
                patch_x_f - patch_x == 0 && patch_y_f - patch_y == 0)
            {
                Primitive* prm = dynamic_cast<Primitive*>(
                    Renderable::get(cur_state->tokens[1]));
                prm->setPatch(patch_x, patch_y);
                return true;
            } else {
                fprintf(stderr, "ERROR input values for %s must be 2 non negative integers\n",
                    argv[0]);
            }
        } else {
            fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
                argv[0]);
        }
    } else {
        fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
            argv[0]);
    }
    return false;
}
示例#2
0
bool Commands::prmSetSpecular(int argc, char** argv) {
    const Line* cur_state = CommandLine::getState();

    // if state is blank we have nothing selected
    // print error message and skip
    if (cur_state) {
        if (cur_state->toCommandID() == Commands::primitive_get_cmd_id) {
            float specular = atof(argv[1]);
            if (specular >= 0.0 && specular <= 1.0) {
                Primitive* prm = dynamic_cast<Primitive*>(
                    Renderable::get(cur_state->tokens[1]));
                prm->setSpecular(specular);
                return true;
            } else {
                fprintf(stderr, "ERROR input values for %s must be 1 numerical value between 0.0 and 1.0 (inclusive)\n",
                    argv[0]);
            }
        } else {
            fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
                argv[0]);
        }
    } else {
        fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
            argv[0]);
    }
    return false;
}
示例#3
0
bool Commands::prmSetExponent(int argc, char** argv) {
    const Line* cur_state = CommandLine::getState();

    // if state is blank we have nothing selected
    // print error message and skip
    if (cur_state) {
        if (cur_state->toCommandID() == Commands::primitive_get_cmd_id) {
            float Exp0 = atof(argv[1]);
            float Exp1 = atof(argv[2]);
            if (Exp0 > 0.0 && Exp1 > 0.0) {
                Primitive* prm = dynamic_cast<Primitive*>(
                    Renderable::get(cur_state->tokens[1]));
                prm->setExponents(Exp0, Exp1);
                return true;
            } else {
                fprintf(stderr, "ERROR input values for %s must be 2 non negative numeric values\n",
                    argv[0]);
            }
        } else {
            fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
                argv[0]);
        }
    } else {
        fprintf(stderr, "ERROR %s requires that you have a Primitive selected\n",
            argv[0]);
    }
    return false;
}
示例#4
0
int Tween::tick(double time) {
    if(!active) return 0;

    Primitive *prim = (Primitive*) primitives.edit(idx);
    if(!prim) return 1;

    passed += time;
    if(passed >= duration) passed = duration;

    if(reverse) {
        value = to - (to - from) * passed / duration;        
    } else {
        value = from + (to - from) * passed / duration;
    }

    prim->change(name, (int)rint(value));

    if(passed == duration) {
        if(repeat) {
            passed = 0.0;
            reverse = !reverse;
        } else {
            return 1;
        }
    }

    return 0;
}
  Primitive* PlattfussSchlange::createSegment(int index, const OdeHandle& odeHandle){
    Primitive* p;

    /////////// MIDDLE SEGMENT (BODY)
    if ( index*2 == conf.segmNumber-1) {
      //p = new Box(conf.segmLength*1.5,conf.segmLength*1.5, conf.segmLength*.6);
      //p = new Capsule(conf.segmDia*.8/*2.8*/ , conf.segmLength*1);

       //  p = new Capsule(conf.segmLength/2 , conf.segmLength*2);
      p = new Sphere(conf.segmLength*.8);
      p->setTexture("Images/wood.rgb");
      p->init(odeHandle, conf.segmMass*2, osgHandle);
      // p->setPose( osg::Matrix::rotate(M_PI/2, 0, 1, 0)*osg::Matrix::translate( conf.segmDia, 0, 0) );
    } /////// FEED
    else if( (index == 0) | (index== conf.segmNumber-1)) {
      // p = new Capsule(conf.segmDia*.8/*2.8*/ , conf.segmLength*1);
       // p = new Sphere(conf.segmLength/2*2);
      p = new Box(1.8*conf.segmLength,3*conf.segmLength, conf.segmLength*.3);
      p->setTexture("Images/whitemetal_farbig_small.rgb");
      p->init(odeHandle, conf.segmMass*3, osgHandle);
    } /////// NORMAL SEGMENT
    else {
      p = SchlangeServo2::createSegment(index, odeHandle);
    }
    return p;
  }
示例#6
0
void scene::generateDefaultScene()
{

    //add bounding box

    MyRectangle *roomFloor = new MyRectangle(vector3(-70, 0, 0), vector3(-70, 0, -201), vector3(70, 0, -201),  materialConstants (0.7f,1.0f,1.0f, Rgb(0.9, 0.9, 0.3), 0));

  //Utils::rotateFloorMyRectangle(roomFloor, pii/13);
   float roomHeight = 130;
   vector<Primitive *> parallelogramSides = getParrallelogramSides(roomFloor, roomHeight);
   Primitive *leftSide = parallelogramSides[2];
   Primitive *rightSide = parallelogramSides[3];
   leftSide->setMaterial(materialConstants (1.0f,1.0f,1.0f, Rgb(1, 0.2, 0.2)));
   rightSide->setMaterial(materialConstants (1.0f,1.0f,1.0f, Rgb(0.2, 1, 0.2)));


   primitives.insert( primitives.end(), parallelogramSides.begin(), parallelogramSides.end() );

   //add box
   MyRectangle *base = new MyRectangle(vector3(-15, 0, -20), vector3(-45, 0, -20), vector3(-40, 0, -50),  materialConstants (1.0f,1.0f,1.0f, Rgb(0.9, 0.9, 0.3), 0));
   rotateFloorMyRectangle(base, pii/10);
  float boxHeight = 50;

  vector<Primitive *> baseSides = getParrallelogramSides(base, boxHeight);

   primitives.insert( primitives.end(), baseSides.begin(), baseSides.end() );



//add sphere----------------------------------------

  // Sphere *sp = new Sphere(20, vector3(-30, -20, -50), materialConstants (1.0f,0.2f, 1.0f,  Rgb(0.9, 0.8, 0.3), 1, 0.9));//glossy
 //  Sphere *sp = new Sphere(20, vector3(-30, -20, -50), materialConstants (1.0f,0.2f, 1.0f,  Rgb(0.9, 0.8, 0.3), 3, 0.9, 1.5));//refraction

   Sphere *spMirror = new Sphere(12, vector3(-30, -boxHeight-12, -35), materialConstants (1.0f,0.2f, 1.0f,  Rgb(0.8, 0.8, 0.8), 2, 0));//mirror
   primitives.push_back(spMirror);

//add light----------------------------------------
  MyRectangle *lightSource = new MyRectangle(vector3(-50, -roomHeight + 0.5f, -20), vector3(-50, -roomHeight + 0.5f, -150), vector3(50, -roomHeight + 0.5f, -150),  materialConstants (Rgb(0.8, 1, 1)));
 //  MyRectangle *lightSource = new MyRectangle(vector3(-30, -roomHeight + 0.5f, -30), vector3(-30, -roomHeight + 0.5f, -110), vector3(30, -roomHeight + 0.5f, -110),  materialConstants (Rgb(0.8, 1, 1)));

   lightSource->setIslightSource(true);
   cout << " LIGHT : " << lightSource->ifIsLightSource() << endl;

   primitives.push_back(lightSource);
//cylindre-------------------------------------------
   cylindre * cy = new cylindre(50, vector3(0,-1,0), vector3(37, 0, -30),17, materialConstants(1.0f,0.4f,1.0f, Rgb(1, 1, 1) , 1, 2.5));
   QImage fanta = QImage("fanta.jpg");
   cout << "height :"<< fanta.height() << endl;
   cout << "width : "<< fanta.width() << endl;

   cy->setTexture(fanta);

   primitives.push_back(cy);
   //refracting----------------------------------------------
   Sphere *sp = new Sphere(12, vector3(10, -12, -72), materialConstants (1.0f,0.2f, 1.0f,  Rgb(0.9, 0.8, 0.3), 3, 0.9, 1.2));//refraction
   primitives.push_back(sp);

   cout << "  i'm alive " << endl;
}
void ToHoudiniCortexObjectConverter::transferAttribs( GU_Detail *geo, const GA_Range &points, const GA_Range &prims ) const
{
	GA_Primitive *hPrim = geo->getPrimitiveList().get( prims.begin().getOffset() );
	if ( hPrim->getTypeId() != GU_CortexPrimitive::typeId() )
	{
		return;
	}
	
	const Primitive *input = IECore::runTimeCast<const Primitive>( srcParameter()->getValue() );
	Primitive *output = IECore::runTimeCast<Primitive>( ((GU_CortexPrimitive *)hPrim)->getObject() );
	if ( !input || !output )
	{
		return;
	}
	
	const char *filter = attributeFilterParameter()->getTypedValue().c_str();
	for ( PrimitiveVariableMap::const_iterator it = input->variables.begin() ; it != input->variables.end(); ++it )
	{
		if ( !UT_String( it->first ).multiMatch( filter ) )
		{
			continue;
		}
		
		if ( output->isPrimitiveVariableValid( it->second ) )
		{
			output->variables[it->first] = it->second;
		}
	}
	
	if ( UT_String( "P" ).multiMatch( filter ) )
	{
		geo->setPos3( points.begin().getOffset(), IECore::convert<UT_Vector3>( input->bound().center() ) );
	}
}
示例#8
0
Vec3f TraceBase::volumeLightSample(PathSampleGenerator &sampler,
                    MediumSample &mediumSample,
                    const Primitive &light,
                    const Medium *medium,
                    int bounce,
                    const Ray &parentRay)
{
    LightSample lightSample;
    if (!light.sampleDirect(_threadId, mediumSample.p, sampler, lightSample))
        return Vec3f(0.0f);

    Vec3f f = mediumSample.phase->eval(parentRay.dir(), lightSample.d);
    if (f == 0.0f)
        return Vec3f(0.0f);

    Ray ray = parentRay.scatter(mediumSample.p, lightSample.d, 0.0f);
    ray.setPrimaryRay(false);

    IntersectionTemporary data;
    IntersectionInfo info;
    Vec3f e = attenuatedEmission(sampler, light, medium, lightSample.dist, data, info, bounce, false, ray, nullptr);
    if (e == 0.0f)
        return Vec3f(0.0f);

    Vec3f lightF = f*e/lightSample.pdf;

    if (!light.isDirac())
        lightF *= SampleWarp::powerHeuristic(lightSample.pdf, mediumSample.phase->pdf(parentRay.dir(), lightSample.d));

    return lightF;
}
示例#9
0
  int Ng_CreatePrimitive (ClientData clientData,
			  Tcl_Interp * interp,
			  int argc, tcl_const char *argv[])
  {
    CSGeometry * geometry = dynamic_cast<CSGeometry*> (ng_geometry.Ptr());
    if (!geometry)
      {
	Tcl_SetResult (interp, err_needscsgeometry, TCL_STATIC);
	return TCL_ERROR;
      }


    tcl_const char * classname = argv[1];
    tcl_const char * name = argv[2];

    cout << "Create primitive, class = " << classname
	 << ", name = " << name << endl;

    Primitive * nprim = Primitive::CreatePrimitive (classname);
    Solid * nsol = new Solid (nprim);

    char sname[100];
    for (int j = 1; j <= nprim->GetNSurfaces(); j++)
      {
	sprintf (sname, "%s,%d", name, j);
	geometry -> AddSurface (sname, &nprim->GetSurface(j));
	nprim -> SetSurfaceId (j, geometry->GetNSurf());
      }

    geometry->SetSolid (name, nsol);

    return TCL_OK;
  }
示例#10
0
Vec3f TraceBase::attenuatedEmission(PathSampleGenerator &sampler,
                         const Primitive &light,
                         const Medium *medium,
                         float expectedDist,
                         IntersectionTemporary &data,
                         IntersectionInfo &info,
                         int bounce,
                         bool startsOnSurface,
                         Ray &ray,
                         Vec3f *transmittance)
{
    CONSTEXPR float fudgeFactor = 1.0f + 1e-3f;

    if (light.isDirac()) {
        ray.setFarT(expectedDist);
    } else {
        if (!light.intersect(ray, data) || ray.farT()*fudgeFactor < expectedDist)
            return Vec3f(0.0f);
    }
    info.p = ray.pos() + ray.dir()*ray.farT();
    info.w = ray.dir();
    light.intersectionInfo(data, info);

    Vec3f shadow = generalizedShadowRay(sampler, ray, medium, &light, startsOnSurface, true, bounce);
    if (transmittance)
        *transmittance = shadow;
    if (shadow == 0.0f)
        return Vec3f(0.0f);

    return shadow*light.evalDirect(data, info);
}
/*!
	@brief		トレース
	@param[o]	out: 出力輝度
	@param[i]	ray: 光線
	@param[i]	depth: 深度
 */
void Renderer::Trace(Color& out, const Ray& ray, std::size_t depth)
{
	Primitive* prim = NULL;
	Primitive::Param param;

	if((depth >= max_depth) || !FindNearest(&prim, param, ray))
	{
		out = scene->GetBGColor();
		return;
	}

	Vertex v;
	prim->CalcVertex(v, param, ray);
	Material* mtrl = prim->GetMaterial();

	// emittance
	out = mtrl->e;
 #ifdef USE_LOCAL_ILLUMINATION
	// direct lighting
	Color direct;
	DirectLighting(direct, ray, v, *mtrl);
	ColorAdd3(&out, &out, &direct);
 #endif // USE_LOCAL_ILLUMINATION
 #ifdef USE_GLOBAL_ILLUMINATION
	// indirect lighting
	Color indirect;
	IndirectLighting(indirect, ray, v, *mtrl, depth);
	ColorAdd3(&out, &out, &indirect);
 #endif // USE_GLOBAL_ILLUMINATION
}
示例#12
0
Primitive*
PAPER_DOLL::build_primitive(CBface_list& o_faces)
{
   LMESHptr skel_mesh = dynamic_pointer_cast<LMESH>(o_faces.mesh());
   assert(skel_mesh);
   LMESHptr mesh = get_inflate_mesh(skel_mesh);
   assert(mesh);

   // create vertices for top and bottom parts:
   Bvert_list o_verts = o_faces.get_verts();            // original verts
   Bvert_list t_verts = copy_verts(o_verts, mesh);      // top verts
   Bvert_list b_verts = copy_verts(o_verts, mesh);      // bottom verts

   // set up mappings:
   //   original --> top
   //   original --> bottom
   VertMapper t_map(o_verts, t_verts, true);
   VertMapper b_map(o_verts, b_verts, true);

   Primitive* ret = new Primitive(mesh, skel_mesh);

   // build dependencies
   Bsurface_list surfs = Bsurface::get_surfaces(o_faces);
   for (int i = 0; i < surfs.num(); i++)
      ret->absorb_skel(surfs[i]);

   // generate top faces and bottom faces
   Bface_list t_faces = copy_faces(o_faces, t_map, ret, false);
   Bface_list b_faces = copy_faces(o_faces, b_map, ret, true);

   // create the sides:
   create_sides(o_faces, t_map, b_map, ret);

   Wvec n = o_faces.avg_normal();
   if (1) {
      define_offsets(o_verts, t_map, b_map, n, ret);
   } else {
      // under construction...
      //  for now just offset the top and bottom uniformly for testing...
      const double k = Config::get_var_dbl("PAPER_DOLL_OFFSET_SCALE",1.0);
      double       h = o_faces.get_edges().strong_edges().avg_len();
      t_verts.transform(Wtransf::translation( 0.5*k*h*n));
      b_verts.transform(Wtransf::translation(-0.5*k*h*n));
   }


   // make it all undoable:
   MULTI_CMDptr cmd = make_shared<MULTI_CMD>();

   // finish build
   ret->finish_build(cmd);

   //cmd->add(hide_surfs_cmd(Bsurface::get_surfaces(o_faces)));
   cmd->add(make_shared<SHOW_BBASE_CMD>(ret));
   WORLD::add_command(cmd);

   return _prim = ret;
}
示例#13
0
//////////////////////////////////////////////////////////
//
// RayTracer implementation
// =========
RayTracer::RayTracer(Scene& scene, Camera* camera) :
Renderer(scene, camera),
maxRecursionLevel(6),
minWeight(MIN_WEIGHT)
//[]---------------------------------------------------[]
//|  Constructor                                        |
//[]---------------------------------------------------[]
{
	// TODO: UNCOMMENT THE CODE BELOW

	int n = scene.getNumberOfActors();

	printf("Building aggregates for %d actors...\n", n);

	clock_t t = clock();
	Array<ModelPtr> models(n);
	map<uint, ModelPtr> aggregates;
	string actorNames;
	int totalNodes = 0;
	int i = 1;

	for (ActorIterator ait(scene.getActorIterator()); ait; i++)
	{
		const Actor* a = ait++;

		printf("Processing actor %d/%d...\n", i, n);
		if (!a->isVisible())
			continue;

		Primitive* p = dynamic_cast<Primitive*>(a->getModel());
		const TriangleMesh* mesh = p->triangleMesh();
		// checking if the id already exists in idList

		if (mesh != 0)	
		{
			ModelPtr& a = aggregates[mesh->id];

			BVH* bvh = new BVH(std::move(p->refine()));

			totalNodes += bvh->size();
			a = bvh;

			models.add(new ModelInstance(*a, *p));
			
		}
	}
	printf("Building scene aggregate...\n");
	{
		BVH* bvh = new BVH(std::move(models));

		totalNodes += bvh->size();
		aggregate = bvh;
	}
	printf("BVH(s) built: %d (%d nodes)\n", aggregates.size() + 1, totalNodes);
	printElapsedTime("", clock() - t);

}
示例#14
0
void Primitive::Add( Primitive& primitive ) {
	const std::vector<Vertex>& vertices( primitive.GetVertices() );
	const std::vector<GLuint>& indices( primitive.GetIndices() );

	std::size_t index_count = indices.size();

	for( std::size_t index_index = 0; index_index < index_count; ++index_index ) {
		AddVertex( vertices[ indices[index_index] ] );
	}
}
示例#15
0
void Connections::paintGL()
{
    glLineWidth(1);
    for (int i = 0; i < prims.length(); i++){
        Primitive* p = prims.at(i);
        p->paintGL();
    }
    //paintPoints();
    glDisable(GL_DEPTH_TEST);
    if (selected) selected->paintGL();
}
示例#16
0
文件: alias.cpp 项目: mvila/child
CHILD_DEFINE_NATIVE_METHOD(Alias, init) {
    CHILD_FIND_LAST_MESSAGE;
    CHILD_CHECK_INPUT_SIZE(1);
    Primitive *primitive = message->firstInput()->value();
    while(primitive) {
        Message *msg = Message::dynamicCast(primitive->value());
        if(!msg) CHILD_THROW(ArgumentException, "expected 'Message'");
        names().append(msg->name());
        primitive = primitive->next();
    }
    return this;
}
示例#17
0
Actor*
newActor(
  TriangleMesh* mesh,
  const vec3& position = vec3::null(),
  const vec3& size = vec3(1, 1, 1),
  const Color& color = Color::white)
{
  Primitive* p = new TriangleMeshShape(mesh);

  p->setMaterial(MaterialFactory::New(color));
  p->setTRS(position, quat::identity(), size);
  return new Actor(*p);
}
示例#18
0
 Primitive* Schlange::createSegment(int index, const OdeHandle& odeHandle){
   Primitive* p;
   p = new Capsule(conf.segmDia * 0.8, conf.segmLength);
   // if (index==0) 
   //   p = new Box(conf.segmLength*.1,conf.segmLength*.9, conf.segmLength*.6);
   p->setTexture("Images/whitemetal_farbig_small.rgb");
   p->init(odeHandle, conf.segmMass, osgHandle);
   if(index==0)
     p->setColor(conf.headColor);
   else
     p->setColor(conf.bodyColor);
   return p;
 }
Color Raytracer::CalnRefraction( Collider* collider , Vector3 ray_V , int dep , bool refracted , int* hash, int rc, Color weight) {
	Primitive* pri = collider->GetPrimitive();
	double n = pri->GetMaterial()->rindex;
	if ( !refracted ) n = 1 / n;
	
	bool nextRefracted = refracted;
	ray_V = ray_V.Refract( collider->N , n , &nextRefracted );
	
	Color alpha = Color(1, 1, 1) * pri->GetMaterial()->refr;
	if (refracted)
		alpha *= (pri->GetMaterial()->absor * -collider->dist).Exp();
	Color rcol = RayTracing( collider->C , ray_V , dep + 1 , nextRefracted , hash, rc, weight * alpha);
	return rcol * alpha;
}
Color Raytracer::CalnReflection( Collider* collider , Vector3 ray_V , int dep , bool refracted , int* hash, int rc, Color weight) {
	Primitive* pri = collider->GetPrimitive();
	ray_V = ray_V.Reflect( collider->N );

	if ( pri->GetMaterial()->drefl < EPS || dep > MAX_DREFL_DEP ) {
		Color alpha = pri->GetMaterial()->color * pri->GetMaterial()->refl;
		return RayTracing( collider->C , ray_V , dep + 1 , refracted , hash, rc, weight * alpha) * alpha;
	}

	Vector3 Dx = ray_V.GetAnVerticalVector();
	Vector3 Dy = ray_V.Cross(Dx);
	Dx = Dx.GetUnitVector() * pri->GetMaterial()->drefl;
	Dy = Dy.GetUnitVector() * pri->GetMaterial()->drefl;
	
	int totalSample = camera->GetDreflQuality();
	Color rcol, alpha = pri->GetMaterial()->color * pri->GetMaterial()->refl / totalSample;
	for ( int k = 0 ; k < totalSample ; k++ ) {
		double x , y;
		do {
			x = ran() * 2 - 1;
			y = ran() * 2 - 1;
		} while ( x * x + y * y > 1 );
		x *= pri->GetMaterial()->drefl;
		y *= pri->GetMaterial()->drefl;

		rcol += RayTracing( collider->C , ray_V + Dx * x + Dy * y , dep + MAX_DREFL_DEP , refracted , NULL, rc, weight * alpha);
	}
	return rcol * alpha;
}
示例#21
0
Vec3f TraceBase::bsdfSample(const Primitive &light,
                            SurfaceScatterEvent &event,
                            const Medium *medium,
                            int bounce,
                            const Ray &parentRay)
{
    event.requestedLobe = BsdfLobes::AllButSpecular;
    if (!event.info->bsdf->sample(event, false))
        return Vec3f(0.0f);
    if (event.weight == 0.0f)
        return Vec3f(0.0f);

    Vec3f wo = event.frame.toGlobal(event.wo);
    if (!isConsistent(event, wo))
        return Vec3f(0.0f);

    bool geometricBackside = (wo.dot(event.info->Ng) < 0.0f);
    medium = event.info->primitive->selectMedium(medium, geometricBackside);

    Ray ray = parentRay.scatter(event.info->p, wo, event.info->epsilon);
    ray.setPrimaryRay(false);

    IntersectionTemporary data;
    IntersectionInfo info;
    Vec3f e = attenuatedEmission(*event.sampler, light, medium, -1.0f, data, info, bounce, true, ray, nullptr);

    if (e == Vec3f(0.0f))
        return Vec3f(0.0f);

    Vec3f bsdfF = e*event.weight;

    bsdfF *= SampleWarp::powerHeuristic(event.pdf, light.directPdf(_threadId, data, info, event.info->p));

    return bsdfF;
}
示例#22
0
Vec3f TraceBase::volumePhaseSample(const Primitive &light,
                    PathSampleGenerator &sampler,
                    MediumSample &mediumSample,
                    const Medium *medium,
                    int bounce,
                    const Ray &parentRay)
{
    PhaseSample phaseSample;
    if (!mediumSample.phase->sample(sampler, parentRay.dir(), phaseSample))
        return Vec3f(0.0f);

    Ray ray = parentRay.scatter(mediumSample.p, phaseSample.w, 0.0f);
    ray.setPrimaryRay(false);

    IntersectionTemporary data;
    IntersectionInfo info;
    Vec3f e = attenuatedEmission(sampler, light, medium, -1.0f, data, info, bounce, false, ray, nullptr);

    if (e == Vec3f(0.0f))
        return Vec3f(0.0f);

    Vec3f phaseF = e*phaseSample.weight;

    phaseF *= SampleWarp::powerHeuristic(phaseSample.pdf, light.directPdf(_threadId, data, info, mediumSample.p));

    return phaseF;
}
示例#23
0
void BuildKdTreeStream::appendGeometry(Geometry * geo)
{
// std::cout<<" geo type "<<geo->type()<<" ";
	const unsigned n = geo->numComponents();
	m_primitives.expandBy(n);
	m_indices.expandBy(n);
	for(unsigned i = 0; i < n; i++) {
		Primitive *p = m_primitives.asPrimitive();
		p->setGeometry(geo);
		p->setComponentIndex(i);
		
		unsigned *dest = m_indices.asIndex();
		*dest = m_primitives.index();
		m_primitives.next();
		m_indices.next();
	}
}
示例#24
0
void KdCluster::leafWriteGroup(KdTreeNode *node, const BoundingBox & box)
{
	const unsigned num = node->getNumPrims();
	if(num < 1) return;
	
	m_groupGeometries[m_currentGroup] = new GeometryArray;
	
	GeometryArray * curGrp = m_groupGeometries[m_currentGroup];
	curGrp->create(num);
	
	unsigned start = node->getPrimStart();
	sdb::VectorArray<Primitive> &indir = indirection();
	//sdb::VectorArray<Primitive> &prims = primitives();
	int igeom, icomponent;
	unsigned igroup = 0;
	for(unsigned i = 0; i < num; i++) {
		//unsigned *iprim = indir[start + i];
		//Primitive * prim = prims.get(*iprim);
		Primitive * prim = indir[start + i];
		prim->getGeometryComponent(igeom, icomponent);
		Geometry * geo = m_stream.geometry(igeom);
		if(geo->type() == TGeometryArray) {
			GeometryArray * ga = (GeometryArray *)geo;
			Geometry * comp = ga->geometry(icomponent);
			
			BoundingBox comb = ga->calculateBBox(icomponent);

// do not add straddling geo			
			if(comb.getMax(0) <= box.getMax(0) && 
				comb.getMax(1) <= box.getMax(1) && 
				comb.getMax(2) <= box.getMax(2)) 
			{
				curGrp->setGeometry(comp, igroup);
				igroup++;
			}
		}
		else {
			std::cout<<" grouping only works with geometry arry.";
		}
		//indir.next();
	}
	
	curGrp->setNumGeometries(igroup);
	m_nodeGroupInd[node] = m_currentGroup;
	m_currentGroup++;
}
Color Raytracer::CalnDiffusion( Collider* collider , int* hash, int rc, Color weight) {
	Primitive* pri = collider->GetPrimitive();
	Color color = pri->GetMaterial()->color;
	if (pri->GetMaterial()->texture != NULL)
	{
		if (pri->getName() == 0)
			color = color * pri->GetTexture(collider->C);
		else
			color = color * pri->GetTexture(Vector3(collider->u, collider->v, 0));
	}
		
	Color ret = color * scene->GetBackgroundColor() * pri->GetMaterial()->diff;
	for ( Light* light = scene->GetLightHead() ; light != NULL ; light = light->GetNext() )
		ret += color * light->GetIrradiance( collider , scene->GetPrimitiveHead() , scene->GetCamera()->GetShadeQuality() , hash );
	
	if (camera->GetAlgorithm() == "PM")
		ret += color * photonmap->GetIrradiance( collider , camera->GetSampleDist() , camera->GetSamplePhotons() );
	
	if (camera->GetAlgorithm() == "PPM" || camera->GetAlgorithm() == "SPPM") {
		Hitpoint hitpoint;
		hitpoint.pos = collider->C;
		hitpoint.dir = collider->I;
		hitpoint.N = collider->N;
		hitpoint.primitive = collider->GetPrimitive();
		hitpoint.rc = rc;
		hitpoint.weight = weight * color;
		hitpoint.R2 = photonmap->GetRadius2(collider, camera->GetSampleDist(), camera->GetSamplePhotons());
		hitpointMap->Store(hitpoint);
	}
	
	return ret;
}
bool XMLBoundingShape::init(const lpzrobots::OdeHandle& _odeHandle, const lpzrobots::OsgHandle& osgHandle,
      double scale, char mode) {
  odeHandle = OdeHandle(_odeHandle);
  parentSpace = odeHandle.space;
  odeHandle.createNewSimpleSpace(parentSpace,true);
  char primitiveMode = mode & ~Primitive::Body; // never create any body for the primitives (TODO: compound body)
  if (!(mode & Primitive::Body)) {
    attachedToParentBody = false;
  }
  for EACHCHILDNODE(boundingBoxNode, node) {
    if (node->getNodeType() == DOMNode::ELEMENT_NODE) {
      Primitive* primitive = 0;
      if (XMLHelper::matchesName(node,XMLDefinitions::boxNode))
        primitive = new Box(VALOFNODE(node, XMLDefinitions::lengthAtt) * scale, VALOFNODE(node, XMLDefinitions::widthAtt) * scale, VALOFNODE(node, XMLDefinitions::heightAtt) * scale);
      else if(XMLHelper::matchesName(node,XMLDefinitions::sphereNode))
        primitive = new Sphere(VALOFNODE(node,XMLDefinitions::radiusAtt));
      else if(XMLHelper::matchesName(node,XMLDefinitions::cylinderNode))
        primitive = new Cylinder(VALOFNODE(node,XMLDefinitions::radiusAtt) * scale, VALOFNODE(node,XMLDefinitions::heightAtt) * scale);
      else if(XMLHelper::matchesName(node,XMLDefinitions::capsuleNode))
        primitive = new Capsule(VALOFNODE(node,XMLDefinitions::radiusAtt) * scale, VALOFNODE(node,XMLDefinitions::heightAtt) * scale);
      if (primitive!=0) {
        XMLPrimitiveFactory::setMaterial(boundingBoxNode, primitive);
        XMLPrimitiveFactory::setMaterial(node,primitive);
        const Vec3 rot = XMLHelper::getRotation(node);
        const Vec3 pos = XMLHelper::getPosition(node);
        if (mode & Primitive::Body) {  // use Transforms to attach the Primitives to the body
          std::cout << "BoundingShape body mode!" << std::endl;
          Primitive* Trans = new lpzrobots::Transform(parent, primitive, osgRotate(rot[0]*M_PI/180.0f,rot[1]*M_PI/180.0f,rot[2]*M_PI/180.0f)
                   *osg::Matrix::translate(scale*pos[0],scale*pos[1],scale*pos[2]));
          Trans->init(odeHandle, 0, osgHandle.changeColor(Color(1.0,0,0,0.3)),primitiveMode);
        }
        else {
          std::cout << "BoundingShape geom only mode!" << std::endl;
          primitive->init(odeHandle, 0, osgHandle.changeColor(Color(1.0,0,0,0.3)), primitiveMode);
          boundingPrimitiveList.push_back(primitive);
          boundingPrimitivePoseList.push_back(osgRotate(rot[0]*M_PI/180.0f,rot[1]*M_PI/180.0f,rot[2]*M_PI/180.0f)
                   *osg::Matrix::translate(scale*pos[0],scale*pos[1],scale*pos[2]));
        }
        active = true;
        std::cout << "Primitive for BoundingShape created!" << std::endl;
      }
    }
  }
  return active;
}
示例#27
0
void SceneNode::setFlagWind(float wind)
{
	int size = this->primitives.size();

	for(int i = 0; i < size; i++)
	{
		Primitive *p = primitives.at(i);

		if(p->Type() == "Flag")
		{
			((Flag *)primitives.at(i))->setWind(wind);
		}
		else if(p->Type() == "Water")
		{
			((Water *)primitives.at(i))->setWind(wind);
		}
	}
}
示例#28
0
void SceneNode::resetAnimation()
{
	if(hasAnimation)
	{
		this->animation->reset();
	}

	int size = this->primitives.size();

	for(int i = 0; i < size; i++)
	{
		Primitive *p = primitives.at(i);

		if(p->Type() == "Vehicle")
		{
			((Vehicle *)primitives.at(i))->resetAnimation();
		}
	}
}
示例#29
0
Node* GameDynamicObject::getRenderObject( sg::Camera* camera ) 
{
	GameObject::getRenderObject( camera );

	if ( camera )
	{
		// view frustum test
		if ( !camera->isInView(position(), boundSphere()) )
			return 0;

		// occlusion test
		/*const Matrix4x4& camtm = camera->cachedWorldTransform();
		if ( !isVisibleFrom(camtm.translation()) )
			return 0;*/

		// apply animations
		if ( m_worldAnim )
			applyWorldSpaceAnimations();

		// set shader parameters
		Light* keylight = this->keylight();
		m_geometry->validateHierarchy();
		for ( Node* node = m_geometry ; node ; node = node->nextInHierarchy() )
		{
			Mesh* mesh = dynamic_cast<Mesh*>( node );
			if ( mesh )
			{
				for ( int i = 0 ; i < mesh->primitives() ; ++i )
				{
					Primitive* prim = mesh->getPrimitive(i);
					Shader* fx = prim->shader();
					if ( fx && fx->parameters() > 0 )
					{
						setShaderParams( fx, mesh, keylight );
					}
				}
			}
		}
	}

	return m_geometry;
}
示例#30
0
	void init(Primitive *prim) {
		data = prim;

		// Get bounds at time 0.5
		BBox mid_bb = data->bounds().at_time(0.5);
		bmin = mid_bb.min;
		bmax = mid_bb.max;

		// Get centroid
		c = (bmin * 0.5) + (bmax * 0.5);
	}