/// <summary> /// calculates the tansform to convert models to metres and centre on the most populated region, includes reference models /// </summary> /// <returns></returns> private XbimMatrix3D GetGlobalModelTransform() { XbimRegion largest = _context.GetLargestRegion(); XbimRect3D bb = XbimRect3D.Empty; if (largest != null) bb = new XbimRect3D(largest.Centre, largest.Centre); foreach (var refModel in _context.Model.ReferencedModels) { XbimRegion r; Xbim3DModelContext refContext = new Xbim3DModelContext(refModel.Model); r = refContext.GetLargestRegion(); if (r != null) { if (bb.IsEmpty) bb = new XbimRect3D(r.Centre, r.Centre); else bb.Union(r.Centre); } } XbimPoint3D p = bb.Centroid(); var modelTranslation = new XbimVector3D(-p.X, -p.Y, -p.Z); double metreFactor = 1.0 / _context.Model.ModelFactors.OneMetre; return XbimMatrix3D.CreateTranslation(modelTranslation) * XbimMatrix3D.CreateScale(metreFactor); }
public static XbimMeshGeometry3D GetMesh(this XbimModel xbimModel, IEnumerable<IPersistIfcEntity> items, XbimMatrix3D wcsTransform) { var m = new XbimMeshGeometry3D(); if (xbimModel.GeometrySupportLevel == 1) { // this is what happens for version 1 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null) continue; var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { // todo: add guidance to the TransformBy method so that users can understand how to stop using it (it's marked absolete) geomData.TransformBy(wcsTransform); m.Add(geomData); // todo: what is the modelid value to be passed? } } } else { // this is what happens for version 2 of the engine // foreach (var item in items) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) continue; var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct) item) .Where( s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType) shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry) shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } } } return m; }
private void DoExport(object sender, RoutedEventArgs e) { var totExports = (ChkWexbim.IsChecked.HasValue && ChkWexbim.IsChecked.Value ? 1 : 0); if (totExports == 0) return; if (!Directory.Exists(TxtFolderName.Text)) { try { Directory.CreateDirectory(TxtFolderName.Text); } catch (Exception) { MessageBox.Show("Error creating directory. Select a different location."); return; } } Cursor = Cursors.Wait; if (ChkWexbim.IsChecked.HasValue && ChkWexbim.IsChecked.Value) { // file preparation // var wexbimFileName = GetExportName("wexbim"); try { using (var wexBimFile = new FileStream(wexbimFileName, FileMode.Create)) { using (var binaryWriter = new BinaryWriter(wexBimFile)) { try { var geomContext = new Xbim3DModelContext(_mainWindow.Model); geomContext.Write(binaryWriter); } finally { binaryWriter.Flush(); wexBimFile.Close(); } } } } catch (Exception ce) { if (CancelAfterNotification("Error exporting Wexbim file.", ce, totExports)) { Cursor = Cursors.Arrow; return; } } totExports--; } Cursor = Cursors.Arrow; Close(); }
public static void AddElements(this MeshGeometry3D m, IPersistIfcEntity item, XbimMatrix3D wcsTransform) { var fromModel = item.ModelOf as XbimModel; if (fromModel == null || !(item is IfcProduct)) return; switch (fromModel.GeometrySupportLevel) { case 2: var context = new Xbim3DModelContext(fromModel); var productShape = context.ShapeInstancesOf((IfcProduct) item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is IfcFeatureElement) { productShape = context.ShapeInstancesOf((IfcProduct) item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) return; foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType) shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry) shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } break; case 1: var xm3d = new XbimMeshGeometry3D(); var geomDataSet = fromModel.GetGeometryData(item.EntityLabel, XbimGeometryType.TriangulatedMesh); foreach (var geomData in geomDataSet) { var gd = geomData.TransformBy(wcsTransform); xm3d.Add(gd); } m.Add(xm3d); break; } }
private static void ExportGeometryData(string geometryFileName, Xbim3DModelContext m3DModelContext) { using (var geometryStream = new FileStream(geometryFileName, FileMode.Create)) { using (var bw = new BinaryWriter(geometryStream)) { m3DModelContext.Write(bw); bw.Close(); geometryStream.Close(); } } }
public XbimModelPositioning(XbimModel model) { _model = model; Context = new Xbim3DModelContext(model); var supportLevel = model.GeometrySupportLevel; switch (supportLevel) { case 1: LargestRegion = GetLargestRegion(model); break; case 2: LargestRegion = Context.GetLargestRegion(); break; } }
public override void Calculate() { if (InputPorts[0].Data == null) { return; } var modelInfo = InputPorts[0].Data as ModelInfo; if (modelInfo == null) { return; } var model = modelController.GetModel(modelInfo.modelId) as IfcModel; if (model == null) { return; } // Get the model content xModel = model.GetModel(); context = model.xModelContext; _elements = model.GetAllElements(); // Write a Property for each element var propertySet = _control.PropertySetTextBox.Text; var property = _control.PropertyTextBox.Text; // foreach (var item in _elements) // { // (item as IfcProduct).PropertySets.FirstOrDefault(). // } foreach (var element in _elements) { using (var txn = xModel.BeginTransaction("Add some Properties Wall")) { CreateSimpleProperty(xModel, element); txn.Commit(); } } }
public void SimpleIfcElementSignatureTest() { using (var model = new XbimModel()) { model.CreateFrom("Standard Classroom CIC 6.ifc", null, null, true); var geomContext = new Xbim3DModelContext(model); geomContext.CreateContext(XbimGeometryType.PolyhedronBinary); var summary = new IfcElementSignatureSummary(); foreach (var elem in model.Instances.OfType <IfcElement>()) { var signature = new IfcElementSignature(elem, geomContext); summary.Add(signature); Debug.WriteLine(signature.ToCSV()); } Debug.WriteLine(summary.ToString()); } }
private void ExportGeometry(ZipArchive zip, IfcStore model) { var context = new Xbim3DModelContext(model); context.CreateContext(); var entity = zip.CreateEntry("api/model.wexbim"); using (var memory = new MemoryStream()) using (var w = new BinaryWriter(memory)) using (var wexbim = entity.Open()) { model.SaveAsWexBim(w); memory.Seek(0, SeekOrigin.Begin); memory.CopyTo(wexbim); wexbim.Close(); } }
private static void TestForClassificationOfIfcFeatureElements(Xbim3DModelContext context) { var excludedTypes = new HashSet <short> { IfcMetaData.IfcType(typeof(IfcFeatureElement)).TypeId, IfcMetaData.IfcType(typeof(IfcOpeningElement)).TypeId, IfcMetaData.IfcType(typeof(IfcProjectionElement)).TypeId }; var shapeInstances = context.ShapeInstances().Where(s => excludedTypes.Contains(s.IfcTypeId) && // ifcfeatures s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsOnly); // that are not classified as OpeningsAndAdditionsOnly Assert.IsFalse(shapeInstances.Any(), "Should not find any shapes of with this classification of typeid and representationType."); }
static void Main() { string path = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName; string fileName = path + "//qhzf.ifc"; //this can be either IFC2x3 or IFC4 IfcStore model = IfcStore.Open(fileName); var context = new Xbim3DModelContext(model); context.CreateContext(); PropertyExtract start = new PropertyExtract(model, context); string properties = JsonConvert.SerializeObject(start.GetRelContains()); //start.GetRelContains(); Console.WriteLine(properties); Console.ReadKey(); }
public static int Main(string[] args) { Log.Logger = new LoggerConfiguration() .Enrich.FromLogContext() .WriteTo.ColoredConsole() .CreateLogger(); var lf = new LoggerFactory().AddSerilog(); var log = lf.CreateLogger("WexbimCreation"); log.LogInformation("Creating wexBIM file from IFC model."); // set up xBIM logging. It will use your providers. XbimLogging.LoggerFactory = lf; //const string fileName = @"SampleHouse.ifc"; string fileName = GetInputFilePath(args); if (fileName == null) { log.LogError("You must specify an input file."); return(-1); } log.LogInformation($"File size: {new FileInfo(fileName).Length / 1e6}MB"); IfcStore.ModelProviderFactory.UseHeuristicModelProvider(); using (var model = IfcStore.Open(fileName, null, -1)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexBimFilename = Path.ChangeExtension(fileName, "wexbim"); using (var wexBimFile = File.Create(wexBimFilename)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBimFile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBimFile.Close(); } } return(0); }
private static Task <Stream> ConvertIfcFileToWexbim(Stream ifcFileStream, Xbim.Common.Step21.IfcSchemaVersion ifcSchemaVersion) { return(Task.Run <Stream>(() => { using (var model = IfcStore.Open(ifcFileStream, Xbim.IO.IfcStorageType.Ifc, ifcSchemaVersion, XbimModelType.MemoryModel)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var memStream = new MemoryStream(); using (var wexBimBinaryWriter = new BinaryWriter(memStream, Encoding.Default, true)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } memStream.Position = 0; return memStream; } })); }
public void GetGeometryFromXbimModel_IFC4(MeshGeometry3D m, IPersistEntity item, XbimMatrix3D wcsTransform) { if (item.Model == null || !(item is Xbim.Ifc4.Kernel.IfcProduct)) { return; } var context = new Xbim3DModelContext(item.Model); var productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); if (!productShape.Any() && item is Xbim.Ifc4.Interfaces.IIfcFeatureElement) { productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item) .Where( s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); } if (!productShape.Any()) { return; } foreach (var shapeInstance in productShape) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: m.Read(shapeGeom.ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; case XbimGeometryType.Polyhedron: m.Read(((XbimShapeGeometry)shapeGeom).ShapeData, XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform)); break; } } }
public void LargeCoordinatesDisplacementTest() { using (var m = new MemoryModel(new Ifc2x3.EntityFactoryIfc2x3())) { m.LoadStep21("LargeTriangulatedCoordinates.ifc"); var c = new Xbim3DModelContext(m); c.CreateContext(null, false); using (var store = m.GeometryStore.BeginRead()) { var product = m.Instances.FirstOrDefault <IIfcBuildingElementProxy>(); Assert.IsNotNull(product.Representation); var instances = store.ShapeInstancesOfEntity(product); Assert.AreEqual(1, instances.Count()); var instance = instances.First(); var geometry = store.ShapeGeometryOfInstance(instance); // this should be a large displacement var transform = instance.Transformation; var length = transform.Translation.Length; Assert.IsTrue(length > 6200000); // geometry thould be in small numbers var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData); var br = new BinaryReader(ms); var tr = br.ReadShapeTriangulation(); var point = tr.Vertices.FirstOrDefault(); Assert.IsTrue(point.X < 1000); Assert.IsTrue(point.Y < 1000); Assert.IsTrue(point.Z < 1000); // when transformation is applied to the geometry it should be large tr = tr.Transform(transform); point = tr.Vertices.FirstOrDefault(); Assert.IsTrue(point.X > 300000); Assert.IsTrue(point.Y > 6200000); } } }
public void ConverIfcToWexBim() { const string ifcFileFullName = @"Lakeside_Restaurant.ifc"; var fileName = Path.GetFileName(ifcFileFullName); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var workingDir = Directory.GetCurrentDirectory(); var coreFileName = Path.Combine(workingDir, fileNameWithoutExtension); var wexBimFileName = Path.ChangeExtension(coreFileName, "wexbim"); var xbimFile = Path.ChangeExtension(coreFileName, "xbim"); try { using (var wexBimFile = new FileStream(wexBimFileName, FileMode.Create)) { using (var binaryWriter = new BinaryWriter(wexBimFile)) { using (var model = new XbimModel()) { try { model.CreateFrom(ifcFileFullName, xbimFile, null, true); var geomContext = new Xbim3DModelContext(model); geomContext.CreateContext(XbimGeometryType.PolyhedronBinary); geomContext.Write(binaryWriter); } finally { model.Close(); binaryWriter.Flush(); wexBimFile.Close(); } } } } } catch (Exception e) { Assert.Fail("Failed to process " + ifcFileFullName + " - " + e.Message); } }
public static void ToWexBim(string filePath) { using (var model = IfcStore.Open(filePath)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexBimFilename = Path.ChangeExtension(filePath, "wexBIM"); using (var wexBiMfile = File.Create(wexBimFilename)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } } }
public void SaveAs(string filePath, Extension extension) { switch (extension) { case Extension.Ifc: model.SaveAs(filePath, IfcStorageType.Ifc); break; case Extension.IfcXml: model.SaveAs(filePath, IfcStorageType.IfcXml); break; case Extension.IfcZip: model.SaveAs(filePath, IfcStorageType.IfcZip); break; case Extension.WexBim: // create wexBim file using (var model = IfcStore.Open(filePath)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexBimFilename = Path.ChangeExtension(filePath, "wexBIM"); using (var wexBiMfile = File.Create(wexBimFilename)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } } break; default: break; } }
public static void CreateWEXFileFromIFCModel(string IFCModelName, string DestinationPath) { string fileName = "C:\\Users\\zno\\source\\repos\\xbimDemo\\xbimDemo\\" + IFCModelName; using (var model = IfcStore.Open(fileName)) { var context = new Xbim3DModelContext(model); context.CreateContext(); using (var wexBiMfile = File.Create(DestinationPath)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } } }
public async Task <Stream> ConvertIfcToWexBimAsync(IfcStore ifcStore) { MemoryStream memStream = new MemoryStream(); try{ var context = new Xbim3DModelContext(ifcStore); context.CreateContext(); using (var wexBimBinaryWriter = new BinaryWriter(memStream, Encoding.Default, true)) { ifcStore.SaveAsWexBim(wexBimBinaryWriter); } memStream.Position = 0; } catch (Exception exception) { Console.WriteLine(exception.Message); } return(memStream); }
//Needed Geometry to test, but Steve's comment on "need to resolve generate geometry" may see GenerateGeometry change private void GenerateGeometry(COBieContext context) { //now convert the geometry var model = context.Model; var total = (int)model.Instances.CountOf <IfcProduct>(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { context.UpdateStatus("Creating Geometry File", total, (total * percentProgress / 100)); }; var m3D = new Xbim3DModelContext(model); try { m3D.CreateContext(progDelegate: progDelegate); } catch (Exception ce) { context.UpdateStatus("Error compiling geometry\n" + ce.Message, total, 100); } }
public void ConverIfcToWexBim() { const string ifcFileFullName = @"Lakeside_Restaurant.ifc"; var fileName = Path.GetFileName(ifcFileFullName); var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var workingDir = Directory.GetCurrentDirectory(); var coreFileName = Path.Combine(workingDir, fileNameWithoutExtension); var wexBimFileName = Path.ChangeExtension(coreFileName, "wexbim"); var xbimFile = Path.ChangeExtension(coreFileName, "xbim"); try { using (var wexBimFile = new FileStream(wexBimFileName, FileMode.Create)) { using (var binaryWriter = new BinaryWriter(wexBimFile)) { using (var model = new XbimModel()) { try { model.CreateFrom(ifcFileFullName, xbimFile, null, true); var geomContext = new Xbim3DModelContext(model); geomContext.CreateContext(XbimGeometryType.PolyhedronBinary); geomContext.Write(binaryWriter); } finally { model.Close(); binaryWriter.Flush(); wexBimFile.Close(); } } } } } catch (Exception e) { Assert.Fail("Failed to process " + ifcFileFullName + " - " + e.Message); } }
/// <summary> /// Get Style of each Item /// /// </summary> /// <param name="item"></param> /// <returns></returns> public Material GetStyleFromXbimModel_IFC2x3(Xbim.Ifc2x3.Kernel.IfcProduct item, double opacity = 1) { var context = new Xbim3DModelContext(item.Model); var productShape = context.ShapeInstancesOf((Xbim.Ifc4.Interfaces.IIfcProduct)item) .Where(s => s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsExcluded) .ToList(); Material wpfMaterial = null; if (productShape.Count > 0) { wpfMaterial = GetWpfMaterial(item.Model, productShape[0].StyleLabel); } else { wpfMaterial = GetWpfMaterial(item.Model, 0); } ((System.Windows.Media.Media3D.DiffuseMaterial)wpfMaterial).Brush.Opacity = opacity; return(wpfMaterial); }
protected void ConvertIFCtoWEXBIM(string filePath) { var IfcTestFile = filePath; using (var model = IfcStore.Open(IfcTestFile)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexBimFilename = Path.ChangeExtension(IfcTestFile, "wexbim"); using (var wexBiMfile = File.Create(wexBimFilename)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } } }
public static void Main() { const string fileName = "SampleHouse.ifc"; using (var model = IfcStore.Open(fileName, null, -1)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexBimFilename = Path.ChangeExtension(fileName, "wexbim"); using (var wexBimFile = File.Create(wexBimFilename)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBimFile)) { model.SaveAsWexBim(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBimFile.Close(); } } }
static void Main(string[] args) { const string modelFile = @"App_Data\4walls1floorSite.ifc"; using (var model = IfcStore.Open(modelFile)) { var context = new Xbim3DModelContext(model); context.CreateContext(); var wexbimFilename = Path.ChangeExtension(modelFile, "wexbim"); using (var wexbimFile = File.Create(wexbimFilename)) { using (var wexbimWriter = new BinaryWriter(wexbimFile)) { model.SaveAsWexBim(wexbimWriter); wexbimWriter.Close(); } wexbimFile.Close(); } } }
public override void Calculate() { if (InputPorts[0].Data == null) { return; } var modelInfo = InputPorts[0].Data as ModelInfo; if (modelInfo == null) { return; } var model = modelController.GetModel(modelInfo.modelId) as IfcModel; if (model == null) { return; } // Get the model content xModel = model.GetModel(); context = model.xModelContext; var storeys = xModel.Instances.OfType <IIfcBuildingStorey>(); if (storeys.Count() == 0) { return; } DataContext = this; pedSimNodeControl.storeyComboBox.ItemsSource = storeys; pedSimNodeControl.storeyComboBox.DisplayMemberPath = "FriendlyName"; // INIT THE SIMULATION InitSimulation(); }
private static void getgeometry(XbimShapeInstance shape, Xbim3DModelContext m_context) { XbimShapeTriangulation mesh = null; var geometry = m_context.ShapeGeometry(shape); //Console.WriteLine("====" + geometry.GetType()); Console.WriteLine($"{"\n"}{GetIndent(11)}{"--Geometry Type: " + geometry.Format}"); var ms = new MemoryStream(((IXbimShapeGeometryData)geometry).ShapeData); var br = new BinaryReader(ms); mesh = br.ReadShapeTriangulation(); mesh = mesh.Transform(((XbimShapeInstance)shape).Transformation); var facesfound = mesh.Faces.ToList(); Console.WriteLine($"{"\n"}{GetIndent(11)}{" -----No. of faces on the shape #" + shape.IfcProductLabel + ": " + facesfound.Count()}"); foreach (XbimFaceTriangulation f in facesfound) { Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Triangle count on face: " + f.GetType() + " :mesh is " + f.TriangleCount}"); //foreach (var fi in f.Indices) //{ // Console.WriteLine($"{GetIndent(13)}{" -> " + fi}"); //} composetrianglesets(f, mesh); } //Console.WriteLine($"{"\n"}{GetIndent(13)}{" -----Vertices of the shape: #" + shape.IfcProductLabel}"); //foreach (var v in mesh.Vertices.ToList()) //{ // Console.WriteLine($"{GetIndent(13)}{" --vertex_" + mesh.Vertices.ToList().IndexOf(v) + " : " + Math.Round((double)v.X, 2) + " | " + Math.Round((double)v.Y, 2) + " | " + Math.Round((double)v.Z, 2)}"); //} Console.WriteLine("\n"); }
public void BindUi(IXbimXplorerPluginMasterWindow mainWindow) { _parentWindow = mainWindow; SetBinding(ModelProperty, new Binding()); ScriptingControl.OnModelChangedByScript += delegate(object o, ModelChangedEventArgs arg) { ModelProperty = null; var m3D = new Xbim3DModelContext(arg.NewModel); m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false); Model = arg.NewModel; // todo: Fire Update request of model property (is it needed?) // ModelProvider.Refresh(); }; ScriptingControl.OnScriptParsed += delegate { // todo: Fire Update request to parent window // GroupControl.Regenerate(); // SpatialControl.Regenerate(); }; }
/// <summary> /// Validates all data and creates model. /// Provide a "XbimModel model = DataContext as XbimModel;" /// </summary> /// <returns>Returns XbimReferencedModel == null </returns> public bool TryBuild(XbimModel model) { //it's already build, so no need to recreate it if (ReferencedModel != null) { return(true); } if (string.IsNullOrWhiteSpace(Name)) { return(false); } else { string ext = System.IO.Path.GetExtension(Name).ToLowerInvariant(); using (XbimModel refM = new XbimModel()) { if (ext != ".xbim") { refM.CreateFrom(Name, null, null, true); var m3D = new Xbim3DModelContext(refM); m3D.CreateContext(); Name = System.IO.Path.ChangeExtension(Name, "xbim"); } } _xbimReferencedModel = model.AddModelReference(Name, OrganisationName, OrganisationRole); } if (_xbimReferencedModel != null) { //refresh all OnPropertyChanged("Identifier"); OnPropertyChanged("Name"); OnPropertyChanged("OrganisationName"); OnPropertyChanged("OrganisationRole"); } return(ReferencedModel != null); }
/// <summary> /// Validates all data and creates model. /// </summary> /// <returns>Returns XbimReferencedModel == null </returns> public bool TryBuildAndAddTo(IfcStore destinationFederatedModel) { //it's already build, so no need to recreate it if (ReferencedModel != null) { return(true); } if (string.IsNullOrWhiteSpace(Name)) { return(false); } _xbimReferencedModel = destinationFederatedModel.AddModelReference(Name, OrganisationName, OrganisationRole); if (_xbimReferencedModel.Model.GeometryStore.IsEmpty) { var m3D = new Xbim3DModelContext(_xbimReferencedModel.Model); m3D.CreateContext(); } //var tmpModel = IfcStore.Open(Name); //if (tmpModel.GeometryStore.IsEmpty) //{ // var m3D = new Xbim3DModelContext(tmpModel); // m3D.CreateContext(); //} if (_xbimReferencedModel == null) { return(ReferencedModel != null); } //refresh all OnPropertyChanged("Identifier"); OnPropertyChanged("Name"); OnPropertyChanged("OrganisationName"); OnPropertyChanged("OrganisationRole"); return(ReferencedModel != null); }
/// <summary> /// Validates all data and creates model. /// Provide a "XbimModel model = DataContext as XbimModel;" /// </summary> /// <returns>Returns XbimReferencedModel == null </returns> public bool TryBuild(XbimModel model) { //it's already build, so no need to recreate it if (ReferencedModel != null) { return(true); } if (string.IsNullOrWhiteSpace(Name)) { return(false); } var ext = Path.GetExtension(Name).ToLowerInvariant(); using (var refM = new XbimModel()) { var xbimName = Path.ChangeExtension(Name, "xbim"); if (ext != ".xbim" && !File.Exists(xbimName)) { refM.CreateFrom(Name, null, null, true); var m3D = new Xbim3DModelContext(refM); m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false); Name = Path.ChangeExtension(Name, "xbim"); } Name = xbimName; } _xbimReferencedModel = model.AddModelReference(Name, OrganisationName, OrganisationRole); if (_xbimReferencedModel == null) { return(ReferencedModel != null); } //refresh all OnPropertyChanged("Identifier"); OnPropertyChanged("Name"); OnPropertyChanged("OrganisationName"); OnPropertyChanged("OrganisationRole"); return(ReferencedModel != null); }
public void BindUi(IXbimXplorerPluginMasterWindow mainWindow) { _parentWindow = mainWindow; SetBinding(ModelProperty, new Binding()); ScriptingControl.OnModelChangedByScript += delegate(object o, ModelChangedEventArgs arg) { ModelProperty = null; var m3D = new Xbim3DModelContext(arg.NewModel); m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false); Model = arg.NewModel; // todo: Fire Update request of model property (is it needed?) // ModelProvider.Refresh(); }; ScriptingControl.OnScriptParsed += delegate { // todo: Fire Update request to parent window // GroupControl.Regenerate(); // SpatialControl.Regenerate(); }; }
static void Main(string[] args) { const string file = @"4walls1floorSite.ifc"; var model = IfcStore.Open(file); var context = new Xbim3DModelContext(model); context.CreateContext(); var instances = context.ShapeInstances(); foreach (var instance in instances) { var geometry = context.ShapeGeometry(instance); var data = ((IXbimShapeGeometryData)geometry).ShapeData; using (var stream = new MemoryStream(data)) { using (var reader = new BinaryReader(stream)) { var mesh = reader.ReadShapeTriangulation(); } } } }
public static XbimGeometryHandleCollection GetApproximateGeometryHandles(this Xbim3DModelContext context, IEnumerable <int> loadLabels = null) { var retCollection = new XbimGeometryHandleCollection(); if (loadLabels != null) { foreach (var shapeInstance in context.ShapeInstances() .Where(x => loadLabels.Contains(x.InstanceLabel))) { retCollection.Add( new XbimGeometryHandle( shapeInstance.InstanceLabel, XbimGeometryType.TriangulatedMesh, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId, shapeInstance.StyleLabel ) ); } } else { foreach (var shapeInstance in context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded)) { retCollection.Add( new XbimGeometryHandle( shapeInstance.InstanceLabel, XbimGeometryType.TriangulatedMesh, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId, shapeInstance.StyleLabel ) ); } } return(retCollection); }
public string CreateOBJFile(IfcStore model, string projectId) { this.model = model; IfcBuilding ifcBuilding = model.Instances.OfType <IfcBuilding>().FirstOrDefault(); if (ifcBuilding != null) { building = new XPreviewBuilding(ifcBuilding); XPreviewElement.vertexCount = 1; var context = new Xbim3DModelContext(model); context.CreateContext(); string objfile = building.GetPreviewObjGroup(context); string path = GetFolderPath(projectId) + "pegasus.obj"; System.IO.File.WriteAllText(path, objfile); // Create the material template library by scanning for unit colors string mtlfile = string.Empty; foreach (UnitParameters unit in parameters.UnitDefinitions) { string unitType = unit.UnitType.Replace(' ', '_'); mtlfile += "newmtl " + unit.UnitType.Replace(' ', '_') + Environment.NewLine; System.Drawing.Color color1 = System.Drawing.ColorTranslator.FromHtml(unit.Color); mtlfile += "kd " + color1.R / 255.0 + ", " + color1.G / 255.0 + ", " + color1.B / 255.0 + Environment.NewLine; } mtlfile += "newmtl corridor" + Environment.NewLine; System.Drawing.Color color = System.Drawing.ColorTranslator.FromHtml("#afafaf"); mtlfile += "kd " + color.R / 255.0 + ", " + color.G / 255.0 + ", " + color.B / 255.0 + Environment.NewLine; System.IO.File.WriteAllText(GetFolderPath(projectId) + "pegasus.mtl", mtlfile); model.Close(); return(path); } else { return(string.Empty); } }
public void GeometryVersionUpgradeTest() { using (var model = new XbimModel()) { // start afresh model.Open(@"GConv\Monolith_v10.xBIM", XbimDBAccess.Exclusive); Assert.AreEqual(1, model.GeometrySupportLevel); // now remove the existing geometry model.DeleteGeometryCache(); Assert.AreEqual(0, model.GeometrySupportLevel); // now create the geometry back model.EnsureGeometryTables(); // update the database structure first var context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary); // then populate it // final tests Assert.AreEqual(2, model.GeometrySupportLevel); // and tidy up model.Close(); } }
public void GeometryVersionUpgradeTest() { using (var model = new XbimModel()) { // start afresh model.Open(@"GConv\Monolith_v10.xBIM", XbimDBAccess.Exclusive); Assert.AreEqual(1, model.GeometrySupportLevel); // now remove the existing geometry model.DeleteGeometryCache(); Assert.AreEqual(0, model.GeometrySupportLevel); // now create the geometry back model.EnsureGeometryTables(); // update the database structure first var context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary); // then populate it // final tests Assert.AreEqual(2, model.GeometrySupportLevel); // and tidy up model.Close(); } }
/// <summary> /// Reads the geometry from model if empty. /// </summary> /// <param name="model">The model</param> /// <param name="progressing">The progress emitter</param> /// <param name="forceUpdate">Whether to force an update of geometry store anyway</param> /// <returns>The given udpated state or a new state</returns> public IEnumerable <IIfcRepresentationContext> ReadGeometryStore(IModel model, CancelableProgressing progressing, bool forceUpdate = false) { // Use Xbim Model Context for geometry creation if (forceUpdate || (model.GeometryStore?.IsEmpty ?? false)) { progressing?.NotifyProgressEstimateUpdate(100); ReportProgressDelegate progressDelegate = (percent, userState) => { progressing?.State.UpdateDone(percent, userState.ToString()); progressing?.NotifyOnProgressChange(); }; var context = new Xbim3DModelContext(model, "model", null, Logger); context.CreateContext(progressDelegate, false); return(context.Contexts); } else { return(model.GeometryStore.BeginRead().ContextIds .Select(label => model.Instances[label]) .Cast <IIfcRepresentationContext>()); } }
public void TestShapeGeometriesEnumerability() { using (var model = new XbimModel()) { model.Open(@"EsentTestFiles\TwoWalls.xbim"); var geomContext = new Xbim3DModelContext(model); var lst = new Dictionary<int, int>(); // ShapeGeometries does not have duplicates... lst.Clear(); foreach (var g1 in geomContext.ShapeGeometries()) { lst.Add(g1.ShapeLabel, g1.IfcShapeLabel); } // ... so it shouldn't even through the ToArray() function. lst.Clear(); foreach (var g1 in geomContext.ShapeGeometries().ToArray()) { lst.Add(g1.ShapeLabel, g1.IfcShapeLabel); } } }
// NOTE: I don't recommend you do this under a web server due to the use of unmanaged code and the fact the operation is very expensive in terms of resources private void BuildGeometry(XbimModel model, string geometryFileName) { if (Cached(geometryFileName)) { return; } var m3DModelContext = new Xbim3DModelContext(model); m3DModelContext.CreateContext(XbimGeometryType.PolyhedronBinary); ExportGeometryData(geometryFileName, m3DModelContext); }
public void ReadAndWriteWexBimFile() { using (var m = new XbimModel()) { m.CreateFrom("SolidTestFiles\\19 - TwoProxy.ifc", null, null, true, true); var m3D = new Xbim3DModelContext(m); m3D.CreateContext(XbimGeometryType.PolyhedronBinary); using (var bw = new BinaryWriter(new FileStream("test.wexBIM", FileMode.Create))) { m3D.Write(bw); bw.Close(); } using (var fs = new FileStream(@"test.wexBIM", FileMode.Open, FileAccess.Read)) { using (var br = new BinaryReader(fs)) { var magicNumber = br.ReadInt32(); var version = br.ReadByte(); var shapeCount = br.ReadInt32(); var vertexCount = br.ReadInt32(); var triangleCount = br.ReadInt32(); var matrixCount = br.ReadInt32(); var productCount = br.ReadInt32(); var styleCount = br.ReadInt32(); var meter = br.ReadSingle(); Assert.IsTrue(meter>0); var regionCount = br.ReadInt16(); for (int i = 0; i < regionCount; i++) { var population = br.ReadInt32(); var centreX = br.ReadSingle(); var centreY = br.ReadSingle(); var centreZ = br.ReadSingle(); var boundsBytes = br.ReadBytes(6 * sizeof(float)); var modelBounds = XbimRect3D.FromArray(boundsBytes); } for (int i = 0; i < styleCount; i++) { var styleId = br.ReadInt32(); var red = br.ReadSingle(); var green = br.ReadSingle(); var blue = br.ReadSingle(); var alpha = br.ReadSingle(); } for (int i = 0; i < productCount ; i++) { var productLabel = br.ReadInt32(); var productType = br.ReadInt16(); var boxBytes = br.ReadBytes(6 * sizeof(float)); XbimRect3D bb = XbimRect3D.FromArray(boxBytes); } for (int i = 0; i < shapeCount; i++) { var shapeRepetition = br.ReadInt32(); Assert.IsTrue(shapeRepetition > 0); if (shapeRepetition > 1) { for (int j = 0; j < shapeRepetition; j++) { var ifcProductLabel = br.ReadInt32(); var instanceTypeId = br.ReadInt16(); var instanceLabel = br.ReadInt32(); var styleId = br.ReadInt32(); var transform = XbimMatrix3D.FromArray(br.ReadBytes(sizeof(float) * 16)); } var triangulation = br.ReadShapeTriangulation(); } else if (shapeRepetition == 1) { var ifcProductLabel = br.ReadInt32(); var instanceTypeId = br.ReadInt16(); var instanceLabel = br.ReadInt32(); var styleId = br.ReadInt32(); var triangulation = br.ReadShapeTriangulation(); } } } } } }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="context"></param> /// <param name="exclude">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param> /// <returns></returns> private void BuildScene(Xbim3DModelContext context) { //get a list of all the unique styles Dictionary<int, WpfMaterial> styles = new Dictionary<int, WpfMaterial>(); Dictionary<int, MeshGeometry3D> shapeGeometries = new Dictionary<int, MeshGeometry3D>(); Dictionary<int, WpfMeshGeometry3D> meshSets = new Dictionary<int, WpfMeshGeometry3D>(); Model3DGroup opaques = new Model3DGroup(); Model3DGroup transparents = new Model3DGroup(); foreach (var shapeGeom in context.ShapeGeometries()) { MeshGeometry3D wpfMesh = new MeshGeometry3D(); wpfMesh.SetValue(TagProperty, shapeGeom); //don't read the geometry into the mesh yet as we do not know where the instance is located shapeGeometries.Add(shapeGeom.ShapeLabel, wpfMesh); } foreach (var style in context.SurfaceStyles()) { WpfMaterial wpfMaterial = new WpfMaterial(); wpfMaterial.CreateMaterial(style); styles.Add(style.DefinedObjectId, wpfMaterial); WpfMeshGeometry3D mg = new WpfMeshGeometry3D(wpfMaterial, wpfMaterial); meshSets.Add(style.DefinedObjectId, mg); if (style.IsTransparent) transparents.Children.Add(mg); else opaques.Children.Add(mg); } ////if (!styles.Any()) return ; //this should always have something unless the model is empty ////double metre = model.ModelFactors.OneMetre; ////XbimMatrix3D wcsTransform = XbimMatrix3D.CreateTranslation(_modelTranslation) * XbimMatrix3D.CreateScale((float)(1 / metre)); ////foreach (var shapeInstance in context.ShapeInstances() //// .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && //// !typeof(IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) && //// !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)))) ////{ //// int styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; //// //GET THE ACTUAL GEOMETRY //// MeshGeometry3D wpfMesh; //// //see if we have already read it //// if (shapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) //// { //// GeometryModel3D mg = new GeometryModel3D(wpfMesh, styles[styleId]); //// mg.SetValue(TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); //// mg.BackMaterial = mg.Material; //// mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform).ToMatrixTransform3D(); //// if (styles[styleId].IsTransparent) //// transparents.Children.Add(mg); //// else //// opaques.Children.Add(mg); //// } //// else //we need to get the shape geometry //// { //// XbimShapeGeometry shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); //// if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again //// { //// wpfMesh = new MeshGeometry3D(); //// wpfMesh.Read(shapeGeom.ShapeData); //// shapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh); //// GeometryModel3D mg = new GeometryModel3D(wpfMesh, styles[styleId]); //// mg.SetValue(TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); //// mg.BackMaterial = mg.Material; //// mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform).ToMatrixTransform3D(); //// if (styles[styleId].IsTransparent) //// transparents.Children.Add(mg); //// else //// opaques.Children.Add(mg); //// } //// else //it is a one off, merge it with shapes of a similar material //// { //// WpfMeshGeometry3D mg = meshSets[styleId]; //// mg.Add(shapeGeom.ShapeData, //// shapeInstance.IfcTypeId, //// shapeInstance.IfcProductLabel, //// shapeInstance.InstanceLabel, //// XbimMatrix3D.Multiply(shapeInstance.Transformation, wcsTransform), 0); //// } //// } ////} if (opaques.Children.Any()) { ModelVisual3D mv = new ModelVisual3D(); mv.Content = opaques; Opaques.Children.Add(mv); if (_modelBounds.IsEmpty) _modelBounds = mv.Content.Bounds.ToXbimRect3D(); else _modelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } if (transparents.Children.Any()) { ModelVisual3D mv = new ModelVisual3D(); mv.Content = transparents; Transparents.Children.Add(mv); if (_modelBounds.IsEmpty) _modelBounds = mv.Content.Bounds.ToXbimRect3D(); else _modelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } }
private static void IfcFeaturesClassificationIsCorrect(string ifcFileFullName) { var xbimFileFullName = Path.ChangeExtension(ifcFileFullName, ".xbim"); using (var m = new XbimModel()) { m.CreateFrom(ifcFileFullName, xbimFileFullName, null, true, true); var context = new Xbim3DModelContext(m); context.CreateContext(XbimGeometryType.PolyhedronBinary); TestForClassificationOfIfcFeatureElements(context); m.Close(); } }
private ProcessResult ProcessFile(string ifcFile, StreamWriter writer) { RemoveFiles(ifcFile); long geomTime = -1; long parseTime = -1; using (EventTrace eventTrace = LoggerFactory.CreateEventTrace()) { ProcessResult result = new ProcessResult() { Errors = -1 }; try { Stopwatch watch = new Stopwatch(); watch.Start(); using (XbimModel model = ParseModelFile(ifcFile,Params.Caching)) { parseTime = watch.ElapsedMilliseconds; string xbimFilename = BuildFileName(ifcFile, ".xbim"); //model.Open(xbimFilename, XbimDBAccess.ReadWrite); //if (_params.GeometryV1) // XbimMesher.GenerateGeometry(model, Logger, null); //else //{ Xbim3DModelContext context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary); //} geomTime = watch.ElapsedMilliseconds - parseTime; //XbimSceneBuilder sb = new XbimSceneBuilder(); //string xbimSceneName = BuildFileName(ifcFile, ".xbimScene"); //sb.BuildGlobalScene(model, xbimSceneName); // sceneTime = watch.ElapsedMilliseconds - geomTime; IIfcFileHeader header = model.Header; watch.Stop(); IfcOwnerHistory ohs = model.Instances.OfType<IfcOwnerHistory>().FirstOrDefault(); result = new ProcessResult { ParseDuration = parseTime, GeometryDuration = geomTime, // SceneDuration = sceneTime, FileName = ifcFile.Remove(0,Params.TestFileRoot.Length).TrimStart('\\'), Entities = model.Instances.Count, IfcSchema = header.FileSchema.Schemas.FirstOrDefault(), IfcDescription = String.Format("{0}, {1}", header.FileDescription.Description.FirstOrDefault(), header.FileDescription.ImplementationLevel), GeometryEntries = model.GeometriesCount, IfcLength = ReadFileLength(ifcFile), XbimLength = ReadFileLength(xbimFilename), // SceneLength = ReadFileLength(xbimSceneName), IfcProductEntries = model.Instances.CountOf<IfcProduct>(), IfcSolidGeometries = model.Instances.CountOf<IfcSolidModel>(), IfcMappedGeometries = model.Instances.CountOf<IfcMappedItem>(), BooleanGeometries = model.Instances.CountOf<IfcBooleanResult>(), Application = ohs == null ? "Unknown" : ohs.OwningApplication.ToString(), }; model.Close(); } } catch (Exception ex) { Logger.Error(String.Format("Problem converting file: {0}", ifcFile), ex); result.Failed = true; } finally { result.Errors = (from e in eventTrace.Events where (e.EventLevel == EventLevel.ERROR) select e).Count(); result.Warnings = (from e in eventTrace.Events where (e.EventLevel == EventLevel.WARN) select e).Count(); result.FileName = ifcFile.Remove(0, Params.TestFileRoot.Length).TrimStart('\\'); if (eventTrace.Events.Count > 0) { CreateLogFile(ifcFile, eventTrace.Events); } lock (thisLock) { writer.WriteLine(result.ToCsv()); writer.Flush(); } } return result; } }
private static void WriteWexBim(string fnameIn) { var fNameOut = Path.ChangeExtension(fnameIn, "wexbim"); using (var m = new XbimModel()) { m.CreateFrom(fnameIn, null, null, true, true); var m3D = new Xbim3DModelContext(m); m3D.CreateContext(XbimGeometryType.PolyhedronBinary); using (var bw = new BinaryWriter(new FileStream(fNameOut, FileMode.Create))) { m3D.Write(bw); bw.Close(); } } }
private static void TestForClassificationOfIfcFeatureElements(Xbim3DModelContext context) { var excludedTypes = new HashSet<short> { IfcMetaData.IfcType(typeof (IfcFeatureElement)).TypeId, IfcMetaData.IfcType(typeof (IfcOpeningElement)).TypeId, IfcMetaData.IfcType(typeof (IfcProjectionElement)).TypeId }; var shapeInstances = context.ShapeInstances().Where(s => excludedTypes.Contains(s.IfcTypeId) && // ifcfeatures s.RepresentationType != XbimGeometryRepresentationType.OpeningsAndAdditionsOnly); // that are not classified as OpeningsAndAdditionsOnly Assert.IsFalse(shapeInstances.Any(), "Should not find any shapes of with this classification of typeid and representationType."); }
/// <summary> /// This version uses the new Geometry representation /// </summary> /// <param name="model"></param> /// <param name="context"></param> /// <param name="exclude">List of type to exclude, by default excplict openings and spaces are excluded if exclude = null</param> /// <returns></returns> public XbimScene<WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List<Type> exclude = null) { var scene = new XbimScene<WpfMeshGeometry3D, WpfMaterial>(model); if (context == null) return scene; //get a list of all the unique styles var styles = new Dictionary<int, WpfMaterial>(); var repeatedShapeGeometries = new Dictionary<int, MeshGeometry3D>(); var styleMeshSets = new Dictionary<int, WpfMeshGeometry3D>(); var tmpOpaquesGroup = new Model3DGroup(); var tmpTransparentsGroup = new Model3DGroup(); var sstyles = context.SurfaceStyles(); foreach (var style in sstyles) { var wpfMaterial = new WpfMaterial(); wpfMaterial.CreateMaterial(style); styles.Add(style.DefinedObjectId, wpfMaterial); var mg = new WpfMeshGeometry3D(wpfMaterial, wpfMaterial); mg.WpfModel.SetValue(FrameworkElement.TagProperty, mg); styleMeshSets.Add(style.DefinedObjectId, mg); mg.BeginUpdate(); if (style.IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } if (!styles.Any()) return scene; //this should always return something int i = 0; var shapeInstances = context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/); foreach (var shapeInstance in shapeInstances) { Console.WriteLine(i++); var styleId = shapeInstance.StyleLabel > 0 ? shapeInstance.StyleLabel : shapeInstance.IfcTypeId * -1; //GET THE ACTUAL GEOMETRY MeshGeometry3D wpfMesh; //see if we have already read it if (repeatedShapeGeometries.TryGetValue(shapeInstance.ShapeGeometryLabel, out wpfMesh)) { var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } else //we need to get the shape geometry { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); if (shapeGeom.ReferenceCount > 1) //only store if we are going to use again { wpfMesh = new MeshGeometry3D(); switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.PolyhedronBinary: wpfMesh.Read(shapeGeom.ShapeData); break; case XbimGeometryType.Polyhedron: wpfMesh.Read(((XbimShapeGeometry)shapeGeom).ShapeData); break; } repeatedShapeGeometries.Add(shapeInstance.ShapeGeometryLabel, wpfMesh); var mg = new GeometryModel3D(wpfMesh, styles[styleId]); mg.SetValue(FrameworkElement.TagProperty, new XbimInstanceHandle(model, shapeInstance.IfcProductLabel, shapeInstance.IfcTypeId)); mg.BackMaterial = mg.Material; mg.Transform = XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform).ToMatrixTransform3D(); if (styles[styleId].IsTransparent) tmpTransparentsGroup.Children.Add(mg); else tmpOpaquesGroup.Children.Add(mg); } else //it is a one off, merge it with shapes of a similar material { var targetMergeMeshByStyle = styleMeshSets[styleId]; switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: var shapePoly = (XbimShapeGeometry)shapeGeom; targetMergeMeshByStyle.Add( shapePoly.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform)); break; case XbimGeometryType.PolyhedronBinary: targetMergeMeshByStyle.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.WcsTransform)); break; default: throw new ArgumentOutOfRangeException(); } } } } foreach (var wpfMeshGeometry3D in styleMeshSets.Values) { wpfMeshGeometry3D.EndUpdate(); } //} if (tmpOpaquesGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpOpaquesGroup; Control.Opaques.Children.Add(mv); Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); } if (tmpTransparentsGroup.Children.Any()) { var mv = new ModelVisual3D(); mv.Content = tmpTransparentsGroup; Control.Transparents.Children.Add(mv); if (Control.ModelBounds.IsEmpty) Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); else Control.ModelBounds.Union(mv.Content.Bounds.ToXbimRect3D()); } return scene; }
/// <summary> /// Converts an Ifc File to xBIM if it does not already exists, then converts the geoemtry to Xbim format and profiles the results /// </summary> /// <param name="args"> file[.ifc, xbim]</param> static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("No Ifc or xBim file specified"); return; } var fileName = args[0]; var mainStopWatch = new Stopwatch(); mainStopWatch.Start(); using (var model = GetModel(fileName)) { if (model != null) { var functionStack = new ConcurrentStack<Tuple<string,double>>(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { if (percentProgress == -1) { functionStack.Push(new Tuple<string,double>(userState.ToString(), DateTime.Now.TimeOfDay.TotalMilliseconds)); Logger.InfoFormat("Entering - {0}", userState.ToString()); } else if (percentProgress == 101) { Tuple<string,double> func; if(functionStack.TryPop(out func)) Logger.InfoFormat("Complete in \t\t{0:0.0} ms", DateTime.Now.TimeOfDay.TotalMilliseconds - func.Item2); } }; var context = new Xbim3DModelContext(model); context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: progDelegate); mainStopWatch.Stop(); Logger.InfoFormat("Xbim total Compile Time \t\t{0:0.0} ms", mainStopWatch.ElapsedMilliseconds); var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM"); using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { var stopWatch = new Stopwatch(); Logger.InfoFormat("Entering - Create wexBIM"); stopWatch.Start(); context.Write(wexBimBinaryWriter); stopWatch.Stop(); Logger.InfoFormat("Complete - in \t\t{0:0.0} ms", stopWatch.ElapsedMilliseconds); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } model.Close(); } } Console.WriteLine("Press any key to exit"); Console.Read(); }
public XbimSceneJS(Xbim3DModelContext context) { _context = context; }
/// <summary> /// Clears the current graphics and initiates the cascade of events that result in viewing the scene. /// </summary> /// <param name="EntityLabels">If null loads the whole model, otherwise only elements listed in the enumerable</param> public void LoadGeometry(XbimModel model, bool recalcView = true) { // AddLayerToDrawingControl is the function that actually populates the geometry in the viewer. // AddLayerToDrawingControl is triggered by BuildRefModelScene and BuildScene below here when layers get ready. //reset all the visuals ClearGraphics(recalcView); short userDefinedId = 0; if (model == null) return; //nothing to show model.UserDefinedId = userDefinedId; Xbim3DModelContext context = new Xbim3DModelContext(model); XbimRegion largest = context.GetLargestRegion(); XbimPoint3D c = new XbimPoint3D(0, 0, 0); XbimRect3D bb = XbimRect3D.Empty; if (largest != null) bb = new XbimRect3D(largest.Centre, largest.Centre); foreach (var refModel in model.ReferencedModels) { XbimRegion r; refModel.Model.UserDefinedId = ++userDefinedId; Xbim3DModelContext refContext = new Xbim3DModelContext(refModel.Model); r = refContext.GetLargestRegion(); if (r != null) { if (bb.IsEmpty) bb = new XbimRect3D(r.Centre, r.Centre); else bb.Union(r.Centre); } } XbimPoint3D p = bb.Centroid(); _modelTranslation = new XbimVector3D(-p.X, -p.Y, -p.Z); model.ReferencedModels.CollectionChanged += RefencedModels_CollectionChanged; //build the geometric scene and render as we go BuildScene(context); foreach (var refModel in model.ReferencedModels) { Xbim3DModelContext refContext = new Xbim3DModelContext(refModel.Model); BuildScene(refContext); } if (recalcView) RecalculateView(model); }
private void OpenIfcFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var ifcFilename = args.Argument as string; var model = new XbimModel(); try { _temporaryXbimFileName = Path.GetTempFileName(); _openedModelFileName = ifcFilename; if (worker != null) { model.CreateFrom(ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); var context = new Xbim3DModelContext(model);//upgrade to new geometry represenation, uses the default 3D model context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: worker.ReportProgress); if (worker.CancellationPending) //if a cancellation has been requested then don't open the resulting file { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) File.Delete(_temporaryXbimFileName); //tidy up; _temporaryXbimFileName = null; _openedModelFileName = null; } // ReSharper disable once EmptyGeneralCatchClause catch { } return; } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
private void OpenScriptingWindow(object sender, RoutedEventArgs e) { var win = new ScriptingWindow(); win.Owner = this; win.ScriptingConcrol.DataContext = ModelProvider; var binding = new Binding(); win.ScriptingConcrol.SetBinding(ScriptingControl.ModelProperty, binding); win.ScriptingConcrol.OnModelChangedByScript += delegate(object o, ModelChangedEventArgs arg) { ModelProvider.ObjectInstance = null; var m3D = new Xbim3DModelContext(arg.NewModel); m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary); ModelProvider.ObjectInstance = arg.NewModel; ModelProvider.Refresh(); }; win.ScriptingConcrol.OnScriptParsed += delegate { GroupControl.Regenerate(); //SpatialControl.Regenerate(); }; ScriptResults.Visibility = Visibility.Visible; win.Closing += delegate { ScriptResults.Visibility = Visibility.Collapsed; }; win.Show(); }
//private void Add_Click(object sender, RoutedEventArgs e) //{ // XbimModel model = DataContext as XbimModel; // if (model != null) // { // AddFederatedModel fdlg = new AddFederatedModel(); // bool? done = fdlg.ShowDialog(); // if (done.HasValue && done.Value == true) // { // string fileName = fdlg.FileName; // string ext = System.IO.Path.GetExtension(fileName); // using (XbimModel refM = new XbimModel()) // { // if (string.Compare(ext, ".xbim", true) != 0) // { // refM.CreateFrom(fileName, null, null, true); // XbimMesher.GenerateGeometry(refM); // fileName = System.IO.Path.ChangeExtension(fileName, "xbim"); // } // } // IfcRole role = fdlg.Role; // if (role == IfcRole.UserDefined) // model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName); // else // model.AddModelReference(fileName, fdlg.OrganisationName, role); // } // } //} private void Add_Click(object sender, RoutedEventArgs e) { XbimModel model = DataContext as XbimModel; if (model != null) { AddFederatedModel fdlg = new AddFederatedModel(); bool? done = fdlg.ShowDialog(); if (done.HasValue && done.Value == true) { string fileName = fdlg.FileName; string ext = System.IO.Path.GetExtension(fileName); using (XbimModel refM = new XbimModel()) { if (string.Compare(ext, ".xbim", true) != 0) { refM.CreateFrom(fileName, null, null, true); var m3D = new Xbim3DModelContext(refM); m3D.CreateContext(); fileName = System.IO.Path.ChangeExtension(fileName, "xbim"); } } IfcRole role = fdlg.Role; if (role == IfcRole.UserDefined) model.AddModelReference(fileName, fdlg.OrganisationName, fdlg.RoleName); else model.AddModelReference(fileName, fdlg.OrganisationName, role); } } }
/// <summary> /// Validates all data and creates model. /// Provide a "XbimModel model = DataContext as XbimModel;" /// </summary> /// <returns>Returns XbimReferencedModel == null </returns> public bool TryBuild(XbimModel model) { //it's already build, so no need to recreate it if (ReferencedModel != null) return true; if (string.IsNullOrWhiteSpace(Name)) return false; var ext = Path.GetExtension(Name).ToLowerInvariant(); using (var refM = new XbimModel()) { var xbimName = Path.ChangeExtension(Name, "xbim"); if (ext != ".xbim" && !File.Exists(xbimName)) { refM.CreateFrom(Name, null, null, true); var m3D = new Xbim3DModelContext(refM); m3D.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary, progDelegate: null, adjustWCS: false); Name = Path.ChangeExtension(Name, "xbim"); } Name = xbimName; } _xbimReferencedModel = model.AddModelReference(Name, OrganisationName, OrganisationRole); if (_xbimReferencedModel == null) return ReferencedModel != null; //refresh all OnPropertyChanged("Identifier"); OnPropertyChanged("Name"); OnPropertyChanged("OrganisationName"); OnPropertyChanged("OrganisationRole"); return ReferencedModel != null; }
static void Main(string[] args) { if (args.Length < 1) { Console.WriteLine("No Ifc or xBim file specified"); return; } var fileName = args[0]; Console.WriteLine("Reading " + fileName); using (var model = GetModel(fileName)) { if (model != null) { var context = new Xbim3DModelContext(model); context.CreateContext(geomStorageType: XbimGeometryType.PolyhedronBinary); var wexBimFilename = Path.ChangeExtension(fileName, "wexBIM"); using (var wexBiMfile = new FileStream(wexBimFilename, FileMode.Create, FileAccess.Write)) { using (var wexBimBinaryWriter = new BinaryWriter(wexBiMfile)) { Console.WriteLine("Creating " + wexBimFilename); context.Write(wexBimBinaryWriter); wexBimBinaryWriter.Close(); } wexBiMfile.Close(); } //now do the DPoW files var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileName); var fileDirectoryName = Path.GetDirectoryName(fileName); var facilities = new List<Facility>(); var ifcToCoBieLiteUkExchanger = new IfcToCOBieLiteUkExchanger(model, facilities); facilities = ifcToCoBieLiteUkExchanger.Convert(); var facilityNumber = 0; foreach (var facility in facilities) { var dpow = "DPoW"; if (facilities.Count > 1) dpow += ++facilityNumber; // ReSharper disable AssignNullToNotNullAttribute var dPoWFile = Path.Combine(fileDirectoryName, fileNameWithoutExtension + "_" + dpow); // ReSharper restore AssignNullToNotNullAttribute dPoWFile = Path.ChangeExtension(dPoWFile, "json"); Console.WriteLine("Creating " + dPoWFile); facility.WriteJson(dPoWFile); string cobieFile = Path.ChangeExtension(dPoWFile, "Xlsx"); Console.WriteLine("Creating " + cobieFile); string error; facility.WriteCobie(cobieFile, out error); if (!string.IsNullOrWhiteSpace(error)) Console.WriteLine("COBie Errors: " + error); dPoWFile = Path.ChangeExtension(dPoWFile, "xml"); Console.WriteLine("Creating " + dPoWFile); // facility.WriteXml(dPoWFile); var req = Facility.ReadJson(@"..\..\Tests\ValidationFiles\Lakeside_Restaurant-stage6-COBie.json"); var validator = new FacilityValidator(); var result = validator.Validate(req, facility); var verificationResults = Path.ChangeExtension(dPoWFile, "verified.xlsx"); Console.WriteLine("Creating " + verificationResults); //create report using (var stream = File.Create(verificationResults)) { var report = new ExcelValidationReport(); report.Create(result, stream, ExcelValidationReport.SpreadSheetFormat.Xlsx); stream.Close(); } facility.ValidateUK2012(Console.Out,true); string cobieValidatedFile = Path.ChangeExtension(dPoWFile, "Validated.Xlsx"); facility.WriteCobie(cobieValidatedFile, out error); dPoWFile = Path.ChangeExtension(dPoWFile, "xbim"); Console.WriteLine("Creating " + dPoWFile); using (var ifcModel = XbimModel.CreateModel(dPoWFile)) { ifcModel.Initialise("Xbim Tester", "XbimTeam", "Xbim.Exchanger", "Xbim Development Team", "3.0"); ifcModel.ReloadModelFactors(); using (var txn = ifcModel.BeginTransaction("Convert from COBieLiteUK")) { var coBieLiteUkToIfcExchanger = new CoBieLiteUkToIfcExchanger(facility, ifcModel); coBieLiteUkToIfcExchanger.Convert(); txn.Commit(); //var err = model.Validate(model.Instances, Console.Out); } dPoWFile = Path.ChangeExtension(dPoWFile, "ifc"); Console.WriteLine("Creating " + dPoWFile); ifcModel.SaveAs(dPoWFile, XbimStorageType.IFC); ifcModel.Close(); } } model.Close(); } } Console.WriteLine("Press any key to exit"); Console.Read(); }
public XbimScene<WpfMeshGeometry3D, WpfMaterial> BuildScene(XbimModel model, Xbim3DModelContext context, List<Type> exclude = null) { var tmpOpaquesGroup = new Model3DGroup(); var retScene = new XbimScene<WpfMeshGeometry3D, WpfMaterial>(model); var red = PrepareMesh(new XbimColour("Red", 1.0, 0.0, 0.0)); var green = PrepareMesh(new XbimColour("Green", 0.0, 1.0, 0.0)); var amber =PrepareMesh(new XbimColour("Amber", 0.0, 0.0, 1.0, 0.9)); tmpOpaquesGroup.Children.Add(red); tmpOpaquesGroup.Children.Add(green); tmpOpaquesGroup.Children.Add(amber); var i = 0; foreach (var shapeInstance in context.ShapeInstances() .Where(s => s.RepresentationType == XbimGeometryRepresentationType.OpeningsAndAdditionsIncluded && !typeof (IfcFeatureElement).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId)) /*&& !typeof(IfcSpace).IsAssignableFrom(IfcMetaData.GetType(s.IfcTypeId))*/)) { IXbimShapeGeometryData shapeGeom = context.ShapeGeometry(shapeInstance.ShapeGeometryLabel); WpfMeshGeometry3D targetMergeMesh; switch (i++%3) { case 0: targetMergeMesh = red; break; case 1: targetMergeMesh = green; break; default: targetMergeMesh = amber; break; } switch ((XbimGeometryType)shapeGeom.Format) { case XbimGeometryType.Polyhedron: var shapePoly = (XbimShapeGeometry)shapeGeom; targetMergeMesh.Add( shapePoly.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId ); break; case XbimGeometryType.PolyhedronBinary: targetMergeMesh.Add( shapeGeom.ShapeData, shapeInstance.IfcTypeId, shapeInstance.IfcProductLabel, shapeInstance.InstanceLabel, XbimMatrix3D.Multiply(shapeInstance.Transformation, Control.ModelPositions[model].Transfrom), model.UserDefinedId); break; default: throw new ArgumentOutOfRangeException(); } } var mv = new ModelVisual3D {Content = tmpOpaquesGroup}; Control.OpaquesVisual3D.Children.Add(mv); Control.ModelBounds = mv.Content.Bounds.ToXbimRect3D(); return retScene; }
private void OpenFile(object s, DoWorkEventArgs args) { var worker = s as BackgroundWorker; var model = new XbimModel(); try { if (worker != null) { IsLoading = true; _openedModelFileName = _ifcFilename; _temporaryXbimFileName = Path.GetTempFileName(); model.CreateFrom(_ifcFilename, _temporaryXbimFileName, worker.ReportProgress, true); //upgrade to new geometry represenation, uses the default 3D model var context = new Xbim3DModelContext(model); context.CreateContext(XbimGeometryType.PolyhedronBinary, worker.ReportProgress, false); if (worker.CancellationPending) { try { model.Close(); if (File.Exists(_temporaryXbimFileName)) { File.Delete(_temporaryXbimFileName); _temporaryXbimFileName = null; } } catch (Exception) { // ignored } } } args.Result = model; } catch (Exception ex) { var sb = new StringBuilder(); sb.AppendLine("Error reading " + _ifcFilename); var indent = "\t"; while (ex != null) { sb.AppendLine(indent + ex.Message); ex = ex.InnerException; indent += "\t"; } args.Result = new Exception(sb.ToString()); } }
private void Modify_Click(object sender, RoutedEventArgs e) { XbimModel model = DataContext as XbimModel; foreach (var item in FederatedList.SelectedItems) { if (item is XbimReferencedModel) { var rItem = item as XbimReferencedModel; AddFederatedModel fdlg = new AddFederatedModel(rItem); bool? done = fdlg.ShowDialog(); if (done.HasValue && done.Value == true) { string fileName = fdlg.FileName; string ext = System.IO.Path.GetExtension(fileName); using (XbimModel refM = new XbimModel()) { if (string.Compare(ext, ".xbim", true) != 0) { refM.CreateFrom(fileName, null, null, true); var m3D = new Xbim3DModelContext(refM); m3D.CreateContext(); fileName = System.IO.Path.ChangeExtension(fileName, "xbim"); } } using (var txn = model.BeginTransaction()) { rItem.DocumentInformation.Name = fileName; txn.Commit(); } } } } }
//Needed Geometry to test, but Steve's comment on "need to resolve generate geometry" may see GenerateGeometry change private void GenerateGeometry(COBieContext context) { //now convert the geometry XbimModel model = context.Model; int total = (int)model.Instances.CountOf<IfcProduct>(); ReportProgressDelegate progDelegate = delegate(int percentProgress, object userState) { context.UpdateStatus("Creating Geometry File", total, (total * percentProgress / 100)); }; var m3D = new Xbim3DModelContext(model); try { m3D.CreateContext(progDelegate: progDelegate); } catch (Exception ce) { context.UpdateStatus("Error compiling geometry\n" + ce.Message, total, 100); } }