Example #1
0
bool PropertyBag::loadFromFile(const FileName &filename, bool merge) {
	if (!isFileOnDisk(filename)) {
		ERR("File not found: " + filename.str());
		return false;
	}
	
	FileText file;
	
	if (!file.openStream(filename, File::FILE_MODE_READ)) {
		ERR("File failed to load: " + filename.str());
		return false;
	}
	
	const string fileContents = file.getFullText();
	
	// Load / Merge the data
	if (!merge) {
		data.clear();
	}
	
	if (!loadMergeFromString(fileContents)) {
		FAIL("Failed to merge file contents on load: " + filename.str());
		return false;
	}
	
	return true;
}
Example #2
0
int loadHairBin(const FileName& fileName, OBJScene::HairSet* hairset, Vec3fa& offset)
{
    FILE* fin = fopen(fileName.c_str(),"rb");
    if (!fin) throw std::runtime_error("could not open " + fileName.str());
    int magick;
    fread(&magick,sizeof(int),1,fin);
    if (magick != hair_bin_magick)
        throw std::runtime_error("invalid binary hair file " + fileName.str());
    int numHairs;
    fread(&numHairs,sizeof(int),1,fin);
    int numPoints;
    fread(&numPoints,sizeof(int),1,fin);
    int numSegments;
    fread(&numSegments,sizeof(int),1,fin);
    hairset->v.resize(numPoints);
    hairset->hairs.resize(numSegments);
    if (numPoints) fread(&hairset->v[0],sizeof(Vec3fa),numPoints,fin);
    if (numSegments) fread(&hairset->hairs[0],sizeof(OBJScene::Hair),numSegments,fin);
    fclose(fin);

    for (size_t i=0; i<numPoints; i++) {
        hairset->v[i].x-=offset.x;
        hairset->v[i].y-=offset.y;
        hairset->v[i].z-=offset.z;
    }
    return numHairs;
}
Example #3
0
    void Importer::importDefaultExtensions(const std::shared_ptr<Node> &world,
                                           const FileName &fileNamen)
    {
      std::cout << "importDefaultExtensions \"" << fileNamen.str() << "\"" << std::endl;
      std::vector<FileName> files;
      //check for multiple files
      if (fileNamen.str().find(",") != std::string::npos) {
        std::cout << "parsing import file series" << std::endl;
        // file series
        std::string filestr = fileNamen.str();
        std::replace(filestr.begin(),filestr.end(),',',' ');
        std::stringstream ss(filestr);
        std::string file;
        while (ss >> file)
          files.push_back(FileName(file));

        if (files.size() > 0) {
          auto ext = files[0].ext(); //TODO: check that they are all homogeneous
#ifdef OSPRAY_APPS_SG_VTK
          auto& selector = createChild("selector", "Selector");
          if (ext == "vti") {
            sg::importVTIs(selector.shared_from_this(), files);
            return;
          }
#endif
        }
      } else {
Example #4
0
 /*! read png texture from disk */
 std::shared_ptr<Texture> Texture::load(const FileName& fileName)
 {
   if (texture_cache.find(fileName.str()) != texture_cache.end())
     return texture_cache[fileName.str()];
   
   std::shared_ptr<Texture> tex(new Texture(loadImage(fileName),fileName));
   return texture_cache[fileName.str()] = tex;
 }
Example #5
0
  /*! read PFM file from disk */
  Ref<Image> loadPFM(const FileName& fileName)
  {
    /* open PPM file */
    FILE* file = fopen(fileName.c_str(), "rb");
    if (!file) THROW_RUNTIME_ERROR("cannot open " + fileName.str());

    /* read file type */
    char type[8];
    if (fscanf(file, "%7s", type) != 1)
      THROW_RUNTIME_ERROR("Error reading " + fileName.str());

    /* skip comment lines */
    while (readCommentLine(file)) {};

    /* read width, height, and maximal color value */
    int width, height;
    float maxColor;
    if (fscanf(file, "%i %i %f", &width, &height, &maxColor) != 3)
      THROW_RUNTIME_ERROR("Error reading " + fileName.str());

    /* Check for big endian PFM file */
    if (maxColor > 0.0f) {
      fclose(file);
      THROW_RUNTIME_ERROR("Big endian PFM files not supported");
    }
    float rcpMaxColor = -1.0f/float(maxColor);

    /* get return or space */
    fgetc(file);

    /* create image and fill with data */
    Ref<Image> img = new Image3f(width,height,fileName);

    /* image in binary format 32 bit */
    if (!strcmp(type, "PF"))
    {
      float rgb[3];
      for (ssize_t y=0; y<height; y++) {
        for (ssize_t x=0; x<width; x++) {
          if (fread(rgb,sizeof(rgb),1,file) != 1)
            THROW_RUNTIME_ERROR("Error reading " + fileName.str());
          img->set(x,y,Color4(float(rgb[0])*rcpMaxColor,float(rgb[1])*rcpMaxColor,float(rgb[2])*rcpMaxColor,1.0f));
        }
      }
    }

    /* invalid magic value */
    else {
      fclose(file);
      THROW_RUNTIME_ERROR("Invalid magic value in PFM file");
    }

    fclose(file);
    return img;
  }
Example #6
0
  Ref<Device::RTTexture> loadTexture(const FileName fileName)
  {
    static std::map<std::string,Ref<Device::RTTexture> > texture_map;

    if (texture_map.find(fileName.str()) != texture_map.end())
      return texture_map[fileName.str()];

    Ref<Device::RTTexture> texture = g_device->rtNewTexture("nearest");
    texture->rtSetImage("image",loadRTImage(fileName));
    texture->rtCommit();

    return texture_map[fileName.str()] = texture;
  }
Example #7
0
/* main function in embree namespace */
int main(int argc, char** argv)
{
    /* for best performance set FTZ and DAZ flags in MXCSR control and status register */
    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */
    parseCommandLine(stream, FileName());

    /* load default scene if none specified */
    if (filename.ext() == "") {
        FileName file = FileName::executableFolder() + FileName("models/cornell_box.ecs");
        parseCommandLine(new ParseStream(new LineCommentFilter(file, "#")), file.path());
    }

    /* configure number of threads */
    if (g_numThreads)
        g_rtcore += ",threads=" + std::to_string((long long)g_numThreads);
    if (g_numBenchmarkFrames)
        g_rtcore += ",benchmark=1";

    g_rtcore += g_subdiv_mode;

    /* load scene */
    if (strlwr(filename.ext()) == std::string("obj")) {
        g_scene->add(loadOBJ(filename,g_subdiv_mode != ""));
    }
    else if (strlwr(filename.ext()) == std::string("xml")) {
        g_scene->add(loadXML(filename,one));
    }
    else if (filename.ext() != "")
        THROW_RUNTIME_ERROR("invalid scene type: "+strlwr(filename.ext()));

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* send model */
    g_obj_scene.add(g_scene.dynamicCast<SceneGraph::Node>(),g_instancing_mode);
    g_scene = nullptr;
    set_scene(&g_obj_scene);

    /* benchmark mode */
    if (g_numBenchmarkFrames)
        renderBenchmark(outFilename);

    /* render to disk */
    if (outFilename.str() != "")
        renderToFile(outFilename);

    /* interactive mode */
    if (g_interactive) {
        initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
        enterWindowRunLoop(g_anim_mode);
    }

    return 0;
}
Example #8
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    if (filename.str() == "") {
      printf("Error: No input OBJ file specified, use -i option.\n");
      exit(1);
    }

    /* load scene */
    loadOBJ(filename,g_mesh);

    /* initialize ISPC */
    init(g_verbose);

    /* set scene */
    setScene(g_mesh,g_pointLightPosition,g_pointLightIntensity,g_ambientLightIntensity);

    /* initialize GLUT */
    initGlut("tutorial03",g_width,g_height,g_fullscreen,false);
    
    return 0;
  }
Example #9
0
  void main(int argc, char **argv) 
  {
    std::cout << " === Possible cmd line options: -lazy, -pregenerate, -cache === " << std::endl;

    /* set default camera */
    g_camera.from = Vec3fa(1.5f,1.5f,-1.5f);
    g_camera.to   = Vec3fa(0.0f,0.0f,0.0f);

    /*! Parse command line options. */  
    parseCommandLine(new ParseStream(new CommandLineStream(argc, argv)), FileName());

    /*! Set the thread count in the Embree configuration string. */
    if (g_numThreads) g_rtcore += ",threads=" + std::stringOf(g_numThreads);
    g_rtcore += g_subdiv_mode;

    /*! Initialize the task scheduler. */
#if !defined(RTCORE_EXPORT_ALL_SYMBOLS)
    TaskScheduler::create(g_numThreads);
#endif

    /*! Initialize Embree state. */
    init(g_rtcore.c_str());

    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);
    
    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop();
    }
  }
Example #10
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* set default camera */
    g_camera.from = Vec3fa(2.5f,2.5f,2.5f);
    g_camera.to   = Vec3fa(0.0f,0.0f,0.0f);

    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    if (g_numThreads) 
      g_rtcore += ",threads=" + std::stringOf(g_numThreads);

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* render to disk */
    if (outFilename.str() != "") {
      renderToFile(outFilename);
      return 0;
    } 

    /* initialize GLUT */
    initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
    
    /* enter the GLUT run loop */
    enterWindowRunLoop();

    return 0;
  }
Example #11
0
  void storeTga(const Ref<Image>& img, const FileName& fileName)
  {
    FILE* file = fopen(fileName.c_str(), "wb");
    if (!file) THROW_RUNTIME_ERROR("error opening file " + fileName.str());

    fwrite_uchar(0x00, file);
    fwrite_uchar(0x00, file);
    fwrite_uchar(0x02, file);
    fwrite_ushort(0x0000, file);
    fwrite_ushort(0x0000, file);
    fwrite_ushort(0x0000, file);
    fwrite_ushort(0x0000, file);
    fwrite_uchar(0x00, file);
    fwrite_ushort((unsigned short)img->width , file);
    fwrite_ushort((unsigned short)img->height, file);
    fwrite_uchar(0x18, file);
    fwrite_uchar(0x20, file);

    for (size_t y=0; y<img->height; y++) {
      for (size_t x=0; x<img->width; x++) {
        Color c = img->get(x,y);
        fwrite_uchar((unsigned char)(clamp(c.b)*255.0f), file);
        fwrite_uchar((unsigned char)(clamp(c.g)*255.0f), file);
        fwrite_uchar((unsigned char)(clamp(c.r)*255.0f), file);
      }
    }
    fclose(file);
  }
Example #12
0
  int loadHairASCII(const FileName& fileName, OBJScene::HairSet* hairset, Vec3fa& offset)
  {  
    /* open hair file */
    FILE* f = fopen(fileName.c_str(),"r");
    if (!f) throw std::runtime_error("could not open " + fileName.str());

    char line[10000];
    fgets(line,10000,f);
    int numCurves = 0;
    
    while (fgets(line,10000,f) && !feof(f))
    {
      /* comment */
      if (line[0] == '#')
	continue;
      
      if (!strncmp(line,"Curve:",strlen("Curve:")))
      {
        char name[1000];
        unsigned int tracks, points;
        sscanf(line,"Curve: %s %d Tracks %d Points",name,&tracks,&points);

        /* skip Tracks line */
        fgets(line,10000,f);
        
        const int vertex_start_id = hairset->v.size();
        
        double x,y,z,w;
        unsigned int id = 0;
        for (int i=0; i<points; i++)
        {
          fgets(line,10000,f);

          /* comment */
          if (line[0] == '#' || !strncmp(line," Tracks:",strlen(" Tracks:")))
            continue;

          Vec3fa v;
          if (i == 0) sscanf(line,"%d : Bezier %f %f %f %f",&id,&v.x,&v.y,&v.z,&v.w);
          else        sscanf(line,"%d : %f %f %f %f",&id,&v.x,&v.y,&v.z,&v.w);
          //printf("%d %d : %f %f %f %f \n",id,vertex_start_id+id,v.x,v.y,v.z,v.w);		
          v.x-=offset.x;
          v.y-=offset.y;
          v.z-=offset.z;
          hairset->v.push_back(v);
        }
        
        /* add indices to hair starts */
        for (int i=0; i<points-1; i+=3)
          hairset->hairs.push_back(OBJScene::Hair(vertex_start_id + i,numCurves));
	
        if (id != points-1) 
          throw std::runtime_error("hair parsing error");

        numCurves++;
      }
    }
    fclose(f);
    return numCurves;
  }
Example #13
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* for best performance set FTZ and DAZ flags in MXCSR control and status register */
    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

    /* set default camera */
    g_camera.from = Vec3fa(2.5f,2.5f,2.5f);
    g_camera.to   = Vec3fa(0.0f,0.0f,0.0f);

    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    if (g_numThreads) 
      g_rtcore += ",threads=" + toString(g_numThreads);

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* render to disk */
    if (outFilename.str() != "") {
      renderToFile(outFilename);
      return 0;
    } 

    /* initialize GLUT */
    initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
    
    /* enter the GLUT run loop */
    enterWindowRunLoop();

    return 0;
  }
  int main(int argc, char **argv) 
  {
    /* for best performance set FTZ and DAZ flags in MXCSR control and status register */
    _MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
    _MM_SET_DENORMALS_ZERO_MODE(_MM_DENORMALS_ZERO_ON);

    std::cout << " === Possible cmd line options: -pregenerate, -cache === " << std::endl;

    /* set default camera */
    g_camera.from = Vec3fa(1.5f,1.5f,-1.5f);
    g_camera.to   = Vec3fa(0.0f,0.0f,0.0f);

    /*! Parse command line options. */  
    parseCommandLine(new ParseStream(new CommandLineStream(argc, argv)), FileName());

    /*! Set the thread count in the Embree configuration string. */
    if (g_numThreads) g_rtcore += ",threads=" + std::to_string((long long)g_numThreads);
    g_rtcore += g_subdiv_mode;

    /*! Initialize Embree state. */
    init(g_rtcore.c_str());

    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);
    
    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop();
    }
    return 0;
  }
Example #15
0
vector<KeyFrame>
ModelLoaderMD3::loadKeyFrames(const FileName &fileName,
                              const FileName &skinName,
                              TextureFactory &textureFactory) const {
	FILE * stream = fopen(fileName.c_str(), "rb");

	
	VERIFY(stream && !ferror(stream), "MD3 failed to open: "+fileName.str());
	
	Header header = readHeader(stream);
	
	Frame *frames = readFrames(stream, header);
	
	Tag *tags = readTags(stream, header);
	
	Surface *surfaces = readSurfaces(stream, header);
	
	fclose(stream);
	
	vector<KeyFrame> keyFrames = buildKeyFrame(surfaces,
	                             fileName,
	                             skinName,
	                             header,
	                             textureFactory);
	                             
	delete [] frames;
	delete [] tags;
	delete [] surfaces;
	
	return keyFrames;
}
Example #16
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    
    if (g_numThreads) 
      g_rtcore += ",threads=" + std::stringOf(g_numThreads);
    if (g_numBenchmarkFrames)
      g_rtcore += ",benchmark=1";

     g_rtcore += g_subdiv_mode;

    /* load scene */
     if (strlwr(filename.ext()) == std::string("obj"))
       {
         if (g_subdiv_mode != "")
           {
             std::cout << "enabling subdiv mode" << std::endl;
             loadOBJ(filename,one,g_obj_scene,true);	
           }
         else
           loadOBJ(filename,one,g_obj_scene);
       }
    else if (strlwr(filename.ext()) == std::string("xml"))
      loadXML(filename,one,g_obj_scene);
    else if (filename.ext() != "")
      THROW_RUNTIME_ERROR("invalid scene type: "+strlwr(filename.ext()));

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* convert triangle meshes to subdiv meshes */
    if (g_only_subdivs)
      g_obj_scene.convert_to_subdiv();

    /* send model */
    set_scene(&g_obj_scene);
    
    /* benchmark mode */
    if (g_numBenchmarkFrames)
      renderBenchmark(outFilename);
    
    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);
    
    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop(g_anim_mode);

    }

    return 0;
  }
Example #17
0
  /* main function in embree namespace */
  int main(int argc, char** argv) 
  {
    /* create stream for parsing */
    Ref<ParseStream> stream = new ParseStream(new CommandLineStream(argc, argv));

    /* parse command line */  
    parseCommandLine(stream, FileName());
    if (g_numThreads) 
      g_rtcore += ",threads=" + std::stringOf(g_numThreads);
    if (g_numBenchmarkFrames)
      g_rtcore += ",benchmark=1";

    /* initialize task scheduler */
#if !defined(__EXPORT_ALL_SYMBOLS__)
    TaskScheduler::create(g_numThreads);
#endif

    /* load scene */
    if (filename.str() != "")
      loadOBJ(filename,one,g_obj_scene);

    /* initialize ray tracing core */
    init(g_rtcore.c_str());

    /* send model */
    set_scene(&g_obj_scene);
    
    /* benchmark mode */
    if (g_numBenchmarkFrames)
      renderBenchmark(outFilename);
    
    /* render to disk */
    if (outFilename.str() != "")
      renderToFile(outFilename);
    
    /* interactive mode */
    if (g_interactive) {
      initWindowState(argc,argv,tutorialName, g_width, g_height, g_fullscreen);
      enterWindowRunLoop();
    }

    return 0;
  }
Example #18
0
AnimationController* AnimationControllerFactory::createDefault() {
	const FileName fileName("data/models/cylinder/cylinder.md3xml");
	MAP::iterator i = loader.find(fileName.getExtension());
	shared_ptr<ModelLoader> &modelLoader = i->second;
	
	if (i == loader.end()) {
		FAIL("No loader appropriate for default model: " + fileName.str());
		return 0;
	}
	
	// Attempt to load the default model
	AnimationController *model = modelLoader->load(fileName, textureFactory);
	
	if (model) {
		return model;
	} else {
		FAIL("Failed to load default model: " + fileName.str());
		return 0;
	}
}
Example #19
0
  Ref<Device::RTImage> loadRTImage(const FileName fileName)
  {
    static std::map<std::string,Ref<Device::RTImage> > image_map;

    if (image_map.find(fileName.str()) != image_map.end())
      return image_map[fileName.str()];

    Ref<Image> image = loadImage(fileName,true);

    if (!image) {
      int white = 0xFFFFFFFF;
      image_map[fileName.str()] = g_device->rtNewImage("RGB8",1,1,&white);
    }
    else if (Ref<Image3f> fimg = image.dynamicCast<Image3f>())
      image_map[fileName.str()] = g_device->rtNewImage("RGB_FLOAT32",fimg->width,fimg->height,&fimg->data[0]);
    else if (Ref<Image3c> cimg = image.dynamicCast<Image3c>())
      image_map[fileName.str()] = g_device->rtNewImage("RGB8",cimg->width,cimg->height,&cimg->data[0]);
    else
      throw std::runtime_error("unknown image type");

    return image_map[fileName.str()];
  }
Example #20
0
void SoundSystem::playMusic(const FileName &fileName)
{
	stopMusic();

	if(!mute && fileName!=FileName("none") && fileName!=FileName(""))
	{
		musicStream = FSOUND_Stream_Open(fileName.c_str(),
		                                 FSOUND_LOOP_NORMAL,
										 0, 0);
		musicChannel = FSOUND_Stream_Play(FSOUND_FREE, musicStream);
		TRACE("Playing music: " + fileName.str());
	}
}
Example #21
0
vector<KeyFrame> ModelLoaderMD3::buildKeyFrame(Surface * surfaces,
  const FileName &fileName,
  const FileName &skinName,
  const Header &header,
  TextureFactory &textureFactory) {
	vector<KeyFrame> keyFrames;
	
	const FileName directory = fileName.getPath();
	
	/*
	Only the first frame loads texture files.
	The other frames use a copy of the handles and that copy is stored in here.
	*/
	Material md3Material;
	
	// Take the all the surfaces and push each frame into the mesh manager
	for (int i=0; i<surfaces[0].header.numFrames; ++i) {
		string name = fileName.str() + "#" + itos(i);
		
		// Create a mesh from the surface
		Mesh *mesh = surfaces[0].getObject(i);
		
		// Load a material for the first mesh in the first model.
		// First model only! Ignored for subsequent models
		if (i==0) {
			if (header.numSurfaces > 0) {
				mesh->material.clear();
				
#if 0
				if (surfaces[0].header.numShaders > 0) {
					const char *shaderName=(char*)surfaces[0].shaders[0].name;
					FileName skin = directory.append(FileName(shaderName));
					mesh->material.setTexture(textureFactory.load(skin));
				} else {
					mesh->material.setTexture(textureFactory.load(skinName));
				}
#else
				mesh->material.setTexture(textureFactory.load(skinName));
#endif
				// Keep a copy of the material to propagate to the subsequent frames
				md3Material = mesh->material;
			}
		} else {
			mesh->material = md3Material; // shallow copy
		}
		
		keyFrames.push_back(KeyFrame(mesh));
	}
	
	return keyFrames;
}
Example #22
0
  void loadHair(const FileName& fileName, OBJScene& scene, Vec3fa& offset)
  {
    /* add new hair set to scene */
    OBJScene::HairSet* hairset = new OBJScene::HairSet; 
#if CONVERT_TO_BINARY   
    offset = Vec3fa(zero);
#endif

    int numHairs = 0;
    if (fileName.ext() == "txt")
      numHairs = loadHairASCII(fileName,hairset,offset);
    else
      numHairs = loadHairBin(fileName,hairset,offset);
    
    /* reduce number of hairs */
    if (g_reduce_hair_segment_error != 0.0f)
    {
      std::ios_base :: fmtflags   flag = std::cout.flags();
      std           :: streamsize prec = std::cout.precision();
      std::cout << "reducing number of hair segments ... " << std::flush;
      std::cout.precision(3);
      std::cout << 1E-6*float(hairset->hairs.size()) << "M" << std::flush;
      for (size_t i=0; i<10; i++) {
        hairset = reduce_hairs(hairset,g_reduce_hair_segment_error);
        std::cout << " " << 1E-6*float(hairset->hairs.size()) << "M" << std::flush;
      }
      std::cout << " [DONE]" << std::endl;
      std::cout.flags    (flag);
      std::cout.precision(prec);
    }

    /* add hairset to scene */
    scene.hairsets.push_back(hairset);

    int numPoints = hairset->v.size();
    int numSegments = hairset->hairs.size();

#if CONVERT_TO_BINARY
    FILE* fout = fopen(fileName.setExt(".bin").c_str(),"wb");
    if (!fout) THROW_RUNTIME_ERROR("could not open " + fileName.str());
    fwrite(&hair_bin_magick,sizeof(int),1,fout);
    fwrite(&numHairs,sizeof(int),1,fout);
    fwrite(&numPoints,sizeof(int),1,fout);
    fwrite(&numSegments,sizeof(int),1,fout);
    if (numPoints) fwrite(&hairset->v[0],sizeof(Vec3fa),numPoints,fout);
    if (numSegments) fwrite(&hairset->hairs[0],sizeof(OBJScene::Hair),numSegments,fout);
    fclose(fout);
#endif
  }
Example #23
0
  void loadHair(const FileName& fileName, OBJScene& scene, Vec3fa& offset)
  {
    /* add new hair set to scene */
    OBJScene::HairSet* hairset = new OBJScene::HairSet; 
#if CONVERT_TO_BINARY   
    offset = Vec3fa(zero);
#endif

    int numHairs = 0;
    if (fileName.ext() == "txt")
      numHairs = loadHairASCII(fileName,hairset,offset);
    else
      numHairs = loadHairBin(fileName,hairset,offset);
    
    /* reduce number of hairs */
#if 0
    PRINT(hairset->hairs.size());
    hairset = reduce_hairs(hairset);
    PRINT(hairset->hairs.size());
    hairset = reduce_hairs(hairset);
    PRINT(hairset->hairs.size());
    hairset = reduce_hairs(hairset);
    PRINT(hairset->hairs.size());
    hairset = reduce_hairs(hairset);
    PRINT(hairset->hairs.size());
#endif

    /* add hairset to scene */
    scene.hairsets.push_back(hairset);

    int numPoints = hairset->v.size();
    int numSegments = hairset->hairs.size();
    PRINT(numHairs);
    PRINT(numSegments);
    PRINT(numPoints);

#if CONVERT_TO_BINARY
    FILE* fout = fopen(fileName.setExt(".bin").c_str(),"wb");
    if (!fout) throw std::runtime_error("could not open " + fileName.str());
    fwrite(&hair_bin_magick,sizeof(int),1,fout);
    fwrite(&numHairs,sizeof(int),1,fout);
    fwrite(&numPoints,sizeof(int),1,fout);
    fwrite(&numSegments,sizeof(int),1,fout);
    if (numPoints) fwrite(&hairset->v[0],sizeof(Vec3fa),numPoints,fout);
    if (numSegments) fwrite(&hairset->hairs[0],sizeof(OBJScene::Hair),numSegments,fout);
    fclose(fout);
#endif
  }
Example #24
0
  /*! store PFM file to disk */
  void storePFM(const Ref<Image>& img, const FileName& fileName)
  {
    FILE* file = fopen(fileName.c_str(), "wb");
    if (!file) THROW_RUNTIME_ERROR("cannot open file " + fileName.str());
    fprintf(file,"PF\n%i %i\n%f\n", int(img->width), int(img->height), -1.0f);

    float rgb[3];
    for (size_t y=0; y<img->height; y++) {
      for (size_t x=0; x<img->width; x++) {
        Color4 c = img->get(x,y);
        rgb[0] = c.r; rgb[1] = c.g; rgb[2] = c.b;
        fwrite(rgb,sizeof(rgb),1,file);
      }
    }
    fclose(file);
  }
Example #25
0
/*! store PPM file to disk */
void storePPM(const Ref<Image>& img, const FileName& fileName)
{
    FILE* file = fopen(fileName.c_str(), "wb");
    if (!file) THROW_RUNTIME_ERROR("cannot open file " + fileName.str());
    fprintf(file,"P6\n%i %i\n255\n", int(img->width), int(img->height));

    for (size_t y=0; y<img->height; y++) {
        for (size_t x=0; x<img->width; x++) {
            const Color4 c = img->get(x,y);
            fputc((unsigned char)(clamp(c.r)*255.0f), file);
            fputc((unsigned char)(clamp(c.g)*255.0f), file);
            fputc((unsigned char)(clamp(c.b)*255.0f), file);
        }
    }
    fclose(file);
}
AnimationController* AnimationControllerFactory::createDefault()
{
    AnimationController *model = 0;

	const FileName fileName("data/models/cylinder/cylinder.md3xml");

	MAP::iterator i = loader.find(fileName.getExtension());

	if(i == loader.end() ||
      (i != loader.end() &&
	       !(model = i->second->load(fileName, textureFactory))))
	{
        FAIL("Failed to load default model: " + fileName.str());
        return 0;
	}
       
    return model;
}
Example #27
0
  void loadKeyFrameAnimation(FileName &fileName)
  {
    PRINT(fileName);
    std::ifstream cin;
    cin.open(fileName.c_str());
    if (!cin.is_open()) {
      std::cerr << "cannot open " << fileName.str() << std::endl;
      return;
    }
    
    FileName path;
    path = fileName.path();

    char line[10000];
    memset(line, 0, sizeof(line));

    int cur = 0;
    while (cin.peek() != -1)
    {
      /* load next multiline */
      char* pline = line;
      while (true) {
        cin.getline(pline, sizeof(line) - (pline - line) - 16, '\n');
        ssize_t last = strlen(pline) - 1;
        if (last < 0 || pline[last] != '\\') break;
        pline += last;
        *pline++ = ' ';
      }
      OBJScene *scene = new OBJScene;
      FileName keyframe = path + FileName(line);
      loadOBJ(keyframe,one,*scene,true);	
      PRINT(keyframe);
      if (g_obj_scene.subdiv.size() != scene->subdiv.size())
	FATAL("#subdiv meshes differ");
      for (size_t i=0;i<g_obj_scene.subdiv.size();i++)
	if (g_obj_scene.subdiv[i]->positions.size() != scene->subdiv[i]->positions.size())
	  FATAL("#positions differ");

      g_keyframes.push_back(scene);
    } 
    cin.close();

    
  }
Example #28
0
vector<KeyFrame>
ModelLoaderMD2::loadKeyFrames(const FileName &fileName,
                              const FileName &skinName,
                              TextureFactory &textureFactory) const {
	FILE *stream=0;
	
//	fopen_s(&stream, fileName.c_str(), "rb");
	stream = fopen(fileName.c_str(), "rb");
	
	VERIFY(stream && !ferror(stream), "MD2 failed to open: "+fileName.str());
	
	Header header = readHeader(stream);
	Skin *skins = readSkins(stream, header);
	TexCoord *texCoords = readTexCoords(stream, header);
	Triangle *triangles = readTriangles(stream, header);
	Frame *frames = readFrames(stream, header);
	
	fclose(stream);
	
	Material skin;
	
	if (header.numOfSkins>0) {
		skin.setTexture(textureFactory.load(FileName((const char*)skins[0].name)));
	} else {
		skin.setTexture(textureFactory.load(skinName));
	}
	
	vector<KeyFrame> keyFrames = buildKeyFrames(fileName,
	                             skin,
	                             header,
	                             texCoords,
	                             triangles,
	                             frames);
	                             
	delete [] skins;
	delete [] texCoords;
	delete [] triangles;
	delete [] frames;
	
	return keyFrames;
}
Example #29
0
  SceneLoadingTutorialApplication::SceneLoadingTutorialApplication (const std::string& tutorialName, int features)

    : TutorialApplication(tutorialName, features),
      scene(new SceneGraph::GroupNode),
      convert_tris_to_quads(false),
      convert_tris_to_quads_prop(inf),
      convert_bezier_to_lines(false),
      convert_hair_to_curves(false),
      convert_bezier_to_bspline(false),
      convert_bspline_to_bezier(false),
      remove_mblur(false),
      remove_non_mblur(false),
      sceneFilename(""),
      instancing_mode(SceneGraph::INSTANCING_NONE),
      print_scene_cameras(false)
  {
    registerOption("i", [this] (Ref<ParseStream> cin, const FileName& path) {
        sceneFilename = path + cin->getFileName();
      }, "-i <filename>: parses scene from <filename>");

    registerOption("animlist", [this] (Ref<ParseStream> cin, const FileName& path) {
        FileName listFilename = path + cin->getFileName();

        std::ifstream listFile;
        listFile.open(listFilename.c_str());
        if (!listFile.is_open()) {
          THROW_RUNTIME_ERROR("cannot open " + listFilename.str());
        }
        else
        {
          while (!listFile.eof())
          {
            std::string line;
            listFile >> line;
            if (line != "")
              keyFramesFilenames.push_back(listFilename.path() + line);
          }
        }
      }, "-animlist <filename>: parses a sequence of .obj/.xml files listed in <filename> and adds them to the scene");
Example #30
0
vector<KeyFrame> ModelLoaderMD2::buildKeyFrames(const FileName &fileName,
  const Material &skin,
  const Header &header,
  TexCoord *texCoords,
  Triangle *triangles,
  Frame *frames) {
  
	vector<KeyFrame> keyFrames;
	
	float heightBelowGround=0;
	
	// Take the all the frames and push each frame into the mesh manager
	for (int i=0; i<header.numOfFrames; ++i) {
		string name = fileName.str() + "#" + itos(i);
		
		Mesh *mesh = buildKeyFrame(skin,
		                           header,
		                           texCoords,
		                           triangles,
		                           frames[i]);
		                           
		if (i==0) {
			heightBelowGround = mesh->calculateHeightBelowGround();
		}
		
		// Place the feet of the mesh on the ground
		vec3 *vertices = (vec3*)mesh->vertexArray->lock();
		for (int i=0; i<mesh->vertexArray->getNumber(); ++i) {
			vertices[i].y -= heightBelowGround;
		}
		mesh->vertexArray->unlock();
		
		keyFrames.push_back(KeyFrame(mesh));
	}
	
	return keyFrames;
}