Пример #1
0
        public static void AssertNoSurfaceIntersections(PolySurface TestPolysurface)
        {
            var SubSurfaces = (TestPolysurface as PolySurface).Surfaces().ToList();

            // perfrom the intersection test

            bool overlapflag = false;

            foreach (var surfaceToIntersect in SubSurfaces)
            {
                foreach (var rotsubface in SubSurfaces)
                {
                    if (surfaceToIntersect.Equals(rotsubface))
                    {
                        continue;
                    }
                    var resultantGeo = surfaceToIntersect.Intersect(rotsubface);
                    foreach (var geo in resultantGeo)
                    {
                        if (geo is Surface)
                        {
                            overlapflag = true;
                        }
                    }
                }
            }
            Assert.IsFalse(overlapflag);
        }
Пример #2
0
        /***************************************************/

        private static oM.Physical.Elements.Wall WallFromRevit_Curtain(this Wall wall, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            List <BH.oM.Physical.Elements.IOpening> curtainPanels = wall.CurtainGrid.CurtainPanels(wall.Document, settings, refObjects);

            ISurface location = null;

            if (curtainPanels == null || curtainPanels.Count == 0)
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Processing of panels of Revit curtain wall failed. BHoM wall without location has been returned. Revit ElementId: {0}", wall.Id.IntegerValue));
            }
            else if (curtainPanels.Count == 1)
            {
                location = curtainPanels[0].Location;
            }
            else
            {
                location = new PolySurface {
                    Surfaces = curtainPanels.Select(x => x.Location).ToList()
                }
            };

            return(new oM.Physical.Elements.Wall {
                Location = location, Openings = curtainPanels
            });
        }

        /***************************************************/
    }
Пример #3
0
    private void GenerateSamples(int amount = 10)
    {
        meshCollider.sharedMesh = currentPointCloud.mesh.mesh;

        var camRay = camera.ScreenPointToRay(Input.mousePosition);
        var dir    = camRay.direction;

        var(dist, _) = PolySurface.RayMarch(coefficients, camRay.origin, dir, 1000.0f, surface.Center);
        var hit = camRay.origin + (dist + 0.001f) * camRay.direction;

        hit = currentCenter - currentNormal * 0.001f;
        dir = -currentNormal;

        int count = 0;

        while (count < amount)
        {
            int stepCount = 0;
            var exit      = TestDataGenerator.SimulatePath(
                samplesRandom,
                surface.Coefficients,
                hit, dir,
                surface.Center,
                surface.g, surface.SigmaSReduced, surface.sigmaT,
                distScale,
                null,
                ref stepCount);

            if (exit != null)
            {
                count += 1;
                var ray = new Ray(exit.Value, -PolySurface.GetNormalAt(surface.Coefficients, exit.Value, surface.Center));
                if (autoProjectSamples && meshCollider.Raycast(ray, out var h, float.MaxValue))
                {
                    var go = GameObject.Instantiate(samplePointPrefab, transform);
                    go.transform.position = h.point;
                    samples.Add(go);

                    //samples.Add(new MeshDBSample
                    //{
                    //    position = h.point,
                    //    gradient = -ray.direction,
                    //});
                }
                else
                {
                    var go = GameObject.Instantiate(samplePointPrefab, transform);
                    go.transform.position = exit.Value;
                    samples.Add(go);
                    //samples.Add(new MeshDBSample
                    //{
                    //    position = exit.Value,
                    //    gradient = -ray.direction
                    //});
                }
            }
        }
Пример #4
0
        public static double Area(this PolySurface pSurf, double tolerance = Tolerance.Distance)
        {
            if (pSurf == null)
            {
                BH.Engine.Reflection.Compute.RecordError("Cannot query area as the geometry is null.");
                return(double.NaN);
            }

            return(pSurf.Surfaces.Sum(x => x.IArea(tolerance)));
        }
Пример #5
0
        public static List <Point> IsPlanar(this PolySurface surface)
        {
            List <Point> points = new List <Point>();

            foreach (ISurface s in surface.Surfaces)
            {
                points.AddRange(IPoints(s));
            }

            return(points);
        }
Пример #6
0
        /***************************************************/

        public static bool IsPlanar(this PolySurface surface, double tolerance = Tolerance.Distance)
        {
            foreach (ISurface s in surface.Surfaces)
            {
                if (!s.IIsPlanar(tolerance))
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #7
0
        /***************************************************/
        /**** Public Methods - Surfaces                 ****/
        /***************************************************/

        public static List <ISurface> SubParts(this PolySurface surface)
        {
            List <ISurface> exploded = new List <ISurface>();
            List <ISurface> surfaces = surface.Surfaces;

            for (int i = 0; i < surfaces.Count; i++)
            {
                exploded.AddRange(surfaces[i].ISubParts());
            }

            return(exploded);
        }
Пример #8
0
        internal static global::Topologic.Shell ShellByPolySurface(PolySurface bhomPolySurface, double tolerance)
        {
            List <global::Topologic.Face> faces = new List <global::Topologic.Face>();

            foreach (ISurface bhomSurface in bhomPolySurface.Surfaces)
            {
                global::Topologic.Face face = Create.FaceBySurface(bhomSurface);
                faces.Add(face);
            }

            return(global::Topologic.Shell.ByFaces(faces, tolerance));
        }
Пример #9
0
        /***************************************************/
        /****              Private methods              ****/
        /***************************************************/

        private static bool TryAddSurface(this BRepBuilder brep, PolySurface ps)
        {
            foreach (ISurface s in ps.Surfaces)
            {
                if (!TryAddSurface(brep, s as dynamic))
                {
                    return(false);
                }
            }

            return(true);
        }
Пример #10
0
        /***************************************************/

        private static oM.Physical.Elements.Roof CurtainRoofFromRevit(this RoofBase roof, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            List <BH.oM.Physical.Elements.IOpening> openings = new List <oM.Physical.Elements.IOpening>();
            List <CurtainGrid> curtainGrids = roof.ICurtainGrids();

            bool partFailed = false;

            foreach (CurtainGrid cg in curtainGrids)
            {
                List <BH.oM.Physical.Elements.IOpening> curtainPanels = cg.CurtainPanels(roof.Document, settings, refObjects);
                if (curtainPanels == null)
                {
                    partFailed = true;
                }
                else
                {
                    openings.AddRange(curtainPanels);
                }
            }

            ISurface location = null;

            if (openings == null || openings.Count == 0)
            {
                BH.Engine.Reflection.Compute.RecordError(String.Format("Processing of panels of Revit curtain roof failed. BHoM roof without location has been returned. Revit ElementId: {0}", roof.Id.IntegerValue));
            }
            else
            {
                if (partFailed)
                {
                    BH.Engine.Reflection.Compute.RecordError(String.Format("Processing of panels of a Revit curtain roof failed. Parts of the geometry of the BHoM roof may be missing. Revit ElementId: {0}", roof.Id.IntegerValue));
                }

                if (openings.Count == 1)
                {
                    location = openings[0].Location;
                }
                else
                {
                    location = new PolySurface {
                        Surfaces = openings.Select(x => x.Location).ToList()
                    }
                };
            }

            return(new oM.Physical.Elements.Roof {
                Location = location, Openings = openings
            });
        }

        /***************************************************/
    }
Пример #11
0
        public static DraftingInstance DraftingInstance(InstanceProperties properties, string viewName, ISurface location)
        {
            if (properties == null || string.IsNullOrWhiteSpace(viewName))
            {
                return(null);
            }

            List <PlanarSurface> surfaces = new List <PlanarSurface>();

            if (location is PlanarSurface)
            {
                surfaces.Add((PlanarSurface)location);
            }
            else if (location is PolySurface)
            {
                PolySurface polySurface = (PolySurface)location;
                if (polySurface.Surfaces.Any(x => !(x is PlanarSurface)))
                {
                    BH.Engine.Reflection.Compute.RecordError("Only PlanarSurfaces and PolySurfaces consisting of PlanarSurfaces can be used as location for ISurface-based DraftingInstances.");
                    return(null);
                }

                surfaces = polySurface.Surfaces.Cast <PlanarSurface>().ToList();
            }
            else
            {
                BH.Engine.Reflection.Compute.RecordError("Only PlanarSurfaces and PolySurfaces consisting of PlanarSurfaces can be used as location for ISurface-based DraftingInstances.");
                return(null);
            }

            foreach (PlanarSurface surface in surfaces)
            {
                Vector normal = (surface).Normal();
                if (normal == null || 1 - Math.Abs(normal.DotProduct(Vector.ZAxis)) > Tolerance.Angle)
                {
                    BH.Engine.Reflection.Compute.RecordError("Normal of the surface or its components is not parallel to the global Z axis.");
                    return(null);
                }
            }

            DraftingInstance draftingInstance = new DraftingInstance()
            {
                Properties = properties,
                Name       = properties.Name,
                ViewName   = viewName,
                Location   = location
            };

            return(draftingInstance);
        }
Пример #12
0
        private static PolySurface GetObjGroupMesh(Group group, LoadResult result)
        {
            var polygons = new List <Surface>();
            var points   = new List <Point>();

            foreach (var face in group.Faces)
            {
                for (int i = 0; i < face.Count; i++)
                {
                    var index = face[i].VertexIndex - 1;
                    points.Add(Point.ByCoordinates(result.Vertices[index].X, result.Vertices[index].Y, result.Vertices[index].Z));
                }
            }

            for (int i = 0; i < points.Count; i += 3)
            {
                int j = i + 1;
                int k = i + 2;

                var point1 = points[i];
                var point2 = points[j];
                var point3 = points[k];

                var facePoints = new List <Point>()
                {
                    point1, point2, point3
                };
                try
                {
                    polygons.Add(Surface.ByPerimeterPoints(facePoints));
                    point1.Dispose();
                    point2.Dispose();
                    point3.Dispose();
                }
                catch
                {
                    point1.Dispose();
                    point2.Dispose();
                    point3.Dispose();
                    continue;
                }
            }

            return(PolySurface.ByJoinedSurfaces(polygons));
        }
Пример #13
0
        /***************************************************/

        public static BoundingBox Bounds(this PolySurface surface)
        {
            List <ISurface> surfaces = surface.Surfaces;

            if (surfaces.Count == 0)
            {
                return(null);
            }

            BoundingBox box = surfaces[0].IBounds();

            for (int i = 1; i < surfaces.Count; i++)
            {
                box += surfaces[i].IBounds();
            }

            return(box);
        }
Пример #14
0
        public static void AssertConditionForEverySurfaceAgainstEverySurface(PolySurface TestPolysurface, Condition condition)
        {
            var SubSurfaces = (TestPolysurface as PolySurface).Surfaces().ToList();

            // perfrom the intersection test

            foreach (var surfaceToIntersect in SubSurfaces)
            {
                foreach (var rotsubface in SubSurfaces)
                {
                    if (surfaceToIntersect.Equals(rotsubface))
                    {
                        continue;
                    }
                    condition(surfaceToIntersect, rotsubface);
                }
            }
        }
Пример #15
0
        /***************************************************/

        private static Element ToRevitElement(this DraftingInstance draftingInstance, FilledRegionType regionType, View view, RevitSettings settings)
        {
            ISurface location = draftingInstance.Location as ISurface;

            List <PlanarSurface> surfaces = new List <PlanarSurface>();

            if (location is PlanarSurface)
            {
                surfaces.Add((PlanarSurface)location);
            }
            else if (location is PolySurface)
            {
                PolySurface polySurface = (PolySurface)location;
                if (polySurface.Surfaces.Any(x => !(x is PlanarSurface)))
                {
                    draftingInstance.InvalidRegionSurfaceError();
                    return(null);
                }

                surfaces = polySurface.Surfaces.Cast <PlanarSurface>().ToList();
            }
            else
            {
                draftingInstance.InvalidRegionSurfaceError();
                return(null);
            }

            List <CurveLoop> loops = new List <CurveLoop>();

            foreach (PlanarSurface surface in surfaces)
            {
                foreach (ICurve curve in surface.Edges())
                {
                    loops.Add(curve.ToRevitCurveLoop());
                }
            }

            if (loops.Count != 0)
            {
                return(FilledRegion.Create(view.Document, regionType.Id, view.Id, loops));
            }

            return(null);
        }
Пример #16
0
        public void BySurfNameCategoryMaterial_ValidInput()
        {
            var cube  = Cuboid.ByLengths();
            var faces = cube.Faces;
            var surfs = faces.Select(x => x.SurfaceGeometry()).ToList();
            var surf  = PolySurface.ByJoinedSurfaces(surfs);

            var mat = DocumentManager.Instance.ElementsOfType <Autodesk.Revit.DB.Material>().First();

            var ds = DirectShape.ByGeometry(surf, Category.ByName("OST_GenericModel"), Material.ByName(mat.Name), "a polysurface");

            Assert.NotNull(ds);
            Assert.AreEqual("a polysurface", ds.Name);
            Assert.AreEqual((surf.Tags.LookupTag(ds.InternalElement.Id.ToString()) as DirectShapeState).materialId, mat.Id.IntegerValue);
            BoundingBoxCentroid(ds).DistanceTo(Point.Origin()).ShouldBeApproximately(0);
            surf.Dispose();
            surfs.ForEach(x => x.Dispose());
            faces.ForEach(x => x.Dispose());
            cube.Dispose();
        }
Пример #17
0
        public static List <Autodesk.DesignScript.Geometry.Geometry> DivideSurface(
            Surface surface,
            List <double> U,
            List <double> V)
        {
            List <IDisposable> disposables = new List <IDisposable>();
            List <Autodesk.DesignScript.Geometry.Geometry> dividedSurfaces = new List <Autodesk.DesignScript.Geometry.Geometry>();

            List <PolySurface>    polySurfaces = new List <PolySurface>();
            List <List <double> > UV           = new List <List <double> > {
                U, V
            };
            Curve uCurve = Curve.ByIsoCurveOnSurface(surface, 1, 0);

            for (int i = 0; i <= 1; i++)
            {
                List <Surface> crvSurf = new List <Surface>();
                foreach (double item in UV[i])
                {
                    Curve crv = Curve.ByIsoCurveOnSurface(surface, i, item);
                    crvSurf.Add(crv.Extrude(Vector.ByCoordinates(0, 0, 1)));
                    crv.Dispose();
                }
                polySurfaces.Add(PolySurface.ByJoinedSurfaces(crvSurf));
                disposables.AddRange(crvSurf);
            }
            List <Autodesk.DesignScript.Geometry.Geometry> splitSurfaces  = surface.Split(polySurfaces[1]).ToList();
            List <Autodesk.DesignScript.Geometry.Geometry> sortedSurfaces = splitSurfaces.OrderBy(x => uCurve.DistanceTo(x)).ToList();

            disposables.AddRange(splitSurfaces);

            foreach (var surf in sortedSurfaces)
            {
                dividedSurfaces.AddRange(surf.Split(polySurfaces[0]));
            }
            disposables.AddRange(sortedSurfaces);
            disposables.AddRange(polySurfaces);

            disposables.ForEach(x => x.Dispose());
            return(dividedSurfaces);
        }
Пример #18
0
 /// <summary>
 /// creates instance of unrolling
 /// </summary>
 /// <param name="polysurface">input polysurface</param>
 /// <returns>Unroll object</returns>
 public static Unroll ByPolySurface(PolySurface polysurface, double thickness, double tolerance = 1)
 {
     bool canUnroll = true;
     List<Surface> surfaces = new List<Surface>();
     Geometry[] Parts = polysurface.Explode();
     for (int n = 0; n < Parts.Length; n++)
     {
         surfaces.Add((Surface)Parts[n]);
         for (float i = 0; i < 1; i += 0.1f)
         {
             for (float j = 0; j < 1; j += 0.1f)
             {
                 if (surfaces[n].GaussianCurvatureAtParameter(i, j) > 0)
                 {
                     canUnroll = false;
                     continue;
                 }
             }
         }
     }
     return new Unroll(surfaces, thickness, canUnroll, tolerance);
 }
Пример #19
0
        /// <summary>
        /// 将Mesh转化为PolySurface
        /// </summary>
        /// <param name="mesh">网格</param>
        /// <returns>转化后的PolySurface</returns>
        public static PolySurface ConvertToPolySurface(Mesh mesh)
        {
            List <Surface> surfaces = new List <Surface>();

            Point[]      vertexs    = mesh.VertexPositions;
            IndexGroup[] indexGroup = mesh.FaceIndices;
            foreach (var item in indexGroup)
            {
                if (item.Count == 3)
                {
                    Point   pt1     = vertexs[item.A];
                    Point   pt2     = vertexs[item.B];
                    Point   pt3     = vertexs[item.C];
                    Surface surface = Surface.ByPerimeterPoints(new Point[] { pt1, pt2, pt3 });
                    surfaces.Add(surface);
                    pt1.Dispose();
                    pt2.Dispose();
                    pt3.Dispose();
                    surface.Dispose();
                }
                else
                {
                    Point pt1 = vertexs[item.A];
                    Point pt2 = vertexs[item.B];
                    Point pt3 = vertexs[item.C];
                    Point pt4 = vertexs[item.D];

                    Surface surface = Surface.ByPerimeterPoints(new Point[] { pt1, pt2, pt3, pt4 });
                    surfaces.Add(surface);
                    pt1.Dispose();
                    pt2.Dispose();
                    pt3.Dispose();
                    surface.Dispose();
                }
            }
            return(PolySurface.ByJoinedSurfaces(surfaces));
        }
Пример #20
0
        public static Dictionary <string, object> ContextByElement(PolySurface polysurface)
        {
            Solid[]            solidList       = null;
            List <BoundingBox> boundingBoxList = null;
            List <double>      heightList      = null;

            if (polysurface == null)
            {
                throw new ArgumentNullException(nameof(polysurface));
            }

            solidList = polysurface.ExtractSolids();

            boundingBoxList = solidList.Select(e => e.BoundingBox).ToList();

            heightList = boundingBoxList.Select(b => b.MaxPoint.Z - b.MinPoint.Z).ToList();

            return(new Dictionary <string, object>
            {
                { "solidList", solidList },
                { "boundingBoxList", boundingBoxList },
                { "heightList", heightList }
            });
        }
Пример #21
0
    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.F1))
        {
            SaveVector("currentCenter", currentCenter);
            SaveVector("currentNormal", currentNormal);
            PlayerPrefs.Save();
        }
        if (Input.GetKeyDown(KeyCode.F2))
        {
            currentCenter = LoadVector("currentCenter");
            currentNormal = LoadVector("currentNormal");

            hitLocation.transform.position = currentCenter;
        }

        if (Input.GetKeyDown(KeyCode.F4))
        {
            if (modelStddev == 1)
            {
                modelStddev = 20;
            }
            else
            {
                modelStddev = 1;
            }
        }

        if (Input.GetKeyDown(KeyCode.F5))
        {
            foreach (var go in samples)
            {
                GameObject.Destroy(go);
            }
            samples.Clear();
            GenerateSamples(samplesToGenerate);
        }
        if (Input.GetKeyDown(KeyCode.F6))
        {
            modelName         = modelNames[currentModelIndex];
            currentModelIndex = (currentModelIndex + 1) % modelNames.Length;
        }

        if (Input.GetKeyDown(KeyCode.F7))
        {
            modelVersion             = modelVersions[currentModelVersionIndex].ToString();
            currentModelVersionIndex = (currentModelVersionIndex + 1) % modelVersions.Length;
        }
        if (Input.GetKeyDown(KeyCode.F8))
        {
            foreach (var go in samples)
            {
                GameObject.Destroy(go);
            }
            samples.Clear();
            GetSamplesFromModelCurrentPos();
        }

        surface.renderer.enabled = renderPolySurface;

        var ctrl  = Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl);
        var shift = Input.GetKey(KeyCode.LeftShift);

        pointCloudMaterial.SetFloat("_WeightScale", weightScale);
        pointCloudMaterial.SetFloat("_WeightFactor", weightFactor);

        if (currentPointCloud != null)
        {
            currentVertices = currentPointCloud.vertices;

            if (ctrl && Input.GetMouseButtonDown(1))
            {
                var ray = camera.ScreenPointToRay(Input.mousePosition);
                if (Physics.Raycast(ray, out var hit))
                {
                    camera.transform.parent.position = hit.point;
                }
                else
                {
                    camera.transform.parent.position = Vector3.zero;
                }
            }
            if (!ctrl && Input.GetMouseButton(1))
            {
                var ray = camera.ScreenPointToRay(Input.mousePosition);
                meshCollider.sharedMesh = currentPointCloud.mesh.mesh;
                if (meshCollider.Raycast(ray, out var hit, float.MaxValue))
                {
                    //Debug.Log($"({ray.origin.x}, {ray.origin.y}, {ray.origin.z}), ({ray.direction.x}, {ray.direction.y}, {ray.direction.z})");
                    hitLocation.position = hit.point;
                    currentCenter        = hit.point;
                    currentNormal        = hit.normal;
                    currentVertices      = currentPointCloud.vertices;
                    pointCloudMaterial.SetVector("center", hit.point);

                    //
                    if (currentPointCloud.mesh.coefficients != null)
                    {
                        var uvw = hit.barycentricCoordinate;

                        var coefficientsArray = currentPointCloud.mesh.coefficients;
                        var faces             = currentPointCloud.mesh.faces;

                        float[] c0 = coefficientsArray[faces[hit.triangleIndex * 3 + 0]];
                        float[] c1 = coefficientsArray[faces[hit.triangleIndex * 3 + 1]];
                        float[] c2 = coefficientsArray[faces[hit.triangleIndex * 3 + 2]];

                        float[] coefficients = new float[20];
                        for (int i = 0; i < 20; i++)
                        {
                            coefficients[i] = uvw.x * c0[i] + uvw.y * c1[i] + uvw.z * c2[i];
                        }

                        surface.SetCenter(currentCenter);
                        surface.SetCoefficients(coefficients);
                    }
                }
            }
        }

        if (ctrl && Input.GetMouseButtonDown(0))
        {
            var point = camera.ScreenPointToRay(Input.mousePosition);

            var random = new System.Random();

            currentPath.Clear();
            currentPath.Add(new PathPoint
            {
                position  = point.origin,
                direction = point.direction
            });


            var(dist, _) = PolySurface.RayMarch(coefficients, point.origin, point.direction, 1000.0f, surface.Center);
            var hit = point.origin + (dist + 0.001f) * point.direction;

            int stepCount = 0;
            var exit      = TestDataGenerator.SimulatePath(
                random,
                surface.Coefficients,
                hit, point.direction,
                surface.Center,
                surface.g, surface.SigmaSReduced, surface.sigmaT,
                distScale,
                (p) => currentPath.Add(p),
                ref stepCount);

            if (exit != null)
            {
                currentPath.Add(new PathPoint
                {
                    position  = exit.Value,
                    direction = (exit.Value - currentPath.Last().position).normalized,
                });

                currentPath.Add(new PathPoint
                {
                    position = currentPath.Last().position + currentPath.Last().direction * 10,
                });
            }
        }

        if (process != null && process.HasExited)
        {
            Debug.Log("generator done");

            foreach (var go in samples)
            {
                GameObject.Destroy(go);
            }
            samples.Clear();

            foreach (var sample in samplesTemp)
            {
                var go = GameObject.Instantiate(samplePointPrefab, transform);
                go.transform.position = sample.position;
                samples.Add(go);
            }
            samplesTemp.Clear();
            process = null;
        }

        // generate samples
        if (shift && Input.GetMouseButtonDown(0))
        {
            foreach (var go in samples)
            {
                GameObject.Destroy(go);
            }
            samples.Clear();
            if (sampleSource != SampleSource.Generate && process == null)
            {
                var ray = camera.ScreenPointToRay(Input.mousePosition);
                if (meshCollider.Raycast(ray, out var hit, float.MaxValue))
                {
                    var dir = ray.direction;
                    if (incidentIsNormal)
                    {
                        dir = -hit.normal;
                    }
                    GetSamplesFromModel(hit.point, hit.normal, dir);
                }
            }
        }
        if (shift && Input.GetMouseButton(0))
        {
            if (sampleSource == SampleSource.Generate)
            {
                GenerateSamples();
            }
        }

        for (int i = 0; i < currentPath.Count; i++)
        {
            var p = currentPath[i];

            if (RenderPathAxis)
            {
                if (p.uv != null)
                {
                    var vec = p.right.Value * p.uv.Value.x + p.up.Value * p.uv.Value.y;
                    Debug.DrawRay(p.position, vec * PathAxisLen, Color.yellow, 0, false);
                }
                if (p.right != null)
                {
                    Debug.DrawRay(p.position, p.right.Value * PathAxisLen, Color.red, 0, false);
                }
                if (p.up != null)
                {
                    Debug.DrawRay(p.position, p.up.Value * PathAxisLen, Color.green, 0, false);
                }
                Debug.DrawRay(p.position, p.direction, Color.blue, 0, false);
            }

            if (RenderPath && i < currentPath.Count - 1)
            {
                var col = Color.white;
                if (i == 0)
                {
                    col = Color.cyan;
                }
                else if (i == currentPath.Count - 2)
                {
                    col = Color.magenta;
                }
                Debug.DrawLine(p.position, currentPath[i + 1].position, col, 0, false);
            }
        }
    }
Пример #22
0
    private void GetSamplesFromModel(Vector3 center, Vector3 normal, Vector3 direction)
    {
        Debug.Log("Start generator");
        foreach (var go in samples)
        {
            GameObject.Destroy(go);
        }
        samples.Clear();

        var coefficients = surface.Coefficients.ToArray();

        var normalToZ    = new Frame(normal);
        var zToDirection = new Frame(-direction).Invert();

        TestDataGenerator.RotatePolynomial(coefficients, normalToZ.x, normalToZ.y, normalToZ.z);

        if (!incidentIsNormal)
        {
            TestDataGenerator.RotatePolynomial(coefficients, zToDirection.x, zToDirection.y, zToDirection.z);
        }

        string[] arguments = null;
        string   fileExe   = null;

        var model = string.IsNullOrWhiteSpace(modelVersion) ? $"{modelName}/final" : $"{modelName}/{modelVersion}";

        switch (sampleSource)
        {
        case SampleSource.Cpp:
            fileExe   = @"D:\Bachelorarbeit\CppModelTest\x64\Release\CppModelTest.exe";
            arguments = new string[]
            {
                model,
                samplesToGenerate.ToString(),
                modelStddev.ToString(),
                $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}"
            };
            break;

        case SampleSource.Python:
            fileExe   = "python.exe";
            arguments = new string[]
            {
                @"D:\Bachelorarbeit\Bachelorarbeit\Model\generate_samples.py",
                model,
                samplesToGenerate.ToString(),
                modelStddev.ToString(),
                $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}"
            };
            break;

        default:
            fileExe   = @"D:\Bachelorarbeit\CppModelTest\x64\Release\CppModelTest.exe";
            arguments = new string[]
            {
                model,
                samplesToGenerate.ToString(),
                modelStddev.ToString(),
                $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}"
            };
            break;
        }

        var p = new System.Diagnostics.Process();

        p.StartInfo.FileName               = fileExe;
        p.StartInfo.WindowStyle            = System.Diagnostics.ProcessWindowStyle.Hidden;
        p.StartInfo.WorkingDirectory       = @"D:\Bachelorarbeit\Bachelorarbeit\Model";
        p.StartInfo.UseShellExecute        = false;
        p.StartInfo.CreateNoWindow         = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.Arguments              = string.Join(" ", arguments.Select(a => $"\"{a}\""));

        Debug.Log(p.StartInfo.Arguments);

        var r = new System.Random();

        p.OutputDataReceived += (sender, args) => {
            if (args.Data != null && args.Data.StartsWith("# "))
            {
                var parts = args.Data.Substring(2).Split(',').Select(s => float.Parse(s)).ToArray();
                var pos   = new Vector3(parts[0], parts[1], parts[2]);
                var n     = PolySurface.GetNormalAt(coefficients, pos, Vector3.zero);

                //pos = new Vector3(0, 0, (float)r.NextDouble());

                if (!incidentIsNormal)
                {
                    pos = zToDirection.ToMatrix() * pos;
                    n   = zToDirection.ToMatrix() * n;
                }
                pos = normalToZ.ToMatrix() * pos;
                n   = normalToZ.ToMatrix() * n;

                pos += center;

                samplesTemp.Add(new MeshDBSample
                {
                    position = pos,
                    gradient = n
                });
            }
        };

        p.Start();
        p.BeginOutputReadLine();

        process = p;
    }
Пример #23
0
        /***************************************************/
        /****              Private Methods              ****/
        /***************************************************/

        private static oM.Physical.Elements.Roof SolidRoofFromRevit(this RoofBase roof, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null)
        {
            ISurface location = null;
            List <BH.oM.Physical.Elements.IOpening> openings = new List <oM.Physical.Elements.IOpening>();

            Dictionary <PlanarSurface, List <PlanarSurface> > surfaces = null;
            BoundingBoxXYZ bbox = roof.get_BoundingBox(null);

            if (bbox != null)
            {
                BoundingBoxIntersectsFilter bbif      = new BoundingBoxIntersectsFilter(new Outline(bbox.Min, bbox.Max));
                IList <ElementId>           insertIds = (roof as HostObject).FindInserts(true, true, true, true);
                List <Element> inserts;
                if (insertIds.Count == 0)
                {
                    inserts = new List <Element>();
                }
                else
                {
                    inserts = new FilteredElementCollector(roof.Document, insertIds).WherePasses(bbif).ToList();
                }

                List <FamilyInstance> windows = inserts.Where(x => x is FamilyInstance && x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Windows).Cast <FamilyInstance>().ToList();
                List <FamilyInstance> doors   = inserts.Where(x => x is FamilyInstance && x.Category.Id.IntegerValue == (int)BuiltInCategory.OST_Doors).Cast <FamilyInstance>().ToList();

                surfaces = roof.PanelSurfaces(windows.Union(doors).Select(x => x.Id), settings);
                if (surfaces != null)
                {
                    List <ISurface> locations = new List <ISurface>(surfaces.Keys);
                    if (locations.Count == 1)
                    {
                        location = locations[0];
                    }
                    else
                    {
                        location = new PolySurface {
                            Surfaces = locations
                        }
                    };

                    foreach (List <PlanarSurface> ps in surfaces.Values)
                    {
                        openings.AddRange(ps.Select(x => new BH.oM.Physical.Elements.Void {
                            Location = x
                        }));
                    }

                    foreach (FamilyInstance window in windows)
                    {
                        BH.oM.Physical.Elements.Window bHoMWindow = window.WindowFromRevit(roof, settings, refObjects);
                        if (bHoMWindow != null)
                        {
                            openings.Add(bHoMWindow);
                        }
                    }

                    foreach (FamilyInstance door in doors)
                    {
                        BH.oM.Physical.Elements.Door bHoMDoor = door.DoorFromRevit(roof, settings, refObjects);
                        if (bHoMDoor != null)
                        {
                            openings.Add(bHoMDoor);
                        }
                    }
                }
            }

            if (surfaces == null || surfaces.Count == 0)
            {
                roof.NoPanelLocationError();
            }

            return(new oM.Physical.Elements.Roof {
                Location = location, Openings = openings
            });
        }
Пример #24
0
        /***************************************************/

        public static List <ICurve> InternalEdges(this PolySurface surface)
        {
            return(surface.Surfaces.SelectMany(x => x.IInternalEdges()).ToList());
        }
Пример #25
0
        /***************************************************/

        public static double Area(this PolySurface pSurf)
        {
            return(pSurf.Surfaces.Sum(x => x.IArea()));
        }
Пример #26
0
        /***************************************************/

        public static PolySurface Scale(this PolySurface surface, Point origin, Vector scaleVector)
        {
            TransformMatrix scaleMatrix = Create.ScaleMatrix(origin, scaleVector);

            return(Transform(surface, scaleMatrix));
        }
Пример #27
0
        /***************************************************/

        public static PolySurface Translate(this PolySurface surface, Vector transform)
        {
            return(new PolySurface {
                Surfaces = surface.Surfaces.Select(x => x.ITranslate(transform)).ToList()
            });
        }
Пример #28
0
        private static int GetIntersection(Surface face, List <Surface> surfaces, Point point, double offset, ref List <Curve> curves, bool reverse)
        {
            Surface my = face;

            if (face.GetType() == typeof(PolySurface))
            {
                PolySurface poly = (PolySurface)face;
                foreach (Surface s in poly.Surfaces())
                {
                    UV coords = s.UVParameterAtPoint(point);
                    if (coords != null && coords.U >= 0 && coords.U <= 1 && coords.V >= 0 && coords.V <= 1)
                    {
                        my = s;
                    }
                }
            }

            // Get the Normal at that point
            Vector normal = my.NormalAtPoint(point);



            // Remove Z Value in order to create horizontal normals
            Vector optimizedNormal = (reverse) ? normal.Reverse() : normal;
            // Vector.ByCoordinates(normal.X, normal.Y, 0).Reverse() : Vector.ByCoordinates(normal.X, normal.Y, 0);

            // Get an startpoint offset if it applies
            Point startPoint = point;

            if (offset != 0)
            {
                Line offsetLine = Line.ByStartPointDirectionLength(point, optimizedNormal, offset);
                startPoint = offsetLine.EndPoint;
            }

            // Create an almost endless line
            Line line = Line.ByStartPointDirectionLength(startPoint, optimizedNormal, 100000000);

            // Get intersection points with boundary surfaces
            List <double> intersections = line.Insersection(surfaces);

            // If there are any intersections
            if (intersections.Count > 1)
            {
                // trim the curve into segments if there are gaps or holes
                Curve[] segments = line.ParameterTrimSegments(intersections.ToArray(), false);

                // Walk through trimmed curves and add only those to the return collection
                // which are of a reasonable length
                foreach (Curve segment in segments)
                {
                    //if (segment.Length < 100000)
                    curves.Add(segment);
                }
            }
            else if (intersections.Count == 1)
            {
                Curve[] segments = line.ParameterSplit(intersections[0]);
                curves.Add(segments[0]);
            }

            return(intersections.Count);
        }
Пример #29
0
        /***************************************************/

        public static PolySurface ProjectAlong(this PolySurface surface, Plane plane, Vector vector)
        {
            return(new PolySurface {
                Surfaces = surface.Surfaces.Select(x => x.IProjectAlong(plane, vector)).ToList()
            });
        }
Пример #30
0
 public static Point ClosestPoint(this PolySurface surface, Point point)
 {
     throw new NotImplementedException();
 }
Пример #31
0
        /***************************************************/

        public static PolySurface Project(this PolySurface surface, Plane p)
        {
            return(new PolySurface {
                Surfaces = surface.Surfaces.Select(x => x.IProject(p)).ToList()
            });
        }