예제 #1
0
파일: brep.cpp 프로젝트: cciechad/brlcad
/**
 *			R T _ B R E P _ I M P O R T 5
 */
int
rt_brep_import5(struct rt_db_internal *ip, const struct bu_external *ep, register const fastf_t *mat, const struct db_i *dbip)
{
    ON::Begin();
    TRACE1("rt_brep_import5");
    struct rt_brep_internal* bi;
    BU_CK_EXTERNAL(ep);
    RT_CK_DB_INTERNAL(ip);
    ip->idb_major_type = DB5_MAJORTYPE_BRLCAD;
    ip->idb_type = ID_BREP;
    ip->idb_meth = &rt_functab[ID_BREP];
    ip->idb_ptr = bu_malloc(sizeof(struct rt_brep_internal), "rt_brep_internal");

    bi = (struct rt_brep_internal*)ip->idb_ptr;
    bi->magic = RT_BREP_INTERNAL_MAGIC;

    RT_MemoryArchive archive(ep->ext_buf, ep->ext_nbytes);
    ONX_Model model;
    ON_TextLog dump(stderr);
    //archive.Dump3dmChunk(dump);
    model.Read(archive, &dump);

    if (model.IsValid(&dump)) {
	ONX_Model_Object mo = model.m_object_table[0];
	// XXX does openNURBS force us to copy? it seems the answer is
	// YES due to the const-ness
	bi->brep = new ON_Brep(*ON_Brep::Cast(mo.m_object));
	return 0;
    } else {
	return -1;
    }
}
예제 #2
0
static void write_file( const char* filename, const ON_Point& point )
{
  ONX_Model model;

  ONX_Model_Object& mo = model.m_object_table.AppendNew();
  mo.m_object = &point;
  mo.m_bDeleteObject = false;

  int version = 4; // 2, 3 or 4
  model.Polish();
  model.Write( filename, version, "example_userdata.cpp file" );
}
static void write_file( const char* filename, const ON_Point& point )
{
  ONX_Model model;

  ONX_Model_Object& mo = model.m_object_table.AppendNew();
  mo.m_object = &point;
  mo.m_bDeleteObject = false;

  int version = 0; // version will be ON_BinaryArchive::CurrentArchiveVersion()

  model.Polish();
  model.Write( filename, version, "example_userdata.cpp file" );
}
//int main( int argc, const char *argv[] )
int main()
{
  ON::Begin();

  ON_TextLog error_log;

  // Before working through this example, you should understand
  // the example_write.cpp example.

  ON_Brep* brep = MakeTwistedCube(error_log);
  if ( !brep )
    return 1;

  ONX_Model model;

  ONX_Model_Object& mo = model.m_object_table.AppendNew();
  mo.m_object = brep;
  mo.m_bDeleteObject = true; // ~ONX_Model will delete brep
  brep = 0;
  mo.m_attributes.m_name = "Twisted b-rep";

  // OPTIONAL - change values from defaults
  model.m_properties.m_Notes.m_notes = "File created by OpenNURBS example_brep.cpp";
  model.m_properties.m_Notes.m_bVisible = true;

  model.m_properties.m_Application.m_application_name 
    = "OpenNURBS example_brep.cpp";
  model.m_properties.m_Application.m_application_URL 
    = "http://www.opennurbs.org";
  model.m_properties.m_Application.m_application_details 
    = "OpenNURBS example showing how to create and write a simple b-rep";


  int version = 0; // version will be ON_BinaryArchive::CurrentArchiveVersion()
  model.Polish();
  const char* filename = "my_brep.3dm";
  bool rc = model.Write( filename, 
               version,
               __FILE__ " example_brep.cpp " __DATE__,
               &error_log
               );

  if (rc)
    printf("Wrote %s.\n",filename);
  else
    printf("Errors writing %s.\n",filename);

  ON::End();

  return 0;
}
static void read_file( const char* filename, ON_Object*& pObject )
{
  // see example_read.cpp for information about read 3dm files
  // This code will only read the file created by write_file().
  // This code should not be used as a model for reading general 3dm files.


  ONX_Model model;
  model.Read( filename );

  if ( model.m_object_table.Count() > 0 )
  {
    pObject = const_cast<ON_Object*>(model.m_object_table[0].m_object);
    model.m_object_table[0].m_object = 0; // so ~ONX_Model will not delete object
  }

}
예제 #6
0
파일: brep.cpp 프로젝트: cciechad/brlcad
/**
 *			R T _ B R E P _ E X P O R T 5
 */
int
rt_brep_export5(struct bu_external *ep, const struct rt_db_internal *ip, double local2mm, const struct db_i *dbip)
{
    TRACE1("rt_brep_export5");
    struct rt_brep_internal* bi;

    RT_CK_DB_INTERNAL(ip);
    if (ip->idb_type != ID_BREP) return -1;
    bi = (struct rt_brep_internal*)ip->idb_ptr;
    RT_BREP_CK_MAGIC(bi);

    BU_INIT_EXTERNAL(ep);

    RT_MemoryArchive archive;
    /* XXX what to do about the version */
    ONX_Model model;

    {
	ON_Layer default_layer;
	default_layer.SetLayerIndex(0);
	default_layer.SetLayerName("Default");
	model.m_layer_table.Reserve(1);
	model.m_layer_table.Append(default_layer);
    }

    ONX_Model_Object& mo = model.m_object_table.AppendNew();
    mo.m_object = bi->brep;
    mo.m_attributes.m_layer_index = 0;
    mo.m_attributes.m_name = "brep";
    mo.m_attributes.m_uuid = ON_opennurbs4_id;

    model.m_properties.m_RevisionHistory.NewRevision();
    model.m_properties.m_Application.m_application_name = "BRL-CAD B-Rep primitive";

    model.Polish();
    ON_TextLog err(stderr);
    bool ok = model.Write(archive, 4, "export5", &err);
    if (ok) {
	ep->ext_nbytes = archive.Size();
	ep->ext_buf = archive.CreateCopy();
	return 0;
    } else {
	return -1;
    }
}
예제 #7
0
static ON_ModelGeometryComponent read_file( 
  const wchar_t* filename,
  bool bManageGeometryObject
)
{
  // see example_read.cpp for information about read 3dm files
  // This code will only read the file created by write_file().
  // This code should not be used as a model for reading general 3dm files.
  
  ONX_Model model;
  ON_BinaryFile archive(ON::archive_mode::read3dm, filename);
  if (!model.IncrementalReadBegin(archive, true, 0, nullptr))
    return ON_ModelGeometryComponent::Unset;

  ON_ModelComponentReference mcr;
  if (!model.IncrementalReadModelGeometry(archive, true, bManageGeometryObject, true, 0, mcr))
    return ON_ModelGeometryComponent::Unset;

  const ON_ModelGeometryComponent* mgc = ON_ModelGeometryComponent::Cast(mcr.ModelComponent());
  if (nullptr == mgc)
    return ON_ModelGeometryComponent::Unset;

  return *mgc;
}
예제 #8
0
int
main (int argc, char *argv[])
{
  std::string pcd_file, file_3dm;

  if (argc < 3)
  {
    printf ("\nUsage: pcl_example_nurbs_fitting_surface pcd<PointXYZ>-in-file 3dm-out-file\n\n");
    exit (0);
  }
  pcd_file = argv[1];
  file_3dm = argv[2];

  pcl::visualization::PCLVisualizer viewer ("B-spline surface fitting");
  viewer.setSize (800, 600);

  // ############################################################################
  // load point cloud

  printf ("  loading %s\n", pcd_file.c_str ());
  pcl::PointCloud<Point>::Ptr cloud (new pcl::PointCloud<Point>);
  pcl::PCLPointCloud2 cloud2;
  pcl::on_nurbs::NurbsDataSurface data;

  if (pcl::io::loadPCDFile (pcd_file, cloud2) == -1)
    throw std::runtime_error ("  PCD file not found.");

  fromPCLPointCloud2 (cloud2, *cloud);
  PointCloud2Vector3d (cloud, data.interior);
  pcl::visualization::PointCloudColorHandlerCustom<Point> handler (cloud, 0, 255, 0);
  viewer.addPointCloud<Point> (cloud, handler, "cloud_cylinder");
  printf ("  %lu points in data set\n", cloud->size ());

  // ############################################################################
  // fit B-spline surface

  // parameters
  unsigned order (3);
  unsigned refinement (5);
  unsigned iterations (10);
  unsigned mesh_resolution (256);

  pcl::on_nurbs::FittingSurface::Parameter params;
  params.interior_smoothness = 0.2;
  params.interior_weight = 1.0;
  params.boundary_smoothness = 0.2;
  params.boundary_weight = 0.0;

  // initialize
  printf ("  surface fitting ...\n");
  ON_NurbsSurface nurbs = pcl::on_nurbs::FittingSurface::initNurbsPCABoundingBox (order, &data);
  pcl::on_nurbs::FittingSurface fit (&data, nurbs);
  //  fit.setQuiet (false); // enable/disable debug output

  // mesh for visualization
  pcl::PolygonMesh mesh;
  pcl::PointCloud<pcl::PointXYZ>::Ptr mesh_cloud (new pcl::PointCloud<pcl::PointXYZ>);
  std::vector<pcl::Vertices> mesh_vertices;
  std::string mesh_id = "mesh_nurbs";
  pcl::on_nurbs::Triangulation::convertSurface2PolygonMesh (fit.m_nurbs, mesh, mesh_resolution);
  viewer.addPolygonMesh (mesh, mesh_id);

  // surface refinement
  for (unsigned i = 0; i < refinement; i++)
  {
    fit.refine (0);
    fit.refine (1);
    fit.assemble (params);
    fit.solve ();
    pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution);
    viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id);
    viewer.spinOnce ();
  }

  // surface fitting with final refinement level
  for (unsigned i = 0; i < iterations; i++)
  {
    fit.assemble (params);
    fit.solve ();
    pcl::on_nurbs::Triangulation::convertSurface2Vertices (fit.m_nurbs, mesh_cloud, mesh_vertices, mesh_resolution);
    viewer.updatePolygonMesh<pcl::PointXYZ> (mesh_cloud, mesh_vertices, mesh_id);
    viewer.spinOnce ();
  }

  // ############################################################################
  // fit B-spline curve

  // parameters
  pcl::on_nurbs::FittingCurve2dAPDM::FitParameter curve_params;
  curve_params.addCPsAccuracy = 5e-2;
  curve_params.addCPsIteration = 3;
  curve_params.maxCPs = 200;
  curve_params.accuracy = 1e-3;
  curve_params.iterations = 100;

  curve_params.param.closest_point_resolution = 0;
  curve_params.param.closest_point_weight = 1.0;
  curve_params.param.closest_point_sigma2 = 0.1;
  curve_params.param.interior_sigma2 = 0.00001;
  curve_params.param.smooth_concavity = 1.0;
  curve_params.param.smoothness = 1.0;

  // initialisation (circular)
  printf ("  curve fitting ...\n");
  pcl::on_nurbs::NurbsDataCurve2d curve_data;
  curve_data.interior = data.interior_param;
  curve_data.interior_weight_function.push_back (true);
  ON_NurbsCurve curve_nurbs = pcl::on_nurbs::FittingCurve2dAPDM::initNurbsCurve2D (order, curve_data.interior);

  // curve fitting
  pcl::on_nurbs::FittingCurve2dASDM curve_fit (&curve_data, curve_nurbs);
  // curve_fit.setQuiet (false); // enable/disable debug output
  curve_fit.fitting (curve_params);
  visualizeCurve (curve_fit.m_nurbs, fit.m_nurbs, viewer);

  // ############################################################################
  // triangulation of trimmed surface

  printf ("  triangulate trimmed surface ...\n");
  viewer.removePolygonMesh (mesh_id);
  pcl::on_nurbs::Triangulation::convertTrimmedSurface2PolygonMesh (fit.m_nurbs, curve_fit.m_nurbs, mesh,
                                                                   mesh_resolution);
  viewer.addPolygonMesh (mesh, mesh_id);


  // save trimmed B-spline surface
  if ( fit.m_nurbs.IsValid() )
  {
    ONX_Model model;
    ONX_Model_Object& surf = model.m_object_table.AppendNew();
    surf.m_object = new ON_NurbsSurface(fit.m_nurbs);
    surf.m_bDeleteObject = true;
    surf.m_attributes.m_layer_index = 1;
    surf.m_attributes.m_name = "surface";

    ONX_Model_Object& curv = model.m_object_table.AppendNew();
    curv.m_object = new ON_NurbsCurve(curve_fit.m_nurbs);
    curv.m_bDeleteObject = true;
    curv.m_attributes.m_layer_index = 2;
    curv.m_attributes.m_name = "trimming curve";

    model.Write(file_3dm.c_str());
    printf("  model saved: %s\n", file_3dm.c_str());
  }

  printf ("  ... done.\n");

  viewer.spin ();
  return 0;
}
예제 #9
0
int main(int argc, const char *argv[])
{
  // If you are using OpenNURBS as a Windows DLL, then you MUST use
  // ON::OpenFile() to open the file.  If you are not using OpenNURBS
  // as a Windows DLL, then you may use either ON::OpenFile() or fopen()
  // to open the file.

  int argi;
  if (argc < 2)
  {
    Usage(argv[0]);
    return 0;
  }

  // Call once in your application to initialze opennurbs library
  ON::Begin();

  int version = 0; // write current Rhino file

                   // default dump is to stdout
  ON_TextLog dump_to_stdout;
  ON_TextLog* dump = &dump_to_stdout;

  ON_String input;
  ON_String output;
  ON_String logfile;

  for (argi = 1; argi < argc; argi++)
  {
    ON_String arg(argv[argi]);

    if (arg.Left(10).CompareOrdinal("--version=", true) == 0)
    {
      arg = arg.Mid(10);
      version = atoi(arg);
      continue;
    }

    if (arg.Left(2).CompareOrdinal("/v", true) == 0 || arg.Left(2).CompareOrdinal("-v", true) == 0)
    {
      argi++;
      const char* sversion = argv[argi];
      version = atoi(sversion);
      continue;
    }

    if (arg.Left(6).CompareOrdinal("--log=", true) == 0)
    {
      arg = arg.Mid(6);
      logfile = arg;
      continue;
    }

    if (input.IsEmpty())
    {
      input = arg;
      if (false == ON_FileStream::Is3dmFile(input, true))
      {
        input = ON_String::EmptyString;
        break;
      }
      continue;
    }

    if (output.IsEmpty())
    {
      output = arg;
      continue;
    }

    // Invalid command line parameter
    input = ON_String::EmptyString;
    output = ON_String::EmptyString;
    break;
  }

  if (input.IsEmpty() || output.IsEmpty())
  {
    Usage(argv[0]);
    return 1;
  }


  dump->Print("\nOpenNURBS Archive File:  %s\n", static_cast<const char*>(input) );

  // open file containing opennurbs archive
  FILE* archive_fp = ON_FileStream::Open3dmToRead(input);
  if (nullptr == archive_fp)
  {
    dump->Print("  Unable to open file.\n");
    return 1;
  }

  dump->PushIndent();

  // create achive object from file pointer
  ON_BinaryFile archive(ON::archive_mode::read3dm, archive_fp);

  // read the contents of the file into "model"
  ONX_Model model;
  bool rc = model.Read(archive, dump);
  // close the file
  ON::CloseFile(archive_fp);

  if (false == rc)
  {
    dump->Print("Errors during reading.\n");
    return 1;
  }

  if (HasErrorsOrWarnings(dump, "reading input file"))
    return 1;
  
  // print diagnostic
  dump->Print("Successfully read.\n");
  
  // Write file
  model.m_sStartSectionComments = "Converted by example_convert.exe";
  bool outrc = model.Write(output, version, dump);
  if (HasErrorsOrWarnings(dump, "writing output file"))
    return 1;
  
  if (outrc)
  {
    dump->Print("model.Write(%s) succeeded.\n", static_cast<const char*>(output));
    ONX_Model model2;
    if (model2.Read(output, dump))
    {
      dump->Print("model2.Read(%s) succeeded.\n", static_cast<const char*>(output));
      if (HasErrorsOrWarnings(dump, "verifying output file"))
        return 1;

      if (!logfile.IsEmpty())
      {
        FILE* fp = ON::OpenFile(logfile, "w");
        ON_TextLog log(fp);
        model2.Dump(log);
        ON::CloseFile(fp);
      }

    }
    else
    {
      dump->Print("model2.Read(%s) failed.\n", static_cast<const char*>(output));
    }

    dump->PopIndent();
  }

  // OPTIONAL: Call just before your application exits to clean
  //           up opennurbs class definition information.
  //           Opennurbs will not work correctly after ON::End()
  //           is called.
  ON::End();

  return 0;
}
예제 #10
0
int main( int argc, const char *argv[] )
{
    // If you are using OpenNURBS as a Windows DLL, then you MUST use
    // ON::OpenFile() to open the file.  If you are not using OpenNURBS
    // as a Windows DLL, then you may use either ON::OpenFile() or fopen()
    // to open the file.

    int argi;
    if ( argc < 2 )
    {
        printf("Syntax: %s [-out:outputfilename.txt] file1.3dm file2.3dm ...\n",argv[0] );
        return 0;
    }

    // Call once in your application to initialze opennurbs library
    ON::Begin();

    // default dump is to stdout
    ON_TextLog dump_to_stdout;
    ON_TextLog* dump = &dump_to_stdout;
    FILE* dump_fp = 0;

    ONX_Model model;

    for ( argi = 1; argi < argc; argi++ )
    {
        const char* arg = argv[argi];

        // check for -out or /out option
        if ( ( 0 == strncmp(arg,"-out:",5) || 0 == strncmp(arg,"/out:",5) )
                && arg[5] )
        {
            // change destination of dump file
            const char* sDumpFilename = arg+5;
            FILE* text_fp = ON::OpenFile(sDumpFilename,"w");
            if ( text_fp )
            {
                if ( dump_fp )
                {
                    delete dump;
                    ON::CloseFile(dump_fp);
                }
                dump_fp = text_fp;
                dump = new ON_TextLog(dump_fp);
            }
            continue;
        }

        const char* sFileName = arg;

        dump->Print("\nOpenNURBS Archive File:  %s\n", sFileName );

        // open file containing opennurbs archive
        FILE* archive_fp = ON::OpenFile( sFileName, "rb");
        if ( !archive_fp )
        {
            dump->Print("  Unable to open file.\n" );
            continue;
        }

        dump->PushIndent();

        // create achive object from file pointer
        ON_BinaryFile archive( ON::read3dm, archive_fp );

        // read the contents of the file into "model"
        bool rc = model.Read( archive, dump );

        // close the file
        ON::CloseFile( archive_fp );

        // print diagnostic
        if ( rc )
            dump->Print("Successfully read.\n");
        else
            dump->Print("Errors during reading.\n");

        // see if everything is in good shape
        if ( model.IsValid(dump) )
            dump->Print("Model is valid.\n");
        else
        {
            model.Polish();
            if ( model.IsValid() )
            {
                dump->Print("Model is valid after calling Polish().\n");
            }
            else
            {
                dump->Print("Model is not valid.\n");
            }
        }

        /*
        int oi = 14;
        if ( oi >=0 && oi < model.m_object_table.Count() )
        {
          dump->Print("m_object_table[%d].m_object:\n",oi);
          dump->PushIndent();
          model.m_object_table[oi].m_object->Dump(*dump);
          dump->PopIndent();
        }
        */

        int version = 0; // write current Rhino file

        ON_String outfile = sFileName;
        int len = outfile.Length() - 4;
        outfile.SetLength(len);
        outfile += "_roundtrip.3dm";
        bool outrc = model.Write( outfile, version, "roundtrip", dump );
        if ( outrc )
        {
            dump->Print("model.Write(%s) succeeded.\n",outfile.Array());
            ONX_Model model2;
            if ( model2.Read( outfile, dump ) )
            {
                dump->Print("model2.Read(%s) succeeded.\n",outfile.Array());
                if ( model2.IsValid(dump) )
                {
                    dump->Print("Model2 is valid.\n");
                }
                else
                {
                    dump->Print("Model2 is not valid.\n");
                }
                /*
                if ( oi >=0 && oi < model2.m_object_table.Count() )
                {
                  dump->Print("m_object_table[%d].m_object:\n",oi);
                  dump->PushIndent();
                  model2.m_object_table[oi].m_object->Dump(*dump);
                  dump->PopIndent();
                }
                */
            }
            else
            {
                dump->Print("model2.Read(%s) failed.\n",outfile.Array());
            }
        }
        else
            dump->Print("model.Write(%s) failed.\n",outfile.Array());

        // destroy this model
        model.Destroy();

        dump->PopIndent();
    }

    if ( dump_fp )
    {
        // close the text dump file
        delete dump;
        ON::CloseFile( dump_fp );
    }

    // OPTIONAL: Call just before your application exits to clean
    //           up opennurbs class definition information.
    //           Opennurbs will not work correctly after ON::End()
    //           is called.
    ON::End();

    return 0;
}
/*
Returns:
  True if .3dm file was successfully read into an ONX_Model class.
*/
static bool ReadFileHelper( 
  const wchar_t* sFileName,
  bool bVerboseTextDump,
  bool bChunkDump,
  ON_TextLog& dump
  )
{
  if ( bChunkDump )
  {
    return Dump3dmFileHelper(sFileName,dump);
  }

  ONX_Model model;

  dump.Print("\nOpenNURBS Archive File:  %ls\n", sFileName );

  // open file containing opennurbs archive
  FILE* archive_fp = ON::OpenFile( sFileName, L"rb");
  if ( !archive_fp ) 
  {
    dump.Print("  Unable to open file.\n" );
    return false;
  }

  dump.PushIndent();

  // create achive object from file pointer
  ON_BinaryFile archive( ON::read3dm, archive_fp );

  // read the contents of the file into "model"
  bool rc = model.Read( archive, &dump );

  // close the file
  ON::CloseFile( archive_fp );

  // print diagnostic
  if ( rc )
    dump.Print("Successfully read.\n");
  else
    dump.Print("Errors during reading.\n");

  // see if everything is in good shape
  if ( model.IsValid(&dump) )
  {
    dump.Print("Model is valid.\n");
  }
  else
  {
    dump.Print("Model is not valid.\n");
  }

  // create a text dump of the model
  if ( bVerboseTextDump )
  {
    dump.PushIndent();
    model.Dump(dump);
    dump.PopIndent();
  }

  // destroy this model
  model.Destroy();

  dump.PopIndent();

  return rc;
}
CRhinoCommand::result CCommandSampleImportMeshes::RunCommand( const CRhinoCommandContext& context )
{
  CWnd* pMainWnd = CWnd::FromHandle(RhinoApp().MainWnd());
  if (0 == pMainWnd)
    return CRhinoCommand::failure;
 
  CRhinoGetFileDialog gf;
  gf.SetScriptMode(context.IsInteractive() ? FALSE : TRUE);
  BOOL rc = gf.DisplayFileDialog(CRhinoGetFileDialog::open_rhino_only_dialog, 0, pMainWnd);
  if (!rc)
    return CRhinoCommand::cancel;
 
  ON_wString filename = gf.FileName();
  filename.TrimLeftAndRight();
  if (filename.IsEmpty())
    return CRhinoCommand::nothing;

  if (!CRhinoFileUtilities::FileExists(filename))
  {
    RhinoApp().Print(L"File not found\n");
    return CRhinoCommand::failure;
  }

  FILE* archive_fp = ON::OpenFile(filename, L"rb");
  if (0 == archive_fp)
  {
    RhinoApp().Print(L"Unable to open file\n");
    return CRhinoCommand::failure;
  }

  ON_BinaryFile archive(ON::read3dm, archive_fp);

  ONX_Model model;
  rc = model.Read(archive) ? TRUE : FALSE;

  ON::CloseFile( archive_fp );

  if (!rc)
  {
    RhinoApp().Print(L"Error reading file\n");
    return CRhinoCommand::failure;
  }

  int num_imported = 0;
  for (int i = 0; i < model.m_object_table.Count(); i++)
  {
    const ONX_Model_Object& model_object = model.m_object_table[i];
    const ON_Mesh* mesh = ON_Mesh::Cast(model_object.m_object);
    if (0 != mesh)
    {
      // CRhinoDoc::AddMeshObject makes a copy of the input mesh
      context.m_doc.AddMeshObject(*mesh);
      num_imported++;
    }
  }

  if (0 == num_imported)
    RhinoApp().Print(L"No meshes imported\n");
  else if (1 == num_imported)
    RhinoApp().Print(L"1 mesh imported\n");
  else
    RhinoApp().Print(L"%d meshes imported\n", num_imported);

  context.m_doc.Redraw();

  return CRhinoCommand::success;
}