예제 #1
0
        public void constructor_default() {
            var p = new Point3();

            Assert.Equal(0, p.X);
            Assert.Equal(0, p.Y);
            Assert.Equal(0, p.Z);
        }
예제 #2
0
		public RenderItem CalculateHit (Ray ray, out double tHit, double maxT) {
			Point3 inter = new Point3(ray.Offset);
			double t = 0.0d;
			tHit = maxT;
			if(x0 > inter.X || inter.X > x1 || y0 > inter.Y || inter.Y > y1 || z0 > inter.Z || inter.Z > z1) {
				Utils.CalculateBoxHitpoint(ray, inter, out t, this.x0, this.x1, this.y0, this.y1, this.z0, this.z1);
				if(t >= tHit) {
					return null;
				}
			}
			RenderItem ri = null;
			double[] seqxyz = new double[] {
				Maths.SoftInv(ray.DX),
				Maths.SoftInv(ray.DY),
				Maths.SoftInv(ray.DZ),
				x0,
				x1,
				x1,
				y0,
				y1,
				y1,
				z0,
				z1,
				z1
			};
			int dpos = Maths.BinarySign(ray.DX)|(Maths.BinarySign(ray.DY)<<0x02)|(Maths.BinarySign(ray.DZ)<<0x04);
			proceedSubTree(ray, dpos, seqxyz, inter, ref ri, ref t, ref tHit, this.root);
			return ri;
		}
예제 #3
0
 public Voxel AddBlock(Point3 localBlockCoord)
 {
     voxels[localBlockCoord.x,
            localBlockCoord.y,
            localBlockCoord.z] = new Voxel();
     return Get(localBlockCoord);
 }
예제 #4
0
 public static Voxel GetBlock(Point3 worldBlockCoord)
 {
     Chunk chunk = GetChunk(worldBlockCoord);
     return chunk != null
         ? chunk.Get(worldBlockCoord.ToLocalBlockCoord())
         : null;
 }
        public static List<IPolyline3> CreatingPolyLineListWhenWellHasPerforations(Borehole bh)
        {
            List<IPolyline3> plineList = new List<IPolyline3>();

            foreach (Perforation prf in bh.Completions.Perforations)
            {
                double x1 = bh.Transform(Domain.MD, prf.StartMD, Domain.X);
                double y1 = bh.Transform(Domain.MD, prf.StartMD, Domain.Y);
                double z1 = bh.Transform(Domain.MD, prf.StartMD, Domain.ELEVATION_DEPTH);

                List<Point3> ptsList = new List<Point3>();
                Point3 pt3_1 = new Point3(x1, y1, z1);
                ptsList.Add(pt3_1);

                double x2 = bh.Transform(Domain.MD, prf.EndMD, Domain.X);
                double y2 = bh.Transform(Domain.MD, prf.EndMD, Domain.Y);
                double z2 = bh.Transform(Domain.MD, prf.EndMD, Domain.ELEVATION_DEPTH);

                Point3 pt3_2 = new Point3(x2, y2, z2);

                double xmiddle = (x1 + x2)/2;
                double ymiddle = (y1 + y2) / 2;
                double zmiddle = (z1 + z2) / 2;

                Point3 pt3_3 = new Point3(xmiddle, ymiddle, zmiddle);
                ptsList.Add(pt3_3);
                ptsList.Add(pt3_2);

                IPolyline3 pline = new Polyline3(ptsList);

                plineList.Add(pline);
            }

            return plineList;
        }
예제 #6
0
 public void coordinate_triple_coordinate_get_test() {
     ICoordinateTriple<double> p = new Point3(3, 4, 5);
     var a = new Vector3(p);
     Assert.Equal(3, a.X);
     Assert.Equal(4, a.Y);
     Assert.Equal(5, a.Z);
 }
예제 #7
0
 /// <summary>
 /// Multiplies the point by the specified matrix.
 /// </summary>
 internal static Point3 Multiply(Matrix m, Point3 p)
 {
     return new Point3(
         m.m11 * p.X + m.m12 * p.Y + m.m13 * p.Z,
         m.m21 * p.X + m.m22 * p.Y + m.m23 * p.Z,
         m.m31 * p.X + m.m32 * p.Y + m.m33 * p.Z);
 }
예제 #8
0
 public void Copy(double t, Point3 norm, double tu, double tv)
 {
     this.T = t;
     this.Normal.SetValues(norm);
     this.TU.X = tu;
     this.TU.Y = tv;
 }
예제 #9
0
 public ProxyTriangle(RenderItem t, Point3 pa, Point3 pb, Point3 pc)
     : base(t)
 {
     this.pa = pa;
     this.pb = pb;
     this.pc = pc;
 }
예제 #10
0
        public Quadrilateral(Point3 TopLeftIn, Point3 TopRightIn, Point3 BottomLeftIn, Point3 BottomRightIn)
        {
            this.TopLeft = TopLeftIn;
            this.TopRight = TopRightIn;
            this.BottomLeft = BottomLeftIn;
            this.BottomRight = BottomRightIn;

            Plane3 plane = new Plane3(this.TopLeft, this.TopRight, this.BottomLeft);
            //Vector3 ab = new Vector3(new Segment3(this.BottomLeft, this.TopLeft));
            //Vector3 ac = new Vector3(new Segment3(this.BottomLeft, this.BottomRight));
            //Vector3 normal = Vector3.Cross(ab, ac);
            //Vector3 ad = new Vector3(new Segment3(this.BottomLeft, this.TopRight));
            //double dotp = Vector3.Dot(ad, normal);

            //PetrelLogger.InfoOutputWindow("The dot product of this cell's face is " + System.Convert.ToString(dotp));

            if (Plane3Extensions.Contains(plane,this.BottomRight, 1E-7))
            {
                LeftSegment = new Segment3(this.TopLeft, this.BottomLeft);
                RightSegment = new Segment3(this.TopRight, this.BottomRight);
                BottomSegment = new Segment3(this.BottomLeft, this.BottomRight);
                TopSegment = new Segment3(this.TopLeft, this.TopRight);

                CalculateCentroid();
            }
            else
            {   double x = (this.TopLeft.X + this.BottomLeft.X + this.TopRight.X + this.BottomRight.X) / 4.0;
                double y = (this.TopLeft.Y + this.BottomLeft.Y + this.TopRight.Y + this.BottomRight.Y) / 4.0;
                double z = (this.TopLeft.Z + this.BottomLeft.Z + this.TopRight.Z + this.BottomRight.Z) / 4.0;

                this.Centroid = new Point3(x,y,z);
            }
        }
예제 #11
0
 public override void Load(string currentDir, string filename)
 {
     TreeNode<string> tree = filename.ParseTreeBracketsComma();
     if(tree.Count < 0x03) {
         pa = Point3.DummyPoint;
         pb = Point3.DummyXPoint;
         pc = Point3.DummyYPoint;
     }
     else {
         pa = Point3.Parse(tree[0x00].ChildDatas);
         pb = Point3.Parse(tree[0x01].ChildDatas);
         pc = Point3.Parse(tree[0x02].ChildDatas);
     }
     if(tree.Count >= 0x06) {
         na = Point3.Parse(tree[0x03].ChildDatas);
         nb = Point3.Parse(tree[0x04].ChildDatas);
         nc = Point3.Parse(tree[0x05].ChildDatas);
     }
     if(tree.Count >= 0x09) {
         ta = Point3.Parse(tree[0x06].ChildDatas);
         tb = Point3.Parse(tree[0x07].ChildDatas);
         tc = Point3.Parse(tree[0x08].ChildDatas);
     }
     else {
         ta = Point3.DummyYPoint;
         tb = Point3.DummyPoint;
         tc = Point3.DummyXPoint;
     }
 }
예제 #12
0
        bool IGeometryGeneratorSource.CanBuildSide(BlockData me, BlockData side, Point3 mePos, Point3 sidePos)
        {
            if (IsFence(side))
                return false;

            return !side.IsSolid;
        }
 public RenderItem CalculateHit(Ray ray, out double tHit, double maxT)
 {
     Point3 inter = new Point3(ray.Offset);
     tHit = maxT;
     double t = 0.0d;
     if(x0 > inter.X || inter.X > x1 || y0 > inter.Y || inter.Y > y1 || z0 > inter.Z || inter.Z > z1) {
         Utils.CalculateBoxHitpoint(ray, inter, out t, this.x0, this.x1, this.y0, this.y1, this.z0, this.z1);
         if(t > maxT) {
             return null;
         }
     }
     Point3 inter2 = new Point3(Maths.ZeroInv(ray.DX), Maths.ZeroInv(ray.DY), Maths.ZeroInv(ray.DZ));
     double tt = Maths.SoftInv(ray.DX)*(box[Maths.BinarySign(ray.DX)]-ray.X0);
     if(tt < tHit) {
         tHit = tt;
     }
     tt = Maths.SoftInv(ray.DY)*(box[Maths.BinarySign(ray.DY)+0x02]-ray.Y0);
     if(tt < tHit) {
         tHit = tt;
     }
     tt = Maths.SoftInv(ray.DZ)*(box[Maths.BinarySign(ray.DZ)+0x04]-ray.Z0);
     if(tt < tHit) {
         tHit = tt;
     }
     RenderItem ri = null;
     this.root.Hit(ray, inter2, inter, ref t, ref tHit, ref ri);
     return ri;
 }
예제 #14
0
        public void constructor_coordinates() {
            var p = new Point3(1, 2, 3);

            Assert.Equal(1, p.X);
            Assert.Equal(2, p.Y);
            Assert.Equal(3, p.Z);
        }
        //public static Slb.Ocean.Petrel.DomainObject.PillarGrid.Zone GetZone(Index3 cellIndex, List<Slb.Ocean.Petrel.DomainObject.PillarGrid.Zone> Zones)//List<Slb.Ocean.Petrel.DomainObject.PillarGrid.Zone> TopZone)
        //{
        //    foreach (Slb.Ocean.Petrel.DomainObject.PillarGrid.Zone zone in Zones)
        //    {
        //        if (cellIndex.K > zone.BaseK && cellIndex.K)
        //       {
        //       }
        //    }
        //}
        public static Point3[] GetCornerSet(CellSide SideOfCell, Grid gridInContext, Index3 CellIndex)
        {
            CellCorner[] CellCorners = new CellCorner[4];
            Point3[] CellCornerPoints = new Point3[4];

            switch (SideOfCell)
            {
                case CellSide.Up:
                    CellCorners[0] = CellCorner.TopNorthWest; CellCorners[1] = CellCorner.TopNorthEast; CellCorners[2] = CellCorner.TopSouthWest;
                    CellCorners[3] = CellCorner.TopSouthEast;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;

                case CellSide.East:
                    CellCorners[0] = CellCorner.TopSouthEast; CellCorners[1] = CellCorner.TopNorthEast; CellCorners[2] = CellCorner.BaseSouthEast;
                    CellCorners[3] = CellCorner.BaseNorthEast;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;

                case CellSide.West:

                    CellCorners[0] = CellCorner.TopSouthWest; CellCorners[1] = CellCorner.TopNorthWest; CellCorners[2] = CellCorner.BaseSouthWest;
                    CellCorners[3] = CellCorner.BaseNorthWest;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;

                case CellSide.South:
                    CellCorners[0] = CellCorner.TopSouthWest; CellCorners[1] = CellCorner.TopSouthEast; CellCorners[2] = CellCorner.BaseSouthWest;
                    CellCorners[3] = CellCorner.BaseSouthEast;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;

                case CellSide.North:

                    CellCorners[0] = CellCorner.TopNorthWest; CellCorners[1] = CellCorner.TopNorthEast; CellCorners[2] = CellCorner.BaseNorthWest;
                    CellCorners[3] = CellCorner.BaseNorthEast;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;

                case CellSide.Down:

                    CellCorners[0] = CellCorner.BaseNorthWest; CellCorners[1] = CellCorner.BaseNorthEast; CellCorners[2] = CellCorner.BaseSouthWest;
                    CellCorners[3] = CellCorner.BaseSouthEast;
                    CellCornerPoints = gridInContext.GetCellCorners(CellIndex, CellCorners);

                    break;
                default:

                    CellCornerPoints = null;
                    break;
            }

            return CellCornerPoints;
        }
예제 #16
0
        public override List<CustomBlockData> GenerateModel(byte metadata, BlockData me, BlockData Xpos, BlockData Xneg, BlockData Ypos, BlockData Yneg, BlockData Zpos, BlockData Zneg, BlockSource source, Point3 blockPosition)
        {
            List<CustomBlockData> dat = new List<CustomBlockData>();

            float s = 0.707f;
            Vector3 d = new Vector3(-0.02f, 0, -0.02f);

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(0, s, 0) - d,
                Vertex2 = new Vector3(s, s, s) - d,
                Vertex3 = new Vector3(s, 0, s) - d,
                Vertex4 = new Vector3(0, 0, 0) - d,

                Normal = new Vector3(1, 0, 1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(0, s, 0) - d,
                Vertex2 = new Vector3(s, s, s) - d,
                Vertex3 = new Vector3(s, 0, s) - d,
                Vertex4 = new Vector3(0, 0, 0) - d,

                TriFlip = true,

                Normal = new Vector3(-1, 0, -1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(s, s, 0),
                Vertex2 = new Vector3(0, s, s),
                Vertex3 = new Vector3(0, 0, s),
                Vertex4 = new Vector3(s, 0, 0),

                TriFlip = true,

                Normal = new Vector3(-1, 0, 1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            dat.Add(new CustomBlockData()
            {
                Vertex1 = new Vector3(s, s, 0),
                Vertex2 = new Vector3(0, s, s),
                Vertex3 = new Vector3(0, 0, s),
                Vertex4 = new Vector3(s, 0, 0),

                TriFlip = true,

                Normal = new Vector3(1, 0, -1),
                Texture = Textures.GetTexturesForMetadata(metadata)[0]
            }.CreateUVsYFlipped());

            return dat;
        }
예제 #17
0
 public VoxelListener(ComponentManager manager, GameComponent parent, ChunkManager chunkManager, Voxel vref)
     : base("VoxelListener", parent)
 {
     Chunk = vref.Chunk;
     VoxelID = new Point3(vref.GridPosition);
     Chunk.OnVoxelDestroyed += VoxelListener_OnVoxelDestroyed;
     ChunkID = Chunk.ID;
 }
        public SecondaryObservationRoom(Puzzle owner) : base(owner)
        {
            defaultRight = Direction.Y;

            Type = TypeName;
            deletable = true;
            angles = new Point3(-90, 0, 0);
        }
예제 #19
0
        public Creeper(Point3 pos, World level)
        {
            mye = new Entity(this, level);
            mylevel = level;
            e.pos = pos;

            e.UpdateChunks(false, false);
        }
 /// <summary>
 /// Copies the end position in the start position, updates the current position
 /// </summary>
 public void Step( long curTime )
 {
     m_Start				= m_End;
     m_End				= new Point3( m_End );
     m_LastStepInterval	= ( curTime - m_LastStepTime );
     m_LastStepTime		= curTime;
     UpdateCurrent( curTime );
 }
예제 #21
0
 public static Voxel[] GetNeighbours(Point3 worldCoord)
 {
     Voxel[] neighbours = new Voxel[6];
     for (int i=0; i<checkSides.Length; i++) {
         neighbours[i] = ChunkManager.GetBlock(worldCoord + checkSides[i]);
     }
     return neighbours;
 }
예제 #22
0
 public override void Inject(List<RenderItem> items, Matrix4 transform, params string[] args)
 {
     Point3 p = new Point3(0.0d, 0.0d, 0.0d);
     p.Transform(transform);
     Point3 q = new Point3(Maths.Sqrt_3, Maths.Sqrt_3, Maths.Sqrt_3);
     q.TransformNonShift(transform);
     items.Add(new Sphere(p, q.Length, this.DefaultMaterial));
 }
 public BCS(Point3 pos, short id, byte direction)
 {
     this.pos = pos;
     ID = id;
     Direction = direction;
     Amount = 0;
     Damage = 0;
 }
 public BCS(Point3 pos, short id, byte direction, byte amount, short damage)
 {
     this.pos = pos;
     ID = id;
     Direction = direction;
     Amount = amount;
     Damage = damage;
 }
예제 #25
0
파일: Sphere.cs 프로젝트: KommuSoft/MoRen
 public Sphere(Point3 center, double radius, Material material)
     : base(material)
 {
     this.Center = center;
     this.Radius = radius;
     this.Rinv = 1.0d/Radius;
     this.material = material;
 }
 public ContainerChest(World level, Point3 point)
 {
     this.level = level;
     this.point = point;
     items = new Item[Size];
     for (int i = 0; i < Size; i++)
         items[i] = Item.Nothing;
 }
예제 #27
0
        public void cast_vector() {
            var a = new Point3(2, 3, 4);

            Vector3 b = a;
            Point3 c = b;

            Assert.Equal(a.X, c.X);
            Assert.Equal(a.Y, c.Y);
        }
예제 #28
0
        static bool IsContaining(int x1, int y1, int x2, int y2, int x3, int y3)
        {
            var a = new Point3(x1, y1, 0);
            var b = new Point3(x2, y2, 0);
            var c = new Point3(x3, y3, 0);

            var p = new Point3(0,0,0);
            return SameSide(p, a, b, c) && SameSide(p, b, a, c) && SameSide(p, c, a, b);
        }
예제 #29
0
파일: Perlin.cs 프로젝트: KommuSoft/MoRen
 public static Color Marble3(Point3 xyz)
 {
     double sum = 0.0d;
     for(int i = 0x01; i < 0x20; i++) {
         sum += Math.Abs(Perlin3d(xyz.X*i, xyz.Y*i, xyz.Z*i))/i;
     }
     double g = Math.Sin(sum);
     return new Color((uint)Utils.FloatIndex(marbleGradient, g));
 }
예제 #30
0
 public void Copy(double t, double nx, double ny, double nz, double tu, double tv, double tw, Point3 bumpX, Point3 bumpY)
 {
     this.T = t;
     this.Normal.SetValues(nx, ny, nz);
     this.TU.X = tu;
     this.TU.Y = tv;
     this.TU.Z = tw;
     this.BumpX = bumpX;
     this.BumpY = bumpY;
 }
        public void RemoveFire(int x, int y, int z)
        {
            Point3 key = new Point3(x, y, z);

            m_fireData.Remove(key);
        }
 /// <summary>
 /// Gets the dot product of two vectors.
 /// </summary>
 /// <param name="left"></param>
 /// <param name="right"></param>
 /// <returns></returns>
 public static double DotProduct(Point3 left, Point3 right)
 {
     return(left.X * right.X
            + left.Y * right.Y
            + left.Z * right.Z);
 }
예제 #33
0
    public static Point2 CurrentChunk()
    {
        Point3 p = TerrainRaycast.ToCell(Camera.main.transform.position);

        return(ToChunk(p.X, p.Z));
    }
예제 #34
0
    // Update is called once per frame
    void Update()
    {
        //if (AppMgr.pts == null) return;
        //if (AppMgr.lns == null) return;
        gameObject.SetActive(Active);
        ///Debug.Log(PointId);
        if (Point1 != null && Point2 != null && Point3 != null)
        {
            Vec1   = Point1.GetComponent <Point>().transform.position;
            Vec1.z = 0.0f;
            Vec2   = Point2.GetComponent <Point>().transform.position;
            Vec2.z = 0.0f;
            Vec3   = Point3.GetComponent <Point>().transform.position;
            Vec3.z = 0.0f;
        }
        else
        {
            GameObject[] OBJs    = FindObjectsOfType <GameObject>();
            GameObject   LineObj = null;
            Line         LN      = null;
            for (int i = 0; i < OBJs.Length; i++)
            {
                LN = OBJs[i].GetComponent <Line>();
                if (LN != null)
                {
                    if (LN.Id == LineId)
                    {
                        LineObj = OBJs[i];
                        break;
                    }
                }
            }
            if (LineObj == null)
            {
                Active = false;
                LineId = -1;
            }
            else
            {
                Point1 = Point2 = Point3 = null;
                for (int i = 0; i < OBJs.Length; i++)
                {
                    Point PT = OBJs[i].GetComponent <Point>();
                    if (PT != null)
                    {
                        if (PT.Id == PointId)
                        {
                            Point2 = OBJs[i];
                            Vec2   = PT.transform.position;
                            Vec2.z = 0.0f;
                        }
                        if (PT.Id == LN.Point1Id)
                        {
                            Point1 = OBJs[i];
                            Vec1   = PT.transform.position;
                            Vec1.z = 0.0f;
                        }
                        if (PT.Id == LN.Point2Id)
                        {
                            Point3 = OBJs[i];
                            Vec3   = PT.transform.position;
                            Vec3.z = 0.0f;
                        }
                    }
                }
                if (Point1 == null || Point2 == null || Point3 == null)
                {
                    Active = false;
                }
            }
        }
        LR = GetComponent <LineRenderer>();
        LR.SetPosition(0, Vec1);
        LR.SetPosition(1, Vec2);
        LR.SetPosition(2, Vec3);
        Renderer RD = GetComponent <LineRenderer>();

        RD.material.color = StandardColor;
    }
예제 #35
0
        public void MeshLoadProfiling()
        {
            var k3d    = new Toolkit();
            var logger = new MessageLogger();

            int    nBeams      = 20;
            int    nFaces      = 1500;
            double lengthBeams = 10.0;
            double xIncBeam    = lengthBeams / nBeams;
            double xIncMesh    = lengthBeams / nFaces;
            double limit_dist  = xIncBeam / 100.0;

            // create beams
            var lines = new List <Line3>();
            var nodeI = new Point3(0, 0, 0);

            for (int beamInd = 0; beamInd < nBeams; ++beamInd)
            {
                var nodeK = new Point3(nodeI.X + xIncBeam, 0, 0);
                lines.Add(new Line3(nodeI, nodeK));
                nodeI = nodeK;
            }

            var builderElements = k3d.Part.LineToBeam(lines, new List <string>(), new List <CroSec>(), logger, out List <Point3> outPoints);

            // create a MeshLoad
            var mesh = new Mesh3((nFaces + 1) * 2, nFaces);

            mesh.AddVertex(new Point3(0, -0.5, 0));
            mesh.AddVertex(new Point3(0, 0.5, 0));
            for (var faceInd = 0; faceInd < nFaces; ++faceInd)
            {
                mesh.AddVertex(new Point3((faceInd + 1) * xIncMesh, -0.5, 0));
                mesh.AddVertex(new Point3((faceInd + 1) * xIncMesh, 0.5, 0));
                var nV = mesh.Vertices.Count;
                mesh.AddFace(nV - 4, nV - 3, nV - 1, nV - 2);
            }
            UnitsConversionFactory ucf = UnitsConversionFactories.Conv();
            UnitConversion         m   = ucf.m();
            var baseMesh = m.toBaseMesh(mesh);

            // create a mesh load
            var load = k3d.Load.MeshLoad(new List <Vector3>()
            {
                new Vector3(0, 0, -1)
            }, baseMesh);

            // create a support
            var support = k3d.Support.Support(new Point3(0, 0, 0), k3d.Support.SupportFixedConditions);

            // assemble the model
            var model = k3d.Model.AssembleModel(builderElements, new List <Support>()
            {
                support
            }, new List <Load>()
            {
                load
            },
                                                out var info, out var mass, out var cog, out var message, out var runtimeWarning);

            // calculate the model
            model = k3d.Algorithms.AnalyzeThI(model, out var outMaxDisp, out var outG, out var outComp, out var warning);
            Assert.AreEqual(outMaxDisp[0], 2.8232103119228276, 1E-5);
        }
예제 #36
0
        private Matrix <double> GetCameraRotation(Image <Gray, float> depthImage)
        {
            //time filter
            if (!dataReady)
            {
                depthImage1 = depthImage2 = depthImage3 = depthImage4 = depthImage;
                dataReady   = true;
            }
            depthImage0 = depthImage;
            depthImage  = (depthImage0 + depthImage1 + depthImage2 + depthImage3 + depthImage4) / 5.0;
            depthImage4 = depthImage3; depthImage3 = depthImage2; depthImage2 = depthImage1; depthImage1 = depthImage0;

            //median filter
            depthImage = depthImage.SmoothMedian(3);

            //subImage  !! depthImage.Data [240,320,1] !!
            int padding        = 8;
            int widthSubImage  = (int)Math.Ceiling(depthImage.Width * (1.0 - (2.0 / padding)));
            int heightSubImage = (int)Math.Ceiling(depthImage.Height * (1.0 - (2.0 / padding)));
            int originalX      = (int)Math.Ceiling(depthImage.Width * (1.0 / padding));
            int originalY      = (int)Math.Ceiling(depthImage.Height * (1.0 / padding));
            Image <Gray, float> depthImageSub = new Image <Gray, float>(widthSubImage, heightSubImage);

            for (int j = 0; j < heightSubImage; j++)
            {
                for (int i = 0; i < widthSubImage; i++)
                {
                    depthImageSub.Data[j, i, 0] = depthImage.Data[originalY + j, originalX + i, 0];
                }
            }

            //sampling
            //convent to world coordinates
            //move coordinate original to center
            int    samplingSpace    = 3;
            int    widthSampling    = widthSubImage / samplingSpace;
            int    heightSampling   = heightSubImage / samplingSpace;
            double focalLengthDepth = depthImage.Width / (2 * Math.Tan((double)(74 * 3.14 / 180) / 2));

            float[, ,] depthData = depthImageSub.Data;
            Point3[] depthDataSamples = new Point3[widthSampling * heightSampling];
            for (int j = 0; j < heightSampling; j++)
            {
                for (int i = 0; i < widthSampling; i++)
                {
                    float z = Math.Abs(depthData[samplingSpace * j, samplingSpace * i, 0]);
                    float x = (float)((originalX + i * samplingSpace - depthImage.Width / 2.0) * z / focalLengthDepth);
                    float y = (float)((originalY + j * samplingSpace - depthImage.Height / 2.0) * z / focalLengthDepth);
                    depthDataSamples[j * widthSampling + i] = new Point3(x, y, z);
                }
            }
            //Ransac
            Stopwatch      sw             = Stopwatch.StartNew();
            RansacFitPlane ransacFitPlane = new RansacFitPlane(depthDataSamples, 5, 20);
            Plane          plane          = ransacFitPlane.FitPlane();

            if (plane != null)
            {
                Console.WriteLine(plane.A / plane.Offset + " " + plane.B / plane.Offset + " " + plane.C / plane.Offset + " " + plane.Offset);

                //calc rotation matrix
                double[] eula = { Math.Atan((plane.B) / (plane.C)), -Math.Atan((plane.A) / (plane.C)), 0 };
                Console.WriteLine("Xaxis: " + Math.Atan((plane.B) / (plane.C)) * 180 / Math.PI + " Yaxis: " + Math.Atan((plane.A) / (plane.C)) * 180 / Math.PI);
                //avoid shaking
                if (Math.Abs(eula0[0] - eula[0]) > 2 * Math.PI / 180 || Math.Abs(eula0[1] - eula[1]) > 2 * Math.PI / 180)
                {
                    shakeNum++;
                    if (shakeNum == 5)
                    {
                        shakeNum = 0;
                        eula0[0] = eula[0]; eula0[1] = eula[1];
                    }
                }
                else
                {
                    shakeNum = 0;
                }
                cameraRotation = RansacFitPlane.EulaArray2Matrix(eula0);
                Console.WriteLine("time: " + sw.ElapsedMilliseconds);
            }
            return(cameraRotation);
        }
            /// <summary>
            /// Returns the vector normalized with its length.
            /// </summary>
            /// <param name="vector"></param>
            /// <returns></returns>
            public static Point3 Normalize(Point3 vector)
            {
                double length = GetLength(vector);

                return(vector / length);
            }
 /// <summary>
 /// Returns a vector from the starting point to the end point normalized by its length.
 /// </summary>
 /// <param name="startPoint"></param>
 /// <param name="endPoint"></param>
 /// <returns></returns>
 public static Point3 GetNormalizedVector(Point3 startPoint, Point3 endPoint)
 {
     return(Normalize(GetVector(startPoint, endPoint)));
 }
예제 #39
0
 public static extern void GetPoint3BOut(bool e00, bool e01, bool e02, out Point3 <bool> value);
 /// <summary>
 /// 球体
 /// </summary>
 /// <param name="Start"></param>
 /// <param name="End"></param>
 /// <param name="Hollow"></param>
 /// <returns></returns>
 public IEnumerable <Point3> Sphere(Point3 Start, Point3 End, bool Hollow = false)
 {
     throw new Exception("no way");
 }
 /// <summary>
 /// 棱体
 /// </summary>
 /// <param name="Position"></param>
 /// <param name="Radius"></param>
 /// <param name="Hollow"></param>
 /// <param name="creatorType"></param>
 /// <param name="XYZtype"></param>
 /// <param name="typeBool"></param>
 /// <returns></returns>
 public IEnumerable <Point3> Prism(Point3 Position, int Radius, CreatorMain.CreatorType creatorType = CreatorMain.CreatorType.Y, bool Hollow = false, CreatorMain.CreatorType?XYZtype = null, bool typeBool = false)
 {
     for (int x = -Radius; x <= Radius; x++)
     {
         for (int y = -Radius; y <= Radius; y++)
         {
             for (int z = -Radius; z <= Radius; z++)
             {
                 if (XYZtype.HasValue)
                 {
                     if (XYZtype == CreatorMain.CreatorType.X)
                     {
                         if (typeBool)
                         {
                             if (Position.X + x < Position.X)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.X + x > Position.X)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZtype == CreatorMain.CreatorType.Y)
                     {
                         if (typeBool)
                         {
                             if (Position.Y + y < Position.Y)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Y + y > Position.Y)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZtype == CreatorMain.CreatorType.Z)
                     {
                         if (typeBool)
                         {
                             if (Position.Z + z < Position.Z)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Z + z > Position.Z)
                             {
                                 continue;
                             }
                         }
                     }
                 }
                 if (creatorType == CreatorMain.CreatorType.Y)
                 {
                     if ((Math.Abs(x) + Math.Abs(y) > Radius || Math.Abs(z) + Math.Abs(y) > Radius) || (Hollow && Math.Abs(x) + Math.Abs(y) < Radius && Math.Abs(z) + Math.Abs(y) < Radius))
                     {
                         continue;
                     }
                 }
                 if (creatorType == CreatorMain.CreatorType.X)
                 {
                     if ((Math.Abs(x) + Math.Abs(y) > Radius || Math.Abs(z) + Math.Abs(x) > Radius) || (Hollow && Math.Abs(x) + Math.Abs(y) < Radius && Math.Abs(x) + Math.Abs(z) < Radius))
                     {
                         continue;
                     }
                 }
                 if (creatorType == CreatorMain.CreatorType.Z)
                 {
                     if ((Math.Abs(z) + Math.Abs(y) > Radius || Math.Abs(z) + Math.Abs(x) > Radius) || (Hollow && Math.Abs(z) + Math.Abs(y) < Radius && Math.Abs(z) + Math.Abs(x) < Radius))
                     {
                         continue;
                     }
                 }
                 yield return(new Point3(Position.X + x, Position.Y + y, Position.Z + z));
             }
         }
     }
 }
        /// <summary>
        /// 球体
        /// </summary>
        /// <param name="Position"></param>
        /// <param name="Radius"></param>
        /// <param name="Hollow"></param>
        /// <param name="XYZType"></param>
        /// <param name="typeBool"></param>
        /// <returns></returns>
        public IEnumerable <Point3> Sphere(Point3 Position, int Radius, bool Hollow = false, CreatorMain.CreatorType?XYZType = null, bool typeBool = false)
        {
            int MRadius = Radius * Radius;

            for (int x = -Radius; x <= Radius; x++)
            {
                for (int y = -Radius; y <= Radius; y++)
                {
                    for (int z = -Radius; z <= Radius; z++)
                    {
                        if (x * x + y * y + z * z <= MRadius)
                        {
                            if (XYZType.HasValue)
                            {
                                if (XYZType == CreatorMain.CreatorType.X)
                                {
                                    if (typeBool)
                                    {
                                        if (Position.X + x < Position.X)
                                        {
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        if (Position.X + x > Position.X)
                                        {
                                            continue;
                                        }
                                    }
                                }
                                else if (XYZType == CreatorMain.CreatorType.Y)
                                {
                                    if (typeBool)
                                    {
                                        if (Position.Y + y < Position.Y)
                                        {
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        if (Position.Y + y > Position.Y)
                                        {
                                            continue;
                                        }
                                    }
                                }
                                else if (XYZType == CreatorMain.CreatorType.Z)
                                {
                                    if (typeBool)
                                    {
                                        if (Position.Z + z < Position.Z)
                                        {
                                            continue;
                                        }
                                    }
                                    else
                                    {
                                        if (Position.Z + z > Position.Z)
                                        {
                                            continue;
                                        }
                                    }
                                }
                            }
                            if (Hollow && (Math.Abs(x) + 1) * (Math.Abs(x) + 1) + y * y + z * z <= MRadius && x * x + (Math.Abs(y) + 1) * (Math.Abs(y) + 1) + z * z <= MRadius && x * x + y * y + (Math.Abs(z) + 1) * (Math.Abs(z) + 1) <= MRadius)
                            {
                                continue;
                            }
                            yield return(new Point3(Position.X + x, Position.Y + y, Position.Z + z));
                        }
                    }
                }
            }
        }
예제 #43
0
        public RealtimeBenchmark(bool showGUI, int threads)
        {
            IDisplay display = /*showGUI ? new FastDisplay() :*/ new FileDisplay(false);

            UI.printInfo(UI.Module.BENCH, "Preparing benchmarking scene ...");
            // settings
            parameter("threads", threads);
            // spawn regular priority threads
            parameter("threads.lowPriority", false);
            parameter("resolutionX", 512);
            parameter("resolutionY", 512);
            parameter("aa.min", -3);
            parameter("aa.max", 0);
            parameter("depths.diffuse", 1);
            parameter("depths.reflection", 1);
            parameter("depths.refraction", 0);
            parameter("bucket.order", "hilbert");
            parameter("bucket.size", 32);
            options(SunflowAPI.DEFAULT_OPTIONS);
            // camera
            Point3  eye    = new Point3(30, 0, 10.967f);
            Point3  target = new Point3(0, 0, 5.4f);
            Vector3 up     = new Vector3(0, 0, 1);

            parameter("transform", Matrix4.lookAt(eye, target, up));
            parameter("fov", 45.0f);
            camera("camera", "pinhole");
            parameter("camera", "camera");
            options(SunflowAPI.DEFAULT_OPTIONS);
            // geometry
            createGeometry();
            // this first render is not timed, it caches the acceleration data
            // structures and tesselations so they won't be
            // included in the main timing
            UI.printInfo(UI.Module.BENCH, "Rendering warmup frame ...");
            render(SunflowAPI.DEFAULT_OPTIONS, display);
            // now disable all output - and run the benchmark
            UI.set(null);
            Timer t = new Timer();

            t.start();
            float phi    = 0;
            int   frames = 0;

            while (phi < 4 * Math.PI)
            {
                eye.x = 30 * (float)Math.Cos(phi);
                eye.y = 30 * (float)Math.Sin(phi);
                phi  += (float)(Math.PI / 30);
                frames++;
                // update camera
                parameter("transform", Matrix4.lookAt(eye, target, up));
                camera("camera", null);
                render(SunflowAPI.DEFAULT_OPTIONS, display);
            }
            t.end();
            UI.set(new ConsoleInterface());
            UI.printInfo(UI.Module.BENCH, "Benchmark results:");
            UI.printInfo(UI.Module.BENCH, "  * Average FPS:         {0,6:0.00", frames / t.seconds());
            UI.printInfo(UI.Module.BENCH, "  * Total time:          {0}", t);
        }
예제 #44
0
        public void Update(float dt)
        {
            Point3 coordinates = m_componentBlockEntity.Coordinates;

            if (m_updateSmeltingRecipe)
            {
                m_updateSmeltingRecipe = false;
                result[0] = m_matchedIngredients[7];
                result[1] = m_matchedIngredients[8];
                result[2] = m_matchedIngredients[9];
                bool flag = FindSmeltingRecipe(5f);
                if (result[0] != m_matchedIngredients[7] || result[1] != m_matchedIngredients[8] || result[2] != m_matchedIngredients[9])
                {
                    SmeltingProgress = 0f;
                    m_time           = 0;
                }
                m_smeltingRecipe2 = flag;
                if (flag != m_smeltingRecipe)
                {
                    m_smeltingRecipe = flag;
                    SmeltingProgress = 0f;
                    m_time           = 0;
                }
            }
            if (m_smeltingRecipe2 && Utils.SubsystemTime.PeriodicGameTimeEvent(0.2, 0.0))
            {
                int num = 1;
                int num2 = 0;
                var point = CellFace.FaceToPoint3(FourDirectionalBlock.GetDirection(Utils.Terrain.GetCellValue(coordinates.X, coordinates.Y, coordinates.Z)));
                int num3 = coordinates.X - point.X;
                int num4 = coordinates.Y - point.Y;
                int num5 = coordinates.Z - point.Z, v;
                for (int i = -1; i < 2; i++)
                {
                    for (int j = -1; j < 3; j++)
                    {
                        for (int k = -1; k < 2; k++)
                        {
                            int cellContents = Utils.Terrain.GetCellContents(num3 + i, num4 + j, num5 + k);
                            if (i * i + k * k > 0 && j >= 1 && cellContents != 73)
                            {
                                num = 0;
                                break;
                            }
                            if (i * i + k * k == 1 && j == 0 && cellContents == 0 && (v = Terrain.ReplaceLight(Utils.Terrain.GetCellValue(num3 + 2 * i, num4 + j, num5 + 2 * k), 0)) != (BlastBlowerBlock.Index | FurnaceNBlock.SetHeatLevel(Terrain.ExtractData(v), 1) << 14) && (num3 + i != coordinates.X || num5 + k != coordinates.Z))
                            {
                                num = 0;
                                break;
                            }
                            if (i * i + k * k == 1 && j == 0 && cellContents == 0)
                            {
                                num2 = 1;
                            }
                            if (i * i + k * k == 1 && j == 0 && cellContents != 0 && cellContents != 73 && (num3 + i != coordinates.X || num5 + k != coordinates.Z))
                            {
                                num = 0;
                                break;
                            }
                            if (i * i + k * k == 2 && j == 0 && cellContents != 73)
                            {
                                num = 0;
                                break;
                            }
                            if (j < 0 && cellContents != 73)
                            {
                                num = 0;
                                break;
                            }
                        }
                    }
                }
                if (num == 0 || num2 == 0)
                {
                    m_smeltingRecipe = false;
                }
                if (num == 1 && num2 >= 1 && !m_smeltingRecipe)
                {
                    m_smeltingRecipe = m_smeltingRecipe2;
                }
            }
            m_time++;
            if (!m_smeltingRecipe)
            {
                HeatLevel           = 0f;
                m_fireTimeRemaining = 0f;
                SmeltingProgress    = 0f;
            }
            if (m_smeltingRecipe && m_fireTimeRemaining <= 0f)
            {
                HeatLevel = 5f;
            }
            if (m_smeltingRecipe)
            {
                SmeltingProgress = MathUtils.Min(SmeltingProgress + 0.1f * dt, 1f);
                if (SmeltingProgress >= 1f)
                {
                    int[] array =
                    {
                        IronOreChunkBlock.Index,
                        ItemBlock.IdTable["IronOrePowder"],
                        CoalChunkBlock.Index,
                        ItemBlock.IdTable["CoalPowder"],
                        SandBlock.Index,
                        PigmentBlock.Index,
                        IronIngotBlock.Index
                    };
                    for (int l = 0; l < 7; l++)
                    {
                        if (m_matchedIngredients[l] > 0)
                        {
                            int b = array[l];
                            for (int m = 0; m < m_furnaceSize; m++)
                            {
                                if (m_slots[m].Count > 0 && GetSlotValue(m) == b)
                                {
                                    if (m_slots[m].Count >= m_matchedIngredients[l])
                                    {
                                        m_slots[m].Count       -= m_matchedIngredients[l];
                                        m_matchedIngredients[l] = 0;
                                    }
                                    else
                                    {
                                        m_matchedIngredients[l] -= m_slots[m].Count;
                                        m_slots[m].Count         = 0;
                                    }
                                    if (m_matchedIngredients[l] == 0)
                                    {
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    if (m_matchedIngredients[8] >= 1)
                    {
                        m_slots[ResultSlotIndex].Value  = ItemBlock.IdTable["SteelIngot"];
                        m_slots[ResultSlotIndex].Count += m_matchedIngredients[8];
                    }
                    if (m_matchedIngredients[7] >= 1)
                    {
                        m_slots[RemainsSlotIndex].Value  = ItemBlock.IdTable["ScrapIron"];
                        m_slots[RemainsSlotIndex].Count += m_matchedIngredients[7];
                    }
                    if (m_matchedIngredients[9] >= 1)
                    {
                        m_slots[ResultSlotIndex].Value  = IronIngotBlock.Index;
                        m_slots[ResultSlotIndex].Count += m_matchedIngredients[9];
                    }
                    m_smeltingRecipe       = false;
                    SmeltingProgress       = 0f;
                    m_updateSmeltingRecipe = true;
                }
            }
        }
 public void Update(float dt)
 {
     if (m_firePointsCopy.Count == 0)
     {
         m_firePointsCopy.Count += m_fireData.Count;
         m_fireData.Keys.CopyTo(m_firePointsCopy.Array, 0);
         m_copyIndex        = 0;
         m_lastScanDuration = (float)(m_subsystemTime.GameTime - m_lastScanTime);
         m_lastScanTime     = m_subsystemTime.GameTime;
         if (m_firePointsCopy.Count == 0)
         {
             m_fireSoundVolume = 0f;
         }
     }
     if (m_firePointsCopy.Count > 0)
     {
         float num  = MathUtils.Min(1f * dt * (float)m_firePointsCopy.Count + m_remainderToScan, 50f);
         int   num2 = (int)num;
         m_remainderToScan = num - (float)num2;
         int num3 = MathUtils.Min(m_copyIndex + num2, m_firePointsCopy.Count);
         while (m_copyIndex < num3)
         {
             if (m_fireData.TryGetValue(m_firePointsCopy.Array[m_copyIndex], out FireData value))
             {
                 int x    = value.Point.X;
                 int y    = value.Point.Y;
                 int z    = value.Point.Z;
                 int num4 = Terrain.ExtractData(base.SubsystemTerrain.Terrain.GetCellValue(x, y, z));
                 m_fireSoundIntensity += 1f / (m_subsystemAudio.CalculateListenerDistanceSquared(new Vector3(x, y, z)) + 0.01f);
                 if ((num4 & 1) != 0)
                 {
                     value.Time0 -= m_lastScanDuration;
                     if (value.Time0 <= 0f)
                     {
                         QueueBurnAway(x, y, z + 1, value.FireExpandability * 0.85f);
                     }
                     foreach (KeyValuePair <Point3, float> expansionProbability in m_expansionProbabilities)
                     {
                         if (m_random.Float(0f, 1f) < expansionProbability.Value * m_lastScanDuration * value.FireExpandability)
                         {
                             m_toExpand[new Point3(x + expansionProbability.Key.X, y + expansionProbability.Key.Y, z + 1 + expansionProbability.Key.Z)] = value.FireExpandability * 0.85f;
                         }
                     }
                 }
                 if ((num4 & 2) != 0)
                 {
                     value.Time1 -= m_lastScanDuration;
                     if (value.Time1 <= 0f)
                     {
                         QueueBurnAway(x + 1, y, z, value.FireExpandability * 0.85f);
                     }
                     foreach (KeyValuePair <Point3, float> expansionProbability2 in m_expansionProbabilities)
                     {
                         if (m_random.Float(0f, 1f) < expansionProbability2.Value * m_lastScanDuration * value.FireExpandability)
                         {
                             m_toExpand[new Point3(x + 1 + expansionProbability2.Key.X, y + expansionProbability2.Key.Y, z + expansionProbability2.Key.Z)] = value.FireExpandability * 0.85f;
                         }
                     }
                 }
                 if ((num4 & 4) != 0)
                 {
                     value.Time2 -= m_lastScanDuration;
                     if (value.Time2 <= 0f)
                     {
                         QueueBurnAway(x, y, z - 1, value.FireExpandability * 0.85f);
                     }
                     foreach (KeyValuePair <Point3, float> expansionProbability3 in m_expansionProbabilities)
                     {
                         if (m_random.Float(0f, 1f) < expansionProbability3.Value * m_lastScanDuration * value.FireExpandability)
                         {
                             m_toExpand[new Point3(x + expansionProbability3.Key.X, y + expansionProbability3.Key.Y, z - 1 + expansionProbability3.Key.Z)] = value.FireExpandability * 0.85f;
                         }
                     }
                 }
                 if ((num4 & 8) != 0)
                 {
                     value.Time3 -= m_lastScanDuration;
                     if (value.Time3 <= 0f)
                     {
                         QueueBurnAway(x - 1, y, z, value.FireExpandability * 0.85f);
                     }
                     foreach (KeyValuePair <Point3, float> expansionProbability4 in m_expansionProbabilities)
                     {
                         if (m_random.Float(0f, 1f) < expansionProbability4.Value * m_lastScanDuration * value.FireExpandability)
                         {
                             m_toExpand[new Point3(x - 1 + expansionProbability4.Key.X, y + expansionProbability4.Key.Y, z + expansionProbability4.Key.Z)] = value.FireExpandability * 0.85f;
                         }
                     }
                 }
                 if (num4 == 0)
                 {
                     value.Time5 -= m_lastScanDuration;
                     if (value.Time5 <= 0f)
                     {
                         QueueBurnAway(x, y - 1, z, value.FireExpandability * 0.85f);
                     }
                 }
             }
             m_copyIndex++;
         }
         if (m_copyIndex >= m_firePointsCopy.Count)
         {
             m_fireSoundVolume = 0.75f * m_fireSoundIntensity;
             m_firePointsCopy.Clear();
             m_fireSoundIntensity = 0f;
         }
     }
     if (m_subsystemTime.PeriodicGameTimeEvent(5.0, 0.0))
     {
         int num5 = 0;
         int num6 = 0;
         foreach (KeyValuePair <Point3, float> item in m_toBurnAway)
         {
             Point3 key    = item.Key;
             float  value2 = item.Value;
             base.SubsystemTerrain.ChangeCell(key.X, key.Y, key.Z, Terrain.ReplaceContents(0, 0));
             if (value2 > 0.25f)
             {
                 for (int i = 0; i < 5; i++)
                 {
                     Point3 point = CellFace.FaceToPoint3(i);
                     SetCellOnFire(key.X + point.X, key.Y + point.Y, key.Z + point.Z, value2);
                 }
             }
             float num7 = m_subsystemViews.CalculateDistanceFromNearestView(new Vector3(key));
             if (num5 < 15 && num7 < 24f)
             {
                 m_subsystemParticles.AddParticleSystem(new BurntDebrisParticleSystem(base.SubsystemTerrain, key.X, key.Y, key.Z));
                 num5++;
             }
             if (num6 < 4 && num7 < 16f)
             {
                 m_subsystemAudio.PlayRandomSound("Audio/Sizzles", 1f, m_random.Float(-0.25f, 0.25f), new Vector3(key.X, key.Y, key.Z), 3f, autoDelay: true);
                 num6++;
             }
         }
         foreach (KeyValuePair <Point3, float> item2 in m_toExpand)
         {
             SetCellOnFire(item2.Key.X, item2.Key.Y, item2.Key.Z, item2.Value);
         }
         m_toBurnAway.Clear();
         m_toExpand.Clear();
     }
     m_subsystemAmbientSounds.FireSoundVolume = MathUtils.Max(m_subsystemAmbientSounds.FireSoundVolume, m_fireSoundVolume);
 }
예제 #46
0
        public void Beam()
        {
            var    k3d    = new Toolkit();
            var    logger = new MessageLogger();
            double length = 4.0;
            var    p0     = new Point3(0, 0, 0);
            var    p1     = new Point3(length, 0, 0);
            var    axis   = new Line3(p0, p1);

            var resourcePath = @"";

            // get a material from the material table in the folder 'Resources'
            var materialPath = Path.Combine(resourcePath, "Materials/MaterialProperties.csv");
            var inMaterials  = k3d.Material.ReadMaterialTable(materialPath);
            var material     = inMaterials.Find(x => x.name == "Steel");

            // get a cross section from the cross section table in the folder 'Resources'
            var         crosecPath     = Path.Combine(resourcePath, "CrossSections/CrossSectionValues.bin");
            CroSecTable inCroSecs      = k3d.CroSec.ReadCrossSectionTable(crosecPath, out var info);
            var         crosec_family  = inCroSecs.crosecs.FindAll(x => x.family == "FRQ");
            var         crosec_initial = crosec_family.Find(x => x.name == "FRQ45/5");

            // attach the material to the cross section
            crosec_initial.setMaterial(material);

            // create the column
            var beams = k3d.Part.LineToBeam(new List <Line3> {
                axis
            }, new List <string>()
            {
                "B1"
            }, new List <CroSec>()
            {
                crosec_initial
            }, logger,
                                            out var out_points);

            // create supports
            var supports = new List <Support>
            {
                k3d.Support.Support(p0, new List <bool>()
                {
                    true, true, true, true, false, false
                }),
                k3d.Support.Support(p1, new List <bool>()
                {
                    false, true, true, false, false, false
                })
            };

            // create a Point-load
            var loads = new List <Load>
            {
                k3d.Load.PointLoad(p1, new Vector3(0, 0, -100))
            };

            // create the model
            var model = k3d.Model.AssembleModel(beams, supports, loads,
                                                out info, out var mass, out var cog, out var message, out var warning);

            // calculate the natural vibrations
            int    from_shape_ind = 1;
            int    shapes_num     = 1;
            int    max_iter       = 100;
            double eps            = 1e-8;
            var    disp_dummy     = new List <double>();
            var    scaling        = EigenShapesScalingType.matrix;

            model = k3d.Algorithms.NaturalVibes(model, from_shape_ind, shapes_num, max_iter, eps, disp_dummy, scaling,
                                                out List <double> nat_frequencies, out List <double> modal_masses, out List <Vector3> participation_facs,
                                                out List <double> participation_facs_disp, out model);

            Assert.AreEqual(nat_frequencies[0], 8.9828263788644716, 1e-8);
        }
 /// <summary>
 /// Creates a vector from the starting point to the end point.
 /// </summary>
 /// <param name="startPoint"></param>
 /// <param name="endPoint"></param>
 /// <returns></returns>
 public static Point3 GetVector(Point3 startPoint, Point3 endPoint)
 {
     return(endPoint - startPoint);
 }
예제 #48
0
        public void getSamples(ShadingState state)
        {
            if (getNumSamples() <= 0)
            {
                return;
            }
            Vector3 wc = Point3.sub(center, state.getPoint(), new Vector3());
            float   l2 = wc.LengthSquared();

            if (l2 <= r2)
            {
                return; // inside the sphere?
            }
            // top of the sphere as viewed from the current shading point
            float topX = wc.x + state.getNormal().x *radius;
            float topY = wc.y + state.getNormal().y *radius;
            float topZ = wc.z + state.getNormal().z *radius;

            if (state.getNormal().dot(topX, topY, topZ) <= 0)
            {
                return; // top of the sphere is below the horizon
            }
            float            cosThetaMax = (float)Math.Sqrt(Math.Max(0, 1 - r2 / Vector3.dot(wc, wc)));
            OrthoNormalBasis basis       = OrthoNormalBasis.makeFromW(wc);
            int   samples = state.getDiffuseDepth() > 0 ? 1 : getNumSamples();
            float scale   = (float)(2 * Math.PI * (1 - cosThetaMax));
            Color c       = Color.mul(scale / samples, radiance);

            for (int i = 0; i < samples; i++)
            {
                // random offset on unit square
                double randX = state.getRandom(i, 0, samples);
                double randY = state.getRandom(i, 1, samples);

                // cone sampling
                double  cosTheta = (1 - randX) * cosThetaMax + randX;
                double  sinTheta = Math.Sqrt(1 - cosTheta * cosTheta);
                double  phi      = randY * 2 * Math.PI;
                Vector3 dir      = new Vector3((float)(Math.Cos(phi) * sinTheta), (float)(Math.Sin(phi) * sinTheta), (float)cosTheta);
                basis.transform(dir);

                // check that the direction of the sample is the same as the
                // normal
                float cosNx = Vector3.dot(dir, state.getNormal());
                if (cosNx <= 0)
                {
                    continue;
                }

                float    ocx = state.getPoint().x - center.x;
                float    ocy = state.getPoint().y - center.y;
                float    ocz = state.getPoint().z - center.z;
                float    qa  = Vector3.dot(dir, dir);
                float    qb  = 2 * ((dir.x * ocx) + (dir.y * ocy) + (dir.z * ocz));
                float    qc  = ((ocx * ocx) + (ocy * ocy) + (ocz * ocz)) - r2;
                double[] t   = Solvers.solveQuadric(qa, qb, qc);
                if (t == null)
                {
                    continue;
                }
                LightSample dest = new LightSample();
                // compute shadow ray to the sampled point
                dest.setShadowRay(new Ray(state.getPoint(), dir));
                // FIXME: arbitrary bias, should handle as in other places
                dest.getShadowRay().setMax((float)t[0] - 1e-3f);
                // prepare sample
                dest.setRadiance(c, c);
                dest.traceShadow(state);
                state.addSample(dest);
            }
        }
예제 #49
0
 /// <summary>
 /// Adds a block to be drawn
 /// </summary>
 /// <remarks>
 /// Threadsafe
 /// </remarks>
 public void AddBlocks(Point3 chunkPos, List <GraphicalBlock> toAdd)
 {
     Meshes
     .Aggregate((left, right) => left.BlockCount < right.BlockCount ? left : right)
     .AddBlocks(chunkPos, toAdd);
 }
예제 #50
0
 public bool Equals(Point3 <T> other)
 {
     return(this.a.Equals(other.a) && this.b.Equals(other.b) && this.c.Equals(other.c));
 }
예제 #51
0
        public void TwoPointLoads()
        {
            var    k3d    = new Toolkit();
            var    logger = new MessageLogger();
            double length = 4.0;
            var    p0     = new Point3(0, 0, 0);
            var    p1     = new Point3(length, 0, 0);
            var    axis   = new Line3(p0, p1);

            var resourcePath = @"";

            // get a material from the material table in the folder 'Resources'
            var materialPath = Path.Combine(resourcePath, "Materials/MaterialProperties.csv");
            var inMaterials  = k3d.Material.ReadMaterialTable(materialPath);
            var material     = inMaterials.Find(x => x.name == "Steel");

            // get a cross section from the cross section table in the folder 'Resources'
            var         crosecPath     = Path.Combine(resourcePath, "CrossSections/CrossSectionValues.bin");
            CroSecTable inCroSecs      = k3d.CroSec.ReadCrossSectionTable(crosecPath, out var info);
            var         crosec_family  = inCroSecs.crosecs.FindAll(x => x.family == "FRQ");
            var         crosec_initial = crosec_family.Find(x => x.name == "FRQ45/5");

            // attach the material to the cross section
            crosec_initial.setMaterial(material);

            // create the column
            var beams = k3d.Part.LineToBeam(new List <Line3> {
                axis
            }, new List <string>()
            {
                "B1"
            }, new List <CroSec>()
            {
                crosec_initial
            }, logger,
                                            out var out_points);

            // create supports
            var supports = new List <Support>
            {
                k3d.Support.Support(p0, new List <bool>()
                {
                    true, true, true, true, true, true
                }),
            };

            // create a Point-load
            var loads = new List <Load>
            {
                k3d.Load.PointLoad(p1, new Vector3(0, 100, 0), new Vector3(), "LC0"),
                k3d.Load.PointLoad(p1, new Vector3(0, 0, 50), new Vector3(), "LC1")
            };

            // create the model
            var model = k3d.Model.AssembleModel(beams, supports, loads,
                                                out info, out var mass, out var cog, out var message, out var is_warning);

            // calculate the displacements
            ThIAnalyze.solve(model, out var outMaxDisp, out var outG, out var outComp, out var warning, out model);
            Assert.AreEqual(54.338219302231252, outMaxDisp[0], 1e-5);
            Assert.AreEqual(27.169109651115626, outMaxDisp[1], 1e-5);
        }
예제 #52
0
 public static bool IsOutside(Point3 p, int size)
 {
     return(p.X < 0 || p.Y < 0 || p.Z < 0 ||
            p.X >= size || p.Y >= size || p.Z >= size);
 }
예제 #53
0
        /// <summary>
        /// Liest das erste TIN aus einer LandXML Datei
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="errors"></param>
        /// <returns></returns>
        public static Result ReadTIN(bool is3d, string fileName, double minDist, string logFilePath, string verbosityLevel)
        {
            var result = new Result();

            //Serilog.Log.Logger = new LoggerConfiguration()
            //                   .MinimumLevel.Debug()
            //                   .WriteTo.File(logFilePath)
            //                   .CreateLogger();
            var logger = LogManager.GetCurrentClassLogger();

            try
            {
                using (var reader = XmlReader.Create(fileName))
                {
                    XElement el;
                    double?  scale  = null;
                    var      pntIds = new Dictionary <string, int>();

                    //TIN-Builder erzeugen
                    var tinB = Tin.CreateBuilder(true);
                    //PNR "künstlich erzeugen" & für TIN nutzen
                    int pnr = 0;

                    bool insideTin = false;
                    reader.MoveToContent();
                    // Parse the file and display each of the nodes.
                    while (!reader.EOF)
                    {
                        if (reader.NodeType == XmlNodeType.Element)
                        {
                            switch (reader.LocalName)
                            {
                            case "Metric":
                            case "Imperial":
                                el = XElement.ReadFrom(reader) as XElement;
                                if (el != null)
                                {
                                    var att = el.Attribute("linearUnit");
                                    if (att != null && ToMeter.TryGetValue(att.Value.ToLower(), out double tscale))
                                    {
                                        scale = tscale;
                                    }
                                }
                                break;

                            case "Definition":
                                if (reader.MoveToFirstAttribute() &&
                                    reader.LocalName == "surfType" &&
                                    reader.Value.ToUpper() == "TIN")
                                {
                                    insideTin = true;
                                }
                                break;

                            case "P":
                                el = XElement.ReadFrom(reader) as XElement;
                                if (el != null)
                                {
                                    var att = el.Attribute("id");
                                    if (att != null && Point3.Create(
                                            el.Value.Replace(',', '.').Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries), out var pt))
                                    {
                                        Point3 point = Point3.Create(pt.Y, pt.X, pt.Z);
                                        tinB.AddPoint(pnr, point);
                                        pntIds.Add(att.Value, pnr++);
                                    }
                                }
                                break;

                            case "F":
                                el = XElement.ReadFrom(reader) as XElement;
                                if (el != null)
                                {
                                    string[] pts = el.Value.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                    if (pts.Length == 3 &&
                                        pntIds.TryGetValue(pts[0], out int p1) &&
                                        pntIds.TryGetValue(pts[1], out int p2) &&
                                        pntIds.TryGetValue(pts[2], out int p3))
                                    {
                                        //mesh.AddFace(new[] { p1, p2, p3 });
                                        tinB.AddTriangle(p1, p2, p3);
                                    }
                                }
                                break;

                            default:
                                reader.Read();
                                break;
                            }
                        }
                        else if (insideTin && reader.NodeType == XmlNodeType.EndElement && reader.Name == "Definition")
                        {
                            /*
                             * if(!mesh.Points.Any() || !mesh.FaceEdges.Any())
                             * {
                             *  result.Error = string.Format(Properties.Resources.errNoTINData, Path.GetFileName(fileName));
                             *  logger.Error("No TIN-data found");
                             *  return result;
                             * }
                             */
                            logger.Info("Reading LandXML-Data successful");
                            logger.Info(result.Tin.Points.Count() + " points; " + result.Tin.NumTriangles + " triangels processed");

                            //TIN aus TIN-Builder erzeugen
                            Tin tin = tinB.ToTin(out var pointIndex2NumberMap, out var triangleIndex2NumberMap);
                            //Result beschreiben
                            result.Tin = tin;

                            //result.Mesh = mesh;
                            return(result);
                        }
                        else
                        {
                            reader.Read();
                        }
                    }
                }
            }
            catch
            {
                result.Error = string.Format(Properties.Resources.errFileNotReadable, Path.GetFileName(fileName));
                logger.Error("File not readable");
                return(result);
            }
            result.Error = string.Format(Properties.Resources.errNoTIN, Path.GetFileName(fileName));
            logger.Error("No TIN-data found");
            return(result);
        } //End ReadTIN
예제 #54
0
        public bool IsNear(Point3 p)
        {
            Point3d p3d = p.Convert();

            foreach (Point3d to_point in to_points_)
            {
                if (to_point.DistanceTo(p3d) < limit_dist_)
                {
                    return(true);
                }
            }

            foreach (Curve to_curve in to_curves_)
            {
#if UnitTest
                throw new NotImplementedException();
#else
                double t;
                if (to_curve.ClosestPoint(p3d, out t, limit_dist_))
                {
                    return(true);
                }
#endif
            }

            foreach (var to_line in to_lines_)
            {
                if (to_line.DistanceTo(p3d, true) <= limit_dist_)
                {
                    return(true);
                }
            }

            foreach (Plane to_plane in to_planes_)
            {
                if (Math.Abs(to_plane.DistanceTo(p3d)) <= limit_dist_)
                {
                    return(true);
                }
            }

            foreach (Brep to_brep in to_breps_)
            {
#if UnitTest
                throw new NotImplementedException();
#else
                Point3d        closest_point;
                ComponentIndex ci;
                double         s, t;
                Vector3d       normal;
                if (to_brep.ClosestPoint(p3d, out closest_point, out ci, out s, out t,
                                         limit_dist_, out normal))
                {
                    return(true);
                }
#endif
            }

            foreach (Mesh to_mesh in to_meshes_)
            {
#if UnitTest
                throw new NotImplementedException();
#else
                if (to_mesh.ClosestPoint(p3d).DistanceTo(p3d) <= limit_dist_)
                {
                    return(true);
                }
#endif
            }
            return(false);
        }
 /// <summary>
 /// 棱锥
 /// </summary>
 /// <param name="Position"></param>
 /// <param name="Radius"></param>
 /// <param name="Hollow"></param>
 /// <param name="XYZType"></param>
 /// <param name="typeBool"></param>
 /// <returns></returns>
 public IEnumerable <Point3> Pyramid(Point3 Position, int Radius, bool Hollow = false, CreatorMain.CreatorType?XYZType = null, bool typeBool = false)
 {
     for (int x = -Radius; x <= Radius; x++)
     {
         for (int y = -Radius; y <= Radius; y++)
         {
             for (int z = -Radius; z <= Radius; z++)
             {
                 if (XYZType != null)
                 {
                     if (XYZType == CreatorMain.CreatorType.X)
                     {
                         if (typeBool)
                         {
                             if (Position.X + x < Position.X)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.X + x > Position.X)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZType == CreatorMain.CreatorType.Y)
                     {
                         if (typeBool)
                         {
                             if (Position.Y + y < Position.Y)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Y + y > Position.Y)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZType == CreatorMain.CreatorType.Z)
                     {
                         if (typeBool)
                         {
                             if (Position.Z + z < Position.Z)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Z + z > Position.Z)
                             {
                                 continue;
                             }
                         }
                     }
                 }
                 if (!(Math.Abs(x) + Math.Abs(y) + Math.Abs(z) > Radius))
                 {
                     if (!(Hollow && Math.Abs(x) + Math.Abs(y) + Math.Abs(z) < Radius))
                     {
                         yield return(new Point3(Position.X + x, Position.Y + y, Position.Z + z));
                     }
                 }
             }
         }
     }
 }
예제 #56
0
 public TableCell(Point3 key, List <LogSection> values)
 {
     this.key    = key;
     this.values = values;
 }
 /// <summary>
 /// 棱柱
 /// </summary>
 /// <param name="Position"></param>
 /// <param name="Radius"></param>
 /// <param name="Height"></param>
 /// <param name="Hollow"></param>
 /// <param name="creatorType"></param>
 /// <param name="YType"></param>
 /// <param name="XYZType"></param>
 /// <param name="typeBool"></param>
 /// <returns></returns>
 public IEnumerable <Point3> PrismColumn(Point3 Position, int Radius, int Height, CreatorMain.CreatorType creatorType = CreatorMain.CreatorType.Y, bool YType = true, bool Hollow = false, CreatorMain.CreatorType?XYZType = null, bool typeBool = false)
 {
     for (int y = 0; y < Height; y++)
     {
         for (int x = -Radius; x <= Radius; x++)
         {
             for (int z = -Radius; z <= Radius; z++)
             {
                 if (XYZType != null)
                 {
                     if (XYZType == CreatorMain.CreatorType.X)
                     {
                         if (typeBool)
                         {
                             if (Position.X + x < Position.X)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.X + x > Position.X)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZType == CreatorMain.CreatorType.Y)
                     {
                         if (typeBool)
                         {
                             if (Position.Y + y < Position.Y)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Y + y > Position.Y)
                             {
                                 continue;
                             }
                         }
                     }
                     if (XYZType == CreatorMain.CreatorType.Z)
                     {
                         if (typeBool)
                         {
                             if (Position.Z + z < Position.Z)
                             {
                                 continue;
                             }
                         }
                         else
                         {
                             if (Position.Z + z > Position.Z)
                             {
                                 continue;
                             }
                         }
                     }
                 }
                 if (!(Math.Abs(x) + Math.Abs(z) > Radius))
                 {
                     if (!(Hollow && Math.Abs(x) + Math.Abs(z) < Radius))
                     {
                         int Y;
                         if (YType)
                         {
                             Y = y;
                         }
                         else
                         {
                             Y = -y;
                         }
                         if (creatorType == CreatorMain.CreatorType.X)
                         {
                             yield return(new Point3(Position.X + Y, Position.Y + x, Position.Z + z));
                         }
                         else if (creatorType == CreatorMain.CreatorType.Y)
                         {
                             yield return(new Point3(Position.X + x, Position.Y + Y, Position.Z + z));
                         }
                         else
                         {
                             yield return(new Point3(Position.X + x, Position.Y + z, Position.Z + Y));
                         }
                     }
                 }
             }
         }
     }
 }
예제 #58
0
        public void getPhoton(double randX1, double randY1, double randX2, double randY2, Point3 p, Vector3 dir, Color power)
        {
            float z   = (float)(1 - 2 * randX2);
            float r   = (float)Math.Sqrt(Math.Max(0, 1 - z * z));
            float phi = (float)(2 * Math.PI * randY2);
            float x   = r * (float)Math.Cos(phi);
            float y   = r * (float)Math.Sin(phi);

            p.x = center.x + x * radius;
            p.y = center.y + y * radius;
            p.z = center.z + z * radius;
            OrthoNormalBasis basis = OrthoNormalBasis.makeFromW(new Vector3(x, y, z));

            phi = (float)(2 * Math.PI * randX1);
            float cosPhi   = (float)Math.Cos(phi);
            float sinPhi   = (float)Math.Sin(phi);
            float sinTheta = (float)Math.Sqrt(randY1);
            float cosTheta = (float)Math.Sqrt(1 - randY1);

            dir.x = cosPhi * sinTheta;
            dir.y = sinPhi * sinTheta;
            dir.z = cosTheta;
            basis.transform(dir);
            power.set(radiance);
            power.mul((float)(Math.PI * Math.PI * 4 * r2));
        }
예제 #59
0
 public static extern Point3 <bool> AddPoint3B(Point3 <bool> lhs, Point3 <bool> rhs);
예제 #60
0
        public void Update(float dt)
        {
            Point3 coordinates = m_componentBlockEntity.Coordinates;

            if (HeatLevel > 0f)
            {
                m_fireTimeRemaining = MathUtils.Max(0f, m_fireTimeRemaining - dt);
                if (m_fireTimeRemaining == 0f)
                {
                    HeatLevel = 0f;
                }
            }
            if (m_updateSmeltingRecipe)
            {
                m_updateSmeltingRecipe = false;
                string text = m_smeltingRecipe2 = FindSmeltingRecipe(0f);
                if (text != m_smeltingRecipe)
                {
                    m_smeltingRecipe  = text;
                    m_smeltingRecipe2 = text;
                    SmeltingProgress  = 0f;
                    //m_music = 0;
                }
            }
            if (m_smeltingRecipe2 != null)
            {
                int num = 0;
                for (int i = -1; i < 2; i++)
                {
                    for (int j = -1; j < 2; j++)
                    {
                        for (int k = -1; k < 2; k++)
                        {
                            int cellValue = Utils.Terrain.GetCellValue(coordinates.X + i, coordinates.Y + j, coordinates.Z + k);
                            if (i * i + j * j + k * k <= 1 && (Terrain.ExtractContents(cellValue) == FireBoxBlock.Index) && FurnaceNBlock.GetHeatLevel(cellValue) != 0)
                            {
                                num = 1;
                                break;
                            }
                        }
                    }
                }
                if (num == 0)
                {
                    m_smeltingRecipe = null;
                }
                if (num == 1 && m_smeltingRecipe == null)
                {
                    m_smeltingRecipe = m_smeltingRecipe2;
                }
            }
            if (m_smeltingRecipe == null)
            {
                HeatLevel           = 0f;
                m_fireTimeRemaining = 0f;
                //m_music = -1;
            }
            else
            {
                m_fireTimeRemaining = 100f;
            }
            if (m_fireTimeRemaining <= 0f)
            {
                m_smeltingRecipe = null;
                SmeltingProgress = 0f;
                //m_music = -1;
            }
            if (m_smeltingRecipe != null)
            {
                SmeltingProgress = MathUtils.Min(SmeltingProgress + 0.1f * dt, 1f);
                if (SmeltingProgress >= 1f)
                {
                    for (int i = 0; i < 3; i++)
                    {
                        if (m_slots[i].Count > 0)
                        {
                            m_slots[i].Count--;
                        }
                    }
                    int value = ItemBlock.IdTable[m_smeltingRecipe];
                    m_slots[ResultSlotIndex].Value = value;
                    m_slots[ResultSlotIndex].Count++;
                    m_smeltingRecipe       = null;
                    SmeltingProgress       = 0f;
                    m_updateSmeltingRecipe = true;
                }
            }
        }