Example #1
0
void
vpSimulator::save(const char *name,bool binary)
{
  // get a pointer to the object "name"
  SoOutput output ;
  output.openFile(name) ;

  if (binary==true)  output.setBinary(TRUE) ;

  SoWriteAction writeAction(&output) ;
  writeAction.apply(scene) ;
  output.closeFile() ;

}
void
SoIntersectionDetectionAction::apply(SoNode * node)
{
  // Keep this around, as it's handy for dumping a stand-alone scene
  // to work with from an invocation within an application framework.
#if 0 // disabled
  SoOutput out;
  SbBool ok = out.openFile("/tmp/assembly.wrl");
  assert(ok);
  SoWriteAction wa(&out);
  wa.apply(node);
  out.closeFile();
#endif // disabled

  PRIVATE(this)->reset();

  // Needs a bounding box for the full scene, for later initialization
  // of the SbOctTree of shape bounding boxes.
  SbViewportRegion vp;
  SoGetBoundingBoxAction bboxaction(vp);
  bboxaction.apply(node);
  PRIVATE(this)->fullxfbbox = bboxaction.getXfBoundingBox();

  if (ida_debug()) { // debug
    SoGetPrimitiveCountAction counter;
    counter.apply(node);
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "number of triangle primitives in scene: %d",
                           counter.getTriangleCount());
  }

  PRIVATE(this)->traverser->apply(node);

  SbTime starttime;
  if (ida_debug()) { // debug
    starttime = SbTime::getTimeOfDay();
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "calling doIntersectionTesting()...");
  }

  PRIVATE(this)->doIntersectionTesting();

  if (ida_debug()) { // debug
    SoDebugError::postInfo("SoIntersectionDetectionAction::apply",
                           "doIntersectionTesting() done after %f seconds.",
                           (SbTime::getTimeOfDay() - starttime).getValue());
  }
}
Example #3
0
void
MainWindow::saveScene()
{
	SoOutput output;
	
	if (!output.openFile(QString("coach-" + QDateTime::currentDateTime().toString("yyyyMMdd-HHmmsszzz") + ".wrl").toStdString().c_str()))
	{
		return;
	}
	
	output.setHeaderString("#VRML V2.0 utf8");
	
	SoWriteAction writeAction(&output);
	writeAction.apply(this->scene->root);
	
	output.closeFile();
}
Example #4
0
void
Viewer::saveScene()
{
	QString filename = "rlPlanDemo-" + QDateTime::currentDateTime().toString("yyyyMMdd-HHmmsszzz") + ".wrl";
	
	SoOutput output;
	
	if (!output.openFile(filename.toStdString().c_str()))
	{
		return;
	}
	
	output.setHeaderString("#VRML V2.0 utf8");
	
	SoWriteAction writeAction(&output);
	writeAction.apply(this->root);
	
	output.closeFile();
	
	MainWindow::instance()->statusBar()->showMessage("Successfully saved scene in '" + filename + "'.", 1000);
}
osgDB::ReaderWriter::WriteResult
ReaderWriterIV::writeNode(const osg::Node& node, const std::string& fileName,
                          const osgDB::ReaderWriter::Options* /*options*/) const
{
    // accept extension
    std::string ext = osgDB::getLowerCaseFileExtension(fileName);
    if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;
    bool useVRML1 = !isInventorExtension(osgDB::getFileExtension(fileName));

    OSG_NOTICE << "osgDB::ReaderWriterIV::writeNode() Writing file "
                             << fileName.data() << std::endl;

    // Convert OSG graph to Inventor graph
    ConvertToInventor osg2iv;
    osg2iv.setVRML1Conversion(useVRML1);
    (const_cast<osg::Node*>(&node))->accept(osg2iv);
    SoNode *ivRoot = osg2iv.getIvSceneGraph();
    if (ivRoot == NULL)
        return WriteResult::ERROR_IN_WRITING_FILE;
    ivRoot->ref();

    // Change prefix according to VRML spec:
    // Node names must not begin with a digit, and must not contain spaces or
    // control characters, single or double quote characters, backslashes, curly braces,
    // the sharp (#) character, the plus (+) character or the period character.
    if (useVRML1)
      SoBase::setInstancePrefix("_");

    // Write Inventor graph to file
    SoOutput out;
    out.setHeaderString((useVRML1) ? "#VRML V1.0 ascii" : "#Inventor V2.1 ascii");
    if (!out.openFile(fileName.c_str()))
        return WriteResult::ERROR_IN_WRITING_FILE;
    SoWriteAction wa(&out);
    wa.apply(ivRoot);
    ivRoot->unref();

    return WriteResult::FILE_SAVED;
}
Example #6
0
bool CoinVisualizationNode::saveModel(const std::string &modelPath, const std::string &filename)
{
	std::string outFile = filename;

	boost::filesystem::path completePath(modelPath);
	boost::filesystem::path fn(outFile);

	if (!boost::filesystem::is_directory(completePath))
	{
		if (!boost::filesystem::create_directories(completePath))
		{
			VR_ERROR << "Could not create model dir  " << completePath.string() << endl;
			return false;
		}
	}

	boost::filesystem::path completeFile = boost::filesystem::operator/(completePath,fn);

    SoOutput* so = new SoOutput();
    if (!so->openFile(completeFile.string().c_str()))
    {
        VR_ERROR << "Could not open file " << completeFile.string() << " for writing." << endl;
    }
	SoGroup *n = new SoGroup;
	n->ref();
	n->addChild(visualization);
	SoGroup* newVisu = CoinVisualizationFactory::convertSoFileChildren(n);
	newVisu->ref();
    SoWriteAction wa(so);
    wa.apply(newVisu);
	so->closeFile();

	newVisu->unref();
	n->unref();

    return true;
}
Example #7
0
int
main(int argc, char ** argv)
{
  fprintf(stderr, "ivcp v0.1\n");

  SoDB::init();
  SoNodeKit::init();
  SoInteraction::init();

  if (argc != 3 ) {
    fprintf(stdout, "Usage: %s infile outfile\n", argv[0]);
    return 0;
  }

  SoInput * in = new SoInput;
  if (!in->openFile(argv[1])) {
    fprintf(stderr, "error: could not open file '%s'\n", argv[1]);
    delete in;
    SoDB::cleanup();
    return -1;
  }

  SoNode * scene = SoDB::readAll(in);

  if (!scene) {
    fprintf(stderr, "error: could not read file '%s'\n", argv[1]);
    delete in;
    SoDB::cleanup();
    return -1;
  }
  FileType inputFileType;
  if (in->isFileVRML1())
    inputFileType = VRML1;
  else if (in->isFileVRML2())
    inputFileType = VRML2;
  else
    inputFileType = INVENTOR;

  delete in;
  scene->ref();

  SoNode * firstChild = static_cast<SoSeparator*>(scene)->getNumChildren()?
    static_cast<SoSeparator*>(scene)->getChild(0)
    :NULL;

  if (firstChild && firstChild->isOfType(SoForeignFileKit::getClassTypeId())) {
    SoForeignFileKit * kit = (SoForeignFileKit *) firstChild;
    if (kit->canWriteScene() ) {
      SoNode * subscene = NULL;
      kit->writeScene(subscene);
      if (!subscene ) {
        return -1;
      }
      subscene->ref();
      scene->unref();
      scene = subscene;
    }
  }

  SoOutput * out = new SoOutput;
  if (!out->openFile(argv[2])) {
    fprintf(stderr, "error: could not open file '%s' for writing\n");
    scene->unref();
    delete out;
    SoDB::cleanup();
    return -1;
  }
  switch (inputFileType) {
  case VRML1:
    out->setHeaderString("#VRML V1.0 ascii");
    break;
  case VRML2:
    out->setHeaderString("#VRML V2.0 utf8");
  }

  SoWriteAction wa(out);
  wa.apply(scene);

  out->closeFile();
  delete out;

  scene->unref();

  // with actions on the stack, cleanup can't be called...
  // SoDB::cleanup();
  return 0;
}
// Execute full set of intersection detection operations on all the
// primitives that has been souped up from the scene graph.
void
SoIntersectionDetectionAction::PImpl::doIntersectionTesting(void)
{
  if (this->callbacks.empty()) {
    SoDebugError::postWarning("SoIntersectionDetectionAction::PImpl::doIntersectionTesting",
                              "intersection testing invoked, but no callbacks set up");
    return;
  }

  delete this->traverser;
  this->traverser = NULL;

  if (ida_debug()) {
    SoDebugError::postInfo("SoIntersectionDetectionAction::PImpl::doIntersectionTesting",
                           "total number of shapedata items == %d",
                           this->shapedata.getLength());

  }

  const SbOctTreeFuncs funcs = {
    NULL /* ptinsidefunc */,
    shapeinsideboxfunc,
    NULL /* insidespherefunc */,
    NULL /* insideplanesfunc */
  };

  SbBox3f b = this->fullxfbbox.project();
  // Add a 1% slack to the bounding box, to avoid problems in
  // SbOctTree due to floating point inaccuracies (see assert() in
  // SbOctTree::addItem()).
  //
  // This may be just a temporary hack -- see the FIXME at the
  // same place.
  SbMatrix m;
  m.setTransform(SbVec3f(0, 0, 0), // translation
                 SbRotation::identity(), // rotation
                 SbVec3f(1.01f, 1.01f, 1.01f), // scalefactor
                 SbRotation::identity(), // scaleorientation
                 SbVec3f(b.getCenter())); // center
  b.transform(m);

  SbOctTree shapetree(b, funcs);
  for (int k = 0; k < this->shapedata.getLength(); k++) {
    ShapeData * shape = this->shapedata[k];
    if (shape->xfbbox.isEmpty()) { continue; }
    shapetree.addItem(shape);
  }

  if (ida_debug()) { shapetree.debugTree(stderr); }

  // For debugging.
  unsigned int nrshapeshapeisects = 0;
  unsigned int nrselfisects = 0;

  const float theepsilon = this->getEpsilon();

  for (int i = 0; i < this->shapedata.getLength(); i++) {
    ShapeData * shape1 = this->shapedata[i];

    // If the shape has no geometry, immediately skip to next
    // iteration of for-loop.
    if (shape1->xfbbox.isEmpty()) { continue; }

    // Remove shapes from octtree as we iterate over the full set, to
    // avoid self-intersection and to avoid checks against other
    // shapes happening both ways.
    shapetree.removeItem(shape1);

    // FIXME: shouldn't we also invoke the filter-callback here? 20030403 mortene.
    if (this->internalsenabled) {
      nrselfisects++;
      SbBool cont;
      this->doInternalPrimitiveIntersectionTesting(shape1->getPrimitives(), cont);
      if (!cont) { goto done; }
    }

    SbBox3f shapebbox = shape1->xfbbox.project();
    if (theepsilon > 0.0f) {
      const SbVec3f e(theepsilon, theepsilon, theepsilon);
      // Extend bbox in all 6 directions with the epsilon value.
      shapebbox.getMin() -= e;
      shapebbox.getMax() += e;
    }
    SbList<void*> candidateshapes;
    shapetree.findItems(shapebbox, candidateshapes);

    if (ida_debug()) {
      SoDebugError::postInfo("SoIntersectionDetectionAction::PImpl::doIntersectionTesting",
                             "shape %d intersects %d other shapes",
                             i, candidateshapes.getLength());

      // debug, dump to .iv-file the "master" shape bbox given by i,
      // plus ditto for all intersected shapes
#if 0
      if (i == 4) {
        SoSeparator * root = new SoSeparator;
        root->ref();

        root->addChild(make_scene_graph(shape1->xfbbox, "mastershape"));

        for (int j = 0; j < candidateshapes.getLength(); j++) {
          ShapeData * s = (ShapeData * )candidateshapes[j];
          SbString str;
          str.sprintf("%d", j);
          root->addChild(make_scene_graph(s->xfbbox, str.getString()));
        }

        SoOutput out;
        SbBool ok = out.openFile("/tmp/shapechk.iv");
        assert(ok);
        SoWriteAction wa(&out);
        wa.apply(root);

        root->unref();
      }
#endif // debug
    }

    SbXfBox3f xfboxchk;
    if (theepsilon > 0.0f) { xfboxchk = expand_SbXfBox3f(shape1->xfbbox, theepsilon); }
    else { xfboxchk = shape1->xfbbox; }

    for (int j = 0; j < candidateshapes.getLength(); j++) {
      ShapeData * shape2 = static_cast<ShapeData *>(candidateshapes[j]);

      if (!xfboxchk.intersect(shape2->xfbbox)) {
        if (ida_debug()) {
          SoDebugError::postInfo("SoIntersectionDetectionAction::PImpl::doIntersectionTesting",
                                 "shape %d intersecting %d is a miss when tried with SbXfBox3f::intersect(SbXfBox3f)",
                                 i, j);
        }
        continue;
      }

      if (!this->filtercb ||
          this->filtercb(this->filterclosure, shape1->path, shape2->path)) {
        nrshapeshapeisects++;
        SbBool cont;
        this->doPrimitiveIntersectionTesting(shape1->getPrimitives(), shape2->getPrimitives(), cont);
        if (!cont) { goto done; }
      }
    }
  }

 done:
  if (ida_debug()) {
    SoDebugError::postInfo("SoIntersectionDetectionAction::PImpl::doIntersectionTesting",
                           "shape-shape intersections: %d, shape self-intersections: %d",
                           nrshapeshapeisects, nrselfisects);
  }
}
Example #9
0
int
main(int argc, char** argv)
{
	if (argc != 3)
	{
		std::cerr << "Usage: tris2wrl [input.tris] [output.wrl]" << std::endl;
		return EXIT_FAILURE;
	}
	
	SoDB::init();
	
	std::fstream file;
	file.open(argv[1]);
	
	std::string line;
	std::vector<std::string> tokens;
	
	std::getline(file, line);
	
	if (!boost::starts_with(line, "#"))
	{
		file.close();
		return EXIT_FAILURE;
	}
	
	SoVRMLTransform* root = new SoVRMLTransform();
	root->ref();
	
	SoVRMLShape* shape = new SoVRMLShape();
	root->addChild(shape);
	
	SoVRMLAppearance* appearance = new SoVRMLAppearance();
	shape->appearance = appearance;
	
	SoVRMLMaterial* material = new SoVRMLMaterial();
	appearance->material = material;
	
	SoVRMLIndexedFaceSet* indexedFaceSet = new SoVRMLIndexedFaceSet();
	shape->geometry = indexedFaceSet;
	
	SoVRMLCoordinate* coordinate = new SoVRMLCoordinate();
	indexedFaceSet->coord = coordinate;
	
	SoVRMLColor* color = new SoVRMLColor();
	indexedFaceSet->color = color;
	
	indexedFaceSet->colorPerVertex.setValue(false);
	indexedFaceSet->solid.setValue(false);
	
	while (-1 != file.peek())
	{
		std::getline(file, line);
		
		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}
		
		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);
		
		coordinate->point.set1Value(coordinate->point.getNum(), std::stof(tokens[0]), std::stof(tokens[1]), std::stof(tokens[2]));
	}
	
	while (-1 != file.peek())
	{
		std::getline(file, line);
		
		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}
		
		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);
		
		for (std::size_t i = 0; i < tokens.size(); ++i)
		{
			indexedFaceSet->coordIndex.set1Value(indexedFaceSet->coordIndex.getNum(), std::stoi(tokens[i]));
		}
		
		indexedFaceSet->coordIndex.set1Value(indexedFaceSet->coordIndex.getNum(), -1);
	}
	
	while (-1 != file.peek())
	{
		std::getline(file, line);
		
		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}
		
		boost::trim(line);
		boost::split(tokens, line, boost::is_space(), boost::token_compress_on);
		
		if (tokens.size() > 5)
		{
			color->color.set1Value(color->color.getNum(), std::stof(tokens[3]), std::stof(tokens[4]), std::stof(tokens[5]));
		}
	}
	
	while (-1 != file.peek())
	{
		std::getline(file, line);
		
		if (line.empty())
		{
			continue;
		}
		else if (boost::starts_with(line, "#"))
		{
			break;
		}
		
		boost::trim_if(line, boost::is_any_of(", \t\n\v\f\r"));
		boost::split(tokens, line, boost::is_any_of(", "), boost::token_compress_on);
		
		for (std::size_t i = 0; i < tokens.size(); ++i)
		{
			indexedFaceSet->colorIndex.set1Value(indexedFaceSet->colorIndex.getNum(), std::stoi(tokens[i]));
		}
	}
	
	std::cout << "coordinates: " << coordinate->point.getNum() << std::endl;
	std::cout << "faces: " << indexedFaceSet->coordIndex.getNum() / 4 << std::endl;
	std::cout << "materials: " << color->color.getNum() << std::endl;
	std::cout << "material indices: " << indexedFaceSet->colorIndex.getNum() << std::endl;
	
	if (0 == indexedFaceSet->colorIndex.getNum())
	{
		color->ref();
		indexedFaceSet->color.setValue(nullptr);
		color->unref();
	}
	
	file.close();
	
	SoOutput out;
	out.openFile(argv[2]);
	out.setHeaderString("#VRML V2.0 utf8");
	SoWriteAction wra(&out);
	wra.apply(root);
	out.closeFile();
	
	root->unref();
	
	return EXIT_SUCCESS;
}
Example #10
0
int
main(int argc, char ** argv)
{
  if ( argc != 3 ) {
    fprintf(stderr, "Usage: %s <infile.iv> <outfile.iv>\n", argv[0]);
    return -1;
  }

  SoDB::init();
  SoNodeKit::init();
  SoInteraction::init();

  SoGenerateSceneGraphAction::initClass();
  SoTweakAction::initClass();

  SoInput in;
  SoNode * scene, * graph;
  if ( !in.openFile(argv[1]) ) {
    fprintf(stderr, "%s: error opening \"%s\" for reading.\n", argv[0], argv[1]);
    return -1;
  }
  scene = SoDB::readAll(&in);
  if ( scene == NULL ) {
    fprintf(stderr, "%s: error parsing \"%s\"\n", argv[0], argv[1]);
    return -1;
  }
  scene->ref();

  SoGenerateSceneGraphAction action;
  // action.setDropTypeIfNameEnabled(TRUE);
  action.apply(scene);
  graph = action.getGraph();
  if ( graph == NULL ) {
    fprintf(stderr, "%s: error generating scene graph\n", argv[0]);
    return -1;
  }
  graph->ref();
  scene->unref();
  scene = NULL;

  // figure out camera settings and needed rendering canvas size
  SoGetBoundingBoxAction bbaction(SbViewportRegion(64,64)); // just something
  bbaction.apply(graph);

  SbBox3f bbox = bbaction.getBoundingBox();
  SbVec3f min = bbox.getMin();
  SbVec3f max = bbox.getMax();
  float bwidth = max[0] - min[0];
  float bheight = max[1] - min[1];
  // fprintf(stdout, "min: %g %g %g\n", min[0], min[1], min[2]);
  // fprintf(stdout, "max: %g %g %g\n", max[0], max[1], max[2]);

  // place camera
  SoSearchAction search;
  search.setType(SoCamera::getClassTypeId());
  search.setInterest(SoSearchAction::FIRST);
  search.apply(graph);
  SoPath * campath = search.getPath();
  SoOrthographicCamera * cam = (SoOrthographicCamera *) campath->getTail();
  assert(cam != NULL);
  SbVec3f pos = cam->position.getValue();
  cam->position.setValue(SbVec3f(min[0] + ((max[0]-min[0])/2.0),
                                 min[1] + ((max[1]-min[1])/2.0),
				 pos[2]));
  cam->height.setValue(bheight);

  if ( TRUE ) { // FIXME: only write .iv-scene if asked
    SoOutput out;
    if ( !out.openFile(argv[2]) ) {
      fprintf(stderr, "%s: error opening \"%s\" for writing.\n", argv[0], argv[2]);
      return -1;
    }
    SoWriteAction writer(&out);
    // writer.setCoinFormattingEnabled(TRUE);
    writer.apply(graph);
  }

  int width = (int) ceil(bwidth * 150.0) + 2;
  int height = (int) ceil(bheight * 150.0);
  fprintf(stderr, "image: %d x %d\n", width, height);
  if ( TRUE ) { // FIXME: only write image if asked
    SoOffscreenRenderer renderer(SbViewportRegion(width, height));
    SoGLRenderAction * glra = renderer.getGLRenderAction();
    glra->setNumPasses(9);
    // FIXME: auto-crop image afterwards?  seems like it's a perfect fit right now
    renderer.setComponents(SoOffscreenRenderer::RGB_TRANSPARENCY);
    renderer.setBackgroundColor(SbColor(1.0,1.0,1.0));
    renderer.render(graph);
    // FIXME: support command line option filename
    // FIXME: also support .eps
    renderer.writeToFile("output.png", "png");
  }

  graph->unref();
  return 0;
}